target
stringlengths
5
300
feat_repo_name
stringlengths
6
76
text
stringlengths
26
1.05M
server/ExpressUniversalApplicationServer.js
hihiapolla/catela
import async from 'async' import cookie from 'cookie' import bodyParser from 'body-parser' import cookieParser from 'cookie-parser' import createLocation from 'history/lib/createLocation' import express from 'express' import InternationalizationHandler from 'i18n/InternationalizationHandler' import UniversalPageHandler from 'UniversalPageHandler' import path from 'path' import preconditions from 'preconditions' import querystring from 'querystring' import React from 'react' import { renderToStaticMarkup } from 'react-dom/server' import { Provider } from 'react-redux' import { Route, RoutingContext, match } from 'react-router' import { createStore, combineReducers, applyMiddleware } from 'redux' import * as reducers from 'reducers' import thunk from 'redux-thunk' import SimpleHtmlRenderer from 'render/SimpleHtmlRenderer' import { serverFetchReducer } from 'fetch/core' import resolve from 'es6-template-strings/resolve-to-string' import forceDomain from 'forcedomain' import url from 'url' let logger = global.Logger.getLogger('ExpressUniversalApplicationServer') // Currently supported locale is /{lang}-{country}/* let LOCALE_REGEX = /^\/([a-z]{2})-([a-z]{2})(.*)$/ let LOCALE_DEFAULT = 'id-id' let QS_REGEX = /^\?(.*)$/ const createStoreWithMiddleware = applyMiddleware( thunk )(createStore) class ExpressUniversalApplicationServer { constructor (options) { let pc = preconditions.instance(options) pc.shouldBeDefined('port', 'port must be defined.') pc.shouldBeDefined('rootApplicationPath', 'rootApplicationPath must be defined.') pc.shouldBeDefined('rootDeploymentApplicationPath', 'rootDeploymentApplicationPath must be defined.') this._options = options this._app = express() this._routes = this.getRoutes() this._reducers = this.getReducers() this._initialize() } _initialize () { this._setupForceDomain() this._setupAssetsServing() this._setupCookieParser() this._setupBodyParser() this._setupHtmlRenderer() this._setupInternationalizedRoutes() this._setupI18nHandler() } _setupAssetsServing () { console.log(path.join(this._options.rootDeploymentApplicationPath, 'build', this._options.environment, 'client')) // TODO : this should be configurable, but we hard code it for now logger.info('Using ' + path.join(this._options.rootDeploymentApplicationPath, 'build', this._options.environment, 'client') + ', with /assets as assets serving routes') this._app.use('/assets', express.static(path.join(this._options.rootDeploymentApplicationPath, 'build', this._options.environment, 'client'))) logger.info('Using ' + path.join(this._options.rootDeploymentApplicationPath, 'build', this._options.environment, 'server', 'debugging') + ', with /__dev/assets/server/debugging as server-debugging serving routes') this._app.use('/__dev/assets/server/debugging', express.static(path.join(this._options.rootDeploymentApplicationPath, 'build', this._options.environment, 'server', 'debugging'))) // TODO : this should be configurable, but we hard code it for now logger.info('Using ' + path.join(this._options.rootDeploymentApplicationPath, 'assets') + ', with /assets/static as static non-compileable assets serving routes') this._app.use('/assets/static', express.static(path.join(this._options.rootDeploymentApplicationPath, 'assets'))) } _setupCookieParser () { this._app.use(cookieParser()) } _setupBodyParser () { this._app.use(bodyParser.urlencoded({ extended: true })) this._app.use(bodyParser.json()) } _setupHtmlRenderer () { let htmlRendererOptions = { path: path.join(this._options.rootDeploymentApplicationPath, 'html'), cache: !(this._options.environment === 'development') } this._renderer = new SimpleHtmlRenderer(htmlRendererOptions) } _setupInternationalizedRoutes () { let finalRoutes = null let originalRoutes = this.getRoutes() let generatedRoutes = [] this._options.locales.forEach((locale) => { let internationalRoute = ( <Route key={locale} path={locale} component={InternationalizationHandler}> {originalRoutes} </Route> ) generatedRoutes.push(internationalRoute) }) generatedRoutes.push(originalRoutes) finalRoutes = ( <Route path='/' component={UniversalPageHandler}> { generatedRoutes.map((route) => { return route }) } </Route> ) this._routes = finalRoutes } _setupI18nHandler () { this._app.use((req, res, next) => { let match = LOCALE_REGEX.exec(req.url) let url = null if (match != null) { let lang = match[1] let country = match[2] url = match[3] req.locale = lang + '-' + country } else { req.locale = LOCALE_DEFAULT } if (this._options.locales.indexOf(req.locale) >= 0) { next() } else { if (this._options.locales.length === 0) { next() } else { if (url == null || typeof url === 'undefined' || url.length === 0) { res.redirect('/') } else { res.redirect(url) } } } }) } _isIP (host) { let ipRegex = /^(?!0)(?!.*\.$)((1?\d?\d|25[0-5]|2[0-4]\d)(\.|$)){4}$/ return ipRegex.test(host) } _setupForceDomain () { let protocol = 'http' if (this._options.forceHttps === true) { protocol = 'https' } let hostName = this._stripProtocol(this._options.applicationHost) if (!this._isIP(hostName)) { let parsedApplicationHost = url.parse(this._options.applicationHost) if (parsedApplicationHost.port == null) { this._app.use(forceDomain({ hostname: parsedApplicationHost.host, protocol: protocol })) } } } _stripProtocol (url) { if (url != null && typeof url !== 'undefined') { let result = url.replace(/.*?:\/\//g, '') return result } return null } _handleError500 (message, err, res) { logger.error(message, err) if (this._options.environment === 'production') { res.redirect(this.getErrorHandler()) } else { let error = '<br />' if (this._options.environment === 'development') { if (err != null && typeof err !== 'undefined') { error += err.stack } } error = error.replace('\n', '<br />') this._renderer.render('500.html', (err, rendered) => { if (err) { logger.error('[ERROR_RENDER_FATAL] An unknown error occurred when trying to render error 500.', err) return res.status(500).end('An unknown error occurred when trying to render error 500\n' + err.stack) } else { return res.status(500).end(resolve(rendered, { ERROR: error })) } }) } } _handleNotFound404 (res) { this._renderer.render('404.html', (err, rendered) => { if (err) { logger.error('[ERROR_RENDER_FATAL] An unknown error occurred when trying to render error 404.', err) return res.status(500).end('An unknown error occurred when trying to render error 404\n' + err.stack) } else { return res.status(404).end(resolve(rendered, {})) } }) } _runFilterPreFetchStage (filterQueue, renderProps, renderedServerComponents, req, res, context) { if (filterQueue.length > 0) { let filterFnQueue = [] filterQueue.reverse().forEach((filterFn) => { filterFnQueue.push((callback) => { let filterCallContext = { get: function () { return context }, next: function (booleanResult) { if (typeof booleanResult === 'undefined' || booleanResult == null) { booleanResult = true } callback(null, booleanResult) }, redirect: function (redirect) { callback({ type: 'REDIRECTION', redirect: redirect }, false) }, notFound: function () { callback({ type: 'NOT_FOUND' }, false) }, abortWithError: function () { callback({ type: 'SERVER_ERROR' }, false) } } filterFn(filterCallContext) }) }) async.series(filterFnQueue, (err, results) => { if (err) { if (err.type === 'REDIRECTION') { return res.redirect(err.redirect) } else if (err.type === 'NOT_FOUND') { this._renderer.render('404.html', (err, rendered) => { if (err) { logger.error('[ERROR_RENDER_FATAL] An unknown error occurred when trying to render error 404.', err) return res.status(500).end('An unknown error occurred when trying to render error 404\n' + err.stack) } else { return res.status(404).end(resolve(rendered, {})) } }) } else if (err.type === 'SERVER_ERROR') { this._renderer.render('500.html', (err, rendered) => { if (err) { logger.error('[ERROR_RENDER_FATAL] An unknown error occurred when trying to render error 500.', err) return res.status(500).end('An unknown error occurred when trying to render error 500\n' + err.stack) } else { return res.status(500).end(resolve(rendered, {})) } }) } else { this._renderer.render('500.html', (err, rendered) => { if (err) { logger.error('[ERROR_RENDER_FATAL] An unknown error occurred when trying to render error 500.', err) return res.status(500).end('An unknown error occurred when trying to render error 500\n' + err.stack) } else { return res.status(500).end(resolve(rendered, {})) } }) } } else { this._runFetchStage( renderProps, renderedServerComponents, req, res, context) } }) } else { this._runFetchStage( renderProps, renderedServerComponents, req, res, context) } } _runFetchStage (renderProps, renderedServerComponents, req, res, context) { let fetchDataQueue = [] let dataContextObject = {} renderedServerComponents.forEach((rsc) => { if (rsc.__fetchData != null && typeof rsc.__fetchData !== 'undefined') { let fnFetchCall = (callback) => { setTimeout(() => { rsc.__fetchData(dataContextObject, context, callback) }, 1) } fetchDataQueue.push(fnFetchCall) } }) async.series(fetchDataQueue, (err, results) => { if (err) { return this._handleError500('[FETCH_DATA_ERROR] An unknown error occurred when trying to fetch data.', err, res) } else { let fetchedDataContext = {} results.forEach((result) => { fetchedDataContext = { ...fetchedDataContext, ...result } }) let allReducers = { ...reducers, view: serverFetchReducer } const store = createStoreWithMiddleware(combineReducers(allReducers)) store.dispatch({ type: '__SET_VIEW_STATE__', data: fetchedDataContext }) const InitialComponent = ( <Provider store={store}> <RoutingContext {...renderProps} /> </Provider> ) let postFetchFilterQueue = [] renderedServerComponents.forEach((rsc) => { if (rsc.__postFetchFilter != null && typeof rsc.__postFetchFilter !== 'undefined') { postFetchFilterQueue = postFetchFilterQueue.concat(rsc.__postFetchFilter) } }) this._runFilterPostFetchStage( postFetchFilterQueue, store, InitialComponent, renderedServerComponents, req, res, context) } }) } _runFilterPostFetchStage (filterQueue, store, InitialComponent, renderedServerComponents, req, res, context) { if (filterQueue.length > 0) { let filterFnQueue = [] filterQueue.reverse().forEach((filterFn) => { filterFnQueue.push((callback) => { let filterCallContext = { store: function () { return store.getState().view }, get: function () { return context }, next: function (booleanResult) { if (typeof booleanResult === 'undefined' || booleanResult == null) { booleanResult = true } callback(null, booleanResult) }, redirect: function (redirect) { callback({ type: 'REDIRECTION', redirect: redirect }, false) }, notFound: function () { callback({ type: 'NOT_FOUND' }, false) } } filterFn(filterCallContext) }) }) async.series(filterFnQueue, (err, results) => { if (err) { if (err.type === 'REDIRECTION') { return res.redirect(err.redirect) } else if (err.type === 'NOT_FOUND') { this._renderer.render('404.html', (err, rendered) => { if (err) { logger.error('[ERROR_RENDER_FATAL] An unknown error occurred when trying to render error 404.', err) return res.status(500).end('An unknown error occurred when trying to render error 404\n' + err.stack) } else { return res.status(404).end(resolve(rendered, {})) } }) } else { // TODO what case need to be handled? } } else { this._runRenderStage( store, InitialComponent, renderedServerComponents, req, res, context) } }) } else { this._runRenderStage( store, InitialComponent, renderedServerComponents, req, res, context) } } _createCookieSerializationOption (header) { let option = { path: header.path, domain: header.domain, version: header.version } if (header.maxAge > 0) { option.maxAge = header.maxAge } return option } _runSendResponseStage (res, PAGE_HTML, context) { let responseCookies = context.response.cookies let responseHeaders = context.response.headers.cookies Object.keys(responseCookies).forEach((krc) => { let __cookie = responseCookies[krc] let __cookieHeader = {} if (responseHeaders != null && typeof responseHeaders !== 'undefined') { __cookieHeader = responseHeaders[krc] } if (__cookie != null && typeof __cookie !== 'undefined') { let serializedCookie = cookie.serialize(krc, __cookie, this._createCookieSerializationOption(__cookieHeader)) res.append('Set-Cookie', serializedCookie) } }) res.end(PAGE_HTML) } _runRenderStage (store, InitialComponent, renderedServerComponents, req, res, context) { let finalRenderPage = 'main.html' renderedServerComponents.forEach((rsc) => { if (rsc.__renderPage != null && typeof rsc.__renderPage !== 'undefined') { finalRenderPage = rsc.__renderPage } }) let renderBindFnQueue = [] renderedServerComponents.forEach((rsc) => { if (rsc.__renderBindFn != null && typeof rsc.__renderBindFn !== 'undefined') { let bindFnCall = (callback) => { setTimeout(() => { rsc.__renderBindFn(store.getState(), context, callback) }, 1) } renderBindFnQueue.push(bindFnCall) } }) if (renderBindFnQueue.length > 0) { async.series(renderBindFnQueue, (err, results) => { if (err) { return this._handleError500('[RENDER_BIND_PHASE] FATAL_ERROR in render data binding phase.', err, res) } else { this._renderer.render(finalRenderPage, (err, rendered) => { if (err) { return this._handleError500('[RENDER_VIEW_PHASE] FATAL_ERROR in render view template phase.', err, res) } else { let bindData = {} if (results != null && typeof results !== 'undefined') { results.forEach((r) => { bindData = { ...bindData, ...r } }) } try { const HTML = renderToStaticMarkup(InitialComponent) const PAGE_HTML = resolve(rendered, { ...bindData, HTML: HTML, DATA: store.getState() }, { partial: true }) return this._runSendResponseStage(res, PAGE_HTML, context) } catch (err) { return this._handleError500('[RENDER_STATIC_MARKUP_PHASE] FATAL_ERROR in render staticMarkup phase.', err, res) } } }) } }) } else { this._renderer.render(finalRenderPage, (err, rendered) => { if (err) { return this._handleError500('[RENDER_VIEW_PHASE] FATAL_ERROR in render view template phase.', err, res) } else { let bindData = {} try { const HTML = renderToStaticMarkup(InitialComponent) const PAGE_HTML = resolve(rendered, { ...bindData, HTML: HTML, DATA: store.getState() }, { partial: true }) return this._runSendResponseStage(res, PAGE_HTML, context) } catch (err) { return this._handleError500('[RENDER_STATIC_MARKUP_PHASE] FATAL_ERROR in render staticMarkup phase.', err, res) } } }) } } _importRequestCookie (context, req) { let cookies = req.cookies Object.keys(cookies).forEach((ck) => { context.request.cookies[ck] = req.cookies[ck] }) } _setupRoutingHandler () { const routes = this._routes this._app.use((req, res) => { const location = createLocation(req.url) const locale = req.locale logger.info('[HANDLING_ROUTE] path: ' + req.url + ', locale: ' + locale) match({ routes, location }, (err, redirectLocation, renderProps) => { if (err) { return this._handleError500('[MATCH_ROUTE_FATAL_ERROR] An unknown error occurred when trying to match routes.', err, res) } if (!renderProps) { logger.info('[ROUTE_NOT_FOUND] path: ' + req.url + ', locale: ' + locale) return this._handleNotFound404(res) } let query = {} let queryStringMatch = QS_REGEX.exec(renderProps.location.search) let queryString = '' if (queryStringMatch != null && typeof queryStringMatch !== 'undefined') { queryString = queryStringMatch[1] } if (queryString != null && typeof queryString !== 'undefined') { query = querystring.parse(queryString) } let simplifiedRoutes = { name: renderProps.routes[renderProps.routes.length - 1].name, path: renderProps.routes[renderProps.routes.length - 1].path } let context = { host: this._options.applicationHost, url: req.url, path: location.pathname, locale: locale, params: renderProps.params, query: query, routes: simplifiedRoutes, environment: this._options.environment, server: true, client: false, useragent: req.useragent, request: { cookies: {}, headers: {} }, response: { cookies: {}, headers: {} } } this._importRequestCookie(context, req) let renderedServerComponents = renderProps.components let preFetchFilterQueue = [] renderedServerComponents.forEach((rsc) => { if (rsc.__preFetchFilter != null && typeof rsc.__preFetchFilter !== 'undefined') { preFetchFilterQueue = preFetchFilterQueue.concat(rsc.__preFetchFilter) } }) this._runFilterPreFetchStage( preFetchFilterQueue, renderProps, renderedServerComponents, req, res, context ) }) }) } app () { return this._app } getErrorHandler () { return '/' } run () { this._setupRoutingHandler() this._app.listen(this._options.port, (err) => { if (err) logger.error(err) else { logger.info('[EXPRESS_UNIVERSAL_APPLICATION_SERVER] Server listening on port : ' + this._options.port) } }) let pingApp = express() pingApp.use('/ping', (req, res) => { res.end('pong') }) pingApp.listen(this._options.pingPort, (err) => { if (err) logger.error(err) else { logger.info('[EXPRESS_UNIVERSAL_APPLICATION_SERVER] Ping server listening on port : ' + this._options.pingPort) } }) } } export default ExpressUniversalApplicationServer
packages/veritone-react-common/src/components/FormBuilder/FormBuilder.js
veritone/veritone-sdk
import React from 'react'; import { shape, func, string, arrayOf, objectOf } from 'prop-types'; import { DndProvider } from "react-dnd"; import HTML5Backend from "react-dnd-html5-backend"; import { useDrop } from 'react-dnd'; import _ from 'lodash'; import Button from '@material-ui/core/Button'; import Typography from '@material-ui/core/Typography'; import Link from '@material-ui/core/Link'; import cx from 'classnames'; import NullState from '../NullState'; import DragLayer from './DragLayer'; import Block, { blockTypes } from './FormBlocks'; import formItems, { PreviewWrapper } from './FormItems'; import FormConfiguration from './FormConfiguration'; import PreviewDialog from './PreviewDialog'; import { form as formType } from './configuration'; import { generateSchema } from './utils'; import * as blockUtils from './blockUtils'; import typeConfiguration, { initData } from './typeConfiguration'; import useStyles from './FormBuilder.style.js'; function formEqual({ form }, { form: nextForm }) { return _.isEqual(form, nextForm); } function FormBuilderComponent({ form, addBlock, swapBlock, updateBlock, removeBlock, selectBlock, classes, helpLink }) { const styles = useStyles({}); const [isPreview, setIsPreview] = React.useState(false); const [, drop] = useDrop({ accept: formType, drop: item => { if (isNaN(item.index) && form.length === 0) { addBlock(0, item.id); item.index = 0; } } }); const onUpdateForm = React.useCallback( ({ name, value }) => { const updateIndex = form.findIndex(formItem => formItem.selected); updateBlock(updateIndex, { [name]: value }); }, [updateBlock, form]); const handleClickPreview = React.useCallback(() => { setIsPreview(x => !x); }, []); const onBlockClick = React.useCallback((type) => { addBlock(form.length, type); }, [addBlock, form]); const configurationOpen = form.filter(formItem => formItem.selected); const settingOpen = configurationOpen.length > 0; return ( <div className={cx(styles.formBuilder, classes.container)}> <div className={cx(styles.formBlocks)}> <Typography className={cx(styles.formBlocksTitle)}> Blocks </Typography> <div className={styles.blocksWrapper}> {blockTypes.map(block => ( <Block key={block.type} {...block} onCancel={removeBlock} onClick={onBlockClick} /> ))} </div> <hr /> <Button variant="contained" color="secondary" onClick={handleClickPreview} > Preview </Button> {isPreview && ( <PreviewDialog form={form} handleClose={handleClickPreview} /> )} </div> <div className={cx(styles.blocksPreview, classes.previewContainer)}> { form.length > 0 && ( <Typography className={cx(styles.formPreviewTitle)}> Form preview </Typography> ) } <div ref={drop} className={classes.previewContent}> {form.map((block, index) => { const BlockItem = formItems[block.type]; return ( <PreviewWrapper index={index} key={block.name} selected={block.selected} addBlock={addBlock} swapBlock={swapBlock} updateBlock={updateBlock} removeBlock={removeBlock} selectBlock={selectBlock} > <BlockItem {...block} name={`preview-${block.name}`} /> </PreviewWrapper> ); })} { form.length > 0 && ( <pre> {JSON.stringify(generateSchema(form), null, 2)} </pre> ) } { form.length === 0 && ( <NullState titleText="Begin by selecting block to your right" > <Link href={helpLink} target="_blank"> Need help? Click here to watch a turtorial </Link> </NullState> ) } </div> </div> <div className={styles.configurationContainer}> { settingOpen && ( <Typography className={styles.formConfigurationTitle}> {`${configurationOpen[0].name} settings`} </Typography> ) } { settingOpen && ( <FormConfiguration onChange={onUpdateForm} {...configurationOpen[0]} /> ) } </div> </div> ); } const formPropType = arrayOf( shape({ type: string, name: string }) ); FormBuilderComponent.propTypes = { form: formPropType, addBlock: func, swapBlock: func, removeBlock: func, selectBlock: func, updateBlock: func, classes: objectOf(string), helpLink: string, } FormBuilderComponent.defaultProps = { addBlock: _.noop, swapBlock: _.noop, removeBlock: _.noop, selectBlock: _.noop, updateBlock: _.noop, form: [], classes: {}, helpLink: 'https://help.veritone.com/en/' } const FormBuilderComponentMemo = React.memo(FormBuilderComponent, formEqual); function FormBuilder({ form, onChange, ...remainProps }) { const addBlock = React.useCallback((index, type) => { const name = `${type}-${(new Date()).getTime()}`; const item = typeConfiguration[type] .slice(1) .reduce((data, type) => ({ ...data, [type]: initData[type] }), { type, name }); onChange(blockUtils.add(index, form, item)); }, [onChange, form]); const removeBlock = React.useCallback((index) => { onChange(blockUtils.remove(index, form)); }, [onChange, form]); const updateBlock = React.useCallback((index, item) => { onChange(blockUtils.update(index, form, item)); }, [onChange, form]); const swapBlock = React.useCallback((from, to) => { onChange(blockUtils.swap({ from, to }, form)); }, [onChange, form]); const selectBlock = React.useCallback((index) => { onChange(blockUtils.select(index, form)); }, [onChange, form]); return ( <DndProvider backend={HTML5Backend}> <DragLayer /> <FormBuilderComponentMemo form={form} addBlock={addBlock} removeBlock={removeBlock} updateBlock={updateBlock} swapBlock={swapBlock} selectBlock={selectBlock} {...remainProps} /> </DndProvider> ) } FormBuilder.propTypes = { onChange: func, form: formPropType, classes: objectOf(string) } FormBuilder.defaultProps = { onChange: _.noop, form: [], classes: {} } export default FormBuilder;
src/service/MobileAppsFileSampleService/Scripts/jquery-1.10.2.min.js
lindydonna/app-service-mobile-dotnet-todo-list-files
/* NUGET: BEGIN LICENSE TEXT * * Microsoft grants you the right to use these script files for the sole * purpose of either: (i) interacting through your browser with the Microsoft * website or online service, subject to the applicable licensing or use * terms; or (ii) using the files as included with a Microsoft product subject * to that product's license terms. Microsoft reserves all other rights to the * files not expressly granted by Microsoft, whether by implication, estoppel * or otherwise. Insofar as a script file is dual licensed under GPL, * Microsoft neither took the code under GPL nor distributes it thereunder but * under the terms set out in this paragraph. All notices and licenses * below are for informational purposes only. * * JQUERY CORE 1.10.2; Copyright 2005, 2013 jQuery Foundation, Inc. and other contributors; http://jquery.org/license * Includes Sizzle.js; Copyright 2013 jQuery Foundation, Inc. and other contributors; http://opensource.org/licenses/MIT * * NUGET: END LICENSE TEXT */ /*! jQuery v1.10.2 | (c) 2005, 2013 jQuery Foundation, Inc. | jquery.org/license //@ sourceMappingURL=jquery-1.10.2.min.map */ (function(e,t){var n,r,i=typeof t,o=e.location,a=e.document,s=a.documentElement,l=e.jQuery,u=e.$,c={},p=[],f="1.10.2",d=p.concat,h=p.push,g=p.slice,m=p.indexOf,y=c.toString,v=c.hasOwnProperty,b=f.trim,x=function(e,t){return new x.fn.init(e,t,r)},w=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,T=/\S+/g,C=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,N=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,k=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,E=/^[\],:{}\s]*$/,S=/(?:^|:|,)(?:\s*\[)+/g,A=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,j=/"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g,D=/^-ms-/,L=/-([\da-z])/gi,H=function(e,t){return t.toUpperCase()},q=function(e){(a.addEventListener||"load"===e.type||"complete"===a.readyState)&&(_(),x.ready())},_=function(){a.addEventListener?(a.removeEventListener("DOMContentLoaded",q,!1),e.removeEventListener("load",q,!1)):(a.detachEvent("onreadystatechange",q),e.detachEvent("onload",q))};x.fn=x.prototype={jquery:f,constructor:x,init:function(e,n,r){var i,o;if(!e)return this;if("string"==typeof e){if(i="<"===e.charAt(0)&&">"===e.charAt(e.length-1)&&e.length>=3?[null,e,null]:N.exec(e),!i||!i[1]&&n)return!n||n.jquery?(n||r).find(e):this.constructor(n).find(e);if(i[1]){if(n=n instanceof x?n[0]:n,x.merge(this,x.parseHTML(i[1],n&&n.nodeType?n.ownerDocument||n:a,!0)),k.test(i[1])&&x.isPlainObject(n))for(i in n)x.isFunction(this[i])?this[i](n[i]):this.attr(i,n[i]);return this}if(o=a.getElementById(i[2]),o&&o.parentNode){if(o.id!==i[2])return r.find(e);this.length=1,this[0]=o}return this.context=a,this.selector=e,this}return e.nodeType?(this.context=this[0]=e,this.length=1,this):x.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),x.makeArray(e,this))},selector:"",length:0,toArray:function(){return g.call(this)},get:function(e){return null==e?this.toArray():0>e?this[this.length+e]:this[e]},pushStack:function(e){var t=x.merge(this.constructor(),e);return t.prevObject=this,t.context=this.context,t},each:function(e,t){return x.each(this,e,t)},ready:function(e){return x.ready.promise().done(e),this},slice:function(){return this.pushStack(g.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(0>e?t:0);return this.pushStack(n>=0&&t>n?[this[n]]:[])},map:function(e){return this.pushStack(x.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:h,sort:[].sort,splice:[].splice},x.fn.init.prototype=x.fn,x.extend=x.fn.extend=function(){var e,n,r,i,o,a,s=arguments[0]||{},l=1,u=arguments.length,c=!1;for("boolean"==typeof s&&(c=s,s=arguments[1]||{},l=2),"object"==typeof s||x.isFunction(s)||(s={}),u===l&&(s=this,--l);u>l;l++)if(null!=(o=arguments[l]))for(i in o)e=s[i],r=o[i],s!==r&&(c&&r&&(x.isPlainObject(r)||(n=x.isArray(r)))?(n?(n=!1,a=e&&x.isArray(e)?e:[]):a=e&&x.isPlainObject(e)?e:{},s[i]=x.extend(c,a,r)):r!==t&&(s[i]=r));return s},x.extend({expando:"jQuery"+(f+Math.random()).replace(/\D/g,""),noConflict:function(t){return e.$===x&&(e.$=u),t&&e.jQuery===x&&(e.jQuery=l),x},isReady:!1,readyWait:1,holdReady:function(e){e?x.readyWait++:x.ready(!0)},ready:function(e){if(e===!0?!--x.readyWait:!x.isReady){if(!a.body)return setTimeout(x.ready);x.isReady=!0,e!==!0&&--x.readyWait>0||(n.resolveWith(a,[x]),x.fn.trigger&&x(a).trigger("ready").off("ready"))}},isFunction:function(e){return"function"===x.type(e)},isArray:Array.isArray||function(e){return"array"===x.type(e)},isWindow:function(e){return null!=e&&e==e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?c[y.call(e)]||"object":typeof e},isPlainObject:function(e){var n;if(!e||"object"!==x.type(e)||e.nodeType||x.isWindow(e))return!1;try{if(e.constructor&&!v.call(e,"constructor")&&!v.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(r){return!1}if(x.support.ownLast)for(n in e)return v.call(e,n);for(n in e);return n===t||v.call(e,n)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw Error(e)},parseHTML:function(e,t,n){if(!e||"string"!=typeof e)return null;"boolean"==typeof t&&(n=t,t=!1),t=t||a;var r=k.exec(e),i=!n&&[];return r?[t.createElement(r[1])]:(r=x.buildFragment([e],t,i),i&&x(i).remove(),x.merge([],r.childNodes))},parseJSON:function(n){return e.JSON&&e.JSON.parse?e.JSON.parse(n):null===n?n:"string"==typeof n&&(n=x.trim(n),n&&E.test(n.replace(A,"@").replace(j,"]").replace(S,"")))?Function("return "+n)():(x.error("Invalid JSON: "+n),t)},parseXML:function(n){var r,i;if(!n||"string"!=typeof n)return null;try{e.DOMParser?(i=new DOMParser,r=i.parseFromString(n,"text/xml")):(r=new ActiveXObject("Microsoft.XMLDOM"),r.async="false",r.loadXML(n))}catch(o){r=t}return r&&r.documentElement&&!r.getElementsByTagName("parsererror").length||x.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&x.trim(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(D,"ms-").replace(L,H)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,t,n){var r,i=0,o=e.length,a=M(e);if(n){if(a){for(;o>i;i++)if(r=t.apply(e[i],n),r===!1)break}else for(i in e)if(r=t.apply(e[i],n),r===!1)break}else if(a){for(;o>i;i++)if(r=t.call(e[i],i,e[i]),r===!1)break}else for(i in e)if(r=t.call(e[i],i,e[i]),r===!1)break;return e},trim:b&&!b.call("\ufeff\u00a0")?function(e){return null==e?"":b.call(e)}:function(e){return null==e?"":(e+"").replace(C,"")},makeArray:function(e,t){var n=t||[];return null!=e&&(M(Object(e))?x.merge(n,"string"==typeof e?[e]:e):h.call(n,e)),n},inArray:function(e,t,n){var r;if(t){if(m)return m.call(t,e,n);for(r=t.length,n=n?0>n?Math.max(0,r+n):n:0;r>n;n++)if(n in t&&t[n]===e)return n}return-1},merge:function(e,n){var r=n.length,i=e.length,o=0;if("number"==typeof r)for(;r>o;o++)e[i++]=n[o];else while(n[o]!==t)e[i++]=n[o++];return e.length=i,e},grep:function(e,t,n){var r,i=[],o=0,a=e.length;for(n=!!n;a>o;o++)r=!!t(e[o],o),n!==r&&i.push(e[o]);return i},map:function(e,t,n){var r,i=0,o=e.length,a=M(e),s=[];if(a)for(;o>i;i++)r=t(e[i],i,n),null!=r&&(s[s.length]=r);else for(i in e)r=t(e[i],i,n),null!=r&&(s[s.length]=r);return d.apply([],s)},guid:1,proxy:function(e,n){var r,i,o;return"string"==typeof n&&(o=e[n],n=e,e=o),x.isFunction(e)?(r=g.call(arguments,2),i=function(){return e.apply(n||this,r.concat(g.call(arguments)))},i.guid=e.guid=e.guid||x.guid++,i):t},access:function(e,n,r,i,o,a,s){var l=0,u=e.length,c=null==r;if("object"===x.type(r)){o=!0;for(l in r)x.access(e,n,l,r[l],!0,a,s)}else if(i!==t&&(o=!0,x.isFunction(i)||(s=!0),c&&(s?(n.call(e,i),n=null):(c=n,n=function(e,t,n){return c.call(x(e),n)})),n))for(;u>l;l++)n(e[l],r,s?i:i.call(e[l],l,n(e[l],r)));return o?e:c?n.call(e):u?n(e[0],r):a},now:function(){return(new Date).getTime()},swap:function(e,t,n,r){var i,o,a={};for(o in t)a[o]=e.style[o],e.style[o]=t[o];i=n.apply(e,r||[]);for(o in t)e.style[o]=a[o];return i}}),x.ready.promise=function(t){if(!n)if(n=x.Deferred(),"complete"===a.readyState)setTimeout(x.ready);else if(a.addEventListener)a.addEventListener("DOMContentLoaded",q,!1),e.addEventListener("load",q,!1);else{a.attachEvent("onreadystatechange",q),e.attachEvent("onload",q);var r=!1;try{r=null==e.frameElement&&a.documentElement}catch(i){}r&&r.doScroll&&function o(){if(!x.isReady){try{r.doScroll("left")}catch(e){return setTimeout(o,50)}_(),x.ready()}}()}return n.promise(t)},x.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(e,t){c["[object "+t+"]"]=t.toLowerCase()});function M(e){var t=e.length,n=x.type(e);return x.isWindow(e)?!1:1===e.nodeType&&t?!0:"array"===n||"function"!==n&&(0===t||"number"==typeof t&&t>0&&t-1 in e)}r=x(a),function(e,t){var n,r,i,o,a,s,l,u,c,p,f,d,h,g,m,y,v,b="sizzle"+-new Date,w=e.document,T=0,C=0,N=st(),k=st(),E=st(),S=!1,A=function(e,t){return e===t?(S=!0,0):0},j=typeof t,D=1<<31,L={}.hasOwnProperty,H=[],q=H.pop,_=H.push,M=H.push,O=H.slice,F=H.indexOf||function(e){var t=0,n=this.length;for(;n>t;t++)if(this[t]===e)return t;return-1},B="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",P="[\\x20\\t\\r\\n\\f]",R="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",W=R.replace("w","w#"),$="\\["+P+"*("+R+")"+P+"*(?:([*^$|!~]?=)"+P+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+W+")|)|)"+P+"*\\]",I=":("+R+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+$.replace(3,8)+")*)|.*)\\)|)",z=RegExp("^"+P+"+|((?:^|[^\\\\])(?:\\\\.)*)"+P+"+$","g"),X=RegExp("^"+P+"*,"+P+"*"),U=RegExp("^"+P+"*([>+~]|"+P+")"+P+"*"),V=RegExp(P+"*[+~]"),Y=RegExp("="+P+"*([^\\]'\"]*)"+P+"*\\]","g"),J=RegExp(I),G=RegExp("^"+W+"$"),Q={ID:RegExp("^#("+R+")"),CLASS:RegExp("^\\.("+R+")"),TAG:RegExp("^("+R.replace("w","w*")+")"),ATTR:RegExp("^"+$),PSEUDO:RegExp("^"+I),CHILD:RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+P+"*(even|odd|(([+-]|)(\\d*)n|)"+P+"*(?:([+-]|)"+P+"*(\\d+)|))"+P+"*\\)|)","i"),bool:RegExp("^(?:"+B+")$","i"),needsContext:RegExp("^"+P+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+P+"*((?:-\\d)?\\d*)"+P+"*\\)|)(?=[^-]|$)","i")},K=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,et=/^(?:input|select|textarea|button)$/i,tt=/^h\d$/i,nt=/'|\\/g,rt=RegExp("\\\\([\\da-f]{1,6}"+P+"?|("+P+")|.)","ig"),it=function(e,t,n){var r="0x"+t-65536;return r!==r||n?t:0>r?String.fromCharCode(r+65536):String.fromCharCode(55296|r>>10,56320|1023&r)};try{M.apply(H=O.call(w.childNodes),w.childNodes),H[w.childNodes.length].nodeType}catch(ot){M={apply:H.length?function(e,t){_.apply(e,O.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function at(e,t,n,i){var o,a,s,l,u,c,d,m,y,x;if((t?t.ownerDocument||t:w)!==f&&p(t),t=t||f,n=n||[],!e||"string"!=typeof e)return n;if(1!==(l=t.nodeType)&&9!==l)return[];if(h&&!i){if(o=Z.exec(e))if(s=o[1]){if(9===l){if(a=t.getElementById(s),!a||!a.parentNode)return n;if(a.id===s)return n.push(a),n}else if(t.ownerDocument&&(a=t.ownerDocument.getElementById(s))&&v(t,a)&&a.id===s)return n.push(a),n}else{if(o[2])return M.apply(n,t.getElementsByTagName(e)),n;if((s=o[3])&&r.getElementsByClassName&&t.getElementsByClassName)return M.apply(n,t.getElementsByClassName(s)),n}if(r.qsa&&(!g||!g.test(e))){if(m=d=b,y=t,x=9===l&&e,1===l&&"object"!==t.nodeName.toLowerCase()){c=mt(e),(d=t.getAttribute("id"))?m=d.replace(nt,"\\$&"):t.setAttribute("id",m),m="[id='"+m+"'] ",u=c.length;while(u--)c[u]=m+yt(c[u]);y=V.test(e)&&t.parentNode||t,x=c.join(",")}if(x)try{return M.apply(n,y.querySelectorAll(x)),n}catch(T){}finally{d||t.removeAttribute("id")}}}return kt(e.replace(z,"$1"),t,n,i)}function st(){var e=[];function t(n,r){return e.push(n+=" ")>o.cacheLength&&delete t[e.shift()],t[n]=r}return t}function lt(e){return e[b]=!0,e}function ut(e){var t=f.createElement("div");try{return!!e(t)}catch(n){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function ct(e,t){var n=e.split("|"),r=e.length;while(r--)o.attrHandle[n[r]]=t}function pt(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&(~t.sourceIndex||D)-(~e.sourceIndex||D);if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function ft(e){return function(t){var n=t.nodeName.toLowerCase();return"input"===n&&t.type===e}}function dt(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function ht(e){return lt(function(t){return t=+t,lt(function(n,r){var i,o=e([],n.length,t),a=o.length;while(a--)n[i=o[a]]&&(n[i]=!(r[i]=n[i]))})})}s=at.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?"HTML"!==t.nodeName:!1},r=at.support={},p=at.setDocument=function(e){var n=e?e.ownerDocument||e:w,i=n.defaultView;return n!==f&&9===n.nodeType&&n.documentElement?(f=n,d=n.documentElement,h=!s(n),i&&i.attachEvent&&i!==i.top&&i.attachEvent("onbeforeunload",function(){p()}),r.attributes=ut(function(e){return e.className="i",!e.getAttribute("className")}),r.getElementsByTagName=ut(function(e){return e.appendChild(n.createComment("")),!e.getElementsByTagName("*").length}),r.getElementsByClassName=ut(function(e){return e.innerHTML="<div class='a'></div><div class='a i'></div>",e.firstChild.className="i",2===e.getElementsByClassName("i").length}),r.getById=ut(function(e){return d.appendChild(e).id=b,!n.getElementsByName||!n.getElementsByName(b).length}),r.getById?(o.find.ID=function(e,t){if(typeof t.getElementById!==j&&h){var n=t.getElementById(e);return n&&n.parentNode?[n]:[]}},o.filter.ID=function(e){var t=e.replace(rt,it);return function(e){return e.getAttribute("id")===t}}):(delete o.find.ID,o.filter.ID=function(e){var t=e.replace(rt,it);return function(e){var n=typeof e.getAttributeNode!==j&&e.getAttributeNode("id");return n&&n.value===t}}),o.find.TAG=r.getElementsByTagName?function(e,n){return typeof n.getElementsByTagName!==j?n.getElementsByTagName(e):t}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},o.find.CLASS=r.getElementsByClassName&&function(e,n){return typeof n.getElementsByClassName!==j&&h?n.getElementsByClassName(e):t},m=[],g=[],(r.qsa=K.test(n.querySelectorAll))&&(ut(function(e){e.innerHTML="<select><option selected=''></option></select>",e.querySelectorAll("[selected]").length||g.push("\\["+P+"*(?:value|"+B+")"),e.querySelectorAll(":checked").length||g.push(":checked")}),ut(function(e){var t=n.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("t",""),e.querySelectorAll("[t^='']").length&&g.push("[*^$]="+P+"*(?:''|\"\")"),e.querySelectorAll(":enabled").length||g.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),g.push(",.*:")})),(r.matchesSelector=K.test(y=d.webkitMatchesSelector||d.mozMatchesSelector||d.oMatchesSelector||d.msMatchesSelector))&&ut(function(e){r.disconnectedMatch=y.call(e,"div"),y.call(e,"[s!='']:x"),m.push("!=",I)}),g=g.length&&RegExp(g.join("|")),m=m.length&&RegExp(m.join("|")),v=K.test(d.contains)||d.compareDocumentPosition?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},A=d.compareDocumentPosition?function(e,t){if(e===t)return S=!0,0;var i=t.compareDocumentPosition&&e.compareDocumentPosition&&e.compareDocumentPosition(t);return i?1&i||!r.sortDetached&&t.compareDocumentPosition(e)===i?e===n||v(w,e)?-1:t===n||v(w,t)?1:c?F.call(c,e)-F.call(c,t):0:4&i?-1:1:e.compareDocumentPosition?-1:1}:function(e,t){var r,i=0,o=e.parentNode,a=t.parentNode,s=[e],l=[t];if(e===t)return S=!0,0;if(!o||!a)return e===n?-1:t===n?1:o?-1:a?1:c?F.call(c,e)-F.call(c,t):0;if(o===a)return pt(e,t);r=e;while(r=r.parentNode)s.unshift(r);r=t;while(r=r.parentNode)l.unshift(r);while(s[i]===l[i])i++;return i?pt(s[i],l[i]):s[i]===w?-1:l[i]===w?1:0},n):f},at.matches=function(e,t){return at(e,null,null,t)},at.matchesSelector=function(e,t){if((e.ownerDocument||e)!==f&&p(e),t=t.replace(Y,"='$1']"),!(!r.matchesSelector||!h||m&&m.test(t)||g&&g.test(t)))try{var n=y.call(e,t);if(n||r.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(i){}return at(t,f,null,[e]).length>0},at.contains=function(e,t){return(e.ownerDocument||e)!==f&&p(e),v(e,t)},at.attr=function(e,n){(e.ownerDocument||e)!==f&&p(e);var i=o.attrHandle[n.toLowerCase()],a=i&&L.call(o.attrHandle,n.toLowerCase())?i(e,n,!h):t;return a===t?r.attributes||!h?e.getAttribute(n):(a=e.getAttributeNode(n))&&a.specified?a.value:null:a},at.error=function(e){throw Error("Syntax error, unrecognized expression: "+e)},at.uniqueSort=function(e){var t,n=[],i=0,o=0;if(S=!r.detectDuplicates,c=!r.sortStable&&e.slice(0),e.sort(A),S){while(t=e[o++])t===e[o]&&(i=n.push(o));while(i--)e.splice(n[i],1)}return e},a=at.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(1===i||9===i||11===i){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=a(e)}else if(3===i||4===i)return e.nodeValue}else for(;t=e[r];r++)n+=a(t);return n},o=at.selectors={cacheLength:50,createPseudo:lt,match:Q,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(rt,it),e[3]=(e[4]||e[5]||"").replace(rt,it),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||at.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&at.error(e[0]),e},PSEUDO:function(e){var n,r=!e[5]&&e[2];return Q.CHILD.test(e[0])?null:(e[3]&&e[4]!==t?e[2]=e[4]:r&&J.test(r)&&(n=mt(r,!0))&&(n=r.indexOf(")",r.length-n)-r.length)&&(e[0]=e[0].slice(0,n),e[2]=r.slice(0,n)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(rt,it).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=N[e+" "];return t||(t=RegExp("(^|"+P+")"+e+"("+P+"|$)"))&&N(e,function(e){return t.test("string"==typeof e.className&&e.className||typeof e.getAttribute!==j&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r){var i=at.attr(r,e);return null==i?"!="===t:t?(i+="","="===t?i===n:"!="===t?i!==n:"^="===t?n&&0===i.indexOf(n):"*="===t?n&&i.indexOf(n)>-1:"$="===t?n&&i.slice(-n.length)===n:"~="===t?(" "+i+" ").indexOf(n)>-1:"|="===t?i===n||i.slice(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,r,i){var o="nth"!==e.slice(0,3),a="last"!==e.slice(-4),s="of-type"===t;return 1===r&&0===i?function(e){return!!e.parentNode}:function(t,n,l){var u,c,p,f,d,h,g=o!==a?"nextSibling":"previousSibling",m=t.parentNode,y=s&&t.nodeName.toLowerCase(),v=!l&&!s;if(m){if(o){while(g){p=t;while(p=p[g])if(s?p.nodeName.toLowerCase()===y:1===p.nodeType)return!1;h=g="only"===e&&!h&&"nextSibling"}return!0}if(h=[a?m.firstChild:m.lastChild],a&&v){c=m[b]||(m[b]={}),u=c[e]||[],d=u[0]===T&&u[1],f=u[0]===T&&u[2],p=d&&m.childNodes[d];while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if(1===p.nodeType&&++f&&p===t){c[e]=[T,d,f];break}}else if(v&&(u=(t[b]||(t[b]={}))[e])&&u[0]===T)f=u[1];else while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if((s?p.nodeName.toLowerCase()===y:1===p.nodeType)&&++f&&(v&&((p[b]||(p[b]={}))[e]=[T,f]),p===t))break;return f-=i,f===r||0===f%r&&f/r>=0}}},PSEUDO:function(e,t){var n,r=o.pseudos[e]||o.setFilters[e.toLowerCase()]||at.error("unsupported pseudo: "+e);return r[b]?r(t):r.length>1?(n=[e,e,"",t],o.setFilters.hasOwnProperty(e.toLowerCase())?lt(function(e,n){var i,o=r(e,t),a=o.length;while(a--)i=F.call(e,o[a]),e[i]=!(n[i]=o[a])}):function(e){return r(e,0,n)}):r}},pseudos:{not:lt(function(e){var t=[],n=[],r=l(e.replace(z,"$1"));return r[b]?lt(function(e,t,n,i){var o,a=r(e,null,i,[]),s=e.length;while(s--)(o=a[s])&&(e[s]=!(t[s]=o))}):function(e,i,o){return t[0]=e,r(t,null,o,n),!n.pop()}}),has:lt(function(e){return function(t){return at(e,t).length>0}}),contains:lt(function(e){return function(t){return(t.textContent||t.innerText||a(t)).indexOf(e)>-1}}),lang:lt(function(e){return G.test(e||"")||at.error("unsupported lang: "+e),e=e.replace(rt,it).toLowerCase(),function(t){var n;do if(n=h?t.lang:t.getAttribute("xml:lang")||t.getAttribute("lang"))return n=n.toLowerCase(),n===e||0===n.indexOf(e+"-");while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===d},focus:function(e){return e===f.activeElement&&(!f.hasFocus||f.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeName>"@"||3===e.nodeType||4===e.nodeType)return!1;return!0},parent:function(e){return!o.pseudos.empty(e)},header:function(e){return tt.test(e.nodeName)},input:function(e){return et.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||t.toLowerCase()===e.type)},first:ht(function(){return[0]}),last:ht(function(e,t){return[t-1]}),eq:ht(function(e,t,n){return[0>n?n+t:n]}),even:ht(function(e,t){var n=0;for(;t>n;n+=2)e.push(n);return e}),odd:ht(function(e,t){var n=1;for(;t>n;n+=2)e.push(n);return e}),lt:ht(function(e,t,n){var r=0>n?n+t:n;for(;--r>=0;)e.push(r);return e}),gt:ht(function(e,t,n){var r=0>n?n+t:n;for(;t>++r;)e.push(r);return e})}},o.pseudos.nth=o.pseudos.eq;for(n in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})o.pseudos[n]=ft(n);for(n in{submit:!0,reset:!0})o.pseudos[n]=dt(n);function gt(){}gt.prototype=o.filters=o.pseudos,o.setFilters=new gt;function mt(e,t){var n,r,i,a,s,l,u,c=k[e+" "];if(c)return t?0:c.slice(0);s=e,l=[],u=o.preFilter;while(s){(!n||(r=X.exec(s)))&&(r&&(s=s.slice(r[0].length)||s),l.push(i=[])),n=!1,(r=U.exec(s))&&(n=r.shift(),i.push({value:n,type:r[0].replace(z," ")}),s=s.slice(n.length));for(a in o.filter)!(r=Q[a].exec(s))||u[a]&&!(r=u[a](r))||(n=r.shift(),i.push({value:n,type:a,matches:r}),s=s.slice(n.length));if(!n)break}return t?s.length:s?at.error(e):k(e,l).slice(0)}function yt(e){var t=0,n=e.length,r="";for(;n>t;t++)r+=e[t].value;return r}function vt(e,t,n){var r=t.dir,o=n&&"parentNode"===r,a=C++;return t.first?function(t,n,i){while(t=t[r])if(1===t.nodeType||o)return e(t,n,i)}:function(t,n,s){var l,u,c,p=T+" "+a;if(s){while(t=t[r])if((1===t.nodeType||o)&&e(t,n,s))return!0}else while(t=t[r])if(1===t.nodeType||o)if(c=t[b]||(t[b]={}),(u=c[r])&&u[0]===p){if((l=u[1])===!0||l===i)return l===!0}else if(u=c[r]=[p],u[1]=e(t,n,s)||i,u[1]===!0)return!0}}function bt(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 xt(e,t,n,r,i){var o,a=[],s=0,l=e.length,u=null!=t;for(;l>s;s++)(o=e[s])&&(!n||n(o,r,i))&&(a.push(o),u&&t.push(s));return a}function wt(e,t,n,r,i,o){return r&&!r[b]&&(r=wt(r)),i&&!i[b]&&(i=wt(i,o)),lt(function(o,a,s,l){var u,c,p,f=[],d=[],h=a.length,g=o||Nt(t||"*",s.nodeType?[s]:s,[]),m=!e||!o&&t?g:xt(g,f,e,s,l),y=n?i||(o?e:h||r)?[]:a:m;if(n&&n(m,y,s,l),r){u=xt(y,d),r(u,[],s,l),c=u.length;while(c--)(p=u[c])&&(y[d[c]]=!(m[d[c]]=p))}if(o){if(i||e){if(i){u=[],c=y.length;while(c--)(p=y[c])&&u.push(m[c]=p);i(null,y=[],u,l)}c=y.length;while(c--)(p=y[c])&&(u=i?F.call(o,p):f[c])>-1&&(o[u]=!(a[u]=p))}}else y=xt(y===a?y.splice(h,y.length):y),i?i(null,a,y,l):M.apply(a,y)})}function Tt(e){var t,n,r,i=e.length,a=o.relative[e[0].type],s=a||o.relative[" "],l=a?1:0,c=vt(function(e){return e===t},s,!0),p=vt(function(e){return F.call(t,e)>-1},s,!0),f=[function(e,n,r){return!a&&(r||n!==u)||((t=n).nodeType?c(e,n,r):p(e,n,r))}];for(;i>l;l++)if(n=o.relative[e[l].type])f=[vt(bt(f),n)];else{if(n=o.filter[e[l].type].apply(null,e[l].matches),n[b]){for(r=++l;i>r;r++)if(o.relative[e[r].type])break;return wt(l>1&&bt(f),l>1&&yt(e.slice(0,l-1).concat({value:" "===e[l-2].type?"*":""})).replace(z,"$1"),n,r>l&&Tt(e.slice(l,r)),i>r&&Tt(e=e.slice(r)),i>r&&yt(e))}f.push(n)}return bt(f)}function Ct(e,t){var n=0,r=t.length>0,a=e.length>0,s=function(s,l,c,p,d){var h,g,m,y=[],v=0,b="0",x=s&&[],w=null!=d,C=u,N=s||a&&o.find.TAG("*",d&&l.parentNode||l),k=T+=null==C?1:Math.random()||.1;for(w&&(u=l!==f&&l,i=n);null!=(h=N[b]);b++){if(a&&h){g=0;while(m=e[g++])if(m(h,l,c)){p.push(h);break}w&&(T=k,i=++n)}r&&((h=!m&&h)&&v--,s&&x.push(h))}if(v+=b,r&&b!==v){g=0;while(m=t[g++])m(x,y,l,c);if(s){if(v>0)while(b--)x[b]||y[b]||(y[b]=q.call(p));y=xt(y)}M.apply(p,y),w&&!s&&y.length>0&&v+t.length>1&&at.uniqueSort(p)}return w&&(T=k,u=C),x};return r?lt(s):s}l=at.compile=function(e,t){var n,r=[],i=[],o=E[e+" "];if(!o){t||(t=mt(e)),n=t.length;while(n--)o=Tt(t[n]),o[b]?r.push(o):i.push(o);o=E(e,Ct(i,r))}return o};function Nt(e,t,n){var r=0,i=t.length;for(;i>r;r++)at(e,t[r],n);return n}function kt(e,t,n,i){var a,s,u,c,p,f=mt(e);if(!i&&1===f.length){if(s=f[0]=f[0].slice(0),s.length>2&&"ID"===(u=s[0]).type&&r.getById&&9===t.nodeType&&h&&o.relative[s[1].type]){if(t=(o.find.ID(u.matches[0].replace(rt,it),t)||[])[0],!t)return n;e=e.slice(s.shift().value.length)}a=Q.needsContext.test(e)?0:s.length;while(a--){if(u=s[a],o.relative[c=u.type])break;if((p=o.find[c])&&(i=p(u.matches[0].replace(rt,it),V.test(s[0].type)&&t.parentNode||t))){if(s.splice(a,1),e=i.length&&yt(s),!e)return M.apply(n,i),n;break}}}return l(e,f)(i,t,!h,n,V.test(e)),n}r.sortStable=b.split("").sort(A).join("")===b,r.detectDuplicates=S,p(),r.sortDetached=ut(function(e){return 1&e.compareDocumentPosition(f.createElement("div"))}),ut(function(e){return e.innerHTML="<a href='#'></a>","#"===e.firstChild.getAttribute("href")})||ct("type|href|height|width",function(e,n,r){return r?t:e.getAttribute(n,"type"===n.toLowerCase()?1:2)}),r.attributes&&ut(function(e){return e.innerHTML="<input/>",e.firstChild.setAttribute("value",""),""===e.firstChild.getAttribute("value")})||ct("value",function(e,n,r){return r||"input"!==e.nodeName.toLowerCase()?t:e.defaultValue}),ut(function(e){return null==e.getAttribute("disabled")})||ct(B,function(e,n,r){var i;return r?t:(i=e.getAttributeNode(n))&&i.specified?i.value:e[n]===!0?n.toLowerCase():null}),x.find=at,x.expr=at.selectors,x.expr[":"]=x.expr.pseudos,x.unique=at.uniqueSort,x.text=at.getText,x.isXMLDoc=at.isXML,x.contains=at.contains}(e);var O={};function F(e){var t=O[e]={};return x.each(e.match(T)||[],function(e,n){t[n]=!0}),t}x.Callbacks=function(e){e="string"==typeof e?O[e]||F(e):x.extend({},e);var n,r,i,o,a,s,l=[],u=!e.once&&[],c=function(t){for(r=e.memory&&t,i=!0,a=s||0,s=0,o=l.length,n=!0;l&&o>a;a++)if(l[a].apply(t[0],t[1])===!1&&e.stopOnFalse){r=!1;break}n=!1,l&&(u?u.length&&c(u.shift()):r?l=[]:p.disable())},p={add:function(){if(l){var t=l.length;(function i(t){x.each(t,function(t,n){var r=x.type(n);"function"===r?e.unique&&p.has(n)||l.push(n):n&&n.length&&"string"!==r&&i(n)})})(arguments),n?o=l.length:r&&(s=t,c(r))}return this},remove:function(){return l&&x.each(arguments,function(e,t){var r;while((r=x.inArray(t,l,r))>-1)l.splice(r,1),n&&(o>=r&&o--,a>=r&&a--)}),this},has:function(e){return e?x.inArray(e,l)>-1:!(!l||!l.length)},empty:function(){return l=[],o=0,this},disable:function(){return l=u=r=t,this},disabled:function(){return!l},lock:function(){return u=t,r||p.disable(),this},locked:function(){return!u},fireWith:function(e,t){return!l||i&&!u||(t=t||[],t=[e,t.slice?t.slice():t],n?u.push(t):c(t)),this},fire:function(){return p.fireWith(this,arguments),this},fired:function(){return!!i}};return p},x.extend({Deferred:function(e){var t=[["resolve","done",x.Callbacks("once memory"),"resolved"],["reject","fail",x.Callbacks("once memory"),"rejected"],["notify","progress",x.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return x.Deferred(function(n){x.each(t,function(t,o){var a=o[0],s=x.isFunction(e[t])&&e[t];i[o[1]](function(){var e=s&&s.apply(this,arguments);e&&x.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[a+"With"](this===r?n.promise():this,s?[e]:arguments)})}),e=null}).promise()},promise:function(e){return null!=e?x.extend(e,r):r}},i={};return r.pipe=r.then,x.each(t,function(e,o){var a=o[2],s=o[3];r[o[1]]=a.add,s&&a.add(function(){n=s},t[1^e][2].disable,t[2][2].lock),i[o[0]]=function(){return i[o[0]+"With"](this===i?r:this,arguments),this},i[o[0]+"With"]=a.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=g.call(arguments),r=n.length,i=1!==r||e&&x.isFunction(e.promise)?r:0,o=1===i?e:x.Deferred(),a=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?g.call(arguments):r,n===s?o.notifyWith(t,n):--i||o.resolveWith(t,n)}},s,l,u;if(r>1)for(s=Array(r),l=Array(r),u=Array(r);r>t;t++)n[t]&&x.isFunction(n[t].promise)?n[t].promise().done(a(t,u,n)).fail(o.reject).progress(a(t,l,s)):--i;return i||o.resolveWith(u,n),o.promise()}}),x.support=function(t){var n,r,o,s,l,u,c,p,f,d=a.createElement("div");if(d.setAttribute("className","t"),d.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",n=d.getElementsByTagName("*")||[],r=d.getElementsByTagName("a")[0],!r||!r.style||!n.length)return t;s=a.createElement("select"),u=s.appendChild(a.createElement("option")),o=d.getElementsByTagName("input")[0],r.style.cssText="top:1px;float:left;opacity:.5",t.getSetAttribute="t"!==d.className,t.leadingWhitespace=3===d.firstChild.nodeType,t.tbody=!d.getElementsByTagName("tbody").length,t.htmlSerialize=!!d.getElementsByTagName("link").length,t.style=/top/.test(r.getAttribute("style")),t.hrefNormalized="/a"===r.getAttribute("href"),t.opacity=/^0.5/.test(r.style.opacity),t.cssFloat=!!r.style.cssFloat,t.checkOn=!!o.value,t.optSelected=u.selected,t.enctype=!!a.createElement("form").enctype,t.html5Clone="<:nav></:nav>"!==a.createElement("nav").cloneNode(!0).outerHTML,t.inlineBlockNeedsLayout=!1,t.shrinkWrapBlocks=!1,t.pixelPosition=!1,t.deleteExpando=!0,t.noCloneEvent=!0,t.reliableMarginRight=!0,t.boxSizingReliable=!0,o.checked=!0,t.noCloneChecked=o.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!u.disabled;try{delete d.test}catch(h){t.deleteExpando=!1}o=a.createElement("input"),o.setAttribute("value",""),t.input=""===o.getAttribute("value"),o.value="t",o.setAttribute("type","radio"),t.radioValue="t"===o.value,o.setAttribute("checked","t"),o.setAttribute("name","t"),l=a.createDocumentFragment(),l.appendChild(o),t.appendChecked=o.checked,t.checkClone=l.cloneNode(!0).cloneNode(!0).lastChild.checked,d.attachEvent&&(d.attachEvent("onclick",function(){t.noCloneEvent=!1}),d.cloneNode(!0).click());for(f in{submit:!0,change:!0,focusin:!0})d.setAttribute(c="on"+f,"t"),t[f+"Bubbles"]=c in e||d.attributes[c].expando===!1;d.style.backgroundClip="content-box",d.cloneNode(!0).style.backgroundClip="",t.clearCloneStyle="content-box"===d.style.backgroundClip;for(f in x(t))break;return t.ownLast="0"!==f,x(function(){var n,r,o,s="padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;",l=a.getElementsByTagName("body")[0];l&&(n=a.createElement("div"),n.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",l.appendChild(n).appendChild(d),d.innerHTML="<table><tr><td></td><td>t</td></tr></table>",o=d.getElementsByTagName("td"),o[0].style.cssText="padding:0;margin:0;border:0;display:none",p=0===o[0].offsetHeight,o[0].style.display="",o[1].style.display="none",t.reliableHiddenOffsets=p&&0===o[0].offsetHeight,d.innerHTML="",d.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",x.swap(l,null!=l.style.zoom?{zoom:1}:{},function(){t.boxSizing=4===d.offsetWidth}),e.getComputedStyle&&(t.pixelPosition="1%"!==(e.getComputedStyle(d,null)||{}).top,t.boxSizingReliable="4px"===(e.getComputedStyle(d,null)||{width:"4px"}).width,r=d.appendChild(a.createElement("div")),r.style.cssText=d.style.cssText=s,r.style.marginRight=r.style.width="0",d.style.width="1px",t.reliableMarginRight=!parseFloat((e.getComputedStyle(r,null)||{}).marginRight)),typeof d.style.zoom!==i&&(d.innerHTML="",d.style.cssText=s+"width:1px;padding:1px;display:inline;zoom:1",t.inlineBlockNeedsLayout=3===d.offsetWidth,d.style.display="block",d.innerHTML="<div></div>",d.firstChild.style.width="5px",t.shrinkWrapBlocks=3!==d.offsetWidth,t.inlineBlockNeedsLayout&&(l.style.zoom=1)),l.removeChild(n),n=d=o=r=null)}),n=s=l=u=r=o=null,t }({});var B=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,P=/([A-Z])/g;function R(e,n,r,i){if(x.acceptData(e)){var o,a,s=x.expando,l=e.nodeType,u=l?x.cache:e,c=l?e[s]:e[s]&&s;if(c&&u[c]&&(i||u[c].data)||r!==t||"string"!=typeof n)return c||(c=l?e[s]=p.pop()||x.guid++:s),u[c]||(u[c]=l?{}:{toJSON:x.noop}),("object"==typeof n||"function"==typeof n)&&(i?u[c]=x.extend(u[c],n):u[c].data=x.extend(u[c].data,n)),a=u[c],i||(a.data||(a.data={}),a=a.data),r!==t&&(a[x.camelCase(n)]=r),"string"==typeof n?(o=a[n],null==o&&(o=a[x.camelCase(n)])):o=a,o}}function W(e,t,n){if(x.acceptData(e)){var r,i,o=e.nodeType,a=o?x.cache:e,s=o?e[x.expando]:x.expando;if(a[s]){if(t&&(r=n?a[s]:a[s].data)){x.isArray(t)?t=t.concat(x.map(t,x.camelCase)):t in r?t=[t]:(t=x.camelCase(t),t=t in r?[t]:t.split(" ")),i=t.length;while(i--)delete r[t[i]];if(n?!I(r):!x.isEmptyObject(r))return}(n||(delete a[s].data,I(a[s])))&&(o?x.cleanData([e],!0):x.support.deleteExpando||a!=a.window?delete a[s]:a[s]=null)}}}x.extend({cache:{},noData:{applet:!0,embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(e){return e=e.nodeType?x.cache[e[x.expando]]:e[x.expando],!!e&&!I(e)},data:function(e,t,n){return R(e,t,n)},removeData:function(e,t){return W(e,t)},_data:function(e,t,n){return R(e,t,n,!0)},_removeData:function(e,t){return W(e,t,!0)},acceptData:function(e){if(e.nodeType&&1!==e.nodeType&&9!==e.nodeType)return!1;var t=e.nodeName&&x.noData[e.nodeName.toLowerCase()];return!t||t!==!0&&e.getAttribute("classid")===t}}),x.fn.extend({data:function(e,n){var r,i,o=null,a=0,s=this[0];if(e===t){if(this.length&&(o=x.data(s),1===s.nodeType&&!x._data(s,"parsedAttrs"))){for(r=s.attributes;r.length>a;a++)i=r[a].name,0===i.indexOf("data-")&&(i=x.camelCase(i.slice(5)),$(s,i,o[i]));x._data(s,"parsedAttrs",!0)}return o}return"object"==typeof e?this.each(function(){x.data(this,e)}):arguments.length>1?this.each(function(){x.data(this,e,n)}):s?$(s,e,x.data(s,e)):null},removeData:function(e){return this.each(function(){x.removeData(this,e)})}});function $(e,n,r){if(r===t&&1===e.nodeType){var i="data-"+n.replace(P,"-$1").toLowerCase();if(r=e.getAttribute(i),"string"==typeof r){try{r="true"===r?!0:"false"===r?!1:"null"===r?null:+r+""===r?+r:B.test(r)?x.parseJSON(r):r}catch(o){}x.data(e,n,r)}else r=t}return r}function I(e){var t;for(t in e)if(("data"!==t||!x.isEmptyObject(e[t]))&&"toJSON"!==t)return!1;return!0}x.extend({queue:function(e,n,r){var i;return e?(n=(n||"fx")+"queue",i=x._data(e,n),r&&(!i||x.isArray(r)?i=x._data(e,n,x.makeArray(r)):i.push(r)),i||[]):t},dequeue:function(e,t){t=t||"fx";var n=x.queue(e,t),r=n.length,i=n.shift(),o=x._queueHooks(e,t),a=function(){x.dequeue(e,t)};"inprogress"===i&&(i=n.shift(),r--),i&&("fx"===t&&n.unshift("inprogress"),delete o.stop,i.call(e,a,o)),!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return x._data(e,n)||x._data(e,n,{empty:x.Callbacks("once memory").add(function(){x._removeData(e,t+"queue"),x._removeData(e,n)})})}}),x.fn.extend({queue:function(e,n){var r=2;return"string"!=typeof e&&(n=e,e="fx",r--),r>arguments.length?x.queue(this[0],e):n===t?this:this.each(function(){var t=x.queue(this,e,n);x._queueHooks(this,e),"fx"===e&&"inprogress"!==t[0]&&x.dequeue(this,e)})},dequeue:function(e){return this.each(function(){x.dequeue(this,e)})},delay:function(e,t){return e=x.fx?x.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,n){var r=setTimeout(t,e);n.stop=function(){clearTimeout(r)}})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,n){var r,i=1,o=x.Deferred(),a=this,s=this.length,l=function(){--i||o.resolveWith(a,[a])};"string"!=typeof e&&(n=e,e=t),e=e||"fx";while(s--)r=x._data(a[s],e+"queueHooks"),r&&r.empty&&(i++,r.empty.add(l));return l(),o.promise(n)}});var z,X,U=/[\t\r\n\f]/g,V=/\r/g,Y=/^(?:input|select|textarea|button|object)$/i,J=/^(?:a|area)$/i,G=/^(?:checked|selected)$/i,Q=x.support.getSetAttribute,K=x.support.input;x.fn.extend({attr:function(e,t){return x.access(this,x.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){x.removeAttr(this,e)})},prop:function(e,t){return x.access(this,x.prop,e,t,arguments.length>1)},removeProp:function(e){return e=x.propFix[e]||e,this.each(function(){try{this[e]=t,delete this[e]}catch(n){}})},addClass:function(e){var t,n,r,i,o,a=0,s=this.length,l="string"==typeof e&&e;if(x.isFunction(e))return this.each(function(t){x(this).addClass(e.call(this,t,this.className))});if(l)for(t=(e||"").match(T)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(U," "):" ")){o=0;while(i=t[o++])0>r.indexOf(" "+i+" ")&&(r+=i+" ");n.className=x.trim(r)}return this},removeClass:function(e){var t,n,r,i,o,a=0,s=this.length,l=0===arguments.length||"string"==typeof e&&e;if(x.isFunction(e))return this.each(function(t){x(this).removeClass(e.call(this,t,this.className))});if(l)for(t=(e||"").match(T)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(U," "):"")){o=0;while(i=t[o++])while(r.indexOf(" "+i+" ")>=0)r=r.replace(" "+i+" "," ");n.className=e?x.trim(r):""}return this},toggleClass:function(e,t){var n=typeof e;return"boolean"==typeof t&&"string"===n?t?this.addClass(e):this.removeClass(e):x.isFunction(e)?this.each(function(n){x(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if("string"===n){var t,r=0,o=x(this),a=e.match(T)||[];while(t=a[r++])o.hasClass(t)?o.removeClass(t):o.addClass(t)}else(n===i||"boolean"===n)&&(this.className&&x._data(this,"__className__",this.className),this.className=this.className||e===!1?"":x._data(this,"__className__")||"")})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;r>n;n++)if(1===this[n].nodeType&&(" "+this[n].className+" ").replace(U," ").indexOf(t)>=0)return!0;return!1},val:function(e){var n,r,i,o=this[0];{if(arguments.length)return i=x.isFunction(e),this.each(function(n){var o;1===this.nodeType&&(o=i?e.call(this,n,x(this).val()):e,null==o?o="":"number"==typeof o?o+="":x.isArray(o)&&(o=x.map(o,function(e){return null==e?"":e+""})),r=x.valHooks[this.type]||x.valHooks[this.nodeName.toLowerCase()],r&&"set"in r&&r.set(this,o,"value")!==t||(this.value=o))});if(o)return r=x.valHooks[o.type]||x.valHooks[o.nodeName.toLowerCase()],r&&"get"in r&&(n=r.get(o,"value"))!==t?n:(n=o.value,"string"==typeof n?n.replace(V,""):null==n?"":n)}}}),x.extend({valHooks:{option:{get:function(e){var t=x.find.attr(e,"value");return null!=t?t:e.text}},select:{get:function(e){var t,n,r=e.options,i=e.selectedIndex,o="select-one"===e.type||0>i,a=o?null:[],s=o?i+1:r.length,l=0>i?s:o?i:0;for(;s>l;l++)if(n=r[l],!(!n.selected&&l!==i||(x.support.optDisabled?n.disabled:null!==n.getAttribute("disabled"))||n.parentNode.disabled&&x.nodeName(n.parentNode,"optgroup"))){if(t=x(n).val(),o)return t;a.push(t)}return a},set:function(e,t){var n,r,i=e.options,o=x.makeArray(t),a=i.length;while(a--)r=i[a],(r.selected=x.inArray(x(r).val(),o)>=0)&&(n=!0);return n||(e.selectedIndex=-1),o}}},attr:function(e,n,r){var o,a,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return typeof e.getAttribute===i?x.prop(e,n,r):(1===s&&x.isXMLDoc(e)||(n=n.toLowerCase(),o=x.attrHooks[n]||(x.expr.match.bool.test(n)?X:z)),r===t?o&&"get"in o&&null!==(a=o.get(e,n))?a:(a=x.find.attr(e,n),null==a?t:a):null!==r?o&&"set"in o&&(a=o.set(e,r,n))!==t?a:(e.setAttribute(n,r+""),r):(x.removeAttr(e,n),t))},removeAttr:function(e,t){var n,r,i=0,o=t&&t.match(T);if(o&&1===e.nodeType)while(n=o[i++])r=x.propFix[n]||n,x.expr.match.bool.test(n)?K&&Q||!G.test(n)?e[r]=!1:e[x.camelCase("default-"+n)]=e[r]=!1:x.attr(e,n,""),e.removeAttribute(Q?n:r)},attrHooks:{type:{set:function(e,t){if(!x.support.radioValue&&"radio"===t&&x.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}},propFix:{"for":"htmlFor","class":"className"},prop:function(e,n,r){var i,o,a,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return a=1!==s||!x.isXMLDoc(e),a&&(n=x.propFix[n]||n,o=x.propHooks[n]),r!==t?o&&"set"in o&&(i=o.set(e,r,n))!==t?i:e[n]=r:o&&"get"in o&&null!==(i=o.get(e,n))?i:e[n]},propHooks:{tabIndex:{get:function(e){var t=x.find.attr(e,"tabindex");return t?parseInt(t,10):Y.test(e.nodeName)||J.test(e.nodeName)&&e.href?0:-1}}}}),X={set:function(e,t,n){return t===!1?x.removeAttr(e,n):K&&Q||!G.test(n)?e.setAttribute(!Q&&x.propFix[n]||n,n):e[x.camelCase("default-"+n)]=e[n]=!0,n}},x.each(x.expr.match.bool.source.match(/\w+/g),function(e,n){var r=x.expr.attrHandle[n]||x.find.attr;x.expr.attrHandle[n]=K&&Q||!G.test(n)?function(e,n,i){var o=x.expr.attrHandle[n],a=i?t:(x.expr.attrHandle[n]=t)!=r(e,n,i)?n.toLowerCase():null;return x.expr.attrHandle[n]=o,a}:function(e,n,r){return r?t:e[x.camelCase("default-"+n)]?n.toLowerCase():null}}),K&&Q||(x.attrHooks.value={set:function(e,n,r){return x.nodeName(e,"input")?(e.defaultValue=n,t):z&&z.set(e,n,r)}}),Q||(z={set:function(e,n,r){var i=e.getAttributeNode(r);return i||e.setAttributeNode(i=e.ownerDocument.createAttribute(r)),i.value=n+="","value"===r||n===e.getAttribute(r)?n:t}},x.expr.attrHandle.id=x.expr.attrHandle.name=x.expr.attrHandle.coords=function(e,n,r){var i;return r?t:(i=e.getAttributeNode(n))&&""!==i.value?i.value:null},x.valHooks.button={get:function(e,n){var r=e.getAttributeNode(n);return r&&r.specified?r.value:t},set:z.set},x.attrHooks.contenteditable={set:function(e,t,n){z.set(e,""===t?!1:t,n)}},x.each(["width","height"],function(e,n){x.attrHooks[n]={set:function(e,r){return""===r?(e.setAttribute(n,"auto"),r):t}}})),x.support.hrefNormalized||x.each(["href","src"],function(e,t){x.propHooks[t]={get:function(e){return e.getAttribute(t,4)}}}),x.support.style||(x.attrHooks.style={get:function(e){return e.style.cssText||t},set:function(e,t){return e.style.cssText=t+""}}),x.support.optSelected||(x.propHooks.selected={get:function(e){var t=e.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null}}),x.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){x.propFix[this.toLowerCase()]=this}),x.support.enctype||(x.propFix.enctype="encoding"),x.each(["radio","checkbox"],function(){x.valHooks[this]={set:function(e,n){return x.isArray(n)?e.checked=x.inArray(x(e).val(),n)>=0:t}},x.support.checkOn||(x.valHooks[this].get=function(e){return null===e.getAttribute("value")?"on":e.value})});var Z=/^(?:input|select|textarea)$/i,et=/^key/,tt=/^(?:mouse|contextmenu)|click/,nt=/^(?:focusinfocus|focusoutblur)$/,rt=/^([^.]*)(?:\.(.+)|)$/;function it(){return!0}function ot(){return!1}function at(){try{return a.activeElement}catch(e){}}x.event={global:{},add:function(e,n,r,o,a){var s,l,u,c,p,f,d,h,g,m,y,v=x._data(e);if(v){r.handler&&(c=r,r=c.handler,a=c.selector),r.guid||(r.guid=x.guid++),(l=v.events)||(l=v.events={}),(f=v.handle)||(f=v.handle=function(e){return typeof x===i||e&&x.event.triggered===e.type?t:x.event.dispatch.apply(f.elem,arguments)},f.elem=e),n=(n||"").match(T)||[""],u=n.length;while(u--)s=rt.exec(n[u])||[],g=y=s[1],m=(s[2]||"").split(".").sort(),g&&(p=x.event.special[g]||{},g=(a?p.delegateType:p.bindType)||g,p=x.event.special[g]||{},d=x.extend({type:g,origType:y,data:o,handler:r,guid:r.guid,selector:a,needsContext:a&&x.expr.match.needsContext.test(a),namespace:m.join(".")},c),(h=l[g])||(h=l[g]=[],h.delegateCount=0,p.setup&&p.setup.call(e,o,m,f)!==!1||(e.addEventListener?e.addEventListener(g,f,!1):e.attachEvent&&e.attachEvent("on"+g,f))),p.add&&(p.add.call(e,d),d.handler.guid||(d.handler.guid=r.guid)),a?h.splice(h.delegateCount++,0,d):h.push(d),x.event.global[g]=!0);e=null}},remove:function(e,t,n,r,i){var o,a,s,l,u,c,p,f,d,h,g,m=x.hasData(e)&&x._data(e);if(m&&(c=m.events)){t=(t||"").match(T)||[""],u=t.length;while(u--)if(s=rt.exec(t[u])||[],d=g=s[1],h=(s[2]||"").split(".").sort(),d){p=x.event.special[d]||{},d=(r?p.delegateType:p.bindType)||d,f=c[d]||[],s=s[2]&&RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),l=o=f.length;while(o--)a=f[o],!i&&g!==a.origType||n&&n.guid!==a.guid||s&&!s.test(a.namespace)||r&&r!==a.selector&&("**"!==r||!a.selector)||(f.splice(o,1),a.selector&&f.delegateCount--,p.remove&&p.remove.call(e,a));l&&!f.length&&(p.teardown&&p.teardown.call(e,h,m.handle)!==!1||x.removeEvent(e,d,m.handle),delete c[d])}else for(d in c)x.event.remove(e,d+t[u],n,r,!0);x.isEmptyObject(c)&&(delete m.handle,x._removeData(e,"events"))}},trigger:function(n,r,i,o){var s,l,u,c,p,f,d,h=[i||a],g=v.call(n,"type")?n.type:n,m=v.call(n,"namespace")?n.namespace.split("."):[];if(u=f=i=i||a,3!==i.nodeType&&8!==i.nodeType&&!nt.test(g+x.event.triggered)&&(g.indexOf(".")>=0&&(m=g.split("."),g=m.shift(),m.sort()),l=0>g.indexOf(":")&&"on"+g,n=n[x.expando]?n:new x.Event(g,"object"==typeof n&&n),n.isTrigger=o?2:3,n.namespace=m.join("."),n.namespace_re=n.namespace?RegExp("(^|\\.)"+m.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,n.result=t,n.target||(n.target=i),r=null==r?[n]:x.makeArray(r,[n]),p=x.event.special[g]||{},o||!p.trigger||p.trigger.apply(i,r)!==!1)){if(!o&&!p.noBubble&&!x.isWindow(i)){for(c=p.delegateType||g,nt.test(c+g)||(u=u.parentNode);u;u=u.parentNode)h.push(u),f=u;f===(i.ownerDocument||a)&&h.push(f.defaultView||f.parentWindow||e)}d=0;while((u=h[d++])&&!n.isPropagationStopped())n.type=d>1?c:p.bindType||g,s=(x._data(u,"events")||{})[n.type]&&x._data(u,"handle"),s&&s.apply(u,r),s=l&&u[l],s&&x.acceptData(u)&&s.apply&&s.apply(u,r)===!1&&n.preventDefault();if(n.type=g,!o&&!n.isDefaultPrevented()&&(!p._default||p._default.apply(h.pop(),r)===!1)&&x.acceptData(i)&&l&&i[g]&&!x.isWindow(i)){f=i[l],f&&(i[l]=null),x.event.triggered=g;try{i[g]()}catch(y){}x.event.triggered=t,f&&(i[l]=f)}return n.result}},dispatch:function(e){e=x.event.fix(e);var n,r,i,o,a,s=[],l=g.call(arguments),u=(x._data(this,"events")||{})[e.type]||[],c=x.event.special[e.type]||{};if(l[0]=e,e.delegateTarget=this,!c.preDispatch||c.preDispatch.call(this,e)!==!1){s=x.event.handlers.call(this,e,u),n=0;while((o=s[n++])&&!e.isPropagationStopped()){e.currentTarget=o.elem,a=0;while((i=o.handlers[a++])&&!e.isImmediatePropagationStopped())(!e.namespace_re||e.namespace_re.test(i.namespace))&&(e.handleObj=i,e.data=i.data,r=((x.event.special[i.origType]||{}).handle||i.handler).apply(o.elem,l),r!==t&&(e.result=r)===!1&&(e.preventDefault(),e.stopPropagation()))}return c.postDispatch&&c.postDispatch.call(this,e),e.result}},handlers:function(e,n){var r,i,o,a,s=[],l=n.delegateCount,u=e.target;if(l&&u.nodeType&&(!e.button||"click"!==e.type))for(;u!=this;u=u.parentNode||this)if(1===u.nodeType&&(u.disabled!==!0||"click"!==e.type)){for(o=[],a=0;l>a;a++)i=n[a],r=i.selector+" ",o[r]===t&&(o[r]=i.needsContext?x(r,this).index(u)>=0:x.find(r,this,null,[u]).length),o[r]&&o.push(i);o.length&&s.push({elem:u,handlers:o})}return n.length>l&&s.push({elem:this,handlers:n.slice(l)}),s},fix:function(e){if(e[x.expando])return e;var t,n,r,i=e.type,o=e,s=this.fixHooks[i];s||(this.fixHooks[i]=s=tt.test(i)?this.mouseHooks:et.test(i)?this.keyHooks:{}),r=s.props?this.props.concat(s.props):this.props,e=new x.Event(o),t=r.length;while(t--)n=r[t],e[n]=o[n];return e.target||(e.target=o.srcElement||a),3===e.target.nodeType&&(e.target=e.target.parentNode),e.metaKey=!!e.metaKey,s.filter?s.filter(e,o):e},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(e,t){return null==e.which&&(e.which=null!=t.charCode?t.charCode:t.keyCode),e}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,n){var r,i,o,s=n.button,l=n.fromElement;return null==e.pageX&&null!=n.clientX&&(i=e.target.ownerDocument||a,o=i.documentElement,r=i.body,e.pageX=n.clientX+(o&&o.scrollLeft||r&&r.scrollLeft||0)-(o&&o.clientLeft||r&&r.clientLeft||0),e.pageY=n.clientY+(o&&o.scrollTop||r&&r.scrollTop||0)-(o&&o.clientTop||r&&r.clientTop||0)),!e.relatedTarget&&l&&(e.relatedTarget=l===e.target?n.toElement:l),e.which||s===t||(e.which=1&s?1:2&s?3:4&s?2:0),e}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==at()&&this.focus)try{return this.focus(),!1}catch(e){}},delegateType:"focusin"},blur:{trigger:function(){return this===at()&&this.blur?(this.blur(),!1):t},delegateType:"focusout"},click:{trigger:function(){return x.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):t},_default:function(e){return x.nodeName(e.target,"a")}},beforeunload:{postDispatch:function(e){e.result!==t&&(e.originalEvent.returnValue=e.result)}}},simulate:function(e,t,n,r){var i=x.extend(new x.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?x.event.trigger(i,null,t):x.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},x.removeEvent=a.removeEventListener?function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n,!1)}:function(e,t,n){var r="on"+t;e.detachEvent&&(typeof e[r]===i&&(e[r]=null),e.detachEvent(r,n))},x.Event=function(e,n){return this instanceof x.Event?(e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||e.returnValue===!1||e.getPreventDefault&&e.getPreventDefault()?it:ot):this.type=e,n&&x.extend(this,n),this.timeStamp=e&&e.timeStamp||x.now(),this[x.expando]=!0,t):new x.Event(e,n)},x.Event.prototype={isDefaultPrevented:ot,isPropagationStopped:ot,isImmediatePropagationStopped:ot,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=it,e&&(e.preventDefault?e.preventDefault():e.returnValue=!1)},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=it,e&&(e.stopPropagation&&e.stopPropagation(),e.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=it,this.stopPropagation()}},x.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(e,t){x.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,o=e.handleObj;return(!i||i!==r&&!x.contains(r,i))&&(e.type=o.origType,n=o.handler.apply(this,arguments),e.type=t),n}}}),x.support.submitBubbles||(x.event.special.submit={setup:function(){return x.nodeName(this,"form")?!1:(x.event.add(this,"click._submit keypress._submit",function(e){var n=e.target,r=x.nodeName(n,"input")||x.nodeName(n,"button")?n.form:t;r&&!x._data(r,"submitBubbles")&&(x.event.add(r,"submit._submit",function(e){e._submit_bubble=!0}),x._data(r,"submitBubbles",!0))}),t)},postDispatch:function(e){e._submit_bubble&&(delete e._submit_bubble,this.parentNode&&!e.isTrigger&&x.event.simulate("submit",this.parentNode,e,!0))},teardown:function(){return x.nodeName(this,"form")?!1:(x.event.remove(this,"._submit"),t)}}),x.support.changeBubbles||(x.event.special.change={setup:function(){return Z.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(x.event.add(this,"propertychange._change",function(e){"checked"===e.originalEvent.propertyName&&(this._just_changed=!0)}),x.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1),x.event.simulate("change",this,e,!0)})),!1):(x.event.add(this,"beforeactivate._change",function(e){var t=e.target;Z.test(t.nodeName)&&!x._data(t,"changeBubbles")&&(x.event.add(t,"change._change",function(e){!this.parentNode||e.isSimulated||e.isTrigger||x.event.simulate("change",this.parentNode,e,!0)}),x._data(t,"changeBubbles",!0))}),t)},handle:function(e){var n=e.target;return this!==n||e.isSimulated||e.isTrigger||"radio"!==n.type&&"checkbox"!==n.type?e.handleObj.handler.apply(this,arguments):t},teardown:function(){return x.event.remove(this,"._change"),!Z.test(this.nodeName)}}),x.support.focusinBubbles||x.each({focus:"focusin",blur:"focusout"},function(e,t){var n=0,r=function(e){x.event.simulate(t,e.target,x.event.fix(e),!0)};x.event.special[t]={setup:function(){0===n++&&a.addEventListener(e,r,!0)},teardown:function(){0===--n&&a.removeEventListener(e,r,!0)}}}),x.fn.extend({on:function(e,n,r,i,o){var a,s;if("object"==typeof e){"string"!=typeof n&&(r=r||n,n=t);for(a in e)this.on(a,n,r,e[a],o);return this}if(null==r&&null==i?(i=n,r=n=t):null==i&&("string"==typeof n?(i=r,r=t):(i=r,r=n,n=t)),i===!1)i=ot;else if(!i)return this;return 1===o&&(s=i,i=function(e){return x().off(e),s.apply(this,arguments)},i.guid=s.guid||(s.guid=x.guid++)),this.each(function(){x.event.add(this,e,i,r,n)})},one:function(e,t,n,r){return this.on(e,t,n,r,1)},off:function(e,n,r){var i,o;if(e&&e.preventDefault&&e.handleObj)return i=e.handleObj,x(e.delegateTarget).off(i.namespace?i.origType+"."+i.namespace:i.origType,i.selector,i.handler),this;if("object"==typeof e){for(o in e)this.off(o,n,e[o]);return this}return(n===!1||"function"==typeof n)&&(r=n,n=t),r===!1&&(r=ot),this.each(function(){x.event.remove(this,e,r,n)})},trigger:function(e,t){return this.each(function(){x.event.trigger(e,t,this)})},triggerHandler:function(e,n){var r=this[0];return r?x.event.trigger(e,n,r,!0):t}});var st=/^.[^:#\[\.,]*$/,lt=/^(?:parents|prev(?:Until|All))/,ut=x.expr.match.needsContext,ct={children:!0,contents:!0,next:!0,prev:!0};x.fn.extend({find:function(e){var t,n=[],r=this,i=r.length;if("string"!=typeof e)return this.pushStack(x(e).filter(function(){for(t=0;i>t;t++)if(x.contains(r[t],this))return!0}));for(t=0;i>t;t++)x.find(e,r[t],n);return n=this.pushStack(i>1?x.unique(n):n),n.selector=this.selector?this.selector+" "+e:e,n},has:function(e){var t,n=x(e,this),r=n.length;return this.filter(function(){for(t=0;r>t;t++)if(x.contains(this,n[t]))return!0})},not:function(e){return this.pushStack(ft(this,e||[],!0))},filter:function(e){return this.pushStack(ft(this,e||[],!1))},is:function(e){return!!ft(this,"string"==typeof e&&ut.test(e)?x(e):e||[],!1).length},closest:function(e,t){var n,r=0,i=this.length,o=[],a=ut.test(e)||"string"!=typeof e?x(e,t||this.context):0;for(;i>r;r++)for(n=this[r];n&&n!==t;n=n.parentNode)if(11>n.nodeType&&(a?a.index(n)>-1:1===n.nodeType&&x.find.matchesSelector(n,e))){n=o.push(n);break}return this.pushStack(o.length>1?x.unique(o):o)},index:function(e){return e?"string"==typeof e?x.inArray(this[0],x(e)):x.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){var n="string"==typeof e?x(e,t):x.makeArray(e&&e.nodeType?[e]:e),r=x.merge(this.get(),n);return this.pushStack(x.unique(r))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}});function pt(e,t){do e=e[t];while(e&&1!==e.nodeType);return e}x.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return x.dir(e,"parentNode")},parentsUntil:function(e,t,n){return x.dir(e,"parentNode",n)},next:function(e){return pt(e,"nextSibling")},prev:function(e){return pt(e,"previousSibling")},nextAll:function(e){return x.dir(e,"nextSibling")},prevAll:function(e){return x.dir(e,"previousSibling")},nextUntil:function(e,t,n){return x.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return x.dir(e,"previousSibling",n)},siblings:function(e){return x.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return x.sibling(e.firstChild)},contents:function(e){return x.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:x.merge([],e.childNodes)}},function(e,t){x.fn[e]=function(n,r){var i=x.map(this,t,n);return"Until"!==e.slice(-5)&&(r=n),r&&"string"==typeof r&&(i=x.filter(r,i)),this.length>1&&(ct[e]||(i=x.unique(i)),lt.test(e)&&(i=i.reverse())),this.pushStack(i)}}),x.extend({filter:function(e,t,n){var r=t[0];return n&&(e=":not("+e+")"),1===t.length&&1===r.nodeType?x.find.matchesSelector(r,e)?[r]:[]:x.find.matches(e,x.grep(t,function(e){return 1===e.nodeType}))},dir:function(e,n,r){var i=[],o=e[n];while(o&&9!==o.nodeType&&(r===t||1!==o.nodeType||!x(o).is(r)))1===o.nodeType&&i.push(o),o=o[n];return i},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n}});function ft(e,t,n){if(x.isFunction(t))return x.grep(e,function(e,r){return!!t.call(e,r,e)!==n});if(t.nodeType)return x.grep(e,function(e){return e===t!==n});if("string"==typeof t){if(st.test(t))return x.filter(t,e,n);t=x.filter(t,e)}return x.grep(e,function(e){return x.inArray(e,t)>=0!==n})}function dt(e){var t=ht.split("|"),n=e.createDocumentFragment();if(n.createElement)while(t.length)n.createElement(t.pop());return n}var ht="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",gt=/ jQuery\d+="(?:null|\d+)"/g,mt=RegExp("<(?:"+ht+")[\\s/>]","i"),yt=/^\s+/,vt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,bt=/<([\w:]+)/,xt=/<tbody/i,wt=/<|&#?\w+;/,Tt=/<(?:script|style|link)/i,Ct=/^(?:checkbox|radio)$/i,Nt=/checked\s*(?:[^=]|=\s*.checked.)/i,kt=/^$|\/(?:java|ecma)script/i,Et=/^true\/(.*)/,St=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,At={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:x.support.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},jt=dt(a),Dt=jt.appendChild(a.createElement("div"));At.optgroup=At.option,At.tbody=At.tfoot=At.colgroup=At.caption=At.thead,At.th=At.td,x.fn.extend({text:function(e){return x.access(this,function(e){return e===t?x.text(this):this.empty().append((this[0]&&this[0].ownerDocument||a).createTextNode(e))},null,e,arguments.length)},append:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=Lt(this,e);t.appendChild(e)}})},prepend:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=Lt(this,e);t.insertBefore(e,t.firstChild)}})},before:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},remove:function(e,t){var n,r=e?x.filter(e,this):this,i=0;for(;null!=(n=r[i]);i++)t||1!==n.nodeType||x.cleanData(Ft(n)),n.parentNode&&(t&&x.contains(n.ownerDocument,n)&&_t(Ft(n,"script")),n.parentNode.removeChild(n));return this},empty:function(){var e,t=0;for(;null!=(e=this[t]);t++){1===e.nodeType&&x.cleanData(Ft(e,!1));while(e.firstChild)e.removeChild(e.firstChild);e.options&&x.nodeName(e,"select")&&(e.options.length=0)}return this},clone:function(e,t){return e=null==e?!1:e,t=null==t?e:t,this.map(function(){return x.clone(this,e,t)})},html:function(e){return x.access(this,function(e){var n=this[0]||{},r=0,i=this.length;if(e===t)return 1===n.nodeType?n.innerHTML.replace(gt,""):t;if(!("string"!=typeof e||Tt.test(e)||!x.support.htmlSerialize&&mt.test(e)||!x.support.leadingWhitespace&&yt.test(e)||At[(bt.exec(e)||["",""])[1].toLowerCase()])){e=e.replace(vt,"<$1></$2>");try{for(;i>r;r++)n=this[r]||{},1===n.nodeType&&(x.cleanData(Ft(n,!1)),n.innerHTML=e);n=0}catch(o){}}n&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(){var e=x.map(this,function(e){return[e.nextSibling,e.parentNode]}),t=0;return this.domManip(arguments,function(n){var r=e[t++],i=e[t++];i&&(r&&r.parentNode!==i&&(r=this.nextSibling),x(this).remove(),i.insertBefore(n,r))},!0),t?this:this.remove()},detach:function(e){return this.remove(e,!0)},domManip:function(e,t,n){e=d.apply([],e);var r,i,o,a,s,l,u=0,c=this.length,p=this,f=c-1,h=e[0],g=x.isFunction(h);if(g||!(1>=c||"string"!=typeof h||x.support.checkClone)&&Nt.test(h))return this.each(function(r){var i=p.eq(r);g&&(e[0]=h.call(this,r,i.html())),i.domManip(e,t,n)});if(c&&(l=x.buildFragment(e,this[0].ownerDocument,!1,!n&&this),r=l.firstChild,1===l.childNodes.length&&(l=r),r)){for(a=x.map(Ft(l,"script"),Ht),o=a.length;c>u;u++)i=l,u!==f&&(i=x.clone(i,!0,!0),o&&x.merge(a,Ft(i,"script"))),t.call(this[u],i,u);if(o)for(s=a[a.length-1].ownerDocument,x.map(a,qt),u=0;o>u;u++)i=a[u],kt.test(i.type||"")&&!x._data(i,"globalEval")&&x.contains(s,i)&&(i.src?x._evalUrl(i.src):x.globalEval((i.text||i.textContent||i.innerHTML||"").replace(St,"")));l=r=null}return this}});function Lt(e,t){return x.nodeName(e,"table")&&x.nodeName(1===t.nodeType?t:t.firstChild,"tr")?e.getElementsByTagName("tbody")[0]||e.appendChild(e.ownerDocument.createElement("tbody")):e}function Ht(e){return e.type=(null!==x.find.attr(e,"type"))+"/"+e.type,e}function qt(e){var t=Et.exec(e.type);return t?e.type=t[1]:e.removeAttribute("type"),e}function _t(e,t){var n,r=0;for(;null!=(n=e[r]);r++)x._data(n,"globalEval",!t||x._data(t[r],"globalEval"))}function Mt(e,t){if(1===t.nodeType&&x.hasData(e)){var n,r,i,o=x._data(e),a=x._data(t,o),s=o.events;if(s){delete a.handle,a.events={};for(n in s)for(r=0,i=s[n].length;i>r;r++)x.event.add(t,n,s[n][r])}a.data&&(a.data=x.extend({},a.data))}}function Ot(e,t){var n,r,i;if(1===t.nodeType){if(n=t.nodeName.toLowerCase(),!x.support.noCloneEvent&&t[x.expando]){i=x._data(t);for(r in i.events)x.removeEvent(t,r,i.handle);t.removeAttribute(x.expando)}"script"===n&&t.text!==e.text?(Ht(t).text=e.text,qt(t)):"object"===n?(t.parentNode&&(t.outerHTML=e.outerHTML),x.support.html5Clone&&e.innerHTML&&!x.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):"input"===n&&Ct.test(e.type)?(t.defaultChecked=t.checked=e.checked,t.value!==e.value&&(t.value=e.value)):"option"===n?t.defaultSelected=t.selected=e.defaultSelected:("input"===n||"textarea"===n)&&(t.defaultValue=e.defaultValue)}}x.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){x.fn[e]=function(e){var n,r=0,i=[],o=x(e),a=o.length-1;for(;a>=r;r++)n=r===a?this:this.clone(!0),x(o[r])[t](n),h.apply(i,n.get());return this.pushStack(i)}});function Ft(e,n){var r,o,a=0,s=typeof e.getElementsByTagName!==i?e.getElementsByTagName(n||"*"):typeof e.querySelectorAll!==i?e.querySelectorAll(n||"*"):t;if(!s)for(s=[],r=e.childNodes||e;null!=(o=r[a]);a++)!n||x.nodeName(o,n)?s.push(o):x.merge(s,Ft(o,n));return n===t||n&&x.nodeName(e,n)?x.merge([e],s):s}function Bt(e){Ct.test(e.type)&&(e.defaultChecked=e.checked)}x.extend({clone:function(e,t,n){var r,i,o,a,s,l=x.contains(e.ownerDocument,e);if(x.support.html5Clone||x.isXMLDoc(e)||!mt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(Dt.innerHTML=e.outerHTML,Dt.removeChild(o=Dt.firstChild)),!(x.support.noCloneEvent&&x.support.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||x.isXMLDoc(e)))for(r=Ft(o),s=Ft(e),a=0;null!=(i=s[a]);++a)r[a]&&Ot(i,r[a]);if(t)if(n)for(s=s||Ft(e),r=r||Ft(o),a=0;null!=(i=s[a]);a++)Mt(i,r[a]);else Mt(e,o);return r=Ft(o,"script"),r.length>0&&_t(r,!l&&Ft(e,"script")),r=s=i=null,o},buildFragment:function(e,t,n,r){var i,o,a,s,l,u,c,p=e.length,f=dt(t),d=[],h=0;for(;p>h;h++)if(o=e[h],o||0===o)if("object"===x.type(o))x.merge(d,o.nodeType?[o]:o);else if(wt.test(o)){s=s||f.appendChild(t.createElement("div")),l=(bt.exec(o)||["",""])[1].toLowerCase(),c=At[l]||At._default,s.innerHTML=c[1]+o.replace(vt,"<$1></$2>")+c[2],i=c[0];while(i--)s=s.lastChild;if(!x.support.leadingWhitespace&&yt.test(o)&&d.push(t.createTextNode(yt.exec(o)[0])),!x.support.tbody){o="table"!==l||xt.test(o)?"<table>"!==c[1]||xt.test(o)?0:s:s.firstChild,i=o&&o.childNodes.length;while(i--)x.nodeName(u=o.childNodes[i],"tbody")&&!u.childNodes.length&&o.removeChild(u)}x.merge(d,s.childNodes),s.textContent="";while(s.firstChild)s.removeChild(s.firstChild);s=f.lastChild}else d.push(t.createTextNode(o));s&&f.removeChild(s),x.support.appendChecked||x.grep(Ft(d,"input"),Bt),h=0;while(o=d[h++])if((!r||-1===x.inArray(o,r))&&(a=x.contains(o.ownerDocument,o),s=Ft(f.appendChild(o),"script"),a&&_t(s),n)){i=0;while(o=s[i++])kt.test(o.type||"")&&n.push(o)}return s=null,f},cleanData:function(e,t){var n,r,o,a,s=0,l=x.expando,u=x.cache,c=x.support.deleteExpando,f=x.event.special;for(;null!=(n=e[s]);s++)if((t||x.acceptData(n))&&(o=n[l],a=o&&u[o])){if(a.events)for(r in a.events)f[r]?x.event.remove(n,r):x.removeEvent(n,r,a.handle); u[o]&&(delete u[o],c?delete n[l]:typeof n.removeAttribute!==i?n.removeAttribute(l):n[l]=null,p.push(o))}},_evalUrl:function(e){return x.ajax({url:e,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})}}),x.fn.extend({wrapAll:function(e){if(x.isFunction(e))return this.each(function(t){x(this).wrapAll(e.call(this,t))});if(this[0]){var t=x(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstChild&&1===e.firstChild.nodeType)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return x.isFunction(e)?this.each(function(t){x(this).wrapInner(e.call(this,t))}):this.each(function(){var t=x(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=x.isFunction(e);return this.each(function(n){x(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){x.nodeName(this,"body")||x(this).replaceWith(this.childNodes)}).end()}});var Pt,Rt,Wt,$t=/alpha\([^)]*\)/i,It=/opacity\s*=\s*([^)]*)/,zt=/^(top|right|bottom|left)$/,Xt=/^(none|table(?!-c[ea]).+)/,Ut=/^margin/,Vt=RegExp("^("+w+")(.*)$","i"),Yt=RegExp("^("+w+")(?!px)[a-z%]+$","i"),Jt=RegExp("^([+-])=("+w+")","i"),Gt={BODY:"block"},Qt={position:"absolute",visibility:"hidden",display:"block"},Kt={letterSpacing:0,fontWeight:400},Zt=["Top","Right","Bottom","Left"],en=["Webkit","O","Moz","ms"];function tn(e,t){if(t in e)return t;var n=t.charAt(0).toUpperCase()+t.slice(1),r=t,i=en.length;while(i--)if(t=en[i]+n,t in e)return t;return r}function nn(e,t){return e=t||e,"none"===x.css(e,"display")||!x.contains(e.ownerDocument,e)}function rn(e,t){var n,r,i,o=[],a=0,s=e.length;for(;s>a;a++)r=e[a],r.style&&(o[a]=x._data(r,"olddisplay"),n=r.style.display,t?(o[a]||"none"!==n||(r.style.display=""),""===r.style.display&&nn(r)&&(o[a]=x._data(r,"olddisplay",ln(r.nodeName)))):o[a]||(i=nn(r),(n&&"none"!==n||!i)&&x._data(r,"olddisplay",i?n:x.css(r,"display"))));for(a=0;s>a;a++)r=e[a],r.style&&(t&&"none"!==r.style.display&&""!==r.style.display||(r.style.display=t?o[a]||"":"none"));return e}x.fn.extend({css:function(e,n){return x.access(this,function(e,n,r){var i,o,a={},s=0;if(x.isArray(n)){for(o=Rt(e),i=n.length;i>s;s++)a[n[s]]=x.css(e,n[s],!1,o);return a}return r!==t?x.style(e,n,r):x.css(e,n)},e,n,arguments.length>1)},show:function(){return rn(this,!0)},hide:function(){return rn(this)},toggle:function(e){return"boolean"==typeof e?e?this.show():this.hide():this.each(function(){nn(this)?x(this).show():x(this).hide()})}}),x.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Wt(e,"opacity");return""===n?"1":n}}}},cssNumber:{columnCount:!0,fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":x.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,r,i){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var o,a,s,l=x.camelCase(n),u=e.style;if(n=x.cssProps[l]||(x.cssProps[l]=tn(u,l)),s=x.cssHooks[n]||x.cssHooks[l],r===t)return s&&"get"in s&&(o=s.get(e,!1,i))!==t?o:u[n];if(a=typeof r,"string"===a&&(o=Jt.exec(r))&&(r=(o[1]+1)*o[2]+parseFloat(x.css(e,n)),a="number"),!(null==r||"number"===a&&isNaN(r)||("number"!==a||x.cssNumber[l]||(r+="px"),x.support.clearCloneStyle||""!==r||0!==n.indexOf("background")||(u[n]="inherit"),s&&"set"in s&&(r=s.set(e,r,i))===t)))try{u[n]=r}catch(c){}}},css:function(e,n,r,i){var o,a,s,l=x.camelCase(n);return n=x.cssProps[l]||(x.cssProps[l]=tn(e.style,l)),s=x.cssHooks[n]||x.cssHooks[l],s&&"get"in s&&(a=s.get(e,!0,r)),a===t&&(a=Wt(e,n,i)),"normal"===a&&n in Kt&&(a=Kt[n]),""===r||r?(o=parseFloat(a),r===!0||x.isNumeric(o)?o||0:a):a}}),e.getComputedStyle?(Rt=function(t){return e.getComputedStyle(t,null)},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),l=s?s.getPropertyValue(n)||s[n]:t,u=e.style;return s&&(""!==l||x.contains(e.ownerDocument,e)||(l=x.style(e,n)),Yt.test(l)&&Ut.test(n)&&(i=u.width,o=u.minWidth,a=u.maxWidth,u.minWidth=u.maxWidth=u.width=l,l=s.width,u.width=i,u.minWidth=o,u.maxWidth=a)),l}):a.documentElement.currentStyle&&(Rt=function(e){return e.currentStyle},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),l=s?s[n]:t,u=e.style;return null==l&&u&&u[n]&&(l=u[n]),Yt.test(l)&&!zt.test(n)&&(i=u.left,o=e.runtimeStyle,a=o&&o.left,a&&(o.left=e.currentStyle.left),u.left="fontSize"===n?"1em":l,l=u.pixelLeft+"px",u.left=i,a&&(o.left=a)),""===l?"auto":l});function on(e,t,n){var r=Vt.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function an(e,t,n,r,i){var o=n===(r?"border":"content")?4:"width"===t?1:0,a=0;for(;4>o;o+=2)"margin"===n&&(a+=x.css(e,n+Zt[o],!0,i)),r?("content"===n&&(a-=x.css(e,"padding"+Zt[o],!0,i)),"margin"!==n&&(a-=x.css(e,"border"+Zt[o]+"Width",!0,i))):(a+=x.css(e,"padding"+Zt[o],!0,i),"padding"!==n&&(a+=x.css(e,"border"+Zt[o]+"Width",!0,i)));return a}function sn(e,t,n){var r=!0,i="width"===t?e.offsetWidth:e.offsetHeight,o=Rt(e),a=x.support.boxSizing&&"border-box"===x.css(e,"boxSizing",!1,o);if(0>=i||null==i){if(i=Wt(e,t,o),(0>i||null==i)&&(i=e.style[t]),Yt.test(i))return i;r=a&&(x.support.boxSizingReliable||i===e.style[t]),i=parseFloat(i)||0}return i+an(e,t,n||(a?"border":"content"),r,o)+"px"}function ln(e){var t=a,n=Gt[e];return n||(n=un(e,t),"none"!==n&&n||(Pt=(Pt||x("<iframe frameborder='0' width='0' height='0'/>").css("cssText","display:block !important")).appendTo(t.documentElement),t=(Pt[0].contentWindow||Pt[0].contentDocument).document,t.write("<!doctype html><html><body>"),t.close(),n=un(e,t),Pt.detach()),Gt[e]=n),n}function un(e,t){var n=x(t.createElement(e)).appendTo(t.body),r=x.css(n[0],"display");return n.remove(),r}x.each(["height","width"],function(e,n){x.cssHooks[n]={get:function(e,r,i){return r?0===e.offsetWidth&&Xt.test(x.css(e,"display"))?x.swap(e,Qt,function(){return sn(e,n,i)}):sn(e,n,i):t},set:function(e,t,r){var i=r&&Rt(e);return on(e,t,r?an(e,n,r,x.support.boxSizing&&"border-box"===x.css(e,"boxSizing",!1,i),i):0)}}}),x.support.opacity||(x.cssHooks.opacity={get:function(e,t){return It.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":t?"1":""},set:function(e,t){var n=e.style,r=e.currentStyle,i=x.isNumeric(t)?"alpha(opacity="+100*t+")":"",o=r&&r.filter||n.filter||"";n.zoom=1,(t>=1||""===t)&&""===x.trim(o.replace($t,""))&&n.removeAttribute&&(n.removeAttribute("filter"),""===t||r&&!r.filter)||(n.filter=$t.test(o)?o.replace($t,i):o+" "+i)}}),x(function(){x.support.reliableMarginRight||(x.cssHooks.marginRight={get:function(e,n){return n?x.swap(e,{display:"inline-block"},Wt,[e,"marginRight"]):t}}),!x.support.pixelPosition&&x.fn.position&&x.each(["top","left"],function(e,n){x.cssHooks[n]={get:function(e,r){return r?(r=Wt(e,n),Yt.test(r)?x(e).position()[n]+"px":r):t}}})}),x.expr&&x.expr.filters&&(x.expr.filters.hidden=function(e){return 0>=e.offsetWidth&&0>=e.offsetHeight||!x.support.reliableHiddenOffsets&&"none"===(e.style&&e.style.display||x.css(e,"display"))},x.expr.filters.visible=function(e){return!x.expr.filters.hidden(e)}),x.each({margin:"",padding:"",border:"Width"},function(e,t){x.cssHooks[e+t]={expand:function(n){var r=0,i={},o="string"==typeof n?n.split(" "):[n];for(;4>r;r++)i[e+Zt[r]+t]=o[r]||o[r-2]||o[0];return i}},Ut.test(e)||(x.cssHooks[e+t].set=on)});var cn=/%20/g,pn=/\[\]$/,fn=/\r?\n/g,dn=/^(?:submit|button|image|reset|file)$/i,hn=/^(?:input|select|textarea|keygen)/i;x.fn.extend({serialize:function(){return x.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=x.prop(this,"elements");return e?x.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!x(this).is(":disabled")&&hn.test(this.nodeName)&&!dn.test(e)&&(this.checked||!Ct.test(e))}).map(function(e,t){var n=x(this).val();return null==n?null:x.isArray(n)?x.map(n,function(e){return{name:t.name,value:e.replace(fn,"\r\n")}}):{name:t.name,value:n.replace(fn,"\r\n")}}).get()}}),x.param=function(e,n){var r,i=[],o=function(e,t){t=x.isFunction(t)?t():null==t?"":t,i[i.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};if(n===t&&(n=x.ajaxSettings&&x.ajaxSettings.traditional),x.isArray(e)||e.jquery&&!x.isPlainObject(e))x.each(e,function(){o(this.name,this.value)});else for(r in e)gn(r,e[r],n,o);return i.join("&").replace(cn,"+")};function gn(e,t,n,r){var i;if(x.isArray(t))x.each(t,function(t,i){n||pn.test(e)?r(e,i):gn(e+"["+("object"==typeof i?t:"")+"]",i,n,r)});else if(n||"object"!==x.type(t))r(e,t);else for(i in t)gn(e+"["+i+"]",t[i],n,r)}x.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){x.fn[t]=function(e,n){return arguments.length>0?this.on(t,null,e,n):this.trigger(t)}}),x.fn.extend({hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)},bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)}});var mn,yn,vn=x.now(),bn=/\?/,xn=/#.*$/,wn=/([?&])_=[^&]*/,Tn=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Cn=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Nn=/^(?:GET|HEAD)$/,kn=/^\/\//,En=/^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,Sn=x.fn.load,An={},jn={},Dn="*/".concat("*");try{yn=o.href}catch(Ln){yn=a.createElement("a"),yn.href="",yn=yn.href}mn=En.exec(yn.toLowerCase())||[];function Hn(e){return function(t,n){"string"!=typeof t&&(n=t,t="*");var r,i=0,o=t.toLowerCase().match(T)||[];if(x.isFunction(n))while(r=o[i++])"+"===r[0]?(r=r.slice(1)||"*",(e[r]=e[r]||[]).unshift(n)):(e[r]=e[r]||[]).push(n)}}function qn(e,n,r,i){var o={},a=e===jn;function s(l){var u;return o[l]=!0,x.each(e[l]||[],function(e,l){var c=l(n,r,i);return"string"!=typeof c||a||o[c]?a?!(u=c):t:(n.dataTypes.unshift(c),s(c),!1)}),u}return s(n.dataTypes[0])||!o["*"]&&s("*")}function _n(e,n){var r,i,o=x.ajaxSettings.flatOptions||{};for(i in n)n[i]!==t&&((o[i]?e:r||(r={}))[i]=n[i]);return r&&x.extend(!0,e,r),e}x.fn.load=function(e,n,r){if("string"!=typeof e&&Sn)return Sn.apply(this,arguments);var i,o,a,s=this,l=e.indexOf(" ");return l>=0&&(i=e.slice(l,e.length),e=e.slice(0,l)),x.isFunction(n)?(r=n,n=t):n&&"object"==typeof n&&(a="POST"),s.length>0&&x.ajax({url:e,type:a,dataType:"html",data:n}).done(function(e){o=arguments,s.html(i?x("<div>").append(x.parseHTML(e)).find(i):e)}).complete(r&&function(e,t){s.each(r,o||[e.responseText,t,e])}),this},x.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){x.fn[t]=function(e){return this.on(t,e)}}),x.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:yn,type:"GET",isLocal:Cn.test(mn[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Dn,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":x.parseJSON,"text xml":x.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?_n(_n(e,x.ajaxSettings),t):_n(x.ajaxSettings,e)},ajaxPrefilter:Hn(An),ajaxTransport:Hn(jn),ajax:function(e,n){"object"==typeof e&&(n=e,e=t),n=n||{};var r,i,o,a,s,l,u,c,p=x.ajaxSetup({},n),f=p.context||p,d=p.context&&(f.nodeType||f.jquery)?x(f):x.event,h=x.Deferred(),g=x.Callbacks("once memory"),m=p.statusCode||{},y={},v={},b=0,w="canceled",C={readyState:0,getResponseHeader:function(e){var t;if(2===b){if(!c){c={};while(t=Tn.exec(a))c[t[1].toLowerCase()]=t[2]}t=c[e.toLowerCase()]}return null==t?null:t},getAllResponseHeaders:function(){return 2===b?a:null},setRequestHeader:function(e,t){var n=e.toLowerCase();return b||(e=v[n]=v[n]||e,y[e]=t),this},overrideMimeType:function(e){return b||(p.mimeType=e),this},statusCode:function(e){var t;if(e)if(2>b)for(t in e)m[t]=[m[t],e[t]];else C.always(e[C.status]);return this},abort:function(e){var t=e||w;return u&&u.abort(t),k(0,t),this}};if(h.promise(C).complete=g.add,C.success=C.done,C.error=C.fail,p.url=((e||p.url||yn)+"").replace(xn,"").replace(kn,mn[1]+"//"),p.type=n.method||n.type||p.method||p.type,p.dataTypes=x.trim(p.dataType||"*").toLowerCase().match(T)||[""],null==p.crossDomain&&(r=En.exec(p.url.toLowerCase()),p.crossDomain=!(!r||r[1]===mn[1]&&r[2]===mn[2]&&(r[3]||("http:"===r[1]?"80":"443"))===(mn[3]||("http:"===mn[1]?"80":"443")))),p.data&&p.processData&&"string"!=typeof p.data&&(p.data=x.param(p.data,p.traditional)),qn(An,p,n,C),2===b)return C;l=p.global,l&&0===x.active++&&x.event.trigger("ajaxStart"),p.type=p.type.toUpperCase(),p.hasContent=!Nn.test(p.type),o=p.url,p.hasContent||(p.data&&(o=p.url+=(bn.test(o)?"&":"?")+p.data,delete p.data),p.cache===!1&&(p.url=wn.test(o)?o.replace(wn,"$1_="+vn++):o+(bn.test(o)?"&":"?")+"_="+vn++)),p.ifModified&&(x.lastModified[o]&&C.setRequestHeader("If-Modified-Since",x.lastModified[o]),x.etag[o]&&C.setRequestHeader("If-None-Match",x.etag[o])),(p.data&&p.hasContent&&p.contentType!==!1||n.contentType)&&C.setRequestHeader("Content-Type",p.contentType),C.setRequestHeader("Accept",p.dataTypes[0]&&p.accepts[p.dataTypes[0]]?p.accepts[p.dataTypes[0]]+("*"!==p.dataTypes[0]?", "+Dn+"; q=0.01":""):p.accepts["*"]);for(i in p.headers)C.setRequestHeader(i,p.headers[i]);if(p.beforeSend&&(p.beforeSend.call(f,C,p)===!1||2===b))return C.abort();w="abort";for(i in{success:1,error:1,complete:1})C[i](p[i]);if(u=qn(jn,p,n,C)){C.readyState=1,l&&d.trigger("ajaxSend",[C,p]),p.async&&p.timeout>0&&(s=setTimeout(function(){C.abort("timeout")},p.timeout));try{b=1,u.send(y,k)}catch(N){if(!(2>b))throw N;k(-1,N)}}else k(-1,"No Transport");function k(e,n,r,i){var c,y,v,w,T,N=n;2!==b&&(b=2,s&&clearTimeout(s),u=t,a=i||"",C.readyState=e>0?4:0,c=e>=200&&300>e||304===e,r&&(w=Mn(p,C,r)),w=On(p,w,C,c),c?(p.ifModified&&(T=C.getResponseHeader("Last-Modified"),T&&(x.lastModified[o]=T),T=C.getResponseHeader("etag"),T&&(x.etag[o]=T)),204===e||"HEAD"===p.type?N="nocontent":304===e?N="notmodified":(N=w.state,y=w.data,v=w.error,c=!v)):(v=N,(e||!N)&&(N="error",0>e&&(e=0))),C.status=e,C.statusText=(n||N)+"",c?h.resolveWith(f,[y,N,C]):h.rejectWith(f,[C,N,v]),C.statusCode(m),m=t,l&&d.trigger(c?"ajaxSuccess":"ajaxError",[C,p,c?y:v]),g.fireWith(f,[C,N]),l&&(d.trigger("ajaxComplete",[C,p]),--x.active||x.event.trigger("ajaxStop")))}return C},getJSON:function(e,t,n){return x.get(e,t,n,"json")},getScript:function(e,n){return x.get(e,t,n,"script")}}),x.each(["get","post"],function(e,n){x[n]=function(e,r,i,o){return x.isFunction(r)&&(o=o||i,i=r,r=t),x.ajax({url:e,type:n,dataType:o,data:r,success:i})}});function Mn(e,n,r){var i,o,a,s,l=e.contents,u=e.dataTypes;while("*"===u[0])u.shift(),o===t&&(o=e.mimeType||n.getResponseHeader("Content-Type"));if(o)for(s in l)if(l[s]&&l[s].test(o)){u.unshift(s);break}if(u[0]in r)a=u[0];else{for(s in r){if(!u[0]||e.converters[s+" "+u[0]]){a=s;break}i||(i=s)}a=a||i}return a?(a!==u[0]&&u.unshift(a),r[a]):t}function On(e,t,n,r){var i,o,a,s,l,u={},c=e.dataTypes.slice();if(c[1])for(a in e.converters)u[a.toLowerCase()]=e.converters[a];o=c.shift();while(o)if(e.responseFields[o]&&(n[e.responseFields[o]]=t),!l&&r&&e.dataFilter&&(t=e.dataFilter(t,e.dataType)),l=o,o=c.shift())if("*"===o)o=l;else if("*"!==l&&l!==o){if(a=u[l+" "+o]||u["* "+o],!a)for(i in u)if(s=i.split(" "),s[1]===o&&(a=u[l+" "+s[0]]||u["* "+s[0]])){a===!0?a=u[i]:u[i]!==!0&&(o=s[0],c.unshift(s[1]));break}if(a!==!0)if(a&&e["throws"])t=a(t);else try{t=a(t)}catch(p){return{state:"parsererror",error:a?p:"No conversion from "+l+" to "+o}}}return{state:"success",data:t}}x.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(e){return x.globalEval(e),e}}}),x.ajaxPrefilter("script",function(e){e.cache===t&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),x.ajaxTransport("script",function(e){if(e.crossDomain){var n,r=a.head||x("head")[0]||a.documentElement;return{send:function(t,i){n=a.createElement("script"),n.async=!0,e.scriptCharset&&(n.charset=e.scriptCharset),n.src=e.url,n.onload=n.onreadystatechange=function(e,t){(t||!n.readyState||/loaded|complete/.test(n.readyState))&&(n.onload=n.onreadystatechange=null,n.parentNode&&n.parentNode.removeChild(n),n=null,t||i(200,"success"))},r.insertBefore(n,r.firstChild)},abort:function(){n&&n.onload(t,!0)}}}});var Fn=[],Bn=/(=)\?(?=&|$)|\?\?/;x.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Fn.pop()||x.expando+"_"+vn++;return this[e]=!0,e}}),x.ajaxPrefilter("json jsonp",function(n,r,i){var o,a,s,l=n.jsonp!==!1&&(Bn.test(n.url)?"url":"string"==typeof n.data&&!(n.contentType||"").indexOf("application/x-www-form-urlencoded")&&Bn.test(n.data)&&"data");return l||"jsonp"===n.dataTypes[0]?(o=n.jsonpCallback=x.isFunction(n.jsonpCallback)?n.jsonpCallback():n.jsonpCallback,l?n[l]=n[l].replace(Bn,"$1"+o):n.jsonp!==!1&&(n.url+=(bn.test(n.url)?"&":"?")+n.jsonp+"="+o),n.converters["script json"]=function(){return s||x.error(o+" was not called"),s[0]},n.dataTypes[0]="json",a=e[o],e[o]=function(){s=arguments},i.always(function(){e[o]=a,n[o]&&(n.jsonpCallback=r.jsonpCallback,Fn.push(o)),s&&x.isFunction(a)&&a(s[0]),s=a=t}),"script"):t});var Pn,Rn,Wn=0,$n=e.ActiveXObject&&function(){var e;for(e in Pn)Pn[e](t,!0)};function In(){try{return new e.XMLHttpRequest}catch(t){}}function zn(){try{return new e.ActiveXObject("Microsoft.XMLHTTP")}catch(t){}}x.ajaxSettings.xhr=e.ActiveXObject?function(){return!this.isLocal&&In()||zn()}:In,Rn=x.ajaxSettings.xhr(),x.support.cors=!!Rn&&"withCredentials"in Rn,Rn=x.support.ajax=!!Rn,Rn&&x.ajaxTransport(function(n){if(!n.crossDomain||x.support.cors){var r;return{send:function(i,o){var a,s,l=n.xhr();if(n.username?l.open(n.type,n.url,n.async,n.username,n.password):l.open(n.type,n.url,n.async),n.xhrFields)for(s in n.xhrFields)l[s]=n.xhrFields[s];n.mimeType&&l.overrideMimeType&&l.overrideMimeType(n.mimeType),n.crossDomain||i["X-Requested-With"]||(i["X-Requested-With"]="XMLHttpRequest");try{for(s in i)l.setRequestHeader(s,i[s])}catch(u){}l.send(n.hasContent&&n.data||null),r=function(e,i){var s,u,c,p;try{if(r&&(i||4===l.readyState))if(r=t,a&&(l.onreadystatechange=x.noop,$n&&delete Pn[a]),i)4!==l.readyState&&l.abort();else{p={},s=l.status,u=l.getAllResponseHeaders(),"string"==typeof l.responseText&&(p.text=l.responseText);try{c=l.statusText}catch(f){c=""}s||!n.isLocal||n.crossDomain?1223===s&&(s=204):s=p.text?200:404}}catch(d){i||o(-1,d)}p&&o(s,c,p,u)},n.async?4===l.readyState?setTimeout(r):(a=++Wn,$n&&(Pn||(Pn={},x(e).unload($n)),Pn[a]=r),l.onreadystatechange=r):r()},abort:function(){r&&r(t,!0)}}}});var Xn,Un,Vn=/^(?:toggle|show|hide)$/,Yn=RegExp("^(?:([+-])=|)("+w+")([a-z%]*)$","i"),Jn=/queueHooks$/,Gn=[nr],Qn={"*":[function(e,t){var n=this.createTween(e,t),r=n.cur(),i=Yn.exec(t),o=i&&i[3]||(x.cssNumber[e]?"":"px"),a=(x.cssNumber[e]||"px"!==o&&+r)&&Yn.exec(x.css(n.elem,e)),s=1,l=20;if(a&&a[3]!==o){o=o||a[3],i=i||[],a=+r||1;do s=s||".5",a/=s,x.style(n.elem,e,a+o);while(s!==(s=n.cur()/r)&&1!==s&&--l)}return i&&(a=n.start=+a||+r||0,n.unit=o,n.end=i[1]?a+(i[1]+1)*i[2]:+i[2]),n}]};function Kn(){return setTimeout(function(){Xn=t}),Xn=x.now()}function Zn(e,t,n){var r,i=(Qn[t]||[]).concat(Qn["*"]),o=0,a=i.length;for(;a>o;o++)if(r=i[o].call(n,t,e))return r}function er(e,t,n){var r,i,o=0,a=Gn.length,s=x.Deferred().always(function(){delete l.elem}),l=function(){if(i)return!1;var t=Xn||Kn(),n=Math.max(0,u.startTime+u.duration-t),r=n/u.duration||0,o=1-r,a=0,l=u.tweens.length;for(;l>a;a++)u.tweens[a].run(o);return s.notifyWith(e,[u,o,n]),1>o&&l?n:(s.resolveWith(e,[u]),!1)},u=s.promise({elem:e,props:x.extend({},t),opts:x.extend(!0,{specialEasing:{}},n),originalProperties:t,originalOptions:n,startTime:Xn||Kn(),duration:n.duration,tweens:[],createTween:function(t,n){var r=x.Tween(e,u.opts,t,n,u.opts.specialEasing[t]||u.opts.easing);return u.tweens.push(r),r},stop:function(t){var n=0,r=t?u.tweens.length:0;if(i)return this;for(i=!0;r>n;n++)u.tweens[n].run(1);return t?s.resolveWith(e,[u,t]):s.rejectWith(e,[u,t]),this}}),c=u.props;for(tr(c,u.opts.specialEasing);a>o;o++)if(r=Gn[o].call(u,e,c,u.opts))return r;return x.map(c,Zn,u),x.isFunction(u.opts.start)&&u.opts.start.call(e,u),x.fx.timer(x.extend(l,{elem:e,anim:u,queue:u.opts.queue})),u.progress(u.opts.progress).done(u.opts.done,u.opts.complete).fail(u.opts.fail).always(u.opts.always)}function tr(e,t){var n,r,i,o,a;for(n in e)if(r=x.camelCase(n),i=t[r],o=e[n],x.isArray(o)&&(i=o[1],o=e[n]=o[0]),n!==r&&(e[r]=o,delete e[n]),a=x.cssHooks[r],a&&"expand"in a){o=a.expand(o),delete e[r];for(n in o)n in e||(e[n]=o[n],t[n]=i)}else t[r]=i}x.Animation=x.extend(er,{tweener:function(e,t){x.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");var n,r=0,i=e.length;for(;i>r;r++)n=e[r],Qn[n]=Qn[n]||[],Qn[n].unshift(t)},prefilter:function(e,t){t?Gn.unshift(e):Gn.push(e)}});function nr(e,t,n){var r,i,o,a,s,l,u=this,c={},p=e.style,f=e.nodeType&&nn(e),d=x._data(e,"fxshow");n.queue||(s=x._queueHooks(e,"fx"),null==s.unqueued&&(s.unqueued=0,l=s.empty.fire,s.empty.fire=function(){s.unqueued||l()}),s.unqueued++,u.always(function(){u.always(function(){s.unqueued--,x.queue(e,"fx").length||s.empty.fire()})})),1===e.nodeType&&("height"in t||"width"in t)&&(n.overflow=[p.overflow,p.overflowX,p.overflowY],"inline"===x.css(e,"display")&&"none"===x.css(e,"float")&&(x.support.inlineBlockNeedsLayout&&"inline"!==ln(e.nodeName)?p.zoom=1:p.display="inline-block")),n.overflow&&(p.overflow="hidden",x.support.shrinkWrapBlocks||u.always(function(){p.overflow=n.overflow[0],p.overflowX=n.overflow[1],p.overflowY=n.overflow[2]}));for(r in t)if(i=t[r],Vn.exec(i)){if(delete t[r],o=o||"toggle"===i,i===(f?"hide":"show"))continue;c[r]=d&&d[r]||x.style(e,r)}if(!x.isEmptyObject(c)){d?"hidden"in d&&(f=d.hidden):d=x._data(e,"fxshow",{}),o&&(d.hidden=!f),f?x(e).show():u.done(function(){x(e).hide()}),u.done(function(){var t;x._removeData(e,"fxshow");for(t in c)x.style(e,t,c[t])});for(r in c)a=Zn(f?d[r]:0,r,u),r in d||(d[r]=a.start,f&&(a.end=a.start,a.start="width"===r||"height"===r?1:0))}}function rr(e,t,n,r,i){return new rr.prototype.init(e,t,n,r,i)}x.Tween=rr,rr.prototype={constructor:rr,init:function(e,t,n,r,i,o){this.elem=e,this.prop=n,this.easing=i||"swing",this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=o||(x.cssNumber[n]?"":"px")},cur:function(){var e=rr.propHooks[this.prop];return e&&e.get?e.get(this):rr.propHooks._default.get(this)},run:function(e){var t,n=rr.propHooks[this.prop];return this.pos=t=this.options.duration?x.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):rr.propHooks._default.set(this),this}},rr.prototype.init.prototype=rr.prototype,rr.propHooks={_default:{get:function(e){var t;return null==e.elem[e.prop]||e.elem.style&&null!=e.elem.style[e.prop]?(t=x.css(e.elem,e.prop,""),t&&"auto"!==t?t:0):e.elem[e.prop]},set:function(e){x.fx.step[e.prop]?x.fx.step[e.prop](e):e.elem.style&&(null!=e.elem.style[x.cssProps[e.prop]]||x.cssHooks[e.prop])?x.style(e.elem,e.prop,e.now+e.unit):e.elem[e.prop]=e.now}}},rr.propHooks.scrollTop=rr.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},x.each(["toggle","show","hide"],function(e,t){var n=x.fn[t];x.fn[t]=function(e,r,i){return null==e||"boolean"==typeof e?n.apply(this,arguments):this.animate(ir(t,!0),e,r,i)}}),x.fn.extend({fadeTo:function(e,t,n,r){return this.filter(nn).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(e,t,n,r){var i=x.isEmptyObject(e),o=x.speed(t,n,r),a=function(){var t=er(this,x.extend({},e),o);(i||x._data(this,"finish"))&&t.stop(!0)};return a.finish=a,i||o.queue===!1?this.each(a):this.queue(o.queue,a)},stop:function(e,n,r){var i=function(e){var t=e.stop;delete e.stop,t(r)};return"string"!=typeof e&&(r=n,n=e,e=t),n&&e!==!1&&this.queue(e||"fx",[]),this.each(function(){var t=!0,n=null!=e&&e+"queueHooks",o=x.timers,a=x._data(this);if(n)a[n]&&a[n].stop&&i(a[n]);else for(n in a)a[n]&&a[n].stop&&Jn.test(n)&&i(a[n]);for(n=o.length;n--;)o[n].elem!==this||null!=e&&o[n].queue!==e||(o[n].anim.stop(r),t=!1,o.splice(n,1));(t||!r)&&x.dequeue(this,e)})},finish:function(e){return e!==!1&&(e=e||"fx"),this.each(function(){var t,n=x._data(this),r=n[e+"queue"],i=n[e+"queueHooks"],o=x.timers,a=r?r.length:0;for(n.finish=!0,x.queue(this,e,[]),i&&i.stop&&i.stop.call(this,!0),t=o.length;t--;)o[t].elem===this&&o[t].queue===e&&(o[t].anim.stop(!0),o.splice(t,1));for(t=0;a>t;t++)r[t]&&r[t].finish&&r[t].finish.call(this);delete n.finish})}});function ir(e,t){var n,r={height:e},i=0;for(t=t?1:0;4>i;i+=2-t)n=Zt[i],r["margin"+n]=r["padding"+n]=e;return t&&(r.opacity=r.width=e),r}x.each({slideDown:ir("show"),slideUp:ir("hide"),slideToggle:ir("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){x.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}}),x.speed=function(e,t,n){var r=e&&"object"==typeof e?x.extend({},e):{complete:n||!n&&t||x.isFunction(e)&&e,duration:e,easing:n&&t||t&&!x.isFunction(t)&&t};return r.duration=x.fx.off?0:"number"==typeof r.duration?r.duration:r.duration in x.fx.speeds?x.fx.speeds[r.duration]:x.fx.speeds._default,(null==r.queue||r.queue===!0)&&(r.queue="fx"),r.old=r.complete,r.complete=function(){x.isFunction(r.old)&&r.old.call(this),r.queue&&x.dequeue(this,r.queue)},r},x.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}},x.timers=[],x.fx=rr.prototype.init,x.fx.tick=function(){var e,n=x.timers,r=0;for(Xn=x.now();n.length>r;r++)e=n[r],e()||n[r]!==e||n.splice(r--,1);n.length||x.fx.stop(),Xn=t},x.fx.timer=function(e){e()&&x.timers.push(e)&&x.fx.start()},x.fx.interval=13,x.fx.start=function(){Un||(Un=setInterval(x.fx.tick,x.fx.interval))},x.fx.stop=function(){clearInterval(Un),Un=null},x.fx.speeds={slow:600,fast:200,_default:400},x.fx.step={},x.expr&&x.expr.filters&&(x.expr.filters.animated=function(e){return x.grep(x.timers,function(t){return e===t.elem}).length}),x.fn.offset=function(e){if(arguments.length)return e===t?this:this.each(function(t){x.offset.setOffset(this,e,t)});var n,r,o={top:0,left:0},a=this[0],s=a&&a.ownerDocument;if(s)return n=s.documentElement,x.contains(n,a)?(typeof a.getBoundingClientRect!==i&&(o=a.getBoundingClientRect()),r=or(s),{top:o.top+(r.pageYOffset||n.scrollTop)-(n.clientTop||0),left:o.left+(r.pageXOffset||n.scrollLeft)-(n.clientLeft||0)}):o},x.offset={setOffset:function(e,t,n){var r=x.css(e,"position");"static"===r&&(e.style.position="relative");var i=x(e),o=i.offset(),a=x.css(e,"top"),s=x.css(e,"left"),l=("absolute"===r||"fixed"===r)&&x.inArray("auto",[a,s])>-1,u={},c={},p,f;l?(c=i.position(),p=c.top,f=c.left):(p=parseFloat(a)||0,f=parseFloat(s)||0),x.isFunction(t)&&(t=t.call(e,n,o)),null!=t.top&&(u.top=t.top-o.top+p),null!=t.left&&(u.left=t.left-o.left+f),"using"in t?t.using.call(e,u):i.css(u)}},x.fn.extend({position:function(){if(this[0]){var e,t,n={top:0,left:0},r=this[0];return"fixed"===x.css(r,"position")?t=r.getBoundingClientRect():(e=this.offsetParent(),t=this.offset(),x.nodeName(e[0],"html")||(n=e.offset()),n.top+=x.css(e[0],"borderTopWidth",!0),n.left+=x.css(e[0],"borderLeftWidth",!0)),{top:t.top-n.top-x.css(r,"marginTop",!0),left:t.left-n.left-x.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||s;while(e&&!x.nodeName(e,"html")&&"static"===x.css(e,"position"))e=e.offsetParent;return e||s})}}),x.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,n){var r=/Y/.test(n);x.fn[e]=function(i){return x.access(this,function(e,i,o){var a=or(e);return o===t?a?n in a?a[n]:a.document.documentElement[i]:e[i]:(a?a.scrollTo(r?x(a).scrollLeft():o,r?o:x(a).scrollTop()):e[i]=o,t)},e,i,arguments.length,null)}});function or(e){return x.isWindow(e)?e:9===e.nodeType?e.defaultView||e.parentWindow:!1}x.each({Height:"height",Width:"width"},function(e,n){x.each({padding:"inner"+e,content:n,"":"outer"+e},function(r,i){x.fn[i]=function(i,o){var a=arguments.length&&(r||"boolean"!=typeof i),s=r||(i===!0||o===!0?"margin":"border");return x.access(this,function(n,r,i){var o;return x.isWindow(n)?n.document.documentElement["client"+e]:9===n.nodeType?(o=n.documentElement,Math.max(n.body["scroll"+e],o["scroll"+e],n.body["offset"+e],o["offset"+e],o["client"+e])):i===t?x.css(n,r,s):x.style(n,r,i,s)},n,a?i:t,a,null)}})}),x.fn.size=function(){return this.length},x.fn.andSelf=x.fn.addBack,"object"==typeof module&&module&&"object"==typeof module.exports?module.exports=x:(e.jQuery=e.$=x,"function"==typeof define&&define.amd&&define("jquery",[],function(){return x}))})(window);
src/svg-icons/navigation/apps.js
mtsandeep/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NavigationApps = (props) => ( <SvgIcon {...props}> <path d="M4 8h4V4H4v4zm6 12h4v-4h-4v4zm-6 0h4v-4H4v4zm0-6h4v-4H4v4zm6 0h4v-4h-4v4zm6-10v4h4V4h-4zm-6 4h4V4h-4v4zm6 6h4v-4h-4v4zm0 6h4v-4h-4v4z"/> </SvgIcon> ); NavigationApps = pure(NavigationApps); NavigationApps.displayName = 'NavigationApps'; NavigationApps.muiName = 'SvgIcon'; export default NavigationApps;
Examples/UIExplorer/SwitchIOSExample.js
spyrx7/react-native
/** * The examples provided by Facebook are for non-commercial testing and * evaluation purposes only. * * Facebook reserves all rights not expressly granted. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * @flow */ 'use strict'; var React = require('react-native'); var { SwitchIOS, Text, View } = React; var BasicSwitchExample = React.createClass({ getInitialState() { return { trueSwitchIsOn: true, falseSwitchIsOn: false, }; }, render() { return ( <View> <SwitchIOS onValueChange={(value) => this.setState({falseSwitchIsOn: value})} style={{marginBottom: 10}} value={this.state.falseSwitchIsOn} /> <SwitchIOS onValueChange={(value) => this.setState({trueSwitchIsOn: value})} value={this.state.trueSwitchIsOn} /> </View> ); } }); var DisabledSwitchExample = React.createClass({ render() { return ( <View> <SwitchIOS disabled={true} style={{marginBottom: 10}} value={true} /> <SwitchIOS disabled={true} value={false} /> </View> ); }, }); var ColorSwitchExample = React.createClass({ getInitialState() { return { colorTrueSwitchIsOn: true, colorFalseSwitchIsOn: false, }; }, render() { return ( <View> <SwitchIOS onValueChange={(value) => this.setState({colorFalseSwitchIsOn: value})} onTintColor="#00ff00" style={{marginBottom: 10}} thumbTintColor="#0000ff" tintColor="#ff0000" value={this.state.colorFalseSwitchIsOn} /> <SwitchIOS onValueChange={(value) => this.setState({colorTrueSwitchIsOn: value})} onTintColor="#00ff00" thumbTintColor="#0000ff" tintColor="#ff0000" value={this.state.colorTrueSwitchIsOn} /> </View> ); }, }); var EventSwitchExample = React.createClass({ getInitialState() { return { eventSwitchIsOn: false, eventSwitchRegressionIsOn: true, }; }, render() { return ( <View style={{ flexDirection: 'row', justifyContent: 'space-around' }}> <View> <SwitchIOS onValueChange={(value) => this.setState({eventSwitchIsOn: value})} style={{marginBottom: 10}} value={this.state.eventSwitchIsOn} /> <SwitchIOS onValueChange={(value) => this.setState({eventSwitchIsOn: value})} style={{marginBottom: 10}} value={this.state.eventSwitchIsOn} /> <Text>{this.state.eventSwitchIsOn ? "On" : "Off"}</Text> </View> <View> <SwitchIOS onValueChange={(value) => this.setState({eventSwitchRegressionIsOn: value})} style={{marginBottom: 10}} value={this.state.eventSwitchRegressionIsOn} /> <SwitchIOS onValueChange={(value) => this.setState({eventSwitchRegressionIsOn: value})} style={{marginBottom: 10}} value={this.state.eventSwitchRegressionIsOn} /> <Text>{this.state.eventSwitchRegressionIsOn ? "On" : "Off"}</Text> </View> </View> ); } }); exports.title = '<SwitchIOS>'; exports.displayName = 'SwitchExample'; exports.description = 'Native boolean input'; exports.examples = [ { title: 'Switches can be set to true or false', render(): ReactElement { return <BasicSwitchExample />; } }, { title: 'Switches can be disabled', render(): ReactElement { return <DisabledSwitchExample />; } }, { title: 'Custom colors can be provided', render(): ReactElement { return <ColorSwitchExample />; } }, { title: 'Change events can be detected', render(): ReactElement { return <EventSwitchExample />; } }, { title: 'Switches are controlled components', render(): ReactElement { return <SwitchIOS />; } } ];
src/svg-icons/image/control-point.js
ngbrown/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageControlPoint = (props) => ( <SvgIcon {...props}> <path d="M13 7h-2v4H7v2h4v4h2v-4h4v-2h-4V7zm-1-5C6.49 2 2 6.49 2 12s4.49 10 10 10 10-4.49 10-10S17.51 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z"/> </SvgIcon> ); ImageControlPoint = pure(ImageControlPoint); ImageControlPoint.displayName = 'ImageControlPoint'; ImageControlPoint.muiName = 'SvgIcon'; export default ImageControlPoint;
ajax/libs/semantic-ui-react/0.61.7/semantic-ui-react.min.js
joeyparrish/cdnjs
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("React"),require("ReactDOM")):"function"==typeof define&&define.amd?define(["React","ReactDOM"],t):"object"==typeof exports?exports.semanticUIReact=t(require("React"),require("ReactDOM")):e.semanticUIReact=t(e.React,e.ReactDOM)}(this,function(e,t){return function(e){function t(n){if(r[n])return r[n].exports;var o=r[n]={exports:{},id:n,loaded:!1};return e[n].call(o.exports,o,o.exports,t),o.loaded=!0,o.exports}var r={};return t.m=e,t.c=r,t.p="/",t(0)}([/*!********************!*\ !*** ./src/umd.js ***! \********************/ function(e,t,r){"use strict";function n(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},a=r(/*! ./index */316),s=n(a);e.exports=o({},s)},/*!************************!*\ !*** external "React" ***! \************************/ function(t,r){t.exports=e},/*!**************************!*\ !*** ./src/lib/index.js ***! \**************************/ function(e,t,r){"use strict";function n(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}function o(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.objectDiff=t.numberToWord=t.numberToWordMap=t.keyboardKey=t.SUI=t.META=t.leven=t.isBrowser=t.getElementType=t.getUnhandledProps=t.makeDebugger=t.debug=t.customPropTypes=t.useVerticalAlignProp=t.useTextAlignProp=t.useWidthProp=t.useKeyOrValueAndKey=t.useValueAndKey=t.useKeyOnly=t.childrenUtils=t.AutoControlledComponent=void 0;var a=r(/*! ./AutoControlledComponent */317);Object.defineProperty(t,"AutoControlledComponent",{enumerable:!0,get:function(){return o(a).default}});var s=r(/*! ./classNameBuilders */321);Object.defineProperty(t,"useKeyOnly",{enumerable:!0,get:function(){return s.useKeyOnly}}),Object.defineProperty(t,"useValueAndKey",{enumerable:!0,get:function(){return s.useValueAndKey}}),Object.defineProperty(t,"useKeyOrValueAndKey",{enumerable:!0,get:function(){return s.useKeyOrValueAndKey}}),Object.defineProperty(t,"useWidthProp",{enumerable:!0,get:function(){return s.useWidthProp}}),Object.defineProperty(t,"useTextAlignProp",{enumerable:!0,get:function(){return s.useTextAlignProp}}),Object.defineProperty(t,"useVerticalAlignProp",{enumerable:!0,get:function(){return s.useVerticalAlignProp}});var l=r(/*! ./debug */323);Object.defineProperty(t,"debug",{enumerable:!0,get:function(){return l.debug}}),Object.defineProperty(t,"makeDebugger",{enumerable:!0,get:function(){return l.makeDebugger}});var u=r(/*! ./factories */324);Object.keys(u).forEach(function(e){"default"!==e&&"__esModule"!==e&&Object.defineProperty(t,e,{enumerable:!0,get:function(){return u[e]}})});var i=r(/*! ./getUnhandledProps */326);Object.defineProperty(t,"getUnhandledProps",{enumerable:!0,get:function(){return o(i).default}});var c=r(/*! ./getElementType */325);Object.defineProperty(t,"getElementType",{enumerable:!0,get:function(){return o(c).default}});var p=r(/*! ./isBrowser */179);Object.defineProperty(t,"isBrowser",{enumerable:!0,get:function(){return o(p).default}});var d=r(/*! ./leven */180);Object.defineProperty(t,"leven",{enumerable:!0,get:function(){return o(d).default}});var f=r(/*! ./keyboardKey */327);Object.defineProperty(t,"keyboardKey",{enumerable:!0,get:function(){return o(f).default}});var y=r(/*! ./numberToWord */92);Object.defineProperty(t,"numberToWordMap",{enumerable:!0,get:function(){return y.numberToWordMap}}),Object.defineProperty(t,"numberToWord",{enumerable:!0,get:function(){return y.numberToWord}});var m=r(/*! ./objectDiff */328);Object.defineProperty(t,"objectDiff",{enumerable:!0,get:function(){return m.objectDiff}});var h=r(/*! ./childrenUtils */320),v=n(h),b=r(/*! ./customPropTypes */322),g=n(b),P=r(/*! ./META */318),T=n(P),O=r(/*! ./SUI */319),_=n(O);t.childrenUtils=v,t.customPropTypes=g,t.META=T,t.SUI=_},/*!*******************************!*\ !*** ./~/classnames/index.js ***! \*******************************/ function(e,t,r){var n,o;/*! Copyright (c) 2016 Jed Watson. Licensed under the MIT License (MIT), see http://jedwatson.github.io/classnames */ !function(){"use strict";function r(){for(var e=[],t=0;t<arguments.length;t++){var n=arguments[t];if(n){var o=typeof n;if("string"===o||"number"===o)e.push(n);else if(Array.isArray(n))e.push(r.apply(null,n));else if("object"===o)for(var s in n)a.call(n,s)&&n[s]&&e.push(s)}}return e.join(" ")}var a={}.hasOwnProperty;"undefined"!=typeof e&&e.exports?e.exports=r:(n=[],o=function(){return r}.apply(t,n),!(void 0!==o&&(e.exports=o)))}()},/*!*****************************!*\ !*** ./~/lodash/isArray.js ***! \*****************************/ function(e,t){var r=Array.isArray;e.exports=r},/*!************************************!*\ !*** ./~/lodash/fp/placeholder.js ***! \************************************/ function(e,t){e.exports={}},/*!********************************!*\ !*** ./~/lodash/fp/convert.js ***! \********************************/ function(e,t,r){function n(e,t,r){return o(a,e,t,r)}var o=r(/*! ./_baseConvert */488),a=r(/*! ./_util */490);e.exports=n},/*!*****************************!*\ !*** ./~/lodash/without.js ***! \*****************************/ function(e,t,r){var n=r(/*! ./_baseDifference */226),o=r(/*! ./_baseRest */18),a=r(/*! ./isArrayLikeObject */77),s=o(function(e,t){return a(e)?n(e,t):[]});e.exports=s},/*!************************************!*\ !*** ./src/elements/Icon/index.js ***! \************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var o=r(/*! ./Icon */47),a=n(o);t.default=a.default},/*!**************************!*\ !*** ./~/lodash/keys.js ***! \**************************/ function(e,t,r){function n(e){return s(e)?o(e):a(e)}var o=r(/*! ./_arrayLikeKeys */222),a=r(/*! ./_baseKeys */119),s=r(/*! ./isArrayLike */14);e.exports=n},/*!*************************!*\ !*** ./~/lodash/map.js ***! \*************************/ function(e,t,r){function n(e,t){var r=l(e)?o:s;return r(e,a(t,3))}var o=r(/*! ./_arrayMap */17),a=r(/*! ./_baseIteratee */13),s=r(/*! ./_baseMap */230),l=r(/*! ./isArray */4);e.exports=n},/*!***************************!*\ !*** ./~/lodash/_root.js ***! \***************************/ function(e,t,r){var n=r(/*! ./_freeGlobal */241),o="object"==typeof self&&self&&self.Object===Object&&self,a=n||o||Function("return this")();e.exports=a},/*!******************************!*\ !*** ./~/lodash/isObject.js ***! \******************************/ function(e,t){function r(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}e.exports=r},/*!***********************************!*\ !*** ./~/lodash/_baseIteratee.js ***! \***********************************/ function(e,t,r){function n(e){return"function"==typeof e?e:null==e?s:"object"==typeof e?l(e)?a(e[0],e[1]):o(e):u(e)}var o=r(/*! ./_baseMatches */380),a=r(/*! ./_baseMatchesProperty */381),s=r(/*! ./identity */23),l=r(/*! ./isArray */4),u=r(/*! ./property */517);e.exports=n},/*!*********************************!*\ !*** ./~/lodash/isArrayLike.js ***! \*********************************/ function(e,t,r){function n(e){return null!=e&&a(e.length)&&!o(e)}var o=r(/*! ./isFunction */28),a=r(/*! ./isLength */131);e.exports=n},/*!**********************************!*\ !*** ./~/lodash/isObjectLike.js ***! \**********************************/ function(e,t){function r(e){return null!=e&&"object"==typeof e}e.exports=r},/*!*******************************************!*\ !*** ./src/collections/Form/FormField.js ***! \*******************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.control,r=e.children,n=e.className,s=e.disabled,p=e.error,f=e.inline,m=e.label,h=e.required,v=e.type,b=e.width,g=(0,l.default)((0,c.useKeyOnly)(p,"error"),(0,c.useKeyOnly)(s,"disabled"),(0,c.useKeyOnly)(f,"inline"),(0,c.useKeyOnly)(h,"required"),(0,c.useWidthProp)(b,"wide"),"field",n),P=(0,c.getUnhandledProps)(o,e),T=(0,c.getElementType)(o,e);if(!t)return m?i.default.createElement(T,a({},P,{className:g}),i.default.createElement("label",null,m)):i.default.createElement(T,a({},P,{className:g}),r);var O=a({},P,{children:r,required:h,type:v});return"input"!==t||"checkbox"!==v&&"radio"!==v?t===d.default||t===y.default?i.default.createElement(T,{className:g},(0,u.createElement)(t,a({},O,{label:m}))):t&&m?i.default.createElement(T,{className:g},i.default.createElement("label",null,m),(0,u.createElement)(t,O)):t&&!m?i.default.createElement(T,{className:g},(0,u.createElement)(t,O)):void 0:i.default.createElement(T,{className:g},i.default.createElement("label",null,(0,u.createElement)(t,O)," ",m))}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! classnames */3),l=n(s),u=r(/*! react */1),i=n(u),c=r(/*! ../../lib */2),p=r(/*! ../../modules/Checkbox */51),d=n(p),f=r(/*! ../../addons/Radio */82),y=n(f);o._meta={name:"FormField",parent:"Form",type:c.META.TYPES.COLLECTION,props:{width:c.SUI.WIDTHS,control:["button","input","select","textarea"]}},o.propTypes={as:c.customPropTypes.as,control:c.customPropTypes.some([u.PropTypes.func,u.PropTypes.oneOf(o._meta.props.control)]),children:u.PropTypes.node,className:u.PropTypes.string,disabled:u.PropTypes.bool,error:u.PropTypes.bool,inline:u.PropTypes.bool,label:u.PropTypes.string,required:c.customPropTypes.every([c.customPropTypes.demand(["label"]),u.PropTypes.bool]),type:c.customPropTypes.every([c.customPropTypes.demand(["control"])]),width:u.PropTypes.oneOf(o._meta.props.width)},t.default=o},/*!*******************************!*\ !*** ./~/lodash/_arrayMap.js ***! \*******************************/ function(e,t){function r(e,t){for(var r=-1,n=null==e?0:e.length,o=Array(n);++r<n;)o[r]=t(e[r],r,e);return o}e.exports=r},/*!*******************************!*\ !*** ./~/lodash/_baseRest.js ***! \*******************************/ function(e,t,r){function n(e,t){return s(a(e,t,o),e+"")}var o=r(/*! ./identity */23),a=r(/*! ./_overRest */252),s=r(/*! ./_setToString */127);e.exports=n},/*!**************************************!*\ !*** ./~/lodash/fp/_falseOptions.js ***! \**************************************/ function(e,t){e.exports={cap:!1,curry:!1,fixed:!1,immutable:!1,rearg:!1}},/*!*******************************!*\ !*** ./~/lodash/toInteger.js ***! \*******************************/ function(e,t,r){function n(e){var t=o(e),r=t%1;return t===t?r?t-r:t:0}var o=r(/*! ./toFinite */278);e.exports=n},/*!*********************************!*\ !*** ./~/lodash/_baseGetTag.js ***! \*********************************/ function(e,t,r){function n(e){return null==e?void 0===e?u:l:(e=Object(e),i&&i in e?a(e):s(e))}var o=r(/*! ./_Symbol */31),a=r(/*! ./_getRawTag */429),s=r(/*! ./_objectToString */460),l="[object Null]",u="[object Undefined]",i=o?o.toStringTag:void 0;e.exports=n},/*!****************************!*\ !*** ./~/lodash/_toKey.js ***! \****************************/ function(e,t,r){function n(e){if("string"==typeof e||o(e))return e;var t=e+"";return"0"==t&&1/e==-a?"-0":t}var o=r(/*! ./isSymbol */29),a=1/0;e.exports=n},/*!******************************!*\ !*** ./~/lodash/identity.js ***! \******************************/ function(e,t){function r(e){return e}e.exports=r},/*!******************************!*\ !*** ./~/lodash/toString.js ***! \******************************/ function(e,t,r){function n(e){return null==e?"":o(e)}var o=r(/*! ./_baseToString */233);e.exports=n},/*!*******************************!*\ !*** ./~/lodash/_castPath.js ***! \*******************************/ function(e,t,r){function n(e,t){return o(e)?e:a(e,t)?[e]:s(l(e))}var o=r(/*! ./isArray */4),a=r(/*! ./_isKey */125),s=r(/*! ./_stringToPath */257),l=r(/*! ./toString */24);e.exports=n},/*!********************************!*\ !*** ./~/lodash/_getNative.js ***! \********************************/ function(e,t,r){function n(e,t){var r=a(e,t);return o(r)?r:void 0}var o=r(/*! ./_baseIsNative */376),a=r(/*! ./_getValue */430);e.exports=n},/*!*************************!*\ !*** ./~/lodash/has.js ***! \*************************/ function(e,t,r){function n(e,t){return null!=e&&a(e,t,o)}var o=r(/*! ./_baseHas */367),a=r(/*! ./_hasPath */245);e.exports=n},/*!********************************!*\ !*** ./~/lodash/isFunction.js ***! \********************************/ function(e,t,r){function n(e){if(!a(e))return!1;var t=o(e);return t==l||t==u||t==s||t==i}var o=r(/*! ./_baseGetTag */21),a=r(/*! ./isObject */12),s="[object AsyncFunction]",l="[object Function]",u="[object GeneratorFunction]",i="[object Proxy]";e.exports=n},/*!******************************!*\ !*** ./~/lodash/isSymbol.js ***! \******************************/ function(e,t,r){function n(e){return"symbol"==typeof e||a(e)&&o(e)==s}var o=r(/*! ./_baseGetTag */21),a=r(/*! ./isObjectLike */15),s="[object Symbol]";e.exports=n},/*!*************************************!*\ !*** ./src/elements/Image/index.js ***! \*************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var o=r(/*! ./Image */168),a=n(o);t.default=a.default},/*!*****************************!*\ !*** ./~/lodash/_Symbol.js ***! \*****************************/ function(e,t,r){var n=r(/*! ./_root */11),o=n.Symbol;e.exports=o},/*!*******************************!*\ !*** ./~/lodash/_baseEach.js ***! \*******************************/ function(e,t,r){var n=r(/*! ./_baseForOwn */117),o=r(/*! ./_createBaseEach */413),a=o(n);e.exports=a},/*!*********************************!*\ !*** ./~/lodash/_copyObject.js ***! \*********************************/ function(e,t,r){function n(e,t,r,n){var s=!r;r||(r={});for(var l=-1,u=t.length;++l<u;){var i=t[l],c=n?n(r[i],e[i],i,r,e):void 0;void 0===c&&(c=e[i]),s?a(r,i,c):o(r,i,c)}return r}var o=r(/*! ./_assignValue */58),a=r(/*! ./_baseAssignValue */115);e.exports=n},/*!*************************!*\ !*** ./~/lodash/get.js ***! \*************************/ function(e,t,r){function n(e,t,r){var n=null==e?void 0:o(e,t);return void 0===n?r:n}var o=r(/*! ./_baseGet */61);e.exports=n},/*!******************************!*\ !*** ./~/process/browser.js ***! \******************************/ function(e,t){function r(){throw new Error("setTimeout has not been defined")}function n(){throw new Error("clearTimeout has not been defined")}function o(e){if(c===setTimeout)return setTimeout(e,0);if((c===r||!c)&&setTimeout)return c=setTimeout,setTimeout(e,0);try{return c(e,0)}catch(t){try{return c.call(null,e,0)}catch(t){return c.call(this,e,0)}}}function a(e){if(p===clearTimeout)return clearTimeout(e);if((p===n||!p)&&clearTimeout)return p=clearTimeout,clearTimeout(e);try{return p(e)}catch(t){try{return p.call(null,e)}catch(t){return p.call(this,e)}}}function s(){m&&f&&(m=!1,f.length?y=f.concat(y):h=-1,y.length&&l())}function l(){if(!m){var e=o(s);m=!0;for(var t=y.length;t;){for(f=y,y=[];++h<t;)f&&f[h].run();h=-1,t=y.length}f=null,m=!1,a(e)}}function u(e,t){this.fun=e,this.array=t}function i(){}var c,p,d=e.exports={};!function(){try{c="function"==typeof setTimeout?setTimeout:r}catch(e){c=r}try{p="function"==typeof clearTimeout?clearTimeout:n}catch(e){p=n}}();var f,y=[],m=!1,h=-1;d.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var r=1;r<arguments.length;r++)t[r-1]=arguments[r];y.push(new u(e,t)),1!==y.length||m||o(l)},u.prototype.run=function(){this.fun.apply(null,this.array)},d.title="browser",d.browser=!0,d.env={},d.argv=[],d.version="",d.versions={},d.on=i,d.addListener=i,d.once=i,d.off=i,d.removeListener=i,d.removeAllListeners=i,d.emit=i,d.binding=function(e){throw new Error("process.binding is not supported")},d.cwd=function(){return"/"},d.chdir=function(e){throw new Error("process.chdir is not supported")},d.umask=function(){return 0}},/*!********************************!*\ !*** ./~/lodash/_arrayEach.js ***! \********************************/ function(e,t){function r(e,t){for(var r=-1,n=null==e?0:e.length;++r<n&&t(e[r],r,e)!==!1;);return e}e.exports=r},/*!*********************************!*\ !*** ./~/lodash/_baseCreate.js ***! \*********************************/ function(e,t,r){var n=r(/*! ./isObject */12),o=Object.create,a=function(){function e(){}return function(t){if(!n(t))return{};if(o)return o(t);e.prototype=t;var r=new e;return e.prototype=void 0,r}}();e.exports=a},/*!*********************************!*\ !*** ./~/lodash/_createWrap.js ***! \*********************************/ function(e,t,r){function n(e,t,r,n,O,_,E,j){var w=t&h;if(!w&&"function"!=typeof e)throw new TypeError(y);var S=n?n.length:0;if(S||(t&=~(g|P),n=O=void 0),E=void 0===E?E:T(f(E),0),j=void 0===j?j:f(j),S-=O?O.length:0,t&P){var M=n,x=O;n=O=void 0}var k=w?void 0:i(e),A=[e,t,r,n,O,M,x,_,E,j];if(k&&c(A,k),e=A[0],t=A[1],r=A[2],n=A[3],O=A[4],j=A[9]=null==A[9]?w?0:e.length:T(A[9]-S,0),!j&&t&(v|b)&&(t&=~(v|b)),t&&t!=m)C=t==v||t==b?s(e,t,j):t!=g&&t!=(m|g)||O.length?l.apply(void 0,A):u(e,t,r,n);else var C=a(e,t,r);var N=k?o:p;return d(N(C,A),e,t)}var o=r(/*! ./_baseSetData */231),a=r(/*! ./_createBind */415),s=r(/*! ./_createCurry */418),l=r(/*! ./_createHybrid */237),u=r(/*! ./_createPartial */421),i=r(/*! ./_getData */122),c=r(/*! ./_mergeData */456),p=r(/*! ./_setData */254),d=r(/*! ./_setWrapToString */255),f=r(/*! ./toInteger */20),y="Expected a function",m=1,h=2,v=8,b=16,g=32,P=64,T=Math.max;e.exports=n},/*!******************************!*\ !*** ./~/lodash/_isIndex.js ***! \******************************/ function(e,t){function r(e,t){return t=null==t?n:t,!!t&&("number"==typeof e||o.test(e))&&e>-1&&e%1==0&&e<t}var n=9007199254740991,o=/^(?:0|[1-9]\d*)$/;e.exports=r},/*!**********************************!*\ !*** ./~/lodash/_isPrototype.js ***! \**********************************/ function(e,t){function r(e){var t=e&&e.constructor,r="function"==typeof t&&t.prototype||n;return e===r}var n=Object.prototype;e.exports=r},/*!*************************************!*\ !*** ./~/lodash/_replaceHolders.js ***! \*************************************/ function(e,t){function r(e,t){for(var r=-1,o=e.length,a=0,s=[];++r<o;){var l=e[r];l!==t&&l!==n||(e[r]=n,s[a++]=r)}return s}var n="__lodash_placeholder__";e.exports=r},/*!************************!*\ !*** ./~/lodash/eq.js ***! \************************/ function(e,t){function r(e,t){return e===t||e!==e&&t!==t}e.exports=r},/*!******************************!*\ !*** ./~/lodash/isBuffer.js ***! \******************************/ function(e,t,r){(function(e){var n=r(/*! ./_root */11),o=r(/*! ./stubFalse */522),a="object"==typeof t&&t&&!t.nodeType&&t,s=a&&"object"==typeof e&&e&&!e.nodeType&&e,l=s&&s.exports===a,u=l?n.Buffer:void 0,i=u?u.isBuffer:void 0,c=i||o;e.exports=c}).call(t,r(/*! ./../webpack/buildin/module.js */135)(e))},/*!**************************!*\ !*** ./~/lodash/omit.js ***! \**************************/ function(e,t,r){var n=r(/*! ./_arrayMap */17),o=r(/*! ./_baseClone */116),a=r(/*! ./_baseUnset */395),s=r(/*! ./_castPath */25),l=r(/*! ./_copyObject */33),u=r(/*! ./_flatRest */67),i=r(/*! ./_getAllKeysIn */242),c=1,p=2,d=4,f=u(function(e,t){var r={};if(null==e)return r;var u=!1;t=n(t,function(t){return t=s(t,e),u||(u=t.length>1),t}),l(e,i(e),r),u&&(r=o(r,c|p|d));for(var f=t.length;f--;)a(r,t[f]);return r});e.exports=f},/*!************************************!*\ !*** ./src/addons/Portal/index.js ***! \************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var o=r(/*! ./Portal */281),a=n(o);t.default=a.default},/*!********************************************!*\ !*** ./src/collections/Table/TableCell.js ***! \********************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.active,r=e.children,n=e.className,s=e.collapsing,u=e.content,p=e.disabled,f=e.error,y=e.icon,m=e.negative,h=e.positive,v=e.selectable,b=e.singleLine,g=e.textAlign,P=e.verticalAlign,T=e.warning,O=e.width,_=(0,l.default)((0,c.useKeyOnly)(t,"active"),(0,c.useKeyOnly)(s,"collapsing"),(0,c.useKeyOnly)(p,"disabled"),(0,c.useKeyOnly)(f,"error"),(0,c.useKeyOnly)(m,"negative"),(0,c.useKeyOnly)(h,"positive"),(0,c.useKeyOnly)(v,"selectable"),(0,c.useKeyOnly)(b,"single line"),(0,c.useKeyOnly)(T,"warning"),(0,c.useTextAlignProp)(g),(0,c.useVerticalAlignProp)(P),(0,c.useWidthProp)(O,"wide"),n),E=(0,c.getUnhandledProps)(o,e),j=(0,c.getElementType)(o,e);return r?i.default.createElement(j,a({},E,{className:_}),r):i.default.createElement(j,a({},E,{className:_}),d.default.create(y),u)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! classnames */3),l=n(s),u=r(/*! react */1),i=n(u),c=r(/*! ../../lib */2),p=r(/*! ../../elements/Icon */8),d=n(p);o._meta={name:"TableCell",type:c.META.TYPES.COLLECTION,parent:"Table",props:{textAlign:c.SUI.TEXT_ALIGNMENTS,verticalAlign:c.SUI.VERTICAL_ALIGNMENTS,width:c.SUI.WIDTHS}},o.defaultProps={as:"td"},o.propTypes={as:c.customPropTypes.as,active:u.PropTypes.bool,children:u.PropTypes.node,className:u.PropTypes.string,collapsing:u.PropTypes.bool,content:c.customPropTypes.contentShorthand,disabled:u.PropTypes.bool,error:u.PropTypes.bool,icon:c.customPropTypes.itemShorthand,negative:u.PropTypes.bool,positive:u.PropTypes.bool,selectable:u.PropTypes.bool,singleLine:u.PropTypes.bool,textAlign:u.PropTypes.oneOf(o._meta.props.textAlign),verticalAlign:u.PropTypes.oneOf(o._meta.props.verticalAlign),warning:u.PropTypes.bool,width:u.PropTypes.oneOf(o._meta.props.width)},o.create=(0,c.createShorthandFactory)(o,function(e){return{content:e}}),t.default=o},/*!***********************************!*\ !*** ./src/elements/Icon/Icon.js ***! \***********************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.bordered,r=e.className,n=e.circular,s=e.color,u=e.corner,p=e.disabled,d=e.fitted,f=e.flipped,y=e.inverted,m=e.link,h=e.loading,v=e.name,b=e.rotated,g=e.size,P=(0,l.default)(g,s,(0,c.useKeyOnly)(t,"bordered"),(0,c.useKeyOnly)(n,"circular"),(0,c.useKeyOnly)(u,"corner"),(0,c.useKeyOnly)(p,"disabled"),(0,c.useKeyOnly)(d,"fitted"),(0,c.useValueAndKey)(f,"flipped"),(0,c.useKeyOnly)(y,"inverted"),(0,c.useKeyOnly)(m,"link"),(0,c.useKeyOnly)(h,"loading"),(0,c.useValueAndKey)(b,"rotated"),v,r,"icon"),T=(0,c.getUnhandledProps)(o,e),O=(0,c.getElementType)(o,e);return i.default.createElement(O,a({},T,{className:P}))}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! classnames */3),l=n(s),u=r(/*! react */1),i=n(u),c=r(/*! ../../lib */2),p=r(/*! ./IconGroup */167),d=n(p);o.Group=d.default,o._meta={name:"Icon",type:c.META.TYPES.ELEMENT,props:{color:c.SUI.COLORS,flipped:["horizontally","vertically"],name:c.SUI.ICONS,rotated:["clockwise","counterclockwise"],size:c.SUI.SIZES}},o.propTypes={as:c.customPropTypes.as,bordered:u.PropTypes.bool,className:u.PropTypes.string,circular:u.PropTypes.bool,color:u.PropTypes.oneOf(o._meta.props.color),corner:u.PropTypes.bool,disabled:u.PropTypes.bool,fitted:u.PropTypes.bool,flipped:u.PropTypes.oneOf(o._meta.props.flipped),inverted:u.PropTypes.bool,name:c.customPropTypes.suggest(o._meta.props.name),link:u.PropTypes.bool,loading:u.PropTypes.bool,rotated:u.PropTypes.oneOf(o._meta.props.rotated),size:u.PropTypes.oneOf(o._meta.props.size)},o.defaultProps={as:"i"},o.create=(0,c.createShorthandFactory)(o,function(e){return{name:e}}),t.default=o},/*!*************************************!*\ !*** ./src/elements/Label/index.js ***! \*************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var o=r(/*! ./Label */87),a=n(o);t.default=a.default},/*!**********************************************!*\ !*** ./src/elements/List/ListDescription.js ***! \**********************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.children,r=e.className,n=e.content,s=(0,l.default)(r,"description"),u=(0,c.getUnhandledProps)(o,e),p=(0,c.getElementType)(o,e);return i.default.createElement(p,a({},u,{className:s}),t||n)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! classnames */3),l=n(s),u=r(/*! react */1),i=n(u),c=r(/*! ../../lib */2);o._meta={name:"ListDescription",parent:"List",type:c.META.TYPES.ELEMENT},o.propTypes={as:c.customPropTypes.as,children:u.PropTypes.node,className:u.PropTypes.string,content:c.customPropTypes.contentShorthand},o.create=(0,c.createShorthandFactory)(o,function(e){return{content:e}}),t.default=o},/*!*****************************************!*\ !*** ./src/elements/List/ListHeader.js ***! \*****************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.children,r=e.className,n=e.content,s=(0,l.default)(r,"header"),u=(0,c.getUnhandledProps)(o,e),p=(0,c.getElementType)(o,e);return i.default.createElement(p,a({},u,{className:s}),t||n)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! classnames */3),l=n(s),u=r(/*! react */1),i=n(u),c=r(/*! ../../lib */2);o._meta={name:"ListHeader",parent:"List",type:c.META.TYPES.ELEMENT},o.propTypes={as:c.customPropTypes.as,children:u.PropTypes.node,className:u.PropTypes.string,content:c.customPropTypes.contentShorthand},o.create=(0,c.createShorthandFactory)(o,function(e){return{content:e}}),t.default=o},/*!***************************************!*\ !*** ./src/modules/Checkbox/index.js ***! \***************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var o=r(/*! ./Checkbox */330),a=n(o);t.default=a.default},/*!************************************!*\ !*** ./src/views/Feed/FeedDate.js ***! \************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.children,r=e.className,n=e.content,s=(0,l.default)(r,"date"),u=(0,c.getUnhandledProps)(o,e),p=(0,c.getElementType)(o,e);return i.default.createElement(p,a({},u,{className:s}),t||n)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! classnames */3),l=n(s),u=r(/*! react */1),i=n(u),c=r(/*! ../../lib */2);o._meta={name:"FeedDate",parent:"Feed",type:c.META.TYPES.VIEW},o.propTypes={as:c.customPropTypes.as,children:u.PropTypes.node,className:u.PropTypes.string,content:c.customPropTypes.contentShorthand},t.default=o},/*!********************************!*\ !*** ./~/lodash/_ListCache.js ***! \********************************/ function(e,t,r){function n(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}var o=r(/*! ./_listCacheClear */445),a=r(/*! ./_listCacheDelete */446),s=r(/*! ./_listCacheGet */447),l=r(/*! ./_listCacheHas */448),u=r(/*! ./_listCacheSet */449);n.prototype.clear=o,n.prototype.delete=a,n.prototype.get=s,n.prototype.has=l,n.prototype.set=u,e.exports=n},/*!*******************************!*\ !*** ./~/lodash/_SetCache.js ***! \*******************************/ function(e,t,r){function n(e){var t=-1,r=null==e?0:e.length;for(this.__data__=new o;++t<r;)this.add(e[t])}var o=r(/*! ./_MapCache */111),a=r(/*! ./_setCacheAdd */463),s=r(/*! ./_setCacheHas */464);n.prototype.add=n.prototype.push=a,n.prototype.has=s,e.exports=n},/*!****************************!*\ !*** ./~/lodash/_apply.js ***! \****************************/ function(e,t){function r(e,t,r){switch(r.length){case 0:return e.call(t);case 1:return e.call(t,r[0]);case 2:return e.call(t,r[0],r[1]);case 3:return e.call(t,r[0],r[1],r[2])}return e.apply(t,r)}e.exports=r},/*!************************************!*\ !*** ./~/lodash/_arrayIncludes.js ***! \************************************/ function(e,t,r){function n(e,t){var r=null==e?0:e.length;return!!r&&o(e,t,0)>-1}var o=r(/*! ./_baseIndexOf */229);e.exports=n},/*!**********************************!*\ !*** ./~/lodash/_arrayReduce.js ***! \**********************************/ function(e,t){function r(e,t,r,n){var o=-1,a=null==e?0:e.length;for(n&&a&&(r=e[++o]);++o<a;)r=t(r,e[o],o,e);return r}e.exports=r},/*!**********************************!*\ !*** ./~/lodash/_assignValue.js ***! \**********************************/ function(e,t,r){function n(e,t,r){var n=e[t];l.call(e,t)&&a(n,r)&&(void 0!==r||t in e)||o(e,t,r)}var o=r(/*! ./_baseAssignValue */115),a=r(/*! ./eq */42),s=Object.prototype,l=s.hasOwnProperty;e.exports=n},/*!***********************************!*\ !*** ./~/lodash/_assocIndexOf.js ***! \***********************************/ function(e,t,r){function n(e,t){for(var r=e.length;r--;)if(o(e[r][0],t))return r;return-1}var o=r(/*! ./eq */42);e.exports=n},/*!**********************************!*\ !*** ./~/lodash/_baseFlatten.js ***! \**********************************/ function(e,t,r){function n(e,t,r,s,l){var u=-1,i=e.length;for(r||(r=a),l||(l=[]);++u<i;){var c=e[u];t>0&&r(c)?t>1?n(c,t-1,r,s,l):o(l,c):s||(l[l.length]=c)}return l}var o=r(/*! ./_arrayPush */114),a=r(/*! ./_isFlattenable */442);e.exports=n},/*!******************************!*\ !*** ./~/lodash/_baseGet.js ***! \******************************/ function(e,t,r){function n(e,t){t=o(t,e);for(var r=0,n=t.length;null!=e&&r<n;)e=e[a(t[r++])];return r&&r==n?e:void 0}var o=r(/*! ./_castPath */25),a=r(/*! ./_toKey */22);e.exports=n},/*!********************************!*\ !*** ./~/lodash/_baseSlice.js ***! \********************************/ function(e,t){function r(e,t,r){var n=-1,o=e.length;t<0&&(t=-t>o?0:o+t),r=r>o?o:r,r<0&&(r+=o),o=t>r?0:r-t>>>0,t>>>=0;for(var a=Array(o);++n<o;)a[n]=e[n+t];return a}e.exports=r},/*!********************************!*\ !*** ./~/lodash/_baseUnary.js ***! \********************************/ function(e,t){function r(e){return function(t){return e(t)}}e.exports=r},/*!*******************************!*\ !*** ./~/lodash/_cacheHas.js ***! \*******************************/ function(e,t){function r(e,t){return e.has(t)}e.exports=r},/*!********************************!*\ !*** ./~/lodash/_copyArray.js ***! \********************************/ function(e,t){function r(e,t){var r=-1,n=e.length;for(t||(t=Array(n));++r<n;)t[r]=e[r];return t}e.exports=r},/*!*********************************!*\ !*** ./~/lodash/_createCtor.js ***! \*********************************/ function(e,t,r){function n(e){return function(){var t=arguments;switch(t.length){case 0:return new e;case 1:return new e(t[0]);case 2:return new e(t[0],t[1]);case 3:return new e(t[0],t[1],t[2]);case 4:return new e(t[0],t[1],t[2],t[3]);case 5:return new e(t[0],t[1],t[2],t[3],t[4]);case 6:return new e(t[0],t[1],t[2],t[3],t[4],t[5]);case 7:return new e(t[0],t[1],t[2],t[3],t[4],t[5],t[6])}var r=o(e.prototype),n=e.apply(r,t);return a(n)?n:r}}var o=r(/*! ./_baseCreate */37),a=r(/*! ./isObject */12);e.exports=n},/*!*******************************!*\ !*** ./~/lodash/_flatRest.js ***! \*******************************/ function(e,t,r){function n(e){return s(a(e,void 0,o),e+"")}var o=r(/*! ./flatten */485),a=r(/*! ./_overRest */252),s=r(/*! ./_setToString */127);e.exports=n},/*!********************************!*\ !*** ./~/lodash/_getHolder.js ***! \********************************/ function(e,t){function r(e){var t=e;return t.placeholder}e.exports=r},/*!*********************************!*\ !*** ./~/lodash/_getMapData.js ***! \*********************************/ function(e,t,r){function n(e,t){var r=e.__data__;return o(t)?r["string"==typeof t?"string":"hash"]:r.map}var o=r(/*! ./_isKeyable */443);e.exports=n},/*!***********************************!*\ !*** ./~/lodash/_getPrototype.js ***! \***********************************/ function(e,t,r){var n=r(/*! ./_overArg */126),o=n(Object.getPrototypeOf,Object);e.exports=o},/*!*************************************!*\ !*** ./~/lodash/_isIterateeCall.js ***! \*************************************/ function(e,t,r){function n(e,t,r){if(!l(r))return!1;var n=typeof t;return!!("number"==n?a(r)&&s(t,r.length):"string"==n&&t in r)&&o(r[t],e)}var o=r(/*! ./eq */42),a=r(/*! ./isArrayLike */14),s=r(/*! ./_isIndex */39),l=r(/*! ./isObject */12);e.exports=n},/*!***********************************!*\ !*** ./~/lodash/_nativeCreate.js ***! \***********************************/ function(e,t,r){var n=r(/*! ./_getNative */26),o=n(Object,"create");e.exports=o},/*!*********************************!*\ !*** ./~/lodash/_setToArray.js ***! \*********************************/ function(e,t){function r(e){var t=-1,r=Array(e.size);return e.forEach(function(e){r[++t]=e}),r}e.exports=r},/*!**************************!*\ !*** ./~/lodash/each.js ***! \**************************/ function(e,t,r){e.exports=r(/*! ./forEach */487)},/*!******************************!*\ !*** ./~/lodash/includes.js ***! \******************************/ function(e,t,r){function n(e,t,r,n){e=a(e)?e:u(e),r=r&&!n?l(r):0;var c=e.length;return r<0&&(r=i(c+r,0)),s(e)?r<=c&&e.indexOf(t,r)>-1:!!c&&o(e,t,r)>-1}var o=r(/*! ./_baseIndexOf */229),a=r(/*! ./isArrayLike */14),s=r(/*! ./isString */269),l=r(/*! ./toInteger */20),u=r(/*! ./values */134),i=Math.max;e.exports=n},/*!*********************************!*\ !*** ./~/lodash/isArguments.js ***! \*********************************/ function(e,t,r){var n=r(/*! ./_baseIsArguments */372),o=r(/*! ./isObjectLike */15),a=Object.prototype,s=a.hasOwnProperty,l=a.propertyIsEnumerable,u=n(function(){return arguments}())?n:function(e){return o(e)&&s.call(e,"callee")&&!l.call(e,"callee")};e.exports=u},/*!***************************************!*\ !*** ./~/lodash/isArrayLikeObject.js ***! \***************************************/ function(e,t,r){function n(e){return a(e)&&o(e)}var o=r(/*! ./isArrayLike */14),a=r(/*! ./isObjectLike */15);e.exports=n},/*!*****************************!*\ !*** ./~/lodash/isEqual.js ***! \*****************************/ function(e,t,r){function n(e,t){return o(e,t)}var o=r(/*! ./_baseIsEqual */118);e.exports=n},/*!**********************************!*\ !*** ./~/lodash/isTypedArray.js ***! \**********************************/ function(e,t,r){var n=r(/*! ./_baseIsTypedArray */377),o=r(/*! ./_baseUnary */63),a=r(/*! ./_nodeUtil */459),s=a&&a.isTypedArray,l=s?o(s):n;e.exports=l},/*!**************************!*\ !*** ./~/lodash/pick.js ***! \**************************/ function(e,t,r){var n=r(/*! ./_basePick */383),o=r(/*! ./_flatRest */67),a=o(function(e,t){return null==e?{}:n(e,t)});e.exports=a},/*!******************************!*\ !*** ./~/lodash/toNumber.js ***! \******************************/ function(e,t,r){function n(e){if("number"==typeof e)return e;if(a(e))return s;if(o(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=o(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=e.replace(l,"");var r=i.test(e);return r||c.test(e)?p(e.slice(2),r?2:8):u.test(e)?s:+e}var o=r(/*! ./isObject */12),a=r(/*! ./isSymbol */29),s=NaN,l=/^\s+|\s+$/g,u=/^[-+]0x[0-9a-f]+$/i,i=/^0b[01]+$/i,c=/^0o[0-7]+$/i,p=parseInt;e.exports=n},/*!***********************************!*\ !*** ./src/addons/Radio/index.js ***! \***********************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var o=r(/*! ./Radio */282),a=n(o);t.default=a.default},/*!************************************************!*\ !*** ./src/collections/Message/MessageItem.js ***! \************************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.children,r=e.className,n=(0,l.default)("content",r),s=(0,c.getUnhandledProps)(o,e),u=(0,c.getElementType)(o,e);return i.default.createElement(u,a({},s,{className:n}),t)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! classnames */3),l=n(s),u=r(/*! react */1),i=n(u),c=r(/*! ../../lib */2);o._meta={name:"MessageItem",parent:"Message",type:c.META.TYPES.COLLECTION},o.propTypes={as:c.customPropTypes.as,children:u.PropTypes.node,className:u.PropTypes.string},o.defaultProps={as:"li"},t.default=o},/*!**********************************************!*\ !*** ./src/collections/Table/TableHeader.js ***! \**********************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.children,r=e.className,n=e.fullWidth,s=(0,l.default)((0,c.useKeyOnly)(n,"full-width"),r),u=(0,c.getUnhandledProps)(o,e),p=(0,c.getElementType)(o,e);return i.default.createElement(p,a({},u,{className:s}),t)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! classnames */3),l=n(s),u=r(/*! react */1),i=n(u),c=r(/*! ../../lib */2);o._meta={name:"TableHeader",type:c.META.TYPES.COLLECTION,parent:"Table"},o.defaultProps={as:"thead"},o.propTypes={as:c.customPropTypes.as,children:u.PropTypes.node,className:u.PropTypes.string,fullWidth:u.PropTypes.bool},t.default=o},/*!**************************************!*\ !*** ./src/elements/Button/index.js ***! \**************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var o=r(/*! ./Button */160),a=n(o);t.default=a.default},/*!*************************************!*\ !*** ./src/elements/Input/index.js ***! \*************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var o=r(/*! ./Input */304),a=n(o);t.default=a.default},/*!*************************************!*\ !*** ./src/elements/Label/Label.js ***! \*************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var l=r(/*! lodash/isUndefined */133),u=n(l),i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},c=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),p=r(/*! classnames */3),d=n(p),f=r(/*! react */1),y=n(f),m=r(/*! ../../lib */2),h=r(/*! ../Icon/Icon */47),v=n(h),b=r(/*! ../Image/Image */168),g=n(b),P=r(/*! ./LabelDetail */170),T=n(P),O=r(/*! ./LabelGroup */171),_=n(O),E={name:"Label",type:m.META.TYPES.ELEMENT,props:{attached:["top","bottom","top right","top left","bottom left","bottom right"],color:m.SUI.COLORS,corner:["left","right"],pointing:["above","below","left","right"],ribbon:["right"],size:m.SUI.SIZES}},j=function(e){function t(){var e,r,n,s;o(this,t);for(var l=arguments.length,u=Array(l),i=0;i<l;i++)u[i]=arguments[i];return r=n=a(this,(e=t.__proto__||Object.getPrototypeOf(t)).call.apply(e,[this].concat(u))),n.handleClick=function(e){var t=n.props.onClick;t&&t(e,n.props)},n.handleRemove=function(e){var t=n.props.onRemove;t&&t(e,n.props)},s=r,a(n,s)}return s(t,e),c(t,[{key:"render",value:function(){var e=this.props,r=e.active,n=e.attached,o=e.basic,a=e.children,s=e.circular,l=e.className,c=e.color,p=e.content,f=e.corner,h=e.detail,b=e.empty,P=e.floating,O=e.horizontal,_=e.icon,E=e.image,j=e.onRemove,w=e.pointing,S=e.removeIcon,M=e.ribbon,x=e.size,k=e.tag,A=w===!0&&"pointing"||("left"===w||"right"===w)&&w+" pointing"||("above"===w||"below"===w)&&"pointing "+w,C=(0,d.default)("ui",c,A,x,(0,m.useKeyOnly)(r,"active"),(0,m.useKeyOnly)(o,"basic"),(0,m.useKeyOnly)(s,"circular"),(0,m.useKeyOnly)(b,"empty"),(0,m.useKeyOnly)(P,"floating"),(0,m.useKeyOnly)(O,"horizontal"),(0,m.useKeyOnly)(E===!0,"image"),(0,m.useKeyOnly)(k,"tag"),(0,m.useKeyOrValueAndKey)(f,"corner"),(0,m.useKeyOrValueAndKey)(M,"ribbon"),(0,m.useValueAndKey)(n,"attached"),"label",l),N=(0,m.getUnhandledProps)(t,this.props),I=(0,m.getElementType)(t,this.props);if(a)return y.default.createElement(I,i({},N,{className:C,onClick:this.handleClick}),a);var K=(0,u.default)(S)?"delete":S;return y.default.createElement(I,i({className:C,onClick:this.handleClick},N),v.default.create(_),"boolean"!=typeof E&&g.default.create(E),p,(0,m.createShorthand)(T.default,function(e){return{content:e}},h),j&&v.default.create(K,{onClick:this.handleRemove}))}}]),t}(f.Component);j.propTypes={as:m.customPropTypes.as,active:f.PropTypes.bool,attached:f.PropTypes.oneOf(E.props.attached),basic:f.PropTypes.bool,children:f.PropTypes.node,circular:f.PropTypes.bool,className:f.PropTypes.string,color:f.PropTypes.oneOf(E.props.color),content:m.customPropTypes.contentShorthand,corner:f.PropTypes.oneOfType([f.PropTypes.bool,f.PropTypes.oneOf(E.props.corner)]),detail:m.customPropTypes.itemShorthand,empty:m.customPropTypes.every([m.customPropTypes.demand(["circular"]),f.PropTypes.bool]),floating:f.PropTypes.bool,horizontal:f.PropTypes.bool,icon:m.customPropTypes.itemShorthand,image:f.PropTypes.oneOfType([f.PropTypes.bool,m.customPropTypes.itemShorthand]),pointing:f.PropTypes.oneOfType([f.PropTypes.bool,f.PropTypes.oneOf(E.props.pointing)]),onClick:f.PropTypes.func,onRemove:f.PropTypes.func,removeIcon:m.customPropTypes.itemShorthand,ribbon:f.PropTypes.oneOfType([f.PropTypes.bool,f.PropTypes.oneOf(E.props.ribbon)]),size:f.PropTypes.oneOf(E.props.size),tag:f.PropTypes.bool},j._meta=E,j.Detail=T.default,j.Group=_.default,t.default=j,j.create=(0,m.createShorthandFactory)(j,function(e){return{content:e}})},/*!******************************************!*\ !*** ./src/elements/List/ListContent.js ***! \******************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.children,r=e.className,n=e.content,s=e.description,u=e.floated,p=e.header,f=e.verticalAlign,m=(0,l.default)((0,c.useValueAndKey)(u,"floated"),(0,c.useVerticalAlignProp)(f),"content",r),h=(0,c.getUnhandledProps)(o,e),v=(0,c.getElementType)(o,e);return t?i.default.createElement(v,a({},h,{className:m}),t):i.default.createElement(v,a({},h,{className:m}),y.default.create(p),d.default.create(s),n)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! classnames */3),l=n(s),u=r(/*! react */1),i=n(u),c=r(/*! ../../lib */2),p=r(/*! ./ListDescription */49),d=n(p),f=r(/*! ./ListHeader */50),y=n(f);o._meta={name:"ListContent",parent:"List",type:c.META.TYPES.ELEMENT,props:{floated:c.SUI.FLOATS,verticalAlign:c.SUI.VERTICAL_ALIGNMENTS}},o.propTypes={as:c.customPropTypes.as,children:u.PropTypes.node,className:u.PropTypes.string,content:c.customPropTypes.contentShorthand,description:c.customPropTypes.itemShorthand,floated:u.PropTypes.oneOf(o._meta.props.floated),header:c.customPropTypes.itemShorthand,verticalAlign:u.PropTypes.oneOf(o._meta.props.verticalAlign)},o.create=(0,c.createShorthandFactory)(o,function(e){return{content:e}}),t.default=o},/*!***************************************!*\ !*** ./src/elements/List/ListIcon.js ***! \***************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.className,r=e.verticalAlign,n=(0,l.default)((0,c.useVerticalAlignProp)(r),t),s=(0,c.getUnhandledProps)(o,e);return i.default.createElement(d.default,a({},s,{className:n}))}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! classnames */3),l=n(s),u=r(/*! react */1),i=n(u),c=r(/*! ../../lib */2),p=r(/*! ../Icon/Icon */47),d=n(p);o._meta={name:"ListIcon",parent:"List",type:c.META.TYPES.ELEMENT,props:{verticalAlign:c.SUI.VERTICAL_ALIGNMENTS}},o.propTypes={className:u.PropTypes.string,verticalAlign:u.PropTypes.oneOf(o._meta.props.verticalAlign)},o.create=(0,c.createShorthandFactory)(o,function(e){return{name:e}}),t.default=o},/*!**********************************************!*\ !*** ./src/elements/Step/StepDescription.js ***! \**********************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.children,r=e.className,n=e.description,s=(0,l.default)(r,"description"),u=(0,c.getUnhandledProps)(o,e),p=(0,c.getElementType)(o,e);return i.default.createElement(p,a({},u,{className:s}),t||n)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! classnames */3),l=n(s),u=r(/*! react */1),i=n(u),c=r(/*! ../../lib */2);o._meta={name:"StepDescription",parent:"Step",type:c.META.TYPES.ELEMENT},o.propTypes={as:c.customPropTypes.as,className:u.PropTypes.string,children:u.PropTypes.node,description:c.customPropTypes.contentShorthand},t.default=o},/*!****************************************!*\ !*** ./src/elements/Step/StepTitle.js ***! \****************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.children,r=e.className,n=e.title,s=(0,l.default)(r,"title"),u=(0,c.getUnhandledProps)(o,e),p=(0,c.getElementType)(o,e);return i.default.createElement(p,a({},u,{className:s}),t||n)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! classnames */3),l=n(s),u=r(/*! react */1),i=n(u),c=r(/*! ../../lib */2);o._meta={name:"StepTitle",parent:"Step",type:c.META.TYPES.ELEMENT},o.propTypes={as:c.customPropTypes.as,className:u.PropTypes.string,children:u.PropTypes.node,title:c.customPropTypes.contentShorthand},t.default=o},/*!*********************************!*\ !*** ./src/lib/numberToWord.js ***! \*********************************/ function(e,t){"use strict";function r(e){var t="undefined"==typeof e?"undefined":n(e);return"string"===t||"number"===t?o[e]||e:""}Object.defineProperty(t,"__esModule",{value:!0});var n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};t.numberToWord=r;var o=t.numberToWordMap={1:"one",2:"two",3:"three",4:"four",5:"five",6:"six",7:"seven",8:"eight",9:"nine",10:"ten",11:"eleven",12:"twelve",13:"thirteen",14:"fourteen",15:"fifteen",16:"sixteen"}},/*!***************************************!*\ !*** ./src/modules/Dropdown/index.js ***! \***************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var o=r(/*! ./Dropdown */332),a=n(o);t.default=a.default},/*!*******************************************!*\ !*** ./src/views/Card/CardDescription.js ***! \*******************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.children,r=e.className,n=e.content,s=(0,l.default)(r,"description"),u=(0,c.getUnhandledProps)(o,e),p=(0,c.getElementType)(o,e);return i.default.createElement(p,a({},u,{className:s}),t||n)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! classnames */3),l=n(s),u=r(/*! react */1),i=n(u),c=r(/*! ../../lib */2);o._meta={name:"CardDescription",parent:"Card",type:c.META.TYPES.VIEW},o.propTypes={as:c.customPropTypes.as,children:u.PropTypes.node,className:u.PropTypes.string,content:c.customPropTypes.contentShorthand},t.default=o},/*!**************************************!*\ !*** ./src/views/Card/CardHeader.js ***! \**************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.children,r=e.className,n=e.content,s=(0,l.default)(r,"header"),u=(0,c.getUnhandledProps)(o,e),p=(0,c.getElementType)(o,e);return i.default.createElement(p,a({},u,{className:s}),t||n)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! classnames */3),l=n(s),u=r(/*! react */1),i=n(u),c=r(/*! ../../lib */2);o._meta={name:"CardHeader",parent:"Card",type:c.META.TYPES.VIEW},o.propTypes={as:c.customPropTypes.as,children:u.PropTypes.node,className:u.PropTypes.string,content:c.customPropTypes.contentShorthand},t.default=o},/*!************************************!*\ !*** ./src/views/Card/CardMeta.js ***! \************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.children,r=e.className,n=e.content,s=(0,l.default)(r,"meta"),u=(0,c.getUnhandledProps)(o,e),p=(0,c.getElementType)(o,e);return i.default.createElement(p,a({},u,{className:s}),t||n)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! classnames */3),l=n(s),u=r(/*! react */1),i=n(u),c=r(/*! ../../lib */2);o._meta={name:"CardMeta",parent:"Card",type:c.META.TYPES.VIEW},o.propTypes={as:c.customPropTypes.as,children:u.PropTypes.node,className:u.PropTypes.string,content:c.customPropTypes.contentShorthand},t.default=o},/*!***************************************!*\ !*** ./src/views/Feed/FeedContent.js ***! \***************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.children,r=e.className,n=e.content,s=e.extraImages,u=e.extraText,p=e.date,f=e.meta,m=e.summary,v=(0,l.default)(r,"content"),g=(0,c.getUnhandledProps)(o,e),P=(0,c.getElementType)(o,e);return t?i.default.createElement(P,a({},g,{className:v}),t):i.default.createElement(P,a({},g,{className:v}),(0,c.createShorthand)(d.default,function(e){return{content:e}},p),(0,c.createShorthand)(b.default,function(e){return{content:e}},m),n,(0,c.createShorthand)(y.default,function(e){return{text:!0,content:e}},u),(0,c.createShorthand)(y.default,function(e){return{images:e}},s),(0,c.createShorthand)(h.default,function(e){return{content:e}},f))}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! classnames */3),l=n(s),u=r(/*! react */1),i=n(u),c=r(/*! ../../lib */2),p=r(/*! ./FeedDate */52),d=n(p),f=r(/*! ./FeedExtra */98),y=n(f),m=r(/*! ./FeedMeta */101),h=n(m),v=r(/*! ./FeedSummary */102),b=n(v);o._meta={name:"FeedContent",parent:"Feed",type:c.META.TYPES.VIEW},o.propTypes={as:c.customPropTypes.as,children:u.PropTypes.node,className:u.PropTypes.string,content:c.customPropTypes.contentShorthand,date:c.customPropTypes.itemShorthand,extraImages:y.default.propTypes.images,extraText:c.customPropTypes.itemShorthand,meta:c.customPropTypes.itemShorthand,summary:c.customPropTypes.itemShorthand},t.default=o},/*!*************************************!*\ !*** ./src/views/Feed/FeedExtra.js ***! \*************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.children,r=e.className,n=e.content,a=e.images,u=e.text,c=(0,i.default)(r,(0,d.useKeyOnly)(a,"images"),(0,d.useKeyOnly)(n||u,"text"),"extra"),f=(0,d.getUnhandledProps)(o,e),y=(0,d.getElementType)(o,e);if(t)return p.default.createElement(y,l({},f,{className:c}),t);var m=(0,s.default)(a,function(e,t){var r=[t,e].join("-");return(0,d.createHTMLImage)(e,{key:r})});return p.default.createElement(y,l({},f,{className:c}),n,m)}Object.defineProperty(t,"__esModule",{value:!0});var a=r(/*! lodash/map */10),s=n(a),l=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},u=r(/*! classnames */3),i=n(u),c=r(/*! react */1),p=n(c),d=r(/*! ../../lib */2);o._meta={name:"FeedExtra",parent:"Feed",type:d.META.TYPES.VIEW},o.propTypes={as:d.customPropTypes.as,children:c.PropTypes.node,className:c.PropTypes.string,content:d.customPropTypes.contentShorthand,images:d.customPropTypes.every([d.customPropTypes.disallow(["text"]),c.PropTypes.oneOfType([c.PropTypes.bool,d.customPropTypes.collectionShorthand])]),text:c.PropTypes.bool},t.default=o},/*!*************************************!*\ !*** ./src/views/Feed/FeedLabel.js ***! \*************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.children,r=e.className,n=e.content,s=e.icon,u=e.image,p=(0,l.default)(r,"label"),f=(0,c.getUnhandledProps)(o,e),y=(0,c.getElementType)(o,e);return t?i.default.createElement(y,a({},f,{className:p}),t):i.default.createElement(y,a({},f,{className:p}),n,d.default.create(s),(0,c.createHTMLImage)(u))}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! classnames */3),l=n(s),u=r(/*! react */1),i=n(u),c=r(/*! ../../lib */2),p=r(/*! ../../elements/Icon */8),d=n(p);o._meta={name:"FeedLabel",parent:"Feed",type:c.META.TYPES.VIEW},o.propTypes={as:c.customPropTypes.as,children:u.PropTypes.node,className:u.PropTypes.string,content:c.customPropTypes.contentShorthand,icon:c.customPropTypes.itemShorthand,image:c.customPropTypes.itemShorthand},t.default=o},/*!************************************!*\ !*** ./src/views/Feed/FeedLike.js ***! \************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.children,r=e.className,n=e.content,s=e.icon,u=(0,l.default)(r,"like"),p=(0,c.getUnhandledProps)(o,e),f=(0,c.getElementType)(o,e);return t?i.default.createElement(f,a({},p,{className:u}),t):i.default.createElement(f,a({},p,{className:u}),d.default.create(s),n)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! classnames */3),l=n(s),u=r(/*! react */1),i=n(u),c=r(/*! ../../lib */2),p=r(/*! ../../elements/Icon */8),d=n(p);o._meta={name:"FeedLike",parent:"Feed",type:c.META.TYPES.VIEW},o.defaultProps={as:"a"},o.propTypes={as:c.customPropTypes.as,children:u.PropTypes.node,className:u.PropTypes.string,content:c.customPropTypes.contentShorthand,icon:c.customPropTypes.itemShorthand},t.default=o},/*!************************************!*\ !*** ./src/views/Feed/FeedMeta.js ***! \************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.children,r=e.className,n=e.content,s=e.like,u=(0,l.default)(r,"meta"),p=(0,c.getUnhandledProps)(o,e),f=(0,c.getElementType)(o,e);return t?i.default.createElement(f,a({},p,{className:u}),t):i.default.createElement(f,a({},p,{className:u}),(0,c.createShorthand)(d.default,function(e){return{content:e}},s),n)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! classnames */3),l=n(s),u=r(/*! react */1),i=n(u),c=r(/*! ../../lib */2),p=r(/*! ./FeedLike */100),d=n(p);o._meta={name:"FeedMeta",parent:"Feed",type:c.META.TYPES.VIEW},o.propTypes={as:c.customPropTypes.as,children:u.PropTypes.node,className:u.PropTypes.string,content:c.customPropTypes.contentShorthand,like:c.customPropTypes.itemShorthand},t.default=o},/*!***************************************!*\ !*** ./src/views/Feed/FeedSummary.js ***! \***************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.children,r=e.className,n=e.content,s=e.date,u=e.user,p=(0,l.default)(r,"summary"),f=(0,c.getUnhandledProps)(o,e),m=(0,c.getElementType)(o,e);return t?i.default.createElement(m,a({},f,{className:p}),t):i.default.createElement(m,a({},f,{className:p}),(0,c.createShorthand)(y.default,function(e){return{content:e}},u),n,(0,c.createShorthand)(d.default,function(e){return{content:e}},s))}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! classnames */3),l=n(s),u=r(/*! react */1),i=n(u),c=r(/*! ../../lib */2),p=r(/*! ./FeedDate */52),d=n(p),f=r(/*! ./FeedUser */103),y=n(f);o._meta={name:"FeedSummary",parent:"Feed",type:c.META.TYPES.VIEW},o.propTypes={as:c.customPropTypes.as,children:u.PropTypes.node,className:u.PropTypes.string,content:c.customPropTypes.contentShorthand,date:c.customPropTypes.itemShorthand,user:c.customPropTypes.itemShorthand},t.default=o},/*!************************************!*\ !*** ./src/views/Feed/FeedUser.js ***! \************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.children,r=e.className,n=e.content,s=(0,l.default)(r,"user"),u=(0,c.getUnhandledProps)(o,e),p=(0,c.getElementType)(o,e);return i.default.createElement(p,a({},u,{className:s}),t||n)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! classnames */3),l=n(s),u=r(/*! react */1),i=n(u),c=r(/*! ../../lib */2);o._meta={name:"FeedUser",parent:"Feed",type:c.META.TYPES.VIEW},o.propTypes={as:c.customPropTypes.as,children:u.PropTypes.node,className:u.PropTypes.string,content:c.customPropTypes.contentShorthand},o.defaultProps={as:"a"},t.default=o},/*!*******************************************!*\ !*** ./src/views/Item/ItemDescription.js ***! \*******************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.children,r=e.className,n=e.content,s=(0,l.default)(r,"description"),u=(0,c.getUnhandledProps)(o,e),p=(0,c.getElementType)(o,e);return i.default.createElement(p,a({},u,{className:s}),t||n)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! classnames */3),l=n(s),u=r(/*! react */1),i=n(u),c=r(/*! ../../lib */2);o._meta={name:"ItemDescription",parent:"Item",type:c.META.TYPES.VIEW},o.propTypes={as:c.customPropTypes.as,children:u.PropTypes.node,className:u.PropTypes.string,content:c.customPropTypes.contentShorthand},t.default=o},/*!*************************************!*\ !*** ./src/views/Item/ItemExtra.js ***! \*************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.children,r=e.className,n=e.content,s=(0,l.default)(r,"extra"),u=(0,c.getUnhandledProps)(o,e),p=(0,c.getElementType)(o,e);return i.default.createElement(p,a({},u,{className:s}),t||n)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! classnames */3),l=n(s),u=r(/*! react */1),i=n(u),c=r(/*! ../../lib */2);o._meta={name:"ItemExtra",parent:"Item",type:c.META.TYPES.VIEW},o.propTypes={as:c.customPropTypes.as,children:u.PropTypes.node,className:u.PropTypes.string,content:c.customPropTypes.contentShorthand},t.default=o},/*!**************************************!*\ !*** ./src/views/Item/ItemHeader.js ***! \**************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.children,r=e.className,n=e.content,s=(0,l.default)(r,"header"),u=(0,c.getUnhandledProps)(o,e),p=(0,c.getElementType)(o,e);return i.default.createElement(p,a({},u,{className:s}),t||n)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! classnames */3),l=n(s),u=r(/*! react */1),i=n(u),c=r(/*! ../../lib */2);o._meta={name:"ItemHeader",parent:"Item",type:c.META.TYPES.VIEW},o.propTypes={as:c.customPropTypes.as,children:u.PropTypes.node,className:u.PropTypes.string,content:c.customPropTypes.contentShorthand},t.default=o},/*!************************************!*\ !*** ./src/views/Item/ItemMeta.js ***! \************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.children,r=e.className,n=e.content,s=(0,l.default)(r,"meta"),u=(0,c.getUnhandledProps)(o,e),p=(0,c.getElementType)(o,e);return i.default.createElement(p,a({},u,{className:s}),t||n)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! classnames */3),l=n(s),u=r(/*! react */1),i=n(u),c=r(/*! ../../lib */2);o._meta={name:"ItemMeta",parent:"Item",type:c.META.TYPES.VIEW},o.propTypes={as:c.customPropTypes.as,children:u.PropTypes.node,className:u.PropTypes.string,content:c.customPropTypes.contentShorthand},t.default=o},/*!**********************************!*\ !*** ./~/lodash/_LazyWrapper.js ***! \**********************************/ function(e,t,r){function n(e){this.__wrapped__=e,this.__actions__=[],this.__dir__=1,this.__filtered__=!1,this.__iteratees__=[],this.__takeCount__=s,this.__views__=[]}var o=r(/*! ./_baseCreate */37),a=r(/*! ./_baseLodash */120),s=4294967295;n.prototype=o(a.prototype),n.prototype.constructor=n,e.exports=n},/*!************************************!*\ !*** ./~/lodash/_LodashWrapper.js ***! \************************************/ function(e,t,r){function n(e,t){this.__wrapped__=e,this.__actions__=[],this.__chain__=!!t,this.__index__=0,this.__values__=void 0}var o=r(/*! ./_baseCreate */37),a=r(/*! ./_baseLodash */120);n.prototype=o(a.prototype),n.prototype.constructor=n,e.exports=n},/*!**************************!*\ !*** ./~/lodash/_Map.js ***! \**************************/ function(e,t,r){var n=r(/*! ./_getNative */26),o=r(/*! ./_root */11),a=n(o,"Map");e.exports=a},/*!*******************************!*\ !*** ./~/lodash/_MapCache.js ***! \*******************************/ function(e,t,r){function n(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}var o=r(/*! ./_mapCacheClear */450),a=r(/*! ./_mapCacheDelete */451),s=r(/*! ./_mapCacheGet */452),l=r(/*! ./_mapCacheHas */453),u=r(/*! ./_mapCacheSet */454);n.prototype.clear=o,n.prototype.delete=a,n.prototype.get=s,n.prototype.has=l,n.prototype.set=u,e.exports=n},/*!****************************!*\ !*** ./~/lodash/_Stack.js ***! \****************************/ function(e,t,r){function n(e){var t=this.__data__=new o(e);this.size=t.size}var o=r(/*! ./_ListCache */53),a=r(/*! ./_stackClear */465),s=r(/*! ./_stackDelete */466),l=r(/*! ./_stackGet */467),u=r(/*! ./_stackHas */468),i=r(/*! ./_stackSet */469);n.prototype.clear=a,n.prototype.delete=s,n.prototype.get=l,n.prototype.has=u,n.prototype.set=i,e.exports=n},/*!****************************************!*\ !*** ./~/lodash/_arrayIncludesWith.js ***! \****************************************/ function(e,t){function r(e,t,r){for(var n=-1,o=null==e?0:e.length;++n<o;)if(r(t,e[n]))return!0;return!1}e.exports=r},/*!********************************!*\ !*** ./~/lodash/_arrayPush.js ***! \********************************/ function(e,t){function r(e,t){for(var r=-1,n=t.length,o=e.length;++r<n;)e[o+r]=t[r];return e}e.exports=r},/*!**************************************!*\ !*** ./~/lodash/_baseAssignValue.js ***! \**************************************/ function(e,t,r){function n(e,t,r){"__proto__"==t&&o?o(e,t,{configurable:!0,enumerable:!0,value:r,writable:!0}):e[t]=r}var o=r(/*! ./_defineProperty */239);e.exports=n},/*!********************************!*\ !*** ./~/lodash/_baseClone.js ***! \********************************/ function(e,t,r){function n(e,t,r,S,M,x){var k,N=t&_,I=t&E,L=t&j;if(r&&(k=M?r(e,S,M,x):r(e)),void 0!==k)return k;if(!T(e))return e;var U=g(e);if(U){if(k=h(e),!N)return c(e,k)}else{var D=m(e),R=D==A||D==C;if(P(e))return i(e,N);if(D==K||D==w||R&&!M){if(k=I||R?{}:b(e),!N)return I?d(e,u(k,e)):p(e,l(k,e))}else{if(!Q[D])return M?e:{};k=v(e,D,n,N)}}x||(x=new o);var z=x.get(e);if(z)return z;x.set(e,k);var W=L?I?y:f:I?keysIn:O,F=U?void 0:W(e);return a(F||e,function(o,a){F&&(a=o,o=e[a]),s(k,a,n(o,t,r,a,e,x))}),k}var o=r(/*! ./_Stack */112),a=r(/*! ./_arrayEach */36),s=r(/*! ./_assignValue */58),l=r(/*! ./_baseAssign */224),u=r(/*! ./_baseAssignIn */362),i=r(/*! ./_cloneBuffer */399),c=r(/*! ./_copyArray */65),p=r(/*! ./_copySymbols */408),d=r(/*! ./_copySymbolsIn */409),f=r(/*! ./_getAllKeys */427),y=r(/*! ./_getAllKeysIn */242),m=r(/*! ./_getTag */124),h=r(/*! ./_initCloneArray */438),v=r(/*! ./_initCloneByTag */439),b=r(/*! ./_initCloneObject */440),g=r(/*! ./isArray */4),P=r(/*! ./isBuffer */43),T=r(/*! ./isObject */12),O=r(/*! ./keys */9),_=1,E=2,j=4,w="[object Arguments]",S="[object Array]",M="[object Boolean]",x="[object Date]",k="[object Error]",A="[object Function]",C="[object GeneratorFunction]",N="[object Map]",I="[object Number]",K="[object Object]",L="[object RegExp]",U="[object Set]",D="[object String]",R="[object Symbol]",z="[object WeakMap]",W="[object ArrayBuffer]",F="[object DataView]",V="[object Float32Array]",B="[object Float64Array]",Y="[object Int8Array]",q="[object Int16Array]",H="[object Int32Array]",G="[object Uint8Array]",Z="[object Uint8ClampedArray]",$="[object Uint16Array]",X="[object Uint32Array]",Q={};Q[w]=Q[S]=Q[W]=Q[F]=Q[M]=Q[x]=Q[V]=Q[B]=Q[Y]=Q[q]=Q[H]=Q[N]=Q[I]=Q[K]=Q[L]=Q[U]=Q[D]=Q[R]=Q[G]=Q[Z]=Q[$]=Q[X]=!0,Q[k]=Q[A]=Q[z]=!1,e.exports=n},/*!*********************************!*\ !*** ./~/lodash/_baseForOwn.js ***! \*********************************/ function(e,t,r){function n(e,t){return e&&o(e,t,a)}var o=r(/*! ./_baseFor */366),a=r(/*! ./keys */9);e.exports=n},/*!**********************************!*\ !*** ./~/lodash/_baseIsEqual.js ***! \**********************************/ function(e,t,r){function n(e,t,r,l,u){return e===t||(null==e||null==t||!a(e)&&!s(t)?e!==e&&t!==t:o(e,t,r,l,n,u))}var o=r(/*! ./_baseIsEqualDeep */373),a=r(/*! ./isObject */12),s=r(/*! ./isObjectLike */15);e.exports=n},/*!*******************************!*\ !*** ./~/lodash/_baseKeys.js ***! \*******************************/ function(e,t,r){function n(e){if(!o(e))return a(e);var t=[];for(var r in Object(e))l.call(e,r)&&"constructor"!=r&&t.push(r);return t}var o=r(/*! ./_isPrototype */40),a=r(/*! ./_nativeKeys */457),s=Object.prototype,l=s.hasOwnProperty;e.exports=n},/*!*********************************!*\ !*** ./~/lodash/_baseLodash.js ***! \*********************************/ function(e,t){function r(){}e.exports=r},/*!***************************************!*\ !*** ./~/lodash/_cloneArrayBuffer.js ***! \***************************************/ function(e,t,r){function n(e){var t=new e.constructor(e.byteLength);return new o(t).set(new o(e)),t}var o=r(/*! ./_Uint8Array */220);e.exports=n},/*!******************************!*\ !*** ./~/lodash/_getData.js ***! \******************************/ function(e,t,r){var n=r(/*! ./_metaMap */251),o=r(/*! ./noop */272),a=n?function(e){return n.get(e)}:o;e.exports=a},/*!*********************************!*\ !*** ./~/lodash/_getSymbols.js ***! \*********************************/ function(e,t,r){var n=r(/*! ./_overArg */126),o=r(/*! ./stubArray */276),a=Object.getOwnPropertySymbols,s=a?n(a,Object):o;e.exports=s},/*!*****************************!*\ !*** ./~/lodash/_getTag.js ***! \*****************************/ function(e,t,r){var n=r(/*! ./_DataView */353),o=r(/*! ./_Map */110),a=r(/*! ./_Promise */355),s=r(/*! ./_Set */219),l=r(/*! ./_WeakMap */221),u=r(/*! ./_baseGetTag */21),i=r(/*! ./_toSource */258),c="[object Map]",p="[object Object]",d="[object Promise]",f="[object Set]",y="[object WeakMap]",m="[object DataView]",h=i(n),v=i(o),b=i(a),g=i(s),P=i(l),T=u;(n&&T(new n(new ArrayBuffer(1)))!=m||o&&T(new o)!=c||a&&T(a.resolve())!=d||s&&T(new s)!=f||l&&T(new l)!=y)&&(T=function(e){var t=u(e),r=t==p?e.constructor:void 0,n=r?i(r):"";if(n)switch(n){case h:return m;case v:return c;case b:return d;case g:return f;case P:return y}return t}),e.exports=T},/*!****************************!*\ !*** ./~/lodash/_isKey.js ***! \****************************/ function(e,t,r){function n(e,t){if(o(e))return!1;var r=typeof e;return!("number"!=r&&"symbol"!=r&&"boolean"!=r&&null!=e&&!a(e))||(l.test(e)||!s.test(e)||null!=t&&e in Object(t))}var o=r(/*! ./isArray */4),a=r(/*! ./isSymbol */29),s=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,l=/^\w*$/;e.exports=n},/*!******************************!*\ !*** ./~/lodash/_overArg.js ***! \******************************/ function(e,t){function r(e,t){return function(r){return e(t(r))}}e.exports=r},/*!**********************************!*\ !*** ./~/lodash/_setToString.js ***! \**********************************/ function(e,t,r){var n=r(/*! ./_baseSetToString */390),o=r(/*! ./_shortOut */256),a=o(n);e.exports=a},/*!****************************!*\ !*** ./~/lodash/filter.js ***! \****************************/ function(e,t,r){function n(e,t){var r=l(e)?o:a;return r(e,s(t,3))}var o=r(/*! ./_arrayFilter */359),a=r(/*! ./_baseFilter */365),s=r(/*! ./_baseIteratee */13),l=r(/*! ./isArray */4);e.exports=n},/*!**************************!*\ !*** ./~/lodash/find.js ***! \**************************/ function(e,t,r){var n=r(/*! ./_createFind */419),o=r(/*! ./findIndex */262),a=n(o);e.exports=a},/*!*****************************!*\ !*** ./~/lodash/isEmpty.js ***! \*****************************/ function(e,t,r){function n(e){if(null==e)return!0;if(u(e)&&(l(e)||"string"==typeof e||"function"==typeof e.splice||i(e)||p(e)||s(e)))return!e.length;var t=a(e);if(t==d||t==f)return!e.size;if(c(e))return!o(e).length;for(var r in e)if(m.call(e,r))return!1;return!0}var o=r(/*! ./_baseKeys */119),a=r(/*! ./_getTag */124),s=r(/*! ./isArguments */76),l=r(/*! ./isArray */4),u=r(/*! ./isArrayLike */14),i=r(/*! ./isBuffer */43),c=r(/*! ./_isPrototype */40),p=r(/*! ./isTypedArray */79),d="[object Map]",f="[object Set]",y=Object.prototype,m=y.hasOwnProperty;e.exports=n},/*!******************************!*\ !*** ./~/lodash/isLength.js ***! \******************************/ function(e,t){function r(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=n}var n=9007199254740991;e.exports=r},/*!***********************************!*\ !*** ./~/lodash/isPlainObject.js ***! \***********************************/ function(e,t,r){function n(e){if(!s(e)||o(e)!=l)return!1;var t=a(e);if(null===t)return!0;var r=p.call(t,"constructor")&&t.constructor;return"function"==typeof r&&r instanceof r&&c.call(r)==d}var o=r(/*! ./_baseGetTag */21),a=r(/*! ./_getPrototype */70),s=r(/*! ./isObjectLike */15),l="[object Object]",u=Function.prototype,i=Object.prototype,c=u.toString,p=i.hasOwnProperty,d=c.call(Object);e.exports=n},/*!*********************************!*\ !*** ./~/lodash/isUndefined.js ***! \*********************************/ function(e,t){function r(e){return void 0===e}e.exports=r},/*!****************************!*\ !*** ./~/lodash/values.js ***! \****************************/ function(e,t,r){function n(e){return null==e?[]:o(e,a(e))}var o=r(/*! ./_baseValues */396),a=r(/*! ./keys */9);e.exports=n},/*!***********************************!*\ !*** (webpack)/buildin/module.js ***! \***********************************/ function(e,t){e.exports=function(e){return e.webpackPolyfill||(e.deprecate=function(){},e.paths=[],e.children=[],e.webpackPolyfill=1),e}},/*!************************************!*\ !*** ./src/addons/Select/index.js ***! \************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var o=r(/*! ./Select */283),a=n(o);t.default=a.default},/*!**************************************!*\ !*** ./src/addons/TextArea/index.js ***! \**************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var o=r(/*! ./TextArea */284),a=n(o);t.default=a.default},/*!*********************************************************!*\ !*** ./src/collections/Breadcrumb/BreadcrumbDivider.js ***! \*********************************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.children,r=e.content,n=e.icon,s=e.className,u=(0,l.default)(s,"divider"),p=(0,c.getUnhandledProps)(o,e),f=(0,c.getElementType)(o,e);return n?d.default.create(n,a({},p,{className:u})):i.default.createElement(f,a({},p,{className:u}),r||t||"/")}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! classnames */3),l=n(s),u=r(/*! react */1),i=n(u),c=r(/*! ../../lib */2),p=r(/*! ../../elements/Icon */8),d=n(p);o._meta={name:"BreadcrumbDivider",type:c.META.TYPES.COLLECTION,parent:"Breadcrumb"},o.propTypes={as:c.customPropTypes.as,children:u.PropTypes.node,className:u.PropTypes.string,content:c.customPropTypes.contentShorthand,icon:c.customPropTypes.itemShorthand},o.create=(0,c.createShorthandFactory)(o,function(e){return{icon:e}}),t.default=o},/*!*********************************************************!*\ !*** ./src/collections/Breadcrumb/BreadcrumbSection.js ***! \*********************************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var l=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},u=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),i=r(/*! classnames */3),c=n(i),p=r(/*! react */1),d=n(p),f=r(/*! ../../lib */2),y=function(e){function t(){var e,r,n,s;o(this,t);for(var l=arguments.length,u=Array(l),i=0;i<l;i++)u[i]=arguments[i];return r=n=a(this,(e=t.__proto__||Object.getPrototypeOf(t)).call.apply(e,[this].concat(u))),n.handleClick=function(e){var t=n.props.onClick;t&&t(e)},s=r,a(n,s)}return s(t,e),u(t,[{key:"render",value:function(){var e=this.props,r=e.active,n=e.children,o=e.className,a=e.content,s=e.href,u=e.link,i=e.onClick,p=(0,c.default)((0,f.useKeyOnly)(r,"active"),"section",o),y=(0,f.getUnhandledProps)(t,this.props),m=(0,f.getElementType)(t,this.props,function(){if(u||i)return"a"});return d.default.createElement(m,l({},y,{className:p,href:s,onClick:this.handleClick}),n||a)}}]),t}(p.Component);y.propTypes={as:f.customPropTypes.as,active:p.PropTypes.bool,children:p.PropTypes.node,className:p.PropTypes.string,content:f.customPropTypes.contentShorthand,link:f.customPropTypes.every([f.customPropTypes.disallow(["href"]),p.PropTypes.bool]),href:f.customPropTypes.every([f.customPropTypes.disallow(["link"]),p.PropTypes.string]),onClick:p.PropTypes.func},y._meta={name:"BreadcrumbSection",type:f.META.TYPES.COLLECTION,parent:"Breadcrumb"},t.default=y,y.create=(0,f.createShorthandFactory)(y,function(e){return{content:e,link:!0}})},/*!********************************************!*\ !*** ./src/collections/Form/FormButton.js ***! \********************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.control,r=(0,u.getUnhandledProps)(o,e),n=(0,u.getElementType)(o,e);return l.default.createElement(n,a({},r,{control:t}))}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! react */1),l=n(s),u=r(/*! ../../lib */2),i=r(/*! ../../elements/Button */85),c=n(i),p=r(/*! ./FormField */16),d=n(p);o._meta={name:"FormButton",parent:"Form",type:u.META.TYPES.COLLECTION},o.propTypes={as:u.customPropTypes.as,control:d.default.propTypes.control},o.defaultProps={as:d.default,control:c.default},t.default=o},/*!**********************************************!*\ !*** ./src/collections/Form/FormCheckbox.js ***! \**********************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.control,r=(0,u.getUnhandledProps)(o,e),n=(0,u.getElementType)(o,e);return l.default.createElement(n,a({},r,{control:t}))}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! react */1),l=n(s),u=r(/*! ../../lib */2),i=r(/*! ../../modules/Checkbox */51),c=n(i),p=r(/*! ./FormField */16),d=n(p);o._meta={name:"FormCheckbox",parent:"Form",type:u.META.TYPES.COLLECTION},o.propTypes={as:u.customPropTypes.as,control:d.default.propTypes.control},o.defaultProps={as:d.default,control:c.default},t.default=o},/*!**********************************************!*\ !*** ./src/collections/Form/FormDropdown.js ***! \**********************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.control,r=(0,u.getUnhandledProps)(o,e),n=(0,u.getElementType)(o,e);return l.default.createElement(n,a({},r,{control:t}))}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! react */1),l=n(s),u=r(/*! ../../lib */2),i=r(/*! ../../modules/Dropdown */93),c=n(i),p=r(/*! ./FormField */16),d=n(p);o._meta={name:"FormDropdown",parent:"Form",type:u.META.TYPES.COLLECTION},o.propTypes={as:u.customPropTypes.as,control:d.default.propTypes.control},o.defaultProps={as:d.default,control:c.default},t.default=o},/*!*******************************************!*\ !*** ./src/collections/Form/FormGroup.js ***! \*******************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){if(Array.isArray(e)){for(var t=0,r=Array(e.length);t<e.length;t++)r[t]=e[t];return r}return Array.from(e)}function a(e){var t=e.children,r=e.className,n=e.grouped,o=e.inline,l=e.widths,i=(0,c.default)((0,p.useWidthProp)(l,null,!0),(0,p.useKeyOnly)(o,"inline"),(0,p.useKeyOnly)(n,"grouped"),"fields",r),d=(0,p.getUnhandledProps)(a,e),f=(0,p.getElementType)(a,e);return u.default.createElement(f,s({},d,{className:i}),t)}Object.defineProperty(t,"__esModule",{value:!0});var s=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},l=r(/*! react */1),u=n(l),i=r(/*! classnames */3),c=n(i),p=r(/*! ../../lib */2);a._meta={name:"FormGroup",parent:"Form",type:p.META.TYPES.COLLECTION,props:{widths:[].concat(o(p.SUI.WIDTHS),["equal"])}},a.propTypes={as:p.customPropTypes.as,children:l.PropTypes.node,className:l.PropTypes.string,grouped:p.customPropTypes.every([p.customPropTypes.disallow(["inline"]),l.PropTypes.bool]),inline:p.customPropTypes.every([p.customPropTypes.disallow(["grouped"]),l.PropTypes.bool]),widths:l.PropTypes.oneOf(a._meta.props.widths)},a.defaultProps={as:"div"},t.default=a},/*!*******************************************!*\ !*** ./src/collections/Form/FormInput.js ***! \*******************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.control,r=(0,u.getUnhandledProps)(o,e),n=(0,u.getElementType)(o,e);return l.default.createElement(n,a({},r,{control:t}))}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! react */1),l=n(s),u=r(/*! ../../lib */2),i=r(/*! ../../elements/Input */86),c=n(i),p=r(/*! ./FormField */16),d=n(p);o._meta={name:"FormInput",parent:"Form",type:u.META.TYPES.COLLECTION},o.propTypes={as:u.customPropTypes.as,control:d.default.propTypes.control},o.defaultProps={as:d.default,control:c.default},t.default=o},/*!*******************************************!*\ !*** ./src/collections/Form/FormRadio.js ***! \*******************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.control,r=(0,u.getUnhandledProps)(o,e),n=(0,u.getElementType)(o,e);return l.default.createElement(n,a({},r,{control:t}))}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! react */1),l=n(s),u=r(/*! ../../lib */2),i=r(/*! ../../addons/Radio */82),c=n(i),p=r(/*! ./FormField */16),d=n(p);o._meta={name:"FormRadio",parent:"Form",type:u.META.TYPES.COLLECTION},o.propTypes={as:u.customPropTypes.as,control:d.default.propTypes.control},o.defaultProps={as:d.default,control:c.default},t.default=o},/*!********************************************!*\ !*** ./src/collections/Form/FormSelect.js ***! \********************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.control,r=(0,u.getUnhandledProps)(o,e),n=(0,u.getElementType)(o,e);return l.default.createElement(n,a({},r,{control:t}))}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! react */1),l=n(s),u=r(/*! ../../lib */2),i=r(/*! ../../addons/Select */136),c=n(i),p=r(/*! ./FormField */16),d=n(p);o._meta={name:"FormSelect",parent:"Form",type:u.META.TYPES.COLLECTION},o.propTypes={as:u.customPropTypes.as,control:d.default.propTypes.control},o.defaultProps={as:d.default,control:c.default},t.default=o},/*!**********************************************!*\ !*** ./src/collections/Form/FormTextArea.js ***! \**********************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.control,r=(0,u.getUnhandledProps)(o,e),n=(0,u.getElementType)(o,e);return l.default.createElement(n,a({},r,{control:t}))}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! react */1),l=n(s),u=r(/*! ../../lib */2),i=r(/*! ../../addons/TextArea */137),c=n(i),p=r(/*! ./FormField */16),d=n(p);o._meta={name:"FormTextArea",parent:"Form",type:u.META.TYPES.COLLECTION},o.propTypes={as:u.customPropTypes.as,control:d.default.propTypes.control},o.defaultProps={as:d.default,control:c.default},t.default=o},/*!********************************************!*\ !*** ./src/collections/Grid/GridColumn.js ***! \********************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.children,r=e.className,n=e.computer,s=e.color,u=e.floated,p=e.largeScreen,d=e.mobile,f=e.only,y=e.stretched,m=e.tablet,h=e.textAlign,v=e.verticalAlign,b=e.widescreen,g=e.width,P=(0,l.default)(s,(0,c.useKeyOnly)(y,"stretched"),(0,c.useTextAlignProp)(h),(0,c.useValueAndKey)(u,"floated"),(0,c.useValueAndKey)(f,"only"),(0,c.useVerticalAlignProp)(v),(0,c.useWidthProp)(n,"wide computer"),(0,c.useWidthProp)(p,"wide large screen"),(0,c.useWidthProp)(d,"wide mobile"),(0,c.useWidthProp)(m,"wide tablet"),(0,c.useWidthProp)(b,"wide widescreen"),(0,c.useWidthProp)(g,"wide"),"column",r),T=(0,c.getUnhandledProps)(o,e),O=(0,c.getElementType)(o,e);return i.default.createElement(O,a({},T,{className:P}),t)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! classnames */3),l=n(s),u=r(/*! react */1),i=n(u),c=r(/*! ../../lib */2);o._meta={name:"GridColumn",parent:"Grid",type:c.META.TYPES.COLLECTION,props:{color:c.SUI.COLORS,computer:c.SUI.WIDTHS,floated:c.SUI.FLOATS,largeScreen:c.SUI.WIDTHS,mobile:c.SUI.WIDTHS,only:["computer","large screen","mobile","tablet mobile","tablet","widescreen"],tablet:c.SUI.WIDTHS,textAlign:c.SUI.TEXT_ALIGNMENTS,verticalAlign:c.SUI.VERTICAL_ALIGNMENTS,widescreen:c.SUI.WIDTHS,width:c.SUI.WIDTHS}},o.propTypes={as:c.customPropTypes.as,children:u.PropTypes.node,className:u.PropTypes.string,computer:u.PropTypes.oneOf(o._meta.props.width),color:u.PropTypes.oneOf(o._meta.props.color),floated:u.PropTypes.oneOf(o._meta.props.floated),largeScreen:u.PropTypes.oneOf(o._meta.props.width),mobile:u.PropTypes.oneOf(o._meta.props.width),only:u.PropTypes.oneOf(o._meta.props.only),stretched:u.PropTypes.bool,tablet:u.PropTypes.oneOf(o._meta.props.width),textAlign:u.PropTypes.oneOf(o._meta.props.textAlign),verticalAlign:u.PropTypes.oneOf(o._meta.props.verticalAlign),widescreen:u.PropTypes.oneOf(o._meta.props.width),width:u.PropTypes.oneOf(o._meta.props.width)},t.default=o},/*!*****************************************!*\ !*** ./src/collections/Grid/GridRow.js ***! \*****************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){if(Array.isArray(e)){for(var t=0,r=Array(e.length);t<e.length;t++)r[t]=e[t];return r}return Array.from(e)}function a(e){var t=e.centered,r=e.children,n=e.className,o=e.color,l=e.columns,i=e.divided,d=e.only,f=e.reversed,y=e.stretched,m=e.textAlign,h=e.verticalAlign,v=(0,u.default)(o,(0,p.useKeyOnly)(t,"centered"),(0,p.useKeyOnly)(i,"divided"),(0,p.useKeyOnly)(y,"stretched"),(0,p.useTextAlignProp)(m),(0,p.useValueAndKey)(d,"only"),(0,p.useValueAndKey)(f,"reversed"),(0,p.useVerticalAlignProp)(h),(0,p.useWidthProp)(l,"column",!0),"row",n),b=(0,p.getUnhandledProps)(a,e),g=(0,p.getElementType)(a,e);return c.default.createElement(g,s({},b,{className:v}),r)}Object.defineProperty(t,"__esModule",{value:!0});var s=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},l=r(/*! classnames */3),u=n(l),i=r(/*! react */1),c=n(i),p=r(/*! ../../lib */2);a._meta={name:"GridRow",parent:"Grid",type:p.META.TYPES.COLLECTION,props:{color:p.SUI.COLORS,columns:[].concat(o(p.SUI.WIDTHS),["equal"]),only:["computer","large screen","mobile","tablet mobile","tablet","widescreen"],reversed:["computer","computer vertically","mobile","mobile vertically","tablet","tablet vertically"],textAlign:p.SUI.TEXT_ALIGNMENTS,verticalAlign:p.SUI.VERTICAL_ALIGNMENTS}},a.propTypes={as:p.customPropTypes.as,centered:i.PropTypes.bool,children:i.PropTypes.node,className:i.PropTypes.string,color:i.PropTypes.oneOf(a._meta.props.color),columns:i.PropTypes.oneOf(a._meta.props.columns),divided:i.PropTypes.bool,only:i.PropTypes.oneOf(a._meta.props.only),reversed:i.PropTypes.oneOf(a._meta.props.reversed),stretched:i.PropTypes.bool,textAlign:i.PropTypes.oneOf(a._meta.props.textAlign),verticalAlign:i.PropTypes.oneOf(a._meta.props.verticalAlign)},t.default=a},/*!********************************************!*\ !*** ./src/collections/Menu/MenuHeader.js ***! \********************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.children,r=e.className,n=e.content,s=(0,l.default)(r,"header"),u=(0,c.getUnhandledProps)(o,e),p=(0,c.getElementType)(o,e);return i.default.createElement(p,a({},u,{className:s}),t||n)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! classnames */3),l=n(s),u=r(/*! react */1),i=n(u),c=r(/*! ../../lib */2);o._meta={name:"MenuHeader",type:c.META.TYPES.COLLECTION,parent:"Menu"},o.propTypes={as:c.customPropTypes.as,children:u.PropTypes.node,className:u.PropTypes.string,content:c.customPropTypes.contentShorthand},t.default=o},/*!******************************************!*\ !*** ./src/collections/Menu/MenuItem.js ***! \******************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var l=r(/*! lodash/startCase */521),u=n(l),i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},c=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),p=r(/*! classnames */3),d=n(p),f=r(/*! react */1),y=n(f),m=r(/*! ../../lib */2),h=r(/*! ../../elements/Icon */8),v=n(h),b={name:"MenuItem",type:m.META.TYPES.COLLECTION,parent:"Menu",props:{color:m.SUI.COLORS,fitted:["horizontally","vertically"],position:["right"]}},g=function(e){function t(){var e,r,n,s;o(this,t);for(var l=arguments.length,u=Array(l),i=0;i<l;i++)u[i]=arguments[i];return r=n=a(this,(e=t.__proto__||Object.getPrototypeOf(t)).call.apply(e,[this].concat(u))),n.handleClick=function(e){var t=n.props,r=t.index,o=t.name,a=t.onClick;a&&a(e,{name:o,index:r})},s=r,a(n,s)}return s(t,e),c(t,[{key:"render",value:function(){var e=this.props,r=e.active,n=e.children,o=e.className,a=e.color,s=e.content,l=e.fitted,c=e.header,p=e.icon,f=e.link,h=e.name,b=e.onClick,g=e.position,P=(0,d.default)(a,g,(0,m.useKeyOnly)(r,"active"),(0,m.useKeyOnly)(p===!0||p&&!(h||s),"icon"),(0,m.useKeyOnly)(c,"header"),(0,m.useKeyOnly)(f,"link"),(0,m.useKeyOrValueAndKey)(l,"fitted"),"item",o),T=(0,m.getElementType)(t,this.props,function(){if(b)return"a"}),O=(0,m.getUnhandledProps)(t,this.props);return n?y.default.createElement(T,i({},O,{className:P,onClick:this.handleClick}),n):y.default.createElement(T,i({},O,{className:P,onClick:this.handleClick}),v.default.create(p),s||(0,u.default)(h))}}]),t}(f.Component);g.propTypes={as:m.customPropTypes.as,active:f.PropTypes.bool,children:f.PropTypes.node,className:f.PropTypes.string,color:f.PropTypes.oneOf(b.props.color),content:m.customPropTypes.contentShorthand,fitted:f.PropTypes.oneOfType([f.PropTypes.bool,f.PropTypes.oneOf(b.props.fitted)]),header:f.PropTypes.bool,icon:f.PropTypes.oneOfType([f.PropTypes.bool,m.customPropTypes.itemShorthand]),index:f.PropTypes.number,link:f.PropTypes.bool,name:f.PropTypes.string,onClick:f.PropTypes.func,position:f.PropTypes.oneOf(b.props.position)},g._meta=b,t.default=g},/*!******************************************!*\ !*** ./src/collections/Menu/MenuMenu.js ***! \******************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.children,r=e.className,n=e.position,s=(0,l.default)(r,n,"menu"),u=(0,c.getUnhandledProps)(o,e),p=(0,c.getElementType)(o,e);return i.default.createElement(p,a({},u,{className:s}),t)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! classnames */3),l=n(s),u=r(/*! react */1),i=n(u),c=r(/*! ../../lib */2);o._meta={name:"MenuMenu",type:c.META.TYPES.COLLECTION,parent:"Menu",props:{position:["right"]}},o.propTypes={as:c.customPropTypes.as,children:u.PropTypes.node,className:u.PropTypes.string,position:u.PropTypes.oneOf(o._meta.props.position)},t.default=o},/*!***************************************************!*\ !*** ./src/collections/Message/MessageContent.js ***! \***************************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.children,r=e.className,n=(0,l.default)("content",r),s=(0,c.getUnhandledProps)(o,e),u=(0,c.getElementType)(o,e);return i.default.createElement(u,a({},s,{className:n}),t)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! classnames */3),l=n(s),u=r(/*! react */1),i=n(u),c=r(/*! ../../lib */2);o._meta={name:"MessageContent",parent:"Message",type:c.META.TYPES.COLLECTION},o.propTypes={as:c.customPropTypes.as,children:u.PropTypes.node,className:u.PropTypes.string},t.default=o},/*!**************************************************!*\ !*** ./src/collections/Message/MessageHeader.js ***! \**************************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.children,r=e.className,n=(0,l.default)("header",r),s=(0,c.getUnhandledProps)(o,e),u=(0,c.getElementType)(o,e);return i.default.createElement(u,a({},s,{className:n}),t)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! classnames */3),l=n(s),u=r(/*! react */1),i=n(u),c=r(/*! ../../lib */2);o._meta={name:"MessageHeader",parent:"Message",type:c.META.TYPES.COLLECTION},o.propTypes={as:c.customPropTypes.as,children:u.PropTypes.node,className:u.PropTypes.string},t.default=o},/*!************************************************!*\ !*** ./src/collections/Message/MessageList.js ***! \************************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.children,r=e.className,n=e.items,a=(0,i.default)("list",r),u=(0,d.getUnhandledProps)(o,e),c=(0,d.getElementType)(o,e);if(t)return p.default.createElement(c,l({},u,{className:a}),t);var f=(0,s.default)(n,function(e){return p.default.createElement(y.default,{key:e},e)});return p.default.createElement(c,l({},u,{className:a}),f)}Object.defineProperty(t,"__esModule",{value:!0});var a=r(/*! lodash/map */10),s=n(a),l=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},u=r(/*! classnames */3),i=n(u),c=r(/*! react */1),p=n(c),d=r(/*! ../../lib */2),f=r(/*! ./MessageItem */83),y=n(f);o._meta={name:"MessageList",parent:"Message",type:d.META.TYPES.COLLECTION},o.propTypes={as:d.customPropTypes.as,children:c.PropTypes.node,className:c.PropTypes.string,items:c.PropTypes.arrayOf(c.PropTypes.string)},o.defaultProps={as:"ul"},t.default=o},/*!********************************************!*\ !*** ./src/collections/Table/TableBody.js ***! \********************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.children,r=e.className,n=(0,l.default)(r),s=(0,c.getUnhandledProps)(o,e),u=(0,c.getElementType)(o,e);return i.default.createElement(u,a({},s,{className:n}),t)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! classnames */3),l=n(s),u=r(/*! react */1),i=n(u),c=r(/*! ../../lib */2);o._meta={name:"TableBody",type:c.META.TYPES.COLLECTION,parent:"Table"},o.defaultProps={as:"tbody"},o.propTypes={as:c.customPropTypes.as,children:u.PropTypes.node,className:u.PropTypes.string},t.default=o},/*!**********************************************!*\ !*** ./src/collections/Table/TableFooter.js ***! \**********************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){return s.default.createElement(i.default,e)}Object.defineProperty(t,"__esModule",{value:!0});var a=r(/*! react */1),s=n(a),l=r(/*! ../../lib */2),u=r(/*! ./TableHeader */84),i=n(u);o._meta={name:"TableFooter",type:l.META.TYPES.COLLECTION,parent:"Table"},o.defaultProps={as:"tfoot"},t.default=o},/*!**************************************************!*\ !*** ./src/collections/Table/TableHeaderCell.js ***! \**************************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){return s.default.createElement(i.default,e)}Object.defineProperty(t,"__esModule",{value:!0});var a=r(/*! react */1),s=n(a),l=r(/*! ../../lib */2),u=r(/*! ./TableCell */46),i=n(u);o._meta={name:"TableHeaderCell",type:l.META.TYPES.COLLECTION,parent:"Table"},o.defaultProps={as:"th"},t.default=o},/*!*******************************************!*\ !*** ./src/collections/Table/TableRow.js ***! \*******************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.active,r=e.cellAs,n=e.cells,a=e.children,u=e.className,c=e.disabled,f=e.error,m=e.negative,h=e.positive,v=e.textAlign,b=e.verticalAlign,g=e.warning,P=(0,i.default)((0,d.useKeyOnly)(t,"active"),(0,d.useKeyOnly)(c,"disabled"),(0,d.useKeyOnly)(f,"error"),(0,d.useKeyOnly)(m,"negative"),(0,d.useKeyOnly)(h,"positive"),(0,d.useKeyOnly)(g,"warning"),(0,d.useTextAlignProp)(v),(0,d.useVerticalAlignProp)(b),u),T=(0,d.getUnhandledProps)(o,e),O=(0,d.getElementType)(o,e);return a?p.default.createElement(O,l({},T,{className:P}),a):p.default.createElement(O,l({},T,{className:P}),(0,s.default)(n,function(e){return y.default.create(e,{as:r})}))}Object.defineProperty(t,"__esModule",{value:!0});var a=r(/*! lodash/map */10),s=n(a),l=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},u=r(/*! classnames */3),i=n(u),c=r(/*! react */1),p=n(c),d=r(/*! ../../lib */2),f=r(/*! ./TableCell */46),y=n(f);o._meta={name:"TableRow",type:d.META.TYPES.COLLECTION,parent:"Table",props:{textAlign:d.SUI.TEXT_ALIGNMENTS,verticalAlign:d.SUI.VERTICAL_ALIGNMENTS}},o.defaultProps={as:"tr",cellAs:"td"},o.propTypes={as:d.customPropTypes.as,active:c.PropTypes.bool,cellAs:d.customPropTypes.as,cells:d.customPropTypes.collectionShorthand,children:c.PropTypes.node,className:c.PropTypes.string,disabled:c.PropTypes.bool,error:c.PropTypes.bool,negative:c.PropTypes.bool,positive:c.PropTypes.bool,textAlign:c.PropTypes.oneOf(o._meta.props.textAlign),verticalAlign:c.PropTypes.oneOf(o._meta.props.verticalAlign),warning:c.PropTypes.bool},o.create=(0,d.createShorthandFactory)(o,function(e){return{cells:e}}),t.default=o},/*!***************************************!*\ !*** ./src/elements/Button/Button.js ***! \***************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function l(e){if(Array.isArray(e)){for(var t=0,r=Array(e.length);t<e.length;t++)r[t]=e[t];return r}return Array.from(e)}Object.defineProperty(t,"__esModule",{value:!0});var u=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},i=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),c=r(/*! classnames */3),p=n(c),d=r(/*! react */1),f=n(d),y=r(/*! ../../lib */2),m=r(/*! ../Icon/Icon */47),h=n(m),v=r(/*! ../Label/Label */87),b=n(v),g=r(/*! ./ButtonContent */161),P=n(g),T=r(/*! ./ButtonGroup */162),O=n(T),_=r(/*! ./ButtonOr */163),E=n(_),j=(0,y.makeDebugger)("button"),w={name:"Button",type:y.META.TYPES.ELEMENT,props:{animated:["fade","vertical"],attached:["left","right","top","bottom"],color:[].concat(l(y.SUI.COLORS),["facebook","twitter","google plus","vk","linkedin","instagram","youtube"]),floated:y.SUI.FLOATS,labelPosition:["right","left"],size:y.SUI.SIZES}},S=function(e){function t(){var e,r,n,s;o(this,t);for(var l=arguments.length,u=Array(l),i=0;i<l;i++)u[i]=arguments[i];return r=n=a(this,(e=t.__proto__||Object.getPrototypeOf(t)).call.apply(e,[this].concat(u))),n.handleClick=function(e){var t=n.props,r=t.disabled,o=t.onClick;return r?void e.preventDefault():void(o&&o(e,n.props))},s=r,a(n,s)}return s(t,e),i(t,[{key:"render",value:function(){var e=this.props,r=e.active,n=e.animated,o=e.attached,a=e.basic,s=e.children,l=e.circular,i=e.className,c=e.color,d=e.compact,m=e.content,v=e.disabled,g=e.floated,P=e.fluid,T=e.icon,O=e.inverted,_=e.label,E=e.labelPosition,w=e.loading,S=e.negative,M=e.positive,x=e.primary,k=e.secondary,A=e.size,C=e.toggle,N=(0,p.default)((0,y.useKeyOrValueAndKey)(E||!!_,"labeled")),I=(0,p.default)(c,A,(0,y.useKeyOnly)(r,"active"),(0,y.useKeyOrValueAndKey)(n,"animated"),(0,y.useKeyOrValueAndKey)(o,"attached"),(0,y.useKeyOnly)(a,"basic"),(0,y.useKeyOnly)(l,"circular"),(0,y.useKeyOnly)(d,"compact"),(0,y.useKeyOnly)(v,"disabled"),(0,y.useValueAndKey)(g,"floated"),(0,y.useKeyOnly)(P,"fluid"),(0,y.useKeyOnly)(T===!0||T&&(E||!s&&!m),"icon"),(0,y.useKeyOnly)(O,"inverted"),(0,y.useKeyOnly)(w,"loading"),(0,y.useKeyOnly)(S,"negative"),(0,y.useKeyOnly)(M,"positive"),(0,y.useKeyOnly)(x,"primary"),(0,y.useKeyOnly)(k,"secondary"),(0,y.useKeyOnly)(C,"toggle")),K=(0,y.getUnhandledProps)(t,this.props),L=(0,y.getElementType)(t,this.props,function(){if(_||o)return"div"}),U="div"===L?0:void 0;if(s){var D=(0,p.default)("ui",I,N,"button",i);return j("render children:",{classes:D}),f.default.createElement(L,u({},K,{className:D,tabIndex:U,onClick:this.handleClick}),s)}if(_){var R=(0,p.default)("ui",I,"button",i),z=(0,p.default)("ui",N,"button",i);j("render label:",{classes:R,containerClasses:z},this.props);var W=b.default.create(_,{basic:!0,pointing:"left"===E?"right":"left"});return f.default.createElement(L,u({},K,{className:z,onClick:this.handleClick}),"left"===E&&W,f.default.createElement("button",{className:R},h.default.create(T)," ",m),("right"===E||!E)&&W)}if(T&&!_){var F=(0,p.default)("ui",N,I,"button",i);return j("render icon && !label:",{classes:F}),f.default.createElement(L,u({},K,{className:F,tabIndex:U,onClick:this.handleClick}),h.default.create(T)," ",m)}var V=(0,p.default)("ui",N,I,"button",i);return j("render default:",{classes:V}),f.default.createElement(L,u({},K,{className:V,tabIndex:U,onClick:this.handleClick}),m)}}]),t}(d.Component);S.propTypes={as:y.customPropTypes.as,active:d.PropTypes.bool,animated:d.PropTypes.oneOfType([d.PropTypes.bool,d.PropTypes.oneOf(w.props.animated)]),attached:d.PropTypes.oneOf(w.props.attached),basic:d.PropTypes.bool,children:y.customPropTypes.every([d.PropTypes.node,y.customPropTypes.disallow(["label"]),y.customPropTypes.givenProps({icon:d.PropTypes.oneOfType([d.PropTypes.string.isRequired,d.PropTypes.object.isRequired,d.PropTypes.element.isRequired])},y.customPropTypes.disallow(["icon"]))]),circular:d.PropTypes.bool,className:d.PropTypes.string,content:y.customPropTypes.contentShorthand,color:d.PropTypes.oneOf(w.props.color),compact:d.PropTypes.bool,disabled:d.PropTypes.bool,floated:d.PropTypes.oneOf(w.props.floated),fluid:d.PropTypes.bool,icon:y.customPropTypes.some([d.PropTypes.bool,d.PropTypes.string,d.PropTypes.object,d.PropTypes.element]),inverted:d.PropTypes.bool,labelPosition:d.PropTypes.oneOf(w.props.labelPosition),label:y.customPropTypes.some([d.PropTypes.string,d.PropTypes.object,d.PropTypes.element]),loading:d.PropTypes.bool,negative:d.PropTypes.bool,onClick:d.PropTypes.func,positive:d.PropTypes.bool,primary:d.PropTypes.bool,secondary:d.PropTypes.bool,toggle:d.PropTypes.bool,size:d.PropTypes.oneOf(w.props.size)},S.defaultProps={as:"button"},S._meta=w,S.Content=P.default,S.Group=O.default,S.Or=E.default,S.create=(0,y.createShorthandFactory)(S,function(e){return{content:e}}),t.default=S},/*!**********************************************!*\ !*** ./src/elements/Button/ButtonContent.js ***! \**********************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.children,r=e.className,n=e.hidden,s=e.visible,u=(0,l.default)((0,c.useKeyOnly)(s,"visible"),(0,c.useKeyOnly)(n,"hidden"),"content",r),p=(0,c.getUnhandledProps)(o,e),d=(0,c.getElementType)(o,e);return i.default.createElement(d,a({},p,{className:u}),t)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! classnames */3),l=n(s),u=r(/*! react */1),i=n(u),c=r(/*! ../../lib */2);o._meta={name:"ButtonContent",parent:"Button",type:c.META.TYPES.ELEMENT},o.propTypes={as:c.customPropTypes.as,className:u.PropTypes.string,children:u.PropTypes.node,hidden:u.PropTypes.bool,visible:u.PropTypes.bool},t.default=o},/*!********************************************!*\ !*** ./src/elements/Button/ButtonGroup.js ***! \********************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.attached,r=e.basic,n=e.children,s=e.className,u=e.color,p=e.compact,d=e.fluid,f=e.icon,y=e.inverted,m=e.labeled,h=e.negative,v=e.positive,b=e.primary,g=e.secondary,P=e.size,T=e.toggle,O=e.vertical,_=e.widths,E=(0,l.default)("ui",P,u,(0,c.useValueAndKey)(t,"attached"),(0,c.useKeyOnly)(r,"basic"),(0,c.useKeyOnly)(p,"compact"),(0,c.useKeyOnly)(d,"fluid"),(0,c.useKeyOnly)(f,"icon"),(0,c.useKeyOnly)(y,"inverted"),(0,c.useKeyOnly)(m,"labeled"),(0,c.useKeyOnly)(h,"negative"),(0,c.useKeyOnly)(v,"positive"),(0,c.useKeyOnly)(b,"primary"),(0,c.useKeyOnly)(g,"secondary"),(0,c.useKeyOnly)(T,"toggle"),(0,c.useKeyOnly)(O,"vertical"),(0,c.useWidthProp)(_),"buttons",s),j=(0,c.getUnhandledProps)(o,e),w=(0,c.getElementType)(o,e);return i.default.createElement(w,a({},j,{className:E}),n)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! classnames */3),l=n(s),u=r(/*! react */1),i=n(u),c=r(/*! ../../lib */2);o._meta={name:"ButtonGroup",parent:"Button",type:c.META.TYPES.ELEMENT,props:{attached:["left","right","top","bottom"],color:c.SUI.COLORS,size:c.SUI.SIZES,widths:c.SUI.WIDTHS}},o.propTypes={as:c.customPropTypes.as,attached:u.PropTypes.oneOf(o._meta.props.attached),basic:u.PropTypes.bool,className:u.PropTypes.string,children:u.PropTypes.node,color:u.PropTypes.oneOf(o._meta.props.color),compact:u.PropTypes.bool,fluid:u.PropTypes.bool,icon:u.PropTypes.bool,inverted:u.PropTypes.bool,labeled:u.PropTypes.bool,negative:u.PropTypes.bool,positive:u.PropTypes.bool,primary:u.PropTypes.bool,secondary:u.PropTypes.bool,size:u.PropTypes.oneOf(o._meta.props.size),toggle:u.PropTypes.bool,vertical:u.PropTypes.bool,widths:u.PropTypes.oneOf(o._meta.props.widths)},t.default=o},/*!*****************************************!*\ !*** ./src/elements/Button/ButtonOr.js ***! \*****************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.className,r=(0,l.default)("or",t),n=(0,c.getUnhandledProps)(o,e),s=(0,c.getElementType)(o,e);return i.default.createElement(s,a({},n,{className:r}))}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! classnames */3),l=n(s),u=r(/*! react */1),i=n(u),c=r(/*! ../../lib */2);o._meta={name:"ButtonOr",parent:"Button",type:c.META.TYPES.ELEMENT},o.propTypes={as:c.customPropTypes.as,className:u.PropTypes.string},t.default=o},/*!************************************!*\ !*** ./src/elements/Flag/index.js ***! \************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var o=r(/*! ./Flag */301),a=n(o);t.default=a.default},/*!**********************************************!*\ !*** ./src/elements/Header/HeaderContent.js ***! \**********************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.children,r=e.className,n=(0,l.default)(r,"content"),s=(0,c.getUnhandledProps)(o,e),u=(0,c.getElementType)(o,e);return i.default.createElement(u,a({},s,{className:n}),t)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! classnames */3),l=n(s),u=r(/*! react */1),i=n(u),c=r(/*! ../../lib */2);o._meta={name:"HeaderContent",parent:"Header",type:c.META.TYPES.VIEW},o.propTypes={as:c.customPropTypes.as,children:u.PropTypes.node,className:u.PropTypes.string},t.default=o},/*!************************************************!*\ !*** ./src/elements/Header/HeaderSubheader.js ***! \************************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.children,r=e.className,n=e.content,s=(0,l.default)("sub header",r),u=(0,c.getUnhandledProps)(o,e),p=(0,c.getElementType)(o,e);return i.default.createElement(p,a({},u,{className:s}),t||n)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! classnames */3),l=n(s),u=r(/*! react */1),i=n(u),c=r(/*! ../../lib */2);o._meta={name:"HeaderSubheader",parent:"Header",type:c.META.TYPES.ELEMENT},o.propTypes={as:c.customPropTypes.as,children:u.PropTypes.node,className:u.PropTypes.string,content:c.customPropTypes.contentShorthand},o.create=(0,c.createShorthandFactory)(o,function(e){return{content:e}}),t.default=o},/*!****************************************!*\ !*** ./src/elements/Icon/IconGroup.js ***! \****************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.children,r=e.className,n=e.size,s=(0,l.default)(n,"icons",r),u=(0,c.getUnhandledProps)(o,e),p=(0,c.getElementType)(o,e);return i.default.createElement(p,a({},u,{className:s}),t)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! classnames */3),l=n(s),u=r(/*! react */1),i=n(u),c=r(/*! ../../lib */2);o._meta={name:"IconGroup",parent:"Icon",type:c.META.TYPES.ELEMENT,props:{size:c.SUI.SIZES}},o.propTypes={as:c.customPropTypes.as,children:u.PropTypes.node,className:u.PropTypes.string,size:u.PropTypes.oneOf(o._meta.props.size)},o.defaultProps={as:"i"},t.default=o},/*!*************************************!*\ !*** ./src/elements/Image/Image.js ***! \*************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.alt,r=e.avatar,n=e.bordered,s=e.centered,u=e.children,p=e.className,f=e.dimmer,m=e.disabled,h=e.floated,v=e.fluid,b=e.height,g=e.hidden,P=e.href,T=e.inline,O=e.label,_=e.shape,E=e.size,j=e.spaced,w=e.src,S=e.verticalAlign,M=e.width,x=e.wrapped,k=e.ui,A=(0,l.default)((0,c.useKeyOnly)(k,"ui"),E,_,(0,c.useKeyOnly)(r,"avatar"),(0,c.useKeyOnly)(n,"bordered"),(0,c.useKeyOnly)(s,"centered"),(0,c.useKeyOnly)(m,"disabled"),(0,c.useKeyOnly)(v,"fluid"),(0,c.useKeyOnly)(g,"hidden"),(0,c.useKeyOnly)(T,"inline"),(0,c.useKeyOrValueAndKey)(j,"spaced"),(0,c.useValueAndKey)(h,"floated"),(0,c.useVerticalAlignProp)(S,"aligned"),"image",p),C=(0,c.getUnhandledProps)(o,e),N=(0,c.getElementType)(o,e,function(){if(f||O||x||u)return"div"});if(u)return i.default.createElement(N,a({},C,{className:A}),u);var I=a({},C,{className:A}),K={alt:t,src:w,height:b,width:M};return"img"===N?i.default.createElement(N,a({},I,K)):i.default.createElement(N,a({},I,{href:P}),d.default.create(f),y.default.create(O),i.default.createElement("img",K))}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! classnames */3),l=n(s),u=r(/*! react */1),i=n(u),c=r(/*! ../../lib */2),p=r(/*! ../../modules/Dimmer */184),d=n(p),f=r(/*! ../Label/Label */87),y=n(f),m=r(/*! ./ImageGroup */169),h=n(m);o.Group=h.default,o._meta={name:"Image",type:c.META.TYPES.ELEMENT,props:{verticalAlign:c.SUI.VERTICAL_ALIGNMENTS,floated:c.SUI.FLOATS,shape:["rounded","circular"],size:c.SUI.SIZES,spaced:["left","right"]}},o.propTypes={as:c.customPropTypes.as,alt:u.PropTypes.string,avatar:u.PropTypes.bool,bordered:u.PropTypes.bool,centered:u.PropTypes.bool,children:u.PropTypes.node,className:u.PropTypes.string,disabled:u.PropTypes.bool,dimmer:c.customPropTypes.itemShorthand,floated:u.PropTypes.oneOf(o._meta.props.floated),fluid:c.customPropTypes.every([u.PropTypes.bool,c.customPropTypes.disallow(["size"])]),height:u.PropTypes.oneOfType([u.PropTypes.string,u.PropTypes.number]),hidden:u.PropTypes.bool,href:u.PropTypes.string,inline:u.PropTypes.bool,label:c.customPropTypes.itemShorthand,shape:u.PropTypes.oneOf(o._meta.props.shape),size:u.PropTypes.oneOf(o._meta.props.size),spaced:u.PropTypes.oneOfType([u.PropTypes.bool,u.PropTypes.oneOf(o._meta.props.spaced)]),src:u.PropTypes.string,ui:u.PropTypes.bool,verticalAlign:u.PropTypes.oneOf(o._meta.props.verticalAlign),width:u.PropTypes.oneOfType([u.PropTypes.string,u.PropTypes.number]),wrapped:c.customPropTypes.every([u.PropTypes.bool,c.customPropTypes.disallow(["href"])])},o.defaultProps={as:"img",ui:!0},o.create=(0,c.createShorthandFactory)(o,function(e){return{src:e}}),t.default=o},/*!******************************************!*\ !*** ./src/elements/Image/ImageGroup.js ***! \******************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.children,r=e.className,n=e.size,s=(0,i.default)("ui",n,r,"images"),u=(0,c.getUnhandledProps)(o,e),p=(0,c.getElementType)(o,e);return l.default.createElement(p,a({},u,{className:s}),t)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! react */1),l=n(s),u=r(/*! classnames */3),i=n(u),c=r(/*! ../../lib */2);o._meta={name:"ImageGroup",parent:"Image",type:c.META.TYPES.ELEMENT,props:{size:c.SUI.SIZES}},o.propTypes={as:c.customPropTypes.as,children:s.PropTypes.node,className:s.PropTypes.string,size:s.PropTypes.oneOf(o._meta.props.size)},t.default=o},/*!*******************************************!*\ !*** ./src/elements/Label/LabelDetail.js ***! \*******************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.children,r=e.className,n=e.content,s=(0,l.default)("detail",r),u=(0,c.getUnhandledProps)(o,e),p=(0,c.getElementType)(o,e);return i.default.createElement(p,a({},u,{className:s}),t||n)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! classnames */3),l=n(s),u=r(/*! react */1),i=n(u),c=r(/*! ../../lib */2);o._meta={name:"LabelDetail",parent:"Label",type:c.META.TYPES.ELEMENT},o.propTypes={as:c.customPropTypes.as,children:u.PropTypes.node,className:u.PropTypes.string,content:c.customPropTypes.contentShorthand},t.default=o},/*!******************************************!*\ !*** ./src/elements/Label/LabelGroup.js ***! \******************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.children,r=e.circular,n=e.className,s=e.color,u=e.size,p=e.tag,d=(0,l.default)("ui",s,u,(0,c.useKeyOnly)(r,"circular"),(0,c.useKeyOnly)(p,"tag"),"labels",n),f=(0,c.getUnhandledProps)(o,e),y=(0,c.getElementType)(o,e);return i.default.createElement(y,a({},f,{className:d}),t)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! classnames */3),l=n(s),u=r(/*! react */1),i=n(u),c=r(/*! ../../lib */2);o._meta={name:"LabelGroup",parent:"Label",type:c.META.TYPES.ELEMENT,props:{color:c.SUI.COLORS,size:c.SUI.SIZES}},o.propTypes={as:c.customPropTypes.as,children:u.PropTypes.node,circular:u.PropTypes.bool,className:u.PropTypes.string,color:u.PropTypes.oneOf(o._meta.props.color),size:u.PropTypes.oneOf(o._meta.props.size),tag:u.PropTypes.bool},t.default=o},/*!***************************************!*\ !*** ./src/elements/List/ListItem.js ***! \***************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.active,r=e.children,n=e.className,a=e.content,u=e.description,f=e.disabled,m=e.header,v=e.icon,g=e.image,T=e.value,_=(0,d.getElementType)(o,e),E=(0,i.default)((0,d.useKeyOnly)(t,"active"),(0,d.useKeyOnly)(f,"disabled"),(0,d.useKeyOnly)("li"!==_,"item"),n),j=(0,d.getUnhandledProps)(o,e),w="li"===_?{value:T}:{"data-value":T};if(r)return p.default.createElement(_,l({},j,{className:E},w),r);var S=O.default.create(v),M=y.default.create(g);if(!(0,c.isValidElement)(a)&&(0,s.default)(a))return p.default.createElement(_,l({},j,{className:E},w),S||M,h.default.create(a,{header:m,description:u}));var x=P.default.create(m),k=b.default.create(u);return S||M?p.default.createElement(_,l({},j,{className:E},w),S||M,(a||x||k)&&p.default.createElement(h.default,null,x,k,a)):p.default.createElement(_,l({},j,{className:E},w),x,k,a)}Object.defineProperty(t,"__esModule",{value:!0});var a=r(/*! lodash/isPlainObject */132),s=n(a),l=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},u=r(/*! classnames */3),i=n(u),c=r(/*! react */1),p=n(c),d=r(/*! ../../lib */2),f=r(/*! ../../elements/Image */30),y=n(f),m=r(/*! ./ListContent */88),h=n(m),v=r(/*! ./ListDescription */49),b=n(v),g=r(/*! ./ListHeader */50),P=n(g),T=r(/*! ./ListIcon */89),O=n(T);o._meta={name:"ListItem",parent:"List",type:d.META.TYPES.ELEMENT},o.propTypes={as:d.customPropTypes.as,active:c.PropTypes.bool,children:c.PropTypes.node,className:c.PropTypes.string,content:d.customPropTypes.itemShorthand,description:d.customPropTypes.itemShorthand,disabled:c.PropTypes.bool,header:d.customPropTypes.itemShorthand,icon:d.customPropTypes.every([d.customPropTypes.disallow(["image"]),d.customPropTypes.itemShorthand]),image:d.customPropTypes.every([d.customPropTypes.disallow(["icon"]),d.customPropTypes.itemShorthand]),value:c.PropTypes.string},o.create=(0,d.createShorthandFactory)(o,function(e){return{content:e}}),t.default=o},/*!***************************************!*\ !*** ./src/elements/List/ListList.js ***! \***************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.children,r=e.className,n=(0,c.getUnhandledProps)(o,e),s=(0,c.getElementType)(o,e),u=(0,l.default)((0,c.useKeyOnly)("ul"!==s&&"ol"!==s,"list"),r);return i.default.createElement(s,a({},n,{className:u}),t)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! classnames */3),l=n(s),u=r(/*! react */1),i=n(u),c=r(/*! ../../lib */2);o._meta={name:"ListList",parent:"List",type:c.META.TYPES.ELEMENT},o.propTypes={as:c.customPropTypes.as,children:u.PropTypes.node,className:u.PropTypes.string},t.default=o},/*!**********************************************!*\ !*** ./src/elements/Reveal/RevealContent.js ***! \**********************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.children,r=e.className,n=e.hidden,s=e.visible,u=(0,l.default)("ui",(0,c.useKeyOnly)(n,"hidden"),(0,c.useKeyOnly)(s,"visible"),"content",r),p=(0,c.getUnhandledProps)(o,e),d=(0,c.getElementType)(o,e);return i.default.createElement(d,a({},p,{className:u}),t)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! classnames */3),l=n(s),u=r(/*! react */1),i=n(u),c=r(/*! ../../lib */2);o._meta={name:"RevealContent",parent:"Reveal",type:c.META.TYPES.ELEMENT},o.propTypes={as:c.customPropTypes.as,children:u.PropTypes.node,className:u.PropTypes.string,hidden:u.PropTypes.bool,visible:u.PropTypes.bool},t.default=o},/*!**********************************************!*\ !*** ./src/elements/Segment/SegmentGroup.js ***! \**********************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.children,r=e.className,n=e.compact,a=e.horizontal,s=e.piled,u=e.raised,c=e.size,f=e.stacked,y=(0,i.default)("ui",c,(0,d.useKeyOnly)(a,"horizontal"),(0,d.useKeyOnly)(n,"compact"),(0,d.useKeyOnly)(s,"piled"),(0,d.useKeyOnly)(u,"raised"),(0,d.useKeyOnly)(f,"stacked"),r,"segments"),m=(0,d.getUnhandledProps)(o,e),h=(0,d.getElementType)(o,e);return p.default.createElement(h,l({},m,{className:y}),t)}Object.defineProperty(t,"__esModule",{value:!0});var a=r(/*! lodash/without */7),s=n(a),l=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},u=r(/*! classnames */3),i=n(u),c=r(/*! react */1),p=n(c),d=r(/*! ../../lib */2);o._meta={name:"SegmentGroup",parent:"Segment",type:d.META.TYPES.ELEMENT,props:{size:(0,s.default)(d.SUI.SIZES,"medium")}},o.propTypes={as:d.customPropTypes.as,className:c.PropTypes.string,children:c.PropTypes.node,compact:c.PropTypes.bool,horizontal:c.PropTypes.bool,piled:c.PropTypes.bool,raised:c.PropTypes.bool,size:c.PropTypes.oneOf(o._meta.props.size),stacked:c.PropTypes.bool},t.default=o},/*!***********************************!*\ !*** ./src/elements/Step/Step.js ***! \***********************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var l=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},u=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),i=r(/*! classnames */3),c=n(i),p=r(/*! react */1),d=n(p),f=r(/*! ../../lib */2),y=r(/*! ../../elements/Icon */8),m=n(y),h=r(/*! ./StepContent */177),v=n(h),b=r(/*! ./StepDescription */90),g=n(b),P=r(/*! ./StepGroup */178),T=n(P),O=r(/*! ./StepTitle */91),_=n(O),E=function(e){function t(){var e,r,n,s;o(this,t);for(var l=arguments.length,u=Array(l),i=0;i<l;i++)u[i]=arguments[i];return r=n=a(this,(e=t.__proto__||Object.getPrototypeOf(t)).call.apply(e,[this].concat(u))),n.handleClick=function(e){var t=n.props.onClick;t&&t(e)},s=r,a(n,s)}return s(t,e),u(t,[{key:"render",value:function(){var e=this.props,r=e.active,n=e.children,o=e.className,a=e.completed,s=e.description,u=e.disabled,i=e.href,p=e.icon,y=e.link,h=e.onClick,b=e.title,g=(0,c.default)((0,f.useKeyOnly)(r,"active"),(0,f.useKeyOnly)(a,"completed"),(0,f.useKeyOnly)(u,"disabled"),(0,f.useKeyOnly)(y,"link"),"step",o),P=(0,f.getUnhandledProps)(t,this.props),T=(0,f.getElementType)(t,this.props,function(){if(h)return"a"});return n?d.default.createElement(T,l({},P,{className:g,href:i,onClick:this.handleClick}),n):d.default.createElement(T,l({},P,{className:g,href:i,onClick:this.handleClick}),m.default.create(p),d.default.createElement(v.default,{description:s,title:b}))}}]),t}(p.Component);E.propTypes={as:f.customPropTypes.as,active:p.PropTypes.bool,className:p.PropTypes.string,children:p.PropTypes.node,completed:p.PropTypes.bool,description:f.customPropTypes.itemShorthand,disabled:p.PropTypes.bool,icon:f.customPropTypes.itemShorthand,link:p.PropTypes.bool,href:p.PropTypes.string,onClick:p.PropTypes.func,ordered:p.PropTypes.bool,title:f.customPropTypes.itemShorthand},E._meta={name:"Step",type:f.META.TYPES.ELEMENT},E.Content=v.default,E.Description=g.default,E.Group=T.default,E.Title=_.default,t.default=E},/*!******************************************!*\ !*** ./src/elements/Step/StepContent.js ***! \******************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.children,r=e.className,n=e.description,s=e.title,u=(0,i.default)(r,"content"),p=(0,c.getUnhandledProps)(o,e),f=(0,c.getElementType)(o,e);return t?l.default.createElement(f,a({},p,{className:u}),t):l.default.createElement(f,a({},p,{className:u}),(0,c.createShorthand)(y.default,function(e){return{title:e}},s),(0,c.createShorthand)(d.default,function(e){return{description:e}},n))}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! react */1),l=n(s),u=r(/*! classnames */3),i=n(u),c=r(/*! ../../lib */2),p=r(/*! ./StepDescription */90),d=n(p),f=r(/*! ./StepTitle */91),y=n(f);o._meta={name:"StepContent",parent:"Step",type:c.META.TYPES.ELEMENT},o.propTypes={as:c.customPropTypes.as,className:s.PropTypes.string,children:s.PropTypes.node,description:c.customPropTypes.itemShorthand,title:c.customPropTypes.itemShorthand},t.default=o},/*!****************************************!*\ !*** ./src/elements/Step/StepGroup.js ***! \****************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.children,r=e.className,n=e.fluid,a=e.items,s=e.ordered,l=e.size,c=e.stackable,d=e.vertical,m=(0,p.default)("ui",(0,y.useKeyOnly)(n,"fluid"),(0,y.useKeyOnly)(s,"ordered"),(0,y.useValueAndKey)(c,"stackable"),(0,y.useKeyOnly)(d,"vertical"),l,r,"steps"),v=(0,y.getUnhandledProps)(o,e),b=(0,y.getElementType)(o,e);if(t)return f.default.createElement(b,i({},v,{className:m}),t);var g=(0,u.default)(a,function(e){var t=e.key||[e.title,e.description].join("-");return f.default.createElement(h.default,i({key:t},e))});return f.default.createElement(b,i({},v,{className:m}),g)}Object.defineProperty(t,"__esModule",{value:!0});var a=r(/*! lodash/without */7),s=n(a),l=r(/*! lodash/map */10),u=n(l),i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},c=r(/*! classnames */3),p=n(c),d=r(/*! react */1),f=n(d),y=r(/*! ../../lib */2),m=r(/*! ./Step */176),h=n(m);o._meta={name:"StepGroup",parent:"Step",props:{sizes:(0,s.default)(y.SUI.SIZES,"medium"),stackable:["tablet"]},type:y.META.TYPES.ELEMENT},o.propTypes={as:y.customPropTypes.as,className:d.PropTypes.string,children:d.PropTypes.node,fluid:d.PropTypes.bool,items:y.customPropTypes.collectionShorthand,ordered:d.PropTypes.bool,size:d.PropTypes.oneOf(o._meta.props.sizes),stackable:d.PropTypes.oneOf(o._meta.props.stackable),vertical:d.PropTypes.bool},t.default=o},/*!******************************!*\ !*** ./src/lib/isBrowser.js ***! \******************************/ function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n="object"===("undefined"==typeof document?"undefined":r(document))&&null!==document,o="object"===("undefined"==typeof window?"undefined":r(window))&&null!==window&&window.self===window;t.default=n&&o},/*!**************************!*\ !*** ./src/lib/leven.js ***! \**************************/ function(e,t,r){(function(e){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=function(){return 0};"production"!==e.env.NODE_ENV&&!function(){var e=[],t=[];r=function(r,n){if(r===n)return 0;var o=r.length,a=n.length;if(0===o)return a;if(0===a)return o;for(var s=void 0,l=void 0,u=void 0,i=void 0,c=0,p=0;c<o;)t[c]=r.charCodeAt(c),e[c]=++c;for(;p<a;)for(s=n.charCodeAt(p),u=p++,l=p,c=0;c<o;c++)i=s===t[c]?u:u+1,u=e[c],l=e[c]=u>l?i>l?l+1:i:i>u?u+1:i;return l}}(),t.default=r}).call(t,r(/*! ./~/process/browser.js */35))},/*!***************************************************!*\ !*** ./src/modules/Accordion/AccordionContent.js ***! \***************************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.active,r=e.children,n=e.className,s=(0,i.default)("content",(0,c.useKeyOnly)(t,"active"),n),u=(0,c.getUnhandledProps)(o,e),p=(0,c.getElementType)(o,e);return l.default.createElement(p,a({},u,{className:s}),r)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! react */1),l=n(s),u=r(/*! classnames */3),i=n(u),c=r(/*! ../../lib */2);o.displayName="AccordionContent",o.propTypes={as:c.customPropTypes.as,active:s.PropTypes.bool,children:s.PropTypes.node,className:s.PropTypes.string},o._meta={name:"AccordionContent",type:c.META.TYPES.MODULE,parent:"Accordion"},t.default=o},/*!*************************************************!*\ !*** ./src/modules/Accordion/AccordionTitle.js ***! \*************************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var l=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},u=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),i=r(/*! classnames */3),c=n(i),p=r(/*! react */1),d=n(p),f=r(/*! ../../lib */2),y=function(e){function t(){var e,r,n,s;o(this,t);for(var l=arguments.length,u=Array(l),i=0;i<l;i++)u[i]=arguments[i];return r=n=a(this,(e=t.__proto__||Object.getPrototypeOf(t)).call.apply(e,[this].concat(u))),n.handleClick=function(e){var t=n.props.onClick;t&&t(e)},s=r,a(n,s)}return s(t,e),u(t,[{key:"render",value:function(){var e=this.props,r=e.active,n=e.children,o=e.className,a=(0,c.default)((0,f.useKeyOnly)(r,"active"),"title",o),s=(0,f.getUnhandledProps)(t,this.props),u=(0,f.getElementType)(t,this.props);return d.default.createElement(u,l({},s,{className:a,onClick:this.handleClick}),n)}}]),t}(p.Component);y.displayName="AccordionTitle",y.propTypes={as:f.customPropTypes.as,active:p.PropTypes.bool,children:p.PropTypes.node,className:p.PropTypes.string,onClick:p.PropTypes.func},y._meta={name:"AccordionTitle",type:f.META.TYPES.MODULE,parent:"Accordion"},t.default=y},/*!**********************************************!*\ !*** ./src/modules/Dimmer/DimmerDimmable.js ***! \**********************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.blurring,r=e.className,n=e.children,s=e.dimmed,u=(0,l.default)((0,c.useKeyOnly)(t,"blurring"),(0,c.useKeyOnly)(s,"dimmed"),"dimmable",r),p=(0,c.getUnhandledProps)(o,e),d=(0,c.getElementType)(o,e);return i.default.createElement(d,a({},p,{className:u}),n)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! classnames */3),l=n(s),u=r(/*! react */1),i=n(u),c=r(/*! ../../lib */2);o._meta={name:"DimmerDimmable",type:c.META.TYPES.MODULE,parent:"Dimmer"},o.propTypes={as:c.customPropTypes.as,blurring:u.PropTypes.bool,children:u.PropTypes.node,className:u.PropTypes.string,dimmed:u.PropTypes.bool},t.default=o},/*!*************************************!*\ !*** ./src/modules/Dimmer/index.js ***! \*************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var o=r(/*! ./Dimmer */331),a=n(o);t.default=a.default},/*!*************************************************!*\ !*** ./src/modules/Dropdown/DropdownDivider.js ***! \*************************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.className,r=(0,l.default)("divider",t),n=(0,c.getUnhandledProps)(o,e),s=(0,c.getElementType)(o,e);return i.default.createElement(s,a({},n,{className:r}))}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! classnames */3),l=n(s),u=r(/*! react */1),i=n(u),c=r(/*! ../../lib */2);o._meta={name:"DropdownDivider",parent:"Dropdown",type:c.META.TYPES.MODULE},o.propTypes={as:c.customPropTypes.as,className:u.PropTypes.string},t.default=o},/*!************************************************!*\ !*** ./src/modules/Dropdown/DropdownHeader.js ***! \************************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.children,r=e.className,n=e.content,s=e.icon,u=(0,l.default)("header",r),p=(0,c.getUnhandledProps)(o,e),f=(0,c.getElementType)(o,e);return t?i.default.createElement(f,a({},p,{className:u}),t):i.default.createElement(f,a({},p,{className:u}),d.default.create(s),n)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! classnames */3),l=n(s),u=r(/*! react */1),i=n(u),c=r(/*! ../../lib */2),p=r(/*! ../../elements/Icon */8),d=n(p);o._meta={name:"DropdownHeader",parent:"Dropdown",type:c.META.TYPES.MODULE},o.propTypes={as:c.customPropTypes.as,children:u.PropTypes.node,className:u.PropTypes.string,content:c.customPropTypes.contentShorthand,icon:c.customPropTypes.itemShorthand},t.default=o},/*!**********************************************!*\ !*** ./src/modules/Dropdown/DropdownItem.js ***! \**********************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var l=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},u=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),i=r(/*! classnames */3),c=n(i),p=r(/*! react */1),d=n(p),f=r(/*! ../../lib */2),y=r(/*! ../../elements/Flag */164),m=n(y),h=r(/*! ../../elements/Icon */8),v=n(h),b=r(/*! ../../elements/Image */30),g=n(b),P=r(/*! ../../elements/Label */48),T=n(P),O=function(e){function t(){var e,r,n,s;o(this,t);for(var l=arguments.length,u=Array(l),i=0;i<l;i++)u[i]=arguments[i];return r=n=a(this,(e=t.__proto__||Object.getPrototypeOf(t)).call.apply(e,[this].concat(u))),n.handleClick=function(e){var t=n.props.onClick;t&&t(e,n.props)},s=r,a(n,s)}return s(t,e),u(t,[{key:"render",value:function(){var e=this.props,r=e.active,n=e.children,o=e.className,a=e.content,s=e.disabled,u=e.description,i=e.flag,p=e.icon,y=e.image,h=e.label,b=e.selected,P=e.text,O=(0,c.default)((0,f.useKeyOnly)(r,"active"),(0,f.useKeyOnly)(s,"disabled"),(0,f.useKeyOnly)(b,"selected"),"item",o),_=p||f.childrenUtils.someByType(n,"DropdownMenu")&&"dropdown",E=(0,f.getUnhandledProps)(t,this.props),j=(0,f.getElementType)(t,this.props);if(n)return d.default.createElement(j,l({},E,{className:O,onClick:this.handleClick}),n);var w=m.default.create(i),S=v.default.create(_),M=g.default.create(y),x=T.default.create(h),k=(0,f.createShorthand)("span",function(e){return{className:"description",children:e}},u);return k?d.default.createElement(j,l({},E,{className:O,onClick:this.handleClick}),M,S,w,x,k,(0,f.createShorthand)("span",function(e){return{className:"text",children:e}},a||P)):d.default.createElement(j,l({},E,{className:O,onClick:this.handleClick}),M,S,w,x,a||P)}}]),t}(p.Component);O.propTypes={as:f.customPropTypes.as,active:p.PropTypes.bool,children:p.PropTypes.node,className:p.PropTypes.string,content:f.customPropTypes.contentShorthand,description:f.customPropTypes.itemShorthand,disabled:p.PropTypes.bool,flag:f.customPropTypes.itemShorthand,icon:f.customPropTypes.itemShorthand,image:f.customPropTypes.itemShorthand,label:f.customPropTypes.itemShorthand,selected:p.PropTypes.bool,text:f.customPropTypes.contentShorthand,value:p.PropTypes.oneOfType([p.PropTypes.number,p.PropTypes.string]),onClick:p.PropTypes.func},O._meta={name:"DropdownItem",parent:"Dropdown",type:f.META.TYPES.MODULE},t.default=O},/*!**********************************************!*\ !*** ./src/modules/Dropdown/DropdownMenu.js ***! \**********************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.children,r=e.className,n=e.scrolling,s=(0,i.default)((0,c.useKeyOnly)(n,"scrolling"),"menu transition",r),u=(0,c.getUnhandledProps)(o,e),p=(0,c.getElementType)(o,e);return l.default.createElement(p,a({},u,{className:s}),t)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! react */1),l=n(s),u=r(/*! classnames */3),i=n(u),c=r(/*! ../../lib */2);o._meta={name:"DropdownMenu",parent:"Dropdown",type:c.META.TYPES.MODULE},o.propTypes={as:c.customPropTypes.as,children:s.PropTypes.node,className:s.PropTypes.string,scrolling:s.PropTypes.bool},t.default=o},/*!*******************************************!*\ !*** ./src/modules/Modal/ModalActions.js ***! \*******************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.children,r=e.className,n=(0,i.default)(r,"actions"),s=(0,c.getUnhandledProps)(o,e),u=(0,c.getElementType)(o,e);return l.default.createElement(u,a({},s,{className:n}),t)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! react */1),l=n(s),u=r(/*! classnames */3),i=n(u),c=r(/*! ../../lib */2);o._meta={name:"ModalActions",type:c.META.TYPES.MODULE,parent:"Modal"},o.propTypes={as:c.customPropTypes.as,children:s.PropTypes.node,className:s.PropTypes.string},t.default=o},/*!*******************************************!*\ !*** ./src/modules/Modal/ModalContent.js ***! \*******************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.children,r=e.image,n=e.className,s=(0,i.default)(n,(0,c.useKeyOnly)(r,"image"),"content"),u=(0,c.getUnhandledProps)(o,e),p=(0,c.getElementType)(o,e);return l.default.createElement(p,a({},u,{className:s}),t)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! react */1),l=n(s),u=r(/*! classnames */3),i=n(u),c=r(/*! ../../lib */2);o._meta={name:"ModalContent",type:c.META.TYPES.MODULE,parent:"Modal"},o.propTypes={as:c.customPropTypes.as,children:s.PropTypes.node,className:s.PropTypes.string,image:s.PropTypes.bool},t.default=o},/*!***********************************************!*\ !*** ./src/modules/Modal/ModalDescription.js ***! \***********************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.children,r=e.className,n=(0,i.default)(r,"description"),s=(0,c.getUnhandledProps)(o,e),u=(0,c.getElementType)(o,e);return l.default.createElement(u,a({},s,{className:n}),t)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! react */1),l=n(s),u=r(/*! classnames */3),i=n(u),c=r(/*! ../../lib */2);o._meta={name:"ModalDescription",type:c.META.TYPES.MODULE,parent:"Modal"},o.propTypes={as:c.customPropTypes.as,children:s.PropTypes.node,className:s.PropTypes.string},t.default=o},/*!******************************************!*\ !*** ./src/modules/Modal/ModalHeader.js ***! \******************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.children,r=e.className,n=(0,i.default)(r,"header"),s=(0,c.getUnhandledProps)(o,e),u=(0,c.getElementType)(o,e);return l.default.createElement(u,a({},s,{className:n}),t)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! react */1),l=n(s),u=r(/*! classnames */3),i=n(u),c=r(/*! ../../lib */2);o._meta={name:"ModalHeader",type:c.META.TYPES.MODULE,parent:"Modal"},o.propTypes={as:c.customPropTypes.as,children:s.PropTypes.node,className:s.PropTypes.string},t.default=o},/*!************************************!*\ !*** ./src/modules/Modal/index.js ***! \************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var o=r(/*! ./Modal */335),a=n(o);t.default=a.default},/*!*******************************************!*\ !*** ./src/modules/Popup/PopupContent.js ***! \*******************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.children,r=e.className,n=(0,i.default)("content",r),s=(0,c.getUnhandledProps)(o,e),u=(0,c.getElementType)(o,e);return l.default.createElement(u,a({},s,{className:n}),t)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e};t.default=o;var s=r(/*! react */1),l=n(s),u=r(/*! classnames */3),i=n(u),c=r(/*! ../../lib */2);o.create=(0,c.createShorthandFactory)(o,function(e){return{children:e}}),o.propTypes={children:s.PropTypes.node,className:s.PropTypes.string},o._meta={name:"PopupContent",type:c.META.TYPES.MODULE,parent:"Popup"}},/*!******************************************!*\ !*** ./src/modules/Popup/PopupHeader.js ***! \******************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.children,r=e.className,n=(0,i.default)("header",r),s=(0,c.getUnhandledProps)(o,e),u=(0,c.getElementType)(o,e);return l.default.createElement(u,a({},s,{className:n}),t)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e};t.default=o;var s=r(/*! react */1),l=n(s),u=r(/*! classnames */3),i=n(u),c=r(/*! ../../lib */2);o.create=(0,c.createShorthandFactory)(o,function(e){return{children:e}}),o.propTypes={children:s.PropTypes.node,className:s.PropTypes.string},o._meta={name:"PopupHeader",type:c.META.TYPES.MODULE,parent:"Popup"}},/*!**********************************************!*\ !*** ./src/modules/Search/SearchCategory.js ***! \**********************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.active,r=e.children,n=e.className,s=e.renderer,u=(0,i.default)((0,c.useKeyOnly)(t,"active"),"category",n),d=(0,c.getUnhandledProps)(o,e),f=(0,c.getElementType)(o,e);return l.default.createElement(f,a({},d,{className:u}),l.default.createElement("div",{className:"name"},s?s(e):p(e)),r)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! react */1),l=n(s),u=r(/*! classnames */3),i=n(u),c=r(/*! ../../lib */2),p=function(e){var t=e.name;return t};o._meta={name:"SearchCategory",parent:"Search",type:c.META.TYPES.MODULE},o.propTypes={as:c.customPropTypes.as,active:s.PropTypes.bool,children:s.PropTypes.node,className:s.PropTypes.string,name:s.PropTypes.string,renderer:s.PropTypes.func,results:s.PropTypes.array},t.default=o},/*!********************************************!*\ !*** ./src/modules/Search/SearchResult.js ***! \********************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var l=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},u=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),i=r(/*! react */1),c=n(i),p=r(/*! classnames */3),d=n(p),f=r(/*! ../../lib */2),y=function(e){var t=e.image,r=e.price,n=e.title,o=e.description;return[t&&c.default.createElement("div",{key:"image",className:"image"},(0,f.createHTMLImage)(t)),c.default.createElement("div",{key:"content",className:"content"},r&&c.default.createElement("div",{className:"price"},r),n&&c.default.createElement("div",{className:"title"},n),o&&c.default.createElement("div",{className:"description"},o))]},m=function(e){function t(){var e,r,n,s;o(this,t);for(var l=arguments.length,u=Array(l),i=0;i<l;i++)u[i]=arguments[i];return r=n=a(this,(e=t.__proto__||Object.getPrototypeOf(t)).call.apply(e,[this].concat(u))),n.handleClick=function(e){var t=n.props,r=t.id,o=t.onClick;o&&o(e,r)},s=r,a(n,s)}return s(t,e),u(t,[{key:"render",value:function(){var e=this.props,r=e.active,n=e.className,o=e.renderer,a=(0,d.default)((0,f.useKeyOnly)(r,"active"),"result",n),s=(0,f.getUnhandledProps)(t,this.props),u=(0,f.getElementType)(t,this.props);return c.default.createElement(u,l({},s,{className:a,onClick:this.handleClick}),o?o(this.props):y(this.props))}}]),t}(i.Component);m.propTypes={as:f.customPropTypes.as,active:i.PropTypes.bool,className:i.PropTypes.string,description:i.PropTypes.string,id:i.PropTypes.number,image:i.PropTypes.string,onClick:i.PropTypes.func,price:i.PropTypes.string,renderer:i.PropTypes.func,title:i.PropTypes.string},m._meta={name:"SearchResult",parent:"Search",type:f.META.TYPES.MODULE},t.default=m},/*!*********************************************!*\ !*** ./src/modules/Search/SearchResults.js ***! \*********************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.children,r=e.className,n=(0,i.default)("results transition",r),s=(0,c.getUnhandledProps)(o,e),u=(0,c.getElementType)(o,e);return l.default.createElement(u,a({},s,{className:n}),t)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! react */1),l=n(s),u=r(/*! classnames */3),i=n(u),c=r(/*! ../../lib */2);o._meta={name:"SearchResults",parent:"Search",type:c.META.TYPES.MODULE},o.propTypes={as:c.customPropTypes.as,children:s.PropTypes.node,className:s.PropTypes.string},t.default=o},/*!********************************!*\ !*** ./src/views/Card/Card.js ***! \********************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var l=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},u=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),i=r(/*! classnames */3),c=n(i),p=r(/*! react */1),d=n(p),f=r(/*! ../../lib */2),y=r(/*! ../../elements/Image */30),m=n(y),h=r(/*! ./CardContent */200),v=n(h),b=r(/*! ./CardDescription */94),g=n(b),P=r(/*! ./CardGroup */201),T=n(P),O=r(/*! ./CardHeader */95),_=n(O),E=r(/*! ./CardMeta */96),j=n(E),w={name:"Card",type:f.META.TYPES.VIEW,props:{color:f.SUI.COLORS}},S=function(e){function t(){var e,r,n,s;o(this,t);for(var l=arguments.length,u=Array(l),i=0;i<l;i++)u[i]=arguments[i];return r=n=a(this,(e=t.__proto__||Object.getPrototypeOf(t)).call.apply(e,[this].concat(u))),n.handleClick=function(e){var t=n.props.onClick;t&&t(e,n.props)},s=r,a(n,s)}return s(t,e),u(t,[{key:"render",value:function(){var e=this.props,r=e.centered,n=e.children,o=e.className,a=e.color,s=e.description,u=e.extra,i=e.fluid,p=e.header,y=e.href,h=e.image,b=e.meta,g=e.onClick,P=e.raised,T=(0,c.default)("ui",a,(0,f.useKeyOnly)(r,"centered"),(0,f.useKeyOnly)(i,"fluid"),(0,f.useKeyOnly)(P,"raised"),"card",o),O=(0,f.getUnhandledProps)(t,this.props),_=(0,f.getElementType)(t,this.props,function(){if(g)return"a"});return n?d.default.createElement(_,l({},O,{className:T,href:y,onClick:this.handleClick}),n):d.default.createElement(_,l({},O,{className:T,href:y,onClick:this.handleClick}),m.default.create(h),(s||p||b)&&d.default.createElement(v.default,{description:s,header:p,meta:b}),u&&d.default.createElement(v.default,{extra:!0},u))}}]),t}(p.Component);S.propTypes={as:f.customPropTypes.as,centered:p.PropTypes.bool,children:p.PropTypes.node,className:p.PropTypes.string,color:p.PropTypes.oneOf(w.props.color),description:f.customPropTypes.itemShorthand,extra:f.customPropTypes.contentShorthand,fluid:p.PropTypes.bool,header:f.customPropTypes.itemShorthand,href:p.PropTypes.string,image:f.customPropTypes.itemShorthand,meta:f.customPropTypes.itemShorthand,onClick:p.PropTypes.func,raised:p.PropTypes.bool},S._meta=w,S.Content=v.default,S.Description=g.default,S.Group=T.default,S.Header=_.default,S.Meta=j.default,t.default=S},/*!***************************************!*\ !*** ./src/views/Card/CardContent.js ***! \***************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.children,r=e.className,n=e.description,s=e.extra,u=e.header,p=e.meta,f=(0,l.default)(r,(0,c.useKeyOnly)(s,"extra"),"content"),m=(0,c.getUnhandledProps)(o,e),v=(0,c.getElementType)(o,e);return t?i.default.createElement(v,a({},m,{className:f}),t):i.default.createElement(v,a({},m,{className:f}),(0,c.createShorthand)(y.default,function(e){return{content:e}},u),(0,c.createShorthand)(h.default,function(e){return{content:e}},p),(0,c.createShorthand)(d.default,function(e){return{content:e}},n))}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! classnames */3),l=n(s),u=r(/*! react */1),i=n(u),c=r(/*! ../../lib */2),p=r(/*! ./CardDescription */94),d=n(p),f=r(/*! ./CardHeader */95),y=n(f),m=r(/*! ./CardMeta */96),h=n(m);o._meta={name:"CardContent",parent:"Card",type:c.META.TYPES.VIEW},o.propTypes={as:c.customPropTypes.as,children:u.PropTypes.node,className:u.PropTypes.string,description:c.customPropTypes.itemShorthand,extra:u.PropTypes.bool,header:c.customPropTypes.itemShorthand,meta:c.customPropTypes.itemShorthand},t.default=o},/*!*************************************!*\ !*** ./src/views/Card/CardGroup.js ***! \*************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.children,r=e.className,n=e.doubling,a=e.items,u=e.itemsPerRow,c=e.stackable,f=(0,i.default)("ui",(0,d.useWidthProp)(u),(0,d.useKeyOnly)(n,"doubling"),(0,d.useKeyOnly)(c,"stackable"),r,"cards"),m=(0,d.getUnhandledProps)(o,e),h=(0,d.getElementType)(o,e);if(t)return p.default.createElement(h,l({},m,{className:f}),t);var v=(0,s.default)(a,function(e){var t=e.key||[e.header,e.description].join("-");return p.default.createElement(y.default,l({key:t},e))});return p.default.createElement(h,l({},m,{className:f}),v)}Object.defineProperty(t,"__esModule",{value:!0});var a=r(/*! lodash/map */10),s=n(a),l=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},u=r(/*! classnames */3),i=n(u),c=r(/*! react */1),p=n(c),d=r(/*! ../../lib */2),f=r(/*! ./Card */199),y=n(f);o._meta={name:"CardGroup",parent:"Card",props:{itemsPerRow:d.SUI.WIDTHS},type:d.META.TYPES.VIEW},o.propTypes={as:d.customPropTypes.as,children:c.PropTypes.node,className:c.PropTypes.string,doubling:c.PropTypes.bool,items:d.customPropTypes.collectionShorthand,itemsPerRow:c.PropTypes.oneOf(o._meta.props.itemsPerRow),stackable:c.PropTypes.bool},t.default=o},/*!********************************************!*\ !*** ./src/views/Comment/CommentAction.js ***! \********************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.active,r=e.className,n=e.children,s=(0,l.default)((0,c.useKeyOnly)(t,"active"),r),u=(0,c.getUnhandledProps)(o,e),p=(0,c.getElementType)(o,e);return i.default.createElement(p,a({},u,{className:s}),n)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! classnames */3),l=n(s),u=r(/*! react */1),i=n(u),c=r(/*! ../../lib */2);o._meta={name:"CommentAction",parent:"Comment",type:c.META.TYPES.VIEW},o.defaultProps={as:"a"},o.propTypes={as:c.customPropTypes.as,active:u.PropTypes.bool,children:u.PropTypes.node,className:u.PropTypes.string},t.default=o},/*!*********************************************!*\ !*** ./src/views/Comment/CommentActions.js ***! \*********************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.className,r=e.children,n=(0,l.default)("actions",t),s=(0,c.getUnhandledProps)(o,e),u=(0,c.getElementType)(o,e);return i.default.createElement(u,a({},s,{className:n}),r)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! classnames */3),l=n(s),u=r(/*! react */1),i=n(u),c=r(/*! ../../lib */2);o._meta={name:"CommentActions",parent:"Comment",type:c.META.TYPES.VIEW},o.propTypes={as:c.customPropTypes.as,children:u.PropTypes.node,className:u.PropTypes.string},t.default=o},/*!********************************************!*\ !*** ./src/views/Comment/CommentAuthor.js ***! \********************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.className,r=e.children,n=(0,l.default)("author",t),s=(0,c.getUnhandledProps)(o,e),u=(0,c.getElementType)(o,e);return i.default.createElement(u,a({},s,{className:n}),r)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! classnames */3),l=n(s),u=r(/*! react */1),i=n(u),c=r(/*! ../../lib */2);o._meta={name:"CommentAuthor",parent:"Comment",type:c.META.TYPES.VIEW},o.propTypes={as:c.customPropTypes.as,children:u.PropTypes.node,className:u.PropTypes.string},t.default=o},/*!********************************************!*\ !*** ./src/views/Comment/CommentAvatar.js ***! \********************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.className,r=e.src,n=(0,l.default)("avatar",t),s=(0,c.getUnhandledProps)(o,e),u=(0,c.getElementType)(o,e);return i.default.createElement(u,a({},s,{className:n}),(0,c.createHTMLImage)(r))}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! classnames */3),l=n(s),u=r(/*! react */1),i=n(u),c=r(/*! ../../lib */2);o._meta={name:"CommentAvatar",parent:"Comment",type:c.META.TYPES.VIEW},o.propTypes={as:c.customPropTypes.as,className:u.PropTypes.string,src:u.PropTypes.string},t.default=o},/*!*********************************************!*\ !*** ./src/views/Comment/CommentContent.js ***! \*********************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.className,r=e.children,n=(0,l.default)("content",t),s=(0,c.getUnhandledProps)(o,e),u=(0,c.getElementType)(o,e);return i.default.createElement(u,a({},s,{className:n}),r)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! classnames */3),l=n(s),u=r(/*! react */1),i=n(u),c=r(/*! ../../lib */2);o._meta={name:"CommentContent",parent:"Comment",type:c.META.TYPES.VIEW},o.propTypes={as:c.customPropTypes.as,children:u.PropTypes.node,className:u.PropTypes.string},t.default=o},/*!*******************************************!*\ !*** ./src/views/Comment/CommentGroup.js ***! \*******************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.className,r=e.children,n=e.collapsed,s=e.minimal,u=e.threaded,p=(0,l.default)("ui",(0,c.useKeyOnly)(n,"collapsed"),(0,c.useKeyOnly)(s,"minimal"),(0,c.useKeyOnly)(u,"threaded"),"comments",t),d=(0,c.getUnhandledProps)(o,e),f=(0,c.getElementType)(o,e);return i.default.createElement(f,a({},d,{className:p}),r)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! classnames */3),l=n(s),u=r(/*! react */1),i=n(u),c=r(/*! ../../lib */2);o._meta={name:"CommentGroup",parent:"Comment",type:c.META.TYPES.VIEW},o.propTypes={as:c.customPropTypes.as,children:u.PropTypes.node,className:u.PropTypes.string,collapsed:u.PropTypes.bool,minimal:u.PropTypes.bool,threaded:u.PropTypes.bool},t.default=o},/*!**********************************************!*\ !*** ./src/views/Comment/CommentMetadata.js ***! \**********************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.className,r=e.children,n=(0,l.default)("metadata",t),s=(0,c.getUnhandledProps)(o,e),u=(0,c.getElementType)(o,e);return i.default.createElement(u,a({},s,{className:n}),r)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! classnames */3),l=n(s),u=r(/*! react */1),i=n(u),c=r(/*! ../../lib */2);o._meta={name:"CommentMetadata",parent:"Comment",type:c.META.TYPES.VIEW},o.propTypes={as:c.customPropTypes.as,children:u.PropTypes.node,className:u.PropTypes.string},t.default=o},/*!******************************************!*\ !*** ./src/views/Comment/CommentText.js ***! \******************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.className,r=e.children,n=(0,l.default)("text",t),s=(0,c.getUnhandledProps)(o,e),u=(0,c.getElementType)(o,e);return i.default.createElement(u,a({},s,{className:n}),r)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! classnames */3),l=n(s),u=r(/*! react */1),i=n(u),c=r(/*! ../../lib */2);o._meta={name:"CommentText",parent:"Comment",type:c.META.TYPES.VIEW},o.propTypes={as:c.customPropTypes.as,children:u.PropTypes.node,className:u.PropTypes.string},t.default=o},/*!*************************************!*\ !*** ./src/views/Feed/FeedEvent.js ***! \*************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.content,r=e.children,n=e.className,s=e.date,u=e.extraImages,p=e.extraText,f=e.image,m=e.icon,h=e.meta,v=e.summary,b=(0,l.default)(n,"event"),g=(0,c.getUnhandledProps)(o,e),P=(0,c.getElementType)(o,e),T=t||s||u||p||h||v,O={content:t,date:s,extraImages:u,extraText:p,meta:h,summary:v};return i.default.createElement(P,a({},g,{className:b}),(0,c.createShorthand)(y.default,function(e){return{icon:e}},m),(0,c.createShorthand)(y.default,function(e){return{image:e}},f),T&&i.default.createElement(d.default,O),r)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! classnames */3),l=n(s),u=r(/*! react */1),i=n(u),c=r(/*! ../../lib */2),p=r(/*! ./FeedContent */97),d=n(p),f=r(/*! ./FeedLabel */99),y=n(f);o._meta={name:"FeedEvent",parent:"Feed",type:c.META.TYPES.VIEW},o.propTypes={as:c.customPropTypes.as,children:u.PropTypes.node,className:u.PropTypes.string,content:d.default.propTypes.content,date:d.default.propTypes.date,extraImages:d.default.propTypes.extraImages,extraText:d.default.propTypes.extraText,icon:c.customPropTypes.itemShorthand,image:c.customPropTypes.itemShorthand,meta:d.default.propTypes.meta,summary:d.default.propTypes.summary},t.default=o},/*!********************************!*\ !*** ./src/views/Item/Item.js ***! \********************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.children,r=e.className,n=e.content,s=e.description,u=e.extra,p=e.header,f=e.image,y=e.meta,m=(0,l.default)(r,"item"),h=(0,c.getUnhandledProps)(o,e),v=(0,c.getElementType)(o,e);return t?i.default.createElement(v,a({},h,{className:m}),t):i.default.createElement(v,a({},h,{className:m}),(0,c.createShorthand)(O.default,function(e){return{src:e}},f),i.default.createElement(d.default,{content:n,description:s,extra:u,header:p,meta:y}))}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! classnames */3),l=n(s),u=r(/*! react */1),i=n(u),c=r(/*! ../../lib */2),p=r(/*! ./ItemContent */212),d=n(p),f=r(/*! ./ItemDescription */104),y=n(f),m=r(/*! ./ItemExtra */105),h=n(m),v=r(/*! ./ItemGroup */213),b=n(v),g=r(/*! ./ItemHeader */106),P=n(g),T=r(/*! ./ItemImage */214),O=n(T),_=r(/*! ./ItemMeta */107),E=n(_);o._meta={name:"Item",type:c.META.TYPES.VIEW},o.Content=d.default,o.Description=y.default,o.Extra=h.default,o.Group=b.default,o.Header=P.default,o.Image=O.default,o.Meta=E.default,o.propTypes={as:c.customPropTypes.as,children:u.PropTypes.node,className:u.PropTypes.string,content:c.customPropTypes.contentShorthand,description:c.customPropTypes.itemShorthand,extra:c.customPropTypes.itemShorthand,image:c.customPropTypes.itemShorthand,header:c.customPropTypes.itemShorthand,meta:c.customPropTypes.itemShorthand},t.default=o},/*!***************************************!*\ !*** ./src/views/Item/ItemContent.js ***! \***************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.children,r=e.className,n=e.content,s=e.description,u=e.extra,p=e.header,f=e.meta,m=e.verticalAlign,v=(0,l.default)(r,(0,c.useVerticalAlignProp)(m),"content"),g=(0,c.getUnhandledProps)(o,e),P=(0,c.getElementType)(o,e);return t?i.default.createElement(P,a({},g,{className:v}),t):i.default.createElement(P,a({},g,{className:v}),(0,c.createShorthand)(d.default,function(e){return{content:e}},p),(0,c.createShorthand)(b.default,function(e){return{content:e}},f),(0,c.createShorthand)(y.default,function(e){return{content:e}},s),(0,c.createShorthand)(h.default,function(e){return{content:e}},u),n)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! classnames */3),l=n(s),u=r(/*! react */1),i=n(u),c=r(/*! ../../lib */2),p=r(/*! ./ItemHeader */106),d=n(p),f=r(/*! ./ItemDescription */104),y=n(f),m=r(/*! ./ItemExtra */105),h=n(m),v=r(/*! ./ItemMeta */107),b=n(v);o._meta={name:"ItemContent",parent:"Item",type:c.META.TYPES.VIEW,props:{verticalAlign:c.SUI.VERTICAL_ALIGNMENTS}},o.propTypes={as:c.customPropTypes.as,children:u.PropTypes.node,className:u.PropTypes.string,content:c.customPropTypes.contentShorthand,description:c.customPropTypes.itemShorthand,extra:c.customPropTypes.itemShorthand,header:c.customPropTypes.itemShorthand,meta:c.customPropTypes.itemShorthand,verticalAlign:u.PropTypes.oneOf(o._meta.props.verticalAlign)},t.default=o},/*!*************************************!*\ !*** ./src/views/Item/ItemGroup.js ***! \*************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){var r={};for(var n in e)t.indexOf(n)>=0||Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=e[n]);return r}function a(e){var t=e.children,r=e.className,n=e.divided,s=e.items,i=e.link,p=e.relaxed,y=(0,c.default)("ui",r,(0,f.useKeyOnly)(n,"divided"),(0,f.useKeyOnly)(i,"link"),(0,f.useKeyOrValueAndKey)(p,"relaxed"),"items"),h=(0,f.getUnhandledProps)(a,e),v=(0,f.getElementType)(a,e);if(t)return d.default.createElement(v,u({},h,{className:y}),t);var b=(0,l.default)(s,function(e){var t=e.childKey,r=o(e,["childKey"]),n=t||[r.content,r.description,r.header,r.meta].join("-");return d.default.createElement(m.default,u({},r,{key:n}))});return d.default.createElement(v,u({},h,{className:y}),b)}Object.defineProperty(t,"__esModule",{value:!0});var s=r(/*! lodash/map */10),l=n(s),u=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},i=r(/*! classnames */3),c=n(i),p=r(/*! react */1),d=n(p),f=r(/*! ../../lib */2),y=r(/*! ./Item */211),m=n(y);a._meta={name:"ItemGroup",type:f.META.TYPES.VIEW,parent:"Item",props:{relaxed:["very"]}},a.propTypes={as:f.customPropTypes.as,children:p.PropTypes.node,className:p.PropTypes.string,divided:p.PropTypes.bool,items:f.customPropTypes.collectionShorthand,link:p.PropTypes.bool,relaxed:p.PropTypes.oneOfType([p.PropTypes.bool,p.PropTypes.oneOf(a._meta.props.relaxed)])},t.default=a},/*!*************************************!*\ !*** ./src/views/Item/ItemImage.js ***! \*************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.size,r=(0,u.getUnhandledProps)(o,e);return l.default.createElement(c.default,a({},r,{size:t,ui:!!t,wrapped:!0}))}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! react */1),l=n(s),u=r(/*! ../../lib */2),i=r(/*! ../../elements/Image */30),c=n(i);o._meta={name:"ItemImage",parent:"Item",type:u.META.TYPES.VIEW},o.propTypes={size:s.PropTypes.oneOf(c.default._meta.props.size)},t.default=o},/*!******************************************!*\ !*** ./src/views/Statistic/Statistic.js ***! \******************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.children,r=e.className,n=e.color,a=e.floated,s=e.horizontal,u=e.inverted,c=e.label,f=e.size,y=e.text,m=e.value,v=(0,i.default)("ui",n,(0,d.useValueAndKey)(a,"floated"),(0,d.useKeyOnly)(s,"horizontal"),(0,d.useKeyOnly)(u,"inverted"),f,r,"statistic"),g=(0,d.getUnhandledProps)(o,e),P=(0,d.getElementType)(o,e);return t?p.default.createElement(P,l({},g,{className:v}),t):p.default.createElement(P,l({},g,{className:v}),p.default.createElement(b.default,{text:y,value:m}),p.default.createElement(h.default,{label:c}))}Object.defineProperty(t,"__esModule",{value:!0});var a=r(/*! lodash/without */7),s=n(a),l=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},u=r(/*! classnames */3),i=n(u),c=r(/*! react */1),p=n(c),d=r(/*! ../../lib */2),f=r(/*! ./StatisticGroup */216),y=n(f),m=r(/*! ./StatisticLabel */217),h=n(m),v=r(/*! ./StatisticValue */218),b=n(v);o._meta={name:"Statistic",type:d.META.TYPES.VIEW,props:{color:d.SUI.COLORS,floated:d.SUI.FLOATS,size:(0,s.default)(d.SUI.SIZES,"big","massive","medium")}},o.propTypes={as:d.customPropTypes.as,children:c.PropTypes.node,className:c.PropTypes.string,color:c.PropTypes.oneOf(o._meta.props.color),floated:c.PropTypes.oneOf(o._meta.props.floated),horizontal:c.PropTypes.bool,inverted:c.PropTypes.bool,label:d.customPropTypes.contentShorthand,size:c.PropTypes.oneOf(o._meta.props.size),text:c.PropTypes.bool,value:d.customPropTypes.contentShorthand},o.Group=y.default,o.Label=h.default,o.Value=b.default,t.default=o},/*!***********************************************!*\ !*** ./src/views/Statistic/StatisticGroup.js ***! \***********************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.children,r=e.className,n=e.horizontal,a=e.items,u=e.widths,c=(0,i.default)("ui",(0,d.useKeyOnly)(n,"horizontal"),(0,d.useWidthProp)(u),"statistics",r),f=(0,d.getUnhandledProps)(o,e),m=(0,d.getElementType)(o,e);if(t)return p.default.createElement(m,l({},f,{className:c}),t);var h=(0,s.default)(a,function(e){return p.default.createElement(y.default,l({key:e.childKey||[e.label,e.title].join("-")},e))});return p.default.createElement(m,l({},f,{className:c}),h)}Object.defineProperty(t,"__esModule",{value:!0});var a=r(/*! lodash/map */10),s=n(a),l=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},u=r(/*! classnames */3),i=n(u),c=r(/*! react */1),p=n(c),d=r(/*! ../../lib */2),f=r(/*! ./Statistic */215),y=n(f);o._meta={name:"StatisticGroup",type:d.META.TYPES.VIEW,parent:"Statistic",props:{widths:d.SUI.WIDTHS}},o.propTypes={as:d.customPropTypes.as,children:c.PropTypes.node,className:c.PropTypes.string,horizontal:c.PropTypes.bool,items:d.customPropTypes.collectionShorthand,widths:c.PropTypes.oneOf(o._meta.props.widths)},t.default=o},/*!***********************************************!*\ !*** ./src/views/Statistic/StatisticLabel.js ***! \***********************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.children,r=e.className,n=e.label,s=(0,l.default)(r,"label"),u=(0,c.getUnhandledProps)(o,e),p=(0,c.getElementType)(o,e);return i.default.createElement(p,a({},u,{className:s}),t||n)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! classnames */3),l=n(s),u=r(/*! react */1),i=n(u),c=r(/*! ../../lib */2);o._meta={name:"StatisticLabel",parent:"Statistic",type:c.META.TYPES.VIEW},o.propTypes={as:c.customPropTypes.as,children:u.PropTypes.node,className:u.PropTypes.string,label:c.customPropTypes.contentShorthand},t.default=o},/*!***********************************************!*\ !*** ./src/views/Statistic/StatisticValue.js ***! \***********************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.children,r=e.className,n=e.text,s=e.value,u=(0,l.default)((0,c.useKeyOnly)(n,"text"),r,"value"),p=(0,c.getUnhandledProps)(o,e),d=(0,c.getElementType)(o,e);return i.default.createElement(d,a({},p,{className:u}),t||s)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! classnames */3),l=n(s),u=r(/*! react */1),i=n(u),c=r(/*! ../../lib */2);o._meta={name:"StatisticValue",parent:"Statistic",type:c.META.TYPES.VIEW},o.propTypes={as:c.customPropTypes.as,children:u.PropTypes.node,className:u.PropTypes.string,text:u.PropTypes.bool,value:c.customPropTypes.contentShorthand},t.default=o},/*!**************************!*\ !*** ./~/lodash/_Set.js ***! \**************************/ function(e,t,r){var n=r(/*! ./_getNative */26),o=r(/*! ./_root */11),a=n(o,"Set");e.exports=a},/*!*********************************!*\ !*** ./~/lodash/_Uint8Array.js ***! \*********************************/ function(e,t,r){var n=r(/*! ./_root */11),o=n.Uint8Array;e.exports=o},/*!******************************!*\ !*** ./~/lodash/_WeakMap.js ***! \******************************/ function(e,t,r){var n=r(/*! ./_getNative */26),o=r(/*! ./_root */11),a=n(o,"WeakMap");e.exports=a},/*!************************************!*\ !*** ./~/lodash/_arrayLikeKeys.js ***! \************************************/ function(e,t,r){function n(e,t){var r=s(e),n=!r&&a(e),c=!r&&!n&&l(e),d=!r&&!n&&!c&&i(e),f=r||n||c||d,y=f?o(e.length,String):[],m=y.length;for(var h in e)!t&&!p.call(e,h)||f&&("length"==h||c&&("offset"==h||"parent"==h)||d&&("buffer"==h||"byteLength"==h||"byteOffset"==h)||u(h,m))||y.push(h);return y}var o=r(/*! ./_baseTimes */232),a=r(/*! ./isArguments */76),s=r(/*! ./isArray */4),l=r(/*! ./isBuffer */43),u=r(/*! ./_isIndex */39),i=r(/*! ./isTypedArray */79),c=Object.prototype,p=c.hasOwnProperty;e.exports=n},/*!********************************!*\ !*** ./~/lodash/_arraySome.js ***! \********************************/ function(e,t){function r(e,t){for(var r=-1,n=null==e?0:e.length;++r<n;)if(t(e[r],r,e))return!0;return!1}e.exports=r},/*!*********************************!*\ !*** ./~/lodash/_baseAssign.js ***! \*********************************/ function(e,t,r){function n(e,t){return e&&o(t,a(t),e)}var o=r(/*! ./_copyObject */33),a=r(/*! ./keys */9);e.exports=n},/*!********************************!*\ !*** ./~/lodash/_baseClamp.js ***! \********************************/ function(e,t){function r(e,t,r){return e===e&&(void 0!==r&&(e=e<=r?e:r),void 0!==t&&(e=e>=t?e:t)),e}e.exports=r},/*!*************************************!*\ !*** ./~/lodash/_baseDifference.js ***! \*************************************/ function(e,t,r){function n(e,t,r,n){var p=-1,d=a,f=!0,y=e.length,m=[],h=t.length;if(!y)return m;r&&(t=l(t,u(r))),n?(d=s,f=!1):t.length>=c&&(d=i,f=!1,t=new o(t));e:for(;++p<y;){var v=e[p],b=null==r?v:r(v);if(v=n||0!==v?v:0,f&&b===b){for(var g=h;g--;)if(t[g]===b)continue e;m.push(v)}else d(t,b,n)||m.push(v)}return m}var o=r(/*! ./_SetCache */54),a=r(/*! ./_arrayIncludes */56),s=r(/*! ./_arrayIncludesWith */113),l=r(/*! ./_arrayMap */17),u=r(/*! ./_baseUnary */63),i=r(/*! ./_cacheHas */64),c=200;e.exports=n},/*!************************************!*\ !*** ./~/lodash/_baseFindIndex.js ***! \************************************/ function(e,t){function r(e,t,r,n){for(var o=e.length,a=r+(n?1:-1);n?a--:++a<o;)if(t(e[a],a,e))return a;return-1}e.exports=r},/*!*************************************!*\ !*** ./~/lodash/_baseGetAllKeys.js ***! \*************************************/ function(e,t,r){function n(e,t,r){var n=t(e);return a(e)?n:o(n,r(e))}var o=r(/*! ./_arrayPush */114),a=r(/*! ./isArray */4);e.exports=n},/*!**********************************!*\ !*** ./~/lodash/_baseIndexOf.js ***! \**********************************/ function(e,t,r){function n(e,t,r){return t===t?s(e,t,r):o(e,a,r)}var o=r(/*! ./_baseFindIndex */227),a=r(/*! ./_baseIsNaN */375),s=r(/*! ./_strictIndexOf */470);e.exports=n},/*!******************************!*\ !*** ./~/lodash/_baseMap.js ***! \******************************/ function(e,t,r){function n(e,t){var r=-1,n=a(e)?Array(e.length):[];return o(e,function(e,o,a){n[++r]=t(e,o,a)}),n}var o=r(/*! ./_baseEach */32),a=r(/*! ./isArrayLike */14);e.exports=n},/*!**********************************!*\ !*** ./~/lodash/_baseSetData.js ***! \**********************************/ function(e,t,r){var n=r(/*! ./identity */23),o=r(/*! ./_metaMap */251),a=o?function(e,t){return o.set(e,t),e}:n;e.exports=a},/*!********************************!*\ !*** ./~/lodash/_baseTimes.js ***! \********************************/ function(e,t){function r(e,t){for(var r=-1,n=Array(e);++r<e;)n[r]=t(r);return n}e.exports=r},/*!***********************************!*\ !*** ./~/lodash/_baseToString.js ***! \***********************************/ function(e,t,r){function n(e){if("string"==typeof e)return e;if(s(e))return a(e,n)+"";if(l(e))return c?c.call(e):"";var t=e+"";return"0"==t&&1/e==-u?"-0":t}var o=r(/*! ./_Symbol */31),a=r(/*! ./_arrayMap */17),s=r(/*! ./isArray */4),l=r(/*! ./isSymbol */29),u=1/0,i=o?o.prototype:void 0,c=i?i.toString:void 0;e.exports=n},/*!***********************************!*\ !*** ./~/lodash/_castFunction.js ***! \***********************************/ function(e,t,r){function n(e){return"function"==typeof e?e:o}var o=r(/*! ./identity */23);e.exports=n},/*!**********************************!*\ !*** ./~/lodash/_composeArgs.js ***! \**********************************/ function(e,t){function r(e,t,r,o){for(var a=-1,s=e.length,l=r.length,u=-1,i=t.length,c=n(s-l,0),p=Array(i+c),d=!o;++u<i;)p[u]=t[u];for(;++a<l;)(d||a<s)&&(p[r[a]]=e[a]);for(;c--;)p[u++]=e[a++];return p}var n=Math.max;e.exports=r},/*!***************************************!*\ !*** ./~/lodash/_composeArgsRight.js ***! \***************************************/ function(e,t){function r(e,t,r,o){for(var a=-1,s=e.length,l=-1,u=r.length,i=-1,c=t.length,p=n(s-u,0),d=Array(p+c),f=!o;++a<p;)d[a]=e[a];for(var y=a;++i<c;)d[y+i]=t[i];for(;++l<u;)(f||a<s)&&(d[y+r[l]]=e[a++]);return d}var n=Math.max;e.exports=r},/*!***********************************!*\ !*** ./~/lodash/_createHybrid.js ***! \***********************************/ function(e,t,r){function n(e,t,r,g,P,T,O,_,E,j){function w(){for(var f=arguments.length,y=Array(f),m=f;m--;)y[m]=arguments[m];if(k)var h=i(w),v=s(y,h);if(g&&(y=o(y,g,P,k)),T&&(y=a(y,T,O,k)),f-=v,k&&f<j){var b=p(y,h);return u(e,t,n,w.placeholder,r,y,b,_,E,j-f)}var N=M?r:this,I=x?N[e]:e;return f=y.length,_?y=c(y,_):A&&f>1&&y.reverse(),S&&E<f&&(y.length=E),this&&this!==d&&this instanceof w&&(I=C||l(I)),I.apply(N,y)}var S=t&v,M=t&f,x=t&y,k=t&(m|h),A=t&b,C=x?void 0:l(e);return w}var o=r(/*! ./_composeArgs */235),a=r(/*! ./_composeArgsRight */236),s=r(/*! ./_countHolders */411),l=r(/*! ./_createCtor */66),u=r(/*! ./_createRecurry */238),i=r(/*! ./_getHolder */68),c=r(/*! ./_reorder */462),p=r(/*! ./_replaceHolders */41),d=r(/*! ./_root */11),f=1,y=2,m=8,h=16,v=128,b=512;e.exports=n},/*!************************************!*\ !*** ./~/lodash/_createRecurry.js ***! \************************************/ function(e,t,r){function n(e,t,r,n,f,y,m,h,v,b){var g=t&c,P=g?m:void 0,T=g?void 0:m,O=g?y:void 0,_=g?void 0:y;t|=g?p:d,t&=~(g?d:p),t&i||(t&=~(l|u));var E=[e,t,f,O,P,_,T,h,v,b],j=r.apply(void 0,E);return o(e)&&a(j,E),j.placeholder=n,s(j,e,t)}var o=r(/*! ./_isLaziable */247),a=r(/*! ./_setData */254),s=r(/*! ./_setWrapToString */255),l=1,u=2,i=4,c=8,p=32,d=64;e.exports=n},/*!*************************************!*\ !*** ./~/lodash/_defineProperty.js ***! \*************************************/ function(e,t,r){var n=r(/*! ./_getNative */26),o=function(){try{var e=n(Object,"defineProperty");return e({},"",{}),e}catch(e){}}();e.exports=o},/*!**********************************!*\ !*** ./~/lodash/_equalArrays.js ***! \**********************************/ function(e,t,r){function n(e,t,r,n,i,c){var p=r&l,d=e.length,f=t.length;if(d!=f&&!(p&&f>d))return!1;var y=c.get(e);if(y&&c.get(t))return y==t;var m=-1,h=!0,v=r&u?new o:void 0;for(c.set(e,t),c.set(t,e);++m<d;){var b=e[m],g=t[m];if(n)var P=p?n(g,b,m,t,e,c):n(b,g,m,e,t,c);if(void 0!==P){if(P)continue;h=!1;break}if(v){if(!a(t,function(e,t){if(!s(v,t)&&(b===e||i(b,e,r,n,c)))return v.push(t)})){h=!1;break}}else if(b!==g&&!i(b,g,r,n,c)){h=!1;break}}return c.delete(e),c.delete(t),h}var o=r(/*! ./_SetCache */54),a=r(/*! ./_arraySome */223),s=r(/*! ./_cacheHas */64),l=1,u=2;e.exports=n},/*!*********************************!*\ !*** ./~/lodash/_freeGlobal.js ***! \*********************************/ function(e,t){(function(t){var r="object"==typeof t&&t&&t.Object===Object&&t;e.exports=r}).call(t,function(){return this}())},/*!***********************************!*\ !*** ./~/lodash/_getAllKeysIn.js ***! \***********************************/ function(e,t,r){function n(e){return o(e,s,a)}var o=r(/*! ./_baseGetAllKeys */228),a=r(/*! ./_getSymbolsIn */244),s=r(/*! ./keysIn */270);e.exports=n},/*!**********************************!*\ !*** ./~/lodash/_getFuncName.js ***! \**********************************/ function(e,t,r){function n(e){for(var t=e.name+"",r=o[t],n=s.call(o,t)?r.length:0;n--;){var a=r[n],l=a.func;if(null==l||l==e)return a.name}return t}var o=r(/*! ./_realNames */461),a=Object.prototype,s=a.hasOwnProperty;e.exports=n},/*!***********************************!*\ !*** ./~/lodash/_getSymbolsIn.js ***! \***********************************/ function(e,t,r){var n=r(/*! ./_arrayPush */114),o=r(/*! ./_getPrototype */70),a=r(/*! ./_getSymbols */123),s=r(/*! ./stubArray */276),l=Object.getOwnPropertySymbols,u=l?function(e){for(var t=[];e;)n(t,a(e)),e=o(e);return t}:s;e.exports=u},/*!******************************!*\ !*** ./~/lodash/_hasPath.js ***! \******************************/ function(e,t,r){function n(e,t,r){t=o(t,e);for(var n=-1,c=t.length,p=!1;++n<c;){var d=i(t[n]);if(!(p=null!=e&&r(e,d)))break;e=e[d]}return p||++n!=c?p:(c=null==e?0:e.length,!!c&&u(c)&&l(d,c)&&(s(e)||a(e)))}var o=r(/*! ./_castPath */25),a=r(/*! ./isArguments */76),s=r(/*! ./isArray */4),l=r(/*! ./_isIndex */39),u=r(/*! ./isLength */131),i=r(/*! ./_toKey */22);e.exports=n},/*!*********************************!*\ !*** ./~/lodash/_hasUnicode.js ***! \*********************************/ function(e,t){function r(e){return c.test(e)}var n="\\ud800-\\udfff",o="\\u0300-\\u036f",a="\\ufe20-\\ufe2f",s="\\u20d0-\\u20ff",l=o+a+s,u="\\ufe0e\\ufe0f",i="\\u200d",c=RegExp("["+i+n+l+u+"]");e.exports=r},/*!*********************************!*\ !*** ./~/lodash/_isLaziable.js ***! \*********************************/ function(e,t,r){function n(e){var t=s(e),r=l[t];if("function"!=typeof r||!(t in o.prototype))return!1;if(e===r)return!0;var n=a(r);return!!n&&e===n[0]}var o=r(/*! ./_LazyWrapper */108),a=r(/*! ./_getData */122),s=r(/*! ./_getFuncName */243),l=r(/*! ./wrapperLodash */530);e.exports=n},/*!*****************************************!*\ !*** ./~/lodash/_isStrictComparable.js ***! \*****************************************/ function(e,t,r){function n(e){return e===e&&!o(e)}var o=r(/*! ./isObject */12);e.exports=n},/*!*********************************!*\ !*** ./~/lodash/_mapToArray.js ***! \*********************************/ function(e,t){function r(e){var t=-1,r=Array(e.size);return e.forEach(function(e,n){r[++t]=[n,e]}),r}e.exports=r},/*!**********************************************!*\ !*** ./~/lodash/_matchesStrictComparable.js ***! \**********************************************/ function(e,t){function r(e,t){return function(r){return null!=r&&(r[e]===t&&(void 0!==t||e in Object(r)))}}e.exports=r},/*!******************************!*\ !*** ./~/lodash/_metaMap.js ***! \******************************/ function(e,t,r){var n=r(/*! ./_WeakMap */221),o=n&&new n;e.exports=o},/*!*******************************!*\ !*** ./~/lodash/_overRest.js ***! \*******************************/ function(e,t,r){function n(e,t,r){return t=a(void 0===t?e.length-1:t,0),function(){for(var n=arguments,s=-1,l=a(n.length-t,0),u=Array(l);++s<l;)u[s]=n[t+s];s=-1;for(var i=Array(t+1);++s<t;)i[s]=n[s];return i[t]=r(u),o(e,this,i)}}var o=r(/*! ./_apply */55),a=Math.max;e.exports=n},/*!*****************************!*\ !*** ./~/lodash/_parent.js ***! \*****************************/ function(e,t,r){function n(e,t){return t.length<2?e:o(e,a(t,0,-1))}var o=r(/*! ./_baseGet */61),a=r(/*! ./_baseSlice */62);e.exports=n},/*!******************************!*\ !*** ./~/lodash/_setData.js ***! \******************************/ function(e,t,r){var n=r(/*! ./_baseSetData */231),o=r(/*! ./_shortOut */256),a=o(n);e.exports=a},/*!**************************************!*\ !*** ./~/lodash/_setWrapToString.js ***! \**************************************/ function(e,t,r){function n(e,t,r){var n=t+"";return s(e,a(n,l(o(n),r)))}var o=r(/*! ./_getWrapDetails */431),a=r(/*! ./_insertWrapDetails */441),s=r(/*! ./_setToString */127),l=r(/*! ./_updateWrapDetails */474);e.exports=n},/*!*******************************!*\ !*** ./~/lodash/_shortOut.js ***! \*******************************/ function(e,t){function r(e){var t=0,r=0;return function(){var s=a(),l=o-(s-r);if(r=s,l>0){if(++t>=n)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}var n=800,o=16,a=Date.now;e.exports=r},/*!***********************************!*\ !*** ./~/lodash/_stringToPath.js ***! \***********************************/ function(e,t,r){var n=r(/*! ./_memoizeCapped */455),o=/^\./,a=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,s=/\\(\\)?/g,l=n(function(e){var t=[];return o.test(e)&&t.push(""),e.replace(a,function(e,r,n,o){t.push(n?o.replace(s,"$1"):r||e)}),t});e.exports=l},/*!*******************************!*\ !*** ./~/lodash/_toSource.js ***! \*******************************/ function(e,t){function r(e){if(null!=e){try{return o.call(e)}catch(e){}try{return e+""}catch(e){}}return""}var n=Function.prototype,o=n.toString;e.exports=r},/*!*****************************!*\ !*** ./~/lodash/compact.js ***! \*****************************/ function(e,t){function r(e){for(var t=-1,r=null==e?0:e.length,n=0,o=[];++t<r;){var a=e[t];a&&(o[n++]=a)}return o}e.exports=r},/*!***************************!*\ !*** ./~/lodash/curry.js ***! \***************************/ function(e,t,r){function n(e,t,r){t=r?void 0:t;var s=o(e,a,void 0,void 0,void 0,void 0,void 0,t);return s.placeholder=n.placeholder,s}var o=r(/*! ./_createWrap */38),a=8;n.placeholder={},e.exports=n},/*!***************************!*\ !*** ./~/lodash/every.js ***! \***************************/ function(e,t,r){function n(e,t,r){var n=l(e)?o:a;return r&&u(e,t,r)&&(t=void 0),n(e,s(t,3))}var o=r(/*! ./_arrayEvery */358),a=r(/*! ./_baseEvery */363),s=r(/*! ./_baseIteratee */13),l=r(/*! ./isArray */4),u=r(/*! ./_isIterateeCall */71);e.exports=n},/*!*******************************!*\ !*** ./~/lodash/findIndex.js ***! \*******************************/ function(e,t,r){function n(e,t,r){var n=null==e?0:e.length;if(!n)return-1;var u=null==r?0:s(r);return u<0&&(u=l(n+u,0)),o(e,a(t,3),u)}var o=r(/*! ./_baseFindIndex */227),a=r(/*! ./_baseIteratee */13),s=r(/*! ./toInteger */20),l=Math.max;e.exports=n},/*!*****************************!*\ !*** ./~/lodash/fp/flow.js ***! \*****************************/ function(e,t,r){var n=r(/*! ./convert */6),o=n("flow",r(/*! ../flow */486));o.placeholder=r(/*! ./placeholder */5),e.exports=o},/*!*********************************!*\ !*** ./~/lodash/fp/includes.js ***! \*********************************/ function(e,t,r){var n=r(/*! ./convert */6),o=n("includes",r(/*! ../includes */75));o.placeholder=r(/*! ./placeholder */5),e.exports=o},/*!***************************!*\ !*** ./~/lodash/hasIn.js ***! \***************************/ function(e,t,r){function n(e,t){return null!=e&&a(e,t,o)}var o=r(/*! ./_baseHasIn */368),a=r(/*! ./_hasPath */245);e.exports=n},/*!****************************!*\ !*** ./~/lodash/invoke.js ***! \****************************/ function(e,t,r){var n=r(/*! ./_baseInvoke */371),o=r(/*! ./_baseRest */18),a=o(n);e.exports=a},/*!***************************!*\ !*** ./~/lodash/isNil.js ***! \***************************/ function(e,t){function r(e){return null==e}e.exports=r},/*!******************************!*\ !*** ./~/lodash/isNumber.js ***! \******************************/ function(e,t,r){function n(e){return"number"==typeof e||a(e)&&o(e)==s}var o=r(/*! ./_baseGetTag */21),a=r(/*! ./isObjectLike */15),s="[object Number]";e.exports=n},/*!******************************!*\ !*** ./~/lodash/isString.js ***! \******************************/ function(e,t,r){function n(e){return"string"==typeof e||!a(e)&&s(e)&&o(e)==l}var o=r(/*! ./_baseGetTag */21),a=r(/*! ./isArray */4),s=r(/*! ./isObjectLike */15),l="[object String]";e.exports=n},/*!****************************!*\ !*** ./~/lodash/keysIn.js ***! \****************************/ function(e,t,r){function n(e){return s(e)?o(e,!0):a(e)}var o=r(/*! ./_arrayLikeKeys */222),a=r(/*! ./_baseKeysIn */378),s=r(/*! ./isArrayLike */14);e.exports=n},/*!**************************!*\ !*** ./~/lodash/last.js ***! \**************************/ function(e,t){function r(e){var t=null==e?0:e.length;return t?e[t-1]:void 0}e.exports=r},/*!**************************!*\ !*** ./~/lodash/noop.js ***! \**************************/ function(e,t){function r(){}e.exports=r},/*!****************************!*\ !*** ./~/lodash/reduce.js ***! \****************************/ function(e,t,r){function n(e,t,r){var n=u(e)?o:l,i=arguments.length<3;return n(e,s(t,4),r,i,a)}var o=r(/*! ./_arrayReduce */57),a=r(/*! ./_baseEach */32),s=r(/*! ./_baseIteratee */13),l=r(/*! ./_baseReduce */388),u=r(/*! ./isArray */4);e.exports=n},/*!**************************!*\ !*** ./~/lodash/some.js ***! \**************************/ function(e,t,r){function n(e,t,r){var n=l(e)?o:s;return r&&u(e,t,r)&&(t=void 0),n(e,a(t,3))}var o=r(/*! ./_arraySome */223),a=r(/*! ./_baseIteratee */13),s=r(/*! ./_baseSome */391),l=r(/*! ./isArray */4),u=r(/*! ./_isIterateeCall */71);e.exports=n},/*!********************************!*\ !*** ./~/lodash/startsWith.js ***! \********************************/ function(e,t,r){function n(e,t,r){return e=l(e),r=o(s(r),0,e.length),t=a(t),e.slice(r,r+t.length)==t}var o=r(/*! ./_baseClamp */225),a=r(/*! ./_baseToString */233),s=r(/*! ./toInteger */20),l=r(/*! ./toString */24);e.exports=n},/*!*******************************!*\ !*** ./~/lodash/stubArray.js ***! \*******************************/ function(e,t){function r(){return[]}e.exports=r},/*!***************************!*\ !*** ./~/lodash/times.js ***! \***************************/ function(e,t,r){function n(e,t){if(e=s(e),e<1||e>l)return[];var r=u,n=i(e,u);t=a(t),e-=u;for(var c=o(n,t);++r<e;)t(r);return c}var o=r(/*! ./_baseTimes */232),a=r(/*! ./_castFunction */234),s=r(/*! ./toInteger */20),l=9007199254740991,u=4294967295,i=Math.min;e.exports=n},/*!******************************!*\ !*** ./~/lodash/toFinite.js ***! \******************************/ function(e,t,r){function n(e){if(!e)return 0===e?e:0;if(e=o(e),e===a||e===-a){var t=e<0?-1:1;return t*s}return e===e?e:0}var o=r(/*! ./toNumber */81),a=1/0,s=1.7976931348623157e308;e.exports=n},/*!***************************************!*\ !*** ./src/addons/Confirm/Confirm.js ***! \***************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.open,r=e.cancelButton,n=e.confirmButton,a=e.header,u=e.content,p=e.onConfirm,f=e.onCancel,m=(0,c.getUnhandledProps)(o,e),h={};return(0,s.default)(e,"open")&&(h.open=t),i.default.createElement(y.default,l({},h,{size:"small",onClose:f},m),a&&i.default.createElement(y.default.Header,null,a),u&&i.default.createElement(y.default.Content,null,u),i.default.createElement(y.default.Actions,null,i.default.createElement(d.default,{onClick:f},r),i.default.createElement(d.default,{primary:!0,onClick:p},n)))}Object.defineProperty(t,"__esModule",{value:!0});var a=r(/*! lodash/has */27),s=n(a),l=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},u=r(/*! react */1),i=n(u),c=r(/*! ../../lib */2),p=r(/*! ../../elements/Button */85),d=n(p),f=r(/*! ../../modules/Modal */193),y=n(f);o._meta={name:"Confirm",type:c.META.TYPES.ADDON},o.propTypes={open:u.PropTypes.bool,cancelButton:u.PropTypes.string,confirmButton:u.PropTypes.string,header:u.PropTypes.string,content:u.PropTypes.string,onConfirm:u.PropTypes.func,onCancel:u.PropTypes.func},o.defaultProps={cancelButton:"Cancel",confirmButton:"OK",content:"Are you sure?"},t.default=o},/*!*************************************!*\ !*** ./src/addons/Confirm/index.js ***! \*************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var o=r(/*! ./Confirm */279),a=n(o);t.default=a.default},/*!*************************************!*\ !*** ./src/addons/Portal/Portal.js ***! \*************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var l=r(/*! lodash/invoke */266),u=n(l),i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},c=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),p=r(/*! react */1),d=n(p),f=r(/*! react-dom */532),y=n(f),m=r(/*! ../../lib */2),h=(0,m.makeDebugger)("portal"),v={name:"Portal",type:m.META.TYPES.ADDON},b=function(e){function t(){var e,r,n,s;o(this,t);for(var l=arguments.length,c=Array(l),p=0;p<l;p++)c[p]=arguments[p];return r=n=a(this,(e=t.__proto__||Object.getPrototypeOf(t)).call.apply(e,[this].concat(c))),n.state={},n.handleDocumentClick=function(e){var t=n.props,r=t.closeOnDocumentClick,o=t.closeOnRootNodeClick;n.node&&n.portal&&!n.portal.contains(e.target)&&(r||o&&n.node.contains(e.target))&&(h("handleDocumentClick()"),e.stopPropagation(),n.close(e))},n.handleEscape=function(e){n.props.closeOnEscape&&m.keyboardKey.getCode(e)===m.keyboardKey.Escape&&(h("handleEscape()"),e.preventDefault(),n.close(e))},n.handlePortalMouseLeave=function(e){var t=n.props,r=t.closeOnPortalMouseLeave,o=t.mouseLeaveDelay;r&&(h("handlePortalMouseLeave()"),n.mouseLeaveTimer=n.closeWithTimeout(e,o))},n.handlePortalMouseOver=function(e){var t=n.props.closeOnPortalMouseLeave;t&&(h("handlePortalMouseOver()"),clearTimeout(n.mouseLeaveTimer))},n.handleTriggerBlur=function(e){var t=n.props,r=t.trigger,o=t.closeOnTriggerBlur;(0,u.default)(r,"props.onBlur",e),o&&(h("handleTriggerBlur()"),n.close(e))},n.handleTriggerClick=function(e){var t=n.props,r=t.trigger,o=t.closeOnTriggerClick,a=t.openOnTriggerClick,s=n.state.open;(0,u.default)(r,"props.onClick",e),s&&o?(h("handleTriggerClick() - close"),e.stopPropagation(),n.close(e)):!s&&a&&(h("handleTriggerClick() - open"),e.stopPropagation(),n.open(e)),e.nativeEvent.stopImmediatePropagation()},n.handleTriggerFocus=function(e){var t=n.props,r=t.trigger,o=t.openOnTriggerFocus;(0,u.default)(r,"props.onFocus",e),o&&(h("handleTriggerFocus()"),n.open(e))},n.handleTriggerMouseLeave=function(e){clearTimeout(n.mouseOverTimer);var t=n.props,r=t.trigger,o=t.closeOnTriggerMouseLeave,a=t.mouseLeaveDelay;(0,u.default)(r,"props.onMouseLeave",e),o&&(h("handleTriggerMouseLeave()"),n.mouseLeaveTimer=n.closeWithTimeout(e,a))},n.handleTriggerMouseOver=function(e){clearTimeout(n.mouseLeaveTimer);var t=n.props,r=t.trigger,o=t.mouseOverDelay,a=t.openOnTriggerMouseOver;(0,u.default)(r,"props.onMouseOver",e),a&&(h("handleTriggerMouseOver()"),n.mouseOverTimer=n.openWithTimeout(e,o))},n.open=function(e){h("open()");var t=n.props.onOpen;t&&t(e,n.props),n.trySetState({open:!0})},n.openWithTimeout=function(e,t){var r=i({},e);return setTimeout(function(){return n.open(r)},t||0)},n.close=function(e){h("close()");var t=n.props.onClose;t&&t(e,n.props),n.trySetState({open:!1})},n.closeWithTimeout=function(e,t){var r=i({},e);return setTimeout(function(){return n.close(r)},t||0)},n.mountPortal=function(){if(m.isBrowser&&!n.node){h("mountPortal()");var e=n.props,t=e.mountNode,r=e.prepend;n.node=document.createElement("div"),r?t.insertBefore(n.node,t.firstElementChild):t.appendChild(n.node),document.addEventListener("click",n.handleDocumentClick),document.addEventListener("keydown",n.handleEscape);var o=n.props.onMount;o&&o(null,n.props)}},n.unmountPortal=function(){if(m.isBrowser&&n.node){h("unmountPortal()"),y.default.unmountComponentAtNode(n.node),n.node.parentNode.removeChild(n.node),n.portal.removeEventListener("mouseleave",n.handlePortalMouseLeave),n.portal.removeEventListener("mouseover",n.handlePortalMouseOver),n.node=null,n.portal=null,document.removeEventListener("click",n.handleDocumentClick),document.removeEventListener("keydown",n.handleEscape);var e=n.props.onUnmount;e&&e(null,n.props)}},s=r,a(n,s)}return s(t,e),c(t,[{key:"componentDidMount",value:function(){this.renderPortal()}},{key:"componentDidUpdate",value:function(e,t){this.renderPortal(),t.open&&!this.state.open&&(h("portal closed"),this.unmountPortal())}},{key:"componentWillUnmount",value:function(){this.unmountPortal(),clearTimeout(this.mouseOverTimer),clearTimeout(this.mouseLeaveTimer)}},{key:"renderPortal",value:function(){if(this.state.open){h("renderPortal()");var e=this.props,t=e.children,r=e.className;if(this.mountPortal(),!m.isBrowser)return null;this.node.className=r||"",this.portal&&(this.portal.removeEventListener("mouseleave",this.handlePortalMouseLeave),this.portal.removeEventListener("mouseover",this.handlePortalMouseOver)),y.default.unstable_renderSubtreeIntoContainer(this,p.Children.only(t),this.node),this.portal=this.node.firstElementChild,this.portal.addEventListener("mouseleave",this.handlePortalMouseLeave),this.portal.addEventListener("mouseover",this.handlePortalMouseOver)}}},{key:"render",value:function(){var e=this.props.trigger;return e?d.default.cloneElement(e,{onBlur:this.handleTriggerBlur,onClick:this.handleTriggerClick,onFocus:this.handleTriggerFocus,onMouseLeave:this.handleTriggerMouseLeave,onMouseOver:this.handleTriggerMouseOver}):null}}]),t}(m.AutoControlledComponent);b.propTypes={children:p.PropTypes.node.isRequired,className:p.PropTypes.string,closeOnRootNodeClick:m.customPropTypes.every([m.customPropTypes.disallow(["closeOnDocumentClick"]),p.PropTypes.bool]),closeOnDocumentClick:m.customPropTypes.every([m.customPropTypes.disallow(["closeOnRootNodeClick"]),p.PropTypes.bool]),closeOnEscape:p.PropTypes.bool,closeOnPortalMouseLeave:p.PropTypes.bool,closeOnTriggerBlur:p.PropTypes.bool,closeOnTriggerClick:p.PropTypes.bool,closeOnTriggerMouseLeave:p.PropTypes.bool,defaultOpen:p.PropTypes.bool,mountNode:p.PropTypes.any,mouseLeaveDelay:p.PropTypes.number,mouseOverDelay:p.PropTypes.number,onClose:p.PropTypes.func,onMount:p.PropTypes.func,onOpen:p.PropTypes.func,onUnmount:p.PropTypes.func,open:p.PropTypes.bool,openOnTriggerClick:p.PropTypes.bool,openOnTriggerFocus:p.PropTypes.bool,openOnTriggerMouseOver:p.PropTypes.bool,prepend:p.PropTypes.bool,trigger:p.PropTypes.node},b.defaultProps={closeOnDocumentClick:!0,closeOnEscape:!0,openOnTriggerClick:!0,mountNode:m.isBrowser?document.body:null},b.autoControlledProps=["open"],b._meta=v,t.default=b},/*!***********************************!*\ !*** ./src/addons/Radio/Radio.js ***! \***********************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.slider,r=e.toggle,n=e.type,s=(0,u.getUnhandledProps)(o,e),i=!(t||r)||void 0;return l.default.createElement(c.default,a({},s,{type:n,radio:i,slider:t,toggle:r}))}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! react */1),l=n(s),u=r(/*! ../../lib */2),i=r(/*! ../../modules/Checkbox */51),c=n(i);o._meta={name:"Radio",type:u.META.TYPES.ADDON,props:{type:c.default._meta.props.type}},o.propTypes={slider:c.default.propTypes.slider,toggle:c.default.propTypes.toggle,type:s.PropTypes.oneOf(o._meta.props.type)},o.defaultProps={type:"radio"},t.default=o},/*!*************************************!*\ !*** ./src/addons/Select/Select.js ***! \*************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){return l.default.createElement(c.default,a({},e,{selection:!0}))}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! react */1),l=n(s),u=r(/*! ../../lib */2),i=r(/*! ../../modules/Dropdown */93),c=n(i);o._meta={name:"Select",type:u.META.TYPES.ADDON},t.default=o},/*!*****************************************!*\ !*** ./src/addons/TextArea/TextArea.js ***! \*****************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var l=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},u=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),i=r(/*! react */1),c=n(i),p=r(/*! ../../lib */2),d=function(e){function t(){var e,r,n,s;o(this,t);for(var u=arguments.length,i=Array(u),c=0;c<u;c++)i[c]=arguments[c];return r=n=a(this,(e=t.__proto__||Object.getPrototypeOf(t)).call.apply(e,[this].concat(i))),n.handleChange=function(e){var t=n.props.onChange;t&&t(e,l({},n.props,{value:e.target&&e.target.value}))},s=r,a(n,s)}return s(t,e),u(t,[{key:"render",value:function(){var e=(0,p.getUnhandledProps)(t,this.props),r=(0,p.getElementType)(t,this.props);return c.default.createElement(r,l({},e,{onChange:this.handleChange}))}}]),t}(i.Component);d._meta={name:"TextArea",type:p.META.TYPES.ADDON},d.propTypes={as:p.customPropTypes.as,onChange:i.PropTypes.func},d.defaultProps={as:"textarea"},t.default=d},/*!**************************************************!*\ !*** ./src/collections/Breadcrumb/Breadcrumb.js ***! \**************************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.children,r=e.className,n=e.divider,a=e.icon,s=e.size,l=e.sections,i=(0,f.default)("ui",r,s,"breadcrumb"),d=(0,h.getUnhandledProps)(o,e),y=(0,h.getElementType)(o,e);if(t)return m.default.createElement(y,p({},d,{className:i}),t);var v=[];return(0,c.default)(l,function(e,t){var r=P.default.create(e);if(v.push(r),t!==l.length-1){var o=void 0;o=e.key?e.key+"_divider":(0,u.default)(r.props,function(e,t){return t+"="+("function"==typeof e?e.name||"func":e)}).join("|"),v.push(b.default.create({content:n,icon:a,key:o}))}}),m.default.createElement(y,p({},d,{className:i}),v)}Object.defineProperty(t,"__esModule",{value:!0});var a=r(/*! lodash/without */7),s=n(a),l=r(/*! lodash/map */10),u=n(l),i=r(/*! lodash/each */74),c=n(i),p=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},d=r(/*! classnames */3),f=n(d),y=r(/*! react */1),m=n(y),h=r(/*! ../../lib */2),v=r(/*! ./BreadcrumbDivider */138),b=n(v),g=r(/*! ./BreadcrumbSection */139),P=n(g);o._meta={name:"Breadcrumb",type:h.META.TYPES.COLLECTION,props:{size:(0,s.default)(h.SUI.SIZES,"medium")}},o.propTypes={as:h.customPropTypes.as,children:y.PropTypes.node,className:y.PropTypes.string,divider:h.customPropTypes.every([h.customPropTypes.disallow(["icon"]),h.customPropTypes.contentShorthand]),icon:h.customPropTypes.every([h.customPropTypes.disallow(["divider"]),h.customPropTypes.itemShorthand]),sections:h.customPropTypes.collectionShorthand,size:y.PropTypes.oneOf(o._meta.props.size)},o.Divider=b.default,o.Section=P.default,t.default=o},/*!*********************************************!*\ !*** ./src/collections/Breadcrumb/index.js ***! \*********************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var o=r(/*! ./Breadcrumb */285),a=n(o);t.default=a.default},/*!**************************************!*\ !*** ./src/collections/Form/Form.js ***! \**************************************/ function(e,t,r){(function(e){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function l(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function u(t){B("formSerializer()");var r={};return t?((0,b.default)(t.querySelectorAll('input[type="checkbox"]'),function(n,o,a){var s=Y(n),l=(0,h.default)(a,{name:s});if(1===l.length)return r[s]=n.checked&&"on"!==n.value?n.value:n.checked,void q(r,s,n);if(Array.isArray(r[s])||(r[s]=[]),n.checked&&r[s].push(n.value),q(r,s,n),"production"!==e.NODE_ENV&&"on"===n.value){var u=["Encountered a checkbox in a group with the default browser value 'on'.","Each checkbox in a group should have a unique value.","Otherwise, the checkbox value will serialize as ['on', ...]."].join(" ");console.error(u,n,t)}}),(0,b.default)(t.querySelectorAll('input[type="radio"]'),function(n,o,a){var s=Y(n),l=(0,y.default)(a,{name:s,checked:!0});if(l?r[s]=l.value:r[s]=null,q(r,s,n),"production"!==e.NODE_ENV&&"on"===n.value){var u=["Encountered a radio with the default browser value 'on'.","Each radio should have a unique value.","Otherwise, the radio value will serialize as { [name]: 'on' }."].join(" ");console.error(u,n,t)}}),(0,b.default)(t.querySelectorAll('input:not([type="radio"]):not([type="checkbox"])'),function(e){var t=Y(e);r[t]=e.value,q(r,t,e)}),(0,b.default)(t.querySelectorAll("textarea"),function(e){var t=Y(e);r[t]=e.value,q(r,t,e)}),(0,b.default)(t.querySelectorAll("select"),function(e){var t=Y(e);e.multiple?r[t]=(0,d.default)((0,h.default)(e.querySelectorAll("option"),"selected"),"value"):r[t]=e.value,q(r,t,e)}),r):r}Object.defineProperty(t,"__esModule",{value:!0});var i=r(/*! lodash/without */7),c=n(i),p=r(/*! lodash/map */10),d=n(p),f=r(/*! lodash/find */129),y=n(f),m=r(/*! lodash/filter */128),h=n(m),v=r(/*! lodash/each */74),b=n(v),g=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},P=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),T=r(/*! classnames */3),O=n(T),_=r(/*! react */1),E=n(_),j=r(/*! ../../lib */2),w=r(/*! ./FormButton */140),S=n(w),M=r(/*! ./FormCheckbox */141),x=n(M),k=r(/*! ./FormDropdown */142),A=n(k),C=r(/*! ./FormField */16),N=n(C),I=r(/*! ./FormGroup */143),K=n(I),L=r(/*! ./FormInput */144),U=n(L),D=r(/*! ./FormRadio */145),R=n(D),z=r(/*! ./FormSelect */146),W=n(z),F=r(/*! ./FormTextArea */147),V=n(F),B=(0,j.makeDebugger)("form"),Y=function(e){var t=e.name;return t},q=function(){};"production"!==e.NODE_ENV&&(q=function(e,t,r){B("serialized "+JSON.stringify(l({},t,e[t]))+" from:",r)},Y=function(e){var t=e.name;if(!t){var r=["Encountered a form control node without a name attribute.","Each node in a group should have a name.",'Otherwise, the node will serialize as { "undefined": <value> }.'].join(" ");console.error(r,e)}return t});var H={name:"Form",type:j.META.TYPES.COLLECTION,props:{widths:["equal"],size:(0,c.default)(j.SUI.SIZES,"medium")}},G=function(e){function t(){var e,r,n,s;o(this,t);for(var l=arguments.length,u=Array(l),i=0;i<l;i++)u[i]=arguments[i];return r=n=a(this,(e=t.__proto__||Object.getPrototypeOf(t)).call.apply(e,[this].concat(u))),n._form=null,n.handleRef=function(e){return n._form=n._form||e},n.handleSubmit=function(e){var t=n.props,r=t.onSubmit,o=t.serializer;r&&r(e,o(n._form))},s=r,a(n,s)}return s(t,e),P(t,[{key:"render",value:function(){var e=this.props,r=e.children,n=e.className,o=e.error,a=e.loading,s=e.reply,l=e.size,u=e.success,i=e.warning,c=e.widths,p=(0,O.default)("ui",l,(0,j.useKeyOnly)(o,"error"),(0,j.useKeyOnly)(a,"loading"),(0,j.useKeyOnly)(s,"reply"),(0,j.useKeyOnly)(u,"success"),(0,j.useKeyOnly)(i,"warning"),(0,j.useWidthProp)(c,null,!0),"form",n),d=(0,j.getUnhandledProps)(t,this.props),f=(0,j.getElementType)(t,this.props);return E.default.createElement(f,g({},d,{className:p,ref:this.handleRef,onSubmit:this.handleSubmit}),r)}}]),t}(_.Component);G.defaultProps={as:"form",serializer:u},G.propTypes={as:j.customPropTypes.as,children:_.PropTypes.node,className:_.PropTypes.string,error:_.PropTypes.bool,loading:_.PropTypes.bool,onSubmit:_.PropTypes.func,reply:_.PropTypes.bool,serializer:_.PropTypes.func,size:_.PropTypes.oneOf(H.props.size),success:_.PropTypes.bool,warning:_.PropTypes.bool,widths:_.PropTypes.oneOf(H.props.widths)},G._meta=H,G.Field=N.default,G.Button=S.default,G.Checkbox=x.default,G.Dropdown=A.default,G.Group=K.default,G.Input=U.default,G.Radio=R.default,G.Select=W.default,G.TextArea=V.default,t.default=G}).call(t,r(/*! ./~/process/browser.js */35))},/*!***************************************!*\ !*** ./src/collections/Form/index.js ***! \***************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var o=r(/*! ./Form */287),a=n(o);t.default=a.default},/*!**************************************!*\ !*** ./src/collections/Grid/Grid.js ***! \**************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){if(Array.isArray(e)){for(var t=0,r=Array(e.length);t<e.length;t++)r[t]=e[t];return r}return Array.from(e)}function a(e){var t=e.celled,r=e.centered,n=e.children,o=e.className,l=e.columns,i=e.divided,d=e.doubling,f=e.padded,y=e.relaxed,m=e.reversed,h=e.stackable,v=e.stretched,b=e.textAlign,g=e.verticalAlign,P=(0,u.default)("ui",(0,p.useKeyOnly)(r,"centered"),(0,p.useKeyOnly)(d,"doubling"),(0,p.useKeyOnly)(h,"stackable"),(0,p.useKeyOnly)(v,"stretched"),(0,p.useKeyOrValueAndKey)(t,"celled"),(0,p.useKeyOrValueAndKey)(i,"divided"),(0,p.useKeyOrValueAndKey)(f,"padded"),(0,p.useKeyOrValueAndKey)(y,"relaxed"),(0,p.useTextAlignProp)(b),(0,p.useValueAndKey)(m,"reversed"),(0,p.useVerticalAlignProp)(g),(0,p.useWidthProp)(l,"column",!0),"grid",o),T=(0,p.getUnhandledProps)(a,e),O=(0,p.getElementType)(a,e);return c.default.createElement(O,s({},T,{className:P}),n)}Object.defineProperty(t,"__esModule",{value:!0});var s=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},l=r(/*! classnames */3),u=n(l),i=r(/*! react */1),c=n(i),p=r(/*! ../../lib */2),d=r(/*! ./GridColumn */148),f=n(d),y=r(/*! ./GridRow */149),m=n(y);a.Column=f.default,a.Row=m.default,a._meta={name:"Grid",type:p.META.TYPES.COLLECTION,props:{celled:["internally"],columns:[].concat(o(p.SUI.WIDTHS),["equal"]),divided:["vertically"],padded:["horizontally","vertically"],relaxed:["very"],reversed:["computer","computer vertically","mobile","mobile vertically","tablet","tablet vertically"],textAlign:p.SUI.TEXT_ALIGNMENTS,verticalAlign:p.SUI.VERTICAL_ALIGNMENTS}},a.propTypes={as:p.customPropTypes.as,celled:i.PropTypes.oneOfType([i.PropTypes.bool,i.PropTypes.oneOf(a._meta.props.celled)]),centered:i.PropTypes.bool,children:i.PropTypes.node,className:i.PropTypes.string,columns:i.PropTypes.oneOf(a._meta.props.columns),divided:i.PropTypes.oneOfType([i.PropTypes.bool,i.PropTypes.oneOf(a._meta.props.divided)]),doubling:i.PropTypes.bool,padded:i.PropTypes.oneOfType([i.PropTypes.bool,i.PropTypes.oneOf(a._meta.props.padded)]),relaxed:i.PropTypes.oneOfType([i.PropTypes.bool,i.PropTypes.oneOf(a._meta.props.relaxed)]),reversed:i.PropTypes.oneOf(a._meta.props.reversed),stackable:i.PropTypes.bool,stretched:i.PropTypes.bool,textAlign:i.PropTypes.oneOf(a._meta.props.textAlign),verticalAlign:i.PropTypes.oneOf(f.default._meta.props.verticalAlign)},t.default=a},/*!***************************************!*\ !*** ./src/collections/Grid/index.js ***! \***************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var o=r(/*! ./Grid */289),a=n(o);t.default=a.default},/*!**************************************!*\ !*** ./src/collections/Menu/Menu.js ***! \**************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var l=r(/*! lodash/map */10),u=n(l),i=r(/*! lodash/get */34),c=n(i),p=r(/*! lodash/without */7),d=n(p),f=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},y=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),m=r(/*! classnames */3),h=n(m),v=r(/*! react */1),b=n(v),g=r(/*! ../../lib */2),P=r(/*! ./MenuHeader */150),T=n(P),O=r(/*! ./MenuItem */151),_=n(O),E=r(/*! ./MenuMenu */152),j=n(E),w={name:"Menu",type:g.META.TYPES.COLLECTION,props:{attached:["top","bottom"],color:g.SUI.COLORS,floated:["right"],icon:["labeled"],fixed:["left","right","bottom","top"],size:(0,d.default)(g.SUI.SIZES,"medium","big"),tabular:["right"],widths:g.SUI.WIDTHS}},S=function(e){function t(){var e,r,n,s;o(this,t);for(var l=arguments.length,u=Array(l),i=0;i<l;i++)u[i]=arguments[i];return r=n=a(this,(e=t.__proto__||Object.getPrototypeOf(t)).call.apply(e,[this].concat(u))),n.handleItemClick=function(e,t){var r=t.name,o=t.index;n.trySetState({activeIndex:o});var a=n.props,s=a.items,l=a.onItemClick;(0,c.default)(s[o],"onClick")&&s[o].onClick(e,{name:r,index:o}),l&&l(e,{name:r,index:o})},s=r,a(n,s)}return s(t,e),y(t,[{key:"renderItems",value:function(){var e=this,t=this.props.items,r=this.state.activeIndex;return(0,u.default)(t,function(t,n){return(0,g.createShorthand)(_.default,function(e){return{content:e}},t,{active:r===n,childKey:function(e){var t=e.content,r=e.name;return[t,r].join("-")},index:n,onClick:e.handleItemClick})})}},{key:"render",value:function(){var e=this.props,r=e.attached,n=e.borderless,o=e.children,a=e.className,s=e.color,l=e.compact,u=e.fixed,i=e.floated,c=e.fluid,p=e.icon,d=e.inverted,y=e.pagination,m=e.pointing,v=e.secondary,P=e.stackable,T=e.tabular,O=e.text,_=e.vertical,E=e.size,j=e.widths,w=(0,h.default)("ui",s,E,(0,g.useWidthProp)(j,"item"),(0,g.useKeyOrValueAndKey)(r,"attached"),(0,g.useKeyOnly)(n,"borderless"),(0,g.useKeyOnly)(l,"compact"),(0,g.useValueAndKey)(u,"fixed"),(0,g.useKeyOrValueAndKey)(i,"floated"),(0,g.useKeyOnly)(c,"fluid"),(0,g.useKeyOrValueAndKey)(p,"icon"),(0,g.useKeyOnly)(d,"inverted"),(0,g.useKeyOnly)(y,"pagination"),(0,g.useKeyOnly)(m,"pointing"),(0,g.useKeyOnly)(v,"secondary"),(0,g.useKeyOnly)(P,"stackable"),(0,g.useKeyOrValueAndKey)(T,"tabular"),(0,g.useKeyOnly)(O,"text"),(0,g.useKeyOnly)(_,"vertical"),a,"menu"),S=(0,g.getUnhandledProps)(t,this.props),M=(0,g.getElementType)(t,this.props);return b.default.createElement(M,f({},S,{className:w}),o||this.renderItems())}}]),t}(g.AutoControlledComponent);S.propTypes={as:g.customPropTypes.as,activeIndex:v.PropTypes.number,attached:v.PropTypes.oneOfType([v.PropTypes.bool,v.PropTypes.oneOf(w.props.attached)]),borderless:v.PropTypes.bool,children:v.PropTypes.node,className:v.PropTypes.string,color:v.PropTypes.oneOf(w.props.color),compact:v.PropTypes.bool,defaultActiveIndex:v.PropTypes.number,fixed:v.PropTypes.oneOf(w.props.fixed),floated:v.PropTypes.oneOfType([v.PropTypes.bool,v.PropTypes.oneOf(w.props.floated)]),fluid:v.PropTypes.bool,icon:v.PropTypes.oneOfType([v.PropTypes.bool,v.PropTypes.oneOf(w.props.icon)]),inverted:v.PropTypes.bool,items:g.customPropTypes.collectionShorthand,onItemClick:g.customPropTypes.every([g.customPropTypes.disallow(["children"]),v.PropTypes.func]),pagination:v.PropTypes.bool,pointing:v.PropTypes.bool,secondary:v.PropTypes.bool,stackable:v.PropTypes.bool,tabular:v.PropTypes.oneOfType([v.PropTypes.bool,v.PropTypes.oneOf(w.props.tabular)]),text:v.PropTypes.bool,vertical:v.PropTypes.bool,size:v.PropTypes.oneOf(w.props.size),widths:v.PropTypes.oneOf(w.props.widths)},S._meta=w,S.autoControlledProps=["activeIndex"],S.Header=T.default,S.Item=_.default,S.Menu=j.default,t.default=S},/*!***************************************!*\ !*** ./src/collections/Menu/index.js ***! \***************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var o=r(/*! ./Menu */291),a=n(o);t.default=a.default},/*!********************************************!*\ !*** ./src/collections/Message/Message.js ***! \********************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.children,r=e.className,n=e.content,a=e.header,s=e.icon,u=e.list,c=e.onDismiss,f=e.hidden,m=e.visible,v=e.floating,g=e.compact,T=e.attached,O=e.warning,_=e.info,E=e.positive,j=e.success,w=e.negative,S=e.error,M=e.color,x=e.size,k=(0,p.default)("ui",x,M,(0,d.useKeyOnly)(s,"icon"),(0,d.useKeyOnly)(f,"hidden"),(0,d.useKeyOnly)(m,"visible"),(0,d.useKeyOnly)(v,"floating"),(0,d.useKeyOnly)(g,"compact"),(0,d.useKeyOrValueAndKey)(T,"attached"),(0,d.useKeyOnly)(O,"warning"),(0,d.useKeyOnly)(_,"info"),(0,d.useKeyOnly)(E,"positive"),(0,d.useKeyOnly)(j,"success"),(0,d.useKeyOnly)(w,"negative"),(0,d.useKeyOnly)(S,"error"),"message",r),A=c&&i.default.createElement(y.default,{name:"close",onClick:c}),C=(0,d.getUnhandledProps)(o,e),N=(0,d.getElementType)(o,e);return t?i.default.createElement(N,l({},C,{className:k}),A,t):i.default.createElement(N,l({},C,{className:k}),A,y.default.create(s),(a||n||u)&&i.default.createElement(h.default,null,(0,d.createShorthand)(b.default,function(e){return{children:e}},a),(0,d.createShorthand)(P.default,function(e){return{items:e}},u),(0,d.createShorthand)("p",function(e){return{children:e}},n)))}Object.defineProperty(t,"__esModule",{value:!0});var a=r(/*! lodash/without */7),s=n(a),l=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},u=r(/*! react */1),i=n(u),c=r(/*! classnames */3),p=n(c),d=r(/*! ../../lib */2),f=r(/*! ../../elements/Icon */8),y=n(f),m=r(/*! ./MessageContent */153),h=n(m),v=r(/*! ./MessageHeader */154),b=n(v),g=r(/*! ./MessageList */155),P=n(g),T=r(/*! ./MessageItem */83),O=n(T);o._meta={name:"Message",type:d.META.TYPES.COLLECTION,props:{attached:["bottom"],color:d.SUI.COLORS,size:(0,s.default)(d.SUI.SIZES,"medium")}},o.propTypes={as:d.customPropTypes.as,children:u.PropTypes.node,className:u.PropTypes.string,content:d.customPropTypes.contentShorthand,header:d.customPropTypes.itemShorthand,icon:u.PropTypes.oneOfType([u.PropTypes.bool,d.customPropTypes.itemShorthand]),list:d.customPropTypes.collectionShorthand,onDismiss:u.PropTypes.func,hidden:u.PropTypes.bool,visible:u.PropTypes.bool,floating:u.PropTypes.bool,compact:u.PropTypes.bool,attached:u.PropTypes.oneOfType([u.PropTypes.bool,u.PropTypes.oneOf(o._meta.props.attached)]),warning:u.PropTypes.bool,info:u.PropTypes.bool,positive:u.PropTypes.bool,success:u.PropTypes.bool,negative:u.PropTypes.bool,error:u.PropTypes.bool,color:u.PropTypes.oneOf(o._meta.props.color),size:u.PropTypes.oneOf(o._meta.props.size)},o.Content=h.default,o.Header=b.default,o.List=P.default,o.Item=O.default,t.default=o},/*!******************************************!*\ !*** ./src/collections/Message/index.js ***! \******************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var o=r(/*! ./Message */293),a=n(o);t.default=a.default},/*!****************************************!*\ !*** ./src/collections/Table/Table.js ***! \****************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.basic,r=e.attached,n=e.renderBodyRow,a=e.celled,s=e.children,l=e.className,c=e.collapsing,d=e.color,m=e.columns,v=e.compact,b=e.definition,g=e.fixed,T=e.footerRow,_=e.headerRow,E=e.inverted,j=e.padded,S=e.selectable,M=e.singleLine,x=e.size,k=e.stackable,A=e.striped,C=e.structured,N=e.tableData,I=e.unstackable,K=(0,p.default)("ui",d,x,(0,y.useKeyOrValueAndKey)(r,"attached"),(0,y.useKeyOrValueAndKey)(t,"basic"),(0,y.useKeyOnly)(a,"celled"),(0,y.useKeyOnly)(c,"collapsing"),(0,y.useKeyOrValueAndKey)(v,"compact"),(0,y.useKeyOnly)(b,"definition"),(0,y.useKeyOnly)(g,"fixed"),(0,y.useKeyOnly)(E,"inverted"),(0,y.useKeyOrValueAndKey)(j,"padded"),(0,y.useKeyOnly)(S,"selectable"),(0,y.useKeyOnly)(M,"single line"),(0,y.useKeyOnly)(k,"stackable"),(0,y.useKeyOnly)(A,"striped"),(0,y.useKeyOnly)(C,"structured"),(0,y.useKeyOnly)(I,"unstackable"),(0,y.useWidthProp)(m,"column"),l,"table"),L=(0,y.getUnhandledProps)(o,e),U=(0,y.getElementType)(o,e);return s?f.default.createElement(U,i({},L,{className:K}),s):f.default.createElement(U,i({},L,{className:K}),_&&f.default.createElement(O.default,null,w.default.create(_,{cellAs:"th"})),f.default.createElement(h.default,null,n&&(0,u.default)(N,function(e,t){return w.default.create(n(e,t))})),T&&f.default.createElement(P.default,null,w.default.create(T)))}Object.defineProperty(t,"__esModule",{value:!0});var a=r(/*! lodash/without */7),s=n(a),l=r(/*! lodash/map */10),u=n(l),i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},c=r(/*! classnames */3),p=n(c),d=r(/*! react */1),f=n(d),y=r(/*! ../../lib */2),m=r(/*! ./TableBody */156),h=n(m),v=r(/*! ./TableCell */46),b=n(v),g=r(/*! ./TableFooter */157),P=n(g),T=r(/*! ./TableHeader */84),O=n(T),_=r(/*! ./TableHeaderCell */158),E=n(_),j=r(/*! ./TableRow */159),w=n(j);o._meta={name:"Table",type:y.META.TYPES.COLLECTION,props:{attached:["top","bottom"],basic:["very"],color:y.SUI.COLORS,columns:y.SUI.WIDTHS,compact:["very"],padded:["very"],size:(0,s.default)(y.SUI.SIZES,"mini","tiny","medium","big","huge","massive")}},o.defaultProps={as:"table"},o.propTypes={as:y.customPropTypes.as,attached:d.PropTypes.oneOfType([d.PropTypes.oneOf(o._meta.props.attached),d.PropTypes.bool]),basic:d.PropTypes.oneOfType([d.PropTypes.bool,d.PropTypes.oneOf(o._meta.props.basic)]),celled:d.PropTypes.bool,children:d.PropTypes.node,className:d.PropTypes.string,collapsing:d.PropTypes.bool,color:d.PropTypes.oneOf(o._meta.props.color),columns:d.PropTypes.oneOf(o._meta.props.columns),compact:d.PropTypes.oneOfType([d.PropTypes.bool,d.PropTypes.oneOf(o._meta.props.compact)]),definition:d.PropTypes.bool,fixed:d.PropTypes.bool,footerRow:y.customPropTypes.itemShorthand,headerRow:y.customPropTypes.itemShorthand,inverted:d.PropTypes.bool,padded:d.PropTypes.oneOfType([d.PropTypes.bool,d.PropTypes.oneOf(o._meta.props.padded)]),renderBodyRow:y.customPropTypes.every([y.customPropTypes.disallow(["children"]),y.customPropTypes.demand(["tableData"]),d.PropTypes.func]),selectable:d.PropTypes.bool,singleLine:d.PropTypes.bool,size:d.PropTypes.oneOf(o._meta.props.size),stackable:d.PropTypes.bool,striped:d.PropTypes.bool,structured:d.PropTypes.bool,tableData:y.customPropTypes.every([y.customPropTypes.disallow(["children"]),y.customPropTypes.demand(["renderBodyRow"]),d.PropTypes.array]),unstackable:d.PropTypes.bool},o.Body=h.default,o.Cell=b.default,o.Footer=P.default,o.Header=O.default,o.HeaderCell=E.default,o.Row=w.default,t.default=o},/*!****************************************!*\ !*** ./src/collections/Table/index.js ***! \****************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var o=r(/*! ./Table */295),a=n(o);t.default=a.default},/*!*********************************************!*\ !*** ./src/elements/Container/Container.js ***! \*********************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.text,r=e.textAlign,n=e.fluid,s=e.children,u=e.className,p=(0,l.default)("ui",(0,c.useKeyOnly)(t,"text"),(0,c.useKeyOnly)(n,"fluid"),(0,c.useTextAlignProp)(r),"container",u),d=(0,c.getUnhandledProps)(o,e),f=(0,c.getElementType)(o,e);return i.default.createElement(f,a({},d,{className:p}),s)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! classnames */3),l=n(s),u=r(/*! react */1),i=n(u),c=r(/*! ../../lib */2);o._meta={name:"Container",type:c.META.TYPES.ELEMENT,props:{textAlign:c.SUI.TEXT_ALIGNMENTS}},o.propTypes={as:c.customPropTypes.as,children:u.PropTypes.node,className:u.PropTypes.string,text:u.PropTypes.bool,fluid:u.PropTypes.bool,textAlign:u.PropTypes.oneOf(o._meta.props.textAlign)},t.default=o},/*!*****************************************!*\ !*** ./src/elements/Container/index.js ***! \*****************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var o=r(/*! ./Container */297),a=n(o);t.default=a.default},/*!*****************************************!*\ !*** ./src/elements/Divider/Divider.js ***! \*****************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.horizontal,r=e.vertical,n=e.inverted,s=e.fitted,u=e.hidden,p=e.section,d=e.clearing,f=e.children,y=e.className,m=(0,l.default)("ui",(0,c.useKeyOnly)(t,"horizontal"),(0,c.useKeyOnly)(r,"vertical"),(0,c.useKeyOnly)(n,"inverted"),(0,c.useKeyOnly)(s,"fitted"),(0,c.useKeyOnly)(u,"hidden"),(0,c.useKeyOnly)(p,"section"),(0,c.useKeyOnly)(d,"clearing"),"divider",y),h=(0,c.getUnhandledProps)(o,e),v=(0,c.getElementType)(o,e);return i.default.createElement(v,a({},h,{className:m}),f)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! classnames */3),l=n(s),u=r(/*! react */1),i=n(u),c=r(/*! ../../lib */2);o._meta={name:"Divider",type:c.META.TYPES.ELEMENT},o.propTypes={as:c.customPropTypes.as,children:u.PropTypes.node,className:u.PropTypes.string,horizontal:u.PropTypes.bool,vertical:u.PropTypes.bool,inverted:u.PropTypes.bool,fitted:u.PropTypes.bool,hidden:u.PropTypes.bool,section:u.PropTypes.bool,clearing:u.PropTypes.bool},t.default=o},/*!***************************************!*\ !*** ./src/elements/Divider/index.js ***! \***************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var o=r(/*! ./Divider */299),a=n(o);t.default=a.default},/*!***********************************!*\ !*** ./src/elements/Flag/Flag.js ***! \***********************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.className,r=e.name,n=(0,l.default)(r,t,"flag"),s=(0,c.getUnhandledProps)(o,e),u=(0,c.getElementType)(o,e);return i.default.createElement(u,a({},s,{className:n}))}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! classnames */3),l=n(s),u=r(/*! react */1),i=n(u),c=r(/*! ../../lib */2),p=["ad","andorra","ae","united arab emirates","uae","af","afghanistan","ag","antigua","ai","anguilla","al","albania","am","armenia","an","netherlands antilles","ao","angola","ar","argentina","as","american samoa","at","austria","au","australia","aw","aruba","ax","aland islands","az","azerbaijan","ba","bosnia","bb","barbados","bd","bangladesh","be","belgium","bf","burkina faso","bg","bulgaria","bh","bahrain","bi","burundi","bj","benin","bm","bermuda","bn","brunei","bo","bolivia","br","brazil","bs","bahamas","bt","bhutan","bv","bouvet island","bw","botswana","by","belarus","bz","belize","ca","canada","cc","cocos islands","cd","congo","cf","central african republic","cg","congo brazzaville","ch","switzerland","ci","cote divoire","ck","cook islands","cl","chile","cm","cameroon","cn","china","co","colombia","cr","costa rica","cs","cu","cuba","cv","cape verde","cx","christmas island","cy","cyprus","cz","czech republic","de","germany","dj","djibouti","dk","denmark","dm","dominica","do","dominican republic","dz","algeria","ec","ecuador","ee","estonia","eg","egypt","eh","western sahara","er","eritrea","es","spain","et","ethiopia","eu","european union","fi","finland","fj","fiji","fk","falkland islands","fm","micronesia","fo","faroe islands","fr","france","ga","gabon","gb","united kingdom","gd","grenada","ge","georgia","gf","french guiana","gh","ghana","gi","gibraltar","gl","greenland","gm","gambia","gn","guinea","gp","guadeloupe","gq","equatorial guinea","gr","greece","gs","sandwich islands","gt","guatemala","gu","guam","gw","guinea-bissau","gy","guyana","hk","hong kong","hm","heard island","hn","honduras","hr","croatia","ht","haiti","hu","hungary","id","indonesia","ie","ireland","il","israel","in","india","io","indian ocean territory","iq","iraq","ir","iran","is","iceland","it","italy","jm","jamaica","jo","jordan","jp","japan","ke","kenya","kg","kyrgyzstan","kh","cambodia","ki","kiribati","km","comoros","kn","saint kitts and nevis","kp","north korea","kr","south korea","kw","kuwait","ky","cayman islands","kz","kazakhstan","la","laos","lb","lebanon","lc","saint lucia","li","liechtenstein","lk","sri lanka","lr","liberia","ls","lesotho","lt","lithuania","lu","luxembourg","lv","latvia","ly","libya","ma","morocco","mc","monaco","md","moldova","me","montenegro","mg","madagascar","mh","marshall islands","mk","macedonia","ml","mali","mm","myanmar","burma","mn","mongolia","mo","macau","mp","northern mariana islands","mq","martinique","mr","mauritania","ms","montserrat","mt","malta","mu","mauritius","mv","maldives","mw","malawi","mx","mexico","my","malaysia","mz","mozambique","na","namibia","nc","new caledonia","ne","niger","nf","norfolk island","ng","nigeria","ni","nicaragua","nl","netherlands","no","norway","np","nepal","nr","nauru","nu","niue","nz","new zealand","om","oman","pa","panama","pe","peru","pf","french polynesia","pg","new guinea","ph","philippines","pk","pakistan","pl","poland","pm","saint pierre","pn","pitcairn islands","pr","puerto rico","ps","palestine","pt","portugal","pw","palau","py","paraguay","qa","qatar","re","reunion","ro","romania","rs","serbia","ru","russia","rw","rwanda","sa","saudi arabia","sb","solomon islands","sc","seychelles","gb sct","scotland","sd","sudan","se","sweden","sg","singapore","sh","saint helena","si","slovenia","sj","svalbard","jan mayen","sk","slovakia","sl","sierra leone","sm","san marino","sn","senegal","so","somalia","sr","suriname","st","sao tome","sv","el salvador","sy","syria","sz","swaziland","tc","caicos islands","td","chad","tf","french territories","tg","togo","th","thailand","tj","tajikistan","tk","tokelau","tl","timorleste","tm","turkmenistan","tn","tunisia","to","tonga","tr","turkey","tt","trinidad","tv","tuvalu","tw","taiwan","tz","tanzania","ua","ukraine","ug","uganda","um","us minor islands","us","america","united states","uy","uruguay","uz","uzbekistan","va","vatican city","vc","saint vincent","ve","venezuela","vg","british virgin islands","vi","us virgin islands","vn","vietnam","vu","vanuatu","gb wls","wales","wf","wallis and futuna","ws","samoa","ye","yemen","yt","mayotte","za","south africa","zm","zambia","zw","zimbabwe"];o._meta={name:"Flag",type:c.META.TYPES.ELEMENT,props:{name:p}},o.propTypes={as:c.customPropTypes.as,className:u.PropTypes.string,name:c.customPropTypes.suggest(o._meta.props.name)},o.defaultProps={as:"i"},o.create=(0,c.createShorthandFactory)(o,function(e){return{name:e}}),t.default=o},/*!***************************************!*\ !*** ./src/elements/Header/Header.js ***! \***************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.color,r=e.content,n=e.dividing,a=e.block,s=e.attached,u=e.floated,c=e.inverted,f=e.disabled,m=e.sub,v=e.size,g=e.textAlign,T=e.icon,O=e.image,_=e.children,E=e.className,j=e.subheader,w=(0,i.default)("ui",v,t,(0,d.useKeyOrValueAndKey)(s,"attached"),(0,d.useKeyOnly)(a,"block"),(0,d.useKeyOnly)(f,"disabled"),(0,d.useKeyOnly)(n,"dividing"),(0,d.useValueAndKey)(u,"floated"),(0,d.useKeyOnly)(T===!0,"icon"),(0,d.useKeyOnly)(O===!0,"image"),(0,d.useKeyOnly)(c,"inverted"),(0,d.useKeyOnly)(m,"sub"),(0,d.useTextAlignProp)(g),E,"header"),S=(0,d.getUnhandledProps)(o,e),M=(0,d.getElementType)(o,e);if(_)return p.default.createElement(M,l({},S,{className:w}),_);var x=y.default.create(T),k=h.default.create(O),A=b.default.create(j,{className:"sub header"});return x||k?p.default.createElement(M,l({},S,{className:w}),x||k,(r||A)&&p.default.createElement(P.default,null,r,A)):p.default.createElement(M,l({},S,{className:w}),r,A)}Object.defineProperty(t,"__esModule",{value:!0});var a=r(/*! lodash/without */7),s=n(a),l=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},u=r(/*! classnames */3),i=n(u),c=r(/*! react */1),p=n(c),d=r(/*! ../../lib */2),f=r(/*! ../../elements/Icon */8),y=n(f),m=r(/*! ../../elements/Image */30),h=n(m),v=r(/*! ./HeaderSubheader */166),b=n(v),g=r(/*! ./HeaderContent */165),P=n(g);o._meta={name:"Header",type:d.META.TYPES.ELEMENT,props:{attached:["top","bottom"],color:d.SUI.COLORS,size:(0,s.default)(d.SUI.SIZES,"big","massive"),floated:d.SUI.FLOATS,textAlign:d.SUI.TEXT_ALIGNMENTS}},o.propTypes={as:d.customPropTypes.as,className:c.PropTypes.string,children:c.PropTypes.node,content:d.customPropTypes.contentShorthand,icon:d.customPropTypes.every([d.customPropTypes.disallow(["image"]),c.PropTypes.oneOfType([c.PropTypes.bool,d.customPropTypes.itemShorthand])]),image:d.customPropTypes.every([d.customPropTypes.disallow(["icon"]),c.PropTypes.oneOfType([c.PropTypes.bool,d.customPropTypes.itemShorthand])]),color:c.PropTypes.oneOf(o._meta.props.color),dividing:c.PropTypes.bool,block:c.PropTypes.bool,attached:c.PropTypes.oneOfType([c.PropTypes.oneOf(o._meta.props.attached),c.PropTypes.bool]),floated:c.PropTypes.oneOf(o._meta.props.floated),inverted:c.PropTypes.bool,disabled:c.PropTypes.bool,sub:c.PropTypes.bool,size:c.PropTypes.oneOf(o._meta.props.size),subheader:d.customPropTypes.itemShorthand,textAlign:c.PropTypes.oneOf(o._meta.props.textAlign)},o.Content=P.default,o.Subheader=b.default,t.default=o},/*!**************************************!*\ !*** ./src/elements/Header/index.js ***! \**************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var o=r(/*! ./Header */302),a=n(o);t.default=a.default},/*!*************************************!*\ !*** ./src/elements/Input/Input.js ***! \*************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0}),t.htmlInputPropNames=void 0;var l=r(/*! lodash/includes */75),u=n(l),i=r(/*! lodash/pick */80),c=n(i),p=r(/*! lodash/omit */44),d=n(p),f=r(/*! lodash/get */34),y=n(f),m=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},h=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),v=r(/*! react */1),b=n(v),g=r(/*! classnames */3),P=n(g),T=r(/*! ../../lib */2),O=r(/*! ../../elements/Button */85),_=n(O),E=r(/*! ../../elements/Icon */8),j=n(E),w=r(/*! ../../elements/Label */48),S=n(w),M=t.htmlInputPropNames=["selected","defaultValue","defaultChecked","autoComplete","autoFocus","checked","form","max","maxLength","min","name","pattern","placeholder","readOnly","required","step","type","value","onKeyDown","onKeyPress","onKeyUp","onFocus","onBlur","onChange","onInput","onClick","onContextMenu","onDrag","onDragEnd","onDragEnter","onDragExit","onDragLeave","onDragOver","onDragStart","onDrop","onMouseDown","onMouseEnter","onMouseLeave","onMouseMove","onMouseOut","onMouseOver","onMouseUp","onSelect","onTouchCancel","onTouchEnd","onTouchMove","onTouchStart"],x={name:"Input",type:T.META.TYPES.ELEMENT,props:{actionPosition:["left"],iconPosition:["left"],labelPosition:["left","right","left corner","right corner"],size:T.SUI.SIZES}},k=function(e){function t(){var e,r,n,s;o(this,t);for(var l=arguments.length,u=Array(l),i=0;i<l;i++)u[i]=arguments[i];return r=n=a(this,(e=t.__proto__||Object.getPrototypeOf(t)).call.apply(e,[this].concat(u))),n.handleChange=function(e){var t=n.props.onChange;t&&t(e,m({},n.props,{value:(0,y.default)(e,"target.value")}))},s=r,a(n,s)}return s(t,e),h(t,[{key:"render",value:function(){var e=this.props,r=e.action,n=e.actionPosition,o=e.children,a=e.className,s=e.disabled,l=e.error,i=e.focus,p=e.fluid,f=e.icon,y=e.iconPosition,h=e.inverted,g=e.label,O=e.labelPosition,E=e.loading,w=e.onChange,x=e.size,k=e.type,A=e.input,C=e.transparent,N=(0,P.default)("ui",x,(0,T.useValueAndKey)(n,"action")||(0,T.useKeyOnly)(r,"action"),(0,T.useKeyOnly)(s,"disabled"),(0,T.useKeyOnly)(l,"error"),(0,T.useKeyOnly)(i,"focus"),(0,T.useKeyOnly)(p,"fluid"),(0,T.useKeyOnly)(h,"inverted"),(0,T.useValueAndKey)(O,"labeled")||(0,T.useKeyOnly)(g,"labeled"),(0,T.useKeyOnly)(E,"loading"),(0,T.useKeyOnly)(C,"transparent"),(0,T.useValueAndKey)(y,"icon")||(0,T.useKeyOnly)(f,"icon"),a,"input"),I=(0,T.getUnhandledProps)(t,this.props),K=(0,d.default)(I,M),L=(0,c.default)(this.props,M);w&&(L.onChange=this.handleChange);var U=(0,T.getElementType)(t,this.props);if(o){var D=v.Children.map(o,function(e){return"input"!==e.type?e:(0,v.cloneElement)(e,m({},L,e.props))});return b.default.createElement(U,m({},K,{className:N}),D)}var R=_.default.create(r,function(e){return{className:(0,P.default)(!(0,u.default)(e.className,"button")&&"button")}}),z=j.default.create(f),W=S.default.create(g,function(e){return{className:(0,P.default)(!(0,u.default)(e.className,"label")&&"label",(0,u.default)(O,"corner")&&O)}});return b.default.createElement(U,m({},K,{className:N}),"left"===n&&R,"left"===y&&z,"right"!==O&&W,(0,T.createHTMLInput)(A||k,L),"left"!==n&&R,"left"!==y&&z,"right"===O&&W)}}]),t}(v.Component);k.propTypes={as:T.customPropTypes.as,action:v.PropTypes.oneOfType([v.PropTypes.bool,T.customPropTypes.itemShorthand]),actionPosition:v.PropTypes.oneOf(x.props.actionPosition),children:v.PropTypes.node,className:v.PropTypes.string,disabled:v.PropTypes.bool,error:v.PropTypes.bool,focus:v.PropTypes.bool,fluid:v.PropTypes.bool,icon:v.PropTypes.oneOfType([v.PropTypes.bool,T.customPropTypes.itemShorthand]),iconPosition:v.PropTypes.oneOf(x.props.iconPosition),inverted:v.PropTypes.bool,input:T.customPropTypes.itemShorthand,label:T.customPropTypes.itemShorthand,labelPosition:v.PropTypes.oneOf(x.props.labelPosition),loading:v.PropTypes.bool,onChange:v.PropTypes.func,size:v.PropTypes.oneOf(x.props.size),transparent:v.PropTypes.bool,type:v.PropTypes.string},k.defaultProps={type:"text"},k._meta=x,t.default=k},/*!***********************************!*\ !*** ./src/elements/List/List.js ***! \***********************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.animated,r=e.bulleted,n=e.celled,a=e.children,u=e.className,c=e.divided,f=e.floated,y=e.horizontal,m=e.inverted,h=e.items,v=e.link,b=e.ordered,g=e.relaxed,P=e.size,T=e.selection,_=e.verticalAlign,E=(0,i.default)("ui",P,(0,d.useKeyOnly)(t,"animated"),(0,d.useKeyOnly)(r,"bulleted"),(0,d.useKeyOnly)(n,"celled"),(0,d.useKeyOnly)(c,"divided"),(0,d.useKeyOnly)(y,"horizontal"),(0,d.useKeyOnly)(m,"inverted"),(0,d.useKeyOnly)(v,"link"),(0,d.useKeyOnly)(b,"ordered"),(0,d.useKeyOnly)(T,"selection"),(0,d.useKeyOrValueAndKey)(g,"relaxed"),(0,d.useValueAndKey)(f,"floated"),(0,d.useVerticalAlignProp)(_),"list",u),j=(0,d.getUnhandledProps)(o,e),w=(0,d.getElementType)(o,e);return a?p.default.createElement(w,l({},j,{className:E}),a):p.default.createElement(w,l({},j,{className:E}),(0,s.default)(h,function(e){return O.default.create(e)}))}Object.defineProperty(t,"__esModule",{value:!0});var a=r(/*! lodash/map */10),s=n(a),l=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},u=r(/*! classnames */3),i=n(u),c=r(/*! react */1),p=n(c),d=r(/*! ../../lib */2),f=r(/*! ./ListContent */88),y=n(f),m=r(/*! ./ListDescription */49),h=n(m),v=r(/*! ./ListHeader */50),b=n(v),g=r(/*! ./ListIcon */89),P=n(g),T=r(/*! ./ListItem */172),O=n(T),_=r(/*! ./ListList */173),E=n(_);o._meta={name:"List",type:d.META.TYPES.ELEMENT,props:{floated:d.SUI.FLOATS,relaxed:["very"],size:d.SUI.SIZES,verticalAlign:d.SUI.VERTICAL_ALIGNMENTS}},o.propTypes={as:d.customPropTypes.as,animated:c.PropTypes.bool,bulleted:c.PropTypes.bool,celled:c.PropTypes.bool,children:c.PropTypes.node,className:c.PropTypes.string,divided:c.PropTypes.bool,floated:c.PropTypes.oneOf(o._meta.props.floated),horizontal:c.PropTypes.bool,inverted:c.PropTypes.bool,items:d.customPropTypes.collectionShorthand,link:c.PropTypes.bool,ordered:c.PropTypes.bool,relaxed:c.PropTypes.oneOfType([c.PropTypes.bool,c.PropTypes.oneOf(o._meta.props.relaxed)]),selection:c.PropTypes.bool,size:c.PropTypes.oneOf(o._meta.props.size),verticalAlign:c.PropTypes.oneOf(o._meta.props.verticalAlign)},o.Content=y.default,o.Description=h.default,o.Header=b.default,o.Icon=P.default,o.Item=O.default,o.List=E.default,t.default=o},/*!************************************!*\ !*** ./src/elements/List/index.js ***! \************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var o=r(/*! ./List */305),a=n(o);t.default=a.default},/*!***************************************!*\ !*** ./src/elements/Loader/Loader.js ***! \***************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.active,r=e.children,n=e.className,s=e.content,u=e.disabled,p=e.indeterminate,d=e.inline,f=e.inverted,y=e.size,m=(0,l.default)("ui",y,(0,c.useKeyOnly)(t,"active"),(0,c.useKeyOnly)(u,"disabled"),(0,c.useKeyOnly)(p,"indeterminate"),(0,c.useKeyOnly)(f,"inverted"),(0,c.useKeyOnly)(r||s,"text"),(0,c.useKeyOrValueAndKey)(d,"inline"),"loader",n),h=(0,c.getUnhandledProps)(o,e),v=(0,c.getElementType)(o,e);return i.default.createElement(v,a({},h,{className:m}),r||s)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! classnames */3),l=n(s),u=r(/*! react */1),i=n(u),c=r(/*! ../../lib */2);o._meta={name:"Loader",type:c.META.TYPES.ELEMENT,props:{inline:["centered"],size:c.SUI.SIZES}},o.propTypes={as:c.customPropTypes.as,active:u.PropTypes.bool,children:u.PropTypes.node,className:u.PropTypes.string,content:c.customPropTypes.contentShorthand,disabled:u.PropTypes.bool,indeterminate:u.PropTypes.bool,inline:u.PropTypes.oneOfType([u.PropTypes.bool,u.PropTypes.oneOf(o._meta.props.inline)]),inverted:u.PropTypes.bool,size:u.PropTypes.oneOf(o._meta.props.size)},t.default=o},/*!**************************************!*\ !*** ./src/elements/Loader/index.js ***! \**************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var o=r(/*! ./Loader */307),a=n(o);t.default=a.default},/*!***********************************!*\ !*** ./src/elements/Rail/Rail.js ***! \***********************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.attached,r=e.children,n=e.className,a=e.close,s=e.dividing,u=e.internal,c=e.position,f=e.size,y=(0,i.default)("ui",c,f,(0,d.useKeyOnly)(t,"attached"),(0,d.useKeyOnly)(s,"dividing"),(0,d.useKeyOnly)(u,"internal"),(0,d.useKeyOrValueAndKey)(a,"close"),"rail",n),m=(0,d.getUnhandledProps)(o,e),h=(0,d.getElementType)(o,e);return p.default.createElement(h,l({},m,{className:y}),r)}Object.defineProperty(t,"__esModule",{value:!0});var a=r(/*! lodash/without */7),s=n(a),l=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},u=r(/*! classnames */3),i=n(u),c=r(/*! react */1),p=n(c),d=r(/*! ../../lib */2);o._meta={name:"Rail",type:d.META.TYPES.ELEMENT,props:{close:["very"],position:d.SUI.FLOATS,size:(0,s.default)(d.SUI.SIZES,"medium")}},o.propTypes={as:d.customPropTypes.as,attached:c.PropTypes.bool,children:c.PropTypes.node,className:c.PropTypes.string,close:c.PropTypes.oneOfType([c.PropTypes.bool,c.PropTypes.oneOf(o._meta.props.close)]),dividing:c.PropTypes.bool,internal:c.PropTypes.bool,position:c.PropTypes.oneOf(o._meta.props.position).isRequired,size:c.PropTypes.oneOf(o._meta.props.size)},t.default=o},/*!************************************!*\ !*** ./src/elements/Rail/index.js ***! \************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var o=r(/*! ./Rail */309),a=n(o);t.default=a.default},/*!***************************************!*\ !*** ./src/elements/Reveal/Reveal.js ***! \***************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.active,r=e.animated,n=e.children,s=e.className,u=e.disabled,p=e.instant,d=(0,l.default)("ui",r,(0,c.useKeyOnly)(t,"active"),(0,c.useKeyOnly)(u,"disabled"),(0,c.useKeyOnly)(p,"instant"),"reveal",s),f=(0,c.getUnhandledProps)(o,e),y=(0,c.getElementType)(o,e);return i.default.createElement(y,a({},f,{className:d}),n)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! classnames */3),l=n(s),u=r(/*! react */1),i=n(u),c=r(/*! ../../lib */2),p=r(/*! ./RevealContent */174),d=n(p);o._meta={name:"Reveal",type:c.META.TYPES.ELEMENT,props:{animated:["fade","small fade","move","move right","move up","move down","rotate","rotate left"]}},o.propTypes={as:c.customPropTypes.as,active:u.PropTypes.bool,children:u.PropTypes.node,className:u.PropTypes.string,disabled:u.PropTypes.bool,animated:u.PropTypes.oneOf(o._meta.props.animated),instant:u.PropTypes.bool},o.Content=d.default,t.default=o},/*!**************************************!*\ !*** ./src/elements/Reveal/index.js ***! \**************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var o=r(/*! ./Reveal */311),a=n(o);t.default=a.default},/*!*****************************************!*\ !*** ./src/elements/Segment/Segment.js ***! \*****************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.attached,r=e.basic,n=e.children,a=e.circular,s=e.className,u=e.clearing,c=e.color,f=e.compact,y=e.disabled,m=e.floated,h=e.inverted,v=e.loading,b=e.padded,g=e.piled,P=e.raised,T=e.secondary,O=e.size,_=e.stacked,E=e.tertiary,j=e.textAlign,w=e.vertical,S=(0,i.default)("ui",c,O,(0,d.useKeyOrValueAndKey)(t,"attached"),(0,d.useKeyOnly)(r,"basic"),(0,d.useKeyOnly)(a,"circular"),(0,d.useKeyOnly)(u,"clearing"),(0,d.useKeyOnly)(f,"compact"),(0,d.useKeyOnly)(y,"disabled"),(0,d.useValueAndKey)(m,"floated"),(0,d.useKeyOnly)(h,"inverted"),(0,d.useKeyOnly)(v,"loading"),(0,d.useKeyOrValueAndKey)(b,"padded"),(0,d.useKeyOnly)(g,"piled"),(0,d.useKeyOnly)(P,"raised"),(0,d.useKeyOnly)(T,"secondary"),(0,d.useKeyOnly)(_,"stacked"),(0,d.useKeyOnly)(E,"tertiary"),(0,d.useTextAlignProp)(j),(0,d.useKeyOnly)(w,"vertical"),s,"segment"),M=(0,d.getUnhandledProps)(o,e),x=(0,d.getElementType)(o,e);return p.default.createElement(x,l({},M,{className:S}),n)}Object.defineProperty(t,"__esModule",{value:!0});var a=r(/*! lodash/without */7),s=n(a),l=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},u=r(/*! classnames */3),i=n(u),c=r(/*! react */1),p=n(c),d=r(/*! ../../lib */2),f=r(/*! ./SegmentGroup */175),y=n(f);o.Group=y.default,o._meta={name:"Segment",type:d.META.TYPES.ELEMENT,props:{attached:["top","bottom"],color:d.SUI.COLORS,floated:d.SUI.FLOATS,padded:["very"],size:(0,s.default)(d.SUI.SIZES,"medium"),textAlign:d.SUI.TEXT_ALIGNMENTS}},o.propTypes={as:d.customPropTypes.as,attached:c.PropTypes.oneOfType([c.PropTypes.oneOf(o._meta.props.attached),c.PropTypes.bool]),basic:c.PropTypes.bool,children:c.PropTypes.node,circular:c.PropTypes.bool,className:c.PropTypes.string,clearing:c.PropTypes.bool,color:c.PropTypes.oneOf(o._meta.props.color),compact:c.PropTypes.bool,disabled:c.PropTypes.bool,floated:c.PropTypes.oneOf(o._meta.props.floated),inverted:c.PropTypes.bool,loading:c.PropTypes.bool,padded:c.PropTypes.oneOfType([c.PropTypes.bool,c.PropTypes.oneOf(o._meta.props.padded)]),piled:c.PropTypes.bool,raised:c.PropTypes.bool,secondary:c.PropTypes.bool,size:c.PropTypes.oneOf(o._meta.props.size),stacked:c.PropTypes.bool,tertiary:c.PropTypes.bool,textAlign:c.PropTypes.oneOf(o._meta.props.textAlign),vertical:c.PropTypes.bool},t.default=o},/*!***************************************!*\ !*** ./src/elements/Segment/index.js ***! \***************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var o=r(/*! ./Segment */313),a=n(o);t.default=a.default},/*!************************************!*\ !*** ./src/elements/Step/index.js ***! \************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var o=r(/*! ./Step */176),a=n(o);t.default=a.default},/*!**********************!*\ !*** ./src/index.js ***! \**********************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=r(/*! ./addons/Confirm */280);Object.defineProperty(t,"Confirm",{enumerable:!0,get:function(){return n(o).default}});var a=r(/*! ./addons/Portal */45);Object.defineProperty(t,"Portal",{enumerable:!0,get:function(){return n(a).default}});var s=r(/*! ./addons/Radio */82);Object.defineProperty(t,"Radio",{enumerable:!0,get:function(){return n(s).default}});var l=r(/*! ./addons/Select */136);Object.defineProperty(t,"Select",{enumerable:!0,get:function(){return n(l).default}});var u=r(/*! ./addons/TextArea */137);Object.defineProperty(t,"TextArea",{enumerable:!0,get:function(){return n(u).default}});var i=r(/*! ./collections/Breadcrumb */286);Object.defineProperty(t,"Breadcrumb",{enumerable:!0,get:function(){return n(i).default}});var c=r(/*! ./collections/Breadcrumb/BreadcrumbDivider */138);Object.defineProperty(t,"BreadcrumbDivider",{enumerable:!0,get:function(){return n(c).default}});var p=r(/*! ./collections/Breadcrumb/BreadcrumbSection */139);Object.defineProperty(t,"BreadcrumbSection",{enumerable:!0,get:function(){return n(p).default}});var d=r(/*! ./collections/Form */288);Object.defineProperty(t,"Form",{enumerable:!0,get:function(){return n(d).default}});var f=r(/*! ./collections/Form/FormButton */140);Object.defineProperty(t,"FormButton",{enumerable:!0,get:function(){return n(f).default}});var y=r(/*! ./collections/Form/FormCheckbox */141);Object.defineProperty(t,"FormCheckbox",{enumerable:!0,get:function(){return n(y).default}});var m=r(/*! ./collections/Form/FormDropdown */142);Object.defineProperty(t,"FormDropdown",{enumerable:!0,get:function(){return n(m).default}});var h=r(/*! ./collections/Form/FormField */16);Object.defineProperty(t,"FormField",{enumerable:!0,get:function(){return n(h).default}});var v=r(/*! ./collections/Form/FormGroup */143);Object.defineProperty(t,"FormGroup",{enumerable:!0,get:function(){return n(v).default}});var b=r(/*! ./collections/Form/FormInput */144);Object.defineProperty(t,"FormInput",{enumerable:!0,get:function(){return n(b).default}});var g=r(/*! ./collections/Form/FormRadio */145);Object.defineProperty(t,"FormRadio",{enumerable:!0,get:function(){return n(g).default}});var P=r(/*! ./collections/Form/FormSelect */146);Object.defineProperty(t,"FormSelect",{enumerable:!0,get:function(){return n(P).default}});var T=r(/*! ./collections/Form/FormTextArea */147);Object.defineProperty(t,"FormTextArea",{enumerable:!0,get:function(){return n(T).default}});var O=r(/*! ./collections/Grid */290);Object.defineProperty(t,"Grid",{enumerable:!0,get:function(){return n(O).default}});var _=r(/*! ./collections/Grid/GridColumn */148);Object.defineProperty(t,"GridColumn",{enumerable:!0,get:function(){return n(_).default}});var E=r(/*! ./collections/Grid/GridRow */149);Object.defineProperty(t,"GridRow",{enumerable:!0,get:function(){return n(E).default}});var j=r(/*! ./collections/Menu */292);Object.defineProperty(t,"Menu",{enumerable:!0,get:function(){return n(j).default}});var w=r(/*! ./collections/Menu/MenuHeader */150);Object.defineProperty(t,"MenuHeader",{enumerable:!0,get:function(){return n(w).default}});var S=r(/*! ./collections/Menu/MenuItem */151);Object.defineProperty(t,"MenuItem",{enumerable:!0,get:function(){return n(S).default}});var M=r(/*! ./collections/Menu/MenuMenu */152);Object.defineProperty(t,"MenuMenu",{enumerable:!0,get:function(){return n(M).default}});var x=r(/*! ./collections/Message */294);Object.defineProperty(t,"Message",{enumerable:!0,get:function(){return n(x).default}});var k=r(/*! ./collections/Message/MessageContent */153);Object.defineProperty(t,"MessageContent",{enumerable:!0,get:function(){return n(k).default}});var A=r(/*! ./collections/Message/MessageHeader */154);Object.defineProperty(t,"MessageHeader",{enumerable:!0,get:function(){return n(A).default}});var C=r(/*! ./collections/Message/MessageItem */83);Object.defineProperty(t,"MessageItem",{enumerable:!0,get:function(){return n(C).default}});var N=r(/*! ./collections/Message/MessageList */155);Object.defineProperty(t,"MessageList",{enumerable:!0,get:function(){return n(N).default}});var I=r(/*! ./collections/Table */296);Object.defineProperty(t,"Table",{enumerable:!0,get:function(){return n(I).default}});var K=r(/*! ./collections/Table/TableBody */156);Object.defineProperty(t,"TableBody",{enumerable:!0,get:function(){return n(K).default}});var L=r(/*! ./collections/Table/TableCell */46);Object.defineProperty(t,"TableCell",{enumerable:!0,get:function(){return n(L).default}});var U=r(/*! ./collections/Table/TableFooter */157);Object.defineProperty(t,"TableFooter",{enumerable:!0,get:function(){return n(U).default}});var D=r(/*! ./collections/Table/TableHeader */84);Object.defineProperty(t,"TableHeader",{enumerable:!0,get:function(){return n(D).default}});var R=r(/*! ./collections/Table/TableHeaderCell */158);Object.defineProperty(t,"TableHeaderCell",{enumerable:!0,get:function(){return n(R).default}});var z=r(/*! ./collections/Table/TableRow */159);Object.defineProperty(t,"TableRow",{enumerable:!0,get:function(){return n(z).default}});var W=r(/*! ./elements/Button/Button */160);Object.defineProperty(t,"Button",{enumerable:!0,get:function(){return n(W).default}});var F=r(/*! ./elements/Button/ButtonContent */161);Object.defineProperty(t,"ButtonContent",{enumerable:!0,get:function(){return n(F).default}});var V=r(/*! ./elements/Button/ButtonGroup */162);Object.defineProperty(t,"ButtonGroup",{enumerable:!0,get:function(){return n(V).default}});var B=r(/*! ./elements/Button/ButtonOr */163);Object.defineProperty(t,"ButtonOr",{enumerable:!0,get:function(){return n(B).default}});var Y=r(/*! ./elements/Container */298);Object.defineProperty(t,"Container",{enumerable:!0,get:function(){return n(Y).default}});var q=r(/*! ./elements/Divider */300);Object.defineProperty(t,"Divider",{enumerable:!0,get:function(){return n(q).default}});var H=r(/*! ./elements/Flag */164);Object.defineProperty(t,"Flag",{enumerable:!0,get:function(){return n(H).default}});var G=r(/*! ./elements/Header */303);Object.defineProperty(t,"Header",{enumerable:!0,get:function(){return n(G).default}});var Z=r(/*! ./elements/Header/HeaderContent */165);Object.defineProperty(t,"HeaderContent",{enumerable:!0,get:function(){return n(Z).default}});var $=r(/*! ./elements/Header/HeaderSubheader */166);Object.defineProperty(t,"HeaderSubheader",{enumerable:!0,get:function(){return n($).default}});var X=r(/*! ./elements/Icon */8);Object.defineProperty(t,"Icon",{enumerable:!0,get:function(){return n(X).default}});var Q=r(/*! ./elements/Icon/IconGroup */167);Object.defineProperty(t,"IconGroup",{enumerable:!0,get:function(){return n(Q).default}});var J=r(/*! ./elements/Image */30);Object.defineProperty(t,"Image",{enumerable:!0,get:function(){return n(J).default}});var ee=r(/*! ./elements/Image/ImageGroup */169);Object.defineProperty(t,"ImageGroup",{enumerable:!0,get:function(){return n(ee).default}});var te=r(/*! ./elements/Input */86);Object.defineProperty(t,"Input",{enumerable:!0,get:function(){return n(te).default}});var re=r(/*! ./elements/Label */48);Object.defineProperty(t,"Label",{enumerable:!0,get:function(){return n(re).default}});var ne=r(/*! ./elements/Label/LabelDetail */170);Object.defineProperty(t,"LabelDetail",{enumerable:!0,get:function(){return n(ne).default}});var oe=r(/*! ./elements/Label/LabelGroup */171);Object.defineProperty(t,"LabelGroup",{enumerable:!0,get:function(){return n(oe).default}});var ae=r(/*! ./elements/List */306);Object.defineProperty(t,"List",{enumerable:!0,get:function(){return n(ae).default}});var se=r(/*! ./elements/List/ListContent */88);Object.defineProperty(t,"ListContent",{enumerable:!0,get:function(){return n(se).default}});var le=r(/*! ./elements/List/ListDescription */49);Object.defineProperty(t,"ListDescription",{enumerable:!0,get:function(){return n(le).default}});var ue=r(/*! ./elements/List/ListHeader */50);Object.defineProperty(t,"ListHeader",{enumerable:!0,get:function(){return n(ue).default}});var ie=r(/*! ./elements/List/ListIcon */89);Object.defineProperty(t,"ListIcon",{enumerable:!0,get:function(){return n(ie).default}});var ce=r(/*! ./elements/List/ListItem */172);Object.defineProperty(t,"ListItem",{enumerable:!0,get:function(){return n(ce).default}});var pe=r(/*! ./elements/List/ListList */173);Object.defineProperty(t,"ListList",{enumerable:!0,get:function(){return n(pe).default}});var de=r(/*! ./elements/Loader */308);Object.defineProperty(t,"Loader",{enumerable:!0,get:function(){return n(de).default}});var fe=r(/*! ./elements/Rail */310);Object.defineProperty(t,"Rail",{enumerable:!0,get:function(){return n(fe).default}});var ye=r(/*! ./elements/Reveal */312);Object.defineProperty(t,"Reveal",{enumerable:!0,get:function(){return n(ye).default}});var me=r(/*! ./elements/Reveal/RevealContent */174);Object.defineProperty(t,"RevealContent",{enumerable:!0,get:function(){return n(me).default}});var he=r(/*! ./elements/Segment */314);Object.defineProperty(t,"Segment",{enumerable:!0,get:function(){return n(he).default}});var ve=r(/*! ./elements/Segment/SegmentGroup */175);Object.defineProperty(t,"SegmentGroup",{enumerable:!0,get:function(){return n(ve).default}});var be=r(/*! ./elements/Step */315);Object.defineProperty(t,"Step",{enumerable:!0,get:function(){return n(be).default}});var ge=r(/*! ./elements/Step/StepContent */177);Object.defineProperty(t,"StepContent",{enumerable:!0,get:function(){return n(ge).default}});var Pe=r(/*! ./elements/Step/StepDescription */90);Object.defineProperty(t,"StepDescription",{enumerable:!0,get:function(){return n(Pe).default}});var Te=r(/*! ./elements/Step/StepGroup */178);Object.defineProperty(t,"StepGroup",{enumerable:!0,get:function(){return n(Te).default}});var Oe=r(/*! ./elements/Step/StepTitle */91);Object.defineProperty(t,"StepTitle",{enumerable:!0,get:function(){return n(Oe).default}});var _e=r(/*! ./modules/Accordion/Accordion */329);Object.defineProperty(t,"Accordion",{enumerable:!0,get:function(){return n(_e).default}});var Ee=r(/*! ./modules/Accordion/AccordionContent */181);Object.defineProperty(t,"AccordionContent",{enumerable:!0,get:function(){return n(Ee).default}});var je=r(/*! ./modules/Accordion/AccordionTitle */182);Object.defineProperty(t,"AccordionTitle",{enumerable:!0,get:function(){return n(je).default}});var we=r(/*! ./modules/Checkbox */51);Object.defineProperty(t,"Checkbox",{enumerable:!0,get:function(){return n(we).default}});var Se=r(/*! ./modules/Dimmer */184);Object.defineProperty(t,"Dimmer",{enumerable:!0,get:function(){return n(Se).default}});var Me=r(/*! ./modules/Dimmer/DimmerDimmable */183);Object.defineProperty(t,"DimmerDimmable",{enumerable:!0,get:function(){return n(Me).default}});var xe=r(/*! ./modules/Dropdown */93);Object.defineProperty(t,"Dropdown",{enumerable:!0,get:function(){return n(xe).default}});var ke=r(/*! ./modules/Dropdown/DropdownDivider */185);Object.defineProperty(t,"DropdownDivider",{enumerable:!0,get:function(){return n(ke).default}});var Ae=r(/*! ./modules/Dropdown/DropdownHeader */186);Object.defineProperty(t,"DropdownHeader",{enumerable:!0,get:function(){return n(Ae).default}});var Ce=r(/*! ./modules/Dropdown/DropdownItem */187);Object.defineProperty(t,"DropdownItem",{enumerable:!0,get:function(){return n(Ce).default}});var Ne=r(/*! ./modules/Dropdown/DropdownMenu */188);Object.defineProperty(t,"DropdownMenu",{enumerable:!0,get:function(){return n(Ne).default}});var Ie=r(/*! ./modules/Embed */334);Object.defineProperty(t,"Embed",{enumerable:!0,get:function(){return n(Ie).default}});var Ke=r(/*! ./modules/Modal */193);Object.defineProperty(t,"Modal",{enumerable:!0,get:function(){return n(Ke).default}});var Le=r(/*! ./modules/Modal/ModalActions */189);Object.defineProperty(t,"ModalActions",{enumerable:!0,get:function(){return n(Le).default}});var Ue=r(/*! ./modules/Modal/ModalContent */190);Object.defineProperty(t,"ModalContent",{enumerable:!0,get:function(){return n(Ue).default}});var De=r(/*! ./modules/Modal/ModalDescription */191);Object.defineProperty(t,"ModalDescription",{enumerable:!0,get:function(){return n(De).default}});var Re=r(/*! ./modules/Modal/ModalHeader */192);Object.defineProperty(t,"ModalHeader",{enumerable:!0,get:function(){return n(Re).default}});var ze=r(/*! ./modules/Popup */337);Object.defineProperty(t,"Popup",{enumerable:!0,get:function(){return n(ze).default}});var We=r(/*! ./modules/Popup/PopupContent */194);Object.defineProperty(t,"PopupContent",{enumerable:!0,get:function(){return n(We).default}});var Fe=r(/*! ./modules/Popup/PopupHeader */195);Object.defineProperty(t,"PopupHeader",{enumerable:!0,get:function(){return n(Fe).default}});var Ve=r(/*! ./modules/Progress */339);Object.defineProperty(t,"Progress",{enumerable:!0,get:function(){return n(Ve).default}});var Be=r(/*! ./modules/Rating */342);Object.defineProperty(t,"Rating",{enumerable:!0,get:function(){return n(Be).default}});var Ye=r(/*! ./modules/Search */344);Object.defineProperty(t,"Search",{enumerable:!0,get:function(){return n(Ye).default}});var qe=r(/*! ./modules/Search/SearchCategory */196);Object.defineProperty(t,"SearchCategory",{enumerable:!0,get:function(){return n(qe).default}});var He=r(/*! ./modules/Search/SearchResult */197);Object.defineProperty(t,"SearchResult",{enumerable:!0,get:function(){return n(He).default}});var Ge=r(/*! ./modules/Search/SearchResults */198);Object.defineProperty(t,"SearchResults",{enumerable:!0,get:function(){return n(Ge).default}});var Ze=r(/*! ./views/Card/Card */199);Object.defineProperty(t,"Card",{enumerable:!0,get:function(){return n(Ze).default}});var $e=r(/*! ./views/Card/CardContent */200);Object.defineProperty(t,"CardContent",{enumerable:!0,get:function(){return n($e).default}});var Xe=r(/*! ./views/Card/CardDescription */94);Object.defineProperty(t,"CardDescription",{enumerable:!0,get:function(){return n(Xe).default}});var Qe=r(/*! ./views/Card/CardGroup */201);Object.defineProperty(t,"CardGroup",{enumerable:!0,get:function(){return n(Qe).default}});var Je=r(/*! ./views/Card/CardHeader */95);Object.defineProperty(t,"CardHeader",{enumerable:!0,get:function(){return n(Je).default}});var et=r(/*! ./views/Card/CardMeta */96);Object.defineProperty(t,"CardMeta",{enumerable:!0,get:function(){return n(et).default}});var tt=r(/*! ./views/Comment */346);Object.defineProperty(t,"Comment",{enumerable:!0,get:function(){return n(tt).default}});var rt=r(/*! ./views/Comment/CommentAction */202);Object.defineProperty(t,"CommentAction",{enumerable:!0,get:function(){return n(rt).default}});var nt=r(/*! ./views/Comment/CommentActions */203);Object.defineProperty(t,"CommentActions",{enumerable:!0,get:function(){return n(nt).default}});var ot=r(/*! ./views/Comment/CommentAuthor */204);Object.defineProperty(t,"CommentAuthor",{enumerable:!0,get:function(){return n(ot).default}});var at=r(/*! ./views/Comment/CommentAvatar */205);Object.defineProperty(t,"CommentAvatar",{enumerable:!0,get:function(){return n(at).default}});var st=r(/*! ./views/Comment/CommentContent */206);Object.defineProperty(t,"CommentContent",{enumerable:!0,get:function(){return n(st).default}});var lt=r(/*! ./views/Comment/CommentGroup */207);Object.defineProperty(t,"CommentGroup",{enumerable:!0,get:function(){return n(lt).default}});var ut=r(/*! ./views/Comment/CommentMetadata */208);Object.defineProperty(t,"CommentMetadata",{enumerable:!0,get:function(){return n(ut).default}});var it=r(/*! ./views/Comment/CommentText */209);Object.defineProperty(t,"CommentText",{enumerable:!0,get:function(){return n(it).default}});var ct=r(/*! ./views/Feed */348);Object.defineProperty(t,"Feed",{enumerable:!0,get:function(){return n(ct).default}});var pt=r(/*! ./views/Feed/FeedContent */97);Object.defineProperty(t,"FeedContent",{enumerable:!0,get:function(){return n(pt).default}});var dt=r(/*! ./views/Feed/FeedDate */52);Object.defineProperty(t,"FeedDate",{enumerable:!0,get:function(){return n(dt).default}});var ft=r(/*! ./views/Feed/FeedEvent */210);Object.defineProperty(t,"FeedEvent",{enumerable:!0,get:function(){return n(ft).default}});var yt=r(/*! ./views/Feed/FeedExtra */98);Object.defineProperty(t,"FeedExtra",{enumerable:!0,get:function(){return n(yt).default}});var mt=r(/*! ./views/Feed/FeedLabel */99);Object.defineProperty(t,"FeedLabel",{enumerable:!0,get:function(){return n(mt).default}});var ht=r(/*! ./views/Feed/FeedLike */100);Object.defineProperty(t,"FeedLike",{enumerable:!0,get:function(){return n(ht).default}});var vt=r(/*! ./views/Feed/FeedMeta */101);Object.defineProperty(t,"FeedMeta",{enumerable:!0,get:function(){return n(vt).default}});var bt=r(/*! ./views/Feed/FeedSummary */102);Object.defineProperty(t,"FeedSummary",{enumerable:!0,get:function(){return n(bt).default}});var gt=r(/*! ./views/Feed/FeedUser */103);Object.defineProperty(t,"FeedUser",{enumerable:!0,get:function(){return n(gt).default}});var Pt=r(/*! ./views/Item */349);Object.defineProperty(t,"Item",{enumerable:!0,get:function(){return n(Pt).default}});var Tt=r(/*! ./views/Item/ItemContent */212);Object.defineProperty(t,"ItemContent",{enumerable:!0,get:function(){return n(Tt).default}});var Ot=r(/*! ./views/Item/ItemDescription */104);Object.defineProperty(t,"ItemDescription",{enumerable:!0,get:function(){return n(Ot).default}});var _t=r(/*! ./views/Item/ItemExtra */105);Object.defineProperty(t,"ItemExtra",{enumerable:!0,get:function(){return n(_t).default}});var Et=r(/*! ./views/Item/ItemGroup */213);Object.defineProperty(t,"ItemGroup",{enumerable:!0,get:function(){return n(Et).default}});var jt=r(/*! ./views/Item/ItemHeader */106);Object.defineProperty(t,"ItemHeader",{enumerable:!0,get:function(){return n(jt).default}});var wt=r(/*! ./views/Item/ItemImage */214);Object.defineProperty(t,"ItemImage",{enumerable:!0,get:function(){return n(wt).default}});var St=r(/*! ./views/Item/ItemMeta */107);Object.defineProperty(t,"ItemMeta",{enumerable:!0,get:function(){return n(St).default}});var Mt=r(/*! ./views/Statistic */350);Object.defineProperty(t,"Statistic",{enumerable:!0,get:function(){return n(Mt).default}});var xt=r(/*! ./views/Statistic/StatisticGroup */216);Object.defineProperty(t,"StatisticGroup",{enumerable:!0,get:function(){return n(xt).default}});var kt=r(/*! ./views/Statistic/StatisticLabel */217);Object.defineProperty(t,"StatisticLabel",{enumerable:!0,get:function(){return n(kt).default}});var At=r(/*! ./views/Statistic/StatisticValue */218);Object.defineProperty(t,"StatisticValue",{enumerable:!0,get:function(){return n(At).default}})},/*!********************************************!*\ !*** ./src/lib/AutoControlledComponent.js ***! \********************************************/ function(e,t,r){(function(e){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0}),t.getAutoControlledStateValue=void 0;var l=r(/*! lodash/difference */482),u=n(l),i=r(/*! lodash/isUndefined */133),c=n(i),p=r(/*! lodash/startsWith */275),d=n(p),f=r(/*! lodash/filter */128),y=n(f),m=r(/*! lodash/isEmpty */130),h=n(m),v=r(/*! lodash/keys */9),b=n(v),g=r(/*! lodash/intersection */510),P=n(g),T=r(/*! lodash/has */27),O=n(T),_=r(/*! lodash/each */74),E=n(_),j=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},w=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),S=function e(t,r,n){null===t&&(t=Function.prototype);var o=Object.getOwnPropertyDescriptor(t,r);if(void 0===o){var a=Object.getPrototypeOf(t);return null===a?void 0:e(a,r,n)}if("value"in o)return o.value;var s=o.get;if(void 0!==s)return s.call(n)},M=r(/*! react */1),x=function(e){return"default"+(e[0].toUpperCase()+e.slice(1))},k=t.getAutoControlledStateValue=function(e,t){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=x(t),o=e[t],a=e[n],s=void 0!==o,l=void 0!==a;return r&&!s&&l?a:s?o:"checked"!==t&&("value"===t?e.multiple?[]:"":void 0)},A=function(t){function r(){var t,n,s,l;o(this,r);for(var i=arguments.length,c=Array(i),p=0;p<i;p++)c[p]=arguments[p];return n=s=a(this,(t=r.__proto__||Object.getPrototypeOf(r)).call.apply(t,[this].concat(c))),s.trySetState=function(t,r){var n=s.constructor.autoControlledProps;if("production"!==e.env.NODE_ENV){var o=s.constructor.name,a=(0,u.default)((0,b.default)(t),n);(0,h.default)(a)||console.error([o+' called trySetState() with controlled props: "'+a+'".',"State will not be set.","Only props in static autoControlledProps will be set on state."].join(" "))}var l=Object.keys(t).reduce(function(e,r){return void 0!==s.props[r]?e:n.indexOf(r)===-1?e:(e[r]=t[r],e)},{});r&&(l=j({},l,r)),Object.keys(l).length>0&&s.setState(l)},l=n,a(s,l)}return s(r,t),w(r,[{key:"componentWillMount",value:function(){var t=this;S(r.prototype.__proto__||Object.getPrototypeOf(r.prototype),"componentWillMount",this)&&S(r.prototype.__proto__||Object.getPrototypeOf(r.prototype),"componentWillMount",this).call(this);var n=this.constructor.autoControlledProps;"production"!==e.env.NODE_ENV&&!function(){var e=t.constructor,r=e.defaultProps,o=e.name,a=e.propTypes;n||console.error("Auto controlled "+o+" must specify a static autoControlledProps array."),(0,E.default)(n,function(e){var t=x(e);(0,O.default)(a,t)||console.error(o+' is missing "'+t+'" propTypes validation for auto controlled prop "'+e+'".'),(0,O.default)(a,e)||console.error(o+' is missing propTypes validation for auto controlled prop "'+e+'".')});var s=(0,P.default)(n,(0,b.default)(r));(0,h.default)(s)||console.error(["Do not set defaultProps for autoControlledProps,","use trySetState() in constructor() or componentWillMount() instead.","See "+o+' props: "'+s+'".'].join(" "));var l=(0,y.default)(n,function(e){return(0,d.default)(e,"default")});(0,h.default)(l)||console.error(["Do not add default props to autoControlledProps.","Default props are automatically handled.","See "+o+' autoControlledProps: "'+l+'".'].join(" "))}(),this.state=n.reduce(function(r,n){if(r[n]=k(t.props,n,!0),"production"!==e.env.NODE_ENV){var o=x(n),a=t.constructor.name;o in t.props&&n in t.props&&console.error(a+' prop "'+n+'" is auto controlled. Specify either '+o+" or "+n+", but not both.")}return r},{})}},{key:"componentWillReceiveProps",value:function(e){var t=this;S(r.prototype.__proto__||Object.getPrototypeOf(r.prototype),"componentWillReceiveProps",this)&&S(r.prototype.__proto__||Object.getPrototypeOf(r.prototype),"componentWillReceiveProps",this).call(this,e);var n=this.constructor.autoControlledProps,o=n.reduce(function(r,n){var o=(0,c.default)(e[n]),a=!(0,c.default)(t.props[n])&&o;return o?a&&(r[n]=k(e,n)):r[n]=e[n],r},{});Object.keys(o).length>0&&this.setState(o)}}]),r}(M.Component);t.default=A}).call(t,r(/*! ./~/process/browser.js */35))},/*!*************************!*\ !*** ./src/lib/META.js ***! \*************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.isPrivate=t.isChild=t.isParent=t.isModule=t.isView=t.isElement=t.isCollection=t.isAddon=t.isType=t.isMeta=t.TYPES=void 0;var o=r(/*! lodash/fp/startsWith */505),a=n(o),s=r(/*! lodash/fp/has */495),l=n(s),u=r(/*! lodash/fp/eq */493),i=n(u),c=r(/*! lodash/fp/flow */263),p=n(c),d=r(/*! lodash/fp/curry */492),f=n(d),y=r(/*! lodash/fp/get */494),m=n(y),h=r(/*! lodash/fp/includes */264),v=n(h),b=r(/*! lodash/fp/values */508),g=n(b),P=t.TYPES={ADDON:"addon",COLLECTION:"collection",ELEMENT:"element",VIEW:"view",MODULE:"module"},T=(0,g.default)(P),O=t.isMeta=function(e){return(0,v.default)((0,m.default)("type",e),T)},_=function(e){return O(e)?e:O((0,m.default)("_meta",e))?e._meta:O((0,m.default)("constructor._meta",e))?e.constructor._meta:void 0},E=(0,f.default)(function(e,t,r){return(0,p.default)(_,(0,m.default)(e),(0,i.default)(t))(r)}),j=t.isType=E("type");t.isAddon=j(P.ADDON),t.isCollection=j(P.COLLECTION),t.isElement=j(P.ELEMENT),t.isView=j(P.VIEW),t.isModule=j(P.MODULE),t.isParent=(0,p.default)(_,(0,l.default)("parent"),(0,i.default)(!1)),t.isChild=(0,p.default)(_,(0,l.default)("parent")),t.isPrivate=(0,p.default)(_,(0,m.default)("name"),(0,a.default)("_"))},/*!************************!*\ !*** ./src/lib/SUI.js ***! \************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){if(Array.isArray(e)){for(var t=0,r=Array(e.length);t<e.length;t++)r[t]=e[t];return r}return Array.from(e)}Object.defineProperty(t,"__esModule",{value:!0}),t.ICONS=t.WIDTHS=t.VERTICAL_ALIGNMENTS=t.TEXT_ALIGNMENTS=t.SIZES=t.FLOATS=t.COLORS=void 0;var a=r(/*! lodash/values */134),s=n(a),l=r(/*! lodash/keys */9),u=n(l),i=r(/*! ./numberToWord */92);t.COLORS=["red","orange","yellow","olive","green","teal","blue","violet","purple","pink","brown","grey","black"],t.FLOATS=["left","right"],t.SIZES=["mini","tiny","small","medium","large","big","huge","massive"],t.TEXT_ALIGNMENTS=["left","center","right","justified"],t.VERTICAL_ALIGNMENTS=["bottom","middle","top"],t.WIDTHS=[].concat(o((0,u.default)(i.numberToWordMap)),o((0,u.default)(i.numberToWordMap).map(Number)),o((0,s.default)(i.numberToWordMap))),t.ICONS=["search","mail outline","signal","setting","home","inbox","browser","tag","tags","image","calendar","comment","shop","comments","external","privacy","settings","comments","external","trophy","payment","feed","alarm outline","tasks","cloud","lab","mail","dashboard","comment outline","comments outline","sitemap","idea","alarm","terminal","code","protect","calendar outline","ticket","external square","bug","mail square","history","options","text telephone","find","wifi","alarm mute","alarm mute outline","copyright","at","eyedropper","paint brush","heartbeat","mouse pointer","hourglass empty","hourglass start","hourglass half","hourglass end","hourglass full","hand pointer","trademark","registered","creative commons","add to calendar","remove from calendar","delete calendar","checked calendar","industry","shopping bag","shopping basket","hashtag","percent","wait","download","repeat","refresh","lock","bookmark","print","write","adjust","theme","edit","external share","ban","mail forward","share","expand","compress","unhide","hide","random","retweet","sign out","pin","sign in","upload","call","remove bookmark","call square","unlock","configure","filter","wizard","undo","exchange","cloud download","cloud upload","reply","reply all","erase","unlock alternate","write square","share square","archive","translate","recycle","send","send outline","share alternate","share alternate square","add to cart","in cart","add user","remove user","object group","object ungroup","clone","talk","talk outline","help circle","info circle","warning circle","warning sign","announcement","help","info","warning","birthday","help circle outline","user","users","doctor","handicap","student","child","spy","female","male","woman","man","non binary transgender","intergender","transgender","lesbian","gay","heterosexual","other gender","other gender vertical","other gender horizontal","neuter","genderless","universal access","wheelchair","blind","audio description","volume control phone","braille","asl","assistive listening systems","deafness","sign language","low vision","block layout","grid layout","list layout","zoom","zoom out","resize vertical","resize horizontal","maximize","crop","cocktail","road","flag","book","gift","leaf","fire","plane","magnet","lemon","world","travel","shipping","money","legal","lightning","umbrella","treatment","suitcase","bar","flag outline","flag checkered","puzzle","fire extinguisher","rocket","anchor","bullseye","sun","moon","fax","life ring","bomb","soccer","calculator","diamond","sticky note","sticky note outline","law","hand peace","hand rock","hand paper","hand scissors","hand lizard","hand spock","tv","crosshairs","asterisk","square outline","certificate","square","quote left","quote right","spinner","circle","ellipsis horizontal","ellipsis vertical","cube","cubes","circle notched","circle thin","checkmark","remove","checkmark box","move","add circle","minus circle","remove circle","check circle","remove circle outline","check circle outline","plus","minus","add square","radio","minus square","minus square outline","check square","selected radio","plus square outline","toggle off","toggle on","film","sound","photo","bar chart","camera retro","newspaper","area chart","pie chart","line chart","arrow circle outline down","arrow circle outline up","chevron left","chevron right","arrow left","arrow right","arrow up","arrow down","chevron up","chevron down","pointing right","pointing left","pointing up","pointing down","arrow circle left","arrow circle right","arrow circle up","arrow circle down","caret down","caret up","caret left","caret right","angle double left","angle double right","angle double up","angle double down","angle left","angle right","angle up","angle down","chevron circle left","chevron circle right","chevron circle up","chevron circle down","toggle down","toggle up","toggle right","long arrow down","long arrow up","long arrow left","long arrow right","arrow circle outline right","arrow circle outline left","toggle left","tablet","mobile","battery full","battery high","battery medium","battery low","battery empty","power","trash outline","disk outline","desktop","laptop","game","keyboard","plug","trash","file outline","folder","folder open","file text outline","folder outline","folder open outline","level up","level down","file","file text","file pdf outline","file word outline","file excel outline","file powerpoint outline","file image outline","file archive outline","file audio outline","file video outline","file code outline","qrcode","barcode","rss","fork","html5","css3","rss square","openid","database","server","usb","bluetooth","bluetooth alternative","heart","star","empty star","thumbs outline up","thumbs outline down","star half","empty heart","smile","frown","meh","star half empty","thumbs up","thumbs down","music","video play outline","volume off","volume down","volume up","record","step backward","fast backward","backward","play","pause","stop","forward","fast forward","step forward","eject","unmute","mute","video play","closed captioning","pause circle","pause circle outline","stop circle","stop circle outline","marker","coffee","food","building outline","hospital","emergency","first aid","military","h","location arrow","compass","space shuttle","university","building","paw","spoon","car","taxi","tree","bicycle","bus","ship","motorcycle","street view","hotel","train","subway","map pin","map signs","map outline","map","table","columns","sort","sort descending","sort ascending","sort alphabet ascending","sort alphabet descending","sort content ascending","sort content descending","sort numeric ascending","sort numeric descending","font","bold","italic","text height","text width","align left","align center","align right","align justify","list","outdent","indent","linkify","cut","copy","attach","save","content","unordered list","ordered list","strikethrough","underline","paste","unlinkify","superscript","subscript","header","paragraph","text cursor","euro","pound","dollar","rupee","yen","ruble","won","bitcoin","lira","shekel","paypal","google wallet","visa","mastercard","discover","american express","paypal card","stripe","japan credit bureau","diners club","credit card alternative","twitter square","facebook square","linkedin square","github square","twitter","facebook f","github","pinterest","pinterest square","google plus square","google plus","linkedin","github alternate","maxcdn","youtube square","youtube","xing","xing square","youtube play","dropbox","stack overflow","instagram","flickr","adn","bitbucket","bitbucket square","tumblr","tumblr square","apple","windows","android","linux","dribble","skype","foursquare","trello","gittip","vk","weibo","renren","pagelines","stack exchange","vimeo square","slack","wordpress","yahoo","google","reddit","reddit square","stumbleupon circle","stumbleupon","delicious","digg","pied piper","pied piper alternate","drupal","joomla","behance","behance square","steam","steam square","spotify","deviantart","soundcloud","vine","codepen","jsfiddle","rebel","empire","git square","git","hacker news","tencent weibo","qq","wechat","slideshare","twitch","yelp","lastfm","lastfm square","ioxhost","angellist","meanpath","buysellads","connectdevelop","dashcube","forumbee","leanpub","sellsy","shirtsinbulk","simplybuilt","skyatlas","facebook","pinterest","whatsapp","viacoin","medium","y combinator","optinmonster","opencart","expeditedssl","gg","gg circle","tripadvisor","odnoklassniki","odnoklassniki square","pocket","wikipedia","safari","chrome","firefox","opera","internet explorer","contao","500px","amazon","houzz","vimeo","black tie","fonticons","reddit alien","microsoft edge","codiepie","modx","fort awesome","product hunt","mixcloud","scribd","gitlab","wpbeginner","wpforms","envira gallery","glide","glide g","viadeo","viadeo square","snapchat","snapchat ghost","snapchat square","pied piper hat","first order","yoast","themeisle","google plus circle","font awesome","like","favorite","video","check","close","cancel","delete","x","zoom in","magnify","shutdown","clock","time","play circle outline","headphone","camera","video camera","picture","pencil","compose","point","tint","signup","plus circle","question circle","dont","minimize","add","exclamation circle","attention","eye","exclamation triangle","shuffle","chat","cart","shopping cart","bar graph","key","cogs","discussions","like outline","dislike outline","heart outline","log out","thumb tack","winner","phone","bookmark outline","phone square","credit card","hdd outline","bullhorn","bell outline","hand outline right","hand outline left","hand outline up","hand outline down","globe","wrench","briefcase","group","linkify","chain","flask","sidebar","bars","list ul","list ol","numbered list","magic","truck","currency","triangle down","dropdown","triangle up","triangle left","triangle right","envelope","conversation","rain","clipboard","lightbulb","bell","ambulance","medkit","fighter jet","beer","plus square","computer","circle outline","gamepad","star half full","broken chain","question","exclamation","eraser","microphone","microphone slash","shield","target","play circle","pencil square","eur","gbp","usd","inr","cny","rmb","jpy","rouble","rub","krw","btc","gratipay","zip","dot circle outline","try","graduation","circle outline","sliders","weixin","tty","teletype","binoculars","power cord","wifi","visa card","mastercard card","discover card","amex","american express card","stripe card","bell slash","bell slash outline","area graph","pie graph","line graph","cc","sheqel","ils","plus cart","arrow down cart","detective","venus","mars","mercury","intersex","venus double","female homosexual","mars double","male homosexual","venus mars","mars stroke","mars alternate","mars vertical","mars stroke vertical","mars horizontal","mars stroke horizontal","asexual","facebook official","user plus","user times","user close","user cancel","user delete","user x","bed","yc","ycombinator","battery four","battery three","battery three quarters","battery two","battery half","battery one","battery quarter","battery zero","i cursor","jcb","japan credit bureau card","diners club card","balance","hourglass outline","hourglass zero","hourglass one","hourglass two","hourglass three","hourglass four","grab","hand victory","tm","r circle","television","five hundred pixels","calendar plus","calendar minus","calendar times","calendar check","factory","commenting","commenting outline","edge","ms edge","wordpress beginner","wordpress forms","envira","question circle outline","assistive listening devices","als","ald","asl interpreting","deaf","american sign language interpreting","hard of hearing","signing","new pied piper","theme isle","google plus official","fa"]},/*!**********************************!*\ !*** ./src/lib/childrenUtils.js ***! \**********************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.findByType=t.someByType=void 0;var o=r(/*! lodash/find */129),a=n(o),s=r(/*! lodash/some */274),l=n(s),u=r(/*! react */1);t.someByType=function(e,t){return(0,l.default)(u.Children.toArray(e),{type:t})},t.findByType=function(e,t){return(0,a.default)(u.Children.toArray(e),{type:t})}},/*!**************************************!*\ !*** ./src/lib/classNameBuilders.js ***! \**************************************/ function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.useVerticalAlignProp=t.useTextAlignProp=t.useWidthProp=t.useKeyOrValueAndKey=t.useValueAndKey=t.useKeyOnly=void 0;var n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},o=r(/*! ./numberToWord */92),a=(t.useKeyOnly=function(e,t){return e&&t},t.useValueAndKey=function(e,t){return e&&e!==!0&&e+" "+t});t.useKeyOrValueAndKey=function(e,t){return e&&(e===!0?t:e+" "+t)},t.useWidthProp=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(r&&"equal"===e)return"equal width";var a="undefined"==typeof e?"undefined":n(e);return"string"!==a&&"number"!==a||!t?(0,o.numberToWord)(e):(0,o.numberToWord)(e)+" "+t},t.useTextAlignProp=function(e){return"justified"===e?"justified":a(e,"aligned")},t.useVerticalAlignProp=function(e){return a(e,"aligned")}},/*!************************************!*\ !*** ./src/lib/customPropTypes.js ***! \************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){if(Array.isArray(e)){for(var t=0,r=Array(e.length);t<e.length;t++)r[t]=e[t];return r}return Array.from(e)}Object.defineProperty(t,"__esModule",{value:!0}),t.deprecate=t.collectionShorthand=t.itemShorthand=t.contentShorthand=t.demand=t.givenProps=t.some=t.every=t.disallow=t.suggest=t.as=void 0;var a=r(/*! lodash/fp/isObject */498),s=n(a),l=r(/*! lodash/fp/pick */503),u=n(l),i=r(/*! lodash/fp/keys */500),c=n(i),p=r(/*! lodash/fp/isPlainObject */499),d=n(p),f=r(/*! lodash/fp/isFunction */496),y=n(f),m=r(/*! lodash/fp/compact */491),h=n(m),v=r(/*! lodash/fp/take */507),b=n(v),g=r(/*! lodash/fp/sortBy */504),P=n(g),T=r(/*! lodash/fp/sum */506),O=n(T),_=r(/*! lodash/fp/min */502),E=n(_),j=r(/*! lodash/fp/map */501),w=n(j),S=r(/*! lodash/fp/flow */263),M=n(S),x=r(/*! lodash/fp/includes */264),k=n(x),A=r(/*! lodash/fp/isNil */497),C=n(A),N=r(/*! react */1),I=r(/*! ./leven */180),K=n(I),L=function(){var e;return(e=Object.prototype.toString).call.apply(e,arguments)},U=(t.as=function(){return N.PropTypes.oneOfType([N.PropTypes.string,N.PropTypes.func]).apply(void 0,arguments)},t.suggest=function(e){return function(t,r,n){if(!Array.isArray(e))throw new Error(["Invalid argument supplied to suggest, expected an instance of array."," See `"+r+"` prop in `"+n+"`."].join(""));var o=t[r];if(!(0,C.default)(o)&&o!==!1&&!(0,k.default)(o,e)){var a=o.split(" "),s=(0,M.default)((0,w.default)(function(e){var t=e.split(" "),r=(0,M.default)((0,w.default)(function(e){return(0,w.default)(function(t){return(0,K.default)(e,t)},t)}),(0,w.default)(E.default),O.default)(a),n=(0,M.default)((0,w.default)(function(e){return(0,w.default)(function(t){return(0,K.default)(e,t)},a)}),(0,w.default)(E.default),O.default)(t);return{suggestion:e,score:r+n}}),(0,P.default)(["score","suggestion"]),(0,b.default)(3))(e);if(!s.some(function(e){return 0===e.score}))return new Error(["Invalid prop `"+r+"` of value `"+o+"` supplied to `"+n+"`.","\n\nInstead of `"+o+"`, did you mean:",s.map(function(e){return"\n - "+e.suggestion}).join(""),"\n"].join(""))}}},t.disallow=function(e){return function(t,r,n){if(!Array.isArray(e))throw new Error(["Invalid argument supplied to disallow, expected an instance of array."," See `"+r+"` prop in `"+n+"`."].join(""));if(!(0,C.default)(t[r])&&t[r]!==!1){var a=e.reduce(function(e,r){return(0,C.default)(t[r])||t[r]===!1?e:[].concat(o(e),[r])},[]);return a.length>0?new Error(["Prop `"+r+"` in `"+n+"` conflicts with props: `"+a.join("`, `")+"`.","They cannot be defined together, choose one or the other."].join(" ")):void 0}}}),D=t.every=function(e){return function(t,r,n){for(var o=arguments.length,a=Array(o>3?o-3:0),s=3;s<o;s++)a[s-3]=arguments[s];if(!Array.isArray(e))throw new Error(["Invalid argument supplied to every, expected an instance of array.","See `"+r+"` prop in `"+n+"`."].join(" "));var l=(0,M.default)((0,w.default)(function(e){if("function"!=typeof e)throw new Error('every() argument "validators" should contain functions, found: '+L(e)+".");return e.apply(void 0,[t,r,n].concat(a))}),h.default)(e);return l[0]}},R=(t.some=function(e){return function(t,r,n){for(var o=arguments.length,a=Array(o>3?o-3:0),s=3;s<o;s++)a[s-3]=arguments[s];if(!Array.isArray(e))throw new Error(["Invalid argument supplied to some, expected an instance of array.","See `"+r+"` prop in `"+n+"`."].join(" "));var l=(0,h.default)((0,w.default)(e,function(e){if(!(0,y.default)(e))throw new Error('some() argument "validators" should contain functions, found: '+L(e)+".");return e.apply(void 0,[t,r,n].concat(a))}));if(l.length===e.length){var u=new Error("One of these validators must pass:");return u.message+="\n"+(0,w.default)(l,function(e,t){return"["+(t+1)+"]: "+e.message}).join("\n"),u}}},t.givenProps=function(e,t){return function(r,n,o){for(var a=arguments.length,l=Array(a>3?a-3:0),i=3;i<a;i++)l[i-3]=arguments[i];if(!(0,d.default)(e))throw new Error(["Invalid argument supplied to givenProps, expected an object.","See `"+n+"` prop in `"+o+"`."].join(" "));if("function"!=typeof t)throw new Error(["Invalid argument supplied to givenProps, expected a function.","See `"+n+"` prop in `"+o+"`."].join(" "));var p=(0,c.default)(e).every(function(t){var a=e[t];return"function"==typeof a?!a.apply(void 0,[r,t,o].concat(l)):a===r[n]});if(p){var f=t.apply(void 0,[r,n,o].concat(l));if(f){var y="{ "+(0,c.default)((0,u.default)((0,c.default)(e),r)).map(function(e){var t=r[e],n=t;return"string"==typeof t?n='"'+t+'"':Array.isArray(t)?n="["+t.join(", ")+"]":(0,s.default)(t)&&(n="{...}"),e+": "+n}).join(", ")+" }";return f.message="Given props "+y+": "+f.message,f}}}},t.demand=function(e){return function(t,r,n){if(!Array.isArray(e))throw new Error(["Invalid `requiredProps` argument supplied to require, expected an instance of array."," See `"+r+"` prop in `"+n+"`."].join(""));if(void 0!==t[r]){var o=e.filter(function(e){return void 0===t[e]});return o.length>0?new Error("`"+r+"` prop in `"+n+"` requires props: `"+o.join("`, `")+"`."):void 0}}},t.contentShorthand=function(){return D([U(["children"]),N.PropTypes.node]).apply(void 0,arguments)},t.itemShorthand=function(){return D([U(["children"]),N.PropTypes.oneOfType([N.PropTypes.node,N.PropTypes.object])]).apply(void 0,arguments)});t.collectionShorthand=function(){return D([U(["children"]),N.PropTypes.arrayOf(R)]).apply(void 0,arguments)},t.deprecate=function(e,t){return function(r,n,o){for(var a=arguments.length,s=Array(a>3?a-3:0),l=3;l<a;l++)s[l-3]=arguments[l];if("string"!=typeof e)throw new Error(["Invalid `help` argument supplied to deprecate, expected a string.","See `"+n+"` prop in `"+o+"`."].join(" "));if(void 0!==r[n]){var u=new Error("The `"+n+"` prop in `"+o+"` is deprecated.");if(e&&(u.message+=" "+e),t){if("function"!=typeof t)throw new Error(["Invalid argument supplied to deprecate, expected a function.","See `"+n+"` prop in `"+o+"`."].join(" "));var i=t.apply(void 0,[r,n,o].concat(s));i&&(u.message=u.message+" "+i.message)}return u}}}},/*!**************************!*\ !*** ./src/lib/debug.js ***! \**************************/ function(e,t,r){(function(e){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.debug=t.makeDebugger=void 0;var o=r(/*! ./isBrowser */179),a=n(o),s=void 0,l=function(){};if(a.default&&"production"!==e.env.NODE_ENV&&"test"!==e.env.NODE_ENV){var u=void 0;try{u=window.localStorage.debug}catch(e){console.error("Semantic-UI-React could not enable debug."),console.error(e)}s=r(/*! debug */351),s.enable(u)}else s=function(){return l};var i=t.makeDebugger=function(e){return s("semanticUIReact:"+e)};t.debug=i("log")}).call(t,r(/*! ./~/process/browser.js */35))},/*!******************************!*\ !*** ./src/lib/factories.js ***! \******************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){var r={};for(var n in e)t.indexOf(n)>=0||Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=e[n]);return r}function a(e,t,r){var n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};if("function"!=typeof e&&"string"!=typeof e)throw new Error("createShorthandFactory() Component must be a string or function.");if(null===r)return null;var o=void 0,a={};(0,E.isValidElement)(r)?(o="element",a=r.props):(0,h.default)(r)?(o="props",a=r):((0,y.default)(r)||(0,d.default)(r)||(0,c.default)(r))&&(o="literal",a=t(r)),n=(0,b.default)(n)?n(a):n;var s=w(n,a);return"element"===o?(0,E.cloneElement)(r,s):"props"===o||"literal"===o?j.default.createElement(e,s):null}function s(e,t){if("function"!=typeof e&&"string"!=typeof e)throw new Error("createShorthandFactory() Component must be a string or function.");return(0,u.default)(a,e,t)}Object.defineProperty(t,"__esModule",{value:!0}),t.createHTMLInput=t.createHTMLImage=void 0;var l=r(/*! lodash/partial */515),u=n(l),i=r(/*! lodash/isArray */4),c=n(i),p=r(/*! lodash/isNumber */268),d=n(p),f=r(/*! lodash/isString */269),y=n(f),m=r(/*! lodash/isPlainObject */132),h=n(m),v=r(/*! lodash/isFunction */28),b=n(v),g=r(/*! lodash/has */27),P=n(g),T=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e};t.createShorthand=a,t.createShorthandFactory=s;var O=r(/*! classnames */3),_=n(O),E=r(/*! react */1),j=n(E),w=function(e,t){var r=T({},e,t),n=r.childKey,a=o(r,["childKey"]);return((0,P.default)(t,"className")||(0,P.default)(e.className))&&(a.className=(0,_.default)(e.className,t.className)),!a.key&&n&&(a.key=(0,b.default)(n)?n(a):n),a};t.createHTMLImage=s("img",function(e){return{src:e}}),t.createHTMLInput=s("input",function(e){return{type:e}})},/*!***********************************!*\ !*** ./src/lib/getElementType.js ***! \***********************************/ function(e,t){"use strict";function r(e,t,r){var n=e.defaultProps,o=void 0===n?{}:n;if(t.as&&t.as!==o.as)return t.as;if(r){var a=r();if(a)return a}return t.href?"a":o.as||"div"}Object.defineProperty(t,"__esModule",{value:!0}),t.default=r},/*!**************************************!*\ !*** ./src/lib/getUnhandledProps.js ***! \**************************************/ function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=function(e,t){return e.forEach(function(e){t.indexOf(e)===-1&&t.push(e)})},n=function(e,t){var n=e.autoControlledProps,o=e.defaultProps,a=e.propTypes,s=e.handledProps;return s||(s=[],n&&r(n,s),o&&r(Object.keys(o),s),a&&r(Object.keys(a),s),e.handledProps=s),Object.keys(t).reduce(function(e,r){return s.indexOf(r)===-1&&(e[r]=t[r]),e},{})};t.default=n},/*!********************************!*\ !*** ./src/lib/keyboardKey.js ***! \********************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=r(/*! lodash/isObject */12),a=n(o),s=r(/*! lodash/times */277),l=n(s),u={3:"Cancel",6:"Help",8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",28:"Convert",29:"NonConvert",30:"Accept",31:"ModeChange",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",41:"Select",42:"Print",43:"Execute",44:"PrintScreen",45:"Insert",46:"Delete",48:["0",")"],49:["1","!"],50:["2","@"],51:["3","#"],52:["4","$"],53:["5","%"],54:["6","^"],55:["7","&"],56:["8","*"],57:["9","("],91:"OS",93:"ContextMenu",144:"NumLock",145:"ScrollLock",181:"VolumeMute",182:"VolumeDown",183:"VolumeUp",186:[";",":"],187:["=","+"],188:[",","<"],189:["-","_"],190:[".",">"],191:["/","?"],192:["`","~"],219:["[","{"],220:["\\","|"],221:["]","}"],222:["'",'"'],224:"Meta",225:"AltGraph",246:"Attn",247:"CrSel",248:"ExSel",249:"EraseEof",250:"Play",251:"ZoomOut"};(0,l.default)(24,function(e){return u[112+e]="F"+(e+1)}),(0,l.default)(26,function(e){var t=e+65;u[t]=[String.fromCharCode(t+32),String.fromCharCode(t)]});var i={codes:u,getCode:function(e){return(0,a.default)(e)?e.keyCode||e.which||this[e.key]:this[e]},getName:function(e){var t=(0,a.default)(e),r=u[t?e.keyCode||e.which:e];return Array.isArray(r)&&(r=t?r[e.shiftKey?1:0]:r[0]),r},Cancel:3,Help:6,Backspace:8,Tab:9,Clear:12,Enter:13,Shift:16,Control:17,Alt:18,Pause:19,CapsLock:20,Escape:27,Convert:28,NonConvert:29,Accept:30,ModeChange:31," ":32,PageUp:33,PageDown:34,End:35,Home:36,ArrowLeft:37,ArrowUp:38,ArrowRight:39,ArrowDown:40,Select:41,Print:42,Execute:43,PrintScreen:44,Insert:45,Delete:46,0:48,")":48,1:49,"!":49,2:50,"@":50,3:51,"#":51,4:52,$:52,5:53,"%":53,6:54,"^":54,7:55,"&":55,8:56,"*":56,9:57,"(":57,a:65,A:65,b:66,B:66,c:67,C:67,d:68,D:68,e:69,E:69,f:70,F:70,g:71,G:71,h:72,H:72,i:73,I:73,j:74,J:74,k:75,K:75,l:76,L:76,m:77,M:77,n:78,N:78,o:79,O:79,p:80,P:80,q:81,Q:81,r:82,R:82,s:83,S:83,t:84,T:84,u:85,U:85,v:86,V:86,w:87,W:87,x:88,X:88,y:89,Y:89,z:90,Z:90,OS:91,ContextMenu:93,F1:112,F2:113,F3:114,F4:115,F5:116,F6:117,F7:118,F8:119,F9:120,F10:121,F11:122,F12:123,F13:124,F14:125,F15:126,F16:127,F17:128,F18:129,F19:130,F20:131,F21:132,F22:133,F23:134,F24:135,NumLock:144,ScrollLock:145,VolumeMute:181,VolumeDown:182,VolumeUp:183,";":186,":":186,"=":187,"+":187,",":188,"<":188,"-":189,_:189,".":190,">":190,"/":191,"?":191,"`":192,"~":192,"[":219,"{":219,"\\":220,"|":220,"]":221,"}":221,"'":222,'"':222,Meta:224,AltGraph:225,Attn:246,CrSel:247,ExSel:248,EraseEof:249,Play:250,ZoomOut:251};i.Spacebar=i[" "],i.Digit0=i[0],i.Digit1=i[1],i.Digit2=i[2],i.Digit3=i[3],i.Digit4=i[4],i.Digit5=i[5],i.Digit6=i[6],i.Digit7=i[7],i.Digit8=i[8],i.Digit9=i[9],i.Tilde=i["~"],i.GraveAccent=i["`"],i.ExclamationPoint=i["!"],i.AtSign=i["@"],i.PoundSign=i["#"],i.PercentSign=i["%"],i.Caret=i["^"],i.Ampersand=i["&"],i.PlusSign=i["+"],i.MinusSign=i["-"],i.EqualsSign=i["="],i.DivisionSign=i["/"],i.MultiplicationSign=i["*"],i.Comma=i[","],i.Decimal=i["."],i.Colon=i[":"],i.Semicolon=i[";"],i.Pipe=i["|"],i.BackSlash=i["\\"],i.QuestionMark=i["?"],i.SingleQuote=i['"'],i.DoubleQuote=i['"'],i.LeftCurlyBrace=i["{"],i.RightCurlyBrace=i["}"],i.LeftParenthesis=i["("],i.RightParenthesis=i[")"],i.LeftAngleBracket=i["<"],i.RightAngleBracket=i[">"],i.LeftSquareBracket=i["["],i.RightSquareBracket=i["]"],t.default=i},/*!*******************************!*\ !*** ./src/lib/objectDiff.js ***! \*******************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.objectDiff=void 0;var o=r(/*! lodash/isEqual */78),a=n(o),s=r(/*! lodash/has */27),l=n(s),u=r(/*! lodash/transform */526),i=n(u);t.objectDiff=function(e,t){return(0,i.default)(e,function(e,r,n){(0,l.default)(t,n)?(0,a.default)(r,t[n])||(e[n]=t[n]):e[n]="[DELETED]"},{})}},/*!********************************************!*\ !*** ./src/modules/Accordion/Accordion.js ***! \********************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var l=r(/*! lodash/keys */9),u=n(l),i=r(/*! lodash/omit */44),c=n(i),p=r(/*! lodash/each */74),d=n(p),f=r(/*! lodash/has */27),y=n(f),m="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},h=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},v=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),b=function e(t,r,n){null===t&&(t=Function.prototype);var o=Object.getOwnPropertyDescriptor(t,r);if(void 0===o){var a=Object.getPrototypeOf(t);return null===a?void 0:e(a,r,n)}if("value"in o)return o.value;var s=o.get;if(void 0!==s)return s.call(n)},g=r(/*! classnames */3),P=n(g),T=r(/*! react */1),O=n(T),_=r(/*! ../../lib */2),E=r(/*! ../../elements/Icon */8),j=n(E),w=r(/*! ./AccordionContent */181),S=n(w),M=r(/*! ./AccordionTitle */182),x=n(M),k=function(e){function t(){var e,r,n,s;o(this,t);for(var l=arguments.length,u=Array(l),i=0;i<l;i++)u[i]=arguments[i];return r=n=a(this,(e=t.__proto__||Object.getPrototypeOf(t)).call.apply(e,[this].concat(u))),n.state={},n.handleTitleClick=function(e,t){var r=n.props.onTitleClick,o=n.state.activeIndex;n.trySetState({activeIndex:t===o?-1:t}),r&&r(e,t)},n.renderChildren=function(){var e=n.props.children,t=n.state.activeIndex,r=0,o=0;return T.Children.map(e,function(e){var a=e.type===x.default,s=e.type===S.default;if(a){var l=function(){var o=r,a=(0,y.default)(e,"props.active")?e.props.active:t===o,s=function(t){n.handleTitleClick(t,o),e.props.onClick&&e.props.onClick(t,o)};return r++,{v:(0,T.cloneElement)(e,h({},e.props,{active:a,onClick:s}))}}();if("object"===("undefined"==typeof l?"undefined":m(l)))return l.v}if(s){var u=o,i=(0,y.default)(e,"props.active")?e.props.active:t===u;return o++,(0,T.cloneElement)(e,h({},e.props,{active:i}))}return e})},n.renderPanels=function(){var e=n.props.panels,t=n.state.activeIndex,r=[];return(0,d.default)(e,function(e,o){var a=(0,y.default)(e,"active")?e.active:t===o,s=function(t){n.handleTitleClick(t,o),e.onClick&&e.onClick(t,o)};r.push(O.default.createElement(x.default,{key:e.title+"-title",active:a,onClick:s},O.default.createElement(j.default,{name:"dropdown"}),e.title)),r.push(O.default.createElement(S.default,{key:e.title+"-content",active:a},e.content))}),r},s=r,a(n,s)}return s(t,e),v(t,[{key:"componentWillMount",value:function(){b(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"componentWillMount",this).call(this),"undefined"==typeof this.props.defaultActiveIndex&&this.trySetState({activeIndex:-1})}},{key:"render",value:function(){var e=this.props,r=e.className,n=e.fluid,o=e.inverted,a=e.panels,s=e.styled,l=(0,P.default)("ui",(0,_.useKeyOnly)(n,"fluid"),(0,_.useKeyOnly)(o,"inverted"),(0,_.useKeyOnly)(s,"styled"),"accordion",r),i=(0,c.default)(this.props,(0,u.default)(t.propTypes)),p=(0,_.getElementType)(t,this.props);return O.default.createElement(p,h({},i,{className:l}),a?this.renderPanels():this.renderChildren())}}]),t}(_.AutoControlledComponent);k.autoControlledProps=["activeIndex"],k.propTypes={as:_.customPropTypes.as,activeIndex:T.PropTypes.number,children:T.PropTypes.node,className:T.PropTypes.string,defaultActiveIndex:T.PropTypes.number,fluid:T.PropTypes.bool,inverted:T.PropTypes.bool,onTitleClick:T.PropTypes.func,panels:_.customPropTypes.every([_.customPropTypes.disallow(["children"]),T.PropTypes.arrayOf(T.PropTypes.shape({active:T.PropTypes.bool,title:T.PropTypes.string,content:T.PropTypes.string,onClick:T.PropTypes.func}))]),styled:T.PropTypes.bool},k._meta={name:"Accordion",type:_.META.TYPES.MODULE},k.Content=S.default,k.Title=x.default,t.default=k},/*!******************************************!*\ !*** ./src/modules/Checkbox/Checkbox.js ***! \******************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var l=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},u=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),i=r(/*! react */1),c=n(i),p=r(/*! classnames */3),d=n(p),f=r(/*! ../../lib */2),y=(0,f.makeDebugger)("checkbox"),m={name:"Checkbox",type:f.META.TYPES.MODULE,props:{type:["checkbox","radio"]}},h=function(e){function t(){var e,r,n,s;o(this,t);for(var l=arguments.length,u=Array(l),i=0;i<l;i++)u[i]=arguments[i];return r=n=a(this,(e=t.__proto__||Object.getPrototypeOf(t)).call.apply(e,[this].concat(u))),n.state={},n.canToggle=function(){var e=n.props,t=e.disabled,r=e.radio,o=e.readOnly,a=n.state.checked;return!(t||o||r&&a)},n.handleClick=function(e){y("handleClick()");var t=n.props,r=t.onChange,o=t.onClick,a=t.name,s=t.value,l=n.state.checked;y(" name: "+a),y(" value: "+s),y(" checked: "+l),n.canToggle()&&(o&&o(e,{name:a,value:s,checked:!!l}),r&&r(e,{name:a,value:s,checked:!l}),n.trySetState({checked:!l}))},s=r,a(n,s)}return s(t,e),u(t,[{key:"render",value:function(){var e=this.props,r=e.className,n=e.label,o=e.name,a=e.radio,s=e.slider,u=e.toggle,i=e.type,p=e.value,y=e.disabled,m=e.readOnly,h=this.state.checked,v=(0,d.default)("ui",(0,f.useKeyOnly)(h,"checked"),(0,f.useKeyOnly)(!n,"fitted"),(0,f.useKeyOnly)(a,"radio"),(0,f.useKeyOnly)(s,"slider"),(0,f.useKeyOnly)(u,"toggle"),(0,f.useKeyOnly)(y,"disabled"),(0,f.useKeyOnly)(m,"read-only"),"checkbox",r),b=(0,f.getUnhandledProps)(t,this.props),g=(0,f.getElementType)(t,this.props);return c.default.createElement(g,l({},b,{className:v,onClick:this.handleClick,onChange:this.handleClick}),c.default.createElement("input",{type:i,name:o,checked:h,className:"hidden",readOnly:!0,tabIndex:0,value:p}),c.default.createElement("label",null,n))}}]),t}(f.AutoControlledComponent);h.propTypes={as:f.customPropTypes.as,className:i.PropTypes.string,checked:i.PropTypes.bool,defaultChecked:i.PropTypes.bool,slider:f.customPropTypes.every([i.PropTypes.bool,f.customPropTypes.disallow(["radio","toggle"])]),radio:f.customPropTypes.every([i.PropTypes.bool,f.customPropTypes.disallow(["slider","toggle"])]),toggle:f.customPropTypes.every([i.PropTypes.bool,f.customPropTypes.disallow(["radio","slider"])]),disabled:i.PropTypes.bool,fitted:i.PropTypes.bool,label:i.PropTypes.string,type:i.PropTypes.oneOf(m.props.type),name:i.PropTypes.string,onChange:i.PropTypes.func,onClick:i.PropTypes.func,readOnly:i.PropTypes.bool,value:i.PropTypes.string},h.defaultProps={type:"checkbox"},h.autoControlledProps=["checked"],h._meta=m,t.default=h},/*!**************************************!*\ !*** ./src/modules/Dimmer/Dimmer.js ***! \**************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var l=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},u=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),i=r(/*! classnames */3),c=n(i),p=r(/*! react */1),d=n(p),f=r(/*! ../../lib */2),y=r(/*! ../../addons/Portal */45),m=n(y),h=r(/*! ./DimmerDimmable */183),v=n(h),b={name:"Dimmer",type:f.META.TYPES.MODULE},g=function(e){function t(){var e,r,n,s;o(this,t);for(var l=arguments.length,u=Array(l),i=0;i<l;i++)u[i]=arguments[i];return r=n=a(this,(e=t.__proto__||Object.getPrototypeOf(t)).call.apply(e,[this].concat(u))),n.handlePortalMount=function(){f.isBrowser&&document.body.classList.add("dimmed","dimmable")},n.handlePortalUnmount=function(){f.isBrowser&&document.body.classList.remove("dimmed","dimmable")},n.handleClick=function(e){var t=n.props,r=t.onClick,o=t.onClickOutside;r&&r(e,n.props),n.center&&n.center!==e.target&&n.center.contains(e.target)||o&&o(e,n.props)},s=r,a(n,s)}return s(t,e),u(t,[{key:"render",value:function(){var e=this,r=this.props,n=r.active,o=r.children,a=r.className,s=r.content,u=r.disabled,i=r.inverted,p=r.page,y=r.simple,h=(0,c.default)("ui",(0,f.useKeyOnly)(n,"active transition visible"),(0,f.useKeyOnly)(u,"disabled"),(0,f.useKeyOnly)(i,"inverted"),(0,f.useKeyOnly)(p,"page"),(0,f.useKeyOnly)(y,"simple"),"dimmer",a),v=(0,f.getUnhandledProps)(t,this.props),b=(0,f.getElementType)(t,this.props),g=(o||s)&&d.default.createElement("div",{className:"content"},d.default.createElement("div",{className:"center",ref:function(t){return e.center=t}},o||s));return p?d.default.createElement(m.default,{closeOnEscape:!1,closeOnDocumentClick:!1,onMount:this.handlePortalMount,onUnmount:this.handlePortalUnmount,open:n,openOnTriggerClick:!1},d.default.createElement(b,l({},v,{className:h,onClick:this.handleClick}),g)):d.default.createElement(b,l({},v,{className:h,onClick:this.handleClick}),g)}}]),t}(p.Component);g.propTypes={as:f.customPropTypes.as,active:p.PropTypes.bool,children:p.PropTypes.node,className:p.PropTypes.string,content:f.customPropTypes.contentShorthand,disabled:p.PropTypes.bool,onClick:p.PropTypes.func,onClickOutside:p.PropTypes.func,inverted:p.PropTypes.bool,page:p.PropTypes.bool,simple:p.PropTypes.bool},g._meta=b,g.Dimmable=v.default,t.default=g,g.create=(0,f.createShorthandFactory)(g,function(e){return{content:e}})},/*!******************************************!*\ !*** ./src/modules/Dropdown/Dropdown.js ***! \******************************************/ function(e,t,r){(function(e){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var l=r(/*! lodash/compact */259),u=n(l),i=r(/*! lodash/map */10),c=n(i),p=r(/*! lodash/isNil */267),d=n(p),f=r(/*! lodash/every */261),y=n(f),m=r(/*! lodash/without */7),h=n(m),v=r(/*! lodash/findIndex */262),b=n(v),g=r(/*! lodash/find */129),P=n(g),T=r(/*! lodash/reduce */273),O=n(T),_=r(/*! lodash/escapeRegExp */484),E=n(_),j=r(/*! lodash/filter */128),w=n(j),S=r(/*! lodash/isFunction */28),M=n(S),x=r(/*! lodash/dropRight */483),k=n(x),A=r(/*! lodash/isEmpty */130),C=n(A),N=r(/*! lodash/union */527),I=n(N),K=r(/*! lodash/some */274),L=n(K),U=r(/*! lodash/get */34),D=n(U),R=r(/*! lodash/includes */75),z=n(R),W=r(/*! lodash/has */27),F=n(W),V=r(/*! lodash/isEqual */78),B=n(V),Y=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},q=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),H=function e(t,r,n){null===t&&(t=Function.prototype);var o=Object.getOwnPropertyDescriptor(t,r);if(void 0===o){var a=Object.getPrototypeOf(t);return null===a?void 0:e(a,r,n)}if("value"in o)return o.value;var s=o.get;if(void 0!==s)return s.call(n)},G=r(/*! classnames */3),Z=n(G),$=r(/*! react */1),X=n($),Q=r(/*! ../../lib */2),J=r(/*! ../../elements/Icon */8),ee=n(J),te=r(/*! ../../elements/Label */48),re=n(te),ne=r(/*! ./DropdownDivider */185),oe=n(ne),ae=r(/*! ./DropdownItem */187),se=n(ae),le=r(/*! ./DropdownHeader */186),ue=n(le),ie=r(/*! ./DropdownMenu */188),ce=n(ie),pe=(0,Q.makeDebugger)("dropdown"),de={name:"Dropdown",type:Q.META.TYPES.MODULE,props:{pointing:["left","right","top","top left","top right","bottom","bottom left","bottom right"],additionPosition:["top","bottom"]}},fe=function(t){function r(){var e,t,n,s;o(this,r);for(var l=arguments.length,i=Array(l),p=0;p<l;p++)i[p]=arguments[p];return t=n=a(this,(e=r.__proto__||Object.getPrototypeOf(r)).call.apply(e,[this].concat(i))),n.handleChange=function(e,t){pe("handleChange()"),pe(t);var r=n.props,o=r.name,a=r.onChange;a&&a(e,{name:o,value:t})},n.closeOnEscape=function(e){Q.keyboardKey.getCode(e)===Q.keyboardKey.Escape&&(e.preventDefault(),n.close())},n.moveSelectionOnKeyDown=function(e){switch(pe("moveSelectionOnKeyDown()"),pe(Q.keyboardKey.getName(e)),Q.keyboardKey.getCode(e)){case Q.keyboardKey.ArrowDown:e.preventDefault(),n.moveSelectionBy(1);break;case Q.keyboardKey.ArrowUp:e.preventDefault(),n.moveSelectionBy(-1)}},n.openOnSpace=function(e){pe("openOnSpace()"),Q.keyboardKey.getCode(e)===Q.keyboardKey.Spacebar&&(n.state.open||(e.preventDefault(),n.open(e)))},n.openOnArrow=function(e){pe("openOnArrow()");var t=Q.keyboardKey.getCode(e);(0,z.default)([Q.keyboardKey.ArrowDown,Q.keyboardKey.ArrowUp],t)&&(n.state.open||(e.preventDefault(),n.open(e)))},n.selectHighlightedItem=function(e){var t=n.state.open,r=n.props,o=r.multiple,a=r.name,s=r.onAddItem,l=r.options,u=(0,D.default)(n.getSelectedItem(),"value");if(u&&t)if(s&&!(0,L.default)(l,{text:u})&&s(e,{name:a,value:u}),o){var i=(0,I.default)(n.state.value,[u]);n.setValue(i),n.handleChange(e,i)}else n.setValue(u),n.handleChange(e,u),n.close()},n.selectItemOnEnter=function(e){pe("selectItemOnEnter()"),pe(Q.keyboardKey.getName(e)),Q.keyboardKey.getCode(e)===Q.keyboardKey.Enter&&(e.preventDefault(),n.selectHighlightedItem(e))},n.removeItemOnBackspace=function(e){if(pe("removeItemOnBackspace()"),pe(Q.keyboardKey.getName(e)),Q.keyboardKey.getCode(e)===Q.keyboardKey.Backspace){var t=n.props,r=t.multiple,o=t.search,a=n.state,s=a.searchQuery,l=a.value;if(!s&&o&&r&&!(0,C.default)(l)){e.preventDefault();var u=(0,k.default)(l);n.setValue(u),n.handleChange(e,u)}}},n.closeOnDocumentClick=function(e){pe("closeOnDocumentClick()"),pe(e),n._dropdown&&(0,M.default)(n._dropdown.contains)&&n._dropdown.contains(e.target)||n.close()},n.handleMouseDown=function(e){pe("handleMouseDown()");var t=n.props.onMouseDown;t&&t(e),n.isMouseDown=!0,Q.isBrowser&&document.addEventListener("mouseup",n.handleDocumentMouseUp)},n.handleDocumentMouseUp=function(){pe("handleDocumentMouseUp()"),n.isMouseDown=!1,Q.isBrowser&&document.removeEventListener("mouseup",n.handleDocumentMouseUp)},n.handleClick=function(e){pe("handleClick()",e);var t=n.props.onClick;t&&t(e),e.stopPropagation(),n.toggle(e)},n.handleItemClick=function(e,t){var r=t.value;pe("handleItemClick()"),pe(r);var o=n.props,a=o.multiple,s=o.name,l=o.onAddItem,u=o.options,i=n.getItemByValue(r)||{};if(e.stopPropagation(),(a||i.disabled)&&e.nativeEvent.stopImmediatePropagation(),!i.disabled)if(l&&!(0,L.default)(u,{text:r})&&l(e,{name:s,value:r}),a){var c=(0,I.default)(n.state.value,[r]);n.setValue(c),n.handleChange(e,c)}else n.setValue(r),n.handleChange(e,r),n.close()},n.handleFocus=function(e){pe("handleFocus()");var t=n.props.onFocus;t&&t(e),n.setState({focus:!0})},n.handleBlur=function(e){pe("handleBlur()");var t=n.props,r=t.multiple,o=t.onBlur,a=t.selectOnBlur;n.isMouseDown||(o&&o(e),a&&!r&&n.selectHighlightedItem(e),n.setState({focus:!1}))},n.handleSearchChange=function(e){pe("handleSearchChange()"),pe(e.target.value),e.stopPropagation();var t=n.props,r=t.search,o=t.onSearchChange,a=n.state.open,s=e.target.value;o&&o(e,s),r&&s&&!a&&n.open(),n.setState({selectedIndex:n.getEnabledIndices()[0],searchQuery:s})},n.getMenuOptions=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:n.state.value,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:n.props.options,r=n.props,o=r.multiple,a=r.search,s=r.allowAdditions,l=r.additionPosition,u=r.additionLabel,i=n.state.searchQuery,c=t;if(o&&(c=(0,w.default)(c,function(t){return!(0,z.default)(e,t.value)})),a&&i&&((0,M.default)(a)?c=a(c,i):!function(){var e=new RegExp((0,E.default)(i),"i");c=(0,w.default)(c,function(t){return e.test(t.text)})}()),s&&a&&i&&!(0,L.default)(c,{text:i})){var p=X.default.isValidElement(u)?X.default.cloneElement(u,{key:"label"}):u||"",d={text:[p,X.default.createElement("b",{key:"addition"},i)],value:i,className:"addition"};"top"===l?c.unshift(d):c.push(d)}return c},n.getSelectedItem=function(){var e=n.state.selectedIndex,t=n.getMenuOptions();return(0,D.default)(t,"["+e+"]")},n.getEnabledIndices=function(e){var t=e||n.getMenuOptions();return(0,O.default)(t,function(e,t,r){return t.disabled||e.push(r),e},[])},n.getItemByValue=function(e){var t=n.props.options;return(0,P.default)(t,{value:e})},n.getMenuItemIndexByValue=function(e,t){var r=t||n.getMenuOptions();return(0,b.default)(r,["value",e])},n.setValue=function(e){pe("setValue()"),pe("value",e);var t={searchQuery:""};n.trySetState({value:e},t),n.setSelectedIndex(e)},n.setSelectedIndex=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:n.state.value,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:n.props.options,r=n.props.multiple,o=n.state.selectedIndex,a=n.getMenuOptions(e,t),s=n.getEnabledIndices(a),l=void 0;if(!o||o<0){var u=s[0];l=r?u:n.getMenuItemIndexByValue(e,a)||s[0]}else if(r)o>=a.length-1&&(l=s[s.length-1]);else{var i=n.getMenuItemIndexByValue(e,a);l=(0,z.default)(s,i)?i:void 0}(!l||l<0)&&(l=s[0]),n.setState({selectedIndex:l})},n.handleLabelClick=function(e,t){pe("handleLabelClick()"),e.stopPropagation(),n.setState({selectedLabel:t.value});var r=n.props.onLabelClick;r&&r(e,t)},n.handleLabelRemove=function(e,t){pe("handleLabelRemove()"),e.stopPropagation();var r=n.state.value,o=(0,h.default)(r,t.value);pe("label props:",t),pe("current value:",r),pe("remove value:",t.value),pe("new value:",o),n.setValue(o),n.handleChange(e,o)},n.moveSelectionBy=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:n.state.selectedIndex;pe("moveSelectionBy()"),pe("offset: "+e);var r=n.getMenuOptions(),o=r.length-1;if(!(0,y.default)(r,"disabled")){var a=t+e;if(a>o?a=0:a<0&&(a=o),r[a].disabled)return n.moveSelectionBy(e,a);n.setState({selectedIndex:a}),n.scrollSelectedItemIntoView()}},n.scrollSelectedItemIntoView=function(){if(pe("scrollSelectedItemIntoView()"),Q.isBrowser){var e=document.querySelector(".ui.dropdown.active.visible .menu.visible"),t=e.querySelector(".item.selected");pe("menu: "+e),pe("item: "+t);var r=t.offsetTop<e.scrollTop,n=t.offsetTop+t.clientHeight>e.scrollTop+e.clientHeight;r?e.scrollTop=t.offsetTop:n&&(e.scrollTop=t.offsetTop+t.clientHeight-e.clientHeight)}},n.open=function(e){pe("open()");var t=n.props,r=t.disabled,o=t.onOpen,a=t.search;r||(a&&n._search.focus(),o&&o(e,n.props),n.trySetState({open:!0}))},n.close=function(e){pe("close()");var t=n.props.onClose;t&&t(e,n.props),n.trySetState({open:!1})},n.handleClose=function(){pe("handleClose()"),n._dropdown.blur(),n.setState({focus:!1})},n.toggle=function(e){return n.state.open?n.close(e):n.open(e)},n.renderText=function(){var e=n.props,t=e.multiple,r=e.placeholder,o=e.search,a=e.text,s=n.state,l=s.searchQuery,u=s.value,i=s.open,c=t?!(0,C.default)(u):!(0,d.default)(u)&&""!==u,p=(0,Z.default)(r&&!c&&"default","text",o&&l&&"filtered"),f=r;return l?f=null:a?f=a:i&&!t?f=(0,D.default)(n.getSelectedItem(),"text"):c&&(f=(0,D.default)(n.getItemByValue(u),"text")),X.default.createElement("div",{className:p},f)},n.renderHiddenInput=function(){pe("renderHiddenInput()");var e=n.state.value,t=n.props,r=t.multiple,o=t.name,a=t.options,s=t.selection;return pe("name: "+o),pe("selection: "+s),pe("value: "+e),s?X.default.createElement("select",{type:"hidden",name:o,value:e,multiple:r},X.default.createElement("option",{key:"empty",value:""}),(0,c.default)(a,function(e){return X.default.createElement("option",{key:e.value,value:e.value},e.text)})):null},n.renderSearchInput=function(){var e=n.props,t=e.search,r=e.name,o=e.tabIndex,a=n.state.searchQuery;if(!t)return null;var s=void 0;return n._sizer&&a&&(n._sizer.style.display="inline",n._sizer.textContent=a,s=Math.ceil(n._sizer.getBoundingClientRect().width),n._sizer.style.removeProperty("display")),X.default.createElement("input",{value:a,onChange:n.handleSearchChange,className:"search",name:[r,"search"].join("-"),autoComplete:"off",tabIndex:o,style:{width:s},ref:function(e){return n._search=e}})},n.renderSearchSizer=function(){var e=n.props,t=e.search,r=e.multiple;return t&&r?X.default.createElement("span",{className:"sizer",ref:function(e){return n._sizer=e}}):null},n.renderLabels=function(){pe("renderLabels()");var e=n.props,t=e.multiple,r=e.renderLabel,o=n.state,a=o.selectedLabel,s=o.value;if(t&&!(0,C.default)(s)){var l=(0,c.default)(s,n.getItemByValue);return pe("selectedItems",l),(0,c.default)((0,u.default)(l),function(e,t){var o={active:e.value===a,as:"a",key:e.value,onClick:n.handleLabelClick,onRemove:n.handleLabelRemove,value:e.value};return re.default.create(r(e,t,o),o)})}},n.renderOptions=function(){var e=n.props,t=e.multiple,r=e.search,o=e.noResultsMessage,a=n.state,s=a.selectedIndex,l=a.value,u=n.getMenuOptions();if(r&&(0,C.default)(u))return X.default.createElement("div",{className:"message"},o);var i=t?function(e){return(0,z.default)(l,e)}:function(e){return e===l};return(0,c.default)(u,function(e,t){return X.default.createElement(se.default,Y({key:e.value+"-"+t,active:i(e.value),onClick:n.handleItemClick,selected:s===t},e,{style:Y({},e.style,{pointerEvents:"all"})}))})},n.renderMenu=function(){var e=n.props,t=e.children,r=e.header,o=n.state.open,a=o?"visible":"";if(t){var s=$.Children.only(t),l=(0,Z.default)(a,s.props.className);return(0,$.cloneElement)(s,{className:l})}return X.default.createElement(ce.default,{className:a},(0,Q.createShorthand)(ue.default,function(e){return{content:e}},r),n.renderOptions())},s=t,a(n,s)}return s(r,t),q(r,[{key:"componentWillMount",value:function(){H(r.prototype.__proto__||Object.getPrototypeOf(r.prototype),"componentWillMount",this)&&H(r.prototype.__proto__||Object.getPrototypeOf(r.prototype),"componentWillMount",this).call(this),pe("componentWillMount()");var e=this.state,t=e.open,n=e.value;this.setValue(n),t&&this.open()}},{key:"shouldComponentUpdate",value:function(e,t){return!(0,B.default)(e,this.props)||!(0,B.default)(t,this.state)}},{key:"componentWillReceiveProps",value:function(t){if(H(r.prototype.__proto__||Object.getPrototypeOf(r.prototype),"componentWillReceiveProps",this).call(this,t),pe("componentWillReceiveProps()"),pe("to props:",(0,Q.objectDiff)(this.props,t)),"production"!==e.env.NODE_ENV){var n=Array.isArray(t.value),o=(0,F.default)(t,"value");o&&t.multiple&&!n?console.error("Dropdown `value` must be an array when `multiple` is set."+(" Received type: `"+Object.prototype.toString.call(t.value)+"`.")):o&&!t.multiple&&n&&console.error("Dropdown `value` must not be an array when `multiple` is not set. Either set `multiple={true}` or use a string or number value.")}(0,B.default)(t.value,this.props.value)||(pe("value changed, setting",t.value),this.setValue(t.value)),(0,B.default)(t.options,this.props.options)||this.setSelectedIndex(void 0,t.options)}},{key:"componentDidUpdate",value:function(e,t){pe("componentDidUpdate()"),pe("to state:",(0,Q.objectDiff)(t,this.state)),Q.isBrowser&&(!t.focus&&this.state.focus?(pe("dropdown focused"),this.isMouseDown||(pe("mouse is not down, opening"),this.open()),this.state.open?(document.addEventListener("keydown",this.moveSelectionOnKeyDown),document.addEventListener("keydown",this.selectItemOnEnter),document.addEventListener("keydown",this.removeItemOnBackspace)):(document.addEventListener("keydown",this.openOnArrow),document.addEventListener("keydown",this.openOnSpace))):t.focus&&!this.state.focus&&(pe("dropdown blurred"),this.isMouseDown||(pe("mouse is not down, closing"),this.close()),document.removeEventListener("keydown",this.openOnArrow),document.removeEventListener("keydown",this.openOnSpace),document.removeEventListener("keydown",this.moveSelectionOnKeyDown),document.removeEventListener("keydown",this.selectItemOnEnter),document.removeEventListener("keydown",this.removeItemOnBackspace)),!t.open&&this.state.open?(pe("dropdown opened"),document.addEventListener("keydown",this.closeOnEscape),document.addEventListener("keydown",this.moveSelectionOnKeyDown),document.addEventListener("keydown",this.selectItemOnEnter),document.addEventListener("keydown",this.removeItemOnBackspace),document.addEventListener("click",this.closeOnDocumentClick),document.removeEventListener("keydown",this.openOnArrow),document.removeEventListener("keydown",this.openOnSpace)):t.open&&!this.state.open&&(pe("dropdown closed"),this.handleClose(),document.removeEventListener("keydown",this.closeOnEscape),document.removeEventListener("keydown",this.moveSelectionOnKeyDown),document.removeEventListener("keydown",this.selectItemOnEnter),document.removeEventListener("keydown",this.removeItemOnBackspace),document.removeEventListener("click",this.closeOnDocumentClick)))}},{key:"componentWillUnmount",value:function(){pe("componentWillUnmount()"),Q.isBrowser&&(document.removeEventListener("keydown",this.openOnArrow),document.removeEventListener("keydown",this.openOnSpace),document.removeEventListener("keydown",this.moveSelectionOnKeyDown),document.removeEventListener("keydown",this.selectItemOnEnter),document.removeEventListener("keydown",this.removeItemOnBackspace),document.removeEventListener("keydown",this.closeOnEscape),document.removeEventListener("click",this.closeOnDocumentClick))}},{key:"render",value:function(){var e=this;pe("render()"),pe("props",this.props),pe("state",this.state);var t=this.state.open,n=this.props,o=n.basic,a=n.button,s=n.className,l=n.compact,u=n.fluid,i=n.floating,c=n.icon,p=n.inline,d=n.labeled,f=n.multiple,y=n.pointing,m=n.search,h=n.selection,v=n.simple,b=n.loading,g=n.error,P=n.disabled,T=n.scrolling,O=n.tabIndex,_=n.trigger,E=(0,Z.default)("ui",(0,Q.useKeyOnly)(t,"active visible"),(0,Q.useKeyOnly)(P,"disabled"),(0,Q.useKeyOnly)(g,"error"),(0,Q.useKeyOnly)(b,"loading"),(0,Q.useKeyOnly)(o,"basic"),(0,Q.useKeyOnly)(a,"button"),(0,Q.useKeyOnly)(l,"compact"),(0,Q.useKeyOnly)(u,"fluid"),(0,Q.useKeyOnly)(i,"floating"),(0,Q.useKeyOnly)(p,"inline"),(0,Q.useKeyOnly)(d,"labeled"),(0,Q.useKeyOnly)(f,"multiple"),(0,Q.useKeyOnly)(m,"search"),(0,Q.useKeyOnly)(h,"selection"),(0,Q.useKeyOnly)(v,"simple"),(0,Q.useKeyOnly)(T,"scrolling"),(0,Q.useKeyOrValueAndKey)(y,"pointing"),s,"dropdown"),j=(0,Q.getUnhandledProps)(r,this.props),w=(0,Q.getElementType)(r,this.props);return X.default.createElement(w,Y({},j,{className:E,onBlur:this.handleBlur,onClick:this.handleClick,onMouseDown:this.handleMouseDown,onFocus:this.handleFocus,onChange:this.handleChange,tabIndex:P||m?void 0:O,ref:function(t){return e._dropdown=t}}),this.renderHiddenInput(),this.renderLabels(),this.renderSearchInput(),this.renderSearchSizer(),_||this.renderText(),ee.default.create(c),this.renderMenu())}}]),r}(Q.AutoControlledComponent);fe.propTypes={allowAdditions:Q.customPropTypes.every([Q.customPropTypes.demand(["options","selection","search"]),$.PropTypes.bool]),additionPosition:$.PropTypes.oneOf(de.props.additionPosition),additionLabel:$.PropTypes.oneOfType([$.PropTypes.element,$.PropTypes.string]),as:Q.customPropTypes.as,basic:$.PropTypes.bool,button:$.PropTypes.bool,children:Q.customPropTypes.every([Q.customPropTypes.disallow(["options","selection"]),Q.customPropTypes.givenProps({children:$.PropTypes.any.isRequired},X.default.PropTypes.element.isRequired)]),className:$.PropTypes.string,compact:$.PropTypes.bool,defaultOpen:$.PropTypes.bool,defaultSelectedLabel:Q.customPropTypes.every([Q.customPropTypes.demand(["multiple"]),$.PropTypes.oneOfType([$.PropTypes.string,$.PropTypes.number])]),defaultValue:$.PropTypes.oneOfType([$.PropTypes.string,$.PropTypes.number,$.PropTypes.arrayOf($.PropTypes.oneOfType([$.PropTypes.string,$.PropTypes.number]))]),disabled:$.PropTypes.bool,error:$.PropTypes.bool,floating:$.PropTypes.bool,fluid:$.PropTypes.bool,header:$.PropTypes.node,icon:$.PropTypes.oneOfType([$.PropTypes.node,$.PropTypes.object]),inline:$.PropTypes.bool,labeled:$.PropTypes.bool,loading:$.PropTypes.bool,multiple:$.PropTypes.bool,name:$.PropTypes.string,noResultsMessage:$.PropTypes.string,onAddItem:$.PropTypes.func,onBlur:$.PropTypes.func,onChange:$.PropTypes.func,onClose:$.PropTypes.func,onLabelClick:$.PropTypes.func,onOpen:$.PropTypes.func,onSearchChange:$.PropTypes.func,onClick:$.PropTypes.func,onFocus:$.PropTypes.func,onMouseDown:$.PropTypes.func,open:$.PropTypes.bool,options:Q.customPropTypes.every([Q.customPropTypes.disallow(["children"]),$.PropTypes.arrayOf($.PropTypes.shape(se.default.propTypes))]),placeholder:$.PropTypes.string,pointing:$.PropTypes.oneOfType([$.PropTypes.bool,$.PropTypes.oneOf(de.props.pointing)]),renderLabel:$.PropTypes.func,scrolling:$.PropTypes.bool,search:$.PropTypes.oneOfType([$.PropTypes.bool,$.PropTypes.func]),selectedLabel:Q.customPropTypes.every([Q.customPropTypes.demand(["multiple"]),$.PropTypes.oneOfType([$.PropTypes.string,$.PropTypes.number])]),selection:Q.customPropTypes.every([Q.customPropTypes.disallow(["children"]),Q.customPropTypes.demand(["options"]),$.PropTypes.bool]),selectOnBlur:$.PropTypes.bool,simple:$.PropTypes.bool,tabIndex:$.PropTypes.string,text:$.PropTypes.string,trigger:Q.customPropTypes.every([Q.customPropTypes.disallow(["selection","text"]),$.PropTypes.node]),value:$.PropTypes.oneOfType([$.PropTypes.string,$.PropTypes.number,$.PropTypes.arrayOf($.PropTypes.oneOfType([$.PropTypes.string,$.PropTypes.number]))])},fe.defaultProps={additionLabel:"Add ",additionPosition:"top",icon:"dropdown",noResultsMessage:"No results found.",renderLabel:function(e){var t=e.text;return t},selectOnBlur:!0,tabIndex:"0"},fe.autoControlledProps=["open","value","selectedLabel"],fe._meta=de,fe.Divider=oe.default,fe.Header=ue.default,fe.Item=se.default,fe.Menu=ce.default,t.default=fe}).call(t,r(/*! ./~/process/browser.js */35))},/*!************************************!*\ !*** ./src/modules/Embed/Embed.js ***! \************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var l=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},u=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),i=r(/*! classnames */3),c=n(i),p=r(/*! react */1),d=n(p),f=r(/*! ../../lib */2),y=r(/*! ../../elements/Icon */8),m=n(y),h={name:"Embed",type:f.META.TYPES.MODULE,props:{aspectRatio:["4:3","16:9","21:9"],source:["youtube","vimeo"]}},v=function(e){function t(){var e,r,n,s;o(this,t);for(var l=arguments.length,u=Array(l),i=0;i<l;i++)u[i]=arguments[i];return r=n=a(this,(e=t.__proto__||Object.getPrototypeOf(t)).call.apply(e,[this].concat(u))),n.state={},n.handleClick=function(e){var t=n.props.onClick,r=n.state.active;t&&t(e,n.props),r||n.trySetState({active:!0})},s=r,a(n,s)}return s(t,e),u(t,[{key:"getSrc",value:function(){var e=this.props,t=e.autoplay,r=void 0===t||t,n=e.brandedUI,o=void 0!==n&&n,a=e.color,s=void 0===a?"#444444":a,l=e.hd,u=void 0===l||l,i=e.id,c=e.source,p=e.url;return"youtube"===c?["//www.youtube.com/embed/"+i,"?autohide=true","&amp;autoplay="+r,"&amp;color="+encodeURIComponent(s),"&amp;hq="+u,"&amp;jsapi=false","&amp;modestbranding="+o].join(""):"vimeo"===c?["//player.vimeo.com/video/"+i,"?api=false","&amp;autoplay="+r,"&amp;byline=false","&amp;color="+encodeURIComponent(s),"&amp;portrait=false","&amp;title=false"].join(""):p}},{key:"render",value:function(){var e=this.props,r=e.aspectRatio,n=e.className,o=e.icon,a=e.placeholder,s=this.state.active,u=(0,c.default)("ui",r,(0,f.useKeyOnly)(s,"active"),"embed",n),i=(0,f.getUnhandledProps)(t,this.props),p=(0,f.getElementType)(t,this.props);return d.default.createElement(p,l({},i,{className:u,onClick:this.handleClick}),m.default.create(o),a&&d.default.createElement("img",{className:"placeholder",src:a}),this.renderEmbed())}},{key:"renderEmbed",value:function(){var e=this.props.children,t=this.state.active;return t?e?d.default.createElement("div",{className:"embed"},e):d.default.createElement("div",{className:"embed"},d.default.createElement("iframe",{allowFullScreen:"",frameBorder:"0",height:"100%",scrolling:"no",src:this.getSrc(),width:"100%"})):null}}]),t}(f.AutoControlledComponent);v.autoControlledProps=["active"],v.defaultProps={icon:"video play"},v._meta=h,v.propTypes={as:f.customPropTypes.as,active:p.PropTypes.bool,autoplay:f.customPropTypes.every([f.customPropTypes.demand(["source"]),p.PropTypes.bool]),aspectRatio:p.PropTypes.oneOf(h.props.aspectRatio),brandedUI:f.customPropTypes.every([f.customPropTypes.demand(["source"]),p.PropTypes.bool]),children:p.PropTypes.node,className:p.PropTypes.string,color:f.customPropTypes.every([f.customPropTypes.demand(["source"]),p.PropTypes.string]),defaultActive:p.PropTypes.bool,hd:f.customPropTypes.every([f.customPropTypes.demand(["source"]),p.PropTypes.bool]),id:f.customPropTypes.every([f.customPropTypes.demand(["source"]),p.PropTypes.string]),icon:f.customPropTypes.itemShorthand,onClick:p.PropTypes.func,placeholder:p.PropTypes.string,source:f.customPropTypes.every([f.customPropTypes.disallow(["sourceUrl"]),p.PropTypes.oneOf(h.props.source)]),url:f.customPropTypes.every([f.customPropTypes.disallow(["source"]),p.PropTypes.string])},t.default=v},/*!************************************!*\ !*** ./src/modules/Embed/index.js ***! \************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var o=r(/*! ./Embed */333),a=n(o);t.default=a.default},/*!************************************!*\ !*** ./src/modules/Modal/Modal.js ***! \************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var l=r(/*! lodash/pick */80),u=n(l),i=r(/*! lodash/omit */44),c=n(i),p=r(/*! lodash/keys */9),d=n(p),f=r(/*! lodash/isEqual */78),y=n(f),m=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},h=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),v=r(/*! react */1),b=n(v),g=r(/*! classnames */3),P=n(g),T=r(/*! ./ModalHeader */192),O=n(T),_=r(/*! ./ModalContent */190),E=n(_),j=r(/*! ./ModalActions */189),w=n(j),S=r(/*! ./ModalDescription */191),M=n(S),x=r(/*! ../../elements/Icon */8),k=n(x),A=r(/*! ../../addons/Portal */45),C=n(A),N=r(/*! ../../lib */2),I=(0,N.makeDebugger)("modal"),K={name:"Modal",type:N.META.TYPES.MODULE,props:{size:["fullscreen","large","small"],dimmer:["inverted","blurring"]}},L=function(e){function t(){var e,r,n,s;o(this,t);for(var l=arguments.length,u=Array(l),i=0;i<l;i++)u[i]=arguments[i];return r=n=a(this,(e=t.__proto__||Object.getPrototypeOf(t)).call.apply(e,[this].concat(u))),n.state={},n.handleClose=function(e){I("close()");var t=n.props.onClose;t&&t(e,n.props),n.trySetState({open:!1})},n.handleOpen=function(e){I("open()");var t=n.props.onOpen;t&&t(e,n.props),n.trySetState({open:!0})},n.handlePortalMount=function(e){I("handlePortalMount()");var t=n.props,r=t.dimmer,o=t.mountNode;r&&(I("adding dimmer"),o.classList.add("dimmable","dimmed"),"blurring"===r&&(I("adding blurred dimmer"),o.classList.add("blurring"))),n.setPosition();var a=n.props.onMount;a&&a(e,n.props)},n.handlePortalUnmount=function(e){I("handlePortalUnmount()");var t=n.props.mountNode;t.classList.remove("blurring","dimmable","dimmed","scrollable"),cancelAnimationFrame(n.animationRequestId);var r=n.props.onUnmount;r&&r(e,n.props)},n.setPosition=function(){if(n._modalNode){var e=n.props.mountNode,t=n._modalNode.getBoundingClientRect(),r=t.height,o=r>=window.innerHeight,a={marginTop:-Math.round(r/2),scrolling:o};!n.state.scrolling&&o?e.classList.add("scrolling"):n.state.scrolling&&!o&&e.classList.remove("scrolling"),(0,y.default)(a,n.state)||n.setState(a)}n.animationRequestId=requestAnimationFrame(n.setPosition)},s=r,a(n,s)}return s(t,e),h(t,[{key:"componentWillUnmount",value:function(){I("componentWillUnmount()"),this.handlePortalUnmount()}},{key:"render",value:function(){var e=this,r=this.state.open,n=this.props,o=n.basic,a=n.children,s=n.className,l=n.closeIcon,i=n.dimmer,p=n.mountNode,f=n.size;if(!N.isBrowser)return null;var y=this.state,h=y.marginTop,v=y.scrolling,g=(0,P.default)("ui",f,(0,N.useKeyOnly)(o,"basic"),(0,N.useKeyOnly)(v,"scrolling"),"modal transition visible active",s),T=(0,N.getUnhandledProps)(t,this.props),O=(0,d.default)(C.default.propTypes),_=(0,c.default)(T,O),E=(0,u.default)(T,O),j=(0,N.getElementType)(t,this.props),w=l===!0?"close":l,S=b.default.createElement(j,m({},_,{className:g,style:{marginTop:h},ref:function(t){return e._modalNode=t}}),k.default.create(w,{onClick:this.handleClose}),a),M=i?(0,P.default)("ui","inverted"===i&&"inverted","page modals dimmer transition visible active"):null;return b.default.createElement(C.default,m({closeOnRootNodeClick:!0,closeOnDocumentClick:!1},E,{className:M,mountNode:p,onClose:this.handleClose,onMount:this.handlePortalMount,onOpen:this.handleOpen,onUnmount:this.handlePortalUnmount,open:r}),S)}}]),t}(N.AutoControlledComponent);L.propTypes={as:N.customPropTypes.as,children:v.PropTypes.node,className:v.PropTypes.string,closeIcon:v.PropTypes.oneOfType([v.PropTypes.node,v.PropTypes.object,v.PropTypes.bool]),basic:v.PropTypes.bool,defaultOpen:v.PropTypes.bool,dimmer:v.PropTypes.oneOfType([v.PropTypes.bool,v.PropTypes.oneOf(K.props.dimmer)]),mountNode:v.PropTypes.any,onClose:v.PropTypes.func,onMount:v.PropTypes.func,onOpen:v.PropTypes.func,onUnmount:v.PropTypes.func,open:v.PropTypes.bool,size:v.PropTypes.oneOf(K.props.size)},L.defaultProps={dimmer:!0,mountNode:N.isBrowser?document.body:null},L.autoControlledProps=["open"],L._meta=K,L.Header=O.default,L.Content=E.default,L.Description=M.default,L.Actions=w.default,t.default=L},/*!************************************!*\ !*** ./src/modules/Popup/Popup.js ***! \************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var l=r(/*! lodash/pick */80),u=n(l),i=r(/*! lodash/omit */44),c=n(i),p=r(/*! lodash/keys */9),d=n(p),f=r(/*! lodash/assign */477),y=n(f),m=r(/*! lodash/mapValues */512),h=n(m),v=r(/*! lodash/isNumber */268),b=n(v),g=r(/*! lodash/includes */75),P=n(g),T=r(/*! lodash/without */7),O=n(T),_=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},E=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),j=r(/*! react */1),w=n(j),S=r(/*! classnames */3),M=n(S),x=r(/*! ../../lib */2),k=r(/*! ../../addons/Portal */45),A=n(k),C=r(/*! ./PopupContent */194),N=n(C),I=r(/*! ./PopupHeader */195),K=n(I),L=(0,x.makeDebugger)("popup"),U={name:"Popup",type:x.META.TYPES.MODULE,props:{content:[j.PropTypes.string,j.PropTypes.node],on:["hover","click","focus"],positioning:["top left","top right","bottom right","bottom left","right center","left center","top center","bottom center"],size:(0,O.default)(x.SUI.SIZES,"medium","big","massive"),wide:[!0,!1,"very"]}},D=function(e){function t(){var e,r,n,s;o(this,t);for(var l=arguments.length,u=Array(l),i=0;i<l;i++)u[i]=arguments[i];return r=n=a(this,(e=t.__proto__||Object.getPrototypeOf(t)).call.apply(e,[this].concat(u))),n.state={},n.hideOnScroll=function(e){n.setState({closed:!0}),window.removeEventListener("scroll",n.hideOnScroll),setTimeout(function(){return n.setState({closed:!1})},50)},n.handleClose=function(e){L("handleClose()");var t=n.props.onClose;t&&t(e,n.props)},n.handleOpen=function(e){L("handleOpen()"),n.coords=e.currentTarget.getBoundingClientRect();var t=n.props.onOpen;t&&t(e,n.props)},n.handlePortalMount=function(e){L("handlePortalMount()"),n.props.hideOnScroll&&window.addEventListener("scroll",n.hideOnScroll);var t=n.props.onMount;t&&t(e,n.props)},n.handlePortalUnmount=function(e){L("handlePortalUnmount()");var t=n.props.onUnmount;t&&t(e,n.props)},n.popupMounted=function(e){L("popupMounted()"),n.popupCoords=e?e.getBoundingClientRect():null,n.setPopupStyle()},s=r,a(n,s)}return s(t,e),E(t,[{key:"computePopupStyle",value:function(e){var t={position:"absolute"};if(!x.isBrowser)return t;var r=this.props.offset,n=window,o=n.pageYOffset,a=n.pageXOffset,s=document.documentElement,l=s.clientWidth,u=s.clientHeight;if((0,P.default)(e,"right"))t.right=Math.round(l-(this.coords.right+a)),t.left="auto";else if((0,P.default)(e,"left"))t.left=Math.round(this.coords.left+a),t.right="auto";else{var i=(this.coords.width-this.popupCoords.width)/2;t.left=Math.round(this.coords.left+i+a),t.right="auto"}if((0,P.default)(e,"top"))t.bottom=Math.round(u-(this.coords.top+o)),t.top="auto";else if((0,P.default)(e,"bottom"))t.top=Math.round(this.coords.bottom+o),t.bottom="auto";else{var c=(this.coords.height+this.popupCoords.height)/2;t.top=Math.round(this.coords.bottom+o-c),t.bottom="auto";var p=this.popupCoords.width+8;(0,P.default)(e,"right")?t.right-=p:t.left-=p}return r&&((0,b.default)(t.right)?t.right-=r:t.left-=r),t}},{key:"isStyleInViewport",value:function(e){var t=window,r=t.pageYOffset,n=t.pageXOffset,o=document.documentElement,a=o.clientWidth,s=o.clientHeight,l={top:e.top,left:e.left,width:this.popupCoords.width,height:this.popupCoords.height};return(0,b.default)(e.right)&&(l.left=a-e.right-l.width),(0,b.default)(e.bottom)&&(l.top=s-e.bottom-l.height),!(l.top<r)&&(!(l.top+l.height>r+s)&&(!(l.left<n)&&!(l.left+l.width>n+a)))}},{key:"setPopupStyle",value:function(){if(this.coords&&this.popupCoords){for(var e=this.props.positioning,t=this.computePopupStyle(e),r=(0,O.default)(U.props.positioning,e),n=0;!this.isStyleInViewport(t)&&n<r.length;n++)t=this.computePopupStyle(r[n]),e=r[n];t=(0,h.default)(t,function(e){return(0,b.default)(e)?e+"px":e}),this.setState({style:t,positioning:e})}}},{key:"getPortalProps",value:function(){var e={},t=this.props,r=t.on,n=t.hoverable;return n&&(e.closeOnPortalMouseLeave=!0,e.mouseLeaveDelay=300),"click"===r?(e.openOnTriggerClick=!0,e.closeOnTriggerClick=!0,e.closeOnDocumentClick=!0):"focus"===r?(e.openOnTriggerFocus=!0,e.closeOnTriggerBlur=!0):"hover"===r&&(e.openOnTriggerMouseOver=!0,e.closeOnTriggerMouseLeave=!0,e.mouseLeaveDelay=70,e.mouseOverDelay=50),e}},{key:"render",value:function(){var e=this.props,r=e.basic,n=e.children,o=e.className,a=e.content,s=e.flowing,l=e.header,i=e.inverted,p=e.size,f=e.trigger,m=e.wide,h=this.state,v=h.positioning,b=h.closed,g=(0,y.default)({},this.state.style,this.props.style),P=(0,M.default)("ui",v,p,(0,x.useKeyOrValueAndKey)(m,"wide"),(0,x.useKeyOnly)(r,"basic"),(0,x.useKeyOnly)(s,"flowing"),(0,x.useKeyOnly)(i,"inverted"),"popup transition visible",o);if(b)return f;var T=(0,x.getUnhandledProps)(t,this.props),O=(0,d.default)(A.default.propTypes),E=(0,c.default)(T,O),j=(0,u.default)(T,O),S=(0,x.getElementType)(t,this.props),k=w.default.createElement(S,_({},E,{className:P,style:g,ref:this.popupMounted}),n,!n&&K.default.create(l),!n&&N.default.create(a)),C=_({},this.getPortalProps(),j);return L("portal props:",C),w.default.createElement(A.default,_({},C,{trigger:f,onClose:this.handleClose,onMount:this.handlePortalMount,onOpen:this.handleOpen,onUnmount:this.handlePortalUnmount}),k)}}]),t}(j.Component);D.propTypes={basic:j.PropTypes.bool,children:j.PropTypes.node,className:j.PropTypes.string,content:j.PropTypes.oneOfType(U.props.content),flowing:j.PropTypes.bool,header:j.PropTypes.string,hoverable:j.PropTypes.bool,inverted:j.PropTypes.bool,hideOnScroll:j.PropTypes.bool,offset:j.PropTypes.number,on:j.PropTypes.oneOf(U.props.on),onClose:j.PropTypes.func,onMount:j.PropTypes.func,onOpen:j.PropTypes.func,onUnmount:j.PropTypes.func,positioning:j.PropTypes.oneOf(U.props.positioning),size:j.PropTypes.oneOf(U.props.size),style:j.PropTypes.object,trigger:j.PropTypes.node,wide:j.PropTypes.oneOf(U.props.wide)},D.defaultProps={positioning:"top left",on:"hover"},D._meta=U,D.Content=N.default,D.Header=K.default,t.default=D},/*!************************************!*\ !*** ./src/modules/Popup/index.js ***! \************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var o=r(/*! ./Popup */336),a=n(o);t.default=a.default},/*!******************************************!*\ !*** ./src/modules/Progress/Progress.js ***! \******************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.active,r=e.attached,n=e.autoSuccess,a=e.color,s=e.children,l=e.className,i=e.disabled,p=e.error,f=e.indicating,h=e.inverted,b=e.label,T=e.percent,O=e.precision,_=e.progress,E=e.size,j=e.success,w=e.total,S=e.value,M=e.warning,x=n&&(T>=100||S>=w),k=_||b||!(0,y.default)(O)||!(0,d.default)([w,S],y.default),A=void 0;(0,y.default)(T)?(0,y.default)(w)||(0,y.default)(S)||(A=S/w*100):A=T,A=(0,c.default)(A,0,100),(0,y.default)(O)||(A=(0,u.default)(A,O));var C=void 0;"percent"===b||b===!0||(0,y.default)(b)?C=A+"%":"ratio"===b&&(C=S+"/"+w);var N=(0,v.default)("ui",E,a,(0,P.useKeyOnly)(t||f,"active"),(0,P.useKeyOnly)(x||j,"success"),(0,P.useKeyOnly)(M,"warning"),(0,P.useKeyOnly)(p,"error"),(0,P.useKeyOnly)(i,"disabled"),(0,P.useKeyOnly)(f,"indicating"),(0,P.useKeyOnly)(h,"inverted"),(0,P.useValueAndKey)(r,"attached"),l,"progress"),I=(0,P.getUnhandledProps)(o,e),K=(0,P.getElementType)(o,e);return g.default.createElement(K,m({},I,{className:N}),g.default.createElement("div",{className:"bar",style:{width:A+"%"}},k&&g.default.createElement("div",{className:"progress"},C)),s&&g.default.createElement("div",{className:"label"},s))}Object.defineProperty(t,"__esModule",{value:!0});var a=r(/*! lodash/without */7),s=n(a),l=r(/*! lodash/round */519),u=n(l),i=r(/*! lodash/clamp */478),c=n(i),p=r(/*! lodash/every */261),d=n(p),f=r(/*! lodash/isUndefined */133),y=n(f),m=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},h=r(/*! classnames */3),v=n(h),b=r(/*! react */1),g=n(b),P=r(/*! ../../lib */2);o._meta={name:"Progress",type:P.META.TYPES.MODULE,props:{attached:["top","bottom"],color:P.SUI.COLORS,label:["ratio","percent"],size:(0,s.default)(P.SUI.SIZES,"mini","huge","massive")}},o.propTypes={as:P.customPropTypes.as,active:b.PropTypes.bool,attached:b.PropTypes.oneOf(o._meta.props.attached),autoSuccess:b.PropTypes.bool,color:b.PropTypes.oneOf(o._meta.props.color),children:b.PropTypes.node,className:b.PropTypes.string,disabled:b.PropTypes.bool,error:b.PropTypes.bool,indicating:b.PropTypes.bool,inverted:b.PropTypes.bool,label:P.customPropTypes.every([P.customPropTypes.some([P.customPropTypes.demand(["percent"]),P.customPropTypes.demand(["total","value"])]),b.PropTypes.oneOfType([b.PropTypes.bool,b.PropTypes.oneOf(o._meta.props.label)])]),percent:P.customPropTypes.every([P.customPropTypes.disallow(["total","value"]),b.PropTypes.oneOfType([b.PropTypes.string,b.PropTypes.number])]),progress:b.PropTypes.bool,precision:b.PropTypes.number,size:b.PropTypes.oneOf(o._meta.props.size),success:b.PropTypes.bool,total:P.customPropTypes.every([P.customPropTypes.demand(["value"]),P.customPropTypes.disallow(["percent"]),b.PropTypes.oneOfType([b.PropTypes.string,b.PropTypes.number])]),value:P.customPropTypes.every([P.customPropTypes.demand(["total"]),P.customPropTypes.disallow(["percent"]),b.PropTypes.oneOfType([b.PropTypes.string,b.PropTypes.number])]),warning:b.PropTypes.bool},t.default=o},/*!***************************************!*\ !*** ./src/modules/Progress/index.js ***! \***************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var o=r(/*! ./Progress */338),a=n(o);t.default=a.default},/*!**************************************!*\ !*** ./src/modules/Rating/Rating.js ***! \**************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var l=r(/*! lodash/times */277),u=n(l),i=r(/*! lodash/invoke */266),c=n(i),p=r(/*! lodash/without */7),d=n(p),f=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},y=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),m=r(/*! classnames */3),h=n(m),v=r(/*! react */1),b=n(v),g=r(/*! ../../lib */2),P=r(/*! ./RatingIcon */341),T=n(P),O={name:"Rating",type:g.META.TYPES.MODULE,props:{clearable:["auto"],icon:["star","heart"],size:(0,d.default)(g.SUI.SIZES,"medium","big")}},_=function(e){function t(){var e,r,n,s;o(this,t);for(var l=arguments.length,u=Array(l),i=0;i<l;i++)u[i]=arguments[i];return r=n=a(this,(e=t.__proto__||Object.getPrototypeOf(t)).call.apply(e,[this].concat(u))),E.call(n),s=r,a(n,s)}return s(t,e),y(t,[{key:"render",value:function(){var e=this,r=this.props,n=r.className,o=r.disabled,a=r.icon,s=r.maxRating,l=r.size,i=this.state,c=i.rating,p=i.selectedIndex,d=i.isSelecting,y=(0,h.default)("ui",a,l,(0,g.useKeyOnly)(o,"disabled"),(0,g.useKeyOnly)(d&&!o&&p>=0,"selected"),"rating",n),m=(0,g.getUnhandledProps)(t,this.props),v=(0,g.getElementType)(t,this.props);return b.default.createElement(v,f({},m,{className:y,role:"radiogroup",onMouseLeave:this.handleMouseLeave}),(0,u.default)(s,function(t){return b.default.createElement(T.default,{active:c>=t+1,index:t,key:t,"aria-checked":c===t+1,"aria-posinset":t+1,"aria-setsize":s,onClick:e.handleIconClick,onMouseEnter:e.handleIconMouseEnter,selected:p>=t&&d})}))}}]),t}(g.AutoControlledComponent);_.autoControlledProps=["rating"],_.defaultProps={clearable:"auto",maxRating:1},_.propTypes={as:g.customPropTypes.as,className:v.PropTypes.string,clearable:v.PropTypes.oneOfType([v.PropTypes.oneOf(O.props.clearable),v.PropTypes.bool]),defaultRating:v.PropTypes.oneOfType([v.PropTypes.string,v.PropTypes.number]),disabled:v.PropTypes.bool,icon:v.PropTypes.oneOf(O.props.icon),maxRating:v.PropTypes.oneOfType([v.PropTypes.string,v.PropTypes.number]),onRate:v.PropTypes.func,rating:v.PropTypes.oneOfType([v.PropTypes.string,v.PropTypes.number]),size:v.PropTypes.oneOf(O.props.size)},_._meta=O;var E=function(){var e=this;this.handleIconClick=function(t,r){var n=e.props,o=n.clearable,a=n.disabled,s=n.maxRating,l=n.onRate,u=e.state.rating;if(!a){var i=r+1;"auto"===o&&1===s?i=+!u:o===!0&&i===u&&(i=0),e.trySetState({rating:i},{isSelecting:!1}),l&&l(t,{rating:i,maxRating:s})}},this.handleIconMouseEnter=function(t){e.props.disabled||e.setState({selectedIndex:t,isSelecting:!0})},this.handleMouseLeave=function(){for(var t=arguments.length,r=Array(t),n=0;n<t;n++)r[n]=arguments[n];c.default.apply(void 0,[e.props,"onMouseLeave"].concat(r)),e.props.disabled||e.setState({selectedIndex:-1,isSelecting:!1})}};t.default=_},/*!******************************************!*\ !*** ./src/modules/Rating/RatingIcon.js ***! \******************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var l=r(/*! lodash/keys */9),u=n(l),i=r(/*! lodash/omit */44),c=n(i),p=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},d=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),f=r(/*! classnames */3),y=n(f),m=r(/*! react */1),h=n(m),v=r(/*! ../../lib */2),b=function(e){function t(){var e,r,n,s;o(this,t);for(var l=arguments.length,u=Array(l),i=0;i<l;i++)u[i]=arguments[i];return r=n=a(this,(e=t.__proto__||Object.getPrototypeOf(t)).call.apply(e,[this].concat(u))),n.handleClick=function(e){var t=n.props,r=t.onClick,o=t.index;r&&r(e,o)},n.handleKeyUp=function(e){var t=n.props,r=t.onClick,o=t.index;if(r)switch(v.keyboardKey.getCode(e)){case v.keyboardKey.Enter:case v.keyboardKey.Spacebar:e.preventDefault(),r(e,o);break;default:return}},n.handleMouseEnter=function(){var e=n.props,t=e.onMouseEnter,r=e.index;t&&t(r)},s=r,a(n,s)}return s(t,e),d(t,[{key:"render",value:function(){var e=this.props,r=e.active,n=e.selected,o=(0,y.default)((0,v.useKeyOnly)(r,"active"),(0,v.useKeyOnly)(n,"selected"),"icon"),a=(0,c.default)(this.props,(0,u.default)(t.propTypes));return h.default.createElement("i",p({role:"radio",tabIndex:0},a,{className:o,onKeyUp:this.handleKeyUp,onClick:this.handleClick,onMouseEnter:this.handleMouseEnter}))}}]),t}(m.Component);b.propTypes={active:m.PropTypes.bool,index:m.PropTypes.number,onClick:m.PropTypes.func,onMouseEnter:m.PropTypes.func,selected:m.PropTypes.bool},b._meta={name:"RatingIcon",parent:"Rating",type:v.META.TYPES.MODULE},t.default=b},/*!*************************************!*\ !*** ./src/modules/Rating/index.js ***! \*************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var o=r(/*! ./Rating */340),a=n(o);t.default=a.default},/*!**************************************!*\ !*** ./src/modules/Search/Search.js ***! \**************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){var r={};for(var n in e)t.indexOf(n)>=0||Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=e[n]);return r}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function l(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var u=r(/*! lodash/isEmpty */130),i=n(u),c=r(/*! lodash/partialRight */516),p=n(c),d=r(/*! lodash/inRange */509),f=n(d),y=r(/*! lodash/map */10),m=n(y),h=r(/*! lodash/get */34),v=n(h),b=r(/*! lodash/reduce */273),g=n(b),P=r(/*! lodash/isEqual */78),T=n(P),O=r(/*! lodash/without */7),_=n(O),E=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},j=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),w=function e(t,r,n){null===t&&(t=Function.prototype);var o=Object.getOwnPropertyDescriptor(t,r);if(void 0===o){var a=Object.getPrototypeOf(t);return null===a?void 0:e(a,r,n)}if("value"in o)return o.value;var s=o.get;if(void 0!==s)return s.call(n)},S=r(/*! classnames */3),M=n(S),x=r(/*! react */1),k=n(x),A=r(/*! ../../lib */2),C=r(/*! ../../elements/Input */86),N=n(C),I=r(/*! ./SearchCategory */196),K=n(I),L=r(/*! ./SearchResult */197),U=n(L),D=r(/*! ./SearchResults */198),R=n(D),z=(0,A.makeDebugger)("search"),W={name:"Search",type:A.META.TYPES.MODULE,props:{size:(0,_.default)(A.SUI.SIZES,"medium")}},F=function(e){function t(){var e,r,n,l;a(this,t);for(var u=arguments.length,c=Array(u),d=0;d<u;d++)c[d]=arguments[d];return r=n=s(this,(e=t.__proto__||Object.getPrototypeOf(t)).call.apply(e,[this].concat(c))),n.handleChange=function(e,t){z("handleChange()"),z(t);var r=n.props.onChange;r&&r(e,t)},n.closeOnEscape=function(e){A.keyboardKey.getCode(e)===A.keyboardKey.Escape&&(e.preventDefault(),n.close())},n.moveSelectionOnKeyDown=function(e){switch(z("moveSelectionOnKeyDown()"),z(A.keyboardKey.getName(e)),A.keyboardKey.getCode(e)){case A.keyboardKey.ArrowDown:e.preventDefault(),n.moveSelectionBy(1);break;case A.keyboardKey.ArrowUp:e.preventDefault(),n.moveSelectionBy(-1)}},n.selectItemOnEnter=function(e){if(z("selectItemOnEnter()"),z(A.keyboardKey.getName(e)),A.keyboardKey.getCode(e)===A.keyboardKey.Enter){e.preventDefault();var t=n.getSelectedResult();t&&(n.setValue(t.title),n.handleChange(e,t),n.close())}},n.closeOnDocumentClick=function(e){z("closeOnDocumentClick()"),z(e),n.close()},n.handleMouseDown=function(e){z("handleMouseDown()");var t=n.props.onMouseDown;t&&t(e),n.isMouseDown=!0,A.isBrowser&&document.addEventListener("mouseup",n.handleDocumentMouseUp)},n.handleDocumentMouseUp=function(){z("handleDocumentMouseUp()"),n.isMouseDown=!1,A.isBrowser&&document.removeEventListener("mouseup",n.handleDocumentMouseUp)},n.handleInputClick=function(e){z("handleInputClick()",e),e.nativeEvent.stopImmediatePropagation(),n.tryOpen()},n.handleItemClick=function(e,t){z("handleItemClick()"),z(t);var r=n.getSelectedResult(t);e.nativeEvent.stopImmediatePropagation(),n.setValue(r.title),n.handleChange(e,r),n.close()},n.handleFocus=function(e){z("handleFocus()");var t=n.props.onFocus;t&&t(e),n.setState({focus:!0})},n.handleBlur=function(e){z("handleBlur()");var t=n.props.onBlur;t&&t(e),n.setState({focus:!1})},n.handleSearchChange=function(e){z("handleSearchChange()"),z(e.target.value),e.stopPropagation();var t=n.props,r=t.onSearchChange,o=t.minCharacters,a=n.state.open,s=e.target.value;r&&r(e,s),s.length<o?n.close():a||n.tryOpen(s),n.setValue(s)},n.getFlattenedResults=function(){var e=n.props,t=e.category,r=e.results;return t?(0,g.default)(r,function(e,t){return e.concat(t.results)},[]):r},n.getSelectedResult=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:n.state.selectedIndex,t=n.getFlattenedResults();return(0,v.default)(t,e)},n.setValue=function(e){z("setValue()"),z("value",e);var t=n.props.selectFirstResult;n.trySetState({value:e},{selectedIndex:t?0:-1})},n.moveSelectionBy=function(e){z("moveSelectionBy()"),z("offset: "+e);var t=n.state.selectedIndex,r=n.getFlattenedResults(),o=r.length-1,a=t+e;a>o?a=0:a<0&&(a=o),n.setState({selectedIndex:a}),n.scrollSelectedItemIntoView()},n.scrollSelectedItemIntoView=function(){if(z("scrollSelectedItemIntoView()"),A.isBrowser){var e=document.querySelector(".ui.search.active.visible .results.visible"),t=e.querySelector(".result.active");z("menu (results): "+e),z("item (result): "+t);var r=t.offsetTop<e.scrollTop,n=t.offsetTop+t.clientHeight>e.scrollTop+e.clientHeight;r?e.scrollTop=t.offsetTop:n&&(e.scrollTop=t.offsetTop+t.clientHeight-e.clientHeight)}},n.tryOpen=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:n.state.value;z("open()");var t=n.props.minCharacters;e.length<t||n.open()},n.open=function(){z("open()"),n.trySetState({open:!0})},n.close=function(){z("close()"),n.trySetState({open:!1})},n.renderSearchInput=function(){var e=n.props,t=e.icon,r=e.placeholder,o=n.state.value;return k.default.createElement(N.default,{value:o,placeholder:r,onBlur:n.handleBlur,onChange:n.handleSearchChange,onFocus:n.handleFocus,onClick:n.handleInputClick,input:{className:"prompt",tabIndex:"0",autoComplete:"off"},icon:t})},n.renderNoResults=function(){var e=n.props,t=e.noResultsMessage,r=e.noResultsDescription;return k.default.createElement("div",{className:"message empty"},k.default.createElement("div",{className:"header"},t),r&&k.default.createElement("div",{className:"description"},r))},n.renderResult=function(e,t,r){var a=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,s=e.childKey,l=o(e,["childKey"]),u=n.props.resultRenderer,i=n.state.selectedIndex,c=t+a;return k.default.createElement(U.default,E({key:s||l.title,active:i===c,onClick:n.handleItemClick,onMouseDown:function(e){return e.preventDefault()},renderer:u},l,{id:c}))},n.renderResults=function(){var e=n.props.results;return(0,m.default)(e,n.renderResult)},n.renderCategories=function(){var e=n.props,t=e.categoryRenderer,r=e.results,a=n.state.selectedIndex,s=0;return(0,m.default)(r,function(e,r,l){var u=e.childKey,i=o(e,["childKey"]),c=E({key:u||i.name,active:(0,f.default)(a,s,s+i.results.length),renderer:t},i),d=(0,p.default)(n.renderResult,s);return s+=i.results.length,k.default.createElement(K.default,c,i.results.map(d))})},n.renderMenuContent=function(){var e=n.props,t=e.category,r=e.showNoResults,o=e.results;return(0,i.default)(o)?r?n.renderNoResults():null:t?n.renderCategories():n.renderResults()},n.renderResultsMenu=function(){var e=n.state.open,t=e?"visible":"",r=n.renderMenuContent();if(r)return k.default.createElement(R.default,{className:t},r)},l=r,s(n,l)}return l(t,e),j(t,[{key:"componentWillMount",value:function(){w(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"componentWillMount",this)&&w(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"componentWillMount",this).call(this),z("componentWillMount()");var e=this.state,r=e.open,n=e.value;this.setValue(n),r&&this.open()}},{key:"shouldComponentUpdate",value:function(e,t){return!(0,T.default)(e,this.props)||!(0,T.default)(t,this.state)}},{key:"componentWillReceiveProps",value:function(e){w(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"componentWillReceiveProps",this).call(this,e),z("componentWillReceiveProps()"),z("changed props:",(0,A.objectDiff)(e,this.props)),(0,T.default)(e.value,this.props.value)||(z("value changed, setting",e.value),this.setValue(e.value))}},{key:"componentDidUpdate",value:function(e,t){z("componentDidUpdate()"),z("to state:",(0,A.objectDiff)(t,this.state)),A.isBrowser&&(!t.focus&&this.state.focus?(z("search focused"),this.isMouseDown||(z("mouse is not down, opening"),this.tryOpen()),this.state.open&&(document.addEventListener("keydown",this.moveSelectionOnKeyDown),document.addEventListener("keydown",this.selectItemOnEnter))):t.focus&&!this.state.focus&&(z("search blurred"),this.isMouseDown||(z("mouse is not down, closing"),this.close()),document.removeEventListener("keydown",this.moveSelectionOnKeyDown),document.removeEventListener("keydown",this.selectItemOnEnter)),!t.open&&this.state.open?(z("search opened"),this.open(),document.addEventListener("keydown",this.closeOnEscape),document.addEventListener("keydown",this.moveSelectionOnKeyDown),document.addEventListener("keydown",this.selectItemOnEnter),document.addEventListener("click",this.closeOnDocumentClick)):t.open&&!this.state.open&&(z("search closed"),this.close(),document.removeEventListener("keydown",this.closeOnEscape),document.removeEventListener("keydown",this.moveSelectionOnKeyDown),document.removeEventListener("keydown",this.selectItemOnEnter),document.removeEventListener("click",this.closeOnDocumentClick)))}},{key:"componentWillUnmount",value:function(){z("componentWillUnmount()"),A.isBrowser&&(document.removeEventListener("keydown",this.moveSelectionOnKeyDown),document.removeEventListener("keydown",this.selectItemOnEnter),document.removeEventListener("keydown",this.closeOnEscape),document.removeEventListener("click",this.closeOnDocumentClick))}},{key:"render",value:function(){z("render()"),z("props",this.props),z("state",this.state);var e=this.state,r=e.searchClasses,n=e.focus,o=e.open,a=this.props,s=a.aligned,l=a.category,u=a.className,i=a.fluid,c=a.loading,p=a.size,d=(0,M.default)("ui",o&&"active visible",p,r,(0,A.useKeyOnly)(c,"loading"),(0,A.useValueAndKey)(s,"aligned"),(0,A.useKeyOnly)(l,"category"),(0,A.useKeyOnly)(n,"focus"),(0,A.useKeyOnly)(i,"fluid"),u,"search"),f=(0,A.getUnhandledProps)(t,this.props),y=(0,A.getElementType)(t,this.props);return k.default.createElement(y,E({},f,{className:d,onBlur:this.handleBlur,onFocus:this.handleFocus,onChange:this.handleChange,onMouseDown:this.handleMouseDown}),this.renderSearchInput(),this.renderResultsMenu())}}]),t}(A.AutoControlledComponent);F.propTypes={as:A.customPropTypes.as,icon:x.PropTypes.oneOfType([x.PropTypes.node,x.PropTypes.object]),results:x.PropTypes.oneOfType([x.PropTypes.arrayOf(x.PropTypes.shape(U.default.propTypes)),x.PropTypes.object]),open:x.PropTypes.bool,defaultOpen:x.PropTypes.bool,value:x.PropTypes.string,defaultValue:x.PropTypes.string,placeholder:x.PropTypes.string,minCharacters:x.PropTypes.number,noResultsMessage:x.PropTypes.string,noResultsDescription:x.PropTypes.string,selectFirstResult:x.PropTypes.bool,showNoResults:x.PropTypes.bool,categoryRenderer:x.PropTypes.func,resultRenderer:x.PropTypes.func,onBlur:x.PropTypes.func,onChange:x.PropTypes.func,onSearchChange:x.PropTypes.func,onFocus:x.PropTypes.func,onMouseDown:x.PropTypes.func,aligned:x.PropTypes.string,category:x.PropTypes.bool,className:x.PropTypes.string,fluid:x.PropTypes.bool,size:x.PropTypes.oneOf(W.props.size),loading:x.PropTypes.bool},F.defaultProps={icon:"search",minCharacters:1,noResultsMessage:"No results found.",showNoResults:!0},F.autoControlledProps=["open","value"],F._meta=W,F.Result=U.default,F.Results=R.default,F.Category=K.default,t.default=F},/*!*************************************!*\ !*** ./src/modules/Search/index.js ***! \*************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var o=r(/*! ./Search */343),a=n(o);t.default=a.default},/*!**************************************!*\ !*** ./src/views/Comment/Comment.js ***! \**************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.className,r=e.children,n=e.collapsed,s=(0,l.default)((0,c.useKeyOnly)(n,"collapsed"),"comment",t),u=(0,c.getUnhandledProps)(o,e),p=(0,c.getElementType)(o,e);return i.default.createElement(p,a({},u,{className:s}),r)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(/*! classnames */3),l=n(s),u=r(/*! react */1),i=n(u),c=r(/*! ../../lib */2),p=r(/*! ./CommentAction */202),d=n(p),f=r(/*! ./CommentActions */203),y=n(f),m=r(/*! ./CommentAuthor */204),h=n(m),v=r(/*! ./CommentAvatar */205),b=n(v),g=r(/*! ./CommentContent */206),P=n(g),T=r(/*! ./CommentGroup */207),O=n(T),_=r(/*! ./CommentMetadata */208),E=n(_),j=r(/*! ./CommentText */209),w=n(j);o._meta={name:"Comment",type:c.META.TYPES.VIEW},o.propTypes={as:c.customPropTypes.as,children:u.PropTypes.node,className:u.PropTypes.string,collapsed:u.PropTypes.bool},o.Author=h.default,o.Action=d.default,o.Actions=y.default,o.Avatar=b.default,o.Content=P.default,o.Group=O.default,o.Metadata=E.default,o.Text=w.default,t.default=o},/*!************************************!*\ !*** ./src/views/Comment/index.js ***! \************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var o=r(/*! ./Comment */345),a=n(o);t.default=a.default},/*!********************************!*\ !*** ./src/views/Feed/Feed.js ***! \********************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){var r={};for(var n in e)t.indexOf(n)>=0||Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=e[n]);return r}function a(e){var t=e.children,r=e.className,n=e.events,s=e.size,l=(0,d.default)("ui",r,s,"feed"),u=(0,m.getUnhandledProps)(a,e),p=(0,m.getElementType)(a,e);if(t)return y.default.createElement(p,c({},u,{className:l}),t);var f=(0,i.default)(n,function(e){var t=e.childKey,r=e.date,n=e.meta,a=e.summary,s=o(e,["childKey","date","meta","summary"]),l=t||[r,n,a].join("-");return y.default.createElement(T.default,c({date:r,key:l,meta:n,summary:a},s))});return y.default.createElement(p,c({},u,{className:l}),f)}Object.defineProperty(t,"__esModule",{value:!0});var s=r(/*! lodash/without */7),l=n(s),u=r(/*! lodash/map */10),i=n(u),c=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},p=r(/*! classnames */3),d=n(p),f=r(/*! react */1),y=n(f),m=r(/*! ../../lib */2),h=r(/*! ./FeedContent */97),v=n(h),b=r(/*! ./FeedDate */52),g=n(b),P=r(/*! ./FeedEvent */210),T=n(P),O=r(/*! ./FeedExtra */98),_=n(O),E=r(/*! ./FeedLabel */99),j=n(E),w=r(/*! ./FeedLike */100),S=n(w),M=r(/*! ./FeedMeta */101),x=n(M),k=r(/*! ./FeedSummary */102),A=n(k),C=r(/*! ./FeedUser */103),N=n(C);a._meta={name:"Feed",type:m.META.TYPES.VIEW,props:{size:(0,l.default)(m.SUI.SIZES,"mini","tiny","medium","big","huge","massive")}},a.propTypes={as:m.customPropTypes.as,children:f.PropTypes.node,className:f.PropTypes.string,events:m.customPropTypes.collectionShorthand,size:f.PropTypes.oneOf(a._meta.props.size)},a.Content=v.default,a.Date=g.default,a.Event=T.default,a.Extra=_.default,a.Label=j.default,a.Like=S.default,a.Meta=x.default,a.Summary=A.default,a.User=N.default,t.default=a},/*!*********************************!*\ !*** ./src/views/Feed/index.js ***! \*********************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var o=r(/*! ./Feed */347),a=n(o);t.default=a.default},/*!*********************************!*\ !*** ./src/views/Item/index.js ***! \*********************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var o=r(/*! ./Item */211),a=n(o);t.default=a.default},/*!**************************************!*\ !*** ./src/views/Statistic/index.js ***! \**************************************/ function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var o=r(/*! ./Statistic */215),a=n(o);t.default=a.default},/*!****************************!*\ !*** ./~/debug/browser.js ***! \****************************/ function(e,t,r){(function(n){function o(){return"undefined"!=typeof document&&"WebkitAppearance"in document.documentElement.style||window.console&&(console.firebug||console.exception&&console.table)||navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31}function a(){var e=arguments,r=this.useColors;if(e[0]=(r?"%c":"")+this.namespace+(r?" %c":" ")+e[0]+(r?"%c ":" ")+"+"+t.humanize(this.diff),!r)return e;var n="color: "+this.color;e=[e[0],n,"color: inherit"].concat(Array.prototype.slice.call(e,1));var o=0,a=0;return e[0].replace(/%[a-z%]/g,function(e){"%%"!==e&&(o++,"%c"===e&&(a=o))}),e.splice(a,0,n),e}function s(){return"object"==typeof console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}function l(e){try{null==e?t.storage.removeItem("debug"):t.storage.debug=e}catch(e){}}function u(){try{return t.storage.debug}catch(e){}if("undefined"!=typeof n&&"env"in n)return n.env.DEBUG}function i(){try{return window.localStorage}catch(e){}}t=e.exports=r(/*! ./debug */352),t.log=s,t.formatArgs=a,t.save=l,t.load=u,t.useColors=o,t.storage="undefined"!=typeof chrome&&"undefined"!=typeof chrome.storage?chrome.storage.local:i(),t.colors=["lightseagreen","forestgreen","goldenrod","dodgerblue","darkorchid","crimson"],t.formatters.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}},t.enable(u())}).call(t,r(/*! ./~/process/browser.js */35))},/*!**************************!*\ !*** ./~/debug/debug.js ***! \**************************/ function(e,t,r){function n(){return t.colors[c++%t.colors.length]}function o(e){function r(){}function o(){var e=o,r=+new Date,a=r-(i||r);e.diff=a,e.prev=i,e.curr=r,i=r,null==e.useColors&&(e.useColors=t.useColors()),null==e.color&&e.useColors&&(e.color=n());for(var s=new Array(arguments.length),l=0;l<s.length;l++)s[l]=arguments[l];s[0]=t.coerce(s[0]),"string"!=typeof s[0]&&(s=["%o"].concat(s));var u=0;s[0]=s[0].replace(/%([a-z%])/g,function(r,n){if("%%"===r)return r;u++;var o=t.formatters[n];if("function"==typeof o){var a=s[u];r=o.call(e,a),s.splice(u,1),u--}return r}),s=t.formatArgs.apply(e,s);var c=o.log||t.log||console.log.bind(console);c.apply(e,s)}r.enabled=!1,o.enabled=!0;var a=t.enabled(e)?o:r;return a.namespace=e,a}function a(e){t.save(e);for(var r=(e||"").split(/[\s,]+/),n=r.length,o=0;o<n;o++)r[o]&&(e=r[o].replace(/[\\^$+?.()|[\]{}]/g,"\\$&").replace(/\*/g,".*?"),"-"===e[0]?t.skips.push(new RegExp("^"+e.substr(1)+"$")):t.names.push(new RegExp("^"+e+"$")))}function s(){t.enable("")}function l(e){var r,n;for(r=0,n=t.skips.length;r<n;r++)if(t.skips[r].test(e))return!1;for(r=0,n=t.names.length;r<n;r++)if(t.names[r].test(e))return!0;return!1}function u(e){return e instanceof Error?e.stack||e.message:e}t=e.exports=o.debug=o,t.coerce=u,t.disable=s,t.enable=a,t.enabled=l,t.humanize=r(/*! ms */531),t.names=[],t.skips=[],t.formatters={};var i,c=0},/*!*******************************!*\ !*** ./~/lodash/_DataView.js ***! \*******************************/ function(e,t,r){var n=r(/*! ./_getNative */26),o=r(/*! ./_root */11),a=n(o,"DataView");e.exports=a},/*!***************************!*\ !*** ./~/lodash/_Hash.js ***! \***************************/ function(e,t,r){function n(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}var o=r(/*! ./_hashClear */433),a=r(/*! ./_hashDelete */434),s=r(/*! ./_hashGet */435),l=r(/*! ./_hashHas */436),u=r(/*! ./_hashSet */437);n.prototype.clear=o,n.prototype.delete=a,n.prototype.get=s,n.prototype.has=l,n.prototype.set=u,e.exports=n},/*!******************************!*\ !*** ./~/lodash/_Promise.js ***! \******************************/ function(e,t,r){var n=r(/*! ./_getNative */26),o=r(/*! ./_root */11),a=n(o,"Promise");e.exports=a},/*!**********************************!*\ !*** ./~/lodash/_addMapEntry.js ***! \**********************************/ function(e,t){function r(e,t){return e.set(t[0],t[1]),e}e.exports=r},/*!**********************************!*\ !*** ./~/lodash/_addSetEntry.js ***! \**********************************/ function(e,t){function r(e,t){return e.add(t),e}e.exports=r},/*!*********************************!*\ !*** ./~/lodash/_arrayEvery.js ***! \*********************************/ function(e,t){function r(e,t){for(var r=-1,n=null==e?0:e.length;++r<n;)if(!t(e[r],r,e))return!1;return!0}e.exports=r},/*!**********************************!*\ !*** ./~/lodash/_arrayFilter.js ***! \**********************************/ function(e,t){function r(e,t){for(var r=-1,n=null==e?0:e.length,o=0,a=[];++r<n;){var s=e[r];t(s,r,e)&&(a[o++]=s)}return a}e.exports=r},/*!***********************************!*\ !*** ./~/lodash/_asciiToArray.js ***! \***********************************/ function(e,t){function r(e){return e.split("")}e.exports=r},/*!*********************************!*\ !*** ./~/lodash/_asciiWords.js ***! \*********************************/ function(e,t){function r(e){return e.match(n)||[]}var n=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g;e.exports=r},/*!***********************************!*\ !*** ./~/lodash/_baseAssignIn.js ***! \***********************************/ function(e,t,r){function n(e,t){return e&&o(t,a(t),e)}var o=r(/*! ./_copyObject */33),a=r(/*! ./keysIn */270);e.exports=n},/*!********************************!*\ !*** ./~/lodash/_baseEvery.js ***! \********************************/ function(e,t,r){function n(e,t){var r=!0;return o(e,function(e,n,o){return r=!!t(e,n,o)}),r}var o=r(/*! ./_baseEach */32);e.exports=n},/*!***********************************!*\ !*** ./~/lodash/_baseExtremum.js ***! \***********************************/ function(e,t,r){function n(e,t,r){for(var n=-1,a=e.length;++n<a;){var s=e[n],l=t(s);if(null!=l&&(void 0===u?l===l&&!o(l):r(l,u)))var u=l,i=s}return i}var o=r(/*! ./isSymbol */29);e.exports=n},/*!*********************************!*\ !*** ./~/lodash/_baseFilter.js ***! \*********************************/ function(e,t,r){function n(e,t){var r=[];return o(e,function(e,n,o){t(e,n,o)&&r.push(e)}),r}var o=r(/*! ./_baseEach */32);e.exports=n},/*!******************************!*\ !*** ./~/lodash/_baseFor.js ***! \******************************/ function(e,t,r){var n=r(/*! ./_createBaseFor */414),o=n();e.exports=o},/*!******************************!*\ !*** ./~/lodash/_baseHas.js ***! \******************************/ function(e,t){function r(e,t){return null!=e&&o.call(e,t)}var n=Object.prototype,o=n.hasOwnProperty;e.exports=r},/*!********************************!*\ !*** ./~/lodash/_baseHasIn.js ***! \********************************/ function(e,t){function r(e,t){return null!=e&&t in Object(e)}e.exports=r},/*!**********************************!*\ !*** ./~/lodash/_baseInRange.js ***! \**********************************/ function(e,t){function r(e,t,r){return e>=o(t,r)&&e<n(t,r)}var n=Math.max,o=Math.min;e.exports=r},/*!***************************************!*\ !*** ./~/lodash/_baseIntersection.js ***! \***************************************/ function(e,t,r){function n(e,t,r){for(var n=r?s:a,p=e[0].length,d=e.length,f=d,y=Array(d),m=1/0,h=[];f--;){var v=e[f];f&&t&&(v=l(v,u(t))),m=c(v.length,m),y[f]=!r&&(t||p>=120&&v.length>=120)?new o(f&&v):void 0}v=e[0];var b=-1,g=y[0];e:for(;++b<p&&h.length<m;){var P=v[b],T=t?t(P):P;if(P=r||0!==P?P:0,!(g?i(g,T):n(h,T,r))){for(f=d;--f;){var O=y[f];if(!(O?i(O,T):n(e[f],T,r)))continue e}g&&g.push(T),h.push(P)}}return h}var o=r(/*! ./_SetCache */54),a=r(/*! ./_arrayIncludes */56),s=r(/*! ./_arrayIncludesWith */113),l=r(/*! ./_arrayMap */17),u=r(/*! ./_baseUnary */63),i=r(/*! ./_cacheHas */64),c=Math.min;e.exports=n},/*!*********************************!*\ !*** ./~/lodash/_baseInvoke.js ***! \*********************************/ function(e,t,r){function n(e,t,r){t=a(t,e),e=l(e,t);var n=null==e?e:e[u(s(t))];return null==n?void 0:o(n,e,r)}var o=r(/*! ./_apply */55),a=r(/*! ./_castPath */25),s=r(/*! ./last */271),l=r(/*! ./_parent */253),u=r(/*! ./_toKey */22);e.exports=n},/*!**************************************!*\ !*** ./~/lodash/_baseIsArguments.js ***! \**************************************/ function(e,t,r){function n(e){return a(e)&&o(e)==s}var o=r(/*! ./_baseGetTag */21),a=r(/*! ./isObjectLike */15),s="[object Arguments]";e.exports=n},/*!**************************************!*\ !*** ./~/lodash/_baseIsEqualDeep.js ***! \**************************************/ function(e,t,r){function n(e,t,r,n,h,b){var g=i(e),P=i(t),T=y,O=y;g||(T=u(e),T=T==f?m:T),P||(O=u(t),O=O==f?m:O);var _=T==m,E=O==m,j=T==O;if(j&&c(e)){if(!c(t))return!1;g=!0,_=!1}if(j&&!_)return b||(b=new o),g||p(e)?a(e,t,r,n,h,b):s(e,t,T,r,n,h,b);if(!(r&d)){var w=_&&v.call(e,"__wrapped__"),S=E&&v.call(t,"__wrapped__");if(w||S){var M=w?e.value():e,x=S?t.value():t;return b||(b=new o),h(M,x,r,n,b)}}return!!j&&(b||(b=new o),l(e,t,r,n,h,b))}var o=r(/*! ./_Stack */112),a=r(/*! ./_equalArrays */240),s=r(/*! ./_equalByTag */425),l=r(/*! ./_equalObjects */426),u=r(/*! ./_getTag */124),i=r(/*! ./isArray */4),c=r(/*! ./isBuffer */43),p=r(/*! ./isTypedArray */79),d=1,f="[object Arguments]",y="[object Array]",m="[object Object]",h=Object.prototype,v=h.hasOwnProperty;e.exports=n},/*!**********************************!*\ !*** ./~/lodash/_baseIsMatch.js ***! \**********************************/ function(e,t,r){function n(e,t,r,n){var u=r.length,i=u,c=!n;if(null==e)return!i;for(e=Object(e);u--;){var p=r[u];if(c&&p[2]?p[1]!==e[p[0]]:!(p[0]in e))return!1}for(;++u<i;){p=r[u];var d=p[0],f=e[d],y=p[1];if(c&&p[2]){if(void 0===f&&!(d in e))return!1}else{var m=new o;if(n)var h=n(f,y,d,e,t,m);if(!(void 0===h?a(y,f,s|l,n,m):h))return!1}}return!0}var o=r(/*! ./_Stack */112),a=r(/*! ./_baseIsEqual */118),s=1,l=2;e.exports=n},/*!********************************!*\ !*** ./~/lodash/_baseIsNaN.js ***! \********************************/ function(e,t){function r(e){return e!==e}e.exports=r},/*!***********************************!*\ !*** ./~/lodash/_baseIsNative.js ***! \***********************************/ function(e,t,r){function n(e){if(!s(e)||a(e))return!1;var t=o(e)?y:i;return t.test(l(e))}var o=r(/*! ./isFunction */28),a=r(/*! ./_isMasked */444),s=r(/*! ./isObject */12),l=r(/*! ./_toSource */258),u=/[\\^$.*+?()[\]{}|]/g,i=/^\[object .+?Constructor\]$/,c=Function.prototype,p=Object.prototype,d=c.toString,f=p.hasOwnProperty,y=RegExp("^"+d.call(f).replace(u,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");e.exports=n},/*!***************************************!*\ !*** ./~/lodash/_baseIsTypedArray.js ***! \***************************************/ function(e,t,r){function n(e){return s(e)&&a(e.length)&&!!A[o(e)]}var o=r(/*! ./_baseGetTag */21),a=r(/*! ./isLength */131),s=r(/*! ./isObjectLike */15),l="[object Arguments]",u="[object Array]",i="[object Boolean]",c="[object Date]",p="[object Error]",d="[object Function]",f="[object Map]",y="[object Number]",m="[object Object]",h="[object RegExp]",v="[object Set]",b="[object String]",g="[object WeakMap]",P="[object ArrayBuffer]",T="[object DataView]",O="[object Float32Array]",_="[object Float64Array]",E="[object Int8Array]",j="[object Int16Array]",w="[object Int32Array]",S="[object Uint8Array]",M="[object Uint8ClampedArray]",x="[object Uint16Array]",k="[object Uint32Array]",A={};A[O]=A[_]=A[E]=A[j]=A[w]=A[S]=A[M]=A[x]=A[k]=!0,A[l]=A[u]=A[P]=A[i]=A[T]=A[c]=A[p]=A[d]=A[f]=A[y]=A[m]=A[h]=A[v]=A[b]=A[g]=!1,e.exports=n},/*!*********************************!*\ !*** ./~/lodash/_baseKeysIn.js ***! \*********************************/ function(e,t,r){function n(e){if(!o(e))return s(e);var t=a(e),r=[];for(var n in e)("constructor"!=n||!t&&u.call(e,n))&&r.push(n);return r}var o=r(/*! ./isObject */12),a=r(/*! ./_isPrototype */40),s=r(/*! ./_nativeKeysIn */458),l=Object.prototype,u=l.hasOwnProperty;e.exports=n},/*!*****************************!*\ !*** ./~/lodash/_baseLt.js ***! \*****************************/ function(e,t){function r(e,t){return e<t}e.exports=r},/*!**********************************!*\ !*** ./~/lodash/_baseMatches.js ***! \**********************************/ function(e,t,r){function n(e){var t=a(e);return 1==t.length&&t[0][2]?s(t[0][0],t[0][1]):function(r){return r===e||o(r,e,t)}}var o=r(/*! ./_baseIsMatch */374),a=r(/*! ./_getMatchData */428),s=r(/*! ./_matchesStrictComparable */250);e.exports=n},/*!******************************************!*\ !*** ./~/lodash/_baseMatchesProperty.js ***! \******************************************/ function(e,t,r){function n(e,t){return l(e)&&u(t)?i(c(e),t):function(r){var n=a(r,e);return void 0===n&&n===t?s(r,e):o(t,n,p|d)}}var o=r(/*! ./_baseIsEqual */118),a=r(/*! ./get */34),s=r(/*! ./hasIn */265),l=r(/*! ./_isKey */125),u=r(/*! ./_isStrictComparable */248),i=r(/*! ./_matchesStrictComparable */250),c=r(/*! ./_toKey */22),p=1,d=2;e.exports=n},/*!**********************************!*\ !*** ./~/lodash/_baseOrderBy.js ***! \**********************************/ function(e,t,r){function n(e,t,r){var n=-1;t=o(t.length?t:[c],u(a));var p=s(e,function(e,r,a){var s=o(t,function(t){return t(e)});return{criteria:s,index:++n,value:e}});return l(p,function(e,t){return i(e,t,r)})}var o=r(/*! ./_arrayMap */17),a=r(/*! ./_baseIteratee */13),s=r(/*! ./_baseMap */230),l=r(/*! ./_baseSortBy */392),u=r(/*! ./_baseUnary */63),i=r(/*! ./_compareMultiple */407),c=r(/*! ./identity */23);e.exports=n},/*!*******************************!*\ !*** ./~/lodash/_basePick.js ***! \*******************************/ function(e,t,r){function n(e,t){return e=Object(e),o(e,t,function(t,r){return a(e,r)})}var o=r(/*! ./_basePickBy */384),a=r(/*! ./hasIn */265);e.exports=n},/*!*********************************!*\ !*** ./~/lodash/_basePickBy.js ***! \*********************************/ function(e,t,r){function n(e,t,r){for(var n=-1,l=t.length,u={};++n<l;){var i=t[n],c=o(e,i);r(c,i)&&a(u,s(i,e),c)}return u}var o=r(/*! ./_baseGet */61),a=r(/*! ./_baseSet */389),s=r(/*! ./_castPath */25);e.exports=n},/*!***********************************!*\ !*** ./~/lodash/_baseProperty.js ***! \***********************************/ function(e,t){function r(e){return function(t){return null==t?void 0:t[e]}}e.exports=r},/*!***************************************!*\ !*** ./~/lodash/_basePropertyDeep.js ***! \***************************************/ function(e,t,r){function n(e){return function(t){return o(t,e)}}var o=r(/*! ./_baseGet */61);e.exports=n},/*!*************************************!*\ !*** ./~/lodash/_basePropertyOf.js ***! \*************************************/ function(e,t){function r(e){return function(t){return null==e?void 0:e[t]}}e.exports=r},/*!*********************************!*\ !*** ./~/lodash/_baseReduce.js ***! \*********************************/ function(e,t){function r(e,t,r,n,o){return o(e,function(e,o,a){r=n?(n=!1,e):t(r,e,o,a)}),r}e.exports=r},/*!******************************!*\ !*** ./~/lodash/_baseSet.js ***! \******************************/ function(e,t,r){function n(e,t,r,n){if(!l(e))return e;t=a(t,e);for(var i=-1,c=t.length,p=c-1,d=e;null!=d&&++i<c;){var f=u(t[i]),y=r;if(i!=p){var m=d[f];y=n?n(m,f,d):void 0,void 0===y&&(y=l(m)?m:s(t[i+1])?[]:{})}o(d,f,y),d=d[f]}return e}var o=r(/*! ./_assignValue */58),a=r(/*! ./_castPath */25),s=r(/*! ./_isIndex */39),l=r(/*! ./isObject */12),u=r(/*! ./_toKey */22);e.exports=n},/*!**************************************!*\ !*** ./~/lodash/_baseSetToString.js ***! \**************************************/ function(e,t,r){var n=r(/*! ./constant */480),o=r(/*! ./_defineProperty */239),a=r(/*! ./identity */23),s=o?function(e,t){return o(e,"toString",{configurable:!0,enumerable:!1,value:n(t),writable:!0})}:a;e.exports=s},/*!*******************************!*\ !*** ./~/lodash/_baseSome.js ***! \*******************************/ function(e,t,r){function n(e,t){var r;return o(e,function(e,n,o){return r=t(e,n,o),!r}),!!r}var o=r(/*! ./_baseEach */32);e.exports=n},/*!*********************************!*\ !*** ./~/lodash/_baseSortBy.js ***! \*********************************/ function(e,t){function r(e,t){var r=e.length;for(e.sort(t);r--;)e[r]=e[r].value;return e}e.exports=r},/*!******************************!*\ !*** ./~/lodash/_baseSum.js ***! \******************************/ function(e,t){function r(e,t){for(var r,n=-1,o=e.length;++n<o;){var a=t(e[n]);void 0!==a&&(r=void 0===r?a:r+a)}return r}e.exports=r},/*!*******************************!*\ !*** ./~/lodash/_baseUniq.js ***! \*******************************/ function(e,t,r){function n(e,t,r){var n=-1,p=a,d=e.length,f=!0,y=[],m=y;if(r)f=!1,p=s;else if(d>=c){var h=t?null:u(e);if(h)return i(h);f=!1,p=l,m=new o}else m=t?[]:y;e:for(;++n<d;){var v=e[n],b=t?t(v):v;if(v=r||0!==v?v:0,f&&b===b){for(var g=m.length;g--;)if(m[g]===b)continue e;t&&m.push(b),y.push(v)}else p(m,b,r)||(m!==y&&m.push(b),y.push(v))}return y}var o=r(/*! ./_SetCache */54),a=r(/*! ./_arrayIncludes */56),s=r(/*! ./_arrayIncludesWith */113),l=r(/*! ./_cacheHas */64),u=r(/*! ./_createSet */423),i=r(/*! ./_setToArray */73),c=200;e.exports=n},/*!********************************!*\ !*** ./~/lodash/_baseUnset.js ***! \********************************/ function(e,t,r){function n(e,t){return t=o(t,e),e=s(e,t),null==e||delete e[l(a(t))]}var o=r(/*! ./_castPath */25),a=r(/*! ./last */271),s=r(/*! ./_parent */253),l=r(/*! ./_toKey */22);e.exports=n},/*!*********************************!*\ !*** ./~/lodash/_baseValues.js ***! \*********************************/ function(e,t,r){function n(e,t){return o(t,function(t){return e[t]})}var o=r(/*! ./_arrayMap */17);e.exports=n},/*!******************************************!*\ !*** ./~/lodash/_castArrayLikeObject.js ***! \******************************************/ function(e,t,r){function n(e){return o(e)?e:[]}var o=r(/*! ./isArrayLikeObject */77);e.exports=n},/*!********************************!*\ !*** ./~/lodash/_castSlice.js ***! \********************************/ function(e,t,r){function n(e,t,r){var n=e.length;return r=void 0===r?n:r,!t&&r>=n?e:o(e,t,r)}var o=r(/*! ./_baseSlice */62);e.exports=n},/*!**********************************!*\ !*** ./~/lodash/_cloneBuffer.js ***! \**********************************/ function(e,t,r){(function(e){function n(e,t){if(t)return e.slice();var r=e.length,n=i?i(r):new e.constructor(r);return e.copy(n),n}var o=r(/*! ./_root */11),a="object"==typeof t&&t&&!t.nodeType&&t,s=a&&"object"==typeof e&&e&&!e.nodeType&&e,l=s&&s.exports===a,u=l?o.Buffer:void 0,i=u?u.allocUnsafe:void 0;e.exports=n}).call(t,r(/*! ./../webpack/buildin/module.js */135)(e))},/*!************************************!*\ !*** ./~/lodash/_cloneDataView.js ***! \************************************/ function(e,t,r){function n(e,t){var r=t?o(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.byteLength)}var o=r(/*! ./_cloneArrayBuffer */121);e.exports=n},/*!*******************************!*\ !*** ./~/lodash/_cloneMap.js ***! \*******************************/ function(e,t,r){function n(e,t,r){var n=t?r(s(e),l):s(e);return a(n,o,new e.constructor)}var o=r(/*! ./_addMapEntry */356),a=r(/*! ./_arrayReduce */57),s=r(/*! ./_mapToArray */249),l=1;e.exports=n},/*!**********************************!*\ !*** ./~/lodash/_cloneRegExp.js ***! \**********************************/ function(e,t){function r(e){var t=new e.constructor(e.source,n.exec(e));return t.lastIndex=e.lastIndex,t}var n=/\w*$/;e.exports=r},/*!*******************************!*\ !*** ./~/lodash/_cloneSet.js ***! \*******************************/ function(e,t,r){function n(e,t,r){var n=t?r(s(e),l):s(e);return a(n,o,new e.constructor)}var o=r(/*! ./_addSetEntry */357),a=r(/*! ./_arrayReduce */57),s=r(/*! ./_setToArray */73),l=1;e.exports=n},/*!**********************************!*\ !*** ./~/lodash/_cloneSymbol.js ***! \**********************************/ function(e,t,r){function n(e){return s?Object(s.call(e)):{}}var o=r(/*! ./_Symbol */31),a=o?o.prototype:void 0,s=a?a.valueOf:void 0;e.exports=n},/*!**************************************!*\ !*** ./~/lodash/_cloneTypedArray.js ***! \**************************************/ function(e,t,r){function n(e,t){var r=t?o(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.length)}var o=r(/*! ./_cloneArrayBuffer */121);e.exports=n},/*!***************************************!*\ !*** ./~/lodash/_compareAscending.js ***! \***************************************/ function(e,t,r){function n(e,t){if(e!==t){var r=void 0!==e,n=null===e,a=e===e,s=o(e),l=void 0!==t,u=null===t,i=t===t,c=o(t);if(!u&&!c&&!s&&e>t||s&&l&&i&&!u&&!c||n&&l&&i||!r&&i||!a)return 1;if(!n&&!s&&!c&&e<t||c&&r&&a&&!n&&!s||u&&r&&a||!l&&a||!i)return-1}return 0}var o=r(/*! ./isSymbol */29);e.exports=n},/*!**************************************!*\ !*** ./~/lodash/_compareMultiple.js ***! \**************************************/ function(e,t,r){function n(e,t,r){for(var n=-1,a=e.criteria,s=t.criteria,l=a.length,u=r.length;++n<l;){var i=o(a[n],s[n]);if(i){if(n>=u)return i;var c=r[n];return i*("desc"==c?-1:1)}}return e.index-t.index}var o=r(/*! ./_compareAscending */406);e.exports=n},/*!**********************************!*\ !*** ./~/lodash/_copySymbols.js ***! \**********************************/ function(e,t,r){function n(e,t){return o(e,a(e),t)}var o=r(/*! ./_copyObject */33),a=r(/*! ./_getSymbols */123);e.exports=n},/*!************************************!*\ !*** ./~/lodash/_copySymbolsIn.js ***! \************************************/ function(e,t,r){function n(e,t){return o(e,a(e),t)}var o=r(/*! ./_copyObject */33),a=r(/*! ./_getSymbolsIn */244);e.exports=n},/*!*********************************!*\ !*** ./~/lodash/_coreJsData.js ***! \*********************************/ function(e,t,r){var n=r(/*! ./_root */11),o=n["__core-js_shared__"];e.exports=o},/*!***********************************!*\ !*** ./~/lodash/_countHolders.js ***! \***********************************/ function(e,t){function r(e,t){for(var r=e.length,n=0;r--;)e[r]===t&&++n;return n}e.exports=r},/*!*************************************!*\ !*** ./~/lodash/_createAssigner.js ***! \*************************************/ function(e,t,r){function n(e){return o(function(t,r){var n=-1,o=r.length,s=o>1?r[o-1]:void 0,l=o>2?r[2]:void 0;for(s=e.length>3&&"function"==typeof s?(o--,s):void 0,l&&a(r[0],r[1],l)&&(s=o<3?void 0:s,o=1),t=Object(t);++n<o;){var u=r[n];u&&e(t,u,n,s)}return t})}var o=r(/*! ./_baseRest */18),a=r(/*! ./_isIterateeCall */71);e.exports=n},/*!*************************************!*\ !*** ./~/lodash/_createBaseEach.js ***! \*************************************/ function(e,t,r){function n(e,t){return function(r,n){if(null==r)return r;if(!o(r))return e(r,n);for(var a=r.length,s=t?a:-1,l=Object(r);(t?s--:++s<a)&&n(l[s],s,l)!==!1;);return r}}var o=r(/*! ./isArrayLike */14);e.exports=n},/*!************************************!*\ !*** ./~/lodash/_createBaseFor.js ***! \************************************/ function(e,t){function r(e){return function(t,r,n){for(var o=-1,a=Object(t),s=n(t),l=s.length;l--;){var u=s[e?l:++o];if(r(a[u],u,a)===!1)break}return t}}e.exports=r},/*!*********************************!*\ !*** ./~/lodash/_createBind.js ***! \*********************************/ function(e,t,r){function n(e,t,r){function n(){var t=this&&this!==a&&this instanceof n?u:e;return t.apply(l?r:this,arguments)}var l=t&s,u=o(e);return n}var o=r(/*! ./_createCtor */66),a=r(/*! ./_root */11),s=1;e.exports=n},/*!**************************************!*\ !*** ./~/lodash/_createCaseFirst.js ***! \**************************************/ function(e,t,r){function n(e){return function(t){t=l(t);var r=a(t)?s(t):void 0,n=r?r[0]:t.charAt(0),u=r?o(r,1).join(""):t.slice(1);return n[e]()+u}}var o=r(/*! ./_castSlice */398),a=r(/*! ./_hasUnicode */246),s=r(/*! ./_stringToArray */471),l=r(/*! ./toString */24);e.exports=n},/*!***************************************!*\ !*** ./~/lodash/_createCompounder.js ***! \***************************************/ function(e,t,r){function n(e){return function(t){return o(s(a(t).replace(u,"")),e,"")}}var o=r(/*! ./_arrayReduce */57),a=r(/*! ./deburr */481),s=r(/*! ./words */529),l="['’]",u=RegExp(l,"g");e.exports=n},/*!**********************************!*\ !*** ./~/lodash/_createCurry.js ***! \**********************************/ function(e,t,r){function n(e,t,r){function n(){for(var a=arguments.length,d=Array(a),f=a,y=u(n);f--;)d[f]=arguments[f];var m=a<3&&d[0]!==y&&d[a-1]!==y?[]:i(d,y);if(a-=m.length,a<r)return l(e,t,s,n.placeholder,void 0,d,m,void 0,void 0,r-a);var h=this&&this!==c&&this instanceof n?p:e;return o(h,this,d)}var p=a(e);return n}var o=r(/*! ./_apply */55),a=r(/*! ./_createCtor */66),s=r(/*! ./_createHybrid */237),l=r(/*! ./_createRecurry */238),u=r(/*! ./_getHolder */68),i=r(/*! ./_replaceHolders */41),c=r(/*! ./_root */11);e.exports=n},/*!*********************************!*\ !*** ./~/lodash/_createFind.js ***! \*********************************/ function(e,t,r){function n(e){return function(t,r,n){var l=Object(t);if(!a(t)){var u=o(r,3);t=s(t),r=function(e){return u(l[e],e,l)}}var i=e(t,r,n);return i>-1?l[u?t[i]:i]:void 0}}var o=r(/*! ./_baseIteratee */13),a=r(/*! ./isArrayLike */14),s=r(/*! ./keys */9);e.exports=n},/*!*********************************!*\ !*** ./~/lodash/_createFlow.js ***! \*********************************/ function(e,t,r){function n(e){return a(function(t){var r=t.length,n=r,a=o.prototype.thru;for(e&&t.reverse();n--;){var h=t[n];if("function"!=typeof h)throw new TypeError(p);if(a&&!v&&"wrapper"==l(h))var v=new o([],!0)}for(n=v?n:r;++n<r;){h=t[n];var b=l(h),g="wrapper"==b?s(h):void 0;v=g&&i(g[0])&&g[1]==(y|d|f|m)&&!g[4].length&&1==g[9]?v[l(g[0])].apply(v,g[3]):1==h.length&&i(h)?v[b]():v.thru(h)}return function(){var e=arguments,n=e[0];if(v&&1==e.length&&u(n)&&n.length>=c)return v.plant(n).value();for(var o=0,a=r?t[o].apply(this,e):n;++o<r;)a=t[o].call(this,a);return a}})}var o=r(/*! ./_LodashWrapper */109),a=r(/*! ./_flatRest */67),s=r(/*! ./_getData */122),l=r(/*! ./_getFuncName */243),u=r(/*! ./isArray */4),i=r(/*! ./_isLaziable */247),c=200,p="Expected a function",d=8,f=32,y=128,m=256;e.exports=n},/*!************************************!*\ !*** ./~/lodash/_createPartial.js ***! \************************************/ function(e,t,r){function n(e,t,r,n){function u(){for(var t=-1,a=arguments.length,l=-1,p=n.length,d=Array(p+a),f=this&&this!==s&&this instanceof u?c:e;++l<p;)d[l]=n[l];for(;a--;)d[l++]=arguments[++t];return o(f,i?r:this,d)}var i=t&l,c=a(e);return u}var o=r(/*! ./_apply */55),a=r(/*! ./_createCtor */66),s=r(/*! ./_root */11),l=1;e.exports=n},/*!**********************************!*\ !*** ./~/lodash/_createRound.js ***! \**********************************/ function(e,t,r){function n(e){var t=Math[e];return function(e,r){if(e=a(e),r=l(o(r),292)){var n=(s(e)+"e").split("e"),u=t(n[0]+"e"+(+n[1]+r));return n=(s(u)+"e").split("e"),+(n[0]+"e"+(+n[1]-r))}return t(e)}}var o=r(/*! ./toInteger */20),a=r(/*! ./toNumber */81),s=r(/*! ./toString */24),l=Math.min;e.exports=n},/*!********************************!*\ !*** ./~/lodash/_createSet.js ***! \********************************/ function(e,t,r){var n=r(/*! ./_Set */219),o=r(/*! ./noop */272),a=r(/*! ./_setToArray */73),s=1/0,l=n&&1/a(new n([,-0]))[1]==s?function(e){return new n(e)}:o;e.exports=l},/*!***********************************!*\ !*** ./~/lodash/_deburrLetter.js ***! \***********************************/ function(e,t,r){var n=r(/*! ./_basePropertyOf */387),o={"À":"A","Á":"A","Â":"A","Ã":"A","Ä":"A","Å":"A","à":"a","á":"a","â":"a","ã":"a","ä":"a","å":"a","Ç":"C","ç":"c","Ð":"D","ð":"d","È":"E","É":"E","Ê":"E","Ë":"E","è":"e","é":"e","ê":"e","ë":"e","Ì":"I","Í":"I","Î":"I","Ï":"I","ì":"i","í":"i","î":"i","ï":"i","Ñ":"N","ñ":"n","Ò":"O","Ó":"O","Ô":"O","Õ":"O","Ö":"O","Ø":"O","ò":"o","ó":"o","ô":"o","õ":"o","ö":"o","ø":"o","Ù":"U","Ú":"U","Û":"U","Ü":"U","ù":"u","ú":"u","û":"u","ü":"u","Ý":"Y","ý":"y","ÿ":"y","Æ":"Ae","æ":"ae","Þ":"Th","þ":"th","ß":"ss","Ā":"A","Ă":"A","Ą":"A","ā":"a","ă":"a","ą":"a","Ć":"C","Ĉ":"C","Ċ":"C","Č":"C","ć":"c","ĉ":"c","ċ":"c","č":"c","Ď":"D","Đ":"D","ď":"d","đ":"d","Ē":"E","Ĕ":"E","Ė":"E","Ę":"E","Ě":"E","ē":"e","ĕ":"e","ė":"e","ę":"e","ě":"e","Ĝ":"G","Ğ":"G","Ġ":"G","Ģ":"G","ĝ":"g","ğ":"g","ġ":"g","ģ":"g","Ĥ":"H","Ħ":"H","ĥ":"h","ħ":"h","Ĩ":"I","Ī":"I","Ĭ":"I","Į":"I","İ":"I","ĩ":"i","ī":"i","ĭ":"i","į":"i","ı":"i","Ĵ":"J","ĵ":"j","Ķ":"K","ķ":"k","ĸ":"k","Ĺ":"L","Ļ":"L","Ľ":"L","Ŀ":"L","Ł":"L","ĺ":"l","ļ":"l","ľ":"l","ŀ":"l","ł":"l","Ń":"N","Ņ":"N","Ň":"N","Ŋ":"N","ń":"n","ņ":"n","ň":"n","ŋ":"n","Ō":"O","Ŏ":"O","Ő":"O","ō":"o","ŏ":"o","ő":"o","Ŕ":"R","Ŗ":"R","Ř":"R","ŕ":"r","ŗ":"r","ř":"r","Ś":"S","Ŝ":"S","Ş":"S","Š":"S","ś":"s","ŝ":"s","ş":"s","š":"s","Ţ":"T","Ť":"T","Ŧ":"T","ţ":"t","ť":"t","ŧ":"t","Ũ":"U","Ū":"U","Ŭ":"U","Ů":"U","Ű":"U","Ų":"U","ũ":"u","ū":"u","ŭ":"u","ů":"u","ű":"u","ų":"u","Ŵ":"W","ŵ":"w","Ŷ":"Y","ŷ":"y","Ÿ":"Y","Ź":"Z","Ż":"Z","Ž":"Z","ź":"z","ż":"z","ž":"z","IJ":"IJ","ij":"ij","Œ":"Oe","œ":"oe","ʼn":"'n","ſ":"s"},a=n(o);e.exports=a},/*!*********************************!*\ !*** ./~/lodash/_equalByTag.js ***! \*********************************/ function(e,t,r){function n(e,t,r,n,o,_,j){switch(r){case O:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case T:return!(e.byteLength!=t.byteLength||!_(new a(e),new a(t)));case d:case f:case h:return s(+e,+t);case y:return e.name==t.name&&e.message==t.message;case v:case g:return e==t+"";case m:var w=u;case b:var S=n&c;if(w||(w=i),e.size!=t.size&&!S)return!1;var M=j.get(e);if(M)return M==t;n|=p,j.set(e,t);var x=l(w(e),w(t),n,o,_,j);return j.delete(e),x;case P:if(E)return E.call(e)==E.call(t)}return!1}var o=r(/*! ./_Symbol */31),a=r(/*! ./_Uint8Array */220),s=r(/*! ./eq */42),l=r(/*! ./_equalArrays */240),u=r(/*! ./_mapToArray */249),i=r(/*! ./_setToArray */73),c=1,p=2,d="[object Boolean]",f="[object Date]",y="[object Error]",m="[object Map]",h="[object Number]",v="[object RegExp]",b="[object Set]",g="[object String]",P="[object Symbol]",T="[object ArrayBuffer]",O="[object DataView]",_=o?o.prototype:void 0,E=_?_.valueOf:void 0;e.exports=n},/*!***********************************!*\ !*** ./~/lodash/_equalObjects.js ***! \***********************************/ function(e,t,r){function n(e,t,r,n,s,u){var i=r&a,c=o(e),p=c.length,d=o(t),f=d.length;if(p!=f&&!i)return!1;for(var y=p;y--;){var m=c[y];if(!(i?m in t:l.call(t,m)))return!1}var h=u.get(e);if(h&&u.get(t))return h==t;var v=!0;u.set(e,t),u.set(t,e);for(var b=i;++y<p;){m=c[y];var g=e[m],P=t[m];if(n)var T=i?n(P,g,m,t,e,u):n(g,P,m,e,t,u);if(!(void 0===T?g===P||s(g,P,r,n,u):T)){v=!1;break}b||(b="constructor"==m)}if(v&&!b){var O=e.constructor,_=t.constructor;O!=_&&"constructor"in e&&"constructor"in t&&!("function"==typeof O&&O instanceof O&&"function"==typeof _&&_ instanceof _)&&(v=!1)}return u.delete(e),u.delete(t),v}var o=r(/*! ./keys */9),a=1,s=Object.prototype,l=s.hasOwnProperty;e.exports=n},/*!*********************************!*\ !*** ./~/lodash/_getAllKeys.js ***! \*********************************/ function(e,t,r){function n(e){return o(e,s,a)}var o=r(/*! ./_baseGetAllKeys */228),a=r(/*! ./_getSymbols */123),s=r(/*! ./keys */9);e.exports=n},/*!***********************************!*\ !*** ./~/lodash/_getMatchData.js ***! \***********************************/ function(e,t,r){function n(e){for(var t=a(e),r=t.length;r--;){var n=t[r],s=e[n];t[r]=[n,s,o(s)]}return t}var o=r(/*! ./_isStrictComparable */248),a=r(/*! ./keys */9);e.exports=n},/*!********************************!*\ !*** ./~/lodash/_getRawTag.js ***! \********************************/ function(e,t,r){function n(e){var t=s.call(e,u),r=e[u];try{e[u]=void 0;var n=!0}catch(e){}var o=l.call(e);return n&&(t?e[u]=r:delete e[u]),o}var o=r(/*! ./_Symbol */31),a=Object.prototype,s=a.hasOwnProperty,l=a.toString,u=o?o.toStringTag:void 0;e.exports=n},/*!*******************************!*\ !*** ./~/lodash/_getValue.js ***! \*******************************/ function(e,t){function r(e,t){return null==e?void 0:e[t]}e.exports=r},/*!*************************************!*\ !*** ./~/lodash/_getWrapDetails.js ***! \*************************************/ function(e,t){function r(e){var t=e.match(n);return t?t[1].split(o):[]}var n=/\{\n\/\* \[wrapped with (.+)\] \*/,o=/,? & /;e.exports=r},/*!*************************************!*\ !*** ./~/lodash/_hasUnicodeWord.js ***! \*************************************/ function(e,t){function r(e){return n.test(e)}var n=/[a-z][A-Z]|[A-Z]{2,}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/;e.exports=r},/*!********************************!*\ !*** ./~/lodash/_hashClear.js ***! \********************************/ function(e,t,r){function n(){this.__data__=o?o(null):{},this.size=0}var o=r(/*! ./_nativeCreate */72);e.exports=n},/*!*********************************!*\ !*** ./~/lodash/_hashDelete.js ***! \*********************************/ function(e,t){function r(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}e.exports=r},/*!******************************!*\ !*** ./~/lodash/_hashGet.js ***! \******************************/ function(e,t,r){function n(e){var t=this.__data__;if(o){var r=t[e];return r===a?void 0:r}return l.call(t,e)?t[e]:void 0}var o=r(/*! ./_nativeCreate */72),a="__lodash_hash_undefined__",s=Object.prototype,l=s.hasOwnProperty;e.exports=n},/*!******************************!*\ !*** ./~/lodash/_hashHas.js ***! \******************************/ function(e,t,r){function n(e){var t=this.__data__;return o?void 0!==t[e]:s.call(t,e)}var o=r(/*! ./_nativeCreate */72),a=Object.prototype,s=a.hasOwnProperty;e.exports=n},/*!******************************!*\ !*** ./~/lodash/_hashSet.js ***! \******************************/ function(e,t,r){function n(e,t){var r=this.__data__;return this.size+=this.has(e)?0:1,r[e]=o&&void 0===t?a:t,this}var o=r(/*! ./_nativeCreate */72),a="__lodash_hash_undefined__";e.exports=n},/*!*************************************!*\ !*** ./~/lodash/_initCloneArray.js ***! \*************************************/ function(e,t){function r(e){var t=e.length,r=e.constructor(t);return t&&"string"==typeof e[0]&&o.call(e,"index")&&(r.index=e.index,r.input=e.input),r}var n=Object.prototype,o=n.hasOwnProperty;e.exports=r},/*!*************************************!*\ !*** ./~/lodash/_initCloneByTag.js ***! \*************************************/ function(e,t,r){function n(e,t,r,n){var k=e.constructor;switch(t){case g:return o(e);case p:case d:return new k(+e);case P:return a(e,n);case T:case O:case _:case E:case j:case w:case S:case M:case x:return c(e,n);case f:return s(e,n,r);case y:case v:return new k(e);case m:return l(e);case h:return u(e,n,r);case b:return i(e)}}var o=r(/*! ./_cloneArrayBuffer */121),a=r(/*! ./_cloneDataView */400),s=r(/*! ./_cloneMap */401),l=r(/*! ./_cloneRegExp */402),u=r(/*! ./_cloneSet */403),i=r(/*! ./_cloneSymbol */404),c=r(/*! ./_cloneTypedArray */405),p="[object Boolean]",d="[object Date]",f="[object Map]",y="[object Number]",m="[object RegExp]",h="[object Set]",v="[object String]",b="[object Symbol]",g="[object ArrayBuffer]",P="[object DataView]",T="[object Float32Array]",O="[object Float64Array]",_="[object Int8Array]",E="[object Int16Array]",j="[object Int32Array]",w="[object Uint8Array]",S="[object Uint8ClampedArray]",M="[object Uint16Array]",x="[object Uint32Array]";e.exports=n},/*!**************************************!*\ !*** ./~/lodash/_initCloneObject.js ***! \**************************************/ function(e,t,r){function n(e){return"function"!=typeof e.constructor||s(e)?{}:o(a(e))}var o=r(/*! ./_baseCreate */37),a=r(/*! ./_getPrototype */70),s=r(/*! ./_isPrototype */40);e.exports=n},/*!****************************************!*\ !*** ./~/lodash/_insertWrapDetails.js ***! \****************************************/ function(e,t){function r(e,t){var r=t.length;if(!r)return e;var o=r-1;return t[o]=(r>1?"& ":"")+t[o],t=t.join(r>2?", ":" "),e.replace(n,"{\n/* [wrapped with "+t+"] */\n")}var n=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/;e.exports=r},/*!************************************!*\ !*** ./~/lodash/_isFlattenable.js ***! \************************************/ function(e,t,r){function n(e){return s(e)||a(e)||!!(l&&e&&e[l])}var o=r(/*! ./_Symbol */31),a=r(/*! ./isArguments */76),s=r(/*! ./isArray */4),l=o?o.isConcatSpreadable:void 0;e.exports=n},/*!********************************!*\ !*** ./~/lodash/_isKeyable.js ***! \********************************/ function(e,t){function r(e){var t=typeof e;return"string"==t||"number"==t||"symbol"==t||"boolean"==t?"__proto__"!==e:null===e}e.exports=r},/*!*******************************!*\ !*** ./~/lodash/_isMasked.js ***! \*******************************/ function(e,t,r){function n(e){return!!a&&a in e}var o=r(/*! ./_coreJsData */410),a=function(){var e=/[^.]+$/.exec(o&&o.keys&&o.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""}();e.exports=n},/*!*************************************!*\ !*** ./~/lodash/_listCacheClear.js ***! \*************************************/ function(e,t){function r(){this.__data__=[],this.size=0}e.exports=r},/*!**************************************!*\ !*** ./~/lodash/_listCacheDelete.js ***! \**************************************/ function(e,t,r){function n(e){var t=this.__data__,r=o(t,e);if(r<0)return!1;var n=t.length-1;return r==n?t.pop():s.call(t,r,1),--this.size,!0}var o=r(/*! ./_assocIndexOf */59),a=Array.prototype,s=a.splice;e.exports=n},/*!***********************************!*\ !*** ./~/lodash/_listCacheGet.js ***! \***********************************/ function(e,t,r){function n(e){var t=this.__data__,r=o(t,e);return r<0?void 0:t[r][1]}var o=r(/*! ./_assocIndexOf */59);e.exports=n},/*!***********************************!*\ !*** ./~/lodash/_listCacheHas.js ***! \***********************************/ function(e,t,r){function n(e){return o(this.__data__,e)>-1}var o=r(/*! ./_assocIndexOf */59);e.exports=n},/*!***********************************!*\ !*** ./~/lodash/_listCacheSet.js ***! \***********************************/ function(e,t,r){function n(e,t){var r=this.__data__,n=o(r,e);return n<0?(++this.size,r.push([e,t])):r[n][1]=t,this}var o=r(/*! ./_assocIndexOf */59);e.exports=n},/*!************************************!*\ !*** ./~/lodash/_mapCacheClear.js ***! \************************************/ function(e,t,r){function n(){this.size=0,this.__data__={hash:new o,map:new(s||a),string:new o}}var o=r(/*! ./_Hash */354),a=r(/*! ./_ListCache */53),s=r(/*! ./_Map */110);e.exports=n},/*!*************************************!*\ !*** ./~/lodash/_mapCacheDelete.js ***! \*************************************/ function(e,t,r){function n(e){var t=o(this,e).delete(e);return this.size-=t?1:0,t}var o=r(/*! ./_getMapData */69);e.exports=n},/*!**********************************!*\ !*** ./~/lodash/_mapCacheGet.js ***! \**********************************/ function(e,t,r){function n(e){return o(this,e).get(e)}var o=r(/*! ./_getMapData */69);e.exports=n},/*!**********************************!*\ !*** ./~/lodash/_mapCacheHas.js ***! \**********************************/ function(e,t,r){function n(e){return o(this,e).has(e)}var o=r(/*! ./_getMapData */69);e.exports=n},/*!**********************************!*\ !*** ./~/lodash/_mapCacheSet.js ***! \**********************************/ function(e,t,r){function n(e,t){var r=o(this,e),n=r.size;return r.set(e,t),this.size+=r.size==n?0:1,this}var o=r(/*! ./_getMapData */69);e.exports=n},/*!************************************!*\ !*** ./~/lodash/_memoizeCapped.js ***! \************************************/ function(e,t,r){function n(e){var t=o(e,function(e){return r.size===a&&r.clear(),e}),r=t.cache;return t}var o=r(/*! ./memoize */513),a=500;e.exports=n},/*!********************************!*\ !*** ./~/lodash/_mergeData.js ***! \********************************/ function(e,t,r){function n(e,t){var r=e[1],n=t[1],m=r|n,h=m<(u|i|d),v=n==d&&r==p||n==d&&r==f&&e[7].length<=t[8]||n==(d|f)&&t[7].length<=t[8]&&r==p;if(!h&&!v)return e;n&u&&(e[2]=t[2],m|=r&u?0:c);var b=t[3];if(b){var g=e[3];e[3]=g?o(g,b,t[4]):b,e[4]=g?s(e[3],l):t[4]}return b=t[5],b&&(g=e[5],e[5]=g?a(g,b,t[6]):b,e[6]=g?s(e[5],l):t[6]),b=t[7],b&&(e[7]=b),n&d&&(e[8]=null==e[8]?t[8]:y(e[8],t[8])),null==e[9]&&(e[9]=t[9]),e[0]=t[0],e[1]=m,e}var o=r(/*! ./_composeArgs */235),a=r(/*! ./_composeArgsRight */236),s=r(/*! ./_replaceHolders */41),l="__lodash_placeholder__",u=1,i=2,c=4,p=8,d=128,f=256,y=Math.min;e.exports=n},/*!*********************************!*\ !*** ./~/lodash/_nativeKeys.js ***! \*********************************/ function(e,t,r){var n=r(/*! ./_overArg */126),o=n(Object.keys,Object);e.exports=o},/*!***********************************!*\ !*** ./~/lodash/_nativeKeysIn.js ***! \***********************************/ function(e,t){function r(e){var t=[];if(null!=e)for(var r in Object(e))t.push(r);return t}e.exports=r},/*!*******************************!*\ !*** ./~/lodash/_nodeUtil.js ***! \*******************************/ function(e,t,r){(function(e){var n=r(/*! ./_freeGlobal */241),o="object"==typeof t&&t&&!t.nodeType&&t,a=o&&"object"==typeof e&&e&&!e.nodeType&&e,s=a&&a.exports===o,l=s&&n.process,u=function(){try{return l&&l.binding&&l.binding("util")}catch(e){}}();e.exports=u}).call(t,r(/*! ./../webpack/buildin/module.js */135)(e))},/*!*************************************!*\ !*** ./~/lodash/_objectToString.js ***! \*************************************/ function(e,t){function r(e){return o.call(e)}var n=Object.prototype,o=n.toString;e.exports=r},/*!********************************!*\ !*** ./~/lodash/_realNames.js ***! \********************************/ function(e,t){var r={};e.exports=r},/*!******************************!*\ !*** ./~/lodash/_reorder.js ***! \******************************/ function(e,t,r){function n(e,t){for(var r=e.length,n=s(t.length,r),l=o(e);n--;){var u=t[n];e[n]=a(u,r)?l[u]:void 0}return e}var o=r(/*! ./_copyArray */65),a=r(/*! ./_isIndex */39),s=Math.min;e.exports=n},/*!**********************************!*\ !*** ./~/lodash/_setCacheAdd.js ***! \**********************************/ function(e,t){function r(e){return this.__data__.set(e,n),this}var n="__lodash_hash_undefined__";e.exports=r},/*!**********************************!*\ !*** ./~/lodash/_setCacheHas.js ***! \**********************************/ function(e,t){function r(e){return this.__data__.has(e)}e.exports=r},/*!*********************************!*\ !*** ./~/lodash/_stackClear.js ***! \*********************************/ function(e,t,r){function n(){this.__data__=new o,this.size=0}var o=r(/*! ./_ListCache */53);e.exports=n},/*!**********************************!*\ !*** ./~/lodash/_stackDelete.js ***! \**********************************/ function(e,t){function r(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r}e.exports=r},/*!*******************************!*\ !*** ./~/lodash/_stackGet.js ***! \*******************************/ function(e,t){function r(e){return this.__data__.get(e)}e.exports=r},/*!*******************************!*\ !*** ./~/lodash/_stackHas.js ***! \*******************************/ function(e,t){function r(e){return this.__data__.has(e)}e.exports=r},/*!*******************************!*\ !*** ./~/lodash/_stackSet.js ***! \*******************************/ function(e,t,r){function n(e,t){var r=this.__data__;if(r instanceof o){var n=r.__data__;if(!a||n.length<l-1)return n.push([e,t]),this.size=++r.size,this;r=this.__data__=new s(n)}return r.set(e,t),this.size=r.size,this}var o=r(/*! ./_ListCache */53),a=r(/*! ./_Map */110),s=r(/*! ./_MapCache */111),l=200;e.exports=n},/*!************************************!*\ !*** ./~/lodash/_strictIndexOf.js ***! \************************************/ function(e,t){function r(e,t,r){for(var n=r-1,o=e.length;++n<o;)if(e[n]===t)return n;return-1}e.exports=r},/*!************************************!*\ !*** ./~/lodash/_stringToArray.js ***! \************************************/ function(e,t,r){function n(e){return a(e)?s(e):o(e)}var o=r(/*! ./_asciiToArray */360),a=r(/*! ./_hasUnicode */246),s=r(/*! ./_unicodeToArray */472);e.exports=n},/*!*************************************!*\ !*** ./~/lodash/_unicodeToArray.js ***! \*************************************/ function(e,t){function r(e){return e.match(O)||[]}var n="\\ud800-\\udfff",o="\\u0300-\\u036f",a="\\ufe20-\\ufe2f",s="\\u20d0-\\u20ff",l=o+a+s,u="\\ufe0e\\ufe0f",i="["+n+"]",c="["+l+"]",p="\\ud83c[\\udffb-\\udfff]",d="(?:"+c+"|"+p+")",f="[^"+n+"]",y="(?:\\ud83c[\\udde6-\\uddff]){2}",m="[\\ud800-\\udbff][\\udc00-\\udfff]",h="\\u200d",v=d+"?",b="["+u+"]?",g="(?:"+h+"(?:"+[f,y,m].join("|")+")"+b+v+")*",P=b+v+g,T="(?:"+[f+c+"?",c,y,m,i].join("|")+")",O=RegExp(p+"(?="+p+")|"+T+P,"g");e.exports=r},/*!***********************************!*\ !*** ./~/lodash/_unicodeWords.js ***! \***********************************/ function(e,t){function r(e){return e.match(F)||[]}var n="\\ud800-\\udfff",o="\\u0300-\\u036f",a="\\ufe20-\\ufe2f",s="\\u20d0-\\u20ff",l=o+a+s,u="\\u2700-\\u27bf",i="a-z\\xdf-\\xf6\\xf8-\\xff",c="\\xac\\xb1\\xd7\\xf7",p="\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf",d="\\u2000-\\u206f",f=" \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",y="A-Z\\xc0-\\xd6\\xd8-\\xde",m="\\ufe0e\\ufe0f",h=c+p+d+f,v="['’]",b="["+h+"]",g="["+l+"]",P="\\d+",T="["+u+"]",O="["+i+"]",_="[^"+n+h+P+u+i+y+"]",E="\\ud83c[\\udffb-\\udfff]",j="(?:"+g+"|"+E+")",w="[^"+n+"]",S="(?:\\ud83c[\\udde6-\\uddff]){2}",M="[\\ud800-\\udbff][\\udc00-\\udfff]",x="["+y+"]",k="\\u200d",A="(?:"+O+"|"+_+")",C="(?:"+x+"|"+_+")",N="(?:"+v+"(?:d|ll|m|re|s|t|ve))?",I="(?:"+v+"(?:D|LL|M|RE|S|T|VE))?",K=j+"?",L="["+m+"]?",U="(?:"+k+"(?:"+[w,S,M].join("|")+")"+L+K+")*",D="\\d*(?:(?:1st|2nd|3rd|(?![123])\\dth)\\b)",R="\\d*(?:(?:1ST|2ND|3RD|(?![123])\\dTH)\\b)",z=L+K+U,W="(?:"+[T,S,M].join("|")+")"+z,F=RegExp([x+"?"+O+"+"+N+"(?="+[b,x,"$"].join("|")+")",C+"+"+I+"(?="+[b,x+A,"$"].join("|")+")",x+"?"+A+"+"+N,x+"+"+I,R,D,P,W].join("|"),"g");e.exports=r},/*!****************************************!*\ !*** ./~/lodash/_updateWrapDetails.js ***! \****************************************/ function(e,t,r){function n(e,t){return o(m,function(r){var n="_."+r[0];t&r[1]&&!a(e,n)&&e.push(n)}),e.sort()}var o=r(/*! ./_arrayEach */36),a=r(/*! ./_arrayIncludes */56),s=1,l=2,u=8,i=16,c=32,p=64,d=128,f=256,y=512,m=[["ary",d],["bind",s],["bindKey",l],["curry",u],["curryRight",i],["flip",y],["partial",c],["partialRight",p],["rearg",f]];e.exports=n},/*!***********************************!*\ !*** ./~/lodash/_wrapperClone.js ***! \***********************************/ function(e,t,r){function n(e){if(e instanceof o)return e.clone();var t=new a(e.__wrapped__,e.__chain__);return t.__actions__=s(e.__actions__),t.__index__=e.__index__,t.__values__=e.__values__,t}var o=r(/*! ./_LazyWrapper */108),a=r(/*! ./_LodashWrapper */109),s=r(/*! ./_copyArray */65);e.exports=n},/*!*************************!*\ !*** ./~/lodash/ary.js ***! \*************************/ function(e,t,r){function n(e,t,r){return t=r?void 0:t,t=e&&null==t?e.length:t,o(e,a,void 0,void 0,void 0,void 0,t)}var o=r(/*! ./_createWrap */38),a=128;e.exports=n},/*!****************************!*\ !*** ./~/lodash/assign.js ***! \****************************/ function(e,t,r){var n=r(/*! ./_assignValue */58),o=r(/*! ./_copyObject */33),a=r(/*! ./_createAssigner */412),s=r(/*! ./isArrayLike */14),l=r(/*! ./_isPrototype */40),u=r(/*! ./keys */9),i=Object.prototype,c=i.hasOwnProperty,p=a(function(e,t){if(l(t)||s(t))return void o(t,u(t),e);for(var r in t)c.call(t,r)&&n(e,r,t[r])});e.exports=p},/*!***************************!*\ !*** ./~/lodash/clamp.js ***! \***************************/ function(e,t,r){function n(e,t,r){return void 0===r&&(r=t,t=void 0),void 0!==r&&(r=a(r),r=r===r?r:0),void 0!==t&&(t=a(t),t=t===t?t:0),o(a(e),t,r)}var o=r(/*! ./_baseClamp */225),a=r(/*! ./toNumber */81);e.exports=n},/*!***************************!*\ !*** ./~/lodash/clone.js ***! \***************************/ function(e,t,r){function n(e){return o(e,a)}var o=r(/*! ./_baseClone */116),a=4;e.exports=n},/*!******************************!*\ !*** ./~/lodash/constant.js ***! \******************************/ function(e,t){function r(e){return function(){return e}}e.exports=r},/*!****************************!*\ !*** ./~/lodash/deburr.js ***! \****************************/ function(e,t,r){function n(e){return e=a(e),e&&e.replace(s,o).replace(d,"")}var o=r(/*! ./_deburrLetter */424),a=r(/*! ./toString */24),s=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,l="\\u0300-\\u036f",u="\\ufe20-\\ufe2f",i="\\u20d0-\\u20ff",c=l+u+i,p="["+c+"]",d=RegExp(p,"g");e.exports=n},/*!********************************!*\ !*** ./~/lodash/difference.js ***! \********************************/ function(e,t,r){var n=r(/*! ./_baseDifference */226),o=r(/*! ./_baseFlatten */60),a=r(/*! ./_baseRest */18),s=r(/*! ./isArrayLikeObject */77),l=a(function(e,t){return s(e)?n(e,o(t,1,s,!0)):[]});e.exports=l},/*!*******************************!*\ !*** ./~/lodash/dropRight.js ***! \*******************************/ function(e,t,r){function n(e,t,r){var n=null==e?0:e.length;return n?(t=r||void 0===t?1:a(t),t=n-t,o(e,0,t<0?0:t)):[]}var o=r(/*! ./_baseSlice */62),a=r(/*! ./toInteger */20);e.exports=n},/*!**********************************!*\ !*** ./~/lodash/escapeRegExp.js ***! \**********************************/ function(e,t,r){function n(e){return e=o(e),e&&s.test(e)?e.replace(a,"\\$&"):e}var o=r(/*! ./toString */24),a=/[\\^$.*+?()[\]{}|]/g,s=RegExp(a.source);e.exports=n},/*!*****************************!*\ !*** ./~/lodash/flatten.js ***! \*****************************/ function(e,t,r){function n(e){var t=null==e?0:e.length;return t?o(e,1):[]}var o=r(/*! ./_baseFlatten */60);e.exports=n},/*!**************************!*\ !*** ./~/lodash/flow.js ***! \**************************/ function(e,t,r){var n=r(/*! ./_createFlow */420),o=n();e.exports=o},/*!*****************************!*\ !*** ./~/lodash/forEach.js ***! \*****************************/ function(e,t,r){function n(e,t){var r=l(e)?o:a;return r(e,s(t))}var o=r(/*! ./_arrayEach */36),a=r(/*! ./_baseEach */32),s=r(/*! ./_castFunction */234),l=r(/*! ./isArray */4);e.exports=n},/*!*************************************!*\ !*** ./~/lodash/fp/_baseConvert.js ***! \*************************************/ function(e,t,r){function n(e,t){return 2==t?function(t,r){return e.apply(void 0,arguments)}:function(t){return e.apply(void 0,arguments)}}function o(e,t){return 2==t?function(t,r){return e(t,r)}:function(t){return e(t)}}function a(e){for(var t=e?e.length:0,r=Array(t);t--;)r[t]=e[t];return r}function s(e){return function(t){return e({},t)}}function l(e,t){return function(){for(var r=arguments.length,n=Array(r);r--;)n[r]=arguments[r];var o=n[t],a=n.length-1,s=n.slice(0,t);return o&&d.apply(s,o),t!=a&&d.apply(s,n.slice(t+1)),e.apply(this,s)}}function u(e,t){return function(){var r=arguments.length;if(r){for(var n=Array(r);r--;)n[r]=arguments[r];var o=n[0]=t.apply(void 0,n);return e.apply(void 0,n),o}}}function i(e,t,r,d){function f(e,t){if(S.cap){var r=c.iterateeRearg[e];if(r)return T(t,r);var n=!j&&c.iterateeAry[e];if(n)return P(t,n)}return t}function y(e,t,r){return M||S.curry&&r>1?U(t,r):t}function m(e,t,r){if(S.fixed&&(x||!c.skipFixed[e])){var n=c.methodSpread[e],o=n&&n.start;return void 0===o?I(t,r):l(t,o)}return t}function h(e,t,r){return S.rearg&&r>1&&(k||!c.skipRearg[e])?F(t,c.methodRearg[e]||c.aryRearg[r]):t}function v(e,t){t=B(t);for(var r=-1,n=t.length,o=n-1,a=L(Object(e)),s=a;null!=s&&++r<n;){var l=t[r],u=s[l];null!=u&&(s[t[r]]=L(r==o?u:Object(u))),s=s[l]}return a}function b(e){return H.runInContext.convert(e)(void 0)}function g(e,t){var r=c.aliasToReal[e]||e,n=c.remap[r]||r,o=d;return function(e){var a=j?C:N,s=j?C[n]:t,l=K(K({},o),e);return i(a,r,s,l)}}function P(e,t){return O(e,function(e){return"function"==typeof e?o(e,t):e})}function T(e,t){return O(e,function(e){var r=t.length;return n(F(o(e,r),t),r)})}function O(e,t){return function(){var r=arguments.length;if(!r)return e();for(var n=Array(r);r--;)n[r]=arguments[r];var o=S.rearg?0:r-1;return n[o]=t(n[o]),e.apply(void 0,n)}}function _(e,t){var r,n=c.aliasToReal[e]||e,o=t,l=q[n];return l?o=l(t):S.immutable&&(c.mutate.array[n]?o=u(t,a):c.mutate.object[n]?o=u(t,s(t)):c.mutate.set[n]&&(o=u(t,v))),D(Y,function(e){return D(c.aryMethod[e],function(t){if(n==t){var a=c.methodSpread[n],s=a&&a.afterRearg;return r=s?m(n,h(n,o,e),e):h(n,m(n,o,e),e),r=f(n,r),r=y(n,r,e),!1}}),!r}),r||(r=o),r==t&&(r=M?U(r,1):function(){return t.apply(this,arguments)}),r.convert=g(n,t),c.placeholder[n]&&(E=!0,r.placeholder=t.placeholder=A),r}var E,j="function"==typeof t,w=t===Object(t);if(w&&(d=r,r=t,t=void 0),null==r)throw new TypeError;d||(d={});var S={cap:!("cap"in d)||d.cap,curry:!("curry"in d)||d.curry,fixed:!("fixed"in d)||d.fixed,immutable:!("immutable"in d)||d.immutable,rearg:!("rearg"in d)||d.rearg},M="curry"in d&&d.curry,x="fixed"in d&&d.fixed,k="rearg"in d&&d.rearg,A=j?r:p,C=j?r.runInContext():void 0,N=j?r:{ary:e.ary,assign:e.assign,clone:e.clone,curry:e.curry,forEach:e.forEach,isArray:e.isArray,isFunction:e.isFunction,iteratee:e.iteratee,keys:e.keys,rearg:e.rearg,toInteger:e.toInteger,toPath:e.toPath},I=N.ary,K=N.assign,L=N.clone,U=N.curry,D=N.forEach,R=N.isArray,z=N.isFunction,W=N.keys,F=N.rearg,V=N.toInteger,B=N.toPath,Y=W(c.aryMethod),q={castArray:function(e){return function(){var t=arguments[0];return R(t)?e(a(t)):e.apply(void 0,arguments)}},iteratee:function(e){return function(){var t=arguments[0],r=arguments[1],n=e(t,r),a=n.length;return S.cap&&"number"==typeof r?(r=r>2?r-2:1,a&&a<=r?n:o(n,r)):n}},mixin:function(e){return function(t){var r=this;if(!z(r))return e(r,Object(t));var n=[];return D(W(t),function(e){z(t[e])&&n.push([e,r.prototype[e]])}),e(r,Object(t)),D(n,function(e){var t=e[1];z(t)?r.prototype[e[0]]=t:delete r.prototype[e[0]]}),r}},nthArg:function(e){return function(t){var r=t<0?1:V(t)+1;return U(e(t),r)}},rearg:function(e){return function(t,r){var n=r?r.length:0;return U(e(t,r),n)}},runInContext:function(t){return function(r){return i(e,t(r),d)}}};if(!w)return _(t,r);var H=r,G=[];return D(Y,function(e){D(c.aryMethod[e],function(e){var t=H[c.remap[e]||e];t&&G.push([e,_(e,t)])})}),D(W(H),function(e){var t=H[e];if("function"==typeof t){for(var r=G.length;r--;)if(G[r][0]==e)return;t.convert=g(e,t),G.push([e,t])}}),D(G,function(e){H[e[0]]=e[1]}),H.convert=b,E&&(H.placeholder=A),D(W(H),function(e){D(c.realToAlias[e]||[],function(t){H[t]=H[e]})}),H}var c=r(/*! ./_mapping */489),p=r(/*! ./placeholder */5),d=Array.prototype.push;e.exports=i},/*!*********************************!*\ !*** ./~/lodash/fp/_mapping.js ***! \*********************************/ function(e,t){t.aliasToReal={each:"forEach",eachRight:"forEachRight",entries:"toPairs",entriesIn:"toPairsIn",extend:"assignIn",extendAll:"assignInAll",extendAllWith:"assignInAllWith",extendWith:"assignInWith",first:"head",conforms:"conformsTo",matches:"isMatch",property:"get",__:"placeholder",F:"stubFalse",T:"stubTrue",all:"every",allPass:"overEvery",always:"constant",any:"some",anyPass:"overSome",apply:"spread",assoc:"set",assocPath:"set",complement:"negate",compose:"flowRight",contains:"includes",dissoc:"unset",dissocPath:"unset",dropLast:"dropRight",dropLastWhile:"dropRightWhile",equals:"isEqual",identical:"eq",indexBy:"keyBy",init:"initial",invertObj:"invert",juxt:"over",omitAll:"omit",nAry:"ary",path:"get",pathEq:"matchesProperty",pathOr:"getOr",paths:"at",pickAll:"pick",pipe:"flow",pluck:"map",prop:"get",propEq:"matchesProperty",propOr:"getOr",props:"at",symmetricDifference:"xor",symmetricDifferenceBy:"xorBy",symmetricDifferenceWith:"xorWith",takeLast:"takeRight",takeLastWhile:"takeRightWhile",unapply:"rest",unnest:"flatten",useWith:"overArgs",where:"conformsTo",whereEq:"isMatch",zipObj:"zipObject"},t.aryMethod={1:["assignAll","assignInAll","attempt","castArray","ceil","create","curry","curryRight","defaultsAll","defaultsDeepAll","floor","flow","flowRight","fromPairs","invert","iteratee","memoize","method","mergeAll","methodOf","mixin","nthArg","over","overEvery","overSome","rest","reverse","round","runInContext","spread","template","trim","trimEnd","trimStart","uniqueId","words","zipAll"],2:["add","after","ary","assign","assignAllWith","assignIn","assignInAllWith","at","before","bind","bindAll","bindKey","chunk","cloneDeepWith","cloneWith","concat","conformsTo","countBy","curryN","curryRightN","debounce","defaults","defaultsDeep","defaultTo","delay","difference","divide","drop","dropRight","dropRightWhile","dropWhile","endsWith","eq","every","filter","find","findIndex","findKey","findLast","findLastIndex","findLastKey","flatMap","flatMapDeep","flattenDepth","forEach","forEachRight","forIn","forInRight","forOwn","forOwnRight","get","groupBy","gt","gte","has","hasIn","includes","indexOf","intersection","invertBy","invoke","invokeMap","isEqual","isMatch","join","keyBy","lastIndexOf","lt","lte","map","mapKeys","mapValues","matchesProperty","maxBy","meanBy","merge","mergeAllWith","minBy","multiply","nth","omit","omitBy","overArgs","pad","padEnd","padStart","parseInt","partial","partialRight","partition","pick","pickBy","propertyOf","pull","pullAll","pullAt","random","range","rangeRight","rearg","reject","remove","repeat","restFrom","result","sampleSize","some","sortBy","sortedIndex","sortedIndexOf","sortedLastIndex","sortedLastIndexOf","sortedUniqBy","split","spreadFrom","startsWith","subtract","sumBy","take","takeRight","takeRightWhile","takeWhile","tap","throttle","thru","times","trimChars","trimCharsEnd","trimCharsStart","truncate","union","uniqBy","uniqWith","unset","unzipWith","without","wrap","xor","zip","zipObject","zipObjectDeep"],3:["assignInWith","assignWith","clamp","differenceBy","differenceWith","findFrom","findIndexFrom","findLastFrom","findLastIndexFrom","getOr","includesFrom","indexOfFrom","inRange","intersectionBy","intersectionWith","invokeArgs","invokeArgsMap","isEqualWith","isMatchWith","flatMapDepth","lastIndexOfFrom","mergeWith","orderBy","padChars","padCharsEnd","padCharsStart","pullAllBy","pullAllWith","rangeStep","rangeStepRight","reduce","reduceRight","replace","set","slice","sortedIndexBy","sortedLastIndexBy","transform","unionBy","unionWith","update","xorBy","xorWith","zipWith"],4:["fill","setWith","updateWith"]},t.aryRearg={2:[1,0],3:[2,0,1],4:[3,2,0,1]},t.iterateeAry={dropRightWhile:1,dropWhile:1,every:1,filter:1,find:1,findFrom:1,findIndex:1,findIndexFrom:1,findKey:1,findLast:1,findLastFrom:1,findLastIndex:1,findLastIndexFrom:1,findLastKey:1,flatMap:1,flatMapDeep:1,flatMapDepth:1,forEach:1,forEachRight:1,forIn:1,forInRight:1,forOwn:1,forOwnRight:1,map:1,mapKeys:1,mapValues:1,partition:1,reduce:2,reduceRight:2,reject:1,remove:1,some:1,takeRightWhile:1,takeWhile:1,times:1,transform:2},t.iterateeRearg={mapKeys:[1]},t.methodRearg={assignInAllWith:[1,0],assignInWith:[1,2,0],assignAllWith:[1,0],assignWith:[1,2,0],differenceBy:[1,2,0],differenceWith:[1,2,0],getOr:[2,1,0],intersectionBy:[1,2,0],intersectionWith:[1,2,0],isEqualWith:[1,2,0],isMatchWith:[2,1,0],mergeAllWith:[1,0],mergeWith:[1,2,0],padChars:[2,1,0],padCharsEnd:[2,1,0],padCharsStart:[2,1,0],pullAllBy:[2,1,0],pullAllWith:[2,1,0],rangeStep:[1,2,0],rangeStepRight:[1,2,0],setWith:[3,1,2,0],sortedIndexBy:[2,1,0],sortedLastIndexBy:[2,1,0],unionBy:[1,2,0],unionWith:[1,2,0],updateWith:[3,1,2,0],xorBy:[1,2,0],xorWith:[1,2,0],zipWith:[1,2,0]},t.methodSpread={assignAll:{start:0},assignAllWith:{start:0},assignInAll:{start:0},assignInAllWith:{start:0},defaultsAll:{start:0},defaultsDeepAll:{start:0},invokeArgs:{start:2},invokeArgsMap:{start:2},mergeAll:{start:0},mergeAllWith:{start:0},partial:{start:1},partialRight:{start:1},without:{start:1},zipAll:{start:0}},t.mutate={array:{fill:!0,pull:!0,pullAll:!0,pullAllBy:!0,pullAllWith:!0,pullAt:!0,remove:!0,reverse:!0},object:{assign:!0,assignAll:!0,assignAllWith:!0,assignIn:!0,assignInAll:!0,assignInAllWith:!0,assignInWith:!0,assignWith:!0,defaults:!0,defaultsAll:!0,defaultsDeep:!0,defaultsDeepAll:!0,merge:!0,mergeAll:!0,mergeAllWith:!0,mergeWith:!0},set:{set:!0,setWith:!0,unset:!0,update:!0,updateWith:!0}},t.placeholder={bind:!0,bindKey:!0,curry:!0,curryRight:!0,partial:!0,partialRight:!0},t.realToAlias=function(){var e=Object.prototype.hasOwnProperty,r=t.aliasToReal,n={};for(var o in r){var a=r[o];e.call(n,a)?n[a].push(o):n[a]=[o]}return n}(),t.remap={assignAll:"assign",assignAllWith:"assignWith",assignInAll:"assignIn",assignInAllWith:"assignInWith",curryN:"curry",curryRightN:"curryRight",defaultsAll:"defaults",defaultsDeepAll:"defaultsDeep",findFrom:"find",findIndexFrom:"findIndex",findLastFrom:"findLast",findLastIndexFrom:"findLastIndex",getOr:"get",includesFrom:"includes",indexOfFrom:"indexOf",invokeArgs:"invoke",invokeArgsMap:"invokeMap",lastIndexOfFrom:"lastIndexOf",mergeAll:"merge",mergeAllWith:"mergeWith",padChars:"pad",padCharsEnd:"padEnd",padCharsStart:"padStart",propertyOf:"get",rangeStep:"range",rangeStepRight:"rangeRight",restFrom:"rest",spreadFrom:"spread",trimChars:"trim",trimCharsEnd:"trimEnd",trimCharsStart:"trimStart",zipAll:"zip"},t.skipFixed={castArray:!0,flow:!0,flowRight:!0,iteratee:!0,mixin:!0,rearg:!0,runInContext:!0},t.skipRearg={add:!0,assign:!0,assignIn:!0,bind:!0,bindKey:!0,concat:!0,difference:!0,divide:!0,eq:!0,gt:!0,gte:!0,isEqual:!0,lt:!0,lte:!0,matchesProperty:!0,merge:!0,multiply:!0,overArgs:!0,partial:!0,partialRight:!0,propertyOf:!0,random:!0,range:!0,rangeRight:!0,subtract:!0,zip:!0,zipObject:!0,zipObjectDeep:!0}},/*!******************************!*\ !*** ./~/lodash/fp/_util.js ***! \******************************/ function(e,t,r){e.exports={ary:r(/*! ../ary */476),assign:r(/*! ../_baseAssign */224),clone:r(/*! ../clone */479),curry:r(/*! ../curry */260),forEach:r(/*! ../_arrayEach */36),isArray:r(/*! ../isArray */4),isFunction:r(/*! ../isFunction */28),iteratee:r(/*! ../iteratee */511),keys:r(/*! ../_baseKeys */119),rearg:r(/*! ../rearg */518),toInteger:r(/*! ../toInteger */20),toPath:r(/*! ../toPath */525)}},/*!********************************!*\ !*** ./~/lodash/fp/compact.js ***! \********************************/ function(e,t,r){var n=r(/*! ./convert */6),o=n("compact",r(/*! ../compact */259),r(/*! ./_falseOptions */19));o.placeholder=r(/*! ./placeholder */5),e.exports=o},/*!******************************!*\ !*** ./~/lodash/fp/curry.js ***! \******************************/ function(e,t,r){var n=r(/*! ./convert */6),o=n("curry",r(/*! ../curry */260));o.placeholder=r(/*! ./placeholder */5),e.exports=o},/*!***************************!*\ !*** ./~/lodash/fp/eq.js ***! \***************************/ function(e,t,r){var n=r(/*! ./convert */6),o=n("eq",r(/*! ../eq */42));o.placeholder=r(/*! ./placeholder */5),e.exports=o},/*!****************************!*\ !*** ./~/lodash/fp/get.js ***! \****************************/ function(e,t,r){var n=r(/*! ./convert */6),o=n("get",r(/*! ../get */34));o.placeholder=r(/*! ./placeholder */5),e.exports=o},/*!****************************!*\ !*** ./~/lodash/fp/has.js ***! \****************************/ function(e,t,r){var n=r(/*! ./convert */6),o=n("has",r(/*! ../has */27));o.placeholder=r(/*! ./placeholder */5),e.exports=o},/*!***********************************!*\ !*** ./~/lodash/fp/isFunction.js ***! \***********************************/ function(e,t,r){var n=r(/*! ./convert */6),o=n("isFunction",r(/*! ../isFunction */28),r(/*! ./_falseOptions */19));o.placeholder=r(/*! ./placeholder */5),e.exports=o},/*!******************************!*\ !*** ./~/lodash/fp/isNil.js ***! \******************************/ function(e,t,r){var n=r(/*! ./convert */6),o=n("isNil",r(/*! ../isNil */267),r(/*! ./_falseOptions */19));o.placeholder=r(/*! ./placeholder */5),e.exports=o},/*!*********************************!*\ !*** ./~/lodash/fp/isObject.js ***! \*********************************/ function(e,t,r){var n=r(/*! ./convert */6),o=n("isObject",r(/*! ../isObject */12),r(/*! ./_falseOptions */19));o.placeholder=r(/*! ./placeholder */5),e.exports=o},/*!**************************************!*\ !*** ./~/lodash/fp/isPlainObject.js ***! \**************************************/ function(e,t,r){var n=r(/*! ./convert */6),o=n("isPlainObject",r(/*! ../isPlainObject */132),r(/*! ./_falseOptions */19));o.placeholder=r(/*! ./placeholder */5),e.exports=o},/*!*****************************!*\ !*** ./~/lodash/fp/keys.js ***! \*****************************/ function(e,t,r){var n=r(/*! ./convert */6),o=n("keys",r(/*! ../keys */9),r(/*! ./_falseOptions */19));o.placeholder=r(/*! ./placeholder */5),e.exports=o},/*!****************************!*\ !*** ./~/lodash/fp/map.js ***! \****************************/ function(e,t,r){var n=r(/*! ./convert */6),o=n("map",r(/*! ../map */10));o.placeholder=r(/*! ./placeholder */5),e.exports=o},/*!****************************!*\ !*** ./~/lodash/fp/min.js ***! \****************************/ function(e,t,r){var n=r(/*! ./convert */6),o=n("min",r(/*! ../min */514),r(/*! ./_falseOptions */19));o.placeholder=r(/*! ./placeholder */5),e.exports=o},/*!*****************************!*\ !*** ./~/lodash/fp/pick.js ***! \*****************************/ function(e,t,r){var n=r(/*! ./convert */6),o=n("pick",r(/*! ../pick */80));o.placeholder=r(/*! ./placeholder */5),e.exports=o},/*!*******************************!*\ !*** ./~/lodash/fp/sortBy.js ***! \*******************************/ function(e,t,r){var n=r(/*! ./convert */6),o=n("sortBy",r(/*! ../sortBy */520));o.placeholder=r(/*! ./placeholder */5),e.exports=o},/*!***********************************!*\ !*** ./~/lodash/fp/startsWith.js ***! \***********************************/ function(e,t,r){var n=r(/*! ./convert */6),o=n("startsWith",r(/*! ../startsWith */275));o.placeholder=r(/*! ./placeholder */5),e.exports=o},/*!****************************!*\ !*** ./~/lodash/fp/sum.js ***! \****************************/ function(e,t,r){var n=r(/*! ./convert */6),o=n("sum",r(/*! ../sum */523),r(/*! ./_falseOptions */19));o.placeholder=r(/*! ./placeholder */5),e.exports=o},/*!*****************************!*\ !*** ./~/lodash/fp/take.js ***! \*****************************/ function(e,t,r){var n=r(/*! ./convert */6),o=n("take",r(/*! ../take */524));o.placeholder=r(/*! ./placeholder */5),e.exports=o},/*!*******************************!*\ !*** ./~/lodash/fp/values.js ***! \*******************************/ function(e,t,r){var n=r(/*! ./convert */6),o=n("values",r(/*! ../values */134),r(/*! ./_falseOptions */19));o.placeholder=r(/*! ./placeholder */5),e.exports=o},/*!*****************************!*\ !*** ./~/lodash/inRange.js ***! \*****************************/ function(e,t,r){function n(e,t,r){return t=a(t),void 0===r?(r=t,t=0):r=a(r),e=s(e),o(e,t,r)}var o=r(/*! ./_baseInRange */369),a=r(/*! ./toFinite */278),s=r(/*! ./toNumber */81);e.exports=n},/*!**********************************!*\ !*** ./~/lodash/intersection.js ***! \**********************************/ function(e,t,r){var n=r(/*! ./_arrayMap */17),o=r(/*! ./_baseIntersection */370),a=r(/*! ./_baseRest */18),s=r(/*! ./_castArrayLikeObject */397),l=a(function(e){var t=n(e,s);return t.length&&t[0]===e[0]?o(t):[]});e.exports=l},/*!******************************!*\ !*** ./~/lodash/iteratee.js ***! \******************************/ function(e,t,r){function n(e){return a("function"==typeof e?e:o(e,s))}var o=r(/*! ./_baseClone */116),a=r(/*! ./_baseIteratee */13),s=1;e.exports=n},/*!*******************************!*\ !*** ./~/lodash/mapValues.js ***! \*******************************/ function(e,t,r){function n(e,t){var r={};return t=s(t,3),a(e,function(e,n,a){o(r,n,t(e,n,a))}),r}var o=r(/*! ./_baseAssignValue */115),a=r(/*! ./_baseForOwn */117),s=r(/*! ./_baseIteratee */13);e.exports=n},/*!*****************************!*\ !*** ./~/lodash/memoize.js ***! \*****************************/ function(e,t,r){function n(e,t){if("function"!=typeof e||null!=t&&"function"!=typeof t)throw new TypeError(a);var r=function(){var n=arguments,o=t?t.apply(this,n):n[0],a=r.cache;if(a.has(o))return a.get(o);var s=e.apply(this,n);return r.cache=a.set(o,s)||a,s};return r.cache=new(n.Cache||o),r}var o=r(/*! ./_MapCache */111),a="Expected a function";n.Cache=o,e.exports=n},/*!*************************!*\ !*** ./~/lodash/min.js ***! \*************************/ function(e,t,r){function n(e){return e&&e.length?o(e,s,a):void 0}var o=r(/*! ./_baseExtremum */364),a=r(/*! ./_baseLt */379),s=r(/*! ./identity */23);e.exports=n},/*!*****************************!*\ !*** ./~/lodash/partial.js ***! \*****************************/ function(e,t,r){var n=r(/*! ./_baseRest */18),o=r(/*! ./_createWrap */38),a=r(/*! ./_getHolder */68),s=r(/*! ./_replaceHolders */41),l=32,u=n(function(e,t){var r=s(t,a(u));return o(e,l,void 0,t,r)});u.placeholder={},e.exports=u},/*!**********************************!*\ !*** ./~/lodash/partialRight.js ***! \**********************************/ function(e,t,r){var n=r(/*! ./_baseRest */18),o=r(/*! ./_createWrap */38),a=r(/*! ./_getHolder */68),s=r(/*! ./_replaceHolders */41),l=64,u=n(function(e,t){var r=s(t,a(u));return o(e,l,void 0,t,r)});u.placeholder={},e.exports=u},/*!******************************!*\ !*** ./~/lodash/property.js ***! \******************************/ function(e,t,r){function n(e){return s(e)?o(l(e)):a(e)}var o=r(/*! ./_baseProperty */385),a=r(/*! ./_basePropertyDeep */386),s=r(/*! ./_isKey */125),l=r(/*! ./_toKey */22);e.exports=n},/*!***************************!*\ !*** ./~/lodash/rearg.js ***! \***************************/ function(e,t,r){var n=r(/*! ./_createWrap */38),o=r(/*! ./_flatRest */67),a=256,s=o(function(e,t){return n(e,a,void 0,void 0,void 0,t)});e.exports=s},/*!***************************!*\ !*** ./~/lodash/round.js ***! \***************************/ function(e,t,r){var n=r(/*! ./_createRound */422),o=n("round");e.exports=o},/*!****************************!*\ !*** ./~/lodash/sortBy.js ***! \****************************/ function(e,t,r){var n=r(/*! ./_baseFlatten */60),o=r(/*! ./_baseOrderBy */382),a=r(/*! ./_baseRest */18),s=r(/*! ./_isIterateeCall */71),l=a(function(e,t){if(null==e)return[];var r=t.length;return r>1&&s(e,t[0],t[1])?t=[]:r>2&&s(t[0],t[1],t[2])&&(t=[t[0]]),o(e,n(t,1),[])});e.exports=l},/*!*******************************!*\ !*** ./~/lodash/startCase.js ***! \*******************************/ function(e,t,r){var n=r(/*! ./_createCompounder */417),o=r(/*! ./upperFirst */528),a=n(function(e,t,r){return e+(r?" ":"")+o(t)});e.exports=a},/*!*******************************!*\ !*** ./~/lodash/stubFalse.js ***! \*******************************/ function(e,t){function r(){return!1}e.exports=r},/*!*************************!*\ !*** ./~/lodash/sum.js ***! \*************************/ function(e,t,r){function n(e){return e&&e.length?o(e,a):0}var o=r(/*! ./_baseSum */393),a=r(/*! ./identity */23);e.exports=n},/*!**************************!*\ !*** ./~/lodash/take.js ***! \**************************/ function(e,t,r){function n(e,t,r){return e&&e.length?(t=r||void 0===t?1:a(t),o(e,0,t<0?0:t)):[]}var o=r(/*! ./_baseSlice */62),a=r(/*! ./toInteger */20);e.exports=n},/*!****************************!*\ !*** ./~/lodash/toPath.js ***! \****************************/ function(e,t,r){function n(e){return s(e)?o(e,i):l(e)?[e]:a(u(c(e)))}var o=r(/*! ./_arrayMap */17),a=r(/*! ./_copyArray */65),s=r(/*! ./isArray */4),l=r(/*! ./isSymbol */29),u=r(/*! ./_stringToPath */257),i=r(/*! ./_toKey */22),c=r(/*! ./toString */24);e.exports=n},/*!*******************************!*\ !*** ./~/lodash/transform.js ***! \*******************************/ function(e,t,r){function n(e,t,r){var n=i(e),y=n||c(e)||f(e);if(t=l(t,4),null==r){var m=e&&e.constructor;r=y?n?new m:[]:d(e)&&p(m)?a(u(e)):{}}return(y?o:s)(e,function(e,n,o){return t(r,e,n,o)}),r}var o=r(/*! ./_arrayEach */36),a=r(/*! ./_baseCreate */37),s=r(/*! ./_baseForOwn */117),l=r(/*! ./_baseIteratee */13),u=r(/*! ./_getPrototype */70),i=r(/*! ./isArray */4),c=r(/*! ./isBuffer */43),p=r(/*! ./isFunction */28),d=r(/*! ./isObject */12),f=r(/*! ./isTypedArray */79);e.exports=n},/*!***************************!*\ !*** ./~/lodash/union.js ***! \***************************/ function(e,t,r){var n=r(/*! ./_baseFlatten */60),o=r(/*! ./_baseRest */18),a=r(/*! ./_baseUniq */394),s=r(/*! ./isArrayLikeObject */77),l=o(function(e){return a(n(e,1,s,!0))});e.exports=l},/*!********************************!*\ !*** ./~/lodash/upperFirst.js ***! \********************************/ function(e,t,r){var n=r(/*! ./_createCaseFirst */416),o=n("toUpperCase");e.exports=o},/*!***************************!*\ !*** ./~/lodash/words.js ***! \***************************/ function(e,t,r){function n(e,t,r){return e=s(e),t=r?void 0:t,void 0===t?a(e)?l(e):o(e):e.match(t)||[]}var o=r(/*! ./_asciiWords */361),a=r(/*! ./_hasUnicodeWord */432),s=r(/*! ./toString */24),l=r(/*! ./_unicodeWords */473);e.exports=n},/*!***********************************!*\ !*** ./~/lodash/wrapperLodash.js ***! \***********************************/ function(e,t,r){function n(e){if(u(e)&&!l(e)&&!(e instanceof o)){if(e instanceof a)return e;if(p.call(e,"__wrapped__"))return i(e)}return new a(e)}var o=r(/*! ./_LazyWrapper */108),a=r(/*! ./_LodashWrapper */109),s=r(/*! ./_baseLodash */120),l=r(/*! ./isArray */4),u=r(/*! ./isObjectLike */15),i=r(/*! ./_wrapperClone */475),c=Object.prototype,p=c.hasOwnProperty;n.prototype=s.prototype,n.prototype.constructor=n,e.exports=n},/*!***********************!*\ !*** ./~/ms/index.js ***! \***********************/ function(e,t){function r(e){if(e=String(e),!(e.length>1e4)){var t=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(e);if(t){var r=parseFloat(t[1]),n=(t[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return r*c;case"days":case"day":case"d":return r*i;case"hours":case"hour":case"hrs":case"hr":case"h":return r*u;case"minutes":case"minute":case"mins":case"min":case"m":return r*l;case"seconds":case"second":case"secs":case"sec":case"s":return r*s;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}}}function n(e){return e>=i?Math.round(e/i)+"d":e>=u?Math.round(e/u)+"h":e>=l?Math.round(e/l)+"m":e>=s?Math.round(e/s)+"s":e+"ms"}function o(e){return a(e,i,"day")||a(e,u,"hour")||a(e,l,"minute")||a(e,s,"second")||e+" ms"}function a(e,t,r){if(!(e<t))return e<1.5*t?Math.floor(e/t)+" "+r:Math.ceil(e/t)+" "+r+"s"}var s=1e3,l=60*s,u=60*l,i=24*u,c=365.25*i;e.exports=function(e,t){t=t||{};var a=typeof e;if("string"===a&&e.length>0)return r(e);if("number"===a&&isNaN(e)===!1)return t.long?o(e):n(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))}},/*!***************************!*\ !*** external "ReactDOM" ***! \***************************/ function(e,r){e.exports=t}])});
app/javascript/mastodon/features/status/components/card.js
abcang/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import Immutable from 'immutable'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { FormattedMessage } from 'react-intl'; import punycode from 'punycode'; import classnames from 'classnames'; import Icon from 'mastodon/components/icon'; import { useBlurhash } from 'mastodon/initial_state'; import Blurhash from 'mastodon/components/blurhash'; import { debounce } from 'lodash'; const IDNA_PREFIX = 'xn--'; const decodeIDNA = domain => { return domain .split('.') .map(part => part.indexOf(IDNA_PREFIX) === 0 ? punycode.decode(part.slice(IDNA_PREFIX.length)) : part) .join('.'); }; const getHostname = url => { const parser = document.createElement('a'); parser.href = url; return parser.hostname; }; const trim = (text, len) => { const cut = text.indexOf(' ', len); if (cut === -1) { return text; } return text.substring(0, cut) + (text.length > len ? '…' : ''); }; const domParser = new DOMParser(); const addAutoPlay = html => { const document = domParser.parseFromString(html, 'text/html').documentElement; const iframe = document.querySelector('iframe'); if (iframe) { if (iframe.src.indexOf('?') !== -1) { iframe.src += '&'; } else { iframe.src += '?'; } iframe.src += 'autoplay=1&auto_play=1'; // DOM parser creates html/body elements around original HTML fragment, // so we need to get innerHTML out of the body and not the entire document return document.querySelector('body').innerHTML; } return html; }; export default class Card extends React.PureComponent { static propTypes = { card: ImmutablePropTypes.map, maxDescription: PropTypes.number, onOpenMedia: PropTypes.func.isRequired, compact: PropTypes.bool, defaultWidth: PropTypes.number, cacheWidth: PropTypes.func, sensitive: PropTypes.bool, }; static defaultProps = { maxDescription: 50, compact: false, }; state = { width: this.props.defaultWidth || 280, previewLoaded: false, embedded: false, revealed: !this.props.sensitive, }; componentWillReceiveProps (nextProps) { if (!Immutable.is(this.props.card, nextProps.card)) { this.setState({ embedded: false, previewLoaded: false }); } if (this.props.sensitive !== nextProps.sensitive) { this.setState({ revealed: !nextProps.sensitive }); } } componentDidMount () { window.addEventListener('resize', this.handleResize, { passive: true }); } componentWillUnmount () { window.removeEventListener('resize', this.handleResize); } _setDimensions () { const width = this.node.offsetWidth; if (this.props.cacheWidth) { this.props.cacheWidth(width); } this.setState({ width }); } handleResize = debounce(() => { if (this.node) { this._setDimensions(); } }, 250, { trailing: true, }); handlePhotoClick = () => { const { card, onOpenMedia } = this.props; onOpenMedia( Immutable.fromJS([ { type: 'image', url: card.get('embed_url'), description: card.get('title'), meta: { original: { width: card.get('width'), height: card.get('height'), }, }, }, ]), 0, ); }; handleEmbedClick = () => { const { card } = this.props; if (card.get('type') === 'photo') { this.handlePhotoClick(); } else { this.setState({ embedded: true }); } } setRef = c => { this.node = c; if (this.node) { this._setDimensions(); } } handleImageLoad = () => { this.setState({ previewLoaded: true }); } handleReveal = e => { e.preventDefault(); e.stopPropagation(); this.setState({ revealed: true }); } renderVideo () { const { card } = this.props; const content = { __html: addAutoPlay(card.get('html')) }; const { width } = this.state; const ratio = card.get('width') / card.get('height'); const height = width / ratio; return ( <div ref={this.setRef} className='status-card__image status-card-video' dangerouslySetInnerHTML={content} style={{ height }} /> ); } render () { const { card, maxDescription, compact } = this.props; const { width, embedded, revealed } = this.state; if (card === null) { return null; } const provider = card.get('provider_name').length === 0 ? decodeIDNA(getHostname(card.get('url'))) : card.get('provider_name'); const horizontal = (!compact && card.get('width') > card.get('height') && (card.get('width') + 100 >= width)) || card.get('type') !== 'link' || embedded; const interactive = card.get('type') !== 'link'; const className = classnames('status-card', { horizontal, compact, interactive }); const title = interactive ? <a className='status-card__title' href={card.get('url')} title={card.get('title')} rel='noopener noreferrer' target='_blank'><strong>{card.get('title')}</strong></a> : <strong className='status-card__title' title={card.get('title')}>{card.get('title')}</strong>; const ratio = card.get('width') / card.get('height'); const height = (compact && !embedded) ? (width / (16 / 9)) : (width / ratio); const description = ( <div className='status-card__content'> {title} {!(horizontal || compact) && <p className='status-card__description'>{trim(card.get('description') || '', maxDescription)}</p>} <span className='status-card__host'>{provider}</span> </div> ); let embed = ''; let canvas = ( <Blurhash className={classnames('status-card__image-preview', { 'status-card__image-preview--hidden': revealed && this.state.previewLoaded, })} hash={card.get('blurhash')} dummy={!useBlurhash} /> ); let thumbnail = <img src={card.get('image')} alt='' style={{ width: horizontal ? width : null, height: horizontal ? height : null, visibility: revealed ? null : 'hidden' }} onLoad={this.handleImageLoad} className='status-card__image-image' />; let spoilerButton = ( <button type='button' onClick={this.handleReveal} className='spoiler-button__overlay'> <span className='spoiler-button__overlay__label'><FormattedMessage id='status.sensitive_warning' defaultMessage='Sensitive content' /></span> </button> ); spoilerButton = ( <div className={classnames('spoiler-button', { 'spoiler-button--minified': revealed })}> {spoilerButton} </div> ); if (interactive) { if (embedded) { embed = this.renderVideo(); } else { let iconVariant = 'play'; if (card.get('type') === 'photo') { iconVariant = 'search-plus'; } embed = ( <div className='status-card__image'> {canvas} {thumbnail} {revealed && ( <div className='status-card__actions'> <div> <button onClick={this.handleEmbedClick}><Icon id={iconVariant} /></button> {horizontal && <a href={card.get('url')} target='_blank' rel='noopener noreferrer'><Icon id='external-link' /></a>} </div> </div> )} {!revealed && spoilerButton} </div> ); } return ( <div className={className} ref={this.setRef} onClick={revealed ? null : this.handleReveal} role={revealed ? 'button' : null}> {embed} {!compact && description} </div> ); } else if (card.get('image')) { embed = ( <div className='status-card__image'> {canvas} {thumbnail} </div> ); } else { embed = ( <div className='status-card__image'> <Icon id='file-text' /> </div> ); } return ( <a href={card.get('url')} className={className} target='_blank' rel='noopener noreferrer' ref={this.setRef}> {embed} {description} </a> ); } }
ajax/libs/extjs/4.2.1/src/form/Panel.js
Mrkebubun/cdnjs
/* This file is part of Ext JS 4.2 Copyright (c) 2011-2013 Sencha Inc Contact: http://www.sencha.com/contact GNU General Public License Usage This file may be used under the terms of the GNU General Public License version 3.0 as published by the Free Software Foundation and appearing in the file LICENSE included in the packaging of this file. Please review the following information to ensure the GNU General Public License version 3.0 requirements will be met: http://www.gnu.org/copyleft/gpl.html. If you are unsure which license is appropriate for your use, please contact the sales department at http://www.sencha.com/contact. Build date: 2013-05-16 14:36:50 (f9be68accb407158ba2b1be2c226a6ce1f649314) */ /** * @docauthor Jason Johnston <[email protected]> * * FormPanel provides a standard container for forms. It is essentially a standard {@link Ext.panel.Panel} which * automatically creates a {@link Ext.form.Basic BasicForm} for managing any {@link Ext.form.field.Field} * objects that are added as descendants of the panel. It also includes conveniences for configuring and * working with the BasicForm and the collection of Fields. * * # Layout * * By default, FormPanel is configured with `{@link Ext.layout.container.Anchor layout:'anchor'}` for * the layout of its immediate child items. This can be changed to any of the supported container layouts. * The layout of sub-containers is configured in {@link Ext.container.Container#layout the standard way}. * * # BasicForm * * Although **not listed** as configuration options of FormPanel, the FormPanel class accepts all * of the config options supported by the {@link Ext.form.Basic} class, and will pass them along to * the internal BasicForm when it is created. * * The following events fired by the BasicForm will be re-fired by the FormPanel and can therefore be * listened for on the FormPanel itself: * * - {@link Ext.form.Basic#beforeaction beforeaction} * - {@link Ext.form.Basic#actionfailed actionfailed} * - {@link Ext.form.Basic#actioncomplete actioncomplete} * - {@link Ext.form.Basic#validitychange validitychange} * - {@link Ext.form.Basic#dirtychange dirtychange} * * # Field Defaults * * The {@link #fieldDefaults} config option conveniently allows centralized configuration of default values * for all fields added as descendants of the FormPanel. Any config option recognized by implementations * of {@link Ext.form.Labelable} may be included in this object. See the {@link #fieldDefaults} documentation * for details of how the defaults are applied. * * # Form Validation * * With the default configuration, form fields are validated on-the-fly while the user edits their values. * This can be controlled on a per-field basis (or via the {@link #fieldDefaults} config) with the field * config properties {@link Ext.form.field.Field#validateOnChange} and {@link Ext.form.field.Base#checkChangeEvents}, * and the FormPanel's config properties {@link #pollForChanges} and {@link #pollInterval}. * * Any component within the FormPanel can be configured with `formBind: true`. This will cause that * component to be automatically disabled when the form is invalid, and enabled when it is valid. This is most * commonly used for Button components to prevent submitting the form in an invalid state, but can be used on * any component type. * * For more information on form validation see the following: * * - {@link Ext.form.field.Field#validateOnChange} * - {@link #pollForChanges} and {@link #pollInterval} * - {@link Ext.form.field.VTypes} * - {@link Ext.form.Basic#doAction BasicForm.doAction clientValidation notes} * * # Form Submission * * By default, Ext Forms are submitted through Ajax, using {@link Ext.form.action.Action}. See the documentation for * {@link Ext.form.Basic} for details. * * # Example usage * * @example * Ext.create('Ext.form.Panel', { * title: 'Simple Form', * bodyPadding: 5, * width: 350, * * // The form will submit an AJAX request to this URL when submitted * url: 'save-form.php', * * // Fields will be arranged vertically, stretched to full width * layout: 'anchor', * defaults: { * anchor: '100%' * }, * * // The fields * defaultType: 'textfield', * items: [{ * fieldLabel: 'First Name', * name: 'first', * allowBlank: false * },{ * fieldLabel: 'Last Name', * name: 'last', * allowBlank: false * }], * * // Reset and Submit buttons * buttons: [{ * text: 'Reset', * handler: function() { * this.up('form').getForm().reset(); * } * }, { * text: 'Submit', * formBind: true, //only enabled once the form is valid * disabled: true, * handler: function() { * var form = this.up('form').getForm(); * if (form.isValid()) { * form.submit({ * success: function(form, action) { * Ext.Msg.alert('Success', action.result.msg); * }, * failure: function(form, action) { * Ext.Msg.alert('Failed', action.result.msg); * } * }); * } * } * }], * renderTo: Ext.getBody() * }); * */ Ext.define('Ext.form.Panel', { extend:'Ext.panel.Panel', mixins: { fieldAncestor: 'Ext.form.FieldAncestor' }, alias: 'widget.form', alternateClassName: ['Ext.FormPanel', 'Ext.form.FormPanel'], requires: ['Ext.form.Basic', 'Ext.util.TaskRunner'], /** * @cfg {Boolean} pollForChanges * If set to `true`, sets up an interval task (using the {@link #pollInterval}) in which the * panel's fields are repeatedly checked for changes in their values. This is in addition to the normal detection * each field does on its own input element, and is not needed in most cases. It does, however, provide a * means to absolutely guarantee detection of all changes including some edge cases in some browsers which * do not fire native events. Defaults to `false`. */ /** * @cfg {Number} pollInterval * Interval in milliseconds at which the form's fields are checked for value changes. Only used if * the {@link #pollForChanges} option is set to `true`. Defaults to 500 milliseconds. */ /** * @cfg {Ext.enums.Layout/Object} layout * The {@link Ext.container.Container#layout} for the form panel's immediate child items. */ layout: 'anchor', ariaRole: 'form', basicFormConfigs: [ 'api', 'baseParams', 'errorReader', 'jsonSubmit', 'method', 'paramOrder', 'paramsAsHash', 'reader', 'standardSubmit', 'timeout', 'trackResetOnLoad', 'url', 'waitMsgTarget', 'waitTitle' ], initComponent: function() { var me = this; if (me.frame) { me.border = false; } me.initFieldAncestor(); me.callParent(); me.relayEvents(me.form, [ /** * @event beforeaction * @inheritdoc Ext.form.Basic#beforeaction */ 'beforeaction', /** * @event actionfailed * @inheritdoc Ext.form.Basic#actionfailed */ 'actionfailed', /** * @event actioncomplete * @inheritdoc Ext.form.Basic#actioncomplete */ 'actioncomplete', /** * @event validitychange * @inheritdoc Ext.form.Basic#validitychange */ 'validitychange', /** * @event dirtychange * @inheritdoc Ext.form.Basic#dirtychange */ 'dirtychange' ]); // Start polling if configured if (me.pollForChanges) { me.startPolling(me.pollInterval || 500); } }, initItems: function() { // Create the BasicForm this.callParent(); this.initMonitor(); this.form = this.createForm(); }, // Initialize the BasicForm after all layouts have been completed. afterFirstLayout: function() { this.callParent(arguments); this.form.initialize(); }, /** * @private */ createForm: function() { var cfg = {}, props = this.basicFormConfigs, len = props.length, i = 0, prop; for (; i < len; ++i) { prop = props[i]; cfg[prop] = this[prop]; } return new Ext.form.Basic(this, cfg); }, /** * Provides access to the {@link Ext.form.Basic Form} which this Panel contains. * @return {Ext.form.Basic} The {@link Ext.form.Basic Form} which this Panel contains. */ getForm: function() { return this.form; }, /** * Loads an {@link Ext.data.Model} into this form (internally just calls {@link Ext.form.Basic#loadRecord}) * See also {@link Ext.form.Basic#trackResetOnLoad trackResetOnLoad}. * @param {Ext.data.Model} record The record to load * @return {Ext.form.Basic} The Ext.form.Basic attached to this FormPanel */ loadRecord: function(record) { return this.getForm().loadRecord(record); }, /** * Returns the currently loaded Ext.data.Model instance if one was loaded via {@link #loadRecord}. * @return {Ext.data.Model} The loaded instance */ getRecord: function() { return this.getForm().getRecord(); }, /** * Persists the values in this form into the passed {@link Ext.data.Model} object in a beginEdit/endEdit block. * If the record is not specified, it will attempt to update (if it exists) the record provided to {@link #loadRecord}. * @param {Ext.data.Model} [record] The record to edit * @return {Ext.form.Basic} The Ext.form.Basic attached to this FormPanel */ updateRecord: function(record) { return this.getForm().updateRecord(record); }, /** * Convenience function for fetching the current value of each field in the form. This is the same as calling * {@link Ext.form.Basic#getValues this.getForm().getValues()}. * * @inheritdoc Ext.form.Basic#getValues */ getValues: function(asString, dirtyOnly, includeEmptyText, useDataValues) { return this.getForm().getValues(asString, dirtyOnly, includeEmptyText, useDataValues); }, /** * Convenience function to check if the form has any dirty fields. This is the same as calling * {@link Ext.form.Basic#isDirty this.getForm().isDirty()}. * * @inheritdoc Ext.form.Basic#isDirty */ isDirty: function () { return this.form.isDirty(); }, /** * Convenience function to check if the form has all valid fields. This is the same as calling * {@link Ext.form.Basic#isValid this.getForm().isValid()}. * * @inheritdoc Ext.form.Basic#isValid */ isValid: function () { return this.form.isValid(); }, /** * Convenience function to check if the form has any invalid fields. This is the same as calling * {@link Ext.form.Basic#hasInvalidField this.getForm().hasInvalidField()}. * * @inheritdoc Ext.form.Basic#hasInvalidField */ hasInvalidField: function () { return this.form.hasInvalidField(); }, beforeDestroy: function() { this.stopPolling(); this.form.destroy(); this.callParent(); }, /** * This is a proxy for the underlying BasicForm's {@link Ext.form.Basic#load} call. * @param {Object} options The options to pass to the action (see {@link Ext.form.Basic#load} and * {@link Ext.form.Basic#doAction} for details) */ load: function(options) { this.form.load(options); }, /** * This is a proxy for the underlying BasicForm's {@link Ext.form.Basic#submit} call. * @param {Object} options The options to pass to the action (see {@link Ext.form.Basic#submit} and * {@link Ext.form.Basic#doAction} for details) */ submit: function(options) { this.form.submit(options); }, /** * Start an interval task to continuously poll all the fields in the form for changes in their * values. This is normally started automatically by setting the {@link #pollForChanges} config. * @param {Number} interval The interval in milliseconds at which the check should run. */ startPolling: function(interval) { this.stopPolling(); var task = new Ext.util.TaskRunner(interval); task.start({ interval: 0, run: this.checkChange, scope: this }); this.pollTask = task; }, /** * Stop a running interval task that was started by {@link #startPolling}. */ stopPolling: function() { var task = this.pollTask; if (task) { task.stopAll(); delete this.pollTask; } }, /** * Forces each field within the form panel to * {@link Ext.form.field.Field#checkChange check if its value has changed}. */ checkChange: function() { var fields = this.form.getFields().items, f, fLen = fields.length; for (f = 0; f < fLen; f++) { fields[f].checkChange(); } } });
app/containers/AcquisitionPage/form.email.js
rvsiqueira/client
import React from 'react'; import { reduxForm, Field } from 'redux-form/immutable'; import RenderField from 'components/RenderField'; import FormFooter from 'components/FormFooter'; import messages from './messages'; import { FormattedMessage } from 'react-intl'; import asyncValidate from './asyncValidate'; import P from 'components/P'; import mail from '../../assets/icon/mail.svg'; import Header from 'components/Header'; import Body from 'components/Body'; const validate = values => { const errors = {}; // Email if (!values.get('email')) { errors.email = 'Obrigatório'; } else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values.get('email'))) { errors.email = 'Email inválido'; } return errors; }; const Email = (props) => { const { handleSubmit, submitting, valid, previousPage } = props; return ( <Body relaxed offsetExtra> <Header title={<FormattedMessage {...messages.group2} />} back={previousPage} /> <form onSubmit={handleSubmit}> <img src={mail} alt="mail" /> <P className="body1"> <FormattedMessage {...messages.emailLabelMessage} /> </P> <Field name="email" type="email" component={RenderField} placeholder="[email protected]" label={messages.emailHeadingMessage} /> <FormFooter disabled={submitting || !valid} /> </form> </Body> ); }; Email.propTypes = { handleSubmit: React.PropTypes.func, submitting: React.PropTypes.bool, valid: React.PropTypes.bool, previousPage: React.PropTypes.func, }; export default reduxForm({ form: 'wizard', destroyOnUnmount: false, validate, asyncValidate, asyncBlurFields: ['email'], })(Email);
src/assets/scripts/components/Frame.js
curlybracesco/pablo
import React, { Component } from 'react'; import ReactDOM from 'react-dom'; export default class Frame extends Component { buildLinkElements(stylesheetHrefs) { return stylesheetHrefs.map((styleHref) => { return <link href={styleHref} rel="stylesheet" /> }); } setFrameStyles(frame) { frame.contentDocument.body.style.margin = '10px'; frame.style.height = `${frame.contentDocument.body.scrollHeight}px`; } componentDidMount() { this.renderFrameContents(); } renderFrameContents() { const el = ReactDOM.findDOMNode(this); const doc = el.contentDocument; if(doc.readyState === 'complete') { ReactDOM.render(<div>{this.buildLinkElements(this.props.styles)}</div>, doc.head); ReactDOM.render(this.props.children, doc.body); this.setFrameStyles(el); } else { setTimeout(this.renderFrameContents, 0); } } componentDidUpdate() { this.renderFrameContents(); } componentWillUnmount() { React.unmountComponentAtNode(ReactDOM.findDOMNode(this).contentDocument.body); } render() { return <iframe scrolling="no" />; } }
docs/src/Root.js
Terminux/react-bootstrap
import React from 'react'; const Root = React.createClass({ statics: { /** * Get the list of pages that are renderable * * @returns {Array} */ getPages() { return [ 'index.html', 'introduction.html', 'getting-started.html', 'components.html', 'support.html' ]; } }, childContextTypes: { metadata: React.PropTypes.object }, getChildContext() { return {metadata: Root.propData}; }, render() { // Dump out our current props to a global object via a script tag so // when initialising the browser environment we can bootstrap from the // same props as what each page was rendered with. let browserInitScriptObj = { __html: `window.ASSET_BASE_URL = ${JSON.stringify(Root.assetBaseUrl)}; window.PROP_DATA = ${JSON.stringify(Root.propData)}; // console noop shim for IE8/9 (function (w) { var noop = function () {}; if (!w.console) { w.console = {}; ['log', 'info', 'warn', 'error'].forEach(function (method) { w.console[method] = noop; }); } }(window));` }; let head = { __html: `<title>React-Bootstrap</title> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="${Root.assetBaseUrl}/assets/bundle.css" rel="stylesheet"> <link href="${Root.assetBaseUrl}/assets/favicon.ico?v=2" type="image/x-icon" rel="shortcut icon"> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script> <script src="http://cdnjs.cloudflare.com/ajax/libs/es5-shim/3.4.0/es5-shim.js"></script> <script src="http://cdnjs.cloudflare.com/ajax/libs/es5-shim/3.4.0/es5-sham.js"></script> <![endif]-->` }; return ( <html> <head dangerouslySetInnerHTML={head} /> <body> {this.props.children} <script dangerouslySetInnerHTML={browserInitScriptObj} /> <script src={`${Root.assetBaseUrl}/assets/bundle.js`} /> </body> </html> ); } }); export default Root;
ajax/libs/forerunnerdb/1.3.790/fdb-core.js
tholu/cdnjs
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){ var Core = _dereq_('../lib/Core'), ShimIE8 = _dereq_('../lib/Shim.IE8'); if (typeof window !== 'undefined') { window.ForerunnerDB = Core; } module.exports = Core; },{"../lib/Core":6,"../lib/Shim.IE8":30}],2:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), sharedPathSolver = new Path(); var BinaryTree = function (data, compareFunc, hashFunc) { this.init.apply(this, arguments); }; BinaryTree.prototype.init = function (data, index, primaryKey, compareFunc, hashFunc) { this._store = []; this._keys = []; if (primaryKey !== undefined) { this.primaryKey(primaryKey); } if (index !== undefined) { this.index(index); } if (compareFunc !== undefined) { this.compareFunc(compareFunc); } if (hashFunc !== undefined) { this.hashFunc(hashFunc); } if (data !== undefined) { this.data(data); } }; Shared.addModule('BinaryTree', BinaryTree); Shared.mixin(BinaryTree.prototype, 'Mixin.ChainReactor'); Shared.mixin(BinaryTree.prototype, 'Mixin.Sorting'); Shared.mixin(BinaryTree.prototype, 'Mixin.Common'); Shared.synthesize(BinaryTree.prototype, 'compareFunc'); Shared.synthesize(BinaryTree.prototype, 'hashFunc'); Shared.synthesize(BinaryTree.prototype, 'indexDir'); Shared.synthesize(BinaryTree.prototype, 'primaryKey'); Shared.synthesize(BinaryTree.prototype, 'keys'); Shared.synthesize(BinaryTree.prototype, 'index', function (index) { if (index !== undefined) { if (this.debug()) { console.log('Setting index', index, sharedPathSolver.parse(index, true)); } // Convert the index object to an array of key val objects this.keys(sharedPathSolver.parse(index, true)); } return this.$super.call(this, index); }); /** * Remove all data from the binary tree. */ BinaryTree.prototype.clear = function () { delete this._data; delete this._left; delete this._right; this._store = []; }; /** * Sets this node's data object. All further inserted documents that * match this node's key and value will be pushed via the push() * method into the this._store array. When deciding if a new data * should be created left, right or middle (pushed) of this node the * new data is checked against the data set via this method. * @param val * @returns {*} */ BinaryTree.prototype.data = function (val) { if (val !== undefined) { this._data = val; if (this._hashFunc) { this._hash = this._hashFunc(val); } return this; } return this._data; }; /** * Pushes an item to the binary tree node's store array. * @param {*} val The item to add to the store. * @returns {*} */ BinaryTree.prototype.push = function (val) { if (val !== undefined) { this._store.push(val); return this; } return false; }; /** * Pulls an item from the binary tree node's store array. * @param {*} val The item to remove from the store. * @returns {*} */ BinaryTree.prototype.pull = function (val) { if (val !== undefined) { var index = this._store.indexOf(val); if (index > -1) { this._store.splice(index, 1); return this; } } return false; }; /** * Default compare method. Can be overridden. * @param a * @param b * @returns {number} * @private */ BinaryTree.prototype._compareFunc = function (a, b) { // Loop the index array var i, indexData, result = 0; for (i = 0; i < this._keys.length; i++) { indexData = this._keys[i]; if (indexData.value === 1) { result = this.sortAsc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path)); } else if (indexData.value === -1) { result = this.sortDesc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path)); } if (this.debug()) { console.log('Compared %s with %s order %d in path %s and result was %d', sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path), indexData.value, indexData.path, result); } if (result !== 0) { if (this.debug()) { console.log('Retuning result %d', result); } return result; } } if (this.debug()) { console.log('Retuning result %d', result); } return result; }; /** * Default hash function. Can be overridden. * @param obj * @private */ BinaryTree.prototype._hashFunc = function (obj) { /*var i, indexData, hash = ''; for (i = 0; i < this._keys.length; i++) { indexData = this._keys[i]; if (hash) { hash += '_'; } hash += obj[indexData.path]; } return hash;*/ return obj[this._keys[0].path]; }; /** * Removes (deletes reference to) either left or right child if the passed * node matches one of them. * @param {BinaryTree} node The node to remove. */ BinaryTree.prototype.removeChildNode = function (node) { if (this._left === node) { // Remove left delete this._left; } else if (this._right === node) { // Remove right delete this._right; } }; /** * Returns the branch this node matches (left or right). * @param node * @returns {String} */ BinaryTree.prototype.nodeBranch = function (node) { if (this._left === node) { return 'left'; } else if (this._right === node) { return 'right'; } }; /** * Inserts a document into the binary tree. * @param data * @returns {*} */ BinaryTree.prototype.insert = function (data) { var result, inserted, failed, i; if (data instanceof Array) { // Insert array of data inserted = []; failed = []; for (i = 0; i < data.length; i++) { if (this.insert(data[i])) { inserted.push(data[i]); } else { failed.push(data[i]); } } return { inserted: inserted, failed: failed }; } if (this.debug()) { console.log('Inserting', data); } if (!this._data) { if (this.debug()) { console.log('Node has no data, setting data', data); } // Insert into this node (overwrite) as there is no data this.data(data); //this.push(data); return true; } result = this._compareFunc(this._data, data); if (result === 0) { if (this.debug()) { console.log('Data is equal (currrent, new)', this._data, data); } //this.push(data); // Less than this node if (this._left) { // Propagate down the left branch this._left.insert(data); } else { // Assign to left branch this._left = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc); this._left._parent = this; } return true; } if (result === -1) { if (this.debug()) { console.log('Data is greater (currrent, new)', this._data, data); } // Greater than this node if (this._right) { // Propagate down the right branch this._right.insert(data); } else { // Assign to right branch this._right = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc); this._right._parent = this; } return true; } if (result === 1) { if (this.debug()) { console.log('Data is less (currrent, new)', this._data, data); } // Less than this node if (this._left) { // Propagate down the left branch this._left.insert(data); } else { // Assign to left branch this._left = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc); this._left._parent = this; } return true; } return false; }; BinaryTree.prototype.remove = function (data) { var pk = this.primaryKey(), result, removed, i; if (data instanceof Array) { // Insert array of data removed = []; for (i = 0; i < data.length; i++) { if (this.remove(data[i])) { removed.push(data[i]); } } return removed; } if (this.debug()) { console.log('Removing', data); } if (this._data[pk] === data[pk]) { // Remove this node return this._remove(this); } // Compare the data to work out which branch to send the remove command down result = this._compareFunc(this._data, data); if (result === -1 && this._right) { return this._right.remove(data); } if (result === 1 && this._left) { return this._left.remove(data); } return false; }; BinaryTree.prototype._remove = function (node) { var leftNode, rightNode; if (this._left) { // Backup branch data leftNode = this._left; rightNode = this._right; // Copy data from left node this._left = leftNode._left; this._right = leftNode._right; this._data = leftNode._data; this._store = leftNode._store; if (rightNode) { // Attach the rightNode data to the right-most node // of the leftNode leftNode.rightMost()._right = rightNode; } } else if (this._right) { // Backup branch data rightNode = this._right; // Copy data from right node this._left = rightNode._left; this._right = rightNode._right; this._data = rightNode._data; this._store = rightNode._store; } else { this.clear(); } return true; }; BinaryTree.prototype.leftMost = function () { if (!this._left) { return this; } else { return this._left.leftMost(); } }; BinaryTree.prototype.rightMost = function () { if (!this._right) { return this; } else { return this._right.rightMost(); } }; /** * Searches the binary tree for all matching documents based on the data * passed (query). * @param {Object} data The data / document to use for lookups. * @param {Object} options An options object. * @param {Operation} op An optional operation instance. Pass undefined * if not being used. * @param {Array=} resultArr The results passed between recursive calls. * Do not pass anything into this argument when calling externally. * @returns {*|Array} */ BinaryTree.prototype.lookup = function (data, options, op, resultArr) { var result = this._compareFunc(this._data, data); resultArr = resultArr || []; if (result === 0) { if (this._left) { this._left.lookup(data, options, op, resultArr); } resultArr.push(this._data); if (this._right) { this._right.lookup(data, options, op, resultArr); } } if (result === -1) { if (this._right) { this._right.lookup(data, options, op, resultArr); } } if (result === 1) { if (this._left) { this._left.lookup(data, options, op, resultArr); } } return resultArr; }; /** * Returns the entire binary tree ordered. * @param {String} type * @param resultArr * @returns {*|Array} */ BinaryTree.prototype.inOrder = function (type, resultArr) { resultArr = resultArr || []; if (this._left) { this._left.inOrder(type, resultArr); } switch (type) { case 'hash': resultArr.push(this._hash); break; case 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } if (this._right) { this._right.inOrder(type, resultArr); } return resultArr; }; /** * Searches the binary tree for all matching documents based on the regular * expression passed. * @param path * @param val * @param regex * @param {Array=} resultArr The results passed between recursive calls. * Do not pass anything into this argument when calling externally. * @returns {*|Array} */ BinaryTree.prototype.startsWith = function (path, val, regex, resultArr) { var reTest, thisDataPathVal = sharedPathSolver.get(this._data, path), thisDataPathValSubStr = thisDataPathVal.substr(0, val.length), result; //regex = regex || new RegExp('^' + val); resultArr = resultArr || []; if (resultArr._visitedCount === undefined) { resultArr._visitedCount = 0; } resultArr._visitedCount++; resultArr._visitedNodes = resultArr._visitedNodes || []; resultArr._visitedNodes.push(thisDataPathVal); result = this.sortAsc(thisDataPathValSubStr, val); reTest = thisDataPathValSubStr === val; if (result === 0) { if (this._left) { this._left.startsWith(path, val, regex, resultArr); } if (reTest) { resultArr.push(this._data); } if (this._right) { this._right.startsWith(path, val, regex, resultArr); } } if (result === -1) { if (reTest) { resultArr.push(this._data); } if (this._right) { this._right.startsWith(path, val, regex, resultArr); } } if (result === 1) { if (this._left) { this._left.startsWith(path, val, regex, resultArr); } if (reTest) { resultArr.push(this._data); } } return resultArr; }; /*BinaryTree.prototype.find = function (type, search, resultArr) { resultArr = resultArr || []; if (this._left) { this._left.find(type, search, resultArr); } // Check if this node's data is greater or less than the from value var fromResult = this.sortAsc(this._data[key], from), toResult = this.sortAsc(this._data[key], to); if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) { // This data node is greater than or equal to the from value, // and less than or equal to the to value so include it switch (type) { case 'hash': resultArr.push(this._hash); break; case 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } } if (this._right) { this._right.find(type, search, resultArr); } return resultArr; };*/ /** * * @param {String} type * @param {String} key The data key / path to range search against. * @param {Number} from Range search from this value (inclusive) * @param {Number} to Range search to this value (inclusive) * @param {Array=} resultArr Leave undefined when calling (internal use), * passes the result array between recursive calls to be returned when * the recursion chain completes. * @param {Path=} pathResolver Leave undefined when calling (internal use), * caches the path resolver instance for performance. * @returns {Array} Array of matching document objects */ BinaryTree.prototype.findRange = function (type, key, from, to, resultArr, pathResolver) { resultArr = resultArr || []; pathResolver = pathResolver || new Path(key); if (this._left) { this._left.findRange(type, key, from, to, resultArr, pathResolver); } // Check if this node's data is greater or less than the from value var pathVal = pathResolver.value(this._data), fromResult = this.sortAsc(pathVal, from), toResult = this.sortAsc(pathVal, to); if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) { // This data node is greater than or equal to the from value, // and less than or equal to the to value so include it switch (type) { case 'hash': resultArr.push(this._hash); break; case 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } } if (this._right) { this._right.findRange(type, key, from, to, resultArr, pathResolver); } return resultArr; }; /*BinaryTree.prototype.findRegExp = function (type, key, pattern, resultArr) { resultArr = resultArr || []; if (this._left) { this._left.findRegExp(type, key, pattern, resultArr); } // Check if this node's data is greater or less than the from value var fromResult = this.sortAsc(this._data[key], from), toResult = this.sortAsc(this._data[key], to); if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) { // This data node is greater than or equal to the from value, // and less than or equal to the to value so include it switch (type) { case 'hash': resultArr.push(this._hash); break; case 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } } if (this._right) { this._right.findRegExp(type, key, pattern, resultArr); } return resultArr; };*/ /** * Determines if the passed query and options object will be served * by this index successfully or not and gives a score so that the * DB search system can determine how useful this index is in comparison * to other indexes on the same collection. * @param query * @param queryOptions * @param matchOptions * @returns {{matchedKeys: Array, totalKeyCount: Number, score: number}} */ BinaryTree.prototype.match = function (query, queryOptions, matchOptions) { // Check if the passed query has data in the keys our index // operates on and if so, is the query sort matching our order var indexKeyArr, queryArr, matchedKeys = [], matchedKeyCount = 0, i; indexKeyArr = sharedPathSolver.parseArr(this._index, { verbose: true }); queryArr = sharedPathSolver.parseArr(query, matchOptions && matchOptions.pathOptions ? matchOptions.pathOptions : { ignore:/\$/, verbose: true }); // Loop the query array and check the order of keys against the // index key array to see if this index can be used for (i = 0; i < indexKeyArr.length; i++) { if (queryArr[i] === indexKeyArr[i]) { matchedKeyCount++; matchedKeys.push(queryArr[i]); } } return { matchedKeys: matchedKeys, totalKeyCount: queryArr.length, score: matchedKeyCount }; //return sharedPathSolver.countObjectPaths(this._keys, query); }; Shared.finishModule('BinaryTree'); module.exports = BinaryTree; },{"./Path":26,"./Shared":29}],3:[function(_dereq_,module,exports){ "use strict"; var crcTable, checksum; crcTable = (function () { var crcTable = [], c, n, k; for (n = 0; n < 256; n++) { c = n; for (k = 0; k < 8; k++) { c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); // jshint ignore:line } crcTable[n] = c; } return crcTable; }()); /** * Returns a checksum of a string. * @param {String} str The string to checksum. * @return {Number} The checksum generated. */ checksum = function(str) { var crc = 0 ^ (-1), // jshint ignore:line i; for (i = 0; i < str.length; i++) { crc = (crc >>> 8) ^ crcTable[(crc ^ str.charCodeAt(i)) & 0xFF]; // jshint ignore:line } return (crc ^ (-1)) >>> 0; // jshint ignore:line }; module.exports = checksum; },{}],4:[function(_dereq_,module,exports){ "use strict"; var Shared, Db, Metrics, KeyValueStore, Path, IndexHashMap, IndexBinaryTree, Index2d, Overload, ReactorIO, Condition, sharedPathSolver; Shared = _dereq_('./Shared'); /** * Creates a new collection. Collections store multiple documents and * handle CRUD against those documents. * @constructor */ var Collection = function (name, options) { this.init.apply(this, arguments); }; Collection.prototype.init = function (name, options) { this.sharedPathSolver = sharedPathSolver; this._primaryKey = '_id'; this._primaryIndex = new KeyValueStore('primary'); this._primaryCrc = new KeyValueStore('primaryCrc'); this._crcLookup = new KeyValueStore('crcLookup'); this._name = name; this._data = []; this._metrics = new Metrics(); this._options = options || { changeTimestamp: false }; if (this._options.db) { this.db(this._options.db); } // Create an object to store internal protected data this._metaData = {}; this._deferQueue = { insert: [], update: [], remove: [], upsert: [], async: [] }; this._deferThreshold = { insert: 100, update: 100, remove: 100, upsert: 100 }; this._deferTime = { insert: 1, update: 1, remove: 1, upsert: 1 }; this._deferredCalls = true; // Set the subset to itself since it is the root collection this.subsetOf(this); }; Shared.addModule('Collection', Collection); Shared.mixin(Collection.prototype, 'Mixin.Common'); Shared.mixin(Collection.prototype, 'Mixin.Events'); Shared.mixin(Collection.prototype, 'Mixin.ChainReactor'); Shared.mixin(Collection.prototype, 'Mixin.CRUD'); Shared.mixin(Collection.prototype, 'Mixin.Constants'); Shared.mixin(Collection.prototype, 'Mixin.Triggers'); Shared.mixin(Collection.prototype, 'Mixin.Sorting'); Shared.mixin(Collection.prototype, 'Mixin.Matching'); Shared.mixin(Collection.prototype, 'Mixin.Updating'); Shared.mixin(Collection.prototype, 'Mixin.Tags'); Metrics = _dereq_('./Metrics'); KeyValueStore = _dereq_('./KeyValueStore'); Path = _dereq_('./Path'); IndexHashMap = _dereq_('./IndexHashMap'); IndexBinaryTree = _dereq_('./IndexBinaryTree'); Index2d = _dereq_('./Index2d'); Db = Shared.modules.Db; Overload = _dereq_('./Overload'); ReactorIO = _dereq_('./ReactorIO'); Condition = _dereq_('./Condition'); sharedPathSolver = new Path(); /** * Gets / sets the deferred calls flag. If set to true (default) * then operations on large data sets can be broken up and done * over multiple CPU cycles (creating an async state). For purely * synchronous behaviour set this to false. * @param {Boolean=} val The value to set. * @returns {Boolean} */ Shared.synthesize(Collection.prototype, 'deferredCalls'); /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'state'); /** * Gets / sets the name of the collection. * @param {String=} val The name of the collection to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'name'); /** * Gets / sets the metadata stored in the collection. * @param {Object=} val The data to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'metaData'); /** * Gets / sets boolean to determine if the collection should be * capped or not. * @param {Boolean=} val The value to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'capped'); /** * Gets / sets capped collection size. This is the maximum number * of records that the capped collection will store. * @param {Number=} val The value to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'cappedSize'); /** * Adds a job id to the async queue to signal to other parts * of the application that some async work is currently being * done. * @param {String} key The id of the async job. * @private */ Collection.prototype._asyncPending = function (key) { this._deferQueue.async.push(key); }; /** * Removes a job id from the async queue to signal to other * parts of the application that some async work has been * completed. If no further async jobs exist on the queue then * the "ready" event is emitted from this collection instance. * @param {String} key The id of the async job. * @private */ Collection.prototype._asyncComplete = function (key) { // Remove async flag for this type var index = this._deferQueue.async.indexOf(key); while (index > -1) { this._deferQueue.async.splice(index, 1); index = this._deferQueue.async.indexOf(key); } if (this._deferQueue.async.length === 0) { this.deferEmit('ready'); } }; /** * Get the data array that represents the collection's data. * This data is returned by reference and should not be altered outside * of the provided CRUD functionality of the collection as doing so * may cause unstable index behaviour within the collection. * @returns {Array} */ Collection.prototype.data = function () { return this._data; }; /** * Drops a collection and all it's stored data from the database. * @param {Function=} callback A callback method to call once the * operation has completed. * @returns {boolean} True on success, false on failure. */ Collection.prototype.drop = function (callback) { var key; if (!this.isDropped()) { if (this._db && this._db._collection && this._name) { if (this.debug()) { console.log(this.logIdentifier() + ' Dropping'); } this._state = 'dropped'; this.emit('drop', this); delete this._db._collection[this._name]; // Remove any reactor IO chain links if (this._collate) { for (key in this._collate) { if (this._collate.hasOwnProperty(key)) { this.collateRemove(key); } } } delete this._primaryKey; delete this._primaryIndex; delete this._primaryCrc; delete this._crcLookup; delete this._data; delete this._metrics; delete this._listeners; if (callback) { callback.call(this, false, true); } return true; } } else { if (callback) { callback.call(this, false, true); } return true; } if (callback) { callback.call(this, false, true); } return false; }; /** * Gets / sets the primary key for this collection. * @param {String=} keyName The name of the primary key. * @returns {*} */ Collection.prototype.primaryKey = function (keyName) { if (keyName !== undefined) { if (this._primaryKey !== keyName) { var oldKey = this._primaryKey; this._primaryKey = keyName; // Set the primary key index primary key this._primaryIndex.primaryKey(keyName); // Rebuild the primary key index this.rebuildPrimaryKeyIndex(); // Propagate change down the chain this.chainSend('primaryKey', { keyName: keyName, oldData: oldKey }); } return this; } return this._primaryKey; }; /** * Handles insert events and routes changes to binds and views as required. * @param {Array} inserted An array of inserted documents. * @param {Array} failed An array of documents that failed to insert. * @private */ Collection.prototype._onInsert = function (inserted, failed) { this.emit('insert', inserted, failed); }; /** * Handles update events and routes changes to binds and views as required. * @param {Array} items An array of updated documents. * @private */ Collection.prototype._onUpdate = function (items) { this.emit('update', items); }; /** * Handles remove events and routes changes to binds and views as required. * @param {Array} items An array of removed documents. * @private */ Collection.prototype._onRemove = function (items) { this.emit('remove', items); }; /** * Handles any change to the collection by updating the * lastChange timestamp on the collection's metaData. This * only happens if the changeTimestamp option is enabled * on the collection (it is disabled by default). * @private */ Collection.prototype._onChange = function () { if (this._options.changeTimestamp) { // Record the last change timestamp this._metaData.lastChange = this.serialiser.convert(new Date()); } }; /** * Gets / sets the db instance this class instance belongs to. * @param {Db=} db The db instance. * @returns {*} */ Shared.synthesize(Collection.prototype, 'db', function (db) { if (db) { if (this.primaryKey() === '_id') { // Set primary key to the db's key by default this.primaryKey(db.primaryKey()); // Apply the same debug settings this.debug(db.debug()); } } return this.$super.apply(this, arguments); }); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Collection.prototype, 'mongoEmulation'); Collection.prototype.setData = new Overload('Collection.prototype.setData', { /** * Sets the collection's data to the array / documents passed. If any * data already exists in the collection it will be removed before the * new data is set via the remove() method, and the remove event will * fire as well. * @name setData * @param {Array|Object} data The array of documents or a single document * that will be set as the collections data. */ '*': function (data) { return this.$main.call(this, data, {}); }, /** * Sets the collection's data to the array / documents passed. If any * data already exists in the collection it will be removed before the * new data is set via the remove() method, and the remove event will * fire as well. * @name setData * @param {Array|Object} data The array of documents or a single document * that will be set as the collections data. * @param {Object} options Optional options object. */ '*, object': function (data, options) { return this.$main.call(this, data, options); }, /** * Sets the collection's data to the array / documents passed. If any * data already exists in the collection it will be removed before the * new data is set via the remove() method, and the remove event will * fire as well. * @name setData * @param {Array|Object} data The array of documents or a single document * that will be set as the collections data. * @param {Function} callback Optional callback function. */ '*, function': function (data, callback) { return this.$main.call(this, data, {}, callback); }, /** * Sets the collection's data to the array / documents passed. If any * data already exists in the collection it will be removed before the * new data is set via the remove() method, and the remove event will * fire as well. * @name setData * @param {Array|Object} data The array of documents or a single document * that will be set as the collections data. * @param {*} options Optional options object. * @param {Function} callback Optional callback function. */ '*, *, function': function (data, options, callback) { return this.$main.call(this, data, options, callback); }, /** * Sets the collection's data to the array / documents passed. If any * data already exists in the collection it will be removed before the * new data is set via the remove() method, and the remove event will * fire as well. * @name setData * @param {Array|Object} data The array of documents or a single document * that will be set as the collections data. * @param {*} options Optional options object. * @param {*} callback Optional callback function. */ '*, *, *': function (data, options, callback) { return this.$main.call(this, data, options, callback); }, /** * Sets the collection's data to the array / documents passed. If any * data already exists in the collection it will be removed before the * new data is set via the remove() method, and the remove event will * fire as well. * @name setData * @param {Array|Object} data The array of documents or a single document * that will be set as the collections data. * @param {Object} options Optional options object. * @param {Function} callback Optional callback function. */ '$main': function (data, options, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (data) { var deferredSetting = this.deferredCalls(), oldData = [].concat(this._data); // Switch off deferred calls since setData should be // a synchronous call this.deferredCalls(false); options = this.options(options); if (options.$decouple) { data = this.decouple(data); } if (!(data instanceof Array)) { data = [data]; } // Remove all items from the collection this.remove({}); // Insert the new data this.insert(data); // Switch deferred calls back to previous settings this.deferredCalls(deferredSetting); this._onChange(); this.emit('setData', this._data, oldData); } if (callback) { callback.call(this); } return this; } }); /** * Drops and rebuilds the primary key index for all documents * in the collection. * @param {Object=} options An optional options object. * @private */ Collection.prototype.rebuildPrimaryKeyIndex = function (options) { options = options || { $ensureKeys: undefined, $violationCheck: undefined }; var ensureKeys = options && options.$ensureKeys !== undefined ? options.$ensureKeys : true, violationCheck = options && options.$violationCheck !== undefined ? options.$violationCheck : true, arr, arrCount, arrItem, pIndex = this._primaryIndex, crcIndex = this._primaryCrc, crcLookup = this._crcLookup, pKey = this._primaryKey, jString; // Drop the existing primary index pIndex.truncate(); crcIndex.truncate(); crcLookup.truncate(); // Loop the data and check for a primary key in each object arr = this._data; arrCount = arr.length; while (arrCount--) { arrItem = arr[arrCount]; if (ensureKeys) { // Make sure the item has a primary key this.ensurePrimaryKey(arrItem); } if (violationCheck) { // Check for primary key violation if (!pIndex.uniqueSet(arrItem[pKey], arrItem)) { // Primary key violation throw(this.logIdentifier() + ' Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: ' + arrItem[this._primaryKey]); } } else { pIndex.set(arrItem[pKey], arrItem); } // Generate a hash string jString = this.hash(arrItem); crcIndex.set(arrItem[pKey], jString); crcLookup.set(jString, arrItem); } }; /** * Checks for a primary key on the document and assigns one if none * currently exists. * @param {Object} obj The object to check a primary key against. * @private */ Collection.prototype.ensurePrimaryKey = function (obj) { if (obj[this._primaryKey] === undefined) { // Assign a primary key automatically obj[this._primaryKey] = this.objectId(); } }; /** * Clears all data from the collection. * @returns {Collection} */ Collection.prototype.truncate = function () { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } // TODO: This should use remove so that chain reactor events are properly // TODO: handled, but ensure that chunking is switched off this.emit('truncate', this._data); // Clear all the data from the collection this._data.length = 0; // Re-create the primary index data this._primaryIndex = new KeyValueStore('primary'); this._primaryCrc = new KeyValueStore('primaryCrc'); this._crcLookup = new KeyValueStore('crcLookup'); this._onChange(); this.emit('immediateChange', {type: 'truncate'}); this.deferEmit('change', {type: 'truncate'}); return this; }; /** * Inserts a new document or updates an existing document in a * collection depending on if a matching primary key exists in * the collection already or not. * * If the document contains a primary key field (based on the * collections's primary key) then the database will search for * an existing document with a matching id. If a matching * document is found, the document will be updated. Any keys that * match keys on the existing document will be overwritten with * new data. Any keys that do not currently exist on the document * will be added to the document. * * If the document does not contain an id or the id passed does * not match an existing document, an insert is performed instead. * If no id is present a new primary key id is provided for the * document and the document is inserted. * * @param {Object} obj The document object to upsert or an array * containing documents to upsert. * @param {Function=} callback Optional callback method. * @returns {Object} An object containing two keys, "op" contains * either "insert" or "update" depending on the type of operation * that was performed and "result" contains the return data from * the operation used. */ Collection.prototype.upsert = function (obj, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (obj) { var queue = this._deferQueue.upsert, deferThreshold = this._deferThreshold.upsert, returnData = {}, query, i; // Determine if the object passed is an array or not if (obj instanceof Array) { if (this._deferredCalls && obj.length > deferThreshold) { // Break up upsert into blocks this._deferQueue.upsert = queue.concat(obj); this._asyncPending('upsert'); // Fire off the insert queue handler this.processQueue('upsert', callback); return {}; } else { // Loop the array and upsert each item returnData = []; for (i = 0; i < obj.length; i++) { returnData.push(this.upsert(obj[i])); } if (callback) { callback.call(this); } return returnData; } } // Determine if the operation is an insert or an update if (obj[this._primaryKey]) { // Check if an object with this primary key already exists query = {}; query[this._primaryKey] = obj[this._primaryKey]; if (this._primaryIndex.lookup(query)[0]) { // The document already exists with this id, this operation is an update returnData.op = 'update'; } else { // No document with this id exists, this operation is an insert returnData.op = 'insert'; } } else { // The document passed does not contain an id, this operation is an insert returnData.op = 'insert'; } switch (returnData.op) { case 'insert': returnData.result = this.insert(obj, callback); break; case 'update': returnData.result = this.update(query, obj, {}, callback); break; default: break; } return returnData; } else { if (callback) { callback.call(this); } } return {}; }; /** * Executes a method against each document that matches query and returns an * array of documents that may have been modified by the method. * @param {Object} query The query object. * @param {Function} func The method that each document is passed to. If this method * returns false for a particular document it is excluded from the results. * @param {Object=} options Optional options object. * @returns {Array} */ Collection.prototype.filter = function (query, func, options) { return (this.find(query, options)).filter(func); }; /** * Executes a method against each document that matches query and then executes * an update based on the return data of the method. * @param {Object} query The query object. * @param {Function} func The method that each document is passed to. If this method * returns false for a particular document it is excluded from the update. * @param {Object=} options Optional options object passed to the initial find call. * @returns {Array} */ Collection.prototype.filterUpdate = function (query, func, options) { var items = this.find(query, options), results = [], singleItem, singleQuery, singleUpdate, pk = this.primaryKey(), i; for (i = 0; i < items.length; i++) { singleItem = items[i]; singleUpdate = func(singleItem); if (singleUpdate) { singleQuery = {}; singleQuery[pk] = singleItem[pk]; results.push(this.update(singleQuery, singleUpdate)); } } return results; }; /** * Modifies an existing document or documents in a collection. * This will update all matches for 'query' with the data held * in 'update'. It will not overwrite the matched documents * with the update document. * * @param {Object} query The query that must be matched for a * document to be operated on. * @param {Object} update The object containing updated * key/values. Any keys that match keys on the existing document * will be overwritten with this data. Any keys that do not * currently exist on the document will be added to the document. * @param {Object=} options An options object. * @param {Function=} callback The callback method to call when * the update is complete. * @returns {Array} The items that were updated. */ Collection.prototype.update = function (query, update, options, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); this.convertToFdb(update); } else { // Decouple the update data update = this.decouple(update); } // Handle transform update = this.transformIn(update); return this._handleUpdate(query, update, options, callback); }; /** * Handles the update operation that was initiated by a call to update(). * @param {Object} query The query that must be matched for a * document to be operated on. * @param {Object} update The object containing updated * key/values. Any keys that match keys on the existing document * will be overwritten with this data. Any keys that do not * currently exist on the document will be added to the document. * @param {Object=} options An options object. * @param {Function=} callback The callback method to call when * the update is complete. * @returns {Array} The items that were updated. * @private */ Collection.prototype._handleUpdate = function (query, update, options, callback) { var self = this, op = this._metrics.create('update'), dataSet, updated, updateCall = function (referencedDoc) { var oldDoc = self.decouple(referencedDoc), newDoc, triggerOperation, result; if (self.willTrigger(self.TYPE_UPDATE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_UPDATE, self.PHASE_AFTER)) { newDoc = self.decouple(referencedDoc); triggerOperation = { type: 'update', query: self.decouple(query), update: self.decouple(update), options: self.decouple(options), op: op }; // Update newDoc with the update criteria so we know what the data will look // like AFTER the update is processed result = self.updateObject(newDoc, triggerOperation.update, triggerOperation.query, triggerOperation.options, ''); if (self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_BEFORE, referencedDoc, newDoc) !== false) { // No triggers complained so let's execute the replacement of the existing // object with the new one result = self.updateObject(referencedDoc, newDoc, triggerOperation.query, triggerOperation.options, ''); // NOTE: If for some reason we would only like to fire this event if changes are actually going // to occur on the object from the proposed update then we can add "result &&" to the if self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_AFTER, oldDoc, newDoc); } else { // Trigger cancelled operation so tell result that it was not updated result = false; } } else { // No triggers complained so let's execute the replacement of the existing // object with the new one result = self.updateObject(referencedDoc, update, query, options, ''); } // Inform indexes of the change self._updateIndexes(oldDoc, referencedDoc); return result; }; op.start(); op.time('Retrieve documents to update'); dataSet = this.find(query, {$decouple: false}); op.time('Retrieve documents to update'); if (dataSet.length) { op.time('Update documents'); updated = dataSet.filter(updateCall); op.time('Update documents'); if (updated.length) { if (this.debug()) { console.log(this.logIdentifier() + ' Updated some data'); } op.time('Resolve chains'); if (this.chainWillSend()) { this.chainSend('update', { query: query, update: update, dataSet: this.decouple(updated) }, options); } op.time('Resolve chains'); this._onUpdate(updated); this._onChange(); if (callback) { callback.call(this); } this.emit('immediateChange', {type: 'update', data: updated}); this.deferEmit('change', {type: 'update', data: updated}); } } op.stop(); // TODO: Should we decouple the updated array before return by default? return updated || []; }; /** * Replaces an existing object with data from the new object without * breaking data references. It does this by removing existing keys * from the base object and then adding the passed object's keys to * the existing base object, thereby maintaining any references to * the existing base object but effectively replacing the object with * the new one. * @param {Object} currentObj The base object to alter. * @param {Object} newObj The new object to overwrite the existing one * with. * @returns {*} Chain. * @private */ Collection.prototype._replaceObj = function (currentObj, newObj) { var i; // Check if the new document has a different primary key value from the existing one // Remove item from indexes this._removeFromIndexes(currentObj); // Remove existing keys from current object for (i in currentObj) { if (currentObj.hasOwnProperty(i)) { delete currentObj[i]; } } // Add new keys to current object for (i in newObj) { if (newObj.hasOwnProperty(i)) { currentObj[i] = newObj[i]; } } // Update the item in the primary index if (!this._insertIntoIndexes(currentObj)) { throw(this.logIdentifier() + ' Primary key violation in update! Key violated: ' + currentObj[this._primaryKey]); } // Update the object in the collection data //this._data.splice(this._data.indexOf(currentObj), 1, newObj); return this; }; /** * Helper method to update a document via it's id. * @param {String} id The id of the document. * @param {Object} update The object containing the key/values to * update to. * @returns {Object} The document that was updated or undefined * if no document was updated. */ Collection.prototype.updateById = function (id, update) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.update(searchObj, update)[0]; }; /** * Internal method for document updating. * @param {Object} doc The document to update. * @param {Object} update The object with key/value pairs to update * the document with. * @param {Object} query The query object that we need to match to * perform an update. * @param {Object} options An options object. * @param {String} path The current recursive path. * @param {String} opType The type of update operation to perform, * if none is specified default is to set new data against matching * fields. * @returns {Boolean} True if the document was updated with new / * changed data or false if it was not updated because the data was * the same. * @private */ Collection.prototype.updateObject = function (doc, update, query, options, path, opType) { // TODO: This method is long, try to break it into smaller pieces update = this.decouple(update); // Clear leading dots from path path = path || ''; if (path.substr(0, 1) === '.') { path = path.substr(1, path.length -1); } //var oldDoc = this.decouple(doc), var updated = false, recurseUpdated = false, operation, tmpArray, tmpIndex, tmpCount, tempIndex, tempKey, replaceObj, pk, pathInstance, sourceIsArray, updateIsArray, i; // Loop each key in the update object for (i in update) { if (update.hasOwnProperty(i)) { // Reset operation flag operation = false; // Check if the property starts with a dollar (function) if (i.substr(0, 1) === '$') { // Check for commands switch (i) { case '$key': case '$index': case '$data': case '$min': case '$max': // Ignore some operators operation = true; break; case '$each': operation = true; // Loop over the array of updates and run each one tmpCount = update.$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { recurseUpdated = this.updateObject(doc, update.$each[tmpIndex], query, options, path); if (recurseUpdated) { updated = true; } } updated = updated || recurseUpdated; break; case '$replace': operation = true; replaceObj = update.$replace; pk = this.primaryKey(); // Loop the existing item properties and compare with // the replacement (never remove primary key) for (tempKey in doc) { if (doc.hasOwnProperty(tempKey) && tempKey !== pk) { if (replaceObj[tempKey] === undefined) { // The new document doesn't have this field, remove it from the doc this._updateUnset(doc, tempKey); updated = true; } } } // Loop the new item props and update the doc for (tempKey in replaceObj) { if (replaceObj.hasOwnProperty(tempKey) && tempKey !== pk) { this._updateOverwrite(doc, tempKey, replaceObj[tempKey]); updated = true; } } break; default: operation = true; // Now run the operation recurseUpdated = this.updateObject(doc, update[i], query, options, path, i); updated = updated || recurseUpdated; break; } } // Check if the key has a .$ at the end, denoting an array lookup if (this._isPositionalKey(i)) { operation = true; // Modify i to be the name of the field i = i.substr(0, i.length - 2); pathInstance = new Path(path + '.' + i); // Check if the key is an array and has items if (doc[i] && doc[i] instanceof Array && doc[i].length) { tmpArray = []; // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], pathInstance.value(query)[0], options, '', {})) { tmpArray.push(tmpIndex); } } // Loop the items that matched and update them for (tmpIndex = 0; tmpIndex < tmpArray.length; tmpIndex++) { recurseUpdated = this.updateObject(doc[i][tmpArray[tmpIndex]], update[i + '.$'], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } } if (!operation) { if (!opType && typeof(update[i]) === 'object') { if (doc[i] !== null && typeof(doc[i]) === 'object') { // Check if we are dealing with arrays sourceIsArray = doc[i] instanceof Array; updateIsArray = update[i] instanceof Array; if (sourceIsArray || updateIsArray) { // Check if the update is an object and the doc is an array if (!updateIsArray && sourceIsArray) { // Update is an object, source is an array so match the array items // with our query object to find the one to update inside this array // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { recurseUpdated = this.updateObject(doc[i][tmpIndex], update[i], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } else { // Either both source and update are arrays or the update is // an array and the source is not, so set source to update if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } } } else { // The doc key is an object so traverse the // update further recurseUpdated = this.updateObject(doc[i], update[i], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } else { if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } } } else { switch (opType) { case '$inc': var doUpdate = true; // Check for a $min / $max operator if (update[i] > 0) { if (update.$max) { // Check current value if (doc[i] >= update.$max) { // Don't update doUpdate = false; } } } else if (update[i] < 0) { if (update.$min) { // Check current value if (doc[i] <= update.$min) { // Don't update doUpdate = false; } } } if (doUpdate) { this._updateIncrement(doc, i, update[i]); updated = true; } break; case '$cast': // Casts a property to the type specified if it is not already // that type. If the cast is an array or an object and the property // is not already that type a new array or object is created and // set to the property, overwriting the previous value switch (update[i]) { case 'array': if (!(doc[i] instanceof Array)) { // Cast to an array this._updateProperty(doc, i, update.$data || []); updated = true; } break; case 'object': if (!(doc[i] instanceof Object) || (doc[i] instanceof Array)) { // Cast to an object this._updateProperty(doc, i, update.$data || {}); updated = true; } break; case 'number': if (typeof doc[i] !== 'number') { // Cast to a number this._updateProperty(doc, i, Number(doc[i])); updated = true; } break; case 'string': if (typeof doc[i] !== 'string') { // Cast to a string this._updateProperty(doc, i, String(doc[i])); updated = true; } break; default: throw(this.logIdentifier() + ' Cannot update cast to unknown type: ' + update[i]); } break; case '$push': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { // Check for a $position modifier with an $each if (update[i].$position !== undefined && update[i].$each instanceof Array) { // Grab the position to insert at tempIndex = update[i].$position; // Loop the each array and push each item tmpCount = update[i].$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { this._updateSplicePush(doc[i], tempIndex + tmpIndex, update[i].$each[tmpIndex]); } } else if (update[i].$each instanceof Array) { // Do a loop over the each to push multiple items tmpCount = update[i].$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { this._updatePush(doc[i], update[i].$each[tmpIndex]); } } else { // Do a standard push this._updatePush(doc[i], update[i]); } updated = true; } else { throw(this.logIdentifier() + ' Cannot push to a key that is not an array! (' + i + ')'); } break; case '$pull': if (doc[i] instanceof Array) { tmpArray = []; // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], update[i], options, '', {})) { tmpArray.push(tmpIndex); } } tmpCount = tmpArray.length; // Now loop the pull array and remove items to be pulled while (tmpCount--) { this._updatePull(doc[i], tmpArray[tmpCount]); updated = true; } } break; case '$pullAll': if (doc[i] instanceof Array) { if (update[i] instanceof Array) { tmpArray = doc[i]; tmpCount = tmpArray.length; if (tmpCount > 0) { // Now loop the pull array and remove items to be pulled while (tmpCount--) { for (tempIndex = 0; tempIndex < update[i].length; tempIndex++) { if (tmpArray[tmpCount] === update[i][tempIndex]) { this._updatePull(doc[i], tmpCount); tmpCount--; updated = true; } } if (tmpCount < 0) { break; } } } } else { throw(this.logIdentifier() + ' Cannot pullAll without being given an array of values to pull! (' + i + ')'); } } break; case '$addToSet': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { // Loop the target array and check for existence of item var targetArr = doc[i], targetArrIndex, targetArrCount = targetArr.length, objHash, addObj = true, optionObj = (options && options.$addToSet), hashMode, pathSolver; // Check if we have an options object for our operation if (update[i].$key) { hashMode = false; pathSolver = new Path(update[i].$key); objHash = pathSolver.value(update[i])[0]; // Remove the key from the object before we add it delete update[i].$key; } else if (optionObj && optionObj.key) { hashMode = false; pathSolver = new Path(optionObj.key); objHash = pathSolver.value(update[i])[0]; } else { objHash = this.jStringify(update[i]); hashMode = true; } for (targetArrIndex = 0; targetArrIndex < targetArrCount; targetArrIndex++) { if (hashMode) { // Check if objects match via a string hash (JSON) if (this.jStringify(targetArr[targetArrIndex]) === objHash) { // The object already exists, don't add it addObj = false; break; } } else { // Check if objects match based on the path if (objHash === pathSolver.value(targetArr[targetArrIndex])[0]) { // The object already exists, don't add it addObj = false; break; } } } if (addObj) { this._updatePush(doc[i], update[i]); updated = true; } } else { throw(this.logIdentifier() + ' Cannot addToSet on a key that is not an array! (' + i + ')'); } break; case '$splicePush': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { tempIndex = update.$index; if (tempIndex !== undefined) { delete update.$index; // Check for out of bounds index if (tempIndex > doc[i].length) { tempIndex = doc[i].length; } this._updateSplicePush(doc[i], tempIndex, update[i]); updated = true; } else { throw(this.logIdentifier() + ' Cannot splicePush without a $index integer value!'); } } else { throw(this.logIdentifier() + ' Cannot splicePush with a key that is not an array! (' + i + ')'); } break; case '$move': if (doc[i] instanceof Array) { // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], update[i], options, '', {})) { var moveToIndex = update.$index; if (moveToIndex !== undefined) { delete update.$index; this._updateSpliceMove(doc[i], tmpIndex, moveToIndex); updated = true; } else { throw(this.logIdentifier() + ' Cannot move without a $index integer value!'); } break; } } } else { throw(this.logIdentifier() + ' Cannot move on a key that is not an array! (' + i + ')'); } break; case '$mul': this._updateMultiply(doc, i, update[i]); updated = true; break; case '$rename': this._updateRename(doc, i, update[i]); updated = true; break; case '$overwrite': this._updateOverwrite(doc, i, update[i]); updated = true; break; case '$unset': this._updateUnset(doc, i); updated = true; break; case '$clear': this._updateClear(doc, i); updated = true; break; case '$pop': if (doc[i] instanceof Array) { if (this._updatePop(doc[i], update[i])) { updated = true; } } else { throw(this.logIdentifier() + ' Cannot pop from a key that is not an array! (' + i + ')'); } break; case '$toggle': // Toggle the boolean property between true and false this._updateProperty(doc, i, !doc[i]); updated = true; break; default: if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } break; } } } } } return updated; }; /** * Determines if the passed key has an array positional mark * (a dollar at the end of its name). * @param {String} key The key to check. * @returns {Boolean} True if it is a positional or false if not. * @private */ Collection.prototype._isPositionalKey = function (key) { return key.substr(key.length - 2, 2) === '.$'; }; /** * Removes any documents from the collection that match the search * query key/values. * @param {Object} query The query object. * @param {Object=} options An options object. * @param {Function=} callback A callback method. * @returns {Array} An array of the documents that were removed. */ Collection.prototype.remove = function (query, options, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } var self = this, dataSet, index, arrIndex, returnArr, removeMethod, triggerOperation, doc, newDoc; if (typeof(options) === 'function') { callback = options; options = {}; } // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); } if (query instanceof Array) { returnArr = []; for (arrIndex = 0; arrIndex < query.length; arrIndex++) { returnArr.push(this.remove(query[arrIndex], {noEmit: true})); } if (!options || (options && !options.noEmit)) { this._onRemove(returnArr); } if (callback) { callback.call(this, false, returnArr); } return returnArr; } else { returnArr = []; dataSet = this.find(query, {$decouple: false}); if (dataSet.length) { removeMethod = function (dataItem) { // Remove the item from the collection's indexes self._removeFromIndexes(dataItem); // Remove data from internal stores index = self._data.indexOf(dataItem); self._dataRemoveAtIndex(index); returnArr.push(dataItem); }; // Remove the data from the collection for (var i = 0; i < dataSet.length; i++) { doc = dataSet[i]; if (self.willTrigger(self.TYPE_REMOVE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_REMOVE, self.PHASE_AFTER)) { triggerOperation = { type: 'remove' }; newDoc = self.decouple(doc); if (self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_BEFORE, newDoc, newDoc) !== false) { // The trigger didn't ask to cancel so execute the removal method removeMethod(doc); self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_AFTER, newDoc, newDoc); } } else { // No triggers to execute removeMethod(doc); } } if (returnArr.length) { //op.time('Resolve chains'); self.chainSend('remove', { query: query, dataSet: returnArr }, options); //op.time('Resolve chains'); if (!options || (options && !options.noEmit)) { this._onRemove(returnArr); } this._onChange(); this.emit('immediateChange', {type: 'remove', data: returnArr}); this.deferEmit('change', {type: 'remove', data: returnArr}); } } if (callback) { callback.call(this, false, returnArr); } return returnArr; } }; /** * Helper method that removes a document that matches the given id. * @param {String} id The id of the document to remove. * @returns {Object} The document that was removed or undefined if * nothing was removed. */ Collection.prototype.removeById = function (id) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.remove(searchObj)[0]; }; /** * Processes a deferred action queue. * @param {String} type The queue name to process. * @param {Function} callback A method to call when the queue has processed. * @param {Object=} resultObj A temp object to hold results in. */ Collection.prototype.processQueue = function (type, callback, resultObj) { var self = this, queue = this._deferQueue[type], deferThreshold = this._deferThreshold[type], deferTime = this._deferTime[type], dataArr, result; resultObj = resultObj || { deferred: true }; if (queue.length) { // Process items up to the threshold if (queue.length > deferThreshold) { // Grab items up to the threshold value dataArr = queue.splice(0, deferThreshold); } else { // Grab all the remaining items dataArr = queue.splice(0, queue.length); } result = self[type](dataArr); switch (type) { case 'insert': resultObj.inserted = resultObj.inserted || []; resultObj.failed = resultObj.failed || []; resultObj.inserted = resultObj.inserted.concat(result.inserted); resultObj.failed = resultObj.failed.concat(result.failed); break; } // Queue another process setTimeout(function () { self.processQueue.call(self, type, callback, resultObj); }, deferTime); } else { if (callback) { callback.call(this, resultObj); } this._asyncComplete(type); } // Check if all queues are complete if (!this.isProcessingQueue()) { this.deferEmit('queuesComplete'); } }; /** * Checks if any CRUD operations have been deferred and are still waiting to * be processed. * @returns {Boolean} True if there are still deferred CRUD operations to process * or false if all queues are clear. */ Collection.prototype.isProcessingQueue = function () { var i; for (i in this._deferQueue) { if (this._deferQueue.hasOwnProperty(i)) { if (this._deferQueue[i].length) { return true; } } } return false; }; /** * Inserts a document or array of documents into the collection. * @param {Object|Array} data Either a document object or array of document * @param {Number=} index Optional index to insert the record at. * @param {Collection~insertCallback=} callback Optional callback called * once the insert is complete. */ Collection.prototype.insert = function (data, index, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (typeof(index) === 'function') { callback = index; index = this._data.length; } else if (index === undefined) { index = this._data.length; } data = this.transformIn(data); return this._insertHandle(data, index, callback); }; /** * The insert operation's callback. * @callback Collection~insertCallback * @param {Object} result The result object will contain two arrays (inserted * and failed) which represent the documents that did get inserted and those * that didn't for some reason (usually index violation). Failed items also * contain a reason. Inspect the failed array for further information. * * A third field called "deferred" is a boolean value to indicate if the * insert operation was deferred across more than one CPU cycle (to avoid * blocking the main thread). */ /** * Inserts a document or array of documents into the collection. * @param {Object|Array} data Either a document object or array of document * @param {Number=} index Optional index to insert the record at. * @param {Collection~insertCallback=} callback Optional callback called * once the insert is complete. */ Collection.prototype._insertHandle = function (data, index, callback) { var //self = this, queue = this._deferQueue.insert, deferThreshold = this._deferThreshold.insert, //deferTime = this._deferTime.insert, inserted = [], failed = [], insertResult, resultObj, i; if (data instanceof Array) { // Check if there are more insert items than the insert defer // threshold, if so, break up inserts so we don't tie up the // ui or thread if (this._deferredCalls && data.length > deferThreshold) { // Break up insert into blocks this._deferQueue.insert = queue.concat(data); this._asyncPending('insert'); // Fire off the insert queue handler this.processQueue('insert', callback); return; } else { // Loop the array and add items for (i = 0; i < data.length; i++) { insertResult = this._insert(data[i], index + i); if (insertResult === true) { inserted.push(data[i]); } else { failed.push({ doc: data[i], reason: insertResult }); } } } } else { // Store the data item insertResult = this._insert(data, index); if (insertResult === true) { inserted.push(data); } else { failed.push({ doc: data, reason: insertResult }); } } resultObj = { deferred: false, inserted: inserted, failed: failed }; this._onInsert(inserted, failed); if (callback) { callback.call(this, resultObj); } this._onChange(); this.emit('immediateChange', {type: 'insert', data: inserted, failed: failed}); this.deferEmit('change', {type: 'insert', data: inserted, failed: failed}); return resultObj; }; /** * Internal method to insert a document into the collection. Will * check for index violations before allowing the document to be inserted. * @param {Object} doc The document to insert after passing index violation * tests. * @param {Number=} index Optional index to insert the document at. * @returns {Boolean|Object} True on success, false if no document passed, * or an object containing details about an index violation if one occurred. * @private */ Collection.prototype._insert = function (doc, index) { if (doc) { var self = this, indexViolation, triggerOperation, insertMethod, newDoc, capped = this.capped(), cappedSize = this.cappedSize(); this.ensurePrimaryKey(doc); // Check indexes are not going to be broken by the document indexViolation = this.insertIndexViolation(doc); insertMethod = function (doc) { // Add the item to the collection's indexes self._insertIntoIndexes(doc); // Check index overflow if (index > self._data.length) { index = self._data.length; } // Insert the document self._dataInsertAtIndex(index, doc); // Check capped collection status and remove first record // if we are over the threshold if (capped && self._data.length > cappedSize) { // Remove the first item in the data array self.removeById(self._data[0][self._primaryKey]); } //op.time('Resolve chains'); if (self.chainWillSend()) { self.chainSend('insert', { dataSet: self.decouple([doc]) }, { index: index }); } //op.time('Resolve chains'); }; if (!indexViolation) { if (self.willTrigger(self.TYPE_INSERT, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) { triggerOperation = { type: 'insert' }; if (self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_BEFORE, {}, doc) !== false) { insertMethod(doc); if (self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) { // Clone the doc so that the programmer cannot update the internal document // on the "after" phase trigger newDoc = self.decouple(doc); self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_AFTER, {}, newDoc); } } else { // The trigger just wants to cancel the operation return 'Trigger cancelled operation'; } } else { // No triggers to execute insertMethod(doc); } return true; } else { return 'Index violation in index: ' + indexViolation; } } return 'No document passed to insert'; }; /** * Inserts a document into the internal collection data array at * Inserts a document into the internal collection data array at * the specified index. * @param {number} index The index to insert at. * @param {object} doc The document to insert. * @private */ Collection.prototype._dataInsertAtIndex = function (index, doc) { this._data.splice(index, 0, doc); }; /** * Removes a document from the internal collection data array at * the specified index. * @param {number} index The index to remove from. * @private */ Collection.prototype._dataRemoveAtIndex = function (index) { this._data.splice(index, 1); }; /** * Replaces all data in the collection's internal data array with * the passed array of data. * @param {array} data The array of data to replace existing data with. * @private */ Collection.prototype._dataReplace = function (data) { // Clear the array - using a while loop with pop is by far the // fastest way to clear an array currently while (this._data.length) { this._data.pop(); } // Append new items to the array this._data = this._data.concat(data); }; /** * Inserts a document into the collection indexes. * @param {Object} doc The document to insert. * @private */ Collection.prototype._insertIntoIndexes = function (doc) { var arr = this._indexByName, arrIndex, violated, hash = this.hash(doc), pk = this._primaryKey; // Insert to primary key index violated = this._primaryIndex.uniqueSet(doc[pk], doc); this._primaryCrc.uniqueSet(doc[pk], hash); this._crcLookup.uniqueSet(hash, doc); // Insert into other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].insert(doc); } } return violated; }; /** * Removes a document from the collection indexes. * @param {Object} doc The document to remove. * @private */ Collection.prototype._removeFromIndexes = function (doc) { var arr = this._indexByName, arrIndex, hash = this.hash(doc), pk = this._primaryKey; // Remove from primary key index this._primaryIndex.unSet(doc[pk]); this._primaryCrc.unSet(doc[pk]); this._crcLookup.unSet(hash); // Remove from other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].remove(doc); } } }; /** * Updates collection index data for the passed document. * @param {Object} oldDoc The old document as it was before the update. * @param {Object} newDoc The document as it now is after the update. * @private */ Collection.prototype._updateIndexes = function (oldDoc, newDoc) { this._removeFromIndexes(oldDoc); this._insertIntoIndexes(newDoc); }; /** * Rebuild collection indexes. * @private */ Collection.prototype._rebuildIndexes = function () { var arr = this._indexByName, arrIndex; // Remove from other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].rebuild(); } } }; /** * Uses the passed query to generate a new collection with results * matching the query parameters. * * @param {Object} query The query object to generate the subset with. * @param {Object=} options An options object. * @returns {*} */ Collection.prototype.subset = function (query, options) { var result = this.find(query, options), coll; coll = new Collection(); coll.db(this._db); coll.subsetOf(this) .primaryKey(this._primaryKey) .setData(result); return coll; }; /** * Gets / sets the collection that this collection is a subset of. * @param {Collection=} collection The collection to set as the parent of this subset. * @returns {Collection} */ Shared.synthesize(Collection.prototype, 'subsetOf'); /** * Checks if the collection is a subset of the passed collection. * @param {Collection} collection The collection to test against. * @returns {Boolean} True if the passed collection is the parent of * the current collection. */ Collection.prototype.isSubsetOf = function (collection) { return this._subsetOf === collection; }; /** * Find the distinct values for a specified field across a single collection and * returns the results in an array. * @param {String} key The field path to return distinct values for e.g. "person.name". * @param {Object=} query The query to use to filter the documents used to return values from. * @param {Object=} options The query options to use when running the query. * @returns {Array} */ Collection.prototype.distinct = function (key, query, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } var data = this.find(query, options), pathSolver = new Path(key), valueUsed = {}, distinctValues = [], value, i; // Loop the data and build array of distinct values for (i = 0; i < data.length; i++) { value = pathSolver.value(data[i])[0]; if (value && !valueUsed[value]) { valueUsed[value] = true; distinctValues.push(value); } } return distinctValues; }; /** * Helper method to find a document by it's id. * @param {String} id The id of the document. * @param {Object=} options The options object, allowed keys are sort and limit. * @returns {Array} The items that were updated. */ Collection.prototype.findById = function (id, options) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.find(searchObj, options)[0]; }; /** * Finds all documents that contain the passed string or search object * regardless of where the string might occur within the document. This * will match strings from the start, middle or end of the document's * string (partial match). * @param {String} search The string to search for. Case sensitive. * @param {Object=} options A standard find() options object. * @returns {Array} An array of documents that matched the search string. */ Collection.prototype.peek = function (search, options) { // Loop all items var arr = this._data, arrCount = arr.length, arrIndex, arrItem, tempColl = new Collection(), typeOfSearch = typeof search; if (typeOfSearch === 'string') { for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { // Get json representation of object arrItem = this.jStringify(arr[arrIndex]); // Check if string exists in object json if (arrItem.indexOf(search) > -1) { // Add this item to the temp collection tempColl.insert(arr[arrIndex]); } } return tempColl.find({}, options); } else { return this.find(search, options); } }; /** * Provides a query plan / operations log for a query. * @param {Object} query The query to execute. * @param {Object=} options Optional options object. * @returns {Object} The query plan. */ Collection.prototype.explain = function (query, options) { var result = this.find(query, options); return result.__fdbOp._data; }; /** * Generates an options object with default values or adds default * values to a passed object if those values are not currently set * to anything. * @param {object=} obj Optional options object to modify. * @returns {object} The options object. */ Collection.prototype.options = function (obj) { obj = obj || {}; obj.$decouple = obj.$decouple !== undefined ? obj.$decouple : true; obj.$explain = obj.$explain !== undefined ? obj.$explain : false; return obj; }; /** * Queries the collection based on the query object passed. * @param {Object} query The query key/values that a document must match in * order for it to be returned in the result array. * @param {Object=} options An optional options object. * @param {Function=} callback !! DO NOT USE, THIS IS NON-OPERATIONAL !! * Optional callback. If specified the find process * will not return a value and will assume that you wish to operate under an * async mode. This will break up large find requests into smaller chunks and * process them in a non-blocking fashion allowing large datasets to be queried * without causing the browser UI to pause. Results from this type of operation * will be passed back to the callback once completed. * * @returns {Array} The results array from the find operation, containing all * documents that matched the query. */ Collection.prototype.find = function (query, options, callback) { // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); } if (callback) { // Check the size of the collection's data array // Split operation into smaller tasks and callback when complete callback.call(this, 'Callbacks for the find() operation are not yet implemented!', []); return []; } return this._find.call(this, query, options, callback); }; Collection.prototype._find = function (query, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } // TODO: This method is quite long, break into smaller pieces query = query || {}; var op = this._metrics.create('find'), pk = this.primaryKey(), self = this, analysis, scanLength, requiresTableScan = true, resultArr, joinIndex, joinSource = {}, joinQuery, joinPath, joinSourceKey, joinSourceType, joinSourceIdentifier, joinSourceData, resultRemove = [], i, j, k, fieldListOn = [], fieldListOff = [], elemMatchPathSolver, elemMatchSubArr, elemMatchSpliceArr, matcherTmpOptions = {}, result, cursor = {}, pathSolver, waterfallCollection, matcher; if (!(options instanceof Array)) { options = this.options(options); } matcher = function (doc) { return self._match(doc, query, options, 'and', matcherTmpOptions); }; op.start(); if (query) { // Check if the query is an array (multi-operation waterfall query) if (query instanceof Array) { waterfallCollection = this; // Loop the query operations for (i = 0; i < query.length; i++) { // Execute each operation and pass the result into the next // query operation waterfallCollection = waterfallCollection.subset(query[i], options && options[i] ? options[i] : {}); } return waterfallCollection.find(); } // Pre-process any data-changing query operators first if (query.$findSub) { // Check we have all the parts we need if (!query.$findSub.$path) { throw('$findSub missing $path property!'); } return this.findSub( query.$findSub.$query, query.$findSub.$path, query.$findSub.$subQuery, query.$findSub.$subOptions ); } if (query.$findSubOne) { // Check we have all the parts we need if (!query.$findSubOne.$path) { throw('$findSubOne missing $path property!'); } return this.findSubOne( query.$findSubOne.$query, query.$findSubOne.$path, query.$findSubOne.$subQuery, query.$findSubOne.$subOptions ); } // Get query analysis to execute best optimised code path op.time('analyseQuery'); analysis = this._analyseQuery(self.decouple(query), options, op); op.time('analyseQuery'); op.data('analysis', analysis); // Check if the query tries to limit by data that would only exist after // the join operation has been completed if (analysis.hasJoin && analysis.queriesJoin) { // The query has a join and tries to limit by it's joined data // Get references to the join sources op.time('joinReferences'); for (joinIndex = 0; joinIndex < analysis.joinsOn.length; joinIndex++) { joinSourceData = analysis.joinsOn[joinIndex]; joinSourceKey = joinSourceData.key; joinSourceType = joinSourceData.type; joinSourceIdentifier = joinSourceData.id; joinPath = new Path(analysis.joinQueries[joinSourceKey]); joinQuery = joinPath.value(query)[0]; joinSource[joinSourceIdentifier] = this._db[joinSourceType](joinSourceKey).subset(joinQuery); // Remove join clause from main query delete query[analysis.joinQueries[joinSourceKey]]; } op.time('joinReferences'); } // Check if an index lookup can be used to return this result if (analysis.indexMatch.length && (!options || (options && !options.$skipIndex))) { op.data('index.potential', analysis.indexMatch); op.data('index.used', analysis.indexMatch[0].index); // Get the data from the index op.time('indexLookup'); resultArr = analysis.indexMatch[0].lookup || []; op.time('indexLookup'); // Check if the index coverage is all keys, if not we still need to table scan it if (analysis.indexMatch[0].keyData.totalKeyCount === analysis.indexMatch[0].keyData.score) { // Don't require a table scan to find relevant documents requiresTableScan = false; } } else { op.flag('usedIndex', false); } if (requiresTableScan) { if (resultArr && resultArr.length) { scanLength = resultArr.length; op.time('tableScan: ' + scanLength); // Filter the source data and return the result resultArr = resultArr.filter(matcher); } else { // Filter the source data and return the result scanLength = this._data.length; op.time('tableScan: ' + scanLength); resultArr = this._data.filter(matcher); } op.time('tableScan: ' + scanLength); } // Order the array if we were passed a sort clause if (options.$orderBy) { op.time('sort'); resultArr = this.sort(options.$orderBy, resultArr); op.time('sort'); } if (options.$page !== undefined && options.$limit !== undefined) { // Record paging data cursor.page = options.$page; cursor.pages = Math.ceil(resultArr.length / options.$limit); cursor.records = resultArr.length; // Check if we actually need to apply the paging logic if (options.$page && options.$limit > 0) { op.data('cursor', cursor); // Skip to the page specified based on limit resultArr.splice(0, options.$page * options.$limit); } } if (options.$skip) { cursor.skip = options.$skip; // Skip past the number of records specified resultArr.splice(0, options.$skip); op.data('skip', options.$skip); } if (options.$limit && resultArr && resultArr.length > options.$limit) { cursor.limit = options.$limit; resultArr.length = options.$limit; op.data('limit', options.$limit); } if (options.$decouple) { // Now decouple the data from the original objects op.time('decouple'); resultArr = this.decouple(resultArr); op.time('decouple'); op.data('flag.decouple', true); } // Now process any joins on the final data if (options.$join) { resultRemove = resultRemove.concat(this.applyJoin(resultArr, options.$join, joinSource)); op.data('flag.join', true); } // Process removal queue if (resultRemove.length) { op.time('removalQueue'); this.spliceArrayByIndexList(resultArr, resultRemove); op.time('removalQueue'); } if (options.$transform) { op.time('transform'); for (i = 0; i < resultArr.length; i++) { resultArr.splice(i, 1, options.$transform(resultArr[i])); } op.time('transform'); op.data('flag.transform', true); } // Process transforms if (this._transformEnabled && this._transformOut) { op.time('transformOut'); resultArr = this.transformOut(resultArr); op.time('transformOut'); } op.data('results', resultArr.length); } else { resultArr = []; } // Check for an $as operator in the options object and if it exists // iterate over the fields and generate a rename function that will // operate over the entire returned data array and rename each object's // fields to their new names // TODO: Enable $as in collection find to allow renaming fields /*if (options.$as) { renameFieldPath = new Path(); renameFieldMethod = function (obj, oldFieldPath, newFieldName) { renameFieldPath.path(oldFieldPath); renameFieldPath.rename(newFieldName); }; for (i in options.$as) { if (options.$as.hasOwnProperty(i)) { } } }*/ if (!options.$aggregate) { // Generate a list of fields to limit data by // Each property starts off being enabled by default (= 1) then // if any property is explicitly specified as 1 then all switch to // zero except _id. // // Any that are explicitly set to zero are switched off. op.time('scanFields'); for (i in options) { if (options.hasOwnProperty(i) && i.indexOf('$') !== 0) { if (options[i] === 1) { fieldListOn.push(i); } else if (options[i] === 0) { fieldListOff.push(i); } } } op.time('scanFields'); // Limit returned fields by the options data if (fieldListOn.length || fieldListOff.length) { op.data('flag.limitFields', true); op.data('limitFields.on', fieldListOn); op.data('limitFields.off', fieldListOff); op.time('limitFields'); // We have explicit fields switched on or off for (i = 0; i < resultArr.length; i++) { result = resultArr[i]; for (j in result) { if (result.hasOwnProperty(j)) { if (fieldListOn.length) { // We have explicit fields switched on so remove all fields // that are not explicitly switched on // Check if the field name is not the primary key if (j !== pk) { if (fieldListOn.indexOf(j) === -1) { // This field is not in the on list, remove it delete result[j]; } } } if (fieldListOff.length) { // We have explicit fields switched off so remove fields // that are explicitly switched off if (fieldListOff.indexOf(j) > -1) { // This field is in the off list, remove it delete result[j]; } } } } } op.time('limitFields'); } // Now run any projections on the data required if (options.$elemMatch) { op.data('flag.elemMatch', true); op.time('projection-elemMatch'); for (i in options.$elemMatch) { if (options.$elemMatch.hasOwnProperty(i)) { elemMatchPathSolver = new Path(i); // Loop the results array for (j = 0; j < resultArr.length; j++) { elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0]; // Check we have a sub-array to loop if (elemMatchSubArr && elemMatchSubArr.length) { // Loop the sub-array and check for projection query matches for (k = 0; k < elemMatchSubArr.length; k++) { // Check if the current item in the sub-array matches the projection query if (self._match(elemMatchSubArr[k], options.$elemMatch[i], options, '', {})) { // The item matches the projection query so set the sub-array // to an array that ONLY contains the matching item and then // exit the loop since we only want to match the first item elemMatchPathSolver.set(resultArr[j], i, [elemMatchSubArr[k]]); break; } } } } } } op.time('projection-elemMatch'); } if (options.$elemsMatch) { op.data('flag.elemsMatch', true); op.time('projection-elemsMatch'); for (i in options.$elemsMatch) { if (options.$elemsMatch.hasOwnProperty(i)) { elemMatchPathSolver = new Path(i); // Loop the results array for (j = 0; j < resultArr.length; j++) { elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0]; // Check we have a sub-array to loop if (elemMatchSubArr && elemMatchSubArr.length) { elemMatchSpliceArr = []; // Loop the sub-array and check for projection query matches for (k = 0; k < elemMatchSubArr.length; k++) { // Check if the current item in the sub-array matches the projection query if (self._match(elemMatchSubArr[k], options.$elemsMatch[i], options, '', {})) { // The item matches the projection query so add it to the final array elemMatchSpliceArr.push(elemMatchSubArr[k]); } } // Now set the final sub-array to the matched items elemMatchPathSolver.set(resultArr[j], i, elemMatchSpliceArr); } } } } op.time('projection-elemsMatch'); } } // Process aggregation if (options.$aggregate) { op.data('flag.aggregate', true); op.time('aggregate'); pathSolver = new Path(options.$aggregate); resultArr = pathSolver.value(resultArr); op.time('aggregate'); } // Now process any $groupBy clause if (options.$groupBy) { op.data('flag.group', true); op.time('group'); resultArr = this.group(options.$groupBy, resultArr); op.time('group'); } op.stop(); resultArr.__fdbOp = op; resultArr.$cursor = cursor; return resultArr; }; /** * Returns one document that satisfies the specified query criteria. If multiple * documents satisfy the query, this method returns the first document to match * the query. * @returns {*} */ Collection.prototype.findOne = function () { return (this.find.apply(this, arguments))[0]; }; /** * Gets the index in the collection data array of the first item matched by * the passed query object. * @param {Object} query The query to run to find the item to return the index of. * @param {Object=} options An options object. * @returns {Number} */ Collection.prototype.indexOf = function (query, options) { var item = this.find(query, {$decouple: false})[0], sortedData; if (item) { if (!options || options && !options.$orderBy) { // Basic lookup from order of insert return this._data.indexOf(item); } else { // Trying to locate index based on query with sort order options.$decouple = false; sortedData = this.find(query, options); return sortedData.indexOf(item); } } return -1; }; /** * Returns the index of the document identified by the passed item's primary key. * @param {*} itemLookup The document whose primary key should be used to lookup * or the id to lookup. * @param {Object=} options An options object. * @returns {Number} The index the item with the matching primary key is occupying. */ Collection.prototype.indexOfDocById = function (itemLookup, options) { var item, sortedData; if (typeof itemLookup !== 'object') { item = this._primaryIndex.get(itemLookup); } else { item = this._primaryIndex.get(itemLookup[this._primaryKey]); } if (item) { if (!options || options && !options.$orderBy) { // Basic lookup return this._data.indexOf(item); } else { // Sorted lookup options.$decouple = false; sortedData = this.find({}, options); return sortedData.indexOf(item); } } return -1; }; /** * Removes a document from the collection by it's index in the collection's * data array. * @param {Number} index The index of the document to remove. * @returns {Object} The document that has been removed or false if none was * removed. */ Collection.prototype.removeByIndex = function (index) { var doc, docId; doc = this._data[index]; if (doc !== undefined) { doc = this.decouple(doc); docId = doc[this.primaryKey()]; return this.removeById(docId); } return false; }; /** * Gets / sets the collection transform options. * @param {Object} obj A collection transform options object. * @returns {*} */ Collection.prototype.transform = function (obj) { if (obj !== undefined) { if (typeof obj === "object") { if (obj.enabled !== undefined) { this._transformEnabled = obj.enabled; } if (obj.dataIn !== undefined) { this._transformIn = obj.dataIn; } if (obj.dataOut !== undefined) { this._transformOut = obj.dataOut; } } else { this._transformEnabled = obj !== false; } return this; } return { enabled: this._transformEnabled, dataIn: this._transformIn, dataOut: this._transformOut }; }; /** * Transforms data using the set transformIn method. * @param {Object} data The data to transform. * @returns {*} */ Collection.prototype.transformIn = function (data) { if (this._transformEnabled && this._transformIn) { if (data instanceof Array) { var finalArr = [], transformResult, i; for (i = 0; i < data.length; i++) { transformResult = this._transformIn(data[i]); // Support transforms returning multiple items if (transformResult instanceof Array) { finalArr = finalArr.concat(transformResult); } else { finalArr.push(transformResult); } } return finalArr; } else { return this._transformIn(data); } } return data; }; /** * Transforms data using the set transformOut method. * @param {Object} data The data to transform. * @returns {*} */ Collection.prototype.transformOut = function (data) { if (this._transformEnabled && this._transformOut) { if (data instanceof Array) { var finalArr = [], transformResult, i; for (i = 0; i < data.length; i++) { transformResult = this._transformOut(data[i]); // Support transforms returning multiple items if (transformResult instanceof Array) { finalArr = finalArr.concat(transformResult); } else { finalArr.push(transformResult); } } return finalArr; } else { return this._transformOut(data); } } return data; }; /** * Sorts an array of documents by the given sort path. * @param {*} sortObj The keys and orders the array objects should be sorted by. * @param {Array} arr The array of documents to sort. * @returns {Array} */ Collection.prototype.sort = function (sortObj, arr) { // Convert the index object to an array of key val objects var self = this, keys = sharedPathSolver.parse(sortObj, true); if (keys.length) { // Execute sort arr.sort(function (a, b) { // Loop the index array var i, indexData, result = 0; for (i = 0; i < keys.length; i++) { indexData = keys[i]; if (indexData.value === 1) { result = self.sortAsc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path)); } else if (indexData.value === -1) { result = self.sortDesc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path)); } if (result !== 0) { return result; } } return result; }); } return arr; }; /** * Groups an array of documents into multiple array fields, named by the value * of the given group path. * @param {*} groupObj The key path the array objects should be grouped by. * @param {Array} arr The array of documents to group. * @returns {Object} */ Collection.prototype.group = function (groupObj, arr) { // Convert the index object to an array of key val objects var keys = sharedPathSolver.parse(groupObj, true), groupPathSolver = new Path(), groupValue, groupResult = {}, keyIndex, i; if (keys.length) { for (keyIndex = 0; keyIndex < keys.length; keyIndex++) { groupPathSolver.path(keys[keyIndex].path); // Execute group for (i = 0; i < arr.length; i++) { groupValue = groupPathSolver.get(arr[i]); groupResult[groupValue] = groupResult[groupValue] || []; groupResult[groupValue].push(arr[i]); } } } return groupResult; }; // Commented as we have a new method that was originally implemented for binary trees. // This old method actually has problems with nested sort objects /*Collection.prototype.sortold = function (sortObj, arr) { // Make sure we have an array object arr = arr || []; var sortArr = [], sortKey, sortSingleObj; for (sortKey in sortObj) { if (sortObj.hasOwnProperty(sortKey)) { sortSingleObj = {}; sortSingleObj[sortKey] = sortObj[sortKey]; sortSingleObj.___fdbKey = String(sortKey); sortArr.push(sortSingleObj); } } if (sortArr.length < 2) { // There is only one sort criteria, do a simple sort and return it return this._sort(sortObj, arr); } else { return this._bucketSort(sortArr, arr); } };*/ /** * REMOVED AS SUPERCEDED BY BETTER SORT SYSTEMS * Takes array of sort paths and sorts them into buckets before returning final * array fully sorted by multi-keys. * @param keyArr * @param arr * @returns {*} * @private */ /*Collection.prototype._bucketSort = function (keyArr, arr) { var keyObj = keyArr.shift(), arrCopy, bucketData, bucketOrder, bucketKey, buckets, i, finalArr = []; if (keyArr.length > 0) { // Sort array by bucket key arr = this._sort(keyObj, arr); // Split items into buckets bucketData = this.bucket(keyObj.___fdbKey, arr); bucketOrder = bucketData.order; buckets = bucketData.buckets; // Loop buckets and sort contents for (i = 0; i < bucketOrder.length; i++) { bucketKey = bucketOrder[i]; arrCopy = [].concat(keyArr); finalArr = finalArr.concat(this._bucketSort(arrCopy, buckets[bucketKey])); } return finalArr; } else { return this._sort(keyObj, arr); } };*/ /** * Takes an array of objects and returns a new object with the array items * split into buckets by the passed key. * @param {String} key The key to split the array into buckets by. * @param {Array} arr An array of objects. * @returns {Object} */ /*Collection.prototype.bucket = function (key, arr) { var i, oldField, field, fieldArr = [], buckets = {}; for (i = 0; i < arr.length; i++) { field = String(arr[i][key]); if (oldField !== field) { fieldArr.push(field); oldField = field; } buckets[field] = buckets[field] || []; buckets[field].push(arr[i]); } return { buckets: buckets, order: fieldArr }; };*/ /** * Sorts array by individual sort path. * @param {String} key The path to sort by. * @param {Array} arr The array of objects to sort. * @returns {Array|*} * @private */ Collection.prototype._sort = function (key, arr) { var self = this, sorterMethod, pathSolver = new Path(), dataPath = pathSolver.parse(key, true)[0]; pathSolver.path(dataPath.path); if (dataPath.value === 1) { // Sort ascending sorterMethod = function (a, b) { var valA = pathSolver.value(a)[0], valB = pathSolver.value(b)[0]; return self.sortAsc(valA, valB); }; } else if (dataPath.value === -1) { // Sort descending sorterMethod = function (a, b) { var valA = pathSolver.value(a)[0], valB = pathSolver.value(b)[0]; return self.sortDesc(valA, valB); }; } else { throw(this.logIdentifier() + ' $orderBy clause has invalid direction: ' + dataPath.value + ', accepted values are 1 or -1 for ascending or descending!'); } return arr.sort(sorterMethod); }; /** * Internal method that takes a search query and options and * returns an object containing details about the query which * can be used to optimise the search. * * @param {Object} query The search query to analyse. * @param {Object} options The query options object. * @param {Operation} op The instance of the Operation class that * this operation is using to track things like performance and steps * taken etc. * @returns {Object} * @private */ Collection.prototype._analyseQuery = function (query, options, op) { var analysis = { queriesOn: [{id: '$collection.' + this._name, type: 'colletion', key: this._name}], indexMatch: [], hasJoin: false, queriesJoin: false, joinQueries: {}, query: query, options: options }, joinSourceIndex, joinSourceKey, joinSourceType, joinSourceIdentifier, joinMatch, joinSources = [], joinSourceReferences = [], queryPath, index, indexMatchData, indexRef, indexRefName, indexLookup, pathSolver, queryKeyCount, pkQueryType, lookupResult, i; // Check if the query is a primary key lookup op.time('checkIndexes'); pathSolver = new Path(); queryKeyCount = pathSolver.parseArr(query, { ignore:/\$/, verbose: true }).length; if (queryKeyCount) { if (query[this._primaryKey] !== undefined) { // Check suitability of querying key value index pkQueryType = typeof query[this._primaryKey]; if (pkQueryType === 'string' || pkQueryType === 'number' || query[this._primaryKey] instanceof Array) { // Return item via primary key possible op.time('checkIndexMatch: Primary Key'); lookupResult = this._primaryIndex.lookup(query, options, op); analysis.indexMatch.push({ lookup: lookupResult, keyData: { matchedKeys: [this._primaryKey], totalKeyCount: queryKeyCount, score: 1 }, index: this._primaryIndex }); op.time('checkIndexMatch: Primary Key'); } } // Check if an index can speed up the query for (i in this._indexById) { if (this._indexById.hasOwnProperty(i)) { indexRef = this._indexById[i]; indexRefName = indexRef.name(); op.time('checkIndexMatch: ' + indexRefName); indexMatchData = indexRef.match(query, options); if (indexMatchData.score > 0) { // This index can be used, store it indexLookup = indexRef.lookup(query, options, op); analysis.indexMatch.push({ lookup: indexLookup, keyData: indexMatchData, index: indexRef }); } op.time('checkIndexMatch: ' + indexRefName); if (indexMatchData.score === queryKeyCount) { // Found an optimal index, do not check for any more break; } } } op.time('checkIndexes'); // Sort array descending on index key count (effectively a measure of relevance to the query) if (analysis.indexMatch.length > 1) { op.time('findOptimalIndex'); analysis.indexMatch.sort(function (a, b) { if (a.keyData.score > b.keyData.score) { // This index has a higher score than the other return -1; } if (a.keyData.score < b.keyData.score) { // This index has a lower score than the other return 1; } // The indexes have the same score but can still be compared by the number of records // they return from the query. The fewer records they return the better so order by // record count if (a.keyData.score === b.keyData.score) { return a.lookup.length - b.lookup.length; } }); op.time('findOptimalIndex'); } } // Check for join data if (options.$join) { analysis.hasJoin = true; // Loop all join operations for (joinSourceIndex = 0; joinSourceIndex < options.$join.length; joinSourceIndex++) { // Loop the join sources and keep a reference to them for (joinSourceKey in options.$join[joinSourceIndex]) { if (options.$join[joinSourceIndex].hasOwnProperty(joinSourceKey)) { joinMatch = options.$join[joinSourceIndex][joinSourceKey]; joinSourceType = joinMatch.$sourceType || 'collection'; joinSourceIdentifier = '$' + joinSourceType + '.' + joinSourceKey; joinSources.push({ id: joinSourceIdentifier, type: joinSourceType, key: joinSourceKey }); // Check if the join uses an $as operator if (options.$join[joinSourceIndex][joinSourceKey].$as !== undefined) { joinSourceReferences.push(options.$join[joinSourceIndex][joinSourceKey].$as); } else { joinSourceReferences.push(joinSourceKey); } } } } // Loop the join source references and determine if the query references // any of the sources that are used in the join. If there no queries against // joined sources the find method can use a code path optimised for this. // Queries against joined sources requires the joined sources to be filtered // first and then joined so requires a little more work. for (index = 0; index < joinSourceReferences.length; index++) { // Check if the query references any source data that the join will create queryPath = this._queryReferencesSource(query, joinSourceReferences[index], ''); if (queryPath) { analysis.joinQueries[joinSources[index].key] = queryPath; analysis.queriesJoin = true; } } analysis.joinsOn = joinSources; analysis.queriesOn = analysis.queriesOn.concat(joinSources); } return analysis; }; /** * Checks if the passed query references a source object (such * as a collection) by name. * @param {Object} query The query object to scan. * @param {String} sourceName The source name to scan for in the query. * @param {String=} path The path to scan from. * @returns {*} * @private */ Collection.prototype._queryReferencesSource = function (query, sourceName, path) { var i; for (i in query) { if (query.hasOwnProperty(i)) { // Check if this key is a reference match if (i === sourceName) { if (path) { path += '.'; } return path + i; } else { if (typeof(query[i]) === 'object') { // Recurse if (path) { path += '.'; } path += i; return this._queryReferencesSource(query[i], sourceName, path); } } } } return false; }; /** * Returns the number of documents currently in the collection. * @returns {Number} */ Collection.prototype.count = function (query, options) { if (!query) { return this._data.length; } else { // Run query and return count return this.find(query, options).length; } }; /** * Finds sub-documents from the collection's documents. * @param {Object} match The query object to use when matching * parent documents from which the sub-documents are queried. * @param {String} path The path string used to identify the * key in which sub-documents are stored in parent documents. * @param {Object=} subDocQuery The query to use when matching * which sub-documents to return. * @param {Object=} subDocOptions The options object to use * when querying for sub-documents. * @returns {*} */ Collection.prototype.findSub = function (match, path, subDocQuery, subDocOptions) { return this._findSub(this.find(match), path, subDocQuery, subDocOptions); }; Collection.prototype._findSub = function (docArr, path, subDocQuery, subDocOptions) { var pathHandler = new Path(path), docCount = docArr.length, docIndex, subDocArr, subDocCollection = new Collection('__FDB_temp_' + this.objectId()).db(this._db), subDocResults, resultObj = { parents: docCount, subDocTotal: 0, subDocs: [], pathFound: false, err: '' }; subDocOptions = subDocOptions || {}; for (docIndex = 0; docIndex < docCount; docIndex++) { subDocArr = pathHandler.value(docArr[docIndex])[0]; if (subDocArr) { subDocCollection.setData(subDocArr); subDocResults = subDocCollection.find(subDocQuery, subDocOptions); if (subDocOptions.returnFirst && subDocResults.length) { return subDocResults[0]; } if (subDocOptions.$split) { resultObj.subDocs.push(subDocResults); } else { resultObj.subDocs = resultObj.subDocs.concat(subDocResults); } resultObj.subDocTotal += subDocResults.length; resultObj.pathFound = true; } } // Drop the sub-document collection subDocCollection.drop(); if (!resultObj.pathFound) { resultObj.err = 'No objects found in the parent documents with a matching path of: ' + path; } // Check if the call should not return stats, if so return only subDocs array if (subDocOptions.$stats) { return resultObj; } else { return resultObj.subDocs; } }; /** * Finds the first sub-document from the collection's documents * that matches the subDocQuery parameter. * @param {Object} match The query object to use when matching * parent documents from which the sub-documents are queried. * @param {String} path The path string used to identify the * key in which sub-documents are stored in parent documents. * @param {Object=} subDocQuery The query to use when matching * which sub-documents to return. * @param {Object=} subDocOptions The options object to use * when querying for sub-documents. * @returns {Object} */ Collection.prototype.findSubOne = function (match, path, subDocQuery, subDocOptions) { return this.findSub(match, path, subDocQuery, subDocOptions)[0]; }; /** * Checks that the passed document will not violate any index rules if * inserted into the collection. * @param {Object} doc The document to check indexes against. * @returns {Boolean} Either false (no violation occurred) or true if * a violation was detected. */ Collection.prototype.insertIndexViolation = function (doc) { var indexViolated, arr = this._indexByName, arrIndex, arrItem; // Check the item's primary key is not already in use if (this._primaryIndex.get(doc[this._primaryKey])) { indexViolated = this._primaryIndex; } else { // Check violations of other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arrItem = arr[arrIndex]; if (arrItem.unique()) { if (arrItem.violation(doc)) { indexViolated = arrItem; break; } } } } } return indexViolated ? indexViolated.name() : false; }; /** * Creates an index on the specified keys. * @param {Object} keys The object containing keys to index. * @param {Object} options An options object. * @returns {*} */ Collection.prototype.ensureIndex = function (keys, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } this._indexByName = this._indexByName || {}; this._indexById = this._indexById || {}; var index, time = { start: new Date().getTime() }; if (options) { if (options.type) { // Check if the specified type is available if (Shared.index[options.type]) { // We found the type, generate it index = new Shared.index[options.type](keys, options, this); } else { throw(this.logIdentifier() + ' Cannot create index of type "' + options.type + '", type not found in the index type register (Shared.index)'); } } else { // Create default index type index = new IndexHashMap(keys, options, this); } } else { // Default index = new IndexHashMap(keys, options, this); } // Check the index does not already exist if (this._indexByName[index.name()]) { // Index already exists return { err: 'Index with that name already exists' }; } /*if (this._indexById[index.id()]) { // Index already exists return { err: 'Index with those keys already exists' }; }*/ // Create the index index.rebuild(); // Add the index this._indexByName[index.name()] = index; this._indexById[index.id()] = index; time.end = new Date().getTime(); time.total = time.end - time.start; this._lastOp = { type: 'ensureIndex', stats: { time: time } }; return { index: index, id: index.id(), name: index.name(), state: index.state() }; }; /** * Gets an index by it's name. * @param {String} name The name of the index to retreive. * @returns {*} */ Collection.prototype.index = function (name) { if (this._indexByName) { return this._indexByName[name]; } }; /** * Gets the last reporting operation's details such as run time. * @returns {Object} */ Collection.prototype.lastOp = function () { return this._metrics.list(); }; /** * Generates a difference object that contains insert, update and remove arrays * representing the operations to execute to make this collection have the same * data as the one passed. * @param {Collection} collection The collection to diff against. * @returns {{}} */ Collection.prototype.diff = function (collection) { var diff = { insert: [], update: [], remove: [] }; var pk = this.primaryKey(), arr, arrIndex, arrItem, arrCount; // Check if the primary key index of each collection can be utilised if (pk !== collection.primaryKey()) { throw(this.logIdentifier() + ' Diffing requires that both collections have the same primary key!'); } // Use the collection primary key index to do the diff (super-fast) arr = collection._data; // Check if we have an array or another collection while (arr && !(arr instanceof Array)) { // We don't have an array, assign collection and get data collection = arr; arr = collection._data; } arrCount = arr.length; // Loop the collection's data array and check for matching items for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = arr[arrIndex]; // Check for a matching item in this collection if (this._primaryIndex.get(arrItem[pk])) { // Matching item exists, check if the data is the same if (this._primaryCrc.get(arrItem[pk]) !== collection._primaryCrc.get(arrItem[pk])) { // The documents exist in both collections but data differs, update required diff.update.push(arrItem); } } else { // The document is missing from this collection, insert required diff.insert.push(arrItem); } } // Now loop this collection's data and check for matching items arr = this._data; arrCount = arr.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = arr[arrIndex]; if (!collection._primaryIndex.get(arrItem[pk])) { // The document does not exist in the other collection, remove required diff.remove.push(arrItem); } } return diff; }; Collection.prototype.collateAdd = new Overload('Collection.prototype.collateAdd', { /** * Adds a data source to collate data from and specifies the * key name to collate data to. * @func collateAdd * @memberof Collection * @param {Collection} collection The collection to collate data from. * @param {String=} keyName Optional name of the key to collate data to. * If none is provided the record CRUD is operated on the root collection * data. */ 'object, string': function (collection, keyName) { var self = this; self.collateAdd(collection, function (packet) { var obj1, obj2; switch (packet.type) { case 'insert': if (keyName) { obj1 = { $push: {} }; obj1.$push[keyName] = self.decouple(packet.data.dataSet); self.update({}, obj1); } else { self.insert(packet.data.dataSet); } break; case 'update': if (keyName) { obj1 = {}; obj2 = {}; obj1[keyName] = packet.data.query; obj2[keyName + '.$'] = packet.data.update; self.update(obj1, obj2); } else { self.update(packet.data.query, packet.data.update); } break; case 'remove': if (keyName) { obj1 = { $pull: {} }; obj1.$pull[keyName] = {}; obj1.$pull[keyName][self.primaryKey()] = packet.data.dataSet[0][collection.primaryKey()]; self.update({}, obj1); } else { self.remove(packet.data.dataSet); } break; default: } }); }, /** * Adds a data source to collate data from and specifies a process * method that will handle the collation functionality (for custom * collation). * @func collateAdd * @memberof Collection * @param {Collection} collection The collection to collate data from. * @param {Function} process The process method. */ 'object, function': function (collection, process) { if (typeof collection === 'string') { // The collection passed is a name, not a reference so get // the reference from the name collection = this._db.collection(collection, { autoCreate: false, throwError: false }); } if (collection) { this._collate = this._collate || {}; this._collate[collection.name()] = new ReactorIO(collection, this, process); return this; } else { throw('Cannot collate from a non-existent collection!'); } } }); Collection.prototype.collateRemove = function (collection) { if (typeof collection === 'object') { // We need to have the name of the collection to remove it collection = collection.name(); } if (collection) { // Drop the reactor IO chain node this._collate[collection].drop(); // Remove the collection data from the collate object delete this._collate[collection]; return this; } else { throw('No collection name passed to collateRemove() or collection not found!'); } }; /** * Creates a condition handler that will react to changes in data on the * collection. * @example Create a condition handler that reacts when data changes. * var coll = db.collection('test'), * condition = coll.when({_id: 'test1', val: 1}) * .then(function () { * console.log('Condition met!'); * }) * .else(function () { * console.log('Condition un-met'); * }); * * coll.insert({_id: 'test1', val: 1}); * * @see Condition * @param {Object} query The query that will trigger the condition's then() * callback. * @returns {Condition} */ Collection.prototype.when = function (query) { var queryId = JSON.stringify(query); this._when = this._when || {}; this._when[queryId] = this._when[queryId] || new Condition(this, query); return this._when[queryId]; }; Db.prototype.collection = new Overload('Db.prototype.collection', { /** * Get a collection with no name (generates a random name). If the * collection does not already exist then one is created for that * name automatically. * @func collection * @memberof Db * @returns {Collection} */ '': function () { return this.$main.call(this, { name: this.objectId() }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {Object} data An options object or a collection instance. * @returns {Collection} */ 'object': function (data) { // Handle being passed an instance if (data instanceof Collection) { if (data.state() !== 'droppped') { return data; } else { return this.$main.call(this, { name: data.name() }); } } return this.$main.call(this, data); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @returns {Collection} */ 'string': function (collectionName) { return this.$main.call(this, { name: collectionName }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @param {String} primaryKey Optional primary key to specify the * primary key field on the collection objects. Defaults to "_id". * @returns {Collection} */ 'string, string': function (collectionName, primaryKey) { return this.$main.call(this, { name: collectionName, primaryKey: primaryKey }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @param {Object} options An options object. * @returns {Collection} */ 'string, object': function (collectionName, options) { options.name = collectionName; return this.$main.call(this, options); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @param {String} primaryKey Optional primary key to specify the * primary key field on the collection objects. Defaults to "_id". * @param {Object} options An options object. * @returns {Collection} */ 'string, string, object': function (collectionName, primaryKey, options) { options.name = collectionName; options.primaryKey = primaryKey; return this.$main.call(this, options); }, /** * The main handler method. This gets called by all the other * variants and handles the actual logic of the overloaded method. * @func collection * @memberof Db * @param {Object} options An options object. * @returns {*} */ '$main': function (options) { var self = this, name = options.name; if (name) { if (this._collection[name]) { return this._collection[name]; } else { if (options && options.autoCreate === false) { if (options && options.throwError !== false) { throw(this.logIdentifier() + ' Cannot get collection ' + name + ' because it does not exist and auto-create has been disabled!'); } return undefined; } if (this.debug()) { console.log(this.logIdentifier() + ' Creating collection ' + name); } } this._collection[name] = this._collection[name] || new Collection(name, options).db(this); this._collection[name].mongoEmulation(this.mongoEmulation()); if (options.primaryKey !== undefined) { this._collection[name].primaryKey(options.primaryKey); } if (options.capped !== undefined) { // Check we have a size if (options.size !== undefined) { this._collection[name].capped(options.capped); this._collection[name].cappedSize(options.size); } else { throw(this.logIdentifier() + ' Cannot create a capped collection without specifying a size!'); } } // Listen for events on this collection so we can fire global events // on the database in response to it self._collection[name].on('change', function () { self.emit('change', self._collection[name], 'collection', name); }); self.emit('create', self._collection[name], 'collection', name); return this._collection[name]; } else { if (!options || (options && options.throwError !== false)) { throw(this.logIdentifier() + ' Cannot get collection with undefined name!'); } } } }); /** * Determine if a collection with the passed name already exists. * @memberof Db * @param {String} viewName The name of the collection to check for. * @returns {boolean} */ Db.prototype.collectionExists = function (viewName) { return Boolean(this._collection[viewName]); }; /** * Returns an array of collections the DB currently has. * @memberof Db * @param {String|RegExp=} search The optional search string or * regular expression to use to match collection names against. * @returns {Array} An array of objects containing details of each * collection the database is currently managing. */ Db.prototype.collections = function (search) { var arr = [], collections = this._collection, collection, i; if (search) { if (!(search instanceof RegExp)) { // Turn the search into a regular expression search = new RegExp(search); } } for (i in collections) { if (collections.hasOwnProperty(i)) { collection = collections[i]; if (search) { if (search.exec(i)) { arr.push({ name: i, count: collection.count(), linked: collection.isLinked !== undefined ? collection.isLinked() : false }); } } else { arr.push({ name: i, count: collection.count(), linked: collection.isLinked !== undefined ? collection.isLinked() : false }); } } } arr.sort(function (a, b) { return a.name.localeCompare(b.name); }); return arr; }; Shared.finishModule('Collection'); module.exports = Collection; },{"./Condition":5,"./Index2d":9,"./IndexBinaryTree":10,"./IndexHashMap":11,"./KeyValueStore":12,"./Metrics":13,"./Overload":25,"./Path":26,"./ReactorIO":27,"./Shared":29}],5:[function(_dereq_,module,exports){ "use strict"; /** * The condition class monitors a data source and updates it's internal * state depending on clauses that it has been given. When all clauses * are satisfied the then() callback is fired. If conditions were met * but data changed that made them un-met, the else() callback is fired. */ var Shared, Condition; Shared = _dereq_('./Shared'); /** * Create a constructor method that calls the instance's init method. * This allows the constructor to be overridden by other modules because * they can override the init method with their own. */ Condition = function () { this.init.apply(this, arguments); }; Condition.prototype.init = function (dataSource, clause) { this._dataSource = dataSource; this._query = [clause]; this._started = false; this._state = [false]; this._satisfied = false; // Set this to true by default for faster performance this.earlyExit(true); }; // Tell ForerunnerDB about our new module Shared.addModule('Condition', Condition); // Mixin some commonly used methods Shared.mixin(Condition.prototype, 'Mixin.Common'); Shared.mixin(Condition.prototype, 'Mixin.ChainReactor'); Shared.synthesize(Condition.prototype, 'then'); Shared.synthesize(Condition.prototype, 'else'); Shared.synthesize(Condition.prototype, 'earlyExit'); /** * Adds a new clause to the condition. * @param {Object} clause The query clause to add to the condition. * @returns {Condition} */ Condition.prototype.and = function (clause) { this._query.push(clause); this._state.push(false); return this; }; /** * Starts the condition so that changes to data will call callback * methods according to clauses being met. * @returns {Condition} */ Condition.prototype.start = function () { if (!this._started) { var self = this; // Resolve the current state this._updateStates(); self._onChange = function () { self._updateStates(); }; // Create a chain reactor link to the data source so we start receiving CRUD ops from it this._dataSource.on('change', self._onChange); this._started = true; } return this; }; /** * Updates the internal status of all the clauses against the underlying * data source. * @private */ Condition.prototype._updateStates = function () { var satisfied = true, i; for (i = 0; i < this._query.length; i++) { this._state[i] = this._dataSource.count(this._query[i]) > 0; if (!this._state[i]) { satisfied = false; // Early exit since we have found a state that is not true if (this._earlyExit) { break; } } } if (this._satisfied !== satisfied) { // Our state has changed, fire the relevant operation if (satisfied) { // Fire the "then" operation if (this._then) { this._then(); } } else { // Fire the "else" operation if (this._else) { this._else(); } } this._satisfied = satisfied; } }; /** * Stops the condition so that callbacks will no longer fire. * @returns {Condition} */ Condition.prototype.stop = function () { if (this._started) { this._dataSource.off('change', this._onChange); delete this._onChange; this._started = false; } return this; }; // Tell ForerunnerDB that our module has finished loading Shared.finishModule('Condition'); module.exports = Condition; },{"./Shared":29}],6:[function(_dereq_,module,exports){ /* License Copyright (c) 2015 Irrelon Software Limited http://www.irrelon.com http://www.forerunnerdb.com Please visit the license page to see latest license information: http://www.forerunnerdb.com/licensing.html */ "use strict"; var Shared, Db, Metrics, Overload, _instances = []; Shared = _dereq_('./Shared'); Overload = _dereq_('./Overload'); /** * Creates a new ForerunnerDB instance. Core instances handle the lifecycle of * multiple database instances. * @constructor */ var Core = function (val) { this.init.apply(this, arguments); }; Core.prototype.init = function (name) { this._db = {}; this._debug = {}; this._name = name || 'ForerunnerDB'; _instances.push(this); }; /** * Returns the number of instantiated ForerunnerDB objects. * @returns {Number} The number of instantiated instances. */ Core.prototype.instantiatedCount = function () { return _instances.length; }; /** * Get all instances as an array or a single ForerunnerDB instance * by it's array index. * @param {Number=} index Optional index of instance to get. * @returns {Array|Object} Array of instances or a single instance. */ Core.prototype.instances = function (index) { if (index !== undefined) { return _instances[index]; } return _instances; }; /** * Get all instances as an array of instance names or a single ForerunnerDB * instance by it's name. * @param {String=} name Optional name of instance to get. * @returns {Array|Object} Array of instance names or a single instance. */ Core.prototype.namedInstances = function (name) { var i, instArr; if (name !== undefined) { for (i = 0; i < _instances.length; i++) { if (_instances[i].name === name) { return _instances[i]; } } return undefined; } instArr = []; for (i = 0; i < _instances.length; i++) { instArr.push(_instances[i].name); } return instArr; }; Core.prototype.moduleLoaded = new Overload({ /** * Checks if a module has been loaded into the database. * @func moduleLoaded * @memberof Core * @param {String} moduleName The name of the module to check for. * @returns {Boolean} True if the module is loaded, false if not. */ 'string': function (moduleName) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } return true; } return false; }, /** * Checks if a module is loaded and if so calls the passed * callback method. * @func moduleLoaded * @memberof Core * @param {String} moduleName The name of the module to check for. * @param {Function} callback The callback method to call if module is loaded. */ 'string, function': function (moduleName, callback) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } if (callback) { callback(); } } }, /** * Checks if an array of named modules are loaded and if so * calls the passed callback method. * @func moduleLoaded * @memberof Core * @param {Array} moduleName The array of module names to check for. * @param {Function} callback The callback method to call if modules are loaded. */ 'array, function': function (moduleNameArr, callback) { var moduleName, i; for (i = 0; i < moduleNameArr.length; i++) { moduleName = moduleNameArr[i]; if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } } } if (callback) { callback(); } }, /** * Checks if a module is loaded and if so calls the passed * success method, otherwise calls the failure method. * @func moduleLoaded * @memberof Core * @param {String} moduleName The name of the module to check for. * @param {Function} success The callback method to call if module is loaded. * @param {Function} failure The callback method to call if module not loaded. */ 'string, function, function': function (moduleName, success, failure) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { failure(); return false; } } success(); } } }); /** * Checks version against the string passed and if it matches (or partially matches) * then the callback is called. * @param {String} val The version to check against. * @param {Function} callback The callback to call if match is true. * @returns {Boolean} */ Core.prototype.version = function (val, callback) { if (val !== undefined) { if (Shared.version.indexOf(val) === 0) { if (callback) { callback(); } return true; } return false; } return Shared.version; }; // Expose moduleLoaded() method to non-instantiated object ForerunnerDB Core.moduleLoaded = Core.prototype.moduleLoaded; // Expose version() method to non-instantiated object ForerunnerDB Core.version = Core.prototype.version; // Expose instances() method to non-instantiated object ForerunnerDB Core.instances = Core.prototype.instances; // Expose instantiatedCount() method to non-instantiated object ForerunnerDB Core.instantiatedCount = Core.prototype.instantiatedCount; // Provide public access to the Shared object Core.shared = Shared; Core.prototype.shared = Shared; Shared.addModule('Core', Core); Shared.mixin(Core.prototype, 'Mixin.Common'); Shared.mixin(Core.prototype, 'Mixin.Constants'); Db = _dereq_('./Db.js'); Metrics = _dereq_('./Metrics.js'); /** * Gets / sets the name of the instance. This is primarily used for * name-spacing persistent storage. * @param {String=} val The name of the instance to set. * @returns {*} */ Shared.synthesize(Core.prototype, 'name'); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Core.prototype, 'mongoEmulation'); // Set a flag to determine environment Core.prototype._isServer = false; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a browser. */ Core.prototype.isClient = function () { return !this._isServer; }; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a server. */ Core.prototype.isServer = function () { return this._isServer; }; /** * Added to provide an error message for users who have not seen * the new instantiation breaking change warning and try to get * a collection directly from the core instance. */ Core.prototype.collection = function () { throw("ForerunnerDB's instantiation has changed since version 1.3.36 to support multiple database instances. Please see the readme.md file for the minor change you have to make to get your project back up and running, or see the issue related to this change at https://github.com/Irrelon/ForerunnerDB/issues/44"); }; module.exports = Core; },{"./Db.js":7,"./Metrics.js":13,"./Overload":25,"./Shared":29}],7:[function(_dereq_,module,exports){ "use strict"; var Shared, Core, Collection, Metrics, Checksum, Overload; Shared = _dereq_('./Shared'); Overload = _dereq_('./Overload'); /** * Creates a new ForerunnerDB database instance. * @constructor */ var Db = function (name, core) { this.init.apply(this, arguments); }; Db.prototype.init = function (name, core) { this.core(core); this._primaryKey = '_id'; this._name = name; this._collection = {}; this._debug = {}; }; Shared.addModule('Db', Db); Db.prototype.moduleLoaded = new Overload({ /** * Checks if a module has been loaded into the database. * @func moduleLoaded * @memberof Db * @param {String} moduleName The name of the module to check for. * @returns {Boolean} True if the module is loaded, false if not. */ 'string': function (moduleName) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } return true; } return false; }, /** * Checks if a module is loaded and if so calls the passed * callback method. * @func moduleLoaded * @memberof Db * @param {String} moduleName The name of the module to check for. * @param {Function} callback The callback method to call if module is loaded. */ 'string, function': function (moduleName, callback) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } if (callback) { callback(); } } }, /** * Checks if a module is loaded and if so calls the passed * success method, otherwise calls the failure method. * @func moduleLoaded * @memberof Db * @param {String} moduleName The name of the module to check for. * @param {Function} success The callback method to call if module is loaded. * @param {Function} failure The callback method to call if module not loaded. */ 'string, function, function': function (moduleName, success, failure) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { failure(); return false; } } success(); } } }); /** * Checks version against the string passed and if it matches (or partially matches) * then the callback is called. * @param {String} val The version to check against. * @param {Function} callback The callback to call if match is true. * @returns {Boolean} */ Db.prototype.version = function (val, callback) { if (val !== undefined) { if (Shared.version.indexOf(val) === 0) { if (callback) { callback(); } return true; } return false; } return Shared.version; }; // Expose moduleLoaded method to non-instantiated object ForerunnerDB Db.moduleLoaded = Db.prototype.moduleLoaded; // Expose version method to non-instantiated object ForerunnerDB Db.version = Db.prototype.version; // Provide public access to the Shared object Db.shared = Shared; Db.prototype.shared = Shared; Shared.addModule('Db', Db); Shared.mixin(Db.prototype, 'Mixin.Common'); Shared.mixin(Db.prototype, 'Mixin.ChainReactor'); Shared.mixin(Db.prototype, 'Mixin.Constants'); Shared.mixin(Db.prototype, 'Mixin.Tags'); Core = Shared.modules.Core; Collection = _dereq_('./Collection.js'); Metrics = _dereq_('./Metrics.js'); Checksum = _dereq_('./Checksum.js'); Db.prototype._isServer = false; /** * Gets / sets the core object this database belongs to. */ Shared.synthesize(Db.prototype, 'core'); /** * Gets / sets the default primary key for new collections. * @param {String=} val The name of the primary key to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'primaryKey'); /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'state'); /** * Gets / sets the name of the database. * @param {String=} val The name of the database to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'name'); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Db.prototype, 'mongoEmulation'); /** * Returns true if ForerunnerDB is running on a client browser. * @returns {boolean} */ Db.prototype.isClient = function () { return !this._isServer; }; /** * Returns true if ForerunnerDB is running on a server. * @returns {boolean} */ Db.prototype.isServer = function () { return this._isServer; }; /** * Returns a checksum of a string. * @param {String} string The string to checksum. * @return {String} The checksum generated. */ Db.prototype.Checksum = Checksum; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a browser. */ Db.prototype.isClient = function () { return !this._isServer; }; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a server. */ Db.prototype.isServer = function () { return this._isServer; }; /** * Converts a normal javascript array of objects into a DB collection. * @param {Array} arr An array of objects. * @returns {Collection} A new collection instance with the data set to the * array passed. */ Db.prototype.arrayToCollection = function (arr) { return new Collection().setData(arr); }; /** * Registers an event listener against an event name. * @param {String} event The name of the event to listen for. * @param {Function} listener The listener method to call when * the event is fired. * @returns {*} */ Db.prototype.on = function(event, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || []; this._listeners[event].push(listener); return this; }; /** * De-registers an event listener from an event name. * @param {String} event The name of the event to stop listening for. * @param {Function} listener The listener method passed to on() when * registering the event listener. * @returns {*} */ Db.prototype.off = function(event, listener) { if (event in this._listeners) { var arr = this._listeners[event], index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } return this; }; /** * Emits an event by name with the given data. * @param {String} event The name of the event to emit. * @param {*=} data The data to emit with the event. * @returns {*} */ Db.prototype.emit = function(event, data) { this._listeners = this._listeners || {}; if (event in this._listeners) { var arr = this._listeners[event], arrCount = arr.length, arrIndex; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arr[arrIndex].apply(this, Array.prototype.slice.call(arguments, 1)); } } return this; }; Db.prototype.peek = function (search) { var i, coll, arr = [], typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = arr.concat(coll.peek(search)); } else { arr = arr.concat(coll.find(search)); } } } return arr; }; /** * Find all documents across all collections in the database that match the passed * string or search object. * @param search String or search object. * @returns {Array} */ Db.prototype.peek = function (search) { var i, coll, arr = [], typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = arr.concat(coll.peek(search)); } else { arr = arr.concat(coll.find(search)); } } } return arr; }; /** * Find all documents across all collections in the database that match the passed * string or search object and return them in an object where each key is the name * of the collection that the document was matched in. * @param search String or search object. * @returns {object} */ Db.prototype.peekCat = function (search) { var i, coll, cat = {}, arr, typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = coll.peek(search); if (arr && arr.length) { cat[coll.name()] = arr; } } else { arr = coll.find(search); if (arr && arr.length) { cat[coll.name()] = arr; } } } } return cat; }; Db.prototype.drop = new Overload({ /** * Drops the database. * @func drop * @memberof Db */ '': function () { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; }, /** * Drops the database with optional callback method. * @func drop * @memberof Db * @param {Function} callback Optional callback method. */ 'function': function (callback) { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex, finishCount = 0, afterDrop = function () { finishCount++; if (finishCount === arrCount) { if (callback) { callback(); } } }; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(afterDrop); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; }, /** * Drops the database with optional persistent storage drop. Persistent * storage is dropped by default if no preference is provided. * @func drop * @memberof Db * @param {Boolean} removePersist Drop persistent storage for this database. */ 'boolean': function (removePersist) { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(removePersist); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; }, /** * Drops the database and optionally controls dropping persistent storage * and callback method. * @func drop * @memberof Db * @param {Boolean} removePersist Drop persistent storage for this database. * @param {Function} callback Optional callback method. */ 'boolean, function': function (removePersist, callback) { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex, finishCount = 0, afterDrop = function () { finishCount++; if (finishCount === arrCount) { if (callback) { callback(); } } }; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(removePersist, afterDrop); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; } }); /** * Gets a database instance by name. * @memberof Core * @param {String=} name Optional name of the database. If none is provided * a random name is assigned. * @returns {Db} */ Core.prototype.db = function (name) { // Handle being passed an instance if (name instanceof Db) { return name; } if (!name) { name = this.objectId(); } this._db[name] = this._db[name] || new Db(name, this); this._db[name].mongoEmulation(this.mongoEmulation()); return this._db[name]; }; /** * Returns an array of databases that ForerunnerDB currently has. * @memberof Core * @param {String|RegExp=} search The optional search string or regular expression to use * to match collection names against. * @returns {Array} An array of objects containing details of each database * that ForerunnerDB is currently managing and it's child entities. */ Core.prototype.databases = function (search) { var arr = [], tmpObj, addDb, i; if (search) { if (!(search instanceof RegExp)) { // Turn the search into a regular expression search = new RegExp(search); } } for (i in this._db) { if (this._db.hasOwnProperty(i)) { addDb = true; if (search) { if (!search.exec(i)) { addDb = false; } } if (addDb) { tmpObj = { name: i, children: [] }; if (this.shared.moduleExists('Collection')) { tmpObj.children.push({ module: 'collection', moduleName: 'Collections', count: this._db[i].collections().length }); } if (this.shared.moduleExists('CollectionGroup')) { tmpObj.children.push({ module: 'collectionGroup', moduleName: 'Collection Groups', count: this._db[i].collectionGroups().length }); } if (this.shared.moduleExists('Document')) { tmpObj.children.push({ module: 'document', moduleName: 'Documents', count: this._db[i].documents().length }); } if (this.shared.moduleExists('Grid')) { tmpObj.children.push({ module: 'grid', moduleName: 'Grids', count: this._db[i].grids().length }); } if (this.shared.moduleExists('Overview')) { tmpObj.children.push({ module: 'overview', moduleName: 'Overviews', count: this._db[i].overviews().length }); } if (this.shared.moduleExists('View')) { tmpObj.children.push({ module: 'view', moduleName: 'Views', count: this._db[i].views().length }); } arr.push(tmpObj); } } } arr.sort(function (a, b) { return a.name.localeCompare(b.name); }); return arr; }; Shared.finishModule('Db'); module.exports = Db; },{"./Checksum.js":3,"./Collection.js":4,"./Metrics.js":13,"./Overload":25,"./Shared":29}],8:[function(_dereq_,module,exports){ // geohash.js // Geohash library for Javascript // (c) 2008 David Troy // Distributed under the MIT License // Original at: https://github.com/davetroy/geohash-js // Modified by Irrelon Software Limited (http://www.irrelon.com) // to clean up and modularise the code using Node.js-style exports // and add a few helper methods. // @by Rob Evans - [email protected] "use strict"; /* Define some shared constants that will be used by all instances of the module. */ var bits, base32, neighbors, borders, PI180 = Math.PI / 180, PI180R = 180 / Math.PI, earthRadius = 6371; // mean radius of the earth bits = [16, 8, 4, 2, 1]; base32 = "0123456789bcdefghjkmnpqrstuvwxyz"; neighbors = { right: {even: "bc01fg45238967deuvhjyznpkmstqrwx"}, left: {even: "238967debc01fg45kmstqrwxuvhjyznp"}, top: {even: "p0r21436x8zb9dcf5h7kjnmqesgutwvy"}, bottom: {even: "14365h7k9dcfesgujnmqp0r2twvyx8zb"} }; borders = { right: {even: "bcfguvyz"}, left: {even: "0145hjnp"}, top: {even: "prxz"}, bottom: {even: "028b"} }; neighbors.bottom.odd = neighbors.left.even; neighbors.top.odd = neighbors.right.even; neighbors.left.odd = neighbors.bottom.even; neighbors.right.odd = neighbors.top.even; borders.bottom.odd = borders.left.even; borders.top.odd = borders.right.even; borders.left.odd = borders.bottom.even; borders.right.odd = borders.top.even; var GeoHash = function () {}; /** * Converts degrees to radians. * @param {Number} degrees * @return {Number} radians */ GeoHash.prototype.radians = function radians (degrees) { return degrees * PI180; }; /** * Converts radians to degrees. * @param {Number} radians * @return {Number} degrees */ GeoHash.prototype.degrees = function (radians) { return radians * PI180R; }; GeoHash.prototype.refineInterval = function (interval, cd, mask) { if (cd & mask) { //jshint ignore: line interval[0] = (interval[0] + interval[1]) / 2; } else { interval[1] = (interval[0] + interval[1]) / 2; } }; /** * Calculates all surrounding neighbours of a hash and returns them. * @param {String} centerHash The hash at the center of the grid. * @param options * @returns {*} */ GeoHash.prototype.calculateNeighbours = function (centerHash, options) { var response; if (!options || options.type === 'object') { response = { center: centerHash, left: this.calculateAdjacent(centerHash, 'left'), right: this.calculateAdjacent(centerHash, 'right'), top: this.calculateAdjacent(centerHash, 'top'), bottom: this.calculateAdjacent(centerHash, 'bottom') }; response.topLeft = this.calculateAdjacent(response.left, 'top'); response.topRight = this.calculateAdjacent(response.right, 'top'); response.bottomLeft = this.calculateAdjacent(response.left, 'bottom'); response.bottomRight = this.calculateAdjacent(response.right, 'bottom'); } else { response = []; response[4] = centerHash; response[3] = this.calculateAdjacent(centerHash, 'left'); response[5] = this.calculateAdjacent(centerHash, 'right'); response[1] = this.calculateAdjacent(centerHash, 'top'); response[7] = this.calculateAdjacent(centerHash, 'bottom'); response[0] = this.calculateAdjacent(response[3], 'top'); response[2] = this.calculateAdjacent(response[5], 'top'); response[6] = this.calculateAdjacent(response[3], 'bottom'); response[8] = this.calculateAdjacent(response[5], 'bottom'); } return response; }; /** * Calculates a new lat/lng by travelling from the center point in the * bearing specified for the distance specified. * @param {Array} centerPoint An array with latitude at index 0 and * longitude at index 1. * @param {Number} distanceKm The distance to travel in kilometers. * @param {Number} bearing The bearing to travel in degrees (zero is * north). * @returns {{lat: Number, lng: Number}} */ GeoHash.prototype.calculateLatLngByDistanceBearing = function (centerPoint, distanceKm, bearing) { var curLon = centerPoint[1], curLat = centerPoint[0], destLat = Math.asin(Math.sin(this.radians(curLat)) * Math.cos(distanceKm / earthRadius) + Math.cos(this.radians(curLat)) * Math.sin(distanceKm / earthRadius) * Math.cos(this.radians(bearing))), tmpLon = this.radians(curLon) + Math.atan2(Math.sin(this.radians(bearing)) * Math.sin(distanceKm / earthRadius) * Math.cos(this.radians(curLat)), Math.cos(distanceKm / earthRadius) - Math.sin(this.radians(curLat)) * Math.sin(destLat)), destLon = (tmpLon + 3 * Math.PI) % (2 * Math.PI) - Math.PI; // normalise to -180..+180º return { lat: this.degrees(destLat), lng: this.degrees(destLon) }; }; /** * Calculates the extents of a bounding box around the center point which * encompasses the radius in kilometers passed. * @param {Array} centerPoint An array with latitude at index 0 and * longitude at index 1. * @param radiusKm Radius in kilometers. * @returns {{lat: Array, lng: Array}} */ GeoHash.prototype.calculateExtentByRadius = function (centerPoint, radiusKm) { var maxWest, maxEast, maxNorth, maxSouth, lat = [], lng = []; maxNorth = this.calculateLatLngByDistanceBearing(centerPoint, radiusKm, 0); maxEast = this.calculateLatLngByDistanceBearing(centerPoint, radiusKm, 90); maxSouth = this.calculateLatLngByDistanceBearing(centerPoint, radiusKm, 180); maxWest = this.calculateLatLngByDistanceBearing(centerPoint, radiusKm, 270); lat[0] = maxNorth.lat; lat[1] = maxSouth.lat; lng[0] = maxWest.lng; lng[1] = maxEast.lng; return { lat: lat, lng: lng }; }; /** * Calculates all the geohashes that make up the bounding box that surrounds * the circle created from the center point and radius passed. * @param {Array} centerPoint An array with latitude at index 0 and * longitude at index 1. * @param {Number} radiusKm The radius in kilometers to encompass. * @param {Number} precision The number of characters to limit the returned * geohash strings to. * @returns {Array} The array of geohashes that encompass the bounding box. */ GeoHash.prototype.calculateHashArrayByRadius = function (centerPoint, radiusKm, precision) { var extent = this.calculateExtentByRadius(centerPoint, radiusKm), northWest = [extent.lat[0], extent.lng[0]], northEast = [extent.lat[0], extent.lng[1]], southWest = [extent.lat[1], extent.lng[0]], northWestHash = this.encode(northWest[0], northWest[1], precision), northEastHash = this.encode(northEast[0], northEast[1], precision), southWestHash = this.encode(southWest[0], southWest[1], precision), hash, widthCount = 0, heightCount = 0, widthIndex, heightIndex, hashArray = []; hash = northWestHash; hashArray.push(hash); // Walk from north west to north east until we find the north east geohash while (hash !== northEastHash) { hash = this.calculateAdjacent(hash, 'right'); widthCount++; hashArray.push(hash); } hash = northWestHash; // Walk from north west to south west until we find the south west geohash while (hash !== southWestHash) { hash = this.calculateAdjacent(hash, 'bottom'); heightCount++; } // We now know the width and height in hash boxes of the area, fill in the // rest of the hashes into the hashArray array for (widthIndex = 0; widthIndex <= widthCount; widthIndex++) { hash = hashArray[widthIndex]; for (heightIndex = 0; heightIndex < heightCount; heightIndex++) { hash = this.calculateAdjacent(hash, 'bottom'); hashArray.push(hash); } } return hashArray; }; /** * Calculates an adjacent hash to the hash passed, in the direction * specified. * @param {String} srcHash The hash to calculate adjacent to. * @param {String} dir Either "top", "left", "bottom" or "right". * @returns {String} The resulting geohash. */ GeoHash.prototype.calculateAdjacent = function (srcHash, dir) { srcHash = srcHash.toLowerCase(); var lastChr = srcHash.charAt(srcHash.length - 1), type = (srcHash.length % 2) ? 'odd' : 'even', base = srcHash.substring(0, srcHash.length - 1); if (borders[dir][type].indexOf(lastChr) !== -1) { base = this.calculateAdjacent(base, dir); } return base + base32[neighbors[dir][type].indexOf(lastChr)]; }; /** * Decodes a string geohash back to a longitude/latitude array. * The array contains three latitudes and three longitudes. The * first of each is the lower extent of the geohash bounding box, * the second is the upper extent and the third is the center * of the geohash bounding box. * @param {String} geohash The hash to decode. * @returns {Object} */ GeoHash.prototype.decode = function (geohash) { var isEven = 1, lat = [], lon = [], i, c, cd, j, mask, latErr, lonErr; lat[0] = -90.0; lat[1] = 90.0; lon[0] = -180.0; lon[1] = 180.0; latErr = 90.0; lonErr = 180.0; for (i = 0; i < geohash.length; i++) { c = geohash[i]; cd = base32.indexOf(c); for (j = 0; j < 5; j++) { mask = bits[j]; if (isEven) { lonErr /= 2; this.refineInterval(lon, cd, mask); } else { latErr /= 2; this.refineInterval(lat, cd, mask); } isEven = !isEven; } } lat[2] = (lat[0] + lat[1]) / 2; lon[2] = (lon[0] + lon[1]) / 2; return { lat: lat, lng: lon }; }; /** * Encodes a longitude/latitude to geohash string. * @param latitude * @param longitude * @param {Number=} precision Length of the geohash string. Defaults to 12. * @returns {String} */ GeoHash.prototype.encode = function (latitude, longitude, precision) { var isEven = 1, mid, lat = [], lon = [], bit = 0, ch = 0, geoHash = ""; if (!precision) { precision = 12; } lat[0] = -90.0; lat[1] = 90.0; lon[0] = -180.0; lon[1] = 180.0; while (geoHash.length < precision) { if (isEven) { mid = (lon[0] + lon[1]) / 2; if (longitude > mid) { ch |= bits[bit]; //jshint ignore: line lon[0] = mid; } else { lon[1] = mid; } } else { mid = (lat[0] + lat[1]) / 2; if (latitude > mid) { ch |= bits[bit]; //jshint ignore: line lat[0] = mid; } else { lat[1] = mid; } } isEven = !isEven; if (bit < 4) { bit++; } else { geoHash += base32[ch]; bit = 0; ch = 0; } } return geoHash; }; if (typeof module !== 'undefined') { module.exports = GeoHash; } },{}],9:[function(_dereq_,module,exports){ "use strict"; /* name(string) id(string) rebuild(null) state ?? needed? match(query, options) lookup(query, options) insert(doc) remove(doc) primaryKey(string) collection(collection) */ var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), BinaryTree = _dereq_('./BinaryTree'), GeoHash = _dereq_('./GeoHash'), sharedPathSolver = new Path(), sharedGeoHashSolver = new GeoHash(), // GeoHash Distances in Kilometers geoHashDistance = [ 5000, 1250, 156, 39.1, 4.89, 1.22, 0.153, 0.0382, 0.00477, 0.00119, 0.000149, 0.0000372 ]; /** * The index class used to instantiate 2d indexes that the database can * use to handle high-performance geospatial queries. * @constructor */ var Index2d = function () { this.init.apply(this, arguments); }; /** * Create the index. * @param {Object} keys The object with the keys that the user wishes the index * to operate on. * @param {Object} options Can be undefined, if passed is an object with arbitrary * options keys and values. * @param {Collection} collection The collection the index should be created for. */ Index2d.prototype.init = function (keys, options, collection) { this._btree = new BinaryTree(); this._btree.index(keys); this._size = 0; this._id = this._itemKeyHash(keys, keys); this._debug = options && options.debug ? options.debug : false; this.unique(options && options.unique ? options.unique : false); if (keys !== undefined) { this.keys(keys); } if (collection !== undefined) { this.collection(collection); this._btree.primaryKey(collection.primaryKey()); } this.name(options && options.name ? options.name : this._id); this._btree.debug(this._debug); }; Shared.addModule('Index2d', Index2d); Shared.mixin(Index2d.prototype, 'Mixin.Common'); Shared.mixin(Index2d.prototype, 'Mixin.ChainReactor'); Shared.mixin(Index2d.prototype, 'Mixin.Sorting'); Index2d.prototype.id = function () { return this._id; }; Index2d.prototype.state = function () { return this._state; }; Index2d.prototype.size = function () { return this._size; }; Shared.synthesize(Index2d.prototype, 'data'); Shared.synthesize(Index2d.prototype, 'name'); Shared.synthesize(Index2d.prototype, 'collection'); Shared.synthesize(Index2d.prototype, 'type'); Shared.synthesize(Index2d.prototype, 'unique'); Index2d.prototype.keys = function (val) { if (val !== undefined) { this._keys = val; // Count the keys this._keyCount = sharedPathSolver.parse(this._keys).length; return this; } return this._keys; }; Index2d.prototype.rebuild = function () { // Do we have a collection? if (this._collection) { // Get sorted data var collection = this._collection.subset({}, { $decouple: false, $orderBy: this._keys }), collectionData = collection.find(), dataIndex, dataCount = collectionData.length; // Clear the index data for the index this._btree.clear(); this._size = 0; if (this._unique) { this._uniqueLookup = {}; } // Loop the collection data for (dataIndex = 0; dataIndex < dataCount; dataIndex++) { this.insert(collectionData[dataIndex]); } } this._state = { name: this._name, keys: this._keys, indexSize: this._size, built: new Date(), updated: new Date(), ok: true }; }; Index2d.prototype.insert = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash; dataItem = this.decouple(dataItem); if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } // Convert 2d indexed values to geohashes var keys = this._btree.keys(), pathVal, geoHash, lng, lat, i; for (i = 0; i < keys.length; i++) { pathVal = sharedPathSolver.get(dataItem, keys[i].path); if (pathVal instanceof Array) { lng = pathVal[0]; lat = pathVal[1]; geoHash = sharedGeoHashSolver.encode(lng, lat); sharedPathSolver.set(dataItem, keys[i].path, geoHash); } } if (this._btree.insert(dataItem)) { this._size++; return true; } return false; }; Index2d.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } if (this._btree.remove(dataItem)) { this._size--; return true; } return false; }; Index2d.prototype.violation = function (dataItem) { // Generate item hash var uniqueHash = this._itemHash(dataItem, this._keys); // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; Index2d.prototype.hashViolation = function (uniqueHash) { // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; /** * Looks up records that match the passed query and options. * @param query The query to execute. * @param options A query options object. * @param {Operation=} op Optional operation instance that allows * us to provide operation diagnostics and analytics back to the * main calling instance as the process is running. * @returns {*} */ Index2d.prototype.lookup = function (query, options, op) { // Loop the indexed keys and determine if the query has any operators // that we want to handle differently from a standard lookup var keys = this._btree.keys(), pathStr, pathVal, results, i; for (i = 0; i < keys.length; i++) { pathStr = keys[i].path; pathVal = sharedPathSolver.get(query, pathStr); if (typeof pathVal === 'object') { if (pathVal.$near) { results = []; // Do a near point lookup results = results.concat(this.near(pathStr, pathVal.$near, options, op)); } if (pathVal.$geoWithin) { results = []; // Do a geoWithin shape lookup results = results.concat(this.geoWithin(pathStr, pathVal.$geoWithin, options, op)); } return results; } } return this._btree.lookup(query, options); }; Index2d.prototype.near = function (pathStr, query, options, op) { var self = this, neighbours, visitedCount, visitedNodes, visitedData, search, results, finalResults = [], precision, maxDistanceKm, distance, distCache, latLng, pk = this._collection.primaryKey(), i; // Calculate the required precision to encapsulate the distance // TODO: Instead of opting for the "one size larger" than the distance boxes, // TODO: we should calculate closest divisible box size as a multiple and then // TODO: scan neighbours until we have covered the area otherwise we risk // TODO: opening the results up to vastly more information as the box size // TODO: increases dramatically between the geohash precisions if (query.$distanceUnits === 'km') { maxDistanceKm = query.$maxDistance; for (i = 0; i < geoHashDistance.length; i++) { if (maxDistanceKm > geoHashDistance[i]) { precision = i + 1; break; } } } else if (query.$distanceUnits === 'miles') { maxDistanceKm = query.$maxDistance * 1.60934; for (i = 0; i < geoHashDistance.length; i++) { if (maxDistanceKm > geoHashDistance[i]) { precision = i + 1; break; } } } if (precision === 0) { precision = 1; } // Calculate 9 box geohashes if (op) { op.time('index2d.calculateHashArea'); } neighbours = sharedGeoHashSolver.calculateHashArrayByRadius(query.$point, maxDistanceKm, precision); if (op) { op.time('index2d.calculateHashArea'); } if (op) { op.data('index2d.near.precision', precision); op.data('index2d.near.hashArea', neighbours); op.data('index2d.near.maxDistanceKm', maxDistanceKm); op.data('index2d.near.centerPointCoords', [query.$point[0], query.$point[1]]); } // Lookup all matching co-ordinates from the btree results = []; visitedCount = 0; visitedData = {}; visitedNodes = []; if (op) { op.time('index2d.near.getDocsInsideHashArea'); } for (i = 0; i < neighbours.length; i++) { search = this._btree.startsWith(pathStr, neighbours[i]); visitedData[neighbours[i]] = search; visitedCount += search._visitedCount; visitedNodes = visitedNodes.concat(search._visitedNodes); results = results.concat(search); } if (op) { op.time('index2d.near.getDocsInsideHashArea'); op.data('index2d.near.startsWith', visitedData); op.data('index2d.near.visitedTreeNodes', visitedNodes); } // Work with original data if (op) { op.time('index2d.near.lookupDocsById'); } results = this._collection._primaryIndex.lookup(results); if (op) { op.time('index2d.near.lookupDocsById'); } if (query.$distanceField) { // Decouple the results before we modify them results = this.decouple(results); } if (results.length) { distance = {}; if (op) { op.time('index2d.near.calculateDistanceFromCenter'); } // Loop the results and calculate distance for (i = 0; i < results.length; i++) { latLng = sharedPathSolver.get(results[i], pathStr); distCache = distance[results[i][pk]] = this.distanceBetweenPoints(query.$point[0], query.$point[1], latLng[0], latLng[1]); if (distCache <= maxDistanceKm) { if (query.$distanceField) { // Options specify a field to add the distance data to // so add it now sharedPathSolver.set(results[i], query.$distanceField, query.$distanceUnits === 'km' ? distCache : Math.round(distCache * 0.621371)); } if (query.$geoHashField) { // Options specify a field to add the distance data to // so add it now sharedPathSolver.set(results[i], query.$geoHashField, sharedGeoHashSolver.encode(latLng[0], latLng[1], precision)); } // Add item as it is inside radius distance finalResults.push(results[i]); } } if (op) { op.time('index2d.near.calculateDistanceFromCenter'); } // Sort by distance from center if (op) { op.time('index2d.near.sortResultsByDistance'); } finalResults.sort(function (a, b) { return self.sortAsc(distance[a[pk]], distance[b[pk]]); }); if (op) { op.time('index2d.near.sortResultsByDistance'); } } // Return data return finalResults; }; Index2d.prototype.geoWithin = function (pathStr, query, options) { console.log('geoWithin() is currently a prototype method with no actual implementation... it just returns a blank array.'); return []; }; Index2d.prototype.distanceBetweenPoints = function (lat1, lng1, lat2, lng2) { var R = 6371; // kilometres var lat1Rad = this.toRadians(lat1); var lat2Rad = this.toRadians(lat2); var lat2MinusLat1Rad = this.toRadians(lat2-lat1); var lng2MinusLng1Rad = this.toRadians(lng2-lng1); var a = Math.sin(lat2MinusLat1Rad/2) * Math.sin(lat2MinusLat1Rad/2) + Math.cos(lat1Rad) * Math.cos(lat2Rad) * Math.sin(lng2MinusLng1Rad/2) * Math.sin(lng2MinusLng1Rad/2); var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); return R * c; }; Index2d.prototype.toRadians = function (degrees) { return degrees * 0.01747722222222; }; Index2d.prototype.match = function (query, options) { // TODO: work out how to represent that this is a better match if the query has $near than // TODO: a basic btree index which will not be able to resolve a $near operator return this._btree.match(query, options); }; Index2d.prototype._itemHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.value(item, pathData[k].path).join(':'); } return hash; }; Index2d.prototype._itemKeyHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.keyValue(item, pathData[k].path); } return hash; }; Index2d.prototype._itemHashArr = function (item, keys) { var path = new Path(), pathData, //hash = '', hashArr = [], valArr, i, k, j; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { valArr = path.value(item, pathData[k].path); for (i = 0; i < valArr.length; i++) { if (k === 0) { // Setup the initial hash array hashArr.push(valArr[i]); } else { // Loop the hash array and concat the value to it for (j = 0; j < hashArr.length; j++) { hashArr[j] = hashArr[j] + '_' + valArr[i]; } } } } return hashArr; }; // Register this index on the shared object Shared.index['2d'] = Index2d; Shared.finishModule('Index2d'); module.exports = Index2d; },{"./BinaryTree":2,"./GeoHash":8,"./Path":26,"./Shared":29}],10:[function(_dereq_,module,exports){ "use strict"; /* name(string) id(string) rebuild(null) state ?? needed? match(query, options) lookup(query, options) insert(doc) remove(doc) primaryKey(string) collection(collection) */ var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), BinaryTree = _dereq_('./BinaryTree'); /** * The index class used to instantiate btree indexes that the database can * use to speed up queries on collections and views. * @constructor */ var IndexBinaryTree = function () { this.init.apply(this, arguments); }; IndexBinaryTree.prototype.init = function (keys, options, collection) { this._btree = new BinaryTree(); this._btree.index(keys); this._size = 0; this._id = this._itemKeyHash(keys, keys); this._debug = options && options.debug ? options.debug : false; this.unique(options && options.unique ? options.unique : false); if (keys !== undefined) { this.keys(keys); } if (collection !== undefined) { this.collection(collection); this._btree.primaryKey(collection.primaryKey()); } this.name(options && options.name ? options.name : this._id); this._btree.debug(this._debug); }; Shared.addModule('IndexBinaryTree', IndexBinaryTree); Shared.mixin(IndexBinaryTree.prototype, 'Mixin.ChainReactor'); Shared.mixin(IndexBinaryTree.prototype, 'Mixin.Sorting'); IndexBinaryTree.prototype.id = function () { return this._id; }; IndexBinaryTree.prototype.state = function () { return this._state; }; IndexBinaryTree.prototype.size = function () { return this._size; }; Shared.synthesize(IndexBinaryTree.prototype, 'data'); Shared.synthesize(IndexBinaryTree.prototype, 'name'); Shared.synthesize(IndexBinaryTree.prototype, 'collection'); Shared.synthesize(IndexBinaryTree.prototype, 'type'); Shared.synthesize(IndexBinaryTree.prototype, 'unique'); IndexBinaryTree.prototype.keys = function (val) { if (val !== undefined) { this._keys = val; // Count the keys this._keyCount = (new Path()).parse(this._keys).length; return this; } return this._keys; }; IndexBinaryTree.prototype.rebuild = function () { // Do we have a collection? if (this._collection) { // Get sorted data var collection = this._collection.subset({}, { $decouple: false, $orderBy: this._keys }), collectionData = collection.find(), dataIndex, dataCount = collectionData.length; // Clear the index data for the index this._btree.clear(); this._size = 0; if (this._unique) { this._uniqueLookup = {}; } // Loop the collection data for (dataIndex = 0; dataIndex < dataCount; dataIndex++) { this.insert(collectionData[dataIndex]); } } this._state = { name: this._name, keys: this._keys, indexSize: this._size, built: new Date(), updated: new Date(), ok: true }; }; IndexBinaryTree.prototype.insert = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } if (this._btree.insert(dataItem)) { this._size++; return true; } return false; }; IndexBinaryTree.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } if (this._btree.remove(dataItem)) { this._size--; return true; } return false; }; IndexBinaryTree.prototype.violation = function (dataItem) { // Generate item hash var uniqueHash = this._itemHash(dataItem, this._keys); // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexBinaryTree.prototype.hashViolation = function (uniqueHash) { // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexBinaryTree.prototype.lookup = function (query, options, op) { return this._btree.lookup(query, options, op); }; IndexBinaryTree.prototype.match = function (query, options) { return this._btree.match(query, options); }; IndexBinaryTree.prototype._itemHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.value(item, pathData[k].path).join(':'); } return hash; }; IndexBinaryTree.prototype._itemKeyHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.keyValue(item, pathData[k].path); } return hash; }; IndexBinaryTree.prototype._itemHashArr = function (item, keys) { var path = new Path(), pathData, //hash = '', hashArr = [], valArr, i, k, j; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { valArr = path.value(item, pathData[k].path); for (i = 0; i < valArr.length; i++) { if (k === 0) { // Setup the initial hash array hashArr.push(valArr[i]); } else { // Loop the hash array and concat the value to it for (j = 0; j < hashArr.length; j++) { hashArr[j] = hashArr[j] + '_' + valArr[i]; } } } } return hashArr; }; // Register this index on the shared object Shared.index.btree = IndexBinaryTree; Shared.finishModule('IndexBinaryTree'); module.exports = IndexBinaryTree; },{"./BinaryTree":2,"./Path":26,"./Shared":29}],11:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'); /** * The index class used to instantiate hash map indexes that the database can * use to speed up queries on collections and views. * @constructor */ var IndexHashMap = function () { this.init.apply(this, arguments); }; IndexHashMap.prototype.init = function (keys, options, collection) { this._crossRef = {}; this._size = 0; this._id = this._itemKeyHash(keys, keys); this.data({}); this.unique(options && options.unique ? options.unique : false); if (keys !== undefined) { this.keys(keys); } if (collection !== undefined) { this.collection(collection); } this.name(options && options.name ? options.name : this._id); }; Shared.addModule('IndexHashMap', IndexHashMap); Shared.mixin(IndexHashMap.prototype, 'Mixin.ChainReactor'); IndexHashMap.prototype.id = function () { return this._id; }; IndexHashMap.prototype.state = function () { return this._state; }; IndexHashMap.prototype.size = function () { return this._size; }; Shared.synthesize(IndexHashMap.prototype, 'data'); Shared.synthesize(IndexHashMap.prototype, 'name'); Shared.synthesize(IndexHashMap.prototype, 'collection'); Shared.synthesize(IndexHashMap.prototype, 'type'); Shared.synthesize(IndexHashMap.prototype, 'unique'); IndexHashMap.prototype.keys = function (val) { if (val !== undefined) { this._keys = val; // Count the keys this._keyCount = (new Path()).parse(this._keys).length; return this; } return this._keys; }; IndexHashMap.prototype.rebuild = function () { // Do we have a collection? if (this._collection) { // Get sorted data var collection = this._collection.subset({}, { $decouple: false, $orderBy: this._keys }), collectionData = collection.find(), dataIndex, dataCount = collectionData.length; // Clear the index data for the index this._data = {}; this._size = 0; if (this._unique) { this._uniqueLookup = {}; } // Loop the collection data for (dataIndex = 0; dataIndex < dataCount; dataIndex++) { this.insert(collectionData[dataIndex]); } } this._state = { name: this._name, keys: this._keys, indexSize: this._size, built: new Date(), updated: new Date(), ok: true }; }; IndexHashMap.prototype.insert = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, itemHashArr, hashIndex; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } // Generate item hash itemHashArr = this._itemHashArr(dataItem, this._keys); // Get the path search results and store them for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) { this.pushToPathValue(itemHashArr[hashIndex], dataItem); } }; IndexHashMap.prototype.update = function (dataItem, options) { // TODO: Write updates to work // 1: Get uniqueHash for the dataItem primary key value (may need to generate a store for this) // 2: Remove the uniqueHash as it currently stands // 3: Generate a new uniqueHash for dataItem // 4: Insert the new uniqueHash }; IndexHashMap.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, itemHashArr, hashIndex; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } // Generate item hash itemHashArr = this._itemHashArr(dataItem, this._keys); // Get the path search results and store them for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) { this.pullFromPathValue(itemHashArr[hashIndex], dataItem); } }; IndexHashMap.prototype.violation = function (dataItem) { // Generate item hash var uniqueHash = this._itemHash(dataItem, this._keys); // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexHashMap.prototype.hashViolation = function (uniqueHash) { // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexHashMap.prototype.pushToPathValue = function (hash, obj) { var pathValArr = this._data[hash] = this._data[hash] || []; // Make sure we have not already indexed this object at this path/value if (pathValArr.indexOf(obj) === -1) { // Index the object pathValArr.push(obj); // Record the reference to this object in our index size this._size++; // Cross-reference this association for later lookup this.pushToCrossRef(obj, pathValArr); } }; IndexHashMap.prototype.pullFromPathValue = function (hash, obj) { var pathValArr = this._data[hash], indexOfObject; // Make sure we have already indexed this object at this path/value indexOfObject = pathValArr.indexOf(obj); if (indexOfObject > -1) { // Un-index the object pathValArr.splice(indexOfObject, 1); // Record the reference to this object in our index size this._size--; // Remove object cross-reference this.pullFromCrossRef(obj, pathValArr); } // Check if we should remove the path value array if (!pathValArr.length) { // Remove the array delete this._data[hash]; } }; IndexHashMap.prototype.pull = function (obj) { // Get all places the object has been used and remove them var id = obj[this._collection.primaryKey()], crossRefArr = this._crossRef[id], arrIndex, arrCount = crossRefArr.length, arrItem; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = crossRefArr[arrIndex]; // Remove item from this index lookup array this._pullFromArray(arrItem, obj); } // Record the reference to this object in our index size this._size--; // Now remove the cross-reference entry for this object delete this._crossRef[id]; }; IndexHashMap.prototype._pullFromArray = function (arr, obj) { var arrCount = arr.length; while (arrCount--) { if (arr[arrCount] === obj) { arr.splice(arrCount, 1); } } }; IndexHashMap.prototype.pushToCrossRef = function (obj, pathValArr) { var id = obj[this._collection.primaryKey()], crObj; this._crossRef[id] = this._crossRef[id] || []; // Check if the cross-reference to the pathVal array already exists crObj = this._crossRef[id]; if (crObj.indexOf(pathValArr) === -1) { // Add the cross-reference crObj.push(pathValArr); } }; IndexHashMap.prototype.pullFromCrossRef = function (obj, pathValArr) { var id = obj[this._collection.primaryKey()]; delete this._crossRef[id]; }; IndexHashMap.prototype.lookup = function (query) { return this._data[this._itemHash(query, this._keys)] || []; }; IndexHashMap.prototype.match = function (query, options) { // Check if the passed query has data in the keys our index // operates on and if so, is the query sort matching our order var pathSolver = new Path(); var indexKeyArr = pathSolver.parseArr(this._keys), queryArr = pathSolver.parseArr(query), matchedKeys = [], matchedKeyCount = 0, i; // Loop the query array and check the order of keys against the // index key array to see if this index can be used for (i = 0; i < indexKeyArr.length; i++) { if (queryArr[i] === indexKeyArr[i]) { matchedKeyCount++; matchedKeys.push(queryArr[i]); } else { // Query match failed - this is a hash map index so partial key match won't work return { matchedKeys: [], totalKeyCount: queryArr.length, score: 0 }; } } return { matchedKeys: matchedKeys, totalKeyCount: queryArr.length, score: matchedKeyCount }; //return pathSolver.countObjectPaths(this._keys, query); }; IndexHashMap.prototype._itemHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.value(item, pathData[k].path).join(':'); } return hash; }; IndexHashMap.prototype._itemKeyHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.keyValue(item, pathData[k].path); } return hash; }; IndexHashMap.prototype._itemHashArr = function (item, keys) { var path = new Path(), pathData, //hash = '', hashArr = [], valArr, i, k, j; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { valArr = path.value(item, pathData[k].path); for (i = 0; i < valArr.length; i++) { if (k === 0) { // Setup the initial hash array hashArr.push(valArr[i]); } else { // Loop the hash array and concat the value to it for (j = 0; j < hashArr.length; j++) { hashArr[j] = hashArr[j] + '_' + valArr[i]; } } } } return hashArr; }; // Register this index on the shared object Shared.index.hashed = IndexHashMap; Shared.finishModule('IndexHashMap'); module.exports = IndexHashMap; },{"./Path":26,"./Shared":29}],12:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * The key value store class used when storing basic in-memory KV data, * and can be queried for quick retrieval. Mostly used for collection * primary key indexes and lookups. * @param {String=} name Optional KV store name. * @constructor */ var KeyValueStore = function (name) { this.init.apply(this, arguments); }; KeyValueStore.prototype.init = function (name) { this._name = name; this._data = {}; this._primaryKey = '_id'; }; Shared.addModule('KeyValueStore', KeyValueStore); Shared.mixin(KeyValueStore.prototype, 'Mixin.ChainReactor'); /** * Get / set the name of the key/value store. * @param {String} val The name to set. * @returns {*} */ Shared.synthesize(KeyValueStore.prototype, 'name'); /** * Get / set the primary key. * @param {String} key The key to set. * @returns {*} */ KeyValueStore.prototype.primaryKey = function (key) { if (key !== undefined) { this._primaryKey = key; return this; } return this._primaryKey; }; /** * Removes all data from the store. * @returns {*} */ KeyValueStore.prototype.truncate = function () { this._data = {}; return this; }; /** * Sets data against a key in the store. * @param {String} key The key to set data for. * @param {*} value The value to assign to the key. * @returns {*} */ KeyValueStore.prototype.set = function (key, value) { this._data[key] = value ? value : true; return this; }; /** * Gets data stored for the passed key. * @param {String} key The key to get data for. * @returns {*} */ KeyValueStore.prototype.get = function (key) { return this._data[key]; }; /** * Get / set the primary key. * @param {*} val A lookup query. * @returns {*} */ KeyValueStore.prototype.lookup = function (val) { var pk = this._primaryKey, valType = typeof val, arrIndex, arrCount, lookupItem, result = []; // Check for early exit conditions if (valType === 'string' || valType === 'number') { lookupItem = this.get(val); if (lookupItem !== undefined) { return [lookupItem]; } else { return []; } } else if (valType === 'object') { if (val instanceof Array) { // An array of primary keys, find all matches arrCount = val.length; result = []; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { lookupItem = this.lookup(val[arrIndex]); if (lookupItem) { if (lookupItem instanceof Array) { result = result.concat(lookupItem); } else { result.push(lookupItem); } } } return result; } else if (val[pk]) { return this.lookup(val[pk]); } } // COMMENTED AS CODE WILL NEVER BE REACHED // Complex lookup /*lookupData = this._lookupKeys(val); keys = lookupData.keys; negate = lookupData.negate; if (!negate) { // Loop keys and return values for (arrIndex = 0; arrIndex < keys.length; arrIndex++) { result.push(this.get(keys[arrIndex])); } } else { // Loop data and return non-matching keys for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (keys.indexOf(arrIndex) === -1) { result.push(this.get(arrIndex)); } } } } return result;*/ }; // COMMENTED AS WE ARE NOT CURRENTLY PASSING COMPLEX QUERIES TO KEYVALUESTORE INDEXES /*KeyValueStore.prototype._lookupKeys = function (val) { var pk = this._primaryKey, valType = typeof val, arrIndex, arrCount, lookupItem, bool, result; if (valType === 'string' || valType === 'number') { return { keys: [val], negate: false }; } else if (valType === 'object') { if (val instanceof RegExp) { // Create new data result = []; for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (val.test(arrIndex)) { result.push(arrIndex); } } } return { keys: result, negate: false }; } else if (val instanceof Array) { // An array of primary keys, find all matches arrCount = val.length; result = []; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { result = result.concat(this._lookupKeys(val[arrIndex]).keys); } return { keys: result, negate: false }; } else if (val.$in && (val.$in instanceof Array)) { return { keys: this._lookupKeys(val.$in).keys, negate: false }; } else if (val.$nin && (val.$nin instanceof Array)) { return { keys: this._lookupKeys(val.$nin).keys, negate: true }; } else if (val.$ne) { return { keys: this._lookupKeys(val.$ne, true).keys, negate: true }; } else if (val.$or && (val.$or instanceof Array)) { // Create new data result = []; for (arrIndex = 0; arrIndex < val.$or.length; arrIndex++) { result = result.concat(this._lookupKeys(val.$or[arrIndex]).keys); } return { keys: result, negate: false }; } else if (val[pk]) { return this._lookupKeys(val[pk]); } } };*/ /** * Removes data for the given key from the store. * @param {String} key The key to un-set. * @returns {*} */ KeyValueStore.prototype.unSet = function (key) { delete this._data[key]; return this; }; /** * Sets data for the give key in the store only where the given key * does not already have a value in the store. * @param {String} key The key to set data for. * @param {*} value The value to assign to the key. * @returns {Boolean} True if data was set or false if data already * exists for the key. */ KeyValueStore.prototype.uniqueSet = function (key, value) { if (this._data[key] === undefined) { this._data[key] = value; return true; } return false; }; Shared.finishModule('KeyValueStore'); module.exports = KeyValueStore; },{"./Shared":29}],13:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Operation = _dereq_('./Operation'); /** * The metrics class used to store details about operations. * @constructor */ var Metrics = function () { this.init.apply(this, arguments); }; Metrics.prototype.init = function () { this._data = []; }; Shared.addModule('Metrics', Metrics); Shared.mixin(Metrics.prototype, 'Mixin.ChainReactor'); /** * Creates an operation within the metrics instance and if metrics * are currently enabled (by calling the start() method) the operation * is also stored in the metrics log. * @param {String} name The name of the operation. * @returns {Operation} */ Metrics.prototype.create = function (name) { var op = new Operation(name); if (this._enabled) { this._data.push(op); } return op; }; /** * Starts logging operations. * @returns {Metrics} */ Metrics.prototype.start = function () { this._enabled = true; return this; }; /** * Stops logging operations. * @returns {Metrics} */ Metrics.prototype.stop = function () { this._enabled = false; return this; }; /** * Clears all logged operations. * @returns {Metrics} */ Metrics.prototype.clear = function () { this._data = []; return this; }; /** * Returns an array of all logged operations. * @returns {Array} */ Metrics.prototype.list = function () { return this._data; }; Shared.finishModule('Metrics'); module.exports = Metrics; },{"./Operation":24,"./Shared":29}],14:[function(_dereq_,module,exports){ "use strict"; var CRUD = { preSetData: function () { }, postSetData: function () { } }; module.exports = CRUD; },{}],15:[function(_dereq_,module,exports){ "use strict"; /** * The chain reactor mixin, provides methods to the target object that allow chain * reaction events to propagate to the target and be handled, processed and passed * on down the chain. * @mixin */ var ChainReactor = { /** * Creates a chain link between the current reactor node and the passed * reactor node. Chain packets that are send by this reactor node will * then be propagated to the passed node for subsequent packets. * @param {*} obj The chain reactor node to link to. */ chain: function (obj) { if (this.debug && this.debug()) { if (obj._reactorIn && obj._reactorOut) { console.log(obj._reactorIn.logIdentifier() + ' Adding target "' + obj._reactorOut.instanceIdentifier() + '" to the chain reactor target list'); } else { console.log(this.logIdentifier() + ' Adding target "' + obj.instanceIdentifier() + '" to the chain reactor target list'); } } this._chain = this._chain || []; var index = this._chain.indexOf(obj); if (index === -1) { this._chain.push(obj); } }, /** * Removes a chain link between the current reactor node and the passed * reactor node. Chain packets sent from this reactor node will no longer * be received by the passed node. * @param {*} obj The chain reactor node to unlink from. */ unChain: function (obj) { if (this.debug && this.debug()) { if (obj._reactorIn && obj._reactorOut) { console.log(obj._reactorIn.logIdentifier() + ' Removing target "' + obj._reactorOut.instanceIdentifier() + '" from the chain reactor target list'); } else { console.log(this.logIdentifier() + ' Removing target "' + obj.instanceIdentifier() + '" from the chain reactor target list'); } } if (this._chain) { var index = this._chain.indexOf(obj); if (index > -1) { this._chain.splice(index, 1); } } }, /** * Determines if this chain reactor node has any listeners downstream. * @returns {Boolean} True if there are nodes downstream of this node. */ chainWillSend: function () { return Boolean(this._chain); }, /** * Sends a chain reactor packet downstream from this node to any of its * chained targets that were linked to this node via a call to chain(). * @param {String} type The type of chain reactor packet to send. This * can be any string but the receiving reactor nodes will not react to * it unless they recognise the string. Built-in strings include: "insert", * "update", "remove", "setData" and "debug". * @param {Object} data A data object that usually contains a key called * "dataSet" which is an array of items to work on, and can contain other * custom keys that help describe the operation. * @param {Object=} options An options object. Can also contain custom * key/value pairs that your custom chain reactor code can operate on. */ chainSend: function (type, data, options) { if (this._chain) { var arr = this._chain, arrItem, count = arr.length, index, dataCopy = this.decouple(data, count); for (index = 0; index < count; index++) { arrItem = arr[index]; if (!arrItem._state || (arrItem._state && !arrItem.isDropped())) { if (this.debug && this.debug()) { if (arrItem._reactorIn && arrItem._reactorOut) { console.log(arrItem._reactorIn.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem._reactorOut.instanceIdentifier() + '"'); } else { console.log(this.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem.instanceIdentifier() + '"'); } } if (arrItem.chainReceive) { arrItem.chainReceive(this, type, dataCopy[index], options); } } else { console.log('Reactor Data:', type, data, options); console.log('Reactor Node:', arrItem); throw('Chain reactor attempting to send data to target reactor node that is in a dropped state!'); } } } }, /** * Handles receiving a chain reactor message that was sent via the chainSend() * method. Creates the chain packet object and then allows it to be processed. * @param {Object} sender The node that is sending the packet. * @param {String} type The type of packet. * @param {Object} data The data related to the packet. * @param {Object=} options An options object. */ chainReceive: function (sender, type, data, options) { var chainPacket = { sender: sender, type: type, data: data, options: options }, cancelPropagate = false; if (this.debug && this.debug()) { console.log(this.logIdentifier() + ' Received data from parent reactor node'); } // Check if we have a chain handler method if (this._chainHandler) { // Fire our internal handler cancelPropagate = this._chainHandler(chainPacket); } // Check if we were told to cancel further propagation if (!cancelPropagate) { // Propagate the message down the chain this.chainSend(chainPacket.type, chainPacket.data, chainPacket.options); } } }; module.exports = ChainReactor; },{}],16:[function(_dereq_,module,exports){ "use strict"; var idCounter = 0, Overload = _dereq_('./Overload'), Serialiser = _dereq_('./Serialiser'), Common, serialiser = new Serialiser(); /** * Provides commonly used methods to most classes in ForerunnerDB. * @mixin */ Common = { // Expose the serialiser object so it can be extended with new data handlers. serialiser: serialiser, /** * Generates a JSON serialisation-compatible object instance. After the * instance has been passed through this method, it will be able to survive * a JSON.stringify() and JSON.parse() cycle and still end up as an * instance at the end. Further information about this process can be found * in the ForerunnerDB wiki at: https://github.com/Irrelon/ForerunnerDB/wiki/Serialiser-&-Performance-Benchmarks * @param {*} val The object instance such as "new Date()" or "new RegExp()". */ make: function (val) { // This is a conversion request, hand over to serialiser return serialiser.convert(val); }, /** * Gets / sets data in the item store. The store can be used to set and * retrieve data against a key. Useful for adding arbitrary key/value data * to a collection / view etc and retrieving it later. * @param {String|*} key The key under which to store the passed value or * retrieve the existing stored value. * @param {*=} val Optional value. If passed will overwrite the existing value * stored against the specified key if one currently exists. * @returns {*} */ store: function (key, val) { if (key !== undefined) { if (val !== undefined) { // Store the data this._store = this._store || {}; this._store[key] = val; return this; } if (this._store) { return this._store[key]; } } return undefined; }, /** * Removes a previously stored key/value pair from the item store, set previously * by using the store() method. * @param {String|*} key The key of the key/value pair to remove; * @returns {Common} Returns this for chaining. */ unStore: function (key) { if (key !== undefined) { delete this._store[key]; } return this; }, /** * Returns a non-referenced version of the passed object / array. * @param {Object} data The object or array to return as a non-referenced version. * @param {Number=} copies Optional number of copies to produce. If specified, the return * value will be an array of decoupled objects, each distinct from the other. * @returns {*} */ decouple: function (data, copies) { if (data !== undefined && data !== "") { if (!copies) { return this.jParse(this.jStringify(data)); } else { var i, json = this.jStringify(data), copyArr = []; for (i = 0; i < copies; i++) { copyArr.push(this.jParse(json)); } return copyArr; } } return undefined; }, /** * Parses and returns data from stringified version. * @param {String} data The stringified version of data to parse. * @returns {Object} The parsed JSON object from the data. */ jParse: function (data) { return JSON.parse(data, serialiser.reviver()); }, /** * Converts a JSON object into a stringified version. * @param {Object} data The data to stringify. * @returns {String} The stringified data. */ jStringify: function (data) { //return serialiser.stringify(data); return JSON.stringify(data); }, /** * Generates a new 16-character hexadecimal unique ID or * generates a new 16-character hexadecimal ID based on * the passed string. Will always generate the same ID * for the same string. * @param {String=} str A string to generate the ID from. * @return {String} */ objectId: function (str) { var id, pow = Math.pow(10, 17); if (!str) { idCounter++; id = (idCounter + ( Math.random() * pow + Math.random() * pow + Math.random() * pow + Math.random() * pow )).toString(16); } else { var val = 0, count = str.length, i; for (i = 0; i < count; i++) { val += str.charCodeAt(i) * pow; } id = val.toString(16); } return id; }, /** * Generates a unique hash for the passed object. * @param {Object} obj The object to generate a hash for. * @returns {String} */ hash: function (obj) { return JSON.stringify(obj); }, /** * Gets / sets debug flag that can enable debug message output to the * console if required. * @param {Boolean} val The value to set debug flag to. * @return {Boolean} True if enabled, false otherwise. */ /** * Sets debug flag for a particular type that can enable debug message * output to the console if required. * @param {String} type The name of the debug type to set flag for. * @param {Boolean} val The value to set debug flag to. * @return {Boolean} True if enabled, false otherwise. */ debug: new Overload([ function () { return this._debug && this._debug.all; }, function (val) { if (val !== undefined) { if (typeof val === 'boolean') { this._debug = this._debug || {}; this._debug.all = val; this.chainSend('debug', this._debug); return this; } else { return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[val]) || (this._debug && this._debug.all); } } return this._debug && this._debug.all; }, function (type, val) { if (type !== undefined) { if (val !== undefined) { this._debug = this._debug || {}; this._debug[type] = val; this.chainSend('debug', this._debug); return this; } return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[type]); } return this._debug && this._debug.all; } ]), /** * Returns a string describing the class this instance is derived from. * @returns {string} */ classIdentifier: function () { return 'ForerunnerDB.' + this.className; }, /** * Returns a string describing the instance by it's class name and instance * object name. * @returns {String} The instance identifier. */ instanceIdentifier: function () { return '[' + this.className + ']' + this.name(); }, /** * Returns a string used to denote a console log against this instance, * consisting of the class identifier and instance identifier. * @returns {string} The log identifier. */ logIdentifier: function () { return 'ForerunnerDB ' + this.instanceIdentifier(); }, /** * Converts a query object with MongoDB dot notation syntax * to Forerunner's object notation syntax. * @param {Object} obj The object to convert. */ convertToFdb: function (obj) { var varName, splitArr, objCopy, i; for (i in obj) { if (obj.hasOwnProperty(i)) { objCopy = obj; if (i.indexOf('.') > -1) { // Replace .$ with a placeholder before splitting by . char i = i.replace('.$', '[|$|]'); splitArr = i.split('.'); while ((varName = splitArr.shift())) { // Replace placeholder back to original .$ varName = varName.replace('[|$|]', '.$'); if (splitArr.length) { objCopy[varName] = {}; } else { objCopy[varName] = obj[i]; } objCopy = objCopy[varName]; } delete obj[i]; } } } }, /** * Checks if the state is dropped. * @returns {boolean} True when dropped, false otherwise. */ isDropped: function () { return this._state === 'dropped'; }, /** * Registers a timed callback that will overwrite itself if * the same id is used within the timeout period. Useful * for de-bouncing fast-calls. * @param {String} id An ID for the call (use the same one * to debounce the same calls). * @param {Function} callback The callback method to call on * timeout. * @param {Number} timeout The timeout in milliseconds before * the callback is called. */ debounce: function (id, callback, timeout) { var self = this, newData; self._debounce = self._debounce || {}; if (self._debounce[id]) { // Clear timeout for this item clearTimeout(self._debounce[id].timeout); } newData = { callback: callback, timeout: setTimeout(function () { // Delete existing reference delete self._debounce[id]; // Call the callback callback(); }, timeout) }; // Save current data self._debounce[id] = newData; } }; module.exports = Common; },{"./Overload":25,"./Serialiser":28}],17:[function(_dereq_,module,exports){ "use strict"; /** * Provides some database constants. * @mixin */ var Constants = { TYPE_INSERT: 0, TYPE_UPDATE: 1, TYPE_REMOVE: 2, PHASE_BEFORE: 0, PHASE_AFTER: 1 }; module.exports = Constants; },{}],18:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); /** * Provides event emitter functionality including the methods: on, off, once, emit, deferEmit. * @mixin */ var Events = { on: new Overload({ /** * Attach an event listener to the passed event. * @param {String} event The name of the event to listen for. * @param {Function} listener The method to call when the event is fired. */ 'string, function': function (event, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || {}; this._listeners[event]['*'] = this._listeners[event]['*'] || []; this._listeners[event]['*'].push(listener); return this; }, /** * Attach an event listener to the passed event only if the passed * id matches the document id for the event being fired. * @param {String} event The name of the event to listen for. * @param {*} id The document id to match against. * @param {Function} listener The method to call when the event is fired. */ 'string, *, function': function (event, id, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || {}; this._listeners[event][id] = this._listeners[event][id] || []; this._listeners[event][id].push(listener); return this; } }), once: new Overload({ 'string, function': function (eventName, callback) { var self = this, internalCallback = function () { self.off(eventName, internalCallback); callback.apply(self, arguments); }; return this.on(eventName, internalCallback); }, 'string, *, function': function (eventName, id, callback) { var self = this, internalCallback = function () { self.off(eventName, id, internalCallback); callback.apply(self, arguments); }; return this.on(eventName, id, internalCallback); } }), off: new Overload({ 'string': function (event) { if (this._listeners && this._listeners[event] && event in this._listeners) { delete this._listeners[event]; } return this; }, 'string, function': function (event, listener) { var arr, index; if (typeof(listener) === 'string') { if (this._listeners && this._listeners[event] && this._listeners[event][listener]) { delete this._listeners[event][listener]; } } else { if (this._listeners && event in this._listeners) { arr = this._listeners[event]['*']; index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } } return this; }, 'string, *, function': function (event, id, listener) { if (this._listeners && event in this._listeners && id in this.listeners[event]) { var arr = this._listeners[event][id], index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } }, 'string, *': function (event, id) { if (this._listeners && event in this._listeners && id in this._listeners[event]) { // Kill all listeners for this event id delete this._listeners[event][id]; } } }), emit: function (event, data) { this._listeners = this._listeners || {}; if (event in this._listeners) { var arrIndex, arrCount, tmpFunc, arr, listenerIdArr, listenerIdCount, listenerIdIndex; // Handle global emit if (this._listeners[event]['*']) { arr = this._listeners[event]['*']; arrCount = arr.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { // Check we have a function to execute tmpFunc = arr[arrIndex]; if (typeof tmpFunc === 'function') { tmpFunc.apply(this, Array.prototype.slice.call(arguments, 1)); } } } // Handle individual emit if (data instanceof Array) { // Check if the array is an array of objects in the collection if (data[0] && data[0][this._primaryKey]) { // Loop the array and check for listeners against the primary key listenerIdArr = this._listeners[event]; arrCount = data.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { if (listenerIdArr[data[arrIndex][this._primaryKey]]) { // Emit for this id listenerIdCount = listenerIdArr[data[arrIndex][this._primaryKey]].length; for (listenerIdIndex = 0; listenerIdIndex < listenerIdCount; listenerIdIndex++) { tmpFunc = listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex]; if (typeof tmpFunc === 'function') { listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex].apply(this, Array.prototype.slice.call(arguments, 1)); } } } } } } } return this; }, /** * Queues an event to be fired. This has automatic de-bouncing so that any * events of the same type that occur within 100 milliseconds of a previous * one will all be wrapped into a single emit rather than emitting tons of * events for lots of chained inserts etc. Only the data from the last * de-bounced event will be emitted. * @param {String} eventName The name of the event to emit. * @param {*=} data Optional data to emit with the event. */ deferEmit: function (eventName, data) { var self = this, args; if (!this._noEmitDefer && (!this._db || (this._db && !this._db._noEmitDefer))) { args = arguments; // Check for an existing timeout this._deferTimeout = this._deferTimeout || {}; if (this._deferTimeout[eventName]) { clearTimeout(this._deferTimeout[eventName]); } // Set a timeout this._deferTimeout[eventName] = setTimeout(function () { if (self.debug()) { console.log(self.logIdentifier() + ' Emitting ' + args[0]); } self.emit.apply(self, args); }, 1); } else { this.emit.apply(this, arguments); } return this; } }; module.exports = Events; },{"./Overload":25}],19:[function(_dereq_,module,exports){ "use strict"; /** * Provides object matching algorithm methods. * @mixin */ var Matching = { /** * Internal method that checks a document against a test object. * @param {*} source The source object or value to test against. * @param {*} test The test object or value to test with. * @param {Object} queryOptions The options the query was passed with. * @param {String=} opToApply The special operation to apply to the test such * as 'and' or an 'or' operator. * @param {Object=} options An object containing options to apply to the * operation such as limiting the fields returned etc. * @returns {Boolean} True if the test was positive, false on negative. * @private */ _match: function (source, test, queryOptions, opToApply, options) { // TODO: This method is quite long, break into smaller pieces var operation, applyOp = opToApply, recurseVal, tmpIndex, sourceType = typeof source, testType = typeof test, matchedAll = true, opResult, substringCache, i; if (sourceType === 'object' && source === null) { sourceType = 'null'; } if (testType === 'object' && test === null) { testType = 'null'; } options = options || {}; queryOptions = queryOptions || {}; // Check if options currently holds a root query object if (!options.$rootQuery) { // Root query not assigned, hold the root query options.$rootQuery = test; } // Check if options currently holds a root source object if (!options.$rootSource) { // Root query not assigned, hold the root query options.$rootSource = source; } // Assign current query data options.$currentQuery = test; options.$rootData = options.$rootData || {}; // Check if the comparison data are both strings or numbers if ((sourceType === 'string' || sourceType === 'number' || sourceType === 'null') && (testType === 'string' || testType === 'number' || testType === 'null')) { // The source and test data are flat types that do not require recursive searches, // so just compare them and return the result if (sourceType === 'number' || sourceType === 'null' || testType === 'null') { // Number or null comparison if (source !== test) { matchedAll = false; } } else { // String comparison // TODO: We can probably use a queryOptions.$locale as a second parameter here // TODO: to satisfy https://github.com/Irrelon/ForerunnerDB/issues/35 if (source.localeCompare(test)) { matchedAll = false; } } } else if ((sourceType === 'string' || sourceType === 'number') && (testType === 'object' && test instanceof RegExp)) { if (!test.test(source)) { matchedAll = false; } } else { for (i in test) { if (test.hasOwnProperty(i)) { // Assign previous query data options.$previousQuery = options.$parent; // Assign parent query data options.$parent = { query: test[i], key: i, parent: options.$previousQuery }; // Reset operation flag operation = false; // Grab first two chars of the key name to check for $ substringCache = i.substr(0, 2); // Check if the property is a comment (ignorable) if (substringCache === '//') { // Skip this property continue; } // Check if the property starts with a dollar (function) if (substringCache.indexOf('$') === 0) { // Ask the _matchOp method to handle the operation opResult = this._matchOp(i, source, test[i], queryOptions, options); // Check the result of the matchOp operation // If the result is -1 then no operation took place, otherwise the result // will be a boolean denoting a match (true) or no match (false) if (opResult > -1) { if (opResult) { if (opToApply === 'or') { return true; } } else { // Set the matchedAll flag to the result of the operation // because the operation did not return true matchedAll = opResult; } // Record that an operation was handled operation = true; } } // Check for regex if (!operation && test[i] instanceof RegExp) { operation = true; if (sourceType === 'object' && source[i] !== undefined && test[i].test(source[i])) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } if (!operation) { // Check if our query is an object if (typeof(test[i]) === 'object') { // Because test[i] is an object, source must also be an object // Check if our source data we are checking the test query against // is an object or an array if (source[i] !== undefined) { if (source[i] instanceof Array && !(test[i] instanceof Array)) { // The source data is an array, so check each item until a // match is found recurseVal = false; for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) { recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else if (!(source[i] instanceof Array) && test[i] instanceof Array) { // The test key data is an array and the source key data is not so check // each item in the test key data to see if the source item matches one // of them. This is effectively an $in search. recurseVal = false; for (tmpIndex = 0; tmpIndex < test[i].length; tmpIndex++) { recurseVal = this._match(source[i], test[i][tmpIndex], queryOptions, applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else if (typeof(source) === 'object') { // Recurse down the object tree recurseVal = this._match(source[i], test[i], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } } else { // First check if the test match is an $exists if (test[i] && test[i].$exists !== undefined) { // Push the item through another match recurse recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { matchedAll = false; } } } else { // Check if the prop matches our test value if (source && source[i] === test[i]) { if (opToApply === 'or') { return true; } } else if (source && source[i] && source[i] instanceof Array && test[i] && typeof(test[i]) !== "object") { // We are looking for a value inside an array // The source data is an array, so check each item until a // match is found recurseVal = false; for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) { recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { matchedAll = false; } } } if (opToApply === 'and' && !matchedAll) { return false; } } } } return matchedAll; }, /** * Internal method, performs a matching process against a query operator such as $gt or $nin. * @param {String} key The property name in the test that matches the operator to perform * matching against. * @param {*} source The source data to match the query against. * @param {*} test The query to match the source against. * @param {Object} queryOptions The options the query was passed with. * @param {Object=} options An options object. * @returns {*} * @private */ _matchOp: function (key, source, test, queryOptions, options) { // Check for commands switch (key) { case '$gt': // Greater than return source > test; case '$gte': // Greater than or equal return source >= test; case '$lt': // Less than return source < test; case '$lte': // Less than or equal return source <= test; case '$exists': // Property exists return (source === undefined) !== test; case '$eq': // Equals return source == test; // jshint ignore:line case '$eeq': // Equals equals return source === test; case '$ne': // Not equals return source != test; // jshint ignore:line case '$nee': // Not equals equals return source !== test; case '$or': // Match true on ANY check to pass for (var orIndex = 0; orIndex < test.length; orIndex++) { if (this._match(source, test[orIndex], queryOptions, 'and', options)) { return true; } } return false; case '$and': // Match true on ALL checks to pass for (var andIndex = 0; andIndex < test.length; andIndex++) { if (!this._match(source, test[andIndex], queryOptions, 'and', options)) { return false; } } return true; case '$in': // In // Check that the in test is an array if (test instanceof Array) { var inArr = test, inArrCount = inArr.length, inArrIndex; for (inArrIndex = 0; inArrIndex < inArrCount; inArrIndex++) { if (this._match(source, inArr[inArrIndex], queryOptions, 'and', options)) { return true; } } return false; } else if (typeof test === 'object') { return this._match(source, test, queryOptions, 'and', options); } else { console.log(this.logIdentifier() + ' Cannot use an $in operator on a non-array key: ' + key, options.$rootQuery); return false; } break; case '$nin': // Not in // Check that the not-in test is an array if (test instanceof Array) { var notInArr = test, notInArrCount = notInArr.length, notInArrIndex; for (notInArrIndex = 0; notInArrIndex < notInArrCount; notInArrIndex++) { if (this._match(source, notInArr[notInArrIndex], queryOptions, 'and', options)) { return false; } } return true; } else if (typeof test === 'object') { return this._match(source, test, queryOptions, 'and', options); } else { console.log(this.logIdentifier() + ' Cannot use a $nin operator on a non-array key: ' + key, options.$rootQuery); return false; } break; case '$distinct': // Ensure options holds a distinct lookup options.$rootData['//distinctLookup'] = options.$rootData['//distinctLookup'] || {}; for (var distinctProp in test) { if (test.hasOwnProperty(distinctProp)) { options.$rootData['//distinctLookup'][distinctProp] = options.$rootData['//distinctLookup'][distinctProp] || {}; // Check if the options distinct lookup has this field's value if (options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]]) { // Value is already in use return false; } else { // Set the value in the lookup options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]] = true; // Allow the item in the results return true; } } } break; case '$count': var countKey, countArr, countVal; // Iterate the count object's keys for (countKey in test) { if (test.hasOwnProperty(countKey)) { // Check the property exists and is an array. If the property being counted is not // an array (or doesn't exist) then use a value of zero in any further count logic countArr = source[countKey]; if (typeof countArr === 'object' && countArr instanceof Array) { countVal = countArr.length; } else { countVal = 0; } // Now recurse down the query chain further to satisfy the query for this key (countKey) if (!this._match(countVal, test[countKey], queryOptions, 'and', options)) { return false; } } } // Allow the item in the results return true; case '$find': case '$findOne': case '$findSub': var fromType = 'collection', findQuery, findOptions, subQuery, subOptions, subPath, result, operation = {}; // Check all parts of the $find operation exist if (!test.$from) { throw(key + ' missing $from property!'); } if (test.$fromType) { fromType = test.$fromType; // Check the fromType exists as a method if (!this.db()[fromType] || typeof this.db()[fromType] !== 'function') { throw(key + ' cannot operate against $fromType "' + fromType + '" because the database does not recognise this type of object!'); } } // Perform the find operation findQuery = test.$query || {}; findOptions = test.$options || {}; if (key === '$findSub') { if (!test.$path) { throw(key + ' missing $path property!'); } subPath = test.$path; subQuery = test.$subQuery || {}; subOptions = test.$subOptions || {}; if (options.$parent && options.$parent.parent && options.$parent.parent.key) { result = this.db()[fromType](test.$from).findSub(findQuery, subPath, subQuery, subOptions); } else { // This is a root $find* query // Test the source against the main findQuery if (this._match(source, findQuery, {}, 'and', options)) { result = this._findSub([source], subPath, subQuery, subOptions); } return result && result.length > 0; } } else { result = this.db()[fromType](test.$from)[key.substr(1)](findQuery, findOptions); } operation[options.$parent.parent.key] = result; return this._match(source, operation, queryOptions, 'and', options); } return -1; }, /** * * @param {Array | Object} docArr An array of objects to run the join * operation against or a single object. * @param {Array} joinClause The join clause object array (the array in * the $join key of a normal join options object). * @param {Object} joinSource An object containing join source reference * data or a blank object if you are doing a bespoke join operation. * @param {Object} options An options object or blank object if no options. * @returns {Array} * @private */ applyJoin: function (docArr, joinClause, joinSource, options) { var self = this, joinSourceIndex, joinSourceKey, joinMatch, joinSourceType, joinSourceIdentifier, resultKeyName, joinSourceInstance, resultIndex, joinSearchQuery, joinMulti, joinRequire, joinPrefix, joinMatchIndex, joinMatchData, joinSearchOptions, joinFindResults, joinFindResult, joinItem, resultRemove = [], l; if (!(docArr instanceof Array)) { // Turn the document into an array docArr = [docArr]; } for (joinSourceIndex = 0; joinSourceIndex < joinClause.length; joinSourceIndex++) { for (joinSourceKey in joinClause[joinSourceIndex]) { if (joinClause[joinSourceIndex].hasOwnProperty(joinSourceKey)) { // Get the match data for the join joinMatch = joinClause[joinSourceIndex][joinSourceKey]; // Check if the join is to a collection (default) or a specified source type // e.g 'view' or 'collection' joinSourceType = joinMatch.$sourceType || 'collection'; joinSourceIdentifier = '$' + joinSourceType + '.' + joinSourceKey; // Set the key to store the join result in to the collection name by default // can be overridden by the '$as' clause in the join object resultKeyName = joinSourceKey; // Get the join collection instance from the DB if (joinSource[joinSourceIdentifier]) { // We have a joinSource for this identifier already (given to us by // an index when we analysed the query earlier on) and we can use // that source instead. joinSourceInstance = joinSource[joinSourceIdentifier]; } else { // We do not already have a joinSource so grab the instance from the db if (this._db[joinSourceType] && typeof this._db[joinSourceType] === 'function') { joinSourceInstance = this._db[joinSourceType](joinSourceKey); } } // Loop our result data array for (resultIndex = 0; resultIndex < docArr.length; resultIndex++) { // Loop the join conditions and build a search object from them joinSearchQuery = {}; joinMulti = false; joinRequire = false; joinPrefix = ''; for (joinMatchIndex in joinMatch) { if (joinMatch.hasOwnProperty(joinMatchIndex)) { joinMatchData = joinMatch[joinMatchIndex]; // Check the join condition name for a special command operator if (joinMatchIndex.substr(0, 1) === '$') { // Special command switch (joinMatchIndex) { case '$where': if (joinMatchData.$query || joinMatchData.$options) { if (joinMatchData.$query) { // Commented old code here, new one does dynamic reverse lookups //joinSearchQuery = joinMatchData.query; joinSearchQuery = self.resolveDynamicQuery(joinMatchData.$query, docArr[resultIndex]); } if (joinMatchData.$options) { joinSearchOptions = joinMatchData.$options; } } else { throw('$join $where clause requires "$query" and / or "$options" keys to work!'); } break; case '$as': // Rename the collection when stored in the result document resultKeyName = joinMatchData; break; case '$multi': // Return an array of documents instead of a single matching document joinMulti = joinMatchData; break; case '$require': // Remove the result item if no matching join data is found joinRequire = joinMatchData; break; case '$prefix': // Add a prefix to properties mixed in joinPrefix = joinMatchData; break; default: break; } } else { // Get the data to match against and store in the search object // Resolve complex referenced query joinSearchQuery[joinMatchIndex] = self.resolveDynamicQuery(joinMatchData, docArr[resultIndex]); } } } // Do a find on the target collection against the match data joinFindResults = joinSourceInstance.find(joinSearchQuery, joinSearchOptions); // Check if we require a joined row to allow the result item if (!joinRequire || (joinRequire && joinFindResults[0])) { // Join is not required or condition is met if (resultKeyName === '$root') { // The property name to store the join results in is $root // which means we need to mixin the results but this only // works if joinMulti is disabled if (joinMulti !== false) { // Throw an exception here as this join is not physically possible! throw(this.logIdentifier() + ' Cannot combine [$as: "$root"] with [$multi: true] in $join clause!'); } // Mixin the result joinFindResult = joinFindResults[0]; joinItem = docArr[resultIndex]; for (l in joinFindResult) { if (joinFindResult.hasOwnProperty(l) && joinItem[joinPrefix + l] === undefined) { // Properties are only mixed in if they do not already exist // in the target item (are undefined). Using a prefix denoted via // $prefix is a good way to prevent property name conflicts joinItem[joinPrefix + l] = joinFindResult[l]; } } } else { docArr[resultIndex][resultKeyName] = joinMulti === false ? joinFindResults[0] : joinFindResults; } } else { // Join required but condition not met, add item to removal queue resultRemove.push(resultIndex); } } } } } return resultRemove; }, /** * Takes a query object with dynamic references and converts the references * into actual values from the references source. * @param {Object} query The query object with dynamic references. * @param {Object} item The document to apply the references to. * @returns {*} * @private */ resolveDynamicQuery: function (query, item) { var self = this, newQuery, propType, propVal, pathResult, i; // Check for early exit conditions if (typeof query === 'string') { // Check if the property name starts with a back-reference if (query.substr(0, 3) === '$$.') { // Fill the query with a back-referenced value pathResult = this.sharedPathSolver.value(item, query.substr(3, query.length - 3)); } else { pathResult = this.sharedPathSolver.value(item, query); } if (pathResult.length > 1) { return {$in: pathResult}; } else { return pathResult[0]; } } newQuery = {}; for (i in query) { if (query.hasOwnProperty(i)) { propType = typeof query[i]; propVal = query[i]; switch (propType) { case 'string': // Check if the property name starts with a back-reference if (propVal.substr(0, 3) === '$$.') { // Fill the query with a back-referenced value newQuery[i] = this.sharedPathSolver.value(item, propVal.substr(3, propVal.length - 3))[0]; } else { newQuery[i] = propVal; } break; case 'object': newQuery[i] = self.resolveDynamicQuery(propVal, item); break; default: newQuery[i] = propVal; break; } } } return newQuery; }, spliceArrayByIndexList: function (arr, list) { var i; for (i = list.length - 1; i >= 0; i--) { arr.splice(list[i], 1); } } }; module.exports = Matching; },{}],20:[function(_dereq_,module,exports){ "use strict"; /** * Provides sorting methods. * @mixin */ var Sorting = { /** * Sorts the passed value a against the passed value b ascending. * @param {*} a The first value to compare. * @param {*} b The second value to compare. * @returns {*} 1 if a is sorted after b, -1 if a is sorted before b. */ sortAsc: function (a, b) { if (typeof(a) === 'string' && typeof(b) === 'string') { return a.localeCompare(b); } else { if (a > b) { return 1; } else if (a < b) { return -1; } } return 0; }, /** * Sorts the passed value a against the passed value b descending. * @param {*} a The first value to compare. * @param {*} b The second value to compare. * @returns {*} 1 if a is sorted after b, -1 if a is sorted before b. */ sortDesc: function (a, b) { if (typeof(a) === 'string' && typeof(b) === 'string') { return b.localeCompare(a); } else { if (a > b) { return -1; } else if (a < b) { return 1; } } return 0; } }; module.exports = Sorting; },{}],21:[function(_dereq_,module,exports){ "use strict"; var Tags, tagMap = {}; /** * Provides class instance tagging and tag operation methods. * @mixin */ Tags = { /** * Tags a class instance for later lookup. * @param {String} name The tag to add. * @returns {boolean} */ tagAdd: function (name) { var i, self = this, mapArr = tagMap[name] = tagMap[name] || []; for (i = 0; i < mapArr.length; i++) { if (mapArr[i] === self) { return true; } } mapArr.push(self); // Hook the drop event for this so we can react if (self.on) { self.on('drop', function () { // We've been dropped so remove ourselves from the tag map self.tagRemove(name); }); } return true; }, /** * Removes a tag from a class instance. * @param {String} name The tag to remove. * @returns {boolean} */ tagRemove: function (name) { var i, mapArr = tagMap[name]; if (mapArr) { for (i = 0; i < mapArr.length; i++) { if (mapArr[i] === this) { mapArr.splice(i, 1); return true; } } } return false; }, /** * Gets an array of all instances tagged with the passed tag name. * @param {String} name The tag to lookup. * @returns {Array} The array of instances that have the passed tag. */ tagLookup: function (name) { return tagMap[name] || []; }, /** * Drops all instances that are tagged with the passed tag name. * @param {String} name The tag to lookup. * @param {Function} callback Callback once dropping has completed * for all instances that match the passed tag name. * @returns {boolean} */ tagDrop: function (name, callback) { var arr = this.tagLookup(name), dropCb, dropCount, i; dropCb = function () { dropCount--; if (callback && dropCount === 0) { callback(false); } }; if (arr.length) { dropCount = arr.length; // Loop the array and drop all items for (i = arr.length - 1; i >= 0; i--) { arr[i].drop(dropCb); } } return true; } }; module.exports = Tags; },{}],22:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); /** * Provides trigger functionality methods. * @mixin */ var Triggers = { /** * When called in a before phase the newDoc object can be directly altered * to modify the data in it before the operation is carried out. * @callback addTriggerCallback * @param {Object} operation The details about the operation. * @param {Object} oldDoc The document before the operation. * @param {Object} newDoc The document after the operation. */ /** * Add a trigger by id. * @param {String} id The id of the trigger. This must be unique to the type and * phase of the trigger. Only one trigger may be added with this id per type and * phase. * @param {Constants} type The type of operation to apply the trigger to. See * Mixin.Constants for constants to use. * @param {Constants} phase The phase of an operation to fire the trigger on. See * Mixin.Constants for constants to use. * @param {addTriggerCallback} method The method to call when the trigger is fired. * @returns {boolean} True if the trigger was added successfully, false if not. */ addTrigger: function (id, type, phase, method) { var self = this, triggerIndex; // Check if the trigger already exists triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex === -1) { self.triggerStack = {}; // The trigger does not exist, create it self._trigger = self._trigger || {}; self._trigger[type] = self._trigger[type] || {}; self._trigger[type][phase] = self._trigger[type][phase] || []; self._trigger[type][phase].push({ id: id, method: method, enabled: true }); return true; } return false; }, /** * * @param {String} id The id of the trigger to remove. * @param {Number} type The type of operation to remove the trigger from. See * Mixin.Constants for constants to use. * @param {Number} phase The phase of the operation to remove the trigger from. * See Mixin.Constants for constants to use. * @returns {boolean} True if removed successfully, false if not. */ removeTrigger: function (id, type, phase) { var self = this, triggerIndex; // Check if the trigger already exists triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // The trigger exists, remove it self._trigger[type][phase].splice(triggerIndex, 1); } return false; }, /** * Tells the current instance to fire or ignore all triggers whether they * are enabled or not. * @param {Boolean} val Set to true to ignore triggers or false to not * ignore them. * @returns {*} */ ignoreTriggers: function (val) { if (val !== undefined) { this._ignoreTriggers = val; return this; } return this._ignoreTriggers; }, /** * Generates triggers that fire in the after phase for all CRUD ops * that automatically transform data back and forth and keep both * import and export collections in sync with each other. * @param {String} id The unique id for this link IO. * @param {Object} ioData The settings for the link IO. */ addLinkIO: function (id, ioData) { var self = this, matchAll, exportData, importData, exportTriggerMethod, importTriggerMethod, exportTo, importFrom, allTypes, i; // Store the linkIO self._linkIO = self._linkIO || {}; self._linkIO[id] = ioData; exportData = ioData['export']; importData = ioData['import']; if (exportData) { exportTo = self.db().collection(exportData.to); } if (importData) { importFrom = self.db().collection(importData.from); } allTypes = [ self.TYPE_INSERT, self.TYPE_UPDATE, self.TYPE_REMOVE ]; matchAll = function (data, callback) { // Match all callback(false, true); }; if (exportData) { // Check for export match method if (!exportData.match) { // No match method found, use the match all method exportData.match = matchAll; } // Check for export types if (!exportData.types) { exportData.types = allTypes; } exportTriggerMethod = function (operation, oldDoc, newDoc) { // Check if we should execute against this data exportData.match(newDoc, function (err, doExport) { if (!err && doExport) { // Get data to upsert (if any) exportData.data(newDoc, operation.type, function (err, data, callback) { if (!err && data) { // Disable all currently enabled triggers so that we // don't go into a trigger loop exportTo.ignoreTriggers(true); if (operation.type !== 'remove') { // Do upsert exportTo.upsert(data, callback); } else { // Do remove exportTo.remove(data, callback); } // Re-enable the previous triggers exportTo.ignoreTriggers(false); } }); } }); }; } if (importData) { // Check for import match method if (!importData.match) { // No match method found, use the match all method importData.match = matchAll; } // Check for import types if (!importData.types) { importData.types = allTypes; } importTriggerMethod = function (operation, oldDoc, newDoc) { // Check if we should execute against this data importData.match(newDoc, function (err, doExport) { if (!err && doExport) { // Get data to upsert (if any) importData.data(newDoc, operation.type, function (err, data, callback) { if (!err && data) { // Disable all currently enabled triggers so that we // don't go into a trigger loop exportTo.ignoreTriggers(true); if (operation.type !== 'remove') { // Do upsert self.upsert(data, callback); } else { // Do remove self.remove(data, callback); } // Re-enable the previous triggers exportTo.ignoreTriggers(false); } }); } }); }; } if (exportData) { for (i = 0; i < exportData.types.length; i++) { self.addTrigger(id + 'export' + exportData.types[i], exportData.types[i], self.PHASE_AFTER, exportTriggerMethod); } } if (importData) { for (i = 0; i < importData.types.length; i++) { importFrom.addTrigger(id + 'import' + importData.types[i], importData.types[i], self.PHASE_AFTER, importTriggerMethod); } } }, /** * Removes a previously added link IO via it's ID. * @param {String} id The id of the link IO to remove. * @returns {boolean} True if successful, false if the link IO * was not found. */ removeLinkIO: function (id) { var self = this, linkIO = self._linkIO[id], exportData, importData, importFrom, i; if (linkIO) { exportData = linkIO['export']; importData = linkIO['import']; if (exportData) { for (i = 0; i < exportData.types.length; i++) { self.removeTrigger(id + 'export' + exportData.types[i], exportData.types[i], self.db.PHASE_AFTER); } } if (importData) { importFrom = self.db().collection(importData.from); for (i = 0; i < importData.types.length; i++) { importFrom.removeTrigger(id + 'import' + importData.types[i], importData.types[i], self.db.PHASE_AFTER); } } delete self._linkIO[id]; return true; } return false; }, enableTrigger: new Overload({ 'string': function (id) { // Alter all triggers of this type var self = this, types = self._trigger, phases, triggers, result = false, i, k, j; if (types) { for (j in types) { if (types.hasOwnProperty(j)) { phases = types[j]; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set enabled flag for (k = 0; k < triggers.length; k++) { if (triggers[k].id === id) { triggers[k].enabled = true; result = true; } } } } } } } } return result; }, 'number': function (type) { // Alter all triggers of this type var self = this, phases = self._trigger[type], triggers, result = false, i, k; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set to enabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = true; result = true; } } } } return result; }, 'number, number': function (type, phase) { // Alter all triggers of this type and phase var self = this, phases = self._trigger[type], triggers, result = false, k; if (phases) { triggers = phases[phase]; if (triggers) { // Loop triggers and set to enabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = true; result = true; } } } return result; }, 'string, number, number': function (id, type, phase) { // Check if the trigger already exists var self = this, triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // Update the trigger self._trigger[type][phase][triggerIndex].enabled = true; return true; } return false; } }), disableTrigger: new Overload({ 'string': function (id) { // Alter all triggers of this type var self = this, types = self._trigger, phases, triggers, result = false, i, k, j; if (types) { for (j in types) { if (types.hasOwnProperty(j)) { phases = types[j]; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set enabled flag for (k = 0; k < triggers.length; k++) { if (triggers[k].id === id) { triggers[k].enabled = false; result = true; } } } } } } } } return result; }, 'number': function (type) { // Alter all triggers of this type var self = this, phases = self._trigger[type], triggers, result = false, i, k; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set to disabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = false; result = true; } } } } return result; }, 'number, number': function (type, phase) { // Alter all triggers of this type and phase var self = this, phases = self._trigger[type], triggers, result = false, k; if (phases) { triggers = phases[phase]; if (triggers) { // Loop triggers and set to disabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = false; result = true; } } } return result; }, 'string, number, number': function (id, type, phase) { // Check if the trigger already exists var self = this, triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // Update the trigger self._trigger[type][phase][triggerIndex].enabled = false; return true; } return false; } }), /** * Checks if a trigger will fire based on the type and phase provided. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @returns {Boolean} True if the trigger will fire, false otherwise. */ willTrigger: function (type, phase) { if (!this._ignoreTriggers && this._trigger && this._trigger[type] && this._trigger[type][phase] && this._trigger[type][phase].length) { // Check if a trigger in this array is enabled var arr = this._trigger[type][phase], i; for (i = 0; i < arr.length; i++) { if (arr[i].enabled) { return true; } } } return false; }, /** * Processes trigger actions based on the operation, type and phase. * @param {Object} operation Operation data to pass to the trigger. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @param {Object} oldDoc The document snapshot before operations are * carried out against the data. * @param {Object} newDoc The document snapshot after operations are * carried out against the data. * @returns {boolean} */ processTrigger: function (operation, type, phase, oldDoc, newDoc) { var self = this, triggerArr, triggerIndex, triggerCount, triggerItem, response, typeName, phaseName; if (!self._ignoreTriggers && self._trigger && self._trigger[type] && self._trigger[type][phase]) { triggerArr = self._trigger[type][phase]; triggerCount = triggerArr.length; for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) { triggerItem = triggerArr[triggerIndex]; // Check if the trigger is enabled if (triggerItem.enabled) { if (self.debug()) { switch (type) { case this.TYPE_INSERT: typeName = 'insert'; break; case this.TYPE_UPDATE: typeName = 'update'; break; case this.TYPE_REMOVE: typeName = 'remove'; break; default: typeName = ''; break; } switch (phase) { case this.PHASE_BEFORE: phaseName = 'before'; break; case this.PHASE_AFTER: phaseName = 'after'; break; default: phaseName = ''; break; } console.log('Triggers: Processing trigger "' + triggerItem.id + '" for ' + typeName + ' in phase "' + phaseName + '"'); } // Check if the trigger is already in the stack, if it is, // don't fire it again (this is so we avoid infinite loops // where a trigger triggers another trigger which calls this // one and so on) if (self.triggerStack && self.triggerStack[type] && self.triggerStack[type][phase] && self.triggerStack[type][phase][triggerItem.id]) { // The trigger is already in the stack, do not fire the trigger again if (self.debug()) { console.log('Triggers: Will not run trigger "' + triggerItem.id + '" for ' + typeName + ' in phase "' + phaseName + '" as it is already in the stack!'); } continue; } // Add the trigger to the stack so we don't go down an endless // trigger loop self.triggerStack = self.triggerStack || {}; self.triggerStack[type] = {}; self.triggerStack[type][phase] = {}; self.triggerStack[type][phase][triggerItem.id] = true; // Run the trigger's method and store the response response = triggerItem.method.call(self, operation, oldDoc, newDoc); // Remove the trigger from the stack self.triggerStack = self.triggerStack || {}; self.triggerStack[type] = {}; self.triggerStack[type][phase] = {}; self.triggerStack[type][phase][triggerItem.id] = false; // Check the response for a non-expected result (anything other than // [undefined, true or false] is considered a throwable error) if (response === false) { // The trigger wants us to cancel operations return false; } if (response !== undefined && response !== true && response !== false) { // Trigger responded with error, throw the error throw('ForerunnerDB.Mixin.Triggers: Trigger error: ' + response); } } } // Triggers all ran without issue, return a success (true) return true; } }, /** * Returns the index of a trigger by id based on type and phase. * @param {String} id The id of the trigger to find the index of. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @returns {number} * @private */ _triggerIndexOf: function (id, type, phase) { var self = this, triggerArr, triggerCount, triggerIndex; if (self._trigger && self._trigger[type] && self._trigger[type][phase]) { triggerArr = self._trigger[type][phase]; triggerCount = triggerArr.length; for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) { if (triggerArr[triggerIndex].id === id) { return triggerIndex; } } } return -1; } }; module.exports = Triggers; },{"./Overload":25}],23:[function(_dereq_,module,exports){ "use strict"; /** * Provides methods to handle object update operations. * @mixin */ var Updating = { /** * Updates a property on an object. * @param {Object} doc The object whose property is to be updated. * @param {String} prop The property to update. * @param {*} val The new value of the property. * @private */ _updateProperty: function (doc, prop, val) { doc[prop] = val; if (this.debug()) { console.log(this.logIdentifier() + ' Setting non-data-bound document property "' + prop + '" to val "' + val + '"'); } }, /** * Increments a value for a property on a document by the passed number. * @param {Object} doc The document to modify. * @param {String} prop The property to modify. * @param {Number} val The amount to increment by. * @private */ _updateIncrement: function (doc, prop, val) { doc[prop] += val; }, /** * Changes the index of an item in the passed array. * @param {Array} arr The array to modify. * @param {Number} indexFrom The index to move the item from. * @param {Number} indexTo The index to move the item to. * @private */ _updateSpliceMove: function (arr, indexFrom, indexTo) { arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]); if (this.debug()) { console.log(this.logIdentifier() + ' Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"'); } }, /** * Inserts an item into the passed array at the specified index. * @param {Array} arr The array to insert into. * @param {Number} index The index to insert at. * @param {Object} doc The document to insert. * @private */ _updateSplicePush: function (arr, index, doc) { if (arr.length > index) { arr.splice(index, 0, doc); } else { arr.push(doc); } }, /** * Inserts an item at the end of an array. * @param {Array} arr The array to insert the item into. * @param {Object} doc The document to insert. * @private */ _updatePush: function (arr, doc) { arr.push(doc); }, /** * Removes an item from the passed array. * @param {Array} arr The array to modify. * @param {Number} index The index of the item in the array to remove. * @private */ _updatePull: function (arr, index) { arr.splice(index, 1); }, /** * Multiplies a value for a property on a document by the passed number. * @param {Object} doc The document to modify. * @param {String} prop The property to modify. * @param {Number} val The amount to multiply by. * @private */ _updateMultiply: function (doc, prop, val) { doc[prop] *= val; }, /** * Renames a property on a document to the passed property. * @param {Object} doc The document to modify. * @param {String} prop The property to rename. * @param {Number} val The new property name. * @private */ _updateRename: function (doc, prop, val) { doc[val] = doc[prop]; delete doc[prop]; }, /** * Sets a property on a document to the passed value. * @param {Object} doc The document to modify. * @param {String} prop The property to set. * @param {*} val The new property value. * @private */ _updateOverwrite: function (doc, prop, val) { doc[prop] = val; }, /** * Deletes a property on a document. * @param {Object} doc The document to modify. * @param {String} prop The property to delete. * @private */ _updateUnset: function (doc, prop) { delete doc[prop]; }, /** * Removes all properties from an object without destroying * the object instance, thereby maintaining data-bound linking. * @param {Object} doc The parent object to modify. * @param {String} prop The name of the child object to clear. * @private */ _updateClear: function (doc, prop) { var obj = doc[prop], i; if (obj && typeof obj === 'object') { for (i in obj) { if (obj.hasOwnProperty(i)) { this._updateUnset(obj, i); } } } }, /** * Pops an item or items from the array stack. * @param {Object} doc The document to modify. * @param {Number} val If set to a positive integer, will pop the number specified * from the stack, if set to a negative integer will shift the number specified * from the stack. * @return {Boolean} * @private */ _updatePop: function (doc, val) { var updated = false, i; if (doc.length > 0) { if (val > 0) { for (i = 0; i < val; i++) { doc.pop(); } updated = true; } else if (val < 0) { for (i = 0; i > val; i--) { doc.shift(); } updated = true; } } return updated; } }; module.exports = Updating; },{}],24:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'); /** * The operation class, used to store details about an operation being * performed by the database. * @param {String} name The name of the operation. * @constructor */ var Operation = function (name) { this.pathSolver = new Path(); this.counter = 0; this.init.apply(this, arguments); }; Operation.prototype.init = function (name) { this._data = { operation: name, // The name of the operation executed such as "find", "update" etc index: { potential: [], // Indexes that could have potentially been used used: false // The index that was picked to use }, steps: [], // The steps taken to generate the query results, time: { startMs: 0, stopMs: 0, totalMs: 0, process: {} }, flag: {}, // An object with flags that denote certain execution paths log: [] // Any extra data that might be useful such as warnings or helpful hints }; }; Shared.addModule('Operation', Operation); Shared.mixin(Operation.prototype, 'Mixin.ChainReactor'); /** * Starts the operation timer. */ Operation.prototype.start = function () { this._data.time.startMs = new Date().getTime(); }; /** * Adds an item to the operation log. * @param {String} event The item to log. * @returns {*} */ Operation.prototype.log = function (event) { if (event) { var lastLogTime = this._log.length > 0 ? this._data.log[this._data.log.length - 1].time : 0, logObj = { event: event, time: new Date().getTime(), delta: 0 }; this._data.log.push(logObj); if (lastLogTime) { logObj.delta = logObj.time - lastLogTime; } return this; } return this._data.log; }; /** * Called when starting and ending a timed operation, used to time * internal calls within an operation's execution. * @param {String} section An operation name. * @returns {*} */ Operation.prototype.time = function (section) { if (section !== undefined) { var process = this._data.time.process, processObj = process[section] = process[section] || {}; if (!processObj.startMs) { // Timer started processObj.startMs = new Date().getTime(); processObj.stepObj = { name: section }; this._data.steps.push(processObj.stepObj); } else { processObj.stopMs = new Date().getTime(); processObj.totalMs = processObj.stopMs - processObj.startMs; processObj.stepObj.totalMs = processObj.totalMs; delete processObj.stepObj; } return this; } return this._data.time; }; /** * Used to set key/value flags during operation execution. * @param {String} key * @param {String} val * @returns {*} */ Operation.prototype.flag = function (key, val) { if (key !== undefined && val !== undefined) { this._data.flag[key] = val; } else if (key !== undefined) { return this._data.flag[key]; } else { return this._data.flag; } }; Operation.prototype.data = function (path, val, noTime) { if (val !== undefined) { // Assign value to object path this.pathSolver.set(this._data, path, val); return this; } return this.pathSolver.get(this._data, path); }; Operation.prototype.pushData = function (path, val, noTime) { // Assign value to object path this.pathSolver.push(this._data, path, val); }; /** * Stops the operation timer. */ Operation.prototype.stop = function () { this._data.time.stopMs = new Date().getTime(); this._data.time.totalMs = this._data.time.stopMs - this._data.time.startMs; }; Shared.finishModule('Operation'); module.exports = Operation; },{"./Path":26,"./Shared":29}],25:[function(_dereq_,module,exports){ "use strict"; /** * Allows a method to accept overloaded calls with different parameters controlling * which passed overload function is called. * @param {String=} name A name to provide this overload to help identify * it if any errors occur during the resolving phase of the overload. This * is purely for debug purposes and serves no functional purpose. * @param {Object} def The overload definition. * @returns {Function} * @constructor */ var Overload = function (name, def) { if (!def) { def = name; name = undefined; } if (def) { var self = this, index, count, tmpDef, defNewKey, sigIndex, signatures; if (!(def instanceof Array)) { tmpDef = {}; // Def is an object, make sure all prop names are devoid of spaces for (index in def) { if (def.hasOwnProperty(index)) { defNewKey = index.replace(/ /g, ''); // Check if the definition array has a * string in it if (defNewKey.indexOf('*') === -1) { // No * found tmpDef[defNewKey] = def[index]; } else { // A * was found, generate the different signatures that this // definition could represent signatures = this.generateSignaturePermutations(defNewKey); for (sigIndex = 0; sigIndex < signatures.length; sigIndex++) { if (!tmpDef[signatures[sigIndex]]) { tmpDef[signatures[sigIndex]] = def[index]; } } } } } def = tmpDef; } return function () { var arr = [], lookup, type, overloadName; // Check if we are being passed a key/function object or an array of functions if (def instanceof Array) { // We were passed an array of functions count = def.length; for (index = 0; index < count; index++) { if (def[index].length === arguments.length) { return self.callExtend(this, '$main', def, def[index], arguments); } } } else { // Generate lookup key from arguments // Copy arguments to an array for (index = 0; index < arguments.length; index++) { type = typeof arguments[index]; // Handle detecting arrays if (type === 'object' && arguments[index] instanceof Array) { type = 'array'; } // Handle been presented with a single undefined argument if (arguments.length === 1 && type === 'undefined') { break; } // Add the type to the argument types array arr.push(type); } lookup = arr.join(','); // Check for an exact lookup match if (def[lookup]) { return self.callExtend(this, '$main', def, def[lookup], arguments); } else { for (index = arr.length; index >= 0; index--) { // Get the closest match lookup = arr.slice(0, index).join(','); if (def[lookup + ',...']) { // Matched against arguments + "any other" return self.callExtend(this, '$main', def, def[lookup + ',...'], arguments); } } } } overloadName = name !== undefined ? name : typeof this.name === 'function' ? this.name() : 'Unknown'; console.log('Overload Definition:', def); throw('ForerunnerDB.Overload "' + overloadName + '": Overloaded method does not have a matching signature "' + lookup + '" for the passed arguments: ' + this.jStringify(arr)); }; } return function () {}; }; /** * Generates an array of all the different definition signatures that can be * created from the passed string with a catch-all wildcard *. E.g. it will * convert the signature: string,*,string to all potentials: * string,string,string * string,number,string * string,object,string, * string,function,string, * string,undefined,string * * @param {String} str Signature string with a wildcard in it. * @returns {Array} An array of signature strings that are generated. */ Overload.prototype.generateSignaturePermutations = function (str) { var signatures = [], newSignature, types = ['array', 'string', 'object', 'number', 'function', 'undefined'], index; if (str.indexOf('*') > -1) { // There is at least one "any" type, break out into multiple keys // We could do this at query time with regular expressions but // would be significantly slower for (index = 0; index < types.length; index++) { newSignature = str.replace('*', types[index]); signatures = signatures.concat(this.generateSignaturePermutations(newSignature)); } } else { signatures.push(str); } return signatures; }; Overload.prototype.callExtend = function (context, prop, propContext, func, args) { var tmp, ret; if (context && propContext[prop]) { tmp = context[prop]; context[prop] = propContext[prop]; ret = func.apply(context, args); context[prop] = tmp; return ret; } else { return func.apply(context, args); } }; module.exports = Overload; },{}],26:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * Path object used to resolve object paths and retrieve data from * objects by using paths. * @param {String=} path The path to assign. * @constructor */ var Path = function (path) { this.init.apply(this, arguments); }; Path.prototype.init = function (path) { if (path) { this.path(path); } }; Shared.addModule('Path', Path); Shared.mixin(Path.prototype, 'Mixin.Common'); Shared.mixin(Path.prototype, 'Mixin.ChainReactor'); /** * Gets / sets the given path for the Path instance. * @param {String=} path The path to assign. */ Path.prototype.path = function (path) { if (path !== undefined) { this._path = this.clean(path); this._pathParts = this._path.split('.'); return this; } return this._path; }; /** * Tests if the passed object has the paths that are specified and that * a value exists in those paths. * @param {Object} testKeys The object describing the paths to test for. * @param {Object} testObj The object to test paths against. * @returns {Boolean} True if the object paths exist. */ Path.prototype.hasObjectPaths = function (testKeys, testObj) { var result = true, i; for (i in testKeys) { if (testKeys.hasOwnProperty(i)) { if (testObj[i] === undefined) { return false; } if (typeof testKeys[i] === 'object') { // Recurse object result = this.hasObjectPaths(testKeys[i], testObj[i]); // Should we exit early? if (!result) { return false; } } } } return result; }; /** * Counts the total number of key endpoints in the passed object. * @param {Object} testObj The object to count key endpoints for. * @returns {Number} The number of endpoints. */ Path.prototype.countKeys = function (testObj) { var totalKeys = 0, i; for (i in testObj) { if (testObj.hasOwnProperty(i)) { if (testObj[i] !== undefined) { if (typeof testObj[i] !== 'object') { totalKeys++; } else { totalKeys += this.countKeys(testObj[i]); } } } } return totalKeys; }; /** * Tests if the passed object has the paths that are specified and that * a value exists in those paths and if so returns the number matched. * @param {Object} testKeys The object describing the paths to test for. * @param {Object} testObj The object to test paths against. * @returns {Object} Stats on the matched keys */ Path.prototype.countObjectPaths = function (testKeys, testObj) { var matchData, matchedKeys = {}, matchedKeyCount = 0, totalKeyCount = 0, i; for (i in testObj) { if (testObj.hasOwnProperty(i)) { if (typeof testObj[i] === 'object') { // The test / query object key is an object, recurse matchData = this.countObjectPaths(testKeys[i], testObj[i]); matchedKeys[i] = matchData.matchedKeys; totalKeyCount += matchData.totalKeyCount; matchedKeyCount += matchData.matchedKeyCount; } else { // The test / query object has a property that is not an object so add it as a key totalKeyCount++; // Check if the test keys also have this key and it is also not an object if (testKeys && testKeys[i] && typeof testKeys[i] !== 'object') { matchedKeys[i] = true; matchedKeyCount++; } else { matchedKeys[i] = false; } } } } return { matchedKeys: matchedKeys, matchedKeyCount: matchedKeyCount, totalKeyCount: totalKeyCount }; }; /** * Takes a non-recursive object and converts the object hierarchy into * a path string. * @param {Object} obj The object to parse. * @param {Boolean=} withValue If true will include a 'value' key in the returned * object that represents the value the object path points to. * @returns {Object} */ Path.prototype.parse = function (obj, withValue) { var paths = [], path = '', resultData, i, k; for (i in obj) { if (obj.hasOwnProperty(i)) { // Set the path to the key path = i; if (typeof(obj[i]) === 'object') { if (withValue) { resultData = this.parse(obj[i], withValue); for (k = 0; k < resultData.length; k++) { paths.push({ path: path + '.' + resultData[k].path, value: resultData[k].value }); } } else { resultData = this.parse(obj[i]); for (k = 0; k < resultData.length; k++) { paths.push({ path: path + '.' + resultData[k].path }); } } } else { if (withValue) { paths.push({ path: path, value: obj[i] }); } else { paths.push({ path: path }); } } } } return paths; }; /** * Takes a non-recursive object and converts the object hierarchy into * an array of path strings that allow you to target all possible paths * in an object. * * The options object accepts an "ignore" field with a regular expression * as the value. If any key matches the expression it is not included in * the results. * * The options object accepts a boolean "verbose" field. If set to true * the results will include all paths leading up to endpoints as well as * they endpoints themselves. * * @returns {Array} */ Path.prototype.parseArr = function (obj, options) { options = options || {}; return this._parseArr(obj, '', [], options); }; Path.prototype._parseArr = function (obj, path, paths, options) { var i, newPath = ''; path = path || ''; paths = paths || []; for (i in obj) { if (obj.hasOwnProperty(i)) { if (!options.ignore || (options.ignore && !options.ignore.test(i))) { if (path) { newPath = path + '.' + i; } else { newPath = i; } if (typeof(obj[i]) === 'object') { if (options.verbose) { paths.push(newPath); } this._parseArr(obj[i], newPath, paths, options); } else { paths.push(newPath); } } } } return paths; }; /** * Sets a value on an object for the specified path. * @param {Object} obj The object to update. * @param {String} path The path to update. * @param {*} val The value to set the object path to. * @returns {*} */ Path.prototype.set = function (obj, path, val) { if (obj !== undefined && path !== undefined) { var pathParts, part; path = this.clean(path); pathParts = path.split('.'); part = pathParts.shift(); if (pathParts.length) { // Generate the path part in the object if it does not already exist obj[part] = obj[part] || {}; // Recurse this.set(obj[part], pathParts.join('.'), val); } else { // Set the value obj[part] = val; } } return obj; }; /** * Gets a single value from the passed object and given path. * @param {Object} obj The object to inspect. * @param {String} path The path to retrieve data from. * @returns {*} */ Path.prototype.get = function (obj, path) { return this.value(obj, path)[0]; }; /** * Gets the value(s) that the object contains for the currently assigned path string. * @param {Object} obj The object to evaluate the path against. * @param {String=} path A path to use instead of the existing one passed in path(). * @param {Object=} options An optional options object. * @returns {Array} An array of values for the given path. */ Path.prototype.value = function (obj, path, options) { var pathParts, arr, arrCount, objPart, objPartParent, valuesArr, returnArr, i, k; // Detect early exit if (path && path.indexOf('.') === -1) { return [obj[path]]; } if (obj !== undefined && typeof obj === 'object') { if (!options || options && !options.skipArrCheck) { // Check if we were passed an array of objects and if so, // iterate over the array and return the value from each // array item if (obj instanceof Array) { returnArr = []; for (i = 0; i < obj.length; i++) { returnArr.push(this.get(obj[i], path)); } return returnArr; } } valuesArr = []; if (path !== undefined) { path = this.clean(path); pathParts = path.split('.'); } arr = pathParts || this._pathParts; arrCount = arr.length; objPart = obj; for (i = 0; i < arrCount; i++) { objPart = objPart[arr[i]]; if (objPartParent instanceof Array) { // Search inside the array for the next key for (k = 0; k < objPartParent.length; k++) { valuesArr = valuesArr.concat(this.value(objPartParent, k + '.' + arr[i], {skipArrCheck: true})); } return valuesArr; } else { if (!objPart || typeof(objPart) !== 'object') { break; } } objPartParent = objPart; } return [objPart]; } else { return []; } }; /** * Push a value to an array on an object for the specified path. * @param {Object} obj The object to update. * @param {String} path The path to the array to push to. * @param {*} val The value to push to the array at the object path. * @returns {*} */ Path.prototype.push = function (obj, path, val) { if (obj !== undefined && path !== undefined) { var pathParts, part; path = this.clean(path); pathParts = path.split('.'); part = pathParts.shift(); if (pathParts.length) { // Generate the path part in the object if it does not already exist obj[part] = obj[part] || {}; // Recurse this.set(obj[part], pathParts.join('.'), val); } else { // Set the value obj[part] = obj[part] || []; if (obj[part] instanceof Array) { obj[part].push(val); } else { throw('ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!'); } } } return obj; }; /** * Gets the value(s) that the object contains for the currently assigned path string * with their associated keys. * @param {Object} obj The object to evaluate the path against. * @param {String=} path A path to use instead of the existing one passed in path(). * @returns {Array} An array of values for the given path with the associated key. */ Path.prototype.keyValue = function (obj, path) { var pathParts, arr, arrCount, objPart, objPartParent, objPartHash, i; if (path !== undefined) { path = this.clean(path); pathParts = path.split('.'); } arr = pathParts || this._pathParts; arrCount = arr.length; objPart = obj; for (i = 0; i < arrCount; i++) { objPart = objPart[arr[i]]; if (!objPart || typeof(objPart) !== 'object') { objPartHash = arr[i] + ':' + objPart; break; } objPartParent = objPart; } return objPartHash; }; /** * Sets a value on an object for the specified path. * @param {Object} obj The object to update. * @param {String} path The path to update. * @param {*} val The value to set the object path to. * @returns {*} */ Path.prototype.set = function (obj, path, val) { if (obj !== undefined && path !== undefined) { var pathParts, part; path = this.clean(path); pathParts = path.split('.'); part = pathParts.shift(); if (pathParts.length) { // Generate the path part in the object if it does not already exist obj[part] = obj[part] || {}; // Recurse this.set(obj[part], pathParts.join('.'), val); } else { // Set the value obj[part] = val; } } return obj; }; /** * Removes leading period (.) from string and returns it. * @param {String} str The string to clean. * @returns {*} */ Path.prototype.clean = function (str) { if (str.substr(0, 1) === '.') { str = str.substr(1, str.length -1); } return str; }; Shared.finishModule('Path'); module.exports = Path; },{"./Shared":29}],27:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * Provides chain reactor node linking so that a chain reaction can propagate * down a node tree. Effectively creates a chain link between the reactorIn and * reactorOut objects where a chain reaction from the reactorIn is passed through * the reactorProcess before being passed to the reactorOut object. Reactor * packets are only passed through to the reactorOut if the reactor IO method * chainSend is used. * @param {*} reactorIn An object that has the Mixin.ChainReactor methods mixed * in to it. Chain reactions that occur inside this object will be passed through * to the reactorOut object. * @param {*} reactorOut An object that has the Mixin.ChainReactor methods mixed * in to it. Chain reactions that occur in the reactorIn object will be passed * through to this object. * @param {Function} reactorProcess The processing method to use when chain * reactions occur. * @constructor */ var ReactorIO = function (reactorIn, reactorOut, reactorProcess) { if (reactorIn && reactorOut && reactorProcess) { this._reactorIn = reactorIn; this._reactorOut = reactorOut; this._chainHandler = reactorProcess; if (!reactorIn.chain) { throw('ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!'); } // Register the reactorIO with the input reactorIn.chain(this); // Register the output with the reactorIO this.chain(reactorOut); } else { throw('ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!'); } }; Shared.addModule('ReactorIO', ReactorIO); /** * Drop a reactor IO object, breaking the reactor link between the in and out * reactor nodes. * @returns {boolean} */ ReactorIO.prototype.drop = function () { if (!this.isDropped()) { this._state = 'dropped'; // Remove links if (this._reactorIn) { this._reactorIn.unChain(this); } if (this._reactorOut) { this.unChain(this._reactorOut); } delete this._reactorIn; delete this._reactorOut; delete this._chainHandler; this.emit('drop', this); delete this._listeners; } return true; }; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(ReactorIO.prototype, 'state'); Shared.mixin(ReactorIO.prototype, 'Mixin.Common'); Shared.mixin(ReactorIO.prototype, 'Mixin.ChainReactor'); Shared.mixin(ReactorIO.prototype, 'Mixin.Events'); Shared.finishModule('ReactorIO'); module.exports = ReactorIO; },{"./Shared":29}],28:[function(_dereq_,module,exports){ "use strict"; /** * Provides functionality to encode and decode JavaScript objects to strings * and back again. This differs from JSON.stringify and JSON.parse in that * special objects such as dates can be encoded to strings and back again * so that the reconstituted version of the string still contains a JavaScript * date object. * @constructor */ var Serialiser = function () { this.init.apply(this, arguments); }; Serialiser.prototype.init = function () { var self = this; this._encoder = []; this._decoder = []; // Handler for Date() objects this.registerHandler('$date', function (objInstance) { if (objInstance instanceof Date) { // Augment this date object with a new toJSON method objInstance.toJSON = function () { return "$date:" + this.toISOString(); }; // Tell the converter we have matched this object return true; } // Tell converter to keep looking, we didn't match this object return false; }, function (data) { if (typeof data === 'string' && data.indexOf('$date:') === 0) { return self.convert(new Date(data.substr(6))); } return undefined; }); // Handler for RegExp() objects this.registerHandler('$regexp', function (objInstance) { if (objInstance instanceof RegExp) { objInstance.toJSON = function () { return "$regexp:" + this.source.length + ":" + this.source + ":" + (this.global ? 'g' : '') + (this.ignoreCase ? 'i' : ''); /*return { source: this.source, params: '' + (this.global ? 'g' : '') + (this.ignoreCase ? 'i' : '') };*/ }; // Tell the converter we have matched this object return true; } // Tell converter to keep looking, we didn't match this object return false; }, function (data) { if (typeof data === 'string' && data.indexOf('$regexp:') === 0) { var dataStr = data.substr(8),//± lengthEnd = dataStr.indexOf(':'), sourceLength = Number(dataStr.substr(0, lengthEnd)), source = dataStr.substr(lengthEnd + 1, sourceLength), params = dataStr.substr(lengthEnd + sourceLength + 2); return self.convert(new RegExp(source, params)); } return undefined; }); }; Serialiser.prototype.registerHandler = function (handles, encoder, decoder) { if (handles !== undefined) { // Register encoder this._encoder.push(encoder); // Register decoder this._decoder.push(decoder); } }; Serialiser.prototype.convert = function (data) { // Run through converters and check for match var arr = this._encoder, i; for (i = 0; i < arr.length; i++) { if (arr[i](data)) { // The converter we called matched the object and converted it // so let's return it now. return data; } } // No converter matched the object, return the unaltered one return data; }; Serialiser.prototype.reviver = function () { var arr = this._decoder; return function (key, value) { // Check if we have a decoder method for this key var decodedData, i; for (i = 0; i < arr.length; i++) { decodedData = arr[i](value); if (decodedData !== undefined) { // The decoder we called matched the object and decoded it // so let's return it now. return decodedData; } } // No decoder, return basic value return value; }; }; module.exports = Serialiser; },{}],29:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); /** * A shared object that can be used to store arbitrary data between class * instances, and access helper methods. * @mixin */ var Shared = { version: '1.3.790', modules: {}, plugins: {}, index: {}, _synth: {}, /** * Adds a module to ForerunnerDB. * @memberof Shared * @param {String} name The name of the module. * @param {Function} module The module class. */ addModule: function (name, module) { // Store the module in the module registry this.modules[name] = module; // Tell the universe we are loading this module this.emit('moduleLoad', [name, module]); }, /** * Called by the module once all processing has been completed. Used to determine * if the module is ready for use by other modules. * @memberof Shared * @param {String} name The name of the module. */ finishModule: function (name) { if (this.modules[name]) { // Set the finished loading flag to true this.modules[name]._fdbFinished = true; // Assign the module name to itself so it knows what it // is called if (this.modules[name].prototype) { this.modules[name].prototype.className = name; } else { this.modules[name].className = name; } this.emit('moduleFinished', [name, this.modules[name]]); } else { throw('ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): ' + name); } }, /** * Will call your callback method when the specified module has loaded. If the module * is already loaded the callback is called immediately. * @memberof Shared * @param {String} name The name of the module. * @param {Function} callback The callback method to call when the module is loaded. */ moduleFinished: function (name, callback) { if (this.modules[name] && this.modules[name]._fdbFinished) { if (callback) { callback(name, this.modules[name]); } } else { this.on('moduleFinished', callback); } }, /** * Determines if a module has been added to ForerunnerDB or not. * @memberof Shared * @param {String} name The name of the module. * @returns {Boolean} True if the module exists or false if not. */ moduleExists: function (name) { return Boolean(this.modules[name]); }, mixin: new Overload({ /** * Adds the properties and methods defined in the mixin to the passed * object. * @memberof Shared * @name mixin * @param {Object} obj The target object to add mixin key/values to. * @param {String} mixinName The name of the mixin to add to the object. */ 'object, string': function (obj, mixinName) { var mixinObj; if (typeof mixinName === 'string') { mixinObj = this.mixins[mixinName]; if (!mixinObj) { throw('ForerunnerDB.Shared: Cannot find mixin named: ' + mixinName); } } return this.$main.call(this, obj, mixinObj); }, /** * Adds the properties and methods defined in the mixin to the passed * object. * @memberof Shared * @name mixin * @param {Object} obj The target object to add mixin key/values to. * @param {Object} mixinObj The object containing the keys to mix into * the target object. */ 'object, *': function (obj, mixinObj) { return this.$main.call(this, obj, mixinObj); }, '$main': function (obj, mixinObj) { if (mixinObj && typeof mixinObj === 'object') { for (var i in mixinObj) { if (mixinObj.hasOwnProperty(i)) { obj[i] = mixinObj[i]; } } } return obj; } }), /** * Generates a generic getter/setter method for the passed method name. * @memberof Shared * @param {Object} obj The object to add the getter/setter to. * @param {String} name The name of the getter/setter to generate. * @param {Function=} extend A method to call before executing the getter/setter. * The existing getter/setter can be accessed from the extend method via the * $super e.g. this.$super(); */ synthesize: function (obj, name, extend) { this._synth[name] = this._synth[name] || function (val) { if (val !== undefined) { this['_' + name] = val; return this; } return this['_' + name]; }; if (extend) { var self = this; obj[name] = function () { var tmp = this.$super, ret; this.$super = self._synth[name]; ret = extend.apply(this, arguments); this.$super = tmp; return ret; }; } else { obj[name] = this._synth[name]; } }, /** * Allows a method to be overloaded. * @memberof Shared * @param arr * @returns {Function} * @constructor */ overload: Overload, /** * Define the mixins that other modules can use as required. * @memberof Shared */ mixins: { 'Mixin.Common': _dereq_('./Mixin.Common'), 'Mixin.Events': _dereq_('./Mixin.Events'), 'Mixin.ChainReactor': _dereq_('./Mixin.ChainReactor'), 'Mixin.CRUD': _dereq_('./Mixin.CRUD'), 'Mixin.Constants': _dereq_('./Mixin.Constants'), 'Mixin.Triggers': _dereq_('./Mixin.Triggers'), 'Mixin.Sorting': _dereq_('./Mixin.Sorting'), 'Mixin.Matching': _dereq_('./Mixin.Matching'), 'Mixin.Updating': _dereq_('./Mixin.Updating'), 'Mixin.Tags': _dereq_('./Mixin.Tags') } }; // Add event handling to shared Shared.mixin(Shared, 'Mixin.Events'); module.exports = Shared; },{"./Mixin.CRUD":14,"./Mixin.ChainReactor":15,"./Mixin.Common":16,"./Mixin.Constants":17,"./Mixin.Events":18,"./Mixin.Matching":19,"./Mixin.Sorting":20,"./Mixin.Tags":21,"./Mixin.Triggers":22,"./Mixin.Updating":23,"./Overload":25}],30:[function(_dereq_,module,exports){ /* jshint strict:false */ if (!Array.prototype.filter) { Array.prototype.filter = function(fun/*, thisArg*/) { if (this === void 0 || this === null) { throw new TypeError(); } var t = Object(this); var len = t.length >>> 0; // jshint ignore:line if (typeof fun !== 'function') { throw new TypeError(); } var res = []; var thisArg = arguments.length >= 2 ? arguments[1] : void 0; for (var i = 0; i < len; i++) { if (i in t) { var val = t[i]; // NOTE: Technically this should Object.defineProperty at // the next index, as push can be affected by // properties on Object.prototype and Array.prototype. // But that method's new, and collisions should be // rare, so use the more-compatible alternative. if (fun.call(thisArg, val, i, t)) { res.push(val); } } } return res; }; } if (typeof Object.create !== 'function') { Object.create = (function() { var Temp = function() {}; return function (prototype) { if (arguments.length > 1) { throw Error('Second argument not supported'); } if (typeof prototype !== 'object') { throw TypeError('Argument must be an object'); } Temp.prototype = prototype; var result = new Temp(); Temp.prototype = null; return result; }; })(); } // Production steps of ECMA-262, Edition 5, 15.4.4.14 // Reference: http://es5.github.io/#x15.4.4.14e if (!Array.prototype.indexOf) { Array.prototype.indexOf = function(searchElement, fromIndex) { var k; // 1. Let O be the result of calling ToObject passing // the this value as the argument. if (this === null) { throw new TypeError('"this" is null or not defined'); } var O = Object(this); // 2. Let lenValue be the result of calling the Get // internal method of O with the argument "length". // 3. Let len be ToUint32(lenValue). var len = O.length >>> 0; // jshint ignore:line // 4. If len is 0, return -1. if (len === 0) { return -1; } // 5. If argument fromIndex was passed let n be // ToInteger(fromIndex); else let n be 0. var n = +fromIndex || 0; if (Math.abs(n) === Infinity) { n = 0; } // 6. If n >= len, return -1. if (n >= len) { return -1; } // 7. If n >= 0, then Let k be n. // 8. Else, n<0, Let k be len - abs(n). // If k is less than 0, then let k be 0. k = Math.max(n >= 0 ? n : len - Math.abs(n), 0); // 9. Repeat, while k < len while (k < len) { // a. Let Pk be ToString(k). // This is implicit for LHS operands of the in operator // b. Let kPresent be the result of calling the // HasProperty internal method of O with argument Pk. // This step can be combined with c // c. If kPresent is true, then // i. Let elementK be the result of calling the Get // internal method of O with the argument ToString(k). // ii. Let same be the result of applying the // Strict Equality Comparison Algorithm to // searchElement and elementK. // iii. If same is true, return k. if (k in O && O[k] === searchElement) { return k; } k++; } return -1; }; } module.exports = {}; },{}]},{},[1]);
src/components/partials/Selection.js
benjamindehli/chord-finder-app-test
// Dependencies import React, { Component } from 'react'; import { connect } from 'react-redux'; // Material UI import InputLabel from '@material-ui/core/InputLabel'; import MenuItem from '@material-ui/core/MenuItem'; import FormControl from '@material-ui/core/FormControl'; import Select from '@material-ui/core/Select'; import Autocomplete from '@material-ui/lab/Autocomplete'; import TextField from '@material-ui/core/TextField'; // Actions import { updateSelectedKeyNumber } from 'actions/SelectedKeyNumberActions'; import { updateSelectedChordName, updateSelectedScaleName, updateSelectedSelectionSelectList } from 'actions/SelectedSelectionNameActions'; import { updateComputerKeyboardInputEnabled } from 'actions/ComputerKeyboardInputEnabledActions'; // Stylesheets import style from 'components/partials/Selection.module.scss'; class Selection extends Component { handleKeyChange(keyNumber) { this.props.updateSelectedSelectionSelectList( this.props.notes, keyNumber, this.props.selectedSelectionType === 'scale' ? this.props.selectedScaleName : this.props.selectedChordName, this.props.selectedSelectionType === 'scale' ? this.props.scales : this.props.chords, 'key' ); } handleChordChange(chordName) { console.log("chord name", chordName) this.props.updateSelectedSelectionSelectList( this.props.notes, this.props.selectedKeyNumber, chordName, this.props.chords, 'chord' ); } handleScaleChange(scaleName) { this.props.updateSelectedSelectionSelectList( this.props.notes, this.props.selectedKeyNumber, scaleName, this.props.scales, 'scale' ); } renderKeyOptions(notes) { return notes.map(note => { return <MenuItem value={note.number} key={note.number}>{note.name}</MenuItem>; }) } renderChordOptions(chords) { return Object.keys(chords).map(chordName => { return <MenuItem key={chordName} value={chordName}>{chordName}</MenuItem>; }) } renderScaleOptions(scales) { return Object.keys(scales).map(scaleName => { return <MenuItem key={scaleName} value={scaleName}>{scaleName}</MenuItem>; }) } render() { return ( <div className={style.selection}> <FormControl className={style.formControl}> <InputLabel id="key-select-label">Key</InputLabel> <Select className={style.select} labelId="key-select-label" id="key-select" value={this.props.selectedKeyNumber} onChange={event => this.handleKeyChange(parseInt(event.target.value))}> {this.renderKeyOptions(this.props.notes)} </Select> </FormControl> { this.props.selectedSelectionType === 'chord' ? (<FormControl className={`${style.formControl} ${style.wide}`}> <Autocomplete id="chord-select" value={this.props.selectedChordName} onChange={(event, newValue) => this.handleChordChange(newValue)} onFocus={() => this.props.updateComputerKeyboardInputEnabled(false)} onBlur={() => this.props.updateComputerKeyboardInputEnabled(true)} className={style.select} options={Object.keys(this.props.chords)} renderInput={(params) => <TextField {...params} label="Chord" className={style.input} />} /> </FormControl>) : (<FormControl className={`${style.formControl} ${style.wide}`}> <Autocomplete id="scale-select" value={this.props.selectedScaleName} onChange={(event, newValue) => this.handleScaleChange(newValue)} onFocus={() => this.props.updateComputerKeyboardInputEnabled(false)} onBlur={() => this.props.updateComputerKeyboardInputEnabled(true)} className={style.select} options={Object.keys(this.props.scales)} renderInput={(params) => <TextField {...params} label="Scale" className={style.input} />} /> </FormControl>) } </div> ) } } const mapStateToProps = state => ({ notes: state.notes, chords: state.chords, scales: state.scales, selectedKeyNumber: state.selectedKeyNumber, selectedChordName: state.selectedChordName, selectedScaleName: state.selectedScaleName, selectedSelectionType: state.selectedSelectionType }); const mapDispatchToProps = { updateSelectedKeyNumber, updateSelectedChordName, updateSelectedScaleName, updateSelectedSelectionSelectList, updateComputerKeyboardInputEnabled }; export default connect(mapStateToProps, mapDispatchToProps)(Selection);
examples/with-firebase-functions/src/App.js
jaredpalmer/razzle
import './App.css'; import React from 'react'; const App = () => <div>Welcome to Razzle.</div>; export default App;
app/javascript/mastodon/components/load_more.js
pinfort/mastodon
import React from 'react'; import { FormattedMessage } from 'react-intl'; import PropTypes from 'prop-types'; export default class LoadMore extends React.PureComponent { static propTypes = { onClick: PropTypes.func, disabled: PropTypes.bool, visible: PropTypes.bool, } static defaultProps = { visible: true, } render() { const { disabled, visible } = this.props; return ( <button className='load-more' disabled={disabled || !visible} style={{ visibility: visible ? 'visible' : 'hidden' }} onClick={this.props.onClick}> <FormattedMessage id='status.load_more' defaultMessage='Load more' /> </button> ); } }
example/misc.js
glenjamin/devboard
import React from 'react'; var BASE_URL = 'https://github.com/glenjamin/devboard/tree/master/example'; export function sourceLink(definecard, dir, file) { definecard( <a href={BASE_URL + '/' + dir + '/' + file} style={{ position: 'absolute', top: 5, right: 5 }} > Page Source </a> ); }
src/settings/Layout.web.js
NewSpring/Apollos
import React from 'react'; import PropTypes from 'prop-types'; import BackgroundView from '@ui/BackgroundView'; import { ResponsiveSideBySideView as SideBySideView, Right, Left } from '@ui/SideBySideView'; import withUser from '@data/withUser'; import UserAvatarView from '@ui/UserAvatarView'; import MediaQuery from '@ui/MediaQuery'; import styled from '@ui/styled'; export { ProfileDetails, ProfileAddress, ChangePassword } from './forms'; const CurrentUserAvatar = withUser(UserAvatarView); const DesktopCurrentUserAvatar = styled({ height: '100%' })(CurrentUserAvatar); const FlexedSideBySideView = styled({ flex: 1 })(SideBySideView); const FlexedLeft = styled({ flex: 1 })(Left); const Layout = ({ children }) => ( <BackgroundView> <FlexedSideBySideView> <FlexedLeft>{children}</FlexedLeft> <MediaQuery minWidth="md"> <Right> <DesktopCurrentUserAvatar allowProfileImageChange /> </Right> </MediaQuery> </FlexedSideBySideView> </BackgroundView> ); Layout.propTypes = { children: PropTypes.node, }; export default Layout;
pages/blog/test-article-two.js
jacobhamblin/drew
/** * React Static Boilerplate * https://github.com/koistya/react-static-boilerplate * Copyright (c) Konstantin Tarkus (@koistya) | MIT license */ import React, { Component } from 'react'; export default class extends Component { render() { return ( <div> <h1>Test Article 2</h1> <p>Coming soon.</p> </div> ); } }
examples/with-reason-react/src/client.js
jaredpalmer/razzle
import React from 'react'; import { render } from 'react-dom'; import { make } from 'bs/App'; // BuckleScript output directory const App = make; render( <App title="Welcome to Razzle Reason React" />, document.getElementById('root') ); if (module.hot) { module.hot.accept(); }
ajax/libs/analytics.js/2.3.6/analytics.js
the-destro/cdnjs
(function outer(modules, cache, entries){ /** * Global */ var global = (function(){ return this; })(); /** * Require `name`. * * @param {String} name * @param {Boolean} jumped * @api public */ function require(name, jumped){ if (cache[name]) return cache[name].exports; if (modules[name]) return call(name, require); throw new Error('cannot find module "' + name + '"'); } /** * Call module `id` and cache it. * * @param {Number} id * @param {Function} require * @return {Function} * @api private */ function call(id, require){ var m = cache[id] = { exports: {} }; var mod = modules[id]; var name = mod[2]; var fn = mod[0]; fn.call(m.exports, function(req){ var dep = modules[id][1][req]; return require(dep ? dep : req); }, m, m.exports, outer, modules, cache, entries); // expose as `name`. if (name) cache[name] = cache[id]; return cache[id].exports; } /** * Require all entries exposing them on global if needed. */ for (var id in entries) { if (entries[id]) { global[entries[id]] = require(id); } else { require(id); } } /** * Duo flag. */ require.duo = true; /** * Expose cache. */ require.cache = cache; /** * Expose modules */ require.modules = modules; /** * Return newest require. */ return require; })({ 1: [function(require, module, exports) { /** * Analytics.js * * (C) 2013 Segment.io Inc. */ var Integrations = require('analytics.js-integrations'); var Analytics = require('./analytics'); var each = require('each'); /** * Expose the `analytics` singleton. */ var analytics = module.exports = exports = new Analytics(); /** * Expose require */ analytics.require = require; /** * Expose `VERSION`. */ exports.VERSION = require('./version'); /** * Add integrations. */ each(Integrations, function (name, Integration) { analytics.use(Integration); }); }, {"./analytics":2,"./version":3,"analytics.js-integrations":4,"each":5}], 2: [function(require, module, exports) { var after = require('after'); var bind = require('bind'); var callback = require('callback'); var canonical = require('canonical'); var clone = require('clone'); var cookie = require('./cookie'); var debug = require('debug'); var defaults = require('defaults'); var each = require('each'); var Emitter = require('emitter'); var group = require('./group'); var is = require('is'); var isEmail = require('is-email'); var isMeta = require('is-meta'); var newDate = require('new-date'); var on = require('event').bind; var prevent = require('prevent'); var querystring = require('querystring'); var size = require('object').length; var store = require('./store'); var url = require('url'); var user = require('./user'); var Facade = require('facade'); var Identify = Facade.Identify; var Group = Facade.Group; var Alias = Facade.Alias; var Track = Facade.Track; var Page = Facade.Page; /** * Expose `Analytics`. */ exports = module.exports = Analytics; /** * Expose `cookie` */ exports.cookie = cookie; exports.store = store; /** * Initialize a new `Analytics` instance. */ function Analytics () { this.Integrations = {}; this._integrations = {}; this._readied = false; this._timeout = 300; this._user = user; // BACKWARDS COMPATIBILITY bind.all(this); var self = this; this.on('initialize', function (settings, options) { if (options.initialPageview) self.page(); }); this.on('initialize', function () { self._parseQuery(); }); } /** * Event Emitter. */ Emitter(Analytics.prototype); /** * Use a `plugin`. * * @param {Function} plugin * @return {Analytics} */ Analytics.prototype.use = function (plugin) { plugin(this); return this; }; /** * Define a new `Integration`. * * @param {Function} Integration * @return {Analytics} */ Analytics.prototype.addIntegration = function (Integration) { var name = Integration.prototype.name; if (!name) throw new TypeError('attempted to add an invalid integration'); this.Integrations[name] = Integration; return this; }; /** * Initialize with the given integration `settings` and `options`. Aliased to * `init` for convenience. * * @param {Object} settings * @param {Object} options (optional) * @return {Analytics} */ Analytics.prototype.init = Analytics.prototype.initialize = function (settings, options) { settings = settings || {}; options = options || {}; this._options(options); this._readied = false; // clean unknown integrations from settings var self = this; each(settings, function (name) { var Integration = self.Integrations[name]; if (!Integration) delete settings[name]; }); // add integrations each(settings, function (name, opts) { var Integration = self.Integrations[name]; var integration = new Integration(clone(opts)); self.add(integration); }); var integrations = this._integrations; // load user now that options are set user.load(); group.load(); // make ready callback var ready = after(size(integrations), function () { self._readied = true; self.emit('ready'); }); // initialize integrations, passing ready each(integrations, function (name, integration) { if (options.initialPageview && integration.options.initialPageview === false) { integration.page = after(2, integration.page); } integration.analytics = self; integration.once('ready', ready); integration.initialize(); }); // backwards compat with angular plugin. // TODO: remove this.initialized = true; this.emit('initialize', settings, options); return this; }; /** * Add an integration. * * @param {Integration} integration */ Analytics.prototype.add = function(integration){ this._integrations[integration.name] = integration; return this; }; /** * Identify a user by optional `id` and `traits`. * * @param {String} id (optional) * @param {Object} traits (optional) * @param {Object} options (optional) * @param {Function} fn (optional) * @return {Analytics} */ Analytics.prototype.identify = function (id, traits, options, fn) { if (is.fn(options)) fn = options, options = null; if (is.fn(traits)) fn = traits, options = null, traits = null; if (is.object(id)) options = traits, traits = id, id = user.id(); // clone traits before we manipulate so we don't do anything uncouth, and take // from `user` so that we carryover anonymous traits user.identify(id, traits); id = user.id(); traits = user.traits(); this._invoke('identify', new Identify({ options: options, traits: traits, userId: id })); // emit this.emit('identify', id, traits, options); this._callback(fn); return this; }; /** * Return the current user. * * @return {Object} */ Analytics.prototype.user = function () { return user; }; /** * Identify a group by optional `id` and `traits`. Or, if no arguments are * supplied, return the current group. * * @param {String} id (optional) * @param {Object} traits (optional) * @param {Object} options (optional) * @param {Function} fn (optional) * @return {Analytics or Object} */ Analytics.prototype.group = function (id, traits, options, fn) { if (0 === arguments.length) return group; if (is.fn(options)) fn = options, options = null; if (is.fn(traits)) fn = traits, options = null, traits = null; if (is.object(id)) options = traits, traits = id, id = group.id(); // grab from group again to make sure we're taking from the source group.identify(id, traits); id = group.id(); traits = group.traits(); this._invoke('group', new Group({ options: options, traits: traits, groupId: id })); this.emit('group', id, traits, options); this._callback(fn); return this; }; /** * Track an `event` that a user has triggered with optional `properties`. * * @param {String} event * @param {Object} properties (optional) * @param {Object} options (optional) * @param {Function} fn (optional) * @return {Analytics} */ Analytics.prototype.track = function (event, properties, options, fn) { if (is.fn(options)) fn = options, options = null; if (is.fn(properties)) fn = properties, options = null, properties = null; this._invoke('track', new Track({ properties: properties, options: options, event: event })); this.emit('track', event, properties, options); this._callback(fn); return this; }; /** * Helper method to track an outbound link that would normally navigate away * from the page before the analytics calls were sent. * * BACKWARDS COMPATIBILITY: aliased to `trackClick`. * * @param {Element or Array} links * @param {String or Function} event * @param {Object or Function} properties (optional) * @return {Analytics} */ Analytics.prototype.trackClick = Analytics.prototype.trackLink = function (links, event, properties) { if (!links) return this; if (is.element(links)) links = [links]; // always arrays, handles jquery var self = this; each(links, function (el) { on(el, 'click', function (e) { var ev = is.fn(event) ? event(el) : event; var props = is.fn(properties) ? properties(el) : properties; self.track(ev, props); if (el.href && el.target !== '_blank' && !isMeta(e)) { prevent(e); self._callback(function () { window.location.href = el.href; }); } }); }); return this; }; /** * Helper method to track an outbound form that would normally navigate away * from the page before the analytics calls were sent. * * BACKWARDS COMPATIBILITY: aliased to `trackSubmit`. * * @param {Element or Array} forms * @param {String or Function} event * @param {Object or Function} properties (optional) * @return {Analytics} */ Analytics.prototype.trackSubmit = Analytics.prototype.trackForm = function (forms, event, properties) { if (!forms) return this; if (is.element(forms)) forms = [forms]; // always arrays, handles jquery var self = this; each(forms, function (el) { function handler (e) { prevent(e); var ev = is.fn(event) ? event(el) : event; var props = is.fn(properties) ? properties(el) : properties; self.track(ev, props); self._callback(function () { el.submit(); }); } // support the events happening through jQuery or Zepto instead of through // the normal DOM API, since `el.submit` doesn't bubble up events... var $ = window.jQuery || window.Zepto; if ($) { $(el).submit(handler); } else { on(el, 'submit', handler); } }); return this; }; /** * Trigger a pageview, labeling the current page with an optional `category`, * `name` and `properties`. * * @param {String} category (optional) * @param {String} name (optional) * @param {Object or String} properties (or path) (optional) * @param {Object} options (optional) * @param {Function} fn (optional) * @return {Analytics} */ Analytics.prototype.page = function (category, name, properties, options, fn) { if (is.fn(options)) fn = options, options = null; if (is.fn(properties)) fn = properties, options = properties = null; if (is.fn(name)) fn = name, options = properties = name = null; if (is.object(category)) options = name, properties = category, name = category = null; if (is.object(name)) options = properties, properties = name, name = null; if (is.string(category) && !is.string(name)) name = category, category = null; var defs = { path: canonicalPath(), referrer: document.referrer, title: document.title, search: location.search }; if (name) defs.name = name; if (category) defs.category = category; properties = clone(properties) || {}; defaults(properties, defs); properties.url = properties.url || canonicalUrl(properties.search); this._invoke('page', new Page({ properties: properties, category: category, options: options, name: name })); this.emit('page', category, name, properties, options); this._callback(fn); return this; }; /** * BACKWARDS COMPATIBILITY: convert an old `pageview` to a `page` call. * * @param {String} url (optional) * @param {Object} options (optional) * @return {Analytics} * @api private */ Analytics.prototype.pageview = function (url, options) { var properties = {}; if (url) properties.path = url; this.page(properties); return this; }; /** * Merge two previously unassociated user identities. * * @param {String} to * @param {String} from (optional) * @param {Object} options (optional) * @param {Function} fn (optional) * @return {Analytics} */ Analytics.prototype.alias = function (to, from, options, fn) { if (is.fn(options)) fn = options, options = null; if (is.fn(from)) fn = from, options = null, from = null; if (is.object(from)) options = from, from = null; this._invoke('alias', new Alias({ options: options, from: from, to: to })); this.emit('alias', to, from, options); this._callback(fn); return this; }; /** * Register a `fn` to be fired when all the analytics services are ready. * * @param {Function} fn * @return {Analytics} */ Analytics.prototype.ready = function (fn) { if (!is.fn(fn)) return this; this._readied ? callback.async(fn) : this.once('ready', fn); return this; }; /** * Set the `timeout` (in milliseconds) used for callbacks. * * @param {Number} timeout */ Analytics.prototype.timeout = function (timeout) { this._timeout = timeout; }; /** * Enable or disable debug. * * @param {String or Boolean} str */ Analytics.prototype.debug = function(str){ if (0 == arguments.length || str) { debug.enable('analytics:' + (str || '*')); } else { debug.disable(); } }; /** * Apply options. * * @param {Object} options * @return {Analytics} * @api private */ Analytics.prototype._options = function (options) { options = options || {}; cookie.options(options.cookie); store.options(options.localStorage); user.options(options.user); group.options(options.group); return this; }; /** * Callback a `fn` after our defined timeout period. * * @param {Function} fn * @return {Analytics} * @api private */ Analytics.prototype._callback = function (fn) { callback.async(fn, this._timeout); return this; }; /** * Call `method` with `facade` on all enabled integrations. * * @param {String} method * @param {Facade} facade * @return {Analytics} * @api private */ Analytics.prototype._invoke = function (method, facade) { var options = facade.options(); this.emit('invoke', facade); each(this._integrations, function (name, integration) { if (!facade.enabled(name)) return; integration.invoke.call(integration, method, facade); }); return this; }; /** * Push `args`. * * @param {Array} args * @api private */ Analytics.prototype.push = function(args){ var method = args.shift(); if (!this[method]) return; this[method].apply(this, args); }; /** * Parse the query string for callable methods. * * @return {Analytics} * @api private */ Analytics.prototype._parseQuery = function () { // Identify and track any `ajs_uid` and `ajs_event` parameters in the URL. var q = querystring.parse(window.location.search); if (q.ajs_uid) this.identify(q.ajs_uid); if (q.ajs_event) this.track(q.ajs_event); return this; }; /** * Return the canonical path for the page. * * @return {String} */ function canonicalPath () { var canon = canonical(); if (!canon) return window.location.pathname; var parsed = url.parse(canon); return parsed.pathname; } /** * Return the canonical URL for the page concat the given `search` * and strip the hash. * * @param {String} search * @return {String} */ function canonicalUrl (search) { var canon = canonical(); if (canon) return ~canon.indexOf('?') ? canon : canon + search; var url = window.location.href; var i = url.indexOf('#'); return -1 == i ? url : url.slice(0, i); } }, {"./cookie":6,"./group":7,"./store":8,"./user":9,"after":10,"bind":11,"callback":12,"canonical":13,"clone":14,"debug":15,"defaults":16,"each":5,"emitter":17,"is":18,"is-email":19,"is-meta":20,"new-date":21,"event":22,"prevent":23,"querystring":24,"object":25,"url":26,"facade":27}], 6: [function(require, module, exports) { var debug = require('debug')('analytics.js:cookie'); var bind = require('bind'); var cookie = require('cookie'); var clone = require('clone'); var defaults = require('defaults'); var json = require('json'); var topDomain = require('top-domain'); /** * Initialize a new `Cookie` with `options`. * * @param {Object} options */ function Cookie (options) { this.options(options); } /** * Get or set the cookie options. * * @param {Object} options * @field {Number} maxage (1 year) * @field {String} domain * @field {String} path * @field {Boolean} secure */ Cookie.prototype.options = function (options) { if (arguments.length === 0) return this._options; options = options || {}; var domain = '.' + topDomain(window.location.href); this._options = defaults(options, { maxage: 31536000000, // default to a year path: '/', domain: domain }); // http://curl.haxx.se/rfc/cookie_spec.html // https://publicsuffix.org/list/effective_tld_names.dat // // try setting a dummy cookie with the options // if the cookie isn't set, it probably means // that the domain is on the public suffix list // like myapp.herokuapp.com or localhost / ip. this.set('ajs:test', true); if (!this.get('ajs:test')) { debug('fallback to domain=null'); this._options.domain = null; } this.remove('ajs:test'); }; /** * Set a `key` and `value` in our cookie. * * @param {String} key * @param {Object} value * @return {Boolean} saved */ Cookie.prototype.set = function (key, value) { try { value = json.stringify(value); cookie(key, value, clone(this._options)); return true; } catch (e) { return false; } }; /** * Get a value from our cookie by `key`. * * @param {String} key * @return {Object} value */ Cookie.prototype.get = function (key) { try { var value = cookie(key); value = value ? json.parse(value) : null; return value; } catch (e) { return null; } }; /** * Remove a value from our cookie by `key`. * * @param {String} key * @return {Boolean} removed */ Cookie.prototype.remove = function (key) { try { cookie(key, null, clone(this._options)); return true; } catch (e) { return false; } }; /** * Expose the cookie singleton. */ module.exports = bind.all(new Cookie()); /** * Expose the `Cookie` constructor. */ module.exports.Cookie = Cookie; }, {"debug":15,"bind":11,"cookie":28,"clone":14,"defaults":16,"json":29,"top-domain":30}], 15: [function(require, module, exports) { if ('undefined' == typeof window) { module.exports = require('./lib/debug'); } else { module.exports = require('./debug'); } }, {"./lib/debug":31,"./debug":32}], 31: [function(require, module, exports) { /** * Module dependencies. */ var tty = require('tty'); /** * Expose `debug()` as the module. */ module.exports = debug; /** * Enabled debuggers. */ var names = [] , skips = []; (process.env.DEBUG || '') .split(/[\s,]+/) .forEach(function(name){ name = name.replace('*', '.*?'); if (name[0] === '-') { skips.push(new RegExp('^' + name.substr(1) + '$')); } else { names.push(new RegExp('^' + name + '$')); } }); /** * Colors. */ var colors = [6, 2, 3, 4, 5, 1]; /** * Previous debug() call. */ var prev = {}; /** * Previously assigned color. */ var prevColor = 0; /** * Is stdout a TTY? Colored output is disabled when `true`. */ var isatty = tty.isatty(2); /** * Select a color. * * @return {Number} * @api private */ function color() { return colors[prevColor++ % colors.length]; } /** * Humanize the given `ms`. * * @param {Number} m * @return {String} * @api private */ function humanize(ms) { var sec = 1000 , min = 60 * 1000 , hour = 60 * min; if (ms >= hour) return (ms / hour).toFixed(1) + 'h'; if (ms >= min) return (ms / min).toFixed(1) + 'm'; if (ms >= sec) return (ms / sec | 0) + 's'; return ms + 'ms'; } /** * Create a debugger with the given `name`. * * @param {String} name * @return {Type} * @api public */ function debug(name) { function disabled(){} disabled.enabled = false; var match = skips.some(function(re){ return re.test(name); }); if (match) return disabled; match = names.some(function(re){ return re.test(name); }); if (!match) return disabled; var c = color(); function colored(fmt) { fmt = coerce(fmt); var curr = new Date; var ms = curr - (prev[name] || curr); prev[name] = curr; fmt = ' \u001b[9' + c + 'm' + name + ' ' + '\u001b[3' + c + 'm\u001b[90m' + fmt + '\u001b[3' + c + 'm' + ' +' + humanize(ms) + '\u001b[0m'; console.error.apply(this, arguments); } function plain(fmt) { fmt = coerce(fmt); fmt = new Date().toUTCString() + ' ' + name + ' ' + fmt; console.error.apply(this, arguments); } colored.enabled = plain.enabled = true; return isatty || process.env.DEBUG_COLORS ? colored : plain; } /** * Coerce `val`. */ function coerce(val) { if (val instanceof Error) return val.stack || val.message; return val; } }, {}], 32: [function(require, module, exports) { /** * Expose `debug()` as the module. */ module.exports = debug; /** * Create a debugger with the given `name`. * * @param {String} name * @return {Type} * @api public */ function debug(name) { if (!debug.enabled(name)) return function(){}; return function(fmt){ fmt = coerce(fmt); var curr = new Date; var ms = curr - (debug[name] || curr); debug[name] = curr; fmt = name + ' ' + fmt + ' +' + debug.humanize(ms); // This hackery is required for IE8 // where `console.log` doesn't have 'apply' window.console && console.log && Function.prototype.apply.call(console.log, console, arguments); } } /** * The currently active debug mode names. */ debug.names = []; debug.skips = []; /** * Enables a debug mode by name. This can include modes * separated by a colon and wildcards. * * @param {String} name * @api public */ debug.enable = function(name) { try { localStorage.debug = name; } catch(e){} var split = (name || '').split(/[\s,]+/) , len = split.length; for (var i = 0; i < len; i++) { name = split[i].replace('*', '.*?'); if (name[0] === '-') { debug.skips.push(new RegExp('^' + name.substr(1) + '$')); } else { debug.names.push(new RegExp('^' + name + '$')); } } }; /** * Disable debug output. * * @api public */ debug.disable = function(){ debug.enable(''); }; /** * Humanize the given `ms`. * * @param {Number} m * @return {String} * @api private */ debug.humanize = function(ms) { var sec = 1000 , min = 60 * 1000 , hour = 60 * min; if (ms >= hour) return (ms / hour).toFixed(1) + 'h'; if (ms >= min) return (ms / min).toFixed(1) + 'm'; if (ms >= sec) return (ms / sec | 0) + 's'; return ms + 'ms'; }; /** * Returns true if the given mode name is enabled, false otherwise. * * @param {String} name * @return {Boolean} * @api public */ debug.enabled = function(name) { for (var i = 0, len = debug.skips.length; i < len; i++) { if (debug.skips[i].test(name)) { return false; } } for (var i = 0, len = debug.names.length; i < len; i++) { if (debug.names[i].test(name)) { return true; } } return false; }; /** * Coerce `val`. */ function coerce(val) { if (val instanceof Error) return val.stack || val.message; return val; } // persist try { if (window.localStorage) debug.enable(localStorage.debug); } catch(e){} }, {}], 11: [function(require, module, exports) { try { var bind = require('bind'); } catch (e) { var bind = require('bind-component'); } var bindAll = require('bind-all'); /** * Expose `bind`. */ module.exports = exports = bind; /** * Expose `bindAll`. */ exports.all = bindAll; /** * Expose `bindMethods`. */ exports.methods = bindMethods; /** * Bind `methods` on `obj` to always be called with the `obj` as context. * * @param {Object} obj * @param {String} methods... */ function bindMethods (obj, methods) { methods = [].slice.call(arguments, 1); for (var i = 0, method; method = methods[i]; i++) { obj[method] = bind(obj, obj[method]); } return obj; } }, {"bind":33,"bind-all":34}], 33: [function(require, module, exports) { /** * Slice reference. */ var slice = [].slice; /** * Bind `obj` to `fn`. * * @param {Object} obj * @param {Function|String} fn or string * @return {Function} * @api public */ module.exports = function(obj, fn){ if ('string' == typeof fn) fn = obj[fn]; if ('function' != typeof fn) throw new Error('bind() requires a function'); var args = slice.call(arguments, 2); return function(){ return fn.apply(obj, args.concat(slice.call(arguments))); } }; }, {}], 34: [function(require, module, exports) { try { var bind = require('bind'); var type = require('type'); } catch (e) { var bind = require('bind-component'); var type = require('type-component'); } module.exports = function (obj) { for (var key in obj) { var val = obj[key]; if (type(val) === 'function') obj[key] = bind(obj, obj[key]); } return obj; }; }, {"bind":33,"type":35}], 35: [function(require, module, exports) { /** * toString ref. */ var toString = Object.prototype.toString; /** * Return the type of `val`. * * @param {Mixed} val * @return {String} * @api public */ module.exports = function(val){ switch (toString.call(val)) { case '[object Function]': return 'function'; case '[object Date]': return 'date'; case '[object RegExp]': return 'regexp'; case '[object Arguments]': return 'arguments'; case '[object Array]': return 'array'; case '[object String]': return 'string'; } if (val === null) return 'null'; if (val === undefined) return 'undefined'; if (val && val.nodeType === 1) return 'element'; if (val === Object(val)) return 'object'; return typeof val; }; }, {}], 28: [function(require, module, exports) { /** * Encode. */ var encode = encodeURIComponent; /** * Decode. */ var decode = decodeURIComponent; /** * Set or get cookie `name` with `value` and `options` object. * * @param {String} name * @param {String} value * @param {Object} options * @return {Mixed} * @api public */ module.exports = function(name, value, options){ switch (arguments.length) { case 3: case 2: return set(name, value, options); case 1: return get(name); default: return all(); } }; /** * Set cookie `name` to `value`. * * @param {String} name * @param {String} value * @param {Object} options * @api private */ function set(name, value, options) { options = options || {}; var str = encode(name) + '=' + encode(value); if (null == value) options.maxage = -1; if (options.maxage) { options.expires = new Date(+new Date + options.maxage); } if (options.path) str += '; path=' + options.path; if (options.domain) str += '; domain=' + options.domain; if (options.expires) str += '; expires=' + options.expires.toGMTString(); if (options.secure) str += '; secure'; document.cookie = str; } /** * Return all cookies. * * @return {Object} * @api private */ function all() { return parse(document.cookie); } /** * Get cookie `name`. * * @param {String} name * @return {String} * @api private */ function get(name) { return all()[name]; } /** * Parse cookie `str`. * * @param {String} str * @return {Object} * @api private */ function parse(str) { var obj = {}; var pairs = str.split(/ *; */); var pair; if ('' == pairs[0]) return obj; for (var i = 0; i < pairs.length; ++i) { pair = pairs[i].split('='); obj[decode(pair[0])] = decode(pair[1]); } return obj; } }, {}], 14: [function(require, module, exports) { /** * Module dependencies. */ var type; try { type = require('type'); } catch(e){ type = require('type-component'); } /** * Module exports. */ module.exports = clone; /** * Clones objects. * * @param {Mixed} any object * @api public */ function clone(obj){ switch (type(obj)) { case 'object': var copy = {}; for (var key in obj) { if (obj.hasOwnProperty(key)) { copy[key] = clone(obj[key]); } } return copy; case 'array': var copy = new Array(obj.length); for (var i = 0, l = obj.length; i < l; i++) { copy[i] = clone(obj[i]); } return copy; case 'regexp': // from millermedeiros/amd-utils - MIT var flags = ''; flags += obj.multiline ? 'm' : ''; flags += obj.global ? 'g' : ''; flags += obj.ignoreCase ? 'i' : ''; return new RegExp(obj.source, flags); case 'date': return new Date(obj.getTime()); default: // string, number, boolean, … return obj; } } }, {"type":35}], 16: [function(require, module, exports) { 'use strict'; /** * Merge default values. * * @param {Object} dest * @param {Object} defaults * @return {Object} * @api public */ var defaults = function (dest, src, recursive) { for (var prop in src) { if (recursive && dest[prop] instanceof Object && src[prop] instanceof Object) { dest[prop] = defaults(dest[prop], src[prop], true); } else if (! (prop in dest)) { dest[prop] = src[prop]; } } return dest; }; /** * Expose `defaults`. */ module.exports = defaults; }, {}], 29: [function(require, module, exports) { var json = window.JSON || {}; var stringify = json.stringify; var parse = json.parse; module.exports = parse && stringify ? JSON : require('json-fallback'); }, {"json-fallback":36}], 36: [function(require, module, exports) { /* json2.js 2014-02-04 Public Domain. NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. See http://www.JSON.org/js.html This code should be minified before deployment. See http://javascript.crockford.com/jsmin.html USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO NOT CONTROL. This file creates a global JSON object containing two methods: stringify and parse. JSON.stringify(value, replacer, space) value any JavaScript value, usually an object or array. replacer an optional parameter that determines how object values are stringified for objects. It can be a function or an array of strings. space an optional parameter that specifies the indentation of nested structures. If it is omitted, the text will be packed without extra whitespace. If it is a number, it will specify the number of spaces to indent at each level. If it is a string (such as '\t' or '&nbsp;'), it contains the characters used to indent at each level. This method produces a JSON text from a JavaScript value. When an object value is found, if the object contains a toJSON method, its toJSON method will be called and the result will be stringified. A toJSON method does not serialize: it returns the value represented by the name/value pair that should be serialized, or undefined if nothing should be serialized. The toJSON method will be passed the key associated with the value, and this will be bound to the value For example, this would serialize Dates as ISO strings. Date.prototype.toJSON = function (key) { function f(n) { // Format integers to have at least two digits. return n < 10 ? '0' + n : n; } return this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z'; }; You can provide an optional replacer method. It will be passed the key and value of each member, with this bound to the containing object. The value that is returned from your method will be serialized. If your method returns undefined, then the member will be excluded from the serialization. If the replacer parameter is an array of strings, then it will be used to select the members to be serialized. It filters the results such that only members with keys listed in the replacer array are stringified. Values that do not have JSON representations, such as undefined or functions, will not be serialized. Such values in objects will be dropped; in arrays they will be replaced with null. You can use a replacer function to replace those with JSON values. JSON.stringify(undefined) returns undefined. The optional space parameter produces a stringification of the value that is filled with line breaks and indentation to make it easier to read. If the space parameter is a non-empty string, then that string will be used for indentation. If the space parameter is a number, then the indentation will be that many spaces. Example: text = JSON.stringify(['e', {pluribus: 'unum'}]); // text is '["e",{"pluribus":"unum"}]' text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t'); // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]' text = JSON.stringify([new Date()], function (key, value) { return this[key] instanceof Date ? 'Date(' + this[key] + ')' : value; }); // text is '["Date(---current time---)"]' JSON.parse(text, reviver) This method parses a JSON text to produce an object or array. It can throw a SyntaxError exception. The optional reviver parameter is a function that can filter and transform the results. It receives each of the keys and values, and its return value is used instead of the original value. If it returns what it received, then the structure is not modified. If it returns undefined then the member is deleted. Example: // Parse the text. Values that look like ISO date strings will // be converted to Date objects. myData = JSON.parse(text, function (key, value) { var a; if (typeof value === 'string') { a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value); if (a) { return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6])); } } return value; }); myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) { var d; if (typeof value === 'string' && value.slice(0, 5) === 'Date(' && value.slice(-1) === ')') { d = new Date(value.slice(5, -1)); if (d) { return d; } } return value; }); This is a reference implementation. You are free to copy, modify, or redistribute. */ /*jslint evil: true, regexp: true */ /*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply, call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours, getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join, lastIndex, length, parse, prototype, push, replace, slice, stringify, test, toJSON, toString, valueOf */ // Create a JSON object only if one does not already exist. We create the // methods in a closure to avoid creating global variables. (function () { 'use strict'; var JSON = module.exports = {}; function f(n) { // Format integers to have at least two digits. return n < 10 ? '0' + n : n; } if (typeof Date.prototype.toJSON !== 'function') { Date.prototype.toJSON = function () { return isFinite(this.valueOf()) ? this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z' : null; }; String.prototype.toJSON = Number.prototype.toJSON = Boolean.prototype.toJSON = function () { return this.valueOf(); }; } var cx, escapable, gap, indent, meta, rep; function quote(string) { // If the string contains no control characters, no quote characters, and no // backslash characters, then we can safely slap some quotes around it. // Otherwise we must also replace the offending characters with safe escape // sequences. escapable.lastIndex = 0; return escapable.test(string) ? '"' + string.replace(escapable, function (a) { var c = meta[a]; return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; } function str(key, holder) { // Produce a string from holder[key]. var i, // The loop counter. k, // The member key. v, // The member value. length, mind = gap, partial, value = holder[key]; // If the value has a toJSON method, call it to obtain a replacement value. if (value && typeof value === 'object' && typeof value.toJSON === 'function') { value = value.toJSON(key); } // If we were called with a replacer function, then call the replacer to // obtain a replacement value. if (typeof rep === 'function') { value = rep.call(holder, key, value); } // What happens next depends on the value's type. switch (typeof value) { case 'string': return quote(value); case 'number': // JSON numbers must be finite. Encode non-finite numbers as null. return isFinite(value) ? String(value) : 'null'; case 'boolean': case 'null': // If the value is a boolean or null, convert it to a string. Note: // typeof null does not produce 'null'. The case is included here in // the remote chance that this gets fixed someday. return String(value); // If the type is 'object', we might be dealing with an object or an array or // null. case 'object': // Due to a specification blunder in ECMAScript, typeof null is 'object', // so watch out for that case. if (!value) { return 'null'; } // Make an array to hold the partial results of stringifying this object value. gap += indent; partial = []; // Is the value an array? if (Object.prototype.toString.apply(value) === '[object Array]') { // The value is an array. Stringify every element. Use null as a placeholder // for non-JSON values. length = value.length; for (i = 0; i < length; i += 1) { partial[i] = str(i, value) || 'null'; } // Join all of the elements together, separated with commas, and wrap them in // brackets. v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']'; gap = mind; return v; } // If the replacer is an array, use it to select the members to be stringified. if (rep && typeof rep === 'object') { length = rep.length; for (i = 0; i < length; i += 1) { if (typeof rep[i] === 'string') { k = rep[i]; v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } else { // Otherwise, iterate through all of the keys in the object. for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } // Join all of the member texts together, separated with commas, // and wrap them in braces. v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}'; gap = mind; return v; } } // If the JSON object does not yet have a stringify method, give it one. if (typeof JSON.stringify !== 'function') { escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; meta = { // table of character substitutions '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '\\': '\\\\' }; JSON.stringify = function (value, replacer, space) { // The stringify method takes a value and an optional replacer, and an optional // space parameter, and returns a JSON text. The replacer can be a function // that can replace values, or an array of strings that will select the keys. // A default replacer method can be provided. Use of the space parameter can // produce text that is more easily readable. var i; gap = ''; indent = ''; // If the space parameter is a number, make an indent string containing that // many spaces. if (typeof space === 'number') { for (i = 0; i < space; i += 1) { indent += ' '; } // If the space parameter is a string, it will be used as the indent string. } else if (typeof space === 'string') { indent = space; } // If there is a replacer, it must be a function or an array. // Otherwise, throw an error. rep = replacer; if (replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) { throw new Error('JSON.stringify'); } // Make a fake root object containing our value under the key of ''. // Return the result of stringifying the value. return str('', {'': value}); }; } // If the JSON object does not yet have a parse method, give it one. if (typeof JSON.parse !== 'function') { cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; JSON.parse = function (text, reviver) { // The parse method takes a text and an optional reviver function, and returns // a JavaScript value if the text is a valid JSON text. var j; function walk(holder, key) { // The walk method is used to recursively walk the resulting structure so // that modifications can be made. var k, v, value = holder[key]; if (value && typeof value === 'object') { for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = walk(value, k); if (v !== undefined) { value[k] = v; } else { delete value[k]; } } } } return reviver.call(holder, key, value); } // Parsing happens in four stages. In the first stage, we replace certain // Unicode characters with escape sequences. JavaScript handles many characters // incorrectly, either silently deleting them, or treating them as line endings. text = String(text); cx.lastIndex = 0; if (cx.test(text)) { text = text.replace(cx, function (a) { return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }); } // In the second stage, we run the text against regular expressions that look // for non-JSON patterns. We are especially concerned with '()' and 'new' // because they can cause invocation, and '=' because it can cause mutation. // But just to be safe, we want to reject all unexpected forms. // We split the second stage into 4 regexp operations in order to work around // crippling inefficiencies in IE's and Safari's regexp engines. First we // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we // replace all simple value tokens with ']' characters. Third, we delete all // open brackets that follow a colon or comma or that begin the text. Finally, // we look to see that the remaining characters are only whitespace or ']' or // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval. if (/^[\],:{}\s]*$/ .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@') .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']') .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { // In the third stage we use the eval function to compile the text into a // JavaScript structure. The '{' operator is subject to a syntactic ambiguity // in JavaScript: it can begin a block or an object literal. We wrap the text // in parens to eliminate the ambiguity. j = eval('(' + text + ')'); // In the optional fourth stage, we recursively walk the new structure, passing // each name/value pair to a reviver function for possible transformation. return typeof reviver === 'function' ? walk({'': j}, '') : j; } // If the text is not JSON parseable, then a SyntaxError is thrown. throw new SyntaxError('JSON.parse'); }; } }()); }, {}], 30: [function(require, module, exports) { /** * Module dependencies. */ var parse = require('url').parse; /** * Expose `domain` */ module.exports = domain; /** * RegExp */ var regexp = /[a-z0-9][a-z0-9\-]*[a-z0-9]\.[a-z\.]{2,6}$/i; /** * Get the top domain. * * Official Grammar: http://tools.ietf.org/html/rfc883#page-56 * Look for tlds with up to 2-6 characters. * * Example: * * domain('http://localhost:3000/baz'); * // => '' * domain('http://dev:3000/baz'); * // => '' * domain('http://127.0.0.1:3000/baz'); * // => '' * domain('http://segment.io/baz'); * // => 'segment.io' * * @param {String} url * @return {String} * @api public */ function domain(url){ var host = parse(url).hostname; var match = host.match(regexp); return match ? match[0] : ''; }; }, {"url":26}], 26: [function(require, module, exports) { /** * Parse the given `url`. * * @param {String} str * @return {Object} * @api public */ exports.parse = function(url){ var a = document.createElement('a'); a.href = url; return { href: a.href, host: a.host, port: a.port, hash: a.hash, hostname: a.hostname, pathname: a.pathname, protocol: a.protocol, search: a.search, query: a.search.slice(1) } }; /** * Check if `url` is absolute. * * @param {String} url * @return {Boolean} * @api public */ exports.isAbsolute = function(url){ if (0 == url.indexOf('//')) return true; if (~url.indexOf('://')) return true; return false; }; /** * Check if `url` is relative. * * @param {String} url * @return {Boolean} * @api public */ exports.isRelative = function(url){ return ! exports.isAbsolute(url); }; /** * Check if `url` is cross domain. * * @param {String} url * @return {Boolean} * @api public */ exports.isCrossDomain = function(url){ url = exports.parse(url); return url.hostname != location.hostname || url.port != location.port || url.protocol != location.protocol; }; }, {}], 7: [function(require, module, exports) { var debug = require('debug')('analytics:group'); var Entity = require('./entity'); var inherit = require('inherit'); var bind = require('bind'); /** * Group defaults */ Group.defaults = { persist: true, cookie: { key: 'ajs_group_id' }, localStorage: { key: 'ajs_group_properties' } }; /** * Initialize a new `Group` with `options`. * * @param {Object} options */ function Group (options) { this.defaults = Group.defaults; this.debug = debug; Entity.call(this, options); } /** * Inherit `Entity` */ inherit(Group, Entity); /** * Expose the group singleton. */ module.exports = bind.all(new Group()); /** * Expose the `Group` constructor. */ module.exports.Group = Group; }, {"./entity":37,"debug":15,"inherit":38,"bind":11}], 37: [function(require, module, exports) { var traverse = require('isodate-traverse'); var defaults = require('defaults'); var cookie = require('./cookie'); var store = require('./store'); var extend = require('extend'); var clone = require('clone'); /** * Expose `Entity` */ module.exports = Entity; /** * Initialize new `Entity` with `options`. * * @param {Object} options */ function Entity(options){ this.options(options); } /** * Get or set storage `options`. * * @param {Object} options * @property {Object} cookie * @property {Object} localStorage * @property {Boolean} persist (default: `true`) */ Entity.prototype.options = function (options) { if (arguments.length === 0) return this._options; options || (options = {}); defaults(options, this.defaults || {}); this._options = options; }; /** * Get or set the entity's `id`. * * @param {String} id */ Entity.prototype.id = function (id) { switch (arguments.length) { case 0: return this._getId(); case 1: return this._setId(id); } }; /** * Get the entity's id. * * @return {String} */ Entity.prototype._getId = function () { var ret = this._options.persist ? cookie.get(this._options.cookie.key) : this._id; return ret === undefined ? null : ret; }; /** * Set the entity's `id`. * * @param {String} id */ Entity.prototype._setId = function (id) { if (this._options.persist) { cookie.set(this._options.cookie.key, id); } else { this._id = id; } }; /** * Get or set the entity's `traits`. * * BACKWARDS COMPATIBILITY: aliased to `properties` * * @param {Object} traits */ Entity.prototype.properties = Entity.prototype.traits = function (traits) { switch (arguments.length) { case 0: return this._getTraits(); case 1: return this._setTraits(traits); } }; /** * Get the entity's traits. Always convert ISO date strings into real dates, * since they aren't parsed back from local storage. * * @return {Object} */ Entity.prototype._getTraits = function () { var ret = this._options.persist ? store.get(this._options.localStorage.key) : this._traits; return ret ? traverse(clone(ret)) : {}; }; /** * Set the entity's `traits`. * * @param {Object} traits */ Entity.prototype._setTraits = function (traits) { traits || (traits = {}); if (this._options.persist) { store.set(this._options.localStorage.key, traits); } else { this._traits = traits; } }; /** * Identify the entity with an `id` and `traits`. If we it's the same entity, * extend the existing `traits` instead of overwriting. * * @param {String} id * @param {Object} traits */ Entity.prototype.identify = function (id, traits) { traits || (traits = {}); var current = this.id(); if (current === null || current === id) traits = extend(this.traits(), traits); if (id) this.id(id); this.debug('identify %o, %o', id, traits); this.traits(traits); this.save(); }; /** * Save the entity to local storage and the cookie. * * @return {Boolean} */ Entity.prototype.save = function () { if (!this._options.persist) return false; cookie.set(this._options.cookie.key, this.id()); store.set(this._options.localStorage.key, this.traits()); return true; }; /** * Log the entity out, reseting `id` and `traits` to defaults. */ Entity.prototype.logout = function () { this.id(null); this.traits({}); cookie.remove(this._options.cookie.key); store.remove(this._options.localStorage.key); }; /** * Reset all entity state, logging out and returning options to defaults. */ Entity.prototype.reset = function () { this.logout(); this.options({}); }; /** * Load saved entity `id` or `traits` from storage. */ Entity.prototype.load = function () { this.id(cookie.get(this._options.cookie.key)); this.traits(store.get(this._options.localStorage.key)); }; }, {"./cookie":6,"./store":8,"isodate-traverse":39,"defaults":16,"extend":40,"clone":14}], 8: [function(require, module, exports) { var bind = require('bind'); var defaults = require('defaults'); var store = require('store.js'); /** * Initialize a new `Store` with `options`. * * @param {Object} options */ function Store (options) { this.options(options); } /** * Set the `options` for the store. * * @param {Object} options * @field {Boolean} enabled (true) */ Store.prototype.options = function (options) { if (arguments.length === 0) return this._options; options = options || {}; defaults(options, { enabled : true }); this.enabled = options.enabled && store.enabled; this._options = options; }; /** * Set a `key` and `value` in local storage. * * @param {String} key * @param {Object} value */ Store.prototype.set = function (key, value) { if (!this.enabled) return false; return store.set(key, value); }; /** * Get a value from local storage by `key`. * * @param {String} key * @return {Object} */ Store.prototype.get = function (key) { if (!this.enabled) return null; return store.get(key); }; /** * Remove a value from local storage by `key`. * * @param {String} key */ Store.prototype.remove = function (key) { if (!this.enabled) return false; return store.remove(key); }; /** * Expose the store singleton. */ module.exports = bind.all(new Store()); /** * Expose the `Store` constructor. */ module.exports.Store = Store; }, {"bind":11,"defaults":16,"store.js":41}], 41: [function(require, module, exports) { var json = require('json') , store = {} , win = window , doc = win.document , localStorageName = 'localStorage' , namespace = '__storejs__' , storage; store.disabled = false store.set = function(key, value) {} store.get = function(key) {} store.remove = function(key) {} store.clear = function() {} store.transact = function(key, defaultVal, transactionFn) { var val = store.get(key) if (transactionFn == null) { transactionFn = defaultVal defaultVal = null } if (typeof val == 'undefined') { val = defaultVal || {} } transactionFn(val) store.set(key, val) } store.getAll = function() {} store.serialize = function(value) { return json.stringify(value) } store.deserialize = function(value) { if (typeof value != 'string') { return undefined } try { return json.parse(value) } catch(e) { return value || undefined } } // Functions to encapsulate questionable FireFox 3.6.13 behavior // when about.config::dom.storage.enabled === false // See https://github.com/marcuswestin/store.js/issues#issue/13 function isLocalStorageNameSupported() { try { return (localStorageName in win && win[localStorageName]) } catch(err) { return false } } if (isLocalStorageNameSupported()) { storage = win[localStorageName] store.set = function(key, val) { if (val === undefined) { return store.remove(key) } storage.setItem(key, store.serialize(val)) return val } store.get = function(key) { return store.deserialize(storage.getItem(key)) } store.remove = function(key) { storage.removeItem(key) } store.clear = function() { storage.clear() } store.getAll = function() { var ret = {} for (var i=0; i<storage.length; ++i) { var key = storage.key(i) ret[key] = store.get(key) } return ret } } else if (doc.documentElement.addBehavior) { var storageOwner, storageContainer // Since #userData storage applies only to specific paths, we need to // somehow link our data to a specific path. We choose /favicon.ico // as a pretty safe option, since all browsers already make a request to // this URL anyway and being a 404 will not hurt us here. We wrap an // iframe pointing to the favicon in an ActiveXObject(htmlfile) object // (see: http://msdn.microsoft.com/en-us/library/aa752574(v=VS.85).aspx) // since the iframe access rules appear to allow direct access and // manipulation of the document element, even for a 404 page. This // document can be used instead of the current document (which would // have been limited to the current path) to perform #userData storage. try { storageContainer = new ActiveXObject('htmlfile') storageContainer.open() storageContainer.write('<s' + 'cript>document.w=window</s' + 'cript><iframe src="/favicon.ico"></iframe>') storageContainer.close() storageOwner = storageContainer.w.frames[0].document storage = storageOwner.createElement('div') } catch(e) { // somehow ActiveXObject instantiation failed (perhaps some special // security settings or otherwse), fall back to per-path storage storage = doc.createElement('div') storageOwner = doc.body } function withIEStorage(storeFunction) { return function() { var args = Array.prototype.slice.call(arguments, 0) args.unshift(storage) // See http://msdn.microsoft.com/en-us/library/ms531081(v=VS.85).aspx // and http://msdn.microsoft.com/en-us/library/ms531424(v=VS.85).aspx storageOwner.appendChild(storage) storage.addBehavior('#default#userData') storage.load(localStorageName) var result = storeFunction.apply(store, args) storageOwner.removeChild(storage) return result } } // In IE7, keys may not contain special chars. See all of https://github.com/marcuswestin/store.js/issues/40 var forbiddenCharsRegex = new RegExp("[!\"#$%&'()*+,/\\\\:;<=>?@[\\]^`{|}~]", "g") function ieKeyFix(key) { return key.replace(forbiddenCharsRegex, '___') } store.set = withIEStorage(function(storage, key, val) { key = ieKeyFix(key) if (val === undefined) { return store.remove(key) } storage.setAttribute(key, store.serialize(val)) storage.save(localStorageName) return val }) store.get = withIEStorage(function(storage, key) { key = ieKeyFix(key) return store.deserialize(storage.getAttribute(key)) }) store.remove = withIEStorage(function(storage, key) { key = ieKeyFix(key) storage.removeAttribute(key) storage.save(localStorageName) }) store.clear = withIEStorage(function(storage) { var attributes = storage.XMLDocument.documentElement.attributes storage.load(localStorageName) for (var i=0, attr; attr=attributes[i]; i++) { storage.removeAttribute(attr.name) } storage.save(localStorageName) }) store.getAll = withIEStorage(function(storage) { var attributes = storage.XMLDocument.documentElement.attributes var ret = {} for (var i=0, attr; attr=attributes[i]; ++i) { var key = ieKeyFix(attr.name) ret[attr.name] = store.deserialize(storage.getAttribute(key)) } return ret }) } try { store.set(namespace, namespace) if (store.get(namespace) != namespace) { store.disabled = true } store.remove(namespace) } catch(e) { store.disabled = true } store.enabled = !store.disabled module.exports = store; }, {"json":29}], 39: [function(require, module, exports) { var is = require('is'); var isodate = require('isodate'); var each; try { each = require('each'); } catch (err) { each = require('each-component'); } /** * Expose `traverse`. */ module.exports = traverse; /** * Traverse an object or array, and return a clone with all ISO strings parsed * into Date objects. * * @param {Object} obj * @return {Object} */ function traverse (input, strict) { if (strict === undefined) strict = true; if (is.object(input)) return object(input, strict); if (is.array(input)) return array(input, strict); return input; } /** * Object traverser. * * @param {Object} obj * @param {Boolean} strict * @return {Object} */ function object (obj, strict) { each(obj, function (key, val) { if (isodate.is(val, strict)) { obj[key] = isodate.parse(val); } else if (is.object(val) || is.array(val)) { traverse(val, strict); } }); return obj; } /** * Array traverser. * * @param {Array} arr * @param {Boolean} strict * @return {Array} */ function array (arr, strict) { each(arr, function (val, x) { if (is.object(val)) { traverse(val, strict); } else if (isodate.is(val, strict)) { arr[x] = isodate.parse(val); } }); return arr; } }, {"is":42,"isodate":43,"each":5}], 42: [function(require, module, exports) { var isEmpty = require('is-empty'); try { var typeOf = require('type'); } catch (e) { var typeOf = require('component-type'); } /** * Types. */ var types = [ 'arguments', 'array', 'boolean', 'date', 'element', 'function', 'null', 'number', 'object', 'regexp', 'string', 'undefined' ]; /** * Expose type checkers. * * @param {Mixed} value * @return {Boolean} */ for (var i = 0, type; type = types[i]; i++) exports[type] = generate(type); /** * Add alias for `function` for old browsers. */ exports.fn = exports['function']; /** * Expose `empty` check. */ exports.empty = isEmpty; /** * Expose `nan` check. */ exports.nan = function (val) { return exports.number(val) && val != val; }; /** * Generate a type checker. * * @param {String} type * @return {Function} */ function generate (type) { return function (value) { return type === typeOf(value); }; } }, {"is-empty":44,"type":35,"component-type":35}], 44: [function(require, module, exports) { /** * Expose `isEmpty`. */ module.exports = isEmpty; /** * Has. */ var has = Object.prototype.hasOwnProperty; /** * Test whether a value is "empty". * * @param {Mixed} val * @return {Boolean} */ function isEmpty (val) { if (null == val) return true; if ('number' == typeof val) return 0 === val; if (undefined !== val.length) return 0 === val.length; for (var key in val) if (has.call(val, key)) return false; return true; } }, {}], 43: [function(require, module, exports) { /** * Matcher, slightly modified from: * * https://github.com/csnover/js-iso8601/blob/lax/iso8601.js */ var matcher = /^(\d{4})(?:-?(\d{2})(?:-?(\d{2}))?)?(?:([ T])(\d{2}):?(\d{2})(?::?(\d{2})(?:[,\.](\d{1,}))?)?(?:(Z)|([+\-])(\d{2})(?::?(\d{2}))?)?)?$/; /** * Convert an ISO date string to a date. Fallback to native `Date.parse`. * * https://github.com/csnover/js-iso8601/blob/lax/iso8601.js * * @param {String} iso * @return {Date} */ exports.parse = function (iso) { var numericKeys = [1, 5, 6, 7, 11, 12]; var arr = matcher.exec(iso); var offset = 0; // fallback to native parsing if (!arr) return new Date(iso); // remove undefined values for (var i = 0, val; val = numericKeys[i]; i++) { arr[val] = parseInt(arr[val], 10) || 0; } // allow undefined days and months arr[2] = parseInt(arr[2], 10) || 1; arr[3] = parseInt(arr[3], 10) || 1; // month is 0-11 arr[2]--; // allow abitrary sub-second precision arr[8] = arr[8] ? (arr[8] + '00').substring(0, 3) : 0; // apply timezone if one exists if (arr[4] == ' ') { offset = new Date().getTimezoneOffset(); } else if (arr[9] !== 'Z' && arr[10]) { offset = arr[11] * 60 + arr[12]; if ('+' == arr[10]) offset = 0 - offset; } var millis = Date.UTC(arr[1], arr[2], arr[3], arr[5], arr[6] + offset, arr[7], arr[8]); return new Date(millis); }; /** * Checks whether a `string` is an ISO date string. `strict` mode requires that * the date string at least have a year, month and date. * * @param {String} string * @param {Boolean} strict * @return {Boolean} */ exports.is = function (string, strict) { if (strict && false === /^\d{4}-\d{2}-\d{2}/.test(string)) return false; return matcher.test(string); }; }, {}], 5: [function(require, module, exports) { /** * Module dependencies. */ var type = require('type'); /** * HOP reference. */ var has = Object.prototype.hasOwnProperty; /** * Iterate the given `obj` and invoke `fn(val, i)`. * * @param {String|Array|Object} obj * @param {Function} fn * @api public */ module.exports = function(obj, fn){ switch (type(obj)) { case 'array': return array(obj, fn); case 'object': if ('number' == typeof obj.length) return array(obj, fn); return object(obj, fn); case 'string': return string(obj, fn); } }; /** * Iterate string chars. * * @param {String} obj * @param {Function} fn * @api private */ function string(obj, fn) { for (var i = 0; i < obj.length; ++i) { fn(obj.charAt(i), i); } } /** * Iterate object keys. * * @param {Object} obj * @param {Function} fn * @api private */ function object(obj, fn) { for (var key in obj) { if (has.call(obj, key)) { fn(key, obj[key]); } } } /** * Iterate array-ish. * * @param {Array|Object} obj * @param {Function} fn * @api private */ function array(obj, fn) { for (var i = 0; i < obj.length; ++i) { fn(obj[i], i); } } }, {"type":35}], 40: [function(require, module, exports) { module.exports = function extend (object) { // Takes an unlimited number of extenders. var args = Array.prototype.slice.call(arguments, 1); // For each extender, copy their properties on our object. for (var i = 0, source; source = args[i]; i++) { if (!source) continue; for (var property in source) { object[property] = source[property]; } } return object; }; }, {}], 38: [function(require, module, exports) { module.exports = function(a, b){ var fn = function(){}; fn.prototype = b.prototype; a.prototype = new fn; a.prototype.constructor = a; }; }, {}], 9: [function(require, module, exports) { var debug = require('debug')('analytics:user'); var Entity = require('./entity'); var inherit = require('inherit'); var bind = require('bind'); var cookie = require('./cookie'); /** * User defaults */ User.defaults = { persist: true, cookie: { key: 'ajs_user_id', oldKey: 'ajs_user' }, localStorage: { key: 'ajs_user_traits' } }; /** * Initialize a new `User` with `options`. * * @param {Object} options */ function User (options) { this.defaults = User.defaults; this.debug = debug; Entity.call(this, options); } /** * Inherit `Entity` */ inherit(User, Entity); /** * Load saved user `id` or `traits` from storage. */ User.prototype.load = function () { if (this._loadOldCookie()) return; Entity.prototype.load.call(this); }; /** * BACKWARDS COMPATIBILITY: Load the old user from the cookie. * * @return {Boolean} * @api private */ User.prototype._loadOldCookie = function () { var user = cookie.get(this._options.cookie.oldKey); if (!user) return false; this.id(user.id); this.traits(user.traits); cookie.remove(this._options.cookie.oldKey); return true; }; /** * Expose the user singleton. */ module.exports = bind.all(new User()); /** * Expose the `User` constructor. */ module.exports.User = User; }, {"./entity":37,"./cookie":6,"debug":15,"inherit":38,"bind":11}], 10: [function(require, module, exports) { module.exports = function after (times, func) { // After 0, really? if (times <= 0) return func(); // That's more like it. return function() { if (--times < 1) { return func.apply(this, arguments); } }; }; }, {}], 12: [function(require, module, exports) { var next = require('next-tick'); /** * Expose `callback`. */ module.exports = callback; /** * Call an `fn` back synchronously if it exists. * * @param {Function} fn */ function callback (fn) { if ('function' === typeof fn) fn(); } /** * Call an `fn` back asynchronously if it exists. If `wait` is ommitted, the * `fn` will be called on next tick. * * @param {Function} fn * @param {Number} wait (optional) */ callback.async = function (fn, wait) { if ('function' !== typeof fn) return; if (!wait) return next(fn); setTimeout(fn, wait); }; /** * Symmetry. */ callback.sync = callback; }, {"next-tick":45}], 45: [function(require, module, exports) { "use strict" if (typeof setImmediate == 'function') { module.exports = function(f){ setImmediate(f) } } // legacy node.js else if (typeof process != 'undefined' && typeof process.nextTick == 'function') { module.exports = process.nextTick } // fallback for other environments / postMessage behaves badly on IE8 else if (typeof window == 'undefined' || window.ActiveXObject || !window.postMessage) { module.exports = function(f){ setTimeout(f) }; } else { var q = []; window.addEventListener('message', function(){ var i = 0; while (i < q.length) { try { q[i++](); } catch (e) { q = q.slice(i); window.postMessage('tic!', '*'); throw e; } } q.length = 0; }, true); module.exports = function(fn){ if (!q.length) window.postMessage('tic!', '*'); q.push(fn); } } }, {}], 13: [function(require, module, exports) { module.exports = function canonical () { var tags = document.getElementsByTagName('link'); for (var i = 0, tag; tag = tags[i]; i++) { if ('canonical' == tag.getAttribute('rel')) return tag.getAttribute('href'); } }; }, {}], 17: [function(require, module, exports) { /** * Module dependencies. */ var index = require('indexof'); /** * Expose `Emitter`. */ module.exports = Emitter; /** * Initialize a new `Emitter`. * * @api public */ function Emitter(obj) { if (obj) return mixin(obj); }; /** * Mixin the emitter properties. * * @param {Object} obj * @return {Object} * @api private */ function mixin(obj) { for (var key in Emitter.prototype) { obj[key] = Emitter.prototype[key]; } return obj; } /** * Listen on the given `event` with `fn`. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.on = Emitter.prototype.addEventListener = function(event, fn){ this._callbacks = this._callbacks || {}; (this._callbacks[event] = this._callbacks[event] || []) .push(fn); return this; }; /** * Adds an `event` listener that will be invoked a single * time then automatically removed. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.once = function(event, fn){ var self = this; this._callbacks = this._callbacks || {}; function on() { self.off(event, on); fn.apply(this, arguments); } fn._off = on; this.on(event, on); return this; }; /** * Remove the given callback for `event` or all * registered callbacks. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.off = Emitter.prototype.removeListener = Emitter.prototype.removeAllListeners = Emitter.prototype.removeEventListener = function(event, fn){ this._callbacks = this._callbacks || {}; // all if (0 == arguments.length) { this._callbacks = {}; return this; } // specific event var callbacks = this._callbacks[event]; if (!callbacks) return this; // remove all handlers if (1 == arguments.length) { delete this._callbacks[event]; return this; } // remove specific handler var i = index(callbacks, fn._off || fn); if (~i) callbacks.splice(i, 1); return this; }; /** * Emit `event` with the given args. * * @param {String} event * @param {Mixed} ... * @return {Emitter} */ Emitter.prototype.emit = function(event){ this._callbacks = this._callbacks || {}; var args = [].slice.call(arguments, 1) , callbacks = this._callbacks[event]; if (callbacks) { callbacks = callbacks.slice(0); for (var i = 0, len = callbacks.length; i < len; ++i) { callbacks[i].apply(this, args); } } return this; }; /** * Return array of callbacks for `event`. * * @param {String} event * @return {Array} * @api public */ Emitter.prototype.listeners = function(event){ this._callbacks = this._callbacks || {}; return this._callbacks[event] || []; }; /** * Check if this emitter has `event` handlers. * * @param {String} event * @return {Boolean} * @api public */ Emitter.prototype.hasListeners = function(event){ return !! this.listeners(event).length; }; }, {"indexof":46}], 46: [function(require, module, exports) { module.exports = function(arr, obj){ if (arr.indexOf) return arr.indexOf(obj); for (var i = 0; i < arr.length; ++i) { if (arr[i] === obj) return i; } return -1; }; }, {}], 18: [function(require, module, exports) { var isEmpty = require('is-empty'); try { var typeOf = require('type'); } catch (e) { var typeOf = require('component-type'); } /** * Types. */ var types = [ 'arguments', 'array', 'boolean', 'date', 'element', 'function', 'null', 'number', 'object', 'regexp', 'string', 'undefined' ]; /** * Expose type checkers. * * @param {Mixed} value * @return {Boolean} */ for (var i = 0, type; type = types[i]; i++) exports[type] = generate(type); /** * Add alias for `function` for old browsers. */ exports.fn = exports['function']; /** * Expose `empty` check. */ exports.empty = isEmpty; /** * Expose `nan` check. */ exports.nan = function (val) { return exports.number(val) && val != val; }; /** * Generate a type checker. * * @param {String} type * @return {Function} */ function generate (type) { return function (value) { return type === typeOf(value); }; } }, {"is-empty":44,"type":35,"component-type":35}], 19: [function(require, module, exports) { /** * Expose `isEmail`. */ module.exports = isEmail; /** * Email address matcher. */ var matcher = /.+\@.+\..+/; /** * Loosely validate an email address. * * @param {String} string * @return {Boolean} */ function isEmail (string) { return matcher.test(string); } }, {}], 20: [function(require, module, exports) { module.exports = function isMeta (e) { if (e.metaKey || e.altKey || e.ctrlKey || e.shiftKey) return true; // Logic that handles checks for the middle mouse button, based // on [jQuery](https://github.com/jquery/jquery/blob/master/src/event.js#L466). var which = e.which, button = e.button; if (!which && button !== undefined) { return (!button & 1) && (!button & 2) && (button & 4); } else if (which === 2) { return true; } return false; }; }, {}], 21: [function(require, module, exports) { var is = require('is'); var isodate = require('isodate'); var milliseconds = require('./milliseconds'); var seconds = require('./seconds'); /** * Returns a new Javascript Date object, allowing a variety of extra input types * over the native Date constructor. * * @param {Date|String|Number} val */ module.exports = function newDate (val) { if (is.date(val)) return val; if (is.number(val)) return new Date(toMs(val)); // date strings if (isodate.is(val)) return isodate.parse(val); if (milliseconds.is(val)) return milliseconds.parse(val); if (seconds.is(val)) return seconds.parse(val); // fallback to Date.parse return new Date(val); }; /** * If the number passed val is seconds from the epoch, turn it into milliseconds. * Milliseconds would be greater than 31557600000 (December 31, 1970). * * @param {Number} num */ function toMs (num) { if (num < 31557600000) return num * 1000; return num; } }, {"./milliseconds":47,"./seconds":48,"is":49,"isodate":43}], 47: [function(require, module, exports) { /** * Matcher. */ var matcher = /\d{13}/; /** * Check whether a string is a millisecond date string. * * @param {String} string * @return {Boolean} */ exports.is = function (string) { return matcher.test(string); }; /** * Convert a millisecond string to a date. * * @param {String} millis * @return {Date} */ exports.parse = function (millis) { millis = parseInt(millis, 10); return new Date(millis); }; }, {}], 48: [function(require, module, exports) { /** * Matcher. */ var matcher = /\d{10}/; /** * Check whether a string is a second date string. * * @param {String} string * @return {Boolean} */ exports.is = function (string) { return matcher.test(string); }; /** * Convert a second string to a date. * * @param {String} seconds * @return {Date} */ exports.parse = function (seconds) { var millis = parseInt(seconds, 10) * 1000; return new Date(millis); }; }, {}], 49: [function(require, module, exports) { var isEmpty = require('is-empty') , typeOf = require('type'); /** * Types. */ var types = [ 'arguments', 'array', 'boolean', 'date', 'element', 'function', 'null', 'number', 'object', 'regexp', 'string', 'undefined' ]; /** * Expose type checkers. * * @param {Mixed} value * @return {Boolean} */ for (var i = 0, type; type = types[i]; i++) exports[type] = generate(type); /** * Add alias for `function` for old browsers. */ exports.fn = exports['function']; /** * Expose `empty` check. */ exports.empty = isEmpty; /** * Expose `nan` check. */ exports.nan = function (val) { return exports.number(val) && val != val; }; /** * Generate a type checker. * * @param {String} type * @return {Function} */ function generate (type) { return function (value) { return type === typeOf(value); }; } }, {"is-empty":44,"type":35}], 22: [function(require, module, exports) { /** * Bind `el` event `type` to `fn`. * * @param {Element} el * @param {String} type * @param {Function} fn * @param {Boolean} capture * @return {Function} * @api public */ exports.bind = function(el, type, fn, capture){ if (el.addEventListener) { el.addEventListener(type, fn, capture || false); } else { el.attachEvent('on' + type, fn); } return fn; }; /** * Unbind `el` event `type`'s callback `fn`. * * @param {Element} el * @param {String} type * @param {Function} fn * @param {Boolean} capture * @return {Function} * @api public */ exports.unbind = function(el, type, fn, capture){ if (el.removeEventListener) { el.removeEventListener(type, fn, capture || false); } else { el.detachEvent('on' + type, fn); } return fn; }; }, {}], 23: [function(require, module, exports) { /** * prevent default on the given `e`. * * examples: * * anchor.onclick = prevent; * anchor.onclick = function(e){ * if (something) return prevent(e); * }; * * @param {Event} e */ module.exports = function(e){ e = e || window.event return e.preventDefault ? e.preventDefault() : e.returnValue = false; }; }, {}], 24: [function(require, module, exports) { /** * Module dependencies. */ var encode = encodeURIComponent; var decode = decodeURIComponent; var trim = require('trim'); var type = require('type'); /** * Parse the given query `str`. * * @param {String} str * @return {Object} * @api public */ exports.parse = function(str){ if ('string' != typeof str) return {}; str = trim(str); if ('' == str) return {}; if ('?' == str.charAt(0)) str = str.slice(1); var obj = {}; var pairs = str.split('&'); for (var i = 0; i < pairs.length; i++) { var parts = pairs[i].split('='); var key = decode(parts[0]); var m; if (m = /(\w+)\[(\d+)\]/.exec(key)) { obj[m[1]] = obj[m[1]] || []; obj[m[1]][m[2]] = decode(parts[1]); continue; } obj[parts[0]] = null == parts[1] ? '' : decode(parts[1]); } return obj; }; /** * Stringify the given `obj`. * * @param {Object} obj * @return {String} * @api public */ exports.stringify = function(obj){ if (!obj) return ''; var pairs = []; for (var key in obj) { var value = obj[key]; if ('array' == type(value)) { for (var i = 0; i < value.length; ++i) { pairs.push(encode(key + '[' + i + ']') + '=' + encode(value[i])); } continue; } pairs.push(encode(key) + '=' + encode(obj[key])); } return pairs.join('&'); }; }, {"trim":50,"type":35}], 50: [function(require, module, exports) { exports = module.exports = trim; function trim(str){ if (str.trim) return str.trim(); return str.replace(/^\s*|\s*$/g, ''); } exports.left = function(str){ if (str.trimLeft) return str.trimLeft(); return str.replace(/^\s*/, ''); }; exports.right = function(str){ if (str.trimRight) return str.trimRight(); return str.replace(/\s*$/, ''); }; }, {}], 25: [function(require, module, exports) { /** * HOP ref. */ var has = Object.prototype.hasOwnProperty; /** * Return own keys in `obj`. * * @param {Object} obj * @return {Array} * @api public */ exports.keys = Object.keys || function(obj){ var keys = []; for (var key in obj) { if (has.call(obj, key)) { keys.push(key); } } return keys; }; /** * Return own values in `obj`. * * @param {Object} obj * @return {Array} * @api public */ exports.values = function(obj){ var vals = []; for (var key in obj) { if (has.call(obj, key)) { vals.push(obj[key]); } } return vals; }; /** * Merge `b` into `a`. * * @param {Object} a * @param {Object} b * @return {Object} a * @api public */ exports.merge = function(a, b){ for (var key in b) { if (has.call(b, key)) { a[key] = b[key]; } } return a; }; /** * Return length of `obj`. * * @param {Object} obj * @return {Number} * @api public */ exports.length = function(obj){ return exports.keys(obj).length; }; /** * Check if `obj` is empty. * * @param {Object} obj * @return {Boolean} * @api public */ exports.isEmpty = function(obj){ return 0 == exports.length(obj); }; }, {}], 27: [function(require, module, exports) { var Facade = require('./facade'); /** * Expose `Facade` facade. */ module.exports = Facade; /** * Expose specific-method facades. */ Facade.Alias = require('./alias'); Facade.Group = require('./group'); Facade.Identify = require('./identify'); Facade.Track = require('./track'); Facade.Page = require('./page'); Facade.Screen = require('./screen'); }, {"./facade":51,"./alias":52,"./group":53,"./identify":54,"./track":55,"./page":56,"./screen":57}], 51: [function(require, module, exports) { var clone = require('./utils').clone; var isEnabled = require('./is-enabled'); var objCase = require('obj-case'); var traverse = require('isodate-traverse'); var newDate = require('new-date'); /** * Expose `Facade`. */ module.exports = Facade; /** * Initialize a new `Facade` with an `obj` of arguments. * * @param {Object} obj */ function Facade (obj) { if (!obj.hasOwnProperty('timestamp')) obj.timestamp = new Date(); else obj.timestamp = newDate(obj.timestamp); this.obj = obj; } /** * Return a proxy function for a `field` that will attempt to first use methods, * and fallback to accessing the underlying object directly. You can specify * deeply nested fields too like: * * this.proxy('options.Librato'); * * @param {String} field */ Facade.prototype.proxy = function (field) { var fields = field.split('.'); field = fields.shift(); // Call a function at the beginning to take advantage of facaded fields var obj = this[field] || this.field(field); if (!obj) return obj; if (typeof obj === 'function') obj = obj.call(this) || {}; if (fields.length === 0) return transform(obj); obj = objCase(obj, fields.join('.')); return transform(obj); }; /** * Directly access a specific `field` from the underlying object, returning a * clone so outsiders don't mess with stuff. * * @param {String} field * @return {Mixed} */ Facade.prototype.field = function (field) { var obj = this.obj[field]; return transform(obj); }; /** * Utility method to always proxy a particular `field`. You can specify deeply * nested fields too like: * * Facade.proxy('options.Librato'); * * @param {String} field * @return {Function} */ Facade.proxy = function (field) { return function () { return this.proxy(field); }; }; /** * Utility method to directly access a `field`. * * @param {String} field * @return {Function} */ Facade.field = function (field) { return function () { return this.field(field); }; }; /** * Get the basic json object of this facade. * * @return {Object} */ Facade.prototype.json = function () { var ret = clone(this.obj); if (this.type) ret.type = this.type(); return ret; }; /** * Get the options of a call (formerly called "context"). If you pass an * integration name, it will get the options for that specific integration, or * undefined if the integration is not enabled. * * @param {String} integration (optional) * @return {Object or Null} */ Facade.prototype.context = Facade.prototype.options = function (integration) { var options = clone(this.obj.options || this.obj.context) || {}; if (!integration) return clone(options); if (!this.enabled(integration)) return; var integrations = this.integrations(); var value = integrations[integration] || objCase(integrations, integration); if ('boolean' == typeof value) value = {}; return value || {}; }; /** * Check whether an integration is enabled. * * @param {String} integration * @return {Boolean} */ Facade.prototype.enabled = function (integration) { var allEnabled = this.proxy('options.providers.all'); if (typeof allEnabled !== 'boolean') allEnabled = this.proxy('options.all'); if (typeof allEnabled !== 'boolean') allEnabled = this.proxy('integrations.all'); if (typeof allEnabled !== 'boolean') allEnabled = true; var enabled = allEnabled && isEnabled(integration); var options = this.integrations(); // If the integration is explicitly enabled or disabled, use that // First, check options.providers for backwards compatibility if (options.providers && options.providers.hasOwnProperty(integration)) { enabled = options.providers[integration]; } // Next, check for the integration's existence in 'options' to enable it. // If the settings are a boolean, use that, otherwise it should be enabled. if (options.hasOwnProperty(integration)) { var settings = options[integration]; if (typeof settings === 'boolean') { enabled = settings; } else { enabled = true; } } return enabled ? true : false; }; /** * Get all `integration` options. * * @param {String} integration * @return {Object} * @api private */ Facade.prototype.integrations = function(){ return this.obj.integrations || this.proxy('options.providers') || this.options(); }; /** * Check whether the user is active. * * @return {Boolean} */ Facade.prototype.active = function () { var active = this.proxy('options.active'); if (active === null || active === undefined) active = true; return active; }; /** * Get `sessionId / anonymousId`. * * @return {Mixed} * @api public */ Facade.prototype.sessionId = Facade.prototype.anonymousId = function(){ return this.field('anonymousId') || this.field('sessionId'); }; /** * Get `groupId` from `context.groupId`. * * @return {String} * @api public */ Facade.prototype.groupId = Facade.proxy('options.groupId'); /** * Get the call's "super properties" which are just traits that have been * passed in as if from an identify call. * * @param {Object} aliases * @return {Object} */ Facade.prototype.traits = function (aliases) { var ret = this.proxy('options.traits') || {}; var id = this.userId(); aliases = aliases || {}; if (id) ret.id = id; for (var alias in aliases) { var value = null == this[alias] ? this.proxy('options.traits.' + alias) : this[alias](); if (null == value) continue; ret[aliases[alias]] = value; delete ret[alias]; } return ret; }; /** * Add a convenient way to get the library name and version */ Facade.prototype.library = function(){ var library = this.proxy('options.library'); if (!library) return { name: 'unknown', version: null }; if (typeof library === 'string') return { name: library, version: null }; return library; }; /** * Setup some basic proxies. */ Facade.prototype.userId = Facade.field('userId'); Facade.prototype.channel = Facade.field('channel'); Facade.prototype.timestamp = Facade.field('timestamp'); Facade.prototype.userAgent = Facade.proxy('options.userAgent'); Facade.prototype.ip = Facade.proxy('options.ip'); /** * Return the cloned and traversed object * * @param {Mixed} obj * @return {Mixed} */ function transform(obj){ var cloned = clone(obj); traverse(cloned); return cloned; } }, {"./utils":58,"./is-enabled":59,"obj-case":60,"isodate-traverse":39,"new-date":21}], 58: [function(require, module, exports) { /** * TODO: use component symlink, everywhere ? */ try { exports.inherit = require('inherit'); exports.clone = require('clone'); } catch (e) { exports.inherit = require('inherit-component'); exports.clone = require('clone-component'); } }, {"inherit":61,"clone":62}], 61: [function(require, module, exports) { module.exports = function(a, b){ var fn = function(){}; fn.prototype = b.prototype; a.prototype = new fn; a.prototype.constructor = a; }; }, {}], 62: [function(require, module, exports) { /** * Module dependencies. */ var type; try { type = require('component-type'); } catch (_) { type = require('type'); } /** * Module exports. */ module.exports = clone; /** * Clones objects. * * @param {Mixed} any object * @api public */ function clone(obj){ switch (type(obj)) { case 'object': var copy = {}; for (var key in obj) { if (obj.hasOwnProperty(key)) { copy[key] = clone(obj[key]); } } return copy; case 'array': var copy = new Array(obj.length); for (var i = 0, l = obj.length; i < l; i++) { copy[i] = clone(obj[i]); } return copy; case 'regexp': // from millermedeiros/amd-utils - MIT var flags = ''; flags += obj.multiline ? 'm' : ''; flags += obj.global ? 'g' : ''; flags += obj.ignoreCase ? 'i' : ''; return new RegExp(obj.source, flags); case 'date': return new Date(obj.getTime()); default: // string, number, boolean, … return obj; } } }, {"component-type":35,"type":35}], 59: [function(require, module, exports) { /** * A few integrations are disabled by default. They must be explicitly * enabled by setting options[Provider] = true. */ var disabled = { Salesforce: true, Marketo: true }; /** * Check whether an integration should be enabled by default. * * @param {String} integration * @return {Boolean} */ module.exports = function (integration) { return ! disabled[integration]; }; }, {}], 60: [function(require, module, exports) { var Case = require('case'); var identity = function(_){ return _; }; /** * Cases */ var cases = [ identity, Case.upper, Case.lower, Case.snake, Case.pascal, Case.camel, Case.constant, Case.title, Case.capital, Case.sentence ]; /** * Module exports, export */ module.exports = module.exports.find = multiple(find); /** * Export the replacement function, return the modified object */ module.exports.replace = function (obj, key, val) { multiple(replace).apply(this, arguments); return obj; }; /** * Export the delete function, return the modified object */ module.exports.del = function (obj, key) { multiple(del).apply(this, arguments); return obj; }; /** * Compose applying the function to a nested key */ function multiple (fn) { return function (obj, key, val) { var keys = key.split('.'); if (keys.length === 0) return; while (keys.length > 1) { key = keys.shift(); obj = find(obj, key); if (obj === null || obj === undefined) return; } key = keys.shift(); return fn(obj, key, val); }; } /** * Find an object by its key * * find({ first_name : 'Calvin' }, 'firstName') */ function find (obj, key) { for (var i = 0; i < cases.length; i++) { var cased = cases[i](key); if (obj.hasOwnProperty(cased)) return obj[cased]; } } /** * Delete a value for a given key * * del({ a : 'b', x : 'y' }, 'X' }) -> { a : 'b' } */ function del (obj, key) { for (var i = 0; i < cases.length; i++) { var cased = cases[i](key); if (obj.hasOwnProperty(cased)) delete obj[cased]; } return obj; } /** * Replace an objects existing value with a new one * * replace({ a : 'b' }, 'a', 'c') -> { a : 'c' } */ function replace (obj, key, val) { for (var i = 0; i < cases.length; i++) { var cased = cases[i](key); if (obj.hasOwnProperty(cased)) obj[cased] = val; } return obj; } }, {"case":63}], 63: [function(require, module, exports) { var cases = require('./cases'); /** * Expose `determineCase`. */ module.exports = exports = determineCase; /** * Determine the case of a `string`. * * @param {String} string * @return {String|Null} */ function determineCase (string) { for (var key in cases) { if (key == 'none') continue; var convert = cases[key]; if (convert(string) == string) return key; } return null; } /** * Define a case by `name` with a `convert` function. * * @param {String} name * @param {Object} convert */ exports.add = function (name, convert) { exports[name] = cases[name] = convert; }; /** * Add all the `cases`. */ for (var key in cases) { exports.add(key, cases[key]); } }, {"./cases":64}], 64: [function(require, module, exports) { var camel = require('to-camel-case') , capital = require('to-capital-case') , constant = require('to-constant-case') , dot = require('to-dot-case') , none = require('to-no-case') , pascal = require('to-pascal-case') , sentence = require('to-sentence-case') , slug = require('to-slug-case') , snake = require('to-snake-case') , space = require('to-space-case') , title = require('to-title-case'); /** * Camel. */ exports.camel = camel; /** * Pascal. */ exports.pascal = pascal; /** * Dot. Should precede lowercase. */ exports.dot = dot; /** * Slug. Should precede lowercase. */ exports.slug = slug; /** * Snake. Should precede lowercase. */ exports.snake = snake; /** * Space. Should precede lowercase. */ exports.space = space; /** * Constant. Should precede uppercase. */ exports.constant = constant; /** * Capital. Should precede sentence and title. */ exports.capital = capital; /** * Title. */ exports.title = title; /** * Sentence. */ exports.sentence = sentence; /** * Convert a `string` to lower case from camel, slug, etc. Different that the * usual `toLowerCase` in that it will try to break apart the input first. * * @param {String} string * @return {String} */ exports.lower = function (string) { return none(string).toLowerCase(); }; /** * Convert a `string` to upper case from camel, slug, etc. Different that the * usual `toUpperCase` in that it will try to break apart the input first. * * @param {String} string * @return {String} */ exports.upper = function (string) { return none(string).toUpperCase(); }; /** * Invert each character in a `string` from upper to lower and vice versa. * * @param {String} string * @return {String} */ exports.inverse = function (string) { for (var i = 0, char; char = string[i]; i++) { if (!/[a-z]/i.test(char)) continue; var upper = char.toUpperCase(); var lower = char.toLowerCase(); string[i] = char == upper ? lower : upper; } return string; }; /** * None. */ exports.none = none; }, {"to-camel-case":65,"to-capital-case":66,"to-constant-case":67,"to-dot-case":68,"to-no-case":69,"to-pascal-case":70,"to-sentence-case":71,"to-slug-case":72,"to-snake-case":73,"to-space-case":74,"to-title-case":75}], 65: [function(require, module, exports) { var toSpace = require('to-space-case'); /** * Expose `toCamelCase`. */ module.exports = toCamelCase; /** * Convert a `string` to camel case. * * @param {String} string * @return {String} */ function toCamelCase (string) { return toSpace(string).replace(/\s(\w)/g, function (matches, letter) { return letter.toUpperCase(); }); } }, {"to-space-case":74}], 74: [function(require, module, exports) { var clean = require('to-no-case'); /** * Expose `toSpaceCase`. */ module.exports = toSpaceCase; /** * Convert a `string` to space case. * * @param {String} string * @return {String} */ function toSpaceCase (string) { return clean(string).replace(/[\W_]+(.|$)/g, function (matches, match) { return match ? ' ' + match : ''; }); } }, {"to-no-case":69}], 69: [function(require, module, exports) { /** * Expose `toNoCase`. */ module.exports = toNoCase; /** * Test whether a string is camel-case. */ var hasSpace = /\s/; var hasCamel = /[a-z][A-Z]/; var hasSeparator = /[\W_]/; /** * Remove any starting case from a `string`, like camel or snake, but keep * spaces and punctuation that may be important otherwise. * * @param {String} string * @return {String} */ function toNoCase (string) { if (hasSpace.test(string)) return string.toLowerCase(); if (hasSeparator.test(string)) string = unseparate(string); if (hasCamel.test(string)) string = uncamelize(string); return string.toLowerCase(); } /** * Separator splitter. */ var separatorSplitter = /[\W_]+(.|$)/g; /** * Un-separate a `string`. * * @param {String} string * @return {String} */ function unseparate (string) { return string.replace(separatorSplitter, function (m, next) { return next ? ' ' + next : ''; }); } /** * Camelcase splitter. */ var camelSplitter = /(.)([A-Z]+)/g; /** * Un-camelcase a `string`. * * @param {String} string * @return {String} */ function uncamelize (string) { return string.replace(camelSplitter, function (m, previous, uppers) { return previous + ' ' + uppers.toLowerCase().split('').join(' '); }); } }, {}], 66: [function(require, module, exports) { var clean = require('to-no-case'); /** * Expose `toCapitalCase`. */ module.exports = toCapitalCase; /** * Convert a `string` to capital case. * * @param {String} string * @return {String} */ function toCapitalCase (string) { return clean(string).replace(/(^|\s)(\w)/g, function (matches, previous, letter) { return previous + letter.toUpperCase(); }); } }, {"to-no-case":69}], 67: [function(require, module, exports) { var snake = require('to-snake-case'); /** * Expose `toConstantCase`. */ module.exports = toConstantCase; /** * Convert a `string` to constant case. * * @param {String} string * @return {String} */ function toConstantCase (string) { return snake(string).toUpperCase(); } }, {"to-snake-case":73}], 73: [function(require, module, exports) { var toSpace = require('to-space-case'); /** * Expose `toSnakeCase`. */ module.exports = toSnakeCase; /** * Convert a `string` to snake case. * * @param {String} string * @return {String} */ function toSnakeCase (string) { return toSpace(string).replace(/\s/g, '_'); } }, {"to-space-case":74}], 68: [function(require, module, exports) { var toSpace = require('to-space-case'); /** * Expose `toDotCase`. */ module.exports = toDotCase; /** * Convert a `string` to slug case. * * @param {String} string * @return {String} */ function toDotCase (string) { return toSpace(string).replace(/\s/g, '.'); } }, {"to-space-case":74}], 70: [function(require, module, exports) { var toSpace = require('to-space-case'); /** * Expose `toPascalCase`. */ module.exports = toPascalCase; /** * Convert a `string` to pascal case. * * @param {String} string * @return {String} */ function toPascalCase (string) { return toSpace(string).replace(/(?:^|\s)(\w)/g, function (matches, letter) { return letter.toUpperCase(); }); } }, {"to-space-case":74}], 71: [function(require, module, exports) { var clean = require('to-no-case'); /** * Expose `toSentenceCase`. */ module.exports = toSentenceCase; /** * Convert a `string` to camel case. * * @param {String} string * @return {String} */ function toSentenceCase (string) { return clean(string).replace(/[a-z]/i, function (letter) { return letter.toUpperCase(); }); } }, {"to-no-case":69}], 72: [function(require, module, exports) { var toSpace = require('to-space-case'); /** * Expose `toSlugCase`. */ module.exports = toSlugCase; /** * Convert a `string` to slug case. * * @param {String} string * @return {String} */ function toSlugCase (string) { return toSpace(string).replace(/\s/g, '-'); } }, {"to-space-case":74}], 75: [function(require, module, exports) { var capital = require('to-capital-case') , escape = require('escape-regexp') , map = require('map') , minors = require('title-case-minors'); /** * Expose `toTitleCase`. */ module.exports = toTitleCase; /** * Minors. */ var escaped = map(minors, escape); var minorMatcher = new RegExp('[^^]\\b(' + escaped.join('|') + ')\\b', 'ig'); var colonMatcher = /:\s*(\w)/g; /** * Convert a `string` to camel case. * * @param {String} string * @return {String} */ function toTitleCase (string) { return capital(string) .replace(minorMatcher, function (minor) { return minor.toLowerCase(); }) .replace(colonMatcher, function (letter) { return letter.toUpperCase(); }); } }, {"to-capital-case":66,"escape-regexp":76,"map":77,"title-case-minors":78}], 76: [function(require, module, exports) { /** * Escape regexp special characters in `str`. * * @param {String} str * @return {String} * @api public */ module.exports = function(str){ return String(str).replace(/([.*+?=^!:${}()|[\]\/\\])/g, '\\$1'); }; }, {}], 77: [function(require, module, exports) { var each = require('each'); /** * Map an array or object. * * @param {Array|Object} obj * @param {Function} iterator * @return {Mixed} */ module.exports = function map (obj, iterator) { var arr = []; each(obj, function (o) { arr.push(iterator.apply(null, arguments)); }); return arr; }; }, {"each":79}], 79: [function(require, module, exports) { /** * Module dependencies. */ try { var type = require('type'); } catch (err) { var type = require('component-type'); } var toFunction = require('to-function'); /** * HOP reference. */ var has = Object.prototype.hasOwnProperty; /** * Iterate the given `obj` and invoke `fn(val, i)` * in optional context `ctx`. * * @param {String|Array|Object} obj * @param {Function} fn * @param {Object} [ctx] * @api public */ module.exports = function(obj, fn, ctx){ fn = toFunction(fn); ctx = ctx || this; switch (type(obj)) { case 'array': return array(obj, fn, ctx); case 'object': if ('number' == typeof obj.length) return array(obj, fn, ctx); return object(obj, fn, ctx); case 'string': return string(obj, fn, ctx); } }; /** * Iterate string chars. * * @param {String} obj * @param {Function} fn * @param {Object} ctx * @api private */ function string(obj, fn, ctx) { for (var i = 0; i < obj.length; ++i) { fn.call(ctx, obj.charAt(i), i); } } /** * Iterate object keys. * * @param {Object} obj * @param {Function} fn * @param {Object} ctx * @api private */ function object(obj, fn, ctx) { for (var key in obj) { if (has.call(obj, key)) { fn.call(ctx, key, obj[key]); } } } /** * Iterate array-ish. * * @param {Array|Object} obj * @param {Function} fn * @param {Object} ctx * @api private */ function array(obj, fn, ctx) { for (var i = 0; i < obj.length; ++i) { fn.call(ctx, obj[i], i); } } }, {"type":35,"component-type":35,"to-function":80}], 80: [function(require, module, exports) { /** * Module Dependencies */ var expr; try { expr = require('props'); } catch(e) { expr = require('component-props'); } /** * Expose `toFunction()`. */ module.exports = toFunction; /** * Convert `obj` to a `Function`. * * @param {Mixed} obj * @return {Function} * @api private */ function toFunction(obj) { switch ({}.toString.call(obj)) { case '[object Object]': return objectToFunction(obj); case '[object Function]': return obj; case '[object String]': return stringToFunction(obj); case '[object RegExp]': return regexpToFunction(obj); default: return defaultToFunction(obj); } } /** * Default to strict equality. * * @param {Mixed} val * @return {Function} * @api private */ function defaultToFunction(val) { return function(obj){ return val === obj; }; } /** * Convert `re` to a function. * * @param {RegExp} re * @return {Function} * @api private */ function regexpToFunction(re) { return function(obj){ return re.test(obj); }; } /** * Convert property `str` to a function. * * @param {String} str * @return {Function} * @api private */ function stringToFunction(str) { // immediate such as "> 20" if (/^ *\W+/.test(str)) return new Function('_', 'return _ ' + str); // properties such as "name.first" or "age > 18" or "age > 18 && age < 36" return new Function('_', 'return ' + get(str)); } /** * Convert `object` to a function. * * @param {Object} object * @return {Function} * @api private */ function objectToFunction(obj) { var match = {}; for (var key in obj) { match[key] = typeof obj[key] === 'string' ? defaultToFunction(obj[key]) : toFunction(obj[key]); } return function(val){ if (typeof val !== 'object') return false; for (var key in match) { if (!(key in val)) return false; if (!match[key](val[key])) return false; } return true; }; } /** * Built the getter function. Supports getter style functions * * @param {String} str * @return {String} * @api private */ function get(str) { var props = expr(str); if (!props.length) return '_.' + str; var val, i, prop; for (i = 0; i < props.length; i++) { prop = props[i]; val = '_.' + prop; val = "('function' == typeof " + val + " ? " + val + "() : " + val + ")"; // mimic negative lookbehind to avoid problems with nested properties str = stripNested(prop, str, val); } return str; } /** * Mimic negative lookbehind to avoid problems with nested properties. * * See: http://blog.stevenlevithan.com/archives/mimic-lookbehind-javascript * * @param {String} prop * @param {String} str * @param {String} val * @return {String} * @api private */ function stripNested (prop, str, val) { return str.replace(new RegExp('(\\.)?' + prop, 'g'), function($0, $1) { return $1 ? $0 : val; }); } }, {"props":81,"component-props":81}], 81: [function(require, module, exports) { /** * Global Names */ var globals = /\b(this|Array|Date|Object|Math|JSON)\b/g; /** * Return immediate identifiers parsed from `str`. * * @param {String} str * @param {String|Function} map function or prefix * @return {Array} * @api public */ module.exports = function(str, fn){ var p = unique(props(str)); if (fn && 'string' == typeof fn) fn = prefixed(fn); if (fn) return map(str, p, fn); return p; }; /** * Return immediate identifiers in `str`. * * @param {String} str * @return {Array} * @api private */ function props(str) { return str .replace(/\.\w+|\w+ *\(|"[^"]*"|'[^']*'|\/([^/]+)\//g, '') .replace(globals, '') .match(/[$a-zA-Z_]\w*/g) || []; } /** * Return `str` with `props` mapped with `fn`. * * @param {String} str * @param {Array} props * @param {Function} fn * @return {String} * @api private */ function map(str, props, fn) { var re = /\.\w+|\w+ *\(|"[^"]*"|'[^']*'|\/([^/]+)\/|[a-zA-Z_]\w*/g; return str.replace(re, function(_){ if ('(' == _[_.length - 1]) return fn(_); if (!~props.indexOf(_)) return _; return fn(_); }); } /** * Return unique array. * * @param {Array} arr * @return {Array} * @api private */ function unique(arr) { var ret = []; for (var i = 0; i < arr.length; i++) { if (~ret.indexOf(arr[i])) continue; ret.push(arr[i]); } return ret; } /** * Map with prefix `str`. */ function prefixed(str) { return function(_){ return str + _; }; } }, {}], 78: [function(require, module, exports) { module.exports = [ 'a', 'an', 'and', 'as', 'at', 'but', 'by', 'en', 'for', 'from', 'how', 'if', 'in', 'neither', 'nor', 'of', 'on', 'only', 'onto', 'out', 'or', 'per', 'so', 'than', 'that', 'the', 'to', 'until', 'up', 'upon', 'v', 'v.', 'versus', 'vs', 'vs.', 'via', 'when', 'with', 'without', 'yet' ]; }, {}], 52: [function(require, module, exports) { /** * Module dependencies. */ var inherit = require('./utils').inherit; var Facade = require('./facade'); /** * Expose `Alias` facade. */ module.exports = Alias; /** * Initialize a new `Alias` facade with a `dictionary` of arguments. * * @param {Object} dictionary * @property {String} from * @property {String} to * @property {Object} options */ function Alias (dictionary) { Facade.call(this, dictionary); } /** * Inherit from `Facade`. */ inherit(Alias, Facade); /** * Return type of facade. * * @return {String} */ Alias.prototype.type = Alias.prototype.action = function () { return 'alias'; }; /** * Get `previousId`. * * @return {Mixed} * @api public */ Alias.prototype.from = Alias.prototype.previousId = function(){ return this.field('previousId') || this.field('from'); }; /** * Get `userId`. * * @return {String} * @api public */ Alias.prototype.to = Alias.prototype.userId = function(){ return this.field('userId') || this.field('to'); }; }, {"./utils":58,"./facade":51}], 53: [function(require, module, exports) { var inherit = require('./utils').inherit; var Facade = require('./facade'); var newDate = require('new-date'); /** * Expose `Group` facade. */ module.exports = Group; /** * Initialize a new `Group` facade with a `dictionary` of arguments. * * @param {Object} dictionary * @param {String} userId * @param {String} groupId * @param {Object} properties * @param {Object} options */ function Group (dictionary) { Facade.call(this, dictionary); } /** * Inherit from `Facade` */ inherit(Group, Facade); /** * Get the facade's action. */ Group.prototype.type = Group.prototype.action = function () { return 'group'; }; /** * Setup some basic proxies. */ Group.prototype.groupId = Facade.field('groupId'); /** * Get created or createdAt. * * @return {Date} */ Group.prototype.created = function(){ var created = this.proxy('traits.createdAt') || this.proxy('traits.created') || this.proxy('properties.createdAt') || this.proxy('properties.created'); if (created) return newDate(created); }; /** * Get the group's traits. * * @param {Object} aliases * @return {Object} */ Group.prototype.traits = function (aliases) { var ret = this.properties(); var id = this.groupId(); aliases = aliases || {}; if (id) ret.id = id; for (var alias in aliases) { var value = null == this[alias] ? this.proxy('traits.' + alias) : this[alias](); if (null == value) continue; ret[aliases[alias]] = value; delete ret[alias]; } return ret; }; /** * Get traits or properties. * * TODO: remove me * * @return {Object} */ Group.prototype.properties = function(){ return this.field('traits') || this.field('properties') || {}; }; }, {"./utils":58,"./facade":51,"new-date":21}], 54: [function(require, module, exports) { var Facade = require('./facade'); var isEmail = require('is-email'); var newDate = require('new-date'); var utils = require('./utils'); var trim = require('trim'); var inherit = utils.inherit; var clone = utils.clone; /** * Expose `Idenfity` facade. */ module.exports = Identify; /** * Initialize a new `Identify` facade with a `dictionary` of arguments. * * @param {Object} dictionary * @param {String} userId * @param {String} sessionId * @param {Object} traits * @param {Object} options */ function Identify (dictionary) { Facade.call(this, dictionary); } /** * Inherit from `Facade`. */ inherit(Identify, Facade); /** * Get the facade's action. */ Identify.prototype.type = Identify.prototype.action = function () { return 'identify'; }; /** * Get the user's traits. * * @param {Object} aliases * @return {Object} */ Identify.prototype.traits = function (aliases) { var ret = this.field('traits') || {}; var id = this.userId(); aliases = aliases || {}; if (id) ret.id = id; for (var alias in aliases) { var value = null == this[alias] ? this.proxy('traits.' + alias) : this[alias](); if (null == value) continue; ret[aliases[alias]] = value; delete ret[alias]; } return ret; }; /** * Get the user's email, falling back to their user ID if it's a valid email. * * @return {String} */ Identify.prototype.email = function () { var email = this.proxy('traits.email'); if (email) return email; var userId = this.userId(); if (isEmail(userId)) return userId; }; /** * Get the user's created date, optionally looking for `createdAt` since lots of * people do that instead. * * @return {Date or Undefined} */ Identify.prototype.created = function () { var created = this.proxy('traits.created') || this.proxy('traits.createdAt'); if (created) return newDate(created); }; /** * Get the company created date. * * @return {Date or undefined} */ Identify.prototype.companyCreated = function(){ var created = this.proxy('traits.company.created') || this.proxy('traits.company.createdAt'); if (created) return newDate(created); }; /** * Get the user's name, optionally combining a first and last name if that's all * that was provided. * * @return {String or Undefined} */ Identify.prototype.name = function () { var name = this.proxy('traits.name'); if (typeof name === 'string') return trim(name); var firstName = this.firstName(); var lastName = this.lastName(); if (firstName && lastName) return trim(firstName + ' ' + lastName); }; /** * Get the user's first name, optionally splitting it out of a single name if * that's all that was provided. * * @return {String or Undefined} */ Identify.prototype.firstName = function () { var firstName = this.proxy('traits.firstName'); if (typeof firstName === 'string') return trim(firstName); var name = this.proxy('traits.name'); if (typeof name === 'string') return trim(name).split(' ')[0]; }; /** * Get the user's last name, optionally splitting it out of a single name if * that's all that was provided. * * @return {String or Undefined} */ Identify.prototype.lastName = function () { var lastName = this.proxy('traits.lastName'); if (typeof lastName === 'string') return trim(lastName); var name = this.proxy('traits.name'); if (typeof name !== 'string') return; var space = trim(name).indexOf(' '); if (space === -1) return; return trim(name.substr(space + 1)); }; /** * Get the user's unique id. * * @return {String or undefined} */ Identify.prototype.uid = function(){ return this.userId() || this.username() || this.email(); }; /** * Get description. * * @return {String} */ Identify.prototype.description = function(){ return this.proxy('traits.description') || this.proxy('traits.background'); }; /** * Setup sme basic "special" trait proxies. */ Identify.prototype.username = Facade.proxy('traits.username'); Identify.prototype.website = Facade.proxy('traits.website'); Identify.prototype.phone = Facade.proxy('traits.phone'); Identify.prototype.address = Facade.proxy('traits.address'); Identify.prototype.avatar = Facade.proxy('traits.avatar'); }, {"./facade":51,"./utils":58,"is-email":19,"new-date":21,"trim":50}], 55: [function(require, module, exports) { var inherit = require('./utils').inherit; var clone = require('./utils').clone; var Facade = require('./facade'); var Identify = require('./identify'); var isEmail = require('is-email'); /** * Expose `Track` facade. */ module.exports = Track; /** * Initialize a new `Track` facade with a `dictionary` of arguments. * * @param {object} dictionary * @property {String} event * @property {String} userId * @property {String} sessionId * @property {Object} properties * @property {Object} options */ function Track (dictionary) { Facade.call(this, dictionary); } /** * Inherit from `Facade`. */ inherit(Track, Facade); /** * Return the facade's action. * * @return {String} */ Track.prototype.type = Track.prototype.action = function () { return 'track'; }; /** * Setup some basic proxies. */ Track.prototype.event = Facade.field('event'); Track.prototype.value = Facade.proxy('properties.value'); /** * Misc */ Track.prototype.category = Facade.proxy('properties.category'); Track.prototype.country = Facade.proxy('properties.country'); Track.prototype.state = Facade.proxy('properties.state'); Track.prototype.city = Facade.proxy('properties.city'); Track.prototype.zip = Facade.proxy('properties.zip'); /** * Ecommerce */ Track.prototype.id = Facade.proxy('properties.id'); Track.prototype.sku = Facade.proxy('properties.sku'); Track.prototype.tax = Facade.proxy('properties.tax'); Track.prototype.name = Facade.proxy('properties.name'); Track.prototype.price = Facade.proxy('properties.price'); Track.prototype.total = Facade.proxy('properties.total'); Track.prototype.coupon = Facade.proxy('properties.coupon'); Track.prototype.shipping = Facade.proxy('properties.shipping'); /** * Order id. * * @return {String} * @api public */ Track.prototype.orderId = function(){ return this.proxy('properties.id') || this.proxy('properties.orderId'); }; /** * Get subtotal. * * @return {Number} */ Track.prototype.subtotal = function(){ var subtotal = this.obj.properties.subtotal; var total = this.total(); var n; if (subtotal) return subtotal; if (!total) return 0; if (n = this.tax()) total -= n; if (n = this.shipping()) total -= n; return total; }; /** * Get products. * * @return {Array} */ Track.prototype.products = function(){ var props = this.obj.properties || {}; return props.products || []; }; /** * Get quantity. * * @return {Number} */ Track.prototype.quantity = function(){ var props = this.obj.properties || {}; return props.quantity || 1; }; /** * Get currency. * * @return {String} */ Track.prototype.currency = function(){ var props = this.obj.properties || {}; return props.currency || 'USD'; }; /** * BACKWARDS COMPATIBILITY: should probably re-examine where these come from. */ Track.prototype.referrer = Facade.proxy('properties.referrer'); Track.prototype.query = Facade.proxy('options.query'); /** * Get the call's properties. * * @param {Object} aliases * @return {Object} */ Track.prototype.properties = function (aliases) { var ret = this.field('properties') || {}; aliases = aliases || {}; for (var alias in aliases) { var value = null == this[alias] ? this.proxy('properties.' + alias) : this[alias](); if (null == value) continue; ret[aliases[alias]] = value; delete ret[alias]; } return ret; }; /** * Get the call's username. * * @return {String or Undefined} */ Track.prototype.username = function () { return this.proxy('traits.username') || this.proxy('properties.username') || this.userId() || this.sessionId(); }; /** * Get the call's email, using an the user ID if it's a valid email. * * @return {String or Undefined} */ Track.prototype.email = function () { var email = this.proxy('traits.email'); email = email || this.proxy('properties.email'); if (email) return email; var userId = this.userId(); if (isEmail(userId)) return userId; }; /** * Get the call's revenue, parsing it from a string with an optional leading * dollar sign. * * For products/services that don't have shipping and are not directly taxed, * they only care about tracking `revenue`. These are things like * SaaS companies, who sell monthly subscriptions. The subscriptions aren't * taxed directly, and since it's a digital product, it has no shipping. * * The only case where there's a difference between `revenue` and `total` * (in the context of analytics) is on ecommerce platforms, where they want * the `revenue` function to actually return the `total` (which includes * tax and shipping, total = subtotal + tax + shipping). This is probably * because on their backend they assume tax and shipping has been applied to * the value, and so can get the revenue on their own. * * @return {Number} */ Track.prototype.revenue = function () { var revenue = this.proxy('properties.revenue'); var event = this.event(); // it's always revenue, unless it's called during an order completion. if (!revenue && event && event.match(/completed ?order/i)) { revenue = this.proxy('properties.total'); } return currency(revenue); }; /** * Get cents. * * @return {Number} */ Track.prototype.cents = function(){ var revenue = this.revenue(); return 'number' != typeof revenue ? this.value() || 0 : revenue * 100; }; /** * A utility to turn the pieces of a track call into an identify. Used for * integrations with super properties or rate limits. * * TODO: remove me. * * @return {Facade} */ Track.prototype.identify = function () { var json = this.json(); json.traits = this.traits(); return new Identify(json); }; /** * Get float from currency value. * * @param {Mixed} val * @return {Number} */ function currency(val) { if (!val) return; if (typeof val === 'number') return val; if (typeof val !== 'string') return; val = val.replace(/\$/g, ''); val = parseFloat(val); if (!isNaN(val)) return val; } }, {"./utils":58,"./facade":51,"./identify":54,"is-email":19}], 56: [function(require, module, exports) { var inherit = require('./utils').inherit; var Facade = require('./facade'); var Track = require('./track'); /** * Expose `Page` facade */ module.exports = Page; /** * Initialize new `Page` facade with `dictionary`. * * @param {Object} dictionary * @param {String} category * @param {String} name * @param {Object} traits * @param {Object} options */ function Page(dictionary){ Facade.call(this, dictionary); } /** * Inherit from `Facade` */ inherit(Page, Facade); /** * Get the facade's action. * * @return {String} */ Page.prototype.type = Page.prototype.action = function(){ return 'page'; }; /** * Proxies */ Page.prototype.category = Facade.field('category'); Page.prototype.name = Facade.field('name'); /** * Get the page properties mixing `category` and `name`. * * @return {Object} */ Page.prototype.properties = function(){ var props = this.field('properties') || {}; var category = this.category(); var name = this.name(); if (category) props.category = category; if (name) props.name = name; return props; }; /** * Get the page fullName. * * @return {String} */ Page.prototype.fullName = function(){ var category = this.category(); var name = this.name(); return name && category ? category + ' ' + name : name; }; /** * Get event with `name`. * * @return {String} */ Page.prototype.event = function(name){ return name ? 'Viewed ' + name + ' Page' : 'Loaded a Page'; }; /** * Convert this Page to a Track facade with `name`. * * @param {String} name * @return {Track} */ Page.prototype.track = function(name){ var props = this.properties(); return new Track({ event: this.event(name), properties: props }); }; }, {"./utils":58,"./facade":51,"./track":55}], 57: [function(require, module, exports) { var inherit = require('./utils').inherit; var Page = require('./page'); var Track = require('./track'); /** * Expose `Screen` facade */ module.exports = Screen; /** * Initialize new `Screen` facade with `dictionary`. * * @param {Object} dictionary * @param {String} category * @param {String} name * @param {Object} traits * @param {Object} options */ function Screen(dictionary){ Page.call(this, dictionary); } /** * Inherit from `Page` */ inherit(Screen, Page); /** * Get the facade's action. * * @return {String} * @api public */ Screen.prototype.type = Screen.prototype.action = function(){ return 'screen'; }; /** * Get event with `name`. * * @param {String} name * @return {String} * @api public */ Screen.prototype.event = function(name){ return name ? 'Viewed ' + name + ' Screen' : 'Loaded a Screen'; }; /** * Convert this Screen. * * @param {String} name * @return {Track} * @api public */ Screen.prototype.track = function(name){ var props = this.properties(); return new Track({ event: this.event(name), properties: props }); }; }, {"./utils":58,"./page":56,"./track":55}], 3: [function(require, module, exports) { module.exports = '2.3.6'; }, {}], 4: [function(require, module, exports) { /** * Module dependencies. */ var each = require('each'); var plugins = require('./integrations.js'); /** * Expose the integrations, using their own `name` from their `prototype`. */ each(plugins, function(plugin){ var name = (plugin.Integration || plugin).prototype.name; exports[name] = plugin; }); }, {"./integrations.js":82,"each":5}], 82: [function(require, module, exports) { /** * DON'T EDIT THIS FILE. It's automatically generated! */ module.exports = [ require('./lib/adroll'), require('./lib/adwords'), require('./lib/alexa'), require('./lib/amplitude'), require('./lib/appcues'), require('./lib/awesm'), require('./lib/awesomatic'), require('./lib/bing-ads'), require('./lib/bronto'), require('./lib/bugherd'), require('./lib/bugsnag'), require('./lib/chartbeat'), require('./lib/churnbee'), require('./lib/clicktale'), require('./lib/clicky'), require('./lib/comscore'), require('./lib/crazy-egg'), require('./lib/curebit'), require('./lib/customerio'), require('./lib/drip'), require('./lib/errorception'), require('./lib/evergage'), require('./lib/facebook-ads'), require('./lib/foxmetrics'), require('./lib/frontleaf'), require('./lib/gauges'), require('./lib/get-satisfaction'), require('./lib/google-analytics'), require('./lib/google-tag-manager'), require('./lib/gosquared'), require('./lib/heap'), require('./lib/hellobar'), require('./lib/hittail'), require('./lib/hublo'), require('./lib/hubspot'), require('./lib/improvely'), require('./lib/insidevault'), require('./lib/inspectlet'), require('./lib/intercom'), require('./lib/keen-io'), require('./lib/kenshoo'), require('./lib/kissmetrics'), require('./lib/klaviyo'), require('./lib/leadlander'), require('./lib/livechat'), require('./lib/lucky-orange'), require('./lib/lytics'), require('./lib/mixpanel'), require('./lib/mojn'), require('./lib/mouseflow'), require('./lib/mousestats'), require('./lib/navilytics'), require('./lib/olark'), require('./lib/optimizely'), require('./lib/perfect-audience'), require('./lib/pingdom'), require('./lib/piwik'), require('./lib/preact'), require('./lib/qualaroo'), require('./lib/quantcast'), require('./lib/rollbar'), require('./lib/saasquatch'), require('./lib/sentry'), require('./lib/snapengage'), require('./lib/spinnakr'), require('./lib/tapstream'), require('./lib/trakio'), require('./lib/twitter-ads'), require('./lib/usercycle'), require('./lib/userfox'), require('./lib/uservoice'), require('./lib/vero'), require('./lib/visual-website-optimizer'), require('./lib/webengage'), require('./lib/woopra'), require('./lib/yandex-metrica') ]; }, {"./lib/adroll":83,"./lib/adwords":84,"./lib/alexa":85,"./lib/amplitude":86,"./lib/appcues":87,"./lib/awesm":88,"./lib/awesomatic":89,"./lib/bing-ads":90,"./lib/bronto":91,"./lib/bugherd":92,"./lib/bugsnag":93,"./lib/chartbeat":94,"./lib/churnbee":95,"./lib/clicktale":96,"./lib/clicky":97,"./lib/comscore":98,"./lib/crazy-egg":99,"./lib/curebit":100,"./lib/customerio":101,"./lib/drip":102,"./lib/errorception":103,"./lib/evergage":104,"./lib/facebook-ads":105,"./lib/foxmetrics":106,"./lib/frontleaf":107,"./lib/gauges":108,"./lib/get-satisfaction":109,"./lib/google-analytics":110,"./lib/google-tag-manager":111,"./lib/gosquared":112,"./lib/heap":113,"./lib/hellobar":114,"./lib/hittail":115,"./lib/hublo":116,"./lib/hubspot":117,"./lib/improvely":118,"./lib/insidevault":119,"./lib/inspectlet":120,"./lib/intercom":121,"./lib/keen-io":122,"./lib/kenshoo":123,"./lib/kissmetrics":124,"./lib/klaviyo":125,"./lib/leadlander":126,"./lib/livechat":127,"./lib/lucky-orange":128,"./lib/lytics":129,"./lib/mixpanel":130,"./lib/mojn":131,"./lib/mouseflow":132,"./lib/mousestats":133,"./lib/navilytics":134,"./lib/olark":135,"./lib/optimizely":136,"./lib/perfect-audience":137,"./lib/pingdom":138,"./lib/piwik":139,"./lib/preact":140,"./lib/qualaroo":141,"./lib/quantcast":142,"./lib/rollbar":143,"./lib/saasquatch":144,"./lib/sentry":145,"./lib/snapengage":146,"./lib/spinnakr":147,"./lib/tapstream":148,"./lib/trakio":149,"./lib/twitter-ads":150,"./lib/usercycle":151,"./lib/userfox":152,"./lib/uservoice":153,"./lib/vero":154,"./lib/visual-website-optimizer":155,"./lib/webengage":156,"./lib/woopra":157,"./lib/yandex-metrica":158}], 83: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('segmentio/analytics.js-integration'); var snake = require('to-snake-case'); var useHttps = require('use-https'); var each = require('each'); var is = require('is'); /** * HOP */ var has = Object.prototype.hasOwnProperty; /** * Expose `AdRoll` integration. */ var AdRoll = module.exports = integration('AdRoll') .assumesPageview() .global('__adroll_loaded') .global('adroll_adv_id') .global('adroll_pix_id') .global('adroll_custom_data') .option('advId', '') .option('pixId', '') .tag('http', '<script src="http://a.adroll.com/j/roundtrip.js">') .tag('https', '<script src="https://s.adroll.com/j/roundtrip.js">') .mapping('events'); /** * Initialize. * * http://support.adroll.com/getting-started-in-4-easy-steps/#step-one * http://support.adroll.com/enhanced-conversion-tracking/ * * @param {Object} page */ AdRoll.prototype.initialize = function(page){ window.adroll_adv_id = this.options.advId; window.adroll_pix_id = this.options.pixId; window.__adroll_loaded = true; var name = useHttps() ? 'https' : 'http'; this.load(name, this.ready); }; /** * Loaded? * * @return {Boolean} */ AdRoll.prototype.loaded = function(){ return window.__adroll; }; /** * Page. * * http://support.adroll.com/segmenting-clicks/ * * @param {Page} page */ AdRoll.prototype.page = function(page){ var name = page.fullName(); this.track(page.track(name)); }; /** * Track. * * @param {Track} track */ AdRoll.prototype.track = function(track){ var event = track.event(); var user = this.analytics.user(); var events = this.events(event); var total = track.revenue() || track.total() || 0; var orderId = track.orderId() || 0; each(events, function(event){ var data = {}; if (user.id()) data.user_id = user.id(); data.adroll_conversion_value_in_dollars = total; data.order_id = orderId; // the adroll interface only allows for // segment names which are snake cased. data.adroll_segments = snake(event); window.__adroll.record_user(data); }); // no events found if (!events.length) { var data = {}; if (user.id()) data.user_id = user.id(); data.adroll_segments = snake(event); window.__adroll.record_user(data); } }; }, {"segmentio/analytics.js-integration":159,"to-snake-case":160,"use-https":161,"each":5,"is":18}], 159: [function(require, module, exports) { /** * Module dependencies. */ var bind = require('bind'); var callback = require('callback'); var clone = require('clone'); var debug = require('debug'); var defaults = require('defaults'); var protos = require('./protos'); var slug = require('slug'); var statics = require('./statics'); /** * Expose `createIntegration`. */ module.exports = createIntegration; /** * Create a new `Integration` constructor. * * @param {String} name * @return {Function} Integration */ function createIntegration(name){ /** * Initialize a new `Integration`. * * @param {Object} options */ function Integration(options){ if (options && options.addIntegration) { // plugin return options.addIntegration(Integration); } this.debug = debug('analytics:integration:' + slug(name)); this.options = defaults(clone(options) || {}, this.defaults); this._queue = []; this.once('ready', bind(this, this.flush)); Integration.emit('construct', this); this.ready = bind(this, this.ready); this._wrapInitialize(); this._wrapPage(); this._wrapTrack(); } Integration.prototype.defaults = {}; Integration.prototype.globals = []; Integration.prototype.templates = {}; Integration.prototype.name = name; for (var key in statics) Integration[key] = statics[key]; for (var key in protos) Integration.prototype[key] = protos[key]; return Integration; } }, {"./protos":162,"./statics":163,"bind":164,"callback":12,"clone":14,"debug":165,"defaults":16,"slug":166}], 162: [function(require, module, exports) { /** * Module dependencies. */ var loadScript = require('segmentio/load-script'); var normalize = require('to-no-case'); var callback = require('callback'); var Emitter = require('emitter'); var events = require('./events'); var tick = require('next-tick'); var assert = require('assert'); var after = require('after'); var each = require('component/each'); var type = require('type'); var fmt = require('yields/fmt'); /** * Window defaults. */ var setTimeout = window.setTimeout; var setInterval = window.setInterval; var onerror = null; var onload = null; /** * Mixin emitter. */ Emitter(exports); /** * Initialize. */ exports.initialize = function(){ var ready = this.ready; tick(ready); }; /** * Loaded? * * @return {Boolean} * @api private */ exports.loaded = function(){ return false; }; /** * Load. * * @param {Function} cb */ exports.load = function(cb){ callback.async(cb); }; /** * Page. * * @param {Page} page */ exports.page = function(page){}; /** * Track. * * @param {Track} track */ exports.track = function(track){}; /** * Get events that match `str`. * * Examples: * * events = { my_event: 'a4991b88' } * .map(events, 'My Event'); * // => ["a4991b88"] * .map(events, 'whatever'); * // => [] * * events = [{ key: 'my event', value: '9b5eb1fa' }] * .map(events, 'my_event'); * // => ["9b5eb1fa"] * .map(events, 'whatever'); * // => [] * * @param {String} str * @return {Array} * @api public */ exports.map = function(obj, str){ var a = normalize(str); var ret = []; // noop if (!obj) return ret; // object if ('object' == type(obj)) { for (var k in obj) { var item = obj[k]; var b = normalize(k); if (b == a) ret.push(item); } } // array if ('array' == type(obj)) { if (!obj.length) return ret; if (!obj[0].key) return ret; for (var i = 0; i < obj.length; ++i) { var item = obj[i]; var b = normalize(item.key); if (b == a) ret.push(item.value); } } return ret; }; /** * Invoke a `method` that may or may not exist on the prototype with `args`, * queueing or not depending on whether the integration is "ready". Don't * trust the method call, since it contains integration party code. * * @param {String} method * @param {Mixed} args... * @api private */ exports.invoke = function(method){ if (!this[method]) return; var args = [].slice.call(arguments, 1); if (!this._ready) return this.queue(method, args); var ret; try { this.debug('%s with %o', method, args); ret = this[method].apply(this, args); } catch (e) { this.debug('error %o calling %s with %o', e, method, args); } return ret; }; /** * Queue a `method` with `args`. If the integration assumes an initial * pageview, then let the first call to `page` pass through. * * @param {String} method * @param {Array} args * @api private */ exports.queue = function(method, args){ if ('page' == method && this._assumesPageview && !this._initialized) { return this.page.apply(this, args); } this._queue.push({ method: method, args: args }); }; /** * Flush the internal queue. * * @api private */ exports.flush = function(){ this._ready = true; var call; while (call = this._queue.shift()) this[call.method].apply(this, call.args); }; /** * Reset the integration, removing its global variables. * * @api private */ exports.reset = function(){ for (var i = 0, key; key = this.globals[i]; i++) window[key] = undefined; window.setTimeout = setTimeout; window.setInterval = setInterval; window.onerror = onerror; window.onload = onload; }; /** * Load a tag by `name`. * * @param {String} name * @param {Function} [fn] */ exports.load = function(name, locals, fn){ if ('function' == typeof name) fn = name, locals = null, name = null; if (name && 'object' == typeof name) fn = locals, locals = name, name = null; if ('function' == typeof locals) fn = locals, locals = null; name = name || 'library'; locals = locals || {}; locals = this.locals(locals); var template = this.templates[name]; assert(template, fmt('Template "%s" not defined.', name)); var attrs = render(template, locals); var el; switch (template.type) { case 'img': attrs.width = 1; attrs.height = 1; el = loadImage(attrs, fn); break; case 'script': el = loadScript(attrs, fn); // TODO: hack until refactoring load-script delete attrs.src; each(attrs, function(key, val){ el.setAttribute(key, val); }); break; case 'iframe': el = loadIframe(attrs, fn); break; } return el; }; /** * Locals for tag templates. * * By default it includes a cache buster, * and all of the options. * * @param {Object} [locals] * @return {Object} */ exports.locals = function(locals){ locals = locals || {}; var cache = Math.floor(new Date().getTime() / 3600000); if (!locals.hasOwnProperty('cache')) locals.cache = cache; each(this.options, function(key, val){ if (!locals.hasOwnProperty(key)) locals[key] = val; }); return locals; }; /** * Simple way to emit ready. */ exports.ready = function(){ this.emit('ready'); }; /** * Wrap the initialize method in an exists check, so we don't have to do it for * every single integration. * * @api private */ exports._wrapInitialize = function(){ var initialize = this.initialize; this.initialize = function(){ this.debug('initialize'); this._initialized = true; var ret = initialize.apply(this, arguments); this.emit('initialize'); return ret; }; if (this._assumesPageview) this.initialize = after(2, this.initialize); }; /** * Wrap the page method to call `initialize` instead if the integration assumes * a pageview. * * @api private */ exports._wrapPage = function(){ var page = this.page; this.page = function(){ if (this._assumesPageview && !this._initialized) { return this.initialize.apply(this, arguments); } return page.apply(this, arguments); }; }; /** * Wrap the track method to call other ecommerce methods if * available depending on the `track.event()`. * * @api private */ exports._wrapTrack = function(){ var t = this.track; this.track = function(track){ var event = track.event(); var called; var ret; for (var method in events) { var regexp = events[method]; if (!this[method]) continue; if (!regexp.test(event)) continue; ret = this[method].apply(this, arguments); called = true; break; } if (!called) ret = t.apply(this, arguments); return ret; }; }; function loadImage(attrs, fn) { fn = fn || function(){}; var img = new Image; img.onerror = error(fn, 'failed to load pixel', img); img.onload = function(){ fn(); }; img.src = attrs.src; img.width = 1; img.height = 1; return img; } function error(fn, message, img){ return function(e){ e = e || window.event; var err = new Error(message); err.event = e; err.source = img; fn(err); }; } /** * Render template + locals into an `attrs` object. * * @param {Object} template * @param {Object} locals * @return {Object} */ function render(template, locals) { var attrs = {}; each(template.attrs, function(key, val){ attrs[key] = val.replace(/\{\{\ *(\w+)\ *\}\}/g, function(_, $1){ return locals[$1]; }); }); return attrs; } }, {"./events":167,"segmentio/load-script":168,"to-no-case":169,"callback":12,"emitter":17,"next-tick":45,"assert":170,"after":10,"component/each":79,"type":35,"yields/fmt":171}], 167: [function(require, module, exports) { /** * Expose `events`. */ module.exports = { removedProduct: /removed[ _]?product/i, viewedProduct: /viewed[ _]?product/i, addedProduct: /added[ _]?product/i, completedOrder: /completed[ _]?order/i }; }, {}], 168: [function(require, module, exports) { /** * Module dependencies. */ var onload = require('script-onload'); var tick = require('next-tick'); var type = require('type'); /** * Expose `loadScript`. * * @param {Object} options * @param {Function} fn * @api public */ module.exports = function loadScript(options, fn){ if (!options) throw new Error('Cant load nothing...'); // Allow for the simplest case, just passing a `src` string. if ('string' == type(options)) options = { src : options }; var https = document.location.protocol === 'https:' || document.location.protocol === 'chrome-extension:'; // If you use protocol relative URLs, third-party scripts like Google // Analytics break when testing with `file:` so this fixes that. if (options.src && options.src.indexOf('//') === 0) { options.src = https ? 'https:' + options.src : 'http:' + options.src; } // Allow them to pass in different URLs depending on the protocol. if (https && options.https) options.src = options.https; else if (!https && options.http) options.src = options.http; // Make the `<script>` element and insert it before the first script on the // page, which is guaranteed to exist since this Javascript is running. var script = document.createElement('script'); script.type = 'text/javascript'; script.async = true; script.src = options.src; // If we have a fn, attach event handlers, even in IE. Based off of // the Third-Party Javascript script loading example: // https://github.com/thirdpartyjs/thirdpartyjs-code/blob/master/examples/templates/02/loading-files/index.html if ('function' == type(fn)) { onload(script, fn); } tick(function(){ // Append after event listeners are attached for IE. var firstScript = document.getElementsByTagName('script')[0]; firstScript.parentNode.insertBefore(script, firstScript); }); // Return the script element in case they want to do anything special, like // give it an ID or attributes. return script; }; }, {"script-onload":172,"next-tick":45,"type":35}], 172: [function(require, module, exports) { // https://github.com/thirdpartyjs/thirdpartyjs-code/blob/master/examples/templates/02/loading-files/index.html /** * Invoke `fn(err)` when the given `el` script loads. * * @param {Element} el * @param {Function} fn * @api public */ module.exports = function(el, fn){ return el.addEventListener ? add(el, fn) : attach(el, fn); }; /** * Add event listener to `el`, `fn()`. * * @param {Element} el * @param {Function} fn * @api private */ function add(el, fn){ el.addEventListener('load', function(_, e){ fn(null, e); }, false); el.addEventListener('error', function(e){ var err = new Error('failed to load the script "' + el.src + '"'); err.event = e; fn(err); }, false); } /** * Attach evnet. * * @param {Element} el * @param {Function} fn * @api private */ function attach(el, fn){ el.attachEvent('onreadystatechange', function(e){ if (!/complete|loaded/.test(el.readyState)) return; fn(null, e); }); } }, {}], 169: [function(require, module, exports) { /** * Expose `toNoCase`. */ module.exports = toNoCase; /** * Test whether a string is camel-case. */ var hasSpace = /\s/; var hasSeparator = /[\W_]/; /** * Remove any starting case from a `string`, like camel or snake, but keep * spaces and punctuation that may be important otherwise. * * @param {String} string * @return {String} */ function toNoCase (string) { if (hasSpace.test(string)) return string.toLowerCase(); if (hasSeparator.test(string)) return unseparate(string).toLowerCase(); return uncamelize(string).toLowerCase(); } /** * Separator splitter. */ var separatorSplitter = /[\W_]+(.|$)/g; /** * Un-separate a `string`. * * @param {String} string * @return {String} */ function unseparate (string) { return string.replace(separatorSplitter, function (m, next) { return next ? ' ' + next : ''; }); } /** * Camelcase splitter. */ var camelSplitter = /(.)([A-Z]+)/g; /** * Un-camelcase a `string`. * * @param {String} string * @return {String} */ function uncamelize (string) { return string.replace(camelSplitter, function (m, previous, uppers) { return previous + ' ' + uppers.toLowerCase().split('').join(' '); }); } }, {}], 170: [function(require, module, exports) { /** * Module dependencies. */ var equals = require('equals'); var fmt = require('fmt'); var stack = require('stack'); /** * Assert `expr` with optional failure `msg`. * * @param {Mixed} expr * @param {String} [msg] * @api public */ module.exports = exports = function (expr, msg) { if (expr) return; throw new Error(msg || message()); }; /** * Assert `actual` is weak equal to `expected`. * * @param {Mixed} actual * @param {Mixed} expected * @param {String} [msg] * @api public */ exports.equal = function (actual, expected, msg) { if (actual == expected) return; throw new Error(msg || fmt('Expected %o to equal %o.', actual, expected)); }; /** * Assert `actual` is not weak equal to `expected`. * * @param {Mixed} actual * @param {Mixed} expected * @param {String} [msg] * @api public */ exports.notEqual = function (actual, expected, msg) { if (actual != expected) return; throw new Error(msg || fmt('Expected %o not to equal %o.', actual, expected)); }; /** * Assert `actual` is deep equal to `expected`. * * @param {Mixed} actual * @param {Mixed} expected * @param {String} [msg] * @api public */ exports.deepEqual = function (actual, expected, msg) { if (equals(actual, expected)) return; throw new Error(msg || fmt('Expected %o to deeply equal %o.', actual, expected)); }; /** * Assert `actual` is not deep equal to `expected`. * * @param {Mixed} actual * @param {Mixed} expected * @param {String} [msg] * @api public */ exports.notDeepEqual = function (actual, expected, msg) { if (!equals(actual, expected)) return; throw new Error(msg || fmt('Expected %o not to deeply equal %o.', actual, expected)); }; /** * Assert `actual` is strict equal to `expected`. * * @param {Mixed} actual * @param {Mixed} expected * @param {String} [msg] * @api public */ exports.strictEqual = function (actual, expected, msg) { if (actual === expected) return; throw new Error(msg || fmt('Expected %o to strictly equal %o.', actual, expected)); }; /** * Assert `actual` is not strict equal to `expected`. * * @param {Mixed} actual * @param {Mixed} expected * @param {String} [msg] * @api public */ exports.notStrictEqual = function (actual, expected, msg) { if (actual !== expected) return; throw new Error(msg || fmt('Expected %o not to strictly equal %o.', actual, expected)); }; /** * Assert `block` throws an `error`. * * @param {Function} block * @param {Function} [error] * @param {String} [msg] * @api public */ exports.throws = function (block, error, msg) { var err; try { block(); } catch (e) { err = e; } if (!err) throw new Error(msg || fmt('Expected %s to throw an error.', block.toString())); if (error && !(err instanceof error)) { throw new Error(msg || fmt('Expected %s to throw an %o.', block.toString(), error)); } }; /** * Assert `block` doesn't throw an `error`. * * @param {Function} block * @param {Function} [error] * @param {String} [msg] * @api public */ exports.doesNotThrow = function (block, error, msg) { var err; try { block(); } catch (e) { err = e; } if (err) throw new Error(msg || fmt('Expected %s not to throw an error.', block.toString())); if (error && (err instanceof error)) { throw new Error(msg || fmt('Expected %s not to throw an %o.', block.toString(), error)); } }; /** * Create a message from the call stack. * * @return {String} * @api private */ function message() { if (!Error.captureStackTrace) return 'assertion failed'; var callsite = stack()[2]; var fn = callsite.getFunctionName(); var file = callsite.getFileName(); var line = callsite.getLineNumber() - 1; var col = callsite.getColumnNumber() - 1; var src = get(file); line = src.split('\n')[line].slice(col); var m = line.match(/assert\((.*)\)/); return m && m[1].trim(); } /** * Load contents of `script`. * * @param {String} script * @return {String} * @api private */ function get(script) { var xhr = new XMLHttpRequest; xhr.open('GET', script, false); xhr.send(null); return xhr.responseText; } }, {"equals":173,"fmt":171,"stack":174}], 173: [function(require, module, exports) { var type = require('type') /** * expose equals */ module.exports = equals equals.compare = compare /** * assert all values are equal * * @param {Any} [...] * @return {Boolean} */ function equals(){ var i = arguments.length - 1 while (i > 0) { if (!compare(arguments[i], arguments[--i])) return false } return true } // (any, any, [array]) -> boolean function compare(a, b, memos){ // All identical values are equivalent if (a === b) return true var fnA = types[type(a)] var fnB = types[type(b)] return fnA && fnA === fnB ? fnA(a, b, memos) : false } var types = {} // (Number) -> boolean types.number = function(a){ // NaN check return a !== a } // (function, function, array) -> boolean types['function'] = function(a, b, memos){ return a.toString() === b.toString() // Functions can act as objects && types.object(a, b, memos) && compare(a.prototype, b.prototype) } // (date, date) -> boolean types.date = function(a, b){ return +a === +b } // (regexp, regexp) -> boolean types.regexp = function(a, b){ return a.toString() === b.toString() } // (DOMElement, DOMElement) -> boolean types.element = function(a, b){ return a.outerHTML === b.outerHTML } // (textnode, textnode) -> boolean types.textnode = function(a, b){ return a.textContent === b.textContent } // decorate `fn` to prevent it re-checking objects // (function) -> function function memoGaurd(fn){ return function(a, b, memos){ if (!memos) return fn(a, b, []) var i = memos.length, memo while (memo = memos[--i]) { if (memo[0] === a && memo[1] === b) return true } return fn(a, b, memos) } } types['arguments'] = types.array = memoGaurd(compareArrays) // (array, array, array) -> boolean function compareArrays(a, b, memos){ var i = a.length if (i !== b.length) return false memos.push([a, b]) while (i--) { if (!compare(a[i], b[i], memos)) return false } return true } types.object = memoGaurd(compareObjects) // (object, object, array) -> boolean function compareObjects(a, b, memos) { var ka = getEnumerableProperties(a) var kb = getEnumerableProperties(b) var i = ka.length // same number of properties if (i !== kb.length) return false // although not necessarily the same order ka.sort() kb.sort() // cheap key test while (i--) if (ka[i] !== kb[i]) return false // remember memos.push([a, b]) // iterate again this time doing a thorough check i = ka.length while (i--) { var key = ka[i] if (!compare(a[key], b[key], memos)) return false } return true } // (object) -> array function getEnumerableProperties (object) { var result = [] for (var k in object) if (k !== 'constructor') { result.push(k) } return result } }, {"type":175}], 175: [function(require, module, exports) { var toString = {}.toString var DomNode = typeof window != 'undefined' ? window.Node : Function /** * Return the type of `val`. * * @param {Mixed} val * @return {String} * @api public */ module.exports = exports = function(x){ var type = typeof x if (type != 'object') return type type = types[toString.call(x)] if (type) return type if (x instanceof DomNode) switch (x.nodeType) { case 1: return 'element' case 3: return 'text-node' case 9: return 'document' case 11: return 'document-fragment' default: return 'dom-node' } } var types = exports.types = { '[object Function]': 'function', '[object Date]': 'date', '[object RegExp]': 'regexp', '[object Arguments]': 'arguments', '[object Array]': 'array', '[object String]': 'string', '[object Null]': 'null', '[object Undefined]': 'undefined', '[object Number]': 'number', '[object Boolean]': 'boolean', '[object Object]': 'object', '[object Text]': 'text-node', '[object Uint8Array]': 'bit-array', '[object Uint16Array]': 'bit-array', '[object Uint32Array]': 'bit-array', '[object Uint8ClampedArray]': 'bit-array', '[object Error]': 'error', '[object FormData]': 'form-data', '[object File]': 'file', '[object Blob]': 'blob' } }, {}], 171: [function(require, module, exports) { /** * Export `fmt` */ module.exports = fmt; /** * Formatters */ fmt.o = JSON.stringify; fmt.s = String; fmt.d = parseInt; /** * Format the given `str`. * * @param {String} str * @param {...} args * @return {String} * @api public */ function fmt(str){ var args = [].slice.call(arguments, 1); var j = 0; return str.replace(/%([a-z])/gi, function(_, f){ return fmt[f] ? fmt[f](args[j++]) : _ + f; }); } }, {}], 174: [function(require, module, exports) { /** * Expose `stack()`. */ module.exports = stack; /** * Return the stack. * * @return {Array} * @api public */ function stack() { var orig = Error.prepareStackTrace; Error.prepareStackTrace = function(_, stack){ return stack; }; var err = new Error; Error.captureStackTrace(err, arguments.callee); var stack = err.stack; Error.prepareStackTrace = orig; return stack; } }, {}], 163: [function(require, module, exports) { /** * Module dependencies. */ var after = require('after'); var domify = require('component/domify'); var each = require('component/each'); var Emitter = require('emitter'); /** * Mixin emitter. */ Emitter(exports); /** * Add a new option to the integration by `key` with default `value`. * * @param {String} key * @param {Mixed} value * @return {Integration} */ exports.option = function(key, value){ this.prototype.defaults[key] = value; return this; }; /** * Add a new mapping option. * * This will create a method `name` that will return a mapping * for you to use. * * Example: * * Integration('My Integration') * .mapping('events'); * * new MyIntegration().track('My Event'); * * .track = function(track){ * var events = this.events(track.event()); * each(events, send); * }; * * @param {String} name * @return {Integration} */ exports.mapping = function(name){ this.option(name, []); this.prototype[name] = function(str){ return this.map(this.options[name], str); }; return this; }; /** * Register a new global variable `key` owned by the integration, which will be * used to test whether the integration is already on the page. * * @param {String} global * @return {Integration} */ exports.global = function(key){ this.prototype.globals.push(key); return this; }; /** * Mark the integration as assuming an initial pageview, so to defer loading * the script until the first `page` call, noop the first `initialize`. * * @return {Integration} */ exports.assumesPageview = function(){ this.prototype._assumesPageview = true; return this; }; /** * Mark the integration as being "ready" once `load` is called. * * @return {Integration} */ exports.readyOnLoad = function(){ this.prototype._readyOnLoad = true; return this; }; /** * Mark the integration as being "ready" once `initialize` is called. * * @return {Integration} */ exports.readyOnInitialize = function(){ this.prototype._readyOnInitialize = true; return this; }; /** * Define a tag to be loaded. * * @param {String} str DOM tag as string or URL * @return {Integration} */ exports.tag = function(name, str){ if (null == str) { str = name; name = 'library'; } this.prototype.templates[name] = objectify(str); return this; }; /** * Given a string, give back DOM attributes. * * Do it in a way where the browser doesn't load images or iframes. * It turns out, domify will load images/iframes, because * whenever you construct those DOM elements, * the browser immediately loads them. * * @param {String} str * @return {Object} */ function objectify(str) { // replace `src` with `data-src` to prevent image loading str = str.replace(' src="', ' data-src="'); var el = domify(str); var attrs = {}; each(el.attributes, function(attr){ // then replace it back var name = 'data-src' == attr.name ? 'src' : attr.name; attrs[name] = attr.value; }); return { type: el.tagName.toLowerCase(), attrs: attrs }; } }, {"after":10,"component/domify":176,"component/each":79,"emitter":17}], 176: [function(require, module, exports) { /** * Expose `parse`. */ module.exports = parse; /** * Tests for browser support. */ var div = document.createElement('div'); // Setup div.innerHTML = ' <link/><table></table><a href="/a">a</a><input type="checkbox"/>'; // Make sure that link elements get serialized correctly by innerHTML // This requires a wrapper element in IE var innerHTMLBug = !div.getElementsByTagName('link').length; div = undefined; /** * Wrap map from jquery. */ var map = { legend: [1, '<fieldset>', '</fieldset>'], tr: [2, '<table><tbody>', '</tbody></table>'], col: [2, '<table><tbody></tbody><colgroup>', '</colgroup></table>'], // for script/link/style tags to work in IE6-8, you have to wrap // in a div with a non-whitespace character in front, ha! _default: innerHTMLBug ? [1, 'X<div>', '</div>'] : [0, '', ''] }; map.td = map.th = [3, '<table><tbody><tr>', '</tr></tbody></table>']; map.option = map.optgroup = [1, '<select multiple="multiple">', '</select>']; map.thead = map.tbody = map.colgroup = map.caption = map.tfoot = [1, '<table>', '</table>']; map.text = map.circle = map.ellipse = map.line = map.path = map.polygon = map.polyline = map.rect = [1, '<svg xmlns="http://www.w3.org/2000/svg" version="1.1">','</svg>']; /** * Parse `html` and return a DOM Node instance, which could be a TextNode, * HTML DOM Node of some kind (<div> for example), or a DocumentFragment * instance, depending on the contents of the `html` string. * * @param {String} html - HTML string to "domify" * @param {Document} doc - The `document` instance to create the Node for * @return {DOMNode} the TextNode, DOM Node, or DocumentFragment instance * @api private */ function parse(html, doc) { if ('string' != typeof html) throw new TypeError('String expected'); // default to the global `document` object if (!doc) doc = document; // tag name var m = /<([\w:]+)/.exec(html); if (!m) return doc.createTextNode(html); html = html.replace(/^\s+|\s+$/g, ''); // Remove leading/trailing whitespace var tag = m[1]; // body support if (tag == 'body') { var el = doc.createElement('html'); el.innerHTML = html; return el.removeChild(el.lastChild); } // wrap map var wrap = map[tag] || map._default; var depth = wrap[0]; var prefix = wrap[1]; var suffix = wrap[2]; var el = doc.createElement('div'); el.innerHTML = prefix + html + suffix; while (depth--) el = el.lastChild; // one element if (el.firstChild == el.lastChild) { return el.removeChild(el.firstChild); } // several elements var fragment = doc.createDocumentFragment(); while (el.firstChild) { fragment.appendChild(el.removeChild(el.firstChild)); } return fragment; } }, {}], 164: [function(require, module, exports) { var bind = require('bind') , bindAll = require('bind-all'); /** * Expose `bind`. */ module.exports = exports = bind; /** * Expose `bindAll`. */ exports.all = bindAll; /** * Expose `bindMethods`. */ exports.methods = bindMethods; /** * Bind `methods` on `obj` to always be called with the `obj` as context. * * @param {Object} obj * @param {String} methods... */ function bindMethods (obj, methods) { methods = [].slice.call(arguments, 1); for (var i = 0, method; method = methods[i]; i++) { obj[method] = bind(obj, obj[method]); } return obj; } }, {"bind":33,"bind-all":34}], 165: [function(require, module, exports) { if ('undefined' == typeof window) { module.exports = require('./lib/debug'); } else { module.exports = require('./debug'); } }, {"./lib/debug":177,"./debug":178}], 177: [function(require, module, exports) { /** * Module dependencies. */ var tty = require('tty'); /** * Expose `debug()` as the module. */ module.exports = debug; /** * Enabled debuggers. */ var names = [] , skips = []; (process.env.DEBUG || '') .split(/[\s,]+/) .forEach(function(name){ name = name.replace('*', '.*?'); if (name[0] === '-') { skips.push(new RegExp('^' + name.substr(1) + '$')); } else { names.push(new RegExp('^' + name + '$')); } }); /** * Colors. */ var colors = [6, 2, 3, 4, 5, 1]; /** * Previous debug() call. */ var prev = {}; /** * Previously assigned color. */ var prevColor = 0; /** * Is stdout a TTY? Colored output is disabled when `true`. */ var isatty = tty.isatty(2); /** * Select a color. * * @return {Number} * @api private */ function color() { return colors[prevColor++ % colors.length]; } /** * Humanize the given `ms`. * * @param {Number} m * @return {String} * @api private */ function humanize(ms) { var sec = 1000 , min = 60 * 1000 , hour = 60 * min; if (ms >= hour) return (ms / hour).toFixed(1) + 'h'; if (ms >= min) return (ms / min).toFixed(1) + 'm'; if (ms >= sec) return (ms / sec | 0) + 's'; return ms + 'ms'; } /** * Create a debugger with the given `name`. * * @param {String} name * @return {Type} * @api public */ function debug(name) { function disabled(){} disabled.enabled = false; var match = skips.some(function(re){ return re.test(name); }); if (match) return disabled; match = names.some(function(re){ return re.test(name); }); if (!match) return disabled; var c = color(); function colored(fmt) { fmt = coerce(fmt); var curr = new Date; var ms = curr - (prev[name] || curr); prev[name] = curr; fmt = ' \u001b[9' + c + 'm' + name + ' ' + '\u001b[3' + c + 'm\u001b[90m' + fmt + '\u001b[3' + c + 'm' + ' +' + humanize(ms) + '\u001b[0m'; console.error.apply(this, arguments); } function plain(fmt) { fmt = coerce(fmt); fmt = new Date().toUTCString() + ' ' + name + ' ' + fmt; console.error.apply(this, arguments); } colored.enabled = plain.enabled = true; return isatty || process.env.DEBUG_COLORS ? colored : plain; } /** * Coerce `val`. */ function coerce(val) { if (val instanceof Error) return val.stack || val.message; return val; } }, {}], 178: [function(require, module, exports) { /** * Expose `debug()` as the module. */ module.exports = debug; /** * Create a debugger with the given `name`. * * @param {String} name * @return {Type} * @api public */ function debug(name) { if (!debug.enabled(name)) return function(){}; return function(fmt){ fmt = coerce(fmt); var curr = new Date; var ms = curr - (debug[name] || curr); debug[name] = curr; fmt = name + ' ' + fmt + ' +' + debug.humanize(ms); // This hackery is required for IE8 // where `console.log` doesn't have 'apply' window.console && console.log && Function.prototype.apply.call(console.log, console, arguments); } } /** * The currently active debug mode names. */ debug.names = []; debug.skips = []; /** * Enables a debug mode by name. This can include modes * separated by a colon and wildcards. * * @param {String} name * @api public */ debug.enable = function(name) { try { localStorage.debug = name; } catch(e){} var split = (name || '').split(/[\s,]+/) , len = split.length; for (var i = 0; i < len; i++) { name = split[i].replace('*', '.*?'); if (name[0] === '-') { debug.skips.push(new RegExp('^' + name.substr(1) + '$')); } else { debug.names.push(new RegExp('^' + name + '$')); } } }; /** * Disable debug output. * * @api public */ debug.disable = function(){ debug.enable(''); }; /** * Humanize the given `ms`. * * @param {Number} m * @return {String} * @api private */ debug.humanize = function(ms) { var sec = 1000 , min = 60 * 1000 , hour = 60 * min; if (ms >= hour) return (ms / hour).toFixed(1) + 'h'; if (ms >= min) return (ms / min).toFixed(1) + 'm'; if (ms >= sec) return (ms / sec | 0) + 's'; return ms + 'ms'; }; /** * Returns true if the given mode name is enabled, false otherwise. * * @param {String} name * @return {Boolean} * @api public */ debug.enabled = function(name) { for (var i = 0, len = debug.skips.length; i < len; i++) { if (debug.skips[i].test(name)) { return false; } } for (var i = 0, len = debug.names.length; i < len; i++) { if (debug.names[i].test(name)) { return true; } } return false; }; /** * Coerce `val`. */ function coerce(val) { if (val instanceof Error) return val.stack || val.message; return val; } // persist try { if (window.localStorage) debug.enable(localStorage.debug); } catch(e){} }, {}], 166: [function(require, module, exports) { /** * Generate a slug from the given `str`. * * example: * * generate('foo bar'); * // > foo-bar * * @param {String} str * @param {Object} options * @config {String|RegExp} [replace] characters to replace, defaulted to `/[^a-z0-9]/g` * @config {String} [separator] separator to insert, defaulted to `-` * @return {String} */ module.exports = function (str, options) { options || (options = {}); return str.toLowerCase() .replace(options.replace || /[^a-z0-9]/g, ' ') .replace(/^ +| +$/g, '') .replace(/ +/g, options.separator || '-') }; }, {}], 160: [function(require, module, exports) { var toSpace = require('to-space-case'); /** * Expose `toSnakeCase`. */ module.exports = toSnakeCase; /** * Convert a `string` to snake case. * * @param {String} string * @return {String} */ function toSnakeCase (string) { return toSpace(string).replace(/\s/g, '_'); } }, {"to-space-case":179}], 179: [function(require, module, exports) { var clean = require('to-no-case'); /** * Expose `toSpaceCase`. */ module.exports = toSpaceCase; /** * Convert a `string` to space case. * * @param {String} string * @return {String} */ function toSpaceCase (string) { return clean(string).replace(/[\W_]+(.|$)/g, function (matches, match) { return match ? ' ' + match : ''; }); } }, {"to-no-case":69}], 161: [function(require, module, exports) { /** * Protocol. */ module.exports = function (url) { switch (arguments.length) { case 0: return check(); case 1: return transform(url); } }; /** * Transform a protocol-relative `url` to the use the proper protocol. * * @param {String} url * @return {String} */ function transform (url) { return check() ? 'https:' + url : 'http:' + url; } /** * Check whether `https:` be used for loading scripts. * * @return {Boolean} */ function check () { return ( location.protocol == 'https:' || location.protocol == 'chrome-extension:' ); } }, {}], 84: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('segmentio/analytics.js-integration'); var onbody = require('on-body'); var domify = require('domify'); var Queue = require('queue'); var each = require('each'); /** * HOP */ var has = Object.prototype.hasOwnProperty; /** * Script loader queue. */ var q = new Queue({ concurrency: 1, timeout: 2000 }); /** * Expose `AdWords`. */ var AdWords = module.exports = integration('AdWords') .option('conversionId', '') .option('remarketing', false) .tag('conversion', '<script src="//www.googleadservices.com/pagead/conversion.js">') .mapping('events'); /** * Load. * * @param {Function} fn * @api public */ AdWords.prototype.initialize = function(){ onbody(this.ready); }; /** * Loaded. * * @return {Boolean} * @api public */ AdWords.prototype.loaded = function(){ return !! document.body; }; /** * Page. * * https://support.google.com/adwords/answer/3111920#standard_parameters * * @param {Page} page */ AdWords.prototype.page = function(page){ var remarketing = this.options.remarketing; var id = this.options.conversionId; if (remarketing) this.remarketing(id); }; /** * Track. * * @param {Track} * @api public */ AdWords.prototype.track = function(track){ var id = this.options.conversionId; var events = this.events(track.event()); var revenue = track.revenue() || 0; var self = this; each(events, function(label){ self.conversion({ conversionId: id, value: revenue, label: label, }); }); }; /** * Report AdWords conversion. * * @param {Object} obj * @param {Function} [fn] * @api private */ AdWords.prototype.conversion = function(obj, fn){ this.enqueue({ google_conversion_id: obj.conversionId, google_conversion_language: 'en', google_conversion_format: '3', google_conversion_color: 'ffffff', google_conversion_label: obj.label, google_conversion_value: obj.value, google_remarketing_only: false }, fn); }; /** * Add remarketing. * * @param {String} id Conversion ID * @api private */ AdWords.prototype.remarketing = function(id){ this.enqueue({ google_conversion_id: id, google_remarketing_only: true }); }; /** * Queue external call. * * @param {Object} obj * @param {Function} [fn] */ AdWords.prototype.enqueue = function(obj, fn){ this.debug('sending %o', obj); var self = this; q.push(function(next){ self.globalize(obj); self.shim(); self.load('conversion', function(){ if (fn) fn(); next(); }); }); }; /** * Set global variables. * * @param {Object} obj */ AdWords.prototype.globalize = function(obj){ for (var name in obj) { if (obj.hasOwnProperty(name)) { window[name] = obj[name]; } } }; /** * Shim for `document.write`. * * @api private */ AdWords.prototype.shim = function(){ var self = this; var write = document.write; document.write = append; function append(str){ var el = domify(str); if (!el.src) return write(str); if (!/googleadservices/.test(el.src)) return write(str); self.debug('append %o', el); document.body.appendChild(el); document.write = write; } } }, {"segmentio/analytics.js-integration":159,"on-body":180,"domify":181,"queue":182,"each":5}], 180: [function(require, module, exports) { var each = require('each'); /** * Cache whether `<body>` exists. */ var body = false; /** * Callbacks to call when the body exists. */ var callbacks = []; /** * Export a way to add handlers to be invoked once the body exists. * * @param {Function} callback A function to call when the body exists. */ module.exports = function onBody (callback) { if (body) { call(callback); } else { callbacks.push(callback); } }; /** * Set an interval to check for `document.body`. */ var interval = setInterval(function () { if (!document.body) return; body = true; each(callbacks, call); clearInterval(interval); }, 5); /** * Call a callback, passing it the body. * * @param {Function} callback The callback to call. */ function call (callback) { callback(document.body); } }, {"each":79}], 181: [function(require, module, exports) { /** * Expose `parse`. */ module.exports = parse; /** * Wrap map from jquery. */ var map = { legend: [1, '<fieldset>', '</fieldset>'], tr: [2, '<table><tbody>', '</tbody></table>'], col: [2, '<table><tbody></tbody><colgroup>', '</colgroup></table>'], _default: [0, '', ''] }; map.td = map.th = [3, '<table><tbody><tr>', '</tr></tbody></table>']; map.option = map.optgroup = [1, '<select multiple="multiple">', '</select>']; map.thead = map.tbody = map.colgroup = map.caption = map.tfoot = [1, '<table>', '</table>']; map.text = map.circle = map.ellipse = map.line = map.path = map.polygon = map.polyline = map.rect = [1, '<svg xmlns="http://www.w3.org/2000/svg" version="1.1">','</svg>']; /** * Parse `html` and return the children. * * @param {String} html * @return {Array} * @api private */ function parse(html) { if ('string' != typeof html) throw new TypeError('String expected'); html = html.replace(/^\s+|\s+$/g, ''); // Remove leading/trailing whitespace // tag name var m = /<([\w:]+)/.exec(html); if (!m) return document.createTextNode(html); var tag = m[1]; // body support if (tag == 'body') { var el = document.createElement('html'); el.innerHTML = html; return el.removeChild(el.lastChild); } // wrap map var wrap = map[tag] || map._default; var depth = wrap[0]; var prefix = wrap[1]; var suffix = wrap[2]; var el = document.createElement('div'); el.innerHTML = prefix + html + suffix; while (depth--) el = el.lastChild; // one element if (el.firstChild == el.lastChild) { return el.removeChild(el.firstChild); } // several elements var fragment = document.createDocumentFragment(); while (el.firstChild) { fragment.appendChild(el.removeChild(el.firstChild)); } return fragment; } }, {}], 182: [function(require, module, exports) { /** * Module dependencies. */ var Emitter; var bind; try { Emitter = require('emitter'); bind = require('bind'); } catch (err) { Emitter = require('component-emitter'); bind = require('component-bind'); } /** * Expose `Queue`. */ module.exports = Queue; /** * Initialize a `Queue` with the given options: * * - `concurrency` [1] * - `timeout` [0] * * @param {Object} options * @api public */ function Queue(options) { options = options || {}; this.timeout = options.timeout || 0; this.concurrency = options.concurrency || 1; this.pending = 0; this.jobs = []; } /** * Mixin emitter. */ Emitter(Queue.prototype); /** * Return queue length. * * @return {Number} * @api public */ Queue.prototype.length = function(){ return this.pending + this.jobs.length; }; /** * Queue `fn` for execution. * * @param {Function} fn * @param {Function} [cb] * @api public */ Queue.prototype.push = function(fn, cb){ this.jobs.push([fn, cb]); setTimeout(bind(this, this.run), 0); }; /** * Run jobs at the specified concurrency. * * @api private */ Queue.prototype.run = function(){ while (this.pending < this.concurrency) { var job = this.jobs.shift(); if (!job) break; this.exec(job); } }; /** * Execute `job`. * * @param {Array} job * @api private */ Queue.prototype.exec = function(job){ var self = this; var ms = this.timeout; var fn = job[0]; var cb = job[1]; if (ms) fn = timeout(fn, ms); this.pending++; fn(function(err, res){ cb && cb(err, res); self.pending--; self.run(); }); }; /** * Decorate `fn` with a timeout of `ms`. * * @param {Function} fn * @param {Function} ms * @return {Function} * @api private */ function timeout(fn, ms) { return function(cb){ var done; var id = setTimeout(function(){ done = true; var err = new Error('Timeout of ' + ms + 'ms exceeded'); err.timeout = timeout; cb(err); }, ms); fn(function(err, res){ if (done) return; clearTimeout(id); cb(err, res); }); } } }, {"emitter":183,"bind":33,"component-emitter":183,"component-bind":33}], 183: [function(require, module, exports) { /** * Expose `Emitter`. */ module.exports = Emitter; /** * Initialize a new `Emitter`. * * @api public */ function Emitter(obj) { if (obj) return mixin(obj); }; /** * Mixin the emitter properties. * * @param {Object} obj * @return {Object} * @api private */ function mixin(obj) { for (var key in Emitter.prototype) { obj[key] = Emitter.prototype[key]; } return obj; } /** * Listen on the given `event` with `fn`. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.on = Emitter.prototype.addEventListener = function(event, fn){ this._callbacks = this._callbacks || {}; (this._callbacks[event] = this._callbacks[event] || []) .push(fn); return this; }; /** * Adds an `event` listener that will be invoked a single * time then automatically removed. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.once = function(event, fn){ var self = this; this._callbacks = this._callbacks || {}; function on() { self.off(event, on); fn.apply(this, arguments); } on.fn = fn; this.on(event, on); return this; }; /** * Remove the given callback for `event` or all * registered callbacks. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.off = Emitter.prototype.removeListener = Emitter.prototype.removeAllListeners = Emitter.prototype.removeEventListener = function(event, fn){ this._callbacks = this._callbacks || {}; // all if (0 == arguments.length) { this._callbacks = {}; return this; } // specific event var callbacks = this._callbacks[event]; if (!callbacks) return this; // remove all handlers if (1 == arguments.length) { delete this._callbacks[event]; return this; } // remove specific handler var cb; for (var i = 0; i < callbacks.length; i++) { cb = callbacks[i]; if (cb === fn || cb.fn === fn) { callbacks.splice(i, 1); break; } } return this; }; /** * Emit `event` with the given args. * * @param {String} event * @param {Mixed} ... * @return {Emitter} */ Emitter.prototype.emit = function(event){ this._callbacks = this._callbacks || {}; var args = [].slice.call(arguments, 1) , callbacks = this._callbacks[event]; if (callbacks) { callbacks = callbacks.slice(0); for (var i = 0, len = callbacks.length; i < len; ++i) { callbacks[i].apply(this, args); } } return this; }; /** * Return array of callbacks for `event`. * * @param {String} event * @return {Array} * @api public */ Emitter.prototype.listeners = function(event){ this._callbacks = this._callbacks || {}; return this._callbacks[event] || []; }; /** * Check if this emitter has `event` handlers. * * @param {String} event * @return {Boolean} * @api public */ Emitter.prototype.hasListeners = function(event){ return !! this.listeners(event).length; }; }, {}], 85: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('segmentio/analytics.js-integration'); /** * Expose Alexa integration. */ var Alexa = module.exports = integration('Alexa') .assumesPageview() .global('_atrk_opts') .option('account', null) .option('domain', '') .option('dynamic', true) .tag('<script src="//d31qbv1cthcecs.cloudfront.net/atrk.js">'); /** * Initialize. * * @param {Object} page */ Alexa.prototype.initialize = function(page){ var self = this; window._atrk_opts = { atrk_acct: this.options.account, domain: this.options.domain, dynamic: this.options.dynamic }; this.load(function(){ window.atrk(); self.ready(); }); }; /** * Loaded? * * @return {Boolean} */ Alexa.prototype.loaded = function(){ return !! window.atrk; }; }, {"segmentio/analytics.js-integration":159}], 86: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('segmentio/analytics.js-integration'); /** * Expose `Amplitude` integration. */ var Amplitude = module.exports = integration('Amplitude') .assumesPageview() .global('amplitude') .option('apiKey', '') .option('trackAllPages', false) .option('trackNamedPages', true) .option('trackCategorizedPages', true) .tag('<script src="https://d24n15hnbwhuhn.cloudfront.net/libs/amplitude-1.1-min.js">'); /** * Initialize. * * https://github.com/amplitude/Amplitude-Javascript * * @param {Object} page */ Amplitude.prototype.initialize = function(page){ (function(e,t){var r=e.amplitude||{}; r._q=[];function i(e){r[e]=function(){r._q.push([e].concat(Array.prototype.slice.call(arguments,0)));};} var s=["init","logEvent","setUserId","setGlobalUserProperties","setVersionName","setDomain"]; for (var c=0;c<s.length;c++){i(s[c]);}e.amplitude=r;})(window,document); window.amplitude.init(this.options.apiKey); this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Amplitude.prototype.loaded = function(){ return !! (window.amplitude && window.amplitude.options); }; /** * Page. * * @param {Page} page */ Amplitude.prototype.page = function(page){ var properties = page.properties(); var category = page.category(); var name = page.fullName(); var opts = this.options; // all pages if (opts.trackAllPages) { this.track(page.track()); } // categorized pages if (category && opts.trackCategorizedPages) { this.track(page.track(category)); } // named pages if (name && opts.trackNamedPages) { this.track(page.track(name)); } }; /** * Identify. * * @param {Facade} identify */ Amplitude.prototype.identify = function(identify){ var id = identify.userId(); var traits = identify.traits(); if (id) window.amplitude.setUserId(id); if (traits) window.amplitude.setGlobalUserProperties(traits); }; /** * Track. * * @param {Track} event */ Amplitude.prototype.track = function(track){ var props = track.properties(); var event = track.event(); window.amplitude.logEvent(event, props); }; }, {"segmentio/analytics.js-integration":159}], 87: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('segmentio/analytics.js-integration'); var load = require('load-script'); var is = require('is'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(Appcues); }; /** * Expose `Appcues` integration. */ var Appcues = exports.Integration = integration('Appcues') .assumesPageview() .global('Appcues') .global('AppcuesIdentity') .option('appcuesId', '') .option('userId', '') .option('userEmail', ''); /** * Initialize. * * http://appcues.com/docs/ * * @param {Object} */ Appcues.prototype.initialize = function(){ this.load(function() { window.Appcues.init(); }); }; /** * Loaded? * * @return {Boolean} */ Appcues.prototype.loaded = function(){ return is.object(window.Appcues); }; /** * Load the Appcues library. * * @param {Function} callback */ Appcues.prototype.load = function(callback){ var script = load('//d2dubfq97s02eu.cloudfront.net/appcues-bundle.min.js', callback); script.setAttribute('data-appcues-id', this.options.appcuesId); script.setAttribute('data-user-id', this.options.userId); script.setAttribute('data-user-email', this.options.userEmail); }; /** * Identify. * * http://appcues.com/docs#identify * * @param {Identify} identify */ Appcues.prototype.identify = function(identify){ window.Appcues.identify(identify.traits()); }; }, {"segmentio/analytics.js-integration":159,"load-script":168,"is":18}], 88: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('segmentio/analytics.js-integration'); var each = require('each'); /** * Expose `Awesm` integration. */ var Awesm = module.exports = integration('awe.sm') .assumesPageview() .global('AWESM') .option('apiKey', '') .tag('<script src="//widgets.awe.sm/v3/widgets.js?key={{ apiKey }}&async=true">') .mapping('events'); /** * Initialize. * * http://developers.awe.sm/guides/javascript/ * * @param {Object} page */ Awesm.prototype.initialize = function(page){ window.AWESM = { api_key: this.options.apiKey }; this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Awesm.prototype.loaded = function(){ return !! (window.AWESM && window.AWESM._exists); }; /** * Track. * * @param {Track} track */ Awesm.prototype.track = function(track){ var user = this.analytics.user(); var goals = this.events(track.event()); each(goals, function(goal){ window.AWESM.convert(goal, track.cents(), null, user.id()); }); }; }, {"segmentio/analytics.js-integration":159,"each":5}], 89: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('segmentio/analytics.js-integration'); var is = require('is'); var noop = function(){}; var onBody = require('on-body'); /** * Expose `Awesomatic` integration. */ var Awesomatic = module.exports = integration('Awesomatic') .assumesPageview() .global('Awesomatic') .global('AwesomaticSettings') .global('AwsmSetup') .global('AwsmTmp') .option('appId', '') .tag('<script src="https://1c817b7a15b6941337c0-dff9b5f4adb7ba28259631e99c3f3691.ssl.cf2.rackcdn.com/gen/embed.js">'); /** * Initialize. * * @param {Object} page */ Awesomatic.prototype.initialize = function(page){ var self = this; var user = this.analytics.user(); var id = user.id(); var options = user.traits(); options.appId = this.options.appId; if (id) options.user_id = id; this.load(function(){ window.Awesomatic.initialize(options, function(){ self.ready(); // need to wait for initialize to callback }); }); }; /** * Loaded? * * @return {Boolean} */ Awesomatic.prototype.loaded = function(){ return is.object(window.Awesomatic); }; }, {"segmentio/analytics.js-integration":159,"is":18,"on-body":180}], 90: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('segmentio/analytics.js-integration'); var onbody = require('on-body'); var domify = require('domify'); var extend = require('extend'); var bind = require('bind'); var when = require('when'); var each = require('each'); /** * HOP. */ var has = Object.prototype.hasOwnProperty; /** * Noop. */ var noop = function(){}; /** * Expose `Bing`. * * https://bingads.microsoft.com/campaign/signup */ var Bing = module.exports = integration('Bing Ads') .option('siteId', '') .option('domainId', '') .tag('<script id="mstag_tops" src="//flex.msn.com/mstag/site/{{ siteId }}/mstag.js">') .mapping('events'); /** * Initialize. * * http://msdn.microsoft.com/en-us/library/bing-ads-campaign-management-campaign-analytics-scripts.aspx * * @param {Object} page */ Bing.prototype.initialize = function(page){ if (!window.mstag) { window.mstag = { loadTag: noop, time: (new Date()).getTime(), // they use document.write, which doesn't work when loaded async. // they provide a way to override it. // the first time it is called, load the script, // and only when that script is done, is "loading" done. _write: writeToAppend }; }; var self = this; onbody(function(){ self.load(function(){ var loaded = bind(self, self.loaded); // poll until this.loaded() is true. // have to do a weird hack like this because // the first script loads a second script, // and only after the second script is it actually loaded. when(loaded, self.ready); }); }); }; /** * Loaded? * * @return {Boolean} */ Bing.prototype.loaded = function(){ return !! (window.mstag && window.mstag.loadTag !== noop); }; /** * Track. * * @param {Track} track */ Bing.prototype.track = function(track){ var events = this.events(track.event()); var revenue = track.revenue() || 0; var self = this; each(events, function(goal){ window.mstag.loadTag('analytics', { domainId: self.options.domainId, revenue: revenue, dedup: '1', type: '1', actionid: goal }); }); }; /** * Convert `document.write` to `document.appendChild`. * * TODO: make into a component. * * @param {String} str */ function writeToAppend(str) { var first = document.getElementsByTagName('script')[0]; var el = domify(str); // https://github.com/component/domify/issues/14 if ('script' == el.tagName.toLowerCase() && el.getAttribute('src')) { var tmp = document.createElement('script'); tmp.src = el.getAttribute('src'); tmp.async = true; el = tmp; } document.body.appendChild(el); } }, {"segmentio/analytics.js-integration":159,"on-body":180,"domify":181,"extend":40,"bind":33,"when":184,"each":5}], 184: [function(require, module, exports) { var callback = require('callback'); /** * Expose `when`. */ module.exports = when; /** * Loop on a short interval until `condition()` is true, then call `fn`. * * @param {Function} condition * @param {Function} fn * @param {Number} interval (optional) */ function when (condition, fn, interval) { if (condition()) return callback.async(fn); var ref = setInterval(function () { if (!condition()) return; callback(fn); clearInterval(ref); }, interval || 10); } }, {"callback":12}], 91: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('segmentio/analytics.js-integration'); var Identify = require('facade').Identify; var Track = require('facade').Track; var pixel = require('load-pixel')('http://app.bronto.com/public/'); var qs = require('querystring'); var each = require('each'); /** * Expose `Bronto` integration. */ var Bronto = module.exports = integration('Bronto') .global('__bta') .option('siteId', '') .option('host', '') .tag('<script src="//p.bm23.com/bta.js">'); /** * Initialize. * * http://app.bronto.com/mail/help/help_view/?k=mail:home:api_tracking:tracking_data_store_js#addingjavascriptconversiontrackingtoyoursite * http://bronto.com/product-blog/features/using-conversion-tracking-private-domain#.Ut_Vk2T8KqB * http://bronto.com/product-blog/features/javascript-conversion-tracking-setup-and-reporting#.Ut_VhmT8KqB * * @param {Object} page */ Bronto.prototype.initialize = function(page){ var self = this; var params = qs.parse(window.location.search); if (!params._bta_tid && !params._bta_c) { this.debug('missing tracking URL parameters `_bta_tid` and `_bta_c`.'); } this.load(function(){ var opts = self.options; self.bta = new window.__bta(opts.siteId); if (opts.host) self.bta.setHost(opts.host); self.ready(); }); }; /** * Loaded? * * @return {Boolean} */ Bronto.prototype.loaded = function(){ return this.bta; }; /** * Track. * * The JS conversion tracking toggles must be on * in the application in order for you to see the data * in your account, and for it to function as it should. * If the toggle is not on the system will ignore * any requests coming into it. * * To create a test user, create a contact in Bronto, * send that contact an email, then process through your site * to place a test order to hit the JS code. * * Provided you have Click Through Link Tracking enabled, * when a contact clicks a link contained in an email you send them via Bronto, * we create a tracking cookie (most commonly used for tracking conversions). * * https://app.bronto.com/mail/help/help_view/?k=mail:home:api_tracking:tracking_url_parameters * * @param {Track} event */ Bronto.prototype.track = function(track){ var revenue = track.revenue(); var event = track.event(); var type = 'number' == typeof revenue ? '$' : 't'; this.bta.addConversionLegacy(type, event, revenue); }; /** * Completed order. * * The cookie is used to link the order being processed back to the delivery, * message, and contact which makes it a conversion. * Passing in just the email ensures that the order itself * gets linked to the contact record in Bronto even if the user * does not have a tracking cookie. * * @param {Track} track * @api private */ Bronto.prototype.completedOrder = function(track){ var user = this.analytics.user(); var products = track.products(); var props = track.properties(); var items = []; var identify = new Identify({ userId: user.id(), traits: user.traits() }); var email = identify.email(); // items each(products, function(product){ var track = new Track({ properties: product }); items.push({ item_id: track.id() || track.sku(), desc: product.description || track.name(), quantity: track.quantity(), amount: track.price(), }); }); // add conversion this.bta.addOrder({ order_id: track.orderId(), email: email, // they recommend not putting in a date // because it needs to be formatted correctly // YYYY-MM-DDTHH:MM:SS items: items }); }; }, {"segmentio/analytics.js-integration":159,"facade":27,"load-pixel":185,"querystring":186,"each":5}], 185: [function(require, module, exports) { /** * Module dependencies. */ var stringify = require('querystring').stringify; var sub = require('substitute'); /** * Factory function to create a pixel loader. * * @param {String} path * @return {Function} * @api public */ module.exports = function(path){ return function(query, obj, fn){ if ('function' == typeof obj) fn = obj, obj = {}; obj = obj || {}; fn = fn || function(){}; var url = sub(path, obj); var img = new Image; img.onerror = error(fn, 'failed to load pixel', img); img.onload = function(){ fn(); }; query = stringify(query); if (query) query = '?' + query; img.src = url + query; img.width = 1; img.height = 1; return img; }; }; /** * Create an error handler. * * @param {Fucntion} fn * @param {String} message * @param {Image} img * @return {Function} * @api private */ function error(fn, message, img){ return function(e){ e = e || window.event; var err = new Error(message); err.event = e; err.source = img; fn(err); }; } }, {"querystring":186,"substitute":187}], 186: [function(require, module, exports) { /** * Module dependencies. */ var encode = encodeURIComponent; var decode = decodeURIComponent; var trim = require('trim'); var type = require('type'); /** * Parse the given query `str`. * * @param {String} str * @return {Object} * @api public */ exports.parse = function(str){ if ('string' != typeof str) return {}; str = trim(str); if ('' == str) return {}; if ('?' == str.charAt(0)) str = str.slice(1); var obj = {}; var pairs = str.split('&'); for (var i = 0; i < pairs.length; i++) { var parts = pairs[i].split('='); var key = decode(parts[0]); var m; if (m = /(\w+)\[(\d+)\]/.exec(key)) { obj[m[1]] = obj[m[1]] || []; obj[m[1]][m[2]] = decode(parts[1]); continue; } obj[parts[0]] = null == parts[1] ? '' : decode(parts[1]); } return obj; }; /** * Stringify the given `obj`. * * @param {Object} obj * @return {String} * @api public */ exports.stringify = function(obj){ if (!obj) return ''; var pairs = []; for (var key in obj) { var value = obj[key]; if ('array' == type(value)) { for (var i = 0; i < value.length; ++i) { pairs.push(encode(key + '[' + i + ']') + '=' + encode(value[i])); } continue; } pairs.push(encode(key) + '=' + encode(obj[key])); } return pairs.join('&'); }; }, {"trim":50,"type":35}], 187: [function(require, module, exports) { /** * Expose `substitute` */ module.exports = substitute; /** * Substitute `:prop` with the given `obj` in `str` * * @param {String} str * @param {Object} obj * @param {RegExp} expr * @return {String} * @api public */ function substitute(str, obj, expr){ if (!obj) throw new TypeError('expected an object'); expr = expr || /:(\w+)/g; return str.replace(expr, function(_, prop){ return null != obj[prop] ? obj[prop] : _; }); } }, {}], 92: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('segmentio/analytics.js-integration'); var tick = require('next-tick'); /** * Expose `BugHerd` integration. */ var BugHerd = module.exports = integration('BugHerd') .assumesPageview() .global('BugHerdConfig') .global('_bugHerd') .option('apiKey', '') .option('showFeedbackTab', true) .tag('<script src="//www.bugherd.com/sidebarv2.js?apikey={{ apiKey }}">'); /** * Initialize. * * http://support.bugherd.com/home * * @param {Object} page */ BugHerd.prototype.initialize = function(page){ window.BugHerdConfig = { feedback: { hide: !this.options.showFeedbackTab }}; var ready = this.ready; this.load(function(){ tick(ready); }); }; /** * Loaded? * * @return {Boolean} */ BugHerd.prototype.loaded = function(){ return !! window._bugHerd; }; }, {"segmentio/analytics.js-integration":159,"next-tick":45}], 93: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('segmentio/analytics.js-integration'); var is = require('is'); var extend = require('extend'); var onError = require('on-error'); /** * Expose `Bugsnag` integration. */ var Bugsnag = module.exports = integration('Bugsnag') .global('Bugsnag') .option('apiKey', '') .tag('<script src="//d2wy8f7a9ursnm.cloudfront.net/bugsnag-2.min.js">'); /** * Initialize. * * https://bugsnag.com/docs/notifiers/js * * @param {Object} page */ Bugsnag.prototype.initialize = function(page){ var self = this; this.load(function(){ window.Bugsnag.apiKey = self.options.apiKey; self.ready(); }); }; /** * Loaded? * * @return {Boolean} */ Bugsnag.prototype.loaded = function(){ return is.object(window.Bugsnag); }; /** * Identify. * * @param {Identify} identify */ Bugsnag.prototype.identify = function(identify){ window.Bugsnag.metaData = window.Bugsnag.metaData || {}; extend(window.Bugsnag.metaData, identify.traits()); }; }, {"segmentio/analytics.js-integration":159,"is":18,"extend":40,"on-error":188}], 188: [function(require, module, exports) { /** * Expose `onError`. */ module.exports = onError; /** * Callbacks. */ var callbacks = []; /** * Preserve existing handler. */ if ('function' == typeof window.onerror) callbacks.push(window.onerror); /** * Bind to `window.onerror`. */ window.onerror = handler; /** * Error handler. */ function handler () { for (var i = 0, fn; fn = callbacks[i]; i++) fn.apply(this, arguments); } /** * Call a `fn` on `window.onerror`. * * @param {Function} fn */ function onError (fn) { callbacks.push(fn); if (window.onerror != handler) { callbacks.push(window.onerror); window.onerror = handler; } } }, {}], 94: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('segmentio/analytics.js-integration'); var defaults = require('defaults'); var onBody = require('on-body'); /** * Expose `Chartbeat` integration. */ var Chartbeat = module.exports = integration('Chartbeat') .assumesPageview() .global('_sf_async_config') .global('_sf_endpt') .global('pSUPERFLY') .option('domain', '') .option('uid', null) .tag('<script src="//static.chartbeat.com/js/chartbeat.js">'); /** * Initialize. * * http://chartbeat.com/docs/configuration_variables/ * * @param {Object} page */ Chartbeat.prototype.initialize = function(page){ var self = this; window._sf_async_config = window._sf_async_config || {}; window._sf_async_config.useCanonical = true; defaults(window._sf_async_config, this.options); onBody(function(){ window._sf_endpt = new Date().getTime(); // Note: Chartbeat depends on document.body existing so the script does // not load until that is confirmed. Otherwise it may trigger errors. self.load(self.ready); }); }; /** * Loaded? * * @return {Boolean} */ Chartbeat.prototype.loaded = function(){ return !! window.pSUPERFLY; }; /** * Page. * * http://chartbeat.com/docs/handling_virtual_page_changes/ * * @param {Page} page */ Chartbeat.prototype.page = function(page){ var props = page.properties(); var name = page.fullName(); window.pSUPERFLY.virtualPage(props.path, name || props.title); }; }, {"segmentio/analytics.js-integration":159,"defaults":189,"on-body":180}], 189: [function(require, module, exports) { /** * Expose `defaults`. */ module.exports = defaults; function defaults (dest, defaults) { for (var prop in defaults) { if (! (prop in dest)) { dest[prop] = defaults[prop]; } } return dest; }; }, {}], 95: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('segmentio/analytics.js-integration'); var push = require('global-queue')('_cbq'); var each = require('each'); /** * HOP */ var has = Object.prototype.hasOwnProperty; /** * Supported events */ var supported = { activation: true, changePlan: true, register: true, refund: true, charge: true, cancel: true, login: true }; /** * Expose `ChurnBee` integration. */ var ChurnBee = module.exports = integration('ChurnBee') .global('_cbq') .global('ChurnBee') .option('apiKey', '') .tag('<script src="//api.churnbee.com/cb.js">') .mapping('events'); /** * Initialize. * * https://churnbee.com/docs * * @param {Object} page */ ChurnBee.prototype.initialize = function(page){ push('_setApiKey', this.options.apiKey); this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ ChurnBee.prototype.loaded = function(){ return !! window.ChurnBee; }; /** * Track. * * @param {Track} event */ ChurnBee.prototype.track = function(track){ var event = track.event(); var events = this.events(event); events.push(event); each(events, function(event){ if (true != supported[event]) return; push(event, track.properties({ revenue: 'amount' })); }); }; }, {"segmentio/analytics.js-integration":159,"global-queue":190,"each":5}], 190: [function(require, module, exports) { /** * Expose `generate`. */ module.exports = generate; /** * Generate a global queue pushing method with `name`. * * @param {String} name * @param {Object} options * @property {Boolean} wrap * @return {Function} */ function generate (name, options) { options = options || {}; return function (args) { args = [].slice.call(arguments); window[name] || (window[name] = []); options.wrap === false ? window[name].push.apply(window[name], args) : window[name].push(args); }; } }, {}], 96: [function(require, module, exports) { /** * Module dependencies. */ var date = require('load-date'); var domify = require('domify'); var each = require('each'); var integration = require('segmentio/analytics.js-integration'); var is = require('is'); var useHttps = require('use-https'); var onBody = require('on-body'); /** * Expose `ClickTale` integration. */ var ClickTale = module.exports = integration('ClickTale') .assumesPageview() .global('WRInitTime') .global('ClickTale') .global('ClickTaleSetUID') .global('ClickTaleField') .global('ClickTaleEvent') .option('httpCdnUrl', 'http://s.clicktale.net/WRe0.js') .option('httpsCdnUrl', '') .option('projectId', '') .option('recordingRatio', 0.01) .option('partitionId', '') .tag('<script src="{{src}}">'); /** * Initialize. * * http://wiki.clicktale.com/Article/JavaScript_API * * @param {Object} page */ ClickTale.prototype.initialize = function(page){ var self = this; window.WRInitTime = date.getTime(); onBody(function(body){ body.appendChild(domify('<div id="ClickTaleDiv" style="display: none;">')); }); var http = this.options.httpCdnUrl; var https = this.options.httpsCdnUrl; if (useHttps() && !https) return this.debug('https option required'); var src = useHttps() ? https : http; this.load({ src: src }, function(){ window.ClickTale( self.options.projectId, self.options.recordingRatio, self.options.partitionId ); self.ready(); }); }; /** * Loaded? * * @return {Boolean} */ ClickTale.prototype.loaded = function(){ return is.fn(window.ClickTale); }; /** * Identify. * * http://wiki.clicktale.com/Article/ClickTaleTag#ClickTaleSetUID * http://wiki.clicktale.com/Article/ClickTaleTag#ClickTaleField * * @param {Identify} identify */ ClickTale.prototype.identify = function(identify){ var id = identify.userId(); window.ClickTaleSetUID(id); each(identify.traits(), function(key, value){ window.ClickTaleField(key, value); }); }; /** * Track. * * http://wiki.clicktale.com/Article/ClickTaleTag#ClickTaleEvent * * @param {Track} track */ ClickTale.prototype.track = function(track){ window.ClickTaleEvent(track.event()); }; }, {"load-date":191,"domify":181,"each":5,"segmentio/analytics.js-integration":159,"is":18,"use-https":161,"on-body":180}], 191: [function(require, module, exports) { /* * Load date. * * For reference: http://www.html5rocks.com/en/tutorials/webperformance/basics/ */ var time = new Date() , perf = window.performance; if (perf && perf.timing && perf.timing.responseEnd) { time = new Date(perf.timing.responseEnd); } module.exports = time; }, {}], 97: [function(require, module, exports) { /** * Module dependencies. */ var Identify = require('facade').Identify; var extend = require('extend'); var integration = require('segmentio/analytics.js-integration'); var is = require('is'); /** * Expose `Clicky` integration. */ var Clicky = module.exports = integration('Clicky') .assumesPageview() .global('clicky') .global('clicky_site_ids') .global('clicky_custom') .option('siteId', null) .tag('<script src="//static.getclicky.com/js"></script>'); /** * Initialize. * * http://clicky.com/help/customization * * @param {Object} page */ Clicky.prototype.initialize = function(page){ var user = this.analytics.user(); window.clicky_site_ids = window.clicky_site_ids || [this.options.siteId]; this.identify(new Identify({ userId: user.id(), traits: user.traits() })); this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Clicky.prototype.loaded = function(){ return is.object(window.clicky); }; /** * Page. * * http://clicky.com/help/customization#/help/custom/manual * * @param {Page} page */ Clicky.prototype.page = function(page){ var properties = page.properties(); var category = page.category(); var name = page.fullName(); window.clicky.log(properties.path, name || properties.title); }; /** * Identify. * * @param {Identify} id (optional) */ Clicky.prototype.identify = function(identify){ window.clicky_custom = window.clicky_custom || {}; window.clicky_custom.session = window.clicky_custom.session || {}; extend(window.clicky_custom.session, identify.traits()); }; /** * Track. * * http://clicky.com/help/customization#/help/custom/manual * * @param {Track} event */ Clicky.prototype.track = function(track){ window.clicky.goal(track.event(), track.revenue()); }; }, {"facade":27,"extend":40,"segmentio/analytics.js-integration":159,"is":18}], 98: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('segmentio/analytics.js-integration'); var useHttps = require('use-https'); /** * Expose `Comscore` integration. */ var Comscore = module.exports = integration('comScore') .assumesPageview() .global('_comscore') .global('COMSCORE') .option('c1', '2') .option('c2', '') .tag('http', '<script src="http://b.scorecardresearch.com/beacon.js">') .tag('https', '<script src="https://sb.scorecardresearch.com/beacon.js">'); /** * Initialize. * * @param {Object} page */ Comscore.prototype.initialize = function(page){ window._comscore = window._comscore || [this.options]; var name = useHttps() ? 'https' : 'http'; this.load(name, this.ready); }; /** * Loaded? * * @return {Boolean} */ Comscore.prototype.loaded = function(){ return !! window.COMSCORE; }; }, {"segmentio/analytics.js-integration":159,"use-https":161}], 99: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('segmentio/analytics.js-integration'); /** * Expose `CrazyEgg` integration. */ var CrazyEgg = module.exports = integration('Crazy Egg') .assumesPageview() .global('CE2') .option('accountNumber', '') .tag('<script src="//dnn506yrbagrg.cloudfront.net/pages/scripts/{{ path }}.js?{{ cache }}">'); /** * Initialize. * * @param {Object} page */ CrazyEgg.prototype.initialize = function(page){ var number = this.options.accountNumber; var path = number.slice(0,4) + '/' + number.slice(4); var cache = Math.floor(new Date().getTime() / 3600000); this.load({ path: path, cache: cache }, this.ready); }; /** * Loaded? * * @return {Boolean} */ CrazyEgg.prototype.loaded = function(){ return !! window.CE2; }; }, {"segmentio/analytics.js-integration":159}], 100: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('segmentio/analytics.js-integration'); var push = require('global-queue')('_curebitq'); var Identify = require('facade').Identify; var throttle = require('throttle'); var Track = require('facade').Track; var iso = require('to-iso-string'); var clone = require('clone'); var each = require('each'); var bind = require('bind'); /** * Expose `Curebit` integration. */ var Curebit = module.exports = integration('Curebit') .global('_curebitq') .global('curebit') .option('siteId', '') .option('iframeWidth', '100%') .option('iframeHeight', '480') .option('iframeBorder', 0) .option('iframeId', 'curebit_integration') .option('responsive', true) .option('device', '') .option('insertIntoId', '') .option('campaigns', {}) .option('server', 'https://www.curebit.com') .tag('<script src="//d2jjzw81hqbuqv.cloudfront.net/integration/curebit-1.0.min.js">'); /** * Initialize. * * @param {Object} page */ Curebit.prototype.initialize = function(page){ push('init', { site_id: this.options.siteId, server: this.options.server }); this.load(this.ready); // throttle the call to `page` since curebit needs to append an iframe this.page = throttle(bind(this, this.page), 250); }; /** * Loaded? * * @return {Boolean} */ Curebit.prototype.loaded = function(){ return !!window.curebit; }; /** * Page. * * Call the `register_affiliate` method of the Curebit API that will load a * custom iframe onto the page, only if this page's path is marked as a * campaign. * * http://www.curebit.com/docs/affiliate/registration * * This is throttled to prevent accidentally drawing the iframe multiple times, * from multiple `.page()` calls. The `250` is from the curebit script. * * @param {String} url * @param {String} id * @param {Function} fn * @api private */ Curebit.prototype.injectIntoId = function(url, id, fn){ var server = this.options.server; when(function(){ return document.getElementById(id); }, function(){ var script = document.createElement('script'); script.src = url; var parent = document.getElementById(id); parent.appendChild(script); onload(script, fn); }); }; /** * Campaign tags. * * @param {Page} page */ Curebit.prototype.page = function(page){ var user = this.analytics.user(); var campaigns = this.options.campaigns; var path = window.location.pathname; if (!campaigns[path]) return; var tags = (campaigns[path] || '').split(','); if (!tags.length) return; var settings = { responsive: this.options.responsive, device: this.options.device, campaign_tags: tags, iframe: { width: this.options.iframeWidth, height: this.options.iframeHeight, id: this.options.iframeId, frameborder: this.options.iframeBorder, container: this.options.insertIntoId } }; var identify = new Identify({ userId: user.id(), traits: user.traits() }); // if we have an email, add any information about the user if (identify.email()) { settings.affiliate_member = { email: identify.email(), first_name: identify.firstName(), last_name: identify.lastName(), customer_id: identify.userId() }; } push('register_affiliate', settings); }; /** * Completed order. * * Fire the Curebit `register_purchase` with the order details and items. * * https://www.curebit.com/docs/ecommerce/custom * * @param {Track} track */ Curebit.prototype.completedOrder = function(track){ var user = this.analytics.user(); var orderId = track.orderId(); var products = track.products(); var props = track.properties(); var items = []; var identify = new Identify({ traits: user.traits(), userId: user.id() }); each(products, function(product){ var track = new Track({ properties: product }); items.push({ product_id: track.id() || track.sku(), quantity: track.quantity(), image_url: product.image, price: track.price(), title: track.name(), url: product.url, }); }); push('register_purchase', { order_date: iso(props.date || new Date()), order_number: orderId, coupon_code: track.coupon(), subtotal: track.total(), customer_id: identify.userId(), first_name: identify.firstName(), last_name: identify.lastName(), email: identify.email(), items: items }); }; }, {"segmentio/analytics.js-integration":159,"global-queue":190,"facade":27,"throttle":192,"to-iso-string":193,"clone":194,"each":5,"bind":33}], 192: [function(require, module, exports) { /** * Module exports. */ module.exports = throttle; /** * Returns a new function that, when invoked, invokes `func` at most one time per * `wait` milliseconds. * * @param {Function} func The `Function` instance to wrap. * @param {Number} wait The minimum number of milliseconds that must elapse in between `func` invokations. * @return {Function} A new function that wraps the `func` function passed in. * @api public */ function throttle (func, wait) { var rtn; // return value var last = 0; // last invokation timestamp return function throttled () { var now = new Date().getTime(); var delta = now - last; if (delta >= wait) { rtn = func.apply(this, arguments); last = now; } return rtn; }; } }, {}], 193: [function(require, module, exports) { /** * Expose `toIsoString`. */ module.exports = toIsoString; /** * Turn a `date` into an ISO string. * * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString * * @param {Date} date * @return {String} */ function toIsoString (date) { return date.getUTCFullYear() + '-' + pad(date.getUTCMonth() + 1) + '-' + pad(date.getUTCDate()) + 'T' + pad(date.getUTCHours()) + ':' + pad(date.getUTCMinutes()) + ':' + pad(date.getUTCSeconds()) + '.' + String((date.getUTCMilliseconds()/1000).toFixed(3)).slice(2, 5) + 'Z'; } /** * Pad a `number` with a ten's place zero. * * @param {Number} number * @return {String} */ function pad (number) { var n = number.toString(); return n.length === 1 ? '0' + n : n; } }, {}], 194: [function(require, module, exports) { /** * Module dependencies. */ var type; try { type = require('type'); } catch(e){ type = require('type-component'); } /** * Module exports. */ module.exports = clone; /** * Clones objects. * * @param {Mixed} any object * @api public */ function clone(obj){ switch (type(obj)) { case 'object': var copy = {}; for (var key in obj) { if (obj.hasOwnProperty(key)) { copy[key] = clone(obj[key]); } } return copy; case 'array': var copy = new Array(obj.length); for (var i = 0, l = obj.length; i < l; i++) { copy[i] = clone(obj[i]); } return copy; case 'regexp': // from millermedeiros/amd-utils - MIT var flags = ''; flags += obj.multiline ? 'm' : ''; flags += obj.global ? 'g' : ''; flags += obj.ignoreCase ? 'i' : ''; return new RegExp(obj.source, flags); case 'date': return new Date(obj.getTime()); default: // string, number, boolean, … return obj; } } }, {"type":35}], 101: [function(require, module, exports) { /** * Module dependencies. */ var alias = require('alias'); var convertDates = require('convert-dates'); var Identify = require('facade').Identify; var integration = require('segmentio/analytics.js-integration'); /** * Expose `Customerio` integration. */ var Customerio = module.exports = integration('Customer.io') .assumesPageview() .global('_cio') .option('siteId', '') .tag('<script id="cio-tracker" src="https://assets.customer.io/assets/track.js" data-site-id="{{ siteId }}">'); /** * Initialize. * * http://customer.io/docs/api/javascript.html * * @param {Object} page */ Customerio.prototype.initialize = function(page){ window._cio = window._cio || []; (function(){var a,b,c; a = function(f){return function(){window._cio.push([f].concat(Array.prototype.slice.call(arguments,0))); }; }; b = ['identify', 'track']; for (c = 0; c < b.length; c++) {window._cio[b[c]] = a(b[c]); } })(); this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Customerio.prototype.loaded = function(){ return !! (window._cio && window._cio.pageHasLoaded); }; /** * Identify. * * http://customer.io/docs/api/javascript.html#section-Identify_customers * * @param {Identify} identify */ Customerio.prototype.identify = function(identify){ if (!identify.userId()) return this.debug('user id required'); var traits = identify.traits({ created: 'created_at' }); traits = convertDates(traits, convertDate); window._cio.identify(traits); }; /** * Group. * * @param {Group} group */ Customerio.prototype.group = function(group){ var traits = group.traits(); var user = this.analytics.user(); traits = alias(traits, function(trait){ return 'Group ' + trait; }); this.identify(new Identify({ userId: user.id(), traits: traits })); }; /** * Track. * * http://customer.io/docs/api/javascript.html#section-Track_a_custom_event * * @param {Track} track */ Customerio.prototype.track = function(track){ var properties = track.properties(); properties = convertDates(properties, convertDate); window._cio.track(track.event(), properties); }; /** * Convert a date to the format Customer.io supports. * * @param {Date} date * @return {Number} */ function convertDate(date){ return Math.floor(date.getTime() / 1000); } }, {"alias":195,"convert-dates":196,"facade":27,"segmentio/analytics.js-integration":159}], 195: [function(require, module, exports) { var type = require('type'); try { var clone = require('clone'); } catch (e) { var clone = require('clone-component'); } /** * Expose `alias`. */ module.exports = alias; /** * Alias an `object`. * * @param {Object} obj * @param {Mixed} method */ function alias (obj, method) { switch (type(method)) { case 'object': return aliasByDictionary(clone(obj), method); case 'function': return aliasByFunction(clone(obj), method); } } /** * Convert the keys in an `obj` using a dictionary of `aliases`. * * @param {Object} obj * @param {Object} aliases */ function aliasByDictionary (obj, aliases) { for (var key in aliases) { if (undefined === obj[key]) continue; obj[aliases[key]] = obj[key]; delete obj[key]; } return obj; } /** * Convert the keys in an `obj` using a `convert` function. * * @param {Object} obj * @param {Function} convert */ function aliasByFunction (obj, convert) { // have to create another object so that ie8 won't infinite loop on keys var output = {}; for (var key in obj) output[convert(key)] = obj[key]; return output; } }, {"type":35,"clone":62}], 196: [function(require, module, exports) { var is = require('is'); try { var clone = require('clone'); } catch (e) { var clone = require('clone-component'); } /** * Expose `convertDates`. */ module.exports = convertDates; /** * Recursively convert an `obj`'s dates to new values. * * @param {Object} obj * @param {Function} convert * @return {Object} */ function convertDates (obj, convert) { obj = clone(obj); for (var key in obj) { var val = obj[key]; if (is.date(val)) obj[key] = convert(val); if (is.object(val)) obj[key] = convertDates(val, convert); } return obj; } }, {"is":18,"clone":14}], 102: [function(require, module, exports) { /** * Module dependencies. */ var alias = require('alias'); var integration = require('segmentio/analytics.js-integration'); var is = require('is'); var load = require('load-script'); var push = require('global-queue')('_dcq'); /** * Expose `Drip` integration. */ var Drip = module.exports = integration('Drip') .assumesPageview() .global('dc') .global('_dcq') .global('_dcs') .option('account', '') .tag('<script src="//tag.getdrip.com/{{ account }}.js">'); /** * Initialize. * * @param {Object} page */ Drip.prototype.initialize = function(page){ window._dcq = window._dcq || []; window._dcs = window._dcs || {}; window._dcs.account = this.options.account; this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Drip.prototype.loaded = function(){ return is.object(window.dc); }; /** * Track. * * @param {Track} track */ Drip.prototype.track = function(track){ var props = track.properties(); var cents = Math.round(track.cents()); props.action = track.event(); if (cents) props.value = cents; delete props.revenue; push('track', props); }; }, {"alias":195,"segmentio/analytics.js-integration":159,"is":18,"load-script":168,"global-queue":190}], 103: [function(require, module, exports) { /** * Module dependencies. */ var extend = require('extend'); var integration = require('segmentio/analytics.js-integration'); var onError = require('on-error'); var push = require('global-queue')('_errs'); /** * Expose `Errorception` integration. */ var Errorception = module.exports = integration('Errorception') .assumesPageview() .global('_errs') .option('projectId', '') .option('meta', true) .tag('<script src="//beacon.errorception.com/{{ projectId }}.js">'); /** * Initialize. * * https://github.com/amplitude/Errorception-Javascript * * @param {Object} page */ Errorception.prototype.initialize = function(page){ window._errs = window._errs || [this.options.projectId]; onError(push); this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Errorception.prototype.loaded = function(){ return !! (window._errs && window._errs.push !== Array.prototype.push); }; /** * Identify. * * http://blog.errorception.com/2012/11/capture-custom-data-with-your-errors.html * * @param {Object} identify */ Errorception.prototype.identify = function(identify){ if (!this.options.meta) return; var traits = identify.traits(); window._errs = window._errs || []; window._errs.meta = window._errs.meta || {}; extend(window._errs.meta, traits); }; }, {"extend":40,"segmentio/analytics.js-integration":159,"on-error":188,"global-queue":190}], 104: [function(require, module, exports) { /** * Module dependencies. */ var each = require('each'); var integration = require('segmentio/analytics.js-integration'); var push = require('global-queue')('_aaq'); /** * Expose `Evergage` integration.integration. */ var Evergage = module.exports = integration('Evergage') .assumesPageview() .global('_aaq') .option('account', '') .option('dataset', '') .tag('<script src="//cdn.evergage.com/beacon/{{ account }}/{{ dataset }}/scripts/evergage.min.js">'); /** * Initialize. * * @param {Object} page */ Evergage.prototype.initialize = function(page){ var account = this.options.account; var dataset = this.options.dataset; window._aaq = window._aaq || []; push('setEvergageAccount', account); push('setDataset', dataset); push('setUseSiteConfig', true); this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Evergage.prototype.loaded = function(){ return !! (window._aaq && window._aaq.push !== Array.prototype.push); }; /** * Page. * * @param {Page} page */ Evergage.prototype.page = function(page){ var props = page.properties(); var name = page.name(); if (name) push('namePage', name); each(props, function(key, value){ push('setCustomField', key, value, 'page'); }); window.Evergage.init(true); }; /** * Identify. * * @param {Identify} identify */ Evergage.prototype.identify = function(identify){ var id = identify.userId(); if (!id) return; push('setUser', id); var traits = identify.traits({ email: 'userEmail', name: 'userName' }); each(traits, function(key, value){ push('setUserField', key, value, 'page'); }); }; /** * Group. * * @param {Group} group */ Evergage.prototype.group = function(group){ var props = group.traits(); var id = group.groupId(); if (!id) return; push('setCompany', id); each(props, function(key, value){ push('setAccountField', key, value, 'page'); }); }; /** * Track. * * @param {Track} track */ Evergage.prototype.track = function(track){ push('trackAction', track.event(), track.properties()); }; }, {"each":5,"segmentio/analytics.js-integration":159,"global-queue":190}], 105: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('segmentio/analytics.js-integration'); var push = require('global-queue')('_fbq'); var each = require('each'); /** * HOP */ var has = Object.prototype.hasOwnProperty; /** * Expose `Facebook` */ var Facebook = module.exports = integration('Facebook Ads') .global('_fbq') .option('currency', 'USD') .tag('<script src="//connect.facebook.net/en_US/fbds.js">') .mapping('events'); /** * Initialize Facebook Ads. * * https://developers.facebook.com/docs/ads-for-websites/conversion-pixel-code-migration * * @param {Object} page */ Facebook.prototype.initialize = function(page){ window._fbq = window._fbq || []; this.load(this.ready); window._fbq.loaded = true; }; /** * Loaded? * * @return {Boolean} */ Facebook.prototype.loaded = function(){ return !! (window._fbq && window._fbq.loaded); }; /** * Track. * * https://developers.facebook.com/docs/reference/ads-api/custom-audience-website-faq/#fbpixel * * @param {Track} track */ Facebook.prototype.track = function(track){ var event = track.event(); var events = this.events(event); var revenue = track.revenue() || 0; var self = this; each(events, function(event){ push('track', event, { value: String(revenue.toFixed(2)), currency: self.options.currency }); }); if (!events.length) { var data = track.properties(); push('track', event, data); } }; }, {"segmentio/analytics.js-integration":159,"global-queue":190,"each":5}], 106: [function(require, module, exports) { /** * Module dependencies. */ var push = require('global-queue')('_fxm'); var integration = require('segmentio/analytics.js-integration'); var Track = require('facade').Track; var each = require('each'); /** * Expose `FoxMetrics` integration. */ var FoxMetrics = module.exports = integration('FoxMetrics') .assumesPageview() .global('_fxm') .option('appId', '') .tag('<script src="//d35tca7vmefkrc.cloudfront.net/scripts/{{ appId }}.js">'); /** * Initialize. * * http://foxmetrics.com/documentation/apijavascript * * @param {Object} page */ FoxMetrics.prototype.initialize = function(page){ window._fxm = window._fxm || []; this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ FoxMetrics.prototype.loaded = function(){ return !! (window._fxm && window._fxm.appId); }; /** * Page. * * @param {Page} page */ FoxMetrics.prototype.page = function(page){ var properties = page.proxy('properties'); var category = page.category(); var name = page.name(); this._category = category; // store for later push( '_fxm.pages.view', properties.title, // title name, // name category, // category properties.url, // url properties.referrer // referrer ); }; /** * Identify. * * @param {Identify} identify */ FoxMetrics.prototype.identify = function(identify){ var id = identify.userId(); if (!id) return; push( '_fxm.visitor.profile', id, // user id identify.firstName(), // first name identify.lastName(), // last name identify.email(), // email identify.address(), // address undefined, // social undefined, // partners identify.traits() // attributes ); }; /** * Track. * * @param {Track} track */ FoxMetrics.prototype.track = function(track){ var props = track.properties(); var category = this._category || props.category; push(track.event(), category, props); }; /** * Viewed product. * * @param {Track} track * @api private */ FoxMetrics.prototype.viewedProduct = function(track){ ecommerce('productview', track); }; /** * Removed product. * * @param {Track} track * @api private */ FoxMetrics.prototype.removedProduct = function(track){ ecommerce('removecartitem', track); }; /** * Added product. * * @param {Track} track * @api private */ FoxMetrics.prototype.addedProduct = function(track){ ecommerce('cartitem', track); }; /** * Completed Order. * * @param {Track} track * @api private */ FoxMetrics.prototype.completedOrder = function(track){ var orderId = track.orderId(); // transaction push( '_fxm.ecommerce.order', orderId, track.subtotal(), track.shipping(), track.tax(), track.city(), track.state(), track.zip(), track.quantity() ); // items each(track.products(), function(product){ var track = new Track({ properties: product }); ecommerce('purchaseitem', track, [ track.quantity(), track.price(), orderId ]); }); }; /** * Track ecommerce `event` with `track` * with optional `arr` to append. * * @param {String} event * @param {Track} track * @param {Array} arr * @api private */ function ecommerce(event, track, arr){ push.apply(null, [ '_fxm.ecommerce.' + event, track.id() || track.sku(), track.name(), track.category() ].concat(arr || [])); } }, {"global-queue":190,"segmentio/analytics.js-integration":159,"facade":27,"each":5}], 107: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('segmentio/analytics.js-integration'); var bind = require('bind'); var when = require('when'); var is = require('is'); /** * Expose `Frontleaf` integration. */ var Frontleaf = module.exports = integration('Frontleaf') .assumesPageview() .global('_fl') .global('_flBaseUrl') .option('baseUrl', 'https://api.frontleaf.com') .option('token', '') .option('stream', '') .option('trackNamedPages', false) .option('trackCategorizedPages', false) .tag('<script id="_fl" src="{{ baseUrl }}/lib/tracker.js">'); /** * Initialize. * * http://docs.frontleaf.com/#/technical-implementation/tracking-customers/tracking-beacon * * @param {Object} page */ Frontleaf.prototype.initialize = function(page){ window._fl = window._fl || []; window._flBaseUrl = window._flBaseUrl || this.options.baseUrl; this._push('setApiToken', this.options.token); this._push('setStream', this.options.stream); var loaded = bind(this, this.loaded); var ready = this.ready; this.load({ baseUrl: window._flBaseUrl }, this.ready); }; /** * Loaded? * * @return {Boolean} */ Frontleaf.prototype.loaded = function(){ return is.array(window._fl) && window._fl.ready === true; }; /** * Identify. * * @param {Identify} identify */ Frontleaf.prototype.identify = function(identify){ var userId = identify.userId(); if (userId) { this._push('setUser', { id: userId, name: identify.name() || identify.username(), data: clean(identify.traits()) }); } }; /** * Group. * * @param {Group} group */ Frontleaf.prototype.group = function(group){ var groupId = group.groupId(); if (groupId) { this._push('setAccount', { id: groupId, name: group.proxy('traits.name'), data: clean(group.traits()) }); } }; /** * Page. * * @param {Page} page */ Frontleaf.prototype.page = function(page){ var category = page.category(); var name = page.fullName(); var opts = this.options; // categorized pages if (category && opts.trackCategorizedPages) { this.track(page.track(category)); } // named pages if (name && opts.trackNamedPages) { this.track(page.track(name)); } }; /** * Track. * * @param {Track} track */ Frontleaf.prototype.track = function(track){ var event = track.event(); this._push('event', event, clean(track.properties())); }; /** * Push a command onto the global Frontleaf queue. * * @param {String} command * @return {Object} args * @api private */ Frontleaf.prototype._push = function(command){ var args = [].slice.call(arguments, 1); window._fl.push(function(t){ t[command].apply(command, args); }); }; /** * Clean all nested objects and arrays. * * @param {Object} obj * @return {Object} * @api private */ function clean(obj){ var ret = {}; // Remove traits/properties that are already represented // outside of the data container var excludeKeys = ["id","name","firstName","lastName"]; var len = excludeKeys.length; for (var i = 0; i < len; i++) { clear(obj, excludeKeys[i]); } // Flatten nested hierarchy, preserving arrays obj = flatten(obj); // Discard nulls, represent arrays as comma-separated strings for (var key in obj) { var val = obj[key]; if (null == val) { continue; } if (is.array(val)) { ret[key] = val.toString(); continue; } ret[key] = val; } return ret; } /** * Remove a property from an object if set. * * @param {Object} obj * @param {String} key * @api private */ function clear(obj, key){ if (obj.hasOwnProperty(key)) { delete obj[key]; } } /** * Flatten a nested object into a single level space-delimited * hierarchy. * * Based on https://github.com/hughsk/flat * * @param {Object} source * @return {Object} * @api private */ function flatten(source){ var output = {}; function step(object, prev){ for (var key in object) { var value = object[key]; var newKey = prev ? prev + ' ' + key : key; if (!is.array(value) && is.object(value)) { return step(value, newKey); } output[newKey] = value; } } step(source); return output; } }, {"segmentio/analytics.js-integration":159,"bind":33,"when":184,"is":18}], 108: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('segmentio/analytics.js-integration'); var push = require('global-queue')('_gauges'); /** * Expose `Gauges` integration. */ var Gauges = module.exports = integration('Gauges') .assumesPageview() .global('_gauges') .option('siteId', '') .tag('<script id="gauges-tracker" src="//secure.gaug.es/track.js" data-site-id="{{ siteId }}">'); /** * Initialize Gauges. * * http://get.gaug.es/documentation/tracking/ * * @param {Object} page */ Gauges.prototype.initialize = function(page){ window._gauges = window._gauges || []; this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Gauges.prototype.loaded = function(){ return !! (window._gauges && window._gauges.push !== Array.prototype.push); }; /** * Page. * * @param {Page} page */ Gauges.prototype.page = function(page){ push('track'); }; }, {"segmentio/analytics.js-integration":159,"global-queue":190}], 109: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('segmentio/analytics.js-integration'); var onBody = require('on-body'); /** * Expose `GetSatisfaction` integration. */ var GetSatisfaction = module.exports = integration('Get Satisfaction') .assumesPageview() .global('GSFN') .option('widgetId', '') .tag('<script src="https://loader.engage.gsfn.us/loader.js">'); /** * Initialize. * * https://console.getsatisfaction.com/start/101022?signup=true#engage * * @param {Object} page */ GetSatisfaction.prototype.initialize = function(page){ var self = this; var widget = this.options.widgetId; var div = document.createElement('div'); var id = div.id = 'getsat-widget-' + widget; onBody(function(body){ body.appendChild(div); }); // usually the snippet is sync, so wait for it before initializing the tab this.load(function(){ window.GSFN.loadWidget(widget, { containerId: id }); self.ready(); }); }; /** * Loaded? * * @return {Boolean} */ GetSatisfaction.prototype.loaded = function(){ return !! window.GSFN; }; }, {"segmentio/analytics.js-integration":159,"on-body":180}], 110: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('segmentio/analytics.js-integration'); var push = require('global-queue')('_gaq'); var length = require('object').length; var canonical = require('canonical'); var useHttps = require('use-https'); var Track = require('facade').Track; var callback = require('callback'); var load = require('load-script'); var keys = require('object').keys; var dot = require('obj-case'); var each = require('each'); var type = require('type'); var url = require('url'); var is = require('is'); var group; var user; /** * Expose plugin. */ module.exports = exports = function(analytics){ analytics.addIntegration(GA); group = analytics.group(); user = analytics.user(); }; /** * Expose `GA` integration. * * http://support.google.com/analytics/bin/answer.py?hl=en&answer=2558867 * https://developers.google.com/analytics/devguides/collection/gajs/methods/gaJSApiBasicConfiguration#_gat.GA_Tracker_._setSiteSpeedSampleRate */ var GA = exports.Integration = integration('Google Analytics') .readyOnLoad() .global('ga') .global('gaplugins') .global('_gaq') .global('GoogleAnalyticsObject') .option('anonymizeIp', false) .option('classic', false) .option('domain', 'none') .option('doubleClick', false) .option('enhancedLinkAttribution', false) .option('ignoredReferrers', null) .option('includeSearch', false) .option('siteSpeedSampleRate', 1) .option('trackingId', '') .option('trackNamedPages', true) .option('trackCategorizedPages', true) .option('sendUserId', false) .option('metrics', {}) .option('dimensions', {}) .tag('library', '<script src="//www.google-analytics.com/analytics.js">') .tag('double click', '<script src="//stats.g.doubleclick.net/dc.js">') .tag('http', '<script src="http://www.google-analytics.com/ga.js">') .tag('https', '<script src="https://ssl.google-analytics.com/ga.js">'); /** * When in "classic" mode, on `construct` swap all of the method to point to * their classic counterparts. */ GA.on('construct', function(integration){ if (!integration.options.classic) return; integration.initialize = integration.initializeClassic; integration.loaded = integration.loadedClassic; integration.page = integration.pageClassic; integration.track = integration.trackClassic; integration.completedOrder = integration.completedOrderClassic; }); /** * Initialize. * * https://developers.google.com/analytics/devguides/collection/analyticsjs/advanced */ GA.prototype.initialize = function(){ var opts = this.options; // setup the tracker globals window.GoogleAnalyticsObject = 'ga'; window.ga = window.ga || function(){ window.ga.q = window.ga.q || []; window.ga.q.push(arguments); }; window.ga.l = new Date().getTime(); window.ga('create', opts.trackingId, { cookieDomain: opts.domain || GA.prototype.defaults.domain, // to protect against empty string siteSpeedSampleRate: opts.siteSpeedSampleRate, allowLinker: true }); // display advertising if (opts.doubleClick) { window.ga('require', 'displayfeatures'); } // send global id if (opts.sendUserId && user.id()) { window.ga('set', '&uid', user.id()); } // anonymize after initializing, otherwise a warning is shown // in google analytics debugger if (opts.anonymizeIp) window.ga('set', 'anonymizeIp', true); // custom dimensions & metrics var custom = metrics(user.traits(), opts); if (length(custom)) window.ga('set', custom); this.load('library', this.ready); }; /** * Loaded? * * @return {Boolean} */ GA.prototype.loaded = function(){ return !! window.gaplugins; }; /** * Page. * * https://developers.google.com/analytics/devguides/collection/analyticsjs/pages * * @param {Page} page */ GA.prototype.page = function(page){ var category = page.category(); var props = page.properties(); var name = page.fullName(); var pageview = {}; var track; this._category = category; // store for later // send window.ga('send', 'pageview', { page: path(props, this.options), title: name || props.title, location: props.url }); // categorized pages if (category && this.options.trackCategorizedPages) { track = page.track(category); this.track(track, { noninteraction: true }); } // named pages if (name && this.options.trackNamedPages) { track = page.track(name); this.track(track, { noninteraction: true }); } }; /** * Track. * * https://developers.google.com/analytics/devguides/collection/analyticsjs/events * https://developers.google.com/analytics/devguides/collection/analyticsjs/field-reference * * @param {Track} event */ GA.prototype.track = function(track, options){ var opts = options || track.options(this.name); var props = track.properties(); window.ga('send', 'event', { eventAction: track.event(), eventCategory: props.category || this._category || 'All', eventLabel: props.label, eventValue: formatValue(props.value || track.revenue()), nonInteraction: props.noninteraction || opts.noninteraction }); }; /** * Completed order. * * https://developers.google.com/analytics/devguides/collection/analyticsjs/ecommerce * * @param {Track} track * @api private */ GA.prototype.completedOrder = function(track){ var total = track.total() || track.revenue() || 0; var orderId = track.orderId(); var products = track.products(); var props = track.properties(); // orderId is required. if (!orderId) return; // require ecommerce if (!this.ecommerce) { window.ga('require', 'ecommerce', 'ecommerce.js'); this.ecommerce = true; } // add transaction window.ga('ecommerce:addTransaction', { affiliation: props.affiliation, shipping: track.shipping(), revenue: total, tax: track.tax(), id: orderId }); // add products each(products, function(product){ var track = new Track({ properties: product }); window.ga('ecommerce:addItem', { category: track.category(), quantity: track.quantity(), price: track.price(), name: track.name(), sku: track.sku(), id: orderId }); }); // send window.ga('ecommerce:send'); }; /** * Initialize (classic). * * https://developers.google.com/analytics/devguides/collection/gajs/methods/gaJSApiBasicConfiguration */ GA.prototype.initializeClassic = function(){ var opts = this.options; var anonymize = opts.anonymizeIp; var db = opts.doubleClick; var domain = opts.domain; var enhanced = opts.enhancedLinkAttribution; var ignore = opts.ignoredReferrers; var sample = opts.siteSpeedSampleRate; window._gaq = window._gaq || []; push('_setAccount', opts.trackingId); push('_setAllowLinker', true); if (anonymize) push('_gat._anonymizeIp'); if (domain) push('_setDomainName', domain); if (sample) push('_setSiteSpeedSampleRate', sample); if (enhanced) { var protocol = 'https:' === document.location.protocol ? 'https:' : 'http:'; var pluginUrl = protocol + '//www.google-analytics.com/plugins/ga/inpage_linkid.js'; push('_require', 'inpage_linkid', pluginUrl); } if (ignore) { if (!is.array(ignore)) ignore = [ignore]; each(ignore, function (domain) { push('_addIgnoredRef', domain); }); } if (this.options.doubleClick) { this.load('double click', this.ready); } else { var name = useHttps() ? 'https' : 'http'; this.load(name, this.ready); } }; /** * Loaded? (classic) * * @return {Boolean} */ GA.prototype.loadedClassic = function(){ return !! (window._gaq && window._gaq.push !== Array.prototype.push); }; /** * Page (classic). * * https://developers.google.com/analytics/devguides/collection/gajs/methods/gaJSApiBasicConfiguration * * @param {Page} page */ GA.prototype.pageClassic = function(page){ var opts = page.options(this.name); var category = page.category(); var props = page.properties(); var name = page.fullName(); var track; push('_trackPageview', path(props, this.options)); // categorized pages if (category && this.options.trackCategorizedPages) { track = page.track(category); this.track(track, { noninteraction: true }); } // named pages if (name && this.options.trackNamedPages) { track = page.track(name); this.track(track, { noninteraction: true }); } }; /** * Track (classic). * * https://developers.google.com/analytics/devguides/collection/gajs/methods/gaJSApiEventTracking * * @param {Track} track */ GA.prototype.trackClassic = function(track, options){ var opts = options || track.options(this.name); var props = track.properties(); var revenue = track.revenue(); var event = track.event(); var category = this._category || props.category || 'All'; var label = props.label; var value = formatValue(revenue || props.value); var noninteraction = props.noninteraction || opts.noninteraction; push('_trackEvent', category, event, label, value, noninteraction); }; /** * Completed order. * * https://developers.google.com/analytics/devguides/collection/gajs/gaTrackingEcommerce * * @param {Track} track * @api private */ GA.prototype.completedOrderClassic = function(track){ var total = track.total() || track.revenue() || 0; var orderId = track.orderId(); var products = track.products() || []; var props = track.properties(); // required if (!orderId) return; // add transaction push('_addTrans' , orderId , props.affiliation , total , track.tax() , track.shipping() , track.city() , track.state() , track.country()); // add items each(products, function(product){ var track = new Track({ properties: product }); push('_addItem' , orderId , track.sku() , track.name() , track.category() , track.price() , track.quantity()); }) // send push('_trackTrans'); }; /** * Return the path based on `properties` and `options`. * * @param {Object} properties * @param {Object} options */ function path(properties, options) { if (!properties) return; var str = properties.path; if (options.includeSearch && properties.search) str += properties.search; return str; } /** * Format the value property to Google's liking. * * @param {Number} value * @return {Number} */ function formatValue(value) { if (!value || value < 0) return 0; return Math.round(value); } /** * Map google's custom dimensions & metrics with `obj`. * * Example: * * metrics({ revenue: 1.9 }, { { metrics : { revenue: 'metric8' } }); * // => { metric8: 1.9 } * * metrics({ revenue: 1.9 }, {}); * // => {} * * @param {Object} obj * @param {Object} data * @return {Object|null} * @api private */ function metrics(obj, data){ var dimensions = data.dimensions; var metrics = data.metrics; var names = keys(metrics).concat(keys(dimensions)); var ret = {}; for (var i = 0; i < names.length; ++i) { var name = names[i]; var key = metrics[name] || dimensions[name]; var value = dot(obj, name); if (null == value) continue; ret[key] = value; } return ret; } }, {"segmentio/analytics.js-integration":159,"global-queue":190,"object":25,"canonical":13,"use-https":161,"facade":27,"callback":12,"load-script":168,"obj-case":60,"each":5,"type":35,"url":26,"is":18}], 111: [function(require, module, exports) { /** * Module dependencies. */ var push = require('global-queue')('dataLayer', { wrap: false }); var integration = require('segmentio/analytics.js-integration'); /** * Expose `GTM`. */ var GTM = module.exports = integration('Google Tag Manager') .assumesPageview() .global('dataLayer') .global('google_tag_manager') .option('containerId', '') .option('trackNamedPages', true) .option('trackCategorizedPages', true) .tag('<script src="//www.googletagmanager.com/gtm.js?id={{ containerId }}&l=dataLayer">'); /** * Initialize. * * https://developers.google.com/tag-manager * * @param {Object} page */ GTM.prototype.initialize = function(){ push({ 'gtm.start': +new Date, event: 'gtm.js' }); this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ GTM.prototype.loaded = function(){ return !! (window.dataLayer && [].push != window.dataLayer.push); }; /** * Page. * * @param {Page} page * @api public */ GTM.prototype.page = function(page){ var category = page.category(); var props = page.properties(); var name = page.fullName(); var opts = this.options; var track; // all if (opts.trackAllPages) { this.track(page.track()); } // categorized if (category && opts.trackCategorizedPages) { this.track(page.track(category)); } // named if (name && opts.trackNamedPages) { this.track(page.track(name)); } }; /** * Track. * * https://developers.google.com/tag-manager/devguide#events * * @param {Track} track * @api public */ GTM.prototype.track = function(track){ var props = track.properties(); props.event = track.event(); push(props); }; }, {"global-queue":190,"segmentio/analytics.js-integration":159}], 112: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('segmentio/analytics.js-integration'); var Identify = require('facade').Identify; var Track = require('facade').Track; var callback = require('callback'); var load = require('load-script'); var onBody = require('on-body'); var each = require('each'); /** * Expose `GoSquared` integration. */ var GoSquared = module.exports = integration('GoSquared') .assumesPageview() .global('_gs') .option('siteToken', '') .option('anonymizeIP', false) .option('cookieDomain', null) .option('useCookies', true) .option('trackHash', false) .option('trackLocal', false) .option('trackParams', true) .tag('<script src="//d1l6p2sc9645hc.cloudfront.net/tracker.js">'); /** * Initialize. * * https://www.gosquared.com/developer/tracker * Options: https://www.gosquared.com/developer/tracker/configuration * * @param {Object} page */ GoSquared.prototype.initialize = function(page){ var self = this; var options = this.options; var user = this.analytics.user(); push(options.siteToken); each(options, function(name, value){ if ('siteToken' == name) return; if (null == value) return; push('set', name, value); }); self.identify(new Identify({ traits: user.traits(), userId: user.id() })); self.load(this.ready); }; /** * Loaded? (checks if the tracker version is set) * * @return {Boolean} */ GoSquared.prototype.loaded = function(){ return !! (window._gs && window._gs.v); }; /** * Page. * * https://www.gosquared.com/developer/tracker/pageviews * * @param {Page} page */ GoSquared.prototype.page = function(page){ var props = page.properties(); var name = page.fullName(); push('track', props.path, name || props.title) }; /** * Identify. * * https://www.gosquared.com/developer/tracker/tagging * * @param {Identify} identify */ GoSquared.prototype.identify = function(identify){ var traits = identify.traits({ userId: 'userID' }); var username = identify.username(); var email = identify.email(); var id = identify.userId(); if (id) push('set', 'visitorID', id); var name = email || username || id; if (name) push('set', 'visitorName', name); push('set', 'visitor', traits); }; /** * Track. * * https://www.gosquared.com/developer/tracker/events * * @param {Track} track */ GoSquared.prototype.track = function(track){ push('event', track.event(), track.properties()); }; /** * Checked out. * * @param {Track} track * @api private */ GoSquared.prototype.completedOrder = function(track){ var products = track.products(); var items = []; each(products, function(product){ var track = new Track({ properties: product }); items.push({ category: track.category(), quantity: track.quantity(), price: track.price(), name: track.name(), }); }) push('transaction', track.orderId(), { revenue: track.total(), track: true }, items); }; /** * Push to `_gs.q`. * * @param {...} args * @api private */ function push(){ var _gs = window._gs = window._gs || function(){ (_gs.q = _gs.q || []).push(arguments); }; _gs.apply(null, arguments); } }, {"segmentio/analytics.js-integration":159,"facade":27,"callback":12,"load-script":168,"on-body":180,"each":5}], 113: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('segmentio/analytics.js-integration'); var alias = require('alias'); /** * Expose `Heap` integration. */ var Heap = module.exports = integration('Heap') .assumesPageview() .global('heap') .global('_heapid') .option('apiKey', '') .tag('<script src="//d36lvucg9kzous.cloudfront.net">'); /** * Initialize. * * https://heapanalytics.com/docs#installWeb * * @param {Object} page */ Heap.prototype.initialize = function(page){ window.heap=window.heap||[];window.heap.load=function(a){window._heapid=a;var d=function(a){return function(){window.heap.push([a].concat(Array.prototype.slice.call(arguments,0)));};},e=["identify","track"];for (var f=0;f<e.length;f++)window.heap[e[f]]=d(e[f]);}; window.heap.load(this.options.apiKey); this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Heap.prototype.loaded = function(){ return (window.heap && window.heap.appid); }; /** * Identify. * * https://heapanalytics.com/docs#identify * * @param {Identify} identify */ Heap.prototype.identify = function(identify){ var traits = identify.traits(); var username = identify.username(); var id = identify.userId(); var handle = username || id; if (handle) traits.handle = handle; delete traits.username; window.heap.identify(traits); }; /** * Track. * * https://heapanalytics.com/docs#track * * @param {Track} track */ Heap.prototype.track = function(track){ window.heap.track(track.event(), track.properties()); }; }, {"segmentio/analytics.js-integration":159,"alias":195}], 114: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('segmentio/analytics.js-integration'); /** * Expose `hellobar.com` integration. */ var Hellobar = module.exports = integration('Hello Bar') .assumesPageview() .global('_hbq') .option('apiKey', '') .tag('<script src="//s3.amazonaws.com/scripts.hellobar.com/{{ apiKey }}.js">'); /** * Initialize. * * https://s3.amazonaws.com/scripts.hellobar.com/bb900665a3090a79ee1db98c3af21ea174bbc09f.js * * @param {Object} page */ Hellobar.prototype.initialize = function(page){ window._hbq = window._hbq || []; this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Hellobar.prototype.loaded = function(){ return !! (window._hbq && window._hbq.push !== Array.prototype.push); }; }, {"segmentio/analytics.js-integration":159}], 115: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('segmentio/analytics.js-integration'); var is = require('is'); /** * Expose `HitTail` integration. */ var HitTail = module.exports = integration('HitTail') .assumesPageview() .global('htk') .option('siteId', '') .tag('<script src="//{{ siteId }}.hittail.com/mlt.js">'); /** * Initialize. * * @param {Object} page */ HitTail.prototype.initialize = function(page){ this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ HitTail.prototype.loaded = function(){ return is.fn(window.htk); }; }, {"segmentio/analytics.js-integration":159,"is":18}], 116: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); /** * Expose `hublo.com` integration. */ var Hublo = module.exports = integration('Hublo') .assumesPageview() .global('_hublo_') .option('apiKey', null) .tag('<script src="//cdn.hublo.co/{{ apiKey }}.js">'); /** * Initialize. * * https://cdn.hublo.co/5353a2e62b26c1277b000004.js * * @param {Object} page */ Hublo.prototype.initialize = function(page){ this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Hublo.prototype.loaded = function(){ return !! (window._hublo_ && typeof window._hublo_.setup === 'function'); }; }, {"analytics.js-integration":159}], 117: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('segmentio/analytics.js-integration'); var push = require('global-queue')('_hsq'); var convert = require('convert-dates'); /** * Expose `HubSpot` integration. */ var HubSpot = module.exports = integration('HubSpot') .assumesPageview() .global('_hsq') .option('portalId', null) .tag('<script id="hs-analytics" src="https://js.hs-analytics.net/analytics/{{ cache }}/{{ portalId }}.js">'); /** * Initialize. * * @param {Object} page */ HubSpot.prototype.initialize = function(page){ window._hsq = []; var cache = Math.ceil(new Date() / 300000) * 300000; this.load({ cache: cache }, this.ready); }; /** * Loaded? * * @return {Boolean} */ HubSpot.prototype.loaded = function(){ return !! (window._hsq && window._hsq.push !== Array.prototype.push); }; /** * Page. * * @param {String} category (optional) * @param {String} name (optional) * @param {Object} properties (optional) * @param {Object} options (optional) */ HubSpot.prototype.page = function(page){ push('_trackPageview'); }; /** * Identify. * * @param {Identify} identify */ HubSpot.prototype.identify = function(identify){ if (!identify.email()) return; var traits = identify.traits(); traits = convertDates(traits); push('identify', traits); }; /** * Track. * * @param {Track} track */ HubSpot.prototype.track = function(track){ var props = track.properties(); props = convertDates(props); push('trackEvent', track.event(), props); }; /** * Convert all the dates in the HubSpot properties to millisecond times * * @param {Object} properties */ function convertDates(properties){ return convert(properties, function(date){ return date.getTime(); }); } }, {"segmentio/analytics.js-integration":159,"global-queue":190,"convert-dates":196}], 118: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('segmentio/analytics.js-integration'); var alias = require('alias'); /** * Expose `Improvely` integration. */ var Improvely = module.exports = integration('Improvely') .assumesPageview() .global('_improvely') .global('improvely') .option('domain', '') .option('projectId', null) .tag('<script src="//{{ domain }}.iljmp.com/improvely.js">'); /** * Initialize. * * http://www.improvely.com/docs/landing-page-code * * @param {Object} page */ Improvely.prototype.initialize = function(page){ window._improvely = []; window.improvely = { init: function(e, t){ window._improvely.push(["init", e, t]); }, goal: function(e){ window._improvely.push(["goal", e]); }, label: function(e){ window._improvely.push(["label", e]); }}; var domain = this.options.domain; var id = this.options.projectId; window.improvely.init(domain, id); this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Improvely.prototype.loaded = function(){ return !! (window.improvely && window.improvely.identify); }; /** * Identify. * * http://www.improvely.com/docs/labeling-visitors * * @param {Identify} identify */ Improvely.prototype.identify = function(identify){ var id = identify.userId(); if (id) window.improvely.label(id); }; /** * Track. * * http://www.improvely.com/docs/conversion-code * * @param {Track} track */ Improvely.prototype.track = function(track){ var props = track.properties({ revenue: 'amount' }); props.type = track.event(); window.improvely.goal(props); }; }, {"segmentio/analytics.js-integration":159,"alias":195}], 119: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var push = require('global-queue')('_iva'); var is = require('is'); /** * Expose `InsideVault` integration. */ var InsideVault = module.exports = integration('InsideVault') .global('_iva') .option('clientId', '') .option('domain', '') .tag('<script src="//analytics.staticiv.com/iva.js">'); /** * Initialize. * * @param page */ InsideVault.prototype.initialize = function(page){ var domain = this.options.domain; window._iva = window._iva || []; push('setClientId', this.options.clientId); if (domain) push('setDomain', domain); this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ InsideVault.prototype.loaded = function(){ return !! (window._iva && window._iva.push !== Array.prototype.push); }; /** * Track. * * Tracks everything except 'sale' events. * * @param {Track} track */ InsideVault.prototype.track = function(track){ var event = track.event(); var value = track.revenue() || track.value() || 0; var orderId = track.orderId() || ''; // 'sale' is a special event that will be routed to a table that is deprecated on our end. // We don't want a generic 'sale' event to go to our deprecated table. if (event != 'sale') { push('trackEvent', event, value, orderId); } }; }, {"analytics.js-integration":159,"global-queue":190,"is":18}], 120: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('segmentio/analytics.js-integration'); var push = require('global-queue')('__insp'); var alias = require('alias'); var clone = require('clone'); /** * Expose `Inspectlet` integration. */ var Inspectlet = module.exports = integration('Inspectlet') .assumesPageview() .global('__insp') .global('__insp_') .option('wid', '') .tag('<script src="//www.inspectlet.com/inspectlet.js">'); /** * Initialize. * * https://www.inspectlet.com/dashboard/embedcode/1492461759/initial * * @param {Object} page */ Inspectlet.prototype.initialize = function(page){ push('wid', this.options.wid); this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Inspectlet.prototype.loaded = function(){ return !! window.__insp_; }; /** * Identify. * * http://www.inspectlet.com/docs#tagging * * @param {Identify} identify */ Inspectlet.prototype.identify = function (identify) { var traits = identify.traits({ id: 'userid' }); push('tagSession', traits); }; /** * Track. * * http://www.inspectlet.com/docs/tags * * @param {Track} track */ Inspectlet.prototype.track = function(track){ push('tagSession', track.event()); }; }, {"segmentio/analytics.js-integration":159,"global-queue":190,"alias":195,"clone":194}], 121: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('segmentio/analytics.js-integration'); var convertDates = require('convert-dates'); var defaults = require('defaults'); var isEmail = require('is-email'); var load = require('load-script'); var empty = require('is-empty'); var alias = require('alias'); var each = require('each'); var when = require('when'); var is = require('is'); /** * Expose `Intercom` integration. */ var Intercom = module.exports = integration('Intercom') .assumesPageview() .global('Intercom') .option('activator', '#IntercomDefaultWidget') .option('appId', '') .option('inbox', false) .tag('<script src="https://static.intercomcdn.com/intercom.v1.js">'); /** * Initialize. * * http://docs.intercom.io/ * http://docs.intercom.io/#IntercomJS * * @param {Object} page */ Intercom.prototype.initialize = function(page){ var self = this; this.load(function(){ when(function(){ return self.loaded(); }, self.ready); }); }; /** * Loaded? * * @return {Boolean} */ Intercom.prototype.loaded = function(){ return is.fn(window.Intercom); }; /** * Page. * * @param {Page} page */ Intercom.prototype.page = function(page){ window.Intercom('update'); }; /** * Identify. * * http://docs.intercom.io/#IntercomJS * * @param {Identify} identify */ Intercom.prototype.identify = function(identify){ var traits = identify.traits({ userId: 'user_id' }); var activator = this.options.activator; var opts = identify.options(this.name); var companyCreated = identify.companyCreated(); var created = identify.created(); var email = identify.email(); var name = identify.name(); var id = identify.userId(); var group = this.analytics.group(); if (!id && !traits.email) return; // one is required traits.app_id = this.options.appId; // intercom requires `company` to be an object. default it with group traits // so that we guarantee an `id` is there, since they require it if (null != traits.company && !is.object(traits.company)) delete traits.company; if (traits.company) defaults(traits.company, group.traits()); // name if (name) traits.name = name; // handle dates if (traits.company && companyCreated) traits.company.created = companyCreated; if (created) traits.created = created; // convert dates traits = convertDates(traits, formatDate); traits = alias(traits, { created: 'created_at'}); if (traits.company) traits.company = alias(traits.company, { created: 'created_at' }); // handle options if (opts.increments) traits.increments = opts.increments; if (opts.userHash) traits.user_hash = opts.userHash; if (opts.user_hash) traits.user_hash = opts.user_hash; // Intercom, will force the widget to appear // if the selector is #IntercomDefaultWidget // so no need to check inbox, just need to check // that the selector isn't #IntercomDefaultWidget. if ('#IntercomDefaultWidget' != activator) { traits.widget = { activator: activator }; } var method = this._id !== id ? 'boot': 'update'; this._id = id; // cache for next time window.Intercom(method, traits); }; /** * Group. * * @param {Group} group */ Intercom.prototype.group = function(group){ var props = group.properties(); var id = group.groupId(); if (id) props.id = id; window.Intercom('update', { company: props }); }; /** * Track. * * @param {Track} track */ Intercom.prototype.track = function(track){ window.Intercom('trackEvent', track.event(), track.properties()); }; /** * Format a date to Intercom's liking. * * @param {Date} date * @return {Number} */ function formatDate(date) { return Math.floor(date / 1000); } }, {"segmentio/analytics.js-integration":159,"convert-dates":196,"defaults":189,"is-email":19,"load-script":168,"is-empty":44,"alias":195,"each":5,"when":184,"is":18}], 122: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('segmentio/analytics.js-integration'); /** * Expose `Keen IO` integration. */ var Keen = module.exports = integration('Keen IO') .global('Keen') .option('projectId', '') .option('readKey', '') .option('writeKey', '') .option('trackNamedPages', true) .option('trackAllPages', false) .option('trackCategorizedPages', true) .tag('<script src="//dc8na2hxrj29i.cloudfront.net/code/keen-2.1.0-min.js">'); /** * Initialize. * * https://keen.io/docs/ */ Keen.prototype.initialize = function(){ var options = this.options; window.Keen = window.Keen||{ configure:function(e){this._cf=e;}, addEvent:function(e,t,n,i){this._eq=this._eq||[],this._eq.push([e,t,n,i]);}, setGlobalProperties:function(e){this._gp=e;}, onChartsReady:function(e){this._ocrq=this._ocrq||[],this._ocrq.push(e);}}; window.Keen.configure({ projectId: options.projectId, writeKey: options.writeKey, readKey: options.readKey }); this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Keen.prototype.loaded = function(){ return !! (window.Keen && window.Keen.Base64); }; /** * Page. * * @param {Page} page */ Keen.prototype.page = function(page){ var category = page.category(); var props = page.properties(); var name = page.fullName(); var opts = this.options; // all pages if (opts.trackAllPages) { this.track(page.track()); } // named pages if (name && opts.trackNamedPages) { this.track(page.track(name)); } // categorized pages if (category && opts.trackCategorizedPages) { this.track(page.track(category)); } }; /** * Identify. * * TODO: migrate from old `userId` to simpler `id` * * @param {Identify} identify */ Keen.prototype.identify = function(identify){ var traits = identify.traits(); var id = identify.userId(); var user = {}; if (id) user.userId = id; if (traits) user.traits = traits; window.Keen.setGlobalProperties(function(){ return { user: user }; }); }; /** * Track. * * @param {Track} track */ Keen.prototype.track = function(track){ window.Keen.addEvent(track.event(), track.properties()); }; }, {"segmentio/analytics.js-integration":159}], 123: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('segmentio/analytics.js-integration'); var indexof = require('indexof'); var is = require('is'); /** * Expose `Kenshoo` integration. */ var Kenshoo = module.exports = integration('Kenshoo') .global('k_trackevent') .option('cid', '') .option('subdomain', '') .option('events', []) .tag('<script src="//{{ subdomain }}.xg4ken.com/media/getpx.php?cid={{ cid }}">'); /** * Initialize. * * See https://gist.github.com/justinboyle/7875832 * * @param {Object} page */ Kenshoo.prototype.initialize = function(page){ this.load(this.ready); }; /** * Loaded? (checks if the tracking function is set) * * @return {Boolean} */ Kenshoo.prototype.loaded = function(){ return is.fn(window.k_trackevent); }; /** * Track. * * Only tracks events if they are listed in the events array option. * We've asked for docs a few times but no go :/ * * https://github.com/jorgegorka/the_tracker/blob/master/lib/the_tracker/trackers/kenshoo.rb * * @param {Track} event */ Kenshoo.prototype.track = function(track){ var events = this.options.events; var traits = track.traits(); var event = track.event(); var revenue = track.revenue() || 0; if (!~indexof(events, event)) return; var params = [ 'id=' + this.options.cid, 'type=conv', 'val=' + revenue, 'orderId=' + track.orderId(), 'promoCode=' + track.coupon(), 'valueCurrency=' + track.currency(), // Live tracking fields. Ignored for now (until we get documentation). 'GCID=', 'kw=', 'product=' ]; window.k_trackevent(params, this.options.subdomain); }; }, {"segmentio/analytics.js-integration":159,"indexof":46,"is":18}], 124: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('segmentio/analytics.js-integration'); var push = require('global-queue')('_kmq'); var Track = require('facade').Track; var alias = require('alias'); var Batch = require('batch'); var each = require('each'); var is = require('is'); /** * Expose `KISSmetrics` integration. */ var KISSmetrics = module.exports = integration('KISSmetrics') .assumesPageview() .global('_kmq') .global('KM') .global('_kmil') .option('apiKey', '') .option('trackNamedPages', true) .option('trackCategorizedPages', true) .option('prefixProperties', true) .tag('useless', '<script src="//i.kissmetrics.com/i.js">') .tag('library', '<script src="//doug1izaerwt3.cloudfront.net/{{ apiKey }}.1.js">'); /** * Check if browser is mobile, for kissmetrics. * * http://support.kissmetrics.com/how-tos/browser-detection.html#mobile-vs-non-mobile */ exports.isMobile = navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/BlackBerry/i) || navigator.userAgent.match(/iPhone|iPod/i) || navigator.userAgent.match(/iPad/i) || navigator.userAgent.match(/Opera Mini/i) || navigator.userAgent.match(/IEMobile/i); /** * Initialize. * * http://support.kissmetrics.com/apis/javascript * * @param {Object} page */ KISSmetrics.prototype.initialize = function(page){ var self = this; window._kmq = []; if (exports.isMobile) push('set', { 'Mobile Session': 'Yes' }); var batch = new Batch(); batch.push(function(done){ self.load('useless', done); }) // :) batch.push(function(done){ self.load('library', done); }) batch.end(function(){ self.trackPage(page); self.ready(); }); }; /** * Loaded? * * @return {Boolean} */ KISSmetrics.prototype.loaded = function(){ return is.object(window.KM); }; /** * Page. * * @param {Page} page */ KISSmetrics.prototype.page = function(page){ if (!window.KM_SKIP_PAGE_VIEW) window.KM.pageView(); this.trackPage(page); }; /** * Track page. * * @param {Page} page */ KISSmetrics.prototype.trackPage = function(page){ var category = page.category(); var name = page.fullName(); var opts = this.options; // named pages if (name && opts.trackNamedPages) { this.track(page.track(name)); } // categorized pages if (category && opts.trackCategorizedPages) { this.track(page.track(category)); } }; /** * Identify. * * @param {Identify} identify */ KISSmetrics.prototype.identify = function(identify){ var traits = identify.traits(); var id = identify.userId(); if (id) push('identify', id); if (traits) push('set', traits); }; /** * Track. * * @param {Track} track */ KISSmetrics.prototype.track = function(track){ var mapping = { revenue: 'Billing Amount' }; var event = track.event(); var properties = track.properties(mapping); if (this.options.prefixProperties) properties = prefix(event, properties); push('record', event, properties); }; /** * Alias. * * @param {Alias} to */ KISSmetrics.prototype.alias = function(alias){ push('alias', alias.to(), alias.from()); }; /** * Completed order. * * @param {Track} track * @api private */ KISSmetrics.prototype.completedOrder = function(track){ var products = track.products(); var event = track.event(); // transaction push('record', event, prefix(event, track.properties())); // items window._kmq.push(function(){ var km = window.KM; each(products, function(product, i){ var temp = new Track({ event: event, properties: product }); var item = prefix(event, product); item._t = km.ts() + i; item._d = 1; km.set(item); }); }); }; /** * Prefix properties with the event name. * * @param {String} event * @param {Object} properties * @return {Object} prefixed * @api private */ function prefix(event, properties){ var prefixed = {}; each(properties, function(key, val){ if (key === 'Billing Amount') { prefixed[key] = val; } else { prefixed[event + ' - ' + key] = val; } }); return prefixed; } }, {"segmentio/analytics.js-integration":159,"global-queue":190,"facade":27,"alias":195,"batch":197,"each":5,"is":18}], 197: [function(require, module, exports) { /** * Module dependencies. */ try { var EventEmitter = require('events').EventEmitter; } catch (err) { var Emitter = require('emitter'); } /** * Noop. */ function noop(){} /** * Expose `Batch`. */ module.exports = Batch; /** * Create a new Batch. */ function Batch() { if (!(this instanceof Batch)) return new Batch; this.fns = []; this.concurrency(Infinity); this.throws(true); for (var i = 0, len = arguments.length; i < len; ++i) { this.push(arguments[i]); } } /** * Inherit from `EventEmitter.prototype`. */ if (EventEmitter) { Batch.prototype.__proto__ = EventEmitter.prototype; } else { Emitter(Batch.prototype); } /** * Set concurrency to `n`. * * @param {Number} n * @return {Batch} * @api public */ Batch.prototype.concurrency = function(n){ this.n = n; return this; }; /** * Queue a function. * * @param {Function} fn * @return {Batch} * @api public */ Batch.prototype.push = function(fn){ this.fns.push(fn); return this; }; /** * Set wether Batch will or will not throw up. * * @param {Boolean} throws * @return {Batch} * @api public */ Batch.prototype.throws = function(throws) { this.e = !!throws; return this; }; /** * Execute all queued functions in parallel, * executing `cb(err, results)`. * * @param {Function} cb * @return {Batch} * @api public */ Batch.prototype.end = function(cb){ var self = this , total = this.fns.length , pending = total , results = [] , errors = [] , cb = cb || noop , fns = this.fns , max = this.n , throws = this.e , index = 0 , done; // empty if (!fns.length) return cb(null, results); // process function next() { var i = index++; var fn = fns[i]; if (!fn) return; var start = new Date; try { fn(callback); } catch (err) { callback(err); } function callback(err, res){ if (done) return; if (err && throws) return done = true, cb(err); var complete = total - pending + 1; var end = new Date; results[i] = res; errors[i] = err; self.emit('progress', { index: i, value: res, error: err, pending: pending, total: total, complete: complete, percent: complete / total * 100 | 0, start: start, end: end, duration: end - start }); if (--pending) next() else if(!throws) cb(errors, results); else cb(null, results); } } // concurrency for (var i = 0; i < fns.length; i++) { if (i == max) break; next(); } return this; }; }, {"emitter":198}], 198: [function(require, module, exports) { /** * Expose `Emitter`. */ module.exports = Emitter; /** * Initialize a new `Emitter`. * * @api public */ function Emitter(obj) { if (obj) return mixin(obj); }; /** * Mixin the emitter properties. * * @param {Object} obj * @return {Object} * @api private */ function mixin(obj) { for (var key in Emitter.prototype) { obj[key] = Emitter.prototype[key]; } return obj; } /** * Listen on the given `event` with `fn`. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.on = Emitter.prototype.addEventListener = function(event, fn){ this._callbacks = this._callbacks || {}; (this._callbacks[event] = this._callbacks[event] || []) .push(fn); return this; }; /** * Adds an `event` listener that will be invoked a single * time then automatically removed. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.once = function(event, fn){ var self = this; this._callbacks = this._callbacks || {}; function on() { self.off(event, on); fn.apply(this, arguments); } on.fn = fn; this.on(event, on); return this; }; /** * Remove the given callback for `event` or all * registered callbacks. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.off = Emitter.prototype.removeListener = Emitter.prototype.removeAllListeners = Emitter.prototype.removeEventListener = function(event, fn){ this._callbacks = this._callbacks || {}; // all if (0 == arguments.length) { this._callbacks = {}; return this; } // specific event var callbacks = this._callbacks[event]; if (!callbacks) return this; // remove all handlers if (1 == arguments.length) { delete this._callbacks[event]; return this; } // remove specific handler var cb; for (var i = 0; i < callbacks.length; i++) { cb = callbacks[i]; if (cb === fn || cb.fn === fn) { callbacks.splice(i, 1); break; } } return this; }; /** * Emit `event` with the given args. * * @param {String} event * @param {Mixed} ... * @return {Emitter} */ Emitter.prototype.emit = function(event){ this._callbacks = this._callbacks || {}; var args = [].slice.call(arguments, 1) , callbacks = this._callbacks[event]; if (callbacks) { callbacks = callbacks.slice(0); for (var i = 0, len = callbacks.length; i < len; ++i) { callbacks[i].apply(this, args); } } return this; }; /** * Return array of callbacks for `event`. * * @param {String} event * @return {Array} * @api public */ Emitter.prototype.listeners = function(event){ this._callbacks = this._callbacks || {}; return this._callbacks[event] || []; }; /** * Check if this emitter has `event` handlers. * * @param {String} event * @return {Boolean} * @api public */ Emitter.prototype.hasListeners = function(event){ return !! this.listeners(event).length; }; }, {}], 125: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('segmentio/analytics.js-integration'); var push = require('global-queue')('_learnq'); var tick = require('next-tick'); var alias = require('alias'); /** * Trait aliases. */ var aliases = { id: '$id', email: '$email', firstName: '$first_name', lastName: '$last_name', phone: '$phone_number', title: '$title' }; /** * Expose `Klaviyo` integration. */ var Klaviyo = module.exports = integration('Klaviyo') .assumesPageview() .global('_learnq') .option('apiKey', '') .tag('<script src="//a.klaviyo.com/media/js/learnmarklet.js">'); /** * Initialize. * * https://www.klaviyo.com/docs/getting-started * * @param {Object} page */ Klaviyo.prototype.initialize = function(page){ var self = this; push('account', this.options.apiKey); this.load(function(){ tick(self.ready); }); }; /** * Loaded? * * @return {Boolean} */ Klaviyo.prototype.loaded = function(){ return !! (window._learnq && window._learnq.push !== Array.prototype.push); }; /** * Identify. * * @param {Identify} identify */ Klaviyo.prototype.identify = function(identify){ var traits = identify.traits(aliases); if (!traits.$id && !traits.$email) return; push('identify', traits); }; /** * Group. * * @param {Group} group */ Klaviyo.prototype.group = function(group){ var props = group.properties(); if (!props.name) return; push('identify', { $organization: props.name }); }; /** * Track. * * @param {Track} track */ Klaviyo.prototype.track = function(track){ push('track', track.event(), track.properties({ revenue: '$value' })); }; }, {"segmentio/analytics.js-integration":159,"global-queue":190,"next-tick":45,"alias":195}], 126: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('segmentio/analytics.js-integration'); /** * Expose `LeadLander` integration. */ var LeadLander = module.exports = integration('LeadLander') .assumesPageview() .global('llactid') .global('trackalyzer') .option('accountId', null) .tag('<script src="http://t6.trackalyzer.com/trackalyze-nodoc.js">'); /** * Initialize. * * @param {Object} page */ LeadLander.prototype.initialize = function(page){ window.llactid = this.options.accountId; this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ LeadLander.prototype.loaded = function(){ return !! window.trackalyzer; }; }, {"segmentio/analytics.js-integration":159}], 127: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('segmentio/analytics.js-integration'); var clone = require('clone'); var each = require('each'); var when = require('when'); /** * Expose `LiveChat` integration. */ var LiveChat = module.exports = integration('LiveChat') .assumesPageview() .global('__lc') .global('__lc_inited') .global('LC_API') .global('LC_Invite') .option('group', 0) .option('license', '') .tag('<script src="//cdn.livechatinc.com/tracking.js">'); /** * Initialize. * * http://www.livechatinc.com/api/javascript-api * * @param {Object} page */ LiveChat.prototype.initialize = function(page){ var self = this; window.__lc = clone(this.options); this.load(function(){ when(function(){ return self.loaded(); }, self.ready); }); }; /** * Loaded? * * @return {Boolean} */ LiveChat.prototype.loaded = function(){ return !!(window.LC_API && window.LC_Invite); }; /** * Identify. * * @param {Identify} identify */ LiveChat.prototype.identify = function(identify){ var traits = identify.traits({ userId: 'User ID' }); window.LC_API.set_custom_variables(convert(traits)); }; /** * Convert a traits object into the format LiveChat requires. * * @param {Object} traits * @return {Array} */ function convert(traits){ var arr = []; each(traits, function(key, value){ arr.push({ name: key, value: value }); }); return arr; } }, {"segmentio/analytics.js-integration":159,"clone":194,"each":5,"when":184}], 128: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('segmentio/analytics.js-integration'); var Identify = require('facade').Identify; var useHttps = require('use-https'); /** * Expose `LuckyOrange` integration. */ var LuckyOrange = module.exports = integration('Lucky Orange') .assumesPageview() .global('_loq') .global('__wtw_watcher_added') .global('__wtw_lucky_site_id') .global('__wtw_lucky_is_segment_io') .global('__wtw_custom_user_data') .option('siteId', null) .tag('http', '<script src="http://www.luckyorange.com/w.js?{{ cache }}">') .tag('https', '<script src="https://ssl.luckyorange.com/w.js?{{ cache }}">'); /** * Initialize. * * @param {Object} page */ LuckyOrange.prototype.initialize = function(page){ var user = this.analytics.user(); window._loq || (window._loq = []); window.__wtw_lucky_site_id = this.options.siteId; this.identify(new Identify({ traits: user.traits(), userId: user.id() })); var cache = Math.floor(new Date().getTime() / 60000); var name = useHttps() ? 'https' : 'http'; this.load(name, { cache: cache }, this.ready); }; /** * Loaded? * * @return {Boolean} */ LuckyOrange.prototype.loaded = function(){ return !! window.__wtw_watcher_added; }; /** * Identify. * * @param {Identify} identify */ LuckyOrange.prototype.identify = function(identify){ var traits = identify.traits(); var email = identify.email(); var name = identify.name(); if (name) traits.name = name; if (email) traits.email = email; window.__wtw_custom_user_data = traits; }; }, {"segmentio/analytics.js-integration":159,"facade":27,"use-https":161}], 129: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('segmentio/analytics.js-integration'); var alias = require('alias'); /** * Expose `Lytics` integration. */ var Lytics = module.exports = integration('Lytics') .global('jstag') .option('cid', '') .option('cookie', 'seerid') .option('delay', 2000) .option('sessionTimeout', 1800) .option('url', '//c.lytics.io') .tag('<script src="//c.lytics.io/static/io.min.js">'); /** * Options aliases. */ var aliases = { sessionTimeout: 'sessecs' }; /** * Initialize. * * http://admin.lytics.io/doc#jstag * * @param {Object} page */ Lytics.prototype.initialize = function(page){ var options = alias(this.options, aliases); window.jstag = (function(){var t = { _q: [], _c: options, ts: (new Date()).getTime() }; t.send = function(){this._q.push(['ready', 'send', Array.prototype.slice.call(arguments)]); return this; }; return t; })(); this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Lytics.prototype.loaded = function(){ return !! (window.jstag && window.jstag.bind); }; /** * Page. * * @param {Page} page */ Lytics.prototype.page = function(page){ window.jstag.send(page.properties()); }; /** * Idenfity. * * @param {Identify} identify */ Lytics.prototype.identify = function(identify){ var traits = identify.traits({ userId: '_uid' }); window.jstag.send(traits); }; /** * Track. * * @param {String} event * @param {Object} properties (optional) * @param {Object} options (optional) */ Lytics.prototype.track = function(track){ var props = track.properties(); props._e = track.event(); window.jstag.send(props); }; }, {"segmentio/analytics.js-integration":159,"alias":195}], 130: [function(require, module, exports) { /** * Module dependencies. */ var alias = require('alias'); var clone = require('clone'); var dates = require('convert-dates'); var integration = require('segmentio/analytics.js-integration'); var iso = require('to-iso-string'); var indexof = require('indexof'); var del = require('obj-case').del; /** * Expose `Mixpanel` integration. */ var Mixpanel = module.exports = integration('Mixpanel') .global('mixpanel') .option('increments', []) .option('cookieName', '') .option('nameTag', true) .option('pageview', false) .option('people', false) .option('token', '') .option('trackAllPages', false) .option('trackNamedPages', true) .option('trackCategorizedPages', true) .tag('<script src="//cdn.mxpnl.com/libs/mixpanel-2.2.min.js">'); /** * Options aliases. */ var optionsAliases = { cookieName: 'cookie_name' }; /** * Initialize. * * https://mixpanel.com/help/reference/javascript#installing * https://mixpanel.com/help/reference/javascript-full-api-reference#mixpanel.init */ Mixpanel.prototype.initialize = function(){ (function(c, a){window.mixpanel = a; var b, d, h, e; a._i = []; a.init = function(b, c, f){function d(a, b){var c = b.split('.'); 2 == c.length && (a = a[c[0]], b = c[1]); a[b] = function(){a.push([b].concat(Array.prototype.slice.call(arguments, 0))); }; } var g = a; 'undefined' !== typeof f ? g = a[f] = [] : f = 'mixpanel'; g.people = g.people || []; h = ['disable', 'track', 'track_pageview', 'track_links', 'track_forms', 'register', 'register_once', 'unregister', 'identify', 'alias', 'name_tag', 'set_config', 'people.set', 'people.increment', 'people.track_charge', 'people.append']; for (e = 0; e < h.length; e++) d(g, h[e]); a._i.push([b, c, f]); }; a.__SV = 1.2; })(document, window.mixpanel || []); this.options.increments = lowercase(this.options.increments); var options = alias(this.options, optionsAliases); window.mixpanel.init(options.token, options); this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Mixpanel.prototype.loaded = function(){ return !! (window.mixpanel && window.mixpanel.config); }; /** * Page. * * https://mixpanel.com/help/reference/javascript-full-api-reference#mixpanel.track_pageview * * @param {String} category (optional) * @param {String} name (optional) * @param {Object} properties (optional) * @param {Object} options (optional) */ Mixpanel.prototype.page = function(page){ var category = page.category(); var name = page.fullName(); var opts = this.options; // all pages if (opts.trackAllPages) { this.track(page.track()); } // categorized pages if (category && opts.trackCategorizedPages) { this.track(page.track(category)); } // named pages if (name && opts.trackNamedPages) { this.track(page.track(name)); } }; /** * Trait aliases. */ var traitAliases = { created: '$created', email: '$email', firstName: '$first_name', lastName: '$last_name', lastSeen: '$last_seen', name: '$name', username: '$username', phone: '$phone' }; /** * Identify. * * https://mixpanel.com/help/reference/javascript#super-properties * https://mixpanel.com/help/reference/javascript#user-identity * https://mixpanel.com/help/reference/javascript#storing-user-profiles * * @param {Identify} identify */ Mixpanel.prototype.identify = function(identify){ var username = identify.username(); var email = identify.email(); var id = identify.userId(); // id if (id) window.mixpanel.identify(id); // name tag var nametag = email || username || id; if (nametag) window.mixpanel.name_tag(nametag); // traits var traits = identify.traits(traitAliases); if (traits.$created) del(traits, 'createdAt'); window.mixpanel.register(traits); if (this.options.people) window.mixpanel.people.set(traits); }; /** * Track. * * https://mixpanel.com/help/reference/javascript#sending-events * https://mixpanel.com/help/reference/javascript#tracking-revenue * * @param {Track} track */ Mixpanel.prototype.track = function(track){ var increments = this.options.increments; var increment = track.event().toLowerCase(); var people = this.options.people; var props = track.properties(); var revenue = track.revenue(); // delete mixpanel's reserved properties, so they don't conflict delete props.distinct_id; delete props.ip; delete props.mp_name_tag; delete props.mp_note; delete props.token; // increment properties in mixpanel people if (people && ~indexof(increments, increment)) { window.mixpanel.people.increment(track.event()); window.mixpanel.people.set('Last ' + track.event(), new Date); } // track the event props = dates(props, iso); window.mixpanel.track(track.event(), props); // track revenue specifically if (revenue && people) { window.mixpanel.people.track_charge(revenue); } }; /** * Alias. * * https://mixpanel.com/help/reference/javascript#user-identity * https://mixpanel.com/help/reference/javascript-full-api-reference#mixpanel.alias * * @param {Alias} alias */ Mixpanel.prototype.alias = function(alias){ var mp = window.mixpanel; var to = alias.to(); if (mp.get_distinct_id && mp.get_distinct_id() === to) return; // HACK: internal mixpanel API to ensure we don't overwrite if (mp.get_property && mp.get_property('$people_distinct_id') === to) return; // although undocumented, mixpanel takes an optional original id mp.alias(to, alias.from()); }; /** * Lowercase the given `arr`. * * @param {Array} arr * @return {Array} * @api private */ function lowercase(arr){ var ret = new Array(arr.length); for (var i = 0; i < arr.length; ++i) { ret[i] = String(arr[i]).toLowerCase(); } return ret; } }, {"alias":195,"clone":194,"convert-dates":196,"segmentio/analytics.js-integration":159,"to-iso-string":193,"indexof":46,"obj-case":60}], 131: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('segmentio/analytics.js-integration'); var bind = require('bind'); var when = require('when'); var is = require('is'); /** * Expose `Mojn` */ var Mojn = module.exports = integration('Mojn') .option('customerCode', '') .global('_mojnTrack') .tag('<script src="https://track.idtargeting.com/{{ customerCode }}/track.js">'); /** * Initialize. * * @param {Object} page */ Mojn.prototype.initialize = function(){ window._mojnTrack = window._mojnTrack || []; window._mojnTrack.push({ cid: this.options.customerCode }); var loaded = bind(this, this.loaded); var ready = this.ready; this.load(function(){ when(loaded, ready); }); }; /** * Loaded? * * @return {Boolean} */ Mojn.prototype.loaded = function(){ return is.object(window._mojnTrack); }; /** * Identify. * * @param {Identify} identify */ Mojn.prototype.identify = function(identify){ var email = identify.email(); if (!email) return; var img = new Image(); img.src = '//matcher.idtargeting.com/analytics.gif?cid=' + this.options.customerCode + '&_mjnctid='+email; img.width = 1; img.height = 1; return img; }; /** * Track. * * @param {Track} event */ Mojn.prototype.track = function(track){ var properties = track.properties(); var revenue = properties.revenue; var currency = properties.currency || ''; var conv = currency + revenue; if (!revenue) return; window._mojnTrack.push({ conv: conv }); return conv; }; }, {"segmentio/analytics.js-integration":159,"bind":33,"when":184,"is":18}], 132: [function(require, module, exports) { /** * Module dependencies. */ var push = require('global-queue')('_mfq'); var integration = require('segmentio/analytics.js-integration'); var each = require('each'); /** * Expose `Mouseflow`. */ var Mouseflow = module.exports = integration('Mouseflow') .assumesPageview() .global('mouseflow') .global('_mfq') .option('apiKey', '') .option('mouseflowHtmlDelay', 0) .tag('<script src="//cdn.mouseflow.com/projects/{{ apiKey }}.js">'); /** * Initalize. * * @param {Object} page */ Mouseflow.prototype.initialize = function(page){ window.mouseflowHtmlDelay = this.options.mouseflowHtmlDelay; this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Mouseflow.prototype.loaded = function(){ return !! window.mouseflow; }; /** * Page. * * http://mouseflow.zendesk.com/entries/22528817-Single-page-websites * * @param {Page} page */ Mouseflow.prototype.page = function(page){ if (!window.mouseflow) return; if ('function' != typeof mouseflow.newPageView) return; mouseflow.newPageView(); }; /** * Identify. * * http://mouseflow.zendesk.com/entries/24643603-Custom-Variables-Tagging * * @param {Identify} identify */ Mouseflow.prototype.identify = function(identify){ set(identify.traits()); }; /** * Track. * * http://mouseflow.zendesk.com/entries/24643603-Custom-Variables-Tagging * * @param {Track} track */ Mouseflow.prototype.track = function(track){ var props = track.properties(); props.event = track.event(); set(props); }; /** * Push each key and value in the given `obj` onto the queue. * * @param {Object} obj */ function set(obj){ each(obj, function(key, value){ push('setVariable', key, value); }); } }, {"global-queue":190,"segmentio/analytics.js-integration":159,"each":5}], 133: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('segmentio/analytics.js-integration'); var useHttps = require('use-https'); var each = require('each'); var is = require('is'); /** * Expose `MouseStats` integration. */ var MouseStats = module.exports = integration('MouseStats') .assumesPageview() .global('msaa') .global('MouseStatsVisitorPlaybacks') .option('accountNumber', '') .tag('http', '<script src="http://www2.mousestats.com/js/{{ path }}.js?{{ cache }}">') .tag('https', '<script src="https://ssl.mousestats.com/js/{{ path }}.js?{{ cache }}">'); /** * Initialize. * * http://www.mousestats.com/docs/pages/allpages * * @param {Object} page */ MouseStats.prototype.initialize = function(page){ var number = this.options.accountNumber; var path = number.slice(0,1) + '/' + number.slice(1,2) + '/' + number; var cache = Math.floor(new Date().getTime() / 60000); var name = useHttps() ? 'https' : 'http'; this.load(name, { path: path, cache: cache }, this.ready); }; /** * Loaded? * * @return {Boolean} */ MouseStats.prototype.loaded = function(){ return is.array(window.MouseStatsVisitorPlaybacks); }; /** * Identify. * * http://www.mousestats.com/docs/wiki/7/how-to-add-custom-data-to-visitor-playbacks * * @param {Identify} identify */ MouseStats.prototype.identify = function(identify){ each(identify.traits(), function (key, value) { window.MouseStatsVisitorPlaybacks.customVariable(key, value); }); }; }, {"segmentio/analytics.js-integration":159,"use-https":161,"each":5,"is":18}], 134: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('segmentio/analytics.js-integration'); var push = require('global-queue')('__nls'); /** * Expose `Navilytics` integration. */ var Navilytics = module.exports = integration('Navilytics') .assumesPageview() .global('__nls') .option('memberId', '') .option('projectId', '') .tag('<script src="//www.navilytics.com/nls.js?mid={{ memberId }}&pid={{ projectId }}">'); /** * Initialize. * * https://www.navilytics.com/member/code_settings * * @param {Object} page */ Navilytics.prototype.initialize = function(page){ window.__nls = window.__nls || []; this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Navilytics.prototype.loaded = function(){ return !! (window.__nls && [].push != window.__nls.push); }; /** * Track. * * https://www.navilytics.com/docs#tags * * @param {Track} track */ Navilytics.prototype.track = function(track){ push('tagRecording', track.event()); }; }, {"segmentio/analytics.js-integration":159,"global-queue":190}], 135: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('segmentio/analytics.js-integration'); var https = require('use-https'); var tick = require('next-tick'); /** * Expose `Olark` integration. */ var Olark = module.exports = integration('Olark') .assumesPageview() .global('olark') .option('identify', true) .option('page', true) .option('siteId', '') .option('groupId', '') .option('track', false); /** * Initialize. * * http://www.olark.com/documentation * https://www.olark.com/documentation/javascript/api.chat.setOperatorGroup * * @param {Object} page */ Olark.prototype.initialize = function(page){ var self = this; this.load(function(){ tick(self.ready); }); // assign chat to a specific site var groupId = this.options.groupId; if (groupId) { chat('setOperatorGroup', { group: groupId }); } // keep track of the widget's open state var self = this; box('onExpand', function(){ self._open = true; }); box('onShrink', function(){ self._open = false; }); }; /** * Loaded? * * @return {Boolean} */ Olark.prototype.loaded = function(){ return !! window.olark; }; /** * Load. * * @param {Function} callback */ Olark.prototype.load = function(callback){ var el = document.getElementById('olark'); //if (!el) { window.olark||(function(c){var f=window,d=document,l=https()?"https:":"http:",z=c.name,r="load";var nt=function(){f[z]=function(){(a.s=a.s||[]).push(arguments)};var a=f[z]._={},q=c.methods.length;while (q--) {(function(n){f[z][n]=function(){f[z]("call",n,arguments)}})(c.methods[q])}a.l=c.loader;a.i=nt;a.p={ 0:+new Date() };a.P=function(u){a.p[u]=new Date()-a.p[0]};function s(){a.P(r);f[z](r)}f.addEventListener?f.addEventListener(r,s,false):f.attachEvent("on"+r,s);var ld=function(){function p(hd){hd="head";return ["<",hd,"></",hd,"><",i,' onl' + 'oad="var d=',g,";d.getElementsByTagName('head')[0].",j,"(d.",h,"('script')).",k,"='",l,"//",a.l,"'",'"',"></",i,">"].join("")}var i="body",m=d[i];if (!m) {return setTimeout(ld,100)}a.P(1);var j="appendChild",h="createElement",k="src",n=d[h]("div"),v=n[j](d[h](z)),b=d[h]("iframe"),g="document",e="domain",o;n.style.display="none";m.insertBefore(n,m.firstChild).id=z;b.frameBorder="0";b.id=z+"-loader";if (/MSIE[ ]+6/.test(navigator.userAgent)) {b.src="javascript:false"}b.allowTransparency="true";v[j](b);try {b.contentWindow[g].open()}catch (w) {c[e]=d[e];o="javascript:var d="+g+".open();d.domain='"+d.domain+"';";b[k]=o+"void(0);"}try {var t=b.contentWindow[g];t.write(p());t.close()}catch (x) {b[k]=o+'d.write("'+p().replace(/"/g,String.fromCharCode(92)+'"')+'");d.close();'}a.P(2)};ld()};nt()})({ loader: "static.olark.com/jsclient/loader0.js", name:"olark", methods:["configure","extend","declare","identify"] }); window.olark.identify(this.options.siteId); //} callback(); }; /** * Page. * * @param {Page} page */ Olark.prototype.page = function(page){ if (!this.options.page || !this._open) return; var props = page.properties(); var name = page.fullName(); if (!name && !props.url) return; var msg = name ? name.toLowerCase() + ' page' : props.url; chat('sendNotificationToOperator', { body: 'looking at ' + msg // lowercase since olark does }); }; /** * Identify. * * @param {String} id (optional) * @param {Object} traits (optional) * @param {Object} options (optional) */ Olark.prototype.identify = function(identify){ if (!this.options.identify) return; var username = identify.username(); var traits = identify.traits(); var id = identify.userId(); var email = identify.email(); var phone = identify.phone(); var name = identify.name() || identify.firstName(); visitor('updateCustomFields', traits); if (email) visitor('updateEmailAddress', { emailAddress: email }); if (phone) visitor('updatePhoneNumber', { phoneNumber: phone }); // figure out best name if (name) visitor('updateFullName', { fullName: name }); // figure out best nickname var nickname = name || email || username || id; if (name && email) nickname += ' (' + email + ')'; if (nickname) chat('updateVisitorNickname', { snippet: nickname }); }; /** * Track. * * @param {String} event * @param {Object} properties (optional) * @param {Object} options (optional) */ Olark.prototype.track = function(track){ if (!this.options.track || !this._open) return; chat('sendNotificationToOperator', { body: 'visitor triggered "' + track.event() + '"' // lowercase since olark does }); }; /** * Helper method for Olark box API calls. * * @param {String} action * @param {Object} value */ function box(action, value){ window.olark('api.box.' + action, value); } /** * Helper method for Olark visitor API calls. * * @param {String} action * @param {Object} value */ function visitor(action, value){ window.olark('api.visitor.' + action, value); } /** * Helper method for Olark chat API calls. * * @param {String} action * @param {Object} value */ function chat(action, value){ window.olark('api.chat.' + action, value); } }, {"segmentio/analytics.js-integration":159,"use-https":161,"next-tick":45}], 136: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('segmentio/analytics.js-integration'); var push = require('global-queue')('optimizely'); var callback = require('callback'); var tick = require('next-tick'); var bind = require('bind'); var each = require('each'); /** * Expose `Optimizely` integration. */ var Optimizely = module.exports = integration('Optimizely') .option('variations', true) .option('trackNamedPages', true) .option('trackCategorizedPages', true); /** * Initialize. * * https://www.optimizely.com/docs/api#function-calls */ Optimizely.prototype.initialize = function(){ if (this.options.variations) { var self = this; tick(function(){ self.replay(); }); } this.ready(); }; /** * Track. * * https://www.optimizely.com/docs/api#track-event * * @param {Track} track */ Optimizely.prototype.track = function(track){ var props = track.properties(); if (props.revenue) props.revenue *= 100; push('trackEvent', track.event(), props); }; /** * Page. * * https://www.optimizely.com/docs/api#track-event * * @param {Page} page */ Optimizely.prototype.page = function(page){ var category = page.category(); var name = page.fullName(); var opts = this.options; // categorized pages if (category && opts.trackCategorizedPages) { this.track(page.track(category)); } // named pages if (name && opts.trackNamedPages) { this.track(page.track(name)); } }; /** * Replay experiment data as traits to other enabled providers. * * https://www.optimizely.com/docs/api#data-object */ Optimizely.prototype.replay = function(){ if (!window.optimizely) return; // in case the snippet isnt on the page var data = window.optimizely.data; if (!data) return; var experiments = data.experiments; var map = data.state.variationNamesMap; var traits = {}; each(map, function(experimentId, variation){ var experiment = experiments[experimentId].name; traits['Experiment: ' + experiment] = variation; }); this.analytics.identify(traits); }; }, {"segmentio/analytics.js-integration":159,"global-queue":190,"callback":12,"next-tick":45,"bind":33,"each":5}], 137: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('segmentio/analytics.js-integration'); /** * Expose `PerfectAudience` integration. */ var PerfectAudience = module.exports = integration('Perfect Audience') .assumesPageview() .global('_pa') .option('siteId', '') .tag('<script src="//tag.perfectaudience.com/serve/{{ siteId }}.js">'); /** * Initialize. * * https://www.perfectaudience.com/docs#javascript_api_autoopen * * @param {Object} page */ PerfectAudience.prototype.initialize = function(page){ window._pa = window._pa || {}; this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ PerfectAudience.prototype.loaded = function(){ return !! (window._pa && window._pa.track); }; /** * Track. * * @param {Track} event */ PerfectAudience.prototype.track = function(track){ window._pa.track(track.event(), track.properties()); }; }, {"segmentio/analytics.js-integration":159}], 138: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('segmentio/analytics.js-integration'); var push = require('global-queue')('_prum'); var date = require('load-date'); /** * Expose `Pingdom` integration. */ var Pingdom = module.exports = integration('Pingdom') .assumesPageview() .global('_prum') .global('PRUM_EPISODES') .option('id', '') .tag('<script src="//rum-static.pingdom.net/prum.min.js">'); /** * Initialize. * * @param {Object} page */ Pingdom.prototype.initialize = function(page){ window._prum = window._prum || []; push('id', this.options.id); push('mark', 'firstbyte', date.getTime()); var self = this; this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Pingdom.prototype.loaded = function(){ return !! (window._prum && window._prum.push !== Array.prototype.push); }; }, {"segmentio/analytics.js-integration":159,"global-queue":190,"load-date":191}], 139: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('segmentio/analytics.js-integration'); var push = require('global-queue')('_paq'); var each = require('each'); /** * Expose `Piwik` integration. */ var Piwik = module.exports = integration('Piwik') .global('_paq') .option('url', null) .option('siteId', '') .mapping('goals') .tag('<script src="{{ url }}/piwik.js">'); /** * Initialize. * * http://piwik.org/docs/javascript-tracking/#toc-asynchronous-tracking */ Piwik.prototype.initialize = function(){ window._paq = window._paq || []; push('setSiteId', this.options.siteId); push('setTrackerUrl', this.options.url + '/piwik.php'); push('enableLinkTracking'); this.load(this.ready); }; /** * Check if Piwik is loaded */ Piwik.prototype.loaded = function(){ return !! (window._paq && window._paq.push != [].push); }; /** * Page * * @param {Page} page */ Piwik.prototype.page = function(page){ push('trackPageView'); }; /** * Track. * * @param {Track} track */ Piwik.prototype.track = function(track){ var goals = this.goals(track.event()); var revenue = track.revenue() || 0; each(goals, function(goal){ push('trackGoal', goal, revenue); }); }; }, {"segmentio/analytics.js-integration":159,"global-queue":190,"each":5}], 140: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('segmentio/analytics.js-integration'); var convertDates = require('convert-dates'); var push = require('global-queue')('_lnq'); var alias = require('alias'); /** * Expose `Preact` integration. */ var Preact = module.exports = integration('Preact') .assumesPageview() .global('_lnq') .option('projectCode', '') .tag('<script src="//d2bbvl6dq48fa6.cloudfront.net/js/ln-2.4.min.js">'); /** * Initialize. * * http://www.preact.io/api/javascript * * @param {Object} page */ Preact.prototype.initialize = function(page){ window._lnq = window._lnq || []; push('_setCode', this.options.projectCode); this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Preact.prototype.loaded = function(){ return !! (window._lnq && window._lnq.push !== Array.prototype.push); }; /** * Identify. * * @param {Identify} identify */ Preact.prototype.identify = function(identify){ if (!identify.userId()) return; var traits = identify.traits({ created: 'created_at' }); traits = convertDates(traits, convertDate); push('_setPersonData', { name: identify.name(), email: identify.email(), uid: identify.userId(), properties: traits }); }; /** * Group. * * @param {String} id * @param {Object} properties (optional) * @param {Object} options (optional) */ Preact.prototype.group = function(group){ if (!group.groupId()) return; push('_setAccount', group.traits()); }; /** * Track. * * @param {Track} track */ Preact.prototype.track = function(track){ var props = track.properties(); var revenue = track.revenue(); var event = track.event(); var special = { name: event }; if (revenue) { special.revenue = revenue * 100; delete props.revenue; } if (props.note) { special.note = props.note; delete props.note; } push('_logEvent', special, props); }; /** * Convert a `date` to a format Preact supports. * * @param {Date} date * @return {Number} */ function convertDate(date){ return Math.floor(date / 1000); } }, {"segmentio/analytics.js-integration":159,"convert-dates":196,"global-queue":190,"alias":195}], 141: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('segmentio/analytics.js-integration'); var push = require('global-queue')('_kiq'); var Facade = require('facade'); var Identify = Facade.Identify; var bind = require('bind'); var when = require('when'); /** * Expose `Qualaroo` integration. */ var Qualaroo = module.exports = integration('Qualaroo') .assumesPageview() .global('_kiq') .option('customerId', '') .option('siteToken', '') .option('track', false) .tag('<script src="//s3.amazonaws.com/ki.js/{{ customerId }}/{{ siteToken }}.js">'); /** * Initialize. * * @param {Object} page */ Qualaroo.prototype.initialize = function(page){ window._kiq = window._kiq || []; var loaded = bind(this, this.loaded); var ready = this.ready; this.load(function(){ when(loaded, ready); }); }; /** * Loaded? * * @return {Boolean} */ Qualaroo.prototype.loaded = function(){ return !! (window._kiq && window._kiq.push !== Array.prototype.push); }; /** * Identify. * * http://help.qualaroo.com/customer/portal/articles/731085-identify-survey-nudge-takers * http://help.qualaroo.com/customer/portal/articles/731091-set-additional-user-properties * * @param {Identify} identify */ Qualaroo.prototype.identify = function(identify){ var traits = identify.traits(); var id = identify.userId(); var email = identify.email(); if (email) id = email; if (id) push('identify', id); if (traits) push('set', traits); }; /** * Track. * * @param {String} event * @param {Object} properties (optional) * @param {Object} options (optional) */ Qualaroo.prototype.track = function(track){ if (!this.options.track) return; var event = track.event(); var traits = {}; traits['Triggered: ' + event] = true; this.identify(new Identify({ traits: traits })); }; }, {"segmentio/analytics.js-integration":159,"global-queue":190,"facade":27,"bind":33,"when":184}], 142: [function(require, module, exports) { /** * Module dependencies. */ var push = require('global-queue')('_qevents', { wrap: false }); var integration = require('segmentio/analytics.js-integration'); var useHttps = require('use-https'); /** * Expose `Quantcast` integration. */ var Quantcast = module.exports = integration('Quantcast') .assumesPageview() .global('_qevents') .global('__qc') .option('pCode', null) .option('advertise', false) .tag('http', '<script src="http://edge.quantserve.com/quant.js">') .tag('https', '<script src="https://secure.quantserve.com/quant.js">'); /** * Initialize. * * https://www.quantcast.com/learning-center/guides/using-the-quantcast-asynchronous-tag/ * https://www.quantcast.com/help/cross-platform-audience-measurement-guide/ * * @param {Page} page */ Quantcast.prototype.initialize = function(page){ window._qevents = window._qevents || []; var opts = this.options; var settings = { qacct: opts.pCode }; var user = this.analytics.user(); if (user.id()) settings.uid = user.id(); if (page) { settings.labels = this.labels('page', page.category(), page.name()); } push(settings); var name = useHttps() ? 'https' : 'http'; this.load(name, this.ready); }; /** * Loaded? * * @return {Boolean} */ Quantcast.prototype.loaded = function(){ return !! window.__qc; }; /** * Page. * * https://cloudup.com/cBRRFAfq6mf * * @param {Page} page */ Quantcast.prototype.page = function(page){ var category = page.category(); var name = page.name(); var settings = { event: 'refresh', labels: this.labels('page', category, name), qacct: this.options.pCode, }; var user = this.analytics.user(); if (user.id()) settings.uid = user.id(); push(settings); }; /** * Identify. * * https://www.quantcast.com/help/cross-platform-audience-measurement-guide/ * * @param {String} id (optional) */ Quantcast.prototype.identify = function(identify){ // edit the initial quantcast settings // TODO: could be done in a cleaner way var id = identify.userId(); if (id) { window._qevents[0] = window._qevents[0] || {}; window._qevents[0].uid = id; } }; /** * Track. * * https://cloudup.com/cBRRFAfq6mf * * @param {Track} track */ Quantcast.prototype.track = function(track){ var name = track.event(); var revenue = track.revenue(); var settings = { event: 'click', labels: this.labels('event', name), qacct: this.options.pCode }; var user = this.analytics.user(); if (null != revenue) settings.revenue = (revenue+''); // convert to string if (user.id()) settings.uid = user.id(); push(settings); }; /** * Completed Order. * * @param {Track} track * @api private */ Quantcast.prototype.completedOrder = function(track){ var name = track.event(); var revenue = track.total(); var labels = this.labels('event', name); var category = track.category(); if (this.options.advertise && category) { labels += ',' + this.labels('pcat', category); } var settings = { event: 'refresh', // the example Quantcast sent has completed order send refresh not click labels: labels, revenue: (revenue+''), // convert to string orderid: track.orderId(), qacct: this.options.pCode }; push(settings); }; /** * Generate quantcast labels. * * Example: * * options.advertise = false; * labels('event', 'my event'); * // => "event.my event" * * options.advertise = true; * labels('event', 'my event'); * // => "_fp.event.my event" * * @param {String} type * @param {String} ... * @return {String} * @api private */ Quantcast.prototype.labels = function(type){ var args = [].slice.call(arguments, 1); var advertise = this.options.advertise; var ret = []; if (advertise && 'page' == type) type = 'event'; if (advertise) type = '_fp.' + type; for (var i = 0; i < args.length; ++i) { if (null == args[i]) continue; var value = String(args[i]); ret.push(value.replace(/,/g, ';')); } ret = advertise ? ret.join(' ') : ret.join('.'); return [type, ret].join('.'); }; }, {"global-queue":190,"segmentio/analytics.js-integration":159,"use-https":161}], 143: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('segmentio/analytics.js-integration'); var extend = require('extend'); var is = require('is'); /** * Expose `Rollbar` integration. */ var RollbarIntegration = module.exports = integration('Rollbar') .global('Rollbar') .option('identify', true) .option('accessToken', '') .option('environment', 'unknown') .option('captureUncaught', true); /** * Initialize. * * @param {Object} page */ RollbarIntegration.prototype.initialize = function(page){ var _rollbarConfig = this.config = { accessToken: this.options.accessToken, captureUncaught: this.options.captureUncaught, payload: { environment: this.options.environment } }; (function(a){function b(b){this.shimId=++g,this.notifier=null,this.parentShim=b,this.logger=function(){},a.console&&void 0 === a.console.shimId&&(this.logger=a.console.log)}function c(b,c,d){!d[4]&&a._rollbarWrappedError&&(d[4]=a._rollbarWrappedError,a._rollbarWrappedError=null),b.uncaughtError.apply(b,d),c&&c.apply(a,d)}function d(c){var d=b;return f(function(){if (this.notifier)return this.notifier[c].apply(this.notifier,arguments);var b=this,e="scope"===c;e&&(b=new d(this));var f=Array.prototype.slice.call(arguments,0),g={ shim:b, method:c, args:f, ts:new Date };return a._rollbarShimQueue.push(g),e?b:void 0})}function e(a,b){if (b.hasOwnProperty&&b.hasOwnProperty("addEventListener")){var c=b.addEventListener;b.addEventListener=function(b,d,e){c.call(this,b,a.wrap(d),e)};var d=b.removeEventListener;b.removeEventListener=function(a,b,c){d.call(this,a,b._wrapped||b,c)}}}function f(a,b){return b=b||this.logger,function(){try {return a.apply(this,arguments)} catch (c) {b("Rollbar internal error:",c)}}}var g=0;b.init=function(a,d){var g=d.globalAlias||"Rollbar";if ("object"==typeof a[g])return a[g];a._rollbarShimQueue=[],a._rollbarWrappedError=null,d=d||{};var h=new b;return f(function(){if (h.configure(d),d.captureUncaught){var b=a.onerror;a.onerror=function(){var a=Array.prototype.slice.call(arguments,0);c(h,b,a)};var f,i,j=["EventTarget","Window","Node","ApplicationCache","AudioTrackList","ChannelMergerNode","CryptoOperation","EventSource","FileReader","HTMLUnknownElement","IDBDatabase","IDBRequest","IDBTransaction","KeyOperation","MediaController","MessagePort","ModalWindow","Notification","SVGElementInstance","Screen","TextTrack","TextTrackCue","TextTrackList","WebSocket","WebSocketWorker","Worker","XMLHttpRequest","XMLHttpRequestEventTarget","XMLHttpRequestUpload"];for (f=0;f<j.length;++f)i=j[f],a[i]&&a[i].prototype&&e(h,a[i].prototype)}return a[g]=h,h},h.logger)()},b.prototype.loadFull=function(a,b,c,d,e){var g=f(function(){var a=b.createElement("script"),e=b.getElementsByTagName("script")[0];a.src=d.rollbarJsUrl,a.async=!c,a.onload=h,e.parentNode.insertBefore(a,e)},this.logger),h=f(function(){var b;if (void 0===a._rollbarPayloadQueue){var c,d,f,g;for (b=new Error("rollbar.js did not load");c=a._rollbarShimQueue.shift();)for (f=c.args,g=0;g<f.length;++g)if (d=f[g],"function"==typeof d){d(b);break}}e&&e(b)},this.logger);f(function(){c?g():a.addEventListener?a.addEventListener("load",g,!1):a.attachEvent("onload",g)},this.logger)()},b.prototype.wrap=function(b){if ("function"!=typeof b)return b;if (b._isWrap)return b;if (!b._wrapped){b._wrapped=function(){try {return b.apply(this,arguments)} catch (c) {throw a._rollbarWrappedError=c,c}},b._wrapped._isWrap=!0;for (var c in b)b.hasOwnProperty(c)&&(b._wrapped[c]=b[c])}return b._wrapped};for (var h="log,debug,info,warn,warning,error,critical,global,configure,scope,uncaughtError".split(","),i=0;i<h.length;++i)b.prototype[h[i]]=d(h[i]);var j="//d37gvrvc0wt4s1.cloudfront.net/js/v1.0/rollbar.min.js";_rollbarConfig.rollbarJsUrl=_rollbarConfig.rollbarJsUrl||j,b.init(a,_rollbarConfig)})(window,document); this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ RollbarIntegration.prototype.loaded = function(){ return is.object(window.Rollbar) && null == window.Rollbar.shimId; }; /** * Load. * * @param {Function} callback */ RollbarIntegration.prototype.load = function(callback){ window.Rollbar.loadFull(window, document, true, this.config, callback); }; /** * Identify. * * @param {Identify} identify */ RollbarIntegration.prototype.identify = function(identify){ // do stuff with `id` or `traits` if (!this.options.identify) return; // Don't allow identify without a user id var uid = identify.userId(); if (uid === null || uid === undefined) return; var rollbar = window.Rollbar; var person = { id: uid }; extend(person, identify.traits()); rollbar.configure({ payload: { person: person }}); }; }, {"segmentio/analytics.js-integration":159,"extend":40,"is":18}], 144: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('segmentio/analytics.js-integration'); /** * Expose `SaaSquatch` integration. */ var SaaSquatch = module.exports = integration('SaaSquatch') .option('tenantAlias', '') .global('_sqh') .tag('<script src="//d2rcp9ak152ke1.cloudfront.net/assets/javascripts/squatch.min.js">'); /** * Initialize. * * @param {Page} page */ SaaSquatch.prototype.initialize = function(page){ window._sqh = window._sqh || []; this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ SaaSquatch.prototype.loaded = function(){ return window._sqh && window._sqh.push != [].push; }; /** * Identify. * * @param {Facade} identify */ SaaSquatch.prototype.identify = function(identify){ var sqh = window._sqh; var accountId = identify.proxy('traits.accountId'); var image = identify.proxy('traits.referralImage'); var opts = identify.options(this.name); var id = identify.userId(); var email = identify.email(); if (!(id || email)) return; if (this.called) return; var init = { tenant_alias: this.options.tenantAlias, first_name: identify.firstName(), last_name: identify.lastName(), user_image: identify.avatar(), email: email, user_id: id, }; if (accountId) init.account_id = accountId; if (opts.checksum) init.checksum = opts.checksum; if (image) init.fb_share_image = image; sqh.push(['init', init]); this.called = true; this.load(); }; }, {"segmentio/analytics.js-integration":159}], 145: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('segmentio/analytics.js-integration'); var is = require('is'); /** * Expose `Sentry` integration. */ var Sentry = module.exports = integration('Sentry') .global('Raven') .option('config', '') .tag('<script src="//cdn.ravenjs.com/1.1.10/native/raven.min.js">'); /** * Initialize. * * http://raven-js.readthedocs.org/en/latest/config/index.html */ Sentry.prototype.initialize = function(){ var config = this.options.config; var self = this; this.load(function(){ // for now, raven basically requires `install` to be called // https://github.com/getsentry/raven-js/blob/master/src/raven.js#L113 window.Raven.config(config).install(); self.ready(); }); }; /** * Loaded? * * @return {Boolean} */ Sentry.prototype.loaded = function(){ return is.object(window.Raven); }; /** * Identify. * * @param {Identify} identify */ Sentry.prototype.identify = function(identify){ window.Raven.setUser(identify.traits()); }; }, {"segmentio/analytics.js-integration":159,"is":18}], 146: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('segmentio/analytics.js-integration'); var is = require('is'); /** * Expose `SnapEngage` integration. */ var SnapEngage = module.exports = integration('SnapEngage') .assumesPageview() .global('SnapABug') .option('apiKey', '') .tag('<script src="//commondatastorage.googleapis.com/code.snapengage.com/js/{{ apiKey }}.js">'); /** * Initialize. * * http://help.snapengage.com/installation-guide-getting-started-in-a-snap/ * * @param {Object} page */ SnapEngage.prototype.initialize = function(page){ this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ SnapEngage.prototype.loaded = function(){ return is.object(window.SnapABug); }; /** * Identify. * * @param {Identify} identify */ SnapEngage.prototype.identify = function(identify){ var email = identify.email(); if (!email) return; window.SnapABug.setUserEmail(email); }; }, {"segmentio/analytics.js-integration":159,"is":18}], 147: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('segmentio/analytics.js-integration'); var bind = require('bind'); var when = require('when'); /** * Expose `Spinnakr` integration. */ var Spinnakr = module.exports = integration('Spinnakr') .assumesPageview() .global('_spinnakr_site_id') .global('_spinnakr') .option('siteId', '') .tag('<script src="//d3ojzyhbolvoi5.cloudfront.net/js/so.js">'); /** * Initialize. * * @param {Object} page */ Spinnakr.prototype.initialize = function(page){ window._spinnakr_site_id = this.options.siteId; var loaded = bind(this, this.loaded); var ready = this.ready; this.load(function(){ when(loaded, ready); }); }; /** * Loaded? * * @return {Boolean} */ Spinnakr.prototype.loaded = function(){ return !! window._spinnakr; }; }, {"segmentio/analytics.js-integration":159,"bind":33,"when":184}], 148: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('segmentio/analytics.js-integration'); var slug = require('slug'); var push = require('global-queue')('_tsq'); /** * Expose `Tapstream` integration. */ var Tapstream = module.exports = integration('Tapstream') .assumesPageview() .global('_tsq') .option('accountName', '') .option('trackAllPages', true) .option('trackNamedPages', true) .option('trackCategorizedPages', true) .tag('<script src="//cdn.tapstream.com/static/js/tapstream.js">'); /** * Initialize. * * @param {Object} page */ Tapstream.prototype.initialize = function(page){ window._tsq = window._tsq || []; push('setAccountName', this.options.accountName); this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Tapstream.prototype.loaded = function(){ return !! (window._tsq && window._tsq.push !== Array.prototype.push); }; /** * Page. * * @param {Page} page */ Tapstream.prototype.page = function(page){ var category = page.category(); var opts = this.options; var name = page.fullName(); // all pages if (opts.trackAllPages) { this.track(page.track()); } // named pages if (name && opts.trackNamedPages) { this.track(page.track(name)); } // categorized pages if (category && opts.trackCategorizedPages) { this.track(page.track(category)); } }; /** * Track. * * @param {Track} track */ Tapstream.prototype.track = function(track){ var props = track.properties(); push('fireHit', slug(track.event()), [props.url]); // needs events as slugs }; }, {"segmentio/analytics.js-integration":159,"slug":166,"global-queue":190}], 149: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('segmentio/analytics.js-integration'); var alias = require('alias'); var clone = require('clone'); /** * Expose `Trakio` integration. */ var Trakio = module.exports = integration('trak.io') .assumesPageview() .global('trak') .option('token', '') .option('trackNamedPages', true) .option('trackCategorizedPages', true) .tag('<script src="//d29p64779x43zo.cloudfront.net/v1/trak.io.min.js">'); /** * Options aliases. */ var optionsAliases = { initialPageview: 'auto_track_page_view' }; /** * Initialize. * * https://docs.trak.io * * @param {Object} page */ Trakio.prototype.initialize = function(page){ var options = this.options; window.trak = window.trak || []; window.trak.io = window.trak.io || {}; window.trak.push = window.trak.push || function(){}; window.trak.io.load = window.trak.io.load || function(e){var r = function(e){return function(){window.trak.push([e].concat(Array.prototype.slice.call(arguments,0))); }; } ,i=["initialize","identify","track","alias","channel","source","host","protocol","page_view"]; for (var s=0;s<i.length;s++) window.trak.io[i[s]]=r(i[s]); window.trak.io.initialize.apply(window.trak.io,arguments); }; window.trak.io.load(options.token, alias(options, optionsAliases)); this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Trakio.prototype.loaded = function(){ return !! (window.trak && window.trak.loaded); }; /** * Page. * * @param {Page} page */ Trakio.prototype.page = function(page){ var category = page.category(); var props = page.properties(); var name = page.fullName(); window.trak.io.page_view(props.path, name || props.title); // named pages if (name && this.options.trackNamedPages) { this.track(page.track(name)); } // categorized pages if (category && this.options.trackCategorizedPages) { this.track(page.track(category)); } }; /** * Trait aliases. * * http://docs.trak.io/properties.html#special */ var traitAliases = { avatar: 'avatar_url', firstName: 'first_name', lastName: 'last_name' }; /** * Identify. * * @param {Identify} identify */ Trakio.prototype.identify = function(identify){ var traits = identify.traits(traitAliases); var id = identify.userId(); if (id) { window.trak.io.identify(id, traits); } else { window.trak.io.identify(traits); } }; /** * Group. * * @param {String} id (optional) * @param {Object} properties (optional) * @param {Object} options (optional) * * TODO: add group * TODO: add `trait.company/organization` from trak.io docs http://docs.trak.io/properties.html#special */ /** * Track. * * @param {Track} track */ Trakio.prototype.track = function(track){ window.trak.io.track(track.event(), track.properties()); }; /** * Alias. * * @param {Alias} alias */ Trakio.prototype.alias = function(alias){ if (!window.trak.io.distinct_id) return; var from = alias.from(); var to = alias.to(); if (to === window.trak.io.distinct_id()) return; if (from) { window.trak.io.alias(from, to); } else { window.trak.io.alias(to); } }; }, {"segmentio/analytics.js-integration":159,"alias":195,"clone":194}], 150: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('segmentio/analytics.js-integration'); var each = require('each'); /** * HOP. */ var has = Object.prototype.hasOwnProperty; /** * Expose `TwitterAds`. */ var TwitterAds = module.exports = integration('Twitter Ads') .tag('pixel', '<img src="//analytics.twitter.com/i/adsct?txn_id={{ event }}&p_id=Twitter"/>') .mapping('events'); /** * Initialize. * * @param {Object} page */ TwitterAds.prototype.initialize = function(){ this.ready(); }; /** * Track. * * @param {Track} track */ TwitterAds.prototype.track = function(track){ var events = this.events(track.event()); var self = this; each(events, function(event){ var el = self.load('pixel', { event: event }); }); }; }, {"segmentio/analytics.js-integration":159,"each":5}], 151: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('segmentio/analytics.js-integration'); var push = require('global-queue')('_uc'); /** * Expose `Usercycle` integration. */ var Usercycle = module.exports = integration('USERcycle') .assumesPageview() .global('_uc') .option('key', '') .tag('<script src="//api.usercycle.com/javascripts/track.js">'); /** * Initialize. * * http://docs.usercycle.com/javascript_api * * @param {Object} page */ Usercycle.prototype.initialize = function(page){ push('_key', this.options.key); this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Usercycle.prototype.loaded = function(){ return !! (window._uc && window._uc.push !== Array.prototype.push); }; /** * Identify. * * @param {Identify} identify */ Usercycle.prototype.identify = function(identify){ var traits = identify.traits(); var id = identify.userId(); if (id) push('uid', id); // there's a special `came_back` event used for retention and traits push('action', 'came_back', traits); }; /** * Track. * * @param {Track} track */ Usercycle.prototype.track = function(track){ push('action', track.event(), track.properties({ revenue: 'revenue_amount' })); }; }, {"segmentio/analytics.js-integration":159,"global-queue":190}], 152: [function(require, module, exports) { /** * Module dependencies. */ var alias = require('alias'); var callback = require('callback'); var convertDates = require('convert-dates'); var integration = require('analytics.js-integration'); var load = require('load-script'); var push = require('global-queue')('_ufq'); /** * Expose plugin. */ module.exports = exports = function(analytics){ analytics.addIntegration(Userfox); }; /** * Expose `Userfox` integration. */ var Userfox = exports.Integration = integration('userfox') .assumesPageview() .readyOnLoad() .global('_ufq') .option('clientId', ''); /** * Initialize. * * https://www.userfox.com/docs/ * * @param {Object} page */ Userfox.prototype.initialize = function(page){ window._ufq = []; this.load(); }; /** * Loaded? * * @return {Boolean} */ Userfox.prototype.loaded = function(){ return !! (window._ufq && window._ufq.push !== Array.prototype.push); }; /** * Load. * * @param {Function} callback */ Userfox.prototype.load = function(callback){ load('//d2y71mjhnajxcg.cloudfront.net/js/userfox-stable.js', callback); }; /** * Identify. * * https://www.userfox.com/docs/#custom-data * * @param {Identify} identify */ Userfox.prototype.identify = function(identify){ var traits = identify.traits({ created: 'signup_date' }); var email = identify.email(); if (!email) return; // initialize the library with the email now that we have it push('init', { clientId: this.options.clientId, email: email }); traits = convertDates(traits, formatDate); push('track', traits); }; /** * Convert a `date` to a format userfox supports. * * @param {Date} date * @return {String} */ function formatDate(date){ return Math.round(date.getTime() / 1000).toString(); } }, {"alias":195,"callback":12,"convert-dates":196,"analytics.js-integration":159,"load-script":168,"global-queue":190}], 153: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('segmentio/analytics.js-integration'); var push = require('global-queue')('UserVoice'); var convertDates = require('convert-dates'); var unix = require('to-unix-timestamp'); var alias = require('alias'); var clone = require('clone'); /** * Expose `UserVoice` integration. */ var UserVoice = module.exports = integration('UserVoice') .assumesPageview() .global('UserVoice') .global('showClassicWidget') .option('apiKey', '') .option('classic', false) .option('forumId', null) .option('showWidget', true) .option('mode', 'contact') .option('accentColor', '#448dd6') .option('smartvote', true) .option('trigger', null) .option('triggerPosition', 'bottom-right') .option('triggerColor', '#ffffff') .option('triggerBackgroundColor', 'rgba(46, 49, 51, 0.6)') // BACKWARDS COMPATIBILITY: classic options .option('classicMode', 'full') .option('primaryColor', '#cc6d00') .option('linkColor', '#007dbf') .option('defaultMode', 'support') .option('tabLabel', 'Feedback & Support') .option('tabColor', '#cc6d00') .option('tabPosition', 'middle-right') .option('tabInverted', false) .tag('<script src="//widget.uservoice.com/{{ apiKey }}.js">'); /** * When in "classic" mode, on `construct` swap all of the method to point to * their classic counterparts. */ UserVoice.on('construct', function(integration){ if (!integration.options.classic) return; integration.group = undefined; integration.identify = integration.identifyClassic; integration.initialize = integration.initializeClassic; }); /** * Initialize. * * @param {Object} page */ UserVoice.prototype.initialize = function(page){ var options = this.options; var opts = formatOptions(options); push('set', opts); push('autoprompt', {}); if (options.showWidget) { options.trigger ? push('addTrigger', options.trigger, opts) : push('addTrigger', opts); } this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ UserVoice.prototype.loaded = function(){ return !! (window.UserVoice && window.UserVoice.push !== Array.prototype.push); }; /** * Identify. * * @param {Identify} identify */ UserVoice.prototype.identify = function(identify){ var traits = identify.traits({ created: 'created_at' }); traits = convertDates(traits, unix); push('identify', traits); }; /** * Group. * * @param {Group} group */ UserVoice.prototype.group = function(group){ var traits = group.traits({ created: 'created_at' }); traits = convertDates(traits, unix); push('identify', { account: traits }); }; /** * Initialize (classic). * * @param {Object} options * @param {Function} ready */ UserVoice.prototype.initializeClassic = function(){ var options = this.options; window.showClassicWidget = showClassicWidget; // part of public api if (options.showWidget) showClassicWidget('showTab', formatClassicOptions(options)); this.load(this.ready); }; /** * Identify (classic). * * @param {Identify} identify */ UserVoice.prototype.identifyClassic = function(identify){ push('setCustomFields', identify.traits()); }; /** * Format the options for UserVoice. * * @param {Object} options * @return {Object} */ function formatOptions(options){ return alias(options, { forumId: 'forum_id', accentColor: 'accent_color', smartvote: 'smartvote_enabled', triggerColor: 'trigger_color', triggerBackgroundColor: 'trigger_background_color', triggerPosition: 'trigger_position' }); } /** * Format the classic options for UserVoice. * * @param {Object} options * @return {Object} */ function formatClassicOptions(options){ return alias(options, { forumId: 'forum_id', classicMode: 'mode', primaryColor: 'primary_color', tabPosition: 'tab_position', tabColor: 'tab_color', linkColor: 'link_color', defaultMode: 'default_mode', tabLabel: 'tab_label', tabInverted: 'tab_inverted' }); } /** * Show the classic version of the UserVoice widget. This method is usually part * of UserVoice classic's public API. * * @param {String} type ('showTab' or 'showLightbox') * @param {Object} options (optional) */ function showClassicWidget(type, options){ type = type || 'showLightbox'; push(type, 'classic_widget', options); } }, {"segmentio/analytics.js-integration":159,"global-queue":190,"convert-dates":196,"to-unix-timestamp":199,"alias":195,"clone":194}], 199: [function(require, module, exports) { /** * Expose `toUnixTimestamp`. */ module.exports = toUnixTimestamp; /** * Convert a `date` into a Unix timestamp. * * @param {Date} * @return {Number} */ function toUnixTimestamp (date) { return Math.floor(date.getTime() / 1000); } }, {}], 154: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('segmentio/analytics.js-integration'); var push = require('global-queue')('_veroq'); var cookie = require('component/cookie'); /** * Expose `Vero` integration. */ var Vero = module.exports = integration('Vero') .global('_veroq') .option('apiKey', '') .tag('<script src="//d3qxef4rp70elm.cloudfront.net/m.js">'); /** * Initialize. * * https://github.com/getvero/vero-api/blob/master/sections/js.md * * @param {Object} page */ Vero.prototype.initialize = function(page){ // clear default cookie so vero parses correctly. // this is for the tests. // basically, they have window.addEventListener('unload') // which then saves their "command_store", which is an array. // so we just want to create that initially so we can reload the tests. if (!cookie('__veroc4')) cookie('__veroc4', '[]'); push('init', { api_key: this.options.apiKey }); this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Vero.prototype.loaded = function(){ return !! (window._veroq && window._veroq.push !== Array.prototype.push); }; /** * Page. * * https://www.getvero.com/knowledge-base#/questions/71768-Does-Vero-track-pageviews * * @param {Page} page */ Vero.prototype.page = function(page){ push('trackPageview'); }; /** * Identify. * * https://github.com/getvero/vero-api/blob/master/sections/js.md#user-identification * * @param {Identify} identify */ Vero.prototype.identify = function(identify){ var traits = identify.traits(); var email = identify.email(); var id = identify.userId(); if (!id || !email) return; // both required push('user', traits); }; /** * Track. * * https://github.com/getvero/vero-api/blob/master/sections/js.md#tracking-events * * @param {Track} track */ Vero.prototype.track = function(track){ push('track', track.event(), track.properties()); }; }, {"segmentio/analytics.js-integration":159,"global-queue":190,"component/cookie":28}], 155: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('segmentio/analytics.js-integration'); var tick = require('next-tick'); var each = require('each'); /** * Expose `VWO` integration. */ var VWO = module.exports = integration('Visual Website Optimizer') .option('replay', true); /** * Initialize. * * http://v2.visualwebsiteoptimizer.com/tools/get_tracking_code.php */ VWO.prototype.initialize = function(){ if (this.options.replay) this.replay(); this.ready(); }; /** * Replay the experiments the user has seen as traits to all other integrations. * Wait for the next tick to replay so that the `analytics` object and all of * the integrations are fully initialized. */ VWO.prototype.replay = function(){ var analytics = this.analytics; tick(function(){ experiments(function(err, traits){ if (traits) analytics.identify(traits); }); }); }; /** * Get dictionary of experiment keys and variations. * * http://visualwebsiteoptimizer.com/knowledge/integration-of-vwo-with-kissmetrics/ * * @param {Function} fn * @return {Object} */ function experiments(fn){ enqueue(function(){ var data = {}; var ids = window._vwo_exp_ids; if (!ids) return fn(); each(ids, function(id){ var name = variation(id); if (name) data['Experiment: ' + id] = name; }); fn(null, data); }); } /** * Add a `fn` to the VWO queue, creating one if it doesn't exist. * * @param {Function} fn */ function enqueue(fn){ window._vis_opt_queue = window._vis_opt_queue || []; window._vis_opt_queue.push(fn); } /** * Get the chosen variation's name from an experiment `id`. * * http://visualwebsiteoptimizer.com/knowledge/integration-of-vwo-with-kissmetrics/ * * @param {String} id * @return {String} */ function variation(id){ var experiments = window._vwo_exp; if (!experiments) return null; var experiment = experiments[id]; var variationId = experiment.combination_chosen; return variationId ? experiment.comb_n[variationId] : null; } }, {"segmentio/analytics.js-integration":159,"next-tick":45,"each":5}], 156: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('segmentio/analytics.js-integration'); var useHttps = require('use-https'); /** * Expose `WebEngage` integration. */ var WebEngage = module.exports = integration('WebEngage') .assumesPageview() .global('_weq') .global('webengage') .option('widgetVersion', '4.0') .option('licenseCode', '') .tag('http', '<script src="http://cdn.widgets.webengage.com/js/widget/webengage-min-v-4.0.js">') .tag('https', '<script src="https://ssl.widgets.webengage.com/js/widget/webengage-min-v-4.0.js">'); /** * Initialize. * * @param {Object} page */ WebEngage.prototype.initialize = function(page){ var _weq = window._weq = window._weq || {}; _weq['webengage.licenseCode'] = this.options.licenseCode; _weq['webengage.widgetVersion'] = this.options.widgetVersion; var name = useHttps() ? 'https' : 'http'; this.load(name, this.ready); }; /** * Loaded? * * @return {Boolean} */ WebEngage.prototype.loaded = function(){ return !! window.webengage; }; }, {"segmentio/analytics.js-integration":159,"use-https":161}], 157: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('segmentio/analytics.js-integration'); var snake = require('to-snake-case'); var isEmail = require('is-email'); var extend = require('extend'); var each = require('each'); var type = require('type'); /** * Expose `Woopra` integration. */ var Woopra = module.exports = integration('Woopra') .global('woopra') .option('domain', '') .option('cookieName', 'wooTracker') .option('cookieDomain', null) .option('cookiePath', '/') .option('ping', true) .option('pingInterval', 12000) .option('idleTimeout', 300000) .option('downloadTracking', true) .option('outgoingTracking', true) .option('outgoingIgnoreSubdomain', true) .option('downloadPause', 200) .option('outgoingPause', 400) .option('ignoreQueryUrl', true) .option('hideCampaign', false) .tag('<script src="//static.woopra.com/js/w.js">'); /** * Initialize. * * http://www.woopra.com/docs/setup/javascript-tracking/ * * @param {Object} page */ Woopra.prototype.initialize = function(page){ (function () {var i, s, z, w = window, d = document, a = arguments, q = 'script', f = ['config', 'track', 'identify', 'visit', 'push', 'call'], c = function () {var i, self = this; self._e = []; for (i = 0; i < f.length; i++) {(function (f) {self[f] = function () {self._e.push([f].concat(Array.prototype.slice.call(arguments, 0))); return self; }; })(f[i]); } }; w._w = w._w || {}; for (i = 0; i < a.length; i++) { w._w[a[i]] = w[a[i]] = w[a[i]] || new c(); } })('woopra'); this.load(this.ready); each(this.options, function(key, value){ key = snake(key); if (null == value) return; if ('' === value) return; window.woopra.config(key, value); }); }; /** * Loaded? * * @return {Boolean} */ Woopra.prototype.loaded = function(){ return !! (window.woopra && window.woopra.loaded); }; /** * Page. * * @param {String} category (optional) */ Woopra.prototype.page = function(page){ var props = page.properties(); var name = page.fullName(); if (name) props.title = name; window.woopra.track('pv', props); }; /** * Identify. * * @param {Identify} identify */ Woopra.prototype.identify = function(identify){ var traits = identify.traits(); if (identify.name()) traits.name = identify.name(); window.woopra.identify(traits).push(); // `push` sends it off async }; /** * Track. * * @param {Track} track */ Woopra.prototype.track = function(track){ window.woopra.track(track.event(), track.properties()); }; }, {"segmentio/analytics.js-integration":159,"to-snake-case":160,"is-email":19,"extend":40,"each":5,"type":35}], 158: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('segmentio/analytics.js-integration'); var tick = require('next-tick'); var bind = require('bind'); var when = require('when'); /** * Expose `Yandex` integration. */ var Yandex = module.exports = integration('Yandex Metrica') .assumesPageview() .global('yandex_metrika_callbacks') .global('Ya') .option('counterId', null) .tag('<script src="//mc.yandex.ru/metrika/watch.js">'); /** * Initialize. * * http://api.yandex.com/metrika/ * https://metrica.yandex.com/22522351?step=2#tab=code * * @param {Object} page */ Yandex.prototype.initialize = function(page){ var id = this.options.counterId; push(function(){ window['yaCounter' + id] = new window.Ya.Metrika({ id: id }); }); var loaded = bind(this, this.loaded); var ready = this.ready; this.load(function(){ when(loaded, function(){ tick(ready); }); }); }; /** * Loaded? * * @return {Boolean} */ Yandex.prototype.loaded = function(){ return !! (window.Ya && window.Ya.Metrika); }; /** * Push a new callback on the global Yandex queue. * * @param {Function} callback */ function push(callback){ window.yandex_metrika_callbacks = window.yandex_metrika_callbacks || []; window.yandex_metrika_callbacks.push(callback); } }, {"segmentio/analytics.js-integration":159,"next-tick":45,"bind":33,"when":184}]}, {}, {"1":"analytics"})
src/components/ReportList.js
sharkinsspatial/knowsnow
import React from 'react' import Accordion from 'react-bootstrap/lib/Accordion' import Panel from 'react-bootstrap/lib/Panel' import Label from 'react-bootstrap/lib/Label' import moment from 'moment' import PhotoCarousel from './PhotoCarousel' class ReportList extends React.Component { constructor(props) { super(props) } render() { let reportNodes = this.props.reports.map(report => { let date = moment(report.date).format('MMM DD') let dateDifference = moment(report.startTime).fromNow() let distance = (report.distance / 1000).toFixed(1) + ' KM' let glide = report.glideWax !== '' ? <h4 className={'headingPadding'}> <Label bsStyle='success'>{report.glideWax}</Label> </h4> : <div/> let grip = report.gripWax !== '' ? <h4 className={'headingPadding'}> <Label bsStyle='danger'>{report.gripWax}</Label> </h4> : <div/> let narrative = <div className={'headingPadding'}>{report.narrative}</div> let carousel = <PhotoCarousel images={report.imageMetadatas} setActiveImage={this.props.setActiveReportImage} activeImage={this.props.activeReportImage}/> return ( <Panel header={dateDifference + ' by ' + report.displayName + ' - ' + report.parkingLot} key={report.id} eventKey={report.id}> <Panel> <h4 className={'headingPadding'}> <Label bsStyle='primary'> {report.skiType + ' - ' + distance}</Label> </h4> {glide} {grip} {narrative} {carousel} </Panel> </Panel> ) }) return ( <Accordion activeKey={this.props.activeReport} onSelect={this.props.setActiveReport}> {reportNodes} </Accordion> ) } } ReportList.defaultProps = {reports: []} export default ReportList
src/svg-icons/image/crop-rotate.js
rscnt/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageCropRotate = (props) => ( <SvgIcon {...props}> <path d="M7.47 21.49C4.2 19.93 1.86 16.76 1.5 13H0c.51 6.16 5.66 11 11.95 11 .23 0 .44-.02.66-.03L8.8 20.15l-1.33 1.34zM12.05 0c-.23 0-.44.02-.66.04l3.81 3.81 1.33-1.33C19.8 4.07 22.14 7.24 22.5 11H24c-.51-6.16-5.66-11-11.95-11zM16 14h2V8c0-1.11-.9-2-2-2h-6v2h6v6zm-8 2V4H6v2H4v2h2v8c0 1.1.89 2 2 2h8v2h2v-2h2v-2H8z"/> </SvgIcon> ); ImageCropRotate = pure(ImageCropRotate); ImageCropRotate.displayName = 'ImageCropRotate'; export default ImageCropRotate;
src/svg-icons/editor/functions.js
w01fgang/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorFunctions = (props) => ( <SvgIcon {...props}> <path d="M18 4H6v2l6.5 6L6 18v2h12v-3h-7l5-5-5-5h7z"/> </SvgIcon> ); EditorFunctions = pure(EditorFunctions); EditorFunctions.displayName = 'EditorFunctions'; EditorFunctions.muiName = 'SvgIcon'; export default EditorFunctions;
examples/js/custom/csv-button/default-custom-csv-button.js
echaouchna/react-bootstrap-tab
/* eslint max-len: 0 */ /* eslint no-unused-vars: 0 */ /* eslint no-alert: 0 */ /* eslint no-console: 0 */ import React from 'react'; import { BootstrapTable, TableHeaderColumn, ExportCSVButton } 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 DefaultCustomExportButtonTable extends React.Component { handleExportCSVButtonClick = (onClick) => { // Custom your onClick event here, // it's not necessary to implement this function if you have no any process before onClick console.log('This is my custom function for ExportCSVButton click event'); onClick(); } createCustomExportCSVButton = (onClick) => { return ( <ExportCSVButton btnText='CustomExportText' btnContextual='btn-danger' className='my-custom-class' btnGlyphicon='glyphicon-edit' onClick={ e => this.handleExportCSVButtonClick(onClick) }/> ); // If you want have more power to custom the child of ExportCSVButton, // you can do it like following // return ( // <ExportCSVButton // btnContextual='btn-warning' // className='my-custom-class' // onClick={ () => this.handleExportCSVButtonClick(onClick) }> // { ... } // </ExportCSVButton> // ); } render() { const options = { exportCSVBtn: this.createCustomExportCSVButton }; return ( <BootstrapTable data={ products } options={ options } exportCSV> <TableHeaderColumn dataField='id' isKey={ true }>Product ID</TableHeaderColumn> <TableHeaderColumn dataField='name'>Product Name</TableHeaderColumn> <TableHeaderColumn dataField='price'>Product Price</TableHeaderColumn> </BootstrapTable> ); } }
components/transition/src/TransitionGroup.js
fi11/uikit
import React from 'react'; export class TransitionGroup extends React.Component { state = { lockIdx: null }; _lockIdx = null; static defaultProps = { delay: 150, }; render() { return React.Children.map(this.props.children, (c, idx) => { const { lockIdx } = this.state; const children = c.props.children; return React.cloneElement(c, { key: idx, onWillEnter: () => { const { onWillEnter } = c.props; this._lockIdx = idx; onWillEnter && onWillEnter(); }, onDidEnter: () => { const { onDidEnter } = c.props; this.setState({ lockIdx: this._lockIdx, }); onDidEnter && onDidEnter(); }, onDidLeave: () => { const { onDidLeave } = c.props; this._lockIdx = null; setTimeout(() => { this.setState({ lockIdx: null, }); }, this.props.delay || 50); onDidLeave && onDidLeave(); }, children: (lockIdx === null || idx === lockIdx) && !!children ? children : null, }); }); } }
app/config/routes.js
saelili/F3C_Website
import React from 'react' import { BrowserRouter as Router, Route, Switch, Redirect } from 'react-router-dom' import { MainContainer, HomeContainer, ScrollToTopOnMount, MembersContainer, SlackContainer, CalendarContainer, SigninContainer, } from 'containers' const getRoutes = (store) => ( <Router> <ScrollToTopOnMount> <MainContainer> <Switch> <Route exact={true} path='/' component={HomeContainer} /> <Route exact={true} path='/members' component={MembersContainer} /> <Route exact={true} path='/slack' component={SlackContainer} /> <Route exact={true} path='/calendar' component={CalendarContainer} /> <Route exact={true} path='/signin' component={SigninContainer} /> <Route render={() => <Redirect to='/' />} /> </Switch> </MainContainer> </ScrollToTopOnMount> </Router> ) export default getRoutes
react-native-kit/__tests__/index.android.js
fromatlantis/nojs
import 'react-native'; import React from 'react'; import Index from '../index.android.js'; // Note: test renderer must be required after react-native. import renderer from 'react-test-renderer'; it('renders correctly', () => { const tree = renderer.create( <Index /> ); });
src/App.js
w01fgang/react-hot-boilerplate
import React, { Component } from 'react'; export default class App extends Component { render() { return ( <h1>Hello, world.</h1> ); } }
react-universal-web-apps-simple/app/components/common/NoMatch.js
joekraken/react-demos
import React from 'react'; export default class NoMatch extends React.Component { render() { return ( <section className="app-content"> <header className="section-header"> <h3 className="title">Not Found</h3> </header> </section> ); } }
client/src/components/settings/Theme.js
pahosler/freecodecamp
import PropTypes from 'prop-types'; import React from 'react'; import { ControlLabel } from '@freecodecamp/react-bootstrap'; import TB from '../helpers/ToggleButton'; import './theme-settings.css'; const propTypes = { currentTheme: PropTypes.string.isRequired, toggleNightMode: PropTypes.func.isRequired }; export default function ThemeSettings({ currentTheme, toggleNightMode }) { return ( <div id='theme-settings-container'> <ControlLabel className='theme-label' htmlFor='night-mode'> <strong>Night Mode</strong> </ControlLabel> <TB name='night-mode' onChange={() => toggleNightMode(currentTheme === 'night' ? 'default' : 'night') } value={currentTheme === 'night'} /> </div> ); } ThemeSettings.displayName = 'ThemeSettings'; ThemeSettings.propTypes = propTypes;
react-github-battle/app/components/Home.js
guilsa/javascript-stuff
import React from 'react' import { Link } from 'react-router' import { transparentBg } from '../styles' import MainContainer from './MainContainer' var Home = React.createClass({ render () { return( <MainContainer> <h1>Github Battle</h1> <p className="lead">Some fancy motto</p> <Link to="/playerOne"> <button type="button" className="btn btn-lg btn-success">Get Started</button> </Link> </MainContainer> ) } }); export default Home
ajax/libs/primereact/7.0.0-rc.1/scrollpanel/scrollpanel.esm.js
cdnjs/cdnjs
import React, { Component } from 'react'; import { DomHandler, classNames } from 'primereact/core'; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var ScrollPanel = /*#__PURE__*/function (_Component) { _inherits(ScrollPanel, _Component); var _super = _createSuper(ScrollPanel); function ScrollPanel(props) { var _this; _classCallCheck(this, ScrollPanel); _this = _super.call(this, props); _this.moveBar = _this.moveBar.bind(_assertThisInitialized(_this)); _this.onXBarMouseDown = _this.onXBarMouseDown.bind(_assertThisInitialized(_this)); _this.onYBarMouseDown = _this.onYBarMouseDown.bind(_assertThisInitialized(_this)); _this.onDocumentMouseMove = _this.onDocumentMouseMove.bind(_assertThisInitialized(_this)); _this.onDocumentMouseUp = _this.onDocumentMouseUp.bind(_assertThisInitialized(_this)); return _this; } _createClass(ScrollPanel, [{ key: "calculateContainerHeight", value: function calculateContainerHeight() { var containerStyles = getComputedStyle(this.container), xBarStyles = getComputedStyle(this.xBar), pureContainerHeight = DomHandler.getHeight(this.container) - parseInt(xBarStyles['height'], 10); if (containerStyles['max-height'] !== "none" && pureContainerHeight === 0) { if (this.content.offsetHeight + parseInt(xBarStyles['height'], 10) > parseInt(containerStyles['max-height'], 10)) { this.container.style.height = containerStyles['max-height']; } else { this.container.style.height = this.content.offsetHeight + parseFloat(containerStyles.paddingTop) + parseFloat(containerStyles.paddingBottom) + parseFloat(containerStyles.borderTopWidth) + parseFloat(containerStyles.borderBottomWidth) + "px"; } } } }, { key: "moveBar", value: function moveBar() { var _this2 = this; /* horizontal scroll */ var totalWidth = this.content.scrollWidth; var ownWidth = this.content.clientWidth; var bottom = (this.container.clientHeight - this.xBar.clientHeight) * -1; this.scrollXRatio = ownWidth / totalWidth; /* vertical scroll */ var totalHeight = this.content.scrollHeight; var ownHeight = this.content.clientHeight; var right = (this.container.clientWidth - this.yBar.clientWidth) * -1; this.scrollYRatio = ownHeight / totalHeight; this.frame = this.requestAnimationFrame(function () { if (_this2.scrollXRatio >= 1) { DomHandler.addClass(_this2.xBar, 'p-scrollpanel-hidden'); } else { DomHandler.removeClass(_this2.xBar, 'p-scrollpanel-hidden'); _this2.xBar.style.cssText = 'width:' + Math.max(_this2.scrollXRatio * 100, 10) + '%; left:' + _this2.content.scrollLeft / totalWidth * 100 + '%;bottom:' + bottom + 'px;'; } if (_this2.scrollYRatio >= 1) { DomHandler.addClass(_this2.yBar, 'p-scrollpanel-hidden'); } else { DomHandler.removeClass(_this2.yBar, 'p-scrollpanel-hidden'); _this2.yBar.style.cssText = 'height:' + Math.max(_this2.scrollYRatio * 100, 10) + '%; top: calc(' + _this2.content.scrollTop / totalHeight * 100 + '% - ' + _this2.xBar.clientHeight + 'px);right:' + right + 'px;'; } }); } }, { key: "onYBarMouseDown", value: function onYBarMouseDown(e) { this.isYBarClicked = true; this.lastPageY = e.pageY; DomHandler.addClass(this.yBar, 'p-scrollpanel-grabbed'); DomHandler.addClass(document.body, 'p-scrollpanel-grabbed'); document.addEventListener('mousemove', this.onDocumentMouseMove); document.addEventListener('mouseup', this.onDocumentMouseUp); e.preventDefault(); } }, { key: "onXBarMouseDown", value: function onXBarMouseDown(e) { this.isXBarClicked = true; this.lastPageX = e.pageX; DomHandler.addClass(this.xBar, 'p-scrollpanel-grabbed'); DomHandler.addClass(document.body, 'p-scrollpanel-grabbed'); document.addEventListener('mousemove', this.onDocumentMouseMove); document.addEventListener('mouseup', this.onDocumentMouseUp); e.preventDefault(); } }, { key: "onDocumentMouseMove", value: function onDocumentMouseMove(e) { if (this.isXBarClicked) { this.onMouseMoveForXBar(e); } else if (this.isYBarClicked) { this.onMouseMoveForYBar(e); } else { this.onMouseMoveForXBar(e); this.onMouseMoveForYBar(e); } } }, { key: "onMouseMoveForXBar", value: function onMouseMoveForXBar(e) { var _this3 = this; var deltaX = e.pageX - this.lastPageX; this.lastPageX = e.pageX; this.frame = this.requestAnimationFrame(function () { _this3.content.scrollLeft += deltaX / _this3.scrollXRatio; }); } }, { key: "onMouseMoveForYBar", value: function onMouseMoveForYBar(e) { var _this4 = this; var deltaY = e.pageY - this.lastPageY; this.lastPageY = e.pageY; this.frame = this.requestAnimationFrame(function () { _this4.content.scrollTop += deltaY / _this4.scrollYRatio; }); } }, { key: "onDocumentMouseUp", value: function onDocumentMouseUp(e) { DomHandler.removeClass(this.yBar, 'p-scrollpanel-grabbed'); DomHandler.removeClass(this.xBar, 'p-scrollpanel-grabbed'); DomHandler.removeClass(document.body, 'p-scrollpanel-grabbed'); document.removeEventListener('mousemove', this.onDocumentMouseMove); document.removeEventListener('mouseup', this.onDocumentMouseUp); this.isXBarClicked = false; this.isYBarClicked = false; } }, { key: "requestAnimationFrame", value: function requestAnimationFrame(f) { var frame = window.requestAnimationFrame || this.timeoutFrame; return frame(f); } }, { key: "refresh", value: function refresh() { this.moveBar(); } }, { key: "componentDidMount", value: function componentDidMount() { this.moveBar(); this.moveBar = this.moveBar.bind(this); window.addEventListener('resize', this.moveBar); this.calculateContainerHeight(); this.initialized = true; } }, { key: "componentWillUnmount", value: function componentWillUnmount() { if (this.initialized) { window.removeEventListener('resize', this.moveBar); } if (this.frame) { window.cancelAnimationFrame(this.frame); } } }, { key: "render", value: function render() { var _this5 = this; var className = classNames('p-scrollpanel p-component', this.props.className); return /*#__PURE__*/React.createElement("div", { ref: function ref(el) { return _this5.container = el; }, id: this.props.id, className: className, style: this.props.style }, /*#__PURE__*/React.createElement("div", { className: "p-scrollpanel-wrapper" }, /*#__PURE__*/React.createElement("div", { ref: function ref(el) { return _this5.content = el; }, className: "p-scrollpanel-content", onScroll: this.moveBar, onMouseEnter: this.moveBar }, this.props.children)), /*#__PURE__*/React.createElement("div", { ref: function ref(el) { return _this5.xBar = el; }, className: "p-scrollpanel-bar p-scrollpanel-bar-x", onMouseDown: this.onXBarMouseDown }), /*#__PURE__*/React.createElement("div", { ref: function ref(el) { return _this5.yBar = el; }, className: "p-scrollpanel-bar p-scrollpanel-bar-y", onMouseDown: this.onYBarMouseDown })); } }]); return ScrollPanel; }(Component); _defineProperty(ScrollPanel, "defaultProps", { id: null, style: null, className: null }); export { ScrollPanel };
fields/types/localfiles/LocalFilesField.js
codevlabs/keystone
import _ from 'underscore'; import bytes from 'bytes'; import Field from '../Field'; import React from 'react'; import ReactDOM from 'react-dom'; import { Button, FormField, FormInput, FormNote } from 'elemental'; /** * TODO: * - Remove dependency on underscore */ const ICON_EXTS = [ 'aac', 'ai', 'aiff', 'avi', 'bmp', 'c', 'cpp', 'css', 'dat', 'dmg', 'doc', 'dotx', 'dwg', 'dxf', 'eps', 'exe', 'flv', 'gif', 'h', 'hpp', 'html', 'ics', 'iso', 'java', 'jpg', 'js', 'key', 'less', 'mid', 'mp3', 'mp4', 'mpg', 'odf', 'ods', 'odt', 'otp', 'ots', 'ott', 'pdf', 'php', 'png', 'ppt', 'psd', 'py', 'qt', 'rar', 'rb', 'rtf', 'sass', 'scss', 'sql', 'tga', 'tgz', 'tiff', 'txt', 'wav', 'xls', 'xlsx', 'xml', 'yml', 'zip' ]; var LocalFilesFieldItem = React.createClass({ propTypes: { deleted: React.PropTypes.bool, filename: React.PropTypes.string, isQueued: React.PropTypes.bool, key: React.PropTypes.number, size: React.PropTypes.number, toggleDelete: React.PropTypes.func, }, renderActionButton () { if (!this.props.shouldRenderActionButton || this.props.isQueued) return null; var buttonLabel = this.props.deleted ? 'Undo' : 'Remove'; var buttonType = this.props.deleted ? 'link' : 'link-cancel'; return <Button key="action-button" type={buttonType} onClick={this.props.toggleDelete}>{buttonLabel}</Button>; }, render () { let { filename } = this.props; let ext = filename.split('.').pop(); let iconName = '_blank'; if (_.contains(ICON_EXTS, ext)) iconName = ext; let note; if (this.props.deleted) { note = <FormInput key="delete-note" noedit className="field-type-localfiles__note field-type-localfiles__note--delete">save to delete</FormInput>; } else if (this.props.isQueued) { note = <FormInput key="upload-note" noedit className="field-type-localfiles__note field-type-localfiles__note--upload">save to upload</FormInput>; } return ( <FormField> <img key="file-type-icon" className="file-icon" src={Keystone.adminPath + '/images/icons/32/' + iconName + '.png'} /> <FormInput key="file-name" noedit className="field-type-localfiles__filename"> {filename} {this.props.size ? ' (' + bytes(this.props.size) + ')' : null} </FormInput> {note} {this.renderActionButton()} </FormField> ); } }); module.exports = Field.create({ getInitialState () { var items = []; var self = this; _.each(this.props.value, function (item) { self.pushItem(item, items); }); return { items: items }; }, removeItem (id) { var thumbs = []; var self = this; _.each(this.state.items, function (thumb) { if (thumb.props._id === id) { thumb.props.deleted = !thumb.props.deleted; } self.pushItem(thumb.props, thumbs); }); this.setState({ items: thumbs }); }, pushItem (args, thumbs) { thumbs = thumbs || this.state.items; var i = thumbs.length; args.toggleDelete = this.removeItem.bind(this, args._id); args.shouldRenderActionButton = this.shouldRenderField(); args.adminPath = Keystone.adminPath; thumbs.push(<LocalFilesFieldItem key={args._id} {...args} />); }, fileFieldNode () { return ReactDOM.findDOMNode(this.refs.fileField); }, renderFileField () { return <input ref="fileField" type="file" name={this.props.paths.upload} multiple className="field-upload" onChange={this.uploadFile} tabIndex="-1" />; }, clearFiles () { this.fileFieldNode().value = ''; this.setState({ items: this.state.items.filter(function (thumb) { return !thumb.props.isQueued; }) }); }, uploadFile (event) { var self = this; var files = event.target.files; _.each(files, function (f) { self.pushItem({ isQueued: true, filename: f.name }); self.forceUpdate(); }); }, changeFiles () { this.fileFieldNode().click(); }, hasFiles () { return this.refs.fileField && this.fileFieldNode().value; }, renderToolbar () { if (!this.shouldRenderField()) return null; var clearFilesButton; if (this.hasFiles()) { clearFilesButton = <Button type="link-cancel" className="ml-5" onClick={this.clearFiles}>Clear Uploads</Button>; } return ( <div className="files-toolbar"> <Button onClick={this.changeFiles}>Upload</Button> {clearFilesButton} </div> ); }, renderPlaceholder () { return ( <div className="file-field file-upload" onClick={this.changeFiles}> <div className="file-preview"> <span className="file-thumbnail"> <span className="file-dropzone" /> <div className="ion-picture file-uploading" /> </span> </div> <div className="file-details"> <span className="file-message">Click to upload</span> </div> </div> ); }, renderContainer () { return ( <div className="files-container clearfix"> {this.state.items} </div> ); }, renderFieldAction () { var value = ''; var remove = []; _.each(this.state.items, function (thumb) { if (thumb && thumb.props.deleted) remove.push(thumb.props._id); }); if (remove.length) value = 'delete:' + remove.join(','); return <input ref="action" className="field-action" type="hidden" value={value} name={this.props.paths.action} />; }, renderUploadsField () { return <input ref="uploads" className="field-uploads" type="hidden" name={this.props.paths.uploads} />; }, renderNote: function() { if (!this.props.note) return null; return <FormNote note={this.props.note} />; }, renderUI () { return ( <FormField label={this.props.label} className="field-type-localfiles"> {this.renderFieldAction()} {this.renderUploadsField()} {this.renderFileField()} {this.renderContainer()} {this.renderToolbar()} {this.renderNote()} </FormField> ); } });
src/encoded/static/components/item-pages/components/OverviewHeadingContainer.js
4dn-dcic/fourfront
'use strict'; import React from 'react'; import PropTypes from 'prop-types'; import url from 'url'; import _ from 'underscore'; import ReactTooltip from 'react-tooltip'; import Collapse from 'react-bootstrap/esm/Collapse'; /** * A collapsible panel that is meant to be shown near top of Item views. * Is meant to display a grid of Item properties, rendered out via `OverViewBodyItem`s. * However the component may be extended to display other things, e.g. as `ExpandableStaticHeader` does. */ export class OverviewHeadingContainer extends React.Component { static propTypes = { 'onFinishOpen' : PropTypes.func, 'onStartOpen' : PropTypes.func, 'onFinishClose' : PropTypes.func, 'onStartClose' : PropTypes.func }; static defaultProps = { 'className' : 'with-background mb-3 mt-1', 'defaultOpen' : true, 'titleElement' : 'h4', 'title' : 'Properties', 'prependTitleIcon' : false, 'prependTitleIconFxn' : function(open, props){ return <i className={"expand-icon icon fas icon-" + (open ? 'minus' : 'plus')} data-tip={open ? 'Collapse' : 'Expand'}/>; } }; constructor(props){ super(props); this.toggle = _.throttle(this.toggle.bind(this), 500); this.renderInner = this.renderInner.bind(this); this.renderInnerBody = this.renderInnerBody.bind(this); this.state = { 'open' : props.defaultOpen, 'closing' : false }; } toggle(){ this.setState(function(currState){ var open = !currState.open, closing = !open; return { open, closing }; }, ()=>{ setTimeout(()=>{ this.setState(function(currState){ if (!currState.open && currState.closing){ return { 'closing' : false }; } else if (currState.open){ ReactTooltip.rebuild(); } return null; }); }, 750); }); } renderTitle(){ var { title, prependTitleIcon, prependTitleIconFxn } = this.props, open = this.state.open; return ( <span> { prependTitleIcon && prependTitleIconFxn ? prependTitleIconFxn(open, this.props) : null } { title } &nbsp;<i className={"icon fas icon-angle-right" + (open ? ' icon-rotate-90' : '')}/> </span> ); } renderInner(){ var { open, closing } = this.state; return ( <div className="inner"> <hr className="tab-section-title-horiz-divider"/> { open || closing ? this.renderInnerBody() : <div/> } </div> ); } renderInnerBody(){ return <div className="row overview-blocks" children={this.props.children}/>; } render(){ var { title, titleElement, titleClassName, titleTip, className, onStartOpen, onStartClose, onFinishClose, onFinishOpen } = this.props, open = this.state.open, titleProps = title && titleElement && { 'className' : 'tab-section-title clickable with-accent' + (titleClassName ? ' ' + titleClassName : ''), 'onClick' : this.toggle, 'data-tip' : titleTip }; return ( <div className={"overview-blocks-header" + (open ? ' is-open' : ' is-closed') + (typeof className === 'string' ? ' ' + className : '')}> { title && titleElement ? React.createElement(titleElement, titleProps, this.renderTitle()) : null } <Collapse in={open} onEnter={onStartOpen} onEntered={onFinishOpen} onExit={onStartClose} onExited={onFinishClose} children={this.renderInner()} /> </div> ); } }
ajax/libs/core-js/0.4.1/core.js
humbletim/cdnjs
/** * Core.js 0.4.1 * https://github.com/zloirock/core-js * License: http://rock.mit-license.org * © 2015 Denis Pushkarev */ !function(returnThis, framework, undefined){ 'use strict'; /****************************************************************************** * Module : common * ******************************************************************************/ var global = returnThis() // Shortcuts for [[Class]] & property names , OBJECT = 'Object' , FUNCTION = 'Function' , ARRAY = 'Array' , STRING = 'String' , NUMBER = 'Number' , REGEXP = 'RegExp' , DATE = 'Date' , MAP = 'Map' , SET = 'Set' , WEAKMAP = 'WeakMap' , WEAKSET = 'WeakSet' , SYMBOL = 'Symbol' , PROMISE = 'Promise' , MATH = 'Math' , ARGUMENTS = 'Arguments' , PROTOTYPE = 'prototype' , CONSTRUCTOR = 'constructor' , TO_STRING = 'toString' , TO_STRING_TAG = TO_STRING + 'Tag' , TO_LOCALE = 'toLocaleString' , HAS_OWN = 'hasOwnProperty' , FOR_EACH = 'forEach' , ITERATOR = 'iterator' , FF_ITERATOR = '@@' + ITERATOR , PROCESS = 'process' , CREATE_ELEMENT = 'createElement' // Aliases global objects and prototypes , Function = global[FUNCTION] , Object = global[OBJECT] , Array = global[ARRAY] , String = global[STRING] , Number = global[NUMBER] , RegExp = global[REGEXP] , Date = global[DATE] , Map = global[MAP] , Set = global[SET] , WeakMap = global[WEAKMAP] , WeakSet = global[WEAKSET] , Symbol = global[SYMBOL] , Math = global[MATH] , TypeError = global.TypeError , setTimeout = global.setTimeout , setImmediate = global.setImmediate , clearImmediate = global.clearImmediate , process = global[PROCESS] , nextTick = process && process.nextTick , document = global.document , html = document && document.documentElement , navigator = global.navigator , define = global.define , ArrayProto = Array[PROTOTYPE] , ObjectProto = Object[PROTOTYPE] , FunctionProto = Function[PROTOTYPE] , Infinity = 1 / 0 , DOT = '.'; // http://jsperf.com/core-js-isobject function isObject(it){ return it != null && (typeof it == 'object' || typeof it == 'function'); } function isFunction(it){ return typeof it == 'function'; } // Native function? var isNative = ctx(/./.test, /\[native code\]\s*\}\s*$/, 1); // Object internal [[Class]] or toStringTag // http://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring var buildIn = { Undefined: 1, Null: 1, Array: 1, String: 1, Arguments: 1, Function: 1, Error: 1, Boolean: 1, Number: 1, Date: 1, RegExp:1 } , toString = ObjectProto[TO_STRING]; function setToStringTag(it, tag, stat){ if(it && !has(it = stat ? it : it[PROTOTYPE], SYMBOL_TAG))hidden(it, SYMBOL_TAG, tag); } function cof(it){ return it == undefined ? it === undefined ? 'Undefined' : 'Null' : toString.call(it).slice(8, -1); } function classof(it){ var klass = cof(it), tag; return klass == OBJECT && (tag = it[SYMBOL_TAG]) ? has(buildIn, tag) ? '~' + tag : tag : klass; } // Function var call = FunctionProto.call , apply = FunctionProto.apply , REFERENCE_GET; // Partial apply function part(/* ...args */){ var length = arguments.length , args = Array(length) , i = 0 , _ = path._ , holder = false; while(length > i)if((args[i] = arguments[i++]) === _)holder = true; return partial(this, args, length, holder, _, false); } // Internal partial application & context binding function partial(fn, argsPart, lengthPart, holder, _, bind, context){ assertFunction(fn); return function(/* ...args */){ var that = bind ? context : this , length = arguments.length , i = 0, j = 0, args; if(!holder && !length)return invoke(fn, argsPart, that); args = argsPart.slice(); if(holder)for(;lengthPart > i; i++)if(args[i] === _)args[i] = arguments[j++]; while(length > j)args.push(arguments[j++]); return invoke(fn, args, that); } } // Optional / simple context binding function ctx(fn, that, length){ assertFunction(fn); if(~length && that === undefined)return fn; switch(length){ case 1: return function(a){ return fn.call(that, a); } case 2: return function(a, b){ return fn.call(that, a, b); } case 3: return function(a, b, c){ return fn.call(that, a, b, c); } } return function(/* ...args */){ return fn.apply(that, arguments); } } // Fast apply // http://jsperf.lnkit.com/fast-apply/5 function invoke(fn, args, that){ var un = that === undefined; switch(args.length | 0){ case 0: return un ? fn() : fn.call(that); case 1: return un ? fn(args[0]) : fn.call(that, args[0]); case 2: return un ? fn(args[0], args[1]) : fn.call(that, args[0], args[1]); case 3: return un ? fn(args[0], args[1], args[2]) : fn.call(that, args[0], args[1], args[2]); case 4: return un ? fn(args[0], args[1], args[2], args[3]) : fn.call(that, args[0], args[1], args[2], args[3]); case 5: return un ? fn(args[0], args[1], args[2], args[3], args[4]) : fn.call(that, args[0], args[1], args[2], args[3], args[4]); } return fn.apply(that, args); } function construct(target, argumentsList){ var instance = create(target[PROTOTYPE]) , result = apply.call(target, instance, argumentsList); return isObject(result) ? result : instance; } // Object: var create = Object.create , getPrototypeOf = Object.getPrototypeOf , setPrototypeOf = Object.setPrototypeOf , defineProperty = Object.defineProperty , defineProperties = Object.defineProperties , getOwnDescriptor = Object.getOwnPropertyDescriptor , getKeys = Object.keys , getNames = Object.getOwnPropertyNames , getSymbols = Object.getOwnPropertySymbols , has = ctx(call, ObjectProto[HAS_OWN], 2) // Dummy, fix for not array-like ES3 string in es5 module , ES5Object = Object; function returnIt(it){ return it; } function get(object, key){ if(has(object, key))return object[key]; } function ownKeys(it){ return getSymbols ? getNames(it).concat(getSymbols(it)) : getNames(it); } // 19.1.2.1 Object.assign(target, source, ...) var assign = Object.assign || function(target, source){ var T = Object(assertDefined(target)) , l = arguments.length , i = 1; while(l > i){ var S = ES5Object(arguments[i++]) , keys = getKeys(S) , length = keys.length , j = 0 , key; while(length > j)T[key = keys[j++]] = S[key]; } return T; } function keyOf(object, el){ var O = ES5Object(object) , keys = getKeys(O) , length = keys.length , index = 0 , key; while(length > index)if(O[key = keys[index++]] === el)return key; } // Array // array('str1,str2,str3') => ['str1', 'str2', 'str3'] function array(it){ return String(it).split(','); } var push = ArrayProto.push , unshift = ArrayProto.unshift , slice = ArrayProto.slice , splice = ArrayProto.splice , indexOf = ArrayProto.indexOf , forEach = ArrayProto[FOR_EACH]; /* * 0 -> forEach * 1 -> map * 2 -> filter * 3 -> some * 4 -> every * 5 -> find * 6 -> findIndex */ function createArrayMethod(type){ var isMap = type == 1 , isFilter = type == 2 , isSome = type == 3 , isEvery = type == 4 , isFindIndex = type == 6 , noholes = type == 5 || isFindIndex; return function(callbackfn/*, that = undefined */){ var O = Object(assertDefined(this)) , that = arguments[1] , self = ES5Object(O) , f = ctx(callbackfn, that, 3) , length = toLength(self.length) , index = 0 , result = isMap ? Array(length) : isFilter ? [] : undefined , val, res; for(;length > index; index++)if(noholes || index in self){ val = self[index]; res = f(val, index, O); if(type){ if(isMap)result[index] = res; // map else if(res)switch(type){ case 3: return true; // some case 5: return val; // find case 6: return index; // findIndex case 2: result.push(val); // filter } else if(isEvery)return false; // every } } return isFindIndex ? -1 : isSome || isEvery ? isEvery : result; } } function createArrayContains(isContains){ return function(el /*, fromIndex = 0 */){ var O = ES5Object(assertDefined(this)) , length = toLength(O.length) , index = toIndex(arguments[1], length); if(isContains && el != el){ for(;length > index; index++)if(sameNaN(O[index]))return isContains || index; } else for(;length > index; index++)if(isContains || index in O){ if(O[index] === el)return isContains || index; } return !isContains && -1; } } function generic(A, B){ // strange IE quirks mode bug -> use typeof vs isFunction return typeof A == 'function' ? A : B; } // Math var MAX_SAFE_INTEGER = 0x1fffffffffffff // pow(2, 53) - 1 == 9007199254740991 , ceil = Math.ceil , floor = Math.floor , max = Math.max , min = Math.min , random = Math.random , trunc = Math.trunc || function(it){ return (it > 0 ? floor : ceil)(it); } // 20.1.2.4 Number.isNaN(number) function sameNaN(number){ return number != number; } // 7.1.4 ToInteger function toInteger(it){ return isNaN(it) ? 0 : trunc(it); } // 7.1.15 ToLength function toLength(it){ return it > 0 ? min(toInteger(it), MAX_SAFE_INTEGER) : 0; } function toIndex(index, length){ var index = toInteger(index); return index < 0 ? max(index + length, 0) : min(index, length); } function createReplacer(regExp, replace, isStatic){ var replacer = isObject(replace) ? function(part){ return replace[part]; } : replace; return function(it){ return String(isStatic ? it : this).replace(regExp, replacer); } } function createPointAt(toString){ return function(pos){ var s = String(assertDefined(this)) , i = toInteger(pos) , l = s.length , a, b; if(i < 0 || i >= l)return toString ? '' : undefined; a = s.charCodeAt(i); return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff ? toString ? s.charAt(i) : a : toString ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000; } } // Assertion & errors var REDUCE_ERROR = 'Reduce of empty object with no initial value'; function assert(condition, msg1, msg2){ if(!condition)throw TypeError(msg2 ? msg1 + msg2 : msg1); } function assertDefined(it){ if(it == undefined)throw TypeError('Function called on null or undefined'); return it; } function assertFunction(it){ assert(isFunction(it), it, ' is not a function!'); return it; } function assertObject(it){ assert(isObject(it), it, ' is not an object!'); return it; } function assertInstance(it, Constructor, name){ assert(it instanceof Constructor, name, ": use the 'new' operator!"); } // Property descriptors & Symbol function descriptor(bitmap, value){ return { enumerable : !(bitmap & 1), configurable: !(bitmap & 2), writable : !(bitmap & 4), value : value } } function simpleSet(object, key, value){ object[key] = value; return object; } function createDefiner(bitmap){ return DESC ? function(object, key, value){ return defineProperty(object, key, descriptor(bitmap, value)); } : simpleSet; } function uid(key){ return SYMBOL + '(' + key + ')_' + (++sid + random())[TO_STRING](36); } function getWellKnownSymbol(name, setter){ return (Symbol && Symbol[name]) || (setter ? Symbol : safeSymbol)(SYMBOL + DOT + name); } // The engine works fine with descriptors? Thank's IE8 for his funny defineProperty. var DESC = !!function(){try{return defineProperty({}, DOT, ObjectProto)}catch(e){}}() , sid = 0 , hidden = createDefiner(1) , set = Symbol ? simpleSet : hidden , safeSymbol = Symbol || uid; function assignHidden(target, src){ for(var key in src)hidden(target, key, src[key]); return target; } // Iterators var SYMBOL_ITERATOR = getWellKnownSymbol(ITERATOR) , SYMBOL_TAG = getWellKnownSymbol(TO_STRING_TAG) , SUPPORT_FF_ITER = FF_ITERATOR in ArrayProto , ITER = safeSymbol('iter') , KEY = 1 , VALUE = 2 , Iterators = {} , IteratorPrototype = {} , NATIVE_ITERATORS = SYMBOL_ITERATOR in ArrayProto // Safari define byggy iterators w/o `next` , BUGGY_ITERATORS = 'keys' in ArrayProto && !('next' in [].keys()); // 25.1.2.1.1 %IteratorPrototype%[@@iterator]() setIterator(IteratorPrototype, returnThis); function setIterator(O, value){ hidden(O, SYMBOL_ITERATOR, value); // Add iterator for FF iterator protocol SUPPORT_FF_ITER && hidden(O, FF_ITERATOR, value); } function createIterator(Constructor, NAME, next, proto){ Constructor[PROTOTYPE] = create(proto || IteratorPrototype, {next: descriptor(1, next)}); setToStringTag(Constructor, NAME + ' Iterator'); } function defineIterator(Constructor, NAME, value, DEFAULT){ var proto = Constructor[PROTOTYPE] , iter = get(proto, SYMBOL_ITERATOR) || get(proto, FF_ITERATOR) || (DEFAULT && get(proto, DEFAULT)) || value; if(framework){ // Define iterator setIterator(proto, iter); if(iter !== value){ var iterProto = getPrototypeOf(iter.call(new Constructor)); // Set @@toStringTag to native iterators setToStringTag(iterProto, NAME + ' Iterator', true); // FF fix has(proto, FF_ITERATOR) && setIterator(iterProto, returnThis); } } // Plug for library Iterators[NAME] = iter; // FF & v8 fix Iterators[NAME + ' Iterator'] = returnThis; return iter; } function defineStdIterators(Base, NAME, Constructor, next, DEFAULT, IS_SET){ function createIter(kind){ return function(){ return new Constructor(this, kind); } } createIterator(Constructor, NAME, next); var entries = createIter(KEY+VALUE) , values = createIter(VALUE); if(DEFAULT == VALUE)values = defineIterator(Base, NAME, values, 'values'); else entries = defineIterator(Base, NAME, entries, 'entries'); if(DEFAULT){ $define(PROTO + FORCED * BUGGY_ITERATORS, NAME, { entries: entries, keys: IS_SET ? values : createIter(KEY), values: values }); } } function iterResult(done, value){ return {value: value, done: !!done}; } function isIterable(it){ var O = Object(it) , Symbol = global[SYMBOL] , hasExt = !!(Symbol && Symbol[ITERATOR] && Symbol[ITERATOR] in O); return hasExt || SYMBOL_ITERATOR in O || has(Iterators, classof(O)); } function getIterator(it){ var Symbol = global[SYMBOL] , ext = Symbol && Symbol[ITERATOR] && it[Symbol[ITERATOR]] , getIter = ext || it[SYMBOL_ITERATOR] || Iterators[classof(it)]; return assertObject(getIter.call(it)); } function stepCall(fn, value, entries){ return entries ? invoke(fn, value) : fn(value); } function forOf(iterable, entries, fn, that){ var iterator = getIterator(iterable) , f = ctx(fn, that, entries ? 2 : 1) , step; while(!(step = iterator.next()).done)if(stepCall(f, step.value, entries) === false)return; } // core var NODE = cof(process) == PROCESS , core = {} , path = framework ? global : core , old = global.core // type bitmap , FORCED = 1 , GLOBAL = 2 , STATIC = 4 , PROTO = 8 , BIND = 16 , WRAP = 32; function $define(type, name, source){ var key, own, out, exp , isGlobal = type & GLOBAL , target = isGlobal ? global : (type & STATIC) ? global[name] : (global[name] || ObjectProto)[PROTOTYPE] , exports = isGlobal ? core : core[name] || (core[name] = {}); if(isGlobal)source = name; for(key in source){ // there is a similar native own = !(type & FORCED) && target && key in target && (!isFunction(target[key]) || isNative(target[key])); // export native or passed out = (own ? target : source)[key]; // bind timers to global for call from export context if(type & BIND && own)exp = ctx(out, global); // wrap global constructors for prevent change them in library else if(type & WRAP && !framework && target[key] == out){ exp = function(param){ return this instanceof out ? new out(param) : out(param); } exp[PROTOTYPE] = out[PROTOTYPE]; } else exp = type & PROTO && isFunction(out) ? ctx(call, out) : out; // export if(exports[key] != out)hidden(exports, key, exp); // extend global if(framework && target && !own){ if(isGlobal)target[key] = out; else delete target[key] && hidden(target, key, out); } } } // CommonJS export if(typeof module != 'undefined' && module.exports)module.exports = core; // RequireJS export if(isFunction(define) && define.amd)define(function(){return core}); // Export to global object if(!NODE || framework){ core.noConflict = function(){ global.core = old; return core; } global.core = core; } /****************************************************************************** * Module : es5 * ******************************************************************************/ // ECMAScript 5 shim !function(IS_ENUMERABLE, Empty, _classof, $PROTO){ if(!DESC){ getOwnDescriptor = function(O, P){ if(has(O, P))return descriptor(!ObjectProto[IS_ENUMERABLE].call(O, P), O[P]); }; defineProperty = function(O, P, Attributes){ if('value' in Attributes)assertObject(O)[P] = Attributes.value; return O; }; defineProperties = function(O, Properties){ assertObject(O); var keys = getKeys(Properties) , length = keys.length , i = 0 , P, Attributes; while(length > i){ P = keys[i++]; Attributes = Properties[P]; if('value' in Attributes)O[P] = Attributes.value; } return O; }; } $define(STATIC + FORCED * !DESC, OBJECT, { // 19.1.2.6 / 15.2.3.3 Object.getOwnPropertyDescriptor(O, P) getOwnPropertyDescriptor: getOwnDescriptor, // 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes) defineProperty: defineProperty, // 19.1.2.3 / 15.2.3.7 Object.defineProperties(O, Properties) defineProperties: defineProperties }); // IE 8- don't enum bug keys var keys1 = [CONSTRUCTOR, HAS_OWN, 'isPrototypeOf', IS_ENUMERABLE, TO_LOCALE, TO_STRING, 'valueOf'] // Additional keys for getOwnPropertyNames , keys2 = keys1.concat('length', PROTOTYPE) , keysLen1 = keys1.length; // Create object with `null` prototype: use iframe Object with cleared prototype function createDict(){ // Thrash, waste and sodomy: IE GC bug var iframe = document[CREATE_ELEMENT]('iframe') , i = keysLen1 , iframeDocument; iframe.style.display = 'none'; html.appendChild(iframe); iframe.src = 'javascript:'; // createDict = iframe.contentWindow.Object; // html.removeChild(iframe); iframeDocument = iframe.contentWindow.document; iframeDocument.open(); iframeDocument.write('<script>document.F=Object</script>'); iframeDocument.close(); createDict = iframeDocument.F; while(i--)delete createDict[PROTOTYPE][keys1[i]]; return createDict(); } function createGetKeys(names, length, isNames){ return function(object){ var O = ES5Object(object) , i = 0 , result = [] , key; for(key in O)if(key != $PROTO)has(O, key) && result.push(key); // Don't enum bug & hidden keys while(length > i)if(has(O, key = names[i++])){ ~indexOf.call(result, key) || result.push(key); } return result; } } function isPrimitive(it){ return !isObject(it) } $define(STATIC, OBJECT, { // 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O) getPrototypeOf: getPrototypeOf = getPrototypeOf || function(O){ if(has(assertObject(O), $PROTO))return O[$PROTO]; if(isFunction(O[CONSTRUCTOR]) && O instanceof O[CONSTRUCTOR]){ return O[CONSTRUCTOR][PROTOTYPE]; } return O instanceof Object ? ObjectProto : null; }, // 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O) getOwnPropertyNames: getNames = getNames || createGetKeys(keys2, keys2.length, true), // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) create: create = create || function(O, /*?*/Properties){ var result if(O !== null){ Empty[PROTOTYPE] = assertObject(O); result = new Empty(); Empty[PROTOTYPE] = null; // add "__proto__" for Object.getPrototypeOf shim if(result[CONSTRUCTOR][PROTOTYPE] !== O)result[$PROTO] = O; } else result = createDict(); return Properties === undefined ? result : defineProperties(result, Properties); }, // 19.1.2.14 / 15.2.3.14 Object.keys(O) keys: getKeys = getKeys || createGetKeys(keys1, keysLen1, false), // 19.1.2.17 / 15.2.3.8 Object.seal(O) seal: returnIt, // <- cap // 19.1.2.5 / 15.2.3.9 Object.freeze(O) freeze: returnIt, // <- cap // 19.1.2.15 / 15.2.3.10 Object.preventExtensions(O) preventExtensions: returnIt, // <- cap // 19.1.2.13 / 15.2.3.11 Object.isSealed(O) isSealed: isPrimitive, // <- cap // 19.1.2.12 / 15.2.3.12 Object.isFrozen(O) isFrozen: isPrimitive, // <- cap // 19.1.2.11 / 15.2.3.13 Object.isExtensible(O) isExtensible: isObject // <- cap }); // 19.2.3.2 / 15.3.4.5 Function.prototype.bind(thisArg, args...) $define(PROTO, FUNCTION, { bind: function(that /*, args... */){ var fn = assertFunction(this) , partArgs = slice.call(arguments, 1); function bound(/* args... */){ var args = partArgs.concat(slice.call(arguments)); return (this instanceof bound ? construct : invoke)(fn, args, that); } return bound; } }); // Fix for not array-like ES3 string function arrayMethodFix(fn){ return function(){ return fn.apply(ES5Object(this), arguments); } } if(!(0 in Object(DOT) && DOT[0] == DOT)){ ES5Object = function(it){ return cof(it) == STRING ? it.split('') : Object(it); } slice = arrayMethodFix(slice); } $define(PROTO + FORCED * (ES5Object != Object), ARRAY, { slice: slice, join: arrayMethodFix(ArrayProto.join) }); // 22.1.2.2 / 15.4.3.2 Array.isArray(arg) $define(STATIC, ARRAY, { isArray: function(arg){ return cof(arg) == ARRAY } }); function createArrayReduce(isRight){ return function(callbackfn, memo){ assertFunction(callbackfn); var O = ES5Object(this) , length = toLength(O.length) , index = isRight ? length - 1 : 0 , i = isRight ? -1 : 1; if(2 > arguments.length)for(;;){ if(index in O){ memo = O[index]; index += i; break; } index += i; assert(isRight ? index >= 0 : length > index, REDUCE_ERROR); } for(;isRight ? index >= 0 : length > index; index += i)if(index in O){ memo = callbackfn(memo, O[index], index, this); } return memo; } } $define(PROTO, ARRAY, { // 22.1.3.10 / 15.4.4.18 Array.prototype.forEach(callbackfn [, thisArg]) forEach: forEach = forEach || createArrayMethod(0), // 22.1.3.15 / 15.4.4.19 Array.prototype.map(callbackfn [, thisArg]) map: createArrayMethod(1), // 22.1.3.7 / 15.4.4.20 Array.prototype.filter(callbackfn [, thisArg]) filter: createArrayMethod(2), // 22.1.3.23 / 15.4.4.17 Array.prototype.some(callbackfn [, thisArg]) some: createArrayMethod(3), // 22.1.3.5 / 15.4.4.16 Array.prototype.every(callbackfn [, thisArg]) every: createArrayMethod(4), // 22.1.3.18 / 15.4.4.21 Array.prototype.reduce(callbackfn [, initialValue]) reduce: createArrayReduce(false), // 22.1.3.19 / 15.4.4.22 Array.prototype.reduceRight(callbackfn [, initialValue]) reduceRight: createArrayReduce(true), // 22.1.3.11 / 15.4.4.14 Array.prototype.indexOf(searchElement [, fromIndex]) indexOf: indexOf = indexOf || createArrayContains(false), // 22.1.3.14 / 15.4.4.15 Array.prototype.lastIndexOf(searchElement [, fromIndex]) lastIndexOf: function(el, fromIndex /* = @[*-1] */){ var O = ES5Object(this) , length = toLength(O.length) , index = length - 1; if(arguments.length > 1)index = min(index, toInteger(fromIndex)); if(index < 0)index = toLength(length + index); for(;index >= 0; index--)if(index in O)if(O[index] === el)return index; return -1; } }); // 21.1.3.25 / 15.5.4.20 String.prototype.trim() $define(PROTO, STRING, {trim: createReplacer(/^\s*([\s\S]*\S)?\s*$/, '$1')}); // 20.3.3.1 / 15.9.4.4 Date.now() $define(STATIC, DATE, {now: function(){ return +new Date; }}); if(_classof(function(){return arguments}()) == OBJECT)classof = function(it){ var cof = _classof(it); return cof == OBJECT && isFunction(it.callee) ? ARGUMENTS : cof; } }('propertyIsEnumerable', Function(), classof, safeSymbol(PROTOTYPE)); /****************************************************************************** * Module : global * ******************************************************************************/ $define(GLOBAL + FORCED, {global: global}); /****************************************************************************** * Module : es6_symbol * ******************************************************************************/ // ECMAScript 6 symbols shim !function(TAG, SymbolRegistry, setter){ // 19.4.1.1 Symbol([description]) if(!isNative(Symbol)){ Symbol = function(description){ assert(!(this instanceof Symbol), SYMBOL + ' is not a ' + CONSTRUCTOR); var tag = uid(description); DESC && setter && defineProperty(ObjectProto, tag, { configurable: true, set: function(value){ hidden(this, tag, value); } }); return set(create(Symbol[PROTOTYPE]), TAG, tag); } hidden(Symbol[PROTOTYPE], TO_STRING, function(){ return this[TAG]; }); } $define(GLOBAL + WRAP, {Symbol: Symbol}); var symbolStatics = { // 19.4.2.1 Symbol.for(key) 'for': function(key){ return has(SymbolRegistry, key += '') ? SymbolRegistry[key] : SymbolRegistry[key] = Symbol(key); }, // 19.4.2.4 Symbol.iterator iterator: SYMBOL_ITERATOR, // 19.4.2.5 Symbol.keyFor(sym) keyFor: part.call(keyOf, SymbolRegistry), // 19.4.2.13 Symbol.toStringTag toStringTag: SYMBOL_TAG = getWellKnownSymbol(TO_STRING_TAG, true), pure: safeSymbol, set: set, useSetter: function(){setter = true}, useSimple: function(){setter = false} }; // 19.4.2.2 Symbol.hasInstance // 19.4.2.3 Symbol.isConcatSpreadable // 19.4.2.6 Symbol.match // 19.4.2.8 Symbol.replace // 19.4.2.9 Symbol.search // 19.4.2.10 Symbol.species // 19.4.2.11 Symbol.split // 19.4.2.12 Symbol.toPrimitive // 19.4.2.14 Symbol.unscopables forEach.call(array('hasInstance,isConcatSpreadable,match,replace,search,' + 'species,split,toPrimitive,unscopables'), function(it){ symbolStatics[it] = getWellKnownSymbol(it); } ); $define(STATIC, SYMBOL, symbolStatics); setToStringTag(Symbol, SYMBOL); // 26.1.11 Reflect.ownKeys(target) $define(GLOBAL, {Reflect: {ownKeys: ownKeys}}); }(safeSymbol('tag'), {}, true); /****************************************************************************** * Module : es6 * ******************************************************************************/ // ECMAScript 6 shim !function(isFinite, tmp){ var RangeError = global.RangeError // 20.1.2.3 Number.isInteger(number) , isInteger = Number.isInteger || function(it){ return !isObject(it) && isFinite(it) && floor(it) === it; } // 20.2.2.28 Math.sign(x) , sign = Math.sign || function sign(it){ return (it = +it) == 0 || it != it ? it : it < 0 ? -1 : 1; } , pow = Math.pow , abs = Math.abs , exp = Math.exp , log = Math.log , sqrt = Math.sqrt , fcc = String.fromCharCode , at = createPointAt(true); var objectStatic = { // 19.1.3.1 Object.assign(target, source) assign: assign, // 19.1.3.10 Object.is(value1, value2) is: function(x, y){ return x === y ? x !== 0 || 1 / x === 1 / y : x != x && y != y; } }; // 19.1.3.19 Object.setPrototypeOf(O, proto) // Works with __proto__ only. Old v8 can't works with null proto objects. '__proto__' in ObjectProto && function(buggy, set){ try { set = ctx(call, getOwnDescriptor(ObjectProto, '__proto__').set, 2); set({}, ArrayProto); } catch(e){ buggy = true } objectStatic.setPrototypeOf = setPrototypeOf = setPrototypeOf || function(O, proto){ assertObject(O); assert(proto === null || isObject(proto), proto, ": can't set as prototype!"); if(buggy)O.__proto__ = proto; else set(O, proto); return O; } }(); $define(STATIC, OBJECT, objectStatic); // 20.2.2.5 Math.asinh(x) function asinh(x){ return !isFinite(x = +x) || x == 0 ? x : x < 0 ? -asinh(-x) : log(x + sqrt(x * x + 1)); } $define(STATIC, NUMBER, { // 20.1.2.1 Number.EPSILON EPSILON: pow(2, -52), // 20.1.2.2 Number.isFinite(number) isFinite: function(it){ return typeof it == 'number' && isFinite(it); }, // 20.1.2.3 Number.isInteger(number) isInteger: isInteger, // 20.1.2.4 Number.isNaN(number) isNaN: sameNaN, // 20.1.2.5 Number.isSafeInteger(number) isSafeInteger: function(number){ return isInteger(number) && abs(number) <= MAX_SAFE_INTEGER; }, // 20.1.2.6 Number.MAX_SAFE_INTEGER MAX_SAFE_INTEGER: MAX_SAFE_INTEGER, // 20.1.2.10 Number.MIN_SAFE_INTEGER MIN_SAFE_INTEGER: -MAX_SAFE_INTEGER, // 20.1.2.12 Number.parseFloat(string) parseFloat: parseFloat, // 20.1.2.13 Number.parseInt(string, radix) parseInt: parseInt }); $define(STATIC, MATH, { // 20.2.2.3 Math.acosh(x) acosh: function(x){ return x < 1 ? NaN : log(x + sqrt(x * x - 1)); }, // 20.2.2.5 Math.asinh(x) asinh: asinh, // 20.2.2.7 Math.atanh(x) atanh: function(x){ return x == 0 ? +x : log((1 + +x) / (1 - x)) / 2; }, // 20.2.2.9 Math.cbrt(x) cbrt: function(x){ return sign(x) * pow(abs(x), 1 / 3); }, // 20.2.2.11 Math.clz32(x) clz32: function(x){ return (x >>>= 0) ? 32 - x[TO_STRING](2).length : 32; }, // 20.2.2.12 Math.cosh(x) cosh: function(x){ return (exp(x) + exp(-x)) / 2; }, // 20.2.2.14 Math.expm1(x) expm1: function(x){ return x == 0 ? +x : x > -1e-6 && x < 1e-6 ? +x + x * x / 2 : exp(x) - 1; }, // 20.2.2.16 Math.fround(x) // TODO: fallback for IE9- fround: function(x){ return new Float32Array([x])[0]; }, // 20.2.2.17 Math.hypot([value1[, value2[, … ]]]) // TODO: work with very large & small numbers hypot: function(value1, value2){ var sum = 0 , length = arguments.length , value; while(length--){ value = +arguments[length]; if(value == Infinity || value == -Infinity)return Infinity; sum += value * value; } return sqrt(sum); }, // 20.2.2.18 Math.imul(x, y) imul: function(x, y){ var UInt16 = 0xffff , xl = UInt16 & x , yl = UInt16 & y; return 0 | xl * yl + ((UInt16 & x >>> 16) * yl + xl * (UInt16 & y >>> 16) << 16 >>> 0); }, // 20.2.2.20 Math.log1p(x) log1p: function(x){ return x > -1e-8 && x < 1e-8 ? x - x * x / 2 : log(1 + +x); }, // 20.2.2.21 Math.log10(x) log10: function(x){ return log(x) / Math.LN10; }, // 20.2.2.22 Math.log2(x) log2: function(x){ return log(x) / Math.LN2; }, // 20.2.2.28 Math.sign(x) sign: sign, // 20.2.2.30 Math.sinh(x) sinh: function(x){ return x == 0 ? +x : (exp(x) - exp(-x)) / 2; }, // 20.2.2.33 Math.tanh(x) tanh: function(x){ return isFinite(x) ? x == 0 ? +x : (exp(x) - exp(-x)) / (exp(x) + exp(-x)) : sign(x); }, // 20.2.2.34 Math.trunc(x) trunc: trunc }); // 20.2.1.9 Math[@@toStringTag] setToStringTag(Math, MATH, true); function assertNotRegExp(it){ if(isObject(it) && it instanceof RegExp)throw TypeError(); } $define(STATIC, STRING, { // 21.1.2.2 String.fromCodePoint(...codePoints) fromCodePoint: function(x){ var res = [] , len = arguments.length , i = 0 , code while(len > i){ code = +arguments[i++]; if(toIndex(code, 0x10ffff) !== code)throw RangeError(code + ' is not a valid code point'); res.push(code < 0x10000 ? fcc(code) : fcc(((code -= 0x10000) >> 10) + 0xd800, code % 0x400 + 0xdc00) ); } return res.join(''); }, // 21.1.2.4 String.raw(callSite, ...substitutions) raw: function(callSite){ var raw = ES5Object(assertDefined(callSite.raw)) , len = toLength(raw.length) , sln = arguments.length , res = [] , i = 0; while(len > i){ res.push(String(raw[i++])); if(i < sln)res.push(String(arguments[i])); } return res.join(''); } }); $define(PROTO, STRING, { // 21.1.3.3 String.prototype.codePointAt(pos) codePointAt: createPointAt(false), // 21.1.3.6 String.prototype.endsWith(searchString [, endPosition]) endsWith: function(searchString /*, endPosition = @length */){ assertNotRegExp(searchString); var that = String(assertDefined(this)) , endPosition = arguments[1] , len = toLength(that.length) , end = endPosition === undefined ? len : min(toLength(endPosition), len); searchString += ''; return that.slice(end - searchString.length, end) === searchString; }, // 21.1.3.7 String.prototype.includes(searchString, position = 0) includes: function(searchString /*, position = 0 */){ assertNotRegExp(searchString); return !!~String(assertDefined(this)).indexOf(searchString, arguments[1]); }, // 21.1.3.13 String.prototype.repeat(count) repeat: function(count){ var str = String(assertDefined(this)) , res = '' , n = toInteger(count); if(0 > n || n == Infinity)throw RangeError("Count can't be negative"); for(;n > 0; (n >>>= 1) && (str += str))if(n & 1)res += str; return res; }, // 21.1.3.18 String.prototype.startsWith(searchString [, position ]) startsWith: function(searchString /*, position = 0 */){ assertNotRegExp(searchString); var that = String(assertDefined(this)) , index = toLength(min(arguments[1], that.length)); searchString += ''; return that.slice(index, index + searchString.length) === searchString; } }); // 21.1.3.27 String.prototype[@@iterator]() defineStdIterators(String, STRING, function(iterated){ set(this, ITER, {o: String(iterated), i: 0}); // 21.1.5.2.1 %StringIteratorPrototype%.next() }, function(){ var iter = this[ITER] , O = iter.o , index = iter.i , point; if(index >= O.length)return iterResult(1); point = at.call(O, index); iter.i += point.length; return iterResult(0, point); }); $define(STATIC, ARRAY, { // 22.1.2.1 Array.from(arrayLike, mapfn = undefined, thisArg = undefined) from: function(arrayLike/*, mapfn = undefined, thisArg = undefined*/){ var O = Object(assertDefined(arrayLike)) , result = new (generic(this, Array)) , mapfn = arguments[1] , that = arguments[2] , mapping = mapfn !== undefined , f = mapping ? ctx(mapfn, that, 2) : undefined , index = 0 , length; if(isIterable(O))for(var iter = getIterator(O), step; !(step = iter.next()).done; index++){ result[index] = mapping ? f(step.value, index) : step.value; } else for(length = toLength(O.length); length > index; index++){ result[index] = mapping ? f(O[index], index) : O[index]; } result.length = index; return result; }, // 22.1.2.3 Array.of( ...items) of: function(/* ...args */){ var index = 0 , length = arguments.length , result = new (generic(this, Array))(length); while(length > index)result[index] = arguments[index++]; result.length = length; return result; } }); $define(PROTO, ARRAY, { // 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length) copyWithin: function(target /* = 0 */, start /* = 0, end = @length */){ var O = Object(assertDefined(this)) , len = toLength(O.length) , to = toIndex(target, len) , from = toIndex(start, len) , end = arguments[2] , fin = end === undefined ? len : toIndex(end, len) , count = min(fin - from, len - to) , inc = 1; if(from < to && to < from + count){ inc = -1; from = from + count - 1; to = to + count - 1; } while(count-- > 0){ if(from in O)O[to] = O[from]; else delete O[to]; to += inc; from += inc; } return O; }, // 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length) fill: function(value /*, start = 0, end = @length */){ var O = Object(assertDefined(this)) , length = toLength(O.length) , index = toIndex(arguments[1], length) , end = arguments[2] , endPos = end === undefined ? length : toIndex(end, length); while(endPos > index)O[index++] = value; return O; }, // 22.1.3.8 Array.prototype.find(predicate, thisArg = undefined) find: createArrayMethod(5), // 22.1.3.9 Array.prototype.findIndex(predicate, thisArg = undefined) findIndex: createArrayMethod(6) }); // 22.1.3.4 Array.prototype.entries() // 22.1.3.13 Array.prototype.keys() // 22.1.3.29 Array.prototype.values() // 22.1.3.30 Array.prototype[@@iterator]() defineStdIterators(Array, ARRAY, function(iterated, kind){ set(this, ITER, {o: ES5Object(iterated), i: 0, k: kind}); // 22.1.5.2.1 %ArrayIteratorPrototype%.next() }, function(){ var iter = this[ITER] , O = iter.o , kind = iter.k , index = iter.i++; if(!O || index >= O.length)return iter.o = undefined, iterResult(1); if(kind == KEY) return iterResult(0, index); if(kind == VALUE)return iterResult(0, O[index]); return iterResult(0, [index, O[index]]); }, VALUE); // argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7) Iterators[ARGUMENTS] = Iterators[ARRAY]; // 24.3.3 JSON[@@toStringTag] setToStringTag(global.JSON, 'JSON', true); if(framework){ // 19.1.3.6 Object.prototype.toString() tmp[SYMBOL_TAG] = DOT; if(cof(tmp) != DOT)hidden(ObjectProto, TO_STRING, function(){ return '[object ' + classof(this) + ']'; }); // 21.2.5.3 get RegExp.prototype.flags() if(/./g.flags != 'g')defineProperty(RegExp[PROTOTYPE], 'flags', { configurable: true, get: createReplacer(/^.*\/(\w*)$/, '$1') }); } }(isFinite, {}); /****************************************************************************** * Module : immediate * ******************************************************************************/ // setImmediate shim // Node.js 0.9+ & IE10+ has setImmediate, else: isFunction(setImmediate) && isFunction(clearImmediate) || function(ONREADYSTATECHANGE){ var postMessage = global.postMessage , addEventListener = global.addEventListener , MessageChannel = global.MessageChannel , counter = 0 , queue = {} , defer, channel, port; setImmediate = function(fn){ var args = [], i = 1; while(arguments.length > i)args.push(arguments[i++]); queue[++counter] = function(){ invoke(isFunction(fn) ? fn : Function(fn), args); } defer(counter); return counter; } clearImmediate = function(id){ delete queue[id]; } function run(id){ if(has(queue, id)){ var fn = queue[id]; delete queue[id]; fn(); } } function listner(event){ run(event.data); } // Node.js 0.8- if(NODE){ defer = function(id){ nextTick(part.call(run, id)); } // Modern browsers, skip implementation for WebWorkers // IE8 has postMessage, but it's sync & typeof its postMessage is object } else if(addEventListener && isFunction(postMessage) && !global.importScripts){ defer = function(id){ postMessage(id, '*'); } addEventListener('message', listner, false); // WebWorkers } else if(isFunction(MessageChannel)){ channel = new MessageChannel; port = channel.port2; channel.port1.onmessage = listner; defer = ctx(port.postMessage, port, 1); // IE8- } else if(document && ONREADYSTATECHANGE in document[CREATE_ELEMENT]('script')){ defer = function(id){ html.appendChild(document[CREATE_ELEMENT]('script'))[ONREADYSTATECHANGE] = function(){ html.removeChild(this); run(id); } } // Rest old browsers } else { defer = function(id){ setTimeout(part.call(run, id), 0); } } }('onreadystatechange'); $define(GLOBAL + BIND, { setImmediate: setImmediate, clearImmediate: clearImmediate }); /****************************************************************************** * Module : es6_promise * ******************************************************************************/ // ES6 promises shim // Based on https://github.com/getify/native-promise-only/ !function(Promise, test){ isFunction(Promise) && isFunction(Promise.resolve) && Promise.resolve(test = new Promise(Function())) == test || function(asap, DEF){ function isThenable(o){ var then; if(isObject(o))then = o.then; return isFunction(then) ? then : false; } function notify(def){ var chain = def.chain; chain.length && asap(function(){ var msg = def.msg , ok = def.state == 1 , i = 0; while(chain.length > i)!function(react){ var cb = ok ? react.ok : react.fail , ret, then; try { if(cb){ ret = cb === true ? msg : cb(msg); if(ret === react.P){ react.rej(TypeError(PROMISE + '-chain cycle')); } else if(then = isThenable(ret)){ then.call(ret, react.res, react.rej); } else react.res(ret); } else react.rej(msg); } catch(err){ react.rej(err); } }(chain[i++]); chain.length = 0; }); } function resolve(msg){ var def = this , then, wrapper; if(def.done)return; def.done = true; def = def.def || def; // unwrap try { if(then = isThenable(msg)){ wrapper = {def: def, done: false}; // wrap then.call(msg, ctx(resolve, wrapper, 1), ctx(reject, wrapper, 1)); } else { def.msg = msg; def.state = 1; notify(def); } } catch(err){ reject.call(wrapper || {def: def, done: false}, err); // wrap } } function reject(msg){ var def = this; if(def.done)return; def.done = true; def = def.def || def; // unwrap def.msg = msg; def.state = 2; notify(def); } // 25.4.3.1 Promise(executor) Promise = function(executor){ assertFunction(executor); assertInstance(this, Promise, PROMISE); var def = {chain: [], state: 0, done: false, msg: undefined}; hidden(this, DEF, def); try { executor(ctx(resolve, def, 1), ctx(reject, def, 1)); } catch(err){ reject.call(def, err); } } assignHidden(Promise[PROTOTYPE], { // 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected) then: function(onFulfilled, onRejected){ var react = { ok: isFunction(onFulfilled) ? onFulfilled : true, fail: isFunction(onRejected) ? onRejected : false } , P = react.P = new this[CONSTRUCTOR](function(resolve, reject){ react.res = assertFunction(resolve); react.rej = assertFunction(reject); }), def = this[DEF]; def.chain.push(react); def.state && notify(def); return P; }, // 25.4.5.1 Promise.prototype.catch(onRejected) 'catch': function(onRejected){ return this.then(undefined, onRejected); } }); assignHidden(Promise, { // 25.4.4.1 Promise.all(iterable) all: function(iterable){ var Promise = this , values = []; return new Promise(function(resolve, reject){ forOf(iterable, false, push, values); var remaining = values.length , results = Array(remaining); if(remaining)forEach.call(values, function(promise, index){ Promise.resolve(promise).then(function(value){ results[index] = value; --remaining || resolve(results); }, reject); }); else resolve(results); }); }, // 25.4.4.4 Promise.race(iterable) race: function(iterable){ var Promise = this; return new Promise(function(resolve, reject){ forOf(iterable, false, function(promise){ Promise.resolve(promise).then(resolve, reject); }); }); }, // 25.4.4.5 Promise.reject(r) reject: function(r){ return new this(function(resolve, reject){ reject(r); }); }, // 25.4.4.6 Promise.resolve(x) resolve: function(x){ return isObject(x) && getPrototypeOf(x) === this[PROTOTYPE] ? x : new this(function(resolve, reject){ resolve(x); }); } }); }(nextTick || setImmediate, safeSymbol('def')); setToStringTag(Promise, PROMISE); $define(GLOBAL + FORCED * !isNative(Promise), {Promise: Promise}); }(global[PROMISE]); /****************************************************************************** * Module : es6_collections * ******************************************************************************/ // ECMAScript 6 collections shim !function(){ var UID = safeSymbol('uid') , DATA = safeSymbol('data') , WEAK = safeSymbol('weak') , LAST = safeSymbol('last') , FIRST = safeSymbol('first') , SIZE = DESC ? safeSymbol('size') : 'size' , uid = 0; function getCollection(C, NAME, methods, commonMethods, isMap, isWeak){ var ADDER = isMap ? 'set' : 'add' , proto = C && C[PROTOTYPE] , O = {}; function initFromIterable(that, iterable){ if(iterable != undefined)forOf(iterable, isMap, that[ADDER], that); return that; } function fixSVZ(key, chain){ var method = proto[key]; framework && hidden(proto, key, function(a, b){ var result = method.call(this, a === 0 ? 0 : a, b); return chain ? this : result; }); } if(!isNative(C) || !(isWeak || (!BUGGY_ITERATORS && has(proto, 'entries')))){ // create collection constructor C = isWeak ? function(iterable){ assertInstance(this, C, NAME); set(this, UID, uid++); initFromIterable(this, iterable); } : function(iterable){ var that = this; assertInstance(that, C, NAME); set(that, DATA, create(null)); set(that, SIZE, 0); set(that, LAST, undefined); set(that, FIRST, undefined); initFromIterable(that, iterable); }; assignHidden(assignHidden(C[PROTOTYPE], methods), commonMethods); isWeak || defineProperty(C[PROTOTYPE], 'size', {get: function(){ return assertDefined(this[SIZE]); }}); } else { var Native = C , inst = new C , chain = inst[ADDER](isWeak ? {} : -0, 1) , buggyZero; // wrap to init collections from iterable if(!NATIVE_ITERATORS || !C.length){ C = function(iterable){ assertInstance(this, C, NAME); return initFromIterable(new Native, iterable); } C[PROTOTYPE] = proto; } isWeak || inst[FOR_EACH](function(val, key){ buggyZero = 1 / key === -Infinity; }); // fix converting -0 key to +0 if(buggyZero){ fixSVZ('delete'); fixSVZ('has'); isMap && fixSVZ('get'); } // + fix .add & .set for chaining if(buggyZero || chain !== inst)fixSVZ(ADDER, true); } setToStringTag(C, NAME); O[NAME] = C; $define(GLOBAL + WRAP + FORCED * !isNative(C), O); // add .keys, .values, .entries, [@@iterator] // 23.1.3.4, 23.1.3.8, 23.1.3.11, 23.1.3.12, 23.2.3.5, 23.2.3.8, 23.2.3.10, 23.2.3.11 isWeak || defineStdIterators(C, NAME, function(iterated, kind){ set(this, ITER, {o: iterated, k: kind}); }, function(){ var iter = this[ITER] , O = iter.o , kind = iter.k , entry = iter.l; while(entry && entry.r)entry = entry.p; if(!O || !(iter.l = entry = entry ? entry.n : O[FIRST]))return iter.o = undefined, iterResult(1); if(kind == KEY) return iterResult(0, entry.k); if(kind == VALUE)return iterResult(0, entry.v); return iterResult(0, [entry.k, entry.v]); }, isMap ? KEY+VALUE : VALUE, !isMap); return C; } function fastKey(it, create){ // return it with 'S' prefix if it's string or with 'P' prefix for over primitives if(!isObject(it))return (typeof it == 'string' ? 'S' : 'P') + it; // if it hasn't object id - add next if(!has(it, UID)){ if(create)hidden(it, UID, ++uid); else return ''; } // return object id with 'O' prefix return 'O' + it[UID]; } function def(that, key, value){ var index = fastKey(key, true) , data = that[DATA] , last = that[LAST] , entry; if(index in data)data[index].v = value; else { entry = data[index] = {k: key, v: value, p: last}; if(!that[FIRST])that[FIRST] = entry; if(last)last.n = entry; that[LAST] = entry; that[SIZE]++; } return that; } function del(that, index){ var data = that[DATA] , entry = data[index] , next = entry.n , prev = entry.p; delete data[index]; entry.r = true; if(prev)prev.n = next; if(next)next.p = prev; if(that[FIRST] == entry)that[FIRST] = next; if(that[LAST] == entry)that[LAST] = prev; that[SIZE]--; } var collectionMethods = { // 23.1.3.1 Map.prototype.clear() // 23.2.3.2 Set.prototype.clear() clear: function(){ for(var index in this[DATA])del(this, index); }, // 23.1.3.3 Map.prototype.delete(key) // 23.2.3.4 Set.prototype.delete(value) 'delete': function(key){ var index = fastKey(key) , contains = index in this[DATA]; if(contains)del(this, index); return contains; }, // 23.2.3.6 Set.prototype.forEach(callbackfn, thisArg = undefined) // 23.1.3.5 Map.prototype.forEach(callbackfn, thisArg = undefined) forEach: function(callbackfn /*, that = undefined */){ var f = ctx(callbackfn, arguments[1], 3) , entry; while(entry = entry ? entry.n : this[FIRST]){ f(entry.v, entry.k, this); while(entry && entry.r)entry = entry.p; } }, // 23.1.3.7 Map.prototype.has(key) // 23.2.3.7 Set.prototype.has(value) has: function(key){ return fastKey(key) in this[DATA]; } } // 23.1 Map Objects Map = getCollection(Map, MAP, { // 23.1.3.6 Map.prototype.get(key) get: function(key){ var entry = this[DATA][fastKey(key)]; return entry && entry.v; }, // 23.1.3.9 Map.prototype.set(key, value) set: function(key, value){ return def(this, key === 0 ? 0 : key, value); } }, collectionMethods, true); // 23.2 Set Objects Set = getCollection(Set, SET, { // 23.2.3.1 Set.prototype.add(value) add: function(value){ return def(this, value = value === 0 ? 0 : value, value); } }, collectionMethods); function setWeak(that, key, value){ has(assertObject(key), WEAK) || hidden(key, WEAK, {}); key[WEAK][that[UID]] = value; return that; } function hasWeak(key){ return isObject(key) && has(key, WEAK) && has(key[WEAK], this[UID]); } var weakMethods = { // 23.3.3.2 WeakMap.prototype.delete(key) // 23.4.3.3 WeakSet.prototype.delete(value) 'delete': function(key){ return hasWeak.call(this, key) && delete key[WEAK][this[UID]]; }, // 23.3.3.4 WeakMap.prototype.has(key) // 23.4.3.4 WeakSet.prototype.has(value) has: hasWeak }; // 23.3 WeakMap Objects WeakMap = getCollection(WeakMap, WEAKMAP, { // 23.3.3.3 WeakMap.prototype.get(key) get: function(key){ if(isObject(key) && has(key, WEAK))return key[WEAK][this[UID]]; }, // 23.3.3.5 WeakMap.prototype.set(key, value) set: function(key, value){ return setWeak(this, key, value); } }, weakMethods, true, true); // 23.4 WeakSet Objects WeakSet = getCollection(WeakSet, WEAKSET, { // 23.4.3.1 WeakSet.prototype.add(value) add: function(value){ return setWeak(this, value, true); } }, weakMethods, false, true); }(); /****************************************************************************** * Module : es6_reflect * ******************************************************************************/ !function(){ function Enumerate(iterated){ var keys = [], key; for(key in iterated)keys.push(key); set(this, ITER, {o: iterated, a: keys, i: 0}); } createIterator(Enumerate, OBJECT, function(){ var iter = this[ITER] , keys = iter.a , key; do { if(iter.i >= keys.length)return iterResult(1); } while(!((key = keys[iter.i++]) in iter.o)); return iterResult(0, key); }); function wrap(fn){ return function(it){ assertObject(it); try { return fn.apply(undefined, arguments), true; } catch(e){ return false; } } } function reflectGet(target, propertyKey, receiver){ if(receiver === undefined)receiver = target; var desc = getOwnDescriptor(assertObject(target), propertyKey), proto; if(desc)return desc.get ? desc.get.call(receiver) : desc.value; return isObject(proto = getPrototypeOf(target)) ? reflectGet(proto, propertyKey, receiver) : undefined; } function reflectSet(target, propertyKey, V, receiver){ if(receiver === undefined)receiver = target; var desc = getOwnDescriptor(assertObject(target), propertyKey), proto; if(desc){ if(desc.writable === false)return false; if(desc.set)return desc.set.call(receiver, V), true; } if(isObject(proto = getPrototypeOf(target)))return reflectSet(proto, propertyKey, V, receiver); desc = getOwnDescriptor(receiver, propertyKey) || descriptor(0); desc.value = V; return defineProperty(receiver, propertyKey, desc), true; } var reflect = { // 26.1.1 Reflect.apply(target, thisArgument, argumentsList) apply: ctx(call, apply, 3), // 26.1.2 Reflect.construct(target, argumentsList) construct: construct, // 26.1.3 Reflect.defineProperty(target, propertyKey, attributes) defineProperty: wrap(defineProperty), // 26.1.4 Reflect.deleteProperty(target, propertyKey) deleteProperty: function(target, propertyKey){ var desc = getOwnDescriptor(assertObject(target), propertyKey); return desc && !desc.configurable ? false : delete target[propertyKey]; }, // 26.1.5 Reflect.enumerate(target) enumerate: function(target){ return new Enumerate(assertObject(target)); }, // 26.1.6 Reflect.get(target, propertyKey [, receiver]) get: reflectGet, // 26.1.7 Reflect.getOwnPropertyDescriptor(target, propertyKey) getOwnPropertyDescriptor: getOwnDescriptor, // 26.1.8 Reflect.getPrototypeOf(target) getPrototypeOf: getPrototypeOf, // 26.1.9 Reflect.has(target, propertyKey) has: function(target, propertyKey){ return propertyKey in target; }, // 26.1.10 Reflect.isExtensible(target) isExtensible: Object.isExtensible || function(target){ return !!assertObject(target); }, // 26.1.11 Reflect.ownKeys(target) ownKeys: ownKeys, // 26.1.12 Reflect.preventExtensions(target) preventExtensions: wrap(Object.preventExtensions || returnIt), // 26.1.13 Reflect.set(target, propertyKey, V [, receiver]) set: reflectSet } // 26.1.14 Reflect.setPrototypeOf(target, proto) if(setPrototypeOf)reflect.setPrototypeOf = function(target, proto){ return setPrototypeOf(assertObject(target), proto), true; }; $define(GLOBAL, {Reflect: {}}); $define(STATIC, 'Reflect', reflect); }(); /****************************************************************************** * Module : es7 * ******************************************************************************/ !function(){ $define(PROTO, ARRAY, { // https://github.com/domenic/Array.prototype.includes includes: createArrayContains(true) }); $define(PROTO, STRING, { // https://github.com/mathiasbynens/String.prototype.at at: createPointAt(true) }); function createObjectToArray(isEntries){ return function(object){ var O = ES5Object(object) , keys = getKeys(object) , length = keys.length , i = 0 , result = Array(length) , key; if(isEntries)while(length > i)result[i] = [key = keys[i++], O[key]]; else while(length > i)result[i] = O[keys[i++]]; return result; } } $define(STATIC, OBJECT, { // https://github.com/rwaldron/tc39-notes/blob/master/es6/2014-04/apr-9.md#51-objectentries-objectvalues values: createObjectToArray(false), entries: createObjectToArray(true) }); $define(STATIC, REGEXP, { // https://gist.github.com/kangax/9698100 escape: createReplacer(/([\\\-[\]{}()*+?.,^$|])/g, '\\$1', true) }); }(); /****************************************************************************** * Module : es7_refs * ******************************************************************************/ // https://github.com/zenparsing/es-abstract-refs !function(REFERENCE){ REFERENCE_GET = getWellKnownSymbol(REFERENCE+'Get', true); var REFERENCE_SET = getWellKnownSymbol(REFERENCE+SET, true) , REFERENCE_DELETE = getWellKnownSymbol(REFERENCE+'Delete', true); $define(STATIC, SYMBOL, { referenceGet: REFERENCE_GET, referenceSet: REFERENCE_SET, referenceDelete: REFERENCE_DELETE }); hidden(FunctionProto, REFERENCE_GET, returnThis); function setMapMethods(Constructor){ if(Constructor){ var MapProto = Constructor[PROTOTYPE]; hidden(MapProto, REFERENCE_GET, MapProto.get); hidden(MapProto, REFERENCE_SET, MapProto.set); hidden(MapProto, REFERENCE_DELETE, MapProto['delete']); } } setMapMethods(Map); setMapMethods(WeakMap); }('reference'); /****************************************************************************** * Module : dict * ******************************************************************************/ !function(DICT){ function Dict(iterable){ var dict = create(null); if(iterable != undefined){ if(isIterable(iterable)){ for(var iter = getIterator(iterable), step, value; !(step = iter.next()).done;){ value = step.value; dict[value[0]] = value[1]; } } else assign(dict, iterable); } return dict; } Dict[PROTOTYPE] = null; function DictIterator(iterated, kind){ set(this, ITER, {o: ES5Object(iterated), a: getKeys(iterated), i: 0, k: kind}); } createIterator(DictIterator, DICT, function(){ var iter = this[ITER] , O = iter.o , keys = iter.a , kind = iter.k , key; do { if(iter.i >= keys.length)return iterResult(1); } while(!has(O, key = keys[iter.i++])); if(kind == KEY) return iterResult(0, key); if(kind == VALUE)return iterResult(0, O[key]); return iterResult(0, [key, O[key]]); }); function createDictIter(kind){ return function(it){ return new DictIterator(it, kind); } } /* * 0 -> forEach * 1 -> map * 2 -> filter * 3 -> some * 4 -> every * 5 -> find * 6 -> findKey * 7 -> mapPairs */ function createDictMethod(type){ var isMap = type == 1 , isEvery = type == 4; return function(object, callbackfn, that /* = undefined */){ var f = ctx(callbackfn, that, 3) , O = ES5Object(object) , result = isMap || type == 7 || type == 2 ? new (generic(this, Dict)) : undefined , key, val, res; for(key in O)if(has(O, key)){ val = O[key]; res = f(val, key, object); if(type){ if(isMap)result[key] = res; // map else if(res)switch(type){ case 2: result[key] = val; break // filter case 3: return true; // some case 5: return val; // find case 6: return key; // findKey case 7: result[res[0]] = res[1]; // mapPairs } else if(isEvery)return false; // every } } return type == 3 || isEvery ? isEvery : result; } } function createDictReduce(isTurn){ return function(object, mapfn, init){ assertFunction(mapfn); var O = ES5Object(object) , keys = getKeys(O) , length = keys.length , i = 0 , memo, key, result; if(isTurn)memo = init == undefined ? new (generic(this, Dict)) : Object(init); else if(arguments.length < 3){ assert(length, REDUCE_ERROR); memo = O[keys[i++]]; } else memo = Object(init); while(length > i)if(has(O, key = keys[i++])){ result = mapfn(memo, O[key], key, object); if(isTurn){ if(result === false)break; } else memo = result; } return memo; } } var findKey = createDictMethod(6); function includes(object, el){ return (el == el ? keyOf(object, el) : findKey(object, sameNaN)) !== undefined; } var dictMethods = { keys: createDictIter(KEY), values: createDictIter(VALUE), entries: createDictIter(KEY+VALUE), forEach: createDictMethod(0), map: createDictMethod(1), filter: createDictMethod(2), some: createDictMethod(3), every: createDictMethod(4), find: createDictMethod(5), findKey: findKey, mapPairs:createDictMethod(7), reduce: createDictReduce(false), turn: createDictReduce(true), keyOf: keyOf, includes:includes, // Has / get / set own property has: has, get: get, set: createDefiner(0), isDict: function(it){ return isObject(it) && getPrototypeOf(it) === Dict[PROTOTYPE]; } }; if(REFERENCE_GET)for(var key in dictMethods)!function(fn){ function method(){ for(var args = [this], i = 0; i < arguments.length;)args.push(arguments[i++]); return invoke(fn, args); } fn[REFERENCE_GET] = function(){ return method; } }(dictMethods[key]); $define(GLOBAL + FORCED, {Dict: assignHidden(Dict, dictMethods)}); }('Dict'); /****************************************************************************** * Module : $for * ******************************************************************************/ !function(ENTRIES, FN){ function $for(iterable, entries){ if(!(this instanceof $for))return new $for(iterable, entries); this[ITER] = getIterator(iterable); this[ENTRIES] = !!entries; } createIterator($for, 'Wrapper', function(){ return this[ITER].next(); }); var $forProto = $for[PROTOTYPE]; setIterator($forProto, function(){ return this[ITER]; // unwrap }); function createChainIterator(next){ function Iter(I, fn, that){ this[ITER] = getIterator(I); this[ENTRIES] = I[ENTRIES]; this[FN] = ctx(fn, that, I[ENTRIES] ? 2 : 1); } createIterator(Iter, 'Chain', next, $forProto); setIterator(Iter[PROTOTYPE], returnThis); // override $forProto iterator return Iter; } var MapIter = createChainIterator(function(){ var step = this[ITER].next(); return step.done ? step : iterResult(0, stepCall(this[FN], step.value, this[ENTRIES])); }); var FilterIter = createChainIterator(function(){ for(;;){ var step = this[ITER].next(); if(step.done || stepCall(this[FN], step.value, this[ENTRIES]))return step; } }); assignHidden($forProto, { of: function(fn, that){ forOf(this, this[ENTRIES], fn, that); }, array: function(fn, that){ var result = []; forOf(fn != undefined ? this.map(fn, that) : this, false, push, result); return result; }, filter: function(fn, that){ return new FilterIter(this, fn, that); }, map: function(fn, that){ return new MapIter(this, fn, that); } }); $for.isIterable = isIterable; $for.getIterator = getIterator; $define(GLOBAL + FORCED, {$for: $for}); }('entries', safeSymbol('fn')); /****************************************************************************** * Module : timers * ******************************************************************************/ // ie9- setTimeout & setInterval additional parameters fix !function(MSIE){ function wrap(set){ return MSIE ? function(fn, time /*, ...args */){ return set(invoke(part, slice.call(arguments, 2), isFunction(fn) ? fn : Function(fn)), time); } : set; } $define(GLOBAL + BIND + FORCED * MSIE, { setTimeout: setTimeout = wrap(setTimeout), setInterval: wrap(setInterval) }); // ie9- dirty check }(!!navigator && /MSIE .\./.test(navigator.userAgent)); /****************************************************************************** * Module : binding * ******************************************************************************/ !function(_, toLocaleString){ // Placeholder core._ = path._ = path._ || {}; $define(PROTO + FORCED, FUNCTION, { part: part, by: function(that){ var fn = this , _ = path._ , holder = false , length = arguments.length , isThat = that === _ , i = +!isThat , indent = i , it, args; if(isThat){ it = fn; fn = call; } else it = that; if(length < 2)return ctx(fn, it, -1); args = Array(length - indent); while(length > i)if((args[i - indent] = arguments[i++]) === _)holder = true; return partial(fn, args, length, holder, _, true, it); }, only: function(numberArguments, that /* = @ */){ var fn = assertFunction(this) , n = toLength(numberArguments) , isThat = arguments.length > 1; return function(/* ...args */){ var length = min(n, arguments.length) , args = Array(length) , i = 0; while(length > i)args[i] = arguments[i++]; return invoke(fn, args, isThat ? that : this); } } }); function tie(key){ var that = this , bound = {}; return hidden(that, _, function(key){ if(key === undefined || !(key in that))return toLocaleString.call(that); return has(bound, key) ? bound[key] : (bound[key] = ctx(that[key], that, -1)); })[_](key); } hidden(path._, TO_STRING, function(){ return _; }); hidden(ObjectProto, _, tie); DESC || hidden(ArrayProto, _, tie); // IE8- dirty hack - redefined toLocaleString is not enumerable }(DESC ? uid('tie') : TO_LOCALE, ObjectProto[TO_LOCALE]); /****************************************************************************** * Module : object * ******************************************************************************/ !function(){ function define(target, mixin){ var keys = ownKeys(ES5Object(mixin)) , length = keys.length , i = 0, key; while(length > i)defineProperty(target, key = keys[i++], getOwnDescriptor(mixin, key)); return target; }; $define(STATIC + FORCED, OBJECT, { isObject: isObject, classof: classof, define: define, make: function(proto, mixin){ return define(create(proto), mixin); } }); }(); /****************************************************************************** * Module : array * ******************************************************************************/ $define(PROTO + FORCED, ARRAY, { turn: function(fn, target /* = [] */){ assertFunction(fn); var memo = target == undefined ? [] : Object(target) , O = ES5Object(this) , length = toLength(O.length) , index = 0; while(length > index)if(fn(memo, O[index], index++, this) === false)break; return memo; } }); /****************************************************************************** * Module : array_statics * ******************************************************************************/ // JavaScript 1.6 / Strawman array statics shim !function(arrayStatics){ function setArrayStatics(keys, length){ forEach.call(array(keys), function(key){ if(key in ArrayProto)arrayStatics[key] = ctx(call, ArrayProto[key], length); }); } setArrayStatics('pop,reverse,shift,keys,values,entries', 1); setArrayStatics('indexOf,every,some,forEach,map,filter,find,findIndex,includes', 3); setArrayStatics('join,slice,concat,push,splice,unshift,sort,lastIndexOf,' + 'reduce,reduceRight,copyWithin,fill,turn'); $define(STATIC, ARRAY, arrayStatics); }({}); /****************************************************************************** * Module : number * ******************************************************************************/ !function(numberMethods){ function NumberIterator(iterated){ set(this, ITER, {l: toLength(iterated), i: 0}); } createIterator(NumberIterator, NUMBER, function(){ var iter = this[ITER] , i = iter.i++; return i < iter.l ? iterResult(0, i) : iterResult(1); }); defineIterator(Number, NUMBER, function(){ return new NumberIterator(this); }); numberMethods.random = function(lim /* = 0 */){ var a = +this , b = lim == undefined ? 0 : +lim , m = min(a, b); return random() * (max(a, b) - m) + m; }; forEach.call(array( // ES3: 'round,floor,ceil,abs,sin,asin,cos,acos,tan,atan,exp,sqrt,max,min,pow,atan2,' + // ES6: 'acosh,asinh,atanh,cbrt,clz32,cosh,expm1,hypot,imul,log1p,log10,log2,sign,sinh,tanh,trunc' ), function(key){ var fn = Math[key]; if(fn)numberMethods[key] = function(/* ...args */){ // ie9- dont support strict mode & convert `this` to object -> convert it to number var args = [+this] , i = 0; while(arguments.length > i)args.push(arguments[i++]); return invoke(fn, args); } } ); $define(PROTO + FORCED, NUMBER, numberMethods); }({}); /****************************************************************************** * Module : string * ******************************************************************************/ !function(){ var escapeHTMLDict = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&apos;' }, unescapeHTMLDict = {}, key; for(key in escapeHTMLDict)unescapeHTMLDict[escapeHTMLDict[key]] = key; $define(PROTO + FORCED, STRING, { escapeHTML: createReplacer(/[&<>"']/g, escapeHTMLDict), unescapeHTML: createReplacer(/&(?:amp|lt|gt|quot|apos);/g, unescapeHTMLDict) }); }(); /****************************************************************************** * Module : date * ******************************************************************************/ !function(formatRegExp, flexioRegExp, locales, current, SECONDS, MINUTES, HOURS, MONTH, YEAR){ function createFormat(prefix){ return function(template, locale /* = current */){ var that = this , dict = locales[has(locales, locale) ? locale : current]; function get(unit){ return that[prefix + unit](); } return String(template).replace(formatRegExp, function(part){ switch(part){ case 's' : return get(SECONDS); // Seconds : 0-59 case 'ss' : return lz(get(SECONDS)); // Seconds : 00-59 case 'm' : return get(MINUTES); // Minutes : 0-59 case 'mm' : return lz(get(MINUTES)); // Minutes : 00-59 case 'h' : return get(HOURS); // Hours : 0-23 case 'hh' : return lz(get(HOURS)); // Hours : 00-23 case 'D' : return get(DATE); // Date : 1-31 case 'DD' : return lz(get(DATE)); // Date : 01-31 case 'W' : return dict[0][get('Day')]; // Day : Понедельник case 'N' : return get(MONTH) + 1; // Month : 1-12 case 'NN' : return lz(get(MONTH) + 1); // Month : 01-12 case 'M' : return dict[2][get(MONTH)]; // Month : Январь case 'MM' : return dict[1][get(MONTH)]; // Month : Января case 'Y' : return get(YEAR); // Year : 2014 case 'YY' : return lz(get(YEAR) % 100); // Year : 14 } return part; }); } } function lz(num){ return num > 9 ? num : '0' + num; } function addLocale(lang, locale){ function split(index){ var result = []; forEach.call(array(locale.months), function(it){ result.push(it.replace(flexioRegExp, '$' + index)); }); return result; } locales[lang] = [array(locale.weekdays), split(1), split(2)]; return core; } $define(PROTO + FORCED, DATE, { format: createFormat('get'), formatUTC: createFormat('getUTC') }); addLocale(current, { weekdays: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday', months: 'January,February,March,April,May,June,July,August,September,October,November,December' }); addLocale('ru', { weekdays: 'Воскресенье,Понедельник,Вторник,Среда,Четверг,Пятница,Суббота', months: 'Январ:я|ь,Феврал:я|ь,Март:а|,Апрел:я|ь,Ма:я|й,Июн:я|ь,' + 'Июл:я|ь,Август:а|,Сентябр:я|ь,Октябр:я|ь,Ноябр:я|ь,Декабр:я|ь' }); core.locale = function(locale){ return has(locales, locale) ? current = locale : current; }; core.addLocale = addLocale; }(/\b\w\w?\b/g, /:(.*)\|(.*)$/, {}, 'en', 'Seconds', 'Minutes', 'Hours', 'Month', 'FullYear'); /****************************************************************************** * Module : console * ******************************************************************************/ !function(console, enabled){ var _console = { enable: function(){ enabled = true }, disable: function(){ enabled = false } }; // Methods from: // https://github.com/DeveloperToolsWG/console-object/blob/master/api.md // https://developer.mozilla.org/en-US/docs/Web/API/console forEach.call(array('assert,clear,count,debug,dir,dirxml,error,exception,group,' + 'groupCollapsed,groupEnd,info,isIndependentlyComposed,log,markTimeline,profile,' + 'profileEnd,table,time,timeEnd,timeline,timelineEnd,timeStamp,trace,warn'), function(key){ var fn = console[key]; _console[key] = function(){ if(enabled && fn)return apply.call(fn, console, arguments); }; } ); // console methods in some browsers are not configurable try { framework && delete global.console; } catch(e){} $define(GLOBAL + FORCED, {console: _console}); }(global.console || {}, true); }(Function('return this'), true);
ajax/libs/analytics.js/2.3.5/analytics.min.js
magoni/cdnjs
(function outer(modules,cache,entries){var global=function(){return this}();function require(name,jumped){if(cache[name])return cache[name].exports;if(modules[name])return call(name,require);throw new Error('cannot find module "'+name+'"')}function call(id,require){var m=cache[id]={exports:{}};var mod=modules[id];var name=mod[2];var fn=mod[0];fn.call(m.exports,function(req){var dep=modules[id][1][req];return require(dep?dep:req)},m,m.exports,outer,modules,cache,entries);if(name)cache[name]=cache[id];return cache[id].exports}for(var id in entries){if(entries[id]){global[entries[id]]=require(id)}else{require(id)}}require.duo=true;require.cache=cache;require.modules=modules;return require})({1:[function(require,module,exports){var Integrations=require("analytics.js-integrations");var Analytics=require("./analytics");var each=require("each");var analytics=module.exports=exports=new Analytics;analytics.require=require;exports.VERSION=require("./version");each(Integrations,function(name,Integration){analytics.use(Integration)})},{"./analytics":2,"./version":3,"analytics.js-integrations":4,each:5}],2:[function(require,module,exports){var after=require("after");var bind=require("bind");var callback=require("callback");var canonical=require("canonical");var clone=require("clone");var cookie=require("./cookie");var debug=require("debug");var defaults=require("defaults");var each=require("each");var Emitter=require("emitter");var group=require("./group");var is=require("is");var isEmail=require("is-email");var isMeta=require("is-meta");var newDate=require("new-date");var on=require("event").bind;var prevent=require("prevent");var querystring=require("querystring");var size=require("object").length;var store=require("./store");var url=require("url");var user=require("./user");var Facade=require("facade");var Identify=Facade.Identify;var Group=Facade.Group;var Alias=Facade.Alias;var Track=Facade.Track;var Page=Facade.Page;exports=module.exports=Analytics;exports.cookie=cookie;exports.store=store;function Analytics(){this.Integrations={};this._integrations={};this._readied=false;this._timeout=300;this._user=user;bind.all(this);var self=this;this.on("initialize",function(settings,options){if(options.initialPageview)self.page()});this.on("initialize",function(){self._parseQuery()})}Emitter(Analytics.prototype);Analytics.prototype.use=function(plugin){plugin(this);return this};Analytics.prototype.addIntegration=function(Integration){var name=Integration.prototype.name;if(!name)throw new TypeError("attempted to add an invalid integration");this.Integrations[name]=Integration;return this};Analytics.prototype.init=Analytics.prototype.initialize=function(settings,options){settings=settings||{};options=options||{};this._options(options);this._readied=false;var self=this;each(settings,function(name){var Integration=self.Integrations[name];if(!Integration)delete settings[name]});each(settings,function(name,opts){var Integration=self.Integrations[name];var integration=new Integration(clone(opts));self.add(integration)});var integrations=this._integrations;user.load();group.load();var ready=after(size(integrations),function(){self._readied=true;self.emit("ready")});each(integrations,function(name,integration){if(options.initialPageview&&integration.options.initialPageview===false){integration.page=after(2,integration.page)}integration.analytics=self;integration.once("ready",ready);integration.initialize()});this.initialized=true;this.emit("initialize",settings,options);return this};Analytics.prototype.add=function(integration){this._integrations[integration.name]=integration;return this};Analytics.prototype.identify=function(id,traits,options,fn){if(is.fn(options))fn=options,options=null;if(is.fn(traits))fn=traits,options=null,traits=null;if(is.object(id))options=traits,traits=id,id=user.id();user.identify(id,traits);id=user.id();traits=user.traits();this._invoke("identify",new Identify({options:options,traits:traits,userId:id}));this.emit("identify",id,traits,options);this._callback(fn);return this};Analytics.prototype.user=function(){return user};Analytics.prototype.group=function(id,traits,options,fn){if(0===arguments.length)return group;if(is.fn(options))fn=options,options=null;if(is.fn(traits))fn=traits,options=null,traits=null;if(is.object(id))options=traits,traits=id,id=group.id();group.identify(id,traits);id=group.id();traits=group.traits();this._invoke("group",new Group({options:options,traits:traits,groupId:id}));this.emit("group",id,traits,options);this._callback(fn);return this};Analytics.prototype.track=function(event,properties,options,fn){if(is.fn(options))fn=options,options=null;if(is.fn(properties))fn=properties,options=null,properties=null;this._invoke("track",new Track({properties:properties,options:options,event:event}));this.emit("track",event,properties,options);this._callback(fn);return this};Analytics.prototype.trackClick=Analytics.prototype.trackLink=function(links,event,properties){if(!links)return this;if(is.element(links))links=[links];var self=this;each(links,function(el){on(el,"click",function(e){var ev=is.fn(event)?event(el):event;var props=is.fn(properties)?properties(el):properties;self.track(ev,props);if(el.href&&el.target!=="_blank"&&!isMeta(e)){prevent(e);self._callback(function(){window.location.href=el.href})}})});return this};Analytics.prototype.trackSubmit=Analytics.prototype.trackForm=function(forms,event,properties){if(!forms)return this;if(is.element(forms))forms=[forms];var self=this;each(forms,function(el){function handler(e){prevent(e);var ev=is.fn(event)?event(el):event;var props=is.fn(properties)?properties(el):properties;self.track(ev,props);self._callback(function(){el.submit()})}var $=window.jQuery||window.Zepto;if($){$(el).submit(handler)}else{on(el,"submit",handler)}});return this};Analytics.prototype.page=function(category,name,properties,options,fn){if(is.fn(options))fn=options,options=null;if(is.fn(properties))fn=properties,options=properties=null;if(is.fn(name))fn=name,options=properties=name=null;if(is.object(category))options=name,properties=category,name=category=null;if(is.object(name))options=properties,properties=name,name=null;if(is.string(category)&&!is.string(name))name=category,category=null;var defs={path:canonicalPath(),referrer:document.referrer,title:document.title,search:location.search};if(name)defs.name=name;if(category)defs.category=category;properties=clone(properties)||{};defaults(properties,defs);properties.url=properties.url||canonicalUrl(properties.search);this._invoke("page",new Page({properties:properties,category:category,options:options,name:name}));this.emit("page",category,name,properties,options);this._callback(fn);return this};Analytics.prototype.pageview=function(url,options){var properties={};if(url)properties.path=url;this.page(properties);return this};Analytics.prototype.alias=function(to,from,options,fn){if(is.fn(options))fn=options,options=null;if(is.fn(from))fn=from,options=null,from=null;if(is.object(from))options=from,from=null;this._invoke("alias",new Alias({options:options,from:from,to:to}));this.emit("alias",to,from,options);this._callback(fn);return this};Analytics.prototype.ready=function(fn){if(!is.fn(fn))return this;this._readied?callback.async(fn):this.once("ready",fn);return this};Analytics.prototype.timeout=function(timeout){this._timeout=timeout};Analytics.prototype.debug=function(str){if(0==arguments.length||str){debug.enable("analytics:"+(str||"*"))}else{debug.disable()}};Analytics.prototype._options=function(options){options=options||{};cookie.options(options.cookie);store.options(options.localStorage);user.options(options.user);group.options(options.group);return this};Analytics.prototype._callback=function(fn){callback.async(fn,this._timeout);return this};Analytics.prototype._invoke=function(method,facade){var options=facade.options();this.emit("invoke",facade);each(this._integrations,function(name,integration){if(!facade.enabled(name))return;integration.invoke.call(integration,method,facade)});return this};Analytics.prototype.push=function(args){var method=args.shift();if(!this[method])return;this[method].apply(this,args)};Analytics.prototype._parseQuery=function(){var q=querystring.parse(window.location.search);if(q.ajs_uid)this.identify(q.ajs_uid);if(q.ajs_event)this.track(q.ajs_event);return this};function canonicalPath(){var canon=canonical();if(!canon)return window.location.pathname;var parsed=url.parse(canon);return parsed.pathname}function canonicalUrl(search){var canon=canonical();if(canon)return~canon.indexOf("?")?canon:canon+search;var url=window.location.href;var i=url.indexOf("#");return-1==i?url:url.slice(0,i)}},{"./cookie":6,"./group":7,"./store":8,"./user":9,after:10,bind:11,callback:12,canonical:13,clone:14,debug:15,defaults:16,each:5,emitter:17,is:18,"is-email":19,"is-meta":20,"new-date":21,event:22,prevent:23,querystring:24,object:25,url:26,facade:27}],6:[function(require,module,exports){var debug=require("debug")("analytics.js:cookie");var bind=require("bind");var cookie=require("cookie");var clone=require("clone");var defaults=require("defaults");var json=require("json");var topDomain=require("top-domain");function Cookie(options){this.options(options)}Cookie.prototype.options=function(options){if(arguments.length===0)return this._options;options=options||{};var domain="."+topDomain(window.location.href);this._options=defaults(options,{maxage:31536e6,path:"/",domain:domain});this.set("ajs:test",true);if(!this.get("ajs:test")){debug("fallback to domain=null");this._options.domain=null}this.remove("ajs:test")};Cookie.prototype.set=function(key,value){try{value=json.stringify(value);cookie(key,value,clone(this._options));return true}catch(e){return false}};Cookie.prototype.get=function(key){try{var value=cookie(key);value=value?json.parse(value):null;return value}catch(e){return null}};Cookie.prototype.remove=function(key){try{cookie(key,null,clone(this._options));return true}catch(e){return false}};module.exports=bind.all(new Cookie);module.exports.Cookie=Cookie},{debug:15,bind:11,cookie:28,clone:14,defaults:16,json:29,"top-domain":30}],15:[function(require,module,exports){if("undefined"==typeof window){module.exports=require("./lib/debug")}else{module.exports=require("./debug")}},{"./lib/debug":31,"./debug":32}],31:[function(require,module,exports){var tty=require("tty");module.exports=debug;var names=[],skips=[];(process.env.DEBUG||"").split(/[\s,]+/).forEach(function(name){name=name.replace("*",".*?");if(name[0]==="-"){skips.push(new RegExp("^"+name.substr(1)+"$"))}else{names.push(new RegExp("^"+name+"$"))}});var colors=[6,2,3,4,5,1];var prev={};var prevColor=0;var isatty=tty.isatty(2);function color(){return colors[prevColor++%colors.length]}function humanize(ms){var sec=1e3,min=60*1e3,hour=60*min;if(ms>=hour)return(ms/hour).toFixed(1)+"h";if(ms>=min)return(ms/min).toFixed(1)+"m";if(ms>=sec)return(ms/sec|0)+"s";return ms+"ms"}function debug(name){function disabled(){}disabled.enabled=false;var match=skips.some(function(re){return re.test(name)});if(match)return disabled;match=names.some(function(re){return re.test(name)});if(!match)return disabled;var c=color();function colored(fmt){fmt=coerce(fmt);var curr=new Date;var ms=curr-(prev[name]||curr);prev[name]=curr;fmt=" [9"+c+"m"+name+" "+"[3"+c+"m"+fmt+"[3"+c+"m"+" +"+humanize(ms)+"";console.error.apply(this,arguments)}function plain(fmt){fmt=coerce(fmt);fmt=(new Date).toUTCString()+" "+name+" "+fmt;console.error.apply(this,arguments)}colored.enabled=plain.enabled=true;return isatty||process.env.DEBUG_COLORS?colored:plain}function coerce(val){if(val instanceof Error)return val.stack||val.message;return val}},{}],32:[function(require,module,exports){module.exports=debug;function debug(name){if(!debug.enabled(name))return function(){};return function(fmt){fmt=coerce(fmt);var curr=new Date;var ms=curr-(debug[name]||curr);debug[name]=curr;fmt=name+" "+fmt+" +"+debug.humanize(ms);window.console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}}debug.names=[];debug.skips=[];debug.enable=function(name){try{localStorage.debug=name}catch(e){}var split=(name||"").split(/[\s,]+/),len=split.length;for(var i=0;i<len;i++){name=split[i].replace("*",".*?");if(name[0]==="-"){debug.skips.push(new RegExp("^"+name.substr(1)+"$"))}else{debug.names.push(new RegExp("^"+name+"$"))}}};debug.disable=function(){debug.enable("")};debug.humanize=function(ms){var sec=1e3,min=60*1e3,hour=60*min;if(ms>=hour)return(ms/hour).toFixed(1)+"h";if(ms>=min)return(ms/min).toFixed(1)+"m";if(ms>=sec)return(ms/sec|0)+"s";return ms+"ms"};debug.enabled=function(name){for(var i=0,len=debug.skips.length;i<len;i++){if(debug.skips[i].test(name)){return false}}for(var i=0,len=debug.names.length;i<len;i++){if(debug.names[i].test(name)){return true}}return false};function coerce(val){if(val instanceof Error)return val.stack||val.message;return val}try{if(window.localStorage)debug.enable(localStorage.debug)}catch(e){}},{}],11:[function(require,module,exports){try{var bind=require("bind")}catch(e){var bind=require("bind-component")}var bindAll=require("bind-all");module.exports=exports=bind;exports.all=bindAll;exports.methods=bindMethods;function bindMethods(obj,methods){methods=[].slice.call(arguments,1);for(var i=0,method;method=methods[i];i++){obj[method]=bind(obj,obj[method])}return obj}},{bind:33,"bind-all":34}],33:[function(require,module,exports){var slice=[].slice;module.exports=function(obj,fn){if("string"==typeof fn)fn=obj[fn];if("function"!=typeof fn)throw new Error("bind() requires a function");var args=slice.call(arguments,2);return function(){return fn.apply(obj,args.concat(slice.call(arguments)))}}},{}],34:[function(require,module,exports){try{var bind=require("bind");var type=require("type")}catch(e){var bind=require("bind-component");var type=require("type-component")}module.exports=function(obj){for(var key in obj){var val=obj[key];if(type(val)==="function")obj[key]=bind(obj,obj[key])}return obj}},{bind:33,type:35}],35:[function(require,module,exports){var toString=Object.prototype.toString;module.exports=function(val){switch(toString.call(val)){case"[object Function]":return"function";case"[object Date]":return"date";case"[object RegExp]":return"regexp";case"[object Arguments]":return"arguments";case"[object Array]":return"array";case"[object String]":return"string"}if(val===null)return"null";if(val===undefined)return"undefined";if(val&&val.nodeType===1)return"element";if(val===Object(val))return"object";return typeof val}},{}],28:[function(require,module,exports){var encode=encodeURIComponent;var decode=decodeURIComponent;module.exports=function(name,value,options){switch(arguments.length){case 3:case 2:return set(name,value,options);case 1:return get(name);default:return all()}};function set(name,value,options){options=options||{};var str=encode(name)+"="+encode(value);if(null==value)options.maxage=-1;if(options.maxage){options.expires=new Date(+new Date+options.maxage)}if(options.path)str+="; path="+options.path;if(options.domain)str+="; domain="+options.domain;if(options.expires)str+="; expires="+options.expires.toGMTString();if(options.secure)str+="; secure";document.cookie=str}function all(){return parse(document.cookie)}function get(name){return all()[name]}function parse(str){var obj={};var pairs=str.split(/ *; */);var pair;if(""==pairs[0])return obj;for(var i=0;i<pairs.length;++i){pair=pairs[i].split("=");obj[decode(pair[0])]=decode(pair[1])}return obj}},{}],14:[function(require,module,exports){var type;try{type=require("type")}catch(e){type=require("type-component")}module.exports=clone;function clone(obj){switch(type(obj)){case"object":var copy={};for(var key in obj){if(obj.hasOwnProperty(key)){copy[key]=clone(obj[key])}}return copy;case"array":var copy=new Array(obj.length);for(var i=0,l=obj.length;i<l;i++){copy[i]=clone(obj[i])}return copy;case"regexp":var flags="";flags+=obj.multiline?"m":"";flags+=obj.global?"g":"";flags+=obj.ignoreCase?"i":"";return new RegExp(obj.source,flags);case"date":return new Date(obj.getTime());default:return obj}}},{type:35}],16:[function(require,module,exports){"use strict";var defaults=function(dest,src,recursive){for(var prop in src){if(recursive&&dest[prop]instanceof Object&&src[prop]instanceof Object){dest[prop]=defaults(dest[prop],src[prop],true)}else if(!(prop in dest)){dest[prop]=src[prop]}}return dest};module.exports=defaults},{}],29:[function(require,module,exports){var json=window.JSON||{};var stringify=json.stringify;var parse=json.parse;module.exports=parse&&stringify?JSON:require("json-fallback")},{"json-fallback":36}],36:[function(require,module,exports){(function(){"use strict";var JSON=module.exports={};function f(n){return n<10?"0"+n:n}if(typeof Date.prototype.toJSON!=="function"){Date.prototype.toJSON=function(){return isFinite(this.valueOf())?this.getUTCFullYear()+"-"+f(this.getUTCMonth()+1)+"-"+f(this.getUTCDate())+"T"+f(this.getUTCHours())+":"+f(this.getUTCMinutes())+":"+f(this.getUTCSeconds())+"Z":null};String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(){return this.valueOf()}}var cx,escapable,gap,indent,meta,rep;function quote(string){escapable.lastIndex=0;return escapable.test(string)?'"'+string.replace(escapable,function(a){var c=meta[a];return typeof c==="string"?c:"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+string+'"'}function str(key,holder){var i,k,v,length,mind=gap,partial,value=holder[key];if(value&&typeof value==="object"&&typeof value.toJSON==="function"){value=value.toJSON(key)}if(typeof rep==="function"){value=rep.call(holder,key,value)}switch(typeof value){case"string":return quote(value);case"number":return isFinite(value)?String(value):"null";case"boolean":case"null":return String(value);case"object":if(!value){return"null"}gap+=indent;partial=[];if(Object.prototype.toString.apply(value)==="[object Array]"){length=value.length;for(i=0;i<length;i+=1){partial[i]=str(i,value)||"null"}v=partial.length===0?"[]":gap?"[\n"+gap+partial.join(",\n"+gap)+"\n"+mind+"]":"["+partial.join(",")+"]";gap=mind;return v}if(rep&&typeof rep==="object"){length=rep.length;for(i=0;i<length;i+=1){if(typeof rep[i]==="string"){k=rep[i];v=str(k,value);if(v){partial.push(quote(k)+(gap?": ":":")+v)}}}}else{for(k in value){if(Object.prototype.hasOwnProperty.call(value,k)){v=str(k,value);if(v){partial.push(quote(k)+(gap?": ":":")+v)}}}}v=partial.length===0?"{}":gap?"{\n"+gap+partial.join(",\n"+gap)+"\n"+mind+"}":"{"+partial.join(",")+"}";gap=mind;return v}}if(typeof JSON.stringify!=="function"){escapable=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;meta={"\b":"\\b"," ":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"};JSON.stringify=function(value,replacer,space){var i;gap="";indent="";if(typeof space==="number"){for(i=0;i<space;i+=1){indent+=" "}}else if(typeof space==="string"){indent=space}rep=replacer;if(replacer&&typeof replacer!=="function"&&(typeof replacer!=="object"||typeof replacer.length!=="number")){throw new Error("JSON.stringify")}return str("",{"":value})}}if(typeof JSON.parse!=="function"){cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;JSON.parse=function(text,reviver){var j;function walk(holder,key){var k,v,value=holder[key];if(value&&typeof value==="object"){for(k in value){if(Object.prototype.hasOwnProperty.call(value,k)){v=walk(value,k);if(v!==undefined){value[k]=v}else{delete value[k]}}}}return reviver.call(holder,key,value)}text=String(text);cx.lastIndex=0;if(cx.test(text)){text=text.replace(cx,function(a){return"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)})}if(/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,""))){j=eval("("+text+")");return typeof reviver==="function"?walk({"":j},""):j}throw new SyntaxError("JSON.parse")}}})()},{}],30:[function(require,module,exports){var parse=require("url").parse;module.exports=domain;var regexp=/[a-z0-9][a-z0-9\-]*[a-z0-9]\.[a-z\.]{2,6}$/i;function domain(url){var host=parse(url).hostname;var match=host.match(regexp);return match?match[0]:""}},{url:26}],26:[function(require,module,exports){exports.parse=function(url){var a=document.createElement("a");a.href=url;return{href:a.href,host:a.host,port:a.port,hash:a.hash,hostname:a.hostname,pathname:a.pathname,protocol:a.protocol,search:a.search,query:a.search.slice(1)}};exports.isAbsolute=function(url){if(0==url.indexOf("//"))return true;if(~url.indexOf("://"))return true;return false};exports.isRelative=function(url){return!exports.isAbsolute(url)};exports.isCrossDomain=function(url){url=exports.parse(url);return url.hostname!=location.hostname||url.port!=location.port||url.protocol!=location.protocol}},{}],7:[function(require,module,exports){var debug=require("debug")("analytics:group");var Entity=require("./entity");var inherit=require("inherit");var bind=require("bind");Group.defaults={persist:true,cookie:{key:"ajs_group_id"},localStorage:{key:"ajs_group_properties"}};function Group(options){this.defaults=Group.defaults;this.debug=debug;Entity.call(this,options)}inherit(Group,Entity);module.exports=bind.all(new Group);module.exports.Group=Group},{"./entity":37,debug:15,inherit:38,bind:11}],37:[function(require,module,exports){var traverse=require("isodate-traverse");var defaults=require("defaults");var cookie=require("./cookie");var store=require("./store");var extend=require("extend");var clone=require("clone");module.exports=Entity;function Entity(options){this.options(options)}Entity.prototype.options=function(options){if(arguments.length===0)return this._options;options||(options={});defaults(options,this.defaults||{});this._options=options};Entity.prototype.id=function(id){switch(arguments.length){case 0:return this._getId();case 1:return this._setId(id)}};Entity.prototype._getId=function(){var ret=this._options.persist?cookie.get(this._options.cookie.key):this._id;return ret===undefined?null:ret};Entity.prototype._setId=function(id){if(this._options.persist){cookie.set(this._options.cookie.key,id)}else{this._id=id}};Entity.prototype.properties=Entity.prototype.traits=function(traits){switch(arguments.length){case 0:return this._getTraits();case 1:return this._setTraits(traits)}};Entity.prototype._getTraits=function(){var ret=this._options.persist?store.get(this._options.localStorage.key):this._traits;return ret?traverse(clone(ret)):{}};Entity.prototype._setTraits=function(traits){traits||(traits={});if(this._options.persist){store.set(this._options.localStorage.key,traits)}else{this._traits=traits}};Entity.prototype.identify=function(id,traits){traits||(traits={});var current=this.id();if(current===null||current===id)traits=extend(this.traits(),traits);if(id)this.id(id);this.debug("identify %o, %o",id,traits);this.traits(traits);this.save()};Entity.prototype.save=function(){if(!this._options.persist)return false;cookie.set(this._options.cookie.key,this.id());store.set(this._options.localStorage.key,this.traits());return true};Entity.prototype.logout=function(){this.id(null);this.traits({});cookie.remove(this._options.cookie.key);store.remove(this._options.localStorage.key)};Entity.prototype.reset=function(){this.logout();this.options({})};Entity.prototype.load=function(){this.id(cookie.get(this._options.cookie.key));this.traits(store.get(this._options.localStorage.key))}},{"./cookie":6,"./store":8,"isodate-traverse":39,defaults:16,extend:40,clone:14}],8:[function(require,module,exports){var bind=require("bind");var defaults=require("defaults");var store=require("store.js");function Store(options){this.options(options)}Store.prototype.options=function(options){if(arguments.length===0)return this._options;options=options||{};defaults(options,{enabled:true});this.enabled=options.enabled&&store.enabled;this._options=options};Store.prototype.set=function(key,value){if(!this.enabled)return false;return store.set(key,value)};Store.prototype.get=function(key){if(!this.enabled)return null;return store.get(key)};Store.prototype.remove=function(key){if(!this.enabled)return false;return store.remove(key)};module.exports=bind.all(new Store);module.exports.Store=Store},{bind:11,defaults:16,"store.js":41}],41:[function(require,module,exports){var json=require("json"),store={},win=window,doc=win.document,localStorageName="localStorage",namespace="__storejs__",storage;store.disabled=false;store.set=function(key,value){};store.get=function(key){};store.remove=function(key){};store.clear=function(){};store.transact=function(key,defaultVal,transactionFn){var val=store.get(key);if(transactionFn==null){transactionFn=defaultVal;defaultVal=null}if(typeof val=="undefined"){val=defaultVal||{}}transactionFn(val);store.set(key,val)};store.getAll=function(){};store.serialize=function(value){return json.stringify(value)};store.deserialize=function(value){if(typeof value!="string"){return undefined}try{return json.parse(value)}catch(e){return value||undefined}};function isLocalStorageNameSupported(){try{return localStorageName in win&&win[localStorageName]}catch(err){return false}}if(isLocalStorageNameSupported()){storage=win[localStorageName];store.set=function(key,val){if(val===undefined){return store.remove(key)}storage.setItem(key,store.serialize(val));return val};store.get=function(key){return store.deserialize(storage.getItem(key))};store.remove=function(key){storage.removeItem(key)};store.clear=function(){storage.clear()};store.getAll=function(){var ret={};for(var i=0;i<storage.length;++i){var key=storage.key(i);ret[key]=store.get(key)}return ret}}else if(doc.documentElement.addBehavior){var storageOwner,storageContainer;try{storageContainer=new ActiveXObject("htmlfile");storageContainer.open();storageContainer.write("<s"+"cript>document.w=window</s"+'cript><iframe src="/favicon.ico"></iframe>');storageContainer.close();storageOwner=storageContainer.w.frames[0].document;storage=storageOwner.createElement("div")}catch(e){storage=doc.createElement("div");storageOwner=doc.body}function withIEStorage(storeFunction){return function(){var args=Array.prototype.slice.call(arguments,0);args.unshift(storage);storageOwner.appendChild(storage);storage.addBehavior("#default#userData");storage.load(localStorageName);var result=storeFunction.apply(store,args);storageOwner.removeChild(storage);return result}}var forbiddenCharsRegex=new RegExp("[!\"#$%&'()*+,/\\\\:;<=>?@[\\]^`{|}~]","g");function ieKeyFix(key){return key.replace(forbiddenCharsRegex,"___")}store.set=withIEStorage(function(storage,key,val){key=ieKeyFix(key);if(val===undefined){return store.remove(key)}storage.setAttribute(key,store.serialize(val));storage.save(localStorageName);return val});store.get=withIEStorage(function(storage,key){key=ieKeyFix(key);return store.deserialize(storage.getAttribute(key))});store.remove=withIEStorage(function(storage,key){key=ieKeyFix(key);storage.removeAttribute(key);storage.save(localStorageName)});store.clear=withIEStorage(function(storage){var attributes=storage.XMLDocument.documentElement.attributes;storage.load(localStorageName);for(var i=0,attr;attr=attributes[i];i++){storage.removeAttribute(attr.name)}storage.save(localStorageName)});store.getAll=withIEStorage(function(storage){var attributes=storage.XMLDocument.documentElement.attributes;var ret={};for(var i=0,attr;attr=attributes[i];++i){var key=ieKeyFix(attr.name);ret[attr.name]=store.deserialize(storage.getAttribute(key))}return ret})}try{store.set(namespace,namespace);if(store.get(namespace)!=namespace){store.disabled=true}store.remove(namespace)}catch(e){store.disabled=true}store.enabled=!store.disabled;module.exports=store},{json:29}],39:[function(require,module,exports){var is=require("is");var isodate=require("isodate");var each;try{each=require("each")}catch(err){each=require("each-component")}module.exports=traverse;function traverse(input,strict){if(strict===undefined)strict=true;if(is.object(input))return object(input,strict);if(is.array(input))return array(input,strict);return input}function object(obj,strict){each(obj,function(key,val){if(isodate.is(val,strict)){obj[key]=isodate.parse(val)}else if(is.object(val)||is.array(val)){traverse(val,strict)}});return obj}function array(arr,strict){each(arr,function(val,x){if(is.object(val)){traverse(val,strict)}else if(isodate.is(val,strict)){arr[x]=isodate.parse(val)}});return arr}},{is:42,isodate:43,each:5}],42:[function(require,module,exports){var isEmpty=require("is-empty");try{var typeOf=require("type")}catch(e){var typeOf=require("component-type")}var types=["arguments","array","boolean","date","element","function","null","number","object","regexp","string","undefined"];for(var i=0,type;type=types[i];i++)exports[type]=generate(type);exports.fn=exports["function"];exports.empty=isEmpty;exports.nan=function(val){return exports.number(val)&&val!=val};function generate(type){return function(value){return type===typeOf(value)}}},{"is-empty":44,type:35,"component-type":35}],44:[function(require,module,exports){module.exports=isEmpty;var has=Object.prototype.hasOwnProperty;function isEmpty(val){if(null==val)return true;if("number"==typeof val)return 0===val;if(undefined!==val.length)return 0===val.length;for(var key in val)if(has.call(val,key))return false;return true}},{}],43:[function(require,module,exports){var matcher=/^(\d{4})(?:-?(\d{2})(?:-?(\d{2}))?)?(?:([ T])(\d{2}):?(\d{2})(?::?(\d{2})(?:[,\.](\d{1,}))?)?(?:(Z)|([+\-])(\d{2})(?::?(\d{2}))?)?)?$/;exports.parse=function(iso){var numericKeys=[1,5,6,7,11,12];var arr=matcher.exec(iso);var offset=0;if(!arr)return new Date(iso);for(var i=0,val;val=numericKeys[i];i++){arr[val]=parseInt(arr[val],10)||0}arr[2]=parseInt(arr[2],10)||1;arr[3]=parseInt(arr[3],10)||1;arr[2]--;arr[8]=arr[8]?(arr[8]+"00").substring(0,3):0;if(arr[4]==" "){offset=(new Date).getTimezoneOffset()}else if(arr[9]!=="Z"&&arr[10]){offset=arr[11]*60+arr[12];if("+"==arr[10])offset=0-offset}var millis=Date.UTC(arr[1],arr[2],arr[3],arr[5],arr[6]+offset,arr[7],arr[8]);return new Date(millis)};exports.is=function(string,strict){if(strict&&false===/^\d{4}-\d{2}-\d{2}/.test(string))return false;return matcher.test(string)}},{}],5:[function(require,module,exports){var type=require("type");var has=Object.prototype.hasOwnProperty;module.exports=function(obj,fn){switch(type(obj)){case"array":return array(obj,fn);case"object":if("number"==typeof obj.length)return array(obj,fn);return object(obj,fn);case"string":return string(obj,fn)}};function string(obj,fn){for(var i=0;i<obj.length;++i){fn(obj.charAt(i),i)}}function object(obj,fn){for(var key in obj){if(has.call(obj,key)){fn(key,obj[key])}}}function array(obj,fn){for(var i=0;i<obj.length;++i){fn(obj[i],i)}}},{type:35}],40:[function(require,module,exports){module.exports=function extend(object){var args=Array.prototype.slice.call(arguments,1);for(var i=0,source;source=args[i];i++){if(!source)continue;for(var property in source){object[property]=source[property]}}return object}},{}],38:[function(require,module,exports){module.exports=function(a,b){var fn=function(){};fn.prototype=b.prototype;a.prototype=new fn;a.prototype.constructor=a}},{}],9:[function(require,module,exports){var debug=require("debug")("analytics:user");var Entity=require("./entity");var inherit=require("inherit");var bind=require("bind");var cookie=require("./cookie");User.defaults={persist:true,cookie:{key:"ajs_user_id",oldKey:"ajs_user"},localStorage:{key:"ajs_user_traits"}};function User(options){this.defaults=User.defaults;this.debug=debug;Entity.call(this,options)}inherit(User,Entity);User.prototype.load=function(){if(this._loadOldCookie())return;Entity.prototype.load.call(this)};User.prototype._loadOldCookie=function(){var user=cookie.get(this._options.cookie.oldKey);if(!user)return false;this.id(user.id);this.traits(user.traits); cookie.remove(this._options.cookie.oldKey);return true};module.exports=bind.all(new User);module.exports.User=User},{"./entity":37,"./cookie":6,debug:15,inherit:38,bind:11}],10:[function(require,module,exports){module.exports=function after(times,func){if(times<=0)return func();return function(){if(--times<1){return func.apply(this,arguments)}}}},{}],12:[function(require,module,exports){var next=require("next-tick");module.exports=callback;function callback(fn){if("function"===typeof fn)fn()}callback.async=function(fn,wait){if("function"!==typeof fn)return;if(!wait)return next(fn);setTimeout(fn,wait)};callback.sync=callback},{"next-tick":45}],45:[function(require,module,exports){"use strict";if(typeof setImmediate=="function"){module.exports=function(f){setImmediate(f)}}else if(typeof process!="undefined"&&typeof process.nextTick=="function"){module.exports=process.nextTick}else if(typeof window=="undefined"||window.ActiveXObject||!window.postMessage){module.exports=function(f){setTimeout(f)}}else{var q=[];window.addEventListener("message",function(){var i=0;while(i<q.length){try{q[i++]()}catch(e){q=q.slice(i);window.postMessage("tic!","*");throw e}}q.length=0},true);module.exports=function(fn){if(!q.length)window.postMessage("tic!","*");q.push(fn)}}},{}],13:[function(require,module,exports){module.exports=function canonical(){var tags=document.getElementsByTagName("link");for(var i=0,tag;tag=tags[i];i++){if("canonical"==tag.getAttribute("rel"))return tag.getAttribute("href")}}},{}],17:[function(require,module,exports){var index=require("indexof");module.exports=Emitter;function Emitter(obj){if(obj)return mixin(obj)}function mixin(obj){for(var key in Emitter.prototype){obj[key]=Emitter.prototype[key]}return obj}Emitter.prototype.on=Emitter.prototype.addEventListener=function(event,fn){this._callbacks=this._callbacks||{};(this._callbacks[event]=this._callbacks[event]||[]).push(fn);return this};Emitter.prototype.once=function(event,fn){var self=this;this._callbacks=this._callbacks||{};function on(){self.off(event,on);fn.apply(this,arguments)}fn._off=on;this.on(event,on);return this};Emitter.prototype.off=Emitter.prototype.removeListener=Emitter.prototype.removeAllListeners=Emitter.prototype.removeEventListener=function(event,fn){this._callbacks=this._callbacks||{};if(0==arguments.length){this._callbacks={};return this}var callbacks=this._callbacks[event];if(!callbacks)return this;if(1==arguments.length){delete this._callbacks[event];return this}var i=index(callbacks,fn._off||fn);if(~i)callbacks.splice(i,1);return this};Emitter.prototype.emit=function(event){this._callbacks=this._callbacks||{};var args=[].slice.call(arguments,1),callbacks=this._callbacks[event];if(callbacks){callbacks=callbacks.slice(0);for(var i=0,len=callbacks.length;i<len;++i){callbacks[i].apply(this,args)}}return this};Emitter.prototype.listeners=function(event){this._callbacks=this._callbacks||{};return this._callbacks[event]||[]};Emitter.prototype.hasListeners=function(event){return!!this.listeners(event).length}},{indexof:46}],46:[function(require,module,exports){module.exports=function(arr,obj){if(arr.indexOf)return arr.indexOf(obj);for(var i=0;i<arr.length;++i){if(arr[i]===obj)return i}return-1}},{}],18:[function(require,module,exports){var isEmpty=require("is-empty");try{var typeOf=require("type")}catch(e){var typeOf=require("component-type")}var types=["arguments","array","boolean","date","element","function","null","number","object","regexp","string","undefined"];for(var i=0,type;type=types[i];i++)exports[type]=generate(type);exports.fn=exports["function"];exports.empty=isEmpty;exports.nan=function(val){return exports.number(val)&&val!=val};function generate(type){return function(value){return type===typeOf(value)}}},{"is-empty":44,type:35,"component-type":35}],19:[function(require,module,exports){module.exports=isEmail;var matcher=/.+\@.+\..+/;function isEmail(string){return matcher.test(string)}},{}],20:[function(require,module,exports){module.exports=function isMeta(e){if(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)return true;var which=e.which,button=e.button;if(!which&&button!==undefined){return!button&1&&!button&2&&button&4}else if(which===2){return true}return false}},{}],21:[function(require,module,exports){var is=require("is");var isodate=require("isodate");var milliseconds=require("./milliseconds");var seconds=require("./seconds");module.exports=function newDate(val){if(is.date(val))return val;if(is.number(val))return new Date(toMs(val));if(isodate.is(val))return isodate.parse(val);if(milliseconds.is(val))return milliseconds.parse(val);if(seconds.is(val))return seconds.parse(val);return new Date(val)};function toMs(num){if(num<315576e5)return num*1e3;return num}},{"./milliseconds":47,"./seconds":48,is:49,isodate:43}],47:[function(require,module,exports){var matcher=/\d{13}/;exports.is=function(string){return matcher.test(string)};exports.parse=function(millis){millis=parseInt(millis,10);return new Date(millis)}},{}],48:[function(require,module,exports){var matcher=/\d{10}/;exports.is=function(string){return matcher.test(string)};exports.parse=function(seconds){var millis=parseInt(seconds,10)*1e3;return new Date(millis)}},{}],49:[function(require,module,exports){var isEmpty=require("is-empty"),typeOf=require("type");var types=["arguments","array","boolean","date","element","function","null","number","object","regexp","string","undefined"];for(var i=0,type;type=types[i];i++)exports[type]=generate(type);exports.fn=exports["function"];exports.empty=isEmpty;exports.nan=function(val){return exports.number(val)&&val!=val};function generate(type){return function(value){return type===typeOf(value)}}},{"is-empty":44,type:35}],22:[function(require,module,exports){exports.bind=function(el,type,fn,capture){if(el.addEventListener){el.addEventListener(type,fn,capture||false)}else{el.attachEvent("on"+type,fn)}return fn};exports.unbind=function(el,type,fn,capture){if(el.removeEventListener){el.removeEventListener(type,fn,capture||false)}else{el.detachEvent("on"+type,fn)}return fn}},{}],23:[function(require,module,exports){module.exports=function(e){e=e||window.event;return e.preventDefault?e.preventDefault():e.returnValue=false}},{}],24:[function(require,module,exports){var encode=encodeURIComponent;var decode=decodeURIComponent;var trim=require("trim");var type=require("type");exports.parse=function(str){if("string"!=typeof str)return{};str=trim(str);if(""==str)return{};if("?"==str.charAt(0))str=str.slice(1);var obj={};var pairs=str.split("&");for(var i=0;i<pairs.length;i++){var parts=pairs[i].split("=");var key=decode(parts[0]);var m;if(m=/(\w+)\[(\d+)\]/.exec(key)){obj[m[1]]=obj[m[1]]||[];obj[m[1]][m[2]]=decode(parts[1]);continue}obj[parts[0]]=null==parts[1]?"":decode(parts[1])}return obj};exports.stringify=function(obj){if(!obj)return"";var pairs=[];for(var key in obj){var value=obj[key];if("array"==type(value)){for(var i=0;i<value.length;++i){pairs.push(encode(key+"["+i+"]")+"="+encode(value[i]))}continue}pairs.push(encode(key)+"="+encode(obj[key]))}return pairs.join("&")}},{trim:50,type:35}],50:[function(require,module,exports){exports=module.exports=trim;function trim(str){if(str.trim)return str.trim();return str.replace(/^\s*|\s*$/g,"")}exports.left=function(str){if(str.trimLeft)return str.trimLeft();return str.replace(/^\s*/,"")};exports.right=function(str){if(str.trimRight)return str.trimRight();return str.replace(/\s*$/,"")}},{}],25:[function(require,module,exports){var has=Object.prototype.hasOwnProperty;exports.keys=Object.keys||function(obj){var keys=[];for(var key in obj){if(has.call(obj,key)){keys.push(key)}}return keys};exports.values=function(obj){var vals=[];for(var key in obj){if(has.call(obj,key)){vals.push(obj[key])}}return vals};exports.merge=function(a,b){for(var key in b){if(has.call(b,key)){a[key]=b[key]}}return a};exports.length=function(obj){return exports.keys(obj).length};exports.isEmpty=function(obj){return 0==exports.length(obj)}},{}],27:[function(require,module,exports){var Facade=require("./facade");module.exports=Facade;Facade.Alias=require("./alias");Facade.Group=require("./group");Facade.Identify=require("./identify");Facade.Track=require("./track");Facade.Page=require("./page");Facade.Screen=require("./screen")},{"./facade":51,"./alias":52,"./group":53,"./identify":54,"./track":55,"./page":56,"./screen":57}],51:[function(require,module,exports){var clone=require("./utils").clone;var isEnabled=require("./is-enabled");var objCase=require("obj-case");var traverse=require("isodate-traverse");var newDate=require("new-date");module.exports=Facade;function Facade(obj){if(!obj.hasOwnProperty("timestamp"))obj.timestamp=new Date;else obj.timestamp=newDate(obj.timestamp);this.obj=obj}Facade.prototype.proxy=function(field){var fields=field.split(".");field=fields.shift();var obj=this[field]||this.field(field);if(!obj)return obj;if(typeof obj==="function")obj=obj.call(this)||{};if(fields.length===0)return transform(obj);obj=objCase(obj,fields.join("."));return transform(obj)};Facade.prototype.field=function(field){var obj=this.obj[field];return transform(obj)};Facade.proxy=function(field){return function(){return this.proxy(field)}};Facade.field=function(field){return function(){return this.field(field)}};Facade.prototype.json=function(){var ret=clone(this.obj);if(this.type)ret.type=this.type();return ret};Facade.prototype.context=Facade.prototype.options=function(integration){var options=clone(this.obj.options||this.obj.context)||{};if(!integration)return clone(options);if(!this.enabled(integration))return;var integrations=this.integrations();var value=integrations[integration]||objCase(integrations,integration);if("boolean"==typeof value)value={};return value||{}};Facade.prototype.enabled=function(integration){var allEnabled=this.proxy("options.providers.all");if(typeof allEnabled!=="boolean")allEnabled=this.proxy("options.all");if(typeof allEnabled!=="boolean")allEnabled=this.proxy("integrations.all");if(typeof allEnabled!=="boolean")allEnabled=true;var enabled=allEnabled&&isEnabled(integration);var options=this.integrations();if(options.providers&&options.providers.hasOwnProperty(integration)){enabled=options.providers[integration]}if(options.hasOwnProperty(integration)){var settings=options[integration];if(typeof settings==="boolean"){enabled=settings}else{enabled=true}}return enabled?true:false};Facade.prototype.integrations=function(){return this.obj.integrations||this.proxy("options.providers")||this.options()};Facade.prototype.active=function(){var active=this.proxy("options.active");if(active===null||active===undefined)active=true;return active};Facade.prototype.sessionId=Facade.prototype.anonymousId=function(){return this.field("anonymousId")||this.field("sessionId")};Facade.prototype.groupId=Facade.proxy("options.groupId");Facade.prototype.traits=function(aliases){var ret=this.proxy("options.traits")||{};var id=this.userId();aliases=aliases||{};if(id)ret.id=id;for(var alias in aliases){var value=null==this[alias]?this.proxy("options.traits."+alias):this[alias]();if(null==value)continue;ret[aliases[alias]]=value;delete ret[alias]}return ret};Facade.prototype.library=function(){var library=this.proxy("options.library");if(!library)return{name:"unknown",version:null};if(typeof library==="string")return{name:library,version:null};return library};Facade.prototype.userId=Facade.field("userId");Facade.prototype.channel=Facade.field("channel");Facade.prototype.timestamp=Facade.field("timestamp");Facade.prototype.userAgent=Facade.proxy("options.userAgent");Facade.prototype.ip=Facade.proxy("options.ip");function transform(obj){var cloned=clone(obj);traverse(cloned);return cloned}},{"./utils":58,"./is-enabled":59,"obj-case":60,"isodate-traverse":39,"new-date":21}],58:[function(require,module,exports){try{exports.inherit=require("inherit");exports.clone=require("clone")}catch(e){exports.inherit=require("inherit-component");exports.clone=require("clone-component")}},{inherit:61,clone:62}],61:[function(require,module,exports){module.exports=function(a,b){var fn=function(){};fn.prototype=b.prototype;a.prototype=new fn;a.prototype.constructor=a}},{}],62:[function(require,module,exports){var type;try{type=require("component-type")}catch(_){type=require("type")}module.exports=clone;function clone(obj){switch(type(obj)){case"object":var copy={};for(var key in obj){if(obj.hasOwnProperty(key)){copy[key]=clone(obj[key])}}return copy;case"array":var copy=new Array(obj.length);for(var i=0,l=obj.length;i<l;i++){copy[i]=clone(obj[i])}return copy;case"regexp":var flags="";flags+=obj.multiline?"m":"";flags+=obj.global?"g":"";flags+=obj.ignoreCase?"i":"";return new RegExp(obj.source,flags);case"date":return new Date(obj.getTime());default:return obj}}},{"component-type":35,type:35}],59:[function(require,module,exports){var disabled={Salesforce:true,Marketo:true};module.exports=function(integration){return!disabled[integration]}},{}],60:[function(require,module,exports){var Case=require("case");var identity=function(_){return _};var cases=[identity,Case.upper,Case.lower,Case.snake,Case.pascal,Case.camel,Case.constant,Case.title,Case.capital,Case.sentence];module.exports=module.exports.find=multiple(find);module.exports.replace=function(obj,key,val){multiple(replace).apply(this,arguments);return obj};module.exports.del=function(obj,key){multiple(del).apply(this,arguments);return obj};function multiple(fn){return function(obj,key,val){var keys=key.split(".");if(keys.length===0)return;while(keys.length>1){key=keys.shift();obj=find(obj,key);if(obj===null||obj===undefined)return}key=keys.shift();return fn(obj,key,val)}}function find(obj,key){for(var i=0;i<cases.length;i++){var cased=cases[i](key);if(obj.hasOwnProperty(cased))return obj[cased]}}function del(obj,key){for(var i=0;i<cases.length;i++){var cased=cases[i](key);if(obj.hasOwnProperty(cased))delete obj[cased]}return obj}function replace(obj,key,val){for(var i=0;i<cases.length;i++){var cased=cases[i](key);if(obj.hasOwnProperty(cased))obj[cased]=val}return obj}},{"case":63}],63:[function(require,module,exports){var cases=require("./cases");module.exports=exports=determineCase;function determineCase(string){for(var key in cases){if(key=="none")continue;var convert=cases[key];if(convert(string)==string)return key}return null}exports.add=function(name,convert){exports[name]=cases[name]=convert};for(var key in cases){exports.add(key,cases[key])}},{"./cases":64}],64:[function(require,module,exports){var camel=require("to-camel-case"),capital=require("to-capital-case"),constant=require("to-constant-case"),dot=require("to-dot-case"),none=require("to-no-case"),pascal=require("to-pascal-case"),sentence=require("to-sentence-case"),slug=require("to-slug-case"),snake=require("to-snake-case"),space=require("to-space-case"),title=require("to-title-case");exports.camel=camel;exports.pascal=pascal;exports.dot=dot;exports.slug=slug;exports.snake=snake;exports.space=space;exports.constant=constant;exports.capital=capital;exports.title=title;exports.sentence=sentence;exports.lower=function(string){return none(string).toLowerCase()};exports.upper=function(string){return none(string).toUpperCase()};exports.inverse=function(string){for(var i=0,char;char=string[i];i++){if(!/[a-z]/i.test(char))continue;var upper=char.toUpperCase();var lower=char.toLowerCase();string[i]=char==upper?lower:upper}return string};exports.none=none},{"to-camel-case":65,"to-capital-case":66,"to-constant-case":67,"to-dot-case":68,"to-no-case":69,"to-pascal-case":70,"to-sentence-case":71,"to-slug-case":72,"to-snake-case":73,"to-space-case":74,"to-title-case":75}],65:[function(require,module,exports){var toSpace=require("to-space-case");module.exports=toCamelCase;function toCamelCase(string){return toSpace(string).replace(/\s(\w)/g,function(matches,letter){return letter.toUpperCase()})}},{"to-space-case":74}],74:[function(require,module,exports){var clean=require("to-no-case");module.exports=toSpaceCase;function toSpaceCase(string){return clean(string).replace(/[\W_]+(.|$)/g,function(matches,match){return match?" "+match:""})}},{"to-no-case":69}],69:[function(require,module,exports){module.exports=toNoCase;var hasSpace=/\s/;var hasCamel=/[a-z][A-Z]/;var hasSeparator=/[\W_]/;function toNoCase(string){if(hasSpace.test(string))return string.toLowerCase();if(hasSeparator.test(string))string=unseparate(string);if(hasCamel.test(string))string=uncamelize(string);return string.toLowerCase()}var separatorSplitter=/[\W_]+(.|$)/g;function unseparate(string){return string.replace(separatorSplitter,function(m,next){return next?" "+next:""})}var camelSplitter=/(.)([A-Z]+)/g;function uncamelize(string){return string.replace(camelSplitter,function(m,previous,uppers){return previous+" "+uppers.toLowerCase().split("").join(" ")})}},{}],66:[function(require,module,exports){var clean=require("to-no-case");module.exports=toCapitalCase;function toCapitalCase(string){return clean(string).replace(/(^|\s)(\w)/g,function(matches,previous,letter){return previous+letter.toUpperCase()})}},{"to-no-case":69}],67:[function(require,module,exports){var snake=require("to-snake-case");module.exports=toConstantCase;function toConstantCase(string){return snake(string).toUpperCase()}},{"to-snake-case":73}],73:[function(require,module,exports){var toSpace=require("to-space-case");module.exports=toSnakeCase;function toSnakeCase(string){return toSpace(string).replace(/\s/g,"_")}},{"to-space-case":74}],68:[function(require,module,exports){var toSpace=require("to-space-case");module.exports=toDotCase;function toDotCase(string){return toSpace(string).replace(/\s/g,".")}},{"to-space-case":74}],70:[function(require,module,exports){var toSpace=require("to-space-case");module.exports=toPascalCase;function toPascalCase(string){return toSpace(string).replace(/(?:^|\s)(\w)/g,function(matches,letter){return letter.toUpperCase()})}},{"to-space-case":74}],71:[function(require,module,exports){var clean=require("to-no-case");module.exports=toSentenceCase;function toSentenceCase(string){return clean(string).replace(/[a-z]/i,function(letter){return letter.toUpperCase()})}},{"to-no-case":69}],72:[function(require,module,exports){var toSpace=require("to-space-case");module.exports=toSlugCase;function toSlugCase(string){return toSpace(string).replace(/\s/g,"-")}},{"to-space-case":74}],75:[function(require,module,exports){var capital=require("to-capital-case"),escape=require("escape-regexp"),map=require("map"),minors=require("title-case-minors");module.exports=toTitleCase;var escaped=map(minors,escape);var minorMatcher=new RegExp("[^^]\\b("+escaped.join("|")+")\\b","ig");var colonMatcher=/:\s*(\w)/g;function toTitleCase(string){return capital(string).replace(minorMatcher,function(minor){return minor.toLowerCase()}).replace(colonMatcher,function(letter){return letter.toUpperCase()})}},{"to-capital-case":66,"escape-regexp":76,map:77,"title-case-minors":78}],76:[function(require,module,exports){module.exports=function(str){return String(str).replace(/([.*+?=^!:${}()|[\]\/\\])/g,"\\$1")}},{}],77:[function(require,module,exports){var each=require("each");module.exports=function map(obj,iterator){var arr=[];each(obj,function(o){arr.push(iterator.apply(null,arguments))});return arr}},{each:79}],79:[function(require,module,exports){try{var type=require("type")}catch(err){var type=require("component-type")}var toFunction=require("to-function");var has=Object.prototype.hasOwnProperty;module.exports=function(obj,fn,ctx){fn=toFunction(fn);ctx=ctx||this;switch(type(obj)){case"array":return array(obj,fn,ctx);case"object":if("number"==typeof obj.length)return array(obj,fn,ctx);return object(obj,fn,ctx);case"string":return string(obj,fn,ctx)}};function string(obj,fn,ctx){for(var i=0;i<obj.length;++i){fn.call(ctx,obj.charAt(i),i)}}function object(obj,fn,ctx){for(var key in obj){if(has.call(obj,key)){fn.call(ctx,key,obj[key])}}}function array(obj,fn,ctx){for(var i=0;i<obj.length;++i){fn.call(ctx,obj[i],i)}}},{type:35,"component-type":35,"to-function":80}],80:[function(require,module,exports){var expr;try{expr=require("props")}catch(e){expr=require("component-props")}module.exports=toFunction;function toFunction(obj){switch({}.toString.call(obj)){case"[object Object]":return objectToFunction(obj);case"[object Function]":return obj;case"[object String]":return stringToFunction(obj);case"[object RegExp]":return regexpToFunction(obj);default:return defaultToFunction(obj)}}function defaultToFunction(val){return function(obj){return val===obj}}function regexpToFunction(re){return function(obj){return re.test(obj)}}function stringToFunction(str){if(/^ *\W+/.test(str))return new Function("_","return _ "+str);return new Function("_","return "+get(str))}function objectToFunction(obj){var match={};for(var key in obj){match[key]=typeof obj[key]==="string"?defaultToFunction(obj[key]):toFunction(obj[key])}return function(val){if(typeof val!=="object")return false;for(var key in match){if(!(key in val))return false;if(!match[key](val[key]))return false}return true}}function get(str){var props=expr(str);if(!props.length)return"_."+str;var val,i,prop;for(i=0;i<props.length;i++){prop=props[i];val="_."+prop;val="('function' == typeof "+val+" ? "+val+"() : "+val+")";str=stripNested(prop,str,val)}return str}function stripNested(prop,str,val){return str.replace(new RegExp("(\\.)?"+prop,"g"),function($0,$1){return $1?$0:val})}},{props:81,"component-props":81}],81:[function(require,module,exports){var globals=/\b(this|Array|Date|Object|Math|JSON)\b/g;module.exports=function(str,fn){var p=unique(props(str));if(fn&&"string"==typeof fn)fn=prefixed(fn);if(fn)return map(str,p,fn);return p};function props(str){return str.replace(/\.\w+|\w+ *\(|"[^"]*"|'[^']*'|\/([^/]+)\//g,"").replace(globals,"").match(/[$a-zA-Z_]\w*/g)||[]}function map(str,props,fn){var re=/\.\w+|\w+ *\(|"[^"]*"|'[^']*'|\/([^/]+)\/|[a-zA-Z_]\w*/g;return str.replace(re,function(_){if("("==_[_.length-1])return fn(_);if(!~props.indexOf(_))return _;return fn(_)})}function unique(arr){var ret=[];for(var i=0;i<arr.length;i++){if(~ret.indexOf(arr[i]))continue;ret.push(arr[i])}return ret}function prefixed(str){return function(_){return str+_}}},{}],78:[function(require,module,exports){module.exports=["a","an","and","as","at","but","by","en","for","from","how","if","in","neither","nor","of","on","only","onto","out","or","per","so","than","that","the","to","until","up","upon","v","v.","versus","vs","vs.","via","when","with","without","yet"]},{}],52:[function(require,module,exports){var inherit=require("./utils").inherit;var Facade=require("./facade");module.exports=Alias;function Alias(dictionary){Facade.call(this,dictionary)}inherit(Alias,Facade);Alias.prototype.type=Alias.prototype.action=function(){return"alias"};Alias.prototype.from=Alias.prototype.previousId=function(){return this.field("previousId")||this.field("from")};Alias.prototype.to=Alias.prototype.userId=function(){return this.field("userId")||this.field("to")}},{"./utils":58,"./facade":51}],53:[function(require,module,exports){var inherit=require("./utils").inherit;var Facade=require("./facade");var newDate=require("new-date");module.exports=Group;function Group(dictionary){Facade.call(this,dictionary)}inherit(Group,Facade);Group.prototype.type=Group.prototype.action=function(){return"group"};Group.prototype.groupId=Facade.field("groupId");Group.prototype.created=function(){var created=this.proxy("traits.createdAt")||this.proxy("traits.created")||this.proxy("properties.createdAt")||this.proxy("properties.created");if(created)return newDate(created)};Group.prototype.traits=function(aliases){var ret=this.properties();var id=this.groupId();aliases=aliases||{};if(id)ret.id=id;for(var alias in aliases){var value=null==this[alias]?this.proxy("traits."+alias):this[alias]();if(null==value)continue;ret[aliases[alias]]=value;delete ret[alias]}return ret};Group.prototype.properties=function(){return this.field("traits")||this.field("properties")||{}}},{"./utils":58,"./facade":51,"new-date":21}],54:[function(require,module,exports){var Facade=require("./facade");var isEmail=require("is-email");var newDate=require("new-date");var utils=require("./utils");var trim=require("trim");var inherit=utils.inherit;var clone=utils.clone;module.exports=Identify;function Identify(dictionary){Facade.call(this,dictionary)}inherit(Identify,Facade);Identify.prototype.type=Identify.prototype.action=function(){return"identify"};Identify.prototype.traits=function(aliases){var ret=this.field("traits")||{};var id=this.userId();aliases=aliases||{};if(id)ret.id=id;for(var alias in aliases){var value=null==this[alias]?this.proxy("traits."+alias):this[alias]();if(null==value)continue;ret[aliases[alias]]=value;delete ret[alias]}return ret};Identify.prototype.email=function(){var email=this.proxy("traits.email");if(email)return email;var userId=this.userId();if(isEmail(userId))return userId};Identify.prototype.created=function(){var created=this.proxy("traits.created")||this.proxy("traits.createdAt");if(created)return newDate(created)};Identify.prototype.companyCreated=function(){var created=this.proxy("traits.company.created")||this.proxy("traits.company.createdAt");if(created)return newDate(created)};Identify.prototype.name=function(){var name=this.proxy("traits.name");if(typeof name==="string")return trim(name);var firstName=this.firstName();var lastName=this.lastName();if(firstName&&lastName)return trim(firstName+" "+lastName)};Identify.prototype.firstName=function(){var firstName=this.proxy("traits.firstName");if(typeof firstName==="string")return trim(firstName);var name=this.proxy("traits.name");if(typeof name==="string")return trim(name).split(" ")[0]};Identify.prototype.lastName=function(){var lastName=this.proxy("traits.lastName");if(typeof lastName==="string")return trim(lastName);var name=this.proxy("traits.name");if(typeof name!=="string")return;var space=trim(name).indexOf(" ");if(space===-1)return;return trim(name.substr(space+1))};Identify.prototype.uid=function(){return this.userId()||this.username()||this.email()};Identify.prototype.description=function(){return this.proxy("traits.description")||this.proxy("traits.background")};Identify.prototype.username=Facade.proxy("traits.username");Identify.prototype.website=Facade.proxy("traits.website");Identify.prototype.phone=Facade.proxy("traits.phone");Identify.prototype.address=Facade.proxy("traits.address");Identify.prototype.avatar=Facade.proxy("traits.avatar")},{"./facade":51,"./utils":58,"is-email":19,"new-date":21,trim:50}],55:[function(require,module,exports){var inherit=require("./utils").inherit;var clone=require("./utils").clone;var Facade=require("./facade");var Identify=require("./identify");var isEmail=require("is-email");module.exports=Track;function Track(dictionary){Facade.call(this,dictionary)}inherit(Track,Facade);Track.prototype.type=Track.prototype.action=function(){return"track"};Track.prototype.event=Facade.field("event");Track.prototype.value=Facade.proxy("properties.value");Track.prototype.category=Facade.proxy("properties.category");Track.prototype.country=Facade.proxy("properties.country");Track.prototype.state=Facade.proxy("properties.state");Track.prototype.city=Facade.proxy("properties.city");Track.prototype.zip=Facade.proxy("properties.zip");Track.prototype.id=Facade.proxy("properties.id");Track.prototype.sku=Facade.proxy("properties.sku");Track.prototype.tax=Facade.proxy("properties.tax");Track.prototype.name=Facade.proxy("properties.name");Track.prototype.price=Facade.proxy("properties.price");Track.prototype.total=Facade.proxy("properties.total");Track.prototype.coupon=Facade.proxy("properties.coupon");Track.prototype.shipping=Facade.proxy("properties.shipping");Track.prototype.orderId=function(){return this.proxy("properties.id")||this.proxy("properties.orderId")};Track.prototype.subtotal=function(){var subtotal=this.obj.properties.subtotal;var total=this.total();var n;if(subtotal)return subtotal;if(!total)return 0;if(n=this.tax())total-=n;if(n=this.shipping())total-=n;return total};Track.prototype.products=function(){var props=this.obj.properties||{};return props.products||[]};Track.prototype.quantity=function(){var props=this.obj.properties||{};return props.quantity||1};Track.prototype.currency=function(){var props=this.obj.properties||{};return props.currency||"USD"};Track.prototype.referrer=Facade.proxy("properties.referrer");Track.prototype.query=Facade.proxy("options.query");Track.prototype.properties=function(aliases){var ret=this.field("properties")||{};aliases=aliases||{};for(var alias in aliases){var value=null==this[alias]?this.proxy("properties."+alias):this[alias]();if(null==value)continue;ret[aliases[alias]]=value;delete ret[alias]}return ret};Track.prototype.username=function(){return this.proxy("traits.username")||this.proxy("properties.username")||this.userId()||this.sessionId()};Track.prototype.email=function(){var email=this.proxy("traits.email");email=email||this.proxy("properties.email");if(email)return email;var userId=this.userId();if(isEmail(userId))return userId};Track.prototype.revenue=function(){var revenue=this.proxy("properties.revenue");var event=this.event();if(!revenue&&event&&event.match(/completed ?order/i)){revenue=this.proxy("properties.total")}return currency(revenue)};Track.prototype.cents=function(){var revenue=this.revenue();return"number"!=typeof revenue?this.value()||0:revenue*100};Track.prototype.identify=function(){var json=this.json();json.traits=this.traits();return new Identify(json)};function currency(val){if(!val)return;if(typeof val==="number")return val;if(typeof val!=="string")return;val=val.replace(/\$/g,"");val=parseFloat(val);if(!isNaN(val))return val}},{"./utils":58,"./facade":51,"./identify":54,"is-email":19}],56:[function(require,module,exports){var inherit=require("./utils").inherit;var Facade=require("./facade");var Track=require("./track");module.exports=Page;function Page(dictionary){Facade.call(this,dictionary)}inherit(Page,Facade);Page.prototype.type=Page.prototype.action=function(){return"page"};Page.prototype.category=Facade.field("category");Page.prototype.name=Facade.field("name");Page.prototype.properties=function(){var props=this.field("properties")||{};var category=this.category();var name=this.name();if(category)props.category=category;if(name)props.name=name;return props};Page.prototype.fullName=function(){var category=this.category();var name=this.name();return name&&category?category+" "+name:name};Page.prototype.event=function(name){return name?"Viewed "+name+" Page":"Loaded a Page"};Page.prototype.track=function(name){var props=this.properties();return new Track({event:this.event(name),properties:props})}},{"./utils":58,"./facade":51,"./track":55}],57:[function(require,module,exports){var inherit=require("./utils").inherit;var Page=require("./page");var Track=require("./track");module.exports=Screen;function Screen(dictionary){Page.call(this,dictionary)}inherit(Screen,Page);Screen.prototype.type=Screen.prototype.action=function(){return"screen"};Screen.prototype.event=function(name){return name?"Viewed "+name+" Screen":"Loaded a Screen"};Screen.prototype.track=function(name){var props=this.properties();return new Track({event:this.event(name),properties:props})}},{"./utils":58,"./page":56,"./track":55}],3:[function(require,module,exports){module.exports="2.3.5"},{}],4:[function(require,module,exports){var each=require("each");var plugins=require("./integrations.js");each(plugins,function(plugin){var name=(plugin.Integration||plugin).prototype.name;exports[name]=plugin})},{"./integrations.js":82,each:5}],82:[function(require,module,exports){module.exports=[require("./lib/adroll"),require("./lib/adwords"),require("./lib/alexa"),require("./lib/amplitude"),require("./lib/appcues"),require("./lib/awesm"),require("./lib/awesomatic"),require("./lib/bing-ads"),require("./lib/bronto"),require("./lib/bugherd"),require("./lib/bugsnag"),require("./lib/chartbeat"),require("./lib/churnbee"),require("./lib/clicktale"),require("./lib/clicky"),require("./lib/comscore"),require("./lib/crazy-egg"),require("./lib/curebit"),require("./lib/customerio"),require("./lib/drip"),require("./lib/errorception"),require("./lib/evergage"),require("./lib/facebook-ads"),require("./lib/foxmetrics"),require("./lib/frontleaf"),require("./lib/gauges"),require("./lib/get-satisfaction"),require("./lib/google-analytics"),require("./lib/google-tag-manager"),require("./lib/gosquared"),require("./lib/heap"),require("./lib/hellobar"),require("./lib/hittail"),require("./lib/hublo"),require("./lib/hubspot"),require("./lib/improvely"),require("./lib/insidevault"),require("./lib/inspectlet"),require("./lib/intercom"),require("./lib/keen-io"),require("./lib/kenshoo"),require("./lib/kissmetrics"),require("./lib/klaviyo"),require("./lib/leadlander"),require("./lib/livechat"),require("./lib/lucky-orange"),require("./lib/lytics"),require("./lib/mixpanel"),require("./lib/mojn"),require("./lib/mouseflow"),require("./lib/mousestats"),require("./lib/navilytics"),require("./lib/olark"),require("./lib/optimizely"),require("./lib/perfect-audience"),require("./lib/pingdom"),require("./lib/piwik"),require("./lib/preact"),require("./lib/qualaroo"),require("./lib/quantcast"),require("./lib/rollbar"),require("./lib/saasquatch"),require("./lib/sentry"),require("./lib/snapengage"),require("./lib/spinnakr"),require("./lib/tapstream"),require("./lib/trakio"),require("./lib/twitter-ads"),require("./lib/usercycle"),require("./lib/userfox"),require("./lib/uservoice"),require("./lib/vero"),require("./lib/visual-website-optimizer"),require("./lib/webengage"),require("./lib/woopra"),require("./lib/yandex-metrica")] },{"./lib/adroll":83,"./lib/adwords":84,"./lib/alexa":85,"./lib/amplitude":86,"./lib/appcues":87,"./lib/awesm":88,"./lib/awesomatic":89,"./lib/bing-ads":90,"./lib/bronto":91,"./lib/bugherd":92,"./lib/bugsnag":93,"./lib/chartbeat":94,"./lib/churnbee":95,"./lib/clicktale":96,"./lib/clicky":97,"./lib/comscore":98,"./lib/crazy-egg":99,"./lib/curebit":100,"./lib/customerio":101,"./lib/drip":102,"./lib/errorception":103,"./lib/evergage":104,"./lib/facebook-ads":105,"./lib/foxmetrics":106,"./lib/frontleaf":107,"./lib/gauges":108,"./lib/get-satisfaction":109,"./lib/google-analytics":110,"./lib/google-tag-manager":111,"./lib/gosquared":112,"./lib/heap":113,"./lib/hellobar":114,"./lib/hittail":115,"./lib/hublo":116,"./lib/hubspot":117,"./lib/improvely":118,"./lib/insidevault":119,"./lib/inspectlet":120,"./lib/intercom":121,"./lib/keen-io":122,"./lib/kenshoo":123,"./lib/kissmetrics":124,"./lib/klaviyo":125,"./lib/leadlander":126,"./lib/livechat":127,"./lib/lucky-orange":128,"./lib/lytics":129,"./lib/mixpanel":130,"./lib/mojn":131,"./lib/mouseflow":132,"./lib/mousestats":133,"./lib/navilytics":134,"./lib/olark":135,"./lib/optimizely":136,"./lib/perfect-audience":137,"./lib/pingdom":138,"./lib/piwik":139,"./lib/preact":140,"./lib/qualaroo":141,"./lib/quantcast":142,"./lib/rollbar":143,"./lib/saasquatch":144,"./lib/sentry":145,"./lib/snapengage":146,"./lib/spinnakr":147,"./lib/tapstream":148,"./lib/trakio":149,"./lib/twitter-ads":150,"./lib/usercycle":151,"./lib/userfox":152,"./lib/uservoice":153,"./lib/vero":154,"./lib/visual-website-optimizer":155,"./lib/webengage":156,"./lib/woopra":157,"./lib/yandex-metrica":158}],83:[function(require,module,exports){var integration=require("segmentio/analytics.js-integration");var snake=require("to-snake-case");var useHttps=require("use-https");var each=require("each");var is=require("is");var has=Object.prototype.hasOwnProperty;var AdRoll=module.exports=integration("AdRoll").assumesPageview().global("__adroll_loaded").global("adroll_adv_id").global("adroll_pix_id").global("adroll_custom_data").option("advId","").option("pixId","").tag("http",'<script src="http://a.adroll.com/j/roundtrip.js">').tag("https",'<script src="https://s.adroll.com/j/roundtrip.js">').mapping("events");AdRoll.prototype.initialize=function(page){window.adroll_adv_id=this.options.advId;window.adroll_pix_id=this.options.pixId;window.__adroll_loaded=true;var name=useHttps()?"https":"http";this.load(name,this.ready)};AdRoll.prototype.loaded=function(){return window.__adroll};AdRoll.prototype.page=function(page){var name=page.fullName();this.track(page.track(name))};AdRoll.prototype.track=function(track){var event=track.event();var user=this.analytics.user();var events=this.events(event);var total=track.revenue()||track.total()||0;var orderId=track.orderId()||0;each(events,function(event){var data={};if(user.id())data.user_id=user.id();data.adroll_conversion_value_in_dollars=total;data.order_id=orderId;data.adroll_segments=snake(event);window.__adroll.record_user(data)});if(!events.length){var data={};if(user.id())data.user_id=user.id();data.adroll_segments=snake(event);window.__adroll.record_user(data)}}},{"segmentio/analytics.js-integration":159,"to-snake-case":160,"use-https":161,each:5,is:18}],159:[function(require,module,exports){var bind=require("bind");var callback=require("callback");var clone=require("clone");var debug=require("debug");var defaults=require("defaults");var protos=require("./protos");var slug=require("slug");var statics=require("./statics");module.exports=createIntegration;function createIntegration(name){function Integration(options){if(options&&options.addIntegration){return options.addIntegration(Integration)}this.debug=debug("analytics:integration:"+slug(name));this.options=defaults(clone(options)||{},this.defaults);this._queue=[];this.once("ready",bind(this,this.flush));Integration.emit("construct",this);this.ready=bind(this,this.ready);this._wrapInitialize();this._wrapPage();this._wrapTrack()}Integration.prototype.defaults={};Integration.prototype.globals=[];Integration.prototype.templates={};Integration.prototype.name=name;for(var key in statics)Integration[key]=statics[key];for(var key in protos)Integration.prototype[key]=protos[key];return Integration}},{"./protos":162,"./statics":163,bind:164,callback:12,clone:14,debug:165,defaults:16,slug:166}],162:[function(require,module,exports){var loadScript=require("segmentio/load-script");var normalize=require("to-no-case");var callback=require("callback");var Emitter=require("emitter");var events=require("./events");var tick=require("next-tick");var assert=require("assert");var after=require("after");var each=require("component/each");var type=require("type");var fmt=require("yields/fmt");var setTimeout=window.setTimeout;var setInterval=window.setInterval;var onerror=null;var onload=null;Emitter(exports);exports.initialize=function(){var ready=this.ready;tick(ready)};exports.loaded=function(){return false};exports.load=function(cb){callback.async(cb)};exports.page=function(page){};exports.track=function(track){};exports.map=function(obj,str){var a=normalize(str);var ret=[];if(!obj)return ret;if("object"==type(obj)){for(var k in obj){var item=obj[k];var b=normalize(k);if(b==a)ret.push(item)}}if("array"==type(obj)){if(!obj.length)return ret;if(!obj[0].key)return ret;for(var i=0;i<obj.length;++i){var item=obj[i];var b=normalize(item.key);if(b==a)ret.push(item.value)}}return ret};exports.invoke=function(method){if(!this[method])return;var args=[].slice.call(arguments,1);if(!this._ready)return this.queue(method,args);var ret;try{this.debug("%s with %o",method,args);ret=this[method].apply(this,args)}catch(e){this.debug("error %o calling %s with %o",e,method,args)}return ret};exports.queue=function(method,args){if("page"==method&&this._assumesPageview&&!this._initialized){return this.page.apply(this,args)}this._queue.push({method:method,args:args})};exports.flush=function(){this._ready=true;var call;while(call=this._queue.shift())this[call.method].apply(this,call.args)};exports.reset=function(){for(var i=0,key;key=this.globals[i];i++)window[key]=undefined;window.setTimeout=setTimeout;window.setInterval=setInterval;window.onerror=onerror;window.onload=onload};exports.load=function(name,locals,fn){if("function"==typeof name)fn=name,locals=null,name=null;if(name&&"object"==typeof name)fn=locals,locals=name,name=null;if("function"==typeof locals)fn=locals,locals=null;name=name||"library";locals=locals||{};locals=this.locals(locals);var template=this.templates[name];assert(template,fmt('Template "%s" not defined.',name));var attrs=render(template,locals);var el;switch(template.type){case"img":attrs.width=1;attrs.height=1;el=loadImage(attrs,fn);break;case"script":el=loadScript(attrs,fn);delete attrs.src;each(attrs,function(key,val){el.setAttribute(key,val)});break;case"iframe":el=loadIframe(attrs,fn);break}return el};exports.locals=function(locals){locals=locals||{};var cache=Math.floor((new Date).getTime()/36e5);if(!locals.hasOwnProperty("cache"))locals.cache=cache;each(this.options,function(key,val){if(!locals.hasOwnProperty(key))locals[key]=val});return locals};exports.ready=function(){this.emit("ready")};exports._wrapInitialize=function(){var initialize=this.initialize;this.initialize=function(){this.debug("initialize");this._initialized=true;var ret=initialize.apply(this,arguments);this.emit("initialize");return ret};if(this._assumesPageview)this.initialize=after(2,this.initialize)};exports._wrapPage=function(){var page=this.page;this.page=function(){if(this._assumesPageview&&!this._initialized){return this.initialize.apply(this,arguments)}return page.apply(this,arguments)}};exports._wrapTrack=function(){var t=this.track;this.track=function(track){var event=track.event();var called;var ret;for(var method in events){var regexp=events[method];if(!this[method])continue;if(!regexp.test(event))continue;ret=this[method].apply(this,arguments);called=true;break}if(!called)ret=t.apply(this,arguments);return ret}};function loadImage(attrs,fn){fn=fn||function(){};var img=new Image;img.onerror=error(fn,"failed to load pixel",img);img.onload=function(){fn()};img.src=attrs.src;img.width=1;img.height=1;return img}function error(fn,message,img){return function(e){e=e||window.event;var err=new Error(message);err.event=e;err.source=img;fn(err)}}function render(template,locals){var attrs={};each(template.attrs,function(key,val){attrs[key]=val.replace(/\{\{\ *(\w+)\ *\}\}/g,function(_,$1){return locals[$1]})});return attrs}},{"./events":167,"segmentio/load-script":168,"to-no-case":169,callback:12,emitter:17,"next-tick":45,assert:170,after:10,"component/each":79,type:35,"yields/fmt":171}],167:[function(require,module,exports){module.exports={removedProduct:/removed[ _]?product/i,viewedProduct:/viewed[ _]?product/i,addedProduct:/added[ _]?product/i,completedOrder:/completed[ _]?order/i}},{}],168:[function(require,module,exports){var onload=require("script-onload");var tick=require("next-tick");var type=require("type");module.exports=function loadScript(options,fn){if(!options)throw new Error("Cant load nothing...");if("string"==type(options))options={src:options};var https=document.location.protocol==="https:"||document.location.protocol==="chrome-extension:";if(options.src&&options.src.indexOf("//")===0){options.src=https?"https:"+options.src:"http:"+options.src}if(https&&options.https)options.src=options.https;else if(!https&&options.http)options.src=options.http;var script=document.createElement("script");script.type="text/javascript";script.async=true;script.src=options.src;if("function"==type(fn)){onload(script,fn)}tick(function(){var firstScript=document.getElementsByTagName("script")[0];firstScript.parentNode.insertBefore(script,firstScript)});return script}},{"script-onload":172,"next-tick":45,type:35}],172:[function(require,module,exports){module.exports=function(el,fn){return el.addEventListener?add(el,fn):attach(el,fn)};function add(el,fn){el.addEventListener("load",function(_,e){fn(null,e)},false);el.addEventListener("error",function(e){var err=new Error('failed to load the script "'+el.src+'"');err.event=e;fn(err)},false)}function attach(el,fn){el.attachEvent("onreadystatechange",function(e){if(!/complete|loaded/.test(el.readyState))return;fn(null,e)})}},{}],169:[function(require,module,exports){module.exports=toNoCase;var hasSpace=/\s/;var hasSeparator=/[\W_]/;function toNoCase(string){if(hasSpace.test(string))return string.toLowerCase();if(hasSeparator.test(string))return unseparate(string).toLowerCase();return uncamelize(string).toLowerCase()}var separatorSplitter=/[\W_]+(.|$)/g;function unseparate(string){return string.replace(separatorSplitter,function(m,next){return next?" "+next:""})}var camelSplitter=/(.)([A-Z]+)/g;function uncamelize(string){return string.replace(camelSplitter,function(m,previous,uppers){return previous+" "+uppers.toLowerCase().split("").join(" ")})}},{}],170:[function(require,module,exports){var equals=require("equals");var fmt=require("fmt");var stack=require("stack");module.exports=exports=function(expr,msg){if(expr)return;throw new Error(msg||message())};exports.equal=function(actual,expected,msg){if(actual==expected)return;throw new Error(msg||fmt("Expected %o to equal %o.",actual,expected))};exports.notEqual=function(actual,expected,msg){if(actual!=expected)return;throw new Error(msg||fmt("Expected %o not to equal %o.",actual,expected))};exports.deepEqual=function(actual,expected,msg){if(equals(actual,expected))return;throw new Error(msg||fmt("Expected %o to deeply equal %o.",actual,expected))};exports.notDeepEqual=function(actual,expected,msg){if(!equals(actual,expected))return;throw new Error(msg||fmt("Expected %o not to deeply equal %o.",actual,expected))};exports.strictEqual=function(actual,expected,msg){if(actual===expected)return;throw new Error(msg||fmt("Expected %o to strictly equal %o.",actual,expected))};exports.notStrictEqual=function(actual,expected,msg){if(actual!==expected)return;throw new Error(msg||fmt("Expected %o not to strictly equal %o.",actual,expected))};exports.throws=function(block,error,msg){var err;try{block()}catch(e){err=e}if(!err)throw new Error(msg||fmt("Expected %s to throw an error.",block.toString()));if(error&&!(err instanceof error)){throw new Error(msg||fmt("Expected %s to throw an %o.",block.toString(),error))}};exports.doesNotThrow=function(block,error,msg){var err;try{block()}catch(e){err=e}if(err)throw new Error(msg||fmt("Expected %s not to throw an error.",block.toString()));if(error&&err instanceof error){throw new Error(msg||fmt("Expected %s not to throw an %o.",block.toString(),error))}};function message(){if(!Error.captureStackTrace)return"assertion failed";var callsite=stack()[2];var fn=callsite.getFunctionName();var file=callsite.getFileName();var line=callsite.getLineNumber()-1;var col=callsite.getColumnNumber()-1;var src=get(file);line=src.split("\n")[line].slice(col);var m=line.match(/assert\((.*)\)/);return m&&m[1].trim()}function get(script){var xhr=new XMLHttpRequest;xhr.open("GET",script,false);xhr.send(null);return xhr.responseText}},{equals:173,fmt:171,stack:174}],173:[function(require,module,exports){var type=require("type");module.exports=equals;equals.compare=compare;function equals(){var i=arguments.length-1;while(i>0){if(!compare(arguments[i],arguments[--i]))return false}return true}function compare(a,b,memos){if(a===b)return true;var fnA=types[type(a)];var fnB=types[type(b)];return fnA&&fnA===fnB?fnA(a,b,memos):false}var types={};types.number=function(a){return a!==a};types["function"]=function(a,b,memos){return a.toString()===b.toString()&&types.object(a,b,memos)&&compare(a.prototype,b.prototype)};types.date=function(a,b){return+a===+b};types.regexp=function(a,b){return a.toString()===b.toString()};types.element=function(a,b){return a.outerHTML===b.outerHTML};types.textnode=function(a,b){return a.textContent===b.textContent};function memoGaurd(fn){return function(a,b,memos){if(!memos)return fn(a,b,[]);var i=memos.length,memo;while(memo=memos[--i]){if(memo[0]===a&&memo[1]===b)return true}return fn(a,b,memos)}}types["arguments"]=types.array=memoGaurd(compareArrays);function compareArrays(a,b,memos){var i=a.length;if(i!==b.length)return false;memos.push([a,b]);while(i--){if(!compare(a[i],b[i],memos))return false}return true}types.object=memoGaurd(compareObjects);function compareObjects(a,b,memos){var ka=getEnumerableProperties(a);var kb=getEnumerableProperties(b);var i=ka.length;if(i!==kb.length)return false;ka.sort();kb.sort();while(i--)if(ka[i]!==kb[i])return false;memos.push([a,b]);i=ka.length;while(i--){var key=ka[i];if(!compare(a[key],b[key],memos))return false}return true}function getEnumerableProperties(object){var result=[];for(var k in object)if(k!=="constructor"){result.push(k)}return result}},{type:175}],175:[function(require,module,exports){var toString={}.toString;var DomNode=typeof window!="undefined"?window.Node:Function;module.exports=exports=function(x){var type=typeof x;if(type!="object")return type;type=types[toString.call(x)];if(type)return type;if(x instanceof DomNode)switch(x.nodeType){case 1:return"element";case 3:return"text-node";case 9:return"document";case 11:return"document-fragment";default:return"dom-node"}};var types=exports.types={"[object Function]":"function","[object Date]":"date","[object RegExp]":"regexp","[object Arguments]":"arguments","[object Array]":"array","[object String]":"string","[object Null]":"null","[object Undefined]":"undefined","[object Number]":"number","[object Boolean]":"boolean","[object Object]":"object","[object Text]":"text-node","[object Uint8Array]":"bit-array","[object Uint16Array]":"bit-array","[object Uint32Array]":"bit-array","[object Uint8ClampedArray]":"bit-array","[object Error]":"error","[object FormData]":"form-data","[object File]":"file","[object Blob]":"blob"}},{}],171:[function(require,module,exports){module.exports=fmt;fmt.o=JSON.stringify;fmt.s=String;fmt.d=parseInt;function fmt(str){var args=[].slice.call(arguments,1);var j=0;return str.replace(/%([a-z])/gi,function(_,f){return fmt[f]?fmt[f](args[j++]):_+f})}},{}],174:[function(require,module,exports){module.exports=stack;function stack(){var orig=Error.prepareStackTrace;Error.prepareStackTrace=function(_,stack){return stack};var err=new Error;Error.captureStackTrace(err,arguments.callee);var stack=err.stack;Error.prepareStackTrace=orig;return stack}},{}],163:[function(require,module,exports){var after=require("after");var domify=require("component/domify");var each=require("component/each");var Emitter=require("emitter");Emitter(exports);exports.option=function(key,value){this.prototype.defaults[key]=value;return this};exports.mapping=function(name){this.option(name,[]);this.prototype[name]=function(str){return this.map(this.options[name],str)};return this};exports.global=function(key){this.prototype.globals.push(key);return this};exports.assumesPageview=function(){this.prototype._assumesPageview=true;return this};exports.readyOnLoad=function(){this.prototype._readyOnLoad=true;return this};exports.readyOnInitialize=function(){this.prototype._readyOnInitialize=true;return this};exports.tag=function(name,str){if(null==str){str=name;name="library"}this.prototype.templates[name]=objectify(str);return this};function objectify(str){str=str.replace(' src="',' data-src="');var el=domify(str);var attrs={};each(el.attributes,function(attr){var name="data-src"==attr.name?"src":attr.name;attrs[name]=attr.value});return{type:el.tagName.toLowerCase(),attrs:attrs}}},{after:10,"component/domify":176,"component/each":79,emitter:17}],176:[function(require,module,exports){module.exports=parse;var div=document.createElement("div");div.innerHTML=' <link/><table></table><a href="/a">a</a><input type="checkbox"/>';var innerHTMLBug=!div.getElementsByTagName("link").length;div=undefined;var map={legend:[1,"<fieldset>","</fieldset>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],_default:innerHTMLBug?[1,"X<div>","</div>"]:[0,"",""]};map.td=map.th=[3,"<table><tbody><tr>","</tr></tbody></table>"];map.option=map.optgroup=[1,'<select multiple="multiple">',"</select>"];map.thead=map.tbody=map.colgroup=map.caption=map.tfoot=[1,"<table>","</table>"];map.text=map.circle=map.ellipse=map.line=map.path=map.polygon=map.polyline=map.rect=[1,'<svg xmlns="http://www.w3.org/2000/svg" version="1.1">',"</svg>"];function parse(html,doc){if("string"!=typeof html)throw new TypeError("String expected");if(!doc)doc=document;var m=/<([\w:]+)/.exec(html);if(!m)return doc.createTextNode(html);html=html.replace(/^\s+|\s+$/g,"");var tag=m[1];if(tag=="body"){var el=doc.createElement("html");el.innerHTML=html;return el.removeChild(el.lastChild)}var wrap=map[tag]||map._default;var depth=wrap[0];var prefix=wrap[1];var suffix=wrap[2];var el=doc.createElement("div");el.innerHTML=prefix+html+suffix;while(depth--)el=el.lastChild;if(el.firstChild==el.lastChild){return el.removeChild(el.firstChild)}var fragment=doc.createDocumentFragment();while(el.firstChild){fragment.appendChild(el.removeChild(el.firstChild))}return fragment}},{}],164:[function(require,module,exports){var bind=require("bind"),bindAll=require("bind-all");module.exports=exports=bind;exports.all=bindAll;exports.methods=bindMethods;function bindMethods(obj,methods){methods=[].slice.call(arguments,1);for(var i=0,method;method=methods[i];i++){obj[method]=bind(obj,obj[method])}return obj}},{bind:33,"bind-all":34}],165:[function(require,module,exports){if("undefined"==typeof window){module.exports=require("./lib/debug")}else{module.exports=require("./debug")}},{"./lib/debug":177,"./debug":178}],177:[function(require,module,exports){var tty=require("tty");module.exports=debug;var names=[],skips=[];(process.env.DEBUG||"").split(/[\s,]+/).forEach(function(name){name=name.replace("*",".*?");if(name[0]==="-"){skips.push(new RegExp("^"+name.substr(1)+"$"))}else{names.push(new RegExp("^"+name+"$"))}});var colors=[6,2,3,4,5,1];var prev={};var prevColor=0;var isatty=tty.isatty(2);function color(){return colors[prevColor++%colors.length]}function humanize(ms){var sec=1e3,min=60*1e3,hour=60*min;if(ms>=hour)return(ms/hour).toFixed(1)+"h";if(ms>=min)return(ms/min).toFixed(1)+"m";if(ms>=sec)return(ms/sec|0)+"s";return ms+"ms"}function debug(name){function disabled(){}disabled.enabled=false;var match=skips.some(function(re){return re.test(name)});if(match)return disabled;match=names.some(function(re){return re.test(name)});if(!match)return disabled;var c=color();function colored(fmt){fmt=coerce(fmt);var curr=new Date;var ms=curr-(prev[name]||curr);prev[name]=curr;fmt=" [9"+c+"m"+name+" "+"[3"+c+"m"+fmt+"[3"+c+"m"+" +"+humanize(ms)+"";console.error.apply(this,arguments)}function plain(fmt){fmt=coerce(fmt);fmt=(new Date).toUTCString()+" "+name+" "+fmt;console.error.apply(this,arguments)}colored.enabled=plain.enabled=true;return isatty||process.env.DEBUG_COLORS?colored:plain}function coerce(val){if(val instanceof Error)return val.stack||val.message;return val}},{}],178:[function(require,module,exports){module.exports=debug;function debug(name){if(!debug.enabled(name))return function(){};return function(fmt){fmt=coerce(fmt);var curr=new Date;var ms=curr-(debug[name]||curr);debug[name]=curr;fmt=name+" "+fmt+" +"+debug.humanize(ms);window.console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}}debug.names=[];debug.skips=[];debug.enable=function(name){try{localStorage.debug=name}catch(e){}var split=(name||"").split(/[\s,]+/),len=split.length;for(var i=0;i<len;i++){name=split[i].replace("*",".*?");if(name[0]==="-"){debug.skips.push(new RegExp("^"+name.substr(1)+"$"))}else{debug.names.push(new RegExp("^"+name+"$"))}}};debug.disable=function(){debug.enable("")};debug.humanize=function(ms){var sec=1e3,min=60*1e3,hour=60*min;if(ms>=hour)return(ms/hour).toFixed(1)+"h";if(ms>=min)return(ms/min).toFixed(1)+"m";if(ms>=sec)return(ms/sec|0)+"s";return ms+"ms"};debug.enabled=function(name){for(var i=0,len=debug.skips.length;i<len;i++){if(debug.skips[i].test(name)){return false}}for(var i=0,len=debug.names.length;i<len;i++){if(debug.names[i].test(name)){return true}}return false};function coerce(val){if(val instanceof Error)return val.stack||val.message;return val}try{if(window.localStorage)debug.enable(localStorage.debug)}catch(e){}},{}],166:[function(require,module,exports){module.exports=function(str,options){options||(options={});return str.toLowerCase().replace(options.replace||/[^a-z0-9]/g," ").replace(/^ +| +$/g,"").replace(/ +/g,options.separator||"-")}},{}],160:[function(require,module,exports){var toSpace=require("to-space-case");module.exports=toSnakeCase;function toSnakeCase(string){return toSpace(string).replace(/\s/g,"_")}},{"to-space-case":179}],179:[function(require,module,exports){var clean=require("to-no-case");module.exports=toSpaceCase;function toSpaceCase(string){return clean(string).replace(/[\W_]+(.|$)/g,function(matches,match){return match?" "+match:""})}},{"to-no-case":69}],161:[function(require,module,exports){module.exports=function(url){switch(arguments.length){case 0:return check();case 1:return transform(url)}};function transform(url){return check()?"https:"+url:"http:"+url}function check(){return location.protocol=="https:"||location.protocol=="chrome-extension:"}},{}],84:[function(require,module,exports){var integration=require("segmentio/analytics.js-integration");var onbody=require("on-body");var domify=require("domify");var Queue=require("queue");var each=require("each");var has=Object.prototype.hasOwnProperty;var q=new Queue({concurrency:1,timeout:2e3});var AdWords=module.exports=integration("AdWords").option("conversionId","").option("remarketing",false).tag("conversion",'<script src="//www.googleadservices.com/pagead/conversion.js">').mapping("events");AdWords.prototype.initialize=function(){onbody(this.ready)};AdWords.prototype.loaded=function(){return!!document.body};AdWords.prototype.page=function(page){var remarketing=this.options.remarketing;var id=this.options.conversionId;if(remarketing)this.remarketing(id)};AdWords.prototype.track=function(track){var id=this.options.conversionId;var events=this.events(track.event());var revenue=track.revenue()||0;var self=this;each(events,function(label){self.conversion({conversionId:id,value:revenue,label:label})})};AdWords.prototype.conversion=function(obj,fn){this.enqueue({google_conversion_id:obj.conversionId,google_conversion_language:"en",google_conversion_format:"3",google_conversion_color:"ffffff",google_conversion_label:obj.label,google_conversion_value:obj.value,google_remarketing_only:false},fn)};AdWords.prototype.remarketing=function(id){this.enqueue({google_conversion_id:id,google_remarketing_only:true})};AdWords.prototype.enqueue=function(obj,fn){this.debug("sending %o",obj);var self=this;q.push(function(next){self.globalize(obj);self.shim();self.load("conversion",function(){if(fn)fn();next()})})};AdWords.prototype.globalize=function(obj){for(var name in obj){if(obj.hasOwnProperty(name)){window[name]=obj[name]}}};AdWords.prototype.shim=function(){var self=this;var write=document.write;document.write=append;function append(str){var el=domify(str);if(!el.src)return write(str);if(!/googleadservices/.test(el.src))return write(str);self.debug("append %o",el);document.body.appendChild(el);document.write=write}}},{"segmentio/analytics.js-integration":159,"on-body":180,domify:181,queue:182,each:5}],180:[function(require,module,exports){var each=require("each");var body=false;var callbacks=[];module.exports=function onBody(callback){if(body){call(callback)}else{callbacks.push(callback)}};var interval=setInterval(function(){if(!document.body)return;body=true;each(callbacks,call);clearInterval(interval)},5);function call(callback){callback(document.body)}},{each:79}],181:[function(require,module,exports){module.exports=parse;var map={legend:[1,"<fieldset>","</fieldset>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],_default:[0,"",""]};map.td=map.th=[3,"<table><tbody><tr>","</tr></tbody></table>"];map.option=map.optgroup=[1,'<select multiple="multiple">',"</select>"];map.thead=map.tbody=map.colgroup=map.caption=map.tfoot=[1,"<table>","</table>"];map.text=map.circle=map.ellipse=map.line=map.path=map.polygon=map.polyline=map.rect=[1,'<svg xmlns="http://www.w3.org/2000/svg" version="1.1">',"</svg>"];function parse(html){if("string"!=typeof html)throw new TypeError("String expected");html=html.replace(/^\s+|\s+$/g,"");var m=/<([\w:]+)/.exec(html);if(!m)return document.createTextNode(html);var tag=m[1];if(tag=="body"){var el=document.createElement("html");el.innerHTML=html;return el.removeChild(el.lastChild)}var wrap=map[tag]||map._default;var depth=wrap[0];var prefix=wrap[1];var suffix=wrap[2];var el=document.createElement("div");el.innerHTML=prefix+html+suffix;while(depth--)el=el.lastChild;if(el.firstChild==el.lastChild){return el.removeChild(el.firstChild)}var fragment=document.createDocumentFragment();while(el.firstChild){fragment.appendChild(el.removeChild(el.firstChild))}return fragment}},{}],182:[function(require,module,exports){var Emitter;var bind;try{Emitter=require("emitter");bind=require("bind")}catch(err){Emitter=require("component-emitter");bind=require("component-bind")}module.exports=Queue;function Queue(options){options=options||{};this.timeout=options.timeout||0;this.concurrency=options.concurrency||1;this.pending=0;this.jobs=[]}Emitter(Queue.prototype);Queue.prototype.length=function(){return this.pending+this.jobs.length};Queue.prototype.push=function(fn,cb){this.jobs.push([fn,cb]);setTimeout(bind(this,this.run),0)};Queue.prototype.run=function(){while(this.pending<this.concurrency){var job=this.jobs.shift();if(!job)break;this.exec(job)}};Queue.prototype.exec=function(job){var self=this;var ms=this.timeout;var fn=job[0];var cb=job[1];if(ms)fn=timeout(fn,ms);this.pending++;fn(function(err,res){cb&&cb(err,res);self.pending--;self.run()})};function timeout(fn,ms){return function(cb){var done;var id=setTimeout(function(){done=true;var err=new Error("Timeout of "+ms+"ms exceeded");err.timeout=timeout;cb(err)},ms);fn(function(err,res){if(done)return;clearTimeout(id);cb(err,res)})}}},{emitter:183,bind:33,"component-emitter":183,"component-bind":33}],183:[function(require,module,exports){module.exports=Emitter;function Emitter(obj){if(obj)return mixin(obj)}function mixin(obj){for(var key in Emitter.prototype){obj[key]=Emitter.prototype[key]}return obj}Emitter.prototype.on=Emitter.prototype.addEventListener=function(event,fn){this._callbacks=this._callbacks||{};(this._callbacks[event]=this._callbacks[event]||[]).push(fn);return this};Emitter.prototype.once=function(event,fn){var self=this;this._callbacks=this._callbacks||{};function on(){self.off(event,on);fn.apply(this,arguments)}on.fn=fn;this.on(event,on);return this};Emitter.prototype.off=Emitter.prototype.removeListener=Emitter.prototype.removeAllListeners=Emitter.prototype.removeEventListener=function(event,fn){this._callbacks=this._callbacks||{};if(0==arguments.length){this._callbacks={};return this}var callbacks=this._callbacks[event];if(!callbacks)return this;if(1==arguments.length){delete this._callbacks[event];return this}var cb;for(var i=0;i<callbacks.length;i++){cb=callbacks[i];if(cb===fn||cb.fn===fn){callbacks.splice(i,1);break}}return this};Emitter.prototype.emit=function(event){this._callbacks=this._callbacks||{};var args=[].slice.call(arguments,1),callbacks=this._callbacks[event];if(callbacks){callbacks=callbacks.slice(0);for(var i=0,len=callbacks.length;i<len;++i){callbacks[i].apply(this,args)}}return this};Emitter.prototype.listeners=function(event){this._callbacks=this._callbacks||{};return this._callbacks[event]||[]};Emitter.prototype.hasListeners=function(event){return!!this.listeners(event).length}},{}],85:[function(require,module,exports){var integration=require("segmentio/analytics.js-integration");var Alexa=module.exports=integration("Alexa").assumesPageview().global("_atrk_opts").option("account",null).option("domain","").option("dynamic",true).tag('<script src="//d31qbv1cthcecs.cloudfront.net/atrk.js">');Alexa.prototype.initialize=function(page){var self=this;window._atrk_opts={atrk_acct:this.options.account,domain:this.options.domain,dynamic:this.options.dynamic};this.load(function(){window.atrk();self.ready()})};Alexa.prototype.loaded=function(){return!!window.atrk}},{"segmentio/analytics.js-integration":159}],86:[function(require,module,exports){var integration=require("segmentio/analytics.js-integration");var Amplitude=module.exports=integration("Amplitude").assumesPageview().global("amplitude").option("apiKey","").option("trackAllPages",false).option("trackNamedPages",true).option("trackCategorizedPages",true).tag('<script src="https://d24n15hnbwhuhn.cloudfront.net/libs/amplitude-1.1-min.js">');Amplitude.prototype.initialize=function(page){(function(e,t){var r=e.amplitude||{};r._q=[];function i(e){r[e]=function(){r._q.push([e].concat(Array.prototype.slice.call(arguments,0)))}}var s=["init","logEvent","setUserId","setGlobalUserProperties","setVersionName","setDomain"];for(var c=0;c<s.length;c++){i(s[c])}e.amplitude=r})(window,document);window.amplitude.init(this.options.apiKey);this.load(this.ready)};Amplitude.prototype.loaded=function(){return!!(window.amplitude&&window.amplitude.options)};Amplitude.prototype.page=function(page){var properties=page.properties();var category=page.category();var name=page.fullName();var opts=this.options;if(opts.trackAllPages){this.track(page.track())}if(category&&opts.trackCategorizedPages){this.track(page.track(category))}if(name&&opts.trackNamedPages){this.track(page.track(name))}};Amplitude.prototype.identify=function(identify){var id=identify.userId();var traits=identify.traits();if(id)window.amplitude.setUserId(id);if(traits)window.amplitude.setGlobalUserProperties(traits)};Amplitude.prototype.track=function(track){var props=track.properties(); var event=track.event();window.amplitude.logEvent(event,props)}},{"segmentio/analytics.js-integration":159}],87:[function(require,module,exports){var integration=require("segmentio/analytics.js-integration");var load=require("load-script");var is=require("is");module.exports=exports=function(analytics){analytics.addIntegration(Appcues)};var Appcues=exports.Integration=integration("Appcues").assumesPageview().global("Appcues").global("AppcuesIdentity").option("appcuesId","").option("userId","").option("userEmail","");Appcues.prototype.initialize=function(){this.load(function(){window.Appcues.init()})};Appcues.prototype.loaded=function(){return is.object(window.Appcues)};Appcues.prototype.load=function(callback){var script=load("//d2dubfq97s02eu.cloudfront.net/appcues-bundle.min.js",callback);script.setAttribute("data-appcues-id",this.options.appcuesId);script.setAttribute("data-user-id",this.options.userId);script.setAttribute("data-user-email",this.options.userEmail)};Appcues.prototype.identify=function(identify){window.Appcues.identify(identify.traits())}},{"segmentio/analytics.js-integration":159,"load-script":168,is:18}],88:[function(require,module,exports){var integration=require("segmentio/analytics.js-integration");var each=require("each");var Awesm=module.exports=integration("awe.sm").assumesPageview().global("AWESM").option("apiKey","").tag('<script src="//widgets.awe.sm/v3/widgets.js?key={{ apiKey }}&async=true">').mapping("events");Awesm.prototype.initialize=function(page){window.AWESM={api_key:this.options.apiKey};this.load(this.ready)};Awesm.prototype.loaded=function(){return!!(window.AWESM&&window.AWESM._exists)};Awesm.prototype.track=function(track){var user=this.analytics.user();var goals=this.events(track.event());each(goals,function(goal){window.AWESM.convert(goal,track.cents(),null,user.id())})}},{"segmentio/analytics.js-integration":159,each:5}],89:[function(require,module,exports){var integration=require("segmentio/analytics.js-integration");var is=require("is");var noop=function(){};var onBody=require("on-body");var Awesomatic=module.exports=integration("Awesomatic").assumesPageview().global("Awesomatic").global("AwesomaticSettings").global("AwsmSetup").global("AwsmTmp").option("appId","").tag('<script src="https://1c817b7a15b6941337c0-dff9b5f4adb7ba28259631e99c3f3691.ssl.cf2.rackcdn.com/gen/embed.js">');Awesomatic.prototype.initialize=function(page){var self=this;var user=this.analytics.user();var id=user.id();var options=user.traits();options.appId=this.options.appId;if(id)options.user_id=id;this.load(function(){window.Awesomatic.initialize(options,function(){self.ready()})})};Awesomatic.prototype.loaded=function(){return is.object(window.Awesomatic)}},{"segmentio/analytics.js-integration":159,is:18,"on-body":180}],90:[function(require,module,exports){var integration=require("segmentio/analytics.js-integration");var onbody=require("on-body");var domify=require("domify");var extend=require("extend");var bind=require("bind");var when=require("when");var each=require("each");var has=Object.prototype.hasOwnProperty;var noop=function(){};var Bing=module.exports=integration("Bing Ads").option("siteId","").option("domainId","").tag('<script id="mstag_tops" src="//flex.msn.com/mstag/site/{{ siteId }}/mstag.js">').mapping("events");Bing.prototype.initialize=function(page){if(!window.mstag){window.mstag={loadTag:noop,time:(new Date).getTime(),_write:writeToAppend}}var self=this;onbody(function(){self.load(function(){var loaded=bind(self,self.loaded);when(loaded,self.ready)})})};Bing.prototype.loaded=function(){return!!(window.mstag&&window.mstag.loadTag!==noop)};Bing.prototype.track=function(track){var events=this.events(track.event());var revenue=track.revenue()||0;var self=this;each(events,function(goal){window.mstag.loadTag("analytics",{domainId:self.options.domainId,revenue:revenue,dedup:"1",type:"1",actionid:goal})})};function writeToAppend(str){var first=document.getElementsByTagName("script")[0];var el=domify(str);if("script"==el.tagName.toLowerCase()&&el.getAttribute("src")){var tmp=document.createElement("script");tmp.src=el.getAttribute("src");tmp.async=true;el=tmp}document.body.appendChild(el)}},{"segmentio/analytics.js-integration":159,"on-body":180,domify:181,extend:40,bind:33,when:184,each:5}],184:[function(require,module,exports){var callback=require("callback");module.exports=when;function when(condition,fn,interval){if(condition())return callback.async(fn);var ref=setInterval(function(){if(!condition())return;callback(fn);clearInterval(ref)},interval||10)}},{callback:12}],91:[function(require,module,exports){var integration=require("segmentio/analytics.js-integration");var Identify=require("facade").Identify;var Track=require("facade").Track;var pixel=require("load-pixel")("http://app.bronto.com/public/");var qs=require("querystring");var each=require("each");var Bronto=module.exports=integration("Bronto").global("__bta").option("siteId","").option("host","").tag('<script src="//p.bm23.com/bta.js">');Bronto.prototype.initialize=function(page){var self=this;var params=qs.parse(window.location.search);if(!params._bta_tid&&!params._bta_c){this.debug("missing tracking URL parameters `_bta_tid` and `_bta_c`.")}this.load(function(){var opts=self.options;self.bta=new window.__bta(opts.siteId);if(opts.host)self.bta.setHost(opts.host);self.ready()})};Bronto.prototype.loaded=function(){return this.bta};Bronto.prototype.track=function(track){var revenue=track.revenue();var event=track.event();var type="number"==typeof revenue?"$":"t";this.bta.addConversionLegacy(type,event,revenue)};Bronto.prototype.completedOrder=function(track){var user=this.analytics.user();var products=track.products();var props=track.properties();var items=[];var identify=new Identify({userId:user.id(),traits:user.traits()});var email=identify.email();each(products,function(product){var track=new Track({properties:product});items.push({item_id:track.id()||track.sku(),desc:product.description||track.name(),quantity:track.quantity(),amount:track.price()})});this.bta.addOrder({order_id:track.orderId(),email:email,items:items})}},{"segmentio/analytics.js-integration":159,facade:27,"load-pixel":185,querystring:186,each:5}],185:[function(require,module,exports){var stringify=require("querystring").stringify;var sub=require("substitute");module.exports=function(path){return function(query,obj,fn){if("function"==typeof obj)fn=obj,obj={};obj=obj||{};fn=fn||function(){};var url=sub(path,obj);var img=new Image;img.onerror=error(fn,"failed to load pixel",img);img.onload=function(){fn()};query=stringify(query);if(query)query="?"+query;img.src=url+query;img.width=1;img.height=1;return img}};function error(fn,message,img){return function(e){e=e||window.event;var err=new Error(message);err.event=e;err.source=img;fn(err)}}},{querystring:186,substitute:187}],186:[function(require,module,exports){var encode=encodeURIComponent;var decode=decodeURIComponent;var trim=require("trim");var type=require("type");exports.parse=function(str){if("string"!=typeof str)return{};str=trim(str);if(""==str)return{};if("?"==str.charAt(0))str=str.slice(1);var obj={};var pairs=str.split("&");for(var i=0;i<pairs.length;i++){var parts=pairs[i].split("=");var key=decode(parts[0]);var m;if(m=/(\w+)\[(\d+)\]/.exec(key)){obj[m[1]]=obj[m[1]]||[];obj[m[1]][m[2]]=decode(parts[1]);continue}obj[parts[0]]=null==parts[1]?"":decode(parts[1])}return obj};exports.stringify=function(obj){if(!obj)return"";var pairs=[];for(var key in obj){var value=obj[key];if("array"==type(value)){for(var i=0;i<value.length;++i){pairs.push(encode(key+"["+i+"]")+"="+encode(value[i]))}continue}pairs.push(encode(key)+"="+encode(obj[key]))}return pairs.join("&")}},{trim:50,type:35}],187:[function(require,module,exports){module.exports=substitute;function substitute(str,obj,expr){if(!obj)throw new TypeError("expected an object");expr=expr||/:(\w+)/g;return str.replace(expr,function(_,prop){return null!=obj[prop]?obj[prop]:_})}},{}],92:[function(require,module,exports){var integration=require("segmentio/analytics.js-integration");var tick=require("next-tick");var BugHerd=module.exports=integration("BugHerd").assumesPageview().global("BugHerdConfig").global("_bugHerd").option("apiKey","").option("showFeedbackTab",true).tag('<script src="//www.bugherd.com/sidebarv2.js?apikey={{ apiKey }}">');BugHerd.prototype.initialize=function(page){window.BugHerdConfig={feedback:{hide:!this.options.showFeedbackTab}};var ready=this.ready;this.load(function(){tick(ready)})};BugHerd.prototype.loaded=function(){return!!window._bugHerd}},{"segmentio/analytics.js-integration":159,"next-tick":45}],93:[function(require,module,exports){var integration=require("segmentio/analytics.js-integration");var is=require("is");var extend=require("extend");var onError=require("on-error");var Bugsnag=module.exports=integration("Bugsnag").global("Bugsnag").option("apiKey","").tag('<script src="//d2wy8f7a9ursnm.cloudfront.net/bugsnag-2.min.js">');Bugsnag.prototype.initialize=function(page){var self=this;this.load(function(){window.Bugsnag.apiKey=self.options.apiKey;self.ready()})};Bugsnag.prototype.loaded=function(){return is.object(window.Bugsnag)};Bugsnag.prototype.identify=function(identify){window.Bugsnag.metaData=window.Bugsnag.metaData||{};extend(window.Bugsnag.metaData,identify.traits())}},{"segmentio/analytics.js-integration":159,is:18,extend:40,"on-error":188}],188:[function(require,module,exports){module.exports=onError;var callbacks=[];if("function"==typeof window.onerror)callbacks.push(window.onerror);window.onerror=handler;function handler(){for(var i=0,fn;fn=callbacks[i];i++)fn.apply(this,arguments)}function onError(fn){callbacks.push(fn);if(window.onerror!=handler){callbacks.push(window.onerror);window.onerror=handler}}},{}],94:[function(require,module,exports){var integration=require("segmentio/analytics.js-integration");var defaults=require("defaults");var onBody=require("on-body");var Chartbeat=module.exports=integration("Chartbeat").assumesPageview().global("_sf_async_config").global("_sf_endpt").global("pSUPERFLY").option("domain","").option("uid",null).tag('<script src="//static.chartbeat.com/js/chartbeat.js">');Chartbeat.prototype.initialize=function(page){var self=this;window._sf_async_config=window._sf_async_config||{};window._sf_async_config.useCanonical=true;defaults(window._sf_async_config,this.options);onBody(function(){window._sf_endpt=(new Date).getTime();self.load(self.ready)})};Chartbeat.prototype.loaded=function(){return!!window.pSUPERFLY};Chartbeat.prototype.page=function(page){var props=page.properties();var name=page.fullName();window.pSUPERFLY.virtualPage(props.path,name||props.title)}},{"segmentio/analytics.js-integration":159,defaults:189,"on-body":180}],189:[function(require,module,exports){module.exports=defaults;function defaults(dest,defaults){for(var prop in defaults){if(!(prop in dest)){dest[prop]=defaults[prop]}}return dest}},{}],95:[function(require,module,exports){var integration=require("segmentio/analytics.js-integration");var push=require("global-queue")("_cbq");var each=require("each");var has=Object.prototype.hasOwnProperty;var supported={activation:true,changePlan:true,register:true,refund:true,charge:true,cancel:true,login:true};var ChurnBee=module.exports=integration("ChurnBee").global("_cbq").global("ChurnBee").option("apiKey","").tag('<script src="//api.churnbee.com/cb.js">').mapping("events");ChurnBee.prototype.initialize=function(page){push("_setApiKey",this.options.apiKey);this.load(this.ready)};ChurnBee.prototype.loaded=function(){return!!window.ChurnBee};ChurnBee.prototype.track=function(track){var event=track.event();var events=this.events(event);events.push(event);each(events,function(event){if(true!=supported[event])return;push(event,track.properties({revenue:"amount"}))})}},{"segmentio/analytics.js-integration":159,"global-queue":190,each:5}],190:[function(require,module,exports){module.exports=generate;function generate(name,options){options=options||{};return function(args){args=[].slice.call(arguments);window[name]||(window[name]=[]);options.wrap===false?window[name].push.apply(window[name],args):window[name].push(args)}}},{}],96:[function(require,module,exports){var date=require("load-date");var domify=require("domify");var each=require("each");var integration=require("segmentio/analytics.js-integration");var is=require("is");var useHttps=require("use-https");var onBody=require("on-body");var ClickTale=module.exports=integration("ClickTale").assumesPageview().global("WRInitTime").global("ClickTale").global("ClickTaleSetUID").global("ClickTaleField").global("ClickTaleEvent").option("httpCdnUrl","http://s.clicktale.net/WRe0.js").option("httpsCdnUrl","").option("projectId","").option("recordingRatio",.01).option("partitionId","").tag('<script src="{{src}}">');ClickTale.prototype.initialize=function(page){var self=this;window.WRInitTime=date.getTime();onBody(function(body){body.appendChild(domify('<div id="ClickTaleDiv" style="display: none;">'))});var http=this.options.httpCdnUrl;var https=this.options.httpsCdnUrl;if(useHttps()&&!https)return this.debug("https option required");var src=useHttps()?https:http;this.load({src:src},function(){window.ClickTale(self.options.projectId,self.options.recordingRatio,self.options.partitionId);self.ready()})};ClickTale.prototype.loaded=function(){return is.fn(window.ClickTale)};ClickTale.prototype.identify=function(identify){var id=identify.userId();window.ClickTaleSetUID(id);each(identify.traits(),function(key,value){window.ClickTaleField(key,value)})};ClickTale.prototype.track=function(track){window.ClickTaleEvent(track.event())}},{"load-date":191,domify:181,each:5,"segmentio/analytics.js-integration":159,is:18,"use-https":161,"on-body":180}],191:[function(require,module,exports){var time=new Date,perf=window.performance;if(perf&&perf.timing&&perf.timing.responseEnd){time=new Date(perf.timing.responseEnd)}module.exports=time},{}],97:[function(require,module,exports){var Identify=require("facade").Identify;var extend=require("extend");var integration=require("segmentio/analytics.js-integration");var is=require("is");var Clicky=module.exports=integration("Clicky").assumesPageview().global("clicky").global("clicky_site_ids").global("clicky_custom").option("siteId",null).tag('<script src="//static.getclicky.com/js"></script>');Clicky.prototype.initialize=function(page){var user=this.analytics.user();window.clicky_site_ids=window.clicky_site_ids||[this.options.siteId];this.identify(new Identify({userId:user.id(),traits:user.traits()}));this.load(this.ready)};Clicky.prototype.loaded=function(){return is.object(window.clicky)};Clicky.prototype.page=function(page){var properties=page.properties();var category=page.category();var name=page.fullName();window.clicky.log(properties.path,name||properties.title)};Clicky.prototype.identify=function(identify){window.clicky_custom=window.clicky_custom||{};window.clicky_custom.session=window.clicky_custom.session||{};extend(window.clicky_custom.session,identify.traits())};Clicky.prototype.track=function(track){window.clicky.goal(track.event(),track.revenue())}},{facade:27,extend:40,"segmentio/analytics.js-integration":159,is:18}],98:[function(require,module,exports){var integration=require("segmentio/analytics.js-integration");var useHttps=require("use-https");var Comscore=module.exports=integration("comScore").assumesPageview().global("_comscore").global("COMSCORE").option("c1","2").option("c2","").tag("http",'<script src="http://b.scorecardresearch.com/beacon.js">').tag("https",'<script src="https://sb.scorecardresearch.com/beacon.js">');Comscore.prototype.initialize=function(page){window._comscore=window._comscore||[this.options];var name=useHttps()?"https":"http";this.load(name,this.ready)};Comscore.prototype.loaded=function(){return!!window.COMSCORE}},{"segmentio/analytics.js-integration":159,"use-https":161}],99:[function(require,module,exports){var integration=require("segmentio/analytics.js-integration");var CrazyEgg=module.exports=integration("Crazy Egg").assumesPageview().global("CE2").option("accountNumber","").tag('<script src="//dnn506yrbagrg.cloudfront.net/pages/scripts/{{ path }}.js?{{ cache }}">');CrazyEgg.prototype.initialize=function(page){var number=this.options.accountNumber;var path=number.slice(0,4)+"/"+number.slice(4);var cache=Math.floor((new Date).getTime()/36e5);this.load({path:path,cache:cache},this.ready)};CrazyEgg.prototype.loaded=function(){return!!window.CE2}},{"segmentio/analytics.js-integration":159}],100:[function(require,module,exports){var integration=require("segmentio/analytics.js-integration");var push=require("global-queue")("_curebitq");var Identify=require("facade").Identify;var throttle=require("throttle");var Track=require("facade").Track;var iso=require("to-iso-string");var clone=require("clone");var each=require("each");var bind=require("bind");var Curebit=module.exports=integration("Curebit").global("_curebitq").global("curebit").option("siteId","").option("iframeWidth","100%").option("iframeHeight","480").option("iframeBorder",0).option("iframeId","curebit_integration").option("responsive",true).option("device","").option("insertIntoId","").option("campaigns",{}).option("server","https://www.curebit.com").tag('<script src="//d2jjzw81hqbuqv.cloudfront.net/integration/curebit-1.0.min.js">');Curebit.prototype.initialize=function(page){push("init",{site_id:this.options.siteId,server:this.options.server});this.load(this.ready);this.page=throttle(bind(this,this.page),250)};Curebit.prototype.loaded=function(){return!!window.curebit};Curebit.prototype.injectIntoId=function(url,id,fn){var server=this.options.server;when(function(){return document.getElementById(id)},function(){var script=document.createElement("script");script.src=url;var parent=document.getElementById(id);parent.appendChild(script);onload(script,fn)})};Curebit.prototype.page=function(page){var user=this.analytics.user();var campaigns=this.options.campaigns;var path=window.location.pathname;if(!campaigns[path])return;var tags=(campaigns[path]||"").split(",");if(!tags.length)return;var settings={responsive:this.options.responsive,device:this.options.device,campaign_tags:tags,iframe:{width:this.options.iframeWidth,height:this.options.iframeHeight,id:this.options.iframeId,frameborder:this.options.iframeBorder,container:this.options.insertIntoId}};var identify=new Identify({userId:user.id(),traits:user.traits()});if(identify.email()){settings.affiliate_member={email:identify.email(),first_name:identify.firstName(),last_name:identify.lastName(),customer_id:identify.userId()}}push("register_affiliate",settings)};Curebit.prototype.completedOrder=function(track){var user=this.analytics.user();var orderId=track.orderId();var products=track.products();var props=track.properties();var items=[];var identify=new Identify({traits:user.traits(),userId:user.id()});each(products,function(product){var track=new Track({properties:product});items.push({product_id:track.id()||track.sku(),quantity:track.quantity(),image_url:product.image,price:track.price(),title:track.name(),url:product.url})});push("register_purchase",{order_date:iso(props.date||new Date),order_number:orderId,coupon_code:track.coupon(),subtotal:track.total(),customer_id:identify.userId(),first_name:identify.firstName(),last_name:identify.lastName(),email:identify.email(),items:items})}},{"segmentio/analytics.js-integration":159,"global-queue":190,facade:27,throttle:192,"to-iso-string":193,clone:194,each:5,bind:33}],192:[function(require,module,exports){module.exports=throttle;function throttle(func,wait){var rtn;var last=0;return function throttled(){var now=(new Date).getTime();var delta=now-last;if(delta>=wait){rtn=func.apply(this,arguments);last=now}return rtn}}},{}],193:[function(require,module,exports){module.exports=toIsoString;function toIsoString(date){return date.getUTCFullYear()+"-"+pad(date.getUTCMonth()+1)+"-"+pad(date.getUTCDate())+"T"+pad(date.getUTCHours())+":"+pad(date.getUTCMinutes())+":"+pad(date.getUTCSeconds())+"."+String((date.getUTCMilliseconds()/1e3).toFixed(3)).slice(2,5)+"Z"}function pad(number){var n=number.toString();return n.length===1?"0"+n:n}},{}],194:[function(require,module,exports){var type;try{type=require("type")}catch(e){type=require("type-component")}module.exports=clone;function clone(obj){switch(type(obj)){case"object":var copy={};for(var key in obj){if(obj.hasOwnProperty(key)){copy[key]=clone(obj[key])}}return copy;case"array":var copy=new Array(obj.length);for(var i=0,l=obj.length;i<l;i++){copy[i]=clone(obj[i])}return copy;case"regexp":var flags="";flags+=obj.multiline?"m":"";flags+=obj.global?"g":"";flags+=obj.ignoreCase?"i":"";return new RegExp(obj.source,flags);case"date":return new Date(obj.getTime());default:return obj}}},{type:35}],101:[function(require,module,exports){var alias=require("alias");var convertDates=require("convert-dates");var Identify=require("facade").Identify;var integration=require("segmentio/analytics.js-integration");var Customerio=module.exports=integration("Customer.io").assumesPageview().global("_cio").option("siteId","").tag('<script id="cio-tracker" src="https://assets.customer.io/assets/track.js" data-site-id="{{ siteId }}">');Customerio.prototype.initialize=function(page){window._cio=window._cio||[];(function(){var a,b,c;a=function(f){return function(){window._cio.push([f].concat(Array.prototype.slice.call(arguments,0)))}};b=["identify","track"];for(c=0;c<b.length;c++){window._cio[b[c]]=a(b[c])}})();this.load(this.ready)};Customerio.prototype.loaded=function(){return!!(window._cio&&window._cio.pageHasLoaded)};Customerio.prototype.identify=function(identify){if(!identify.userId())return this.debug("user id required");var traits=identify.traits({created:"created_at"});traits=convertDates(traits,convertDate);window._cio.identify(traits)};Customerio.prototype.group=function(group){var traits=group.traits();var user=this.analytics.user();traits=alias(traits,function(trait){return"Group "+trait});this.identify(new Identify({userId:user.id(),traits:traits}))};Customerio.prototype.track=function(track){var properties=track.properties();properties=convertDates(properties,convertDate);window._cio.track(track.event(),properties)};function convertDate(date){return Math.floor(date.getTime()/1e3)}},{alias:195,"convert-dates":196,facade:27,"segmentio/analytics.js-integration":159}],195:[function(require,module,exports){var type=require("type");try{var clone=require("clone")}catch(e){var clone=require("clone-component")}module.exports=alias;function alias(obj,method){switch(type(method)){case"object":return aliasByDictionary(clone(obj),method);case"function":return aliasByFunction(clone(obj),method)}}function aliasByDictionary(obj,aliases){for(var key in aliases){if(undefined===obj[key])continue;obj[aliases[key]]=obj[key];delete obj[key]}return obj}function aliasByFunction(obj,convert){var output={};for(var key in obj)output[convert(key)]=obj[key];return output}},{type:35,clone:62}],196:[function(require,module,exports){var is=require("is");try{var clone=require("clone")}catch(e){var clone=require("clone-component")}module.exports=convertDates;function convertDates(obj,convert){obj=clone(obj);for(var key in obj){var val=obj[key];if(is.date(val))obj[key]=convert(val);if(is.object(val))obj[key]=convertDates(val,convert)}return obj}},{is:18,clone:14}],102:[function(require,module,exports){var alias=require("alias");var integration=require("segmentio/analytics.js-integration");var is=require("is");var load=require("load-script");var push=require("global-queue")("_dcq");var Drip=module.exports=integration("Drip").assumesPageview().global("dc").global("_dcq").global("_dcs").option("account","").tag('<script src="//tag.getdrip.com/{{ account }}.js">');Drip.prototype.initialize=function(page){window._dcq=window._dcq||[];window._dcs=window._dcs||{};window._dcs.account=this.options.account;this.load(this.ready)};Drip.prototype.loaded=function(){return is.object(window.dc)};Drip.prototype.track=function(track){var props=track.properties();var cents=Math.round(track.cents());props.action=track.event();if(cents)props.value=cents;delete props.revenue;push("track",props)}},{alias:195,"segmentio/analytics.js-integration":159,is:18,"load-script":168,"global-queue":190}],103:[function(require,module,exports){var extend=require("extend");var integration=require("segmentio/analytics.js-integration");var onError=require("on-error");var push=require("global-queue")("_errs");var Errorception=module.exports=integration("Errorception").assumesPageview().global("_errs").option("projectId","").option("meta",true).tag('<script src="//beacon.errorception.com/{{ projectId }}.js">');Errorception.prototype.initialize=function(page){window._errs=window._errs||[this.options.projectId];onError(push);this.load(this.ready)};Errorception.prototype.loaded=function(){return!!(window._errs&&window._errs.push!==Array.prototype.push)};Errorception.prototype.identify=function(identify){if(!this.options.meta)return;var traits=identify.traits();window._errs=window._errs||[];window._errs.meta=window._errs.meta||{};extend(window._errs.meta,traits)}},{extend:40,"segmentio/analytics.js-integration":159,"on-error":188,"global-queue":190}],104:[function(require,module,exports){var each=require("each");var integration=require("segmentio/analytics.js-integration");var push=require("global-queue")("_aaq");var Evergage=module.exports=integration("Evergage").assumesPageview().global("_aaq").option("account","").option("dataset","").tag('<script src="//cdn.evergage.com/beacon/{{ account }}/{{ dataset }}/scripts/evergage.min.js">');Evergage.prototype.initialize=function(page){var account=this.options.account;var dataset=this.options.dataset;window._aaq=window._aaq||[];push("setEvergageAccount",account);push("setDataset",dataset);push("setUseSiteConfig",true);this.load(this.ready)};Evergage.prototype.loaded=function(){return!!(window._aaq&&window._aaq.push!==Array.prototype.push)};Evergage.prototype.page=function(page){var props=page.properties();var name=page.name();if(name)push("namePage",name);each(props,function(key,value){push("setCustomField",key,value,"page")});window.Evergage.init(true)};Evergage.prototype.identify=function(identify){var id=identify.userId();if(!id)return;push("setUser",id);var traits=identify.traits({email:"userEmail",name:"userName"});each(traits,function(key,value){push("setUserField",key,value,"page")})};Evergage.prototype.group=function(group){var props=group.traits();var id=group.groupId();if(!id)return;push("setCompany",id);each(props,function(key,value){push("setAccountField",key,value,"page")})};Evergage.prototype.track=function(track){push("trackAction",track.event(),track.properties())}},{each:5,"segmentio/analytics.js-integration":159,"global-queue":190}],105:[function(require,module,exports){var integration=require("segmentio/analytics.js-integration");var push=require("global-queue")("_fbq");var each=require("each");var has=Object.prototype.hasOwnProperty;var Facebook=module.exports=integration("Facebook Ads").global("_fbq").option("currency","USD").tag('<script src="//connect.facebook.net/en_US/fbds.js">').mapping("events");Facebook.prototype.initialize=function(page){window._fbq=window._fbq||[];this.load(this.ready);window._fbq.loaded=true};Facebook.prototype.loaded=function(){return!!(window._fbq&&window._fbq.loaded)};Facebook.prototype.track=function(track){var event=track.event();var events=this.events(event);var revenue=track.revenue()||0;var self=this;each(events,function(event){push("track",event,{value:String(revenue.toFixed(2)),currency:self.options.currency})});if(!events.length){var data=track.properties();push("track",event,data)}}},{"segmentio/analytics.js-integration":159,"global-queue":190,each:5}],106:[function(require,module,exports){var push=require("global-queue")("_fxm");var integration=require("segmentio/analytics.js-integration");var Track=require("facade").Track;var each=require("each");var FoxMetrics=module.exports=integration("FoxMetrics").assumesPageview().global("_fxm").option("appId","").tag('<script src="//d35tca7vmefkrc.cloudfront.net/scripts/{{ appId }}.js">');FoxMetrics.prototype.initialize=function(page){window._fxm=window._fxm||[];this.load(this.ready)};FoxMetrics.prototype.loaded=function(){return!!(window._fxm&&window._fxm.appId)};FoxMetrics.prototype.page=function(page){var properties=page.proxy("properties");var category=page.category();var name=page.name();this._category=category;push("_fxm.pages.view",properties.title,name,category,properties.url,properties.referrer)};FoxMetrics.prototype.identify=function(identify){var id=identify.userId();if(!id)return;push("_fxm.visitor.profile",id,identify.firstName(),identify.lastName(),identify.email(),identify.address(),undefined,undefined,identify.traits())};FoxMetrics.prototype.track=function(track){var props=track.properties();var category=this._category||props.category;push(track.event(),category,props)};FoxMetrics.prototype.viewedProduct=function(track){ecommerce("productview",track)};FoxMetrics.prototype.removedProduct=function(track){ecommerce("removecartitem",track)};FoxMetrics.prototype.addedProduct=function(track){ecommerce("cartitem",track)};FoxMetrics.prototype.completedOrder=function(track){var orderId=track.orderId();push("_fxm.ecommerce.order",orderId,track.subtotal(),track.shipping(),track.tax(),track.city(),track.state(),track.zip(),track.quantity());each(track.products(),function(product){var track=new Track({properties:product});ecommerce("purchaseitem",track,[track.quantity(),track.price(),orderId])})};function ecommerce(event,track,arr){push.apply(null,["_fxm.ecommerce."+event,track.id()||track.sku(),track.name(),track.category()].concat(arr||[]))}},{"global-queue":190,"segmentio/analytics.js-integration":159,facade:27,each:5}],107:[function(require,module,exports){var integration=require("segmentio/analytics.js-integration");var bind=require("bind");var when=require("when");var is=require("is");var Frontleaf=module.exports=integration("Frontleaf").assumesPageview().global("_fl").global("_flBaseUrl").option("baseUrl","https://api.frontleaf.com").option("token","").option("stream","").option("trackNamedPages",false).option("trackCategorizedPages",false).tag('<script id="_fl" src="{{ baseUrl }}/lib/tracker.js">');Frontleaf.prototype.initialize=function(page){window._fl=window._fl||[];window._flBaseUrl=window._flBaseUrl||this.options.baseUrl;this._push("setApiToken",this.options.token);this._push("setStream",this.options.stream);var loaded=bind(this,this.loaded);var ready=this.ready;this.load({baseUrl:window._flBaseUrl},this.ready)};Frontleaf.prototype.loaded=function(){return is.array(window._fl)&&window._fl.ready===true};Frontleaf.prototype.identify=function(identify){var userId=identify.userId();if(userId){this._push("setUser",{id:userId,name:identify.name()||identify.username(),data:clean(identify.traits())})}};Frontleaf.prototype.group=function(group){var groupId=group.groupId();if(groupId){this._push("setAccount",{id:groupId,name:group.proxy("traits.name"),data:clean(group.traits())})}};Frontleaf.prototype.page=function(page){var category=page.category();var name=page.fullName();var opts=this.options;if(category&&opts.trackCategorizedPages){this.track(page.track(category))}if(name&&opts.trackNamedPages){this.track(page.track(name))}};Frontleaf.prototype.track=function(track){var event=track.event();this._push("event",event,clean(track.properties()))};Frontleaf.prototype._push=function(command){var args=[].slice.call(arguments,1);window._fl.push(function(t){t[command].apply(command,args)})};function clean(obj){var ret={};var excludeKeys=["id","name","firstName","lastName"];var len=excludeKeys.length;for(var i=0;i<len;i++){clear(obj,excludeKeys[i])}obj=flatten(obj);for(var key in obj){var val=obj[key];if(null==val){continue}if(is.array(val)){ret[key]=val.toString();continue}ret[key]=val }return ret}function clear(obj,key){if(obj.hasOwnProperty(key)){delete obj[key]}}function flatten(source){var output={};function step(object,prev){for(var key in object){var value=object[key];var newKey=prev?prev+" "+key:key;if(!is.array(value)&&is.object(value)){return step(value,newKey)}output[newKey]=value}}step(source);return output}},{"segmentio/analytics.js-integration":159,bind:33,when:184,is:18}],108:[function(require,module,exports){var integration=require("segmentio/analytics.js-integration");var push=require("global-queue")("_gauges");var Gauges=module.exports=integration("Gauges").assumesPageview().global("_gauges").option("siteId","").tag('<script id="gauges-tracker" src="//secure.gaug.es/track.js" data-site-id="{{ siteId }}">');Gauges.prototype.initialize=function(page){window._gauges=window._gauges||[];this.load(this.ready)};Gauges.prototype.loaded=function(){return!!(window._gauges&&window._gauges.push!==Array.prototype.push)};Gauges.prototype.page=function(page){push("track")}},{"segmentio/analytics.js-integration":159,"global-queue":190}],109:[function(require,module,exports){var integration=require("segmentio/analytics.js-integration");var onBody=require("on-body");var GetSatisfaction=module.exports=integration("Get Satisfaction").assumesPageview().global("GSFN").option("widgetId","").tag('<script src="https://loader.engage.gsfn.us/loader.js">');GetSatisfaction.prototype.initialize=function(page){var self=this;var widget=this.options.widgetId;var div=document.createElement("div");var id=div.id="getsat-widget-"+widget;onBody(function(body){body.appendChild(div)});this.load(function(){window.GSFN.loadWidget(widget,{containerId:id});self.ready()})};GetSatisfaction.prototype.loaded=function(){return!!window.GSFN}},{"segmentio/analytics.js-integration":159,"on-body":180}],110:[function(require,module,exports){var integration=require("segmentio/analytics.js-integration");var push=require("global-queue")("_gaq");var length=require("object").length;var canonical=require("canonical");var useHttps=require("use-https");var Track=require("facade").Track;var callback=require("callback");var load=require("load-script");var keys=require("object").keys;var dot=require("obj-case");var each=require("each");var type=require("type");var url=require("url");var is=require("is");var group;var user;module.exports=exports=function(analytics){analytics.addIntegration(GA);group=analytics.group();user=analytics.user()};var GA=exports.Integration=integration("Google Analytics").readyOnLoad().global("ga").global("gaplugins").global("_gaq").global("GoogleAnalyticsObject").option("anonymizeIp",false).option("classic",false).option("domain","none").option("doubleClick",false).option("enhancedLinkAttribution",false).option("ignoredReferrers",null).option("includeSearch",false).option("siteSpeedSampleRate",1).option("trackingId","").option("trackNamedPages",true).option("trackCategorizedPages",true).option("sendUserId",false).option("metrics",{}).option("dimensions",{}).tag("library",'<script src="//www.google-analytics.com/analytics.js">').tag("double click",'<script src="//stats.g.doubleclick.net/dc.js">').tag("http",'<script src="http://www.google-analytics.com/ga.js">').tag("https",'<script src="https://ssl.google-analytics.com/ga.js">');GA.on("construct",function(integration){if(!integration.options.classic)return;integration.initialize=integration.initializeClassic;integration.loaded=integration.loadedClassic;integration.page=integration.pageClassic;integration.track=integration.trackClassic;integration.completedOrder=integration.completedOrderClassic});GA.prototype.initialize=function(){var opts=this.options;window.GoogleAnalyticsObject="ga";window.ga=window.ga||function(){window.ga.q=window.ga.q||[];window.ga.q.push(arguments)};window.ga.l=(new Date).getTime();window.ga("create",opts.trackingId,{cookieDomain:opts.domain||GA.prototype.defaults.domain,siteSpeedSampleRate:opts.siteSpeedSampleRate,allowLinker:true});if(opts.doubleClick){window.ga("require","displayfeatures")}if(opts.sendUserId&&user.id()){window.ga("set","&uid",user.id())}if(opts.anonymizeIp)window.ga("set","anonymizeIp",true);var custom=metrics(user.traits(),opts);if(length(custom))window.ga("set",custom);this.load("library",this.ready)};GA.prototype.loaded=function(){return!!window.gaplugins};GA.prototype.page=function(page){var category=page.category();var props=page.properties();var name=page.fullName();var pageview={};var track;this._category=category;window.ga("send","pageview",{page:path(props,this.options),title:name||props.title,location:props.url});if(category&&this.options.trackCategorizedPages){track=page.track(category);this.track(track,{noninteraction:true})}if(name&&this.options.trackNamedPages){track=page.track(name);this.track(track,{noninteraction:true})}};GA.prototype.track=function(track,options){var opts=options||track.options(this.name);var props=track.properties();window.ga("send","event",{eventAction:track.event(),eventCategory:props.category||this._category||"All",eventLabel:props.label,eventValue:formatValue(props.value||track.revenue()),nonInteraction:props.noninteraction||opts.noninteraction})};GA.prototype.completedOrder=function(track){var total=track.total()||track.revenue()||0;var orderId=track.orderId();var products=track.products();var props=track.properties();if(!orderId)return;if(!this.ecommerce){window.ga("require","ecommerce","ecommerce.js");this.ecommerce=true}window.ga("ecommerce:addTransaction",{affiliation:props.affiliation,shipping:track.shipping(),revenue:total,tax:track.tax(),id:orderId});each(products,function(product){var track=new Track({properties:product});window.ga("ecommerce:addItem",{category:track.category(),quantity:track.quantity(),price:track.price(),name:track.name(),sku:track.sku(),id:orderId})});window.ga("ecommerce:send")};GA.prototype.initializeClassic=function(){var opts=this.options;var anonymize=opts.anonymizeIp;var db=opts.doubleClick;var domain=opts.domain;var enhanced=opts.enhancedLinkAttribution;var ignore=opts.ignoredReferrers;var sample=opts.siteSpeedSampleRate;window._gaq=window._gaq||[];push("_setAccount",opts.trackingId);push("_setAllowLinker",true);if(anonymize)push("_gat._anonymizeIp");if(domain)push("_setDomainName",domain);if(sample)push("_setSiteSpeedSampleRate",sample);if(enhanced){var protocol="https:"===document.location.protocol?"https:":"http:";var pluginUrl=protocol+"//www.google-analytics.com/plugins/ga/inpage_linkid.js";push("_require","inpage_linkid",pluginUrl)}if(ignore){if(!is.array(ignore))ignore=[ignore];each(ignore,function(domain){push("_addIgnoredRef",domain)})}if(this.options.doubleClick){this.load("double click",this.ready)}else{var name=useHttps()?"https":"http";this.load(name,this.ready)}};GA.prototype.loadedClassic=function(){return!!(window._gaq&&window._gaq.push!==Array.prototype.push)};GA.prototype.pageClassic=function(page){var opts=page.options(this.name);var category=page.category();var props=page.properties();var name=page.fullName();var track;push("_trackPageview",path(props,this.options));if(category&&this.options.trackCategorizedPages){track=page.track(category);this.track(track,{noninteraction:true})}if(name&&this.options.trackNamedPages){track=page.track(name);this.track(track,{noninteraction:true})}};GA.prototype.trackClassic=function(track,options){var opts=options||track.options(this.name);var props=track.properties();var revenue=track.revenue();var event=track.event();var category=this._category||props.category||"All";var label=props.label;var value=formatValue(revenue||props.value);var noninteraction=props.noninteraction||opts.noninteraction;push("_trackEvent",category,event,label,value,noninteraction)};GA.prototype.completedOrderClassic=function(track){var total=track.total()||track.revenue()||0;var orderId=track.orderId();var products=track.products()||[];var props=track.properties();if(!orderId)return;push("_addTrans",orderId,props.affiliation,total,track.tax(),track.shipping(),track.city(),track.state(),track.country());each(products,function(product){var track=new Track({properties:product});push("_addItem",orderId,track.sku(),track.name(),track.category(),track.price(),track.quantity())});push("_trackTrans")};function path(properties,options){if(!properties)return;var str=properties.path;if(options.includeSearch&&properties.search)str+=properties.search;return str}function formatValue(value){if(!value||value<0)return 0;return Math.round(value)}function metrics(obj,data){var dimensions=data.dimensions;var metrics=data.metrics;var names=keys(metrics).concat(keys(dimensions));var ret={};for(var i=0;i<names.length;++i){var name=names[i];var key=metrics[name]||dimensions[name];var value=dot(obj,name);if(null==value)continue;ret[key]=value}return ret}},{"segmentio/analytics.js-integration":159,"global-queue":190,object:25,canonical:13,"use-https":161,facade:27,callback:12,"load-script":168,"obj-case":60,each:5,type:35,url:26,is:18}],111:[function(require,module,exports){var push=require("global-queue")("dataLayer",{wrap:false});var integration=require("segmentio/analytics.js-integration");var GTM=module.exports=integration("Google Tag Manager").assumesPageview().global("dataLayer").global("google_tag_manager").option("containerId","").option("trackNamedPages",true).option("trackCategorizedPages",true).tag('<script src="//www.googletagmanager.com/gtm.js?id={{ containerId }}&l=dataLayer">');GTM.prototype.initialize=function(){push({"gtm.start":+new Date,event:"gtm.js"});this.load(this.ready)};GTM.prototype.loaded=function(){return!!(window.dataLayer&&[].push!=window.dataLayer.push)};GTM.prototype.page=function(page){var category=page.category();var props=page.properties();var name=page.fullName();var opts=this.options;var track;if(opts.trackAllPages){this.track(page.track())}if(category&&opts.trackCategorizedPages){this.track(page.track(category))}if(name&&opts.trackNamedPages){this.track(page.track(name))}};GTM.prototype.track=function(track){var props=track.properties();props.event=track.event();push(props)}},{"global-queue":190,"segmentio/analytics.js-integration":159}],112:[function(require,module,exports){var integration=require("segmentio/analytics.js-integration");var Identify=require("facade").Identify;var Track=require("facade").Track;var callback=require("callback");var load=require("load-script");var onBody=require("on-body");var each=require("each");var GoSquared=module.exports=integration("GoSquared").assumesPageview().global("_gs").option("siteToken","").option("anonymizeIP",false).option("cookieDomain",null).option("useCookies",true).option("trackHash",false).option("trackLocal",false).option("trackParams",true).tag('<script src="//d1l6p2sc9645hc.cloudfront.net/tracker.js">');GoSquared.prototype.initialize=function(page){var self=this;var options=this.options;var user=this.analytics.user();push(options.siteToken);each(options,function(name,value){if("siteToken"==name)return;if(null==value)return;push("set",name,value)});self.identify(new Identify({traits:user.traits(),userId:user.id()}));self.load(this.ready)};GoSquared.prototype.loaded=function(){return!!(window._gs&&window._gs.v)};GoSquared.prototype.page=function(page){var props=page.properties();var name=page.fullName();push("track",props.path,name||props.title)};GoSquared.prototype.identify=function(identify){var traits=identify.traits({userId:"userID"});var username=identify.username();var email=identify.email();var id=identify.userId();if(id)push("set","visitorID",id);var name=email||username||id;if(name)push("set","visitorName",name);push("set","visitor",traits)};GoSquared.prototype.track=function(track){push("event",track.event(),track.properties())};GoSquared.prototype.completedOrder=function(track){var products=track.products();var items=[];each(products,function(product){var track=new Track({properties:product});items.push({category:track.category(),quantity:track.quantity(),price:track.price(),name:track.name()})});push("transaction",track.orderId(),{revenue:track.total(),track:true},items)};function push(){var _gs=window._gs=window._gs||function(){(_gs.q=_gs.q||[]).push(arguments)};_gs.apply(null,arguments)}},{"segmentio/analytics.js-integration":159,facade:27,callback:12,"load-script":168,"on-body":180,each:5}],113:[function(require,module,exports){var integration=require("segmentio/analytics.js-integration");var alias=require("alias");var Heap=module.exports=integration("Heap").assumesPageview().global("heap").global("_heapid").option("apiKey","").tag('<script src="//d36lvucg9kzous.cloudfront.net">');Heap.prototype.initialize=function(page){window.heap=window.heap||[];window.heap.load=function(a){window._heapid=a;var d=function(a){return function(){window.heap.push([a].concat(Array.prototype.slice.call(arguments,0)))}},e=["identify","track"];for(var f=0;f<e.length;f++)window.heap[e[f]]=d(e[f])};window.heap.load(this.options.apiKey);this.load(this.ready)};Heap.prototype.loaded=function(){return window.heap&&window.heap.appid};Heap.prototype.identify=function(identify){var traits=identify.traits();var username=identify.username();var id=identify.userId();var handle=username||id;if(handle)traits.handle=handle;delete traits.username;window.heap.identify(traits)};Heap.prototype.track=function(track){window.heap.track(track.event(),track.properties())}},{"segmentio/analytics.js-integration":159,alias:195}],114:[function(require,module,exports){var integration=require("segmentio/analytics.js-integration");var Hellobar=module.exports=integration("Hello Bar").assumesPageview().global("_hbq").option("apiKey","").tag('<script src="//s3.amazonaws.com/scripts.hellobar.com/{{ apiKey }}.js">');Hellobar.prototype.initialize=function(page){window._hbq=window._hbq||[];this.load(this.ready)};Hellobar.prototype.loaded=function(){return!!(window._hbq&&window._hbq.push!==Array.prototype.push)}},{"segmentio/analytics.js-integration":159}],115:[function(require,module,exports){var integration=require("segmentio/analytics.js-integration");var is=require("is");var HitTail=module.exports=integration("HitTail").assumesPageview().global("htk").option("siteId","").tag('<script src="//{{ siteId }}.hittail.com/mlt.js">');HitTail.prototype.initialize=function(page){this.load(this.ready)};HitTail.prototype.loaded=function(){return is.fn(window.htk)}},{"segmentio/analytics.js-integration":159,is:18}],116:[function(require,module,exports){var integration=require("analytics.js-integration");var Hublo=module.exports=integration("Hublo").assumesPageview().global("_hublo_").option("apiKey",null).tag('<script src="//cdn.hublo.co/{{ apiKey }}.js">');Hublo.prototype.initialize=function(page){this.load(this.ready)};Hublo.prototype.loaded=function(){return!!(window._hublo_&&typeof window._hublo_.setup==="function")}},{"analytics.js-integration":159}],117:[function(require,module,exports){var integration=require("segmentio/analytics.js-integration");var push=require("global-queue")("_hsq");var convert=require("convert-dates");var HubSpot=module.exports=integration("HubSpot").assumesPageview().global("_hsq").option("portalId",null).tag('<script id="hs-analytics" src="https://js.hs-analytics.net/analytics/{{ cache }}/{{ portalId }}.js">');HubSpot.prototype.initialize=function(page){window._hsq=[];var cache=Math.ceil(new Date/3e5)*3e5;this.load({cache:cache},this.ready)};HubSpot.prototype.loaded=function(){return!!(window._hsq&&window._hsq.push!==Array.prototype.push)};HubSpot.prototype.page=function(page){push("_trackPageview")};HubSpot.prototype.identify=function(identify){if(!identify.email())return;var traits=identify.traits();traits=convertDates(traits);push("identify",traits)};HubSpot.prototype.track=function(track){var props=track.properties();props=convertDates(props);push("trackEvent",track.event(),props)};function convertDates(properties){return convert(properties,function(date){return date.getTime()})}},{"segmentio/analytics.js-integration":159,"global-queue":190,"convert-dates":196}],118:[function(require,module,exports){var integration=require("segmentio/analytics.js-integration");var alias=require("alias");var Improvely=module.exports=integration("Improvely").assumesPageview().global("_improvely").global("improvely").option("domain","").option("projectId",null).tag('<script src="//{{ domain }}.iljmp.com/improvely.js">');Improvely.prototype.initialize=function(page){window._improvely=[];window.improvely={init:function(e,t){window._improvely.push(["init",e,t])},goal:function(e){window._improvely.push(["goal",e])},label:function(e){window._improvely.push(["label",e])}};var domain=this.options.domain;var id=this.options.projectId;window.improvely.init(domain,id);this.load(this.ready)};Improvely.prototype.loaded=function(){return!!(window.improvely&&window.improvely.identify)};Improvely.prototype.identify=function(identify){var id=identify.userId();if(id)window.improvely.label(id)};Improvely.prototype.track=function(track){var props=track.properties({revenue:"amount"});props.type=track.event();window.improvely.goal(props)}},{"segmentio/analytics.js-integration":159,alias:195}],119:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_iva");var is=require("is");var InsideVault=module.exports=integration("InsideVault").global("_iva").option("clientId","").option("domain","").tag('<script src="//analytics.staticiv.com/iva.js">');InsideVault.prototype.initialize=function(page){var domain=this.options.domain;window._iva=window._iva||[];push("setClientId",this.options.clientId);if(domain)push("setDomain",domain);this.load(this.ready)};InsideVault.prototype.loaded=function(){return!!(window._iva&&window._iva.push!==Array.prototype.push)};InsideVault.prototype.track=function(track){var event=track.event();var value=track.revenue()||track.value()||0;var orderId=track.orderId()||"";if(event!="sale"){push("trackEvent",event,value,orderId)}}},{"analytics.js-integration":159,"global-queue":190,is:18}],120:[function(require,module,exports){var integration=require("segmentio/analytics.js-integration");var push=require("global-queue")("__insp");var alias=require("alias");var clone=require("clone");var Inspectlet=module.exports=integration("Inspectlet").assumesPageview().global("__insp").global("__insp_").option("wid","").tag('<script src="//www.inspectlet.com/inspectlet.js">');Inspectlet.prototype.initialize=function(page){push("wid",this.options.wid);this.load(this.ready)};Inspectlet.prototype.loaded=function(){return!!window.__insp_};Inspectlet.prototype.identify=function(identify){var traits=identify.traits({id:"userid"});push("tagSession",traits)};Inspectlet.prototype.track=function(track){push("tagSession",track.event())}},{"segmentio/analytics.js-integration":159,"global-queue":190,alias:195,clone:194}],121:[function(require,module,exports){var integration=require("segmentio/analytics.js-integration");var convertDates=require("convert-dates");var defaults=require("defaults");var isEmail=require("is-email");var load=require("load-script");var empty=require("is-empty");var alias=require("alias");var each=require("each");var when=require("when");var is=require("is");var Intercom=module.exports=integration("Intercom").assumesPageview().global("Intercom").option("activator","#IntercomDefaultWidget").option("appId","").option("inbox",false).tag('<script src="https://static.intercomcdn.com/intercom.v1.js">');Intercom.prototype.initialize=function(page){var self=this;this.load(function(){when(function(){return self.loaded()},self.ready)})};Intercom.prototype.loaded=function(){return is.fn(window.Intercom)};Intercom.prototype.page=function(page){window.Intercom("update")};Intercom.prototype.identify=function(identify){var traits=identify.traits({userId:"user_id"});var activator=this.options.activator;var opts=identify.options(this.name);var companyCreated=identify.companyCreated();var created=identify.created();var email=identify.email();var name=identify.name();var id=identify.userId();var group=this.analytics.group();if(!id&&!traits.email)return;traits.app_id=this.options.appId;if(null!=traits.company&&!is.object(traits.company))delete traits.company;if(traits.company)defaults(traits.company,group.traits());if(name)traits.name=name;if(traits.company&&companyCreated)traits.company.created=companyCreated;if(created)traits.created=created;traits=convertDates(traits,formatDate);traits=alias(traits,{created:"created_at"});if(traits.company)traits.company=alias(traits.company,{created:"created_at"});if(opts.increments)traits.increments=opts.increments;if(opts.userHash)traits.user_hash=opts.userHash;if(opts.user_hash)traits.user_hash=opts.user_hash;if("#IntercomDefaultWidget"!=activator){traits.widget={activator:activator}}var method=this._id!==id?"boot":"update";this._id=id;window.Intercom(method,traits)};Intercom.prototype.group=function(group){var props=group.properties();var id=group.groupId();if(id)props.id=id;window.Intercom("update",{company:props})};Intercom.prototype.track=function(track){window.Intercom("trackEvent",track.event(),track.properties())};function formatDate(date){return Math.floor(date/1e3)}},{"segmentio/analytics.js-integration":159,"convert-dates":196,defaults:189,"is-email":19,"load-script":168,"is-empty":44,alias:195,each:5,when:184,is:18}],122:[function(require,module,exports){var integration=require("segmentio/analytics.js-integration");var Keen=module.exports=integration("Keen IO").global("Keen").option("projectId","").option("readKey","").option("writeKey","").option("trackNamedPages",true).option("trackAllPages",false).option("trackCategorizedPages",true).tag('<script src="//dc8na2hxrj29i.cloudfront.net/code/keen-2.1.0-min.js">');Keen.prototype.initialize=function(){var options=this.options;window.Keen=window.Keen||{configure:function(e){this._cf=e},addEvent:function(e,t,n,i){this._eq=this._eq||[],this._eq.push([e,t,n,i])},setGlobalProperties:function(e){this._gp=e},onChartsReady:function(e){this._ocrq=this._ocrq||[],this._ocrq.push(e)}};window.Keen.configure({projectId:options.projectId,writeKey:options.writeKey,readKey:options.readKey});this.load(this.ready)};Keen.prototype.loaded=function(){return!!(window.Keen&&window.Keen.Base64)};Keen.prototype.page=function(page){var category=page.category();var props=page.properties();var name=page.fullName();var opts=this.options;if(opts.trackAllPages){this.track(page.track())}if(name&&opts.trackNamedPages){this.track(page.track(name))}if(category&&opts.trackCategorizedPages){this.track(page.track(category))}};Keen.prototype.identify=function(identify){var traits=identify.traits();var id=identify.userId();var user={};if(id)user.userId=id;if(traits)user.traits=traits;window.Keen.setGlobalProperties(function(){return{user:user}})};Keen.prototype.track=function(track){window.Keen.addEvent(track.event(),track.properties())}},{"segmentio/analytics.js-integration":159}],123:[function(require,module,exports){var integration=require("segmentio/analytics.js-integration");var indexof=require("indexof");var is=require("is");var Kenshoo=module.exports=integration("Kenshoo").global("k_trackevent").option("cid","").option("subdomain","").option("events",[]).tag('<script src="//{{ subdomain }}.xg4ken.com/media/getpx.php?cid={{ cid }}">');Kenshoo.prototype.initialize=function(page){this.load(this.ready)};Kenshoo.prototype.loaded=function(){return is.fn(window.k_trackevent)};Kenshoo.prototype.track=function(track){var events=this.options.events;var traits=track.traits();var event=track.event();var revenue=track.revenue()||0;if(!~indexof(events,event))return;var params=["id="+this.options.cid,"type=conv","val="+revenue,"orderId="+track.orderId(),"promoCode="+track.coupon(),"valueCurrency="+track.currency(),"GCID=","kw=","product="];window.k_trackevent(params,this.options.subdomain)}},{"segmentio/analytics.js-integration":159,indexof:46,is:18}],124:[function(require,module,exports){var integration=require("segmentio/analytics.js-integration");var push=require("global-queue")("_kmq");var Track=require("facade").Track;var alias=require("alias");var Batch=require("batch");var each=require("each");var is=require("is");var KISSmetrics=module.exports=integration("KISSmetrics").assumesPageview().global("_kmq").global("KM").global("_kmil").option("apiKey","").option("trackNamedPages",true).option("trackCategorizedPages",true).option("prefixProperties",true).tag("useless",'<script src="//i.kissmetrics.com/i.js">').tag("library",'<script src="//doug1izaerwt3.cloudfront.net/{{ apiKey }}.1.js">');exports.isMobile=navigator.userAgent.match(/Android/i)||navigator.userAgent.match(/BlackBerry/i)||navigator.userAgent.match(/iPhone|iPod/i)||navigator.userAgent.match(/iPad/i)||navigator.userAgent.match(/Opera Mini/i)||navigator.userAgent.match(/IEMobile/i);KISSmetrics.prototype.initialize=function(page){var self=this;window._kmq=[];if(exports.isMobile)push("set",{"Mobile Session":"Yes"});var batch=new Batch;batch.push(function(done){self.load("useless",done)});batch.push(function(done){self.load("library",done)});batch.end(function(){self.trackPage(page);self.ready()})};KISSmetrics.prototype.loaded=function(){return is.object(window.KM)};KISSmetrics.prototype.page=function(page){if(!window.KM_SKIP_PAGE_VIEW)window.KM.pageView();this.trackPage(page)};KISSmetrics.prototype.trackPage=function(page){var category=page.category();var name=page.fullName();var opts=this.options;if(name&&opts.trackNamedPages){this.track(page.track(name))}if(category&&opts.trackCategorizedPages){this.track(page.track(category))}};KISSmetrics.prototype.identify=function(identify){var traits=identify.traits();var id=identify.userId();if(id)push("identify",id);if(traits)push("set",traits)};KISSmetrics.prototype.track=function(track){var mapping={revenue:"Billing Amount"};var event=track.event();var properties=track.properties(mapping);if(this.options.prefixProperties)properties=prefix(event,properties);push("record",event,properties)};KISSmetrics.prototype.alias=function(alias){push("alias",alias.to(),alias.from())};KISSmetrics.prototype.completedOrder=function(track){var products=track.products();var event=track.event();push("record",event,prefix(event,track.properties()));window._kmq.push(function(){var km=window.KM;each(products,function(product,i){var temp=new Track({event:event,properties:product});var item=prefix(event,product);item._t=km.ts()+i;item._d=1;km.set(item)})})};function prefix(event,properties){var prefixed={};each(properties,function(key,val){if(key==="Billing Amount"){prefixed[key]=val}else{prefixed[event+" - "+key]=val}});return prefixed}},{"segmentio/analytics.js-integration":159,"global-queue":190,facade:27,alias:195,batch:197,each:5,is:18}],197:[function(require,module,exports){try{var EventEmitter=require("events").EventEmitter}catch(err){var Emitter=require("emitter")}function noop(){}module.exports=Batch;function Batch(){if(!(this instanceof Batch))return new Batch;this.fns=[];this.concurrency(Infinity);this.throws(true);for(var i=0,len=arguments.length;i<len;++i){this.push(arguments[i])}}if(EventEmitter){Batch.prototype.__proto__=EventEmitter.prototype}else{Emitter(Batch.prototype)}Batch.prototype.concurrency=function(n){this.n=n;return this};Batch.prototype.push=function(fn){this.fns.push(fn);return this};Batch.prototype.throws=function(throws){this.e=!!throws;return this};Batch.prototype.end=function(cb){var self=this,total=this.fns.length,pending=total,results=[],errors=[],cb=cb||noop,fns=this.fns,max=this.n,throws=this.e,index=0,done;if(!fns.length)return cb(null,results);function next(){var i=index++;var fn=fns[i];if(!fn)return;var start=new Date;try{fn(callback)}catch(err){callback(err)}function callback(err,res){if(done)return;if(err&&throws)return done=true,cb(err);var complete=total-pending+1;var end=new Date;results[i]=res;errors[i]=err;self.emit("progress",{index:i,value:res,error:err,pending:pending,total:total,complete:complete,percent:complete/total*100|0,start:start,end:end,duration:end-start});if(--pending)next();else if(!throws)cb(errors,results);else cb(null,results)}}for(var i=0;i<fns.length;i++){if(i==max)break;next()}return this}},{emitter:198}],198:[function(require,module,exports){module.exports=Emitter;function Emitter(obj){if(obj)return mixin(obj)}function mixin(obj){for(var key in Emitter.prototype){obj[key]=Emitter.prototype[key]}return obj}Emitter.prototype.on=Emitter.prototype.addEventListener=function(event,fn){this._callbacks=this._callbacks||{};(this._callbacks[event]=this._callbacks[event]||[]).push(fn);return this};Emitter.prototype.once=function(event,fn){var self=this;this._callbacks=this._callbacks||{};function on(){self.off(event,on);fn.apply(this,arguments)}on.fn=fn;this.on(event,on);return this};Emitter.prototype.off=Emitter.prototype.removeListener=Emitter.prototype.removeAllListeners=Emitter.prototype.removeEventListener=function(event,fn){this._callbacks=this._callbacks||{};if(0==arguments.length){this._callbacks={};return this}var callbacks=this._callbacks[event];if(!callbacks)return this;if(1==arguments.length){delete this._callbacks[event];return this}var cb;for(var i=0;i<callbacks.length;i++){cb=callbacks[i];if(cb===fn||cb.fn===fn){callbacks.splice(i,1);break}}return this};Emitter.prototype.emit=function(event){this._callbacks=this._callbacks||{};var args=[].slice.call(arguments,1),callbacks=this._callbacks[event];if(callbacks){callbacks=callbacks.slice(0);for(var i=0,len=callbacks.length;i<len;++i){callbacks[i].apply(this,args)}}return this};Emitter.prototype.listeners=function(event){this._callbacks=this._callbacks||{};return this._callbacks[event]||[]};Emitter.prototype.hasListeners=function(event){return!!this.listeners(event).length}},{}],125:[function(require,module,exports){var integration=require("segmentio/analytics.js-integration");var push=require("global-queue")("_learnq");var tick=require("next-tick");var alias=require("alias");var aliases={id:"$id",email:"$email",firstName:"$first_name",lastName:"$last_name",phone:"$phone_number",title:"$title"};var Klaviyo=module.exports=integration("Klaviyo").assumesPageview().global("_learnq").option("apiKey","").tag('<script src="//a.klaviyo.com/media/js/learnmarklet.js">');Klaviyo.prototype.initialize=function(page){var self=this;push("account",this.options.apiKey);this.load(function(){tick(self.ready)})};Klaviyo.prototype.loaded=function(){return!!(window._learnq&&window._learnq.push!==Array.prototype.push)};Klaviyo.prototype.identify=function(identify){var traits=identify.traits(aliases);if(!traits.$id&&!traits.$email)return;push("identify",traits)};Klaviyo.prototype.group=function(group){var props=group.properties();if(!props.name)return;push("identify",{$organization:props.name})};Klaviyo.prototype.track=function(track){push("track",track.event(),track.properties({revenue:"$value"}))}},{"segmentio/analytics.js-integration":159,"global-queue":190,"next-tick":45,alias:195}],126:[function(require,module,exports){var integration=require("segmentio/analytics.js-integration");var LeadLander=module.exports=integration("LeadLander").assumesPageview().global("llactid").global("trackalyzer").option("accountId",null).tag('<script src="http://t6.trackalyzer.com/trackalyze-nodoc.js">');LeadLander.prototype.initialize=function(page){window.llactid=this.options.accountId;this.load(this.ready)};LeadLander.prototype.loaded=function(){return!!window.trackalyzer}},{"segmentio/analytics.js-integration":159}],127:[function(require,module,exports){var integration=require("segmentio/analytics.js-integration");var clone=require("clone");var each=require("each");var when=require("when");var LiveChat=module.exports=integration("LiveChat").assumesPageview().global("__lc").global("__lc_inited").global("LC_API").global("LC_Invite").option("group",0).option("license","").tag('<script src="//cdn.livechatinc.com/tracking.js">');LiveChat.prototype.initialize=function(page){var self=this;window.__lc=clone(this.options);this.load(function(){when(function(){return self.loaded() },self.ready)})};LiveChat.prototype.loaded=function(){return!!(window.LC_API&&window.LC_Invite)};LiveChat.prototype.identify=function(identify){var traits=identify.traits({userId:"User ID"});window.LC_API.set_custom_variables(convert(traits))};function convert(traits){var arr=[];each(traits,function(key,value){arr.push({name:key,value:value})});return arr}},{"segmentio/analytics.js-integration":159,clone:194,each:5,when:184}],128:[function(require,module,exports){var integration=require("segmentio/analytics.js-integration");var Identify=require("facade").Identify;var useHttps=require("use-https");var LuckyOrange=module.exports=integration("Lucky Orange").assumesPageview().global("_loq").global("__wtw_watcher_added").global("__wtw_lucky_site_id").global("__wtw_lucky_is_segment_io").global("__wtw_custom_user_data").option("siteId",null).tag("http",'<script src="http://www.luckyorange.com/w.js?{{ cache }}">').tag("https",'<script src="https://ssl.luckyorange.com/w.js?{{ cache }}">');LuckyOrange.prototype.initialize=function(page){var user=this.analytics.user();window._loq||(window._loq=[]);window.__wtw_lucky_site_id=this.options.siteId;this.identify(new Identify({traits:user.traits(),userId:user.id()}));var cache=Math.floor((new Date).getTime()/6e4);var name=useHttps()?"https":"http";this.load(name,{cache:cache},this.ready)};LuckyOrange.prototype.loaded=function(){return!!window.__wtw_watcher_added};LuckyOrange.prototype.identify=function(identify){var traits=identify.traits();var email=identify.email();var name=identify.name();if(name)traits.name=name;if(email)traits.email=email;window.__wtw_custom_user_data=traits}},{"segmentio/analytics.js-integration":159,facade:27,"use-https":161}],129:[function(require,module,exports){var integration=require("segmentio/analytics.js-integration");var alias=require("alias");var Lytics=module.exports=integration("Lytics").global("jstag").option("cid","").option("cookie","seerid").option("delay",2e3).option("sessionTimeout",1800).option("url","//c.lytics.io").tag('<script src="//c.lytics.io/static/io.min.js">');var aliases={sessionTimeout:"sessecs"};Lytics.prototype.initialize=function(page){var options=alias(this.options,aliases);window.jstag=function(){var t={_q:[],_c:options,ts:(new Date).getTime()};t.send=function(){this._q.push(["ready","send",Array.prototype.slice.call(arguments)]);return this};return t}();this.load(this.ready)};Lytics.prototype.loaded=function(){return!!(window.jstag&&window.jstag.bind)};Lytics.prototype.page=function(page){window.jstag.send(page.properties())};Lytics.prototype.identify=function(identify){var traits=identify.traits({userId:"_uid"});window.jstag.send(traits)};Lytics.prototype.track=function(track){var props=track.properties();props._e=track.event();window.jstag.send(props)}},{"segmentio/analytics.js-integration":159,alias:195}],130:[function(require,module,exports){var alias=require("alias");var clone=require("clone");var dates=require("convert-dates");var integration=require("segmentio/analytics.js-integration");var iso=require("to-iso-string");var indexof=require("indexof");var del=require("obj-case").del;var Mixpanel=module.exports=integration("Mixpanel").global("mixpanel").option("increments",[]).option("cookieName","").option("nameTag",true).option("pageview",false).option("people",false).option("token","").option("trackAllPages",false).option("trackNamedPages",true).option("trackCategorizedPages",true).tag('<script src="//cdn.mxpnl.com/libs/mixpanel-2.2.min.js">');var optionsAliases={cookieName:"cookie_name"};Mixpanel.prototype.initialize=function(){(function(c,a){window.mixpanel=a;var b,d,h,e;a._i=[];a.init=function(b,c,f){function d(a,b){var c=b.split(".");2==c.length&&(a=a[c[0]],b=c[1]);a[b]=function(){a.push([b].concat(Array.prototype.slice.call(arguments,0)))}}var g=a;"undefined"!==typeof f?g=a[f]=[]:f="mixpanel";g.people=g.people||[];h=["disable","track","track_pageview","track_links","track_forms","register","register_once","unregister","identify","alias","name_tag","set_config","people.set","people.increment","people.track_charge","people.append"];for(e=0;e<h.length;e++)d(g,h[e]);a._i.push([b,c,f])};a.__SV=1.2})(document,window.mixpanel||[]);this.options.increments=lowercase(this.options.increments);var options=alias(this.options,optionsAliases);window.mixpanel.init(options.token,options);this.load(this.ready)};Mixpanel.prototype.loaded=function(){return!!(window.mixpanel&&window.mixpanel.config)};Mixpanel.prototype.page=function(page){var category=page.category();var name=page.fullName();var opts=this.options;if(opts.trackAllPages){this.track(page.track())}if(category&&opts.trackCategorizedPages){this.track(page.track(category))}if(name&&opts.trackNamedPages){this.track(page.track(name))}};var traitAliases={created:"$created",email:"$email",firstName:"$first_name",lastName:"$last_name",lastSeen:"$last_seen",name:"$name",username:"$username",phone:"$phone"};Mixpanel.prototype.identify=function(identify){var username=identify.username();var email=identify.email();var id=identify.userId();if(id)window.mixpanel.identify(id);var nametag=email||username||id;if(nametag)window.mixpanel.name_tag(nametag);var traits=identify.traits(traitAliases);if(traits.$created)del(traits,"createdAt");window.mixpanel.register(traits);if(this.options.people)window.mixpanel.people.set(traits)};Mixpanel.prototype.track=function(track){var increments=this.options.increments;var increment=track.event().toLowerCase();var people=this.options.people;var props=track.properties();var revenue=track.revenue();delete props.distinct_id;delete props.ip;delete props.mp_name_tag;delete props.mp_note;delete props.token;if(people&&~indexof(increments,increment)){window.mixpanel.people.increment(track.event());window.mixpanel.people.set("Last "+track.event(),new Date)}props=dates(props,iso);window.mixpanel.track(track.event(),props);if(revenue&&people){window.mixpanel.people.track_charge(revenue)}};Mixpanel.prototype.alias=function(alias){var mp=window.mixpanel;var to=alias.to();if(mp.get_distinct_id&&mp.get_distinct_id()===to)return;if(mp.get_property&&mp.get_property("$people_distinct_id")===to)return;mp.alias(to,alias.from())};function lowercase(arr){var ret=new Array(arr.length);for(var i=0;i<arr.length;++i){ret[i]=String(arr[i]).toLowerCase()}return ret}},{alias:195,clone:194,"convert-dates":196,"segmentio/analytics.js-integration":159,"to-iso-string":193,indexof:46,"obj-case":60}],131:[function(require,module,exports){var integration=require("segmentio/analytics.js-integration");var bind=require("bind");var when=require("when");var is=require("is");var Mojn=module.exports=integration("Mojn").option("customerCode","").global("_mojnTrack").tag('<script src="https://track.idtargeting.com/{{ customerCode }}/track.js">');Mojn.prototype.initialize=function(){window._mojnTrack=window._mojnTrack||[];window._mojnTrack.push({cid:this.options.customerCode});var loaded=bind(this,this.loaded);var ready=this.ready;this.load(function(){when(loaded,ready)})};Mojn.prototype.loaded=function(){return is.object(window._mojnTrack)};Mojn.prototype.identify=function(identify){var email=identify.email();if(!email)return;var img=new Image;img.src="//matcher.idtargeting.com/analytics.gif?cid="+this.options.customerCode+"&_mjnctid="+email;img.width=1;img.height=1;return img};Mojn.prototype.track=function(track){var properties=track.properties();var revenue=properties.revenue;var currency=properties.currency||"";var conv=currency+revenue;if(!revenue)return;window._mojnTrack.push({conv:conv});return conv}},{"segmentio/analytics.js-integration":159,bind:33,when:184,is:18}],132:[function(require,module,exports){var push=require("global-queue")("_mfq");var integration=require("segmentio/analytics.js-integration");var each=require("each");var Mouseflow=module.exports=integration("Mouseflow").assumesPageview().global("mouseflow").global("_mfq").option("apiKey","").option("mouseflowHtmlDelay",0).tag('<script src="//cdn.mouseflow.com/projects/{{ apiKey }}.js">');Mouseflow.prototype.initialize=function(page){window.mouseflowHtmlDelay=this.options.mouseflowHtmlDelay;this.load(this.ready)};Mouseflow.prototype.loaded=function(){return!!window.mouseflow};Mouseflow.prototype.page=function(page){if(!window.mouseflow)return;if("function"!=typeof mouseflow.newPageView)return;mouseflow.newPageView()};Mouseflow.prototype.identify=function(identify){set(identify.traits())};Mouseflow.prototype.track=function(track){var props=track.properties();props.event=track.event();set(props)};function set(obj){each(obj,function(key,value){push("setVariable",key,value)})}},{"global-queue":190,"segmentio/analytics.js-integration":159,each:5}],133:[function(require,module,exports){var integration=require("segmentio/analytics.js-integration");var useHttps=require("use-https");var each=require("each");var is=require("is");var MouseStats=module.exports=integration("MouseStats").assumesPageview().global("msaa").global("MouseStatsVisitorPlaybacks").option("accountNumber","").tag("http",'<script src="http://www2.mousestats.com/js/{{ path }}.js?{{ cache }}">').tag("https",'<script src="https://ssl.mousestats.com/js/{{ path }}.js?{{ cache }}">');MouseStats.prototype.initialize=function(page){var number=this.options.accountNumber;var path=number.slice(0,1)+"/"+number.slice(1,2)+"/"+number;var cache=Math.floor((new Date).getTime()/6e4);var name=useHttps()?"https":"http";this.load(name,{path:path,cache:cache},this.ready)};MouseStats.prototype.loaded=function(){return is.array(window.MouseStatsVisitorPlaybacks)};MouseStats.prototype.identify=function(identify){each(identify.traits(),function(key,value){window.MouseStatsVisitorPlaybacks.customVariable(key,value)})}},{"segmentio/analytics.js-integration":159,"use-https":161,each:5,is:18}],134:[function(require,module,exports){var integration=require("segmentio/analytics.js-integration");var push=require("global-queue")("__nls");var Navilytics=module.exports=integration("Navilytics").assumesPageview().global("__nls").option("memberId","").option("projectId","").tag('<script src="//www.navilytics.com/nls.js?mid={{ memberId }}&pid={{ projectId }}">');Navilytics.prototype.initialize=function(page){window.__nls=window.__nls||[];this.load(this.ready)};Navilytics.prototype.loaded=function(){return!!(window.__nls&&[].push!=window.__nls.push)};Navilytics.prototype.track=function(track){push("tagRecording",track.event())}},{"segmentio/analytics.js-integration":159,"global-queue":190}],135:[function(require,module,exports){var integration=require("segmentio/analytics.js-integration");var https=require("use-https");var tick=require("next-tick");var Olark=module.exports=integration("Olark").assumesPageview().global("olark").option("identify",true).option("page",true).option("siteId","").option("groupId","").option("track",false);Olark.prototype.initialize=function(page){var self=this;this.load(function(){tick(self.ready)});var groupId=this.options.groupId;if(groupId){chat("setOperatorGroup",{group:groupId})}var self=this;box("onExpand",function(){self._open=true});box("onShrink",function(){self._open=false})};Olark.prototype.loaded=function(){return!!window.olark};Olark.prototype.load=function(callback){var el=document.getElementById("olark");window.olark||function(c){var f=window,d=document,l=https()?"https:":"http:",z=c.name,r="load";var nt=function(){f[z]=function(){(a.s=a.s||[]).push(arguments)};var a=f[z]._={},q=c.methods.length;while(q--){(function(n){f[z][n]=function(){f[z]("call",n,arguments)}})(c.methods[q])}a.l=c.loader;a.i=nt;a.p={0:+new Date};a.P=function(u){a.p[u]=new Date-a.p[0]};function s(){a.P(r);f[z](r)}f.addEventListener?f.addEventListener(r,s,false):f.attachEvent("on"+r,s);var ld=function(){function p(hd){hd="head";return["<",hd,"></",hd,"><",i," onl"+'oad="var d=',g,";d.getElementsByTagName('head')[0].",j,"(d.",h,"('script')).",k,"='",l,"//",a.l,"'",'"',"></",i,">"].join("")}var i="body",m=d[i];if(!m){return setTimeout(ld,100)}a.P(1);var j="appendChild",h="createElement",k="src",n=d[h]("div"),v=n[j](d[h](z)),b=d[h]("iframe"),g="document",e="domain",o;n.style.display="none";m.insertBefore(n,m.firstChild).id=z;b.frameBorder="0";b.id=z+"-loader";if(/MSIE[ ]+6/.test(navigator.userAgent)){b.src="javascript:false"}b.allowTransparency="true";v[j](b);try{b.contentWindow[g].open()}catch(w){c[e]=d[e];o="javascript:var d="+g+".open();d.domain='"+d.domain+"';";b[k]=o+"void(0);"}try{var t=b.contentWindow[g];t.write(p());t.close()}catch(x){b[k]=o+'d.write("'+p().replace(/"/g,String.fromCharCode(92)+'"')+'");d.close();'}a.P(2)};ld()};nt()}({loader:"static.olark.com/jsclient/loader0.js",name:"olark",methods:["configure","extend","declare","identify"]});window.olark.identify(this.options.siteId);callback()};Olark.prototype.page=function(page){if(!this.options.page||!this._open)return;var props=page.properties();var name=page.fullName();if(!name&&!props.url)return;var msg=name?name.toLowerCase()+" page":props.url;chat("sendNotificationToOperator",{body:"looking at "+msg})};Olark.prototype.identify=function(identify){if(!this.options.identify)return;var username=identify.username();var traits=identify.traits();var id=identify.userId();var email=identify.email();var phone=identify.phone();var name=identify.name()||identify.firstName();visitor("updateCustomFields",traits);if(email)visitor("updateEmailAddress",{emailAddress:email});if(phone)visitor("updatePhoneNumber",{phoneNumber:phone});if(name)visitor("updateFullName",{fullName:name});var nickname=name||email||username||id;if(name&&email)nickname+=" ("+email+")";if(nickname)chat("updateVisitorNickname",{snippet:nickname})};Olark.prototype.track=function(track){if(!this.options.track||!this._open)return;chat("sendNotificationToOperator",{body:'visitor triggered "'+track.event()+'"'})};function box(action,value){window.olark("api.box."+action,value)}function visitor(action,value){window.olark("api.visitor."+action,value)}function chat(action,value){window.olark("api.chat."+action,value)}},{"segmentio/analytics.js-integration":159,"use-https":161,"next-tick":45}],136:[function(require,module,exports){var integration=require("segmentio/analytics.js-integration");var push=require("global-queue")("optimizely");var callback=require("callback");var tick=require("next-tick");var bind=require("bind");var each=require("each");var Optimizely=module.exports=integration("Optimizely").option("variations",true).option("trackNamedPages",true).option("trackCategorizedPages",true);Optimizely.prototype.initialize=function(){if(this.options.variations){var self=this;tick(function(){self.replay()})}this.ready()};Optimizely.prototype.track=function(track){var props=track.properties();if(props.revenue)props.revenue*=100;push("trackEvent",track.event(),props)};Optimizely.prototype.page=function(page){var category=page.category();var name=page.fullName();var opts=this.options;if(category&&opts.trackCategorizedPages){this.track(page.track(category))}if(name&&opts.trackNamedPages){this.track(page.track(name))}};Optimizely.prototype.replay=function(){if(!window.optimizely)return;var data=window.optimizely.data;if(!data)return;var experiments=data.experiments;var map=data.state.variationNamesMap;var traits={};each(map,function(experimentId,variation){var experiment=experiments[experimentId].name;traits["Experiment: "+experiment]=variation});this.analytics.identify(traits)}},{"segmentio/analytics.js-integration":159,"global-queue":190,callback:12,"next-tick":45,bind:33,each:5}],137:[function(require,module,exports){var integration=require("segmentio/analytics.js-integration");var PerfectAudience=module.exports=integration("Perfect Audience").assumesPageview().global("_pa").option("siteId","").tag('<script src="//tag.perfectaudience.com/serve/{{ siteId }}.js">');PerfectAudience.prototype.initialize=function(page){window._pa=window._pa||{};this.load(this.ready)};PerfectAudience.prototype.loaded=function(){return!!(window._pa&&window._pa.track)};PerfectAudience.prototype.track=function(track){window._pa.track(track.event(),track.properties())}},{"segmentio/analytics.js-integration":159}],138:[function(require,module,exports){var integration=require("segmentio/analytics.js-integration");var push=require("global-queue")("_prum");var date=require("load-date");var Pingdom=module.exports=integration("Pingdom").assumesPageview().global("_prum").global("PRUM_EPISODES").option("id","").tag('<script src="//rum-static.pingdom.net/prum.min.js">');Pingdom.prototype.initialize=function(page){window._prum=window._prum||[];push("id",this.options.id);push("mark","firstbyte",date.getTime());var self=this;this.load(this.ready)};Pingdom.prototype.loaded=function(){return!!(window._prum&&window._prum.push!==Array.prototype.push)}},{"segmentio/analytics.js-integration":159,"global-queue":190,"load-date":191}],139:[function(require,module,exports){var integration=require("segmentio/analytics.js-integration");var push=require("global-queue")("_paq");var each=require("each");var Piwik=module.exports=integration("Piwik").global("_paq").option("url",null).option("siteId","").mapping("goals").tag('<script src="{{ url }}/piwik.js">');Piwik.prototype.initialize=function(){window._paq=window._paq||[];push("setSiteId",this.options.siteId);push("setTrackerUrl",this.options.url+"/piwik.php");push("enableLinkTracking");this.load(this.ready)};Piwik.prototype.loaded=function(){return!!(window._paq&&window._paq.push!=[].push)};Piwik.prototype.page=function(page){push("trackPageView")};Piwik.prototype.track=function(track){var goals=this.goals(track.event());var revenue=track.revenue()||0;each(goals,function(goal){push("trackGoal",goal,revenue)})}},{"segmentio/analytics.js-integration":159,"global-queue":190,each:5}],140:[function(require,module,exports){var integration=require("segmentio/analytics.js-integration");var convertDates=require("convert-dates");var push=require("global-queue")("_lnq");var alias=require("alias");var Preact=module.exports=integration("Preact").assumesPageview().global("_lnq").option("projectCode","").tag('<script src="//d2bbvl6dq48fa6.cloudfront.net/js/ln-2.4.min.js">');Preact.prototype.initialize=function(page){window._lnq=window._lnq||[];push("_setCode",this.options.projectCode);this.load(this.ready)};Preact.prototype.loaded=function(){return!!(window._lnq&&window._lnq.push!==Array.prototype.push)};Preact.prototype.identify=function(identify){if(!identify.userId())return;var traits=identify.traits({created:"created_at"});traits=convertDates(traits,convertDate);push("_setPersonData",{name:identify.name(),email:identify.email(),uid:identify.userId(),properties:traits})};Preact.prototype.group=function(group){if(!group.groupId())return;push("_setAccount",group.traits())};Preact.prototype.track=function(track){var props=track.properties();var revenue=track.revenue();var event=track.event();var special={name:event};if(revenue){special.revenue=revenue*100;delete props.revenue}if(props.note){special.note=props.note;delete props.note}push("_logEvent",special,props)};function convertDate(date){return Math.floor(date/1e3)}},{"segmentio/analytics.js-integration":159,"convert-dates":196,"global-queue":190,alias:195}],141:[function(require,module,exports){var integration=require("segmentio/analytics.js-integration");var push=require("global-queue")("_kiq");var Facade=require("facade");var Identify=Facade.Identify;var bind=require("bind");var when=require("when");var Qualaroo=module.exports=integration("Qualaroo").assumesPageview().global("_kiq").option("customerId","").option("siteToken","").option("track",false).tag('<script src="//s3.amazonaws.com/ki.js/{{ customerId }}/{{ siteToken }}.js">');Qualaroo.prototype.initialize=function(page){window._kiq=window._kiq||[];var loaded=bind(this,this.loaded);var ready=this.ready;this.load(function(){when(loaded,ready)})};Qualaroo.prototype.loaded=function(){return!!(window._kiq&&window._kiq.push!==Array.prototype.push)};Qualaroo.prototype.identify=function(identify){var traits=identify.traits();var id=identify.userId();var email=identify.email();if(email)id=email;if(id)push("identify",id);if(traits)push("set",traits)};Qualaroo.prototype.track=function(track){if(!this.options.track)return;var event=track.event();var traits={};traits["Triggered: "+event]=true;this.identify(new Identify({traits:traits}))}},{"segmentio/analytics.js-integration":159,"global-queue":190,facade:27,bind:33,when:184}],142:[function(require,module,exports){var push=require("global-queue")("_qevents",{wrap:false});var integration=require("segmentio/analytics.js-integration");var useHttps=require("use-https");var Quantcast=module.exports=integration("Quantcast").assumesPageview().global("_qevents").global("__qc").option("pCode",null).option("advertise",false).tag("http",'<script src="http://edge.quantserve.com/quant.js">').tag("https",'<script src="https://secure.quantserve.com/quant.js">');Quantcast.prototype.initialize=function(page){window._qevents=window._qevents||[];var opts=this.options;var settings={qacct:opts.pCode};var user=this.analytics.user();if(user.id())settings.uid=user.id();if(page){settings.labels=this.labels("page",page.category(),page.name())}push(settings);var name=useHttps()?"https":"http";this.load(name,this.ready)};Quantcast.prototype.loaded=function(){return!!window.__qc};Quantcast.prototype.page=function(page){var category=page.category();var name=page.name();var settings={event:"refresh",labels:this.labels("page",category,name),qacct:this.options.pCode};var user=this.analytics.user();if(user.id())settings.uid=user.id();push(settings)};Quantcast.prototype.identify=function(identify){var id=identify.userId();if(id){window._qevents[0]=window._qevents[0]||{};window._qevents[0].uid=id}};Quantcast.prototype.track=function(track){var name=track.event();var revenue=track.revenue();var settings={event:"click",labels:this.labels("event",name),qacct:this.options.pCode};var user=this.analytics.user();if(null!=revenue)settings.revenue=revenue+"";if(user.id())settings.uid=user.id();push(settings)};Quantcast.prototype.completedOrder=function(track){var name=track.event();var revenue=track.total();var labels=this.labels("event",name);var category=track.category();if(this.options.advertise&&category){labels+=","+this.labels("pcat",category)}var settings={event:"refresh",labels:labels,revenue:revenue+"",orderid:track.orderId(),qacct:this.options.pCode};push(settings)};Quantcast.prototype.labels=function(type){var args=[].slice.call(arguments,1);var advertise=this.options.advertise;var ret=[];if(advertise&&"page"==type)type="event";if(advertise)type="_fp."+type;for(var i=0;i<args.length;++i){if(null==args[i])continue;var value=String(args[i]);ret.push(value.replace(/,/g,";"))}ret=advertise?ret.join(" "):ret.join(".");return[type,ret].join(".")}},{"global-queue":190,"segmentio/analytics.js-integration":159,"use-https":161}],143:[function(require,module,exports){var integration=require("segmentio/analytics.js-integration");var extend=require("extend");var is=require("is");var RollbarIntegration=module.exports=integration("Rollbar").global("Rollbar").option("identify",true).option("accessToken","").option("environment","unknown").option("captureUncaught",true);RollbarIntegration.prototype.initialize=function(page){var _rollbarConfig=this.config={accessToken:this.options.accessToken,captureUncaught:this.options.captureUncaught,payload:{environment:this.options.environment}};(function(a){function b(b){this.shimId=++g,this.notifier=null,this.parentShim=b,this.logger=function(){},a.console&&void 0===a.console.shimId&&(this.logger=a.console.log)}function c(b,c,d){!d[4]&&a._rollbarWrappedError&&(d[4]=a._rollbarWrappedError,a._rollbarWrappedError=null),b.uncaughtError.apply(b,d),c&&c.apply(a,d)}function d(c){var d=b;return f(function(){if(this.notifier)return this.notifier[c].apply(this.notifier,arguments);var b=this,e="scope"===c;e&&(b=new d(this));var f=Array.prototype.slice.call(arguments,0),g={shim:b,method:c,args:f,ts:new Date};return a._rollbarShimQueue.push(g),e?b:void 0})}function e(a,b){if(b.hasOwnProperty&&b.hasOwnProperty("addEventListener")){var c=b.addEventListener;b.addEventListener=function(b,d,e){c.call(this,b,a.wrap(d),e)};var d=b.removeEventListener;b.removeEventListener=function(a,b,c){d.call(this,a,b._wrapped||b,c)}}}function f(a,b){return b=b||this.logger,function(){try{return a.apply(this,arguments)}catch(c){b("Rollbar internal error:",c)}}}var g=0;b.init=function(a,d){var g=d.globalAlias||"Rollbar";if("object"==typeof a[g])return a[g];a._rollbarShimQueue=[],a._rollbarWrappedError=null,d=d||{};var h=new b;return f(function(){if(h.configure(d),d.captureUncaught){var b=a.onerror;a.onerror=function(){var a=Array.prototype.slice.call(arguments,0);c(h,b,a)};var f,i,j=["EventTarget","Window","Node","ApplicationCache","AudioTrackList","ChannelMergerNode","CryptoOperation","EventSource","FileReader","HTMLUnknownElement","IDBDatabase","IDBRequest","IDBTransaction","KeyOperation","MediaController","MessagePort","ModalWindow","Notification","SVGElementInstance","Screen","TextTrack","TextTrackCue","TextTrackList","WebSocket","WebSocketWorker","Worker","XMLHttpRequest","XMLHttpRequestEventTarget","XMLHttpRequestUpload"];for(f=0;f<j.length;++f)i=j[f],a[i]&&a[i].prototype&&e(h,a[i].prototype)}return a[g]=h,h},h.logger)()},b.prototype.loadFull=function(a,b,c,d,e){var g=f(function(){var a=b.createElement("script"),e=b.getElementsByTagName("script")[0];a.src=d.rollbarJsUrl,a.async=!c,a.onload=h,e.parentNode.insertBefore(a,e)},this.logger),h=f(function(){var b;if(void 0===a._rollbarPayloadQueue){var c,d,f,g;for(b=new Error("rollbar.js did not load");c=a._rollbarShimQueue.shift();)for(f=c.args,g=0;g<f.length;++g)if(d=f[g],"function"==typeof d){d(b);break}}e&&e(b)},this.logger);f(function(){c?g():a.addEventListener?a.addEventListener("load",g,!1):a.attachEvent("onload",g)},this.logger)()},b.prototype.wrap=function(b){if("function"!=typeof b)return b;if(b._isWrap)return b;if(!b._wrapped){b._wrapped=function(){try{return b.apply(this,arguments)}catch(c){throw a._rollbarWrappedError=c,c}},b._wrapped._isWrap=!0;for(var c in b)b.hasOwnProperty(c)&&(b._wrapped[c]=b[c])}return b._wrapped};for(var h="log,debug,info,warn,warning,error,critical,global,configure,scope,uncaughtError".split(","),i=0;i<h.length;++i)b.prototype[h[i]]=d(h[i]);var j="//d37gvrvc0wt4s1.cloudfront.net/js/v1.0/rollbar.min.js";_rollbarConfig.rollbarJsUrl=_rollbarConfig.rollbarJsUrl||j,b.init(a,_rollbarConfig)})(window,document);this.load(this.ready)};RollbarIntegration.prototype.loaded=function(){return is.object(window.Rollbar)&&null==window.Rollbar.shimId};RollbarIntegration.prototype.load=function(callback){window.Rollbar.loadFull(window,document,true,this.config,callback)};RollbarIntegration.prototype.identify=function(identify){if(!this.options.identify)return;var uid=identify.userId();if(uid===null||uid===undefined)return;var rollbar=window.Rollbar;var person={id:uid};extend(person,identify.traits());rollbar.configure({payload:{person:person}})}},{"segmentio/analytics.js-integration":159,extend:40,is:18}],144:[function(require,module,exports){var integration=require("segmentio/analytics.js-integration");var SaaSquatch=module.exports=integration("SaaSquatch").option("tenantAlias","").global("_sqh").tag('<script src="//d2rcp9ak152ke1.cloudfront.net/assets/javascripts/squatch.min.js">');SaaSquatch.prototype.initialize=function(page){window._sqh=window._sqh||[];this.load(this.ready)};SaaSquatch.prototype.loaded=function(){return window._sqh&&window._sqh.push!=[].push};SaaSquatch.prototype.identify=function(identify){var sqh=window._sqh;var accountId=identify.proxy("traits.accountId");var image=identify.proxy("traits.referralImage");var opts=identify.options(this.name);var id=identify.userId();var email=identify.email();if(!(id||email))return;if(this.called)return;var init={tenant_alias:this.options.tenantAlias,first_name:identify.firstName(),last_name:identify.lastName(),user_image:identify.avatar(),email:email,user_id:id};if(accountId)init.account_id=accountId;if(opts.checksum)init.checksum=opts.checksum;if(image)init.fb_share_image=image;sqh.push(["init",init]);this.called=true;this.load()}},{"segmentio/analytics.js-integration":159}],145:[function(require,module,exports){var integration=require("segmentio/analytics.js-integration");var is=require("is");var Sentry=module.exports=integration("Sentry").global("Raven").option("config","").tag('<script src="//cdn.ravenjs.com/1.1.10/native/raven.min.js">');Sentry.prototype.initialize=function(){var config=this.options.config;var self=this;this.load(function(){window.Raven.config(config).install();self.ready()})};Sentry.prototype.loaded=function(){return is.object(window.Raven)};Sentry.prototype.identify=function(identify){window.Raven.setUser(identify.traits())}},{"segmentio/analytics.js-integration":159,is:18}],146:[function(require,module,exports){var integration=require("segmentio/analytics.js-integration");var is=require("is");var SnapEngage=module.exports=integration("SnapEngage").assumesPageview().global("SnapABug").option("apiKey","").tag('<script src="//commondatastorage.googleapis.com/code.snapengage.com/js/{{ apiKey }}.js">');SnapEngage.prototype.initialize=function(page){this.load(this.ready)};SnapEngage.prototype.loaded=function(){return is.object(window.SnapABug)};SnapEngage.prototype.identify=function(identify){var email=identify.email();if(!email)return;window.SnapABug.setUserEmail(email)}},{"segmentio/analytics.js-integration":159,is:18}],147:[function(require,module,exports){var integration=require("segmentio/analytics.js-integration");var bind=require("bind");var when=require("when");var Spinnakr=module.exports=integration("Spinnakr").assumesPageview().global("_spinnakr_site_id").global("_spinnakr").option("siteId","").tag('<script src="//d3ojzyhbolvoi5.cloudfront.net/js/so.js">');Spinnakr.prototype.initialize=function(page){window._spinnakr_site_id=this.options.siteId;var loaded=bind(this,this.loaded);var ready=this.ready;this.load(function(){when(loaded,ready)})};Spinnakr.prototype.loaded=function(){return!!window._spinnakr}},{"segmentio/analytics.js-integration":159,bind:33,when:184}],148:[function(require,module,exports){var integration=require("segmentio/analytics.js-integration");var slug=require("slug");var push=require("global-queue")("_tsq");var Tapstream=module.exports=integration("Tapstream").assumesPageview().global("_tsq").option("accountName","").option("trackAllPages",true).option("trackNamedPages",true).option("trackCategorizedPages",true).tag('<script src="//cdn.tapstream.com/static/js/tapstream.js">');Tapstream.prototype.initialize=function(page){window._tsq=window._tsq||[];push("setAccountName",this.options.accountName);this.load(this.ready)};Tapstream.prototype.loaded=function(){return!!(window._tsq&&window._tsq.push!==Array.prototype.push)};Tapstream.prototype.page=function(page){var category=page.category();var opts=this.options;var name=page.fullName();if(opts.trackAllPages){this.track(page.track())}if(name&&opts.trackNamedPages){this.track(page.track(name))}if(category&&opts.trackCategorizedPages){this.track(page.track(category))}};Tapstream.prototype.track=function(track){var props=track.properties();push("fireHit",slug(track.event()),[props.url])}},{"segmentio/analytics.js-integration":159,slug:166,"global-queue":190}],149:[function(require,module,exports){var integration=require("segmentio/analytics.js-integration");var alias=require("alias");var clone=require("clone");var Trakio=module.exports=integration("trak.io").assumesPageview().global("trak").option("token","").option("trackNamedPages",true).option("trackCategorizedPages",true).tag('<script src="//d29p64779x43zo.cloudfront.net/v1/trak.io.min.js">');var optionsAliases={initialPageview:"auto_track_page_view"};Trakio.prototype.initialize=function(page){var options=this.options;window.trak=window.trak||[];window.trak.io=window.trak.io||{};window.trak.push=window.trak.push||function(){}; window.trak.io.load=window.trak.io.load||function(e){var r=function(e){return function(){window.trak.push([e].concat(Array.prototype.slice.call(arguments,0)))}},i=["initialize","identify","track","alias","channel","source","host","protocol","page_view"];for(var s=0;s<i.length;s++)window.trak.io[i[s]]=r(i[s]);window.trak.io.initialize.apply(window.trak.io,arguments)};window.trak.io.load(options.token,alias(options,optionsAliases));this.load(this.ready)};Trakio.prototype.loaded=function(){return!!(window.trak&&window.trak.loaded)};Trakio.prototype.page=function(page){var category=page.category();var props=page.properties();var name=page.fullName();window.trak.io.page_view(props.path,name||props.title);if(name&&this.options.trackNamedPages){this.track(page.track(name))}if(category&&this.options.trackCategorizedPages){this.track(page.track(category))}};var traitAliases={avatar:"avatar_url",firstName:"first_name",lastName:"last_name"};Trakio.prototype.identify=function(identify){var traits=identify.traits(traitAliases);var id=identify.userId();if(id){window.trak.io.identify(id,traits)}else{window.trak.io.identify(traits)}};Trakio.prototype.track=function(track){window.trak.io.track(track.event(),track.properties())};Trakio.prototype.alias=function(alias){if(!window.trak.io.distinct_id)return;var from=alias.from();var to=alias.to();if(to===window.trak.io.distinct_id())return;if(from){window.trak.io.alias(from,to)}else{window.trak.io.alias(to)}}},{"segmentio/analytics.js-integration":159,alias:195,clone:194}],150:[function(require,module,exports){var integration=require("segmentio/analytics.js-integration");var each=require("each");var has=Object.prototype.hasOwnProperty;var TwitterAds=module.exports=integration("Twitter Ads").tag("pixel",'<img src="//analytics.twitter.com/i/adsct?txn_id={{ event }}&p_id=Twitter"/>').mapping("events");TwitterAds.prototype.initialize=function(){this.ready()};TwitterAds.prototype.track=function(track){var events=this.events(track.event());var self=this;each(events,function(event){var el=self.load("pixel",{event:event})})}},{"segmentio/analytics.js-integration":159,each:5}],151:[function(require,module,exports){var integration=require("segmentio/analytics.js-integration");var push=require("global-queue")("_uc");var Usercycle=module.exports=integration("USERcycle").assumesPageview().global("_uc").option("key","").tag('<script src="//api.usercycle.com/javascripts/track.js">');Usercycle.prototype.initialize=function(page){push("_key",this.options.key);this.load(this.ready)};Usercycle.prototype.loaded=function(){return!!(window._uc&&window._uc.push!==Array.prototype.push)};Usercycle.prototype.identify=function(identify){var traits=identify.traits();var id=identify.userId();if(id)push("uid",id);push("action","came_back",traits)};Usercycle.prototype.track=function(track){push("action",track.event(),track.properties({revenue:"revenue_amount"}))}},{"segmentio/analytics.js-integration":159,"global-queue":190}],152:[function(require,module,exports){var alias=require("alias");var callback=require("callback");var convertDates=require("convert-dates");var integration=require("analytics.js-integration");var load=require("load-script");var push=require("global-queue")("_ufq");module.exports=exports=function(analytics){analytics.addIntegration(Userfox)};var Userfox=exports.Integration=integration("userfox").assumesPageview().readyOnLoad().global("_ufq").option("clientId","");Userfox.prototype.initialize=function(page){window._ufq=[];this.load()};Userfox.prototype.loaded=function(){return!!(window._ufq&&window._ufq.push!==Array.prototype.push)};Userfox.prototype.load=function(callback){load("//d2y71mjhnajxcg.cloudfront.net/js/userfox-stable.js",callback)};Userfox.prototype.identify=function(identify){var traits=identify.traits({created:"signup_date"});var email=identify.email();if(!email)return;push("init",{clientId:this.options.clientId,email:email});traits=convertDates(traits,formatDate);push("track",traits)};function formatDate(date){return Math.round(date.getTime()/1e3).toString()}},{alias:195,callback:12,"convert-dates":196,"analytics.js-integration":159,"load-script":168,"global-queue":190}],153:[function(require,module,exports){var integration=require("segmentio/analytics.js-integration");var push=require("global-queue")("UserVoice");var convertDates=require("convert-dates");var unix=require("to-unix-timestamp");var alias=require("alias");var clone=require("clone");var UserVoice=module.exports=integration("UserVoice").assumesPageview().global("UserVoice").global("showClassicWidget").option("apiKey","").option("classic",false).option("forumId",null).option("showWidget",true).option("mode","contact").option("accentColor","#448dd6").option("smartvote",true).option("trigger",null).option("triggerPosition","bottom-right").option("triggerColor","#ffffff").option("triggerBackgroundColor","rgba(46, 49, 51, 0.6)").option("classicMode","full").option("primaryColor","#cc6d00").option("linkColor","#007dbf").option("defaultMode","support").option("tabLabel","Feedback & Support").option("tabColor","#cc6d00").option("tabPosition","middle-right").option("tabInverted",false).tag('<script src="//widget.uservoice.com/{{ apiKey }}.js">');UserVoice.on("construct",function(integration){if(!integration.options.classic)return;integration.group=undefined;integration.identify=integration.identifyClassic;integration.initialize=integration.initializeClassic});UserVoice.prototype.initialize=function(page){var options=this.options;var opts=formatOptions(options);push("set",opts);push("autoprompt",{});if(options.showWidget){options.trigger?push("addTrigger",options.trigger,opts):push("addTrigger",opts)}this.load(this.ready)};UserVoice.prototype.loaded=function(){return!!(window.UserVoice&&window.UserVoice.push!==Array.prototype.push)};UserVoice.prototype.identify=function(identify){var traits=identify.traits({created:"created_at"});traits=convertDates(traits,unix);push("identify",traits)};UserVoice.prototype.group=function(group){var traits=group.traits({created:"created_at"});traits=convertDates(traits,unix);push("identify",{account:traits})};UserVoice.prototype.initializeClassic=function(){var options=this.options;window.showClassicWidget=showClassicWidget;if(options.showWidget)showClassicWidget("showTab",formatClassicOptions(options));this.load(this.ready)};UserVoice.prototype.identifyClassic=function(identify){push("setCustomFields",identify.traits())};function formatOptions(options){return alias(options,{forumId:"forum_id",accentColor:"accent_color",smartvote:"smartvote_enabled",triggerColor:"trigger_color",triggerBackgroundColor:"trigger_background_color",triggerPosition:"trigger_position"})}function formatClassicOptions(options){return alias(options,{forumId:"forum_id",classicMode:"mode",primaryColor:"primary_color",tabPosition:"tab_position",tabColor:"tab_color",linkColor:"link_color",defaultMode:"default_mode",tabLabel:"tab_label",tabInverted:"tab_inverted"})}function showClassicWidget(type,options){type=type||"showLightbox";push(type,"classic_widget",options)}},{"segmentio/analytics.js-integration":159,"global-queue":190,"convert-dates":196,"to-unix-timestamp":199,alias:195,clone:194}],199:[function(require,module,exports){module.exports=toUnixTimestamp;function toUnixTimestamp(date){return Math.floor(date.getTime()/1e3)}},{}],154:[function(require,module,exports){var integration=require("segmentio/analytics.js-integration");var push=require("global-queue")("_veroq");var cookie=require("component/cookie");var Vero=module.exports=integration("Vero").global("_veroq").option("apiKey","").tag('<script src="//d3qxef4rp70elm.cloudfront.net/m.js">');Vero.prototype.initialize=function(page){if(!cookie("__veroc4"))cookie("__veroc4","[]");push("init",{api_key:this.options.apiKey});this.load(this.ready)};Vero.prototype.loaded=function(){return!!(window._veroq&&window._veroq.push!==Array.prototype.push)};Vero.prototype.page=function(page){push("trackPageview")};Vero.prototype.identify=function(identify){var traits=identify.traits();var email=identify.email();var id=identify.userId();if(!id||!email)return;push("user",traits)};Vero.prototype.track=function(track){push("track",track.event(),track.properties())}},{"segmentio/analytics.js-integration":159,"global-queue":190,"component/cookie":28}],155:[function(require,module,exports){var integration=require("segmentio/analytics.js-integration");var tick=require("next-tick");var each=require("each");var VWO=module.exports=integration("Visual Website Optimizer").option("replay",true);VWO.prototype.initialize=function(){if(this.options.replay)this.replay();this.ready()};VWO.prototype.replay=function(){var analytics=this.analytics;tick(function(){experiments(function(err,traits){if(traits)analytics.identify(traits)})})};function experiments(fn){enqueue(function(){var data={};var ids=window._vwo_exp_ids;if(!ids)return fn();each(ids,function(id){var name=variation(id);if(name)data["Experiment: "+id]=name});fn(null,data)})}function enqueue(fn){window._vis_opt_queue=window._vis_opt_queue||[];window._vis_opt_queue.push(fn)}function variation(id){var experiments=window._vwo_exp;if(!experiments)return null;var experiment=experiments[id];var variationId=experiment.combination_chosen;return variationId?experiment.comb_n[variationId]:null}},{"segmentio/analytics.js-integration":159,"next-tick":45,each:5}],156:[function(require,module,exports){var integration=require("segmentio/analytics.js-integration");var useHttps=require("use-https");var WebEngage=module.exports=integration("WebEngage").assumesPageview().global("_weq").global("webengage").option("widgetVersion","4.0").option("licenseCode","").tag("http",'<script src="http://cdn.widgets.webengage.com/js/widget/webengage-min-v-4.0.js">').tag("https",'<script src="https://ssl.widgets.webengage.com/js/widget/webengage-min-v-4.0.js">');WebEngage.prototype.initialize=function(page){var _weq=window._weq=window._weq||{};_weq["webengage.licenseCode"]=this.options.licenseCode;_weq["webengage.widgetVersion"]=this.options.widgetVersion;var name=useHttps()?"https":"http";this.load(name,this.ready)};WebEngage.prototype.loaded=function(){return!!window.webengage}},{"segmentio/analytics.js-integration":159,"use-https":161}],157:[function(require,module,exports){var integration=require("segmentio/analytics.js-integration");var snake=require("to-snake-case");var isEmail=require("is-email");var extend=require("extend");var each=require("each");var type=require("type");var Woopra=module.exports=integration("Woopra").global("woopra").option("domain","").option("cookieName","wooTracker").option("cookieDomain",null).option("cookiePath","/").option("ping",true).option("pingInterval",12e3).option("idleTimeout",3e5).option("downloadTracking",true).option("outgoingTracking",true).option("outgoingIgnoreSubdomain",true).option("downloadPause",200).option("outgoingPause",400).option("ignoreQueryUrl",true).option("hideCampaign",false).tag('<script src="//static.woopra.com/js/w.js">');Woopra.prototype.initialize=function(page){(function(){var i,s,z,w=window,d=document,a=arguments,q="script",f=["config","track","identify","visit","push","call"],c=function(){var i,self=this;self._e=[];for(i=0;i<f.length;i++){(function(f){self[f]=function(){self._e.push([f].concat(Array.prototype.slice.call(arguments,0)));return self}})(f[i])}};w._w=w._w||{};for(i=0;i<a.length;i++){w._w[a[i]]=w[a[i]]=w[a[i]]||new c}})("woopra");this.load(this.ready);each(this.options,function(key,value){key=snake(key);if(null==value)return;if(""===value)return;window.woopra.config(key,value)})};Woopra.prototype.loaded=function(){return!!(window.woopra&&window.woopra.loaded)};Woopra.prototype.page=function(page){var props=page.properties();var name=page.fullName();if(name)props.title=name;window.woopra.track("pv",props)};Woopra.prototype.identify=function(identify){var traits=identify.traits();if(identify.name())traits.name=identify.name();window.woopra.identify(traits).push()};Woopra.prototype.track=function(track){window.woopra.track(track.event(),track.properties())}},{"segmentio/analytics.js-integration":159,"to-snake-case":160,"is-email":19,extend:40,each:5,type:35}],158:[function(require,module,exports){var integration=require("segmentio/analytics.js-integration");var tick=require("next-tick");var bind=require("bind");var when=require("when");var Yandex=module.exports=integration("Yandex Metrica").assumesPageview().global("yandex_metrika_callbacks").global("Ya").option("counterId",null).tag('<script src="//mc.yandex.ru/metrika/watch.js">');Yandex.prototype.initialize=function(page){var id=this.options.counterId;push(function(){window["yaCounter"+id]=new window.Ya.Metrika({id:id})});var loaded=bind(this,this.loaded);var ready=this.ready;this.load(function(){when(loaded,function(){tick(ready)})})};Yandex.prototype.loaded=function(){return!!(window.Ya&&window.Ya.Metrika)};function push(callback){window.yandex_metrika_callbacks=window.yandex_metrika_callbacks||[];window.yandex_metrika_callbacks.push(callback)}},{"segmentio/analytics.js-integration":159,"next-tick":45,bind:33,when:184}]},{},{1:"analytics"});
react/tutorials/trello/phoenix_trello/web/static/js/layouts/main.js
VPashkov/learning
import React from 'react'; import { Link } from 'react-router'; export default class MainLayout extends React.Component { constructor() { super(); } render() { return ( <div> {this.props.children} </div> ); } }
files/react/0.13.0-rc2/JSXTransformer.js
firulais/jsdelivr
/** * JSXTransformer v0.13.0-rc2 */ (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.JSXTransformer = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ /* jshint browser: true */ /* jslint evil: true */ /*eslint-disable no-eval */ /*eslint-disable block-scoped-var */ 'use strict'; var ReactTools = _dereq_('../main'); var inlineSourceMap = _dereq_('./inline-source-map'); var headEl; var dummyAnchor; var inlineScriptCount = 0; // The source-map library relies on Object.defineProperty, but IE8 doesn't // support it fully even with es5-sham. Indeed, es5-sham's defineProperty // throws when Object.prototype.__defineGetter__ is missing, so we skip building // the source map in that case. var supportsAccessors = Object.prototype.hasOwnProperty('__defineGetter__'); /** * Run provided code through jstransform. * * @param {string} source Original source code * @param {object?} options Options to pass to jstransform * @return {object} object as returned from jstransform */ function transformReact(source, options) { options = options || {}; // Force the sourcemaps option manually. We don't want to use it if it will // break (see above note about supportsAccessors). We'll only override the // value here if sourceMap was specified and is truthy. This guarantees that // we won't override any user intent (since this method is exposed publicly). if (options.sourceMap) { options.sourceMap = supportsAccessors; } // Otherwise just pass all options straight through to react-tools. return ReactTools.transformWithDetails(source, options); } /** * Eval provided source after transforming it. * * @param {string} source Original source code * @param {object?} options Options to pass to jstransform */ function exec(source, options) { return eval(transformReact(source, options).code); } /** * This method returns a nicely formated line of code pointing to the exact * location of the error `e`. The line is limited in size so big lines of code * are also shown in a readable way. * * Example: * ... x', overflow:'scroll'}} id={} onScroll={this.scroll} class=" ... * ^ * * @param {string} code The full string of code * @param {Error} e The error being thrown * @return {string} formatted message * @internal */ function createSourceCodeErrorMessage(code, e) { var sourceLines = code.split('\n'); // e.lineNumber is non-standard so we can't depend on its availability. If // we're in a browser where it isn't supported, don't even bother trying to // format anything. We may also hit a case where the line number is reported // incorrectly and is outside the bounds of the actual code. Handle that too. if (!e.lineNumber || e.lineNumber > sourceLines.length) { return ''; } var erroneousLine = sourceLines[e.lineNumber - 1]; // Removes any leading indenting spaces and gets the number of // chars indenting the `erroneousLine` var indentation = 0; erroneousLine = erroneousLine.replace(/^\s+/, function(leadingSpaces) { indentation = leadingSpaces.length; return ''; }); // Defines the number of characters that are going to show // before and after the erroneous code var LIMIT = 30; var errorColumn = e.column - indentation; if (errorColumn > LIMIT) { erroneousLine = '... ' + erroneousLine.slice(errorColumn - LIMIT); errorColumn = 4 + LIMIT; } if (erroneousLine.length - errorColumn > LIMIT) { erroneousLine = erroneousLine.slice(0, errorColumn + LIMIT) + ' ...'; } var message = '\n\n' + erroneousLine + '\n'; message += new Array(errorColumn - 1).join(' ') + '^'; return message; } /** * Actually transform the code. * * @param {string} code * @param {string?} url * @param {object?} options * @return {string} The transformed code. * @internal */ function transformCode(code, url, options) { try { var transformed = transformReact(code, options); } catch(e) { e.message += '\n at '; if (url) { if ('fileName' in e) { // We set `fileName` if it's supported by this error object and // a `url` was provided. // The error will correctly point to `url` in Firefox. e.fileName = url; } e.message += url + ':' + e.lineNumber + ':' + e.columnNumber; } else { e.message += location.href; } e.message += createSourceCodeErrorMessage(code, e); throw e; } if (!transformed.sourceMap) { return transformed.code; } var source; if (url == null) { source = 'Inline JSX script'; inlineScriptCount++; if (inlineScriptCount > 1) { source += ' (' + inlineScriptCount + ')'; } } else if (dummyAnchor) { // Firefox has problems when the sourcemap source is a proper URL with a // protocol and hostname, so use the pathname. We could use just the // filename, but hopefully using the full path will prevent potential // issues where the same filename exists in multiple directories. dummyAnchor.href = url; source = dummyAnchor.pathname.substr(1); } return ( transformed.code + '\n' + inlineSourceMap(transformed.sourceMap, code, source) ); } /** * Appends a script element at the end of the <head> with the content of code, * after transforming it. * * @param {string} code The original source code * @param {string?} url Where the code came from. null if inline * @param {object?} options Options to pass to jstransform * @internal */ function run(code, url, options) { var scriptEl = document.createElement('script'); scriptEl.text = transformCode(code, url, options); headEl.appendChild(scriptEl); } /** * Load script from the provided url and pass the content to the callback. * * @param {string} url The location of the script src * @param {function} callback Function to call with the content of url * @internal */ function load(url, successCallback, errorCallback) { var xhr; xhr = window.ActiveXObject ? new window.ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest(); // async, however scripts will be executed in the order they are in the // DOM to mirror normal script loading. xhr.open('GET', url, true); if ('overrideMimeType' in xhr) { xhr.overrideMimeType('text/plain'); } xhr.onreadystatechange = function() { if (xhr.readyState === 4) { if (xhr.status === 0 || xhr.status === 200) { successCallback(xhr.responseText); } else { errorCallback(); throw new Error('Could not load ' + url); } } }; return xhr.send(null); } /** * Loop over provided script tags and get the content, via innerHTML if an * inline script, or by using XHR. Transforms are applied if needed. The scripts * are executed in the order they are found on the page. * * @param {array} scripts The <script> elements to load and run. * @internal */ function loadScripts(scripts) { var result = []; var count = scripts.length; function check() { var script, i; for (i = 0; i < count; i++) { script = result[i]; if (script.loaded && !script.executed) { script.executed = true; run(script.content, script.url, script.options); } else if (!script.loaded && !script.error && !script.async) { break; } } } scripts.forEach(function(script, i) { var options = { sourceMap: true }; if (/;harmony=true(;|$)/.test(script.type)) { options.harmony = true; } if (/;stripTypes=true(;|$)/.test(script.type)) { options.stripTypes = true; } // script.async is always true for non-javascript script tags var async = script.hasAttribute('async'); if (script.src) { result[i] = { async: async, error: false, executed: false, content: null, loaded: false, url: script.src, options: options }; load(script.src, function(content) { result[i].loaded = true; result[i].content = content; check(); }, function() { result[i].error = true; check(); }); } else { result[i] = { async: async, error: false, executed: false, content: script.innerHTML, loaded: true, url: null, options: options }; } }); check(); } /** * Find and run all script tags with type="text/jsx". * * @internal */ function runScripts() { var scripts = document.getElementsByTagName('script'); // Array.prototype.slice cannot be used on NodeList on IE8 var jsxScripts = []; for (var i = 0; i < scripts.length; i++) { if (/^text\/jsx(;|$)/.test(scripts.item(i).type)) { jsxScripts.push(scripts.item(i)); } } if (jsxScripts.length < 1) { return; } console.warn( 'You are using the in-browser JSX transformer. Be sure to precompile ' + 'your JSX for production - ' + 'http://facebook.github.io/react/docs/tooling-integration.html#jsx' ); loadScripts(jsxScripts); } // Listen for load event if we're in a browser and then kick off finding and // running of scripts. if (typeof window !== 'undefined' && window !== null) { headEl = document.getElementsByTagName('head')[0]; dummyAnchor = document.createElement('a'); if (window.addEventListener) { window.addEventListener('DOMContentLoaded', runScripts, false); } else { window.attachEvent('onload', runScripts); } } module.exports = { transform: transformReact, exec: exec }; },{"../main":2,"./inline-source-map":41}],2:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ 'use strict'; /*eslint-disable no-undef*/ var visitors = _dereq_('./vendor/fbtransform/visitors'); var transform = _dereq_('jstransform').transform; var typesSyntax = _dereq_('jstransform/visitors/type-syntax'); var inlineSourceMap = _dereq_('./vendor/inline-source-map'); module.exports = { transform: function(input, options) { options = processOptions(options); var output = innerTransform(input, options); var result = output.code; if (options.sourceMap) { var map = inlineSourceMap( output.sourceMap, input, options.filename ); result += '\n' + map; } return result; }, transformWithDetails: function(input, options) { options = processOptions(options); var output = innerTransform(input, options); var result = {}; result.code = output.code; if (options.sourceMap) { result.sourceMap = output.sourceMap.toJSON(); } if (options.filename) { result.sourceMap.sources = [options.filename]; } return result; } }; /** * Only copy the values that we need. We'll do some preprocessing to account for * converting command line flags to options that jstransform can actually use. */ function processOptions(opts) { opts = opts || {}; var options = {}; options.harmony = opts.harmony; options.stripTypes = opts.stripTypes; options.sourceMap = opts.sourceMap; options.filename = opts.sourceFilename; if (opts.es6module) { options.sourceType = 'module'; } if (opts.nonStrictEs6Module) { options.sourceType = 'nonStrict6Module'; } // Instead of doing any fancy validation, only look for 'es3'. If we have // that, then use it. Otherwise use 'es5'. options.es3 = opts.target === 'es3'; options.es5 = !options.es3; return options; } function innerTransform(input, options) { var visitorSets = ['react']; if (options.harmony) { visitorSets.push('harmony'); } if (options.es3) { visitorSets.push('es3'); } if (options.stripTypes) { // Stripping types needs to happen before the other transforms // unfortunately, due to bad interactions. For example, // es6-rest-param-visitors conflict with stripping rest param type // annotation input = transform(typesSyntax.visitorList, input, options).code; } var visitorList = visitors.getVisitorsBySet(visitorSets); return transform(visitorList, input, options); } },{"./vendor/fbtransform/visitors":40,"./vendor/inline-source-map":41,"jstransform":22,"jstransform/visitors/type-syntax":36}],3:[function(_dereq_,module,exports){ /*! * The buffer module from node.js, for the browser. * * @author Feross Aboukhadijeh <[email protected]> <http://feross.org> * @license MIT */ var base64 = _dereq_('base64-js') var ieee754 = _dereq_('ieee754') var isArray = _dereq_('is-array') exports.Buffer = Buffer exports.SlowBuffer = SlowBuffer exports.INSPECT_MAX_BYTES = 50 Buffer.poolSize = 8192 // not used by this implementation var kMaxLength = 0x3fffffff var rootParent = {} /** * If `Buffer.TYPED_ARRAY_SUPPORT`: * === true Use Uint8Array implementation (fastest) * === false Use Object implementation (most compatible, even IE6) * * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, * Opera 11.6+, iOS 4.2+. * * Note: * * - Implementation must support adding new properties to `Uint8Array` instances. * Firefox 4-29 lacked support, fixed in Firefox 30+. * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. * * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. * * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of * incorrect length in some situations. * * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they will * get the Object implementation, which is slower but will work correctly. */ Buffer.TYPED_ARRAY_SUPPORT = (function () { try { var buf = new ArrayBuffer(0) var arr = new Uint8Array(buf) arr.foo = function () { return 42 } return arr.foo() === 42 && // typed array instances can be augmented typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray` new Uint8Array(1).subarray(1, 1).byteLength === 0 // ie10 has broken `subarray` } catch (e) { return false } })() /** * Class: Buffer * ============= * * The Buffer constructor returns instances of `Uint8Array` that are augmented * with function properties for all the node `Buffer` API functions. We use * `Uint8Array` so that square bracket notation works as expected -- it returns * a single octet. * * By augmenting the instances, we can avoid modifying the `Uint8Array` * prototype. */ function Buffer (subject, encoding, noZero) { if (!(this instanceof Buffer)) return new Buffer(subject, encoding, noZero) var type = typeof subject // Find the length var length if (type === 'number') { length = +subject } else if (type === 'string') { length = Buffer.byteLength(subject, encoding) } else if (type === 'object' && subject !== null) { // assume object is array-like if (subject.type === 'Buffer' && isArray(subject.data)) subject = subject.data length = +subject.length } else { throw new TypeError('must start with number, buffer, array or string') } if (length > kMaxLength) throw new RangeError('Attempt to allocate Buffer larger than maximum ' + 'size: 0x' + kMaxLength.toString(16) + ' bytes') if (length < 0) length = 0 else length >>>= 0 // Coerce to uint32. var self = this if (Buffer.TYPED_ARRAY_SUPPORT) { // Preferred: Return an augmented `Uint8Array` instance for best performance /*eslint-disable consistent-this */ self = Buffer._augment(new Uint8Array(length)) /*eslint-enable consistent-this */ } else { // Fallback: Return THIS instance of Buffer (created by `new`) self.length = length self._isBuffer = true } var i if (Buffer.TYPED_ARRAY_SUPPORT && typeof subject.byteLength === 'number') { // Speed optimization -- use set if we're copying from a typed array self._set(subject) } else if (isArrayish(subject)) { // Treat array-ish objects as a byte array if (Buffer.isBuffer(subject)) { for (i = 0; i < length; i++) self[i] = subject.readUInt8(i) } else { for (i = 0; i < length; i++) self[i] = ((subject[i] % 256) + 256) % 256 } } else if (type === 'string') { self.write(subject, 0, encoding) } else if (type === 'number' && !Buffer.TYPED_ARRAY_SUPPORT && !noZero) { for (i = 0; i < length; i++) { self[i] = 0 } } if (length > 0 && length <= Buffer.poolSize) self.parent = rootParent return self } function SlowBuffer (subject, encoding, noZero) { if (!(this instanceof SlowBuffer)) return new SlowBuffer(subject, encoding, noZero) var buf = new Buffer(subject, encoding, noZero) delete buf.parent return buf } Buffer.isBuffer = function (b) { return !!(b != null && b._isBuffer) } Buffer.compare = function (a, b) { if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) throw new TypeError('Arguments must be Buffers') if (a === b) return 0 var x = a.length var y = b.length for (var i = 0, len = Math.min(x, y); i < len && a[i] === b[i]; i++) {} if (i !== len) { x = a[i] y = b[i] } if (x < y) return -1 if (y < x) return 1 return 0 } Buffer.isEncoding = function (encoding) { switch (String(encoding).toLowerCase()) { case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'raw': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return true default: return false } } Buffer.concat = function (list, totalLength) { if (!isArray(list)) throw new TypeError('Usage: Buffer.concat(list[, length])') if (list.length === 0) { return new Buffer(0) } else if (list.length === 1) { return list[0] } var i if (totalLength === undefined) { totalLength = 0 for (i = 0; i < list.length; i++) { totalLength += list[i].length } } var buf = new Buffer(totalLength) var pos = 0 for (i = 0; i < list.length; i++) { var item = list[i] item.copy(buf, pos) pos += item.length } return buf } Buffer.byteLength = function (str, encoding) { var ret str = str + '' switch (encoding || 'utf8') { case 'ascii': case 'binary': case 'raw': ret = str.length break case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': ret = str.length * 2 break case 'hex': ret = str.length >>> 1 break case 'utf8': case 'utf-8': ret = utf8ToBytes(str).length break case 'base64': ret = base64ToBytes(str).length break default: ret = str.length } return ret } // pre-set for values that may exist in the future Buffer.prototype.length = undefined Buffer.prototype.parent = undefined // toString(encoding, start=0, end=buffer.length) Buffer.prototype.toString = function (encoding, start, end) { var loweredCase = false start = start >>> 0 end = end === undefined || end === Infinity ? this.length : end >>> 0 if (!encoding) encoding = 'utf8' if (start < 0) start = 0 if (end > this.length) end = this.length if (end <= start) return '' while (true) { switch (encoding) { case 'hex': return hexSlice(this, start, end) case 'utf8': case 'utf-8': return utf8Slice(this, start, end) case 'ascii': return asciiSlice(this, start, end) case 'binary': return binarySlice(this, start, end) case 'base64': return base64Slice(this, start, end) case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return utf16leSlice(this, start, end) default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) encoding = (encoding + '').toLowerCase() loweredCase = true } } } Buffer.prototype.equals = function (b) { if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') if (this === b) return true return Buffer.compare(this, b) === 0 } Buffer.prototype.inspect = function () { var str = '' var max = exports.INSPECT_MAX_BYTES if (this.length > 0) { str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') if (this.length > max) str += ' ... ' } return '<Buffer ' + str + '>' } Buffer.prototype.compare = function (b) { if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') if (this === b) return 0 return Buffer.compare(this, b) } // `get` will be removed in Node 0.13+ Buffer.prototype.get = function (offset) { console.log('.get() is deprecated. Access using array indexes instead.') return this.readUInt8(offset) } // `set` will be removed in Node 0.13+ Buffer.prototype.set = function (v, offset) { console.log('.set() is deprecated. Access using array indexes instead.') return this.writeUInt8(v, offset) } function hexWrite (buf, string, offset, length) { offset = Number(offset) || 0 var remaining = buf.length - offset if (!length) { length = remaining } else { length = Number(length) if (length > remaining) { length = remaining } } // must be an even number of digits var strLen = string.length if (strLen % 2 !== 0) throw new Error('Invalid hex string') if (length > strLen / 2) { length = strLen / 2 } for (var i = 0; i < length; i++) { var byte = parseInt(string.substr(i * 2, 2), 16) if (isNaN(byte)) throw new Error('Invalid hex string') buf[offset + i] = byte } return i } function utf8Write (buf, string, offset, length) { var charsWritten = blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) return charsWritten } function asciiWrite (buf, string, offset, length) { var charsWritten = blitBuffer(asciiToBytes(string), buf, offset, length) return charsWritten } function binaryWrite (buf, string, offset, length) { return asciiWrite(buf, string, offset, length) } function base64Write (buf, string, offset, length) { var charsWritten = blitBuffer(base64ToBytes(string), buf, offset, length) return charsWritten } function utf16leWrite (buf, string, offset, length) { var charsWritten = blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) return charsWritten } Buffer.prototype.write = function (string, offset, length, encoding) { // Support both (string, offset, length, encoding) // and the legacy (string, encoding, offset, length) if (isFinite(offset)) { if (!isFinite(length)) { encoding = length length = undefined } } else { // legacy var swap = encoding encoding = offset offset = length length = swap } offset = Number(offset) || 0 if (length < 0 || offset < 0 || offset > this.length) throw new RangeError('attempt to write outside buffer bounds') var remaining = this.length - offset if (!length) { length = remaining } else { length = Number(length) if (length > remaining) { length = remaining } } encoding = String(encoding || 'utf8').toLowerCase() var ret switch (encoding) { case 'hex': ret = hexWrite(this, string, offset, length) break case 'utf8': case 'utf-8': ret = utf8Write(this, string, offset, length) break case 'ascii': ret = asciiWrite(this, string, offset, length) break case 'binary': ret = binaryWrite(this, string, offset, length) break case 'base64': ret = base64Write(this, string, offset, length) break case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': ret = utf16leWrite(this, string, offset, length) break default: throw new TypeError('Unknown encoding: ' + encoding) } return ret } Buffer.prototype.toJSON = function () { return { type: 'Buffer', data: Array.prototype.slice.call(this._arr || this, 0) } } function base64Slice (buf, start, end) { if (start === 0 && end === buf.length) { return base64.fromByteArray(buf) } else { return base64.fromByteArray(buf.slice(start, end)) } } function utf8Slice (buf, start, end) { var res = '' var tmp = '' end = Math.min(buf.length, end) for (var i = start; i < end; i++) { if (buf[i] <= 0x7F) { res += decodeUtf8Char(tmp) + String.fromCharCode(buf[i]) tmp = '' } else { tmp += '%' + buf[i].toString(16) } } return res + decodeUtf8Char(tmp) } function asciiSlice (buf, start, end) { var ret = '' end = Math.min(buf.length, end) for (var i = start; i < end; i++) { ret += String.fromCharCode(buf[i] & 0x7F) } return ret } function binarySlice (buf, start, end) { var ret = '' end = Math.min(buf.length, end) for (var i = start; i < end; i++) { ret += String.fromCharCode(buf[i]) } return ret } function hexSlice (buf, start, end) { var len = buf.length if (!start || start < 0) start = 0 if (!end || end < 0 || end > len) end = len var out = '' for (var i = start; i < end; i++) { out += toHex(buf[i]) } return out } function utf16leSlice (buf, start, end) { var bytes = buf.slice(start, end) var res = '' for (var i = 0; i < bytes.length; i += 2) { res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256) } return res } Buffer.prototype.slice = function (start, end) { var len = this.length start = ~~start end = end === undefined ? len : ~~end if (start < 0) { start += len if (start < 0) start = 0 } else if (start > len) { start = len } if (end < 0) { end += len if (end < 0) end = 0 } else if (end > len) { end = len } if (end < start) end = start var newBuf if (Buffer.TYPED_ARRAY_SUPPORT) { newBuf = Buffer._augment(this.subarray(start, end)) } else { var sliceLen = end - start newBuf = new Buffer(sliceLen, undefined, true) for (var i = 0; i < sliceLen; i++) { newBuf[i] = this[i + start] } } if (newBuf.length) newBuf.parent = this.parent || this return newBuf } /* * Need to make sure that buffer isn't trying to write out of bounds. */ function checkOffset (offset, ext, length) { if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') } Buffer.prototype.readUIntLE = function (offset, byteLength, noAssert) { offset = offset >>> 0 byteLength = byteLength >>> 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var val = this[offset] var mul = 1 var i = 0 while (++i < byteLength && (mul *= 0x100)) val += this[offset + i] * mul return val } Buffer.prototype.readUIntBE = function (offset, byteLength, noAssert) { offset = offset >>> 0 byteLength = byteLength >>> 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var val = this[offset + --byteLength] var mul = 1 while (byteLength > 0 && (mul *= 0x100)) val += this[offset + --byteLength] * mul return val } Buffer.prototype.readUInt8 = function (offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length) return this[offset] } Buffer.prototype.readUInt16LE = function (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length) return this[offset] | (this[offset + 1] << 8) } Buffer.prototype.readUInt16BE = function (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length) return (this[offset] << 8) | this[offset + 1] } Buffer.prototype.readUInt32LE = function (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return ((this[offset]) | (this[offset + 1] << 8) | (this[offset + 2] << 16)) + (this[offset + 3] * 0x1000000) } Buffer.prototype.readUInt32BE = function (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset] * 0x1000000) + ((this[offset + 1] << 16) | (this[offset + 2] << 8) | this[offset + 3]) } Buffer.prototype.readIntLE = function (offset, byteLength, noAssert) { offset = offset >>> 0 byteLength = byteLength >>> 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var val = this[offset] var mul = 1 var i = 0 while (++i < byteLength && (mul *= 0x100)) val += this[offset + i] * mul mul *= 0x80 if (val >= mul) val -= Math.pow(2, 8 * byteLength) return val } Buffer.prototype.readIntBE = function (offset, byteLength, noAssert) { offset = offset >>> 0 byteLength = byteLength >>> 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var i = byteLength var mul = 1 var val = this[offset + --i] while (i > 0 && (mul *= 0x100)) val += this[offset + --i] * mul mul *= 0x80 if (val >= mul) val -= Math.pow(2, 8 * byteLength) return val } Buffer.prototype.readInt8 = function (offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length) if (!(this[offset] & 0x80)) return (this[offset]) return ((0xff - this[offset] + 1) * -1) } Buffer.prototype.readInt16LE = function (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length) var val = this[offset] | (this[offset + 1] << 8) return (val & 0x8000) ? val | 0xFFFF0000 : val } Buffer.prototype.readInt16BE = function (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length) var val = this[offset + 1] | (this[offset] << 8) return (val & 0x8000) ? val | 0xFFFF0000 : val } Buffer.prototype.readInt32LE = function (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset]) | (this[offset + 1] << 8) | (this[offset + 2] << 16) | (this[offset + 3] << 24) } Buffer.prototype.readInt32BE = function (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset] << 24) | (this[offset + 1] << 16) | (this[offset + 2] << 8) | (this[offset + 3]) } Buffer.prototype.readFloatLE = function (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return ieee754.read(this, offset, true, 23, 4) } Buffer.prototype.readFloatBE = function (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return ieee754.read(this, offset, false, 23, 4) } Buffer.prototype.readDoubleLE = function (offset, noAssert) { if (!noAssert) checkOffset(offset, 8, this.length) return ieee754.read(this, offset, true, 52, 8) } Buffer.prototype.readDoubleBE = function (offset, noAssert) { if (!noAssert) checkOffset(offset, 8, this.length) return ieee754.read(this, offset, false, 52, 8) } function checkInt (buf, value, offset, ext, max, min) { if (!Buffer.isBuffer(buf)) throw new TypeError('buffer must be a Buffer instance') if (value > max || value < min) throw new RangeError('value is out of bounds') if (offset + ext > buf.length) throw new RangeError('index out of range') } Buffer.prototype.writeUIntLE = function (value, offset, byteLength, noAssert) { value = +value offset = offset >>> 0 byteLength = byteLength >>> 0 if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0) var mul = 1 var i = 0 this[offset] = value & 0xFF while (++i < byteLength && (mul *= 0x100)) this[offset + i] = (value / mul) >>> 0 & 0xFF return offset + byteLength } Buffer.prototype.writeUIntBE = function (value, offset, byteLength, noAssert) { value = +value offset = offset >>> 0 byteLength = byteLength >>> 0 if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0) var i = byteLength - 1 var mul = 1 this[offset + i] = value & 0xFF while (--i >= 0 && (mul *= 0x100)) this[offset + i] = (value / mul) >>> 0 & 0xFF return offset + byteLength } Buffer.prototype.writeUInt8 = function (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) this[offset] = value return offset + 1 } function objectWriteUInt16 (buf, value, offset, littleEndian) { if (value < 0) value = 0xffff + value + 1 for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; i++) { buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> (littleEndian ? i : 1 - i) * 8 } } Buffer.prototype.writeUInt16LE = function (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = value this[offset + 1] = (value >>> 8) } else objectWriteUInt16(this, value, offset, true) return offset + 2 } Buffer.prototype.writeUInt16BE = function (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 8) this[offset + 1] = value } else objectWriteUInt16(this, value, offset, false) return offset + 2 } function objectWriteUInt32 (buf, value, offset, littleEndian) { if (value < 0) value = 0xffffffff + value + 1 for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; i++) { buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff } } Buffer.prototype.writeUInt32LE = function (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset + 3] = (value >>> 24) this[offset + 2] = (value >>> 16) this[offset + 1] = (value >>> 8) this[offset] = value } else objectWriteUInt32(this, value, offset, true) return offset + 4 } Buffer.prototype.writeUInt32BE = function (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 24) this[offset + 1] = (value >>> 16) this[offset + 2] = (value >>> 8) this[offset + 3] = value } else objectWriteUInt32(this, value, offset, false) return offset + 4 } Buffer.prototype.writeIntLE = function (value, offset, byteLength, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) { checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength - 1) - 1, -Math.pow(2, 8 * byteLength - 1)) } var i = 0 var mul = 1 var sub = value < 0 ? 1 : 0 this[offset] = value & 0xFF while (++i < byteLength && (mul *= 0x100)) this[offset + i] = ((value / mul) >> 0) - sub & 0xFF return offset + byteLength } Buffer.prototype.writeIntBE = function (value, offset, byteLength, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) { checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength - 1) - 1, -Math.pow(2, 8 * byteLength - 1)) } var i = byteLength - 1 var mul = 1 var sub = value < 0 ? 1 : 0 this[offset + i] = value & 0xFF while (--i >= 0 && (mul *= 0x100)) this[offset + i] = ((value / mul) >> 0) - sub & 0xFF return offset + byteLength } Buffer.prototype.writeInt8 = function (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) if (value < 0) value = 0xff + value + 1 this[offset] = value return offset + 1 } Buffer.prototype.writeInt16LE = function (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = value this[offset + 1] = (value >>> 8) } else objectWriteUInt16(this, value, offset, true) return offset + 2 } Buffer.prototype.writeInt16BE = function (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 8) this[offset + 1] = value } else objectWriteUInt16(this, value, offset, false) return offset + 2 } Buffer.prototype.writeInt32LE = function (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = value this[offset + 1] = (value >>> 8) this[offset + 2] = (value >>> 16) this[offset + 3] = (value >>> 24) } else objectWriteUInt32(this, value, offset, true) return offset + 4 } Buffer.prototype.writeInt32BE = function (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) if (value < 0) value = 0xffffffff + value + 1 if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 24) this[offset + 1] = (value >>> 16) this[offset + 2] = (value >>> 8) this[offset + 3] = value } else objectWriteUInt32(this, value, offset, false) return offset + 4 } function checkIEEE754 (buf, value, offset, ext, max, min) { if (value > max || value < min) throw new RangeError('value is out of bounds') if (offset + ext > buf.length) throw new RangeError('index out of range') if (offset < 0) throw new RangeError('index out of range') } function writeFloat (buf, value, offset, littleEndian, noAssert) { if (!noAssert) checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) ieee754.write(buf, value, offset, littleEndian, 23, 4) return offset + 4 } Buffer.prototype.writeFloatLE = function (value, offset, noAssert) { return writeFloat(this, value, offset, true, noAssert) } Buffer.prototype.writeFloatBE = function (value, offset, noAssert) { return writeFloat(this, value, offset, false, noAssert) } function writeDouble (buf, value, offset, littleEndian, noAssert) { if (!noAssert) checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) ieee754.write(buf, value, offset, littleEndian, 52, 8) return offset + 8 } Buffer.prototype.writeDoubleLE = function (value, offset, noAssert) { return writeDouble(this, value, offset, true, noAssert) } Buffer.prototype.writeDoubleBE = function (value, offset, noAssert) { return writeDouble(this, value, offset, false, noAssert) } // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) Buffer.prototype.copy = function (target, target_start, start, end) { var self = this // source if (!start) start = 0 if (!end && end !== 0) end = this.length if (target_start >= target.length) target_start = target.length if (!target_start) target_start = 0 if (end > 0 && end < start) end = start // Copy 0 bytes; we're done if (end === start) return 0 if (target.length === 0 || self.length === 0) return 0 // Fatal error conditions if (target_start < 0) throw new RangeError('targetStart out of bounds') if (start < 0 || start >= self.length) throw new RangeError('sourceStart out of bounds') if (end < 0) throw new RangeError('sourceEnd out of bounds') // Are we oob? if (end > this.length) end = this.length if (target.length - target_start < end - start) end = target.length - target_start + start var len = end - start if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { for (var i = 0; i < len; i++) { target[i + target_start] = this[i + start] } } else { target._set(this.subarray(start, start + len), target_start) } return len } // fill(value, start=0, end=buffer.length) Buffer.prototype.fill = function (value, start, end) { if (!value) value = 0 if (!start) start = 0 if (!end) end = this.length if (end < start) throw new RangeError('end < start') // Fill 0 bytes; we're done if (end === start) return if (this.length === 0) return if (start < 0 || start >= this.length) throw new RangeError('start out of bounds') if (end < 0 || end > this.length) throw new RangeError('end out of bounds') var i if (typeof value === 'number') { for (i = start; i < end; i++) { this[i] = value } } else { var bytes = utf8ToBytes(value.toString()) var len = bytes.length for (i = start; i < end; i++) { this[i] = bytes[i % len] } } return this } /** * Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance. * Added in Node 0.12. Only available in browsers that support ArrayBuffer. */ Buffer.prototype.toArrayBuffer = function () { if (typeof Uint8Array !== 'undefined') { if (Buffer.TYPED_ARRAY_SUPPORT) { return (new Buffer(this)).buffer } else { var buf = new Uint8Array(this.length) for (var i = 0, len = buf.length; i < len; i += 1) { buf[i] = this[i] } return buf.buffer } } else { throw new TypeError('Buffer.toArrayBuffer not supported in this browser') } } // HELPER FUNCTIONS // ================ var BP = Buffer.prototype /** * Augment a Uint8Array *instance* (not the Uint8Array class!) with Buffer methods */ Buffer._augment = function (arr) { arr.constructor = Buffer arr._isBuffer = true // save reference to original Uint8Array get/set methods before overwriting arr._get = arr.get arr._set = arr.set // deprecated, will be removed in node 0.13+ arr.get = BP.get arr.set = BP.set arr.write = BP.write arr.toString = BP.toString arr.toLocaleString = BP.toString arr.toJSON = BP.toJSON arr.equals = BP.equals arr.compare = BP.compare arr.copy = BP.copy arr.slice = BP.slice arr.readUIntLE = BP.readUIntLE arr.readUIntBE = BP.readUIntBE arr.readUInt8 = BP.readUInt8 arr.readUInt16LE = BP.readUInt16LE arr.readUInt16BE = BP.readUInt16BE arr.readUInt32LE = BP.readUInt32LE arr.readUInt32BE = BP.readUInt32BE arr.readIntLE = BP.readIntLE arr.readIntBE = BP.readIntBE arr.readInt8 = BP.readInt8 arr.readInt16LE = BP.readInt16LE arr.readInt16BE = BP.readInt16BE arr.readInt32LE = BP.readInt32LE arr.readInt32BE = BP.readInt32BE arr.readFloatLE = BP.readFloatLE arr.readFloatBE = BP.readFloatBE arr.readDoubleLE = BP.readDoubleLE arr.readDoubleBE = BP.readDoubleBE arr.writeUInt8 = BP.writeUInt8 arr.writeUIntLE = BP.writeUIntLE arr.writeUIntBE = BP.writeUIntBE arr.writeUInt16LE = BP.writeUInt16LE arr.writeUInt16BE = BP.writeUInt16BE arr.writeUInt32LE = BP.writeUInt32LE arr.writeUInt32BE = BP.writeUInt32BE arr.writeIntLE = BP.writeIntLE arr.writeIntBE = BP.writeIntBE arr.writeInt8 = BP.writeInt8 arr.writeInt16LE = BP.writeInt16LE arr.writeInt16BE = BP.writeInt16BE arr.writeInt32LE = BP.writeInt32LE arr.writeInt32BE = BP.writeInt32BE arr.writeFloatLE = BP.writeFloatLE arr.writeFloatBE = BP.writeFloatBE arr.writeDoubleLE = BP.writeDoubleLE arr.writeDoubleBE = BP.writeDoubleBE arr.fill = BP.fill arr.inspect = BP.inspect arr.toArrayBuffer = BP.toArrayBuffer return arr } var INVALID_BASE64_RE = /[^+\/0-9A-z\-]/g function base64clean (str) { // Node strips out invalid characters like \n and \t from the string, base64-js does not str = stringtrim(str).replace(INVALID_BASE64_RE, '') // Node converts strings with length < 2 to '' if (str.length < 2) return '' // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not while (str.length % 4 !== 0) { str = str + '=' } return str } function stringtrim (str) { if (str.trim) return str.trim() return str.replace(/^\s+|\s+$/g, '') } function isArrayish (subject) { return isArray(subject) || Buffer.isBuffer(subject) || subject && typeof subject === 'object' && typeof subject.length === 'number' } function toHex (n) { if (n < 16) return '0' + n.toString(16) return n.toString(16) } function utf8ToBytes (string, units) { units = units || Infinity var codePoint var length = string.length var leadSurrogate = null var bytes = [] var i = 0 for (; i < length; i++) { codePoint = string.charCodeAt(i) // is surrogate component if (codePoint > 0xD7FF && codePoint < 0xE000) { // last char was a lead if (leadSurrogate) { // 2 leads in a row if (codePoint < 0xDC00) { if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) leadSurrogate = codePoint continue } else { // valid surrogate pair codePoint = leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00 | 0x10000 leadSurrogate = null } } else { // no lead yet if (codePoint > 0xDBFF) { // unexpected trail if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) continue } else if (i + 1 === length) { // unpaired lead if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) continue } else { // valid lead leadSurrogate = codePoint continue } } } else if (leadSurrogate) { // valid bmp char, but last char was a lead if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) leadSurrogate = null } // encode utf8 if (codePoint < 0x80) { if ((units -= 1) < 0) break bytes.push(codePoint) } else if (codePoint < 0x800) { if ((units -= 2) < 0) break bytes.push( codePoint >> 0x6 | 0xC0, codePoint & 0x3F | 0x80 ) } else if (codePoint < 0x10000) { if ((units -= 3) < 0) break bytes.push( codePoint >> 0xC | 0xE0, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80 ) } else if (codePoint < 0x200000) { if ((units -= 4) < 0) break bytes.push( codePoint >> 0x12 | 0xF0, codePoint >> 0xC & 0x3F | 0x80, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80 ) } else { throw new Error('Invalid code point') } } return bytes } function asciiToBytes (str) { var byteArray = [] for (var i = 0; i < str.length; i++) { // Node's code seems to be doing this and not & 0x7F.. byteArray.push(str.charCodeAt(i) & 0xFF) } return byteArray } function utf16leToBytes (str, units) { var c, hi, lo var byteArray = [] for (var i = 0; i < str.length; i++) { if ((units -= 2) < 0) break c = str.charCodeAt(i) hi = c >> 8 lo = c % 256 byteArray.push(lo) byteArray.push(hi) } return byteArray } function base64ToBytes (str) { return base64.toByteArray(base64clean(str)) } function blitBuffer (src, dst, offset, length) { for (var i = 0; i < length; i++) { if ((i + offset >= dst.length) || (i >= src.length)) break dst[i + offset] = src[i] } return i } function decodeUtf8Char (str) { try { return decodeURIComponent(str) } catch (err) { return String.fromCharCode(0xFFFD) // UTF 8 invalid char } } },{"base64-js":4,"ieee754":5,"is-array":6}],4:[function(_dereq_,module,exports){ var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; ;(function (exports) { 'use strict'; var Arr = (typeof Uint8Array !== 'undefined') ? Uint8Array : Array var PLUS = '+'.charCodeAt(0) var SLASH = '/'.charCodeAt(0) var NUMBER = '0'.charCodeAt(0) var LOWER = 'a'.charCodeAt(0) var UPPER = 'A'.charCodeAt(0) var PLUS_URL_SAFE = '-'.charCodeAt(0) var SLASH_URL_SAFE = '_'.charCodeAt(0) function decode (elt) { var code = elt.charCodeAt(0) if (code === PLUS || code === PLUS_URL_SAFE) return 62 // '+' if (code === SLASH || code === SLASH_URL_SAFE) return 63 // '/' if (code < NUMBER) return -1 //no match if (code < NUMBER + 10) return code - NUMBER + 26 + 26 if (code < UPPER + 26) return code - UPPER if (code < LOWER + 26) return code - LOWER + 26 } function b64ToByteArray (b64) { var i, j, l, tmp, placeHolders, arr if (b64.length % 4 > 0) { throw new Error('Invalid string. Length must be a multiple of 4') } // the number of equal signs (place holders) // if there are two placeholders, than the two characters before it // represent one byte // if there is only one, then the three characters before it represent 2 bytes // this is just a cheap hack to not do indexOf twice var len = b64.length placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0 // base64 is 4/3 + up to two characters of the original data arr = new Arr(b64.length * 3 / 4 - placeHolders) // if there are placeholders, only get up to the last complete 4 chars l = placeHolders > 0 ? b64.length - 4 : b64.length var L = 0 function push (v) { arr[L++] = v } for (i = 0, j = 0; i < l; i += 4, j += 3) { tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3)) push((tmp & 0xFF0000) >> 16) push((tmp & 0xFF00) >> 8) push(tmp & 0xFF) } if (placeHolders === 2) { tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4) push(tmp & 0xFF) } else if (placeHolders === 1) { tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2) push((tmp >> 8) & 0xFF) push(tmp & 0xFF) } return arr } function uint8ToBase64 (uint8) { var i, extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes output = "", temp, length function encode (num) { return lookup.charAt(num) } function tripletToBase64 (num) { return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F) } // go through the array every three bytes, we'll deal with trailing stuff later for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) { temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) output += tripletToBase64(temp) } // pad the end with zeros, but make sure to not forget the extra bytes switch (extraBytes) { case 1: temp = uint8[uint8.length - 1] output += encode(temp >> 2) output += encode((temp << 4) & 0x3F) output += '==' break case 2: temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1]) output += encode(temp >> 10) output += encode((temp >> 4) & 0x3F) output += encode((temp << 2) & 0x3F) output += '=' break } return output } exports.toByteArray = b64ToByteArray exports.fromByteArray = uint8ToBase64 }(typeof exports === 'undefined' ? (this.base64js = {}) : exports)) },{}],5:[function(_dereq_,module,exports){ exports.read = function(buffer, offset, isLE, mLen, nBytes) { var e, m, eLen = nBytes * 8 - mLen - 1, eMax = (1 << eLen) - 1, eBias = eMax >> 1, nBits = -7, i = isLE ? (nBytes - 1) : 0, d = isLE ? -1 : 1, s = buffer[offset + i]; i += d; e = s & ((1 << (-nBits)) - 1); s >>= (-nBits); nBits += eLen; for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8); m = e & ((1 << (-nBits)) - 1); e >>= (-nBits); nBits += mLen; for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8); if (e === 0) { e = 1 - eBias; } else if (e === eMax) { return m ? NaN : ((s ? -1 : 1) * Infinity); } else { m = m + Math.pow(2, mLen); e = e - eBias; } return (s ? -1 : 1) * m * Math.pow(2, e - mLen); }; exports.write = function(buffer, value, offset, isLE, mLen, nBytes) { var e, m, c, eLen = nBytes * 8 - mLen - 1, eMax = (1 << eLen) - 1, eBias = eMax >> 1, rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0), i = isLE ? 0 : (nBytes - 1), d = isLE ? 1 : -1, s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; value = Math.abs(value); if (isNaN(value) || value === Infinity) { m = isNaN(value) ? 1 : 0; e = eMax; } else { e = Math.floor(Math.log(value) / Math.LN2); if (value * (c = Math.pow(2, -e)) < 1) { e--; c *= 2; } if (e + eBias >= 1) { value += rt / c; } else { value += rt * Math.pow(2, 1 - eBias); } if (value * c >= 2) { e++; c /= 2; } if (e + eBias >= eMax) { m = 0; e = eMax; } else if (e + eBias >= 1) { m = (value * c - 1) * Math.pow(2, mLen); e = e + eBias; } else { m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); e = 0; } } for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8); e = (e << mLen) | m; eLen += mLen; for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8); buffer[offset + i - d] |= s * 128; }; },{}],6:[function(_dereq_,module,exports){ /** * isArray */ var isArray = Array.isArray; /** * toString */ var str = Object.prototype.toString; /** * Whether or not the given `val` * is an array. * * example: * * isArray([]); * // > true * isArray(arguments); * // > false * isArray(''); * // > false * * @param {mixed} val * @return {bool} */ module.exports = isArray || function (val) { return !! val && '[object Array]' == str.call(val); }; },{}],7:[function(_dereq_,module,exports){ (function (process){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // resolves . and .. elements in a path array with directory names there // must be no slashes, empty elements, or device names (c:\) in the array // (so also no leading and trailing slashes - it does not distinguish // relative and absolute paths) function normalizeArray(parts, allowAboveRoot) { // if the path tries to go above the root, `up` ends up > 0 var up = 0; for (var i = parts.length - 1; i >= 0; i--) { var last = parts[i]; if (last === '.') { parts.splice(i, 1); } else if (last === '..') { parts.splice(i, 1); up++; } else if (up) { parts.splice(i, 1); up--; } } // if the path is allowed to go above the root, restore leading ..s if (allowAboveRoot) { for (; up--; up) { parts.unshift('..'); } } return parts; } // Split a filename into [root, dir, basename, ext], unix version // 'root' is just a slash, or nothing. var splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/; var splitPath = function(filename) { return splitPathRe.exec(filename).slice(1); }; // path.resolve([from ...], to) // posix version exports.resolve = function() { var resolvedPath = '', resolvedAbsolute = false; for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { var path = (i >= 0) ? arguments[i] : process.cwd(); // Skip empty and invalid entries if (typeof path !== 'string') { throw new TypeError('Arguments to path.resolve must be strings'); } else if (!path) { continue; } resolvedPath = path + '/' + resolvedPath; resolvedAbsolute = path.charAt(0) === '/'; } // At this point the path should be resolved to a full absolute path, but // handle relative paths to be safe (might happen when process.cwd() fails) // Normalize the path resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) { return !!p; }), !resolvedAbsolute).join('/'); return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.'; }; // path.normalize(path) // posix version exports.normalize = function(path) { var isAbsolute = exports.isAbsolute(path), trailingSlash = substr(path, -1) === '/'; // Normalize the path path = normalizeArray(filter(path.split('/'), function(p) { return !!p; }), !isAbsolute).join('/'); if (!path && !isAbsolute) { path = '.'; } if (path && trailingSlash) { path += '/'; } return (isAbsolute ? '/' : '') + path; }; // posix version exports.isAbsolute = function(path) { return path.charAt(0) === '/'; }; // posix version exports.join = function() { var paths = Array.prototype.slice.call(arguments, 0); return exports.normalize(filter(paths, function(p, index) { if (typeof p !== 'string') { throw new TypeError('Arguments to path.join must be strings'); } return p; }).join('/')); }; // path.relative(from, to) // posix version exports.relative = function(from, to) { from = exports.resolve(from).substr(1); to = exports.resolve(to).substr(1); function trim(arr) { var start = 0; for (; start < arr.length; start++) { if (arr[start] !== '') break; } var end = arr.length - 1; for (; end >= 0; end--) { if (arr[end] !== '') break; } if (start > end) return []; return arr.slice(start, end - start + 1); } var fromParts = trim(from.split('/')); var toParts = trim(to.split('/')); var length = Math.min(fromParts.length, toParts.length); var samePartsLength = length; for (var i = 0; i < length; i++) { if (fromParts[i] !== toParts[i]) { samePartsLength = i; break; } } var outputParts = []; for (var i = samePartsLength; i < fromParts.length; i++) { outputParts.push('..'); } outputParts = outputParts.concat(toParts.slice(samePartsLength)); return outputParts.join('/'); }; exports.sep = '/'; exports.delimiter = ':'; exports.dirname = function(path) { var result = splitPath(path), root = result[0], dir = result[1]; if (!root && !dir) { // No dirname whatsoever return '.'; } if (dir) { // It has a dirname, strip trailing slash dir = dir.substr(0, dir.length - 1); } return root + dir; }; exports.basename = function(path, ext) { var f = splitPath(path)[2]; // TODO: make this comparison case-insensitive on windows? if (ext && f.substr(-1 * ext.length) === ext) { f = f.substr(0, f.length - ext.length); } return f; }; exports.extname = function(path) { return splitPath(path)[3]; }; function filter (xs, f) { if (xs.filter) return xs.filter(f); var res = []; for (var i = 0; i < xs.length; i++) { if (f(xs[i], i, xs)) res.push(xs[i]); } return res; } // String.prototype.substr - negative index don't work in IE8 var substr = 'ab'.substr(-1) === 'b' ? function (str, start, len) { return str.substr(start, len) } : function (str, start, len) { if (start < 0) start = str.length + start; return str.substr(start, len); } ; }).call(this,_dereq_('_process')) },{"_process":8}],8:[function(_dereq_,module,exports){ // shim for using process in browser var process = module.exports = {}; var queue = []; var draining = false; function drainQueue() { if (draining) { return; } draining = true; var currentQueue; var len = queue.length; while(len) { currentQueue = queue; queue = []; var i = -1; while (++i < len) { currentQueue[i](); } len = queue.length; } draining = false; } process.nextTick = function (fun) { queue.push(fun); if (!draining) { setTimeout(drainQueue, 0); } }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); }; // TODO(shtylman) process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; },{}],9:[function(_dereq_,module,exports){ /* Copyright (C) 2013 Ariya Hidayat <[email protected]> Copyright (C) 2013 Thaddee Tyl <[email protected]> Copyright (C) 2012 Ariya Hidayat <[email protected]> Copyright (C) 2012 Mathias Bynens <[email protected]> Copyright (C) 2012 Joost-Wim Boekesteijn <[email protected]> Copyright (C) 2012 Kris Kowal <[email protected]> Copyright (C) 2012 Yusuke Suzuki <[email protected]> Copyright (C) 2012 Arpad Borsos <[email protected]> Copyright (C) 2011 Ariya Hidayat <[email protected]> Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ (function (root, factory) { 'use strict'; // Universal Module Definition (UMD) to support AMD, CommonJS/Node.js, // Rhino, and plain browser loading. /* istanbul ignore next */ if (typeof define === 'function' && define.amd) { define(['exports'], factory); } else if (typeof exports !== 'undefined') { factory(exports); } else { factory((root.esprima = {})); } }(this, function (exports) { 'use strict'; var Token, TokenName, FnExprTokens, Syntax, PropertyKind, Messages, Regex, SyntaxTreeDelegate, XHTMLEntities, ClassPropertyType, source, strict, index, lineNumber, lineStart, length, delegate, lookahead, state, extra; Token = { BooleanLiteral: 1, EOF: 2, Identifier: 3, Keyword: 4, NullLiteral: 5, NumericLiteral: 6, Punctuator: 7, StringLiteral: 8, RegularExpression: 9, Template: 10, JSXIdentifier: 11, JSXText: 12 }; TokenName = {}; TokenName[Token.BooleanLiteral] = 'Boolean'; TokenName[Token.EOF] = '<end>'; TokenName[Token.Identifier] = 'Identifier'; TokenName[Token.Keyword] = 'Keyword'; TokenName[Token.NullLiteral] = 'Null'; TokenName[Token.NumericLiteral] = 'Numeric'; TokenName[Token.Punctuator] = 'Punctuator'; TokenName[Token.StringLiteral] = 'String'; TokenName[Token.JSXIdentifier] = 'JSXIdentifier'; TokenName[Token.JSXText] = 'JSXText'; TokenName[Token.RegularExpression] = 'RegularExpression'; // A function following one of those tokens is an expression. FnExprTokens = ['(', '{', '[', 'in', 'typeof', 'instanceof', 'new', 'return', 'case', 'delete', 'throw', 'void', // assignment operators '=', '+=', '-=', '*=', '/=', '%=', '<<=', '>>=', '>>>=', '&=', '|=', '^=', ',', // binary/unary operators '+', '-', '*', '/', '%', '++', '--', '<<', '>>', '>>>', '&', '|', '^', '!', '~', '&&', '||', '?', ':', '===', '==', '>=', '<=', '<', '>', '!=', '!==']; Syntax = { AnyTypeAnnotation: 'AnyTypeAnnotation', ArrayExpression: 'ArrayExpression', ArrayPattern: 'ArrayPattern', ArrayTypeAnnotation: 'ArrayTypeAnnotation', ArrowFunctionExpression: 'ArrowFunctionExpression', AssignmentExpression: 'AssignmentExpression', BinaryExpression: 'BinaryExpression', BlockStatement: 'BlockStatement', BooleanTypeAnnotation: 'BooleanTypeAnnotation', BreakStatement: 'BreakStatement', CallExpression: 'CallExpression', CatchClause: 'CatchClause', ClassBody: 'ClassBody', ClassDeclaration: 'ClassDeclaration', ClassExpression: 'ClassExpression', ClassImplements: 'ClassImplements', ClassProperty: 'ClassProperty', ComprehensionBlock: 'ComprehensionBlock', ComprehensionExpression: 'ComprehensionExpression', ConditionalExpression: 'ConditionalExpression', ContinueStatement: 'ContinueStatement', DebuggerStatement: 'DebuggerStatement', DeclareClass: 'DeclareClass', DeclareFunction: 'DeclareFunction', DeclareModule: 'DeclareModule', DeclareVariable: 'DeclareVariable', DoWhileStatement: 'DoWhileStatement', EmptyStatement: 'EmptyStatement', ExportDeclaration: 'ExportDeclaration', ExportBatchSpecifier: 'ExportBatchSpecifier', ExportSpecifier: 'ExportSpecifier', ExpressionStatement: 'ExpressionStatement', ForInStatement: 'ForInStatement', ForOfStatement: 'ForOfStatement', ForStatement: 'ForStatement', FunctionDeclaration: 'FunctionDeclaration', FunctionExpression: 'FunctionExpression', FunctionTypeAnnotation: 'FunctionTypeAnnotation', FunctionTypeParam: 'FunctionTypeParam', GenericTypeAnnotation: 'GenericTypeAnnotation', Identifier: 'Identifier', IfStatement: 'IfStatement', ImportDeclaration: 'ImportDeclaration', ImportDefaultSpecifier: 'ImportDefaultSpecifier', ImportNamespaceSpecifier: 'ImportNamespaceSpecifier', ImportSpecifier: 'ImportSpecifier', InterfaceDeclaration: 'InterfaceDeclaration', InterfaceExtends: 'InterfaceExtends', IntersectionTypeAnnotation: 'IntersectionTypeAnnotation', LabeledStatement: 'LabeledStatement', Literal: 'Literal', LogicalExpression: 'LogicalExpression', MemberExpression: 'MemberExpression', MethodDefinition: 'MethodDefinition', ModuleSpecifier: 'ModuleSpecifier', NewExpression: 'NewExpression', NullableTypeAnnotation: 'NullableTypeAnnotation', NumberTypeAnnotation: 'NumberTypeAnnotation', ObjectExpression: 'ObjectExpression', ObjectPattern: 'ObjectPattern', ObjectTypeAnnotation: 'ObjectTypeAnnotation', ObjectTypeCallProperty: 'ObjectTypeCallProperty', ObjectTypeIndexer: 'ObjectTypeIndexer', ObjectTypeProperty: 'ObjectTypeProperty', Program: 'Program', Property: 'Property', QualifiedTypeIdentifier: 'QualifiedTypeIdentifier', ReturnStatement: 'ReturnStatement', SequenceExpression: 'SequenceExpression', SpreadElement: 'SpreadElement', SpreadProperty: 'SpreadProperty', StringLiteralTypeAnnotation: 'StringLiteralTypeAnnotation', StringTypeAnnotation: 'StringTypeAnnotation', SwitchCase: 'SwitchCase', SwitchStatement: 'SwitchStatement', TaggedTemplateExpression: 'TaggedTemplateExpression', TemplateElement: 'TemplateElement', TemplateLiteral: 'TemplateLiteral', ThisExpression: 'ThisExpression', ThrowStatement: 'ThrowStatement', TupleTypeAnnotation: 'TupleTypeAnnotation', TryStatement: 'TryStatement', TypeAlias: 'TypeAlias', TypeAnnotation: 'TypeAnnotation', TypeCastExpression: 'TypeCastExpression', TypeofTypeAnnotation: 'TypeofTypeAnnotation', TypeParameterDeclaration: 'TypeParameterDeclaration', TypeParameterInstantiation: 'TypeParameterInstantiation', UnaryExpression: 'UnaryExpression', UnionTypeAnnotation: 'UnionTypeAnnotation', UpdateExpression: 'UpdateExpression', VariableDeclaration: 'VariableDeclaration', VariableDeclarator: 'VariableDeclarator', VoidTypeAnnotation: 'VoidTypeAnnotation', WhileStatement: 'WhileStatement', WithStatement: 'WithStatement', JSXIdentifier: 'JSXIdentifier', JSXNamespacedName: 'JSXNamespacedName', JSXMemberExpression: 'JSXMemberExpression', JSXEmptyExpression: 'JSXEmptyExpression', JSXExpressionContainer: 'JSXExpressionContainer', JSXElement: 'JSXElement', JSXClosingElement: 'JSXClosingElement', JSXOpeningElement: 'JSXOpeningElement', JSXAttribute: 'JSXAttribute', JSXSpreadAttribute: 'JSXSpreadAttribute', JSXText: 'JSXText', YieldExpression: 'YieldExpression', AwaitExpression: 'AwaitExpression' }; PropertyKind = { Data: 1, Get: 2, Set: 4 }; ClassPropertyType = { 'static': 'static', prototype: 'prototype' }; // Error messages should be identical to V8. Messages = { UnexpectedToken: 'Unexpected token %0', UnexpectedNumber: 'Unexpected number', UnexpectedString: 'Unexpected string', UnexpectedIdentifier: 'Unexpected identifier', UnexpectedReserved: 'Unexpected reserved word', UnexpectedTemplate: 'Unexpected quasi %0', UnexpectedEOS: 'Unexpected end of input', NewlineAfterThrow: 'Illegal newline after throw', InvalidRegExp: 'Invalid regular expression', UnterminatedRegExp: 'Invalid regular expression: missing /', InvalidLHSInAssignment: 'Invalid left-hand side in assignment', InvalidLHSInFormalsList: 'Invalid left-hand side in formals list', InvalidLHSInForIn: 'Invalid left-hand side in for-in', MultipleDefaultsInSwitch: 'More than one default clause in switch statement', NoCatchOrFinally: 'Missing catch or finally after try', UnknownLabel: 'Undefined label \'%0\'', Redeclaration: '%0 \'%1\' has already been declared', IllegalContinue: 'Illegal continue statement', IllegalBreak: 'Illegal break statement', IllegalDuplicateClassProperty: 'Illegal duplicate property in class definition', IllegalClassConstructorProperty: 'Illegal constructor property in class definition', IllegalReturn: 'Illegal return statement', IllegalSpread: 'Illegal spread element', StrictModeWith: 'Strict mode code may not include a with statement', StrictCatchVariable: 'Catch variable may not be eval or arguments in strict mode', StrictVarName: 'Variable name may not be eval or arguments in strict mode', StrictParamName: 'Parameter name eval or arguments is not allowed in strict mode', StrictParamDupe: 'Strict mode function may not have duplicate parameter names', ParameterAfterRestParameter: 'Rest parameter must be final parameter of an argument list', DefaultRestParameter: 'Rest parameter can not have a default value', ElementAfterSpreadElement: 'Spread must be the final element of an element list', PropertyAfterSpreadProperty: 'A rest property must be the final property of an object literal', ObjectPatternAsRestParameter: 'Invalid rest parameter', ObjectPatternAsSpread: 'Invalid spread argument', StrictFunctionName: 'Function name may not be eval or arguments in strict mode', StrictOctalLiteral: 'Octal literals are not allowed in strict mode.', StrictDelete: 'Delete of an unqualified identifier in strict mode.', StrictDuplicateProperty: 'Duplicate data property in object literal not allowed in strict mode', AccessorDataProperty: 'Object literal may not have data and accessor property with the same name', AccessorGetSet: 'Object literal may not have multiple get/set accessors with the same name', StrictLHSAssignment: 'Assignment to eval or arguments is not allowed in strict mode', StrictLHSPostfix: 'Postfix increment/decrement may not have eval or arguments operand in strict mode', StrictLHSPrefix: 'Prefix increment/decrement may not have eval or arguments operand in strict mode', StrictReservedWord: 'Use of future reserved word in strict mode', MissingFromClause: 'Missing from clause', NoAsAfterImportNamespace: 'Missing as after import *', InvalidModuleSpecifier: 'Invalid module specifier', IllegalImportDeclaration: 'Illegal import declaration', IllegalExportDeclaration: 'Illegal export declaration', NoUninitializedConst: 'Const must be initialized', ComprehensionRequiresBlock: 'Comprehension must have at least one block', ComprehensionError: 'Comprehension Error', EachNotAllowed: 'Each is not supported', InvalidJSXAttributeValue: 'JSX value should be either an expression or a quoted JSX text', ExpectedJSXClosingTag: 'Expected corresponding JSX closing tag for %0', AdjacentJSXElements: 'Adjacent JSX elements must be wrapped in an enclosing tag', ConfusedAboutFunctionType: 'Unexpected token =>. It looks like ' + 'you are trying to write a function type, but you ended up ' + 'writing a grouped type followed by an =>, which is a syntax ' + 'error. Remember, function type parameters are named so function ' + 'types look like (name1: type1, name2: type2) => returnType. You ' + 'probably wrote (type1) => returnType' }; // See also tools/generate-unicode-regex.py. Regex = { NonAsciiIdentifierStart: new RegExp('[\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc]'), NonAsciiIdentifierPart: new RegExp('[\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0300-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u0483-\u0487\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u05d0-\u05ea\u05f0-\u05f2\u0610-\u061a\u0620-\u0669\u066e-\u06d3\u06d5-\u06dc\u06df-\u06e8\u06ea-\u06fc\u06ff\u0710-\u074a\u074d-\u07b1\u07c0-\u07f5\u07fa\u0800-\u082d\u0840-\u085b\u08a0\u08a2-\u08ac\u08e4-\u08fe\u0900-\u0963\u0966-\u096f\u0971-\u0977\u0979-\u097f\u0981-\u0983\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bc-\u09c4\u09c7\u09c8\u09cb-\u09ce\u09d7\u09dc\u09dd\u09df-\u09e3\u09e6-\u09f1\u0a01-\u0a03\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a59-\u0a5c\u0a5e\u0a66-\u0a75\u0a81-\u0a83\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abc-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ad0\u0ae0-\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3c-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b5c\u0b5d\u0b5f-\u0b63\u0b66-\u0b6f\u0b71\u0b82\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd0\u0bd7\u0be6-\u0bef\u0c01-\u0c03\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c58\u0c59\u0c60-\u0c63\u0c66-\u0c6f\u0c82\u0c83\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbc-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0cde\u0ce0-\u0ce3\u0ce6-\u0cef\u0cf1\u0cf2\u0d02\u0d03\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d-\u0d44\u0d46-\u0d48\u0d4a-\u0d4e\u0d57\u0d60-\u0d63\u0d66-\u0d6f\u0d7a-\u0d7f\u0d82\u0d83\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0df2\u0df3\u0e01-\u0e3a\u0e40-\u0e4e\u0e50-\u0e59\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb9\u0ebb-\u0ebd\u0ec0-\u0ec4\u0ec6\u0ec8-\u0ecd\u0ed0-\u0ed9\u0edc-\u0edf\u0f00\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e-\u0f47\u0f49-\u0f6c\u0f71-\u0f84\u0f86-\u0f97\u0f99-\u0fbc\u0fc6\u1000-\u1049\u1050-\u109d\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u135d-\u135f\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176c\u176e-\u1770\u1772\u1773\u1780-\u17d3\u17d7\u17dc\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u1820-\u1877\u1880-\u18aa\u18b0-\u18f5\u1900-\u191c\u1920-\u192b\u1930-\u193b\u1946-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u19d0-\u19d9\u1a00-\u1a1b\u1a20-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1aa7\u1b00-\u1b4b\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1bf3\u1c00-\u1c37\u1c40-\u1c49\u1c4d-\u1c7d\u1cd0-\u1cd2\u1cd4-\u1cf6\u1d00-\u1de6\u1dfc-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u200c\u200d\u203f\u2040\u2054\u2071\u207f\u2090-\u209c\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d7f-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2de0-\u2dff\u2e2f\u3005-\u3007\u3021-\u302f\u3031-\u3035\u3038-\u303c\u3041-\u3096\u3099\u309a\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua62b\ua640-\ua66f\ua674-\ua67d\ua67f-\ua697\ua69f-\ua6f1\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua827\ua840-\ua873\ua880-\ua8c4\ua8d0-\ua8d9\ua8e0-\ua8f7\ua8fb\ua900-\ua92d\ua930-\ua953\ua960-\ua97c\ua980-\ua9c0\ua9cf-\ua9d9\uaa00-\uaa36\uaa40-\uaa4d\uaa50-\uaa59\uaa60-\uaa76\uaa7a\uaa7b\uaa80-\uaac2\uaadb-\uaadd\uaae0-\uaaef\uaaf2-\uaaf6\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabea\uabec\uabed\uabf0-\uabf9\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe00-\ufe0f\ufe20-\ufe26\ufe33\ufe34\ufe4d-\ufe4f\ufe70-\ufe74\ufe76-\ufefc\uff10-\uff19\uff21-\uff3a\uff3f\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc]'), LeadingZeros: new RegExp('^0+(?!$)') }; // Ensure the condition is true, otherwise throw an error. // This is only to have a better contract semantic, i.e. another safety net // to catch a logic error. The condition shall be fulfilled in normal case. // Do NOT use this to enforce a certain condition on any user input. function assert(condition, message) { /* istanbul ignore if */ if (!condition) { throw new Error('ASSERT: ' + message); } } function StringMap() { this.$data = {}; } StringMap.prototype.get = function (key) { key = '$' + key; return this.$data[key]; }; StringMap.prototype.set = function (key, value) { key = '$' + key; this.$data[key] = value; return this; }; StringMap.prototype.has = function (key) { key = '$' + key; return Object.prototype.hasOwnProperty.call(this.$data, key); }; StringMap.prototype["delete"] = function (key) { key = '$' + key; return delete this.$data[key]; }; function isDecimalDigit(ch) { return (ch >= 48 && ch <= 57); // 0..9 } function isHexDigit(ch) { return '0123456789abcdefABCDEF'.indexOf(ch) >= 0; } function isOctalDigit(ch) { return '01234567'.indexOf(ch) >= 0; } // 7.2 White Space function isWhiteSpace(ch) { return (ch === 32) || // space (ch === 9) || // tab (ch === 0xB) || (ch === 0xC) || (ch === 0xA0) || (ch >= 0x1680 && '\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\uFEFF'.indexOf(String.fromCharCode(ch)) > 0); } // 7.3 Line Terminators function isLineTerminator(ch) { return (ch === 10) || (ch === 13) || (ch === 0x2028) || (ch === 0x2029); } // 7.6 Identifier Names and Identifiers function isIdentifierStart(ch) { return (ch === 36) || (ch === 95) || // $ (dollar) and _ (underscore) (ch >= 65 && ch <= 90) || // A..Z (ch >= 97 && ch <= 122) || // a..z (ch === 92) || // \ (backslash) ((ch >= 0x80) && Regex.NonAsciiIdentifierStart.test(String.fromCharCode(ch))); } function isIdentifierPart(ch) { return (ch === 36) || (ch === 95) || // $ (dollar) and _ (underscore) (ch >= 65 && ch <= 90) || // A..Z (ch >= 97 && ch <= 122) || // a..z (ch >= 48 && ch <= 57) || // 0..9 (ch === 92) || // \ (backslash) ((ch >= 0x80) && Regex.NonAsciiIdentifierPart.test(String.fromCharCode(ch))); } // 7.6.1.2 Future Reserved Words function isFutureReservedWord(id) { switch (id) { case 'class': case 'enum': case 'export': case 'extends': case 'import': case 'super': return true; default: return false; } } function isStrictModeReservedWord(id) { switch (id) { case 'implements': case 'interface': case 'package': case 'private': case 'protected': case 'public': case 'static': case 'yield': case 'let': return true; default: return false; } } function isRestrictedWord(id) { return id === 'eval' || id === 'arguments'; } // 7.6.1.1 Keywords function isKeyword(id) { if (strict && isStrictModeReservedWord(id)) { return true; } // 'const' is specialized as Keyword in V8. // 'yield' is only treated as a keyword in strict mode. // 'let' is for compatiblity with SpiderMonkey and ES.next. // Some others are from future reserved words. switch (id.length) { case 2: return (id === 'if') || (id === 'in') || (id === 'do'); case 3: return (id === 'var') || (id === 'for') || (id === 'new') || (id === 'try') || (id === 'let'); case 4: return (id === 'this') || (id === 'else') || (id === 'case') || (id === 'void') || (id === 'with') || (id === 'enum'); case 5: return (id === 'while') || (id === 'break') || (id === 'catch') || (id === 'throw') || (id === 'const') || (id === 'class') || (id === 'super'); case 6: return (id === 'return') || (id === 'typeof') || (id === 'delete') || (id === 'switch') || (id === 'export') || (id === 'import'); case 7: return (id === 'default') || (id === 'finally') || (id === 'extends'); case 8: return (id === 'function') || (id === 'continue') || (id === 'debugger'); case 10: return (id === 'instanceof'); default: return false; } } // 7.4 Comments function addComment(type, value, start, end, loc) { var comment; assert(typeof start === 'number', 'Comment must have valid position'); // Because the way the actual token is scanned, often the comments // (if any) are skipped twice during the lexical analysis. // Thus, we need to skip adding a comment if the comment array already // handled it. if (state.lastCommentStart >= start) { return; } state.lastCommentStart = start; comment = { type: type, value: value }; if (extra.range) { comment.range = [start, end]; } if (extra.loc) { comment.loc = loc; } extra.comments.push(comment); if (extra.attachComment) { extra.leadingComments.push(comment); extra.trailingComments.push(comment); } } function skipSingleLineComment() { var start, loc, ch, comment; start = index - 2; loc = { start: { line: lineNumber, column: index - lineStart - 2 } }; while (index < length) { ch = source.charCodeAt(index); ++index; if (isLineTerminator(ch)) { if (extra.comments) { comment = source.slice(start + 2, index - 1); loc.end = { line: lineNumber, column: index - lineStart - 1 }; addComment('Line', comment, start, index - 1, loc); } if (ch === 13 && source.charCodeAt(index) === 10) { ++index; } ++lineNumber; lineStart = index; return; } } if (extra.comments) { comment = source.slice(start + 2, index); loc.end = { line: lineNumber, column: index - lineStart }; addComment('Line', comment, start, index, loc); } } function skipMultiLineComment() { var start, loc, ch, comment; if (extra.comments) { start = index - 2; loc = { start: { line: lineNumber, column: index - lineStart - 2 } }; } while (index < length) { ch = source.charCodeAt(index); if (isLineTerminator(ch)) { if (ch === 13 && source.charCodeAt(index + 1) === 10) { ++index; } ++lineNumber; ++index; lineStart = index; if (index >= length) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } } else if (ch === 42) { // Block comment ends with '*/' (char #42, char #47). if (source.charCodeAt(index + 1) === 47) { ++index; ++index; if (extra.comments) { comment = source.slice(start + 2, index - 2); loc.end = { line: lineNumber, column: index - lineStart }; addComment('Block', comment, start, index, loc); } return; } ++index; } else { ++index; } } throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } function skipComment() { var ch; while (index < length) { ch = source.charCodeAt(index); if (isWhiteSpace(ch)) { ++index; } else if (isLineTerminator(ch)) { ++index; if (ch === 13 && source.charCodeAt(index) === 10) { ++index; } ++lineNumber; lineStart = index; } else if (ch === 47) { // 47 is '/' ch = source.charCodeAt(index + 1); if (ch === 47) { ++index; ++index; skipSingleLineComment(); } else if (ch === 42) { // 42 is '*' ++index; ++index; skipMultiLineComment(); } else { break; } } else { break; } } } function scanHexEscape(prefix) { var i, len, ch, code = 0; len = (prefix === 'u') ? 4 : 2; for (i = 0; i < len; ++i) { if (index < length && isHexDigit(source[index])) { ch = source[index++]; code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase()); } else { return ''; } } return String.fromCharCode(code); } function scanUnicodeCodePointEscape() { var ch, code, cu1, cu2; ch = source[index]; code = 0; // At least, one hex digit is required. if (ch === '}') { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } while (index < length) { ch = source[index++]; if (!isHexDigit(ch)) { break; } code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase()); } if (code > 0x10FFFF || ch !== '}') { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } // UTF-16 Encoding if (code <= 0xFFFF) { return String.fromCharCode(code); } cu1 = ((code - 0x10000) >> 10) + 0xD800; cu2 = ((code - 0x10000) & 1023) + 0xDC00; return String.fromCharCode(cu1, cu2); } function getEscapedIdentifier() { var ch, id; ch = source.charCodeAt(index++); id = String.fromCharCode(ch); // '\u' (char #92, char #117) denotes an escaped character. if (ch === 92) { if (source.charCodeAt(index) !== 117) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } ++index; ch = scanHexEscape('u'); if (!ch || ch === '\\' || !isIdentifierStart(ch.charCodeAt(0))) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } id = ch; } while (index < length) { ch = source.charCodeAt(index); if (!isIdentifierPart(ch)) { break; } ++index; id += String.fromCharCode(ch); // '\u' (char #92, char #117) denotes an escaped character. if (ch === 92) { id = id.substr(0, id.length - 1); if (source.charCodeAt(index) !== 117) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } ++index; ch = scanHexEscape('u'); if (!ch || ch === '\\' || !isIdentifierPart(ch.charCodeAt(0))) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } id += ch; } } return id; } function getIdentifier() { var start, ch; start = index++; while (index < length) { ch = source.charCodeAt(index); if (ch === 92) { // Blackslash (char #92) marks Unicode escape sequence. index = start; return getEscapedIdentifier(); } if (isIdentifierPart(ch)) { ++index; } else { break; } } return source.slice(start, index); } function scanIdentifier() { var start, id, type; start = index; // Backslash (char #92) starts an escaped character. id = (source.charCodeAt(index) === 92) ? getEscapedIdentifier() : getIdentifier(); // There is no keyword or literal with only one character. // Thus, it must be an identifier. if (id.length === 1) { type = Token.Identifier; } else if (isKeyword(id)) { type = Token.Keyword; } else if (id === 'null') { type = Token.NullLiteral; } else if (id === 'true' || id === 'false') { type = Token.BooleanLiteral; } else { type = Token.Identifier; } return { type: type, value: id, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } // 7.7 Punctuators function scanPunctuator() { var start = index, code = source.charCodeAt(index), code2, ch1 = source[index], ch2, ch3, ch4; if (state.inJSXTag || state.inJSXChild) { // Don't need to check for '{' and '}' as it's already handled // correctly by default. switch (code) { case 60: // < case 62: // > ++index; return { type: Token.Punctuator, value: String.fromCharCode(code), lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } } switch (code) { // Check for most common single-character punctuators. case 40: // ( open bracket case 41: // ) close bracket case 59: // ; semicolon case 44: // , comma case 123: // { open curly brace case 125: // } close curly brace case 91: // [ case 93: // ] case 58: // : case 63: // ? case 126: // ~ ++index; if (extra.tokenize) { if (code === 40) { extra.openParenToken = extra.tokens.length; } else if (code === 123) { extra.openCurlyToken = extra.tokens.length; } } return { type: Token.Punctuator, value: String.fromCharCode(code), lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; default: code2 = source.charCodeAt(index + 1); // '=' (char #61) marks an assignment or comparison operator. if (code2 === 61) { switch (code) { case 37: // % case 38: // & case 42: // *: case 43: // + case 45: // - case 47: // / case 60: // < case 62: // > case 94: // ^ case 124: // | index += 2; return { type: Token.Punctuator, value: String.fromCharCode(code) + String.fromCharCode(code2), lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; case 33: // ! case 61: // = index += 2; // !== and === if (source.charCodeAt(index) === 61) { ++index; } return { type: Token.Punctuator, value: source.slice(start, index), lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; default: break; } } break; } // Peek more characters. ch2 = source[index + 1]; ch3 = source[index + 2]; ch4 = source[index + 3]; // 4-character punctuator: >>>= if (ch1 === '>' && ch2 === '>' && ch3 === '>') { if (ch4 === '=') { index += 4; return { type: Token.Punctuator, value: '>>>=', lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } } // 3-character punctuators: === !== >>> <<= >>= if (ch1 === '>' && ch2 === '>' && ch3 === '>') { index += 3; return { type: Token.Punctuator, value: '>>>', lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } if (ch1 === '<' && ch2 === '<' && ch3 === '=') { index += 3; return { type: Token.Punctuator, value: '<<=', lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } if (ch1 === '>' && ch2 === '>' && ch3 === '=') { index += 3; return { type: Token.Punctuator, value: '>>=', lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } if (ch1 === '.' && ch2 === '.' && ch3 === '.') { index += 3; return { type: Token.Punctuator, value: '...', lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } // Other 2-character punctuators: ++ -- << >> && || // Don't match these tokens if we're in a type, since they never can // occur and can mess up types like Map<string, Array<string>> if (ch1 === ch2 && ('+-<>&|'.indexOf(ch1) >= 0) && !state.inType) { index += 2; return { type: Token.Punctuator, value: ch1 + ch2, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } if (ch1 === '=' && ch2 === '>') { index += 2; return { type: Token.Punctuator, value: '=>', lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } if ('<>=!+-*%&|^/'.indexOf(ch1) >= 0) { ++index; return { type: Token.Punctuator, value: ch1, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } if (ch1 === '.') { ++index; return { type: Token.Punctuator, value: ch1, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } // 7.8.3 Numeric Literals function scanHexLiteral(start) { var number = ''; while (index < length) { if (!isHexDigit(source[index])) { break; } number += source[index++]; } if (number.length === 0) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } if (isIdentifierStart(source.charCodeAt(index))) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } return { type: Token.NumericLiteral, value: parseInt('0x' + number, 16), lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } function scanBinaryLiteral(start) { var ch, number; number = ''; while (index < length) { ch = source[index]; if (ch !== '0' && ch !== '1') { break; } number += source[index++]; } if (number.length === 0) { // only 0b or 0B throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } if (index < length) { ch = source.charCodeAt(index); /* istanbul ignore else */ if (isIdentifierStart(ch) || isDecimalDigit(ch)) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } } return { type: Token.NumericLiteral, value: parseInt(number, 2), lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } function scanOctalLiteral(prefix, start) { var number, octal; if (isOctalDigit(prefix)) { octal = true; number = '0' + source[index++]; } else { octal = false; ++index; number = ''; } while (index < length) { if (!isOctalDigit(source[index])) { break; } number += source[index++]; } if (!octal && number.length === 0) { // only 0o or 0O throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } if (isIdentifierStart(source.charCodeAt(index)) || isDecimalDigit(source.charCodeAt(index))) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } return { type: Token.NumericLiteral, value: parseInt(number, 8), octal: octal, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } function scanNumericLiteral() { var number, start, ch; ch = source[index]; assert(isDecimalDigit(ch.charCodeAt(0)) || (ch === '.'), 'Numeric literal must start with a decimal digit or a decimal point'); start = index; number = ''; if (ch !== '.') { number = source[index++]; ch = source[index]; // Hex number starts with '0x'. // Octal number starts with '0'. // Octal number in ES6 starts with '0o'. // Binary number in ES6 starts with '0b'. if (number === '0') { if (ch === 'x' || ch === 'X') { ++index; return scanHexLiteral(start); } if (ch === 'b' || ch === 'B') { ++index; return scanBinaryLiteral(start); } if (ch === 'o' || ch === 'O' || isOctalDigit(ch)) { return scanOctalLiteral(ch, start); } // decimal number starts with '0' such as '09' is illegal. if (ch && isDecimalDigit(ch.charCodeAt(0))) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } } while (isDecimalDigit(source.charCodeAt(index))) { number += source[index++]; } ch = source[index]; } if (ch === '.') { number += source[index++]; while (isDecimalDigit(source.charCodeAt(index))) { number += source[index++]; } ch = source[index]; } if (ch === 'e' || ch === 'E') { number += source[index++]; ch = source[index]; if (ch === '+' || ch === '-') { number += source[index++]; } if (isDecimalDigit(source.charCodeAt(index))) { while (isDecimalDigit(source.charCodeAt(index))) { number += source[index++]; } } else { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } } if (isIdentifierStart(source.charCodeAt(index))) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } return { type: Token.NumericLiteral, value: parseFloat(number), lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } // 7.8.4 String Literals function scanStringLiteral() { var str = '', quote, start, ch, code, unescaped, restore, octal = false; quote = source[index]; assert((quote === '\'' || quote === '"'), 'String literal must starts with a quote'); start = index; ++index; while (index < length) { ch = source[index++]; if (ch === quote) { quote = ''; break; } else if (ch === '\\') { ch = source[index++]; if (!ch || !isLineTerminator(ch.charCodeAt(0))) { switch (ch) { case 'n': str += '\n'; break; case 'r': str += '\r'; break; case 't': str += '\t'; break; case 'u': case 'x': if (source[index] === '{') { ++index; str += scanUnicodeCodePointEscape(); } else { restore = index; unescaped = scanHexEscape(ch); if (unescaped) { str += unescaped; } else { index = restore; str += ch; } } break; case 'b': str += '\b'; break; case 'f': str += '\f'; break; case 'v': str += '\x0B'; break; default: if (isOctalDigit(ch)) { code = '01234567'.indexOf(ch); // \0 is not octal escape sequence if (code !== 0) { octal = true; } /* istanbul ignore else */ if (index < length && isOctalDigit(source[index])) { octal = true; code = code * 8 + '01234567'.indexOf(source[index++]); // 3 digits are only allowed when string starts // with 0, 1, 2, 3 if ('0123'.indexOf(ch) >= 0 && index < length && isOctalDigit(source[index])) { code = code * 8 + '01234567'.indexOf(source[index++]); } } str += String.fromCharCode(code); } else { str += ch; } break; } } else { ++lineNumber; if (ch === '\r' && source[index] === '\n') { ++index; } lineStart = index; } } else if (isLineTerminator(ch.charCodeAt(0))) { break; } else { str += ch; } } if (quote !== '') { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } return { type: Token.StringLiteral, value: str, octal: octal, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } function scanTemplate() { var cooked = '', ch, start, terminated, tail, restore, unescaped, code, octal; terminated = false; tail = false; start = index; ++index; while (index < length) { ch = source[index++]; if (ch === '`') { tail = true; terminated = true; break; } else if (ch === '$') { if (source[index] === '{') { ++index; terminated = true; break; } cooked += ch; } else if (ch === '\\') { ch = source[index++]; if (!isLineTerminator(ch.charCodeAt(0))) { switch (ch) { case 'n': cooked += '\n'; break; case 'r': cooked += '\r'; break; case 't': cooked += '\t'; break; case 'u': case 'x': if (source[index] === '{') { ++index; cooked += scanUnicodeCodePointEscape(); } else { restore = index; unescaped = scanHexEscape(ch); if (unescaped) { cooked += unescaped; } else { index = restore; cooked += ch; } } break; case 'b': cooked += '\b'; break; case 'f': cooked += '\f'; break; case 'v': cooked += '\v'; break; default: if (isOctalDigit(ch)) { code = '01234567'.indexOf(ch); // \0 is not octal escape sequence if (code !== 0) { octal = true; } /* istanbul ignore else */ if (index < length && isOctalDigit(source[index])) { octal = true; code = code * 8 + '01234567'.indexOf(source[index++]); // 3 digits are only allowed when string starts // with 0, 1, 2, 3 if ('0123'.indexOf(ch) >= 0 && index < length && isOctalDigit(source[index])) { code = code * 8 + '01234567'.indexOf(source[index++]); } } cooked += String.fromCharCode(code); } else { cooked += ch; } break; } } else { ++lineNumber; if (ch === '\r' && source[index] === '\n') { ++index; } lineStart = index; } } else if (isLineTerminator(ch.charCodeAt(0))) { ++lineNumber; if (ch === '\r' && source[index] === '\n') { ++index; } lineStart = index; cooked += '\n'; } else { cooked += ch; } } if (!terminated) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } return { type: Token.Template, value: { cooked: cooked, raw: source.slice(start + 1, index - ((tail) ? 1 : 2)) }, tail: tail, octal: octal, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } function scanTemplateElement(option) { var startsWith, template; lookahead = null; skipComment(); startsWith = (option.head) ? '`' : '}'; if (source[index] !== startsWith) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } template = scanTemplate(); peek(); return template; } function testRegExp(pattern, flags) { var tmp = pattern, value; if (flags.indexOf('u') >= 0) { // Replace each astral symbol and every Unicode code point // escape sequence with a single ASCII symbol to avoid throwing on // regular expressions that are only valid in combination with the // `/u` flag. // Note: replacing with the ASCII symbol `x` might cause false // negatives in unlikely scenarios. For example, `[\u{61}-b]` is a // perfectly valid pattern that is equivalent to `[a-b]`, but it // would be replaced by `[x-b]` which throws an error. tmp = tmp .replace(/\\u\{([0-9a-fA-F]+)\}/g, function ($0, $1) { if (parseInt($1, 16) <= 0x10FFFF) { return 'x'; } throwError({}, Messages.InvalidRegExp); }) .replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g, 'x'); } // First, detect invalid regular expressions. try { value = new RegExp(tmp); } catch (e) { throwError({}, Messages.InvalidRegExp); } // Return a regular expression object for this pattern-flag pair, or // `null` in case the current environment doesn't support the flags it // uses. try { return new RegExp(pattern, flags); } catch (exception) { return null; } } function scanRegExpBody() { var ch, str, classMarker, terminated, body; ch = source[index]; assert(ch === '/', 'Regular expression literal must start with a slash'); str = source[index++]; classMarker = false; terminated = false; while (index < length) { ch = source[index++]; str += ch; if (ch === '\\') { ch = source[index++]; // ECMA-262 7.8.5 if (isLineTerminator(ch.charCodeAt(0))) { throwError({}, Messages.UnterminatedRegExp); } str += ch; } else if (isLineTerminator(ch.charCodeAt(0))) { throwError({}, Messages.UnterminatedRegExp); } else if (classMarker) { if (ch === ']') { classMarker = false; } } else { if (ch === '/') { terminated = true; break; } else if (ch === '[') { classMarker = true; } } } if (!terminated) { throwError({}, Messages.UnterminatedRegExp); } // Exclude leading and trailing slash. body = str.substr(1, str.length - 2); return { value: body, literal: str }; } function scanRegExpFlags() { var ch, str, flags, restore; str = ''; flags = ''; while (index < length) { ch = source[index]; if (!isIdentifierPart(ch.charCodeAt(0))) { break; } ++index; if (ch === '\\' && index < length) { ch = source[index]; if (ch === 'u') { ++index; restore = index; ch = scanHexEscape('u'); if (ch) { flags += ch; for (str += '\\u'; restore < index; ++restore) { str += source[restore]; } } else { index = restore; flags += 'u'; str += '\\u'; } throwErrorTolerant({}, Messages.UnexpectedToken, 'ILLEGAL'); } else { str += '\\'; throwErrorTolerant({}, Messages.UnexpectedToken, 'ILLEGAL'); } } else { flags += ch; str += ch; } } return { value: flags, literal: str }; } function scanRegExp() { var start, body, flags, value; lookahead = null; skipComment(); start = index; body = scanRegExpBody(); flags = scanRegExpFlags(); value = testRegExp(body.value, flags.value); if (extra.tokenize) { return { type: Token.RegularExpression, value: value, regex: { pattern: body.value, flags: flags.value }, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } return { literal: body.literal + flags.literal, value: value, regex: { pattern: body.value, flags: flags.value }, range: [start, index] }; } function isIdentifierName(token) { return token.type === Token.Identifier || token.type === Token.Keyword || token.type === Token.BooleanLiteral || token.type === Token.NullLiteral; } function advanceSlash() { var prevToken, checkToken; // Using the following algorithm: // https://github.com/mozilla/sweet.js/wiki/design prevToken = extra.tokens[extra.tokens.length - 1]; if (!prevToken) { // Nothing before that: it cannot be a division. return scanRegExp(); } if (prevToken.type === 'Punctuator') { if (prevToken.value === ')') { checkToken = extra.tokens[extra.openParenToken - 1]; if (checkToken && checkToken.type === 'Keyword' && (checkToken.value === 'if' || checkToken.value === 'while' || checkToken.value === 'for' || checkToken.value === 'with')) { return scanRegExp(); } return scanPunctuator(); } if (prevToken.value === '}') { // Dividing a function by anything makes little sense, // but we have to check for that. if (extra.tokens[extra.openCurlyToken - 3] && extra.tokens[extra.openCurlyToken - 3].type === 'Keyword') { // Anonymous function. checkToken = extra.tokens[extra.openCurlyToken - 4]; if (!checkToken) { return scanPunctuator(); } } else if (extra.tokens[extra.openCurlyToken - 4] && extra.tokens[extra.openCurlyToken - 4].type === 'Keyword') { // Named function. checkToken = extra.tokens[extra.openCurlyToken - 5]; if (!checkToken) { return scanRegExp(); } } else { return scanPunctuator(); } // checkToken determines whether the function is // a declaration or an expression. if (FnExprTokens.indexOf(checkToken.value) >= 0) { // It is an expression. return scanPunctuator(); } // It is a declaration. return scanRegExp(); } return scanRegExp(); } if (prevToken.type === 'Keyword' && prevToken.value !== 'this') { return scanRegExp(); } return scanPunctuator(); } function advance() { var ch; if (!state.inJSXChild) { skipComment(); } if (index >= length) { return { type: Token.EOF, lineNumber: lineNumber, lineStart: lineStart, range: [index, index] }; } if (state.inJSXChild) { return advanceJSXChild(); } ch = source.charCodeAt(index); // Very common: ( and ) and ; if (ch === 40 || ch === 41 || ch === 58) { return scanPunctuator(); } // String literal starts with single quote (#39) or double quote (#34). if (ch === 39 || ch === 34) { if (state.inJSXTag) { return scanJSXStringLiteral(); } return scanStringLiteral(); } if (state.inJSXTag && isJSXIdentifierStart(ch)) { return scanJSXIdentifier(); } if (ch === 96) { return scanTemplate(); } if (isIdentifierStart(ch)) { return scanIdentifier(); } // Dot (.) char #46 can also start a floating-point number, hence the need // to check the next character. if (ch === 46) { if (isDecimalDigit(source.charCodeAt(index + 1))) { return scanNumericLiteral(); } return scanPunctuator(); } if (isDecimalDigit(ch)) { return scanNumericLiteral(); } // Slash (/) char #47 can also start a regex. if (extra.tokenize && ch === 47) { return advanceSlash(); } return scanPunctuator(); } function lex() { var token; token = lookahead; index = token.range[1]; lineNumber = token.lineNumber; lineStart = token.lineStart; lookahead = advance(); index = token.range[1]; lineNumber = token.lineNumber; lineStart = token.lineStart; return token; } function peek() { var pos, line, start; pos = index; line = lineNumber; start = lineStart; lookahead = advance(); index = pos; lineNumber = line; lineStart = start; } function lookahead2() { var adv, pos, line, start, result; // If we are collecting the tokens, don't grab the next one yet. /* istanbul ignore next */ adv = (typeof extra.advance === 'function') ? extra.advance : advance; pos = index; line = lineNumber; start = lineStart; // Scan for the next immediate token. /* istanbul ignore if */ if (lookahead === null) { lookahead = adv(); } index = lookahead.range[1]; lineNumber = lookahead.lineNumber; lineStart = lookahead.lineStart; // Grab the token right after. result = adv(); index = pos; lineNumber = line; lineStart = start; return result; } function rewind(token) { index = token.range[0]; lineNumber = token.lineNumber; lineStart = token.lineStart; lookahead = token; } function markerCreate() { if (!extra.loc && !extra.range) { return undefined; } skipComment(); return {offset: index, line: lineNumber, col: index - lineStart}; } function markerCreatePreserveWhitespace() { if (!extra.loc && !extra.range) { return undefined; } return {offset: index, line: lineNumber, col: index - lineStart}; } function processComment(node) { var lastChild, trailingComments, bottomRight = extra.bottomRightStack, last = bottomRight[bottomRight.length - 1]; if (node.type === Syntax.Program) { /* istanbul ignore else */ if (node.body.length > 0) { return; } } if (extra.trailingComments.length > 0) { if (extra.trailingComments[0].range[0] >= node.range[1]) { trailingComments = extra.trailingComments; extra.trailingComments = []; } else { extra.trailingComments.length = 0; } } else { if (last && last.trailingComments && last.trailingComments[0].range[0] >= node.range[1]) { trailingComments = last.trailingComments; delete last.trailingComments; } } // Eating the stack. if (last) { while (last && last.range[0] >= node.range[0]) { lastChild = last; last = bottomRight.pop(); } } if (lastChild) { if (lastChild.leadingComments && lastChild.leadingComments[lastChild.leadingComments.length - 1].range[1] <= node.range[0]) { node.leadingComments = lastChild.leadingComments; delete lastChild.leadingComments; } } else if (extra.leadingComments.length > 0 && extra.leadingComments[extra.leadingComments.length - 1].range[1] <= node.range[0]) { node.leadingComments = extra.leadingComments; extra.leadingComments = []; } if (trailingComments) { node.trailingComments = trailingComments; } bottomRight.push(node); } function markerApply(marker, node) { if (extra.range) { node.range = [marker.offset, index]; } if (extra.loc) { node.loc = { start: { line: marker.line, column: marker.col }, end: { line: lineNumber, column: index - lineStart } }; node = delegate.postProcess(node); } if (extra.attachComment) { processComment(node); } return node; } SyntaxTreeDelegate = { name: 'SyntaxTree', postProcess: function (node) { return node; }, createArrayExpression: function (elements) { return { type: Syntax.ArrayExpression, elements: elements }; }, createAssignmentExpression: function (operator, left, right) { return { type: Syntax.AssignmentExpression, operator: operator, left: left, right: right }; }, createBinaryExpression: function (operator, left, right) { var type = (operator === '||' || operator === '&&') ? Syntax.LogicalExpression : Syntax.BinaryExpression; return { type: type, operator: operator, left: left, right: right }; }, createBlockStatement: function (body) { return { type: Syntax.BlockStatement, body: body }; }, createBreakStatement: function (label) { return { type: Syntax.BreakStatement, label: label }; }, createCallExpression: function (callee, args) { return { type: Syntax.CallExpression, callee: callee, 'arguments': args }; }, createCatchClause: function (param, body) { return { type: Syntax.CatchClause, param: param, body: body }; }, createConditionalExpression: function (test, consequent, alternate) { return { type: Syntax.ConditionalExpression, test: test, consequent: consequent, alternate: alternate }; }, createContinueStatement: function (label) { return { type: Syntax.ContinueStatement, label: label }; }, createDebuggerStatement: function () { return { type: Syntax.DebuggerStatement }; }, createDoWhileStatement: function (body, test) { return { type: Syntax.DoWhileStatement, body: body, test: test }; }, createEmptyStatement: function () { return { type: Syntax.EmptyStatement }; }, createExpressionStatement: function (expression) { return { type: Syntax.ExpressionStatement, expression: expression }; }, createForStatement: function (init, test, update, body) { return { type: Syntax.ForStatement, init: init, test: test, update: update, body: body }; }, createForInStatement: function (left, right, body) { return { type: Syntax.ForInStatement, left: left, right: right, body: body, each: false }; }, createForOfStatement: function (left, right, body) { return { type: Syntax.ForOfStatement, left: left, right: right, body: body }; }, createFunctionDeclaration: function (id, params, defaults, body, rest, generator, expression, isAsync, returnType, typeParameters) { var funDecl = { type: Syntax.FunctionDeclaration, id: id, params: params, defaults: defaults, body: body, rest: rest, generator: generator, expression: expression, returnType: returnType, typeParameters: typeParameters }; if (isAsync) { funDecl.async = true; } return funDecl; }, createFunctionExpression: function (id, params, defaults, body, rest, generator, expression, isAsync, returnType, typeParameters) { var funExpr = { type: Syntax.FunctionExpression, id: id, params: params, defaults: defaults, body: body, rest: rest, generator: generator, expression: expression, returnType: returnType, typeParameters: typeParameters }; if (isAsync) { funExpr.async = true; } return funExpr; }, createIdentifier: function (name) { return { type: Syntax.Identifier, name: name, // Only here to initialize the shape of the object to ensure // that the 'typeAnnotation' key is ordered before others that // are added later (like 'loc' and 'range'). This just helps // keep the shape of Identifier nodes consistent with everything // else. typeAnnotation: undefined, optional: undefined }; }, createTypeAnnotation: function (typeAnnotation) { return { type: Syntax.TypeAnnotation, typeAnnotation: typeAnnotation }; }, createTypeCast: function (expression, typeAnnotation) { return { type: Syntax.TypeCastExpression, expression: expression, typeAnnotation: typeAnnotation }; }, createFunctionTypeAnnotation: function (params, returnType, rest, typeParameters) { return { type: Syntax.FunctionTypeAnnotation, params: params, returnType: returnType, rest: rest, typeParameters: typeParameters }; }, createFunctionTypeParam: function (name, typeAnnotation, optional) { return { type: Syntax.FunctionTypeParam, name: name, typeAnnotation: typeAnnotation, optional: optional }; }, createNullableTypeAnnotation: function (typeAnnotation) { return { type: Syntax.NullableTypeAnnotation, typeAnnotation: typeAnnotation }; }, createArrayTypeAnnotation: function (elementType) { return { type: Syntax.ArrayTypeAnnotation, elementType: elementType }; }, createGenericTypeAnnotation: function (id, typeParameters) { return { type: Syntax.GenericTypeAnnotation, id: id, typeParameters: typeParameters }; }, createQualifiedTypeIdentifier: function (qualification, id) { return { type: Syntax.QualifiedTypeIdentifier, qualification: qualification, id: id }; }, createTypeParameterDeclaration: function (params) { return { type: Syntax.TypeParameterDeclaration, params: params }; }, createTypeParameterInstantiation: function (params) { return { type: Syntax.TypeParameterInstantiation, params: params }; }, createAnyTypeAnnotation: function () { return { type: Syntax.AnyTypeAnnotation }; }, createBooleanTypeAnnotation: function () { return { type: Syntax.BooleanTypeAnnotation }; }, createNumberTypeAnnotation: function () { return { type: Syntax.NumberTypeAnnotation }; }, createStringTypeAnnotation: function () { return { type: Syntax.StringTypeAnnotation }; }, createStringLiteralTypeAnnotation: function (token) { return { type: Syntax.StringLiteralTypeAnnotation, value: token.value, raw: source.slice(token.range[0], token.range[1]) }; }, createVoidTypeAnnotation: function () { return { type: Syntax.VoidTypeAnnotation }; }, createTypeofTypeAnnotation: function (argument) { return { type: Syntax.TypeofTypeAnnotation, argument: argument }; }, createTupleTypeAnnotation: function (types) { return { type: Syntax.TupleTypeAnnotation, types: types }; }, createObjectTypeAnnotation: function (properties, indexers, callProperties) { return { type: Syntax.ObjectTypeAnnotation, properties: properties, indexers: indexers, callProperties: callProperties }; }, createObjectTypeIndexer: function (id, key, value, isStatic) { return { type: Syntax.ObjectTypeIndexer, id: id, key: key, value: value, "static": isStatic }; }, createObjectTypeCallProperty: function (value, isStatic) { return { type: Syntax.ObjectTypeCallProperty, value: value, "static": isStatic }; }, createObjectTypeProperty: function (key, value, optional, isStatic) { return { type: Syntax.ObjectTypeProperty, key: key, value: value, optional: optional, "static": isStatic }; }, createUnionTypeAnnotation: function (types) { return { type: Syntax.UnionTypeAnnotation, types: types }; }, createIntersectionTypeAnnotation: function (types) { return { type: Syntax.IntersectionTypeAnnotation, types: types }; }, createTypeAlias: function (id, typeParameters, right) { return { type: Syntax.TypeAlias, id: id, typeParameters: typeParameters, right: right }; }, createInterface: function (id, typeParameters, body, extended) { return { type: Syntax.InterfaceDeclaration, id: id, typeParameters: typeParameters, body: body, "extends": extended }; }, createInterfaceExtends: function (id, typeParameters) { return { type: Syntax.InterfaceExtends, id: id, typeParameters: typeParameters }; }, createDeclareFunction: function (id) { return { type: Syntax.DeclareFunction, id: id }; }, createDeclareVariable: function (id) { return { type: Syntax.DeclareVariable, id: id }; }, createDeclareModule: function (id, body) { return { type: Syntax.DeclareModule, id: id, body: body }; }, createJSXAttribute: function (name, value) { return { type: Syntax.JSXAttribute, name: name, value: value || null }; }, createJSXSpreadAttribute: function (argument) { return { type: Syntax.JSXSpreadAttribute, argument: argument }; }, createJSXIdentifier: function (name) { return { type: Syntax.JSXIdentifier, name: name }; }, createJSXNamespacedName: function (namespace, name) { return { type: Syntax.JSXNamespacedName, namespace: namespace, name: name }; }, createJSXMemberExpression: function (object, property) { return { type: Syntax.JSXMemberExpression, object: object, property: property }; }, createJSXElement: function (openingElement, closingElement, children) { return { type: Syntax.JSXElement, openingElement: openingElement, closingElement: closingElement, children: children }; }, createJSXEmptyExpression: function () { return { type: Syntax.JSXEmptyExpression }; }, createJSXExpressionContainer: function (expression) { return { type: Syntax.JSXExpressionContainer, expression: expression }; }, createJSXOpeningElement: function (name, attributes, selfClosing) { return { type: Syntax.JSXOpeningElement, name: name, selfClosing: selfClosing, attributes: attributes }; }, createJSXClosingElement: function (name) { return { type: Syntax.JSXClosingElement, name: name }; }, createIfStatement: function (test, consequent, alternate) { return { type: Syntax.IfStatement, test: test, consequent: consequent, alternate: alternate }; }, createLabeledStatement: function (label, body) { return { type: Syntax.LabeledStatement, label: label, body: body }; }, createLiteral: function (token) { var object = { type: Syntax.Literal, value: token.value, raw: source.slice(token.range[0], token.range[1]) }; if (token.regex) { object.regex = token.regex; } return object; }, createMemberExpression: function (accessor, object, property) { return { type: Syntax.MemberExpression, computed: accessor === '[', object: object, property: property }; }, createNewExpression: function (callee, args) { return { type: Syntax.NewExpression, callee: callee, 'arguments': args }; }, createObjectExpression: function (properties) { return { type: Syntax.ObjectExpression, properties: properties }; }, createPostfixExpression: function (operator, argument) { return { type: Syntax.UpdateExpression, operator: operator, argument: argument, prefix: false }; }, createProgram: function (body) { return { type: Syntax.Program, body: body }; }, createProperty: function (kind, key, value, method, shorthand, computed) { return { type: Syntax.Property, key: key, value: value, kind: kind, method: method, shorthand: shorthand, computed: computed }; }, createReturnStatement: function (argument) { return { type: Syntax.ReturnStatement, argument: argument }; }, createSequenceExpression: function (expressions) { return { type: Syntax.SequenceExpression, expressions: expressions }; }, createSwitchCase: function (test, consequent) { return { type: Syntax.SwitchCase, test: test, consequent: consequent }; }, createSwitchStatement: function (discriminant, cases) { return { type: Syntax.SwitchStatement, discriminant: discriminant, cases: cases }; }, createThisExpression: function () { return { type: Syntax.ThisExpression }; }, createThrowStatement: function (argument) { return { type: Syntax.ThrowStatement, argument: argument }; }, createTryStatement: function (block, guardedHandlers, handlers, finalizer) { return { type: Syntax.TryStatement, block: block, guardedHandlers: guardedHandlers, handlers: handlers, finalizer: finalizer }; }, createUnaryExpression: function (operator, argument) { if (operator === '++' || operator === '--') { return { type: Syntax.UpdateExpression, operator: operator, argument: argument, prefix: true }; } return { type: Syntax.UnaryExpression, operator: operator, argument: argument, prefix: true }; }, createVariableDeclaration: function (declarations, kind) { return { type: Syntax.VariableDeclaration, declarations: declarations, kind: kind }; }, createVariableDeclarator: function (id, init) { return { type: Syntax.VariableDeclarator, id: id, init: init }; }, createWhileStatement: function (test, body) { return { type: Syntax.WhileStatement, test: test, body: body }; }, createWithStatement: function (object, body) { return { type: Syntax.WithStatement, object: object, body: body }; }, createTemplateElement: function (value, tail) { return { type: Syntax.TemplateElement, value: value, tail: tail }; }, createTemplateLiteral: function (quasis, expressions) { return { type: Syntax.TemplateLiteral, quasis: quasis, expressions: expressions }; }, createSpreadElement: function (argument) { return { type: Syntax.SpreadElement, argument: argument }; }, createSpreadProperty: function (argument) { return { type: Syntax.SpreadProperty, argument: argument }; }, createTaggedTemplateExpression: function (tag, quasi) { return { type: Syntax.TaggedTemplateExpression, tag: tag, quasi: quasi }; }, createArrowFunctionExpression: function (params, defaults, body, rest, expression, isAsync) { var arrowExpr = { type: Syntax.ArrowFunctionExpression, id: null, params: params, defaults: defaults, body: body, rest: rest, generator: false, expression: expression }; if (isAsync) { arrowExpr.async = true; } return arrowExpr; }, createMethodDefinition: function (propertyType, kind, key, value, computed) { return { type: Syntax.MethodDefinition, key: key, value: value, kind: kind, 'static': propertyType === ClassPropertyType["static"], computed: computed }; }, createClassProperty: function (key, typeAnnotation, computed, isStatic) { return { type: Syntax.ClassProperty, key: key, typeAnnotation: typeAnnotation, computed: computed, "static": isStatic }; }, createClassBody: function (body) { return { type: Syntax.ClassBody, body: body }; }, createClassImplements: function (id, typeParameters) { return { type: Syntax.ClassImplements, id: id, typeParameters: typeParameters }; }, createClassExpression: function (id, superClass, body, typeParameters, superTypeParameters, implemented) { return { type: Syntax.ClassExpression, id: id, superClass: superClass, body: body, typeParameters: typeParameters, superTypeParameters: superTypeParameters, "implements": implemented }; }, createClassDeclaration: function (id, superClass, body, typeParameters, superTypeParameters, implemented) { return { type: Syntax.ClassDeclaration, id: id, superClass: superClass, body: body, typeParameters: typeParameters, superTypeParameters: superTypeParameters, "implements": implemented }; }, createModuleSpecifier: function (token) { return { type: Syntax.ModuleSpecifier, value: token.value, raw: source.slice(token.range[0], token.range[1]) }; }, createExportSpecifier: function (id, name) { return { type: Syntax.ExportSpecifier, id: id, name: name }; }, createExportBatchSpecifier: function () { return { type: Syntax.ExportBatchSpecifier }; }, createImportDefaultSpecifier: function (id) { return { type: Syntax.ImportDefaultSpecifier, id: id }; }, createImportNamespaceSpecifier: function (id) { return { type: Syntax.ImportNamespaceSpecifier, id: id }; }, createExportDeclaration: function (isDefault, declaration, specifiers, src) { return { type: Syntax.ExportDeclaration, 'default': !!isDefault, declaration: declaration, specifiers: specifiers, source: src }; }, createImportSpecifier: function (id, name) { return { type: Syntax.ImportSpecifier, id: id, name: name }; }, createImportDeclaration: function (specifiers, src, isType) { return { type: Syntax.ImportDeclaration, specifiers: specifiers, source: src, isType: isType }; }, createYieldExpression: function (argument, dlg) { return { type: Syntax.YieldExpression, argument: argument, delegate: dlg }; }, createAwaitExpression: function (argument) { return { type: Syntax.AwaitExpression, argument: argument }; }, createComprehensionExpression: function (filter, blocks, body) { return { type: Syntax.ComprehensionExpression, filter: filter, blocks: blocks, body: body }; } }; // Return true if there is a line terminator before the next token. function peekLineTerminator() { var pos, line, start, found; pos = index; line = lineNumber; start = lineStart; skipComment(); found = lineNumber !== line; index = pos; lineNumber = line; lineStart = start; return found; } // Throw an exception function throwError(token, messageFormat) { var error, args = Array.prototype.slice.call(arguments, 2), msg = messageFormat.replace( /%(\d)/g, function (whole, idx) { assert(idx < args.length, 'Message reference must be in range'); return args[idx]; } ); if (typeof token.lineNumber === 'number') { error = new Error('Line ' + token.lineNumber + ': ' + msg); error.index = token.range[0]; error.lineNumber = token.lineNumber; error.column = token.range[0] - lineStart + 1; } else { error = new Error('Line ' + lineNumber + ': ' + msg); error.index = index; error.lineNumber = lineNumber; error.column = index - lineStart + 1; } error.description = msg; throw error; } function throwErrorTolerant() { try { throwError.apply(null, arguments); } catch (e) { if (extra.errors) { extra.errors.push(e); } else { throw e; } } } // Throw an exception because of the token. function throwUnexpected(token) { if (token.type === Token.EOF) { throwError(token, Messages.UnexpectedEOS); } if (token.type === Token.NumericLiteral) { throwError(token, Messages.UnexpectedNumber); } if (token.type === Token.StringLiteral || token.type === Token.JSXText) { throwError(token, Messages.UnexpectedString); } if (token.type === Token.Identifier) { throwError(token, Messages.UnexpectedIdentifier); } if (token.type === Token.Keyword) { if (isFutureReservedWord(token.value)) { throwError(token, Messages.UnexpectedReserved); } else if (strict && isStrictModeReservedWord(token.value)) { throwErrorTolerant(token, Messages.StrictReservedWord); return; } throwError(token, Messages.UnexpectedToken, token.value); } if (token.type === Token.Template) { throwError(token, Messages.UnexpectedTemplate, token.value.raw); } // BooleanLiteral, NullLiteral, or Punctuator. throwError(token, Messages.UnexpectedToken, token.value); } // Expect the next token to match the specified punctuator. // If not, an exception will be thrown. function expect(value) { var token = lex(); if (token.type !== Token.Punctuator || token.value !== value) { throwUnexpected(token); } } // Expect the next token to match the specified keyword. // If not, an exception will be thrown. function expectKeyword(keyword, contextual) { var token = lex(); if (token.type !== (contextual ? Token.Identifier : Token.Keyword) || token.value !== keyword) { throwUnexpected(token); } } // Expect the next token to match the specified contextual keyword. // If not, an exception will be thrown. function expectContextualKeyword(keyword) { return expectKeyword(keyword, true); } // Return true if the next token matches the specified punctuator. function match(value) { return lookahead.type === Token.Punctuator && lookahead.value === value; } // Return true if the next token matches the specified keyword function matchKeyword(keyword, contextual) { var expectedType = contextual ? Token.Identifier : Token.Keyword; return lookahead.type === expectedType && lookahead.value === keyword; } // Return true if the next token matches the specified contextual keyword function matchContextualKeyword(keyword) { return matchKeyword(keyword, true); } // Return true if the next token is an assignment operator function matchAssign() { var op; if (lookahead.type !== Token.Punctuator) { return false; } op = lookahead.value; return op === '=' || op === '*=' || op === '/=' || op === '%=' || op === '+=' || op === '-=' || op === '<<=' || op === '>>=' || op === '>>>=' || op === '&=' || op === '^=' || op === '|='; } // Note that 'yield' is treated as a keyword in strict mode, but a // contextual keyword (identifier) in non-strict mode, so we need to // use matchKeyword('yield', false) and matchKeyword('yield', true) // (i.e. matchContextualKeyword) appropriately. function matchYield() { return state.yieldAllowed && matchKeyword('yield', !strict); } function matchAsync() { var backtrackToken = lookahead, matches = false; if (matchContextualKeyword('async')) { lex(); // Make sure peekLineTerminator() starts after 'async'. matches = !peekLineTerminator(); rewind(backtrackToken); // Revert the lex(). } return matches; } function matchAwait() { return state.awaitAllowed && matchContextualKeyword('await'); } function consumeSemicolon() { var line, oldIndex = index, oldLineNumber = lineNumber, oldLineStart = lineStart, oldLookahead = lookahead; // Catch the very common case first: immediately a semicolon (char #59). if (source.charCodeAt(index) === 59) { lex(); return; } line = lineNumber; skipComment(); if (lineNumber !== line) { index = oldIndex; lineNumber = oldLineNumber; lineStart = oldLineStart; lookahead = oldLookahead; return; } if (match(';')) { lex(); return; } if (lookahead.type !== Token.EOF && !match('}')) { throwUnexpected(lookahead); } } // Return true if provided expression is LeftHandSideExpression function isLeftHandSide(expr) { return expr.type === Syntax.Identifier || expr.type === Syntax.MemberExpression; } function isAssignableLeftHandSide(expr) { return isLeftHandSide(expr) || expr.type === Syntax.ObjectPattern || expr.type === Syntax.ArrayPattern; } // 11.1.4 Array Initialiser function parseArrayInitialiser() { var elements = [], blocks = [], filter = null, tmp, possiblecomprehension = true, marker = markerCreate(); expect('['); while (!match(']')) { if (lookahead.value === 'for' && lookahead.type === Token.Keyword) { if (!possiblecomprehension) { throwError({}, Messages.ComprehensionError); } matchKeyword('for'); tmp = parseForStatement({ignoreBody: true}); tmp.of = tmp.type === Syntax.ForOfStatement; tmp.type = Syntax.ComprehensionBlock; if (tmp.left.kind) { // can't be let or const throwError({}, Messages.ComprehensionError); } blocks.push(tmp); } else if (lookahead.value === 'if' && lookahead.type === Token.Keyword) { if (!possiblecomprehension) { throwError({}, Messages.ComprehensionError); } expectKeyword('if'); expect('('); filter = parseExpression(); expect(')'); } else if (lookahead.value === ',' && lookahead.type === Token.Punctuator) { possiblecomprehension = false; // no longer allowed. lex(); elements.push(null); } else { tmp = parseSpreadOrAssignmentExpression(); elements.push(tmp); if (tmp && tmp.type === Syntax.SpreadElement) { if (!match(']')) { throwError({}, Messages.ElementAfterSpreadElement); } } else if (!(match(']') || matchKeyword('for') || matchKeyword('if'))) { expect(','); // this lexes. possiblecomprehension = false; } } } expect(']'); if (filter && !blocks.length) { throwError({}, Messages.ComprehensionRequiresBlock); } if (blocks.length) { if (elements.length !== 1) { throwError({}, Messages.ComprehensionError); } return markerApply(marker, delegate.createComprehensionExpression(filter, blocks, elements[0])); } return markerApply(marker, delegate.createArrayExpression(elements)); } // 11.1.5 Object Initialiser function parsePropertyFunction(options) { var previousStrict, previousYieldAllowed, previousAwaitAllowed, params, defaults, body, marker = markerCreate(); previousStrict = strict; previousYieldAllowed = state.yieldAllowed; state.yieldAllowed = options.generator; previousAwaitAllowed = state.awaitAllowed; state.awaitAllowed = options.async; params = options.params || []; defaults = options.defaults || []; body = parseConciseBody(); if (options.name && strict && isRestrictedWord(params[0].name)) { throwErrorTolerant(options.name, Messages.StrictParamName); } strict = previousStrict; state.yieldAllowed = previousYieldAllowed; state.awaitAllowed = previousAwaitAllowed; return markerApply(marker, delegate.createFunctionExpression( null, params, defaults, body, options.rest || null, options.generator, body.type !== Syntax.BlockStatement, options.async, options.returnType, options.typeParameters )); } function parsePropertyMethodFunction(options) { var previousStrict, tmp, method; previousStrict = strict; strict = true; tmp = parseParams(); if (tmp.stricted) { throwErrorTolerant(tmp.stricted, tmp.message); } method = parsePropertyFunction({ params: tmp.params, defaults: tmp.defaults, rest: tmp.rest, generator: options.generator, async: options.async, returnType: tmp.returnType, typeParameters: options.typeParameters }); strict = previousStrict; return method; } function parseObjectPropertyKey() { var marker = markerCreate(), token = lex(), propertyKey, result; // Note: This function is called only from parseObjectProperty(), where // EOF and Punctuator tokens are already filtered out. if (token.type === Token.StringLiteral || token.type === Token.NumericLiteral) { if (strict && token.octal) { throwErrorTolerant(token, Messages.StrictOctalLiteral); } return markerApply(marker, delegate.createLiteral(token)); } if (token.type === Token.Punctuator && token.value === '[') { // For computed properties we should skip the [ and ], and // capture in marker only the assignment expression itself. marker = markerCreate(); propertyKey = parseAssignmentExpression(); result = markerApply(marker, propertyKey); expect(']'); return result; } return markerApply(marker, delegate.createIdentifier(token.value)); } function parseObjectProperty() { var token, key, id, param, computed, marker = markerCreate(), returnType, typeParameters; token = lookahead; computed = (token.value === '[' && token.type === Token.Punctuator); if (token.type === Token.Identifier || computed || matchAsync()) { id = parseObjectPropertyKey(); if (match(':')) { lex(); return markerApply( marker, delegate.createProperty( 'init', id, parseAssignmentExpression(), false, false, computed ) ); } if (match('(') || match('<')) { if (match('<')) { typeParameters = parseTypeParameterDeclaration(); } return markerApply( marker, delegate.createProperty( 'init', id, parsePropertyMethodFunction({ generator: false, async: false, typeParameters: typeParameters }), true, false, computed ) ); } // Property Assignment: Getter and Setter. if (token.value === 'get') { computed = (lookahead.value === '['); key = parseObjectPropertyKey(); expect('('); expect(')'); if (match(':')) { returnType = parseTypeAnnotation(); } return markerApply( marker, delegate.createProperty( 'get', key, parsePropertyFunction({ generator: false, async: false, returnType: returnType }), false, false, computed ) ); } if (token.value === 'set') { computed = (lookahead.value === '['); key = parseObjectPropertyKey(); expect('('); token = lookahead; param = [ parseTypeAnnotatableIdentifier() ]; expect(')'); if (match(':')) { returnType = parseTypeAnnotation(); } return markerApply( marker, delegate.createProperty( 'set', key, parsePropertyFunction({ params: param, generator: false, async: false, name: token, returnType: returnType }), false, false, computed ) ); } if (token.value === 'async') { computed = (lookahead.value === '['); key = parseObjectPropertyKey(); if (match('<')) { typeParameters = parseTypeParameterDeclaration(); } return markerApply( marker, delegate.createProperty( 'init', key, parsePropertyMethodFunction({ generator: false, async: true, typeParameters: typeParameters }), true, false, computed ) ); } if (computed) { // Computed properties can only be used with full notation. throwUnexpected(lookahead); } return markerApply( marker, delegate.createProperty('init', id, id, false, true, false) ); } if (token.type === Token.EOF || token.type === Token.Punctuator) { if (!match('*')) { throwUnexpected(token); } lex(); computed = (lookahead.type === Token.Punctuator && lookahead.value === '['); id = parseObjectPropertyKey(); if (match('<')) { typeParameters = parseTypeParameterDeclaration(); } if (!match('(')) { throwUnexpected(lex()); } return markerApply(marker, delegate.createProperty( 'init', id, parsePropertyMethodFunction({ generator: true, typeParameters: typeParameters }), true, false, computed )); } key = parseObjectPropertyKey(); if (match(':')) { lex(); return markerApply(marker, delegate.createProperty('init', key, parseAssignmentExpression(), false, false, false)); } if (match('(') || match('<')) { if (match('<')) { typeParameters = parseTypeParameterDeclaration(); } return markerApply(marker, delegate.createProperty( 'init', key, parsePropertyMethodFunction({ generator: false, typeParameters: typeParameters }), true, false, false )); } throwUnexpected(lex()); } function parseObjectSpreadProperty() { var marker = markerCreate(); expect('...'); return markerApply(marker, delegate.createSpreadProperty(parseAssignmentExpression())); } function getFieldName(key) { var toString = String; if (key.type === Syntax.Identifier) { return key.name; } return toString(key.value); } function parseObjectInitialiser() { var properties = [], property, name, kind, storedKind, map = new StringMap(), marker = markerCreate(), toString = String; expect('{'); while (!match('}')) { if (match('...')) { property = parseObjectSpreadProperty(); } else { property = parseObjectProperty(); if (property.key.type === Syntax.Identifier) { name = property.key.name; } else { name = toString(property.key.value); } kind = (property.kind === 'init') ? PropertyKind.Data : (property.kind === 'get') ? PropertyKind.Get : PropertyKind.Set; if (map.has(name)) { storedKind = map.get(name); if (storedKind === PropertyKind.Data) { if (strict && kind === PropertyKind.Data) { throwErrorTolerant({}, Messages.StrictDuplicateProperty); } else if (kind !== PropertyKind.Data) { throwErrorTolerant({}, Messages.AccessorDataProperty); } } else { if (kind === PropertyKind.Data) { throwErrorTolerant({}, Messages.AccessorDataProperty); } else if (storedKind & kind) { throwErrorTolerant({}, Messages.AccessorGetSet); } } map.set(name, storedKind | kind); } else { map.set(name, kind); } } properties.push(property); if (!match('}')) { expect(','); } } expect('}'); return markerApply(marker, delegate.createObjectExpression(properties)); } function parseTemplateElement(option) { var marker = markerCreate(), token = scanTemplateElement(option); if (strict && token.octal) { throwError(token, Messages.StrictOctalLiteral); } return markerApply(marker, delegate.createTemplateElement({ raw: token.value.raw, cooked: token.value.cooked }, token.tail)); } function parseTemplateLiteral() { var quasi, quasis, expressions, marker = markerCreate(); quasi = parseTemplateElement({ head: true }); quasis = [ quasi ]; expressions = []; while (!quasi.tail) { expressions.push(parseExpression()); quasi = parseTemplateElement({ head: false }); quasis.push(quasi); } return markerApply(marker, delegate.createTemplateLiteral(quasis, expressions)); } // 11.1.6 The Grouping Operator function parseGroupExpression() { var expr, marker, typeAnnotation; expect('('); ++state.parenthesizedCount; marker = markerCreate(); expr = parseExpression(); if (match(':')) { typeAnnotation = parseTypeAnnotation(); expr = markerApply(marker, delegate.createTypeCast( expr, typeAnnotation )); } expect(')'); return expr; } function matchAsyncFuncExprOrDecl() { var token; if (matchAsync()) { token = lookahead2(); if (token.type === Token.Keyword && token.value === 'function') { return true; } } return false; } // 11.1 Primary Expressions function parsePrimaryExpression() { var marker, type, token, expr; type = lookahead.type; if (type === Token.Identifier) { marker = markerCreate(); return markerApply(marker, delegate.createIdentifier(lex().value)); } if (type === Token.StringLiteral || type === Token.NumericLiteral) { if (strict && lookahead.octal) { throwErrorTolerant(lookahead, Messages.StrictOctalLiteral); } marker = markerCreate(); return markerApply(marker, delegate.createLiteral(lex())); } if (type === Token.Keyword) { if (matchKeyword('this')) { marker = markerCreate(); lex(); return markerApply(marker, delegate.createThisExpression()); } if (matchKeyword('function')) { return parseFunctionExpression(); } if (matchKeyword('class')) { return parseClassExpression(); } if (matchKeyword('super')) { marker = markerCreate(); lex(); return markerApply(marker, delegate.createIdentifier('super')); } } if (type === Token.BooleanLiteral) { marker = markerCreate(); token = lex(); token.value = (token.value === 'true'); return markerApply(marker, delegate.createLiteral(token)); } if (type === Token.NullLiteral) { marker = markerCreate(); token = lex(); token.value = null; return markerApply(marker, delegate.createLiteral(token)); } if (match('[')) { return parseArrayInitialiser(); } if (match('{')) { return parseObjectInitialiser(); } if (match('(')) { return parseGroupExpression(); } if (match('/') || match('/=')) { marker = markerCreate(); expr = delegate.createLiteral(scanRegExp()); peek(); return markerApply(marker, expr); } if (type === Token.Template) { return parseTemplateLiteral(); } if (match('<')) { return parseJSXElement(); } throwUnexpected(lex()); } // 11.2 Left-Hand-Side Expressions function parseArguments() { var args = [], arg; expect('('); if (!match(')')) { while (index < length) { arg = parseSpreadOrAssignmentExpression(); args.push(arg); if (match(')')) { break; } else if (arg.type === Syntax.SpreadElement) { throwError({}, Messages.ElementAfterSpreadElement); } expect(','); } } expect(')'); return args; } function parseSpreadOrAssignmentExpression() { if (match('...')) { var marker = markerCreate(); lex(); return markerApply(marker, delegate.createSpreadElement(parseAssignmentExpression())); } return parseAssignmentExpression(); } function parseNonComputedProperty() { var marker = markerCreate(), token = lex(); if (!isIdentifierName(token)) { throwUnexpected(token); } return markerApply(marker, delegate.createIdentifier(token.value)); } function parseNonComputedMember() { expect('.'); return parseNonComputedProperty(); } function parseComputedMember() { var expr; expect('['); expr = parseExpression(); expect(']'); return expr; } function parseNewExpression() { var callee, args, marker = markerCreate(); expectKeyword('new'); callee = parseLeftHandSideExpression(); args = match('(') ? parseArguments() : []; return markerApply(marker, delegate.createNewExpression(callee, args)); } function parseLeftHandSideExpressionAllowCall() { var expr, args, marker = markerCreate(); expr = matchKeyword('new') ? parseNewExpression() : parsePrimaryExpression(); while (match('.') || match('[') || match('(') || lookahead.type === Token.Template) { if (match('(')) { args = parseArguments(); expr = markerApply(marker, delegate.createCallExpression(expr, args)); } else if (match('[')) { expr = markerApply(marker, delegate.createMemberExpression('[', expr, parseComputedMember())); } else if (match('.')) { expr = markerApply(marker, delegate.createMemberExpression('.', expr, parseNonComputedMember())); } else { expr = markerApply(marker, delegate.createTaggedTemplateExpression(expr, parseTemplateLiteral())); } } return expr; } function parseLeftHandSideExpression() { var expr, marker = markerCreate(); expr = matchKeyword('new') ? parseNewExpression() : parsePrimaryExpression(); while (match('.') || match('[') || lookahead.type === Token.Template) { if (match('[')) { expr = markerApply(marker, delegate.createMemberExpression('[', expr, parseComputedMember())); } else if (match('.')) { expr = markerApply(marker, delegate.createMemberExpression('.', expr, parseNonComputedMember())); } else { expr = markerApply(marker, delegate.createTaggedTemplateExpression(expr, parseTemplateLiteral())); } } return expr; } // 11.3 Postfix Expressions function parsePostfixExpression() { var marker = markerCreate(), expr = parseLeftHandSideExpressionAllowCall(), token; if (lookahead.type !== Token.Punctuator) { return expr; } if ((match('++') || match('--')) && !peekLineTerminator()) { // 11.3.1, 11.3.2 if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) { throwErrorTolerant({}, Messages.StrictLHSPostfix); } if (!isLeftHandSide(expr)) { throwError({}, Messages.InvalidLHSInAssignment); } token = lex(); expr = markerApply(marker, delegate.createPostfixExpression(token.value, expr)); } return expr; } // 11.4 Unary Operators function parseUnaryExpression() { var marker, token, expr; if (lookahead.type !== Token.Punctuator && lookahead.type !== Token.Keyword) { return parsePostfixExpression(); } if (match('++') || match('--')) { marker = markerCreate(); token = lex(); expr = parseUnaryExpression(); // 11.4.4, 11.4.5 if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) { throwErrorTolerant({}, Messages.StrictLHSPrefix); } if (!isLeftHandSide(expr)) { throwError({}, Messages.InvalidLHSInAssignment); } return markerApply(marker, delegate.createUnaryExpression(token.value, expr)); } if (match('+') || match('-') || match('~') || match('!')) { marker = markerCreate(); token = lex(); expr = parseUnaryExpression(); return markerApply(marker, delegate.createUnaryExpression(token.value, expr)); } if (matchKeyword('delete') || matchKeyword('void') || matchKeyword('typeof')) { marker = markerCreate(); token = lex(); expr = parseUnaryExpression(); expr = markerApply(marker, delegate.createUnaryExpression(token.value, expr)); if (strict && expr.operator === 'delete' && expr.argument.type === Syntax.Identifier) { throwErrorTolerant({}, Messages.StrictDelete); } return expr; } return parsePostfixExpression(); } function binaryPrecedence(token, allowIn) { var prec = 0; if (token.type !== Token.Punctuator && token.type !== Token.Keyword) { return 0; } switch (token.value) { case '||': prec = 1; break; case '&&': prec = 2; break; case '|': prec = 3; break; case '^': prec = 4; break; case '&': prec = 5; break; case '==': case '!=': case '===': case '!==': prec = 6; break; case '<': case '>': case '<=': case '>=': case 'instanceof': prec = 7; break; case 'in': prec = allowIn ? 7 : 0; break; case '<<': case '>>': case '>>>': prec = 8; break; case '+': case '-': prec = 9; break; case '*': case '/': case '%': prec = 11; break; default: break; } return prec; } // 11.5 Multiplicative Operators // 11.6 Additive Operators // 11.7 Bitwise Shift Operators // 11.8 Relational Operators // 11.9 Equality Operators // 11.10 Binary Bitwise Operators // 11.11 Binary Logical Operators function parseBinaryExpression() { var expr, token, prec, previousAllowIn, stack, right, operator, left, i, marker, markers; previousAllowIn = state.allowIn; state.allowIn = true; marker = markerCreate(); left = parseUnaryExpression(); token = lookahead; prec = binaryPrecedence(token, previousAllowIn); if (prec === 0) { return left; } token.prec = prec; lex(); markers = [marker, markerCreate()]; right = parseUnaryExpression(); stack = [left, token, right]; while ((prec = binaryPrecedence(lookahead, previousAllowIn)) > 0) { // Reduce: make a binary expression from the three topmost entries. while ((stack.length > 2) && (prec <= stack[stack.length - 2].prec)) { right = stack.pop(); operator = stack.pop().value; left = stack.pop(); expr = delegate.createBinaryExpression(operator, left, right); markers.pop(); marker = markers.pop(); markerApply(marker, expr); stack.push(expr); markers.push(marker); } // Shift. token = lex(); token.prec = prec; stack.push(token); markers.push(markerCreate()); expr = parseUnaryExpression(); stack.push(expr); } state.allowIn = previousAllowIn; // Final reduce to clean-up the stack. i = stack.length - 1; expr = stack[i]; markers.pop(); while (i > 1) { expr = delegate.createBinaryExpression(stack[i - 1].value, stack[i - 2], expr); i -= 2; marker = markers.pop(); markerApply(marker, expr); } return expr; } // 11.12 Conditional Operator function parseConditionalExpression() { var expr, previousAllowIn, consequent, alternate, marker = markerCreate(); expr = parseBinaryExpression(); if (match('?')) { lex(); previousAllowIn = state.allowIn; state.allowIn = true; consequent = parseAssignmentExpression(); state.allowIn = previousAllowIn; expect(':'); alternate = parseAssignmentExpression(); expr = markerApply(marker, delegate.createConditionalExpression(expr, consequent, alternate)); } return expr; } // 11.13 Assignment Operators // 12.14.5 AssignmentPattern function reinterpretAsAssignmentBindingPattern(expr) { var i, len, property, element; if (expr.type === Syntax.ObjectExpression) { expr.type = Syntax.ObjectPattern; for (i = 0, len = expr.properties.length; i < len; i += 1) { property = expr.properties[i]; if (property.type === Syntax.SpreadProperty) { if (i < len - 1) { throwError({}, Messages.PropertyAfterSpreadProperty); } reinterpretAsAssignmentBindingPattern(property.argument); } else { if (property.kind !== 'init') { throwError({}, Messages.InvalidLHSInAssignment); } reinterpretAsAssignmentBindingPattern(property.value); } } } else if (expr.type === Syntax.ArrayExpression) { expr.type = Syntax.ArrayPattern; for (i = 0, len = expr.elements.length; i < len; i += 1) { element = expr.elements[i]; /* istanbul ignore else */ if (element) { reinterpretAsAssignmentBindingPattern(element); } } } else if (expr.type === Syntax.Identifier) { if (isRestrictedWord(expr.name)) { throwError({}, Messages.InvalidLHSInAssignment); } } else if (expr.type === Syntax.SpreadElement) { reinterpretAsAssignmentBindingPattern(expr.argument); if (expr.argument.type === Syntax.ObjectPattern) { throwError({}, Messages.ObjectPatternAsSpread); } } else { /* istanbul ignore else */ if (expr.type !== Syntax.MemberExpression && expr.type !== Syntax.CallExpression && expr.type !== Syntax.NewExpression) { throwError({}, Messages.InvalidLHSInAssignment); } } } // 13.2.3 BindingPattern function reinterpretAsDestructuredParameter(options, expr) { var i, len, property, element; if (expr.type === Syntax.ObjectExpression) { expr.type = Syntax.ObjectPattern; for (i = 0, len = expr.properties.length; i < len; i += 1) { property = expr.properties[i]; if (property.type === Syntax.SpreadProperty) { if (i < len - 1) { throwError({}, Messages.PropertyAfterSpreadProperty); } reinterpretAsDestructuredParameter(options, property.argument); } else { if (property.kind !== 'init') { throwError({}, Messages.InvalidLHSInFormalsList); } reinterpretAsDestructuredParameter(options, property.value); } } } else if (expr.type === Syntax.ArrayExpression) { expr.type = Syntax.ArrayPattern; for (i = 0, len = expr.elements.length; i < len; i += 1) { element = expr.elements[i]; if (element) { reinterpretAsDestructuredParameter(options, element); } } } else if (expr.type === Syntax.Identifier) { validateParam(options, expr, expr.name); } else if (expr.type === Syntax.SpreadElement) { // BindingRestElement only allows BindingIdentifier if (expr.argument.type !== Syntax.Identifier) { throwError({}, Messages.InvalidLHSInFormalsList); } validateParam(options, expr.argument, expr.argument.name); } else { throwError({}, Messages.InvalidLHSInFormalsList); } } function reinterpretAsCoverFormalsList(expressions) { var i, len, param, params, defaults, defaultCount, options, rest; params = []; defaults = []; defaultCount = 0; rest = null; options = { paramSet: new StringMap() }; for (i = 0, len = expressions.length; i < len; i += 1) { param = expressions[i]; if (param.type === Syntax.Identifier) { params.push(param); defaults.push(null); validateParam(options, param, param.name); } else if (param.type === Syntax.ObjectExpression || param.type === Syntax.ArrayExpression) { reinterpretAsDestructuredParameter(options, param); params.push(param); defaults.push(null); } else if (param.type === Syntax.SpreadElement) { assert(i === len - 1, 'It is guaranteed that SpreadElement is last element by parseExpression'); if (param.argument.type !== Syntax.Identifier) { throwError({}, Messages.InvalidLHSInFormalsList); } reinterpretAsDestructuredParameter(options, param.argument); rest = param.argument; } else if (param.type === Syntax.AssignmentExpression) { params.push(param.left); defaults.push(param.right); ++defaultCount; validateParam(options, param.left, param.left.name); } else { return null; } } if (options.message === Messages.StrictParamDupe) { throwError( strict ? options.stricted : options.firstRestricted, options.message ); } if (defaultCount === 0) { defaults = []; } return { params: params, defaults: defaults, rest: rest, stricted: options.stricted, firstRestricted: options.firstRestricted, message: options.message }; } function parseArrowFunctionExpression(options, marker) { var previousStrict, previousYieldAllowed, previousAwaitAllowed, body; expect('=>'); previousStrict = strict; previousYieldAllowed = state.yieldAllowed; state.yieldAllowed = false; previousAwaitAllowed = state.awaitAllowed; state.awaitAllowed = !!options.async; body = parseConciseBody(); if (strict && options.firstRestricted) { throwError(options.firstRestricted, options.message); } if (strict && options.stricted) { throwErrorTolerant(options.stricted, options.message); } strict = previousStrict; state.yieldAllowed = previousYieldAllowed; state.awaitAllowed = previousAwaitAllowed; return markerApply(marker, delegate.createArrowFunctionExpression( options.params, options.defaults, body, options.rest, body.type !== Syntax.BlockStatement, !!options.async )); } function parseAssignmentExpression() { var marker, expr, token, params, oldParenthesizedCount, startsWithParen = false, backtrackToken = lookahead, possiblyAsync = false; if (matchYield()) { return parseYieldExpression(); } if (matchAwait()) { return parseAwaitExpression(); } oldParenthesizedCount = state.parenthesizedCount; marker = markerCreate(); if (matchAsyncFuncExprOrDecl()) { return parseFunctionExpression(); } if (matchAsync()) { // We can't be completely sure that this 'async' token is // actually a contextual keyword modifying a function // expression, so we might have to un-lex() it later by // calling rewind(backtrackToken). possiblyAsync = true; lex(); } if (match('(')) { token = lookahead2(); if ((token.type === Token.Punctuator && token.value === ')') || token.value === '...') { params = parseParams(); if (!match('=>')) { throwUnexpected(lex()); } params.async = possiblyAsync; return parseArrowFunctionExpression(params, marker); } startsWithParen = true; } token = lookahead; // If the 'async' keyword is not followed by a '(' character or an // identifier, then it can't be an arrow function modifier, and we // should interpret it as a normal identifer. if (possiblyAsync && !match('(') && token.type !== Token.Identifier) { possiblyAsync = false; rewind(backtrackToken); } expr = parseConditionalExpression(); if (match('=>') && (state.parenthesizedCount === oldParenthesizedCount || state.parenthesizedCount === (oldParenthesizedCount + 1))) { if (expr.type === Syntax.Identifier) { params = reinterpretAsCoverFormalsList([ expr ]); } else if (expr.type === Syntax.AssignmentExpression || expr.type === Syntax.ArrayExpression || expr.type === Syntax.ObjectExpression) { if (!startsWithParen) { throwUnexpected(lex()); } params = reinterpretAsCoverFormalsList([ expr ]); } else if (expr.type === Syntax.SequenceExpression) { params = reinterpretAsCoverFormalsList(expr.expressions); } if (params) { params.async = possiblyAsync; return parseArrowFunctionExpression(params, marker); } } // If we haven't returned by now, then the 'async' keyword was not // a function modifier, and we should rewind and interpret it as a // normal identifier. if (possiblyAsync) { possiblyAsync = false; rewind(backtrackToken); expr = parseConditionalExpression(); } if (matchAssign()) { // 11.13.1 if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) { throwErrorTolerant(token, Messages.StrictLHSAssignment); } // ES.next draf 11.13 Runtime Semantics step 1 if (match('=') && (expr.type === Syntax.ObjectExpression || expr.type === Syntax.ArrayExpression)) { reinterpretAsAssignmentBindingPattern(expr); } else if (!isLeftHandSide(expr)) { throwError({}, Messages.InvalidLHSInAssignment); } expr = markerApply(marker, delegate.createAssignmentExpression(lex().value, expr, parseAssignmentExpression())); } return expr; } // 11.14 Comma Operator function parseExpression() { var marker, expr, expressions, sequence, spreadFound; marker = markerCreate(); expr = parseAssignmentExpression(); expressions = [ expr ]; if (match(',')) { while (index < length) { if (!match(',')) { break; } lex(); expr = parseSpreadOrAssignmentExpression(); expressions.push(expr); if (expr.type === Syntax.SpreadElement) { spreadFound = true; if (!match(')')) { throwError({}, Messages.ElementAfterSpreadElement); } break; } } sequence = markerApply(marker, delegate.createSequenceExpression(expressions)); } if (spreadFound && lookahead2().value !== '=>') { throwError({}, Messages.IllegalSpread); } return sequence || expr; } // 12.1 Block function parseStatementList() { var list = [], statement; while (index < length) { if (match('}')) { break; } statement = parseSourceElement(); if (typeof statement === 'undefined') { break; } list.push(statement); } return list; } function parseBlock() { var block, marker = markerCreate(); expect('{'); block = parseStatementList(); expect('}'); return markerApply(marker, delegate.createBlockStatement(block)); } // 12.2 Variable Statement function parseTypeParameterDeclaration() { var marker = markerCreate(), paramTypes = []; expect('<'); while (!match('>')) { paramTypes.push(parseVariableIdentifier()); if (!match('>')) { expect(','); } } expect('>'); return markerApply(marker, delegate.createTypeParameterDeclaration( paramTypes )); } function parseTypeParameterInstantiation() { var marker = markerCreate(), oldInType = state.inType, paramTypes = []; state.inType = true; expect('<'); while (!match('>')) { paramTypes.push(parseType()); if (!match('>')) { expect(','); } } expect('>'); state.inType = oldInType; return markerApply(marker, delegate.createTypeParameterInstantiation( paramTypes )); } function parseObjectTypeIndexer(marker, isStatic) { var id, key, value; expect('['); id = parseObjectPropertyKey(); expect(':'); key = parseType(); expect(']'); expect(':'); value = parseType(); return markerApply(marker, delegate.createObjectTypeIndexer( id, key, value, isStatic )); } function parseObjectTypeMethodish(marker) { var params = [], rest = null, returnType, typeParameters = null; if (match('<')) { typeParameters = parseTypeParameterDeclaration(); } expect('('); while (lookahead.type === Token.Identifier) { params.push(parseFunctionTypeParam()); if (!match(')')) { expect(','); } } if (match('...')) { lex(); rest = parseFunctionTypeParam(); } expect(')'); expect(':'); returnType = parseType(); return markerApply(marker, delegate.createFunctionTypeAnnotation( params, returnType, rest, typeParameters )); } function parseObjectTypeMethod(marker, isStatic, key) { var optional = false, value; value = parseObjectTypeMethodish(marker); return markerApply(marker, delegate.createObjectTypeProperty( key, value, optional, isStatic )); } function parseObjectTypeCallProperty(marker, isStatic) { var valueMarker = markerCreate(); return markerApply(marker, delegate.createObjectTypeCallProperty( parseObjectTypeMethodish(valueMarker), isStatic )); } function parseObjectType(allowStatic) { var callProperties = [], indexers = [], marker, optional = false, properties = [], propertyKey, propertyTypeAnnotation, token, isStatic, matchStatic; expect('{'); while (!match('}')) { marker = markerCreate(); matchStatic = strict ? matchKeyword('static') : matchContextualKeyword('static'); if (allowStatic && matchStatic) { token = lex(); isStatic = true; } if (match('[')) { indexers.push(parseObjectTypeIndexer(marker, isStatic)); } else if (match('(') || match('<')) { callProperties.push(parseObjectTypeCallProperty(marker, allowStatic)); } else { if (isStatic && match(':')) { propertyKey = markerApply(marker, delegate.createIdentifier(token)); throwErrorTolerant(token, Messages.StrictReservedWord); } else { propertyKey = parseObjectPropertyKey(); } if (match('<') || match('(')) { // This is a method property properties.push(parseObjectTypeMethod(marker, isStatic, propertyKey)); } else { if (match('?')) { lex(); optional = true; } expect(':'); propertyTypeAnnotation = parseType(); properties.push(markerApply(marker, delegate.createObjectTypeProperty( propertyKey, propertyTypeAnnotation, optional, isStatic ))); } } if (match(';')) { lex(); } else if (!match('}')) { throwUnexpected(lookahead); } } expect('}'); return delegate.createObjectTypeAnnotation( properties, indexers, callProperties ); } function parseGenericType() { var marker = markerCreate(), typeParameters = null, typeIdentifier; typeIdentifier = parseVariableIdentifier(); while (match('.')) { expect('.'); typeIdentifier = markerApply(marker, delegate.createQualifiedTypeIdentifier( typeIdentifier, parseVariableIdentifier() )); } if (match('<')) { typeParameters = parseTypeParameterInstantiation(); } return markerApply(marker, delegate.createGenericTypeAnnotation( typeIdentifier, typeParameters )); } function parseVoidType() { var marker = markerCreate(); expectKeyword('void'); return markerApply(marker, delegate.createVoidTypeAnnotation()); } function parseTypeofType() { var argument, marker = markerCreate(); expectKeyword('typeof'); argument = parsePrimaryType(); return markerApply(marker, delegate.createTypeofTypeAnnotation( argument )); } function parseTupleType() { var marker = markerCreate(), types = []; expect('['); // We allow trailing commas while (index < length && !match(']')) { types.push(parseType()); if (match(']')) { break; } expect(','); } expect(']'); return markerApply(marker, delegate.createTupleTypeAnnotation( types )); } function parseFunctionTypeParam() { var marker = markerCreate(), name, optional = false, typeAnnotation; name = parseVariableIdentifier(); if (match('?')) { lex(); optional = true; } expect(':'); typeAnnotation = parseType(); return markerApply(marker, delegate.createFunctionTypeParam( name, typeAnnotation, optional )); } function parseFunctionTypeParams() { var ret = { params: [], rest: null }; while (lookahead.type === Token.Identifier) { ret.params.push(parseFunctionTypeParam()); if (!match(')')) { expect(','); } } if (match('...')) { lex(); ret.rest = parseFunctionTypeParam(); } return ret; } // The parsing of types roughly parallels the parsing of expressions, and // primary types are kind of like primary expressions...they're the // primitives with which other types are constructed. function parsePrimaryType() { var params = null, returnType = null, marker = markerCreate(), rest = null, tmp, typeParameters, token, type, isGroupedType = false; switch (lookahead.type) { case Token.Identifier: switch (lookahead.value) { case 'any': lex(); return markerApply(marker, delegate.createAnyTypeAnnotation()); case 'bool': // fallthrough case 'boolean': lex(); return markerApply(marker, delegate.createBooleanTypeAnnotation()); case 'number': lex(); return markerApply(marker, delegate.createNumberTypeAnnotation()); case 'string': lex(); return markerApply(marker, delegate.createStringTypeAnnotation()); } return markerApply(marker, parseGenericType()); case Token.Punctuator: switch (lookahead.value) { case '{': return markerApply(marker, parseObjectType()); case '[': return parseTupleType(); case '<': typeParameters = parseTypeParameterDeclaration(); expect('('); tmp = parseFunctionTypeParams(); params = tmp.params; rest = tmp.rest; expect(')'); expect('=>'); returnType = parseType(); return markerApply(marker, delegate.createFunctionTypeAnnotation( params, returnType, rest, typeParameters )); case '(': lex(); // Check to see if this is actually a grouped type if (!match(')') && !match('...')) { if (lookahead.type === Token.Identifier) { token = lookahead2(); isGroupedType = token.value !== '?' && token.value !== ':'; } else { isGroupedType = true; } } if (isGroupedType) { type = parseType(); expect(')'); // If we see a => next then someone was probably confused about // function types, so we can provide a better error message if (match('=>')) { throwError({}, Messages.ConfusedAboutFunctionType); } return type; } tmp = parseFunctionTypeParams(); params = tmp.params; rest = tmp.rest; expect(')'); expect('=>'); returnType = parseType(); return markerApply(marker, delegate.createFunctionTypeAnnotation( params, returnType, rest, null /* typeParameters */ )); } break; case Token.Keyword: switch (lookahead.value) { case 'void': return markerApply(marker, parseVoidType()); case 'typeof': return markerApply(marker, parseTypeofType()); } break; case Token.StringLiteral: token = lex(); if (token.octal) { throwError(token, Messages.StrictOctalLiteral); } return markerApply(marker, delegate.createStringLiteralTypeAnnotation( token )); } throwUnexpected(lookahead); } function parsePostfixType() { var marker = markerCreate(), t = parsePrimaryType(); if (match('[')) { expect('['); expect(']'); return markerApply(marker, delegate.createArrayTypeAnnotation(t)); } return t; } function parsePrefixType() { var marker = markerCreate(); if (match('?')) { lex(); return markerApply(marker, delegate.createNullableTypeAnnotation( parsePrefixType() )); } return parsePostfixType(); } function parseIntersectionType() { var marker = markerCreate(), type, types; type = parsePrefixType(); types = [type]; while (match('&')) { lex(); types.push(parsePrefixType()); } return types.length === 1 ? type : markerApply(marker, delegate.createIntersectionTypeAnnotation( types )); } function parseUnionType() { var marker = markerCreate(), type, types; type = parseIntersectionType(); types = [type]; while (match('|')) { lex(); types.push(parseIntersectionType()); } return types.length === 1 ? type : markerApply(marker, delegate.createUnionTypeAnnotation( types )); } function parseType() { var oldInType = state.inType, type; state.inType = true; type = parseUnionType(); state.inType = oldInType; return type; } function parseTypeAnnotation() { var marker = markerCreate(), type; expect(':'); type = parseType(); return markerApply(marker, delegate.createTypeAnnotation(type)); } function parseVariableIdentifier() { var marker = markerCreate(), token = lex(); if (token.type !== Token.Identifier) { throwUnexpected(token); } return markerApply(marker, delegate.createIdentifier(token.value)); } function parseTypeAnnotatableIdentifier(requireTypeAnnotation, canBeOptionalParam) { var marker = markerCreate(), ident = parseVariableIdentifier(), isOptionalParam = false; if (canBeOptionalParam && match('?')) { expect('?'); isOptionalParam = true; } if (requireTypeAnnotation || match(':')) { ident.typeAnnotation = parseTypeAnnotation(); ident = markerApply(marker, ident); } if (isOptionalParam) { ident.optional = true; ident = markerApply(marker, ident); } return ident; } function parseVariableDeclaration(kind) { var id, marker = markerCreate(), init = null, typeAnnotationMarker = markerCreate(); if (match('{')) { id = parseObjectInitialiser(); reinterpretAsAssignmentBindingPattern(id); if (match(':')) { id.typeAnnotation = parseTypeAnnotation(); markerApply(typeAnnotationMarker, id); } } else if (match('[')) { id = parseArrayInitialiser(); reinterpretAsAssignmentBindingPattern(id); if (match(':')) { id.typeAnnotation = parseTypeAnnotation(); markerApply(typeAnnotationMarker, id); } } else { /* istanbul ignore next */ id = state.allowKeyword ? parseNonComputedProperty() : parseTypeAnnotatableIdentifier(); // 12.2.1 if (strict && isRestrictedWord(id.name)) { throwErrorTolerant({}, Messages.StrictVarName); } } if (kind === 'const') { if (!match('=')) { throwError({}, Messages.NoUninitializedConst); } expect('='); init = parseAssignmentExpression(); } else if (match('=')) { lex(); init = parseAssignmentExpression(); } return markerApply(marker, delegate.createVariableDeclarator(id, init)); } function parseVariableDeclarationList(kind) { var list = []; do { list.push(parseVariableDeclaration(kind)); if (!match(',')) { break; } lex(); } while (index < length); return list; } function parseVariableStatement() { var declarations, marker = markerCreate(); expectKeyword('var'); declarations = parseVariableDeclarationList(); consumeSemicolon(); return markerApply(marker, delegate.createVariableDeclaration(declarations, 'var')); } // kind may be `const` or `let` // Both are experimental and not in the specification yet. // see http://wiki.ecmascript.org/doku.php?id=harmony:const // and http://wiki.ecmascript.org/doku.php?id=harmony:let function parseConstLetDeclaration(kind) { var declarations, marker = markerCreate(); expectKeyword(kind); declarations = parseVariableDeclarationList(kind); consumeSemicolon(); return markerApply(marker, delegate.createVariableDeclaration(declarations, kind)); } // people.mozilla.org/~jorendorff/es6-draft.html function parseModuleSpecifier() { var marker = markerCreate(), specifier; if (lookahead.type !== Token.StringLiteral) { throwError({}, Messages.InvalidModuleSpecifier); } specifier = delegate.createModuleSpecifier(lookahead); lex(); return markerApply(marker, specifier); } function parseExportBatchSpecifier() { var marker = markerCreate(); expect('*'); return markerApply(marker, delegate.createExportBatchSpecifier()); } function parseExportSpecifier() { var id, name = null, marker = markerCreate(), from; if (matchKeyword('default')) { lex(); id = markerApply(marker, delegate.createIdentifier('default')); // export {default} from "something"; } else { id = parseVariableIdentifier(); } if (matchContextualKeyword('as')) { lex(); name = parseNonComputedProperty(); } return markerApply(marker, delegate.createExportSpecifier(id, name)); } function parseExportDeclaration() { var declaration = null, possibleIdentifierToken, sourceElement, isExportFromIdentifier, src = null, specifiers = [], marker = markerCreate(); expectKeyword('export'); if (matchKeyword('default')) { // covers: // export default ... lex(); if (matchKeyword('function') || matchKeyword('class')) { possibleIdentifierToken = lookahead2(); if (isIdentifierName(possibleIdentifierToken)) { // covers: // export default function foo () {} // export default class foo {} sourceElement = parseSourceElement(); return markerApply(marker, delegate.createExportDeclaration(true, sourceElement, [sourceElement.id], null)); } // covers: // export default function () {} // export default class {} switch (lookahead.value) { case 'class': return markerApply(marker, delegate.createExportDeclaration(true, parseClassExpression(), [], null)); case 'function': return markerApply(marker, delegate.createExportDeclaration(true, parseFunctionExpression(), [], null)); } } if (matchContextualKeyword('from')) { throwError({}, Messages.UnexpectedToken, lookahead.value); } // covers: // export default {}; // export default []; if (match('{')) { declaration = parseObjectInitialiser(); } else if (match('[')) { declaration = parseArrayInitialiser(); } else { declaration = parseAssignmentExpression(); } consumeSemicolon(); return markerApply(marker, delegate.createExportDeclaration(true, declaration, [], null)); } // non-default export if (lookahead.type === Token.Keyword || matchContextualKeyword('type')) { // covers: // export var f = 1; switch (lookahead.value) { case 'type': case 'let': case 'const': case 'var': case 'class': case 'function': return markerApply(marker, delegate.createExportDeclaration(false, parseSourceElement(), specifiers, null)); } } if (match('*')) { // covers: // export * from "foo"; specifiers.push(parseExportBatchSpecifier()); if (!matchContextualKeyword('from')) { throwError({}, lookahead.value ? Messages.UnexpectedToken : Messages.MissingFromClause, lookahead.value); } lex(); src = parseModuleSpecifier(); consumeSemicolon(); return markerApply(marker, delegate.createExportDeclaration(false, null, specifiers, src)); } expect('{'); if (!match('}')) { do { isExportFromIdentifier = isExportFromIdentifier || matchKeyword('default'); specifiers.push(parseExportSpecifier()); } while (match(',') && lex()); } expect('}'); if (matchContextualKeyword('from')) { // covering: // export {default} from "foo"; // export {foo} from "foo"; lex(); src = parseModuleSpecifier(); consumeSemicolon(); } else if (isExportFromIdentifier) { // covering: // export {default}; // missing fromClause throwError({}, lookahead.value ? Messages.UnexpectedToken : Messages.MissingFromClause, lookahead.value); } else { // cover // export {foo}; consumeSemicolon(); } return markerApply(marker, delegate.createExportDeclaration(false, declaration, specifiers, src)); } function parseImportSpecifier() { // import {<foo as bar>} ...; var id, name = null, marker = markerCreate(); id = parseNonComputedProperty(); if (matchContextualKeyword('as')) { lex(); name = parseVariableIdentifier(); } return markerApply(marker, delegate.createImportSpecifier(id, name)); } function parseNamedImports() { var specifiers = []; // {foo, bar as bas} expect('{'); if (!match('}')) { do { specifiers.push(parseImportSpecifier()); } while (match(',') && lex()); } expect('}'); return specifiers; } function parseImportDefaultSpecifier() { // import <foo> ...; var id, marker = markerCreate(); id = parseNonComputedProperty(); return markerApply(marker, delegate.createImportDefaultSpecifier(id)); } function parseImportNamespaceSpecifier() { // import <* as foo> ...; var id, marker = markerCreate(); expect('*'); if (!matchContextualKeyword('as')) { throwError({}, Messages.NoAsAfterImportNamespace); } lex(); id = parseNonComputedProperty(); return markerApply(marker, delegate.createImportNamespaceSpecifier(id)); } function parseImportDeclaration() { var specifiers, src, marker = markerCreate(), isType = false, token2; expectKeyword('import'); if (matchContextualKeyword('type')) { token2 = lookahead2(); if ((token2.type === Token.Identifier && token2.value !== 'from') || (token2.type === Token.Punctuator && (token2.value === '{' || token2.value === '*'))) { isType = true; lex(); } } specifiers = []; if (lookahead.type === Token.StringLiteral) { // covers: // import "foo"; src = parseModuleSpecifier(); consumeSemicolon(); return markerApply(marker, delegate.createImportDeclaration(specifiers, src, isType)); } if (!matchKeyword('default') && isIdentifierName(lookahead)) { // covers: // import foo // import foo, ... specifiers.push(parseImportDefaultSpecifier()); if (match(',')) { lex(); } } if (match('*')) { // covers: // import foo, * as foo // import * as foo specifiers.push(parseImportNamespaceSpecifier()); } else if (match('{')) { // covers: // import foo, {bar} // import {bar} specifiers = specifiers.concat(parseNamedImports()); } if (!matchContextualKeyword('from')) { throwError({}, lookahead.value ? Messages.UnexpectedToken : Messages.MissingFromClause, lookahead.value); } lex(); src = parseModuleSpecifier(); consumeSemicolon(); return markerApply(marker, delegate.createImportDeclaration(specifiers, src, isType)); } // 12.3 Empty Statement function parseEmptyStatement() { var marker = markerCreate(); expect(';'); return markerApply(marker, delegate.createEmptyStatement()); } // 12.4 Expression Statement function parseExpressionStatement() { var marker = markerCreate(), expr = parseExpression(); consumeSemicolon(); return markerApply(marker, delegate.createExpressionStatement(expr)); } // 12.5 If statement function parseIfStatement() { var test, consequent, alternate, marker = markerCreate(); expectKeyword('if'); expect('('); test = parseExpression(); expect(')'); consequent = parseStatement(); if (matchKeyword('else')) { lex(); alternate = parseStatement(); } else { alternate = null; } return markerApply(marker, delegate.createIfStatement(test, consequent, alternate)); } // 12.6 Iteration Statements function parseDoWhileStatement() { var body, test, oldInIteration, marker = markerCreate(); expectKeyword('do'); oldInIteration = state.inIteration; state.inIteration = true; body = parseStatement(); state.inIteration = oldInIteration; expectKeyword('while'); expect('('); test = parseExpression(); expect(')'); if (match(';')) { lex(); } return markerApply(marker, delegate.createDoWhileStatement(body, test)); } function parseWhileStatement() { var test, body, oldInIteration, marker = markerCreate(); expectKeyword('while'); expect('('); test = parseExpression(); expect(')'); oldInIteration = state.inIteration; state.inIteration = true; body = parseStatement(); state.inIteration = oldInIteration; return markerApply(marker, delegate.createWhileStatement(test, body)); } function parseForVariableDeclaration() { var marker = markerCreate(), token = lex(), declarations = parseVariableDeclarationList(); return markerApply(marker, delegate.createVariableDeclaration(declarations, token.value)); } function parseForStatement(opts) { var init, test, update, left, right, body, operator, oldInIteration, marker = markerCreate(); init = test = update = null; expectKeyword('for'); // http://wiki.ecmascript.org/doku.php?id=proposals:iterators_and_generators&s=each if (matchContextualKeyword('each')) { throwError({}, Messages.EachNotAllowed); } expect('('); if (match(';')) { lex(); } else { if (matchKeyword('var') || matchKeyword('let') || matchKeyword('const')) { state.allowIn = false; init = parseForVariableDeclaration(); state.allowIn = true; if (init.declarations.length === 1) { if (matchKeyword('in') || matchContextualKeyword('of')) { operator = lookahead; if (!((operator.value === 'in' || init.kind !== 'var') && init.declarations[0].init)) { lex(); left = init; right = parseExpression(); init = null; } } } } else { state.allowIn = false; init = parseExpression(); state.allowIn = true; if (matchContextualKeyword('of')) { operator = lex(); left = init; right = parseExpression(); init = null; } else if (matchKeyword('in')) { // LeftHandSideExpression if (!isAssignableLeftHandSide(init)) { throwError({}, Messages.InvalidLHSInForIn); } operator = lex(); left = init; right = parseExpression(); init = null; } } if (typeof left === 'undefined') { expect(';'); } } if (typeof left === 'undefined') { if (!match(';')) { test = parseExpression(); } expect(';'); if (!match(')')) { update = parseExpression(); } } expect(')'); oldInIteration = state.inIteration; state.inIteration = true; if (!(opts !== undefined && opts.ignoreBody)) { body = parseStatement(); } state.inIteration = oldInIteration; if (typeof left === 'undefined') { return markerApply(marker, delegate.createForStatement(init, test, update, body)); } if (operator.value === 'in') { return markerApply(marker, delegate.createForInStatement(left, right, body)); } return markerApply(marker, delegate.createForOfStatement(left, right, body)); } // 12.7 The continue statement function parseContinueStatement() { var label = null, marker = markerCreate(); expectKeyword('continue'); // Optimize the most common form: 'continue;'. if (source.charCodeAt(index) === 59) { lex(); if (!state.inIteration) { throwError({}, Messages.IllegalContinue); } return markerApply(marker, delegate.createContinueStatement(null)); } if (peekLineTerminator()) { if (!state.inIteration) { throwError({}, Messages.IllegalContinue); } return markerApply(marker, delegate.createContinueStatement(null)); } if (lookahead.type === Token.Identifier) { label = parseVariableIdentifier(); if (!state.labelSet.has(label.name)) { throwError({}, Messages.UnknownLabel, label.name); } } consumeSemicolon(); if (label === null && !state.inIteration) { throwError({}, Messages.IllegalContinue); } return markerApply(marker, delegate.createContinueStatement(label)); } // 12.8 The break statement function parseBreakStatement() { var label = null, marker = markerCreate(); expectKeyword('break'); // Catch the very common case first: immediately a semicolon (char #59). if (source.charCodeAt(index) === 59) { lex(); if (!(state.inIteration || state.inSwitch)) { throwError({}, Messages.IllegalBreak); } return markerApply(marker, delegate.createBreakStatement(null)); } if (peekLineTerminator()) { if (!(state.inIteration || state.inSwitch)) { throwError({}, Messages.IllegalBreak); } return markerApply(marker, delegate.createBreakStatement(null)); } if (lookahead.type === Token.Identifier) { label = parseVariableIdentifier(); if (!state.labelSet.has(label.name)) { throwError({}, Messages.UnknownLabel, label.name); } } consumeSemicolon(); if (label === null && !(state.inIteration || state.inSwitch)) { throwError({}, Messages.IllegalBreak); } return markerApply(marker, delegate.createBreakStatement(label)); } // 12.9 The return statement function parseReturnStatement() { var argument = null, marker = markerCreate(); expectKeyword('return'); if (!state.inFunctionBody) { throwErrorTolerant({}, Messages.IllegalReturn); } // 'return' followed by a space and an identifier is very common. if (source.charCodeAt(index) === 32) { if (isIdentifierStart(source.charCodeAt(index + 1))) { argument = parseExpression(); consumeSemicolon(); return markerApply(marker, delegate.createReturnStatement(argument)); } } if (peekLineTerminator()) { return markerApply(marker, delegate.createReturnStatement(null)); } if (!match(';')) { if (!match('}') && lookahead.type !== Token.EOF) { argument = parseExpression(); } } consumeSemicolon(); return markerApply(marker, delegate.createReturnStatement(argument)); } // 12.10 The with statement function parseWithStatement() { var object, body, marker = markerCreate(); if (strict) { throwErrorTolerant({}, Messages.StrictModeWith); } expectKeyword('with'); expect('('); object = parseExpression(); expect(')'); body = parseStatement(); return markerApply(marker, delegate.createWithStatement(object, body)); } // 12.10 The swith statement function parseSwitchCase() { var test, consequent = [], sourceElement, marker = markerCreate(); if (matchKeyword('default')) { lex(); test = null; } else { expectKeyword('case'); test = parseExpression(); } expect(':'); while (index < length) { if (match('}') || matchKeyword('default') || matchKeyword('case')) { break; } sourceElement = parseSourceElement(); if (typeof sourceElement === 'undefined') { break; } consequent.push(sourceElement); } return markerApply(marker, delegate.createSwitchCase(test, consequent)); } function parseSwitchStatement() { var discriminant, cases, clause, oldInSwitch, defaultFound, marker = markerCreate(); expectKeyword('switch'); expect('('); discriminant = parseExpression(); expect(')'); expect('{'); cases = []; if (match('}')) { lex(); return markerApply(marker, delegate.createSwitchStatement(discriminant, cases)); } oldInSwitch = state.inSwitch; state.inSwitch = true; defaultFound = false; while (index < length) { if (match('}')) { break; } clause = parseSwitchCase(); if (clause.test === null) { if (defaultFound) { throwError({}, Messages.MultipleDefaultsInSwitch); } defaultFound = true; } cases.push(clause); } state.inSwitch = oldInSwitch; expect('}'); return markerApply(marker, delegate.createSwitchStatement(discriminant, cases)); } // 12.13 The throw statement function parseThrowStatement() { var argument, marker = markerCreate(); expectKeyword('throw'); if (peekLineTerminator()) { throwError({}, Messages.NewlineAfterThrow); } argument = parseExpression(); consumeSemicolon(); return markerApply(marker, delegate.createThrowStatement(argument)); } // 12.14 The try statement function parseCatchClause() { var param, body, marker = markerCreate(); expectKeyword('catch'); expect('('); if (match(')')) { throwUnexpected(lookahead); } param = parseExpression(); // 12.14.1 if (strict && param.type === Syntax.Identifier && isRestrictedWord(param.name)) { throwErrorTolerant({}, Messages.StrictCatchVariable); } expect(')'); body = parseBlock(); return markerApply(marker, delegate.createCatchClause(param, body)); } function parseTryStatement() { var block, handlers = [], finalizer = null, marker = markerCreate(); expectKeyword('try'); block = parseBlock(); if (matchKeyword('catch')) { handlers.push(parseCatchClause()); } if (matchKeyword('finally')) { lex(); finalizer = parseBlock(); } if (handlers.length === 0 && !finalizer) { throwError({}, Messages.NoCatchOrFinally); } return markerApply(marker, delegate.createTryStatement(block, [], handlers, finalizer)); } // 12.15 The debugger statement function parseDebuggerStatement() { var marker = markerCreate(); expectKeyword('debugger'); consumeSemicolon(); return markerApply(marker, delegate.createDebuggerStatement()); } // 12 Statements function parseStatement() { var type = lookahead.type, marker, expr, labeledBody; if (type === Token.EOF) { throwUnexpected(lookahead); } if (type === Token.Punctuator) { switch (lookahead.value) { case ';': return parseEmptyStatement(); case '{': return parseBlock(); case '(': return parseExpressionStatement(); default: break; } } if (type === Token.Keyword) { switch (lookahead.value) { case 'break': return parseBreakStatement(); case 'continue': return parseContinueStatement(); case 'debugger': return parseDebuggerStatement(); case 'do': return parseDoWhileStatement(); case 'for': return parseForStatement(); case 'function': return parseFunctionDeclaration(); case 'class': return parseClassDeclaration(); case 'if': return parseIfStatement(); case 'return': return parseReturnStatement(); case 'switch': return parseSwitchStatement(); case 'throw': return parseThrowStatement(); case 'try': return parseTryStatement(); case 'var': return parseVariableStatement(); case 'while': return parseWhileStatement(); case 'with': return parseWithStatement(); default: break; } } if (matchAsyncFuncExprOrDecl()) { return parseFunctionDeclaration(); } marker = markerCreate(); expr = parseExpression(); // 12.12 Labelled Statements if ((expr.type === Syntax.Identifier) && match(':')) { lex(); if (state.labelSet.has(expr.name)) { throwError({}, Messages.Redeclaration, 'Label', expr.name); } state.labelSet.set(expr.name, true); labeledBody = parseStatement(); state.labelSet["delete"](expr.name); return markerApply(marker, delegate.createLabeledStatement(expr, labeledBody)); } consumeSemicolon(); return markerApply(marker, delegate.createExpressionStatement(expr)); } // 13 Function Definition function parseConciseBody() { if (match('{')) { return parseFunctionSourceElements(); } return parseAssignmentExpression(); } function parseFunctionSourceElements() { var sourceElement, sourceElements = [], token, directive, firstRestricted, oldLabelSet, oldInIteration, oldInSwitch, oldInFunctionBody, oldParenthesizedCount, marker = markerCreate(); expect('{'); while (index < length) { if (lookahead.type !== Token.StringLiteral) { break; } token = lookahead; sourceElement = parseSourceElement(); sourceElements.push(sourceElement); if (sourceElement.expression.type !== Syntax.Literal) { // this is not directive break; } directive = source.slice(token.range[0] + 1, token.range[1] - 1); if (directive === 'use strict') { strict = true; if (firstRestricted) { throwErrorTolerant(firstRestricted, Messages.StrictOctalLiteral); } } else { if (!firstRestricted && token.octal) { firstRestricted = token; } } } oldLabelSet = state.labelSet; oldInIteration = state.inIteration; oldInSwitch = state.inSwitch; oldInFunctionBody = state.inFunctionBody; oldParenthesizedCount = state.parenthesizedCount; state.labelSet = new StringMap(); state.inIteration = false; state.inSwitch = false; state.inFunctionBody = true; state.parenthesizedCount = 0; while (index < length) { if (match('}')) { break; } sourceElement = parseSourceElement(); if (typeof sourceElement === 'undefined') { break; } sourceElements.push(sourceElement); } expect('}'); state.labelSet = oldLabelSet; state.inIteration = oldInIteration; state.inSwitch = oldInSwitch; state.inFunctionBody = oldInFunctionBody; state.parenthesizedCount = oldParenthesizedCount; return markerApply(marker, delegate.createBlockStatement(sourceElements)); } function validateParam(options, param, name) { if (strict) { if (isRestrictedWord(name)) { options.stricted = param; options.message = Messages.StrictParamName; } if (options.paramSet.has(name)) { options.stricted = param; options.message = Messages.StrictParamDupe; } } else if (!options.firstRestricted) { if (isRestrictedWord(name)) { options.firstRestricted = param; options.message = Messages.StrictParamName; } else if (isStrictModeReservedWord(name)) { options.firstRestricted = param; options.message = Messages.StrictReservedWord; } else if (options.paramSet.has(name)) { options.firstRestricted = param; options.message = Messages.StrictParamDupe; } } options.paramSet.set(name, true); } function parseParam(options) { var marker, token, rest, param, def; token = lookahead; if (token.value === '...') { token = lex(); rest = true; } if (match('[')) { marker = markerCreate(); param = parseArrayInitialiser(); reinterpretAsDestructuredParameter(options, param); if (match(':')) { param.typeAnnotation = parseTypeAnnotation(); markerApply(marker, param); } } else if (match('{')) { marker = markerCreate(); if (rest) { throwError({}, Messages.ObjectPatternAsRestParameter); } param = parseObjectInitialiser(); reinterpretAsDestructuredParameter(options, param); if (match(':')) { param.typeAnnotation = parseTypeAnnotation(); markerApply(marker, param); } } else { param = rest ? parseTypeAnnotatableIdentifier( false, /* requireTypeAnnotation */ false /* canBeOptionalParam */ ) : parseTypeAnnotatableIdentifier( false, /* requireTypeAnnotation */ true /* canBeOptionalParam */ ); validateParam(options, token, token.value); } if (match('=')) { if (rest) { throwErrorTolerant(lookahead, Messages.DefaultRestParameter); } lex(); def = parseAssignmentExpression(); ++options.defaultCount; } if (rest) { if (!match(')')) { throwError({}, Messages.ParameterAfterRestParameter); } options.rest = param; return false; } options.params.push(param); options.defaults.push(def); return !match(')'); } function parseParams(firstRestricted) { var options, marker = markerCreate(); options = { params: [], defaultCount: 0, defaults: [], rest: null, firstRestricted: firstRestricted }; expect('('); if (!match(')')) { options.paramSet = new StringMap(); while (index < length) { if (!parseParam(options)) { break; } expect(','); } } expect(')'); if (options.defaultCount === 0) { options.defaults = []; } if (match(':')) { options.returnType = parseTypeAnnotation(); } return markerApply(marker, options); } function parseFunctionDeclaration() { var id, body, token, tmp, firstRestricted, message, generator, isAsync, previousStrict, previousYieldAllowed, previousAwaitAllowed, marker = markerCreate(), typeParameters; isAsync = false; if (matchAsync()) { lex(); isAsync = true; } expectKeyword('function'); generator = false; if (match('*')) { lex(); generator = true; } token = lookahead; id = parseVariableIdentifier(); if (match('<')) { typeParameters = parseTypeParameterDeclaration(); } if (strict) { if (isRestrictedWord(token.value)) { throwErrorTolerant(token, Messages.StrictFunctionName); } } else { if (isRestrictedWord(token.value)) { firstRestricted = token; message = Messages.StrictFunctionName; } else if (isStrictModeReservedWord(token.value)) { firstRestricted = token; message = Messages.StrictReservedWord; } } tmp = parseParams(firstRestricted); firstRestricted = tmp.firstRestricted; if (tmp.message) { message = tmp.message; } previousStrict = strict; previousYieldAllowed = state.yieldAllowed; state.yieldAllowed = generator; previousAwaitAllowed = state.awaitAllowed; state.awaitAllowed = isAsync; body = parseFunctionSourceElements(); if (strict && firstRestricted) { throwError(firstRestricted, message); } if (strict && tmp.stricted) { throwErrorTolerant(tmp.stricted, message); } strict = previousStrict; state.yieldAllowed = previousYieldAllowed; state.awaitAllowed = previousAwaitAllowed; return markerApply( marker, delegate.createFunctionDeclaration( id, tmp.params, tmp.defaults, body, tmp.rest, generator, false, isAsync, tmp.returnType, typeParameters ) ); } function parseFunctionExpression() { var token, id = null, firstRestricted, message, tmp, body, generator, isAsync, previousStrict, previousYieldAllowed, previousAwaitAllowed, marker = markerCreate(), typeParameters; isAsync = false; if (matchAsync()) { lex(); isAsync = true; } expectKeyword('function'); generator = false; if (match('*')) { lex(); generator = true; } if (!match('(')) { if (!match('<')) { token = lookahead; id = parseVariableIdentifier(); if (strict) { if (isRestrictedWord(token.value)) { throwErrorTolerant(token, Messages.StrictFunctionName); } } else { if (isRestrictedWord(token.value)) { firstRestricted = token; message = Messages.StrictFunctionName; } else if (isStrictModeReservedWord(token.value)) { firstRestricted = token; message = Messages.StrictReservedWord; } } } if (match('<')) { typeParameters = parseTypeParameterDeclaration(); } } tmp = parseParams(firstRestricted); firstRestricted = tmp.firstRestricted; if (tmp.message) { message = tmp.message; } previousStrict = strict; previousYieldAllowed = state.yieldAllowed; state.yieldAllowed = generator; previousAwaitAllowed = state.awaitAllowed; state.awaitAllowed = isAsync; body = parseFunctionSourceElements(); if (strict && firstRestricted) { throwError(firstRestricted, message); } if (strict && tmp.stricted) { throwErrorTolerant(tmp.stricted, message); } strict = previousStrict; state.yieldAllowed = previousYieldAllowed; state.awaitAllowed = previousAwaitAllowed; return markerApply( marker, delegate.createFunctionExpression( id, tmp.params, tmp.defaults, body, tmp.rest, generator, false, isAsync, tmp.returnType, typeParameters ) ); } function parseYieldExpression() { var delegateFlag, expr, marker = markerCreate(); expectKeyword('yield', !strict); delegateFlag = false; if (match('*')) { lex(); delegateFlag = true; } expr = parseAssignmentExpression(); return markerApply(marker, delegate.createYieldExpression(expr, delegateFlag)); } function parseAwaitExpression() { var expr, marker = markerCreate(); expectContextualKeyword('await'); expr = parseAssignmentExpression(); return markerApply(marker, delegate.createAwaitExpression(expr)); } // 14 Functions and classes // 14.1 Functions is defined above (13 in ES5) // 14.2 Arrow Functions Definitions is defined in (7.3 assignments) // 14.3 Method Definitions // 14.3.7 function specialMethod(methodDefinition) { return methodDefinition.kind === 'get' || methodDefinition.kind === 'set' || methodDefinition.value.generator; } function parseMethodDefinition(key, isStatic, generator, computed) { var token, param, propType, isAsync, typeParameters, tokenValue, returnType; propType = isStatic ? ClassPropertyType["static"] : ClassPropertyType.prototype; if (generator) { return delegate.createMethodDefinition( propType, '', key, parsePropertyMethodFunction({ generator: true }), computed ); } tokenValue = key.type === 'Identifier' && key.name; if (tokenValue === 'get' && !match('(')) { key = parseObjectPropertyKey(); expect('('); expect(')'); if (match(':')) { returnType = parseTypeAnnotation(); } return delegate.createMethodDefinition( propType, 'get', key, parsePropertyFunction({ generator: false, returnType: returnType }), computed ); } if (tokenValue === 'set' && !match('(')) { key = parseObjectPropertyKey(); expect('('); token = lookahead; param = [ parseTypeAnnotatableIdentifier() ]; expect(')'); if (match(':')) { returnType = parseTypeAnnotation(); } return delegate.createMethodDefinition( propType, 'set', key, parsePropertyFunction({ params: param, generator: false, name: token, returnType: returnType }), computed ); } if (match('<')) { typeParameters = parseTypeParameterDeclaration(); } isAsync = tokenValue === 'async' && !match('('); if (isAsync) { key = parseObjectPropertyKey(); } return delegate.createMethodDefinition( propType, '', key, parsePropertyMethodFunction({ generator: false, async: isAsync, typeParameters: typeParameters }), computed ); } function parseClassProperty(key, computed, isStatic) { var typeAnnotation; typeAnnotation = parseTypeAnnotation(); expect(';'); return delegate.createClassProperty( key, typeAnnotation, computed, isStatic ); } function parseClassElement() { var computed = false, generator = false, key, marker = markerCreate(), isStatic = false, possiblyOpenBracketToken; if (match(';')) { lex(); return undefined; } if (lookahead.value === 'static') { lex(); isStatic = true; } if (match('*')) { lex(); generator = true; } possiblyOpenBracketToken = lookahead; if (matchContextualKeyword('get') || matchContextualKeyword('set')) { possiblyOpenBracketToken = lookahead2(); } if (possiblyOpenBracketToken.type === Token.Punctuator && possiblyOpenBracketToken.value === '[') { computed = true; } key = parseObjectPropertyKey(); if (!generator && lookahead.value === ':') { return markerApply(marker, parseClassProperty(key, computed, isStatic)); } return markerApply(marker, parseMethodDefinition( key, isStatic, generator, computed )); } function parseClassBody() { var classElement, classElements = [], existingProps = {}, marker = markerCreate(), propName, propType; existingProps[ClassPropertyType["static"]] = new StringMap(); existingProps[ClassPropertyType.prototype] = new StringMap(); expect('{'); while (index < length) { if (match('}')) { break; } classElement = parseClassElement(existingProps); if (typeof classElement !== 'undefined') { classElements.push(classElement); propName = !classElement.computed && getFieldName(classElement.key); if (propName !== false) { propType = classElement["static"] ? ClassPropertyType["static"] : ClassPropertyType.prototype; if (classElement.type === Syntax.MethodDefinition) { if (propName === 'constructor' && !classElement["static"]) { if (specialMethod(classElement)) { throwError(classElement, Messages.IllegalClassConstructorProperty); } if (existingProps[ClassPropertyType.prototype].has('constructor')) { throwError(classElement.key, Messages.IllegalDuplicateClassProperty); } } existingProps[propType].set(propName, true); } } } } expect('}'); return markerApply(marker, delegate.createClassBody(classElements)); } function parseClassImplements() { var id, implemented = [], marker, typeParameters; if (strict) { expectKeyword('implements'); } else { expectContextualKeyword('implements'); } while (index < length) { marker = markerCreate(); id = parseVariableIdentifier(); if (match('<')) { typeParameters = parseTypeParameterInstantiation(); } else { typeParameters = null; } implemented.push(markerApply(marker, delegate.createClassImplements( id, typeParameters ))); if (!match(',')) { break; } expect(','); } return implemented; } function parseClassExpression() { var id, implemented, previousYieldAllowed, superClass = null, superTypeParameters, marker = markerCreate(), typeParameters, matchImplements; expectKeyword('class'); matchImplements = strict ? matchKeyword('implements') : matchContextualKeyword('implements'); if (!matchKeyword('extends') && !matchImplements && !match('{')) { id = parseVariableIdentifier(); } if (match('<')) { typeParameters = parseTypeParameterDeclaration(); } if (matchKeyword('extends')) { expectKeyword('extends'); previousYieldAllowed = state.yieldAllowed; state.yieldAllowed = false; superClass = parseLeftHandSideExpressionAllowCall(); if (match('<')) { superTypeParameters = parseTypeParameterInstantiation(); } state.yieldAllowed = previousYieldAllowed; } if (strict ? matchKeyword('implements') : matchContextualKeyword('implements')) { implemented = parseClassImplements(); } return markerApply(marker, delegate.createClassExpression( id, superClass, parseClassBody(), typeParameters, superTypeParameters, implemented )); } function parseClassDeclaration() { var id, implemented, previousYieldAllowed, superClass = null, superTypeParameters, marker = markerCreate(), typeParameters; expectKeyword('class'); id = parseVariableIdentifier(); if (match('<')) { typeParameters = parseTypeParameterDeclaration(); } if (matchKeyword('extends')) { expectKeyword('extends'); previousYieldAllowed = state.yieldAllowed; state.yieldAllowed = false; superClass = parseLeftHandSideExpressionAllowCall(); if (match('<')) { superTypeParameters = parseTypeParameterInstantiation(); } state.yieldAllowed = previousYieldAllowed; } if (strict ? matchKeyword('implements') : matchContextualKeyword('implements')) { implemented = parseClassImplements(); } return markerApply(marker, delegate.createClassDeclaration( id, superClass, parseClassBody(), typeParameters, superTypeParameters, implemented )); } // 15 Program function parseSourceElement() { var token; if (lookahead.type === Token.Keyword) { switch (lookahead.value) { case 'const': case 'let': return parseConstLetDeclaration(lookahead.value); case 'function': return parseFunctionDeclaration(); case 'export': throwErrorTolerant({}, Messages.IllegalExportDeclaration); return parseExportDeclaration(); case 'import': throwErrorTolerant({}, Messages.IllegalImportDeclaration); return parseImportDeclaration(); case 'interface': if (lookahead2().type === Token.Identifier) { return parseInterface(); } return parseStatement(); default: return parseStatement(); } } if (matchContextualKeyword('type') && lookahead2().type === Token.Identifier) { return parseTypeAlias(); } if (matchContextualKeyword('interface') && lookahead2().type === Token.Identifier) { return parseInterface(); } if (matchContextualKeyword('declare')) { token = lookahead2(); if (token.type === Token.Keyword) { switch (token.value) { case 'class': return parseDeclareClass(); case 'function': return parseDeclareFunction(); case 'var': return parseDeclareVariable(); } } else if (token.type === Token.Identifier && token.value === 'module') { return parseDeclareModule(); } } if (lookahead.type !== Token.EOF) { return parseStatement(); } } function parseProgramElement() { var isModule = extra.sourceType === 'module' || extra.sourceType === 'nonStrictModule'; if (isModule && lookahead.type === Token.Keyword) { switch (lookahead.value) { case 'export': return parseExportDeclaration(); case 'import': return parseImportDeclaration(); } } return parseSourceElement(); } function parseProgramElements() { var sourceElement, sourceElements = [], token, directive, firstRestricted; while (index < length) { token = lookahead; if (token.type !== Token.StringLiteral) { break; } sourceElement = parseProgramElement(); sourceElements.push(sourceElement); if (sourceElement.expression.type !== Syntax.Literal) { // this is not directive break; } directive = source.slice(token.range[0] + 1, token.range[1] - 1); if (directive === 'use strict') { strict = true; if (firstRestricted) { throwErrorTolerant(firstRestricted, Messages.StrictOctalLiteral); } } else { if (!firstRestricted && token.octal) { firstRestricted = token; } } } while (index < length) { sourceElement = parseProgramElement(); if (typeof sourceElement === 'undefined') { break; } sourceElements.push(sourceElement); } return sourceElements; } function parseProgram() { var body, marker = markerCreate(); strict = extra.sourceType === 'module'; peek(); body = parseProgramElements(); return markerApply(marker, delegate.createProgram(body)); } // 16 JSX XHTMLEntities = { quot: '\u0022', amp: '&', apos: '\u0027', lt: '<', gt: '>', nbsp: '\u00A0', iexcl: '\u00A1', cent: '\u00A2', pound: '\u00A3', curren: '\u00A4', yen: '\u00A5', brvbar: '\u00A6', sect: '\u00A7', uml: '\u00A8', copy: '\u00A9', ordf: '\u00AA', laquo: '\u00AB', not: '\u00AC', shy: '\u00AD', reg: '\u00AE', macr: '\u00AF', deg: '\u00B0', plusmn: '\u00B1', sup2: '\u00B2', sup3: '\u00B3', acute: '\u00B4', micro: '\u00B5', para: '\u00B6', middot: '\u00B7', cedil: '\u00B8', sup1: '\u00B9', ordm: '\u00BA', raquo: '\u00BB', frac14: '\u00BC', frac12: '\u00BD', frac34: '\u00BE', iquest: '\u00BF', Agrave: '\u00C0', Aacute: '\u00C1', Acirc: '\u00C2', Atilde: '\u00C3', Auml: '\u00C4', Aring: '\u00C5', AElig: '\u00C6', Ccedil: '\u00C7', Egrave: '\u00C8', Eacute: '\u00C9', Ecirc: '\u00CA', Euml: '\u00CB', Igrave: '\u00CC', Iacute: '\u00CD', Icirc: '\u00CE', Iuml: '\u00CF', ETH: '\u00D0', Ntilde: '\u00D1', Ograve: '\u00D2', Oacute: '\u00D3', Ocirc: '\u00D4', Otilde: '\u00D5', Ouml: '\u00D6', times: '\u00D7', Oslash: '\u00D8', Ugrave: '\u00D9', Uacute: '\u00DA', Ucirc: '\u00DB', Uuml: '\u00DC', Yacute: '\u00DD', THORN: '\u00DE', szlig: '\u00DF', agrave: '\u00E0', aacute: '\u00E1', acirc: '\u00E2', atilde: '\u00E3', auml: '\u00E4', aring: '\u00E5', aelig: '\u00E6', ccedil: '\u00E7', egrave: '\u00E8', eacute: '\u00E9', ecirc: '\u00EA', euml: '\u00EB', igrave: '\u00EC', iacute: '\u00ED', icirc: '\u00EE', iuml: '\u00EF', eth: '\u00F0', ntilde: '\u00F1', ograve: '\u00F2', oacute: '\u00F3', ocirc: '\u00F4', otilde: '\u00F5', ouml: '\u00F6', divide: '\u00F7', oslash: '\u00F8', ugrave: '\u00F9', uacute: '\u00FA', ucirc: '\u00FB', uuml: '\u00FC', yacute: '\u00FD', thorn: '\u00FE', yuml: '\u00FF', OElig: '\u0152', oelig: '\u0153', Scaron: '\u0160', scaron: '\u0161', Yuml: '\u0178', fnof: '\u0192', circ: '\u02C6', tilde: '\u02DC', Alpha: '\u0391', Beta: '\u0392', Gamma: '\u0393', Delta: '\u0394', Epsilon: '\u0395', Zeta: '\u0396', Eta: '\u0397', Theta: '\u0398', Iota: '\u0399', Kappa: '\u039A', Lambda: '\u039B', Mu: '\u039C', Nu: '\u039D', Xi: '\u039E', Omicron: '\u039F', Pi: '\u03A0', Rho: '\u03A1', Sigma: '\u03A3', Tau: '\u03A4', Upsilon: '\u03A5', Phi: '\u03A6', Chi: '\u03A7', Psi: '\u03A8', Omega: '\u03A9', alpha: '\u03B1', beta: '\u03B2', gamma: '\u03B3', delta: '\u03B4', epsilon: '\u03B5', zeta: '\u03B6', eta: '\u03B7', theta: '\u03B8', iota: '\u03B9', kappa: '\u03BA', lambda: '\u03BB', mu: '\u03BC', nu: '\u03BD', xi: '\u03BE', omicron: '\u03BF', pi: '\u03C0', rho: '\u03C1', sigmaf: '\u03C2', sigma: '\u03C3', tau: '\u03C4', upsilon: '\u03C5', phi: '\u03C6', chi: '\u03C7', psi: '\u03C8', omega: '\u03C9', thetasym: '\u03D1', upsih: '\u03D2', piv: '\u03D6', ensp: '\u2002', emsp: '\u2003', thinsp: '\u2009', zwnj: '\u200C', zwj: '\u200D', lrm: '\u200E', rlm: '\u200F', ndash: '\u2013', mdash: '\u2014', lsquo: '\u2018', rsquo: '\u2019', sbquo: '\u201A', ldquo: '\u201C', rdquo: '\u201D', bdquo: '\u201E', dagger: '\u2020', Dagger: '\u2021', bull: '\u2022', hellip: '\u2026', permil: '\u2030', prime: '\u2032', Prime: '\u2033', lsaquo: '\u2039', rsaquo: '\u203A', oline: '\u203E', frasl: '\u2044', euro: '\u20AC', image: '\u2111', weierp: '\u2118', real: '\u211C', trade: '\u2122', alefsym: '\u2135', larr: '\u2190', uarr: '\u2191', rarr: '\u2192', darr: '\u2193', harr: '\u2194', crarr: '\u21B5', lArr: '\u21D0', uArr: '\u21D1', rArr: '\u21D2', dArr: '\u21D3', hArr: '\u21D4', forall: '\u2200', part: '\u2202', exist: '\u2203', empty: '\u2205', nabla: '\u2207', isin: '\u2208', notin: '\u2209', ni: '\u220B', prod: '\u220F', sum: '\u2211', minus: '\u2212', lowast: '\u2217', radic: '\u221A', prop: '\u221D', infin: '\u221E', ang: '\u2220', and: '\u2227', or: '\u2228', cap: '\u2229', cup: '\u222A', 'int': '\u222B', there4: '\u2234', sim: '\u223C', cong: '\u2245', asymp: '\u2248', ne: '\u2260', equiv: '\u2261', le: '\u2264', ge: '\u2265', sub: '\u2282', sup: '\u2283', nsub: '\u2284', sube: '\u2286', supe: '\u2287', oplus: '\u2295', otimes: '\u2297', perp: '\u22A5', sdot: '\u22C5', lceil: '\u2308', rceil: '\u2309', lfloor: '\u230A', rfloor: '\u230B', lang: '\u2329', rang: '\u232A', loz: '\u25CA', spades: '\u2660', clubs: '\u2663', hearts: '\u2665', diams: '\u2666' }; function getQualifiedJSXName(object) { if (object.type === Syntax.JSXIdentifier) { return object.name; } if (object.type === Syntax.JSXNamespacedName) { return object.namespace.name + ':' + object.name.name; } /* istanbul ignore else */ if (object.type === Syntax.JSXMemberExpression) { return ( getQualifiedJSXName(object.object) + '.' + getQualifiedJSXName(object.property) ); } /* istanbul ignore next */ throwUnexpected(object); } function isJSXIdentifierStart(ch) { // exclude backslash (\) return (ch !== 92) && isIdentifierStart(ch); } function isJSXIdentifierPart(ch) { // exclude backslash (\) and add hyphen (-) return (ch !== 92) && (ch === 45 || isIdentifierPart(ch)); } function scanJSXIdentifier() { var ch, start, value = ''; start = index; while (index < length) { ch = source.charCodeAt(index); if (!isJSXIdentifierPart(ch)) { break; } value += source[index++]; } return { type: Token.JSXIdentifier, value: value, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } function scanJSXEntity() { var ch, str = '', start = index, count = 0, code; ch = source[index]; assert(ch === '&', 'Entity must start with an ampersand'); index++; while (index < length && count++ < 10) { ch = source[index++]; if (ch === ';') { break; } str += ch; } // Well-formed entity (ending was found). if (ch === ';') { // Numeric entity. if (str[0] === '#') { if (str[1] === 'x') { code = +('0' + str.substr(1)); } else { // Removing leading zeros in order to avoid treating as octal in old browsers. code = +str.substr(1).replace(Regex.LeadingZeros, ''); } if (!isNaN(code)) { return String.fromCharCode(code); } /* istanbul ignore else */ } else if (XHTMLEntities[str]) { return XHTMLEntities[str]; } } // Treat non-entity sequences as regular text. index = start + 1; return '&'; } function scanJSXText(stopChars) { var ch, str = '', start; start = index; while (index < length) { ch = source[index]; if (stopChars.indexOf(ch) !== -1) { break; } if (ch === '&') { str += scanJSXEntity(); } else { index++; if (ch === '\r' && source[index] === '\n') { str += ch; ch = source[index]; index++; } if (isLineTerminator(ch.charCodeAt(0))) { ++lineNumber; lineStart = index; } str += ch; } } return { type: Token.JSXText, value: str, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } function scanJSXStringLiteral() { var innerToken, quote, start; quote = source[index]; assert((quote === '\'' || quote === '"'), 'String literal must starts with a quote'); start = index; ++index; innerToken = scanJSXText([quote]); if (quote !== source[index]) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } ++index; innerToken.range = [start, index]; return innerToken; } /** * Between JSX opening and closing tags (e.g. <foo>HERE</foo>), anything that * is not another JSX tag and is not an expression wrapped by {} is text. */ function advanceJSXChild() { var ch = source.charCodeAt(index); // '<' 60, '>' 62, '{' 123, '}' 125 if (ch !== 60 && ch !== 62 && ch !== 123 && ch !== 125) { return scanJSXText(['<', '>', '{', '}']); } return scanPunctuator(); } function parseJSXIdentifier() { var token, marker = markerCreate(); if (lookahead.type !== Token.JSXIdentifier) { throwUnexpected(lookahead); } token = lex(); return markerApply(marker, delegate.createJSXIdentifier(token.value)); } function parseJSXNamespacedName() { var namespace, name, marker = markerCreate(); namespace = parseJSXIdentifier(); expect(':'); name = parseJSXIdentifier(); return markerApply(marker, delegate.createJSXNamespacedName(namespace, name)); } function parseJSXMemberExpression() { var marker = markerCreate(), expr = parseJSXIdentifier(); while (match('.')) { lex(); expr = markerApply(marker, delegate.createJSXMemberExpression(expr, parseJSXIdentifier())); } return expr; } function parseJSXElementName() { if (lookahead2().value === ':') { return parseJSXNamespacedName(); } if (lookahead2().value === '.') { return parseJSXMemberExpression(); } return parseJSXIdentifier(); } function parseJSXAttributeName() { if (lookahead2().value === ':') { return parseJSXNamespacedName(); } return parseJSXIdentifier(); } function parseJSXAttributeValue() { var value, marker; if (match('{')) { value = parseJSXExpressionContainer(); if (value.expression.type === Syntax.JSXEmptyExpression) { throwError( value, 'JSX attributes must only be assigned a non-empty ' + 'expression' ); } } else if (match('<')) { value = parseJSXElement(); } else if (lookahead.type === Token.JSXText) { marker = markerCreate(); value = markerApply(marker, delegate.createLiteral(lex())); } else { throwError({}, Messages.InvalidJSXAttributeValue); } return value; } function parseJSXEmptyExpression() { var marker = markerCreatePreserveWhitespace(); while (source.charAt(index) !== '}') { index++; } return markerApply(marker, delegate.createJSXEmptyExpression()); } function parseJSXExpressionContainer() { var expression, origInJSXChild, origInJSXTag, marker = markerCreate(); origInJSXChild = state.inJSXChild; origInJSXTag = state.inJSXTag; state.inJSXChild = false; state.inJSXTag = false; expect('{'); if (match('}')) { expression = parseJSXEmptyExpression(); } else { expression = parseExpression(); } state.inJSXChild = origInJSXChild; state.inJSXTag = origInJSXTag; expect('}'); return markerApply(marker, delegate.createJSXExpressionContainer(expression)); } function parseJSXSpreadAttribute() { var expression, origInJSXChild, origInJSXTag, marker = markerCreate(); origInJSXChild = state.inJSXChild; origInJSXTag = state.inJSXTag; state.inJSXChild = false; state.inJSXTag = false; expect('{'); expect('...'); expression = parseAssignmentExpression(); state.inJSXChild = origInJSXChild; state.inJSXTag = origInJSXTag; expect('}'); return markerApply(marker, delegate.createJSXSpreadAttribute(expression)); } function parseJSXAttribute() { var name, marker; if (match('{')) { return parseJSXSpreadAttribute(); } marker = markerCreate(); name = parseJSXAttributeName(); // HTML empty attribute if (match('=')) { lex(); return markerApply(marker, delegate.createJSXAttribute(name, parseJSXAttributeValue())); } return markerApply(marker, delegate.createJSXAttribute(name)); } function parseJSXChild() { var token, marker; if (match('{')) { token = parseJSXExpressionContainer(); } else if (lookahead.type === Token.JSXText) { marker = markerCreatePreserveWhitespace(); token = markerApply(marker, delegate.createLiteral(lex())); } else if (match('<')) { token = parseJSXElement(); } else { throwUnexpected(lookahead); } return token; } function parseJSXClosingElement() { var name, origInJSXChild, origInJSXTag, marker = markerCreate(); origInJSXChild = state.inJSXChild; origInJSXTag = state.inJSXTag; state.inJSXChild = false; state.inJSXTag = true; expect('<'); expect('/'); name = parseJSXElementName(); // Because advance() (called by lex() called by expect()) expects there // to be a valid token after >, it needs to know whether to look for a // standard JS token or an JSX text node state.inJSXChild = origInJSXChild; state.inJSXTag = origInJSXTag; expect('>'); return markerApply(marker, delegate.createJSXClosingElement(name)); } function parseJSXOpeningElement() { var name, attributes = [], selfClosing = false, origInJSXChild, origInJSXTag, marker = markerCreate(); origInJSXChild = state.inJSXChild; origInJSXTag = state.inJSXTag; state.inJSXChild = false; state.inJSXTag = true; expect('<'); name = parseJSXElementName(); while (index < length && lookahead.value !== '/' && lookahead.value !== '>') { attributes.push(parseJSXAttribute()); } state.inJSXTag = origInJSXTag; if (lookahead.value === '/') { expect('/'); // Because advance() (called by lex() called by expect()) expects // there to be a valid token after >, it needs to know whether to // look for a standard JS token or an JSX text node state.inJSXChild = origInJSXChild; expect('>'); selfClosing = true; } else { state.inJSXChild = true; expect('>'); } return markerApply(marker, delegate.createJSXOpeningElement(name, attributes, selfClosing)); } function parseJSXElement() { var openingElement, closingElement = null, children = [], origInJSXChild, origInJSXTag, marker = markerCreate(); origInJSXChild = state.inJSXChild; origInJSXTag = state.inJSXTag; openingElement = parseJSXOpeningElement(); if (!openingElement.selfClosing) { while (index < length) { state.inJSXChild = false; // Call lookahead2() with inJSXChild = false because </ should not be considered in the child if (lookahead.value === '<' && lookahead2().value === '/') { break; } state.inJSXChild = true; children.push(parseJSXChild()); } state.inJSXChild = origInJSXChild; state.inJSXTag = origInJSXTag; closingElement = parseJSXClosingElement(); if (getQualifiedJSXName(closingElement.name) !== getQualifiedJSXName(openingElement.name)) { throwError({}, Messages.ExpectedJSXClosingTag, getQualifiedJSXName(openingElement.name)); } } // When (erroneously) writing two adjacent tags like // // var x = <div>one</div><div>two</div>; // // the default error message is a bit incomprehensible. Since it's // rarely (never?) useful to write a less-than sign after an JSX // element, we disallow it here in the parser in order to provide a // better error message. (In the rare case that the less-than operator // was intended, the left tag can be wrapped in parentheses.) if (!origInJSXChild && match('<')) { throwError(lookahead, Messages.AdjacentJSXElements); } return markerApply(marker, delegate.createJSXElement(openingElement, closingElement, children)); } function parseTypeAlias() { var id, marker = markerCreate(), typeParameters = null, right; expectContextualKeyword('type'); id = parseVariableIdentifier(); if (match('<')) { typeParameters = parseTypeParameterDeclaration(); } expect('='); right = parseType(); consumeSemicolon(); return markerApply(marker, delegate.createTypeAlias(id, typeParameters, right)); } function parseInterfaceExtends() { var marker = markerCreate(), id, typeParameters = null; id = parseVariableIdentifier(); if (match('<')) { typeParameters = parseTypeParameterInstantiation(); } return markerApply(marker, delegate.createInterfaceExtends( id, typeParameters )); } function parseInterfaceish(marker, allowStatic) { var body, bodyMarker, extended = [], id, typeParameters = null; id = parseVariableIdentifier(); if (match('<')) { typeParameters = parseTypeParameterDeclaration(); } if (matchKeyword('extends')) { expectKeyword('extends'); while (index < length) { extended.push(parseInterfaceExtends()); if (!match(',')) { break; } expect(','); } } bodyMarker = markerCreate(); body = markerApply(bodyMarker, parseObjectType(allowStatic)); return markerApply(marker, delegate.createInterface( id, typeParameters, body, extended )); } function parseInterface() { var marker = markerCreate(); if (strict) { expectKeyword('interface'); } else { expectContextualKeyword('interface'); } return parseInterfaceish(marker, /* allowStatic */false); } function parseDeclareClass() { var marker = markerCreate(), ret; expectContextualKeyword('declare'); expectKeyword('class'); ret = parseInterfaceish(marker, /* allowStatic */true); ret.type = Syntax.DeclareClass; return ret; } function parseDeclareFunction() { var id, idMarker, marker = markerCreate(), params, returnType, rest, tmp, typeParameters = null, value, valueMarker; expectContextualKeyword('declare'); expectKeyword('function'); idMarker = markerCreate(); id = parseVariableIdentifier(); valueMarker = markerCreate(); if (match('<')) { typeParameters = parseTypeParameterDeclaration(); } expect('('); tmp = parseFunctionTypeParams(); params = tmp.params; rest = tmp.rest; expect(')'); expect(':'); returnType = parseType(); value = markerApply(valueMarker, delegate.createFunctionTypeAnnotation( params, returnType, rest, typeParameters )); id.typeAnnotation = markerApply(valueMarker, delegate.createTypeAnnotation( value )); markerApply(idMarker, id); consumeSemicolon(); return markerApply(marker, delegate.createDeclareFunction( id )); } function parseDeclareVariable() { var id, marker = markerCreate(); expectContextualKeyword('declare'); expectKeyword('var'); id = parseTypeAnnotatableIdentifier(); consumeSemicolon(); return markerApply(marker, delegate.createDeclareVariable( id )); } function parseDeclareModule() { var body = [], bodyMarker, id, idMarker, marker = markerCreate(), token; expectContextualKeyword('declare'); expectContextualKeyword('module'); if (lookahead.type === Token.StringLiteral) { if (strict && lookahead.octal) { throwErrorTolerant(lookahead, Messages.StrictOctalLiteral); } idMarker = markerCreate(); id = markerApply(idMarker, delegate.createLiteral(lex())); } else { id = parseVariableIdentifier(); } bodyMarker = markerCreate(); expect('{'); while (index < length && !match('}')) { token = lookahead2(); switch (token.value) { case 'class': body.push(parseDeclareClass()); break; case 'function': body.push(parseDeclareFunction()); break; case 'var': body.push(parseDeclareVariable()); break; default: throwUnexpected(lookahead); } } expect('}'); return markerApply(marker, delegate.createDeclareModule( id, markerApply(bodyMarker, delegate.createBlockStatement(body)) )); } function collectToken() { var loc, token, range, value, entry; /* istanbul ignore else */ if (!state.inJSXChild) { skipComment(); } loc = { start: { line: lineNumber, column: index - lineStart } }; token = extra.advance(); loc.end = { line: lineNumber, column: index - lineStart }; if (token.type !== Token.EOF) { range = [token.range[0], token.range[1]]; value = source.slice(token.range[0], token.range[1]); entry = { type: TokenName[token.type], value: value, range: range, loc: loc }; if (token.regex) { entry.regex = { pattern: token.regex.pattern, flags: token.regex.flags }; } extra.tokens.push(entry); } return token; } function collectRegex() { var pos, loc, regex, token; skipComment(); pos = index; loc = { start: { line: lineNumber, column: index - lineStart } }; regex = extra.scanRegExp(); loc.end = { line: lineNumber, column: index - lineStart }; if (!extra.tokenize) { /* istanbul ignore next */ // Pop the previous token, which is likely '/' or '/=' if (extra.tokens.length > 0) { token = extra.tokens[extra.tokens.length - 1]; if (token.range[0] === pos && token.type === 'Punctuator') { if (token.value === '/' || token.value === '/=') { extra.tokens.pop(); } } } extra.tokens.push({ type: 'RegularExpression', value: regex.literal, regex: regex.regex, range: [pos, index], loc: loc }); } return regex; } function filterTokenLocation() { var i, entry, token, tokens = []; for (i = 0; i < extra.tokens.length; ++i) { entry = extra.tokens[i]; token = { type: entry.type, value: entry.value }; if (entry.regex) { token.regex = { pattern: entry.regex.pattern, flags: entry.regex.flags }; } if (extra.range) { token.range = entry.range; } if (extra.loc) { token.loc = entry.loc; } tokens.push(token); } extra.tokens = tokens; } function patch() { if (typeof extra.tokens !== 'undefined') { extra.advance = advance; extra.scanRegExp = scanRegExp; advance = collectToken; scanRegExp = collectRegex; } } function unpatch() { if (typeof extra.scanRegExp === 'function') { advance = extra.advance; scanRegExp = extra.scanRegExp; } } // This is used to modify the delegate. function extend(object, properties) { var entry, result = {}; for (entry in object) { /* istanbul ignore else */ if (object.hasOwnProperty(entry)) { result[entry] = object[entry]; } } for (entry in properties) { /* istanbul ignore else */ if (properties.hasOwnProperty(entry)) { result[entry] = properties[entry]; } } return result; } function tokenize(code, options) { var toString, token, tokens; toString = String; if (typeof code !== 'string' && !(code instanceof String)) { code = toString(code); } delegate = SyntaxTreeDelegate; source = code; index = 0; lineNumber = (source.length > 0) ? 1 : 0; lineStart = 0; length = source.length; lookahead = null; state = { allowKeyword: true, allowIn: true, labelSet: new StringMap(), inFunctionBody: false, inIteration: false, inSwitch: false, lastCommentStart: -1 }; extra = {}; // Options matching. options = options || {}; // Of course we collect tokens here. options.tokens = true; extra.tokens = []; extra.tokenize = true; // The following two fields are necessary to compute the Regex tokens. extra.openParenToken = -1; extra.openCurlyToken = -1; extra.range = (typeof options.range === 'boolean') && options.range; extra.loc = (typeof options.loc === 'boolean') && options.loc; if (typeof options.comment === 'boolean' && options.comment) { extra.comments = []; } if (typeof options.tolerant === 'boolean' && options.tolerant) { extra.errors = []; } patch(); try { peek(); if (lookahead.type === Token.EOF) { return extra.tokens; } token = lex(); while (lookahead.type !== Token.EOF) { try { token = lex(); } catch (lexError) { token = lookahead; if (extra.errors) { extra.errors.push(lexError); // We have to break on the first error // to avoid infinite loops. break; } else { throw lexError; } } } filterTokenLocation(); tokens = extra.tokens; if (typeof extra.comments !== 'undefined') { tokens.comments = extra.comments; } if (typeof extra.errors !== 'undefined') { tokens.errors = extra.errors; } } catch (e) { throw e; } finally { unpatch(); extra = {}; } return tokens; } function parse(code, options) { var program, toString; toString = String; if (typeof code !== 'string' && !(code instanceof String)) { code = toString(code); } delegate = SyntaxTreeDelegate; source = code; index = 0; lineNumber = (source.length > 0) ? 1 : 0; lineStart = 0; length = source.length; lookahead = null; state = { allowKeyword: false, allowIn: true, labelSet: new StringMap(), parenthesizedCount: 0, inFunctionBody: false, inIteration: false, inSwitch: false, inJSXChild: false, inJSXTag: false, inType: false, lastCommentStart: -1, yieldAllowed: false, awaitAllowed: false }; extra = {}; if (typeof options !== 'undefined') { extra.range = (typeof options.range === 'boolean') && options.range; extra.loc = (typeof options.loc === 'boolean') && options.loc; extra.attachComment = (typeof options.attachComment === 'boolean') && options.attachComment; if (extra.loc && options.source !== null && options.source !== undefined) { delegate = extend(delegate, { 'postProcess': function (node) { node.loc.source = toString(options.source); return node; } }); } extra.sourceType = options.sourceType; if (typeof options.tokens === 'boolean' && options.tokens) { extra.tokens = []; } if (typeof options.comment === 'boolean' && options.comment) { extra.comments = []; } if (typeof options.tolerant === 'boolean' && options.tolerant) { extra.errors = []; } if (extra.attachComment) { extra.range = true; extra.comments = []; extra.bottomRightStack = []; extra.trailingComments = []; extra.leadingComments = []; } } patch(); try { program = parseProgram(); if (typeof extra.comments !== 'undefined') { program.comments = extra.comments; } if (typeof extra.tokens !== 'undefined') { filterTokenLocation(); program.tokens = extra.tokens; } if (typeof extra.errors !== 'undefined') { program.errors = extra.errors; } } catch (e) { throw e; } finally { unpatch(); extra = {}; } return program; } // Sync with *.json manifests. exports.version = '13001.1.0-dev-harmony-fb'; exports.tokenize = tokenize; exports.parse = parse; // Deep copy. /* istanbul ignore next */ exports.Syntax = (function () { var name, types = {}; if (typeof Object.create === 'function') { types = Object.create(null); } for (name in Syntax) { if (Syntax.hasOwnProperty(name)) { types[name] = Syntax[name]; } } if (typeof Object.freeze === 'function') { Object.freeze(types); } return types; }()); })); /* vim: set sw=4 ts=4 et tw=80 : */ },{}],10:[function(_dereq_,module,exports){ var Base62 = (function (my) { my.chars = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"] my.encode = function(i){ if (i === 0) {return '0'} var s = '' while (i > 0) { s = this.chars[i % 62] + s i = Math.floor(i/62) } return s }; my.decode = function(a,b,c,d){ for ( b = c = ( a === (/\W|_|^$/.test(a += "") || a) ) - 1; d = a.charCodeAt(c++); ) b = b * 62 + d - [, 48, 29, 87][d >> 5]; return b }; return my; }({})); module.exports = Base62 },{}],11:[function(_dereq_,module,exports){ /* * Copyright 2009-2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE.txt or: * http://opensource.org/licenses/BSD-3-Clause */ exports.SourceMapGenerator = _dereq_('./source-map/source-map-generator').SourceMapGenerator; exports.SourceMapConsumer = _dereq_('./source-map/source-map-consumer').SourceMapConsumer; exports.SourceNode = _dereq_('./source-map/source-node').SourceNode; },{"./source-map/source-map-consumer":16,"./source-map/source-map-generator":17,"./source-map/source-node":18}],12:[function(_dereq_,module,exports){ /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ if (typeof define !== 'function') { var define = _dereq_('amdefine')(module, _dereq_); } define(function (_dereq_, exports, module) { var util = _dereq_('./util'); /** * A data structure which is a combination of an array and a set. Adding a new * member is O(1), testing for membership is O(1), and finding the index of an * element is O(1). Removing elements from the set is not supported. Only * strings are supported for membership. */ function ArraySet() { this._array = []; this._set = {}; } /** * Static method for creating ArraySet instances from an existing array. */ ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) { var set = new ArraySet(); for (var i = 0, len = aArray.length; i < len; i++) { set.add(aArray[i], aAllowDuplicates); } return set; }; /** * Add the given string to this set. * * @param String aStr */ ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) { var isDuplicate = this.has(aStr); var idx = this._array.length; if (!isDuplicate || aAllowDuplicates) { this._array.push(aStr); } if (!isDuplicate) { this._set[util.toSetString(aStr)] = idx; } }; /** * Is the given string a member of this set? * * @param String aStr */ ArraySet.prototype.has = function ArraySet_has(aStr) { return Object.prototype.hasOwnProperty.call(this._set, util.toSetString(aStr)); }; /** * What is the index of the given string in the array? * * @param String aStr */ ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) { if (this.has(aStr)) { return this._set[util.toSetString(aStr)]; } throw new Error('"' + aStr + '" is not in the set.'); }; /** * What is the element at the given index? * * @param Number aIdx */ ArraySet.prototype.at = function ArraySet_at(aIdx) { if (aIdx >= 0 && aIdx < this._array.length) { return this._array[aIdx]; } throw new Error('No element indexed by ' + aIdx); }; /** * Returns the array representation of this set (which has the proper indices * indicated by indexOf). Note that this is a copy of the internal array used * for storing the members so that no one can mess with internal state. */ ArraySet.prototype.toArray = function ArraySet_toArray() { return this._array.slice(); }; exports.ArraySet = ArraySet; }); },{"./util":19,"amdefine":20}],13:[function(_dereq_,module,exports){ /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause * * Based on the Base 64 VLQ implementation in Closure Compiler: * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java * * Copyright 2011 The Closure Compiler Authors. All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ if (typeof define !== 'function') { var define = _dereq_('amdefine')(module, _dereq_); } define(function (_dereq_, exports, module) { var base64 = _dereq_('./base64'); // A single base 64 digit can contain 6 bits of data. For the base 64 variable // length quantities we use in the source map spec, the first bit is the sign, // the next four bits are the actual value, and the 6th bit is the // continuation bit. The continuation bit tells us whether there are more // digits in this value following this digit. // // Continuation // | Sign // | | // V V // 101011 var VLQ_BASE_SHIFT = 5; // binary: 100000 var VLQ_BASE = 1 << VLQ_BASE_SHIFT; // binary: 011111 var VLQ_BASE_MASK = VLQ_BASE - 1; // binary: 100000 var VLQ_CONTINUATION_BIT = VLQ_BASE; /** * Converts from a two-complement value to a value where the sign bit is * is placed in the least significant bit. For example, as decimals: * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary) * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary) */ function toVLQSigned(aValue) { return aValue < 0 ? ((-aValue) << 1) + 1 : (aValue << 1) + 0; } /** * Converts to a two-complement value from a value where the sign bit is * is placed in the least significant bit. For example, as decimals: * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1 * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2 */ function fromVLQSigned(aValue) { var isNegative = (aValue & 1) === 1; var shifted = aValue >> 1; return isNegative ? -shifted : shifted; } /** * Returns the base 64 VLQ encoded value. */ exports.encode = function base64VLQ_encode(aValue) { var encoded = ""; var digit; var vlq = toVLQSigned(aValue); do { digit = vlq & VLQ_BASE_MASK; vlq >>>= VLQ_BASE_SHIFT; if (vlq > 0) { // There are still more digits in this value, so we must make sure the // continuation bit is marked. digit |= VLQ_CONTINUATION_BIT; } encoded += base64.encode(digit); } while (vlq > 0); return encoded; }; /** * Decodes the next base 64 VLQ value from the given string and returns the * value and the rest of the string. */ exports.decode = function base64VLQ_decode(aStr) { var i = 0; var strLen = aStr.length; var result = 0; var shift = 0; var continuation, digit; do { if (i >= strLen) { throw new Error("Expected more digits in base 64 VLQ value."); } digit = base64.decode(aStr.charAt(i++)); continuation = !!(digit & VLQ_CONTINUATION_BIT); digit &= VLQ_BASE_MASK; result = result + (digit << shift); shift += VLQ_BASE_SHIFT; } while (continuation); return { value: fromVLQSigned(result), rest: aStr.slice(i) }; }; }); },{"./base64":14,"amdefine":20}],14:[function(_dereq_,module,exports){ /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ if (typeof define !== 'function') { var define = _dereq_('amdefine')(module, _dereq_); } define(function (_dereq_, exports, module) { var charToIntMap = {}; var intToCharMap = {}; 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' .split('') .forEach(function (ch, index) { charToIntMap[ch] = index; intToCharMap[index] = ch; }); /** * Encode an integer in the range of 0 to 63 to a single base 64 digit. */ exports.encode = function base64_encode(aNumber) { if (aNumber in intToCharMap) { return intToCharMap[aNumber]; } throw new TypeError("Must be between 0 and 63: " + aNumber); }; /** * Decode a single base 64 digit to an integer. */ exports.decode = function base64_decode(aChar) { if (aChar in charToIntMap) { return charToIntMap[aChar]; } throw new TypeError("Not a valid base 64 digit: " + aChar); }; }); },{"amdefine":20}],15:[function(_dereq_,module,exports){ /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ if (typeof define !== 'function') { var define = _dereq_('amdefine')(module, _dereq_); } define(function (_dereq_, exports, module) { /** * Recursive implementation of binary search. * * @param aLow Indices here and lower do not contain the needle. * @param aHigh Indices here and higher do not contain the needle. * @param aNeedle The element being searched for. * @param aHaystack The non-empty array being searched. * @param aCompare Function which takes two elements and returns -1, 0, or 1. */ function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare) { // This function terminates when one of the following is true: // // 1. We find the exact element we are looking for. // // 2. We did not find the exact element, but we can return the next // closest element that is less than that element. // // 3. We did not find the exact element, and there is no next-closest // element which is less than the one we are searching for, so we // return null. var mid = Math.floor((aHigh - aLow) / 2) + aLow; var cmp = aCompare(aNeedle, aHaystack[mid], true); if (cmp === 0) { // Found the element we are looking for. return aHaystack[mid]; } else if (cmp > 0) { // aHaystack[mid] is greater than our needle. if (aHigh - mid > 1) { // The element is in the upper half. return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare); } // We did not find an exact match, return the next closest one // (termination case 2). return aHaystack[mid]; } else { // aHaystack[mid] is less than our needle. if (mid - aLow > 1) { // The element is in the lower half. return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare); } // The exact needle element was not found in this haystack. Determine if // we are in termination case (2) or (3) and return the appropriate thing. return aLow < 0 ? null : aHaystack[aLow]; } } /** * This is an implementation of binary search which will always try and return * the next lowest value checked if there is no exact hit. This is because * mappings between original and generated line/col pairs are single points, * and there is an implicit region between each of them, so a miss just means * that you aren't on the very start of a region. * * @param aNeedle The element you are looking for. * @param aHaystack The array that is being searched. * @param aCompare A function which takes the needle and an element in the * array and returns -1, 0, or 1 depending on whether the needle is less * than, equal to, or greater than the element, respectively. */ exports.search = function search(aNeedle, aHaystack, aCompare) { return aHaystack.length > 0 ? recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, aCompare) : null; }; }); },{"amdefine":20}],16:[function(_dereq_,module,exports){ /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ if (typeof define !== 'function') { var define = _dereq_('amdefine')(module, _dereq_); } define(function (_dereq_, exports, module) { var util = _dereq_('./util'); var binarySearch = _dereq_('./binary-search'); var ArraySet = _dereq_('./array-set').ArraySet; var base64VLQ = _dereq_('./base64-vlq'); /** * A SourceMapConsumer instance represents a parsed source map which we can * query for information about the original file positions by giving it a file * position in the generated source. * * The only parameter is the raw source map (either as a JSON string, or * already parsed to an object). According to the spec, source maps have the * following attributes: * * - version: Which version of the source map spec this map is following. * - sources: An array of URLs to the original source files. * - names: An array of identifiers which can be referrenced by individual mappings. * - sourceRoot: Optional. The URL root from which all sources are relative. * - sourcesContent: Optional. An array of contents of the original source files. * - mappings: A string of base64 VLQs which contain the actual mappings. * - file: The generated file this source map is associated with. * * Here is an example source map, taken from the source map spec[0]: * * { * version : 3, * file: "out.js", * sourceRoot : "", * sources: ["foo.js", "bar.js"], * names: ["src", "maps", "are", "fun"], * mappings: "AA,AB;;ABCDE;" * } * * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1# */ function SourceMapConsumer(aSourceMap) { var sourceMap = aSourceMap; if (typeof aSourceMap === 'string') { sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); } var version = util.getArg(sourceMap, 'version'); var sources = util.getArg(sourceMap, 'sources'); // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which // requires the array) to play nice here. var names = util.getArg(sourceMap, 'names', []); var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null); var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null); var mappings = util.getArg(sourceMap, 'mappings'); var file = util.getArg(sourceMap, 'file', null); // Once again, Sass deviates from the spec and supplies the version as a // string rather than a number, so we use loose equality checking here. if (version != this._version) { throw new Error('Unsupported version: ' + version); } // Pass `true` below to allow duplicate names and sources. While source maps // are intended to be compressed and deduplicated, the TypeScript compiler // sometimes generates source maps with duplicates in them. See Github issue // #72 and bugzil.la/889492. this._names = ArraySet.fromArray(names, true); this._sources = ArraySet.fromArray(sources, true); this.sourceRoot = sourceRoot; this.sourcesContent = sourcesContent; this._mappings = mappings; this.file = file; } /** * Create a SourceMapConsumer from a SourceMapGenerator. * * @param SourceMapGenerator aSourceMap * The source map that will be consumed. * @returns SourceMapConsumer */ SourceMapConsumer.fromSourceMap = function SourceMapConsumer_fromSourceMap(aSourceMap) { var smc = Object.create(SourceMapConsumer.prototype); smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true); smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true); smc.sourceRoot = aSourceMap._sourceRoot; smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), smc.sourceRoot); smc.file = aSourceMap._file; smc.__generatedMappings = aSourceMap._mappings.slice() .sort(util.compareByGeneratedPositions); smc.__originalMappings = aSourceMap._mappings.slice() .sort(util.compareByOriginalPositions); return smc; }; /** * The version of the source mapping spec that we are consuming. */ SourceMapConsumer.prototype._version = 3; /** * The list of original sources. */ Object.defineProperty(SourceMapConsumer.prototype, 'sources', { get: function () { return this._sources.toArray().map(function (s) { return this.sourceRoot ? util.join(this.sourceRoot, s) : s; }, this); } }); // `__generatedMappings` and `__originalMappings` are arrays that hold the // parsed mapping coordinates from the source map's "mappings" attribute. They // are lazily instantiated, accessed via the `_generatedMappings` and // `_originalMappings` getters respectively, and we only parse the mappings // and create these arrays once queried for a source location. We jump through // these hoops because there can be many thousands of mappings, and parsing // them is expensive, so we only want to do it if we must. // // Each object in the arrays is of the form: // // { // generatedLine: The line number in the generated code, // generatedColumn: The column number in the generated code, // source: The path to the original source file that generated this // chunk of code, // originalLine: The line number in the original source that // corresponds to this chunk of generated code, // originalColumn: The column number in the original source that // corresponds to this chunk of generated code, // name: The name of the original symbol which generated this chunk of // code. // } // // All properties except for `generatedLine` and `generatedColumn` can be // `null`. // // `_generatedMappings` is ordered by the generated positions. // // `_originalMappings` is ordered by the original positions. SourceMapConsumer.prototype.__generatedMappings = null; Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', { get: function () { if (!this.__generatedMappings) { this.__generatedMappings = []; this.__originalMappings = []; this._parseMappings(this._mappings, this.sourceRoot); } return this.__generatedMappings; } }); SourceMapConsumer.prototype.__originalMappings = null; Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', { get: function () { if (!this.__originalMappings) { this.__generatedMappings = []; this.__originalMappings = []; this._parseMappings(this._mappings, this.sourceRoot); } return this.__originalMappings; } }); /** * Parse the mappings in a string in to a data structure which we can easily * query (the ordered arrays in the `this.__generatedMappings` and * `this.__originalMappings` properties). */ SourceMapConsumer.prototype._parseMappings = function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { var generatedLine = 1; var previousGeneratedColumn = 0; var previousOriginalLine = 0; var previousOriginalColumn = 0; var previousSource = 0; var previousName = 0; var mappingSeparator = /^[,;]/; var str = aStr; var mapping; var temp; while (str.length > 0) { if (str.charAt(0) === ';') { generatedLine++; str = str.slice(1); previousGeneratedColumn = 0; } else if (str.charAt(0) === ',') { str = str.slice(1); } else { mapping = {}; mapping.generatedLine = generatedLine; // Generated column. temp = base64VLQ.decode(str); mapping.generatedColumn = previousGeneratedColumn + temp.value; previousGeneratedColumn = mapping.generatedColumn; str = temp.rest; if (str.length > 0 && !mappingSeparator.test(str.charAt(0))) { // Original source. temp = base64VLQ.decode(str); mapping.source = this._sources.at(previousSource + temp.value); previousSource += temp.value; str = temp.rest; if (str.length === 0 || mappingSeparator.test(str.charAt(0))) { throw new Error('Found a source, but no line and column'); } // Original line. temp = base64VLQ.decode(str); mapping.originalLine = previousOriginalLine + temp.value; previousOriginalLine = mapping.originalLine; // Lines are stored 0-based mapping.originalLine += 1; str = temp.rest; if (str.length === 0 || mappingSeparator.test(str.charAt(0))) { throw new Error('Found a source and line, but no column'); } // Original column. temp = base64VLQ.decode(str); mapping.originalColumn = previousOriginalColumn + temp.value; previousOriginalColumn = mapping.originalColumn; str = temp.rest; if (str.length > 0 && !mappingSeparator.test(str.charAt(0))) { // Original name. temp = base64VLQ.decode(str); mapping.name = this._names.at(previousName + temp.value); previousName += temp.value; str = temp.rest; } } this.__generatedMappings.push(mapping); if (typeof mapping.originalLine === 'number') { this.__originalMappings.push(mapping); } } } this.__originalMappings.sort(util.compareByOriginalPositions); }; /** * Find the mapping that best matches the hypothetical "needle" mapping that * we are searching for in the given "haystack" of mappings. */ SourceMapConsumer.prototype._findMapping = function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, aColumnName, aComparator) { // To return the position we are searching for, we must first find the // mapping for the given position and then return the opposite position it // points to. Because the mappings are sorted, we can use binary search to // find the best mapping. if (aNeedle[aLineName] <= 0) { throw new TypeError('Line must be greater than or equal to 1, got ' + aNeedle[aLineName]); } if (aNeedle[aColumnName] < 0) { throw new TypeError('Column must be greater than or equal to 0, got ' + aNeedle[aColumnName]); } return binarySearch.search(aNeedle, aMappings, aComparator); }; /** * Returns the original source, line, and column information for the generated * source's line and column positions provided. The only argument is an object * with the following properties: * * - line: The line number in the generated source. * - column: The column number in the generated source. * * and an object is returned with the following properties: * * - source: The original source file, or null. * - line: The line number in the original source, or null. * - column: The column number in the original source, or null. * - name: The original identifier, or null. */ SourceMapConsumer.prototype.originalPositionFor = function SourceMapConsumer_originalPositionFor(aArgs) { var needle = { generatedLine: util.getArg(aArgs, 'line'), generatedColumn: util.getArg(aArgs, 'column') }; var mapping = this._findMapping(needle, this._generatedMappings, "generatedLine", "generatedColumn", util.compareByGeneratedPositions); if (mapping) { var source = util.getArg(mapping, 'source', null); if (source && this.sourceRoot) { source = util.join(this.sourceRoot, source); } return { source: source, line: util.getArg(mapping, 'originalLine', null), column: util.getArg(mapping, 'originalColumn', null), name: util.getArg(mapping, 'name', null) }; } return { source: null, line: null, column: null, name: null }; }; /** * Returns the original source content. The only argument is the url of the * original source file. Returns null if no original source content is * availible. */ SourceMapConsumer.prototype.sourceContentFor = function SourceMapConsumer_sourceContentFor(aSource) { if (!this.sourcesContent) { return null; } if (this.sourceRoot) { aSource = util.relative(this.sourceRoot, aSource); } if (this._sources.has(aSource)) { return this.sourcesContent[this._sources.indexOf(aSource)]; } var url; if (this.sourceRoot && (url = util.urlParse(this.sourceRoot))) { // XXX: file:// URIs and absolute paths lead to unexpected behavior for // many users. We can help them out when they expect file:// URIs to // behave like it would if they were running a local HTTP server. See // https://bugzilla.mozilla.org/show_bug.cgi?id=885597. var fileUriAbsPath = aSource.replace(/^file:\/\//, ""); if (url.scheme == "file" && this._sources.has(fileUriAbsPath)) { return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)] } if ((!url.path || url.path == "/") && this._sources.has("/" + aSource)) { return this.sourcesContent[this._sources.indexOf("/" + aSource)]; } } throw new Error('"' + aSource + '" is not in the SourceMap.'); }; /** * Returns the generated line and column information for the original source, * line, and column positions provided. The only argument is an object with * the following properties: * * - source: The filename of the original source. * - line: The line number in the original source. * - column: The column number in the original source. * * and an object is returned with the following properties: * * - line: The line number in the generated source, or null. * - column: The column number in the generated source, or null. */ SourceMapConsumer.prototype.generatedPositionFor = function SourceMapConsumer_generatedPositionFor(aArgs) { var needle = { source: util.getArg(aArgs, 'source'), originalLine: util.getArg(aArgs, 'line'), originalColumn: util.getArg(aArgs, 'column') }; if (this.sourceRoot) { needle.source = util.relative(this.sourceRoot, needle.source); } var mapping = this._findMapping(needle, this._originalMappings, "originalLine", "originalColumn", util.compareByOriginalPositions); if (mapping) { return { line: util.getArg(mapping, 'generatedLine', null), column: util.getArg(mapping, 'generatedColumn', null) }; } return { line: null, column: null }; }; SourceMapConsumer.GENERATED_ORDER = 1; SourceMapConsumer.ORIGINAL_ORDER = 2; /** * Iterate over each mapping between an original source/line/column and a * generated line/column in this source map. * * @param Function aCallback * The function that is called with each mapping. * @param Object aContext * Optional. If specified, this object will be the value of `this` every * time that `aCallback` is called. * @param aOrder * Either `SourceMapConsumer.GENERATED_ORDER` or * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to * iterate over the mappings sorted by the generated file's line/column * order or the original's source/line/column order, respectively. Defaults to * `SourceMapConsumer.GENERATED_ORDER`. */ SourceMapConsumer.prototype.eachMapping = function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) { var context = aContext || null; var order = aOrder || SourceMapConsumer.GENERATED_ORDER; var mappings; switch (order) { case SourceMapConsumer.GENERATED_ORDER: mappings = this._generatedMappings; break; case SourceMapConsumer.ORIGINAL_ORDER: mappings = this._originalMappings; break; default: throw new Error("Unknown order of iteration."); } var sourceRoot = this.sourceRoot; mappings.map(function (mapping) { var source = mapping.source; if (source && sourceRoot) { source = util.join(sourceRoot, source); } return { source: source, generatedLine: mapping.generatedLine, generatedColumn: mapping.generatedColumn, originalLine: mapping.originalLine, originalColumn: mapping.originalColumn, name: mapping.name }; }).forEach(aCallback, context); }; exports.SourceMapConsumer = SourceMapConsumer; }); },{"./array-set":12,"./base64-vlq":13,"./binary-search":15,"./util":19,"amdefine":20}],17:[function(_dereq_,module,exports){ /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ if (typeof define !== 'function') { var define = _dereq_('amdefine')(module, _dereq_); } define(function (_dereq_, exports, module) { var base64VLQ = _dereq_('./base64-vlq'); var util = _dereq_('./util'); var ArraySet = _dereq_('./array-set').ArraySet; /** * An instance of the SourceMapGenerator represents a source map which is * being built incrementally. To create a new one, you must pass an object * with the following properties: * * - file: The filename of the generated source. * - sourceRoot: An optional root for all URLs in this source map. */ function SourceMapGenerator(aArgs) { this._file = util.getArg(aArgs, 'file'); this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null); this._sources = new ArraySet(); this._names = new ArraySet(); this._mappings = []; this._sourcesContents = null; } SourceMapGenerator.prototype._version = 3; /** * Creates a new SourceMapGenerator based on a SourceMapConsumer * * @param aSourceMapConsumer The SourceMap. */ SourceMapGenerator.fromSourceMap = function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) { var sourceRoot = aSourceMapConsumer.sourceRoot; var generator = new SourceMapGenerator({ file: aSourceMapConsumer.file, sourceRoot: sourceRoot }); aSourceMapConsumer.eachMapping(function (mapping) { var newMapping = { generated: { line: mapping.generatedLine, column: mapping.generatedColumn } }; if (mapping.source) { newMapping.source = mapping.source; if (sourceRoot) { newMapping.source = util.relative(sourceRoot, newMapping.source); } newMapping.original = { line: mapping.originalLine, column: mapping.originalColumn }; if (mapping.name) { newMapping.name = mapping.name; } } generator.addMapping(newMapping); }); aSourceMapConsumer.sources.forEach(function (sourceFile) { var content = aSourceMapConsumer.sourceContentFor(sourceFile); if (content) { generator.setSourceContent(sourceFile, content); } }); return generator; }; /** * Add a single mapping from original source line and column to the generated * source's line and column for this source map being created. The mapping * object should have the following properties: * * - generated: An object with the generated line and column positions. * - original: An object with the original line and column positions. * - source: The original source file (relative to the sourceRoot). * - name: An optional original token name for this mapping. */ SourceMapGenerator.prototype.addMapping = function SourceMapGenerator_addMapping(aArgs) { var generated = util.getArg(aArgs, 'generated'); var original = util.getArg(aArgs, 'original', null); var source = util.getArg(aArgs, 'source', null); var name = util.getArg(aArgs, 'name', null); this._validateMapping(generated, original, source, name); if (source && !this._sources.has(source)) { this._sources.add(source); } if (name && !this._names.has(name)) { this._names.add(name); } this._mappings.push({ generatedLine: generated.line, generatedColumn: generated.column, originalLine: original != null && original.line, originalColumn: original != null && original.column, source: source, name: name }); }; /** * Set the source content for a source file. */ SourceMapGenerator.prototype.setSourceContent = function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) { var source = aSourceFile; if (this._sourceRoot) { source = util.relative(this._sourceRoot, source); } if (aSourceContent !== null) { // Add the source content to the _sourcesContents map. // Create a new _sourcesContents map if the property is null. if (!this._sourcesContents) { this._sourcesContents = {}; } this._sourcesContents[util.toSetString(source)] = aSourceContent; } else { // Remove the source file from the _sourcesContents map. // If the _sourcesContents map is empty, set the property to null. delete this._sourcesContents[util.toSetString(source)]; if (Object.keys(this._sourcesContents).length === 0) { this._sourcesContents = null; } } }; /** * Applies the mappings of a sub-source-map for a specific source file to the * source map being generated. Each mapping to the supplied source file is * rewritten using the supplied source map. Note: The resolution for the * resulting mappings is the minimium of this map and the supplied map. * * @param aSourceMapConsumer The source map to be applied. * @param aSourceFile Optional. The filename of the source file. * If omitted, SourceMapConsumer's file property will be used. */ SourceMapGenerator.prototype.applySourceMap = function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile) { // If aSourceFile is omitted, we will use the file property of the SourceMap if (!aSourceFile) { aSourceFile = aSourceMapConsumer.file; } var sourceRoot = this._sourceRoot; // Make "aSourceFile" relative if an absolute Url is passed. if (sourceRoot) { aSourceFile = util.relative(sourceRoot, aSourceFile); } // Applying the SourceMap can add and remove items from the sources and // the names array. var newSources = new ArraySet(); var newNames = new ArraySet(); // Find mappings for the "aSourceFile" this._mappings.forEach(function (mapping) { if (mapping.source === aSourceFile && mapping.originalLine) { // Check if it can be mapped by the source map, then update the mapping. var original = aSourceMapConsumer.originalPositionFor({ line: mapping.originalLine, column: mapping.originalColumn }); if (original.source !== null) { // Copy mapping if (sourceRoot) { mapping.source = util.relative(sourceRoot, original.source); } else { mapping.source = original.source; } mapping.originalLine = original.line; mapping.originalColumn = original.column; if (original.name !== null && mapping.name !== null) { // Only use the identifier name if it's an identifier // in both SourceMaps mapping.name = original.name; } } } var source = mapping.source; if (source && !newSources.has(source)) { newSources.add(source); } var name = mapping.name; if (name && !newNames.has(name)) { newNames.add(name); } }, this); this._sources = newSources; this._names = newNames; // Copy sourcesContents of applied map. aSourceMapConsumer.sources.forEach(function (sourceFile) { var content = aSourceMapConsumer.sourceContentFor(sourceFile); if (content) { if (sourceRoot) { sourceFile = util.relative(sourceRoot, sourceFile); } this.setSourceContent(sourceFile, content); } }, this); }; /** * A mapping can have one of the three levels of data: * * 1. Just the generated position. * 2. The Generated position, original position, and original source. * 3. Generated and original position, original source, as well as a name * token. * * To maintain consistency, we validate that any new mapping being added falls * in to one of these categories. */ SourceMapGenerator.prototype._validateMapping = function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, aName) { if (aGenerated && 'line' in aGenerated && 'column' in aGenerated && aGenerated.line > 0 && aGenerated.column >= 0 && !aOriginal && !aSource && !aName) { // Case 1. return; } else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated && aOriginal && 'line' in aOriginal && 'column' in aOriginal && aGenerated.line > 0 && aGenerated.column >= 0 && aOriginal.line > 0 && aOriginal.column >= 0 && aSource) { // Cases 2 and 3. return; } else { throw new Error('Invalid mapping: ' + JSON.stringify({ generated: aGenerated, source: aSource, orginal: aOriginal, name: aName })); } }; /** * Serialize the accumulated mappings in to the stream of base 64 VLQs * specified by the source map format. */ SourceMapGenerator.prototype._serializeMappings = function SourceMapGenerator_serializeMappings() { var previousGeneratedColumn = 0; var previousGeneratedLine = 1; var previousOriginalColumn = 0; var previousOriginalLine = 0; var previousName = 0; var previousSource = 0; var result = ''; var mapping; // The mappings must be guaranteed to be in sorted order before we start // serializing them or else the generated line numbers (which are defined // via the ';' separators) will be all messed up. Note: it might be more // performant to maintain the sorting as we insert them, rather than as we // serialize them, but the big O is the same either way. this._mappings.sort(util.compareByGeneratedPositions); for (var i = 0, len = this._mappings.length; i < len; i++) { mapping = this._mappings[i]; if (mapping.generatedLine !== previousGeneratedLine) { previousGeneratedColumn = 0; while (mapping.generatedLine !== previousGeneratedLine) { result += ';'; previousGeneratedLine++; } } else { if (i > 0) { if (!util.compareByGeneratedPositions(mapping, this._mappings[i - 1])) { continue; } result += ','; } } result += base64VLQ.encode(mapping.generatedColumn - previousGeneratedColumn); previousGeneratedColumn = mapping.generatedColumn; if (mapping.source) { result += base64VLQ.encode(this._sources.indexOf(mapping.source) - previousSource); previousSource = this._sources.indexOf(mapping.source); // lines are stored 0-based in SourceMap spec version 3 result += base64VLQ.encode(mapping.originalLine - 1 - previousOriginalLine); previousOriginalLine = mapping.originalLine - 1; result += base64VLQ.encode(mapping.originalColumn - previousOriginalColumn); previousOriginalColumn = mapping.originalColumn; if (mapping.name) { result += base64VLQ.encode(this._names.indexOf(mapping.name) - previousName); previousName = this._names.indexOf(mapping.name); } } } return result; }; SourceMapGenerator.prototype._generateSourcesContent = function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) { return aSources.map(function (source) { if (!this._sourcesContents) { return null; } if (aSourceRoot) { source = util.relative(aSourceRoot, source); } var key = util.toSetString(source); return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) ? this._sourcesContents[key] : null; }, this); }; /** * Externalize the source map. */ SourceMapGenerator.prototype.toJSON = function SourceMapGenerator_toJSON() { var map = { version: this._version, file: this._file, sources: this._sources.toArray(), names: this._names.toArray(), mappings: this._serializeMappings() }; if (this._sourceRoot) { map.sourceRoot = this._sourceRoot; } if (this._sourcesContents) { map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot); } return map; }; /** * Render the source map being generated to a string. */ SourceMapGenerator.prototype.toString = function SourceMapGenerator_toString() { return JSON.stringify(this); }; exports.SourceMapGenerator = SourceMapGenerator; }); },{"./array-set":12,"./base64-vlq":13,"./util":19,"amdefine":20}],18:[function(_dereq_,module,exports){ /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ if (typeof define !== 'function') { var define = _dereq_('amdefine')(module, _dereq_); } define(function (_dereq_, exports, module) { var SourceMapGenerator = _dereq_('./source-map-generator').SourceMapGenerator; var util = _dereq_('./util'); /** * SourceNodes provide a way to abstract over interpolating/concatenating * snippets of generated JavaScript source code while maintaining the line and * column information associated with the original source code. * * @param aLine The original line number. * @param aColumn The original column number. * @param aSource The original source's filename. * @param aChunks Optional. An array of strings which are snippets of * generated JS, or other SourceNodes. * @param aName The original identifier. */ function SourceNode(aLine, aColumn, aSource, aChunks, aName) { this.children = []; this.sourceContents = {}; this.line = aLine === undefined ? null : aLine; this.column = aColumn === undefined ? null : aColumn; this.source = aSource === undefined ? null : aSource; this.name = aName === undefined ? null : aName; if (aChunks != null) this.add(aChunks); } /** * Creates a SourceNode from generated code and a SourceMapConsumer. * * @param aGeneratedCode The generated code * @param aSourceMapConsumer The SourceMap for the generated code */ SourceNode.fromStringWithSourceMap = function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer) { // The SourceNode we want to fill with the generated code // and the SourceMap var node = new SourceNode(); // The generated code // Processed fragments are removed from this array. var remainingLines = aGeneratedCode.split('\n'); // We need to remember the position of "remainingLines" var lastGeneratedLine = 1, lastGeneratedColumn = 0; // The generate SourceNodes we need a code range. // To extract it current and last mapping is used. // Here we store the last mapping. var lastMapping = null; aSourceMapConsumer.eachMapping(function (mapping) { if (lastMapping === null) { // We add the generated code until the first mapping // to the SourceNode without any mapping. // Each line is added as separate string. while (lastGeneratedLine < mapping.generatedLine) { node.add(remainingLines.shift() + "\n"); lastGeneratedLine++; } if (lastGeneratedColumn < mapping.generatedColumn) { var nextLine = remainingLines[0]; node.add(nextLine.substr(0, mapping.generatedColumn)); remainingLines[0] = nextLine.substr(mapping.generatedColumn); lastGeneratedColumn = mapping.generatedColumn; } } else { // We add the code from "lastMapping" to "mapping": // First check if there is a new line in between. if (lastGeneratedLine < mapping.generatedLine) { var code = ""; // Associate full lines with "lastMapping" do { code += remainingLines.shift() + "\n"; lastGeneratedLine++; lastGeneratedColumn = 0; } while (lastGeneratedLine < mapping.generatedLine); // When we reached the correct line, we add code until we // reach the correct column too. if (lastGeneratedColumn < mapping.generatedColumn) { var nextLine = remainingLines[0]; code += nextLine.substr(0, mapping.generatedColumn); remainingLines[0] = nextLine.substr(mapping.generatedColumn); lastGeneratedColumn = mapping.generatedColumn; } // Create the SourceNode. addMappingWithCode(lastMapping, code); } else { // There is no new line in between. // Associate the code between "lastGeneratedColumn" and // "mapping.generatedColumn" with "lastMapping" var nextLine = remainingLines[0]; var code = nextLine.substr(0, mapping.generatedColumn - lastGeneratedColumn); remainingLines[0] = nextLine.substr(mapping.generatedColumn - lastGeneratedColumn); lastGeneratedColumn = mapping.generatedColumn; addMappingWithCode(lastMapping, code); } } lastMapping = mapping; }, this); // We have processed all mappings. // Associate the remaining code in the current line with "lastMapping" // and add the remaining lines without any mapping addMappingWithCode(lastMapping, remainingLines.join("\n")); // Copy sourcesContent into SourceNode aSourceMapConsumer.sources.forEach(function (sourceFile) { var content = aSourceMapConsumer.sourceContentFor(sourceFile); if (content) { node.setSourceContent(sourceFile, content); } }); return node; function addMappingWithCode(mapping, code) { if (mapping === null || mapping.source === undefined) { node.add(code); } else { node.add(new SourceNode(mapping.originalLine, mapping.originalColumn, mapping.source, code, mapping.name)); } } }; /** * Add a chunk of generated JS to this source node. * * @param aChunk A string snippet of generated JS code, another instance of * SourceNode, or an array where each member is one of those things. */ SourceNode.prototype.add = function SourceNode_add(aChunk) { if (Array.isArray(aChunk)) { aChunk.forEach(function (chunk) { this.add(chunk); }, this); } else if (aChunk instanceof SourceNode || typeof aChunk === "string") { if (aChunk) { this.children.push(aChunk); } } else { throw new TypeError( "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk ); } return this; }; /** * Add a chunk of generated JS to the beginning of this source node. * * @param aChunk A string snippet of generated JS code, another instance of * SourceNode, or an array where each member is one of those things. */ SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) { if (Array.isArray(aChunk)) { for (var i = aChunk.length-1; i >= 0; i--) { this.prepend(aChunk[i]); } } else if (aChunk instanceof SourceNode || typeof aChunk === "string") { this.children.unshift(aChunk); } else { throw new TypeError( "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk ); } return this; }; /** * Walk over the tree of JS snippets in this node and its children. The * walking function is called once for each snippet of JS and is passed that * snippet and the its original associated source's line/column location. * * @param aFn The traversal function. */ SourceNode.prototype.walk = function SourceNode_walk(aFn) { var chunk; for (var i = 0, len = this.children.length; i < len; i++) { chunk = this.children[i]; if (chunk instanceof SourceNode) { chunk.walk(aFn); } else { if (chunk !== '') { aFn(chunk, { source: this.source, line: this.line, column: this.column, name: this.name }); } } } }; /** * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between * each of `this.children`. * * @param aSep The separator. */ SourceNode.prototype.join = function SourceNode_join(aSep) { var newChildren; var i; var len = this.children.length; if (len > 0) { newChildren = []; for (i = 0; i < len-1; i++) { newChildren.push(this.children[i]); newChildren.push(aSep); } newChildren.push(this.children[i]); this.children = newChildren; } return this; }; /** * Call String.prototype.replace on the very right-most source snippet. Useful * for trimming whitespace from the end of a source node, etc. * * @param aPattern The pattern to replace. * @param aReplacement The thing to replace the pattern with. */ SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) { var lastChild = this.children[this.children.length - 1]; if (lastChild instanceof SourceNode) { lastChild.replaceRight(aPattern, aReplacement); } else if (typeof lastChild === 'string') { this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement); } else { this.children.push(''.replace(aPattern, aReplacement)); } return this; }; /** * Set the source content for a source file. This will be added to the SourceMapGenerator * in the sourcesContent field. * * @param aSourceFile The filename of the source file * @param aSourceContent The content of the source file */ SourceNode.prototype.setSourceContent = function SourceNode_setSourceContent(aSourceFile, aSourceContent) { this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent; }; /** * Walk over the tree of SourceNodes. The walking function is called for each * source file content and is passed the filename and source content. * * @param aFn The traversal function. */ SourceNode.prototype.walkSourceContents = function SourceNode_walkSourceContents(aFn) { for (var i = 0, len = this.children.length; i < len; i++) { if (this.children[i] instanceof SourceNode) { this.children[i].walkSourceContents(aFn); } } var sources = Object.keys(this.sourceContents); for (var i = 0, len = sources.length; i < len; i++) { aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]); } }; /** * Return the string representation of this source node. Walks over the tree * and concatenates all the various snippets together to one string. */ SourceNode.prototype.toString = function SourceNode_toString() { var str = ""; this.walk(function (chunk) { str += chunk; }); return str; }; /** * Returns the string representation of this source node along with a source * map. */ SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) { var generated = { code: "", line: 1, column: 0 }; var map = new SourceMapGenerator(aArgs); var sourceMappingActive = false; var lastOriginalSource = null; var lastOriginalLine = null; var lastOriginalColumn = null; var lastOriginalName = null; this.walk(function (chunk, original) { generated.code += chunk; if (original.source !== null && original.line !== null && original.column !== null) { if(lastOriginalSource !== original.source || lastOriginalLine !== original.line || lastOriginalColumn !== original.column || lastOriginalName !== original.name) { map.addMapping({ source: original.source, original: { line: original.line, column: original.column }, generated: { line: generated.line, column: generated.column }, name: original.name }); } lastOriginalSource = original.source; lastOriginalLine = original.line; lastOriginalColumn = original.column; lastOriginalName = original.name; sourceMappingActive = true; } else if (sourceMappingActive) { map.addMapping({ generated: { line: generated.line, column: generated.column } }); lastOriginalSource = null; sourceMappingActive = false; } chunk.split('').forEach(function (ch) { if (ch === '\n') { generated.line++; generated.column = 0; } else { generated.column++; } }); }); this.walkSourceContents(function (sourceFile, sourceContent) { map.setSourceContent(sourceFile, sourceContent); }); return { code: generated.code, map: map }; }; exports.SourceNode = SourceNode; }); },{"./source-map-generator":17,"./util":19,"amdefine":20}],19:[function(_dereq_,module,exports){ /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ if (typeof define !== 'function') { var define = _dereq_('amdefine')(module, _dereq_); } define(function (_dereq_, exports, module) { /** * This is a helper function for getting values from parameter/options * objects. * * @param args The object we are extracting values from * @param name The name of the property we are getting. * @param defaultValue An optional value to return if the property is missing * from the object. If this is not specified and the property is missing, an * error will be thrown. */ function getArg(aArgs, aName, aDefaultValue) { if (aName in aArgs) { return aArgs[aName]; } else if (arguments.length === 3) { return aDefaultValue; } else { throw new Error('"' + aName + '" is a required argument.'); } } exports.getArg = getArg; var urlRegexp = /([\w+\-.]+):\/\/((\w+:\w+)@)?([\w.]+)?(:(\d+))?(\S+)?/; var dataUrlRegexp = /^data:.+\,.+/; function urlParse(aUrl) { var match = aUrl.match(urlRegexp); if (!match) { return null; } return { scheme: match[1], auth: match[3], host: match[4], port: match[6], path: match[7] }; } exports.urlParse = urlParse; function urlGenerate(aParsedUrl) { var url = aParsedUrl.scheme + "://"; if (aParsedUrl.auth) { url += aParsedUrl.auth + "@" } if (aParsedUrl.host) { url += aParsedUrl.host; } if (aParsedUrl.port) { url += ":" + aParsedUrl.port } if (aParsedUrl.path) { url += aParsedUrl.path; } return url; } exports.urlGenerate = urlGenerate; function join(aRoot, aPath) { var url; if (aPath.match(urlRegexp) || aPath.match(dataUrlRegexp)) { return aPath; } if (aPath.charAt(0) === '/' && (url = urlParse(aRoot))) { url.path = aPath; return urlGenerate(url); } return aRoot.replace(/\/$/, '') + '/' + aPath; } exports.join = join; /** * Because behavior goes wacky when you set `__proto__` on objects, we * have to prefix all the strings in our set with an arbitrary character. * * See https://github.com/mozilla/source-map/pull/31 and * https://github.com/mozilla/source-map/issues/30 * * @param String aStr */ function toSetString(aStr) { return '$' + aStr; } exports.toSetString = toSetString; function fromSetString(aStr) { return aStr.substr(1); } exports.fromSetString = fromSetString; function relative(aRoot, aPath) { aRoot = aRoot.replace(/\/$/, ''); var url = urlParse(aRoot); if (aPath.charAt(0) == "/" && url && url.path == "/") { return aPath.slice(1); } return aPath.indexOf(aRoot + '/') === 0 ? aPath.substr(aRoot.length + 1) : aPath; } exports.relative = relative; function strcmp(aStr1, aStr2) { var s1 = aStr1 || ""; var s2 = aStr2 || ""; return (s1 > s2) - (s1 < s2); } /** * Comparator between two mappings where the original positions are compared. * * Optionally pass in `true` as `onlyCompareGenerated` to consider two * mappings with the same original source/line/column, but different generated * line and column the same. Useful when searching for a mapping with a * stubbed out mapping. */ function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { var cmp; cmp = strcmp(mappingA.source, mappingB.source); if (cmp) { return cmp; } cmp = mappingA.originalLine - mappingB.originalLine; if (cmp) { return cmp; } cmp = mappingA.originalColumn - mappingB.originalColumn; if (cmp || onlyCompareOriginal) { return cmp; } cmp = strcmp(mappingA.name, mappingB.name); if (cmp) { return cmp; } cmp = mappingA.generatedLine - mappingB.generatedLine; if (cmp) { return cmp; } return mappingA.generatedColumn - mappingB.generatedColumn; }; exports.compareByOriginalPositions = compareByOriginalPositions; /** * Comparator between two mappings where the generated positions are * compared. * * Optionally pass in `true` as `onlyCompareGenerated` to consider two * mappings with the same generated line and column, but different * source/name/original line and column the same. Useful when searching for a * mapping with a stubbed out mapping. */ function compareByGeneratedPositions(mappingA, mappingB, onlyCompareGenerated) { var cmp; cmp = mappingA.generatedLine - mappingB.generatedLine; if (cmp) { return cmp; } cmp = mappingA.generatedColumn - mappingB.generatedColumn; if (cmp || onlyCompareGenerated) { return cmp; } cmp = strcmp(mappingA.source, mappingB.source); if (cmp) { return cmp; } cmp = mappingA.originalLine - mappingB.originalLine; if (cmp) { return cmp; } cmp = mappingA.originalColumn - mappingB.originalColumn; if (cmp) { return cmp; } return strcmp(mappingA.name, mappingB.name); }; exports.compareByGeneratedPositions = compareByGeneratedPositions; }); },{"amdefine":20}],20:[function(_dereq_,module,exports){ (function (process,__filename){ /** vim: et:ts=4:sw=4:sts=4 * @license amdefine 0.1.0 Copyright (c) 2011, The Dojo Foundation All Rights Reserved. * Available via the MIT or new BSD license. * see: http://github.com/jrburke/amdefine for details */ /*jslint node: true */ /*global module, process */ 'use strict'; /** * Creates a define for node. * @param {Object} module the "module" object that is defined by Node for the * current module. * @param {Function} [requireFn]. Node's require function for the current module. * It only needs to be passed in Node versions before 0.5, when module.require * did not exist. * @returns {Function} a define function that is usable for the current node * module. */ function amdefine(module, requireFn) { 'use strict'; var defineCache = {}, loaderCache = {}, alreadyCalled = false, path = _dereq_('path'), makeRequire, stringRequire; /** * Trims the . and .. from an array of path segments. * It will keep a leading path segment if a .. will become * the first path segment, to help with module name lookups, * which act like paths, but can be remapped. But the end result, * all paths that use this function should look normalized. * NOTE: this method MODIFIES the input array. * @param {Array} ary the array of path segments. */ function trimDots(ary) { var i, part; for (i = 0; ary[i]; i+= 1) { part = ary[i]; if (part === '.') { ary.splice(i, 1); i -= 1; } else if (part === '..') { if (i === 1 && (ary[2] === '..' || ary[0] === '..')) { //End of the line. Keep at least one non-dot //path segment at the front so it can be mapped //correctly to disk. Otherwise, there is likely //no path mapping for a path starting with '..'. //This can still fail, but catches the most reasonable //uses of .. break; } else if (i > 0) { ary.splice(i - 1, 2); i -= 2; } } } } function normalize(name, baseName) { var baseParts; //Adjust any relative paths. if (name && name.charAt(0) === '.') { //If have a base name, try to normalize against it, //otherwise, assume it is a top-level require that will //be relative to baseUrl in the end. if (baseName) { baseParts = baseName.split('/'); baseParts = baseParts.slice(0, baseParts.length - 1); baseParts = baseParts.concat(name.split('/')); trimDots(baseParts); name = baseParts.join('/'); } } return name; } /** * Create the normalize() function passed to a loader plugin's * normalize method. */ function makeNormalize(relName) { return function (name) { return normalize(name, relName); }; } function makeLoad(id) { function load(value) { loaderCache[id] = value; } load.fromText = function (id, text) { //This one is difficult because the text can/probably uses //define, and any relative paths and requires should be relative //to that id was it would be found on disk. But this would require //bootstrapping a module/require fairly deeply from node core. //Not sure how best to go about that yet. throw new Error('amdefine does not implement load.fromText'); }; return load; } makeRequire = function (systemRequire, exports, module, relId) { function amdRequire(deps, callback) { if (typeof deps === 'string') { //Synchronous, single module require('') return stringRequire(systemRequire, exports, module, deps, relId); } else { //Array of dependencies with a callback. //Convert the dependencies to modules. deps = deps.map(function (depName) { return stringRequire(systemRequire, exports, module, depName, relId); }); //Wait for next tick to call back the require call. process.nextTick(function () { callback.apply(null, deps); }); } } amdRequire.toUrl = function (filePath) { if (filePath.indexOf('.') === 0) { return normalize(filePath, path.dirname(module.filename)); } else { return filePath; } }; return amdRequire; }; //Favor explicit value, passed in if the module wants to support Node 0.4. requireFn = requireFn || function req() { return module.require.apply(module, arguments); }; function runFactory(id, deps, factory) { var r, e, m, result; if (id) { e = loaderCache[id] = {}; m = { id: id, uri: __filename, exports: e }; r = makeRequire(requireFn, e, m, id); } else { //Only support one define call per file if (alreadyCalled) { throw new Error('amdefine with no module ID cannot be called more than once per file.'); } alreadyCalled = true; //Use the real variables from node //Use module.exports for exports, since //the exports in here is amdefine exports. e = module.exports; m = module; r = makeRequire(requireFn, e, m, module.id); } //If there are dependencies, they are strings, so need //to convert them to dependency values. if (deps) { deps = deps.map(function (depName) { return r(depName); }); } //Call the factory with the right dependencies. if (typeof factory === 'function') { result = factory.apply(m.exports, deps); } else { result = factory; } if (result !== undefined) { m.exports = result; if (id) { loaderCache[id] = m.exports; } } } stringRequire = function (systemRequire, exports, module, id, relId) { //Split the ID by a ! so that var index = id.indexOf('!'), originalId = id, prefix, plugin; if (index === -1) { id = normalize(id, relId); //Straight module lookup. If it is one of the special dependencies, //deal with it, otherwise, delegate to node. if (id === 'require') { return makeRequire(systemRequire, exports, module, relId); } else if (id === 'exports') { return exports; } else if (id === 'module') { return module; } else if (loaderCache.hasOwnProperty(id)) { return loaderCache[id]; } else if (defineCache[id]) { runFactory.apply(null, defineCache[id]); return loaderCache[id]; } else { if(systemRequire) { return systemRequire(originalId); } else { throw new Error('No module with ID: ' + id); } } } else { //There is a plugin in play. prefix = id.substring(0, index); id = id.substring(index + 1, id.length); plugin = stringRequire(systemRequire, exports, module, prefix, relId); if (plugin.normalize) { id = plugin.normalize(id, makeNormalize(relId)); } else { //Normalize the ID normally. id = normalize(id, relId); } if (loaderCache[id]) { return loaderCache[id]; } else { plugin.load(id, makeRequire(systemRequire, exports, module, relId), makeLoad(id), {}); return loaderCache[id]; } } }; //Create a define function specific to the module asking for amdefine. function define(id, deps, factory) { if (Array.isArray(id)) { factory = deps; deps = id; id = undefined; } else if (typeof id !== 'string') { factory = id; id = deps = undefined; } if (deps && !Array.isArray(deps)) { factory = deps; deps = undefined; } if (!deps) { deps = ['require', 'exports', 'module']; } //Set up properties for this module. If an ID, then use //internal cache. If no ID, then use the external variables //for this node module. if (id) { //Put the module in deep freeze until there is a //require call for it. defineCache[id] = [id, deps, factory]; } else { runFactory(id, deps, factory); } } //define.require, which has access to all the values in the //cache. Useful for AMD modules that all have IDs in the file, //but need to finally export a value to node based on one of those //IDs. define.require = function (id) { if (loaderCache[id]) { return loaderCache[id]; } if (defineCache[id]) { runFactory.apply(null, defineCache[id]); return loaderCache[id]; } }; define.amd = {}; return define; } module.exports = amdefine; }).call(this,_dereq_('_process'),"/node_modules/jstransform/node_modules/source-map/node_modules/amdefine/amdefine.js") },{"_process":8,"path":7}],21:[function(_dereq_,module,exports){ /** * Copyright 2013 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var docblockRe = /^\s*(\/\*\*(.|\r?\n)*?\*\/)/; var ltrimRe = /^\s*/; /** * @param {String} contents * @return {String} */ function extract(contents) { var match = contents.match(docblockRe); if (match) { return match[0].replace(ltrimRe, '') || ''; } return ''; } var commentStartRe = /^\/\*\*?/; var commentEndRe = /\*+\/$/; var wsRe = /[\t ]+/g; var stringStartRe = /(\r?\n|^) *\*/g; var multilineRe = /(?:^|\r?\n) *(@[^\r\n]*?) *\r?\n *([^@\r\n\s][^@\r\n]+?) *\r?\n/g; var propertyRe = /(?:^|\r?\n) *@(\S+) *([^\r\n]*)/g; /** * @param {String} contents * @return {Array} */ function parse(docblock) { docblock = docblock .replace(commentStartRe, '') .replace(commentEndRe, '') .replace(wsRe, ' ') .replace(stringStartRe, '$1'); // Normalize multi-line directives var prev = ''; while (prev != docblock) { prev = docblock; docblock = docblock.replace(multilineRe, "\n$1 $2\n"); } docblock = docblock.trim(); var result = []; var match; while (match = propertyRe.exec(docblock)) { result.push([match[1], match[2]]); } return result; } /** * Same as parse but returns an object of prop: value instead of array of paris * If a property appers more than once the last one will be returned * * @param {String} contents * @return {Object} */ function parseAsObject(docblock) { var pairs = parse(docblock); var result = {}; for (var i = 0; i < pairs.length; i++) { result[pairs[i][0]] = pairs[i][1]; } return result; } exports.extract = extract; exports.parse = parse; exports.parseAsObject = parseAsObject; },{}],22:[function(_dereq_,module,exports){ /** * Copyright 2013 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*jslint node: true*/ "use strict"; var esprima = _dereq_('esprima-fb'); var utils = _dereq_('./utils'); var getBoundaryNode = utils.getBoundaryNode; var declareIdentInScope = utils.declareIdentInLocalScope; var initScopeMetadata = utils.initScopeMetadata; var Syntax = esprima.Syntax; /** * @param {object} node * @param {object} parentNode * @return {boolean} */ function _nodeIsClosureScopeBoundary(node, parentNode) { if (node.type === Syntax.Program) { return true; } var parentIsFunction = parentNode.type === Syntax.FunctionDeclaration || parentNode.type === Syntax.FunctionExpression || parentNode.type === Syntax.ArrowFunctionExpression; var parentIsCurlylessArrowFunc = parentNode.type === Syntax.ArrowFunctionExpression && node === parentNode.body; return parentIsFunction && (node.type === Syntax.BlockStatement || parentIsCurlylessArrowFunc); } function _nodeIsBlockScopeBoundary(node, parentNode) { if (node.type === Syntax.Program) { return false; } return node.type === Syntax.BlockStatement && parentNode.type === Syntax.CatchClause; } /** * @param {object} node * @param {array} path * @param {object} state */ function traverse(node, path, state) { /*jshint -W004*/ // Create a scope stack entry if this is the first node we've encountered in // its local scope var startIndex = null; var parentNode = path[0]; if (!Array.isArray(node) && state.localScope.parentNode !== parentNode) { if (_nodeIsClosureScopeBoundary(node, parentNode)) { var scopeIsStrict = state.scopeIsStrict; if (!scopeIsStrict && (node.type === Syntax.BlockStatement || node.type === Syntax.Program)) { scopeIsStrict = node.body.length > 0 && node.body[0].type === Syntax.ExpressionStatement && node.body[0].expression.type === Syntax.Literal && node.body[0].expression.value === 'use strict'; } if (node.type === Syntax.Program) { startIndex = state.g.buffer.length; state = utils.updateState(state, { scopeIsStrict: scopeIsStrict }); } else { startIndex = state.g.buffer.length + 1; state = utils.updateState(state, { localScope: { parentNode: parentNode, parentScope: state.localScope, identifiers: {}, tempVarIndex: 0, tempVars: [] }, scopeIsStrict: scopeIsStrict }); // All functions have an implicit 'arguments' object in scope declareIdentInScope('arguments', initScopeMetadata(node), state); // Include function arg identifiers in the scope boundaries of the // function if (parentNode.params.length > 0) { var param; var metadata = initScopeMetadata(parentNode, path.slice(1), path[0]); for (var i = 0; i < parentNode.params.length; i++) { param = parentNode.params[i]; if (param.type === Syntax.Identifier) { declareIdentInScope(param.name, metadata, state); } } } // Include rest arg identifiers in the scope boundaries of their // functions if (parentNode.rest) { var metadata = initScopeMetadata( parentNode, path.slice(1), path[0] ); declareIdentInScope(parentNode.rest.name, metadata, state); } // Named FunctionExpressions scope their name within the body block of // themselves only if (parentNode.type === Syntax.FunctionExpression && parentNode.id) { var metaData = initScopeMetadata(parentNode, path.parentNodeslice, parentNode); declareIdentInScope(parentNode.id.name, metaData, state); } } // Traverse and find all local identifiers in this closure first to // account for function/variable declaration hoisting collectClosureIdentsAndTraverse(node, path, state); } if (_nodeIsBlockScopeBoundary(node, parentNode)) { startIndex = state.g.buffer.length; state = utils.updateState(state, { localScope: { parentNode: parentNode, parentScope: state.localScope, identifiers: {}, tempVarIndex: 0, tempVars: [] } }); if (parentNode.type === Syntax.CatchClause) { var metadata = initScopeMetadata( parentNode, path.slice(1), parentNode ); declareIdentInScope(parentNode.param.name, metadata, state); } collectBlockIdentsAndTraverse(node, path, state); } } // Only catchup() before and after traversing a child node function traverser(node, path, state) { node.range && utils.catchup(node.range[0], state); traverse(node, path, state); node.range && utils.catchup(node.range[1], state); } utils.analyzeAndTraverse(walker, traverser, node, path, state); // Inject temp variables into the scope. if (startIndex !== null) { utils.injectTempVarDeclarations(state, startIndex); } } function collectClosureIdentsAndTraverse(node, path, state) { utils.analyzeAndTraverse( visitLocalClosureIdentifiers, collectClosureIdentsAndTraverse, node, path, state ); } function collectBlockIdentsAndTraverse(node, path, state) { utils.analyzeAndTraverse( visitLocalBlockIdentifiers, collectBlockIdentsAndTraverse, node, path, state ); } function visitLocalClosureIdentifiers(node, path, state) { var metaData; switch (node.type) { case Syntax.ArrowFunctionExpression: case Syntax.FunctionExpression: // Function expressions don't get their names (if there is one) added to // the closure scope they're defined in return false; case Syntax.ClassDeclaration: case Syntax.ClassExpression: case Syntax.FunctionDeclaration: if (node.id) { metaData = initScopeMetadata(getBoundaryNode(path), path.slice(), node); declareIdentInScope(node.id.name, metaData, state); } return false; case Syntax.VariableDeclarator: // Variables have function-local scope if (path[0].kind === 'var') { metaData = initScopeMetadata(getBoundaryNode(path), path.slice(), node); declareIdentInScope(node.id.name, metaData, state); } break; } } function visitLocalBlockIdentifiers(node, path, state) { // TODO: Support 'let' here...maybe...one day...or something... if (node.type === Syntax.CatchClause) { return false; } } function walker(node, path, state) { var visitors = state.g.visitors; for (var i = 0; i < visitors.length; i++) { if (visitors[i].test(node, path, state)) { return visitors[i](traverse, node, path, state); } } } var _astCache = {}; function getAstForSource(source, options) { if (_astCache[source] && !options.disableAstCache) { return _astCache[source]; } var ast = esprima.parse(source, { comment: true, loc: true, range: true, sourceType: options.sourceType }); if (!options.disableAstCache) { _astCache[source] = ast; } return ast; } /** * Applies all available transformations to the source * @param {array} visitors * @param {string} source * @param {?object} options * @return {object} */ function transform(visitors, source, options) { options = options || {}; var ast; try { ast = getAstForSource(source, options); } catch (e) { e.message = 'Parse Error: ' + e.message; throw e; } var state = utils.createState(source, ast, options); state.g.visitors = visitors; if (options.sourceMap) { var SourceMapGenerator = _dereq_('source-map').SourceMapGenerator; state.g.sourceMap = new SourceMapGenerator({file: options.filename || 'transformed.js'}); } traverse(ast, [], state); utils.catchup(source.length, state); var ret = {code: state.g.buffer, extra: state.g.extra}; if (options.sourceMap) { ret.sourceMap = state.g.sourceMap; ret.sourceMapFilename = options.filename || 'source.js'; } return ret; } exports.transform = transform; exports.Syntax = Syntax; },{"./utils":23,"esprima-fb":9,"source-map":11}],23:[function(_dereq_,module,exports){ /** * Copyright 2013 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*jslint node: true*/ var Syntax = _dereq_('esprima-fb').Syntax; var leadingIndentRegexp = /(^|\n)( {2}|\t)/g; var nonWhiteRegexp = /(\S)/g; /** * A `state` object represents the state of the parser. It has "local" and * "global" parts. Global contains parser position, source, etc. Local contains * scope based properties like current class name. State should contain all the * info required for transformation. It's the only mandatory object that is * being passed to every function in transform chain. * * @param {string} source * @param {object} transformOptions * @return {object} */ function createState(source, rootNode, transformOptions) { return { /** * A tree representing the current local scope (and its lexical scope chain) * Useful for tracking identifiers from parent scopes, etc. * @type {Object} */ localScope: { parentNode: rootNode, parentScope: null, identifiers: {}, tempVarIndex: 0, tempVars: [] }, /** * The name (and, if applicable, expression) of the super class * @type {Object} */ superClass: null, /** * The namespace to use when munging identifiers * @type {String} */ mungeNamespace: '', /** * Ref to the node for the current MethodDefinition * @type {Object} */ methodNode: null, /** * Ref to the node for the FunctionExpression of the enclosing * MethodDefinition * @type {Object} */ methodFuncNode: null, /** * Name of the enclosing class * @type {String} */ className: null, /** * Whether we're currently within a `strict` scope * @type {Bool} */ scopeIsStrict: null, /** * Indentation offset * @type {Number} */ indentBy: 0, /** * Global state (not affected by updateState) * @type {Object} */ g: { /** * A set of general options that transformations can consider while doing * a transformation: * * - minify * Specifies that transformation steps should do their best to minify * the output source when possible. This is useful for places where * minification optimizations are possible with higher-level context * info than what jsxmin can provide. * * For example, the ES6 class transform will minify munged private * variables if this flag is set. */ opts: transformOptions, /** * Current position in the source code * @type {Number} */ position: 0, /** * Auxiliary data to be returned by transforms * @type {Object} */ extra: {}, /** * Buffer containing the result * @type {String} */ buffer: '', /** * Source that is being transformed * @type {String} */ source: source, /** * Cached parsed docblock (see getDocblock) * @type {object} */ docblock: null, /** * Whether the thing was used * @type {Boolean} */ tagNamespaceUsed: false, /** * If using bolt xjs transformation * @type {Boolean} */ isBolt: undefined, /** * Whether to record source map (expensive) or not * @type {SourceMapGenerator|null} */ sourceMap: null, /** * Filename of the file being processed. Will be returned as a source * attribute in the source map */ sourceMapFilename: 'source.js', /** * Only when source map is used: last line in the source for which * source map was generated * @type {Number} */ sourceLine: 1, /** * Only when source map is used: last line in the buffer for which * source map was generated * @type {Number} */ bufferLine: 1, /** * The top-level Program AST for the original file. */ originalProgramAST: null, sourceColumn: 0, bufferColumn: 0 } }; } /** * Updates a copy of a given state with "update" and returns an updated state. * * @param {object} state * @param {object} update * @return {object} */ function updateState(state, update) { var ret = Object.create(state); Object.keys(update).forEach(function(updatedKey) { ret[updatedKey] = update[updatedKey]; }); return ret; } /** * Given a state fill the resulting buffer from the original source up to * the end * * @param {number} end * @param {object} state * @param {?function} contentTransformer Optional callback to transform newly * added content. */ function catchup(end, state, contentTransformer) { if (end < state.g.position) { // cannot move backwards return; } var source = state.g.source.substring(state.g.position, end); var transformed = updateIndent(source, state); if (state.g.sourceMap && transformed) { // record where we are state.g.sourceMap.addMapping({ generated: { line: state.g.bufferLine, column: state.g.bufferColumn }, original: { line: state.g.sourceLine, column: state.g.sourceColumn }, source: state.g.sourceMapFilename }); // record line breaks in transformed source var sourceLines = source.split('\n'); var transformedLines = transformed.split('\n'); // Add line break mappings between last known mapping and the end of the // added piece. So for the code piece // (foo, bar); // > var x = 2; // > var b = 3; // var c = // only add lines marked with ">": 2, 3. for (var i = 1; i < sourceLines.length - 1; i++) { state.g.sourceMap.addMapping({ generated: { line: state.g.bufferLine, column: 0 }, original: { line: state.g.sourceLine, column: 0 }, source: state.g.sourceMapFilename }); state.g.sourceLine++; state.g.bufferLine++; } // offset for the last piece if (sourceLines.length > 1) { state.g.sourceLine++; state.g.bufferLine++; state.g.sourceColumn = 0; state.g.bufferColumn = 0; } state.g.sourceColumn += sourceLines[sourceLines.length - 1].length; state.g.bufferColumn += transformedLines[transformedLines.length - 1].length; } state.g.buffer += contentTransformer ? contentTransformer(transformed) : transformed; state.g.position = end; } /** * Returns original source for an AST node. * @param {object} node * @param {object} state * @return {string} */ function getNodeSourceText(node, state) { return state.g.source.substring(node.range[0], node.range[1]); } function _replaceNonWhite(value) { return value.replace(nonWhiteRegexp, ' '); } /** * Removes all non-whitespace characters */ function _stripNonWhite(value) { return value.replace(nonWhiteRegexp, ''); } /** * Finds the position of the next instance of the specified syntactic char in * the pending source. * * NOTE: This will skip instances of the specified char if they sit inside a * comment body. * * NOTE: This function also assumes that the buffer's current position is not * already within a comment or a string. This is rarely the case since all * of the buffer-advancement utility methods tend to be used on syntactic * nodes' range values -- but it's a small gotcha that's worth mentioning. */ function getNextSyntacticCharOffset(char, state) { var pendingSource = state.g.source.substring(state.g.position); var pendingSourceLines = pendingSource.split('\n'); var charOffset = 0; var line; var withinBlockComment = false; var withinString = false; lineLoop: while ((line = pendingSourceLines.shift()) !== undefined) { var lineEndPos = charOffset + line.length; charLoop: for (; charOffset < lineEndPos; charOffset++) { var currChar = pendingSource[charOffset]; if (currChar === '"' || currChar === '\'') { withinString = !withinString; continue charLoop; } else if (withinString) { continue charLoop; } else if (charOffset + 1 < lineEndPos) { var nextTwoChars = currChar + line[charOffset + 1]; if (nextTwoChars === '//') { charOffset = lineEndPos + 1; continue lineLoop; } else if (nextTwoChars === '/*') { withinBlockComment = true; charOffset += 1; continue charLoop; } else if (nextTwoChars === '*/') { withinBlockComment = false; charOffset += 1; continue charLoop; } } if (!withinBlockComment && currChar === char) { return charOffset + state.g.position; } } // Account for '\n' charOffset++; withinString = false; } throw new Error('`' + char + '` not found!'); } /** * Catches up as `catchup` but replaces non-whitespace chars with spaces. */ function catchupWhiteOut(end, state) { catchup(end, state, _replaceNonWhite); } /** * Catches up as `catchup` but removes all non-whitespace characters. */ function catchupWhiteSpace(end, state) { catchup(end, state, _stripNonWhite); } /** * Removes all non-newline characters */ var reNonNewline = /[^\n]/g; function stripNonNewline(value) { return value.replace(reNonNewline, function() { return ''; }); } /** * Catches up as `catchup` but removes all non-newline characters. * * Equivalent to appending as many newlines as there are in the original source * between the current position and `end`. */ function catchupNewlines(end, state) { catchup(end, state, stripNonNewline); } /** * Same as catchup but does not touch the buffer * * @param {number} end * @param {object} state */ function move(end, state) { // move the internal cursors if (state.g.sourceMap) { if (end < state.g.position) { state.g.position = 0; state.g.sourceLine = 1; state.g.sourceColumn = 0; } var source = state.g.source.substring(state.g.position, end); var sourceLines = source.split('\n'); if (sourceLines.length > 1) { state.g.sourceLine += sourceLines.length - 1; state.g.sourceColumn = 0; } state.g.sourceColumn += sourceLines[sourceLines.length - 1].length; } state.g.position = end; } /** * Appends a string of text to the buffer * * @param {string} str * @param {object} state */ function append(str, state) { if (state.g.sourceMap && str) { state.g.sourceMap.addMapping({ generated: { line: state.g.bufferLine, column: state.g.bufferColumn }, original: { line: state.g.sourceLine, column: state.g.sourceColumn }, source: state.g.sourceMapFilename }); var transformedLines = str.split('\n'); if (transformedLines.length > 1) { state.g.bufferLine += transformedLines.length - 1; state.g.bufferColumn = 0; } state.g.bufferColumn += transformedLines[transformedLines.length - 1].length; } state.g.buffer += str; } /** * Update indent using state.indentBy property. Indent is measured in * double spaces. Updates a single line only. * * @param {string} str * @param {object} state * @return {string} */ function updateIndent(str, state) { /*jshint -W004*/ var indentBy = state.indentBy; if (indentBy < 0) { for (var i = 0; i < -indentBy; i++) { str = str.replace(leadingIndentRegexp, '$1'); } } else { for (var i = 0; i < indentBy; i++) { str = str.replace(leadingIndentRegexp, '$1$2$2'); } } return str; } /** * Calculates indent from the beginning of the line until "start" or the first * character before start. * @example * " foo.bar()" * ^ * start * indent will be " " * * @param {number} start * @param {object} state * @return {string} */ function indentBefore(start, state) { var end = start; start = start - 1; while (start > 0 && state.g.source[start] != '\n') { if (!state.g.source[start].match(/[ \t]/)) { end = start; } start--; } return state.g.source.substring(start + 1, end); } function getDocblock(state) { if (!state.g.docblock) { var docblock = _dereq_('./docblock'); state.g.docblock = docblock.parseAsObject(docblock.extract(state.g.source)); } return state.g.docblock; } function identWithinLexicalScope(identName, state, stopBeforeNode) { var currScope = state.localScope; while (currScope) { if (currScope.identifiers[identName] !== undefined) { return true; } if (stopBeforeNode && currScope.parentNode === stopBeforeNode) { break; } currScope = currScope.parentScope; } return false; } function identInLocalScope(identName, state) { return state.localScope.identifiers[identName] !== undefined; } /** * @param {object} boundaryNode * @param {?array} path * @return {?object} node */ function initScopeMetadata(boundaryNode, path, node) { return { boundaryNode: boundaryNode, bindingPath: path, bindingNode: node }; } function declareIdentInLocalScope(identName, metaData, state) { state.localScope.identifiers[identName] = { boundaryNode: metaData.boundaryNode, path: metaData.bindingPath, node: metaData.bindingNode, state: Object.create(state) }; } function getLexicalBindingMetadata(identName, state) { var currScope = state.localScope; while (currScope) { if (currScope.identifiers[identName] !== undefined) { return currScope.identifiers[identName]; } currScope = currScope.parentScope; } } function getLocalBindingMetadata(identName, state) { return state.localScope.identifiers[identName]; } /** * Apply the given analyzer function to the current node. If the analyzer * doesn't return false, traverse each child of the current node using the given * traverser function. * * @param {function} analyzer * @param {function} traverser * @param {object} node * @param {array} path * @param {object} state */ function analyzeAndTraverse(analyzer, traverser, node, path, state) { if (node.type) { if (analyzer(node, path, state) === false) { return; } path.unshift(node); } getOrderedChildren(node).forEach(function(child) { traverser(child, path, state); }); node.type && path.shift(); } /** * It is crucial that we traverse in order, or else catchup() on a later * node that is processed out of order can move the buffer past a node * that we haven't handled yet, preventing us from modifying that node. * * This can happen when a node has multiple properties containing children. * For example, XJSElement nodes have `openingElement`, `closingElement` and * `children`. If we traverse `openingElement`, then `closingElement`, then * when we get to `children`, the buffer has already caught up to the end of * the closing element, after the children. * * This is basically a Schwartzian transform. Collects an array of children, * each one represented as [child, startIndex]; sorts the array by start * index; then traverses the children in that order. */ function getOrderedChildren(node) { var queue = []; for (var key in node) { if (node.hasOwnProperty(key)) { enqueueNodeWithStartIndex(queue, node[key]); } } queue.sort(function(a, b) { return a[1] - b[1]; }); return queue.map(function(pair) { return pair[0]; }); } /** * Helper function for analyzeAndTraverse which queues up all of the children * of the given node. * * Children can also be found in arrays, so we basically want to merge all of * those arrays together so we can sort them and then traverse the children * in order. * * One example is the Program node. It contains `body` and `comments`, both * arrays. Lexographically, comments are interspersed throughout the body * nodes, but esprima's AST groups them together. */ function enqueueNodeWithStartIndex(queue, node) { if (typeof node !== 'object' || node === null) { return; } if (node.range) { queue.push([node, node.range[0]]); } else if (Array.isArray(node)) { for (var ii = 0; ii < node.length; ii++) { enqueueNodeWithStartIndex(queue, node[ii]); } } } /** * Checks whether a node or any of its sub-nodes contains * a syntactic construct of the passed type. * @param {object} node - AST node to test. * @param {string} type - node type to lookup. */ function containsChildOfType(node, type) { return containsChildMatching(node, function(node) { return node.type === type; }); } function containsChildMatching(node, matcher) { var foundMatchingChild = false; function nodeTypeAnalyzer(node) { if (matcher(node) === true) { foundMatchingChild = true; return false; } } function nodeTypeTraverser(child, path, state) { if (!foundMatchingChild) { foundMatchingChild = containsChildMatching(child, matcher); } } analyzeAndTraverse( nodeTypeAnalyzer, nodeTypeTraverser, node, [] ); return foundMatchingChild; } var scopeTypes = {}; scopeTypes[Syntax.ArrowFunctionExpression] = true; scopeTypes[Syntax.FunctionExpression] = true; scopeTypes[Syntax.FunctionDeclaration] = true; scopeTypes[Syntax.Program] = true; function getBoundaryNode(path) { for (var ii = 0; ii < path.length; ++ii) { if (scopeTypes[path[ii].type]) { return path[ii]; } } throw new Error( 'Expected to find a node with one of the following types in path:\n' + JSON.stringify(Object.keys(scopeTypes)) ); } function getTempVar(tempVarIndex) { return '$__' + tempVarIndex; } function injectTempVar(state) { var tempVar = '$__' + (state.localScope.tempVarIndex++); state.localScope.tempVars.push(tempVar); return tempVar; } function injectTempVarDeclarations(state, index) { if (state.localScope.tempVars.length) { state.g.buffer = state.g.buffer.slice(0, index) + 'var ' + state.localScope.tempVars.join(', ') + ';' + state.g.buffer.slice(index); state.localScope.tempVars = []; } } exports.analyzeAndTraverse = analyzeAndTraverse; exports.append = append; exports.catchup = catchup; exports.catchupNewlines = catchupNewlines; exports.catchupWhiteOut = catchupWhiteOut; exports.catchupWhiteSpace = catchupWhiteSpace; exports.containsChildMatching = containsChildMatching; exports.containsChildOfType = containsChildOfType; exports.createState = createState; exports.declareIdentInLocalScope = declareIdentInLocalScope; exports.getBoundaryNode = getBoundaryNode; exports.getDocblock = getDocblock; exports.getLexicalBindingMetadata = getLexicalBindingMetadata; exports.getLocalBindingMetadata = getLocalBindingMetadata; exports.getNextSyntacticCharOffset = getNextSyntacticCharOffset; exports.getNodeSourceText = getNodeSourceText; exports.getOrderedChildren = getOrderedChildren; exports.getTempVar = getTempVar; exports.identInLocalScope = identInLocalScope; exports.identWithinLexicalScope = identWithinLexicalScope; exports.indentBefore = indentBefore; exports.initScopeMetadata = initScopeMetadata; exports.injectTempVar = injectTempVar; exports.injectTempVarDeclarations = injectTempVarDeclarations; exports.move = move; exports.scopeTypes = scopeTypes; exports.updateIndent = updateIndent; exports.updateState = updateState; },{"./docblock":21,"esprima-fb":9}],24:[function(_dereq_,module,exports){ /** * Copyright 2013 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*global exports:true*/ /** * Desugars ES6 Arrow functions to ES3 function expressions. * If the function contains `this` expression -- automatically * binds the function to current value of `this`. * * Single parameter, simple expression: * * [1, 2, 3].map(x => x * x); * * [1, 2, 3].map(function(x) { return x * x; }); * * Several parameters, complex block: * * this.users.forEach((user, idx) => { * return this.isActive(idx) && this.send(user); * }); * * this.users.forEach(function(user, idx) { * return this.isActive(idx) && this.send(user); * }.bind(this)); * */ var restParamVisitors = _dereq_('./es6-rest-param-visitors'); var destructuringVisitors = _dereq_('./es6-destructuring-visitors'); var Syntax = _dereq_('esprima-fb').Syntax; var utils = _dereq_('../src/utils'); /** * @public */ function visitArrowFunction(traverse, node, path, state) { var notInExpression = (path[0].type === Syntax.ExpressionStatement); // Wrap a function into a grouping operator, if it's not // in the expression position. if (notInExpression) { utils.append('(', state); } utils.append('function', state); renderParams(traverse, node, path, state); // Skip arrow. utils.catchupWhiteSpace(node.body.range[0], state); var renderBody = node.body.type == Syntax.BlockStatement ? renderStatementBody : renderExpressionBody; path.unshift(node); renderBody(traverse, node, path, state); path.shift(); // Bind the function only if `this` value is used // inside it or inside any sub-expression. var containsBindingSyntax = utils.containsChildMatching(node.body, function(node) { return node.type === Syntax.ThisExpression || (node.type === Syntax.Identifier && node.name === "super"); }); if (containsBindingSyntax) { utils.append('.bind(this)', state); } utils.catchupWhiteSpace(node.range[1], state); // Close wrapper if not in the expression. if (notInExpression) { utils.append(')', state); } return false; } function renderParams(traverse, node, path, state) { // To preserve inline typechecking directives, we // distinguish between parens-free and paranthesized single param. if (isParensFreeSingleParam(node, state) || !node.params.length) { utils.append('(', state); } if (node.params.length !== 0) { path.unshift(node); traverse(node.params, path, state); path.unshift(); } utils.append(')', state); } function isParensFreeSingleParam(node, state) { return node.params.length === 1 && state.g.source[state.g.position] !== '('; } function renderExpressionBody(traverse, node, path, state) { // Wrap simple expression bodies into a block // with explicit return statement. utils.append('{', state); // Special handling of rest param. if (node.rest) { utils.append( restParamVisitors.renderRestParamSetup(node, state), state ); } // Special handling of destructured params. destructuringVisitors.renderDestructuredComponents( node, utils.updateState(state, { localScope: { parentNode: state.parentNode, parentScope: state.parentScope, identifiers: state.identifiers, tempVarIndex: 0 } }) ); utils.append('return ', state); renderStatementBody(traverse, node, path, state); utils.append(';}', state); } function renderStatementBody(traverse, node, path, state) { traverse(node.body, path, state); utils.catchup(node.body.range[1], state); } visitArrowFunction.test = function(node, path, state) { return node.type === Syntax.ArrowFunctionExpression; }; exports.visitorList = [ visitArrowFunction ]; },{"../src/utils":23,"./es6-destructuring-visitors":27,"./es6-rest-param-visitors":30,"esprima-fb":9}],25:[function(_dereq_,module,exports){ /** * Copyright 2004-present Facebook. All Rights Reserved. */ /*global exports:true*/ /** * Implements ES6 call spread. * * instance.method(a, b, c, ...d) * * instance.method.apply(instance, [a, b, c].concat(d)) * */ var Syntax = _dereq_('esprima-fb').Syntax; var utils = _dereq_('../src/utils'); function process(traverse, node, path, state) { utils.move(node.range[0], state); traverse(node, path, state); utils.catchup(node.range[1], state); } function visitCallSpread(traverse, node, path, state) { utils.catchup(node.range[0], state); if (node.type === Syntax.NewExpression) { // Input = new Set(1, 2, ...list) // Output = new (Function.prototype.bind.apply(Set, [null, 1, 2].concat(list))) utils.append('new (Function.prototype.bind.apply(', state); process(traverse, node.callee, path, state); } else if (node.callee.type === Syntax.MemberExpression) { // Input = get().fn(1, 2, ...more) // Output = (_ = get()).fn.apply(_, [1, 2].apply(more)) var tempVar = utils.injectTempVar(state); utils.append('(' + tempVar + ' = ', state); process(traverse, node.callee.object, path, state); utils.append(')', state); if (node.callee.property.type === Syntax.Identifier) { utils.append('.', state); process(traverse, node.callee.property, path, state); } else { utils.append('[', state); process(traverse, node.callee.property, path, state); utils.append(']', state); } utils.append('.apply(' + tempVar, state); } else { // Input = max(1, 2, ...list) // Output = max.apply(null, [1, 2].concat(list)) var needsToBeWrappedInParenthesis = node.callee.type === Syntax.FunctionDeclaration || node.callee.type === Syntax.FunctionExpression; if (needsToBeWrappedInParenthesis) { utils.append('(', state); } process(traverse, node.callee, path, state); if (needsToBeWrappedInParenthesis) { utils.append(')', state); } utils.append('.apply(null', state); } utils.append(', ', state); var args = node.arguments.slice(); var spread = args.pop(); if (args.length || node.type === Syntax.NewExpression) { utils.append('[', state); if (node.type === Syntax.NewExpression) { utils.append('null' + (args.length ? ', ' : ''), state); } while (args.length) { var arg = args.shift(); utils.move(arg.range[0], state); traverse(arg, path, state); if (args.length) { utils.catchup(args[0].range[0], state); } else { utils.catchup(arg.range[1], state); } } utils.append('].concat(', state); process(traverse, spread.argument, path, state); utils.append(')', state); } else { process(traverse, spread.argument, path, state); } utils.append(node.type === Syntax.NewExpression ? '))' : ')', state); utils.move(node.range[1], state); return false; } visitCallSpread.test = function(node, path, state) { return ( ( node.type === Syntax.CallExpression || node.type === Syntax.NewExpression ) && node.arguments.length > 0 && node.arguments[node.arguments.length - 1].type === Syntax.SpreadElement ); }; exports.visitorList = [ visitCallSpread ]; },{"../src/utils":23,"esprima-fb":9}],26:[function(_dereq_,module,exports){ /** * Copyright 2013 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*jslint node:true*/ /** * @typechecks */ 'use strict'; var base62 = _dereq_('base62'); var Syntax = _dereq_('esprima-fb').Syntax; var utils = _dereq_('../src/utils'); var reservedWordsHelper = _dereq_('./reserved-words-helper'); var declareIdentInLocalScope = utils.declareIdentInLocalScope; var initScopeMetadata = utils.initScopeMetadata; var SUPER_PROTO_IDENT_PREFIX = '____SuperProtoOf'; var _anonClassUUIDCounter = 0; var _mungedSymbolMaps = {}; function resetSymbols() { _anonClassUUIDCounter = 0; _mungedSymbolMaps = {}; } /** * Used to generate a unique class for use with code-gens for anonymous class * expressions. * * @param {object} state * @return {string} */ function _generateAnonymousClassName(state) { var mungeNamespace = state.mungeNamespace || ''; return '____Class' + mungeNamespace + base62.encode(_anonClassUUIDCounter++); } /** * Given an identifier name, munge it using the current state's mungeNamespace. * * @param {string} identName * @param {object} state * @return {string} */ function _getMungedName(identName, state) { var mungeNamespace = state.mungeNamespace; var shouldMinify = state.g.opts.minify; if (shouldMinify) { if (!_mungedSymbolMaps[mungeNamespace]) { _mungedSymbolMaps[mungeNamespace] = { symbolMap: {}, identUUIDCounter: 0 }; } var symbolMap = _mungedSymbolMaps[mungeNamespace].symbolMap; if (!symbolMap[identName]) { symbolMap[identName] = base62.encode(_mungedSymbolMaps[mungeNamespace].identUUIDCounter++); } identName = symbolMap[identName]; } return '$' + mungeNamespace + identName; } /** * Extracts super class information from a class node. * * Information includes name of the super class and/or the expression string * (if extending from an expression) * * @param {object} node * @param {object} state * @return {object} */ function _getSuperClassInfo(node, state) { var ret = { name: null, expression: null }; if (node.superClass) { if (node.superClass.type === Syntax.Identifier) { ret.name = node.superClass.name; } else { // Extension from an expression ret.name = _generateAnonymousClassName(state); ret.expression = state.g.source.substring( node.superClass.range[0], node.superClass.range[1] ); } } return ret; } /** * Used with .filter() to find the constructor method in a list of * MethodDefinition nodes. * * @param {object} classElement * @return {boolean} */ function _isConstructorMethod(classElement) { return classElement.type === Syntax.MethodDefinition && classElement.key.type === Syntax.Identifier && classElement.key.name === 'constructor'; } /** * @param {object} node * @param {object} state * @return {boolean} */ function _shouldMungeIdentifier(node, state) { return ( !!state.methodFuncNode && !utils.getDocblock(state).hasOwnProperty('preventMunge') && /^_(?!_)/.test(node.name) ); } /** * @param {function} traverse * @param {object} node * @param {array} path * @param {object} state */ function visitClassMethod(traverse, node, path, state) { if (!state.g.opts.es5 && (node.kind === 'get' || node.kind === 'set')) { throw new Error( 'This transform does not support ' + node.kind + 'ter methods for ES6 ' + 'classes. (line: ' + node.loc.start.line + ', col: ' + node.loc.start.column + ')' ); } state = utils.updateState(state, { methodNode: node }); utils.catchup(node.range[0], state); path.unshift(node); traverse(node.value, path, state); path.shift(); return false; } visitClassMethod.test = function(node, path, state) { return node.type === Syntax.MethodDefinition; }; /** * @param {function} traverse * @param {object} node * @param {array} path * @param {object} state */ function visitClassFunctionExpression(traverse, node, path, state) { var methodNode = path[0]; var isGetter = methodNode.kind === 'get'; var isSetter = methodNode.kind === 'set'; state = utils.updateState(state, { methodFuncNode: node }); if (methodNode.key.name === 'constructor') { utils.append('function ' + state.className, state); } else { var methodAccessorComputed = false; var methodAccessor; var prototypeOrStatic = methodNode["static"] ? '' : '.prototype'; var objectAccessor = state.className + prototypeOrStatic; if (methodNode.key.type === Syntax.Identifier) { // foo() {} methodAccessor = methodNode.key.name; if (_shouldMungeIdentifier(methodNode.key, state)) { methodAccessor = _getMungedName(methodAccessor, state); } if (isGetter || isSetter) { methodAccessor = JSON.stringify(methodAccessor); } else if (reservedWordsHelper.isReservedWord(methodAccessor)) { methodAccessorComputed = true; methodAccessor = JSON.stringify(methodAccessor); } } else if (methodNode.key.type === Syntax.Literal) { // 'foo bar'() {} | get 'foo bar'() {} | set 'foo bar'() {} methodAccessor = JSON.stringify(methodNode.key.value); methodAccessorComputed = true; } if (isSetter || isGetter) { utils.append( 'Object.defineProperty(' + objectAccessor + ',' + methodAccessor + ',' + '{configurable:true,' + methodNode.kind + ':function', state ); } else { if (state.g.opts.es3) { if (methodAccessorComputed) { methodAccessor = '[' + methodAccessor + ']'; } else { methodAccessor = '.' + methodAccessor; } utils.append( objectAccessor + methodAccessor + '=function' + (node.generator ? '*' : ''), state ); } else { if (!methodAccessorComputed) { methodAccessor = JSON.stringify(methodAccessor); } utils.append( 'Object.defineProperty(' + objectAccessor + ',' + methodAccessor + ',' + '{writable:true,configurable:true,' + 'value:function' + (node.generator ? '*' : ''), state ); } } } utils.move(methodNode.key.range[1], state); utils.append('(', state); var params = node.params; if (params.length > 0) { utils.catchupNewlines(params[0].range[0], state); for (var i = 0; i < params.length; i++) { utils.catchup(node.params[i].range[0], state); path.unshift(node); traverse(params[i], path, state); path.shift(); } } var closingParenPosition = utils.getNextSyntacticCharOffset(')', state); utils.catchupWhiteSpace(closingParenPosition, state); var openingBracketPosition = utils.getNextSyntacticCharOffset('{', state); utils.catchup(openingBracketPosition + 1, state); if (!state.scopeIsStrict) { utils.append('"use strict";', state); state = utils.updateState(state, { scopeIsStrict: true }); } utils.move(node.body.range[0] + '{'.length, state); path.unshift(node); traverse(node.body, path, state); path.shift(); utils.catchup(node.body.range[1], state); if (methodNode.key.name !== 'constructor') { if (isGetter || isSetter || !state.g.opts.es3) { utils.append('})', state); } utils.append(';', state); } return false; } visitClassFunctionExpression.test = function(node, path, state) { return node.type === Syntax.FunctionExpression && path[0].type === Syntax.MethodDefinition; }; function visitClassMethodParam(traverse, node, path, state) { var paramName = node.name; if (_shouldMungeIdentifier(node, state)) { paramName = _getMungedName(node.name, state); } utils.append(paramName, state); utils.move(node.range[1], state); } visitClassMethodParam.test = function(node, path, state) { if (!path[0] || !path[1]) { return; } var parentFuncExpr = path[0]; var parentClassMethod = path[1]; return parentFuncExpr.type === Syntax.FunctionExpression && parentClassMethod.type === Syntax.MethodDefinition && node.type === Syntax.Identifier; }; /** * @param {function} traverse * @param {object} node * @param {array} path * @param {object} state */ function _renderClassBody(traverse, node, path, state) { var className = state.className; var superClass = state.superClass; // Set up prototype of constructor on same line as `extends` for line-number // preservation. This relies on function-hoisting if a constructor function is // defined in the class body. if (superClass.name) { // If the super class is an expression, we need to memoize the output of the // expression into the generated class name variable and use that to refer // to the super class going forward. Example: // // class Foo extends mixin(Bar, Baz) {} // --transforms to-- // function Foo() {} var ____Class0Blah = mixin(Bar, Baz); if (superClass.expression !== null) { utils.append( 'var ' + superClass.name + '=' + superClass.expression + ';', state ); } var keyName = superClass.name + '____Key'; var keyNameDeclarator = ''; if (!utils.identWithinLexicalScope(keyName, state)) { keyNameDeclarator = 'var '; declareIdentInLocalScope(keyName, initScopeMetadata(node), state); } utils.append( 'for(' + keyNameDeclarator + keyName + ' in ' + superClass.name + '){' + 'if(' + superClass.name + '.hasOwnProperty(' + keyName + ')){' + className + '[' + keyName + ']=' + superClass.name + '[' + keyName + '];' + '}' + '}', state ); var superProtoIdentStr = SUPER_PROTO_IDENT_PREFIX + superClass.name; if (!utils.identWithinLexicalScope(superProtoIdentStr, state)) { utils.append( 'var ' + superProtoIdentStr + '=' + superClass.name + '===null?' + 'null:' + superClass.name + '.prototype;', state ); declareIdentInLocalScope(superProtoIdentStr, initScopeMetadata(node), state); } utils.append( className + '.prototype=Object.create(' + superProtoIdentStr + ');', state ); utils.append( className + '.prototype.constructor=' + className + ';', state ); utils.append( className + '.__superConstructor__=' + superClass.name + ';', state ); } // If there's no constructor method specified in the class body, create an // empty constructor function at the top (same line as the class keyword) if (!node.body.body.filter(_isConstructorMethod).pop()) { utils.append('function ' + className + '(){', state); if (!state.scopeIsStrict) { utils.append('"use strict";', state); } if (superClass.name) { utils.append( 'if(' + superClass.name + '!==null){' + superClass.name + '.apply(this,arguments);}', state ); } utils.append('}', state); } utils.move(node.body.range[0] + '{'.length, state); traverse(node.body, path, state); utils.catchupWhiteSpace(node.range[1], state); } /** * @param {function} traverse * @param {object} node * @param {array} path * @param {object} state */ function visitClassDeclaration(traverse, node, path, state) { var className = node.id.name; var superClass = _getSuperClassInfo(node, state); state = utils.updateState(state, { mungeNamespace: className, className: className, superClass: superClass }); _renderClassBody(traverse, node, path, state); return false; } visitClassDeclaration.test = function(node, path, state) { return node.type === Syntax.ClassDeclaration; }; /** * @param {function} traverse * @param {object} node * @param {array} path * @param {object} state */ function visitClassExpression(traverse, node, path, state) { var className = node.id && node.id.name || _generateAnonymousClassName(state); var superClass = _getSuperClassInfo(node, state); utils.append('(function(){', state); state = utils.updateState(state, { mungeNamespace: className, className: className, superClass: superClass }); _renderClassBody(traverse, node, path, state); utils.append('return ' + className + ';})()', state); return false; } visitClassExpression.test = function(node, path, state) { return node.type === Syntax.ClassExpression; }; /** * @param {function} traverse * @param {object} node * @param {array} path * @param {object} state */ function visitPrivateIdentifier(traverse, node, path, state) { utils.append(_getMungedName(node.name, state), state); utils.move(node.range[1], state); } visitPrivateIdentifier.test = function(node, path, state) { if (node.type === Syntax.Identifier && _shouldMungeIdentifier(node, state)) { // Always munge non-computed properties of MemberExpressions // (a la preventing access of properties of unowned objects) if (path[0].type === Syntax.MemberExpression && path[0].object !== node && path[0].computed === false) { return true; } // Always munge identifiers that were declared within the method function // scope if (utils.identWithinLexicalScope(node.name, state, state.methodFuncNode)) { return true; } // Always munge private keys on object literals defined within a method's // scope. if (path[0].type === Syntax.Property && path[1].type === Syntax.ObjectExpression) { return true; } // Always munge function parameters if (path[0].type === Syntax.FunctionExpression || path[0].type === Syntax.FunctionDeclaration || path[0].type === Syntax.ArrowFunctionExpression) { for (var i = 0; i < path[0].params.length; i++) { if (path[0].params[i] === node) { return true; } } } } return false; }; /** * @param {function} traverse * @param {object} node * @param {array} path * @param {object} state */ function visitSuperCallExpression(traverse, node, path, state) { var superClassName = state.superClass.name; if (node.callee.type === Syntax.Identifier) { if (_isConstructorMethod(state.methodNode)) { utils.append(superClassName + '.call(', state); } else { var protoProp = SUPER_PROTO_IDENT_PREFIX + superClassName; if (state.methodNode.key.type === Syntax.Identifier) { protoProp += '.' + state.methodNode.key.name; } else if (state.methodNode.key.type === Syntax.Literal) { protoProp += '[' + JSON.stringify(state.methodNode.key.value) + ']'; } utils.append(protoProp + ".call(", state); } utils.move(node.callee.range[1], state); } else if (node.callee.type === Syntax.MemberExpression) { utils.append(SUPER_PROTO_IDENT_PREFIX + superClassName, state); utils.move(node.callee.object.range[1], state); if (node.callee.computed) { // ["a" + "b"] utils.catchup(node.callee.property.range[1] + ']'.length, state); } else { // .ab utils.append('.' + node.callee.property.name, state); } utils.append('.call(', state); utils.move(node.callee.range[1], state); } utils.append('this', state); if (node.arguments.length > 0) { utils.append(',', state); utils.catchupWhiteSpace(node.arguments[0].range[0], state); traverse(node.arguments, path, state); } utils.catchupWhiteSpace(node.range[1], state); utils.append(')', state); return false; } visitSuperCallExpression.test = function(node, path, state) { if (state.superClass && node.type === Syntax.CallExpression) { var callee = node.callee; if (callee.type === Syntax.Identifier && callee.name === 'super' || callee.type == Syntax.MemberExpression && callee.object.name === 'super') { return true; } } return false; }; /** * @param {function} traverse * @param {object} node * @param {array} path * @param {object} state */ function visitSuperMemberExpression(traverse, node, path, state) { var superClassName = state.superClass.name; utils.append(SUPER_PROTO_IDENT_PREFIX + superClassName, state); utils.move(node.object.range[1], state); } visitSuperMemberExpression.test = function(node, path, state) { return state.superClass && node.type === Syntax.MemberExpression && node.object.type === Syntax.Identifier && node.object.name === 'super'; }; exports.resetSymbols = resetSymbols; exports.visitorList = [ visitClassDeclaration, visitClassExpression, visitClassFunctionExpression, visitClassMethod, visitClassMethodParam, visitPrivateIdentifier, visitSuperCallExpression, visitSuperMemberExpression ]; },{"../src/utils":23,"./reserved-words-helper":34,"base62":10,"esprima-fb":9}],27:[function(_dereq_,module,exports){ /** * Copyright 2014 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*global exports:true*/ /** * Implements ES6 destructuring assignment and pattern matchng. * * function init({port, ip, coords: [x, y]}) { * return (x && y) ? {id, port} : {ip}; * }; * * function init($__0) { * var * port = $__0.port, * ip = $__0.ip, * $__1 = $__0.coords, * x = $__1[0], * y = $__1[1]; * return (x && y) ? {id, port} : {ip}; * } * * var x, {ip, port} = init({ip, port}); * * var x, $__0 = init({ip, port}), ip = $__0.ip, port = $__0.port; * */ var Syntax = _dereq_('esprima-fb').Syntax; var utils = _dereq_('../src/utils'); var reservedWordsHelper = _dereq_('./reserved-words-helper'); var restParamVisitors = _dereq_('./es6-rest-param-visitors'); var restPropertyHelpers = _dereq_('./es7-rest-property-helpers'); // ------------------------------------------------------- // 1. Structured variable declarations. // // var [a, b] = [b, a]; // var {x, y} = {y, x}; // ------------------------------------------------------- function visitStructuredVariable(traverse, node, path, state) { // Allocate new temp for the pattern. utils.append(utils.getTempVar(state.localScope.tempVarIndex) + '=', state); // Skip the pattern and assign the init to the temp. utils.catchupWhiteSpace(node.init.range[0], state); traverse(node.init, path, state); utils.catchup(node.init.range[1], state); // Render the destructured data. utils.append(',' + getDestructuredComponents(node.id, state), state); state.localScope.tempVarIndex++; return false; } visitStructuredVariable.test = function(node, path, state) { return node.type === Syntax.VariableDeclarator && isStructuredPattern(node.id); }; function isStructuredPattern(node) { return node.type === Syntax.ObjectPattern || node.type === Syntax.ArrayPattern; } // Main function which does actual recursive destructuring // of nested complex structures. function getDestructuredComponents(node, state) { var tmpIndex = state.localScope.tempVarIndex; var components = []; var patternItems = getPatternItems(node); for (var idx = 0; idx < patternItems.length; idx++) { var item = patternItems[idx]; if (!item) { continue; } if (item.type === Syntax.SpreadElement) { // Spread/rest of an array. // TODO(dmitrys): support spread in the middle of a pattern // and also for function param patterns: [x, ...xs, y] components.push(item.argument.name + '=Array.prototype.slice.call(' + utils.getTempVar(tmpIndex) + ',' + idx + ')' ); continue; } if (item.type === Syntax.SpreadProperty) { var restExpression = restPropertyHelpers.renderRestExpression( utils.getTempVar(tmpIndex), patternItems ); components.push(item.argument.name + '=' + restExpression); continue; } // Depending on pattern type (Array or Object), we get // corresponding pattern item parts. var accessor = getPatternItemAccessor(node, item, tmpIndex, idx); var value = getPatternItemValue(node, item); // TODO(dmitrys): implement default values: {x, y=5} if (value.type === Syntax.Identifier) { // Simple pattern item. components.push(value.name + '=' + accessor); } else { // Complex sub-structure. components.push( utils.getTempVar(++state.localScope.tempVarIndex) + '=' + accessor + ',' + getDestructuredComponents(value, state) ); } } return components.join(','); } function getPatternItems(node) { return node.properties || node.elements; } function getPatternItemAccessor(node, patternItem, tmpIndex, idx) { var tmpName = utils.getTempVar(tmpIndex); if (node.type === Syntax.ObjectPattern) { if (reservedWordsHelper.isReservedWord(patternItem.key.name)) { return tmpName + '["' + patternItem.key.name + '"]'; } else if (patternItem.key.type === Syntax.Literal) { return tmpName + '[' + JSON.stringify(patternItem.key.value) + ']'; } else if (patternItem.key.type === Syntax.Identifier) { return tmpName + '.' + patternItem.key.name; } } else if (node.type === Syntax.ArrayPattern) { return tmpName + '[' + idx + ']'; } } function getPatternItemValue(node, patternItem) { return node.type === Syntax.ObjectPattern ? patternItem.value : patternItem; } // ------------------------------------------------------- // 2. Assignment expression. // // [a, b] = [b, a]; // ({x, y} = {y, x}); // ------------------------------------------------------- function visitStructuredAssignment(traverse, node, path, state) { var exprNode = node.expression; utils.append('var ' + utils.getTempVar(state.localScope.tempVarIndex) + '=', state); utils.catchupWhiteSpace(exprNode.right.range[0], state); traverse(exprNode.right, path, state); utils.catchup(exprNode.right.range[1], state); utils.append( ';' + getDestructuredComponents(exprNode.left, state) + ';', state ); utils.catchupWhiteSpace(node.range[1], state); state.localScope.tempVarIndex++; return false; } visitStructuredAssignment.test = function(node, path, state) { // We consider the expression statement rather than just assignment // expression to cover case with object patters which should be // wrapped in grouping operator: ({x, y} = {y, x}); return node.type === Syntax.ExpressionStatement && node.expression.type === Syntax.AssignmentExpression && isStructuredPattern(node.expression.left); }; // ------------------------------------------------------- // 3. Structured parameter. // // function foo({x, y}) { ... } // ------------------------------------------------------- function visitStructuredParameter(traverse, node, path, state) { utils.append(utils.getTempVar(getParamIndex(node, path)), state); utils.catchupWhiteSpace(node.range[1], state); return true; } function getParamIndex(paramNode, path) { var funcNode = path[0]; var tmpIndex = 0; for (var k = 0; k < funcNode.params.length; k++) { var param = funcNode.params[k]; if (param === paramNode) { break; } if (isStructuredPattern(param)) { tmpIndex++; } } return tmpIndex; } visitStructuredParameter.test = function(node, path, state) { return isStructuredPattern(node) && isFunctionNode(path[0]); }; function isFunctionNode(node) { return (node.type == Syntax.FunctionDeclaration || node.type == Syntax.FunctionExpression || node.type == Syntax.MethodDefinition || node.type == Syntax.ArrowFunctionExpression); } // ------------------------------------------------------- // 4. Function body for structured parameters. // // function foo({x, y}) { x; y; } // ------------------------------------------------------- function visitFunctionBodyForStructuredParameter(traverse, node, path, state) { var funcNode = path[0]; utils.catchup(funcNode.body.range[0] + 1, state); renderDestructuredComponents(funcNode, state); if (funcNode.rest) { utils.append( restParamVisitors.renderRestParamSetup(funcNode, state), state ); } return true; } function renderDestructuredComponents(funcNode, state) { var destructuredComponents = []; for (var k = 0; k < funcNode.params.length; k++) { var param = funcNode.params[k]; if (isStructuredPattern(param)) { destructuredComponents.push( getDestructuredComponents(param, state) ); state.localScope.tempVarIndex++; } } if (destructuredComponents.length) { utils.append('var ' + destructuredComponents.join(',') + ';', state); } } visitFunctionBodyForStructuredParameter.test = function(node, path, state) { return node.type === Syntax.BlockStatement && isFunctionNode(path[0]); }; exports.visitorList = [ visitStructuredVariable, visitStructuredAssignment, visitStructuredParameter, visitFunctionBodyForStructuredParameter ]; exports.renderDestructuredComponents = renderDestructuredComponents; },{"../src/utils":23,"./es6-rest-param-visitors":30,"./es7-rest-property-helpers":32,"./reserved-words-helper":34,"esprima-fb":9}],28:[function(_dereq_,module,exports){ /** * Copyright 2013 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*jslint node:true*/ /** * Desugars concise methods of objects to function expressions. * * var foo = { * method(x, y) { ... } * }; * * var foo = { * method: function(x, y) { ... } * }; * */ var Syntax = _dereq_('esprima-fb').Syntax; var utils = _dereq_('../src/utils'); var reservedWordsHelper = _dereq_('./reserved-words-helper'); function visitObjectConciseMethod(traverse, node, path, state) { var isGenerator = node.value.generator; if (isGenerator) { utils.catchupWhiteSpace(node.range[0] + 1, state); } if (node.computed) { // [<expr>]() { ...} utils.catchup(node.key.range[1] + 1, state); } else if (reservedWordsHelper.isReservedWord(node.key.name)) { utils.catchup(node.key.range[0], state); utils.append('"', state); utils.catchup(node.key.range[1], state); utils.append('"', state); } utils.catchup(node.key.range[1], state); utils.append( ':function' + (isGenerator ? '*' : ''), state ); path.unshift(node); traverse(node.value, path, state); path.shift(); return false; } visitObjectConciseMethod.test = function(node, path, state) { return node.type === Syntax.Property && node.value.type === Syntax.FunctionExpression && node.method === true; }; exports.visitorList = [ visitObjectConciseMethod ]; },{"../src/utils":23,"./reserved-words-helper":34,"esprima-fb":9}],29:[function(_dereq_,module,exports){ /** * Copyright 2013 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*jslint node: true*/ /** * Desugars ES6 Object Literal short notations into ES3 full notation. * * // Easier return values. * function foo(x, y) { * return {x, y}; // {x: x, y: y} * }; * * // Destructuring. * function init({port, ip, coords: {x, y}}) { ... } * */ var Syntax = _dereq_('esprima-fb').Syntax; var utils = _dereq_('../src/utils'); /** * @public */ function visitObjectLiteralShortNotation(traverse, node, path, state) { utils.catchup(node.key.range[1], state); utils.append(':' + node.key.name, state); return false; } visitObjectLiteralShortNotation.test = function(node, path, state) { return node.type === Syntax.Property && node.kind === 'init' && node.shorthand === true && path[0].type !== Syntax.ObjectPattern; }; exports.visitorList = [ visitObjectLiteralShortNotation ]; },{"../src/utils":23,"esprima-fb":9}],30:[function(_dereq_,module,exports){ /** * Copyright 2013 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*jslint node:true*/ /** * Desugars ES6 rest parameters into an ES3 arguments array. * * function printf(template, ...args) { * args.forEach(...); * } * * We could use `Array.prototype.slice.call`, but that usage of arguments causes * functions to be deoptimized in V8, so instead we use a for-loop. * * function printf(template) { * for (var args = [], $__0 = 1, $__1 = arguments.length; $__0 < $__1; $__0++) * args.push(arguments[$__0]); * args.forEach(...); * } * */ var Syntax = _dereq_('esprima-fb').Syntax; var utils = _dereq_('../src/utils'); function _nodeIsFunctionWithRestParam(node) { return (node.type === Syntax.FunctionDeclaration || node.type === Syntax.FunctionExpression || node.type === Syntax.ArrowFunctionExpression) && node.rest; } function visitFunctionParamsWithRestParam(traverse, node, path, state) { if (node.parametricType) { utils.catchup(node.parametricType.range[0], state); path.unshift(node); traverse(node.parametricType, path, state); path.shift(); } // Render params. if (node.params.length) { path.unshift(node); traverse(node.params, path, state); path.shift(); } else { // -3 is for ... of the rest. utils.catchup(node.rest.range[0] - 3, state); } utils.catchupWhiteSpace(node.rest.range[1], state); path.unshift(node); traverse(node.body, path, state); path.shift(); return false; } visitFunctionParamsWithRestParam.test = function(node, path, state) { return _nodeIsFunctionWithRestParam(node); }; function renderRestParamSetup(functionNode, state) { var idx = state.localScope.tempVarIndex++; var len = state.localScope.tempVarIndex++; return 'for (var ' + functionNode.rest.name + '=[],' + utils.getTempVar(idx) + '=' + functionNode.params.length + ',' + utils.getTempVar(len) + '=arguments.length;' + utils.getTempVar(idx) + '<' + utils.getTempVar(len) + ';' + utils.getTempVar(idx) + '++) ' + functionNode.rest.name + '.push(arguments[' + utils.getTempVar(idx) + ']);'; } function visitFunctionBodyWithRestParam(traverse, node, path, state) { utils.catchup(node.range[0] + 1, state); var parentNode = path[0]; utils.append(renderRestParamSetup(parentNode, state), state); return true; } visitFunctionBodyWithRestParam.test = function(node, path, state) { return node.type === Syntax.BlockStatement && _nodeIsFunctionWithRestParam(path[0]); }; exports.renderRestParamSetup = renderRestParamSetup; exports.visitorList = [ visitFunctionParamsWithRestParam, visitFunctionBodyWithRestParam ]; },{"../src/utils":23,"esprima-fb":9}],31:[function(_dereq_,module,exports){ /** * Copyright 2013 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*jslint node:true*/ /** * @typechecks */ 'use strict'; var Syntax = _dereq_('esprima-fb').Syntax; var utils = _dereq_('../src/utils'); /** * http://people.mozilla.org/~jorendorff/es6-draft.html#sec-12.1.9 */ function visitTemplateLiteral(traverse, node, path, state) { var templateElements = node.quasis; utils.append('(', state); for (var ii = 0; ii < templateElements.length; ii++) { var templateElement = templateElements[ii]; if (templateElement.value.raw !== '') { utils.append(getCookedValue(templateElement), state); if (!templateElement.tail) { // + between element and substitution utils.append(' + ', state); } // maintain line numbers utils.move(templateElement.range[0], state); utils.catchupNewlines(templateElement.range[1], state); } else { // templateElement.value.raw === '' // Concatenat adjacent substitutions, e.g. `${x}${y}`. Empty templates // appear before the first and after the last element - nothing to add in // those cases. if (ii > 0 && !templateElement.tail) { // + between substitution and substitution utils.append(' + ', state); } } utils.move(templateElement.range[1], state); if (!templateElement.tail) { var substitution = node.expressions[ii]; if (substitution.type === Syntax.Identifier || substitution.type === Syntax.MemberExpression || substitution.type === Syntax.CallExpression) { utils.catchup(substitution.range[1], state); } else { utils.append('(', state); traverse(substitution, path, state); utils.catchup(substitution.range[1], state); utils.append(')', state); } // if next templateElement isn't empty... if (templateElements[ii + 1].value.cooked !== '') { utils.append(' + ', state); } } } utils.move(node.range[1], state); utils.append(')', state); return false; } visitTemplateLiteral.test = function(node, path, state) { return node.type === Syntax.TemplateLiteral; }; /** * http://people.mozilla.org/~jorendorff/es6-draft.html#sec-12.2.6 */ function visitTaggedTemplateExpression(traverse, node, path, state) { var template = node.quasi; var numQuasis = template.quasis.length; // print the tag utils.move(node.tag.range[0], state); traverse(node.tag, path, state); utils.catchup(node.tag.range[1], state); // print array of template elements utils.append('(function() { var siteObj = [', state); for (var ii = 0; ii < numQuasis; ii++) { utils.append(getCookedValue(template.quasis[ii]), state); if (ii !== numQuasis - 1) { utils.append(', ', state); } } utils.append(']; siteObj.raw = [', state); for (ii = 0; ii < numQuasis; ii++) { utils.append(getRawValue(template.quasis[ii]), state); if (ii !== numQuasis - 1) { utils.append(', ', state); } } utils.append( ']; Object.freeze(siteObj.raw); Object.freeze(siteObj); return siteObj; }()', state ); // print substitutions if (numQuasis > 1) { for (ii = 0; ii < template.expressions.length; ii++) { var expression = template.expressions[ii]; utils.append(', ', state); // maintain line numbers by calling catchupWhiteSpace over the whole // previous TemplateElement utils.move(template.quasis[ii].range[0], state); utils.catchupNewlines(template.quasis[ii].range[1], state); utils.move(expression.range[0], state); traverse(expression, path, state); utils.catchup(expression.range[1], state); } } // print blank lines to push the closing ) down to account for the final // TemplateElement. utils.catchupNewlines(node.range[1], state); utils.append(')', state); return false; } visitTaggedTemplateExpression.test = function(node, path, state) { return node.type === Syntax.TaggedTemplateExpression; }; function getCookedValue(templateElement) { return JSON.stringify(templateElement.value.cooked); } function getRawValue(templateElement) { return JSON.stringify(templateElement.value.raw); } exports.visitorList = [ visitTemplateLiteral, visitTaggedTemplateExpression ]; },{"../src/utils":23,"esprima-fb":9}],32:[function(_dereq_,module,exports){ /** * Copyright 2013 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*jslint node:true*/ /** * Desugars ES7 rest properties into ES5 object iteration. */ var Syntax = _dereq_('esprima-fb').Syntax; // TODO: This is a pretty massive helper, it should only be defined once, in the // transform's runtime environment. We don't currently have a runtime though. var restFunction = '(function(source, exclusion) {' + 'var rest = {};' + 'var hasOwn = Object.prototype.hasOwnProperty;' + 'if (source == null) {' + 'throw new TypeError();' + '}' + 'for (var key in source) {' + 'if (hasOwn.call(source, key) && !hasOwn.call(exclusion, key)) {' + 'rest[key] = source[key];' + '}' + '}' + 'return rest;' + '})'; function getPropertyNames(properties) { var names = []; for (var i = 0; i < properties.length; i++) { var property = properties[i]; if (property.type === Syntax.SpreadProperty) { continue; } if (property.type === Syntax.Identifier) { names.push(property.name); } else { names.push(property.key.name); } } return names; } function getRestFunctionCall(source, exclusion) { return restFunction + '(' + source + ',' + exclusion + ')'; } function getSimpleShallowCopy(accessorExpression) { // This could be faster with 'Object.assign({}, ' + accessorExpression + ')' // but to unify code paths and avoid a ES6 dependency we use the same // helper as for the exclusion case. return getRestFunctionCall(accessorExpression, '{}'); } function renderRestExpression(accessorExpression, excludedProperties) { var excludedNames = getPropertyNames(excludedProperties); if (!excludedNames.length) { return getSimpleShallowCopy(accessorExpression); } return getRestFunctionCall( accessorExpression, '{' + excludedNames.join(':1,') + ':1}' ); } exports.renderRestExpression = renderRestExpression; },{"esprima-fb":9}],33:[function(_dereq_,module,exports){ /** * Copyright 2004-present Facebook. All Rights Reserved. */ /*global exports:true*/ /** * Implements ES7 object spread property. * https://gist.github.com/sebmarkbage/aa849c7973cb4452c547 * * { ...a, x: 1 } * * Object.assign({}, a, {x: 1 }) * */ var Syntax = _dereq_('esprima-fb').Syntax; var utils = _dereq_('../src/utils'); function visitObjectLiteralSpread(traverse, node, path, state) { utils.catchup(node.range[0], state); utils.append('Object.assign({', state); // Skip the original { utils.move(node.range[0] + 1, state); var previousWasSpread = false; for (var i = 0; i < node.properties.length; i++) { var property = node.properties[i]; if (property.type === Syntax.SpreadProperty) { // Close the previous object or initial object if (!previousWasSpread) { utils.append('}', state); } if (i === 0) { // Normally there will be a comma when we catch up, but not before // the first property. utils.append(',', state); } utils.catchup(property.range[0], state); // skip ... utils.move(property.range[0] + 3, state); traverse(property.argument, path, state); utils.catchup(property.range[1], state); previousWasSpread = true; } else { utils.catchup(property.range[0], state); if (previousWasSpread) { utils.append('{', state); } traverse(property, path, state); utils.catchup(property.range[1], state); previousWasSpread = false; } } // Strip any non-whitespace between the last item and the end. // We only catch up on whitespace so that we ignore any trailing commas which // are stripped out for IE8 support. Unfortunately, this also strips out any // trailing comments. utils.catchupWhiteSpace(node.range[1] - 1, state); // Skip the trailing } utils.move(node.range[1], state); if (!previousWasSpread) { utils.append('}', state); } utils.append(')', state); return false; } visitObjectLiteralSpread.test = function(node, path, state) { if (node.type !== Syntax.ObjectExpression) { return false; } // Tight loop optimization var hasAtLeastOneSpreadProperty = false; for (var i = 0; i < node.properties.length; i++) { var property = node.properties[i]; if (property.type === Syntax.SpreadProperty) { hasAtLeastOneSpreadProperty = true; } else if (property.kind !== 'init') { return false; } } return hasAtLeastOneSpreadProperty; }; exports.visitorList = [ visitObjectLiteralSpread ]; },{"../src/utils":23,"esprima-fb":9}],34:[function(_dereq_,module,exports){ /** * Copyright 2014 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var KEYWORDS = [ 'break', 'do', 'in', 'typeof', 'case', 'else', 'instanceof', 'var', 'catch', 'export', 'new', 'void', 'class', 'extends', 'return', 'while', 'const', 'finally', 'super', 'with', 'continue', 'for', 'switch', 'yield', 'debugger', 'function', 'this', 'default', 'if', 'throw', 'delete', 'import', 'try' ]; var FUTURE_RESERVED_WORDS = [ 'enum', 'await', 'implements', 'package', 'protected', 'static', 'interface', 'private', 'public' ]; var LITERALS = [ 'null', 'true', 'false' ]; // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-reserved-words var RESERVED_WORDS = [].concat( KEYWORDS, FUTURE_RESERVED_WORDS, LITERALS ); var reservedWordsMap = Object.create(null); RESERVED_WORDS.forEach(function(k) { reservedWordsMap[k] = true; }); /** * This list should not grow as new reserved words are introdued. This list is * of words that need to be quoted because ES3-ish browsers do not allow their * use as identifier names. */ var ES3_FUTURE_RESERVED_WORDS = [ 'enum', 'implements', 'package', 'protected', 'static', 'interface', 'private', 'public' ]; var ES3_RESERVED_WORDS = [].concat( KEYWORDS, ES3_FUTURE_RESERVED_WORDS, LITERALS ); var es3ReservedWordsMap = Object.create(null); ES3_RESERVED_WORDS.forEach(function(k) { es3ReservedWordsMap[k] = true; }); exports.isReservedWord = function(word) { return !!reservedWordsMap[word]; }; exports.isES3ReservedWord = function(word) { return !!es3ReservedWordsMap[word]; }; },{}],35:[function(_dereq_,module,exports){ /** * Copyright 2014 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /*global exports:true*/ var Syntax = _dereq_('esprima-fb').Syntax; var utils = _dereq_('../src/utils'); var reserverdWordsHelper = _dereq_('./reserved-words-helper'); /** * Code adapted from https://github.com/spicyj/es3ify * The MIT License (MIT) * Copyright (c) 2014 Ben Alpert */ function visitProperty(traverse, node, path, state) { utils.catchup(node.key.range[0], state); utils.append('"', state); utils.catchup(node.key.range[1], state); utils.append('"', state); utils.catchup(node.value.range[0], state); traverse(node.value, path, state); return false; } visitProperty.test = function(node) { return node.type === Syntax.Property && node.key.type === Syntax.Identifier && !node.method && !node.shorthand && !node.computed && reserverdWordsHelper.isES3ReservedWord(node.key.name); }; function visitMemberExpression(traverse, node, path, state) { traverse(node.object, path, state); utils.catchup(node.property.range[0] - 1, state); utils.append('[', state); utils.catchupWhiteSpace(node.property.range[0], state); utils.append('"', state); utils.catchup(node.property.range[1], state); utils.append('"]', state); return false; } visitMemberExpression.test = function(node) { return node.type === Syntax.MemberExpression && node.property.type === Syntax.Identifier && reserverdWordsHelper.isES3ReservedWord(node.property.name); }; exports.visitorList = [ visitProperty, visitMemberExpression ]; },{"../src/utils":23,"./reserved-words-helper":34,"esprima-fb":9}],36:[function(_dereq_,module,exports){ var esprima = _dereq_('esprima-fb'); var utils = _dereq_('../src/utils'); var Syntax = esprima.Syntax; function _isFunctionNode(node) { return node.type === Syntax.FunctionDeclaration || node.type === Syntax.FunctionExpression || node.type === Syntax.ArrowFunctionExpression; } function visitClassProperty(traverse, node, path, state) { utils.catchup(node.range[0], state); utils.catchupWhiteOut(node.range[1], state); return false; } visitClassProperty.test = function(node, path, state) { return node.type === Syntax.ClassProperty; }; function visitTypeAlias(traverse, node, path, state) { utils.catchupWhiteOut(node.range[1], state); return false; } visitTypeAlias.test = function(node, path, state) { return node.type === Syntax.TypeAlias; }; function visitTypeCast(traverse, node, path, state) { path.unshift(node); traverse(node.expression, path, state); path.shift(); utils.catchup(node.typeAnnotation.range[0], state); utils.catchupWhiteOut(node.typeAnnotation.range[1], state); return false; } visitTypeCast.test = function(node, path, state) { return node.type === Syntax.TypeCastExpression; }; function visitInterfaceDeclaration(traverse, node, path, state) { utils.catchupWhiteOut(node.range[1], state); return false; } visitInterfaceDeclaration.test = function(node, path, state) { return node.type === Syntax.InterfaceDeclaration; }; function visitDeclare(traverse, node, path, state) { utils.catchupWhiteOut(node.range[1], state); return false; } visitDeclare.test = function(node, path, state) { switch (node.type) { case Syntax.DeclareVariable: case Syntax.DeclareFunction: case Syntax.DeclareClass: case Syntax.DeclareModule: return true; } return false; }; function visitFunctionParametricAnnotation(traverse, node, path, state) { utils.catchup(node.range[0], state); utils.catchupWhiteOut(node.range[1], state); return false; } visitFunctionParametricAnnotation.test = function(node, path, state) { return node.type === Syntax.TypeParameterDeclaration && path[0] && _isFunctionNode(path[0]) && node === path[0].typeParameters; }; function visitFunctionReturnAnnotation(traverse, node, path, state) { utils.catchup(node.range[0], state); utils.catchupWhiteOut(node.range[1], state); return false; } visitFunctionReturnAnnotation.test = function(node, path, state) { return path[0] && _isFunctionNode(path[0]) && node === path[0].returnType; }; function visitOptionalFunctionParameterAnnotation(traverse, node, path, state) { utils.catchup(node.range[0] + node.name.length, state); utils.catchupWhiteOut(node.range[1], state); return false; } visitOptionalFunctionParameterAnnotation.test = function(node, path, state) { return node.type === Syntax.Identifier && node.optional && path[0] && _isFunctionNode(path[0]); }; function visitTypeAnnotatedIdentifier(traverse, node, path, state) { utils.catchup(node.typeAnnotation.range[0], state); utils.catchupWhiteOut(node.typeAnnotation.range[1], state); return false; } visitTypeAnnotatedIdentifier.test = function(node, path, state) { return node.type === Syntax.Identifier && node.typeAnnotation; }; function visitTypeAnnotatedObjectOrArrayPattern(traverse, node, path, state) { utils.catchup(node.typeAnnotation.range[0], state); utils.catchupWhiteOut(node.typeAnnotation.range[1], state); return false; } visitTypeAnnotatedObjectOrArrayPattern.test = function(node, path, state) { var rightType = node.type === Syntax.ObjectPattern || node.type === Syntax.ArrayPattern; return rightType && node.typeAnnotation; }; /** * Methods cause trouble, since esprima parses them as a key/value pair, where * the location of the value starts at the method body. For example * { bar(x:number,...y:Array<number>):number {} } * is parsed as * { bar: function(x: number, ...y:Array<number>): number {} } * except that the location of the FunctionExpression value is 40-something, * which is the location of the function body. This means that by the time we * visit the params, rest param, and return type organically, we've already * catchup()'d passed them. */ function visitMethod(traverse, node, path, state) { path.unshift(node); traverse(node.key, path, state); path.unshift(node.value); traverse(node.value.params, path, state); node.value.rest && traverse(node.value.rest, path, state); node.value.returnType && traverse(node.value.returnType, path, state); traverse(node.value.body, path, state); path.shift(); path.shift(); return false; } visitMethod.test = function(node, path, state) { return (node.type === "Property" && (node.method || node.kind === "set" || node.kind === "get")) || (node.type === "MethodDefinition"); }; function visitImportType(traverse, node, path, state) { utils.catchupWhiteOut(node.range[1], state); return false; } visitImportType.test = function(node, path, state) { return node.type === 'ImportDeclaration' && node.isType; }; exports.visitorList = [ visitClassProperty, visitDeclare, visitImportType, visitInterfaceDeclaration, visitFunctionParametricAnnotation, visitFunctionReturnAnnotation, visitMethod, visitOptionalFunctionParameterAnnotation, visitTypeAlias, visitTypeCast, visitTypeAnnotatedIdentifier, visitTypeAnnotatedObjectOrArrayPattern ]; },{"../src/utils":23,"esprima-fb":9}],37:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ /*global exports:true*/ 'use strict'; var Syntax = _dereq_('jstransform').Syntax; var utils = _dereq_('jstransform/src/utils'); function renderJSXLiteral(object, isLast, state, start, end) { var lines = object.value.split(/\r\n|\n|\r/); if (start) { utils.append(start, state); } var lastNonEmptyLine = 0; lines.forEach(function(line, index) { if (line.match(/[^ \t]/)) { lastNonEmptyLine = index; } }); lines.forEach(function(line, index) { var isFirstLine = index === 0; var isLastLine = index === lines.length - 1; var isLastNonEmptyLine = index === lastNonEmptyLine; // replace rendered whitespace tabs with spaces var trimmedLine = line.replace(/\t/g, ' '); // trim whitespace touching a newline if (!isFirstLine) { trimmedLine = trimmedLine.replace(/^[ ]+/, ''); } if (!isLastLine) { trimmedLine = trimmedLine.replace(/[ ]+$/, ''); } if (!isFirstLine) { utils.append(line.match(/^[ \t]*/)[0], state); } if (trimmedLine || isLastNonEmptyLine) { utils.append( JSON.stringify(trimmedLine) + (!isLastNonEmptyLine ? ' + \' \' +' : ''), state); if (isLastNonEmptyLine) { if (end) { utils.append(end, state); } if (!isLast) { utils.append(', ', state); } } // only restore tail whitespace if line had literals if (trimmedLine && !isLastLine) { utils.append(line.match(/[ \t]*$/)[0], state); } } if (!isLastLine) { utils.append('\n', state); } }); utils.move(object.range[1], state); } function renderJSXExpressionContainer(traverse, object, isLast, path, state) { // Plus 1 to skip `{`. utils.move(object.range[0] + 1, state); utils.catchup(object.expression.range[0], state); traverse(object.expression, path, state); if (!isLast && object.expression.type !== Syntax.JSXEmptyExpression) { // If we need to append a comma, make sure to do so after the expression. utils.catchup(object.expression.range[1], state, trimLeft); utils.append(', ', state); } // Minus 1 to skip `}`. utils.catchup(object.range[1] - 1, state, trimLeft); utils.move(object.range[1], state); return false; } function quoteAttrName(attr) { // Quote invalid JS identifiers. if (!/^[a-z_$][a-z\d_$]*$/i.test(attr)) { return '"' + attr + '"'; } return attr; } function trimLeft(value) { return value.replace(/^[ ]+/, ''); } exports.renderJSXExpressionContainer = renderJSXExpressionContainer; exports.renderJSXLiteral = renderJSXLiteral; exports.quoteAttrName = quoteAttrName; exports.trimLeft = trimLeft; },{"jstransform":22,"jstransform/src/utils":23}],38:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ /*global exports:true*/ 'use strict'; var Syntax = _dereq_('jstransform').Syntax; var utils = _dereq_('jstransform/src/utils'); var renderJSXExpressionContainer = _dereq_('./jsx').renderJSXExpressionContainer; var renderJSXLiteral = _dereq_('./jsx').renderJSXLiteral; var quoteAttrName = _dereq_('./jsx').quoteAttrName; var trimLeft = _dereq_('./jsx').trimLeft; /** * Customized desugar processor for React JSX. Currently: * * <X> </X> => React.createElement(X, null) * <X prop="1" /> => React.createElement(X, {prop: '1'}, null) * <X prop="2"><Y /></X> => React.createElement(X, {prop:'2'}, * React.createElement(Y, null) * ) * <div /> => React.createElement("div", null) */ /** * Removes all non-whitespace/parenthesis characters */ var reNonWhiteParen = /([^\s\(\)])/g; function stripNonWhiteParen(value) { return value.replace(reNonWhiteParen, ''); } var tagConvention = /^[a-z]|\-/; function isTagName(name) { return tagConvention.test(name); } function visitReactTag(traverse, object, path, state) { var openingElement = object.openingElement; var nameObject = openingElement.name; var attributesObject = openingElement.attributes; utils.catchup(openingElement.range[0], state, trimLeft); if (nameObject.type === Syntax.JSXNamespacedName && nameObject.namespace) { throw new Error('Namespace tags are not supported. ReactJSX is not XML.'); } // We assume that the React runtime is already in scope utils.append('React.createElement(', state); if (nameObject.type === Syntax.JSXIdentifier && isTagName(nameObject.name)) { utils.append('"' + nameObject.name + '"', state); utils.move(nameObject.range[1], state); } else { // Use utils.catchup in this case so we can easily handle // JSXMemberExpressions which look like Foo.Bar.Baz. This also handles // JSXIdentifiers that aren't fallback tags. utils.move(nameObject.range[0], state); utils.catchup(nameObject.range[1], state); } utils.append(', ', state); var hasAttributes = attributesObject.length; var hasAtLeastOneSpreadProperty = attributesObject.some(function(attr) { return attr.type === Syntax.JSXSpreadAttribute; }); // if we don't have any attributes, pass in null if (hasAtLeastOneSpreadProperty) { utils.append('React.__spread({', state); } else if (hasAttributes) { utils.append('{', state); } else { utils.append('null', state); } // keep track of if the previous attribute was a spread attribute var previousWasSpread = false; // write attributes attributesObject.forEach(function(attr, index) { var isLast = index === attributesObject.length - 1; if (attr.type === Syntax.JSXSpreadAttribute) { // Close the previous object or initial object if (!previousWasSpread) { utils.append('}, ', state); } // Move to the expression start, ignoring everything except parenthesis // and whitespace. utils.catchup(attr.range[0], state, stripNonWhiteParen); // Plus 1 to skip `{`. utils.move(attr.range[0] + 1, state); utils.catchup(attr.argument.range[0], state, stripNonWhiteParen); traverse(attr.argument, path, state); utils.catchup(attr.argument.range[1], state); // Move to the end, ignoring parenthesis and the closing `}` utils.catchup(attr.range[1] - 1, state, stripNonWhiteParen); if (!isLast) { utils.append(', ', state); } utils.move(attr.range[1], state); previousWasSpread = true; return; } // If the next attribute is a spread, we're effective last in this object if (!isLast) { isLast = attributesObject[index + 1].type === Syntax.JSXSpreadAttribute; } if (attr.name.namespace) { throw new Error( 'Namespace attributes are not supported. ReactJSX is not XML.'); } var name = attr.name.name; utils.catchup(attr.range[0], state, trimLeft); if (previousWasSpread) { utils.append('{', state); } utils.append(quoteAttrName(name), state); utils.append(': ', state); if (!attr.value) { state.g.buffer += 'true'; state.g.position = attr.name.range[1]; if (!isLast) { utils.append(', ', state); } } else { utils.move(attr.name.range[1], state); // Use catchupNewlines to skip over the '=' in the attribute utils.catchupNewlines(attr.value.range[0], state); if (attr.value.type === Syntax.Literal) { renderJSXLiteral(attr.value, isLast, state); } else { renderJSXExpressionContainer(traverse, attr.value, isLast, path, state); } } utils.catchup(attr.range[1], state, trimLeft); previousWasSpread = false; }); if (!openingElement.selfClosing) { utils.catchup(openingElement.range[1] - 1, state, trimLeft); utils.move(openingElement.range[1], state); } if (hasAttributes && !previousWasSpread) { utils.append('}', state); } if (hasAtLeastOneSpreadProperty) { utils.append(')', state); } // filter out whitespace var childrenToRender = object.children.filter(function(child) { return !(child.type === Syntax.Literal && typeof child.value === 'string' && child.value.match(/^[ \t]*[\r\n][ \t\r\n]*$/)); }); if (childrenToRender.length > 0) { var lastRenderableIndex; childrenToRender.forEach(function(child, index) { if (child.type !== Syntax.JSXExpressionContainer || child.expression.type !== Syntax.JSXEmptyExpression) { lastRenderableIndex = index; } }); if (lastRenderableIndex !== undefined) { utils.append(', ', state); } childrenToRender.forEach(function(child, index) { utils.catchup(child.range[0], state, trimLeft); var isLast = index >= lastRenderableIndex; if (child.type === Syntax.Literal) { renderJSXLiteral(child, isLast, state); } else if (child.type === Syntax.JSXExpressionContainer) { renderJSXExpressionContainer(traverse, child, isLast, path, state); } else { traverse(child, path, state); if (!isLast) { utils.append(', ', state); } } utils.catchup(child.range[1], state, trimLeft); }); } if (openingElement.selfClosing) { // everything up to /> utils.catchup(openingElement.range[1] - 2, state, trimLeft); utils.move(openingElement.range[1], state); } else { // everything up to </ sdflksjfd> utils.catchup(object.closingElement.range[0], state, trimLeft); utils.move(object.closingElement.range[1], state); } utils.append(')', state); return false; } visitReactTag.test = function(object, path, state) { return object.type === Syntax.JSXElement; }; exports.visitorList = [ visitReactTag ]; },{"./jsx":37,"jstransform":22,"jstransform/src/utils":23}],39:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ /*global exports:true*/ 'use strict'; var Syntax = _dereq_('jstransform').Syntax; var utils = _dereq_('jstransform/src/utils'); function addDisplayName(displayName, object, state) { if (object && object.type === Syntax.CallExpression && object.callee.type === Syntax.MemberExpression && object.callee.object.type === Syntax.Identifier && object.callee.object.name === 'React' && object.callee.property.type === Syntax.Identifier && object.callee.property.name === 'createClass' && object.arguments.length === 1 && object.arguments[0].type === Syntax.ObjectExpression) { // Verify that the displayName property isn't already set var properties = object.arguments[0].properties; var safe = properties.every(function(property) { var value = property.key.type === Syntax.Identifier ? property.key.name : property.key.value; return value !== 'displayName'; }); if (safe) { utils.catchup(object.arguments[0].range[0] + 1, state); utils.append('displayName: "' + displayName + '",', state); } } } /** * Transforms the following: * * var MyComponent = React.createClass({ * render: ... * }); * * into: * * var MyComponent = React.createClass({ * displayName: 'MyComponent', * render: ... * }); * * Also catches: * * MyComponent = React.createClass(...); * exports.MyComponent = React.createClass(...); * module.exports = {MyComponent: React.createClass(...)}; */ function visitReactDisplayName(traverse, object, path, state) { var left, right; if (object.type === Syntax.AssignmentExpression) { left = object.left; right = object.right; } else if (object.type === Syntax.Property) { left = object.key; right = object.value; } else if (object.type === Syntax.VariableDeclarator) { left = object.id; right = object.init; } if (left && left.type === Syntax.MemberExpression) { left = left.property; } if (left && left.type === Syntax.Identifier) { addDisplayName(left.name, right, state); } } visitReactDisplayName.test = function(object, path, state) { return ( object.type === Syntax.AssignmentExpression || object.type === Syntax.Property || object.type === Syntax.VariableDeclarator ); }; exports.visitorList = [ visitReactDisplayName ]; },{"jstransform":22,"jstransform/src/utils":23}],40:[function(_dereq_,module,exports){ /*global exports:true*/ 'use strict'; var es6ArrowFunctions = _dereq_('jstransform/visitors/es6-arrow-function-visitors'); var es6Classes = _dereq_('jstransform/visitors/es6-class-visitors'); var es6Destructuring = _dereq_('jstransform/visitors/es6-destructuring-visitors'); var es6ObjectConciseMethod = _dereq_('jstransform/visitors/es6-object-concise-method-visitors'); var es6ObjectShortNotation = _dereq_('jstransform/visitors/es6-object-short-notation-visitors'); var es6RestParameters = _dereq_('jstransform/visitors/es6-rest-param-visitors'); var es6Templates = _dereq_('jstransform/visitors/es6-template-visitors'); var es6CallSpread = _dereq_('jstransform/visitors/es6-call-spread-visitors'); var es7SpreadProperty = _dereq_('jstransform/visitors/es7-spread-property-visitors'); var react = _dereq_('./transforms/react'); var reactDisplayName = _dereq_('./transforms/reactDisplayName'); var reservedWords = _dereq_('jstransform/visitors/reserved-words-visitors'); /** * Map from transformName => orderedListOfVisitors. */ var transformVisitors = { 'es6-arrow-functions': es6ArrowFunctions.visitorList, 'es6-classes': es6Classes.visitorList, 'es6-destructuring': es6Destructuring.visitorList, 'es6-object-concise-method': es6ObjectConciseMethod.visitorList, 'es6-object-short-notation': es6ObjectShortNotation.visitorList, 'es6-rest-params': es6RestParameters.visitorList, 'es6-templates': es6Templates.visitorList, 'es6-call-spread': es6CallSpread.visitorList, 'es7-spread-property': es7SpreadProperty.visitorList, 'react': react.visitorList.concat(reactDisplayName.visitorList), 'reserved-words': reservedWords.visitorList }; var transformSets = { 'harmony': [ 'es6-arrow-functions', 'es6-object-concise-method', 'es6-object-short-notation', 'es6-classes', 'es6-rest-params', 'es6-templates', 'es6-destructuring', 'es6-call-spread', 'es7-spread-property' ], 'es3': [ 'reserved-words' ], 'react': [ 'react' ] }; /** * Specifies the order in which each transform should run. */ var transformRunOrder = [ 'reserved-words', 'es6-arrow-functions', 'es6-object-concise-method', 'es6-object-short-notation', 'es6-classes', 'es6-rest-params', 'es6-templates', 'es6-destructuring', 'es6-call-spread', 'es7-spread-property', 'react' ]; /** * Given a list of transform names, return the ordered list of visitors to be * passed to the transform() function. * * @param {array?} excludes * @return {array} */ function getAllVisitors(excludes) { var ret = []; for (var i = 0, il = transformRunOrder.length; i < il; i++) { if (!excludes || excludes.indexOf(transformRunOrder[i]) === -1) { ret = ret.concat(transformVisitors[transformRunOrder[i]]); } } return ret; } /** * Given a list of visitor set names, return the ordered list of visitors to be * passed to jstransform. * * @param {array} * @return {array} */ function getVisitorsBySet(sets) { var visitorsToInclude = sets.reduce(function(visitors, set) { if (!transformSets.hasOwnProperty(set)) { throw new Error('Unknown visitor set: ' + set); } transformSets[set].forEach(function(visitor) { visitors[visitor] = true; }); return visitors; }, {}); var visitorList = []; for (var i = 0; i < transformRunOrder.length; i++) { if (visitorsToInclude.hasOwnProperty(transformRunOrder[i])) { visitorList = visitorList.concat(transformVisitors[transformRunOrder[i]]); } } return visitorList; } exports.getVisitorsBySet = getVisitorsBySet; exports.getAllVisitors = getAllVisitors; exports.transformVisitors = transformVisitors; },{"./transforms/react":38,"./transforms/reactDisplayName":39,"jstransform/visitors/es6-arrow-function-visitors":24,"jstransform/visitors/es6-call-spread-visitors":25,"jstransform/visitors/es6-class-visitors":26,"jstransform/visitors/es6-destructuring-visitors":27,"jstransform/visitors/es6-object-concise-method-visitors":28,"jstransform/visitors/es6-object-short-notation-visitors":29,"jstransform/visitors/es6-rest-param-visitors":30,"jstransform/visitors/es6-template-visitors":31,"jstransform/visitors/es7-spread-property-visitors":33,"jstransform/visitors/reserved-words-visitors":35}],41:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ 'use strict'; /*eslint-disable no-undef*/ var Buffer = _dereq_('buffer').Buffer; function inlineSourceMap(sourceMap, sourceCode, sourceFilename) { // This can be used with a sourcemap that has already has toJSON called on it. // Check first. var json = sourceMap; if (typeof sourceMap.toJSON === 'function') { json = sourceMap.toJSON(); } json.sources = [sourceFilename]; json.sourcesContent = [sourceCode]; var base64 = Buffer(JSON.stringify(json)).toString('base64'); return '//# sourceMappingURL=data:application/json;base64,' + base64; } module.exports = inlineSourceMap; },{"buffer":3}]},{},[1])(1) });
ajax/libs/yui/3.16.0/scrollview-base/scrollview-base-coverage.js
jakubfiala/cdnjs
/* YUI 3.16.0 (build 76f0e08) Copyright 2014 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ if (typeof __coverage__ === 'undefined') { __coverage__ = {}; } if (!__coverage__['build/scrollview-base/scrollview-base.js']) { __coverage__['build/scrollview-base/scrollview-base.js'] = {"path":"build/scrollview-base/scrollview-base.js","s":{"1":0,"2":0,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0,"13":0,"14":0,"15":0,"16":0,"17":0,"18":0,"19":0,"20":0,"21":0,"22":0,"23":0,"24":0,"25":0,"26":0,"27":0,"28":0,"29":0,"30":0,"31":0,"32":0,"33":0,"34":0,"35":0,"36":0,"37":0,"38":0,"39":0,"40":0,"41":0,"42":0,"43":0,"44":0,"45":0,"46":0,"47":0,"48":0,"49":0,"50":0,"51":0,"52":0,"53":0,"54":0,"55":0,"56":0,"57":0,"58":0,"59":0,"60":0,"61":0,"62":0,"63":0,"64":0,"65":0,"66":0,"67":0,"68":0,"69":0,"70":0,"71":0,"72":0,"73":0,"74":0,"75":0,"76":0,"77":0,"78":0,"79":0,"80":0,"81":0,"82":0,"83":0,"84":0,"85":0,"86":0,"87":0,"88":0,"89":0,"90":0,"91":0,"92":0,"93":0,"94":0,"95":0,"96":0,"97":0,"98":0,"99":0,"100":0,"101":0,"102":0,"103":0,"104":0,"105":0,"106":0,"107":0,"108":0,"109":0,"110":0,"111":0,"112":0,"113":0,"114":0,"115":0,"116":0,"117":0,"118":0,"119":0,"120":0,"121":0,"122":0,"123":0,"124":0,"125":0,"126":0,"127":0,"128":0,"129":0,"130":0,"131":0,"132":0,"133":0,"134":0,"135":0,"136":0,"137":0,"138":0,"139":0,"140":0,"141":0,"142":0,"143":0,"144":0,"145":0,"146":0,"147":0,"148":0,"149":0,"150":0,"151":0,"152":0,"153":0,"154":0,"155":0,"156":0,"157":0,"158":0,"159":0,"160":0,"161":0,"162":0,"163":0,"164":0,"165":0,"166":0,"167":0,"168":0,"169":0,"170":0,"171":0,"172":0,"173":0,"174":0,"175":0,"176":0,"177":0,"178":0,"179":0,"180":0,"181":0,"182":0,"183":0,"184":0,"185":0,"186":0,"187":0,"188":0,"189":0,"190":0,"191":0,"192":0,"193":0,"194":0,"195":0,"196":0,"197":0,"198":0,"199":0,"200":0,"201":0,"202":0,"203":0,"204":0,"205":0,"206":0,"207":0,"208":0,"209":0,"210":0,"211":0,"212":0,"213":0,"214":0,"215":0,"216":0,"217":0,"218":0,"219":0,"220":0,"221":0,"222":0,"223":0},"b":{"1":[0,0],"2":[0,0],"3":[0,0],"4":[0,0],"5":[0,0],"6":[0,0],"7":[0,0],"8":[0,0],"9":[0,0],"10":[0,0],"11":[0,0],"12":[0,0],"13":[0,0],"14":[0,0],"15":[0,0],"16":[0,0],"17":[0,0],"18":[0,0],"19":[0,0],"20":[0,0],"21":[0,0],"22":[0,0],"23":[0,0],"24":[0,0],"25":[0,0],"26":[0,0],"27":[0,0],"28":[0,0],"29":[0,0],"30":[0,0],"31":[0,0],"32":[0,0],"33":[0,0],"34":[0,0],"35":[0,0],"36":[0,0],"37":[0,0],"38":[0,0],"39":[0,0],"40":[0,0],"41":[0,0],"42":[0,0],"43":[0,0],"44":[0,0],"45":[0,0],"46":[0,0],"47":[0,0],"48":[0,0],"49":[0,0],"50":[0,0],"51":[0,0,0],"52":[0,0],"53":[0,0],"54":[0,0],"55":[0,0],"56":[0,0],"57":[0,0],"58":[0,0],"59":[0,0],"60":[0,0],"61":[0,0],"62":[0,0],"63":[0,0],"64":[0,0,0],"65":[0,0],"66":[0,0],"67":[0,0],"68":[0,0],"69":[0,0],"70":[0,0],"71":[0,0],"72":[0,0],"73":[0,0],"74":[0,0],"75":[0,0,0,0,0,0],"76":[0,0],"77":[0,0],"78":[0,0],"79":[0,0],"80":[0,0],"81":[0,0],"82":[0,0],"83":[0,0],"84":[0,0],"85":[0,0],"86":[0,0]},"f":{"1":0,"2":0,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0,"13":0,"14":0,"15":0,"16":0,"17":0,"18":0,"19":0,"20":0,"21":0,"22":0,"23":0,"24":0,"25":0,"26":0,"27":0,"28":0,"29":0,"30":0,"31":0,"32":0,"33":0,"34":0,"35":0,"36":0,"37":0,"38":0},"fnMap":{"1":{"name":"(anonymous_1)","line":1,"loc":{"start":{"line":1,"column":27},"end":{"line":1,"column":46}}},"2":{"name":"(anonymous_2)","line":49,"loc":{"start":{"line":49,"column":17},"end":{"line":49,"column":42}}},"3":{"name":"ScrollView","line":62,"loc":{"start":{"line":62,"column":0},"end":{"line":62,"column":22}}},"4":{"name":"(anonymous_4)","line":168,"loc":{"start":{"line":168,"column":17},"end":{"line":168,"column":29}}},"5":{"name":"(anonymous_5)","line":189,"loc":{"start":{"line":189,"column":12},"end":{"line":189,"column":24}}},"6":{"name":"(anonymous_6)","line":237,"loc":{"start":{"line":237,"column":16},"end":{"line":237,"column":28}}},"7":{"name":"(anonymous_7)","line":265,"loc":{"start":{"line":265,"column":15},"end":{"line":265,"column":31}}},"8":{"name":"(anonymous_8)","line":285,"loc":{"start":{"line":285,"column":16},"end":{"line":285,"column":33}}},"9":{"name":"(anonymous_9)","line":308,"loc":{"start":{"line":308,"column":21},"end":{"line":308,"column":43}}},"10":{"name":"(anonymous_10)","line":330,"loc":{"start":{"line":330,"column":12},"end":{"line":330,"column":24}}},"11":{"name":"(anonymous_11)","line":374,"loc":{"start":{"line":374,"column":20},"end":{"line":374,"column":32}}},"12":{"name":"(anonymous_12)","line":417,"loc":{"start":{"line":417,"column":25},"end":{"line":417,"column":37}}},"13":{"name":"(anonymous_13)","line":459,"loc":{"start":{"line":459,"column":16},"end":{"line":459,"column":34}}},"14":{"name":"(anonymous_14)","line":476,"loc":{"start":{"line":476,"column":16},"end":{"line":476,"column":28}}},"15":{"name":"(anonymous_15)","line":499,"loc":{"start":{"line":499,"column":14},"end":{"line":499,"column":54}}},"16":{"name":"(anonymous_16)","line":579,"loc":{"start":{"line":579,"column":16},"end":{"line":579,"column":32}}},"17":{"name":"(anonymous_17)","line":599,"loc":{"start":{"line":599,"column":14},"end":{"line":599,"column":35}}},"18":{"name":"(anonymous_18)","line":616,"loc":{"start":{"line":616,"column":17},"end":{"line":616,"column":29}}},"19":{"name":"(anonymous_19)","line":641,"loc":{"start":{"line":641,"column":25},"end":{"line":641,"column":38}}},"20":{"name":"(anonymous_20)","line":707,"loc":{"start":{"line":707,"column":20},"end":{"line":707,"column":33}}},"21":{"name":"(anonymous_21)","line":749,"loc":{"start":{"line":749,"column":23},"end":{"line":749,"column":36}}},"22":{"name":"(anonymous_22)","line":804,"loc":{"start":{"line":804,"column":12},"end":{"line":804,"column":25}}},"23":{"name":"(anonymous_23)","line":837,"loc":{"start":{"line":837,"column":17},"end":{"line":837,"column":63}}},"24":{"name":"(anonymous_24)","line":900,"loc":{"start":{"line":900,"column":18},"end":{"line":900,"column":30}}},"25":{"name":"(anonymous_25)","line":920,"loc":{"start":{"line":920,"column":17},"end":{"line":920,"column":30}}},"26":{"name":"(anonymous_26)","line":970,"loc":{"start":{"line":970,"column":20},"end":{"line":970,"column":36}}},"27":{"name":"(anonymous_27)","line":993,"loc":{"start":{"line":993,"column":15},"end":{"line":993,"column":27}}},"28":{"name":"(anonymous_28)","line":1025,"loc":{"start":{"line":1025,"column":24},"end":{"line":1025,"column":37}}},"29":{"name":"(anonymous_29)","line":1062,"loc":{"start":{"line":1062,"column":23},"end":{"line":1062,"column":36}}},"30":{"name":"(anonymous_30)","line":1073,"loc":{"start":{"line":1073,"column":26},"end":{"line":1073,"column":39}}},"31":{"name":"(anonymous_31)","line":1085,"loc":{"start":{"line":1085,"column":22},"end":{"line":1085,"column":35}}},"32":{"name":"(anonymous_32)","line":1096,"loc":{"start":{"line":1096,"column":22},"end":{"line":1096,"column":35}}},"33":{"name":"(anonymous_33)","line":1107,"loc":{"start":{"line":1107,"column":21},"end":{"line":1107,"column":33}}},"34":{"name":"(anonymous_34)","line":1118,"loc":{"start":{"line":1118,"column":21},"end":{"line":1118,"column":33}}},"35":{"name":"(anonymous_35)","line":1140,"loc":{"start":{"line":1140,"column":17},"end":{"line":1140,"column":32}}},"36":{"name":"(anonymous_36)","line":1161,"loc":{"start":{"line":1161,"column":17},"end":{"line":1161,"column":31}}},"37":{"name":"(anonymous_37)","line":1179,"loc":{"start":{"line":1179,"column":17},"end":{"line":1179,"column":31}}},"38":{"name":"(anonymous_38)","line":1191,"loc":{"start":{"line":1191,"column":17},"end":{"line":1191,"column":31}}}},"statementMap":{"1":{"start":{"line":1,"column":0},"end":{"line":1457,"column":110}},"2":{"start":{"line":11,"column":0},"end":{"line":51,"column":6}},"3":{"start":{"line":50,"column":8},"end":{"line":50,"column":49}},"4":{"start":{"line":62,"column":0},"end":{"line":64,"column":1}},"5":{"start":{"line":63,"column":4},"end":{"line":63,"column":61}},"6":{"start":{"line":66,"column":0},"end":{"line":1454,"column":3}},"7":{"start":{"line":169,"column":8},"end":{"line":169,"column":22}},"8":{"start":{"line":172,"column":8},"end":{"line":172,"column":38}},"9":{"start":{"line":173,"column":8},"end":{"line":173,"column":37}},"10":{"start":{"line":176,"column":8},"end":{"line":176,"column":33}},"11":{"start":{"line":177,"column":8},"end":{"line":177,"column":37}},"12":{"start":{"line":178,"column":8},"end":{"line":178,"column":48}},"13":{"start":{"line":179,"column":8},"end":{"line":179,"column":49}},"14":{"start":{"line":180,"column":8},"end":{"line":180,"column":52}},"15":{"start":{"line":190,"column":8},"end":{"line":190,"column":22}},"16":{"start":{"line":193,"column":8},"end":{"line":193,"column":37}},"17":{"start":{"line":194,"column":8},"end":{"line":194,"column":35}},"18":{"start":{"line":195,"column":8},"end":{"line":195,"column":33}},"19":{"start":{"line":198,"column":8},"end":{"line":198,"column":24}},"20":{"start":{"line":201,"column":8},"end":{"line":203,"column":9}},"21":{"start":{"line":202,"column":12},"end":{"line":202,"column":44}},"22":{"start":{"line":206,"column":8},"end":{"line":208,"column":9}},"23":{"start":{"line":207,"column":12},"end":{"line":207,"column":60}},"24":{"start":{"line":210,"column":8},"end":{"line":212,"column":9}},"25":{"start":{"line":211,"column":12},"end":{"line":211,"column":56}},"26":{"start":{"line":214,"column":8},"end":{"line":216,"column":9}},"27":{"start":{"line":215,"column":12},"end":{"line":215,"column":46}},"28":{"start":{"line":218,"column":8},"end":{"line":220,"column":9}},"29":{"start":{"line":219,"column":12},"end":{"line":219,"column":58}},"30":{"start":{"line":222,"column":8},"end":{"line":224,"column":9}},"31":{"start":{"line":223,"column":12},"end":{"line":223,"column":58}},"32":{"start":{"line":238,"column":8},"end":{"line":240,"column":50}},"33":{"start":{"line":243,"column":8},"end":{"line":253,"column":11}},"34":{"start":{"line":266,"column":8},"end":{"line":267,"column":24}},"35":{"start":{"line":270,"column":8},"end":{"line":270,"column":31}},"36":{"start":{"line":272,"column":8},"end":{"line":274,"column":9}},"37":{"start":{"line":273,"column":12},"end":{"line":273,"column":89}},"38":{"start":{"line":286,"column":8},"end":{"line":287,"column":24}},"39":{"start":{"line":290,"column":8},"end":{"line":290,"column":32}},"40":{"start":{"line":292,"column":8},"end":{"line":297,"column":9}},"41":{"start":{"line":293,"column":12},"end":{"line":293,"column":69}},"42":{"start":{"line":296,"column":12},"end":{"line":296,"column":39}},"43":{"start":{"line":309,"column":8},"end":{"line":310,"column":24}},"44":{"start":{"line":314,"column":8},"end":{"line":314,"column":37}},"45":{"start":{"line":317,"column":8},"end":{"line":320,"column":9}},"46":{"start":{"line":319,"column":12},"end":{"line":319,"column":71}},"47":{"start":{"line":331,"column":8},"end":{"line":336,"column":51}},"48":{"start":{"line":339,"column":8},"end":{"line":348,"column":9}},"49":{"start":{"line":342,"column":12},"end":{"line":345,"column":14}},"50":{"start":{"line":347,"column":12},"end":{"line":347,"column":37}},"51":{"start":{"line":351,"column":8},"end":{"line":351,"column":66}},"52":{"start":{"line":354,"column":8},"end":{"line":354,"column":41}},"53":{"start":{"line":357,"column":8},"end":{"line":357,"column":33}},"54":{"start":{"line":360,"column":8},"end":{"line":362,"column":9}},"55":{"start":{"line":361,"column":12},"end":{"line":361,"column":27}},"56":{"start":{"line":375,"column":8},"end":{"line":385,"column":17}},"57":{"start":{"line":388,"column":8},"end":{"line":391,"column":9}},"58":{"start":{"line":389,"column":12},"end":{"line":389,"column":46}},"59":{"start":{"line":390,"column":12},"end":{"line":390,"column":47}},"60":{"start":{"line":393,"column":8},"end":{"line":393,"column":48}},"61":{"start":{"line":394,"column":8},"end":{"line":394,"column":38}},"62":{"start":{"line":396,"column":8},"end":{"line":396,"column":29}},"63":{"start":{"line":397,"column":8},"end":{"line":402,"column":10}},"64":{"start":{"line":403,"column":8},"end":{"line":403,"column":43}},"65":{"start":{"line":405,"column":8},"end":{"line":405,"column":48}},"66":{"start":{"line":407,"column":8},"end":{"line":407,"column":20}},"67":{"start":{"line":418,"column":8},"end":{"line":430,"column":60}},"68":{"start":{"line":432,"column":8},"end":{"line":434,"column":9}},"69":{"start":{"line":433,"column":12},"end":{"line":433,"column":48}},"70":{"start":{"line":436,"column":8},"end":{"line":438,"column":9}},"71":{"start":{"line":437,"column":12},"end":{"line":437,"column":46}},"72":{"start":{"line":440,"column":8},"end":{"line":445,"column":11}},"73":{"start":{"line":460,"column":8},"end":{"line":460,"column":22}},"74":{"start":{"line":464,"column":8},"end":{"line":464,"column":43}},"75":{"start":{"line":465,"column":8},"end":{"line":465,"column":43}},"76":{"start":{"line":466,"column":8},"end":{"line":466,"column":43}},"77":{"start":{"line":467,"column":8},"end":{"line":467,"column":43}},"78":{"start":{"line":477,"column":8},"end":{"line":477,"column":22}},"79":{"start":{"line":479,"column":8},"end":{"line":484,"column":10}},"80":{"start":{"line":501,"column":8},"end":{"line":503,"column":9}},"81":{"start":{"line":502,"column":12},"end":{"line":502,"column":19}},"82":{"start":{"line":505,"column":8},"end":{"line":512,"column":22}},"83":{"start":{"line":515,"column":8},"end":{"line":515,"column":33}},"84":{"start":{"line":516,"column":8},"end":{"line":516,"column":42}},"85":{"start":{"line":517,"column":8},"end":{"line":517,"column":26}},"86":{"start":{"line":519,"column":8},"end":{"line":522,"column":9}},"87":{"start":{"line":520,"column":12},"end":{"line":520,"column":42}},"88":{"start":{"line":521,"column":12},"end":{"line":521,"column":24}},"89":{"start":{"line":524,"column":8},"end":{"line":527,"column":9}},"90":{"start":{"line":525,"column":12},"end":{"line":525,"column":42}},"91":{"start":{"line":526,"column":12},"end":{"line":526,"column":24}},"92":{"start":{"line":529,"column":8},"end":{"line":529,"column":46}},"93":{"start":{"line":531,"column":8},"end":{"line":534,"column":9}},"94":{"start":{"line":533,"column":12},"end":{"line":533,"column":80}},"95":{"start":{"line":537,"column":8},"end":{"line":567,"column":9}},"96":{"start":{"line":538,"column":12},"end":{"line":550,"column":13}},"97":{"start":{"line":539,"column":16},"end":{"line":539,"column":54}},"98":{"start":{"line":544,"column":16},"end":{"line":546,"column":17}},"99":{"start":{"line":545,"column":20},"end":{"line":545,"column":51}},"100":{"start":{"line":547,"column":16},"end":{"line":549,"column":17}},"101":{"start":{"line":548,"column":20},"end":{"line":548,"column":50}},"102":{"start":{"line":555,"column":12},"end":{"line":555,"column":39}},"103":{"start":{"line":556,"column":12},"end":{"line":556,"column":50}},"104":{"start":{"line":558,"column":12},"end":{"line":564,"column":13}},"105":{"start":{"line":559,"column":16},"end":{"line":559,"column":49}},"106":{"start":{"line":562,"column":16},"end":{"line":562,"column":44}},"107":{"start":{"line":563,"column":16},"end":{"line":563,"column":43}},"108":{"start":{"line":566,"column":12},"end":{"line":566,"column":50}},"109":{"start":{"line":581,"column":8},"end":{"line":581,"column":57}},"110":{"start":{"line":583,"column":8},"end":{"line":585,"column":9}},"111":{"start":{"line":584,"column":12},"end":{"line":584,"column":37}},"112":{"start":{"line":587,"column":8},"end":{"line":587,"column":20}},"113":{"start":{"line":600,"column":8},"end":{"line":605,"column":9}},"114":{"start":{"line":601,"column":12},"end":{"line":601,"column":62}},"115":{"start":{"line":603,"column":12},"end":{"line":603,"column":40}},"116":{"start":{"line":604,"column":12},"end":{"line":604,"column":39}},"117":{"start":{"line":617,"column":8},"end":{"line":617,"column":22}},"118":{"start":{"line":620,"column":8},"end":{"line":631,"column":9}},"119":{"start":{"line":621,"column":12},"end":{"line":621,"column":27}},"120":{"start":{"line":630,"column":12},"end":{"line":630,"column":35}},"121":{"start":{"line":643,"column":8},"end":{"line":645,"column":9}},"122":{"start":{"line":644,"column":12},"end":{"line":644,"column":25}},"123":{"start":{"line":647,"column":8},"end":{"line":652,"column":32}},"124":{"start":{"line":654,"column":8},"end":{"line":656,"column":9}},"125":{"start":{"line":655,"column":12},"end":{"line":655,"column":31}},"126":{"start":{"line":659,"column":8},"end":{"line":662,"column":9}},"127":{"start":{"line":660,"column":12},"end":{"line":660,"column":30}},"128":{"start":{"line":661,"column":12},"end":{"line":661,"column":29}},"129":{"start":{"line":665,"column":8},"end":{"line":665,"column":31}},"130":{"start":{"line":668,"column":8},"end":{"line":697,"column":10}},"131":{"start":{"line":708,"column":8},"end":{"line":718,"column":32}},"132":{"start":{"line":720,"column":8},"end":{"line":722,"column":9}},"133":{"start":{"line":721,"column":12},"end":{"line":721,"column":31}},"134":{"start":{"line":724,"column":8},"end":{"line":724,"column":48}},"135":{"start":{"line":725,"column":8},"end":{"line":725,"column":48}},"136":{"start":{"line":729,"column":8},"end":{"line":731,"column":9}},"137":{"start":{"line":730,"column":12},"end":{"line":730,"column":97}},"138":{"start":{"line":734,"column":8},"end":{"line":739,"column":9}},"139":{"start":{"line":735,"column":12},"end":{"line":735,"column":54}},"140":{"start":{"line":737,"column":13},"end":{"line":739,"column":9}},"141":{"start":{"line":738,"column":12},"end":{"line":738,"column":54}},"142":{"start":{"line":750,"column":8},"end":{"line":755,"column":18}},"143":{"start":{"line":757,"column":8},"end":{"line":759,"column":9}},"144":{"start":{"line":758,"column":12},"end":{"line":758,"column":31}},"145":{"start":{"line":762,"column":8},"end":{"line":762,"column":37}},"146":{"start":{"line":763,"column":8},"end":{"line":763,"column":37}},"147":{"start":{"line":766,"column":8},"end":{"line":766,"column":39}},"148":{"start":{"line":767,"column":8},"end":{"line":767,"column":42}},"149":{"start":{"line":770,"column":8},"end":{"line":794,"column":9}},"150":{"start":{"line":776,"column":12},"end":{"line":793,"column":13}},"151":{"start":{"line":778,"column":16},"end":{"line":778,"column":44}},"152":{"start":{"line":781,"column":16},"end":{"line":792,"column":17}},"153":{"start":{"line":782,"column":20},"end":{"line":782,"column":35}},"154":{"start":{"line":789,"column":20},"end":{"line":791,"column":21}},"155":{"start":{"line":790,"column":24},"end":{"line":790,"column":41}},"156":{"start":{"line":805,"column":8},"end":{"line":807,"column":9}},"157":{"start":{"line":806,"column":12},"end":{"line":806,"column":25}},"158":{"start":{"line":809,"column":8},"end":{"line":815,"column":45}},"159":{"start":{"line":818,"column":8},"end":{"line":820,"column":9}},"160":{"start":{"line":819,"column":12},"end":{"line":819,"column":38}},"161":{"start":{"line":823,"column":8},"end":{"line":825,"column":9}},"162":{"start":{"line":824,"column":12},"end":{"line":824,"column":68}},"163":{"start":{"line":839,"column":8},"end":{"line":864,"column":20}},"164":{"start":{"line":867,"column":8},"end":{"line":869,"column":9}},"165":{"start":{"line":868,"column":12},"end":{"line":868,"column":34}},"166":{"start":{"line":872,"column":8},"end":{"line":872,"column":61}},"167":{"start":{"line":875,"column":8},"end":{"line":897,"column":9}},"168":{"start":{"line":877,"column":12},"end":{"line":879,"column":13}},"169":{"start":{"line":878,"column":16},"end":{"line":878,"column":34}},"170":{"start":{"line":882,"column":12},"end":{"line":889,"column":13}},"171":{"start":{"line":883,"column":16},"end":{"line":883,"column":33}},"172":{"start":{"line":888,"column":16},"end":{"line":888,"column":31}},"173":{"start":{"line":895,"column":12},"end":{"line":895,"column":109}},"174":{"start":{"line":896,"column":12},"end":{"line":896,"column":42}},"175":{"start":{"line":901,"column":8},"end":{"line":901,"column":22}},"176":{"start":{"line":903,"column":8},"end":{"line":909,"column":9}},"177":{"start":{"line":905,"column":12},"end":{"line":905,"column":35}},"178":{"start":{"line":908,"column":12},"end":{"line":908,"column":33}},"179":{"start":{"line":921,"column":8},"end":{"line":927,"column":72}},"180":{"start":{"line":929,"column":8},"end":{"line":929,"column":80}},"181":{"start":{"line":935,"column":8},"end":{"line":958,"column":9}},"182":{"start":{"line":938,"column":12},"end":{"line":938,"column":35}},"183":{"start":{"line":941,"column":12},"end":{"line":941,"column":40}},"184":{"start":{"line":945,"column":12},"end":{"line":951,"column":13}},"185":{"start":{"line":947,"column":16},"end":{"line":947,"column":40}},"186":{"start":{"line":948,"column":16},"end":{"line":948,"column":38}},"187":{"start":{"line":954,"column":12},"end":{"line":954,"column":29}},"188":{"start":{"line":957,"column":12},"end":{"line":957,"column":31}},"189":{"start":{"line":971,"column":8},"end":{"line":981,"column":37}},"190":{"start":{"line":983,"column":8},"end":{"line":983,"column":118}},"191":{"start":{"line":994,"column":8},"end":{"line":1005,"column":41}},"192":{"start":{"line":1007,"column":8},"end":{"line":1015,"column":9}},"193":{"start":{"line":1008,"column":12},"end":{"line":1008,"column":71}},"194":{"start":{"line":1010,"column":13},"end":{"line":1015,"column":9}},"195":{"start":{"line":1011,"column":12},"end":{"line":1011,"column":71}},"196":{"start":{"line":1014,"column":12},"end":{"line":1014,"column":29}},"197":{"start":{"line":1026,"column":8},"end":{"line":1028,"column":9}},"198":{"start":{"line":1027,"column":12},"end":{"line":1027,"column":25}},"199":{"start":{"line":1030,"column":8},"end":{"line":1034,"column":30}},"200":{"start":{"line":1037,"column":8},"end":{"line":1037,"column":73}},"201":{"start":{"line":1040,"column":8},"end":{"line":1047,"column":9}},"202":{"start":{"line":1041,"column":12},"end":{"line":1041,"column":35}},"203":{"start":{"line":1042,"column":12},"end":{"line":1042,"column":48}},"204":{"start":{"line":1045,"column":12},"end":{"line":1045,"column":48}},"205":{"start":{"line":1046,"column":12},"end":{"line":1046,"column":35}},"206":{"start":{"line":1049,"column":8},"end":{"line":1049,"column":36}},"207":{"start":{"line":1050,"column":8},"end":{"line":1050,"column":34}},"208":{"start":{"line":1052,"column":8},"end":{"line":1052,"column":44}},"209":{"start":{"line":1063,"column":8},"end":{"line":1063,"column":34}},"210":{"start":{"line":1075,"column":8},"end":{"line":1075,"column":35}},"211":{"start":{"line":1086,"column":8},"end":{"line":1086,"column":31}},"212":{"start":{"line":1097,"column":8},"end":{"line":1097,"column":33}},"213":{"start":{"line":1108,"column":8},"end":{"line":1108,"column":35}},"214":{"start":{"line":1119,"column":8},"end":{"line":1119,"column":22}},"215":{"start":{"line":1121,"column":8},"end":{"line":1123,"column":9}},"216":{"start":{"line":1122,"column":12},"end":{"line":1122,"column":30}},"217":{"start":{"line":1143,"column":8},"end":{"line":1148,"column":9}},"218":{"start":{"line":1144,"column":12},"end":{"line":1147,"column":14}},"219":{"start":{"line":1164,"column":8},"end":{"line":1166,"column":9}},"220":{"start":{"line":1165,"column":12},"end":{"line":1165,"column":44}},"221":{"start":{"line":1168,"column":8},"end":{"line":1168,"column":19}},"222":{"start":{"line":1180,"column":8},"end":{"line":1180,"column":43}},"223":{"start":{"line":1192,"column":8},"end":{"line":1192,"column":43}}},"branchMap":{"1":{"line":78,"type":"cond-expr","locations":[{"start":{"line":78,"column":38},"end":{"line":78,"column":42}},{"start":{"line":78,"column":45},"end":{"line":78,"column":50}}]},"2":{"line":201,"type":"if","locations":[{"start":{"line":201,"column":8},"end":{"line":201,"column":8}},{"start":{"line":201,"column":8},"end":{"line":201,"column":8}}]},"3":{"line":206,"type":"if","locations":[{"start":{"line":206,"column":8},"end":{"line":206,"column":8}},{"start":{"line":206,"column":8},"end":{"line":206,"column":8}}]},"4":{"line":210,"type":"if","locations":[{"start":{"line":210,"column":8},"end":{"line":210,"column":8}},{"start":{"line":210,"column":8},"end":{"line":210,"column":8}}]},"5":{"line":214,"type":"if","locations":[{"start":{"line":214,"column":8},"end":{"line":214,"column":8}},{"start":{"line":214,"column":8},"end":{"line":214,"column":8}}]},"6":{"line":218,"type":"if","locations":[{"start":{"line":218,"column":8},"end":{"line":218,"column":8}},{"start":{"line":218,"column":8},"end":{"line":218,"column":8}}]},"7":{"line":222,"type":"if","locations":[{"start":{"line":222,"column":8},"end":{"line":222,"column":8}},{"start":{"line":222,"column":8},"end":{"line":222,"column":8}}]},"8":{"line":272,"type":"if","locations":[{"start":{"line":272,"column":8},"end":{"line":272,"column":8}},{"start":{"line":272,"column":8},"end":{"line":272,"column":8}}]},"9":{"line":292,"type":"if","locations":[{"start":{"line":292,"column":8},"end":{"line":292,"column":8}},{"start":{"line":292,"column":8},"end":{"line":292,"column":8}}]},"10":{"line":317,"type":"if","locations":[{"start":{"line":317,"column":8},"end":{"line":317,"column":8}},{"start":{"line":317,"column":8},"end":{"line":317,"column":8}}]},"11":{"line":339,"type":"if","locations":[{"start":{"line":339,"column":8},"end":{"line":339,"column":8}},{"start":{"line":339,"column":8},"end":{"line":339,"column":8}}]},"12":{"line":360,"type":"if","locations":[{"start":{"line":360,"column":8},"end":{"line":360,"column":8}},{"start":{"line":360,"column":8},"end":{"line":360,"column":8}}]},"13":{"line":388,"type":"if","locations":[{"start":{"line":388,"column":8},"end":{"line":388,"column":8}},{"start":{"line":388,"column":8},"end":{"line":388,"column":8}}]},"14":{"line":427,"type":"cond-expr","locations":[{"start":{"line":427,"column":32},"end":{"line":427,"column":67}},{"start":{"line":427,"column":70},"end":{"line":427,"column":71}}]},"15":{"line":428,"type":"cond-expr","locations":[{"start":{"line":428,"column":32},"end":{"line":428,"column":33}},{"start":{"line":428,"column":36},"end":{"line":428,"column":68}}]},"16":{"line":432,"type":"if","locations":[{"start":{"line":432,"column":8},"end":{"line":432,"column":8}},{"start":{"line":432,"column":8},"end":{"line":432,"column":8}}]},"17":{"line":432,"type":"binary-expr","locations":[{"start":{"line":432,"column":12},"end":{"line":432,"column":18}},{"start":{"line":432,"column":22},"end":{"line":432,"column":30}}]},"18":{"line":436,"type":"if","locations":[{"start":{"line":436,"column":8},"end":{"line":436,"column":8}},{"start":{"line":436,"column":8},"end":{"line":436,"column":8}}]},"19":{"line":436,"type":"binary-expr","locations":[{"start":{"line":436,"column":12},"end":{"line":436,"column":18}},{"start":{"line":436,"column":22},"end":{"line":436,"column":30}}]},"20":{"line":501,"type":"if","locations":[{"start":{"line":501,"column":8},"end":{"line":501,"column":8}},{"start":{"line":501,"column":8},"end":{"line":501,"column":8}}]},"21":{"line":515,"type":"binary-expr","locations":[{"start":{"line":515,"column":19},"end":{"line":515,"column":27}},{"start":{"line":515,"column":31},"end":{"line":515,"column":32}}]},"22":{"line":516,"type":"binary-expr","locations":[{"start":{"line":516,"column":17},"end":{"line":516,"column":23}},{"start":{"line":516,"column":27},"end":{"line":516,"column":41}}]},"23":{"line":517,"type":"binary-expr","locations":[{"start":{"line":517,"column":15},"end":{"line":517,"column":19}},{"start":{"line":517,"column":23},"end":{"line":517,"column":25}}]},"24":{"line":519,"type":"if","locations":[{"start":{"line":519,"column":8},"end":{"line":519,"column":8}},{"start":{"line":519,"column":8},"end":{"line":519,"column":8}}]},"25":{"line":524,"type":"if","locations":[{"start":{"line":524,"column":8},"end":{"line":524,"column":8}},{"start":{"line":524,"column":8},"end":{"line":524,"column":8}}]},"26":{"line":531,"type":"if","locations":[{"start":{"line":531,"column":8},"end":{"line":531,"column":8}},{"start":{"line":531,"column":8},"end":{"line":531,"column":8}}]},"27":{"line":537,"type":"if","locations":[{"start":{"line":537,"column":8},"end":{"line":537,"column":8}},{"start":{"line":537,"column":8},"end":{"line":537,"column":8}}]},"28":{"line":538,"type":"if","locations":[{"start":{"line":538,"column":12},"end":{"line":538,"column":12}},{"start":{"line":538,"column":12},"end":{"line":538,"column":12}}]},"29":{"line":544,"type":"if","locations":[{"start":{"line":544,"column":16},"end":{"line":544,"column":16}},{"start":{"line":544,"column":16},"end":{"line":544,"column":16}}]},"30":{"line":547,"type":"if","locations":[{"start":{"line":547,"column":16},"end":{"line":547,"column":16}},{"start":{"line":547,"column":16},"end":{"line":547,"column":16}}]},"31":{"line":558,"type":"if","locations":[{"start":{"line":558,"column":12},"end":{"line":558,"column":12}},{"start":{"line":558,"column":12},"end":{"line":558,"column":12}}]},"32":{"line":583,"type":"if","locations":[{"start":{"line":583,"column":8},"end":{"line":583,"column":8}},{"start":{"line":583,"column":8},"end":{"line":583,"column":8}}]},"33":{"line":600,"type":"if","locations":[{"start":{"line":600,"column":8},"end":{"line":600,"column":8}},{"start":{"line":600,"column":8},"end":{"line":600,"column":8}}]},"34":{"line":620,"type":"if","locations":[{"start":{"line":620,"column":8},"end":{"line":620,"column":8}},{"start":{"line":620,"column":8},"end":{"line":620,"column":8}}]},"35":{"line":643,"type":"if","locations":[{"start":{"line":643,"column":8},"end":{"line":643,"column":8}},{"start":{"line":643,"column":8},"end":{"line":643,"column":8}}]},"36":{"line":654,"type":"if","locations":[{"start":{"line":654,"column":8},"end":{"line":654,"column":8}},{"start":{"line":654,"column":8},"end":{"line":654,"column":8}}]},"37":{"line":659,"type":"if","locations":[{"start":{"line":659,"column":8},"end":{"line":659,"column":8}},{"start":{"line":659,"column":8},"end":{"line":659,"column":8}}]},"38":{"line":720,"type":"if","locations":[{"start":{"line":720,"column":8},"end":{"line":720,"column":8}},{"start":{"line":720,"column":8},"end":{"line":720,"column":8}}]},"39":{"line":729,"type":"if","locations":[{"start":{"line":729,"column":8},"end":{"line":729,"column":8}},{"start":{"line":729,"column":8},"end":{"line":729,"column":8}}]},"40":{"line":730,"type":"cond-expr","locations":[{"start":{"line":730,"column":83},"end":{"line":730,"column":88}},{"start":{"line":730,"column":91},"end":{"line":730,"column":96}}]},"41":{"line":734,"type":"if","locations":[{"start":{"line":734,"column":8},"end":{"line":734,"column":8}},{"start":{"line":734,"column":8},"end":{"line":734,"column":8}}]},"42":{"line":734,"type":"binary-expr","locations":[{"start":{"line":734,"column":12},"end":{"line":734,"column":34}},{"start":{"line":734,"column":38},"end":{"line":734,"column":45}}]},"43":{"line":737,"type":"if","locations":[{"start":{"line":737,"column":13},"end":{"line":737,"column":13}},{"start":{"line":737,"column":13},"end":{"line":737,"column":13}}]},"44":{"line":737,"type":"binary-expr","locations":[{"start":{"line":737,"column":17},"end":{"line":737,"column":39}},{"start":{"line":737,"column":43},"end":{"line":737,"column":50}}]},"45":{"line":757,"type":"if","locations":[{"start":{"line":757,"column":8},"end":{"line":757,"column":8}},{"start":{"line":757,"column":8},"end":{"line":757,"column":8}}]},"46":{"line":770,"type":"if","locations":[{"start":{"line":770,"column":8},"end":{"line":770,"column":8}},{"start":{"line":770,"column":8},"end":{"line":770,"column":8}}]},"47":{"line":776,"type":"if","locations":[{"start":{"line":776,"column":12},"end":{"line":776,"column":12}},{"start":{"line":776,"column":12},"end":{"line":776,"column":12}}]},"48":{"line":776,"type":"binary-expr","locations":[{"start":{"line":776,"column":16},"end":{"line":776,"column":39}},{"start":{"line":776,"column":43},"end":{"line":776,"column":66}}]},"49":{"line":781,"type":"if","locations":[{"start":{"line":781,"column":16},"end":{"line":781,"column":16}},{"start":{"line":781,"column":16},"end":{"line":781,"column":16}}]},"50":{"line":789,"type":"if","locations":[{"start":{"line":789,"column":20},"end":{"line":789,"column":20}},{"start":{"line":789,"column":20},"end":{"line":789,"column":20}}]},"51":{"line":789,"type":"binary-expr","locations":[{"start":{"line":789,"column":24},"end":{"line":789,"column":33}},{"start":{"line":789,"column":38},"end":{"line":789,"column":46}},{"start":{"line":789,"column":50},"end":{"line":789,"column":83}}]},"52":{"line":805,"type":"if","locations":[{"start":{"line":805,"column":8},"end":{"line":805,"column":8}},{"start":{"line":805,"column":8},"end":{"line":805,"column":8}}]},"53":{"line":814,"type":"cond-expr","locations":[{"start":{"line":814,"column":45},"end":{"line":814,"column":53}},{"start":{"line":814,"column":56},"end":{"line":814,"column":64}}]},"54":{"line":818,"type":"if","locations":[{"start":{"line":818,"column":8},"end":{"line":818,"column":8}},{"start":{"line":818,"column":8},"end":{"line":818,"column":8}}]},"55":{"line":823,"type":"if","locations":[{"start":{"line":823,"column":8},"end":{"line":823,"column":8}},{"start":{"line":823,"column":8},"end":{"line":823,"column":8}}]},"56":{"line":840,"type":"cond-expr","locations":[{"start":{"line":840,"column":45},"end":{"line":840,"column":53}},{"start":{"line":840,"column":56},"end":{"line":840,"column":64}}]},"57":{"line":854,"type":"cond-expr","locations":[{"start":{"line":854,"column":40},"end":{"line":854,"column":57}},{"start":{"line":854,"column":60},"end":{"line":854,"column":77}}]},"58":{"line":855,"type":"cond-expr","locations":[{"start":{"line":855,"column":40},"end":{"line":855,"column":57}},{"start":{"line":855,"column":60},"end":{"line":855,"column":77}}]},"59":{"line":861,"type":"binary-expr","locations":[{"start":{"line":861,"column":30},"end":{"line":861,"column":38}},{"start":{"line":861,"column":43},"end":{"line":861,"column":76}}]},"60":{"line":862,"type":"binary-expr","locations":[{"start":{"line":862,"column":30},"end":{"line":862,"column":38}},{"start":{"line":862,"column":43},"end":{"line":862,"column":76}}]},"61":{"line":867,"type":"if","locations":[{"start":{"line":867,"column":8},"end":{"line":867,"column":8}},{"start":{"line":867,"column":8},"end":{"line":867,"column":8}}]},"62":{"line":867,"type":"binary-expr","locations":[{"start":{"line":867,"column":12},"end":{"line":867,"column":26}},{"start":{"line":867,"column":30},"end":{"line":867,"column":44}}]},"63":{"line":875,"type":"if","locations":[{"start":{"line":875,"column":8},"end":{"line":875,"column":8}},{"start":{"line":875,"column":8},"end":{"line":875,"column":8}}]},"64":{"line":875,"type":"binary-expr","locations":[{"start":{"line":875,"column":12},"end":{"line":875,"column":19}},{"start":{"line":875,"column":23},"end":{"line":875,"column":36}},{"start":{"line":875,"column":40},"end":{"line":875,"column":53}}]},"65":{"line":877,"type":"if","locations":[{"start":{"line":877,"column":12},"end":{"line":877,"column":12}},{"start":{"line":877,"column":12},"end":{"line":877,"column":12}}]},"66":{"line":882,"type":"if","locations":[{"start":{"line":882,"column":12},"end":{"line":882,"column":12}},{"start":{"line":882,"column":12},"end":{"line":882,"column":12}}]},"67":{"line":882,"type":"binary-expr","locations":[{"start":{"line":882,"column":16},"end":{"line":882,"column":24}},{"start":{"line":882,"column":28},"end":{"line":882,"column":36}}]},"68":{"line":903,"type":"if","locations":[{"start":{"line":903,"column":8},"end":{"line":903,"column":8}},{"start":{"line":903,"column":8},"end":{"line":903,"column":8}}]},"69":{"line":927,"type":"cond-expr","locations":[{"start":{"line":927,"column":48},"end":{"line":927,"column":49}},{"start":{"line":927,"column":52},"end":{"line":927,"column":54}}]},"70":{"line":935,"type":"if","locations":[{"start":{"line":935,"column":8},"end":{"line":935,"column":8}},{"start":{"line":935,"column":8},"end":{"line":935,"column":8}}]},"71":{"line":935,"type":"binary-expr","locations":[{"start":{"line":935,"column":12},"end":{"line":935,"column":33}},{"start":{"line":935,"column":37},"end":{"line":935,"column":53}}]},"72":{"line":945,"type":"if","locations":[{"start":{"line":945,"column":12},"end":{"line":945,"column":12}},{"start":{"line":945,"column":12},"end":{"line":945,"column":12}}]},"73":{"line":975,"type":"binary-expr","locations":[{"start":{"line":975,"column":23},"end":{"line":975,"column":24}},{"start":{"line":975,"column":28},"end":{"line":975,"column":44}}]},"74":{"line":976,"type":"binary-expr","locations":[{"start":{"line":976,"column":23},"end":{"line":976,"column":24}},{"start":{"line":976,"column":28},"end":{"line":976,"column":44}}]},"75":{"line":983,"type":"binary-expr","locations":[{"start":{"line":983,"column":16},"end":{"line":983,"column":23}},{"start":{"line":983,"column":28},"end":{"line":983,"column":43}},{"start":{"line":983,"column":47},"end":{"line":983,"column":62}},{"start":{"line":983,"column":69},"end":{"line":983,"column":76}},{"start":{"line":983,"column":81},"end":{"line":983,"column":96}},{"start":{"line":983,"column":100},"end":{"line":983,"column":115}}]},"76":{"line":1007,"type":"if","locations":[{"start":{"line":1007,"column":8},"end":{"line":1007,"column":8}},{"start":{"line":1007,"column":8},"end":{"line":1007,"column":8}}]},"77":{"line":1010,"type":"if","locations":[{"start":{"line":1010,"column":13},"end":{"line":1010,"column":13}},{"start":{"line":1010,"column":13},"end":{"line":1010,"column":13}}]},"78":{"line":1026,"type":"if","locations":[{"start":{"line":1026,"column":8},"end":{"line":1026,"column":8}},{"start":{"line":1026,"column":8},"end":{"line":1026,"column":8}}]},"79":{"line":1040,"type":"if","locations":[{"start":{"line":1040,"column":8},"end":{"line":1040,"column":8}},{"start":{"line":1040,"column":8},"end":{"line":1040,"column":8}}]},"80":{"line":1121,"type":"if","locations":[{"start":{"line":1121,"column":8},"end":{"line":1121,"column":8}},{"start":{"line":1121,"column":8},"end":{"line":1121,"column":8}}]},"81":{"line":1143,"type":"if","locations":[{"start":{"line":1143,"column":8},"end":{"line":1143,"column":8}},{"start":{"line":1143,"column":8},"end":{"line":1143,"column":8}}]},"82":{"line":1145,"type":"cond-expr","locations":[{"start":{"line":1145,"column":37},"end":{"line":1145,"column":41}},{"start":{"line":1145,"column":44},"end":{"line":1145,"column":49}}]},"83":{"line":1146,"type":"cond-expr","locations":[{"start":{"line":1146,"column":37},"end":{"line":1146,"column":41}},{"start":{"line":1146,"column":44},"end":{"line":1146,"column":49}}]},"84":{"line":1164,"type":"if","locations":[{"start":{"line":1164,"column":8},"end":{"line":1164,"column":8}},{"start":{"line":1164,"column":8},"end":{"line":1164,"column":8}}]},"85":{"line":1393,"type":"cond-expr","locations":[{"start":{"line":1393,"column":34},"end":{"line":1393,"column":69}},{"start":{"line":1393,"column":72},"end":{"line":1393,"column":92}}]},"86":{"line":1394,"type":"cond-expr","locations":[{"start":{"line":1394,"column":34},"end":{"line":1394,"column":69}},{"start":{"line":1394,"column":72},"end":{"line":1394,"column":92}}]}},"code":["(function () { YUI.add('scrollview-base', function (Y, NAME) {","","/**"," * The scrollview-base module provides a basic ScrollView Widget, without scrollbar indicators"," *"," * @module scrollview"," * @submodule scrollview-base"," */",""," // Local vars","var getClassName = Y.ClassNameManager.getClassName,"," DOCUMENT = Y.config.doc,"," IE = Y.UA.ie,"," NATIVE_TRANSITIONS = Y.Transition.useNative,"," vendorPrefix = Y.Transition._VENDOR_PREFIX, // Todo: This is a private property, and alternative approaches should be investigated"," SCROLLVIEW = 'scrollview',"," CLASS_NAMES = {"," vertical: getClassName(SCROLLVIEW, 'vert'),"," horizontal: getClassName(SCROLLVIEW, 'horiz')"," },"," EV_SCROLL_END = 'scrollEnd',"," FLICK = 'flick',"," DRAG = 'drag',"," MOUSEWHEEL = 'mousewheel',"," UI = 'ui',"," TOP = 'top',"," LEFT = 'left',"," PX = 'px',"," AXIS = 'axis',"," SCROLL_Y = 'scrollY',"," SCROLL_X = 'scrollX',"," BOUNCE = 'bounce',"," DISABLED = 'disabled',"," DECELERATION = 'deceleration',"," DIM_X = 'x',"," DIM_Y = 'y',"," BOUNDING_BOX = 'boundingBox',"," CONTENT_BOX = 'contentBox',"," GESTURE_MOVE = 'gesturemove',"," START = 'start',"," END = 'end',"," EMPTY = '',"," ZERO = '0s',"," SNAP_DURATION = 'snapDuration',"," SNAP_EASING = 'snapEasing',"," EASING = 'easing',"," FRAME_DURATION = 'frameDuration',"," BOUNCE_RANGE = 'bounceRange',"," _constrain = function (val, min, max) {"," return Math.min(Math.max(val, min), max);"," };","","/**"," * ScrollView provides a scrollable widget, supporting flick gestures,"," * across both touch and mouse based devices."," *"," * @class ScrollView"," * @param config {Object} Object literal with initial attribute values"," * @extends Widget"," * @constructor"," */","function ScrollView() {"," ScrollView.superclass.constructor.apply(this, arguments);","}","","Y.ScrollView = Y.extend(ScrollView, Y.Widget, {",""," // *** Y.ScrollView prototype",""," /**"," * Flag driving whether or not we should try and force H/W acceleration when transforming. Currently enabled by default for Webkit."," * Used by the _transform method."," *"," * @property _forceHWTransforms"," * @type boolean"," * @protected"," */"," _forceHWTransforms: Y.UA.webkit ? true : false,",""," /**"," * <p>Used to control whether or not ScrollView's internal"," * gesturemovestart, gesturemove and gesturemoveend"," * event listeners should preventDefault. The value is an"," * object, with \"start\", \"move\" and \"end\" properties used to"," * specify which events should preventDefault and which shouldn't:</p>"," *"," * <pre>"," * {"," * start: false,"," * move: true,"," * end: false"," * }"," * </pre>"," *"," * <p>The default values are set up in order to prevent panning,"," * on touch devices, while allowing click listeners on elements inside"," * the ScrollView to be notified as expected.</p>"," *"," * @property _prevent"," * @type Object"," * @protected"," */"," _prevent: {"," start: false,"," move: true,"," end: false"," },",""," /**"," * Contains the distance (postive or negative) in pixels by which"," * the scrollview was last scrolled. This is useful when setting up"," * click listeners on the scrollview content, which on mouse based"," * devices are always fired, even after a drag/flick."," *"," * <p>Touch based devices don't currently fire a click event,"," * if the finger has been moved (beyond a threshold) so this"," * check isn't required, if working in a purely touch based environment</p>"," *"," * @property lastScrolledAmt"," * @type Number"," * @public"," * @default 0"," */"," lastScrolledAmt: 0,",""," /**"," * Internal state, defines the minimum amount that the scrollview can be scrolled along the X axis"," *"," * @property _minScrollX"," * @type number"," * @protected"," */"," _minScrollX: null,",""," /**"," * Internal state, defines the maximum amount that the scrollview can be scrolled along the X axis"," *"," * @property _maxScrollX"," * @type number"," * @protected"," */"," _maxScrollX: null,",""," /**"," * Internal state, defines the minimum amount that the scrollview can be scrolled along the Y axis"," *"," * @property _minScrollY"," * @type number"," * @protected"," */"," _minScrollY: null,",""," /**"," * Internal state, defines the maximum amount that the scrollview can be scrolled along the Y axis"," *"," * @property _maxScrollY"," * @type number"," * @protected"," */"," _maxScrollY: null,",""," /**"," * Designated initializer"," *"," * @method initializer"," * @param {Object} Configuration object for the plugin"," */"," initializer: function () {"," var sv = this;",""," // Cache these values, since they aren't going to change."," sv._bb = sv.get(BOUNDING_BOX);"," sv._cb = sv.get(CONTENT_BOX);",""," // Cache some attributes"," sv._cAxis = sv.get(AXIS);"," sv._cBounce = sv.get(BOUNCE);"," sv._cBounceRange = sv.get(BOUNCE_RANGE);"," sv._cDeceleration = sv.get(DECELERATION);"," sv._cFrameDuration = sv.get(FRAME_DURATION);"," },",""," /**"," * bindUI implementation"," *"," * Hooks up events for the widget"," * @method bindUI"," */"," bindUI: function () {"," var sv = this;",""," // Bind interaction listers"," sv._bindFlick(sv.get(FLICK));"," sv._bindDrag(sv.get(DRAG));"," sv._bindMousewheel(true);",""," // Bind change events"," sv._bindAttrs();",""," // IE SELECT HACK. See if we can do this non-natively and in the gesture for a future release."," if (IE) {"," sv._fixIESelect(sv._bb, sv._cb);"," }",""," // Set any deprecated static properties"," if (ScrollView.SNAP_DURATION) {"," sv.set(SNAP_DURATION, ScrollView.SNAP_DURATION);"," }",""," if (ScrollView.SNAP_EASING) {"," sv.set(SNAP_EASING, ScrollView.SNAP_EASING);"," }",""," if (ScrollView.EASING) {"," sv.set(EASING, ScrollView.EASING);"," }",""," if (ScrollView.FRAME_STEP) {"," sv.set(FRAME_DURATION, ScrollView.FRAME_STEP);"," }",""," if (ScrollView.BOUNCE_RANGE) {"," sv.set(BOUNCE_RANGE, ScrollView.BOUNCE_RANGE);"," }",""," // Recalculate dimension properties"," // TODO: This should be throttled."," // Y.one(WINDOW).after('resize', sv._afterDimChange, sv);"," },",""," /**"," * Bind event listeners"," *"," * @method _bindAttrs"," * @private"," */"," _bindAttrs: function () {"," var sv = this,"," scrollChangeHandler = sv._afterScrollChange,"," dimChangeHandler = sv._afterDimChange;",""," // Bind any change event listeners"," sv.after({"," 'scrollEnd': sv._afterScrollEnd,"," 'disabledChange': sv._afterDisabledChange,"," 'flickChange': sv._afterFlickChange,"," 'dragChange': sv._afterDragChange,"," 'axisChange': sv._afterAxisChange,"," 'scrollYChange': scrollChangeHandler,"," 'scrollXChange': scrollChangeHandler,"," 'heightChange': dimChangeHandler,"," 'widthChange': dimChangeHandler"," });"," },",""," /**"," * Bind (or unbind) gesture move listeners required for drag support"," *"," * @method _bindDrag"," * @param drag {boolean} If true, the method binds listener to enable"," * drag (gesturemovestart). If false, the method unbinds gesturemove"," * listeners for drag support."," * @private"," */"," _bindDrag: function (drag) {"," var sv = this,"," bb = sv._bb;",""," // Unbind any previous 'drag' listeners"," bb.detach(DRAG + '|*');",""," if (drag) {"," bb.on(DRAG + '|' + GESTURE_MOVE + START, Y.bind(sv._onGestureMoveStart, sv));"," }"," },",""," /**"," * Bind (or unbind) flick listeners."," *"," * @method _bindFlick"," * @param flick {Object|boolean} If truthy, the method binds listeners for"," * flick support. If false, the method unbinds flick listeners."," * @private"," */"," _bindFlick: function (flick) {"," var sv = this,"," bb = sv._bb;",""," // Unbind any previous 'flick' listeners"," bb.detach(FLICK + '|*');",""," if (flick) {"," bb.on(FLICK + '|' + FLICK, Y.bind(sv._flick, sv), flick);",""," // Rebind Drag, becuase _onGestureMoveEnd always has to fire -after- _flick"," sv._bindDrag(sv.get(DRAG));"," }"," },",""," /**"," * Bind (or unbind) mousewheel listeners."," *"," * @method _bindMousewheel"," * @param mousewheel {Object|boolean} If truthy, the method binds listeners for"," * mousewheel support. If false, the method unbinds mousewheel listeners."," * @private"," */"," _bindMousewheel: function (mousewheel) {"," var sv = this,"," bb = sv._bb;",""," // Unbind any previous 'mousewheel' listeners"," // TODO: This doesn't actually appear to work properly. Fix. #2532743"," bb.detach(MOUSEWHEEL + '|*');",""," // Only enable for vertical scrollviews"," if (mousewheel) {"," // Bound to document, because that's where mousewheel events fire off of."," Y.one(DOCUMENT).on(MOUSEWHEEL, Y.bind(sv._mousewheel, sv));"," }"," },",""," /**"," * syncUI implementation."," *"," * Update the scroll position, based on the current value of scrollX/scrollY."," *"," * @method syncUI"," */"," syncUI: function () {"," var sv = this,"," scrollDims = sv._getScrollDims(),"," width = scrollDims.offsetWidth,"," height = scrollDims.offsetHeight,"," scrollWidth = scrollDims.scrollWidth,"," scrollHeight = scrollDims.scrollHeight;",""," // If the axis is undefined, auto-calculate it"," if (sv._cAxis === undefined) {"," // This should only ever be run once (for now)."," // In the future SV might post-load axis changes"," sv._cAxis = {"," x: (scrollWidth > width),"," y: (scrollHeight > height)"," };",""," sv._set(AXIS, sv._cAxis);"," }",""," // get text direction on or inherited by scrollview node"," sv.rtl = (sv._cb.getComputedStyle('direction') === 'rtl');",""," // Cache the disabled value"," sv._cDisabled = sv.get(DISABLED);",""," // Run this to set initial values"," sv._uiDimensionsChange();",""," // If we're out-of-bounds, snap back."," if (sv._isOutOfBounds()) {"," sv._snapBack();"," }"," },",""," /**"," * Utility method to obtain widget dimensions"," *"," * @method _getScrollDims"," * @return {Object} The offsetWidth, offsetHeight, scrollWidth and"," * scrollHeight as an array: [offsetWidth, offsetHeight, scrollWidth,"," * scrollHeight]"," * @private"," */"," _getScrollDims: function () {"," var sv = this,"," cb = sv._cb,"," bb = sv._bb,"," TRANS = ScrollView._TRANSITION,"," // Ideally using CSSMatrix - don't think we have it normalized yet though."," // origX = (new WebKitCSSMatrix(cb.getComputedStyle(\"transform\"))).e,"," // origY = (new WebKitCSSMatrix(cb.getComputedStyle(\"transform\"))).f,"," origX = sv.get(SCROLL_X),"," origY = sv.get(SCROLL_Y),"," origHWTransform,"," dims;",""," // TODO: Is this OK? Just in case it's called 'during' a transition."," if (NATIVE_TRANSITIONS) {"," cb.setStyle(TRANS.DURATION, ZERO);"," cb.setStyle(TRANS.PROPERTY, EMPTY);"," }",""," origHWTransform = sv._forceHWTransforms;"," sv._forceHWTransforms = false; // the z translation was causing issues with picking up accurate scrollWidths in Chrome/Mac.",""," sv._moveTo(cb, 0, 0);"," dims = {"," 'offsetWidth': bb.get('offsetWidth'),"," 'offsetHeight': bb.get('offsetHeight'),"," 'scrollWidth': bb.get('scrollWidth'),"," 'scrollHeight': bb.get('scrollHeight')"," };"," sv._moveTo(cb, -(origX), -(origY));",""," sv._forceHWTransforms = origHWTransform;",""," return dims;"," },",""," /**"," * This method gets invoked whenever the height or width attributes change,"," * allowing us to determine which scrolling axes need to be enabled."," *"," * @method _uiDimensionsChange"," * @protected"," */"," _uiDimensionsChange: function () {"," var sv = this,"," bb = sv._bb,"," scrollDims = sv._getScrollDims(),"," width = scrollDims.offsetWidth,"," height = scrollDims.offsetHeight,"," scrollWidth = scrollDims.scrollWidth,"," scrollHeight = scrollDims.scrollHeight,"," rtl = sv.rtl,"," svAxis = sv._cAxis,"," minScrollX = (rtl ? Math.min(0, -(scrollWidth - width)) : 0),"," maxScrollX = (rtl ? 0 : Math.max(0, scrollWidth - width)),"," minScrollY = 0,"," maxScrollY = Math.max(0, scrollHeight - height);",""," if (svAxis && svAxis.x) {"," bb.addClass(CLASS_NAMES.horizontal);"," }",""," if (svAxis && svAxis.y) {"," bb.addClass(CLASS_NAMES.vertical);"," }",""," sv._setBounds({"," minScrollX: minScrollX,"," maxScrollX: maxScrollX,"," minScrollY: minScrollY,"," maxScrollY: maxScrollY"," });"," },",""," /**"," * Set the bounding dimensions of the ScrollView"," *"," * @method _setBounds"," * @protected"," * @param bounds {Object} [duration] ms of the scroll animation. (default is 0)"," * @param {Number} [bounds.minScrollX] The minimum scroll X value"," * @param {Number} [bounds.maxScrollX] The maximum scroll X value"," * @param {Number} [bounds.minScrollY] The minimum scroll Y value"," * @param {Number} [bounds.maxScrollY] The maximum scroll Y value"," */"," _setBounds: function (bounds) {"," var sv = this;",""," // TODO: Do a check to log if the bounds are invalid",""," sv._minScrollX = bounds.minScrollX;"," sv._maxScrollX = bounds.maxScrollX;"," sv._minScrollY = bounds.minScrollY;"," sv._maxScrollY = bounds.maxScrollY;"," },",""," /**"," * Get the bounding dimensions of the ScrollView"," *"," * @method _getBounds"," * @protected"," */"," _getBounds: function () {"," var sv = this;",""," return {"," minScrollX: sv._minScrollX,"," maxScrollX: sv._maxScrollX,"," minScrollY: sv._minScrollY,"," maxScrollY: sv._maxScrollY"," };",""," },",""," /**"," * Scroll the element to a given xy coordinate"," *"," * @method scrollTo"," * @param x {Number} The x-position to scroll to. (null for no movement)"," * @param y {Number} The y-position to scroll to. (null for no movement)"," * @param {Number} [duration] ms of the scroll animation. (default is 0)"," * @param {String} [easing] An easing equation if duration is set. (default is `easing` attribute)"," * @param {String} [node] The node to transform. Setting this can be useful in"," * dual-axis paginated instances. (default is the instance's contentBox)"," */"," scrollTo: function (x, y, duration, easing, node) {"," // Check to see if widget is disabled"," if (this._cDisabled) {"," return;"," }",""," var sv = this,"," cb = sv._cb,"," TRANS = ScrollView._TRANSITION,"," callback = Y.bind(sv._onTransEnd, sv), // @Todo : cache this"," newX = 0,"," newY = 0,"," transition = {},"," transform;",""," // default the optional arguments"," duration = duration || 0;"," easing = easing || sv.get(EASING); // @TODO: Cache this"," node = node || cb;",""," if (x !== null) {"," sv.set(SCROLL_X, x, {src:UI});"," newX = -(x);"," }",""," if (y !== null) {"," sv.set(SCROLL_Y, y, {src:UI});"," newY = -(y);"," }",""," transform = sv._transform(newX, newY);",""," if (NATIVE_TRANSITIONS) {"," // ANDROID WORKAROUND - try and stop existing transition, before kicking off new one."," node.setStyle(TRANS.DURATION, ZERO).setStyle(TRANS.PROPERTY, EMPTY);"," }",""," // Move"," if (duration === 0) {"," if (NATIVE_TRANSITIONS) {"," node.setStyle('transform', transform);"," }"," else {"," // TODO: If both set, batch them in the same update"," // Update: Nope, setStyles() just loops through each property and applies it."," if (x !== null) {"," node.setStyle(LEFT, newX + PX);"," }"," if (y !== null) {"," node.setStyle(TOP, newY + PX);"," }"," }"," }",""," // Animate"," else {"," transition.easing = easing;"," transition.duration = duration / 1000;",""," if (NATIVE_TRANSITIONS) {"," transition.transform = transform;"," }"," else {"," transition.left = newX + PX;"," transition.top = newY + PX;"," }",""," node.transition(transition, callback);"," }"," },",""," /**"," * Utility method, to create the translate transform string with the"," * x, y translation amounts provided."," *"," * @method _transform"," * @param {Number} x Number of pixels to translate along the x axis"," * @param {Number} y Number of pixels to translate along the y axis"," * @private"," */"," _transform: function (x, y) {"," // TODO: Would we be better off using a Matrix for this?"," var prop = 'translate(' + x + 'px, ' + y + 'px)';",""," if (this._forceHWTransforms) {"," prop += ' translateZ(0)';"," }",""," return prop;"," },",""," /**"," * Utility method, to move the given element to the given xy position"," *"," * @method _moveTo"," * @param node {Node} The node to move"," * @param x {Number} The x-position to move to"," * @param y {Number} The y-position to move to"," * @private"," */"," _moveTo : function(node, x, y) {"," if (NATIVE_TRANSITIONS) {"," node.setStyle('transform', this._transform(x, y));"," } else {"," node.setStyle(LEFT, x + PX);"," node.setStyle(TOP, y + PX);"," }"," },","",""," /**"," * Content box transition callback"," *"," * @method _onTransEnd"," * @param {EventFacade} e The event facade"," * @private"," */"," _onTransEnd: function () {"," var sv = this;",""," // If for some reason we're OOB, snapback"," if (sv._isOutOfBounds()) {"," sv._snapBack();"," }"," else {"," /**"," * Notification event fired at the end of a scroll transition"," *"," * @event scrollEnd"," * @param e {EventFacade} The default event facade."," */"," sv.fire(EV_SCROLL_END);"," }"," },",""," /**"," * gesturemovestart event handler"," *"," * @method _onGestureMoveStart"," * @param e {EventFacade} The gesturemovestart event facade"," * @private"," */"," _onGestureMoveStart: function (e) {",""," if (this._cDisabled) {"," return false;"," }",""," var sv = this,"," bb = sv._bb,"," currentX = sv.get(SCROLL_X),"," currentY = sv.get(SCROLL_Y),"," clientX = e.clientX,"," clientY = e.clientY;",""," if (sv._prevent.start) {"," e.preventDefault();"," }",""," // if a flick animation is in progress, cancel it"," if (sv._flickAnim) {"," sv._cancelFlick();"," sv._onTransEnd();"," }",""," // Reset lastScrolledAmt"," sv.lastScrolledAmt = 0;",""," // Stores data for this gesture cycle. Cleaned up later"," sv._gesture = {",""," // Will hold the axis value"," axis: null,",""," // The current attribute values"," startX: currentX,"," startY: currentY,",""," // The X/Y coordinates where the event began"," startClientX: clientX,"," startClientY: clientY,",""," // The X/Y coordinates where the event will end"," endClientX: null,"," endClientY: null,",""," // The current delta of the event"," deltaX: null,"," deltaY: null,",""," // Will be populated for flicks"," flick: null,",""," // Create some listeners for the rest of the gesture cycle"," onGestureMove: bb.on(DRAG + '|' + GESTURE_MOVE, Y.bind(sv._onGestureMove, sv)),",""," // @TODO: Don't bind gestureMoveEnd if it's a Flick?"," onGestureMoveEnd: bb.on(DRAG + '|' + GESTURE_MOVE + END, Y.bind(sv._onGestureMoveEnd, sv))"," };"," },",""," /**"," * gesturemove event handler"," *"," * @method _onGestureMove"," * @param e {EventFacade} The gesturemove event facade"," * @private"," */"," _onGestureMove: function (e) {"," var sv = this,"," gesture = sv._gesture,"," svAxis = sv._cAxis,"," svAxisX = svAxis.x,"," svAxisY = svAxis.y,"," startX = gesture.startX,"," startY = gesture.startY,"," startClientX = gesture.startClientX,"," startClientY = gesture.startClientY,"," clientX = e.clientX,"," clientY = e.clientY;",""," if (sv._prevent.move) {"," e.preventDefault();"," }",""," gesture.deltaX = startClientX - clientX;"," gesture.deltaY = startClientY - clientY;",""," // Determine if this is a vertical or horizontal movement"," // @TODO: This is crude, but it works. Investigate more intelligent ways to detect intent"," if (gesture.axis === null) {"," gesture.axis = (Math.abs(gesture.deltaX) > Math.abs(gesture.deltaY)) ? DIM_X : DIM_Y;"," }",""," // Move X or Y. @TODO: Move both if dualaxis."," if (gesture.axis === DIM_X && svAxisX) {"," sv.set(SCROLL_X, startX + gesture.deltaX);"," }"," else if (gesture.axis === DIM_Y && svAxisY) {"," sv.set(SCROLL_Y, startY + gesture.deltaY);"," }"," },",""," /**"," * gesturemoveend event handler"," *"," * @method _onGestureMoveEnd"," * @param e {EventFacade} The gesturemoveend event facade"," * @private"," */"," _onGestureMoveEnd: function (e) {"," var sv = this,"," gesture = sv._gesture,"," flick = gesture.flick,"," clientX = e.clientX,"," clientY = e.clientY,"," isOOB;",""," if (sv._prevent.end) {"," e.preventDefault();"," }",""," // Store the end X/Y coordinates"," gesture.endClientX = clientX;"," gesture.endClientY = clientY;",""," // Cleanup the event handlers"," gesture.onGestureMove.detach();"," gesture.onGestureMoveEnd.detach();",""," // If this wasn't a flick, wrap up the gesture cycle"," if (!flick) {"," // @TODO: Be more intelligent about this. Look at the Flick attribute to see"," // if it is safe to assume _flick did or didn't fire."," // Then, the order _flick and _onGestureMoveEnd fire doesn't matter?",""," // If there was movement (_onGestureMove fired)"," if (gesture.deltaX !== null && gesture.deltaY !== null) {",""," isOOB = sv._isOutOfBounds();",""," // If we're out-out-bounds, then snapback"," if (isOOB) {"," sv._snapBack();"," }",""," // Inbounds"," else {"," // Fire scrollEnd unless this is a paginated instance and the gesture axis is the same as paginator's"," // Not totally confident this is ideal to access a plugin's properties from a host, @TODO revisit"," if (!sv.pages || (sv.pages && !sv.pages.get(AXIS)[gesture.axis])) {"," sv._onTransEnd();"," }"," }"," }"," }"," },",""," /**"," * Execute a flick at the end of a scroll action"," *"," * @method _flick"," * @param e {EventFacade} The Flick event facade"," * @private"," */"," _flick: function (e) {"," if (this._cDisabled) {"," return false;"," }",""," var sv = this,"," svAxis = sv._cAxis,"," flick = e.flick,"," flickAxis = flick.axis,"," flickVelocity = flick.velocity,"," axisAttr = flickAxis === DIM_X ? SCROLL_X : SCROLL_Y,"," startPosition = sv.get(axisAttr);",""," // Sometimes flick is enabled, but drag is disabled"," if (sv._gesture) {"," sv._gesture.flick = flick;"," }",""," // Prevent unneccesary firing of _flickFrame if we can't scroll on the flick axis"," if (svAxis[flickAxis]) {"," sv._flickFrame(flickVelocity, flickAxis, startPosition);"," }"," },",""," /**"," * Execute a single frame in the flick animation"," *"," * @method _flickFrame"," * @param velocity {Number} The velocity of this animated frame"," * @param flickAxis {String} The axis on which to animate"," * @param startPosition {Number} The starting X/Y point to flick from"," * @protected"," */"," _flickFrame: function (velocity, flickAxis, startPosition) {",""," var sv = this,"," axisAttr = flickAxis === DIM_X ? SCROLL_X : SCROLL_Y,"," bounds = sv._getBounds(),",""," // Localize cached values"," bounce = sv._cBounce,"," bounceRange = sv._cBounceRange,"," deceleration = sv._cDeceleration,"," frameDuration = sv._cFrameDuration,",""," // Calculate"," newVelocity = velocity * deceleration,"," newPosition = startPosition - (frameDuration * newVelocity),",""," // Some convinience conditions"," min = flickAxis === DIM_X ? bounds.minScrollX : bounds.minScrollY,"," max = flickAxis === DIM_X ? bounds.maxScrollX : bounds.maxScrollY,"," belowMin = (newPosition < min),"," belowMax = (newPosition < max),"," aboveMin = (newPosition > min),"," aboveMax = (newPosition > max),"," belowMinRange = (newPosition < (min - bounceRange)),"," withinMinRange = (belowMin && (newPosition > (min - bounceRange))),"," withinMaxRange = (aboveMax && (newPosition < (max + bounceRange))),"," aboveMaxRange = (newPosition > (max + bounceRange)),"," tooSlow;",""," // If we're within the range but outside min/max, dampen the velocity"," if (withinMinRange || withinMaxRange) {"," newVelocity *= bounce;"," }",""," // Is the velocity too slow to bother?"," tooSlow = (Math.abs(newVelocity).toFixed(4) < 0.015);",""," // If the velocity is too slow or we're outside the range"," if (tooSlow || belowMinRange || aboveMaxRange) {"," // Cancel and delete sv._flickAnim"," if (sv._flickAnim) {"," sv._cancelFlick();"," }",""," // If we're inside the scroll area, just end"," if (aboveMin && belowMax) {"," sv._onTransEnd();"," }",""," // We're outside the scroll area, so we need to snap back"," else {"," sv._snapBack();"," }"," }",""," // Otherwise, animate to the next frame"," else {"," // @TODO: maybe use requestAnimationFrame instead"," sv._flickAnim = Y.later(frameDuration, sv, '_flickFrame', [newVelocity, flickAxis, newPosition]);"," sv.set(axisAttr, newPosition);"," }"," },",""," _cancelFlick: function () {"," var sv = this;",""," if (sv._flickAnim) {"," // Cancel the flick (if it exists)"," sv._flickAnim.cancel();",""," // Also delete it, otherwise _onGestureMoveStart will think we're still flicking"," delete sv._flickAnim;"," }",""," },",""," /**"," * Handle mousewheel events on the widget"," *"," * @method _mousewheel"," * @param e {EventFacade} The mousewheel event facade"," * @private"," */"," _mousewheel: function (e) {"," var sv = this,"," scrollY = sv.get(SCROLL_Y),"," bounds = sv._getBounds(),"," bb = sv._bb,"," scrollOffset = 10, // 10px"," isForward = (e.wheelDelta > 0),"," scrollToY = scrollY - ((isForward ? 1 : -1) * scrollOffset);",""," scrollToY = _constrain(scrollToY, bounds.minScrollY, bounds.maxScrollY);",""," // Because Mousewheel events fire off 'document', every ScrollView widget will react"," // to any mousewheel anywhere on the page. This check will ensure that the mouse is currently"," // over this specific ScrollView. Also, only allow mousewheel scrolling on Y-axis,"," // becuase otherwise the 'prevent' will block page scrolling."," if (bb.contains(e.target) && sv._cAxis[DIM_Y]) {",""," // Reset lastScrolledAmt"," sv.lastScrolledAmt = 0;",""," // Jump to the new offset"," sv.set(SCROLL_Y, scrollToY);",""," // if we have scrollbars plugin, update & set the flash timer on the scrollbar"," // @TODO: This probably shouldn't be in this module"," if (sv.scrollbars) {"," // @TODO: The scrollbars should handle this themselves"," sv.scrollbars._update();"," sv.scrollbars.flash();"," // or just this"," // sv.scrollbars._hostDimensionsChange();"," }",""," // Fire the 'scrollEnd' event"," sv._onTransEnd();",""," // prevent browser default behavior on mouse scroll"," e.preventDefault();"," }"," },",""," /**"," * Checks to see the current scrollX/scrollY position beyond the min/max boundary"," *"," * @method _isOutOfBounds"," * @param x {Number} [optional] The X position to check"," * @param y {Number} [optional] The Y position to check"," * @return {Boolean} Whether the current X/Y position is out of bounds (true) or not (false)"," * @private"," */"," _isOutOfBounds: function (x, y) {"," var sv = this,"," svAxis = sv._cAxis,"," svAxisX = svAxis.x,"," svAxisY = svAxis.y,"," currentX = x || sv.get(SCROLL_X),"," currentY = y || sv.get(SCROLL_Y),"," bounds = sv._getBounds(),"," minX = bounds.minScrollX,"," minY = bounds.minScrollY,"," maxX = bounds.maxScrollX,"," maxY = bounds.maxScrollY;",""," return (svAxisX && (currentX < minX || currentX > maxX)) || (svAxisY && (currentY < minY || currentY > maxY));"," },",""," /**"," * Bounces back"," * @TODO: Should be more generalized and support both X and Y detection"," *"," * @method _snapBack"," * @private"," */"," _snapBack: function () {"," var sv = this,"," currentX = sv.get(SCROLL_X),"," currentY = sv.get(SCROLL_Y),"," bounds = sv._getBounds(),"," minX = bounds.minScrollX,"," minY = bounds.minScrollY,"," maxX = bounds.maxScrollX,"," maxY = bounds.maxScrollY,"," newY = _constrain(currentY, minY, maxY),"," newX = _constrain(currentX, minX, maxX),"," duration = sv.get(SNAP_DURATION),"," easing = sv.get(SNAP_EASING);",""," if (newX !== currentX) {"," sv.set(SCROLL_X, newX, {duration:duration, easing:easing});"," }"," else if (newY !== currentY) {"," sv.set(SCROLL_Y, newY, {duration:duration, easing:easing});"," }"," else {"," sv._onTransEnd();"," }"," },",""," /**"," * After listener for changes to the scrollX or scrollY attribute"," *"," * @method _afterScrollChange"," * @param e {EventFacade} The event facade"," * @protected"," */"," _afterScrollChange: function (e) {"," if (e.src === ScrollView.UI_SRC) {"," return false;"," }",""," var sv = this,"," duration = e.duration,"," easing = e.easing,"," val = e.newVal,"," scrollToArgs = [];",""," // Set the scrolled value"," sv.lastScrolledAmt = sv.lastScrolledAmt + (e.newVal - e.prevVal);",""," // Generate the array of args to pass to scrollTo()"," if (e.attrName === SCROLL_X) {"," scrollToArgs.push(val);"," scrollToArgs.push(sv.get(SCROLL_Y));"," }"," else {"," scrollToArgs.push(sv.get(SCROLL_X));"," scrollToArgs.push(val);"," }",""," scrollToArgs.push(duration);"," scrollToArgs.push(easing);",""," sv.scrollTo.apply(sv, scrollToArgs);"," },",""," /**"," * After listener for changes to the flick attribute"," *"," * @method _afterFlickChange"," * @param e {EventFacade} The event facade"," * @protected"," */"," _afterFlickChange: function (e) {"," this._bindFlick(e.newVal);"," },",""," /**"," * After listener for changes to the disabled attribute"," *"," * @method _afterDisabledChange"," * @param e {EventFacade} The event facade"," * @protected"," */"," _afterDisabledChange: function (e) {"," // Cache for performance - we check during move"," this._cDisabled = e.newVal;"," },",""," /**"," * After listener for the axis attribute"," *"," * @method _afterAxisChange"," * @param e {EventFacade} The event facade"," * @protected"," */"," _afterAxisChange: function (e) {"," this._cAxis = e.newVal;"," },",""," /**"," * After listener for changes to the drag attribute"," *"," * @method _afterDragChange"," * @param e {EventFacade} The event facade"," * @protected"," */"," _afterDragChange: function (e) {"," this._bindDrag(e.newVal);"," },",""," /**"," * After listener for the height or width attribute"," *"," * @method _afterDimChange"," * @param e {EventFacade} The event facade"," * @protected"," */"," _afterDimChange: function () {"," this._uiDimensionsChange();"," },",""," /**"," * After listener for scrollEnd, for cleanup"," *"," * @method _afterScrollEnd"," * @param e {EventFacade} The event facade"," * @protected"," */"," _afterScrollEnd: function () {"," var sv = this;",""," if (sv._flickAnim) {"," sv._cancelFlick();"," }",""," // Ideally this should be removed, but doing so causing some JS errors with fast swiping"," // because _gesture is being deleted after the previous one has been overwritten"," // delete sv._gesture; // TODO: Move to sv.prevGesture?"," },",""," /**"," * Setter for 'axis' attribute"," *"," * @method _axisSetter"," * @param val {Mixed} A string ('x', 'y', 'xy') to specify which axis/axes to allow scrolling on"," * @param name {String} The attribute name"," * @return {Object} An object to specify scrollability on the x & y axes"," *"," * @protected"," */"," _axisSetter: function (val) {",""," // Turn a string into an axis object"," if (Y.Lang.isString(val)) {"," return {"," x: val.match(/x/i) ? true : false,"," y: val.match(/y/i) ? true : false"," };"," }"," },",""," /**"," * The scrollX, scrollY setter implementation"," *"," * @method _setScroll"," * @private"," * @param {Number} val"," * @param {String} dim"," *"," * @return {Number} The value"," */"," _setScroll : function(val) {",""," // Just ensure the widget is not disabled"," if (this._cDisabled) {"," val = Y.Attribute.INVALID_VALUE;"," }",""," return val;"," },",""," /**"," * Setter for the scrollX attribute"," *"," * @method _setScrollX"," * @param val {Number} The new scrollX value"," * @return {Number} The normalized value"," * @protected"," */"," _setScrollX: function(val) {"," return this._setScroll(val, DIM_X);"," },",""," /**"," * Setter for the scrollY ATTR"," *"," * @method _setScrollY"," * @param val {Number} The new scrollY value"," * @return {Number} The normalized value"," * @protected"," */"," _setScrollY: function(val) {"," return this._setScroll(val, DIM_Y);"," }",""," // End prototype properties","","}, {",""," // Static properties",""," /**"," * The identity of the widget."," *"," * @property NAME"," * @type String"," * @default 'scrollview'"," * @readOnly"," * @protected"," * @static"," */"," NAME: 'scrollview',",""," /**"," * Static property used to define the default attribute configuration of"," * the Widget."," *"," * @property ATTRS"," * @type {Object}"," * @protected"," * @static"," */"," ATTRS: {",""," /**"," * Specifies ability to scroll on x, y, or x and y axis/axes."," *"," * @attribute axis"," * @type String"," */"," axis: {"," setter: '_axisSetter',"," writeOnce: 'initOnly'"," },",""," /**"," * The current scroll position in the x-axis"," *"," * @attribute scrollX"," * @type Number"," * @default 0"," */"," scrollX: {"," value: 0,"," setter: '_setScrollX'"," },",""," /**"," * The current scroll position in the y-axis"," *"," * @attribute scrollY"," * @type Number"," * @default 0"," */"," scrollY: {"," value: 0,"," setter: '_setScrollY'"," },",""," /**"," * Drag coefficent for inertial scrolling. The closer to 1 this"," * value is, the less friction during scrolling."," *"," * @attribute deceleration"," * @default 0.93"," */"," deceleration: {"," value: 0.93"," },",""," /**"," * Drag coefficient for intertial scrolling at the upper"," * and lower boundaries of the scrollview. Set to 0 to"," * disable \"rubber-banding\"."," *"," * @attribute bounce"," * @type Number"," * @default 0.1"," */"," bounce: {"," value: 0.1"," },",""," /**"," * The minimum distance and/or velocity which define a flick. Can be set to false,"," * to disable flick support (note: drag support is enabled/disabled separately)"," *"," * @attribute flick"," * @type Object"," * @default Object with properties minDistance = 10, minVelocity = 0.3."," */"," flick: {"," value: {"," minDistance: 10,"," minVelocity: 0.3"," }"," },",""," /**"," * Enable/Disable dragging the ScrollView content (note: flick support is enabled/disabled separately)"," * @attribute drag"," * @type boolean"," * @default true"," */"," drag: {"," value: true"," },",""," /**"," * The default duration to use when animating the bounce snap back."," *"," * @attribute snapDuration"," * @type Number"," * @default 400"," */"," snapDuration: {"," value: 400"," },",""," /**"," * The default easing to use when animating the bounce snap back."," *"," * @attribute snapEasing"," * @type String"," * @default 'ease-out'"," */"," snapEasing: {"," value: 'ease-out'"," },",""," /**"," * The default easing used when animating the flick"," *"," * @attribute easing"," * @type String"," * @default 'cubic-bezier(0, 0.1, 0, 1.0)'"," */"," easing: {"," value: 'cubic-bezier(0, 0.1, 0, 1.0)'"," },",""," /**"," * The interval (ms) used when animating the flick for JS-timer animations"," *"," * @attribute frameDuration"," * @type Number"," * @default 15"," */"," frameDuration: {"," value: 15"," },",""," /**"," * The default bounce distance in pixels"," *"," * @attribute bounceRange"," * @type Number"," * @default 150"," */"," bounceRange: {"," value: 150"," }"," },",""," /**"," * List of class names used in the scrollview's DOM"," *"," * @property CLASS_NAMES"," * @type Object"," * @static"," */"," CLASS_NAMES: CLASS_NAMES,",""," /**"," * Flag used to source property changes initiated from the DOM"," *"," * @property UI_SRC"," * @type String"," * @static"," * @default 'ui'"," */"," UI_SRC: UI,",""," /**"," * Object map of style property names used to set transition properties."," * Defaults to the vendor prefix established by the Transition module."," * The configured property names are `_TRANSITION.DURATION` (e.g. \"WebkitTransitionDuration\") and"," * `_TRANSITION.PROPERTY (e.g. \"WebkitTransitionProperty\")."," *"," * @property _TRANSITION"," * @private"," */"," _TRANSITION: {"," DURATION: (vendorPrefix ? vendorPrefix + 'TransitionDuration' : 'transitionDuration'),"," PROPERTY: (vendorPrefix ? vendorPrefix + 'TransitionProperty' : 'transitionProperty')"," },",""," /**"," * The default bounce distance in pixels"," *"," * @property BOUNCE_RANGE"," * @type Number"," * @static"," * @default false"," * @deprecated (in 3.7.0)"," */"," BOUNCE_RANGE: false,",""," /**"," * The interval (ms) used when animating the flick"," *"," * @property FRAME_STEP"," * @type Number"," * @static"," * @default false"," * @deprecated (in 3.7.0)"," */"," FRAME_STEP: false,",""," /**"," * The default easing used when animating the flick"," *"," * @property EASING"," * @type String"," * @static"," * @default false"," * @deprecated (in 3.7.0)"," */"," EASING: false,",""," /**"," * The default easing to use when animating the bounce snap back."," *"," * @property SNAP_EASING"," * @type String"," * @static"," * @default false"," * @deprecated (in 3.7.0)"," */"," SNAP_EASING: false,",""," /**"," * The default duration to use when animating the bounce snap back."," *"," * @property SNAP_DURATION"," * @type Number"," * @static"," * @default false"," * @deprecated (in 3.7.0)"," */"," SNAP_DURATION: false",""," // End static properties","","});","","","}, '3.16.0', {\"requires\": [\"widget\", \"event-gestures\", \"event-mousewheel\", \"transition\"], \"skinnable\": true});","","}());"]}; } var __cov_cyIK2vRXoVgOuWid4NBKqw = __coverage__['build/scrollview-base/scrollview-base.js']; __cov_cyIK2vRXoVgOuWid4NBKqw.s['1']++;YUI.add('scrollview-base',function(Y,NAME){__cov_cyIK2vRXoVgOuWid4NBKqw.f['1']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['2']++;var getClassName=Y.ClassNameManager.getClassName,DOCUMENT=Y.config.doc,IE=Y.UA.ie,NATIVE_TRANSITIONS=Y.Transition.useNative,vendorPrefix=Y.Transition._VENDOR_PREFIX,SCROLLVIEW='scrollview',CLASS_NAMES={vertical:getClassName(SCROLLVIEW,'vert'),horizontal:getClassName(SCROLLVIEW,'horiz')},EV_SCROLL_END='scrollEnd',FLICK='flick',DRAG='drag',MOUSEWHEEL='mousewheel',UI='ui',TOP='top',LEFT='left',PX='px',AXIS='axis',SCROLL_Y='scrollY',SCROLL_X='scrollX',BOUNCE='bounce',DISABLED='disabled',DECELERATION='deceleration',DIM_X='x',DIM_Y='y',BOUNDING_BOX='boundingBox',CONTENT_BOX='contentBox',GESTURE_MOVE='gesturemove',START='start',END='end',EMPTY='',ZERO='0s',SNAP_DURATION='snapDuration',SNAP_EASING='snapEasing',EASING='easing',FRAME_DURATION='frameDuration',BOUNCE_RANGE='bounceRange',_constrain=function(val,min,max){__cov_cyIK2vRXoVgOuWid4NBKqw.f['2']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['3']++;return Math.min(Math.max(val,min),max);};__cov_cyIK2vRXoVgOuWid4NBKqw.s['4']++;function ScrollView(){__cov_cyIK2vRXoVgOuWid4NBKqw.f['3']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['5']++;ScrollView.superclass.constructor.apply(this,arguments);}__cov_cyIK2vRXoVgOuWid4NBKqw.s['6']++;Y.ScrollView=Y.extend(ScrollView,Y.Widget,{_forceHWTransforms:Y.UA.webkit?(__cov_cyIK2vRXoVgOuWid4NBKqw.b['1'][0]++,true):(__cov_cyIK2vRXoVgOuWid4NBKqw.b['1'][1]++,false),_prevent:{start:false,move:true,end:false},lastScrolledAmt:0,_minScrollX:null,_maxScrollX:null,_minScrollY:null,_maxScrollY:null,initializer:function(){__cov_cyIK2vRXoVgOuWid4NBKqw.f['4']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['7']++;var sv=this;__cov_cyIK2vRXoVgOuWid4NBKqw.s['8']++;sv._bb=sv.get(BOUNDING_BOX);__cov_cyIK2vRXoVgOuWid4NBKqw.s['9']++;sv._cb=sv.get(CONTENT_BOX);__cov_cyIK2vRXoVgOuWid4NBKqw.s['10']++;sv._cAxis=sv.get(AXIS);__cov_cyIK2vRXoVgOuWid4NBKqw.s['11']++;sv._cBounce=sv.get(BOUNCE);__cov_cyIK2vRXoVgOuWid4NBKqw.s['12']++;sv._cBounceRange=sv.get(BOUNCE_RANGE);__cov_cyIK2vRXoVgOuWid4NBKqw.s['13']++;sv._cDeceleration=sv.get(DECELERATION);__cov_cyIK2vRXoVgOuWid4NBKqw.s['14']++;sv._cFrameDuration=sv.get(FRAME_DURATION);},bindUI:function(){__cov_cyIK2vRXoVgOuWid4NBKqw.f['5']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['15']++;var sv=this;__cov_cyIK2vRXoVgOuWid4NBKqw.s['16']++;sv._bindFlick(sv.get(FLICK));__cov_cyIK2vRXoVgOuWid4NBKqw.s['17']++;sv._bindDrag(sv.get(DRAG));__cov_cyIK2vRXoVgOuWid4NBKqw.s['18']++;sv._bindMousewheel(true);__cov_cyIK2vRXoVgOuWid4NBKqw.s['19']++;sv._bindAttrs();__cov_cyIK2vRXoVgOuWid4NBKqw.s['20']++;if(IE){__cov_cyIK2vRXoVgOuWid4NBKqw.b['2'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['21']++;sv._fixIESelect(sv._bb,sv._cb);}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['2'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['22']++;if(ScrollView.SNAP_DURATION){__cov_cyIK2vRXoVgOuWid4NBKqw.b['3'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['23']++;sv.set(SNAP_DURATION,ScrollView.SNAP_DURATION);}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['3'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['24']++;if(ScrollView.SNAP_EASING){__cov_cyIK2vRXoVgOuWid4NBKqw.b['4'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['25']++;sv.set(SNAP_EASING,ScrollView.SNAP_EASING);}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['4'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['26']++;if(ScrollView.EASING){__cov_cyIK2vRXoVgOuWid4NBKqw.b['5'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['27']++;sv.set(EASING,ScrollView.EASING);}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['5'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['28']++;if(ScrollView.FRAME_STEP){__cov_cyIK2vRXoVgOuWid4NBKqw.b['6'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['29']++;sv.set(FRAME_DURATION,ScrollView.FRAME_STEP);}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['6'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['30']++;if(ScrollView.BOUNCE_RANGE){__cov_cyIK2vRXoVgOuWid4NBKqw.b['7'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['31']++;sv.set(BOUNCE_RANGE,ScrollView.BOUNCE_RANGE);}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['7'][1]++;}},_bindAttrs:function(){__cov_cyIK2vRXoVgOuWid4NBKqw.f['6']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['32']++;var sv=this,scrollChangeHandler=sv._afterScrollChange,dimChangeHandler=sv._afterDimChange;__cov_cyIK2vRXoVgOuWid4NBKqw.s['33']++;sv.after({'scrollEnd':sv._afterScrollEnd,'disabledChange':sv._afterDisabledChange,'flickChange':sv._afterFlickChange,'dragChange':sv._afterDragChange,'axisChange':sv._afterAxisChange,'scrollYChange':scrollChangeHandler,'scrollXChange':scrollChangeHandler,'heightChange':dimChangeHandler,'widthChange':dimChangeHandler});},_bindDrag:function(drag){__cov_cyIK2vRXoVgOuWid4NBKqw.f['7']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['34']++;var sv=this,bb=sv._bb;__cov_cyIK2vRXoVgOuWid4NBKqw.s['35']++;bb.detach(DRAG+'|*');__cov_cyIK2vRXoVgOuWid4NBKqw.s['36']++;if(drag){__cov_cyIK2vRXoVgOuWid4NBKqw.b['8'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['37']++;bb.on(DRAG+'|'+GESTURE_MOVE+START,Y.bind(sv._onGestureMoveStart,sv));}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['8'][1]++;}},_bindFlick:function(flick){__cov_cyIK2vRXoVgOuWid4NBKqw.f['8']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['38']++;var sv=this,bb=sv._bb;__cov_cyIK2vRXoVgOuWid4NBKqw.s['39']++;bb.detach(FLICK+'|*');__cov_cyIK2vRXoVgOuWid4NBKqw.s['40']++;if(flick){__cov_cyIK2vRXoVgOuWid4NBKqw.b['9'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['41']++;bb.on(FLICK+'|'+FLICK,Y.bind(sv._flick,sv),flick);__cov_cyIK2vRXoVgOuWid4NBKqw.s['42']++;sv._bindDrag(sv.get(DRAG));}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['9'][1]++;}},_bindMousewheel:function(mousewheel){__cov_cyIK2vRXoVgOuWid4NBKqw.f['9']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['43']++;var sv=this,bb=sv._bb;__cov_cyIK2vRXoVgOuWid4NBKqw.s['44']++;bb.detach(MOUSEWHEEL+'|*');__cov_cyIK2vRXoVgOuWid4NBKqw.s['45']++;if(mousewheel){__cov_cyIK2vRXoVgOuWid4NBKqw.b['10'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['46']++;Y.one(DOCUMENT).on(MOUSEWHEEL,Y.bind(sv._mousewheel,sv));}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['10'][1]++;}},syncUI:function(){__cov_cyIK2vRXoVgOuWid4NBKqw.f['10']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['47']++;var sv=this,scrollDims=sv._getScrollDims(),width=scrollDims.offsetWidth,height=scrollDims.offsetHeight,scrollWidth=scrollDims.scrollWidth,scrollHeight=scrollDims.scrollHeight;__cov_cyIK2vRXoVgOuWid4NBKqw.s['48']++;if(sv._cAxis===undefined){__cov_cyIK2vRXoVgOuWid4NBKqw.b['11'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['49']++;sv._cAxis={x:scrollWidth>width,y:scrollHeight>height};__cov_cyIK2vRXoVgOuWid4NBKqw.s['50']++;sv._set(AXIS,sv._cAxis);}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['11'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['51']++;sv.rtl=sv._cb.getComputedStyle('direction')==='rtl';__cov_cyIK2vRXoVgOuWid4NBKqw.s['52']++;sv._cDisabled=sv.get(DISABLED);__cov_cyIK2vRXoVgOuWid4NBKqw.s['53']++;sv._uiDimensionsChange();__cov_cyIK2vRXoVgOuWid4NBKqw.s['54']++;if(sv._isOutOfBounds()){__cov_cyIK2vRXoVgOuWid4NBKqw.b['12'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['55']++;sv._snapBack();}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['12'][1]++;}},_getScrollDims:function(){__cov_cyIK2vRXoVgOuWid4NBKqw.f['11']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['56']++;var sv=this,cb=sv._cb,bb=sv._bb,TRANS=ScrollView._TRANSITION,origX=sv.get(SCROLL_X),origY=sv.get(SCROLL_Y),origHWTransform,dims;__cov_cyIK2vRXoVgOuWid4NBKqw.s['57']++;if(NATIVE_TRANSITIONS){__cov_cyIK2vRXoVgOuWid4NBKqw.b['13'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['58']++;cb.setStyle(TRANS.DURATION,ZERO);__cov_cyIK2vRXoVgOuWid4NBKqw.s['59']++;cb.setStyle(TRANS.PROPERTY,EMPTY);}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['13'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['60']++;origHWTransform=sv._forceHWTransforms;__cov_cyIK2vRXoVgOuWid4NBKqw.s['61']++;sv._forceHWTransforms=false;__cov_cyIK2vRXoVgOuWid4NBKqw.s['62']++;sv._moveTo(cb,0,0);__cov_cyIK2vRXoVgOuWid4NBKqw.s['63']++;dims={'offsetWidth':bb.get('offsetWidth'),'offsetHeight':bb.get('offsetHeight'),'scrollWidth':bb.get('scrollWidth'),'scrollHeight':bb.get('scrollHeight')};__cov_cyIK2vRXoVgOuWid4NBKqw.s['64']++;sv._moveTo(cb,-origX,-origY);__cov_cyIK2vRXoVgOuWid4NBKqw.s['65']++;sv._forceHWTransforms=origHWTransform;__cov_cyIK2vRXoVgOuWid4NBKqw.s['66']++;return dims;},_uiDimensionsChange:function(){__cov_cyIK2vRXoVgOuWid4NBKqw.f['12']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['67']++;var sv=this,bb=sv._bb,scrollDims=sv._getScrollDims(),width=scrollDims.offsetWidth,height=scrollDims.offsetHeight,scrollWidth=scrollDims.scrollWidth,scrollHeight=scrollDims.scrollHeight,rtl=sv.rtl,svAxis=sv._cAxis,minScrollX=rtl?(__cov_cyIK2vRXoVgOuWid4NBKqw.b['14'][0]++,Math.min(0,-(scrollWidth-width))):(__cov_cyIK2vRXoVgOuWid4NBKqw.b['14'][1]++,0),maxScrollX=rtl?(__cov_cyIK2vRXoVgOuWid4NBKqw.b['15'][0]++,0):(__cov_cyIK2vRXoVgOuWid4NBKqw.b['15'][1]++,Math.max(0,scrollWidth-width)),minScrollY=0,maxScrollY=Math.max(0,scrollHeight-height);__cov_cyIK2vRXoVgOuWid4NBKqw.s['68']++;if((__cov_cyIK2vRXoVgOuWid4NBKqw.b['17'][0]++,svAxis)&&(__cov_cyIK2vRXoVgOuWid4NBKqw.b['17'][1]++,svAxis.x)){__cov_cyIK2vRXoVgOuWid4NBKqw.b['16'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['69']++;bb.addClass(CLASS_NAMES.horizontal);}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['16'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['70']++;if((__cov_cyIK2vRXoVgOuWid4NBKqw.b['19'][0]++,svAxis)&&(__cov_cyIK2vRXoVgOuWid4NBKqw.b['19'][1]++,svAxis.y)){__cov_cyIK2vRXoVgOuWid4NBKqw.b['18'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['71']++;bb.addClass(CLASS_NAMES.vertical);}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['18'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['72']++;sv._setBounds({minScrollX:minScrollX,maxScrollX:maxScrollX,minScrollY:minScrollY,maxScrollY:maxScrollY});},_setBounds:function(bounds){__cov_cyIK2vRXoVgOuWid4NBKqw.f['13']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['73']++;var sv=this;__cov_cyIK2vRXoVgOuWid4NBKqw.s['74']++;sv._minScrollX=bounds.minScrollX;__cov_cyIK2vRXoVgOuWid4NBKqw.s['75']++;sv._maxScrollX=bounds.maxScrollX;__cov_cyIK2vRXoVgOuWid4NBKqw.s['76']++;sv._minScrollY=bounds.minScrollY;__cov_cyIK2vRXoVgOuWid4NBKqw.s['77']++;sv._maxScrollY=bounds.maxScrollY;},_getBounds:function(){__cov_cyIK2vRXoVgOuWid4NBKqw.f['14']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['78']++;var sv=this;__cov_cyIK2vRXoVgOuWid4NBKqw.s['79']++;return{minScrollX:sv._minScrollX,maxScrollX:sv._maxScrollX,minScrollY:sv._minScrollY,maxScrollY:sv._maxScrollY};},scrollTo:function(x,y,duration,easing,node){__cov_cyIK2vRXoVgOuWid4NBKqw.f['15']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['80']++;if(this._cDisabled){__cov_cyIK2vRXoVgOuWid4NBKqw.b['20'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['81']++;return;}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['20'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['82']++;var sv=this,cb=sv._cb,TRANS=ScrollView._TRANSITION,callback=Y.bind(sv._onTransEnd,sv),newX=0,newY=0,transition={},transform;__cov_cyIK2vRXoVgOuWid4NBKqw.s['83']++;duration=(__cov_cyIK2vRXoVgOuWid4NBKqw.b['21'][0]++,duration)||(__cov_cyIK2vRXoVgOuWid4NBKqw.b['21'][1]++,0);__cov_cyIK2vRXoVgOuWid4NBKqw.s['84']++;easing=(__cov_cyIK2vRXoVgOuWid4NBKqw.b['22'][0]++,easing)||(__cov_cyIK2vRXoVgOuWid4NBKqw.b['22'][1]++,sv.get(EASING));__cov_cyIK2vRXoVgOuWid4NBKqw.s['85']++;node=(__cov_cyIK2vRXoVgOuWid4NBKqw.b['23'][0]++,node)||(__cov_cyIK2vRXoVgOuWid4NBKqw.b['23'][1]++,cb);__cov_cyIK2vRXoVgOuWid4NBKqw.s['86']++;if(x!==null){__cov_cyIK2vRXoVgOuWid4NBKqw.b['24'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['87']++;sv.set(SCROLL_X,x,{src:UI});__cov_cyIK2vRXoVgOuWid4NBKqw.s['88']++;newX=-x;}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['24'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['89']++;if(y!==null){__cov_cyIK2vRXoVgOuWid4NBKqw.b['25'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['90']++;sv.set(SCROLL_Y,y,{src:UI});__cov_cyIK2vRXoVgOuWid4NBKqw.s['91']++;newY=-y;}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['25'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['92']++;transform=sv._transform(newX,newY);__cov_cyIK2vRXoVgOuWid4NBKqw.s['93']++;if(NATIVE_TRANSITIONS){__cov_cyIK2vRXoVgOuWid4NBKqw.b['26'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['94']++;node.setStyle(TRANS.DURATION,ZERO).setStyle(TRANS.PROPERTY,EMPTY);}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['26'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['95']++;if(duration===0){__cov_cyIK2vRXoVgOuWid4NBKqw.b['27'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['96']++;if(NATIVE_TRANSITIONS){__cov_cyIK2vRXoVgOuWid4NBKqw.b['28'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['97']++;node.setStyle('transform',transform);}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['28'][1]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['98']++;if(x!==null){__cov_cyIK2vRXoVgOuWid4NBKqw.b['29'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['99']++;node.setStyle(LEFT,newX+PX);}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['29'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['100']++;if(y!==null){__cov_cyIK2vRXoVgOuWid4NBKqw.b['30'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['101']++;node.setStyle(TOP,newY+PX);}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['30'][1]++;}}}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['27'][1]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['102']++;transition.easing=easing;__cov_cyIK2vRXoVgOuWid4NBKqw.s['103']++;transition.duration=duration/1000;__cov_cyIK2vRXoVgOuWid4NBKqw.s['104']++;if(NATIVE_TRANSITIONS){__cov_cyIK2vRXoVgOuWid4NBKqw.b['31'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['105']++;transition.transform=transform;}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['31'][1]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['106']++;transition.left=newX+PX;__cov_cyIK2vRXoVgOuWid4NBKqw.s['107']++;transition.top=newY+PX;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['108']++;node.transition(transition,callback);}},_transform:function(x,y){__cov_cyIK2vRXoVgOuWid4NBKqw.f['16']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['109']++;var prop='translate('+x+'px, '+y+'px)';__cov_cyIK2vRXoVgOuWid4NBKqw.s['110']++;if(this._forceHWTransforms){__cov_cyIK2vRXoVgOuWid4NBKqw.b['32'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['111']++;prop+=' translateZ(0)';}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['32'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['112']++;return prop;},_moveTo:function(node,x,y){__cov_cyIK2vRXoVgOuWid4NBKqw.f['17']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['113']++;if(NATIVE_TRANSITIONS){__cov_cyIK2vRXoVgOuWid4NBKqw.b['33'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['114']++;node.setStyle('transform',this._transform(x,y));}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['33'][1]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['115']++;node.setStyle(LEFT,x+PX);__cov_cyIK2vRXoVgOuWid4NBKqw.s['116']++;node.setStyle(TOP,y+PX);}},_onTransEnd:function(){__cov_cyIK2vRXoVgOuWid4NBKqw.f['18']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['117']++;var sv=this;__cov_cyIK2vRXoVgOuWid4NBKqw.s['118']++;if(sv._isOutOfBounds()){__cov_cyIK2vRXoVgOuWid4NBKqw.b['34'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['119']++;sv._snapBack();}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['34'][1]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['120']++;sv.fire(EV_SCROLL_END);}},_onGestureMoveStart:function(e){__cov_cyIK2vRXoVgOuWid4NBKqw.f['19']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['121']++;if(this._cDisabled){__cov_cyIK2vRXoVgOuWid4NBKqw.b['35'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['122']++;return false;}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['35'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['123']++;var sv=this,bb=sv._bb,currentX=sv.get(SCROLL_X),currentY=sv.get(SCROLL_Y),clientX=e.clientX,clientY=e.clientY;__cov_cyIK2vRXoVgOuWid4NBKqw.s['124']++;if(sv._prevent.start){__cov_cyIK2vRXoVgOuWid4NBKqw.b['36'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['125']++;e.preventDefault();}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['36'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['126']++;if(sv._flickAnim){__cov_cyIK2vRXoVgOuWid4NBKqw.b['37'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['127']++;sv._cancelFlick();__cov_cyIK2vRXoVgOuWid4NBKqw.s['128']++;sv._onTransEnd();}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['37'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['129']++;sv.lastScrolledAmt=0;__cov_cyIK2vRXoVgOuWid4NBKqw.s['130']++;sv._gesture={axis:null,startX:currentX,startY:currentY,startClientX:clientX,startClientY:clientY,endClientX:null,endClientY:null,deltaX:null,deltaY:null,flick:null,onGestureMove:bb.on(DRAG+'|'+GESTURE_MOVE,Y.bind(sv._onGestureMove,sv)),onGestureMoveEnd:bb.on(DRAG+'|'+GESTURE_MOVE+END,Y.bind(sv._onGestureMoveEnd,sv))};},_onGestureMove:function(e){__cov_cyIK2vRXoVgOuWid4NBKqw.f['20']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['131']++;var sv=this,gesture=sv._gesture,svAxis=sv._cAxis,svAxisX=svAxis.x,svAxisY=svAxis.y,startX=gesture.startX,startY=gesture.startY,startClientX=gesture.startClientX,startClientY=gesture.startClientY,clientX=e.clientX,clientY=e.clientY;__cov_cyIK2vRXoVgOuWid4NBKqw.s['132']++;if(sv._prevent.move){__cov_cyIK2vRXoVgOuWid4NBKqw.b['38'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['133']++;e.preventDefault();}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['38'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['134']++;gesture.deltaX=startClientX-clientX;__cov_cyIK2vRXoVgOuWid4NBKqw.s['135']++;gesture.deltaY=startClientY-clientY;__cov_cyIK2vRXoVgOuWid4NBKqw.s['136']++;if(gesture.axis===null){__cov_cyIK2vRXoVgOuWid4NBKqw.b['39'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['137']++;gesture.axis=Math.abs(gesture.deltaX)>Math.abs(gesture.deltaY)?(__cov_cyIK2vRXoVgOuWid4NBKqw.b['40'][0]++,DIM_X):(__cov_cyIK2vRXoVgOuWid4NBKqw.b['40'][1]++,DIM_Y);}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['39'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['138']++;if((__cov_cyIK2vRXoVgOuWid4NBKqw.b['42'][0]++,gesture.axis===DIM_X)&&(__cov_cyIK2vRXoVgOuWid4NBKqw.b['42'][1]++,svAxisX)){__cov_cyIK2vRXoVgOuWid4NBKqw.b['41'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['139']++;sv.set(SCROLL_X,startX+gesture.deltaX);}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['41'][1]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['140']++;if((__cov_cyIK2vRXoVgOuWid4NBKqw.b['44'][0]++,gesture.axis===DIM_Y)&&(__cov_cyIK2vRXoVgOuWid4NBKqw.b['44'][1]++,svAxisY)){__cov_cyIK2vRXoVgOuWid4NBKqw.b['43'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['141']++;sv.set(SCROLL_Y,startY+gesture.deltaY);}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['43'][1]++;}}},_onGestureMoveEnd:function(e){__cov_cyIK2vRXoVgOuWid4NBKqw.f['21']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['142']++;var sv=this,gesture=sv._gesture,flick=gesture.flick,clientX=e.clientX,clientY=e.clientY,isOOB;__cov_cyIK2vRXoVgOuWid4NBKqw.s['143']++;if(sv._prevent.end){__cov_cyIK2vRXoVgOuWid4NBKqw.b['45'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['144']++;e.preventDefault();}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['45'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['145']++;gesture.endClientX=clientX;__cov_cyIK2vRXoVgOuWid4NBKqw.s['146']++;gesture.endClientY=clientY;__cov_cyIK2vRXoVgOuWid4NBKqw.s['147']++;gesture.onGestureMove.detach();__cov_cyIK2vRXoVgOuWid4NBKqw.s['148']++;gesture.onGestureMoveEnd.detach();__cov_cyIK2vRXoVgOuWid4NBKqw.s['149']++;if(!flick){__cov_cyIK2vRXoVgOuWid4NBKqw.b['46'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['150']++;if((__cov_cyIK2vRXoVgOuWid4NBKqw.b['48'][0]++,gesture.deltaX!==null)&&(__cov_cyIK2vRXoVgOuWid4NBKqw.b['48'][1]++,gesture.deltaY!==null)){__cov_cyIK2vRXoVgOuWid4NBKqw.b['47'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['151']++;isOOB=sv._isOutOfBounds();__cov_cyIK2vRXoVgOuWid4NBKqw.s['152']++;if(isOOB){__cov_cyIK2vRXoVgOuWid4NBKqw.b['49'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['153']++;sv._snapBack();}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['49'][1]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['154']++;if((__cov_cyIK2vRXoVgOuWid4NBKqw.b['51'][0]++,!sv.pages)||(__cov_cyIK2vRXoVgOuWid4NBKqw.b['51'][1]++,sv.pages)&&(__cov_cyIK2vRXoVgOuWid4NBKqw.b['51'][2]++,!sv.pages.get(AXIS)[gesture.axis])){__cov_cyIK2vRXoVgOuWid4NBKqw.b['50'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['155']++;sv._onTransEnd();}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['50'][1]++;}}}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['47'][1]++;}}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['46'][1]++;}},_flick:function(e){__cov_cyIK2vRXoVgOuWid4NBKqw.f['22']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['156']++;if(this._cDisabled){__cov_cyIK2vRXoVgOuWid4NBKqw.b['52'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['157']++;return false;}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['52'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['158']++;var sv=this,svAxis=sv._cAxis,flick=e.flick,flickAxis=flick.axis,flickVelocity=flick.velocity,axisAttr=flickAxis===DIM_X?(__cov_cyIK2vRXoVgOuWid4NBKqw.b['53'][0]++,SCROLL_X):(__cov_cyIK2vRXoVgOuWid4NBKqw.b['53'][1]++,SCROLL_Y),startPosition=sv.get(axisAttr);__cov_cyIK2vRXoVgOuWid4NBKqw.s['159']++;if(sv._gesture){__cov_cyIK2vRXoVgOuWid4NBKqw.b['54'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['160']++;sv._gesture.flick=flick;}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['54'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['161']++;if(svAxis[flickAxis]){__cov_cyIK2vRXoVgOuWid4NBKqw.b['55'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['162']++;sv._flickFrame(flickVelocity,flickAxis,startPosition);}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['55'][1]++;}},_flickFrame:function(velocity,flickAxis,startPosition){__cov_cyIK2vRXoVgOuWid4NBKqw.f['23']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['163']++;var sv=this,axisAttr=flickAxis===DIM_X?(__cov_cyIK2vRXoVgOuWid4NBKqw.b['56'][0]++,SCROLL_X):(__cov_cyIK2vRXoVgOuWid4NBKqw.b['56'][1]++,SCROLL_Y),bounds=sv._getBounds(),bounce=sv._cBounce,bounceRange=sv._cBounceRange,deceleration=sv._cDeceleration,frameDuration=sv._cFrameDuration,newVelocity=velocity*deceleration,newPosition=startPosition-frameDuration*newVelocity,min=flickAxis===DIM_X?(__cov_cyIK2vRXoVgOuWid4NBKqw.b['57'][0]++,bounds.minScrollX):(__cov_cyIK2vRXoVgOuWid4NBKqw.b['57'][1]++,bounds.minScrollY),max=flickAxis===DIM_X?(__cov_cyIK2vRXoVgOuWid4NBKqw.b['58'][0]++,bounds.maxScrollX):(__cov_cyIK2vRXoVgOuWid4NBKqw.b['58'][1]++,bounds.maxScrollY),belowMin=newPosition<min,belowMax=newPosition<max,aboveMin=newPosition>min,aboveMax=newPosition>max,belowMinRange=newPosition<min-bounceRange,withinMinRange=(__cov_cyIK2vRXoVgOuWid4NBKqw.b['59'][0]++,belowMin)&&(__cov_cyIK2vRXoVgOuWid4NBKqw.b['59'][1]++,newPosition>min-bounceRange),withinMaxRange=(__cov_cyIK2vRXoVgOuWid4NBKqw.b['60'][0]++,aboveMax)&&(__cov_cyIK2vRXoVgOuWid4NBKqw.b['60'][1]++,newPosition<max+bounceRange),aboveMaxRange=newPosition>max+bounceRange,tooSlow;__cov_cyIK2vRXoVgOuWid4NBKqw.s['164']++;if((__cov_cyIK2vRXoVgOuWid4NBKqw.b['62'][0]++,withinMinRange)||(__cov_cyIK2vRXoVgOuWid4NBKqw.b['62'][1]++,withinMaxRange)){__cov_cyIK2vRXoVgOuWid4NBKqw.b['61'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['165']++;newVelocity*=bounce;}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['61'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['166']++;tooSlow=Math.abs(newVelocity).toFixed(4)<0.015;__cov_cyIK2vRXoVgOuWid4NBKqw.s['167']++;if((__cov_cyIK2vRXoVgOuWid4NBKqw.b['64'][0]++,tooSlow)||(__cov_cyIK2vRXoVgOuWid4NBKqw.b['64'][1]++,belowMinRange)||(__cov_cyIK2vRXoVgOuWid4NBKqw.b['64'][2]++,aboveMaxRange)){__cov_cyIK2vRXoVgOuWid4NBKqw.b['63'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['168']++;if(sv._flickAnim){__cov_cyIK2vRXoVgOuWid4NBKqw.b['65'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['169']++;sv._cancelFlick();}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['65'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['170']++;if((__cov_cyIK2vRXoVgOuWid4NBKqw.b['67'][0]++,aboveMin)&&(__cov_cyIK2vRXoVgOuWid4NBKqw.b['67'][1]++,belowMax)){__cov_cyIK2vRXoVgOuWid4NBKqw.b['66'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['171']++;sv._onTransEnd();}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['66'][1]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['172']++;sv._snapBack();}}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['63'][1]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['173']++;sv._flickAnim=Y.later(frameDuration,sv,'_flickFrame',[newVelocity,flickAxis,newPosition]);__cov_cyIK2vRXoVgOuWid4NBKqw.s['174']++;sv.set(axisAttr,newPosition);}},_cancelFlick:function(){__cov_cyIK2vRXoVgOuWid4NBKqw.f['24']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['175']++;var sv=this;__cov_cyIK2vRXoVgOuWid4NBKqw.s['176']++;if(sv._flickAnim){__cov_cyIK2vRXoVgOuWid4NBKqw.b['68'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['177']++;sv._flickAnim.cancel();__cov_cyIK2vRXoVgOuWid4NBKqw.s['178']++;delete sv._flickAnim;}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['68'][1]++;}},_mousewheel:function(e){__cov_cyIK2vRXoVgOuWid4NBKqw.f['25']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['179']++;var sv=this,scrollY=sv.get(SCROLL_Y),bounds=sv._getBounds(),bb=sv._bb,scrollOffset=10,isForward=e.wheelDelta>0,scrollToY=scrollY-(isForward?(__cov_cyIK2vRXoVgOuWid4NBKqw.b['69'][0]++,1):(__cov_cyIK2vRXoVgOuWid4NBKqw.b['69'][1]++,-1))*scrollOffset;__cov_cyIK2vRXoVgOuWid4NBKqw.s['180']++;scrollToY=_constrain(scrollToY,bounds.minScrollY,bounds.maxScrollY);__cov_cyIK2vRXoVgOuWid4NBKqw.s['181']++;if((__cov_cyIK2vRXoVgOuWid4NBKqw.b['71'][0]++,bb.contains(e.target))&&(__cov_cyIK2vRXoVgOuWid4NBKqw.b['71'][1]++,sv._cAxis[DIM_Y])){__cov_cyIK2vRXoVgOuWid4NBKqw.b['70'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['182']++;sv.lastScrolledAmt=0;__cov_cyIK2vRXoVgOuWid4NBKqw.s['183']++;sv.set(SCROLL_Y,scrollToY);__cov_cyIK2vRXoVgOuWid4NBKqw.s['184']++;if(sv.scrollbars){__cov_cyIK2vRXoVgOuWid4NBKqw.b['72'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['185']++;sv.scrollbars._update();__cov_cyIK2vRXoVgOuWid4NBKqw.s['186']++;sv.scrollbars.flash();}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['72'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['187']++;sv._onTransEnd();__cov_cyIK2vRXoVgOuWid4NBKqw.s['188']++;e.preventDefault();}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['70'][1]++;}},_isOutOfBounds:function(x,y){__cov_cyIK2vRXoVgOuWid4NBKqw.f['26']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['189']++;var sv=this,svAxis=sv._cAxis,svAxisX=svAxis.x,svAxisY=svAxis.y,currentX=(__cov_cyIK2vRXoVgOuWid4NBKqw.b['73'][0]++,x)||(__cov_cyIK2vRXoVgOuWid4NBKqw.b['73'][1]++,sv.get(SCROLL_X)),currentY=(__cov_cyIK2vRXoVgOuWid4NBKqw.b['74'][0]++,y)||(__cov_cyIK2vRXoVgOuWid4NBKqw.b['74'][1]++,sv.get(SCROLL_Y)),bounds=sv._getBounds(),minX=bounds.minScrollX,minY=bounds.minScrollY,maxX=bounds.maxScrollX,maxY=bounds.maxScrollY;__cov_cyIK2vRXoVgOuWid4NBKqw.s['190']++;return(__cov_cyIK2vRXoVgOuWid4NBKqw.b['75'][0]++,svAxisX)&&((__cov_cyIK2vRXoVgOuWid4NBKqw.b['75'][1]++,currentX<minX)||(__cov_cyIK2vRXoVgOuWid4NBKqw.b['75'][2]++,currentX>maxX))||(__cov_cyIK2vRXoVgOuWid4NBKqw.b['75'][3]++,svAxisY)&&((__cov_cyIK2vRXoVgOuWid4NBKqw.b['75'][4]++,currentY<minY)||(__cov_cyIK2vRXoVgOuWid4NBKqw.b['75'][5]++,currentY>maxY));},_snapBack:function(){__cov_cyIK2vRXoVgOuWid4NBKqw.f['27']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['191']++;var sv=this,currentX=sv.get(SCROLL_X),currentY=sv.get(SCROLL_Y),bounds=sv._getBounds(),minX=bounds.minScrollX,minY=bounds.minScrollY,maxX=bounds.maxScrollX,maxY=bounds.maxScrollY,newY=_constrain(currentY,minY,maxY),newX=_constrain(currentX,minX,maxX),duration=sv.get(SNAP_DURATION),easing=sv.get(SNAP_EASING);__cov_cyIK2vRXoVgOuWid4NBKqw.s['192']++;if(newX!==currentX){__cov_cyIK2vRXoVgOuWid4NBKqw.b['76'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['193']++;sv.set(SCROLL_X,newX,{duration:duration,easing:easing});}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['76'][1]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['194']++;if(newY!==currentY){__cov_cyIK2vRXoVgOuWid4NBKqw.b['77'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['195']++;sv.set(SCROLL_Y,newY,{duration:duration,easing:easing});}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['77'][1]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['196']++;sv._onTransEnd();}}},_afterScrollChange:function(e){__cov_cyIK2vRXoVgOuWid4NBKqw.f['28']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['197']++;if(e.src===ScrollView.UI_SRC){__cov_cyIK2vRXoVgOuWid4NBKqw.b['78'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['198']++;return false;}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['78'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['199']++;var sv=this,duration=e.duration,easing=e.easing,val=e.newVal,scrollToArgs=[];__cov_cyIK2vRXoVgOuWid4NBKqw.s['200']++;sv.lastScrolledAmt=sv.lastScrolledAmt+(e.newVal-e.prevVal);__cov_cyIK2vRXoVgOuWid4NBKqw.s['201']++;if(e.attrName===SCROLL_X){__cov_cyIK2vRXoVgOuWid4NBKqw.b['79'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['202']++;scrollToArgs.push(val);__cov_cyIK2vRXoVgOuWid4NBKqw.s['203']++;scrollToArgs.push(sv.get(SCROLL_Y));}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['79'][1]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['204']++;scrollToArgs.push(sv.get(SCROLL_X));__cov_cyIK2vRXoVgOuWid4NBKqw.s['205']++;scrollToArgs.push(val);}__cov_cyIK2vRXoVgOuWid4NBKqw.s['206']++;scrollToArgs.push(duration);__cov_cyIK2vRXoVgOuWid4NBKqw.s['207']++;scrollToArgs.push(easing);__cov_cyIK2vRXoVgOuWid4NBKqw.s['208']++;sv.scrollTo.apply(sv,scrollToArgs);},_afterFlickChange:function(e){__cov_cyIK2vRXoVgOuWid4NBKqw.f['29']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['209']++;this._bindFlick(e.newVal);},_afterDisabledChange:function(e){__cov_cyIK2vRXoVgOuWid4NBKqw.f['30']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['210']++;this._cDisabled=e.newVal;},_afterAxisChange:function(e){__cov_cyIK2vRXoVgOuWid4NBKqw.f['31']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['211']++;this._cAxis=e.newVal;},_afterDragChange:function(e){__cov_cyIK2vRXoVgOuWid4NBKqw.f['32']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['212']++;this._bindDrag(e.newVal);},_afterDimChange:function(){__cov_cyIK2vRXoVgOuWid4NBKqw.f['33']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['213']++;this._uiDimensionsChange();},_afterScrollEnd:function(){__cov_cyIK2vRXoVgOuWid4NBKqw.f['34']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['214']++;var sv=this;__cov_cyIK2vRXoVgOuWid4NBKqw.s['215']++;if(sv._flickAnim){__cov_cyIK2vRXoVgOuWid4NBKqw.b['80'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['216']++;sv._cancelFlick();}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['80'][1]++;}},_axisSetter:function(val){__cov_cyIK2vRXoVgOuWid4NBKqw.f['35']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['217']++;if(Y.Lang.isString(val)){__cov_cyIK2vRXoVgOuWid4NBKqw.b['81'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['218']++;return{x:val.match(/x/i)?(__cov_cyIK2vRXoVgOuWid4NBKqw.b['82'][0]++,true):(__cov_cyIK2vRXoVgOuWid4NBKqw.b['82'][1]++,false),y:val.match(/y/i)?(__cov_cyIK2vRXoVgOuWid4NBKqw.b['83'][0]++,true):(__cov_cyIK2vRXoVgOuWid4NBKqw.b['83'][1]++,false)};}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['81'][1]++;}},_setScroll:function(val){__cov_cyIK2vRXoVgOuWid4NBKqw.f['36']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['219']++;if(this._cDisabled){__cov_cyIK2vRXoVgOuWid4NBKqw.b['84'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['220']++;val=Y.Attribute.INVALID_VALUE;}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['84'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['221']++;return val;},_setScrollX:function(val){__cov_cyIK2vRXoVgOuWid4NBKqw.f['37']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['222']++;return this._setScroll(val,DIM_X);},_setScrollY:function(val){__cov_cyIK2vRXoVgOuWid4NBKqw.f['38']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['223']++;return this._setScroll(val,DIM_Y);}},{NAME:'scrollview',ATTRS:{axis:{setter:'_axisSetter',writeOnce:'initOnly'},scrollX:{value:0,setter:'_setScrollX'},scrollY:{value:0,setter:'_setScrollY'},deceleration:{value:0.93},bounce:{value:0.1},flick:{value:{minDistance:10,minVelocity:0.3}},drag:{value:true},snapDuration:{value:400},snapEasing:{value:'ease-out'},easing:{value:'cubic-bezier(0, 0.1, 0, 1.0)'},frameDuration:{value:15},bounceRange:{value:150}},CLASS_NAMES:CLASS_NAMES,UI_SRC:UI,_TRANSITION:{DURATION:vendorPrefix?(__cov_cyIK2vRXoVgOuWid4NBKqw.b['85'][0]++,vendorPrefix+'TransitionDuration'):(__cov_cyIK2vRXoVgOuWid4NBKqw.b['85'][1]++,'transitionDuration'),PROPERTY:vendorPrefix?(__cov_cyIK2vRXoVgOuWid4NBKqw.b['86'][0]++,vendorPrefix+'TransitionProperty'):(__cov_cyIK2vRXoVgOuWid4NBKqw.b['86'][1]++,'transitionProperty')},BOUNCE_RANGE:false,FRAME_STEP:false,EASING:false,SNAP_EASING:false,SNAP_DURATION:false});},'3.16.0',{'requires':['widget','event-gestures','event-mousewheel','transition'],'skinnable':true});
stories/Calendar.stories.js
jquense/react-big-calendar
import React from 'react' import { action } from '@storybook/addon-actions' import demoEvents from './resources/events' import { Calendar } from '../src' import { events, Calendar as BaseCalendar, Views } from './helpers' import createEvents from './helpers/createEvents' import customComponents from './resources/customComponents' export default { title: 'Additional Examples', component: Calendar, } const Template = (args) => ( <div className="height600"> <BaseCalendar {...args} /> </div> ) export const ComplexDayViewLayout = Template.bind({}) ComplexDayViewLayout.storyName = 'complex day view layout' ComplexDayViewLayout.args = { defaultView: Views.DAY, defaultDate: new Date(), events: createEvents(1), step: 30, } const TimeGutter = () => <p>Custom gutter text</p> export const CustomTimeGutterHeader = Template.bind({}) CustomTimeGutterHeader.storyName = 'custom TimeGutter header' CustomTimeGutterHeader.args = { popup: true, events: demoEvents, onSelectEvent: action('event selected'), defaultDate: new Date(2015, 3, 1), defaultView: Views.WEEK, views: [Views.WEEK, Views.DAY], components: { timeGutterHeader: TimeGutter, }, } export const CustomDateCellWrapper = Template.bind({}) CustomDateCellWrapper.storyName = 'add custom dateCellWrapper' CustomDateCellWrapper.args = { defaultView: Views.MONTH, events, components: { dateCellWrapper: customComponents.dateCellWrapper, }, } export const CustomTimeSlotWrapper = Template.bind({}) CustomTimeSlotWrapper.storyName = 'add custom timeSlotWrapper' CustomTimeSlotWrapper.args = { defaultView: Views.DAY, events, components: { timeSlotWrapper: customComponents.timeSlotWrapper, }, } export const CustomEventWrapper = Template.bind({}) CustomEventWrapper.storyName = 'add custom eventWrapper' CustomEventWrapper.args = { defaultView: Views.DAY, events, components: { eventWrapper: customComponents.eventWrapper, }, } export const CustomNoAgendaEventsLabel = Template.bind({}) CustomNoAgendaEventsLabel.storyName = 'add custom no agenda events label' CustomNoAgendaEventsLabel.args = { defaultView: Views.AGENDA, events, messages: { noEventsInRange: 'There are no special events in this range [test message]', }, }
packages/react-dom/src/__tests__/ReactEmptyComponent-test.js
rricard/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. * * @emails react-core */ 'use strict'; let React; let ReactDOM; let ReactTestUtils; let TogglingComponent; let log; describe('ReactEmptyComponent', () => { beforeEach(() => { jest.resetModules(); React = require('react'); ReactDOM = require('react-dom'); ReactTestUtils = require('react-dom/test-utils'); log = jest.fn(); TogglingComponent = class extends React.Component { state = {component: this.props.firstComponent}; componentDidMount() { log(ReactDOM.findDOMNode(this)); this.setState({component: this.props.secondComponent}); } componentDidUpdate() { log(ReactDOM.findDOMNode(this)); } render() { const Component = this.state.component; return Component ? <Component /> : null; } }; }); it('should not produce child DOM nodes for null and false', () => { class Component1 extends React.Component { render() { return null; } } class Component2 extends React.Component { render() { return false; } } const container1 = document.createElement('div'); ReactDOM.render(<Component1 />, container1); expect(container1.children.length).toBe(0); const container2 = document.createElement('div'); ReactDOM.render(<Component2 />, container2); expect(container2.children.length).toBe(0); }); it('should still throw when rendering to undefined', () => { class Component extends React.Component { render() {} } expect(function() { ReactTestUtils.renderIntoDocument(<Component />); }).toThrowError( 'Component(...): Nothing was returned from render. This usually means a return statement is missing. ' + 'Or, to render nothing, return null.', ); }); it('should be able to switch between rendering null and a normal tag', () => { const instance1 = ( <TogglingComponent firstComponent={null} secondComponent={'div'} /> ); const instance2 = ( <TogglingComponent firstComponent={'div'} secondComponent={null} /> ); ReactTestUtils.renderIntoDocument(instance1); ReactTestUtils.renderIntoDocument(instance2); expect(log).toHaveBeenCalledTimes(4); expect(log).toHaveBeenNthCalledWith(1, null); expect(log).toHaveBeenNthCalledWith( 2, expect.objectContaining({tagName: 'DIV'}), ); expect(log).toHaveBeenNthCalledWith( 3, expect.objectContaining({tagName: 'DIV'}), ); expect(log).toHaveBeenNthCalledWith(4, null); }); it('should be able to switch in a list of children', () => { const instance1 = ( <TogglingComponent firstComponent={null} secondComponent={'div'} /> ); ReactTestUtils.renderIntoDocument( <div> {instance1} {instance1} {instance1} </div>, ); expect(log).toHaveBeenCalledTimes(6); expect(log).toHaveBeenNthCalledWith(1, null); expect(log).toHaveBeenNthCalledWith(2, null); expect(log).toHaveBeenNthCalledWith(3, null); expect(log).toHaveBeenNthCalledWith( 4, expect.objectContaining({tagName: 'DIV'}), ); expect(log).toHaveBeenNthCalledWith( 5, expect.objectContaining({tagName: 'DIV'}), ); expect(log).toHaveBeenNthCalledWith( 6, expect.objectContaining({tagName: 'DIV'}), ); }); it('should distinguish between a script placeholder and an actual script tag', () => { const instance1 = ( <TogglingComponent firstComponent={null} secondComponent={'script'} /> ); const instance2 = ( <TogglingComponent firstComponent={'script'} secondComponent={null} /> ); expect(function() { ReactTestUtils.renderIntoDocument(instance1); }).not.toThrow(); expect(function() { ReactTestUtils.renderIntoDocument(instance2); }).not.toThrow(); expect(log).toHaveBeenCalledTimes(4); expect(log).toHaveBeenNthCalledWith(1, null); expect(log).toHaveBeenNthCalledWith( 2, expect.objectContaining({tagName: 'SCRIPT'}), ); expect(log).toHaveBeenNthCalledWith( 3, expect.objectContaining({tagName: 'SCRIPT'}), ); expect(log).toHaveBeenNthCalledWith(4, null); }); it( 'should have findDOMNode return null when multiple layers of composite ' + 'components render to the same null placeholder', () => { class GrandChild extends React.Component { render() { return null; } } class Child extends React.Component { render() { return <GrandChild />; } } const instance1 = ( <TogglingComponent firstComponent={'div'} secondComponent={Child} /> ); const instance2 = ( <TogglingComponent firstComponent={Child} secondComponent={'div'} /> ); expect(function() { ReactTestUtils.renderIntoDocument(instance1); }).not.toThrow(); expect(function() { ReactTestUtils.renderIntoDocument(instance2); }).not.toThrow(); expect(log).toHaveBeenCalledTimes(4); expect(log).toHaveBeenNthCalledWith( 1, expect.objectContaining({tagName: 'DIV'}), ); expect(log).toHaveBeenNthCalledWith(2, null); expect(log).toHaveBeenNthCalledWith(3, null); expect(log).toHaveBeenNthCalledWith( 4, expect.objectContaining({tagName: 'DIV'}), ); }, ); it('works when switching components', () => { let assertions = 0; class Inner extends React.Component { render() { return <span />; } componentDidMount() { // Make sure the DOM node resolves properly even if we're replacing a // `null` component expect(ReactDOM.findDOMNode(this)).not.toBe(null); assertions++; } componentWillUnmount() { // Even though we're getting replaced by `null`, we haven't been // replaced yet! expect(ReactDOM.findDOMNode(this)).not.toBe(null); assertions++; } } class Wrapper extends React.Component { render() { return this.props.showInner ? <Inner /> : null; } } const el = document.createElement('div'); let component; // Render the <Inner /> component... component = ReactDOM.render(<Wrapper showInner={true} />, el); expect(ReactDOM.findDOMNode(component)).not.toBe(null); // Switch to null... component = ReactDOM.render(<Wrapper showInner={false} />, el); expect(ReactDOM.findDOMNode(component)).toBe(null); // ...then switch back. component = ReactDOM.render(<Wrapper showInner={true} />, el); expect(ReactDOM.findDOMNode(component)).not.toBe(null); expect(assertions).toBe(3); }); it('can render null at the top level', () => { const div = document.createElement('div'); ReactDOM.render(null, div); expect(div.innerHTML).toBe(''); }); it('does not break when updating during mount', () => { class Child extends React.Component { componentDidMount() { if (this.props.onMount) { this.props.onMount(); } } render() { if (!this.props.visible) { return null; } return <div>hello world</div>; } } class Parent extends React.Component { update = () => { this.forceUpdate(); }; render() { return ( <div> <Child key="1" visible={false} /> <Child key="0" visible={true} onMount={this.update} /> <Child key="2" visible={false} /> </div> ); } } expect(function() { ReactTestUtils.renderIntoDocument(<Parent />); }).not.toThrow(); }); it('preserves the dom node during updates', () => { class Empty extends React.Component { render() { return null; } } const container = document.createElement('div'); ReactDOM.render(<Empty />, container); const noscript1 = container.firstChild; expect(noscript1).toBe(null); // This update shouldn't create a DOM node ReactDOM.render(<Empty />, container); const noscript2 = container.firstChild; expect(noscript2).toBe(null); }); });
src/client/components/search/GridEntityActions.js
gearz-lab/hypersonic
import React from 'react'; import {ButtonGroup, Button} from 'react-bootstrap'; import _ from 'underscore'; export default React.createClass({ propTypes: { selection: React.PropTypes.object, rows: React.PropTypes.array, handleSelectionChange: React.PropTypes.func }, handleAction: function (a) { let {handleAction} = this.props; return () => handleAction(a, this.props.selection); }, render: function () { let { actions, selection, } = this.props; let generalActions = []; let entitySpecificActions = []; _.each(actions, action => { if (action.entitySpecific == undefined || action.entitySpecific == true) entitySpecificActions.push(action); else generalActions.push(action); }); let generalActionsButtons = null; if (generalActions.length) { generalActionsButtons = <ButtonGroup className="button-bar"> { generalActions.map(a => { let icon = a.icon ? <i className={`fa fa-${a.icon}`}></i> : null; return <Button key={`action-${a.name}`} onClick={this.handleAction(a)}> {icon} {a.displayName || a.name} </Button> }) } </ButtonGroup>; } let entitySpecificActionsButtons = null; if (entitySpecificActions.length && Object.keys(selection).length) { entitySpecificActionsButtons = <ButtonGroup className="button-bar"> { entitySpecificActions.map(a => { let allowMultiple = a.allowMultiple == undefined || a.allowMultiple == null || a.allowMultiple == true; if (Object.keys(selection).length > 1 && !allowMultiple) return null; let icon = a.icon ? <i className={`fa fa-${a.icon}`}></i> : null; return <Button key={`action-${a.name}`} onClick={this.handleAction(a)}> {icon} {a.displayName || a.name} </Button> }) } </ButtonGroup> } return <span> { generalActionsButtons } { entitySpecificActionsButtons } </span>; } })
src/routes/dashboardPages/processRunning/index.js
bhavik3jain/LibertyMutual320Project
import React from 'react'; import RunningProcess from './processRunning'; export default { path: '/processRunning', action() { return <RunningProcess />; }, };
templates/rubix/demo/src/common/sidebar.js
jeffthemaximum/Teachers-Dont-Pay-Jeff
import React from 'react'; import { Sidebar, SidebarNav, SidebarNavItem, SidebarControls, SidebarControlBtn, LoremIpsum, Grid, Row, Col, FormControl, Label, Progress, Icon, SidebarDivider } from '@sketchpixy/rubix'; import { Link, withRouter } from 'react-router'; import ChatComponent from './chat'; import StatisticsComponent from './statistics'; import TimelineComponent from './timeline'; import NotificationsComponent from './notifications'; @withRouter class ApplicationSidebar extends React.Component { handleChange(e) { this._nav.search(e.target.value); } getPath(path) { var dir = this.props.location.pathname.search('rtl') !== -1 ? 'rtl' : 'ltr'; path = `/${dir}/${path}`; return path; } render() { return ( <div> <Grid> <Row> <Col xs={12}> <FormControl type='text' placeholder='Search...' onChange={::this.handleChange} className='sidebar-search' style={{border: 'none', background: 'none', margin: '10px 0 0 0', borderBottom: '1px solid #666', color: 'white'}} /> <div className='sidebar-nav-container'> <SidebarNav style={{marginBottom: 0}} ref={(c) => this._nav = c}> { /** Pages Section */ } <div className='sidebar-header'>PAGES</div> <SidebarNavItem glyph='icon-fontello-gauge' name='Dashboard' href={::this.getPath('dashboard')} /> <SidebarNavItem glyph='icon-feather-mail' name={<span>Mailbox <Label className='bg-darkgreen45 fg-white'>3</Label></span>}> <SidebarNav> <SidebarNavItem glyph='icon-feather-inbox' name='Inbox' href={::this.getPath('mailbox/inbox')} /> <SidebarNavItem glyph='icon-outlined-mail-open' name='Mail' href={::this.getPath('mailbox/mail')} /> <SidebarNavItem glyph='icon-dripicons-message' name='Compose' href={::this.getPath('mailbox/compose')} /> </SidebarNav> </SidebarNavItem> <SidebarNavItem glyph='icon-pixelvicon-photo-gallery' name='Gallery' href={::this.getPath('gallery')} /> <SidebarNavItem glyph='icon-feather-share' name='Social' href={::this.getPath('social')} /> <SidebarNavItem glyph='icon-stroke-gap-icons-Blog' name={<span>Blog <Label className='bg-darkcyan fg-white'>2</Label></span>}> <SidebarNav> <SidebarNavItem glyph='icon-feather-layout' name='Posts' href={::this.getPath('blog/posts')} /> <SidebarNavItem glyph='icon-feather-paper' name='Single Post' href={::this.getPath('blog/post')} /> </SidebarNav> </SidebarNavItem> <SidebarDivider /> { /** Components Section */ } <div className='sidebar-header'>COMPONENTS</div> <SidebarNavItem glyph='icon-simple-line-icons-layers float-right-rtl' name='Panels' href={::this.getPath('panels')} /> <SidebarNavItem glyph='icon-ikons-bar-chart-2 float-right-rtl' name={<span>Charts <Label className='bg-brown50 fg-white'>4</Label></span>}> <SidebarNav> <SidebarNavItem glyph='icon-fontello-chart-area' name='Rubix Charts'> <SidebarNav> <SidebarNavItem name='Line Series' href={::this.getPath('charts/rubix/line')} /> <SidebarNavItem name='Area Series' href={::this.getPath('charts/rubix/area')} /> <SidebarNavItem name='Bar + Column Series' href={::this.getPath('charts/rubix/barcol')} /> <SidebarNavItem name='Mixed Series' href={::this.getPath('charts/rubix/mixed')} /> <SidebarNavItem name='Pie + Donut Series' href={::this.getPath('charts/rubix/piedonut')} /> </SidebarNav> </SidebarNavItem> <SidebarNavItem glyph='icon-simple-line-icons-graph' name='Chart.JS' href={::this.getPath('charts/chartjs')} /> <SidebarNavItem glyph='icon-dripicons-graph-line' name='C3.JS' href={::this.getPath('charts/c3js')} /> <SidebarNavItem glyph='icon-feather-pie-graph' name='Morris.JS' href={::this.getPath('charts/morrisjs')} /> </SidebarNav> </SidebarNavItem> <SidebarNavItem href={::this.getPath('timeline')} glyph='icon-ikons-time' name='Static Timeline' /> <SidebarNavItem href={::this.getPath('interactive-timeline')} glyph='icon-fontello-back-in-time' name='Interactive Timeline' /> <SidebarNavItem href={::this.getPath('codemirror')} glyph='icon-dripicons-code' name='Codemirror' /> <SidebarNavItem href={::this.getPath('maps')} glyph='icon-ikons-pin-2' name='Maps' /> <SidebarNavItem href={::this.getPath('editor')} glyph='icon-simple-line-icons-note' name='Editor' /> <SidebarNavItem glyph='icon-feather-toggle' name={<span>UI Elements <Label className='bg-deepred fg-white'>7</Label></span>}> <SidebarNav> <SidebarNavItem href={::this.getPath('ui-elements/buttons')} glyph='icon-mfizz-oracle' name='Buttons' /> <SidebarNavItem href={::this.getPath('ui-elements/dropdowns')} glyph='icon-outlined-arrow-down' name='Dropdowns' /> <SidebarNavItem href={::this.getPath('ui-elements/tabs-and-navs')} glyph='icon-nargela-navigation' name='Tabs &amp; Navs' /> <SidebarNavItem href={::this.getPath('ui-elements/sliders')} glyph='icon-outlined-three-stripes-horiz' name='Sliders' /> <SidebarNavItem href={::this.getPath('ui-elements/knobs')} glyph='icon-ikons-chart-3-8' name='Knobs' /> <SidebarNavItem href={::this.getPath('ui-elements/modals')} glyph='icon-pixelvicon-browser-1' name='Modals' /> <SidebarNavItem href={::this.getPath('ui-elements/messenger')} glyph='icon-dripicons-message' name='Messenger' /> </SidebarNav> </SidebarNavItem> <SidebarNavItem glyph='icon-stroke-gap-icons-Files float-right-rtl' name={<span>Forms <Label className='bg-danger fg-white'>3</Label></span>}> <SidebarNav> <SidebarNavItem glyph='icon-mfizz-fire-alt' href={::this.getPath('forms/controls')} name='Controls' /> <SidebarNavItem glyph='icon-stroke-gap-icons-Edit' href={::this.getPath('forms/x-editable')} name='X-Editable' /> <SidebarNavItem glyph='icon-simple-line-icons-magic-wand' href={::this.getPath('forms/wizard')} name='Wizard' /> </SidebarNav> </SidebarNavItem> <SidebarNavItem glyph='icon-fontello-table' name={<span>Tables <Label className='bg-blue fg-white'>3</Label></span>}> <SidebarNav> <SidebarNavItem href={::this.getPath('tables/bootstrap-tables')} glyph='icon-fontello-th-thumb' name='Bootstrap Tables' /> <SidebarNavItem href={::this.getPath('tables/datatables')} glyph='icon-fontello-th-2' name='Datatables' /> <SidebarNavItem href={::this.getPath('tables/tablesaw')} glyph='icon-fontello-view-mode' name='Tablesaw' /> </SidebarNav> </SidebarNavItem> <SidebarNavItem href={::this.getPath('grid')} glyph='icon-ikons-grid-1 float-right-rtl' name='Grid' /> <SidebarNavItem href={::this.getPath('calendar')} glyph='icon-fontello-calendar-alt' name='Calendar' /> <SidebarNavItem glyph='icon-fontello-folder-open-empty' name={<span>File Utilities <Label className='bg-orange fg-darkbrown'>2</Label></span>}> <SidebarNav> <SidebarNavItem href={::this.getPath('file-utilities/dropzone')} glyph='icon-stroke-gap-icons-Download' name='Dropzone' /> <SidebarNavItem href={::this.getPath('file-utilities/crop')} glyph='icon-ikons-crop' name='Image Cropping' /> </SidebarNav> </SidebarNavItem> <SidebarNavItem href={::this.getPath('fonts')} glyph='icon-fontello-fontsize' name='Fonts' /> <SidebarDivider /> { /** Extras Section */ } <div className='sidebar-header'>EXTRAS</div> <SidebarNavItem glyph='icon-ikons-login' name='Login' href={::this.getPath('login')} /> <SidebarNavItem glyph='icon-simple-line-icons-users' name='Signup' href={::this.getPath('signup')} /> <SidebarNavItem glyph='icon-ikons-lock' name='Lock Page' href={::this.getPath('lock')} /> <SidebarNavItem glyph='icon-dripicons-document' name='Invoice' href={::this.getPath('invoice')} /> <SidebarNavItem glyph='icon-feather-tag icon-rotate-135' name='Pricing Tables' href={::this.getPath('pricing')} /> <SidebarDivider /> { /** Documentation Section */ } <div className='sidebar-header'>DOCUMENTATION</div> <li className='sidebar-nav-item' style={{display: 'block', height: 45}}> <a href='http://rubix-docs.sketchpixy.com' style={{height: 45}}> <Icon glyph='icon-fontello-install' /> <span className='name'>Documentation</span> </a> </li> </SidebarNav> <br /> <br /> <br /> </div> </Col> </Row> </Grid> </div> ); } } class DummySidebar extends React.Component { render() { return ( <Grid> <Row> <Col xs={12}> <div className='sidebar-header'>DUMMY SIDEBAR</div> <LoremIpsum query='1p' /> </Col> </Row> </Grid> ); } } @withRouter export default class SidebarContainer extends React.Component { getPath(path) { var dir = this.props.location.pathname.search('rtl') !== -1 ? 'rtl' : 'ltr'; path = `/${dir}/${path}`; return path; } render() { return ( <div id='sidebar'> <div id='avatar'> <Grid> <Row className='fg-white'> <Col xs={4} collapseRight> <img src='/imgs/app/avatars/avatar0.png' width='40' height='40' /> </Col> <Col xs={8} collapseLeft id='avatar-col'> <div style={{top: 23, fontSize: 16, lineHeight: 1, position: 'relative'}}>Anna Sanchez</div> <div> <Progress id='demo-progress' value={30} color='#ffffff'/> <Link to={::this.getPath('lock')}> <Icon id='demo-icon' bundle='fontello' glyph='lock-5' /> </Link> </div> </Col> </Row> </Grid> </div> <SidebarControls> <SidebarControlBtn bundle='fontello' glyph='docs' sidebar={0} /> <SidebarControlBtn bundle='fontello' glyph='chat-1' sidebar={1} /> <SidebarControlBtn bundle='fontello' glyph='chart-pie-2' sidebar={2} /> <SidebarControlBtn bundle='fontello' glyph='th-list-2' sidebar={3} /> <SidebarControlBtn bundle='fontello' glyph='bell-5' sidebar={4} /> </SidebarControls> <div id='sidebar-container'> <Sidebar sidebar={0}> <ApplicationSidebar /> </Sidebar> <Sidebar sidebar={1}> <ChatComponent /> </Sidebar> <Sidebar sidebar={2}> <StatisticsComponent /> </Sidebar> <Sidebar sidebar={3}> <TimelineComponent /> </Sidebar> <Sidebar sidebar={4}> <NotificationsComponent /> </Sidebar> </div> </div> ); } }
ajax/libs/angular.js/1.0.0rc6/angular-scenario.js
nolsherry/cdnjs
/*! * jQuery JavaScript Library v1.7.2 * http://jquery.com/ * * Copyright 2011, John Resig * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * Includes Sizzle.js * http://sizzlejs.com/ * Copyright 2011, The Dojo Foundation * Released under the MIT, BSD, and GPL Licenses. * * Date: Wed Mar 21 12:46:34 2012 -0700 */ (function( window, undefined ) { 'use strict'; // 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.2", // The default length of a jQuery object is 0 length: 0, // The number of elements contained in the matched element set size: function() { return this.length; }, toArray: function() { return slice.call( this, 0 ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num == null ? // Return a 'clean' array this.toArray() : // Return just the object ( num < 0 ? this[ 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"; }, isWindow: function( obj ) { return obj != null && obj == obj.window; }, 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 ) { if ( typeof data !== "string" || !data ) { return null; } 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, fn, key, value, chainable, emptyGet, pass ) { var exec, bulk = key == null, i = 0, length = elems.length; // Sets many values if ( key && typeof key === "object" ) { for ( i in key ) { jQuery.access( elems, fn, i, key[i], 1, emptyGet, value ); } chainable = 1; // Sets one value } else if ( value !== undefined ) { // Optionally, function values get executed if exec is true exec = pass === undefined && jQuery.isFunction( value ); if ( bulk ) { // Bulk operations only iterate when executing function values if ( exec ) { exec = fn; fn = function( elem, key, value ) { return exec.call( jQuery( elem ), value ); }; // Otherwise they run against the entire set } else { fn.call( elems, value ); fn = null; } } if ( fn ) { for (; i < length; i++ ) { fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass ); } } chainable = 1; } return chainable ? elems : // Gets bulk ? fn.call( elems ) : length ? fn( elems[0], key ) : emptyGet; }, 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 was already fired fired, // Flag to know if list is currently firing firing, // First callback to fire (used internally by add and fireWith) firingStart, // End of the loop when firing firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, // 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 ]; fired = true; 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 !!fired; } }; 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, 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, pixelMargin: true }; // jQuery.boxModel DEPRECATED in 1.3, use jQuery.support.boxModel instead jQuery.boxModel = support.boxModel = (document.compatMode === "CSS1Compat"); // 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"); // #11217 - WebKit loses check when the name is after the checked attribute input.setAttribute( "name", "t" ); 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 ); // 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 = div = input = null; // Run tests that need a body at doc ready jQuery(function() { var container, outer, inner, table, td, offsetSupport, marginDiv, conMarginTop, style, html, positionTopLeftWidthHeight, paddingMarginBorderVisibility, paddingMarginBorder, body = document.getElementsByTagName("body")[0]; if ( !body ) { // Return for frameset docs that don't have a body return; } conMarginTop = 1; paddingMarginBorder = "padding:0;margin:0;border:"; positionTopLeftWidthHeight = "position:absolute;top:0;left:0;width:1px;height:1px;"; paddingMarginBorderVisibility = paddingMarginBorder + "0;visibility:hidden;"; style = "style='" + positionTopLeftWidthHeight + paddingMarginBorder + "5px solid #000;"; html = "<div " + style + "display:block;'><div style='" + paddingMarginBorder + "0;display:block;overflow:hidden;'></div></div>" + "<table " + style + "' cellpadding='0' cellspacing='0'>" + "<tr><td></td></tr></table>"; container = document.createElement("div"); container.style.cssText = paddingMarginBorderVisibility + "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='" + paddingMarginBorder + "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 ); // 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 ) { div.innerHTML = ""; 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; } 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.innerHTML = ""; div.style.width = div.style.padding = "1px"; div.style.border = 0; div.style.overflow = "hidden"; div.style.display = "inline"; div.style.zoom = 1; support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 ); // Check if elements with layout shrink-wrap their children // (IE 6 does this) div.style.display = "block"; div.style.overflow = "visible"; div.innerHTML = "<div style='width:5px;'></div>"; support.shrinkWrapBlocks = ( div.offsetWidth !== 3 ); } div.style.cssText = positionTopLeftWidthHeight + paddingMarginBorderVisibility; 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 ); if ( window.getComputedStyle ) { div.style.marginTop = "1%"; support.pixelMargin = ( window.getComputedStyle( div, null ) || { marginTop: 0 } ).marginTop !== "1%"; } if ( typeof container.style.zoom !== "undefined" ) { container.style.zoom = 1; } body.removeChild( container ); marginDiv = 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, part, attr, name, l, elem = this[0], i = 0, data = null; // Gets all values if ( key === undefined ) { if ( this.length ) { data = jQuery.data( elem ); if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) { attr = elem.attributes; for ( l = attr.length; i < l; i++ ) { name = attr[i].name; if ( name.indexOf( "data-" ) === 0 ) { name = jQuery.camelCase( name.substring(5) ); dataAttr( elem, name, data[ name ] ); } } jQuery._data( elem, "parsedAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each(function() { jQuery.data( this, key ); }); } parts = key.split( ".", 2 ); parts[1] = parts[1] ? "." + parts[1] : ""; part = parts[1] + "!"; return jQuery.access( this, function( value ) { if ( value === undefined ) { data = this.triggerHandler( "getData" + part, [ parts[0] ] ); // Try to fetch any internally stored data first if ( data === undefined && elem ) { data = jQuery.data( elem, key ); data = dataAttr( elem, key, data ); } return data === undefined && parts[1] ? this.data( parts[0] ) : data; } parts[1] = value; this.each(function() { var self = jQuery( this ); self.triggerHandler( "setData" + part, parts ); jQuery.data( this, key, value ); self.triggerHandler( "changeData" + part, parts ); }); }, null, value, arguments.length > 1, null, false ); }, 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 ) ? +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 ) { var setter = 2; if ( typeof type !== "string" ) { data = type; type = "fx"; setter--; } if ( arguments.length < setter ) { return jQuery.queue( this[0], type ); } return data === undefined ? this : this.each(function() { var queue = jQuery.queue( this, type, data ); 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( object ); } }); 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, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each(function() { jQuery.removeAttr( this, name ); }); }, prop: function( name, value ) { return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 ); }, removeProp: function( name ) { name = jQuery.propFix[ name ] || name; return this.each(function() { // try/catch handles cases where IE balks (such as removing a property on window) try { this[ name ] = undefined; delete this[ name ]; } catch( e ) {} }); }, addClass: function( value ) { var 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.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { return ret; } ret = elem.value; return typeof ret === "string" ? // handle most common string cases ret.replace(rreturn, "") : // handle cases where value is null/undef or number ret == null ? "" : ret; } return; } isFunction = jQuery.isFunction( value ); return this.each(function( i ) { var 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.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; // If set returns undefined, fall back to normal setting if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } }); } }); jQuery.extend({ valHooks: { option: { get: function( elem ) { // attributes.value is undefined in Blackberry 4.7 but // uses .value. See #6932 var val = elem.attributes.value; return !val || val.specified ? elem.value : elem.text; } }, select: { get: function( elem ) { var value, 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, isBool, 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; isBool = rboolean.test( name ); // See #9699 for explanation of this approach (setting first, then removal) // Do not do this for boolean attributes (see #10870) if ( !isBool ) { jQuery.attr( elem, name, "" ); } elem.removeAttribute( getSetAttribute ? name : propName ); // Set corresponding property to false for boolean attributes if ( isBool && 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, coords: 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 = /(?:^|\s)hover(\.\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; selector = handleObjIn.selector; } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first 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: selector && 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, special = jQuery.event.special[ event.type ] || {}, 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; // Call the preDispatch hook for the mapped type, and let it bail if desired if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { return; } // Determine handlers that should run if there are delegated events // Avoid non-left-click bubbling in Firefox (#3861) if ( delegateCount && !(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 ) { // Don't process events on disabled elements (#6911, #8165) if ( cur.disabled !== true ) { 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(); } } } } } // Call the postDispatch hook for the mapped type if ( special.postDispatch ) { special.postDispatch.call( this, event ); } 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 ) { event._submit_bubble = true; }); form._submit_attached = true; } }); // return undefined since we don't need an event listener }, postDispatch: function( event ) { // If form was submitted by the user, bubble the event up the tree if ( event._submit_bubble ) { delete event._submit_bubble; if ( this.parentNode && !event.isTrigger ) { jQuery.event.simulate( "submit", this.parentNode, event, true ); } } }, teardown: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Remove delegated handlers; cleanData eventually reaps submit handlers attached above jQuery.event.remove( this, "._submit" ); } }; } // IE change delegation and checkbox/radio fix if ( !jQuery.support.changeBubbles ) { jQuery.event.special.change = { setup: function() { if ( rformElems.test( this.nodeName ) ) { // IE doesn't fire change on a check/radio until blur; trigger it on click // after a propertychange. Eat the blur-change in special.change.handle. // This still fires onchange a second time for check/radio after blur. if ( this.type === "checkbox" || this.type === "radio" ) { jQuery.event.add( this, "propertychange._change", function( event ) { if ( event.originalEvent.propertyName === "checked" ) { this._just_changed = true; } }); jQuery.event.add( this, "click._change", function( event ) { if ( this._just_changed && !event.isTrigger ) { this._just_changed = false; 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" ) { // && selector != null // ( types-Object, data ) data = data || selector; selector = undefined; } for ( type in types ) { this.on( type, selector, data, types[ type ], one ); } return this; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return this; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since event contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return this.each( function() { jQuery.event.add( this, types, fn, data, selector ); }); }, one: function( types, selector, data, fn ) { return this.on( types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event var handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( 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 || nodeType === 11 ) { // 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; /* falls through */ 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) ); } // Expose origPOS // "global" as in regardless of relation to brackets/parens Expr.match.globalPOS = origPOS; 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.globalPOS, // 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|bdi|canvas|data|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 + ")[\\s/>]", "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( value ) { return jQuery.access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) ); }, null, value, arguments.length ); }, wrapAll: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapAll( html.call(this, i) ); }); } if ( this[0] ) { // The elements to wrap the target around var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true); if ( this[0].parentNode ) { wrap.insertBefore( this[0] ); } wrap.map(function() { var elem = this; while ( elem.firstChild && elem.firstChild.nodeType === 1 ) { elem = elem.firstChild; } return elem; }).append( this ); } return this; }, wrapInner: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapInner( html.call(this, i) ); }); } return this.each(function() { var self = jQuery( this ), contents = self.contents(); if ( contents.length ) { contents.wrapAll( html ); } else { self.append( html ); } }); }, wrap: function( html ) { var isFunction = jQuery.isFunction( html ); return this.each(function(i) { jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html ); }); }, unwrap: function() { return this.parent().each(function() { if ( !jQuery.nodeName( this, "body" ) ) { jQuery( this ).replaceWith( this.childNodes ); } }).end(); }, append: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 ) { this.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 ) { return jQuery.access( this, function( value ) { var elem = this[0] || {}, i = 0, l = this.length; if ( value === undefined ) { return elem.nodeType === 1 ? elem.innerHTML.replace( rinlinejQuery, "" ) : null; } 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 (; i < l; i++ ) { // Remove element nodes and prevent memory leaks elem = this[i] || {}; if ( elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName( "*" ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch(e) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function( value ) { 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, function( i, elem ) { if ( elem.src ) { jQuery.ajax({ type: "GET", global: false, 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 ); } }); } } 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 ] ); } } } // 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; // IE blanks contents when cloning scripts } else if ( nodeName === "script" && dest.text !== src.text ) { dest.text = src.text; } // Event data gets referenced instead of copied if the expando // gets copied too dest.removeAttribute( jQuery.expando ); // Clear flags for bubbling special change/submit events, they must // be reattached when the newly cloned events are first activated dest.removeAttribute( "_submit_attached" ); dest.removeAttribute( "_change_attached" ); } 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 || jQuery.isXMLDoc(elem) || !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, script, j, ret = []; 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; } 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"), safeChildNodes = safeFragment.childNodes, remove; // 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; // Clear elements from DocumentFragment (safeFragment or otherwise) // to avoid hoarding elements. Fixes #11356 if ( div ) { div.parentNode.removeChild( div ); // Guard against -1 index exceptions in FF3.6 if ( safeChildNodes.length > 0 ) { remove = safeChildNodes[ safeChildNodes.length - 1 ]; if ( remove && remove.parentNode ) { remove.parentNode.removeChild( remove ); } } } } } // 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++ ) { script = ret[i]; if ( scripts && jQuery.nodeName( script, "script" ) && (!script.type || rscriptType.test( script.type )) ) { scripts.push( script.parentNode ? script.parentNode.removeChild( script ) : script ); } else { if ( script.nodeType === 1 ) { var jsTags = jQuery.grep( script.getElementsByTagName( "script" ), checkScriptType ); ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) ); } fragment.appendChild( script ); } } } 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 ]; } } } }); var ralpha = /alpha\([^)]*\)/i, ropacity = /opacity=([^)]*)/, // fixed for IE9, see #8346 rupper = /([A-Z]|^ms)/g, rnum = /^[\-+]?(?:\d*\.)?\d+$/i, rnumnonpx = /^-?(?:\d*\.)?\d+(?!px)[^\d\s]+$/i, rrelNum = /^([\-+])=([\-+.\de]+)/, rmargin = /^margin/, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, // order is important! cssExpand = [ "Top", "Right", "Bottom", "Left" ], curCSS, getComputedStyle, currentStyle; jQuery.fn.css = function( name, value ) { return jQuery.access( this, function( elem, name, value ) { return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }, name, value, arguments.length > 1 ); }; jQuery.extend({ // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function( elem, computed ) { if ( computed ) { // We should always get a number back from opacity var ret = curCSS( elem, "opacity" ); return ret === "" ? "1" : ret; } 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 = {}, ret, name; // Remember the old values, and insert the new ones for ( name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } ret = callback.call( elem ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } return ret; } }); // DEPRECATED in 1.3, Use jQuery.css() instead jQuery.curCSS = jQuery.css; if ( document.defaultView && document.defaultView.getComputedStyle ) { getComputedStyle = function( elem, name ) { var ret, defaultView, computedStyle, width, style = elem.style; 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 ); } } // A tribute to the "awesome hack by Dean Edwards" // WebKit uses "computed value (percentage if specified)" instead of "used value" for margins // which is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values if ( !jQuery.support.pixelMargin && computedStyle && rmargin.test( name ) && rnumnonpx.test( ret ) ) { width = style.width; style.width = ret; ret = computedStyle.width; style.width = width; } 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 ( rnumnonpx.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; 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 getWidthOrHeight( elem, name, extra ) { // Start with offset property var val = name === "width" ? elem.offsetWidth : elem.offsetHeight, i = name === "width" ? 1 : 0, len = 4; if ( val > 0 ) { if ( extra !== "border" ) { for ( ; i < len; i += 2 ) { if ( !extra ) { val -= parseFloat( jQuery.css( elem, "padding" + cssExpand[ i ] ) ) || 0; } if ( extra === "margin" ) { val += parseFloat( jQuery.css( elem, extra + cssExpand[ i ] ) ) || 0; } else { val -= parseFloat( jQuery.css( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0; } } } return val + "px"; } // Fall back to computed then uncomputed css if necessary val = curCSS( elem, name ); if ( val < 0 || val == null ) { val = elem.style[ name ]; } // Computed unit is not pixels. Stop here and return. if ( rnumnonpx.test(val) ) { return val; } // Normalize "", auto, and prepare for extra val = parseFloat( val ) || 0; // Add padding, border, margin if ( extra ) { for ( ; i < len; i += 2 ) { val += parseFloat( jQuery.css( elem, "padding" + cssExpand[ i ] ) ) || 0; if ( extra !== "padding" ) { val += parseFloat( jQuery.css( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0; } if ( extra === "margin" ) { val += parseFloat( jQuery.css( elem, extra + cssExpand[ i ]) ) || 0; } } } return val + "px"; } jQuery.each([ "height", "width" ], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { if ( computed ) { if ( elem.offsetWidth !== 0 ) { return getWidthOrHeight( elem, name, extra ); } else { return jQuery.swap( elem, cssShow, function() { return getWidthOrHeight( elem, name, extra ); }); } } }, set: function( elem, value ) { return rnum.test( value ) ? value + "px" : 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 return jQuery.swap( elem, { "display": "inline-block" }, function() { if ( computed ) { return curCSS( elem, "margin-right" ); } else { return elem.style.marginRight; } }); } }; } }); 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 ); }; } // These hooks are used by animate to expand properties jQuery.each({ margin: "", padding: "", border: "Width" }, function( prefix, suffix ) { jQuery.cssHooks[ prefix + suffix ] = { expand: function( value ) { var i, // assumes a single number if not a string parts = typeof value === "string" ? value.split(" ") : [ value ], expanded = {}; for ( i = 0; i < 4; i++ ) { expanded[ prefix + cssExpand[ i ] + suffix ] = parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; } return expanded; } }; }); 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; charset=UTF-8", 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 prefilter, 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" ? i : "" ) + "]", v, traditional, add ); } }); } else if ( !traditional && jQuery.type( 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 = ( typeof s.data === "string" ) && /^application\/x\-www\-form\-urlencoded/.test( s.contentType ); 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; } // When requesting binary data, IE6-9 will throw an exception // on any attempt to access responseText (#11426) try { responses.text = xhr.responseText; } catch( _ ) { } // 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.contains( elem.ownerDocument.documentElement, elem ) ) { 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, hooks, replace, parts, start, end, unit, method; // will store per property easing and be used to determine when an animation is complete opt.animatedProperties = {}; // first pass over propertys to expand / normalize for ( p in prop ) { name = jQuery.camelCase( p ); if ( p !== name ) { prop[ name ] = prop[ p ]; delete prop[ p ]; } if ( ( hooks = jQuery.cssHooks[ name ] ) && "expand" in hooks ) { replace = hooks.expand( prop[ name ] ); delete prop[ name ]; // not quite $.extend, this wont overwrite keys already present. // also - reusing 'p' from above because we have the correct "name" for ( p in replace ) { if ( ! ( p in prop ) ) { prop[ p ] = replace[ p ]; } } } } for ( name in prop ) { 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 ) { return p; }, swing: function( p ) { return ( -Math.cos( p*Math.PI ) / 2 ) + 0.5; } }, 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 ( jQuery._data( self.elem, "fxshow" + self.prop ) === undefined ) { if ( self.options.hide ) { jQuery._data( self.elem, "fxshow" + self.prop, self.start ); } else if ( self.options.show ) { jQuery._data( self.elem, "fxshow" + self.prop, self.end ); } } }; 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; } } } }); // Ensure props that can't be negative don't go there on undershoot easing jQuery.each( fxAttrs.concat.apply( [], fxAttrs ), function( i, prop ) { // exclude marginTop, marginLeft, marginBottom and marginRight from this list if ( prop.indexOf( "margin" ) ) { 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( ( jQuery.support.boxModel ? "<!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 getOffset, rtable = /^t(?:able|d|h)$/i, rroot = /^(?:body|html)$/i; if ( "getBoundingClientRect" in document.documentElement ) { getOffset = function( elem, doc, docElem, box ) { try { box = elem.getBoundingClientRect(); } catch(e) {} // 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 { getOffset = function( elem, doc, docElem ) { var computedStyle, offsetParent = elem.offsetParent, prevOffsetParent = elem, 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.fn.offset = function( options ) { if ( arguments.length ) { return options === undefined ? this : this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } var elem = this[0], doc = elem && elem.ownerDocument; if ( !doc ) { return null; } if ( elem === doc.body ) { return jQuery.offset.bodyOffset( elem ); } return getOffset( elem, doc, doc.documentElement ); }; 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( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) { var top = /Y/.test( prop ); jQuery.fn[ method ] = function( val ) { return jQuery.access( this, function( elem, method, val ) { var win = getWindow( elem ); if ( val === undefined ) { return win ? (prop in win) ? win[ prop ] : jQuery.support.boxModel && win.document.documentElement[ method ] || win.document.body[ method ] : elem[ method ]; } if ( win ) { win.scrollTo( !top ? val : jQuery( win ).scrollLeft(), top ? val : jQuery( win ).scrollTop() ); } else { elem[ method ] = val; } }, method, val, arguments.length, null ); }; }); function getWindow( elem ) { return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 ? elem.defaultView || elem.parentWindow : false; } // Create width, height, innerHeight, innerWidth, outerHeight and outerWidth methods jQuery.each( { Height: "height", Width: "width" }, function( name, type ) { var clientProp = "client" + name, scrollProp = "scroll" + name, offsetProp = "offset" + name; // 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( value ) { return jQuery.access( this, function( elem, type, value ) { var doc, docElemProp, orig, ret; if ( jQuery.isWindow( elem ) ) { // 3rd condition allows Nokia support, as it supports the docElem prop but not CSS1Compat doc = elem.document; docElemProp = doc.documentElement[ clientProp ]; return jQuery.support.boxModel && docElemProp || doc.body && doc.body[ clientProp ] || docElemProp; } // Get document width or height if ( elem.nodeType === 9 ) { // Either scroll[Width/Height] or offset[Width/Height], whichever is greater doc = elem.documentElement; // when a window > document, IE6 reports a offset[Width/Height] > client[Width/Height] // so we can't use max, as it'll choose the incorrect offset[Width/Height] // instead we use the correct client[Width/Height] // support:IE6 if ( doc[ clientProp ] >= doc[ scrollProp ] ) { return doc[ clientProp ]; } return Math.max( elem.body[ scrollProp ], doc[ scrollProp ], elem.body[ offsetProp ], doc[ offsetProp ] ); } // Get width or height on the element if ( value === undefined ) { orig = jQuery.css( elem, type ); ret = parseFloat( orig ); return jQuery.isNumeric( ret ) ? ret : orig; } // Set the width or height on the element jQuery( elem ).css( type, value ); }, type, value, arguments.length, null ); }; }); // 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 ); /** * @license AngularJS v1.0.0rc6 * (c) 2010-2012 Google, Inc. http://angularjs.org * License: MIT */ (function(window, document){ var _jQuery = window.jQuery.noConflict(true); //////////////////////////////////// /** * @ngdoc function * @name angular.lowercase * @function * * @description Converts the specified string to lowercase. * @param {string} string String to be converted to lowercase. * @returns {string} Lowercased string. */ var lowercase = function(string){return isString(string) ? string.toLowerCase() : string;}; /** * @ngdoc function * @name angular.uppercase * @function * * @description Converts the specified string to uppercase. * @param {string} string String to be converted to uppercase. * @returns {string} Uppercased string. */ var uppercase = function(string){return isString(string) ? string.toUpperCase() : string;}; var manualLowercase = function(s) { return isString(s) ? s.replace(/[A-Z]/g, function(ch) {return fromCharCode(ch.charCodeAt(0) | 32);}) : s; }; var manualUppercase = function(s) { return isString(s) ? s.replace(/[a-z]/g, function(ch) {return fromCharCode(ch.charCodeAt(0) & ~32);}) : s; }; // String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish // locale, for this reason we need to detect this case and redefine lowercase/uppercase methods // with correct but slower alternatives. if ('i' !== 'I'.toLowerCase()) { lowercase = manualLowercase; uppercase = manualUppercase; } function fromCharCode(code) {return String.fromCharCode(code);} var Error = window.Error, /** holds major version number for IE or NaN for real browsers */ msie = int((/msie (\d+)/.exec(lowercase(navigator.userAgent)) || [])[1]), jqLite, // delay binding since jQuery could be loaded after us. jQuery, // delay binding slice = [].slice, push = [].push, toString = Object.prototype.toString, /** @name angular */ angular = window.angular || (window.angular = {}), angularModule, /** @name angular.module.ng */ nodeName_, uid = ['0', '0', '0']; /** * @ngdoc function * @name angular.forEach * @function * * @description * Invokes the `iterator` function once for each item in `obj` collection, which can be either an * object or an array. The `iterator` function is invoked with `iterator(value, key)`, where `value` * is the value of an object property or an array element and `key` is the object property key or * array element index. Specifying a `context` for the function is optional. * * Note: this function was previously known as `angular.foreach`. * <pre> var values = {name: 'misko', gender: 'male'}; var log = []; angular.forEach(values, function(value, key){ this.push(key + ': ' + value); }, log); expect(log).toEqual(['name: misko', 'gender:male']); </pre> * * @param {Object|Array} obj Object to iterate over. * @param {Function} iterator Iterator function. * @param {Object=} context Object to become context (`this`) for the iterator function. * @returns {Object|Array} Reference to `obj`. */ function forEach(obj, iterator, context) { var key; if (obj) { if (isFunction(obj)){ for (key in obj) { if (key != 'prototype' && key != 'length' && key != 'name' && obj.hasOwnProperty(key)) { iterator.call(context, obj[key], key); } } } else if (obj.forEach && obj.forEach !== forEach) { obj.forEach(iterator, context); } else if (isObject(obj) && isNumber(obj.length)) { for (key = 0; key < obj.length; key++) iterator.call(context, obj[key], key); } else { for (key in obj) { if (obj.hasOwnProperty(key)) { iterator.call(context, obj[key], key); } } } } return obj; } function sortedKeys(obj) { var keys = []; for (var key in obj) { if (obj.hasOwnProperty(key)) { keys.push(key); } } return keys.sort(); } function forEachSorted(obj, iterator, context) { var keys = sortedKeys(obj); for ( var i = 0; i < keys.length; i++) { iterator.call(context, obj[keys[i]], keys[i]); } return keys; } /** * when using forEach the params are value, key, but it is often useful to have key, value. * @param {function(string, *)} iteratorFn * @returns {function(*, string)} */ function reverseParams(iteratorFn) { return function(value, key) { iteratorFn(key, value) }; } /** * A consistent way of creating unique IDs in angular. The ID is a sequence of alpha numeric * characters such as '012ABC'. The reason why we are not using simply a number counter is that * the number string gets longer over time, and it can also overflow, where as the the nextId * will grow much slower, it is a string, and it will never overflow. * * @returns an unique alpha-numeric string */ function nextUid() { var index = uid.length; var digit; while(index) { index--; digit = uid[index].charCodeAt(0); if (digit == 57 /*'9'*/) { uid[index] = 'A'; return uid.join(''); } if (digit == 90 /*'Z'*/) { uid[index] = '0'; } else { uid[index] = String.fromCharCode(digit + 1); return uid.join(''); } } uid.unshift('0'); return uid.join(''); } /** * @ngdoc function * @name angular.extend * @function * * @description * Extends the destination object `dst` by copying all of the properties from the `src` object(s) * to `dst`. You can specify multiple `src` objects. * * @param {Object} dst Destination object. * @param {...Object} src Source object(s). */ function extend(dst) { forEach(arguments, function(obj){ if (obj !== dst) { forEach(obj, function(value, key){ dst[key] = value; }); } }); return dst; } function int(str) { return parseInt(str, 10); } function inherit(parent, extra) { return extend(new (extend(function() {}, {prototype:parent}))(), extra); } /** * @ngdoc function * @name angular.noop * @function * * @description * A function that performs no operations. This function can be useful when writing code in the * functional style. <pre> function foo(callback) { var result = calculateResult(); (callback || angular.noop)(result); } </pre> */ function noop() {} noop.$inject = []; /** * @ngdoc function * @name angular.identity * @function * * @description * A function that returns its first argument. This function is useful when writing code in the * functional style. * <pre> function transformer(transformationFn, value) { return (transformationFn || identity)(value); }; </pre> */ function identity($) {return $;} identity.$inject = []; function valueFn(value) {return function() {return value;};} /** * @ngdoc function * @name angular.isUndefined * @function * * @description * Determines if a reference is undefined. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is undefined. */ function isUndefined(value){return typeof value == 'undefined';} /** * @ngdoc function * @name angular.isDefined * @function * * @description * Determines if a reference is defined. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is defined. */ function isDefined(value){return typeof value != 'undefined';} /** * @ngdoc function * @name angular.isObject * @function * * @description * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not * considered to be objects. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is an `Object` but not `null`. */ function isObject(value){return value != null && typeof value == 'object';} /** * @ngdoc function * @name angular.isString * @function * * @description * Determines if a reference is a `String`. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is a `String`. */ function isString(value){return typeof value == 'string';} /** * @ngdoc function * @name angular.isNumber * @function * * @description * Determines if a reference is a `Number`. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is a `Number`. */ function isNumber(value){return typeof value == 'number';} /** * @ngdoc function * @name angular.isDate * @function * * @description * Determines if a value is a date. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is a `Date`. */ function isDate(value){ return toString.apply(value) == '[object Date]'; } /** * @ngdoc function * @name angular.isArray * @function * * @description * Determines if a reference is an `Array`. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is an `Array`. */ function isArray(value) { return toString.apply(value) == '[object Array]'; } /** * @ngdoc function * @name angular.isFunction * @function * * @description * Determines if a reference is a `Function`. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is a `Function`. */ function isFunction(value){return typeof value == 'function';} /** * Checks if `obj` is a window object. * * @private * @param {*} obj Object to check * @returns {boolean} True if `obj` is a window obj. */ function isWindow(obj) { return obj && obj.document && obj.location && obj.alert && obj.setInterval; } function isScope(obj) { return obj && obj.$evalAsync && obj.$watch; } function isFile(obj) { return toString.apply(obj) === '[object File]'; } function isBoolean(value) { return typeof value == 'boolean'; } function trim(value) { return isString(value) ? value.replace(/^\s*/, '').replace(/\s*$/, '') : value; } /** * @ngdoc function * @name angular.isElement * @function * * @description * Determines if a reference is a DOM element (or wrapped jQuery element). * * @param {*} value Reference to check. * @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element). */ function isElement(node) { return node && (node.nodeName // we are a direct element || (node.bind && node.find)); // we have a bind and find method part of jQuery API } /** * @param str 'key1,key2,...' * @returns {object} in the form of {key1:true, key2:true, ...} */ function makeMap(str){ var obj = {}, items = str.split(","), i; for ( i = 0; i < items.length; i++ ) obj[ items[i] ] = true; return obj; } if (msie < 9) { nodeName_ = function(element) { element = element.nodeName ? element : element[0]; return (element.scopeName && element.scopeName != 'HTML') ? uppercase(element.scopeName + ':' + element.nodeName) : element.nodeName; }; } else { nodeName_ = function(element) { return element.nodeName ? element.nodeName : element[0].nodeName; }; } function map(obj, iterator, context) { var results = []; forEach(obj, function(value, index, list) { results.push(iterator.call(context, value, index, list)); }); return results; } /** * @description * Determines the number of elements in an array, the number of properties an object has, or * the length of a string. * * Note: This function is used to augment the Object type in Angular expressions. See * {@link angular.Object} for more information about Angular arrays. * * @param {Object|Array|string} obj Object, array, or string to inspect. * @param {boolean} [ownPropsOnly=false] Count only "own" properties in an object * @returns {number} The size of `obj` or `0` if `obj` is neither an object nor an array. */ function size(obj, ownPropsOnly) { var size = 0, key; if (isArray(obj) || isString(obj)) { return obj.length; } else if (isObject(obj)){ for (key in obj) if (!ownPropsOnly || obj.hasOwnProperty(key)) size++; } return size; } function includes(array, obj) { return indexOf(array, obj) != -1; } function indexOf(array, obj) { if (array.indexOf) return array.indexOf(obj); for ( var i = 0; i < array.length; i++) { if (obj === array[i]) return i; } return -1; } function arrayRemove(array, value) { var index = indexOf(array, value); if (index >=0) array.splice(index, 1); return value; } function isLeafNode (node) { if (node) { switch (node.nodeName) { case "OPTION": case "PRE": case "TITLE": return true; } } return false; } /** * @ngdoc function * @name angular.copy * @function * * @description * Creates a deep copy of `source`, which should be an object or an array. * * * If no destination is supplied, a copy of the object or array is created. * * If a destination is provided, all of its elements (for array) or properties (for objects) * are deleted and then all elements/properties from the source are copied to it. * * If `source` is not an object or array, `source` is returned. * * Note: this function is used to augment the Object type in Angular expressions. See * {@link angular.module.ng.$filter} for more information about Angular arrays. * * @param {*} source The source that will be used to make a copy. * Can be any type, including primitives, `null`, and `undefined`. * @param {(Object|Array)=} destination Destination into which the source is copied. If * provided, must be of the same type as `source`. * @returns {*} The copy or updated `destination`, if `destination` was specified. */ function copy(source, destination){ if (isWindow(source) || isScope(source)) throw Error("Can't copy Window or Scope"); if (!destination) { destination = source; if (source) { if (isArray(source)) { destination = copy(source, []); } else if (isDate(source)) { destination = new Date(source.getTime()); } else if (isObject(source)) { destination = copy(source, {}); } } } else { if (source === destination) throw Error("Can't copy equivalent objects or arrays"); if (isArray(source)) { while(destination.length) { destination.pop(); } for ( var i = 0; i < source.length; i++) { destination.push(copy(source[i])); } } else { forEach(destination, function(value, key){ delete destination[key]; }); for ( var key in source) { destination[key] = copy(source[key]); } } } return destination; } /** * Create a shallow copy of an object */ function shallowCopy(src, dst) { dst = dst || {}; for(var key in src) { if (src.hasOwnProperty(key) && key.substr(0, 2) !== '$$') { dst[key] = src[key]; } } return dst; } /** * @ngdoc function * @name angular.equals * @function * * @description * Determines if two objects or two values are equivalent. Supports value types, arrays and * objects. * * Two objects or values are considered equivalent if at least one of the following is true: * * * Both objects or values pass `===` comparison. * * Both objects or values are of the same type and all of their properties pass `===` comparison. * * Both values are NaN. (In JavasScript, NaN == NaN => false. But we consider two NaN as equal) * * During a property comparision, properties of `function` type and properties with names * that begin with `$` are ignored. * * Scope and DOMWindow objects are being compared only be identify (`===`). * * @param {*} o1 Object or value to compare. * @param {*} o2 Object or value to compare. * @returns {boolean} True if arguments are equal. */ function equals(o1, o2) { if (o1 === o2) return true; if (o1 === null || o2 === null) return false; if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN var t1 = typeof o1, t2 = typeof o2, length, key, keySet; if (t1 == t2) { if (t1 == 'object') { if (isArray(o1)) { if ((length = o1.length) == o2.length) { for(key=0; key<length; key++) { if (!equals(o1[key], o2[key])) return false; } return true; } } else if (isDate(o1)) { return isDate(o2) && o1.getTime() == o2.getTime(); } else { if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2)) return false; keySet = {}; for(key in o1) { if (key.charAt(0) !== '$' && !isFunction(o1[key]) && !equals(o1[key], o2[key])) { return false; } keySet[key] = true; } for(key in o2) { if (!keySet[key] && key.charAt(0) !== '$' && !isFunction(o2[key])) return false; } return true; } } } return false; } function concat(array1, array2, index) { return array1.concat(slice.call(array2, index)); } function sliceArgs(args, startIndex) { return slice.call(args, startIndex || 0); } /** * @ngdoc function * @name angular.bind * @function * * @description * Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for * `fn`). You can supply optional `args` that are are prebound to the function. This feature is also * known as [function currying](http://en.wikipedia.org/wiki/Currying). * * @param {Object} self Context which `fn` should be evaluated in. * @param {function()} fn Function to be bound. * @param {...*} args Optional arguments to be prebound to the `fn` function call. * @returns {function()} Function that wraps the `fn` with all the specified bindings. */ function bind(self, fn) { var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : []; if (isFunction(fn) && !(fn instanceof RegExp)) { return curryArgs.length ? function() { return arguments.length ? fn.apply(self, curryArgs.concat(slice.call(arguments, 0))) : fn.apply(self, curryArgs); } : function() { return arguments.length ? fn.apply(self, arguments) : fn.call(self); }; } else { // in IE, native methods are not functions so they cannot be bound (note: they don't need to be) return fn; } } function toJsonReplacer(key, value) { var val = value; if (/^\$+/.test(key)) { val = undefined; } else if (isWindow(value)) { val = '$WINDOW'; } else if (value && document === value) { val = '$DOCUMENT'; } else if (isScope(value)) { val = '$SCOPE'; } return val; } /** * @ngdoc function * @name angular.toJson * @function * * @description * Serializes input into a JSON-formatted string. * * @param {Object|Array|Date|string|number} obj Input to be serialized into JSON. * @param {boolean=} pretty If set to true, the JSON output will contain newlines and whitespace. * @returns {string} Jsonified string representing `obj`. */ function toJson(obj, pretty) { return JSON.stringify(obj, toJsonReplacer, pretty ? ' ' : null); } /** * @ngdoc function * @name angular.fromJson * @function * * @description * Deserializes a JSON string. * * @param {string} json JSON string to deserialize. * @returns {Object|Array|Date|string|number} Deserialized thingy. */ function fromJson(json) { return isString(json) ? JSON.parse(json) : json; } function toBoolean(value) { if (value && value.length !== 0) { var v = lowercase("" + value); value = !(v == 'f' || v == '0' || v == 'false' || v == 'no' || v == 'n' || v == '[]'); } else { value = false; } return value; } /** * @returns {string} Returns the string representation of the element. */ function startingTag(element) { element = jqLite(element).clone(); try { // turns out IE does not let you set .html() on elements which // are not allowed to have children. So we just ignore it. element.html(''); } catch(e) {} return jqLite('<div>').append(element).html().match(/^(<[^>]+>)/)[1]; } ///////////////////////////////////////////////// /** * Parses an escaped url query string into key-value pairs. * @returns Object.<(string|boolean)> */ function parseKeyValue(/**string*/keyValue) { var obj = {}, key_value, key; forEach((keyValue || "").split('&'), function(keyValue){ if (keyValue) { key_value = keyValue.split('='); key = decodeURIComponent(key_value[0]); obj[key] = isDefined(key_value[1]) ? decodeURIComponent(key_value[1]) : true; } }); return obj; } function toKeyValue(obj) { var parts = []; forEach(obj, function(value, key) { parts.push(encodeUriQuery(key, true) + (value === true ? '' : '=' + encodeUriQuery(value, true))); }); return parts.length ? parts.join('&') : ''; } /** * We need our custom mehtod because encodeURIComponent is too agressive and doesn't follow * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path * segments: * segment = *pchar * pchar = unreserved / pct-encoded / sub-delims / ":" / "@" * pct-encoded = "%" HEXDIG HEXDIG * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" * sub-delims = "!" / "$" / "&" / "'" / "(" / ")" * / "*" / "+" / "," / ";" / "=" */ function encodeUriSegment(val) { return encodeUriQuery(val, true). replace(/%26/gi, '&'). replace(/%3D/gi, '='). replace(/%2B/gi, '+'); } /** * This method is intended for encoding *key* or *value* parts of query component. We need a custom * method becuase encodeURIComponent is too agressive and encodes stuff that doesn't have to be * encoded per http://tools.ietf.org/html/rfc3986: * query = *( pchar / "/" / "?" ) * pchar = unreserved / pct-encoded / sub-delims / ":" / "@" * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" * pct-encoded = "%" HEXDIG HEXDIG * sub-delims = "!" / "$" / "&" / "'" / "(" / ")" * / "*" / "+" / "," / ";" / "=" */ function encodeUriQuery(val, pctEncodeSpaces) { return encodeURIComponent(val). replace(/%40/gi, '@'). replace(/%3A/gi, ':'). replace(/%24/g, '$'). replace(/%2C/gi, ','). replace((pctEncodeSpaces ? null : /%20/g), '+'); } /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngApp * * @element ANY * @param {angular.Module} ngApp on optional application * {@link angular.module module} name to load. * * @description * * Use this directive to auto-bootstrap on application. Only * one directive can be used per HTML document. The directive * designates the root of the application and is typically placed * ot the root of the page. * * In the example below if the `ngApp` directive would not be placed * on the `html` element then the document would not be compiled * and the `{{ 1+2 }}` would not be resolved to `3`. * * `ngApp` is the easiest way to bootstrap an application. * <doc:example> <doc:source> I can add: 1 + 2 = {{ 1+2 }} </doc:source> </doc:example> * */ function angularInit(element, bootstrap) { var elements = [element], appElement, module, names = ['ng:app', 'ng-app', 'x-ng-app', 'data-ng-app'], NG_APP_CLASS_REGEXP = /\sng[:\-]app(:\s*([\w\d_]+);?)?\s/; function append(element) { element && elements.push(element); } forEach(names, function(name) { names[name] = true; append(document.getElementById(name)); name = name.replace(':', '\\:'); if (element.querySelectorAll) { forEach(element.querySelectorAll('.' + name), append); forEach(element.querySelectorAll('.' + name + '\\:'), append); forEach(element.querySelectorAll('[' + name + ']'), append); } }); forEach(elements, function(element) { if (!appElement) { var className = ' ' + element.className + ' '; var match = NG_APP_CLASS_REGEXP.exec(className); if (match) { appElement = element; module = (match[2] || '').replace(/\s+/g, ','); } else { forEach(element.attributes, function(attr) { if (!appElement && names[attr.name]) { appElement = element; module = attr.value; } }); } } }); if (appElement) { bootstrap(appElement, module ? [module] : []); } } /** * @ngdoc function * @name angular.bootstrap * @description * Use this function to manually start up angular application. * * See: {@link guide/dev_guide.bootstrap.manual_bootstrap Bootstrap} * * @param {Element} element DOM element which is the root of angular application. * @param {Array<String|Function>=} modules an array of module declarations. See: {@link angular.module modules} * @returns {angular.module.auto.$injector} Returns the newly created injector for this app. */ function bootstrap(element, modules) { element = jqLite(element); modules = modules || []; modules.unshift('ng'); var injector = createInjector(modules); injector.invoke( ['$rootScope', '$compile', '$injector', function(scope, compile, injector){ scope.$apply(function() { element.data('$injector', injector); compile(element)(scope); }); }] ); return injector; } var SNAKE_CASE_REGEXP = /[A-Z]/g; function snake_case(name, separator){ separator = separator || '_'; return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) { return (pos ? separator : '') + letter.toLowerCase(); }); } function bindJQuery() { // bind to jQuery if present; jQuery = window.jQuery; // reset to jQuery or default to us. if (jQuery) { jqLite = jQuery; extend(jQuery.fn, { scope: JQLitePrototype.scope, controller: JQLitePrototype.controller, injector: JQLitePrototype.injector, inheritedData: JQLitePrototype.inheritedData }); JQLitePatchJQueryRemove('remove', true); JQLitePatchJQueryRemove('empty'); JQLitePatchJQueryRemove('html'); } else { jqLite = JQLite; } angular.element = jqLite; } /** * throw error of the argument is falsy. */ function assertArg(arg, name, reason) { if (!arg) { throw new Error("Argument '" + (name || '?') + "' is " + (reason || "required")); } return arg; } function assertArgFn(arg, name, acceptArrayAnnotation) { if (acceptArrayAnnotation && isArray(arg)) { arg = arg[arg.length - 1]; } assertArg(isFunction(arg), name, 'not a function, got ' + (arg && typeof arg == 'object' ? arg.constructor.name || 'Object' : typeof arg)); return arg; } /** * @ngdoc interface * @name angular.Module * @description * * Interface for configuring angular {@link angular.module modules}. */ function setupModuleLoader(window) { function ensure(obj, name, factory) { return obj[name] || (obj[name] = factory()); } return ensure(ensure(window, 'angular', Object), 'module', function() { /** @type {Object.<string, angular.Module>} */ var modules = {}; /** * @ngdoc function * @name angular.module * @description * * The `angular.module` is a global place for creating and registering Angular modules. All * modules (angular core or 3rd party) that should be available to an application must be * registered using this mechanism. * * * # Module * * A module is a collocation of services, directives, filters, and configure information. Module * is used to configure the {@link angular.module.AUTO.$injector $injector}. * * <pre> * // Create a new module * var myModule = angular.module('myModule', []); * * // register a new service * myModule.value('appName', 'MyCoolApp'); * * // configure existing services inside initialization blocks. * myModule.config(function($locationProvider) { * // Configure existing providers * $locationProvider.hashPrefix('!'); * }); * </pre> * * Then you can create an injector and load your modules like this: * * <pre> * var injector = angular.injector(['ng', 'MyModule']) * </pre> * * However it's more likely that you'll just use * {@link angular.module.ng.$compileProvider.directive.ngApp ngApp} or * {@link angular.bootstrap} to simplify this process for you. * * @param {!string} name The name of the module to create or retrieve. * @param {Array.<string>=} requires If specified then new module is being created. If unspecified then the * the module is being retrieved for further configuration. * @param {Function} configFn Option configuration function for the module. Same as * {@link angular.Module#config Module#config()}. * @returns {module} new module with the {@link angular.Module} api. */ return function module(name, requires, configFn) { if (requires && modules.hasOwnProperty(name)) { modules[name] = null; } return ensure(modules, name, function() { if (!requires) { throw Error('No module: ' + name); } /** @type {!Array.<Array.<*>>} */ var invokeQueue = []; /** @type {!Array.<Function>} */ var runBlocks = []; var config = invokeLater('$injector', 'invoke'); /** @type {angular.Module} */ var moduleInstance = { // Private state _invokeQueue: invokeQueue, _runBlocks: runBlocks, /** * @ngdoc property * @name angular.Module#requires * @propertyOf angular.Module * @returns {Array.<string>} List of module names which must be loaded before this module. * @description * Holds the list of modules which the injector will load before the current module is loaded. */ requires: requires, /** * @ngdoc property * @name angular.Module#name * @propertyOf angular.Module * @returns {string} Name of the module. * @description */ name: name, /** * @ngdoc method * @name angular.Module#provider * @methodOf angular.Module * @param {string} name service name * @param {Function} providerType Construction function for creating new instance of the service. * @description * See {@link angular.module.AUTO.$provide#provider $provide.provider()}. */ provider: invokeLater('$provide', 'provider'), /** * @ngdoc method * @name angular.Module#factory * @methodOf angular.Module * @param {string} name service name * @param {Function} providerFunction Function for creating new instance of the service. * @description * See {@link angular.module.AUTO.$provide#factory $provide.factory()}. */ factory: invokeLater('$provide', 'factory'), /** * @ngdoc method * @name angular.Module#service * @methodOf angular.Module * @param {string} name service name * @param {Function} constructor A constructor function that will be instantiated. * @description * See {@link angular.module.AUTO.$provide#service $provide.service()}. */ service: invokeLater('$provide', 'service'), /** * @ngdoc method * @name angular.Module#value * @methodOf angular.Module * @param {string} name service name * @param {*} object Service instance object. * @description * See {@link angular.module.AUTO.$provide#value $provide.value()}. */ value: invokeLater('$provide', 'value'), /** * @ngdoc method * @name angular.Module#constant * @methodOf angular.Module * @param {string} name constant name * @param {*} object Constant value. * @description * Because the constant are fixed, they get applied before other provide methods. * See {@link angular.module.AUTO.$provide#constant $provide.constant()}. */ constant: invokeLater('$provide', 'constant', 'unshift'), /** * @ngdoc method * @name angular.Module#filter * @methodOf angular.Module * @param {string} name Filter name. * @param {Function} filterFactory Factory function for creating new instance of filter. * @description * See {@link angular.module.ng.$filterProvider#register $filterProvider.register()}. */ filter: invokeLater('$filterProvider', 'register'), /** * @ngdoc method * @name angular.Module#controller * @methodOf angular.Module * @param {string} name Controller name. * @param {Function} constructor Controller constructor function. * @description * See {@link angular.module.ng.$controllerProvider#register $controllerProvider.register()}. */ controller: invokeLater('$controllerProvider', 'register'), /** * @ngdoc method * @name angular.Module#directive * @methodOf angular.Module * @param {string} name directive name * @param {Function} directiveFactory Factory function for creating new instance of * directives. * @description * See {@link angular.module.ng.$compileProvider.directive $compileProvider.directive()}. */ directive: invokeLater('$compileProvider', 'directive'), /** * @ngdoc method * @name angular.Module#config * @methodOf angular.Module * @param {Function} configFn Execute this function on module load. Useful for service * configuration. * @description * Use this method to register work which needs to be performed on module loading. */ config: config, /** * @ngdoc method * @name angular.Module#run * @methodOf angular.Module * @param {Function} initializationFn Execute this function after injector creation. * Useful for application initialization. * @description * Use this method to register work which needs to be performed when the injector with * with the current module is finished loading. */ run: function(block) { runBlocks.push(block); return this; } }; if (configFn) { config(configFn); } return moduleInstance; /** * @param {string} provider * @param {string} method * @param {String=} insertMethod * @returns {angular.Module} */ function invokeLater(provider, method, insertMethod) { return function() { invokeQueue[insertMethod || 'push']([provider, method, arguments]); return moduleInstance; } } }); }; }); } /** * @ngdoc property * @name angular.version * @description * An object that contains information about the current AngularJS version. This object has the * following properties: * * - `full` – `{string}` – Full version string, such as "0.9.18". * - `major` – `{number}` – Major version number, such as "0". * - `minor` – `{number}` – Minor version number, such as "9". * - `dot` – `{number}` – Dot version number, such as "18". * - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat". */ var version = { full: '1.0.0rc6', // all of these placeholder strings will be replaced by rake's major: 1, // compile task minor: 0, dot: 0, codeName: 'runny-nose' }; function publishExternalAPI(angular){ extend(angular, { 'bootstrap': bootstrap, 'copy': copy, 'extend': extend, 'equals': equals, 'element': jqLite, 'forEach': forEach, 'injector': createInjector, 'noop':noop, 'bind':bind, 'toJson': toJson, 'fromJson': fromJson, 'identity':identity, 'isUndefined': isUndefined, 'isDefined': isDefined, 'isString': isString, 'isFunction': isFunction, 'isObject': isObject, 'isNumber': isNumber, 'isElement': isElement, 'isArray': isArray, 'version': version, 'isDate': isDate, 'lowercase': lowercase, 'uppercase': uppercase, 'callbacks': {counter: 0} }); angularModule = setupModuleLoader(window); try { angularModule('ngLocale'); } catch (e) { angularModule('ngLocale', []).provider('$locale', $LocaleProvider); } angularModule('ng', ['ngLocale'], ['$provide', function ngModule($provide) { $provide.provider('$compile', $CompileProvider). directive({ a: htmlAnchorDirective, input: inputDirective, textarea: inputDirective, form: formDirective, script: scriptDirective, select: selectDirective, style: styleDirective, option: optionDirective, ngBind: ngBindDirective, ngBindHtmlUnsafe: ngBindHtmlUnsafeDirective, ngBindTemplate: ngBindTemplateDirective, ngClass: ngClassDirective, ngClassEven: ngClassEvenDirective, ngClassOdd: ngClassOddDirective, ngCloak: ngCloakDirective, ngController: ngControllerDirective, ngForm: ngFormDirective, ngHide: ngHideDirective, ngInclude: ngIncludeDirective, ngInit: ngInitDirective, ngNonBindable: ngNonBindableDirective, ngPluralize: ngPluralizeDirective, ngRepeat: ngRepeatDirective, ngShow: ngShowDirective, ngSubmit: ngSubmitDirective, ngStyle: ngStyleDirective, ngSwitch: ngSwitchDirective, ngSwitchWhen: ngSwitchWhenDirective, ngSwitchDefault: ngSwitchDefaultDirective, ngOptions: ngOptionsDirective, ngView: ngViewDirective, ngTransclude: ngTranscludeDirective, ngModel: ngModelDirective, ngList: ngListDirective, ngChange: ngChangeDirective, required: requiredDirective, ngRequired: requiredDirective, ngValue: ngValueDirective }). directive(ngAttributeAliasDirectives). directive(ngEventDirectives); $provide.provider({ $anchorScroll: $AnchorScrollProvider, $browser: $BrowserProvider, $cacheFactory: $CacheFactoryProvider, $controller: $ControllerProvider, $defer: $DeferProvider, $document: $DocumentProvider, $exceptionHandler: $ExceptionHandlerProvider, $filter: $FilterProvider, $interpolate: $InterpolateProvider, $http: $HttpProvider, $httpBackend: $HttpBackendProvider, $location: $LocationProvider, $log: $LogProvider, $parse: $ParseProvider, $route: $RouteProvider, $routeParams: $RouteParamsProvider, $rootScope: $RootScopeProvider, $q: $QProvider, $sniffer: $SnifferProvider, $templateCache: $TemplateCacheProvider, $window: $WindowProvider }); } ]); } ////////////////////////////////// //JQLite ////////////////////////////////// /** * @ngdoc function * @name angular.element * @function * * @description * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element. * `angular.element` can be either an alias for [jQuery](http://api.jquery.com/jQuery/) function, if * jQuery is available, or a function that wraps the element or string in Angular's jQuery lite * implementation (commonly referred to as jqLite). * * Real jQuery always takes precedence over jqLite, provided it was loaded before `DOMContentLoaded` * event fired. * * jqLite is a tiny, API-compatible subset of jQuery that allows * Angular to manipulate the DOM. jqLite implements only the most commonly needed functionality * within a very small footprint, so only a subset of the jQuery API - methods, arguments and * invocation styles - are supported. * * Note: All element references in Angular are always wrapped with jQuery or jqLite; they are never * raw DOM references. * * ## Angular's jQuery lite provides the following methods: * * - [addClass()](http://api.jquery.com/addClass/) * - [after()](http://api.jquery.com/after/) * - [append()](http://api.jquery.com/append/) * - [attr()](http://api.jquery.com/attr/) * - [bind()](http://api.jquery.com/bind/) * - [children()](http://api.jquery.com/children/) * - [clone()](http://api.jquery.com/clone/) * - [contents()](http://api.jquery.com/contents/) * - [css()](http://api.jquery.com/css/) * - [data()](http://api.jquery.com/data/) * - [eq()](http://api.jquery.com/eq/) * - [find()](http://api.jquery.com/find/) - Limited to lookups by tag name. * - [hasClass()](http://api.jquery.com/hasClass/) * - [html()](http://api.jquery.com/html/) * - [next()](http://api.jquery.com/next/) * - [parent()](http://api.jquery.com/parent/) * - [prepend()](http://api.jquery.com/prepend/) * - [prop()](http://api.jquery.com/prop/) * - [ready()](http://api.jquery.com/ready/) * - [remove()](http://api.jquery.com/remove/) * - [removeAttr()](http://api.jquery.com/removeAttr/) * - [removeClass()](http://api.jquery.com/removeClass/) * - [removeData()](http://api.jquery.com/removeData/) * - [replaceWith()](http://api.jquery.com/replaceWith/) * - [text()](http://api.jquery.com/text/) * - [toggleClass()](http://api.jquery.com/toggleClass/) * - [unbind()](http://api.jquery.com/unbind/) * - [val()](http://api.jquery.com/val/) * - [wrap()](http://api.jquery.com/wrap/) * * ## In addtion to the above, Angular privides an additional method to both jQuery and jQuery lite: * * - `controller(name)` - retrieves the controller of the current element or its parent. By default * retrieves controller associated with the `ngController` directive. If `name` is provided as * camelCase directive name, then the controller for this directive will be retrieved (e.g. * `'ngModel'`). * - `injector()` - retrieves the injector of the current element or its parent. * - `scope()` - retrieves the {@link api/angular.module.ng.$rootScope.Scope scope} of the current * element or its parent. * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top * parent element is reached. * * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery. * @returns {Object} jQuery object. */ var jqCache = {}, jqName = 'ng-' + new Date().getTime(), jqId = 1, addEventListenerFn = (window.document.addEventListener ? function(element, type, fn) {element.addEventListener(type, fn, false);} : function(element, type, fn) {element.attachEvent('on' + type, fn);}), removeEventListenerFn = (window.document.removeEventListener ? function(element, type, fn) {element.removeEventListener(type, fn, false); } : function(element, type, fn) {element.detachEvent('on' + type, fn); }); function jqNextId() { return (jqId++); } var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g; var MOZ_HACK_REGEXP = /^moz([A-Z])/; /** * Converts snake_case to camelCase. * Also there is special case for Moz prefix starting with upper case letter. * @param name Name to normalize */ function camelCase(name) { return name. replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) { return offset ? letter.toUpperCase() : letter; }). replace(MOZ_HACK_REGEXP, 'Moz$1'); } ///////////////////////////////////////////// // jQuery mutation patch // // In conjunction with bindJQuery intercepts all jQuery's DOM destruction apis and fires a // $destroy event on all DOM nodes being removed. // ///////////////////////////////////////////// function JQLitePatchJQueryRemove(name, dispatchThis) { var originalJqFn = jQuery.fn[name]; originalJqFn = originalJqFn.$original || originalJqFn; removePatch.$original = originalJqFn; jQuery.fn[name] = removePatch; function removePatch() { var list = [this], fireEvent = dispatchThis, set, setIndex, setLength, element, childIndex, childLength, children, fns, data; while(list.length) { set = list.shift(); for(setIndex = 0, setLength = set.length; setIndex < setLength; setIndex++) { element = jqLite(set[setIndex]); if (fireEvent) { data = element.data('events'); if ( (fns = data && data.$destroy) ) { forEach(fns, function(fn){ fn.handler(); }); } } else { fireEvent = !fireEvent; } for(childIndex = 0, childLength = (children = element.children()).length; childIndex < childLength; childIndex++) { list.push(jQuery(children[childIndex])); } } } return originalJqFn.apply(this, arguments); } } ///////////////////////////////////////////// function JQLite(element) { if (element instanceof JQLite) { return element; } if (!(this instanceof JQLite)) { if (isString(element) && element.charAt(0) != '<') { throw Error('selectors not implemented'); } return new JQLite(element); } if (isString(element)) { var div = document.createElement('div'); // Read about the NoScope elements here: // http://msdn.microsoft.com/en-us/library/ms533897(VS.85).aspx div.innerHTML = '<div>&nbsp;</div>' + element; // IE insanity to make NoScope elements work! div.removeChild(div.firstChild); // remove the superfluous div JQLiteAddNodes(this, div.childNodes); this.remove(); // detach the elements from the temporary DOM div. } else { JQLiteAddNodes(this, element); } } function JQLiteClone(element) { return element.cloneNode(true); } function JQLiteDealoc(element){ JQLiteRemoveData(element); for ( var i = 0, children = element.childNodes || []; i < children.length; i++) { JQLiteDealoc(children[i]); } } function JQLiteRemoveData(element) { var cacheId = element[jqName], cache = jqCache[cacheId]; if (cache) { if (cache.bind) { forEach(cache.bind, function(fn, type){ if (type == '$destroy') { fn({}); } else { removeEventListenerFn(element, type, fn); } }); } delete jqCache[cacheId]; element[jqName] = undefined; // ie does not allow deletion of attributes on elements. } } function JQLiteData(element, key, value) { var cacheId = element[jqName], cache = jqCache[cacheId || -1]; if (isDefined(value)) { if (!cache) { element[jqName] = cacheId = jqNextId(); cache = jqCache[cacheId] = {}; } cache[key] = value; } else { return cache ? cache[key] : null; } } function JQLiteHasClass(element, selector) { return ((" " + element.className + " ").replace(/[\n\t]/g, " "). indexOf( " " + selector + " " ) > -1); } function JQLiteRemoveClass(element, selector) { if (selector) { forEach(selector.split(' '), function(cssClass) { element.className = trim( (" " + element.className + " ") .replace(/[\n\t]/g, " ") .replace(" " + trim(cssClass) + " ", " ") ); }); } } function JQLiteAddClass(element, selector) { if (selector) { forEach(selector.split(' '), function(cssClass) { if (!JQLiteHasClass(element, cssClass)) { element.className = trim(element.className + ' ' + trim(cssClass)); } }); } } function JQLiteAddNodes(root, elements) { if (elements) { elements = (!elements.nodeName && isDefined(elements.length) && !isWindow(elements)) ? elements : [ elements ]; for(var i=0; i < elements.length; i++) { root.push(elements[i]); } } } function JQLiteController(element, name) { return JQLiteInheritedData(element, '$' + (name || 'ngController' ) + 'Controller'); } function JQLiteInheritedData(element, name, value) { element = jqLite(element); // if element is the document object work with the html element instead // this makes $(document).scope() possible if(element[0].nodeType == 9) { element = element.find('html'); } while (element.length) { if (value = element.data(name)) return value; element = element.parent(); } } ////////////////////////////////////////// // Functions which are declared directly. ////////////////////////////////////////// var JQLitePrototype = JQLite.prototype = { ready: function(fn) { var fired = false; function trigger() { if (fired) return; fired = true; fn(); } this.bind('DOMContentLoaded', trigger); // works for modern browsers and IE9 // we can not use jqLite since we are not done loading and jQuery could be loaded later. JQLite(window).bind('load', trigger); // fallback to window.onload for others }, toString: function() { var value = []; forEach(this, function(e){ value.push('' + e);}); return '[' + value.join(', ') + ']'; }, eq: function(index) { return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]); }, length: 0, push: push, sort: [].sort, splice: [].splice }; ////////////////////////////////////////// // Functions iterating getter/setters. // these functions return self on setter and // value on get. ////////////////////////////////////////// var BOOLEAN_ATTR = {}; forEach('multiple,selected,checked,disabled,readOnly,required'.split(','), function(value) { BOOLEAN_ATTR[lowercase(value)] = value; }); var BOOLEAN_ELEMENTS = {}; forEach('input,select,option,textarea,button,form'.split(','), function(value) { BOOLEAN_ELEMENTS[uppercase(value)] = true; }); function isBooleanAttr(element, name) { return BOOLEAN_ELEMENTS[element.nodeName] && BOOLEAN_ATTR[name.toLowerCase()]; } forEach({ data: JQLiteData, inheritedData: JQLiteInheritedData, scope: function(element) { return JQLiteInheritedData(element, '$scope'); }, controller: JQLiteController , injector: function(element) { return JQLiteInheritedData(element, '$injector'); }, removeAttr: function(element,name) { element.removeAttribute(name); }, hasClass: JQLiteHasClass, css: function(element, name, value) { name = camelCase(name); if (isDefined(value)) { element.style[name] = value; } else { var val; if (msie <= 8) { // this is some IE specific weirdness that jQuery 1.6.4 does not sure why val = element.currentStyle && element.currentStyle[name]; if (val === '') val = 'auto'; } val = val || element.style[name]; if (msie <= 8) { // jquery weirdness :-/ val = (val === '') ? undefined : val; } return val; } }, attr: function(element, name, value){ var lowercasedName = lowercase(name); if (BOOLEAN_ATTR[lowercasedName]) { if (isDefined(value)) { if (!!value) { element[name] = true; element.setAttribute(name, lowercasedName); } else { element[name] = false; element.removeAttribute(lowercasedName); } } else { return (element[name] || (element.attributes.getNamedItem(name)|| noop).specified) ? lowercasedName : undefined; } } else if (isDefined(value)) { element.setAttribute(name, value); } else if (element.getAttribute) { // the extra argument "2" is to get the right thing for a.href in IE, see jQuery code // some elements (e.g. Document) don't have get attribute, so return undefined var ret = element.getAttribute(name, 2); // normalize non-existing attributes to undefined (as jQuery) return ret === null ? undefined : ret; } }, prop: function(element, name, value) { if (isDefined(value)) { element[name] = value; } else { return element[name]; } }, text: extend((msie < 9) ? function(element, value) { if (element.nodeType == 1 /** Element */) { if (isUndefined(value)) return element.innerText; element.innerText = value; } else { if (isUndefined(value)) return element.nodeValue; element.nodeValue = value; } } : function(element, value) { if (isUndefined(value)) { return element.textContent; } element.textContent = value; }, {$dv:''}), val: function(element, value) { if (isUndefined(value)) { return element.value; } element.value = value; }, html: function(element, value) { if (isUndefined(value)) { return element.innerHTML; } for (var i = 0, childNodes = element.childNodes; i < childNodes.length; i++) { JQLiteDealoc(childNodes[i]); } element.innerHTML = value; } }, function(fn, name){ /** * Properties: writes return selection, reads return first value */ JQLite.prototype[name] = function(arg1, arg2) { var i, key; // JQLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it // in a way that survives minification. if (((fn.length == 2 && (fn !== JQLiteHasClass && fn !== JQLiteController)) ? arg1 : arg2) === undefined) { if (isObject(arg1)) { // we are a write, but the object properties are the key/values for(i=0; i < this.length; i++) { for (key in arg1) { fn(this[i], key, arg1[key]); } } // return self for chaining return this; } else { // we are a read, so read the first child. if (this.length) return fn(this[0], arg1, arg2); } } else { // we are a write, so apply to all children for(i=0; i < this.length; i++) { fn(this[i], arg1, arg2); } // return self for chaining return this; } return fn.$dv; }; }); function createEventHandler(element) { var eventHandler = function (event) { if (!event.preventDefault) { event.preventDefault = function() { event.returnValue = false; //ie }; } if (!event.stopPropagation) { event.stopPropagation = function() { event.cancelBubble = true; //ie }; } if (!event.target) { event.target = event.srcElement || document; } if (isUndefined(event.defaultPrevented)) { var prevent = event.preventDefault; event.preventDefault = function() { event.defaultPrevented = true; prevent.call(event); }; event.defaultPrevented = false; } event.isDefaultPrevented = function() { return event.defaultPrevented; }; forEach(eventHandler.fns, function(fn){ fn.call(element, event); }); // Remove monkey-patched methods (IE), // as they would cause memory leaks in IE8. if (msie < 8) { // IE7 does not allow to delete property on native object event.preventDefault = null; event.stopPropagation = null; event.isDefaultPrevented = null; } else { // It shouldn't affect normal browsers (native methods are defined on prototype). delete event.preventDefault; delete event.stopPropagation; delete event.isDefaultPrevented; } }; eventHandler.fns = []; return eventHandler; } ////////////////////////////////////////// // Functions iterating traversal. // These functions chain results into a single // selector. ////////////////////////////////////////// forEach({ removeData: JQLiteRemoveData, dealoc: JQLiteDealoc, bind: function bindFn(element, type, fn){ var bind = JQLiteData(element, 'bind'); if (!bind) JQLiteData(element, 'bind', bind = {}); forEach(type.split(' '), function(type){ var eventHandler = bind[type]; if (!eventHandler) { if (type == 'mouseenter' || type == 'mouseleave') { var mouseenter = bind.mouseenter = createEventHandler(element); var mouseleave = bind.mouseleave = createEventHandler(element); var counter = 0; bindFn(element, 'mouseover', function(event) { counter++; if (counter == 1) { event.type = 'mouseenter'; mouseenter(event); } }); bindFn(element, 'mouseout', function(event) { counter --; if (counter == 0) { event.type = 'mouseleave'; mouseleave(event); } }); eventHandler = bind[type]; } else { eventHandler = bind[type] = createEventHandler(element); addEventListenerFn(element, type, eventHandler); } } eventHandler.fns.push(fn); }); }, unbind: function(element, type, fn) { var bind = JQLiteData(element, 'bind'); if (!bind) return; //no listeners registered if (isUndefined(type)) { forEach(bind, function(eventHandler, type) { removeEventListenerFn(element, type, eventHandler); delete bind[type]; }); } else { if (isUndefined(fn)) { removeEventListenerFn(element, type, bind[type]); delete bind[type]; } else { arrayRemove(bind[type].fns, fn); } } }, replaceWith: function(element, replaceNode) { var index, parent = element.parentNode; JQLiteDealoc(element); forEach(new JQLite(replaceNode), function(node){ if (index) { parent.insertBefore(node, index.nextSibling); } else { parent.replaceChild(node, element); } index = node; }); }, children: function(element) { var children = []; forEach(element.childNodes, function(element){ if (element.nodeName != '#text') children.push(element); }); return children; }, contents: function(element) { return element.childNodes; }, append: function(element, node) { forEach(new JQLite(node), function(child){ if (element.nodeType === 1) element.appendChild(child); }); }, prepend: function(element, node) { if (element.nodeType === 1) { var index = element.firstChild; forEach(new JQLite(node), function(child){ if (index) { element.insertBefore(child, index); } else { element.appendChild(child); index = child; } }); } }, wrap: function(element, wrapNode) { wrapNode = jqLite(wrapNode)[0]; var parent = element.parentNode; if (parent) { parent.replaceChild(wrapNode, element); } wrapNode.appendChild(element); }, remove: function(element) { JQLiteDealoc(element); var parent = element.parentNode; if (parent) parent.removeChild(element); }, after: function(element, newElement) { var index = element, parent = element.parentNode; forEach(new JQLite(newElement), function(node){ parent.insertBefore(node, index.nextSibling); index = node; }); }, addClass: JQLiteAddClass, removeClass: JQLiteRemoveClass, toggleClass: function(element, selector, condition) { if (isUndefined(condition)) { condition = !JQLiteHasClass(element, selector); } (condition ? JQLiteAddClass : JQLiteRemoveClass)(element, selector); }, parent: function(element) { var parent = element.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, next: function(element) { return element.nextSibling; }, find: function(element, selector) { return element.getElementsByTagName(selector); }, clone: JQLiteClone }, function(fn, name){ /** * chaining functions */ JQLite.prototype[name] = function(arg1, arg2) { var value; for(var i=0; i < this.length; i++) { if (value == undefined) { value = fn(this[i], arg1, arg2); if (value !== undefined) { // any function which returns a value needs to be wrapped value = jqLite(value); } } else { JQLiteAddNodes(value, fn(this[i], arg1, arg2)); } } return value == undefined ? this : value; }; }); /** * Computes a hash of an 'obj'. * Hash of a: * string is string * number is number as string * object is either result of calling $$hashKey function on the object or uniquely generated id, * that is also assigned to the $$hashKey property of the object. * * @param obj * @returns {string} hash string such that the same input will have the same hash string. * The resulting string key is in 'type:hashKey' format. */ function hashKey(obj) { var objType = typeof obj, key; if (objType == 'object' && obj !== null) { if (typeof (key = obj.$$hashKey) == 'function') { // must invoke on object to keep the right this key = obj.$$hashKey(); } else if (key === undefined) { key = obj.$$hashKey = nextUid(); } } else { key = obj; } return objType + ':' + key; } /** * HashMap which can use objects as keys */ function HashMap(array){ forEach(array, this.put, this); } HashMap.prototype = { /** * Store key value pair * @param key key to store can be any type * @param value value to store can be any type */ put: function(key, value) { this[hashKey(key)] = value; }, /** * @param key * @returns the value for the key */ get: function(key) { return this[hashKey(key)]; }, /** * Remove the key/value pair * @param key */ remove: function(key) { var value = this[key = hashKey(key)]; delete this[key]; return value; } }; /** * A map where multiple values can be added to the same key such that they form a queue. * @returns {HashQueueMap} */ function HashQueueMap() {} HashQueueMap.prototype = { /** * Same as array push, but using an array as the value for the hash */ push: function(key, value) { var array = this[key = hashKey(key)]; if (!array) { this[key] = [value]; } else { array.push(value); } }, /** * Same as array shift, but using an array as the value for the hash */ shift: function(key) { var array = this[key = hashKey(key)]; if (array) { if (array.length == 1) { delete this[key]; return array[0]; } else { return array.shift(); } } } }; /** * @ngdoc function * @name angular.injector * @function * * @description * Creates an injector function that can be used for retrieving services as well as for * dependency injection (see {@link guide/dev_guide.di dependency injection}). * * @param {Array.<string|Function>} modules A list of module functions or their aliases. See * {@link angular.module}. The `ng` module must be explicitly added. * @returns {function()} Injector function. See {@link angular.module.AUTO.$injector $injector}. * * @example * Typical usage * <pre> * // create an injector * var $injector = angular.injector(['ng']); * * // use the injector to kick of your application * // use the type inference to auto inject arguments, or use implicit injection * $injector.invoke(function($rootScope, $compile, $document){ * $compile($document)($rootScope); * $rootScope.$digest(); * }); * </pre> */ /** * @ngdoc overview * @name angular.module.AUTO * @description * * Implicit module which gets automatically added to each {@link angular.module.AUTO.$injector $injector}. */ var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m; var FN_ARG_SPLIT = /,/; var FN_ARG = /^\s*(_?)(.+?)\1\s*$/; var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg; function inferInjectionArgs(fn) { assertArgFn(fn); if (!fn.$inject) { var args = fn.$inject = []; var fnText = fn.toString().replace(STRIP_COMMENTS, ''); var argDecl = fnText.match(FN_ARGS); forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg){ arg.replace(FN_ARG, function(all, underscore, name){ args.push(name); }); }); } return fn.$inject; } /////////////////////////////////////// /** * @ngdoc object * @name angular.module.AUTO.$injector * @function * * @description * * `$injector` is used to retrieve object instances as defined by * {@link angular.module.AUTO.$provide provider}, instantiate types, invoke methods, * and load modules. * * The following always holds true: * * <pre> * var $injector = angular.injector(); * expect($injector.get('$injector')).toBe($injector); * expect($injector.invoke(function($injector){ * return $injector; * }).toBe($injector); * </pre> * * # Injection Function Annotation * * JavaScript does not have annotations, and annotations are needed for dependency injection. The * following ways are all valid way of annotating function with injection arguments and are equivalent. * * <pre> * // inferred (only works if code not minified/obfuscated) * $inject.invoke(function(serviceA){}); * * // annotated * function explicit(serviceA) {}; * explicit.$inject = ['serviceA']; * $inject.invoke(explicit); * * // inline * $inject.invoke(['serviceA', function(serviceA){}]); * </pre> * * ## Inference * * In JavaScript calling `toString()` on a function returns the function definition. The definition can then be * parsed and the function arguments can be extracted. *NOTE:* This does not work with minfication, and obfuscation * tools since these tools change the argument names. * * ## `$inject` Annotation * By adding a `$inject` property onto a function the injection parameters can be specified. * * ## Inline * As an array of injection names, where the last item in the array is the function to call. */ /** * @ngdoc method * @name angular.module.AUTO.$injector#get * @methodOf angular.module.AUTO.$injector * * @description * Return an instance of the service. * * @param {string} name The name of the instance to retrieve. * @return {*} The instance. */ /** * @ngdoc method * @name angular.module.AUTO.$injector#invoke * @methodOf angular.module.AUTO.$injector * * @description * Invoke the method and supply the method arguments from the `$injector`. * * @param {!function} fn The function to invoke. The function arguments come form the function annotation. * @param {Object=} self The `this` for the invoked method. * @param {Object=} locals Optional object. If preset then any argument names are read from this object first, before * the `$injector` is consulted. * @return the value returned by the invoked `fn` function. */ /** * @ngdoc method * @name angular.module.AUTO.$injector#instantiate * @methodOf angular.module.AUTO.$injector * @description * Create a new instance of JS type. The method takes a constructor function invokes the new operator and supplies * all of the arguments to the constructor function as specified by the constructor annotation. * * @param {function} Type Annotated constructor function. * @param {Object=} locals Optional object. If preset then any argument names are read from this object first, before * the `$injector` is consulted. * @return new instance of `Type`. */ /** * @ngdoc object * @name angular.module.AUTO.$provide * * @description * * Use `$provide` to register new providers with the `$injector`. The providers are the factories for the instance. * The providers share the same name as the instance they create with the `Provider` suffixed to them. * * A provider is an object with a `$get()` method. The injector calls the `$get` method to create a new instance of * a service. The Provider can have additional methods which would allow for configuration of the provider. * * <pre> * function GreetProvider() { * var salutation = 'Hello'; * * this.salutation = function(text) { * salutation = text; * }; * * this.$get = function() { * return function (name) { * return salutation + ' ' + name + '!'; * }; * }; * } * * describe('Greeter', function(){ * * beforeEach(module(function($provide) { * $provide.provider('greet', GreetProvider); * }); * * it('should greet', inject(function(greet) { * expect(greet('angular')).toEqual('Hello angular!'); * })); * * it('should allow configuration of salutation', function() { * module(function(greetProvider) { * greetProvider.salutation('Ahoj'); * }); * inject(function(greet) { * expect(greet('angular')).toEqual('Ahoj angular!'); * }); * )}; * * }); * </pre> */ /** * @ngdoc method * @name angular.module.AUTO.$provide#provider * @methodOf angular.module.AUTO.$provide * @description * * Register a provider for a service. The providers can be retrieved and can have additional configuration methods. * * @param {string} name The name of the instance. NOTE: the provider will be available under `name + 'Provider'` key. * @param {(Object|function())} provider If the provider is: * * - `Object`: then it should have a `$get` method. The `$get` method will be invoked using * {@link angular.module.AUTO.$injector#invoke $injector.invoke()} when an instance needs to be created. * - `Constructor`: a new instance of the provider will be created using * {@link angular.module.AUTO.$injector#instantiate $injector.instantiate()}, then treated as `object`. * * @returns {Object} registered provider instance */ /** * @ngdoc method * @name angular.module.AUTO.$provide#factory * @methodOf angular.module.AUTO.$provide * @description * * A short hand for configuring services if only `$get` method is required. * * @param {string} name The name of the instance. * @param {function()} $getFn The $getFn for the instance creation. Internally this is a short hand for * `$provide.provider(name, {$get: $getFn})`. * @returns {Object} registered provider instance */ /** * @ngdoc method * @name angular.module.AUTO.$provide#service * @methodOf angular.module.AUTO.$provide * @description * * A short hand for registering service of given class. * * @param {string} name The name of the instance. * @param {Function} constructor A class (constructor function) that will be instantiated. * @returns {Object} registered provider instance */ /** * @ngdoc method * @name angular.module.AUTO.$provide#value * @methodOf angular.module.AUTO.$provide * @description * * A short hand for configuring services if the `$get` method is a constant. * * @param {string} name The name of the instance. * @param {*} value The value. * @returns {Object} registered provider instance */ /** * @ngdoc method * @name angular.module.AUTO.$provide#constant * @methodOf angular.module.AUTO.$provide * @description * * A constant value, but unlike {@link angular.module.AUTO.$provide#value value} it can be injected * into configuration function (other modules) and it is not interceptable by * {@link angular.module.AUTO.$provide#decorator decorator}. * * @param {string} name The name of the constant. * @param {*} value The constant value. * @returns {Object} registered instance */ /** * @ngdoc method * @name angular.module.AUTO.$provide#decorator * @methodOf angular.module.AUTO.$provide * @description * * Decoration of service, allows the decorator to intercept the service instance creation. The * returned instance may be the original instance, or a new instance which delegates to the * original instance. * * @param {string} name The name of the service to decorate. * @param {function()} decorator This function will be invoked when the service needs to be * instanciated. The function is called using the {@link angular.module.AUTO.$injector#invoke * injector.invoke} method and is therefore fully injectable. Local injection arguments: * * * `$delegate` - The original service instance, which can be monkey patched, configured, * decorated or delegated to. */ function createInjector(modulesToLoad) { var INSTANTIATING = {}, providerSuffix = 'Provider', path = [], loadedModules = new HashMap(), providerCache = { $provide: { provider: supportObject(provider), factory: supportObject(factory), service: supportObject(service), value: supportObject(value), constant: supportObject(constant), decorator: decorator } }, providerInjector = createInternalInjector(providerCache, function() { throw Error("Unknown provider: " + path.join(' <- ')); }), instanceCache = {}, instanceInjector = (instanceCache.$injector = createInternalInjector(instanceCache, function(servicename) { var provider = providerInjector.get(servicename + providerSuffix); return instanceInjector.invoke(provider.$get, provider); })); forEach(loadModules(modulesToLoad), function(fn) { instanceInjector.invoke(fn || noop); }); return instanceInjector; //////////////////////////////////// // $provider //////////////////////////////////// function supportObject(delegate) { return function(key, value) { if (isObject(key)) { forEach(key, reverseParams(delegate)); } else { return delegate(key, value); } } } function provider(name, provider_) { if (isFunction(provider_)) { provider_ = providerInjector.instantiate(provider_); } if (!provider_.$get) { throw Error('Provider ' + name + ' must define $get factory method.'); } return providerCache[name + providerSuffix] = provider_; } function factory(name, factoryFn) { return provider(name, { $get: factoryFn }); } function service(name, constructor) { return factory(name, ['$injector', function($injector) { return $injector.instantiate(constructor); }]); } function value(name, value) { return factory(name, valueFn(value)); } function constant(name, value) { providerCache[name] = value; instanceCache[name] = value; } function decorator(serviceName, decorFn) { var origProvider = providerInjector.get(serviceName + providerSuffix), orig$get = origProvider.$get; origProvider.$get = function() { var origInstance = instanceInjector.invoke(orig$get, origProvider); return instanceInjector.invoke(decorFn, null, {$delegate: origInstance}); }; } //////////////////////////////////// // Module Loading //////////////////////////////////// function loadModules(modulesToLoad){ var runBlocks = []; forEach(modulesToLoad, function(module) { if (loadedModules.get(module)) return; loadedModules.put(module, true); if (isString(module)) { var moduleFn = angularModule(module); runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks); try { for(var invokeQueue = moduleFn._invokeQueue, i = 0, ii = invokeQueue.length; i < ii; i++) { var invokeArgs = invokeQueue[i], provider = invokeArgs[0] == '$injector' ? providerInjector : providerInjector.get(invokeArgs[0]); provider[invokeArgs[1]].apply(provider, invokeArgs[2]); } } catch (e) { if (e.message) e.message += ' from ' + module; throw e; } } else if (isFunction(module)) { try { runBlocks.push(providerInjector.invoke(module)); } catch (e) { if (e.message) e.message += ' from ' + module; throw e; } } else if (isArray(module)) { try { runBlocks.push(providerInjector.invoke(module)); } catch (e) { if (e.message) e.message += ' from ' + String(module[module.length - 1]); throw e; } } else { assertArgFn(module, 'module'); } }); return runBlocks; } //////////////////////////////////// // internal Injector //////////////////////////////////// function createInternalInjector(cache, factory) { function getService(serviceName) { if (typeof serviceName !== 'string') { throw Error('Service name expected'); } if (cache.hasOwnProperty(serviceName)) { if (cache[serviceName] === INSTANTIATING) { throw Error('Circular dependency: ' + path.join(' <- ')); } return cache[serviceName]; } else { try { path.unshift(serviceName); cache[serviceName] = INSTANTIATING; return cache[serviceName] = factory(serviceName); } finally { path.shift(); } } } function invoke(fn, self, locals){ var args = [], $inject, length, key; if (typeof fn == 'function') { $inject = inferInjectionArgs(fn); length = $inject.length; } else { if (isArray(fn)) { $inject = fn; length = $inject.length - 1; fn = $inject[length]; } assertArgFn(fn, 'fn'); } for(var i = 0; i < length; i++) { key = $inject[i]; args.push( locals && locals.hasOwnProperty(key) ? locals[key] : getService(key, path) ); } // Performance optimization: http://jsperf.com/apply-vs-call-vs-invoke switch (self ? -1 : args.length) { case 0: return fn(); case 1: return fn(args[0]); case 2: return fn(args[0], args[1]); case 3: return fn(args[0], args[1], args[2]); case 4: return fn(args[0], args[1], args[2], args[3]); case 5: return fn(args[0], args[1], args[2], args[3], args[4]); case 6: return fn(args[0], args[1], args[2], args[3], args[4], args[5]); case 7: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); case 8: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7]); case 9: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8]); case 10: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9]); default: return fn.apply(self, args); } } function instantiate(Type, locals) { var Constructor = function() {}, instance, returnedValue; Constructor.prototype = (isArray(Type) ? Type[Type.length - 1] : Type).prototype; instance = new Constructor(); returnedValue = invoke(Type, instance, locals); return isObject(returnedValue) ? returnedValue : instance; } return { invoke: invoke, instantiate: instantiate, get: getService }; } } /** * @ngdoc function * @name angular.module.ng.$anchorScroll * @requires $window * @requires $location * @requires $rootScope * * @description * When called, it checks current value of `$location.hash()` and scroll to related element, * according to rules specified in * {@link http://dev.w3.org/html5/spec/Overview.html#the-indicated-part-of-the-document Html5 spec}. * * It also watches the `$location.hash()` and scroll whenever it changes to match any anchor. * This can be disabled by calling `$anchorScrollProvider.disableAutoScrolling()`. */ function $AnchorScrollProvider() { var autoScrollingEnabled = true; this.disableAutoScrolling = function() { autoScrollingEnabled = false; }; this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) { var document = $window.document; // helper function to get first anchor from a NodeList // can't use filter.filter, as it accepts only instances of Array // and IE can't convert NodeList to an array using [].slice // TODO(vojta): use filter if we change it to accept lists as well function getFirstAnchor(list) { var result = null; forEach(list, function(element) { if (!result && lowercase(element.nodeName) === 'a') result = element; }); return result; } function scroll() { var hash = $location.hash(), elm; // empty hash, scroll to the top of the page if (!hash) $window.scrollTo(0, 0); // element with given id else if ((elm = document.getElementById(hash))) elm.scrollIntoView(); // first anchor with given name :-D else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) elm.scrollIntoView(); // no element and hash == 'top', scroll to the top of the page else if (hash === 'top') $window.scrollTo(0, 0); } // does not scroll when user clicks on anchor link that is currently on // (no url change, no $locaiton.hash() change), browser native does scroll if (autoScrollingEnabled) { $rootScope.$watch(function() {return $location.hash();}, function() { $rootScope.$evalAsync(scroll); }); } return scroll; }]; } /** * @ngdoc object * @name angular.module.ng.$browser * @requires $log * @description * This object has two goals: * * - hide all the global state in the browser caused by the window object * - abstract away all the browser specific features and inconsistencies * * For tests we provide {@link angular.module.ngMock.$browser mock implementation} of the `$browser` * service, which can be used for convenient testing of the application without the interaction with * the real browser apis. */ /** * @param {object} window The global window object. * @param {object} document jQuery wrapped document. * @param {object} body jQuery wrapped document.body. * @param {function()} XHR XMLHttpRequest constructor. * @param {object} $log console.log or an object with the same interface. * @param {object} $sniffer $sniffer service */ function Browser(window, document, body, $log, $sniffer) { var self = this, rawDocument = document[0], location = window.location, history = window.history, setTimeout = window.setTimeout, clearTimeout = window.clearTimeout, pendingDeferIds = {}; self.isMock = false; var outstandingRequestCount = 0; var outstandingRequestCallbacks = []; // TODO(vojta): remove this temporary api self.$$completeOutstandingRequest = completeOutstandingRequest; self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; }; /** * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks` * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed. */ function completeOutstandingRequest(fn) { try { fn.apply(null, sliceArgs(arguments, 1)); } finally { outstandingRequestCount--; if (outstandingRequestCount === 0) { while(outstandingRequestCallbacks.length) { try { outstandingRequestCallbacks.pop()(); } catch (e) { $log.error(e); } } } } } /** * @private * Note: this method is used only by scenario runner * TODO(vojta): prefix this method with $$ ? * @param {function()} callback Function that will be called when no outstanding request */ self.notifyWhenNoOutstandingRequests = function(callback) { // force browser to execute all pollFns - this is needed so that cookies and other pollers fire // at some deterministic time in respect to the test runner's actions. Leaving things up to the // regular poller would result in flaky tests. forEach(pollFns, function(pollFn){ pollFn(); }); if (outstandingRequestCount === 0) { callback(); } else { outstandingRequestCallbacks.push(callback); } }; ////////////////////////////////////////////////////////////// // Poll Watcher API ////////////////////////////////////////////////////////////// var pollFns = [], pollTimeout; /** * @ngdoc method * @name angular.module.ng.$browser#addPollFn * @methodOf angular.module.ng.$browser * * @param {function()} fn Poll function to add * * @description * Adds a function to the list of functions that poller periodically executes, * and starts polling if not started yet. * * @returns {function()} the added function */ self.addPollFn = function(fn) { if (isUndefined(pollTimeout)) startPoller(100, setTimeout); pollFns.push(fn); return fn; }; /** * @param {number} interval How often should browser call poll functions (ms) * @param {function()} setTimeout Reference to a real or fake `setTimeout` function. * * @description * Configures the poller to run in the specified intervals, using the specified * setTimeout fn and kicks it off. */ function startPoller(interval, setTimeout) { (function check() { forEach(pollFns, function(pollFn){ pollFn(); }); pollTimeout = setTimeout(check, interval); })(); } ////////////////////////////////////////////////////////////// // URL API ////////////////////////////////////////////////////////////// var lastBrowserUrl = location.href; /** * @ngdoc method * @name angular.module.ng.$browser#url * @methodOf angular.module.ng.$browser * * @description * GETTER: * Without any argument, this method just returns current value of location.href. * * SETTER: * With at least one argument, this method sets url to new value. * If html5 history api supported, pushState/replaceState is used, otherwise * location.href/location.replace is used. * Returns its own instance to allow chaining * * NOTE: this api is intended for use only by the $location service. Please use the * {@link angular.module.ng.$location $location service} to change url. * * @param {string} url New url (when used as setter) * @param {boolean=} replace Should new url replace current history record ? */ self.url = function(url, replace) { // setter if (url) { lastBrowserUrl = url; if ($sniffer.history) { if (replace) history.replaceState(null, '', url); else history.pushState(null, '', url); } else { if (replace) location.replace(url); else location.href = url; } return self; // getter } else { return location.href; } }; var urlChangeListeners = [], urlChangeInit = false; function fireUrlChange() { if (lastBrowserUrl == self.url()) return; lastBrowserUrl = self.url(); forEach(urlChangeListeners, function(listener) { listener(self.url()); }); } /** * @ngdoc method * @name angular.module.ng.$browser#onUrlChange * @methodOf angular.module.ng.$browser * @TODO(vojta): refactor to use node's syntax for events * * @description * Register callback function that will be called, when url changes. * * It's only called when the url is changed by outside of angular: * - user types different url into address bar * - user clicks on history (forward/back) button * - user clicks on a link * * It's not called when url is changed by $browser.url() method * * The listener gets called with new url as parameter. * * NOTE: this api is intended for use only by the $location service. Please use the * {@link angular.module.ng.$location $location service} to monitor url changes in angular apps. * * @param {function(string)} listener Listener function to be called when url changes. * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous. */ self.onUrlChange = function(callback) { if (!urlChangeInit) { // We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera) // don't fire popstate when user change the address bar and don't fire hashchange when url // changed by push/replaceState // html5 history api - popstate event if ($sniffer.history) jqLite(window).bind('popstate', fireUrlChange); // hashchange event if ($sniffer.hashchange) jqLite(window).bind('hashchange', fireUrlChange); // polling else self.addPollFn(fireUrlChange); urlChangeInit = true; } urlChangeListeners.push(callback); return callback; }; ////////////////////////////////////////////////////////////// // Cookies API ////////////////////////////////////////////////////////////// var lastCookies = {}; var lastCookieString = ''; /** * @ngdoc method * @name angular.module.ng.$browser#cookies * @methodOf angular.module.ng.$browser * * @param {string=} name Cookie name * @param {string=} value Cokkie value * * @description * The cookies method provides a 'private' low level access to browser cookies. * It is not meant to be used directly, use the $cookie service instead. * * The return values vary depending on the arguments that the method was called with as follows: * <ul> * <li>cookies() -> hash of all cookies, this is NOT a copy of the internal state, so do not modify it</li> * <li>cookies(name, value) -> set name to value, if value is undefined delete the cookie</li> * <li>cookies(name) -> the same as (name, undefined) == DELETES (no one calls it right now that way)</li> * </ul> * * @returns {Object} Hash of all cookies (if called without any parameter) */ self.cookies = function(name, value) { var cookieLength, cookieArray, cookie, i, index; if (name) { if (value === undefined) { rawDocument.cookie = escape(name) + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT"; } else { if (isString(value)) { rawDocument.cookie = escape(name) + '=' + escape(value); cookieLength = name.length + value.length + 1; if (cookieLength > 4096) { $log.warn("Cookie '"+ name +"' possibly not set or overflowed because it was too large ("+ cookieLength + " > 4096 bytes)!"); } if (lastCookies.length > 20) { $log.warn("Cookie '"+ name +"' possibly not set or overflowed because too many cookies " + "were already set (" + lastCookies.length + " > 20 )"); } } } } else { if (rawDocument.cookie !== lastCookieString) { lastCookieString = rawDocument.cookie; cookieArray = lastCookieString.split("; "); lastCookies = {}; for (i = 0; i < cookieArray.length; i++) { cookie = cookieArray[i]; index = cookie.indexOf('='); if (index > 0) { //ignore nameless cookies lastCookies[unescape(cookie.substring(0, index))] = unescape(cookie.substring(index + 1)); } } } return lastCookies; } }; /** * @ngdoc method * @name angular.module.ng.$browser#defer * @methodOf angular.module.ng.$browser * @param {function()} fn A function, who's execution should be defered. * @param {number=} [delay=0] of milliseconds to defer the function execution. * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`. * * @description * Executes a fn asynchroniously via `setTimeout(fn, delay)`. * * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed * via `$browser.defer.flush()`. * */ self.defer = function(fn, delay) { var timeoutId; outstandingRequestCount++; timeoutId = setTimeout(function() { delete pendingDeferIds[timeoutId]; completeOutstandingRequest(fn); }, delay || 0); pendingDeferIds[timeoutId] = true; return timeoutId; }; /** * THIS DOC IS NOT VISIBLE because ngdocs can't process docs for foo#method.method * * @name angular.module.ng.$browser#defer.cancel * @methodOf angular.module.ng.$browser.defer * * @description * Cancels a defered task identified with `deferId`. * * @param {*} deferId Token returned by the `$browser.defer` function. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfuly canceled. */ self.defer.cancel = function(deferId) { if (pendingDeferIds[deferId]) { delete pendingDeferIds[deferId]; clearTimeout(deferId); completeOutstandingRequest(noop); return true; } return false; }; ////////////////////////////////////////////////////////////// // Misc API ////////////////////////////////////////////////////////////// /** * Returns current <base href> * (always relative - without domain) * * @returns {string=} */ self.baseHref = function() { var href = document.find('base').attr('href'); return href ? href.replace(/^https?\:\/\/[^\/]*/, '') : href; }; } function $BrowserProvider(){ this.$get = ['$window', '$log', '$sniffer', '$document', function( $window, $log, $sniffer, $document){ return new Browser($window, $document, $document.find('body'), $log, $sniffer); }]; } /** * @ngdoc object * @name angular.module.ng.$cacheFactory * * @description * Factory that constructs cache objects. * * * @param {string} cacheId Name or id of the newly created cache. * @param {object=} options Options object that specifies the cache behavior. Properties: * * - `{number=}` `capacity` — turns the cache into LRU cache. * * @returns {object} Newly created cache object with the following set of methods: * * - `{object}` `info()` — Returns id, size, and options of cache. * - `{void}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache. * - `{{*}} `get({string} key) — Returns cached value for `key` or undefined for cache miss. * - `{void}` `remove({string} key) — Removes a key-value pair from the cache. * - `{void}` `removeAll() — Removes all cached values. * - `{void}` `destroy() — Removes references to this cache from $cacheFactory. * */ function $CacheFactoryProvider() { this.$get = function() { var caches = {}; function cacheFactory(cacheId, options) { if (cacheId in caches) { throw Error('cacheId ' + cacheId + ' taken'); } var size = 0, stats = extend({}, options, {id: cacheId}), data = {}, capacity = (options && options.capacity) || Number.MAX_VALUE, lruHash = {}, freshEnd = null, staleEnd = null; return caches[cacheId] = { put: function(key, value) { var lruEntry = lruHash[key] || (lruHash[key] = {key: key}); refresh(lruEntry); if (isUndefined(value)) return; if (!(key in data)) size++; data[key] = value; if (size > capacity) { this.remove(staleEnd.key); } }, get: function(key) { var lruEntry = lruHash[key]; if (!lruEntry) return; refresh(lruEntry); return data[key]; }, remove: function(key) { var lruEntry = lruHash[key]; if (lruEntry == freshEnd) freshEnd = lruEntry.p; if (lruEntry == staleEnd) staleEnd = lruEntry.n; link(lruEntry.n,lruEntry.p); delete lruHash[key]; delete data[key]; size--; }, removeAll: function() { data = {}; size = 0; lruHash = {}; freshEnd = staleEnd = null; }, destroy: function() { data = null; stats = null; lruHash = null; delete caches[cacheId]; }, info: function() { return extend({}, stats, {size: size}); } }; /** * makes the `entry` the freshEnd of the LRU linked list */ function refresh(entry) { if (entry != freshEnd) { if (!staleEnd) { staleEnd = entry; } else if (staleEnd == entry) { staleEnd = entry.n; } link(entry.n, entry.p); link(entry, freshEnd); freshEnd = entry; freshEnd.n = null; } } /** * bidirectionally links two entries of the LRU linked list */ function link(nextEntry, prevEntry) { if (nextEntry != prevEntry) { if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify } } } cacheFactory.info = function() { var info = {}; forEach(caches, function(cache, cacheId) { info[cacheId] = cache.info(); }); return info; }; cacheFactory.get = function(cacheId) { return caches[cacheId]; }; return cacheFactory; }; } function $TemplateCacheProvider() { this.$get = ['$cacheFactory', function($cacheFactory) { return $cacheFactory('templates'); }]; } /** * @ngdoc function * @name angular.module.ng.$compile * @function * * @description * Compiles a piece of HTML string or DOM into a template and produces a template function, which * can then be used to link {@link angular.module.ng.$rootScope.Scope scope} and the template together. * * The compilation is a process of walking the DOM tree and trying to match DOM elements to * {@link angular.module.ng.$compileProvider.directive directives}. For each match it * executes corresponding template function and collects the * instance functions into a single template function which is then returned. * * The template function can then be used once to produce the view or as it is the case with * {@link angular.module.ng.$compileProvider.directive.ngRepeat repeater} many-times, in which * case each call results in a view that is a DOM clone of the original template. * <doc:example module="compile"> <doc:source> <script> // declare a new module, and inject the $compileProvider angular.module('compile', [], function($compileProvider) { // configure new 'compile' directive by passing a directive // factory function. The factory function injects the '$compile' $compileProvider.directive('compile', function($compile) { // directive factory creates a link function return function(scope, element, attrs) { scope.$watch( function(scope) { // watch the 'compile' expression for changes return scope.$eval(attrs.compile); }, function(value) { // when the 'compile' expression changes // assign it into the current DOM element.html(value); // compile the new DOM and link it to the current // scope. // NOTE: we only compile .childNodes so that // we don't get into infinite loop compiling ourselves $compile(element.contents())(scope); } ); }; }) }); function Ctrl($scope) { $scope.name = 'Angular'; $scope.html = 'Hello {{name}}'; } </script> <div ng-controller="Ctrl"> <input ng-model="name"> <br> <textarea ng-model="html"></textarea> <br> <div compile="html"></div> </div> </doc:source> <doc:scenario> it('should auto compile', function() { expect(element('div[compile]').text()).toBe('Hello Angular'); input('html').enter('{{name}}!'); expect(element('div[compile]').text()).toBe('Angular!'); }); </doc:scenario> </doc:example> * * * @param {string|DOMElement} element Element or HTML string to compile into a template function. * @param {function(angular.Scope[, cloneAttachFn]} transclude function available to directives. * @param {number} maxPriority only apply directives lower then given priority (Only effects the * root element(s), not their children) * @returns {function(scope[, cloneAttachFn])} a link function which is used to bind template * (a DOM element/tree) to a scope. Where: * * * `scope` - A {@link angular.module.ng.$rootScope.Scope Scope} to bind to. * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the * `template` and call the `cloneAttachFn` function allowing the caller to attach the * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is * called as: <br> `cloneAttachFn(clonedElement, scope)` where: * * * `clonedElement` - is a clone of the original `element` passed into the compiler. * * `scope` - is the current scope with which the linking function is working with. * * Calling the linking function returns the element of the template. It is either the original element * passed in, or the clone of the element if the `cloneAttachFn` is provided. * * After linking the view is not updated until after a call to $digest which typically is done by * Angular automatically. * * If you need access to the bound view, there are two ways to do it: * * - If you are not asking the linking function to clone the template, create the DOM element(s) * before you send them to the compiler and keep this reference around. * <pre> * var element = $compile('<p>{{total}}</p>')(scope); * </pre> * * - if on the other hand, you need the element to be cloned, the view reference from the original * example would not point to the clone, but rather to the original template that was cloned. In * this case, you can access the clone via the cloneAttachFn: * <pre> * var templateHTML = angular.element('<p>{{total}}</p>'), * scope = ....; * * var clonedElement = $compile(templateHTML)(scope, function(clonedElement, scope) { * //attach the clone to DOM document at the right place * }); * * //now we have reference to the cloned DOM via `clone` * </pre> * * * For information on how the compiler works, see the * {@link guide/dev_guide.compiler Angular HTML Compiler} section of the Developer Guide. */ $CompileProvider.$inject = ['$provide']; function $CompileProvider($provide) { var hasDirectives = {}, Suffix = 'Directive', COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\d\w\-_]+)\s+(.*)$/, CLASS_DIRECTIVE_REGEXP = /(([\d\w\-_]+)(?:\:([^;]+))?;?)/, CONTENT_REGEXP = /\<\<content\>\>/i, HAS_ROOT_ELEMENT = /^\<[\s\S]*\>$/; this.directive = function registerDirective(name, directiveFactory) { if (isString(name)) { assertArg(directiveFactory, 'directive'); if (!hasDirectives.hasOwnProperty(name)) { hasDirectives[name] = []; $provide.factory(name + Suffix, ['$injector', '$exceptionHandler', function($injector, $exceptionHandler) { var directives = []; forEach(hasDirectives[name], function(directiveFactory) { try { var directive = $injector.invoke(directiveFactory); if (isFunction(directive)) { directive = { compile: valueFn(directive) }; } else if (!directive.compile && directive.link) { directive.compile = valueFn(directive.link); } directive.priority = directive.priority || 0; directive.name = directive.name || name; directive.require = directive.require || (directive.controller && directive.name); directive.restrict = directive.restrict || 'A'; directives.push(directive); } catch (e) { $exceptionHandler(e); } }); return directives; }]); } hasDirectives[name].push(directiveFactory); } else { forEach(name, reverseParams(registerDirective)); } return this; }; this.$get = [ '$injector', '$interpolate', '$exceptionHandler', '$http', '$templateCache', '$parse', '$controller', function($injector, $interpolate, $exceptionHandler, $http, $templateCache, $parse, $controller) { var LOCAL_MODE = { attribute: function(localName, mode, parentScope, scope, attr) { scope[localName] = attr[localName]; }, evaluate: function(localName, mode, parentScope, scope, attr) { scope[localName] = parentScope.$eval(attr[localName]); }, bind: function(localName, mode, parentScope, scope, attr) { var getter = $interpolate(attr[localName]); scope.$watch( function() { return getter(parentScope); }, function(v) { scope[localName] = v; } ); }, accessor: function(localName, mode, parentScope, scope, attr) { var getter = noop, setter = noop, exp = attr[localName]; if (exp) { getter = $parse(exp); setter = getter.assign || function() { throw Error("Expression '" + exp + "' not assignable."); }; } scope[localName] = function(value) { return arguments.length ? setter(parentScope, value) : getter(parentScope); }; }, expression: function(localName, mode, parentScope, scope, attr) { scope[localName] = function(locals) { $parse(attr[localName])(parentScope, locals); }; } }; var Attributes = function(element, attr) { this.$$element = element; this.$$observers = {}; this.$attr = attr || {}; }; Attributes.prototype = { $normalize: directiveNormalize, /** * Set a normalized attribute on the element in a way such that all directives * can share the attribute. This function properly handles boolean attributes. * @param {string} key Normalized key. (ie ngAttribute) * @param {string|boolean} value The value to set. If `null` attribute will be deleted. * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute. * Defaults to true. * @param {string=} attrName Optional none normalized name. Defaults to key. */ $set: function(key, value, writeAttr, attrName) { var booleanKey = isBooleanAttr(this.$$element[0], key.toLowerCase()); if (booleanKey) { this.$$element.prop(key, value); attrName = booleanKey; } this[key] = value; // translate normalized key to actual key if (attrName) { this.$attr[key] = attrName; } else { attrName = this.$attr[key]; if (!attrName) { this.$attr[key] = attrName = snake_case(key, '-'); } } if (writeAttr !== false) { if (value === null || value === undefined) { this.$$element.removeAttr(attrName); } else { this.$$element.attr(attrName, value); } } // fire observers forEach(this.$$observers[key], function(fn) { try { fn(value); } catch (e) { $exceptionHandler(e); } }); }, /** * Observe an interpolated attribute. * The observer will never be called, if given attribute is not interpolated. * * @param {string} key Normalized key. (ie ngAttribute) . * @param {function(*)} fn Function that will be called whenever the attribute value changes. */ $observe: function(key, fn) { // keep only observers for interpolated attrs if (this.$$observers[key]) { this.$$observers[key].push(fn); } } }; return compile; //================================ function compile(templateElement, transcludeFn, maxPriority) { if (!(templateElement instanceof jqLite)) { // jquery always rewraps, where as we need to preserve the original selector so that we can modify it. templateElement = jqLite(templateElement); } // We can not compile top level text elements since text nodes can be merged and we will // not be able to attach scope data to them, so we will wrap them in <span> forEach(templateElement, function(node, index){ if (node.nodeType == 3 /* text node */) { templateElement[index] = jqLite(node).wrap('<span>').parent()[0]; } }); var linkingFn = compileNodes(templateElement, transcludeFn, templateElement, maxPriority); return function(scope, cloneConnectFn){ assertArg(scope, 'scope'); // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart // and sometimes changes the structure of the DOM. var element = cloneConnectFn ? JQLitePrototype.clone.call(templateElement) // IMPORTANT!!! : templateElement; safeAddClass(element.data('$scope', scope), 'ng-scope'); if (cloneConnectFn) cloneConnectFn(element, scope); if (linkingFn) linkingFn(scope, element, element); return element; }; } function wrongMode(localName, mode) { throw Error("Unsupported '" + mode + "' for '" + localName + "'."); } function safeAddClass(element, className) { try { element.addClass(className); } catch(e) { // ignore, since it means that we are trying to set class on // SVG element, where class name is read-only. } } /** * Compile function matches each node in nodeList against the directives. Once all directives * for a particular node are collected their compile functions are executed. The compile * functions return values - the linking functions - are combined into a composite linking * function, which is the a linking function for the node. * * @param {NodeList} nodeList an array of nodes to compile * @param {function(angular.Scope[, cloneAttachFn]} transcludeFn A linking function, where the * scope argument is auto-generated to the new child of the transcluded parent scope. * @param {DOMElement=} rootElement If the nodeList is the root of the compilation tree then the * rootElement must be set the jqLite collection of the compile root. This is * needed so that the jqLite collection items can be replaced with widgets. * @param {number=} max directive priority * @returns {?function} A composite linking function of all of the matched directives or null. */ function compileNodes(nodeList, transcludeFn, rootElement, maxPriority) { var linkingFns = [], directiveLinkingFn, childLinkingFn, directives, attrs, linkingFnFound; for(var i = 0; i < nodeList.length; i++) { attrs = new Attributes(); // we must always refer to nodeList[i] since the nodes can be replaced underneath us. directives = collectDirectives(nodeList[i], [], attrs, maxPriority); directiveLinkingFn = (directives.length) ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, rootElement) : null; childLinkingFn = (directiveLinkingFn && directiveLinkingFn.terminal) ? null : compileNodes(nodeList[i].childNodes, directiveLinkingFn ? directiveLinkingFn.transclude : transcludeFn); linkingFns.push(directiveLinkingFn); linkingFns.push(childLinkingFn); linkingFnFound = (linkingFnFound || directiveLinkingFn || childLinkingFn); } // return a linking function if we have found anything, null otherwise return linkingFnFound ? linkingFn : null; /* nodesetLinkingFn */ function linkingFn(scope, nodeList, rootElement, boundTranscludeFn) { var childLinkingFn, directiveLinkingFn, node, childScope, childTransclusionFn; for(var i=0, n=0, ii=linkingFns.length; i<ii; n++) { node = nodeList[n]; directiveLinkingFn = /* directiveLinkingFn */ linkingFns[i++]; childLinkingFn = /* nodesetLinkingFn */ linkingFns[i++]; if (directiveLinkingFn) { if (directiveLinkingFn.scope) { childScope = scope.$new(isObject(directiveLinkingFn.scope)); jqLite(node).data('$scope', childScope); } else { childScope = scope; } childTransclusionFn = directiveLinkingFn.transclude; if (childTransclusionFn || (!boundTranscludeFn && transcludeFn)) { directiveLinkingFn(childLinkingFn, childScope, node, rootElement, (function(transcludeFn) { return function(cloneFn) { var transcludeScope = scope.$new(); return transcludeFn(transcludeScope, cloneFn). bind('$destroy', bind(transcludeScope, transcludeScope.$destroy)); }; })(childTransclusionFn || transcludeFn) ); } else { directiveLinkingFn(childLinkingFn, childScope, node, undefined, boundTranscludeFn); } } else if (childLinkingFn) { childLinkingFn(scope, node.childNodes, undefined, boundTranscludeFn); } } } } /** * Looks for directives on the given node ands them to the directive collection which is sorted. * * @param node node to search * @param directives an array to which the directives are added to. This array is sorted before * the function returns. * @param attrs the shared attrs object which is used to populate the normalized attributes. * @param {number=} max directive priority */ function collectDirectives(node, directives, attrs, maxPriority) { var nodeType = node.nodeType, attrsMap = attrs.$attr, match, className; switch(nodeType) { case 1: /* Element */ // use the node name: <directive> addDirective(directives, directiveNormalize(nodeName_(node).toLowerCase()), 'E', maxPriority); // iterate over the attributes for (var attr, name, nName, value, nAttrs = node.attributes, j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) { attr = nAttrs[j]; if (attr.specified) { name = attr.name; nName = directiveNormalize(name.toLowerCase()); attrsMap[nName] = name; attrs[nName] = value = trim((msie && name == 'href') ? decodeURIComponent(node.getAttribute(name, 2)) : attr.value); if (isBooleanAttr(node, nName)) { attrs[nName] = true; // presence means true } addAttrInterpolateDirective(node, directives, value, nName); addDirective(directives, nName, 'A', maxPriority); } } // use class as directive className = node.className; if (isString(className)) { while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) { nName = directiveNormalize(match[2]); if (addDirective(directives, nName, 'C', maxPriority)) { attrs[nName] = trim(match[3]); } className = className.substr(match.index + match[0].length); } } break; case 3: /* Text Node */ addTextInterpolateDirective(directives, node.nodeValue); break; case 8: /* Comment */ try { match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue); if (match) { nName = directiveNormalize(match[1]); if (addDirective(directives, nName, 'M', maxPriority)) { attrs[nName] = trim(match[2]); } } } catch (e) { // turns out that under some circumstances IE9 throws errors when one attempts to read comment's node value. // Just ignore it and continue. (Can't seem to reproduce in test case.) } break; } directives.sort(byPriority); return directives; } /** * Once the directives have been collected their compile functions is executed. This method * is responsible for inlining directive templates as well as terminating the application * of the directives if the terminal directive has been reached.. * * @param {Array} directives Array of collected directives to execute their compile function. * this needs to be pre-sorted by priority order. * @param {Node} templateNode The raw DOM node to apply the compile functions to * @param {Object} templateAttrs The shared attribute function * @param {function(angular.Scope[, cloneAttachFn]} transcludeFn A linking function, where the * scope argument is auto-generated to the new child of the transcluded parent scope. * @param {DOMElement} rootElement If we are working on the root of the compile tree then this * argument has the root jqLite array so that we can replace widgets on it. * @returns linkingFn */ function applyDirectivesToNode(directives, templateNode, templateAttrs, transcludeFn, rootElement) { var terminalPriority = -Number.MAX_VALUE, preLinkingFns = [], postLinkingFns = [], newScopeDirective = null, newIsolatedScopeDirective = null, templateDirective = null, delayedLinkingFn = null, element = templateAttrs.$$element = jqLite(templateNode), directive, directiveName, template, transcludeDirective, childTranscludeFn = transcludeFn, controllerDirectives, linkingFn, directiveValue; // executes all directives on the current element for(var i = 0, ii = directives.length; i < ii; i++) { directive = directives[i]; template = undefined; if (terminalPriority > directive.priority) { break; // prevent further processing of directives } if (directiveValue = directive.scope) { assertNoDuplicate('isolated scope', newIsolatedScopeDirective, directive, element); if (isObject(directiveValue)) { safeAddClass(element, 'ng-isolate-scope'); newIsolatedScopeDirective = directive; } safeAddClass(element, 'ng-scope'); newScopeDirective = newScopeDirective || directive; } directiveName = directive.name; if (directiveValue = directive.controller) { controllerDirectives = controllerDirectives || {}; assertNoDuplicate("'" + directiveName + "' controller", controllerDirectives[directiveName], directive, element); controllerDirectives[directiveName] = directive; } if (directiveValue = directive.transclude) { assertNoDuplicate('transclusion', transcludeDirective, directive, element); transcludeDirective = directive; terminalPriority = directive.priority; if (directiveValue == 'element') { template = jqLite(templateNode); templateNode = (element = templateAttrs.$$element = jqLite( '<!-- ' + directiveName + ': ' + templateAttrs[directiveName] + ' -->'))[0]; replaceWith(rootElement, jqLite(template[0]), templateNode); childTranscludeFn = compile(template, transcludeFn, terminalPriority); } else { template = jqLite(JQLiteClone(templateNode)); element.html(''); // clear contents childTranscludeFn = compile(template.contents(), transcludeFn); } } if (directiveValue = directive.template) { assertNoDuplicate('template', templateDirective, directive, element); templateDirective = directive; // include the contents of the original element into the template and replace the element var content = directiveValue.replace(CONTENT_REGEXP, element.html()); templateNode = jqLite(content)[0]; if (directive.replace) { replaceWith(rootElement, element, templateNode); var newTemplateAttrs = {$attr: {}}; // combine directives from the original node and from the template: // - take the array of directives for this element // - split it into two parts, those that were already applied and those that weren't // - collect directives from the template, add them to the second group and sort them // - append the second group with new directives to the first group directives = directives.concat( collectDirectives( templateNode, directives.splice(i + 1, directives.length - (i + 1)), newTemplateAttrs ) ); mergeTemplateAttributes(templateAttrs, newTemplateAttrs); ii = directives.length; } else { element.html(content); } } if (directive.templateUrl) { assertNoDuplicate('template', templateDirective, directive, element); templateDirective = directive; delayedLinkingFn = compileTemplateUrl(directives.splice(i, directives.length - i), /* directiveLinkingFn */ compositeLinkFn, element, templateAttrs, rootElement, directive.replace, childTranscludeFn); ii = directives.length; } else if (directive.compile) { try { linkingFn = directive.compile(element, templateAttrs, childTranscludeFn); if (isFunction(linkingFn)) { addLinkingFns(null, linkingFn); } else if (linkingFn) { addLinkingFns(linkingFn.pre, linkingFn.post); } } catch (e) { $exceptionHandler(e, startingTag(element)); } } if (directive.terminal) { compositeLinkFn.terminal = true; terminalPriority = Math.max(terminalPriority, directive.priority); } } linkingFn = delayedLinkingFn || compositeLinkFn; linkingFn.scope = newScopeDirective && newScopeDirective.scope; linkingFn.transclude = transcludeDirective && childTranscludeFn; // if we have templateUrl, then we have to delay linking return linkingFn; //////////////////// function addLinkingFns(pre, post) { if (pre) { pre.require = directive.require; preLinkingFns.push(pre); } if (post) { post.require = directive.require; postLinkingFns.push(post); } } function getControllers(require, element) { var value, retrievalMethod = 'data', optional = false; if (isString(require)) { while((value = require.charAt(0)) == '^' || value == '?') { require = require.substr(1); if (value == '^') { retrievalMethod = 'inheritedData'; } optional = optional || value == '?'; } value = element[retrievalMethod]('$' + require + 'Controller'); if (!value && !optional) { throw Error("No controller: " + require); } return value; } else if (isArray(require)) { value = []; forEach(require, function(require) { value.push(getControllers(require, element)); }); } return value; } /* directiveLinkingFn */ function compositeLinkFn(/* nodesetLinkingFn */ childLinkingFn, scope, linkNode, rootElement, boundTranscludeFn) { var attrs, element, i, ii, linkingFn, controller; if (templateNode === linkNode) { attrs = templateAttrs; } else { attrs = shallowCopy(templateAttrs, new Attributes(jqLite(linkNode), templateAttrs.$attr)); } element = attrs.$$element; if (newScopeDirective && isObject(newScopeDirective.scope)) { forEach(newScopeDirective.scope, function(mode, name) { (LOCAL_MODE[mode] || wrongMode)(name, mode, scope.$parent || scope, scope, attrs); }); } if (controllerDirectives) { forEach(controllerDirectives, function(directive) { var locals = { $scope: scope, $element: element, $attrs: attrs, $transclude: boundTranscludeFn }; forEach(directive.inject || {}, function(mode, name) { (LOCAL_MODE[mode] || wrongMode)(name, mode, newScopeDirective ? scope.$parent || scope : scope, locals, attrs); }); controller = directive.controller; if (controller == '@') { controller = attrs[directive.name]; } element.data( '$' + directive.name + 'Controller', $controller(controller, locals)); }); } // PRELINKING for(i = 0, ii = preLinkingFns.length; i < ii; i++) { try { linkingFn = preLinkingFns[i]; linkingFn(scope, element, attrs, linkingFn.require && getControllers(linkingFn.require, element)); } catch (e) { $exceptionHandler(e, startingTag(element)); } } // RECURSION childLinkingFn && childLinkingFn(scope, linkNode.childNodes, undefined, boundTranscludeFn); // POSTLINKING for(i = 0, ii = postLinkingFns.length; i < ii; i++) { try { linkingFn = postLinkingFns[i]; linkingFn(scope, element, attrs, linkingFn.require && getControllers(linkingFn.require, element)); } catch (e) { $exceptionHandler(e, startingTag(element)); } } } } /** * looks up the directive and decorates it with exception handling and proper parameters. We * call this the boundDirective. * * @param {string} name name of the directive to look up. * @param {string} location The directive must be found in specific format. * String containing any of theses characters: * * * `E`: element name * * `A': attribute * * `C`: class * * `M`: comment * @returns true if directive was added. */ function addDirective(tDirectives, name, location, maxPriority) { var match = false; if (hasDirectives.hasOwnProperty(name)) { for(var directive, directives = $injector.get(name + Suffix), i=0, ii = directives.length; i<ii; i++) { try { directive = directives[i]; if ( (maxPriority === undefined || maxPriority > directive.priority) && directive.restrict.indexOf(location) != -1) { tDirectives.push(directive); match = true; } } catch(e) { $exceptionHandler(e); } } } return match; } /** * When the element is replaced with HTML template then the new attributes * on the template need to be merged with the existing attributes in the DOM. * The desired effect is to have both of the attributes present. * * @param {object} dst destination attributes (original DOM) * @param {object} src source attributes (from the directive template) */ function mergeTemplateAttributes(dst, src) { var srcAttr = src.$attr, dstAttr = dst.$attr, element = dst.$$element; // reapply the old attributes to the new element forEach(dst, function(value, key) { if (key.charAt(0) != '$') { if (src[key]) { value += (key === 'style' ? ';' : ' ') + src[key]; } dst.$set(key, value, true, srcAttr[key]); } }); // copy the new attributes on the old attrs object forEach(src, function(value, key) { if (key == 'class') { safeAddClass(element, value); } else if (key == 'style') { element.attr('style', element.attr('style') + ';' + value); } else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) { dst[key] = value; dstAttr[key] = srcAttr[key]; } }); } function compileTemplateUrl(directives, /* directiveLinkingFn */ beforeWidgetLinkFn, tElement, tAttrs, rootElement, replace, transcludeFn) { var linkQueue = [], afterWidgetLinkFn, afterWidgetChildrenLinkFn, originalWidgetNode = tElement[0], asyncWidgetDirective = directives.shift(), // The fact that we have to copy and patch the directive seems wrong! syncWidgetDirective = extend({}, asyncWidgetDirective, {templateUrl:null, transclude:null}), html = tElement.html(); tElement.html(''); $http.get(asyncWidgetDirective.templateUrl, {cache: $templateCache}). success(function(content) { content = trim(content).replace(CONTENT_REGEXP, html); if (replace && !content.match(HAS_ROOT_ELEMENT)) { throw Error('Template must have exactly one root element: ' + content); } var templateNode, tempTemplateAttrs; if (replace) { tempTemplateAttrs = {$attr: {}}; templateNode = jqLite(content)[0]; replaceWith(rootElement, tElement, templateNode); collectDirectives(tElement[0], directives, tempTemplateAttrs); mergeTemplateAttributes(tAttrs, tempTemplateAttrs); } else { templateNode = tElement[0]; tElement.html(content); } directives.unshift(syncWidgetDirective); afterWidgetLinkFn = /* directiveLinkingFn */ applyDirectivesToNode(directives, tElement, tAttrs, transcludeFn); afterWidgetChildrenLinkFn = /* nodesetLinkingFn */ compileNodes(tElement.contents(), transcludeFn); while(linkQueue.length) { var controller = linkQueue.pop(), linkRootElement = linkQueue.pop(), cLinkNode = linkQueue.pop(), scope = linkQueue.pop(), node = templateNode; if (cLinkNode !== originalWidgetNode) { // it was cloned therefore we have to clone as well. node = JQLiteClone(templateNode); replaceWith(linkRootElement, jqLite(cLinkNode), node); } afterWidgetLinkFn(function() { beforeWidgetLinkFn(afterWidgetChildrenLinkFn, scope, node, rootElement, controller); }, scope, node, rootElement, controller); } linkQueue = null; }). error(function(response, code, headers, config) { throw Error('Failed to load template: ' + config.url); }); return /* directiveLinkingFn */ function(ignoreChildLinkingFn, scope, node, rootElement, controller) { if (linkQueue) { linkQueue.push(scope); linkQueue.push(node); linkQueue.push(rootElement); linkQueue.push(controller); } else { afterWidgetLinkFn(function() { beforeWidgetLinkFn(afterWidgetChildrenLinkFn, scope, node, rootElement, controller); }, scope, node, rootElement, controller); } }; } /** * Sorting function for bound directives. */ function byPriority(a, b) { return b.priority - a.priority; } function assertNoDuplicate(what, previousDirective, directive, element) { if (previousDirective) { throw Error('Multiple directives [' + previousDirective.name + ', ' + directive.name + '] asking for ' + what + ' on: ' + startingTag(element)); } } function addTextInterpolateDirective(directives, text) { var interpolateFn = $interpolate(text, true); if (interpolateFn) { directives.push({ priority: 0, compile: valueFn(function(scope, node) { var parent = node.parent(), bindings = parent.data('$binding') || []; bindings.push(interpolateFn); safeAddClass(parent.data('$binding', bindings), 'ng-binding'); scope.$watch(interpolateFn, function(value) { node[0].nodeValue = value; }); }) }); } } function addAttrInterpolateDirective(node, directives, value, name) { var interpolateFn = $interpolate(value, true); // no interpolation found -> ignore if (!interpolateFn) return; directives.push({ priority: 100, compile: valueFn(function(scope, element, attr) { if (name === 'class') { // we need to interpolate classes again, in the case the element was replaced // and therefore the two class attrs got merged - we want to interpolate the result interpolateFn = $interpolate(attr[name], true); } // we define observers array only for interpolated attrs // and ignore observers for non interpolated attrs to save some memory attr.$$observers[name] = []; attr[name] = undefined; scope.$watch(interpolateFn, function(value) { attr.$set(name, value); }); }) }); } /** * This is a special jqLite.replaceWith, which can replace items which * have no parents, provided that the containing jqLite collection is provided. * * @param {JqLite=} rootElement The root of the compile tree. Used so that we can replace nodes * in the root of the tree. * @param {JqLite} element The jqLite element which we are going to replace. We keep the shell, * but replace its DOM node reference. * @param {Node} newNode The new DOM node. */ function replaceWith(rootElement, element, newNode) { var oldNode = element[0], parent = oldNode.parentNode, i, ii; if (rootElement) { for(i = 0, ii = rootElement.length; i<ii; i++) { if (rootElement[i] == oldNode) { rootElement[i] = newNode; } } } if (parent) { parent.replaceChild(newNode, oldNode); } element[0] = newNode; } }]; } var PREFIX_REGEXP = /^(x[\:\-_]|data[\:\-_])/i; /** * Converts all accepted directives format into proper directive name. * All of these will become 'myDirective': * my:DiRective * my-directive * x-my-directive * data-my:directive * * Also there is special case for Moz prefix starting with upper case letter. * @param name Name to normalize */ function directiveNormalize(name) { return camelCase(name.replace(PREFIX_REGEXP, '')); } /** * Closure compiler type information */ function nodesetLinkingFn( /* angular.Scope */ scope, /* NodeList */ nodeList, /* Element */ rootElement, /* function(Function) */ boundTranscludeFn ){} function directiveLinkingFn( /* nodesetLinkingFn */ nodesetLinkingFn, /* angular.Scope */ scope, /* Node */ node, /* Element */ rootElement, /* function(Function) */ boundTranscludeFn ){} /** * @ngdoc object * @name angular.module.ng.$controllerProvider * @description * The {@link angular.module.ng.$controller $controller service} is used by Angular to create new * controllers. * * This provider allows controller registration via the * {@link angular.module.ng.$controllerProvider#register register} method. */ function $ControllerProvider() { var controllers = {}; /** * @ngdoc function * @name angular.module.ng.$controllerProvider#register * @methodOf angular.module.ng.$controllerProvider * @param {string} name Controller name * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI * annotations in the array notation). */ this.register = function(name, constructor) { controllers[name] = constructor; }; this.$get = ['$injector', '$window', function($injector, $window) { /** * @ngdoc function * @name angular.module.ng.$controller * @requires $injector * * @param {Function|string} constructor If called with a function then it's considered to be the * controller constructor function. Otherwise it's considered to be a string which is used * to retrieve the controller constructor using the following steps: * * * check if a controller with given name is registered via `$controllerProvider` * * check if evaluating the string on the current scope returns a constructor * * check `window[constructor]` on the global `window` object * * @param {Object} locals Injection locals for Controller. * @return {Object} Instance of given controller. * * @description * `$controller` service is responsible for instantiating controllers. * * It's just simple call to {@link angular.module.AUTO.$injector $injector}, but extracted into * a service, so that one can override this service with {@link https://gist.github.com/1649788 * BC version}. */ return function(constructor, locals) { if(isString(constructor)) { var name = constructor; constructor = controllers.hasOwnProperty(name) ? controllers[name] : getter(locals.$scope, name, true) || getter($window, name, true); assertArgFn(constructor, name, true); } return $injector.instantiate(constructor, locals); }; }]; } /** * @ngdoc function * @name angular.module.ng.$defer * @requires $browser * * @description * Delegates to {@link angular.module.ng.$browser#defer $browser.defer}, but wraps the `fn` function * into a try/catch block and delegates any exceptions to * {@link angular.module.ng.$exceptionHandler $exceptionHandler} service. * * In tests you can use `$browser.defer.flush()` to flush the queue of deferred functions. * * @param {function()} fn A function, who's execution should be deferred. * @param {number=} [delay=0] of milliseconds to defer the function execution. * @returns {*} DeferId that can be used to cancel the task via `$defer.cancel()`. */ /** * @ngdoc function * @name angular.module.ng.$defer#cancel * @methodOf angular.module.ng.$defer * * @description * Cancels a defered task identified with `deferId`. * * @param {*} deferId Token returned by the `$defer` function. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfuly canceled. */ function $DeferProvider(){ this.$get = ['$rootScope', '$browser', function($rootScope, $browser) { function defer(fn, delay) { return $browser.defer(function() { $rootScope.$apply(fn); }, delay); } defer.cancel = function(deferId) { return $browser.defer.cancel(deferId); }; return defer; }]; } /** * @ngdoc object * @name angular.module.ng.$document * @requires $window * * @description * A {@link angular.element jQuery (lite)}-wrapped reference to the browser's `window.document` * element. */ function $DocumentProvider(){ this.$get = ['$window', function(window){ return jqLite(window.document); }]; } /** * @ngdoc function * @name angular.module.ng.$exceptionHandler * @requires $log * * @description * Any uncaught exception in angular expressions is delegated to this service. * The default implementation simply delegates to `$log.error` which logs it into * the browser console. * * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by * {@link angular.module.ngMock.$exceptionHandler mock $exceptionHandler} * * @param {Error} exception Exception associated with the error. * @param {string=} cause optional information about the context in which * the error was thrown. */ function $ExceptionHandlerProvider() { this.$get = ['$log', function($log){ return function(exception, cause) { $log.error.apply($log, arguments); }; }]; } /** * @ngdoc function * @name angular.module.ng.$interpolateProvider * @function * * @description * * Used for configuring the interpolation markup. Deafults to `{{` and `}}`. */ function $InterpolateProvider() { var startSymbol = '{{'; var endSymbol = '}}'; /** * @ngdoc method * @name angular.module.ng.$interpolateProvider#startSymbol * @methodOf angular.module.ng.$interpolateProvider * @description * Symbol to denote start of expression in the interpolated string. Defaults to `{{`. * * @prop {string=} value new value to set the starting symbol to. */ this.startSymbol = function(value){ if (value) { startSymbol = value; return this; } else { return startSymbol; } }; /** * @ngdoc method * @name angular.module.ng.$interpolateProvider#endSymbol * @methodOf angular.module.ng.$interpolateProvider * @description * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`. * * @prop {string=} value new value to set the ending symbol to. */ this.endSymbol = function(value){ if (value) { endSymbol = value; return this; } else { return startSymbol; } }; this.$get = ['$parse', function($parse) { var startSymbolLength = startSymbol.length, endSymbolLength = endSymbol.length; /** * @ngdoc function * @name angular.module.ng.$interpolate * @function * * @requires $parse * * @description * * Compiles a string with markup into an interpolation function. This service is used by the * HTML {@link angular.module.ng.$compile $compile} service for data binding. See * {@link angular.module.ng.$interpolateProvider $interpolateProvider} for configuring the * interpolation markup. * * <pre> var $interpolate = ...; // injected var exp = $interpolate('Hello {{name}}!'); expect(exp({name:'Angular'}).toEqual('Hello Angular!'); </pre> * * * @param {string} text The text with markup to interpolate. * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have * embedded expression in order to return an interpolation function. Strings with no * embedded expression will return null for the interpolation function. * @returns {function(context)} an interpolation function which is used to compute the interpolated * string. The function has these parameters: * * * `context`: an object against which any expressions embedded in the strings are evaluated * against. * */ return function(text, mustHaveExpression) { var startIndex, endIndex, index = 0, parts = [], length = text.length, hasInterpolation = false, fn, exp, concat = []; while(index < length) { if ( ((startIndex = text.indexOf(startSymbol, index)) != -1) && ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1) ) { (index != startIndex) && parts.push(text.substring(index, startIndex)); parts.push(fn = $parse(exp = text.substring(startIndex + startSymbolLength, endIndex))); fn.exp = exp; index = endIndex + endSymbolLength; hasInterpolation = true; } else { // we did not find anything, so we have to add the remainder to the parts array (index != length) && parts.push(text.substring(index)); index = length; } } if (!(length = parts.length)) { // we added, nothing, must have been an empty string. parts.push(''); length = 1; } if (!mustHaveExpression || hasInterpolation) { concat.length = length; fn = function(context) { for(var i = 0, ii = length, part; i<ii; i++) { if (typeof (part = parts[i]) == 'function') { part = part(context); if (part == null || part == undefined) { part = ''; } else if (typeof part != 'string') { part = toJson(part); } } concat[i] = part; } return concat.join(''); }; fn.exp = text; fn.parts = parts; return fn; } }; }]; } var URL_MATCH = /^(file|ftp|http|https):\/\/(\w+:{0,1}\w*@)?([\w\.-]*)(:([0-9]+))?(\/[^\?#]*)?(\?([^#]*))?(#(.*))?$/, PATH_MATCH = /^([^\?#]*)?(\?([^#]*))?(#(.*))?$/, HASH_MATCH = PATH_MATCH, DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21}; /** * Encode path using encodeUriSegment, ignoring forward slashes * * @param {string} path Path to encode * @returns {string} */ function encodePath(path) { var segments = path.split('/'), i = segments.length; while (i--) { segments[i] = encodeUriSegment(segments[i]); } return segments.join('/'); } function matchUrl(url, obj) { var match = URL_MATCH.exec(url); match = { protocol: match[1], host: match[3], port: int(match[5]) || DEFAULT_PORTS[match[1]] || null, path: match[6] || '/', search: match[8], hash: match[10] }; if (obj) { obj.$$protocol = match.protocol; obj.$$host = match.host; obj.$$port = match.port; } return match; } function composeProtocolHostPort(protocol, host, port) { return protocol + '://' + host + (port == DEFAULT_PORTS[protocol] ? '' : ':' + port); } function pathPrefixFromBase(basePath) { return basePath.substr(0, basePath.lastIndexOf('/')); } function convertToHtml5Url(url, basePath, hashPrefix) { var match = matchUrl(url); // already html5 url if (decodeURIComponent(match.path) != basePath || isUndefined(match.hash) || match.hash.indexOf(hashPrefix) !== 0) { return url; // convert hashbang url -> html5 url } else { return composeProtocolHostPort(match.protocol, match.host, match.port) + pathPrefixFromBase(basePath) + match.hash.substr(hashPrefix.length); } } function convertToHashbangUrl(url, basePath, hashPrefix) { var match = matchUrl(url); // already hashbang url if (decodeURIComponent(match.path) == basePath) { return url; // convert html5 url -> hashbang url } else { var search = match.search && '?' + match.search || '', hash = match.hash && '#' + match.hash || '', pathPrefix = pathPrefixFromBase(basePath), path = match.path.substr(pathPrefix.length); if (match.path.indexOf(pathPrefix) !== 0) { throw 'Invalid url "' + url + '", missing path prefix "' + pathPrefix + '" !'; } return composeProtocolHostPort(match.protocol, match.host, match.port) + basePath + '#' + hashPrefix + path + search + hash; } } /** * LocationUrl represents an url * This object is exposed as $location service when HTML5 mode is enabled and supported * * @constructor * @param {string} url HTML5 url * @param {string} pathPrefix */ function LocationUrl(url, pathPrefix) { pathPrefix = pathPrefix || ''; /** * Parse given html5 (regular) url string into properties * @param {string} url HTML5 url * @private */ this.$$parse = function(url) { var match = matchUrl(url, this); if (match.path.indexOf(pathPrefix) !== 0) { throw 'Invalid url "' + url + '", missing path prefix "' + pathPrefix + '" !'; } this.$$path = decodeURIComponent(match.path.substr(pathPrefix.length)); this.$$search = parseKeyValue(match.search); this.$$hash = match.hash && decodeURIComponent(match.hash) || ''; this.$$compose(); }; /** * Compose url and update `absUrl` property * @private */ this.$$compose = function() { var search = toKeyValue(this.$$search), hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : ''; this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash; this.$$absUrl = composeProtocolHostPort(this.$$protocol, this.$$host, this.$$port) + pathPrefix + this.$$url; }; this.$$parse(url); } /** * LocationHashbangUrl represents url * This object is exposed as $location service when html5 history api is disabled or not supported * * @constructor * @param {string} url Legacy url * @param {string} hashPrefix Prefix for hash part (containing path and search) */ function LocationHashbangUrl(url, hashPrefix) { var basePath; /** * Parse given hashbang url into properties * @param {string} url Hashbang url * @private */ this.$$parse = function(url) { var match = matchUrl(url, this); if (match.hash && match.hash.indexOf(hashPrefix) !== 0) { throw 'Invalid url "' + url + '", missing hash prefix "' + hashPrefix + '" !'; } basePath = match.path + (match.search ? '?' + match.search : ''); match = HASH_MATCH.exec((match.hash || '').substr(hashPrefix.length)); if (match[1]) { this.$$path = (match[1].charAt(0) == '/' ? '' : '/') + decodeURIComponent(match[1]); } else { this.$$path = ''; } this.$$search = parseKeyValue(match[3]); this.$$hash = match[5] && decodeURIComponent(match[5]) || ''; this.$$compose(); }; /** * Compose hashbang url and update `absUrl` property * @private */ this.$$compose = function() { var search = toKeyValue(this.$$search), hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : ''; this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash; this.$$absUrl = composeProtocolHostPort(this.$$protocol, this.$$host, this.$$port) + basePath + (this.$$url ? '#' + hashPrefix + this.$$url : ''); }; this.$$parse(url); } LocationUrl.prototype = { /** * Has any change been replacing ? * @private */ $$replace: false, /** * @ngdoc method * @name angular.module.ng.$location#absUrl * @methodOf angular.module.ng.$location * * @description * This method is getter only. * * Return full url representation with all segments encoded according to rules specified in * {@link http://www.ietf.org/rfc/rfc3986.txt RFC 3986}. * * @return {string} */ absUrl: locationGetter('$$absUrl'), /** * @ngdoc method * @name angular.module.ng.$location#url * @methodOf angular.module.ng.$location * * @description * This method is getter / setter. * * Return url (e.g. `/path?a=b#hash`) when called without any parameter. * * Change path, search and hash, when called with parameter and return `$location`. * * @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`) * @return {string} */ url: function(url, replace) { if (isUndefined(url)) return this.$$url; var match = PATH_MATCH.exec(url); if (match[1]) this.path(decodeURIComponent(match[1])); if (match[2] || match[1]) this.search(match[3] || ''); this.hash(match[5] || '', replace); return this; }, /** * @ngdoc method * @name angular.module.ng.$location#protocol * @methodOf angular.module.ng.$location * * @description * This method is getter only. * * Return protocol of current url. * * @return {string} */ protocol: locationGetter('$$protocol'), /** * @ngdoc method * @name angular.module.ng.$location#host * @methodOf angular.module.ng.$location * * @description * This method is getter only. * * Return host of current url. * * @return {string} */ host: locationGetter('$$host'), /** * @ngdoc method * @name angular.module.ng.$location#port * @methodOf angular.module.ng.$location * * @description * This method is getter only. * * Return port of current url. * * @return {Number} */ port: locationGetter('$$port'), /** * @ngdoc method * @name angular.module.ng.$location#path * @methodOf angular.module.ng.$location * * @description * This method is getter / setter. * * Return path of current url when called without any parameter. * * Change path when called with parameter and return `$location`. * * Note: Path should always begin with forward slash (/), this method will add the forward slash * if it is missing. * * @param {string=} path New path * @return {string} */ path: locationGetterSetter('$$path', function(path) { return path.charAt(0) == '/' ? path : '/' + path; }), /** * @ngdoc method * @name angular.module.ng.$location#search * @methodOf angular.module.ng.$location * * @description * This method is getter / setter. * * Return search part (as object) of current url when called without any parameter. * * Change search part when called with parameter and return `$location`. * * @param {string|object<string,string>=} search New search params - string or hash object * @param {string=} paramValue If `search` is a string, then `paramValue` will override only a * single search parameter. If the value is `null`, the parameter will be deleted. * * @return {string} */ search: function(search, paramValue) { if (isUndefined(search)) return this.$$search; if (isDefined(paramValue)) { if (paramValue === null) { delete this.$$search[search]; } else { this.$$search[search] = paramValue; } } else { this.$$search = isString(search) ? parseKeyValue(search) : search; } this.$$compose(); return this; }, /** * @ngdoc method * @name angular.module.ng.$location#hash * @methodOf angular.module.ng.$location * * @description * This method is getter / setter. * * Return hash fragment when called without any parameter. * * Change hash fragment when called with parameter and return `$location`. * * @param {string=} hash New hash fragment * @return {string} */ hash: locationGetterSetter('$$hash', identity), /** * @ngdoc method * @name angular.module.ng.$location#replace * @methodOf angular.module.ng.$location * * @description * If called, all changes to $location during current `$digest` will be replacing current history * record, instead of adding new one. */ replace: function() { this.$$replace = true; return this; } }; LocationHashbangUrl.prototype = inherit(LocationUrl.prototype); function locationGetter(property) { return function() { return this[property]; }; } function locationGetterSetter(property, preprocess) { return function(value) { if (isUndefined(value)) return this[property]; this[property] = preprocess(value); this.$$compose(); return this; }; } /** * @ngdoc object * @name angular.module.ng.$location * * @requires $browser * @requires $sniffer * @requires $document * * @description * The $location service parses the URL in the browser address bar (based on the {@link https://developer.mozilla.org/en/window.location window.location}) and makes the URL available to your application. Changes to the URL in the address bar are reflected into $location service and changes to $location are reflected into the browser address bar. * * **The $location service:** * * - Exposes the current URL in the browser address bar, so you can * - Watch and observe the URL. * - Change the URL. * - Synchronizes the URL with the browser when the user * - Changes the address bar. * - Clicks the back or forward button (or clicks a History link). * - Clicks on a link. * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash). * * For more information see {@link guide/dev_guide.services.$location Developer Guide: Angular Services: Using $location} */ /** * @ngdoc object * @name angular.module.ng.$locationProvider * @description * Use the `$locationProvider` to configure how the application deep linking paths are stored. */ function $LocationProvider(){ var hashPrefix = '', html5Mode = false; /** * @ngdoc property * @name angular.module.ng.$locationProvider#hashPrefix * @methodOf angular.module.ng.$locationProvider * @description * @param {string=} prefix Prefix for hash part (containing path and search) * @returns {*} current value if used as getter or itself (chaining) if used as setter */ this.hashPrefix = function(prefix) { if (isDefined(prefix)) { hashPrefix = prefix; return this; } else { return hashPrefix; } }; /** * @ngdoc property * @name angular.module.ng.$locationProvider#html5Mode * @methodOf angular.module.ng.$locationProvider * @description * @param {string=} mode Use HTML5 strategy if available. * @returns {*} current value if used as getter or itself (chaining) if used as setter */ this.html5Mode = function(mode) { if (isDefined(mode)) { html5Mode = mode; return this; } else { return html5Mode; } }; this.$get = ['$rootScope', '$browser', '$sniffer', '$document', function( $rootScope, $browser, $sniffer, $document) { var currentUrl, basePath = $browser.baseHref() || '/', pathPrefix = pathPrefixFromBase(basePath), initUrl = $browser.url(); if (html5Mode) { if ($sniffer.history) { currentUrl = new LocationUrl(convertToHtml5Url(initUrl, basePath, hashPrefix), pathPrefix); } else { currentUrl = new LocationHashbangUrl(convertToHashbangUrl(initUrl, basePath, hashPrefix), hashPrefix); } // link rewriting var u = currentUrl, absUrlPrefix = composeProtocolHostPort(u.protocol(), u.host(), u.port()) + pathPrefix; $document.bind('click', function(event) { // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser) // currently we open nice url link and redirect then if (event.ctrlKey || event.metaKey || event.which == 2) return; var elm = jqLite(event.target); // traverse the DOM up to find first A tag while (elm.length && lowercase(elm[0].nodeName) !== 'a') { elm = elm.parent(); } var absHref = elm.prop('href'); if (!absHref || elm.attr('target') || absHref.indexOf(absUrlPrefix) !== 0) { // link to different domain or base path return; } // update location with href without the prefix currentUrl.url(absHref.substr(absUrlPrefix.length)); $rootScope.$apply(); event.preventDefault(); // hack to work around FF6 bug 684208 when scenario runner clicks on links window.angular['ff-684208-preventDefault'] = true; }); } else { currentUrl = new LocationHashbangUrl(initUrl, hashPrefix); } // rewrite hashbang url <> html5 url if (currentUrl.absUrl() != initUrl) { $browser.url(currentUrl.absUrl(), true); } // update $location when $browser url changes $browser.onUrlChange(function(newUrl) { if (currentUrl.absUrl() != newUrl) { $rootScope.$evalAsync(function() { currentUrl.$$parse(newUrl); }); if (!$rootScope.$$phase) $rootScope.$digest(); } }); // update browser var changeCounter = 0; $rootScope.$watch(function $locationWatch() { if ($browser.url() != currentUrl.absUrl()) { changeCounter++; $rootScope.$evalAsync(function() { $browser.url(currentUrl.absUrl(), currentUrl.$$replace); currentUrl.$$replace = false; }); } return changeCounter; }); return currentUrl; }]; } /** * @ngdoc object * @name angular.module.ng.$log * @requires $window * * @description * Simple service for logging. Default implementation writes the message * into the browser's console (if present). * * The main purpose of this service is to simplify debugging and troubleshooting. * * @example <doc:example> <doc:source> <script> function LogCtrl($log) { this.$log = $log; this.message = 'Hello World!'; } </script> <div ng-controller="LogCtrl"> <p>Reload this page with open console, enter text and hit the log button...</p> Message: <input type="text" ng-model="message"/> <button ng-click="$log.log(message)">log</button> <button ng-click="$log.warn(message)">warn</button> <button ng-click="$log.info(message)">info</button> <button ng-click="$log.error(message)">error</button> </div> </doc:source> <doc:scenario> </doc:scenario> </doc:example> */ function $LogProvider(){ this.$get = ['$window', function($window){ return { /** * @ngdoc method * @name angular.module.ng.$log#log * @methodOf angular.module.ng.$log * * @description * Write a log message */ log: consoleLog('log'), /** * @ngdoc method * @name angular.module.ng.$log#warn * @methodOf angular.module.ng.$log * * @description * Write a warning message */ warn: consoleLog('warn'), /** * @ngdoc method * @name angular.module.ng.$log#info * @methodOf angular.module.ng.$log * * @description * Write an information message */ info: consoleLog('info'), /** * @ngdoc method * @name angular.module.ng.$log#error * @methodOf angular.module.ng.$log * * @description * Write an error message */ error: consoleLog('error') }; function formatError(arg) { if (arg instanceof Error) { if (arg.stack) { arg = (arg.message && arg.stack.indexOf(arg.message) === -1) ? 'Error: ' + arg.message + '\n' + arg.stack : arg.stack; } else if (arg.sourceURL) { arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line; } } return arg; } function consoleLog(type) { var console = $window.console || {}, logFn = console[type] || console.log || noop; if (logFn.apply) { return function() { var args = []; forEach(arguments, function(arg) { args.push(formatError(arg)); }); return logFn.apply(console, args); }; } // we are IE which either doesn't have window.console => this is noop and we do nothing, // or we are IE where console.log doesn't have apply so we log at least first 2 args return function(arg1, arg2) { logFn(arg1, arg2); } } }]; } var OPERATORS = { 'null':function(){return null;}, 'true':function(){return true;}, 'false':function(){return false;}, undefined:noop, '+':function(self, locals, a,b){a=a(self, locals); b=b(self, locals); return (isDefined(a)?a:0)+(isDefined(b)?b:0);}, '-':function(self, locals, a,b){a=a(self, locals); b=b(self, locals); return (isDefined(a)?a:0)-(isDefined(b)?b:0);}, '*':function(self, locals, a,b){return a(self, locals)*b(self, locals);}, '/':function(self, locals, a,b){return a(self, locals)/b(self, locals);}, '%':function(self, locals, a,b){return a(self, locals)%b(self, locals);}, '^':function(self, locals, a,b){return a(self, locals)^b(self, locals);}, '=':noop, '==':function(self, locals, a,b){return a(self, locals)==b(self, locals);}, '!=':function(self, locals, a,b){return a(self, locals)!=b(self, locals);}, '<':function(self, locals, a,b){return a(self, locals)<b(self, locals);}, '>':function(self, locals, a,b){return a(self, locals)>b(self, locals);}, '<=':function(self, locals, a,b){return a(self, locals)<=b(self, locals);}, '>=':function(self, locals, a,b){return a(self, locals)>=b(self, locals);}, '&&':function(self, locals, a,b){return a(self, locals)&&b(self, locals);}, '||':function(self, locals, a,b){return a(self, locals)||b(self, locals);}, '&':function(self, locals, a,b){return a(self, locals)&b(self, locals);}, // '|':function(self, locals, a,b){return a|b;}, '|':function(self, locals, a,b){return b(self, locals)(self, locals, a(self, locals));}, '!':function(self, locals, a){return !a(self, locals);} }; var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'}; function lex(text){ var tokens = [], token, index = 0, json = [], ch, lastCh = ':'; // can start regexp while (index < text.length) { ch = text.charAt(index); if (is('"\'')) { readString(ch); } else if (isNumber(ch) || is('.') && isNumber(peek())) { readNumber(); } else if (isIdent(ch)) { readIdent(); // identifiers can only be if the preceding char was a { or , if (was('{,') && json[0]=='{' && (token=tokens[tokens.length-1])) { token.json = token.text.indexOf('.') == -1; } } else if (is('(){}[].,;:')) { tokens.push({ index:index, text:ch, json:(was(':[,') && is('{[')) || is('}]:,') }); if (is('{[')) json.unshift(ch); if (is('}]')) json.shift(); index++; } else if (isWhitespace(ch)) { index++; continue; } else { var ch2 = ch + peek(), fn = OPERATORS[ch], fn2 = OPERATORS[ch2]; if (fn2) { tokens.push({index:index, text:ch2, fn:fn2}); index += 2; } else if (fn) { tokens.push({index:index, text:ch, fn:fn, json: was('[,:') && is('+-')}); index += 1; } else { throwError("Unexpected next character ", index, index+1); } } lastCh = ch; } return tokens; function is(chars) { return chars.indexOf(ch) != -1; } function was(chars) { return chars.indexOf(lastCh) != -1; } function peek() { return index + 1 < text.length ? text.charAt(index + 1) : false; } function isNumber(ch) { return '0' <= ch && ch <= '9'; } function isWhitespace(ch) { return ch == ' ' || ch == '\r' || ch == '\t' || ch == '\n' || ch == '\v' || ch == '\u00A0'; // IE treats non-breaking space as \u00A0 } function isIdent(ch) { return 'a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || '_' == ch || ch == '$'; } function isExpOperator(ch) { return ch == '-' || ch == '+' || isNumber(ch); } function throwError(error, start, end) { end = end || index; throw Error("Lexer Error: " + error + " at column" + (isDefined(start) ? "s " + start + "-" + index + " [" + text.substring(start, end) + "]" : " " + end) + " in expression [" + text + "]."); } function readNumber() { var number = ""; var start = index; while (index < text.length) { var ch = lowercase(text.charAt(index)); if (ch == '.' || isNumber(ch)) { number += ch; } else { var peekCh = peek(); if (ch == 'e' && isExpOperator(peekCh)) { number += ch; } else if (isExpOperator(ch) && peekCh && isNumber(peekCh) && number.charAt(number.length - 1) == 'e') { number += ch; } else if (isExpOperator(ch) && (!peekCh || !isNumber(peekCh)) && number.charAt(number.length - 1) == 'e') { throwError('Invalid exponent'); } else { break; } } index++; } number = 1 * number; tokens.push({index:start, text:number, json:true, fn:function() {return number;}}); } function readIdent() { var ident = "", start = index, lastDot, peekIndex, methodName; while (index < text.length) { var ch = text.charAt(index); if (ch == '.' || isIdent(ch) || isNumber(ch)) { if (ch == '.') lastDot = index; ident += ch; } else { break; } index++; } //check if this is not a method invocation and if it is back out to last dot if (lastDot) { peekIndex = index; while(peekIndex < text.length) { var ch = text.charAt(peekIndex); if (ch == '(') { methodName = ident.substr(lastDot - start + 1); ident = ident.substr(0, lastDot - start); index = peekIndex; break; } if(isWhitespace(ch)) { peekIndex++; } else { break; } } } var token = { index:start, text:ident }; if (OPERATORS.hasOwnProperty(ident)) { token.fn = token.json = OPERATORS[ident]; } else { var getter = getterFn(ident); token.fn = extend(function(self, locals) { return (getter(self, locals)); }, { assign: function(self, value) { return setter(self, ident, value); } }); } tokens.push(token); if (methodName) { tokens.push({ index:lastDot, text: '.', json: false }); tokens.push({ index: lastDot + 1, text: methodName, json: false }); } } function readString(quote) { var start = index; index++; var string = ""; var rawString = quote; var escape = false; while (index < text.length) { var ch = text.charAt(index); rawString += ch; if (escape) { if (ch == 'u') { var hex = text.substring(index + 1, index + 5); if (!hex.match(/[\da-f]{4}/i)) throwError( "Invalid unicode escape [\\u" + hex + "]"); index += 4; string += String.fromCharCode(parseInt(hex, 16)); } else { var rep = ESCAPE[ch]; if (rep) { string += rep; } else { string += ch; } } escape = false; } else if (ch == '\\') { escape = true; } else if (ch == quote) { index++; tokens.push({ index:start, text:rawString, string:string, json:true, fn:function() { return string; } }); return; } else { string += ch; } index++; } throwError("Unterminated quote", start); } } ///////////////////////////////////////// function parser(text, json, $filter){ var ZERO = valueFn(0), value, tokens = lex(text), assignment = _assignment, functionCall = _functionCall, fieldAccess = _fieldAccess, objectIndex = _objectIndex, filterChain = _filterChain; if(json){ // The extra level of aliasing is here, just in case the lexer misses something, so that // we prevent any accidental execution in JSON. assignment = logicalOR; functionCall = fieldAccess = objectIndex = filterChain = function() { throwError("is not valid json", {text:text, index:0}); }; value = primary(); } else { value = statements(); } if (tokens.length !== 0) { throwError("is an unexpected token", tokens[0]); } return value; /////////////////////////////////// function throwError(msg, token) { throw Error("Syntax Error: Token '" + token.text + "' " + msg + " at column " + (token.index + 1) + " of the expression [" + text + "] starting at [" + text.substring(token.index) + "]."); } function peekToken() { if (tokens.length === 0) throw Error("Unexpected end of expression: " + text); return tokens[0]; } function peek(e1, e2, e3, e4) { if (tokens.length > 0) { var token = tokens[0]; var t = token.text; if (t==e1 || t==e2 || t==e3 || t==e4 || (!e1 && !e2 && !e3 && !e4)) { return token; } } return false; } function expect(e1, e2, e3, e4){ var token = peek(e1, e2, e3, e4); if (token) { if (json && !token.json) { throwError("is not valid json", token); } tokens.shift(); return token; } return false; } function consume(e1){ if (!expect(e1)) { throwError("is unexpected, expecting [" + e1 + "]", peek()); } } function unaryFn(fn, right) { return function(self, locals) { return fn(self, locals, right); }; } function binaryFn(left, fn, right) { return function(self, locals) { return fn(self, locals, left, right); }; } function statements() { var statements = []; while(true) { if (tokens.length > 0 && !peek('}', ')', ';', ']')) statements.push(filterChain()); if (!expect(';')) { // optimize for the common case where there is only one statement. // TODO(size): maybe we should not support multiple statements? return statements.length == 1 ? statements[0] : function(self, locals){ var value; for ( var i = 0; i < statements.length; i++) { var statement = statements[i]; if (statement) value = statement(self, locals); } return value; }; } } } function _filterChain() { var left = expression(); var token; while(true) { if ((token = expect('|'))) { left = binaryFn(left, token.fn, filter()); } else { return left; } } } function filter() { var token = expect(); var fn = $filter(token.text); var argsFn = []; while(true) { if ((token = expect(':'))) { argsFn.push(expression()); } else { var fnInvoke = function(self, locals, input){ var args = [input]; for ( var i = 0; i < argsFn.length; i++) { args.push(argsFn[i](self, locals)); } return fn.apply(self, args); }; return function() { return fnInvoke; }; } } } function expression() { return assignment(); } function _assignment() { var left = logicalOR(); var right; var token; if ((token = expect('='))) { if (!left.assign) { throwError("implies assignment but [" + text.substring(0, token.index) + "] can not be assigned to", token); } right = logicalOR(); return function(self, locals){ return left.assign(self, right(self, locals), locals); }; } else { return left; } } function logicalOR() { var left = logicalAND(); var token; while(true) { if ((token = expect('||'))) { left = binaryFn(left, token.fn, logicalAND()); } else { return left; } } } function logicalAND() { var left = equality(); var token; if ((token = expect('&&'))) { left = binaryFn(left, token.fn, logicalAND()); } return left; } function equality() { var left = relational(); var token; if ((token = expect('==','!='))) { left = binaryFn(left, token.fn, equality()); } return left; } function relational() { var left = additive(); var token; if ((token = expect('<', '>', '<=', '>='))) { left = binaryFn(left, token.fn, relational()); } return left; } function additive() { var left = multiplicative(); var token; while ((token = expect('+','-'))) { left = binaryFn(left, token.fn, multiplicative()); } return left; } function multiplicative() { var left = unary(); var token; while ((token = expect('*','/','%'))) { left = binaryFn(left, token.fn, unary()); } return left; } function unary() { var token; if (expect('+')) { return primary(); } else if ((token = expect('-'))) { return binaryFn(ZERO, token.fn, unary()); } else if ((token = expect('!'))) { return unaryFn(token.fn, unary()); } else { return primary(); } } function primary() { var primary; if (expect('(')) { primary = filterChain(); consume(')'); } else if (expect('[')) { primary = arrayDeclaration(); } else if (expect('{')) { primary = object(); } else { var token = expect(); primary = token.fn; if (!primary) { throwError("not a primary expression", token); } } var next, context; while ((next = expect('(', '[', '.'))) { if (next.text === '(') { primary = functionCall(primary, context); context = null; } else if (next.text === '[') { context = primary; primary = objectIndex(primary); } else if (next.text === '.') { context = primary; primary = fieldAccess(primary); } else { throwError("IMPOSSIBLE"); } } return primary; } function _fieldAccess(object) { var field = expect().text; var getter = getterFn(field); return extend( function(self, locals) { return getter(object(self, locals), locals); }, { assign:function(self, value, locals) { return setter(object(self, locals), field, value); } } ); } function _objectIndex(obj) { var indexFn = expression(); consume(']'); return extend( function(self, locals){ var o = obj(self, locals), i = indexFn(self, locals), v, p; if (!o) return undefined; v = o[i]; if (v && v.then) { p = v; if (!('$$v' in v)) { p.$$v = undefined; p.then(function(val) { p.$$v = val; }); } v = v.$$v; } return v; }, { assign:function(self, value, locals){ return obj(self, locals)[indexFn(self, locals)] = value; } }); } function _functionCall(fn, contextGetter) { var argsFn = []; if (peekToken().text != ')') { do { argsFn.push(expression()); } while (expect(',')); } consume(')'); return function(self, locals){ var args = [], context = contextGetter ? contextGetter(self, locals) : self; for ( var i = 0; i < argsFn.length; i++) { args.push(argsFn[i](self, locals)); } var fnPtr = fn(self, locals) || noop; // IE stupidity! return fnPtr.apply ? fnPtr.apply(context, args) : fnPtr(args[0], args[1], args[2], args[3], args[4]); }; } // This is used with json array declaration function arrayDeclaration () { var elementFns = []; if (peekToken().text != ']') { do { elementFns.push(expression()); } while (expect(',')); } consume(']'); return function(self, locals){ var array = []; for ( var i = 0; i < elementFns.length; i++) { array.push(elementFns[i](self, locals)); } return array; }; } function object () { var keyValues = []; if (peekToken().text != '}') { do { var token = expect(), key = token.string || token.text; consume(":"); var value = expression(); keyValues.push({key:key, value:value}); } while (expect(',')); } consume('}'); return function(self, locals){ var object = {}; for ( var i = 0; i < keyValues.length; i++) { var keyValue = keyValues[i]; var value = keyValue.value(self, locals); object[keyValue.key] = value; } return object; }; } } ////////////////////////////////////////////////// // Parser helper functions ////////////////////////////////////////////////// function setter(obj, path, setValue) { var element = path.split('.'); for (var i = 0; element.length > 1; i++) { var key = element.shift(); var propertyObj = obj[key]; if (!propertyObj) { propertyObj = {}; obj[key] = propertyObj; } obj = propertyObj; } obj[element.shift()] = setValue; return setValue; } /** * Return the value accesible from the object by path. Any undefined traversals are ignored * @param {Object} obj starting object * @param {string} path path to traverse * @param {boolean=true} bindFnToScope * @returns value as accesbile by path */ //TODO(misko): this function needs to be removed function getter(obj, path, bindFnToScope) { if (!path) return obj; var keys = path.split('.'); var key; var lastInstance = obj; var len = keys.length; for (var i = 0; i < len; i++) { key = keys[i]; if (obj) { obj = (lastInstance = obj)[key]; } } if (!bindFnToScope && isFunction(obj)) { return bind(lastInstance, obj); } return obj; } var getterFnCache = {}; function getterFn(path) { if (getterFnCache.hasOwnProperty(path)) { return getterFnCache[path]; } var fn, code = 'var l, fn, p;\n'; forEach(path.split('.'), function(key, index) { code += 'if(!s) return s;\n' + 'l=s;\n' + 's='+ (index // we simply direference 's' on any .dot notation ? 's' // but if we are first then we check locals firs, and if so read it first : '((k&&k.hasOwnProperty("' + key + '"))?k:s)') + '["' + key + '"]' + ';\n' + 'if (s && s.then) {\n' + ' if (!("$$v" in s)) {\n' + ' p=s;\n' + ' p.$$v = undefined;\n' + ' p.then(function(v) {p.$$v=v;});\n' + '}\n' + ' s=s.$$v\n' + '}\n'; }); code += 'return s;'; fn = Function('s', 'k', code); fn.toString = function() { return code; }; return getterFnCache[path] = fn; } /////////////////////////////////// function $ParseProvider() { var cache = {}; this.$get = ['$filter', function($filter) { return function(exp) { switch(typeof exp) { case 'string': return cache.hasOwnProperty(exp) ? cache[exp] : cache[exp] = parser(exp, false, $filter); case 'function': return exp; default: return noop; } }; }]; } /** * @ngdoc service * @name angular.module.ng.$q * @requires $rootScope * * @description * A promise/deferred implementation inspired by [Kris Kowal's Q](https://github.com/kriskowal/q). * * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an * interface for interacting with an object that represents the result of an action that is * performed asynchronously, and may or may not be finished at any given point in time. * * From the perspective of dealing with error handling, deferred and promise apis are to * asynchronous programing what `try`, `catch` and `throw` keywords are to synchronous programing. * * <pre> * // for the purpose of this example let's assume that variables `$q` and `scope` are * // available in the current lexical scope (they could have been injected or passed in). * * function asyncGreet(name) { * var deferred = $q.defer(); * * setTimeout(function() { * // since this fn executes async in a future turn of the event loop, we need to wrap * // our code into an $apply call so that the model changes are properly observed. * scope.$apply(function() { * if (okToGreet(name)) { * deferred.resolve('Hello, ' + name + '!'); * } else { * deferred.reject('Greeting ' + name + ' is not allowed.'); * } * }); * }, 1000); * * return deferred.promise; * } * * var promise = asyncGreet('Robin Hood'); * promise.then(function(greeting) { * alert('Success: ' + greeting); * }, function(reason) { * alert('Failed: ' + reason); * ); * </pre> * * At first it might not be obvious why this extra complexity is worth the trouble. The payoff * comes in the way of * [guarantees that promise and deferred apis make](https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md). * * Additionally the promise api allows for composition that is very hard to do with the * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach. * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the * section on serial or parallel joining of promises. * * * # The Deferred API * * A new instance of deferred is constructed by calling `$q.defer()`. * * The purpose of the deferred object is to expose the associated Promise instance as well as apis * that can be used for signaling the successful or unsuccessful completion of the task. * * **Methods** * * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection * constructed via `$q.reject`, the promise will be rejected instead. * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to * resolving it with a rejection constructed via `$q.reject`. * * **Properties** * * - promise – `{Promise}` – promise object associated with this deferred. * * * # The Promise API * * A new promise instance is created when a deferred instance is created and can be retrieved by * calling `deferred.promise`. * * The purpose of the promise object is to allow for interested parties to get access to the result * of the deferred task when it completes. * * **Methods** * * - `then(successCallback, errorCallback)` – regardless of when the promise was or will be resolved * or rejected calls one of the success or error callbacks asynchronously as soon as the result * is available. The callbacks are called with a single argument the result or rejection reason. * * This method *returns a new promise* which is resolved or rejected via the return value of the * `successCallback` or `errorCallback`. * * * # Chaining promises * * Because calling `then` api of a promise returns a new derived promise, it is easily possible * to create a chain of promises: * * <pre> * promiseB = promiseA.then(function(result) { * return result + 1; * }); * * // promiseB will be resolved immediately after promiseA is resolved and it's value will be * // the result of promiseA incremented by 1 * </pre> * * It is possible to create chains of any length and since a promise can be resolved with another * promise (which will defer its resolution further), it is possible to pause/defer resolution of * the promises at any point in the chain. This makes it possible to implement powerful apis like * $http's response interceptors. * * * # Differences between Kris Kowal's Q and $q * * There are three main differences: * * - $q is integrated with the {@link angular.module.ng.$rootScope.Scope} Scope model observation * mechanism in angular, which means faster propagation of resolution or rejection into your * models and avoiding unnecessary browser repaints, which would result in flickering UI. * - $q promises are recognized by the templating engine in angular, which means that in templates * you can treat promises attached to a scope as if they were the resulting values. * - Q has many more features that $q, but that comes at a cost of bytes. $q is tiny, but contains * all the important functionality needed for common async tasks. */ function $QProvider() { this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) { return qFactory(function(callback) { $rootScope.$evalAsync(callback); }, $exceptionHandler); }]; } /** * Constructs a promise manager. * * @param {function(function)} nextTick Function for executing functions in the next turn. * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for * debugging purposes. * @returns {object} Promise manager. */ function qFactory(nextTick, exceptionHandler) { /** * @ngdoc * @name angular.module.ng.$q#defer * @methodOf angular.module.ng.$q * @description * Creates a `Deferred` object which represents a task which will finish in the future. * * @returns {Deferred} Returns a new instance of deferred. */ var defer = function() { var pending = [], value, deferred; deferred = { resolve: function(val) { if (pending) { var callbacks = pending; pending = undefined; value = ref(val); if (callbacks.length) { nextTick(function() { var callback; for (var i = 0, ii = callbacks.length; i < ii; i++) { callback = callbacks[i]; value.then(callback[0], callback[1]); } }); } } }, reject: function(reason) { deferred.resolve(reject(reason)); }, promise: { then: function(callback, errback) { var result = defer(); var wrappedCallback = function(value) { try { result.resolve((callback || defaultCallback)(value)); } catch(e) { exceptionHandler(e); result.reject(e); } }; var wrappedErrback = function(reason) { try { result.resolve((errback || defaultErrback)(reason)); } catch(e) { exceptionHandler(e); result.reject(e); } }; if (pending) { pending.push([wrappedCallback, wrappedErrback]); } else { value.then(wrappedCallback, wrappedErrback); } return result.promise; } } }; return deferred; }; var ref = function(value) { if (value && value.then) return value; return { then: function(callback) { var result = defer(); nextTick(function() { result.resolve(callback(value)); }); return result.promise; } }; }; /** * @ngdoc * @name angular.module.ng.$q#reject * @methodOf angular.module.ng.$q * @description * Creates a promise that is resolved as rejected with the specified `reason`. This api should be * used to forward rejection in a chain of promises. If you are dealing with the last promise in * a promise chain, you don't need to worry about it. * * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via * a promise error callback and you want to forward the error to the promise derived from the * current promise, you have to "rethrow" the error by returning a rejection constructed via * `reject`. * * <pre> * promiseB = promiseA.then(function(result) { * // success: do something and resolve promiseB * // with the old or a new result * return result; * }, function(reason) { * // error: handle the error if possible and * // resolve promiseB with newPromiseOrValue, * // otherwise forward the rejection to promiseB * if (canHandle(reason)) { * // handle the error and recover * return newPromiseOrValue; * } * return $q.reject(reason); * }); * </pre> * * @param {*} reason Constant, message, exception or an object representing the rejection reason. * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`. */ var reject = function(reason) { return { then: function(callback, errback) { var result = defer(); nextTick(function() { result.resolve((errback || defaultErrback)(reason)); }); return result.promise; } }; }; /** * @ngdoc * @name angular.module.ng.$q#when * @methodOf angular.module.ng.$q * @description * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. * This is useful when you are dealing with on object that might or might not be a promise, or if * the promise comes from a source that can't be trusted. * * @param {*} value Value or a promise * @returns {Promise} Returns a single promise that will be resolved with an array of values, * each value coresponding to the promise at the same index in the `promises` array. If any of * the promises is resolved with a rejection, this resulting promise will be resolved with the * same rejection. */ var when = function(value, callback, errback) { var result = defer(), done; var wrappedCallback = function(value) { try { return (callback || defaultCallback)(value); } catch (e) { exceptionHandler(e); return reject(e); } }; var wrappedErrback = function(reason) { try { return (errback || defaultErrback)(reason); } catch (e) { exceptionHandler(e); return reject(e); } }; nextTick(function() { ref(value).then(function(value) { if (done) return; done = true; result.resolve(ref(value).then(wrappedCallback, wrappedErrback)); }, function(reason) { if (done) return; done = true; result.resolve(wrappedErrback(reason)); }); }); return result.promise; }; function defaultCallback(value) { return value; } function defaultErrback(reason) { return reject(reason); } /** * @ngdoc * @name angular.module.ng.$q#all * @methodOf angular.module.ng.$q * @description * Combines multiple promises into a single promise that is resolved when all of the input * promises are resolved. * * @param {Array.<Promise>} promises An array of promises. * @returns {Promise} Returns a single promise that will be resolved with an array of values, * each value coresponding to the promise at the same index in the `promises` array. If any of * the promises is resolved with a rejection, this resulting promise will be resolved with the * same rejection. */ function all(promises) { var deferred = defer(), counter = promises.length, results = []; if (counter) { forEach(promises, function(promise, index) { ref(promise).then(function(value) { if (index in results) return; results[index] = value; if (!(--counter)) deferred.resolve(results); }, function(reason) { if (index in results) return; deferred.reject(reason); }); }); } else { deferred.resolve(results); } return deferred.promise; } return { defer: defer, reject: reject, when: when, all: all }; } /** * @ngdoc object * @name angular.module.ng.$routeProvider * @function * * @description * * Used for configuring routes. See {@link angular.module.ng.$route $route} for an example. */ function $RouteProvider(){ var routes = {}; /** * @ngdoc method * @name angular.module.ng.$routeProvider#when * @methodOf angular.module.ng.$routeProvider * * @param {string} path Route path (matched against `$location.path`). If `$location.path` * contains redudant trailing slash or is missing one, the route will still match and the * `$location.path` will be updated to add or drop the trailing slash to exacly match the * route definition. * @param {Object} route Mapping information to be assigned to `$route.current` on route * match. * * Object properties: * * - `controller` – `{function()=}` – Controller fn that should be associated with newly * created scope. * - `template` – `{string=}` – path to an html template that should be used by * {@link angular.module.ng.$compileProvider.directive.ngView ngView} or * {@link angular.module.ng.$compileProvider.directive.ngInclude ngInclude} directives. * - `redirectTo` – {(string|function())=} – value to update * {@link angular.module.ng.$location $location} path with and trigger route redirection. * * If `redirectTo` is a function, it will be called with the following parameters: * * - `{Object.<string>}` - route parameters extracted from the current * `$location.path()` by applying the current route template. * - `{string}` - current `$location.path()` * - `{Object}` - current `$location.search()` * * The custom `redirectTo` function is expected to return a string which will be used * to update `$location.path()` and `$location.search()`. * * - `[reloadOnSearch=true]` - {boolean=} - reload route when only $location.search() * changes. * * If the option is set to `false` and url in the browser changes, then * `$routeUpdate` event is broadcasted on the root scope. * * @returns {Object} self * * @description * Adds a new route definition to the `$route` service. */ this.when = function(path, route) { routes[path] = extend({reloadOnSearch: true}, route); // create redirection for trailing slashes if (path) { var redirectPath = (path[path.length-1] == '/') ? path.substr(0, path.length-1) : path +'/'; routes[redirectPath] = {redirectTo: path}; } return this; }; /** * @ngdoc method * @name angular.module.ng.$routeProvider#otherwise * @methodOf angular.module.ng.$routeProvider * * @description * Sets route definition that will be used on route change when no other route definition * is matched. * * @param {Object} params Mapping information to be assigned to `$route.current`. * @returns {Object} self */ this.otherwise = function(params) { this.when(null, params); return this; }; this.$get = ['$rootScope', '$location', '$routeParams', function( $rootScope, $location, $routeParams) { /** * @ngdoc object * @name angular.module.ng.$route * @requires $location * @requires $routeParams * * @property {Object} current Reference to the current route definition. * @property {Array.<Object>} routes Array of all configured routes. * * @description * Is used for deep-linking URLs to controllers and views (HTML partials). * It watches `$location.url()` and tries to map the path to an existing route definition. * * You can define routes through {@link angular.module.ng.$routeProvider $routeProvider}'s API. * * The `$route` service is typically used in conjunction with {@link angular.module.ng.$compileProvider.directive.ngView ngView} * directive and the {@link angular.module.ng.$routeParams $routeParams} service. * * @example This example shows how changing the URL hash causes the `$route` to match a route against the URL, and the `ngView` pulls in the partial. Note that this example is using {@link angular.module.ng.$compileProvider.directive.script inlined templates} to get it working on jsfiddle as well. <doc:example module="route"> <doc:source> <script type="text/ng-template" id="examples/book.html"> controller: {{name}}<br /> Book Id: {{params.bookId}}<br /> </script> <script type="text/ng-template" id="examples/chapter.html"> controller: {{name}}<br /> Book Id: {{params.bookId}}<br /> Chapter Id: {{params.chapterId}} </script> <script> angular.module('route', [], function($routeProvider, $locationProvider) { $routeProvider.when('/Book/:bookId', {template: 'examples/book.html', controller: BookCntl}); $routeProvider.when('/Book/:bookId/ch/:chapterId', {template: 'examples/chapter.html', controller: ChapterCntl}); // configure html5 to get links working on jsfiddle $locationProvider.html5Mode(true); }); function MainCntl($scope, $route, $routeParams, $location) { $scope.$route = $route; $scope.$location = $location; $scope.$routeParams = $routeParams; } function BookCntl($scope, $routeParams) { $scope.name = "BookCntl"; $scope.params = $routeParams; } function ChapterCntl($scope, $routeParams) { $scope.name = "ChapterCntl"; $scope.params = $routeParams; } </script> <div ng-controller="MainCntl"> Choose: <a href="Book/Moby">Moby</a> | <a href="Book/Moby/ch/1">Moby: Ch1</a> | <a href="Book/Gatsby">Gatsby</a> | <a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> | <a href="Book/Scarlet">Scarlet Letter</a><br/> <div ng-view></div> <hr /> <pre>$location.path() = {{$location.path()}}</pre> <pre>$route.current.template = {{$route.current.template}}</pre> <pre>$route.current.params = {{$route.current.params}}</pre> <pre>$route.current.scope.name = {{$route.current.scope.name}}</pre> <pre>$routeParams = {{$routeParams}}</pre> </div> </doc:source> <doc:scenario> it('should load and compile correct template', function() { element('a:contains("Moby: Ch1")').click(); var content = element('.doc-example-live [ng-view]').text(); expect(content).toMatch(/controller\: ChapterCntl/); expect(content).toMatch(/Book Id\: Moby/); expect(content).toMatch(/Chapter Id\: 1/); element('a:contains("Scarlet")').click(); content = element('.doc-example-live [ng-view]').text(); expect(content).toMatch(/controller\: BookCntl/); expect(content).toMatch(/Book Id\: Scarlet/); }); </doc:scenario> </doc:example> */ /** * @ngdoc event * @name angular.module.ng.$route#$beforeRouteChange * @eventOf angular.module.ng.$route * @eventType broadcast on root scope * @description * Broadcasted before a route change. * * @param {Route} next Future route information. * @param {Route} current Current route information. */ /** * @ngdoc event * @name angular.module.ng.$route#$afterRouteChange * @eventOf angular.module.ng.$route * @eventType broadcast on root scope * @description * Broadcasted after a route change. * * @param {Route} current Current route information. * @param {Route} previous Previous route information. */ /** * @ngdoc event * @name angular.module.ng.$route#$routeUpdate * @eventOf angular.module.ng.$route * @eventType broadcast on root scope * @description * * The `reloadOnSearch` property has been set to false, and we are reusing the same * instance of the Controller. */ var matcher = switchRouteMatcher, dirty = 0, forceReload = false, $route = { routes: routes, /** * @ngdoc method * @name angular.module.ng.$route#reload * @methodOf angular.module.ng.$route * * @description * Causes `$route` service to reload the current route even if * {@link angular.module.ng.$location $location} hasn't changed. * * As a result of that, {@link angular.module.ng.$compileProvider.directive.ngView ngView} * creates new scope, reinstantiates the controller. */ reload: function() { dirty++; forceReload = true; } }; $rootScope.$watch(function() { return dirty + $location.url(); }, updateRoute); return $route; ///////////////////////////////////////////////////// function switchRouteMatcher(on, when) { // TODO(i): this code is convoluted and inefficient, we should construct the route matching // regex only once and then reuse it var regex = '^' + when.replace(/([\.\\\(\)\^\$])/g, "\\$1") + '$', params = [], dst = {}; forEach(when.split(/\W/), function(param) { if (param) { var paramRegExp = new RegExp(":" + param + "([\\W])"); if (regex.match(paramRegExp)) { regex = regex.replace(paramRegExp, "([^\\/]*)$1"); params.push(param); } } }); var match = on.match(new RegExp(regex)); if (match) { forEach(params, function(name, index) { dst[name] = match[index + 1]; }); } return match ? dst : null; } function updateRoute() { var next = parseRoute(), last = $route.current; if (next && last && next.$route === last.$route && equals(next.pathParams, last.pathParams) && !next.reloadOnSearch && !forceReload) { last.params = next.params; copy(last.params, $routeParams); $rootScope.$broadcast('$routeUpdate', last); } else if (next || last) { forceReload = false; $rootScope.$broadcast('$beforeRouteChange', next, last); $route.current = next; if (next) { if (next.redirectTo) { if (isString(next.redirectTo)) { $location.path(interpolate(next.redirectTo, next.params)).search(next.params) .replace(); } else { $location.url(next.redirectTo(next.pathParams, $location.path(), $location.search())) .replace(); } } else { copy(next.params, $routeParams); } } $rootScope.$broadcast('$afterRouteChange', next, last); } } /** * @returns the current active route, by matching it against the URL */ function parseRoute() { // Match a route var params, match; forEach(routes, function(route, path) { if (!match && (params = matcher($location.path(), path))) { match = inherit(route, { params: extend({}, $location.search(), params), pathParams: params}); match.$route = route; } }); // No route matched; fallback to "otherwise" route return match || routes[null] && inherit(routes[null], {params: {}, pathParams:{}}); } /** * @returns interpolation of the redirect path with the parametrs */ function interpolate(string, params) { var result = []; forEach((string||'').split(':'), function(segment, i) { if (i == 0) { result.push(segment); } else { var segmentMatch = segment.match(/(\w+)(.*)/); var key = segmentMatch[1]; result.push(params[key]); result.push(segmentMatch[2] || ''); delete params[key]; } }); return result.join(''); } }]; } /** * @ngdoc object * @name angular.module.ng.$routeParams * @requires $route * * @description * Current set of route parameters. The route parameters are a combination of the * {@link angular.module.ng.$location $location} `search()`, and `path()`. The `path` parameters * are extracted when the {@link angular.module.ng.$route $route} path is matched. * * In case of parameter name collision, `path` params take precedence over `search` params. * * The service guarantees that the identity of the `$routeParams` object will remain unchanged * (but its properties will likely change) even when a route change occurs. * * @example * <pre> * // Given: * // URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby * // Route: /Chapter/:chapterId/Section/:sectionId * // * // Then * $routeParams ==> {chapterId:1, sectionId:2, search:'moby'} * </pre> */ function $RouteParamsProvider() { this.$get = valueFn({}); } /** * DESIGN NOTES * * The design decisions behind the scope ware heavily favored for speed and memory consumption. * * The typical use of scope is to watch the expressions, which most of the time return the same * value as last time so we optimize the operation. * * Closures construction is expensive from speed as well as memory: * - no closures, instead ups prototypical inheritance for API * - Internal state needs to be stored on scope directly, which means that private state is * exposed as $$____ properties * * Loop operations are optimized by using while(count--) { ... } * - this means that in order to keep the same order of execution as addition we have to add * items to the array at the begging (shift) instead of at the end (push) * * Child scopes are created and removed often * - Using array would be slow since inserts in meddle are expensive so we use linked list * * There are few watches then a lot of observers. This is why you don't want the observer to be * implemented in the same way as watch. Watch requires return of initialization function which * are expensive to construct. */ /** * @ngdoc object * @name angular.module.ng.$rootScopeProvider * @description * * Provider for the $rootScope service. */ /** * @ngdoc function * @name angular.module.ng.$rootScopeProvider#digestTtl * @methodOf angular.module.ng.$rootScopeProvider * @description * * Sets the number of digest iteration the scope should attempt to execute before giving up and * assuming that the model is unstable. * * The current default is 10 iterations. * * @param {number} limit The number of digest iterations. */ /** * @ngdoc object * @name angular.module.ng.$rootScope * @description * * Every application has a single root {@link angular.module.ng.$rootScope.Scope scope}. * All other scopes are child scopes of the root scope. Scopes provide mechanism for watching the model and provide * event processing life-cycle. See {@link guide/dev_guide.scopes developer guide on scopes}. */ function $RootScopeProvider(){ var TTL = 10; this.digestTtl = function(value) { if (arguments.length) { TTL = value; } return TTL; }; this.$get = ['$injector', '$exceptionHandler', '$parse', function( $injector, $exceptionHandler, $parse) { /** * @ngdoc function * @name angular.module.ng.$rootScope.Scope * * @description * A root scope can be retrieved using the {@link angular.module.ng.$rootScope $rootScope} key from the * {@link angular.module.AUTO.$injector $injector}. Child scopes are created using the * {@link angular.module.ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when * compiled HTML template is executed.) * * Here is a simple scope snippet to show how you can interact with the scope. * <pre> angular.injector(['ng']).invoke(function($rootScope) { var scope = $rootScope.$new(); scope.salutation = 'Hello'; scope.name = 'World'; expect(scope.greeting).toEqual(undefined); scope.$watch('name', function() { this.greeting = this.salutation + ' ' + this.name + '!'; }); // initialize the watch expect(scope.greeting).toEqual(undefined); scope.name = 'Misko'; // still old value, since watches have not been called yet expect(scope.greeting).toEqual(undefined); scope.$digest(); // fire all the watches expect(scope.greeting).toEqual('Hello Misko!'); }); * </pre> * * # Inheritance * A scope can inherit from a parent scope, as in this example: * <pre> var parent = $rootScope; var child = parent.$new(); parent.salutation = "Hello"; child.name = "World"; expect(child.salutation).toEqual('Hello'); child.salutation = "Welcome"; expect(child.salutation).toEqual('Welcome'); expect(parent.salutation).toEqual('Hello'); * </pre> * * # Dependency Injection * See {@link guide/dev_guide.di dependency injection}. * * * @param {Object.<string, function()>=} providers Map of service factory which need to be provided * for the current scope. Defaults to {@link angular.module.ng}. * @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should * append/override services provided by `providers`. This is handy when unit-testing and having * the need to override a default service. * @returns {Object} Newly created scope. * */ function Scope() { this.$id = nextUid(); this.$$phase = this.$parent = this.$$watchers = this.$$nextSibling = this.$$prevSibling = this.$$childHead = this.$$childTail = null; this['this'] = this.$root = this; this.$$asyncQueue = []; this.$$listeners = {}; } /** * @ngdoc property * @name angular.module.ng.$rootScope.Scope#$id * @propertyOf angular.module.ng.$rootScope.Scope * @returns {number} Unique scope ID (monotonically increasing alphanumeric sequence) useful for * debugging. */ Scope.prototype = { /** * @ngdoc function * @name angular.module.ng.$rootScope.Scope#$new * @methodOf angular.module.ng.$rootScope.Scope * @function * * @description * Creates a new child {@link angular.module.ng.$rootScope.Scope scope}. * * The parent scope will propagate the {@link angular.module.ng.$rootScope.Scope#$digest $digest()} and * {@link angular.module.ng.$rootScope.Scope#$digest $digest()} events. The scope can be removed from the scope * hierarchy using {@link angular.module.ng.$rootScope.Scope#$destroy $destroy()}. * * {@link angular.module.ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is desired for * the scope and its child scopes to be permanently detached from the parent and thus stop * participating in model change detection and listener notification by invoking. * * @params {boolean} isolate if true then the scoped does not prototypically inherit from the * parent scope. The scope is isolated, as it can not se parent scope properties. * When creating widgets it is useful for the widget to not accidently read parent * state. * * @returns {Object} The newly created child scope. * */ $new: function(isolate) { var Child, child; if (isFunction(isolate)) { // TODO: remove at some point throw Error('API-CHANGE: Use $controller to instantiate controllers.'); } if (isolate) { child = new Scope(); child.$root = this.$root; } else { Child = function() {}; // should be anonymous; This is so that when the minifier munges // the name it does not become random set of chars. These will then show up as class // name in the debugger. Child.prototype = this; child = new Child(); child.$id = nextUid(); } child['this'] = child; child.$$listeners = {}; child.$parent = this; child.$$asyncQueue = []; child.$$watchers = child.$$nextSibling = child.$$childHead = child.$$childTail = null; child.$$prevSibling = this.$$childTail; if (this.$$childHead) { this.$$childTail.$$nextSibling = child; this.$$childTail = child; } else { this.$$childHead = this.$$childTail = child; } return child; }, /** * @ngdoc function * @name angular.module.ng.$rootScope.Scope#$watch * @methodOf angular.module.ng.$rootScope.Scope * @function * * @description * Registers a `listener` callback to be executed whenever the `watchExpression` changes. * * - The `watchExpression` is called on every call to {@link angular.module.ng.$rootScope.Scope#$digest $digest()} and * should return the value which will be watched. (Since {@link angular.module.ng.$rootScope.Scope#$digest $digest()} * reruns when it detects changes the `watchExpression` can execute multiple times per * {@link angular.module.ng.$rootScope.Scope#$digest $digest()} and should be idempotent.) * - The `listener` is called only when the value from the current `watchExpression` and the * previous call to `watchExpression' are not equal (with the exception of the initial run * see below). The inequality is determined according to * {@link angular.equals} function. To save the value of the object for later comparison * {@link angular.copy} function is used. It also means that watching complex options will * have adverse memory and performance implications. * - The watch `listener` may change the model, which may trigger other `listener`s to fire. This * is achieved by rerunning the watchers until no changes are detected. The rerun iteration * limit is 100 to prevent infinity loop deadlock. * * * If you want to be notified whenever {@link angular.module.ng.$rootScope.Scope#$digest $digest} is called, * you can register an `watchExpression` function with no `listener`. (Since `watchExpression`, * can execute multiple times per {@link angular.module.ng.$rootScope.Scope#$digest $digest} cycle when a change is * detected, be prepared for multiple calls to your listener.) * * After a watcher is registered with the scope, the `listener` fn is called asynchronously * (via {@link angular.module.ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the * watcher. In rare cases, this is undesirable because the listener is called when the result * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the * listener was called due to initialization. * * * # Example <pre> // let's assume that scope was dependency injected as the $rootScope var scope = $rootScope; scope.name = 'misko'; scope.counter = 0; expect(scope.counter).toEqual(0); scope.$watch('name', function(newValue, oldValue) { counter = counter + 1; }); expect(scope.counter).toEqual(0); scope.$digest(); // no variable change expect(scope.counter).toEqual(0); scope.name = 'adam'; scope.$digest(); expect(scope.counter).toEqual(1); </pre> * * * * @param {(function()|string)} watchExpression Expression that is evaluated on each * {@link angular.module.ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers a * call to the `listener`. * * - `string`: Evaluated as {@link guide/dev_guide.expressions expression} * - `function(scope)`: called with current `scope` as a parameter. * @param {(function()|string)=} listener Callback called whenever the return value of * the `watchExpression` changes. * * - `string`: Evaluated as {@link guide/dev_guide.expressions expression} * - `function(newValue, oldValue, scope)`: called with current and previous values as parameters. * * @param {boolean=} objectEquality Compare object for equality rather then for refference. * @returns {function()} Returns a deregistration function for this listener. */ $watch: function(watchExp, listener, objectEquality) { var scope = this, get = compileToFn(watchExp, 'watch'), array = scope.$$watchers, watcher = { fn: listener, last: initWatchVal, get: get, exp: watchExp, eq: !!objectEquality }; // in the case user pass string, we need to compile it, do we really need this ? if (!isFunction(listener)) { var listenFn = compileToFn(listener || noop, 'listener'); watcher.fn = function(newVal, oldVal, scope) {listenFn(scope);}; } if (!array) { array = scope.$$watchers = []; } // we use unshift since we use a while loop in $digest for speed. // the while loop reads in reverse order. array.unshift(watcher); return function() { arrayRemove(array, watcher); }; }, /** * @ngdoc function * @name angular.module.ng.$rootScope.Scope#$digest * @methodOf angular.module.ng.$rootScope.Scope * @function * * @description * Process all of the {@link angular.module.ng.$rootScope.Scope#$watch watchers} of the current scope and its children. * Because a {@link angular.module.ng.$rootScope.Scope#$watch watcher}'s listener can change the model, the * `$digest()` keeps calling the {@link angular.module.ng.$rootScope.Scope#$watch watchers} until no more listeners are * firing. This means that it is possible to get into an infinite loop. This function will throw * `'Maximum iteration limit exceeded.'` if the number of iterations exceeds 100. * * Usually you don't call `$digest()` directly in * {@link angular.module.ng.$compileProvider.directive.ngController controllers} or in * {@link angular.module.ng.$compileProvider.directive directives}. * Instead a call to {@link angular.module.ng.$rootScope.Scope#$apply $apply()} (typically from within a * {@link angular.module.ng.$compileProvider.directive directives}) will force a `$digest()`. * * If you want to be notified whenever `$digest()` is called, * you can register a `watchExpression` function with {@link angular.module.ng.$rootScope.Scope#$watch $watch()} * with no `listener`. * * You may have a need to call `$digest()` from within unit-tests, to simulate the scope * life-cycle. * * # Example <pre> var scope = ...; scope.name = 'misko'; scope.counter = 0; expect(scope.counter).toEqual(0); scope.$watch('name', function(scope, newValue, oldValue) { counter = counter + 1; }); expect(scope.counter).toEqual(0); scope.$digest(); // no variable change expect(scope.counter).toEqual(0); scope.name = 'adam'; scope.$digest(); expect(scope.counter).toEqual(1); </pre> * */ $digest: function() { var watch, value, last, watchers, asyncQueue, length, dirty, ttl = TTL, next, current, target = this, watchLog = [], logIdx, logMsg; flagPhase(target, '$digest'); do { dirty = false; current = target; do { asyncQueue = current.$$asyncQueue; while(asyncQueue.length) { try { current.$eval(asyncQueue.shift()); } catch (e) { $exceptionHandler(e); } } if ((watchers = current.$$watchers)) { // process our watches length = watchers.length; while (length--) { try { watch = watchers[length]; // Most common watches are on primitives, in which case we can short // circuit it with === operator, only when === fails do we use .equals if ((value = watch.get(current)) !== (last = watch.last) && !(watch.eq ? equals(value, last) : (typeof value == 'number' && typeof last == 'number' && isNaN(value) && isNaN(last)))) { dirty = true; watch.last = watch.eq ? copy(value) : value; watch.fn(value, ((last === initWatchVal) ? value : last), current); if (ttl < 5) { logIdx = 4 - ttl; if (!watchLog[logIdx]) watchLog[logIdx] = []; logMsg = (isFunction(watch.exp)) ? 'fn: ' + (watch.exp.name || watch.exp.toString()) : watch.exp; logMsg += '; newVal: ' + toJson(value) + '; oldVal: ' + toJson(last); watchLog[logIdx].push(logMsg); } } } catch (e) { $exceptionHandler(e); } } } // Insanity Warning: scope depth-first traversal // yes, this code is a bit crazy, but it works and we have tests to prove it! // this piece should be kept in sync with the traversal in $broadcast if (!(next = (current.$$childHead || (current !== target && current.$$nextSibling)))) { while(current !== target && !(next = current.$$nextSibling)) { current = current.$parent; } } } while ((current = next)); if(dirty && !(ttl--)) { throw Error(TTL + ' $digest() iterations reached. Aborting!\n' + 'Watchers fired in the last 5 iterations: ' + toJson(watchLog)); } } while (dirty || asyncQueue.length); this.$root.$$phase = null; }, /** * @ngdoc event * @name angular.module.$rootScope.Scope#$destroy * @eventOf angular.module.ng.$rootScope.Scope * @eventType broadcast on scope being destroyed * * @description * Broadcasted when a scope and its children are being destroyed. */ /** * @ngdoc function * @name angular.module.ng.$rootScope.Scope#$destroy * @methodOf angular.module.ng.$rootScope.Scope * @function * * @description * Remove the current scope (and all of its children) from the parent scope. Removal implies * that calls to {@link angular.module.ng.$rootScope.Scope#$digest $digest()} will no longer * propagate to the current scope and its children. Removal also implies that the current * scope is eligible for garbage collection. * * The `$destroy()` is usually used by directives such as * {@link angular.module.ng.$compileProvider.directive.ngRepeat ngRepeat} for managing the * unrolling of the loop. * * Just before a scope is destroyed a `$destroy` event is broadcasted on this scope. * Application code can register a `$destroy` event handler that will give it chance to * perform any necessary cleanup. */ $destroy: function() { if (this.$root == this) return; // we can't remove the root node; var parent = this.$parent; this.$broadcast('$destroy'); if (parent.$$childHead == this) parent.$$childHead = this.$$nextSibling; if (parent.$$childTail == this) parent.$$childTail = this.$$prevSibling; if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling; if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling; }, /** * @ngdoc function * @name angular.module.ng.$rootScope.Scope#$eval * @methodOf angular.module.ng.$rootScope.Scope * @function * * @description * Executes the `expression` on the current scope returning the result. Any exceptions in the * expression are propagated (uncaught). This is useful when evaluating engular expressions. * * # Example <pre> var scope = angular.module.ng.$rootScope.Scope(); scope.a = 1; scope.b = 2; expect(scope.$eval('a+b')).toEqual(3); expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3); </pre> * * @param {(string|function())=} expression An angular expression to be executed. * * - `string`: execute using the rules as defined in {@link guide/dev_guide.expressions expression}. * - `function(scope, locals)`: execute the function with the current `scope` parameter. * @param {Object=} locals Hash object of local variables for the expression. * * @returns {*} The result of evaluating the expression. */ $eval: function(expr, locals) { return $parse(expr)(this, locals); }, /** * @ngdoc function * @name angular.module.ng.$rootScope.Scope#$evalAsync * @methodOf angular.module.ng.$rootScope.Scope * @function * * @description * Executes the expression on the current scope at a later point in time. * * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only that: * * - it will execute in the current script execution context (before any DOM rendering). * - at least one {@link angular.module.ng.$rootScope.Scope#$digest $digest cycle} will be performed after * `expression` execution. * * Any exceptions from the execution of the expression are forwarded to the * {@link angular.module.ng.$exceptionHandler $exceptionHandler} service. * * @param {(string|function())=} expression An angular expression to be executed. * * - `string`: execute using the rules as defined in {@link guide/dev_guide.expressions expression}. * - `function(scope)`: execute the function with the current `scope` parameter. * */ $evalAsync: function(expr) { this.$$asyncQueue.push(expr); }, /** * @ngdoc function * @name angular.module.ng.$rootScope.Scope#$apply * @methodOf angular.module.ng.$rootScope.Scope * @function * * @description * `$apply()` is used to execute an expression in angular from outside of the angular framework. * (For example from browser DOM events, setTimeout, XHR or third party libraries). * Because we are calling into the angular framework we need to perform proper scope life-cycle * of {@link angular.module.ng.$exceptionHandler exception handling}, * {@link angular.module.ng.$rootScope.Scope#$digest executing watches}. * * ## Life cycle * * # Pseudo-Code of `$apply()` function $apply(expr) { try { return $eval(expr); } catch (e) { $exceptionHandler(e); } finally { $root.$digest(); } } * * * Scope's `$apply()` method transitions through the following stages: * * 1. The {@link guide/dev_guide.expressions expression} is executed using the * {@link angular.module.ng.$rootScope.Scope#$eval $eval()} method. * 2. Any exceptions from the execution of the expression are forwarded to the * {@link angular.module.ng.$exceptionHandler $exceptionHandler} service. * 3. The {@link angular.module.ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the expression * was executed using the {@link angular.module.ng.$rootScope.Scope#$digest $digest()} method. * * * @param {(string|function())=} exp An angular expression to be executed. * * - `string`: execute using the rules as defined in {@link guide/dev_guide.expressions expression}. * - `function(scope)`: execute the function with current `scope` parameter. * * @returns {*} The result of evaluating the expression. */ $apply: function(expr) { try { flagPhase(this, '$apply'); return this.$eval(expr); } catch (e) { $exceptionHandler(e); } finally { this.$root.$$phase = null; this.$root.$digest(); } }, /** * @ngdoc function * @name angular.module.ng.$rootScope.Scope#$on * @methodOf angular.module.ng.$rootScope.Scope * @function * * @description * Listen on events of a given type. See {@link angular.module.ng.$rootScope.Scope#$emit $emit} for discussion of * event life cycle. * * @param {string} name Event name to listen on. * @param {function(event)} listener Function to call when the event is emitted. * @returns {function()} Returns a deregistration function for this listener. * * The event listener function format is: `function(event)`. The `event` object passed into the * listener has the following attributes * * - `targetScope` - {Scope}: the scope on which the event was `$emit`-ed or `$broadcast`-ed. * - `currentScope` - {Scope}: the current scope which is handling the event. * - `name` - {string}: Name of the event. * - `cancel` - {function=}: calling `cancel` function will cancel further event propagation * (available only for events that were `$emit`-ed). * - `cancelled` - {boolean}: Whether the event was cancelled. */ $on: function(name, listener) { var namedListeners = this.$$listeners[name]; if (!namedListeners) { this.$$listeners[name] = namedListeners = []; } namedListeners.push(listener); return function() { arrayRemove(namedListeners, listener); }; }, /** * @ngdoc function * @name angular.module.ng.$rootScope.Scope#$emit * @methodOf angular.module.ng.$rootScope.Scope * @function * * @description * Dispatches an event `name` upwards through the scope hierarchy notifying the * registered {@link angular.module.ng.$rootScope.Scope#$on} listeners. * * The event life cycle starts at the scope on which `$emit` was called. All * {@link angular.module.ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get notified. * Afterwards, the event traverses upwards toward the root scope and calls all registered * listeners along the way. The event will stop propagating if one of the listeners cancels it. * * Any exception emmited from the {@link angular.module.ng.$rootScope.Scope#$on listeners} will be passed * onto the {@link angular.module.ng.$exceptionHandler $exceptionHandler} service. * * @param {string} name Event name to emit. * @param {...*} args Optional set of arguments which will be passed onto the event listeners. * @return {Object} Event object, see {@link angular.module.ng.$rootScope.Scope#$on} */ $emit: function(name, args) { var empty = [], namedListeners, scope = this, event = { name: name, targetScope: scope, cancel: function() {event.cancelled = true;}, cancelled: false }, listenerArgs = concat([event], arguments, 1), i, length; do { namedListeners = scope.$$listeners[name] || empty; event.currentScope = scope; for (i=0, length=namedListeners.length; i<length; i++) { try { namedListeners[i].apply(null, listenerArgs); if (event.cancelled) return event; } catch (e) { $exceptionHandler(e); } } //traverse upwards scope = scope.$parent; } while (scope); return event; }, /** * @ngdoc function * @name angular.module.ng.$rootScope.Scope#$broadcast * @methodOf angular.module.ng.$rootScope.Scope * @function * * @description * Dispatches an event `name` downwards to all child scopes (and their children) notifying the * registered {@link angular.module.ng.$rootScope.Scope#$on} listeners. * * The event life cycle starts at the scope on which `$broadcast` was called. All * {@link angular.module.ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get notified. * Afterwards, the event propagates to all direct and indirect scopes of the current scope and * calls all registered listeners along the way. The event cannot be canceled. * * Any exception emmited from the {@link angular.module.ng.$rootScope.Scope#$on listeners} will be passed * onto the {@link angular.module.ng.$exceptionHandler $exceptionHandler} service. * * @param {string} name Event name to emit. * @param {...*} args Optional set of arguments which will be passed onto the event listeners. * @return {Object} Event object, see {@link angular.module.ng.$rootScope.Scope#$on} */ $broadcast: function(name, args) { var target = this, current = target, next = target, event = { name: name, targetScope: target }, listenerArgs = concat([event], arguments, 1); //down while you can, then up and next sibling or up and next sibling until back at root do { current = next; event.currentScope = current; forEach(current.$$listeners[name], function(listener) { try { listener.apply(null, listenerArgs); } catch(e) { $exceptionHandler(e); } }); // Insanity Warning: scope depth-first traversal // yes, this code is a bit crazy, but it works and we have tests to prove it! // this piece should be kept in sync with the traversal in $digest if (!(next = (current.$$childHead || (current !== target && current.$$nextSibling)))) { while(current !== target && !(next = current.$$nextSibling)) { current = current.$parent; } } } while ((current = next)); return event; } }; function flagPhase(scope, phase) { var root = scope.$root; if (root.$$phase) { throw Error(root.$$phase + ' already in progress'); } root.$$phase = phase; } return new Scope(); function compileToFn(exp, name) { var fn = $parse(exp); assertArgFn(fn, name); return fn; } /** * function used as an initial value for watchers. * because it's uniqueue we can easily tell it apart from other values */ function initWatchVal() {} }]; } /** * !!! This is an undocumented "private" service !!! * * @name angular.module.ng.$sniffer * @requires $window * * @property {boolean} history Does the browser support html5 history api ? * @property {boolean} hashchange Does the browser support hashchange event ? * * @description * This is very simple implementation of testing browser's features. */ function $SnifferProvider() { this.$get = ['$window', function($window) { var eventSupport = {}; return { history: !!($window.history && $window.history.pushState), hashchange: 'onhashchange' in $window && // IE8 compatible mode lies (!$window.document.documentMode || $window.document.documentMode > 7), hasEvent: function(event) { if (isUndefined(eventSupport[event])) { var divElm = $window.document.createElement('div'); eventSupport[event] = 'on' + event in divElm; } return eventSupport[event]; } }; }]; } /** * @ngdoc object * @name angular.module.ng.$window * * @description * A reference to the browser's `window` object. While `window` * is globally available in JavaScript, it causes testability problems, because * it is a global variable. In angular we always refer to it through the * `$window` service, so it may be overriden, removed or mocked for testing. * * All expressions are evaluated with respect to current scope so they don't * suffer from window globality. * * @example <doc:example> <doc:source> <input ng-init="$window = $service('$window'); greeting='Hello World!'" type="text" ng-model="greeting" /> <button ng-click="$window.alert(greeting)">ALERT</button> </doc:source> <doc:scenario> </doc:scenario> </doc:example> */ function $WindowProvider(){ this.$get = valueFn(window); } /** * Parse headers into key value object * * @param {string} headers Raw headers as a string * @returns {Object} Parsed headers as key value object */ function parseHeaders(headers) { var parsed = {}, key, val, i; if (!headers) return parsed; forEach(headers.split('\n'), function(line) { i = line.indexOf(':'); key = lowercase(trim(line.substr(0, i))); val = trim(line.substr(i + 1)); if (key) { if (parsed[key]) { parsed[key] += ', ' + val; } else { parsed[key] = val; } } }); return parsed; } /** * Returns a function that provides access to parsed headers. * * Headers are lazy parsed when first requested. * @see parseHeaders * * @param {(string|Object)} headers Headers to provide access to. * @returns {function(string=)} Returns a getter function which if called with: * * - if called with single an argument returns a single header value or null * - if called with no arguments returns an object containing all headers. */ function headersGetter(headers) { var headersObj = isObject(headers) ? headers : undefined; return function(name) { if (!headersObj) headersObj = parseHeaders(headers); if (name) { return headersObj[lowercase(name)] || null; } return headersObj; }; } /** * Chain all given functions * * This function is used for both request and response transforming * * @param {*} data Data to transform. * @param {function(string=)} headers Http headers getter fn. * @param {(function|Array.<function>)} fns Function or an array of functions. * @returns {*} Transformed data. */ function transformData(data, headers, fns) { if (isFunction(fns)) return fns(data, headers); forEach(fns, function(fn) { data = fn(data, headers); }); return data; } function isSuccess(status) { return 200 <= status && status < 300; } function $HttpProvider() { var JSON_START = /^\s*(\[|\{[^\{])/, JSON_END = /[\}\]]\s*$/, PROTECTION_PREFIX = /^\)\]\}',?\n/; var $config = this.defaults = { // transform incoming response data transformResponse: [function(data) { if (isString(data)) { // strip json vulnerability protection prefix data = data.replace(PROTECTION_PREFIX, ''); if (JSON_START.test(data) && JSON_END.test(data)) data = fromJson(data, true); } return data; }], // transform outgoing request data transformRequest: [function(d) { return isObject(d) && !isFile(d) ? toJson(d) : d; }], // default headers headers: { common: { 'Accept': 'application/json, text/plain, */*', 'X-Requested-With': 'XMLHttpRequest' }, post: {'Content-Type': 'application/json'}, put: {'Content-Type': 'application/json'} } }; var providerResponseInterceptors = this.responseInterceptors = []; this.$get = ['$httpBackend', '$browser', '$cacheFactory', '$rootScope', '$q', '$injector', function($httpBackend, $browser, $cacheFactory, $rootScope, $q, $injector) { var defaultCache = $cacheFactory('$http'), responseInterceptors = []; forEach(providerResponseInterceptors, function(interceptor) { responseInterceptors.push( isString(interceptor) ? $injector.get(interceptor) : $injector.invoke(interceptor) ); }); /** * @ngdoc function * @name angular.module.ng.$http * @requires $httpBacked * @requires $browser * @requires $cacheFactory * @requires $rootScope * @requires $q * @requires $injector * * @description * The `$http` service is a core Angular service that facilitates communication with the remote * HTTP servers via browser's {@link https://developer.mozilla.org/en/xmlhttprequest * XMLHttpRequest} object or via {@link http://en.wikipedia.org/wiki/JSONP JSONP}. * * For unit testing applications that use `$http` service, see * {@link angular.module.ngMock.$httpBackend $httpBackend mock}. * * For a higher level of abstraction, please check out the {@link angular.module.ngResource.$resource * $resource} service. * * The $http API is based on the {@link angular.module.ng.$q deferred/promise APIs} exposed by * the $q service. While for simple usage patters this doesn't matter much, for advanced usage, * it is important to familiarize yourself with these apis and guarantees they provide. * * * # General usage * The `$http` service is a function which takes a single argument — a configuration object — * that is used to generate an http request and returns a {@link angular.module.ng.$q promise} * with two $http specific methods: `success` and `error`. * * <pre> * $http({method: 'GET', url: '/someUrl'}). * success(function(data, status, headers, config) { * // this callback will be called asynchronously * // when the response is available * }). * error(function(data, status, headers, config) { * // called asynchronously if an error occurs * // or server returns response with status * // code outside of the <200, 400) range * }); * </pre> * * Since the returned value of calling the $http function is a Promise object, you can also use * the `then` method to register callbacks, and these callbacks will receive a single argument – * an object representing the response. See the api signature and type info below for more * details. * * * # Shortcut methods * * Since all invocation of the $http service require definition of the http method and url and * POST and PUT requests require response body/data to be provided as well, shortcut methods * were created to simplify using the api: * * <pre> * $http.get('/someUrl').success(successCallback); * $http.post('/someUrl', data).success(successCallback); * </pre> * * Complete list of shortcut methods: * * - {@link angular.module.ng.$http#get $http.get} * - {@link angular.module.ng.$http#head $http.head} * - {@link angular.module.ng.$http#post $http.post} * - {@link angular.module.ng.$http#put $http.put} * - {@link angular.module.ng.$http#delete $http.delete} * - {@link angular.module.ng.$http#jsonp $http.jsonp} * * * # Setting HTTP Headers * * The $http service will automatically add certain http headers to all requests. These defaults * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration * object, which currently contains this default configuration: * * - `$httpProvider.defaults.headers.common` (headers that are common for all requests): * - `Accept: application/json, text/plain, * / *` * - `X-Requested-With: XMLHttpRequest` * - `$httpProvider.defaults.headers.post`: (header defaults for HTTP POST requests) * - `Content-Type: application/json` * - `$httpProvider.defaults.headers.put` (header defaults for HTTP PUT requests) * - `Content-Type: application/json` * * To add or overwrite these defaults, simply add or remove a property from this configuration * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object * with name equal to the lower-cased http method name, e.g. * `$httpProvider.defaults.headers.get['My-Header']='value'`. * * Additionally, the defaults can be set at runtime via the `$http.defaults` object in a similar * fassion as described above. * * * # Transforming Requests and Responses * * Both requests and responses can be transformed using transform functions. By default, Angular * applies these transformations: * * Request transformations: * * - if the `data` property of the request config object contains an object, serialize it into * JSON format. * * Response transformations: * * - if XSRF prefix is detected, strip it (see Security Considerations section below) * - if json response is detected, deserialize it using a JSON parser * * To override these transformation locally, specify transform functions as `transformRequest` * and/or `transformResponse` properties of the config object. To globally override the default * transforms, override the `$httpProvider.defaults.transformRequest` and * `$httpProvider.defaults.transformResponse` properties of the `$httpProvider`. * * * # Caching * * To enable caching set the configuration property `cache` to `true`. When the cache is * enabled, `$http` stores the response from the server in local cache. Next time the * response is served from the cache without sending a request to the server. * * Note that even if the response is served from cache, delivery of the data is asynchronous in * the same way that real requests are. * * If there are multiple GET requests for the same url that should be cached using the same * cache, but the cache is not populated yet, only one request to the server will be made and * the remaining requests will be fulfilled using the response for the first request. * * * # Response interceptors * * Before you start creating interceptors, be sure to understand the * {@link angular.module.ng.$q $q and deferred/promise APIs}. * * For purposes of global error handling, authentication or any kind of synchronous or * asynchronous preprocessing of received responses, it is desirable to be able to intercept * responses for http requests before they are handed over to the application code that * initiated these requests. The response interceptors leverage the {@link angular.module.ng.$q * promise apis} to fulfil this need for both synchronous and asynchronous preprocessing. * * The interceptors are service factories that are registered with the $httpProvider by * adding them to the `$httpProvider.responseInterceptors` array. The factory is called and * injected with dependencies (if specified) and returns the interceptor — a function that * takes a {@link angular.module.ng.$q promise} and returns the original or a new promise. * * <pre> * // register the interceptor as a service * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) { * return function(promise) { * return promise.then(function(response) { * // do something on success * }, function(response) { * // do something on error * if (canRecover(response)) { * return responseOrNewPromise * } * return $q.reject(response); * }); * } * }); * * $httpProvider.responseInterceptors.push('myHttpInterceptor'); * * * // register the interceptor via an anonymous factory * $httpProvider.responseInterceptors.push(function($q, dependency1, dependency2) { * return function(promise) { * // same as above * } * }); * </pre> * * * # Security Considerations * * When designing web applications, consider security threats from: * * - {@link http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx * JSON Vulnerability} * - {@link http://en.wikipedia.org/wiki/Cross-site_request_forgery XSRF} * * Both server and the client must cooperate in order to eliminate these threats. Angular comes * pre-configured with strategies that address these issues, but for this to work backend server * cooperation is required. * * ## JSON Vulnerability Protection * * A {@link http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx * JSON Vulnerability} allows third party web-site to turn your JSON resource URL into * {@link http://en.wikipedia.org/wiki/JSON#JSONP JSONP} request under some conditions. To * counter this your server can prefix all JSON requests with following string `")]}',\n"`. * Angular will automatically strip the prefix before processing it as JSON. * * For example if your server needs to return: * <pre> * ['one','two'] * </pre> * * which is vulnerable to attack, your server can return: * <pre> * )]}', * ['one','two'] * </pre> * * Angular will strip the prefix, before processing the JSON. * * * ## Cross Site Request Forgery (XSRF) Protection * * {@link http://en.wikipedia.org/wiki/Cross-site_request_forgery XSRF} is a technique by which * an unauthorized site can gain your user's private data. Angular provides following mechanism * to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie * called `XSRF-TOKEN` and sets it as the HTTP header `X-XSRF-TOKEN`. Since only JavaScript that * runs on your domain could read the cookie, your server can be assured that the XHR came from * JavaScript running on your domain. * * To take advantage of this, your server needs to set a token in a JavaScript readable session * cookie called `XSRF-TOKEN` on first HTTP GET request. On subsequent non-GET requests the * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure * that only JavaScript running on your domain could have read the token. The token must be * unique for each user and must be verifiable by the server (to prevent the JavaScript making * up its own tokens). We recommend that the token is a digest of your site's authentication * cookie with {@link http://en.wikipedia.org/wiki/Rainbow_table salt for added security}. * * * @param {object} config Object describing the request to be made and how it should be * processed. The object has following properties: * * - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc) * - **url** – `{string}` – Absolute or relative URL of the resource that is being requested. * - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be turned to * `?key1=value1&key2=value2` after the url. If the value is not a string, it will be JSONified. * - **data** – `{string|Object}` – Data to be sent as the request message data. * - **headers** – `{Object}` – Map of strings representing HTTP headers to send to the server. * - **transformRequest** – `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` – * transform function or an array of such functions. The transform function takes the http * request body and headers and returns its transformed (typically serialized) version. * - **transformResponse** – `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` – * transform function or an array of such functions. The transform function takes the http * response body and headers and returns its transformed (typically deserialized) version. * - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the * GET request, otherwise if a cache instance built with * {@link angular.module.ng.$cacheFactory $cacheFactory}, this cache will be used for * caching. * - **timeout** – `{number}` – timeout in milliseconds. * - **withCredentials** - `{boolean}` - whether to to set the `withCredentials` flag on the * XHR object. See {@link https://developer.mozilla.org/en/http_access_control#section_5 * requests with credentials} for more information. * * @returns {HttpPromise} Returns a {@link angular.module.ng.$q promise} object with the * standard `then` method and two http specific methods: `success` and `error`. The `then` * method takes two arguments a success and an error callback which will be called with a * response object. The `success` and `error` methods take a single argument - a function that * will be called when the request succeeds or fails respectively. The arguments passed into * these functions are destructured representation of the response object passed into the * `then` method. The response object has these properties: * * - **data** – `{string|Object}` – The response body transformed with the transform functions. * - **status** – `{number}` – HTTP status code of the response. * - **headers** – `{function([headerName])}` – Header getter function. * - **config** – `{Object}` – The configuration object that was used to generate the request. * * @property {Array.<Object>} pendingRequests Array of config objects for currently pending * requests. This is primarily meant to be used for debugging purposes. * * * @example <doc:example> <doc:source jsfiddle="false"> <script> function FetchCtrl($scope, $http) { $scope.method = 'GET'; $scope.url = 'examples/http-hello.html'; $scope.fetch = function() { $scope.code = null; $scope.response = null; $http({method: $scope.method, url: $scope.url}). success(function(data, status) { $scope.status = status; $scope.data = data; }). error(function(data, status) { $scope.data = data || "Request failed"; $scope.status = status; }); }; $scope.updateModel = function(method, url) { $scope.method = method; $scope.url = url; }; } </script> <div ng-controller="FetchCtrl"> <select ng-model="method"> <option>GET</option> <option>JSONP</option> </select> <input type="text" ng-model="url" size="80"/> <button ng-click="fetch()">fetch</button><br> <button ng-click="updateModel('GET', 'examples/http-hello.html')">Sample GET</button> <button ng-click="updateModel('JSONP', 'http://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')">Sample JSONP</button> <button ng-click="updateModel('JSONP', 'http://angularjs.org/doesntexist&callback=JSON_CALLBACK')">Invalid JSONP</button> <pre>http status code: {{status}}</pre> <pre>http response data: {{data}}</pre> </div> </doc:source> <doc:scenario> it('should make an xhr GET request', function() { element(':button:contains("Sample GET")').click(); element(':button:contains("fetch")').click(); expect(binding('status')).toBe('200'); expect(binding('data')).toBe('Hello, $http!\n'); }); it('should make a JSONP request to angularjs.org', function() { element(':button:contains("Sample JSONP")').click(); element(':button:contains("fetch")').click(); expect(binding('status')).toBe('200'); expect(binding('data')).toMatch(/Super Hero!/); }); it('should make JSONP request to invalid URL and invoke the error handler', function() { element(':button:contains("Invalid JSONP")').click(); element(':button:contains("fetch")').click(); expect(binding('status')).toBe('0'); expect(binding('data')).toBe('Request failed'); }); </doc:scenario> </doc:example> */ function $http(config) { config.method = uppercase(config.method); var reqTransformFn = config.transformRequest || $config.transformRequest, respTransformFn = config.transformResponse || $config.transformResponse, defHeaders = $config.headers, reqHeaders = extend({'X-XSRF-TOKEN': $browser.cookies()['XSRF-TOKEN']}, defHeaders.common, defHeaders[lowercase(config.method)], config.headers), reqData = transformData(config.data, headersGetter(reqHeaders), reqTransformFn), promise; // strip content-type if data is undefined if (isUndefined(config.data)) { delete reqHeaders['Content-Type']; } // send request promise = sendReq(config, reqData, reqHeaders); // transform future response promise = promise.then(transformResponse, transformResponse); // apply interceptors forEach(responseInterceptors, function(interceptor) { promise = interceptor(promise); }); promise.success = function(fn) { promise.then(function(response) { fn(response.data, response.status, response.headers, config); }); return promise; }; promise.error = function(fn) { promise.then(null, function(response) { fn(response.data, response.status, response.headers, config); }); return promise; }; return promise; function transformResponse(response) { // make a copy since the response must be cacheable var resp = extend({}, response, { data: transformData(response.data, response.headers, respTransformFn) }); return (isSuccess(response.status)) ? resp : $q.reject(resp); } } $http.pendingRequests = []; /** * @ngdoc method * @name angular.module.ng.$http#get * @methodOf angular.module.ng.$http * * @description * Shortcut method to perform `GET` request * * @param {string} url Relative or absolute URL specifying the destination of the request * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ /** * @ngdoc method * @name angular.module.ng.$http#delete * @methodOf angular.module.ng.$http * * @description * Shortcut method to perform `DELETE` request * * @param {string} url Relative or absolute URL specifying the destination of the request * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ /** * @ngdoc method * @name angular.module.ng.$http#head * @methodOf angular.module.ng.$http * * @description * Shortcut method to perform `HEAD` request * * @param {string} url Relative or absolute URL specifying the destination of the request * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ /** * @ngdoc method * @name angular.module.ng.$http#jsonp * @methodOf angular.module.ng.$http * * @description * Shortcut method to perform `JSONP` request * * @param {string} url Relative or absolute URL specifying the destination of the request. * Should contain `JSON_CALLBACK` string. * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ createShortMethods('get', 'delete', 'head', 'jsonp'); /** * @ngdoc method * @name angular.module.ng.$http#post * @methodOf angular.module.ng.$http * * @description * Shortcut method to perform `POST` request * * @param {string} url Relative or absolute URL specifying the destination of the request * @param {*} data Request content * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ /** * @ngdoc method * @name angular.module.ng.$http#put * @methodOf angular.module.ng.$http * * @description * Shortcut method to perform `PUT` request * * @param {string} url Relative or absolute URL specifying the destination of the request * @param {*} data Request content * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ createShortMethodsWithData('post', 'put'); /** * @ngdoc property * @name angular.module.ng.$http#defaults * @propertyOf angular.module.ng.$http * * @description * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of * default headers as well as request and response transformations. * * See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above. */ $http.defaults = $config; return $http; function createShortMethods(names) { forEach(arguments, function(name) { $http[name] = function(url, config) { return $http(extend(config || {}, { method: name, url: url })); }; }); } function createShortMethodsWithData(name) { forEach(arguments, function(name) { $http[name] = function(url, data, config) { return $http(extend(config || {}, { method: name, url: url, data: data })); }; }); } /** * Makes the request * * !!! ACCESSES CLOSURE VARS: * $httpBackend, $config, $log, $rootScope, defaultCache, $http.pendingRequests */ function sendReq(config, reqData, reqHeaders) { var deferred = $q.defer(), promise = deferred.promise, cache, cachedResp, url = buildUrl(config.url, config.params); $http.pendingRequests.push(config); promise.then(removePendingReq, removePendingReq); if (config.cache && config.method == 'GET') { cache = isObject(config.cache) ? config.cache : defaultCache; } if (cache) { cachedResp = cache.get(url); if (cachedResp) { if (cachedResp.then) { // cached request has already been sent, but there is no response yet cachedResp.then(removePendingReq, removePendingReq); return cachedResp; } else { // serving from cache if (isArray(cachedResp)) { resolvePromise(cachedResp[1], cachedResp[0], copy(cachedResp[2])); } else { resolvePromise(cachedResp, 200, {}); } } } else { // put the promise for the non-transformed response into cache as a placeholder cache.put(url, promise); } } // if we won't have the response in cache, send the request to the backend if (!cachedResp) { $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout, config.withCredentials); } return promise; /** * Callback registered to $httpBackend(): * - caches the response if desired * - resolves the raw $http promise * - calls $apply */ function done(status, response, headersString) { if (cache) { if (isSuccess(status)) { cache.put(url, [status, response, parseHeaders(headersString)]); } else { // remove promise from the cache cache.remove(url); } } resolvePromise(response, status, headersString); $rootScope.$apply(); } /** * Resolves the raw $http promise. */ function resolvePromise(response, status, headers) { // normalize internal statuses to 0 status = Math.max(status, 0); (isSuccess(status) ? deferred.resolve : deferred.reject)({ data: response, status: status, headers: headersGetter(headers), config: config }); } function removePendingReq() { var idx = indexOf($http.pendingRequests, config); if (idx !== -1) $http.pendingRequests.splice(idx, 1); } } function buildUrl(url, params) { if (!params) return url; var parts = []; forEachSorted(params, function(value, key) { if (value == null || value == undefined) return; if (isObject(value)) { value = toJson(value); } parts.push(encodeURIComponent(key) + '=' + encodeURIComponent(value)); }); return url + ((url.indexOf('?') == -1) ? '?' : '&') + parts.join('&'); } }]; } var XHR = window.XMLHttpRequest || function() { try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch (e1) {} try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch (e2) {} try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e3) {} throw new Error("This browser does not support XMLHttpRequest."); }; /** * @ngdoc object * @name angular.module.ng.$httpBackend * @requires $browser * @requires $window * @requires $document * * @description * HTTP backend used by the {@link angular.module.ng.$http service} that delegates to * XMLHttpRequest object or JSONP and deals with browser incompatibilities. * * You should never need to use this service directly, instead use the higher-level abstractions: * {@link angular.module.ng.$http $http} or {@link angular.module.ngResource.$resource $resource}. * * During testing this implementation is swapped with {@link angular.module.ngMock.$httpBackend mock * $httpBackend} which can be trained with responses. */ function $HttpBackendProvider() { this.$get = ['$browser', '$window', '$document', function($browser, $window, $document) { return createHttpBackend($browser, XHR, $browser.defer, $window.angular.callbacks, $document[0], $window.location.protocol.replace(':', '')); }]; } function createHttpBackend($browser, XHR, $browserDefer, callbacks, rawDocument, locationProtocol) { // TODO(vojta): fix the signature return function(method, url, post, callback, headers, timeout, withCredentials) { $browser.$$incOutstandingRequestCount(); url = url || $browser.url(); if (lowercase(method) == 'jsonp') { var callbackId = '_' + (callbacks.counter++).toString(36); callbacks[callbackId] = function(data) { callbacks[callbackId].data = data; }; jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId), function() { if (callbacks[callbackId].data) { completeRequest(callback, 200, callbacks[callbackId].data); } else { completeRequest(callback, -2); } delete callbacks[callbackId]; }); } else { var xhr = new XHR(); xhr.open(method, url, true); forEach(headers, function(value, key) { if (value) xhr.setRequestHeader(key, value); }); var status; // In IE6 and 7, this might be called synchronously when xhr.send below is called and the // response is in the cache. the promise api will ensure that to the app code the api is // always async xhr.onreadystatechange = function() { if (xhr.readyState == 4) { completeRequest( callback, status || xhr.status, xhr.responseText, xhr.getAllResponseHeaders()); } }; if (withCredentials) { xhr.withCredentials = true; } xhr.send(post || ''); if (timeout > 0) { $browserDefer(function() { status = -1; xhr.abort(); }, timeout); } } function completeRequest(callback, status, response, headersString) { // URL_MATCH is defined in src/service/location.js var protocol = (url.match(URL_MATCH) || ['', locationProtocol])[1]; // fix status code for file protocol (it's always 0) status = (protocol == 'file') ? (response ? 200 : 404) : status; // normalize IE bug (http://bugs.jquery.com/ticket/1450) status = status == 1223 ? 204 : status; callback(status, response, headersString); $browser.$$completeOutstandingRequest(noop); } }; function jsonpReq(url, done) { // we can't use jQuery/jqLite here because jQuery does crazy shit with script elements, e.g.: // - fetches local scripts via XHR and evals them // - adds and immediately removes script elements from the document var script = rawDocument.createElement('script'), doneWrapper = function() { rawDocument.body.removeChild(script); if (done) done(); }; script.type = 'text/javascript'; script.src = url; if (msie) { script.onreadystatechange = function() { if (/loaded|complete/.test(script.readyState)) doneWrapper(); }; } else { script.onload = script.onerror = doneWrapper; } rawDocument.body.appendChild(script); } } /** * @ngdoc object * @name angular.module.ng.$locale * * @description * $locale service provides localization rules for various Angular components. As of right now the * only public api is: * * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`) */ function $LocaleProvider(){ this.$get = function() { return { id: 'en-us', NUMBER_FORMATS: { DECIMAL_SEP: '.', GROUP_SEP: ',', PATTERNS: [ { // Decimal Pattern minInt: 1, minFrac: 0, maxFrac: 3, posPre: '', posSuf: '', negPre: '-', negSuf: '', gSize: 3, lgSize: 3 },{ //Currency Pattern minInt: 1, minFrac: 2, maxFrac: 2, posPre: '\u00A4', posSuf: '', negPre: '(\u00A4', negSuf: ')', gSize: 3, lgSize: 3 } ], CURRENCY_SYM: '$' }, DATETIME_FORMATS: { MONTH: 'January,February,March,April,May,June,July,August,September,October,November,December' .split(','), SHORTMONTH: 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(','), DAY: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(','), SHORTDAY: 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split(','), AMPMS: ['AM','PM'], medium: 'MMM d, y h:mm:ss a', short: 'M/d/yy h:mm a', fullDate: 'EEEE, MMMM d, y', longDate: 'MMMM d, y', mediumDate: 'MMM d, y', shortDate: 'M/d/yy', mediumTime: 'h:mm:ss a', shortTime: 'h:mm a' }, pluralCat: function(num) { if (num === 1) { return 'one'; } return 'other'; } }; }; } /** * @ngdoc object * @name angular.module.ng.$filterProvider * @description * * Filters are just functions which transform input to an output. However filters need to be Dependency Injected. To * achieve this a filter definition consists of a factory function which is annotated with dependencies and is * responsible for creating a the filter function. * * <pre> * // Filter registration * function MyModule($provide, $filterProvider) { * // create a service to demonstrate injection (not always needed) * $provide.value('greet', function(name){ * return 'Hello ' + name + '!': * }); * * // register a filter factory which uses the * // greet service to demonstrate DI. * $filterProvider.register('greet', function(greet){ * // return the filter function which uses the greet service * // to generate salutation * return function(text) { * // filters need to be forgiving so check input validity * return text && greet(text) || text; * }; * }; * } * </pre> * * The filter function is registered with the `$injector` under the filter name suffixe with `Filter`. * <pre> * it('should be the same instance', inject( * function($filterProvider) { * $filterProvider.register('reverse', function(){ * return ...; * }); * }, * function($filter, reverseFilter) { * expect($filter('reverse')).toBe(reverseFilter); * }); * </pre> * * * For more information about how angular filters work, and how to create your own filters, see * {@link guide/dev_guide.templates.filters Understanding Angular Filters} in the angular Developer * Guide. */ /** * @ngdoc method * @name angular.module.ng.$filterProvider#register * @methodOf angular.module.ng.$filterProvider * @description * Register filter factory function. * * @param {String} name Name of the filter. * @param {function} fn The filter factory function which is injectable. */ /** * @ngdoc function * @name angular.module.ng.$filter * @function * @description * Filters are used for formatting data displayed to the user. * * The general syntax in templates is as follows: * * {{ expression | [ filter_name ] }} * * @param {String} name Name of the filter function to retrieve * @return {Function} the filter function */ $FilterProvider.$inject = ['$provide']; function $FilterProvider($provide) { var suffix = 'Filter'; function register(name, factory) { return $provide.factory(name + suffix, factory); } this.register = register; this.$get = ['$injector', function($injector) { return function(name) { return $injector.get(name + suffix); } }]; //////////////////////////////////////// register('currency', currencyFilter); register('date', dateFilter); register('filter', filterFilter); register('json', jsonFilter); register('limitTo', limitToFilter); register('lowercase', lowercaseFilter); register('number', numberFilter); register('orderBy', orderByFilter); register('uppercase', uppercaseFilter); } /** * @ngdoc filter * @name angular.module.ng.$filter.filter * @function * * @description * Selects a subset of items from `array` and returns it as a new array. * * Note: This function is used to augment the `Array` type in Angular expressions. See * {@link angular.module.ng.$filter} for more information about Angular arrays. * * @param {Array} array The source array. * @param {string|Object|function()} expression The predicate to be used for selecting items from * `array`. * * Can be one of: * * - `string`: Predicate that results in a substring match using the value of `expression` * string. All strings or objects with string properties in `array` that contain this string * will be returned. The predicate can be negated by prefixing the string with `!`. * * - `Object`: A pattern object can be used to filter specific properties on objects contained * by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items * which have property `name` containing "M" and property `phone` containing "1". A special * property name `$` can be used (as in `{$:"text"}`) to accept a match against any * property of the object. That's equivalent to the simple substring match with a `string` * as described above. * * - `function`: A predicate function can be used to write arbitrary filters. The function is * called for each element of `array`. The final result is an array of those elements that * the predicate returned true for. * * @example <doc:example> <doc:source> <div ng-init="friends = [{name:'John', phone:'555-1276'}, {name:'Mary', phone:'800-BIG-MARY'}, {name:'Mike', phone:'555-4321'}, {name:'Adam', phone:'555-5678'}, {name:'Julie', phone:'555-8765'}]"></div> Search: <input ng-model="searchText"> <table id="searchTextResults"> <tr><th>Name</th><th>Phone</th><tr> <tr ng-repeat="friend in friends | filter:searchText"> <td>{{friend.name}}</td> <td>{{friend.phone}}</td> <tr> </table> <hr> Any: <input ng-model="search.$"> <br> Name only <input ng-model="search.name"><br> Phone only <input ng-model="search.phone"å><br> <table id="searchObjResults"> <tr><th>Name</th><th>Phone</th><tr> <tr ng-repeat="friend in friends | filter:search"> <td>{{friend.name}}</td> <td>{{friend.phone}}</td> <tr> </table> </doc:source> <doc:scenario> it('should search across all fields when filtering with a string', function() { input('searchText').enter('m'); expect(repeater('#searchTextResults tr', 'friend in friends').column('friend.name')). toEqual(['Mary', 'Mike', 'Adam']); input('searchText').enter('76'); expect(repeater('#searchTextResults tr', 'friend in friends').column('friend.name')). toEqual(['John', 'Julie']); }); it('should search in specific fields when filtering with a predicate object', function() { input('search.$').enter('i'); expect(repeater('#searchObjResults tr', 'friend in friends').column('friend.name')). toEqual(['Mary', 'Mike', 'Julie']); }); </doc:scenario> </doc:example> */ function filterFilter() { return function(array, expression) { if (!(array instanceof Array)) return array; var predicates = []; predicates.check = function(value) { for (var j = 0; j < predicates.length; j++) { if(!predicates[j](value)) { return false; } } return true; }; var search = function(obj, text){ if (text.charAt(0) === '!') { return !search(obj, text.substr(1)); } switch (typeof obj) { case "boolean": case "number": case "string": return ('' + obj).toLowerCase().indexOf(text) > -1; case "object": for ( var objKey in obj) { if (objKey.charAt(0) !== '$' && search(obj[objKey], text)) { return true; } } return false; case "array": for ( var i = 0; i < obj.length; i++) { if (search(obj[i], text)) { return true; } } return false; default: return false; } }; switch (typeof expression) { case "boolean": case "number": case "string": expression = {$:expression}; case "object": for (var key in expression) { if (key == '$') { (function() { var text = (''+expression[key]).toLowerCase(); if (!text) return; predicates.push(function(value) { return search(value, text); }); })(); } else { (function() { var path = key; var text = (''+expression[key]).toLowerCase(); if (!text) return; predicates.push(function(value) { return search(getter(value, path), text); }); })(); } } break; case 'function': predicates.push(expression); break; default: return array; } var filtered = []; for ( var j = 0; j < array.length; j++) { var value = array[j]; if (predicates.check(value)) { filtered.push(value); } } return filtered; } } /** * @ngdoc filter * @name angular.module.ng.$filter.currency * @function * * @description * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default * symbol for current locale is used. * * @param {number} amount Input to filter. * @param {string=} symbol Currency symbol or identifier to be displayed. * @returns {string} Formatted number. * * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.amount = 1234.56; } </script> <div ng-controller="Ctrl"> <input type="number" ng-model="amount"> <br> default currency symbol ($): {{amount | currency}}<br> custom currency identifier (USD$): {{amount | currency:"USD$"}} </div> </doc:source> <doc:scenario> it('should init with 1234.56', function() { expect(binding('amount | currency')).toBe('$1,234.56'); expect(binding('amount | currency:"USD$"')).toBe('USD$1,234.56'); }); it('should update', function() { input('amount').enter('-1234'); expect(binding('amount | currency')).toBe('($1,234.00)'); expect(binding('amount | currency:"USD$"')).toBe('(USD$1,234.00)'); }); </doc:scenario> </doc:example> */ currencyFilter.$inject = ['$locale']; function currencyFilter($locale) { var formats = $locale.NUMBER_FORMATS; return function(amount, currencySymbol){ if (isUndefined(currencySymbol)) currencySymbol = formats.CURRENCY_SYM; return formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, 2). replace(/\u00A4/g, currencySymbol); }; } /** * @ngdoc filter * @name angular.module.ng.$filter.number * @function * * @description * Formats a number as text. * * If the input is not a number an empty string is returned. * * @param {number|string} number Number to format. * @param {(number|string)=} [fractionSize=2] Number of decimal places to round the number to. * @returns {string} Number rounded to decimalPlaces and places a “,” after each third digit. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.val = 1234.56789; } </script> <div ng-controller="Ctrl"> Enter number: <input ng-model='val'><br> Default formatting: {{val | number}}<br> No fractions: {{val | number:0}}<br> Negative number: {{-val | number:4}} </div> </doc:source> <doc:scenario> it('should format numbers', function() { expect(binding('val | number')).toBe('1,234.568'); expect(binding('val | number:0')).toBe('1,235'); expect(binding('-val | number:4')).toBe('-1,234.5679'); }); it('should update', function() { input('val').enter('3374.333'); expect(binding('val | number')).toBe('3,374.333'); expect(binding('val | number:0')).toBe('3,374'); expect(binding('-val | number:4')).toBe('-3,374.3330'); }); </doc:scenario> </doc:example> */ numberFilter.$inject = ['$locale']; function numberFilter($locale) { var formats = $locale.NUMBER_FORMATS; return function(number, fractionSize) { return formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP, fractionSize); }; } var DECIMAL_SEP = '.'; function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) { if (isNaN(number) || !isFinite(number)) return ''; var isNegative = number < 0; number = Math.abs(number); var numStr = number + '', formatedText = '', parts = []; if (numStr.indexOf('e') !== -1) { formatedText = numStr; } else { var fractionLen = (numStr.split(DECIMAL_SEP)[1] || '').length; // determine fractionSize if it is not specified if (isUndefined(fractionSize)) { fractionSize = Math.min(Math.max(pattern.minFrac, fractionLen), pattern.maxFrac); } var pow = Math.pow(10, fractionSize); number = Math.round(number * pow) / pow; var fraction = ('' + number).split(DECIMAL_SEP); var whole = fraction[0]; fraction = fraction[1] || ''; var pos = 0, lgroup = pattern.lgSize, group = pattern.gSize; if (whole.length >= (lgroup + group)) { pos = whole.length - lgroup; for (var i = 0; i < pos; i++) { if ((pos - i)%group === 0 && i !== 0) { formatedText += groupSep; } formatedText += whole.charAt(i); } } for (i = pos; i < whole.length; i++) { if ((whole.length - i)%lgroup === 0 && i !== 0) { formatedText += groupSep; } formatedText += whole.charAt(i); } // format fraction part. while(fraction.length < fractionSize) { fraction += '0'; } if (fractionSize) formatedText += decimalSep + fraction.substr(0, fractionSize); } parts.push(isNegative ? pattern.negPre : pattern.posPre); parts.push(formatedText); parts.push(isNegative ? pattern.negSuf : pattern.posSuf); return parts.join(''); } function padNumber(num, digits, trim) { var neg = ''; if (num < 0) { neg = '-'; num = -num; } num = '' + num; while(num.length < digits) num = '0' + num; if (trim) num = num.substr(num.length - digits); return neg + num; } function dateGetter(name, size, offset, trim) { return function(date) { var value = date['get' + name](); if (offset > 0 || value > -offset) value += offset; if (value === 0 && offset == -12 ) value = 12; return padNumber(value, size, trim); }; } function dateStrGetter(name, shortForm) { return function(date, formats) { var value = date['get' + name](); var get = uppercase(shortForm ? ('SHORT' + name) : name); return formats[get][value]; }; } function timeZoneGetter(date) { var offset = date.getTimezoneOffset(); return padNumber(offset / 60, 2) + padNumber(Math.abs(offset % 60), 2); } function ampmGetter(date, formats) { return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1]; } var DATE_FORMATS = { yyyy: dateGetter('FullYear', 4), yy: dateGetter('FullYear', 2, 0, true), y: dateGetter('FullYear', 1), MMMM: dateStrGetter('Month'), MMM: dateStrGetter('Month', true), MM: dateGetter('Month', 2, 1), M: dateGetter('Month', 1, 1), dd: dateGetter('Date', 2), d: dateGetter('Date', 1), HH: dateGetter('Hours', 2), H: dateGetter('Hours', 1), hh: dateGetter('Hours', 2, -12), h: dateGetter('Hours', 1, -12), mm: dateGetter('Minutes', 2), m: dateGetter('Minutes', 1), ss: dateGetter('Seconds', 2), s: dateGetter('Seconds', 1), EEEE: dateStrGetter('Day'), EEE: dateStrGetter('Day', true), a: ampmGetter, Z: timeZoneGetter }; var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZE']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z))(.*)/, NUMBER_STRING = /^\d+$/; /** * @ngdoc filter * @name angular.module.ng.$filter.date * @function * * @description * Formats `date` to a string based on the requested `format`. * * `format` string can be composed of the following elements: * * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010) * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10) * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199) * * `'MMMM'`: Month in year (January-December) * * `'MMM'`: Month in year (Jan-Dec) * * `'MM'`: Month in year, padded (01-12) * * `'M'`: Month in year (1-12) * * `'dd'`: Day in month, padded (01-31) * * `'d'`: Day in month (1-31) * * `'EEEE'`: Day in Week,(Sunday-Saturday) * * `'EEE'`: Day in Week, (Sun-Sat) * * `'HH'`: Hour in day, padded (00-23) * * `'H'`: Hour in day (0-23) * * `'hh'`: Hour in am/pm, padded (01-12) * * `'h'`: Hour in am/pm, (1-12) * * `'mm'`: Minute in hour, padded (00-59) * * `'m'`: Minute in hour (0-59) * * `'ss'`: Second in minute, padded (00-59) * * `'s'`: Second in minute (0-59) * * `'a'`: am/pm marker * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-1200) * * `format` string can also be one of the following predefined * {@link guide/dev_guide.i18n localizable formats}: * * * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale * (e.g. Sep 3, 2010 12:05:08 pm) * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 pm) * * `'fullDate'`: equivalent to `'EEEE, MMMM d,y'` for en_US locale * (e.g. Friday, September 3, 2010) * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010 * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010) * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10) * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 pm) * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 pm) * * `format` string can contain literal values. These need to be quoted with single quotes (e.g. * `"h 'in the morning'"`). In order to output single quote, use two single quotes in a sequence * (e.g. `"h o''clock"`). * * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.SSSZ and it's * shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). * @param {string=} format Formatting rules (see Description). If not specified, * `mediumDate` is used. * @returns {string} Formatted string or the input if input is not recognized as date/millis. * * @example <doc:example> <doc:source> <span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>: {{1288323623006 | date:'medium'}}<br> <span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>: {{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}<br> <span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>: {{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}<br> </doc:source> <doc:scenario> it('should format date', function() { expect(binding("1288323623006 | date:'medium'")). toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/); expect(binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")). toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} \-?\d{4}/); expect(binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")). toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/); }); </doc:scenario> </doc:example> */ dateFilter.$inject = ['$locale']; function dateFilter($locale) { var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d{3}))?)?)?(Z|([+-])(\d\d):?(\d\d)))?$/; function jsonStringToDate(string){ var match; if (match = string.match(R_ISO8601_STR)) { var date = new Date(0), tzHour = 0, tzMin = 0; if (match[9]) { tzHour = int(match[9] + match[10]); tzMin = int(match[9] + match[11]); } date.setUTCFullYear(int(match[1]), int(match[2]) - 1, int(match[3])); date.setUTCHours(int(match[4]||0) - tzHour, int(match[5]||0) - tzMin, int(match[6]||0), int(match[7]||0)); return date; } return string; } return function(date, format) { var text = '', parts = [], fn, match; format = format || 'mediumDate'; format = $locale.DATETIME_FORMATS[format] || format; if (isString(date)) { if (NUMBER_STRING.test(date)) { date = int(date); } else { date = jsonStringToDate(date); } } if (isNumber(date)) { date = new Date(date); } if (!isDate(date)) { return date; } while(format) { match = DATE_FORMATS_SPLIT.exec(format); if (match) { parts = concat(parts, match, 1); format = parts.pop(); } else { parts.push(format); format = null; } } forEach(parts, function(value){ fn = DATE_FORMATS[value]; text += fn ? fn(date, $locale.DATETIME_FORMATS) : value.replace(/(^'|'$)/g, '').replace(/''/g, "'"); }); return text; }; } /** * @ngdoc filter * @name angular.module.ng.$filter.json * @function * * @description * Allows you to convert a JavaScript object into JSON string. * * This filter is mostly useful for debugging. When using the double curly {{value}} notation * the binding is automatically converted to JSON. * * @param {*} object Any JavaScript object (including arrays and primitive types) to filter. * @returns {string} JSON string. * * * @example: <doc:example> <doc:source> <pre>{{ {'name':'value'} | json }}</pre> </doc:source> <doc:scenario> it('should jsonify filtered objects', function() { expect(binding("{'name':'value'}")).toMatch(/\{\n "name": ?"value"\n}/); }); </doc:scenario> </doc:example> * */ function jsonFilter() { return function(object) { return toJson(object, true); }; } /** * @ngdoc filter * @name angular.module.ng.$filter.lowercase * @function * @description * Converts string to lowercase. * @see angular.lowercase */ var lowercaseFilter = valueFn(lowercase); /** * @ngdoc filter * @name angular.module.ng.$filter.uppercase * @function * @description * Converts string to uppercase. * @see angular.uppercase */ var uppercaseFilter = valueFn(uppercase); /** * @ngdoc function * @name angular.module.ng.$filter.limitTo * @function * * @description * Creates a new array containing only a specified number of elements in an array. The elements * are taken from either the beginning or the end of the source array, as specified by the * value and sign (positive or negative) of `limit`. * * Note: This function is used to augment the `Array` type in Angular expressions. See * {@link angular.module.ng.$filter} for more information about Angular arrays. * * @param {Array} array Source array to be limited. * @param {string|Number} limit The length of the returned array. If the `limit` number is * positive, `limit` number of items from the beginning of the source array are copied. * If the number is negative, `limit` number of items from the end of the source array are * copied. The `limit` will be trimmed if it exceeds `array.length` * @returns {Array} A new sub-array of length `limit` or less if input array had less than `limit` * elements. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.numbers = [1,2,3,4,5,6,7,8,9]; $scope.limit = 3; } </script> <div ng-controller="Ctrl"> Limit {{numbers}} to: <input type="integer" ng-model="limit"> <p>Output: {{ numbers | limitTo:limit }}</p> </div> </doc:source> <doc:scenario> it('should limit the numer array to first three items', function() { expect(element('.doc-example-live input[ng-model=limit]').val()).toBe('3'); expect(binding('numbers | limitTo:limit')).toEqual('[1,2,3]'); }); it('should update the output when -3 is entered', function() { input('limit').enter(-3); expect(binding('numbers | limitTo:limit')).toEqual('[7,8,9]'); }); it('should not exceed the maximum size of input array', function() { input('limit').enter(100); expect(binding('numbers | limitTo:limit')).toEqual('[1,2,3,4,5,6,7,8,9]'); }); </doc:scenario> </doc:example> */ function limitToFilter(){ return function(array, limit) { if (!(array instanceof Array)) return array; limit = int(limit); var out = [], i, n; // check that array is iterable if (!array || !(array instanceof Array)) return out; // if abs(limit) exceeds maximum length, trim it if (limit > array.length) limit = array.length; else if (limit < -array.length) limit = -array.length; if (limit > 0) { i = 0; n = limit; } else { i = array.length + limit; n = array.length; } for (; i<n; i++) { out.push(array[i]); } return out; } } /** * @ngdoc function * @name angular.module.ng.$filter.orderBy * @function * * @description * Orders a specified `array` by the `expression` predicate. * * Note: this function is used to augment the `Array` type in Angular expressions. See * {@link angular.module.ng.$filter} for more informaton about Angular arrays. * * @param {Array} array The array to sort. * @param {function(*)|string|Array.<(function(*)|string)>} expression A predicate to be * used by the comparator to determine the order of elements. * * Can be one of: * * - `function`: Getter function. The result of this function will be sorted using the * `<`, `=`, `>` operator. * - `string`: An Angular expression which evaluates to an object to order by, such as 'name' * to sort by a property called 'name'. Optionally prefixed with `+` or `-` to control * ascending or descending sort order (for example, +name or -name). * - `Array`: An array of function or string predicates. The first predicate in the array * is used for sorting, but when two items are equivalent, the next predicate is used. * * @param {boolean=} reverse Reverse the order the array. * @returns {Array} Sorted copy of the source array. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.friends = [{name:'John', phone:'555-1212', age:10}, {name:'Mary', phone:'555-9876', age:19}, {name:'Mike', phone:'555-4321', age:21}, {name:'Adam', phone:'555-5678', age:35}, {name:'Julie', phone:'555-8765', age:29}] $scope.predicate = '-age'; } </script> <div ng-controller="Ctrl"> <pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre> <hr/> [ <a href="" ng-click="predicate=''">unsorted</a> ] <table class="friend"> <tr> <th><a href="" ng-click="predicate = 'name'; reverse=false">Name</a> (<a href ng-click="predicate = '-name'; reverse=false">^</a>)</th> <th><a href="" ng-click="predicate = 'phone'; reverse=!reverse">Phone Number</a></th> <th><a href="" ng-click="predicate = 'age'; reverse=!reverse">Age</a></th> <tr> <tr ng-repeat="friend in friends | orderBy:predicate:reverse"> <td>{{friend.name}}</td> <td>{{friend.phone}}</td> <td>{{friend.age}}</td> <tr> </table> </div> </doc:source> <doc:scenario> it('should be reverse ordered by aged', function() { expect(binding('predicate')).toBe('-age'); expect(repeater('table.friend', 'friend in friends').column('friend.age')). toEqual(['35', '29', '21', '19', '10']); expect(repeater('table.friend', 'friend in friends').column('friend.name')). toEqual(['Adam', 'Julie', 'Mike', 'Mary', 'John']); }); it('should reorder the table when user selects different predicate', function() { element('.doc-example-live a:contains("Name")').click(); expect(repeater('table.friend', 'friend in friends').column('friend.name')). toEqual(['Adam', 'John', 'Julie', 'Mary', 'Mike']); expect(repeater('table.friend', 'friend in friends').column('friend.age')). toEqual(['35', '10', '29', '19', '21']); element('.doc-example-live a:contains("Phone")').click(); expect(repeater('table.friend', 'friend in friends').column('friend.phone')). toEqual(['555-9876', '555-8765', '555-5678', '555-4321', '555-1212']); expect(repeater('table.friend', 'friend in friends').column('friend.name')). toEqual(['Mary', 'Julie', 'Adam', 'Mike', 'John']); }); </doc:scenario> </doc:example> */ orderByFilter.$inject = ['$parse']; function orderByFilter($parse){ return function(array, sortPredicate, reverseOrder) { if (!(array instanceof Array)) return array; if (!sortPredicate) return array; sortPredicate = isArray(sortPredicate) ? sortPredicate: [sortPredicate]; sortPredicate = map(sortPredicate, function(predicate){ var descending = false, get = predicate || identity; if (isString(predicate)) { if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) { descending = predicate.charAt(0) == '-'; predicate = predicate.substring(1); } get = $parse(predicate); } return reverseComparator(function(a,b){ return compare(get(a),get(b)); }, descending); }); var arrayCopy = []; for ( var i = 0; i < array.length; i++) { arrayCopy.push(array[i]); } return arrayCopy.sort(reverseComparator(comparator, reverseOrder)); function comparator(o1, o2){ for ( var i = 0; i < sortPredicate.length; i++) { var comp = sortPredicate[i](o1, o2); if (comp !== 0) return comp; } return 0; } function reverseComparator(comp, descending) { return toBoolean(descending) ? function(a,b){return comp(b,a);} : comp; } function compare(v1, v2){ var t1 = typeof v1; var t2 = typeof v2; if (t1 == t2) { if (t1 == "string") v1 = v1.toLowerCase(); if (t1 == "string") v2 = v2.toLowerCase(); if (v1 === v2) return 0; return v1 < v2 ? -1 : 1; } else { return t1 < t2 ? -1 : 1; } } } } function ngDirective(directive) { if (isFunction(directive)) { directive = { link: directive } } directive.restrict = directive.restrict || 'AC'; return valueFn(directive); } /* * Modifies the default behavior of html A tag, so that the default action is prevented when href * attribute is empty. * * The reasoning for this change is to allow easy creation of action links with `ngClick` directive * without changing the location or causing page reloads, e.g.: * <a href="" ng-click="model.$save()">Save</a> */ var htmlAnchorDirective = valueFn({ restrict: 'E', compile: function(element, attr) { // turn <a href ng-click="..">link</a> into a link in IE // but only if it doesn't have name attribute, in which case it's an anchor if (!attr.href) { attr.$set('href', ''); } return function(scope, element) { element.bind('click', function(event){ // if we have no href url, then don't navigate anywhere. if (!element.attr('href')) { event.preventDefault(); } }); } } }); /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngHref * @restrict A * * @description * Using Angular markup like {{hash}} in an href attribute makes * the page open to a wrong URL, if the user clicks that link before * angular has a chance to replace the {{hash}} with actual URL, the * link will be broken and will most likely return a 404 error. * The `ngHref` directive solves this problem. * * The buggy way to write it: * <pre> * <a href="http://www.gravatar.com/avatar/{{hash}}"/> * </pre> * * The correct way to write it: * <pre> * <a ng-href="http://www.gravatar.com/avatar/{{hash}}"/> * </pre> * * @element A * @param {template} ngHref any string which can contain `{{}}` markup. * * @example * This example uses `link` variable inside `href` attribute: <doc:example> <doc:source> <input ng-model="value" /><br /> <a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br /> <a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br /> <a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, reload!)<br /> <a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br /> <a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br /> <a id="link-6" ng-href="{{value}}">link</a> (link, change location) </doc:source> <doc:scenario> it('should execute ng-click but not reload when href without value', function() { element('#link-1').click(); expect(input('value').val()).toEqual('1'); expect(element('#link-1').attr('href')).toBe(""); }); it('should execute ng-click but not reload when href empty string', function() { element('#link-2').click(); expect(input('value').val()).toEqual('2'); expect(element('#link-2').attr('href')).toBe(""); }); it('should execute ng-click and change url when ng-href specified', function() { expect(element('#link-3').attr('href')).toBe("/123"); element('#link-3').click(); expect(browser().window().path()).toEqual('/123'); }); it('should execute ng-click but not reload when href empty string and name specified', function() { element('#link-4').click(); expect(input('value').val()).toEqual('4'); expect(element('#link-4').attr('href')).toBe(''); }); it('should execute ng-click but not reload when no href but name specified', function() { element('#link-5').click(); expect(input('value').val()).toEqual('5'); expect(element('#link-5').attr('href')).toBe(''); }); it('should only change url when only ng-href', function() { input('value').enter('6'); expect(element('#link-6').attr('href')).toBe('6'); element('#link-6').click(); expect(browser().location().url()).toEqual('/6'); }); </doc:scenario> </doc:example> */ /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngSrc * @restrict A * * @description * Using Angular markup like `{{hash}}` in a `src` attribute doesn't * work right: The browser will fetch from the URL with the literal * text `{{hash}}` until Angular replaces the expression inside * `{{hash}}`. The `ngSrc` directive solves this problem. * * The buggy way to write it: * <pre> * <img src="http://www.gravatar.com/avatar/{{hash}}"/> * </pre> * * The correct way to write it: * <pre> * <img ng-src="http://www.gravatar.com/avatar/{{hash}}"/> * </pre> * * @element IMG * @param {template} ngSrc any string which can contain `{{}}` markup. */ /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngDisabled * @restrict A * * @description * * The following markup will make the button enabled on Chrome/Firefox but not on IE8 and older IEs: * <pre> * <div ng-init="scope = { isDisabled: false }"> * <button disabled="{{scope.isDisabled}}">Disabled</button> * </div> * </pre> * * The HTML specs do not require browsers to preserve the special attributes such as disabled. * (The presence of them means true and absence means false) * This prevents the angular compiler from correctly retrieving the binding expression. * To solve this problem, we introduce the `ngDisabled` directive. * * @example <doc:example> <doc:source> Click me to toggle: <input type="checkbox" ng-model="checked"><br/> <button ng-model="button" ng-disabled="checked">Button</button> </doc:source> <doc:scenario> it('should toggle button', function() { expect(element('.doc-example-live :button').prop('disabled')).toBeFalsy(); input('checked').check(); expect(element('.doc-example-live :button').prop('disabled')).toBeTruthy(); }); </doc:scenario> </doc:example> * * @element INPUT * @param {expression} ngDisabled Angular expression that will be evaluated. */ /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngChecked * @restrict A * * @description * The HTML specs do not require browsers to preserve the special attributes such as checked. * (The presence of them means true and absence means false) * This prevents the angular compiler from correctly retrieving the binding expression. * To solve this problem, we introduce the `ngChecked` directive. * @example <doc:example> <doc:source> Check me to check both: <input type="checkbox" ng-model="master"><br/> <input id="checkSlave" type="checkbox" ng-checked="master"> </doc:source> <doc:scenario> it('should check both checkBoxes', function() { expect(element('.doc-example-live #checkSlave').prop('checked')).toBeFalsy(); input('master').check(); expect(element('.doc-example-live #checkSlave').prop('checked')).toBeTruthy(); }); </doc:scenario> </doc:example> * * @element INPUT * @param {expression} ngChecked Angular expression that will be evaluated. */ /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngMultiple * @restrict A * * @description * The HTML specs do not require browsers to preserve the special attributes such as multiple. * (The presence of them means true and absence means false) * This prevents the angular compiler from correctly retrieving the binding expression. * To solve this problem, we introduce the `ngMultiple` directive. * * @example <doc:example> <doc:source> Check me check multiple: <input type="checkbox" ng-model="checked"><br/> <select id="select" ng-multiple="checked"> <option>Misko</option> <option>Igor</option> <option>Vojta</option> <option>Di</option> </select> </doc:source> <doc:scenario> it('should toggle multiple', function() { expect(element('.doc-example-live #select').prop('multiple')).toBeFalsy(); input('checked').check(); expect(element('.doc-example-live #select').prop('multiple')).toBeTruthy(); }); </doc:scenario> </doc:example> * * @element SELECT * @param {expression} ngMultiple Angular expression that will be evaluated. */ /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngReadonly * @restrict A * * @description * The HTML specs do not require browsers to preserve the special attributes such as readonly. * (The presence of them means true and absence means false) * This prevents the angular compiler from correctly retrieving the binding expression. * To solve this problem, we introduce the `ngReadonly` directive. * @example <doc:example> <doc:source> Check me to make text readonly: <input type="checkbox" ng-model="checked"><br/> <input type="text" ng-readonly="checked" value="I'm Angular"/> </doc:source> <doc:scenario> it('should toggle readonly attr', function() { expect(element('.doc-example-live :text').prop('readonly')).toBeFalsy(); input('checked').check(); expect(element('.doc-example-live :text').prop('readonly')).toBeTruthy(); }); </doc:scenario> </doc:example> * * @element INPUT * @param {string} expression Angular expression that will be evaluated. */ /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngSelected * @restrict A * * @description * The HTML specs do not require browsers to preserve the special attributes such as selected. * (The presence of them means true and absence means false) * This prevents the angular compiler from correctly retrieving the binding expression. * To solve this problem, we introduced the `ngSelected` directive. * @example <doc:example> <doc:source> Check me to select: <input type="checkbox" ng-model="selected"><br/> <select> <option>Hello!</option> <option id="greet" ng-selected="selected">Greetings!</option> </select> </doc:source> <doc:scenario> it('should select Greetings!', function() { expect(element('.doc-example-live #greet').prop('selected')).toBeFalsy(); input('selected').check(); expect(element('.doc-example-live #greet').prop('selected')).toBeTruthy(); }); </doc:scenario> </doc:example> * * @element OPTION * @param {string} expression Angular expression that will be evaluated. */ var ngAttributeAliasDirectives = {}; // boolean attrs are evaluated forEach(BOOLEAN_ATTR, function(propName, attrName) { var normalized = directiveNormalize('ng-' + attrName); ngAttributeAliasDirectives[normalized] = function() { return { priority: 100, compile: function() { return function(scope, element, attr) { attr.$$observers[attrName] = []; scope.$watch(attr[normalized], function(value) { attr.$set(attrName, !!value); }); }; } }; }; }); // ng-src, ng-href are interpolated forEach(['src', 'href'], function(attrName) { var normalized = directiveNormalize('ng-' + attrName); ngAttributeAliasDirectives[normalized] = function() { return { priority: 99, // it needs to run after the attributes are interpolated compile: function() { return function(scope, element, attr) { var value = attr[normalized]; if (value == undefined) { // undefined value means that the directive is being interpolated // so just register observer attr.$$observers[attrName] = []; attr.$observe(normalized, function(value) { attr.$set(attrName, value); }); } else { // value present means that no interpolation, so copy to native attribute. attr.$set(attrName, value); } }; } }; }; }); var nullFormCtrl = { $addControl: noop, $removeControl: noop, $setValidity: noop, $setDirty: noop }; /** * @ngdoc object * @name angular.module.ng.$compileProvider.directive.form.FormController * * @property {boolean} $pristine True if user has not interacted with the form yet. * @property {boolean} $dirty True if user has already interacted with the form. * @property {boolean} $valid True if all of the containg forms and controls are valid. * @property {boolean} $invalid True if at least one containing control or form is invalid. * * @property {Object} $error Is an object hash, containing references to all invalid controls or * forms, where: * * - keys are validation tokens (error names) — such as `REQUIRED`, `URL` or `EMAIL`), * - values are arrays of controls or forms that are invalid with given error. * * @description * `FormController` keeps track of all its controls and nested forms as well as state of them, * such as being valid/invalid or dirty/pristine. * * Each {@link angular.module.ng.$compileProvider.directive.form form} directive creates an instance * of `FormController`. * */ //asks for $scope to fool the BC controller module FormController.$inject = ['$element', '$attrs', '$scope']; function FormController(element, attrs) { var form = this, parentForm = element.parent().controller('form') || nullFormCtrl, invalidCount = 0, // used to easily determine if we are valid errors = form.$error = {}; // init state form.$name = attrs.name; form.$dirty = false; form.$pristine = true; form.$valid = true; form.$invalid = false; parentForm.$addControl(form); // Setup initial state of the control element.addClass(PRISTINE_CLASS); toggleValidCss(true); // convenience method for easy toggling of classes function toggleValidCss(isValid, validationErrorKey) { validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : ''; element. removeClass((isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey). addClass((isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey); } form.$addControl = function(control) { if (control.$name && !form.hasOwnProperty(control.$name)) { form[control.$name] = control; } }; form.$removeControl = function(control) { if (control.$name && form[control.$name] === control) { delete form[control.$name]; } forEach(errors, function(queue, validationToken) { form.$setValidity(validationToken, true, control); }); }; form.$setValidity = function(validationToken, isValid, control) { var queue = errors[validationToken]; if (isValid) { if (queue) { arrayRemove(queue, control); if (!queue.length) { invalidCount--; if (!invalidCount) { toggleValidCss(isValid); form.$valid = true; form.$invalid = false; } errors[validationToken] = false; toggleValidCss(true, validationToken); parentForm.$setValidity(validationToken, true, form); } } } else { if (!invalidCount) { toggleValidCss(isValid); } if (queue) { if (includes(queue, control)) return; } else { errors[validationToken] = queue = []; invalidCount++; toggleValidCss(false, validationToken); parentForm.$setValidity(validationToken, false, form); } queue.push(control); form.$valid = false; form.$invalid = true; } }; form.$setDirty = function() { element.removeClass(PRISTINE_CLASS).addClass(DIRTY_CLASS); form.$dirty = true; form.$pristine = false; }; } /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngForm * @restrict EAC * * @description * Nestable alias of {@link angular.module.ng.$compileProvider.directive.form `form`} directive. HTML * does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a * sub-group of controls needs to be determined. * * @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into * related scope, under this name. * */ /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.form * @restrict E * * @description * Directive that instantiates * {@link angular.module.ng.$compileProvider.directive.form.FormController FormController}. * * If `name` attribute is specified, the form controller is published onto the current scope under * this name. * * # Alias: {@link angular.module.ng.$compileProvider.directive.ngForm `ngForm`} * * In angular forms can be nested. This means that the outer form is valid when all of the child * forms are valid as well. However browsers do not allow nesting of `<form>` elements, for this * reason angular provides {@link angular.module.ng.$compileProvider.directive.ngForm `ngForm`} alias * which behaves identical to `<form>` but allows form nesting. * * * # CSS classes * - `ng-valid` Is set if the form is valid. * - `ng-invalid` Is set if the form is invalid. * - `ng-pristine` Is set if the form is pristine. * - `ng-dirty` Is set if the form is dirty. * * * # Submitting a form and preventing default action * * Since the role of forms in client-side Angular applications is different than in classical * roundtrip apps, it is desirable for the browser not to translate the form submission into a full * page reload that sends the data to the server. Instead some javascript logic should be triggered * to handle the form submission in application specific way. * * For this reason, Angular prevents the default action (form submission to the server) unless the * `<form>` element has an `action` attribute specified. * * You can use one of the following two ways to specify what javascript method should be called when * a form is submitted: * * - {@link angular.module.ng.$compileProvider.directive.ngSubmit ngSubmit} directive on the form element * - {@link angular.module.ng.$compileProvider.directive.ngClick ngClick} directive on the first * button or input field of type submit (input[type=submit]) * * To prevent double execution of the handler, use only one of ngSubmit or ngClick directives. This * is because of the following form submission rules coming from the html spec: * * - If a form has only one input field then hitting enter in this field triggers form submit * (`ngSubmit`) * - if a form has has 2+ input fields and no buttons or input[type=submit] then hitting enter * doesn't trigger submit * - if a form has one or more input fields and one or more buttons or input[type=submit] then * hitting enter in any of the input fields will trigger the click handler on the *first* button or * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`) * * @param {string=} name Name of the form. If specified, the form controller will be published into * related scope, under this name. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.userType = 'guest'; } </script> <form name="myForm" ng-controller="Ctrl"> userType: <input name="input" ng-model="userType" required> <span class="error" ng-show="myForm.input.$error.REQUIRED">Required!</span><br> <tt>userType = {{userType}}</tt><br> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br> <tt>myForm.$valid = {{myForm.$valid}}</tt><br> <tt>myForm.$error.REQUIRED = {{!!myForm.$error.REQUIRED}}</tt><br> </form> </doc:source> <doc:scenario> it('should initialize to model', function() { expect(binding('userType')).toEqual('guest'); expect(binding('myForm.input.$valid')).toEqual('true'); }); it('should be invalid if empty', function() { input('userType').enter(''); expect(binding('userType')).toEqual(''); expect(binding('myForm.input.$valid')).toEqual('false'); }); </doc:scenario> </doc:example> */ var formDirectiveDir = { name: 'form', restrict: 'E', controller: FormController, compile: function() { return { pre: function(scope, formElement, attr, controller) { if (!attr.action) { formElement.bind('submit', function(event) { event.preventDefault(); }); } var parentFormCtrl = formElement.parent().controller('form'), alias = attr.name || attr.ngForm; if (alias) { scope[alias] = controller; } if (parentFormCtrl) { formElement.bind('$destroy', function() { parentFormCtrl.$removeControl(controller); if (alias) { scope[alias] = undefined; } extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards }); } } }; } }; var formDirective = valueFn(formDirectiveDir); var ngFormDirective = valueFn(extend(copy(formDirectiveDir), {restrict: 'EAC'})); var URL_REGEXP = /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/; var EMAIL_REGEXP = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/; var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))\s*$/; var inputType = { /** * @ngdoc inputType * @name angular.module.ng.$compileProvider.directive.input.text * * @description * Standard HTML text input with angular data binding. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} required Sets `required` validation error key if the value is not entered. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than * minlength. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than * maxlength. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for * patterns defined as scope expressions. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.text = 'guest'; $scope.word = /^\w*$/; } </script> <form name="myForm" ng-controller="Ctrl"> Single word: <input type="text" name="input" ng-model="text" ng-pattern="word" required> <span class="error" ng-show="myForm.input.$error.required"> Required!</span> <span class="error" ng-show="myForm.input.$error.pattern"> Single word only!</span> <tt>text = {{text}}</tt><br/> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> </form> </doc:source> <doc:scenario> it('should initialize to model', function() { expect(binding('text')).toEqual('guest'); expect(binding('myForm.input.$valid')).toEqual('true'); }); it('should be invalid if empty', function() { input('text').enter(''); expect(binding('text')).toEqual(''); expect(binding('myForm.input.$valid')).toEqual('false'); }); it('should be invalid if multi word', function() { input('text').enter('hello world'); expect(binding('myForm.input.$valid')).toEqual('false'); }); </doc:scenario> </doc:example> */ 'text': textInputType, /** * @ngdoc inputType * @name angular.module.ng.$compileProvider.directive.input.number * * @description * Text input with number validation and transformation. Sets the `number` validation * error if not a valid number. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} min Sets the `min` validation error key if the value entered is less then `min`. * @param {string=} max Sets the `max` validation error key if the value entered is greater then `min`. * @param {string=} required Sets `required` validation error key if the value is not entered. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than * minlength. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than * maxlength. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for * patterns defined as scope expressions. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.value = 12; } </script> <form name="myForm" ng-controller="Ctrl"> Number: <input type="number" name="input" ng-model="value" min="0" max="99" required> <span class="error" ng-show="myForm.list.$error.required"> Required!</span> <span class="error" ng-show="myForm.list.$error.number"> Not valid number!</span> <tt>value = {{value}}</tt><br/> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> </form> </doc:source> <doc:scenario> it('should initialize to model', function() { expect(binding('value')).toEqual('12'); expect(binding('myForm.input.$valid')).toEqual('true'); }); it('should be invalid if empty', function() { input('value').enter(''); expect(binding('value')).toEqual(''); expect(binding('myForm.input.$valid')).toEqual('false'); }); it('should be invalid if over max', function() { input('value').enter('123'); expect(binding('value')).toEqual(''); expect(binding('myForm.input.$valid')).toEqual('false'); }); </doc:scenario> </doc:example> */ 'number': numberInputType, /** * @ngdoc inputType * @name angular.module.ng.$compileProvider.directive.input.url * * @description * Text input with URL validation. Sets the `url` validation error key if the content is not a * valid URL. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} required Sets `required` validation error key if the value is not entered. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than * minlength. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than * maxlength. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for * patterns defined as scope expressions. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.text = 'http://google.com'; } </script> <form name="myForm" ng-controller="Ctrl"> URL: <input type="url" name="input" ng-model="text" required> <span class="error" ng-show="myForm.input.$error.required"> Required!</span> <span class="error" ng-show="myForm.input.$error.url"> Not valid url!</span> <tt>text = {{text}}</tt><br/> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> <tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/> </form> </doc:source> <doc:scenario> it('should initialize to model', function() { expect(binding('text')).toEqual('http://google.com'); expect(binding('myForm.input.$valid')).toEqual('true'); }); it('should be invalid if empty', function() { input('text').enter(''); expect(binding('text')).toEqual(''); expect(binding('myForm.input.$valid')).toEqual('false'); }); it('should be invalid if not url', function() { input('text').enter('xxx'); expect(binding('myForm.input.$valid')).toEqual('false'); }); </doc:scenario> </doc:example> */ 'url': urlInputType, /** * @ngdoc inputType * @name angular.module.ng.$compileProvider.directive.input.email * * @description * Text input with email validation. Sets the `email` validation error key if not a valid email * address. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} required Sets `required` validation error key if the value is not entered. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than * minlength. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than * maxlength. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for * patterns defined as scope expressions. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.text = '[email protected]'; } </script> <form name="myForm" ng-controller="Ctrl"> Email: <input type="email" name="input" ng-model="text" required> <span class="error" ng-show="myForm.input.$error.required"> Required!</span> <span class="error" ng-show="myForm.input.$error.email"> Not valid email!</span> <tt>text = {{text}}</tt><br/> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> <tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/> </form> </doc:source> <doc:scenario> it('should initialize to model', function() { expect(binding('text')).toEqual('[email protected]'); expect(binding('myForm.input.$valid')).toEqual('true'); }); it('should be invalid if empty', function() { input('text').enter(''); expect(binding('text')).toEqual(''); expect(binding('myForm.input.$valid')).toEqual('false'); }); it('should be invalid if not email', function() { input('text').enter('xxx'); expect(binding('myForm.input.$valid')).toEqual('false'); }); </doc:scenario> </doc:example> */ 'email': emailInputType, /** * @ngdoc inputType * @name angular.module.ng.$compileProvider.directive.input.radio * * @description * HTML radio button. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string} value The value to which the expression should be set when selected. * @param {string=} name Property name of the form under which the control is published. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.color = 'blue'; } </script> <form name="myForm" ng-controller="Ctrl"> <input type="radio" ng-model="color" value="red"> Red <br/> <input type="radio" ng-model="color" value="green"> Green <br/> <input type="radio" ng-model="color" value="blue"> Blue <br/> <tt>color = {{color}}</tt><br/> </form> </doc:source> <doc:scenario> it('should change state', function() { expect(binding('color')).toEqual('blue'); input('color').select('red'); expect(binding('color')).toEqual('red'); }); </doc:scenario> </doc:example> */ 'radio': radioInputType, /** * @ngdoc inputType * @name angular.module.ng.$compileProvider.directive.input.checkbox * * @description * HTML checkbox. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} ngTrueValue The value to which the expression should be set when selected. * @param {string=} ngFalseValue The value to which the expression should be set when not selected. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.value1 = true; $scope.value2 = 'YES' } </script> <form name="myForm" ng-controller="Ctrl"> Value1: <input type="checkbox" ng-model="value1"> <br/> Value2: <input type="checkbox" ng-model="value2" ng-true-value="YES" ng-false-value="NO"> <br/> <tt>value1 = {{value1}}</tt><br/> <tt>value2 = {{value2}}</tt><br/> </form> </doc:source> <doc:scenario> it('should change state', function() { expect(binding('value1')).toEqual('true'); expect(binding('value2')).toEqual('YES'); input('value1').check(); input('value2').check(); expect(binding('value1')).toEqual('false'); expect(binding('value2')).toEqual('NO'); }); </doc:scenario> </doc:example> */ 'checkbox': checkboxInputType, 'hidden': noop, 'button': noop, 'submit': noop, 'reset': noop }; function isEmpty(value) { return isUndefined(value) || value === '' || value === null || value !== value; } function textInputType(scope, element, attr, ctrl, $sniffer, $browser) { var listener = function() { var value = trim(element.val()); if (ctrl.$viewValue !== value) { scope.$apply(function() { ctrl.$setViewValue(value); }); } }; // if the browser does support "input" event, we are fine if ($sniffer.hasEvent('input')) { element.bind('input', listener); } else { var timeout; element.bind('keydown', function(event) { var key = event.keyCode; // ignore // command modifiers arrows if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return; if (!timeout) { timeout = $browser.defer(function() { listener(); timeout = null; }); } }); // if user paste into input using mouse, we need "change" event to catch it element.bind('change', listener); } ctrl.$render = function() { element.val(isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue); }; // pattern validator var pattern = attr.ngPattern, patternValidator; var validate = function(regexp, value) { if (isEmpty(value) || regexp.test(value)) { ctrl.$setValidity('pattern', true); return value; } else { ctrl.$setValidity('pattern', false); return undefined; } }; if (pattern) { if (pattern.match(/^\/(.*)\/$/)) { pattern = new RegExp(pattern.substr(1, pattern.length - 2)); patternValidator = function(value) { return validate(pattern, value) }; } else { patternValidator = function(value) { var patternObj = scope.$eval(pattern); if (!patternObj || !patternObj.test) { throw new Error('Expected ' + pattern + ' to be a RegExp but was ' + patternObj); } return validate(patternObj, value); }; } ctrl.$formatters.push(patternValidator); ctrl.$parsers.push(patternValidator); } // min length validator if (attr.ngMinlength) { var minlength = int(attr.ngMinlength); var minLengthValidator = function(value) { if (!isEmpty(value) && value.length < minlength) { ctrl.$setValidity('minlength', false); return undefined; } else { ctrl.$setValidity('minlength', true); return value; } }; ctrl.$parsers.push(minLengthValidator); ctrl.$formatters.push(minLengthValidator); } // max length validator if (attr.ngMaxlength) { var maxlength = int(attr.ngMaxlength); var maxLengthValidator = function(value) { if (!isEmpty(value) && value.length > maxlength) { ctrl.$setValidity('maxlength', false); return undefined; } else { ctrl.$setValidity('maxlength', true); return value; } }; ctrl.$parsers.push(maxLengthValidator); ctrl.$formatters.push(maxLengthValidator); } } function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) { textInputType(scope, element, attr, ctrl, $sniffer, $browser); ctrl.$parsers.push(function(value) { var empty = isEmpty(value); if (empty || NUMBER_REGEXP.test(value)) { ctrl.$setValidity('number', true); return value === '' ? null : (empty ? value : parseFloat(value)); } else { ctrl.$setValidity('number', false); return undefined; } }); ctrl.$formatters.push(function(value) { return isEmpty(value) ? '' : '' + value; }); if (attr.min) { var min = parseFloat(attr.min); var minValidator = function(value) { if (!isEmpty(value) && value < min) { ctrl.$setValidity('min', false); return undefined; } else { ctrl.$setValidity('min', true); return value; } }; ctrl.$parsers.push(minValidator); ctrl.$formatters.push(minValidator); } if (attr.max) { var max = parseFloat(attr.max); var maxValidator = function(value) { if (!isEmpty(value) && value > max) { ctrl.$setValidity('max', false); return undefined; } else { ctrl.$setValidity('max', true); return value; } }; ctrl.$parsers.push(maxValidator); ctrl.$formatters.push(maxValidator); } ctrl.$formatters.push(function(value) { if (isEmpty(value) || isNumber(value)) { ctrl.$setValidity('number', true); return value; } else { ctrl.$setValidity('number', false); return undefined; } }); } function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) { textInputType(scope, element, attr, ctrl, $sniffer, $browser); var urlValidator = function(value) { if (isEmpty(value) || URL_REGEXP.test(value)) { ctrl.$setValidity('url', true); return value; } else { ctrl.$setValidity('url', false); return undefined; } }; ctrl.$formatters.push(urlValidator); ctrl.$parsers.push(urlValidator); } function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) { textInputType(scope, element, attr, ctrl, $sniffer, $browser); var emailValidator = function(value) { if (isEmpty(value) || EMAIL_REGEXP.test(value)) { ctrl.$setValidity('email', true); return value; } else { ctrl.$setValidity('email', false); return undefined; } }; ctrl.$formatters.push(emailValidator); ctrl.$parsers.push(emailValidator); } function radioInputType(scope, element, attr, ctrl) { // make the name unique, if not defined if (isUndefined(attr.name)) { element.attr('name', nextUid()); } element.bind('click', function() { if (element[0].checked) { scope.$apply(function() { ctrl.$setViewValue(attr.value); }); } }); ctrl.$render = function() { var value = attr.value; element[0].checked = (value == ctrl.$viewValue); }; attr.$observe('value', ctrl.$render); } function checkboxInputType(scope, element, attr, ctrl) { var trueValue = attr.ngTrueValue, falseValue = attr.ngFalseValue; if (!isString(trueValue)) trueValue = true; if (!isString(falseValue)) falseValue = false; element.bind('click', function() { scope.$apply(function() { ctrl.$setViewValue(element[0].checked); }); }); ctrl.$render = function() { element[0].checked = ctrl.$viewValue; }; ctrl.$formatters.push(function(value) { return value === trueValue; }); ctrl.$parsers.push(function(value) { return value ? trueValue : falseValue; }); } /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.textarea * * @description * HTML textarea element control with angular data-binding. The data-binding and validation * properties of this element are exactly the same as those of the * {@link angular.module.ng.$compileProvider.directive.input input element}. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} required Sets `required` validation error key if the value is not entered. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than * minlength. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than * maxlength. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for * patterns defined as scope expressions. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. */ /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.input * @restrict E * * @description * HTML input element control with angular data-binding. Input control follows HTML5 input types * and polyfills the HTML5 validation behavior for older browsers. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} required Sets `required` validation error key if the value is not entered. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than * minlength. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than * maxlength. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for * patterns defined as scope expressions. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.user = {name: 'guest', last: 'visitor'}; } </script> <div ng-controller="Ctrl"> <form name="myForm"> User name: <input type="text" name="userName" ng-model="user.name" required> <span class="error" ng-show="myForm.userName.$error.required"> Required!</span><br> Last name: <input type="text" name="lastName" ng-model="user.last" ng-minlength="3" ng-maxlength="10"> <span class="error" ng-show="myForm.lastName.$error.minlength"> Too short!</span> <span class="error" ng-show="myForm.lastName.$error.maxlength"> Too long!</span><br> </form> <hr> <tt>user = {{user}}</tt><br/> <tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br> <tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br> <tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br> <tt>myForm.userName.$error = {{myForm.lastName.$error}}</tt><br> <tt>myForm.$valid = {{myForm.$valid}}</tt><br> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br> <tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br> <tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br> </div> </doc:source> <doc:scenario> it('should initialize to model', function() { expect(binding('user')).toEqual('{"name":"guest","last":"visitor"}'); expect(binding('myForm.userName.$valid')).toEqual('true'); expect(binding('myForm.$valid')).toEqual('true'); }); it('should be invalid if empty when required', function() { input('user.name').enter(''); expect(binding('user')).toEqual('{"last":"visitor"}'); expect(binding('myForm.userName.$valid')).toEqual('false'); expect(binding('myForm.$valid')).toEqual('false'); }); it('should be valid if empty when min length is set', function() { input('user.last').enter(''); expect(binding('user')).toEqual('{"name":"guest","last":""}'); expect(binding('myForm.lastName.$valid')).toEqual('true'); expect(binding('myForm.$valid')).toEqual('true'); }); it('should be invalid if less than required min length', function() { input('user.last').enter('xx'); expect(binding('user')).toEqual('{"name":"guest"}'); expect(binding('myForm.lastName.$valid')).toEqual('false'); expect(binding('myForm.lastName.$error')).toMatch(/minlength/); expect(binding('myForm.$valid')).toEqual('false'); }); it('should be invalid if longer than max length', function() { input('user.last').enter('some ridiculously long name'); expect(binding('user')) .toEqual('{"name":"guest"}'); expect(binding('myForm.lastName.$valid')).toEqual('false'); expect(binding('myForm.lastName.$error')).toMatch(/maxlength/); expect(binding('myForm.$valid')).toEqual('false'); }); </doc:scenario> </doc:example> */ var inputDirective = ['$browser', '$sniffer', function($browser, $sniffer) { return { restrict: 'E', require: '?ngModel', link: function(scope, element, attr, ctrl) { if (ctrl) { (inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrl, $sniffer, $browser); } } }; }]; var VALID_CLASS = 'ng-valid', INVALID_CLASS = 'ng-invalid', PRISTINE_CLASS = 'ng-pristine', DIRTY_CLASS = 'ng-dirty'; /** * @ngdoc object * @name angular.module.ng.$compileProvider.directive.ngModel.NgModelController * * @property {string} $viewValue Actual string value in the view. * @property {*} $modelValue The value in the model, that the control is bound to. * @property {Array.<Function>} $parsers Whenever the control reads value from the DOM, it executes * all of these functions to sanitize / convert the value as well as validate. * * @property {Array.<Function>} $formatters Whenever the model value changes, it executes all of * these functions to convert the value as well as validate. * * @property {Object} $error An bject hash with all errors as keys. * * @property {boolean} $pristine True if user has not interacted with the control yet. * @property {boolean} $dirty True if user has already interacted with the control. * @property {boolean} $valid True if there is no error. * @property {boolean} $invalid True if at least one error on the control. * * @description * */ var NgModelController = ['$scope', '$exceptionHandler', '$attrs', 'ngModel', '$element', function($scope, $exceptionHandler, $attr, ngModel, $element) { this.$viewValue = Number.NaN; this.$modelValue = Number.NaN; this.$parsers = []; this.$formatters = []; this.$viewChangeListeners = []; this.$pristine = true; this.$dirty = false; this.$valid = true; this.$invalid = false; this.$render = noop; this.$name = $attr.name; var parentForm = $element.inheritedData('$formController') || nullFormCtrl, invalidCount = 0, // used to easily determine if we are valid $error = this.$error = {}; // keep invalid keys here // Setup initial state of the control $element.addClass(PRISTINE_CLASS); toggleValidCss(true); // convenience method for easy toggling of classes function toggleValidCss(isValid, validationErrorKey) { validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : ''; $element. removeClass((isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey). addClass((isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey); } /** * @ngdoc function * @name angular.module.ng.$compileProvider.directive.ngModel.NgModelController#$setValidity * @methodOf angular.module.ng.$compileProvider.directive.ngModel.NgModelController * * @description * Change the validity state, and notifies the form when the control changes validity. (i.e. it * does not notify form if given validator is already marked as invalid). * * This method should be called by validators - i.e. the parser or formatter functions. * * @param {string} validationErrorKey Name of the validator. the `validationErrorKey` will assign * to `$error[validationErrorKey]=isValid` so that it is available for data-binding. * The `validationErrorKey` should be in camelCase and will get converted into dash-case * for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error` * class and can be bound to as `{{someForm.someControl.$error.myError}}` . * @param {boolean} isValid Whether the current state is valid (true) or invalid (false). */ this.$setValidity = function(validationErrorKey, isValid) { if ($error[validationErrorKey] === !isValid) return; if (isValid) { if ($error[validationErrorKey]) invalidCount--; if (!invalidCount) { toggleValidCss(true); this.$valid = true; this.$invalid = false; } } else { toggleValidCss(false); this.$invalid = true; this.$valid = false; invalidCount++; } $error[validationErrorKey] = !isValid; toggleValidCss(isValid, validationErrorKey); parentForm.$setValidity(validationErrorKey, isValid, this); }; /** * @ngdoc function * @name angular.module.ng.$compileProvider.directive.ngModel.NgModelController#$setViewValue * @methodOf angular.module.ng.$compileProvider.directive.ngModel.NgModelController * * @description * Read a value from view. * * This method should be called from within a DOM event handler. * For example {@link angular.module.ng.$compileProvider.directive.input input} or * {@link angular.module.ng.$compileProvider.directive.select select} directives call it. * * It internally calls all `formatters` and if resulted value is valid, updates the model and * calls all registered change listeners. * * @param {string} value Value from the view. */ this.$setViewValue = function(value) { this.$viewValue = value; // change to dirty if (this.$pristine) { this.$dirty = true; this.$pristine = false; $element.removeClass(PRISTINE_CLASS).addClass(DIRTY_CLASS); parentForm.$setDirty(); } forEach(this.$parsers, function(fn) { value = fn(value); }); if (this.$modelValue !== value) { this.$modelValue = value; ngModel(value); forEach(this.$viewChangeListeners, function(listener) { try { listener(); } catch(e) { $exceptionHandler(e); } }) } }; // model -> value var ctrl = this; $scope.$watch(function() { return ngModel(); }, function(value) { // ignore change from view if (ctrl.$modelValue === value) return; var formatters = ctrl.$formatters, idx = formatters.length; ctrl.$modelValue = value; while(idx--) { value = formatters[idx](value); } if (ctrl.$viewValue !== value) { ctrl.$viewValue = value; ctrl.$render(); } }); }]; /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngModel * * @element input * * @description * Is directive that tells Angular to do two-way data binding. It works together with `input`, * `select`, `textarea`. You can easily write your own directives to use `ngModel` as well. * * `ngModel` is responsible for: * * - binding the view into the model, which other directives such as `input`, `textarea` or `select` * require, * - providing validation behavior (i.e. required, number, email, url), * - keeping state of the control (valid/invalid, dirty/pristine, validation errors), * - setting related css class onto the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`), * - register the control with parent {@link angular.module.ng.$compileProvider.directive.form form}. * * For basic examples, how to use `ngModel`, see: * * - {@link angular.module.ng.$compileProvider.directive.input input} * - {@link angular.module.ng.$compileProvider.directive.input.text text} * - {@link angular.module.ng.$compileProvider.directive.input.checkbox checkbox} * - {@link angular.module.ng.$compileProvider.directive.input.radio radio} * - {@link angular.module.ng.$compileProvider.directive.input.number number} * - {@link angular.module.ng.$compileProvider.directive.input.email email} * - {@link angular.module.ng.$compileProvider.directive.input.url url} * - {@link angular.module.ng.$compileProvider.directive.select select} * - {@link angular.module.ng.$compileProvider.directive.textarea textarea} * */ var ngModelDirective = [function() { return { inject: { ngModel: 'accessor' }, require: ['ngModel', '^?form'], controller: NgModelController, link: function(scope, element, attr, ctrls) { // notify others, especially parent forms var modelCtrl = ctrls[0], formCtrl = ctrls[1] || nullFormCtrl; formCtrl.$addControl(modelCtrl); element.bind('$destroy', function() { formCtrl.$removeControl(modelCtrl); }); } }; }]; /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngChange * @restrict E * * @description * Evaluate given expression when user changes the input. * The expression is not evaluated when the value change is coming from the model. * * Note, this directive requires `ngModel` to be present. * * @element input * * @example * <doc:example> * <doc:source> * <script> * function Controller($scope) { * $scope.counter = 0; * $scope.change = function() { * $scope.counter++; * }; * } * </script> * <div ng-controller="Controller"> * <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" /> * <input type="checkbox" ng-model="confirmed" id="ng-change-example2" /> * <label for="ng-change-example2">Confirmed</label><br /> * debug = {{confirmed}}<br /> * counter = {{counter}} * </div> * </doc:source> * <doc:scenario> * it('should evaluate the expression if changing from view', function() { * expect(binding('counter')).toEqual('0'); * element('#ng-change-example1').click(); * expect(binding('counter')).toEqual('1'); * expect(binding('confirmed')).toEqual('true'); * }); * * it('should not evaluate the expression if changing from model', function() { * element('#ng-change-example2').click(); * expect(binding('counter')).toEqual('0'); * expect(binding('confirmed')).toEqual('true'); * }); * </doc:scenario> * </doc:example> */ var ngChangeDirective = valueFn({ require: 'ngModel', link: function(scope, element, attr, ctrl) { ctrl.$viewChangeListeners.push(function() { scope.$eval(attr.ngChange); }); } }); var requiredDirective = [function() { return { require: '?ngModel', link: function(scope, elm, attr, ctrl) { if (!ctrl) return; var validator = function(value) { if (attr.required && (isEmpty(value) || value === false)) { ctrl.$setValidity('required', false); return; } else { ctrl.$setValidity('required', true); return value; } }; ctrl.$formatters.push(validator); ctrl.$parsers.unshift(validator); attr.$observe('required', function() { validator(ctrl.$viewValue); }); } }; }]; /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngList * * @description * Text input that converts between comma-seperated string into an array of strings. * * @element input * @param {string=} ngList optional delimiter that should be used to split the value. If * specified in form `/something/` then the value will be converted into a regular expression. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.names = ['igor', 'misko', 'vojta']; } </script> <form name="myForm" ng-controller="Ctrl"> List: <input name="namesInput" ng-model="names" ng-list required> <span class="error" ng-show="myForm.list.$error.required"> Required!</span> <tt>names = {{names}}</tt><br/> <tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/> <tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> </form> </doc:source> <doc:scenario> it('should initialize to model', function() { expect(binding('names')).toEqual('["igor","misko","vojta"]'); expect(binding('myForm.namesInput.$valid')).toEqual('true'); }); it('should be invalid if empty', function() { input('names').enter(''); expect(binding('names')).toEqual('[]'); expect(binding('myForm.namesInput.$valid')).toEqual('false'); }); </doc:scenario> </doc:example> */ var ngListDirective = function() { return { require: 'ngModel', link: function(scope, element, attr, ctrl) { var match = /\/(.*)\//.exec(attr.ngList), separator = match && new RegExp(match[1]) || attr.ngList || ','; var parse = function(viewValue) { var list = []; if (viewValue) { forEach(viewValue.split(separator), function(value) { if (value) list.push(trim(value)); }); } return list; }; ctrl.$parsers.push(parse); ctrl.$formatters.push(function(value) { if (isArray(value) && !equals(parse(ctrl.$viewValue), value)) { return value.join(', '); } return undefined; }); } }; }; var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/; var ngValueDirective = [function() { return { priority: 100, compile: function(tpl, tplAttr) { if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) { return function(scope, elm, attr) { attr.$set('value', scope.$eval(attr.ngValue)); }; } else { return function(scope, elm, attr) { attr.$$observers.value = []; scope.$watch(attr.ngValue, function(value) { attr.$set('value', value, false); }); }; } } }; }]; /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngBind * * @description * The `ngBind` attribute tells Angular to replace the text content of the specified HTML element * with the value of a given expression, and to update the text content when the value of that * expression changes. * * Typically, you don't use `ngBind` directly, but instead you use the double curly markup like * `{{ expression }}` which is similar but less verbose. * * Once scenario in which the use of `ngBind` is prefered over `{{ expression }}` binding is when * it's desirable to put bindings into template that is momentarily displayed by the browser in its * raw state before Angular compiles it. Since `ngBind` is an element attribute, it makes the * bindings invisible to the user while the page is loading. * * An alternative solution to this problem would be using the * {@link angular.module.ng.$compileProvider.directive.ngCloak ngCloak} directive. * * * @element ANY * @param {expression} ngBind {@link guide/dev_guide.expressions Expression} to evaluate. * * @example * Enter a name in the Live Preview text box; the greeting below the text box changes instantly. <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.name = 'Whirled'; } </script> <div ng-controller="Ctrl"> Enter name: <input type="text" ng-model="name"><br> Hello <span ng-bind="name"></span>! </div> </doc:source> <doc:scenario> it('should check ng-bind', function() { expect(using('.doc-example-live').binding('name')).toBe('Whirled'); using('.doc-example-live').input('name').enter('world'); expect(using('.doc-example-live').binding('name')).toBe('world'); }); </doc:scenario> </doc:example> */ var ngBindDirective = ngDirective(function(scope, element, attr) { element.addClass('ng-binding').data('$binding', attr.ngBind); scope.$watch(attr.ngBind, function(value) { element.text(value == undefined ? '' : value); }); }); /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngBindTemplate * * @description * The `ngBindTemplate` directive specifies that the element * text should be replaced with the template in ngBindTemplate. * Unlike ngBind the ngBindTemplate can contain multiple `{{` `}}` * expressions. (This is required since some HTML elements * can not have SPAN elements such as TITLE, or OPTION to name a few.) * * @element ANY * @param {string} ngBindTemplate template of form * <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval. * * @example * Try it here: enter text in text box and watch the greeting change. <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.salutation = 'Hello'; $scope.name = 'World'; } </script> <div ng-controller="Ctrl"> Salutation: <input type="text" ng-model="salutation"><br> Name: <input type="text" ng-model="name"><br> <pre ng-bind-template="{{salutation}} {{name}}!"></pre> </div> </doc:source> <doc:scenario> it('should check ng-bind', function() { expect(using('.doc-example-live').binding('salutation')). toBe('Hello'); expect(using('.doc-example-live').binding('name')). toBe('World'); using('.doc-example-live').input('salutation').enter('Greetings'); using('.doc-example-live').input('name').enter('user'); expect(using('.doc-example-live').binding('salutation')). toBe('Greetings'); expect(using('.doc-example-live').binding('name')). toBe('user'); }); </doc:scenario> </doc:example> */ var ngBindTemplateDirective = ['$interpolate', function($interpolate) { return function(scope, element, attr) { // TODO: move this to scenario runner var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate)); element.addClass('ng-binding').data('$binding', interpolateFn); attr.$observe('ngBindTemplate', function(value) { element.text(value); }); } }]; /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngBindHtmlUnsafe * * @description * Creates a binding that will innerHTML the result of evaluating the `expression` into the current * element. *The innerHTML-ed content will not be sanitized!* You should use this directive only if * {@link angular.module.ng.$compileProvider.directive.ngBindHtml ngBindHtml} directive is too * restrictive and when you absolutely trust the source of the content you are binding to. * * See {@link angular.module.ngSanitize.$sanitize $sanitize} docs for examples. * * @element ANY * @param {expression} ngBindHtmlUnsafe {@link guide/dev_guide.expressions Expression} to evaluate. */ var ngBindHtmlUnsafeDirective = [function() { return function(scope, element, attr) { element.addClass('ng-binding').data('$binding', attr.ngBindHtmlUnsafe); scope.$watch(attr.ngBindHtmlUnsafe, function(value) { element.html(value || ''); }); }; }]; function classDirective(name, selector) { name = 'ngClass' + name; return ngDirective(function(scope, element, attr) { scope.$watch(attr[name], function(newVal, oldVal) { if (selector === true || scope.$index % 2 === selector) { if (oldVal && (newVal !== oldVal)) { if (isObject(oldVal) && !isArray(oldVal)) oldVal = map(oldVal, function(v, k) { if (v) return k }); element.removeClass(isArray(oldVal) ? oldVal.join(' ') : oldVal); } if (isObject(newVal) && !isArray(newVal)) newVal = map(newVal, function(v, k) { if (v) return k }); if (newVal) element.addClass(isArray(newVal) ? newVal.join(' ') : newVal); } }, true); }); } /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngClass * * @description * The `ngClass` allows you to set CSS class on HTML element dynamically by databinding an * expression that represents all classes to be added. * * The directive won't add duplicate classes if a particular class was already set. * * When the expression changes, the previously added classes are removed and only then the classes * new classes are added. * * @element ANY * @param {expression} ngClass {@link guide/dev_guide.expressions Expression} to eval. The result * of the evaluation can be a string representing space delimited class * names, an array, or a map of class names to boolean values. * * @example <doc:example> <doc:source> <input type="button" value="set" ng-click="myVar='ng-invalid'"> <input type="button" value="clear" ng-click="myVar=''"> <br> <span ng-class="myVar">Sample Text &nbsp;&nbsp;&nbsp;&nbsp;</span> </doc:source> <doc:scenario> it('should check ng-class', function() { expect(element('.doc-example-live span').prop('className')).not(). toMatch(/ng-invalid/); using('.doc-example-live').element(':button:first').click(); expect(element('.doc-example-live span').prop('className')). toMatch(/ng-invalid/); using('.doc-example-live').element(':button:last').click(); expect(element('.doc-example-live span').prop('className')).not(). toMatch(/ng-invalid/); }); </doc:scenario> </doc:example> */ var ngClassDirective = classDirective('', true); /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngClassOdd * * @description * The `ngClassOdd` and `ngClassEven` directives work exactly as * {@link angular.module.ng.$compileProvider.directive.ngClass ngClass}, except it works in * conjunction with `ngRepeat` and takes affect only on odd (even) rows. * * This directive can be applied only within a scope of an * {@link angular.module.ng.$compileProvider.directive.ngRepeat ngRepeat}. * * @element ANY * @param {expression} ngClassOdd {@link guide/dev_guide.expressions Expression} to eval. The result * of the evaluation can be a string representing space delimited class names or an array. * * @example <doc:example> <doc:source> <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']"> <li ng-repeat="name in names"> <span ng-class-odd="'ng-format-negative'" ng-class-even="'ng-invalid'"> {{name}} &nbsp; &nbsp; &nbsp; </span> </li> </ol> </doc:source> <doc:scenario> it('should check ng-class-odd and ng-class-even', function() { expect(element('.doc-example-live li:first span').prop('className')). toMatch(/ng-format-negative/); expect(element('.doc-example-live li:last span').prop('className')). toMatch(/ng-invalid/); }); </doc:scenario> </doc:example> */ var ngClassOddDirective = classDirective('Odd', 0); /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngClassEven * * @description * The `ngClassOdd` and `ngClassEven` works exactly as * {@link angular.module.ng.$compileProvider.directive.ngClass ngClass}, except it works in * conjunction with `ngRepeat` and takes affect only on odd (even) rows. * * This directive can be applied only within a scope of an * {@link angular.module.ng.$compileProvider.directive.ngRepeat ngRepeat}. * * @element ANY * @param {expression} ngClassEven {@link guide/dev_guide.expressions Expression} to eval. The * result of the evaluation can be a string representing space delimited class names or an array. * * @example <doc:example> <doc:source> <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']"> <li ng-repeat="name in names"> <span ng-class-odd="'odd'" ng-class-even="'even'"> {{name}} &nbsp; &nbsp; &nbsp; </span> </li> </ol> </doc:source> <doc:scenario> it('should check ng-class-odd and ng-class-even', function() { expect(element('.doc-example-live li:first span').prop('className')). toMatch(/odd/); expect(element('.doc-example-live li:last span').prop('className')). toMatch(/even/); }); </doc:scenario> </doc:example> */ var ngClassEvenDirective = classDirective('Even', 1); /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngCloak * * @description * The `ngCloak` directive is used to prevent the Angular html template from being briefly * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this * directive to avoid the undesirable flicker effect caused by the html template display. * * The directive can be applied to the `<body>` element, but typically a fine-grained application is * prefered in order to benefit from progressive rendering of the browser view. * * `ngCloak` works in cooperation with a css rule that is embedded within `angular.js` and * `angular.min.js` files. Following is the css rule: * * <pre> * [ng\:cloak], [ng-cloak], .ng-cloak { * display: none; * } * </pre> * * When this css rule is loaded by the browser, all html elements (including their children) that * are tagged with the `ng-cloak` directive are hidden. When Angular comes across this directive * during the compilation of the template it deletes the `ngCloak` element attribute, which * makes the compiled element visible. * * For the best result, `angular.js` script must be loaded in the head section of the html file; * alternatively, the css rule (above) must be included in the external stylesheet of the * application. * * Legacy browsers, like IE7, do not provide attribute selector support (added in CSS 2.1) so they * cannot match the `[ng\:cloak]` selector. To work around this limitation, you must add the css * class `ngCloak` in addition to `ngCloak` directive as shown in the example below. * * @element ANY * * @example <doc:example> <doc:source> <div id="template1" ng-cloak>{{ 'hello' }}</div> <div id="template2" ng-cloak class="ng-cloak">{{ 'hello IE7' }}</div> </doc:source> <doc:scenario> it('should remove the template directive and css class', function() { expect(element('.doc-example-live #template1').attr('ng-cloak')). not().toBeDefined(); expect(element('.doc-example-live #template2').attr('ng-cloak')). not().toBeDefined(); }); </doc:scenario> </doc:example> * */ var ngCloakDirective = ngDirective({ compile: function(element, attr) { attr.$set('ngCloak', undefined); element.removeClass('ng-cloak'); } }); /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngController * * @description * The `ngController` directive assigns behavior to a scope. This is a key aspect of how angular * supports the principles behind the Model-View-Controller design pattern. * * MVC components in angular: * * * Model — The Model is data in scope properties; scopes are attached to the DOM. * * View — The template (HTML with data bindings) is rendered into the View. * * Controller — The `ngController` directive specifies a Controller class; the class has * methods that typically express the business logic behind the application. * * Note that an alternative way to define controllers is via the `{@link angular.module.ng.$route}` * service. * * @element ANY * @scope * @param {expression} ngController Name of a globally accessible constructor function or an * {@link guide/dev_guide.expressions expression} that on the current scope evaluates to a * constructor function. * * @example * Here is a simple form for editing user contact information. Adding, removing, clearing, and * greeting are methods declared on the controller (see source tab). These methods can * easily be called from the angular markup. Notice that the scope becomes the `this` for the * controller's instance. This allows for easy access to the view data from the controller. Also * notice that any changes to the data are automatically reflected in the View without the need * for a manual update. <doc:example> <doc:source> <script type="text/javascript"> function SettingsController($scope) { $scope.name = "John Smith"; $scope.contacts = [ {type:'phone', value:'408 555 1212'}, {type:'email', value:'[email protected]'} ]; $scope.greet = function() { alert(this.name); }; $scope.addContact = function() { this.contacts.push({type:'email', value:'[email protected]'}); }; $scope.removeContact = function(contactToRemove) { var index = this.contacts.indexOf(contactToRemove); this.contacts.splice(index, 1); }; $scope.clearContact = function(contact) { contact.type = 'phone'; contact.value = ''; }; } </script> <div ng-controller="SettingsController"> Name: <input type="text" ng-model="name"/> [ <a href="" ng-click="greet()">greet</a> ]<br/> Contact: <ul> <li ng-repeat="contact in contacts"> <select ng-model="contact.type"> <option>phone</option> <option>email</option> </select> <input type="text" ng-model="contact.value"/> [ <a href="" ng-click="clearContact(contact)">clear</a> | <a href="" ng-click="removeContact(contact)">X</a> ] </li> <li>[ <a href="" ng-click="addContact()">add</a> ]</li> </ul> </div> </doc:source> <doc:scenario> it('should check controller', function() { expect(element('.doc-example-live div>:input').val()).toBe('John Smith'); expect(element('.doc-example-live li:nth-child(1) input').val()) .toBe('408 555 1212'); expect(element('.doc-example-live li:nth-child(2) input').val()) .toBe('[email protected]'); element('.doc-example-live li:first a:contains("clear")').click(); expect(element('.doc-example-live li:first input').val()).toBe(''); element('.doc-example-live li:last a:contains("add")').click(); expect(element('.doc-example-live li:nth-child(3) input').val()) .toBe('[email protected]'); }); </doc:scenario> </doc:example> */ var ngControllerDirective = [function() { return { scope: true, controller: '@' }; }]; /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngClick * * @description * The ngClick allows you to specify custom behavior when * element is clicked. * * @element ANY * @param {expression} ngClick {@link guide/dev_guide.expressions Expression} to evaluate upon * click. (Event object is available as `$event`) * * @example <doc:example> <doc:source> <button ng-click="count = count + 1" ng-init="count=0"> Increment </button> count: {{count}} </doc:source> <doc:scenario> it('should check ng-click', function() { expect(binding('count')).toBe('0'); element('.doc-example-live :button').click(); expect(binding('count')).toBe('1'); }); </doc:scenario> </doc:example> */ /* * A directive that allows creation of custom onclick handlers that are defined as angular * expressions and are compiled and executed within the current scope. * * Events that are handled via these handler are always configured not to propagate further. */ var ngEventDirectives = {}; forEach( 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave'.split(' '), function(name) { var directiveName = directiveNormalize('ng-' + name); ngEventDirectives[directiveName] = ['$parse', function($parse) { return function(scope, element, attr) { var fn = $parse(attr[directiveName]); element.bind(lowercase(name), function(event) { scope.$apply(function() { fn(scope, {$event:event}); }); }); }; }]; } ); /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngDblclick * * @description * The `ngDblclick` directive allows you to specify custom behavior on dblclick event. * * @element ANY * @param {expression} ngDblclick {@link guide/dev_guide.expressions Expression} to evaluate upon * dblclick. (Event object is available as `$event`) * * @example * See {@link angular.module.ng.$compileProvider.directive.ngClick ngClick} */ /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngMousedown * * @description * The ngMousedown directive allows you to specify custom behavior on mousedown event. * * @element ANY * @param {expression} ngMousedown {@link guide/dev_guide.expressions Expression} to evaluate upon * mousedown. (Event object is available as `$event`) * * @example * See {@link angular.module.ng.$compileProvider.directive.ngClick ngClick} */ /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngMouseup * * @description * Specify custom behavior on mouseup event. * * @element ANY * @param {expression} ngMouseup {@link guide/dev_guide.expressions Expression} to evaluate upon * mouseup. (Event object is available as `$event`) * * @example * See {@link angular.module.ng.$compileProvider.directive.ngClick ngClick} */ /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngMouseover * * @description * Specify custom behavior on mouseover event. * * @element ANY * @param {expression} ngMouseover {@link guide/dev_guide.expressions Expression} to evaluate upon * mouseover. (Event object is available as `$event`) * * @example * See {@link angular.module.ng.$compileProvider.directive.ngClick ngClick} */ /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngMouseenter * * @description * Specify custom behavior on mouseenter event. * * @element ANY * @param {expression} ngMouseenter {@link guide/dev_guide.expressions Expression} to evaluate upon * mouseenter. (Event object is available as `$event`) * * @example * See {@link angular.module.ng.$compileProvider.directive.ngClick ngClick} */ /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngMouseleave * * @description * Specify custom behavior on mouseleave event. * * @element ANY * @param {expression} ngMouseleave {@link guide/dev_guide.expressions Expression} to evaluate upon * mouseleave. (Event object is available as `$event`) * * @example * See {@link angular.module.ng.$compileProvider.directive.ngClick ngClick} */ /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngMousemove * * @description * Specify custom behavior on mousemove event. * * @element ANY * @param {expression} ngMousemove {@link guide/dev_guide.expressions Expression} to evaluate upon * mousemove. (Event object is available as `$event`) * * @example * See {@link angular.module.ng.$compileProvider.directive.ngClick ngClick} */ /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngSubmit * * @description * Enables binding angular expressions to onsubmit events. * * Additionally it prevents the default action (which for form means sending the request to the * server and reloading the current page). * * @element form * @param {expression} ngSubmit {@link guide/dev_guide.expressions Expression} to eval. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.list = []; $scope.text = 'hello'; $scope.submit = function() { if (this.text) { this.list.push(this.text); this.text = ''; } }; } </script> <form ng-submit="submit()" ng-controller="Ctrl"> Enter text and hit enter: <input type="text" ng-model="text" name="text" /> <input type="submit" id="submit" value="Submit" /> <pre>list={{list}}</pre> </form> </doc:source> <doc:scenario> it('should check ng-submit', function() { expect(binding('list')).toBe('[]'); element('.doc-example-live #submit').click(); expect(binding('list')).toBe('["hello"]'); expect(input('text').val()).toBe(''); }); it('should ignore empty strings', function() { expect(binding('list')).toBe('[]'); element('.doc-example-live #submit').click(); element('.doc-example-live #submit').click(); expect(binding('list')).toBe('["hello"]'); }); </doc:scenario> </doc:example> */ var ngSubmitDirective = ngDirective(function(scope, element, attrs) { element.bind('submit', function() { scope.$apply(attrs.ngSubmit); }); }); /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngInclude * @restrict ECA * * @description * Fetches, compiles and includes an external HTML fragment. * * Keep in mind that Same Origin Policy applies to included resources * (e.g. ngInclude won't work for cross-domain requests on all browsers and for * file:// access on some browsers). * * @scope * * @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant, * make sure you wrap it in quotes, e.g. `src="'myPartialTemplate.html'"`. * @param {string=} onload Expression to evaluate when a new partial is loaded. * * @param {string=} autoscroll Whether `ngInclude` should call {@link angular.module.ng.$anchorScroll * $anchorScroll} to scroll the viewport after the content is loaded. * * - If the attribute is not set, disable scrolling. * - If the attribute is set without value, enable scrolling. * - Otherwise enable scrolling only if the expression evaluates to truthy value. * * @example <doc:example> <doc:source jsfiddle="false"> <script> function Ctrl($scope) { $scope.templates = [ { name: 'template1.html', url: 'examples/ng-include/template1.html'} , { name: 'template2.html', url: 'examples/ng-include/template2.html'} ]; $scope.template = $scope.templates[0]; } </script> <div ng-controller="Ctrl"> <select ng-model="template" ng-options="t.name for t in templates"> <option value="">(blank)</option> </select> url of the template: <tt><a href="{{template.url}}">{{template.url}}</a></tt> <hr/> <div ng-include src="template.url"></div> </div> </doc:source> <doc:scenario> it('should load template1.html', function() { expect(element('.doc-example-live [ng-include]').text()). toBe('Content of template1.html\n'); }); it('should load template2.html', function() { select('template').option('1'); expect(element('.doc-example-live [ng-include]').text()). toBe('Content of template2.html\n'); }); it('should change to blank', function() { select('template').option(''); expect(element('.doc-example-live [ng-include]').text()).toEqual(''); }); </doc:scenario> </doc:example> */ /** * @ngdoc event * @name angular.module.ng.$compileProvider.directive.ngInclude#$includeContentLoaded * @eventOf angular.module.ng.$compileProvider.directive.ngInclude * @eventType emit on the current ngInclude scope * @description * Emitted every time the ngInclude content is reloaded. */ var ngIncludeDirective = ['$http', '$templateCache', '$anchorScroll', '$compile', function($http, $templateCache, $anchorScroll, $compile) { return { restrict: 'ECA', terminal: true, compile: function(element, attr) { var srcExp = attr.ngInclude || attr.src, onloadExp = attr.onload || '', autoScrollExp = attr.autoscroll; return function(scope, element) { var changeCounter = 0, childScope; var clearContent = function() { if (childScope) { childScope.$destroy(); childScope = null; } element.html(''); }; scope.$watch(srcExp, function(src) { var thisChangeId = ++changeCounter; if (src) { $http.get(src, {cache: $templateCache}).success(function(response) { if (thisChangeId !== changeCounter) return; if (childScope) childScope.$destroy(); childScope = scope.$new(); element.html(response); $compile(element.contents())(childScope); if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) { $anchorScroll(); } childScope.$emit('$includeContentLoaded'); scope.$eval(onloadExp); }).error(function() { if (thisChangeId === changeCounter) clearContent(); }); } else clearContent(); }); }; } }; }]; /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngInit * * @description * The `ngInit` directive specifies initialization tasks to be executed * before the template enters execution mode during bootstrap. * * @element ANY * @param {expression} ngInit {@link guide/dev_guide.expressions Expression} to eval. * * @example <doc:example> <doc:source> <div ng-init="greeting='Hello'; person='World'"> {{greeting}} {{person}}! </div> </doc:source> <doc:scenario> it('should check greeting', function() { expect(binding('greeting')).toBe('Hello'); expect(binding('person')).toBe('World'); }); </doc:scenario> </doc:example> */ var ngInitDirective = ngDirective({ compile: function() { return { pre: function(scope, element, attrs) { scope.$eval(attrs.ngInit); } } } }); /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngNonBindable * @priority 1000 * * @description * Sometimes it is necessary to write code which looks like bindings but which should be left alone * by angular. Use `ngNonBindable` to make angular ignore a chunk of HTML. * * @element ANY * * @example * In this example there are two location where a simple binding (`{{}}`) is present, but the one * wrapped in `ngNonBindable` is left alone. * * @example <doc:example> <doc:source> <div>Normal: {{1 + 2}}</div> <div ng-non-bindable>Ignored: {{1 + 2}}</div> </doc:source> <doc:scenario> it('should check ng-non-bindable', function() { expect(using('.doc-example-live').binding('1 + 2')).toBe('3'); expect(using('.doc-example-live').element('div:last').text()). toMatch(/1 \+ 2/); }); </doc:scenario> </doc:example> */ var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 }); /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngPluralize * @restrict EA * * @description * # Overview * `ngPluralize` is a directive that displays messages according to en-US localization rules. * These rules are bundled with angular.js and the rules can be overridden * (see {@link guide/dev_guide.i18n Angular i18n} dev guide). You configure ngPluralize directive * by specifying the mappings between * {@link http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html * plural categories} and the strings to be displayed. * * # Plural categories and explicit number rules * There are two * {@link http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html * plural categories} in Angular's default en-US locale: "one" and "other". * * While a pural category may match many numbers (for example, in en-US locale, "other" can match * any number that is not 1), an explicit number rule can only match one number. For example, the * explicit number rule for "3" matches the number 3. You will see the use of plural categories * and explicit number rules throughout later parts of this documentation. * * # Configuring ngPluralize * You configure ngPluralize by providing 2 attributes: `count` and `when`. * You can also provide an optional attribute, `offset`. * * The value of the `count` attribute can be either a string or an {@link guide/dev_guide.expressions * Angular expression}; these are evaluated on the current scope for its binded value. * * The `when` attribute specifies the mappings between plural categories and the actual * string to be displayed. The value of the attribute should be a JSON object so that Angular * can interpret it correctly. * * The following example shows how to configure ngPluralize: * * <pre> * <ng-pluralize count="personCount" when="{'0': 'Nobody is viewing.', * 'one': '1 person is viewing.', * 'other': '{} people are viewing.'}"> * </ng-pluralize> *</pre> * * In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not * specify this rule, 0 would be matched to the "other" category and "0 people are viewing" * would be shown instead of "Nobody is viewing". You can specify an explicit number rule for * other numbers, for example 12, so that instead of showing "12 people are viewing", you can * show "a dozen people are viewing". * * You can use a set of closed braces(`{}`) as a placeholder for the number that you want substituted * into pluralized strings. In the previous example, Angular will replace `{}` with * <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder * for <span ng-non-bindable>{{numberExpression}}</span>. * * # Configuring ngPluralize with offset * The `offset` attribute allows further customization of pluralized text, which can result in * a better user experience. For example, instead of the message "4 people are viewing this document", * you might display "John, Kate and 2 others are viewing this document". * The offset attribute allows you to offset a number by any desired value. * Let's take a look at an example: * * <pre> * <ng-pluralize count="personCount" offset=2 * when="{'0': 'Nobody is viewing.', * '1': '{{person1}} is viewing.', * '2': '{{person1}} and {{person2}} are viewing.', * 'one': '{{person1}}, {{person2}} and one other person are viewing.', * 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}"> * </ng-pluralize> * </pre> * * Notice that we are still using two plural categories(one, other), but we added * three explicit number rules 0, 1 and 2. * When one person, perhaps John, views the document, "John is viewing" will be shown. * When three people view the document, no explicit number rule is found, so * an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category. * In this case, plural category 'one' is matched and "John, Marry and one other person are viewing" * is shown. * * Note that when you specify offsets, you must provide explicit number rules for * numbers from 0 up to and including the offset. If you use an offset of 3, for example, * you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for * plural categories "one" and "other". * * @param {string|expression} count The variable to be bounded to. * @param {string} when The mapping between plural category to its correspoding strings. * @param {number=} offset Offset to deduct from the total number. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.person1 = 'Igor'; $scope.person2 = 'Misko'; $scope.personCount = 1; } </script> <div ng-controller="Ctrl"> Person 1:<input type="text" ng-model="person1" value="Igor" /><br/> Person 2:<input type="text" ng-model="person2" value="Misko" /><br/> Number of People:<input type="text" ng-model="personCount" value="1" /><br/> <!--- Example with simple pluralization rules for en locale ---> Without Offset: <ng-pluralize count="personCount" when="{'0': 'Nobody is viewing.', 'one': '1 person is viewing.', 'other': '{} people are viewing.'}"> </ng-pluralize><br> <!--- Example with offset ---> With Offset(2): <ng-pluralize count="personCount" offset=2 when="{'0': 'Nobody is viewing.', '1': '{{person1}} is viewing.', '2': '{{person1}} and {{person2}} are viewing.', 'one': '{{person1}}, {{person2}} and one other person are viewing.', 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}"> </ng-pluralize> </div> </doc:source> <doc:scenario> it('should show correct pluralized string', function() { expect(element('.doc-example-live ng-pluralize:first').text()). toBe('1 person is viewing.'); expect(element('.doc-example-live ng-pluralize:last').text()). toBe('Igor is viewing.'); using('.doc-example-live').input('personCount').enter('0'); expect(element('.doc-example-live ng-pluralize:first').text()). toBe('Nobody is viewing.'); expect(element('.doc-example-live ng-pluralize:last').text()). toBe('Nobody is viewing.'); using('.doc-example-live').input('personCount').enter('2'); expect(element('.doc-example-live ng-pluralize:first').text()). toBe('2 people are viewing.'); expect(element('.doc-example-live ng-pluralize:last').text()). toBe('Igor and Misko are viewing.'); using('.doc-example-live').input('personCount').enter('3'); expect(element('.doc-example-live ng-pluralize:first').text()). toBe('3 people are viewing.'); expect(element('.doc-example-live ng-pluralize:last').text()). toBe('Igor, Misko and one other person are viewing.'); using('.doc-example-live').input('personCount').enter('4'); expect(element('.doc-example-live ng-pluralize:first').text()). toBe('4 people are viewing.'); expect(element('.doc-example-live ng-pluralize:last').text()). toBe('Igor, Misko and 2 other people are viewing.'); }); it('should show data-binded names', function() { using('.doc-example-live').input('personCount').enter('4'); expect(element('.doc-example-live ng-pluralize:last').text()). toBe('Igor, Misko and 2 other people are viewing.'); using('.doc-example-live').input('person1').enter('Di'); using('.doc-example-live').input('person2').enter('Vojta'); expect(element('.doc-example-live ng-pluralize:last').text()). toBe('Di, Vojta and 2 other people are viewing.'); }); </doc:scenario> </doc:example> */ var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interpolate) { var BRACE = /{}/g; return { restrict: 'EA', link: function(scope, element, attr) { var numberExp = attr.count, whenExp = element.attr(attr.$attr.when), // this is because we have {{}} in attrs offset = attr.offset || 0, whens = scope.$eval(whenExp), whensExpFns = {}; forEach(whens, function(expression, key) { whensExpFns[key] = $interpolate(expression.replace(BRACE, '{{' + numberExp + '-' + offset + '}}')); }); scope.$watch(function() { var value = parseFloat(scope.$eval(numberExp)); if (!isNaN(value)) { //if explicit number rule such as 1, 2, 3... is defined, just use it. Otherwise, //check it against pluralization rules in $locale service if (!whens[value]) value = $locale.pluralCat(value - offset); return whensExpFns[value](scope, element, true); } else { return ''; } }, function(newVal) { element.text(newVal); }); } }; }]; /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngRepeat * * @description * The `ngRepeat` directive instantiates a template once per item from a collection. Each template * instance gets its own scope, where the given loop variable is set to the current collection item, * and `$index` is set to the item index or key. * * Special properties are exposed on the local scope of each template instance, including: * * * `$index` – `{number}` – iterator offset of the repeated element (0..length-1) * * `$position` – `{string}` – position of the repeated element in the iterator. One of: * * `'first'`, * * `'middle'` * * `'last'` * * * @element ANY * @scope * @priority 1000 * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. Two * formats are currently supported: * * * `variable in expression` – where variable is the user defined loop variable and `expression` * is a scope expression giving the collection to enumerate. * * For example: `track in cd.tracks`. * * * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers, * and `expression` is the scope expression giving the collection to enumerate. * * For example: `(name, age) in {'adam':10, 'amalie':12}`. * * @example * This example initializes the scope to a list of names and * then uses `ngRepeat` to display every person: <doc:example> <doc:source> <div ng-init="friends = [{name:'John', age:25}, {name:'Mary', age:28}]"> I have {{friends.length}} friends. They are: <ul> <li ng-repeat="friend in friends"> [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old. </li> </ul> </div> </doc:source> <doc:scenario> it('should check ng-repeat', function() { var r = using('.doc-example-live').repeater('ul li'); expect(r.count()).toBe(2); expect(r.row(0)).toEqual(["1","John","25"]); expect(r.row(1)).toEqual(["2","Mary","28"]); }); </doc:scenario> </doc:example> */ var ngRepeatDirective = ngDirective({ transclude: 'element', priority: 1000, terminal: true, compile: function(element, attr, linker) { return function(scope, iterStartElement, attr){ var expression = attr.ngRepeat; var match = expression.match(/^\s*(.+)\s+in\s+(.*)\s*$/), lhs, rhs, valueIdent, keyIdent; if (! match) { throw Error("Expected ngRepeat in form of '_item_ in _collection_' but got '" + expression + "'."); } lhs = match[1]; rhs = match[2]; match = lhs.match(/^(?:([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\))$/); if (!match) { throw Error("'item' in 'item in collection' should be identifier or (key, value) but got '" + lhs + "'."); } valueIdent = match[3] || match[1]; keyIdent = match[2]; // Store a list of elements from previous run. This is a hash where key is the item from the // iterator, and the value is an array of objects with following properties. // - scope: bound scope // - element: previous element. // - index: position // We need an array of these objects since the same object can be returned from the iterator. // We expect this to be a rare case. var lastOrder = new HashQueueMap(); scope.$watch(function(scope){ var index, length, collection = scope.$eval(rhs), collectionLength = size(collection, true), childScope, // Same as lastOrder but it has the current state. It will become the // lastOrder on the next iteration. nextOrder = new HashQueueMap(), key, value, // key/value of iteration array, last, // last object information {scope, element, index} cursor = iterStartElement; // current position of the node if (!isArray(collection)) { // if object, extract keys, sort them and use to determine order of iteration over obj props array = []; for(key in collection) { if (collection.hasOwnProperty(key) && key.charAt(0) != '$') { array.push(key); } } array.sort(); } else { array = collection || []; } // we are not using forEach for perf reasons (trying to avoid #call) for (index = 0, length = array.length; index < length; index++) { key = (collection === array) ? index : array[index]; value = collection[key]; last = lastOrder.shift(value); if (last) { // if we have already seen this object, then we need to reuse the // associated scope/element childScope = last.scope; nextOrder.push(value, last); if (index === last.index) { // do nothing cursor = last.element; } else { // existing item which got moved last.index = index; // This may be a noop, if the element is next, but I don't know of a good way to // figure this out, since it would require extra DOM access, so let's just hope that // the browsers realizes that it is noop, and treats it as such. cursor.after(last.element); cursor = last.element; } } else { // new item which we don't know about childScope = scope.$new(); } childScope[valueIdent] = value; if (keyIdent) childScope[keyIdent] = key; childScope.$index = index; childScope.$position = index === 0 ? 'first' : (index == collectionLength - 1 ? 'last' : 'middle'); if (!last) { linker(childScope, function(clone){ cursor.after(clone); last = { scope: childScope, element: (cursor = clone), index: index }; nextOrder.push(value, last); }); } } //shrink children for (key in lastOrder) { if (lastOrder.hasOwnProperty(key)) { array = lastOrder[key]; while(array.length) { value = array.pop(); value.element.remove(); value.scope.$destroy(); } } } lastOrder = nextOrder; }); }; } }); /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngShow * * @description * The `ngShow` and `ngHide` directives show or hide a portion of the DOM tree (HTML) * conditionally. * * @element ANY * @param {expression} ngShow If the {@link guide/dev_guide.expressions expression} is truthy * then the element is shown or hidden respectively. * * @example <doc:example> <doc:source> Click me: <input type="checkbox" ng-model="checked"><br/> Show: <span ng-show="checked">I show up when your checkbox is checked.</span> <br/> Hide: <span ng-hide="checked">I hide when your checkbox is checked.</span> </doc:source> <doc:scenario> it('should check ng-show / ng-hide', function() { expect(element('.doc-example-live span:first:hidden').count()).toEqual(1); expect(element('.doc-example-live span:last:visible').count()).toEqual(1); input('checked').check(); expect(element('.doc-example-live span:first:visible').count()).toEqual(1); expect(element('.doc-example-live span:last:hidden').count()).toEqual(1); }); </doc:scenario> </doc:example> */ //TODO(misko): refactor to remove element from the DOM var ngShowDirective = ngDirective(function(scope, element, attr){ scope.$watch(attr.ngShow, function(value){ element.css('display', toBoolean(value) ? '' : 'none'); }); }); /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngHide * * @description * The `ngHide` and `ngShow` directives hide or show a portion * of the HTML conditionally. * * @element ANY * @param {expression} ngHide If the {@link guide/dev_guide.expressions expression} truthy then * the element is shown or hidden respectively. * * @example <doc:example> <doc:source> Click me: <input type="checkbox" ng-model="checked"><br/> Show: <span ng-show="checked">I show up when you checkbox is checked?</span> <br/> Hide: <span ng-hide="checked">I hide when you checkbox is checked?</span> </doc:source> <doc:scenario> it('should check ng-show / ng-hide', function() { expect(element('.doc-example-live span:first:hidden').count()).toEqual(1); expect(element('.doc-example-live span:last:visible').count()).toEqual(1); input('checked').check(); expect(element('.doc-example-live span:first:visible').count()).toEqual(1); expect(element('.doc-example-live span:last:hidden').count()).toEqual(1); }); </doc:scenario> </doc:example> */ //TODO(misko): refactor to remove element from the DOM var ngHideDirective = ngDirective(function(scope, element, attr){ scope.$watch(attr.ngHide, function(value){ element.css('display', toBoolean(value) ? 'none' : ''); }); }); /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngStyle * * @description * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally. * * @element ANY * @param {expression} ngStyle {@link guide/dev_guide.expressions Expression} which evals to an * object whose keys are CSS style names and values are corresponding values for those CSS * keys. * * @example <doc:example> <doc:source> <input type="button" value="set" ng-click="myStyle={color:'red'}"> <input type="button" value="clear" ng-click="myStyle={}"> <br/> <span ng-style="myStyle">Sample Text</span> <pre>myStyle={{myStyle}}</pre> </doc:source> <doc:scenario> it('should check ng-style', function() { expect(element('.doc-example-live span').css('color')).toBe('rgb(0, 0, 0)'); element('.doc-example-live :button[value=set]').click(); expect(element('.doc-example-live span').css('color')).toBe('rgb(255, 0, 0)'); element('.doc-example-live :button[value=clear]').click(); expect(element('.doc-example-live span').css('color')).toBe('rgb(0, 0, 0)'); }); </doc:scenario> </doc:example> */ var ngStyleDirective = ngDirective(function(scope, element, attr) { scope.$watch(attr.ngStyle, function(newStyles, oldStyles) { if (oldStyles && (newStyles !== oldStyles)) { forEach(oldStyles, function(val, style) { element.css(style, '');}); } if (newStyles) element.css(newStyles); }, true); }); /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngSwitch * @restrict EA * * @description * Conditionally change the DOM structure. * * @usageContent * <ANY ng-switch-when="matchValue1">...</ANY> * <ANY ng-switch-when="matchValue2">...</ANY> * ... * <ANY ng-switch-default>...</ANY> * * @scope * @param {*} ngSwitch|on expression to match against <tt>ng-switch-when</tt>. * @paramDescription * On child elments add: * * * `ngSwitchWhen`: the case statement to match against. If match then this * case will be displayed. * * `ngSwitchDefault`: the default case when no other casses match. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.items = ['settings', 'home', 'other']; $scope.selection = $scope.items[0]; } </script> <div ng-controller="Ctrl"> <select ng-model="selection" ng-options="item for item in items"> </select> <tt>selection={{selection}}</tt> <hr/> <div ng-switch on="selection" > <div ng-switch-when="settings">Settings Div</div> <span ng-switch-when="home">Home Span</span> <span ng-switch-default>default</span> </div> </div> </doc:source> <doc:scenario> it('should start in settings', function() { expect(element('.doc-example-live [ng-switch]').text()).toMatch(/Settings Div/); }); it('should change to home', function() { select('selection').option('home'); expect(element('.doc-example-live [ng-switch]').text()).toMatch(/Home Span/); }); it('should select deafault', function() { select('selection').option('other'); expect(element('.doc-example-live [ng-switch]').text()).toMatch(/default/); }); </doc:scenario> </doc:example> */ var NG_SWITCH = 'ng-switch'; var ngSwitchDirective = valueFn({ restrict: 'EA', compile: function(element, attr) { var watchExpr = attr.ngSwitch || attr.on, cases = {}; element.data(NG_SWITCH, cases); return function(scope, element){ var selectedTransclude, selectedElement, selectedScope; scope.$watch(watchExpr, function(value) { if (selectedElement) { selectedScope.$destroy(); selectedElement.remove(); selectedElement = selectedScope = null; } if ((selectedTransclude = cases['!' + value] || cases['?'])) { scope.$eval(attr.change); selectedScope = scope.$new(); selectedTransclude(selectedScope, function(caseElement) { selectedElement = caseElement; element.append(caseElement); }); } }); }; } }); var ngSwitchWhenDirective = ngDirective({ transclude: 'element', priority: 500, compile: function(element, attrs, transclude) { var cases = element.inheritedData(NG_SWITCH); assertArg(cases); cases['!' + attrs.ngSwitchWhen] = transclude; } }); var ngSwitchDefaultDirective = ngDirective({ transclude: 'element', priority: 500, compile: function(element, attrs, transclude) { var cases = element.inheritedData(NG_SWITCH); assertArg(cases); cases['?'] = transclude; } }); /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngTransclude * * @description * Insert the transcluded DOM here. * * @element ANY * * @example <doc:example module="transclude"> <doc:source> <script> function Ctrl($scope) { $scope.title = 'Lorem Ipsum'; $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...'; } angular.module('transclude', []) .directive('pane', function(){ return { restrict: 'E', transclude: true, scope: 'isolate', locals: { title:'bind' }, template: '<div style="border: 1px solid black;">' + '<div style="background-color: gray">{{title}}</div>' + '<div ng-transclude></div>' + '</div>' }; }); </script> <div ng-controller="Ctrl"> <input ng-model="title"><br> <textarea ng-model="text"></textarea> <br/> <pane title="{{title}}">{{text}}</pane> </div> </doc:source> <doc:scenario> it('should have transcluded', function() { input('title').enter('TITLE'); input('text').enter('TEXT'); expect(binding('title')).toEqual('TITLE'); expect(binding('text')).toEqual('TEXT'); }); </doc:scenario> </doc:example> * */ var ngTranscludeDirective = ngDirective({ controller: ['$transclude', '$element', function($transclude, $element) { $transclude(function(clone) { $element.append(clone); }); }] }); /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngView * @restrict ECA * * @description * # Overview * `ngView` is a directive that complements the {@link angular.module.ng.$route $route} service by * including the rendered template of the current route into the main layout (`index.html`) file. * Every time the current route changes, the included view changes with it according to the * configuration of the `$route` service. * * @scope * @example <doc:example module="ngView"> <doc:source> <script type="text/ng-template" id="examples/book.html"> controller: {{name}}<br /> Book Id: {{params.bookId}}<br /> </script> <script type="text/ng-template" id="examples/chapter.html"> controller: {{name}}<br /> Book Id: {{params.bookId}}<br /> Chapter Id: {{params.chapterId}} </script> <script> angular.module('ngView', [], function($routeProvider, $locationProvider) { $routeProvider.when('/Book/:bookId', { template: 'examples/book.html', controller: BookCntl }); $routeProvider.when('/Book/:bookId/ch/:chapterId', { template: 'examples/chapter.html', controller: ChapterCntl }); // configure html5 to get links working on jsfiddle $locationProvider.html5Mode(true); }); function MainCntl($scope, $route, $routeParams, $location) { $scope.$route = $route; $scope.$location = $location; $scope.$routeParams = $routeParams; } function BookCntl($scope, $routeParams) { $scope.name = "BookCntl"; $scope.params = $routeParams; } function ChapterCntl($scope, $routeParams) { $scope.name = "ChapterCntl"; $scope.params = $routeParams; } </script> <div ng-controller="MainCntl"> Choose: <a href="Book/Moby">Moby</a> | <a href="Book/Moby/ch/1">Moby: Ch1</a> | <a href="Book/Gatsby">Gatsby</a> | <a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> | <a href="Book/Scarlet">Scarlet Letter</a><br/> <div ng-view></div> <hr /> <pre>$location.path() = {{$location.path()}}</pre> <pre>$route.current.template = {{$route.current.template}}</pre> <pre>$route.current.params = {{$route.current.params}}</pre> <pre>$route.current.scope.name = {{$route.current.scope.name}}</pre> <pre>$routeParams = {{$routeParams}}</pre> </div> </doc:source> <doc:scenario> it('should load and compile correct template', function() { element('a:contains("Moby: Ch1")').click(); var content = element('.doc-example-live [ng-view]').text(); expect(content).toMatch(/controller\: ChapterCntl/); expect(content).toMatch(/Book Id\: Moby/); expect(content).toMatch(/Chapter Id\: 1/); element('a:contains("Scarlet")').click(); content = element('.doc-example-live [ng-view]').text(); expect(content).toMatch(/controller\: BookCntl/); expect(content).toMatch(/Book Id\: Scarlet/); }); </doc:scenario> </doc:example> */ /** * @ngdoc event * @name angular.module.ng.$compileProvider.directive.ngView#$viewContentLoaded * @eventOf angular.module.ng.$compileProvider.directive.ngView * @eventType emit on the current ngView scope * @description * Emitted every time the ngView content is reloaded. */ var ngViewDirective = ['$http', '$templateCache', '$route', '$anchorScroll', '$compile', '$controller', function($http, $templateCache, $route, $anchorScroll, $compile, $controller) { return { restrict: 'ECA', terminal: true, link: function(scope, element, attr) { var changeCounter = 0, lastScope, onloadExp = attr.onload || ''; scope.$on('$afterRouteChange', update); update(); function destroyLastScope() { if (lastScope) { lastScope.$destroy(); lastScope = null; } } function update() { var template = $route.current && $route.current.template, thisChangeId = ++changeCounter; function clearContent() { // ignore callback if another route change occured since if (thisChangeId === changeCounter) { element.html(''); destroyLastScope(); } } if (template) { $http.get(template, {cache: $templateCache}).success(function(response) { // ignore callback if another route change occured since if (thisChangeId === changeCounter) { element.html(response); destroyLastScope(); var link = $compile(element.contents()), current = $route.current, controller; lastScope = current.scope = scope.$new(); if (current.controller) { controller = $controller(current.controller, {$scope: lastScope}); element.contents().data('$ngControllerController', controller); } link(lastScope); lastScope.$emit('$viewContentLoaded'); lastScope.$eval(onloadExp); // $anchorScroll might listen on event... $anchorScroll(); } }).error(clearContent); } else { clearContent(); } } } }; }]; /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.script * * @description * Load content of a script tag, with type `text/ng-template`, into `$templateCache`, so that the * template can be used by `ngInclude`, `ngView` or directive templates. * * @restrict E * @param {'text/ng-template'} type must be set to `'text/ng-template'` * * @example <doc:example> <doc:source> <script type="text/ng-template" id="/tpl.html"> Content of the template. </script> <a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a> <div id="tpl-content" ng-include src="currentTpl"></div> </doc:source> <doc:scenario> it('should load template defined inside script tag', function() { element('#tpl-link').click(); expect(element('#tpl-content').text()).toMatch(/Content of the template/); }); </doc:scenario> </doc:example> */ var scriptDirective = ['$templateCache', function($templateCache) { return { restrict: 'E', terminal: true, compile: function(element, attr) { if (attr.type == 'text/ng-template') { var templateUrl = attr.id, // IE is not consistent, in scripts we have to read .text but in other nodes we have to read .textContent text = element[0].text; $templateCache.put(templateUrl, text); } } }; }]; /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.select * @restrict E * * @description * HTML `SELECT` element with angular data-binding. * * # `ngOptions` * * Optionally `ngOptions` attribute can be used to dynamically generate a list of `<option>` * elements for a `<select>` element using an array or an object obtained by evaluating the * `ngOptions` expression. *˝˝ * When an item in the select menu is select, the value of array element or object property * represented by the selected option will be bound to the model identified by the `ngModel` * directive of the parent select element. * * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can * be nested into the `<select>` element. This element will then represent `null` or "not selected" * option. See example below for demonstration. * * Note: `ngOptions` provides iterator facility for `<option>` element which should be used instead * of {@link angular.module.ng.$compileProvider.directive.ngRepeat ngRepeat} when you want the * `select` model to be bound to a non-string value. This is because an option element can currently * be bound to string values only. * * @param {string} name assignable expression to data-bind to. * @param {string=} required The control is considered valid only if value is entered. * @param {comprehension_expression=} ngOptions in one of the following forms: * * * for array data sources: * * `label` **`for`** `value` **`in`** `array` * * `select` **`as`** `label` **`for`** `value` **`in`** `array` * * `label` **`group by`** `group` **`for`** `value` **`in`** `array` * * `select` **`as`** `label` **`group by`** `group` **`for`** `value` **`in`** `array` * * for object data sources: * * `label` **`for (`**`key` **`,`** `value`**`) in`** `object` * * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object` * * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object` * * `select` **`as`** `label` **`group by`** `group` * **`for` `(`**`key`**`,`** `value`**`) in`** `object` * * Where: * * * `array` / `object`: an expression which evaluates to an array / object to iterate over. * * `value`: local variable which will refer to each item in the `array` or each property value * of `object` during iteration. * * `key`: local variable which will refer to a property name in `object` during iteration. * * `label`: The result of this expression will be the label for `<option>` element. The * `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`). * * `select`: The result of this expression will be bound to the model of the parent `<select>` * element. If not specified, `select` expression will default to `value`. * * `group`: The result of this expression will be used to group options using the `<optgroup>` * DOM element. * * @example <doc:example> <doc:source> <script> function MyCntrl($scope) { $scope.colors = [ {name:'black', shade:'dark'}, {name:'white', shade:'light'}, {name:'red', shade:'dark'}, {name:'blue', shade:'dark'}, {name:'yellow', shade:'light'} ]; $scope.color = $scope.colors[2]; // red } </script> <div ng-controller="MyCntrl"> <ul> <li ng-repeat="color in colors"> Name: <input ng-model="color.name"> [<a href ng-click="colors.$remove(color)">X</a>] </li> <li> [<a href ng-click="colors.push({})">add</a>] </li> </ul> <hr/> Color (null not allowed): <select ng-model="color" ng-options="c.name for c in colors"></select><br> Color (null allowed): <span class="nullable"> <select ng-model="color" ng-options="c.name for c in colors"> <option value="">-- chose color --</option> </select> </span><br/> Color grouped by shade: <select ng-model="color" ng-options="c.name group by c.shade for c in colors"> </select><br/> Select <a href ng-click="color={name:'not in list'}">bogus</a>.<br> <hr/> Currently selected: {{ {selected_color:color} }} <div style="border:solid 1px black; height:20px" ng-style="{'background-color':color.name}"> </div> </div> </doc:source> <doc:scenario> it('should check ng-options', function() { expect(binding('{selected_color:color}')).toMatch('red'); select('color').option('0'); expect(binding('{selected_color:color}')).toMatch('black'); using('.nullable').select('color').option(''); expect(binding('{selected_color:color}')).toMatch('null'); }); </doc:scenario> </doc:example> */ var ngOptionsDirective = valueFn({ terminal: true }); var selectDirective = ['$compile', '$parse', function($compile, $parse) { //00001111100000000000222200000000000000000000003333000000000000044444444444444444000000000555555555555555550000000666666666666666660000000000000007777 var NG_OPTIONS_REGEXP = /^\s*(.*?)(?:\s+as\s+(.*?))?(?:\s+group\s+by\s+(.*))?\s+for\s+(?:([\$\w][\$\w\d]*)|(?:\(\s*([\$\w][\$\w\d]*)\s*,\s*([\$\w][\$\w\d]*)\s*\)))\s+in\s+(.*)$/, nullModelCtrl = {$setViewValue: noop}; return { restrict: 'E', require: ['select', '?ngModel'], controller: ['$element', '$scope', function($element, $scope) { var self = this, optionsMap = {}, ngModelCtrl = nullModelCtrl, nullOption, unknownOption; self.init = function(ngModelCtrl_, nullOption_, unknownOption_) { ngModelCtrl = ngModelCtrl_; nullOption = nullOption_; unknownOption = unknownOption_; } self.addOption = function(value) { optionsMap[value] = true; if (ngModelCtrl.$viewValue == value) { $element.val(value); if (unknownOption.parent()) unknownOption.remove(); } }; self.removeOption = function(value) { if (this.hasOption(value)) { delete optionsMap[value]; if (ngModelCtrl.$viewValue == value) { this.renderUnknownOption(value); } } }; self.renderUnknownOption = function(val) { var unknownVal = '? ' + hashKey(val) + ' ?'; unknownOption.val(unknownVal); $element.prepend(unknownOption); $element.val(unknownVal); unknownOption.prop('selected', true); // needed for IE } self.hasOption = function(value) { return optionsMap.hasOwnProperty(value); } $scope.$on('$destroy', function() { // disable unknown option so that we don't do work when the whole select is being destroyed self.renderUnknownOption = noop; }); }], link: function(scope, element, attr, ctrls) { // if ngModel is not defined, we don't need to do anything if (!ctrls[1]) return; var selectCtrl = ctrls[0], ngModelCtrl = ctrls[1], multiple = attr.multiple, optionsExp = attr.ngOptions, nullOption = false, // if false, user will not be able to select it (used by ngOptions) emptyOption, // we can't just jqLite('<option>') since jqLite is not smart enough // to create it in <select> and IE barfs otherwise. optionTemplate = jqLite(document.createElement('option')), optGroupTemplate =jqLite(document.createElement('optgroup')), unknownOption = optionTemplate.clone(); // find "null" option for(var i = 0, children = element.children(), ii = children.length; i < ii; i++) { if (children[i].value == '') { emptyOption = nullOption = children.eq(i); break; } } selectCtrl.init(ngModelCtrl, nullOption, unknownOption); // required validator if (multiple && (attr.required || attr.ngRequired)) { var requiredValidator = function(value) { ngModelCtrl.$setValidity('required', !attr.required || (value && value.length)); return value; }; ngModelCtrl.$parsers.push(requiredValidator); ngModelCtrl.$formatters.unshift(requiredValidator); attr.$observe('required', function() { requiredValidator(ngModelCtrl.$viewValue); }); } if (optionsExp) Options(scope, element, ngModelCtrl); else if (multiple) Multiple(scope, element, ngModelCtrl); else Single(scope, element, ngModelCtrl, selectCtrl); //////////////////////////// function Single(scope, selectElement, ngModelCtrl, selectCtrl) { ngModelCtrl.$render = function() { var viewValue = ngModelCtrl.$viewValue; if (selectCtrl.hasOption(viewValue)) { if (unknownOption.parent()) unknownOption.remove(); selectElement.val(viewValue); if (viewValue === '') emptyOption.prop('selected', true); // to make IE9 happy } else { if (isUndefined(viewValue) && emptyOption) { selectElement.val(''); } else { selectCtrl.renderUnknownOption(viewValue); } } }; selectElement.bind('change', function() { scope.$apply(function() { if (unknownOption.parent()) unknownOption.remove(); ngModelCtrl.$setViewValue(selectElement.val()); }); }); } function Multiple(scope, selectElement, ctrl) { var lastView; ctrl.$render = function() { var items = new HashMap(ctrl.$viewValue); forEach(selectElement.children(), function(option) { option.selected = isDefined(items.get(option.value)); }); }; // we have to do it on each watch since ngModel watches reference, but // we need to work of an array, so we need to see if anything was inserted/removed scope.$watch(function() { if (!equals(lastView, ctrl.$viewValue)) { lastView = copy(ctrl.$viewValue); ctrl.$render(); } }); selectElement.bind('change', function() { scope.$apply(function() { var array = []; forEach(selectElement.children(), function(option) { if (option.selected) { array.push(option.value); } }); ctrl.$setViewValue(array); }); }); } function Options(scope, selectElement, ctrl) { var match; if (! (match = optionsExp.match(NG_OPTIONS_REGEXP))) { throw Error( "Expected ngOptions in form of '_select_ (as _label_)? for (_key_,)?_value_ in _collection_'" + " but got '" + optionsExp + "'."); } var displayFn = $parse(match[2] || match[1]), valueName = match[4] || match[6], keyName = match[5], groupByFn = $parse(match[3] || ''), valueFn = $parse(match[2] ? match[1] : valueName), valuesFn = $parse(match[7]), // This is an array of array of existing option groups in DOM. We try to reuse these if possible // optionGroupsCache[0] is the options with no option group // optionGroupsCache[?][0] is the parent: either the SELECT or OPTGROUP element optionGroupsCache = [[{element: selectElement, label:''}]]; if (nullOption) { // compile the element since there might be bindings in it $compile(nullOption)(scope); // remove the class, which is added automatically because we recompile the element and it // becomes the compilation root nullOption.removeClass('ng-scope'); // we need to remove it before calling selectElement.html('') because otherwise IE will // remove the label from the element. wtf? nullOption.remove(); } // clear contents, we'll add what's needed based on the model selectElement.html(''); selectElement.bind('change', function() { scope.$apply(function() { var optionGroup, collection = valuesFn(scope) || [], locals = {}, key, value, optionElement, index, groupIndex, length, groupLength; if (multiple) { value = []; for (groupIndex = 0, groupLength = optionGroupsCache.length; groupIndex < groupLength; groupIndex++) { // list of options for that group. (first item has the parent) optionGroup = optionGroupsCache[groupIndex]; for(index = 1, length = optionGroup.length; index < length; index++) { if ((optionElement = optionGroup[index].element)[0].selected) { key = optionElement.val(); if (keyName) locals[keyName] = key; locals[valueName] = collection[key]; value.push(valueFn(scope, locals)); } } } } else { key = selectElement.val(); if (key == '?') { value = undefined; } else if (key == ''){ value = null; } else { locals[valueName] = collection[key]; if (keyName) locals[keyName] = key; value = valueFn(scope, locals); } } ctrl.$setViewValue(value); }); }); ctrl.$render = render; // TODO(vojta): can't we optimize this ? scope.$watch(render); function render() { var optionGroups = {'':[]}, // Temporary location for the option groups before we render them optionGroupNames = [''], optionGroupName, optionGroup, option, existingParent, existingOptions, existingOption, modelValue = ctrl.$modelValue, values = valuesFn(scope) || [], keys = keyName ? sortedKeys(values) : values, groupLength, length, groupIndex, index, locals = {}, selected, selectedSet = false, // nothing is selected yet lastElement, element; if (multiple) { selectedSet = new HashMap(modelValue); } else if (modelValue === null || nullOption) { // if we are not multiselect, and we are null then we have to add the nullOption optionGroups[''].push({selected:modelValue === null, id:'', label:''}); selectedSet = true; } // We now build up the list of options we need (we merge later) for (index = 0; length = keys.length, index < length; index++) { locals[valueName] = values[keyName ? locals[keyName]=keys[index]:index]; optionGroupName = groupByFn(scope, locals) || ''; if (!(optionGroup = optionGroups[optionGroupName])) { optionGroup = optionGroups[optionGroupName] = []; optionGroupNames.push(optionGroupName); } if (multiple) { selected = selectedSet.remove(valueFn(scope, locals)) != undefined; } else { selected = modelValue === valueFn(scope, locals); selectedSet = selectedSet || selected; // see if at least one item is selected } optionGroup.push({ id: keyName ? keys[index] : index, // either the index into array or key from object label: displayFn(scope, locals) || '', // what will be seen by the user selected: selected // determine if we should be selected }); } if (!multiple && !selectedSet) { // nothing was selected, we have to insert the undefined item optionGroups[''].unshift({id:'?', label:'', selected:true}); } // Now we need to update the list of DOM nodes to match the optionGroups we computed above for (groupIndex = 0, groupLength = optionGroupNames.length; groupIndex < groupLength; groupIndex++) { // current option group name or '' if no group optionGroupName = optionGroupNames[groupIndex]; // list of options for that group. (first item has the parent) optionGroup = optionGroups[optionGroupName]; if (optionGroupsCache.length <= groupIndex) { // we need to grow the optionGroups existingParent = { element: optGroupTemplate.clone().attr('label', optionGroupName), label: optionGroup.label }; existingOptions = [existingParent]; optionGroupsCache.push(existingOptions); selectElement.append(existingParent.element); } else { existingOptions = optionGroupsCache[groupIndex]; existingParent = existingOptions[0]; // either SELECT (no group) or OPTGROUP element // update the OPTGROUP label if not the same. if (existingParent.label != optionGroupName) { existingParent.element.attr('label', existingParent.label = optionGroupName); } } lastElement = null; // start at the beginning for(index = 0, length = optionGroup.length; index < length; index++) { option = optionGroup[index]; if ((existingOption = existingOptions[index+1])) { // reuse elements lastElement = existingOption.element; if (existingOption.label !== option.label) { lastElement.text(existingOption.label = option.label); } if (existingOption.id !== option.id) { lastElement.val(existingOption.id = option.id); } if (existingOption.element.selected !== option.selected) { lastElement.prop('selected', (existingOption.selected = option.selected)); } } else { // grow elements // if it's a null option if (option.id === '' && nullOption) { // put back the pre-compiled element element = nullOption; } else { // jQuery(v1.4.2) Bug: We should be able to chain the method calls, but // in this version of jQuery on some browser the .text() returns a string // rather then the element. (element = optionTemplate.clone()) .val(option.id) .attr('selected', option.selected) .text(option.label); } existingOptions.push(existingOption = { element: element, label: option.label, id: option.id, selected: option.selected }); if (lastElement) { lastElement.after(element); } else { existingParent.element.append(element); } lastElement = element; } } // remove any excessive OPTIONs in a group index++; // increment since the existingOptions[0] is parent element not OPTION while(existingOptions.length > index) { existingOptions.pop().element.remove(); } } // remove any excessive OPTGROUPs from select while(optionGroupsCache.length > groupIndex) { optionGroupsCache.pop()[0].element.remove(); } } } } } }]; var optionDirective = ['$interpolate', function($interpolate) { return { restrict: 'E', priority: 100, require: '^select', compile: function(element, attr) { if (isUndefined(attr.value)) { var interpolateFn = $interpolate(element.text(), true); if (!interpolateFn) { attr.$set('value', element.text()); } } // For some reason Opera defaults to true and if not overridden this messes up the repeater. // We don't want the view to drive the initialization of the model anyway. element.prop('selected', false); return function (scope, element, attr, selectCtrl) { if (interpolateFn) { scope.$watch(interpolateFn, function(newVal, oldVal) { attr.$set('value', newVal); if (newVal !== oldVal) selectCtrl.removeOption(oldVal); selectCtrl.addOption(newVal); }); } else { selectCtrl.addOption(attr.value); } element.bind('$destroy', function() { selectCtrl.removeOption(attr.value); }); }; } } }]; var styleDirective = valueFn({ restrict: 'E', terminal: true }); /** * Setup file for the Scenario. * Must be first in the compilation/bootstrap list. */ // Public namespace angular.scenario = angular.scenario || {}; /** * Defines a new output format. * * @param {string} name the name of the new output format * @param {function()} fn function(context, runner) that generates the output */ angular.scenario.output = angular.scenario.output || function(name, fn) { angular.scenario.output[name] = fn; }; /** * Defines a new DSL statement. If your factory function returns a Future * it's returned, otherwise the result is assumed to be a map of functions * for chaining. Chained functions are subject to the same rules. * * Note: All functions on the chain are bound to the chain scope so values * set on "this" in your statement function are available in the chained * functions. * * @param {string} name The name of the statement * @param {function()} fn Factory function(), return a function for * the statement. */ angular.scenario.dsl = angular.scenario.dsl || function(name, fn) { angular.scenario.dsl[name] = function() { function executeStatement(statement, args) { var result = statement.apply(this, args); if (angular.isFunction(result) || result instanceof angular.scenario.Future) return result; var self = this; var chain = angular.extend({}, result); angular.forEach(chain, function(value, name) { if (angular.isFunction(value)) { chain[name] = function() { return executeStatement.call(self, value, arguments); }; } else { chain[name] = value; } }); return chain; } var statement = fn.apply(this, arguments); return function() { return executeStatement.call(this, statement, arguments); }; }; }; /** * Defines a new matcher for use with the expects() statement. The value * this.actual (like in Jasmine) is available in your matcher to compare * against. Your function should return a boolean. The future is automatically * created for you. * * @param {string} name The name of the matcher * @param {function()} fn The matching function(expected). */ angular.scenario.matcher = angular.scenario.matcher || function(name, fn) { angular.scenario.matcher[name] = function(expected) { var prefix = 'expect ' + this.future.name + ' '; if (this.inverse) { prefix += 'not '; } var self = this; this.addFuture(prefix + name + ' ' + angular.toJson(expected), function(done) { var error; self.actual = self.future.value; if ((self.inverse && fn.call(self, expected)) || (!self.inverse && !fn.call(self, expected))) { error = 'expected ' + angular.toJson(expected) + ' but was ' + angular.toJson(self.actual); } done(error); }); }; }; /** * Initialize the scenario runner and run ! * * Access global window and document object * Access $runner through closure * * @param {Object=} config Config options */ angular.scenario.setUpAndRun = function(config) { var href = window.location.href; var body = _jQuery(document.body); var output = []; var objModel = new angular.scenario.ObjectModel($runner); if (config && config.scenario_output) { output = config.scenario_output.split(','); } angular.forEach(angular.scenario.output, function(fn, name) { if (!output.length || indexOf(output,name) != -1) { var context = body.append('<div></div>').find('div:last'); context.attr('id', name); fn.call({}, context, $runner, objModel); } }); if (!/^http/.test(href) && !/^https/.test(href)) { body.append('<p id="system-error"></p>'); body.find('#system-error').text( 'Scenario runner must be run using http or https. The protocol ' + href.split(':')[0] + ':// is not supported.' ); return; } var appFrame = body.append('<div id="application"></div>').find('#application'); var application = new angular.scenario.Application(appFrame); $runner.on('RunnerEnd', function() { appFrame.css('display', 'none'); appFrame.find('iframe').attr('src', 'about:blank'); }); $runner.on('RunnerError', function(error) { if (window.console) { console.log(formatException(error)); } else { // Do something for IE alert(error); } }); $runner.run(application); }; /** * Iterates through list with iterator function that must call the * continueFunction to continute iterating. * * @param {Array} list list to iterate over * @param {function()} iterator Callback function(value, continueFunction) * @param {function()} done Callback function(error, result) called when * iteration finishes or an error occurs. */ function asyncForEach(list, iterator, done) { var i = 0; function loop(error, index) { if (index && index > i) { i = index; } if (error || i >= list.length) { done(error); } else { try { iterator(list[i++], loop); } catch (e) { done(e); } } } loop(); } /** * Formats an exception into a string with the stack trace, but limits * to a specific line length. * * @param {Object} error The exception to format, can be anything throwable * @param {Number=} [maxStackLines=5] max lines of the stack trace to include * default is 5. */ function formatException(error, maxStackLines) { maxStackLines = maxStackLines || 5; var message = error.toString(); if (error.stack) { var stack = error.stack.split('\n'); if (stack[0].indexOf(message) === -1) { maxStackLines++; stack.unshift(error.message); } message = stack.slice(0, maxStackLines).join('\n'); } return message; } /** * Returns a function that gets the file name and line number from a * location in the stack if available based on the call site. * * Note: this returns another function because accessing .stack is very * expensive in Chrome. * * @param {Number} offset Number of stack lines to skip */ function callerFile(offset) { var error = new Error(); return function() { var line = (error.stack || '').split('\n')[offset]; // Clean up the stack trace line if (line) { if (line.indexOf('@') !== -1) { // Firefox line = line.substring(line.indexOf('@')+1); } else { // Chrome line = line.substring(line.indexOf('(')+1).replace(')', ''); } } return line || ''; }; } /** * Triggers a browser event. Attempts to choose the right event if one is * not specified. * * @param {Object} element Either a wrapped jQuery/jqLite node or a DOMElement * @param {string} type Optional event type. * @param {Array.<string>=} keys Optional list of pressed keys * (valid values: 'alt', 'meta', 'shift', 'ctrl') */ function browserTrigger(element, type, keys) { if (element && !element.nodeName) element = element[0]; if (!element) return; if (!type) { type = { 'text': 'change', 'textarea': 'change', 'hidden': 'change', 'password': 'change', 'button': 'click', 'submit': 'click', 'reset': 'click', 'image': 'click', 'checkbox': 'click', 'radio': 'click', 'select-one': 'change', 'select-multiple': 'change' }[lowercase(element.type)] || 'click'; } if (lowercase(nodeName_(element)) == 'option') { element.parentNode.value = element.value; element = element.parentNode; type = 'change'; } keys = keys || []; function pressed(key) { return indexOf(keys, key) !== -1; } if (msie < 9) { switch(element.type) { case 'radio': case 'checkbox': element.checked = !element.checked; break; } // WTF!!! Error: Unspecified error. // Don't know why, but some elements when detached seem to be in inconsistent state and // calling .fireEvent() on them will result in very unhelpful error (Error: Unspecified error) // forcing the browser to compute the element position (by reading its CSS) // puts the element in consistent state. element.style.posLeft; // TODO(vojta): create event objects with pressed keys to get it working on IE<9 var ret = element.fireEvent('on' + type); if (lowercase(element.type) == 'submit') { while(element) { if (lowercase(element.nodeName) == 'form') { element.fireEvent('onsubmit'); break; } element = element.parentNode; } } return ret; } else { var evnt = document.createEvent('MouseEvents'), originalPreventDefault = evnt.preventDefault, iframe = _jQuery('#application iframe')[0], appWindow = iframe ? iframe.contentWindow : window, fakeProcessDefault = true, finalProcessDefault; // igor: temporary fix for https://bugzilla.mozilla.org/show_bug.cgi?id=684208 appWindow.angular['ff-684208-preventDefault'] = false; evnt.preventDefault = function() { fakeProcessDefault = false; return originalPreventDefault.apply(evnt, arguments); }; evnt.initMouseEvent(type, true, true, window, 0, 0, 0, 0, 0, pressed('ctrl'), pressed('alt'), pressed('shift'), pressed('meta'), 0, element); element.dispatchEvent(evnt); finalProcessDefault = !(appWindow.angular['ff-684208-preventDefault'] || !fakeProcessDefault); delete appWindow.angular['ff-684208-preventDefault']; return finalProcessDefault; } } /** * Don't use the jQuery trigger method since it works incorrectly. * * jQuery notifies listeners and then changes the state of a checkbox and * does not create a real browser event. A real click changes the state of * the checkbox and then notifies listeners. * * To work around this we instead use our own handler that fires a real event. */ (function(fn){ var parentTrigger = fn.trigger; fn.trigger = function(type) { if (/(click|change|keydown|blur|input)/.test(type)) { var processDefaults = []; this.each(function(index, node) { processDefaults.push(browserTrigger(node, type)); }); // this is not compatible with jQuery - we return an array of returned values, // so that scenario runner know whether JS code has preventDefault() of the event or not... return processDefaults; } return parentTrigger.apply(this, arguments); }; })(_jQuery.fn); /** * Finds all bindings with the substring match of name and returns an * array of their values. * * @param {string} bindExp The name to match * @return {Array.<string>} String of binding values */ _jQuery.fn.bindings = function(windowJquery, bindExp) { var result = [], match, bindSelector = '.ng-binding:visible'; if (angular.isString(bindExp)) { bindExp = bindExp.replace(/\s/g, ''); match = function (actualExp) { if (actualExp) { actualExp = actualExp.replace(/\s/g, ''); if (actualExp == bindExp) return true; if (actualExp.indexOf(bindExp) == 0) { return actualExp.charAt(bindExp.length) == '|'; } } } } else if (bindExp) { match = function(actualExp) { return actualExp && bindExp.exec(actualExp); } } else { match = function(actualExp) { return !!actualExp; }; } var selection = this.find(bindSelector); if (this.is(bindSelector)) { selection = selection.add(this); } function push(value) { if (value == undefined) { value = ''; } else if (typeof value != 'string') { value = angular.toJson(value); } result.push('' + value); } selection.each(function() { var element = windowJquery(this), binding; if (binding = element.data('$binding')) { if (typeof binding == 'string') { if (match(binding)) { push(element.scope().$eval(binding)); } } else { if (!angular.isArray(binding)) { binding = [binding]; } for(var fns, j=0, jj=binding.length; j<jj; j++) { fns = binding[j]; if (fns.parts) { fns = fns.parts; } else { fns = [fns]; } for (var scope, fn, i = 0, ii = fns.length; i < ii; i++) { if(match((fn = fns[i]).exp)) { push(fn(scope = scope || element.scope())); } } } } } }); return result; }; /** * Represents the application currently being tested and abstracts usage * of iframes or separate windows. * * @param {Object} context jQuery wrapper around HTML context. */ angular.scenario.Application = function(context) { this.context = context; context.append( '<h2>Current URL: <a href="about:blank">None</a></h2>' + '<div id="test-frames"></div>' ); }; /** * Gets the jQuery collection of frames. Don't use this directly because * frames may go stale. * * @private * @return {Object} jQuery collection */ angular.scenario.Application.prototype.getFrame_ = function() { return this.context.find('#test-frames iframe:last'); }; /** * Gets the window of the test runner frame. Always favor executeAction() * instead of this method since it prevents you from getting a stale window. * * @private * @return {Object} the window of the frame */ angular.scenario.Application.prototype.getWindow_ = function() { var contentWindow = this.getFrame_().prop('contentWindow'); if (!contentWindow) throw 'Frame window is not accessible.'; return contentWindow; }; /** * Changes the location of the frame. * * @param {string} url The URL. If it begins with a # then only the * hash of the page is changed. * @param {function()} loadFn function($window, $document) Called when frame loads. * @param {function()} errorFn function(error) Called if any error when loading. */ angular.scenario.Application.prototype.navigateTo = function(url, loadFn, errorFn) { var self = this; var frame = this.getFrame_(); //TODO(esprehn): Refactor to use rethrow() errorFn = errorFn || function(e) { throw e; }; if (url === 'about:blank') { errorFn('Sandbox Error: Navigating to about:blank is not allowed.'); } else if (url.charAt(0) === '#') { url = frame.attr('src').split('#')[0] + url; frame.attr('src', url); this.executeAction(loadFn); } else { frame.remove(); this.context.find('#test-frames').append('<iframe>'); frame = this.getFrame_(); frame.load(function() { frame.unbind(); try { self.executeAction(loadFn); } catch (e) { errorFn(e); } }).attr('src', url); } this.context.find('> h2 a').attr('href', url).text(url); }; /** * Executes a function in the context of the tested application. Will wait * for all pending angular xhr requests before executing. * * @param {function()} action The callback to execute. function($window, $document) * $document is a jQuery wrapped document. */ angular.scenario.Application.prototype.executeAction = function(action) { var self = this; var $window = this.getWindow_(); if (!$window.document) { throw 'Sandbox Error: Application document not accessible.'; } if (!$window.angular) { return action.call(this, $window, _jQuery($window.document)); } angularInit($window.document, function(element) { var $injector = $window.angular.element(element).injector(); $injector.invoke(function($browser){ $browser.notifyWhenNoOutstandingRequests(function() { action.call(self, $window, _jQuery($window.document)); }); }); }); }; /** * The representation of define blocks. Don't used directly, instead use * define() in your tests. * * @param {string} descName Name of the block * @param {Object} parent describe or undefined if the root. */ angular.scenario.Describe = function(descName, parent) { this.only = parent && parent.only; this.beforeEachFns = []; this.afterEachFns = []; this.its = []; this.children = []; this.name = descName; this.parent = parent; this.id = angular.scenario.Describe.id++; /** * Calls all before functions. */ var beforeEachFns = this.beforeEachFns; this.setupBefore = function() { if (parent) parent.setupBefore.call(this); angular.forEach(beforeEachFns, function(fn) { fn.call(this); }, this); }; /** * Calls all after functions. */ var afterEachFns = this.afterEachFns; this.setupAfter = function() { angular.forEach(afterEachFns, function(fn) { fn.call(this); }, this); if (parent) parent.setupAfter.call(this); }; }; // Shared Unique ID generator for every describe block angular.scenario.Describe.id = 0; // Shared Unique ID generator for every it (spec) angular.scenario.Describe.specId = 0; /** * Defines a block to execute before each it or nested describe. * * @param {function()} body Body of the block. */ angular.scenario.Describe.prototype.beforeEach = function(body) { this.beforeEachFns.push(body); }; /** * Defines a block to execute after each it or nested describe. * * @param {function()} body Body of the block. */ angular.scenario.Describe.prototype.afterEach = function(body) { this.afterEachFns.push(body); }; /** * Creates a new describe block that's a child of this one. * * @param {string} name Name of the block. Appended to the parent block's name. * @param {function()} body Body of the block. */ angular.scenario.Describe.prototype.describe = function(name, body) { var child = new angular.scenario.Describe(name, this); this.children.push(child); body.call(child); }; /** * Same as describe() but makes ddescribe blocks the only to run. * * @param {string} name Name of the test. * @param {function()} body Body of the block. */ angular.scenario.Describe.prototype.ddescribe = function(name, body) { var child = new angular.scenario.Describe(name, this); child.only = true; this.children.push(child); body.call(child); }; /** * Use to disable a describe block. */ angular.scenario.Describe.prototype.xdescribe = angular.noop; /** * Defines a test. * * @param {string} name Name of the test. * @param {function()} vody Body of the block. */ angular.scenario.Describe.prototype.it = function(name, body) { this.its.push({ id: angular.scenario.Describe.specId++, definition: this, only: this.only, name: name, before: this.setupBefore, body: body, after: this.setupAfter }); }; /** * Same as it() but makes iit tests the only test to run. * * @param {string} name Name of the test. * @param {function()} body Body of the block. */ angular.scenario.Describe.prototype.iit = function(name, body) { this.it.apply(this, arguments); this.its[this.its.length-1].only = true; }; /** * Use to disable a test block. */ angular.scenario.Describe.prototype.xit = angular.noop; /** * Gets an array of functions representing all the tests (recursively). * that can be executed with SpecRunner's. * * @return {Array<Object>} Array of it blocks { * definition : Object // parent Describe * only: boolean * name: string * before: Function * body: Function * after: Function * } */ angular.scenario.Describe.prototype.getSpecs = function() { var specs = arguments[0] || []; angular.forEach(this.children, function(child) { child.getSpecs(specs); }); angular.forEach(this.its, function(it) { specs.push(it); }); var only = []; angular.forEach(specs, function(it) { if (it.only) { only.push(it); } }); return (only.length && only) || specs; }; /** * A future action in a spec. * * @param {string} name of the future action * @param {function()} future callback(error, result) * @param {function()} Optional. function that returns the file/line number. */ angular.scenario.Future = function(name, behavior, line) { this.name = name; this.behavior = behavior; this.fulfilled = false; this.value = undefined; this.parser = angular.identity; this.line = line || function() { return ''; }; }; /** * Executes the behavior of the closure. * * @param {function()} doneFn Callback function(error, result) */ angular.scenario.Future.prototype.execute = function(doneFn) { var self = this; this.behavior(function(error, result) { self.fulfilled = true; if (result) { try { result = self.parser(result); } catch(e) { error = e; } } self.value = error || result; doneFn(error, result); }); }; /** * Configures the future to convert it's final with a function fn(value) * * @param {function()} fn function(value) that returns the parsed value */ angular.scenario.Future.prototype.parsedWith = function(fn) { this.parser = fn; return this; }; /** * Configures the future to parse it's final value from JSON * into objects. */ angular.scenario.Future.prototype.fromJson = function() { return this.parsedWith(angular.fromJson); }; /** * Configures the future to convert it's final value from objects * into JSON. */ angular.scenario.Future.prototype.toJson = function() { return this.parsedWith(angular.toJson); }; /** * Maintains an object tree from the runner events. * * @param {Object} runner The scenario Runner instance to connect to. * * TODO(esprehn): Every output type creates one of these, but we probably * want one global shared instance. Need to handle events better too * so the HTML output doesn't need to do spec model.getSpec(spec.id) * silliness. * * TODO(vojta) refactor on, emit methods (from all objects) - use inheritance */ angular.scenario.ObjectModel = function(runner) { var self = this; this.specMap = {}; this.listeners = []; this.value = { name: '', children: {} }; runner.on('SpecBegin', function(spec) { var block = self.value, definitions = []; angular.forEach(self.getDefinitionPath(spec), function(def) { if (!block.children[def.name]) { block.children[def.name] = { id: def.id, name: def.name, children: {}, specs: {} }; } block = block.children[def.name]; definitions.push(def.name); }); var it = self.specMap[spec.id] = block.specs[spec.name] = new angular.scenario.ObjectModel.Spec(spec.id, spec.name, definitions); // forward the event self.emit('SpecBegin', it); }); runner.on('SpecError', function(spec, error) { var it = self.getSpec(spec.id); it.status = 'error'; it.error = error; // forward the event self.emit('SpecError', it, error); }); runner.on('SpecEnd', function(spec) { var it = self.getSpec(spec.id); complete(it); // forward the event self.emit('SpecEnd', it); }); runner.on('StepBegin', function(spec, step) { var it = self.getSpec(spec.id); var step = new angular.scenario.ObjectModel.Step(step.name); it.steps.push(step); // forward the event self.emit('StepBegin', it, step); }); runner.on('StepEnd', function(spec) { var it = self.getSpec(spec.id); var step = it.getLastStep(); if (step.name !== step.name) throw 'Events fired in the wrong order. Step names don\'t match.'; complete(step); // forward the event self.emit('StepEnd', it, step); }); runner.on('StepFailure', function(spec, step, error) { var it = self.getSpec(spec.id), modelStep = it.getLastStep(); modelStep.setErrorStatus('failure', error, step.line()); it.setStatusFromStep(modelStep); // forward the event self.emit('StepFailure', it, modelStep, error); }); runner.on('StepError', function(spec, step, error) { var it = self.getSpec(spec.id), modelStep = it.getLastStep(); modelStep.setErrorStatus('error', error, step.line()); it.setStatusFromStep(modelStep); // forward the event self.emit('StepError', it, modelStep, error); }); runner.on('RunnerEnd', function() { self.emit('RunnerEnd'); }); function complete(item) { item.endTime = new Date().getTime(); item.duration = item.endTime - item.startTime; item.status = item.status || 'success'; } }; /** * Adds a listener for an event. * * @param {string} eventName Name of the event to add a handler for * @param {function()} listener Function that will be called when event is fired */ angular.scenario.ObjectModel.prototype.on = function(eventName, listener) { eventName = eventName.toLowerCase(); this.listeners[eventName] = this.listeners[eventName] || []; this.listeners[eventName].push(listener); }; /** * Emits an event which notifies listeners and passes extra * arguments. * * @param {string} eventName Name of the event to fire. */ angular.scenario.ObjectModel.prototype.emit = function(eventName) { var self = this, args = Array.prototype.slice.call(arguments, 1), eventName = eventName.toLowerCase(); if (this.listeners[eventName]) { angular.forEach(this.listeners[eventName], function(listener) { listener.apply(self, args); }); } }; /** * Computes the path of definition describe blocks that wrap around * this spec. * * @param spec Spec to compute the path for. * @return {Array<Describe>} The describe block path */ angular.scenario.ObjectModel.prototype.getDefinitionPath = function(spec) { var path = []; var currentDefinition = spec.definition; while (currentDefinition && currentDefinition.name) { path.unshift(currentDefinition); currentDefinition = currentDefinition.parent; } return path; }; /** * Gets a spec by id. * * @param {string} The id of the spec to get the object for. * @return {Object} the Spec instance */ angular.scenario.ObjectModel.prototype.getSpec = function(id) { return this.specMap[id]; }; /** * A single it block. * * @param {string} id Id of the spec * @param {string} name Name of the spec * @param {Array<string>=} definitionNames List of all describe block names that wrap this spec */ angular.scenario.ObjectModel.Spec = function(id, name, definitionNames) { this.id = id; this.name = name; this.startTime = new Date().getTime(); this.steps = []; this.fullDefinitionName = (definitionNames || []).join(' '); }; /** * Adds a new step to the Spec. * * @param {string} step Name of the step (really name of the future) * @return {Object} the added step */ angular.scenario.ObjectModel.Spec.prototype.addStep = function(name) { var step = new angular.scenario.ObjectModel.Step(name); this.steps.push(step); return step; }; /** * Gets the most recent step. * * @return {Object} the step */ angular.scenario.ObjectModel.Spec.prototype.getLastStep = function() { return this.steps[this.steps.length-1]; }; /** * Set status of the Spec from given Step * * @param {angular.scenario.ObjectModel.Step} step */ angular.scenario.ObjectModel.Spec.prototype.setStatusFromStep = function(step) { if (!this.status || step.status == 'error') { this.status = step.status; this.error = step.error; this.line = step.line; } }; /** * A single step inside a Spec. * * @param {string} step Name of the step */ angular.scenario.ObjectModel.Step = function(name) { this.name = name; this.startTime = new Date().getTime(); }; /** * Helper method for setting all error status related properties * * @param {string} status * @param {string} error * @param {string} line */ angular.scenario.ObjectModel.Step.prototype.setErrorStatus = function(status, error, line) { this.status = status; this.error = error; this.line = line; }; /** * The representation of define blocks. Don't used directly, instead use * define() in your tests. * * @param {string} descName Name of the block * @param {Object} parent describe or undefined if the root. */ angular.scenario.Describe = function(descName, parent) { this.only = parent && parent.only; this.beforeEachFns = []; this.afterEachFns = []; this.its = []; this.children = []; this.name = descName; this.parent = parent; this.id = angular.scenario.Describe.id++; /** * Calls all before functions. */ var beforeEachFns = this.beforeEachFns; this.setupBefore = function() { if (parent) parent.setupBefore.call(this); angular.forEach(beforeEachFns, function(fn) { fn.call(this); }, this); }; /** * Calls all after functions. */ var afterEachFns = this.afterEachFns; this.setupAfter = function() { angular.forEach(afterEachFns, function(fn) { fn.call(this); }, this); if (parent) parent.setupAfter.call(this); }; }; // Shared Unique ID generator for every describe block angular.scenario.Describe.id = 0; // Shared Unique ID generator for every it (spec) angular.scenario.Describe.specId = 0; /** * Defines a block to execute before each it or nested describe. * * @param {function()} body Body of the block. */ angular.scenario.Describe.prototype.beforeEach = function(body) { this.beforeEachFns.push(body); }; /** * Defines a block to execute after each it or nested describe. * * @param {function()} body Body of the block. */ angular.scenario.Describe.prototype.afterEach = function(body) { this.afterEachFns.push(body); }; /** * Creates a new describe block that's a child of this one. * * @param {string} name Name of the block. Appended to the parent block's name. * @param {function()} body Body of the block. */ angular.scenario.Describe.prototype.describe = function(name, body) { var child = new angular.scenario.Describe(name, this); this.children.push(child); body.call(child); }; /** * Same as describe() but makes ddescribe blocks the only to run. * * @param {string} name Name of the test. * @param {function()} body Body of the block. */ angular.scenario.Describe.prototype.ddescribe = function(name, body) { var child = new angular.scenario.Describe(name, this); child.only = true; this.children.push(child); body.call(child); }; /** * Use to disable a describe block. */ angular.scenario.Describe.prototype.xdescribe = angular.noop; /** * Defines a test. * * @param {string} name Name of the test. * @param {function()} vody Body of the block. */ angular.scenario.Describe.prototype.it = function(name, body) { this.its.push({ id: angular.scenario.Describe.specId++, definition: this, only: this.only, name: name, before: this.setupBefore, body: body, after: this.setupAfter }); }; /** * Same as it() but makes iit tests the only test to run. * * @param {string} name Name of the test. * @param {function()} body Body of the block. */ angular.scenario.Describe.prototype.iit = function(name, body) { this.it.apply(this, arguments); this.its[this.its.length-1].only = true; }; /** * Use to disable a test block. */ angular.scenario.Describe.prototype.xit = angular.noop; /** * Gets an array of functions representing all the tests (recursively). * that can be executed with SpecRunner's. * * @return {Array<Object>} Array of it blocks { * definition : Object // parent Describe * only: boolean * name: string * before: Function * body: Function * after: Function * } */ angular.scenario.Describe.prototype.getSpecs = function() { var specs = arguments[0] || []; angular.forEach(this.children, function(child) { child.getSpecs(specs); }); angular.forEach(this.its, function(it) { specs.push(it); }); var only = []; angular.forEach(specs, function(it) { if (it.only) { only.push(it); } }); return (only.length && only) || specs; }; /** * Runner for scenarios * * Has to be initialized before any test is loaded, * because it publishes the API into window (global space). */ angular.scenario.Runner = function($window) { this.listeners = []; this.$window = $window; this.rootDescribe = new angular.scenario.Describe(); this.currentDescribe = this.rootDescribe; this.api = { it: this.it, iit: this.iit, xit: angular.noop, describe: this.describe, ddescribe: this.ddescribe, xdescribe: angular.noop, beforeEach: this.beforeEach, afterEach: this.afterEach }; angular.forEach(this.api, angular.bind(this, function(fn, key) { this.$window[key] = angular.bind(this, fn); })); }; /** * Emits an event which notifies listeners and passes extra * arguments. * * @param {string} eventName Name of the event to fire. */ angular.scenario.Runner.prototype.emit = function(eventName) { var self = this; var args = Array.prototype.slice.call(arguments, 1); eventName = eventName.toLowerCase(); if (!this.listeners[eventName]) return; angular.forEach(this.listeners[eventName], function(listener) { listener.apply(self, args); }); }; /** * Adds a listener for an event. * * @param {string} eventName The name of the event to add a handler for * @param {string} listener The fn(...) that takes the extra arguments from emit() */ angular.scenario.Runner.prototype.on = function(eventName, listener) { eventName = eventName.toLowerCase(); this.listeners[eventName] = this.listeners[eventName] || []; this.listeners[eventName].push(listener); }; /** * Defines a describe block of a spec. * * @see Describe.js * * @param {string} name Name of the block * @param {function()} body Body of the block */ angular.scenario.Runner.prototype.describe = function(name, body) { var self = this; this.currentDescribe.describe(name, function() { var parentDescribe = self.currentDescribe; self.currentDescribe = this; try { body.call(this); } finally { self.currentDescribe = parentDescribe; } }); }; /** * Same as describe, but makes ddescribe the only blocks to run. * * @see Describe.js * * @param {string} name Name of the block * @param {function()} body Body of the block */ angular.scenario.Runner.prototype.ddescribe = function(name, body) { var self = this; this.currentDescribe.ddescribe(name, function() { var parentDescribe = self.currentDescribe; self.currentDescribe = this; try { body.call(this); } finally { self.currentDescribe = parentDescribe; } }); }; /** * Defines a test in a describe block of a spec. * * @see Describe.js * * @param {string} name Name of the block * @param {function()} body Body of the block */ angular.scenario.Runner.prototype.it = function(name, body) { this.currentDescribe.it(name, body); }; /** * Same as it, but makes iit tests the only tests to run. * * @see Describe.js * * @param {string} name Name of the block * @param {function()} body Body of the block */ angular.scenario.Runner.prototype.iit = function(name, body) { this.currentDescribe.iit(name, body); }; /** * Defines a function to be called before each it block in the describe * (and before all nested describes). * * @see Describe.js * * @param {function()} Callback to execute */ angular.scenario.Runner.prototype.beforeEach = function(body) { this.currentDescribe.beforeEach(body); }; /** * Defines a function to be called after each it block in the describe * (and before all nested describes). * * @see Describe.js * * @param {function()} Callback to execute */ angular.scenario.Runner.prototype.afterEach = function(body) { this.currentDescribe.afterEach(body); }; /** * Creates a new spec runner. * * @private * @param {Object} scope parent scope */ angular.scenario.Runner.prototype.createSpecRunner_ = function(scope) { var child = scope.$new(); var Cls = angular.scenario.SpecRunner; // Export all the methods to child scope manually as now we don't mess controllers with scopes // TODO(vojta): refactor scenario runner so that these objects are not tightly coupled as current for (var name in Cls.prototype) child[name] = angular.bind(child, Cls.prototype[name]); Cls.call(child); return child; }; /** * Runs all the loaded tests with the specified runner class on the * provided application. * * @param {angular.scenario.Application} application App to remote control. */ angular.scenario.Runner.prototype.run = function(application) { var self = this; var $root = angular.injector(['ng']).get('$rootScope'); angular.extend($root, this); angular.forEach(angular.scenario.Runner.prototype, function(fn, name) { $root[name] = angular.bind(self, fn); }); $root.application = application; $root.emit('RunnerBegin'); asyncForEach(this.rootDescribe.getSpecs(), function(spec, specDone) { var dslCache = {}; var runner = self.createSpecRunner_($root); angular.forEach(angular.scenario.dsl, function(fn, key) { dslCache[key] = fn.call($root); }); angular.forEach(angular.scenario.dsl, function(fn, key) { self.$window[key] = function() { var line = callerFile(3); var scope = runner.$new(); // Make the dsl accessible on the current chain scope.dsl = {}; angular.forEach(dslCache, function(fn, key) { scope.dsl[key] = function() { return dslCache[key].apply(scope, arguments); }; }); // Make these methods work on the current chain scope.addFuture = function() { Array.prototype.push.call(arguments, line); return angular.scenario.SpecRunner. prototype.addFuture.apply(scope, arguments); }; scope.addFutureAction = function() { Array.prototype.push.call(arguments, line); return angular.scenario.SpecRunner. prototype.addFutureAction.apply(scope, arguments); }; return scope.dsl[key].apply(scope, arguments); }; }); runner.run(spec, function() { runner.$destroy(); specDone.apply(this, arguments); }); }, function(error) { if (error) { self.emit('RunnerError', error); } self.emit('RunnerEnd'); }); }; /** * This class is the "this" of the it/beforeEach/afterEach method. * Responsibilities: * - "this" for it/beforeEach/afterEach * - keep state for single it/beforeEach/afterEach execution * - keep track of all of the futures to execute * - run single spec (execute each future) */ angular.scenario.SpecRunner = function() { this.futures = []; this.afterIndex = 0; }; /** * Executes a spec which is an it block with associated before/after functions * based on the describe nesting. * * @param {Object} spec A spec object * @param {function()} specDone function that is called when the spec finshes. Function(error, index) */ angular.scenario.SpecRunner.prototype.run = function(spec, specDone) { var self = this; this.spec = spec; this.emit('SpecBegin', spec); try { spec.before.call(this); spec.body.call(this); this.afterIndex = this.futures.length; spec.after.call(this); } catch (e) { this.emit('SpecError', spec, e); this.emit('SpecEnd', spec); specDone(); return; } var handleError = function(error, done) { if (self.error) { return done(); } self.error = true; done(null, self.afterIndex); }; asyncForEach( this.futures, function(future, futureDone) { self.step = future; self.emit('StepBegin', spec, future); try { future.execute(function(error) { if (error) { self.emit('StepFailure', spec, future, error); self.emit('StepEnd', spec, future); return handleError(error, futureDone); } self.emit('StepEnd', spec, future); self.$window.setTimeout(function() { futureDone(); }, 0); }); } catch (e) { self.emit('StepError', spec, future, e); self.emit('StepEnd', spec, future); handleError(e, futureDone); } }, function(e) { if (e) { self.emit('SpecError', spec, e); } self.emit('SpecEnd', spec); // Call done in a timeout so exceptions don't recursively // call this function self.$window.setTimeout(function() { specDone(); }, 0); } ); }; /** * Adds a new future action. * * Note: Do not pass line manually. It happens automatically. * * @param {string} name Name of the future * @param {function()} behavior Behavior of the future * @param {function()} line fn() that returns file/line number */ angular.scenario.SpecRunner.prototype.addFuture = function(name, behavior, line) { var future = new angular.scenario.Future(name, angular.bind(this, behavior), line); this.futures.push(future); return future; }; /** * Adds a new future action to be executed on the application window. * * Note: Do not pass line manually. It happens automatically. * * @param {string} name Name of the future * @param {function()} behavior Behavior of the future * @param {function()} line fn() that returns file/line number */ angular.scenario.SpecRunner.prototype.addFutureAction = function(name, behavior, line) { var self = this; var NG = /\[ng\\\:/; return this.addFuture(name, function(done) { this.application.executeAction(function($window, $document) { //TODO(esprehn): Refactor this so it doesn't need to be in here. $document.elements = function(selector) { var args = Array.prototype.slice.call(arguments, 1); selector = (self.selector || '') + ' ' + (selector || ''); selector = _jQuery.trim(selector) || '*'; angular.forEach(args, function(value, index) { selector = selector.replace('$' + (index + 1), value); }); var result = $document.find(selector); if (selector.match(NG)) { result = result.add(selector.replace(NG, '[ng-'), $document); } if (!result.length) { throw { type: 'selector', message: 'Selector ' + selector + ' did not match any elements.' }; } return result; }; try { behavior.call(self, $window, $document, done); } catch(e) { if (e.type && e.type === 'selector') { done(e.message); } else { throw e; } } }); }, line); }; /** * Shared DSL statements that are useful to all scenarios. */ /** * Usage: * pause() pauses until you call resume() in the console */ angular.scenario.dsl('pause', function() { return function() { return this.addFuture('pausing for you to resume', function(done) { this.emit('InteractivePause', this.spec, this.step); this.$window.resume = function() { done(); }; }); }; }); /** * Usage: * sleep(seconds) pauses the test for specified number of seconds */ angular.scenario.dsl('sleep', function() { return function(time) { return this.addFuture('sleep for ' + time + ' seconds', function(done) { this.$window.setTimeout(function() { done(null, time * 1000); }, time * 1000); }); }; }); /** * Usage: * browser().navigateTo(url) Loads the url into the frame * browser().navigateTo(url, fn) where fn(url) is called and returns the URL to navigate to * browser().reload() refresh the page (reload the same URL) * browser().window.href() window.location.href * browser().window.path() window.location.pathname * browser().window.search() window.location.search * browser().window.hash() window.location.hash without # prefix * browser().location().url() see angular.module.ng.$location#url * browser().location().path() see angular.module.ng.$location#path * browser().location().search() see angular.module.ng.$location#search * browser().location().hash() see angular.module.ng.$location#hash */ angular.scenario.dsl('browser', function() { var chain = {}; chain.navigateTo = function(url, delegate) { var application = this.application; return this.addFuture("browser navigate to '" + url + "'", function(done) { if (delegate) { url = delegate.call(this, url); } application.navigateTo(url, function() { done(null, url); }, done); }); }; chain.reload = function() { var application = this.application; return this.addFutureAction('browser reload', function($window, $document, done) { var href = $window.location.href; application.navigateTo(href, function() { done(null, href); }, done); }); }; chain.window = function() { var api = {}; api.href = function() { return this.addFutureAction('window.location.href', function($window, $document, done) { done(null, $window.location.href); }); }; api.path = function() { return this.addFutureAction('window.location.path', function($window, $document, done) { done(null, $window.location.pathname); }); }; api.search = function() { return this.addFutureAction('window.location.search', function($window, $document, done) { done(null, $window.location.search); }); }; api.hash = function() { return this.addFutureAction('window.location.hash', function($window, $document, done) { done(null, $window.location.hash.replace('#', '')); }); }; return api; }; chain.location = function() { var api = {}; api.url = function() { return this.addFutureAction('$location.url()', function($window, $document, done) { done(null, $window.angular.element($window.document).injector().get('$location').url()); }); }; api.path = function() { return this.addFutureAction('$location.path()', function($window, $document, done) { done(null, $window.angular.element($window.document).injector().get('$location').path()); }); }; api.search = function() { return this.addFutureAction('$location.search()', function($window, $document, done) { done(null, $window.angular.element($window.document).injector().get('$location').search()); }); }; api.hash = function() { return this.addFutureAction('$location.hash()', function($window, $document, done) { done(null, $window.angular.element($window.document).injector().get('$location').hash()); }); }; return api; }; return function() { return chain; }; }); /** * Usage: * expect(future).{matcher} where matcher is one of the matchers defined * with angular.scenario.matcher * * ex. expect(binding("name")).toEqual("Elliott") */ angular.scenario.dsl('expect', function() { var chain = angular.extend({}, angular.scenario.matcher); chain.not = function() { this.inverse = true; return chain; }; return function(future) { this.future = future; return chain; }; }); /** * Usage: * using(selector, label) scopes the next DSL element selection * * ex. * using('#foo', "'Foo' text field").input('bar') */ angular.scenario.dsl('using', function() { return function(selector, label) { this.selector = _jQuery.trim((this.selector||'') + ' ' + selector); if (angular.isString(label) && label.length) { this.label = label + ' ( ' + this.selector + ' )'; } else { this.label = this.selector; } return this.dsl; }; }); /** * Usage: * binding(name) returns the value of the first matching binding */ angular.scenario.dsl('binding', function() { return function(name) { return this.addFutureAction("select binding '" + name + "'", function($window, $document, done) { var values = $document.elements().bindings($window.angular.element, name); if (!values.length) { return done("Binding selector '" + name + "' did not match."); } done(null, values[0]); }); }; }); /** * Usage: * input(name).enter(value) enters value in input with specified name * input(name).check() checks checkbox * input(name).select(value) selects the radio button with specified name/value * input(name).val() returns the value of the input. */ angular.scenario.dsl('input', function() { var chain = {}; var supportInputEvent = 'oninput' in document.createElement('div'); chain.enter = function(value, event) { return this.addFutureAction("input '" + this.name + "' enter '" + value + "'", function($window, $document, done) { var input = $document.elements('[ng\\:model="$1"]', this.name).filter(':input'); input.val(value); input.trigger(event || supportInputEvent && 'input' || 'change'); done(); }); }; chain.check = function() { return this.addFutureAction("checkbox '" + this.name + "' toggle", function($window, $document, done) { var input = $document.elements('[ng\\:model="$1"]', this.name).filter(':checkbox'); input.trigger('click'); done(); }); }; chain.select = function(value) { return this.addFutureAction("radio button '" + this.name + "' toggle '" + value + "'", function($window, $document, done) { var input = $document. elements('[ng\\:model="$1"][value="$2"]', this.name, value).filter(':radio'); input.trigger('click'); done(); }); }; chain.val = function() { return this.addFutureAction("return input val", function($window, $document, done) { var input = $document.elements('[ng\\:model="$1"]', this.name).filter(':input'); done(null,input.val()); }); }; return function(name) { this.name = name; return chain; }; }); /** * Usage: * repeater('#products table', 'Product List').count() number of rows * repeater('#products table', 'Product List').row(1) all bindings in row as an array * repeater('#products table', 'Product List').column('product.name') all values across all rows in an array */ angular.scenario.dsl('repeater', function() { var chain = {}; chain.count = function() { return this.addFutureAction("repeater '" + this.label + "' count", function($window, $document, done) { try { done(null, $document.elements().length); } catch (e) { done(null, 0); } }); }; chain.column = function(binding) { return this.addFutureAction("repeater '" + this.label + "' column '" + binding + "'", function($window, $document, done) { done(null, $document.elements().bindings($window.angular.element, binding)); }); }; chain.row = function(index) { return this.addFutureAction("repeater '" + this.label + "' row '" + index + "'", function($window, $document, done) { var matches = $document.elements().slice(index, index + 1); if (!matches.length) return done('row ' + index + ' out of bounds'); done(null, matches.bindings($window.angular.element)); }); }; return function(selector, label) { this.dsl.using(selector, label); return chain; }; }); /** * Usage: * select(name).option('value') select one option * select(name).options('value1', 'value2', ...) select options from a multi select */ angular.scenario.dsl('select', function() { var chain = {}; chain.option = function(value) { return this.addFutureAction("select '" + this.name + "' option '" + value + "'", function($window, $document, done) { var select = $document.elements('select[ng\\:model="$1"]', this.name); var option = select.find('option[value="' + value + '"]'); if (option.length) { select.val(value); } else { option = select.find('option:contains("' + value + '")'); if (option.length) { select.val(option.val()); } } select.trigger('change'); done(); }); }; chain.options = function() { var values = arguments; return this.addFutureAction("select '" + this.name + "' options '" + values + "'", function($window, $document, done) { var select = $document.elements('select[multiple][ng\\:model="$1"]', this.name); select.val(values); select.trigger('change'); done(); }); }; return function(name) { this.name = name; return chain; }; }); /** * Usage: * element(selector, label).count() get the number of elements that match selector * element(selector, label).click() clicks an element * element(selector, label).query(fn) executes fn(selectedElements, done) * element(selector, label).{method}() gets the value (as defined by jQuery, ex. val) * element(selector, label).{method}(value) sets the value (as defined by jQuery, ex. val) * element(selector, label).{method}(key) gets the value (as defined by jQuery, ex. attr) * element(selector, label).{method}(key, value) sets the value (as defined by jQuery, ex. attr) */ angular.scenario.dsl('element', function() { var KEY_VALUE_METHODS = ['attr', 'css', 'prop']; var VALUE_METHODS = [ 'val', 'text', 'html', 'height', 'innerHeight', 'outerHeight', 'width', 'innerWidth', 'outerWidth', 'position', 'scrollLeft', 'scrollTop', 'offset' ]; var chain = {}; chain.count = function() { return this.addFutureAction("element '" + this.label + "' count", function($window, $document, done) { try { done(null, $document.elements().length); } catch (e) { done(null, 0); } }); }; chain.click = function() { return this.addFutureAction("element '" + this.label + "' click", function($window, $document, done) { var elements = $document.elements(); var href = elements.attr('href'); var eventProcessDefault = elements.trigger('click')[0]; if (href && elements[0].nodeName.toUpperCase() === 'A' && eventProcessDefault) { this.application.navigateTo(href, function() { done(); }, done); } else { done(); } }); }; chain.query = function(fn) { return this.addFutureAction('element ' + this.label + ' custom query', function($window, $document, done) { fn.call(this, $document.elements(), done); }); }; angular.forEach(KEY_VALUE_METHODS, function(methodName) { chain[methodName] = function(name, value) { var args = arguments, futureName = (args.length == 1) ? "element '" + this.label + "' get " + methodName + " '" + name + "'" : "element '" + this.label + "' set " + methodName + " '" + name + "' to " + "'" + value + "'"; return this.addFutureAction(futureName, function($window, $document, done) { var element = $document.elements(); done(null, element[methodName].apply(element, args)); }); }; }); angular.forEach(VALUE_METHODS, function(methodName) { chain[methodName] = function(value) { var args = arguments, futureName = (args.length == 0) ? "element '" + this.label + "' " + methodName : futureName = "element '" + this.label + "' set " + methodName + " to '" + value + "'"; return this.addFutureAction(futureName, function($window, $document, done) { var element = $document.elements(); done(null, element[methodName].apply(element, args)); }); }; }); return function(selector, label) { this.dsl.using(selector, label); return chain; }; }); /** * Matchers for implementing specs. Follows the Jasmine spec conventions. */ angular.scenario.matcher('toEqual', function(expected) { return angular.equals(this.actual, expected); }); angular.scenario.matcher('toBe', function(expected) { return this.actual === expected; }); angular.scenario.matcher('toBeDefined', function() { return angular.isDefined(this.actual); }); angular.scenario.matcher('toBeTruthy', function() { return this.actual; }); angular.scenario.matcher('toBeFalsy', function() { return !this.actual; }); angular.scenario.matcher('toMatch', function(expected) { return new RegExp(expected).test(this.actual); }); angular.scenario.matcher('toBeNull', function() { return this.actual === null; }); angular.scenario.matcher('toContain', function(expected) { return includes(this.actual, expected); }); angular.scenario.matcher('toBeLessThan', function(expected) { return this.actual < expected; }); angular.scenario.matcher('toBeGreaterThan', function(expected) { return this.actual > expected; }); /** * User Interface for the Scenario Runner. * * TODO(esprehn): This should be refactored now that ObjectModel exists * to use angular bindings for the UI. */ angular.scenario.output('html', function(context, runner, model) { var specUiMap = {}, lastStepUiMap = {}; context.append( '<div id="header">' + ' <h1><span class="angular">AngularJS</span>: Scenario Test Runner</h1>' + ' <ul id="status-legend" class="status-display">' + ' <li class="status-error">0 Errors</li>' + ' <li class="status-failure">0 Failures</li>' + ' <li class="status-success">0 Passed</li>' + ' </ul>' + '</div>' + '<div id="specs">' + ' <div class="test-children"></div>' + '</div>' ); runner.on('InteractivePause', function(spec) { var ui = lastStepUiMap[spec.id]; ui.find('.test-title'). html('paused... <a href="javascript:resume()">resume</a> when ready.'); }); runner.on('SpecBegin', function(spec) { var ui = findContext(spec); ui.find('> .tests').append( '<li class="status-pending test-it"></li>' ); ui = ui.find('> .tests li:last'); ui.append( '<div class="test-info">' + ' <p class="test-title">' + ' <span class="timer-result"></span>' + ' <span class="test-name"></span>' + ' </p>' + '</div>' + '<div class="scrollpane">' + ' <ol class="test-actions"></ol>' + '</div>' ); ui.find('> .test-info .test-name').text(spec.name); ui.find('> .test-info').click(function() { var scrollpane = ui.find('> .scrollpane'); var actions = scrollpane.find('> .test-actions'); var name = context.find('> .test-info .test-name'); if (actions.find(':visible').length) { actions.hide(); name.removeClass('open').addClass('closed'); } else { actions.show(); scrollpane.attr('scrollTop', scrollpane.attr('scrollHeight')); name.removeClass('closed').addClass('open'); } }); specUiMap[spec.id] = ui; }); runner.on('SpecError', function(spec, error) { var ui = specUiMap[spec.id]; ui.append('<pre></pre>'); ui.find('> pre').text(formatException(error)); }); runner.on('SpecEnd', function(spec) { var ui = specUiMap[spec.id]; spec = model.getSpec(spec.id); ui.removeClass('status-pending'); ui.addClass('status-' + spec.status); ui.find("> .test-info .timer-result").text(spec.duration + "ms"); if (spec.status === 'success') { ui.find('> .test-info .test-name').addClass('closed'); ui.find('> .scrollpane .test-actions').hide(); } updateTotals(spec.status); }); runner.on('StepBegin', function(spec, step) { var ui = specUiMap[spec.id]; spec = model.getSpec(spec.id); step = spec.getLastStep(); ui.find('> .scrollpane .test-actions').append('<li class="status-pending"></li>'); var stepUi = lastStepUiMap[spec.id] = ui.find('> .scrollpane .test-actions li:last'); stepUi.append( '<div class="timer-result"></div>' + '<div class="test-title"></div>' ); stepUi.find('> .test-title').text(step.name); var scrollpane = stepUi.parents('.scrollpane'); scrollpane.attr('scrollTop', scrollpane.attr('scrollHeight')); }); runner.on('StepFailure', function(spec, step, error) { var ui = lastStepUiMap[spec.id]; addError(ui, step.line, error); }); runner.on('StepError', function(spec, step, error) { var ui = lastStepUiMap[spec.id]; addError(ui, step.line, error); }); runner.on('StepEnd', function(spec, step) { var stepUi = lastStepUiMap[spec.id]; spec = model.getSpec(spec.id); step = spec.getLastStep(); stepUi.find('.timer-result').text(step.duration + 'ms'); stepUi.removeClass('status-pending'); stepUi.addClass('status-' + step.status); var scrollpane = specUiMap[spec.id].find('> .scrollpane'); scrollpane.attr('scrollTop', scrollpane.attr('scrollHeight')); }); /** * Finds the context of a spec block defined by the passed definition. * * @param {Object} The definition created by the Describe object. */ function findContext(spec) { var currentContext = context.find('#specs'); angular.forEach(model.getDefinitionPath(spec), function(defn) { var id = 'describe-' + defn.id; if (!context.find('#' + id).length) { currentContext.find('> .test-children').append( '<div class="test-describe" id="' + id + '">' + ' <h2></h2>' + ' <div class="test-children"></div>' + ' <ul class="tests"></ul>' + '</div>' ); context.find('#' + id).find('> h2').text('describe: ' + defn.name); } currentContext = context.find('#' + id); }); return context.find('#describe-' + spec.definition.id); } /** * Updates the test counter for the status. * * @param {string} the status. */ function updateTotals(status) { var legend = context.find('#status-legend .status-' + status); var parts = legend.text().split(' '); var value = (parts[0] * 1) + 1; legend.text(value + ' ' + parts[1]); } /** * Add an error to a step. * * @param {Object} The JQuery wrapped context * @param {function()} fn() that should return the file/line number of the error * @param {Object} the error. */ function addError(context, line, error) { context.find('.test-title').append('<pre></pre>'); var message = _jQuery.trim(line() + '\n\n' + formatException(error)); context.find('.test-title pre:last').text(message); } }); /** * Generates JSON output into a context. */ angular.scenario.output('json', function(context, runner, model) { model.on('RunnerEnd', function() { context.text(angular.toJson(model.value)); }); }); /** * Generates XML output into a context. */ angular.scenario.output('xml', function(context, runner, model) { var $ = function(args) {return new context.init(args);}; model.on('RunnerEnd', function() { var scenario = $('<scenario></scenario>'); context.append(scenario); serializeXml(scenario, model.value); }); /** * Convert the tree into XML. * * @param {Object} context jQuery context to add the XML to. * @param {Object} tree node to serialize */ function serializeXml(context, tree) { angular.forEach(tree.children, function(child) { var describeContext = $('<describe></describe>'); describeContext.attr('id', child.id); describeContext.attr('name', child.name); context.append(describeContext); serializeXml(describeContext, child); }); var its = $('<its></its>'); context.append(its); angular.forEach(tree.specs, function(spec) { var it = $('<it></it>'); it.attr('id', spec.id); it.attr('name', spec.name); it.attr('duration', spec.duration); it.attr('status', spec.status); its.append(it); angular.forEach(spec.steps, function(step) { var stepContext = $('<step></step>'); stepContext.attr('name', step.name); stepContext.attr('duration', step.duration); stepContext.attr('status', step.status); it.append(stepContext); if (step.error) { var error = $('<error></error>'); stepContext.append(error); error.text(formatException(stepContext.error)); } }); }); } }); /** * Creates a global value $result with the result of the runner. */ angular.scenario.output('object', function(context, runner, model) { runner.$window.$result = model.value; }); bindJQuery(); publishExternalAPI(angular); var $runner = new angular.scenario.Runner(window), scripts = document.getElementsByTagName('script'), script = scripts[scripts.length - 1], config = {}; angular.forEach(script.attributes, function(attr) { var match = attr.name.match(/ng[:\-](.*)/); if (match) { config[match[1]] = attr.value || true; } }); if (config.autotest) { JQLite(document).ready(function() { angular.scenario.setUpAndRun(config); }); } })(window, document); angular.element(document).find('head').append('<style type="text/css">@charset "UTF-8";\n\n[ng\\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak],\n.ng-cloak, .x-ng-cloak {\n display: none;\n}\n\nng\\:form {\n display: block;\n}\n</style>'); angular.element(document).find('head').append('<style type="text/css">@charset "UTF-8";\n/* CSS Document */\n\n/** Structure */\nbody {\n font-family: Arial, sans-serif;\n margin: 0;\n font-size: 14px;\n}\n\n#system-error {\n font-size: 1.5em;\n text-align: center;\n}\n\n#json, #xml {\n display: none;\n}\n\n#header {\n position: fixed;\n width: 100%;\n}\n\n#specs {\n padding-top: 50px;\n}\n\n#header .angular {\n font-family: Courier New, monospace;\n font-weight: bold;\n}\n\n#header h1 {\n font-weight: normal;\n float: left;\n font-size: 30px;\n line-height: 30px;\n margin: 0;\n padding: 10px 10px;\n height: 30px;\n}\n\n#application h2,\n#specs h2 {\n margin: 0;\n padding: 0.5em;\n font-size: 1.1em;\n}\n\n#status-legend {\n margin-top: 10px;\n margin-right: 10px;\n}\n\n#header,\n#application,\n.test-info,\n.test-actions li {\n overflow: hidden;\n}\n\n#application {\n margin: 10px;\n}\n\n#application iframe {\n width: 100%;\n height: 758px;\n}\n\n#application .popout {\n float: right;\n}\n\n#application iframe {\n border: none;\n}\n\n.tests li,\n.test-actions li,\n.test-it li,\n.test-it ol,\n.status-display {\n list-style-type: none;\n}\n\n.tests,\n.test-it ol,\n.status-display {\n margin: 0;\n padding: 0;\n}\n\n.test-info {\n margin-left: 1em;\n margin-top: 0.5em;\n border-radius: 8px 0 0 8px;\n -webkit-border-radius: 8px 0 0 8px;\n -moz-border-radius: 8px 0 0 8px;\n cursor: pointer;\n}\n\n.test-info:hover .test-name {\n text-decoration: underline;\n}\n\n.test-info .closed:before {\n content: \'\\25b8\\00A0\';\n}\n\n.test-info .open:before {\n content: \'\\25be\\00A0\';\n font-weight: bold;\n}\n\n.test-it ol {\n margin-left: 2.5em;\n}\n\n.status-display,\n.status-display li {\n float: right;\n}\n\n.status-display li {\n padding: 5px 10px;\n}\n\n.timer-result,\n.test-title {\n display: inline-block;\n margin: 0;\n padding: 4px;\n}\n\n.test-actions .test-title,\n.test-actions .test-result {\n display: table-cell;\n padding-left: 0.5em;\n padding-right: 0.5em;\n}\n\n.test-actions {\n display: table;\n}\n\n.test-actions li {\n display: table-row;\n}\n\n.timer-result {\n width: 4em;\n padding: 0 10px;\n text-align: right;\n font-family: monospace;\n}\n\n.test-it pre,\n.test-actions pre {\n clear: left;\n color: black;\n margin-left: 6em;\n}\n\n.test-describe {\n padding-bottom: 0.5em;\n}\n\n.test-describe .test-describe {\n margin: 5px 5px 10px 2em;\n}\n\n.test-actions .status-pending .test-title:before {\n content: \'\\00bb\\00A0\';\n}\n\n.scrollpane {\n max-height: 20em;\n overflow: auto;\n}\n\n/** Colors */\n\n#header {\n background-color: #F2C200;\n}\n\n#specs h2 {\n border-top: 2px solid #BABAD1;\n}\n\n#specs h2,\n#application h2 {\n background-color: #efefef;\n}\n\n#application {\n border: 1px solid #BABAD1;\n}\n\n.test-describe .test-describe {\n border-left: 1px solid #BABAD1;\n border-right: 1px solid #BABAD1;\n border-bottom: 1px solid #BABAD1;\n}\n\n.status-display {\n border: 1px solid #777;\n}\n\n.status-display .status-pending,\n.status-pending .test-info {\n background-color: #F9EEBC;\n}\n\n.status-display .status-success,\n.status-success .test-info {\n background-color: #B1D7A1;\n}\n\n.status-display .status-failure,\n.status-failure .test-info {\n background-color: #FF8286;\n}\n\n.status-display .status-error,\n.status-error .test-info {\n background-color: black;\n color: white;\n}\n\n.test-actions .status-success .test-title {\n color: #30B30A;\n}\n\n.test-actions .status-failure .test-title {\n color: #DF0000;\n}\n\n.test-actions .status-error .test-title {\n color: black;\n}\n\n.test-actions .timer-result {\n color: #888;\n}\n</style>');
ajax/libs/react-intl/1.0.1/react-intl.min.js
dada0423/cdnjs
(function(){"use strict";function a(a){var b,c,d,e,f=Array.prototype.slice.call(arguments,1);for(b=0,c=f.length;c>b;b+=1)if(d=f[b])for(e in d)o.call(d,e)&&(a[e]=d[e]);return a}function b(a,b,c){this.locales=a,this.formats=b,this.pluralFn=c}function c(a){this.id=a}function d(a,b,c,d){this.id=a,this.offset=b,this.options=c,this.pluralFn=d}function e(a,b,c,d){this.id=a,this.offset=b,this.numberFormat=c,this.string=d}function f(a,b){this.id=a,this.options=b}function g(a,b,c){var d="string"==typeof a?g.__parse(a):a;if(!d||"messageFormatPattern"!==d.type)throw new TypeError("A message must be provided as a String or AST.");c=this._mergeFormats(g.formats,c),q(this,"_locale",{value:this._resolveLocale(b)});var e=g.__localeData__[this._locale].pluralRuleFunction,f=this._compilePattern(d,b,c,e),h=this;this.format=function(a){return h._format(f,a)}}function h(a){return 400*a/146097}function i(a,b){b=b||{},z(this,"_locale",{value:this._resolveLocale(a)}),z(this,"_options",{value:{style:this._resolveStyle(b.style),units:this._isValidUnits(b.units)&&b.units}}),z(this,"_messages",{value:A(null)});var c=this;this.format=function(a){return c._format(a)}}function j(a){var b=N(null);return function(){var c=Array.prototype.slice.call(arguments),d=k(c),e=d&&b[d];return e||(e=N(a.prototype),a.apply(e,c),d&&(b[d]=e)),e}}function k(a){if("undefined"!=typeof JSON){var b,c,d,e=[];for(b=0,c=a.length;c>b;b+=1)d=a[b],e.push(d&&"object"==typeof d?l(d):d);return JSON.stringify(e)}}function l(a){var b,c,d,e,f=[],g=[];for(b in a)a.hasOwnProperty(b)&&g.push(b);var h=g.sort();for(c=0,d=h.length;d>c;c+=1)b=h[c],e={},e[b]=a[b],f[c]=e;return f}function m(a,b){if(!isFinite(a))throw new TypeError(b)}function n(a,b){if("number"!=typeof a)throw new TypeError(b)}var o=Object.prototype.hasOwnProperty,p=function(){try{return!!Object.defineProperty({},"a",{})}catch(a){return!1}}(),q=(!p&&!Object.prototype.__defineGetter__,p?Object.defineProperty:function(a,b,c){"get"in c&&a.__defineGetter__?a.__defineGetter__(b,c.get):(!o.call(a,b)||"value"in c)&&(a[b]=c.value)}),r=Object.create||function(a,b){function c(){}var d,e;c.prototype=a,d=new c;for(e in b)o.call(b,e)&&q(d,e,b[e]);return d},s=b;b.prototype.compile=function(a){return this.pluralStack=[],this.currentPlural=null,this.pluralNumberFormat=null,this.compileMessage(a)},b.prototype.compileMessage=function(a){if(!a||"messageFormatPattern"!==a.type)throw new Error('Message AST is not of type: "messageFormatPattern"');var b,c,d,e=a.elements,f=[];for(b=0,c=e.length;c>b;b+=1)switch(d=e[b],d.type){case"messageTextElement":f.push(this.compileMessageText(d));break;case"argumentElement":f.push(this.compileArgument(d));break;default:throw new Error("Message element does not have a valid type")}return f},b.prototype.compileMessageText=function(a){return this.currentPlural&&/(^|[^\\])#/g.test(a.value)?(this.pluralNumberFormat||(this.pluralNumberFormat=new Intl.NumberFormat(this.locales)),new e(this.currentPlural.id,this.currentPlural.format.offset,this.pluralNumberFormat,a.value)):a.value.replace(/\\#/g,"#")},b.prototype.compileArgument=function(a){var b=a.format;if(!b)return new c(a.id);var e,g=this.formats,h=this.locales,i=this.pluralFn;switch(b.type){case"numberFormat":return e=g.number[b.style],{id:a.id,format:new Intl.NumberFormat(h,e).format};case"dateFormat":return e=g.date[b.style],{id:a.id,format:new Intl.DateTimeFormat(h,e).format};case"timeFormat":return e=g.time[b.style],{id:a.id,format:new Intl.DateTimeFormat(h,e).format};case"pluralFormat":return e=this.compileOptions(a),new d(a.id,b.offset,e,i);case"selectFormat":return e=this.compileOptions(a),new f(a.id,e);default:throw new Error("Message element does not have a valid format type")}},b.prototype.compileOptions=function(a){var b=a.format,c=b.options,d={};this.pluralStack.push(this.currentPlural),this.currentPlural="pluralFormat"===b.type?a:null;var e,f,g;for(e=0,f=c.length;f>e;e+=1)g=c[e],d[g.selector]=this.compileMessage(g.value);return this.currentPlural=this.pluralStack.pop(),d},c.prototype.format=function(a){return a?"string"==typeof a?a:String(a):""},d.prototype.getOption=function(a){var b=this.options,c=b["="+a]||b[this.pluralFn(a-this.offset)];return c||b.other},e.prototype.format=function(a){var b=this.numberFormat.format(a-this.offset);return this.string.replace(/(^|[^\\])#/g,"$1"+b).replace(/\\#/g,"#")},f.prototype.getOption=function(a){var b=this.options;return b[a]||b.other};var t=function(){function a(a,b){function c(){this.constructor=a}c.prototype=b.prototype,a.prototype=new c}function b(a,b,c,d,e,f){this.message=a,this.expected=b,this.found=c,this.offset=d,this.line=e,this.column=f,this.name="SyntaxError"}function c(a){function c(b){function c(b,c,d){var e,f;for(e=c;d>e;e++)f=a.charAt(e),"\n"===f?(b.seenCR||b.line++,b.column=1,b.seenCR=!1):"\r"===f||"\u2028"===f||"\u2029"===f?(b.line++,b.column=1,b.seenCR=!0):(b.column++,b.seenCR=!1)}return Ob!==b&&(Ob>b&&(Ob=0,Pb={line:1,column:1,seenCR:!1}),c(Pb,Ob,b),Ob=b),Pb}function d(a){Qb>Mb||(Mb>Qb&&(Qb=Mb,Rb=[]),Rb.push(a))}function e(d,e,f){function g(a){var b=1;for(a.sort(function(a,b){return a.description<b.description?-1:a.description>b.description?1:0});b<a.length;)a[b-1]===a[b]?a.splice(b,1):b++}function h(a,b){function c(a){function b(a){return a.charCodeAt(0).toString(16).toUpperCase()}return a.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\x08/g,"\\b").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\f/g,"\\f").replace(/\r/g,"\\r").replace(/[\x00-\x07\x0B\x0E\x0F]/g,function(a){return"\\x0"+b(a)}).replace(/[\x10-\x1F\x80-\xFF]/g,function(a){return"\\x"+b(a)}).replace(/[\u0180-\u0FFF]/g,function(a){return"\\u0"+b(a)}).replace(/[\u1080-\uFFFF]/g,function(a){return"\\u"+b(a)})}var d,e,f,g=new Array(a.length);for(f=0;f<a.length;f++)g[f]=a[f].description;return d=a.length>1?g.slice(0,-1).join(", ")+" or "+g[a.length-1]:g[0],e=b?'"'+c(b)+'"':"end of input","Expected "+d+" but "+e+" found."}var i=c(f),j=f<a.length?a.charAt(f):null;return null!==e&&g(e),new b(null!==d?d:h(e,j),e,j,f,i.line,i.column)}function f(){var a;return a=g()}function g(){var a,b,c;for(a=Mb,b=[],c=h();c!==C;)b.push(c),c=h();return b!==C&&(Nb=a,b=F(b)),a=b}function h(){var a;return a=j(),a===C&&(a=l()),a}function i(){var b,c,d,e,f,g;if(b=Mb,c=[],d=Mb,e=u(),e!==C?(f=z(),f!==C?(g=u(),g!==C?(e=[e,f,g],d=e):(Mb=d,d=G)):(Mb=d,d=G)):(Mb=d,d=G),d!==C)for(;d!==C;)c.push(d),d=Mb,e=u(),e!==C?(f=z(),f!==C?(g=u(),g!==C?(e=[e,f,g],d=e):(Mb=d,d=G)):(Mb=d,d=G)):(Mb=d,d=G);else c=G;return c!==C&&(Nb=b,c=H(c)),b=c,b===C&&(b=Mb,c=t(),c!==C&&(c=a.substring(b,Mb)),b=c),b}function j(){var a,b;return a=Mb,b=i(),b!==C&&(Nb=a,b=I(b)),a=b}function k(){var b,c,e;if(b=x(),b===C){if(b=Mb,c=[],J.test(a.charAt(Mb))?(e=a.charAt(Mb),Mb++):(e=C,0===Sb&&d(K)),e!==C)for(;e!==C;)c.push(e),J.test(a.charAt(Mb))?(e=a.charAt(Mb),Mb++):(e=C,0===Sb&&d(K));else c=G;c!==C&&(c=a.substring(b,Mb)),b=c}return b}function l(){var b,c,e,f,g,h,i,j,l;return b=Mb,123===a.charCodeAt(Mb)?(c=L,Mb++):(c=C,0===Sb&&d(M)),c!==C?(e=u(),e!==C?(f=k(),f!==C?(g=u(),g!==C?(h=Mb,44===a.charCodeAt(Mb)?(i=O,Mb++):(i=C,0===Sb&&d(P)),i!==C?(j=u(),j!==C?(l=m(),l!==C?(i=[i,j,l],h=i):(Mb=h,h=G)):(Mb=h,h=G)):(Mb=h,h=G),h===C&&(h=N),h!==C?(i=u(),i!==C?(125===a.charCodeAt(Mb)?(j=Q,Mb++):(j=C,0===Sb&&d(R)),j!==C?(Nb=b,c=S(f,h),b=c):(Mb=b,b=G)):(Mb=b,b=G)):(Mb=b,b=G)):(Mb=b,b=G)):(Mb=b,b=G)):(Mb=b,b=G)):(Mb=b,b=G),b}function m(){var a;return a=n(),a===C&&(a=o(),a===C&&(a=p())),a}function n(){var b,c,e,f,g,h,i;return b=Mb,a.substr(Mb,6)===T?(c=T,Mb+=6):(c=C,0===Sb&&d(U)),c===C&&(a.substr(Mb,4)===V?(c=V,Mb+=4):(c=C,0===Sb&&d(W)),c===C&&(a.substr(Mb,4)===X?(c=X,Mb+=4):(c=C,0===Sb&&d(Y)))),c!==C?(e=u(),e!==C?(f=Mb,44===a.charCodeAt(Mb)?(g=O,Mb++):(g=C,0===Sb&&d(P)),g!==C?(h=u(),h!==C?(i=z(),i!==C?(g=[g,h,i],f=g):(Mb=f,f=G)):(Mb=f,f=G)):(Mb=f,f=G),f===C&&(f=N),f!==C?(Nb=b,c=Z(c,f),b=c):(Mb=b,b=G)):(Mb=b,b=G)):(Mb=b,b=G),b}function o(){var b,c,e,f,g,h,i,j,k;if(b=Mb,a.substr(Mb,6)===$?(c=$,Mb+=6):(c=C,0===Sb&&d(_)),c!==C)if(e=u(),e!==C)if(44===a.charCodeAt(Mb)?(f=O,Mb++):(f=C,0===Sb&&d(P)),f!==C)if(g=u(),g!==C)if(h=s(),h===C&&(h=N),h!==C)if(i=u(),i!==C){if(j=[],k=r(),k!==C)for(;k!==C;)j.push(k),k=r();else j=G;j!==C?(Nb=b,c=ab(h,j),b=c):(Mb=b,b=G)}else Mb=b,b=G;else Mb=b,b=G;else Mb=b,b=G;else Mb=b,b=G;else Mb=b,b=G;else Mb=b,b=G;return b}function p(){var b,c,e,f,g,h,i;if(b=Mb,a.substr(Mb,6)===bb?(c=bb,Mb+=6):(c=C,0===Sb&&d(cb)),c!==C)if(e=u(),e!==C)if(44===a.charCodeAt(Mb)?(f=O,Mb++):(f=C,0===Sb&&d(P)),f!==C)if(g=u(),g!==C){if(h=[],i=r(),i!==C)for(;i!==C;)h.push(i),i=r();else h=G;h!==C?(Nb=b,c=db(h),b=c):(Mb=b,b=G)}else Mb=b,b=G;else Mb=b,b=G;else Mb=b,b=G;else Mb=b,b=G;return b}function q(){var b,c,e,f;return b=Mb,c=Mb,61===a.charCodeAt(Mb)?(e=eb,Mb++):(e=C,0===Sb&&d(fb)),e!==C?(f=x(),f!==C?(e=[e,f],c=e):(Mb=c,c=G)):(Mb=c,c=G),c!==C&&(c=a.substring(b,Mb)),b=c,b===C&&(b=z()),b}function r(){var b,c,e,f,h,i,j,k,l;return b=Mb,c=u(),c!==C?(e=q(),e!==C?(f=u(),f!==C?(123===a.charCodeAt(Mb)?(h=L,Mb++):(h=C,0===Sb&&d(M)),h!==C?(i=u(),i!==C?(j=g(),j!==C?(k=u(),k!==C?(125===a.charCodeAt(Mb)?(l=Q,Mb++):(l=C,0===Sb&&d(R)),l!==C?(Nb=b,c=gb(e,j),b=c):(Mb=b,b=G)):(Mb=b,b=G)):(Mb=b,b=G)):(Mb=b,b=G)):(Mb=b,b=G)):(Mb=b,b=G)):(Mb=b,b=G)):(Mb=b,b=G),b}function s(){var b,c,e,f;return b=Mb,a.substr(Mb,7)===hb?(c=hb,Mb+=7):(c=C,0===Sb&&d(ib)),c!==C?(e=u(),e!==C?(f=x(),f!==C?(Nb=b,c=jb(f),b=c):(Mb=b,b=G)):(Mb=b,b=G)):(Mb=b,b=G),b}function t(){var b,c;if(Sb++,b=[],lb.test(a.charAt(Mb))?(c=a.charAt(Mb),Mb++):(c=C,0===Sb&&d(mb)),c!==C)for(;c!==C;)b.push(c),lb.test(a.charAt(Mb))?(c=a.charAt(Mb),Mb++):(c=C,0===Sb&&d(mb));else b=G;return Sb--,b===C&&(c=C,0===Sb&&d(kb)),b}function u(){var b,c,e;for(Sb++,b=Mb,c=[],e=t();e!==C;)c.push(e),e=t();return c!==C&&(c=a.substring(b,Mb)),b=c,Sb--,b===C&&(c=C,0===Sb&&d(nb)),b}function v(){var b;return ob.test(a.charAt(Mb))?(b=a.charAt(Mb),Mb++):(b=C,0===Sb&&d(pb)),b}function w(){var b;return qb.test(a.charAt(Mb))?(b=a.charAt(Mb),Mb++):(b=C,0===Sb&&d(rb)),b}function x(){var b,c,e,f,g,h;if(b=Mb,48===a.charCodeAt(Mb)?(c=sb,Mb++):(c=C,0===Sb&&d(tb)),c===C){if(c=Mb,e=Mb,ub.test(a.charAt(Mb))?(f=a.charAt(Mb),Mb++):(f=C,0===Sb&&d(vb)),f!==C){for(g=[],h=v();h!==C;)g.push(h),h=v();g!==C?(f=[f,g],e=f):(Mb=e,e=G)}else Mb=e,e=G;e!==C&&(e=a.substring(c,Mb)),c=e}return c!==C&&(Nb=b,c=wb(c)),b=c}function y(){var b,c,e,f,g,h,i,j;return xb.test(a.charAt(Mb))?(b=a.charAt(Mb),Mb++):(b=C,0===Sb&&d(yb)),b===C&&(b=Mb,a.substr(Mb,2)===zb?(c=zb,Mb+=2):(c=C,0===Sb&&d(Ab)),c!==C&&(Nb=b,c=Bb()),b=c,b===C&&(b=Mb,a.substr(Mb,2)===Cb?(c=Cb,Mb+=2):(c=C,0===Sb&&d(Db)),c!==C&&(Nb=b,c=Eb()),b=c,b===C&&(b=Mb,a.substr(Mb,2)===Fb?(c=Fb,Mb+=2):(c=C,0===Sb&&d(Gb)),c!==C&&(Nb=b,c=Hb()),b=c,b===C&&(b=Mb,a.substr(Mb,2)===Ib?(c=Ib,Mb+=2):(c=C,0===Sb&&d(Jb)),c!==C?(e=Mb,f=Mb,g=w(),g!==C?(h=w(),h!==C?(i=w(),i!==C?(j=w(),j!==C?(g=[g,h,i,j],f=g):(Mb=f,f=G)):(Mb=f,f=G)):(Mb=f,f=G)):(Mb=f,f=G),f!==C&&(f=a.substring(e,Mb)),e=f,e!==C?(Nb=b,c=Kb(e),b=c):(Mb=b,b=G)):(Mb=b,b=G))))),b}function z(){var a,b,c;if(a=Mb,b=[],c=y(),c!==C)for(;c!==C;)b.push(c),c=y();else b=G;return b!==C&&(Nb=a,b=Lb(b)),a=b}var A,B=arguments.length>1?arguments[1]:{},C={},D={start:f},E=f,F=function(a){return{type:"messageFormatPattern",elements:a}},G=C,H=function(a){var b,c,d,e,f,g="";for(b=0,d=a.length;d>b;b+=1)for(e=a[b],c=0,f=e.length;f>c;c+=1)g+=e[c];return g},I=function(a){return{type:"messageTextElement",value:a}},J=/^[^ \t\n\r,.+={}#]/,K={type:"class",value:"[^ \\t\\n\\r,.+={}#]",description:"[^ \\t\\n\\r,.+={}#]"},L="{",M={type:"literal",value:"{",description:'"{"'},N=null,O=",",P={type:"literal",value:",",description:'","'},Q="}",R={type:"literal",value:"}",description:'"}"'},S=function(a,b){return{type:"argumentElement",id:a,format:b&&b[2]}},T="number",U={type:"literal",value:"number",description:'"number"'},V="date",W={type:"literal",value:"date",description:'"date"'},X="time",Y={type:"literal",value:"time",description:'"time"'},Z=function(a,b){return{type:a+"Format",style:b&&b[2]}},$="plural",_={type:"literal",value:"plural",description:'"plural"'},ab=function(a,b){return{type:"pluralFormat",offset:a||0,options:b}},bb="select",cb={type:"literal",value:"select",description:'"select"'},db=function(a){return{type:"selectFormat",options:a}},eb="=",fb={type:"literal",value:"=",description:'"="'},gb=function(a,b){return{type:"optionalFormatPattern",selector:a,value:b}},hb="offset:",ib={type:"literal",value:"offset:",description:'"offset:"'},jb=function(a){return a},kb={type:"other",description:"whitespace"},lb=/^[ \t\n\r]/,mb={type:"class",value:"[ \\t\\n\\r]",description:"[ \\t\\n\\r]"},nb={type:"other",description:"optionalWhitespace"},ob=/^[0-9]/,pb={type:"class",value:"[0-9]",description:"[0-9]"},qb=/^[0-9a-f]/i,rb={type:"class",value:"[0-9a-f]i",description:"[0-9a-f]i"},sb="0",tb={type:"literal",value:"0",description:'"0"'},ub=/^[1-9]/,vb={type:"class",value:"[1-9]",description:"[1-9]"},wb=function(a){return parseInt(a,10)},xb=/^[^{}\\\0-\x1F \t\n\r]/,yb={type:"class",value:"[^{}\\\\\\0-\\x1F \\t\\n\\r]",description:"[^{}\\\\\\0-\\x1F \\t\\n\\r]"},zb="\\#",Ab={type:"literal",value:"\\#",description:'"\\\\#"'},Bb=function(){return"\\#"},Cb="\\{",Db={type:"literal",value:"\\{",description:'"\\\\{"'},Eb=function(){return"{"},Fb="\\}",Gb={type:"literal",value:"\\}",description:'"\\\\}"'},Hb=function(){return"}"},Ib="\\u",Jb={type:"literal",value:"\\u",description:'"\\\\u"'},Kb=function(a){return String.fromCharCode(parseInt(a,16))},Lb=function(a){return a.join("")},Mb=0,Nb=0,Ob=0,Pb={line:1,column:1,seenCR:!1},Qb=0,Rb=[],Sb=0;if("startRule"in B){if(!(B.startRule in D))throw new Error("Can't start parsing from rule \""+B.startRule+'".');E=D[B.startRule]}if(A=E(),A!==C&&Mb===a.length)return A;throw A!==C&&Mb<a.length&&d({type:"end",description:"end of input"}),e(null,Rb,Qb)}return a(b,Error),{SyntaxError:b,parse:c}}(),u=g;q(g,"formats",{enumerable:!0,value:{number:{currency:{style:"currency"},percent:{style:"percent"}},date:{"short":{month:"numeric",day:"numeric",year:"2-digit"},medium:{month:"short",day:"numeric",year:"numeric"},"long":{month:"long",day:"numeric",year:"numeric"},full:{weekday:"long",month:"long",day:"numeric",year:"numeric"}},time:{"short":{hour:"numeric",minute:"numeric"},medium:{hour:"numeric",minute:"numeric",second:"numeric"},"long":{hour:"numeric",minute:"numeric",second:"numeric",timeZoneName:"short"},full:{hour:"numeric",minute:"numeric",second:"numeric",timeZoneName:"short"}}}}),q(g,"__localeData__",{value:r(null)}),q(g,"__addLocaleData",{value:function(a){if(!a||!a.locale)throw new Error("Locale data provided to IntlMessageFormat is missing a `locale` property");if(!a.pluralRuleFunction)throw new Error("Locale data provided to IntlMessageFormat is missing a `pluralRuleFunction` property");var b=a.locale.toLowerCase().split("-")[0];g.__localeData__[b]=a}}),q(g,"__parse",{value:t.parse}),q(g,"defaultLocale",{enumerable:!0,writable:!0,value:void 0}),g.prototype.resolvedOptions=function(){return{locale:this._locale}},g.prototype._compilePattern=function(a,b,c,d){var e=new s(b,c,d);return e.compile(a)},g.prototype._format=function(a,b){var c,d,e,f,g,h="";for(c=0,d=a.length;d>c;c+=1)if(e=a[c],"string"!=typeof e){if(f=e.id,!b||!o.call(b,f))throw new Error("A value must be provided for: "+f);g=b[f],h+=e.options?this._format(e.getOption(g),b):e.format(g)}else h+=e;return h},g.prototype._mergeFormats=function(b,c){var d,e,f={};for(d in b)o.call(b,d)&&(f[d]=e=r(b[d]),c&&o.call(c,d)&&a(e,c[d]));return f},g.prototype._resolveLocale=function(a){a||(a=g.defaultLocale),"string"==typeof a&&(a=[a]);var b,c,d,e=g.__localeData__;for(b=0,c=a.length;c>b;b+=1){if(d=a[b].split("-")[0].toLowerCase(),!/[a-z]{2,3}/.test(d))throw new Error("Language tag provided to IntlMessageFormat is not structrually valid: "+d);if(o.call(e,d))return d}throw new Error("No locale data has been added to IntlMessageFormat for: "+a.join(", "))};var v={locale:"en",pluralRuleFunction:function(a){var b=Math.floor(Math.abs(a)),c=a.toString().replace(/^[^.]*\.?/,"").length;return a=Math.floor(a),1===b&&0===c?"one":"other"}};u.__addLocaleData(v),u.defaultLocale="en";var w=u,x=Object.prototype.hasOwnProperty,y=function(){try{return!!Object.defineProperty({},"a",{})}catch(a){return!1}}(),z=(!y&&!Object.prototype.__defineGetter__,y?Object.defineProperty:function(a,b,c){"get"in c&&a.__defineGetter__?a.__defineGetter__(b,c.get):(!x.call(a,b)||"value"in c)&&(a[b]=c.value)}),A=Object.create||function(a,b){function c(){}var d,e;c.prototype=a,d=new c;for(e in b)x.call(b,e)&&z(d,e,b[e]);return d},B=Array.prototype.indexOf||function(a,b){var c=this;if(!c.length)return-1;for(var d=b||0,e=c.length;e>d;d++)if(c[d]===a)return d;return-1},C=Math.round,D=function(a,b){a=+a,b=+b;var c=C(b-a),d=C(c/1e3),e=C(d/60),f=C(e/60),g=C(f/24),i=C(g/7),j=h(g),k=C(12*j),l=C(j);return{millisecond:c,second:d,minute:e,hour:f,day:g,week:i,month:k,year:l}},E=i,F=["second","minute","hour","day","month","year"],G=["best fit","numeric"],H=Date.now?Date.now:function(){return(new Date).getTime()};z(i,"__localeData__",{value:A(null)}),z(i,"__addLocaleData",{value:function(a){if(!a||!a.locale)throw new Error("Locale data provided to IntlRelativeFormat is missing a `locale` property value");if(!a.fields)throw new Error("Locale data provided to IntlRelativeFormat is missing a `fields` property value");w.__addLocaleData(a);var b=a.locale.toLowerCase().split("-")[0];i.__localeData__[b]=a}}),z(i,"defaultLocale",{enumerable:!0,writable:!0,value:void 0}),z(i,"thresholds",{enumerable:!0,value:{second:45,minute:45,hour:22,day:26,month:11}}),i.prototype.resolvedOptions=function(){return{locale:this._locale,style:this._options.style,units:this._options.units}},i.prototype._format=function(a){var b=H();if(void 0===a&&(a=b),!isFinite(a))throw new RangeError("The date value provided to IntlRelativeFormat#format() is not in valid range.");var c=D(b,a),d=this._options.units||this._selectUnits(c),e=c[d];if("numeric"!==this._options.style){var f=this._resolveRelativeUnits(e,d);if(f)return f}return this._resolveMessage(d).format({0:Math.abs(e),when:0>e?"past":"future"})},i.prototype._isValidUnits=function(a){if(!a||B.call(F,a)>=0)return!0;if("string"==typeof a){var b=/s$/.test(a)&&a.substr(0,a.length-1);if(b&&B.call(F,b)>=0)throw new Error('"'+a+'" is not a valid IntlRelativeFormat `units` value, did you mean: '+b)}throw new Error('"'+a+'" is not a valid IntlRelativeFormat `units` value, it must be one of: "'+F.join('", "')+'"')},i.prototype._resolveLocale=function(a){a||(a=i.defaultLocale),"string"==typeof a&&(a=[a]);var b,c,d,e=Object.prototype.hasOwnProperty,f=i.__localeData__;for(b=0,c=a.length;c>b;b+=1){if(d=a[b].split("-")[0].toLowerCase(),!/[a-z]{2,3}/.test(d))throw new Error("Language tag provided to IntlRelativeFormat is not structrually valid: "+d);if(e.call(f,d))return d}throw new Error("No locale data has been added to IntlRelativeFormat for: "+a.join(", "))},i.prototype._resolveMessage=function(a){var b,c,d,e,f,g,h=this._messages;if(!h[a]){b=i.__localeData__[this._locale].fields[a],c=b.relativeTime,e="",f="";for(d in c.future)c.future.hasOwnProperty(d)&&(e+=" "+d+" {"+c.future[d].replace("{0}","#")+"}");for(d in c.past)c.past.hasOwnProperty(d)&&(f+=" "+d+" {"+c.past[d].replace("{0}","#")+"}");g="{when, select, future {{0, plural, "+e+"}}past {{0, plural, "+f+"}}}",h[a]=new w(g,this._locale)}return h[a]},i.prototype._resolveRelativeUnits=function(a,b){var c=i.__localeData__[this._locale].fields[b];return c.relative?c.relative[a]:void 0},i.prototype._resolveStyle=function(a){if(!a)return G[0];if(B.call(G,a)>=0)return a;throw new Error('"'+a+'" is not a valid IntlRelativeFormat `style` value, it must be one of: "'+G.join('", "')+'"')},i.prototype._selectUnits=function(a){var b,c,d;for(b=0,c=F.length;c>b&&(d=F[b],!(Math.abs(a[d])<i.thresholds[d]));b+=1);return d};var I={locale:"en",pluralRuleFunction:function(a){var b=Math.floor(Math.abs(a)),c=a.toString().replace(/^[^.]*\.?/,"").length;return a=Math.floor(a),1===b&&0===c?"one":"other"},fields:{second:{displayName:"Second",relative:{0:"now"},relativeTime:{future:{one:"in {0} second",other:"in {0} seconds"},past:{one:"{0} second ago",other:"{0} seconds ago"}}},minute:{displayName:"Minute",relativeTime:{future:{one:"in {0} minute",other:"in {0} minutes"},past:{one:"{0} minute ago",other:"{0} minutes ago"}}},hour:{displayName:"Hour",relativeTime:{future:{one:"in {0} hour",other:"in {0} hours"},past:{one:"{0} hour ago",other:"{0} hours ago"}}},day:{displayName:"Day",relative:{0:"today",1:"tomorrow","-1":"yesterday"},relativeTime:{future:{one:"in {0} day",other:"in {0} days"},past:{one:"{0} day ago",other:"{0} days ago"}}},month:{displayName:"Month",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{one:"in {0} month",other:"in {0} months"},past:{one:"{0} month ago",other:"{0} months ago"}}},year:{displayName:"Year",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{one:"in {0} year",other:"in {0} years"},past:{one:"{0} year ago",other:"{0} years ago"}}}}};E.__addLocaleData(I),E.defaultLocale="en";var J=E,K=Object.prototype.hasOwnProperty,L=function(){try{return!!Object.defineProperty({},"a",{})}catch(a){return!1}}(),M=(!L&&!Object.prototype.__defineGetter__,L?Object.defineProperty:function(a,b,c){"get"in c&&a.__defineGetter__?a.__defineGetter__(b,c.get):(!K.call(a,b)||"value"in c)&&(a[b]=c.value)}),N=Object.create||function(a,b){function c(){}var d,e;c.prototype=a,d=new c;for(e in b)K.call(b,e)&&M(d,e,b[e]);return d},O=j,P={locales:React.PropTypes.oneOfType([React.PropTypes.string,React.PropTypes.array]),formats:React.PropTypes.object,messages:React.PropTypes.object},Q={propsTypes:P,contextTypes:P,childContextTypes:P,getNumberFormat:O(Intl.NumberFormat),getDateTimeFormat:O(Intl.DateTimeFormat),getMessageFormat:O(w),getRelativeFormat:O(J),getChildContext:function(){var a=this.context,b=this.props;return{locales:b.locales||a.locales,formats:b.formats||a.formats,messages:b.messages||a.messages}},formatDate:function(a,b){return a=new Date(a),m(a,"A date or timestamp must be provided to formatDate()"),this._format("date",a,b)},formatTime:function(a,b){return a=new Date(a),m(a,"A date or timestamp must be provided to formatTime()"),this._format("time",a,b)},formatRelative:function(a,b){return a=new Date(a),m(a,"A date or timestamp must be provided to formatRelative()"),this._format("relative",a,b)},formatNumber:function(a,b){return n(a,"A number must be provided to formatNumber()"),this._format("number",a,b)},formatMessage:function(a,b){var c=this.props.locales||this.context.locales,d=this.props.formats||this.context.formats;return"function"==typeof a?a(b):("string"==typeof a&&(a=this.getMessageFormat(a,c,d)),a.format(b))},getIntlMessage:function(a){var b,c=this.props.messages||this.context.messages,d=a.split(".");try{b=d.reduce(function(a,b){return a[b]},c)}finally{if(void 0===b)throw new ReferenceError("Could not find Intl message: "+a)}return b},_format:function(a,b,c){var d=this.props.locales||this.context.locales,e=this.props.formats||this.context.formats;if(c&&"string"==typeof c)try{c=e[a][c]}catch(f){c=void 0}finally{if(void 0===c)throw new ReferenceError("No "+a+" format named: "+c)}switch(a){case"date":case"time":return this.getDateTimeFormat(d,c).format(b);case"number":return this.getNumberFormat(d,c).format(b);case"relative":return this.getRelativeFormat(d,c).format(b);default:throw new Error("Unrecognized format type: "+a)}},__addLocaleData:function(a){w.__addLocaleData(a),J.__addLocaleData(a)}},R={locale:"en",pluralRuleFunction:function(a){var b=Math.floor(Math.abs(a)),c=a.toString().replace(/^[^.]*\.?/,"").length;return a=Math.floor(a),1===b&&0===c?"one":"other"},fields:{second:{displayName:"Second",relative:{0:"now"},relativeTime:{future:{one:"in {0} second",other:"in {0} seconds"},past:{one:"{0} second ago",other:"{0} seconds ago"}}},minute:{displayName:"Minute",relativeTime:{future:{one:"in {0} minute",other:"in {0} minutes"},past:{one:"{0} minute ago",other:"{0} minutes ago"}}},hour:{displayName:"Hour",relativeTime:{future:{one:"in {0} hour",other:"in {0} hours"},past:{one:"{0} hour ago",other:"{0} hours ago"}}},day:{displayName:"Day",relative:{0:"today",1:"tomorrow","-1":"yesterday"},relativeTime:{future:{one:"in {0} day",other:"in {0} days"},past:{one:"{0} day ago",other:"{0} days ago"}}},month:{displayName:"Month",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{one:"in {0} month",other:"in {0} months"},past:{one:"{0} month ago",other:"{0} months ago"}}},year:{displayName:"Year",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{one:"in {0} year",other:"in {0} years"},past:{one:"{0} year ago",other:"{0} years ago"}}}}};Q.__addLocaleData(R);var S=Q;this.ReactIntlMixin=S}).call(this); //# sourceMappingURL=react-intl.min.js.map
ajax/libs/qooxdoo/2.1.2/q.js
voronianski/cdnjs
/** qooxdoo v.2.1.2 | (c) 2012 1&1 Internet AG 1und1.de | qooxdoo.org/license */ (function(){ if (!window.qx) window.qx = {}; var qx = window.qx; if (!qx.$$environment) qx.$$environment = {}; var envinfo = {"json":true,"qx.application":"library.Application","qx.debug":false,"qx.debug.databinding":false,"qx.debug.dispose":false,"qx.debug.io":false,"qx.debug.ui.queue":false,"qx.optimization.variants":true,"qx.revision":"","qx.theme":"qx.theme.Modern","qx.version":"2.1.2"}; for (var k in envinfo) qx.$$environment[k] = envinfo[k]; qx.$$packageData = {}; /** qooxdoo v.2.1.2 | (c) 2012 1&1 Internet AG 1und1.de | qooxdoo.org/license */ qx.$$packageData['0']={"locales":{},"resources":{},"translations":{"C":{},"en":{}}}; /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Andreas Ecker (ecker) * Martin Wittemann (martinwittemann) ************************************************************************ */ /* ************************************************************************ #ignore(qx.data) #ignore(qx.data.IListData) #ignore(qx.util.OOUtil) ************************************************************************ */ /** * Create namespace */ if(!window.qx){ window.qx = { }; }; /** * Bootstrap qx.Bootstrap to create myself later * This is needed for the API browser etc. to let them detect me */ qx.Bootstrap = { genericToString : function(){ return "[Class " + this.classname + "]"; }, createNamespace : function(name, object){ var splits = name.split("."); var parent = window; var part = splits[0]; for(var i = 0,len = splits.length - 1;i < len;i++,part = splits[i]){ if(!parent[part]){ parent = parent[part] = { }; } else { parent = parent[part]; }; }; // store object parent[part] = object; // return last part name (e.g. classname) return part; }, setDisplayName : function(fcn, classname, name){ fcn.displayName = classname + "." + name + "()"; }, setDisplayNames : function(functionMap, classname){ for(var name in functionMap){ var value = functionMap[name]; if(value instanceof Function){ value.displayName = classname + "." + name + "()"; }; }; }, define : function(name, config){ if(!config){ var config = { statics : { } }; }; var clazz; var proto = null; qx.Bootstrap.setDisplayNames(config.statics, name); if(config.members || config.extend){ qx.Bootstrap.setDisplayNames(config.members, name + ".prototype"); clazz = config.construct || new Function; if(config.extend){ this.extendClass(clazz, clazz, config.extend, name, basename); }; var statics = config.statics || { }; // use keys to include the shadowed in IE for(var i = 0,keys = qx.Bootstrap.keys(statics),l = keys.length;i < l;i++){ var key = keys[i]; clazz[key] = statics[key]; }; proto = clazz.prototype; var members = config.members || { }; // use keys to include the shadowed in IE for(var i = 0,keys = qx.Bootstrap.keys(members),l = keys.length;i < l;i++){ var key = keys[i]; proto[key] = members[key]; }; } else { clazz = config.statics || { }; }; // Create namespace var basename = name ? this.createNamespace(name, clazz) : ""; // Store names in constructor/object clazz.name = clazz.classname = name; clazz.basename = basename; // Store type info clazz.$$type = "Class"; // Attach toString if(!clazz.hasOwnProperty("toString")){ clazz.toString = this.genericToString; }; // Execute defer section if(config.defer){ config.defer(clazz, proto); }; // Store class reference in global class registry qx.Bootstrap.$$registry[name] = clazz; return clazz; } }; /** * Internal class that is responsible for bootstrapping the qooxdoo * framework at load time. * * Does support: * * * Construct * * Statics * * Members * * Extend * * Defer * * Does not support: * * * Super class calls * * Mixins, Interfaces, Properties, ... */ qx.Bootstrap.define("qx.Bootstrap", { statics : { /** Timestamp of qooxdoo based application startup */ LOADSTART : qx.$$start || new Date(), /** * Mapping for early use of the qx.debug environment setting. */ DEBUG : (function(){ // make sure to reflect all changes here to the environment class! var debug = true; if(qx.$$environment && qx.$$environment["qx.debug"] === false){ debug = false; }; return debug; })(), /** * Minimal accessor API for the environment settings given from the * generator. * * WARNING: This method only should be used if the * {@link qx.core.Environment} class is not loaded! * * @param key {String} The key to get the value from. * @return {var} The value of the setting or <code>undefined</code>. */ getEnvironmentSetting : function(key){ if(qx.$$environment){ return qx.$$environment[key]; }; }, /** * Minimal mutator for the environment settings given from the generator. * It checks for the existance of the environment settings and sets the * key if its not given from the generator. If a setting is available from * the generator, the setting will be ignored. * * WARNING: This method only should be used if the * {@link qx.core.Environment} class is not loaded! * * @param key {String} The key of the setting. * @param value {var} The value for the setting. */ setEnvironmentSetting : function(key, value){ if(!qx.$$environment){ qx.$$environment = { }; }; if(qx.$$environment[key] === undefined){ qx.$$environment[key] = value; }; }, /** * Creates a namespace and assigns the given object to it. * * @internal * @param name {String} The complete namespace to create. Typically, the last part is the class name itself * @param object {Object} The object to attach to the namespace * @return {Object} last part of the namespace (typically the class name) * @throws {Error} when the given object already exists. */ createNamespace : qx.Bootstrap.createNamespace, /** * Define a new class using the qooxdoo class system. * Lightweight version of {@link qx.Class#define} only used during bootstrap phase. * * @internal * @signature function(name, config) * @param name {String?} Name of the class. If null, the class will not be * attached to a namespace. * @param config {Map ? null} Class definition structure. * @return {Class} The defined class */ define : qx.Bootstrap.define, /** * Sets the display name of the given function * * @signature function(fcn, classname, name) * @param fcn {Function} the function to set the display name for * @param classname {String} the name of the class the function is defined in * @param name {String} the function name */ setDisplayName : qx.Bootstrap.setDisplayName, /** * Set the names of all functions defined in the given map * * @signature function(functionMap, classname) * @param functionMap {Object} a map with functions as values * @param classname {String} the name of the class, the functions are * defined in */ setDisplayNames : qx.Bootstrap.setDisplayNames, /** * This method will be attached to all classes to return * a nice identifier for them. * * @internal * @signature function() * @return {String} The class identifier */ genericToString : qx.Bootstrap.genericToString, /** * Inherit a clazz from a super class. * * This function differentiates between class and constructor because the * constructor written by the user might be wrapped and the <code>base</code> * property has to be attached to the constructor, while the <code>superclass</code> * property has to be attached to the wrapped constructor. * * @param clazz {Function} The class's wrapped constructor * @param construct {Function} The unwrapped constructor * @param superClass {Function} The super class * @param name {Function} fully qualified class name * @param basename {Function} the base name */ extendClass : function(clazz, construct, superClass, name, basename){ var superproto = superClass.prototype; // Use helper function/class to save the unnecessary constructor call while // setting up inheritance. var helper = new Function(); helper.prototype = superproto; var proto = new helper(); // Apply prototype to new helper instance clazz.prototype = proto; // Store names in prototype proto.name = proto.classname = name; proto.basename = basename; /* - Store base constructor to constructor- - Store reference to extend class */ construct.base = superClass; clazz.superclass = superClass; /* - Store statics/constructor onto constructor/prototype - Store correct constructor - Store statics onto prototype */ construct.self = clazz.constructor = proto.constructor = clazz; }, /** * Find a class by its name * * @param name {String} class name to resolve * @return {Class} the class */ getByName : function(name){ return qx.Bootstrap.$$registry[name]; }, /** {Map} Stores all defined classes */ $$registry : { }, /* --------------------------------------------------------------------------- OBJECT UTILITY FUNCTIONS --------------------------------------------------------------------------- */ /** * Get the number of own properties in the object. * * @param map {Object} the map * @return {Integer} number of objects in the map * @lint ignoreUnused(key) */ objectGetLength : function(map){ return qx.Bootstrap.keys(map).length; }, /** * Inserts all keys of the source object into the * target objects. Attention: The target map gets modified. * * @param target {Object} target object * @param source {Object} object to be merged * @param overwrite {Boolean ? true} If enabled existing keys will be overwritten * @return {Object} Target with merged values from the source object */ objectMergeWith : function(target, source, overwrite){ if(overwrite === undefined){ overwrite = true; }; for(var key in source){ if(overwrite || target[key] === undefined){ target[key] = source[key]; }; }; return target; }, /** * IE does not return "shadowed" keys even if they are defined directly * in the object. * * @internal */ __shadowedKeys : ["isPrototypeOf", "hasOwnProperty", "toLocaleString", "toString", "valueOf", "propertyIsEnumerable", "constructor"], /** * Get the keys of a map as array as returned by a "for ... in" statement. * * @deprecated {2.1.} Please use Object.keys instead. * @param map {Object} the map * @return {Array} array of the keys of the map */ getKeys : function(map){ if(qx.Bootstrap.DEBUG){ qx.Bootstrap.warn("'qx.Bootstrap.getKeys' is deprecated. " + "Please use the native 'Object.keys()' instead."); }; return qx.Bootstrap.keys(map); }, /** * Get the keys of a map as array as returned by a "for ... in" statement. * * @signature function(map) * @internal * @param map {Object} the map * @return {Array} array of the keys of the map */ keys : ({ "ES5" : Object.keys, "BROKEN_IE" : function(map){ if(map === null || (typeof map != "object" && typeof map != "function")){ throw new TypeError("Object.keys requires an object as argument."); }; var arr = []; var hasOwnProperty = Object.prototype.hasOwnProperty; for(var key in map){ if(hasOwnProperty.call(map, key)){ arr.push(key); }; }; // IE does not return "shadowed" keys even if they are defined directly // in the object. This is incompatible with the ECMA standard!! // This is why this checks are needed. var shadowedKeys = qx.Bootstrap.__shadowedKeys; for(var i = 0,a = shadowedKeys,l = a.length;i < l;i++){ if(hasOwnProperty.call(map, a[i])){ arr.push(a[i]); }; }; return arr; }, "default" : function(map){ if(map === null || (typeof map != "object" && typeof map != "function")){ throw new TypeError("Object.keys requires an object as argument."); }; var arr = []; var hasOwnProperty = Object.prototype.hasOwnProperty; for(var key in map){ if(hasOwnProperty.call(map, key)){ arr.push(key); }; }; return arr; } })[typeof (Object.keys) == "function" ? "ES5" : (function(){ for(var key in { toString : 1 }){ return key; }; })() !== "toString" ? "BROKEN_IE" : "default"], /** * Get the keys of a map as string * * @param map {Object} the map * @deprecated {2.1} Object.keys(map).join('\", "'). * @return {String} String of the keys of the map * The keys are separated by ", " */ getKeysAsString : function(map){ { }; var keys = qx.Bootstrap.keys(map); if(keys.length == 0){ return ""; }; return '"' + keys.join('\", "') + '"'; }, /** * Mapping from JavaScript string representation of objects to names * @internal */ __classToTypeMap : { "[object String]" : "String", "[object Array]" : "Array", "[object Object]" : "Object", "[object RegExp]" : "RegExp", "[object Number]" : "Number", "[object Boolean]" : "Boolean", "[object Date]" : "Date", "[object Function]" : "Function", "[object Error]" : "Error" }, /* --------------------------------------------------------------------------- FUNCTION UTILITY FUNCTIONS --------------------------------------------------------------------------- */ /** * Returns a function whose "this" is altered. * * *Syntax* * * <pre class='javascript'>qx.Bootstrap.bind(myFunction, [self, [varargs...]]);</pre> * * *Example* * * <pre class='javascript'> * function myFunction() * { * this.setStyle('color', 'red'); * // note that 'this' here refers to myFunction, not an element * // we'll need to bind this function to the element we want to alter * }; * * var myBoundFunction = qx.Bootstrap.bind(myFunction, myElement); * myBoundFunction(); // this will make the element myElement red. * </pre> * * @param func {Function} Original function to wrap * @param self {Object ? null} The object that the "this" of the function will refer to. * @param varargs {arguments ? null} The arguments to pass to the function. * @return {Function} The bound function. */ bind : function(func, self, varargs){ var fixedArgs = Array.prototype.slice.call(arguments, 2, arguments.length); return function(){ var args = Array.prototype.slice.call(arguments, 0, arguments.length); return func.apply(self, fixedArgs.concat(args)); }; }, /* --------------------------------------------------------------------------- STRING UTILITY FUNCTIONS --------------------------------------------------------------------------- */ /** * Convert the first character of the string to upper case. * * @param str {String} the string * @return {String} the string with an upper case first character */ firstUp : function(str){ return str.charAt(0).toUpperCase() + str.substr(1); }, /** * Convert the first character of the string to lower case. * * @param str {String} the string * @return {String} the string with a lower case first character */ firstLow : function(str){ return str.charAt(0).toLowerCase() + str.substr(1); }, /* --------------------------------------------------------------------------- TYPE UTILITY FUNCTIONS --------------------------------------------------------------------------- */ /** * Get the internal class of the value. See * http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/ * for details. * * @param value {var} value to get the class for * @return {String} the internal class of the value */ getClass : function(value){ var classString = Object.prototype.toString.call(value); return (qx.Bootstrap.__classToTypeMap[classString] || classString.slice(8, -1)); }, /** * Whether the value is a string. * * @param value {var} Value to check. * @return {Boolean} Whether the value is a string. */ isString : function(value){ // Added "value !== null" because IE throws an exception "Object expected" // by executing "value instanceof String" if value is a DOM element that // doesn't exist. It seems that there is an internal different between a // JavaScript null and a null returned from calling DOM. // e.q. by document.getElementById("ReturnedNull"). return (value !== null && (typeof value === "string" || qx.Bootstrap.getClass(value) == "String" || value instanceof String || (!!value && !!value.$$isString))); }, /** * Whether the value is an array. * * @param value {var} Value to check. * @return {Boolean} Whether the value is an array. */ isArray : function(value){ // Added "value !== null" because IE throws an exception "Object expected" // by executing "value instanceof Array" if value is a DOM element that // doesn't exist. It seems that there is an internal different between a // JavaScript null and a null returned from calling DOM. // e.q. by document.getElementById("ReturnedNull"). return (value !== null && (value instanceof Array || (value && qx.data && qx.data.IListData && qx.util.OOUtil.hasInterface(value.constructor, qx.data.IListData)) || qx.Bootstrap.getClass(value) == "Array" || (!!value && !!value.$$isArray))); }, /** * Whether the value is an object. Note that built-in types like Window are * not reported to be objects. * * @param value {var} Value to check. * @return {Boolean} Whether the value is an object. */ isObject : function(value){ return (value !== undefined && value !== null && qx.Bootstrap.getClass(value) == "Object"); }, /** * Whether the value is a function. * * @param value {var} Value to check. * @return {Boolean} Whether the value is a function. */ isFunction : function(value){ return qx.Bootstrap.getClass(value) == "Function"; }, /* --------------------------------------------------------------------------- LOGGING UTILITY FUNCTIONS --------------------------------------------------------------------------- */ $$logs : [], /** * Sending a message at level "debug" to the logger. * * @param object {Object} Contextual object (either instance or static class) * @param message {var} Any number of arguments supported. An argument may * have any JavaScript data type. All data is serialized immediately and * does not keep references to other objects. */ debug : function(object, message){ qx.Bootstrap.$$logs.push(["debug", arguments]); }, /** * Sending a message at level "info" to the logger. * * @param object {Object} Contextual object (either instance or static class) * @param message {var} Any number of arguments supported. An argument may * have any JavaScript data type. All data is serialized immediately and * does not keep references to other objects. */ info : function(object, message){ qx.Bootstrap.$$logs.push(["info", arguments]); }, /** * Sending a message at level "warn" to the logger. * * @param object {Object} Contextual object (either instance or static class) * @param message {var} Any number of arguments supported. An argument may * have any JavaScript data type. All data is serialized immediately and * does not keep references to other objects. */ warn : function(object, message){ qx.Bootstrap.$$logs.push(["warn", arguments]); }, /** * Sending a message at level "error" to the logger. * * @param object {Object} Contextual object (either instance or static class) * @param message {var} Any number of arguments supported. An argument may * have any JavaScript data type. All data is serialized immediately and * does not keep references to other objects. */ error : function(object, message){ qx.Bootstrap.$$logs.push(["error", arguments]); }, /** * Prints the current stack trace at level "info" * * @param object {Object} Contextual object (either instance or static class) */ trace : function(object){ } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2005-2011 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * This class is the single point to access all settings that may be different * in different environments. This contains e.g. the browser name, engine * version but also qooxdoo or application specific settings. * * Its public API can be found in its four main methods. One pair of methods * is used to check the synchronous values of the environment. The other pair * of methods is used for asynchronous checks. * * The most often used method should be {@link #get}, which returns the * current value for a given environment check. * * All qooxdoo settings can be changed via the generator's config. See the manual * for more details about the environment key in the config. As you can see * from the methods API, there is no way to override an existing key. So if you * need to change a qooxdoo setting, you have to use the generator to do so. * * The following table shows the available checks. If you are * interested in more details, check the reference to the implementation of * each check. Please do not use those check implementations directly, as the * Environment class comes with a smart caching feature. * * <table border="0" cellspacing="10"> * <tbody> * <tr> * <td colspan="4"><h2>Synchronous checks</h2> * </td> * </tr> * <tr> * <th><h3>Key</h3></th> * <th><h3>Type</h3></th> * <th><h3>Example</h3></th> * <th><h3>Details</h3></th> * </tr> * <tr> * <td colspan="4"><b>browser</b></td> * </tr> * <tr> * <td>browser.documentmode</td><td><i>Integer</i></td><td><code>0</code></td> * <td>{@link qx.bom.client.Browser#getDocumentMode}</td> * </tr> * <tr> * <td>browser.name</td><td><i>String</i></td><td><code> chrome </code></td> * <td>{@link qx.bom.client.Browser#getName}</td> * </tr> * <tr> * <td>browser.quirksmode</td><td><i>Boolean</i></td><td><code>false</code></td> * <td>{@link qx.bom.client.Browser#getQuirksMode}</td> * </tr> * <tr> * <td>browser.version</td><td><i>String</i></td><td><code>11.0</code></td> * <td>{@link qx.bom.client.Browser#getVersion}</td> * </tr> * <tr> * <td colspan="4"><b>runtime</b></td> * </tr> * <tr> * <td>runtime.name</td><td><i> String </i></td><td><code> node.js </code></td> * <td>{@link qx.bom.client.Runtime#getName}</td> * </tr> * <tr> * <td colspan="4"><b>css</b></td> * </tr> * <tr> * <td>css.borderradius</td><td><i>String</i> or <i>null</i></td><td><code>borderRadius</code></td> * <td>{@link qx.bom.client.Css#getBorderRadius}</td> * </tr> * <tr> * <td>css.borderimage</td><td><i>String</i> or <i>null</i></td><td><code>WebkitBorderImage</code></td> * <td>{@link qx.bom.client.Css#getBorderImage}</td> * </tr> * <tr> * <td>css.borderimage.standardsyntax</td><td><i>Boolean</i> or <i>null</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Css#getBorderImageSyntax}</td> * </tr> * <tr> * <td>css.boxmodel</td><td><i>String</i></td><td><code>content</code></td> * <td>{@link qx.bom.client.Css#getBoxModel}</td> * </tr> * <tr> * <td>css.boxshadow</td><td><i>String</i> or <i>null</i></td><td><code>boxShadow</code></td> * <td>{@link qx.bom.client.Css#getBoxShadow}</td> * </tr> * <tr> * <td>css.gradient.linear</td><td><i>String</i> or <i>null</i></td><td><code>-moz-linear-gradient</code></td> * <td>{@link qx.bom.client.Css#getLinearGradient}</td> * </tr> * <tr> * <td>css.gradient.filter</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Css#getFilterGradient}</td> * </tr> * <tr> * <td>css.gradient.radial</td><td><i>String</i> or <i>null</i></td><td><code>-moz-radial-gradient</code></td> * <td>{@link qx.bom.client.Css#getRadialGradient}</td> * </tr> * <tr> * <td>css.gradient.legacywebkit</td><td><i>Boolean</i></td><td><code>false</code></td> * <td>{@link qx.bom.client.Css#getLegacyWebkitGradient}</td> * </tr> * <tr> * <td>css.placeholder</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Css#getPlaceholder}</td> * </tr> * <tr> * <td>css.textoverflow</td><td><i>String</i> or <i>null</i></td><td><code>textOverflow</code></td> * <td>{@link qx.bom.client.Css#getTextOverflow}</td> * </tr> * <tr> * <td>css.rgba</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Css#getRgba}</td> * </tr> * <tr> * <td>css.usermodify</td><td><i>String</i> or <i>null</i></td><td><code>WebkitUserModify</code></td> * <td>{@link qx.bom.client.Css#getUserModify}</td> * </tr> * <tr> * <td>css.appearance</td><td><i>String</i> or <i>null</i></td><td><code>WebkitAppearance</code></td> * <td>{@link qx.bom.client.Css#getAppearance}</td> * </tr> * <tr> * <td>css.float</td><td><i>String</i> or <i>null</i></td><td><code>cssFloat</code></td> * <td>{@link qx.bom.client.Css#getFloat}</td> * </tr> * <tr> * <td>css.userselect</td><td><i>String</i> or <i>null</i></td><td><code>WebkitUserSelect</code></td> * <td>{@link qx.bom.client.Css#getUserSelect}</td> * </tr> * <tr> * <td>css.userselect.none</td><td><i>String</i> or <i>null</i></td><td><code>-moz-none</code></td> * <td>{@link qx.bom.client.Css#getUserSelectNone}</td> * </tr> * <tr> * <td>css.boxsizing</td><td><i>String</i> or <i>null</i></td><td><code>boxSizing</code></td> * <td>{@link qx.bom.client.Css#getBoxSizing}</td> * </tr> * <tr> * <td>css.animation</td><td><i>Object</i> or <i>null</i></td><td><code>{end-event: "webkitAnimationEnd", keyframes: "@-webkit-keyframes", play-state: null, name: "WebkitAnimation"}</code></td> * <td>{@link qx.bom.client.CssAnimation#getSupport}</td> * </tr> * <tr> * <td>css.animation.requestframe</td><td><i>String</i> or <i>null</i></td><td><code>mozRequestAnimationFrame</code></td> * <td>{@link qx.bom.client.CssAnimation#getRequestAnimationFrame}</td> * </tr> * <tr> * <td>css.transform</td><td><i>Object</i> or <i>null</i></td><td><code>{3d: true, origin: "WebkitTransformOrigin", name: "WebkitTransform", style: "WebkitTransformStyle", perspective: "WebkitPerspective", perspective-origin: "WebkitPerspectiveOrigin", backface-visibility: "WebkitBackfaceVisibility"}</code></td> * <td>{@link qx.bom.client.CssTransform#getSupport}</td> * </tr> * <tr> * <td>css.transform.3d</td><td><i>Boolean</i></td><td><code>false</code></td> * <td>{@link qx.bom.client.CssTransform#get3D}</td> * </tr> * <tr> * <td>css.inlineblock</td><td><i>String</i> or <i>null</i></td><td><code>inline-block</code></td> * <td>{@link qx.bom.client.Css#getInlineBlock}</td> * </tr> * <tr> * <td>css.opacity</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Css#getOpacity}</td> * </tr> * <tr> * <td>deprecated since 2.1: css.overflowxy</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Css#getOverflowXY}</td> * </tr> * <tr> * <td>css.textShadow</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Css#getTextShadow}</td> * </tr> * <tr> * <td>css.textShadow.filter</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Css#getFilterTextShadow}</td> * </tr> * <tr> * <td colspan="4"><b>device</b></td> * </tr> * <tr> * <td>device.name</td><td><i>String</i></td><td><code>pc</code></td> * <td>{@link qx.bom.client.Device#getName}</td> * </tr> * <tr> * <td>device.type</td><td><i>String</i></td><td><code>mobile</code></td> * <td>{@link qx.bom.client.Device#getType}</td> * </tr> * <tr> * <td colspan="4"><b>ecmascript</b></td> * </tr> * <tr> * <td>ecmascript.error.stacktrace</td><td><i>String</i> or <i>null</i></td><td><code>stack</code></td> * <td>{@link qx.bom.client.EcmaScript#getStackTrace}</td> * </tr> * <tr> * <td>ecmascript.array.indexof<td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.EcmaScript#getArrayIndexOf}</td> * </tr> * <tr> * <td>ecmascript.array.lastindexof<td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.EcmaScript#getArrayLastIndexOf}</td> * </tr> * <tr> * <td>ecmascript.array.foreach<td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.EcmaScript#getArrayForEach}</td> * </tr> * <tr> * <td>ecmascript.array.filter<td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.EcmaScript#getArrayFilter}</td> * </tr> * <tr> * <td>ecmascript.array.map<td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.EcmaScript#getArrayMap}</td> * </tr> * <tr> * <td>ecmascript.array.some<td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.EcmaScript#getArraySome}</td> * </tr> * <tr> * <td>ecmascript.array.every<td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.EcmaScript#getArrayEvery}</td> * </tr> * <tr> * <td>ecmascript.array.reduce<td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.EcmaScript#getArrayReduce}</td> * </tr> * <tr> * <td>ecmascript.array.reduceright<td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.EcmaScript#getArrayReduceRight}</td> * </tr> * <tr> * <td>ecmascript.function.bind<td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.EcmaScript#getFunctionBind}</td> * </tr> * <tr> * <td>ecmascript.object.keys<td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.EcmaScript#getObjectKeys}</td> * </tr> * <tr> * <td>ecmascript.date.now<td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.EcmaScript#getDateNow}</td> * </tr> * <tr> * <td>ecmascript.error.toString</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.EcmaScript#getErrorToString}</td> * </tr> * <tr> * <td>ecmascript.string.trim</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.EcmaScript#getStringTrim}</td> * </tr> * <tr> * <td colspan="4"><b>engine</b></td> * </tr> * <tr> * <td>engine.name</td><td><i>String</i></td><td><code>webkit</code></td> * <td>{@link qx.bom.client.Engine#getName}</td> * </tr> * <tr> * <td>engine.version</td><td><i>String</i></td><td><code>534.24</code></td> * <td>{@link qx.bom.client.Engine#getVersion}</td> * </tr> * <tr> * <td colspan="4"><b>event</b></td> * </tr> * <tr> * <td>event.pointer</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Event#getPointer}</td> * </tr> * <tr> * <td>event.mspointer</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Event#getMsPointer}</td> * </tr> * <tr> * <td>event.touch</td><td><i>Boolean</i></td><td><code>false</code></td> * <td>{@link qx.bom.client.Event#getTouch}</td> * </tr> * <tr> * <td>event.help</td><td><i>Boolean</i></td><td><code>false</code></td> * <td>{@link qx.bom.client.Event#getHelp}</td> * </tr> * <tr> * <td>event.hashchange</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Event#getHashChange}</td> * </tr> * <tr> * <td colspan="4"><b>html</b></td> * </tr> * <tr> * <td>html.audio</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Html#getAudio}</td> * </tr> * <tr> * <td>html.audio.mp3</td><td><i>String</i></td><td><code>""</code></td> * <td>{@link qx.bom.client.Html#getAudioMp3}</td> * </tr> * <tr> * <td>html.audio.ogg</td><td><i>String</i></td><td><code>"maybe"</code></td> * <td>{@link qx.bom.client.Html#getAudioOgg}</td> * </tr> * <tr> * <td>html.audio.wav</td><td><i>String</i></td><td><code>"probably"</code></td> * <td>{@link qx.bom.client.Html#getAudioWav}</td> * </tr> * <tr> * <td>html.audio.au</td><td><i>String</i></td><td><code>"maybe"</code></td> * <td>{@link qx.bom.client.Html#getAudioAu}</td> * </tr> * <tr> * <td>html.audio.aif</td><td><i>String</i></td><td><code>"probably"</code></td> * <td>{@link qx.bom.client.Html#getAudioAif}</td> * </tr> * <tr> * <td>html.canvas</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Html#getCanvas}</td> * </tr> * <tr> * <td>html.classlist</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Html#getClassList}</td> * </tr> * <tr> * <td>html.geolocation</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Html#getGeoLocation}</td> * </tr> * <tr> * <td>html.storage.local</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Html#getLocalStorage}</td> * </tr> * <tr> * <td>html.storage.session</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Html#getSessionStorage}</td> * </tr> * <tr> * <td>html.storage.userdata</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Html#getUserDataStorage}</td> * </tr> * <tr> * <td>html.svg</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Html#getSvg}</td> * </tr> * <tr> * <td>html.video</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Html#getVideo}</td> * </tr> * <tr> * <td>html.video.h264</td><td><i>String</i></td><td><code>"probably"</code></td> * <td>{@link qx.bom.client.Html#getVideoH264}</td> * </tr> * <tr> * <td>html.video.ogg</td><td><i>String</i></td><td><code>""</code></td> * <td>{@link qx.bom.client.Html#getVideoOgg}</td> * </tr> * <tr> * <td>html.video.webm</td><td><i>String</i></td><td><code>"maybe"</code></td> * <td>{@link qx.bom.client.Html#getVideoWebm}</td> * </tr> * <tr> * <td>html.vml</td><td><i>Boolean</i></td><td><code>false</code></td> * <td>{@link qx.bom.client.Html#getVml}</td> * </tr> * <tr> * <td>html.webworker</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Html#getWebWorker}</td> * <tr> * <td>html.filereader</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Html#getFileReader}</td> * </tr> * <tr> * <td>html.xpath</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Html#getXPath}</td> * </tr> * <tr> * <td>html.xul</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Html#getXul}</td> * </tr> * <tr> * <td>html.console</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Html#getConsole}</td> * </tr> * <tr> * <td>html.element.contains</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Html#getContains}</td> * </tr> * <tr> * <td>html.element.compareDocumentPosition</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Html#getCompareDocumentPosition}</td> * </tr> * <tr> * <td>html.element.textContent</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Html#getTextContent}</td> * </tr> * <tr> * <td>html.image.naturaldimensions</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Html#getNaturalDimensions}</td> * </tr> * <tr> * <td>html.history.state</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Html#getHistoryState}</td> * </tr> * <tr> * <td>html.selection</td><td><i>String</i></td><td><code>getSelection</code></td> * <td>{@link qx.bom.client.Html#getSelection}</td> * </tr> * <tr> * <td colspan="4"><b>XML</b></td> * </tr> * <tr> * <td>xml.implementation</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Xml#getImplementation}</td> * </tr> * <tr> * <td>xml.domparser</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Xml#getDomParser}</td> * </tr> * <tr> * <td>xml.selectsinglenode</td><td><i>Boolean</i></td><td><code>false</code></td> * <td>{@link qx.bom.client.Xml#getSelectSingleNode}</td> * </tr> * <tr> * <td>xml.selectnodes</td><td><i>Boolean</i></td><td><code>false</code></td> * <td>{@link qx.bom.client.Xml#getSelectNodes}</td> * </tr> * <tr> * <td>xml.getelementsbytagnamens</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Xml#getElementsByTagNameNS}</td> * </tr> * <tr> * <td>xml.domproperties</td><td><i>Boolean</i></td><td><code>false</code></td> * <td>{@link qx.bom.client.Xml#getDomProperties}</td> * </tr> * <tr> * <td>xml.attributens</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Xml#getAttributeNS}</td> * </tr> * <tr> * <td>xml.createelementns</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Xml#getCreateElementNS}</td> * </tr> * <tr> * <td>xml.createnode</td><td><i>Boolean</i></td><td><code>false</code></td> * <td>{@link qx.bom.client.Xml#getCreateNode}</td> * </tr> * <tr> * <td>xml.getqualifieditem</td><td><i>Boolean</i></td><td><code>false</code></td> * <td>{@link qx.bom.client.Xml#getQualifiedItem}</td> * </tr> * <tr> * <td colspan="4"><b>Stylesheets</b></td> * </tr> * <tr> * <td>html.stylesheet.createstylesheet</td><td><i>Boolean</i></td><td><code>false</code></td> * <td>{@link qx.bom.client.Stylesheet#getCreateStyleSheet}</td> * </tr> * <tr> * <td>html.stylesheet.insertrule</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Stylesheet#getInsertRule}</td> * </tr> * <tr> * <td>html.stylesheet.deleterule</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Stylesheet#getDeleteRule}</td> * </tr> * <tr> * <td>html.stylesheet.addimport</td><td><i>Boolean</i></td><td><code>false</code></td> * <td>{@link qx.bom.client.Stylesheet#getAddImport}</td> * </tr> * <tr> * <td>html.stylesheet.removeimport</td><td><i>Boolean</i></td><td><code>false</code></td> * <td>{@link qx.bom.client.Stylesheet#getRemoveImport}</td> * </tr> * <tr> * <td colspan="4"><b>io</b></td> * </tr> * <tr> * <td>io.maxrequests</td><td><i>Integer</i></td><td><code>4</code></td> * <td>{@link qx.bom.client.Transport#getMaxConcurrentRequestCount}</td> * </tr> * <tr> * <td>io.ssl</td><td><i>Boolean</i></td><td><code>false</code></td> * <td>{@link qx.bom.client.Transport#getSsl}</td> * </tr> * <tr> * <td>io.xhr</td><td><i>String</i></td><td><code>xhr</code></td> * <td>{@link qx.bom.client.Transport#getXmlHttpRequest}</td> * </tr> * <tr> * <td colspan="4"><b>locale</b></td> * </tr> * <tr> * <td>locale</td><td><i>String</i></td><td><code>de</code></td> * <td>{@link qx.bom.client.Locale#getLocale}</td> * </tr> * <tr> * <td>locale.variant</td><td><i>String</i></td><td><code>de</code></td> * <td>{@link qx.bom.client.Locale#getVariant}</td> * </tr> * <tr> * <td colspan="4"><b>os</b></td> * </tr> * <tr> * <td>os.name</td><td><i>String</i></td><td><code>osx</code></td> * <td>{@link qx.bom.client.OperatingSystem#getName}</td> * </tr> * <tr> * <td>os.version</td><td><i>String</i></td><td><code>10.6</code></td> * <td>{@link qx.bom.client.OperatingSystem#getVersion}</td> * </tr> * <tr> * <td>os.scrollBarOverlayed</td><td><i>Boolean</i></td><td><code>false</code></td> * <td>{@link qx.bom.client.Scroll#scrollBarOverlayed}</td> * </tr> * <tr> * <td colspan="4"><b>phonegap</b></td> * </tr> * <tr> * <td>phonegap</td><td><i>Boolean</i></td><td><code>false</code></td> * <td>{@link qx.bom.client.PhoneGap#getPhoneGap}</td> * </tr> * <tr> * <td>phonegap.notification</td><td><i>Boolean</i></td><td><code>false</code></td> * <td>{@link qx.bom.client.PhoneGap#getNotification}</td> * </tr> * <tr> * <td colspan="4"><b>plugin</b></td> * </tr> * <tr> * <td>plugin.divx</td><td><i>Boolean</i></td><td><code>false</code></td> * <td>{@link qx.bom.client.Plugin#getDivX}</td> * </tr> * <tr> * <td>plugin.divx.version</td><td><i>String</i></td><td></td> * <td>{@link qx.bom.client.Plugin#getDivXVersion}</td> * </tr> * <tr> * <td>plugin.flash</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Flash#isAvailable}</td> * </tr> * <tr> * <td>plugin.flash.express</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Flash#getExpressInstall}</td> * </tr> * <tr> * <td>plugin.flash.strictsecurity</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Flash#getStrictSecurityModel}</td> * </tr> * <tr> * <td>plugin.flash.version</td><td><i>String</i></td><td><code>10.2.154</code></td> * <td>{@link qx.bom.client.Flash#getVersion}</td> * </tr> * <tr> * <td>plugin.gears</td><td><i>Boolean</i></td><td><code>false</code></td> * <td>{@link qx.bom.client.Plugin#getGears}</td> * </tr> * <tr> * <td>plugin.activex</td><td><i>Boolean</i></td><td><code>false</code></td> * <td>{@link qx.bom.client.Plugin#getActiveX}</td> * </tr> * <tr> * <td>plugin.skype</td><td><i>Boolean</i></td><td><code>false</code></td> * <td>{@link qx.bom.client.Plugin#getSkype}</td> * </tr> * <tr> * <td>plugin.pdf</td><td><i>Boolean</i></td><td><code>false</code></td> * <td>{@link qx.bom.client.Plugin#getPdf}</td> * </tr> * <tr> * <td>plugin.pdf.version</td><td><i>String</i></td><td></td> * <td>{@link qx.bom.client.Plugin#getPdfVersion}</td> * </tr> * <tr> * <td>plugin.quicktime</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Plugin#getQuicktime}</td> * </tr> * <tr> * <td>plugin.quicktime.version</td><td><i>String</i></td><td><code>7.6</code></td> * <td>{@link qx.bom.client.Plugin#getQuicktimeVersion}</td> * </tr> * <tr> * <td>plugin.silverlight</td><td><i>Boolean</i></td><td><code>false</code></td> * <td>{@link qx.bom.client.Plugin#getSilverlight}</td> * </tr> * <tr> * <td>plugin.silverlight.version</td><td><i>String</i></td><td></td> * <td>{@link qx.bom.client.Plugin#getSilverlightVersion}</td> * </tr> * <tr> * <td>plugin.windowsmedia</td><td><i>Boolean</i></td><td><code>false</code></td> * <td>{@link qx.bom.client.Plugin#getWindowsMedia}</td> * </tr> * <tr> * <td>plugin.windowsmedia.version</td><td><i>String</i></td><td></td> * <td>{@link qx.bom.client.Plugin#getWindowsMediaVersion}</td> * </tr> * <tr> * <td colspan="4"><b>qx</b></td> * </tr> * <tr> * <td>qx.allowUrlSettings</td><td><i>Boolean</i></td><td><code>true</code></td> * <td><i>default:</i> <code>false</code></td> * </tr> * <tr> * <td>qx.allowUrlVariants</td><td><i>Boolean</i></td><td><code>true</code></td> * <td><i>default:</i> <code>false</code></td> * </tr> * <tr> * <td>qx.application</td><td><i>String</i></td><td><code>name.space</code></td> * <td><i>default:</i> <code>&lt;&lt;application name&gt;&gt;</code></td> * </tr> * <tr> * <td>qx.aspects</td><td><i>Boolean</i></td><td><code>false</code></td> * <td><i>default:</i> <code>false</code></td> * </tr> * <tr> * <td>qx.debug</td><td><i>Boolean</i></td><td><code>true</code></td> * <td><i>default:</i> <code>true</code></td> * </tr> * <tr> * <td>qx.debug.databinding</td><td><i>Boolean</i></td><td><code>false</code></td> * <td><i>default:</i> <code>false</code></td> * </tr> * <tr> * <td>qx.debug.dispose</td><td><i>Boolean</i></td><td><code>false</code></td> * <td><i>default:</i> <code>false</code></td> * </tr> * <tr> * <td>qx.debug.dispose.level</td><td><i>Integer</i></td><td><code>0</code></td> * <td><i>default:</i> <code>0</code></td> * </tr> * <tr> * <td>qx.debug.io</td><td><i>Boolean</i></td><td><code>true</code></td> * <td><i>default:</i> <code>false</code></td> * </tr> * <tr> * <tr> * <td>qx.debug.io.remote</td><td><i>Boolean</i></td><td><code>true</code></td> * <td><i>default:</i> <code>false</code></td> * </tr> * <tr> * <tr> * <td>qx.debug.io.remote.data</td><td><i>Boolean</i></td><td><code>true</code></td> * <td><i>default:</i> <code>false</code></td> * </tr> * <tr> * <td>qx.debug.property.level</td><td><i>Integer</i></td><td><code>0</code></td> * <td><i>default:</i> <code>0</code></td> * </tr> * <tr> * <td>qx.debug.ui.queue</td><td><i>Boolean</i></td><td><code>true</code></td> * <td><i>default:</i> <code>true</code></td> * </tr> * <tr> * <td>qx.dynamicmousewheel</td><td><i>Boolean</i></td><td><code>true</code></td> * <td><i>default:</i> <code>true</code></td> * </tr> * <tr> * <td>qx.dynlocale</td><td><i>Boolean</i></td><td><code>true</code></td> * <td><i>default:</i> <code>true</code></td> * </tr> * <tr> * <td>qx.globalErrorHandling</td><td><i>Boolean</i></td><td><code>true</code></td> * <td><i>default:</i> <code>true</code></td> * </tr> * <tr> * <td>qx.mobile.emulatetouch</td><td><i>Boolean</i></td><td><code>false</code></td> * <td><i>default:</i> <code>false</code></td> * </tr> * <tr> * <td>qx.mobile.nativescroll</td><td><i>Boolean</i></td><td><code>false</code></td> * <td><i>default:</i> <code>false</code></td> * </tr> * <tr> * <td>qx.optimization.basecalls</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>true if the corresp. <i>optimize</i> key is set in the config</td> * </tr> * <tr> * <td>qx.optimization.comments</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>true if the corresp. <i>optimize</i> key is set in the config</td> * </tr> * <tr> * <td>qx.optimization.privates</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>true if the corresp. <i>optimize</i> key is set in the config</td> * </tr> * <tr> * <td>qx.optimization.strings</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>true if the corresp. <i>optimize</i> key is set in the config</td> * </tr> * <tr> * <td>qx.optimization.variables</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>true if the corresp. <i>optimize</i> key is set in the config</td> * </tr> * <tr> * <td>qx.optimization.variants</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>true if the corresp. <i>optimize</i> key is set in the config</td> * </tr> * <tr> * <td>qx.revision</td><td><i>String</i></td><td><code>27348</code></td> * </tr> * <tr> * <td>qx.theme</td><td><i>String</i></td><td><code>qx.theme.Modern</code></td> * <td><i>default:</i> <code>&lt;&lt;initial theme name&gt;&gt;</code></td> * </tr> * <tr> * <td>qx.version</td><td><i>String</i></td><td><code>${qxversion}</code></td> * </tr> * <tr> * <td>qx.blankpage</td><td><i>String</i></td><td><code>URI to blank.html page</code></td> * </tr> * <tr> * <td colspan="4"><b>module</b></td> * </tr> * <tr> * <td>module.databinding</td><td><i>Boolean</i></td><td><code>true</code></td> * <td><i>default:</i> <code>true</code></td> * </tr> * <tr> * <td>module.logger</td><td><i>Boolean</i></td><td><code>true</code></td> * <td><i>default:</i> <code>true</code></td> * </tr> * <tr> * <td>module.property</td><td><i>Boolean</i></td><td><code>true</code></td> * <td><i>default:</i> <code>true</code></td> * </tr> * <tr> * <td>module.events</td><td><i>Boolean</i></td><td><code>true</code></td> * <td><i>default:</i> <code>true</code></td> * </tr> * <tr> * <td colspan="4"><h3>Asynchronous checks</h3> * </td> * </tr> * <tr> * <td>html.dataurl</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Html#getDataUrl}</td> * </tr> * </tbody> * </table> * */ qx.Bootstrap.define("qx.core.Environment", { statics : { /** Map containing the synchronous check functions. */ _checks : { }, /** Map containing the asynchronous check functions. */ _asyncChecks : { }, /** Internal cache for all checks. */ __cache : { }, /** Internal map for environment keys to check methods. */ _checksMap : { "engine.version" : "qx.bom.client.Engine.getVersion", "engine.name" : "qx.bom.client.Engine.getName", "browser.name" : "qx.bom.client.Browser.getName", "browser.version" : "qx.bom.client.Browser.getVersion", "browser.documentmode" : "qx.bom.client.Browser.getDocumentMode", "browser.quirksmode" : "qx.bom.client.Browser.getQuirksMode", "runtime.name" : "qx.bom.client.Runtime.getName", "device.name" : "qx.bom.client.Device.getName", "device.type" : "qx.bom.client.Device.getType", "locale" : "qx.bom.client.Locale.getLocale", "locale.variant" : "qx.bom.client.Locale.getVariant", "os.name" : "qx.bom.client.OperatingSystem.getName", "os.version" : "qx.bom.client.OperatingSystem.getVersion", "os.scrollBarOverlayed" : "qx.bom.client.Scroll.scrollBarOverlayed", "plugin.gears" : "qx.bom.client.Plugin.getGears", "plugin.activex" : "qx.bom.client.Plugin.getActiveX", "plugin.skype" : "qx.bom.client.Plugin.getSkype", "plugin.quicktime" : "qx.bom.client.Plugin.getQuicktime", "plugin.quicktime.version" : "qx.bom.client.Plugin.getQuicktimeVersion", "plugin.windowsmedia" : "qx.bom.client.Plugin.getWindowsMedia", "plugin.windowsmedia.version" : "qx.bom.client.Plugin.getWindowsMediaVersion", "plugin.divx" : "qx.bom.client.Plugin.getDivX", "plugin.divx.version" : "qx.bom.client.Plugin.getDivXVersion", "plugin.silverlight" : "qx.bom.client.Plugin.getSilverlight", "plugin.silverlight.version" : "qx.bom.client.Plugin.getSilverlightVersion", "plugin.flash" : "qx.bom.client.Flash.isAvailable", "plugin.flash.version" : "qx.bom.client.Flash.getVersion", "plugin.flash.express" : "qx.bom.client.Flash.getExpressInstall", "plugin.flash.strictsecurity" : "qx.bom.client.Flash.getStrictSecurityModel", "plugin.pdf" : "qx.bom.client.Plugin.getPdf", "plugin.pdf.version" : "qx.bom.client.Plugin.getPdfVersion", "io.maxrequests" : "qx.bom.client.Transport.getMaxConcurrentRequestCount", "io.ssl" : "qx.bom.client.Transport.getSsl", "io.xhr" : "qx.bom.client.Transport.getXmlHttpRequest", "event.touch" : "qx.bom.client.Event.getTouch", "event.pointer" : "qx.bom.client.Event.getPointer", "event.help" : "qx.bom.client.Event.getHelp", "event.hashchange" : "qx.bom.client.Event.getHashChange", "ecmascript.stacktrace" : "qx.bom.client.EcmaScript.getStackTrace", // @deprecated {2.1} "ecmascript.error.stacktrace" : "qx.bom.client.EcmaScript.getStackTrace", "ecmascript.array.indexof" : "qx.bom.client.EcmaScript.getArrayIndexOf", "ecmascript.array.lastindexof" : "qx.bom.client.EcmaScript.getArrayLastIndexOf", "ecmascript.array.foreach" : "qx.bom.client.EcmaScript.getArrayForEach", "ecmascript.array.filter" : "qx.bom.client.EcmaScript.getArrayFilter", "ecmascript.array.map" : "qx.bom.client.EcmaScript.getArrayMap", "ecmascript.array.some" : "qx.bom.client.EcmaScript.getArraySome", "ecmascript.array.every" : "qx.bom.client.EcmaScript.getArrayEvery", "ecmascript.array.reduce" : "qx.bom.client.EcmaScript.getArrayReduce", "ecmascript.array.reduceright" : "qx.bom.client.EcmaScript.getArrayReduceRight", "ecmascript.function.bind" : "qx.bom.client.EcmaScript.getFunctionBind", "ecmascript.object.keys" : "qx.bom.client.EcmaScript.getObjectKeys", "ecmascript.date.now" : "qx.bom.client.EcmaScript.getDateNow", "ecmascript.error.toString" : "qx.bom.client.EcmaScript.getErrorToString", "ecmascript.string.trim" : "qx.bom.client.EcmaScript.getStringTrim", "html.webworker" : "qx.bom.client.Html.getWebWorker", "html.filereader" : "qx.bom.client.Html.getFileReader", "html.geolocation" : "qx.bom.client.Html.getGeoLocation", "html.audio" : "qx.bom.client.Html.getAudio", "html.audio.ogg" : "qx.bom.client.Html.getAudioOgg", "html.audio.mp3" : "qx.bom.client.Html.getAudioMp3", "html.audio.wav" : "qx.bom.client.Html.getAudioWav", "html.audio.au" : "qx.bom.client.Html.getAudioAu", "html.audio.aif" : "qx.bom.client.Html.getAudioAif", "html.video" : "qx.bom.client.Html.getVideo", "html.video.ogg" : "qx.bom.client.Html.getVideoOgg", "html.video.h264" : "qx.bom.client.Html.getVideoH264", "html.video.webm" : "qx.bom.client.Html.getVideoWebm", "html.storage.local" : "qx.bom.client.Html.getLocalStorage", "html.storage.session" : "qx.bom.client.Html.getSessionStorage", "html.storage.userdata" : "qx.bom.client.Html.getUserDataStorage", "html.classlist" : "qx.bom.client.Html.getClassList", "html.xpath" : "qx.bom.client.Html.getXPath", "html.xul" : "qx.bom.client.Html.getXul", "html.canvas" : "qx.bom.client.Html.getCanvas", "html.svg" : "qx.bom.client.Html.getSvg", "html.vml" : "qx.bom.client.Html.getVml", "html.dataset" : "qx.bom.client.Html.getDataset", "html.dataurl" : "qx.bom.client.Html.getDataUrl", "html.console" : "qx.bom.client.Html.getConsole", "html.stylesheet.createstylesheet" : "qx.bom.client.Stylesheet.getCreateStyleSheet", "html.stylesheet.insertrule" : "qx.bom.client.Stylesheet.getInsertRule", "html.stylesheet.deleterule" : "qx.bom.client.Stylesheet.getDeleteRule", "html.stylesheet.addimport" : "qx.bom.client.Stylesheet.getAddImport", "html.stylesheet.removeimport" : "qx.bom.client.Stylesheet.getRemoveImport", "html.element.contains" : "qx.bom.client.Html.getContains", "html.element.compareDocumentPosition" : "qx.bom.client.Html.getCompareDocumentPosition", "html.element.textcontent" : "qx.bom.client.Html.getTextContent", "html.image.naturaldimensions" : "qx.bom.client.Html.getNaturalDimensions", "html.history.state" : "qx.bom.client.Html.getHistoryState", "html.selection" : "qx.bom.client.Html.getSelection", "json" : "qx.bom.client.Json.getJson", "css.textoverflow" : "qx.bom.client.Css.getTextOverflow", "css.placeholder" : "qx.bom.client.Css.getPlaceholder", "css.borderradius" : "qx.bom.client.Css.getBorderRadius", "css.borderimage" : "qx.bom.client.Css.getBorderImage", "css.borderimage.standardsyntax" : "qx.bom.client.Css.getBorderImageSyntax", "css.boxshadow" : "qx.bom.client.Css.getBoxShadow", "css.gradient.linear" : "qx.bom.client.Css.getLinearGradient", "css.gradient.filter" : "qx.bom.client.Css.getFilterGradient", "css.gradient.radial" : "qx.bom.client.Css.getRadialGradient", "css.gradient.legacywebkit" : "qx.bom.client.Css.getLegacyWebkitGradient", "css.boxmodel" : "qx.bom.client.Css.getBoxModel", "css.rgba" : "qx.bom.client.Css.getRgba", "css.userselect" : "qx.bom.client.Css.getUserSelect", "css.userselect.none" : "qx.bom.client.Css.getUserSelectNone", "css.usermodify" : "qx.bom.client.Css.getUserModify", "css.appearance" : "qx.bom.client.Css.getAppearance", "css.float" : "qx.bom.client.Css.getFloat", "css.boxsizing" : "qx.bom.client.Css.getBoxSizing", "css.animation" : "qx.bom.client.CssAnimation.getSupport", "css.animation.requestframe" : "qx.bom.client.CssAnimation.getRequestAnimationFrame", "css.transform" : "qx.bom.client.CssTransform.getSupport", "css.transform.3d" : "qx.bom.client.CssTransform.get3D", "css.inlineblock" : "qx.bom.client.Css.getInlineBlock", "css.opacity" : "qx.bom.client.Css.getOpacity", "css.overflowxy" : "qx.bom.client.Css.getOverflowXY", // @deprecated {2.1} "css.textShadow" : "qx.bom.client.Css.getTextShadow", "css.textShadow.filter" : "qx.bom.client.Css.getFilterTextShadow", "phonegap" : "qx.bom.client.PhoneGap.getPhoneGap", "phonegap.notification" : "qx.bom.client.PhoneGap.getNotification", "xml.implementation" : "qx.bom.client.Xml.getImplementation", "xml.domparser" : "qx.bom.client.Xml.getDomParser", "xml.selectsinglenode" : "qx.bom.client.Xml.getSelectSingleNode", "xml.selectnodes" : "qx.bom.client.Xml.getSelectNodes", "xml.getelementsbytagnamens" : "qx.bom.client.Xml.getElementsByTagNameNS", "xml.domproperties" : "qx.bom.client.Xml.getDomProperties", "xml.attributens" : "qx.bom.client.Xml.getAttributeNS", "xml.createnode" : "qx.bom.client.Xml.getCreateNode", "xml.getqualifieditem" : "qx.bom.client.Xml.getQualifiedItem", "xml.createelementns" : "qx.bom.client.Xml.getCreateElementNS" }, /** * The default accessor for the checks. It returns the value the current * environment has for the given key. The key could be something like * "qx.debug", "css.textoverflow" or "io.ssl". A complete list of * checks can be found in the class comment of this class. * * Please keep in mind that the result is cached. If you want to run the * check function again in case something could have been changed, take a * look at the {@link #invalidateCacheKey} function. * * @param key {String} The name of the check you want to query. * @return {var} The stored value depending on the given key. * (Details in the class doc) */ get : function(key){ if(qx.Bootstrap.DEBUG){ // @deprecated {2.1} if(key == "css.overflowxy"){ qx.Bootstrap.warn("The environment key 'css.overflowxy' is deprecated."); }; // @deprecated {2.1} if(key == "ecmascript.stacktrace"){ qx.Bootstrap.warn("The environment key 'ecmascript.stacktrace' is now 'ecmascript.error.stacktrace'."); key = "ecmascript.error.stacktrace"; }; }; // check the cache if(this.__cache[key] != undefined){ return this.__cache[key]; }; // search for a matching check var check = this._checks[key]; if(check){ // execute the check and write the result in the cache var value = check(); this.__cache[key] = value; return value; }; // try class lookup var classAndMethod = this._getClassNameFromEnvKey(key); if(classAndMethod[0] != undefined){ var clazz = classAndMethod[0]; var method = classAndMethod[1]; var value = clazz[method](); // call the check method this.__cache[key] = value; return value; }; // debug flag if(qx.Bootstrap.DEBUG){ qx.Bootstrap.warn(key + " is not a valid key. Please see the API-doc of " + "qx.core.Environment for a list of predefined keys."); qx.Bootstrap.trace(this); }; }, /** * Maps an environment key to a check class and method name. * * @param key {String} The name of the check you want to query. * @return {Array} [className, methodName] of * the corresponding implementation. */ _getClassNameFromEnvKey : function(key){ var envmappings = this._checksMap; if(envmappings[key] != undefined){ var implementation = envmappings[key]; // separate class from method var lastdot = implementation.lastIndexOf("."); if(lastdot > -1){ var classname = implementation.slice(0, lastdot); var methodname = implementation.slice(lastdot + 1); var clazz = qx.Bootstrap.getByName(classname); if(clazz != undefined){ return [clazz, methodname]; }; }; }; return [undefined, undefined]; }, /** * Invokes the callback as soon as the check has been done. If no check * could be found, a warning will be printed. * * @param key {String} The key of the asynchronous check. * @param callback {Function} The function to call as soon as the check is * done. The function should have one argument which is the result of the * check. * @param self {var} The context to use when invoking the callback. */ getAsync : function(key, callback, self){ // check the cache var env = this; if(this.__cache[key] != undefined){ // force async behavior window.setTimeout(function(){ callback.call(self, env.__cache[key]); }, 0); return; }; var check = this._asyncChecks[key]; if(check){ check(function(result){ env.__cache[key] = result; callback.call(self, result); }); return; }; // try class lookup var classAndMethod = this._getClassNameFromEnvKey(key); if(classAndMethod[0] != undefined){ var clazz = classAndMethod[0]; var method = classAndMethod[1]; clazz[method](function(result){ // call the check method env.__cache[key] = result; callback.call(self, result); }); return; }; // debug flag if(qx.Bootstrap.DEBUG){ qx.Bootstrap.warn(key + " is not a valid key. Please see the API-doc of " + "qx.core.Environment for a list of predefined keys."); qx.Bootstrap.trace(this); }; }, /** * Returns the proper value dependent on the check for the given key. * * @param key {String} The name of the check the select depends on. * @param values {Map} A map containing the values which should be returned * in any case. The "default" key could be used as a catch all statement. * @return {var} The value which is stored in the map for the given * check of the key. */ select : function(key, values){ return this.__pickFromValues(this.get(key), values); }, /** * Selects the proper function dependent on the asynchronous check. * * @param key {String} The key for the async check. * @param values {Map} A map containing functions. The map keys should * contain all possibilities which could be returned by the given check * key. The "default" key could be used as a catch all statement. * The called function will get one parameter, the result of the query. * @param self {var} The context which should be used when calling the * method in the values map. */ selectAsync : function(key, values, self){ this.getAsync(key, function(result){ var value = this.__pickFromValues(key, values); value.call(self, result); }, this); }, /** * Internal helper which tries to pick the given key from the given values * map. If that key is not found, it tries to use a key named "default". * If there is also no default key, it prints out a warning and returns * undefined. * * @param key {String} The key to search for in the values. * @param values {Map} A map containing some keys. * @return {var} The value stored as values[key] usually. */ __pickFromValues : function(key, values){ var value = values[key]; if(values.hasOwnProperty(key)){ return value; }; // check for piped values for(var id in values){ if(id.indexOf("|") != -1){ var ids = id.split("|"); for(var i = 0;i < ids.length;i++){ if(ids[i] == key){ return values[id]; }; }; }; }; if(values["default"] !== undefined){ return values["default"]; }; if(qx.Bootstrap.DEBUG){ throw new Error('No match for variant "' + key + '" (' + (typeof key) + ' type)' + ' in variants [' + qx.Bootstrap.keys(values) + '] found, and no default ("default") given'); }; }, /** * Takes a given map containing the check names as keys and converts * the map to an array only containing the values for check evaluating * to <code>true</code>. This is especially handy for conditional * includes of mixins. * @param map {Map} A map containing check names as keys and values. * @return {Array} An array containing the values. */ filter : function(map){ var returnArray = []; for(var check in map){ if(this.get(check)){ returnArray.push(map[check]); }; }; return returnArray; }, /** * Invalidates the cache for the given key. * * @param key {String} The key of the check. */ invalidateCacheKey : function(key){ delete this.__cache[key]; }, /** * Add a check to the environment class. If there is already a check * added for the given key, the add will be ignored. * * @param key {String} The key for the check e.g. html.featurexyz. * @param check {var} It could be either a function or a simple value. * The function should be responsible for the check and should return the * result of the check. */ add : function(key, check){ // ignore already added checks. if(this._checks[key] == undefined){ // add functions directly if(check instanceof Function){ this._checks[key] = check; } else { this._checks[key] = this.__createCheck(check); }; }; }, /** * Adds an asynchronous check to the environment. If there is already a check * added for the given key, the add will be ignored. * * @param key {String} The key of the check e.g. html.featureabc * @param check {Function} A function which should check for a specific * environment setting in an asynchronous way. The method should take two * arguments. First one is the callback and the second one is the context. */ addAsync : function(key, check){ if(this._checks[key] == undefined){ this._asyncChecks[key] = check; }; }, /** * Returns all currently defined synchronous checks. * * @internal * @return {Map} The map of synchronous checks */ getChecks : function(){ return this._checks; }, /** * Returns all currently defined asynchronous checks. * * @internal * @return {Map} The map of asynchronous checks */ getAsyncChecks : function(){ return this._asyncChecks; }, /** * Initializer for the default values of the framework settings. */ _initDefaultQxValues : function(){ // an always-true key (e.g. for use in qx.core.Environment.filter() calls) this.add("true", function(){ return true; }); // old settings this.add("qx.allowUrlSettings", function(){ return false; }); this.add("qx.allowUrlVariants", function(){ return false; }); this.add("qx.debug.property.level", function(){ return 0; }); // old variants // make sure to reflect all changes to qx.debug here in the bootstrap class! this.add("qx.debug", function(){ return true; }); this.add("qx.debug.ui.queue", function(){ return true; }); this.add("qx.aspects", function(){ return false; }); this.add("qx.dynlocale", function(){ return true; }); this.add("qx.mobile.emulatetouch", function(){ return false; }); this.add("qx.mobile.nativescroll", function(){ return false; }); this.add("qx.blankpage", function(){ return "qx/static/blank.html"; }); this.add("qx.dynamicmousewheel", function(){ return true; }); this.add("qx.debug.databinding", function(){ return false; }); this.add("qx.debug.dispose", function(){ return false; }); // generator optimization vectors this.add("qx.optimization.basecalls", function(){ return false; }); this.add("qx.optimization.comments", function(){ return false; }); this.add("qx.optimization.privates", function(){ return false; }); this.add("qx.optimization.strings", function(){ return false; }); this.add("qx.optimization.variables", function(){ return false; }); this.add("qx.optimization.variants", function(){ return false; }); // qooxdoo modules this.add("module.databinding", function(){ return true; }); this.add("module.logger", function(){ return true; }); this.add("module.property", function(){ return true; }); this.add("module.events", function(){ return true; }); this.add("qx.nativeScrollBars", function(){ return false; }); }, /** * Import checks from global qx.$$environment into the Environment class. */ __importFromGenerator : function(){ // import the environment map if(qx && qx.$$environment){ for(var key in qx.$$environment){ var value = qx.$$environment[key]; this._checks[key] = this.__createCheck(value); }; }; }, /** * Checks the URL for environment settings and imports these into the * Environment class. */ __importFromUrl : function(){ if(window.document && window.document.location){ var urlChecks = window.document.location.search.slice(1).split("&"); for(var i = 0;i < urlChecks.length;i++){ var check = urlChecks[i].split(":"); if(check.length != 3 || check[0] != "qxenv"){ continue; }; var key = check[1]; var value = decodeURIComponent(check[2]); // implicit type conversion if(value == "true"){ value = true; } else if(value == "false"){ value = false; } else if(/^(\d|\.)+$/.test(value)){ value = parseFloat(value); };; this._checks[key] = this.__createCheck(value); }; }; }, /** * Internal helper which creates a function returning the given value. * * @param value {var} The value which should be returned. * @return {Function} A function which could be used by a test. */ __createCheck : function(value){ return qx.Bootstrap.bind(function(value){ return value; }, null, value); } }, defer : function(statics){ // create default values for the environment class statics._initDefaultQxValues(); // load the checks from the generator statics.__importFromGenerator(); // load the checks from the url if(statics.get("qx.allowUrlSettings") === true){ statics.__importFromUrl(); }; } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Martin Wittemann (martinwittemann) ====================================================================== This class contains code from: Copyright: 2011 Pocket Widget S.L., Spain, http://www.pocketwidget.com License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php Authors: * Javier Martinez Villacampa ************************************************************************ */ /** * This class comes with all relevant information regarding * the client's engine. * * This class is used by {@link qx.core.Environment} and should not be used * directly. Please check its class comment for details how to use it. * * @internal */ qx.Bootstrap.define("qx.bom.client.Engine", { // General: http://en.wikipedia.org/wiki/Browser_timeline // Webkit: https://developer.apple.com/internet/safari/uamatrix.html // Firefox: http://en.wikipedia.org/wiki/History_of_Mozilla_Firefox // Maple: http://www.scribd.com/doc/46675822/2011-SDK2-0-Maple-Browser-Specification-V1-00 statics : { /** * Returns the version of the engine. * * @return {String} The version number of the current engine. * @internal */ getVersion : function(){ var agent = window.navigator.userAgent; var version = ""; if(qx.bom.client.Engine.__isOpera()){ // Opera has a special versioning scheme, where the second part is combined // e.g. 8.54 which should be handled like 8.5.4 to be compatible to the // common versioning system used by other browsers if(/Opera[\s\/]([0-9]+)\.([0-9])([0-9]*)/.test(agent)){ // opera >= 10 has as a first verison 9.80 and adds the proper version // in a separate "Version/" postfix // http://my.opera.com/chooseopera/blog/2009/05/29/changes-in-operas-user-agent-string-format if(agent.indexOf("Version/") != -1){ var match = agent.match(/Version\/(\d+)\.(\d+)/); // ignore the first match, its the whole version string version = match[1] + "." + match[2].charAt(0) + "." + match[2].substring(1, match[2].length); } else { version = RegExp.$1 + "." + RegExp.$2; if(RegExp.$3 != ""){ version += "." + RegExp.$3; }; }; }; } else if(qx.bom.client.Engine.__isWebkit()){ if(/AppleWebKit\/([^ ]+)/.test(agent)){ version = RegExp.$1; // We need to filter these invalid characters var invalidCharacter = RegExp("[^\\.0-9]").exec(version); if(invalidCharacter){ version = version.slice(0, invalidCharacter.index); }; }; } else if(qx.bom.client.Engine.__isGecko() || qx.bom.client.Engine.__isMaple()){ // Parse "rv" section in user agent string if(/rv\:([^\);]+)(\)|;)/.test(agent)){ version = RegExp.$1; }; } else if(qx.bom.client.Engine.__isMshtml()){ var isTrident = /Trident\/([^\);]+)(\)|;)/.test(agent); if(/MSIE\s+([^\);]+)(\)|;)/.test(agent)){ version = RegExp.$1; // If the IE8 or IE9 is running in the compatibility mode, the MSIE value // is set to an older version, but we need the correct version. The only // way is to compare the trident version. if(version < 8 && isTrident){ if(RegExp.$1 == "4.0"){ version = "8.0"; } else if(RegExp.$1 == "5.0"){ version = "9.0"; }; }; } else if(isTrident){ // IE 11 dropped the "MSIE" string var match = /\brv\:(\d+?\.\d+?)\b/.exec(agent); if(match){ version = match[1]; }; }; } else { var failFunction = window.qxFail; if(failFunction && typeof failFunction === "function"){ version = failFunction().FULLVERSION; } else { version = "1.9.0.0"; qx.Bootstrap.warn("Unsupported client: " + agent + "! Assumed gecko version 1.9.0.0 (Firefox 3.0)."); }; };;; return version; }, /** * Returns the name of the engine. * * @return {String} The name of the current engine. * @internal */ getName : function(){ var name; if(qx.bom.client.Engine.__isOpera()){ name = "opera"; } else if(qx.bom.client.Engine.__isWebkit()){ name = "webkit"; } else if(qx.bom.client.Engine.__isGecko() || qx.bom.client.Engine.__isMaple()){ name = "gecko"; } else if(qx.bom.client.Engine.__isMshtml()){ name = "mshtml"; } else { // check for the fallback var failFunction = window.qxFail; if(failFunction && typeof failFunction === "function"){ name = failFunction().NAME; } else { name = "gecko"; qx.Bootstrap.warn("Unsupported client: " + window.navigator.userAgent + "! Assumed gecko version 1.9.0.0 (Firefox 3.0)."); }; };;; return name; }, /** * Internal helper for checking for opera. * @return {Boolean} true, if its opera. */ __isOpera : function(){ return window.opera && Object.prototype.toString.call(window.opera) == "[object Opera]"; }, /** * Internal helper for checking for webkit. * @return {Boolean} true, if its webkit. */ __isWebkit : function(){ return window.navigator.userAgent.indexOf("AppleWebKit/") != -1; }, /** * Internal helper for checking for Maple . * Maple is used in Samsung SMART TV 2010-2011 models. It's based on Gecko * engine 1.8.1.11. * @return {Boolean} true, if its maple. */ __isMaple : function(){ return window.navigator.userAgent.indexOf("Maple") != -1; }, /** * Internal helper for checking for gecko. * @return {Boolean} true, if its gecko. */ __isGecko : function(){ return window.controllers && window.navigator.product === "Gecko" && window.navigator.userAgent.indexOf("Maple") == -1 && window.navigator.userAgent.indexOf("Trident") == -1; }, /** * Internal helper to check for MSHTML. * @return {Boolean} true, if its MSHTML. */ __isMshtml : function(){ return window.navigator.cpuClass && (/MSIE\s+([^\);]+)(\)|;)/.test(window.navigator.userAgent) || /Trident\/\d+?\.\d+?/.test(window.navigator.userAgent)); } }, defer : function(statics){ qx.core.Environment.add("engine.version", statics.getVersion); qx.core.Environment.add("engine.name", statics.getName); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2011 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * The main purpose of this class to hold all checks about ECMAScript. * * This class is used by {@link qx.core.Environment} and should not be used * directly. Please check its class comment for details how to use it. * * @internal */ qx.Bootstrap.define("qx.bom.client.EcmaScript", { statics : { /** * Returns the name of the Error object property that holds stack trace * information or null if the client does not provide any. * * @internal * @return {String|null} <code>stack</code>, <code>stacktrace</code> or * <code>null</code> */ getStackTrace : function(){ var propName; var e = new Error("e"); propName = e.stack ? "stack" : e.stacktrace ? "stacktrace" : null; // only thrown errors have the stack property in IE10 and PhantomJS if(!propName){ try{ throw e; } catch(ex) { e = ex; }; }; return e.stacktrace ? "stacktrace" : e.stack ? "stack" : null; }, /** * Checks if 'indexOf' is supported on the Array object. * @internal * @return {Boolean} <code>true</code>, if the method is available. */ getArrayIndexOf : function(){ return !!Array.prototype.indexOf; }, /** * Checks if 'lastIndexOf' is supported on the Array object. * @internal * @return {Boolean} <code>true</code>, if the method is available. */ getArrayLastIndexOf : function(){ return !!Array.prototype.lastIndexOf; }, /** * Checks if 'forEach' is supported on the Array object. * @internal * @return {Boolean} <code>true</code>, if the method is available. */ getArrayForEach : function(){ return !!Array.prototype.forEach; }, /** * Checks if 'filter' is supported on the Array object. * @internal * @return {Boolean} <code>true</code>, if the method is available. */ getArrayFilter : function(){ return !!Array.prototype.filter; }, /** * Checks if 'map' is supported on the Array object. * @internal * @return {Boolean} <code>true</code>, if the method is available. */ getArrayMap : function(){ return !!Array.prototype.map; }, /** * Checks if 'some' is supported on the Array object. * @internal * @return {Boolean} <code>true</code>, if the method is available. */ getArraySome : function(){ return !!Array.prototype.some; }, /** * Checks if 'every' is supported on the Array object. * @internal * @return {Boolean} <code>true</code>, if the method is available. */ getArrayEvery : function(){ return !!Array.prototype.every; }, /** * Checks if 'reduce' is supported on the Array object. * @internal * @return {Boolean} <code>true</code>, if the method is available. */ getArrayReduce : function(){ return !!Array.prototype.reduce; }, /** * Checks if 'reduceRight' is supported on the Array object. * @internal * @return {Boolean} <code>true</code>, if the method is available. */ getArrayReduceRight : function(){ return !!Array.prototype.reduceRight; }, /** * Checks if 'toString' is supported on the Error object and * its working as expected. * @internal * @return {Boolean} <code>true</code>, if the method is available. */ getErrorToString : function(){ return typeof Error.prototype.toString == "function" && Error.prototype.toString() !== "[object Error]"; }, /** * Checks if 'bind' is supported on the Function object. * @internal * @return {Boolean} <code>true</code>, if the method is available. */ getFunctionBind : function(){ return typeof Function.prototype.bind === "function"; }, /** * Checks if 'keys' is supported on the Object object. * @internal * @return {Boolean} <code>true</code>, if the method is available. */ getObjectKeys : function(){ return !!Object.keys; }, /** * Checks if 'now' is supported on the Date object. * @internal * @return {Boolean} <code>true</code>, if the method is available. */ getDateNow : function(){ return !!Date.now; }, /** * Checks if 'trim' is supported on the String object. * @internal * @return {Boolean} <code>true</code>, if the method is available. */ getStringTrim : function(){ return typeof String.prototype.trim === "function"; } }, defer : function(statics){ // array polyfill qx.core.Environment.add("ecmascript.array.indexof", statics.getArrayIndexOf); qx.core.Environment.add("ecmascript.array.lastindexof", statics.getArrayLastIndexOf); qx.core.Environment.add("ecmascript.array.foreach", statics.getArrayForEach); qx.core.Environment.add("ecmascript.array.filter", statics.getArrayFilter); qx.core.Environment.add("ecmascript.array.map", statics.getArrayMap); qx.core.Environment.add("ecmascript.array.some", statics.getArraySome); qx.core.Environment.add("ecmascript.array.every", statics.getArrayEvery); qx.core.Environment.add("ecmascript.array.reduce", statics.getArrayReduce); qx.core.Environment.add("ecmascript.array.reduceright", statics.getArrayReduceRight); // date polyfill qx.core.Environment.add("ecmascript.date.now", statics.getDateNow); // error bugfix qx.core.Environment.add("ecmascript.error.toString", statics.getErrorToString); qx.core.Environment.add("ecmascript.error.stacktrace", statics.getStackTrace); // function polyfill qx.core.Environment.add("ecmascript.function.bind", statics.getFunctionBind); // object polyfill qx.core.Environment.add("ecmascript.object.keys", statics.getObjectKeys); // string polyfill qx.core.Environment.add("ecmascript.string.trim", statics.getStringTrim); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2011 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /** * This class takes care of the normalization of the native 'Array' object. * Therefore it checks the availability of the following methods and appends * it, if not available. This means you can use the methods during * development in every browser. For usage samples, check out the attached links. * * *indexOf*: * <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/indexOf">MDN documentation</a> | * <a href="http://es5.github.com/#x15.4.4.14">Annotated ES5 Spec</a> * * *lastIndexOf*: * <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/lastIndexOf">MDN documentation</a> | * <a href="http://es5.github.com/#x15.4.4.15">Annotated ES5 Spec</a> * * *forEach*: * <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/forEach">MDN documentation</a> | * <a href="http://es5.github.com/#x15.4.4.18">Annotated ES5 Spec</a> * * *filter*: * <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/filter">MDN documentation</a> | * <a href="http://es5.github.com/#x15.4.4.20">Annotated ES5 Spec</a> * * *map*: * <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/map">MDN documentation</a> | * <a href="http://es5.github.com/#x15.4.4.19">Annotated ES5 Spec</a> * * *some*: * <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/some">MDN documentation</a> | * <a href="http://es5.github.com/#x15.4.4.17">Annotated ES5 Spec</a> * * *every*: * <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/every">MDN documentation</a> | * <a href="http://es5.github.com/#x15.4.4.16">Annotated ES5 Spec</a> * * *reduce*: * <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/reduce">MDN documentation</a> | * <a href="http://es5.github.com/#x15.4.4.21">Annotated ES5 Spec</a> * * *reduceRight*: * <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/reduceRight">MDN documentation</a> | * <a href="http://es5.github.com/#x15.4.4.22">Annotated ES5 Spec</a> * * Here is a little sample of how to use <code>indexOf</code> e.g. * <pre class="javascript">var a = ["a", "b", "c"]; * a.indexOf("b"); // returns 1</pre> */ qx.Bootstrap.define("qx.lang.normalize.Array", { defer : function(){ // fix indexOf if(!qx.core.Environment.get("ecmascript.array.indexof")){ Array.prototype.indexOf = function(searchElement, fromIndex){ if(fromIndex == null){ fromIndex = 0; } else if(fromIndex < 0){ fromIndex = Math.max(0, this.length + fromIndex); }; for(var i = fromIndex;i < this.length;i++){ if(this[i] === searchElement){ return i; }; }; return -1; }; }; // lastIndexOf if(!qx.core.Environment.get("ecmascript.array.lastindexof")){ Array.prototype.lastIndexOf = function(searchElement, fromIndex){ if(fromIndex == null){ fromIndex = this.length - 1; } else if(fromIndex < 0){ fromIndex = Math.max(0, this.length + fromIndex); }; for(var i = fromIndex;i >= 0;i--){ if(this[i] === searchElement){ return i; }; }; return -1; }; }; // forEach if(!qx.core.Environment.get("ecmascript.array.foreach")){ Array.prototype.forEach = function(callback, obj){ var l = this.length; for(var i = 0;i < l;i++){ var value = this[i]; if(value !== undefined){ callback.call(obj || window, value, i, this); }; }; }; }; // filter if(!qx.core.Environment.get("ecmascript.array.filter")){ Array.prototype.filter = function(callback, obj){ var res = []; var l = this.length; for(var i = 0;i < l;i++){ var value = this[i]; if(value !== undefined){ if(callback.call(obj || window, value, i, this)){ res.push(this[i]); }; }; }; return res; }; }; // map if(!qx.core.Environment.get("ecmascript.array.map")){ Array.prototype.map = function(callback, obj){ var res = []; var l = this.length; for(var i = 0;i < l;i++){ var value = this[i]; if(value !== undefined){ res[i] = callback.call(obj || window, value, i, this); }; }; return res; }; }; // some if(!qx.core.Environment.get("ecmascript.array.some")){ Array.prototype.some = function(callback, obj){ var l = this.length; for(var i = 0;i < l;i++){ var value = this[i]; if(value !== undefined){ if(callback.call(obj || window, value, i, this)){ return true; }; }; }; return false; }; }; // every if(!qx.core.Environment.get("ecmascript.array.every")){ Array.prototype.every = function(callback, obj){ var l = this.length; for(var i = 0;i < l;i++){ var value = this[i]; if(value !== undefined){ if(!callback.call(obj || window, value, i, this)){ return false; }; }; }; return true; }; }; // reduce if(!qx.core.Environment.get("ecmascript.array.reduce")){ Array.prototype.reduce = function(callback, init){ if(typeof callback !== "function"){ throw new TypeError("First argument is not callable"); }; if(init === undefined && this.length === 0){ throw new TypeError("Length is 0 and no second argument given"); }; var ret = init === undefined ? this[0] : init; for(var i = init === undefined ? 1 : 0;i < this.length;i++){ if(i in this){ ret = callback.call(undefined, ret, this[i], i, this); }; }; return ret; }; }; // reduceRight if(!qx.core.Environment.get("ecmascript.array.reduceright")){ Array.prototype.reduceRight = function(callback, init){ if(typeof callback !== "function"){ throw new TypeError("First argument is not callable"); }; if(init === undefined && this.length === 0){ throw new TypeError("Length is 0 and no second argument given"); }; var ret = init === undefined ? this[this.length - 1] : init; for(var i = init === undefined ? this.length - 2 : this.length - 1;i >= 0;i--){ if(i in this){ ret = callback.call(undefined, ret, this[i], i, this); }; }; return ret; }; }; } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2007-2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Fabian Jakobs (fjakobs) ====================================================================== This class uses ideas and code snipplets presented at http://webreflection.blogspot.com/2008/05/habemus-array-unlocked-length-in-ie8.html http://webreflection.blogspot.com/2008/05/stack-and-arrayobject-how-to-create.html Author: Andrea Giammarchi License: MIT: http://www.opensource.org/licenses/mit-license.php ====================================================================== This class uses documentation of the native Array methods from the MDC documentation of Mozilla. License: CC Attribution-Sharealike License: http://creativecommons.org/licenses/by-sa/2.5/ ************************************************************************ */ /* ************************************************************************ #require(qx.bom.client.Engine) #require(qx.lang.normalize.Array) ************************************************************************ */ /** * This class is the common superclass for most array classes in * qooxdoo. It supports all of the shiny 1.6 JavaScript array features * like <code>forEach</code> and <code>map</code>. * * This class may be instantiated instead of the native Array if * one wants to work with a feature-unified Array instead of the native * one. This class uses native features whereever possible but fills * all missing implementations with custom ones. * * Through the ability to extend from this class one could add even * more utility features on top of it. */ qx.Bootstrap.define("qx.type.BaseArray", { extend : Array, /* ***************************************************************************** CONSTRUCTOR ***************************************************************************** */ /** * Creates a new Array with the given length or the listed elements. * * <pre class="javascript"> * var arr1 = new qx.type.BaseArray(arrayLength); * var arr2 = new qx.type.BaseArray(item0, item1, ..., itemN); * </pre> * * * <code>arrayLength</code>: The initial length of the array. You can access * this value using the length property. If the value specified is not a * number, an array of length 1 is created, with the first element having * the specified value. The maximum length allowed for an * array is 2^32-1, i.e. 4,294,967,295. * * <code>itemN</code>: A value for the element in that position in the * array. When this form is used, the array is initialized with the specified * values as its elements, and the array's length property is set to the * number of arguments. * * @param length_or_items {Integer|var?null} The initial length of the array * OR an argument list of values. */ construct : function(length_or_items){ }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { /** * Converts a base array to a native Array * * @signature function() * @return {Array} The native array */ toArray : null, /** * Returns the current number of items stored in the Array * * @signature function() * @return {Integer} number of items */ valueOf : null, /** * Removes the last element from an array and returns that element. * * This method modifies the array. * * @signature function() * @return {var} The last element of the array. */ pop : null, /** * Adds one or more elements to the end of an array and returns the new length of the array. * * This method modifies the array. * * @signature function(varargs) * @param varargs {var} The elements to add to the end of the array. * @return {Integer} The new array's length */ push : null, /** * Reverses the order of the elements of an array -- the first becomes the last, and the last becomes the first. * * This method modifies the array. * * @signature function() * @return {Array} Returns the modified array (works in place) */ reverse : null, /** * Removes the first element from an array and returns that element. * * This method modifies the array. * * @signature function() * @return {var} The first element of the array. */ shift : null, /** * Sorts the elements of an array. * * This method modifies the array. * * @signature function(compareFunction) * @param compareFunction {Function?null} Specifies a function that defines the sort order. If omitted, * the array is sorted lexicographically (in dictionary order) according to the string conversion of each element. * @return {Array} Returns the modified array (works in place) */ sort : null, /** * Adds and/or removes elements from an array. * * @signature function(index, howMany, varargs) * @param index {Integer} Index at which to start changing the array. If negative, will begin * that many elements from the end. * @param howMany {Integer} An integer indicating the number of old array elements to remove. * If <code>howMany</code> is 0, no elements are removed. In this case, you should specify * at least one new element. * @param varargs {var?null} The elements to add to the array. If you don't specify any elements, * splice simply removes elements from the array. * @return {BaseArray} New array with the removed elements. */ splice : null, /** * Adds one or more elements to the front of an array and returns the new length of the array. * * This method modifies the array. * * @signature function(varargs) * @param varargs {var} The elements to add to the front of the array. * @return {Integer} The new array's length */ unshift : null, /** * Returns a new array comprised of this array joined with other array(s) and/or value(s). * * This method does not modify the array and returns a modified copy of the original. * * @signature function(varargs) * @param varargs {Array|var} Arrays and/or values to concatenate to the resulting array. * @return {qx.type.BaseArray} New array built of the given arrays or values. */ concat : null, /** * Joins all elements of an array into a string. * * @signature function(separator) * @param separator {String} Specifies a string to separate each element of the array. The separator is * converted to a string if necessary. If omitted, the array elements are separated with a comma. * @return {String} The stringified values of all elements divided by the given separator. */ join : null, /** * Extracts a section of an array and returns a new array. * * @signature function(begin, end) * @param begin {Integer} Zero-based index at which to begin extraction. As a negative index, start indicates * an offset from the end of the sequence. slice(-2) extracts the second-to-last element and the last element * in the sequence. * @param end {Integer?length} Zero-based index at which to end extraction. slice extracts up to but not including end. * <code>slice(1,4)</code> extracts the second element through the fourth element (elements indexed 1, 2, and 3). * As a negative index, end indicates an offset from the end of the sequence. slice(2,-1) extracts the third element through the second-to-last element in the sequence. * If end is omitted, slice extracts to the end of the sequence. * @return {BaseArray} An new array which contains a copy of the given region. */ slice : null, /** * Returns a string representing the array and its elements. Overrides the Object.prototype.toString method. * * @signature function() * @return {String} The string representation of the array. */ toString : null, /** * Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found. * * @signature function(searchElement, fromIndex) * @param searchElement {var} Element to locate in the array. * @param fromIndex {Integer?0} The index at which to begin the search. Defaults to 0, i.e. the * whole array will be searched. If the index is greater than or equal to the length of the * array, -1 is returned, i.e. the array will not be searched. If negative, it is taken as * the offset from the end of the array. Note that even when the index is negative, the array * is still searched from front to back. If the calculated index is less than 0, the whole * array will be searched. * @return {Integer} The index of the given element */ indexOf : null, /** * Returns the last (greatest) index of an element within the array equal to the specified value, or -1 if none is found. * * @signature function(searchElement, fromIndex) * @param searchElement {var} Element to locate in the array. * @param fromIndex {Integer?length} The index at which to start searching backwards. Defaults to * the array's length, i.e. the whole array will be searched. If the index is greater than * or equal to the length of the array, the whole array will be searched. If negative, it * is taken as the offset from the end of the array. Note that even when the index is * negative, the array is still searched from back to front. If the calculated index is * less than 0, -1 is returned, i.e. the array will not be searched. * @return {Integer} The index of the given element */ lastIndexOf : null, /** * Executes a provided function once per array element. * * <code>forEach</code> executes the provided function (<code>callback</code>) once for each * element present in the array. <code>callback</code> is invoked only for indexes of the array * which have assigned values; it is not invoked for indexes which have been deleted or which * have never been assigned values. * * <code>callback</code> is invoked with three arguments: the value of the element, the index * of the element, and the Array object being traversed. * * If a <code>obj</code> parameter is provided to <code>forEach</code>, it will be used * as the <code>this</code> for each invocation of the <code>callback</code>. If it is not * provided, or is <code>null</code>, the global object associated with <code>callback</code> * is used instead. * * <code>forEach</code> does not mutate the array on which it is called. * * The range of elements processed by <code>forEach</code> is set before the first invocation of * <code>callback</code>. Elements which are appended to the array after the call to * <code>forEach</code> begins will not be visited by <code>callback</code>. If existing elements * of the array are changed, or deleted, their value as passed to <code>callback</code> will be * the value at the time <code>forEach</code> visits them; elements that are deleted are not visited. * * @signature function(callback, obj) * @param callback {Function} Function to execute for each element. * @param obj {Object} Object to use as this when executing callback. */ forEach : null, /** * Creates a new array with all elements that pass the test implemented by the provided * function. * * <code>filter</code> calls a provided <code>callback</code> function once for each * element in an array, and constructs a new array of all the values for which * <code>callback</code> returns a true value. <code>callback</code> is invoked only * for indexes of the array which have assigned values; it is not invoked for indexes * which have been deleted or which have never been assigned values. Array elements which * do not pass the <code>callback</code> test are simply skipped, and are not included * in the new array. * * <code>callback</code> is invoked with three arguments: the value of the element, the * index of the element, and the Array object being traversed. * * If a <code>obj</code> parameter is provided to <code>filter</code>, it will * be used as the <code>this</code> for each invocation of the <code>callback</code>. * If it is not provided, or is <code>null</code>, the global object associated with * <code>callback</code> is used instead. * * <code>filter</code> does not mutate the array on which it is called. The range of * elements processed by <code>filter</code> is set before the first invocation of * <code>callback</code>. Elements which are appended to the array after the call to * <code>filter</code> begins will not be visited by <code>callback</code>. If existing * elements of the array are changed, or deleted, their value as passed to <code>callback</code> * will be the value at the time <code>filter</code> visits them; elements that are deleted * are not visited. * * @signature function(callback, obj) * @param callback {Function} Function to test each element of the array. * @param obj {Object} Object to use as <code>this</code> when executing <code>callback</code>. * @return {BaseArray} The newly created array with all matching elements */ filter : null, /** * Creates a new array with the results of calling a provided function on every element in this array. * * <code>map</code> calls a provided <code>callback</code> function once for each element in an array, * in order, and constructs a new array from the results. <code>callback</code> is invoked only for * indexes of the array which have assigned values; it is not invoked for indexes which have been * deleted or which have never been assigned values. * * <code>callback</code> is invoked with three arguments: the value of the element, the index of the * element, and the Array object being traversed. * * If a <code>obj</code> parameter is provided to <code>map</code>, it will be used as the * <code>this</code> for each invocation of the <code>callback</code>. If it is not provided, or is * <code>null</code>, the global object associated with <code>callback</code> is used instead. * * <code>map</code> does not mutate the array on which it is called. * * The range of elements processed by <code>map</code> is set before the first invocation of * <code>callback</code>. Elements which are appended to the array after the call to <code>map</code> * begins will not be visited by <code>callback</code>. If existing elements of the array are changed, * or deleted, their value as passed to <code>callback</code> will be the value at the time * <code>map</code> visits them; elements that are deleted are not visited. * * @signature function(callback, obj) * @param callback {Function} Function produce an element of the new Array from an element of the current one. * @param obj {Object} Object to use as <code>this</code> when executing <code>callback</code>. * @return {BaseArray} A new array which contains the return values of every item executed through the given function */ map : null, /** * Tests whether some element in the array passes the test implemented by the provided function. * * <code>some</code> executes the <code>callback</code> function once for each element present in * the array until it finds one where <code>callback</code> returns a true value. If such an element * is found, <code>some</code> immediately returns <code>true</code>. Otherwise, <code>some</code> * returns <code>false</code>. <code>callback</code> is invoked only for indexes of the array which * have assigned values; it is not invoked for indexes which have been deleted or which have never * been assigned values. * * <code>callback</code> is invoked with three arguments: the value of the element, the index of the * element, and the Array object being traversed. * * If a <code>obj</code> parameter is provided to <code>some</code>, it will be used as the * <code>this</code> for each invocation of the <code>callback</code>. If it is not provided, or is * <code>null</code>, the global object associated with <code>callback</code> is used instead. * * <code>some</code> does not mutate the array on which it is called. * * The range of elements processed by <code>some</code> is set before the first invocation of * <code>callback</code>. Elements that are appended to the array after the call to <code>some</code> * begins will not be visited by <code>callback</code>. If an existing, unvisited element of the array * is changed by <code>callback</code>, its value passed to the visiting <code>callback</code> will * be the value at the time that <code>some</code> visits that element's index; elements that are * deleted are not visited. * * @signature function(callback, obj) * @param callback {Function} Function to test for each element. * @param obj {Object} Object to use as <code>this</code> when executing <code>callback</code>. * @return {Boolean} Whether at least one elements passed the test */ some : null, /** * Tests whether all elements in the array pass the test implemented by the provided function. * * <code>every</code> executes the provided <code>callback</code> function once for each element * present in the array until it finds one where <code>callback</code> returns a false value. If * such an element is found, the <code>every</code> method immediately returns <code>false</code>. * Otherwise, if <code>callback</code> returned a true value for all elements, <code>every</code> * will return <code>true</code>. <code>callback</code> is invoked only for indexes of the array * which have assigned values; it is not invoked for indexes which have been deleted or which have * never been assigned values. * * <code>callback</code> is invoked with three arguments: the value of the element, the index of * the element, and the Array object being traversed. * * If a <code>obj</code> parameter is provided to <code>every</code>, it will be used as * the <code>this</code> for each invocation of the <code>callback</code>. If it is not provided, * or is <code>null</code>, the global object associated with <code>callback</code> is used instead. * * <code>every</code> does not mutate the array on which it is called. The range of elements processed * by <code>every</code> is set before the first invocation of <code>callback</code>. Elements which * are appended to the array after the call to <code>every</code> begins will not be visited by * <code>callback</code>. If existing elements of the array are changed, their value as passed * to <code>callback</code> will be the value at the time <code>every</code> visits them; elements * that are deleted are not visited. * * @signature function(callback, obj) * @param callback {Function} Function to test for each element. * @param obj {Object} Object to use as <code>this</code> when executing <code>callback</code>. * @return {Boolean} Whether all elements passed the test */ every : null } }); (function(){ function createStackConstructor(stack){ // In IE don't inherit from Array but use an empty object as prototype // and copy the methods from Array if((qx.core.Environment.get("engine.name") == "mshtml")){ Stack.prototype = { length : 0, $$isArray : true }; var args = "pop.push.reverse.shift.sort.splice.unshift.join.slice".split("."); for(var length = args.length;length;){ Stack.prototype[args[--length]] = Array.prototype[args[length]]; }; }; // Remember Array's slice method var slice = Array.prototype.slice; // Fix "concat" method Stack.prototype.concat = function(){ var constructor = this.slice(0); for(var i = 0,length = arguments.length;i < length;i++){ var copy; if(arguments[i] instanceof Stack){ copy = slice.call(arguments[i], 0); } else if(arguments[i] instanceof Array){ copy = arguments[i]; } else { copy = [arguments[i]]; }; constructor.push.apply(constructor, copy); }; return constructor; }; // Fix "toString" method Stack.prototype.toString = function(){ return slice.call(this, 0).toString(); }; // Fix "toLocaleString" Stack.prototype.toLocaleString = function(){ return slice.call(this, 0).toLocaleString(); }; // Fix constructor Stack.prototype.constructor = Stack; // Add JS 1.6 Array features Stack.prototype.indexOf = Array.prototype.indexOf; Stack.prototype.lastIndexOf = Array.prototype.lastIndexOf; Stack.prototype.forEach = Array.prototype.forEach; Stack.prototype.some = Array.prototype.some; Stack.prototype.every = Array.prototype.every; var filter = Array.prototype.filter; var map = Array.prototype.map; // Fix methods which generates a new instance // to return an instance of the same class Stack.prototype.filter = function(){ var ret = new this.constructor; ret.push.apply(ret, filter.apply(this, arguments)); return ret; }; Stack.prototype.map = function(){ var ret = new this.constructor; ret.push.apply(ret, map.apply(this, arguments)); return ret; }; Stack.prototype.slice = function(){ var ret = new this.constructor; ret.push.apply(ret, Array.prototype.slice.apply(this, arguments)); return ret; }; Stack.prototype.splice = function(){ var ret = new this.constructor; ret.push.apply(ret, Array.prototype.splice.apply(this, arguments)); return ret; }; // Add new "toArray" method for convert a base array to a native Array Stack.prototype.toArray = function(){ return Array.prototype.slice.call(this, 0); }; // Add valueOf() to return the length Stack.prototype.valueOf = function(){ return this.length; }; // Return final class return Stack; }; function Stack(length){ if(arguments.length === 1 && typeof length === "number"){ this.length = -1 < length && length === length >> .5 ? length : this.push(length); } else if(arguments.length){ this.push.apply(this, arguments); }; }; function PseudoArray(){ }; PseudoArray.prototype = []; Stack.prototype = new PseudoArray; Stack.prototype.length = 0; qx.type.BaseArray = createStackConstructor(Stack); })(); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /* ************************************************************************ #ignore(q) ************************************************************************ */ /** * The Core module's responsibility is to query the DOM for elements and offer * these elements as a collection. The Core module itself does not offer any methods to * work with the collection. These methods are added by the other included modules, * such as Manipulating or Attributes. * * Core also provides the plugin API which allows modules to attach either * static functions to the global <code>q</code> object or define methods on the * collection it returns. * * By default, the core module is assigned to a global module named <code>q</code>. * In case <code>q</code> is already defined, the name <code>qxWeb</code> * is used instead. * * For further details, take a look at the documentation in the * <a href='http://manual.qooxdoo.org/${qxversion}/pages/website.html' target='_blank'>user manual</a>. */ qx.Bootstrap.define("qxWeb", { extend : qx.type.BaseArray, statics : { // internal storage for all initializers __init : [], // internal reference to the used qx namespace $$qx : qx, /** * Internal helper to initialize collections. * * @param arg {var} An array of Elements which will * be initialized as {@link q}. All items in the array which are not * either a window object or a node object will be ignored. * @return {q} A new initialized collection. */ $init : function(arg){ var clean = []; for(var i = 0;i < arg.length;i++){ var isNode = !!(arg[i] && arg[i].nodeType != null); if(isNode){ clean.push(arg[i]); continue; }; var isWindow = !!(arg[i] && arg[i].history && arg[i].location && arg[i].document); if(isWindow){ clean.push(arg[i]); }; }; // check for node or window object var col = qx.lang.Array.cast(clean, qxWeb); for(var i = 0;i < qxWeb.__init.length;i++){ qxWeb.__init[i].call(col); }; return col; }, /** * This is an API for module development and can be used to attach new methods * to {@link q}. * * @param module {Map} A map containing the methods to attach. */ $attach : function(module){ for(var name in module){ { }; qxWeb.prototype[name] = module[name]; }; }, /** * This is an API for module development and can be used to attach new methods * to {@link q}. * * @param module {Map} A map containing the methods to attach. */ $attachStatic : function(module){ for(var name in module){ { }; qxWeb[name] = module[name]; }; }, /** * This is an API for module development and can be used to attach new initialization * methods to {@link q} which will be called when a new collection is * created. * * @param init {Function} The initialization method for a module. */ $attachInit : function(init){ this.__init.push(init); }, /** * Define a new class using the qooxdoo class system. * * @signature function(name, config) * @param name {String?} Name of the class. If null, the class will not be * attached to a namespace. * @param config {Map} Class definition structure. * @return {Function} The defined class. */ define : function(name, config){ if(config == undefined){ config = name; name = null; }; return qx.Bootstrap.define.call(qx.Bootstrap, name, config); } }, /** * Accepts a selector string and returns a set of found items. The optional context * element can be used to reduce the amount of found elements to children of the * context element. * * <a href="http://sizzlejs.com/" target="_blank">Sizzle</a> is used as selector engine. * Check out the <a href="https://github.com/jquery/sizzle/wiki/Sizzle-Home" target="_blank">documentation</a> * for more details. * * @param selector {String|Element|Array} Valid selector (CSS3 + extensions) * or DOM element or Array of DOM Elements. * @param context {Element} Only the children of this element are considered. * @return {q} A collection of DOM elements. */ construct : function(selector, context){ if(!selector && this instanceof qxWeb){ return this; }; if(qx.Bootstrap.isString(selector)){ selector = qx.bom.Selector.query(selector, context); } else if(!(qx.Bootstrap.isArray(selector))){ selector = [selector]; }; return qxWeb.$init(selector); }, members : { /** * Gets a new collection containing only those elements that passed the * given filter. This can be either a selector expression or a filter * function. * * @param selector {String|Function} Selector expression or filter function * @return {q} New collection containing the elements that passed the filter */ filter : function(selector){ if(qx.lang.Type.isFunction(selector)){ return qxWeb.$init(Array.prototype.filter.call(this, selector)); }; return qxWeb.$init(qx.bom.Selector.matches(selector, this)); }, /** * Returns a copy of the collection within the given range. * * @param begin {Number} The index to begin. * @param end {Number?} The index to end. * @return {q} A new collection containing a slice of the original collection. */ slice : function(begin, end){ // Old IEs return an empty array if the second argument is undefined if(end){ return qxWeb.$init(Array.prototype.slice.call(this, begin, end)); } else { return qxWeb.$init(Array.prototype.slice.call(this, begin)); }; }, /** * Removes the given number of items and returns the removed items as a new collection. * This method can also add items. Take a look at the * <a href='https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/splice' target='_blank'>documentation of MDN</a> for more details. * * @param index {Number} The index to begin. * @param howMany {Number} the amount of items to remove. * @param varargs {var} As many items as you want to add. * @return {q} A new collection containing the removed items. */ splice : function(index, howMany, varargs){ return qxWeb.$init(Array.prototype.splice.apply(this, arguments)); }, /** * Returns a new collection containing the modified elements. For more details, check out the * <a href='https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/map' target='_blank'>MDN documentation</a>. * * @param callback {Function} Function which produces the new element. * @param thisarg {var} Context of the callback. * @return {q} New collection containing the elements that passed the filter */ map : function(callback, thisarg){ return qxWeb.$init(Array.prototype.map.apply(this, arguments)); }, /** * Returns a copy of the collection including the given elements. * * @param varargs {var} As many items as you want to add. * @return {q} A new collection containing all items. */ concat : function(varargs){ var clone = Array.prototype.slice.call(this, 0); for(var i = 0;i < arguments.length;i++){ if(arguments[i] instanceof qxWeb){ clone = clone.concat(Array.prototype.slice.call(arguments[i], 0)); } else { clone.push(arguments[i]); }; }; return qxWeb.$init(clone); } }, /** * @lint ignoreUndefined(q) */ defer : function(statics){ if(window.q == undefined){ q = statics; }; } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /** * This class takes care of the normalization of the native 'Date' object. * Therefore it checks the availability of the following methods and appends * it, if not available. This means you can use the methods during * development in every browser. For usage samples, check out the attached links. * * *now*: * <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/now">MDN documentation</a> | * <a href="http://es5.github.com/#x15.9.4.4">Annotated ES5 Spec</a> */ qx.Bootstrap.define("qx.lang.normalize.Date", { defer : function(){ // Date.now if(!qx.core.Environment.get("ecmascript.date.now")){ Date.now = function(){ return +new Date(); }; }; } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Andreas Ecker (ecker) ====================================================================== This class contains code based on the following work: * jQuery http://jquery.com Version 1.3.1 Copyright: 2009 John Resig License: MIT: http://www.opensource.org/licenses/mit-license.php ************************************************************************ */ /* ************************************************************************ #ignore(qx.data.IListData) #ignore(qx.Class) #require(qx.lang.normalize.Date) ************************************************************************ */ /** * Static helper functions for arrays with a lot of often used convenience * methods like <code>remove</code> or <code>contains</code>. * * The native JavaScript Array is not modified by this class. However, * there are modifications to the native Array in {@link qx.lang.normalize.Array} for * browsers that do not support certain JavaScript features natively . */ qx.Bootstrap.define("qx.lang.Array", { statics : { /** * Converts array like constructions like the <code>argument</code> object, * node collections like the ones returned by <code>getElementsByTagName</code> * or extended array objects like <code>qx.type.BaseArray</code> to an * native Array instance. * * @deprecated {2.1} Please use cast with 'Array' as constructor. * @param object {var} any array like object * @param offset {Integer?0} position to start from * @return {Array} New array with the content of the incoming object */ toArray : function(object, offset){ { }; return this.cast(object, Array, offset); }, /** * Converts an array like object to any other array like * object. * * Attention: The returned array may be same * instance as the incoming one if the constructor is identical! * * @param object {var} any array-like object * @param constructor {Function} constructor of the new instance * @param offset {Integer?0} position to start from * @return {Array} the converted array */ cast : function(object, constructor, offset){ if(object.constructor === constructor){ return object; }; if(qx.data && qx.data.IListData){ if(qx.Class && qx.Class.hasInterface(object, qx.data.IListData)){ var object = object.toArray(); }; }; // Create from given constructor var ret = new constructor; // Some collections in mshtml are not able to be sliced. // These lines are a special workaround for this client. if((qx.core.Environment.get("engine.name") == "mshtml")){ if(object.item){ for(var i = offset || 0,l = object.length;i < l;i++){ ret.push(object[i]); }; return ret; }; }; // Copy over items if(Object.prototype.toString.call(object) === "[object Array]" && offset == null){ ret.push.apply(ret, object); } else { ret.push.apply(ret, Array.prototype.slice.call(object, offset || 0)); }; return ret; }, /** * Convert an arguments object into an array. * * @param args {arguments} arguments object * @param offset {Integer?0} position to start from * @return {Array} a newly created array (copy) with the content of the arguments object. */ fromArguments : function(args, offset){ return Array.prototype.slice.call(args, offset || 0); }, /** * Convert a (node) collection into an array * * @param coll {var} node collection * @return {Array} a newly created array (copy) with the content of the node collection. */ fromCollection : function(coll){ // The native Array.slice cannot be used with some Array-like objects // including NodeLists in older IEs if((qx.core.Environment.get("engine.name") == "mshtml")){ if(coll.item){ var arr = []; for(var i = 0,l = coll.length;i < l;i++){ arr[i] = coll[i]; }; return arr; }; }; return Array.prototype.slice.call(coll, 0); }, /** * Expand shorthand definition to a four element list. * This is an utility function for padding/margin and all other shorthand handling. * * @param input {Array} arr with one to four elements * @return {Array} an arr with four elements */ fromShortHand : function(input){ var len = input.length; var result = qx.lang.Array.clone(input); // Copy Values (according to the length) switch(len){case 1: result[1] = result[2] = result[3] = result[0]; break;case 2: result[2] = result[0];// no break here case 3: result[3] = result[1];}; // Return list with 4 items return result; }, /** * Return a copy of the given array * * @param arr {Array} the array to copy * @return {Array} copy of the array */ clone : function(arr){ return arr.concat(); }, /** * Insert an element at a given position into the array * * @param arr {Array} the array * @param obj {var} the element to insert * @param i {Integer} position where to insert the element into the array * @return {Array} the array */ insertAt : function(arr, obj, i){ arr.splice(i, 0, obj); return arr; }, /** * Insert an element into the array before a given second element. * * @param arr {Array} the array * @param obj {var} object to be inserted * @param obj2 {var} insert obj1 before this object * @return {Array} the array */ insertBefore : function(arr, obj, obj2){ var i = arr.indexOf(obj2); if(i == -1){ arr.push(obj); } else { arr.splice(i, 0, obj); }; return arr; }, /** * Insert an element into the array after a given second element. * * @param arr {Array} the array * @param obj {var} object to be inserted * @param obj2 {var} insert obj1 after this object * @return {Array} the array */ insertAfter : function(arr, obj, obj2){ var i = arr.indexOf(obj2); if(i == -1 || i == (arr.length - 1)){ arr.push(obj); } else { arr.splice(i + 1, 0, obj); }; return arr; }, /** * Remove an element from the array at the given index * * @param arr {Array} the array * @param i {Integer} index of the element to be removed * @return {var} The removed element. */ removeAt : function(arr, i){ return arr.splice(i, 1)[0]; }, /** * Remove all elements from the array * * @param arr {Array} the array * @return {Array} empty array */ removeAll : function(arr){ arr.length = 0; return this; }, /** * Append the elements of an array to the array * * @param arr1 {Array} the array * @param arr2 {Array} the elements of this array will be appended to other one * @return {Array} The modified array. * @throws {Error} if one of the arguments is not an array */ append : function(arr1, arr2){ { }; Array.prototype.push.apply(arr1, arr2); return arr1; }, /** * Modifies the first array as it removes all elements * which are listed in the second array as well. * * @param arr1 {Array} the array * @param arr2 {Array} the elements of this array will be excluded from the other one * @return {Array} The modified array. * @throws {Error} if one of the arguments is not an array */ exclude : function(arr1, arr2){ { }; for(var i = 0,il = arr2.length,index;i < il;i++){ index = arr1.indexOf(arr2[i]); if(index != -1){ arr1.splice(index, 1); }; }; return arr1; }, /** * Remove an element from the array. * * @param arr {Array} the array * @param obj {var} element to be removed from the array * @return {var} the removed element */ remove : function(arr, obj){ var i = arr.indexOf(obj); if(i != -1){ arr.splice(i, 1); return obj; }; }, /** * Whether the array contains the given element * * @param arr {Array} the array * @param obj {var} object to look for * @return {Boolean} whether the arr contains the element */ contains : function(arr, obj){ return arr.indexOf(obj) !== -1; }, /** * Check whether the two arrays have the same content. Checks only the * equality of the arrays' content. * * @param arr1 {Array} first array * @param arr2 {Array} second array * @return {Boolean} Whether the two arrays are equal */ equals : function(arr1, arr2){ var length = arr1.length; if(length !== arr2.length){ return false; }; for(var i = 0;i < length;i++){ if(arr1[i] !== arr2[i]){ return false; }; }; return true; }, /** * Returns the sum of all values in the given array. Supports * numeric values only. * * @param arr {Number[]} Array to process * @return {Number} The sum of all values. */ sum : function(arr){ var result = 0; for(var i = 0,l = arr.length;i < l;i++){ result += arr[i]; }; return result; }, /** * Returns the highest value in the given array. Supports * numeric values only. * * @param arr {Number[]} Array to process * @return {Number | null} The highest of all values or undefined if array is empty. */ max : function(arr){ { }; var i,len = arr.length,result = arr[0]; for(i = 1;i < len;i++){ if(arr[i] > result){ result = arr[i]; }; }; return result === undefined ? null : result; }, /** * Returns the lowest value in the given array. Supports * numeric values only. * * @param arr {Number[]} Array to process * @return {Number | null} The lowest of all values or undefined if array is empty. */ min : function(arr){ { }; var i,len = arr.length,result = arr[0]; for(i = 1;i < len;i++){ if(arr[i] < result){ result = arr[i]; }; }; return result === undefined ? null : result; }, /** * Recreates an array which is free of all duplicate elements from the original. * * This method do not modifies the original array! * * Keep in mind that this methods deletes undefined indexes. * * @param arr {Array} Incoming array * @return {Array} Returns a copy with no duplicates or the original array if no duplicates were found */ unique : function(arr){ var ret = [],doneStrings = { },doneNumbers = { },doneObjects = { }; var value,count = 0; var key = "qx" + Date.now(); var hasNull = false,hasFalse = false,hasTrue = false; // Rebuild array and omit duplicates for(var i = 0,len = arr.length;i < len;i++){ value = arr[i]; // Differ between null, primitives and reference types if(value === null){ if(!hasNull){ hasNull = true; ret.push(value); }; } else if(value === undefined){ } else if(value === false){ if(!hasFalse){ hasFalse = true; ret.push(value); }; } else if(value === true){ if(!hasTrue){ hasTrue = true; ret.push(value); }; } else if(typeof value === "string"){ if(!doneStrings[value]){ doneStrings[value] = 1; ret.push(value); }; } else if(typeof value === "number"){ if(!doneNumbers[value]){ doneNumbers[value] = 1; ret.push(value); }; } else { var hash = value[key]; if(hash == null){ hash = value[key] = count++; }; if(!doneObjects[hash]){ doneObjects[hash] = value; ret.push(value); }; };;;;; }; // Clear object hashs for(var hash in doneObjects){ try{ // TODO: The following delete seems to fail in IE7 delete doneObjects[hash][key]; } catch(ex) { try{ doneObjects[hash][key] = null; } catch(ex1) { throw new Error("Cannot clean-up map entry doneObjects[" + hash + "][" + key + "]"); }; }; }; return ret; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2008-2010 Sebastian Werner, http://sebastian-werner.net License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Fabian Jakobs (fjakobs) * Andreas Ecker (ecker) ====================================================================== This class contains code based on the following work: * Sizzle CSS Selector Engine - v1.8.2 Homepage: http://sizzlejs.com/ Documentation: http://wiki.github.com/jeresig/sizzle Discussion: http://groups.google.com/group/sizzlejs Code: http://github.com/jeresig/sizzle/tree Copyright: (c) 2009, The Dojo Foundation License: MIT: http://www.opensource.org/licenses/mit-license.php ---------------------------------------------------------------------- Copyright (c) 2009 John Resig Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ---------------------------------------------------------------------- Version: Snapshot taken on 2012-10-02, latest Sizzle commit on 2012-09-20: commit 41a7c2ce9be6c66e0c9b8b15e0a29c8e3ca6fb31 ************************************************************************ */ /** * The selector engine supports virtually all CSS 3 Selectors – this even * includes some parts that are infrequently implemented such as escaped * selectors (<code>.foo\\+bar</code>), Unicode selectors, and results returned * in document order. There are a few notable exceptions to the CSS 3 selector * support: * * * <code>:root</code> * * <code>:target</code> * * <code>:nth-last-child</code> * * <code>:nth-of-type</code> * * <code>:nth-last-of-type</code> * * <code>:first-of-type</code> * * <code>:last-of-type</code> * * <code>:only-of-type</code> * * <code>:lang()</code> * * In addition to the CSS 3 Selectors the engine supports the following * additional selectors or conventions. * * *Changes* * * * <code>:not(a.b)</code>: Supports non-simple selectors in <code>:not()</code> (most browsers only support <code>:not(a)</code>, for example). * * <code>:not(div > p)</code>: Supports full selectors in <code>:not()</code>. * * <code>:not(div, p)</code>: Supports multiple selectors in <code>:not()</code>. * * <code>[NAME=VALUE]</code>: Doesn't require quotes around the specified value in an attribute selector. * * *Additions* * * * <code>[NAME!=VALUE]</code>: Finds all elements whose <code>NAME</code> attribute doesn't match the specified value. Is equivalent to doing <code>:not([NAME=VALUE])</code>. * * <code>:contains(TEXT)</code>: Finds all elements whose textual context contains the word <code>TEXT</code> (case sensitive). * * <code>:header</code>: Finds all elements that are a header element (h1, h2, h3, h4, h5, h6). * * <code>:parent</code>: Finds all elements that contains another element. * * *Positional Selector Additions* * * * <code>:first</code>/</code>:last</code>: Finds the first or last matching element on the page. (e.g. <code>div:first</code> would find the first div on the page, in document order) * * <code>:even</code>/<code>:odd</code>: Finds every other element on the page (counting begins at 0, so <code>:even</code> would match the first element). * * <code>:eq</code>/<code>:nth</code>: Finds the Nth element on the page (e.g. <code>:eq(5)</code> finds the 6th element on the page). * * <code>:lt</code>/<code>:gt</code>: Finds all elements at positions less than or greater than the specified positions. * * *Form Selector Additions* * * * <code>:input</code>: Finds all input elements (includes textareas, selects, and buttons). * * <code>:text</code>, <code>:checkbox</code>, <code>:file</code>, <code>:password</code>, <code>:submit</code>, <code>:image</code>, <code>:reset</code>, <code>:button</code>: Finds the input element with the specified input type (<code>:button</code> also finds button elements). * * Based on Sizzle by John Resig, see: * * * http://sizzlejs.com/ * * For further usage details also have a look at the wiki page at: * * * https://github.com/jquery/sizzle/wiki/Sizzle-Home */ qx.Bootstrap.define("qx.bom.Selector", { statics : { /** * Queries the document for the given selector. Supports all CSS3 selectors * plus some extensions as mentioned in the class description. * * @signature function(selector, context) * @param selector {String} Valid selector (CSS3 + extensions) * @param context {Element} Context element (result elements must be children of this element) * @return {Array} Matching elements */ query : null, /** * Returns an reduced array which only contains the elements from the given * array which matches the given selector * * @signature function(selector, set) * @param selector {String} Selector to filter given set * @param set {Array} List to filter according to given selector * @return {Array} New array containing matching elements */ matches : null } }); /** * Below is the original Sizzle code. Snapshot date is mentioned in the head of * this file. * @lint ignoreUnused(j, rnot, rendsWithNot) */ /*! * Sizzle CSS Selector Engine * Copyright 2012 jQuery Foundation and other contributors * Released under the MIT license * http://sizzlejs.com/ */ (function(window, undefined){ var cachedruns,assertGetIdNotName,Expr,getText,isXML,contains,compile,sortOrder,hasDuplicate,outermostContext,baseHasDuplicate = true,strundefined = "undefined",expando = ("sizcache" + Math.random()).replace(".", ""),Token = String,document = window.document,docElem = document.documentElement,dirruns = 0,done = 0,pop = [].pop,push = [].push,slice = [].slice,// Use a stripped-down indexOf if a native one is unavailable indexOf = [].indexOf || function(elem){ var i = 0,len = this.length; for(;i < len;i++){ if(this[i] === elem){ return i; }; }; return -1; },// Augment a function for special use by Sizzle markFunction = function(fn, value){ fn[expando] = value == null || value; return fn; },createCache = function(){ var cache = { },keys = []; return markFunction(function(key, value){ // Only keep the most recent entries if(keys.push(key) > Expr.cacheLength){ delete cache[keys.shift()]; }; return (cache[key] = value); }, cache); },classCache = createCache(),tokenCache = createCache(),compilerCache = createCache(),// Regex // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]",// http://www.w3.org/TR/css3-syntax/#characters characterEncoding = "(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",// Loosely modeled on CSS identifier characters // An unquoted value should be a CSS identifier (http://www.w3.org/TR/css3-selectors/#attribute-selectors) // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier identifier = characterEncoding.replace("w", "w#"),// Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors operators = "([*^$|!~]?=)",attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace + "*(?:" + operators + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]",// Prefer arguments not in parens/brackets, // then attribute selectors and non-pseudos (denoted by :), // then anything else // These preferences are here to reduce the number of selectors // needing tokenize in the PSEUDO preFilter pseudos = ":(" + characterEncoding + ")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:" + attributes + ")|[^:]|\\\\.)*|.*))\\)|)",// For matchExpr.POS and matchExpr.needsContext pos = ":(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)",// Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rtrim = new RegExp("^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g"),rcomma = new RegExp("^" + whitespace + "*," + whitespace + "*"),rcombinators = new RegExp("^" + whitespace + "*([\\x20\\t\\r\\n\\f>+~])" + whitespace + "*"),rpseudo = new RegExp(pseudos),// Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,rnot = /^:not/,rsibling = /[\x20\t\r\n\f]*[+~]/,rendsWithNot = /:not\($/,rheader = /h\d/i,rinputs = /input|select|textarea|button/i,rbackslash = /\\(?!\\)/g,matchExpr = { "ID" : new RegExp("^#(" + characterEncoding + ")"), "CLASS" : new RegExp("^\\.(" + characterEncoding + ")"), "NAME" : new RegExp("^\\[name=['\"]?(" + characterEncoding + ")['\"]?\\]"), "TAG" : new RegExp("^(" + characterEncoding.replace("w", "w*") + ")"), "ATTR" : new RegExp("^" + attributes), "PSEUDO" : new RegExp("^" + pseudos), "POS" : new RegExp(pos, "i"), "CHILD" : new RegExp("^:(only|nth|first|last)-child(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i"), // For use in libraries implementing .is() "needsContext" : new RegExp("^" + whitespace + "*[>+~]|" + pos, "i") },// Support // Used for testing something on an element assert = function(fn){ var div = document.createElement("div"); try{ return fn(div); } catch(e) { return false; }finally{ // release memory in IE div = null; }; },// Check if getElementsByTagName("*") returns only elements assertTagNameNoComments = assert(function(div){ div.appendChild(document.createComment("")); return !div.getElementsByTagName("*").length; }),// Check if getAttribute returns normalized href attributes assertHrefNotNormalized = assert(function(div){ div.innerHTML = "<a href='#'></a>"; return div.firstChild && typeof div.firstChild.getAttribute !== strundefined && div.firstChild.getAttribute("href") === "#"; }),// Check if attributes should be retrieved by attribute nodes assertAttributes = assert(function(div){ div.innerHTML = "<select></select>"; var type = typeof div.lastChild.getAttribute("multiple"); // IE8 returns a string for some attributes even when not present return type !== "boolean" && type !== "string"; }),// Check if getElementsByClassName can be trusted assertUsableClassName = assert(function(div){ // Opera can't find a second classname (in 9.6) div.innerHTML = "<div class='hidden e'></div><div class='hidden'></div>"; if(!div.getElementsByClassName || !div.getElementsByClassName("e").length){ return false; }; // Safari 3.2 caches class attributes and doesn't catch changes div.lastChild.className = "e"; return div.getElementsByClassName("e").length === 2; }),// Check if getElementById returns elements by name // Check if getElementsByName privileges form controls or returns elements by ID assertUsableName = assert(function(div){ // Inject content div.id = expando + 0; div.innerHTML = "<a name='" + expando + "'></a><div name='" + expando + "'></div>"; docElem.insertBefore(div, docElem.firstChild); // Test var pass = document.getElementsByName && // buggy browsers will return fewer than the correct 2 document.getElementsByName(expando).length === 2 + // buggy browsers will return more than the correct 0 document.getElementsByName(expando + 0).length; assertGetIdNotName = !document.getElementById(expando); // Cleanup docElem.removeChild(div); return pass; }); // If slice is not available, provide a backup try{ slice.call(docElem.childNodes, 0)[0].nodeType; } catch(e) { slice = function(i){ var elem,results = []; for(;(elem = this[i]);i++){ results.push(elem); }; return results; }; }; function Sizzle(selector, context, results, seed){ results = results || []; context = context || document; var match,elem,xml,m,nodeType = context.nodeType; if(!selector || typeof selector !== "string"){ return results; }; if(nodeType !== 1 && nodeType !== 9){ return []; }; xml = isXML(context); if(!xml && !seed){ if((match = rquickExpr.exec(selector))){ // Speed-up: Sizzle("#ID") if((m = match[1])){ if(nodeType === 9){ elem = context.getElementById(m); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if(elem && elem.parentNode){ // Handle the case where IE, Opera, and Webkit return items // by name instead of ID if(elem.id === m){ results.push(elem); return results; }; } else { return results; }; } else { // Context is not a document if(context.ownerDocument && (elem = context.ownerDocument.getElementById(m)) && contains(context, elem) && elem.id === m){ results.push(elem); return results; }; }; } else if(match[2]){ push.apply(results, slice.call(context.getElementsByTagName(selector), 0)); return results; } else if((m = match[3]) && assertUsableClassName && context.getElementsByClassName){ push.apply(results, slice.call(context.getElementsByClassName(m), 0)); return results; };; }; }; // All others return select(selector.replace(rtrim, "$1"), context, results, seed, xml); }; Sizzle.matches = function(expr, elements){ return Sizzle(expr, null, null, elements); }; Sizzle.matchesSelector = function(elem, expr){ return Sizzle(expr, null, null, [elem]).length > 0; }; // Returns a function to use in pseudos for input types function createInputPseudo(type){ return function(elem){ var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; }; // Returns a function to use in pseudos for buttons function createButtonPseudo(type){ return function(elem){ var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && elem.type === type; }; }; // Returns a function to use in pseudos for positionals function createPositionalPseudo(fn){ return markFunction(function(argument){ argument = +argument; return markFunction(function(seed, matches){ var j,matchIndexes = fn([], seed.length, argument),i = matchIndexes.length; // Match elements found at the specified indexes while(i--){ if(seed[(j = matchIndexes[i])]){ seed[j] = !(matches[j] = seed[j]); }; }; }); }); }; /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function(elem){ var node,ret = "",i = 0,nodeType = elem.nodeType; if(nodeType){ if(nodeType === 1 || nodeType === 9 || nodeType === 11){ // Use textContent for elements // innerText usage removed for consistency of new lines (see #11153) if(typeof elem.textContent === "string"){ return elem.textContent; } else { // Traverse its children for(elem = elem.firstChild;elem;elem = elem.nextSibling){ ret += getText(elem); }; }; } else if(nodeType === 3 || nodeType === 4){ return elem.nodeValue; }; } else { // If no nodeType, this is expected to be an array for(;(node = elem[i]);i++){ // Do not traverse comment nodes ret += getText(node); }; }; return ret; }; isXML = Sizzle.isXML = function(elem){ // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = elem && (elem.ownerDocument || elem).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; // Element contains another contains = Sizzle.contains = docElem.contains ? function(a, b){ var adown = a.nodeType === 9 ? a.documentElement : a,bup = b && b.parentNode; return a === bup || !!(bup && bup.nodeType === 1 && adown.contains && adown.contains(bup)); } : docElem.compareDocumentPosition ? function(a, b){ return b && !!(a.compareDocumentPosition(b) & 16); } : function(a, b){ while((b = b.parentNode)){ if(b === a){ return true; }; }; return false; }; Sizzle.attr = function(elem, name){ var val,xml = isXML(elem); if(!xml){ name = name.toLowerCase(); }; if((val = Expr.attrHandle[name])){ return val(elem); }; if(xml || assertAttributes){ return elem.getAttribute(name); }; val = elem.getAttributeNode(name); return val ? typeof elem[name] === "boolean" ? elem[name] ? name : null : val.specified ? val.value : null : null; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength : 50, createPseudo : markFunction, match : matchExpr, // IE6/7 return a modified href attrHandle : assertHrefNotNormalized ? { } : { "href" : function(elem){ return elem.getAttribute("href", 2); }, "type" : function(elem){ return elem.getAttribute("type"); } }, find : { "ID" : assertGetIdNotName ? function(id, context, xml){ if(typeof context.getElementById !== strundefined && !xml){ var m = context.getElementById(id); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [m] : []; }; } : function(id, context, xml){ if(typeof context.getElementById !== strundefined && !xml){ var m = context.getElementById(id); return m ? m.id === id || typeof m.getAttributeNode !== strundefined && m.getAttributeNode("id").value === id ? [m] : undefined : []; }; }, "TAG" : assertTagNameNoComments ? function(tag, context){ if(typeof context.getElementsByTagName !== strundefined){ return context.getElementsByTagName(tag); }; } : function(tag, context){ var results = context.getElementsByTagName(tag); // Filter out possible comments if(tag === "*"){ var elem,tmp = [],i = 0; for(;(elem = results[i]);i++){ if(elem.nodeType === 1){ tmp.push(elem); }; }; return tmp; }; return results; }, "NAME" : assertUsableName && function(tag, context){ if(typeof context.getElementsByName !== strundefined){ return context.getElementsByName(name); }; }, "CLASS" : assertUsableClassName && function(className, context, xml){ if(typeof context.getElementsByClassName !== strundefined && !xml){ return context.getElementsByClassName(className); }; } }, relative : { ">" : { dir : "parentNode", first : true }, " " : { dir : "parentNode" }, "+" : { dir : "previousSibling", first : true }, "~" : { dir : "previousSibling" } }, preFilter : { "ATTR" : function(match){ match[1] = match[1].replace(rbackslash, ""); // Move the given value to match[3] whether quoted or unquoted match[3] = (match[4] || match[5] || "").replace(rbackslash, ""); if(match[2] === "~="){ match[3] = " " + match[3] + " "; }; return match.slice(0, 4); }, "CHILD" : function(match){ /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 3 xn-component of xn+y argument ([+-]?\d*n|) 4 sign of xn-component 5 x of xn-component 6 sign of y-component 7 y of y-component */ match[1] = match[1].toLowerCase(); if(match[1] === "nth"){ // nth-child requires argument if(!match[2]){ Sizzle.error(match[0]); }; // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[3] = +(match[3] ? match[4] + (match[5] || 1) : 2 * (match[2] === "even" || match[2] === "odd")); match[4] = +((match[6] + match[7]) || match[2] === "odd"); } else if(match[2]){ Sizzle.error(match[0]); }; return match; }, "PSEUDO" : function(match){ var unquoted,excess; if(matchExpr["CHILD"].test(match[0])){ return null; }; if(match[3]){ match[2] = match[3]; } else if((unquoted = match[4])){ // Only check arguments that contain a pseudo if(rpseudo.test(unquoted) && // Get excess from tokenize (recursively) (excess = tokenize(unquoted, true)) && // advance to the next closing parenthesis (excess = unquoted.indexOf(")", unquoted.length - excess) - unquoted.length)){ // excess is a negative index unquoted = unquoted.slice(0, excess); match[0] = match[0].slice(0, excess); }; match[2] = unquoted; }; // Return only captures needed by the pseudo filter method (type and argument) return match.slice(0, 3); } }, filter : { "ID" : assertGetIdNotName ? function(id){ id = id.replace(rbackslash, ""); return function(elem){ return elem.getAttribute("id") === id; }; } : function(id){ id = id.replace(rbackslash, ""); return function(elem){ var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); return node && node.value === id; }; }, "TAG" : function(nodeName){ if(nodeName === "*"){ return function(){ return true; }; }; nodeName = nodeName.replace(rbackslash, "").toLowerCase(); return function(elem){ return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS" : function(className){ var pattern = classCache[expando][className]; if(!pattern){ pattern = classCache(className, new RegExp("(^|" + whitespace + ")" + className + "(" + whitespace + "|$)")); }; return function(elem){ return pattern.test(elem.className || (typeof elem.getAttribute !== strundefined && elem.getAttribute("class")) || ""); }; }, "ATTR" : function(name, operator, check){ return function(elem, context){ var result = Sizzle.attr(elem, name); if(result == null){ return operator === "!="; }; if(!operator){ return true; }; result += ""; return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf(check) === 0 : operator === "*=" ? check && result.indexOf(check) > -1 : operator === "$=" ? check && result.substr(result.length - check.length) === check : operator === "~=" ? (" " + result + " ").indexOf(check) > -1 : operator === "|=" ? result === check || result.substr(0, check.length + 1) === check + "-" : false; }; }, "CHILD" : function(type, argument, first, last){ if(type === "nth"){ return function(elem){ var node,diff,parent = elem.parentNode; if(first === 1 && last === 0){ return true; }; if(parent){ diff = 0; for(node = parent.firstChild;node;node = node.nextSibling){ if(node.nodeType === 1){ diff++; if(elem === node){ break; }; }; }; }; // Incorporate the offset (or cast to NaN), then check against cycle size diff -= last; return diff === first || (diff % first === 0 && diff / first >= 0); }; }; return function(elem){ var 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;/* falls through */ case "last": while((node = node.nextSibling)){ if(node.nodeType === 1){ return false; }; }; return true;}; }; }, "PSEUDO" : function(pseudo, argument){ // pseudo-class names are case-insensitive // http://www.w3.org/TR/selectors/#pseudo-classes // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters // Remember that setFilters inherits from pseudos var args,fn = Expr.pseudos[pseudo] || Expr.setFilters[pseudo.toLowerCase()] || Sizzle.error("unsupported pseudo: " + pseudo); // The user may use createPseudo to indicate that // arguments are needed to create the filter function // just as Sizzle does if(fn[expando]){ return fn(argument); }; // But maintain support for old signatures if(fn.length > 1){ args = [pseudo, pseudo, "", argument]; return Expr.setFilters.hasOwnProperty(pseudo.toLowerCase()) ? markFunction(function(seed, matches){ var idx,matched = fn(seed, argument),i = matched.length; while(i--){ idx = indexOf.call(seed, matched[i]); seed[idx] = !(matches[idx] = matched[i]); }; }) : function(elem){ return fn(elem, 0, args); }; }; return fn; } }, pseudos : { "not" : markFunction(function(selector){ // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var input = [],results = [],matcher = compile(selector.replace(rtrim, "$1")); return matcher[expando] ? markFunction(function(seed, matches, context, xml){ var elem,unmatched = matcher(seed, null, xml, []),i = seed.length; // Match elements unmatched by `matcher` while(i--){ if((elem = unmatched[i])){ seed[i] = !(matches[i] = elem); }; }; }) : function(elem, context, xml){ input[0] = elem; matcher(input, null, xml, results); return !results.pop(); }; }), "has" : markFunction(function(selector){ return function(elem){ return Sizzle(selector, elem).length > 0; }; }), "contains" : markFunction(function(text){ return function(elem){ return (elem.textContent || elem.innerText || getText(elem)).indexOf(text) > -1; }; }), "enabled" : function(elem){ return elem.disabled === false; }, "disabled" : function(elem){ return elem.disabled === true; }, "checked" : function(elem){ // In CSS3, :checked should return both checked and selected elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked var nodeName = elem.nodeName.toLowerCase(); return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); }, "selected" : function(elem){ // Accessing this property makes selected-by-default // options in Safari work properly if(elem.parentNode){ elem.parentNode.selectedIndex; }; return elem.selected === true; }, "parent" : function(elem){ return !Expr.pseudos["empty"](elem); }, "empty" : function(elem){ // http://www.w3.org/TR/selectors/#empty-pseudo // :empty is only affected by element nodes and content nodes(including text(3), cdata(4)), // not comment, processing instructions, or others // Thanks to Diego Perini for the nodeName shortcut // Greater than "@" means alpha characters (specifically not starting with "#" or "?") var nodeType; elem = elem.firstChild; while(elem){ if(elem.nodeName > "@" || (nodeType = elem.nodeType) === 3 || nodeType === 4){ return false; }; elem = elem.nextSibling; }; return true; }, "header" : function(elem){ return rheader.test(elem.nodeName); }, "text" : function(elem){ var type,attr; // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) // use getAttribute instead to test this case return elem.nodeName.toLowerCase() === "input" && (type = elem.type) === "text" && ((attr = elem.getAttribute("type")) == null || attr.toLowerCase() === type); }, // Input types "radio" : createInputPseudo("radio"), "checkbox" : createInputPseudo("checkbox"), "file" : createInputPseudo("file"), "password" : createInputPseudo("password"), "image" : createInputPseudo("image"), "submit" : createButtonPseudo("submit"), "reset" : createButtonPseudo("reset"), "button" : function(elem){ var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "input" : function(elem){ return rinputs.test(elem.nodeName); }, "focus" : function(elem){ var doc = elem.ownerDocument; return elem === doc.activeElement && (!doc.hasFocus || doc.hasFocus()) && !!(elem.type || elem.href); }, "active" : function(elem){ return elem === elem.ownerDocument.activeElement; }, // Positional types "first" : createPositionalPseudo(function(matchIndexes, length, argument){ return [0]; }), "last" : createPositionalPseudo(function(matchIndexes, length, argument){ return [length - 1]; }), "eq" : createPositionalPseudo(function(matchIndexes, length, argument){ return [argument < 0 ? argument + length : argument]; }), "even" : createPositionalPseudo(function(matchIndexes, length, argument){ for(var i = 0;i < length;i += 2){ matchIndexes.push(i); }; return matchIndexes; }), "odd" : createPositionalPseudo(function(matchIndexes, length, argument){ for(var i = 1;i < length;i += 2){ matchIndexes.push(i); }; return matchIndexes; }), "lt" : createPositionalPseudo(function(matchIndexes, length, argument){ for(var i = argument < 0 ? argument + length : argument;--i >= 0;){ matchIndexes.push(i); }; return matchIndexes; }), "gt" : createPositionalPseudo(function(matchIndexes, length, argument){ for(var i = argument < 0 ? argument + length : argument;++i < length;){ matchIndexes.push(i); }; return matchIndexes; }) } }; function siblingCheck(a, b, ret){ if(a === b){ return ret; }; var cur = a.nextSibling; while(cur){ if(cur === b){ return -1; }; cur = cur.nextSibling; }; return 1; }; sortOrder = docElem.compareDocumentPosition ? function(a, b){ if(a === b){ hasDuplicate = true; return 0; }; return (!a.compareDocumentPosition || !b.compareDocumentPosition ? a.compareDocumentPosition : a.compareDocumentPosition(b) & 4) ? -1 : 1; } : function(a, b){ // The nodes are identical, we can exit early if(a === b){ hasDuplicate = true; return 0; } 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); } 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); }; // Always assume the presence of duplicates if sort doesn't // pass them to our comparison function (as in Google Chrome). [0, 0].sort(sortOrder); baseHasDuplicate = !hasDuplicate; // Document sorting and removing duplicates Sizzle.uniqueSort = function(results){ var elem,i = 1; hasDuplicate = baseHasDuplicate; results.sort(sortOrder); if(hasDuplicate){ for(;(elem = results[i]);i++){ if(elem === results[i - 1]){ results.splice(i--, 1); }; }; }; return results; }; Sizzle.error = function(msg){ throw new Error("Syntax error, unrecognized expression: " + msg); }; function tokenize(selector, parseOnly){ var matched,match,tokens,type,soFar,groups,preFilters,cached = tokenCache[expando][selector]; if(cached){ return parseOnly ? 0 : cached.slice(0); }; soFar = selector; groups = []; preFilters = Expr.preFilter; while(soFar){ // Comma and first run if(!matched || (match = rcomma.exec(soFar))){ if(match){ soFar = soFar.slice(match[0].length); }; groups.push(tokens = []); }; matched = false; // Combinators if((match = rcombinators.exec(soFar))){ tokens.push(matched = new Token(match.shift())); soFar = soFar.slice(matched.length); // Cast descendant combinators to space matched.type = match[0].replace(rtrim, " "); }; // Filters for(type in Expr.filter){ if((match = matchExpr[type].exec(soFar)) && (!preFilters[type] || // The last two arguments here are (context, xml) for backCompat (match = preFilters[type](match, document, true)))){ tokens.push(matched = new Token(match.shift())); soFar = soFar.slice(matched.length); matched.type = type; matched.matches = match; }; }; if(!matched){ break; }; }; // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error(selector) : // Cache the tokens tokenCache(selector, groups).slice(0); }; function addCombinator(matcher, combinator, base){ var dir = combinator.dir,checkNonElements = base && combinator.dir === "parentNode",doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function(elem, context, xml){ while((elem = elem[dir])){ if(checkNonElements || elem.nodeType === 1){ return matcher(elem, context, xml); }; }; } : // Check against all ancestor/preceding elements function(elem, context, xml){ // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching if(!xml){ var cache,dirkey = dirruns + " " + doneName + " ",cachedkey = dirkey + cachedruns; while((elem = elem[dir])){ if(checkNonElements || elem.nodeType === 1){ if((cache = elem[expando]) === cachedkey){ return elem.sizset; } else if(typeof cache === "string" && cache.indexOf(dirkey) === 0){ if(elem.sizset){ return elem; }; } else { elem[expando] = cachedkey; if(matcher(elem, context, xml)){ elem.sizset = true; return elem; }; elem.sizset = false; }; }; }; } else { while((elem = elem[dir])){ if(checkNonElements || elem.nodeType === 1){ if(matcher(elem, context, xml)){ return elem; }; }; }; }; }; }; function elementMatcher(matchers){ return matchers.length > 1 ? function(elem, context, xml){ var i = matchers.length; while(i--){ if(!matchers[i](elem, context, xml)){ return false; }; }; return true; } : matchers[0]; }; function condense(unmatched, map, filter, context, xml){ var elem,newUnmatched = [],i = 0,len = unmatched.length,mapped = map != null; for(;i < len;i++){ if((elem = unmatched[i])){ if(!filter || filter(elem, context, xml)){ newUnmatched.push(elem); if(mapped){ map.push(i); }; }; }; }; return newUnmatched; }; function setMatcher(preFilter, selector, matcher, postFilter, postFinder, postSelector){ if(postFilter && !postFilter[expando]){ postFilter = setMatcher(postFilter); }; if(postFinder && !postFinder[expando]){ postFinder = setMatcher(postFinder, postSelector); }; return markFunction(function(seed, results, context, xml){ // Positional selectors apply to seed elements, so it is invalid to follow them with relative ones if(seed && postFinder){ return; }; var i,elem,postFilterIn,preMap = [],postMap = [],preexisting = results.length,// Get initial elements from seed or context elems = seed || multipleContexts(selector || "*", context.nodeType ? [context] : context, [], seed),// Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && (seed || !selector) ? condense(elems, preMap, preFilter, context, xml) : elems,matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, postFinder || (seed ? preFilter : preexisting || postFilter) ? // ...intermediate processing is necessary [] : // ...otherwise use results directly results : matcherIn; // Find primary matches if(matcher){ matcher(matcherIn, matcherOut, context, xml); }; // Apply postFilter if(postFilter){ postFilterIn = condense(matcherOut, postMap); postFilter(postFilterIn, [], context, xml); // Un-match failing elements by moving them back to matcherIn i = postFilterIn.length; while(i--){ if((elem = postFilterIn[i])){ matcherOut[postMap[i]] = !(matcherIn[postMap[i]] = elem); }; }; }; // Keep seed and results synchronized if(seed){ // Ignore postFinder because it can't coexist with seed i = preFilter && matcherOut.length; while(i--){ if((elem = matcherOut[i])){ seed[preMap[i]] = !(results[preMap[i]] = elem); }; }; } else { matcherOut = condense(matcherOut === results ? matcherOut.splice(preexisting, matcherOut.length) : matcherOut); if(postFinder){ postFinder(null, results, matcherOut, xml); } else { push.apply(results, matcherOut); }; }; }); }; function matcherFromTokens(tokens){ var checkContext,matcher,j,len = tokens.length,leadingRelative = Expr.relative[tokens[0].type],implicitRelative = leadingRelative || Expr.relative[" "],i = leadingRelative ? 1 : 0,// The foundational matcher ensures that elements are reachable from top-level context(s) matchContext = addCombinator(function(elem){ return elem === checkContext; }, implicitRelative, true),matchAnyContext = addCombinator(function(elem){ return indexOf.call(checkContext, elem) > -1; }, implicitRelative, true),matchers = [function(elem, context, xml){ return (!leadingRelative && (xml || context !== outermostContext)) || ((checkContext = context).nodeType ? matchContext(elem, context, xml) : matchAnyContext(elem, context, xml)); }]; for(;i < len;i++){ if((matcher = Expr.relative[tokens[i].type])){ matchers = [addCombinator(elementMatcher(matchers), matcher)]; } else { // The concatenated values are (context, xml) for backCompat matcher = Expr.filter[tokens[i].type].apply(null, tokens[i].matches); // Return special upon seeing a positional matcher if(matcher[expando]){ // Find the next relative operator (if any) for proper handling j = ++i; for(;j < len;j++){ if(Expr.relative[tokens[j].type]){ break; }; }; return setMatcher(i > 1 && elementMatcher(matchers), i > 1 && tokens.slice(0, i - 1).join("").replace(rtrim, "$1"), matcher, i < j && matcherFromTokens(tokens.slice(i, j)), j < len && matcherFromTokens((tokens = tokens.slice(j))), j < len && tokens.join("")); }; matchers.push(matcher); }; }; return elementMatcher(matchers); }; function matcherFromGroupMatchers(elementMatchers, setMatchers){ var bySet = setMatchers.length > 0,byElement = elementMatchers.length > 0,superMatcher = function(seed, context, xml, results, expandContext){ var elem,j,matcher,setMatched = [],matchedCount = 0,i = "0",unmatched = seed && [],outermost = expandContext != null,contextBackup = outermostContext,// We must always have either seed elements or context elems = seed || byElement && Expr.find["TAG"]("*", expandContext && context.parentNode || context),// Nested matchers should use non-integer dirruns dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.E); if(outermost){ outermostContext = context !== document && context; cachedruns = superMatcher.el; }; // Add elements passing elementMatchers directly to results for(;(elem = elems[i]) != null;i++){ if(byElement && elem){ for(j = 0;(matcher = elementMatchers[j]);j++){ if(matcher(elem, context, xml)){ results.push(elem); break; }; }; if(outermost){ dirruns = dirrunsUnique; cachedruns = ++superMatcher.el; }; }; // Track unmatched elements for set filters if(bySet){ // They will have gone through all possible matchers if((elem = !matcher && elem)){ matchedCount--; }; // Lengthen the array for every element, matched or not if(seed){ unmatched.push(elem); }; }; }; // Apply set filters to unmatched elements matchedCount += i; if(bySet && i !== matchedCount){ for(j = 0;(matcher = setMatchers[j]);j++){ matcher(unmatched, setMatched, context, xml); }; if(seed){ // Reintegrate element matches to eliminate the need for sorting if(matchedCount > 0){ while(i--){ if(!(unmatched[i] || setMatched[i])){ setMatched[i] = pop.call(results); }; }; }; // Discard index placeholder values to get only actual matches setMatched = condense(setMatched); }; // Add matches to results push.apply(results, setMatched); // Seedless set matches succeeding multiple successful matchers stipulate sorting if(outermost && !seed && setMatched.length > 0 && (matchedCount + setMatchers.length) > 1){ Sizzle.uniqueSort(results); }; }; // Override manipulation of globals by nested matchers if(outermost){ dirruns = dirrunsUnique; outermostContext = contextBackup; }; return unmatched; }; superMatcher.el = 0; return bySet ? markFunction(superMatcher) : superMatcher; }; compile = Sizzle.compile = function(selector, group){ var i,setMatchers = [],elementMatchers = [],cached = compilerCache[expando][selector]; if(!cached){ // Generate a function of recursive functions that can be used to check each element if(!group){ group = tokenize(selector); }; i = group.length; while(i--){ cached = matcherFromTokens(group[i]); if(cached[expando]){ setMatchers.push(cached); } else { elementMatchers.push(cached); }; }; // Cache the compiled function cached = compilerCache(selector, matcherFromGroupMatchers(elementMatchers, setMatchers)); }; return cached; }; function multipleContexts(selector, contexts, results, seed){ var i = 0,len = contexts.length; for(;i < len;i++){ Sizzle(selector, contexts[i], results, seed); }; return results; }; function select(selector, context, results, seed, xml){ var i,tokens,token,type,find,match = tokenize(selector),j = match.length; if(!seed){ // Try to minimize operations if there is only one group if(match.length === 1){ // Take a shortcut and set the context if the root selector is an ID tokens = match[0] = match[0].slice(0); if(tokens.length > 2 && (token = tokens[0]).type === "ID" && context.nodeType === 9 && !xml && Expr.relative[tokens[1].type]){ context = Expr.find["ID"](token.matches[0].replace(rbackslash, ""), context, xml)[0]; if(!context){ return results; }; selector = selector.slice(tokens.shift().length); }; // Fetch a seed set for right-to-left matching for(i = matchExpr["POS"].test(selector) ? -1 : tokens.length - 1;i >= 0;i--){ token = tokens[i]; // Abort if we hit a combinator if(Expr.relative[(type = token.type)]){ break; }; if((find = Expr.find[type])){ // Search, expanding context for leading sibling combinators if((seed = find(token.matches[0].replace(rbackslash, ""), rsibling.test(tokens[0].type) && context.parentNode || context, xml))){ // If seed is empty or no tokens remain, we can return early tokens.splice(i, 1); selector = seed.length && tokens.join(""); if(!selector){ push.apply(results, slice.call(seed, 0)); return results; }; break; }; }; }; }; }; // Compile and execute a filtering function // Provide `match` to avoid retokenization if we modified the selector above compile(selector, match)(seed, context, xml, results, rsibling.test(selector)); return results; }; if(document.querySelectorAll){ (function(){ var disconnectedMatch,oldSelect = select,rescape = /'|\\/g,rattributeQuotes = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,// qSa(:focus) reports false when true (Chrome 21), // A support test would require too much code (would include document ready) rbuggyQSA = [":focus"],// matchesSelector(:focus) reports false when true (Chrome 21), // matchesSelector(:active) reports false when true (IE9/Opera 11.5) // A support test would require too much code (would include document ready) // just skip matchesSelector for :active rbuggyMatches = [":active", ":focus"],matches = docElem.matchesSelector || docElem.mozMatchesSelector || docElem.webkitMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector; // Build QSA regex // Regex strategy adopted from Diego Perini assert(function(div){ // Select is set to empty string on purpose // This is to test IE's treatment of not explictly // setting a boolean content attribute, // since its presence should be enough // http://bugs.jquery.com/ticket/12359 div.innerHTML = "<select><option selected=''></option></select>"; // IE8 - Some boolean attributes are not treated correctly if(!div.querySelectorAll("[selected]").length){ rbuggyQSA.push("\\[" + whitespace + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)"); }; // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here (do not put tests after this one) if(!div.querySelectorAll(":checked").length){ rbuggyQSA.push(":checked"); }; }); assert(function(div){ // Opera 10-12/IE9 - ^= $= *= and empty values // Should not select anything div.innerHTML = "<p test=''></p>"; if(div.querySelectorAll("[test^='']").length){ rbuggyQSA.push("[*^$]=" + whitespace + "*(?:\"\"|'')"); }; // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here (do not put tests after this one) div.innerHTML = "<input type='hidden'/>"; if(!div.querySelectorAll(":enabled").length){ rbuggyQSA.push(":enabled", ":disabled"); }; }); // rbuggyQSA always contains :focus, so no need for a length check rbuggyQSA = /* rbuggyQSA.length && */ new RegExp(rbuggyQSA.join("|")); select = function(selector, context, results, seed, xml){ // Only use querySelectorAll when not filtering, // when this is not xml, // and when no QSA bugs apply if(!seed && !xml && (!rbuggyQSA || !rbuggyQSA.test(selector))){ var groups,i,old = true,nid = expando,newContext = context,newSelector = context.nodeType === 9 && selector; // qSA works strangely on Element-rooted queries // We can work around this by specifying an extra ID on the root // and working up from there (Thanks to Andrew Dupont for the technique) // IE 8 doesn't work on object elements if(context.nodeType === 1 && context.nodeName.toLowerCase() !== "object"){ groups = tokenize(selector); if((old = context.getAttribute("id"))){ nid = old.replace(rescape, "\\$&"); } else { context.setAttribute("id", nid); }; nid = "[id='" + nid + "'] "; i = groups.length; while(i--){ groups[i] = nid + groups[i].join(""); }; newContext = rsibling.test(selector) && context.parentNode || context; newSelector = groups.join(","); }; if(newSelector){ try{ push.apply(results, slice.call(newContext.querySelectorAll(newSelector), 0)); return results; } catch(qsaError) { }finally{ if(!old){ context.removeAttribute("id"); }; }; }; }; return oldSelect(selector, context, results, seed, xml); }; if(matches){ assert(function(div){ // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) disconnectedMatch = matches.call(div, "div"); // This should fail with an exception // Gecko does not error, returns false instead try{ matches.call(div, "[test!='']:sizzle"); rbuggyMatches.push("!=", pseudos); } catch(e) { }; }); // rbuggyMatches always contains :active and :focus, so no need for a length check rbuggyMatches = /* rbuggyMatches.length && */ new RegExp(rbuggyMatches.join("|")); Sizzle.matchesSelector = function(elem, expr){ // Make sure that attribute selectors are quoted expr = expr.replace(rattributeQuotes, "='$1']"); // rbuggyMatches always contains :active, so no need for an existence check if(!isXML(elem) && !rbuggyMatches.test(expr) && (!rbuggyQSA || !rbuggyQSA.test(expr))){ try{ var ret = matches.call(elem, expr); // IE 9's matchesSelector returns false on disconnected nodes if(ret || disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11){ return ret; }; } catch(e) { }; }; return Sizzle(expr, null, null, [elem]).length > 0; }; }; })(); }; // Deprecated Expr.pseudos["nth"] = Expr.pseudos["eq"]; // Back-compat function setFilters(){ }; Expr.filters = setFilters.prototype = Expr.pseudos; Expr.setFilters = new setFilters(); // EXPOSE qooxdoo variant qx.bom.Selector.query = function(selector, context){ return Sizzle(selector, context); }; qx.bom.Selector.matches = function(selector, set){ return Sizzle(selector, null, null, set); }; })(window); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2007-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Fabian Jakobs (fjakobs) ************************************************************************ */ /** * Utility class with type check for all native JavaScript data types. */ qx.Bootstrap.define("qx.lang.Type", { statics : { /** * Get the internal class of the value. See * http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/ * for details. * * @signature function(value) * @param value {var} value to get the class for * @return {String} the internal class of the value */ getClass : qx.Bootstrap.getClass, /** * Whether the value is a string. * * @signature function(value) * @param value {var} Value to check. * @return {Boolean} Whether the value is a string. */ isString : qx.Bootstrap.isString, /** * Whether the value is an array. * * @signature function(value) * @param value {var} Value to check. * @return {Boolean} Whether the value is an array. */ isArray : qx.Bootstrap.isArray, /** * Whether the value is an object. Note that built-in types like Window are * not reported to be objects. * * @signature function(value) * @param value {var} Value to check. * @return {Boolean} Whether the value is an object. */ isObject : qx.Bootstrap.isObject, /** * Whether the value is a function. * * @signature function(value) * @param value {var} Value to check. * @return {Boolean} Whether the value is a function. */ isFunction : qx.Bootstrap.isFunction, /** * Whether the value is a regular expression. * * @param value {var} Value to check. * @return {Boolean} Whether the value is a regular expression. */ isRegExp : function(value){ return this.getClass(value) == "RegExp"; }, /** * Whether the value is a number. * * @param value {var} Value to check. * @return {Boolean} Whether the value is a number. */ isNumber : function(value){ // Added "value !== null" because IE throws an exception "Object expected" // by executing "value instanceof Number" if value is a DOM element that // doesn't exist. It seems that there is an internal different between a // JavaScript null and a null returned from calling DOM. // e.q. by document.getElementById("ReturnedNull"). return (value !== null && (this.getClass(value) == "Number" || value instanceof Number)); }, /** * Whether the value is a boolean. * * @param value {var} Value to check. * @return {Boolean} Whether the value is a boolean. */ isBoolean : function(value){ // Added "value !== null" because IE throws an exception "Object expected" // by executing "value instanceof Boolean" if value is a DOM element that // doesn't exist. It seems that there is an internal different between a // JavaScript null and a null returned from calling DOM. // e.q. by document.getElementById("ReturnedNull"). return (value !== null && (this.getClass(value) == "Boolean" || value instanceof Boolean)); }, /** * Whether the value is a date. * * @param value {var} Value to check. * @return {Boolean} Whether the value is a date. */ isDate : function(value){ // Added "value !== null" because IE throws an exception "Object expected" // by executing "value instanceof Date" if value is a DOM element that // doesn't exist. It seems that there is an internal different between a // JavaScript null and a null returned from calling DOM. // e.q. by document.getElementById("ReturnedNull"). return (value !== null && (this.getClass(value) == "Date" || value instanceof Date)); }, /** * Whether the value is a Error. * * @param value {var} Value to check. * @return {Boolean} Whether the value is a Error. */ isError : function(value){ // Added "value !== null" because IE throws an exception "Object expected" // by executing "value instanceof Error" if value is a DOM element that // doesn't exist. It seems that there is an internal different between a // JavaScript null and a null returned from calling DOM. // e.q. by document.getElementById("ReturnedNull"). return (value !== null && (this.getClass(value) == "Error" || value instanceof Error)); } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /** * This module offers a cross browser storage implementation. The API is aligned * with the API of the HTML web storage (http://www.w3.org/TR/webstorage/) which is * also the preferred implementation used. As fallback for IE < 8, we use user data. * If both techniques are unsupported, we supply a in memory storage, which is * of course, not persistent. */ qx.Bootstrap.define("qx.module.Storage", { statics : { /** * Store an item in the storage. * * @attachStatic {qxWeb, localStorage.setItem} * @param key {String} The identifier key. * @param value {var} The data, which will be stored as JSON. */ setLocalItem : function(key, value){ qx.bom.Storage.getLocal().setItem(key, value); }, /** * Returns the stored item. * * @attachStatic {qxWeb, localStorage.getItem} * @param key {String} The identifier to get the data. * @return {var} The stored data. */ getLocalItem : function(key){ return qx.bom.Storage.getLocal().getItem(key); }, /** * Removes an item form the storage. * @attachStatic {qxWeb, localStorage.removeItem} * @param key {String} The identifier. */ removeLocalItem : function(key){ qx.bom.Storage.getLocal().removeItem(key); }, /** * Returns the amount of key-value pairs stored. * @attachStatic {qxWeb, localStorage.getLength} * @return {Number} The length of the storage. */ getLocalLength : function(){ return qx.bom.Storage.getLocal().getLength(); }, /** * Returns the named key at the given index. * @attachStatic {qxWeb, localStorage.getKey} * @param index {Number} The index in the storage. * @return {String} The key stored at the given index. */ getLocalKey : function(index){ return qx.bom.Storage.getLocal().getKey(index); }, /** * Deletes every stored item in the storage. * @attachStatic {qxWeb, localStorage.clear} */ clearLocal : function(){ qx.bom.Storage.getLocal().clear(); }, /** * Helper to access every stored item. * * @attachStatic {qxWeb, localStorage.forEach} * @param callback {Function} A function which will be called for every item. * The function will have two arguments, first the key and second the value * of the stored data. * @param scope {var} The scope of the function. */ forEachLocal : function(callback, scope){ qx.bom.Storage.getLocal().forEach(callback, scope); }, /** * Store an item in the storage. * * @attachStatic {qxWeb, sessionStorage.setItem} * @param key {String} The identifier key. * @param value {var} The data, which will be stored as JSON. */ setSessionItem : function(key, value){ qx.bom.Storage.getSession().setItem(key, value); }, /** * Returns the stored item. * * @attachStatic {qxWeb, sessionStorage.getItem} * @param key {String} The identifier to get the data. * @return {var} The stored data. */ getSessionItem : function(key){ return qx.bom.Storage.getSession().getItem(key); }, /** * Removes an item form the storage. * @attachStatic {qxWeb, sessionStorage.removeItem} * @param key {String} The identifier. */ removeSessionItem : function(key){ qx.bom.Storage.getSession().removeItem(key); }, /** * Returns the amount of key-value pairs stored. * @attachStatic {qxWeb, sessionStorage.getLength} * @return {Number} The length of the storage. */ getSessionLength : function(){ return qx.bom.Storage.getSession().getLength(); }, /** * Returns the named key at the given index. * @attachStatic {qxWeb, sessionStorage.getKey} * @param index {Number} The index in the storage. * @return {String} The key stored at the given index. */ getSessionKey : function(index){ return qx.bom.Storage.getSession().getKey(index); }, /** * Deletes every stored item in the storage. * @attachStatic {qxWeb, sessionStorage.clear} */ clearSession : function(){ qx.bom.Storage.getSession().clear(); }, /** * Helper to access every stored item. * * @attachStatic {qxWeb, sessionStorage.forEach} * @param callback {Function} A function which will be called for every item. * The function will have two arguments, first the key and second the value * of the stored data. * @param scope {var} The scope of the function. */ forEachSession : function(callback, scope){ qx.bom.Storage.getSession().forEach(callback, scope); } }, defer : function(statics){ qxWeb.$attachStatic({ "localStorage" : { setItem : statics.setLocalItem, getItem : statics.getLocalItem, removeItem : statics.removeLocalItem, getLength : statics.getLocalLength, getKey : statics.getLocalKey, clear : statics.clearLocal, forEach : statics.forEachLocal }, "sessionStorage" : { setItem : statics.setSessionItem, getItem : statics.getSessionItem, removeItem : statics.removeSessionItem, getLength : statics.getSessionLength, getKey : statics.getSessionKey, clear : statics.clearSession, forEach : statics.forEachSession } }); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2011 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /** * This is a cross browser storage implementation. The API is aligned with the * API of the HTML web storage (http://www.w3.org/TR/webstorage/) which is also * the preferred implementation used. As fallback for IE < 8, we use user data. * If both techniques are unsupported, we supply a in memory storage, which is * of course, not persistent. */ qx.Bootstrap.define("qx.bom.Storage", { statics : { __impl : null, /** * Get an instance of a local storage. * @return {qx.bom.storage.Web|qx.bom.storage.UserData|qx.bom.storage.Memory} * An instance of a storage implementation. */ getLocal : function(){ // always use HTML5 web storage if available if(qx.core.Environment.get("html.storage.local")){ return qx.bom.storage.Web.getLocal(); } else if(qx.core.Environment.get("html.storage.userdata")){ // IE <8 fallback // as fallback,use the userdata storage for IE5.5 - 8 return qx.bom.storage.UserData.getLocal(); }; // as last fallback, use a in memory storage (this one is not persistent) return qx.bom.storage.Memory.getLocal(); }, /** * Get an instance of a session storage. * @return {qx.bom.storage.Web|qx.bom.storage.UserData|qx.bom.storage.Memory} * An instance of a storage implementation. */ getSession : function(){ // always use HTML5 web storage if available if(qx.core.Environment.get("html.storage.local")){ return qx.bom.storage.Web.getSession(); } else if(qx.core.Environment.get("html.storage.userdata")){ // IE <8 fallback // as fallback,use the userdata storage for IE5.5 - 8 return qx.bom.storage.UserData.getSession(); }; // as last fallback, use a in memory storage (this one is not persistent) return qx.bom.storage.Memory.getSession(); } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2011 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * Internal class which contains the checks used by {@link qx.core.Environment}. * All checks in here are marked as internal which means you should never use * them directly. * * This class should contain all checks about HTML. * * @internal */ qx.Bootstrap.define("qx.bom.client.Html", { statics : { /** * Whether the client supports Web Workers. * * @internal * @return {Boolean} <code>true</code> if webworkers are supported */ getWebWorker : function(){ return window.Worker != null; }, /** * Whether the client supports File Readers * * @internal * @return {Boolean} <code>true</code> if FileReaders are supported */ getFileReader : function(){ return window.FileReader != null; }, /** * Whether the client supports Geo Location. * * @internal * @return {Boolean} <code>true</code> if geolocation supported */ getGeoLocation : function(){ return navigator.geolocation != null; }, /** * Whether the client supports audio. * * @internal * @return {Boolean} <code>true</code> if audio is supported */ getAudio : function(){ return !!document.createElement('audio').canPlayType; }, /** * Whether the client can play ogg audio format. * * @internal * @return {String} "" or "maybe" or "probably" */ getAudioOgg : function(){ if(!qx.bom.client.Html.getAudio()){ return ""; }; var a = document.createElement("audio"); return a.canPlayType("audio/ogg"); }, /** * Whether the client can play mp3 audio format. * * @internal * @return {String} "" or "maybe" or "probably" */ getAudioMp3 : function(){ if(!qx.bom.client.Html.getAudio()){ return ""; }; var a = document.createElement("audio"); return a.canPlayType("audio/mpeg"); }, /** * Whether the client can play wave audio wave format. * * @internal * @return {String} "" or "maybe" or "probably" */ getAudioWav : function(){ if(!qx.bom.client.Html.getAudio()){ return ""; }; var a = document.createElement("audio"); return a.canPlayType("audio/x-wav"); }, /** * Whether the client can play au audio format. * * @internal * @return {String} "" or "maybe" or "probably" */ getAudioAu : function(){ if(!qx.bom.client.Html.getAudio()){ return ""; }; var a = document.createElement("audio"); return a.canPlayType("audio/basic"); }, /** * Whether the client can play aif audio format. * * @internal * @return {String} "" or "maybe" or "probably" */ getAudioAif : function(){ if(!qx.bom.client.Html.getAudio()){ return ""; }; var a = document.createElement("audio"); return a.canPlayType("audio/x-aiff"); }, /** * Whether the client supports video. * * @internal * @return {Boolean} <code>true</code> if video is supported */ getVideo : function(){ return !!document.createElement('video').canPlayType; }, /** * Whether the client supports ogg video. * * @internal * @return {String} "" or "maybe" or "probably" */ getVideoOgg : function(){ if(!qx.bom.client.Html.getVideo()){ return ""; }; var v = document.createElement("video"); return v.canPlayType('video/ogg; codecs="theora, vorbis"'); }, /** * Whether the client supports mp4 video. * * @internal * @return {String} "" or "maybe" or "probably" */ getVideoH264 : function(){ if(!qx.bom.client.Html.getVideo()){ return ""; }; var v = document.createElement("video"); return v.canPlayType('video/mp4; codecs="avc1.42E01E, mp4a.40.2"'); }, /** * Whether the client supports webm video. * * @internal * @return {String} "" or "maybe" or "probably" */ getVideoWebm : function(){ if(!qx.bom.client.Html.getVideo()){ return ""; }; var v = document.createElement("video"); return v.canPlayType('video/webm; codecs="vp8, vorbis"'); }, /** * Whether the client supports local storage. * * @internal * @return {Boolean} <code>true</code> if local storage is supported */ getLocalStorage : function(){ try{ return window.localStorage != null; } catch(exc) { // Firefox Bug: Local execution of window.sessionStorage throws error // see https://bugzilla.mozilla.org/show_bug.cgi?id=357323 return false; }; }, /** * Whether the client supports session storage. * * @internal * @return {Boolean} <code>true</code> if session storage is supported */ getSessionStorage : function(){ try{ return window.sessionStorage != null; } catch(exc) { // Firefox Bug: Local execution of window.sessionStorage throws error // see https://bugzilla.mozilla.org/show_bug.cgi?id=357323 return false; }; }, /** * Whether the client supports user data to persist data. This is only * relevant for IE < 8. * * @internal * @return {Boolean} <code>true</code> if the user data is supported. */ getUserDataStorage : function(){ var el = document.createElement("div"); el.style["display"] = "none"; document.getElementsByTagName("head")[0].appendChild(el); var supported = false; try{ el.addBehavior("#default#userdata"); el.load("qxtest"); supported = true; } catch(e) { }; document.getElementsByTagName("head")[0].removeChild(el); return supported; }, /** * Whether the browser supports CSS class lists. * https://developer.mozilla.org/en-US/docs/DOM/element.classList * * @internal * @return {Boolean} <code>true</code> if class list is supported. */ getClassList : function(){ return !!(document.documentElement.classList && qx.Bootstrap.getClass(document.documentElement.classList) === "DOMTokenList"); }, /** * Checks if XPath could be used. * * @internal * @return {Boolean} <code>true</code> if xpath is supported. */ getXPath : function(){ return !!document.evaluate; }, /** * Checks if XUL could be used. * * @internal * @return {Boolean} <code>true</code> if XUL is supported. */ getXul : function(){ try{ document.createElementNS("http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul", "label"); return true; } catch(e) { return false; }; }, /** * Checks if SVG could be used * * @internal * @return {Boolean} <code>true</code> if SVG is supported. */ getSvg : function(){ return document.implementation && document.implementation.hasFeature && (document.implementation.hasFeature("org.w3c.dom.svg", "1.0") || document.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); }, /** * Checks if VML is supported * * @internal * @return {Boolean} <code>true</code> if VML is supported. */ getVml : function(){ var el = document.createElement("div"); document.body.appendChild(el); el.innerHTML = '<v:shape id="vml_flag1" adj="1" />'; el.firstChild.style.behavior = "url(#default#VML)"; var hasVml = typeof el.firstChild.adj == "object"; document.body.removeChild(el); return hasVml; }, /** * Checks if canvas could be used * * @internal * @return {Boolean} <code>true</code> if canvas is supported. */ getCanvas : function(){ return !!window.CanvasRenderingContext2D; }, /** * Asynchronous check for using data urls. * * @internal * @param callback {Function} The function which should be executed as * soon as the check is done. */ getDataUrl : function(callback){ var data = new Image(); data.onload = data.onerror = function(){ // wrap that into a timeout because IE might execute it synchronously window.setTimeout(function(){ callback.call(null, (data.width == 1 && data.height == 1)); }, 0); }; data.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw=="; }, /** * Checks if dataset could be used * * @internal * @return {Boolean} <code>true</code> if dataset is supported. */ getDataset : function(){ return !!document.documentElement.dataset; }, /** * Check for element.contains * * @internal * @return {Boolean} <code>true</code> if element.contains is supported */ getContains : function(){ // "object" in IE6/7/8, "function" in IE9 return (typeof document.documentElement.contains !== "undefined"); }, /** * Check for element.compareDocumentPosition * * @internal * @return {Boolean} <code>true</code> if element.compareDocumentPosition is supported */ getCompareDocumentPosition : function(){ return (typeof document.documentElement.compareDocumentPosition === "function"); }, /** * Check for element.textContent. Legacy IEs do not support this, use * innerText instead. * * @internal * @return {Boolean} <code>true</code> if textContent is supported */ getTextContent : function(){ var el = document.createElement("span"); return (typeof el.textContent !== "undefined"); }, /** * Check for a console object. * * @internal * @return {Boolean} <code>true</code> if a console is available. */ getConsole : function(){ return typeof window.console !== "undefined"; }, /** * Check for the <code>naturalHeight</code> and <code>naturalWidth</code> * image element attributes. * * @internal * @return {Boolean} <code>true</code> if both attributes are supported */ getNaturalDimensions : function(){ var img = document.createElement("img"); return typeof img.naturalHeight === "number" && typeof img.naturalWidth === "number"; }, /** * Check for HTML5 history manipulation support. * @internal * @return {Boolean} <code>true</code> if the HTML5 history API is supported */ getHistoryState : function(){ return (typeof window.onpopstate !== "undefined" && typeof window.history.replaceState !== "undefined" && typeof window.history.pushState !== "undefined"); }, /** * Returns the name of the native object/function used to access the * document's text selection. * * @return {String|null} <code>getSelection</code> if the standard window.getSelection * function is available; <code>selection</code> if the MS-proprietary * document.selection object is available; <code>null</code> if no known * text selection API is available. */ getSelection : function(){ if(typeof window.getSelection === "function"){ return "getSelection"; }; if(typeof document.selection === "object"){ return "selection"; }; return null; } }, defer : function(statics){ qx.core.Environment.add("html.webworker", statics.getWebWorker); qx.core.Environment.add("html.filereader", statics.getFileReader); qx.core.Environment.add("html.geolocation", statics.getGeoLocation); qx.core.Environment.add("html.audio", statics.getAudio); qx.core.Environment.add("html.audio.ogg", statics.getAudioOgg); qx.core.Environment.add("html.audio.mp3", statics.getAudioMp3); qx.core.Environment.add("html.audio.wav", statics.getAudioWav); qx.core.Environment.add("html.audio.au", statics.getAudioAu); qx.core.Environment.add("html.audio.aif", statics.getAudioAif); qx.core.Environment.add("html.video", statics.getVideo); qx.core.Environment.add("html.video.ogg", statics.getVideoOgg); qx.core.Environment.add("html.video.h264", statics.getVideoH264); qx.core.Environment.add("html.video.webm", statics.getVideoWebm); qx.core.Environment.add("html.storage.local", statics.getLocalStorage); qx.core.Environment.add("html.storage.session", statics.getSessionStorage); qx.core.Environment.add("html.storage.userdata", statics.getUserDataStorage); qx.core.Environment.add("html.classlist", statics.getClassList); qx.core.Environment.add("html.xpath", statics.getXPath); qx.core.Environment.add("html.xul", statics.getXul); qx.core.Environment.add("html.canvas", statics.getCanvas); qx.core.Environment.add("html.svg", statics.getSvg); qx.core.Environment.add("html.vml", statics.getVml); qx.core.Environment.add("html.dataset", statics.getDataset); qx.core.Environment.addAsync("html.dataurl", statics.getDataUrl); qx.core.Environment.add("html.element.contains", statics.getContains); qx.core.Environment.add("html.element.compareDocumentPosition", statics.getCompareDocumentPosition); qx.core.Environment.add("html.element.textcontent", statics.getTextContent); qx.core.Environment.add("html.console", statics.getConsole); qx.core.Environment.add("html.image.naturaldimensions", statics.getNaturalDimensions); qx.core.Environment.add("html.history.state", statics.getHistoryState); qx.core.Environment.add("html.selection", statics.getSelection); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2011 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /* ************************************************************************ #require(qx.bom.storage.Web#getLength) #require(qx.bom.storage.Web#setItem) #require(qx.bom.storage.Web#getItem) #require(qx.bom.storage.Web#removeItem) #require(qx.bom.storage.Web#clear) #require(qx.bom.storage.Web#getKey) #require(qx.bom.storage.Web#forEach) ************************************************************************ */ /** * Storage implementation using HTML web storage: * http://www.w3.org/TR/webstorage/ */ qx.Bootstrap.define("qx.bom.storage.Web", { statics : { __local : null, __session : null, /** * Static accessor for the local storage. * @return {qx.bom.storage.Web} An instance of a local storage. */ getLocal : function(){ if(this.__local){ return this.__local; }; return this.__local = new qx.bom.storage.Web("local"); }, /** * Static accessor for the session storage. * @return {qx.bom.storage.Web} An instance of a session storage. */ getSession : function(){ if(this.__session){ return this.__session; }; return this.__session = new qx.bom.storage.Web("session"); } }, /** * Create a new instance. Usually, you should take the static * accessors to get your instance. * * @param type {String} type of storage, either * <code>local</code> or <code>session</code>. */ construct : function(type){ this.__type = type; }, members : { __type : null, /** * Returns the internal used storage (the native object). * * @internal * @return {Storage} The native storage implementation. */ getStorage : function(){ return window[this.__type + "Storage"]; }, /** * Returns the amount of key-value pairs stored. * @return {Integer} The length of the storage. */ getLength : function(){ return this.getStorage(this.__type).length; }, /** * Store an item in the storage. * * @param key {String} The identifier key. * @param value {var} The data, which will be stored as JSON. */ setItem : function(key, value){ value = qx.lang.Json.stringify(value); try{ this.getStorage(this.__type).setItem(key, value); } catch(e) { throw new Error("Storage full."); }; }, /** * Returns the stored item. * * @param key {String} The identifier to get the data. * @return {var} The stored data. */ getItem : function(key){ var item = this.getStorage(this.__type).getItem(key); if(qx.lang.Type.isString(item)){ item = qx.lang.Json.parse(item); } else if(item && item.value && qx.lang.Type.isString(item.value)){ item = qx.lang.Json.parse(item.value); }; return item; }, /** * Removes an item form the storage. * @param key {String} The identifier. */ removeItem : function(key){ this.getStorage(this.__type).removeItem(key); }, /** * Deletes every stored item in the storage. */ clear : function(){ var storage = this.getStorage(this.__type); if(!storage.clear){ for(var i = storage.length - 1;i >= 0;i--){ storage.removeItem(storage.key(i)); }; } else { storage.clear(); }; }, /** * Returns the named key at the given index. * @param index {Integer} The index in the storage. * @return {String} The key stored at the given index. */ getKey : function(index){ return this.getStorage(this.__type).key(index); }, /** * Helper to access every stored item. * * @param callback {Function} A function which will be called for every item. * The function will have two arguments, first the key and second the value * of the stored data. * @param scope {var} The scope of the function. */ forEach : function(callback, scope){ var length = this.getLength(); for(var i = 0;i < length;i++){ var key = this.getKey(i); callback.call(scope, key, this.getItem(key)); }; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Fabian Jakobs (fjakobs) ________________________________________________________________________ This class contains code based on the following work: http://www.JSON.org/json2.js 2009-06-29 Public Domain. NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. See http://www.JSON.org/js.html ************************************************************************ */ /** * Pure JavaScript implementation of the EcmaScript 3.1 JSON object. This class * is used, if the browser does not support it natively. * * @internal */ qx.Bootstrap.define("qx.lang.JsonImpl", { extend : Object, construct : function(){ // bind parse and stringify so they can be called without a context. this.stringify = qx.lang.Function.bind(this.stringify, this); this.parse = qx.lang.Function.bind(this.parse, this); }, members : { __gap : null, __indent : null, __rep : null, __stack : null, /** * This method produces a JSON text from a JavaScript value. * * @param value {var} any JavaScript value, usually an object or array. * * @param replacer {Function?} an optional parameter that determines how * object values are stringified for objects. It can be a function or an * array of strings. * * @param space {String?} an optional parameter that specifies the * indentation of nested structures. If it is omitted, the text will * be packed without extra whitespace. If it is a number, it will specify * the number of spaces to indent at each level. If it is a string * (such as '\t' or '&nbsp;'), it contains the characters used to indent * at each level. * * @return {String} The JSON string of the value */ stringify : function(value, replacer, space){ this.__gap = ''; this.__indent = ''; this.__stack = []; if(qx.lang.Type.isNumber(space)){ // If the space parameter is a number, make an indent string containing that // many spaces. var space = Math.min(10, Math.floor(space)); for(var i = 0;i < space;i += 1){ this.__indent += ' '; }; } else if(qx.lang.Type.isString(space)){ if(space.length > 10){ space = space.slice(0, 10); }; // If the space parameter is a string, it will be used as the indent string. this.__indent = space; }; // If there is a replacer, it must be a function or an array. // Otherwise, ignore it. if(replacer && (qx.lang.Type.isFunction(replacer) || qx.lang.Type.isArray(replacer))){ this.__rep = replacer; } else { this.__rep = null; }; // Make a fake root object containing our value under the key of ''. // Return the result of stringifying the value. return this.__str('', { '' : value }); }, /** * Produce a string from holder[key]. * * @param key {String} the map key * @param holder {Object} an object with the given key * @return {String} The string representation of holder[key] */ __str : function(key, holder){ var mind = this.__gap,partial,value = holder[key]; // If the value has a toJSON method, call it to obtain a replacement value. if(value && qx.lang.Type.isFunction(value.toJSON)){ value = value.toJSON(key); } else if(qx.lang.Type.isDate(value)){ value = this.dateToJSON(value); }; // If we were called with a replacer function, then call the replacer to // obtain a replacement value. if(typeof this.__rep === 'function'){ value = this.__rep.call(holder, key, value); }; if(value === null){ return 'null'; }; if(value === undefined){ return undefined; }; // What happens next depends on the value's type. switch(qx.lang.Type.getClass(value)){case 'String': return this.__quote(value);case 'Number': // JSON numbers must be finite. Encode non-finite numbers as null. return isFinite(value) ? String(value) : 'null';case 'Boolean': // If the value is a boolean or null, convert it to a string. Note: // typeof null does not produce 'null'. The case is included here in // the remote chance that this gets fixed someday. return String(value);case 'Array': // Make an array to hold the partial results of stringifying this array value. this.__gap += this.__indent; partial = []; if(this.__stack.indexOf(value) !== -1){ throw new TypeError("Cannot stringify a recursive object."); }; this.__stack.push(value); // The value is an array. Stringify every element. Use null as a placeholder // for non-JSON values. var length = value.length; for(var i = 0;i < length;i += 1){ partial[i] = this.__str(i, value) || 'null'; }; this.__stack.pop(); // Join all of the elements together, separated with commas, and wrap them in // brackets. if(partial.length === 0){ var string = '[]'; } else if(this.__gap){ string = '[\n' + this.__gap + partial.join(',\n' + this.__gap) + '\n' + mind + ']'; } else { string = '[' + partial.join(',') + ']'; }; this.__gap = mind; return string;case 'Object': // Make an array to hold the partial results of stringifying this object value. this.__gap += this.__indent; partial = []; if(this.__stack.indexOf(value) !== -1){ throw new TypeError("Cannot stringify a recursive object."); }; this.__stack.push(value); // If the replacer is an array, use it to select the members to be stringified. if(this.__rep && typeof this.__rep === 'object'){ var length = this.__rep.length; for(var i = 0;i < length;i += 1){ var k = this.__rep[i]; if(typeof k === 'string'){ var v = this.__str(k, value); if(v){ partial.push(this.__quote(k) + (this.__gap ? ': ' : ':') + v); }; }; }; } else { // Otherwise, iterate through all of the keys in the object. for(var k in value){ if(Object.hasOwnProperty.call(value, k)){ var v = this.__str(k, value); if(v){ partial.push(this.__quote(k) + (this.__gap ? ': ' : ':') + v); }; }; }; }; this.__stack.pop(); // Join all of the member texts together, separated with commas, // and wrap them in braces. if(partial.length === 0){ var string = '{}'; } else if(this.__gap){ string = '{\n' + this.__gap + partial.join(',\n' + this.__gap) + '\n' + mind + '}'; } else { string = '{' + partial.join(',') + '}'; }; this.__gap = mind; return string;}; }, /** * Convert a date to JSON * * @param date {Date} The date to convert * @return {String} The JSON representation of the date */ dateToJSON : function(date){ // Format integers to have at least two digits. var f2 = function(n){ return n < 10 ? '0' + n : n; }; var f3 = function(n){ var value = f2(n); return n < 100 ? '0' + value : value; }; return isFinite(date.valueOf()) ? date.getUTCFullYear() + '-' + f2(date.getUTCMonth() + 1) + '-' + f2(date.getUTCDate()) + 'T' + f2(date.getUTCHours()) + ':' + f2(date.getUTCMinutes()) + ':' + f2(date.getUTCSeconds()) + '.' + f3(date.getUTCMilliseconds()) + 'Z' : null; }, /** * If the string contains no control characters, no quote characters, and no * backslash characters, then we can safely slap some quotes around it. * Otherwise we must also replace the offending characters with safe escape * sequences. * * @param string {String} The string to quote * @return {String} The quoted string */ __quote : function(string){ var meta = { // table of character substitutions '\b' : '\\b', '\t' : '\\t', '\n' : '\\n', '\f' : '\\f', '\r' : '\\r', '"' : '\\"', '\\' : '\\\\' }; var escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; escapable.lastIndex = 0; if(escapable.test(string)){ return '"' + string.replace(escapable, function(a){ var c = meta[a]; return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }) + '"'; } else { return '"' + string + '"'; }; }, /** * This method parses a JSON text to produce an object or array. * It can throw a SyntaxError exception. * * @param text {String} JSON string to parse * * @param reviver {Function?} Optional reviver function to filter and * transform the results * * @return {Object} The parsed JSON object * * @lint ignoreDeprecated(eval) */ parse : function(text, reviver){ var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; cx.lastIndex = 0; // Parsing happens in four stages. In the first stage, we replace certain // Unicode characters with escape sequences. JavaScript handles many characters // incorrectly, either silently deleting them, or treating them as line endings. if(cx.test(text)){ text = text.replace(cx, function(a){ return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }); }; // In the second stage, we run the text against regular expressions that look // for non-JSON patterns. We are especially concerned with '()' and 'new' // because they can cause invocation, and '=' because it can cause mutation. // But just to be safe, we want to reject all unexpected forms. // We split the second stage into 4 regexp operations in order to work around // crippling inefficiencies in IE's and Safari's regexp engines. First we // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we // replace all simple value tokens with ']' characters. Third, we delete all // open brackets that follow a colon or comma or that begin the text. Finally, // we look to see that the remaining characters are only whitespace or ']' or // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval. if(/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').replace(/(?:^|:|,)(?:\s*\[)+/g, ''))){ // In the third stage we use the eval function to compile the text into a // JavaScript structure. The '{' operator is subject to a syntactic ambiguity // in JavaScript: it can begin a block or an object literal. We wrap the text // in parens to eliminate the ambiguity. var j = eval('(' + text + ')'); // In the optional fourth stage, we recursively walk the new structure, passing // each name/value pair to a reviver function for possible transformation. return typeof reviver === 'function' ? this.__walk({ '' : j }, '', reviver) : j; }; // If the text is not JSON parseable, then a SyntaxError is thrown. throw new SyntaxError('JSON.parse'); }, /** * The walk method is used to recursively walk the resulting structure so * that modifications can be made. * * @param holder {Object} the root object * @param key {String} walk holder[key] * @param reviver {Function} callback, which is called on every node. * @return {var} The reviver's return value */ __walk : function(holder, key, reviver){ var value = holder[key]; if(value && typeof value === 'object'){ for(var k in value){ if(Object.hasOwnProperty.call(value, k)){ var v = this.__walk(value, k, reviver); if(v !== undefined){ value[k] = v; } else { delete value[k]; }; }; }; }; return reviver.call(holder, key, value); } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Andreas Ecker (ecker) ====================================================================== This class contains code based on the following work: * Mootools http://mootools.net Version 1.1.1 Copyright: 2007 Valerio Proietti License: MIT: http://www.opensource.org/licenses/mit-license.php ************************************************************************ */ /* ************************************************************************ #require(qx.lang.Array) #ignore(qx.core.Object) #ignore(qx.event.GlobalError) ************************************************************************ */ /** * Collection of helper methods operating on functions. */ qx.Bootstrap.define("qx.lang.Function", { statics : { /** * Extract the caller of a function from the arguments variable. * This will not work in Opera < 9.6. * * @param args {arguments} The local arguments variable * @return {Function} A reference to the calling function or "undefined" if caller is not supported. */ getCaller : function(args){ return args.caller ? args.caller.callee : args.callee.caller; }, /** * Try to get a sensible textual description of a function object. * This may be the class/mixin and method name of a function * or at least the signature of the function. * * @param fcn {Function} function the get the name for. * @return {String} Name of the function. */ getName : function(fcn){ if(fcn.displayName){ return fcn.displayName; }; if(fcn.$$original || fcn.wrapper || fcn.classname){ return fcn.classname + ".constructor()"; }; if(fcn.$$mixin){ //members for(var key in fcn.$$mixin.$$members){ if(fcn.$$mixin.$$members[key] == fcn){ return fcn.$$mixin.name + ".prototype." + key + "()"; }; }; // statics for(var key in fcn.$$mixin){ if(fcn.$$mixin[key] == fcn){ return fcn.$$mixin.name + "." + key + "()"; }; }; }; if(fcn.self){ var clazz = fcn.self.constructor; if(clazz){ // members for(var key in clazz.prototype){ if(clazz.prototype[key] == fcn){ return clazz.classname + ".prototype." + key + "()"; }; }; // statics for(var key in clazz){ if(clazz[key] == fcn){ return clazz.classname + "." + key + "()"; }; }; }; }; var fcnReResult = fcn.toString().match(/function\s*(\w*)\s*\(.*/); if(fcnReResult && fcnReResult.length >= 1 && fcnReResult[1]){ return fcnReResult[1] + "()"; }; return 'anonymous()'; }, /** * Evaluates JavaScript code globally * * @lint ignoreDeprecated(eval) * * @param data {String} JavaScript commands * @return {var} Result of the execution */ globalEval : function(data){ if(window.execScript){ return window.execScript(data); } else { return eval.call(window, data); }; }, /** * empty function * @deprecated {2.1} Please use a new empty function. */ empty : function(){ }, /** * Simply return true. * @deprecated {2.1} Please use a custom function. * @return {Boolean} Always returns true. */ returnTrue : function(){ return true; }, /** * Simply return false. * @deprecated {2.1} Please use a custom function. * @return {Boolean} Always returns false. */ returnFalse : function(){ return false; }, /** * Simply return null. * @deprecated {2.1} Please use a custom function. * @return {var} Always returns null. */ returnNull : function(){ return null; }, /** * Return "this". * @deprecated {2.1} Please use a custom function. * @return {Object} Always returns "this". */ returnThis : function(){ return this; }, /** * Simply return 0. * @deprecated {2.1} Please use a custom function. * @return {Number} Always returns 0. */ returnZero : function(){ return 0; }, /** * Base function for creating functional closures which is used by most other methods here. * * *Syntax* * * <pre class='javascript'>var createdFunction = qx.lang.Function.create(myFunction, [options]);</pre> * * @param func {Function} Original function to wrap * @param options {Map?} Map of options * <ul> * <li><strong>self</strong>: The object that the "this" of the function will refer to. Default is the same as the wrapper function is called.</li> * <li><strong>args</strong>: An array of arguments that will be passed as arguments to the function when called. * Default is no custom arguments; the function will receive the standard arguments when called.</li> * <li><strong>delay</strong>: If set, the returned function will delay the actual execution by this amount of milliseconds and return a timer handle when called. * Default is no delay.</li> * <li><strong>periodical</strong>: If set the returned function will periodically perform the actual execution with this specified interval * and return a timer handle when called. Default is no periodical execution.</li> * <li><strong>attempt</strong>: If set to true, the returned function will try to execute and return either the results or false on error. Default is false.</li> * </ul> * * @return {Function} Wrapped function */ create : function(func, options){ { }; // Nothing to be done when there are no options. if(!options){ return func; }; // Check for at least one attribute. if(!(options.self || options.args || options.delay != null || options.periodical != null || options.attempt)){ return func; }; return function(event){ { }; // Convert (and copy) incoming arguments var args = qx.lang.Array.fromArguments(arguments); // Prepend static arguments if(options.args){ args = options.args.concat(args); }; if(options.delay || options.periodical){ var returns = function(){ return func.apply(options.self || this, args); }; if(qx.core.Environment.get("qx.globalErrorHandling")){ returns = qx.event.GlobalError.observeMethod(returns); }; if(options.delay){ return window.setTimeout(returns, options.delay); }; if(options.periodical){ return window.setInterval(returns, options.periodical); }; } else if(options.attempt){ var ret = false; try{ ret = func.apply(options.self || this, args); } catch(ex) { }; return ret; } else { return func.apply(options.self || this, args); }; }; }, /** * Returns a function whose "this" is altered. * * * *Native way* * * This is also a feature of JavaScript 1.8.5 and will be supplied * by modern browsers. Including {@link qx.lang.normalize.Function} * will supply a cross browser normalization of the native * implementation. We like to encourage you to use the native function! * * * *Syntax* * * <pre class='javascript'>qx.lang.Function.bind(myFunction, [self, [varargs...]]);</pre> * * *Example* * * <pre class='javascript'> * function myFunction() * { * this.setStyle('color', 'red'); * // note that 'this' here refers to myFunction, not an element * // we'll need to bind this function to the element we want to alter * }; * * var myBoundFunction = qx.lang.Function.bind(myFunction, myElement); * myBoundFunction(); // this will make the element myElement red. * </pre> * * If you find yourself using this static method a lot, you may be * interested in the bindTo() method in the mixin qx.core.MBindTo. * * @see qx.core.MBindTo * * @param func {Function} Original function to wrap * @param self {Object ? null} The object that the "this" of the function will refer to. * @param varargs {arguments ? null} The arguments to pass to the function. * @return {Function} The bound function. */ bind : function(func, self, varargs){ return this.create(func, { self : self, args : arguments.length > 2 ? qx.lang.Array.fromArguments(arguments, 2) : null }); }, /** * Returns a function whose arguments are pre-configured. * * *Syntax* * * <pre class='javascript'>qx.lang.Function.curry(myFunction, [varargs...]);</pre> * * *Example* * * <pre class='javascript'> * function myFunction(elem) { * elem.setStyle('color', 'red'); * }; * * var myBoundFunction = qx.lang.Function.curry(myFunction, myElement); * myBoundFunction(); // this will make the element myElement red. * </pre> * * @param func {Function} Original function to wrap * @param varargs {arguments} The arguments to pass to the function. * @return {var} The pre-configured function. */ curry : function(func, varargs){ return this.create(func, { args : arguments.length > 1 ? qx.lang.Array.fromArguments(arguments, 1) : null }); }, /** * Returns a function which could be used as a listener for a native event callback. * * *Syntax* * * <pre class='javascript'>qx.lang.Function.listener(myFunction, [self, [varargs...]]);</pre> * * @param func {Function} Original function to wrap * @param self {Object ? null} The object that the "this" of the function will refer to. * @param varargs {arguments ? null} The arguments to pass to the function. * @return {var} The bound function. */ listener : function(func, self, varargs){ if(arguments.length < 3){ return function(event){ // Directly execute, but force first parameter to be the event object. return func.call(self || this, event || window.event); }; } else { var optargs = qx.lang.Array.fromArguments(arguments, 2); return function(event){ var args = [event || window.event]; // Append static arguments args.push.apply(args, optargs); // Finally execute original method func.apply(self || this, args); }; }; }, /** * Tries to execute the function. * * *Syntax* * * <pre class='javascript'>var result = qx.lang.Function.attempt(myFunction, [self, [varargs...]]);</pre> * * *Example* * * <pre class='javascript'> * var myObject = { * 'cow': 'moo!' * }; * * var myFunction = function() * { * for(var i = 0; i < arguments.length; i++) { * if(!this[arguments[i]]) throw('doh!'); * } * }; * * var result = qx.lang.Function.attempt(myFunction, myObject, 'pig', 'cow'); // false * </pre> * * @param func {Function} Original function to wrap * @param self {Object ? null} The object that the "this" of the function will refer to. * @param varargs {arguments ? null} The arguments to pass to the function. * @return {Boolean|var} <code>false</code> if an exception is thrown, else the function's return. */ attempt : function(func, self, varargs){ return this.create(func, { self : self, attempt : true, args : arguments.length > 2 ? qx.lang.Array.fromArguments(arguments, 2) : null })(); }, /** * Delays the execution of a function by a specified duration. * * *Syntax* * * <pre class='javascript'>var timeoutID = qx.lang.Function.delay(myFunction, [delay, [self, [varargs...]]]);</pre> * * *Example* * * <pre class='javascript'> * var myFunction = function(){ alert('moo! Element id is: ' + this.id); }; * //wait 50 milliseconds, then call myFunction and bind myElement to it * qx.lang.Function.delay(myFunction, 50, myElement); // alerts: 'moo! Element id is: ... ' * * // An anonymous function, example * qx.lang.Function.delay(function(){ alert('one second later...'); }, 1000); //wait a second and alert * </pre> * * @param func {Function} Original function to wrap * @param delay {Integer} The duration to wait (in milliseconds). * @param self {Object ? null} The object that the "this" of the function will refer to. * @param varargs {arguments ? null} The arguments to pass to the function. * @return {Integer} The JavaScript Timeout ID (useful for clearing delays). */ delay : function(func, delay, self, varargs){ return this.create(func, { delay : delay, self : self, args : arguments.length > 3 ? qx.lang.Array.fromArguments(arguments, 3) : null })(); }, /** * Executes a function in the specified intervals of time * * *Syntax* * * <pre class='javascript'>var intervalID = qx.lang.Function.periodical(myFunction, [period, [self, [varargs...]]]);</pre> * * *Example* * * <pre class='javascript'> * var Site = { counter: 0 }; * var addCount = function(){ this.counter++; }; * qx.lang.Function.periodical(addCount, 1000, Site); // will add the number of seconds at the Site * </pre> * * @param func {Function} Original function to wrap * @param interval {Integer} The duration of the intervals between executions. * @param self {Object ? null} The object that the "this" of the function will refer to. * @param varargs {arguments ? null} The arguments to pass to the function. * @return {Integer} The Interval ID (useful for clearing a periodical). */ periodical : function(func, interval, self, varargs){ return this.create(func, { periodical : interval, self : self, args : arguments.length > 3 ? qx.lang.Array.fromArguments(arguments, 3) : null })(); } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Fabian Jakobs (fjakobs) ________________________________________________________________________ This class contains code based on the following work: http://www.JSON.org/json2.js 2009-06-29 Public Domain. NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. See http://www.JSON.org/js.html ************************************************************************ */ /** * JSON (JavaScript Object Notation) parser, serializer for qooxdoo * * This class implements EcmaScript 3.1 JSON support. * * http://wiki.ecmascript.org/doku.php?id=es3.1:json_support * * If the browser supports native JSON the browser implementation is used. */ qx.Bootstrap.define("qx.lang.Json", { statics : { /** * {JSON} The JSON object to use. If the browser has native JSON support * this member points to <code>window.JSON</code>. Otherwise it points to * the qooxdoo implementation {@link JsonImpl}. */ JSON : true ? window.JSON : new qx.lang.JsonImpl(), /** * This method produces a JSON text from a JavaScript value. * * When an object value is found, if the object contains a toJSON * method, its toJSON method will be called and the result will be * stringified. A toJSON method does not serialize: it returns the * value represented by the name/value pair that should be serialized, * or undefined if nothing should be serialized. The toJSON method * will be passed the key associated with the value, and this will be * bound to the object holding the key. * * For example, this would serialize Dates as ISO strings. * * <pre class="javascript"> * Date.prototype.toJSON = function (key) { * function f(n) { * // Format integers to have at least two digits. * return n < 10 ? '0' + n : n; * } * * return this.getUTCFullYear() + '-' + * f(this.getUTCMonth() + 1) + '-' + * f(this.getUTCDate()) + 'T' + * f(this.getUTCHours()) + ':' + * f(this.getUTCMinutes()) + ':' + * f(this.getUTCSeconds()) + 'Z'; * }; * </pre> * * You can provide an optional replacer method. It will be passed the * key and value of each member, with this bound to the containing * object. The value that is returned from your method will be * serialized. If your method returns undefined, then the member will * be excluded from the serialization. * * If the replacer parameter is an array of strings, then it will be * used to select the members to be serialized. It filters the results * such that only members with keys listed in the replacer array are * stringified. * * Values that do not have JSON representations, such as undefined or * functions, will not be serialized. Such values in objects will be * dropped; in arrays they will be replaced with null. You can use * a replacer function to replace those with JSON values. * JSON.stringify(undefined) returns undefined. * * The optional space parameter produces a stringification of the * value that is filled with line breaks and indentation to make it * easier to read. * * If the space parameter is a non-empty string, then that string will * be used for indentation. If the space parameter is a number, then * the indentation will be that many spaces. * * Example: * * <pre class="javascript"> * text = JSON.stringify(['e', {pluribus: 'unum'}]); * // text is '["e",{"pluribus":"unum"}]' * * * text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t'); * // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]' * * text = JSON.stringify([new Date()], function (key, value) { * return this[key] instanceof Date ? * 'Date(' + this[key] + ')' : value; * }); * // text is '["Date(---current time---)"]' * </pre> * * @signature function(value, replacer, space) * * @param value {var} any JavaScript value, usually an object or array. * * @param replacer {Function?} an optional parameter that determines how * object values are stringified for objects. It can be a function or an * array of strings. * * @param space {String?} an optional parameter that specifies the * indentation of nested structures. If it is omitted, the text will * be packed without extra whitespace. If it is a number, it will specify * the number of spaces to indent at each level. If it is a string * (such as '\t' or '&nbsp;'), it contains the characters used to indent * at each level. * * @return {String} The JSON string of the value */ stringify : null, // will be set in the defer block /** * This method parses a JSON text to produce an object or array. * It can throw a SyntaxError exception. * * The optional reviver parameter is a function that can filter and * transform the results. It receives each of the keys and values, * and its return value is used instead of the original value. * If it returns what it received, then the structure is not modified. * If it returns undefined then the member is deleted. * * Example: * * <pre class="javascript"> * // Parse the text. Values that look like ISO date strings will * // be converted to Date objects. * * myData = JSON.parse(text, function (key, value) * { * if (typeof value === 'string') * { * var a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value); * if (a) { * return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6])); * } * } * return value; * }); * * myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) { * var d; * if (typeof value === 'string' && * value.slice(0, 5) === 'Date(' && * value.slice(-1) === ')') { * d = new Date(value.slice(5, -1)); * if (d) { * return d; * } * } * return value; * }); * </pre> * * @signature function(text, reviver) * * @param text {String} JSON string to parse * * @param reviver {Function?} Optional reviver function to filter and * transform the results * * @return {Object} The parsed JSON object */ parse : null }, defer : function(statics){ statics.stringify = statics.JSON.stringify; statics.parse = statics.JSON.parse; } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /* ************************************************************************ #require(qx.bom.storage.UserData#getLength) #require(qx.bom.storage.UserData#setItem) #require(qx.bom.storage.UserData#getItem) #require(qx.bom.storage.UserData#removeItem) #require(qx.bom.storage.UserData#clear) #require(qx.bom.storage.UserData#getKey) #require(qx.bom.storage.UserData#forEach) ************************************************************************ */ /** * Fallback storage implementation usable in IE browsers. It is recommended to use * these implementation only in IE < 8 because IE >= 8 supports * {@link qx.bom.storage.Web}. */ qx.Bootstrap.define("qx.bom.storage.UserData", { statics : { __local : null, __session : null, // global id used as key for the storage __id : 0, /** * Returns an instance of {@link qx.bom.storage.UserData} used to store * data persistent. * @return {qx.bom.storage.UserData} A storage instance. */ getLocal : function(){ if(this.__local){ return this.__local; }; return this.__local = new qx.bom.storage.UserData("local"); }, /** * Returns an instance of {@link qx.bom.storage.UserData} used to store * data persistent. * @return {qx.bom.storage.UserData} A storage instance. */ getSession : function(){ if(this.__session){ return this.__session; }; return this.__session = new qx.bom.storage.UserData("session"); } }, /** * Create a new instance. Usually, you should take the static * accessors to get your instance. * * @param storeName {String} type of storage. */ construct : function(storeName){ // create a dummy DOM element used for storage this.__el = document.createElement("div"); this.__el.style["display"] = "none"; document.getElementsByTagName("head")[0].appendChild(this.__el); this.__el.addBehavior("#default#userdata"); this.__storeName = storeName; // load the inital data which might be stored this.__el.load(this.__storeName); // set up the internal reference maps this.__storage = { }; this.__reference = { }; // initialize var value = this.__el.getAttribute("qx" + qx.bom.storage.UserData.__id); while(value != undefined){ value = qx.lang.Json.parse(value); // save the data in the internal storage this.__storage[value.key] = value.value; // save the reference this.__reference[value.key] = "qx" + qx.bom.storage.UserData.__id; qx.bom.storage.UserData.__id++; value = this.__el.getAttribute("qx" + qx.bom.storage.UserData.__id); }; }, members : { __el : null, __storeName : "qxtest", // storage which holds the key and the value __storage : null, // reference store which holds the key and the key used to store __reference : null, /** * Returns the map used to keep a in memory copy of the stored data. * @return {Map} The stored data. * @internal */ getStorage : function(){ return this.__storage; }, /** * Returns the amount of key-value pairs stored. * @return {Integer} The length of the storage. */ getLength : function(){ return Object.keys(this.__storage).length; }, /** * Store an item in the storage. * * @param key {String} The identifier key. * @param value {var} The data, which will be stored as JSON. */ setItem : function(key, value){ // override case if(this.__reference[key]){ var storageKey = this.__reference[key]; } else { var storageKey = "qx" + qx.bom.storage.UserData.__id; qx.bom.storage.UserData.__id++; }; // build and save the data used to store both, key and value var storageValue = qx.lang.Json.stringify({ key : key, value : value }); this.__el.setAttribute(storageKey, storageValue); this.__el.save(this.__storeName); // also update the internal mappings this.__storage[key] = value; this.__reference[key] = storageKey; }, /** * Returns the stored item. * * @param key {String} The identifier to get the data. * @return {var} The stored data. */ getItem : function(key){ return this.__storage[key] || null; }, /** * Removes an item form the storage. * @param key {String} The identifier. */ removeItem : function(key){ // check if the item is availabel var storageName = this.__reference[key]; if(storageName == undefined){ return; }; // remove the item this.__el.removeAttribute(storageName); // decrease the id because we removed one item qx.bom.storage.UserData.__id--; // update the internal maps delete this.__storage[key]; delete this.__reference[key]; // check if we have deleted the last item var lastStoreName = "qx" + qx.bom.storage.UserData.__id; if(this.__el.getAttribute(lastStoreName)){ // if not, move the last item to the deleted spot var lastItem = this.__el.getAttribute("qx" + qx.bom.storage.UserData.__id); this.__el.removeAttribute(lastStoreName); this.__el.setAttribute(storageName, lastItem); // update the reference map var lastKey = qx.lang.Json.parse(lastItem).key; this.__reference[lastKey] = storageName; }; this.__el.save(this.__storeName); }, /** * Deletes every stored item in the storage. */ clear : function(){ // delete all entries from the storage for(var key in this.__reference){ this.__el.removeAttribute(this.__reference[key]); }; this.__el.save(this.__storeName); // reset the internal maps this.__storage = { }; this.__reference = { }; }, /** * Returns the named key at the given index. * @param index {Integer} The index in the storage. * @return {String} The key stored at the given index. */ getKey : function(index){ return Object.keys(this.__storage)[index]; }, /** * Helper to access every stored item. * * @param callback {Function} A function which will be called for every item. * The function will have two arguments, first the key and second the value * of the stored data. * @param scope {var} The scope of the function. */ forEach : function(callback, scope){ var length = this.getLength(); for(var i = 0;i < length;i++){ var key = this.getKey(i); callback.call(scope, key, this.getItem(key)); }; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /* ************************************************************************ #require(qx.bom.storage.Memory#getLength) #require(qx.bom.storage.Memory#setItem) #require(qx.bom.storage.Memory#getItem) #require(qx.bom.storage.Memory#removeItem) #require(qx.bom.storage.Memory#clear) #require(qx.bom.storage.Memory#getKey) #require(qx.bom.storage.Memory#forEach) ************************************************************************ */ /** * Fallback storage implementation which offers the same API as every other storage * but is not persistent. Basically, its just a storage API on a JavaScript map. */ qx.Bootstrap.define("qx.bom.storage.Memory", { statics : { __local : null, __session : null, /** * Returns an instance of {@link qx.bom.storage.Memory} which is of course * not persisted on reload. * @return {qx.bom.storage.Memory} A memory storage. */ getLocal : function(){ if(this.__local){ return this.__local; }; return this.__local = new qx.bom.storage.Memory(); }, /** * Returns an instance of {@link qx.bom.storage.Memory} which is of course * not persisted on reload. * @return {qx.bom.storage.Memory} A memory storage. */ getSession : function(){ if(this.__session){ return this.__session; }; return this.__session = new qx.bom.storage.Memory(); } }, construct : function(){ this.__storage = { }; }, members : { __storage : null, /** * Returns the internal used map. * @return {Map} The storage. * @internal */ getStorage : function(){ return this.__storage; }, /** * Returns the amount of key-value pairs stored. * @return {Integer} The length of the storage. */ getLength : function(){ return Object.keys(this.__storage).length; }, /** * Store an item in the storage. * * @param key {String} The identifier key. * @param value {var} The data, which will be stored as JSON. */ setItem : function(key, value){ value = qx.lang.Json.stringify(value); this.__storage[key] = value; }, /** * Returns the stored item. * * @param key {String} The identifier to get the data. * @return {var} The stored data. */ getItem : function(key){ var item = this.__storage[key]; if(qx.lang.Type.isString(item)){ item = qx.lang.Json.parse(item); }; return item; }, /** * Removes an item form the storage. * @param key {String} The identifier. */ removeItem : function(key){ delete this.__storage[key]; }, /** * Deletes every stored item in the storage. */ clear : function(){ this.__storage = { }; }, /** * Returns the named key at the given index. * @param index {Integer} The index in the storage. * @return {String} The key stored at the given index. */ getKey : function(index){ var keys = Object.keys(this.__storage); return keys[index]; }, /** * Helper to access every stored item. * * @param callback {Function} A function which will be called for every item. * The function will have two arguments, first the key and second the value * of the stored data. * @param scope {var} The scope of the function. */ forEach : function(callback, scope){ var length = this.getLength(); for(var i = 0;i < length;i++){ var key = this.getKey(i); callback.call(scope, key, this.getItem(key)); }; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2011-2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) * Daniel Wagner (danielwagner) ************************************************************************ */ /** * CSS/Style property manipulation module */ qx.Bootstrap.define("qx.module.Css", { statics : { /** * Modifies the given style property on all elements in the collection. * * @attach {qxWeb} * @param name {String} Name of the style property to modify * @param value {var} The value to apply * @return {qxWeb} The collection for chaining */ setStyle : function(name, value){ if(/\w-\w/.test(name)){ name = qx.lang.String.camelCase(name); }; for(var i = 0;i < this.length;i++){ qx.bom.element.Style.set(this[i], name, value); }; return this; }, /** * Returns the value of the given style property for the first item in the * collection. * * @attach {qxWeb} * @param name {String} Style property name * @return {var} Style property value */ getStyle : function(name){ if(this[0]){ if(/\w-\w/.test(name)){ name = qx.lang.String.camelCase(name); }; return qx.bom.element.Style.get(this[0], name); }; return null; }, /** * Sets multiple style properties for each item in the collection. * * @attach {qxWeb} * @param styles {Map} A map of style property name/value pairs * @return {qxWeb} The collection for chaining */ setStyles : function(styles){ for(var name in styles){ this.setStyle(name, styles[name]); }; return this; }, /** * Returns the values of multiple style properties for each item in the * collection * * @attach {qxWeb} * @param names {String[]} List of style property names * @return {Map} Map of style property name/value pairs */ getStyles : function(names){ var styles = { }; for(var i = 0;i < names.length;i++){ styles[names[i]] = this.getStyle(names[i]); }; return styles; }, /** * Adds a class name to each element in the collection * * @attach {qxWeb} * @param name {String} Class name * @return {qxWeb} The collection for chaining */ addClass : function(name){ for(var i = 0;i < this.length;i++){ qx.bom.element.Class.add(this[i], name); }; return this; }, /** * Adds multiple class names to each element in the collection * * @attach {qxWeb} * @param names {String[]} List of class names to add * @return {qxWeb} The collection for chaining */ addClasses : function(names){ for(var i = 0;i < this.length;i++){ qx.bom.element.Class.addClasses(this[i], names); }; return this; }, /** * Removes a class name from each element in the collection * * @attach {qxWeb} * @param name {String} The class name to remove * @return {qxWeb} The collection for chaining */ removeClass : function(name){ for(var i = 0;i < this.length;i++){ qx.bom.element.Class.remove(this[i], name); }; return this; }, /** * Removes multiple class names from each element in the collection * * @attach {qxWeb} * @param names {String[]} List of class names to remove * @return {qxWeb} The collection for chaining */ removeClasses : function(names){ for(var i = 0;i < this.length;i++){ qx.bom.element.Class.removeClasses(this[i], names); }; return this; }, /** * Checks if the first element in the collection has the given class name * * @attach {qxWeb} * @param name {String} Class name to check for * @return {Boolean} <code>true</code> if the first item has the given class name */ hasClass : function(name){ if(!this[0]){ return false; }; return qx.bom.element.Class.has(this[0], name); }, /** * Returns the class name of the first element in the collection * * @attach {qxWeb} * @return {String} Class name */ getClass : function(){ if(!this[0]){ return ""; }; return qx.bom.element.Class.get(this[0]); }, /** * Toggles the given class name on each item in the collection * * @attach {qxWeb} * @param name {String} Class name * @return {qxWeb} The collection for chaining */ toggleClass : function(name){ var bCls = qx.bom.element.Class; for(var i = 0,l = this.length;i < l;i++){ bCls.has(this[i], name) ? bCls.remove(this[i], name) : bCls.add(this[i], name); }; return this; }, /** * Toggles the given list of class names on each item in the collection * * @attach {qxWeb} * @param names {String[]} Class names * @return {qxWeb} The collection for chaining */ toggleClasses : function(names){ for(var i = 0,l = names.length;i < l;i++){ this.toggleClass(names[i]); }; return this; }, /** * Replaces a class name on each element in the collection * * @attach {qxWeb} * @param oldName {String} Class name to remove * @param newName {String} Class name to add * @return {qxWeb} The collection for chaining */ replaceClass : function(oldName, newName){ for(var i = 0,l = this.length;i < l;i++){ qx.bom.element.Class.replace(this[i], oldName, newName); }; return this; }, /** * Returns the rendered height of the first element in the collection. * @attach {qxWeb} * @return {Number} The first item's rendered height */ getHeight : function(){ var elem = this[0]; if(elem){ if(qx.dom.Node.isElement(elem)){ return qx.bom.element.Dimension.getHeight(elem); } else if(qx.dom.Node.isDocument(elem)){ return qx.bom.Document.getHeight(qx.dom.Node.getWindow(elem)); } else if(qx.dom.Node.isWindow(elem)){ return qx.bom.Viewport.getHeight(elem); };; }; return null; }, /** * Returns the rendered width of the first element in the collection * @attach {qxWeb} * @return {Number} The first item's rendered width */ getWidth : function(){ var elem = this[0]; if(elem){ if(qx.dom.Node.isElement(elem)){ return qx.bom.element.Dimension.getWidth(elem); } else if(qx.dom.Node.isDocument(elem)){ return qx.bom.Document.getWidth(qx.dom.Node.getWindow(elem)); } else if(qx.dom.Node.isWindow(elem)){ return qx.bom.Viewport.getWidth(elem); };; }; return null; }, /** * Returns the computed location of the given element in the context of the * document dimensions. * * @attach {qxWeb} * @return {Map} A map with the keys <code>left<code/>, <code>top<code/>, * <code>right<code/> and <code>bottom<code/> which contains the distance * of the element relative to the document. */ getOffset : function(){ var elem = this[0]; if(elem){ return qx.bom.element.Location.get(elem); }; return null; }, /** * Returns the content height of the first element in the collection. * This is the maximum height the element can use, excluding borders, * margins, padding or scroll bars. * @attach {qxWeb} * @return {Number} Computed content height */ getContentHeight : function(){ var obj = this[0]; if(qx.dom.Node.isElement(obj)){ return qx.bom.element.Dimension.getContentHeight(obj); }; return null; }, /** * Returns the content width of the first element in the collection. * This is the maximum width the element can use, excluding borders, * margins, padding or scroll bars. * @attach {qxWeb} * @return {Number} Computed content width */ getContentWidth : function(){ var obj = this[0]; if(qx.dom.Node.isElement(obj)){ return qx.bom.element.Dimension.getContentWidth(obj); }; return null; }, /** * Returns the distance between the first element in the collection and its * offset parent * * @attach {qxWeb} * @return {Map} a map with the keys <code>left</code> and <code>top</code> * containing the distance between the elements */ getPosition : function(){ var obj = this[0]; if(qx.dom.Node.isElement(obj)){ return qx.bom.element.Location.getPosition(obj); }; return null; }, /** * Includes a Stylesheet file * * @attachStatic {qxWeb} * @param uri {String} The stylesheet's URI * @param doc {Document?} Document to modify */ includeStylesheet : function(uri, doc){ qx.bom.Stylesheet.includeFile(uri, doc); }, /** * Hides all elements in the collection by setting their "display" * style to "none". The previous value is stored so it can be re-applied * when {@link #show} is called. * * @attach {qxWeb} * @return {qxWeb} The collection for chaining */ hide : function(){ for(var i = 0,l = this.length;i < l;i++){ var item = this.slice(i, i + 1); var prevStyle = item.getStyle("display"); if(prevStyle !== "none"){ item[0].$$qPrevDisp = prevStyle; item.setStyle("display", "none"); }; }; return this; }, /** * Shows any elements with "display: none" in the collection. If an element * was hidden by using the {@link #hide} method, its previous * "display" style value will be re-applied. Otherwise, the * default "display" value for the element type will be applied. * * @attach {qxWeb} * @return {qxWeb} The collection for chaining */ show : function(){ for(var i = 0,l = this.length;i < l;i++){ var item = this.slice(i, i + 1); var currentVal = item.getStyle("display"); var prevVal = item[0].$$qPrevDisp; var newVal; if(currentVal == "none"){ if(prevVal && prevVal != "none"){ newVal = prevVal; } else { var doc = qxWeb.getDocument(item[0]); newVal = qx.module.Css.__getDisplayDefault(item[0].tagName, doc); }; item.setStyle("display", newVal); item[0].$$qPrevDisp = "none"; }; }; return this; }, /** * Maps HTML elements to their default "display" style values. */ __displayDefaults : { }, /** * Attempts tp determine the default "display" style value for * elements with the given tag name. * * @param tagName {String} Tag name * @param doc {Document?} Document element. Default: The current document * @return {String} The default "display" value, e.g. <code>inline</code> * or <code>block</code> */ __getDisplayDefault : function(tagName, doc){ var defaults = qx.module.Css.__displayDefaults; if(!defaults[tagName]){ var docu = doc || document; var tempEl = qxWeb(docu.createElement(tagName)).appendTo(doc.body); defaults[tagName] = tempEl.getStyle("display"); tempEl.remove(); }; return defaults[tagName] || ""; } }, defer : function(statics){ qxWeb.$attach({ "setStyle" : statics.setStyle, "getStyle" : statics.getStyle, "setStyles" : statics.setStyles, "getStyles" : statics.getStyles, "addClass" : statics.addClass, "addClasses" : statics.addClasses, "removeClass" : statics.removeClass, "removeClasses" : statics.removeClasses, "hasClass" : statics.hasClass, "getClass" : statics.getClass, "toggleClass" : statics.toggleClass, "toggleClasses" : statics.toggleClasses, "replaceClass" : statics.replaceClass, "getHeight" : statics.getHeight, "getWidth" : statics.getWidth, "getOffset" : statics.getOffset, "getContentHeight" : statics.getContentHeight, "getContentWidth" : statics.getContentWidth, "getPosition" : statics.getPosition, "hide" : statics.hide, "show" : statics.show }); qxWeb.$attachStatic({ "includeStylesheet" : statics.includeStylesheet }); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /** * This class takes care of the normalization of the native 'String' object. * Therefore it checks the availability of the following methods and appends * it, if not available. This means you can use the methods during * development in every browser. For usage samples, check out the attached links. * * *trim*: * <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/Trim">MDN documentation</a> | * <a href="http://es5.github.com/#x15.5.4.20">Annotated ES5 Spec</a> */ qx.Bootstrap.define("qx.lang.normalize.String", { defer : function(){ // trim if(!qx.core.Environment.get("ecmascript.string.trim")){ String.prototype.trim = function(context){ return this.replace(/^\s+|\s+$/g, ''); }; }; } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Andreas Ecker (ecker) ====================================================================== This class contains code based on the following work: * Mootools http://mootools.net/ Version 1.1.1 Copyright: (c) 2007 Valerio Proietti License: MIT: http://www.opensource.org/licenses/mit-license.php and * XRegExp http://xregexp.com/ Version 1.5 Copyright: (c) 2006-2007, Steven Levithan <http://stevenlevithan.com> License: MIT: http://www.opensource.org/licenses/mit-license.php Authors: * Steven Levithan ************************************************************************ */ /* ************************************************************************ #require(qx.lang.normalize.String) ************************************************************************ */ /** * String helper functions * * The native JavaScript String is not modified by this class. However, * there are modifications to the native String in {@link qx.lang.normalize.String} for * browsers that do not support certain features. */ qx.Bootstrap.define("qx.lang.String", { statics : { /** * Unicode letters. they are taken from Steve Levithan's excellent XRegExp library [http://xregexp.com/addons/unicode/unicode-base.js] */ __unicodeLetters : "0041-005A0061-007A00AA00B500BA00C0-00D600D8-00F600F8-02C102C6-02D102E0-02E402EC02EE0370-037403760377037A-037D03860388-038A038C038E-03A103A3-03F503F7-0481048A-05250531-055605590561-058705D0-05EA05F0-05F20621-064A066E066F0671-06D306D506E506E606EE06EF06FA-06FC06FF07100712-072F074D-07A507B107CA-07EA07F407F507FA0800-0815081A082408280904-0939093D09500958-0961097109720979-097F0985-098C098F09900993-09A809AA-09B009B209B6-09B909BD09CE09DC09DD09DF-09E109F009F10A05-0A0A0A0F0A100A13-0A280A2A-0A300A320A330A350A360A380A390A59-0A5C0A5E0A72-0A740A85-0A8D0A8F-0A910A93-0AA80AAA-0AB00AB20AB30AB5-0AB90ABD0AD00AE00AE10B05-0B0C0B0F0B100B13-0B280B2A-0B300B320B330B35-0B390B3D0B5C0B5D0B5F-0B610B710B830B85-0B8A0B8E-0B900B92-0B950B990B9A0B9C0B9E0B9F0BA30BA40BA8-0BAA0BAE-0BB90BD00C05-0C0C0C0E-0C100C12-0C280C2A-0C330C35-0C390C3D0C580C590C600C610C85-0C8C0C8E-0C900C92-0CA80CAA-0CB30CB5-0CB90CBD0CDE0CE00CE10D05-0D0C0D0E-0D100D12-0D280D2A-0D390D3D0D600D610D7A-0D7F0D85-0D960D9A-0DB10DB3-0DBB0DBD0DC0-0DC60E01-0E300E320E330E40-0E460E810E820E840E870E880E8A0E8D0E94-0E970E99-0E9F0EA1-0EA30EA50EA70EAA0EAB0EAD-0EB00EB20EB30EBD0EC0-0EC40EC60EDC0EDD0F000F40-0F470F49-0F6C0F88-0F8B1000-102A103F1050-1055105A-105D106110651066106E-10701075-1081108E10A0-10C510D0-10FA10FC1100-1248124A-124D1250-12561258125A-125D1260-1288128A-128D1290-12B012B2-12B512B8-12BE12C012C2-12C512C8-12D612D8-13101312-13151318-135A1380-138F13A0-13F41401-166C166F-167F1681-169A16A0-16EA1700-170C170E-17111720-17311740-17511760-176C176E-17701780-17B317D717DC1820-18771880-18A818AA18B0-18F51900-191C1950-196D1970-19741980-19AB19C1-19C71A00-1A161A20-1A541AA71B05-1B331B45-1B4B1B83-1BA01BAE1BAF1C00-1C231C4D-1C4F1C5A-1C7D1CE9-1CEC1CEE-1CF11D00-1DBF1E00-1F151F18-1F1D1F20-1F451F48-1F4D1F50-1F571F591F5B1F5D1F5F-1F7D1F80-1FB41FB6-1FBC1FBE1FC2-1FC41FC6-1FCC1FD0-1FD31FD6-1FDB1FE0-1FEC1FF2-1FF41FF6-1FFC2071207F2090-209421022107210A-211321152119-211D212421262128212A-212D212F-2139213C-213F2145-2149214E218321842C00-2C2E2C30-2C5E2C60-2CE42CEB-2CEE2D00-2D252D30-2D652D6F2D80-2D962DA0-2DA62DA8-2DAE2DB0-2DB62DB8-2DBE2DC0-2DC62DC8-2DCE2DD0-2DD62DD8-2DDE2E2F300530063031-3035303B303C3041-3096309D-309F30A1-30FA30FC-30FF3105-312D3131-318E31A0-31B731F0-31FF3400-4DB54E00-9FCBA000-A48CA4D0-A4FDA500-A60CA610-A61FA62AA62BA640-A65FA662-A66EA67F-A697A6A0-A6E5A717-A71FA722-A788A78BA78CA7FB-A801A803-A805A807-A80AA80C-A822A840-A873A882-A8B3A8F2-A8F7A8FBA90A-A925A930-A946A960-A97CA984-A9B2A9CFAA00-AA28AA40-AA42AA44-AA4BAA60-AA76AA7AAA80-AAAFAAB1AAB5AAB6AAB9-AABDAAC0AAC2AADB-AADDABC0-ABE2AC00-D7A3D7B0-D7C6D7CB-D7FBF900-FA2DFA30-FA6DFA70-FAD9FB00-FB06FB13-FB17FB1DFB1F-FB28FB2A-FB36FB38-FB3CFB3EFB40FB41FB43FB44FB46-FBB1FBD3-FD3DFD50-FD8FFD92-FDC7FDF0-FDFBFE70-FE74FE76-FEFCFF21-FF3AFF41-FF5AFF66-FFBEFFC2-FFC7FFCA-FFCFFFD2-FFD7FFDA-FFDC", /** * A RegExp that matches the first letter in a word - unicode aware */ __unicodeFirstLetterInWordRegexp : null, /** * {Map} Cache for often used string operations [camelCasing and hyphenation] * e.g. marginTop => margin-top */ __stringsMap : { }, /** * Converts a hyphenated string (separated by '-') to camel case. * * Example: * <pre class='javascript'>qx.lang.String.camelCase("I-like-cookies"); //returns "ILikeCookies"</pre> * * @param str {String} hyphenated string * @return {String} camelcase string */ camelCase : function(str){ var result = this.__stringsMap[str]; if(!result){ result = str.replace(/\-([a-z])/g, function(match, chr){ return chr.toUpperCase(); }); if(str.indexOf("-") >= 0){ this.__stringsMap[str] = result; }; }; return result; }, /** * Converts a camelcased string to a hyphenated (separated by '-') string. * * Example: * <pre class='javascript'>qx.lang.String.hyphenate("weLikeCookies"); //returns "we-like-cookies"</pre> * * @param str {String} camelcased string * @return {String} hyphenated string */ hyphenate : function(str){ var result = this.__stringsMap[str]; if(!result){ result = str.replace(/[A-Z]/g, function(match){ return ('-' + match.charAt(0).toLowerCase()); }); if(str.indexOf("-") == -1){ this.__stringsMap[str] = result; }; }; return result; }, /** * Converts a string to camel case. * * Example: * <pre class='javascript'>qx.lang.String.camelCase("i like cookies"); //returns "I Like Cookies"</pre> * * @param str {String} any string * @return {String} capitalized string */ capitalize : function(str){ if(this.__unicodeFirstLetterInWordRegexp === null){ var unicodeEscapePrefix = '\\u'; this.__unicodeFirstLetterInWordRegexp = new RegExp("(^|[^" + this.__unicodeLetters.replace(/[0-9A-F]{4}/g, function(match){ return unicodeEscapePrefix + match; }) + "])[" + this.__unicodeLetters.replace(/[0-9A-F]{4}/g, function(match){ return unicodeEscapePrefix + match; }) + "]", "g"); }; return str.replace(this.__unicodeFirstLetterInWordRegexp, function(match){ return match.toUpperCase(); }); }, /** * Removes all extraneous whitespace from a string and trims it * * Example: * * <code> * qx.lang.String.clean(" i like cookies \n\n"); * </code> * * Returns "i like cookies" * * @param str {String} the string to clean up * @return {String} Cleaned up string */ clean : function(str){ return str.replace(/\s+/g, ' ').trim(); }, /** * removes white space from the left side of a string * * @param str {String} the string to trim * @return {String} the trimmed string */ trimLeft : function(str){ return str.replace(/^\s+/, ""); }, /** * removes white space from the right side of a string * * @param str {String} the string to trim * @return {String} the trimmed string */ trimRight : function(str){ return str.replace(/\s+$/, ""); }, /** * removes white space from the left and the right side of a string * * @deprecated {2.1} please use the native trim method. * @param str {String} the string to trim * @return {String} the trimmed string */ trim : function(str){ { }; return str.replace(/^\s+|\s+$/g, ""); }, /** * Check whether the string starts with the given substring * * @param fullstr {String} the string to search in * @param substr {String} the substring to look for * @return {Boolean} whether the string starts with the given substring */ startsWith : function(fullstr, substr){ return fullstr.indexOf(substr) === 0; }, /** * Check whether the string ends with the given substring * * @param fullstr {String} the string to search in * @param substr {String} the substring to look for * @return {Boolean} whether the string ends with the given substring */ endsWith : function(fullstr, substr){ return fullstr.substring(fullstr.length - substr.length, fullstr.length) === substr; }, /** * Returns a string, which repeats a string 'length' times * * @param str {String} string used to repeat * @param times {Integer} the number of repetitions * @return {String} repeated string */ repeat : function(str, times){ return str.length > 0 ? new Array(times + 1).join(str) : ""; }, /** * Pad a string up to a given length. Padding characters are added to the left of the string. * * @param str {String} the string to pad * @param length {Integer} the final length of the string * @param ch {String} character used to fill up the string * @return {String} padded string */ pad : function(str, length, ch){ var padLength = length - str.length; if(padLength > 0){ if(typeof ch === "undefined"){ ch = "0"; }; return this.repeat(ch, padLength) + str; } else { return str; }; }, /** * Convert the first character of the string to upper case. * * @signature function(str) * @param str {String} the string * @return {String} the string with an upper case first character */ firstUp : qx.Bootstrap.firstUp, /** * Convert the first character of the string to lower case. * * @signature function(str) * @param str {String} the string * @return {String} the string with a lower case first character */ firstLow : qx.Bootstrap.firstLow, /** * Check whether the string contains a given substring * * @param str {String} the string * @param substring {String} substring to search for * @return {Boolean} whether the string contains the substring */ contains : function(str, substring){ return str.indexOf(substring) != -1; }, /** * Print a list of arguments using a format string * In the format string occurrences of %n are replaced by the n'th element of the args list. * Example: * <pre class='javascript'>qx.lang.String.format("Hello %1, my name is %2", ["Egon", "Franz"]) == "Hello Egon, my name is Franz"</pre> * * @param pattern {String} format string * @param args {Array} array of arguments to insert into the format string * @return {String} the formatted string */ format : function(pattern, args){ var str = pattern; var i = args.length; while(i--){ // be sure to always use a string for replacement. str = str.replace(new RegExp("%" + (i + 1), "g"), args[i] + ""); }; return str; }, /** * Escapes all chars that have a special meaning in regular expressions * * @param str {String} the string where to escape the chars. * @return {String} the string with the escaped chars. */ escapeRegexpChars : function(str){ return str.replace(/([.*+?^${}()|[\]\/\\])/g, '\\$1'); }, /** * Converts a string to an array of characters. * <pre>"hello" => [ "h", "e", "l", "l", "o" ];</pre> * * @param str {String} the string which should be split * @return {Array} the result array of characters */ toArray : function(str){ return str.split(/\B|\b/g); }, /** * Remove HTML/XML tags from a string * Example: * <pre class='javascript'>qx.lang.String.stripTags("&lt;h1>Hello&lt;/h1>") == "Hello"</pre> * * @param str {String} string containing tags * @return {String} the string with stripped tags */ stripTags : function(str){ return str.replace(/<\/?[^>]+>/gi, ""); }, /** * Strips <script> tags including its content from the given string. * * @param str {String} string containing tags * @param exec {Boolean?false} Whether the filtered code should be executed * @return {String} The filtered string */ stripScripts : function(str, exec){ var scripts = ""; var text = str.replace(/<script[^>]*>([\s\S]*?)<\/script>/gi, function(){ scripts += arguments[1] + '\n'; return ""; }); if(exec === true){ qx.lang.Function.globalEval(scripts); }; return text; }, /** * Quotes the given string. * @param str {String} String to quote. * @return {String} The quoted string. */ quote : function(str){ return '"' + str.replace(/\\/g, "\\\\").replace(/\"/g, "\\\"") + '"'; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2011 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /* ************************************************************************ #ignore(WebKitCSSMatrix) ************************************************************************ */ /** * The purpose of this class is to contain all checks about css. * * This class is used by {@link qx.core.Environment} and should not be used * directly. Please check its class comment for details how to use it. * * @internal */ qx.Bootstrap.define("qx.bom.client.Css", { statics : { __WEBKIT_LEGACY_GRADIENT : null, /** * Checks what box model is used in the current environemnt. * @return {String} It either returns "content" or "border". * @internal */ getBoxModel : function(){ var content = qx.bom.client.Engine.getName() !== "mshtml" || !qx.bom.client.Browser.getQuirksMode(); return content ? "content" : "border"; }, /** * Returns the (possibly vendor-prefixed) name the browser uses for the * <code>textOverflow</code> style property. * * @return {String|null} textOverflow property name or <code>null</code> if * textOverflow is not supported. * @internal */ getTextOverflow : function(){ return qx.bom.Style.getPropertyName("textOverflow"); }, /** * Checks if a placeholder could be used. * @return {Boolean} <code>true</code>, if it could be used. * @internal */ getPlaceholder : function(){ var i = document.createElement("input"); return "placeholder" in i; }, /** * Returns the (possibly vendor-prefixed) name the browser uses for the * <code>appearance</code> style property. * * @return {String|null} appearance property name or <code>null</code> if * appearance is not supported. * @internal */ getAppearance : function(){ return qx.bom.Style.getPropertyName("appearance"); }, /** * Returns the (possibly vendor-prefixed) name the browser uses for the * <code>borderRadius</code> style property. * * @return {String|null} borderRadius property name or <code>null</code> if * borderRadius is not supported. * @internal */ getBorderRadius : function(){ return qx.bom.Style.getPropertyName("borderRadius"); }, /** * Returns the (possibly vendor-prefixed) name the browser uses for the * <code>boxShadow</code> style property. * * @return {String|null} boxShadow property name or <code>null</code> if * boxShadow is not supported. * @internal */ getBoxShadow : function(){ return qx.bom.Style.getPropertyName("boxShadow"); }, /** * Returns the (possibly vendor-prefixed) name the browser uses for the * <code>borderImage</code> style property. * * @return {String|null} borderImage property name or <code>null</code> if * borderImage is not supported. * @internal */ getBorderImage : function(){ return qx.bom.Style.getPropertyName("borderImage"); }, /** * Returns the type of syntax this client supports for its CSS border-image * implementation. Some browsers do not support the "fill" keyword defined * in the W3C draft (http://www.w3.org/TR/css3-background/) and will not * show the border image if it's set. Others follow the standard closely and * will omit the center image if "fill" is not set. * * @return {Boolean|null} <code>true</code> if the standard syntax is supported. * <code>null</code> if the supported syntax could not be detected. * @internal */ getBorderImageSyntax : function(){ var styleName = qx.bom.client.Css.getBorderImage(); if(!styleName){ return null; }; var el = document.createElement("div"); if(styleName === "borderImage"){ // unprefixed implementation: check individual properties el.style[styleName] = 'url("foo.png") 4 4 4 4 fill stretch'; if(el.style.borderImageSource.indexOf("foo.png") >= 0 && el.style.borderImageSlice.indexOf("4 fill") >= 0 && el.style.borderImageRepeat.indexOf("stretch") >= 0){ return true; }; } else { // prefixed implementation, assume no support for "fill" el.style[styleName] = 'url("foo.png") 4 4 4 4 stretch'; // serialized value is unreliable, so just a simple check if(el.style[styleName].indexOf("foo.png") >= 0){ return false; }; }; // unable to determine syntax return null; }, /** * Returns the (possibly vendor-prefixed) name the browser uses for the * <code>userSelect</code> style property. * * @return {String|null} userSelect property name or <code>null</code> if * userSelect is not supported. * @internal */ getUserSelect : function(){ return qx.bom.Style.getPropertyName("userSelect"); }, /** * Returns the (possibly vendor-prefixed) value for the * <code>userSelect</code> style property that disables selection. For Gecko, * "-moz-none" is returned since "none" only makes the target element appear * as if its text could not be selected * * @internal * @return {String|null} the userSelect property value that disables * selection or <code>null</code> if userSelect is not supported */ getUserSelectNone : function(){ var styleProperty = qx.bom.client.Css.getUserSelect(); if(styleProperty){ var el = document.createElement("span"); el.style[styleProperty] = "-moz-none"; return el.style[styleProperty] === "-moz-none" ? "-moz-none" : "none"; }; return null; }, /** * Returns the (possibly vendor-prefixed) name the browser uses for the * <code>userModify</code> style property. * * @return {String|null} userModify property name or <code>null</code> if * userModify is not supported. * @internal */ getUserModify : function(){ return qx.bom.Style.getPropertyName("userModify"); }, /** * Returns the vendor-specific name of the <code>float</code> style property * * @return {String|null} <code>cssFloat</code> for standards-compliant * browsers, <code>styleFloat</code> for legacy IEs, <code>null</code> if * the client supports neither property. * @internal */ getFloat : function(){ var style = document.documentElement.style; return style.cssFloat !== undefined ? "cssFloat" : style.styleFloat !== undefined ? "styleFloat" : null; }, /** * Checks if translate3d can be used. * @return {Boolean} <code>true</code>, if it could be used. * @internal * @lint ignoreUndefined(WebKitCSSMatrix) */ getTranslate3d : function(){ return 'WebKitCSSMatrix' in window && 'm11' in new WebKitCSSMatrix(); }, /** * Returns the (possibly vendor-prefixed) name this client uses for * <code>linear-gradient</code>. * http://dev.w3.org/csswg/css3-images/#linear-gradients * * @return {String|null} Prefixed linear-gradient name or <code>null</code> * if linear gradients are not supported * @internal */ getLinearGradient : function(){ qx.bom.client.Css.__WEBKIT_LEGACY_GRADIENT = false; var value = "linear-gradient(0deg, #fff, #000)"; var el = document.createElement("div"); var style = qx.bom.Style.getAppliedStyle(el, "backgroundImage", value); if(!style){ //try old WebKit syntax (versions 528 - 534.16) value = "-webkit-gradient(linear,0% 0%,100% 100%,from(white), to(red))"; var style = qx.bom.Style.getAppliedStyle(el, "backgroundImage", value, false); if(style){ qx.bom.client.Css.__WEBKIT_LEGACY_GRADIENT = true; }; }; // not supported if(!style){ return null; }; var match = /(.*?)\(/.exec(style); return match ? match[1] : null; }, /** * Returns <code>true</code> if the browser supports setting gradients * using the filter style. This usually only applies for IE browsers * starting from IE5.5. * http://msdn.microsoft.com/en-us/library/ms532997(v=vs.85).aspx * * @return {Boolean} <code>true</code> if supported. * @internal */ getFilterGradient : function(){ return qx.bom.client.Css.__isFilterSupported("DXImageTransform.Microsoft.Gradient", "startColorStr=#550000FF, endColorStr=#55FFFF00"); }, /** * Returns the (possibly vendor-prefixed) name this client uses for * <code>radial-gradient</code>. * * @return {String|null} Prefixed radial-gradient name or <code>null</code> * if radial gradients are not supported * @internal */ getRadialGradient : function(){ var value = "radial-gradient(0px 0px, cover, red 50%, blue 100%)"; var el = document.createElement("div"); var style = qx.bom.Style.getAppliedStyle(el, "backgroundImage", value); if(!style){ return null; }; var match = /(.*?)\(/.exec(style); return match ? match[1] : null; }, /** * Checks if **only** the old WebKit (version < 534.16) syntax for * linear gradients is supported, e.g. * <code>linear-gradient(0deg, #fff, #000)</code> * * @return {Boolean} <code>true</code> if the legacy syntax must be used * @internal */ getLegacyWebkitGradient : function(){ if(qx.bom.client.Css.__WEBKIT_LEGACY_GRADIENT === null){ qx.bom.client.Css.getLinearGradient(); }; return qx.bom.client.Css.__WEBKIT_LEGACY_GRADIENT; }, /** * Checks if rgba colors can be used: * http://www.w3.org/TR/2010/PR-css3-color-20101028/#rgba-color * * @return {Boolean} <code>true</code>, if rgba colors are supported. * @internal */ getRgba : function(){ var el; try{ el = document.createElement("div"); } catch(ex) { el = document.createElement(); }; // try catch for IE try{ el.style["color"] = "rgba(1, 2, 3, 0.5)"; if(el.style["color"].indexOf("rgba") != -1){ return true; }; } catch(ex) { }; return false; }, /** * Returns the (possibly vendor-prefixed) name the browser uses for the * <code>boxSizing</code> style property. * * @return {String|null} boxSizing property name or <code>null</code> if * boxSizing is not supported. * @internal */ getBoxSizing : function(){ return qx.bom.Style.getPropertyName("boxSizing"); }, /** * Returns the browser-specific name used for the <code>display</code> style * property's <code>inline-block</code> value. * * @internal * @return {String|null} */ getInlineBlock : function(){ var el = document.createElement("span"); el.style.display = "inline-block"; if(el.style.display == "inline-block"){ return "inline-block"; }; el.style.display = "-moz-inline-box"; if(el.style.display !== "-moz-inline-box"){ return "-moz-inline-box"; }; return null; }, /** * Checks if CSS opacity is supported * * @internal * @return {Boolean} <code>true</code> if opacity is supported */ getOpacity : function(){ return (typeof document.documentElement.style.opacity == "string"); }, /** * Checks if the overflowX and overflowY style properties are supported * * @internal * @return {Boolean} <code>true</code> if overflow-x and overflow-y can be * used * @deprecated {2.1} */ getOverflowXY : function(){ return (typeof document.documentElement.style.overflowX == "string") && (typeof document.documentElement.style.overflowY == "string"); }, /** * Checks if CSS texShadow is supported * * @internal * @return {Boolean} <code>true</code> if textShadow is supported */ getTextShadow : function(){ return !!qx.bom.Style.getPropertyName("textShadow"); }, /** * Returns <code>true</code> if the browser supports setting text shadow * using the filter style. This usually only applies for IE browsers * starting from IE5.5. * * @internal * @return {Boolean} <code>true</code> if textShadow is supported */ getFilterTextShadow : function(){ return qx.bom.client.Css.__isFilterSupported("DXImageTransform.Microsoft.Shadow", "color=#666666,direction=45"); }, /** * Checks if the given filter is supported. * * @param filterClass {String} The name of the filter class * @param initParams {String} Init values for the filter * @return {Boolean} <code>true</code> if the given filter is supported */ __isFilterSupported : function(filterClass, initParams){ var supported = false; var value = "progid:" + filterClass + "(" + initParams + ");"; var el = document.createElement("div"); document.body.appendChild(el); el.style.filter = value; if(el.filters && el.filters.length > 0 && el.filters.item(filterClass).enabled == true){ supported = true; }; document.body.removeChild(el); return supported; } }, defer : function(statics){ qx.core.Environment.add("css.textoverflow", statics.getTextOverflow); qx.core.Environment.add("css.placeholder", statics.getPlaceholder); qx.core.Environment.add("css.borderradius", statics.getBorderRadius); qx.core.Environment.add("css.boxshadow", statics.getBoxShadow); qx.core.Environment.add("css.gradient.linear", statics.getLinearGradient); qx.core.Environment.add("css.gradient.filter", statics.getFilterGradient); qx.core.Environment.add("css.gradient.radial", statics.getRadialGradient); qx.core.Environment.add("css.gradient.legacywebkit", statics.getLegacyWebkitGradient); qx.core.Environment.add("css.boxmodel", statics.getBoxModel); qx.core.Environment.add("css.rgba", statics.getRgba); qx.core.Environment.add("css.borderimage", statics.getBorderImage); qx.core.Environment.add("css.borderimage.standardsyntax", statics.getBorderImageSyntax); qx.core.Environment.add("css.usermodify", statics.getUserModify); qx.core.Environment.add("css.userselect", statics.getUserSelect); qx.core.Environment.add("css.userselect.none", statics.getUserSelectNone); qx.core.Environment.add("css.appearance", statics.getAppearance); qx.core.Environment.add("css.float", statics.getFloat); qx.core.Environment.add("css.boxsizing", statics.getBoxSizing); qx.core.Environment.add("css.inlineblock", statics.getInlineBlock); qx.core.Environment.add("css.opacity", statics.getOpacity); qx.core.Environment.add("css.overflowxy", statics.getOverflowXY); qx.core.Environment.add("css.textShadow", statics.getTextShadow); qx.core.Environment.add("css.textShadow.filter", statics.getFilterTextShadow); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2011 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) * Sebastian Fastner (fastner) ************************************************************************ */ /** * This class is responsible for checking the operating systems name. * * This class is used by {@link qx.core.Environment} and should not be used * directly. Please check its class comment for details how to use it. * * @internal */ qx.Bootstrap.define("qx.bom.client.OperatingSystem", { statics : { /** * Checks for the name of the operating system. * @return {String} The name of the operating system. * @internal */ getName : function(){ if(!navigator){ return ""; }; var input = navigator.platform || ""; var agent = navigator.userAgent || ""; if(input.indexOf("Windows") != -1 || input.indexOf("Win32") != -1 || input.indexOf("Win64") != -1){ return "win"; } else if(input.indexOf("Macintosh") != -1 || input.indexOf("MacPPC") != -1 || input.indexOf("MacIntel") != -1 || input.indexOf("Mac OS X") != -1){ return "osx"; } else if(agent.indexOf("RIM Tablet OS") != -1){ return "rim_tabletos"; } else if(agent.indexOf("webOS") != -1){ return "webos"; } else if(input.indexOf("iPod") != -1 || input.indexOf("iPhone") != -1 || input.indexOf("iPad") != -1){ return "ios"; } else if(agent.indexOf("Android") != -1){ return "android"; } else if(input.indexOf("Linux") != -1){ return "linux"; } else if(input.indexOf("X11") != -1 || input.indexOf("BSD") != -1 || input.indexOf("Darwin") != -1){ return "unix"; } else if(input.indexOf("SymbianOS") != -1){ return "symbian"; } else if(input.indexOf("BlackBerry") != -1){ return "blackberry"; };;;;;;;;; // don't know return ""; }, /** Maps user agent names to system IDs */ __ids : { // Windows "Windows NT 6.3" : "8.1", "Windows NT 6.2" : "8", "Windows NT 6.1" : "7", "Windows NT 6.0" : "vista", "Windows NT 5.2" : "2003", "Windows NT 5.1" : "xp", "Windows NT 5.0" : "2000", "Windows 2000" : "2000", "Windows NT 4.0" : "nt4", "Win 9x 4.90" : "me", "Windows CE" : "ce", "Windows 98" : "98", "Win98" : "98", "Windows 95" : "95", "Win95" : "95", // OS X "Mac OS X 10_9" : "10.9", "Mac OS X 10.9" : "10.9", "Mac OS X 10_8" : "10.8", "Mac OS X 10.8" : "10.8", "Mac OS X 10_7" : "10.7", "Mac OS X 10.7" : "10.7", "Mac OS X 10_6" : "10.6", "Mac OS X 10.6" : "10.6", "Mac OS X 10_5" : "10.5", "Mac OS X 10.5" : "10.5", "Mac OS X 10_4" : "10.4", "Mac OS X 10.4" : "10.4", "Mac OS X 10_3" : "10.3", "Mac OS X 10.3" : "10.3", "Mac OS X 10_2" : "10.2", "Mac OS X 10.2" : "10.2", "Mac OS X 10_1" : "10.1", "Mac OS X 10.1" : "10.1", "Mac OS X 10_0" : "10.0", "Mac OS X 10.0" : "10.0" }, /** * Checks for the version of the operating system using the internal map. * * @internal * @return {String} The version as strin or an empty string if the version * could not be detected. */ getVersion : function(){ var version = qx.bom.client.OperatingSystem.__getVersionForDesktopOs(navigator.userAgent); if(version == null){ version = qx.bom.client.OperatingSystem.__getVersionForMobileOs(navigator.userAgent); }; if(version != null){ return version; } else { return ""; }; }, /** * Detect OS version for desktop devices * @param userAgent {String} userAgent parameter, needed for detection. * @return {String} version number as string or null. */ __getVersionForDesktopOs : function(userAgent){ var str = []; for(var key in qx.bom.client.OperatingSystem.__ids){ str.push(key); }; var reg = new RegExp("(" + str.join("|").replace(/\./g, "\.") + ")", "g"); var match = reg.exec(userAgent); if(match && match[1]){ return qx.bom.client.OperatingSystem.__ids[match[1]]; }; return null; }, /** * Detect OS version for mobile devices * @param userAgent {String} userAgent parameter, needed for detection. * @return {String} version number as string or null. */ __getVersionForMobileOs : function(userAgent){ var android = userAgent.indexOf("Android") != -1; var iOs = userAgent.match(/(iPad|iPhone|iPod)/i) ? true : false; if(android){ var androidVersionRegExp = new RegExp(/ Android (\d+(?:\.\d+)+)/i); var androidMatch = androidVersionRegExp.exec(userAgent); if(androidMatch && androidMatch[1]){ return androidMatch[1]; }; } else if(iOs){ var iOsVersionRegExp = new RegExp(/(CPU|iPhone|iPod) OS (\d+)_(\d+)\s+/); var iOsMatch = iOsVersionRegExp.exec(userAgent); if(iOsMatch && iOsMatch[2] && iOsMatch[3]){ return iOsMatch[2] + "." + iOsMatch[3]; }; }; return null; } }, defer : function(statics){ qx.core.Environment.add("os.name", statics.getName); qx.core.Environment.add("os.version", statics.getVersion); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Christian Hagendorn (chris_schmidt) * Martin Wittemann (martinwittemann) ====================================================================== This class contains code from: Copyright: 2009 Deutsche Telekom AG, Germany, http://telekom.com License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php Authors: * Sebastian Werner (wpbasti) ====================================================================== This class contains code from: Copyright: 2011 Pocket Widget S.L., Spain, http://www.pocketwidget.com License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php Authors: * Javier Martinez Villacampa ************************************************************************ */ /** #require(qx.bom.client.OperatingSystem#getVersion) */ /** * Basic browser detection for qooxdoo. * * This class is used by {@link qx.core.Environment} and should not be used * directly. Please check its class comment for details how to use it. * * @internal */ qx.Bootstrap.define("qx.bom.client.Browser", { statics : { /** * Checks for the name of the browser and returns it. * @return {String} The name of the current browser. * @internal */ getName : function(){ var agent = navigator.userAgent; var reg = new RegExp("(" + qx.bom.client.Browser.__agents + ")(/| )([0-9]+\.[0-9])"); var match = agent.match(reg); if(!match){ return ""; }; var name = match[1].toLowerCase(); var engine = qx.bom.client.Engine.getName(); if(engine === "webkit"){ if(name === "android"){ // Fix Chrome name (for instance wrongly defined in user agent on Android 1.6) name = "mobile chrome"; } else if(agent.indexOf("Mobile Safari") !== -1 || agent.indexOf("Mobile/") !== -1){ // Fix Safari name name = "mobile safari"; }; } else if(engine === "mshtml"){ // IE 11's ua string no longer contains "MSIE" or even "IE" if(name === "msie" || name === "trident"){ name = "ie"; // Fix IE mobile before Microsoft added IEMobile string if(qx.bom.client.OperatingSystem.getVersion() === "ce"){ name = "iemobile"; }; }; } else if(engine === "opera"){ if(name === "opera mobi"){ name = "operamobile"; } else if(name === "opera mini"){ name = "operamini"; }; } else if(engine === "gecko"){ if(agent.indexOf("Maple") !== -1){ name = "maple"; }; };;; return name; }, /** * Determines the version of the current browser. * @return {String} The name of the current browser. * @internal */ getVersion : function(){ var agent = navigator.userAgent; var reg = new RegExp("(" + qx.bom.client.Browser.__agents + ")(/| )([0-9]+\.[0-9])"); var match = agent.match(reg); if(!match){ return ""; }; var name = match[1].toLowerCase(); var version = match[3]; // Support new style version string used by Opera and Safari if(agent.match(/Version(\/| )([0-9]+\.[0-9])/)){ version = RegExp.$2; }; if(qx.bom.client.Engine.getName() == "mshtml"){ // Use the Engine version, because IE8 and higher change the user agent // string to an older version in compatibility mode version = qx.bom.client.Engine.getVersion(); if(name === "msie" && qx.bom.client.OperatingSystem.getVersion() == "ce"){ // Fix IE mobile before Microsoft added IEMobile string version = "5.0"; }; }; if(qx.bom.client.Browser.getName() == "maple"){ // Fix version detection for Samsung Smart TVs Maple browser from 2010 and 2011 models reg = new RegExp("(Maple )([0-9]+\.[0-9]+\.[0-9]*)"); match = agent.match(reg); if(!match){ return ""; }; version = match[2]; }; return version; }, /** * Returns in which document mode the current document is (only for IE). * * @internal * @return {Number} The mode in which the browser is. */ getDocumentMode : function(){ if(document.documentMode){ return document.documentMode; }; return 0; }, /** * Check if in quirks mode. * * @internal * @return {Boolean} <code>true</code>, if the environment is in quirks mode */ getQuirksMode : function(){ if(qx.bom.client.Engine.getName() == "mshtml" && parseFloat(qx.bom.client.Engine.getVersion()) >= 8){ return qx.bom.client.Engine.DOCUMENT_MODE === 5; } else { return document.compatMode !== "CSS1Compat"; }; }, /** * Internal helper map for picking the right browser names to check. */ __agents : { // Safari should be the last one to check, because some other Webkit-based browsers // use this identifier together with their own one. // "Version" is used in Safari 4 to define the Safari version. After "Safari" they place the // Webkit version instead. Silly. // Palm Pre uses both Safari (contains Webkit version) and "Version" contains the "Pre" version. But // as "Version" is not Safari here, we better detect this as the Pre-Browser version. So place // "Pre" in front of both "Version" and "Safari". "webkit" : "AdobeAIR|Titanium|Fluid|Chrome|Android|Epiphany|Konqueror|iCab|OmniWeb|Maxthon|Pre|Mobile Safari|Safari", // Better security by keeping Firefox the last one to match "gecko" : "prism|Fennec|Camino|Kmeleon|Galeon|Netscape|SeaMonkey|Namoroka|Firefox", // No idea what other browsers based on IE's engine "mshtml" : "IEMobile|Maxthon|MSIE|Trident", // Keep "Opera" the last one to correctly prefer/match the mobile clients "opera" : "Opera Mini|Opera Mobi|Opera" }[qx.bom.client.Engine.getName()] }, defer : function(statics){ qx.core.Environment.add("browser.name", statics.getName),qx.core.Environment.add("browser.version", statics.getVersion),qx.core.Environment.add("browser.documentmode", statics.getDocumentMode),qx.core.Environment.add("browser.quirksmode", statics.getQuirksMode); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2011 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) * Daniel Wagner (danielwagner) ************************************************************************ */ /** * Responsible class for everything concerning styles without the need of * an element. * * If you want to query or modify styles of HTML elements, * take a look at {@link qx.bom.element.Style}. */ qx.Bootstrap.define("qx.bom.Style", { statics : { /** Vendor-specific style property prefixes */ VENDOR_PREFIXES : ["Webkit", "Moz", "O", "ms", "Khtml"], /** * Internal lookup table to map property names to CSS names * @internal */ __cssName : { }, /** * Takes the name of a style property and returns the name the browser uses * for its implementation, which might include a vendor prefix. * * @param propertyName {String} Style property name to check * @return {String|null} The supported property name or <code>null</code> if * not supported */ getPropertyName : function(propertyName){ var style = document.documentElement.style; if(style[propertyName] !== undefined){ return propertyName; }; for(var i = 0,l = this.VENDOR_PREFIXES.length;i < l;i++){ var prefixedProp = this.VENDOR_PREFIXES[i] + qx.lang.String.firstUp(propertyName); if(style[prefixedProp] !== undefined){ return prefixedProp; }; }; return null; }, /** * Takes the name of a JavaScript style property and returns the * corresponding CSS name. * * The name of the style property is taken as is, i.e. it gets not * extended by vendor prefixes. The conversion into the CSS name is * done by string manipulation, not involving the DOM. * * Example: * <pre class='javascript'>qx.bom.Style.getCssName("MozTransform"); //returns "-moz-transform"</pre> * * @param propertyName {String} JavaScript style property * @return {String} CSS property */ getCssName : function(propertyName){ var cssName = this.__cssName[propertyName]; if(!cssName){ // all vendor prefixes (except for "ms") start with an uppercase letter cssName = propertyName.replace(/[A-Z]/g, function(match){ return ('-' + match.charAt(0).toLowerCase()); }); // lowercase "ms" vendor prefix needs special handling if((/^ms/.test(cssName))){ cssName = "-" + cssName; }; this.__cssName[propertyName] = cssName; }; return cssName; }, /** * Detects CSS support by applying a style to a DOM element of the given type * and verifying the result. Also checks for vendor-prefixed variants of the * value, e.g. "linear-gradient" -> "-webkit-linear-gradient". Returns the * (possibly vendor-prefixed) value if successful or <code>null</code> if * the property and/or value are not supported. * * @param element {Element} element to be used for the detection * @param propertyName {String} the style property to be tested * @param value {String} style property value to be tested * @param prefixed {Boolean?} try to determine the appropriate vendor prefix * for the value. Default: <code>true</code> * @return {String|null} prefixed style value or <code>null</code> if not supported * @internal */ getAppliedStyle : function(element, propertyName, value, prefixed){ var vendorPrefixes = (prefixed !== false) ? [null].concat(this.VENDOR_PREFIXES) : [null]; for(var i = 0,l = vendorPrefixes.length;i < l;i++){ var prefixedVal = vendorPrefixes[i] ? "-" + vendorPrefixes[i].toLowerCase() + "-" + value : value; // IE might throw an exception try{ element.style[propertyName] = prefixedVal; if(typeof element.style[propertyName] == "string" && element.style[propertyName] !== ""){ return prefixedVal; }; } catch(ex) { }; }; return null; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Christian Hagendorn (chris_schmidt) ====================================================================== This class contains code based on the following work: * Prototype JS http://www.prototypejs.org/ Version 1.5 Copyright: (c) 2006-2007, Prototype Core Team License: MIT: http://www.opensource.org/licenses/mit-license.php Authors: * Prototype Core Team ---------------------------------------------------------------------- Copyright (c) 2005-2008 Sam Stephenson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ************************************************************************ */ /** * Cross-browser opacity support. * * Optimized for animations (contains workarounds for typical flickering * in some browsers). Reduced class dependencies for optimal size and * performance. */ qx.Bootstrap.define("qx.bom.element.Opacity", { statics : { /** * {Boolean} <code>true</code> when the style attribute "opacity" is supported, * <code>false</code> otherwise. * @deprecated {2.1} Please use qx.core.Environment.get("css.opacity") instead. */ SUPPORT_CSS3_OPACITY : false, /** * Compiles the given opacity value into a cross-browser CSS string. * Accepts numbers between zero and one * where "0" means transparent, "1" means opaque. * * @signature function(opacity) * @param opacity {Float} A float number between 0 and 1 * @return {String} CSS compatible string */ compile : qx.core.Environment.select("engine.name", { "mshtml" : function(opacity){ if(opacity >= 1){ opacity = 1; }; if(opacity < 0.00001){ opacity = 0; }; if(qx.core.Environment.get("css.opacity")){ return "opacity:" + opacity + ";"; } else { return "zoom:1;filter:alpha(opacity=" + (opacity * 100) + ");"; }; }, "default" : function(opacity){ if(opacity >= 1){ return ""; }; return "opacity:" + opacity + ";"; } }), /** * Sets opacity of given element. Accepts numbers between zero and one * where "0" means transparent, "1" means opaque. * * @param element {Element} DOM element to modify * @param opacity {Float} A float number between 0 and 1 * @signature function(element, opacity) */ set : qx.core.Environment.select("engine.name", { "mshtml" : function(element, opacity){ if(qx.core.Environment.get("css.opacity")){ if(opacity >= 1){ opacity = ""; }; element.style.opacity = opacity; } else { // Read in computed filter var filter = qx.bom.element.Style.get(element, "filter", qx.bom.element.Style.COMPUTED_MODE, false); if(opacity >= 1){ opacity = 1; }; if(opacity < 0.00001){ opacity = 0; }; // IE has trouble with opacity if it does not have layout (hasLayout) // Force it by setting the zoom level if(!element.currentStyle || !element.currentStyle.hasLayout){ element.style.zoom = 1; }; // Remove old alpha filter and add new one element.style.filter = filter.replace(/alpha\([^\)]*\)/gi, "") + "alpha(opacity=" + opacity * 100 + ")"; }; }, "default" : function(element, opacity){ if(opacity >= 1){ opacity = ""; }; element.style.opacity = opacity; } }), /** * Resets opacity of given element. * * @param element {Element} DOM element to modify * @signature function(element) */ reset : qx.core.Environment.select("engine.name", { "mshtml" : function(element){ if(qx.core.Environment.get("css.opacity")){ element.style.opacity = ""; } else { // Read in computed filter var filter = qx.bom.element.Style.get(element, "filter", qx.bom.element.Style.COMPUTED_MODE, false); // Remove old alpha filter element.style.filter = filter.replace(/alpha\([^\)]*\)/gi, ""); }; }, "default" : function(element){ element.style.opacity = ""; } }), /** * Gets computed opacity of given element. Accepts numbers between zero and one * where "0" means transparent, "1" means opaque. * * @param element {Element} DOM element to modify * @param mode {Number} Choose one of the modes {@link qx.bom.element.Style#COMPUTED_MODE}, * {@link qx.bom.element.Style#CASCADED_MODE}, {@link qx.bom.element.Style#LOCAL_MODE}. * The computed mode is the default one. * @return {Float} A float number between 0 and 1 * @signature function(element, mode) */ get : qx.core.Environment.select("engine.name", { "mshtml" : function(element, mode){ if(qx.core.Environment.get("css.opacity")){ var opacity = qx.bom.element.Style.get(element, "opacity", mode, false); if(opacity != null){ return parseFloat(opacity); }; return 1.0; } else { var filter = qx.bom.element.Style.get(element, "filter", mode, false); if(filter){ var opacity = filter.match(/alpha\(opacity=(.*)\)/); if(opacity && opacity[1]){ return parseFloat(opacity[1]) / 100; }; }; return 1.0; }; }, "default" : function(element, mode){ var opacity = qx.bom.element.Style.get(element, "opacity", mode, false); if(opacity != null){ return parseFloat(opacity); }; return 1.0; } }) }, // @deprecated {2.1} defer : function(statics){ statics.SUPPORT_CSS3_OPACITY = qx.core.Environment.get("css.opacity"); } }); { }; /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) ************************************************************************ */ /* ************************************************************************ #require(qx.lang.normalize.String) ************************************************************************ */ /** * Contains methods to control and query the element's clip property */ qx.Bootstrap.define("qx.bom.element.Clip", { /* ***************************************************************************** STATICS ***************************************************************************** */ statics : { /** * Compiles the given clipping into a CSS compatible string. This * is a simple square which describes the visible area of an DOM element. * Changing the clipping does not change the dimensions of * an element. * * @param map {Map} Map which contains <code>left</code>, <code>top</code> * <code>width</code> and <code>height</code> of the clipped area. * @return {String} CSS compatible string */ compile : function(map){ if(!map){ return "clip:auto;"; }; var left = map.left; var top = map.top; var width = map.width; var height = map.height; var right,bottom; if(left == null){ right = (width == null ? "auto" : width + "px"); left = "auto"; } else { right = (width == null ? "auto" : left + width + "px"); left = left + "px"; }; if(top == null){ bottom = (height == null ? "auto" : height + "px"); top = "auto"; } else { bottom = (height == null ? "auto" : top + height + "px"); top = top + "px"; }; return "clip:rect(" + top + "," + right + "," + bottom + "," + left + ");"; }, /** * Gets the clipping of the given element. * * @param element {Element} DOM element to query * @param mode {Number} Choose one of the modes {@link qx.bom.element.Style#COMPUTED_MODE}, * {@link qx.bom.element.Style#CASCADED_MODE}, {@link qx.bom.element.Style#LOCAL_MODE}. * The computed mode is the default one. * @return {Map} Map which contains <code>left</code>, <code>top</code> * <code>width</code> and <code>height</code> of the clipped area. * Each one could be null or any integer value. */ get : function(element, mode){ var clip = qx.bom.element.Style.get(element, "clip", mode, false); var left,top,width,height; var right,bottom; if(typeof clip === "string" && clip !== "auto" && clip !== ""){ clip = clip.trim(); // Do not use "global" here. This will break Firefox because of // an issue that the lastIndex will not be resetted on separate calls. if(/\((.*)\)/.test(clip)){ var result = RegExp.$1; // Process result // Some browsers store values space-separated, others comma-separated. // Handle both cases by means of feature-detection. if(/,/.test(result)){ var split = result.split(","); } else { var split = result.split(" "); }; top = split[0].trim(); right = split[1].trim(); bottom = split[2].trim(); left = split[3].trim(); // Normalize "auto" to null if(left === "auto"){ left = null; }; if(top === "auto"){ top = null; }; if(right === "auto"){ right = null; }; if(bottom === "auto"){ bottom = null; }; // Convert to integer values if(top != null){ top = parseInt(top, 10); }; if(right != null){ right = parseInt(right, 10); }; if(bottom != null){ bottom = parseInt(bottom, 10); }; if(left != null){ left = parseInt(left, 10); }; // Compute width and height if(right != null && left != null){ width = right - left; } else if(right != null){ width = right; }; if(bottom != null && top != null){ height = bottom - top; } else if(bottom != null){ height = bottom; }; } else { throw new Error("Could not parse clip string: " + clip); }; }; // Return map when any value is available. return { left : left || null, top : top || null, width : width || null, height : height || null }; }, /** * Sets the clipping of the given element. This is a simple * square which describes the visible area of an DOM element. * Changing the clipping does not change the dimensions of * an element. * * @param element {Element} DOM element to modify * @param map {Map} A map with one or more of these available keys: * <code>left</code>, <code>top</code>, <code>width</code>, <code>height</code>. */ set : function(element, map){ if(!map){ element.style.clip = "rect(auto,auto,auto,auto)"; return; }; var left = map.left; var top = map.top; var width = map.width; var height = map.height; var right,bottom; if(left == null){ right = (width == null ? "auto" : width + "px"); left = "auto"; } else { right = (width == null ? "auto" : left + width + "px"); left = left + "px"; }; if(top == null){ bottom = (height == null ? "auto" : height + "px"); top = "auto"; } else { bottom = (height == null ? "auto" : top + height + "px"); top = top + "px"; }; element.style.clip = "rect(" + top + "," + right + "," + bottom + "," + left + ")"; }, /** * Resets the clipping of the given DOM element. * * @param element {Element} DOM element to modify */ reset : function(element){ element.style.clip = "rect(auto, auto, auto, auto)"; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) ************************************************************************ */ /** * Contains methods to control and query the element's cursor property */ qx.Bootstrap.define("qx.bom.element.Cursor", { /* ***************************************************************************** STATICS ***************************************************************************** */ statics : { /** Internal helper structure to map cursor values to supported ones */ __map : { }, /** * Compiles the given cursor into a CSS compatible string. * * @param cursor {String} Valid CSS cursor name * @return {String} CSS string */ compile : function(cursor){ return "cursor:" + (this.__map[cursor] || cursor) + ";"; }, /** * Returns the computed cursor style for the given element. * * @param element {Element} The element to query * @param mode {Number} Choose one of the modes {@link qx.bom.element.Style#COMPUTED_MODE}, * {@link qx.bom.element.Style#CASCADED_MODE}, {@link qx.bom.element.Style#LOCAL_MODE}. * The computed mode is the default one. * @return {String} Computed cursor value of the given element. */ get : function(element, mode){ return qx.bom.element.Style.get(element, "cursor", mode, false); }, /** * Applies a new cursor style to the given element * * @param element {Element} The element to modify * @param value {String} New cursor value to set */ set : function(element, value){ element.style.cursor = this.__map[value] || value; }, /** * Removes the local cursor style applied to the element * * @param element {Element} The element to modify */ reset : function(element){ element.style.cursor = ""; } }, defer : function(statics){ // < IE 9 if(qx.core.Environment.get("engine.name") == "mshtml" && ((parseFloat(qx.core.Environment.get("engine.version")) < 9 || qx.core.Environment.get("browser.documentmode") < 9) && !qx.core.Environment.get("browser.quirksmode"))){ statics.__map["nesw-resize"] = "ne-resize"; statics.__map["nwse-resize"] = "nw-resize"; // < IE 8 if(((parseFloat(qx.core.Environment.get("engine.version")) < 8 || qx.core.Environment.get("browser.documentmode") < 8) && !qx.core.Environment.get("browser.quirksmode"))){ statics.__map["ew-resize"] = "e-resize"; statics.__map["ns-resize"] = "n-resize"; }; } else if(qx.core.Environment.get("engine.name") == "opera" && parseInt(qx.core.Environment.get("engine.version")) < 12){ statics.__map["nesw-resize"] = "ne-resize"; statics.__map["nwse-resize"] = "nw-resize"; }; } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /** * This class takes care of the normalization of the native 'Object' object. * Therefore it checks the availability of the following methods and appends * it, if not available. This means you can use the methods during * development in every browser. For usage samples, check out the attached links. * * *keys*: * <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/keys">MDN documentation</a> | * <a href="http://es5.github.com/#x15.2.3.14">Annotated ES5 Spec</a> */ qx.Bootstrap.define("qx.lang.normalize.Object", { defer : function(){ // keys if(!qx.core.Environment.get("ecmascript.object.keys")){ Object.keys = qx.Bootstrap.keys; }; } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Andreas Ecker (ecker) ************************************************************************ */ /* ************************************************************************ #require(qx.lang.normalize.Object) ************************************************************************ */ /** * Helper functions to handle Object as a Hash map. */ qx.Bootstrap.define("qx.lang.Object", { statics : { /** * Clears the map from all values * * @param map {Object} the map to clear */ empty : function(map){ { }; for(var key in map){ if(map.hasOwnProperty(key)){ delete map[key]; }; }; }, /** * Check if the hash has any keys * * @signature function(map) * @param map {Object} the map to check * @return {Boolean} whether the map has any keys * @lint ignoreUnused(key) */ isEmpty : function(map){ { }; for(var key in map){ return false; }; return true; }, /** * Check whether the number of objects in the maps is at least "length" * * @signature function(map, minLength) * @param map {Object} the map to check * @param minLength {Integer} minimum number of objects in the map * @deprecated {2.1} Please use a check and 'qx.lang.Object.getLength'. * @return {Boolean} whether the map contains at least "length" objects. * @lint ignoreUnused(key) */ hasMinLength : function(map, minLength){ { }; if(minLength <= 0){ return true; }; var length = 0; for(var key in map){ if((++length) >= minLength){ return true; }; }; return false; }, /** * Get the number of objects in the map * * @signature function(map) * @param map {Object} the map * @return {Integer} number of objects in the map */ getLength : qx.Bootstrap.objectGetLength, /** * Get the keys of a map as array as returned by a "for ... in" statement. * * @deprecated {2.1.} Please use Object.keys instead. * @signature function(map) * @param map {Object} the map * @return {Array} array of the keys of the map */ getKeys : qx.Bootstrap.getKeys, /** * Get the keys of a map as string * * @signature function(map) * @param map {Object} the map * @deprecated {2.1} Object.keys(map).join(). * @return {String} String of the keys of the map * The keys are separated by ", " */ getKeysAsString : qx.Bootstrap.getKeysAsString, /** * Get the values of a map as array * * @param map {Object} the map * @return {Array} array of the values of the map */ getValues : function(map){ { }; var arr = []; var keys = Object.keys(map); for(var i = 0,l = keys.length;i < l;i++){ arr.push(map[keys[i]]); }; return arr; }, /** * Inserts all keys of the source object into the * target objects. Attention: The target map gets modified. * * @signature function(target, source, overwrite) * @param target {Object} target object * @param source {Object} object to be merged * @param overwrite {Boolean ? true} If enabled existing keys will be overwritten * @return {Object} Target with merged values from the source object */ mergeWith : qx.Bootstrap.objectMergeWith, /** * Inserts all key/value pairs of the source object into the * target object but doesn't override existing keys * * @param target {Object} target object * @param source {Object} object to be merged * @return {Object} target with merged values from source * @deprecated {2.1} please use mergeWith instead with override set to false */ carefullyMergeWith : function(target, source){ { }; return qx.lang.Object.mergeWith(target, source, false); }, /** * Merge a number of objects. * * @param target {Object} target object * @param varargs {Object} variable number of objects to merged with target * @return {Object} target with merged values from the other objects * @deprecated {2.1} Please use mergeWith instead. */ merge : function(target, varargs){ { }; var len = arguments.length; for(var i = 1;i < len;i++){ qx.lang.Object.mergeWith(target, arguments[i]); }; return target; }, /** * Return a copy of an Object * * @param source {Object} Object to copy * @param deep {Boolean} If the clone should be a deep clone. * @return {Object} A copy of the object */ clone : function(source, deep){ if(qx.lang.Type.isObject(source)){ var clone = { }; for(var key in source){ if(deep){ clone[key] = qx.lang.Object.clone(source[key], deep); } else { clone[key] = source[key]; }; }; return clone; } else if(qx.lang.Type.isArray(source)){ var clone = []; for(var i = 0;i < source.length;i++){ if(deep){ clone[i] = qx.lang.Object.clone(source[i]); } else { clone[i] = source[i]; }; }; return clone; }; return source; }, /** * Inverts a map by exchanging the keys with the values. * * If the map has the same values for different keys, information will get lost. * The values will be converted to strings using the toString methods. * * @param map {Object} Map to invert * @return {Object} inverted Map */ invert : function(map){ { }; var result = { }; for(var key in map){ result[map[key].toString()] = key; }; return result; }, /** * Get the key of the given value from a map. * If the map has more than one key matching the value, the first match is returned. * If the map does not contain the value, <code>null</code> is returned. * * @param map {Object} Map to search for the key * @param value {var} Value to look for * @return {String|null} Name of the key (null if not found). */ getKeyFromValue : function(map, value){ { }; for(var key in map){ if(map.hasOwnProperty(key) && map[key] === value){ return key; }; }; return null; }, /** * Whether the map contains the given value. * * @param map {Object} Map to search for the value * @param value {var} Value to look for * @return {Boolean} Whether the value was found in the map. */ contains : function(map, value){ { }; return this.getKeyFromValue(map, value) !== null; }, /** * Selects the value with the given key from the map. * * @param key {String} name of the key to get the value from * @param map {Object} map to get the value from * @return {var} value for the given key from the map * @deprecated {2.1} */ select : function(key, map){ { }; { }; return map[key]; }, /** * Convert an array into a map. * * All elements of the array become keys of the returned map by * calling <code>toString</code> on the array elements. The values of the * map are set to <code>true</code> * * @param array {Array} array to convert * @return {Map} the array converted to a map. */ fromArray : function(array){ { }; var obj = { }; for(var i = 0,l = array.length;i < l;i++){ { }; obj[array[i].toString()] = true; }; return obj; }, /** * Serializes an object to URI parameters (also known as query string). * * Escapes characters that have a special meaning in URIs as well as * umlauts. Uses the global function encodeURIComponent, see * https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/encodeURIComponent * * Note: For URI parameters that are to be sent as * application/x-www-form-urlencoded (POST), spaces should be encoded * with "+". * * @param obj {Object} Object to serialize. * @param post {Boolean} Whether spaces should be encoded with "+". * @return {String} Serialized object. Safe to append to URIs or send as * URL encoded string. * @deprecated {2.1} Please use qx.util.Uri.toParameter instead. */ toUriParameter : function(obj, post){ { }; return qx.util.Uri.toParameter(obj, post); } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2011 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Tristan Koch (tristankoch) ************************************************************************ */ /** * Static helpers for parsing and modifying URIs. */ qx.Bootstrap.define("qx.util.Uri", { statics : { /** * Split URL * * Code taken from: * parseUri 1.2.2 * (c) Steven Levithan <stevenlevithan.com> * MIT License * * * @param str {String} String to parse as URI * @param strict {Boolean} Whether to parse strictly by the rules * @return {Object} Map with parts of URI as properties */ parseUri : function(str, strict){ var options = { key : ["source", "protocol", "authority", "userInfo", "user", "password", "host", "port", "relative", "path", "directory", "file", "query", "anchor"], q : { name : "queryKey", parser : /(?:^|&)([^&=]*)=?([^&]*)/g }, parser : { strict : /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/, loose : /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/ } }; var o = options,m = options.parser[strict ? "strict" : "loose"].exec(str),uri = { },i = 14; while(i--){ uri[o.key[i]] = m[i] || ""; }; uri[o.q.name] = { }; uri[o.key[12]].replace(o.q.parser, function($0, $1, $2){ if($1){ uri[o.q.name][$1] = $2; }; }); return uri; }, /** * Append string to query part of URL. Respects existing query. * * @param url {String} URL to append string to. * @param params {String} Parameters to append to URL. * @return {String} URL with string appended in query part. */ appendParamsToUrl : function(url, params){ if(params === undefined){ return url; }; { }; if(qx.lang.Type.isObject(params)){ params = qx.util.Uri.toParameter(params); }; if(!params){ return url; }; return url += (/\?/).test(url) ? "&" + params : "?" + params; }, /** * Serializes an object to URI parameters (also known as query string). * * Escapes characters that have a special meaning in URIs as well as * umlauts. Uses the global function encodeURIComponent, see * https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/encodeURIComponent * * Note: For URI parameters that are to be sent as * application/x-www-form-urlencoded (POST), spaces should be encoded * with "+". * * @param obj {Object} Object to serialize. * @param post {Boolean} Whether spaces should be encoded with "+". * @return {String} Serialized object. Safe to append to URIs or send as * URL encoded string. */ toParameter : function(obj, post){ var key,parts = []; for(key in obj){ if(obj.hasOwnProperty(key)){ var value = obj[key]; if(value instanceof Array){ for(var i = 0;i < value.length;i++){ this.__toParameterPair(key, value[i], parts, post); }; } else { this.__toParameterPair(key, value, parts, post); }; }; }; return parts.join("&"); }, /** * Encodes key/value to URI safe string and pushes to given array. * * @param key {String} Key. * @param value {String} Value. * @param parts {Array} Array to push to. * @param post {Boolean} Whether spaces should be encoded with "+". */ __toParameterPair : function(key, value, parts, post){ var encode = window.encodeURIComponent; if(post){ parts.push(encode(key).replace(/%20/g, "+") + "=" + encode(value).replace(/%20/g, "+")); } else { parts.push(encode(key) + "=" + encode(value)); }; }, /** * Takes a relative URI and returns an absolute one. * * @param uri {String} relative URI * @return {String} absolute URI */ getAbsolute : function(uri){ var div = document.createElement("div"); div.innerHTML = '<a href="' + uri + '">0</a>'; return div.firstChild.href; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) ************************************************************************ */ /** * Contains methods to control and query the element's box-sizing property. * * Supported values: * * * "content-box" = W3C model (dimensions are content specific) * * "border-box" = Microsoft model (dimensions are box specific incl. border and padding) */ qx.Bootstrap.define("qx.bom.element.BoxSizing", { /* ***************************************************************************** STATICS ***************************************************************************** */ statics : { /** {Map} Internal data structure for __usesNativeBorderBox() */ __nativeBorderBox : { tags : { button : true, select : true }, types : { search : true, button : true, submit : true, reset : true, checkbox : true, radio : true } }, /** * Whether the given elements defaults to the "border-box" Microsoft model in all cases. * * @param element {Element} DOM element to query * @return {Boolean} true when the element uses "border-box" independently from the doctype */ __usesNativeBorderBox : function(element){ var map = this.__nativeBorderBox; return map.tags[element.tagName.toLowerCase()] || map.types[element.type]; }, /** * Compiles the given box sizing into a CSS compatible string. * * @param value {String} Valid CSS box-sizing value * @return {String} CSS string */ compile : function(value){ if(qx.core.Environment.get("css.boxsizing")){ var prop = qx.bom.Style.getCssName(qx.core.Environment.get("css.boxsizing")); return prop + ":" + value + ";"; } else { { }; }; }, /** * Returns the box sizing for the given element. * * @param element {Element} The element to query * @return {String} Box sizing value of the given element. */ get : function(element){ if(qx.core.Environment.get("css.boxsizing")){ return qx.bom.element.Style.get(element, "boxSizing", null, false) || ""; }; if(qx.bom.Document.isStandardMode(qx.dom.Node.getWindow(element))){ if(!this.__usesNativeBorderBox(element)){ return "content-box"; }; }; return "border-box"; }, /** * Applies a new box sizing to the given element * * @param element {Element} The element to modify * @param value {String} New box sizing value to set */ set : function(element, value){ if(qx.core.Environment.get("css.boxsizing")){ // IE8 bombs when trying to apply an unsupported value try{ element.style[qx.core.Environment.get("css.boxsizing")] = value; } catch(ex) { { }; }; } else { { }; }; }, /** * Removes the local box sizing applied to the element * * @param element {Element} The element to modify */ reset : function(element){ this.set(element, ""); } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) ====================================================================== This class contains code based on the following work: * Prototype JS http://www.prototypejs.org/ Version 1.5 Copyright: (c) 2006-2007, Prototype Core Team License: MIT: http://www.opensource.org/licenses/mit-license.php Authors: * Prototype Core Team ---------------------------------------------------------------------- Copyright (c) 2005-2008 Sam Stephenson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ************************************************************************ */ /* ************************************************************************ #require(qx.lang.String) #require(qx.bom.client.Css) #require(qx.bom.element.Clip#set) #require(qx.bom.element.Cursor#set) #require(qx.bom.element.Opacity#set) #require(qx.bom.element.BoxSizing#set) #require(qx.bom.element.Clip#get) #require(qx.bom.element.Cursor#get) #require(qx.bom.element.Opacity#get) #require(qx.bom.element.BoxSizing#get) #require(qx.bom.element.Clip#reset) #require(qx.bom.element.Cursor#reset) #require(qx.bom.element.Opacity#reset) #require(qx.bom.element.BoxSizing#reset) #require(qx.bom.element.Clip#compile) #require(qx.bom.element.Cursor#compile) #require(qx.bom.element.Opacity#compile) #require(qx.bom.element.BoxSizing#compile) ************************************************************************ */ /** * Style querying and modification of HTML elements. * * Automatically normalizes cross-browser differences for setting and reading * CSS attributes. Optimized for performance. */ qx.Bootstrap.define("qx.bom.element.Style", { /* ***************************************************************************** STATICS ***************************************************************************** */ statics : { __styleNames : null, __cssNames : null, /** * Detect vendor specific properties. */ __detectVendorProperties : function(){ var styleNames = { "appearance" : qx.core.Environment.get("css.appearance"), "userSelect" : qx.core.Environment.get("css.userselect"), "textOverflow" : qx.core.Environment.get("css.textoverflow"), "borderImage" : qx.core.Environment.get("css.borderimage"), "float" : qx.core.Environment.get("css.float"), "userModify" : qx.core.Environment.get("css.usermodify"), "boxSizing" : qx.core.Environment.get("css.boxsizing") }; this.__cssNames = { }; for(var key in qx.lang.Object.clone(styleNames)){ if(!styleNames[key]){ delete styleNames[key]; } else { this.__cssNames[key] = key == "float" ? "float" : qx.bom.Style.getCssName(styleNames[key]); }; }; this.__styleNames = styleNames; }, /** * Gets the (possibly vendor-prefixed) name of a style property and stores * it to avoid multiple checks. * * @param name {String} Style property name to check * @return {String|null} The client-specific name of the property, or * <code>null</code> if it's not supported. */ __getStyleName : function(name){ var styleName = qx.bom.Style.getPropertyName(name); if(styleName){ this.__styleNames[name] = styleName; }; return styleName; }, /** * Mshtml has proprietary pixel* properties for locations and dimensions * which return the pixel value. Used by getComputed() in mshtml variant. * * @internal */ __mshtmlPixel : { width : "pixelWidth", height : "pixelHeight", left : "pixelLeft", right : "pixelRight", top : "pixelTop", bottom : "pixelBottom" }, /** * Whether a special class is available for the processing of this style. * * @internal */ __special : { clip : qx.bom.element.Clip, cursor : qx.bom.element.Cursor, opacity : qx.bom.element.Opacity, boxSizing : qx.bom.element.BoxSizing }, /* --------------------------------------------------------------------------- COMPILE SUPPORT --------------------------------------------------------------------------- */ /** * Compiles the given styles into a string which can be used to * concat a HTML string for innerHTML usage. * * @param map {Map} Map of style properties to compile * @return {String} Compiled string of given style properties. */ compile : function(map){ var html = []; var special = this.__special; var cssNames = this.__cssNames; var name,value; for(name in map){ // read value value = map[name]; if(value == null){ continue; }; // normalize name name = this.__styleNames[name] || this.__getStyleName(name) || name; // process special properties if(special[name]){ html.push(special[name].compile(value)); } else { if(!cssNames[name]){ cssNames[name] = qx.bom.Style.getCssName(name); }; html.push(cssNames[name], ":", value, ";"); }; }; return html.join(""); }, /* --------------------------------------------------------------------------- CSS TEXT SUPPORT --------------------------------------------------------------------------- */ /** * Set the full CSS content of the style attribute * * @param element {Element} The DOM element to modify * @param value {String} The full CSS string */ setCss : function(element, value){ if(qx.core.Environment.get("engine.name") === "mshtml" && parseInt(qx.core.Environment.get("browser.documentmode"), 10) < 8){ element.style.cssText = value; } else { element.setAttribute("style", value); }; }, /** * Returns the full content of the style attribute. * * @param element {Element} The DOM element to query * @return {String} the full CSS string * @signature function(element) */ getCss : function(element){ if(qx.core.Environment.get("engine.name") === "mshtml" && parseInt(qx.core.Environment.get("browser.documentmode"), 10) < 8){ return element.style.cssText.toLowerCase(); } else { return element.getAttribute("style"); }; }, /* --------------------------------------------------------------------------- STYLE ATTRIBUTE SUPPORT --------------------------------------------------------------------------- */ /** * Checks whether the browser supports the given CSS property. * * @param propertyName {String} The name of the property * @return {Boolean} Whether the property id supported */ isPropertySupported : function(propertyName){ return (this.__special[propertyName] || this.__styleNames[propertyName] || propertyName in document.documentElement.style); }, /** {Integer} Computed value of a style property. Compared to the cascaded style, * this one also interprets the values e.g. translates <code>em</code> units to * <code>px</code>. */ COMPUTED_MODE : 1, /** {Integer} Cascaded value of a style property. */ CASCADED_MODE : 2, /** * {Integer} Local value of a style property. Ignores inheritance cascade. * Does not interpret values. */ LOCAL_MODE : 3, /** * Sets the value of a style property * * @param element {Element} The DOM element to modify * @param name {String} Name of the style attribute (js variant e.g. marginTop, wordSpacing) * @param value {var} The value for the given style * @param smart {Boolean?true} Whether the implementation should automatically use * special implementations for some properties */ set : function(element, name, value, smart){ { }; // normalize name name = this.__styleNames[name] || this.__getStyleName(name) || name; // special handling for specific properties // through this good working switch this part costs nothing when // processing non-smart properties if(smart !== false && this.__special[name]){ this.__special[name].set(element, value); } else { element.style[name] = value !== null ? value : ""; }; }, /** * Convenience method to modify a set of styles at once. * * @param element {Element} The DOM element to modify * @param styles {Map} a map where the key is the name of the property * and the value is the value to use. * @param smart {Boolean?true} Whether the implementation should automatically use * special implementations for some properties */ setStyles : function(element, styles, smart){ { }; // inline calls to "set" and "reset" because this method is very // performance critical! var styleNames = this.__styleNames; var special = this.__special; var style = element.style; for(var key in styles){ var value = styles[key]; var name = styleNames[key] || this.__getStyleName(key) || key; if(value === undefined){ if(smart !== false && special[name]){ special[name].reset(element); } else { style[name] = ""; }; } else { if(smart !== false && special[name]){ special[name].set(element, value); } else { style[name] = value !== null ? value : ""; }; }; }; }, /** * Resets the value of a style property * * @param element {Element} The DOM element to modify * @param name {String} Name of the style attribute (js variant e.g. marginTop, wordSpacing) * @param smart {Boolean?true} Whether the implementation should automatically use * special implementations for some properties */ reset : function(element, name, smart){ // normalize name name = this.__styleNames[name] || this.__getStyleName(name) || name; // special handling for specific properties if(smart !== false && this.__special[name]){ this.__special[name].reset(element); } else { element.style[name] = ""; }; }, /** * Gets the value of a style property. * * *Computed* * * Returns the computed value of a style property. Compared to the cascaded style, * this one also interprets the values e.g. translates <code>em</code> units to * <code>px</code>. * * *Cascaded* * * Returns the cascaded value of a style property. * * *Local* * * Ignores inheritance cascade. Does not interpret values. * * @signature function(element, name, mode, smart) * @param element {Element} The DOM element to modify * @param name {String} Name of the style attribute (js variant e.g. marginTop, wordSpacing) * @param mode {Number} Choose one of the modes {@link #COMPUTED_MODE}, {@link #CASCADED_MODE}, * {@link #LOCAL_MODE}. The computed mode is the default one. * @param smart {Boolean?true} Whether the implementation should automatically use * special implementations for some properties * @return {var} The value of the property */ get : qx.core.Environment.select("engine.name", { "mshtml" : function(element, name, mode, smart){ // normalize name name = this.__styleNames[name] || this.__getStyleName(name) || name; // special handling if(smart !== false && this.__special[name]){ return this.__special[name].get(element, mode); }; // if the element is not inserted into the document "currentStyle" // may be undefined. In this case always return the local style. if(!element.currentStyle){ return element.style[name] || ""; }; // switch to right mode switch(mode){case this.LOCAL_MODE: return element.style[name] || "";case this.CASCADED_MODE: return element.currentStyle[name] || "";default: // Read cascaded style. Shorthand properties like "border" are not available // on the currentStyle object. var currentStyle = element.currentStyle[name] || element.style[name] || ""; // Pixel values are always OK if(/^-?[\.\d]+(px)?$/i.test(currentStyle)){ return currentStyle; }; // Try to convert non-pixel values var pixel = this.__mshtmlPixel[name]; if(pixel){ // Backup local and runtime style var localStyle = element.style[name]; // Overwrite local value with cascaded value // This is needed to have the pixel value setupped element.style[name] = currentStyle || 0; // Read pixel value and add "px" var value = element.style[pixel] + "px"; // Recover old local value element.style[name] = localStyle; // Return value return value; }; // Just the current style return currentStyle;}; }, "default" : function(element, name, mode, smart){ // normalize name name = this.__styleNames[name] || this.__getStyleName(name) || name; // special handling if(smart !== false && this.__special[name]){ return this.__special[name].get(element, mode); }; // switch to right mode switch(mode){case this.LOCAL_MODE: return element.style[name] || "";case this.CASCADED_MODE: // Currently only supported by Opera and Internet Explorer if(element.currentStyle){ return element.currentStyle[name] || ""; }; throw new Error("Cascaded styles are not supported in this browser!");// Support for the DOM2 getComputedStyle method // // Safari >= 3 & Gecko > 1.4 expose all properties to the returned // CSSStyleDeclaration object. In older browsers the function // "getPropertyValue" is needed to access the values. // // On a computed style object all properties are read-only which is // identical to the behavior of MSHTML's "currentStyle". default: // Opera, Mozilla and Safari 3+ also have a global getComputedStyle which is identical // to the one found under document.defaultView. // The problem with this is however that this does not work correctly // when working with frames and access an element of another frame. // Then we must use the <code>getComputedStyle</code> of the document // where the element is defined. var doc = qx.dom.Node.getDocument(element); var computed = doc.defaultView.getComputedStyle(element, null); // All relevant browsers expose the configured style properties to // the CSSStyleDeclaration objects if(computed && computed[name]){ return computed[name]; }; return element.style[name] || "";}; } }) }, defer : function(statics){ statics.__detectVendorProperties(); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) ************************************************************************ */ /** * Basic node creation and type detection */ qx.Bootstrap.define("qx.dom.Node", { /* ***************************************************************************** STATICS ***************************************************************************** */ statics : { /* --------------------------------------------------------------------------- NODE TYPES --------------------------------------------------------------------------- */ /** * {Map} Node type: * * * ELEMENT * * ATTRIBUTE * * TEXT * * CDATA_SECTION * * ENTITY_REFERENCE * * ENTITY * * PROCESSING_INSTRUCTION * * COMMENT * * DOCUMENT * * DOCUMENT_TYPE * * DOCUMENT_FRAGMENT * * NOTATION */ ELEMENT : 1, ATTRIBUTE : 2, TEXT : 3, CDATA_SECTION : 4, ENTITY_REFERENCE : 5, ENTITY : 6, PROCESSING_INSTRUCTION : 7, COMMENT : 8, DOCUMENT : 9, DOCUMENT_TYPE : 10, DOCUMENT_FRAGMENT : 11, NOTATION : 12, /* --------------------------------------------------------------------------- DOCUMENT ACCESS --------------------------------------------------------------------------- */ /** * Returns the owner document of the given node * * @param node {Node|Document|Window} the node which should be tested * @return {Document|null} The document of the given DOM node */ getDocument : function(node){ return node.nodeType === this.DOCUMENT ? node : // is document already node.ownerDocument || // is DOM node node.document; }, /** * Returns the DOM2 <code>defaultView</code> (window). * * @param node {Node|Document|Window} node to inspect * @return {Window} the <code>defaultView</code> of the given node */ getWindow : function(node){ // is a window already if(node.nodeType == null){ return node; }; // jump to document if(node.nodeType !== this.DOCUMENT){ node = node.ownerDocument; }; // jump to window return node.defaultView || node.parentWindow; }, /** * Returns the document element. (Logical root node) * * This is a convenience attribute that allows direct access to the child * node that is the root element of the document. For HTML documents, * this is the element with the tagName "HTML". * * @param node {Node|Document|Window} node to inspect * @return {Element} document element of the given node */ getDocumentElement : function(node){ return this.getDocument(node).documentElement; }, /** * Returns the body element. (Visual root node) * * This normally only makes sense for HTML documents. It returns * the content area of the HTML document. * * @param node {Node|Document|Window} node to inspect * @return {Element} document body of the given node */ getBodyElement : function(node){ return this.getDocument(node).body; }, /* --------------------------------------------------------------------------- TYPE TESTS --------------------------------------------------------------------------- */ /** * Whether the given object is a DOM node * * @param node {Node} the node which should be tested * @return {Boolean} true if the node is a DOM node */ isNode : function(node){ return !!(node && node.nodeType != null); }, /** * Whether the given object is a DOM element node * * @param node {Node} the node which should be tested * @return {Boolean} true if the node is a DOM element */ isElement : function(node){ return !!(node && node.nodeType === this.ELEMENT); }, /** * Whether the given object is a DOM document node * * @param node {Node} the node which should be tested * @return {Boolean} true when the node is a DOM document */ isDocument : function(node){ return !!(node && node.nodeType === this.DOCUMENT); }, /** * Whether the given object is a DOM text node * * @param node {Node} the node which should be tested * @return {Boolean} true if the node is a DOM text node */ isText : function(node){ return !!(node && node.nodeType === this.TEXT); }, /** * Check whether the given object is a browser window object. * * @param obj {Object} the object which should be tested * @return {Boolean} true if the object is a window object */ isWindow : function(obj){ return !!(obj && obj.history && obj.location && obj.document); }, /** * Whether the node has the given node name * * @param node {Node} the node * @param nodeName {String} the node name to check for * @return {Boolean} Whether the node has the given node name */ isNodeName : function(node, nodeName){ if(!nodeName || !node || !node.nodeName){ return false; }; return nodeName.toLowerCase() == qx.dom.Node.getName(node); }, /* --------------------------------------------------------------------------- UTILITIES --------------------------------------------------------------------------- */ /** * Get the node name as lower case string * * @param node {Node} the node * @return {String} the node name */ getName : function(node){ if(!node || !node.nodeName){ return null; }; return node.nodeName.toLowerCase(); }, /** * Returns the text content of an node where the node may be of node type * NODE_ELEMENT, NODE_ATTRIBUTE, NODE_TEXT or NODE_CDATA * * @param node {Node} the node from where the search should start. * If the node has subnodes the text contents are recursively retreived and joined. * @return {String} the joined text content of the given node or null if not appropriate. * @signature function(node) */ getText : function(node){ if(!node || !node.nodeType){ return null; }; switch(node.nodeType){case 1: // NODE_ELEMENT var i,a = [],nodes = node.childNodes,length = nodes.length; for(i = 0;i < length;i++){ a[i] = this.getText(nodes[i]); }; return a.join("");case 2:// NODE_ATTRIBUTE case 3:// NODE_TEXT case 4: // CDATA return node.nodeValue;}; return null; }, /** * Checks if the given node is a block node * * @param node {Node} Node * @return {Boolean} whether it is a block node */ isBlockNode : function(node){ if(!qx.dom.Node.isElement(node)){ return false; }; node = qx.dom.Node.getName(node); return /^(body|form|textarea|fieldset|ul|ol|dl|dt|dd|li|div|hr|p|h[1-6]|quote|pre|table|thead|tbody|tfoot|tr|td|th|iframe|address|blockquote)$/.test(node); } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) ====================================================================== This class contains code based on the following work: * Yahoo! UI Library http://developer.yahoo.com/yui Version 2.2.0 Copyright: (c) 2007, Yahoo! Inc. License: BSD: http://developer.yahoo.com/yui/license.txt ---------------------------------------------------------------------- http://developer.yahoo.com/yui/license.html Copyright (c) 2009, Yahoo! Inc. All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Yahoo! Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of Yahoo! Inc. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ************************************************************************ */ /** * Includes library functions to work with the current document. */ qx.Bootstrap.define("qx.bom.Document", { statics : { /** * Whether the document is in quirks mode (e.g. non XHTML, HTML4 Strict or missing doctype) * * @signature function(win) * @param win {Window?window} The window to query * @return {Boolean} true when containing document is in quirks mode */ isQuirksMode : qx.core.Environment.select("engine.name", { "mshtml" : function(win){ if(qx.core.Environment.get("engine.version") >= 8){ return (win || window).document.documentMode === 5; } else { return (win || window).document.compatMode !== "CSS1Compat"; }; }, "webkit" : function(win){ if(document.compatMode === undefined){ var el = (win || window).document.createElement("div"); el.style.cssText = "position:absolute;width:0;height:0;width:1"; return el.style.width === "1px" ? true : false; } else { return (win || window).document.compatMode !== "CSS1Compat"; }; }, "default" : function(win){ return (win || window).document.compatMode !== "CSS1Compat"; } }), /** * Whether the document is in standard mode (e.g. XHTML, HTML4 Strict or doctype defined) * * @param win {Window?window} The window to query * @return {Boolean} true when containing document is in standard mode */ isStandardMode : function(win){ return !this.isQuirksMode(win); }, /** * Returns the width of the document. * * Internet Explorer in standard mode stores the proprietary <code>scrollWidth</code> property * on the <code>documentElement</code>, but in quirks mode on the body element. All * other known browsers simply store the correct value on the <code>documentElement</code>. * * If the viewport is wider than the document the viewport width is returned. * * As the html element has no visual appearance it also can not scroll. This * means that we must use the body <code>scrollWidth</code> in all non mshtml clients. * * Verified to correctly work with: * * * Mozilla Firefox 2.0.0.4 * * Opera 9.2.1 * * Safari 3.0 beta (3.0.2) * * Internet Explorer 7.0 * * @param win {Window?window} The window to query * @return {Integer} The width of the actual document (which includes the body and its margin). * * NOTE: Opera 9.5x and 9.6x have wrong value for the scrollWidth property, * if an element use negative value for top and left to be outside the viewport! * See: http://bugzilla.qooxdoo.org/show_bug.cgi?id=2869 */ getWidth : function(win){ var doc = (win || window).document; var view = qx.bom.Viewport.getWidth(win); var scroll = this.isStandardMode(win) ? doc.documentElement.scrollWidth : doc.body.scrollWidth; return Math.max(scroll, view); }, /** * Returns the height of the document. * * Internet Explorer in standard mode stores the proprietary <code>scrollHeight</code> property * on the <code>documentElement</code>, but in quirks mode on the body element. All * other known browsers simply store the correct value on the <code>documentElement</code>. * * If the viewport is higher than the document the viewport height is returned. * * As the html element has no visual appearance it also can not scroll. This * means that we must use the body <code>scrollHeight</code> in all non mshtml clients. * * Verified to correctly work with: * * * Mozilla Firefox 2.0.0.4 * * Opera 9.2.1 * * Safari 3.0 beta (3.0.2) * * Internet Explorer 7.0 * * @param win {Window?window} The window to query * @return {Integer} The height of the actual document (which includes the body and its margin). * * NOTE: Opera 9.5x and 9.6x have wrong value for the scrollWidth property, * if an element use negative value for top and left to be outside the viewport! * See: http://bugzilla.qooxdoo.org/show_bug.cgi?id=2869 */ getHeight : function(win){ var doc = (win || window).document; var view = qx.bom.Viewport.getHeight(win); var scroll = this.isStandardMode(win) ? doc.documentElement.scrollHeight : doc.body.scrollHeight; return Math.max(scroll, view); } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Sebastian Fastner (fastner) * Tino Butz (tbtz) ====================================================================== This class contains code based on the following work: * Unify Project Homepage: http://unify-project.org Copyright: 2009-2010 Deutsche Telekom AG, Germany, http://telekom.com License: MIT: http://www.opensource.org/licenses/mit-license.php * Yahoo! UI Library http://developer.yahoo.com/yui Version 2.2.0 Copyright: (c) 2007, Yahoo! Inc. License: BSD: http://developer.yahoo.com/yui/license.txt ---------------------------------------------------------------------- http://developer.yahoo.com/yui/license.html Copyright (c) 2009, Yahoo! Inc. All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Yahoo! Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of Yahoo! Inc. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ************************************************************************ */ /** * Includes library functions to work with the client's viewport (window). * Orientation related functions are point to window.top as default. */ qx.Bootstrap.define("qx.bom.Viewport", { statics : { /** * Returns the current width of the viewport (excluding the vertical scrollbar * if present). * * @param win {Window?window} The window to query * @return {Integer} The width of the viewable area of the page (excluding scrollbars). */ getWidth : function(win){ var win = win || window; var doc = win.document; return qx.bom.Document.isStandardMode(win) ? doc.documentElement.clientWidth : doc.body.clientWidth; }, /** * Returns the current height of the viewport (excluding the horizontal scrollbar * if present). * * @param win {Window?window} The window to query * @return {Integer} The Height of the viewable area of the page (excluding scrollbars). */ getHeight : function(win){ var win = win || window; var doc = win.document; return qx.bom.Document.isStandardMode(win) ? doc.documentElement.clientHeight : doc.body.clientHeight; }, /** * Returns the scroll position of the viewport * * All clients except IE < 9 support the non-standard property <code>pageXOffset</code>. * As this is easier to evaluate we prefer this property over <code>scrollLeft</code>. * Since the window could differ from the one the application is running in, we can't * use a one-time environment check to decide which property to use. * * @param win {Window?window} The window to query * @return {Integer} Scroll position in pixels from left edge, always a positive integer or zero */ getScrollLeft : function(win){ var win = win ? win : window; if(typeof win.pageXOffset !== "undefined"){ return win.pageXOffset; }; // Firefox is using 'documentElement.scrollLeft' and Chrome is using // 'document.body.scrollLeft'. For the other value each browser is returning // 0, so we can use this check to get the positive value without using specific // browser checks. var doc = win.document; return doc.documentElement.scrollLeft || doc.body.scrollLeft; }, /** * Returns the scroll position of the viewport * * All clients except MSHTML support the non-standard property <code>pageYOffset</code>. * As this is easier to evaluate we prefer this property over <code>scrollTop</code>. * Since the window could differ from the one the application is running in, we can't * use a one-time environment check to decide which property to use. * * @param win {Window?window} The window to query * @return {Integer} Scroll position in pixels from top edge, always a positive integer or zero */ getScrollTop : function(win){ var win = win ? win : window; if(typeof win.pageYOffeset !== "undefined"){ return win.pageYOffset; }; // Firefox is using 'documentElement.scrollTop' and Chrome is using // 'document.body.scrollTop'. For the other value each browser is returning // 0, so we can use this check to get the positive value without using specific // browser checks. var doc = win.document; return doc.documentElement.scrollTop || doc.body.scrollTop; }, /** * Returns an orientation normalizer value that should be added to device orientation * to normalize behaviour on different devices. * * @param win {Window} The window to query * @return {Map} Orientation normalizing value */ __getOrientationNormalizer : function(win){ // Calculate own understanding of orientation (0 = portrait, 90 = landscape) var currentOrientation = this.getWidth(win) > this.getHeight(win) ? 90 : 0; var deviceOrientation = win.orientation; if(deviceOrientation == null || Math.abs(deviceOrientation % 180) == currentOrientation){ // No device orientation available or device orientation equals own understanding of orientation return { "-270" : 90, "-180" : 180, "-90" : -90, "0" : 0, "90" : 90, "180" : 180, "270" : -90 }; } else { // Device orientation is not equal to own understanding of orientation return { "-270" : 180, "-180" : -90, "-90" : 0, "0" : 90, "90" : 180, "180" : -90, "270" : 0 }; }; }, // Cache orientation normalizer map on start __orientationNormalizer : null, /** * Returns the current orientation of the viewport in degree. * * All possible values and their meaning: * * * <code>-90</code>: "Landscape" * * <code>0</code>: "Portrait" * * <code>90</code>: "Landscape" * * <code>180</code>: "Portrait" * * @param win {Window?window.top} The window to query. (Default = top window) * @return {Integer} The current orientation in degree */ getOrientation : function(win){ // Set window.top as default, because orientationChange event is only fired top window var win = win || window.top; // The orientation property of window does not have the same behaviour over all devices // iPad has 0degrees = Portrait, Playbook has 90degrees = Portrait, same for Android Honeycomb // // To fix this an orientationNormalizer map is calculated on application start // // The calculation of getWidth and getHeight returns wrong values if you are in an input field // on iPad and rotate your device! var orientation = win.orientation; if(orientation == null){ // Calculate orientation from window width and window height orientation = this.getWidth(win) > this.getHeight(win) ? 90 : 0; } else { if(this.__orientationNormalizer == null){ this.__orientationNormalizer = this.__getOrientationNormalizer(win); }; // Normalize orientation value orientation = this.__orientationNormalizer[orientation]; }; return orientation; }, /** * Whether the viewport orientation is currently in landscape mode. * * @param win {Window?window} The window to query * @return {Boolean} <code>true</code> when the viewport orientation * is currently in landscape mode. */ isLandscape : function(win){ return this.getWidth(win) >= this.getHeight(win); }, /** * Whether the viewport orientation is currently in portrait mode. * * @param win {Window?window} The window to query * @return {Boolean} <code>true</code> when the viewport orientation * is currently in portrait mode. */ isPortrait : function(win){ return this.getWidth(win) < this.getHeight(win); } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) ====================================================================== This class contains code based on the following work: * Base2 http://code.google.com/p/base2/ Version 0.9 Copyright: (c) 2006-2007, Dean Edwards License: MIT: http://www.opensource.org/licenses/mit-license.php Authors: * Dean Edwards ************************************************************************ */ /** * CSS class name support for HTML elements. Supports multiple class names * for each element. Can query and apply class names to HTML elements. */ qx.Bootstrap.define("qx.bom.element.Class", { /* ***************************************************************************** STATICS ***************************************************************************** */ statics : { /** {RegExp} Regular expressions to split class names */ __splitter : /\s+/g, /** {RegExp} String trim regular expression. */ __trim : /^\s+|\s+$/g, /** * Adds a className to the given element * If successfully added the given className will be returned * * @signature function(element, name) * @param element {Element} The element to modify * @param name {String} The class name to add * @return {String} The added classname (if so) */ add : { "native" : function(element, name){ element.classList.add(name); return name; }, "default" : function(element, name){ if(!this.has(element, name)){ element.className += (element.className ? " " : "") + name; }; return name; } }[qx.core.Environment.get("html.classlist") ? "native" : "default"], /** * Adds multiple classes to the given element * * @signature function(element, classes) * @param element {Element} DOM element to modify * @param classes {String[]} List of classes to add. * @return {String} The resulting class name which was applied */ addClasses : { "native" : function(element, classes){ for(var i = 0;i < classes.length;i++){ element.classList.add(classes[i]); }; return element.className; }, "default" : function(element, classes){ var keys = { }; var result; var old = element.className; if(old){ result = old.split(this.__splitter); for(var i = 0,l = result.length;i < l;i++){ keys[result[i]] = true; }; for(var i = 0,l = classes.length;i < l;i++){ if(!keys[classes[i]]){ result.push(classes[i]); }; }; } else { result = classes; }; return element.className = result.join(" "); } }[qx.core.Environment.get("html.classlist") ? "native" : "default"], /** * Gets the classname of the given element * * @param element {Element} The element to query * @return {String} The retrieved classname */ get : function(element){ var className = element.className; if(typeof className.split !== 'function'){ if(typeof className === 'object'){ if(qx.Bootstrap.getClass(className) == 'SVGAnimatedString'){ className = className.baseVal; } else { { }; className = ''; }; }; if(typeof className === 'undefined'){ { }; className = ''; }; }; return className; }, /** * Whether the given element has the given className. * * @signature function(element, name) * @param element {Element} The DOM element to check * @param name {String} The class name to check for * @return {Boolean} true when the element has the given classname */ has : { "native" : function(element, name){ return element.classList.contains(name); }, "default" : function(element, name){ var regexp = new RegExp("(^|\\s)" + name + "(\\s|$)"); return regexp.test(element.className); } }[qx.core.Environment.get("html.classlist") ? "native" : "default"], /** * Removes a className from the given element * * @signature function(element, name) * @param element {Element} The DOM element to modify * @param name {String} The class name to remove * @return {String} The removed class name */ remove : { "native" : function(element, name){ element.classList.remove(name); return name; }, "default" : function(element, name){ var regexp = new RegExp("(^|\\s)" + name + "(\\s|$)"); element.className = element.className.replace(regexp, "$2"); return name; } }[qx.core.Environment.get("html.classlist") ? "native" : "default"], /** * Removes multiple classes from the given element * * @signature function(element, classes) * @param element {Element} DOM element to modify * @param classes {String[]} List of classes to remove. * @return {String} The resulting class name which was applied */ removeClasses : { "native" : function(element, classes){ for(var i = 0;i < classes.length;i++){ element.classList.remove(classes[i]); }; return element.className; }, "default" : function(element, classes){ var reg = new RegExp("\\b" + classes.join("\\b|\\b") + "\\b", "g"); return element.className = element.className.replace(reg, "").replace(this.__trim, "").replace(this.__splitter, " "); } }[qx.core.Environment.get("html.classlist") ? "native" : "default"], /** * Replaces the first given class name with the second one * * @param element {Element} The DOM element to modify * @param oldName {String} The class name to remove * @param newName {String} The class name to add * @return {String} The added class name */ replace : function(element, oldName, newName){ if(!this.has(element, oldName)){ return ""; }; this.remove(element, oldName); return this.add(element, newName); }, /** * Toggles a className of the given element * * @signature function(element, name, toggle) * @param element {Element} The DOM element to modify * @param name {String} The class name to toggle * @param toggle {Boolean?null} Whether to switch class on/off. Without * the parameter an automatic toggling would happen. * @return {String} The class name */ toggle : { "native" : function(element, name, toggle){ if(toggle === undefined){ element.classList.toggle(name); } else { toggle ? this.add(element, name) : this.remove(element, name); }; return name; }, "default" : function(element, name, toggle){ if(toggle == null){ toggle = !this.has(element, name); }; toggle ? this.add(element, name) : this.remove(element, name); return name; } }[qx.core.Environment.get("html.classlist") ? "native" : "default"] } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Fabian Jakobs (fjakobs) ************************************************************************ */ /** * Contains support for calculating dimensions of HTML elements. * * We differ between the box (or border) size which is available via * {@link #getWidth} and {@link #getHeight} and the content or scroll * sizes which are available via {@link #getContentWidth} and * {@link #getContentHeight}. */ qx.Bootstrap.define("qx.bom.element.Dimension", { /* ***************************************************************************** STATICS ***************************************************************************** */ statics : { /** * Returns the rendered width of the given element. * * This is the visible width of the object, which need not to be identical * to the width configured via CSS. This highly depends on the current * box-sizing for the document and maybe even for the element. * * @signature function(element) * @param element {Element} element to query * @return {Integer} width of the element */ getWidth : qx.core.Environment.select("engine.name", { "gecko" : function(element){ // offsetWidth in Firefox does not always return the rendered pixel size // of an element. // Starting with Firefox 3 the rendered size can be determined by using // getBoundingClientRect // https://bugzilla.mozilla.org/show_bug.cgi?id=450422 if(element.getBoundingClientRect){ var rect = element.getBoundingClientRect(); return Math.round(rect.right) - Math.round(rect.left); } else { return element.offsetWidth; }; }, "default" : function(element){ return element.offsetWidth; } }), /** * Returns the rendered height of the given element. * * This is the visible height of the object, which need not to be identical * to the height configured via CSS. This highly depends on the current * box-sizing for the document and maybe even for the element. * * @signature function(element) * @param element {Element} element to query * @return {Integer} height of the element */ getHeight : qx.core.Environment.select("engine.name", { "gecko" : function(element){ if(element.getBoundingClientRect){ var rect = element.getBoundingClientRect(); return Math.round(rect.bottom) - Math.round(rect.top); } else { return element.offsetHeight; }; }, "default" : function(element){ return element.offsetHeight; } }), /** * Returns the rendered size of the given element. * * @param element {Element} element to query * @return {Map} map containing the width and height of the element */ getSize : function(element){ return { width : this.getWidth(element), height : this.getHeight(element) }; }, /** {Map} Contains all overflow values where scrollbars are invisible */ __hiddenScrollbars : { visible : true, hidden : true }, /** * Returns the content width. * * The content width is basically the maximum * width used or the maximum width which can be used by the content. This * excludes all kind of styles of the element like borders, paddings, margins, * and even scrollbars. * * Please note that with visible scrollbars the content width returned * may be larger than the box width returned via {@link #getWidth}. * * @param element {Element} element to query * @return {Integer} Computed content width */ getContentWidth : function(element){ var Style = qx.bom.element.Style; var overflowX = qx.bom.element.Style.get(element, "overflowX"); var paddingLeft = parseInt(Style.get(element, "paddingLeft") || "0px", 10); var paddingRight = parseInt(Style.get(element, "paddingRight") || "0px", 10); if(this.__hiddenScrollbars[overflowX]){ var contentWidth = element.clientWidth; if((qx.core.Environment.get("engine.name") == "opera") || qx.dom.Node.isBlockNode(element)){ contentWidth = contentWidth - paddingLeft - paddingRight; }; return contentWidth; } else { if(element.clientWidth >= element.scrollWidth){ // Scrollbars visible, but not needed? We need to substract both paddings return Math.max(element.clientWidth, element.scrollWidth) - paddingLeft - paddingRight; } else { // Scrollbars visible and needed. We just remove the left padding, // as the right padding is not respected in rendering. var width = element.scrollWidth - paddingLeft; // IE renders the paddingRight as well with scrollbars on if(qx.core.Environment.get("engine.name") == "mshtml" && qx.core.Environment.get("engine.version") >= 6){ width -= paddingRight; }; return width; }; }; }, /** * Returns the content height. * * The content height is basically the maximum * height used or the maximum height which can be used by the content. This * excludes all kind of styles of the element like borders, paddings, margins, * and even scrollbars. * * Please note that with visible scrollbars the content height returned * may be larger than the box height returned via {@link #getHeight}. * * @param element {Element} element to query * @return {Integer} Computed content height */ getContentHeight : function(element){ var Style = qx.bom.element.Style; var overflowY = qx.bom.element.Style.get(element, "overflowY"); var paddingTop = parseInt(Style.get(element, "paddingTop") || "0px", 10); var paddingBottom = parseInt(Style.get(element, "paddingBottom") || "0px", 10); if(this.__hiddenScrollbars[overflowY]){ return element.clientHeight - paddingTop - paddingBottom; } else { if(element.clientHeight >= element.scrollHeight){ // Scrollbars visible, but not needed? We need to substract both paddings return Math.max(element.clientHeight, element.scrollHeight) - paddingTop - paddingBottom; } else { // Scrollbars visible and needed. We just remove the top padding, // as the bottom padding is not respected in rendering. var height = element.scrollHeight - paddingTop; // IE renders the paddingBottom as well with scrollbars on if(qx.core.Environment.get("engine.name") == "mshtml" && qx.core.Environment.get("engine.version") == 6){ height -= paddingBottom; }; return height; }; }; }, /** * Returns the rendered content size of the given element. * * @param element {Element} element to query * @return {Map} map containing the content width and height of the element */ getContentSize : function(element){ return { width : this.getContentWidth(element), height : this.getContentHeight(element) }; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) ====================================================================== This class contains code based on the following work: * jQuery Dimension Plugin http://jquery.com/ Version 1.1.3 Copyright: (c) 2007, Paul Bakaus & Brandon Aaron License: MIT: http://www.opensource.org/licenses/mit-license.php Authors: Paul Bakaus Brandon Aaron ************************************************************************ */ /** * Query the location of an arbitrary DOM element in relation to its top * level body element. Works in all major browsers: * * * Mozilla 1.5 + 2.0 * * Internet Explorer 6.0 + 7.0 (both standard & quirks mode) * * Opera 9.2 * * Safari 3.0 beta */ qx.Bootstrap.define("qx.bom.element.Location", { statics : { /** * Queries a style property for the given element * * @param elem {Element} DOM element to query * @param style {String} Style property * @return {String} Value of given style property */ __style : function(elem, style){ return qx.bom.element.Style.get(elem, style, qx.bom.element.Style.COMPUTED_MODE, false); }, /** * Queries a style property for the given element and parses it to an integer value * * @param elem {Element} DOM element to query * @param style {String} Style property * @return {Integer} Value of given style property */ __num : function(elem, style){ return parseInt(qx.bom.element.Style.get(elem, style, qx.bom.element.Style.COMPUTED_MODE, false), 10) || 0; }, /** * Computes the scroll offset of the given element relative to the document * <code>body</code>. * * @param elem {Element} DOM element to query * @return {Map} Map which contains the <code>left</code> and <code>top</code> scroll offsets */ __computeScroll : function(elem){ var left = 0,top = 0; // Find window var win = qx.dom.Node.getWindow(elem); left -= qx.bom.Viewport.getScrollLeft(win); top -= qx.bom.Viewport.getScrollTop(win); return { left : left, top : top }; }, /** * Computes the offset of the given element relative to the document * <code>body</code>. * * @param elem {Element} DOM element to query * @return {Map} Map which contains the <code>left</code> and <code>top</code> offsets */ __computeBody : qx.core.Environment.select("engine.name", { "mshtml" : function(elem){ // Find body element var doc = qx.dom.Node.getDocument(elem); var body = doc.body; var left = 0; var top = 0; left -= body.clientLeft + doc.documentElement.clientLeft; top -= body.clientTop + doc.documentElement.clientTop; if(!qx.core.Environment.get("browser.quirksmode")){ left += this.__num(body, "borderLeftWidth"); top += this.__num(body, "borderTopWidth"); }; return { left : left, top : top }; }, "webkit" : function(elem){ // Find body element var doc = qx.dom.Node.getDocument(elem); var body = doc.body; // Start with the offset var left = body.offsetLeft; var top = body.offsetTop; // only for safari < version 4.0 if(parseFloat(qx.core.Environment.get("engine.version")) < 530.17){ left += this.__num(body, "borderLeftWidth"); top += this.__num(body, "borderTopWidth"); }; return { left : left, top : top }; }, "gecko" : function(elem){ // Find body element var body = qx.dom.Node.getDocument(elem).body; // Start with the offset var left = body.offsetLeft; var top = body.offsetTop; // add the body margin for firefox 3.0 and below if(parseFloat(qx.core.Environment.get("engine.version")) < 1.9){ left += this.__num(body, "marginLeft"); top += this.__num(body, "marginTop"); }; // Correct substracted border (only in content-box mode) if(qx.bom.element.BoxSizing.get(body) !== "border-box"){ left += this.__num(body, "borderLeftWidth"); top += this.__num(body, "borderTopWidth"); }; return { left : left, top : top }; }, // At the moment only correctly supported by Opera "default" : function(elem){ // Find body element var body = qx.dom.Node.getDocument(elem).body; // Start with the offset var left = body.offsetLeft; var top = body.offsetTop; return { left : left, top : top }; } }), /** * Computes the sum of all offsets of the given element node. * * Traditionally this is a loop which goes up the whole parent tree * and sums up all found offsets. * * But both <code>mshtml</code> and <code>gecko >= 1.9</code> support * <code>getBoundingClientRect</code> which allows a * much faster access to the offset position. * * Please note: When gecko 1.9 does not use the <code>getBoundingClientRect</code> * implementation, and therefore use the traditional offset calculation * the gecko 1.9 fix in <code>__computeBody</code> must not be applied. * * @signature function(elem) * @param elem {Element} DOM element to query * @return {Map} Map which contains the <code>left</code> and <code>top</code> offsets */ __computeOffset : qx.core.Environment.select("engine.name", { "gecko" : function(elem){ // Use faster getBoundingClientRect() if available (gecko >= 1.9) if(elem.getBoundingClientRect){ var rect = elem.getBoundingClientRect(); // Firefox 3.0 alpha 6 (gecko 1.9) returns floating point numbers // use Math.round() to round them to style compatible numbers // MSHTML returns integer numbers var left = Math.round(rect.left); var top = Math.round(rect.top); } else { var left = 0; var top = 0; // Stop at the body var body = qx.dom.Node.getDocument(elem).body; var box = qx.bom.element.BoxSizing; if(box.get(elem) !== "border-box"){ left -= this.__num(elem, "borderLeftWidth"); top -= this.__num(elem, "borderTopWidth"); }; while(elem && elem !== body){ // Add node offsets left += elem.offsetLeft; top += elem.offsetTop; // Mozilla does not add the borders to the offset // when using box-sizing=content-box if(box.get(elem) !== "border-box"){ left += this.__num(elem, "borderLeftWidth"); top += this.__num(elem, "borderTopWidth"); }; // Mozilla does not add the border for a parent that has // overflow set to anything but visible if(elem.parentNode && this.__style(elem.parentNode, "overflow") != "visible"){ left += this.__num(elem.parentNode, "borderLeftWidth"); top += this.__num(elem.parentNode, "borderTopWidth"); }; // One level up (offset hierarchy) elem = elem.offsetParent; }; }; return { left : left, top : top }; }, "default" : function(elem){ var doc = qx.dom.Node.getDocument(elem); // Use faster getBoundingClientRect() if available if(elem.getBoundingClientRect){ var rect = elem.getBoundingClientRect(); var left = Math.round(rect.left); var top = Math.round(rect.top); } else { // Offset of the incoming element var left = elem.offsetLeft; var top = elem.offsetTop; // Start with the first offset parent elem = elem.offsetParent; // Stop at the body var body = doc.body; // Border correction is only needed for each parent // not for the incoming element itself while(elem && elem != body){ // Add node offsets left += elem.offsetLeft; top += elem.offsetTop; // Fix missing border left += this.__num(elem, "borderLeftWidth"); top += this.__num(elem, "borderTopWidth"); // One level up (offset hierarchy) elem = elem.offsetParent; }; }; return { left : left, top : top }; } }), /** * Computes the location of the given element in context of * the document dimensions. * * Supported modes: * * * <code>margin</code>: Calculate from the margin box of the element (bigger than the visual appearance: including margins of given element) * * <code>box</code>: Calculates the offset box of the element (default, uses the same size as visible) * * <code>border</code>: Calculate the border box (useful to align to border edges of two elements). * * <code>scroll</code>: Calculate the scroll box (relevant for absolute positioned content). * * <code>padding</code>: Calculate the padding box (relevant for static/relative positioned content). * * @param elem {Element} DOM element to query * @param mode {String?box} A supported option. See comment above. * @return {Map} Returns a map with <code>left</code>, <code>top</code>, * <code>right</code> and <code>bottom</code> which contains the distance * of the element relative to the document. */ get : function(elem, mode){ if(elem.tagName == "BODY"){ var location = this.__getBodyLocation(elem); var left = location.left; var top = location.top; } else { var body = this.__computeBody(elem); var offset = this.__computeOffset(elem); // Reduce by viewport scrolling. // Hint: getBoundingClientRect returns the location of the // element in relation to the viewport which includes // the scrolling var scroll = this.__computeScroll(elem); var left = offset.left + body.left - scroll.left; var top = offset.top + body.top - scroll.top; }; var right = left + elem.offsetWidth; var bottom = top + elem.offsetHeight; if(mode){ // In this modes we want the size as seen from a child what means that we want the full width/height // which may be higher than the outer width/height when the element has scrollbars. if(mode == "padding" || mode == "scroll"){ var overX = qx.bom.element.Style.get(elem, "overflowX"); if(overX == "scroll" || overX == "auto"){ right += elem.scrollWidth - elem.offsetWidth + this.__num(elem, "borderLeftWidth") + this.__num(elem, "borderRightWidth"); }; var overY = qx.bom.element.Style.get(elem, "overflowY"); if(overY == "scroll" || overY == "auto"){ bottom += elem.scrollHeight - elem.offsetHeight + this.__num(elem, "borderTopWidth") + this.__num(elem, "borderBottomWidth"); }; }; switch(mode){case "padding": left += this.__num(elem, "paddingLeft"); top += this.__num(elem, "paddingTop"); right -= this.__num(elem, "paddingRight"); bottom -= this.__num(elem, "paddingBottom");// no break here case "scroll": left -= elem.scrollLeft; top -= elem.scrollTop; right -= elem.scrollLeft; bottom -= elem.scrollTop;// no break here case "border": left += this.__num(elem, "borderLeftWidth"); top += this.__num(elem, "borderTopWidth"); right -= this.__num(elem, "borderRightWidth"); bottom -= this.__num(elem, "borderBottomWidth"); break;case "margin": left -= this.__num(elem, "marginLeft"); top -= this.__num(elem, "marginTop"); right += this.__num(elem, "marginRight"); bottom += this.__num(elem, "marginBottom"); break;}; }; return { left : left, top : top, right : right, bottom : bottom }; }, /** * Get the location of the body element relative to the document. * @param body {Element} The body element. * @return {Map} map with the keys <code>left</code> and <code>top</code> */ __getBodyLocation : function(body){ var top = body.offsetTop; var left = body.offsetLeft; if(qx.core.Environment.get("engine.name") !== "mshtml" || !((parseFloat(qx.core.Environment.get("engine.version")) < 8 || qx.core.Environment.get("browser.documentmode") < 8) && !qx.core.Environment.get("browser.quirksmode"))){ top += this.__num(body, "marginTop"); left += this.__num(body, "marginLeft"); }; if(qx.core.Environment.get("engine.name") === "gecko"){ top += this.__num(body, "borderLeftWidth"); left += this.__num(body, "borderTopWidth"); }; return { left : left, top : top }; }, /** * Computes the location of the given element in context of * the document dimensions. For supported modes please * have a look at the {@link qx.bom.element.Location#get} method. * * @param elem {Element} DOM element to query * @param mode {String} A supported option. See comment above. * @return {Integer} The left distance * of the element relative to the document. */ getLeft : function(elem, mode){ return this.get(elem, mode).left; }, /** * Computes the location of the given element in context of * the document dimensions. For supported modes please * have a look at the {@link qx.bom.element.Location#get} method. * * @param elem {Element} DOM element to query * @param mode {String} A supported option. See comment above. * @return {Integer} The top distance * of the element relative to the document. */ getTop : function(elem, mode){ return this.get(elem, mode).top; }, /** * Computes the location of the given element in context of * the document dimensions. For supported modes please * have a look at the {@link qx.bom.element.Location#get} method. * * @param elem {Element} DOM element to query * @param mode {String} A supported option. See comment above. * @return {Integer} The right distance * of the element relative to the document. */ getRight : function(elem, mode){ return this.get(elem, mode).right; }, /** * Computes the location of the given element in context of * the document dimensions. For supported modes please * have a look at the {@link qx.bom.element.Location#get} method. * * @param elem {Element} DOM element to query * @param mode {String} A supported option. See comment above. * @return {Integer} The bottom distance * of the element relative to the document. */ getBottom : function(elem, mode){ return this.get(elem, mode).bottom; }, /** * Returns the distance between two DOM elements. For supported modes please * have a look at the {@link qx.bom.element.Location#get} method. * * @param elem1 {Element} First element * @param elem2 {Element} Second element * @param mode1 {String?null} Mode for first element * @param mode2 {String?null} Mode for second element * @return {Map} Returns a map with <code>left</code> and <code>top</code> * which contains the distance of the elements from each other. */ getRelative : function(elem1, elem2, mode1, mode2){ var loc1 = this.get(elem1, mode1); var loc2 = this.get(elem2, mode2); return { left : loc1.left - loc2.left, top : loc1.top - loc2.top, right : loc1.right - loc2.right, bottom : loc1.bottom - loc2.bottom }; }, /** * Returns the distance between the given element to its offset parent. * * @param elem {Element} DOM element to query * @return {Map} Returns a map with <code>left</code> and <code>top</code> * which contains the distance of the elements from each other. */ getPosition : function(elem){ return this.getRelative(elem, this.getOffsetParent(elem)); }, /** * Detects the offset parent of the given element * * @param element {Element} Element to query for offset parent * @return {Element} Detected offset parent */ getOffsetParent : function(element){ var offsetParent = element.offsetParent || document.body; var Style = qx.bom.element.Style; while(offsetParent && (!/^body|html$/i.test(offsetParent.tagName) && Style.get(offsetParent, "position") === "static")){ offsetParent = offsetParent.offsetParent; }; return offsetParent; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de 2006 STZ-IDA, Germany, http://www.stz-ida.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Andreas Ecker (ecker) * Andreas Junghans (lucidcake) ************************************************************************ */ /** * Cross-browser wrapper to work with CSS stylesheets. */ qx.Bootstrap.define("qx.bom.Stylesheet", { /* ***************************************************************************** STATICS ***************************************************************************** */ statics : { /** * Include a CSS file * * <em>Note:</em> Using a resource ID as the <code>href</code> parameter * will no longer be supported. Call * <code>qx.util.ResourceManager.getInstance().toUri(href)</code> to get * valid URI to be used with this method. * * @param href {String} Href value * @param doc {Document?} Document to modify */ includeFile : function(href, doc){ if(!doc){ doc = document; }; var el = doc.createElement("link"); el.type = "text/css"; el.rel = "stylesheet"; el.href = href; var head = doc.getElementsByTagName("head")[0]; head.appendChild(el); }, /** * Create a new Stylesheet node and append it to the document * * @param text {String?} optional string of css rules * @return {Stylesheet} the generates stylesheet element */ createElement : function(text){ if(qx.core.Environment.get("html.stylesheet.createstylesheet")){ var sheet = document.createStyleSheet(); if(text){ sheet.cssText = text; }; return sheet; } else { var elem = document.createElement("style"); elem.type = "text/css"; if(text){ elem.appendChild(document.createTextNode(text)); }; document.getElementsByTagName("head")[0].appendChild(elem); return elem.sheet; }; }, /** * Insert a new CSS rule into a given Stylesheet * * @param sheet {Object} the target Stylesheet object * @param selector {String} the selector * @param entry {String} style rule */ addRule : function(sheet, selector, entry){ if(qx.core.Environment.get("html.stylesheet.insertrule")){ sheet.insertRule(selector + "{" + entry + "}", sheet.cssRules.length); } else { sheet.addRule(selector, entry); }; }, /** * Remove a CSS rule from a stylesheet * * @param sheet {Object} the Stylesheet * @param selector {String} the Selector of the rule to remove */ removeRule : function(sheet, selector){ if(qx.core.Environment.get("html.stylesheet.deleterule")){ var rules = sheet.cssRules; var len = rules.length; for(var i = len - 1;i >= 0;--i){ if(rules[i].selectorText == selector){ sheet.deleteRule(i); }; }; } else { var rules = sheet.rules; var len = rules.length; for(var i = len - 1;i >= 0;--i){ if(rules[i].selectorText == selector){ sheet.removeRule(i); }; }; }; }, /** * Remove the given sheet from its owner. * @param sheet {Object} the stylesheet object */ removeSheet : function(sheet){ var owner = sheet.ownerNode ? sheet.ownerNode : sheet.owningElement; qx.dom.Element.removeChild(owner, owner.parentNode); }, /** * Remove all CSS rules from a stylesheet * * @param sheet {Object} the stylesheet object */ removeAllRules : function(sheet){ if(qx.core.Environment.get("html.stylesheet.deleterule")){ var rules = sheet.cssRules; var len = rules.length; for(var i = len - 1;i >= 0;i--){ sheet.deleteRule(i); }; } else { var rules = sheet.rules; var len = rules.length; for(var i = len - 1;i >= 0;i--){ sheet.removeRule(i); }; }; }, /** * Add an import of an external CSS file to a stylesheet * * @param sheet {Object} the stylesheet object * @param url {String} URL of the external stylesheet file */ addImport : function(sheet, url){ if(qx.core.Environment.get("html.stylesheet.addimport")){ sheet.addImport(url); } else { sheet.insertRule('@import "' + url + '";', sheet.cssRules.length); }; }, /** * Removes an import from a stylesheet * * @param sheet {Object} the stylesheet object * @param url {String} URL of the imported CSS file */ removeImport : function(sheet, url){ if(qx.core.Environment.get("html.stylesheet.removeimport")){ var imports = sheet.imports; var len = imports.length; for(var i = len - 1;i >= 0;i--){ if(imports[i].href == url || imports[i].href == qx.util.Uri.getAbsolute(url)){ sheet.removeImport(i); }; }; } else { var rules = sheet.cssRules; var len = rules.length; for(var i = len - 1;i >= 0;i--){ if(rules[i].href == url){ sheet.deleteRule(i); }; }; }; }, /** * Remove all imports from a stylesheet * * @param sheet {Object} the stylesheet object */ removeAllImports : function(sheet){ if(qx.core.Environment.get("html.stylesheet.removeimport")){ var imports = sheet.imports; var len = imports.length; for(var i = len - 1;i >= 0;i--){ sheet.removeImport(i); }; } else { var rules = sheet.cssRules; var len = rules.length; for(var i = len - 1;i >= 0;i--){ if(rules[i].type == rules[i].IMPORT_RULE){ sheet.deleteRule(i); }; }; }; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2011 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Daniel Wagner (d_wagner) ************************************************************************ */ /** * Internal class which contains the checks used by {@link qx.core.Environment}. * All checks in here are marked as internal which means you should never use * them directly. * * This class contains checks related to Stylesheet objects. * * @internal */ qx.Bootstrap.define("qx.bom.client.Stylesheet", { statics : { /** * Returns a stylesheet to be used for feature checks * * @return {Stylesheet} Stylesheet element */ __getStylesheet : function(){ if(!qx.bom.client.Stylesheet.__stylesheet){ qx.bom.client.Stylesheet.__stylesheet = qx.bom.Stylesheet.createElement(); }; return qx.bom.client.Stylesheet.__stylesheet; }, /** * Check for IE's non-standard document.createStyleSheet function. * In IE9 (standards mode), the typeof check returns "function" so false is * returned. This is intended since IE9 supports the DOM-standard * createElement("style") which should be used instead. * * @internal * @return {Boolean} <code>true</code> if the browser supports * document.createStyleSheet */ getCreateStyleSheet : function(){ return typeof document.createStyleSheet === "object"; }, /** * Check for stylesheet.insertRule. Legacy IEs do not support this. * * @internal * @return {Boolean} <code>true</code> if insertRule is supported */ getInsertRule : function(){ return typeof qx.bom.client.Stylesheet.__getStylesheet().insertRule === "function"; }, /** * Check for stylesheet.deleteRule. Legacy IEs do not support this. * * @internal * @return {Boolean} <code>true</code> if deleteRule is supported */ getDeleteRule : function(){ return typeof qx.bom.client.Stylesheet.__getStylesheet().deleteRule === "function"; }, /** * Decides whether to use the legacy IE-only stylesheet.addImport or the * DOM-standard stylesheet.insertRule('@import [...]') * * @internal * @return {Boolean} <code>true</code> if stylesheet.addImport is supported */ getAddImport : function(){ return (typeof qx.bom.client.Stylesheet.__getStylesheet().addImport === "object"); }, /** * Decides whether to use the legacy IE-only stylesheet.removeImport or the * DOM-standard stylesheet.deleteRule('@import [...]') * * @internal * @return {Boolean} <code>true</code> if stylesheet.removeImport is supported */ getRemoveImport : function(){ return (typeof qx.bom.client.Stylesheet.__getStylesheet().removeImport === "object"); } }, defer : function(statics){ qx.core.Environment.add("html.stylesheet.createstylesheet", statics.getCreateStyleSheet); qx.core.Environment.add("html.stylesheet.insertrule", statics.getInsertRule); qx.core.Environment.add("html.stylesheet.deleterule", statics.getDeleteRule); qx.core.Environment.add("html.stylesheet.addimport", statics.getAddImport); qx.core.Environment.add("html.stylesheet.removeimport", statics.getRemoveImport); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) ************************************************************************ */ /** * Manages children structures of an element. Easy and convenient APIs * to insert, remove and replace children. */ qx.Bootstrap.define("qx.dom.Element", { statics : { /** * {Map} A list of all attributes which needs to be part of the initial element to work correctly * * @internal */ __initialAttributes : { "onload" : true, "onpropertychange" : true, "oninput" : true, "onchange" : true, "name" : true, "type" : true, "checked" : true, "disabled" : true }, /** * Whether the given <code>child</code> is a child of <code>parent</code> * * @param parent {Element} parent element * @param child {Node} child node * @return {Boolean} true when the given <code>child</code> is a child of <code>parent</code> */ hasChild : function(parent, child){ return child.parentNode === parent; }, /** * Whether the given <code>element</code> has children. * * @param element {Element} element to test * @return {Boolean} true when the given <code>element</code> has at least one child node */ hasChildren : function(element){ return !!element.firstChild; }, /** * Whether the given <code>element</code> has any child elements. * * @param element {Element} element to test * @return {Boolean} true when the given <code>element</code> has at least one child element */ hasChildElements : function(element){ element = element.firstChild; while(element){ if(element.nodeType === 1){ return true; }; element = element.nextSibling; }; return false; }, /** * Returns the parent element of the given element. * * @param element {Element} Element to find the parent for * @return {Element} The parent element */ getParentElement : function(element){ return element.parentNode; }, /** * Checks if the <code>element</code> is in the DOM, but note that * the method is very expensive! * * @param element {Element} The DOM element to check. * @param win {Window} The window to check for. * @return {Boolean} <code>true</code> if the <code>element</code> is in * the DOM, <code>false</code> otherwise. */ isInDom : function(element, win){ if(!win){ win = window; }; var domElements = win.document.getElementsByTagName(element.nodeName); for(var i = 0,l = domElements.length;i < l;i++){ if(domElements[i] === element){ return true; }; }; return false; }, /* --------------------------------------------------------------------------- INSERTION --------------------------------------------------------------------------- */ /** * Inserts <code>node</code> at the given <code>index</code> * inside <code>parent</code>. * * @param node {Node} node to insert * @param parent {Element} parent element node * @param index {Integer} where to insert * @return {Boolean} returns true (successful) */ insertAt : function(node, parent, index){ var ref = parent.childNodes[index]; if(ref){ parent.insertBefore(node, ref); } else { parent.appendChild(node); }; return true; }, /** * Insert <code>node</code> into <code>parent</code> as first child. * Indexes of other children will be incremented by one. * * @param node {Node} Node to insert * @param parent {Element} parent element node * @return {Boolean} returns true (successful) */ insertBegin : function(node, parent){ if(parent.firstChild){ this.insertBefore(node, parent.firstChild); } else { parent.appendChild(node); }; return true; }, /** * Insert <code>node</code> into <code>parent</code> as last child. * * @param node {Node} Node to insert * @param parent {Element} parent element node * @return {Boolean} returns true (successful) */ insertEnd : function(node, parent){ parent.appendChild(node); return true; }, /** * Inserts <code>node</code> before <code>ref</code> in the same parent. * * @param node {Node} Node to insert * @param ref {Node} Node which will be used as reference for insertion * @return {Boolean} returns true (successful) */ insertBefore : function(node, ref){ ref.parentNode.insertBefore(node, ref); return true; }, /** * Inserts <code>node</code> after <code>ref</code> in the same parent. * * @param node {Node} Node to insert * @param ref {Node} Node which will be used as reference for insertion * @return {Boolean} returns true (successful) */ insertAfter : function(node, ref){ var parent = ref.parentNode; if(ref == parent.lastChild){ parent.appendChild(node); } else { return this.insertBefore(node, ref.nextSibling); }; return true; }, /* --------------------------------------------------------------------------- REMOVAL --------------------------------------------------------------------------- */ /** * Removes the given <code>node</code> from its parent element. * * @param node {Node} Node to remove * @return {Boolean} <code>true</code> when node was successfully removed, * otherwise <code>false</code> */ remove : function(node){ if(!node.parentNode){ return false; }; node.parentNode.removeChild(node); return true; }, /** * Removes the given <code>node</code> from the <code>parent</code>. * * @param node {Node} Node to remove * @param parent {Element} parent element which contains the <code>node</code> * @return {Boolean} <code>true</code> when node was successfully removed, * otherwise <code>false</code> */ removeChild : function(node, parent){ if(node.parentNode !== parent){ return false; }; parent.removeChild(node); return true; }, /** * Removes the node at the given <code>index</code> * from the <code>parent</code>. * * @param index {Integer} position of the node which should be removed * @param parent {Element} parent DOM element * @return {Boolean} <code>true</code> when node was successfully removed, * otherwise <code>false</code> */ removeChildAt : function(index, parent){ var child = parent.childNodes[index]; if(!child){ return false; }; parent.removeChild(child); return true; }, /* --------------------------------------------------------------------------- REPLACE --------------------------------------------------------------------------- */ /** * Replaces <code>oldNode</code> with <code>newNode</code> in the current * parent of <code>oldNode</code>. * * @param newNode {Node} DOM node to insert * @param oldNode {Node} DOM node to remove * @return {Boolean} <code>true</code> when node was successfully replaced */ replaceChild : function(newNode, oldNode){ if(!oldNode.parentNode){ return false; }; oldNode.parentNode.replaceChild(newNode, oldNode); return true; }, /** * Replaces the node at <code>index</code> with <code>newNode</code> in * the given parent. * * @param newNode {Node} DOM node to insert * @param index {Integer} position of old DOM node * @param parent {Element} parent DOM element * @return {Boolean} <code>true</code> when node was successfully replaced */ replaceAt : function(newNode, index, parent){ var oldNode = parent.childNodes[index]; if(!oldNode){ return false; }; parent.replaceChild(newNode, oldNode); return true; }, /** * Stores helper element for element creation in WebKit * * @internal */ __helperElement : { }, /** * Saves whether a helper element is needed for each window. * * @internal */ __allowMarkup : { }, /** * Detects if the DOM support a <code>document.createElement</code> call with a * <code>String</code> as markup like: * * <pre class="javascript"> * document.createElement("<INPUT TYPE='RADIO' NAME='RADIOTEST' VALUE='Second Choice'>"); * </pre> * * Element creation with markup is not standard compatible with Document Object Model (Core) Level 1, but * Internet Explorer supports it. With an exception that IE9 in IE9 standard mode is standard compatible and * doesn't support element creation with markup. * * @param win {Window?} Window to check for * @return {Boolean} <code>true</code> if the DOM supports it, <code>false</code> otherwise. */ _allowCreationWithMarkup : function(win){ if(!win){ win = window; }; // key is needed to allow using different windows var key = win.location.href; if(qx.dom.Element.__allowMarkup[key] == undefined){ try{ win.document.createElement("<INPUT TYPE='RADIO' NAME='RADIOTEST' VALUE='Second Choice'>"); qx.dom.Element.__allowMarkup[key] = true; } catch(e) { qx.dom.Element.__allowMarkup[key] = false; }; }; return qx.dom.Element.__allowMarkup[key]; }, /** * Creates and returns a DOM helper element. * * @param win {Window?} Window to create the element for * @return {Element} The created element node */ getHelperElement : function(win){ if(!win){ win = window; }; // key is needed to allow using different windows var key = win.location.href; if(!qx.dom.Element.__helperElement[key]){ var helper = qx.dom.Element.__helperElement[key] = win.document.createElement("div"); // innerHTML will only parsed correctly if element is appended to document if(qx.core.Environment.get("engine.name") == "webkit"){ helper.style.display = "none"; win.document.body.appendChild(helper); }; }; return qx.dom.Element.__helperElement[key]; }, /** * Creates a DOM element. * * Attributes may be given directly with this call. This is critical * for some attributes e.g. name, type, ... in many clients. * * Depending on the kind of attributes passed, <code>innerHTML</code> may be * used internally to assemble the element. Please make sure you understand * the security implications. See {@link qx.bom.Html#clean}. * * @param name {String} Tag name of the element * @param attributes {Map?} Map of attributes to apply * @param win {Window?} Window to create the element for * @return {Element} The created element node */ create : function(name, attributes, win){ if(!win){ win = window; }; if(!name){ throw new Error("The tag name is missing!"); }; var initial = this.__initialAttributes; var attributesHtml = ""; for(var key in attributes){ if(initial[key]){ attributesHtml += key + "='" + attributes[key] + "' "; }; }; var element; // If specific attributes are defined we need to process // the element creation in a more complex way. if(attributesHtml != ""){ if(qx.dom.Element._allowCreationWithMarkup(win)){ element = win.document.createElement("<" + name + " " + attributesHtml + ">"); } else { var helper = qx.dom.Element.getHelperElement(win); helper.innerHTML = "<" + name + " " + attributesHtml + "></" + name + ">"; element = helper.firstChild; }; } else { element = win.document.createElement(name); }; for(var key in attributes){ if(!initial[key]){ qx.bom.element.Attribute.set(element, key, attributes[key]); }; }; return element; }, /** * Removes all content from the given element * * @param element {Element} element to clean * @return {String} empty string (new HTML content) */ empty : function(element){ return element.innerHTML = ""; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2010 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Alexander Steitz (aback) ====================================================================== This class contains code based on the following work: * Prototype JS http://www.prototypejs.org/ Version 1.5 Copyright: (c) 2006-2007, Prototype Core Team License: MIT: http://www.opensource.org/licenses/mit-license.php Authors: * Prototype Core Team ---------------------------------------------------------------------- Copyright (c) 2005-2008 Sam Stephenson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ************************************************************************ */ /** * Attribute/Property handling for DOM HTML elements. * * Also includes support for HTML properties like <code>checked</code> * or <code>value</code>. This feature set is supported cross-browser * through one common interface and is independent of the differences between * the multiple implementations. * * Supports applying text and HTML content using the attribute names * <code>text</code> and <code>html</code>. */ qx.Bootstrap.define("qx.bom.element.Attribute", { /* ***************************************************************************** STATICS ***************************************************************************** */ statics : { /** Internal map of attribute conversions */ __hints : { // Name translation table (camelcase is important for some attributes) names : { "class" : "className", "for" : "htmlFor", html : "innerHTML", text : qx.core.Environment.get("html.element.textcontent") ? "textContent" : "innerText", colspan : "colSpan", rowspan : "rowSpan", valign : "vAlign", datetime : "dateTime", accesskey : "accessKey", tabindex : "tabIndex", maxlength : "maxLength", readonly : "readOnly", longdesc : "longDesc", cellpadding : "cellPadding", cellspacing : "cellSpacing", frameborder : "frameBorder", usemap : "useMap" }, // Attributes which are only applyable on a DOM element (not using compile()) runtime : { "html" : 1, "text" : 1 }, // Attributes which are (forced) boolean bools : { compact : 1, nowrap : 1, ismap : 1, declare : 1, noshade : 1, checked : 1, disabled : 1, readOnly : 1, multiple : 1, selected : 1, noresize : 1, defer : 1, allowTransparency : 1 }, // Interpreted as property (element.property) property : { // Used by qx.html.Element $$html : 1, // Used by qx.ui.core.Widget $$widget : 1, // Native properties disabled : 1, checked : 1, readOnly : 1, multiple : 1, selected : 1, value : 1, maxLength : 1, className : 1, innerHTML : 1, innerText : 1, textContent : 1, htmlFor : 1, tabIndex : 1 }, qxProperties : { $$widget : 1, $$html : 1 }, // Default values when "null" is given to a property propertyDefault : { disabled : false, checked : false, readOnly : false, multiple : false, selected : false, value : "", className : "", innerHTML : "", innerText : "", textContent : "", htmlFor : "", tabIndex : 0, maxLength : qx.core.Environment.select("engine.name", { "mshtml" : 2147483647, "webkit" : 524288, "default" : -1 }) }, // Properties which can be removed to reset them removeableProperties : { disabled : 1, multiple : 1, maxLength : 1 }, // Use getAttribute(name, 2) for these to query for the real value, not // the interpreted one. original : { href : 1, src : 1, type : 1 } }, /** * Compiles an incoming attribute map to a string which * could be used when building HTML blocks using innerHTML. * * This method silently ignores runtime attributes like * <code>html</code> or <code>text</code>. * * @param map {Map} Map of attributes. The key is the name of the attribute. * @return {String} Returns a compiled string ready for usage. */ compile : function(map){ var html = []; var runtime = this.__hints.runtime; for(var key in map){ if(!runtime[key]){ html.push(key, "='", map[key], "'"); }; }; return html.join(""); }, /** * Returns the value of the given HTML attribute * * @param element {Element} The DOM element to query * @param name {String} Name of the attribute * @return {var} The value of the attribute */ get : function(element, name){ var hints = this.__hints; var value; // normalize name name = hints.names[name] || name; // respect original values // http://msdn2.microsoft.com/en-us/library/ms536429.aspx if(qx.core.Environment.get("engine.name") == "mshtml" && parseInt(qx.core.Environment.get("browser.documentmode"), 10) < 8 && hints.original[name]){ value = element.getAttribute(name, 2); } else if(hints.property[name]){ value = element[name]; if(typeof hints.propertyDefault[name] !== "undefined" && value == hints.propertyDefault[name]){ // only return null for all non-boolean properties if(typeof hints.bools[name] === "undefined"){ return null; } else { return value; }; }; } else { // fallback to attribute value = element.getAttribute(name); }; if(hints.bools[name]){ return !!value; }; return value; }, /** * Sets an HTML attribute on the given DOM element * * @param element {Element} The DOM element to modify * @param name {String} Name of the attribute * @param value {var} New value of the attribute */ set : function(element, name, value){ if(typeof value === "undefined"){ return; }; var hints = this.__hints; // normalize name name = hints.names[name] || name; // respect booleans if(hints.bools[name]){ value = !!value; }; // apply attribute // only properties which can be applied by the browser or qxProperties // otherwise use the attribute methods if(hints.property[name] && (!(element[name] === undefined) || hints.qxProperties[name])){ // resetting the attribute/property if(value == null){ // for properties which need to be removed for a correct reset if(hints.removeableProperties[name]){ element.removeAttribute(name); return; } else if(typeof hints.propertyDefault[name] !== "undefined"){ value = hints.propertyDefault[name]; }; }; element[name] = value; } else { if(value === true){ element.setAttribute(name, name); } else if(value === false || value === null){ element.removeAttribute(name); } else { element.setAttribute(name, value); }; }; }, /** * Resets an HTML attribute on the given DOM element * * @param element {Element} The DOM element to modify * @param name {String} Name of the attribute */ reset : function(element, name){ this.set(element, name, null); } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /** * Utility for checking the type of a variable. * It adds a <code>type</code> key static to q and offers the given method. * * <pre class="javascript"> * q.type.get("abc"); // return "String" e.g. * </pre> */ qx.Bootstrap.define("qx.module.util.Type", { statics : { /** * Get the internal class of the value. The following classes are possible: * <code>"String"</code>, * <code>"Array"</code>, * <code>"Object"</code>, * <code>"RegExp"</code>, * <code>"Number"</code>, * <code>"Boolean"</code>, * <code>"Date"</code>, * <code>"Function"</code>, * <code>"Error"</code> * </pre> * @attachStatic {qxWeb, type.get} * @signature function(value) * @param value {var} Value to get the class for. * @return {String} The internal class of the value. */ get : qx.Bootstrap.getClass }, defer : function(statics){ qxWeb.$attachStatic({ type : { get : statics.get } }); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ====================================================================== This class contains code based on the following work: * es5-shim Code: https://github.com/kriskowal/es5-shim/ Copyright: (c) 2009, 2010 Kristopher Michael Kowal License: https://github.com/kriskowal/es5-shim/blob/master/LICENSE ---------------------------------------------------------------------- Copyright 2009, 2010 Kristopher Michael Kowal. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ---------------------------------------------------------------------- Version: Snapshot taken on 2012-07-25,: commit 9f539abd9aa9950e1d907077a4be7f5133a00e52 ************************************************************************ */ /** * This class takes care of the normalization of the native 'Function' object. * Therefore it checks the availability of the following methods and appends * it, if not available. This means you can use the methods during * development in every browser. For usage samples, check out the attached links. * * *bind*: * <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind">MDN documentation</a> | * <a href="http://es5.github.com/#x15.3.4.5">Annotated ES5 Spec</a> */ qx.Bootstrap.define("qx.lang.normalize.Function", { defer : function(){ // bind if(!qx.core.Environment.get("ecmascript.function.bind")){ var slice = Array.prototype.slice; Function.prototype.bind = function(that){ // .length is 1 // 1. Let Target be the this value. var target = this; // 2. If IsCallable(Target) is false, throw a TypeError exception. if(typeof target != "function"){ throw new TypeError("Function.prototype.bind called on incompatible " + target); }; // 3. Let A be a new (possibly empty) internal list of all of the // argument values provided after thisArg (arg1, arg2 etc), in order. // XXX slicedArgs will stand in for "A" if used var args = slice.call(arguments, 1); // for normal call // 4. Let F be a new native ECMAScript object. // 11. Set the [[Prototype]] internal property of F to the standard // built-in Function prototype object as specified in 15.3.3.1. // 12. Set the [[Call]] internal property of F as described in // 15.3.4.5.1. // 13. Set the [[Construct]] internal property of F as described in // 15.3.4.5.2. // 14. Set the [[HasInstance]] internal property of F as described in // 15.3.4.5.3. var bound = function(){ if(this instanceof bound){ // 15.3.4.5.2 [[Construct]] // When the [[Construct]] internal method of a function object, // F that was created using the bind function is called with a // list of arguments ExtraArgs, the following steps are taken: // 1. Let target be the value of F's [[TargetFunction]] // internal property. // 2. If target has no [[Construct]] internal method, a // TypeError exception is thrown. // 3. Let boundArgs be the value of F's [[BoundArgs]] internal // property. // 4. Let args be a new list containing the same values as the // list boundArgs in the same order followed by the same // values as the list ExtraArgs in the same order. // 5. Return the result of calling the [[Construct]] internal // method of target providing args as the arguments. var F = function(){ }; F.prototype = target.prototype; var self = new F; var result = target.apply(self, args.concat(slice.call(arguments))); if(Object(result) === result){ return result; }; return self; } else { // 15.3.4.5.1 [[Call]] // When the [[Call]] internal method of a function object, F, // which was created using the bind function is called with a // this value and a list of arguments ExtraArgs, the following // steps are taken: // 1. Let boundArgs be the value of F's [[BoundArgs]] internal // property. // 2. Let boundThis be the value of F's [[BoundThis]] internal // property. // 3. Let target be the value of F's [[TargetFunction]] internal // property. // 4. Let args be a new list containing the same values as the // list boundArgs in the same order followed by the same // values as the list ExtraArgs in the same order. // 5. Return the result of calling the [[Call]] internal method // of target providing boundThis as the this value and // providing args as the arguments. // equiv: target.call(this, ...boundArgs, ...args) return target.apply(that, args.concat(slice.call(arguments))); }; }; // XXX bound.length is never writable, so don't even try // // 15. If the [[Class]] internal property of Target is "Function", then // a. Let L be the length property of Target minus the length of A. // b. Set the length own property of F to either 0 or L, whichever is // larger. // 16. Else set the length own property of F to 0. // 17. Set the attributes of the length own property of F to the values // specified in 15.3.5.1. // TODO // 18. Set the [[Extensible]] internal property of F to true. // TODO // 19. Let thrower be the [[ThrowTypeError]] function Object (13.2.3). // 20. Call the [[DefineOwnProperty]] internal method of F with // arguments "caller", PropertyDescriptor {[[Get]]: thrower, [[Set]]: // thrower, [[Enumerable]]: false, [[Configurable]]: false}, and // false. // 21. Call the [[DefineOwnProperty]] internal method of F with // arguments "arguments", PropertyDescriptor {[[Get]]: thrower, // [[Set]]: thrower, [[Enumerable]]: false, [[Configurable]]: false}, // and false. // NOTE Function objects created using Function.prototype.bind do not // have a prototype property or the [[Code]], [[FormalParameters]], and // [[Scope]] internal properties. // XXX can't delete prototype in pure-js. // 22. Return F. return bound; }; }; } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /** * This class takes care of the normalization of the native 'Error' object. * It contains a simple bugfix for toString which might not print out the proper * error message. * * *toString*: * <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Error/toString">MDN documentation</a> | * <a href="http://es5.github.com/#x15.11.4.4">Annotated ES5 Spec</a> */ qx.Bootstrap.define("qx.lang.normalize.Error", { defer : function(){ // toString if(!qx.core.Environment.get("ecmascript.error.toString")){ Error.prototype.toString = function(){ var name = this.name || "Error"; var message = this.message || ""; if(name === "" && message === ""){ return "Error"; }; if(name === ""){ return message; }; if(message === ""){ return name; }; return name + ": " + message; }; }; } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) * Daniel Wagner (danielwagner) ************************************************************************ */ /* ************************************************************************ #require(qx.lang.normalize.Function) #require(qx.lang.normalize.String) #require(qx.lang.normalize.Date) #require(qx.lang.normalize.Array) #require(qx.lang.normalize.Error) #require(qx.lang.normalize.Object) ************************************************************************ */ /** * Adds JavaScript features that may not be supported by all clients. */ qx.Bootstrap.define("qx.module.Polyfill", { }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2011-2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) * Daniel Wagner (danielwagner) ************************************************************************ */ /* ************************************************************************ #require(qx.module.Polyfill) ************************************************************************ */ /** * Support for native and custom events. */ qx.Bootstrap.define("qx.module.Event", { statics : { /** * Event normalization registry * * @internal */ __normalizations : { }, /** * Registry of event hooks * @internal */ __hooks : { on : { }, off : { } }, /** * Registers a listener for the given event type on each item in the * collection. This can be either native or custom events. * * @attach {qxWeb} * @param type {String} Type of the event to listen for * @param listener {Function} Listener callback * @param context {Object?} Context the callback function will be executed in. * Default: The element on which the listener was registered * @return {qxWeb} The collection for chaining */ on : function(type, listener, context){ for(var i = 0;i < this.length;i++){ var el = this[i]; var ctx = context || qxWeb(el); // call hooks var hooks = qx.module.Event.__hooks.on; // generic var typeHooks = hooks["*"] || []; // type specific if(hooks[type]){ typeHooks = typeHooks.concat(hooks[type]); }; for(var j = 0,m = typeHooks.length;j < m;j++){ typeHooks[j](el, type, listener, context); }; var bound = function(event){ // apply normalizations var registry = qx.module.Event.__normalizations; // generic var normalizations = registry["*"] || []; // type specific if(registry[type]){ normalizations = normalizations.concat(registry[type]); }; for(var x = 0,y = normalizations.length;x < y;x++){ event = normalizations[x](event, el, type); }; // call original listener with normalized event listener.apply(this, [event]); }.bind(ctx); bound.original = listener; // add native listener if(qx.bom.Event.supportsEvent(el, type)){ qx.bom.Event.addNativeListener(el, type, bound); }; // create an emitter if necessary if(!el.__emitter){ el.__emitter = new qx.event.Emitter(); }; var id = el.__emitter.on(type, bound, ctx); if(!el.__listener){ el.__listener = { }; }; if(!el.__listener[type]){ el.__listener[type] = { }; }; el.__listener[type][id] = bound; if(!context){ // store a reference to the dynamically created context so we know // what to check for when removing the listener if(!el.__ctx){ el.__ctx = { }; }; el.__ctx[id] = ctx; }; }; return this; }, /** * Unregisters event listeners for the given type from each element in the * collection. * * @attach {qxWeb} * @param type {String} Type of the event * @param listener {Function} Listener callback * @param context {Object?} Listener callback context * @return {qxWeb} The collection for chaining */ off : function(type, listener, context){ for(var j = 0;j < this.length;j++){ var el = this[j]; // continue if no listener are available if(!el.__listener){ continue; }; for(var id in el.__listener[type]){ var storedListener = el.__listener[type][id]; if(storedListener == listener || storedListener.original == listener){ // get the stored context var hasStoredContext = typeof el.__ctx !== "undefined" && el.__ctx[id]; if(!context && hasStoredContext){ var storedContext = el.__ctx[id]; }; // remove the listener from the emitter el.__emitter.off(type, storedListener, storedContext || context); // check if it's a bound listener which means it was a native event if(storedListener.original == listener){ // remove the native listener qx.bom.Event.removeNativeListener(el, type, storedListener); }; delete el.__listener[type][id]; if(hasStoredContext){ delete el.__ctx[id]; }; }; }; // call hooks var hooks = qx.module.Event.__hooks.off; // generic var typeHooks = hooks["*"] || []; // type specific if(hooks[type]){ typeHooks = typeHooks.concat(hooks[type]); }; for(var i = 0,m = typeHooks.length;i < m;i++){ typeHooks[i](el, type, listener, context); }; }; return this; }, /** * Fire an event of the given type. * * @attach {qxWeb} * @param type {String} Event type * @param data {var?} Optional data that will be passed to the listener * callback function. * @return {qxWeb} The collection for chaining */ emit : function(type, data){ for(var j = 0;j < this.length;j++){ var el = this[j]; if(el.__emitter){ el.__emitter.emit(type, data); }; }; return this; }, /** * Attaches a listener for the given event that will be executed only once. * * @attach {qxWeb} * @param type {String} Type of the event to listen for * @param listener {Function} Listener callback * @param context {Object?} Context the callback function will be executed in. * Default: The element on which the listener was registered * @return {qxWeb} The collection for chaining */ once : function(type, listener, context){ var self = this; var wrappedListener = function(data){ self.off(type, wrappedListener, context); listener.call(this, data); }; this.on(type, wrappedListener, context); return this; }, /** * Checks if one or more listeners for the given event type are attached to * the first element in the collection * * @attach {qxWeb} * @param type {String} Event type, e.g. <code>mousedown</code> * @return {Boolean} <code>true</code> if one or more listeners are attached */ hasListener : function(type){ if(!this[0] || !this[0].__emitter || !this[0].__emitter.getListeners()[type]){ return false; }; return this[0].__emitter.getListeners()[type].length > 0; }, /** * Copies any event listeners that are attached to the elements in the * collection to the provided target element * * @internal * @param target {Element} Element to attach the copied listeners to */ copyEventsTo : function(target){ // Copy both arrays to make sure the original collections are not manipulated. // If e.g. the 'target' array contains a DOM node with child nodes we run into // problems because the 'target' array is flattened within this method. var source = this.concat(); var targetCopy = target.concat(); // get all children of source and target for(var i = source.length - 1;i >= 0;i--){ var descendants = source[i].getElementsByTagName("*"); for(var j = 0;j < descendants.length;j++){ source.push(descendants[j]); }; }; for(var i = targetCopy.length - 1;i >= 0;i--){ var descendants = targetCopy[i].getElementsByTagName("*"); for(var j = 0;j < descendants.length;j++){ targetCopy.push(descendants[j]); }; }; // make sure no emitter object has been copied targetCopy.forEach(function(el){ el.__emitter = null; }); for(var i = 0;i < source.length;i++){ var el = source[i]; if(!el.__emitter){ continue; }; var storage = el.__emitter.getListeners(); for(var name in storage){ for(var j = storage[name].length - 1;j >= 0;j--){ var listener = storage[name][j].listener; if(listener.original){ listener = listener.original; }; qxWeb(targetCopy[i]).on(name, listener, storage[name][j].ctx); }; }; }; }, __isReady : false, /** * Executes the given function once the document is ready. * * @attachStatic {qxWeb} * @param callback {Function} callback function */ ready : function(callback){ // DOM is already ready if(document.readyState === "complete"){ window.setTimeout(callback, 1); return; }; // listen for the load event so the callback is executed no matter what var onWindowLoad = function(){ qx.module.Event.__isReady = true; callback(); }; qxWeb(window).on("load", onWindowLoad); var wrappedCallback = function(){ qxWeb(window).off("load", onWindowLoad); callback(); }; // Listen for DOMContentLoaded event if available (no way to reliably detect // support) if(qxWeb.env.get("engine.name") !== "mshtml" || qxWeb.env.get("browser.documentmode") > 8){ qx.bom.Event.addNativeListener(document, "DOMContentLoaded", wrappedCallback); } else { // Continually check to see if the document is ready var timer = function(){ // onWindowLoad already executed if(qx.module.Event.__isReady){ return; }; try{ // If DOMContentLoaded is unavailable, use the trick by Diego Perini // http://javascript.nwbox.com/IEContentLoaded/ document.documentElement.doScroll("left"); if(document.body){ wrappedCallback(); }; } catch(error) { window.setTimeout(timer, 100); }; }; timer(); }; }, /** * Registers a normalization function for the given event types. Listener * callbacks for these types will be called with the return value of the * normalization function instead of the regular event object. * * The normalizer will be called with two arguments: The original event * object and the element on which the event was triggered * * @attachStatic {qxWeb, $registerEventNormalization} * @param types {String[]} List of event types to be normalized. Use an * asterisk (<code>*</code>) to normalize all event types * @param normalizer {Function} Normalizer function */ $registerNormalization : function(types, normalizer){ if(!qx.lang.Type.isArray(types)){ types = [types]; }; var registry = qx.module.Event.__normalizations; for(var i = 0,l = types.length;i < l;i++){ var type = types[i]; if(qx.lang.Type.isFunction(normalizer)){ if(!registry[type]){ registry[type] = []; }; registry[type].push(normalizer); }; }; }, /** * Unregisters a normalization function from the given event types. * * @attachStatic {qxWeb, $unregisterEventNormalization} * @param types {String[]} List of event types * @param normalizer {Function} Normalizer function */ $unregisterNormalization : function(types, normalizer){ if(!qx.lang.Type.isArray(types)){ types = [types]; }; var registry = qx.module.Event.__normalizations; for(var i = 0,l = types.length;i < l;i++){ var type = types[i]; if(registry[type]){ qx.lang.Array.remove(registry[type], normalizer); }; }; }, /** * Returns all registered event normalizers * * @attachStatic {qxWeb, $getEventNormalizationRegistry} * @return {Map} Map of event types/normalizer functions */ $getRegistry : function(){ return qx.module.Event.__normalizations; }, /** * Registers an event hook for the given event types. * * @attachStatic {qxWeb, $registerEventHook} * @param types {String[]} List of event types * @param registerHook {Function} Hook function to be called on event registration * @param unregisterHook {Function?} Hook function to be called on event deregistration * @internal */ $registerEventHook : function(types, registerHook, unregisterHook){ if(!qx.lang.Type.isArray(types)){ types = [types]; }; var onHooks = qx.module.Event.__hooks.on; for(var i = 0,l = types.length;i < l;i++){ var type = types[i]; if(qx.lang.Type.isFunction(registerHook)){ if(!onHooks[type]){ onHooks[type] = []; }; onHooks[type].push(registerHook); }; }; if(!unregisterHook){ return; }; var offHooks = qx.module.Event.__hooks.off; for(var i = 0,l = types.length;i < l;i++){ var type = types[i]; if(qx.lang.Type.isFunction(unregisterHook)){ if(!offHooks[type]){ offHooks[type] = []; }; offHooks[type].push(unregisterHook); }; }; }, /** * Unregisters a hook from the given event types. * * @attachStatic {qxWeb, $unregisterEventHooks} * @param types {String[]} List of event types * @param registerHook {Function} Hook function to be called on event registration * @param unregisterHook {Function?} Hook function to be called on event deregistration * @internal */ $unregisterEventHook : function(types, registerHook, unregisterHook){ if(!qx.lang.Type.isArray(types)){ types = [types]; }; var onHooks = qx.module.Event.__hooks.on; for(var i = 0,l = types.length;i < l;i++){ var type = types[i]; if(onHooks[type]){ qx.lang.Array.remove(onHooks[type], registerHook); }; }; if(!unregisterHook){ return; }; var offHooks = qx.module.Event.__hooks.off; for(var i = 0,l = types.length;i < l;i++){ var type = types[i]; if(offHooks[type]){ qx.lang.Array.remove(offHooks[type], unregisterHook); }; }; }, /** * Returns all registered event hooks * * @attachStatic {qxWeb, $getEventHookRegistry} * @return {Map} Map of event types/registration hook functions * @internal */ $getHookRegistry : function(){ return qx.module.Event.__hooks; } }, defer : function(statics){ qxWeb.$attach({ "on" : statics.on, "off" : statics.off, "once" : statics.once, "emit" : statics.emit, "hasListener" : statics.hasListener, "copyEventsTo" : statics.copyEventsTo }); qxWeb.$attachStatic({ "ready" : statics.ready, "$registerEventNormalization" : statics.$registerNormalization, "$unregisterEventNormalization" : statics.$unregisterNormalization, "$getEventNormalizationRegistry" : statics.$getRegistry, "$registerEventHook" : statics.$registerEventHook, "$unregisterEventHook" : statics.$unregisterEventHook, "$getEventHookRegistry" : statics.$getHookRegistry }); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2007-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Fabian Jakobs (fjakobs) * Sebastian Werner (wpbasti) * Alexander Steitz (aback) * Christian Hagendorn (chris_schmidt) ====================================================================== This class contains code based on the following work: * Juriy Zaytsev http://thinkweb2.com/projects/prototype/detecting-event-support-without-browser-sniffing/ Copyright (c) 2009 Juriy Zaytsev Licence: BSD: http://github.com/kangax/iseventsupported/blob/master/LICENSE ---------------------------------------------------------------------- http://github.com/kangax/iseventsupported/blob/master/LICENSE Copyright (c) 2009 Juriy Zaytsev Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ************************************************************************ */ /** * Wrapper around native event management capabilities of the browser. * This class should not be used directly normally. It's better * to use {@link qx.event.Registration} instead. */ qx.Bootstrap.define("qx.bom.Event", { statics : { /** * Use the low level browser functionality to attach event listeners * to DOM nodes. * * Use this with caution. This is only thought for event handlers and * qualified developers. These are not mem-leak protected! * * @param target {Object} Any valid native event target * @param type {String} Name of the event * @param listener {Function} The pointer to the function to assign * @param useCapture {Boolean ? false} A Boolean value that specifies the event phase to add * the event handler for the capturing phase or the bubbling phase. */ addNativeListener : function(target, type, listener, useCapture){ if(target.addEventListener){ target.addEventListener(type, listener, !!useCapture); } else if(target.attachEvent){ target.attachEvent("on" + type, listener); } else if(typeof target["on" + type] != "undefined"){ target["on" + type] = listener; } else { { }; };; }, /** * Use the low level browser functionality to remove event listeners * from DOM nodes. * * @param target {Object} Any valid native event target * @param type {String} Name of the event * @param listener {Function} The pointer to the function to assign * @param useCapture {Boolean ? false} A Boolean value that specifies the event phase to remove * the event handler for the capturing phase or the bubbling phase. */ removeNativeListener : function(target, type, listener, useCapture){ if(target.removeEventListener){ target.removeEventListener(type, listener, !!useCapture); } else if(target.detachEvent){ try{ target.detachEvent("on" + type, listener); } catch(e) { // IE7 sometimes dispatches "unload" events on protected windows // Ignore the "permission denied" errors. if(e.number !== -2146828218){ throw e; }; }; } else if(typeof target["on" + type] != "undefined"){ target["on" + type] = null; } else { { }; };; }, /** * Returns the target of the event. * * @param e {Event} Native event object * @return {Object} Any valid native event target */ getTarget : function(e){ return e.target || e.srcElement; }, /** * Computes the related target from the native DOM event * * @param e {Event} Native DOM event object * @return {Element} The related target */ getRelatedTarget : function(e){ if(e.relatedTarget !== undefined){ // In Firefox the related target of mouse events is sometimes an // anonymous div inside of a text area, which raises an exception if // the nodeType is read. This is why the try/catch block is needed. if((qx.core.Environment.get("engine.name") == "gecko")){ try{ e.relatedTarget && e.relatedTarget.nodeType; } catch(ex) { return null; }; }; return e.relatedTarget; } else if(e.fromElement !== undefined && e.type === "mouseover"){ return e.fromElement; } else if(e.toElement !== undefined){ return e.toElement; } else { return null; };; }, /** * Prevent the native default of the event to be processed. * * This is useful to stop native keybindings, native selection * and other native functionality behind events. * * @param e {Event} Native event object */ preventDefault : function(e){ if(e.preventDefault){ e.preventDefault(); } else { try{ // this allows us to prevent some key press events in IE. // See bug #1049 e.keyCode = 0; } catch(ex) { }; e.returnValue = false; }; }, /** * Stops the propagation of the given event to the parent element. * * Only useful for events which bubble e.g. mousedown. * * @param e {Event} Native event object */ stopPropagation : function(e){ if(e.stopPropagation){ e.stopPropagation(); } else { e.cancelBubble = true; }; }, /** * Fires a synthetic native event on the given element. * * @param target {Element} DOM element to fire event on * @param type {String} Name of the event to fire * @return {Boolean} A value that indicates whether any of the event handlers called {@link #preventDefault}. * <code>true</code> The default action is permitted, <code>false</code> the caller should prevent the default action. */ fire : function(target, type){ // dispatch for standard first if(document.createEvent){ var evt = document.createEvent("HTMLEvents"); evt.initEvent(type, true, true); return !target.dispatchEvent(evt); } else { var evt = document.createEventObject(); return target.fireEvent("on" + type, evt); }; }, /** * Whether the given target supports the given event type. * * Useful for testing for support of new features like * touch events, gesture events, orientation change, on/offline, etc. * * @signature function(target, type) * @param target {var} Any valid target e.g. window, dom node, etc. * @param type {String} Type of the event e.g. click, mousedown * @return {Boolean} Whether the given event is supported */ supportsEvent : function(target, type){ // Detecting the transitionend event's name is not possible in some // browsers, so we deduce it from the style property name instead. if(type.toLowerCase().indexOf("transitionend") != -1){ var transitionProp = qx.bom.Style.getPropertyName("transition"); if(!transitionProp){ return false; }; var endEvent = qx.lang.String.firstLow(transitionProp) + (transitionProp.indexOf("Trans") > 0 ? "E" : "e") + "nd"; return type == endEvent; }; var eventName = "on" + type; var supportsEvent = (eventName in target); if(!supportsEvent){ supportsEvent = typeof target[eventName] == "function"; if(!supportsEvent && target.setAttribute){ target.setAttribute(eventName, "return;"); supportsEvent = typeof target[eventName] == "function"; target.removeAttribute(eventName); }; }; return supportsEvent; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /** * EXPERIMENTAL - NOT READY FOR PRODUCTION * * Basic implementation for an event emitter. This supplies a basic and * minimalistic event mechanism. */ qx.Bootstrap.define("qx.event.Emitter", { extend : Object, statics : { /** Static storage for all event listener */ __storage : [] }, members : { __listener : null, __any : null, /** * Attach a listener to the event emitter. The given <code>name</code> * will define the type of event. Handing in a <code>'*'</code> will * listen to all events emitted by the event emitter. * * @param name {String} The name of the event to listen to. * @param listener {Function} The function execute on {@link #emit}. * @param ctx {var?Window} The context of the listener. * @return {Integer} An unique <code>id</code> for the attached listener. */ on : function(name, listener, ctx){ var id = qx.event.Emitter.__storage.length; this.__getStorage(name).push({ listener : listener, ctx : ctx, id : id }); qx.event.Emitter.__storage.push({ name : name, listener : listener, ctx : ctx }); return id; }, /** * Attach a listener to the event emitter which will be executed only once. * The given <code>name</code> will define the type of event. Handing in a * <code>'*'</code> will listen to all events emitted by the event emitter. * * @param name {String} The name of the event to listen to. * @param listener {Function} The function execute on {@link #emit}. * @param ctx {var?Window} The context of the listener. * @return {Integer} An unique <code>id</code> for the attached listener. */ once : function(name, listener, ctx){ var id = qx.event.Emitter.__storage.length; this.__getStorage(name).push({ listener : listener, ctx : ctx, once : true, id : id }); qx.event.Emitter.__storage.push({ name : name, listener : listener, ctx : ctx }); return id; }, /** * Remove a listener from the event emitter. The given <code>name</code> * will define the type of event. * * @param name {String} The name of the event to listen to. * @param listener {Function} The function execute on {@link #emit}. * @param ctx {var?Window} The context of the listener. * @return {Integer|null} The listener's id if it was removed or * <code>null</code> if it wasn't found */ off : function(name, listener, ctx){ var storage = this.__getStorage(name); for(var i = storage.length - 1;i >= 0;i--){ var entry = storage[i]; if(entry.listener == listener && entry.ctx == ctx){ storage.splice(i, 1); qx.event.Emitter.__storage[entry.id] = null; return entry.id; }; }; return null; }, /** * Removes the listener identified by the given <code>id</code>. The id * will be return on attaching the listener and can be stored for removing. * * @param id {Integer} The id of the listener. */ offById : function(id){ var entry = qx.event.Emitter.__storage[id]; this.off(entry.name, entry.listener, entry.ctx); }, /** * Alternative for {@link #on}. * @param name {String} The name of the event to listen to. * @param listener {Function} The function execute on {@link #emit}. * @param ctx {var?Window} The context of the listener. * @return {Integer} An unique <code>id</code> for the attached listener. */ addListener : function(name, listener, ctx){ return this.on(name, listener, ctx); }, /** * Alternative for {@link #once}. * @param name {String} The name of the event to listen to. * @param listener {Function} The function execute on {@link #emit}. * @param ctx {var?Window} The context of the listener. * @return {Integer} An unique <code>id</code> for the attached listener. */ addListenerOnce : function(name, listener, ctx){ return this.once(name, listener, ctx); }, /** * Alternative for {@link #off}. * @param name {String} The name of the event to listen to. * @param listener {Function} The function execute on {@link #emit}. * @param ctx {var?Window} The context of the listener. */ removeListener : function(name, listener, ctx){ this.off(name, listener, ctx); }, /** * Alternative for {@link #offById}. * @param id {Integer} The id of the listener. */ removeListenerById : function(id){ this.offById(id); }, /** * Emits an event with the given name. The data will be passed * to the listener. * @param name {String} The name of the event to emit. * @param data {var?undefined} The data which should be passed to the listener. */ emit : function(name, data){ var storage = this.__getStorage(name); for(var i = 0;i < storage.length;i++){ var entry = storage[i]; entry.listener.call(entry.ctx, data); if(entry.once){ storage.splice(i, 1); i--; }; }; // call on any storage = this.__getStorage("*"); for(var i = storage.length - 1;i >= 0;i--){ var entry = storage[i]; entry.listener.call(entry.ctx, data); }; }, /** * Returns the internal attached listener. * @internal * @return {Map} A map which has the event name as key. The values are * arrays containing a map with 'listener' and 'ctx'. */ getListeners : function(){ return this.__listener; }, /** * Internal helper which will return the storage for the given name. * @param name {String} The name of the event. * @return {Array} An array which is the storage for the listener and * the given event name. */ __getStorage : function(name){ if(this.__listener == null){ this.__listener = { }; }; if(this.__listener[name] == null){ this.__listener[name] = []; }; return this.__listener[name]; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Daniel Wagner (danielwagner) ************************************************************************ */ /* ************************************************************************ #require(qx.module.Event) ************************************************************************ */ /** * Normalization for touch events */ qx.Bootstrap.define("qx.module.event.Touch", { statics : { /** * List of event types to be normalized * @type {Array} */ TYPES : ["tap", "swipe"], /** * Manipulates the native event object, adding methods if they're not * already present * * @param event {Event} Native event object * @param element {Element} DOM element the listener was attached to * @param type {String} Event type * @return {Event} Normalized event object * @internal */ normalize : function(event, element, type){ if(!event){ return event; }; event._type = type; return event; } }, defer : function(statics){ qxWeb.$registerEventNormalization(statics.TYPES, statics.normalize); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2011 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * The class is responsible for device detection. This is specially usefull * if you are on a mobile device. * * This class is used by {@link qx.core.Environment} and should not be used * directly. Please check its class comment for details how to use it. * * @internal */ qx.Bootstrap.define("qx.bom.client.Device", { statics : { /** Maps user agent names to device IDs */ __ids : { "iPod" : "ipod", "iPad" : "ipad", "iPhone" : "iPhone", "PSP" : "psp", "PLAYSTATION 3" : "ps3", "Nintendo Wii" : "wii", "Nintendo DS" : "ds", "XBOX" : "xbox", "Xbox" : "xbox" }, /** * Returns the name of the current device if detectable. It falls back to * <code>pc</code> if the detection for other devices fails. * * @internal * @return {String} The string of the device found. */ getName : function(){ var str = []; for(var key in this.__ids){ str.push(key); }; var reg = new RegExp("(" + str.join("|").replace(/\./g, "\.") + ")", "g"); var match = reg.exec(navigator.userAgent); if(match && match[1]){ return qx.bom.client.Device.__ids[match[1]]; }; return "pc"; }, /** * Determines on what type of device the application is running. * Valid values are: "mobile", "tablet" or "desktop". * @return {String} The device type name of determined device. */ getType : function(){ return qx.bom.client.Device.detectDeviceType(navigator.userAgent); }, /** * Detects the device type, based on given userAgentString. * * @param userAgentString {String} userAgent parameter, needed for decision. * @return {String} The device type name of determined device: "mobile","desktop","tablet" */ detectDeviceType : function(userAgentString){ if(qx.bom.client.Device.detectTabletDevice(userAgentString)){ return "tablet"; } else if(qx.bom.client.Device.detectMobileDevice(userAgentString)){ return "mobile"; }; return "desktop"; }, /** * Detects if a device is a mobile phone. (Tablets excluded.) * @param userAgentString {String} userAgent parameter, needed for decision. * @return {Boolean} Flag which indicates whether it is a mobile device. */ detectMobileDevice : function(userAgentString){ return /android.+mobile|ip(hone|od)|bada\/|blackberry|maemo|opera m(ob|in)i|fennec|NetFront|phone|psp|symbian|IEMobile|windows (ce|phone)|xda/i.test(userAgentString); }, /** * Detects if a device is a tablet device. * @param userAgentString {String} userAgent parameter, needed for decision. * @return {Boolean} Flag which indicates whether it is a tablet device. */ detectTabletDevice : function(userAgentString){ var isIE10Tablet = (/MSIE 10/i.test(userAgentString)) && (/ARM/i.test(userAgentString)) && !(/windows phone/i.test(userAgentString)); var isCommonTablet = (!(/Fennec|HTC.Magic|Nexus|android.+mobile|Tablet PC/i.test(userAgentString)) && (/Android|ipad|tablet|playbook|silk|kindle|psp/i.test(userAgentString))); return isIE10Tablet || isCommonTablet; } }, defer : function(statics){ qx.core.Environment.add("device.name", statics.getName); qx.core.Environment.add("device.type", statics.getType); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /** * Module for querying information about the environment / runtime. * It adds a static key <code>env</code> to qxWeb and offers the given methods. * * <pre class="javascript"> * q.env.get("engine.name"); // return "webkit" e.g. * </pre> * * The following values are predefined: * * * <code>browser.name</code> : The name of the browser * * <code>browser.version</code> : The version of the browser * * <code>browser.quirksmode</code> : <code>true</code> if the browser is in quirksmode * * <code>browser.documentmode</code> : The document mode of the browser * * * <code>device.name</code> : The name of the device e.g. <code>iPad</code>. * * <code>device.type</code> : Either <code>desktop</code>, <code>tablet</code> or <code>mobile</code>. * * * <code>engine.name</code> : The name of the browser engine * * <code>engine.version</code> : The version of the browser engine */ qx.Bootstrap.define("qx.module.Environment", { statics : { /** * Get the value stored for the given key. * * @attachStatic {qxWeb, env.get} * @param key {String} The key to check for. * @return {var} The value stored for the given key. * @lint environmentNonLiteralKey(key) */ get : function(key){ return qx.core.Environment.get(key); }, /** * Adds a new environment setting which can be queried via {@link #get}. * @param key {String} The key to store the value for. * * @attachStatic {qxWeb, env.add} * @param value {var} The value to store. * @return {qxWeb} The collection for chaining. */ add : function(key, value){ qx.core.Environment.add(key, value); return this; } }, defer : function(statics){ // make sure the desired keys are available (browser.* and engine.*) qx.core.Environment.get("browser.name"); qx.core.Environment.get("browser.version"); qx.core.Environment.get("browser.quirksmode"); qx.core.Environment.get("browser.documentmode"); qx.core.Environment.get("engine.name"); qx.core.Environment.get("engine.version"); qx.core.Environment.get("device.type"); qxWeb.$attachStatic({ "env" : { get : statics.get, add : statics.add } }); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Daniel Wagner (danielwagner) ************************************************************************ */ /* ************************************************************************ #require(qx.module.Environment) #require(qx.module.Event) ************************************************************************ */ /** * Normalization for native mouse events */ qx.Bootstrap.define("qx.module.event.Mouse", { statics : { /** * List of event types to be normalized */ TYPES : ["click", "dblclick", "mousedown", "mouseup", "mouseover", "mousemove", "mouseout"], /** * List qx.module.event.Mouse methods to be attached to native mouse event * objects * @internal */ BIND_METHODS : ["getButton", "getViewportLeft", "getViewportTop", "getDocumentLeft", "getDocumentTop", "getScreenLeft", "getScreenTop"], /** * Standard mouse button mapping */ BUTTONS_DOM2 : { '0' : "left", '2' : "right", '1' : "middle" }, /** * Legacy Internet Explorer mouse button mapping */ BUTTONS_MSHTML : { '1' : "left", '2' : "right", '4' : "middle" }, /** * Returns the identifier of the mouse button that change state when the * event was triggered * * @return {String} One of <code>left</code>, <code>right</code> or * <code>middle</code> */ getButton : function(){ switch(this.type){case "contextmenu": return "right";case "click": // IE does not support buttons on click --> assume left button if(qxWeb.env.get("browser.name") === "ie" && qxWeb.env.get("browser.documentmode") < 9){ return "left"; };default: if(this.target !== undefined){ return qx.module.event.Mouse.BUTTONS_DOM2[this.button] || "none"; } else { return qx.module.event.Mouse.BUTTONS_MSHTML[this.button] || "none"; };}; }, /** * Get the horizontal coordinate at which the event occurred relative * to the viewport. * * @return {Number} The horizontal mouse position */ getViewportLeft : function(){ return this.clientX; }, /** * Get the vertical coordinate at which the event occurred relative * to the viewport. * * @return {Number} The vertical mouse position * @signature function() */ getViewportTop : function(){ return this.clientY; }, /** * Get the horizontal position at which the event occurred relative to the * left of the document. This property takes into account any scrolling of * the page. * * @return {Number} The horizontal mouse position in the document. */ getDocumentLeft : function(){ if(this.pageX !== undefined){ return this.pageX; } else { var win = qx.dom.Node.getWindow(this.srcElement); return this.clientX + qx.bom.Viewport.getScrollLeft(win); }; }, /** * Get the vertical position at which the event occurred relative to the * top of the document. This property takes into account any scrolling of * the page. * * @return {Number} The vertical mouse position in the document. */ getDocumentTop : function(){ if(this.pageY !== undefined){ return this.pageY; } else { var win = qx.dom.Node.getWindow(this.srcElement); return this.clientY + qx.bom.Viewport.getScrollTop(win); }; }, /** * Get the horizontal coordinate at which the event occurred relative to * the origin of the screen coordinate system. * * Note: This value is usually not very useful unless you want to * position a native popup window at this coordinate. * * @return {Number} The horizontal mouse position on the screen. */ getScreenLeft : function(){ return this.screenX; }, /** * Get the vertical coordinate at which the event occurred relative to * the origin of the screen coordinate system. * * Note: This value is usually not very useful unless you want to * position a native popup window at this coordinate. * * @return {Number} The vertical mouse position on the screen. */ getScreenTop : function(){ return this.screenY; }, /** * Manipulates the native event object, adding methods if they're not * already present * * @param event {Event} Native event object * @param element {Element} DOM element the listener was attached to * @return {Event} Normalized event object * @internal */ normalize : function(event, element){ if(!event){ return event; }; var bindMethods = qx.module.event.Mouse.BIND_METHODS; for(var i = 0,l = bindMethods.length;i < l;i++){ if(typeof event[bindMethods[i]] != "function"){ event[bindMethods[i]] = qx.module.event.Mouse[bindMethods[i]].bind(event); }; }; return event; } }, defer : function(statics){ qxWeb.$registerEventNormalization(qx.module.event.Mouse.TYPES, statics.normalize); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2011 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Tino Butz (tbtz) * Martin Wittemann (wittemann) ************************************************************************ */ /** * Define messages to react on certain channels. * * The channel names will be used in the {@link #on} method to define handlers which will * be called on certain channels and routes. The {@link #emit} method can be used * to execute a given route on a channel. {@link #onAny} defines a handler on any channel. * * *Example* * * Here is a little example of how to use the messaging. * * <pre class='javascript'> * var m = new qx.event.Messaging(); * * m.on("get", "/address/{id}", function(data) { * var id = data.params.id; // 1234 * // do something with the id... * },this); * * m.emit("get", "/address/1234"); * </pre> */ qx.Bootstrap.define("qx.event.Messaging", { construct : function(){ this._listener = { },this.__listenerIdCount = 0; this.__channelToIdMapping = { }; }, members : { _listener : null, __listenerIdCount : null, __channelToIdMapping : null, /** * Adds a route handler for the given channel. The route is called * if the {@link #emit} method finds a match. * * @param channel {String} The channel of the message. * @param type {String|RegExp} The type, used for checking if the executed path matches. * @param handler {Function} The handler to call if the route matches the executed path. * @param scope {var ? null} The scope of the handler. * @return {String} The id of the route used to remove the route. */ on : function(channel, type, handler, scope){ return this._addListener(channel, type, handler, scope); }, /** * Adds a handler for the "any" channel. The "any" channel is called * before all other channels. * * @param type {String|RegExp} The route, used for checking if the executed path matches * @param handler {Function} The handler to call if the route matches the executed path * @param scope {var ? null} The scope of the handler. * @return {String} The id of the route used to remove the route. */ onAny : function(type, handler, scope){ return this._addListener("any", type, handler, scope); }, /** * Adds a listener for a certain channel. * * @param channel {String} The channel the route should be registered for * @param type {String|RegExp} The type, used for checking if the executed path matches * @param handler {Function} The handler to call if the route matches the executed path * @param scope {var ? null} The scope of the handler. * @return {String} The id of the route used to remove the route. */ _addListener : function(channel, type, handler, scope){ var listeners = this._listener[channel] = this._listener[channel] || { }; var id = this.__listenerIdCount++; var params = []; var param = null; // Convert the route to a regular expression. if(qx.lang.Type.isString(type)){ var paramsRegexp = /\{([\w\d]+)\}/g; while((param = paramsRegexp.exec(type)) !== null){ params.push(param[1]); }; type = new RegExp("^" + type.replace(paramsRegexp, "([^\/]+)") + "$"); }; listeners[id] = { regExp : type, params : params, handler : handler, scope : scope }; this.__channelToIdMapping[id] = channel; return id; }, /** * Removes a registered listener by the given id. * * @param id {String} The id of the registered listener. */ remove : function(id){ var channel = this.__channelToIdMapping[id]; var listener = this._listener[channel]; delete listener[id]; delete this.__channelToIdMapping[id]; }, /** * Sends a message on the given channel and informs all matching route handlers. * * @param channel {String} The channel of the message. * @param path {String} The path to execute * @param params {Map} The given parameters that should be propagated * @param customData {var} The given custom data that should be propagated */ emit : function(channel, path, params, customData){ this._emit(channel, path, params, customData); }, /** * Executes a certain channel with a given path. Informs all * route handlers that match with the path. * * @param channel {String} The channel to execute. * @param path {String} The path to check * @param params {Map} The given parameters that should be propagated * @param customData {var} The given custom data that should be propagated */ _emit : function(channel, path, params, customData){ var listenerMatchedAny = false; var listener = this._listener["any"]; listenerMatchedAny = this._emitListeners(channel, path, listener, params, customData); var listenerMatched = false; listener = this._listener[channel]; listenerMatched = this._emitListeners(channel, path, listener, params, customData); if(!listenerMatched && !listenerMatchedAny){ qx.Bootstrap.info("No listener found for " + path); }; }, /** * Executes all given listener for a certain channel. Checks all listeners if they match * with the given path and executes the stored handler of the matching route. * * @param channel {String} The channel to execute. * @param path {String} The path to check * @param listeners {Map[]} All routes to test and execute. * @param params {Map} The given parameters that should be propagated * @param customData {var} The given custom data that should be propagated * * @return {Boolean} Whether the route has been executed */ _emitListeners : function(channel, path, listeners, params, customData){ if(!listeners || qx.lang.Object.isEmpty(listeners)){ return false; }; var listenerMatched = false; for(var id in listeners){ var listener = listeners[id]; listenerMatched |= this._emitRoute(channel, path, listener, params, customData); }; return listenerMatched; }, /** * Executes a certain listener. Checks if the listener matches the given path and * executes the stored handler of the route. * * @param channel {String} The channel to execute. * @param path {String} The path to check * @param listener {Map} The route data. * @param params {Map} The given parameters that should be propagated * @param customData {var} The given custom data that should be propagated * * @return {Boolean} Whether the route has been executed */ _emitRoute : function(channel, path, listener, params, customData){ var match = listener.regExp.exec(path); if(match){ var params = params || { }; var param = null; var value = null; match.shift(); // first match is the whole path for(var i = 0;i < match.length;i++){ value = match[i]; param = listener.params[i]; if(param){ params[param] = value; } else { params[i] = value; }; }; listener.handler.call(listener.scope, { path : path, params : params, customData : customData }); }; return match != undefined; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /* ************************************************************************ #require(qx.event.Messaging#on) #require(qx.event.Messaging#onAny) #require(qx.event.Messaging#remove) #require(qx.event.Messaging#emit) ************************************************************************ */ /** * Define messages to react on certain channels. * * The channel names will be used in the q.messaging.on method to define handlers which will * be called on certain channels and routes. The q.messaging.emit method can be used * to execute a given route on a channel. q.messaging.onAny defines a handler on any channel. */ qx.Bootstrap.define("qx.module.Messaging", { statics : { /** * Adds a route handler for the given channel. The route is called * if the {@link #emit} method finds a match. * * @attachStatic{qxWeb, messaging.on} * @param channel {String} The channel of the message. * @param type {String|RegExp} The type, used for checking if the executed path matches. * @param handler {Function} The handler to call if the route matches the executed path. * @param scope {var ? null} The scope of the handler. * @return {String} The id of the route used to remove the route. * @signature function(channel, type, handler, scope) */ on : null, /** * Adds a handler for the "any" channel. The "any" channel is called * before all other channels. * * @attachStatic{qxWeb, messaging.onAny} * @param type {String|RegExp} The route, used for checking if the executed path matches * @param handler {Function} The handler to call if the route matches the executed path * @param scope {var ? null} The scope of the handler. * @return {String} The id of the route used to remove the route. * @signature function(type, handler, scope) */ onAny : null, /** * Removes a registered listener by the given id. * * @attachStatic{qxWeb, messaging.remove} * @param id {String} The id of the registered listener. * @signature function(id) */ remove : null, /** * Sends a message on the given channel and informs all matching route handlers. * * @attachStatic{qxWeb, messaging.emit} * @param channel {String} The channel of the message. * @param path {String} The path to execute * @param params {Map} The given parameters that should be propagated * @param customData {var} The given custom data that should be propagated * @signature function(channel, path, params, customData) */ emit : null }, defer : function(statics){ qxWeb.$attachStatic({ "messaging" : new qx.event.Messaging() }); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /** * Utility module to give some support to work with arrays. */ qx.Bootstrap.define("qx.module.util.Array", { statics : { /** * Converts an array like object to any other array like * object. * * Attention: The returned array may be same * instance as the incoming one if the constructor is identical! * * @signature function(object, constructor, offset) * @attachStatic {qxWeb, array.cast} * * @param object {var} any array-like object * @param constructor {Function} constructor of the new instance * @param offset {Number?0} position to start from * @return {Array} the converted array */ cast : qx.lang.Array.cast, /** * Check whether the two arrays have the same content. Checks only the * equality of the arrays' content. * * @signature function(arr1, arr2) * @attachStatic {qxWeb, array.equals} * * @param arr1 {Array} first array * @param arr2 {Array} second array * @return {Boolean} Whether the two arrays are equal */ equals : qx.lang.Array.equals, /** * Modifies the first array as it removes all elements * which are listed in the second array as well. * * @signature function(arr1, arr2) * @attachStatic {qxWeb, array.exclude} * * @param arr1 {Array} the array * @param arr2 {Array} the elements of this array will be excluded from the other one * @return {Array} The modified array. */ exclude : qx.lang.Array.exclude, /** * Convert an arguments object into an array. * * @signature function(args, offset) * @attachStatic {qxWeb, array.fromArguments} * * @param args {arguments} arguments object * @param offset {Number?0} position to start from * @return {Array} a newly created array (copy) with the content of the arguments object. */ fromArguments : qx.lang.Array.fromArguments, /** * Insert an element into the array after a given second element. * * @signature function(arr, obj, obj2) * @attachStatic {qxWeb, array.insertAfter} * * @param arr {Array} the array * @param obj {var} object to be inserted * @param obj2 {var} insert obj1 after this object * @return {Array} The given array. */ insertAfter : qx.lang.Array.insertAfter, /** * Insert an element into the array before a given second element. * * @signature function(arr, obj, obj2) * @attachStatic {qxWeb, array.insertBefore} * * @param arr {Array} the array * @param obj {var} object to be inserted * @param obj2 {var} insert obj1 before this object * @return {Array} The given array. */ insertBefore : qx.lang.Array.insertBefore, /** * Returns the highest value in the given array. Supports * numeric values only. * * @signature function(arr) * @attachStatic {qxWeb, array.max} * * @param arr {Array} Array to process. * @return {Number | undefined} The highest of all values or undefined if array is empty. */ max : qx.lang.Array.max, /** * Returns the lowest value in the given array. Supports * numeric values only. * * @signature function(arr) * @attachStatic {qxWeb, array.min} * * @param arr {Array} Array to process. * @return {Number | undefined} The lowest of all values or undefined if array is empty. */ min : qx.lang.Array.min, /** * Remove an element from the array. * * @signature function(arr, obj) * @attachStatic {qxWeb, array.remove} * * @param arr {Array} the array * @param obj {var} element to be removed from the array * @return {var} the removed element */ remove : qx.lang.Array.remove, /** * Remove all elements from the array * * @signature function(arr) * @attachStatic {qxWeb, array.removeAll} * * @param arr {Array} the array * @return {Array} empty array */ removeAll : qx.lang.Array.removeAll, /** * Recreates an array which is free of all duplicate elements from the original. * This method do not modifies the original array! * Keep in mind that this methods deletes undefined indexes. * * @signature function(arr) * @attachStatic {qxWeb, array.unique} * * @param arr {Array} Incoming array * @return {Array} Returns a copy with no duplicates * or the original array if no duplicates were found. */ unique : qx.lang.Array.unique }, defer : function(statics){ qxWeb.$attachStatic({ array : { cast : statics.cast, equals : statics.equals, exclude : statics.exclude, fromArguments : statics.fromArguments, insertAfter : statics.insertAfter, insertBefore : statics.insertBefore, max : statics.max, min : statics.min, remove : statics.remove, removeAll : statics.removeAll, unique : statics.unique } }); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /** * Utility module to give some support to work with strings. */ qx.Bootstrap.define("qx.module.util.String", { statics : { /** * Converts a hyphenated string (separated by '-') to camel case. * * Example: * <pre class='javascript'>q.string.camelCase("I-like-cookies"); //returns "ILikeCookies"</pre> * * @attachStatic {qxWeb, string.camelCase} * @param str {String} hyphenated string * @return {String} camelcase string */ camelCase : function(str){ return qx.lang.String.camelCase.call(qx.lang.String, str); }, /** * Converts a camelcased string to a hyphenated (separated by '-') string. * * Example: * <pre class='javascript'>q.string.hyphenate("weLikeCookies"); //returns "we-like-cookies"</pre> * * @attachStatic {qxWeb, string.hyphenate} * @param str {String} camelcased string * @return {String} hyphenated string */ hyphenate : function(str){ return qx.lang.String.hyphenate.call(qx.lang.String, str); }, /** * Convert the first character of the string to upper case. * * @attachStatic {qxWeb, string.firstUp} * @signature function(str) * @param str {String} the string * @return {String} the string with an upper case first character */ firstUp : qx.lang.String.firstUp, /** * Convert the first character of the string to lower case. * * @attachStatic {qxWeb, string.firstLow} * @signature function(str) * @param str {String} the string * @return {String} the string with a lower case first character */ firstLow : qx.lang.String.firstLow, /** * Check whether the string starts with the given substring. * * @attachStatic {qxWeb, string.startsWith} * @signature function(fullstr, substr) * @param fullstr {String} the string to search in * @param substr {String} the substring to look for * @return {Boolean} whether the string starts with the given substring */ startsWith : qx.lang.String.startsWith, /** * Check whether the string ends with the given substring. * * @attachStatic {qxWeb, string.endsWith} * @signature function(fullstr, substr) * @param fullstr {String} the string to search in * @param substr {String} the substring to look for * @return {Boolean} whether the string ends with the given substring */ endsWith : qx.lang.String.endsWith, /** * Escapes all chars that have a special meaning in regular expressions. * * @attachStatic {qxWeb, string.escapeRegexpChars} * @signature function(str) * @param str {String} the string where to escape the chars. * @return {String} the string with the escaped chars. */ escapeRegexpChars : qx.lang.String.escapeRegexpChars }, defer : function(statics){ qxWeb.$attachStatic({ string : { camelCase : statics.camelCase, hyphenate : statics.hyphenate, firstUp : statics.firstUp, firstLow : statics.firstLow, startsWith : statics.startsWith, endsWith : statics.endsWith, escapeRegexpChars : statics.escapeRegexpChars } }); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /** * This class is responsible for applying CSS3 transforms to the collection. * The implementation is mostly a cross browser wrapper for applying the * transforms. * The API is keep to the spec as close as possible. * * http://www.w3.org/TR/css3-3d-transforms/ */ qx.Bootstrap.define("qx.module.Transform", { statics : { /** * Method to apply multiple transforms at once to the given element. It * takes a map containing the transforms you want to apply plus the values * e.g.<code>{scale: 2, rotate: "5deg"}</code>. * The values can be either singular, which means a single value will * be added to the CSS. If you give an array, the values will be split up * and each array entry will be used for the X, Y or Z dimension in that * order e.g. <code>{scale: [2, 0.5]}</code> will result in a element * double the size in X direction and half the size in Y direction. * Make sure your browser supports all transformations you apply. * * @attach {qxWeb} * @param transforms {Map} The map containing the transforms and value. * @return {qxWeb} This reference for chaining. */ transform : function(transforms){ this.forEach(function(el){ qx.bom.element.Transform.transform(el, transforms); }); return this; }, /** * Translates by the given value. For further details, take * a look at the {@link #transform} method. * * @attach {qxWeb} * @param value {String|Array} The value to translate e.g. <code>"10px"</code>. * @return {qxWeb} This reference for chaining. */ translate : function(value){ return this.transform({ translate : value }); }, /** * Scales by the given value. For further details, take * a look at the {@link #transform} method. * * @attach {qxWeb} * @param value {Number|Array} The value to scale. * @return {qxWeb} This reference for chaining. */ scale : function(value){ return this.transform({ scale : value }); }, /** * Rotates by the given value. For further details, take * a look at the {@link #transform} method. * @param value {String|Array} The value to rotate e.g. <code>"90deg"</code>. * @return {qxWeb} This reference for chaining. */ rotate : function(value){ return this.transform({ rotate : value }); }, /** * Skews by the given value. For further details, take * a look at the {@link #transform} method. * * @attach {qxWeb} * @param value {String|Array} The value to skew e.g. <code>"90deg"</code>. * @return {qxWeb} This reference for chaining. */ skew : function(value){ return this.transform({ skew : value }); }, /** * Sets the transform-origin property. * * Spec: http://www.w3.org/TR/css3-3d-transforms/#transform-origin-property * * @attach {qxWeb} * @param value {String} CSS position values like <code>50% 50%</code> or * <code>left top</code>. * @return {qxWeb} This reference for chaining. */ setTransformOrigin : function(value){ this.forEach(function(el){ qx.bom.element.Transform.setOrigin(el, value); }); return this; }, /** * Returns the transform-origin property of the first element. * * Spec: http://www.w3.org/TR/css3-3d-transforms/#transform-origin-property * * @attach {qxWeb} * @return {String} The set property, e.g. <code>50% 50%</code> or null, * of the collection is empty. */ getTransformOrigin : function(){ if(this[0]){ return qx.bom.element.Transform.getOrigin(this[0]); }; return ""; }, /** * Sets the transform-style property. * * Spec: http://www.w3.org/TR/css3-3d-transforms/#transform-style-property * * @attach {qxWeb} * @param value {String} Either <code>flat</code> or <code>preserve-3d</code>. * @return {qxWeb} This reference for chaining. */ setTransformStyle : function(value){ this.forEach(function(el){ qx.bom.element.Transform.setStyle(el, value); }); return this; }, /** * Returns the transform-style property of the first element. * * Spec: http://www.w3.org/TR/css3-3d-transforms/#transform-style-property * * @attach {qxWeb} * @return {String} The set property, either <code>flat</code> or * <code>preserve-3d</code>. */ getTransformStyle : function(){ if(this[0]){ return qx.bom.element.Transform.getStyle(this[0]); }; return ""; }, /** * Sets the perspective property. * * Spec: http://www.w3.org/TR/css3-3d-transforms/#perspective-property * * @attach {qxWeb} * @param value {Number} The perspective layer. Numbers between 100 * and 5000 give the best results. * @return {qxWeb} This reference for chaining. */ setTransformPerspective : function(value){ this.forEach(function(el){ qx.bom.element.Transform.setPerspective(el, value); }); return this; }, /** * Returns the perspective property of the first element. * * Spec: http://www.w3.org/TR/css3-3d-transforms/#perspective-property * * @attach {qxWeb} * @return {String} The set property, e.g. <code>500</code> */ getTransformPerspective : function(){ if(this[0]){ return qx.bom.element.Transform.getPerspective(this[0]); }; return ""; }, /** * Sets the perspective-origin property. * * Spec: http://www.w3.org/TR/css3-3d-transforms/#perspective-origin-property * * @attach {qxWeb} * @param value {String} CSS position values like <code>50% 50%</code> or * <code>left top</code>. * @return {qxWeb} This reference for chaining. */ setTransformPerspectiveOrigin : function(value){ this.forEach(function(el){ qx.bom.element.Transform.setPerspectiveOrigin(el, value); }); return this; }, /** * Returns the perspective-origin property of the first element. * * Spec: http://www.w3.org/TR/css3-3d-transforms/#perspective-origin-property * * @attach {qxWeb} * @return {String} The set property, e.g. <code>50% 50%</code> */ getTransformPerspectiveOrigin : function(){ if(this[0]){ return qx.bom.element.Transform.getPerspectiveOrigin(this[0]); }; return ""; }, /** * Sets the backface-visibility property. * * Spec: http://www.w3.org/TR/css3-3d-transforms/#backface-visibility-property * * @attach {qxWeb} * @param value {Boolean} <code>true</code> if the backface should be visible. * @return {qxWeb} This reference for chaining. */ setTransformBackfaceVisibility : function(value){ this.forEach(function(el){ qx.bom.element.Transform.setBackfaceVisibility(el, value); }); return this; }, /** * Returns the backface-visibility property of the first element. * * Spec: http://www.w3.org/TR/css3-3d-transforms/#backface-visibility-property * * @attach {qxWeb} * @return {Boolean} <code>true</code>, if the backface is visible. */ getTransformBackfaceVisibility : function(){ if(this[0]){ return qx.bom.element.Transform.getBackfaceVisibility(this[0]); }; return ""; } }, defer : function(statics){ qxWeb.$attach({ "transform" : statics.transform, "translate" : statics.translate, "rotate" : statics.rotate, "skew" : statics.skew, "scale" : statics.scale, "setTransformStyle" : statics.setTransformStyle, "getTransformStyle" : statics.getTransformStyle, "setTransformOrigin" : statics.setTransformOrigin, "getTransformOrigin" : statics.getTransformOrigin, "setTransformPerspective" : statics.setTransformPerspective, "getTransformPerspective" : statics.getTransformPerspective, "setTransformPerspectiveOrigin" : statics.setTransformPerspectiveOrigin, "getTransformPerspectiveOrigin" : statics.getTransformPerspectiveOrigin, "setTransformBackfaceVisibility" : statics.setTransformBackfaceVisibility, "getTransformBackfaceVisibility" : statics.getTransformBackfaceVisibility }); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2011 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /** * Responsible for checking all relevant CSS transform properties. * * Specs: * http://www.w3.org/TR/css3-2d-transforms/ * http://www.w3.org/TR/css3-3d-transforms/ * * @internal */ qx.Bootstrap.define("qx.bom.client.CssTransform", { statics : { /** * Main check method which returns an object if CSS animations are * supported. This object contains all necessary keys to work with CSS * animations. * <ul> * <li><code>name</code> The name of the css transform style</li> * <li><code>style</code> The name of the css transform-style style</li> * <li><code>origin</code> The name of the transform-origin style</li> * <li><code>3d</code> Whether 3d transforms are supported</li> * <li><code>perspective</code> The name of the perspective style</li> * <li><code>perspective-origin</code> The name of the perspective-origin style</li> * <li><code>backface-visibility</code> The name of the backface-visibility style</li> * </ul> * * @internal * @return {Object|null} The described object or null, if animations are * not supported. */ getSupport : function(){ var name = qx.bom.client.CssTransform.getName(); if(name != null){ return { "name" : name, "style" : qx.bom.client.CssTransform.getStyle(), "origin" : qx.bom.client.CssTransform.getOrigin(), "3d" : qx.bom.client.CssTransform.get3D(), "perspective" : qx.bom.client.CssTransform.getPerspective(), "perspective-origin" : qx.bom.client.CssTransform.getPerspectiveOrigin(), "backface-visibility" : qx.bom.client.CssTransform.getBackFaceVisibility() }; }; return null; }, /** * Checks for the style name used to set the transform origin. * @internal * @return {String|null} The name of the style or null, if the style is * not supported. */ getStyle : function(){ return qx.bom.Style.getPropertyName("transformStyle"); }, /** * Checks for the style name used to set the transform origin. * @internal * @return {String|null} The name of the style or null, if the style is * not supported. */ getPerspective : function(){ return qx.bom.Style.getPropertyName("perspective"); }, /** * Checks for the style name used to set the perspective origin. * @internal * @return {String|null} The name of the style or null, if the style is * not supported. */ getPerspectiveOrigin : function(){ return qx.bom.Style.getPropertyName("perspectiveOrigin"); }, /** * Checks for the style name used to set the backface visibility. * @internal * @return {String|null} The name of the style or null, if the style is * not supported. */ getBackFaceVisibility : function(){ return qx.bom.Style.getPropertyName("backfaceVisibility"); }, /** * Checks for the style name used to set the transform origin. * @internal * @return {String|null} The name of the style or null, if the style is * not supported. */ getOrigin : function(){ return qx.bom.Style.getPropertyName("transformOrigin"); }, /** * Checks for the style name used for transforms. * @internal * @return {String|null} The name of the style or null, if the style is * not supported. */ getName : function(){ return qx.bom.Style.getPropertyName("transform"); }, /** * Checks if 3D transforms are supported. * @internal * @return {Boolean} <code>true</code>, if 3D transformations are supported */ get3D : function(){ return qx.bom.client.CssTransform.getPerspective() != null; } }, defer : function(statics){ qx.core.Environment.add("css.transform", statics.getSupport); qx.core.Environment.add("css.transform.3d", statics.get3D); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2011 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /** * This class is responsible for applying CSS3 transforms to plain DOM elements. * The implementation is mostly a cross browser wrapper for applying the * transforms. * The API is keep to the spec as close as possible. * * http://www.w3.org/TR/css3-3d-transforms/ */ qx.Bootstrap.define("qx.bom.element.Transform", { statics : { /** The dimensions of the transforms */ __dimensions : ["X", "Y", "Z"], /** Internal storage of the CSS names */ __cssKeys : qx.core.Environment.get("css.transform"), /** * Method to apply multiple transforms at once to the given element. It * takes a map containing the transforms you want to apply plus the values * e.g.<code>{scale: 2, rotate: "5deg"}</code>. * The values can be either singular, which means a single value will * be added to the CSS. If you give an array, the values will be split up * and each array entry will be used for the X, Y or Z dimension in that * order e.g. <code>{scale: [2, 0.5]}</code> will result in a element * double the size in X direction and half the size in Y direction. * Make sure your browser supports all transformations you apply. * @param el {Element} The element to apply the transformation. * @param transforms {Map} The map containing the transforms and value. */ transform : function(el, transforms){ var transformCss = this.__mapToCss(transforms); if(this.__cssKeys != null){ var style = this.__cssKeys["name"]; el.style[style] = transformCss; }; }, /** * Translates the given element by the given value. For further details, take * a look at the {@link #transform} method. * @param el {Element} The element to apply the transformation. * @param value {String|Array} The value to translate e.g. <code>"10px"</code>. */ translate : function(el, value){ this.transform(el, { translate : value }); }, /** * Scales the given element by the given value. For further details, take * a look at the {@link #transform} method. * @param el {Element} The element to apply the transformation. * @param value {Number|Array} The value to scale. */ scale : function(el, value){ this.transform(el, { scale : value }); }, /** * Rotates the given element by the given value. For further details, take * a look at the {@link #transform} method. * @param el {Element} The element to apply the transformation. * @param value {String|Array} The value to rotate e.g. <code>"90deg"</code>. */ rotate : function(el, value){ this.transform(el, { rotate : value }); }, /** * Skews the given element by the given value. For further details, take * a look at the {@link #transform} method. * @param el {Element} The element to apply the transformation. * @param value {String|Array} The value to skew e.g. <code>"90deg"</code>. */ skew : function(el, value){ this.transform(el, { skew : value }); }, /** * Converts the given map to a string which could be added to a css * stylesheet. * @param transforms {Map} The transforms map. For a detailed description, * take a look at the {@link #transform} method. * @return {String} The CSS value. */ getCss : function(transforms){ var transformCss = this.__mapToCss(transforms); if(this.__cssKeys != null){ var style = this.__cssKeys["name"]; return qx.bom.Style.getCssName(style) + ":" + transformCss + ";"; }; return ""; }, /** * Sets the transform-origin property of the given element. * * Spec: http://www.w3.org/TR/css3-3d-transforms/#transform-origin-property * @param el {Element} The dom element to set the property. * @param value {String} CSS position values like <code>50% 50%</code> or * <code>left top</code>. */ setOrigin : function(el, value){ if(this.__cssKeys != null){ el.style[this.__cssKeys["origin"]] = value; }; }, /** * Returns the transform-origin property of the given element. * * Spec: http://www.w3.org/TR/css3-3d-transforms/#transform-origin-property * @param el {Element} The dom element to read the property. * @return {String} The set property, e.g. <code>50% 50%</code> */ getOrigin : function(el){ if(this.__cssKeys != null){ return el.style[this.__cssKeys["origin"]]; }; return ""; }, /** * Sets the transform-style property of the given element. * * Spec: http://www.w3.org/TR/css3-3d-transforms/#transform-style-property * @param el {Element} The dom element to set the property. * @param value {String} Either <code>flat</code> or <code>preserve-3d</code>. */ setStyle : function(el, value){ if(this.__cssKeys != null){ el.style[this.__cssKeys["style"]] = value; }; }, /** * Returns the transform-style property of the given element. * * Spec: http://www.w3.org/TR/css3-3d-transforms/#transform-style-property * @param el {Element} The dom element to read the property. * @return {String} The set property, either <code>flat</code> or * <code>preserve-3d</code>. */ getStyle : function(el){ if(this.__cssKeys != null){ return el.style[this.__cssKeys["style"]]; }; return ""; }, /** * Sets the perspective property of the given element. * * Spec: http://www.w3.org/TR/css3-3d-transforms/#perspective-property * @param el {Element} The dom element to set the property. * @param value {Number} The perspective layer. Numbers between 100 * and 5000 give the best results. */ setPerspective : function(el, value){ if(this.__cssKeys != null){ el.style[this.__cssKeys["perspective"]] = value + "px"; }; }, /** * Returns the perspective property of the given element. * * Spec: http://www.w3.org/TR/css3-3d-transforms/#perspective-property * @param el {Element} The dom element to read the property. * @return {String} The set property, e.g. <code>500</code> */ getPerspective : function(el){ if(this.__cssKeys != null){ return el.style[this.__cssKeys["perspective"]]; }; return ""; }, /** * Sets the perspective-origin property of the given element. * * Spec: http://www.w3.org/TR/css3-3d-transforms/#perspective-origin-property * @param el {Element} The dom element to set the property. * @param value {String} CSS position values like <code>50% 50%</code> or * <code>left top</code>. */ setPerspectiveOrigin : function(el, value){ if(this.__cssKeys != null){ el.style[this.__cssKeys["perspective-origin"]] = value; }; }, /** * Returns the perspective-origin property of the given element. * * Spec: http://www.w3.org/TR/css3-3d-transforms/#perspective-origin-property * @param el {Element} The dom element to read the property. * @return {String} The set property, e.g. <code>50% 50%</code> */ getPerspectiveOrigin : function(el){ if(this.__cssKeys != null){ var value = el.style[this.__cssKeys["perspective-origin"]]; if(value != ""){ return value; } else { var valueX = el.style[this.__cssKeys["perspective-origin"] + "X"]; var valueY = el.style[this.__cssKeys["perspective-origin"] + "Y"]; if(valueX != ""){ return valueX + " " + valueY; }; }; }; return ""; }, /** * Sets the backface-visibility property of the given element. * * Spec: http://www.w3.org/TR/css3-3d-transforms/#backface-visibility-property * @param el {Element} The dom element to set the property. * @param value {Boolean} <code>true</code> if the backface should be visible. */ setBackfaceVisibility : function(el, value){ if(this.__cssKeys != null){ el.style[this.__cssKeys["backface-visibility"]] = value ? "visible" : "hidden"; }; }, /** * Returns the backface-visibility property of the given element. * * Spec: http://www.w3.org/TR/css3-3d-transforms/#backface-visibility-property * @param el {Element} The dom element to read the property. * @return {Boolean} <code>true</code>, if the backface is visible. */ getBackfaceVisibility : function(el){ if(this.__cssKeys != null){ return el.style[this.__cssKeys["backface-visibility"]] == "visible"; }; return true; }, /** * Internal helper which converts the given transforms map to a valid CSS * string. * @param transforms {Map} A map containing the transforms. * @return {String} The CSS transforms. */ __mapToCss : function(transforms){ var value = ""; for(var func in transforms){ var params = transforms[func]; // if an array is given if(qx.Bootstrap.isArray(params)){ for(var i = 0;i < params.length;i++){ if(params[i] == undefined){ continue; }; value += func + this.__dimensions[i] + "("; value += params[i]; value += ") "; }; } else { // single value case value += func + "(" + transforms[func] + ") "; }; }; return value; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Daniel Wagner (danielwagner) ************************************************************************ */ /* ************************************************************************ #require(qx.module.Event) #require(qx.bom.Event#getTarget) #require(qx.bom.Event#getRelatedTarget) ************************************************************************ */ /** * Common normalizations for native events */ qx.Bootstrap.define("qx.module.event.Native", { statics : { /** * List of event types to be normalized */ TYPES : ["*"], /** * List of qx.bom.Event methods to be attached to native event objects * @internal */ FORWARD_METHODS : ["getTarget", "getRelatedTarget"], /** * List of qx.module.event.Native methods to be attached to native event objects * @internal */ BIND_METHODS : ["preventDefault", "stopPropagation", "getType"], /** * Prevent the native default behavior of the event. */ preventDefault : function(){ try{ // this allows us to prevent some key press events in IE. // See bug #1049 this.keyCode = 0; } catch(ex) { }; this.returnValue = false; }, /** * Stops the event's propagation to the element's parent */ stopPropagation : function(){ this.cancelBubble = true; }, /** * Returns the event's type * * @return {String} event type */ getType : function(){ return this._type || this.type; }, /** * Returns the target of the event. * Example: * <pre class="javascript"> * var collection = q("div.inline"); * collection.on("click", function(e) { * var clickedElement = e.getTarget(); * }); * </pre> * * @signature function() * @return {Object} Any valid native event target */ getTarget : function(){ }, /** * Computes the related target from the native DOM event * * Example: * <pre class="javascript"> * var collection = q("div.inline"); * collection.on("mouseout", function(e) { * // when using 'mouseout' events the 'relatedTarget' is pointing to the DOM element * // the device exited to. * // Useful for scenarios you only interested if e.g. the user moved away from a * // section at the website * var exitTarget = e.getRelatedTarget(); * }); * * collection.on("mouseover", function(e){ * // when using 'mouseover' events the 'relatedTarget' is pointing to the DOM element * // the device entered from. * var earlierElement = e.getRelatedTarget(); * }); * </pre> * * @signature function() * @return {Element} The related target */ getRelatedTarget : function(){ }, /** * Manipulates the native event object, adding methods if they're not * already present * * @param event {Event} Native event object * @param element {Element} DOM element the listener was attached to * @return {Event} Normalized event object * @internal */ normalize : function(event, element){ if(!event){ return event; }; var fwdMethods = qx.module.event.Native.FORWARD_METHODS; for(var i = 0,l = fwdMethods.length;i < l;i++){ event[fwdMethods[i]] = qx.lang.Function.curry(qx.bom.Event[fwdMethods[i]], event); }; var bindMethods = qx.module.event.Native.BIND_METHODS; for(var i = 0,l = bindMethods.length;i < l;i++){ if(typeof event[bindMethods[i]] != "function"){ event[bindMethods[i]] = qx.module.event.Native[bindMethods[i]].bind(event); }; }; event.getCurrentTarget = function(){ return event.currentTarget || element; }; return event; } }, defer : function(statics){ qxWeb.$registerEventNormalization(statics.TYPES, statics.normalize); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) ====================================================================== This class contains code based on the following work: * Prototype JS http://www.prototypejs.org/ Version 1.5 Copyright: (c) 2006-2007, Prototype Core Team License: MIT: http://www.opensource.org/licenses/mit-license.php Authors: * Prototype Core Team ---------------------------------------------------------------------- Copyright (c) 2005-2008 Sam Stephenson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ************************************************************************ */ /** * Methods to operate on nodes and elements on a DOM tree. This contains * special getters to query for child nodes, siblings, etc. This class also * supports to operate on one element and reorganize the content with * the insertion of new HTML or nodes. */ qx.Bootstrap.define("qx.dom.Hierarchy", { statics : { /** * Returns the DOM index of the given node * * @param node {Node} Node to look for * @return {Integer} The DOM index */ getNodeIndex : function(node){ var index = 0; while(node && (node = node.previousSibling)){ index++; }; return index; }, /** * Returns the DOM index of the given element (ignoring non-elements) * * @param element {Element} Element to look for * @return {Integer} The DOM index */ getElementIndex : function(element){ var index = 0; var type = qx.dom.Node.ELEMENT; while(element && (element = element.previousSibling)){ if(element.nodeType == type){ index++; }; }; return index; }, /** * Return the next element to the supplied element * * "nextSibling" is not good enough as it might return a text or comment element * * @param element {Element} Starting element node * @return {Element | null} Next element node */ getNextElementSibling : function(element){ while(element && (element = element.nextSibling) && !qx.dom.Node.isElement(element)){ continue; }; return element || null; }, /** * Return the previous element to the supplied element * * "previousSibling" is not good enough as it might return a text or comment element * * @param element {Element} Starting element node * @return {Element | null} Previous element node */ getPreviousElementSibling : function(element){ while(element && (element = element.previousSibling) && !qx.dom.Node.isElement(element)){ continue; }; return element || null; }, /** * Whether the first element contains the second one * * Uses native non-standard contains() in Internet Explorer, * Opera and Webkit (supported since Safari 3.0 beta) * * @param element {Element} Parent element * @param target {Node} Child node * @return {Boolean} */ contains : function(element, target){ if(qx.core.Environment.get("html.element.contains")){ if(qx.dom.Node.isDocument(element)){ var doc = qx.dom.Node.getDocument(target); return element && doc == element; } else if(qx.dom.Node.isDocument(target)){ return false; } else { return element.contains(target); }; } else if(qx.core.Environment.get("html.element.compareDocumentPosition")){ // https://developer.mozilla.org/en-US/docs/DOM:Node.compareDocumentPosition return !!(element.compareDocumentPosition(target) & 16); } else { while(target){ if(element == target){ return true; }; target = target.parentNode; }; return false; }; }, /** * Whether the element is inserted into the document * for which it was created. * * @param element {Element} DOM element to check * @return {Boolean} <code>true</code> when the element is inserted * into the document. */ isRendered : function(element){ var doc = element.ownerDocument || element.document; if(qx.core.Environment.get("html.element.contains")){ // Fast check for all elements which are not in the DOM if(!element.parentNode || !element.offsetParent){ return false; }; return doc.body.contains(element); } else if(qx.core.Environment.get("html.element.compareDocumentPosition")){ // Gecko way, DOM3 method return !!(doc.compareDocumentPosition(element) & 16); } else { while(element){ if(element == doc.body){ return true; }; element = element.parentNode; }; return false; }; }, /** * Checks if <code>element</code> is a descendant of <code>ancestor</code>. * * @param element {Element} first element * @param ancestor {Element} second element * @return {Boolean} Element is a descendant of ancestor */ isDescendantOf : function(element, ancestor){ return this.contains(ancestor, element); }, /** * Get the common parent element of two given elements. Returns * <code>null</code> when no common element has been found. * * Uses native non-standard contains() in Opera and Internet Explorer * * @param element1 {Element} First element * @param element2 {Element} Second element * @return {Element} the found parent, if none was found <code>null</code> */ getCommonParent : function(element1, element2){ if(element1 === element2){ return element1; }; if(qx.core.Environment.get("html.element.contains")){ while(element1 && qx.dom.Node.isElement(element1)){ if(element1.contains(element2)){ return element1; }; element1 = element1.parentNode; }; return null; } else { var known = []; while(element1 || element2){ if(element1){ if(qx.lang.Array.contains(known, element1)){ return element1; }; known.push(element1); element1 = element1.parentNode; }; if(element2){ if(qx.lang.Array.contains(known, element2)){ return element2; }; known.push(element2); element2 = element2.parentNode; }; }; return null; }; }, /** * Collects all of element's ancestors and returns them as an array of * elements. * * @param element {Element} DOM element to query for ancestors * @return {Array} list of all parents */ getAncestors : function(element){ return this._recursivelyCollect(element, "parentNode"); }, /** * Returns element's children. * * @param element {Element} DOM element to query for child elements * @return {Array} list of all child elements */ getChildElements : function(element){ element = element.firstChild; if(!element){ return []; }; var arr = this.getNextSiblings(element); if(element.nodeType === 1){ arr.unshift(element); }; return arr; }, /** * Collects all of element's descendants (deep) and returns them as an array * of elements. * * @param element {Element} DOM element to query for child elements * @return {Array} list of all found elements */ getDescendants : function(element){ return qx.lang.Array.fromCollection(element.getElementsByTagName("*")); }, /** * Returns the first child that is an element. This is opposed to firstChild DOM * property which will return any node (whitespace in most usual cases). * * @param element {Element} DOM element to query for first descendant * @return {Element} the first descendant */ getFirstDescendant : function(element){ element = element.firstChild; while(element && element.nodeType != 1){ element = element.nextSibling; }; return element; }, /** * Returns the last child that is an element. This is opposed to lastChild DOM * property which will return any node (whitespace in most usual cases). * * @param element {Element} DOM element to query for last descendant * @return {Element} the last descendant */ getLastDescendant : function(element){ element = element.lastChild; while(element && element.nodeType != 1){ element = element.previousSibling; }; return element; }, /** * Collects all of element's previous siblings and returns them as an array of elements. * * @param element {Element} DOM element to query for previous siblings * @return {Array} list of found DOM elements */ getPreviousSiblings : function(element){ return this._recursivelyCollect(element, "previousSibling"); }, /** * Collects all of element's next siblings and returns them as an array of * elements. * * @param element {Element} DOM element to query for next siblings * @return {Array} list of found DOM elements */ getNextSiblings : function(element){ return this._recursivelyCollect(element, "nextSibling"); }, /** * Recursively collects elements whose relationship is specified by * property. <code>property</code> has to be a property (a method won't * do!) of element that points to a single DOM node. Returns an array of * elements. * * @param element {Element} DOM element to start with * @param property {String} property to look for * @return {Array} result list */ _recursivelyCollect : function(element, property){ var list = []; while(element = element[property]){ if(element.nodeType == 1){ list.push(element); }; }; return list; }, /** * Collects all of element's siblings and returns them as an array of elements. * * @param element {var} DOM element to start with * @return {Array} list of all found siblings */ getSiblings : function(element){ return this.getPreviousSiblings(element).reverse().concat(this.getNextSiblings(element)); }, /** * Whether the given element is empty. * Inspired by Base2 (Dean Edwards) * * @param element {Element} The element to check * @return {Boolean} true when the element is empty */ isEmpty : function(element){ element = element.firstChild; while(element){ if(element.nodeType === qx.dom.Node.ELEMENT || element.nodeType === qx.dom.Node.TEXT){ return false; }; element = element.nextSibling; }; return true; }, /** * Removes all of element's text nodes which contain only whitespace * * @param element {Element} Element to cleanup */ cleanWhitespace : function(element){ var node = element.firstChild; while(node){ var nextNode = node.nextSibling; if(node.nodeType == 3 && !/\S/.test(node.nodeValue)){ element.removeChild(node); }; node = nextNode; }; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2011-2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) * Daniel Wagner (danielwagner) ************************************************************************ */ /* ************************************************************************ #require(qx.dom.Hierarchy#getSiblings) #require(qx.dom.Hierarchy#getNextSiblings) #require(qx.dom.Hierarchy#getPreviousSiblings) ************************************************************************ */ /** * DOM traversal module */ qx.Bootstrap.define("qx.module.Traversing", { statics : { /** * Adds an element to the collection * * @attach {qxWeb} * @param el {Element} DOM element to add to the collection * @return {qxWeb} The collection for chaining */ add : function(el){ this.push(el); return this; }, /** * Gets a set of elements containing all of the unique immediate children of * each of the matched set of elements. * This set can be filtered with an optional expression that will cause only * elements matching the selector to be collected. * * @attach {qxWeb} * @param selector {String?null} Optional selector to match * @return {qxWeb} Collection containing the child elements */ getChildren : function(selector){ var children = []; for(var i = 0;i < this.length;i++){ var found = qx.dom.Hierarchy.getChildElements(this[i]); if(selector){ found = qx.bom.Selector.matches(selector, found); }; children = children.concat(found); }; return qxWeb.$init(children); }, /** * Executes the provided callback function once for each item in the * collection. * * @attach {qxWeb} * @param fn {Function} Callback function * @param ctx {Object} Context object * @return {qxWeb} The collection for chaining */ forEach : function(fn, ctx){ for(var i = 0;i < this.length;i++){ fn.call(ctx, this[i], i, this); }; return this; }, /** * Gets a set of elements containing the parent of each element in the * collection. * This set can be filtered with an optional expression that will cause only * elements matching the selector to be collected. * * @attach {qxWeb} * @param selector {String?null} Optional selector to match * @return {qxWeb} Collection containing the parent elements */ getParents : function(selector){ var parents = []; for(var i = 0;i < this.length;i++){ var found = qx.dom.Element.getParentElement(this[i]); if(selector){ found = qx.bom.Selector.matches(selector, [found]); }; parents = parents.concat(found); }; return qxWeb.$init(parents); }, /** * Gets a set of elements containing all ancestors of each element in the * collection. * This set can be filtered with an optional expression that will cause only * elements matching the selector to be collected. * * @attach {qxWeb} * @param filter {String?null} Optional selector to match * @return {qxWeb} Collection containing the ancestor elements */ getAncestors : function(filter){ return this.__getAncestors(null, filter); }, /** * Gets a set of elements containing all ancestors of each element in the * collection, up to (but not including) the element matched by the provided * selector. * This set can be filtered with an optional expression that will cause only * elements matching the selector to be collected. * * @attach {qxWeb} * @param selector {String} Selector that indicates where to stop including * ancestor elements * @param filter {String?null} Optional selector to match * @return {qxWeb} Collection containing the ancestor elements */ getAncestorsUntil : function(selector, filter){ return this.__getAncestors(selector, filter); }, /** * Internal helper for getAncestors and getAncestorsUntil * * @attach {qxWeb} * @param selector {String} Selector that indicates where to stop including * ancestor elements * @param filter {String?null} Optional selector to match * @return {qxWeb} Collection containing the ancestor elements * @internal */ __getAncestors : function(selector, filter){ var ancestors = []; for(var i = 0;i < this.length;i++){ var parent = qx.dom.Element.getParentElement(this[i]); while(parent){ var found = [parent]; if(selector && qx.bom.Selector.matches(selector, found).length > 0){ break; }; if(filter){ found = qx.bom.Selector.matches(filter, found); }; ancestors = ancestors.concat(found); parent = qx.dom.Element.getParentElement(parent); }; }; return qxWeb.$init(ancestors); }, /** * Gets a set containing the closest matching ancestor for each item in * the collection. * If the item itself matches, it is added to the new set. Otherwise, the * item's parent chain will be traversed until a match is found. * * @attach {qxWeb} * @param selector {String} Selector expression to match * @return {qxWeb} New collection containing the closest matching ancestors */ getClosest : function(selector){ var closest = []; var findClosest = function findClosest(current){ var found = qx.bom.Selector.matches(selector, current); if(found.length){ closest.push(found[0]); } else { current = current.getParents(); // One up if(current[0] && current[0].parentNode){ findClosest(current); }; }; }; for(var i = 0;i < this.length;i++){ findClosest(qxWeb(this[i])); }; return qxWeb.$init(closest); }, /** * Searches the child elements of each item in the collection and returns * a new collection containing the children that match the provided selector * * @attach {qxWeb} * @param selector {String} Selector expression to match the child elements * against * @return {qxWeb} New collection containing the matching child elements */ find : function(selector){ var found = []; for(var i = 0;i < this.length;i++){ found = found.concat(qx.bom.Selector.query(selector, this[i])); }; return qxWeb.$init(found); }, /** * Gets a new set of elements containing the child nodes of each item in the * current set. * * @attach {qxWeb} * @return {qxWeb} New collection containing the child nodes */ getContents : function(){ var found = []; for(var i = 0;i < this.length;i++){ found = found.concat(qx.lang.Array.fromCollection(this[i].childNodes)); }; return qxWeb.$init(found); }, /** * Checks if at least one element in the collection passes the provided * filter. This can be either a selector expression or a filter * function * * @attach {qxWeb} * @param selector {String|Function} Selector expression or filter function * @return {Boolean} <code>true</code> if at least one element matches */ is : function(selector){ if(qx.lang.Type.isFunction(selector)){ return this.filter(selector).length > 0; }; return !!selector && qx.bom.Selector.matches(selector, this).length > 0; }, /** * Reduce the set of matched elements to a single element. * * @attach {qxWeb} * @param index {Number} The position of the element in the collection * @return {qxWeb} A new collection containing one element */ eq : function(index){ return this.slice(index, +index + 1); }, /** * Reduces the collection to the first element. * * @attach {qxWeb} * @return {qxWeb} A new collection containing one element */ getFirst : function(){ return this.slice(0, 1); }, /** * Reduces the collection to the last element. * * @attach {qxWeb} * @return {qxWeb} A new collection containing one element */ getLast : function(){ return this.slice(this.length - 1); }, /** * Gets a collection containing only the elements that have descendants * matching the given selector * * @attach {qxWeb} * @param selector {String} Selector expression * @return {qxWeb} a new collection containing only elements with matching descendants */ has : function(selector){ var found = []; for(var i = 0;i < this.length;i++){ var descendants = qx.bom.Selector.matches(selector, this.eq(i).getContents()); if(descendants.length > 0){ found.push(this[i]); }; }; return qxWeb.$init(found); }, /** * Gets a collection containing the next sibling element of each item in * the current set (ignoring text and comment nodes). * This set can be filtered with an optional expression that will cause only * elements matching the selector to be collected. * * @attach {qxWeb} * @param selector {String?} Optional selector expression * @return {qxWeb} New set containing next siblings */ getNext : function(selector){ var found = this.map(qx.dom.Hierarchy.getNextElementSibling, qx.dom.Hierarchy); if(selector){ found = qx.bom.Selector.matches(selector, found); }; return found; }, /** * Gets a collection containing all following sibling elements of each * item in the current set (ignoring text and comment nodes). * This set can be filtered with an optional expression that will cause only * elements matching the selector to be collected. * * @attach {qxWeb} * @param selector {String?} Optional selector expression * @return {qxWeb} New set containing following siblings */ getNextAll : function(selector){ var ret = qx.module.Traversing.__hierarchyHelper(this, "getNextSiblings", selector); return qxWeb.$init(ret); }, /** * Gets a collection containing the following sibling elements of each * item in the current set (ignoring text and comment nodes) up to but not * including any element that matches the given selector. * * @attach {qxWeb} * @param selector {String?} Optional selector expression * @return {qxWeb} New set containing following siblings */ getNextUntil : function(selector){ var found = []; this.forEach(function(item, index){ var nextSiblings = qx.dom.Hierarchy.getNextSiblings(item); for(var i = 0,l = nextSiblings.length;i < l;i++){ if(qx.bom.Selector.matches(selector, [nextSiblings[i]]).length > 0){ break; }; found.push(nextSiblings[i]); }; }); return qxWeb.$init(found); }, /** * Gets a collection containing the previous sibling element of each item in * the current set (ignoring text and comment nodes). * This set can be filtered with an optional expression that will cause only * elements matching the selector to be collected. * * @attach {qxWeb} * @param selector {String?} Optional selector expression * @return {qxWeb} New set containing previous siblings */ getPrev : function(selector){ var found = this.map(qx.dom.Hierarchy.getPreviousElementSibling, qx.dom.Hierarchy); if(selector){ found = qx.bom.Selector.matches(selector, found); }; return found; }, /** * Gets a collection containing all preceding sibling elements of each * item in the current set (ignoring text and comment nodes). * This set can be filtered with an optional expression that will cause only * elements matching the selector to be collected. * * @attach {qxWeb} * @param selector {String?} Optional selector expression * @return {qxWeb} New set containing preceding siblings */ getPrevAll : function(selector){ var ret = qx.module.Traversing.__hierarchyHelper(this, "getPreviousSiblings", selector); return qxWeb.$init(ret); }, /** * Gets a collection containing the preceding sibling elements of each * item in the current set (ignoring text and comment nodes) up to but not * including any element that matches the given selector. * * @attach {qxWeb} * @param selector {String?} Optional selector expression * @return {qxWeb} New set containing preceding siblings */ getPrevUntil : function(selector){ var found = []; this.forEach(function(item, index){ var previousSiblings = qx.dom.Hierarchy.getPreviousSiblings(item); for(var i = 0,l = previousSiblings.length;i < l;i++){ if(qx.bom.Selector.matches(selector, [previousSiblings[i]]).length > 0){ break; }; found.push(previousSiblings[i]); }; }); return qxWeb.$init(found); }, /** * Gets a collection containing all sibling elements of the items in the * current set. * This set can be filtered with an optional expression that will cause only * elements matching the selector to be collected. * * @attach {qxWeb} * @param selector {String?} Optional selector expression * @return {qxWeb} New set containing sibling elements */ getSiblings : function(selector){ var ret = qx.module.Traversing.__hierarchyHelper(this, "getSiblings", selector); return qxWeb.$init(ret); }, /** * Remove elements from the collection that do not pass the given filter. * This can be either a selector expression or a filter function * * @attach {qxWeb} * @param selector {String|Function} Selector or filter function * @return {qxWeb} Reduced collection */ not : function(selector){ if(qx.lang.Type.isFunction(selector)){ return this.filter(function(item, index, obj){ return !selector(item, index, obj); }); }; var res = qx.bom.Selector.matches(selector, this); return this.filter(function(value){ return res.indexOf(value) === -1; }); }, /** * Gets a new collection containing the offset parent of each item in the * current set. * * @attach {qxWeb} * @return {qxWeb} New collection containing offset parents */ getOffsetParent : function(){ return this.map(qx.bom.element.Location.getOffsetParent); }, /** * Whether the first element in the collection is inserted into * the document for which it was created. * * @return {Boolean} <code>true</code> when the element is inserted * into the document. */ isRendered : function(){ if(!this[0]){ return false; }; return qx.dom.Hierarchy.isRendered(this[0]); }, /** * Checks if the given object is a DOM element * * @attachStatic{qxWeb} * @param element {Object} Object to check * @return {Boolean} <code>true</code> if the object is a DOM element */ isElement : function(element){ return qx.dom.Node.isElement(element); }, /** * Checks if the given object is a DOM node * * @attachStatic{qxWeb} * @param node {Object} Object to check * @return {Boolean} <code>true</code> if the object is a DOM node */ isNode : function(node){ return qx.dom.Node.isNode(node); }, /** * Checks if the given object is a DOM document object * * @attachStatic{qxWeb} * @param node {Object} Object to check * @return {Boolean} <code>true</code> if the object is a DOM document */ isDocument : function(node){ return qx.dom.Node.isDocument(node); }, /** * Returns the DOM2 <code>defaultView</code> (window) for the given node. * * @attachStatic{qxWeb} * @param node {Node|Document|Window} Node to inspect * @return {Window} the <code>defaultView</code> for the given node */ getWindow : function(node){ return qx.dom.Node.getWindow(node); }, /** * Returns the owner document of the given node * * @attachStatic{qxWeb} * @param node {Node } Node to get the document for * @return {Document|null} The document of the given DOM node */ getDocument : function(node){ return qx.dom.Node.getDocument(node); }, /** * Helper function that iterates over a set of items and applies the given * qx.dom.Hierarchy method to each entry, storing the results in a new Array. * Duplicates are removed and the items are filtered if a selector is * provided. * * @attach{qxWeb} * @param collection {Array} Collection to iterate over (any Array-like object) * @param method {String} Name of the qx.dom.Hierarchy method to apply * @param selector {String?} Optional selector that elements to be included * must match * @return {Array} Result array * @internal */ __hierarchyHelper : function(collection, method, selector){ // Iterate ourself, as we want to directly combine the result var all = []; var Hierarchy = qx.dom.Hierarchy; for(var i = 0,l = collection.length;i < l;i++){ all.push.apply(all, Hierarchy[method](collection[i])); }; // Remove duplicates var ret = qx.lang.Array.unique(all); // Post reduce result by selector if(selector){ ret = qx.bom.Selector.matches(selector, ret); }; return ret; } }, defer : function(statics){ qxWeb.$attach({ "add" : statics.add, "getChildren" : statics.getChildren, "forEach" : statics.forEach, "getParents" : statics.getParents, "getAncestors" : statics.getAncestors, "getAncestorsUntil" : statics.getAncestorsUntil, "__getAncestors" : statics.__getAncestors, "getClosest" : statics.getClosest, "find" : statics.find, "getContents" : statics.getContents, "is" : statics.is, "eq" : statics.eq, "getFirst" : statics.getFirst, "getLast" : statics.getLast, "has" : statics.has, "getNext" : statics.getNext, "getNextAll" : statics.getNextAll, "getNextUntil" : statics.getNextUntil, "getPrev" : statics.getPrev, "getPrevAll" : statics.getPrevAll, "getPrevUntil" : statics.getPrevUntil, "getSiblings" : statics.getSiblings, "not" : statics.not, "getOffsetParent" : statics.getOffsetParent, "isRendered" : statics.isRendered }); qxWeb.$attachStatic({ "isElement" : statics.isElement, "isNode" : statics.isNode, "isDocument" : statics.isDocument, "getDocument" : statics.getDocument, "getWindow" : statics.getWindow }); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2011-2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) * Daniel Wagner (danielwagner) ************************************************************************ */ /** * Attribute/Property handling for DOM elements. */ qx.Bootstrap.define("qx.module.Attribute", { statics : { /** * Returns the HTML content of the first item in the collection * @attach {qxWeb} * @return {String|null} HTML content or null if the collection is empty */ getHtml : function(){ if(this[0]){ return qx.bom.element.Attribute.get(this[0], "html"); }; return null; }, /** * Sets the HTML content of each item in the collection * * @attach {qxWeb} * @param html {String} HTML string * @return {qxWeb} The collection for chaining */ setHtml : function(html){ html = qx.bom.Html.fixEmptyTags(html); for(var i = 0;i < this.length;i++){ qx.bom.element.Attribute.set(this[i], "html", html); }; return this; }, /** * Sets an HTML attribute on each item in the collection * * @attach {qxWeb} * @param name {String} Attribute name * @param value {var} Attribute value * @return {qxWeb} The collection for chaining */ setAttribute : function(name, value){ for(var i = 0;i < this.length;i++){ qx.bom.element.Attribute.set(this[i], name, value); }; return this; }, /** * Returns the value of the given attribute for the first item in the * collection. * * @attach {qxWeb} * @param name {String} Attribute name * @return {var} Attribute value */ getAttribute : function(name){ if(this[0]){ return qx.bom.element.Attribute.get(this[0], name); }; return null; }, /** * Removes the given attribute from all elements in the collection * * @attach {qxWeb} * @param name {String} Attribute name * @return {qxWeb} The collection for chaining */ removeAttribute : function(name){ for(var i = 0;i < this.length;i++){ qx.bom.element.Attribute.set(this[i], name, null); }; return this; }, /** * Sets multiple attributes for each item in the collection. * * @attach {qxWeb} * @param attributes {Map} A map of attribute name/value pairs * @return {qxWeb} The collection for chaining */ setAttributes : function(attributes){ for(var name in attributes){ this.setAttribute(name, attributes[name]); }; return this; }, /** * Returns the values of multiple attributes for the first item in the collection * * @attach {qxWeb} * @param names {String[]} List of attribute names * @return {Map} Map of attribute name/value pairs */ getAttributes : function(names){ var attributes = { }; for(var i = 0;i < names.length;i++){ attributes[names[i]] = this.getAttribute(names[i]); }; return attributes; }, /** * Removes multiple attributes from each item in the collection. * * @attach {qxWeb} * @param attributes {String[]} List of attribute names * @return {qxWeb} The collection for chaining */ removeAttributes : function(attributes){ for(var i = 0,l = attributes.length;i < l;i++){ this.removeAttribute(attributes[i]); }; return this; }, /** * Sets a property on each item in the collection * * @attach {qxWeb} * @param name {String} Property name * @param value {var} Property value * @return {qxWeb} The collection for chaining */ setProperty : function(name, value){ for(var i = 0;i < this.length;i++){ this[i][name] = value; }; return this; }, /** * Returns the value of the given property for the first item in the * collection * * @attach {qxWeb} * @param name {String} Property name * @return {var} Property value */ getProperty : function(name){ if(this[0]){ return this[0][name]; }; return null; }, /** * Sets multiple properties for each item in the collection. * * @attach {qxWeb} * @param properties {Map} A map of property name/value pairs * @return {qxWeb} The collection for chaining */ setProperties : function(properties){ for(var name in properties){ this.setProperty(name, properties[name]); }; return this; }, /** * Returns the values of multiple properties for the first item in the collection * * @attach {qxWeb} * @param names {String[]} List of property names * @return {Map} Map of property name/value pairs */ getProperties : function(names){ var properties = { }; for(var i = 0;i < names.length;i++){ properties[names[i]] = this.getProperty(names[i]); }; return properties; }, /** * Returns the currently configured value for the first item in the collection. * Works with simple input fields as well as with select boxes or option * elements. Returns an array for select boxes with multi selection. In all * other cases, a string is returned. * * @attach {qxWeb} * @return {String|Array} */ getValue : function(){ if(this[0]){ return qx.bom.Input.getValue(this[0]); }; return null; }, /** * Applies the given value to each element in the collection. * Normally the value is given as a string/number value and applied to the * field content (textfield, textarea) or used to detect whether the field * is checked (checkbox, radiobutton). * Supports array values for selectboxes (multiple selection) and checkboxes * or radiobuttons (for convenience). * Please note: To modify the value attribute of a checkbox or radiobutton * use @link{#set} instead. * * @attach {qxWeb} * @param value {String|Number|Array} The value to apply * @return {qxWeb} The collection for chaining */ setValue : function(value){ for(var i = 0,l = this.length;i < l;i++){ qx.bom.Input.setValue(this[i], value); }; return this; } }, defer : function(statics){ qxWeb.$attach({ "getHtml" : statics.getHtml, "setHtml" : statics.setHtml, "getAttribute" : statics.getAttribute, "setAttribute" : statics.setAttribute, "removeAttribute" : statics.removeAttribute, "getAttributes" : statics.getAttributes, "setAttributes" : statics.setAttributes, "removeAttributes" : statics.removeAttributes, "getProperty" : statics.getProperty, "setProperty" : statics.setProperty, "getProperties" : statics.getProperties, "setProperties" : statics.setProperties, "getValue" : statics.getValue, "setValue" : statics.setValue }); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2009 Sebastian Werner, http://sebastian-werner.net License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) ====================================================================== This class contains code based on the following work: * jQuery http://jquery.com Version 1.3.1 Copyright: 2009 John Resig License: MIT: http://www.opensource.org/licenses/mit-license.php ************************************************************************ */ /* ************************************************************************ #ignore(qxWeb) ************************************************************************ */ /** * This class is mainly a convenience wrapper for DOM elements to * qooxdoo's event system. */ qx.Bootstrap.define("qx.bom.Html", { /* ***************************************************************************** STATICS ***************************************************************************** */ statics : { /** * Helper method for XHTML replacement. * * @param all {String} Complete string * @param front {String} Front of the match * @param tag {String} Tag name * @return {String} XHTML corrected tag */ __fixNonDirectlyClosableHelper : function(all, front, tag){ return tag.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i) ? all : front + "></" + tag + ">"; }, /** {Map} Contains wrap fragments for specific HTML matches */ __convertMap : { opt : [1, "<select multiple='multiple'>", "</select>"], // option or optgroup leg : [1, "<fieldset>", "</fieldset>"], table : [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>"], def : qx.core.Environment.select("engine.name", { "mshtml" : [1, "div<div>", "</div>"], "default" : null }) }, /** * Fixes "XHTML"-style tags in all browsers. * Replaces tags which are not allowed to be closed directly such as * <code>div</code> or <code>p</code>. They are patched to use opening and * closing tags instead, e.g. <code>&lt;p&gt;</code> => <code>&lt;p&gt;&lt;/p&gt;</code> * * @param html {String} HTML to fix * @return {String} Fixed HTML */ fixEmptyTags : function(html){ return html.replace(/(<(\w+)[^>]*?)\/>/g, this.__fixNonDirectlyClosableHelper); }, /** * Translates a HTML string into an array of elements. * * @param html {String} HTML string * @param context {Document} Context document in which (helper) elements should be created * @return {Array} List of resulting elements */ __convertHtmlString : function(html, context){ var div = context.createElement("div"); html = qx.bom.Html.fixEmptyTags(html); // Trim whitespace, otherwise indexOf won't work as expected var tags = html.replace(/^\s+/, "").substring(0, 5).toLowerCase(); // Auto-wrap content into required DOM structure var wrap,map = this.__convertMap; if(!tags.indexOf("<opt")){ wrap = map.opt; } else if(!tags.indexOf("<leg")){ wrap = map.leg; } else if(tags.match(/^<(thead|tbody|tfoot|colg|cap)/)){ wrap = map.table; } else if(!tags.indexOf("<tr")){ wrap = map.tr; } else if(!tags.indexOf("<td") || !tags.indexOf("<th")){ wrap = map.td; } else if(!tags.indexOf("<col")){ wrap = map.col; } else { wrap = map.def; };;;;; // Omit string concat when no wrapping is needed if(wrap){ // Go to html and back, then peel off extra wrappers div.innerHTML = wrap[1] + html + wrap[2]; // Move to the right depth var depth = wrap[0]; while(depth--){ div = div.lastChild; }; } else { div.innerHTML = html; }; // Fix IE specific bugs if((qx.core.Environment.get("engine.name") == "mshtml")){ // Remove IE's autoinserted <tbody> from table fragments // String was a <table>, *may* have spurious <tbody> var hasBody = /<tbody/i.test(html); // String was a bare <thead> or <tfoot> var tbody = !tags.indexOf("<table") && !hasBody ? div.firstChild && div.firstChild.childNodes : wrap[1] == "<table>" && !hasBody ? div.childNodes : []; for(var j = tbody.length - 1;j >= 0;--j){ if(tbody[j].tagName.toLowerCase() === "tbody" && !tbody[j].childNodes.length){ tbody[j].parentNode.removeChild(tbody[j]); }; }; // IE completely kills leading whitespace when innerHTML is used if(/^\s/.test(html)){ div.insertBefore(context.createTextNode(html.match(/^\s*/)[0]), div.firstChild); }; }; return qx.lang.Array.fromCollection(div.childNodes); }, /** * Cleans-up the given HTML and append it to a fragment * * When no <code>context</code> is given the global document is used to * create new DOM elements. * * When a <code>fragment</code> is given the nodes are appended to this * fragment except the script tags. These are returned in a separate Array. * * Please note: HTML coming from user input must be validated prior * to passing it to this method. HTML is temporarily inserted to the DOM * using <code>innerHTML</code>. As a consequence, scripts included in * attribute event handlers may be executed. * * @param objs {Element[]|String[]} Array of DOM elements or HTML strings * @param context {Document?document} Context in which the elements should be created * @param fragment {Element?null} Document fragment to appends elements to * @return {Element[]} Array of elements (when a fragment is given it only contains script elements) */ clean : function(objs, context, fragment){ 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; }; // Fast-Path: // If a single string is passed in and it's a single tag // just do a createElement and skip the rest if(!fragment && objs.length === 1 && typeof objs[0] === "string"){ var match = /^<(\w+)\s*\/?>$/.exec(objs[0]); if(match){ return [context.createElement(match[1])]; }; }; // Interate through items in incoming array var obj,ret = []; for(var i = 0,l = objs.length;i < l;i++){ obj = objs[i]; // Convert HTML string into DOM nodes if(typeof obj === "string"){ obj = this.__convertHtmlString(obj, context); }; // Append or merge depending on type if(obj.nodeType){ ret.push(obj); } else if(obj instanceof qx.type.BaseArray || (typeof qxWeb !== "undefined" && obj instanceof qxWeb)){ ret.push.apply(ret, Array.prototype.slice.call(obj, 0)); } else if(obj.toElement){ ret.push(obj.toElement()); } else { ret.push.apply(ret, obj); };; }; // Append to fragment and filter out scripts... or... if(fragment){ var scripts = [],elem; for(var i = 0;ret[i];i++){ elem = ret[i]; if(elem.nodeType == 1 && elem.tagName.toLowerCase() === "script" && (!elem.type || elem.type.toLowerCase() === "text/javascript")){ // Trying to remove the element from DOM if(elem.parentNode){ elem.parentNode.removeChild(ret[i]); }; // Store in script list scripts.push(elem); } else { if(elem.nodeType === 1){ // Recursively search for scripts and append them to the list of elements to process var scriptList = qx.lang.Array.fromCollection(elem.getElementsByTagName("script")); ret.splice.apply(ret, [i + 1, 0].concat(scriptList)); }; // Finally append element to fragment fragment.appendChild(elem); }; }; return scripts; }; // Otherwise return the array of all elements return ret; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Andreas Ecker (ecker) ====================================================================== This class contains code based on the following work: * jQuery http://jquery.com Version 1.3.1 Copyright: 2009 John Resig License: MIT: http://www.opensource.org/licenses/mit-license.php ************************************************************************ */ /* ************************************************************************ #require(qx.lang.Array#contains) ************************************************************************ */ /** * Cross browser abstractions to work with input elements. */ qx.Bootstrap.define("qx.bom.Input", { /* ***************************************************************************** STATICS ***************************************************************************** */ statics : { /** {Map} Internal data structures with all supported input types */ __types : { text : 1, textarea : 1, select : 1, checkbox : 1, radio : 1, password : 1, hidden : 1, submit : 1, image : 1, file : 1, search : 1, reset : 1, button : 1 }, /** * Creates an DOM input/textarea/select element. * * Attributes may be given directly with this call. This is critical * for some attributes e.g. name, type, ... in many clients. * * Note: <code>select</code> and <code>textarea</code> elements are created * using the identically named <code>type</code>. * * @param type {String} Any valid type for HTML, <code>select</code> * and <code>textarea</code> * @param attributes {Map} Map of attributes to apply * @param win {Window} Window to create the element for * @return {Element} The created input node */ create : function(type, attributes, win){ { }; // Work on a copy to not modify given attributes map var attributes = attributes ? qx.lang.Object.clone(attributes) : { }; var tag; if(type === "textarea" || type === "select"){ tag = type; } else { tag = "input"; attributes.type = type; }; return qx.dom.Element.create(tag, attributes, win); }, /** * Applies the given value to the element. * * Normally the value is given as a string/number value and applied * to the field content (textfield, textarea) or used to * detect whether the field is checked (checkbox, radiobutton). * * Supports array values for selectboxes (multiple-selection) * and checkboxes or radiobuttons (for convenience). * * Please note: To modify the value attribute of a checkbox or * radiobutton use {@link qx.bom.element.Attribute#set} instead. * * @param element {Element} element to update * @param value {String|Number|Array} the value to apply */ setValue : function(element, value){ var tag = element.nodeName.toLowerCase(); var type = element.type; var Array = qx.lang.Array; var Type = qx.lang.Type; if(typeof value === "number"){ value += ""; }; if((type === "checkbox" || type === "radio")){ if(Type.isArray(value)){ element.checked = Array.contains(value, element.value); } else { element.checked = element.value == value; }; } else if(tag === "select"){ var isArray = Type.isArray(value); var options = element.options; var subel,subval; for(var i = 0,l = options.length;i < l;i++){ subel = options[i]; subval = subel.getAttribute("value"); if(subval == null){ subval = subel.text; }; subel.selected = isArray ? Array.contains(value, subval) : value == subval; }; if(isArray && value.length == 0){ element.selectedIndex = -1; }; } else if((type === "text" || type === "textarea") && (qx.core.Environment.get("engine.name") == "mshtml")){ // These flags are required to detect self-made property-change // events during value modification. They are used by the Input // event handler to filter events. element.$$inValueSet = true; element.value = value; element.$$inValueSet = null; } else { element.value = value; };; }, /** * Returns the currently configured value. * * Works with simple input fields as well as with * select boxes or option elements. * * Returns an array in cases of multi-selection in * select boxes but in all other cases a string. * * @param element {Element} DOM element to query * @return {String|Array} The value of the given element */ getValue : function(element){ var tag = element.nodeName.toLowerCase(); if(tag === "option"){ return (element.attributes.value || { }).specified ? element.value : element.text; }; if(tag === "select"){ var index = element.selectedIndex; // Nothing was selected if(index < 0){ return null; }; var values = []; var options = element.options; var one = element.type == "select-one"; var clazz = qx.bom.Input; var value; // Loop through all the selected options for(var i = one ? index : 0,max = one ? index + 1 : options.length;i < max;i++){ var option = options[i]; if(option.selected){ // Get the specifc value for the option value = clazz.getValue(option); // We don't need an array for one selects if(one){ return value; }; // Multi-Selects return an array values.push(value); }; }; return values; } else { return (element.value || "").replace(/\r/g, ""); }; }, /** * Sets the text wrap behaviour of a text area element. * This property uses the attribute "wrap" respectively * the style property "whiteSpace" * * @signature function(element, wrap) * @param element {Element} DOM element to modify * @param wrap {Boolean} Whether to turn text wrap on or off. */ setWrap : qx.core.Environment.select("engine.name", { "mshtml" : function(element, wrap){ var wrapValue = wrap ? "soft" : "off"; // Explicitly set overflow-y CSS property to auto when wrapped, // allowing the vertical scroll-bar to appear if necessary var styleValue = wrap ? "auto" : ""; element.wrap = wrapValue; element.style.overflowY = styleValue; }, "gecko|webkit" : function(element, wrap){ var wrapValue = wrap ? "soft" : "off"; var styleValue = wrap ? "" : "auto"; element.setAttribute("wrap", wrapValue); element.style.overflow = styleValue; }, "default" : function(element, wrap){ element.style.whiteSpace = wrap ? "normal" : "nowrap"; } }) } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2011-2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) * Daniel Wagner (danielwagner) ************************************************************************ */ /* ************************************************************************ #ignore(qx.bom.element.AnimationJs) #ignore(qx.bom) ************************************************************************ */ /** * DOM manipulation module */ qx.Bootstrap.define("qx.module.Manipulating", { statics : { /** * Creates a new collection from the given argument. This can either be an * HTML string, a single DOM element or an array of elements * * @attachStatic{qxWeb} * @param html {String|Element[]} HTML string or DOM element(s) * @return {qxWeb} Collection of elements */ create : function(html){ return qxWeb.$init(qx.bom.Html.clean([html])); }, /** * Clones the items in the current collection and returns them in a new set. * Event listeners can also be cloned. * * @attach{qxWeb} * @param events {Boolean} clone event listeners. Default: <pre>false</pre> * @return {qxWeb} New collection with clones */ clone : function(events){ var clones = []; for(var i = 0;i < this.length;i++){ clones[i] = this[i].cloneNode(true); }; if(events === true && this.copyEventsTo){ this.copyEventsTo(clones); }; return qxWeb(clones); }, /** * Appends content to each element in the current set. Accepts an HTML string, * a single DOM element or an array of elements * * @attach{qxWeb} * @param html {String|Element[]} HTML string or DOM element(s) to append * @return {qxWeb} The collection for chaining */ append : function(html){ var arr = qx.bom.Html.clean([html]); var children = qxWeb.$init(arr); for(var i = 0,l = this.length;i < l;i++){ for(var j = 0,m = children.length;j < m;j++){ if(i == 0){ // first parent: move the target node(s) qx.dom.Element.insertEnd(children[j], this[i]); } else { qx.dom.Element.insertEnd(children.eq(j).clone(true)[0], this[i]); }; }; }; return this; }, /** * Appends all items in the collection to the specified parents. If multiple * parents are given, the items will be moved to the first parent, while * clones of the items will be appended to subsequent parents. * * @attach{qxWeb} * @param parent {String|Element[]} Parent selector expression or list of * parent elements * @return {qxWeb} The collection for chaining */ appendTo : function(parent){ parent = qx.module.Manipulating.__getElementArray(parent); for(var i = 0,l = parent.length;i < l;i++){ for(var j = 0,m = this.length;j < m;j++){ if(i == 0){ // first parent: move the target node(s) qx.dom.Element.insertEnd(this[j], parent[i]); } else { // further parents: clone the target node(s) qx.dom.Element.insertEnd(this.eq(j).clone(true)[0], parent[i]); }; }; }; return this; }, /** * Inserts the current collection before each target item. The collection * items are moved before the first target. For subsequent targets, * clones of the collection items are created and inserted. * * @attach{qxWeb} * @param target {String|Element} Selector expression or DOM element * @return {qxWeb} The collection for chaining */ insertBefore : function(target){ target = qx.module.Manipulating.__getElementArray(target); for(var i = 0,l = target.length;i < l;i++){ for(var j = 0,m = this.length;j < m;j++){ if(i == 0){ // first target: move the target node(s) qx.dom.Element.insertBefore(this[j], target[i]); } else { // further targets: clone the target node(s) qx.dom.Element.insertBefore(this.eq(j).clone(true)[0], target[i]); }; }; }; return this; }, /** * Inserts the current collection after each target item. The collection * items are moved after the first target. For subsequent targets, * clones of the collection items are created and inserted. * * @attach{qxWeb} * @param target {String|Element} Selector expression or DOM element * @return {qxWeb} The collection for chaining */ insertAfter : function(target){ target = qx.module.Manipulating.__getElementArray(target); for(var i = 0,l = target.length;i < l;i++){ for(var j = this.length - 1;j >= 0;j--){ if(i == 0){ // first target: move the target node(s) qx.dom.Element.insertAfter(this[j], target[i]); } else { // further targets: clone the target node(s) qx.dom.Element.insertAfter(this.eq(j).clone(true)[0], target[i]); }; }; }; return this; }, /** * Returns an array from a selector expression or a single element * * @attach{qxWeb} * @param arg {String|Element} Selector expression or DOM element * @return {Element[]} Array of elements * @internal */ __getElementArray : function(arg){ if(!qx.lang.Type.isArray(arg)){ var fromSelector = qxWeb(arg); arg = fromSelector.length > 0 ? fromSelector : [arg]; }; return arg; }, /** * Wraps each element in the collection in a copy of an HTML structure. * Elements will be appended to the deepest nested element in the structure * as determined by a depth-first search. * * @attach{qxWeb} * @param wrapper {var} Selector expression, HTML string, DOM element or * list of DOM elements * @return {qxWeb} The collection for chaining */ wrap : function(wrapper){ var wrapper = qx.module.Manipulating.__getCollectionFromArgument(wrapper); if(wrapper.length == 0 || !qx.dom.Node.isElement(wrapper[0])){ return this; }; for(var i = 0,l = this.length;i < l;i++){ var clonedwrapper = wrapper.eq(0).clone(true); qx.dom.Element.insertAfter(clonedwrapper[0], this[i]); var innermost = qx.module.Manipulating.__getInnermostElement(clonedwrapper[0]); qx.dom.Element.insertEnd(this[i], innermost); }; return this; }, /** * Creates a new collection from the given argument * @param arg {var} Selector expression, HTML string, DOM element or list of * DOM elements * @return {qxWeb} Collection * @internal */ __getCollectionFromArgument : function(arg){ var coll; // Collection/array of DOM elements if(qx.lang.Type.isArray(arg)){ coll = qxWeb(arg); } else { var arr = qx.bom.Html.clean([arg]); if(arr.length > 0 && qx.dom.Node.isElement(arr[0])){ coll = qxWeb(arr); } else { coll = qxWeb(arg); }; }; return coll; }, /** * Returns the innermost element of a DOM tree as determined by a simple * depth-first search. * * @param element {Element} Root element * @return {Element} innermost element * @internal */ __getInnermostElement : function(element){ if(element.childNodes.length == 0){ return element; }; for(var i = 0,l = element.childNodes.length;i < l;i++){ if(element.childNodes[i].nodeType === 1){ return this.__getInnermostElement(element.childNodes[i]); }; }; return element; }, /** * Removes each element in the current collection from the DOM * * @attach{qxWeb} * @return {qxWeb} The collection for chaining */ remove : function(){ for(var i = 0;i < this.length;i++){ qx.dom.Element.remove(this[i]); }; return this; }, /** * Removes all content from the elements in the collection * * @attach{qxWeb} * @return {qxWeb} The collection for chaining */ empty : function(){ for(var i = 0;i < this.length;i++){ // don't use innerHTML="" because of [BUG #7323] // and don't use textContent="" because of missing IE8 support while(this[i].firstChild){ this[i].removeChild(this[i].firstChild); }; }; return this; }, /** * Inserts content before each element in the collection. This can either * be an HTML string, an array of HTML strings, a single DOM element or an * array of elements. * * @attach{qxWeb} * @param content {String[]|Element[]} HTML string(s) or DOM element(s) * @return {qxWeb} The collection for chaining */ before : function(content){ if(!qx.lang.Type.isArray(content)){ content = [content]; }; var fragment = document.createDocumentFragment(); qx.bom.Html.clean(content, document, fragment); this.forEach(function(item, index){ var kids = qx.lang.Array.cast(fragment.childNodes, Array); for(var i = 0,l = kids.length;i < l;i++){ var child; if(index < this.length - 1){ child = kids[i].cloneNode(true); } else { child = kids[i]; }; item.parentNode.insertBefore(child, item); }; }, this); return this; }, /** * Inserts content after each element in the collection. This can either * be an HTML string, an array of HTML strings, a single DOM element or an * array of elements. * * @attach{qxWeb} * @param content {String[]|Element[]} HTML string(s) or DOM element(s) * @return {qxWeb} The collection for chaining */ after : function(content){ if(!qx.lang.Type.isArray(content)){ content = [content]; }; var fragment = document.createDocumentFragment(); qx.bom.Html.clean(content, document, fragment); this.forEach(function(item, index){ var kids = qx.lang.Array.cast(fragment.childNodes, Array); for(var i = kids.length - 1;i >= 0;i--){ var child; if(index < this.length - 1){ child = kids[i].cloneNode(true); } else { child = kids[i]; }; item.parentNode.insertBefore(child, item.nextSibling); }; }, this); return this; }, /** * Returns the left scroll position of the first element in the collection. * * @attach{qxWeb} * @return {Number} Current left scroll position */ getScrollLeft : function(){ var obj = this[0]; if(!obj){ return null; }; var Node = qx.dom.Node; if(Node.isWindow(obj) || Node.isDocument(obj)){ return qx.bom.Viewport.getScrollLeft(); }; return obj.scrollLeft; }, /** * Returns the top scroll position of the first element in the collection. * * @attach{qxWeb} * @return {Number} Current top scroll position */ getScrollTop : function(){ var obj = this[0]; if(!obj){ return null; }; var Node = qx.dom.Node; if(Node.isWindow(obj) || Node.isDocument(obj)){ return qx.bom.Viewport.getScrollTop(); }; return obj.scrollTop; }, /** Default animation descriptions for animated scrolling **/ _animationDescription : { scrollLeft : { duration : 700, timing : "ease-in", keep : 100, keyFrames : { '0' : { }, '100' : { scrollLeft : 1 } } }, scrollTop : { duration : 700, timing : "ease-in", keep : 100, keyFrames : { '0' : { }, '100' : { scrollTop : 1 } } } }, /** * Performs animated scrolling * * @param property {String} Element property to animate: <code>scrollLeft</code> * or <code>scrollTop</code> * @param value {Number} Final scroll position * @param duration {Number} The animation's duration in ms * @return {q} The collection for chaining. */ __animateScroll : function(property, value, duration){ var desc = qx.lang.Object.clone(qx.module.Manipulating._animationDescription[property], true); desc.keyFrames[100][property] = value; return this.animate(desc, duration); }, /** * Scrolls the elements of the collection to the given coordinate. * * @attach{qxWeb} * @param value {Number} Left scroll position * @param duration {Number?} Optional: Duration in ms for animated scrolling * @return {qxWeb} The collection for chaining */ setScrollLeft : function(value, duration){ var Node = qx.dom.Node; if(duration && qx.bom.element && qx.bom.element.AnimationJs){ qx.module.Manipulating.__animateScroll.bind(this, "scrollLeft", value, duration)(); }; for(var i = 0,l = this.length,obj;i < l;i++){ obj = this[i]; if(Node.isElement(obj)){ if(!(duration && qx.bom.element && qx.bom.element.AnimationJs)){ obj.scrollLeft = value; }; } else if(Node.isWindow(obj)){ obj.scrollTo(value, this.getScrollTop(obj)); } else if(Node.isDocument(obj)){ Node.getWindow(obj).scrollTo(value, this.getScrollTop(obj)); };; }; return this; }, /** * Scrolls the elements of the collection to the given coordinate. * * @attach{qxWeb} * @param value {Number} Top scroll position * @param duration {Number?} Optional: Duration in ms for animated scrolling * @return {qxWeb} The collection for chaining */ setScrollTop : function(value, duration){ var Node = qx.dom.Node; if(duration && qx.bom.element && qx.bom.element.AnimationJs){ qx.module.Manipulating.__animateScroll.bind(this, "scrollTop", value, duration)(); }; for(var i = 0,l = this.length,obj;i < l;i++){ obj = this[i]; if(Node.isElement(obj)){ if(!(duration && qx.bom.element && qx.bom.element.AnimationJs)){ obj.scrollTop = value; }; } else if(Node.isWindow(obj)){ obj.scrollTo(this.getScrollLeft(obj), value); } else if(Node.isDocument(obj)){ Node.getWindow(obj).scrollTo(this.getScrollLeft(obj), value); };; }; return this; }, /** * Focuses the first element in the collection * * @attach{qxWeb} * @return {qxWeb} The collection for chaining */ focus : function(){ try{ this[0].focus(); } catch(ex) { }; return this; }, /** * Blurs each element in the collection * * @attach{qxWeb} * @return {qxWeb} The collection for chaining */ blur : function(){ this.forEach(function(item, index){ try{ item.blur(); } catch(ex) { }; }); return this; } }, defer : function(statics){ qxWeb.$attachStatic({ "create" : statics.create }); qxWeb.$attach({ "append" : statics.append, "appendTo" : statics.appendTo, "remove" : statics.remove, "empty" : statics.empty, "before" : statics.before, "insertBefore" : statics.insertBefore, "after" : statics.after, "insertAfter" : statics.insertAfter, "wrap" : statics.wrap, "clone" : statics.clone, "getScrollLeft" : statics.getScrollLeft, "setScrollLeft" : statics.setScrollLeft, "getScrollTop" : statics.getScrollTop, "setScrollTop" : statics.setScrollTop, "focus" : statics.focus, "blur" : statics.blur }); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /* ************************************************************************ #require(qx.module.Manipulating) #require(qx.module.Css) #require(qx.module.Attribute) #require(qx.module.Event) #require(qx.module.Environment) #require(qx.module.Polyfill) #require(qx.module.Traversing) ************************************************************************ */ /** * The module supplies a fallback implementation for placeholders, which is * used on input and textarea elements. If the browser supports native placeholders * the API silently ignores all calls. If not, an element will be created for every * given input element and acts as placeholder. Most modern browsers support * placeholders which makes the fallback only relevant for IE < 10 and FF < 4. * * * <a href="http://dev.w3.org/html5/spec/single-page.html#the-placeholder-attribute">HTML Spec</a> * * * <a href="http://caniuse.com/#feat=input-placeholder">Browser Support</a> */ qx.Bootstrap.define("qx.module.Placeholder", { statics : { /** * String holding the property name which holds the placeholder * element for each input. */ PLACEHOLDER_NAME : "$qx_placeholder", /** * Queries for all input and textarea elements on the page and updates * their placeholder. * @attachStatic{qxWeb, placeholder.update} */ update : function(){ // ignore if native placeholder are supported if(!qxWeb.env.get("css.placeholder")){ qxWeb("input[placeholder], textarea[placeholder]").updatePlaceholder(); }; }, /** * Updates the placeholders for input's and textarea's in the collection. * This includes positioning, styles and DOM positioning. * In case the browser supports native placeholders, this methods simply * does nothing. * * @attach {qxWeb} * @return {qxWeb} The collection for chaining */ updatePlaceholder : function(){ // ignore everything if native placeholder are supported if(!qxWeb.env.get("css.placeholder")){ for(var i = 0;i < this.length;i++){ var item = qxWeb(this[i]); // ignore all not fitting items in the collection var placeholder = item.getAttribute("placeholder"); var tagName = item.getProperty("tagName"); if(!placeholder || (tagName != "TEXTAREA" && tagName != "INPUT")){ continue; }; // create the element if necessary var placeholderEl = item.getProperty(qx.module.Placeholder.PLACEHOLDER_NAME); if(!placeholderEl){ placeholderEl = qx.module.Placeholder.__createPlaceholderElement(item); }; // remove and add handling var itemInBody = item.isRendered(); var placeholderElInBody = placeholderEl.isRendered(); if(itemInBody && !placeholderElInBody){ item.before(placeholderEl); } else if(!itemInBody && placeholderElInBody){ placeholderEl.remove(); return this; }; qx.module.Placeholder.__syncStyles(item); }; }; return this; }, /** * Internal helper method to update the styles for a given input element. * @param item {qxWeb} The input element to update. */ __syncStyles : function(item){ var placeholder = item.getAttribute("placeholder"); var placeholderEl = item.getProperty(qx.module.Placeholder.PLACEHOLDER_NAME); var zIndex = item.getStyle("z-index"); var paddingHor = parseInt(item.getStyle("padding-left")) + 2 * parseInt(item.getStyle("padding-right")); var paddingVer = parseInt(item.getStyle("padding-top")) + 2 * parseInt(item.getStyle("padding-bottom")); placeholderEl.setHtml(placeholder).setStyles({ display : item.getValue() == "" ? "inline" : "none", zIndex : zIndex == "auto" ? 1 : zIndex + 1, textAlign : item.getStyle("text-align"), width : (item.getWidth() - paddingHor - 4) + "px", height : (item.getHeight() - paddingVer - 4) + "px", left : item.getOffset().left + "px", top : item.getOffset().top + "px", fontFamily : item.getStyle("font-family"), fontStyle : item.getStyle("font-style"), fontVariant : item.getStyle("font-variant"), fontWeight : item.getStyle("font-weight"), fontSize : item.getStyle("font-size"), paddingTop : (parseInt(item.getStyle("padding-top")) + 2) + "px", paddingRight : (parseInt(item.getStyle("padding-right")) + 2) + "px", paddingBottom : (parseInt(item.getStyle("padding-bottom")) + 2) + "px", paddingLeft : (parseInt(item.getStyle("padding-left")) + 2) + "px" }); }, /** * Creates a placeholder element based on the given input element. * @param item {qxWeb} The input element. * @return {qxWeb} The placeholder element. */ __createPlaceholderElement : function(item){ // create the label with initial styles var placeholderEl = qxWeb.create("<label>").setStyles({ position : "absolute", color : "#989898", overflow : "hidden", pointerEvents : "none" }); // store the label at the input field item.setProperty(qx.module.Placeholder.PLACEHOLDER_NAME, placeholderEl); // update the placeholders visibility on keyUp item.on("keyup", function(item){ var el = item.getProperty(qx.module.Placeholder.PLACEHOLDER_NAME); el.setStyle("display", item.getValue() == "" ? "inline" : "none"); }.bind(this, item)); // for browsers not supporting pointer events if(!qxWeb.env.get("event.pointer")){ placeholderEl.setStyle("cursor", "text").on("click", function(item){ item.focus(); }.bind(this, item)); }; return placeholderEl; } }, defer : function(statics){ qxWeb.$attachStatic({ "placeholder" : { update : statics.update } }); qxWeb.$attach({ "updatePlaceholder" : statics.updatePlaceholder }); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /** * HTML templating module. This is a wrapper for mustache.js which is a * "framework-agnostic way to render logic-free views". * * Here is a basic example how to use it: * <pre class="javascript"> * var template = "Hi, my name is {{name}}!"; * var view = {name: "qooxdoo"}; * q.template.render(template, view); * // return "Hi, my name is qooxdoo!" * </pre> * * For further details, please visit the mustache.js documentation here: * https://github.com/janl/mustache.js/blob/master/README.md */ qx.Bootstrap.define("qx.module.Template", { statics : { /** * Helper method which provides direct access to templates stored as HTML in * the DOM. The DOM node with the given ID will be treated as a template, * parsed and a new DOM node will be returned containing the parsed data. * Keep in mind that templates can only have one root element. * Additionally, you should not put the template into a regular, hidden * DOM element because the template may not be valid HTML due to the containing * mustache tags. We suggest to put it into a script tag with the type * <code>text/template</code>. * * @attachStatic{qxWeb, template.get} * @param id {String} The id of the HTML template in the DOM. * @param view {Object} The object holding the data to render. * @param partials {Object} Object holding parts of a template. * @return {qxWeb} Collection containing a single DOM element with the parsed * template data. */ get : function(id, view, partials){ var el = qx.bom.Template.get(id, view, partials); return qxWeb.$init([el]); }, /** * Original and only template method of mustache.js. For further * documentation, please visit https://github.com/janl/mustache.js * * @attachStatic{qxWeb, template.render} * @param template {String} The String containing the template. * @param view {Object} The object holding the data to render. * @param partials {Object} Object holding parts of a template. * @return {String} The parsed template. */ render : function(template, view, partials){ return qx.bom.Template.render(template, view, partials); } }, defer : function(statics){ qxWeb.$attachStatic({ "template" : { get : statics.get, render : statics.render } }); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ====================================================================== This class contains code based on the following work: * Mustache.js version 0.7.0 Code: https://github.com/janl/mustache.js Copyright: (c) 2009 Chris Wanstrath (Ruby) (c) 2010 Jan Lehnardt (JavaScript) License: MIT: http://www.opensource.org/licenses/mit-license.php ---------------------------------------------------------------------- Copyright (c) 2009 Chris Wanstrath (Ruby) Copyright (c) 2010 Jan Lehnardt (JavaScript) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ************************************************************************ */ /* ************************************************************************ #ignore(module) ************************************************************************ */ /** * The is a template class which can be used for HTML templating. In fact, * this is a wrapper for mustache.js which is a "framework-agnostic way to * render logic-free views". * * Here is a basic example how to use it: * Template: * <pre class="javascript"> * var template = "Hi, my name is {{name}}!"; * var view = {name: "qooxdoo"}; * qx.bom.Template.render(template, view); * // return "Hi, my name is qooxdoo!" * </pre> * * For further details, please visit the mustache.js documentation here: * https://github.com/janl/mustache.js/blob/master/README.md * */ qx.Bootstrap.define("qx.bom.Template", { statics : { /** Contains the mustache.js version. */ version : null, /** * Original and only template method of mustache.js. For further * documentation, please visit https://github.com/janl/mustache.js * * @signature function(template, view, partials) * @param template {String} The String containing the template. * @param view {Object} The object holding the data to render. * @param partials {Object} Object holding parts of a template. * @return {String} The parsed template. */ render : null, /** * Helper method which provides you with a direct access to templates * stored as HTML in the DOM. The DOM node with the given ID will be used * as a template, parsed and a new DOM node will be returned containing the * parsed data. Keep in mind to have only one root DOM element in the the * template. * Additionally, you should not put the template into a regular, hidden * DOM element because the template may not be valid HTML due to the containing * mustache tags. We suggest to put it into a script tag with the type * <code>text/template</code>. * * @param id {String} The id of the HTML template in the DOM. * @param view {Object} The object holding the data to render. * @param partials {Object} Object holding parts of a template. * @return {Element} A DOM element holding the parsed template data. */ get : function(id, view, partials){ // get the content stored in the DOM var template = document.getElementById(id); var inner = template.innerHTML; // apply the view inner = this.render(inner, view, partials); // special case for text only conversion if(inner.search(/<|>/) === -1){ return document.createTextNode(inner); }; // create a helper to convert the string into DOM nodes var helper = qx.dom.Element.create("div"); helper.innerHTML = inner; return helper.children[0]; } } }); (function(){ /** * Below is the original mustache.js code. Snapshot date is mentioned in * the head of this file. * @lint ignoreUndefined(module) */ /*! * mustache.js - Logic-less {{mustache}} templates with JavaScript * http://github.com/janl/mustache.js */ /*global define: false*/ var Mustache; /** * @lint ignoreUndefined(module,define) */ (function(exports){ Mustache = exports; }((function(){ var exports = { }; exports.name = "mustache.js"; exports.version = "0.7.0"; exports.tags = ["{{", "}}"]; exports.Scanner = Scanner; exports.Context = Context; exports.Writer = Writer; var whiteRe = /\s*/; var spaceRe = /\s+/; var nonSpaceRe = /\S/; var eqRe = /\s*=/; var curlyRe = /\s*\}/; var tagRe = /#|\^|\/|>|\{|&|=|!/; // Workaround for https://issues.apache.org/jira/browse/COUCHDB-577 // See https://github.com/janl/mustache.js/issues/189 function testRe(re, string){ return RegExp.prototype.test.call(re, string); }; function isWhitespace(string){ return !testRe(nonSpaceRe, string); }; var isArray = Array.isArray || function(obj){ return Object.prototype.toString.call(obj) === "[object Array]"; }; function escapeRe(string){ return string.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&"); }; var entityMap = { "&" : "&amp;", "<" : "&lt;", ">" : "&gt;", '"' : '&quot;', "'" : '&#39;', "/" : '&#x2F;' }; function escapeHtml(string){ return String(string).replace(/[&<>"'\/]/g, function(s){ return entityMap[s]; }); }; // Export the escaping function so that the user may override it. // See https://github.com/janl/mustache.js/issues/244 exports.escape = escapeHtml; function Scanner(string){ this.string = string; this.tail = string; this.pos = 0; }; /** * Returns `true` if the tail is empty (end of string). */ Scanner.prototype.eos = function(){ return this.tail === ""; }; /** * Tries to match the given regular expression at the current position. * Returns the matched text if it can match, the empty string otherwise. */ Scanner.prototype.scan = function(re){ var match = this.tail.match(re); if(match && match.index === 0){ this.tail = this.tail.substring(match[0].length); this.pos += match[0].length; return match[0]; }; return ""; }; /** * Skips all text until the given regular expression can be matched. Returns * the skipped string, which is the entire tail if no match can be made. */ Scanner.prototype.scanUntil = function(re){ var match,pos = this.tail.search(re); switch(pos){case -1: match = this.tail; this.pos += this.tail.length; this.tail = ""; break;case 0: match = ""; break;default: match = this.tail.substring(0, pos); this.tail = this.tail.substring(pos); this.pos += pos;}; return match; }; function Context(view, parent){ this.view = view; this.parent = parent; this.clearCache(); }; Context.make = function(view){ return (view instanceof Context) ? view : new Context(view); }; Context.prototype.clearCache = function(){ this._cache = { }; }; Context.prototype.push = function(view){ return new Context(view, this); }; Context.prototype.lookup = function(name){ var value = this._cache[name]; if(!value){ if(name === "."){ value = this.view; } else { var context = this; while(context){ if(name.indexOf(".") > 0){ var names = name.split("."),i = 0; value = context.view; while(value && i < names.length){ value = value[names[i++]]; }; } else { value = context.view[name]; }; if(value != null){ break; }; context = context.parent; }; }; this._cache[name] = value; }; if(typeof value === "function"){ value = value.call(this.view); }; return value; }; function Writer(){ this.clearCache(); }; Writer.prototype.clearCache = function(){ this._cache = { }; this._partialCache = { }; }; Writer.prototype.compile = function(template, tags){ var fn = this._cache[template]; if(!fn){ var tokens = exports.parse(template, tags); fn = this._cache[template] = this.compileTokens(tokens, template); }; return fn; }; Writer.prototype.compilePartial = function(name, template, tags){ var fn = this.compile(template, tags); this._partialCache[name] = fn; return fn; }; Writer.prototype.compileTokens = function(tokens, template){ var fn = compileTokens(tokens); var self = this; return function(view, partials){ if(partials){ if(typeof partials === "function"){ self._loadPartial = partials; } else { for(var name in partials){ self.compilePartial(name, partials[name]); }; }; }; return fn(self, Context.make(view), template); }; }; Writer.prototype.render = function(template, view, partials){ return this.compile(template)(view, partials); }; Writer.prototype._section = function(name, context, text, callback){ var value = context.lookup(name); switch(typeof value){case "object": if(isArray(value)){ var buffer = ""; for(var i = 0,len = value.length;i < len;++i){ buffer += callback(this, context.push(value[i])); }; return buffer; }; return value ? callback(this, context.push(value)) : "";case "function": var self = this; var scopedRender = function(template){ return self.render(template, context); }; return value.call(context.view, text, scopedRender) || "";default: if(value){ return callback(this, context); };}; return ""; }; Writer.prototype._inverted = function(name, context, callback){ var value = context.lookup(name); // Use JavaScript's definition of falsy. Include empty arrays. // See https://github.com/janl/mustache.js/issues/186 if(!value || (isArray(value) && value.length === 0)){ return callback(this, context); }; return ""; }; Writer.prototype._partial = function(name, context){ if(!(name in this._partialCache) && this._loadPartial){ this.compilePartial(name, this._loadPartial(name)); }; var fn = this._partialCache[name]; return fn ? fn(context) : ""; }; Writer.prototype._name = function(name, context){ var value = context.lookup(name); if(typeof value === "function"){ value = value.call(context.view); }; return (value == null) ? "" : String(value); }; Writer.prototype._escaped = function(name, context){ return exports.escape(this._name(name, context)); }; /** * Calculates the bounds of the section represented by the given `token` in * the original template by drilling down into nested sections to find the * last token that is part of that section. Returns an array of [start, end]. */ function sectionBounds(token){ var start = token[3]; var end = start; var tokens; while((tokens = token[4]) && tokens.length){ token = tokens[tokens.length - 1]; end = token[3]; }; return [start, end]; }; /** * Low-level function that compiles the given `tokens` into a function * that accepts three arguments: a Writer, a Context, and the template. */ function compileTokens(tokens){ var subRenders = { }; function subRender(i, tokens, template){ if(!subRenders[i]){ var fn = compileTokens(tokens); subRenders[i] = function(writer, context){ return fn(writer, context, template); }; }; return subRenders[i]; }; return function(writer, context, template){ var buffer = ""; var token,sectionText; for(var i = 0,len = tokens.length;i < len;++i){ token = tokens[i]; switch(token[0]){case "#": sectionText = template.slice.apply(template, sectionBounds(token)); buffer += writer._section(token[1], context, sectionText, subRender(i, token[4], template)); break;case "^": buffer += writer._inverted(token[1], context, subRender(i, token[4], template)); break;case ">": buffer += writer._partial(token[1], context); break;case "&": buffer += writer._name(token[1], context); break;case "name": buffer += writer._escaped(token[1], context); break;case "text": buffer += token[1]; break;}; }; return buffer; }; }; /** * Forms the given array of `tokens` into a nested tree structure where * tokens that represent a section have a fifth item: an array that contains * all tokens in that section. */ function nestTokens(tokens){ var tree = []; var collector = tree; var sections = []; var token,section; for(var i = 0;i < tokens.length;++i){ token = tokens[i]; switch(token[0]){case "#":case "^": token[4] = []; sections.push(token); collector.push(token); collector = token[4]; break;case "/": if(sections.length === 0){ throw new Error("Unopened section: " + token[1]); }; section = sections.pop(); if(section[1] !== token[1]){ throw new Error("Unclosed section: " + section[1]); }; if(sections.length > 0){ collector = sections[sections.length - 1][4]; } else { collector = tree; }; break;default: collector.push(token);}; }; // Make sure there were no open sections when we're done. section = sections.pop(); if(section){ throw new Error("Unclosed section: " + section[1]); }; return tree; }; /** * Combines the values of consecutive text tokens in the given `tokens` array * to a single token. */ function squashTokens(tokens){ var token,lastToken; for(var i = 0;i < tokens.length;++i){ token = tokens[i]; if(lastToken && lastToken[0] === "text" && token[0] === "text"){ lastToken[1] += token[1]; lastToken[3] = token[3]; tokens.splice(i--, 1); } else { lastToken = token; }; }; }; function escapeTags(tags){ if(tags.length !== 2){ throw new Error("Invalid tags: " + tags.join(" ")); }; return [new RegExp(escapeRe(tags[0]) + "\\s*"), new RegExp("\\s*" + escapeRe(tags[1]))]; }; /** * Breaks up the given `template` string into a tree of token objects. If * `tags` is given here it must be an array with two string values: the * opening and closing tags used in the template (e.g. ["<%", "%>"]). Of * course, the default is to use mustaches (i.e. Mustache.tags). */ exports.parse = function(template, tags){ tags = tags || exports.tags; var tagRes = escapeTags(tags); var scanner = new Scanner(template); var tokens = [],// Buffer to hold the tokens spaces = [],// Indices of whitespace tokens on the current line hasTag = false,// Is there a {{tag}} on the current line? nonSpace = false; // Is there a non-space char on the current line? // Strips all whitespace tokens array for the current line // if there was a {{#tag}} on it and otherwise only space. function stripSpace(){ if(hasTag && !nonSpace){ while(spaces.length){ tokens.splice(spaces.pop(), 1); }; } else { spaces = []; }; hasTag = false; nonSpace = false; }; var start,type,value,chr; while(!scanner.eos()){ start = scanner.pos; value = scanner.scanUntil(tagRes[0]); if(value){ for(var i = 0,len = value.length;i < len;++i){ chr = value.charAt(i); if(isWhitespace(chr)){ spaces.push(tokens.length); } else { nonSpace = true; }; tokens.push(["text", chr, start, start + 1]); start += 1; if(chr === "\n"){ stripSpace(); }; }; }; start = scanner.pos; // Match the opening tag. if(!scanner.scan(tagRes[0])){ break; }; hasTag = true; type = scanner.scan(tagRe) || "name"; // Skip any whitespace between tag and value. scanner.scan(whiteRe); // Extract the tag value. if(type === "="){ value = scanner.scanUntil(eqRe); scanner.scan(eqRe); scanner.scanUntil(tagRes[1]); } else if(type === "{"){ var closeRe = new RegExp("\\s*" + escapeRe("}" + tags[1])); value = scanner.scanUntil(closeRe); scanner.scan(curlyRe); scanner.scanUntil(tagRes[1]); type = "&"; } else { value = scanner.scanUntil(tagRes[1]); }; // Match the closing tag. if(!scanner.scan(tagRes[1])){ throw new Error("Unclosed tag at " + scanner.pos); }; tokens.push([type, value, start, scanner.pos]); if(type === "name" || type === "{" || type === "&"){ nonSpace = true; }; // Set the tags for the next time around. if(type === "="){ tags = value.split(spaceRe); tagRes = escapeTags(tags); }; }; squashTokens(tokens); return nestTokens(tokens); }; // The high-level clearCache, compile, compilePartial, and render functions // use this default writer. var _writer = new Writer(); /** * Clears all cached templates and partials in the default writer. */ exports.clearCache = function(){ return _writer.clearCache(); }; /** * Compiles the given `template` to a reusable function using the default * writer. */ exports.compile = function(template, tags){ return _writer.compile(template, tags); }; /** * Compiles the partial with the given `name` and `template` to a reusable * function using the default writer. */ exports.compilePartial = function(name, template, tags){ return _writer.compilePartial(name, template, tags); }; /** * Compiles the given array of tokens (the output of a parse) to a reusable * function using the default writer. */ exports.compileTokens = function(tokens, template){ return _writer.compileTokens(tokens, template); }; /** * Renders the `template` with the given `view` and `partials` using the * default writer. */ exports.render = function(template, view, partials){ return _writer.render(template, view, partials); }; // This is here for backwards compatibility with 0.4.x. exports.to_html = function(template, view, partials, send){ var result = exports.render(template, view, partials); if(typeof send === "function"){ send(result); } else { return result; }; }; return exports; }()))); /** * Above is the original mustache code. */ // EXPOSE qooxdoo variant qx.bom.Template.version = Mustache.version; qx.bom.Template.render = Mustache.render; })(); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Daniel Wagner (danielwagner) ************************************************************************ */ /* ************************************************************************ #require(qx.module.Event) ************************************************************************ */ /** * Orientation handler which is responsible for registering and unregistering a * {@link qx.event.handler.OrientationCore} handler for each given element. */ qx.Bootstrap.define("qx.module.event.OrientationHandler", { statics : { /** * List of events that require an orientation handler * @type {Array} */ TYPES : ["orientationchange"], /** * Creates an orientation handler for the given window when an * orientationchange event listener is attached to it * * @param element {Window} DOM Window */ register : function(element){ if(!qx.dom.Node.isWindow(element)){ throw new Error("The 'orientationchange' event is only available on window objects!"); }; if(!element.__orientationHandler){ if(!element.__emitter){ element.__emitter = new qx.event.Emitter(); }; element.__orientationHandler = new qx.event.handler.OrientationCore(element, element.__emitter); }; }, /** * Removes the orientation event handler from the element if there are no more * orientationchange event listeners attached to it * @param element {Element} DOM element */ unregister : function(element){ if(element.__orientationHandler){ if(!element.__emitter){ element.__orientationHandler = null; } else { var hasListener = false; var listeners = element.__emitter.getListeners(); qx.module.event.OrientationHandler.TYPES.forEach(function(type){ if(type in listeners && listeners[type].length > 0){ hasListener = true; }; }); if(!hasListener){ element.__orientationHandler = null; }; }; }; } }, defer : function(statics){ qxWeb.$registerEventHook(statics.TYPES, statics.register, statics.unregister); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Tino Butz (tbtz) * Daniel Wagner (danielwagner) ====================================================================== This class contains code based on the following work: * Unify Project Homepage: http://unify-project.org Copyright: 2009-2010 Deutsche Telekom AG, Germany, http://telekom.com License: MIT: http://www.opensource.org/licenses/mit-license.php ************************************************************************ */ /** * Listens for native orientation change events */ qx.Bootstrap.define("qx.event.handler.OrientationCore", { extend : Object, /** * * @param targetWindow {Window} DOM window object * @param emitter {qx.event.Emitter} Event emitter object */ construct : function(targetWindow, emitter){ this._window = targetWindow || window; this.__emitter = emitter; this._initObserver(); }, members : { __emitter : null, _window : null, _currentOrientation : null, __onNativeWrapper : null, __nativeEventType : null, /* --------------------------------------------------------------------------- OBSERVER INIT --------------------------------------------------------------------------- */ /** * Initializes the native orientation change event listeners. */ _initObserver : function(){ this.__onNativeWrapper = qx.lang.Function.listener(this._onNative, this); // Handle orientation change event for Android devices by the resize event. // See http://stackoverflow.com/questions/1649086/detect-rotation-of-android-phone-in-the-browser-with-javascript // for more information. this.__nativeEventType = qx.bom.Event.supportsEvent(this._window, "orientationchange") ? "orientationchange" : "resize"; qx.bom.Event.addNativeListener(this._window, this.__nativeEventType, this.__onNativeWrapper); }, /* --------------------------------------------------------------------------- OBSERVER STOP --------------------------------------------------------------------------- */ /** * Disconnects the native orientation change event listeners. */ _stopObserver : function(){ qx.bom.Event.removeNativeListener(this._window, this.__nativeEventType, this.__onNativeWrapper); }, /* --------------------------------------------------------------------------- NATIVE EVENT OBSERVERS --------------------------------------------------------------------------- */ /** * Handler for the native orientation change event. * * @signature function(domEvent) * @param domEvent {Event} The touch event from the browser. */ _onNative : function(domEvent){ var orientation = qx.bom.Viewport.getOrientation(); if(this._currentOrientation != orientation){ this._currentOrientation = orientation; var mode = qx.bom.Viewport.isLandscape() ? "landscape" : "portrait"; domEvent._orientation = orientation; domEvent._mode = mode; if(this.__emitter){ this.__emitter.emit("orientationchange", domEvent); }; }; } }, /* ***************************************************************************** DESTRUCTOR ***************************************************************************** */ destruct : function(){ this._stopObserver(); this.__manager = this.__emitter = null; } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2011 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Tristan Koch (tristankoch) ************************************************************************ */ /* ************************************************************************ #ignore(XDomainRequest) #require(qx.bom.request.Xhr#open) #require(qx.bom.request.Xhr#send) #require(qx.bom.request.Xhr#on) #require(qx.bom.request.Xhr#onreadystatechange) #require(qx.bom.request.Xhr#onload) #require(qx.bom.request.Xhr#onloadend) #require(qx.bom.request.Xhr#onerror) #require(qx.bom.request.Xhr#onabort) #require(qx.bom.request.Xhr#ontimeout) #require(qx.bom.request.Xhr#setRequestHeader) #require(qx.bom.request.Xhr#getAllResponseHeaders) #require(qx.bom.request.Xhr#getRequest) ************************************************************************ */ /** * A wrapper of the XMLHttpRequest host object (or equivalent). The interface is * similar to <a href="http://www.w3.org/TR/XMLHttpRequest/">XmlHttpRequest</a>. * * Hides browser inconsistencies and works around bugs found in popular * implementations. * * <div class="desktop"> * Example: * * <pre class="javascript"> * var req = new qx.bom.request.Xhr(); * req.onload = function() { * // Handle data received * req.responseText; * } * * req.open("GET", url); * req.send(); * </pre> * </div> */ qx.Bootstrap.define("qx.bom.request.Xhr", { construct : function(){ this.__onNativeReadyStateChangeBound = qx.Bootstrap.bind(this.__onNativeReadyStateChange, this); this.__onNativeAbortBound = qx.Bootstrap.bind(this.__onNativeAbort, this); this.__onTimeoutBound = qx.Bootstrap.bind(this.__onTimeout, this); this.__initNativeXhr(); this._emitter = new qx.event.Emitter(); // BUGFIX: IE // IE keeps connections alive unless aborted on unload if(window.attachEvent){ this.__onUnloadBound = qx.Bootstrap.bind(this.__onUnload, this); window.attachEvent("onunload", this.__onUnloadBound); }; }, statics : { UNSENT : 0, OPENED : 1, HEADERS_RECEIVED : 2, LOADING : 3, DONE : 4 }, events : { /** Fired at ready state changes. */ "readystatechange" : "qx.bom.request.Xhr", /** Fired on error. */ "error" : "qx.bom.request.Xhr", /** Fired at loadend. */ "loadend" : "qx.bom.request.Xhr", /** Fired on timeouts. */ "timeout" : "qx.bom.request.Xhr", /** Fired when the request is aborted. */ "abort" : "qx.bom.request.Xhr", /** Fired on successful retrieval. */ "load" : "qx.bom.request.Xhr" }, members : { /* --------------------------------------------------------------------------- PUBLIC --------------------------------------------------------------------------- */ /** * {Number} Ready state. * * States can be: * UNSENT: 0, * OPENED: 1, * HEADERS_RECEIVED: 2, * LOADING: 3, * DONE: 4 */ readyState : 0, /** * {String} The response of the request as text. */ responseText : "", /** * {Object} The response of the request as a Document object. */ responseXML : null, /** * {Number} The HTTP status code. */ status : 0, /** * {String} The HTTP status text. */ statusText : "", /** * {Number} Timeout limit in milliseconds. * * 0 (default) means no timeout. Not supported for synchronous requests. */ timeout : 0, /** * Initializes (prepares) request. * * @lint ignoreUndefined(XDomainRequest) * * @param method {String?"GET"} * The HTTP method to use. * @param url {String} * The URL to which to send the request. * @param async {Boolean?true} * Whether or not to perform the operation asynchronously. * @param user {String?null} * Optional user name to use for authentication purposes. * @param password {String?null} * Optional password to use for authentication purposes. */ open : function(method, url, async, user, password){ this.__checkDisposed(); // Mimick native behavior if(typeof url === "undefined"){ throw new Error("Not enough arguments"); } else if(typeof method === "undefined"){ method = "GET"; }; // Reset flags that may have been set on previous request this.__abort = false; this.__send = false; this.__conditional = false; // Store URL for later checks this.__url = url; if(typeof async == "undefined"){ async = true; }; this.__async = async; // BUGFIX // IE < 9 and FF < 3.5 cannot reuse the native XHR to issue many requests if(!this.__supportsManyRequests() && this.readyState > qx.bom.request.Xhr.UNSENT){ // XmlHttpRequest Level 1 requires open() to abort any pending requests // associated to the object. Since we're dealing with a new object here, // we have to emulate this behavior. Moreover, allow old native XHR to be garbage collected // // Dispose and abort. // this.dispose(); // Replace the underlying native XHR with a new one that can // be used to issue new requests. this.__initNativeXhr(); }; // Restore handler in case it was removed before this.__nativeXhr.onreadystatechange = this.__onNativeReadyStateChangeBound; try{ { }; this.__nativeXhr.open(method, url, async, user, password); } catch(OpenError) { // Only work around exceptions caused by cross domain request attempts if(!qx.util.Request.isCrossDomain(url)){ // Is same origin throw OpenError; }; if(!this.__async){ this.__openError = OpenError; }; if(this.__async){ // Try again with XDomainRequest // (Success case not handled on purpose) // - IE 9 if(window.XDomainRequest){ this.readyState = 4; this.__nativeXhr = new XDomainRequest(); this.__nativeXhr.onerror = qx.Bootstrap.bind(function(){ this._emit("readystatechange"); this._emit("error"); this._emit("loadend"); }, this); { }; this.__nativeXhr.open(method, url, async, user, password); return; }; // Access denied // - IE 6: -2146828218 // - IE 7: -2147024891 // - Legacy Firefox window.setTimeout(qx.Bootstrap.bind(function(){ if(this.__disposed){ return; }; this.readyState = 4; this._emit("readystatechange"); this._emit("error"); this._emit("loadend"); }, this)); }; }; // BUGFIX: IE < 9 // IE < 9 tends to cache overly agressive. This may result in stale // representations. Force validating freshness of cached representation. if(qx.core.Environment.get("engine.name") === "mshtml" && qx.core.Environment.get("browser.documentmode") < 9 && this.__nativeXhr.readyState > 0){ this.__nativeXhr.setRequestHeader("If-Modified-Since", "-1"); }; // BUGFIX: Firefox // Firefox < 4 fails to trigger onreadystatechange OPENED for sync requests if(qx.core.Environment.get("engine.name") === "gecko" && parseInt(qx.core.Environment.get("engine.version"), 10) < 2 && !this.__async){ // Native XHR is already set to readyState DONE. Fake readyState // and call onreadystatechange manually. this.readyState = qx.bom.request.Xhr.OPENED; this._emit("readystatechange"); }; }, /** * Sets an HTTP request header to be used by the request. * * Note: The request must be initialized before using this method. * * @param key {String} * The name of the header whose value is to be set. * @param value {String} * The value to set as the body of the header. * @return {qx.bom.request.Xhr} Self for chaining. */ setRequestHeader : function(key, value){ this.__checkDisposed(); // Detect conditional requests if(key == "If-Match" || key == "If-Modified-Since" || key == "If-None-Match" || key == "If-Range"){ this.__conditional = true; }; this.__nativeXhr.setRequestHeader(key, value); return this; }, /** * Sends request. * * @param data {String|Document?null} * Optional data to send. * @return {qx.bom.request.Xhr} Self for chaining. */ send : function(data){ this.__checkDisposed(); // BUGFIX: IE & Firefox < 3.5 // For sync requests, some browsers throw error on open() // while it should be on send() // if(!this.__async && this.__openError){ throw this.__openError; }; // BUGFIX: Opera // On network error, Opera stalls at readyState HEADERS_RECEIVED // This violates the spec. See here http://www.w3.org/TR/XMLHttpRequest2/#send // (Section: If there is a network error) // // To fix, assume a default timeout of 10 seconds. Note: The "error" // event will be fired correctly, because the error flag is inferred // from the statusText property. Of course, compared to other // browsers there is an additional call to ontimeout(), but this call // should not harm. // if(qx.core.Environment.get("engine.name") === "opera" && this.timeout === 0){ this.timeout = 10000; }; // Timeout if(this.timeout > 0){ this.__timerId = window.setTimeout(this.__onTimeoutBound, this.timeout); }; // BUGFIX: Firefox 2 // "NS_ERROR_XPC_NOT_ENOUGH_ARGS" when calling send() without arguments data = typeof data == "undefined" ? null : data; // Some browsers may throw an error when sending of async request fails. // This violates the spec which states only sync requests should. try{ { }; this.__nativeXhr.send(data); } catch(SendError) { if(!this.__async){ throw SendError; }; // BUGFIX // Some browsers throws error when file not found via file:// protocol. // Synthesize readyState changes. if(this._getProtocol() === "file:"){ this.readyState = 2; this.__readyStateChange(); var that = this; window.setTimeout(function(){ if(that.__disposed){ return; }; that.readyState = 3; that.__readyStateChange(); that.readyState = 4; that.__readyStateChange(); }); }; }; // BUGFIX: Firefox // Firefox fails to trigger onreadystatechange DONE for sync requests if(qx.core.Environment.get("engine.name") === "gecko" && !this.__async){ // Properties all set, only missing native readystatechange event this.__onNativeReadyStateChange(); }; // Set send flag this.__send = true; return this; }, /** * Abort request - i.e. cancels any network activity. * * Note: * On Windows 7 every browser strangely skips the loading phase * when this method is called (because readyState never gets 3). * * So keep this in mind if you rely on the phases which are * passed through. They will be "opened", "sent", "abort" * instead of normally "opened", "sent", "loading", "abort". * * @return {qx.bom.request.Xhr} Self for chaining. */ abort : function(){ this.__checkDisposed(); this.__abort = true; this.__nativeXhr.abort(); if(this.__nativeXhr){ this.readyState = this.__nativeXhr.readyState; }; return this; }, /** * Helper to emit events and call the callback methods. * @param event {String} The name of the event. */ _emit : function(event){ this["on" + event](); this._emitter.emit(event, this); }, /** * Event handler for XHR event that fires at every state change. * * Replace with custom method to get informed about the communication progress. */ onreadystatechange : function(){ }, /** * Event handler for XHR event "load" that is fired on successful retrieval. * * Note: This handler is called even when the HTTP status indicates an error. * * Replace with custom method to listen to the "load" event. */ onload : function(){ }, /** * Event handler for XHR event "loadend" that is fired on retrieval. * * Note: This handler is called even when a network error (or similar) * occurred. * * Replace with custom method to listen to the "loadend" event. */ onloadend : function(){ }, /** * Event handler for XHR event "error" that is fired on a network error. * * Replace with custom method to listen to the "error" event. */ onerror : function(){ }, /** * Event handler for XHR event "abort" that is fired when request * is aborted. * * Replace with custom method to listen to the "abort" event. */ onabort : function(){ }, /** * Event handler for XHR event "timeout" that is fired when timeout * interval has passed. * * Replace with custom method to listen to the "timeout" event. */ ontimeout : function(){ }, /** * Add an event listener for the given event name. * * @param name {String} The name of the event to listen to. * @param listener {Function} The function to execute when the event is fired * @param ctx {var?} The context of the listener. * @return {qx.bom.request.Xhr} Self for chaining. */ on : function(name, listener, ctx){ this._emitter.on(name, listener, ctx); return this; }, /** * Get a single response header from response. * * @param header {String} * Key of the header to get the value from. * @return {String} * Response header. */ getResponseHeader : function(header){ this.__checkDisposed(); return this.__nativeXhr.getResponseHeader(header); }, /** * Get all response headers from response. * * @return {String} All response headers. */ getAllResponseHeaders : function(){ this.__checkDisposed(); return this.__nativeXhr.getAllResponseHeaders(); }, /** * Get wrapped native XMLHttpRequest (or equivalent). * * Can be XMLHttpRequest or ActiveX. * * @return {Object} XMLHttpRequest or equivalent. */ getRequest : function(){ return this.__nativeXhr; }, /* --------------------------------------------------------------------------- HELPER --------------------------------------------------------------------------- */ /** * Dispose object and wrapped native XHR. * @return {Boolean} <code>true</code> if the object was successfully disposed */ dispose : function(){ if(this.__disposed){ return false; }; window.clearTimeout(this.__timerId); // Remove unload listener in IE. Aborting on unload is no longer required // for this instance. if(window.detachEvent){ window.detachEvent("onunload", this.__onUnloadBound); }; // May fail in IE try{ this.__nativeXhr.onreadystatechange; } catch(PropertiesNotAccessable) { return false; }; // Clear out listeners var noop = function(){ }; this.__nativeXhr.onreadystatechange = noop; this.__nativeXhr.onload = noop; this.__nativeXhr.onerror = noop; // Abort any network activity this.abort(); // Remove reference to native XHR this.__nativeXhr = null; this.__disposed = true; return true; }, /* --------------------------------------------------------------------------- PROTECTED --------------------------------------------------------------------------- */ /** * Create XMLHttpRequest (or equivalent). * * @return {Object} XMLHttpRequest or equivalent. */ _createNativeXhr : function(){ var xhr = qx.core.Environment.get("io.xhr"); if(xhr === "xhr"){ return new XMLHttpRequest(); }; if(xhr == "activex"){ return new window.ActiveXObject("Microsoft.XMLHTTP"); }; qx.Bootstrap.error(this, "No XHR support available."); }, /** * Get protocol of requested URL. * * @return {String} The used protocol. */ _getProtocol : function(){ var url = this.__url; var protocolRe = /^(\w+:)\/\//; // Could be http:// from file:// if(url !== null && url.match){ var match = url.match(protocolRe); if(match && match[1]){ return match[1]; }; }; return window.location.protocol; }, /* --------------------------------------------------------------------------- PRIVATE --------------------------------------------------------------------------- */ /** * {Object} XMLHttpRequest or equivalent. */ __nativeXhr : null, /** * {Boolean} Whether request is async. */ __async : null, /** * {Function} Bound __onNativeReadyStateChange handler. */ __onNativeReadyStateChangeBound : null, /** * {Function} Bound __onNativeAbort handler. */ __onNativeAbortBound : null, /** * {Function} Bound __onUnload handler. */ __onUnloadBound : null, /** * {Function} Bound __onTimeout handler. */ __onTimeoutBound : null, /** * {Boolean} Send flag */ __send : null, /** * {String} Requested URL */ __url : null, /** * {Boolean} Abort flag */ __abort : null, /** * {Boolean} Timeout flag */ __timeout : null, /** * {Boolean} Whether object has been disposed. */ __disposed : null, /** * {Number} ID of timeout timer. */ __timerId : null, /** * {Error} Error thrown on open, if any. */ __openError : null, /** * {Boolean} Conditional get flag */ __conditional : null, /** * Init native XHR. */ __initNativeXhr : function(){ // Create native XHR or equivalent and hold reference this.__nativeXhr = this._createNativeXhr(); // Track native ready state changes this.__nativeXhr.onreadystatechange = this.__onNativeReadyStateChangeBound; // Track native abort, when supported if(this.__nativeXhr.onabort){ this.__nativeXhr.onabort = this.__onNativeAbortBound; }; // Reset flags this.__disposed = this.__send = this.__abort = false; }, /** * Track native abort. * * In case the end user cancels the request by other * means than calling abort(). */ __onNativeAbort : function(){ // When the abort that triggered this method was not a result from // calling abort() if(!this.__abort){ this.abort(); }; }, /** * Handle native onreadystatechange. * * Calls user-defined function onreadystatechange on each * state change and syncs the XHR status properties. */ __onNativeReadyStateChange : function(){ var nxhr = this.__nativeXhr,propertiesReadable = true; { }; // BUGFIX: IE, Firefox // onreadystatechange() is called twice for readyState OPENED. // // Call onreadystatechange only when readyState has changed. if(this.readyState == nxhr.readyState){ return; }; // Sync current readyState this.readyState = nxhr.readyState; // BUGFIX: IE // Superfluous onreadystatechange DONE when aborting OPENED // without send flag if(this.readyState === qx.bom.request.Xhr.DONE && this.__abort && !this.__send){ return; }; // BUGFIX: IE // IE fires onreadystatechange HEADERS_RECEIVED and LOADING when sync // // According to spec, only onreadystatechange OPENED and DONE should // be fired. if(!this.__async && (nxhr.readyState == 2 || nxhr.readyState == 3)){ return; }; // Default values according to spec. this.status = 0; this.statusText = this.responseText = ""; this.responseXML = null; if(this.readyState >= qx.bom.request.Xhr.HEADERS_RECEIVED){ // In some browsers, XHR properties are not readable // while request is in progress. try{ this.status = nxhr.status; this.statusText = nxhr.statusText; this.responseText = nxhr.responseText; this.responseXML = nxhr.responseXML; } catch(XhrPropertiesNotReadable) { propertiesReadable = false; }; if(propertiesReadable){ this.__normalizeStatus(); this.__normalizeResponseXML(); }; }; this.__readyStateChange(); // BUGFIX: IE // Memory leak in XMLHttpRequest (on-page) if(this.readyState == qx.bom.request.Xhr.DONE){ // Allow garbage collecting of native XHR if(nxhr){ nxhr.onreadystatechange = function(){ }; }; }; }, /** * Handle readystatechange. Called internally when readyState is changed. */ __readyStateChange : function(){ var that = this; // Cancel timeout before invoking handlers because they may throw if(this.readyState === qx.bom.request.Xhr.DONE){ // Request determined DONE. Cancel timeout. window.clearTimeout(this.__timerId); }; // BUGFIX: IE // IE < 8 fires LOADING and DONE on open() - before send() - when from cache if(qx.core.Environment.get("engine.name") == "mshtml" && qx.core.Environment.get("browser.documentmode") < 8){ // Detect premature events when async. LOADING and DONE is // illogical to happen before request was sent. if(this.__async && !this.__send && this.readyState >= qx.bom.request.Xhr.LOADING){ if(this.readyState == qx.bom.request.Xhr.LOADING){ // To early to fire, skip. return; }; if(this.readyState == qx.bom.request.Xhr.DONE){ window.setTimeout(function(){ if(that.__disposed){ return; }; // Replay previously skipped that.readyState = 3; that._emit("readystatechange"); that.readyState = 4; that._emit("readystatechange"); that.__readyStateChangeDone(); }); return; }; }; }; // Always fire "readystatechange" this._emit("readystatechange"); if(this.readyState === qx.bom.request.Xhr.DONE){ this.__readyStateChangeDone(); }; }, /** * Handle readystatechange. Called internally by * {@link #__readyStateChange} when readyState is DONE. */ __readyStateChangeDone : function(){ // Fire "timeout" if timeout flag is set if(this.__timeout){ this._emit("timeout"); // BUGFIX: Opera // Since Opera does not fire "error" on network error, fire additional // "error" on timeout (may well be related to network error) if(qx.core.Environment.get("engine.name") === "opera"){ this._emit("error"); }; this.__timeout = false; } else { if(this.__abort){ this._emit("abort"); } else { if(this.__isNetworkError()){ this._emit("error"); } else { this._emit("load"); }; }; }; // Always fire "onloadend" when DONE this._emit("loadend"); }, /** * Check for network error. * * @return {Boolean} Whether a network error occured. */ __isNetworkError : function(){ var error; // Infer the XHR internal error flag from statusText when not aborted. // See http://www.w3.org/TR/XMLHttpRequest2/#error-flag and // http://www.w3.org/TR/XMLHttpRequest2/#the-statustext-attribute // // With file://, statusText is always falsy. Assume network error when // response is empty. if(this._getProtocol() === "file:"){ error = !this.responseText; } else { error = !this.statusText; }; return error; }, /** * Handle faked timeout. */ __onTimeout : function(){ // Basically, mimick http://www.w3.org/TR/XMLHttpRequest2/#timeout-error var nxhr = this.__nativeXhr; this.readyState = qx.bom.request.Xhr.DONE; // Set timeout flag this.__timeout = true; // No longer consider request. Abort. nxhr.abort(); this.responseText = ""; this.responseXML = null; // Signal readystatechange this.__readyStateChange(); }, /** * Normalize status property across browsers. */ __normalizeStatus : function(){ var isDone = this.readyState === qx.bom.request.Xhr.DONE; // BUGFIX: Most browsers // Most browsers tell status 0 when it should be 200 for local files if(this._getProtocol() === "file:" && this.status === 0 && isDone){ if(!this.__isNetworkError()){ this.status = 200; }; }; // BUGFIX: IE // IE sometimes tells 1223 when it should be 204 if(this.status === 1223){ this.status = 204; }; // BUGFIX: Opera // Opera tells 0 for conditional requests when it should be 304 // // Detect response to conditional request that signals fresh cache. if(qx.core.Environment.get("engine.name") === "opera"){ if(isDone && // Done this.__conditional && // Conditional request !this.__abort && // Not aborted this.status === 0){ this.status = 304; }; }; }, /** * Normalize responseXML property across browsers. */ __normalizeResponseXML : function(){ // BUGFIX: IE // IE does not recognize +xml extension, resulting in empty responseXML. // // Check if Content-Type is +xml, verify missing responseXML then parse // responseText as XML. if(qx.core.Environment.get("engine.name") == "mshtml" && (this.getResponseHeader("Content-Type") || "").match(/[^\/]+\/[^\+]+\+xml/) && this.responseXML && !this.responseXML.documentElement){ var dom = new window.ActiveXObject("Microsoft.XMLDOM"); dom.async = false; dom.validateOnParse = false; dom.loadXML(this.responseText); this.responseXML = dom; }; }, /** * Handler for native unload event. */ __onUnload : function(){ try{ // Abort and dispose if(this){ this.dispose(); }; } catch(e) { }; }, /** * Helper method to determine whether browser supports reusing the * same native XHR to send more requests. * @return {Boolean} <code>true</code> if request object reuse is supported */ __supportsManyRequests : function(){ var name = qx.core.Environment.get("engine.name"); var version = qx.core.Environment.get("browser.version"); return !(name == "mshtml" && version < 9 || name == "gecko" && version < 3.5); }, /** * Throw when already disposed. */ __checkDisposed : function(){ if(this.__disposed){ throw new Error("Already disposed"); }; } }, defer : function(){ qx.core.Environment.add("qx.debug.io", false); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2011 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Tristan Koch (tristankoch) ************************************************************************ */ /** * Static helpers for handling requests. */ qx.Bootstrap.define("qx.util.Request", { statics : { /** * Whether URL given points to resource that is cross-domain, * i.e. not of same origin. * * @param url {String} URL. * @return {Boolean} Whether URL is cross domain. */ isCrossDomain : function(url){ var result = qx.util.Uri.parseUri(url),location = window.location; if(!location){ return false; }; var protocol = location.protocol; // URL is relative in the sence that it points to origin host if(!(url.indexOf("//") !== -1)){ return false; }; if(protocol.substr(0, protocol.length - 1) == result.protocol && location.host === result.host && location.port === result.port){ return false; }; return true; }, /** * Determine if given HTTP status is considered successful. * * @param status {Number} HTTP status. * @return {Boolean} Whether status is considered successful. */ isSuccessful : function(status){ return (status >= 200 && status < 300 || status === 304); }, /** * Request body is ignored for HTTP method GET and HEAD. * * See http://www.w3.org/TR/XMLHttpRequest2/#the-send-method. * * @param method {String} The HTTP method. * @return {Boolean} Whether request may contain body. */ methodAllowsRequestBody : function(method){ return !((/^(GET)|(HEAD)$/).test(method)); } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Carsten Lergenmueller (carstenl) * Fabian Jakobs (fbjakobs) * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * Determines browser-dependent information about the transport layer. * * This class is used by {@link qx.core.Environment} and should not be used * directly. Please check its class comment for details how to use it. * * @internal */ qx.Bootstrap.define("qx.bom.client.Transport", { /* ***************************************************************************** STATICS ***************************************************************************** */ statics : { /** * Returns the maximum number of parallel requests the current browser * supports per host addressed. * * Note that this assumes one connection can support one request at a time * only. Technically, this is not correct when pipelining is enabled (which * it currently is only for IE 8 and Opera). In this case, the number * returned will be too low, as one connection supports multiple pipelined * requests. This is accepted for now because pipelining cannot be * detected from JavaScript and because modern browsers have enough * parallel connections already - it's unlikely an app will require more * than 4 parallel XMLHttpRequests to one server at a time. * * @internal * @return {Integer} Maximum number of parallel requests */ getMaxConcurrentRequestCount : function(){ var maxConcurrentRequestCount; // Parse version numbers. var versionParts = qx.bom.client.Engine.getVersion().split("."); var versionMain = 0; var versionMajor = 0; var versionMinor = 0; // Main number if(versionParts[0]){ versionMain = versionParts[0]; }; // Major number if(versionParts[1]){ versionMajor = versionParts[1]; }; // Minor number if(versionParts[2]){ versionMinor = versionParts[2]; }; // IE 8 gives the max number of connections in a property // see http://msdn.microsoft.com/en-us/library/cc197013(VS.85).aspx if(window.maxConnectionsPerServer){ maxConcurrentRequestCount = window.maxConnectionsPerServer; } else if(qx.bom.client.Engine.getName() == "opera"){ // Opera: 8 total // see http://operawiki.info/HttpProtocol maxConcurrentRequestCount = 8; } else if(qx.bom.client.Engine.getName() == "webkit"){ // Safari: 4 // http://www.stevesouders.com/blog/2008/03/20/roundup-on-parallel-connections/ // Bug #6917: Distinguish Chrome from Safari, Chrome has 6 connections // according to // http://stackoverflow.com/questions/561046/how-many-concurrent-ajax-xmlhttprequest-requests-are-allowed-in-popular-browser maxConcurrentRequestCount = 4; } else if(qx.bom.client.Engine.getName() == "gecko" && ((versionMain > 1) || ((versionMain == 1) && (versionMajor > 9)) || ((versionMain == 1) && (versionMajor == 9) && (versionMinor >= 1)))){ // FF 3.5 (== Gecko 1.9.1): 6 Connections. // see http://gemal.dk/blog/2008/03/18/firefox_3_beta_5_will_have_improved_connection_parallelism/ maxConcurrentRequestCount = 6; } else { // Default is 2, as demanded by RFC 2616 // see http://blogs.msdn.com/ie/archive/2005/04/11/407189.aspx maxConcurrentRequestCount = 2; };;; return maxConcurrentRequestCount; }, /** * Checks whether the app is loaded with SSL enabled which means via https. * * @internal * @return {Boolean} <code>true</code>, if the app runs on https */ getSsl : function(){ return window.location.protocol === "https:"; }, /** * Checks what kind of XMLHttpRequest object the browser supports * for the current protocol, if any. * * The standard XMLHttpRequest is preferred over ActiveX XMLHTTP. * * @internal * @return {String} * <code>"xhr"</code>, if the browser provides standard XMLHttpRequest.<br/> * <code>"activex"</code>, if the browser provides ActiveX XMLHTTP.<br/> * <code>""</code>, if there is not XHR support at all. */ getXmlHttpRequest : function(){ // Standard XHR can be disabled in IE's security settings, // therefore provide ActiveX as fallback. Additionaly, // standard XHR in IE7 is broken for file protocol. var supports = window.ActiveXObject ? (function(){ if(window.location.protocol !== "file:"){ try{ new window.XMLHttpRequest(); return "xhr"; } catch(noXhr) { }; }; try{ new window.ActiveXObject("Microsoft.XMLHTTP"); return "activex"; } catch(noActiveX) { }; })() : (function(){ try{ new window.XMLHttpRequest(); return "xhr"; } catch(noXhr) { }; })(); return supports || ""; } }, defer : function(statics){ qx.core.Environment.add("io.maxrequests", statics.getMaxConcurrentRequestCount); qx.core.Environment.add("io.ssl", statics.getSsl); qx.core.Environment.add("io.xhr", statics.getXmlHttpRequest); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /* ************************************************************************ #require(qx.bom.request.Xhr#open) ************************************************************************ */ /** * This module provides basic IO functionality. It contains three ways to load * data: * * * XMLHttpRequest: {@link #xhr} * * Script tag: {@link #script} * * Script tag using JSONP: {@link #jsonp} */ qx.Bootstrap.define("qx.module.Io", { statics : { /** * Returns a configured XMLHttpRequest object. Using the send method will * finally send the request. * * @param url {String} Mandatory URL to load the data from. * @param settings {Map?} Optional settings map which may contain one of * the following settings: * <ul> * <li><code>method</code> The method of the request. Default: <code>GET</code></li> * <li><code>async</code> flag to mark the request as asynchronous. Default: <code>true</code></li> * <li><code>header</code> A map of request headers.</li> * </ul> * * @attachStatic {qxWeb, io.xhr} * @return {qx.bom.request.Xhr} The request object. */ xhr : function(url, settings){ if(!settings){ settings = { }; }; var xhr = new qx.bom.request.Xhr(); xhr.open(settings.method, url, settings.async); if(settings.header){ var header = settings.header; for(var key in header){ xhr.setRequestHeader(key, header[key]); }; }; return xhr; }, /** * Returns a predefined script tag wrapper which can be used to load data * from cross-domain origins. * * @param url {String} Mandatory URL to load the data from. * @attachStatic {qxWeb, io.script} * @return {qx.bom.request.Script} The request object. */ script : function(url){ var script = new qx.bom.request.Script(); script.open("get", url); return script; }, /** * Returns a predefined script tag wrapper which can be used to load data * from cross-domain origins via JSONP. * * @param url {String} Mandatory URL to load the data from. * @param settings {Map?} Optional settings map which may contain one of * the following settings: * * * <code>callbackName</code>: The name of the callback which will * be called by the loaded script. * * <code>callbackParam</code>: The name of the callback expected by the server * @attachStatic {qxWeb, io.jsonp} * @return {qx.bom.request.Jsonp} The request object. */ jsonp : function(url, settings){ var script = new qx.bom.request.Jsonp(); if(settings && settings.callbackName){ script.setCallbackName(settings.callbackName); }; if(settings && settings.callbackParam){ script.setCallbackParam(settings.callbackParam); }; script.setPrefix("qxWeb.$$"); // needed in case no callback name is given script.open("get", url); return script; } }, defer : function(statics){ qxWeb.$attachStatic({ io : { xhr : statics.xhr, script : statics.script, jsonp : statics.jsonp } }); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2011 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Tristan Koch (tristankoch) ************************************************************************ */ /** * Script loader with interface similar to * <a href="http://www.w3.org/TR/XMLHttpRequest/">XmlHttpRequest</a>. * * The script loader can be used to load scripts from arbitrary sources. * <span class="desktop"> * For JSONP requests, consider the {@link qx.bom.request.Jsonp} transport * that derives from the script loader. * </span> * * <div class="desktop"> * Example: * * <pre class="javascript"> * var req = new qx.bom.request.Script(); * req.onload = function() { * // Script is loaded and parsed and * // globals set are available * } * * req.open("GET", url); * req.send(); * </pre> * </div> */ /* ************************************************************************ #ignore(qx.core.Environment) #require(qx.bom.request.Script#_success) #require(qx.bom.request.Script#abort) #require(qx.bom.request.Script#dispose) #require(qx.bom.request.Script#getAllResponseHeaders) #require(qx.bom.request.Script#getResponseHeader) #require(qx.bom.request.Script#setDetermineSuccess) #require(qx.bom.request.Script#setRequestHeader) ************************************************************************ */ qx.Bootstrap.define("qx.bom.request.Script", { construct : function(){ this.__initXhrProperties(); this.__onNativeLoadBound = qx.Bootstrap.bind(this._onNativeLoad, this); this.__onNativeErrorBound = qx.Bootstrap.bind(this._onNativeError, this); this.__onTimeoutBound = qx.Bootstrap.bind(this._onTimeout, this); this.__headElement = document.head || document.getElementsByTagName("head")[0] || document.documentElement; this._emitter = new qx.event.Emitter(); // BUGFIX: Browsers not supporting error handler // Set default timeout to capture network errors // // Note: The script is parsed and executed, before a "load" is fired. this.timeout = this.__supportsErrorHandler() ? 0 : 15000; }, events : { /** Fired at ready state changes. */ "readystatechange" : "qx.bom.request.Script", /** Fired on error. */ "error" : "qx.bom.request.Script", /** Fired at loadend. */ "loadend" : "qx.bom.request.Script", /** Fired on timeouts. */ "timeout" : "qx.bom.request.Script", /** Fired when the request is aborted. */ "abort" : "qx.bom.request.Script", /** Fired on successful retrieval. */ "load" : "qx.bom.request.Script" }, members : { /** * {Number} Ready state. * * States can be: * UNSENT: 0, * OPENED: 1, * LOADING: 2, * LOADING: 3, * DONE: 4 * * Contrary to {@link qx.bom.request.Xhr#readyState}, the script transport * does not receive response headers. For compatibility, another LOADING * state is implemented that replaces the HEADERS_RECEIVED state. */ readyState : null, /** * {Number} The status code. * * Note: The script transport cannot determine the HTTP status code. */ status : null, /** * {String} The status text. * * The script transport does not receive response headers. For compatibility, * the statusText property is set to the status casted to string. */ statusText : null, /** * {Number} Timeout limit in milliseconds. * * 0 (default) means no timeout. */ timeout : null, /** * {Function} Function that is executed once the script was loaded. */ __determineSuccess : null, /** * Add an event listener for the given event name. * * @param name {String} The name of the event to listen to. * @param listener {Function} The function to execute when the event is fired * @param ctx {var?} The context of the listener. * @return {qx.bom.request.Script} Self for chaining. */ on : function(name, listener, ctx){ this._emitter.on(name, listener, ctx); return this; }, /** * Initializes (prepares) request. * * @param method {String} * The HTTP method to use. * This parameter exists for compatibility reasons. The script transport * does not support methods other than GET. * @param url {String} * The URL to which to send the request. */ open : function(method, url){ if(this.__disposed){ return; }; // Reset XHR properties that may have been set by previous request this.__initXhrProperties(); this.__abort = null; this.__url = url; if(this.__environmentGet("qx.debug.io")){ qx.Bootstrap.debug(qx.bom.request.Script, "Open native request with " + "url: " + url); }; this._readyStateChange(1); }, /** * Appends a query parameter to URL. * * This method exists for compatibility reasons. The script transport * does not support request headers. However, many services parse query * parameters like request headers. * * Note: The request must be initialized before using this method. * * @param key {String} * The name of the header whose value is to be set. * @param value {String} * The value to set as the body of the header. * @return {qx.bom.request.Script} Self for chaining. */ setRequestHeader : function(key, value){ if(this.__disposed){ return null; }; var param = { }; if(this.readyState !== 1){ throw new Error("Invalid state"); }; param[key] = value; this.__url = qx.util.Uri.appendParamsToUrl(this.__url, param); return this; }, /** * Sends request. * @return {qx.bom.request.Script} Self for chaining. */ send : function(){ if(this.__disposed){ return null; }; var script = this.__createScriptElement(),head = this.__headElement,that = this; if(this.timeout > 0){ this.__timeoutId = window.setTimeout(this.__onTimeoutBound, this.timeout); }; if(this.__environmentGet("qx.debug.io")){ qx.Bootstrap.debug(qx.bom.request.Script, "Send native request"); }; // Attach script to DOM head.insertBefore(script, head.firstChild); // The resource is loaded once the script is in DOM. // Assume HEADERS_RECEIVED and LOADING and dispatch async. window.setTimeout(function(){ that._readyStateChange(2); that._readyStateChange(3); }); return this; }, /** * Aborts request. * @return {qx.bom.request.Script} Self for chaining. */ abort : function(){ if(this.__disposed){ return null; }; this.__abort = true; this.__disposeScriptElement(); this._emit("abort"); return this; }, /** * Helper to emit events and call the callback methods. * @param event {String} The name of the event. */ _emit : function(event){ this["on" + event](); this._emitter.emit(event, this); }, /** * Event handler for an event that fires at every state change. * * Replace with custom method to get informed about the communication progress. */ onreadystatechange : function(){ }, /** * Event handler for XHR event "load" that is fired on successful retrieval. * * Note: This handler is called even when an invalid script is returned. * * Warning: Internet Explorer < 9 receives a false "load" for invalid URLs. * This "load" is fired about 2 seconds after sending the request. To * distinguish from a real "load", consider defining a custom check * function using {@link #setDetermineSuccess} and query the status * property. However, the script loaded needs to have a known impact on * the global namespace. If this does not work for you, you may be able * to set a timeout lower than 2 seconds, depending on script size, * complexity and execution time. * * Replace with custom method to listen to the "load" event. */ onload : function(){ }, /** * Event handler for XHR event "loadend" that is fired on retrieval. * * Note: This handler is called even when a network error (or similar) * occurred. * * Replace with custom method to listen to the "loadend" event. */ onloadend : function(){ }, /** * Event handler for XHR event "error" that is fired on a network error. * * Note: Some browsers do not support the "error" event. * * Replace with custom method to listen to the "error" event. */ onerror : function(){ }, /** * Event handler for XHR event "abort" that is fired when request * is aborted. * * Replace with custom method to listen to the "abort" event. */ onabort : function(){ }, /** * Event handler for XHR event "timeout" that is fired when timeout * interval has passed. * * Replace with custom method to listen to the "timeout" event. */ ontimeout : function(){ }, /** * Get a single response header from response. * * Note: This method exists for compatibility reasons. The script * transport does not receive response headers. * * @param key {String} * Key of the header to get the value from. * @return {String|null} Warning message or <code>null</code> if the request * is disposed */ getResponseHeader : function(key){ if(this.__disposed){ return null; }; if(this.__environmentGet("qx.debug")){ qx.Bootstrap.debug("Response header cannot be determined for " + "requests made with script transport."); }; return "unknown"; }, /** * Get all response headers from response. * * Note: This method exists for compatibility reasons. The script * transport does not receive response headers. * @return {String|null} Warning message or <code>null</code> if the request * is disposed */ getAllResponseHeaders : function(){ if(this.__disposed){ return null; }; if(this.__environmentGet("qx.debug")){ qx.Bootstrap.debug("Response headers cannot be determined for" + "requests made with script transport."); }; return "Unknown response headers"; }, /** * Determine if loaded script has expected impact on global namespace. * * The function is called once the script was loaded and must return a * boolean indicating if the response is to be considered successful. * * @param check {Function} Function executed once the script was loaded. * */ setDetermineSuccess : function(check){ this.__determineSuccess = check; }, /** * Dispose object. */ dispose : function(){ var script = this.__scriptElement; if(!this.__disposed){ // Prevent memory leaks if(script){ script.onload = script.onreadystatechange = null; this.__disposeScriptElement(); }; if(this.__timeoutId){ window.clearTimeout(this.__timeoutId); }; this.__disposed = true; }; }, /* --------------------------------------------------------------------------- PROTECTED --------------------------------------------------------------------------- */ /** * Get URL of request. * * @return {String} URL of request. */ _getUrl : function(){ return this.__url; }, /** * Get script element used for request. * * @return {Element} Script element. */ _getScriptElement : function(){ return this.__scriptElement; }, /** * Handle timeout. */ _onTimeout : function(){ this.__failure(); if(!this.__supportsErrorHandler()){ this._emit("error"); }; this._emit("timeout"); if(!this.__supportsErrorHandler()){ this._emit("loadend"); }; }, /** * Handle native load. */ _onNativeLoad : function(){ var script = this.__scriptElement,determineSuccess = this.__determineSuccess,that = this; // Aborted request must not fire load if(this.__abort){ return; }; // BUGFIX: IE < 9 // When handling "readystatechange" event, skip if readyState // does not signal loaded script if(this.__environmentGet("engine.name") === "mshtml" && this.__environmentGet("browser.documentmode") < 9){ if(!(/loaded|complete/).test(script.readyState)){ return; } else { if(this.__environmentGet("qx.debug.io")){ qx.Bootstrap.debug(qx.bom.request.Script, "Received native readyState: loaded"); }; }; }; if(this.__environmentGet("qx.debug.io")){ qx.Bootstrap.debug(qx.bom.request.Script, "Received native load"); }; // Determine status by calling user-provided check function if(determineSuccess){ // Status set before has higher precedence if(!this.status){ this.status = determineSuccess() ? 200 : 500; }; }; if(this.status === 500){ if(this.__environmentGet("qx.debug.io")){ qx.Bootstrap.debug(qx.bom.request.Script, "Detected error"); }; }; if(this.__timeoutId){ window.clearTimeout(this.__timeoutId); }; window.setTimeout(function(){ that._success(); that._readyStateChange(4); that._emit("load"); that._emit("loadend"); }); }, /** * Handle native error. */ _onNativeError : function(){ this.__failure(); this._emit("error"); this._emit("loadend"); }, /* --------------------------------------------------------------------------- PRIVATE --------------------------------------------------------------------------- */ /** * {Element} Script element */ __scriptElement : null, /** * {Element} Head element */ __headElement : null, /** * {String} URL */ __url : "", /** * {Function} Bound _onNativeLoad handler. */ __onNativeLoadBound : null, /** * {Function} Bound _onNativeError handler. */ __onNativeErrorBound : null, /** * {Function} Bound _onTimeout handler. */ __onTimeoutBound : null, /** * {Number} Timeout timer iD. */ __timeoutId : null, /** * {Boolean} Whether request was aborted. */ __abort : null, /** * {Boolean} Whether request was disposed. */ __disposed : null, /* --------------------------------------------------------------------------- HELPER --------------------------------------------------------------------------- */ /** * Initialize properties. */ __initXhrProperties : function(){ this.readyState = 0; this.status = 0; this.statusText = ""; }, /** * Change readyState. * * @param readyState {Number} The desired readyState */ _readyStateChange : function(readyState){ this.readyState = readyState; this._emit("readystatechange"); }, /** * Handle success. */ _success : function(){ this.__disposeScriptElement(); this.readyState = 4; // By default, load is considered successful if(!this.status){ this.status = 200; }; this.statusText = "" + this.status; }, /** * Handle failure. */ __failure : function(){ this.__disposeScriptElement(); this.readyState = 4; this.status = 0; this.statusText = null; }, /** * Looks up whether browser supports error handler. * * @return {Boolean} Whether browser supports error handler. */ __supportsErrorHandler : function(){ var isLegacyIe = this.__environmentGet("engine.name") === "mshtml" && this.__environmentGet("browser.documentmode") < 9; var isOpera = this.__environmentGet("engine.name") === "opera"; return !(isLegacyIe || isOpera); }, /** * Create and configure script element. * * @return {Element} Configured script element. */ __createScriptElement : function(){ var script = this.__scriptElement = document.createElement("script"); script.src = this.__url; script.onerror = this.__onNativeErrorBound; script.onload = this.__onNativeLoadBound; // BUGFIX: IE < 9 // Legacy IEs do not fire the "load" event for script elements. // Instead, they support the "readystatechange" event if(this.__environmentGet("engine.name") === "mshtml" && this.__environmentGet("browser.documentmode") < 9){ script.onreadystatechange = this.__onNativeLoadBound; }; return script; }, /** * Remove script element from DOM. */ __disposeScriptElement : function(){ var script = this.__scriptElement; if(script && script.parentNode){ this.__headElement.removeChild(script); }; }, /** * Proxy Environment.get to guard against env not being present yet. * * @param key {String} Environment key. * @return {var} Value of the queried environment key * @lint environmentNonLiteralKey(key) */ __environmentGet : function(key){ if(qx && qx.core && qx.core.Environment){ return qx.core.Environment.get(key); } else { if(key === "engine.name"){ return qx.bom.client.Engine.getName(); }; if(key === "browser.documentmode"){ return qx.bom.client.Browser.getDocumentMode(); }; if(key == "qx.debug.io"){ return false; }; throw new Error("Unknown environment key at this phase"); }; } }, defer : function(){ if(qx && qx.core && qx.core.Environment){ qx.core.Environment.add("qx.debug.io", false); }; } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2011 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Tristan Koch (tristankoch) ************************************************************************ */ /* ************************************************************************ #require(qx.bom.request.Script#open) #require(qx.bom.request.Script#on) #require(qx.bom.request.Script#onreadystatechange) #require(qx.bom.request.Script#onload) #require(qx.bom.request.Script#onloadend) #require(qx.bom.request.Script#onerror) #require(qx.bom.request.Script#onabort) #require(qx.bom.request.Script#ontimeout) #require(qx.bom.request.Script#send) ************************************************************************ */ /** * A special script loader handling JSONP responses. Automatically * provides callbacks and populates responseJson property. * * Example: * * <pre class="javascript"> * var req = new qx.bom.request.Jsonp(); * * // Some services have a fixed callback name * // req.setCallbackName("callback"); * * req.onload = function() { * // Handle data received * req.responseJson; * } * * req.open("GET", url); * req.send(); * </pre> */ qx.Bootstrap.define("qx.bom.request.Jsonp", { extend : qx.bom.request.Script, construct : function(){ // Borrow super-class constructor qx.bom.request.Script.apply(this); this.__generateId(); }, members : { /** * {Object} Parsed JSON response. */ responseJson : null, /** * {Number} Identifier of this instance. */ __id : null, /** * {String} Callback parameter. */ __callbackParam : null, /** * {String} Callback name. */ __callbackName : null, /** * {Boolean} Whether callback was called. */ __callbackCalled : null, /** * {Boolean} Whether a custom callback was created automatically. */ __customCallbackCreated : null, /** * {String} The generated URL for the current request */ __generatedUrl : null, /** * {Boolean} Whether request was disposed. */ __disposed : null, /** Prefix used for the internal callback name. */ __prefix : "", /** * Initializes (prepares) request. * * @param method {String} * The HTTP method to use. * This parameter exists for compatibility reasons. The script transport * does not support methods other than GET. * @param url {String} * The URL to which to send the request. */ open : function(method, url){ if(this.__disposed){ return; }; var query = { },callbackParam,callbackName,that = this; // Reset properties that may have been set by previous request this.responseJson = null; this.__callbackCalled = false; callbackParam = this.__callbackParam || "callback"; callbackName = this.__callbackName || this.__prefix + "qx.bom.request.Jsonp." + this.__id + ".callback"; // Default callback if(!this.__callbackName){ // Store globally available reference to this object this.constructor[this.__id] = this; } else { // Dynamically create globally available callback (if it does not // exist yet) with user defined name. Delegate to this object’s // callback method. if(!window[this.__callbackName]){ this.__customCallbackCreated = true; window[this.__callbackName] = function(data){ that.callback(data); }; } else { { }; }; }; { }; query[callbackParam] = callbackName; this.__generatedUrl = url = qx.util.Uri.appendParamsToUrl(url, query); this.__callBase("open", [method, url]); }, /** * Callback provided for JSONP response to pass data. * * Called internally to populate responseJson property * and indicate successful status. * * Note: If you write a custom callback you’ll need to call * this method in order to notify the request about the data * loaded. Writing a custom callback should not be necessary * in most cases. * * @param data {Object} JSON */ callback : function(data){ if(this.__disposed){ return; }; // Signal callback was called this.__callbackCalled = true; { }; // Set response this.responseJson = data; // Delete global reference to this this.constructor[this.__id] = undefined; this.__deleteCustomCallback(); }, /** * Set callback parameter. * * Some JSONP services expect the callback name to be passed labeled with a * special URL parameter key, e.g. "jsonp" in "?jsonp=myCallback". The * default is "callback". * * @param param {String} Name of the callback parameter. * @return {qx.bom.request.Jsonp} Self reference for chaining. */ setCallbackParam : function(param){ this.__callbackParam = param; return this; }, /** * Set callback name. * * Must be set to the name of the callback function that is called by the * script returned from the JSONP service. By default, the callback name * references this instance’s {@link #callback} method, allowing to connect * multiple JSONP responses to different requests. * * If the JSONP service allows to set custom callback names, it should not * be necessary to change the default. However, some services use a fixed * callback name. This is when setting the callbackName is useful. A * function is created and made available globally under the given name. * The function receives the JSON data and dispatches it to this instance’s * {@link #callback} method. Please note that this function is only created * if it does not exist before. * * @param name {String} Name of the callback function. * @return {qx.bom.request.Jsonp} Self reference for chaining. */ setCallbackName : function(name){ this.__callbackName = name; return this; }, /** * Set the prefix used in front of 'qx.' in case 'qx' is not available * (for qx.Website e.g.) * @internal * @param prefix {String} The prefix to put in front of 'qx' */ setPrefix : function(prefix){ this.__prefix = prefix; }, /** * Returns the generated URL for the current / last request * * @internal * @return {String} The current generated URL for the request */ getGeneratedUrl : function(){ return this.__generatedUrl; }, dispose : function(){ // In case callback was not called this.__deleteCustomCallback(); this.__callBase("dispose"); }, /** * Handle native load. */ _onNativeLoad : function(){ // Indicate erroneous status (500) if callback was not called. // // Why 500? 5xx belongs to the range of server errors. If the callback was // not called, it is assumed the server failed to provide an appropriate // response. Since the exact reason of the error is unknown, the most // generic message ("500 Internal Server Error") is chosen. this.status = this.__callbackCalled ? 200 : 500; this.__callBase("_onNativeLoad"); }, /** * Delete custom callback if dynamically created before. */ __deleteCustomCallback : function(){ if(this.__customCallbackCreated && window[this.__callbackName]){ window[this.__callbackName] = undefined; this.__customCallbackCreated = false; }; }, /** * Call overriden method. * * @param method {String} Name of the overriden method. * @param args {Array} Arguments. */ __callBase : function(method, args){ qx.bom.request.Script.prototype[method].apply(this, args || []); }, /** * Generate ID. */ __generateId : function(){ // Add random digits to date to allow immediately following requests // that may be send at the same time this.__id = "qx" + (new Date().valueOf()) + ("" + Math.random()).substring(2, 5); } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Daniel Wagner (danielwagner) ************************************************************************ */ /* ************************************************************************ #require(qx.module.Environment) #require(qx.module.Manipulating) #require(qx.module.Traversing) #require(qx.module.Css) #require(qx.module.Attribute) ************************************************************************ */ /** * Provides a way to block elements so they will no longer receive (native) * events by overlaying them with a div. * For Internet Explorer, an additional Iframe element will be overlayed since * native form controls cannot be blocked otherwise. * * The blocker can also be applied to the entire document, e.g.: * * <pre class="javascript"> * q(document).block(); * </pre> */ qxWeb.define("qx.module.Blocker", { statics : { /** * Attaches a blocker div (and additionally a blocker Iframe for IE) to the * given element. * * @param item {Element|Document} The element to be overlaid with the blocker * @param color {String} The color for the blocker element (any CSS color value) * @param opacity {Number} The CSS opacity value for the blocker * @param zIndex {Number} The zIndex value for the blocker */ __attachBlocker : function(item, color, opacity, zIndex){ var win = qxWeb.getWindow(item); var isDocument = qxWeb.isDocument(item); if(!item.__blocker){ item.__blocker = { div : qxWeb.create("<div/>") }; if((qxWeb.env.get("engine.name") == "mshtml")){ item.__blocker.iframe = qx.module.Blocker.__getIframeElement(win); }; }; qx.module.Blocker.__styleBlocker(item, color, opacity, zIndex, isDocument); item.__blocker.div.appendTo(win.document.body); if(item.__blocker.iframe){ item.__blocker.iframe.appendTo(win.document.body); }; if(isDocument){ qxWeb(win).on("resize", qx.module.Blocker.__onWindowResize); }; }, /** * Styles the blocker element(s) * * @param item {Element|Document} The element to be overlaid with the blocker * @param color {String} The color for the blocker element (any CSS color value) * @param opacity {Number} The CSS opacity value for the blocker * @param zIndex {Number} The zIndex value for the blocker * @param isDocument {Boolean} Whether the item is a document node */ __styleBlocker : function(item, color, opacity, zIndex, isDocument){ var qItem = qxWeb(item); var styles = { "zIndex" : zIndex, "display" : "block", "position" : "absolute", "backgroundColor" : color, "opacity" : opacity, "width" : qItem.getWidth() + "px", "height" : qItem.getHeight() + "px" }; if(isDocument){ styles.top = 0 + "px"; styles.left = 0 + "px"; } else { var pos = qItem.getOffset(); styles.top = pos.top + "px"; styles.left = pos.left + "px"; }; item.__blocker.div.setStyles(styles); if(item.__blocker.iframe){ styles.zIndex = styles.zIndex - 1; styles.backgroundColor = "transparent"; styles.opacity = 0; item.__blocker.iframe.setStyles(styles); }; }, /** * Creates an iframe element used as a blocker in IE * * @param win {Window} The parent window of the item to be blocked * @return {Element} Iframe blocker */ __getIframeElement : function(win){ var iframe = qxWeb.create('<iframe></iframe>'); iframe.setAttributes({ frameBorder : 0, frameSpacing : 0, marginWidth : 0, marginHeight : 0, hspace : 0, vspace : 0, border : 0, allowTransparency : false, src : "javascript:false" }); return iframe; }, /** * Callback for the Window's resize event. Applies the window's new sizes * to the blocker element(s). * * @param ev {Event} resize event */ __onWindowResize : function(ev){ var win = this[0]; var size = { width : this.getWidth() + "px", height : this.getHeight() + "px" }; qxWeb(win.document.__blocker.div).setStyles(size); if(win.document.__blocker.iframe){ qxWeb(win.document.__blocker.iframe).setStyles(size); }; }, /** * Removes the given item's blocker element(s) from the DOM * * @param item {Element} Blocked element * @param index {Number} index of the item in the collection */ __detachBlocker : function(item, index){ if(!item.__blocker){ return; }; item.__blocker.div.remove(); if(item.__blocker.iframe){ item.__blocker.iframe.remove(); }; if(qxWeb.isDocument(item)){ qxWeb(qxWeb.getWindow(item)).off("resize", qx.module.Blocker.__onWindowResize); }; }, /** * Adds an overlay to all items in the collection that intercepts mouse * events. * * @attach {qxWeb} * @param color {String ? transparent} The color for the blocker element (any CSS color value) * @param opacity {Float ? 0} The CSS opacity value for the blocker * @param zIndex {Number ? 10000} The zIndex value for the blocker * @return {qxWeb} The collection for chaining */ block : function(color, opacity, zIndex){ if(!this[0]){ return this; }; color = color || "transparent"; opacity = opacity || 0; zIndex = zIndex || 10000; this.forEach(function(item, index){ qx.module.Blocker.__attachBlocker(item, color, opacity, zIndex); }); return this; }, /** * Removes the blockers from all items in the collection * * @attach {qxWeb} * @return {qxWeb} The collection for chaining */ unblock : function(){ if(!this[0]){ return this; }; this.forEach(qx.module.Blocker.__detachBlocker); return this; } }, defer : function(statics){ qxWeb.$attach({ "block" : statics.block, "unblock" : statics.unblock }); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /* ************************************************************************ #require(qx.module.Css) #require(qx.module.Event) ************************************************************************ */ /** * Cross browser animation layer. It uses feature detection to check if CSS * animations are available and ready to use. If not, a JavaScript-based * fallback will be used. */ qx.Bootstrap.define("qx.module.Animation", { events : { /** Fired when an animation starts. */ "animationStart" : undefined, /** Fired when an animation has ended one iteration. */ "animationIteration" : undefined, /** Fired when an animation has ended. */ "animationEnd" : undefined }, statics : { /** * Returns the stored animation handles. The handles are only * available while an animation is running. * * @internal * @return {Array} An array of animation handles. */ getAnimationHandles : function(){ var animationHandles = []; for(var i = 0;i < this.length;i++){ animationHandles[i] = this[i].$$animation; }; return animationHandles; }, /** * Animation description used in {@link #fadeOut}. */ _fadeOut : { duration : 700, timing : "ease-out", keep : 100, keyFrames : { '0' : { opacity : 1 }, '100' : { opacity : 0, display : "none" } } }, /** * Animation description used in {@link #fadeIn}. */ _fadeIn : { duration : 700, timing : "ease-in", keep : 100, keyFrames : { '0' : { opacity : 0 }, '100' : { opacity : 1 } } }, /** * Starts the animation with the given description. * The description should be a map, which could look like this: * * <pre class="javascript"> * { * "duration": 1000, * "keep": 100, * "keyFrames": { * 0 : {"opacity": 1, "scale": 1}, * 100 : {"opacity": 0, "scale": 0} * }, * "origin": "50% 50%", * "repeat": 1, * "timing": "ease-out", * "alternate": false, * "delay": 2000 * } * </pre> * * *duration* is the time in milliseconds one animation cycle should take. * * *keep* is the key frame to apply at the end of the animation. (optional) * * *keyFrames* is a map of separate frames. Each frame is defined by a * number which is the percentage value of time in the animation. The value * is a map itself which holds css properties or transforms * (Transforms only for CSS Animations). * * *origin* maps to the transform origin {@link qx.bom.element.Transform#setOrigin} * (Only for CSS animations). * * *repeat* is the amount of time the animation should be run in * sequence. You can also use "infinite". * * *timing* takes one of these predefined values: * <code>ease</code> | <code>linear</code> | <code>ease-in</code> * | <code>ease-out</code> | <code>ease-in-out</code> | * <code>cubic-bezier(&lt;number&gt;, &lt;number&gt;, &lt;number&gt;, &lt;number&gt;)</code> * (cubic-bezier only available for CSS animations) * * *alternate* defines if every other animation should be run in reverse order. * * *delay* is the time in milliseconds the animation should wait before start. * * @attach {qxWeb} * @param desc {Map} The animation's description. * @param duration {Number?} The duration in milliseconds of the animation, * which will override the duration given in the description. * @return {qxWeb} The collection for chaining. */ animate : function(desc, duration){ qx.module.Animation._animate.bind(this)(desc, duration, false); return this; }, /** * Starts an animation in reversed order. For further details, take a look at * the {@link #animate} method. * @attach {qxWeb} * @param desc {Map} The animation's description. * @param duration {Number?} The duration in milliseconds of the animation, * which will override the duration given in the description. * @return {qxWeb} The collection for chaining. */ animateReverse : function(desc, duration){ qx.module.Animation._animate.bind(this)(desc, duration, true); return this; }, /** * Animation execute either regular or reversed direction. * @param desc {Map} The animation's description. * @param duration {Number?} The duration in milliseconds of the animation, * which will override the duration given in the description. * @param reverse {Boolean} <code>true</code>, if the animation should be reversed */ _animate : function(desc, duration, reverse){ for(var i = 0;i < this.length;i++){ var el = this[i]; // stop all running animations if(el.$$animation){ el.$$animation.stop(); }; if(reverse){ var handle = qx.bom.element.Animation.animateReverse(el, desc, duration); } else { var handle = qx.bom.element.Animation.animate(el, desc, duration); }; var self = this; // only register for the first element if(i == 0){ handle.on("start", function(){ self.emit("animationStart"); }, handle); handle.on("iteration", function(){ self.emit("animationIteration"); }, handle); }; handle.on("end", function(){ for(var i = 0;i < self.length;i++){ if(self[i].$$animation){ return; }; }; self.emit("animationEnd"); }, el); }; }, /** * Manipulates the play state of the animation. * This can be used to continue an animation when paused. * @attach {qxWeb} * @return {qxWeb} The collection for chaining. */ play : function(){ for(var i = 0;i < this.length;i++){ var handle = this[i].$$animation; if(handle){ handle.play(); }; }; return this; }, /** * Manipulates the play state of the animation. * This can be used to pause an animation when running. * @attach {qxWeb} * @return {qxWeb} The collection for chaining. */ pause : function(){ for(var i = 0;i < this.length;i++){ var handle = this[i].$$animation; if(handle){ handle.pause(); }; }; return this; }, /** * Stops a running animation. * @attach {qxWeb} * @return {qxWeb} The collection for chaining. */ stop : function(){ for(var i = 0;i < this.length;i++){ var handle = this[i].$$animation; if(handle){ handle.stop(); }; }; return this; }, /** * Returns whether an animation is running or not. * @attach {qxWeb} * @return {Boolean} <code>true</code>, if an animation is running. */ isPlaying : function(){ for(var i = 0;i < this.length;i++){ var handle = this[i].$$animation; if(handle && handle.isPlaying()){ return true; }; }; return false; }, /** * Returns whether an animation has ended or not. * @attach {qxWeb} * @return {Boolean} <code>true</code>, if an animation has ended. */ isEnded : function(){ for(var i = 0;i < this.length;i++){ var handle = this[i].$$animation; if(handle && !handle.isEnded()){ return false; }; }; return true; }, /** * Fades in all elements in the collection. * @attach {qxWeb} * @param duration {Number?} The duration in milliseconds. * @return {qxWeb} The collection for chaining. */ fadeIn : function(duration){ // remove 'display: none' style this.setStyle("display", ""); return this.animate(qx.module.Animation._fadeIn, duration); }, /** * Fades out all elements in the collection. * @attach {qxWeb} * @param duration {Number?} The duration in milliseconds. * @return {qxWeb} The collection for chaining. */ fadeOut : function(duration){ return this.animate(qx.module.Animation._fadeOut, duration); } }, defer : function(statics){ qxWeb.$attach({ "animate" : statics.animate, "animateReverse" : statics.animateReverse, "fadeIn" : statics.fadeIn, "fadeOut" : statics.fadeOut, "play" : statics.play, "pause" : statics.pause, "stop" : statics.stop, "isEnded" : statics.isEnded, "isPlaying" : statics.isPlaying, "getAnimationHandles" : statics.getAnimationHandles }); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * Wrapper for {@link qx.bom.element.AnimationCss} and * {@link qx.bom.element.AnimationJs}. It offers the pubilc API and decides using * feature checks either to use CSS animations or JS animations. * * If you use this class, the restrictions of the JavaScript animations apply. * This means that you can not use transforms and custom bezier timing functions. */ qx.Bootstrap.define("qx.bom.element.Animation", { statics : { /** * This function takes care of the feature check and starts the animation. * It takes a DOM element to apply the animation to, and a description. * The description should be a map, which could look like this: * * <pre class="javascript"> * { * "duration": 1000, * "keep": 100, * "keyFrames": { * 0 : {"opacity": 1, "scale": 1}, * 100 : {"opacity": 0, "scale": 0} * }, * "origin": "50% 50%", * "repeat": 1, * "timing": "ease-out", * "alternate": false, * "delay" : 2000 * } * </pre> * * *duration* is the time in milliseconds one animation cycle should take. * * *keep* is the key frame to apply at the end of the animation. (optional) * Keep in mind that the keep key is reversed in case you use an reverse * animation or set the alternate key and a even repeat count. * * *keyFrames* is a map of separate frames. Each frame is defined by a * number which is the percentage value of time in the animation. The value * is a map itself which holds css properties or transforms * {@link qx.bom.element.Transform} (Transforms only for CSS Animations). * * *origin* maps to the transform origin {@link qx.bom.element.Transform#setOrigin} * (Only for CSS animations). * * *repeat* is the amount of time the animation should be run in * sequence. You can also use "infinite". * * *timing* takes one of the predefined value: * <code>ease</code> | <code>linear</code> | <code>ease-in</code> * | <code>ease-out</code> | <code>ease-in-out</code> | * <code>cubic-bezier(&lt;number&gt;, &lt;number&gt;, &lt;number&gt;, &lt;number&gt;)</code> * (cubic-bezier only available for CSS animations) * * *alternate* defines if every other animation should be run in reverse order. * * *delay* is the time in milliseconds the animation should wait before start. * * @param el {Element} The element to animate. * @param desc {Map} The animations description. * @param duration {Integer?} The duration in milliseconds of the animation * which will override the duration given in the description. * @return {qx.bom.element.AnimationHandle} AnimationHandle instance to control * the animation. */ animate : function(el, desc, duration){ var onlyCssKeys = qx.bom.element.Animation.__hasOnlyCssKeys(el, desc.keyFrames); if(qx.core.Environment.get("css.animation") && onlyCssKeys){ return qx.bom.element.AnimationCss.animate(el, desc, duration); } else { return qx.bom.element.AnimationJs.animate(el, desc, duration); }; }, /** * Starts an animation in reversed order. For further details, take a look at * the {@link #animate} method. * @param el {Element} The element to animate. * @param desc {Map} The animations description. * @param duration {Integer?} The duration in milliseconds of the animation * which will override the duration given in the description. * @return {qx.bom.element.AnimationHandle} AnimationHandle instance to control * the animation. */ animateReverse : function(el, desc, duration){ var onlyCssKeys = qx.bom.element.Animation.__hasOnlyCssKeys(el, desc.keyFrames); if(qx.core.Environment.get("css.animation") && onlyCssKeys){ return qx.bom.element.AnimationCss.animateReverse(el, desc, duration); } else { return qx.bom.element.AnimationJs.animateReverse(el, desc, duration); }; }, /** * Detection helper which detects if only CSS keys are in * the animations key frames. * @param el {Element} The element to check for the styles. * @param keyFrames {Map} The keyFrames of the animation. * @return {Boolean} <code>true</code> if only css properties are included. */ __hasOnlyCssKeys : function(el, keyFrames){ var keys = []; for(var nr in keyFrames){ var frame = keyFrames[nr]; for(var key in frame){ if(keys.indexOf(key) == -1){ keys.push(key); }; }; }; var transformKeys = ["scale", "rotate", "skew", "translate"]; for(var i = 0;i < keys.length;i++){ var key = qx.lang.String.camelCase(keys[i]); if(!(key in el.style)){ // check for transform keys if(transformKeys.indexOf(keys[i]) != -1){ continue; }; return false; }; }; return true; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2011 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /* ************************************************************************ #require(qx.bom.Stylesheet) ************************************************************************ */ /** * Responsible for checking all relevant animation properties. * * Spec: http://www.w3.org/TR/css3-animations/ * * @internal */ qx.Bootstrap.define("qx.bom.client.CssAnimation", { statics : { /** * Main check method which returns an object if CSS animations are * supported. This object contains all necessary keys to work with CSS * animations. * <ul> * <li><code>name</code> The name of the css animation style</li> * <li><code>play-state</code> The name of the play-state style</li> * <li><code>start-event</code> The name of the start event</li> * <li><code>iternation-event</code> The name of the iternation event</li> * <li><code>end-event</code> The name of the end event</li> * <li><code>fill-mode</code> The fill-mode style</li> * <li><code>keyframes</code> The name of the keyframes selector.</li> * </ul> * * @internal * @return {Object|null} The described object or null, if animations are * not supported. */ getSupport : function(){ var name = qx.bom.client.CssAnimation.getName(); if(name != null){ return { "name" : name, "play-state" : qx.bom.client.CssAnimation.getPlayState(), "start-event" : qx.bom.client.CssAnimation.getAnimationStart(), "iteration-event" : qx.bom.client.CssAnimation.getAnimationIteration(), "end-event" : qx.bom.client.CssAnimation.getAnimationEnd(), "fill-mode" : qx.bom.client.CssAnimation.getFillMode(), "keyframes" : qx.bom.client.CssAnimation.getKeyFrames() }; }; return null; }, /** * Checks for the 'animation-fill-mode' CSS style. * @internal * @return {String|null} The name of the style or null, if the style is * not supported. */ getFillMode : function(){ return qx.bom.Style.getPropertyName("AnimationFillMode"); }, /** * Checks for the 'animation-play-state' CSS style. * @internal * @return {String|null} The name of the style or null, if the style is * not supported. */ getPlayState : function(){ return qx.bom.Style.getPropertyName("AnimationPlayState"); }, /** * Checks for the style name used for animations. * @internal * @return {String|null} The name of the style or null, if the style is * not supported. */ getName : function(){ return qx.bom.Style.getPropertyName("animation"); }, /** * Checks for the event name of animation start. * @internal * @return {String} The name of the event. */ getAnimationStart : function(){ var mapping = { "msAnimation" : "MSAnimationStart", "WebkitAnimation" : "webkitAnimationStart", "MozAnimation" : "animationstart", "OAnimation" : "oAnimationStart", "animation" : "animationstart" }; return mapping[this.getName()]; }, /** * Checks for the event name of animation end. * @internal * @return {String} The name of the event. */ getAnimationIteration : function(){ var mapping = { "msAnimation" : "MSAnimationIteration", "WebkitAnimation" : "webkitAnimationIteration", "MozAnimation" : "animationiteration", "OAnimation" : "oAnimationIteration", "animation" : "animationiteration" }; return mapping[this.getName()]; }, /** * Checks for the event name of animation end. * @internal * @return {String} The name of the event. */ getAnimationEnd : function(){ var mapping = { "msAnimation" : "MSAnimationEnd", "WebkitAnimation" : "webkitAnimationEnd", "MozAnimation" : "animationend", "OAnimation" : "oAnimationEnd", "animation" : "animationend" }; return mapping[this.getName()]; }, /** * Checks what selector should be used to add keyframes to stylesheets. * @internal * @return {String|null} The name of the selector or null, if the selector * is not supported. */ getKeyFrames : function(){ var prefixes = qx.bom.Style.VENDOR_PREFIXES; var keyFrames = []; for(var i = 0;i < prefixes.length;i++){ var key = "@" + qx.bom.Style.getCssName(prefixes[i]) + "-keyframes"; keyFrames.push(key); }; keyFrames.unshift("@keyframes"); var sheet = qx.bom.Stylesheet.createElement(); for(var i = 0;i < keyFrames.length;i++){ try{ qx.bom.Stylesheet.addRule(sheet, keyFrames[i] + " name", ""); return keyFrames[i]; } catch(e) { }; }; return null; }, /** * Checks for the requestAnimationFrame method and return the prefixed name. * @internal * @return {String|null} A string the method name or null, if the method * is not supported. */ getRequestAnimationFrame : function(){ var choices = ["requestAnimationFrame", "msRequestAnimationFrame", "webkitRequestAnimationFrame", "mozRequestAnimationFrame", "oRequestAnimationFrame"]; for(var i = 0;i < choices.length;i++){ if(window[choices[i]] != undefined){ return choices[i]; }; }; return null; } }, defer : function(statics){ qx.core.Environment.add("css.animation", statics.getSupport); qx.core.Environment.add("css.animation.requestframe", statics.getRequestAnimationFrame); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2011 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * This class is responsible for applying CSS3 animations to plain DOM elements. * * The implementation is mostly a cross-browser wrapper for applying the * animations, including transforms. If the browser does not support * CSS animations, but you have set a keep frame, the keep frame will be applied * immediately, thus making the animations optional. * * The API aligns closely to the spec wherever possible. * * http://www.w3.org/TR/css3-animations/ * * {@link qx.bom.element.Animation} is the class, which takes care of the * feature detection for CSS animations and decides which implementation * (CSS or JavaScript) should be used. Most likely, this implementation should * be the one to use. */ qx.Bootstrap.define("qx.bom.element.AnimationCss", { statics : { // initialization __sheet : null, __rulePrefix : "Anni", __id : 0, /** Static map of rules */ __rules : { }, /** The used keys for transforms. */ __transitionKeys : { "scale" : true, "rotate" : true, "skew" : true, "translate" : true }, /** Map of cross browser CSS keys. */ __cssAnimationKeys : qx.core.Environment.get("css.animation"), /** * This is the main function to start the animation in reverse mode. * For further details, take a look at the documentation of the wrapper * {@link qx.bom.element.Animation}. * @param el {Element} The element to animate. * @param desc {Map} Animation description. * @param duration {Integer?} The duration of the animation which will * override the duration given in the description. * @return {qx.bom.element.AnimationHandle} The handle. */ animateReverse : function(el, desc, duration){ return this._animate(el, desc, duration, true); }, /** * This is the main function to start the animation. For further details, * take a look at the documentation of the wrapper * {@link qx.bom.element.Animation}. * @param el {Element} The element to animate. * @param desc {Map} Animation description. * @param duration {Integer?} The duration of the animation which will * override the duration given in the description. * @return {qx.bom.element.AnimationHandle} The handle. */ animate : function(el, desc, duration){ return this._animate(el, desc, duration, false); }, /** * Internal method to start an animation either reverse or not. * {@link qx.bom.element.Animation}. * @param el {Element} The element to animate. * @param desc {Map} Animation description. * @param duration {Integer?} The duration of the animation which will * override the duration given in the description. * @param reverse {Boolean} <code>true</code>, if the animation should be * reversed. * @return {qx.bom.element.AnimationHandle} The handle. */ _animate : function(el, desc, duration, reverse){ this.__normalizeDesc(desc); { }; // reverse the keep property if the animation is reverse as well var keep = desc.keep; if(keep != null && (reverse || (desc.alternate && desc.repeat % 2 == 0))){ keep = 100 - keep; }; if(!this.__sheet){ this.__sheet = qx.bom.Stylesheet.createElement(); }; var keyFrames = desc.keyFrames; if(duration == undefined){ duration = desc.duration; }; // if animations are supported if(this.__cssAnimationKeys != null){ var name = this.__addKeyFrames(keyFrames, reverse); var style = name + " " + duration + "ms " + desc.repeat + " " + desc.timing + " " + (desc.delay ? desc.delay + "ms " : "") + (desc.alternate ? "alternate" : ""); qx.bom.Event.addNativeListener(el, this.__cssAnimationKeys["start-event"], this.__onAnimationStart); qx.bom.Event.addNativeListener(el, this.__cssAnimationKeys["iteration-event"], this.__onAnimationIteration); qx.bom.Event.addNativeListener(el, this.__cssAnimationKeys["end-event"], this.__onAnimationEnd); el.style[qx.lang.String.camelCase(this.__cssAnimationKeys["name"])] = style; // use the fill mode property if available and suitable if(keep && keep == 100 && this.__cssAnimationKeys["fill-mode"]){ el.style[this.__cssAnimationKeys["fill-mode"]] = "forwards"; }; }; var animation = new qx.bom.element.AnimationHandle(); animation.desc = desc; animation.el = el; animation.keep = keep; el.$$animation = animation; // additional transform keys if(desc.origin != null){ qx.bom.element.Transform.setOrigin(el, desc.origin); }; // fallback for browsers not supporting animations if(this.__cssAnimationKeys == null){ window.setTimeout(function(){ qx.bom.element.AnimationCss.__onAnimationEnd({ target : el }); }, 0); }; return animation; }, /** * Handler for the animation start. * @param e {Event} The native event from the browser. */ __onAnimationStart : function(e){ e.target.$$animation.emit("start", e.target); }, /** * Handler for the animation iteration. * @param e {Event} The native event from the browser. */ __onAnimationIteration : function(e){ // It could happen that an animation end event is fired before an // animation iteration appears [BUG #6928] if(e.target != null && e.target.$$animation != null){ e.target.$$animation.emit("iteration", e.target); }; }, /** * Handler for the animation end. * @param e {Event} The native event from the browser. */ __onAnimationEnd : function(e){ var el = e.target; var animation = el.$$animation; // ignore events when already cleaned up if(!animation){ return; }; var desc = animation.desc; if(qx.bom.element.AnimationCss.__cssAnimationKeys != null){ // reset the styling var key = qx.lang.String.camelCase(qx.bom.element.AnimationCss.__cssAnimationKeys["name"]); el.style[key] = ""; qx.bom.Event.removeNativeListener(el, qx.bom.element.AnimationCss.__cssAnimationKeys["name"], qx.bom.element.AnimationCss.__onAnimationEnd); }; if(desc.origin != null){ qx.bom.element.Transform.setOrigin(el, ""); }; qx.bom.element.AnimationCss.__keepFrame(el, desc.keyFrames[animation.keep]); el.$$animation = null; animation.el = null; animation.ended = true; animation.emit("end", el); }, /** * Helper method which takes an element and a key frame description and * applies the properties defined in the given frame to the element. This * method is used to keep the state of the animation. * @param el {Element} The element to apply the frame to. * @param endFrame {Map} The description of the end frame, which is basically * a map containing CSS properties and values including transforms. */ __keepFrame : function(el, endFrame){ // keep the element at this animation step var transforms; for(var style in endFrame){ if(style in qx.bom.element.AnimationCss.__transitionKeys){ if(!transforms){ transforms = { }; }; transforms[style] = endFrame[style]; } else { el.style[qx.lang.String.camelCase(style)] = endFrame[style]; }; }; // transform keeping if(transforms){ qx.bom.element.Transform.transform(el, transforms); }; }, /** * Preprocessing of the description to make sure every necessary key is * set to its default. * @param desc {Map} The description of the animation. */ __normalizeDesc : function(desc){ if(!desc.hasOwnProperty("alternate")){ desc.alternate = false; }; if(!desc.hasOwnProperty("keep")){ desc.keep = null; }; if(!desc.hasOwnProperty("repeat")){ desc.repeat = 1; }; if(!desc.hasOwnProperty("timing")){ desc.timing = "linear"; }; if(!desc.hasOwnProperty("origin")){ desc.origin = null; }; }, /** * Debugging helper to validate the description. * @signature function(desc) * @param desc {Map} The description of the animation. */ __validateDesc : null, /** * Helper to add the given frames to an internal CSS stylesheet. It parses * the description and adds the key frames to the sheet. * @param frames {Map} A map of key frames that describe the animation. * @param reverse {Boolean} <code>true</code>, if the key frames should * be added in reverse order. * @return {String} The generated name of the keyframes rule. */ __addKeyFrames : function(frames, reverse){ var rule = ""; // for each key frame for(var position in frames){ rule += (reverse ? -(position - 100) : position) + "% {"; var frame = frames[position]; var transforms; // each style for(var style in frame){ if(style in this.__transitionKeys){ if(!transforms){ transforms = { }; }; transforms[style] = frame[style]; } else { rule += style + ":" + frame[style] + ";"; }; }; // transform handling if(transforms){ rule += qx.bom.element.Transform.getCss(transforms); }; rule += "} "; }; // cached shorthand if(this.__rules[rule]){ return this.__rules[rule]; }; var name = this.__rulePrefix + this.__id++; var selector = this.__cssAnimationKeys["keyframes"] + " " + name; qx.bom.Stylesheet.addRule(this.__sheet, selector, rule); this.__rules[rule] = name; return name; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2011 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /* ************************************************************************ #ignore(qx.bom.element.AnimationJs) ************************************************************************ */ /** * This is a simple handle, which will be returned when an animation is * started using the {@link qx.bom.element.Animation#animate} method. It * basically controls the animation. */ qx.Bootstrap.define("qx.bom.element.AnimationHandle", { extend : qx.event.Emitter, construct : function(){ var css = qx.core.Environment.get("css.animation"); this.__playState = css && css["play-state"]; this.__playing = true; }, events : { /** Fired when the animation started via {@link qx.bom.element.Animation}. */ "start" : "Element", /** * Fired when the animation started via {@link qx.bom.element.Animation} has * ended. */ "end" : "Element", /** Fired on every iteration of the animation. */ "iteration" : "Element" }, members : { __playState : null, __playing : false, __ended : false, /** * Accessor of the playing state. * @return {Boolean} <code>true</code>, if the animations is playing. */ isPlaying : function(){ return this.__playing; }, /** * Accessor of the ended state. * @return {Boolean} <code>true</code>, if the animations has ended. */ isEnded : function(){ return this.__ended; }, /** * Accessor of the paused state. * @return {Boolean} <code>true</code>, if the animations is paused. */ isPaused : function(){ return this.el.style[this.__playState] == "paused"; }, /** * Pauses the animation, if running. If not running, it will be ignored. */ pause : function(){ if(this.el){ this.el.style[this.__playState] = "paused"; this.el.$$animation.__playing = false; // in case the animation is based on JS if(this.animationId && qx.bom.element.AnimationJs){ qx.bom.element.AnimationJs.pause(this); }; }; }, /** * Resumes an animation. This does not start the animation once it has ended. * You need to create start a new Animation if you want to restart the animation. */ play : function(){ if(this.el){ this.el.style[this.__playState] = "running"; this.el.$$animation.__playing = true; // in case the animation is based on JS if(this.i != undefined && qx.bom.element.AnimationJs){ qx.bom.element.AnimationJs.play(this); }; }; }, /** * Stops the animation if running. */ stop : function(){ if(this.el && qx.core.Environment.get("css.animation") && !this.jsAnimation){ this.el.style[this.__playState] = ""; this.el.style[qx.core.Environment.get("css.animation").name] = ""; this.el.$$animation.__playing = false; this.el.$$animation.__ended = true; } else if(this.jsAnimation){ this.stopped = true; qx.bom.element.AnimationJs.stop(this); }; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /* ************************************************************************ #ignore(qx.bom.element.Style) #use(qx.bom.element.AnimationJs#play) ************************************************************************ */ /** * This class offers the same API as the CSS3 animation layer in * {@link qx.bom.element.AnimationCss} but uses JavaScript to fake the behavior. * * {@link qx.bom.element.Animation} is the class, which takes care of the * feature detection for CSS animations and decides which implementation * (CSS or JavaScript) should be used. Most likely, this implementation should * be the one to use. */ qx.Bootstrap.define("qx.bom.element.AnimationJs", { statics : { /** * The maximal time a frame should take. */ __maxStepTime : 30, /** * The supported CSS units. */ __units : ["%", "in", "cm", "mm", "em", "ex", "pt", "pc", "px"], /** * This is the main function to start the animation. For further details, * take a look at the documentation of the wrapper * {@link qx.bom.element.Animation}. * @param el {Element} The element to animate. * @param desc {Map} Animation description. * @param duration {Integer?} The duration of the animation which will * override the duration given in the description. * @return {qx.bom.element.AnimationHandle} The handle. */ animate : function(el, desc, duration){ return this._animate(el, desc, duration, false); }, /** * This is the main function to start the animation in reversed mode. * For further details, take a look at the documentation of the wrapper * {@link qx.bom.element.Animation}. * @param el {Element} The element to animate. * @param desc {Map} Animation description. * @param duration {Integer?} The duration of the animation which will * override the duration given in the description. * @return {qx.bom.element.AnimationHandle} The handle. */ animateReverse : function(el, desc, duration){ return this._animate(el, desc, duration, true); }, /** * Helper to start the animation, either in reversed order or not. * * @param el {Element} The element to animate. * @param desc {Map} Animation description. * @param duration {Integer?} The duration of the animation which will * override the duration given in the description. * @param reverse {Boolean} <code>true</code>, if the animation should be * reversed. * @return {qx.bom.element.AnimationHandle} The handle. */ _animate : function(el, desc, duration, reverse){ // stop if an animation is already running if(el.$$animation){ return el.$$animation; }; desc = qx.lang.Object.clone(desc, true); if(duration == undefined){ duration = desc.duration; }; var keyFrames = desc.keyFrames; var keys = this.__getOrderedKeys(keyFrames); var stepTime = this.__getStepTime(duration, keys); var steps = parseInt(duration / stepTime, 10); this.__normalizeKeyFrames(keyFrames, el); var delta = this.__calculateDelta(steps, stepTime, keys, keyFrames, duration, desc.timing); var handle = new qx.bom.element.AnimationHandle(); handle.jsAnimation = true; if(reverse){ delta.reverse(); handle.reverse = true; }; handle.desc = desc; handle.el = el; handle.delta = delta; handle.stepTime = stepTime; handle.steps = steps; el.$$animation = handle; handle.i = 0; handle.initValues = { }; handle.repeatSteps = this.__applyRepeat(steps, desc.repeat); var delay = desc.delay || 0; var self = this; handle.delayId = window.setTimeout(function(){ handle.delayId = null; self.play(handle); }, delay); return handle; }, /** * Try to normalize the keyFrames by adding the default / set values of the * element. * @param keyFrames {Map} The map of key frames. * @param el {Element} The element to animate. */ __normalizeKeyFrames : function(keyFrames, el){ // collect all possible keys and its units var units = { }; for(var percent in keyFrames){ for(var name in keyFrames[percent]){ if(units[name] == undefined){ var item = keyFrames[percent][name]; if(typeof item == "string"){ units[name] = item.substring((parseInt(item, 10) + "").length, item.length); } else { units[name] = ""; }; }; }; }; // add all missing keys for(var percent in keyFrames){ var frame = keyFrames[percent]; for(var name in units){ if(frame[name] == undefined){ if(name in el.style){ // get the computed style if possible if(window.getComputedStyle){ frame[name] = getComputedStyle(el, null)[name]; } else { frame[name] = el.style[name]; }; } else { frame[name] = el[name]; }; // if its a unit we know, set 0 as fallback if(frame[name] === "" && this.__units.indexOf(units[name]) != -1){ frame[name] = "0" + units[name]; }; }; }; }; }, /** * Precalculation of the delta which will be applied during the animation. * The whole deltas will be calculated prior to the animation and stored * in a single array. This method takes care of that calculation. * * @param steps {Integer} The amount of steps to take to the end of the * animation. * @param stepTime {Integer} The amount of milliseconds each step takes. * @param keys {Array} Ordered list of keys in the key frames map. * @param keyFrames {Map} The map of key frames. * @param duration {Integer} Time in milliseconds the animation should take. * @param timing {String} The given timing function. * @return {Array} An array containing the animation deltas. */ __calculateDelta : function(steps, stepTime, keys, keyFrames, duration, timing){ var delta = new Array(steps); var keyIndex = 1; delta[0] = keyFrames[0]; var last = keyFrames[0]; var next = keyFrames[keys[keyIndex]]; // for every step for(var i = 1;i < delta.length;i++){ // switch key frames if we crossed a percent border if(i * stepTime / duration * 100 > keys[keyIndex]){ last = next; keyIndex++; next = keyFrames[keys[keyIndex]]; }; delta[i] = { }; // for every property for(var name in next){ var nItem = next[name] + ""; // color values if(nItem.charAt(0) == "#"){ // get the two values from the frames as RGB arrays var value0 = qx.util.ColorUtil.cssStringToRgb(last[name]); var value1 = qx.util.ColorUtil.cssStringToRgb(nItem); var stepValue = []; // calculate every color chanel for(var j = 0;j < value0.length;j++){ var range = value0[j] - value1[j]; stepValue[j] = parseInt(value0[j] - range * qx.bom.AnimationFrame.calculateTiming(timing, i / steps), 10); }; delta[i][name] = qx.util.ColorUtil.rgbToHexString(stepValue); } else if(!isNaN(parseInt(nItem, 10))){ var unit = nItem.substring((parseInt(nItem, 10) + "").length, nItem.length); var range = parseFloat(nItem) - parseFloat(last[name]); delta[i][name] = (parseFloat(last[name]) + range * qx.bom.AnimationFrame.calculateTiming(timing, i / steps)) + unit; } else { delta[i][name] = last[name] + ""; }; }; }; // make sure the last key frame is right delta[delta.length - 1] = keyFrames[100]; return delta; }, /** * Internal helper for the {@link qx.bom.element.AnimationHandle} to play * the animation. * @internal * @param handle {qx.bom.element.AnimationHandle} The hand which * represents the animation. * @return {qx.bom.element.AnimationHandle} The handle for chaining. */ play : function(handle){ handle.emit("start", handle.el); var id = window.setInterval(function(){ handle.repeatSteps--; var values = handle.delta[handle.i % handle.steps]; // save the init values if(handle.i === 0){ for(var name in values){ if(handle.initValues[name] === undefined){ // animate element property if(handle.el[name] !== undefined){ handle.initValues[name] = handle.el[name]; } else if(qx.bom.element.Style){ handle.initValues[name] = qx.bom.element.Style.get(handle.el, qx.lang.String.camelCase(name)); } else { handle.initValues[name] = handle.el.style[qx.lang.String.camelCase(name)]; }; }; }; }; qx.bom.element.AnimationJs.__applyStyles(handle.el, values); handle.i++; // iteration condition if(handle.i % handle.steps == 0){ handle.emit("iteration", handle.el); if(handle.desc.alternate){ handle.delta.reverse(); }; }; // end condition if(handle.repeatSteps < 0){ qx.bom.element.AnimationJs.stop(handle); }; }, handle.stepTime); handle.animationId = id; return handle; }, /** * Internal helper for the {@link qx.bom.element.AnimationHandle} to pause * the animation. * @internal * @param handle {qx.bom.element.AnimationHandle} The hand which * represents the animation. * @return {qx.bom.element.AnimationHandle} The handle for chaining. */ pause : function(handle){ // stop the interval window.clearInterval(handle.animationId); handle.animationId = null; return handle; }, /** * Internal helper for the {@link qx.bom.element.AnimationHandle} to stop * the animation. * @internal * @param handle {qx.bom.element.AnimationHandle} The hand which * represents the animation. * @return {qx.bom.element.AnimationHandle} The handle for chaining. */ stop : function(handle){ var desc = handle.desc; var el = handle.el; var initValues = handle.initValues; if(handle.animationId){ window.clearInterval(handle.animationId); }; // clear the delay if the animation has not been started if(handle.delayId){ window.clearTimeout(handle.delayId); }; // check if animation is already stopped if(el == undefined){ return handle; }; // if we should keep a frame var keep = desc.keep; if(keep != undefined && !handle.stopped){ if(handle.reverse || (desc.alternate && desc.repeat && desc.repeat % 2 == 0)){ keep = 100 - keep; }; this.__applyStyles(el, desc.keyFrames[keep]); } else { this.__applyStyles(el, initValues); }; el.$$animation = null; handle.el = null; handle.ended = true; handle.animationId = null; handle.emit("end", el); return handle; }, /** * Takes care of the repeat key of the description. * @param steps {Integer} The number of steps one iteration would take. * @param repeat {Integer|String} It can be either a number how often the * animation should be repeated or the string 'infinite'. * @return {Integer} The number of steps to animate. */ __applyRepeat : function(steps, repeat){ if(repeat == undefined){ return steps; }; if(repeat == "infinite"){ return Number.MAX_VALUE; }; return steps * repeat; }, /** * Central method to apply css styles and element properties. * @param el {Element} The DOM element to apply the styles. * @param styles {Map} A map containing styles and values. */ __applyStyles : function(el, styles){ for(var key in styles){ // ignore undefined values (might be a bad detection) if(styles[key] === undefined){ continue; }; // apply element property value - only if a CSS property // is *not* available if(typeof el.style[key] === "undefined" && key in el){ el[key] = styles[key]; continue; }; var name = qx.lang.String.camelCase(key); if(qx.bom.element.Style){ qx.bom.element.Style.set(el, name, styles[key]); } else { el.style[name] = styles[key]; }; }; }, /** * Dynamic calculation of the steps time considering a max step time. * @param duration {Number} The duration of the animation. * @param keys {Array} An array containing the orderd set of key frame keys. * @return {Integer} The best suited step time. */ __getStepTime : function(duration, keys){ // get min difference var minDiff = 100; for(var i = 0;i < keys.length - 1;i++){ minDiff = Math.min(minDiff, keys[i + 1] - keys[i]); }; var stepTime = duration * minDiff / 100; while(stepTime > this.__maxStepTime){ stepTime = stepTime / 2; }; return Math.round(stepTime); }, /** * Helper which returns the orderd keys of the key frame map. * @param keyFrames {Map} The map of key frames. * @return {Array} An orderd list of kyes. */ __getOrderedKeys : function(keyFrames){ var keys = Object.keys(keyFrames); for(var i = 0;i < keys.length;i++){ keys[i] = parseInt(keys[i], 10); }; keys.sort(function(a, b){ return a - b; }); return keys; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Andreas Ecker (ecker) * Christian Hagendorn (cs) ************************************************************************ */ /* ************************************************************************ #ignore(qx.theme.*) #ignore(qx.theme) #ignore(qx.Class) ************************************************************************ */ /** * Methods to convert colors between different color spaces. */ qx.Bootstrap.define("qx.util.ColorUtil", { statics : { /** * Regular expressions for color strings */ REGEXP : { hex3 : /^#([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/, hex6 : /^#([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/, rgb : /^rgb\(\s*([0-9]{1,3}\.{0,1}[0-9]*)\s*,\s*([0-9]{1,3}\.{0,1}[0-9]*)\s*,\s*([0-9]{1,3}\.{0,1}[0-9]*)\s*\)$/, rgba : /^rgba\(\s*([0-9]{1,3}\.{0,1}[0-9]*)\s*,\s*([0-9]{1,3}\.{0,1}[0-9]*)\s*,\s*([0-9]{1,3}\.{0,1}[0-9]*)\s*,\s*([0-9]{1,3}\.{0,1}[0-9]*)\s*\)$/ }, /** * CSS3 system color names. */ SYSTEM : { activeborder : true, activecaption : true, appworkspace : true, background : true, buttonface : true, buttonhighlight : true, buttonshadow : true, buttontext : true, captiontext : true, graytext : true, highlight : true, highlighttext : true, inactiveborder : true, inactivecaption : true, inactivecaptiontext : true, infobackground : true, infotext : true, menu : true, menutext : true, scrollbar : true, threeddarkshadow : true, threedface : true, threedhighlight : true, threedlightshadow : true, threedshadow : true, window : true, windowframe : true, windowtext : true }, /** * Named colors, only the 16 basic colors plus the following ones: * transparent, grey, magenta, orange and brown */ NAMED : { black : [0, 0, 0], silver : [192, 192, 192], gray : [128, 128, 128], white : [255, 255, 255], maroon : [128, 0, 0], red : [255, 0, 0], purple : [128, 0, 128], fuchsia : [255, 0, 255], green : [0, 128, 0], lime : [0, 255, 0], olive : [128, 128, 0], yellow : [255, 255, 0], navy : [0, 0, 128], blue : [0, 0, 255], teal : [0, 128, 128], aqua : [0, 255, 255], // Additional values transparent : [-1, -1, -1], magenta : [255, 0, 255], // alias for fuchsia orange : [255, 165, 0], brown : [165, 42, 42] }, /** * Whether the incoming value is a named color. * * @param value {String} the color value to test * @return {Boolean} true if the color is a named color */ isNamedColor : function(value){ return this.NAMED[value] !== undefined; }, /** * Whether the incoming value is a system color. * * @param value {String} the color value to test * @return {Boolean} true if the color is a system color */ isSystemColor : function(value){ return this.SYSTEM[value] !== undefined; }, /** * Whether the color theme manager is loaded. Generally * part of the GUI of qooxdoo. * * @return {Boolean} <code>true</code> when color theme support is ready. **/ supportsThemes : function(){ if(qx.Class){ return qx.Class.isDefined("qx.theme.manager.Color"); }; return false; }, /** * Whether the incoming value is a themed color. * * @param value {String} the color value to test * @return {Boolean} true if the color is a themed color */ isThemedColor : function(value){ if(!this.supportsThemes()){ return false; }; if(qx.theme && qx.theme.manager && qx.theme.manager.Color){ return qx.theme.manager.Color.getInstance().isDynamic(value); }; return false; }, /** * Try to convert an incoming string to an RGB array. * Supports themed, named and system colors, but also RGB strings, * hex3 and hex6 values. * * @param str {String} any string * @return {Array} returns an array of red, green, blue on a successful transformation * @throws {Error} if the string could not be parsed */ stringToRgb : function(str){ if(this.supportsThemes() && this.isThemedColor(str)){ var str = qx.theme.manager.Color.getInstance().resolveDynamic(str); }; if(this.isNamedColor(str)){ return this.NAMED[str]; } else if(this.isSystemColor(str)){ throw new Error("Could not convert system colors to RGB: " + str); } else if(this.isRgbString(str)){ return this.__rgbStringToRgb(); } else if(this.isHex3String(str)){ return this.__hex3StringToRgb(); } else if(this.isHex6String(str)){ return this.__hex6StringToRgb(); };;;; throw new Error("Could not parse color: " + str); }, /** * Try to convert an incoming string to an RGB array. * Support named colors, RGB strings, hex3 and hex6 values. * * @param str {String} any string * @return {Array} returns an array of red, green, blue on a successful transformation * @throws {Error} if the string could not be parsed */ cssStringToRgb : function(str){ if(this.isNamedColor(str)){ return this.NAMED[str]; } else if(this.isSystemColor(str)){ throw new Error("Could not convert system colors to RGB: " + str); } else if(this.isRgbString(str)){ return this.__rgbStringToRgb(); } else if(this.isRgbaString(str)){ return this.__rgbaStringToRgb(); } else if(this.isHex3String(str)){ return this.__hex3StringToRgb(); } else if(this.isHex6String(str)){ return this.__hex6StringToRgb(); };;;;; throw new Error("Could not parse color: " + str); }, /** * Try to convert an incoming string to an RGB string, which can be used * for all color properties. * Supports themed, named and system colors, but also RGB strings, * hex3 and hex6 values. * * @param str {String} any string * @return {String} a RGB string * @throws {Error} if the string could not be parsed */ stringToRgbString : function(str){ return this.rgbToRgbString(this.stringToRgb(str)); }, /** * Converts a RGB array to an RGB string * * @param rgb {Array} an array with red, green and blue * @return {String} a RGB string */ rgbToRgbString : function(rgb){ return "rgb(" + rgb[0] + "," + rgb[1] + "," + rgb[2] + ")"; }, /** * Converts a RGB array to an hex6 string * * @param rgb {Array} an array with red, green and blue * @return {String} a hex6 string (#xxxxxx) */ rgbToHexString : function(rgb){ return ("#" + qx.lang.String.pad(rgb[0].toString(16).toUpperCase(), 2) + qx.lang.String.pad(rgb[1].toString(16).toUpperCase(), 2) + qx.lang.String.pad(rgb[2].toString(16).toUpperCase(), 2)); }, /** * Detects if a string is a valid qooxdoo color * * @param str {String} any string * @return {Boolean} true when the incoming value is a valid qooxdoo color */ isValidPropertyValue : function(str){ return (this.isThemedColor(str) || this.isNamedColor(str) || this.isHex3String(str) || this.isHex6String(str) || this.isRgbString(str) || this.isRgbaString(str)); }, /** * Detects if a string is a valid CSS color string * * @param str {String} any string * @return {Boolean} true when the incoming value is a valid CSS color string */ isCssString : function(str){ return (this.isSystemColor(str) || this.isNamedColor(str) || this.isHex3String(str) || this.isHex6String(str) || this.isRgbString(str) || this.isRgbaString(str)); }, /** * Detects if a string is a valid hex3 string * * @param str {String} any string * @return {Boolean} true when the incoming value is a valid hex3 string */ isHex3String : function(str){ return this.REGEXP.hex3.test(str); }, /** * Detects if a string is a valid hex6 string * * @param str {String} any string * @return {Boolean} true when the incoming value is a valid hex6 string */ isHex6String : function(str){ return this.REGEXP.hex6.test(str); }, /** * Detects if a string is a valid RGB string * * @param str {String} any string * @return {Boolean} true when the incoming value is a valid RGB string */ isRgbString : function(str){ return this.REGEXP.rgb.test(str); }, /** * Detects if a string is a valid RGBA string * * @param str {String} any string * @return {Boolean} true when the incoming value is a valid RGBA string */ isRgbaString : function(str){ return this.REGEXP.rgba.test(str); }, /** * Converts a regexp object match of a rgb string to an RGB array. * * @return {Array} an array with red, green, blue */ __rgbStringToRgb : function(){ var red = parseInt(RegExp.$1, 10); var green = parseInt(RegExp.$2, 10); var blue = parseInt(RegExp.$3, 10); return [red, green, blue]; }, /** * Converts a regexp object match of a rgba string to an RGB array. * * @return {Array} an array with red, green, blue */ __rgbaStringToRgb : function(){ var red = parseInt(RegExp.$1, 10); var green = parseInt(RegExp.$2, 10); var blue = parseInt(RegExp.$3, 10); return [red, green, blue]; }, /** * Converts a regexp object match of a hex3 string to an RGB array. * * @return {Array} an array with red, green, blue */ __hex3StringToRgb : function(){ var red = parseInt(RegExp.$1, 16) * 17; var green = parseInt(RegExp.$2, 16) * 17; var blue = parseInt(RegExp.$3, 16) * 17; return [red, green, blue]; }, /** * Converts a regexp object match of a hex6 string to an RGB array. * * @return {Array} an array with red, green, blue */ __hex6StringToRgb : function(){ var red = (parseInt(RegExp.$1, 16) * 16) + parseInt(RegExp.$2, 16); var green = (parseInt(RegExp.$3, 16) * 16) + parseInt(RegExp.$4, 16); var blue = (parseInt(RegExp.$5, 16) * 16) + parseInt(RegExp.$6, 16); return [red, green, blue]; }, /** * Converts a hex3 string to an RGB array * * @param value {String} a hex3 (#xxx) string * @return {Array} an array with red, green, blue */ hex3StringToRgb : function(value){ if(this.isHex3String(value)){ return this.__hex3StringToRgb(value); }; throw new Error("Invalid hex3 value: " + value); }, /** * Converts a hex3 (#xxx) string to a hex6 (#xxxxxx) string. * * @param value {String} a hex3 (#xxx) string * @return {String} The hex6 (#xxxxxx) string or the passed value when the * passed value is not an hex3 (#xxx) value. */ hex3StringToHex6String : function(value){ if(this.isHex3String(value)){ return this.rgbToHexString(this.hex3StringToRgb(value)); }; return value; }, /** * Converts a hex6 string to an RGB array * * @param value {String} a hex6 (#xxxxxx) string * @return {Array} an array with red, green, blue */ hex6StringToRgb : function(value){ if(this.isHex6String(value)){ return this.__hex6StringToRgb(value); }; throw new Error("Invalid hex6 value: " + value); }, /** * Converts a hex string to an RGB array * * @param value {String} a hex3 (#xxx) or hex6 (#xxxxxx) string * @return {Array} an array with red, green, blue */ hexStringToRgb : function(value){ if(this.isHex3String(value)){ return this.__hex3StringToRgb(value); }; if(this.isHex6String(value)){ return this.__hex6StringToRgb(value); }; throw new Error("Invalid hex value: " + value); }, /** * Convert RGB colors to HSB * * @param rgb {Number[]} red, blue and green as array * @return {Array} an array with hue, saturation and brightness */ rgbToHsb : function(rgb){ var hue,saturation,brightness; var red = rgb[0]; var green = rgb[1]; var blue = rgb[2]; var cmax = (red > green) ? red : green; if(blue > cmax){ cmax = blue; }; var cmin = (red < green) ? red : green; if(blue < cmin){ cmin = blue; }; brightness = cmax / 255.0; if(cmax != 0){ saturation = (cmax - cmin) / cmax; } else { saturation = 0; }; if(saturation == 0){ hue = 0; } else { var redc = (cmax - red) / (cmax - cmin); var greenc = (cmax - green) / (cmax - cmin); var bluec = (cmax - blue) / (cmax - cmin); if(red == cmax){ hue = bluec - greenc; } else if(green == cmax){ hue = 2.0 + redc - bluec; } else { hue = 4.0 + greenc - redc; }; hue = hue / 6.0; if(hue < 0){ hue = hue + 1.0; }; }; return [Math.round(hue * 360), Math.round(saturation * 100), Math.round(brightness * 100)]; }, /** * Convert HSB colors to RGB * * @param hsb {Number[]} an array with hue, saturation and brightness * @return {Integer[]} an array with red, green, blue */ hsbToRgb : function(hsb){ var i,f,p,q,t; var hue = hsb[0] / 360; var saturation = hsb[1] / 100; var brightness = hsb[2] / 100; if(hue >= 1.0){ hue %= 1.0; }; if(saturation > 1.0){ saturation = 1.0; }; if(brightness > 1.0){ brightness = 1.0; }; var tov = Math.floor(255 * brightness); var rgb = { }; if(saturation == 0.0){ rgb.red = rgb.green = rgb.blue = tov; } else { hue *= 6.0; i = Math.floor(hue); f = hue - i; p = Math.floor(tov * (1.0 - saturation)); q = Math.floor(tov * (1.0 - (saturation * f))); t = Math.floor(tov * (1.0 - (saturation * (1.0 - f)))); switch(i){case 0: rgb.red = tov; rgb.green = t; rgb.blue = p; break;case 1: rgb.red = q; rgb.green = tov; rgb.blue = p; break;case 2: rgb.red = p; rgb.green = tov; rgb.blue = t; break;case 3: rgb.red = p; rgb.green = q; rgb.blue = tov; break;case 4: rgb.red = t; rgb.green = p; rgb.blue = tov; break;case 5: rgb.red = tov; rgb.green = p; rgb.blue = q; break;}; }; return [rgb.red, rgb.green, rgb.blue]; }, /** * Creates a random color. * * @return {String} a valid qooxdoo/CSS rgb color string. */ randomColor : function(){ var r = Math.round(Math.random() * 255); var g = Math.round(Math.random() * 255); var b = Math.round(Math.random() * 255); return this.rgbToRgbString([r, g, b]); } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2011 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /* ************************************************************************ #ignore(performance) #ignore(performance.timing) ************************************************************************* */ /** * This is a cross browser wrapper for requestAnimationFrame. For further * information about the feature, take a look at spec: * http://www.w3.org/TR/animation-timing/ * * This class offers two ways of using this feature. First, the plain * API the spec describes. * * Here is a sample usage: * <pre class='javascript'>var start = +(new Date()); * var clb = function(time) { * if (time >= start + duration) { * // ... do some last tasks * } else { * var timePassed = time - start; * // ... calculate the current step and apply it * qx.bom.AnimationFrame.request(clb, this); * } * }; * qx.bom.AnimationFrame.request(clb, this); * </pre> * * Another way of using it is to use it as an instance emitting events. * * Here is a sample usage of that API: * <pre class='javascript'>var frame = new qx.bom.AnimationFrame(); * frame.on("end", function() { * // ... do some last tasks * }, this); * frame.on("frame", function(timePassed) { * // ... calculate the current step and apply it * }, this); * frame.startSequence(duration); * </pre> */ qx.Bootstrap.define("qx.bom.AnimationFrame", { extend : qx.event.Emitter, events : { /** Fired as soon as the animation has ended. */ "end" : undefined, /** Fired on every frame having the passed time as value. */ "frame" : "Number" }, members : { /** * Method used to start a series of animation frames. The series will end as * soon as the given duration is over. * * @param duration {Number} The duration the sequence should take. */ startSequence : function(duration){ var start = +(new Date()); var clb = function(){ var time = +(new Date()); // final call if(time >= start + duration){ this.emit("end"); this.id = null; } else { var timePassed = time - start; this.emit("frame", timePassed); this.id = qx.bom.AnimationFrame.request(clb, this); }; }; this.id = qx.bom.AnimationFrame.request(clb, this); } }, statics : { /** * The default time in ms the timeout fallback implementation uses. */ TIMEOUT : 30, /** * Calculation of the predefined timing functions. Approximation of the real * bezier curves has ben used for easier calculation. This is good and close * enough for the predefined functions like <code>ease</code> or * <code>linear</code>. * * @param func {String} The defined timing function. One of the following values: * <code>"ease-in"</code>, <code>"ease-out"</code>, <code>"linear"</code>, * <code>"ease-in-out"</code>, <code>"ease"</code>. * @param x {Integer} The percent value of the function. * @return {Integer} The calculated value */ calculateTiming : function(func, x){ if(func == "ease-in"){ var a = [3.1223e-7, 0.0757, 1.2646, -0.167, -0.4387, 0.2654]; } else if(func == "ease-out"){ var a = [-7.0198e-8, 1.652, -0.551, -0.0458, 0.1255, -0.1807]; } else if(func == "linear"){ return x; } else if(func == "ease-in-out"){ var a = [2.482e-7, -0.2289, 3.3466, -1.0857, -1.7354, 0.7034]; } else { // default is 'ease' var a = [-0.0021, 0.2472, 9.8054, -21.6869, 17.7611, -5.1226]; };;; // A 6th grade polynomial has been used as approximation of the original // bezier curves described in the transition spec // http://www.w3.org/TR/css3-transitions/#transition-timing-function_tag // (the same is used for animations as well) var y = 0; for(var i = 0;i < a.length;i++){ y += a[i] * Math.pow(x, i); }; return y; }, /** * Request for an animation frame. If the native <code>requestAnimationFrame</code> * method is supported, it will be used. Otherwise, we use timeouts with a * 30ms delay. * @param callback {Function} The callback function which will get the current * time as argument. * @param context {var} The context of the callback. * @return {Number} The id of the request. */ request : function(callback, context){ var req = qx.core.Environment.get("css.animation.requestframe"); var clb = function(){ var time = +(new Date()); callback.call(context, time); }; if(req){ return window[req](clb); } else { // make sure to use an indirection because setTimeout passes a // number as first argument as well return window.setTimeout(function(){ clb(); }, qx.bom.AnimationFrame.TIMEOUT); }; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Fabian Jakobs (fjakobs) * Christian Hagendorn (chris_schmidt) ************************************************************************ */ /** * Abstract class to compute the position of an object on one axis. */ qx.Bootstrap.define("qx.util.placement.AbstractAxis", { extend : Object, statics : { /** * Computes the start of the object on the axis * * @param size {Integer} Size of the object to align * @param target {Map} Location of the object to align the object to. This map * should have the keys <code>start</code> and <code>end</code>. * @param offsets {Map} Map with all offsets on each side. * Comes with the keys <code>start</code> and <code>end</code>. * @param areaSize {Integer} Size of the axis. * @param position {String} Alignment of the object on the target. Valid values are * <ul> * <li><code>edge-start</code> The object is placed before the target</li> * <li><code>edge-end</code> The object is placed after the target</li> * <li><code>align-start</code>The start of the object is aligned with the start of the target</li> * <li><code>align-center</code>The center of the object is aligned with the center of the target</li> * <li><code>align-end</code>The end of the object is aligned with the end of the object</li> * </ul> * @return {Integer} The computed start position of the object. * @abstract */ computeStart : function(size, target, offsets, areaSize, position){ throw new Error("abstract method call!"); }, /** * Computes the start of the object by taking only the attachment and * alignment into account. The object by be not fully visible. * * @param size {Integer} Size of the object to align * @param target {Map} Location of the object to align the object to. This map * should have the keys <code>start</code> and <code>end</code>. * @param offsets {Map} Map with all offsets on each side. * Comes with the keys <code>start</code> and <code>end</code>. * @param position {String} Accepts the same values as the <code> position</code> * argument of {@link #computeStart}. * @return {Integer} The computed start position of the object. */ _moveToEdgeAndAlign : function(size, target, offsets, position){ switch(position){case "edge-start": return target.start - offsets.end - size;case "edge-end": return target.end + offsets.start;case "align-start": return target.start + offsets.start;case "align-center": return target.start + parseInt((target.end - target.start - size) / 2, 10) + offsets.start;case "align-end": return target.end - offsets.end - size;}; }, /** * Whether the object specified by <code>start</code> and <code>size</code> * is completely inside of the axis' range.. * * @param start {Integer} Computed start position of the object * @param size {Integer} Size of the object * @param areaSize {Integer} The size of the axis * @return {Boolean} Whether the object is inside of the axis' range */ _isInRange : function(start, size, areaSize){ return start >= 0 && start + size <= areaSize; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Fabian Jakobs (fjakobs) * Christian Hagendorn (chris_schmidt) ************************************************************************ */ /** * Places the object directly at the specified position. It is not moved if * parts of the object are outside of the axis' range. */ qx.Bootstrap.define("qx.util.placement.DirectAxis", { statics : { /** * Computes the start of the object by taking only the attachment and * alignment into account. The object by be not fully visible. * * @param size {Integer} Size of the object to align * @param target {Map} Location of the object to align the object to. This map * should have the keys <code>start</code> and <code>end</code>. * @param offsets {Map} Map with all offsets on each side. * Comes with the keys <code>start</code> and <code>end</code>. * @param position {String} Accepts the same values as the <code> position</code> * argument of {@link #computeStart}. * @return {Integer} The computed start position of the object. */ _moveToEdgeAndAlign : qx.util.placement.AbstractAxis._moveToEdgeAndAlign, /** * Computes the start of the object on the axis * * @param size {Integer} Size of the object to align * @param target {Map} Location of the object to align the object to. This map * should have the keys <code>start</code> and <code>end</code>. * @param offsets {Map} Map with all offsets on each side. * Comes with the keys <code>start</code> and <code>end</code>. * @param areaSize {Integer} Size of the axis. * @param position {String} Alignment of the object on the target. Valid values are * <ul> * <li><code>edge-start</code> The object is placed before the target</li> * <li><code>edge-end</code> The object is placed after the target</li> * <li><code>align-start</code>The start of the object is aligned with the start of the target</li> * <li><code>align-center</code>The center of the object is aligned with the center of the target</li> * <li><code>align-end</code>The end of the object is aligned with the end of the object</li> * </ul> * @return {Integer} The computed start position of the object. */ computeStart : function(size, target, offsets, areaSize, position){ return this._moveToEdgeAndAlign(size, target, offsets, position); } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Fabian Jakobs (fjakobs) * Christian Hagendorn (chris_schmidt) ************************************************************************ */ /** * Places the object to the target. If parts of the object are outside of the * range this class places the object at the best "edge", "alignment" * combination so that the overlap between object and range is maximized. */ qx.Bootstrap.define("qx.util.placement.KeepAlignAxis", { statics : { /** * Computes the start of the object by taking only the attachment and * alignment into account. The object by be not fully visible. * * @param size {Integer} Size of the object to align * @param target {Map} Location of the object to align the object to. This map * should have the keys <code>start</code> and <code>end</code>. * @param offsets {Map} Map with all offsets on each side. * Comes with the keys <code>start</code> and <code>end</code>. * @param position {String} Accepts the same values as the <code> position</code> * argument of {@link #computeStart}. * @return {Integer} The computed start position of the object. */ _moveToEdgeAndAlign : qx.util.placement.AbstractAxis._moveToEdgeAndAlign, /** * Whether the object specified by <code>start</code> and <code>size</code> * is completely inside of the axis' range.. * * @param start {Integer} Computed start position of the object * @param size {Integer} Size of the object * @param areaSize {Integer} The size of the axis * @return {Boolean} Whether the object is inside of the axis' range */ _isInRange : qx.util.placement.AbstractAxis._isInRange, /** * Computes the start of the object on the axis * * @param size {Integer} Size of the object to align * @param target {Map} Location of the object to align the object to. This map * should have the keys <code>start</code> and <code>end</code>. * @param offsets {Map} Map with all offsets on each side. * Comes with the keys <code>start</code> and <code>end</code>. * @param areaSize {Integer} Size of the axis. * @param position {String} Alignment of the object on the target. Valid values are * <ul> * <li><code>edge-start</code> The object is placed before the target</li> * <li><code>edge-end</code> The object is placed after the target</li> * <li><code>align-start</code>The start of the object is aligned with the start of the target</li> * <li><code>align-center</code>The center of the object is aligned with the center of the target</li> * <li><code>align-end</code>The end of the object is aligned with the end of the object</li> * </ul> * @return {Integer} The computed start position of the object. */ computeStart : function(size, target, offsets, areaSize, position){ var start = this._moveToEdgeAndAlign(size, target, offsets, position); var range1End,range2Start; if(this._isInRange(start, size, areaSize)){ return start; }; if(position == "edge-start" || position == "edge-end"){ range1End = target.start - offsets.end; range2Start = target.end + offsets.start; } else { range1End = target.end - offsets.end; range2Start = target.start + offsets.start; }; if(range1End > areaSize - range2Start){ start = range1End - size; } else { start = range2Start; }; return start; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Fabian Jakobs (fjakobs) * Christian Hagendorn (chris_schmidt) ************************************************************************ */ /** * Places the object according to the target. If parts of the object are outside * of the axis' range the object's start is adjusted so that the overlap between * the object and the axis is maximized. */ qx.Bootstrap.define("qx.util.placement.BestFitAxis", { statics : { /** * Whether the object specified by <code>start</code> and <code>size</code> * is completely inside of the axis' range.. * * @param start {Integer} Computed start position of the object * @param size {Integer} Size of the object * @param areaSize {Integer} The size of the axis * @return {Boolean} Whether the object is inside of the axis' range */ _isInRange : qx.util.placement.AbstractAxis._isInRange, /** * Computes the start of the object by taking only the attachment and * alignment into account. The object by be not fully visible. * * @param size {Integer} Size of the object to align * @param target {Map} Location of the object to align the object to. This map * should have the keys <code>start</code> and <code>end</code>. * @param offsets {Map} Map with all offsets on each side. * Comes with the keys <code>start</code> and <code>end</code>. * @param position {String} Accepts the same values as the <code> position</code> * argument of {@link #computeStart}. * @return {Integer} The computed start position of the object. */ _moveToEdgeAndAlign : qx.util.placement.AbstractAxis._moveToEdgeAndAlign, /** * Computes the start of the object on the axis * * @param size {Integer} Size of the object to align * @param target {Map} Location of the object to align the object to. This map * should have the keys <code>start</code> and <code>end</code>. * @param offsets {Map} Map with all offsets on each side. * Comes with the keys <code>start</code> and <code>end</code>. * @param areaSize {Integer} Size of the axis. * @param position {String} Alignment of the object on the target. Valid values are * <ul> * <li><code>edge-start</code> The object is placed before the target</li> * <li><code>edge-end</code> The object is placed after the target</li> * <li><code>align-start</code>The start of the object is aligned with the start of the target</li> * <li><code>align-center</code>The center of the object is aligned with the center of the target</li> * <li><code>align-end</code>The end of the object is aligned with the end of the object</li> * </ul> * @return {Integer} The computed start position of the object. */ computeStart : function(size, target, offsets, areaSize, position){ var start = this._moveToEdgeAndAlign(size, target, offsets, position); if(this._isInRange(start, size, areaSize)){ return start; }; if(start < 0){ start = Math.min(0, areaSize - size); }; if(start + size > areaSize){ start = Math.max(0, areaSize - size); }; return start; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Daniel Wagner (danielwagner) ************************************************************************ */ /* ************************************************************************ #require(qx.util.placement.KeepAlignAxis#computeStart) #require(qx.util.placement.BestFitAxis#computeStart) #require(qx.util.placement.DirectAxis#computeStart) ************************************************************************ */ /** * The Placement module provides a convenient way to align two elements relative * to each other using various pre-defined algorithms. */ qxWeb.define("qx.module.Placement", { statics : { /** * Moves the first element in the collection, aligning it with the given * target. * * @attach{qxWeb} * @param target {Element} Placement target * @param position {String} Alignment of the object with the target, any of * <code>"top-left"</code>, <code>"top-center"</code>, <code>"top-right"</code>, * <code>"bottom-left"</code>, <code>"bottom-center"</code>, <code>"bottom-right"</code>, * <code>"left-top"</code>, <code>"left-middle"</code>, <code>"left-bottom"</code>, * <code>"right-top"</code>, <code>"right-middle"</code>, <code>"right-bottom"</code> * @param offsets {Map?null} Map with the desired offsets between the two elements. * Must contain the keys <code>left</code>, <code>top</code>, * <code>right</code> and <code>bottom</code> * @param modeX {String?"direct"} Horizontal placement mode. Valid values are: * <ul> * <li><code>direct</code>: place the element directly at the given * location.</li> * <li><code>keep-align</code>: if the element is partially outside of the * visible area, it is moved to the best fitting 'edge' and 'alignment' of * the target. * It is guaranteed the the new position attaches the object to one of the * target edges and that it is aligned with a target edge.</li> * <li><code>best-fit</code>: If the element is partially outside of the visible * area, it is moved into the view port, ignoring any offset and position * values.</li> * </ul> * @param modeY {String?"direct"} Vertical placement mode. Accepts the same values as * the 'modeX' argument. * @return {qxWeb} The collection for chaining */ placeTo : function(target, position, offsets, modeX, modeY){ if(!this[0]){ return null; }; var axes = { x : qx.module.Placement._getAxis(modeX), y : qx.module.Placement._getAxis(modeY) }; var size = { width : this.getWidth(), height : this.getHeight() }; var parent = this.getParents(); var area = { width : parent.getWidth(), height : parent.getHeight() }; var target = qxWeb(target).getOffset(); var offsets = offsets || { top : 0, right : 0, bottom : 0, left : 0 }; var splitted = position.split("-"); var edge = splitted[0]; var align = splitted[1]; var position = { x : qx.module.Placement._getPositionX(edge, align), y : qx.module.Placement._getPositionY(edge, align) }; var newLocation = qx.module.Placement._computePlacement(axes, size, area, target, offsets, position); this.setStyles({ position : "absolute", left : newLocation.left + "px", top : newLocation.top + "px" }); return this; }, /** * Returns the appropriate axis implementation for the given placement * mode * * @param mode {String} Placement mode * @return {Object} Placement axis class */ _getAxis : function(mode){ switch(mode){case "keep-align": return qx.util.placement.KeepAlignAxis;case "best-fit": return qx.util.placement.BestFitAxis;case "direct":default: return qx.util.placement.DirectAxis;}; }, /** * Returns the computed coordinates for the element to be placed * * @param axes {Map} Map with the keys <code>x</code> and <code>y</code>. Values * are the axis implementations * @param size {Map} Map with the keys <code>width</code> and <code>height</code> * containing the size of the placement target * @param area {Map} Map with the keys <code>width</code> and <code>height</code> * containing the size of the two elements' common parent (available space for * placement) * @param target {qxWeb} Collection containing the placement target * @param offsets {Map} Map of offsets (top, right, bottom, left) * @param position {Map} Map with the keys <code>x</code> and <code>y</code>, * containing the type of positioning for each axis * @return {Map} Map with the keys <code>left</code> and <code>top</code> * containing the computed coordinates to which the element should be moved */ _computePlacement : function(axes, size, area, target, offsets, position){ var left = axes.x.computeStart(size.width, { start : target.left, end : target.right }, { start : offsets.left, end : offsets.right }, area.width, position.x); var top = axes.y.computeStart(size.height, { start : target.top, end : target.bottom }, { start : offsets.top, end : offsets.bottom }, area.height, position.y); return { left : left, top : top }; }, /** * Returns the X axis positioning type for the given edge and alignment * values * * @param edge {String} edge value * @param align {String} align value * @return {String} X positioning type */ _getPositionX : function(edge, align){ if(edge == "left"){ return "edge-start"; } else if(edge == "right"){ return "edge-end"; } else if(align == "left"){ return "align-start"; } else if(align == "right"){ return "align-end"; };;; }, /** * Returns the Y axis positioning type for the given edge and alignment * values * * @param edge {String} edge value * @param align {String} align value * @return {String} Y positioning type */ _getPositionY : function(edge, align){ if(edge == "top"){ return "edge-start"; } else if(edge == "bottom"){ return "edge-end"; } else if(align == "top"){ return "align-start"; } else if(align == "bottom"){ return "align-end"; };;; } }, defer : function(statics){ qxWeb.$attach({ "placeTo" : statics.placeTo }); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Daniel Wagner (danielwagner) ************************************************************************ */ /* ************************************************************************ #require(qx.module.Event) ************************************************************************ */ /** * Creates a touch event handler that fires high-level events such as "swipe" * based on low-level event sequences on the given element */ qx.Bootstrap.define("qx.module.event.TouchHandler", { statics : { /** * List of events that require a touch handler * @type {Array} */ TYPES : ["tap", "swipe"], /** * Creates a touch handler for the given element when a touch event listener * is attached to it * * @param element {Element} DOM element */ register : function(element){ if(!element.__touchHandler){ if(!element.__emitter){ element.__emitter = new qx.event.Emitter(); }; element.__touchHandler = new qx.event.handler.TouchCore(element, element.__emitter); }; }, /** * Removes the touch event handler from the element if there are no more * touch event listeners attached to it * @param element {Element} DOM element */ unregister : function(element){ if(element.__touchHandler){ if(!element.__emitter){ element.__touchHandler = null; } else { var hasTouchListener = false; var listeners = element.__emitter.getListeners(); qx.module.event.TouchHandler.TYPES.forEach(function(type){ if(type in listeners && listeners[type].length > 0){ hasTouchListener = true; }; }); if(!hasTouchListener){ element.__touchHandler = null; }; }; }; } }, defer : function(statics){ qxWeb.$registerEventHook(statics.TYPES, statics.register, statics.unregister); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) * Tino Butz (tbtz) * Christian Hagendorn (chris_schmidt) * Daniel Wagner (danielwagner) ************************************************************************ */ /* ************************************************************************ #ignore(qx.event.type.Tap) #ignore(qx.event.type.Swipe) #ignore(qx.event.type) #ignore(qx.event) ************************************************************************ */ /** * Listens for native touch events and fires composite events like "tap" and * "swipe" */ qx.Bootstrap.define("qx.event.handler.TouchCore", { extend : Object, statics : { /** {Integer} The maximum distance of a tap. Only if the x or y distance of * the performed tap is less or equal the value of this constant, a tap * event is fired. */ TAP_MAX_DISTANCE : qx.core.Environment.get("os.name") != "android" ? 10 : 40, /** {Map} The direction of a swipe relative to the axis */ SWIPE_DIRECTION : { x : ["left", "right"], y : ["up", "down"] }, /** {Integer} The minimum distance of a swipe. Only if the x or y distance * of the performed swipe is greater as or equal the value of this * constant, a swipe event is fired. */ SWIPE_MIN_DISTANCE : qx.core.Environment.get("os.name") != "android" ? 11 : 41, /** {Integer} The minimum velocity of a swipe. Only if the velocity of the * performed swipe is greater as or equal the value of this constant, a * swipe event is fired. */ SWIPE_MIN_VELOCITY : 0 }, /** * Create a new instance * * @param target {Element} element on which to listen for native touch events * @param emitter {qx.event.Emitter} Event emitter object */ construct : function(target, emitter){ this.__target = target; this.__emitter = emitter; this._initTouchObserver(); }, members : { __target : null, __emitter : null, __onTouchEventWrapper : null, __originalTarget : null, __startPageX : null, __startPageY : null, __startTime : null, __isSingleTouchGesture : null, __isTapGesture : null, __onMove : null, __beginScalingDistance : null, __beginRotation : null, /* --------------------------------------------------------------------------- OBSERVER INIT --------------------------------------------------------------------------- */ /** * Initializes the native touch event listeners. */ _initTouchObserver : function(){ this.__onTouchEventWrapper = qx.lang.Function.listener(this._onTouchEvent, this); var Event = qx.bom.Event; Event.addNativeListener(this.__target, "touchstart", this.__onTouchEventWrapper); Event.addNativeListener(this.__target, "touchmove", this.__onTouchEventWrapper); Event.addNativeListener(this.__target, "touchend", this.__onTouchEventWrapper); Event.addNativeListener(this.__target, "touchcancel", this.__onTouchEventWrapper); if(qx.core.Environment.get("event.mspointer")){ Event.addNativeListener(this.__target, "MSPointerDown", this.__onTouchEventWrapper); Event.addNativeListener(this.__target, "MSPointerMove", this.__onTouchEventWrapper); Event.addNativeListener(this.__target, "MSPointerUp", this.__onTouchEventWrapper); Event.addNativeListener(this.__target, "MSPointerCancel", this.__onTouchEventWrapper); }; }, /* --------------------------------------------------------------------------- OBSERVER STOP --------------------------------------------------------------------------- */ /** * Disconnects the native touch event listeners. */ _stopTouchObserver : function(){ var Event = qx.bom.Event; Event.removeNativeListener(this.__target, "touchstart", this.__onTouchEventWrapper); Event.removeNativeListener(this.__target, "touchmove", this.__onTouchEventWrapper); Event.removeNativeListener(this.__target, "touchend", this.__onTouchEventWrapper); Event.removeNativeListener(this.__target, "touchcancel", this.__onTouchEventWrapper); if(qx.core.Environment.get("event.mspointer")){ Event.removeNativeListener(this.__target, "MSPointerDown", this.__onTouchEventWrapper); Event.removeNativeListener(this.__target, "MSPointerMove", this.__onTouchEventWrapper); Event.removeNativeListener(this.__target, "MSPointerUp", this.__onTouchEventWrapper); Event.removeNativeListener(this.__target, "MSPointerCancel", this.__onTouchEventWrapper); }; }, /* --------------------------------------------------------------------------- NATIVE EVENT OBSERVERS --------------------------------------------------------------------------- */ /** * Handler for native touch events. * * @param domEvent {Event} The touch event from the browser. */ _onTouchEvent : function(domEvent){ this._commonTouchEventHandler(domEvent); }, /** * Calculates the scaling distance between two touches. * @param touch0 {Event} The touch event from the browser. * @param touch1 {Event} The touch event from the browser. * @return {Number} the calculated distance. */ _getScalingDistance : function(touch0, touch1){ return (Math.sqrt(Math.pow(touch0.pageX - touch1.pageX, 2) + Math.pow(touch0.pageY - touch1.pageY, 2))); }, /** * Calculates the rotation between two touches. * @param touch0 {Event} The touch event from the browser. * @param touch1 {Event} The touch event from the browser. * @return {Number} the calculated rotation. */ _getRotationAngle : function(touch0, touch1){ var x = touch0.pageX - touch1.pageX; var y = touch0.pageY - touch1.pageY; return (Math.atan2(y, x) * 180 / Math.PI); }, /** * Called by an event handler. * * @param domEvent {Event} DOM event * @param type {String ? null} type of the event */ _commonTouchEventHandler : function(domEvent, type){ var type = type || domEvent.type; if(qx.core.Environment.get("event.mspointer")){ domEvent.changedTouches = [domEvent]; domEvent.targetTouches = [domEvent]; domEvent.touches = [domEvent]; if(type == "MSPointerDown"){ type = "touchstart"; } else if(type == "MSPointerUp"){ type = "touchend"; } else if(type == "MSPointerMove"){ if(this.__onMove == true){ type = "touchmove"; }; } else if(type == "MSPointerCancel"){ type = "touchcancel"; };;; }; if(type == "touchstart"){ this.__originalTarget = this._getTarget(domEvent); this.__isTapGesture = true; if(domEvent.touches && domEvent.touches.length > 1){ this.__beginScalingDistance = this._getScalingDistance(domEvent.touches[0], domEvent.touches[1]); this.__beginRotation = this._getRotationAngle(domEvent.touches[0], domEvent.touches[1]); }; }; if(type == "touchmove"){ // Polyfill for scale if(typeof domEvent.scale == "undefined" && domEvent.changedTouches.length > 1){ var currentScalingDistance = this._getScalingDistance(domEvent.changedTouches[0], domEvent.changedTouches[1]); domEvent.scale = currentScalingDistance / this.__beginScalingDistance; }; // Polyfill for rotation if(typeof domEvent.rotation == "undefined" && domEvent.changedTouches.length > 1){ var currentRotation = this._getRotationAngle(domEvent.changedTouches[0], domEvent.changedTouches[1]); domEvent.rotation = currentRotation - this.__beginRotation; }; if(this.__isTapGesture){ this.__isTapGesture = this._isBelowTapMaxDistance(domEvent.changedTouches[0]); }; }; this._fireEvent(domEvent, type); this.__checkAndFireGesture(domEvent, type); }, /** * Checks if the distance between the x/y coordinates of "touchstart" and "touchmove" event * exceeds TAP_MAX_DISTANCE and returns the result. * * @param touch {Event} The "touchmove" event from the browser. * @return {Boolean} true if distance is below TAP_MAX_DISTANCE. */ _isBelowTapMaxDistance : function(touch){ var deltaCoordinates = { x : touch.screenX - this.__startPageX, y : touch.screenY - this.__startPageY }; var clazz = qx.event.handler.TouchCore; return (Math.abs(deltaCoordinates.x) <= clazz.TAP_MAX_DISTANCE && Math.abs(deltaCoordinates.y) <= clazz.TAP_MAX_DISTANCE); }, /* --------------------------------------------------------------------------- HELPERS --------------------------------------------------------------------------- */ /** * Return the target of the event. * * @param domEvent {Event} DOM event * @return {Element} Event target */ _getTarget : function(domEvent){ var target = qx.bom.Event.getTarget(domEvent); // Text node. Fix Safari Bug, see http://www.quirksmode.org/js/events_properties.html if(qx.core.Environment.get("engine.name") == "webkit"){ if(target && target.nodeType == 3){ target = target.parentNode; }; } else if(qx.core.Environment.get("event.mspointer")){ // Fix for IE10 and pointer-events:none var targetForIE = this.__evaluateTarget(domEvent); if(targetForIE){ target = targetForIE; }; }; return target; }, /** * This method fixes "pointer-events:none" for Internet Explorer 10. * Checks which elements are placed to position x/y and traverses the array * till one element has no "pointer-events:none" inside its style attribute. * @param domEvent {Event} DOM event * @return {Element | null} Event target */ __evaluateTarget : function(domEvent){ if(domEvent && domEvent.touches){ var clientX = domEvent.touches[0].clientX; var clientY = domEvent.touches[0].clientY; }; // Retrieve an array with elements on point X/Y. var hitTargets = document.msElementsFromPoint(clientX, clientY); if(hitTargets){ // Traverse this array for the elements which has no pointer-events:none inside. for(var i = 0;i < hitTargets.length;i++){ var currentTarget = hitTargets[i]; var pointerEvents = qx.bom.element.Style.get(currentTarget, "pointer-events", 3); if(pointerEvents != "none"){ return currentTarget; }; }; }; return null; }, /** * Fire a touch event with the given parameters * * @param domEvent {Event} DOM event * @param type {String ? null} type of the event * @param target {Element ? null} event target */ _fireEvent : function(domEvent, type, target){ if(!target){ target = this._getTarget(domEvent); }; var type = type || domEvent.type; if(target && target.nodeType && this.__emitter){ this.__emitter.emit(type, domEvent); }; }, /** * Checks if a gesture was made and fires the gesture event. * * @param domEvent {Event} DOM event * @param type {String ? null} type of the event * @param target {Element ? null} event target */ __checkAndFireGesture : function(domEvent, type, target){ if(!target){ target = this._getTarget(domEvent); }; var type = type || domEvent.type; if(type == "touchstart"){ this.__gestureStart(domEvent, target); } else if(type == "touchmove"){ this.__gestureChange(domEvent, target); } else if(type == "touchend"){ this.__gestureEnd(domEvent, target); };; }, /** * Helper method for gesture start. * * @param domEvent {Event} DOM event * @param target {Element} event target */ __gestureStart : function(domEvent, target){ var touch = domEvent.changedTouches[0]; this.__onMove = true; this.__startPageX = touch.screenX; this.__startPageY = touch.screenY; this.__startTime = new Date().getTime(); this.__isSingleTouchGesture = domEvent.changedTouches.length === 1; }, /** * Helper method for gesture change. * * @param domEvent {Event} DOM event * @param target {Element} event target */ __gestureChange : function(domEvent, target){ // Abort a single touch gesture when another touch occurs. if(this.__isSingleTouchGesture && domEvent.changedTouches.length > 1){ this.__isSingleTouchGesture = false; }; }, /** * Helper method for gesture end. * * @param domEvent {Event} DOM event * @param target {Element} event target */ __gestureEnd : function(domEvent, target){ this.__onMove = false; if(this.__isSingleTouchGesture){ var touch = domEvent.changedTouches[0]; var deltaCoordinates = { x : touch.screenX - this.__startPageX, y : touch.screenY - this.__startPageY }; var eventType; if(this.__originalTarget == target && this.__isTapGesture){ if(qx.event && qx.event.type && qx.event.type.Tap){ eventType = qx.event.type.Tap; }; this._fireEvent(domEvent, "tap", target, eventType); } else { var swipe = this.__getSwipeGesture(domEvent, target, deltaCoordinates); if(swipe){ if(qx.event && qx.event.type && qx.event.type.Swipe){ eventType = qx.event.type.Swipe; }; domEvent.swipe = swipe; this._fireEvent(domEvent, "swipe", target, eventType); }; }; }; }, /** * Returns the swipe gesture when the user performed a swipe. * * @param domEvent {Event} DOM event * @param target {Element} event target * @param deltaCoordinates {Map} delta x/y coordinates since the gesture started. * @return {Map} returns the swipe data when the user performed a swipe, null if the gesture was no swipe. */ __getSwipeGesture : function(domEvent, target, deltaCoordinates){ var clazz = qx.event.handler.TouchCore; var duration = new Date().getTime() - this.__startTime; var axis = (Math.abs(deltaCoordinates.x) >= Math.abs(deltaCoordinates.y)) ? "x" : "y"; var distance = deltaCoordinates[axis]; var direction = clazz.SWIPE_DIRECTION[axis][distance < 0 ? 0 : 1]; var velocity = (duration !== 0) ? distance / duration : 0; var swipe = null; if(Math.abs(velocity) >= clazz.SWIPE_MIN_VELOCITY && Math.abs(distance) >= clazz.SWIPE_MIN_DISTANCE){ swipe = { startTime : this.__startTime, duration : duration, axis : axis, direction : direction, distance : distance, velocity : velocity }; }; return swipe; }, /** * Dispose this object */ dispose : function(){ this._stopTouchObserver(); this.__originalTarget = this.__target = this.__emitter = this.__beginScalingDistance = this.__beginRotation = null; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Daniel Wagner (danielwagner) ************************************************************************ */ /* ************************************************************************ #require(qx.module.Event) ************************************************************************ */ /** * Normalization for orientationchange events * Example: * <pre class="javascript"> * q(window).on("orientationchange", function(ev) { * ev.getOrientation(); * ev.isLandscape(); * }); * </pre> */ qx.Bootstrap.define("qx.module.event.Orientation", { statics : { /** * List of event types to be normalized */ TYPES : ["orientationchange"], /** * List of qx.module.event.Orientation methods to be attached to native * event objects * @internal */ BIND_METHODS : ["getOrientation", "isLandscape", "isPortrait"], /** * Returns the current orientation of the viewport in degrees. * * All possible values and their meaning: * * * <code>0</code>: "Portrait" * * <code>-90</code>: "Landscape (right, screen turned clockwise)" * * <code>90</code>: "Landscape (left, screen turned counterclockwise)" * * <code>180</code>: "Portrait (upside-down portrait)" * * @return {Number} The current orientation in degrees */ getOrientation : function(){ return this._orientation; }, /** * Whether the viewport orientation is currently in landscape mode. * * @return {Boolean} <code>true</code> when the viewport orientation * is currently in landscape mode. */ isLandscape : function(){ return this._mode == "landscape"; }, /** * Whether the viewport orientation is currently in portrait mode. * * @return {Boolean} <code>true</code> when the viewport orientation * is currently in portrait mode. */ isPortrait : function(){ return this._mode == "portrait"; }, /** * Manipulates the native event object, adding methods if they're not * already present * * @param event {Event} Native event object * @param element {Element} DOM element the listener was attached to * @param type {String} Event type * @return {Event} Normalized event object * @internal */ normalize : function(event, element, type){ if(!event){ return event; }; event._type = type; var bindMethods = qx.module.event.Orientation.BIND_METHODS; for(var i = 0,l = bindMethods.length;i < l;i++){ if(typeof event[bindMethods[i]] != "function"){ event[bindMethods[i]] = qx.module.event.Orientation[bindMethods[i]].bind(event); }; }; return event; } }, defer : function(statics){ qxWeb.$registerEventNormalization(statics.TYPES, statics.normalize); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /* ************************************************************************ #require(qx.module.Attribute) #require(qx.module.Css) #require(qx.module.Environment) #require(qx.module.Event) #require(qx.module.Manipulating) #require(qx.module.Polyfill) #require(qx.module.Traversing) ************************************************************************ */ /** * Placeholder class which simply defines and includes the core of qxWeb. * The core modules are: * * * {@link qx.module.Attribute} * * {@link qx.module.Css} * * {@link qx.module.Environment} * * {@link qx.module.Event} * * {@link qx.module.Manipulating} * * {@link qx.module.Polyfill} * * {@link qx.module.Traversing} */ qx.Bootstrap.define("qx.module.Core", { }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Daniel Wagner (danielwagner) ************************************************************************ */ /* ************************************************************************ #require(qx.module.Event) #require(qx.module.Environment) ************************************************************************ */ /** * Normalization for native keyboard events */ qx.Bootstrap.define("qx.module.event.Keyboard", { statics : { /** * List of event types to be normalized */ TYPES : ["keydown", "keypress", "keyup"], /** * List qx.module.event.Keyboard methods to be attached to native mouse event * objects * @internal */ BIND_METHODS : ["getKeyIdentifier"], /** * Identifier of the pressed key. This property is modeled after the <em>KeyboardEvent.keyIdentifier</em> property * of the W3C DOM 3 event specification * (http://www.w3.org/TR/2003/NOTE-DOM-Level-3-Events-20031107/events.html#Events-KeyboardEvent-keyIdentifier). * * Printable keys are represented by an unicode string, non-printable keys * have one of the following values: * * <table> * <tr><th>Backspace</th><td>The Backspace (Back) key.</td></tr> * <tr><th>Tab</th><td>The Horizontal Tabulation (Tab) key.</td></tr> * <tr><th>Space</th><td>The Space (Spacebar) key.</td></tr> * <tr><th>Enter</th><td>The Enter key. Note: This key identifier is also used for the Return (Macintosh numpad) key.</td></tr> * <tr><th>Shift</th><td>The Shift key.</td></tr> * <tr><th>Control</th><td>The Control (Ctrl) key.</td></tr> * <tr><th>Alt</th><td>The Alt (Menu) key.</td></tr> * <tr><th>CapsLock</th><td>The CapsLock key</td></tr> * <tr><th>Meta</th><td>The Meta key. (Apple Meta and Windows key)</td></tr> * <tr><th>Escape</th><td>The Escape (Esc) key.</td></tr> * <tr><th>Left</th><td>The Left Arrow key.</td></tr> * <tr><th>Up</th><td>The Up Arrow key.</td></tr> * <tr><th>Right</th><td>The Right Arrow key.</td></tr> * <tr><th>Down</th><td>The Down Arrow key.</td></tr> * <tr><th>PageUp</th><td>The Page Up key.</td></tr> * <tr><th>PageDown</th><td>The Page Down (Next) key.</td></tr> * <tr><th>End</th><td>The End key.</td></tr> * <tr><th>Home</th><td>The Home key.</td></tr> * <tr><th>Insert</th><td>The Insert (Ins) key. (Does not fire in Opera/Win)</td></tr> * <tr><th>Delete</th><td>The Delete (Del) Key.</td></tr> * <tr><th>F1</th><td>The F1 key.</td></tr> * <tr><th>F2</th><td>The F2 key.</td></tr> * <tr><th>F3</th><td>The F3 key.</td></tr> * <tr><th>F4</th><td>The F4 key.</td></tr> * <tr><th>F5</th><td>The F5 key.</td></tr> * <tr><th>F6</th><td>The F6 key.</td></tr> * <tr><th>F7</th><td>The F7 key.</td></tr> * <tr><th>F8</th><td>The F8 key.</td></tr> * <tr><th>F9</th><td>The F9 key.</td></tr> * <tr><th>F10</th><td>The F10 key.</td></tr> * <tr><th>F11</th><td>The F11 key.</td></tr> * <tr><th>F12</th><td>The F12 key.</td></tr> * <tr><th>NumLock</th><td>The Num Lock key.</td></tr> * <tr><th>PrintScreen</th><td>The Print Screen (PrintScrn, SnapShot) key.</td></tr> * <tr><th>Scroll</th><td>The scroll lock key</td></tr> * <tr><th>Pause</th><td>The pause/break key</td></tr> * <tr><th>Win</th><td>The Windows Logo key</td></tr> * <tr><th>Apps</th><td>The Application key (Windows Context Menu)</td></tr> * </table> * * @return {String} The key identifier */ getKeyIdentifier : function(){ if(this.type == "keypress" && (qxWeb.env.get("engine.name") != "gecko" || this.charCode !== 0)){ return qx.event.util.Keyboard.charCodeToIdentifier(this.charCode || this.keyCode); }; return qx.event.util.Keyboard.keyCodeToIdentifier(this.keyCode); }, /** * Manipulates the native event object, adding methods if they're not * already present * * @param event {Event} Native event object * @param element {Element} DOM element the listener was attached to * @return {Event} Normalized event object * @internal */ normalize : function(event, element){ if(!event){ return event; }; var bindMethods = qx.module.event.Keyboard.BIND_METHODS; for(var i = 0,l = bindMethods.length;i < l;i++){ if(typeof event[bindMethods[i]] != "function"){ event[bindMethods[i]] = qx.module.event.Keyboard[bindMethods[i]].bind(event); }; }; return event; }, /** * IE9 will not fire an "input" event on text input elements if the user changes * the field's value by pressing the Backspace key. We fix this by listening * for the "keyup" event and emitting the missing event if necessary * * @param element {Element} Target element */ registerInputFix : function(element){ if(element.type === "text" || element.type === "password" || element.type === "textarea"){ if(!element.__inputFix){ element.__inputFix = qxWeb(element).on("keyup", qx.module.event.Keyboard._inputFix); }; }; }, /** * Removes the IE9 input event fix * @param element {Element} target element */ unregisterInputFix : function(element){ if(element.__inputFix && !qxWeb(element).hasListener("input")){ qxWeb(element).off("keyup", qx.module.event.Keyboard._inputFix); element.__inputFix = null; }; }, /** * IE9 fix: Emits an "input" event if a text input element's value was changed * using the Backspace key * @param ev {Event} Keyup event */ _inputFix : function(ev){ if(ev.getKeyIdentifier() !== "Backspace"){ return; }; var target = ev.getTarget(); var newValue = qxWeb(target).getValue(); if(!target.__oldInputValue || target.__oldInputValue !== newValue){ target.__oldInputValue = newValue; ev.type = ev._type = "input"; target.__emitter.emit("input", ev); }; } }, defer : function(statics){ qxWeb.$registerEventNormalization(qx.module.event.Keyboard.TYPES, statics.normalize); if(qxWeb.env.get("engine.name") === "mshtml" && qxWeb.env.get("browser.documentmode") === 9){ qxWeb.$registerEventHook("input", statics.registerInputFix, statics.unregisterInputFix); }; } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Andreas Ecker (ecker) * Fabian Jakobs (fjakobs) ************************************************************************ */ /** * Utilities for working with character codes and key identifiers */ qx.Bootstrap.define("qx.event.util.Keyboard", { statics : { /* --------------------------------------------------------------------------- KEY MAPS --------------------------------------------------------------------------- */ /** * {Map} maps the charcodes of special printable keys to key identifiers * * @lint ignoreReferenceField(specialCharCodeMap) */ specialCharCodeMap : { '8' : "Backspace", // The Backspace (Back) key. '9' : "Tab", // The Horizontal Tabulation (Tab) key. // Note: This key identifier is also used for the // Return (Macintosh numpad) key. '13' : "Enter", // The Enter key. '27' : "Escape", // The Escape (Esc) key. '32' : "Space" }, /** * {Map} maps the keycodes of the numpad keys to the right charcodes * * @lint ignoreReferenceField(numpadToCharCode) */ numpadToCharCode : { '96' : "0".charCodeAt(0), '97' : "1".charCodeAt(0), '98' : "2".charCodeAt(0), '99' : "3".charCodeAt(0), '100' : "4".charCodeAt(0), '101' : "5".charCodeAt(0), '102' : "6".charCodeAt(0), '103' : "7".charCodeAt(0), '104' : "8".charCodeAt(0), '105' : "9".charCodeAt(0), '106' : "*".charCodeAt(0), '107' : "+".charCodeAt(0), '109' : "-".charCodeAt(0), '110' : ",".charCodeAt(0), '111' : "/".charCodeAt(0) }, /** * {Map} maps the keycodes of non printable keys to key identifiers * * @lint ignoreReferenceField(keyCodeToIdentifierMap) */ keyCodeToIdentifierMap : { '16' : "Shift", // The Shift key. '17' : "Control", // The Control (Ctrl) key. '18' : "Alt", // The Alt (Menu) key. '20' : "CapsLock", // The CapsLock key '224' : "Meta", // The Meta key. (Apple Meta and Windows key) '37' : "Left", // The Left Arrow key. '38' : "Up", // The Up Arrow key. '39' : "Right", // The Right Arrow key. '40' : "Down", // The Down Arrow key. '33' : "PageUp", // The Page Up key. '34' : "PageDown", // The Page Down (Next) key. '35' : "End", // The End key. '36' : "Home", // The Home key. '45' : "Insert", // The Insert (Ins) key. (Does not fire in Opera/Win) '46' : "Delete", // The Delete (Del) Key. '112' : "F1", // The F1 key. '113' : "F2", // The F2 key. '114' : "F3", // The F3 key. '115' : "F4", // The F4 key. '116' : "F5", // The F5 key. '117' : "F6", // The F6 key. '118' : "F7", // The F7 key. '119' : "F8", // The F8 key. '120' : "F9", // The F9 key. '121' : "F10", // The F10 key. '122' : "F11", // The F11 key. '123' : "F12", // The F12 key. '144' : "NumLock", // The Num Lock key. '44' : "PrintScreen", // The Print Screen (PrintScrn, SnapShot) key. '145' : "Scroll", // The scroll lock key '19' : "Pause", // The pause/break key // The left Windows Logo key or left cmd key '91' : qx.core.Environment.get("os.name") == "osx" ? "cmd" : "Win", '92' : "Win", // The right Windows Logo key or left cmd key // The Application key (Windows Context Menu) or right cmd key '93' : qx.core.Environment.get("os.name") == "osx" ? "cmd" : "Apps" }, /** char code for capital A */ charCodeA : "A".charCodeAt(0), /** char code for capital Z */ charCodeZ : "Z".charCodeAt(0), /** char code for 0 */ charCode0 : "0".charCodeAt(0), /** char code for 9 */ charCode9 : "9".charCodeAt(0), /** * converts a keyboard code to the corresponding identifier * * @param keyCode {Integer} key code * @return {String} key identifier */ keyCodeToIdentifier : function(keyCode){ if(this.isIdentifiableKeyCode(keyCode)){ var numPadKeyCode = this.numpadToCharCode[keyCode]; if(numPadKeyCode){ return String.fromCharCode(numPadKeyCode); }; return (this.keyCodeToIdentifierMap[keyCode] || this.specialCharCodeMap[keyCode] || String.fromCharCode(keyCode)); } else { return "Unidentified"; }; }, /** * converts a character code to the corresponding identifier * * @param charCode {String} character code * @return {String} key identifier */ charCodeToIdentifier : function(charCode){ return this.specialCharCodeMap[charCode] || String.fromCharCode(charCode).toUpperCase(); }, /** * Check whether the keycode can be reliably detected in keyup/keydown events * * @param keyCode {String} key code to check. * @return {Boolean} Whether the keycode can be reliably detected in keyup/keydown events. */ isIdentifiableKeyCode : function(keyCode){ // A-Z (TODO: is this lower or uppercase?) if(keyCode >= this.charCodeA && keyCode <= this.charCodeZ){ return true; }; // 0-9 if(keyCode >= this.charCode0 && keyCode <= this.charCode9){ return true; }; // Enter, Space, Tab, Backspace if(this.specialCharCodeMap[keyCode]){ return true; }; // Numpad if(this.numpadToCharCode[keyCode]){ return true; }; // non printable keys if(this.isNonPrintableKeyCode(keyCode)){ return true; }; return false; }, /** * Checks whether the keyCode represents a non printable key * * @param keyCode {String} key code to check. * @return {Boolean} Whether the keyCode represents a non printable key. */ isNonPrintableKeyCode : function(keyCode){ return this.keyCodeToIdentifierMap[keyCode] ? true : false; }, /** * Checks whether a given string is a valid keyIdentifier * * @param keyIdentifier {String} The key identifier. * @return {Boolean} whether the given string is a valid keyIdentifier */ isValidKeyIdentifier : function(keyIdentifier){ if(this.identifierToKeyCodeMap[keyIdentifier]){ return true; }; if(keyIdentifier.length != 1){ return false; }; if(keyIdentifier >= "0" && keyIdentifier <= "9"){ return true; }; if(keyIdentifier >= "A" && keyIdentifier <= "Z"){ return true; }; switch(keyIdentifier){case "+":case "-":case "*":case "/": return true;default: return false;}; }, /** * Checks whether a given string is a printable keyIdentifier. * * @param keyIdentifier {String} The key identifier. * @return {Boolean} whether the given string is a printable keyIdentifier. */ isPrintableKeyIdentifier : function(keyIdentifier){ if(keyIdentifier === "Space"){ return true; } else { return this.identifierToKeyCodeMap[keyIdentifier] ? false : true; }; } }, defer : function(statics, members){ // construct inverse of keyCodeToIdentifierMap if(!statics.identifierToKeyCodeMap){ statics.identifierToKeyCodeMap = { }; for(var key in statics.keyCodeToIdentifierMap){ statics.identifierToKeyCodeMap[statics.keyCodeToIdentifierMap[key]] = parseInt(key, 10); }; for(var key in statics.specialCharCodeMap){ statics.identifierToKeyCodeMap[statics.specialCharCodeMap[key]] = parseInt(key, 10); }; }; } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Andreas Ecker (ecker) ************************************************************************ */ /** * A wrapper for Cookie handling. */ qx.Bootstrap.define("qx.bom.Cookie", { /* ***************************************************************************** STATICS ***************************************************************************** */ statics : { /* --------------------------------------------------------------------------- USER APPLICATION METHODS --------------------------------------------------------------------------- */ /** * Returns the string value of a cookie. * * @param key {String} The key for the saved string value. * @return {null | String} Returns the saved string value, if the cookie * contains a value for the key, <code>null</code> otherwise. */ get : function(key){ var start = document.cookie.indexOf(key + "="); var len = start + key.length + 1; if((!start) && (key != document.cookie.substring(0, key.length))){ return null; }; if(start == -1){ return null; }; var end = document.cookie.indexOf(";", len); if(end == -1){ end = document.cookie.length; }; return unescape(document.cookie.substring(len, end)); }, /** * Sets the string value of a cookie. * * @param key {String} The key for the string value. * @param value {String} The string value. * @param expires {Number?null} The expires in days starting from now, * or <code>null</code> if the cookie should deleted after browser close. * @param path {String?null} Path value. * @param domain {String?null} Domain value. * @param secure {Boolean?null} Secure flag. */ set : function(key, value, expires, path, domain, secure){ // Generate cookie var cookie = [key, "=", escape(value)]; if(expires){ var today = new Date(); today.setTime(today.getTime()); cookie.push(";expires=", new Date(today.getTime() + (expires * 1000 * 60 * 60 * 24)).toGMTString()); }; if(path){ cookie.push(";path=", path); }; if(domain){ cookie.push(";domain=", domain); }; if(secure){ cookie.push(";secure"); }; // Store cookie document.cookie = cookie.join(""); }, /** * Deletes the string value of a cookie. * * @param key {String} The key for the string value. * @param path {String?null} Path value. * @param domain {String?null} Domain value. */ del : function(key, path, domain){ if(!qx.bom.Cookie.get(key)){ return; }; // Generate cookie var cookie = [key, "="]; if(path){ cookie.push(";path=", path); }; if(domain){ cookie.push(";domain=", domain); }; cookie.push(";expires=Thu, 01-Jan-1970 00:00:01 GMT"); // Store cookie document.cookie = cookie.join(""); } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Daniel Wagner (danielwagner) ************************************************************************ */ /** * Cookie handling module */ qx.Bootstrap.define("qx.module.Cookie", { statics : { /** * Returns the string value of a cookie. * * @attachStatic {qxWeb, cookie.get} * @param key {String} The key for the saved string value. * @return {String|null} Returns the saved string value if the cookie * contains a value for the key, otherwise <code>null</code> * @signature function(key) */ get : qx.bom.Cookie.get, /** * Sets the string value of a cookie. * * @attachStatic {qxWeb, cookie.set} * @param key {String} The key for the string value. * @param value {String} The string value. * @param expires {Number?null} Expires directive value in days starting from now, * or <code>null</code> if the cookie should be deleted when the browser * is closed. * @param path {String?null} Path value. * @param domain {String?null} Domain value. * @param secure {Boolean?null} Secure flag. * @signature function(key, value, expires, path, domain, secure) */ set : qx.bom.Cookie.set, /** * Deletes the string value of a cookie. * * @attachStatic {qxWeb, cookie.del} * @param key {String} The key for the string value. * @param path {String?null} Path value. * @param domain {String?null} Domain value. * @signature function(key, path, domain) */ del : qx.bom.Cookie.del }, defer : function(statics){ qxWeb.$attachStatic({ "cookie" : { get : statics.get, set : statics.set, del : statics.del } }); } }); var exp = envinfo["qx.export"]; if (exp) { for (var name in exp) { var c = exp[name].split("."); var root = window; for (var i=0; i < c.length; i++) { root = root[c[i]]; }; window[name] = root; } } window["qx"] = undefined; try { delete window.qx; } catch(e) {} })();
components/menu/MenuDivider.js
jasonleibowitz/react-toolbox
import React from 'react'; import PropTypes from 'prop-types'; import { themr } from 'react-css-themr'; import { MENU } from '../identifiers.js'; const MenuDivider = ({ theme }) => ( <hr data-react-toolbox='menu-divider' className={theme.menuDivider}/> ); MenuDivider.propTypes = { theme: PropTypes.shape({ menuDivider: PropTypes.string }) }; export default themr(MENU)(MenuDivider); export { MenuDivider };
vitrail_tests/test_vitrail.js
CANTUS-Project/vitrail
// -*- coding: utf-8 -*- // ------------------------------------------------------------------------------------------------ // Program Name: vitrail // Program Description: HTML/CSS/JavaScript user agent for the Cantus API. // // Filename: vitrail_tests/test_onebox.js // Purpose: Tests for the OneboxSearch (and related) React components. // // Copyright (C) 2016 Christopher Antila // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // 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 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 init from '../js/nuclear/init'; import {mount, shallow} from 'enzyme'; import {Immutable} from 'nuclear-js'; import React from 'react'; import Alert from 'react-bootstrap/lib/Alert'; import Panel from 'react-bootstrap/lib/Panel'; import Table from 'react-bootstrap/lib/Table'; // import {getters} from '../js/nuclear/getters'; // import reactor from '../js/nuclear/reactor'; // import ResultList from '../js/react/result_list'; // import {SIGNALS as signals} from '../js/nuclear/signals'; jest.dontMock('../js/react/vitrail.js'); // module under test const vitrail = require('../js/react/vitrail.js').MODULE_FOR_TESTING; describe('AlertView', () => { it('renders properly', () => { const classProp = 'success'; const children = 'rawr!'; const actual = shallow(<vitrail.AlertView class={classProp}>{children}</vitrail.AlertView>); expect(actual.type()).toBe(Panel); expect(actual.childAt(0).type()).toBe(Alert); expect(actual.childAt(0).prop('bsStyle')).toBe(classProp); expect(actual.childAt(0).children().text()).toBe(children); expect(actual.childAt(1).type()).toBe(vitrail.AlertFieldList); }); }); describe('AlertFieldList', () => { it('renders when no fields are given', () => { const actual = shallow(<vitrail.AlertFieldList/>); expect(actual.html()).toBe(null); }); it('renders when three fields are given', () => { const fields = Immutable.Map({ 'Power Rating': '20-275W', 'Frequency Response': '30Hz-25kHz', 'Nominal Impedance': '8 Ohms', }); const actual = shallow(<vitrail.AlertFieldList fields={fields}/>); expect(actual.type()).toBe(Table); expect(actual.childAt(0).type()).toBe('tbody'); const rows = actual.find('tr'); expect(rows.length).toBe(3); rows.forEach((row) => { const key = row.childAt(0).text().slice(0, -1); expect(fields.get(key)).toEqual(row.childAt(1).text()); }); }); });
index.ios.js
keske/react-native-easy-gestures
import React, { Component } from 'react'; import { AppRegistry, Image, View } from 'react-native'; import Gestures from './lib'; const photo = require('./static/photo.jpg'); export default class Example extends Component { render() { return ( <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center', }} > <Gestures ref={(c) => { this.gestures = c; }} onStart={(event, styles) => { // console.log('On Start'); }} onChange={(event, styles) => { // console.log('On change'); }} onEnd={(event, styles) => { // console.log('On End'); }} onMultyTouchStart={(event, styles) => { // console.log('On MultyTouch Start'); }} onMultyTouchChange={(event, styles) => { // console.log('On MultyTouch change'); }} onMultyTouchEnd={(event, styles) => { // console.log('On MultyTouch End'); }} onRotateStart={(event, styles) => { // console.log('On Rotate Start'); }} onRotateChange={(event, styles) => { // console.log('On Rotate Change'); }} onRotateEnd={(event, styles) => { // console.log('On Rotate End'); }} onScaleStart={(event, styles) => { // console.log('On Scale Start'); }} onScaleChange={(event, styles) => { // console.log('On Scale Change'); }} onScaleEnd={(event, styles) => { // console.log('On Scale End'); }} style={{ left: 0, top: 0, }} > <Image source={photo} style={{ width: 300, height: 400, }} /> </Gestures> </View> ); } } AppRegistry.registerComponent('GesturesExample', () => Example);
node_modules/react-bootstrap/es/CarouselItem.js
caughtclean/but-thats-wrong-blog
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import ReactDOM from 'react-dom'; import TransitionEvents from './utils/TransitionEvents'; // TODO: This should use a timeout instead of TransitionEvents, or else just // not wait until transition end to trigger continuing animations. var propTypes = { direction: React.PropTypes.oneOf(['prev', 'next']), onAnimateOutEnd: React.PropTypes.func, active: React.PropTypes.bool, animateIn: React.PropTypes.bool, animateOut: React.PropTypes.bool, index: React.PropTypes.number }; var defaultProps = { active: false, animateIn: false, animateOut: false }; var CarouselItem = function (_React$Component) { _inherits(CarouselItem, _React$Component); function CarouselItem(props, context) { _classCallCheck(this, CarouselItem); var _this = _possibleConstructorReturn(this, _React$Component.call(this, props, context)); _this.handleAnimateOutEnd = _this.handleAnimateOutEnd.bind(_this); _this.state = { direction: null }; _this.isUnmounted = false; return _this; } CarouselItem.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) { if (this.props.active !== nextProps.active) { this.setState({ direction: null }); } }; CarouselItem.prototype.componentDidUpdate = function componentDidUpdate(prevProps) { var _this2 = this; var active = this.props.active; var prevActive = prevProps.active; if (!active && prevActive) { TransitionEvents.addEndEventListener(ReactDOM.findDOMNode(this), this.handleAnimateOutEnd); } if (active !== prevActive) { setTimeout(function () { return _this2.startAnimation(); }, 20); } }; CarouselItem.prototype.componentWillUnmount = function componentWillUnmount() { this.isUnmounted = true; }; CarouselItem.prototype.handleAnimateOutEnd = function handleAnimateOutEnd() { if (this.isUnmounted) { return; } if (this.props.onAnimateOutEnd) { this.props.onAnimateOutEnd(this.props.index); } }; CarouselItem.prototype.startAnimation = function startAnimation() { if (this.isUnmounted) { return; } this.setState({ direction: this.props.direction === 'prev' ? 'right' : 'left' }); }; CarouselItem.prototype.render = function render() { var _props = this.props, direction = _props.direction, active = _props.active, animateIn = _props.animateIn, animateOut = _props.animateOut, className = _props.className, props = _objectWithoutProperties(_props, ['direction', 'active', 'animateIn', 'animateOut', 'className']); delete props.onAnimateOutEnd; delete props.index; var classes = { item: true, active: active && !animateIn || animateOut }; if (direction && active && animateIn) { classes[direction] = true; } if (this.state.direction && (animateIn || animateOut)) { classes[this.state.direction] = true; } return React.createElement('div', _extends({}, props, { className: classNames(className, classes) })); }; return CarouselItem; }(React.Component); CarouselItem.propTypes = propTypes; CarouselItem.defaultProps = defaultProps; export default CarouselItem;
frontend/src/components/TongueTwisterView.js
ttang02/tongue-twister
import React, { Component } from 'react'; export default class TongueTwisterView extends Component{ }
src/svg-icons/editor/merge-type.js
rhaedes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorMergeType = (props) => ( <SvgIcon {...props}> <path d="M17 20.41L18.41 19 15 15.59 13.59 17 17 20.41zM7.5 8H11v5.59L5.59 19 7 20.41l6-6V8h3.5L12 3.5 7.5 8z"/> </SvgIcon> ); EditorMergeType = pure(EditorMergeType); EditorMergeType.displayName = 'EditorMergeType'; export default EditorMergeType;
actor-apps/app-web/src/app/components/Deactivated.react.js
zwensoft/actor-platform
import React from 'react'; class Deactivated extends React.Component { render() { return ( <div className="deactivated row center-xs middle-xs"> <div className="deactivated__window"> <h2>Tab deactivated</h2> <p> Oops, you have opened another tab with Actor, so we had to deactivate this one to prevent some dangerous things happening. </p> </div> </div> ); } } export default Deactivated;
nlyyAPP/component/受试者随机/登记受试者/MLDjssz.js
a497500306/nlyy_APP
import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View, TouchableOpacity, Navigator, ListView, Alert, DatePickerAndroid, TouchableHighlight, DatePickerIOS, Picker, ActivityIndicator, } from 'react-native'; //时间操作 var moment = require('moment'); moment().format(); import Pickers from 'react-native-picker'; // var Modal = require('react-native-modal'); var Users = require('../../../entity/Users') var MLModal = require('../../MLModal/MLModal'); var study = require('../../../entity/study'); var Dimensions = require('Dimensions'); var {width, height} = Dimensions.get('window'); var settings = require('../../../settings'); var MLNavigatorBar = require('../../MLNavigatorBar/MLNavigatorBar'); var researchParameter = require('../../../entity/researchParameter'); var MLTableCell = require('../../MLTableCell/MLTableCell'); // var XzsxcgsszQR = require('./MLXzsxcgsszQR') var DjsszQR = require('./MLDjsszQR') var Xzsxcgssz = React.createClass({ getInitialState() { var UserSite = ''; for (var i = 0 ; i < Users.Users.length ; i++) { if (Users.Users[i].UserSite != null) { if (Users.Users[i].UserFun == 'H2' || Users.Users[i].UserFun == 'H3' || Users.Users[i].UserFun == 'S1' ){ UserSite = Users.Users[i].UserSite } } } console.log('123123'); console.log(Users.Users); console.log(UserSite); var tableData = []; tableData.push('受试者出生日期') tableData.push('受试者性别') tableData.push('受试者姓名缩写') tableData.push('受试者手机号') var isShowZhongXin = false; if (UserSite.indexOf(',') != -1){ isShowZhongXin = true; tableData.push('中心') }else { if (researchParameter.researchParameter.LabelStraI != null){ isShowZhongXin = true; tableData.push(researchParameter.researchParameter.LabelStraI != null ? researchParameter.researchParameter.LabelStraI : '中心') } } tableData.push('') //ListView设置 var ds = new ListView.DataSource({rowHasChanged:(r1, r2) => r1 !== r2}); let date = []; for(let i=1900;i<2050;i++){ let month = []; for(let j = 1;j<13;j++){ let day = []; if(j === 2){ for(let k=1;k<29;k++){ day.push(k); } } else if(j in {1:1, 3:1, 5:1, 7:1, 8:1, 10:1, 12:1}){ for(let k=1;k<32;k++){ day.push(k); } } else{ for(let k=1;k<31;k++){ day.push(k); } } let _month = {}; _month[j] = day; month.push(_month); } let _date = {}; _date[i] = month; date.push(_date); } return { tableData:tableData, //ListView设置 dataSource: ds.cloneWithRows(tableData), //ListView设置 animating: false, //是否显示选择器 isLanguage : false, //选择器默认选择值 language:'', //选择器内容数组 languages:['javar','jss'], date : date, //出生年月 csDate:'', //受试者性别 xb:'', //输入的第几个 shuru:0, //姓名缩写 name:'', //受试者手机号 phone:'', LabelStraI:UserSite, newLabelStraI : UserSite.indexOf(',') != -1 ? '' : UserSite, isShowZhongXin:isShowZhongXin, //是否显示moda isModalOpen:false, //输入框显示文字 srkxswz:[''] } }, closeModal() { this.setState({isModalOpen: false}); }, render() { console.log('researchParameter.researchParameter') console.log(researchParameter.researchParameter) if (this.state.isLanguage == false){ return ( <View style={styles.container}> <MLNavigatorBar title={'新登记受试者'} isBack={true} backFunc={() => { Pickers.hide(); this.props.navigator.pop() }}/> <ListView dataSource={this.state.dataSource}//数据源 renderRow={this.renderRow} /> {/*<Modal isVisible={this.state.isModalOpen} onClose={() => this.closeModal()}>*/} {/*<Text>Hello world!</Text>*/} {/*</Modal>*/} <MLModal placeholders={this.state.srkxswz} isVisible={this.state.isModalOpen} onClose={(text) => { //ListView设置 var ds = new ListView.DataSource({rowHasChanged:(r1, r2) => r1 !== r2}); if (this.state.shuru == 0){ this.setState({name:text,dataSource: ds.cloneWithRows(this.state.tableData),isModalOpen:false,srkxswz:['受试者姓名缩写']}) }else{ this.setState({phone:text,dataSource: ds.cloneWithRows(this.state.tableData),isModalOpen:false,srkxswz:['受试者姓名缩写']}) } }} quxiao={(text) => { this.setState({isModalOpen:false,srkxswz:['受试者姓名缩写']}) }}>></MLModal> </View> ); }else{ return ( <View style={styles.container}> <MLNavigatorBar title={'新登记受试者'} isBack={true} backFunc={() => { this.props.navigator.pop() }}/> <ListView dataSource={this.state.dataSource}//数据源 renderRow={this.renderRow} /> <MLModal placeholders={this.state.srkxswz} isVisible={this.state.isModalOpen} onClose={(text) => { //ListView设置 var ds = new ListView.DataSource({rowHasChanged:(r1, r2) => r1 !== r2}); if (this.state.shuru == 0){ this.setState({name:text,dataSource: ds.cloneWithRows(this.state.tableData),isModalOpen:false,srkxswz:['受试者姓名缩写']}) }else{ this.setState({phone:text,dataSource: ds.cloneWithRows(this.state.tableData),isModalOpen:false,srkxswz:['受试者姓名缩写']}) } }} quxiao={(text) => { this.setState({isModalOpen:false,srkxswz:['受试者姓名缩写如ZHY、Z-Y']}) }}>></MLModal> <View style={{position:'absolute', right:0, bottom:0, width:width, height:height, backgroundColor:'rgba(0,0,0,0.5)'}}> <Picker selectedValue={this.state.language} onValueChange={(lang) => this.setState({language: lang})}> {this.PickerItem()} </Picker> </View> </View> ); } }, PickerItem(){ var views = []; for (var i = 0 ; i < this.state.languages.length ; i++) { views.push(<Picker.Item label={this.state.languages[i]} key={i} value="java" />) } return views // <Picker.Item label="Java" value="java" /> // <Picker.Item label="JavaScript" value="js" /> }, //返回具体的cell renderRow(rowData){ //选择 if (rowData == (researchParameter.researchParameter.LabelStraI != null ? researchParameter.researchParameter.LabelStraI : '中心')){ if (this.state.isShowZhongXin == true) { if (this.state.LabelStraI.indexOf(',') != -1) {//需要选择中心 var sites = this.state.LabelStraI.split(","); return ( <TouchableOpacity onPress={() => { Pickers.init({ pickerData: sites, onPickerConfirm: pickedValue => { //ListView设置 var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}); this.setState({ newLabelStraI: pickedValue[0], LabelStraI: pickedValue[0], dataSource: ds.cloneWithRows(this.state.tableData), }) }, onPickerCancel: pickedValue => { //ListView设置 var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}); this.setState({ newLabelStraI: pickedValue[0], LabelStraI: pickedValue[0], dataSource: ds.cloneWithRows(this.state.tableData), }) }, onPickerSelect: pickedValue => { } }); Pickers.show(); }}> <MLTableCell title={'中心'} rightTitle={this.state.newLabelStraI} isArrow={true}/> </TouchableOpacity> ) } else {//不需要选择中心 return ( <MLTableCell title={'中心'} rightTitle={this.state.newLabelStraI} isArrow={false}/> ) } } } // if (researchParameter.researchParameter.LabelStraI != null){ // if (rowData == researchParameter.researchParameter.LabelStraI){ // if (this.state.LabelStraI.indexOf(',') != -1 ){ // var sites = this.state.LabelStraI.split(","); // return( // <TouchableOpacity onPress={()=>{ // Pickers.init({ // pickerData: sites, // onPickerConfirm: pickedValue => { // //ListView设置 // var ds = new ListView.DataSource({rowHasChanged:(r1, r2) => r1 !== r2}); // this.setState({newLabelStraI:pickedValue[0],LabelStraI:pickedValue[0],dataSource: ds.cloneWithRows(this.state.tableData),}) // // }, // onPickerCancel: pickedValue => { // //ListView设置 // var ds = new ListView.DataSource({rowHasChanged:(r1, r2) => r1 !== r2}); // this.setState({newLabelStraI:pickedValue[0],LabelStraI:pickedValue[0],dataSource: ds.cloneWithRows(this.state.tableData),}) // }, // onPickerSelect: pickedValue => { // } // }); // Pickers.show(); // }}> // <MLTableCell title={rowData} rightTitle={this.state.newLabelStraI} isArrow={true}/> // </TouchableOpacity> // ) // }else { // return( // <MLTableCell title={rowData} rightTitle={this.state.newLabelStraI} isArrow={false}/> // ) // } // } // }else if (this.state.newLabelStraI != '' && researchParameter.researchParameter.LabelStraI != null){ // var sites = this.state.LabelStraI.split(","); // return( // <TouchableOpacity onPress={()=>{ // Pickers.init({ // pickerData: sites, // onPickerConfirm: pickedValue => { // //ListView设置 // var ds = new ListView.DataSource({rowHasChanged:(r1, r2) => r1 !== r2}); // this.setState({newLabelStraI:pickedValue[0],dataSource: ds.cloneWithRows(this.state.tableData),}) // // }, // onPickerCancel: pickedValue => { // //ListView设置 // var ds = new ListView.DataSource({rowHasChanged:(r1, r2) => r1 !== r2}); // this.setState({newLabelStraI:pickedValue[0],dataSource: ds.cloneWithRows(this.state.tableData),}) // }, // onPickerSelect: pickedValue => { // } // }); // Pickers.show(); // }}> // <MLTableCell title={rowData} rightTitle={this.state.newLabelStraI} isArrow={true}/> // </TouchableOpacity> // ) // } /*************/ if(rowData == "受试者出生日期") { return( <TouchableOpacity onPress={()=>{ Pickers.init({ pickerData: this.state.date, selectedValue: [1960,1,1], onPickerConfirm: pickedValue => { //ListView设置 var ds = new ListView.DataSource({rowHasChanged:(r1, r2) => r1 !== r2}); this.setState({csDate:pickedValue[0] + '/' + pickedValue[1]+ '/' + pickedValue[2],dataSource: ds.cloneWithRows(this.state.tableData),}) }, onPickerCancel: pickedValue => { //ListView设置 var ds = new ListView.DataSource({rowHasChanged:(r1, r2) => r1 !== r2}); this.setState({csDate:'',dataSource: ds.cloneWithRows(this.state.tableData),}) }, onPickerSelect: pickedValue => { } }); Pickers.show(); }}> <MLTableCell title={rowData} rightTitle={this.state.csDate}/> </TouchableOpacity> ) } if(rowData == "受试者性别") { return( <TouchableOpacity onPress={()=>{ var data = ['男','女']; Pickers.init({ pickerData: data, selectedValue: ['男'], onPickerConfirm: pickedValue => { //ListView设置 var ds = new ListView.DataSource({rowHasChanged:(r1, r2) => r1 !== r2}); this.setState({xb:pickedValue[0],dataSource: ds.cloneWithRows(this.state.tableData),}) }, onPickerCancel: pickedValue => { //ListView设置 var ds = new ListView.DataSource({rowHasChanged:(r1, r2) => r1 !== r2}); this.setState({xb:'',dataSource: ds.cloneWithRows(this.state.tableData),}) }, onPickerSelect: pickedValue => { console.log('area', pickedValue[0]); } }); Pickers.show(); }}> <MLTableCell title={rowData} rightTitle={this.state.xb}/> </TouchableOpacity> ) } if (rowData == '受试者姓名缩写'){ return( <TouchableOpacity onPress={()=>{ Pickers.hide(); this.setState({isModalOpen:true,srkxswz:['受试者姓名缩写'],shuru:0}) }}> <MLTableCell title={rowData} rightTitle={this.state.name}/> </TouchableOpacity> ) } if (rowData == '受试者手机号'){ return( <TouchableOpacity onPress={()=>{ Pickers.hide(); this.setState({isModalOpen:true,srkxswz:['受试者手机号'],shuru:1}) }}> <MLTableCell title={rowData} rightTitle={this.state.phone}/> </TouchableOpacity> ) } if (rowData == ''){ return( <View> <TouchableOpacity style={styles.dengluBtnStyle} onPress={this.getLogin}> <Text style={{color:'white',fontSize: 14,marginLeft:15}}> 确 定 </Text> <ActivityIndicator animating={this.state.animating} style={[styles.centering, {height: 30}]} size="small" color="white" /> </TouchableOpacity> </View> ) } return( <MLTableCell title={rowData+'123'}/> ) }, IsNum(s) { if(s!=null){ var r,re; re = /\d*/i; //\d表示数字,*表示匹配多个数字 r = s.match(re); return (r==s)?true:false; } return false; }, getLogin(){ if (this.state.csDate.length == 0){ //错误 Alert.alert( '出生年月为空', null, [ {text: '确定'} ] ) return } if (this.state.newLabelStraI == ''){ //错误 Alert.alert( '提示', '没有选择中心', [ {text: '确定'} ] ) return } if (this.state.xb.length == 0){ //错误 Alert.alert( '性别为空', null, [ {text: '确定'} ] ) return } if (this.state.name.length == 0){ //错误 Alert.alert( '姓名缩写为空', null, [ {text: '确定'} ] ) return } // if (this.state.phone.length != 11){ // //错误 // Alert.alert( // '请输入正确的手机号', // null, // [ // {text: '确定'} // ] // ) // return // }else if (/^\d+$/.test(this.state.phone) == false){ // //判断是否为数字 // //错误 // Alert.alert( // '请输入正确的手机号', // null, // [ // {text: '确定'} // ] // ) // return // } this.setState({ animating: true }) var UserSite = ''; for (var i = 0 ; i < Users.Users.length ; i++) { if (Users.Users[i].UserSite != null) { UserSite = Users.Users[i].UserSite } } //获取中心数据网络请求 fetch(settings.fwqUrl + "/app/getSingleSite", { method: 'POST', headers: { 'Accept': 'application/json; charset=utf-8', 'Content-Type': 'application/json', }, body: JSON.stringify({ StudyID: Users.Users[0].StudyID, UserSite:this.state.newLabelStraI }) }) .then((response) => response.json()) .then((responseJson) => { this.setState({ animating: false }) if (responseJson.isSucceed == 200){ //错误 Alert.alert( responseJson.msg, null, [ {text: '确定'} ] ) }else { console.log(responseJson) // 页面的切换 this.props.navigator.push({ component: DjsszQR, // 具体路由的版块 //传递参数 passProps:{ //出生年月 csDate:this.state.csDate, //受试者性别 xb:this.state.xb, //姓名缩写 name:this.state.name, //受试者手机号 phone:this.state.phone, //是否参加子研究 zyj:this.state.zyj, newLabelStraI:this.state.newLabelStraI, //中心数据 site:responseJson.site } }); } }) .catch((error) => {//错误 this.setState({ animating: false }) this.setState({animating:false}); console.log(error), //错误 Alert.alert( '请检查您的网络111', null, [ {text: '确定'} ] ) }); }, }); const styles = StyleSheet.create({ container: { flex: 1, // justifyContent: 'center', // alignItems: 'center', backgroundColor: 'rgba(233,234,239,1.0)', }, xiantiaoViewStyle:{ width: 42, backgroundColor: 'white', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, zongView: { backgroundColor: 'white', // 设置主轴的方向 flexDirection:'row', // 垂直居中 ---> 设置侧轴的对齐方式 alignItems:'center' }, dengluBtnStyle:{ // 设置主轴的方向 flexDirection:'row', // 垂直居中 ---> 设置侧轴的对齐方式 alignItems:'center', // 设置主轴的对齐方式 justifyContent:'center', width:width - 40, marginTop:20, marginLeft:20, height:40, backgroundColor:'rgba(0,136,212,1.0)', // 设置圆角 borderRadius:5, }, }); // 输出组件类 module.exports = Xzsxcgssz;
files/angularjs/1.0.2/angular-scenario.js
jtblin/jsdelivr
/*! * jQuery JavaScript Library v1.7.2 * http://jquery.com/ * * Copyright 2011, John Resig * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * Includes Sizzle.js * http://sizzlejs.com/ * Copyright 2011, The Dojo Foundation * Released under the MIT, BSD, and GPL Licenses. * * Date: Wed Mar 21 12:46:34 2012 -0700 */ (function( window, undefined ) { 'use strict'; // 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.2", // The default length of a jQuery object is 0 length: 0, // The number of elements contained in the matched element set size: function() { return this.length; }, toArray: function() { return slice.call( this, 0 ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num == null ? // Return a 'clean' array this.toArray() : // Return just the object ( num < 0 ? this[ 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"; }, isWindow: function( obj ) { return obj != null && obj == obj.window; }, 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 ) { if ( typeof data !== "string" || !data ) { return null; } 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, fn, key, value, chainable, emptyGet, pass ) { var exec, bulk = key == null, i = 0, length = elems.length; // Sets many values if ( key && typeof key === "object" ) { for ( i in key ) { jQuery.access( elems, fn, i, key[i], 1, emptyGet, value ); } chainable = 1; // Sets one value } else if ( value !== undefined ) { // Optionally, function values get executed if exec is true exec = pass === undefined && jQuery.isFunction( value ); if ( bulk ) { // Bulk operations only iterate when executing function values if ( exec ) { exec = fn; fn = function( elem, key, value ) { return exec.call( jQuery( elem ), value ); }; // Otherwise they run against the entire set } else { fn.call( elems, value ); fn = null; } } if ( fn ) { for (; i < length; i++ ) { fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass ); } } chainable = 1; } return chainable ? elems : // Gets bulk ? fn.call( elems ) : length ? fn( elems[0], key ) : emptyGet; }, 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 was already fired fired, // Flag to know if list is currently firing firing, // First callback to fire (used internally by add and fireWith) firingStart, // End of the loop when firing firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, // 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 ]; fired = true; 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 !!fired; } }; 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, 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, pixelMargin: true }; // jQuery.boxModel DEPRECATED in 1.3, use jQuery.support.boxModel instead jQuery.boxModel = support.boxModel = (document.compatMode === "CSS1Compat"); // 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"); // #11217 - WebKit loses check when the name is after the checked attribute input.setAttribute( "name", "t" ); 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 ); // 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 = div = input = null; // Run tests that need a body at doc ready jQuery(function() { var container, outer, inner, table, td, offsetSupport, marginDiv, conMarginTop, style, html, positionTopLeftWidthHeight, paddingMarginBorderVisibility, paddingMarginBorder, body = document.getElementsByTagName("body")[0]; if ( !body ) { // Return for frameset docs that don't have a body return; } conMarginTop = 1; paddingMarginBorder = "padding:0;margin:0;border:"; positionTopLeftWidthHeight = "position:absolute;top:0;left:0;width:1px;height:1px;"; paddingMarginBorderVisibility = paddingMarginBorder + "0;visibility:hidden;"; style = "style='" + positionTopLeftWidthHeight + paddingMarginBorder + "5px solid #000;"; html = "<div " + style + "display:block;'><div style='" + paddingMarginBorder + "0;display:block;overflow:hidden;'></div></div>" + "<table " + style + "' cellpadding='0' cellspacing='0'>" + "<tr><td></td></tr></table>"; container = document.createElement("div"); container.style.cssText = paddingMarginBorderVisibility + "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='" + paddingMarginBorder + "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 ); // 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 ) { div.innerHTML = ""; 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; } 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.innerHTML = ""; div.style.width = div.style.padding = "1px"; div.style.border = 0; div.style.overflow = "hidden"; div.style.display = "inline"; div.style.zoom = 1; support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 ); // Check if elements with layout shrink-wrap their children // (IE 6 does this) div.style.display = "block"; div.style.overflow = "visible"; div.innerHTML = "<div style='width:5px;'></div>"; support.shrinkWrapBlocks = ( div.offsetWidth !== 3 ); } div.style.cssText = positionTopLeftWidthHeight + paddingMarginBorderVisibility; 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 ); if ( window.getComputedStyle ) { div.style.marginTop = "1%"; support.pixelMargin = ( window.getComputedStyle( div, null ) || { marginTop: 0 } ).marginTop !== "1%"; } if ( typeof container.style.zoom !== "undefined" ) { container.style.zoom = 1; } body.removeChild( container ); marginDiv = 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, part, attr, name, l, elem = this[0], i = 0, data = null; // Gets all values if ( key === undefined ) { if ( this.length ) { data = jQuery.data( elem ); if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) { attr = elem.attributes; for ( l = attr.length; i < l; i++ ) { name = attr[i].name; if ( name.indexOf( "data-" ) === 0 ) { name = jQuery.camelCase( name.substring(5) ); dataAttr( elem, name, data[ name ] ); } } jQuery._data( elem, "parsedAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each(function() { jQuery.data( this, key ); }); } parts = key.split( ".", 2 ); parts[1] = parts[1] ? "." + parts[1] : ""; part = parts[1] + "!"; return jQuery.access( this, function( value ) { if ( value === undefined ) { data = this.triggerHandler( "getData" + part, [ parts[0] ] ); // Try to fetch any internally stored data first if ( data === undefined && elem ) { data = jQuery.data( elem, key ); data = dataAttr( elem, key, data ); } return data === undefined && parts[1] ? this.data( parts[0] ) : data; } parts[1] = value; this.each(function() { var self = jQuery( this ); self.triggerHandler( "setData" + part, parts ); jQuery.data( this, key, value ); self.triggerHandler( "changeData" + part, parts ); }); }, null, value, arguments.length > 1, null, false ); }, 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 ) ? +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 ) { var setter = 2; if ( typeof type !== "string" ) { data = type; type = "fx"; setter--; } if ( arguments.length < setter ) { return jQuery.queue( this[0], type ); } return data === undefined ? this : this.each(function() { var queue = jQuery.queue( this, type, data ); 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( object ); } }); 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, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each(function() { jQuery.removeAttr( this, name ); }); }, prop: function( name, value ) { return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 ); }, removeProp: function( name ) { name = jQuery.propFix[ name ] || name; return this.each(function() { // try/catch handles cases where IE balks (such as removing a property on window) try { this[ name ] = undefined; delete this[ name ]; } catch( e ) {} }); }, addClass: function( value ) { var 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.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { return ret; } ret = elem.value; return typeof ret === "string" ? // handle most common string cases ret.replace(rreturn, "") : // handle cases where value is null/undef or number ret == null ? "" : ret; } return; } isFunction = jQuery.isFunction( value ); return this.each(function( i ) { var 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.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; // If set returns undefined, fall back to normal setting if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } }); } }); jQuery.extend({ valHooks: { option: { get: function( elem ) { // attributes.value is undefined in Blackberry 4.7 but // uses .value. See #6932 var val = elem.attributes.value; return !val || val.specified ? elem.value : elem.text; } }, select: { get: function( elem ) { var value, 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, isBool, 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; isBool = rboolean.test( name ); // See #9699 for explanation of this approach (setting first, then removal) // Do not do this for boolean attributes (see #10870) if ( !isBool ) { jQuery.attr( elem, name, "" ); } elem.removeAttribute( getSetAttribute ? name : propName ); // Set corresponding property to false for boolean attributes if ( isBool && 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, coords: 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 = /(?:^|\s)hover(\.\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; selector = handleObjIn.selector; } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first 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: selector && 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, special = jQuery.event.special[ event.type ] || {}, 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; // Call the preDispatch hook for the mapped type, and let it bail if desired if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { return; } // Determine handlers that should run if there are delegated events // Avoid non-left-click bubbling in Firefox (#3861) if ( delegateCount && !(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 ) { // Don't process events on disabled elements (#6911, #8165) if ( cur.disabled !== true ) { 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(); } } } } } // Call the postDispatch hook for the mapped type if ( special.postDispatch ) { special.postDispatch.call( this, event ); } 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 ) { event._submit_bubble = true; }); form._submit_attached = true; } }); // return undefined since we don't need an event listener }, postDispatch: function( event ) { // If form was submitted by the user, bubble the event up the tree if ( event._submit_bubble ) { delete event._submit_bubble; if ( this.parentNode && !event.isTrigger ) { jQuery.event.simulate( "submit", this.parentNode, event, true ); } } }, teardown: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Remove delegated handlers; cleanData eventually reaps submit handlers attached above jQuery.event.remove( this, "._submit" ); } }; } // IE change delegation and checkbox/radio fix if ( !jQuery.support.changeBubbles ) { jQuery.event.special.change = { setup: function() { if ( rformElems.test( this.nodeName ) ) { // IE doesn't fire change on a check/radio until blur; trigger it on click // after a propertychange. Eat the blur-change in special.change.handle. // This still fires onchange a second time for check/radio after blur. if ( this.type === "checkbox" || this.type === "radio" ) { jQuery.event.add( this, "propertychange._change", function( event ) { if ( event.originalEvent.propertyName === "checked" ) { this._just_changed = true; } }); jQuery.event.add( this, "click._change", function( event ) { if ( this._just_changed && !event.isTrigger ) { this._just_changed = false; 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" ) { // && selector != null // ( types-Object, data ) data = data || selector; selector = undefined; } for ( type in types ) { this.on( type, selector, data, types[ type ], one ); } return this; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return this; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since event contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return this.each( function() { jQuery.event.add( this, types, fn, data, selector ); }); }, one: function( types, selector, data, fn ) { return this.on( types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event var handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( 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 || nodeType === 11 ) { // 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; /* falls through */ 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) ); } // Expose origPOS // "global" as in regardless of relation to brackets/parens Expr.match.globalPOS = origPOS; 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.globalPOS, // 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|bdi|canvas|data|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 + ")[\\s/>]", "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( value ) { return jQuery.access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) ); }, null, value, arguments.length ); }, wrapAll: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapAll( html.call(this, i) ); }); } if ( this[0] ) { // The elements to wrap the target around var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true); if ( this[0].parentNode ) { wrap.insertBefore( this[0] ); } wrap.map(function() { var elem = this; while ( elem.firstChild && elem.firstChild.nodeType === 1 ) { elem = elem.firstChild; } return elem; }).append( this ); } return this; }, wrapInner: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapInner( html.call(this, i) ); }); } return this.each(function() { var self = jQuery( this ), contents = self.contents(); if ( contents.length ) { contents.wrapAll( html ); } else { self.append( html ); } }); }, wrap: function( html ) { var isFunction = jQuery.isFunction( html ); return this.each(function(i) { jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html ); }); }, unwrap: function() { return this.parent().each(function() { if ( !jQuery.nodeName( this, "body" ) ) { jQuery( this ).replaceWith( this.childNodes ); } }).end(); }, append: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 ) { this.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 ) { return jQuery.access( this, function( value ) { var elem = this[0] || {}, i = 0, l = this.length; if ( value === undefined ) { return elem.nodeType === 1 ? elem.innerHTML.replace( rinlinejQuery, "" ) : null; } 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 (; i < l; i++ ) { // Remove element nodes and prevent memory leaks elem = this[i] || {}; if ( elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName( "*" ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch(e) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function( value ) { 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, function( i, elem ) { if ( elem.src ) { jQuery.ajax({ type: "GET", global: false, 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 ); } }); } } 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 ] ); } } } // 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; // IE blanks contents when cloning scripts } else if ( nodeName === "script" && dest.text !== src.text ) { dest.text = src.text; } // Event data gets referenced instead of copied if the expando // gets copied too dest.removeAttribute( jQuery.expando ); // Clear flags for bubbling special change/submit events, they must // be reattached when the newly cloned events are first activated dest.removeAttribute( "_submit_attached" ); dest.removeAttribute( "_change_attached" ); } 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 || jQuery.isXMLDoc(elem) || !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, script, j, ret = []; 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; } 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"), safeChildNodes = safeFragment.childNodes, remove; // 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; // Clear elements from DocumentFragment (safeFragment or otherwise) // to avoid hoarding elements. Fixes #11356 if ( div ) { div.parentNode.removeChild( div ); // Guard against -1 index exceptions in FF3.6 if ( safeChildNodes.length > 0 ) { remove = safeChildNodes[ safeChildNodes.length - 1 ]; if ( remove && remove.parentNode ) { remove.parentNode.removeChild( remove ); } } } } } // 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++ ) { script = ret[i]; if ( scripts && jQuery.nodeName( script, "script" ) && (!script.type || rscriptType.test( script.type )) ) { scripts.push( script.parentNode ? script.parentNode.removeChild( script ) : script ); } else { if ( script.nodeType === 1 ) { var jsTags = jQuery.grep( script.getElementsByTagName( "script" ), checkScriptType ); ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) ); } fragment.appendChild( script ); } } } 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 ]; } } } }); var ralpha = /alpha\([^)]*\)/i, ropacity = /opacity=([^)]*)/, // fixed for IE9, see #8346 rupper = /([A-Z]|^ms)/g, rnum = /^[\-+]?(?:\d*\.)?\d+$/i, rnumnonpx = /^-?(?:\d*\.)?\d+(?!px)[^\d\s]+$/i, rrelNum = /^([\-+])=([\-+.\de]+)/, rmargin = /^margin/, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, // order is important! cssExpand = [ "Top", "Right", "Bottom", "Left" ], curCSS, getComputedStyle, currentStyle; jQuery.fn.css = function( name, value ) { return jQuery.access( this, function( elem, name, value ) { return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }, name, value, arguments.length > 1 ); }; jQuery.extend({ // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function( elem, computed ) { if ( computed ) { // We should always get a number back from opacity var ret = curCSS( elem, "opacity" ); return ret === "" ? "1" : ret; } 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 = {}, ret, name; // Remember the old values, and insert the new ones for ( name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } ret = callback.call( elem ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } return ret; } }); // DEPRECATED in 1.3, Use jQuery.css() instead jQuery.curCSS = jQuery.css; if ( document.defaultView && document.defaultView.getComputedStyle ) { getComputedStyle = function( elem, name ) { var ret, defaultView, computedStyle, width, style = elem.style; 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 ); } } // A tribute to the "awesome hack by Dean Edwards" // WebKit uses "computed value (percentage if specified)" instead of "used value" for margins // which is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values if ( !jQuery.support.pixelMargin && computedStyle && rmargin.test( name ) && rnumnonpx.test( ret ) ) { width = style.width; style.width = ret; ret = computedStyle.width; style.width = width; } 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 ( rnumnonpx.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; 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 getWidthOrHeight( elem, name, extra ) { // Start with offset property var val = name === "width" ? elem.offsetWidth : elem.offsetHeight, i = name === "width" ? 1 : 0, len = 4; if ( val > 0 ) { if ( extra !== "border" ) { for ( ; i < len; i += 2 ) { if ( !extra ) { val -= parseFloat( jQuery.css( elem, "padding" + cssExpand[ i ] ) ) || 0; } if ( extra === "margin" ) { val += parseFloat( jQuery.css( elem, extra + cssExpand[ i ] ) ) || 0; } else { val -= parseFloat( jQuery.css( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0; } } } return val + "px"; } // Fall back to computed then uncomputed css if necessary val = curCSS( elem, name ); if ( val < 0 || val == null ) { val = elem.style[ name ]; } // Computed unit is not pixels. Stop here and return. if ( rnumnonpx.test(val) ) { return val; } // Normalize "", auto, and prepare for extra val = parseFloat( val ) || 0; // Add padding, border, margin if ( extra ) { for ( ; i < len; i += 2 ) { val += parseFloat( jQuery.css( elem, "padding" + cssExpand[ i ] ) ) || 0; if ( extra !== "padding" ) { val += parseFloat( jQuery.css( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0; } if ( extra === "margin" ) { val += parseFloat( jQuery.css( elem, extra + cssExpand[ i ]) ) || 0; } } } return val + "px"; } jQuery.each([ "height", "width" ], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { if ( computed ) { if ( elem.offsetWidth !== 0 ) { return getWidthOrHeight( elem, name, extra ); } else { return jQuery.swap( elem, cssShow, function() { return getWidthOrHeight( elem, name, extra ); }); } } }, set: function( elem, value ) { return rnum.test( value ) ? value + "px" : 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 return jQuery.swap( elem, { "display": "inline-block" }, function() { if ( computed ) { return curCSS( elem, "margin-right" ); } else { return elem.style.marginRight; } }); } }; } }); 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 ); }; } // These hooks are used by animate to expand properties jQuery.each({ margin: "", padding: "", border: "Width" }, function( prefix, suffix ) { jQuery.cssHooks[ prefix + suffix ] = { expand: function( value ) { var i, // assumes a single number if not a string parts = typeof value === "string" ? value.split(" ") : [ value ], expanded = {}; for ( i = 0; i < 4; i++ ) { expanded[ prefix + cssExpand[ i ] + suffix ] = parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; } return expanded; } }; }); 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; charset=UTF-8", 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 prefilter, 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" ? i : "" ) + "]", v, traditional, add ); } }); } else if ( !traditional && jQuery.type( 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 = ( typeof s.data === "string" ) && /^application\/x\-www\-form\-urlencoded/.test( s.contentType ); 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; } // When requesting binary data, IE6-9 will throw an exception // on any attempt to access responseText (#11426) try { responses.text = xhr.responseText; } catch( _ ) { } // 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.contains( elem.ownerDocument.documentElement, elem ) ) { 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, hooks, replace, parts, start, end, unit, method; // will store per property easing and be used to determine when an animation is complete opt.animatedProperties = {}; // first pass over propertys to expand / normalize for ( p in prop ) { name = jQuery.camelCase( p ); if ( p !== name ) { prop[ name ] = prop[ p ]; delete prop[ p ]; } if ( ( hooks = jQuery.cssHooks[ name ] ) && "expand" in hooks ) { replace = hooks.expand( prop[ name ] ); delete prop[ name ]; // not quite $.extend, this wont overwrite keys already present. // also - reusing 'p' from above because we have the correct "name" for ( p in replace ) { if ( ! ( p in prop ) ) { prop[ p ] = replace[ p ]; } } } } for ( name in prop ) { 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 ) { return p; }, swing: function( p ) { return ( -Math.cos( p*Math.PI ) / 2 ) + 0.5; } }, 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 ( jQuery._data( self.elem, "fxshow" + self.prop ) === undefined ) { if ( self.options.hide ) { jQuery._data( self.elem, "fxshow" + self.prop, self.start ); } else if ( self.options.show ) { jQuery._data( self.elem, "fxshow" + self.prop, self.end ); } } }; 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; } } } }); // Ensure props that can't be negative don't go there on undershoot easing jQuery.each( fxAttrs.concat.apply( [], fxAttrs ), function( i, prop ) { // exclude marginTop, marginLeft, marginBottom and marginRight from this list if ( prop.indexOf( "margin" ) ) { 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( ( jQuery.support.boxModel ? "<!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 getOffset, rtable = /^t(?:able|d|h)$/i, rroot = /^(?:body|html)$/i; if ( "getBoundingClientRect" in document.documentElement ) { getOffset = function( elem, doc, docElem, box ) { try { box = elem.getBoundingClientRect(); } catch(e) {} // 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 { getOffset = function( elem, doc, docElem ) { var computedStyle, offsetParent = elem.offsetParent, prevOffsetParent = elem, 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.fn.offset = function( options ) { if ( arguments.length ) { return options === undefined ? this : this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } var elem = this[0], doc = elem && elem.ownerDocument; if ( !doc ) { return null; } if ( elem === doc.body ) { return jQuery.offset.bodyOffset( elem ); } return getOffset( elem, doc, doc.documentElement ); }; 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( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) { var top = /Y/.test( prop ); jQuery.fn[ method ] = function( val ) { return jQuery.access( this, function( elem, method, val ) { var win = getWindow( elem ); if ( val === undefined ) { return win ? (prop in win) ? win[ prop ] : jQuery.support.boxModel && win.document.documentElement[ method ] || win.document.body[ method ] : elem[ method ]; } if ( win ) { win.scrollTo( !top ? val : jQuery( win ).scrollLeft(), top ? val : jQuery( win ).scrollTop() ); } else { elem[ method ] = val; } }, method, val, arguments.length, null ); }; }); function getWindow( elem ) { return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 ? elem.defaultView || elem.parentWindow : false; } // Create width, height, innerHeight, innerWidth, outerHeight and outerWidth methods jQuery.each( { Height: "height", Width: "width" }, function( name, type ) { var clientProp = "client" + name, scrollProp = "scroll" + name, offsetProp = "offset" + name; // 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( value ) { return jQuery.access( this, function( elem, type, value ) { var doc, docElemProp, orig, ret; if ( jQuery.isWindow( elem ) ) { // 3rd condition allows Nokia support, as it supports the docElem prop but not CSS1Compat doc = elem.document; docElemProp = doc.documentElement[ clientProp ]; return jQuery.support.boxModel && docElemProp || doc.body && doc.body[ clientProp ] || docElemProp; } // Get document width or height if ( elem.nodeType === 9 ) { // Either scroll[Width/Height] or offset[Width/Height], whichever is greater doc = elem.documentElement; // when a window > document, IE6 reports a offset[Width/Height] > client[Width/Height] // so we can't use max, as it'll choose the incorrect offset[Width/Height] // instead we use the correct client[Width/Height] // support:IE6 if ( doc[ clientProp ] >= doc[ scrollProp ] ) { return doc[ clientProp ]; } return Math.max( elem.body[ scrollProp ], doc[ scrollProp ], elem.body[ offsetProp ], doc[ offsetProp ] ); } // Get width or height on the element if ( value === undefined ) { orig = jQuery.css( elem, type ); ret = parseFloat( orig ); return jQuery.isNumeric( ret ) ? ret : orig; } // Set the width or height on the element jQuery( elem ).css( type, value ); }, type, value, arguments.length, null ); }; }); // 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 ); /** * @license AngularJS v1.0.2 * (c) 2010-2012 Google, Inc. http://angularjs.org * License: MIT */ (function(window, document){ var _jQuery = window.jQuery.noConflict(true); //////////////////////////////////// /** * @ngdoc function * @name angular.lowercase * @function * * @description Converts the specified string to lowercase. * @param {string} string String to be converted to lowercase. * @returns {string} Lowercased string. */ var lowercase = function(string){return isString(string) ? string.toLowerCase() : string;}; /** * @ngdoc function * @name angular.uppercase * @function * * @description Converts the specified string to uppercase. * @param {string} string String to be converted to uppercase. * @returns {string} Uppercased string. */ var uppercase = function(string){return isString(string) ? string.toUpperCase() : string;}; var manualLowercase = function(s) { return isString(s) ? s.replace(/[A-Z]/g, function(ch) {return fromCharCode(ch.charCodeAt(0) | 32);}) : s; }; var manualUppercase = function(s) { return isString(s) ? s.replace(/[a-z]/g, function(ch) {return fromCharCode(ch.charCodeAt(0) & ~32);}) : s; }; // String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish // locale, for this reason we need to detect this case and redefine lowercase/uppercase methods // with correct but slower alternatives. if ('i' !== 'I'.toLowerCase()) { lowercase = manualLowercase; uppercase = manualUppercase; } function fromCharCode(code) {return String.fromCharCode(code);} var Error = window.Error, /** holds major version number for IE or NaN for real browsers */ msie = int((/msie (\d+)/.exec(lowercase(navigator.userAgent)) || [])[1]), jqLite, // delay binding since jQuery could be loaded after us. jQuery, // delay binding slice = [].slice, push = [].push, toString = Object.prototype.toString, /** @name angular */ angular = window.angular || (window.angular = {}), angularModule, nodeName_, uid = ['0', '0', '0']; /** * @ngdoc function * @name angular.forEach * @function * * @description * Invokes the `iterator` function once for each item in `obj` collection, which can be either an * object or an array. The `iterator` function is invoked with `iterator(value, key)`, where `value` * is the value of an object property or an array element and `key` is the object property key or * array element index. Specifying a `context` for the function is optional. * * Note: this function was previously known as `angular.foreach`. * <pre> var values = {name: 'misko', gender: 'male'}; var log = []; angular.forEach(values, function(value, key){ this.push(key + ': ' + value); }, log); expect(log).toEqual(['name: misko', 'gender:male']); </pre> * * @param {Object|Array} obj Object to iterate over. * @param {Function} iterator Iterator function. * @param {Object=} context Object to become context (`this`) for the iterator function. * @returns {Object|Array} Reference to `obj`. */ function forEach(obj, iterator, context) { var key; if (obj) { if (isFunction(obj)){ for (key in obj) { if (key != 'prototype' && key != 'length' && key != 'name' && obj.hasOwnProperty(key)) { iterator.call(context, obj[key], key); } } } else if (obj.forEach && obj.forEach !== forEach) { obj.forEach(iterator, context); } else if (isObject(obj) && isNumber(obj.length)) { for (key = 0; key < obj.length; key++) iterator.call(context, obj[key], key); } else { for (key in obj) { if (obj.hasOwnProperty(key)) { iterator.call(context, obj[key], key); } } } } return obj; } function sortedKeys(obj) { var keys = []; for (var key in obj) { if (obj.hasOwnProperty(key)) { keys.push(key); } } return keys.sort(); } function forEachSorted(obj, iterator, context) { var keys = sortedKeys(obj); for ( var i = 0; i < keys.length; i++) { iterator.call(context, obj[keys[i]], keys[i]); } return keys; } /** * when using forEach the params are value, key, but it is often useful to have key, value. * @param {function(string, *)} iteratorFn * @returns {function(*, string)} */ function reverseParams(iteratorFn) { return function(value, key) { iteratorFn(key, value) }; } /** * A consistent way of creating unique IDs in angular. The ID is a sequence of alpha numeric * characters such as '012ABC'. The reason why we are not using simply a number counter is that * the number string gets longer over time, and it can also overflow, where as the the nextId * will grow much slower, it is a string, and it will never overflow. * * @returns an unique alpha-numeric string */ function nextUid() { var index = uid.length; var digit; while(index) { index--; digit = uid[index].charCodeAt(0); if (digit == 57 /*'9'*/) { uid[index] = 'A'; return uid.join(''); } if (digit == 90 /*'Z'*/) { uid[index] = '0'; } else { uid[index] = String.fromCharCode(digit + 1); return uid.join(''); } } uid.unshift('0'); return uid.join(''); } /** * @ngdoc function * @name angular.extend * @function * * @description * Extends the destination object `dst` by copying all of the properties from the `src` object(s) * to `dst`. You can specify multiple `src` objects. * * @param {Object} dst Destination object. * @param {...Object} src Source object(s). */ function extend(dst) { forEach(arguments, function(obj){ if (obj !== dst) { forEach(obj, function(value, key){ dst[key] = value; }); } }); return dst; } function int(str) { return parseInt(str, 10); } function inherit(parent, extra) { return extend(new (extend(function() {}, {prototype:parent}))(), extra); } /** * @ngdoc function * @name angular.noop * @function * * @description * A function that performs no operations. This function can be useful when writing code in the * functional style. <pre> function foo(callback) { var result = calculateResult(); (callback || angular.noop)(result); } </pre> */ function noop() {} noop.$inject = []; /** * @ngdoc function * @name angular.identity * @function * * @description * A function that returns its first argument. This function is useful when writing code in the * functional style. * <pre> function transformer(transformationFn, value) { return (transformationFn || identity)(value); }; </pre> */ function identity($) {return $;} identity.$inject = []; function valueFn(value) {return function() {return value;};} /** * @ngdoc function * @name angular.isUndefined * @function * * @description * Determines if a reference is undefined. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is undefined. */ function isUndefined(value){return typeof value == 'undefined';} /** * @ngdoc function * @name angular.isDefined * @function * * @description * Determines if a reference is defined. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is defined. */ function isDefined(value){return typeof value != 'undefined';} /** * @ngdoc function * @name angular.isObject * @function * * @description * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not * considered to be objects. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is an `Object` but not `null`. */ function isObject(value){return value != null && typeof value == 'object';} /** * @ngdoc function * @name angular.isString * @function * * @description * Determines if a reference is a `String`. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is a `String`. */ function isString(value){return typeof value == 'string';} /** * @ngdoc function * @name angular.isNumber * @function * * @description * Determines if a reference is a `Number`. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is a `Number`. */ function isNumber(value){return typeof value == 'number';} /** * @ngdoc function * @name angular.isDate * @function * * @description * Determines if a value is a date. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is a `Date`. */ function isDate(value){ return toString.apply(value) == '[object Date]'; } /** * @ngdoc function * @name angular.isArray * @function * * @description * Determines if a reference is an `Array`. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is an `Array`. */ function isArray(value) { return toString.apply(value) == '[object Array]'; } /** * @ngdoc function * @name angular.isFunction * @function * * @description * Determines if a reference is a `Function`. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is a `Function`. */ function isFunction(value){return typeof value == 'function';} /** * Checks if `obj` is a window object. * * @private * @param {*} obj Object to check * @returns {boolean} True if `obj` is a window obj. */ function isWindow(obj) { return obj && obj.document && obj.location && obj.alert && obj.setInterval; } function isScope(obj) { return obj && obj.$evalAsync && obj.$watch; } function isFile(obj) { return toString.apply(obj) === '[object File]'; } function isBoolean(value) { return typeof value == 'boolean'; } function trim(value) { return isString(value) ? value.replace(/^\s*/, '').replace(/\s*$/, '') : value; } /** * @ngdoc function * @name angular.isElement * @function * * @description * Determines if a reference is a DOM element (or wrapped jQuery element). * * @param {*} value Reference to check. * @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element). */ function isElement(node) { return node && (node.nodeName // we are a direct element || (node.bind && node.find)); // we have a bind and find method part of jQuery API } /** * @param str 'key1,key2,...' * @returns {object} in the form of {key1:true, key2:true, ...} */ function makeMap(str){ var obj = {}, items = str.split(","), i; for ( i = 0; i < items.length; i++ ) obj[ items[i] ] = true; return obj; } if (msie < 9) { nodeName_ = function(element) { element = element.nodeName ? element : element[0]; return (element.scopeName && element.scopeName != 'HTML') ? uppercase(element.scopeName + ':' + element.nodeName) : element.nodeName; }; } else { nodeName_ = function(element) { return element.nodeName ? element.nodeName : element[0].nodeName; }; } function map(obj, iterator, context) { var results = []; forEach(obj, function(value, index, list) { results.push(iterator.call(context, value, index, list)); }); return results; } /** * @description * Determines the number of elements in an array, the number of properties an object has, or * the length of a string. * * Note: This function is used to augment the Object type in Angular expressions. See * {@link angular.Object} for more information about Angular arrays. * * @param {Object|Array|string} obj Object, array, or string to inspect. * @param {boolean} [ownPropsOnly=false] Count only "own" properties in an object * @returns {number} The size of `obj` or `0` if `obj` is neither an object nor an array. */ function size(obj, ownPropsOnly) { var size = 0, key; if (isArray(obj) || isString(obj)) { return obj.length; } else if (isObject(obj)){ for (key in obj) if (!ownPropsOnly || obj.hasOwnProperty(key)) size++; } return size; } function includes(array, obj) { return indexOf(array, obj) != -1; } function indexOf(array, obj) { if (array.indexOf) return array.indexOf(obj); for ( var i = 0; i < array.length; i++) { if (obj === array[i]) return i; } return -1; } function arrayRemove(array, value) { var index = indexOf(array, value); if (index >=0) array.splice(index, 1); return value; } function isLeafNode (node) { if (node) { switch (node.nodeName) { case "OPTION": case "PRE": case "TITLE": return true; } } return false; } /** * @ngdoc function * @name angular.copy * @function * * @description * Creates a deep copy of `source`, which should be an object or an array. * * * If no destination is supplied, a copy of the object or array is created. * * If a destination is provided, all of its elements (for array) or properties (for objects) * are deleted and then all elements/properties from the source are copied to it. * * If `source` is not an object or array, `source` is returned. * * Note: this function is used to augment the Object type in Angular expressions. See * {@link ng.$filter} for more information about Angular arrays. * * @param {*} source The source that will be used to make a copy. * Can be any type, including primitives, `null`, and `undefined`. * @param {(Object|Array)=} destination Destination into which the source is copied. If * provided, must be of the same type as `source`. * @returns {*} The copy or updated `destination`, if `destination` was specified. */ function copy(source, destination){ if (isWindow(source) || isScope(source)) throw Error("Can't copy Window or Scope"); if (!destination) { destination = source; if (source) { if (isArray(source)) { destination = copy(source, []); } else if (isDate(source)) { destination = new Date(source.getTime()); } else if (isObject(source)) { destination = copy(source, {}); } } } else { if (source === destination) throw Error("Can't copy equivalent objects or arrays"); if (isArray(source)) { while(destination.length) { destination.pop(); } for ( var i = 0; i < source.length; i++) { destination.push(copy(source[i])); } } else { forEach(destination, function(value, key){ delete destination[key]; }); for ( var key in source) { destination[key] = copy(source[key]); } } } return destination; } /** * Create a shallow copy of an object */ function shallowCopy(src, dst) { dst = dst || {}; for(var key in src) { if (src.hasOwnProperty(key) && key.substr(0, 2) !== '$$') { dst[key] = src[key]; } } return dst; } /** * @ngdoc function * @name angular.equals * @function * * @description * Determines if two objects or two values are equivalent. Supports value types, arrays and * objects. * * Two objects or values are considered equivalent if at least one of the following is true: * * * Both objects or values pass `===` comparison. * * Both objects or values are of the same type and all of their properties pass `===` comparison. * * Both values are NaN. (In JavasScript, NaN == NaN => false. But we consider two NaN as equal) * * During a property comparision, properties of `function` type and properties with names * that begin with `$` are ignored. * * Scope and DOMWindow objects are being compared only be identify (`===`). * * @param {*} o1 Object or value to compare. * @param {*} o2 Object or value to compare. * @returns {boolean} True if arguments are equal. */ function equals(o1, o2) { if (o1 === o2) return true; if (o1 === null || o2 === null) return false; if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN var t1 = typeof o1, t2 = typeof o2, length, key, keySet; if (t1 == t2) { if (t1 == 'object') { if (isArray(o1)) { if ((length = o1.length) == o2.length) { for(key=0; key<length; key++) { if (!equals(o1[key], o2[key])) return false; } return true; } } else if (isDate(o1)) { return isDate(o2) && o1.getTime() == o2.getTime(); } else { if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2)) return false; keySet = {}; for(key in o1) { if (key.charAt(0) !== '$' && !isFunction(o1[key]) && !equals(o1[key], o2[key])) { return false; } keySet[key] = true; } for(key in o2) { if (!keySet[key] && key.charAt(0) !== '$' && !isFunction(o2[key])) return false; } return true; } } } return false; } function concat(array1, array2, index) { return array1.concat(slice.call(array2, index)); } function sliceArgs(args, startIndex) { return slice.call(args, startIndex || 0); } /** * @ngdoc function * @name angular.bind * @function * * @description * Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for * `fn`). You can supply optional `args` that are are prebound to the function. This feature is also * known as [function currying](http://en.wikipedia.org/wiki/Currying). * * @param {Object} self Context which `fn` should be evaluated in. * @param {function()} fn Function to be bound. * @param {...*} args Optional arguments to be prebound to the `fn` function call. * @returns {function()} Function that wraps the `fn` with all the specified bindings. */ function bind(self, fn) { var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : []; if (isFunction(fn) && !(fn instanceof RegExp)) { return curryArgs.length ? function() { return arguments.length ? fn.apply(self, curryArgs.concat(slice.call(arguments, 0))) : fn.apply(self, curryArgs); } : function() { return arguments.length ? fn.apply(self, arguments) : fn.call(self); }; } else { // in IE, native methods are not functions so they cannot be bound (note: they don't need to be) return fn; } } function toJsonReplacer(key, value) { var val = value; if (/^\$+/.test(key)) { val = undefined; } else if (isWindow(value)) { val = '$WINDOW'; } else if (value && document === value) { val = '$DOCUMENT'; } else if (isScope(value)) { val = '$SCOPE'; } return val; } /** * @ngdoc function * @name angular.toJson * @function * * @description * Serializes input into a JSON-formatted string. * * @param {Object|Array|Date|string|number} obj Input to be serialized into JSON. * @param {boolean=} pretty If set to true, the JSON output will contain newlines and whitespace. * @returns {string} Jsonified string representing `obj`. */ function toJson(obj, pretty) { return JSON.stringify(obj, toJsonReplacer, pretty ? ' ' : null); } /** * @ngdoc function * @name angular.fromJson * @function * * @description * Deserializes a JSON string. * * @param {string} json JSON string to deserialize. * @returns {Object|Array|Date|string|number} Deserialized thingy. */ function fromJson(json) { return isString(json) ? JSON.parse(json) : json; } function toBoolean(value) { if (value && value.length !== 0) { var v = lowercase("" + value); value = !(v == 'f' || v == '0' || v == 'false' || v == 'no' || v == 'n' || v == '[]'); } else { value = false; } return value; } /** * @returns {string} Returns the string representation of the element. */ function startingTag(element) { element = jqLite(element).clone(); try { // turns out IE does not let you set .html() on elements which // are not allowed to have children. So we just ignore it. element.html(''); } catch(e) {} return jqLite('<div>').append(element).html(). match(/^(<[^>]+>)/)[1]. replace(/^<([\w\-]+)/, function(match, nodeName) { return '<' + lowercase(nodeName); }); } ///////////////////////////////////////////////// /** * Parses an escaped url query string into key-value pairs. * @returns Object.<(string|boolean)> */ function parseKeyValue(/**string*/keyValue) { var obj = {}, key_value, key; forEach((keyValue || "").split('&'), function(keyValue){ if (keyValue) { key_value = keyValue.split('='); key = decodeURIComponent(key_value[0]); obj[key] = isDefined(key_value[1]) ? decodeURIComponent(key_value[1]) : true; } }); return obj; } function toKeyValue(obj) { var parts = []; forEach(obj, function(value, key) { parts.push(encodeUriQuery(key, true) + (value === true ? '' : '=' + encodeUriQuery(value, true))); }); return parts.length ? parts.join('&') : ''; } /** * We need our custom mehtod because encodeURIComponent is too agressive and doesn't follow * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path * segments: * segment = *pchar * pchar = unreserved / pct-encoded / sub-delims / ":" / "@" * pct-encoded = "%" HEXDIG HEXDIG * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" * sub-delims = "!" / "$" / "&" / "'" / "(" / ")" * / "*" / "+" / "," / ";" / "=" */ function encodeUriSegment(val) { return encodeUriQuery(val, true). replace(/%26/gi, '&'). replace(/%3D/gi, '='). replace(/%2B/gi, '+'); } /** * This method is intended for encoding *key* or *value* parts of query component. We need a custom * method becuase encodeURIComponent is too agressive and encodes stuff that doesn't have to be * encoded per http://tools.ietf.org/html/rfc3986: * query = *( pchar / "/" / "?" ) * pchar = unreserved / pct-encoded / sub-delims / ":" / "@" * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" * pct-encoded = "%" HEXDIG HEXDIG * sub-delims = "!" / "$" / "&" / "'" / "(" / ")" * / "*" / "+" / "," / ";" / "=" */ function encodeUriQuery(val, pctEncodeSpaces) { return encodeURIComponent(val). replace(/%40/gi, '@'). replace(/%3A/gi, ':'). replace(/%24/g, '$'). replace(/%2C/gi, ','). replace((pctEncodeSpaces ? null : /%20/g), '+'); } /** * @ngdoc directive * @name ng.directive:ngApp * * @element ANY * @param {angular.Module} ngApp on optional application * {@link angular.module module} name to load. * * @description * * Use this directive to auto-bootstrap on application. Only * one directive can be used per HTML document. The directive * designates the root of the application and is typically placed * ot the root of the page. * * In the example below if the `ngApp` directive would not be placed * on the `html` element then the document would not be compiled * and the `{{ 1+2 }}` would not be resolved to `3`. * * `ngApp` is the easiest way to bootstrap an application. * <doc:example> <doc:source> I can add: 1 + 2 = {{ 1+2 }} </doc:source> </doc:example> * */ function angularInit(element, bootstrap) { var elements = [element], appElement, module, names = ['ng:app', 'ng-app', 'x-ng-app', 'data-ng-app'], NG_APP_CLASS_REGEXP = /\sng[:\-]app(:\s*([\w\d_]+);?)?\s/; function append(element) { element && elements.push(element); } forEach(names, function(name) { names[name] = true; append(document.getElementById(name)); name = name.replace(':', '\\:'); if (element.querySelectorAll) { forEach(element.querySelectorAll('.' + name), append); forEach(element.querySelectorAll('.' + name + '\\:'), append); forEach(element.querySelectorAll('[' + name + ']'), append); } }); forEach(elements, function(element) { if (!appElement) { var className = ' ' + element.className + ' '; var match = NG_APP_CLASS_REGEXP.exec(className); if (match) { appElement = element; module = (match[2] || '').replace(/\s+/g, ','); } else { forEach(element.attributes, function(attr) { if (!appElement && names[attr.name]) { appElement = element; module = attr.value; } }); } } }); if (appElement) { bootstrap(appElement, module ? [module] : []); } } /** * @ngdoc function * @name angular.bootstrap * @description * Use this function to manually start up angular application. * * See: {@link guide/bootstrap Bootstrap} * * @param {Element} element DOM element which is the root of angular application. * @param {Array<String|Function>=} modules an array of module declarations. See: {@link angular.module modules} * @returns {AUTO.$injector} Returns the newly created injector for this app. */ function bootstrap(element, modules) { element = jqLite(element); modules = modules || []; modules.unshift(['$provide', function($provide) { $provide.value('$rootElement', element); }]); modules.unshift('ng'); var injector = createInjector(modules); injector.invoke( ['$rootScope', '$rootElement', '$compile', '$injector', function(scope, element, compile, injector){ scope.$apply(function() { element.data('$injector', injector); compile(element)(scope); }); }] ); return injector; } var SNAKE_CASE_REGEXP = /[A-Z]/g; function snake_case(name, separator){ separator = separator || '_'; return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) { return (pos ? separator : '') + letter.toLowerCase(); }); } function bindJQuery() { // bind to jQuery if present; jQuery = window.jQuery; // reset to jQuery or default to us. if (jQuery) { jqLite = jQuery; extend(jQuery.fn, { scope: JQLitePrototype.scope, controller: JQLitePrototype.controller, injector: JQLitePrototype.injector, inheritedData: JQLitePrototype.inheritedData }); JQLitePatchJQueryRemove('remove', true); JQLitePatchJQueryRemove('empty'); JQLitePatchJQueryRemove('html'); } else { jqLite = JQLite; } angular.element = jqLite; } /** * throw error of the argument is falsy. */ function assertArg(arg, name, reason) { if (!arg) { throw new Error("Argument '" + (name || '?') + "' is " + (reason || "required")); } return arg; } function assertArgFn(arg, name, acceptArrayAnnotation) { if (acceptArrayAnnotation && isArray(arg)) { arg = arg[arg.length - 1]; } assertArg(isFunction(arg), name, 'not a function, got ' + (arg && typeof arg == 'object' ? arg.constructor.name || 'Object' : typeof arg)); return arg; } /** * @ngdoc interface * @name angular.Module * @description * * Interface for configuring angular {@link angular.module modules}. */ function setupModuleLoader(window) { function ensure(obj, name, factory) { return obj[name] || (obj[name] = factory()); } return ensure(ensure(window, 'angular', Object), 'module', function() { /** @type {Object.<string, angular.Module>} */ var modules = {}; /** * @ngdoc function * @name angular.module * @description * * The `angular.module` is a global place for creating and registering Angular modules. All * modules (angular core or 3rd party) that should be available to an application must be * registered using this mechanism. * * * # Module * * A module is a collocation of services, directives, filters, and configure information. Module * is used to configure the {@link AUTO.$injector $injector}. * * <pre> * // Create a new module * var myModule = angular.module('myModule', []); * * // register a new service * myModule.value('appName', 'MyCoolApp'); * * // configure existing services inside initialization blocks. * myModule.config(function($locationProvider) { * // Configure existing providers * $locationProvider.hashPrefix('!'); * }); * </pre> * * Then you can create an injector and load your modules like this: * * <pre> * var injector = angular.injector(['ng', 'MyModule']) * </pre> * * However it's more likely that you'll just use * {@link ng.directive:ngApp ngApp} or * {@link angular.bootstrap} to simplify this process for you. * * @param {!string} name The name of the module to create or retrieve. * @param {Array.<string>=} requires If specified then new module is being created. If unspecified then the * the module is being retrieved for further configuration. * @param {Function} configFn Option configuration function for the module. Same as * {@link angular.Module#config Module#config()}. * @returns {module} new module with the {@link angular.Module} api. */ return function module(name, requires, configFn) { if (requires && modules.hasOwnProperty(name)) { modules[name] = null; } return ensure(modules, name, function() { if (!requires) { throw Error('No module: ' + name); } /** @type {!Array.<Array.<*>>} */ var invokeQueue = []; /** @type {!Array.<Function>} */ var runBlocks = []; var config = invokeLater('$injector', 'invoke'); /** @type {angular.Module} */ var moduleInstance = { // Private state _invokeQueue: invokeQueue, _runBlocks: runBlocks, /** * @ngdoc property * @name angular.Module#requires * @propertyOf angular.Module * @returns {Array.<string>} List of module names which must be loaded before this module. * @description * Holds the list of modules which the injector will load before the current module is loaded. */ requires: requires, /** * @ngdoc property * @name angular.Module#name * @propertyOf angular.Module * @returns {string} Name of the module. * @description */ name: name, /** * @ngdoc method * @name angular.Module#provider * @methodOf angular.Module * @param {string} name service name * @param {Function} providerType Construction function for creating new instance of the service. * @description * See {@link AUTO.$provide#provider $provide.provider()}. */ provider: invokeLater('$provide', 'provider'), /** * @ngdoc method * @name angular.Module#factory * @methodOf angular.Module * @param {string} name service name * @param {Function} providerFunction Function for creating new instance of the service. * @description * See {@link AUTO.$provide#factory $provide.factory()}. */ factory: invokeLater('$provide', 'factory'), /** * @ngdoc method * @name angular.Module#service * @methodOf angular.Module * @param {string} name service name * @param {Function} constructor A constructor function that will be instantiated. * @description * See {@link AUTO.$provide#service $provide.service()}. */ service: invokeLater('$provide', 'service'), /** * @ngdoc method * @name angular.Module#value * @methodOf angular.Module * @param {string} name service name * @param {*} object Service instance object. * @description * See {@link AUTO.$provide#value $provide.value()}. */ value: invokeLater('$provide', 'value'), /** * @ngdoc method * @name angular.Module#constant * @methodOf angular.Module * @param {string} name constant name * @param {*} object Constant value. * @description * Because the constant are fixed, they get applied before other provide methods. * See {@link AUTO.$provide#constant $provide.constant()}. */ constant: invokeLater('$provide', 'constant', 'unshift'), /** * @ngdoc method * @name angular.Module#filter * @methodOf angular.Module * @param {string} name Filter name. * @param {Function} filterFactory Factory function for creating new instance of filter. * @description * See {@link ng.$filterProvider#register $filterProvider.register()}. */ filter: invokeLater('$filterProvider', 'register'), /** * @ngdoc method * @name angular.Module#controller * @methodOf angular.Module * @param {string} name Controller name. * @param {Function} constructor Controller constructor function. * @description * See {@link ng.$controllerProvider#register $controllerProvider.register()}. */ controller: invokeLater('$controllerProvider', 'register'), /** * @ngdoc method * @name angular.Module#directive * @methodOf angular.Module * @param {string} name directive name * @param {Function} directiveFactory Factory function for creating new instance of * directives. * @description * See {@link ng.$compileProvider#directive $compileProvider.directive()}. */ directive: invokeLater('$compileProvider', 'directive'), /** * @ngdoc method * @name angular.Module#config * @methodOf angular.Module * @param {Function} configFn Execute this function on module load. Useful for service * configuration. * @description * Use this method to register work which needs to be performed on module loading. */ config: config, /** * @ngdoc method * @name angular.Module#run * @methodOf angular.Module * @param {Function} initializationFn Execute this function after injector creation. * Useful for application initialization. * @description * Use this method to register work which needs to be performed when the injector with * with the current module is finished loading. */ run: function(block) { runBlocks.push(block); return this; } }; if (configFn) { config(configFn); } return moduleInstance; /** * @param {string} provider * @param {string} method * @param {String=} insertMethod * @returns {angular.Module} */ function invokeLater(provider, method, insertMethod) { return function() { invokeQueue[insertMethod || 'push']([provider, method, arguments]); return moduleInstance; } } }); }; }); } /** * @ngdoc property * @name angular.version * @description * An object that contains information about the current AngularJS version. This object has the * following properties: * * - `full` – `{string}` – Full version string, such as "0.9.18". * - `major` – `{number}` – Major version number, such as "0". * - `minor` – `{number}` – Minor version number, such as "9". * - `dot` – `{number}` – Dot version number, such as "18". * - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat". */ var version = { full: '1.0.2', // all of these placeholder strings will be replaced by rake's major: 1, // compile task minor: 0, dot: 2, codeName: 'debilitating-awesomeness' }; function publishExternalAPI(angular){ extend(angular, { 'bootstrap': bootstrap, 'copy': copy, 'extend': extend, 'equals': equals, 'element': jqLite, 'forEach': forEach, 'injector': createInjector, 'noop':noop, 'bind':bind, 'toJson': toJson, 'fromJson': fromJson, 'identity':identity, 'isUndefined': isUndefined, 'isDefined': isDefined, 'isString': isString, 'isFunction': isFunction, 'isObject': isObject, 'isNumber': isNumber, 'isElement': isElement, 'isArray': isArray, 'version': version, 'isDate': isDate, 'lowercase': lowercase, 'uppercase': uppercase, 'callbacks': {counter: 0} }); angularModule = setupModuleLoader(window); try { angularModule('ngLocale'); } catch (e) { angularModule('ngLocale', []).provider('$locale', $LocaleProvider); } angularModule('ng', ['ngLocale'], ['$provide', function ngModule($provide) { $provide.provider('$compile', $CompileProvider). directive({ a: htmlAnchorDirective, input: inputDirective, textarea: inputDirective, form: formDirective, script: scriptDirective, select: selectDirective, style: styleDirective, option: optionDirective, ngBind: ngBindDirective, ngBindHtmlUnsafe: ngBindHtmlUnsafeDirective, ngBindTemplate: ngBindTemplateDirective, ngClass: ngClassDirective, ngClassEven: ngClassEvenDirective, ngClassOdd: ngClassOddDirective, ngCsp: ngCspDirective, ngCloak: ngCloakDirective, ngController: ngControllerDirective, ngForm: ngFormDirective, ngHide: ngHideDirective, ngInclude: ngIncludeDirective, ngInit: ngInitDirective, ngNonBindable: ngNonBindableDirective, ngPluralize: ngPluralizeDirective, ngRepeat: ngRepeatDirective, ngShow: ngShowDirective, ngSubmit: ngSubmitDirective, ngStyle: ngStyleDirective, ngSwitch: ngSwitchDirective, ngSwitchWhen: ngSwitchWhenDirective, ngSwitchDefault: ngSwitchDefaultDirective, ngOptions: ngOptionsDirective, ngView: ngViewDirective, ngTransclude: ngTranscludeDirective, ngModel: ngModelDirective, ngList: ngListDirective, ngChange: ngChangeDirective, required: requiredDirective, ngRequired: requiredDirective, ngValue: ngValueDirective }). directive(ngAttributeAliasDirectives). directive(ngEventDirectives); $provide.provider({ $anchorScroll: $AnchorScrollProvider, $browser: $BrowserProvider, $cacheFactory: $CacheFactoryProvider, $controller: $ControllerProvider, $document: $DocumentProvider, $exceptionHandler: $ExceptionHandlerProvider, $filter: $FilterProvider, $interpolate: $InterpolateProvider, $http: $HttpProvider, $httpBackend: $HttpBackendProvider, $location: $LocationProvider, $log: $LogProvider, $parse: $ParseProvider, $route: $RouteProvider, $routeParams: $RouteParamsProvider, $rootScope: $RootScopeProvider, $q: $QProvider, $sniffer: $SnifferProvider, $templateCache: $TemplateCacheProvider, $timeout: $TimeoutProvider, $window: $WindowProvider }); } ]); } ////////////////////////////////// //JQLite ////////////////////////////////// /** * @ngdoc function * @name angular.element * @function * * @description * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element. * `angular.element` can be either an alias for [jQuery](http://api.jquery.com/jQuery/) function, if * jQuery is available, or a function that wraps the element or string in Angular's jQuery lite * implementation (commonly referred to as jqLite). * * Real jQuery always takes precedence over jqLite, provided it was loaded before `DOMContentLoaded` * event fired. * * jqLite is a tiny, API-compatible subset of jQuery that allows * Angular to manipulate the DOM. jqLite implements only the most commonly needed functionality * within a very small footprint, so only a subset of the jQuery API - methods, arguments and * invocation styles - are supported. * * Note: All element references in Angular are always wrapped with jQuery or jqLite; they are never * raw DOM references. * * ## Angular's jQuery lite provides the following methods: * * - [addClass()](http://api.jquery.com/addClass/) * - [after()](http://api.jquery.com/after/) * - [append()](http://api.jquery.com/append/) * - [attr()](http://api.jquery.com/attr/) * - [bind()](http://api.jquery.com/bind/) * - [children()](http://api.jquery.com/children/) * - [clone()](http://api.jquery.com/clone/) * - [contents()](http://api.jquery.com/contents/) * - [css()](http://api.jquery.com/css/) * - [data()](http://api.jquery.com/data/) * - [eq()](http://api.jquery.com/eq/) * - [find()](http://api.jquery.com/find/) - Limited to lookups by tag name. * - [hasClass()](http://api.jquery.com/hasClass/) * - [html()](http://api.jquery.com/html/) * - [next()](http://api.jquery.com/next/) * - [parent()](http://api.jquery.com/parent/) * - [prepend()](http://api.jquery.com/prepend/) * - [prop()](http://api.jquery.com/prop/) * - [ready()](http://api.jquery.com/ready/) * - [remove()](http://api.jquery.com/remove/) * - [removeAttr()](http://api.jquery.com/removeAttr/) * - [removeClass()](http://api.jquery.com/removeClass/) * - [removeData()](http://api.jquery.com/removeData/) * - [replaceWith()](http://api.jquery.com/replaceWith/) * - [text()](http://api.jquery.com/text/) * - [toggleClass()](http://api.jquery.com/toggleClass/) * - [unbind()](http://api.jquery.com/unbind/) * - [val()](http://api.jquery.com/val/) * - [wrap()](http://api.jquery.com/wrap/) * * ## In addtion to the above, Angular privides an additional method to both jQuery and jQuery lite: * * - `controller(name)` - retrieves the controller of the current element or its parent. By default * retrieves controller associated with the `ngController` directive. If `name` is provided as * camelCase directive name, then the controller for this directive will be retrieved (e.g. * `'ngModel'`). * - `injector()` - retrieves the injector of the current element or its parent. * - `scope()` - retrieves the {@link api/ng.$rootScope.Scope scope} of the current * element or its parent. * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top * parent element is reached. * * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery. * @returns {Object} jQuery object. */ var jqCache = JQLite.cache = {}, jqName = JQLite.expando = 'ng-' + new Date().getTime(), jqId = 1, addEventListenerFn = (window.document.addEventListener ? function(element, type, fn) {element.addEventListener(type, fn, false);} : function(element, type, fn) {element.attachEvent('on' + type, fn);}), removeEventListenerFn = (window.document.removeEventListener ? function(element, type, fn) {element.removeEventListener(type, fn, false); } : function(element, type, fn) {element.detachEvent('on' + type, fn); }); function jqNextId() { return ++jqId; } var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g; var MOZ_HACK_REGEXP = /^moz([A-Z])/; /** * Converts snake_case to camelCase. * Also there is special case for Moz prefix starting with upper case letter. * @param name Name to normalize */ function camelCase(name) { return name. replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) { return offset ? letter.toUpperCase() : letter; }). replace(MOZ_HACK_REGEXP, 'Moz$1'); } ///////////////////////////////////////////// // jQuery mutation patch // // In conjunction with bindJQuery intercepts all jQuery's DOM destruction apis and fires a // $destroy event on all DOM nodes being removed. // ///////////////////////////////////////////// function JQLitePatchJQueryRemove(name, dispatchThis) { var originalJqFn = jQuery.fn[name]; originalJqFn = originalJqFn.$original || originalJqFn; removePatch.$original = originalJqFn; jQuery.fn[name] = removePatch; function removePatch() { var list = [this], fireEvent = dispatchThis, set, setIndex, setLength, element, childIndex, childLength, children, fns, events; while(list.length) { set = list.shift(); for(setIndex = 0, setLength = set.length; setIndex < setLength; setIndex++) { element = jqLite(set[setIndex]); if (fireEvent) { events = element.data('events'); if ( (fns = events && events.$destroy) ) { forEach(fns, function(fn){ fn.handler(); }); } } else { fireEvent = !fireEvent; } for(childIndex = 0, childLength = (children = element.children()).length; childIndex < childLength; childIndex++) { list.push(jQuery(children[childIndex])); } } } return originalJqFn.apply(this, arguments); } } ///////////////////////////////////////////// function JQLite(element) { if (element instanceof JQLite) { return element; } if (!(this instanceof JQLite)) { if (isString(element) && element.charAt(0) != '<') { throw Error('selectors not implemented'); } return new JQLite(element); } if (isString(element)) { var div = document.createElement('div'); // Read about the NoScope elements here: // http://msdn.microsoft.com/en-us/library/ms533897(VS.85).aspx div.innerHTML = '<div>&#160;</div>' + element; // IE insanity to make NoScope elements work! div.removeChild(div.firstChild); // remove the superfluous div JQLiteAddNodes(this, div.childNodes); this.remove(); // detach the elements from the temporary DOM div. } else { JQLiteAddNodes(this, element); } } function JQLiteClone(element) { return element.cloneNode(true); } function JQLiteDealoc(element){ JQLiteRemoveData(element); for ( var i = 0, children = element.childNodes || []; i < children.length; i++) { JQLiteDealoc(children[i]); } } function JQLiteUnbind(element, type, fn) { var events = JQLiteExpandoStore(element, 'events'), handle = JQLiteExpandoStore(element, 'handle'); if (!handle) return; //no listeners registered if (isUndefined(type)) { forEach(events, function(eventHandler, type) { removeEventListenerFn(element, type, eventHandler); delete events[type]; }); } else { if (isUndefined(fn)) { removeEventListenerFn(element, type, events[type]); delete events[type]; } else { arrayRemove(events[type], fn); } } } function JQLiteRemoveData(element) { var expandoId = element[jqName], expandoStore = jqCache[expandoId]; if (expandoStore) { if (expandoStore.handle) { expandoStore.events.$destroy && expandoStore.handle({}, '$destroy'); JQLiteUnbind(element); } delete jqCache[expandoId]; element[jqName] = undefined; // ie does not allow deletion of attributes on elements. } } function JQLiteExpandoStore(element, key, value) { var expandoId = element[jqName], expandoStore = jqCache[expandoId || -1]; if (isDefined(value)) { if (!expandoStore) { element[jqName] = expandoId = jqNextId(); expandoStore = jqCache[expandoId] = {}; } expandoStore[key] = value; } else { return expandoStore && expandoStore[key]; } } function JQLiteData(element, key, value) { var data = JQLiteExpandoStore(element, 'data'), isSetter = isDefined(value), keyDefined = !isSetter && isDefined(key), isSimpleGetter = keyDefined && !isObject(key); if (!data && !isSimpleGetter) { JQLiteExpandoStore(element, 'data', data = {}); } if (isSetter) { data[key] = value; } else { if (keyDefined) { if (isSimpleGetter) { // don't create data in this case. return data && data[key]; } else { extend(data, key); } } else { return data; } } } function JQLiteHasClass(element, selector) { return ((" " + element.className + " ").replace(/[\n\t]/g, " "). indexOf( " " + selector + " " ) > -1); } function JQLiteRemoveClass(element, selector) { if (selector) { forEach(selector.split(' '), function(cssClass) { element.className = trim( (" " + element.className + " ") .replace(/[\n\t]/g, " ") .replace(" " + trim(cssClass) + " ", " ") ); }); } } function JQLiteAddClass(element, selector) { if (selector) { forEach(selector.split(' '), function(cssClass) { if (!JQLiteHasClass(element, cssClass)) { element.className = trim(element.className + ' ' + trim(cssClass)); } }); } } function JQLiteAddNodes(root, elements) { if (elements) { elements = (!elements.nodeName && isDefined(elements.length) && !isWindow(elements)) ? elements : [ elements ]; for(var i=0; i < elements.length; i++) { root.push(elements[i]); } } } function JQLiteController(element, name) { return JQLiteInheritedData(element, '$' + (name || 'ngController' ) + 'Controller'); } function JQLiteInheritedData(element, name, value) { element = jqLite(element); // if element is the document object work with the html element instead // this makes $(document).scope() possible if(element[0].nodeType == 9) { element = element.find('html'); } while (element.length) { if (value = element.data(name)) return value; element = element.parent(); } } ////////////////////////////////////////// // Functions which are declared directly. ////////////////////////////////////////// var JQLitePrototype = JQLite.prototype = { ready: function(fn) { var fired = false; function trigger() { if (fired) return; fired = true; fn(); } this.bind('DOMContentLoaded', trigger); // works for modern browsers and IE9 // we can not use jqLite since we are not done loading and jQuery could be loaded later. JQLite(window).bind('load', trigger); // fallback to window.onload for others }, toString: function() { var value = []; forEach(this, function(e){ value.push('' + e);}); return '[' + value.join(', ') + ']'; }, eq: function(index) { return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]); }, length: 0, push: push, sort: [].sort, splice: [].splice }; ////////////////////////////////////////// // Functions iterating getter/setters. // these functions return self on setter and // value on get. ////////////////////////////////////////// var BOOLEAN_ATTR = {}; forEach('multiple,selected,checked,disabled,readOnly,required'.split(','), function(value) { BOOLEAN_ATTR[lowercase(value)] = value; }); var BOOLEAN_ELEMENTS = {}; forEach('input,select,option,textarea,button,form'.split(','), function(value) { BOOLEAN_ELEMENTS[uppercase(value)] = true; }); function getBooleanAttrName(element, name) { // check dom last since we will most likely fail on name var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()]; // booleanAttr is here twice to minimize DOM access return booleanAttr && BOOLEAN_ELEMENTS[element.nodeName] && booleanAttr; } forEach({ data: JQLiteData, inheritedData: JQLiteInheritedData, scope: function(element) { return JQLiteInheritedData(element, '$scope'); }, controller: JQLiteController , injector: function(element) { return JQLiteInheritedData(element, '$injector'); }, removeAttr: function(element,name) { element.removeAttribute(name); }, hasClass: JQLiteHasClass, css: function(element, name, value) { name = camelCase(name); if (isDefined(value)) { element.style[name] = value; } else { var val; if (msie <= 8) { // this is some IE specific weirdness that jQuery 1.6.4 does not sure why val = element.currentStyle && element.currentStyle[name]; if (val === '') val = 'auto'; } val = val || element.style[name]; if (msie <= 8) { // jquery weirdness :-/ val = (val === '') ? undefined : val; } return val; } }, attr: function(element, name, value){ var lowercasedName = lowercase(name); if (BOOLEAN_ATTR[lowercasedName]) { if (isDefined(value)) { if (!!value) { element[name] = true; element.setAttribute(name, lowercasedName); } else { element[name] = false; element.removeAttribute(lowercasedName); } } else { return (element[name] || (element.attributes.getNamedItem(name)|| noop).specified) ? lowercasedName : undefined; } } else if (isDefined(value)) { element.setAttribute(name, value); } else if (element.getAttribute) { // the extra argument "2" is to get the right thing for a.href in IE, see jQuery code // some elements (e.g. Document) don't have get attribute, so return undefined var ret = element.getAttribute(name, 2); // normalize non-existing attributes to undefined (as jQuery) return ret === null ? undefined : ret; } }, prop: function(element, name, value) { if (isDefined(value)) { element[name] = value; } else { return element[name]; } }, text: extend((msie < 9) ? function(element, value) { if (element.nodeType == 1 /** Element */) { if (isUndefined(value)) return element.innerText; element.innerText = value; } else { if (isUndefined(value)) return element.nodeValue; element.nodeValue = value; } } : function(element, value) { if (isUndefined(value)) { return element.textContent; } element.textContent = value; }, {$dv:''}), val: function(element, value) { if (isUndefined(value)) { return element.value; } element.value = value; }, html: function(element, value) { if (isUndefined(value)) { return element.innerHTML; } for (var i = 0, childNodes = element.childNodes; i < childNodes.length; i++) { JQLiteDealoc(childNodes[i]); } element.innerHTML = value; } }, function(fn, name){ /** * Properties: writes return selection, reads return first value */ JQLite.prototype[name] = function(arg1, arg2) { var i, key; // JQLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it // in a way that survives minification. if (((fn.length == 2 && (fn !== JQLiteHasClass && fn !== JQLiteController)) ? arg1 : arg2) === undefined) { if (isObject(arg1)) { // we are a write, but the object properties are the key/values for(i=0; i < this.length; i++) { if (fn === JQLiteData) { // data() takes the whole object in jQuery fn(this[i], arg1); } else { for (key in arg1) { fn(this[i], key, arg1[key]); } } } // return self for chaining return this; } else { // we are a read, so read the first child. if (this.length) return fn(this[0], arg1, arg2); } } else { // we are a write, so apply to all children for(i=0; i < this.length; i++) { fn(this[i], arg1, arg2); } // return self for chaining return this; } return fn.$dv; }; }); function createEventHandler(element, events) { var eventHandler = function (event, type) { if (!event.preventDefault) { event.preventDefault = function() { event.returnValue = false; //ie }; } if (!event.stopPropagation) { event.stopPropagation = function() { event.cancelBubble = true; //ie }; } if (!event.target) { event.target = event.srcElement || document; } if (isUndefined(event.defaultPrevented)) { var prevent = event.preventDefault; event.preventDefault = function() { event.defaultPrevented = true; prevent.call(event); }; event.defaultPrevented = false; } event.isDefaultPrevented = function() { return event.defaultPrevented; }; forEach(events[type || event.type], function(fn) { fn.call(element, event); }); // Remove monkey-patched methods (IE), // as they would cause memory leaks in IE8. if (msie <= 8) { // IE7/8 does not allow to delete property on native object event.preventDefault = null; event.stopPropagation = null; event.isDefaultPrevented = null; } else { // It shouldn't affect normal browsers (native methods are defined on prototype). delete event.preventDefault; delete event.stopPropagation; delete event.isDefaultPrevented; } }; eventHandler.elem = element; return eventHandler; } ////////////////////////////////////////// // Functions iterating traversal. // These functions chain results into a single // selector. ////////////////////////////////////////// forEach({ removeData: JQLiteRemoveData, dealoc: JQLiteDealoc, bind: function bindFn(element, type, fn){ var events = JQLiteExpandoStore(element, 'events'), handle = JQLiteExpandoStore(element, 'handle'); if (!events) JQLiteExpandoStore(element, 'events', events = {}); if (!handle) JQLiteExpandoStore(element, 'handle', handle = createEventHandler(element, events)); forEach(type.split(' '), function(type){ var eventFns = events[type]; if (!eventFns) { if (type == 'mouseenter' || type == 'mouseleave') { var counter = 0; events.mouseenter = []; events.mouseleave = []; bindFn(element, 'mouseover', function(event) { counter++; if (counter == 1) { handle(event, 'mouseenter'); } }); bindFn(element, 'mouseout', function(event) { counter --; if (counter == 0) { handle(event, 'mouseleave'); } }); } else { addEventListenerFn(element, type, handle); events[type] = []; } eventFns = events[type] } eventFns.push(fn); }); }, unbind: JQLiteUnbind, replaceWith: function(element, replaceNode) { var index, parent = element.parentNode; JQLiteDealoc(element); forEach(new JQLite(replaceNode), function(node){ if (index) { parent.insertBefore(node, index.nextSibling); } else { parent.replaceChild(node, element); } index = node; }); }, children: function(element) { var children = []; forEach(element.childNodes, function(element){ if (element.nodeName != '#text') children.push(element); }); return children; }, contents: function(element) { return element.childNodes; }, append: function(element, node) { forEach(new JQLite(node), function(child){ if (element.nodeType === 1) element.appendChild(child); }); }, prepend: function(element, node) { if (element.nodeType === 1) { var index = element.firstChild; forEach(new JQLite(node), function(child){ if (index) { element.insertBefore(child, index); } else { element.appendChild(child); index = child; } }); } }, wrap: function(element, wrapNode) { wrapNode = jqLite(wrapNode)[0]; var parent = element.parentNode; if (parent) { parent.replaceChild(wrapNode, element); } wrapNode.appendChild(element); }, remove: function(element) { JQLiteDealoc(element); var parent = element.parentNode; if (parent) parent.removeChild(element); }, after: function(element, newElement) { var index = element, parent = element.parentNode; forEach(new JQLite(newElement), function(node){ parent.insertBefore(node, index.nextSibling); index = node; }); }, addClass: JQLiteAddClass, removeClass: JQLiteRemoveClass, toggleClass: function(element, selector, condition) { if (isUndefined(condition)) { condition = !JQLiteHasClass(element, selector); } (condition ? JQLiteAddClass : JQLiteRemoveClass)(element, selector); }, parent: function(element) { var parent = element.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, next: function(element) { return element.nextSibling; }, find: function(element, selector) { return element.getElementsByTagName(selector); }, clone: JQLiteClone }, function(fn, name){ /** * chaining functions */ JQLite.prototype[name] = function(arg1, arg2) { var value; for(var i=0; i < this.length; i++) { if (value == undefined) { value = fn(this[i], arg1, arg2); if (value !== undefined) { // any function which returns a value needs to be wrapped value = jqLite(value); } } else { JQLiteAddNodes(value, fn(this[i], arg1, arg2)); } } return value == undefined ? this : value; }; }); /** * Computes a hash of an 'obj'. * Hash of a: * string is string * number is number as string * object is either result of calling $$hashKey function on the object or uniquely generated id, * that is also assigned to the $$hashKey property of the object. * * @param obj * @returns {string} hash string such that the same input will have the same hash string. * The resulting string key is in 'type:hashKey' format. */ function hashKey(obj) { var objType = typeof obj, key; if (objType == 'object' && obj !== null) { if (typeof (key = obj.$$hashKey) == 'function') { // must invoke on object to keep the right this key = obj.$$hashKey(); } else if (key === undefined) { key = obj.$$hashKey = nextUid(); } } else { key = obj; } return objType + ':' + key; } /** * HashMap which can use objects as keys */ function HashMap(array){ forEach(array, this.put, this); } HashMap.prototype = { /** * Store key value pair * @param key key to store can be any type * @param value value to store can be any type */ put: function(key, value) { this[hashKey(key)] = value; }, /** * @param key * @returns the value for the key */ get: function(key) { return this[hashKey(key)]; }, /** * Remove the key/value pair * @param key */ remove: function(key) { var value = this[key = hashKey(key)]; delete this[key]; return value; } }; /** * A map where multiple values can be added to the same key such that they form a queue. * @returns {HashQueueMap} */ function HashQueueMap() {} HashQueueMap.prototype = { /** * Same as array push, but using an array as the value for the hash */ push: function(key, value) { var array = this[key = hashKey(key)]; if (!array) { this[key] = [value]; } else { array.push(value); } }, /** * Same as array shift, but using an array as the value for the hash */ shift: function(key) { var array = this[key = hashKey(key)]; if (array) { if (array.length == 1) { delete this[key]; return array[0]; } else { return array.shift(); } } } }; /** * @ngdoc function * @name angular.injector * @function * * @description * Creates an injector function that can be used for retrieving services as well as for * dependency injection (see {@link guide/di dependency injection}). * * @param {Array.<string|Function>} modules A list of module functions or their aliases. See * {@link angular.module}. The `ng` module must be explicitly added. * @returns {function()} Injector function. See {@link AUTO.$injector $injector}. * * @example * Typical usage * <pre> * // create an injector * var $injector = angular.injector(['ng']); * * // use the injector to kick of your application * // use the type inference to auto inject arguments, or use implicit injection * $injector.invoke(function($rootScope, $compile, $document){ * $compile($document)($rootScope); * $rootScope.$digest(); * }); * </pre> */ /** * @ngdoc overview * @name AUTO * @description * * Implicit module which gets automatically added to each {@link AUTO.$injector $injector}. */ var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m; var FN_ARG_SPLIT = /,/; var FN_ARG = /^\s*(_?)(.+?)\1\s*$/; var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg; function annotate(fn) { var $inject, fnText, argDecl, last; if (typeof fn == 'function') { if (!($inject = fn.$inject)) { $inject = []; fnText = fn.toString().replace(STRIP_COMMENTS, ''); argDecl = fnText.match(FN_ARGS); forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg){ arg.replace(FN_ARG, function(all, underscore, name){ $inject.push(name); }); }); fn.$inject = $inject; } } else if (isArray(fn)) { last = fn.length - 1; assertArgFn(fn[last], 'fn') $inject = fn.slice(0, last); } else { assertArgFn(fn, 'fn', true); } return $inject; } /////////////////////////////////////// /** * @ngdoc object * @name AUTO.$injector * @function * * @description * * `$injector` is used to retrieve object instances as defined by * {@link AUTO.$provide provider}, instantiate types, invoke methods, * and load modules. * * The following always holds true: * * <pre> * var $injector = angular.injector(); * expect($injector.get('$injector')).toBe($injector); * expect($injector.invoke(function($injector){ * return $injector; * }).toBe($injector); * </pre> * * # Injection Function Annotation * * JavaScript does not have annotations, and annotations are needed for dependency injection. The * following ways are all valid way of annotating function with injection arguments and are equivalent. * * <pre> * // inferred (only works if code not minified/obfuscated) * $inject.invoke(function(serviceA){}); * * // annotated * function explicit(serviceA) {}; * explicit.$inject = ['serviceA']; * $inject.invoke(explicit); * * // inline * $inject.invoke(['serviceA', function(serviceA){}]); * </pre> * * ## Inference * * In JavaScript calling `toString()` on a function returns the function definition. The definition can then be * parsed and the function arguments can be extracted. *NOTE:* This does not work with minification, and obfuscation * tools since these tools change the argument names. * * ## `$inject` Annotation * By adding a `$inject` property onto a function the injection parameters can be specified. * * ## Inline * As an array of injection names, where the last item in the array is the function to call. */ /** * @ngdoc method * @name AUTO.$injector#get * @methodOf AUTO.$injector * * @description * Return an instance of the service. * * @param {string} name The name of the instance to retrieve. * @return {*} The instance. */ /** * @ngdoc method * @name AUTO.$injector#invoke * @methodOf AUTO.$injector * * @description * Invoke the method and supply the method arguments from the `$injector`. * * @param {!function} fn The function to invoke. The function arguments come form the function annotation. * @param {Object=} self The `this` for the invoked method. * @param {Object=} locals Optional object. If preset then any argument names are read from this object first, before * the `$injector` is consulted. * @returns {*} the value returned by the invoked `fn` function. */ /** * @ngdoc method * @name AUTO.$injector#instantiate * @methodOf AUTO.$injector * @description * Create a new instance of JS type. The method takes a constructor function invokes the new operator and supplies * all of the arguments to the constructor function as specified by the constructor annotation. * * @param {function} Type Annotated constructor function. * @param {Object=} locals Optional object. If preset then any argument names are read from this object first, before * the `$injector` is consulted. * @returns {Object} new instance of `Type`. */ /** * @ngdoc method * @name AUTO.$injector#annotate * @methodOf AUTO.$injector * * @description * Returns an array of service names which the function is requesting for injection. This API is used by the injector * to determine which services need to be injected into the function when the function is invoked. There are three * ways in which the function can be annotated with the needed dependencies. * * # Argument names * * The simplest form is to extract the dependencies from the arguments of the function. This is done by converting * the function into a string using `toString()` method and extracting the argument names. * <pre> * // Given * function MyController($scope, $route) { * // ... * } * * // Then * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']); * </pre> * * This method does not work with code minfication / obfuscation. For this reason the following annotation strategies * are supported. * * # The `$injector` property * * If a function has an `$inject` property and its value is an array of strings, then the strings represent names of * services to be injected into the function. * <pre> * // Given * var MyController = function(obfuscatedScope, obfuscatedRoute) { * // ... * } * // Define function dependencies * MyController.$inject = ['$scope', '$route']; * * // Then * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']); * </pre> * * # The array notation * * It is often desirable to inline Injected functions and that's when setting the `$inject` property is very * inconvenient. In these situations using the array notation to specify the dependencies in a way that survives * minification is a better choice: * * <pre> * // We wish to write this (not minification / obfuscation safe) * injector.invoke(function($compile, $rootScope) { * // ... * }); * * // We are forced to write break inlining * var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) { * // ... * }; * tmpFn.$inject = ['$compile', '$rootScope']; * injector.invoke(tempFn); * * // To better support inline function the inline annotation is supported * injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) { * // ... * }]); * * // Therefore * expect(injector.annotate( * ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}]) * ).toEqual(['$compile', '$rootScope']); * </pre> * * @param {function|Array.<string|Function>} fn Function for which dependent service names need to be retrieved as described * above. * * @returns {Array.<string>} The names of the services which the function requires. */ /** * @ngdoc object * @name AUTO.$provide * * @description * * Use `$provide` to register new providers with the `$injector`. The providers are the factories for the instance. * The providers share the same name as the instance they create with the `Provider` suffixed to them. * * A provider is an object with a `$get()` method. The injector calls the `$get` method to create a new instance of * a service. The Provider can have additional methods which would allow for configuration of the provider. * * <pre> * function GreetProvider() { * var salutation = 'Hello'; * * this.salutation = function(text) { * salutation = text; * }; * * this.$get = function() { * return function (name) { * return salutation + ' ' + name + '!'; * }; * }; * } * * describe('Greeter', function(){ * * beforeEach(module(function($provide) { * $provide.provider('greet', GreetProvider); * }); * * it('should greet', inject(function(greet) { * expect(greet('angular')).toEqual('Hello angular!'); * })); * * it('should allow configuration of salutation', function() { * module(function(greetProvider) { * greetProvider.salutation('Ahoj'); * }); * inject(function(greet) { * expect(greet('angular')).toEqual('Ahoj angular!'); * }); * )}; * * }); * </pre> */ /** * @ngdoc method * @name AUTO.$provide#provider * @methodOf AUTO.$provide * @description * * Register a provider for a service. The providers can be retrieved and can have additional configuration methods. * * @param {string} name The name of the instance. NOTE: the provider will be available under `name + 'Provider'` key. * @param {(Object|function())} provider If the provider is: * * - `Object`: then it should have a `$get` method. The `$get` method will be invoked using * {@link AUTO.$injector#invoke $injector.invoke()} when an instance needs to be created. * - `Constructor`: a new instance of the provider will be created using * {@link AUTO.$injector#instantiate $injector.instantiate()}, then treated as `object`. * * @returns {Object} registered provider instance */ /** * @ngdoc method * @name AUTO.$provide#factory * @methodOf AUTO.$provide * @description * * A short hand for configuring services if only `$get` method is required. * * @param {string} name The name of the instance. * @param {function()} $getFn The $getFn for the instance creation. Internally this is a short hand for * `$provide.provider(name, {$get: $getFn})`. * @returns {Object} registered provider instance */ /** * @ngdoc method * @name AUTO.$provide#service * @methodOf AUTO.$provide * @description * * A short hand for registering service of given class. * * @param {string} name The name of the instance. * @param {Function} constructor A class (constructor function) that will be instantiated. * @returns {Object} registered provider instance */ /** * @ngdoc method * @name AUTO.$provide#value * @methodOf AUTO.$provide * @description * * A short hand for configuring services if the `$get` method is a constant. * * @param {string} name The name of the instance. * @param {*} value The value. * @returns {Object} registered provider instance */ /** * @ngdoc method * @name AUTO.$provide#constant * @methodOf AUTO.$provide * @description * * A constant value, but unlike {@link AUTO.$provide#value value} it can be injected * into configuration function (other modules) and it is not interceptable by * {@link AUTO.$provide#decorator decorator}. * * @param {string} name The name of the constant. * @param {*} value The constant value. * @returns {Object} registered instance */ /** * @ngdoc method * @name AUTO.$provide#decorator * @methodOf AUTO.$provide * @description * * Decoration of service, allows the decorator to intercept the service instance creation. The * returned instance may be the original instance, or a new instance which delegates to the * original instance. * * @param {string} name The name of the service to decorate. * @param {function()} decorator This function will be invoked when the service needs to be * instanciated. The function is called using the {@link AUTO.$injector#invoke * injector.invoke} method and is therefore fully injectable. Local injection arguments: * * * `$delegate` - The original service instance, which can be monkey patched, configured, * decorated or delegated to. */ function createInjector(modulesToLoad) { var INSTANTIATING = {}, providerSuffix = 'Provider', path = [], loadedModules = new HashMap(), providerCache = { $provide: { provider: supportObject(provider), factory: supportObject(factory), service: supportObject(service), value: supportObject(value), constant: supportObject(constant), decorator: decorator } }, providerInjector = createInternalInjector(providerCache, function() { throw Error("Unknown provider: " + path.join(' <- ')); }), instanceCache = {}, instanceInjector = (instanceCache.$injector = createInternalInjector(instanceCache, function(servicename) { var provider = providerInjector.get(servicename + providerSuffix); return instanceInjector.invoke(provider.$get, provider); })); forEach(loadModules(modulesToLoad), function(fn) { instanceInjector.invoke(fn || noop); }); return instanceInjector; //////////////////////////////////// // $provider //////////////////////////////////// function supportObject(delegate) { return function(key, value) { if (isObject(key)) { forEach(key, reverseParams(delegate)); } else { return delegate(key, value); } } } function provider(name, provider_) { if (isFunction(provider_)) { provider_ = providerInjector.instantiate(provider_); } if (!provider_.$get) { throw Error('Provider ' + name + ' must define $get factory method.'); } return providerCache[name + providerSuffix] = provider_; } function factory(name, factoryFn) { return provider(name, { $get: factoryFn }); } function service(name, constructor) { return factory(name, ['$injector', function($injector) { return $injector.instantiate(constructor); }]); } function value(name, value) { return factory(name, valueFn(value)); } function constant(name, value) { providerCache[name] = value; instanceCache[name] = value; } function decorator(serviceName, decorFn) { var origProvider = providerInjector.get(serviceName + providerSuffix), orig$get = origProvider.$get; origProvider.$get = function() { var origInstance = instanceInjector.invoke(orig$get, origProvider); return instanceInjector.invoke(decorFn, null, {$delegate: origInstance}); }; } //////////////////////////////////// // Module Loading //////////////////////////////////// function loadModules(modulesToLoad){ var runBlocks = []; forEach(modulesToLoad, function(module) { if (loadedModules.get(module)) return; loadedModules.put(module, true); if (isString(module)) { var moduleFn = angularModule(module); runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks); try { for(var invokeQueue = moduleFn._invokeQueue, i = 0, ii = invokeQueue.length; i < ii; i++) { var invokeArgs = invokeQueue[i], provider = invokeArgs[0] == '$injector' ? providerInjector : providerInjector.get(invokeArgs[0]); provider[invokeArgs[1]].apply(provider, invokeArgs[2]); } } catch (e) { if (e.message) e.message += ' from ' + module; throw e; } } else if (isFunction(module)) { try { runBlocks.push(providerInjector.invoke(module)); } catch (e) { if (e.message) e.message += ' from ' + module; throw e; } } else if (isArray(module)) { try { runBlocks.push(providerInjector.invoke(module)); } catch (e) { if (e.message) e.message += ' from ' + String(module[module.length - 1]); throw e; } } else { assertArgFn(module, 'module'); } }); return runBlocks; } //////////////////////////////////// // internal Injector //////////////////////////////////// function createInternalInjector(cache, factory) { function getService(serviceName) { if (typeof serviceName !== 'string') { throw Error('Service name expected'); } if (cache.hasOwnProperty(serviceName)) { if (cache[serviceName] === INSTANTIATING) { throw Error('Circular dependency: ' + path.join(' <- ')); } return cache[serviceName]; } else { try { path.unshift(serviceName); cache[serviceName] = INSTANTIATING; return cache[serviceName] = factory(serviceName); } finally { path.shift(); } } } function invoke(fn, self, locals){ var args = [], $inject = annotate(fn), length, i, key; for(i = 0, length = $inject.length; i < length; i++) { key = $inject[i]; args.push( locals && locals.hasOwnProperty(key) ? locals[key] : getService(key, path) ); } if (!fn.$inject) { // this means that we must be an array. fn = fn[length]; } // Performance optimization: http://jsperf.com/apply-vs-call-vs-invoke switch (self ? -1 : args.length) { case 0: return fn(); case 1: return fn(args[0]); case 2: return fn(args[0], args[1]); case 3: return fn(args[0], args[1], args[2]); case 4: return fn(args[0], args[1], args[2], args[3]); case 5: return fn(args[0], args[1], args[2], args[3], args[4]); case 6: return fn(args[0], args[1], args[2], args[3], args[4], args[5]); case 7: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); case 8: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7]); case 9: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8]); case 10: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9]); default: return fn.apply(self, args); } } function instantiate(Type, locals) { var Constructor = function() {}, instance, returnedValue; Constructor.prototype = (isArray(Type) ? Type[Type.length - 1] : Type).prototype; instance = new Constructor(); returnedValue = invoke(Type, instance, locals); return isObject(returnedValue) ? returnedValue : instance; } return { invoke: invoke, instantiate: instantiate, get: getService, annotate: annotate }; } } /** * @ngdoc function * @name ng.$anchorScroll * @requires $window * @requires $location * @requires $rootScope * * @description * When called, it checks current value of `$location.hash()` and scroll to related element, * according to rules specified in * {@link http://dev.w3.org/html5/spec/Overview.html#the-indicated-part-of-the-document Html5 spec}. * * It also watches the `$location.hash()` and scroll whenever it changes to match any anchor. * This can be disabled by calling `$anchorScrollProvider.disableAutoScrolling()`. */ function $AnchorScrollProvider() { var autoScrollingEnabled = true; this.disableAutoScrolling = function() { autoScrollingEnabled = false; }; this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) { var document = $window.document; // helper function to get first anchor from a NodeList // can't use filter.filter, as it accepts only instances of Array // and IE can't convert NodeList to an array using [].slice // TODO(vojta): use filter if we change it to accept lists as well function getFirstAnchor(list) { var result = null; forEach(list, function(element) { if (!result && lowercase(element.nodeName) === 'a') result = element; }); return result; } function scroll() { var hash = $location.hash(), elm; // empty hash, scroll to the top of the page if (!hash) $window.scrollTo(0, 0); // element with given id else if ((elm = document.getElementById(hash))) elm.scrollIntoView(); // first anchor with given name :-D else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) elm.scrollIntoView(); // no element and hash == 'top', scroll to the top of the page else if (hash === 'top') $window.scrollTo(0, 0); } // does not scroll when user clicks on anchor link that is currently on // (no url change, no $locaiton.hash() change), browser native does scroll if (autoScrollingEnabled) { $rootScope.$watch(function() {return $location.hash();}, function() { $rootScope.$evalAsync(scroll); }); } return scroll; }]; } /** * ! This is a private undocumented service ! * * @name ng.$browser * @requires $log * @description * This object has two goals: * * - hide all the global state in the browser caused by the window object * - abstract away all the browser specific features and inconsistencies * * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser` * service, which can be used for convenient testing of the application without the interaction with * the real browser apis. */ /** * @param {object} window The global window object. * @param {object} document jQuery wrapped document. * @param {function()} XHR XMLHttpRequest constructor. * @param {object} $log console.log or an object with the same interface. * @param {object} $sniffer $sniffer service */ function Browser(window, document, $log, $sniffer) { var self = this, rawDocument = document[0], location = window.location, history = window.history, setTimeout = window.setTimeout, clearTimeout = window.clearTimeout, pendingDeferIds = {}; self.isMock = false; var outstandingRequestCount = 0; var outstandingRequestCallbacks = []; // TODO(vojta): remove this temporary api self.$$completeOutstandingRequest = completeOutstandingRequest; self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; }; /** * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks` * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed. */ function completeOutstandingRequest(fn) { try { fn.apply(null, sliceArgs(arguments, 1)); } finally { outstandingRequestCount--; if (outstandingRequestCount === 0) { while(outstandingRequestCallbacks.length) { try { outstandingRequestCallbacks.pop()(); } catch (e) { $log.error(e); } } } } } /** * @private * Note: this method is used only by scenario runner * TODO(vojta): prefix this method with $$ ? * @param {function()} callback Function that will be called when no outstanding request */ self.notifyWhenNoOutstandingRequests = function(callback) { // force browser to execute all pollFns - this is needed so that cookies and other pollers fire // at some deterministic time in respect to the test runner's actions. Leaving things up to the // regular poller would result in flaky tests. forEach(pollFns, function(pollFn){ pollFn(); }); if (outstandingRequestCount === 0) { callback(); } else { outstandingRequestCallbacks.push(callback); } }; ////////////////////////////////////////////////////////////// // Poll Watcher API ////////////////////////////////////////////////////////////// var pollFns = [], pollTimeout; /** * @name ng.$browser#addPollFn * @methodOf ng.$browser * * @param {function()} fn Poll function to add * * @description * Adds a function to the list of functions that poller periodically executes, * and starts polling if not started yet. * * @returns {function()} the added function */ self.addPollFn = function(fn) { if (isUndefined(pollTimeout)) startPoller(100, setTimeout); pollFns.push(fn); return fn; }; /** * @param {number} interval How often should browser call poll functions (ms) * @param {function()} setTimeout Reference to a real or fake `setTimeout` function. * * @description * Configures the poller to run in the specified intervals, using the specified * setTimeout fn and kicks it off. */ function startPoller(interval, setTimeout) { (function check() { forEach(pollFns, function(pollFn){ pollFn(); }); pollTimeout = setTimeout(check, interval); })(); } ////////////////////////////////////////////////////////////// // URL API ////////////////////////////////////////////////////////////// var lastBrowserUrl = location.href, baseElement = document.find('base'); /** * @name ng.$browser#url * @methodOf ng.$browser * * @description * GETTER: * Without any argument, this method just returns current value of location.href. * * SETTER: * With at least one argument, this method sets url to new value. * If html5 history api supported, pushState/replaceState is used, otherwise * location.href/location.replace is used. * Returns its own instance to allow chaining * * NOTE: this api is intended for use only by the $location service. Please use the * {@link ng.$location $location service} to change url. * * @param {string} url New url (when used as setter) * @param {boolean=} replace Should new url replace current history record ? */ self.url = function(url, replace) { // setter if (url) { if (lastBrowserUrl == url) return; lastBrowserUrl = url; if ($sniffer.history) { if (replace) history.replaceState(null, '', url); else { history.pushState(null, '', url); // Crazy Opera Bug: http://my.opera.com/community/forums/topic.dml?id=1185462 baseElement.attr('href', baseElement.attr('href')); } } else { if (replace) location.replace(url); else location.href = url; } return self; // getter } else { // the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172 return location.href.replace(/%27/g,"'"); } }; var urlChangeListeners = [], urlChangeInit = false; function fireUrlChange() { if (lastBrowserUrl == self.url()) return; lastBrowserUrl = self.url(); forEach(urlChangeListeners, function(listener) { listener(self.url()); }); } /** * @name ng.$browser#onUrlChange * @methodOf ng.$browser * @TODO(vojta): refactor to use node's syntax for events * * @description * Register callback function that will be called, when url changes. * * It's only called when the url is changed by outside of angular: * - user types different url into address bar * - user clicks on history (forward/back) button * - user clicks on a link * * It's not called when url is changed by $browser.url() method * * The listener gets called with new url as parameter. * * NOTE: this api is intended for use only by the $location service. Please use the * {@link ng.$location $location service} to monitor url changes in angular apps. * * @param {function(string)} listener Listener function to be called when url changes. * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous. */ self.onUrlChange = function(callback) { if (!urlChangeInit) { // We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera) // don't fire popstate when user change the address bar and don't fire hashchange when url // changed by push/replaceState // html5 history api - popstate event if ($sniffer.history) jqLite(window).bind('popstate', fireUrlChange); // hashchange event if ($sniffer.hashchange) jqLite(window).bind('hashchange', fireUrlChange); // polling else self.addPollFn(fireUrlChange); urlChangeInit = true; } urlChangeListeners.push(callback); return callback; }; ////////////////////////////////////////////////////////////// // Misc API ////////////////////////////////////////////////////////////// /** * Returns current <base href> * (always relative - without domain) * * @returns {string=} */ self.baseHref = function() { var href = baseElement.attr('href'); return href ? href.replace(/^https?\:\/\/[^\/]*/, '') : href; }; ////////////////////////////////////////////////////////////// // Cookies API ////////////////////////////////////////////////////////////// var lastCookies = {}; var lastCookieString = ''; var cookiePath = self.baseHref(); /** * @name ng.$browser#cookies * @methodOf ng.$browser * * @param {string=} name Cookie name * @param {string=} value Cokkie value * * @description * The cookies method provides a 'private' low level access to browser cookies. * It is not meant to be used directly, use the $cookie service instead. * * The return values vary depending on the arguments that the method was called with as follows: * <ul> * <li>cookies() -> hash of all cookies, this is NOT a copy of the internal state, so do not modify it</li> * <li>cookies(name, value) -> set name to value, if value is undefined delete the cookie</li> * <li>cookies(name) -> the same as (name, undefined) == DELETES (no one calls it right now that way)</li> * </ul> * * @returns {Object} Hash of all cookies (if called without any parameter) */ self.cookies = function(name, value) { var cookieLength, cookieArray, cookie, i, index; if (name) { if (value === undefined) { rawDocument.cookie = escape(name) + "=;path=" + cookiePath + ";expires=Thu, 01 Jan 1970 00:00:00 GMT"; } else { if (isString(value)) { cookieLength = (rawDocument.cookie = escape(name) + '=' + escape(value) + ';path=' + cookiePath).length + 1; if (cookieLength > 4096) { $log.warn("Cookie '"+ name +"' possibly not set or overflowed because it was too large ("+ cookieLength + " > 4096 bytes)!"); } if (lastCookies.length > 20) { $log.warn("Cookie '"+ name +"' possibly not set or overflowed because too many cookies " + "were already set (" + lastCookies.length + " > 20 )"); } } } } else { if (rawDocument.cookie !== lastCookieString) { lastCookieString = rawDocument.cookie; cookieArray = lastCookieString.split("; "); lastCookies = {}; for (i = 0; i < cookieArray.length; i++) { cookie = cookieArray[i]; index = cookie.indexOf('='); if (index > 0) { //ignore nameless cookies lastCookies[unescape(cookie.substring(0, index))] = unescape(cookie.substring(index + 1)); } } } return lastCookies; } }; /** * @name ng.$browser#defer * @methodOf ng.$browser * @param {function()} fn A function, who's execution should be defered. * @param {number=} [delay=0] of milliseconds to defer the function execution. * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`. * * @description * Executes a fn asynchroniously via `setTimeout(fn, delay)`. * * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed * via `$browser.defer.flush()`. * */ self.defer = function(fn, delay) { var timeoutId; outstandingRequestCount++; timeoutId = setTimeout(function() { delete pendingDeferIds[timeoutId]; completeOutstandingRequest(fn); }, delay || 0); pendingDeferIds[timeoutId] = true; return timeoutId; }; /** * @name ng.$browser#defer.cancel * @methodOf ng.$browser.defer * * @description * Cancels a defered task identified with `deferId`. * * @param {*} deferId Token returned by the `$browser.defer` function. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfuly canceled. */ self.defer.cancel = function(deferId) { if (pendingDeferIds[deferId]) { delete pendingDeferIds[deferId]; clearTimeout(deferId); completeOutstandingRequest(noop); return true; } return false; }; } function $BrowserProvider(){ this.$get = ['$window', '$log', '$sniffer', '$document', function( $window, $log, $sniffer, $document){ return new Browser($window, $document, $log, $sniffer); }]; } /** * @ngdoc object * @name ng.$cacheFactory * * @description * Factory that constructs cache objects. * * * @param {string} cacheId Name or id of the newly created cache. * @param {object=} options Options object that specifies the cache behavior. Properties: * * - `{number=}` `capacity` — turns the cache into LRU cache. * * @returns {object} Newly created cache object with the following set of methods: * * - `{object}` `info()` — Returns id, size, and options of cache. * - `{void}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache. * - `{{*}} `get({string} key) — Returns cached value for `key` or undefined for cache miss. * - `{void}` `remove({string} key) — Removes a key-value pair from the cache. * - `{void}` `removeAll() — Removes all cached values. * - `{void}` `destroy() — Removes references to this cache from $cacheFactory. * */ function $CacheFactoryProvider() { this.$get = function() { var caches = {}; function cacheFactory(cacheId, options) { if (cacheId in caches) { throw Error('cacheId ' + cacheId + ' taken'); } var size = 0, stats = extend({}, options, {id: cacheId}), data = {}, capacity = (options && options.capacity) || Number.MAX_VALUE, lruHash = {}, freshEnd = null, staleEnd = null; return caches[cacheId] = { put: function(key, value) { var lruEntry = lruHash[key] || (lruHash[key] = {key: key}); refresh(lruEntry); if (isUndefined(value)) return; if (!(key in data)) size++; data[key] = value; if (size > capacity) { this.remove(staleEnd.key); } }, get: function(key) { var lruEntry = lruHash[key]; if (!lruEntry) return; refresh(lruEntry); return data[key]; }, remove: function(key) { var lruEntry = lruHash[key]; if (lruEntry == freshEnd) freshEnd = lruEntry.p; if (lruEntry == staleEnd) staleEnd = lruEntry.n; link(lruEntry.n,lruEntry.p); delete lruHash[key]; delete data[key]; size--; }, removeAll: function() { data = {}; size = 0; lruHash = {}; freshEnd = staleEnd = null; }, destroy: function() { data = null; stats = null; lruHash = null; delete caches[cacheId]; }, info: function() { return extend({}, stats, {size: size}); } }; /** * makes the `entry` the freshEnd of the LRU linked list */ function refresh(entry) { if (entry != freshEnd) { if (!staleEnd) { staleEnd = entry; } else if (staleEnd == entry) { staleEnd = entry.n; } link(entry.n, entry.p); link(entry, freshEnd); freshEnd = entry; freshEnd.n = null; } } /** * bidirectionally links two entries of the LRU linked list */ function link(nextEntry, prevEntry) { if (nextEntry != prevEntry) { if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify } } } cacheFactory.info = function() { var info = {}; forEach(caches, function(cache, cacheId) { info[cacheId] = cache.info(); }); return info; }; cacheFactory.get = function(cacheId) { return caches[cacheId]; }; return cacheFactory; }; } /** * @ngdoc object * @name ng.$templateCache * * @description * Cache used for storing html templates. * * See {@link ng.$cacheFactory $cacheFactory}. * */ function $TemplateCacheProvider() { this.$get = ['$cacheFactory', function($cacheFactory) { return $cacheFactory('templates'); }]; } /* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE! * * DOM-related variables: * * - "node" - DOM Node * - "element" - DOM Element or Node * - "$node" or "$element" - jqLite-wrapped node or element * * * Compiler related stuff: * * - "linkFn" - linking fn of a single directive * - "nodeLinkFn" - function that aggregates all linking fns for a particular node * - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node * - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList) */ var NON_ASSIGNABLE_MODEL_EXPRESSION = 'Non-assignable model expression: '; /** * @ngdoc function * @name ng.$compile * @function * * @description * Compiles a piece of HTML string or DOM into a template and produces a template function, which * can then be used to link {@link ng.$rootScope.Scope scope} and the template together. * * The compilation is a process of walking the DOM tree and trying to match DOM elements to * {@link ng.$compileProvider#directive directives}. For each match it * executes corresponding template function and collects the * instance functions into a single template function which is then returned. * * The template function can then be used once to produce the view or as it is the case with * {@link ng.directive:ngRepeat repeater} many-times, in which * case each call results in a view that is a DOM clone of the original template. * <doc:example module="compile"> <doc:source> <script> // declare a new module, and inject the $compileProvider angular.module('compile', [], function($compileProvider) { // configure new 'compile' directive by passing a directive // factory function. The factory function injects the '$compile' $compileProvider.directive('compile', function($compile) { // directive factory creates a link function return function(scope, element, attrs) { scope.$watch( function(scope) { // watch the 'compile' expression for changes return scope.$eval(attrs.compile); }, function(value) { // when the 'compile' expression changes // assign it into the current DOM element.html(value); // compile the new DOM and link it to the current // scope. // NOTE: we only compile .childNodes so that // we don't get into infinite loop compiling ourselves $compile(element.contents())(scope); } ); }; }) }); function Ctrl($scope) { $scope.name = 'Angular'; $scope.html = 'Hello {{name}}'; } </script> <div ng-controller="Ctrl"> <input ng-model="name"> <br> <textarea ng-model="html"></textarea> <br> <div compile="html"></div> </div> </doc:source> <doc:scenario> it('should auto compile', function() { expect(element('div[compile]').text()).toBe('Hello Angular'); input('html').enter('{{name}}!'); expect(element('div[compile]').text()).toBe('Angular!'); }); </doc:scenario> </doc:example> * * * @param {string|DOMElement} element Element or HTML string to compile into a template function. * @param {function(angular.Scope[, cloneAttachFn]} transclude function available to directives. * @param {number} maxPriority only apply directives lower then given priority (Only effects the * root element(s), not their children) * @returns {function(scope[, cloneAttachFn])} a link function which is used to bind template * (a DOM element/tree) to a scope. Where: * * * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to. * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the * `template` and call the `cloneAttachFn` function allowing the caller to attach the * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is * called as: <br> `cloneAttachFn(clonedElement, scope)` where: * * * `clonedElement` - is a clone of the original `element` passed into the compiler. * * `scope` - is the current scope with which the linking function is working with. * * Calling the linking function returns the element of the template. It is either the original element * passed in, or the clone of the element if the `cloneAttachFn` is provided. * * After linking the view is not updated until after a call to $digest which typically is done by * Angular automatically. * * If you need access to the bound view, there are two ways to do it: * * - If you are not asking the linking function to clone the template, create the DOM element(s) * before you send them to the compiler and keep this reference around. * <pre> * var element = $compile('<p>{{total}}</p>')(scope); * </pre> * * - if on the other hand, you need the element to be cloned, the view reference from the original * example would not point to the clone, but rather to the original template that was cloned. In * this case, you can access the clone via the cloneAttachFn: * <pre> * var templateHTML = angular.element('<p>{{total}}</p>'), * scope = ....; * * var clonedElement = $compile(templateHTML)(scope, function(clonedElement, scope) { * //attach the clone to DOM document at the right place * }); * * //now we have reference to the cloned DOM via `clone` * </pre> * * * For information on how the compiler works, see the * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide. */ /** * @ngdoc service * @name ng.$compileProvider * @function * * @description */ $CompileProvider.$inject = ['$provide']; function $CompileProvider($provide) { var hasDirectives = {}, Suffix = 'Directive', COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\d\w\-_]+)\s+(.*)$/, CLASS_DIRECTIVE_REGEXP = /(([\d\w\-_]+)(?:\:([^;]+))?;?)/, MULTI_ROOT_TEMPLATE_ERROR = 'Template must have exactly one root element. was: '; /** * @ngdoc function * @name ng.$compileProvider#directive * @methodOf ng.$compileProvider * @function * * @description * Register a new directives with the compiler. * * @param {string} name Name of the directive in camel-case. (ie <code>ngBind</code> which will match as * <code>ng-bind</code>). * @param {function} directiveFactory An injectable directive factroy function. See {@link guide/directive} for more * info. * @returns {ng.$compileProvider} Self for chaining. */ this.directive = function registerDirective(name, directiveFactory) { if (isString(name)) { assertArg(directiveFactory, 'directive'); if (!hasDirectives.hasOwnProperty(name)) { hasDirectives[name] = []; $provide.factory(name + Suffix, ['$injector', '$exceptionHandler', function($injector, $exceptionHandler) { var directives = []; forEach(hasDirectives[name], function(directiveFactory) { try { var directive = $injector.invoke(directiveFactory); if (isFunction(directive)) { directive = { compile: valueFn(directive) }; } else if (!directive.compile && directive.link) { directive.compile = valueFn(directive.link); } directive.priority = directive.priority || 0; directive.name = directive.name || name; directive.require = directive.require || (directive.controller && directive.name); directive.restrict = directive.restrict || 'A'; directives.push(directive); } catch (e) { $exceptionHandler(e); } }); return directives; }]); } hasDirectives[name].push(directiveFactory); } else { forEach(name, reverseParams(registerDirective)); } return this; }; this.$get = [ '$injector', '$interpolate', '$exceptionHandler', '$http', '$templateCache', '$parse', '$controller', '$rootScope', function($injector, $interpolate, $exceptionHandler, $http, $templateCache, $parse, $controller, $rootScope) { var Attributes = function(element, attr) { this.$$element = element; this.$attr = attr || {}; }; Attributes.prototype = { $normalize: directiveNormalize, /** * Set a normalized attribute on the element in a way such that all directives * can share the attribute. This function properly handles boolean attributes. * @param {string} key Normalized key. (ie ngAttribute) * @param {string|boolean} value The value to set. If `null` attribute will be deleted. * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute. * Defaults to true. * @param {string=} attrName Optional none normalized name. Defaults to key. */ $set: function(key, value, writeAttr, attrName) { var booleanKey = getBooleanAttrName(this.$$element[0], key), $$observers = this.$$observers; if (booleanKey) { this.$$element.prop(key, value); attrName = booleanKey; } this[key] = value; // translate normalized key to actual key if (attrName) { this.$attr[key] = attrName; } else { attrName = this.$attr[key]; if (!attrName) { this.$attr[key] = attrName = snake_case(key, '-'); } } if (writeAttr !== false) { if (value === null || value === undefined) { this.$$element.removeAttr(attrName); } else { this.$$element.attr(attrName, value); } } // fire observers $$observers && forEach($$observers[key], function(fn) { try { fn(value); } catch (e) { $exceptionHandler(e); } }); }, /** * Observe an interpolated attribute. * The observer will never be called, if given attribute is not interpolated. * * @param {string} key Normalized key. (ie ngAttribute) . * @param {function(*)} fn Function that will be called whenever the attribute value changes. * @returns {function(*)} the `fn` Function passed in. */ $observe: function(key, fn) { var attrs = this, $$observers = (attrs.$$observers || (attrs.$$observers = {})), listeners = ($$observers[key] || ($$observers[key] = [])); listeners.push(fn); $rootScope.$evalAsync(function() { if (!listeners.$$inter) { // no one registered attribute interpolation function, so lets call it manually fn(attrs[key]); } }); return fn; } }; var startSymbol = $interpolate.startSymbol(), endSymbol = $interpolate.endSymbol(), denormalizeTemplate = (startSymbol == '{{' || endSymbol == '}}') ? identity : function denormalizeTemplate(template) { return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol); }; return compile; //================================ function compile($compileNode, transcludeFn, maxPriority) { if (!($compileNode instanceof jqLite)) { // jquery always rewraps, where as we need to preserve the original selector so that we can modify it. $compileNode = jqLite($compileNode); } // We can not compile top level text elements since text nodes can be merged and we will // not be able to attach scope data to them, so we will wrap them in <span> forEach($compileNode, function(node, index){ if (node.nodeType == 3 /* text node */) { $compileNode[index] = jqLite(node).wrap('<span></span>').parent()[0]; } }); var compositeLinkFn = compileNodes($compileNode, transcludeFn, $compileNode, maxPriority); return function(scope, cloneConnectFn){ assertArg(scope, 'scope'); // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart // and sometimes changes the structure of the DOM. var $linkNode = cloneConnectFn ? JQLitePrototype.clone.call($compileNode) // IMPORTANT!!! : $compileNode; $linkNode.data('$scope', scope); safeAddClass($linkNode, 'ng-scope'); if (cloneConnectFn) cloneConnectFn($linkNode, scope); if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode); return $linkNode; }; } function wrongMode(localName, mode) { throw Error("Unsupported '" + mode + "' for '" + localName + "'."); } function safeAddClass($element, className) { try { $element.addClass(className); } catch(e) { // ignore, since it means that we are trying to set class on // SVG element, where class name is read-only. } } /** * Compile function matches each node in nodeList against the directives. Once all directives * for a particular node are collected their compile functions are executed. The compile * functions return values - the linking functions - are combined into a composite linking * function, which is the a linking function for the node. * * @param {NodeList} nodeList an array of nodes to compile * @param {function(angular.Scope[, cloneAttachFn]} transcludeFn A linking function, where the * scope argument is auto-generated to the new child of the transcluded parent scope. * @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then the * rootElement must be set the jqLite collection of the compile root. This is * needed so that the jqLite collection items can be replaced with widgets. * @param {number=} max directive priority * @returns {?function} A composite linking function of all of the matched directives or null. */ function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority) { var linkFns = [], nodeLinkFn, childLinkFn, directives, attrs, linkFnFound; for(var i = 0; i < nodeList.length; i++) { attrs = new Attributes(); // we must always refer to nodeList[i] since the nodes can be replaced underneath us. directives = collectDirectives(nodeList[i], [], attrs, maxPriority); nodeLinkFn = (directives.length) ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement) : null; childLinkFn = (nodeLinkFn && nodeLinkFn.terminal) ? null : compileNodes(nodeList[i].childNodes, nodeLinkFn ? nodeLinkFn.transclude : transcludeFn); linkFns.push(nodeLinkFn); linkFns.push(childLinkFn); linkFnFound = (linkFnFound || nodeLinkFn || childLinkFn); } // return a linking function if we have found anything, null otherwise return linkFnFound ? compositeLinkFn : null; function compositeLinkFn(scope, nodeList, $rootElement, boundTranscludeFn) { var nodeLinkFn, childLinkFn, node, childScope, childTranscludeFn; for(var i = 0, n = 0, ii = linkFns.length; i < ii; n++) { node = nodeList[n]; nodeLinkFn = linkFns[i++]; childLinkFn = linkFns[i++]; if (nodeLinkFn) { if (nodeLinkFn.scope) { childScope = scope.$new(isObject(nodeLinkFn.scope)); jqLite(node).data('$scope', childScope); } else { childScope = scope; } childTranscludeFn = nodeLinkFn.transclude; if (childTranscludeFn || (!boundTranscludeFn && transcludeFn)) { nodeLinkFn(childLinkFn, childScope, node, $rootElement, (function(transcludeFn) { return function(cloneFn) { var transcludeScope = scope.$new(); return transcludeFn(transcludeScope, cloneFn). bind('$destroy', bind(transcludeScope, transcludeScope.$destroy)); }; })(childTranscludeFn || transcludeFn) ); } else { nodeLinkFn(childLinkFn, childScope, node, undefined, boundTranscludeFn); } } else if (childLinkFn) { childLinkFn(scope, node.childNodes, undefined, boundTranscludeFn); } } } } /** * Looks for directives on the given node ands them to the directive collection which is sorted. * * @param node node to search * @param directives an array to which the directives are added to. This array is sorted before * the function returns. * @param attrs the shared attrs object which is used to populate the normalized attributes. * @param {number=} max directive priority */ function collectDirectives(node, directives, attrs, maxPriority) { var nodeType = node.nodeType, attrsMap = attrs.$attr, match, className; switch(nodeType) { case 1: /* Element */ // use the node name: <directive> addDirective(directives, directiveNormalize(nodeName_(node).toLowerCase()), 'E', maxPriority); // iterate over the attributes for (var attr, name, nName, value, nAttrs = node.attributes, j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) { attr = nAttrs[j]; if (attr.specified) { name = attr.name; nName = directiveNormalize(name.toLowerCase()); attrsMap[nName] = name; attrs[nName] = value = trim((msie && name == 'href') ? decodeURIComponent(node.getAttribute(name, 2)) : attr.value); if (getBooleanAttrName(node, nName)) { attrs[nName] = true; // presence means true } addAttrInterpolateDirective(node, directives, value, nName); addDirective(directives, nName, 'A', maxPriority); } } // use class as directive className = node.className; if (isString(className)) { while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) { nName = directiveNormalize(match[2]); if (addDirective(directives, nName, 'C', maxPriority)) { attrs[nName] = trim(match[3]); } className = className.substr(match.index + match[0].length); } } break; case 3: /* Text Node */ addTextInterpolateDirective(directives, node.nodeValue); break; case 8: /* Comment */ try { match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue); if (match) { nName = directiveNormalize(match[1]); if (addDirective(directives, nName, 'M', maxPriority)) { attrs[nName] = trim(match[2]); } } } catch (e) { // turns out that under some circumstances IE9 throws errors when one attempts to read comment's node value. // Just ignore it and continue. (Can't seem to reproduce in test case.) } break; } directives.sort(byPriority); return directives; } /** * Once the directives have been collected their compile functions is executed. This method * is responsible for inlining directive templates as well as terminating the application * of the directives if the terminal directive has been reached.. * * @param {Array} directives Array of collected directives to execute their compile function. * this needs to be pre-sorted by priority order. * @param {Node} compileNode The raw DOM node to apply the compile functions to * @param {Object} templateAttrs The shared attribute function * @param {function(angular.Scope[, cloneAttachFn]} transcludeFn A linking function, where the * scope argument is auto-generated to the new child of the transcluded parent scope. * @param {DOMElement} $rootElement If we are working on the root of the compile tree then this * argument has the root jqLite array so that we can replace widgets on it. * @returns linkFn */ function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn, $rootElement) { var terminalPriority = -Number.MAX_VALUE, preLinkFns = [], postLinkFns = [], newScopeDirective = null, newIsolatedScopeDirective = null, templateDirective = null, $compileNode = templateAttrs.$$element = jqLite(compileNode), directive, directiveName, $template, transcludeDirective, childTranscludeFn = transcludeFn, controllerDirectives, linkFn, directiveValue; // executes all directives on the current element for(var i = 0, ii = directives.length; i < ii; i++) { directive = directives[i]; $template = undefined; if (terminalPriority > directive.priority) { break; // prevent further processing of directives } if (directiveValue = directive.scope) { assertNoDuplicate('isolated scope', newIsolatedScopeDirective, directive, $compileNode); if (isObject(directiveValue)) { safeAddClass($compileNode, 'ng-isolate-scope'); newIsolatedScopeDirective = directive; } safeAddClass($compileNode, 'ng-scope'); newScopeDirective = newScopeDirective || directive; } directiveName = directive.name; if (directiveValue = directive.controller) { controllerDirectives = controllerDirectives || {}; assertNoDuplicate("'" + directiveName + "' controller", controllerDirectives[directiveName], directive, $compileNode); controllerDirectives[directiveName] = directive; } if (directiveValue = directive.transclude) { assertNoDuplicate('transclusion', transcludeDirective, directive, $compileNode); transcludeDirective = directive; terminalPriority = directive.priority; if (directiveValue == 'element') { $template = jqLite(compileNode); $compileNode = templateAttrs.$$element = jqLite('<!-- ' + directiveName + ': ' + templateAttrs[directiveName] + ' -->'); compileNode = $compileNode[0]; replaceWith($rootElement, jqLite($template[0]), compileNode); childTranscludeFn = compile($template, transcludeFn, terminalPriority); } else { $template = jqLite(JQLiteClone(compileNode)).contents(); $compileNode.html(''); // clear contents childTranscludeFn = compile($template, transcludeFn); } } if ((directiveValue = directive.template)) { assertNoDuplicate('template', templateDirective, directive, $compileNode); templateDirective = directive; directiveValue = denormalizeTemplate(directiveValue); if (directive.replace) { $template = jqLite('<div>' + trim(directiveValue) + '</div>').contents(); compileNode = $template[0]; if ($template.length != 1 || compileNode.nodeType !== 1) { throw new Error(MULTI_ROOT_TEMPLATE_ERROR + directiveValue); } replaceWith($rootElement, $compileNode, compileNode); var newTemplateAttrs = {$attr: {}}; // combine directives from the original node and from the template: // - take the array of directives for this element // - split it into two parts, those that were already applied and those that weren't // - collect directives from the template, add them to the second group and sort them // - append the second group with new directives to the first group directives = directives.concat( collectDirectives( compileNode, directives.splice(i + 1, directives.length - (i + 1)), newTemplateAttrs ) ); mergeTemplateAttributes(templateAttrs, newTemplateAttrs); ii = directives.length; } else { $compileNode.html(directiveValue); } } if (directive.templateUrl) { assertNoDuplicate('template', templateDirective, directive, $compileNode); templateDirective = directive; nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), nodeLinkFn, $compileNode, templateAttrs, $rootElement, directive.replace, childTranscludeFn); ii = directives.length; } else if (directive.compile) { try { linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn); if (isFunction(linkFn)) { addLinkFns(null, linkFn); } else if (linkFn) { addLinkFns(linkFn.pre, linkFn.post); } } catch (e) { $exceptionHandler(e, startingTag($compileNode)); } } if (directive.terminal) { nodeLinkFn.terminal = true; terminalPriority = Math.max(terminalPriority, directive.priority); } } nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope; nodeLinkFn.transclude = transcludeDirective && childTranscludeFn; // might be normal or delayed nodeLinkFn depending on if templateUrl is present return nodeLinkFn; //////////////////// function addLinkFns(pre, post) { if (pre) { pre.require = directive.require; preLinkFns.push(pre); } if (post) { post.require = directive.require; postLinkFns.push(post); } } function getControllers(require, $element) { var value, retrievalMethod = 'data', optional = false; if (isString(require)) { while((value = require.charAt(0)) == '^' || value == '?') { require = require.substr(1); if (value == '^') { retrievalMethod = 'inheritedData'; } optional = optional || value == '?'; } value = $element[retrievalMethod]('$' + require + 'Controller'); if (!value && !optional) { throw Error("No controller: " + require); } return value; } else if (isArray(require)) { value = []; forEach(require, function(require) { value.push(getControllers(require, $element)); }); } return value; } function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) { var attrs, $element, i, ii, linkFn, controller; if (compileNode === linkNode) { attrs = templateAttrs; } else { attrs = shallowCopy(templateAttrs, new Attributes(jqLite(linkNode), templateAttrs.$attr)); } $element = attrs.$$element; if (newScopeDirective && isObject(newScopeDirective.scope)) { var LOCAL_REGEXP = /^\s*([@=&])\s*(\w*)\s*$/; var parentScope = scope.$parent || scope; forEach(newScopeDirective.scope, function(definiton, scopeName) { var match = definiton.match(LOCAL_REGEXP) || [], attrName = match[2]|| scopeName, mode = match[1], // @, =, or & lastValue, parentGet, parentSet; switch (mode) { case '@': { attrs.$observe(attrName, function(value) { scope[scopeName] = value; }); attrs.$$observers[attrName].$$scope = parentScope; break; } case '=': { parentGet = $parse(attrs[attrName]); parentSet = parentGet.assign || function() { // reset the change, or we will throw this exception on every $digest lastValue = scope[scopeName] = parentGet(parentScope); throw Error(NON_ASSIGNABLE_MODEL_EXPRESSION + attrs[attrName] + ' (directive: ' + newScopeDirective.name + ')'); }; lastValue = scope[scopeName] = parentGet(parentScope); scope.$watch(function() { var parentValue = parentGet(parentScope); if (parentValue !== scope[scopeName]) { // we are out of sync and need to copy if (parentValue !== lastValue) { // parent changed and it has precedence lastValue = scope[scopeName] = parentValue; } else { // if the parent can be assigned then do so parentSet(parentScope, lastValue = scope[scopeName]); } } return parentValue; }); break; } case '&': { parentGet = $parse(attrs[attrName]); scope[scopeName] = function(locals) { return parentGet(parentScope, locals); } break; } default: { throw Error('Invalid isolate scope definition for directive ' + newScopeDirective.name + ': ' + definiton); } } }); } if (controllerDirectives) { forEach(controllerDirectives, function(directive) { var locals = { $scope: scope, $element: $element, $attrs: attrs, $transclude: boundTranscludeFn }; controller = directive.controller; if (controller == '@') { controller = attrs[directive.name]; } $element.data( '$' + directive.name + 'Controller', $controller(controller, locals)); }); } // PRELINKING for(i = 0, ii = preLinkFns.length; i < ii; i++) { try { linkFn = preLinkFns[i]; linkFn(scope, $element, attrs, linkFn.require && getControllers(linkFn.require, $element)); } catch (e) { $exceptionHandler(e, startingTag($element)); } } // RECURSION childLinkFn && childLinkFn(scope, linkNode.childNodes, undefined, boundTranscludeFn); // POSTLINKING for(i = 0, ii = postLinkFns.length; i < ii; i++) { try { linkFn = postLinkFns[i]; linkFn(scope, $element, attrs, linkFn.require && getControllers(linkFn.require, $element)); } catch (e) { $exceptionHandler(e, startingTag($element)); } } } } /** * looks up the directive and decorates it with exception handling and proper parameters. We * call this the boundDirective. * * @param {string} name name of the directive to look up. * @param {string} location The directive must be found in specific format. * String containing any of theses characters: * * * `E`: element name * * `A': attribute * * `C`: class * * `M`: comment * @returns true if directive was added. */ function addDirective(tDirectives, name, location, maxPriority) { var match = false; if (hasDirectives.hasOwnProperty(name)) { for(var directive, directives = $injector.get(name + Suffix), i = 0, ii = directives.length; i<ii; i++) { try { directive = directives[i]; if ( (maxPriority === undefined || maxPriority > directive.priority) && directive.restrict.indexOf(location) != -1) { tDirectives.push(directive); match = true; } } catch(e) { $exceptionHandler(e); } } } return match; } /** * When the element is replaced with HTML template then the new attributes * on the template need to be merged with the existing attributes in the DOM. * The desired effect is to have both of the attributes present. * * @param {object} dst destination attributes (original DOM) * @param {object} src source attributes (from the directive template) */ function mergeTemplateAttributes(dst, src) { var srcAttr = src.$attr, dstAttr = dst.$attr, $element = dst.$$element; // reapply the old attributes to the new element forEach(dst, function(value, key) { if (key.charAt(0) != '$') { if (src[key]) { value += (key === 'style' ? ';' : ' ') + src[key]; } dst.$set(key, value, true, srcAttr[key]); } }); // copy the new attributes on the old attrs object forEach(src, function(value, key) { if (key == 'class') { safeAddClass($element, value); dst['class'] = (dst['class'] ? dst['class'] + ' ' : '') + value; } else if (key == 'style') { $element.attr('style', $element.attr('style') + ';' + value); } else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) { dst[key] = value; dstAttr[key] = srcAttr[key]; } }); } function compileTemplateUrl(directives, beforeTemplateNodeLinkFn, $compileNode, tAttrs, $rootElement, replace, childTranscludeFn) { var linkQueue = [], afterTemplateNodeLinkFn, afterTemplateChildLinkFn, beforeTemplateCompileNode = $compileNode[0], origAsyncDirective = directives.shift(), // The fact that we have to copy and patch the directive seems wrong! derivedSyncDirective = extend({}, origAsyncDirective, { controller: null, templateUrl: null, transclude: null }); $compileNode.html(''); $http.get(origAsyncDirective.templateUrl, {cache: $templateCache}). success(function(content) { var compileNode, tempTemplateAttrs, $template; content = denormalizeTemplate(content); if (replace) { $template = jqLite('<div>' + trim(content) + '</div>').contents(); compileNode = $template[0]; if ($template.length != 1 || compileNode.nodeType !== 1) { throw new Error(MULTI_ROOT_TEMPLATE_ERROR + content); } tempTemplateAttrs = {$attr: {}}; replaceWith($rootElement, $compileNode, compileNode); collectDirectives(compileNode, directives, tempTemplateAttrs); mergeTemplateAttributes(tAttrs, tempTemplateAttrs); } else { compileNode = beforeTemplateCompileNode; $compileNode.html(content); } directives.unshift(derivedSyncDirective); afterTemplateNodeLinkFn = applyDirectivesToNode(directives, $compileNode, tAttrs, childTranscludeFn); afterTemplateChildLinkFn = compileNodes($compileNode.contents(), childTranscludeFn); while(linkQueue.length) { var controller = linkQueue.pop(), linkRootElement = linkQueue.pop(), beforeTemplateLinkNode = linkQueue.pop(), scope = linkQueue.pop(), linkNode = compileNode; if (beforeTemplateLinkNode !== beforeTemplateCompileNode) { // it was cloned therefore we have to clone as well. linkNode = JQLiteClone(compileNode); replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode); } afterTemplateNodeLinkFn(function() { beforeTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement, controller); }, scope, linkNode, $rootElement, controller); } linkQueue = null; }). error(function(response, code, headers, config) { throw Error('Failed to load template: ' + config.url); }); return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, controller) { if (linkQueue) { linkQueue.push(scope); linkQueue.push(node); linkQueue.push(rootElement); linkQueue.push(controller); } else { afterTemplateNodeLinkFn(function() { beforeTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, controller); }, scope, node, rootElement, controller); } }; } /** * Sorting function for bound directives. */ function byPriority(a, b) { return b.priority - a.priority; } function assertNoDuplicate(what, previousDirective, directive, element) { if (previousDirective) { throw Error('Multiple directives [' + previousDirective.name + ', ' + directive.name + '] asking for ' + what + ' on: ' + startingTag(element)); } } function addTextInterpolateDirective(directives, text) { var interpolateFn = $interpolate(text, true); if (interpolateFn) { directives.push({ priority: 0, compile: valueFn(function(scope, node) { var parent = node.parent(), bindings = parent.data('$binding') || []; bindings.push(interpolateFn); safeAddClass(parent.data('$binding', bindings), 'ng-binding'); scope.$watch(interpolateFn, function(value) { node[0].nodeValue = value; }); }) }); } } function addAttrInterpolateDirective(node, directives, value, name) { var interpolateFn = $interpolate(value, true); // no interpolation found -> ignore if (!interpolateFn) return; directives.push({ priority: 100, compile: valueFn(function(scope, element, attr) { var $$observers = (attr.$$observers || (attr.$$observers = {})); if (name === 'class') { // we need to interpolate classes again, in the case the element was replaced // and therefore the two class attrs got merged - we want to interpolate the result interpolateFn = $interpolate(attr[name], true); } attr[name] = undefined; ($$observers[name] || ($$observers[name] = [])).$$inter = true; (attr.$$observers && attr.$$observers[name].$$scope || scope). $watch(interpolateFn, function(value) { attr.$set(name, value); }); }) }); } /** * This is a special jqLite.replaceWith, which can replace items which * have no parents, provided that the containing jqLite collection is provided. * * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes * in the root of the tree. * @param {JqLite} $element The jqLite element which we are going to replace. We keep the shell, * but replace its DOM node reference. * @param {Node} newNode The new DOM node. */ function replaceWith($rootElement, $element, newNode) { var oldNode = $element[0], parent = oldNode.parentNode, i, ii; if ($rootElement) { for(i = 0, ii = $rootElement.length; i < ii; i++) { if ($rootElement[i] == oldNode) { $rootElement[i] = newNode; break; } } } if (parent) { parent.replaceChild(newNode, oldNode); } newNode[jqLite.expando] = oldNode[jqLite.expando]; $element[0] = newNode; } }]; } var PREFIX_REGEXP = /^(x[\:\-_]|data[\:\-_])/i; /** * Converts all accepted directives format into proper directive name. * All of these will become 'myDirective': * my:DiRective * my-directive * x-my-directive * data-my:directive * * Also there is special case for Moz prefix starting with upper case letter. * @param name Name to normalize */ function directiveNormalize(name) { return camelCase(name.replace(PREFIX_REGEXP, '')); } /** * @ngdoc object * @name ng.$compile.directive.Attributes * @description * * A shared object between directive compile / linking functions which contains normalized DOM element * attributes. The the values reflect current binding state `{{ }}`. The normalization is needed * since all of these are treated as equivalent in Angular: * * <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a"> */ /** * @ngdoc property * @name ng.$compile.directive.Attributes#$attr * @propertyOf ng.$compile.directive.Attributes * @returns {object} A map of DOM element attribute names to the normalized name. This is * needed to do reverse lookup from normalized name back to actual name. */ /** * @ngdoc function * @name ng.$compile.directive.Attributes#$set * @methodOf ng.$compile.directive.Attributes * @function * * @description * Set DOM element attribute value. * * * @param {string} name Normalized element attribute name of the property to modify. The name is * revers translated using the {@link ng.$compile.directive.Attributes#$attr $attr} * property to the original name. * @param {string} value Value to set the attribute to. */ /** * Closure compiler type information */ function nodesetLinkingFn( /* angular.Scope */ scope, /* NodeList */ nodeList, /* Element */ rootElement, /* function(Function) */ boundTranscludeFn ){} function directiveLinkingFn( /* nodesetLinkingFn */ nodesetLinkingFn, /* angular.Scope */ scope, /* Node */ node, /* Element */ rootElement, /* function(Function) */ boundTranscludeFn ){} /** * @ngdoc object * @name ng.$controllerProvider * @description * The {@link ng.$controller $controller service} is used by Angular to create new * controllers. * * This provider allows controller registration via the * {@link ng.$controllerProvider#register register} method. */ function $ControllerProvider() { var controllers = {}; /** * @ngdoc function * @name ng.$controllerProvider#register * @methodOf ng.$controllerProvider * @param {string} name Controller name * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI * annotations in the array notation). */ this.register = function(name, constructor) { if (isObject(name)) { extend(controllers, name) } else { controllers[name] = constructor; } }; this.$get = ['$injector', '$window', function($injector, $window) { /** * @ngdoc function * @name ng.$controller * @requires $injector * * @param {Function|string} constructor If called with a function then it's considered to be the * controller constructor function. Otherwise it's considered to be a string which is used * to retrieve the controller constructor using the following steps: * * * check if a controller with given name is registered via `$controllerProvider` * * check if evaluating the string on the current scope returns a constructor * * check `window[constructor]` on the global `window` object * * @param {Object} locals Injection locals for Controller. * @return {Object} Instance of given controller. * * @description * `$controller` service is responsible for instantiating controllers. * * It's just simple call to {@link AUTO.$injector $injector}, but extracted into * a service, so that one can override this service with {@link https://gist.github.com/1649788 * BC version}. */ return function(constructor, locals) { if(isString(constructor)) { var name = constructor; constructor = controllers.hasOwnProperty(name) ? controllers[name] : getter(locals.$scope, name, true) || getter($window, name, true); assertArgFn(constructor, name, true); } return $injector.instantiate(constructor, locals); }; }]; } /** * @ngdoc object * @name ng.$document * @requires $window * * @description * A {@link angular.element jQuery (lite)}-wrapped reference to the browser's `window.document` * element. */ function $DocumentProvider(){ this.$get = ['$window', function(window){ return jqLite(window.document); }]; } /** * @ngdoc function * @name ng.$exceptionHandler * @requires $log * * @description * Any uncaught exception in angular expressions is delegated to this service. * The default implementation simply delegates to `$log.error` which logs it into * the browser console. * * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by * {@link ngMock.$exceptionHandler mock $exceptionHandler} * * @param {Error} exception Exception associated with the error. * @param {string=} cause optional information about the context in which * the error was thrown. */ function $ExceptionHandlerProvider() { this.$get = ['$log', function($log){ return function(exception, cause) { $log.error.apply($log, arguments); }; }]; } /** * @ngdoc object * @name ng.$interpolateProvider * @function * * @description * * Used for configuring the interpolation markup. Defaults to `{{` and `}}`. */ function $InterpolateProvider() { var startSymbol = '{{'; var endSymbol = '}}'; /** * @ngdoc method * @name ng.$interpolateProvider#startSymbol * @methodOf ng.$interpolateProvider * @description * Symbol to denote start of expression in the interpolated string. Defaults to `{{`. * * @param {string=} value new value to set the starting symbol to. * @returns {string|self} Returns the symbol when used as getter and self if used as setter. */ this.startSymbol = function(value){ if (value) { startSymbol = value; return this; } else { return startSymbol; } }; /** * @ngdoc method * @name ng.$interpolateProvider#endSymbol * @methodOf ng.$interpolateProvider * @description * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`. * * @param {string=} value new value to set the ending symbol to. * @returns {string|self} Returns the symbol when used as getter and self if used as setter. */ this.endSymbol = function(value){ if (value) { endSymbol = value; return this; } else { return endSymbol; } }; this.$get = ['$parse', function($parse) { var startSymbolLength = startSymbol.length, endSymbolLength = endSymbol.length; /** * @ngdoc function * @name ng.$interpolate * @function * * @requires $parse * * @description * * Compiles a string with markup into an interpolation function. This service is used by the * HTML {@link ng.$compile $compile} service for data binding. See * {@link ng.$interpolateProvider $interpolateProvider} for configuring the * interpolation markup. * * <pre> var $interpolate = ...; // injected var exp = $interpolate('Hello {{name}}!'); expect(exp({name:'Angular'}).toEqual('Hello Angular!'); </pre> * * * @param {string} text The text with markup to interpolate. * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have * embedded expression in order to return an interpolation function. Strings with no * embedded expression will return null for the interpolation function. * @returns {function(context)} an interpolation function which is used to compute the interpolated * string. The function has these parameters: * * * `context`: an object against which any expressions embedded in the strings are evaluated * against. * */ function $interpolate(text, mustHaveExpression) { var startIndex, endIndex, index = 0, parts = [], length = text.length, hasInterpolation = false, fn, exp, concat = []; while(index < length) { if ( ((startIndex = text.indexOf(startSymbol, index)) != -1) && ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1) ) { (index != startIndex) && parts.push(text.substring(index, startIndex)); parts.push(fn = $parse(exp = text.substring(startIndex + startSymbolLength, endIndex))); fn.exp = exp; index = endIndex + endSymbolLength; hasInterpolation = true; } else { // we did not find anything, so we have to add the remainder to the parts array (index != length) && parts.push(text.substring(index)); index = length; } } if (!(length = parts.length)) { // we added, nothing, must have been an empty string. parts.push(''); length = 1; } if (!mustHaveExpression || hasInterpolation) { concat.length = length; fn = function(context) { for(var i = 0, ii = length, part; i<ii; i++) { if (typeof (part = parts[i]) == 'function') { part = part(context); if (part == null || part == undefined) { part = ''; } else if (typeof part != 'string') { part = toJson(part); } } concat[i] = part; } return concat.join(''); }; fn.exp = text; fn.parts = parts; return fn; } } /** * @ngdoc method * @name ng.$interpolate#startSymbol * @methodOf ng.$interpolate * @description * Symbol to denote the start of expression in the interpolated string. Defaults to `{{`. * * Use {@link ng.$interpolateProvider#startSymbol $interpolateProvider#startSymbol} to change * the symbol. * * @returns {string} start symbol. */ $interpolate.startSymbol = function() { return startSymbol; } /** * @ngdoc method * @name ng.$interpolate#endSymbol * @methodOf ng.$interpolate * @description * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`. * * Use {@link ng.$interpolateProvider#endSymbol $interpolateProvider#endSymbol} to change * the symbol. * * @returns {string} start symbol. */ $interpolate.endSymbol = function() { return endSymbol; } return $interpolate; }]; } var URL_MATCH = /^([^:]+):\/\/(\w+:{0,1}\w*@)?([\w\.-]*)(:([0-9]+))?(\/[^\?#]*)?(\?([^#]*))?(#(.*))?$/, PATH_MATCH = /^([^\?#]*)?(\?([^#]*))?(#(.*))?$/, HASH_MATCH = PATH_MATCH, DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21}; /** * Encode path using encodeUriSegment, ignoring forward slashes * * @param {string} path Path to encode * @returns {string} */ function encodePath(path) { var segments = path.split('/'), i = segments.length; while (i--) { segments[i] = encodeUriSegment(segments[i]); } return segments.join('/'); } function stripHash(url) { return url.split('#')[0]; } function matchUrl(url, obj) { var match = URL_MATCH.exec(url); match = { protocol: match[1], host: match[3], port: int(match[5]) || DEFAULT_PORTS[match[1]] || null, path: match[6] || '/', search: match[8], hash: match[10] }; if (obj) { obj.$$protocol = match.protocol; obj.$$host = match.host; obj.$$port = match.port; } return match; } function composeProtocolHostPort(protocol, host, port) { return protocol + '://' + host + (port == DEFAULT_PORTS[protocol] ? '' : ':' + port); } function pathPrefixFromBase(basePath) { return basePath.substr(0, basePath.lastIndexOf('/')); } function convertToHtml5Url(url, basePath, hashPrefix) { var match = matchUrl(url); // already html5 url if (decodeURIComponent(match.path) != basePath || isUndefined(match.hash) || match.hash.indexOf(hashPrefix) !== 0) { return url; // convert hashbang url -> html5 url } else { return composeProtocolHostPort(match.protocol, match.host, match.port) + pathPrefixFromBase(basePath) + match.hash.substr(hashPrefix.length); } } function convertToHashbangUrl(url, basePath, hashPrefix) { var match = matchUrl(url); // already hashbang url if (decodeURIComponent(match.path) == basePath) { return url; // convert html5 url -> hashbang url } else { var search = match.search && '?' + match.search || '', hash = match.hash && '#' + match.hash || '', pathPrefix = pathPrefixFromBase(basePath), path = match.path.substr(pathPrefix.length); if (match.path.indexOf(pathPrefix) !== 0) { throw Error('Invalid url "' + url + '", missing path prefix "' + pathPrefix + '" !'); } return composeProtocolHostPort(match.protocol, match.host, match.port) + basePath + '#' + hashPrefix + path + search + hash; } } /** * LocationUrl represents an url * This object is exposed as $location service when HTML5 mode is enabled and supported * * @constructor * @param {string} url HTML5 url * @param {string} pathPrefix */ function LocationUrl(url, pathPrefix, appBaseUrl) { pathPrefix = pathPrefix || ''; /** * Parse given html5 (regular) url string into properties * @param {string} newAbsoluteUrl HTML5 url * @private */ this.$$parse = function(newAbsoluteUrl) { var match = matchUrl(newAbsoluteUrl, this); if (match.path.indexOf(pathPrefix) !== 0) { throw Error('Invalid url "' + newAbsoluteUrl + '", missing path prefix "' + pathPrefix + '" !'); } this.$$path = decodeURIComponent(match.path.substr(pathPrefix.length)); this.$$search = parseKeyValue(match.search); this.$$hash = match.hash && decodeURIComponent(match.hash) || ''; this.$$compose(); }; /** * Compose url and update `absUrl` property * @private */ this.$$compose = function() { var search = toKeyValue(this.$$search), hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : ''; this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash; this.$$absUrl = composeProtocolHostPort(this.$$protocol, this.$$host, this.$$port) + pathPrefix + this.$$url; }; this.$$rewriteAppUrl = function(absoluteLinkUrl) { if(absoluteLinkUrl.indexOf(appBaseUrl) == 0) { return absoluteLinkUrl; } } this.$$parse(url); } /** * LocationHashbangUrl represents url * This object is exposed as $location service when html5 history api is disabled or not supported * * @constructor * @param {string} url Legacy url * @param {string} hashPrefix Prefix for hash part (containing path and search) */ function LocationHashbangUrl(url, hashPrefix, appBaseUrl) { var basePath; /** * Parse given hashbang url into properties * @param {string} url Hashbang url * @private */ this.$$parse = function(url) { var match = matchUrl(url, this); if (match.hash && match.hash.indexOf(hashPrefix) !== 0) { throw Error('Invalid url "' + url + '", missing hash prefix "' + hashPrefix + '" !'); } basePath = match.path + (match.search ? '?' + match.search : ''); match = HASH_MATCH.exec((match.hash || '').substr(hashPrefix.length)); if (match[1]) { this.$$path = (match[1].charAt(0) == '/' ? '' : '/') + decodeURIComponent(match[1]); } else { this.$$path = ''; } this.$$search = parseKeyValue(match[3]); this.$$hash = match[5] && decodeURIComponent(match[5]) || ''; this.$$compose(); }; /** * Compose hashbang url and update `absUrl` property * @private */ this.$$compose = function() { var search = toKeyValue(this.$$search), hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : ''; this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash; this.$$absUrl = composeProtocolHostPort(this.$$protocol, this.$$host, this.$$port) + basePath + (this.$$url ? '#' + hashPrefix + this.$$url : ''); }; this.$$rewriteAppUrl = function(absoluteLinkUrl) { if(absoluteLinkUrl.indexOf(appBaseUrl) == 0) { return absoluteLinkUrl; } } this.$$parse(url); } LocationUrl.prototype = { /** * Has any change been replacing ? * @private */ $$replace: false, /** * @ngdoc method * @name ng.$location#absUrl * @methodOf ng.$location * * @description * This method is getter only. * * Return full url representation with all segments encoded according to rules specified in * {@link http://www.ietf.org/rfc/rfc3986.txt RFC 3986}. * * @return {string} full url */ absUrl: locationGetter('$$absUrl'), /** * @ngdoc method * @name ng.$location#url * @methodOf ng.$location * * @description * This method is getter / setter. * * Return url (e.g. `/path?a=b#hash`) when called without any parameter. * * Change path, search and hash, when called with parameter and return `$location`. * * @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`) * @return {string} url */ url: function(url, replace) { if (isUndefined(url)) return this.$$url; var match = PATH_MATCH.exec(url); if (match[1]) this.path(decodeURIComponent(match[1])); if (match[2] || match[1]) this.search(match[3] || ''); this.hash(match[5] || '', replace); return this; }, /** * @ngdoc method * @name ng.$location#protocol * @methodOf ng.$location * * @description * This method is getter only. * * Return protocol of current url. * * @return {string} protocol of current url */ protocol: locationGetter('$$protocol'), /** * @ngdoc method * @name ng.$location#host * @methodOf ng.$location * * @description * This method is getter only. * * Return host of current url. * * @return {string} host of current url. */ host: locationGetter('$$host'), /** * @ngdoc method * @name ng.$location#port * @methodOf ng.$location * * @description * This method is getter only. * * Return port of current url. * * @return {Number} port */ port: locationGetter('$$port'), /** * @ngdoc method * @name ng.$location#path * @methodOf ng.$location * * @description * This method is getter / setter. * * Return path of current url when called without any parameter. * * Change path when called with parameter and return `$location`. * * Note: Path should always begin with forward slash (/), this method will add the forward slash * if it is missing. * * @param {string=} path New path * @return {string} path */ path: locationGetterSetter('$$path', function(path) { return path.charAt(0) == '/' ? path : '/' + path; }), /** * @ngdoc method * @name ng.$location#search * @methodOf ng.$location * * @description * This method is getter / setter. * * Return search part (as object) of current url when called without any parameter. * * Change search part when called with parameter and return `$location`. * * @param {string|object<string,string>=} search New search params - string or hash object * @param {string=} paramValue If `search` is a string, then `paramValue` will override only a * single search parameter. If the value is `null`, the parameter will be deleted. * * @return {string} search */ search: function(search, paramValue) { if (isUndefined(search)) return this.$$search; if (isDefined(paramValue)) { if (paramValue === null) { delete this.$$search[search]; } else { this.$$search[search] = paramValue; } } else { this.$$search = isString(search) ? parseKeyValue(search) : search; } this.$$compose(); return this; }, /** * @ngdoc method * @name ng.$location#hash * @methodOf ng.$location * * @description * This method is getter / setter. * * Return hash fragment when called without any parameter. * * Change hash fragment when called with parameter and return `$location`. * * @param {string=} hash New hash fragment * @return {string} hash */ hash: locationGetterSetter('$$hash', identity), /** * @ngdoc method * @name ng.$location#replace * @methodOf ng.$location * * @description * If called, all changes to $location during current `$digest` will be replacing current history * record, instead of adding new one. */ replace: function() { this.$$replace = true; return this; } }; LocationHashbangUrl.prototype = inherit(LocationUrl.prototype); function LocationHashbangInHtml5Url(url, hashPrefix, appBaseUrl, baseExtra) { LocationHashbangUrl.apply(this, arguments); this.$$rewriteAppUrl = function(absoluteLinkUrl) { if (absoluteLinkUrl.indexOf(appBaseUrl) == 0) { return appBaseUrl + baseExtra + '#' + hashPrefix + absoluteLinkUrl.substr(appBaseUrl.length); } } } LocationHashbangInHtml5Url.prototype = inherit(LocationHashbangUrl.prototype); function locationGetter(property) { return function() { return this[property]; }; } function locationGetterSetter(property, preprocess) { return function(value) { if (isUndefined(value)) return this[property]; this[property] = preprocess(value); this.$$compose(); return this; }; } /** * @ngdoc object * @name ng.$location * * @requires $browser * @requires $sniffer * @requires $rootElement * * @description * The $location service parses the URL in the browser address bar (based on the * {@link https://developer.mozilla.org/en/window.location window.location}) and makes the URL * available to your application. Changes to the URL in the address bar are reflected into * $location service and changes to $location are reflected into the browser address bar. * * **The $location service:** * * - Exposes the current URL in the browser address bar, so you can * - Watch and observe the URL. * - Change the URL. * - Synchronizes the URL with the browser when the user * - Changes the address bar. * - Clicks the back or forward button (or clicks a History link). * - Clicks on a link. * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash). * * For more information see {@link guide/dev_guide.services.$location Developer Guide: Angular * Services: Using $location} */ /** * @ngdoc object * @name ng.$locationProvider * @description * Use the `$locationProvider` to configure how the application deep linking paths are stored. */ function $LocationProvider(){ var hashPrefix = '', html5Mode = false; /** * @ngdoc property * @name ng.$locationProvider#hashPrefix * @methodOf ng.$locationProvider * @description * @param {string=} prefix Prefix for hash part (containing path and search) * @returns {*} current value if used as getter or itself (chaining) if used as setter */ this.hashPrefix = function(prefix) { if (isDefined(prefix)) { hashPrefix = prefix; return this; } else { return hashPrefix; } }; /** * @ngdoc property * @name ng.$locationProvider#html5Mode * @methodOf ng.$locationProvider * @description * @param {string=} mode Use HTML5 strategy if available. * @returns {*} current value if used as getter or itself (chaining) if used as setter */ this.html5Mode = function(mode) { if (isDefined(mode)) { html5Mode = mode; return this; } else { return html5Mode; } }; this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement', function( $rootScope, $browser, $sniffer, $rootElement) { var $location, basePath, pathPrefix, initUrl = $browser.url(), initUrlParts = matchUrl(initUrl), appBaseUrl; if (html5Mode) { basePath = $browser.baseHref() || '/'; pathPrefix = pathPrefixFromBase(basePath); appBaseUrl = composeProtocolHostPort(initUrlParts.protocol, initUrlParts.host, initUrlParts.port) + pathPrefix + '/'; if ($sniffer.history) { $location = new LocationUrl( convertToHtml5Url(initUrl, basePath, hashPrefix), pathPrefix, appBaseUrl); } else { $location = new LocationHashbangInHtml5Url( convertToHashbangUrl(initUrl, basePath, hashPrefix), hashPrefix, appBaseUrl, basePath.substr(pathPrefix.length + 1)); } } else { appBaseUrl = composeProtocolHostPort(initUrlParts.protocol, initUrlParts.host, initUrlParts.port) + (initUrlParts.path || '') + (initUrlParts.search ? ('?' + initUrlParts.search) : '') + '#' + hashPrefix + '/'; $location = new LocationHashbangUrl(initUrl, hashPrefix, appBaseUrl); } $rootElement.bind('click', function(event) { // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser) // currently we open nice url link and redirect then if (event.ctrlKey || event.metaKey || event.which == 2) return; var elm = jqLite(event.target); // traverse the DOM up to find first A tag while (lowercase(elm[0].nodeName) !== 'a') { // ignore rewriting if no A tag (reached root element, or no parent - removed from document) if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return; } var absHref = elm.prop('href'), rewrittenUrl = $location.$$rewriteAppUrl(absHref); if (absHref && !elm.attr('target') && rewrittenUrl) { // update location manually $location.$$parse(rewrittenUrl); $rootScope.$apply(); event.preventDefault(); // hack to work around FF6 bug 684208 when scenario runner clicks on links window.angular['ff-684208-preventDefault'] = true; } }); // rewrite hashbang url <> html5 url if ($location.absUrl() != initUrl) { $browser.url($location.absUrl(), true); } // update $location when $browser url changes $browser.onUrlChange(function(newUrl) { if ($location.absUrl() != newUrl) { $rootScope.$evalAsync(function() { var oldUrl = $location.absUrl(); $location.$$parse(newUrl); afterLocationChange(oldUrl); }); if (!$rootScope.$$phase) $rootScope.$digest(); } }); // update browser var changeCounter = 0; $rootScope.$watch(function $locationWatch() { var oldUrl = $browser.url(); if (!changeCounter || oldUrl != $location.absUrl()) { changeCounter++; $rootScope.$evalAsync(function() { if ($rootScope.$broadcast('$locationChangeStart', $location.absUrl(), oldUrl). defaultPrevented) { $location.$$parse(oldUrl); } else { $browser.url($location.absUrl(), $location.$$replace); $location.$$replace = false; afterLocationChange(oldUrl); } }); } return changeCounter; }); return $location; function afterLocationChange(oldUrl) { $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl); } }]; } /** * @ngdoc object * @name ng.$log * @requires $window * * @description * Simple service for logging. Default implementation writes the message * into the browser's console (if present). * * The main purpose of this service is to simplify debugging and troubleshooting. * * @example <example> <file name="script.js"> function LogCtrl($scope, $log) { $scope.$log = $log; $scope.message = 'Hello World!'; } </file> <file name="index.html"> <div ng-controller="LogCtrl"> <p>Reload this page with open console, enter text and hit the log button...</p> Message: <input type="text" ng-model="message"/> <button ng-click="$log.log(message)">log</button> <button ng-click="$log.warn(message)">warn</button> <button ng-click="$log.info(message)">info</button> <button ng-click="$log.error(message)">error</button> </div> </file> </example> */ function $LogProvider(){ this.$get = ['$window', function($window){ return { /** * @ngdoc method * @name ng.$log#log * @methodOf ng.$log * * @description * Write a log message */ log: consoleLog('log'), /** * @ngdoc method * @name ng.$log#warn * @methodOf ng.$log * * @description * Write a warning message */ warn: consoleLog('warn'), /** * @ngdoc method * @name ng.$log#info * @methodOf ng.$log * * @description * Write an information message */ info: consoleLog('info'), /** * @ngdoc method * @name ng.$log#error * @methodOf ng.$log * * @description * Write an error message */ error: consoleLog('error') }; function formatError(arg) { if (arg instanceof Error) { if (arg.stack) { arg = (arg.message && arg.stack.indexOf(arg.message) === -1) ? 'Error: ' + arg.message + '\n' + arg.stack : arg.stack; } else if (arg.sourceURL) { arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line; } } return arg; } function consoleLog(type) { var console = $window.console || {}, logFn = console[type] || console.log || noop; if (logFn.apply) { return function() { var args = []; forEach(arguments, function(arg) { args.push(formatError(arg)); }); return logFn.apply(console, args); }; } // we are IE which either doesn't have window.console => this is noop and we do nothing, // or we are IE where console.log doesn't have apply so we log at least first 2 args return function(arg1, arg2) { logFn(arg1, arg2); } } }]; } var OPERATORS = { 'null':function(){return null;}, 'true':function(){return true;}, 'false':function(){return false;}, undefined:noop, '+':function(self, locals, a,b){a=a(self, locals); b=b(self, locals); return (isDefined(a)?a:0)+(isDefined(b)?b:0);}, '-':function(self, locals, a,b){a=a(self, locals); b=b(self, locals); return (isDefined(a)?a:0)-(isDefined(b)?b:0);}, '*':function(self, locals, a,b){return a(self, locals)*b(self, locals);}, '/':function(self, locals, a,b){return a(self, locals)/b(self, locals);}, '%':function(self, locals, a,b){return a(self, locals)%b(self, locals);}, '^':function(self, locals, a,b){return a(self, locals)^b(self, locals);}, '=':noop, '==':function(self, locals, a,b){return a(self, locals)==b(self, locals);}, '!=':function(self, locals, a,b){return a(self, locals)!=b(self, locals);}, '<':function(self, locals, a,b){return a(self, locals)<b(self, locals);}, '>':function(self, locals, a,b){return a(self, locals)>b(self, locals);}, '<=':function(self, locals, a,b){return a(self, locals)<=b(self, locals);}, '>=':function(self, locals, a,b){return a(self, locals)>=b(self, locals);}, '&&':function(self, locals, a,b){return a(self, locals)&&b(self, locals);}, '||':function(self, locals, a,b){return a(self, locals)||b(self, locals);}, '&':function(self, locals, a,b){return a(self, locals)&b(self, locals);}, // '|':function(self, locals, a,b){return a|b;}, '|':function(self, locals, a,b){return b(self, locals)(self, locals, a(self, locals));}, '!':function(self, locals, a){return !a(self, locals);} }; var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'}; function lex(text, csp){ var tokens = [], token, index = 0, json = [], ch, lastCh = ':'; // can start regexp while (index < text.length) { ch = text.charAt(index); if (is('"\'')) { readString(ch); } else if (isNumber(ch) || is('.') && isNumber(peek())) { readNumber(); } else if (isIdent(ch)) { readIdent(); // identifiers can only be if the preceding char was a { or , if (was('{,') && json[0]=='{' && (token=tokens[tokens.length-1])) { token.json = token.text.indexOf('.') == -1; } } else if (is('(){}[].,;:')) { tokens.push({ index:index, text:ch, json:(was(':[,') && is('{[')) || is('}]:,') }); if (is('{[')) json.unshift(ch); if (is('}]')) json.shift(); index++; } else if (isWhitespace(ch)) { index++; continue; } else { var ch2 = ch + peek(), fn = OPERATORS[ch], fn2 = OPERATORS[ch2]; if (fn2) { tokens.push({index:index, text:ch2, fn:fn2}); index += 2; } else if (fn) { tokens.push({index:index, text:ch, fn:fn, json: was('[,:') && is('+-')}); index += 1; } else { throwError("Unexpected next character ", index, index+1); } } lastCh = ch; } return tokens; function is(chars) { return chars.indexOf(ch) != -1; } function was(chars) { return chars.indexOf(lastCh) != -1; } function peek() { return index + 1 < text.length ? text.charAt(index + 1) : false; } function isNumber(ch) { return '0' <= ch && ch <= '9'; } function isWhitespace(ch) { return ch == ' ' || ch == '\r' || ch == '\t' || ch == '\n' || ch == '\v' || ch == '\u00A0'; // IE treats non-breaking space as \u00A0 } function isIdent(ch) { return 'a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || '_' == ch || ch == '$'; } function isExpOperator(ch) { return ch == '-' || ch == '+' || isNumber(ch); } function throwError(error, start, end) { end = end || index; throw Error("Lexer Error: " + error + " at column" + (isDefined(start) ? "s " + start + "-" + index + " [" + text.substring(start, end) + "]" : " " + end) + " in expression [" + text + "]."); } function readNumber() { var number = ""; var start = index; while (index < text.length) { var ch = lowercase(text.charAt(index)); if (ch == '.' || isNumber(ch)) { number += ch; } else { var peekCh = peek(); if (ch == 'e' && isExpOperator(peekCh)) { number += ch; } else if (isExpOperator(ch) && peekCh && isNumber(peekCh) && number.charAt(number.length - 1) == 'e') { number += ch; } else if (isExpOperator(ch) && (!peekCh || !isNumber(peekCh)) && number.charAt(number.length - 1) == 'e') { throwError('Invalid exponent'); } else { break; } } index++; } number = 1 * number; tokens.push({index:start, text:number, json:true, fn:function() {return number;}}); } function readIdent() { var ident = "", start = index, lastDot, peekIndex, methodName; while (index < text.length) { var ch = text.charAt(index); if (ch == '.' || isIdent(ch) || isNumber(ch)) { if (ch == '.') lastDot = index; ident += ch; } else { break; } index++; } //check if this is not a method invocation and if it is back out to last dot if (lastDot) { peekIndex = index; while(peekIndex < text.length) { var ch = text.charAt(peekIndex); if (ch == '(') { methodName = ident.substr(lastDot - start + 1); ident = ident.substr(0, lastDot - start); index = peekIndex; break; } if(isWhitespace(ch)) { peekIndex++; } else { break; } } } var token = { index:start, text:ident }; if (OPERATORS.hasOwnProperty(ident)) { token.fn = token.json = OPERATORS[ident]; } else { var getter = getterFn(ident, csp); token.fn = extend(function(self, locals) { return (getter(self, locals)); }, { assign: function(self, value) { return setter(self, ident, value); } }); } tokens.push(token); if (methodName) { tokens.push({ index:lastDot, text: '.', json: false }); tokens.push({ index: lastDot + 1, text: methodName, json: false }); } } function readString(quote) { var start = index; index++; var string = ""; var rawString = quote; var escape = false; while (index < text.length) { var ch = text.charAt(index); rawString += ch; if (escape) { if (ch == 'u') { var hex = text.substring(index + 1, index + 5); if (!hex.match(/[\da-f]{4}/i)) throwError( "Invalid unicode escape [\\u" + hex + "]"); index += 4; string += String.fromCharCode(parseInt(hex, 16)); } else { var rep = ESCAPE[ch]; if (rep) { string += rep; } else { string += ch; } } escape = false; } else if (ch == '\\') { escape = true; } else if (ch == quote) { index++; tokens.push({ index:start, text:rawString, string:string, json:true, fn:function() { return string; } }); return; } else { string += ch; } index++; } throwError("Unterminated quote", start); } } ///////////////////////////////////////// function parser(text, json, $filter, csp){ var ZERO = valueFn(0), value, tokens = lex(text, csp), assignment = _assignment, functionCall = _functionCall, fieldAccess = _fieldAccess, objectIndex = _objectIndex, filterChain = _filterChain; if(json){ // The extra level of aliasing is here, just in case the lexer misses something, so that // we prevent any accidental execution in JSON. assignment = logicalOR; functionCall = fieldAccess = objectIndex = filterChain = function() { throwError("is not valid json", {text:text, index:0}); }; value = primary(); } else { value = statements(); } if (tokens.length !== 0) { throwError("is an unexpected token", tokens[0]); } return value; /////////////////////////////////// function throwError(msg, token) { throw Error("Syntax Error: Token '" + token.text + "' " + msg + " at column " + (token.index + 1) + " of the expression [" + text + "] starting at [" + text.substring(token.index) + "]."); } function peekToken() { if (tokens.length === 0) throw Error("Unexpected end of expression: " + text); return tokens[0]; } function peek(e1, e2, e3, e4) { if (tokens.length > 0) { var token = tokens[0]; var t = token.text; if (t==e1 || t==e2 || t==e3 || t==e4 || (!e1 && !e2 && !e3 && !e4)) { return token; } } return false; } function expect(e1, e2, e3, e4){ var token = peek(e1, e2, e3, e4); if (token) { if (json && !token.json) { throwError("is not valid json", token); } tokens.shift(); return token; } return false; } function consume(e1){ if (!expect(e1)) { throwError("is unexpected, expecting [" + e1 + "]", peek()); } } function unaryFn(fn, right) { return function(self, locals) { return fn(self, locals, right); }; } function binaryFn(left, fn, right) { return function(self, locals) { return fn(self, locals, left, right); }; } function statements() { var statements = []; while(true) { if (tokens.length > 0 && !peek('}', ')', ';', ']')) statements.push(filterChain()); if (!expect(';')) { // optimize for the common case where there is only one statement. // TODO(size): maybe we should not support multiple statements? return statements.length == 1 ? statements[0] : function(self, locals){ var value; for ( var i = 0; i < statements.length; i++) { var statement = statements[i]; if (statement) value = statement(self, locals); } return value; }; } } } function _filterChain() { var left = expression(); var token; while(true) { if ((token = expect('|'))) { left = binaryFn(left, token.fn, filter()); } else { return left; } } } function filter() { var token = expect(); var fn = $filter(token.text); var argsFn = []; while(true) { if ((token = expect(':'))) { argsFn.push(expression()); } else { var fnInvoke = function(self, locals, input){ var args = [input]; for ( var i = 0; i < argsFn.length; i++) { args.push(argsFn[i](self, locals)); } return fn.apply(self, args); }; return function() { return fnInvoke; }; } } } function expression() { return assignment(); } function _assignment() { var left = logicalOR(); var right; var token; if ((token = expect('='))) { if (!left.assign) { throwError("implies assignment but [" + text.substring(0, token.index) + "] can not be assigned to", token); } right = logicalOR(); return function(self, locals){ return left.assign(self, right(self, locals), locals); }; } else { return left; } } function logicalOR() { var left = logicalAND(); var token; while(true) { if ((token = expect('||'))) { left = binaryFn(left, token.fn, logicalAND()); } else { return left; } } } function logicalAND() { var left = equality(); var token; if ((token = expect('&&'))) { left = binaryFn(left, token.fn, logicalAND()); } return left; } function equality() { var left = relational(); var token; if ((token = expect('==','!='))) { left = binaryFn(left, token.fn, equality()); } return left; } function relational() { var left = additive(); var token; if ((token = expect('<', '>', '<=', '>='))) { left = binaryFn(left, token.fn, relational()); } return left; } function additive() { var left = multiplicative(); var token; while ((token = expect('+','-'))) { left = binaryFn(left, token.fn, multiplicative()); } return left; } function multiplicative() { var left = unary(); var token; while ((token = expect('*','/','%'))) { left = binaryFn(left, token.fn, unary()); } return left; } function unary() { var token; if (expect('+')) { return primary(); } else if ((token = expect('-'))) { return binaryFn(ZERO, token.fn, unary()); } else if ((token = expect('!'))) { return unaryFn(token.fn, unary()); } else { return primary(); } } function primary() { var primary; if (expect('(')) { primary = filterChain(); consume(')'); } else if (expect('[')) { primary = arrayDeclaration(); } else if (expect('{')) { primary = object(); } else { var token = expect(); primary = token.fn; if (!primary) { throwError("not a primary expression", token); } } var next, context; while ((next = expect('(', '[', '.'))) { if (next.text === '(') { primary = functionCall(primary, context); context = null; } else if (next.text === '[') { context = primary; primary = objectIndex(primary); } else if (next.text === '.') { context = primary; primary = fieldAccess(primary); } else { throwError("IMPOSSIBLE"); } } return primary; } function _fieldAccess(object) { var field = expect().text; var getter = getterFn(field, csp); return extend( function(self, locals) { return getter(object(self, locals), locals); }, { assign:function(self, value, locals) { return setter(object(self, locals), field, value); } } ); } function _objectIndex(obj) { var indexFn = expression(); consume(']'); return extend( function(self, locals){ var o = obj(self, locals), i = indexFn(self, locals), v, p; if (!o) return undefined; v = o[i]; if (v && v.then) { p = v; if (!('$$v' in v)) { p.$$v = undefined; p.then(function(val) { p.$$v = val; }); } v = v.$$v; } return v; }, { assign:function(self, value, locals){ return obj(self, locals)[indexFn(self, locals)] = value; } }); } function _functionCall(fn, contextGetter) { var argsFn = []; if (peekToken().text != ')') { do { argsFn.push(expression()); } while (expect(',')); } consume(')'); return function(self, locals){ var args = [], context = contextGetter ? contextGetter(self, locals) : self; for ( var i = 0; i < argsFn.length; i++) { args.push(argsFn[i](self, locals)); } var fnPtr = fn(self, locals) || noop; // IE stupidity! return fnPtr.apply ? fnPtr.apply(context, args) : fnPtr(args[0], args[1], args[2], args[3], args[4]); }; } // This is used with json array declaration function arrayDeclaration () { var elementFns = []; if (peekToken().text != ']') { do { elementFns.push(expression()); } while (expect(',')); } consume(']'); return function(self, locals){ var array = []; for ( var i = 0; i < elementFns.length; i++) { array.push(elementFns[i](self, locals)); } return array; }; } function object () { var keyValues = []; if (peekToken().text != '}') { do { var token = expect(), key = token.string || token.text; consume(":"); var value = expression(); keyValues.push({key:key, value:value}); } while (expect(',')); } consume('}'); return function(self, locals){ var object = {}; for ( var i = 0; i < keyValues.length; i++) { var keyValue = keyValues[i]; var value = keyValue.value(self, locals); object[keyValue.key] = value; } return object; }; } } ////////////////////////////////////////////////// // Parser helper functions ////////////////////////////////////////////////// function setter(obj, path, setValue) { var element = path.split('.'); for (var i = 0; element.length > 1; i++) { var key = element.shift(); var propertyObj = obj[key]; if (!propertyObj) { propertyObj = {}; obj[key] = propertyObj; } obj = propertyObj; } obj[element.shift()] = setValue; return setValue; } /** * Return the value accesible from the object by path. Any undefined traversals are ignored * @param {Object} obj starting object * @param {string} path path to traverse * @param {boolean=true} bindFnToScope * @returns value as accesbile by path */ //TODO(misko): this function needs to be removed function getter(obj, path, bindFnToScope) { if (!path) return obj; var keys = path.split('.'); var key; var lastInstance = obj; var len = keys.length; for (var i = 0; i < len; i++) { key = keys[i]; if (obj) { obj = (lastInstance = obj)[key]; } } if (!bindFnToScope && isFunction(obj)) { return bind(lastInstance, obj); } return obj; } var getterFnCache = {}; /** * Implementation of the "Black Hole" variant from: * - http://jsperf.com/angularjs-parse-getter/4 * - http://jsperf.com/path-evaluation-simplified/7 */ function cspSafeGetterFn(key0, key1, key2, key3, key4) { return function(scope, locals) { var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope, promise; if (pathVal === null || pathVal === undefined) return pathVal; pathVal = pathVal[key0]; if (pathVal && pathVal.then) { if (!("$$v" in pathVal)) { promise = pathVal; promise.$$v = undefined; promise.then(function(val) { promise.$$v = val; }); } pathVal = pathVal.$$v; } if (!key1 || pathVal === null || pathVal === undefined) return pathVal; pathVal = pathVal[key1]; if (pathVal && pathVal.then) { if (!("$$v" in pathVal)) { promise = pathVal; promise.$$v = undefined; promise.then(function(val) { promise.$$v = val; }); } pathVal = pathVal.$$v; } if (!key2 || pathVal === null || pathVal === undefined) return pathVal; pathVal = pathVal[key2]; if (pathVal && pathVal.then) { if (!("$$v" in pathVal)) { promise = pathVal; promise.$$v = undefined; promise.then(function(val) { promise.$$v = val; }); } pathVal = pathVal.$$v; } if (!key3 || pathVal === null || pathVal === undefined) return pathVal; pathVal = pathVal[key3]; if (pathVal && pathVal.then) { if (!("$$v" in pathVal)) { promise = pathVal; promise.$$v = undefined; promise.then(function(val) { promise.$$v = val; }); } pathVal = pathVal.$$v; } if (!key4 || pathVal === null || pathVal === undefined) return pathVal; pathVal = pathVal[key4]; if (pathVal && pathVal.then) { if (!("$$v" in pathVal)) { promise = pathVal; promise.$$v = undefined; promise.then(function(val) { promise.$$v = val; }); } pathVal = pathVal.$$v; } return pathVal; }; }; function getterFn(path, csp) { if (getterFnCache.hasOwnProperty(path)) { return getterFnCache[path]; } var pathKeys = path.split('.'), pathKeysLength = pathKeys.length, fn; if (csp) { fn = (pathKeysLength < 6) ? cspSafeGetterFn(pathKeys[0], pathKeys[1], pathKeys[2], pathKeys[3], pathKeys[4]) : function(scope, locals) { var i = 0, val do { val = cspSafeGetterFn( pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++] )(scope, locals); locals = undefined; // clear after first iteration scope = val; } while (i < pathKeysLength); return val; } } else { var code = 'var l, fn, p;\n'; forEach(pathKeys, function(key, index) { code += 'if(s === null || s === undefined) return s;\n' + 'l=s;\n' + 's='+ (index // we simply dereference 's' on any .dot notation ? 's' // but if we are first then we check locals first, and if so read it first : '((k&&k.hasOwnProperty("' + key + '"))?k:s)') + '["' + key + '"]' + ';\n' + 'if (s && s.then) {\n' + ' if (!("$$v" in s)) {\n' + ' p=s;\n' + ' p.$$v = undefined;\n' + ' p.then(function(v) {p.$$v=v;});\n' + '}\n' + ' s=s.$$v\n' + '}\n'; }); code += 'return s;'; fn = Function('s', 'k', code); // s=scope, k=locals fn.toString = function() { return code; }; } return getterFnCache[path] = fn; } /////////////////////////////////// /** * @ngdoc function * @name ng.$parse * @function * * @description * * Converts Angular {@link guide/expression expression} into a function. * * <pre> * var getter = $parse('user.name'); * var setter = getter.assign; * var context = {user:{name:'angular'}}; * var locals = {user:{name:'local'}}; * * expect(getter(context)).toEqual('angular'); * setter(context, 'newValue'); * expect(context.user.name).toEqual('newValue'); * expect(getter(context, locals)).toEqual('local'); * </pre> * * * @param {string} expression String expression to compile. * @returns {function(context, locals)} a function which represents the compiled expression: * * * `context`: an object against which any expressions embedded in the strings are evaluated * against (Topically a scope object). * * `locals`: local variables context object, useful for overriding values in `context`. * * The return function also has an `assign` property, if the expression is assignable, which * allows one to set values to expressions. * */ function $ParseProvider() { var cache = {}; this.$get = ['$filter', '$sniffer', function($filter, $sniffer) { return function(exp) { switch(typeof exp) { case 'string': return cache.hasOwnProperty(exp) ? cache[exp] : cache[exp] = parser(exp, false, $filter, $sniffer.csp); case 'function': return exp; default: return noop; } }; }]; } /** * @ngdoc service * @name ng.$q * @requires $rootScope * * @description * A promise/deferred implementation inspired by [Kris Kowal's Q](https://github.com/kriskowal/q). * * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an * interface for interacting with an object that represents the result of an action that is * performed asynchronously, and may or may not be finished at any given point in time. * * From the perspective of dealing with error handling, deferred and promise apis are to * asynchronous programing what `try`, `catch` and `throw` keywords are to synchronous programing. * * <pre> * // for the purpose of this example let's assume that variables `$q` and `scope` are * // available in the current lexical scope (they could have been injected or passed in). * * function asyncGreet(name) { * var deferred = $q.defer(); * * setTimeout(function() { * // since this fn executes async in a future turn of the event loop, we need to wrap * // our code into an $apply call so that the model changes are properly observed. * scope.$apply(function() { * if (okToGreet(name)) { * deferred.resolve('Hello, ' + name + '!'); * } else { * deferred.reject('Greeting ' + name + ' is not allowed.'); * } * }); * }, 1000); * * return deferred.promise; * } * * var promise = asyncGreet('Robin Hood'); * promise.then(function(greeting) { * alert('Success: ' + greeting); * }, function(reason) { * alert('Failed: ' + reason); * ); * </pre> * * At first it might not be obvious why this extra complexity is worth the trouble. The payoff * comes in the way of * [guarantees that promise and deferred apis make](https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md). * * Additionally the promise api allows for composition that is very hard to do with the * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach. * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the * section on serial or parallel joining of promises. * * * # The Deferred API * * A new instance of deferred is constructed by calling `$q.defer()`. * * The purpose of the deferred object is to expose the associated Promise instance as well as apis * that can be used for signaling the successful or unsuccessful completion of the task. * * **Methods** * * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection * constructed via `$q.reject`, the promise will be rejected instead. * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to * resolving it with a rejection constructed via `$q.reject`. * * **Properties** * * - promise – `{Promise}` – promise object associated with this deferred. * * * # The Promise API * * A new promise instance is created when a deferred instance is created and can be retrieved by * calling `deferred.promise`. * * The purpose of the promise object is to allow for interested parties to get access to the result * of the deferred task when it completes. * * **Methods** * * - `then(successCallback, errorCallback)` – regardless of when the promise was or will be resolved * or rejected calls one of the success or error callbacks asynchronously as soon as the result * is available. The callbacks are called with a single argument the result or rejection reason. * * This method *returns a new promise* which is resolved or rejected via the return value of the * `successCallback` or `errorCallback`. * * * # Chaining promises * * Because calling `then` api of a promise returns a new derived promise, it is easily possible * to create a chain of promises: * * <pre> * promiseB = promiseA.then(function(result) { * return result + 1; * }); * * // promiseB will be resolved immediately after promiseA is resolved and it's value will be * // the result of promiseA incremented by 1 * </pre> * * It is possible to create chains of any length and since a promise can be resolved with another * promise (which will defer its resolution further), it is possible to pause/defer resolution of * the promises at any point in the chain. This makes it possible to implement powerful apis like * $http's response interceptors. * * * # Differences between Kris Kowal's Q and $q * * There are three main differences: * * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation * mechanism in angular, which means faster propagation of resolution or rejection into your * models and avoiding unnecessary browser repaints, which would result in flickering UI. * - $q promises are recognized by the templating engine in angular, which means that in templates * you can treat promises attached to a scope as if they were the resulting values. * - Q has many more features that $q, but that comes at a cost of bytes. $q is tiny, but contains * all the important functionality needed for common async tasks. */ function $QProvider() { this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) { return qFactory(function(callback) { $rootScope.$evalAsync(callback); }, $exceptionHandler); }]; } /** * Constructs a promise manager. * * @param {function(function)} nextTick Function for executing functions in the next turn. * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for * debugging purposes. * @returns {object} Promise manager. */ function qFactory(nextTick, exceptionHandler) { /** * @ngdoc * @name ng.$q#defer * @methodOf ng.$q * @description * Creates a `Deferred` object which represents a task which will finish in the future. * * @returns {Deferred} Returns a new instance of deferred. */ var defer = function() { var pending = [], value, deferred; deferred = { resolve: function(val) { if (pending) { var callbacks = pending; pending = undefined; value = ref(val); if (callbacks.length) { nextTick(function() { var callback; for (var i = 0, ii = callbacks.length; i < ii; i++) { callback = callbacks[i]; value.then(callback[0], callback[1]); } }); } } }, reject: function(reason) { deferred.resolve(reject(reason)); }, promise: { then: function(callback, errback) { var result = defer(); var wrappedCallback = function(value) { try { result.resolve((callback || defaultCallback)(value)); } catch(e) { exceptionHandler(e); result.reject(e); } }; var wrappedErrback = function(reason) { try { result.resolve((errback || defaultErrback)(reason)); } catch(e) { exceptionHandler(e); result.reject(e); } }; if (pending) { pending.push([wrappedCallback, wrappedErrback]); } else { value.then(wrappedCallback, wrappedErrback); } return result.promise; } } }; return deferred; }; var ref = function(value) { if (value && value.then) return value; return { then: function(callback) { var result = defer(); nextTick(function() { result.resolve(callback(value)); }); return result.promise; } }; }; /** * @ngdoc * @name ng.$q#reject * @methodOf ng.$q * @description * Creates a promise that is resolved as rejected with the specified `reason`. This api should be * used to forward rejection in a chain of promises. If you are dealing with the last promise in * a promise chain, you don't need to worry about it. * * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via * a promise error callback and you want to forward the error to the promise derived from the * current promise, you have to "rethrow" the error by returning a rejection constructed via * `reject`. * * <pre> * promiseB = promiseA.then(function(result) { * // success: do something and resolve promiseB * // with the old or a new result * return result; * }, function(reason) { * // error: handle the error if possible and * // resolve promiseB with newPromiseOrValue, * // otherwise forward the rejection to promiseB * if (canHandle(reason)) { * // handle the error and recover * return newPromiseOrValue; * } * return $q.reject(reason); * }); * </pre> * * @param {*} reason Constant, message, exception or an object representing the rejection reason. * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`. */ var reject = function(reason) { return { then: function(callback, errback) { var result = defer(); nextTick(function() { result.resolve((errback || defaultErrback)(reason)); }); return result.promise; } }; }; /** * @ngdoc * @name ng.$q#when * @methodOf ng.$q * @description * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. * This is useful when you are dealing with on object that might or might not be a promise, or if * the promise comes from a source that can't be trusted. * * @param {*} value Value or a promise * @returns {Promise} Returns a single promise that will be resolved with an array of values, * each value coresponding to the promise at the same index in the `promises` array. If any of * the promises is resolved with a rejection, this resulting promise will be resolved with the * same rejection. */ var when = function(value, callback, errback) { var result = defer(), done; var wrappedCallback = function(value) { try { return (callback || defaultCallback)(value); } catch (e) { exceptionHandler(e); return reject(e); } }; var wrappedErrback = function(reason) { try { return (errback || defaultErrback)(reason); } catch (e) { exceptionHandler(e); return reject(e); } }; nextTick(function() { ref(value).then(function(value) { if (done) return; done = true; result.resolve(ref(value).then(wrappedCallback, wrappedErrback)); }, function(reason) { if (done) return; done = true; result.resolve(wrappedErrback(reason)); }); }); return result.promise; }; function defaultCallback(value) { return value; } function defaultErrback(reason) { return reject(reason); } /** * @ngdoc * @name ng.$q#all * @methodOf ng.$q * @description * Combines multiple promises into a single promise that is resolved when all of the input * promises are resolved. * * @param {Array.<Promise>} promises An array of promises. * @returns {Promise} Returns a single promise that will be resolved with an array of values, * each value coresponding to the promise at the same index in the `promises` array. If any of * the promises is resolved with a rejection, this resulting promise will be resolved with the * same rejection. */ function all(promises) { var deferred = defer(), counter = promises.length, results = []; if (counter) { forEach(promises, function(promise, index) { ref(promise).then(function(value) { if (index in results) return; results[index] = value; if (!(--counter)) deferred.resolve(results); }, function(reason) { if (index in results) return; deferred.reject(reason); }); }); } else { deferred.resolve(results); } return deferred.promise; } return { defer: defer, reject: reject, when: when, all: all }; } /** * @ngdoc object * @name ng.$routeProvider * @function * * @description * * Used for configuring routes. See {@link ng.$route $route} for an example. */ function $RouteProvider(){ var routes = {}; /** * @ngdoc method * @name ng.$routeProvider#when * @methodOf ng.$routeProvider * * @param {string} path Route path (matched against `$location.path`). If `$location.path` * contains redundant trailing slash or is missing one, the route will still match and the * `$location.path` will be updated to add or drop the trailing slash to exacly match the * route definition. * @param {Object} route Mapping information to be assigned to `$route.current` on route * match. * * Object properties: * * - `controller` – `{(string|function()=}` – Controller fn that should be associated with newly * created scope or the name of a {@link angular.Module#controller registered controller} * if passed as a string. * - `template` – `{string=}` – html template as a string that should be used by * {@link ng.directive:ngView ngView} or * {@link ng.directive:ngInclude ngInclude} directives. * this property takes precedence over `templateUrl`. * - `templateUrl` – `{string=}` – path to an html template that should be used by * {@link ng.directive:ngView ngView}. * - `resolve` - `{Object.<string, function>=}` - An optional map of dependencies which should * be injected into the controller. If any of these dependencies are promises, they will be * resolved and converted to a value before the controller is instantiated and the * `$afterRouteChange` event is fired. The map object is: * * - `key` – `{string}`: a name of a dependency to be injected into the controller. * - `factory` - `{string|function}`: If `string` then it is an alias for a service. * Otherwise if function, then it is {@link api/AUTO.$injector#invoke injected} * and the return value is treated as the dependency. If the result is a promise, it is resolved * before its value is injected into the controller. * * - `redirectTo` – {(string|function())=} – value to update * {@link ng.$location $location} path with and trigger route redirection. * * If `redirectTo` is a function, it will be called with the following parameters: * * - `{Object.<string>}` - route parameters extracted from the current * `$location.path()` by applying the current route templateUrl. * - `{string}` - current `$location.path()` * - `{Object}` - current `$location.search()` * * The custom `redirectTo` function is expected to return a string which will be used * to update `$location.path()` and `$location.search()`. * * - `[reloadOnSearch=true]` - {boolean=} - reload route when only $location.search() * changes. * * If the option is set to `false` and url in the browser changes, then * `$routeUpdate` event is broadcasted on the root scope. * * @returns {Object} self * * @description * Adds a new route definition to the `$route` service. */ this.when = function(path, route) { routes[path] = extend({reloadOnSearch: true}, route); // create redirection for trailing slashes if (path) { var redirectPath = (path[path.length-1] == '/') ? path.substr(0, path.length-1) : path +'/'; routes[redirectPath] = {redirectTo: path}; } return this; }; /** * @ngdoc method * @name ng.$routeProvider#otherwise * @methodOf ng.$routeProvider * * @description * Sets route definition that will be used on route change when no other route definition * is matched. * * @param {Object} params Mapping information to be assigned to `$route.current`. * @returns {Object} self */ this.otherwise = function(params) { this.when(null, params); return this; }; this.$get = ['$rootScope', '$location', '$routeParams', '$q', '$injector', '$http', '$templateCache', function( $rootScope, $location, $routeParams, $q, $injector, $http, $templateCache) { /** * @ngdoc object * @name ng.$route * @requires $location * @requires $routeParams * * @property {Object} current Reference to the current route definition. * The route definition contains: * * - `controller`: The controller constructor as define in route definition. * - `locals`: A map of locals which is used by {@link ng.$controller $controller} service for * controller instantiation. The `locals` contain * the resolved values of the `resolve` map. Additionally the `locals` also contain: * * - `$scope` - The current route scope. * - `$template` - The current route template HTML. * * @property {Array.<Object>} routes Array of all configured routes. * * @description * Is used for deep-linking URLs to controllers and views (HTML partials). * It watches `$location.url()` and tries to map the path to an existing route definition. * * You can define routes through {@link ng.$routeProvider $routeProvider}'s API. * * The `$route` service is typically used in conjunction with {@link ng.directive:ngView ngView} * directive and the {@link ng.$routeParams $routeParams} service. * * @example This example shows how changing the URL hash causes the `$route` to match a route against the URL, and the `ngView` pulls in the partial. Note that this example is using {@link ng.directive:script inlined templates} to get it working on jsfiddle as well. <example module="ngView"> <file name="index.html"> <div ng-controller="MainCntl"> Choose: <a href="Book/Moby">Moby</a> | <a href="Book/Moby/ch/1">Moby: Ch1</a> | <a href="Book/Gatsby">Gatsby</a> | <a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> | <a href="Book/Scarlet">Scarlet Letter</a><br/> <div ng-view></div> <hr /> <pre>$location.path() = {{$location.path()}}</pre> <pre>$route.current.templateUrl = {{$route.current.templateUrl}}</pre> <pre>$route.current.params = {{$route.current.params}}</pre> <pre>$route.current.scope.name = {{$route.current.scope.name}}</pre> <pre>$routeParams = {{$routeParams}}</pre> </div> </file> <file name="book.html"> controller: {{name}}<br /> Book Id: {{params.bookId}}<br /> </file> <file name="chapter.html"> controller: {{name}}<br /> Book Id: {{params.bookId}}<br /> Chapter Id: {{params.chapterId}} </file> <file name="script.js"> angular.module('ngView', [], function($routeProvider, $locationProvider) { $routeProvider.when('/Book/:bookId', { templateUrl: 'book.html', controller: BookCntl, resolve: { // I will cause a 1 second delay delay: function($q, $timeout) { var delay = $q.defer(); $timeout(delay.resolve, 1000); return delay.promise; } } }); $routeProvider.when('/Book/:bookId/ch/:chapterId', { templateUrl: 'chapter.html', controller: ChapterCntl }); // configure html5 to get links working on jsfiddle $locationProvider.html5Mode(true); }); function MainCntl($scope, $route, $routeParams, $location) { $scope.$route = $route; $scope.$location = $location; $scope.$routeParams = $routeParams; } function BookCntl($scope, $routeParams) { $scope.name = "BookCntl"; $scope.params = $routeParams; } function ChapterCntl($scope, $routeParams) { $scope.name = "ChapterCntl"; $scope.params = $routeParams; } </file> <file name="scenario.js"> it('should load and compile correct template', function() { element('a:contains("Moby: Ch1")').click(); var content = element('.doc-example-live [ng-view]').text(); expect(content).toMatch(/controller\: ChapterCntl/); expect(content).toMatch(/Book Id\: Moby/); expect(content).toMatch(/Chapter Id\: 1/); element('a:contains("Scarlet")').click(); sleep(2); // promises are not part of scenario waiting content = element('.doc-example-live [ng-view]').text(); expect(content).toMatch(/controller\: BookCntl/); expect(content).toMatch(/Book Id\: Scarlet/); }); </file> </example> */ /** * @ngdoc event * @name ng.$route#$routeChangeStart * @eventOf ng.$route * @eventType broadcast on root scope * @description * Broadcasted before a route change. At this point the route services starts * resolving all of the dependencies needed for the route change to occurs. * Typically this involves fetching the view template as well as any dependencies * defined in `resolve` route property. Once all of the dependencies are resolved * `$routeChangeSuccess` is fired. * * @param {Route} next Future route information. * @param {Route} current Current route information. */ /** * @ngdoc event * @name ng.$route#$routeChangeSuccess * @eventOf ng.$route * @eventType broadcast on root scope * @description * Broadcasted after a route dependencies are resolved. * {@link ng.directive:ngView ngView} listens for the directive * to instantiate the controller and render the view. * * @param {Route} current Current route information. * @param {Route} previous Previous route information. */ /** * @ngdoc event * @name ng.$route#$routeChangeError * @eventOf ng.$route * @eventType broadcast on root scope * @description * Broadcasted if any of the resolve promises are rejected. * * @param {Route} current Current route information. * @param {Route} previous Previous route information. * @param {Route} rejection Rejection of the promise. Usually the error of the failed promise. */ /** * @ngdoc event * @name ng.$route#$routeUpdate * @eventOf ng.$route * @eventType broadcast on root scope * @description * * The `reloadOnSearch` property has been set to false, and we are reusing the same * instance of the Controller. */ var matcher = switchRouteMatcher, forceReload = false, $route = { routes: routes, /** * @ngdoc method * @name ng.$route#reload * @methodOf ng.$route * * @description * Causes `$route` service to reload the current route even if * {@link ng.$location $location} hasn't changed. * * As a result of that, {@link ng.directive:ngView ngView} * creates new scope, reinstantiates the controller. */ reload: function() { forceReload = true; $rootScope.$evalAsync(updateRoute); } }; $rootScope.$on('$locationChangeSuccess', updateRoute); return $route; ///////////////////////////////////////////////////// function switchRouteMatcher(on, when) { // TODO(i): this code is convoluted and inefficient, we should construct the route matching // regex only once and then reuse it var regex = '^' + when.replace(/([\.\\\(\)\^\$])/g, "\\$1") + '$', params = [], dst = {}; forEach(when.split(/\W/), function(param) { if (param) { var paramRegExp = new RegExp(":" + param + "([\\W])"); if (regex.match(paramRegExp)) { regex = regex.replace(paramRegExp, "([^\\/]*)$1"); params.push(param); } } }); var match = on.match(new RegExp(regex)); if (match) { forEach(params, function(name, index) { dst[name] = match[index + 1]; }); } return match ? dst : null; } function updateRoute() { var next = parseRoute(), last = $route.current; if (next && last && next.$route === last.$route && equals(next.pathParams, last.pathParams) && !next.reloadOnSearch && !forceReload) { last.params = next.params; copy(last.params, $routeParams); $rootScope.$broadcast('$routeUpdate', last); } else if (next || last) { forceReload = false; $rootScope.$broadcast('$routeChangeStart', next, last); $route.current = next; if (next) { if (next.redirectTo) { if (isString(next.redirectTo)) { $location.path(interpolate(next.redirectTo, next.params)).search(next.params) .replace(); } else { $location.url(next.redirectTo(next.pathParams, $location.path(), $location.search())) .replace(); } } } $q.when(next). then(function() { if (next) { var keys = [], values = [], template; forEach(next.resolve || {}, function(value, key) { keys.push(key); values.push(isFunction(value) ? $injector.invoke(value) : $injector.get(value)); }); if (isDefined(template = next.template)) { } else if (isDefined(template = next.templateUrl)) { template = $http.get(template, {cache: $templateCache}). then(function(response) { return response.data; }); } if (isDefined(template)) { keys.push('$template'); values.push(template); } return $q.all(values).then(function(values) { var locals = {}; forEach(values, function(value, index) { locals[keys[index]] = value; }); return locals; }); } }). // after route change then(function(locals) { if (next == $route.current) { if (next) { next.locals = locals; copy(next.params, $routeParams); } $rootScope.$broadcast('$routeChangeSuccess', next, last); } }, function(error) { if (next == $route.current) { $rootScope.$broadcast('$routeChangeError', next, last, error); } }); } } /** * @returns the current active route, by matching it against the URL */ function parseRoute() { // Match a route var params, match; forEach(routes, function(route, path) { if (!match && (params = matcher($location.path(), path))) { match = inherit(route, { params: extend({}, $location.search(), params), pathParams: params}); match.$route = route; } }); // No route matched; fallback to "otherwise" route return match || routes[null] && inherit(routes[null], {params: {}, pathParams:{}}); } /** * @returns interpolation of the redirect path with the parametrs */ function interpolate(string, params) { var result = []; forEach((string||'').split(':'), function(segment, i) { if (i == 0) { result.push(segment); } else { var segmentMatch = segment.match(/(\w+)(.*)/); var key = segmentMatch[1]; result.push(params[key]); result.push(segmentMatch[2] || ''); delete params[key]; } }); return result.join(''); } }]; } /** * @ngdoc object * @name ng.$routeParams * @requires $route * * @description * Current set of route parameters. The route parameters are a combination of the * {@link ng.$location $location} `search()`, and `path()`. The `path` parameters * are extracted when the {@link ng.$route $route} path is matched. * * In case of parameter name collision, `path` params take precedence over `search` params. * * The service guarantees that the identity of the `$routeParams` object will remain unchanged * (but its properties will likely change) even when a route change occurs. * * @example * <pre> * // Given: * // URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby * // Route: /Chapter/:chapterId/Section/:sectionId * // * // Then * $routeParams ==> {chapterId:1, sectionId:2, search:'moby'} * </pre> */ function $RouteParamsProvider() { this.$get = valueFn({}); } /** * DESIGN NOTES * * The design decisions behind the scope ware heavily favored for speed and memory consumption. * * The typical use of scope is to watch the expressions, which most of the time return the same * value as last time so we optimize the operation. * * Closures construction is expensive from speed as well as memory: * - no closures, instead ups prototypical inheritance for API * - Internal state needs to be stored on scope directly, which means that private state is * exposed as $$____ properties * * Loop operations are optimized by using while(count--) { ... } * - this means that in order to keep the same order of execution as addition we have to add * items to the array at the begging (shift) instead of at the end (push) * * Child scopes are created and removed often * - Using array would be slow since inserts in meddle are expensive so we use linked list * * There are few watches then a lot of observers. This is why you don't want the observer to be * implemented in the same way as watch. Watch requires return of initialization function which * are expensive to construct. */ /** * @ngdoc object * @name ng.$rootScopeProvider * @description * * Provider for the $rootScope service. */ /** * @ngdoc function * @name ng.$rootScopeProvider#digestTtl * @methodOf ng.$rootScopeProvider * @description * * Sets the number of digest iteration the scope should attempt to execute before giving up and * assuming that the model is unstable. * * The current default is 10 iterations. * * @param {number} limit The number of digest iterations. */ /** * @ngdoc object * @name ng.$rootScope * @description * * Every application has a single root {@link ng.$rootScope.Scope scope}. * All other scopes are child scopes of the root scope. Scopes provide mechanism for watching the model and provide * event processing life-cycle. See {@link guide/scope developer guide on scopes}. */ function $RootScopeProvider(){ var TTL = 10; this.digestTtl = function(value) { if (arguments.length) { TTL = value; } return TTL; }; this.$get = ['$injector', '$exceptionHandler', '$parse', function( $injector, $exceptionHandler, $parse) { /** * @ngdoc function * @name ng.$rootScope.Scope * * @description * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the * {@link AUTO.$injector $injector}. Child scopes are created using the * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when * compiled HTML template is executed.) * * Here is a simple scope snippet to show how you can interact with the scope. * <pre> angular.injector(['ng']).invoke(function($rootScope) { var scope = $rootScope.$new(); scope.salutation = 'Hello'; scope.name = 'World'; expect(scope.greeting).toEqual(undefined); scope.$watch('name', function() { this.greeting = this.salutation + ' ' + this.name + '!'; }); // initialize the watch expect(scope.greeting).toEqual(undefined); scope.name = 'Misko'; // still old value, since watches have not been called yet expect(scope.greeting).toEqual(undefined); scope.$digest(); // fire all the watches expect(scope.greeting).toEqual('Hello Misko!'); }); * </pre> * * # Inheritance * A scope can inherit from a parent scope, as in this example: * <pre> var parent = $rootScope; var child = parent.$new(); parent.salutation = "Hello"; child.name = "World"; expect(child.salutation).toEqual('Hello'); child.salutation = "Welcome"; expect(child.salutation).toEqual('Welcome'); expect(parent.salutation).toEqual('Hello'); * </pre> * * * @param {Object.<string, function()>=} providers Map of service factory which need to be provided * for the current scope. Defaults to {@link ng}. * @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should * append/override services provided by `providers`. This is handy when unit-testing and having * the need to override a default service. * @returns {Object} Newly created scope. * */ function Scope() { this.$id = nextUid(); this.$$phase = this.$parent = this.$$watchers = this.$$nextSibling = this.$$prevSibling = this.$$childHead = this.$$childTail = null; this['this'] = this.$root = this; this.$$asyncQueue = []; this.$$listeners = {}; } /** * @ngdoc property * @name ng.$rootScope.Scope#$id * @propertyOf ng.$rootScope.Scope * @returns {number} Unique scope ID (monotonically increasing alphanumeric sequence) useful for * debugging. */ Scope.prototype = { /** * @ngdoc function * @name ng.$rootScope.Scope#$new * @methodOf ng.$rootScope.Scope * @function * * @description * Creates a new child {@link ng.$rootScope.Scope scope}. * * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} and * {@link ng.$rootScope.Scope#$digest $digest()} events. The scope can be removed from the scope * hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}. * * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is desired for * the scope and its child scopes to be permanently detached from the parent and thus stop * participating in model change detection and listener notification by invoking. * * @param {boolean} isolate if true then the scoped does not prototypically inherit from the * parent scope. The scope is isolated, as it can not se parent scope properties. * When creating widgets it is useful for the widget to not accidently read parent * state. * * @returns {Object} The newly created child scope. * */ $new: function(isolate) { var Child, child; if (isFunction(isolate)) { // TODO: remove at some point throw Error('API-CHANGE: Use $controller to instantiate controllers.'); } if (isolate) { child = new Scope(); child.$root = this.$root; } else { Child = function() {}; // should be anonymous; This is so that when the minifier munges // the name it does not become random set of chars. These will then show up as class // name in the debugger. Child.prototype = this; child = new Child(); child.$id = nextUid(); } child['this'] = child; child.$$listeners = {}; child.$parent = this; child.$$asyncQueue = []; child.$$watchers = child.$$nextSibling = child.$$childHead = child.$$childTail = null; child.$$prevSibling = this.$$childTail; if (this.$$childHead) { this.$$childTail.$$nextSibling = child; this.$$childTail = child; } else { this.$$childHead = this.$$childTail = child; } return child; }, /** * @ngdoc function * @name ng.$rootScope.Scope#$watch * @methodOf ng.$rootScope.Scope * @function * * @description * Registers a `listener` callback to be executed whenever the `watchExpression` changes. * * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest $digest()} and * should return the value which will be watched. (Since {@link ng.$rootScope.Scope#$digest $digest()} * reruns when it detects changes the `watchExpression` can execute multiple times per * {@link ng.$rootScope.Scope#$digest $digest()} and should be idempotent.) * - The `listener` is called only when the value from the current `watchExpression` and the * previous call to `watchExpression' are not equal (with the exception of the initial run * see below). The inequality is determined according to * {@link angular.equals} function. To save the value of the object for later comparison * {@link angular.copy} function is used. It also means that watching complex options will * have adverse memory and performance implications. * - The watch `listener` may change the model, which may trigger other `listener`s to fire. This * is achieved by rerunning the watchers until no changes are detected. The rerun iteration * limit is 100 to prevent infinity loop deadlock. * * * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called, * you can register an `watchExpression` function with no `listener`. (Since `watchExpression`, * can execute multiple times per {@link ng.$rootScope.Scope#$digest $digest} cycle when a change is * detected, be prepared for multiple calls to your listener.) * * After a watcher is registered with the scope, the `listener` fn is called asynchronously * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the * watcher. In rare cases, this is undesirable because the listener is called when the result * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the * listener was called due to initialization. * * * # Example * <pre> // let's assume that scope was dependency injected as the $rootScope var scope = $rootScope; scope.name = 'misko'; scope.counter = 0; expect(scope.counter).toEqual(0); scope.$watch('name', function(newValue, oldValue) { counter = counter + 1; }); expect(scope.counter).toEqual(0); scope.$digest(); // no variable change expect(scope.counter).toEqual(0); scope.name = 'adam'; scope.$digest(); expect(scope.counter).toEqual(1); * </pre> * * * * @param {(function()|string)} watchExpression Expression that is evaluated on each * {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers a * call to the `listener`. * * - `string`: Evaluated as {@link guide/expression expression} * - `function(scope)`: called with current `scope` as a parameter. * @param {(function()|string)=} listener Callback called whenever the return value of * the `watchExpression` changes. * * - `string`: Evaluated as {@link guide/expression expression} * - `function(newValue, oldValue, scope)`: called with current and previous values as parameters. * * @param {boolean=} objectEquality Compare object for equality rather then for refference. * @returns {function()} Returns a deregistration function for this listener. */ $watch: function(watchExp, listener, objectEquality) { var scope = this, get = compileToFn(watchExp, 'watch'), array = scope.$$watchers, watcher = { fn: listener, last: initWatchVal, get: get, exp: watchExp, eq: !!objectEquality }; // in the case user pass string, we need to compile it, do we really need this ? if (!isFunction(listener)) { var listenFn = compileToFn(listener || noop, 'listener'); watcher.fn = function(newVal, oldVal, scope) {listenFn(scope);}; } if (!array) { array = scope.$$watchers = []; } // we use unshift since we use a while loop in $digest for speed. // the while loop reads in reverse order. array.unshift(watcher); return function() { arrayRemove(array, watcher); }; }, /** * @ngdoc function * @name ng.$rootScope.Scope#$digest * @methodOf ng.$rootScope.Scope * @function * * @description * Process all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and its children. * Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change the model, the * `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers} until no more listeners are * firing. This means that it is possible to get into an infinite loop. This function will throw * `'Maximum iteration limit exceeded.'` if the number of iterations exceeds 10. * * Usually you don't call `$digest()` directly in * {@link ng.directive:ngController controllers} or in * {@link ng.$compileProvider#directive directives}. * Instead a call to {@link ng.$rootScope.Scope#$apply $apply()} (typically from within a * {@link ng.$compileProvider#directive directives}) will force a `$digest()`. * * If you want to be notified whenever `$digest()` is called, * you can register a `watchExpression` function with {@link ng.$rootScope.Scope#$watch $watch()} * with no `listener`. * * You may have a need to call `$digest()` from within unit-tests, to simulate the scope * life-cycle. * * # Example * <pre> var scope = ...; scope.name = 'misko'; scope.counter = 0; expect(scope.counter).toEqual(0); scope.$watch('name', function(newValue, oldValue) { counter = counter + 1; }); expect(scope.counter).toEqual(0); scope.$digest(); // no variable change expect(scope.counter).toEqual(0); scope.name = 'adam'; scope.$digest(); expect(scope.counter).toEqual(1); * </pre> * */ $digest: function() { var watch, value, last, watchers, asyncQueue, length, dirty, ttl = TTL, next, current, target = this, watchLog = [], logIdx, logMsg; beginPhase('$digest'); do { dirty = false; current = target; do { asyncQueue = current.$$asyncQueue; while(asyncQueue.length) { try { current.$eval(asyncQueue.shift()); } catch (e) { $exceptionHandler(e); } } if ((watchers = current.$$watchers)) { // process our watches length = watchers.length; while (length--) { try { watch = watchers[length]; // Most common watches are on primitives, in which case we can short // circuit it with === operator, only when === fails do we use .equals if ((value = watch.get(current)) !== (last = watch.last) && !(watch.eq ? equals(value, last) : (typeof value == 'number' && typeof last == 'number' && isNaN(value) && isNaN(last)))) { dirty = true; watch.last = watch.eq ? copy(value) : value; watch.fn(value, ((last === initWatchVal) ? value : last), current); if (ttl < 5) { logIdx = 4 - ttl; if (!watchLog[logIdx]) watchLog[logIdx] = []; logMsg = (isFunction(watch.exp)) ? 'fn: ' + (watch.exp.name || watch.exp.toString()) : watch.exp; logMsg += '; newVal: ' + toJson(value) + '; oldVal: ' + toJson(last); watchLog[logIdx].push(logMsg); } } } catch (e) { $exceptionHandler(e); } } } // Insanity Warning: scope depth-first traversal // yes, this code is a bit crazy, but it works and we have tests to prove it! // this piece should be kept in sync with the traversal in $broadcast if (!(next = (current.$$childHead || (current !== target && current.$$nextSibling)))) { while(current !== target && !(next = current.$$nextSibling)) { current = current.$parent; } } } while ((current = next)); if(dirty && !(ttl--)) { clearPhase(); throw Error(TTL + ' $digest() iterations reached. Aborting!\n' + 'Watchers fired in the last 5 iterations: ' + toJson(watchLog)); } } while (dirty || asyncQueue.length); clearPhase(); }, /** * @ngdoc event * @name ng.$rootScope.Scope#$destroy * @eventOf ng.$rootScope.Scope * @eventType broadcast on scope being destroyed * * @description * Broadcasted when a scope and its children are being destroyed. */ /** * @ngdoc function * @name ng.$rootScope.Scope#$destroy * @methodOf ng.$rootScope.Scope * @function * * @description * Remove the current scope (and all of its children) from the parent scope. Removal implies * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer * propagate to the current scope and its children. Removal also implies that the current * scope is eligible for garbage collection. * * The `$destroy()` is usually used by directives such as * {@link ng.directive:ngRepeat ngRepeat} for managing the * unrolling of the loop. * * Just before a scope is destroyed a `$destroy` event is broadcasted on this scope. * Application code can register a `$destroy` event handler that will give it chance to * perform any necessary cleanup. */ $destroy: function() { if ($rootScope == this) return; // we can't remove the root node; var parent = this.$parent; this.$broadcast('$destroy'); if (parent.$$childHead == this) parent.$$childHead = this.$$nextSibling; if (parent.$$childTail == this) parent.$$childTail = this.$$prevSibling; if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling; if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling; }, /** * @ngdoc function * @name ng.$rootScope.Scope#$eval * @methodOf ng.$rootScope.Scope * @function * * @description * Executes the `expression` on the current scope returning the result. Any exceptions in the * expression are propagated (uncaught). This is useful when evaluating engular expressions. * * # Example * <pre> var scope = ng.$rootScope.Scope(); scope.a = 1; scope.b = 2; expect(scope.$eval('a+b')).toEqual(3); expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3); * </pre> * * @param {(string|function())=} expression An angular expression to be executed. * * - `string`: execute using the rules as defined in {@link guide/expression expression}. * - `function(scope)`: execute the function with the current `scope` parameter. * * @returns {*} The result of evaluating the expression. */ $eval: function(expr, locals) { return $parse(expr)(this, locals); }, /** * @ngdoc function * @name ng.$rootScope.Scope#$evalAsync * @methodOf ng.$rootScope.Scope * @function * * @description * Executes the expression on the current scope at a later point in time. * * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only that: * * - it will execute in the current script execution context (before any DOM rendering). * - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after * `expression` execution. * * Any exceptions from the execution of the expression are forwarded to the * {@link ng.$exceptionHandler $exceptionHandler} service. * * @param {(string|function())=} expression An angular expression to be executed. * * - `string`: execute using the rules as defined in {@link guide/expression expression}. * - `function(scope)`: execute the function with the current `scope` parameter. * */ $evalAsync: function(expr) { this.$$asyncQueue.push(expr); }, /** * @ngdoc function * @name ng.$rootScope.Scope#$apply * @methodOf ng.$rootScope.Scope * @function * * @description * `$apply()` is used to execute an expression in angular from outside of the angular framework. * (For example from browser DOM events, setTimeout, XHR or third party libraries). * Because we are calling into the angular framework we need to perform proper scope life-cycle * of {@link ng.$exceptionHandler exception handling}, * {@link ng.$rootScope.Scope#$digest executing watches}. * * ## Life cycle * * # Pseudo-Code of `$apply()` * <pre> function $apply(expr) { try { return $eval(expr); } catch (e) { $exceptionHandler(e); } finally { $root.$digest(); } } * </pre> * * * Scope's `$apply()` method transitions through the following stages: * * 1. The {@link guide/expression expression} is executed using the * {@link ng.$rootScope.Scope#$eval $eval()} method. * 2. Any exceptions from the execution of the expression are forwarded to the * {@link ng.$exceptionHandler $exceptionHandler} service. * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the expression * was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method. * * * @param {(string|function())=} exp An angular expression to be executed. * * - `string`: execute using the rules as defined in {@link guide/expression expression}. * - `function(scope)`: execute the function with current `scope` parameter. * * @returns {*} The result of evaluating the expression. */ $apply: function(expr) { try { beginPhase('$apply'); return this.$eval(expr); } catch (e) { $exceptionHandler(e); } finally { clearPhase(); try { $rootScope.$digest(); } catch (e) { $exceptionHandler(e); throw e; } } }, /** * @ngdoc function * @name ng.$rootScope.Scope#$on * @methodOf ng.$rootScope.Scope * @function * * @description * Listen on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for discussion of * event life cycle. * * @param {string} name Event name to listen on. * @param {function(event)} listener Function to call when the event is emitted. * @returns {function()} Returns a deregistration function for this listener. * * The event listener function format is: `function(event, args...)`. The `event` object * passed into the listener has the following attributes: * * - `targetScope` - {Scope}: the scope on which the event was `$emit`-ed or `$broadcast`-ed. * - `currentScope` - {Scope}: the current scope which is handling the event. * - `name` - {string}: Name of the event. * - `stopPropagation` - {function=}: calling `stopPropagation` function will cancel further event propagation * (available only for events that were `$emit`-ed). * - `preventDefault` - {function}: calling `preventDefault` sets `defaultPrevented` flag to true. * - `defaultPrevented` - {boolean}: true if `preventDefault` was called. */ $on: function(name, listener) { var namedListeners = this.$$listeners[name]; if (!namedListeners) { this.$$listeners[name] = namedListeners = []; } namedListeners.push(listener); return function() { arrayRemove(namedListeners, listener); }; }, /** * @ngdoc function * @name ng.$rootScope.Scope#$emit * @methodOf ng.$rootScope.Scope * @function * * @description * Dispatches an event `name` upwards through the scope hierarchy notifying the * registered {@link ng.$rootScope.Scope#$on} listeners. * * The event life cycle starts at the scope on which `$emit` was called. All * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get notified. * Afterwards, the event traverses upwards toward the root scope and calls all registered * listeners along the way. The event will stop propagating if one of the listeners cancels it. * * Any exception emmited from the {@link ng.$rootScope.Scope#$on listeners} will be passed * onto the {@link ng.$exceptionHandler $exceptionHandler} service. * * @param {string} name Event name to emit. * @param {...*} args Optional set of arguments which will be passed onto the event listeners. * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on} */ $emit: function(name, args) { var empty = [], namedListeners, scope = this, stopPropagation = false, event = { name: name, targetScope: scope, stopPropagation: function() {stopPropagation = true;}, preventDefault: function() { event.defaultPrevented = true; }, defaultPrevented: false }, listenerArgs = concat([event], arguments, 1), i, length; do { namedListeners = scope.$$listeners[name] || empty; event.currentScope = scope; for (i=0, length=namedListeners.length; i<length; i++) { try { namedListeners[i].apply(null, listenerArgs); if (stopPropagation) return event; } catch (e) { $exceptionHandler(e); } } //traverse upwards scope = scope.$parent; } while (scope); return event; }, /** * @ngdoc function * @name ng.$rootScope.Scope#$broadcast * @methodOf ng.$rootScope.Scope * @function * * @description * Dispatches an event `name` downwards to all child scopes (and their children) notifying the * registered {@link ng.$rootScope.Scope#$on} listeners. * * The event life cycle starts at the scope on which `$broadcast` was called. All * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get notified. * Afterwards, the event propagates to all direct and indirect scopes of the current scope and * calls all registered listeners along the way. The event cannot be canceled. * * Any exception emmited from the {@link ng.$rootScope.Scope#$on listeners} will be passed * onto the {@link ng.$exceptionHandler $exceptionHandler} service. * * @param {string} name Event name to emit. * @param {...*} args Optional set of arguments which will be passed onto the event listeners. * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on} */ $broadcast: function(name, args) { var target = this, current = target, next = target, event = { name: name, targetScope: target, preventDefault: function() { event.defaultPrevented = true; }, defaultPrevented: false }, listenerArgs = concat([event], arguments, 1); //down while you can, then up and next sibling or up and next sibling until back at root do { current = next; event.currentScope = current; forEach(current.$$listeners[name], function(listener) { try { listener.apply(null, listenerArgs); } catch(e) { $exceptionHandler(e); } }); // Insanity Warning: scope depth-first traversal // yes, this code is a bit crazy, but it works and we have tests to prove it! // this piece should be kept in sync with the traversal in $digest if (!(next = (current.$$childHead || (current !== target && current.$$nextSibling)))) { while(current !== target && !(next = current.$$nextSibling)) { current = current.$parent; } } } while ((current = next)); return event; } }; var $rootScope = new Scope(); return $rootScope; function beginPhase(phase) { if ($rootScope.$$phase) { throw Error($rootScope.$$phase + ' already in progress'); } $rootScope.$$phase = phase; } function clearPhase() { $rootScope.$$phase = null; } function compileToFn(exp, name) { var fn = $parse(exp); assertArgFn(fn, name); return fn; } /** * function used as an initial value for watchers. * because it's uniqueue we can easily tell it apart from other values */ function initWatchVal() {} }]; } /** * !!! This is an undocumented "private" service !!! * * @name ng.$sniffer * @requires $window * * @property {boolean} history Does the browser support html5 history api ? * @property {boolean} hashchange Does the browser support hashchange event ? * * @description * This is very simple implementation of testing browser's features. */ function $SnifferProvider() { this.$get = ['$window', function($window) { var eventSupport = {}, android = int((/android (\d+)/.exec(lowercase($window.navigator.userAgent)) || [])[1]); return { // Android has history.pushState, but it does not update location correctly // so let's not use the history API at all. // http://code.google.com/p/android/issues/detail?id=17471 // https://github.com/angular/angular.js/issues/904 history: !!($window.history && $window.history.pushState && !(android < 4)), hashchange: 'onhashchange' in $window && // IE8 compatible mode lies (!$window.document.documentMode || $window.document.documentMode > 7), hasEvent: function(event) { // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have // it. In particular the event is not fired when backspace or delete key are pressed or // when cut operation is performed. if (event == 'input' && msie == 9) return false; if (isUndefined(eventSupport[event])) { var divElm = $window.document.createElement('div'); eventSupport[event] = 'on' + event in divElm; } return eventSupport[event]; }, // TODO(i): currently there is no way to feature detect CSP without triggering alerts csp: false }; }]; } /** * @ngdoc object * @name ng.$window * * @description * A reference to the browser's `window` object. While `window` * is globally available in JavaScript, it causes testability problems, because * it is a global variable. In angular we always refer to it through the * `$window` service, so it may be overriden, removed or mocked for testing. * * All expressions are evaluated with respect to current scope so they don't * suffer from window globality. * * @example <doc:example> <doc:source> <input ng-init="$window = $service('$window'); greeting='Hello World!'" type="text" ng-model="greeting" /> <button ng-click="$window.alert(greeting)">ALERT</button> </doc:source> <doc:scenario> </doc:scenario> </doc:example> */ function $WindowProvider(){ this.$get = valueFn(window); } /** * Parse headers into key value object * * @param {string} headers Raw headers as a string * @returns {Object} Parsed headers as key value object */ function parseHeaders(headers) { var parsed = {}, key, val, i; if (!headers) return parsed; forEach(headers.split('\n'), function(line) { i = line.indexOf(':'); key = lowercase(trim(line.substr(0, i))); val = trim(line.substr(i + 1)); if (key) { if (parsed[key]) { parsed[key] += ', ' + val; } else { parsed[key] = val; } } }); return parsed; } /** * Returns a function that provides access to parsed headers. * * Headers are lazy parsed when first requested. * @see parseHeaders * * @param {(string|Object)} headers Headers to provide access to. * @returns {function(string=)} Returns a getter function which if called with: * * - if called with single an argument returns a single header value or null * - if called with no arguments returns an object containing all headers. */ function headersGetter(headers) { var headersObj = isObject(headers) ? headers : undefined; return function(name) { if (!headersObj) headersObj = parseHeaders(headers); if (name) { return headersObj[lowercase(name)] || null; } return headersObj; }; } /** * Chain all given functions * * This function is used for both request and response transforming * * @param {*} data Data to transform. * @param {function(string=)} headers Http headers getter fn. * @param {(function|Array.<function>)} fns Function or an array of functions. * @returns {*} Transformed data. */ function transformData(data, headers, fns) { if (isFunction(fns)) return fns(data, headers); forEach(fns, function(fn) { data = fn(data, headers); }); return data; } function isSuccess(status) { return 200 <= status && status < 300; } function $HttpProvider() { var JSON_START = /^\s*(\[|\{[^\{])/, JSON_END = /[\}\]]\s*$/, PROTECTION_PREFIX = /^\)\]\}',?\n/; var $config = this.defaults = { // transform incoming response data transformResponse: [function(data) { if (isString(data)) { // strip json vulnerability protection prefix data = data.replace(PROTECTION_PREFIX, ''); if (JSON_START.test(data) && JSON_END.test(data)) data = fromJson(data, true); } return data; }], // transform outgoing request data transformRequest: [function(d) { return isObject(d) && !isFile(d) ? toJson(d) : d; }], // default headers headers: { common: { 'Accept': 'application/json, text/plain, */*', 'X-Requested-With': 'XMLHttpRequest' }, post: {'Content-Type': 'application/json;charset=utf-8'}, put: {'Content-Type': 'application/json;charset=utf-8'} } }; var providerResponseInterceptors = this.responseInterceptors = []; this.$get = ['$httpBackend', '$browser', '$cacheFactory', '$rootScope', '$q', '$injector', function($httpBackend, $browser, $cacheFactory, $rootScope, $q, $injector) { var defaultCache = $cacheFactory('$http'), responseInterceptors = []; forEach(providerResponseInterceptors, function(interceptor) { responseInterceptors.push( isString(interceptor) ? $injector.get(interceptor) : $injector.invoke(interceptor) ); }); /** * @ngdoc function * @name ng.$http * @requires $httpBacked * @requires $browser * @requires $cacheFactory * @requires $rootScope * @requires $q * @requires $injector * * @description * The `$http` service is a core Angular service that facilitates communication with the remote * HTTP servers via browser's {@link https://developer.mozilla.org/en/xmlhttprequest * XMLHttpRequest} object or via {@link http://en.wikipedia.org/wiki/JSONP JSONP}. * * For unit testing applications that use `$http` service, see * {@link ngMock.$httpBackend $httpBackend mock}. * * For a higher level of abstraction, please check out the {@link ngResource.$resource * $resource} service. * * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by * the $q service. While for simple usage patters this doesn't matter much, for advanced usage, * it is important to familiarize yourself with these apis and guarantees they provide. * * * # General usage * The `$http` service is a function which takes a single argument — a configuration object — * that is used to generate an http request and returns a {@link ng.$q promise} * with two $http specific methods: `success` and `error`. * * <pre> * $http({method: 'GET', url: '/someUrl'}). * success(function(data, status, headers, config) { * // this callback will be called asynchronously * // when the response is available * }). * error(function(data, status, headers, config) { * // called asynchronously if an error occurs * // or server returns response with status * // code outside of the <200, 400) range * }); * </pre> * * Since the returned value of calling the $http function is a Promise object, you can also use * the `then` method to register callbacks, and these callbacks will receive a single argument – * an object representing the response. See the api signature and type info below for more * details. * * * # Shortcut methods * * Since all invocation of the $http service require definition of the http method and url and * POST and PUT requests require response body/data to be provided as well, shortcut methods * were created to simplify using the api: * * <pre> * $http.get('/someUrl').success(successCallback); * $http.post('/someUrl', data).success(successCallback); * </pre> * * Complete list of shortcut methods: * * - {@link ng.$http#get $http.get} * - {@link ng.$http#head $http.head} * - {@link ng.$http#post $http.post} * - {@link ng.$http#put $http.put} * - {@link ng.$http#delete $http.delete} * - {@link ng.$http#jsonp $http.jsonp} * * * # Setting HTTP Headers * * The $http service will automatically add certain http headers to all requests. These defaults * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration * object, which currently contains this default configuration: * * - `$httpProvider.defaults.headers.common` (headers that are common for all requests): * - `Accept: application/json, text/plain, * / *` * - `X-Requested-With: XMLHttpRequest` * - `$httpProvider.defaults.headers.post`: (header defaults for HTTP POST requests) * - `Content-Type: application/json` * - `$httpProvider.defaults.headers.put` (header defaults for HTTP PUT requests) * - `Content-Type: application/json` * * To add or overwrite these defaults, simply add or remove a property from this configuration * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object * with name equal to the lower-cased http method name, e.g. * `$httpProvider.defaults.headers.get['My-Header']='value'`. * * Additionally, the defaults can be set at runtime via the `$http.defaults` object in a similar * fassion as described above. * * * # Transforming Requests and Responses * * Both requests and responses can be transformed using transform functions. By default, Angular * applies these transformations: * * Request transformations: * * - if the `data` property of the request config object contains an object, serialize it into * JSON format. * * Response transformations: * * - if XSRF prefix is detected, strip it (see Security Considerations section below) * - if json response is detected, deserialize it using a JSON parser * * To override these transformation locally, specify transform functions as `transformRequest` * and/or `transformResponse` properties of the config object. To globally override the default * transforms, override the `$httpProvider.defaults.transformRequest` and * `$httpProvider.defaults.transformResponse` properties of the `$httpProvider`. * * * # Caching * * To enable caching set the configuration property `cache` to `true`. When the cache is * enabled, `$http` stores the response from the server in local cache. Next time the * response is served from the cache without sending a request to the server. * * Note that even if the response is served from cache, delivery of the data is asynchronous in * the same way that real requests are. * * If there are multiple GET requests for the same url that should be cached using the same * cache, but the cache is not populated yet, only one request to the server will be made and * the remaining requests will be fulfilled using the response for the first request. * * * # Response interceptors * * Before you start creating interceptors, be sure to understand the * {@link ng.$q $q and deferred/promise APIs}. * * For purposes of global error handling, authentication or any kind of synchronous or * asynchronous preprocessing of received responses, it is desirable to be able to intercept * responses for http requests before they are handed over to the application code that * initiated these requests. The response interceptors leverage the {@link ng.$q * promise apis} to fulfil this need for both synchronous and asynchronous preprocessing. * * The interceptors are service factories that are registered with the $httpProvider by * adding them to the `$httpProvider.responseInterceptors` array. The factory is called and * injected with dependencies (if specified) and returns the interceptor — a function that * takes a {@link ng.$q promise} and returns the original or a new promise. * * <pre> * // register the interceptor as a service * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) { * return function(promise) { * return promise.then(function(response) { * // do something on success * }, function(response) { * // do something on error * if (canRecover(response)) { * return responseOrNewPromise * } * return $q.reject(response); * }); * } * }); * * $httpProvider.responseInterceptors.push('myHttpInterceptor'); * * * // register the interceptor via an anonymous factory * $httpProvider.responseInterceptors.push(function($q, dependency1, dependency2) { * return function(promise) { * // same as above * } * }); * </pre> * * * # Security Considerations * * When designing web applications, consider security threats from: * * - {@link http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx * JSON Vulnerability} * - {@link http://en.wikipedia.org/wiki/Cross-site_request_forgery XSRF} * * Both server and the client must cooperate in order to eliminate these threats. Angular comes * pre-configured with strategies that address these issues, but for this to work backend server * cooperation is required. * * ## JSON Vulnerability Protection * * A {@link http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx * JSON Vulnerability} allows third party web-site to turn your JSON resource URL into * {@link http://en.wikipedia.org/wiki/JSON#JSONP JSONP} request under some conditions. To * counter this your server can prefix all JSON requests with following string `")]}',\n"`. * Angular will automatically strip the prefix before processing it as JSON. * * For example if your server needs to return: * <pre> * ['one','two'] * </pre> * * which is vulnerable to attack, your server can return: * <pre> * )]}', * ['one','two'] * </pre> * * Angular will strip the prefix, before processing the JSON. * * * ## Cross Site Request Forgery (XSRF) Protection * * {@link http://en.wikipedia.org/wiki/Cross-site_request_forgery XSRF} is a technique by which * an unauthorized site can gain your user's private data. Angular provides following mechanism * to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie * called `XSRF-TOKEN` and sets it as the HTTP header `X-XSRF-TOKEN`. Since only JavaScript that * runs on your domain could read the cookie, your server can be assured that the XHR came from * JavaScript running on your domain. * * To take advantage of this, your server needs to set a token in a JavaScript readable session * cookie called `XSRF-TOKEN` on first HTTP GET request. On subsequent non-GET requests the * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure * that only JavaScript running on your domain could have read the token. The token must be * unique for each user and must be verifiable by the server (to prevent the JavaScript making * up its own tokens). We recommend that the token is a digest of your site's authentication * cookie with {@link http://en.wikipedia.org/wiki/Rainbow_table salt for added security}. * * * @param {object} config Object describing the request to be made and how it should be * processed. The object has following properties: * * - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc) * - **url** – `{string}` – Absolute or relative URL of the resource that is being requested. * - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be turned to * `?key1=value1&key2=value2` after the url. If the value is not a string, it will be JSONified. * - **data** – `{string|Object}` – Data to be sent as the request message data. * - **headers** – `{Object}` – Map of strings representing HTTP headers to send to the server. * - **transformRequest** – `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` – * transform function or an array of such functions. The transform function takes the http * request body and headers and returns its transformed (typically serialized) version. * - **transformResponse** – `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` – * transform function or an array of such functions. The transform function takes the http * response body and headers and returns its transformed (typically deserialized) version. * - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the * GET request, otherwise if a cache instance built with * {@link ng.$cacheFactory $cacheFactory}, this cache will be used for * caching. * - **timeout** – `{number}` – timeout in milliseconds. * - **withCredentials** - `{boolean}` - whether to to set the `withCredentials` flag on the * XHR object. See {@link https://developer.mozilla.org/en/http_access_control#section_5 * requests with credentials} for more information. * * @returns {HttpPromise} Returns a {@link ng.$q promise} object with the * standard `then` method and two http specific methods: `success` and `error`. The `then` * method takes two arguments a success and an error callback which will be called with a * response object. The `success` and `error` methods take a single argument - a function that * will be called when the request succeeds or fails respectively. The arguments passed into * these functions are destructured representation of the response object passed into the * `then` method. The response object has these properties: * * - **data** – `{string|Object}` – The response body transformed with the transform functions. * - **status** – `{number}` – HTTP status code of the response. * - **headers** – `{function([headerName])}` – Header getter function. * - **config** – `{Object}` – The configuration object that was used to generate the request. * * @property {Array.<Object>} pendingRequests Array of config objects for currently pending * requests. This is primarily meant to be used for debugging purposes. * * * @example <example> <file name="index.html"> <div ng-controller="FetchCtrl"> <select ng-model="method"> <option>GET</option> <option>JSONP</option> </select> <input type="text" ng-model="url" size="80"/> <button ng-click="fetch()">fetch</button><br> <button ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button> <button ng-click="updateModel('JSONP', 'http://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')">Sample JSONP</button> <button ng-click="updateModel('JSONP', 'http://angularjs.org/doesntexist&callback=JSON_CALLBACK')">Invalid JSONP</button> <pre>http status code: {{status}}</pre> <pre>http response data: {{data}}</pre> </div> </file> <file name="script.js"> function FetchCtrl($scope, $http, $templateCache) { $scope.method = 'GET'; $scope.url = 'http-hello.html'; $scope.fetch = function() { $scope.code = null; $scope.response = null; $http({method: $scope.method, url: $scope.url, cache: $templateCache}). success(function(data, status) { $scope.status = status; $scope.data = data; }). error(function(data, status) { $scope.data = data || "Request failed"; $scope.status = status; }); }; $scope.updateModel = function(method, url) { $scope.method = method; $scope.url = url; }; } </file> <file name="http-hello.html"> Hello, $http! </file> <file name="scenario.js"> it('should make an xhr GET request', function() { element(':button:contains("Sample GET")').click(); element(':button:contains("fetch")').click(); expect(binding('status')).toBe('200'); expect(binding('data')).toMatch(/Hello, \$http!/); }); it('should make a JSONP request to angularjs.org', function() { element(':button:contains("Sample JSONP")').click(); element(':button:contains("fetch")').click(); expect(binding('status')).toBe('200'); expect(binding('data')).toMatch(/Super Hero!/); }); it('should make JSONP request to invalid URL and invoke the error handler', function() { element(':button:contains("Invalid JSONP")').click(); element(':button:contains("fetch")').click(); expect(binding('status')).toBe('0'); expect(binding('data')).toBe('Request failed'); }); </file> </example> */ function $http(config) { config.method = uppercase(config.method); var reqTransformFn = config.transformRequest || $config.transformRequest, respTransformFn = config.transformResponse || $config.transformResponse, defHeaders = $config.headers, reqHeaders = extend({'X-XSRF-TOKEN': $browser.cookies()['XSRF-TOKEN']}, defHeaders.common, defHeaders[lowercase(config.method)], config.headers), reqData = transformData(config.data, headersGetter(reqHeaders), reqTransformFn), promise; // strip content-type if data is undefined if (isUndefined(config.data)) { delete reqHeaders['Content-Type']; } // send request promise = sendReq(config, reqData, reqHeaders); // transform future response promise = promise.then(transformResponse, transformResponse); // apply interceptors forEach(responseInterceptors, function(interceptor) { promise = interceptor(promise); }); promise.success = function(fn) { promise.then(function(response) { fn(response.data, response.status, response.headers, config); }); return promise; }; promise.error = function(fn) { promise.then(null, function(response) { fn(response.data, response.status, response.headers, config); }); return promise; }; return promise; function transformResponse(response) { // make a copy since the response must be cacheable var resp = extend({}, response, { data: transformData(response.data, response.headers, respTransformFn) }); return (isSuccess(response.status)) ? resp : $q.reject(resp); } } $http.pendingRequests = []; /** * @ngdoc method * @name ng.$http#get * @methodOf ng.$http * * @description * Shortcut method to perform `GET` request * * @param {string} url Relative or absolute URL specifying the destination of the request * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ /** * @ngdoc method * @name ng.$http#delete * @methodOf ng.$http * * @description * Shortcut method to perform `DELETE` request * * @param {string} url Relative or absolute URL specifying the destination of the request * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ /** * @ngdoc method * @name ng.$http#head * @methodOf ng.$http * * @description * Shortcut method to perform `HEAD` request * * @param {string} url Relative or absolute URL specifying the destination of the request * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ /** * @ngdoc method * @name ng.$http#jsonp * @methodOf ng.$http * * @description * Shortcut method to perform `JSONP` request * * @param {string} url Relative or absolute URL specifying the destination of the request. * Should contain `JSON_CALLBACK` string. * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ createShortMethods('get', 'delete', 'head', 'jsonp'); /** * @ngdoc method * @name ng.$http#post * @methodOf ng.$http * * @description * Shortcut method to perform `POST` request * * @param {string} url Relative or absolute URL specifying the destination of the request * @param {*} data Request content * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ /** * @ngdoc method * @name ng.$http#put * @methodOf ng.$http * * @description * Shortcut method to perform `PUT` request * * @param {string} url Relative or absolute URL specifying the destination of the request * @param {*} data Request content * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ createShortMethodsWithData('post', 'put'); /** * @ngdoc property * @name ng.$http#defaults * @propertyOf ng.$http * * @description * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of * default headers as well as request and response transformations. * * See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above. */ $http.defaults = $config; return $http; function createShortMethods(names) { forEach(arguments, function(name) { $http[name] = function(url, config) { return $http(extend(config || {}, { method: name, url: url })); }; }); } function createShortMethodsWithData(name) { forEach(arguments, function(name) { $http[name] = function(url, data, config) { return $http(extend(config || {}, { method: name, url: url, data: data })); }; }); } /** * Makes the request * * !!! ACCESSES CLOSURE VARS: * $httpBackend, $config, $log, $rootScope, defaultCache, $http.pendingRequests */ function sendReq(config, reqData, reqHeaders) { var deferred = $q.defer(), promise = deferred.promise, cache, cachedResp, url = buildUrl(config.url, config.params); $http.pendingRequests.push(config); promise.then(removePendingReq, removePendingReq); if (config.cache && config.method == 'GET') { cache = isObject(config.cache) ? config.cache : defaultCache; } if (cache) { cachedResp = cache.get(url); if (cachedResp) { if (cachedResp.then) { // cached request has already been sent, but there is no response yet cachedResp.then(removePendingReq, removePendingReq); return cachedResp; } else { // serving from cache if (isArray(cachedResp)) { resolvePromise(cachedResp[1], cachedResp[0], copy(cachedResp[2])); } else { resolvePromise(cachedResp, 200, {}); } } } else { // put the promise for the non-transformed response into cache as a placeholder cache.put(url, promise); } } // if we won't have the response in cache, send the request to the backend if (!cachedResp) { $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout, config.withCredentials); } return promise; /** * Callback registered to $httpBackend(): * - caches the response if desired * - resolves the raw $http promise * - calls $apply */ function done(status, response, headersString) { if (cache) { if (isSuccess(status)) { cache.put(url, [status, response, parseHeaders(headersString)]); } else { // remove promise from the cache cache.remove(url); } } resolvePromise(response, status, headersString); $rootScope.$apply(); } /** * Resolves the raw $http promise. */ function resolvePromise(response, status, headers) { // normalize internal statuses to 0 status = Math.max(status, 0); (isSuccess(status) ? deferred.resolve : deferred.reject)({ data: response, status: status, headers: headersGetter(headers), config: config }); } function removePendingReq() { var idx = indexOf($http.pendingRequests, config); if (idx !== -1) $http.pendingRequests.splice(idx, 1); } } function buildUrl(url, params) { if (!params) return url; var parts = []; forEachSorted(params, function(value, key) { if (value == null || value == undefined) return; if (isObject(value)) { value = toJson(value); } parts.push(encodeURIComponent(key) + '=' + encodeURIComponent(value)); }); return url + ((url.indexOf('?') == -1) ? '?' : '&') + parts.join('&'); } }]; } var XHR = window.XMLHttpRequest || function() { try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch (e1) {} try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch (e2) {} try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e3) {} throw new Error("This browser does not support XMLHttpRequest."); }; /** * @ngdoc object * @name ng.$httpBackend * @requires $browser * @requires $window * @requires $document * * @description * HTTP backend used by the {@link ng.$http service} that delegates to * XMLHttpRequest object or JSONP and deals with browser incompatibilities. * * You should never need to use this service directly, instead use the higher-level abstractions: * {@link ng.$http $http} or {@link ngResource.$resource $resource}. * * During testing this implementation is swapped with {@link ngMock.$httpBackend mock * $httpBackend} which can be trained with responses. */ function $HttpBackendProvider() { this.$get = ['$browser', '$window', '$document', function($browser, $window, $document) { return createHttpBackend($browser, XHR, $browser.defer, $window.angular.callbacks, $document[0], $window.location.protocol.replace(':', '')); }]; } function createHttpBackend($browser, XHR, $browserDefer, callbacks, rawDocument, locationProtocol) { // TODO(vojta): fix the signature return function(method, url, post, callback, headers, timeout, withCredentials) { $browser.$$incOutstandingRequestCount(); url = url || $browser.url(); if (lowercase(method) == 'jsonp') { var callbackId = '_' + (callbacks.counter++).toString(36); callbacks[callbackId] = function(data) { callbacks[callbackId].data = data; }; jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId), function() { if (callbacks[callbackId].data) { completeRequest(callback, 200, callbacks[callbackId].data); } else { completeRequest(callback, -2); } delete callbacks[callbackId]; }); } else { var xhr = new XHR(); xhr.open(method, url, true); forEach(headers, function(value, key) { if (value) xhr.setRequestHeader(key, value); }); var status; // In IE6 and 7, this might be called synchronously when xhr.send below is called and the // response is in the cache. the promise api will ensure that to the app code the api is // always async xhr.onreadystatechange = function() { if (xhr.readyState == 4) { completeRequest( callback, status || xhr.status, xhr.responseText, xhr.getAllResponseHeaders()); } }; if (withCredentials) { xhr.withCredentials = true; } xhr.send(post || ''); if (timeout > 0) { $browserDefer(function() { status = -1; xhr.abort(); }, timeout); } } function completeRequest(callback, status, response, headersString) { // URL_MATCH is defined in src/service/location.js var protocol = (url.match(URL_MATCH) || ['', locationProtocol])[1]; // fix status code for file protocol (it's always 0) status = (protocol == 'file') ? (response ? 200 : 404) : status; // normalize IE bug (http://bugs.jquery.com/ticket/1450) status = status == 1223 ? 204 : status; callback(status, response, headersString); $browser.$$completeOutstandingRequest(noop); } }; function jsonpReq(url, done) { // we can't use jQuery/jqLite here because jQuery does crazy shit with script elements, e.g.: // - fetches local scripts via XHR and evals them // - adds and immediately removes script elements from the document var script = rawDocument.createElement('script'), doneWrapper = function() { rawDocument.body.removeChild(script); if (done) done(); }; script.type = 'text/javascript'; script.src = url; if (msie) { script.onreadystatechange = function() { if (/loaded|complete/.test(script.readyState)) doneWrapper(); }; } else { script.onload = script.onerror = doneWrapper; } rawDocument.body.appendChild(script); } } /** * @ngdoc object * @name ng.$locale * * @description * $locale service provides localization rules for various Angular components. As of right now the * only public api is: * * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`) */ function $LocaleProvider(){ this.$get = function() { return { id: 'en-us', NUMBER_FORMATS: { DECIMAL_SEP: '.', GROUP_SEP: ',', PATTERNS: [ { // Decimal Pattern minInt: 1, minFrac: 0, maxFrac: 3, posPre: '', posSuf: '', negPre: '-', negSuf: '', gSize: 3, lgSize: 3 },{ //Currency Pattern minInt: 1, minFrac: 2, maxFrac: 2, posPre: '\u00A4', posSuf: '', negPre: '(\u00A4', negSuf: ')', gSize: 3, lgSize: 3 } ], CURRENCY_SYM: '$' }, DATETIME_FORMATS: { MONTH: 'January,February,March,April,May,June,July,August,September,October,November,December' .split(','), SHORTMONTH: 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(','), DAY: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(','), SHORTDAY: 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split(','), AMPMS: ['AM','PM'], medium: 'MMM d, y h:mm:ss a', short: 'M/d/yy h:mm a', fullDate: 'EEEE, MMMM d, y', longDate: 'MMMM d, y', mediumDate: 'MMM d, y', shortDate: 'M/d/yy', mediumTime: 'h:mm:ss a', shortTime: 'h:mm a' }, pluralCat: function(num) { if (num === 1) { return 'one'; } return 'other'; } }; }; } function $TimeoutProvider() { this.$get = ['$rootScope', '$browser', '$q', '$exceptionHandler', function($rootScope, $browser, $q, $exceptionHandler) { var deferreds = {}; /** * @ngdoc function * @name ng.$timeout * @requires $browser * * @description * Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch * block and delegates any exceptions to * {@link ng.$exceptionHandler $exceptionHandler} service. * * The return value of registering a timeout function is a promise which will be resolved when * the timeout is reached and the timeout function is executed. * * To cancel a the timeout request, call `$timeout.cancel(promise)`. * * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to * synchronously flush the queue of deferred functions. * * @param {function()} fn A function, who's execution should be delayed. * @param {number=} [delay=0] Delay in milliseconds. * @param {boolean=} [invokeApply=true] If set to false skips model dirty checking, otherwise * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block. * @returns {*} Promise that will be resolved when the timeout is reached. The value this * promise will be resolved with is the return value of the `fn` function. */ function timeout(fn, delay, invokeApply) { var deferred = $q.defer(), promise = deferred.promise, skipApply = (isDefined(invokeApply) && !invokeApply), timeoutId, cleanup; timeoutId = $browser.defer(function() { try { deferred.resolve(fn()); } catch(e) { deferred.reject(e); $exceptionHandler(e); } if (!skipApply) $rootScope.$apply(); }, delay); cleanup = function() { delete deferreds[promise.$$timeoutId]; }; promise.$$timeoutId = timeoutId; deferreds[timeoutId] = deferred; promise.then(cleanup, cleanup); return promise; } /** * @ngdoc function * @name ng.$timeout#cancel * @methodOf ng.$timeout * * @description * Cancels a task associated with the `promise`. As a result of this the promise will be * resolved with a rejection. * * @param {Promise=} promise Promise returned by the `$timeout` function. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully * canceled. */ timeout.cancel = function(promise) { if (promise && promise.$$timeoutId in deferreds) { deferreds[promise.$$timeoutId].reject('canceled'); return $browser.defer.cancel(promise.$$timeoutId); } return false; }; return timeout; }]; } /** * @ngdoc object * @name ng.$filterProvider * @description * * Filters are just functions which transform input to an output. However filters need to be Dependency Injected. To * achieve this a filter definition consists of a factory function which is annotated with dependencies and is * responsible for creating a the filter function. * * <pre> * // Filter registration * function MyModule($provide, $filterProvider) { * // create a service to demonstrate injection (not always needed) * $provide.value('greet', function(name){ * return 'Hello ' + name + '!'; * }); * * // register a filter factory which uses the * // greet service to demonstrate DI. * $filterProvider.register('greet', function(greet){ * // return the filter function which uses the greet service * // to generate salutation * return function(text) { * // filters need to be forgiving so check input validity * return text && greet(text) || text; * }; * }); * } * </pre> * * The filter function is registered with the `$injector` under the filter name suffixe with `Filter`. * <pre> * it('should be the same instance', inject( * function($filterProvider) { * $filterProvider.register('reverse', function(){ * return ...; * }); * }, * function($filter, reverseFilter) { * expect($filter('reverse')).toBe(reverseFilter); * }); * </pre> * * * For more information about how angular filters work, and how to create your own filters, see * {@link guide/dev_guide.templates.filters Understanding Angular Filters} in the angular Developer * Guide. */ /** * @ngdoc method * @name ng.$filterProvider#register * @methodOf ng.$filterProvider * @description * Register filter factory function. * * @param {String} name Name of the filter. * @param {function} fn The filter factory function which is injectable. */ /** * @ngdoc function * @name ng.$filter * @function * @description * Filters are used for formatting data displayed to the user. * * The general syntax in templates is as follows: * * {{ expression | [ filter_name ] }} * * @param {String} name Name of the filter function to retrieve * @return {Function} the filter function */ $FilterProvider.$inject = ['$provide']; function $FilterProvider($provide) { var suffix = 'Filter'; function register(name, factory) { return $provide.factory(name + suffix, factory); } this.register = register; this.$get = ['$injector', function($injector) { return function(name) { return $injector.get(name + suffix); } }]; //////////////////////////////////////// register('currency', currencyFilter); register('date', dateFilter); register('filter', filterFilter); register('json', jsonFilter); register('limitTo', limitToFilter); register('lowercase', lowercaseFilter); register('number', numberFilter); register('orderBy', orderByFilter); register('uppercase', uppercaseFilter); } /** * @ngdoc filter * @name ng.filter:filter * @function * * @description * Selects a subset of items from `array` and returns it as a new array. * * Note: This function is used to augment the `Array` type in Angular expressions. See * {@link ng.$filter} for more information about Angular arrays. * * @param {Array} array The source array. * @param {string|Object|function()} expression The predicate to be used for selecting items from * `array`. * * Can be one of: * * - `string`: Predicate that results in a substring match using the value of `expression` * string. All strings or objects with string properties in `array` that contain this string * will be returned. The predicate can be negated by prefixing the string with `!`. * * - `Object`: A pattern object can be used to filter specific properties on objects contained * by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items * which have property `name` containing "M" and property `phone` containing "1". A special * property name `$` can be used (as in `{$:"text"}`) to accept a match against any * property of the object. That's equivalent to the simple substring match with a `string` * as described above. * * - `function`: A predicate function can be used to write arbitrary filters. The function is * called for each element of `array`. The final result is an array of those elements that * the predicate returned true for. * * @example <doc:example> <doc:source> <div ng-init="friends = [{name:'John', phone:'555-1276'}, {name:'Mary', phone:'800-BIG-MARY'}, {name:'Mike', phone:'555-4321'}, {name:'Adam', phone:'555-5678'}, {name:'Julie', phone:'555-8765'}]"></div> Search: <input ng-model="searchText"> <table id="searchTextResults"> <tr><th>Name</th><th>Phone</th><tr> <tr ng-repeat="friend in friends | filter:searchText"> <td>{{friend.name}}</td> <td>{{friend.phone}}</td> <tr> </table> <hr> Any: <input ng-model="search.$"> <br> Name only <input ng-model="search.name"><br> Phone only <input ng-model="search.phone"å><br> <table id="searchObjResults"> <tr><th>Name</th><th>Phone</th><tr> <tr ng-repeat="friend in friends | filter:search"> <td>{{friend.name}}</td> <td>{{friend.phone}}</td> <tr> </table> </doc:source> <doc:scenario> it('should search across all fields when filtering with a string', function() { input('searchText').enter('m'); expect(repeater('#searchTextResults tr', 'friend in friends').column('friend.name')). toEqual(['Mary', 'Mike', 'Adam']); input('searchText').enter('76'); expect(repeater('#searchTextResults tr', 'friend in friends').column('friend.name')). toEqual(['John', 'Julie']); }); it('should search in specific fields when filtering with a predicate object', function() { input('search.$').enter('i'); expect(repeater('#searchObjResults tr', 'friend in friends').column('friend.name')). toEqual(['Mary', 'Mike', 'Julie']); }); </doc:scenario> </doc:example> */ function filterFilter() { return function(array, expression) { if (!(array instanceof Array)) return array; var predicates = []; predicates.check = function(value) { for (var j = 0; j < predicates.length; j++) { if(!predicates[j](value)) { return false; } } return true; }; var search = function(obj, text){ if (text.charAt(0) === '!') { return !search(obj, text.substr(1)); } switch (typeof obj) { case "boolean": case "number": case "string": return ('' + obj).toLowerCase().indexOf(text) > -1; case "object": for ( var objKey in obj) { if (objKey.charAt(0) !== '$' && search(obj[objKey], text)) { return true; } } return false; case "array": for ( var i = 0; i < obj.length; i++) { if (search(obj[i], text)) { return true; } } return false; default: return false; } }; switch (typeof expression) { case "boolean": case "number": case "string": expression = {$:expression}; case "object": for (var key in expression) { if (key == '$') { (function() { var text = (''+expression[key]).toLowerCase(); if (!text) return; predicates.push(function(value) { return search(value, text); }); })(); } else { (function() { var path = key; var text = (''+expression[key]).toLowerCase(); if (!text) return; predicates.push(function(value) { return search(getter(value, path), text); }); })(); } } break; case 'function': predicates.push(expression); break; default: return array; } var filtered = []; for ( var j = 0; j < array.length; j++) { var value = array[j]; if (predicates.check(value)) { filtered.push(value); } } return filtered; } } /** * @ngdoc filter * @name ng.filter:currency * @function * * @description * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default * symbol for current locale is used. * * @param {number} amount Input to filter. * @param {string=} symbol Currency symbol or identifier to be displayed. * @returns {string} Formatted number. * * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.amount = 1234.56; } </script> <div ng-controller="Ctrl"> <input type="number" ng-model="amount"> <br> default currency symbol ($): {{amount | currency}}<br> custom currency identifier (USD$): {{amount | currency:"USD$"}} </div> </doc:source> <doc:scenario> it('should init with 1234.56', function() { expect(binding('amount | currency')).toBe('$1,234.56'); expect(binding('amount | currency:"USD$"')).toBe('USD$1,234.56'); }); it('should update', function() { input('amount').enter('-1234'); expect(binding('amount | currency')).toBe('($1,234.00)'); expect(binding('amount | currency:"USD$"')).toBe('(USD$1,234.00)'); }); </doc:scenario> </doc:example> */ currencyFilter.$inject = ['$locale']; function currencyFilter($locale) { var formats = $locale.NUMBER_FORMATS; return function(amount, currencySymbol){ if (isUndefined(currencySymbol)) currencySymbol = formats.CURRENCY_SYM; return formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, 2). replace(/\u00A4/g, currencySymbol); }; } /** * @ngdoc filter * @name ng.filter:number * @function * * @description * Formats a number as text. * * If the input is not a number an empty string is returned. * * @param {number|string} number Number to format. * @param {(number|string)=} [fractionSize=2] Number of decimal places to round the number to. * @returns {string} Number rounded to decimalPlaces and places a “,” after each third digit. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.val = 1234.56789; } </script> <div ng-controller="Ctrl"> Enter number: <input ng-model='val'><br> Default formatting: {{val | number}}<br> No fractions: {{val | number:0}}<br> Negative number: {{-val | number:4}} </div> </doc:source> <doc:scenario> it('should format numbers', function() { expect(binding('val | number')).toBe('1,234.568'); expect(binding('val | number:0')).toBe('1,235'); expect(binding('-val | number:4')).toBe('-1,234.5679'); }); it('should update', function() { input('val').enter('3374.333'); expect(binding('val | number')).toBe('3,374.333'); expect(binding('val | number:0')).toBe('3,374'); expect(binding('-val | number:4')).toBe('-3,374.3330'); }); </doc:scenario> </doc:example> */ numberFilter.$inject = ['$locale']; function numberFilter($locale) { var formats = $locale.NUMBER_FORMATS; return function(number, fractionSize) { return formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP, fractionSize); }; } var DECIMAL_SEP = '.'; function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) { if (isNaN(number) || !isFinite(number)) return ''; var isNegative = number < 0; number = Math.abs(number); var numStr = number + '', formatedText = '', parts = []; if (numStr.indexOf('e') !== -1) { formatedText = numStr; } else { var fractionLen = (numStr.split(DECIMAL_SEP)[1] || '').length; // determine fractionSize if it is not specified if (isUndefined(fractionSize)) { fractionSize = Math.min(Math.max(pattern.minFrac, fractionLen), pattern.maxFrac); } var pow = Math.pow(10, fractionSize); number = Math.round(number * pow) / pow; var fraction = ('' + number).split(DECIMAL_SEP); var whole = fraction[0]; fraction = fraction[1] || ''; var pos = 0, lgroup = pattern.lgSize, group = pattern.gSize; if (whole.length >= (lgroup + group)) { pos = whole.length - lgroup; for (var i = 0; i < pos; i++) { if ((pos - i)%group === 0 && i !== 0) { formatedText += groupSep; } formatedText += whole.charAt(i); } } for (i = pos; i < whole.length; i++) { if ((whole.length - i)%lgroup === 0 && i !== 0) { formatedText += groupSep; } formatedText += whole.charAt(i); } // format fraction part. while(fraction.length < fractionSize) { fraction += '0'; } if (fractionSize) formatedText += decimalSep + fraction.substr(0, fractionSize); } parts.push(isNegative ? pattern.negPre : pattern.posPre); parts.push(formatedText); parts.push(isNegative ? pattern.negSuf : pattern.posSuf); return parts.join(''); } function padNumber(num, digits, trim) { var neg = ''; if (num < 0) { neg = '-'; num = -num; } num = '' + num; while(num.length < digits) num = '0' + num; if (trim) num = num.substr(num.length - digits); return neg + num; } function dateGetter(name, size, offset, trim) { return function(date) { var value = date['get' + name](); if (offset > 0 || value > -offset) value += offset; if (value === 0 && offset == -12 ) value = 12; return padNumber(value, size, trim); }; } function dateStrGetter(name, shortForm) { return function(date, formats) { var value = date['get' + name](); var get = uppercase(shortForm ? ('SHORT' + name) : name); return formats[get][value]; }; } function timeZoneGetter(date) { var offset = date.getTimezoneOffset(); return padNumber(offset / 60, 2) + padNumber(Math.abs(offset % 60), 2); } function ampmGetter(date, formats) { return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1]; } var DATE_FORMATS = { yyyy: dateGetter('FullYear', 4), yy: dateGetter('FullYear', 2, 0, true), y: dateGetter('FullYear', 1), MMMM: dateStrGetter('Month'), MMM: dateStrGetter('Month', true), MM: dateGetter('Month', 2, 1), M: dateGetter('Month', 1, 1), dd: dateGetter('Date', 2), d: dateGetter('Date', 1), HH: dateGetter('Hours', 2), H: dateGetter('Hours', 1), hh: dateGetter('Hours', 2, -12), h: dateGetter('Hours', 1, -12), mm: dateGetter('Minutes', 2), m: dateGetter('Minutes', 1), ss: dateGetter('Seconds', 2), s: dateGetter('Seconds', 1), EEEE: dateStrGetter('Day'), EEE: dateStrGetter('Day', true), a: ampmGetter, Z: timeZoneGetter }; var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZE']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z))(.*)/, NUMBER_STRING = /^\d+$/; /** * @ngdoc filter * @name ng.filter:date * @function * * @description * Formats `date` to a string based on the requested `format`. * * `format` string can be composed of the following elements: * * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010) * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10) * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199) * * `'MMMM'`: Month in year (January-December) * * `'MMM'`: Month in year (Jan-Dec) * * `'MM'`: Month in year, padded (01-12) * * `'M'`: Month in year (1-12) * * `'dd'`: Day in month, padded (01-31) * * `'d'`: Day in month (1-31) * * `'EEEE'`: Day in Week,(Sunday-Saturday) * * `'EEE'`: Day in Week, (Sun-Sat) * * `'HH'`: Hour in day, padded (00-23) * * `'H'`: Hour in day (0-23) * * `'hh'`: Hour in am/pm, padded (01-12) * * `'h'`: Hour in am/pm, (1-12) * * `'mm'`: Minute in hour, padded (00-59) * * `'m'`: Minute in hour (0-59) * * `'ss'`: Second in minute, padded (00-59) * * `'s'`: Second in minute (0-59) * * `'a'`: am/pm marker * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-1200) * * `format` string can also be one of the following predefined * {@link guide/i18n localizable formats}: * * * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale * (e.g. Sep 3, 2010 12:05:08 pm) * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 pm) * * `'fullDate'`: equivalent to `'EEEE, MMMM d,y'` for en_US locale * (e.g. Friday, September 3, 2010) * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010 * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010) * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10) * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 pm) * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 pm) * * `format` string can contain literal values. These need to be quoted with single quotes (e.g. * `"h 'in the morning'"`). In order to output single quote, use two single quotes in a sequence * (e.g. `"h o''clock"`). * * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.SSSZ and it's * shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). * @param {string=} format Formatting rules (see Description). If not specified, * `mediumDate` is used. * @returns {string} Formatted string or the input if input is not recognized as date/millis. * * @example <doc:example> <doc:source> <span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>: {{1288323623006 | date:'medium'}}<br> <span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>: {{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}<br> <span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>: {{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}<br> </doc:source> <doc:scenario> it('should format date', function() { expect(binding("1288323623006 | date:'medium'")). toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/); expect(binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")). toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} \-?\d{4}/); expect(binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")). toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/); }); </doc:scenario> </doc:example> */ dateFilter.$inject = ['$locale']; function dateFilter($locale) { var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d{3}))?)?)?(Z|([+-])(\d\d):?(\d\d)))?$/; function jsonStringToDate(string){ var match; if (match = string.match(R_ISO8601_STR)) { var date = new Date(0), tzHour = 0, tzMin = 0; if (match[9]) { tzHour = int(match[9] + match[10]); tzMin = int(match[9] + match[11]); } date.setUTCFullYear(int(match[1]), int(match[2]) - 1, int(match[3])); date.setUTCHours(int(match[4]||0) - tzHour, int(match[5]||0) - tzMin, int(match[6]||0), int(match[7]||0)); return date; } return string; } return function(date, format) { var text = '', parts = [], fn, match; format = format || 'mediumDate'; format = $locale.DATETIME_FORMATS[format] || format; if (isString(date)) { if (NUMBER_STRING.test(date)) { date = int(date); } else { date = jsonStringToDate(date); } } if (isNumber(date)) { date = new Date(date); } if (!isDate(date)) { return date; } while(format) { match = DATE_FORMATS_SPLIT.exec(format); if (match) { parts = concat(parts, match, 1); format = parts.pop(); } else { parts.push(format); format = null; } } forEach(parts, function(value){ fn = DATE_FORMATS[value]; text += fn ? fn(date, $locale.DATETIME_FORMATS) : value.replace(/(^'|'$)/g, '').replace(/''/g, "'"); }); return text; }; } /** * @ngdoc filter * @name ng.filter:json * @function * * @description * Allows you to convert a JavaScript object into JSON string. * * This filter is mostly useful for debugging. When using the double curly {{value}} notation * the binding is automatically converted to JSON. * * @param {*} object Any JavaScript object (including arrays and primitive types) to filter. * @returns {string} JSON string. * * * @example: <doc:example> <doc:source> <pre>{{ {'name':'value'} | json }}</pre> </doc:source> <doc:scenario> it('should jsonify filtered objects', function() { expect(binding("{'name':'value'}")).toMatch(/\{\n "name": ?"value"\n}/); }); </doc:scenario> </doc:example> * */ function jsonFilter() { return function(object) { return toJson(object, true); }; } /** * @ngdoc filter * @name ng.filter:lowercase * @function * @description * Converts string to lowercase. * @see angular.lowercase */ var lowercaseFilter = valueFn(lowercase); /** * @ngdoc filter * @name ng.filter:uppercase * @function * @description * Converts string to uppercase. * @see angular.uppercase */ var uppercaseFilter = valueFn(uppercase); /** * @ngdoc function * @name ng.filter:limitTo * @function * * @description * Creates a new array containing only a specified number of elements in an array. The elements * are taken from either the beginning or the end of the source array, as specified by the * value and sign (positive or negative) of `limit`. * * Note: This function is used to augment the `Array` type in Angular expressions. See * {@link ng.$filter} for more information about Angular arrays. * * @param {Array} array Source array to be limited. * @param {string|Number} limit The length of the returned array. If the `limit` number is * positive, `limit` number of items from the beginning of the source array are copied. * If the number is negative, `limit` number of items from the end of the source array are * copied. The `limit` will be trimmed if it exceeds `array.length` * @returns {Array} A new sub-array of length `limit` or less if input array had less than `limit` * elements. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.numbers = [1,2,3,4,5,6,7,8,9]; $scope.limit = 3; } </script> <div ng-controller="Ctrl"> Limit {{numbers}} to: <input type="integer" ng-model="limit"> <p>Output: {{ numbers | limitTo:limit }}</p> </div> </doc:source> <doc:scenario> it('should limit the numer array to first three items', function() { expect(element('.doc-example-live input[ng-model=limit]').val()).toBe('3'); expect(binding('numbers | limitTo:limit')).toEqual('[1,2,3]'); }); it('should update the output when -3 is entered', function() { input('limit').enter(-3); expect(binding('numbers | limitTo:limit')).toEqual('[7,8,9]'); }); it('should not exceed the maximum size of input array', function() { input('limit').enter(100); expect(binding('numbers | limitTo:limit')).toEqual('[1,2,3,4,5,6,7,8,9]'); }); </doc:scenario> </doc:example> */ function limitToFilter(){ return function(array, limit) { if (!(array instanceof Array)) return array; limit = int(limit); var out = [], i, n; // check that array is iterable if (!array || !(array instanceof Array)) return out; // if abs(limit) exceeds maximum length, trim it if (limit > array.length) limit = array.length; else if (limit < -array.length) limit = -array.length; if (limit > 0) { i = 0; n = limit; } else { i = array.length + limit; n = array.length; } for (; i<n; i++) { out.push(array[i]); } return out; } } /** * @ngdoc function * @name ng.filter:orderBy * @function * * @description * Orders a specified `array` by the `expression` predicate. * * Note: this function is used to augment the `Array` type in Angular expressions. See * {@link ng.$filter} for more informaton about Angular arrays. * * @param {Array} array The array to sort. * @param {function(*)|string|Array.<(function(*)|string)>} expression A predicate to be * used by the comparator to determine the order of elements. * * Can be one of: * * - `function`: Getter function. The result of this function will be sorted using the * `<`, `=`, `>` operator. * - `string`: An Angular expression which evaluates to an object to order by, such as 'name' * to sort by a property called 'name'. Optionally prefixed with `+` or `-` to control * ascending or descending sort order (for example, +name or -name). * - `Array`: An array of function or string predicates. The first predicate in the array * is used for sorting, but when two items are equivalent, the next predicate is used. * * @param {boolean=} reverse Reverse the order the array. * @returns {Array} Sorted copy of the source array. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.friends = [{name:'John', phone:'555-1212', age:10}, {name:'Mary', phone:'555-9876', age:19}, {name:'Mike', phone:'555-4321', age:21}, {name:'Adam', phone:'555-5678', age:35}, {name:'Julie', phone:'555-8765', age:29}] $scope.predicate = '-age'; } </script> <div ng-controller="Ctrl"> <pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre> <hr/> [ <a href="" ng-click="predicate=''">unsorted</a> ] <table class="friend"> <tr> <th><a href="" ng-click="predicate = 'name'; reverse=false">Name</a> (<a href ng-click="predicate = '-name'; reverse=false">^</a>)</th> <th><a href="" ng-click="predicate = 'phone'; reverse=!reverse">Phone Number</a></th> <th><a href="" ng-click="predicate = 'age'; reverse=!reverse">Age</a></th> <tr> <tr ng-repeat="friend in friends | orderBy:predicate:reverse"> <td>{{friend.name}}</td> <td>{{friend.phone}}</td> <td>{{friend.age}}</td> <tr> </table> </div> </doc:source> <doc:scenario> it('should be reverse ordered by aged', function() { expect(binding('predicate')).toBe('-age'); expect(repeater('table.friend', 'friend in friends').column('friend.age')). toEqual(['35', '29', '21', '19', '10']); expect(repeater('table.friend', 'friend in friends').column('friend.name')). toEqual(['Adam', 'Julie', 'Mike', 'Mary', 'John']); }); it('should reorder the table when user selects different predicate', function() { element('.doc-example-live a:contains("Name")').click(); expect(repeater('table.friend', 'friend in friends').column('friend.name')). toEqual(['Adam', 'John', 'Julie', 'Mary', 'Mike']); expect(repeater('table.friend', 'friend in friends').column('friend.age')). toEqual(['35', '10', '29', '19', '21']); element('.doc-example-live a:contains("Phone")').click(); expect(repeater('table.friend', 'friend in friends').column('friend.phone')). toEqual(['555-9876', '555-8765', '555-5678', '555-4321', '555-1212']); expect(repeater('table.friend', 'friend in friends').column('friend.name')). toEqual(['Mary', 'Julie', 'Adam', 'Mike', 'John']); }); </doc:scenario> </doc:example> */ orderByFilter.$inject = ['$parse']; function orderByFilter($parse){ return function(array, sortPredicate, reverseOrder) { if (!(array instanceof Array)) return array; if (!sortPredicate) return array; sortPredicate = isArray(sortPredicate) ? sortPredicate: [sortPredicate]; sortPredicate = map(sortPredicate, function(predicate){ var descending = false, get = predicate || identity; if (isString(predicate)) { if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) { descending = predicate.charAt(0) == '-'; predicate = predicate.substring(1); } get = $parse(predicate); } return reverseComparator(function(a,b){ return compare(get(a),get(b)); }, descending); }); var arrayCopy = []; for ( var i = 0; i < array.length; i++) { arrayCopy.push(array[i]); } return arrayCopy.sort(reverseComparator(comparator, reverseOrder)); function comparator(o1, o2){ for ( var i = 0; i < sortPredicate.length; i++) { var comp = sortPredicate[i](o1, o2); if (comp !== 0) return comp; } return 0; } function reverseComparator(comp, descending) { return toBoolean(descending) ? function(a,b){return comp(b,a);} : comp; } function compare(v1, v2){ var t1 = typeof v1; var t2 = typeof v2; if (t1 == t2) { if (t1 == "string") v1 = v1.toLowerCase(); if (t1 == "string") v2 = v2.toLowerCase(); if (v1 === v2) return 0; return v1 < v2 ? -1 : 1; } else { return t1 < t2 ? -1 : 1; } } } } function ngDirective(directive) { if (isFunction(directive)) { directive = { link: directive } } directive.restrict = directive.restrict || 'AC'; return valueFn(directive); } /** * @ngdoc directive * @name ng.directive:a * @restrict E * * @description * Modifies the default behavior of html A tag, so that the default action is prevented when href * attribute is empty. * * The reasoning for this change is to allow easy creation of action links with `ngClick` directive * without changing the location or causing page reloads, e.g.: * <a href="" ng-click="model.$save()">Save</a> */ var htmlAnchorDirective = valueFn({ restrict: 'E', compile: function(element, attr) { // turn <a href ng-click="..">link</a> into a link in IE // but only if it doesn't have name attribute, in which case it's an anchor if (!attr.href) { attr.$set('href', ''); } return function(scope, element) { element.bind('click', function(event){ // if we have no href url, then don't navigate anywhere. if (!element.attr('href')) { event.preventDefault(); } }); } } }); /** * @ngdoc directive * @name ng.directive:ngHref * @restrict A * * @description * Using Angular markup like {{hash}} in an href attribute makes * the page open to a wrong URL, if the user clicks that link before * angular has a chance to replace the {{hash}} with actual URL, the * link will be broken and will most likely return a 404 error. * The `ngHref` directive solves this problem. * * The buggy way to write it: * <pre> * <a href="http://www.gravatar.com/avatar/{{hash}}"/> * </pre> * * The correct way to write it: * <pre> * <a ng-href="http://www.gravatar.com/avatar/{{hash}}"/> * </pre> * * @element A * @param {template} ngHref any string which can contain `{{}}` markup. * * @example * This example uses `link` variable inside `href` attribute: <doc:example> <doc:source> <input ng-model="value" /><br /> <a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br /> <a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br /> <a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, reload!)<br /> <a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br /> <a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br /> <a id="link-6" ng-href="{{value}}">link</a> (link, change location) </doc:source> <doc:scenario> it('should execute ng-click but not reload when href without value', function() { element('#link-1').click(); expect(input('value').val()).toEqual('1'); expect(element('#link-1').attr('href')).toBe(""); }); it('should execute ng-click but not reload when href empty string', function() { element('#link-2').click(); expect(input('value').val()).toEqual('2'); expect(element('#link-2').attr('href')).toBe(""); }); it('should execute ng-click and change url when ng-href specified', function() { expect(element('#link-3').attr('href')).toBe("/123"); element('#link-3').click(); expect(browser().window().path()).toEqual('/123'); }); it('should execute ng-click but not reload when href empty string and name specified', function() { element('#link-4').click(); expect(input('value').val()).toEqual('4'); expect(element('#link-4').attr('href')).toBe(''); }); it('should execute ng-click but not reload when no href but name specified', function() { element('#link-5').click(); expect(input('value').val()).toEqual('5'); expect(element('#link-5').attr('href')).toBe(''); }); it('should only change url when only ng-href', function() { input('value').enter('6'); expect(element('#link-6').attr('href')).toBe('6'); element('#link-6').click(); expect(browser().location().url()).toEqual('/6'); }); </doc:scenario> </doc:example> */ /** * @ngdoc directive * @name ng.directive:ngSrc * @restrict A * * @description * Using Angular markup like `{{hash}}` in a `src` attribute doesn't * work right: The browser will fetch from the URL with the literal * text `{{hash}}` until Angular replaces the expression inside * `{{hash}}`. The `ngSrc` directive solves this problem. * * The buggy way to write it: * <pre> * <img src="http://www.gravatar.com/avatar/{{hash}}"/> * </pre> * * The correct way to write it: * <pre> * <img ng-src="http://www.gravatar.com/avatar/{{hash}}"/> * </pre> * * @element IMG * @param {template} ngSrc any string which can contain `{{}}` markup. */ /** * @ngdoc directive * @name ng.directive:ngDisabled * @restrict A * * @description * * The following markup will make the button enabled on Chrome/Firefox but not on IE8 and older IEs: * <pre> * <div ng-init="scope = { isDisabled: false }"> * <button disabled="{{scope.isDisabled}}">Disabled</button> * </div> * </pre> * * The HTML specs do not require browsers to preserve the special attributes such as disabled. * (The presence of them means true and absence means false) * This prevents the angular compiler from correctly retrieving the binding expression. * To solve this problem, we introduce the `ngDisabled` directive. * * @example <doc:example> <doc:source> Click me to toggle: <input type="checkbox" ng-model="checked"><br/> <button ng-model="button" ng-disabled="checked">Button</button> </doc:source> <doc:scenario> it('should toggle button', function() { expect(element('.doc-example-live :button').prop('disabled')).toBeFalsy(); input('checked').check(); expect(element('.doc-example-live :button').prop('disabled')).toBeTruthy(); }); </doc:scenario> </doc:example> * * @element INPUT * @param {expression} ngDisabled Angular expression that will be evaluated. */ /** * @ngdoc directive * @name ng.directive:ngChecked * @restrict A * * @description * The HTML specs do not require browsers to preserve the special attributes such as checked. * (The presence of them means true and absence means false) * This prevents the angular compiler from correctly retrieving the binding expression. * To solve this problem, we introduce the `ngChecked` directive. * @example <doc:example> <doc:source> Check me to check both: <input type="checkbox" ng-model="master"><br/> <input id="checkSlave" type="checkbox" ng-checked="master"> </doc:source> <doc:scenario> it('should check both checkBoxes', function() { expect(element('.doc-example-live #checkSlave').prop('checked')).toBeFalsy(); input('master').check(); expect(element('.doc-example-live #checkSlave').prop('checked')).toBeTruthy(); }); </doc:scenario> </doc:example> * * @element INPUT * @param {expression} ngChecked Angular expression that will be evaluated. */ /** * @ngdoc directive * @name ng.directive:ngMultiple * @restrict A * * @description * The HTML specs do not require browsers to preserve the special attributes such as multiple. * (The presence of them means true and absence means false) * This prevents the angular compiler from correctly retrieving the binding expression. * To solve this problem, we introduce the `ngMultiple` directive. * * @example <doc:example> <doc:source> Check me check multiple: <input type="checkbox" ng-model="checked"><br/> <select id="select" ng-multiple="checked"> <option>Misko</option> <option>Igor</option> <option>Vojta</option> <option>Di</option> </select> </doc:source> <doc:scenario> it('should toggle multiple', function() { expect(element('.doc-example-live #select').prop('multiple')).toBeFalsy(); input('checked').check(); expect(element('.doc-example-live #select').prop('multiple')).toBeTruthy(); }); </doc:scenario> </doc:example> * * @element SELECT * @param {expression} ngMultiple Angular expression that will be evaluated. */ /** * @ngdoc directive * @name ng.directive:ngReadonly * @restrict A * * @description * The HTML specs do not require browsers to preserve the special attributes such as readonly. * (The presence of them means true and absence means false) * This prevents the angular compiler from correctly retrieving the binding expression. * To solve this problem, we introduce the `ngReadonly` directive. * @example <doc:example> <doc:source> Check me to make text readonly: <input type="checkbox" ng-model="checked"><br/> <input type="text" ng-readonly="checked" value="I'm Angular"/> </doc:source> <doc:scenario> it('should toggle readonly attr', function() { expect(element('.doc-example-live :text').prop('readonly')).toBeFalsy(); input('checked').check(); expect(element('.doc-example-live :text').prop('readonly')).toBeTruthy(); }); </doc:scenario> </doc:example> * * @element INPUT * @param {string} expression Angular expression that will be evaluated. */ /** * @ngdoc directive * @name ng.directive:ngSelected * @restrict A * * @description * The HTML specs do not require browsers to preserve the special attributes such as selected. * (The presence of them means true and absence means false) * This prevents the angular compiler from correctly retrieving the binding expression. * To solve this problem, we introduced the `ngSelected` directive. * @example <doc:example> <doc:source> Check me to select: <input type="checkbox" ng-model="selected"><br/> <select> <option>Hello!</option> <option id="greet" ng-selected="selected">Greetings!</option> </select> </doc:source> <doc:scenario> it('should select Greetings!', function() { expect(element('.doc-example-live #greet').prop('selected')).toBeFalsy(); input('selected').check(); expect(element('.doc-example-live #greet').prop('selected')).toBeTruthy(); }); </doc:scenario> </doc:example> * * @element OPTION * @param {string} expression Angular expression that will be evaluated. */ var ngAttributeAliasDirectives = {}; // boolean attrs are evaluated forEach(BOOLEAN_ATTR, function(propName, attrName) { var normalized = directiveNormalize('ng-' + attrName); ngAttributeAliasDirectives[normalized] = function() { return { priority: 100, compile: function() { return function(scope, element, attr) { scope.$watch(attr[normalized], function(value) { attr.$set(attrName, !!value); }); }; } }; }; }); // ng-src, ng-href are interpolated forEach(['src', 'href'], function(attrName) { var normalized = directiveNormalize('ng-' + attrName); ngAttributeAliasDirectives[normalized] = function() { return { priority: 99, // it needs to run after the attributes are interpolated link: function(scope, element, attr) { attr.$observe(normalized, function(value) { attr.$set(attrName, value); // on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need // to set the property as well to achieve the desired effect if (msie) element.prop(attrName, value); }); } }; }; }); var nullFormCtrl = { $addControl: noop, $removeControl: noop, $setValidity: noop, $setDirty: noop }; /** * @ngdoc object * @name ng.directive:form.FormController * * @property {boolean} $pristine True if user has not interacted with the form yet. * @property {boolean} $dirty True if user has already interacted with the form. * @property {boolean} $valid True if all of the containg forms and controls are valid. * @property {boolean} $invalid True if at least one containing control or form is invalid. * * @property {Object} $error Is an object hash, containing references to all invalid controls or * forms, where: * * - keys are validation tokens (error names) — such as `REQUIRED`, `URL` or `EMAIL`), * - values are arrays of controls or forms that are invalid with given error. * * @description * `FormController` keeps track of all its controls and nested forms as well as state of them, * such as being valid/invalid or dirty/pristine. * * Each {@link ng.directive:form form} directive creates an instance * of `FormController`. * */ //asks for $scope to fool the BC controller module FormController.$inject = ['$element', '$attrs', '$scope']; function FormController(element, attrs) { var form = this, parentForm = element.parent().controller('form') || nullFormCtrl, invalidCount = 0, // used to easily determine if we are valid errors = form.$error = {}; // init state form.$name = attrs.name; form.$dirty = false; form.$pristine = true; form.$valid = true; form.$invalid = false; parentForm.$addControl(form); // Setup initial state of the control element.addClass(PRISTINE_CLASS); toggleValidCss(true); // convenience method for easy toggling of classes function toggleValidCss(isValid, validationErrorKey) { validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : ''; element. removeClass((isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey). addClass((isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey); } form.$addControl = function(control) { if (control.$name && !form.hasOwnProperty(control.$name)) { form[control.$name] = control; } }; form.$removeControl = function(control) { if (control.$name && form[control.$name] === control) { delete form[control.$name]; } forEach(errors, function(queue, validationToken) { form.$setValidity(validationToken, true, control); }); }; form.$setValidity = function(validationToken, isValid, control) { var queue = errors[validationToken]; if (isValid) { if (queue) { arrayRemove(queue, control); if (!queue.length) { invalidCount--; if (!invalidCount) { toggleValidCss(isValid); form.$valid = true; form.$invalid = false; } errors[validationToken] = false; toggleValidCss(true, validationToken); parentForm.$setValidity(validationToken, true, form); } } } else { if (!invalidCount) { toggleValidCss(isValid); } if (queue) { if (includes(queue, control)) return; } else { errors[validationToken] = queue = []; invalidCount++; toggleValidCss(false, validationToken); parentForm.$setValidity(validationToken, false, form); } queue.push(control); form.$valid = false; form.$invalid = true; } }; form.$setDirty = function() { element.removeClass(PRISTINE_CLASS).addClass(DIRTY_CLASS); form.$dirty = true; form.$pristine = false; }; } /** * @ngdoc directive * @name ng.directive:ngForm * @restrict EAC * * @description * Nestable alias of {@link ng.directive:form `form`} directive. HTML * does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a * sub-group of controls needs to be determined. * * @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into * related scope, under this name. * */ /** * @ngdoc directive * @name ng.directive:form * @restrict E * * @description * Directive that instantiates * {@link ng.directive:form.FormController FormController}. * * If `name` attribute is specified, the form controller is published onto the current scope under * this name. * * # Alias: {@link ng.directive:ngForm `ngForm`} * * In angular forms can be nested. This means that the outer form is valid when all of the child * forms are valid as well. However browsers do not allow nesting of `<form>` elements, for this * reason angular provides {@link ng.directive:ngForm `ngForm`} alias * which behaves identical to `<form>` but allows form nesting. * * * # CSS classes * - `ng-valid` Is set if the form is valid. * - `ng-invalid` Is set if the form is invalid. * - `ng-pristine` Is set if the form is pristine. * - `ng-dirty` Is set if the form is dirty. * * * # Submitting a form and preventing default action * * Since the role of forms in client-side Angular applications is different than in classical * roundtrip apps, it is desirable for the browser not to translate the form submission into a full * page reload that sends the data to the server. Instead some javascript logic should be triggered * to handle the form submission in application specific way. * * For this reason, Angular prevents the default action (form submission to the server) unless the * `<form>` element has an `action` attribute specified. * * You can use one of the following two ways to specify what javascript method should be called when * a form is submitted: * * - {@link ng.directive:ngSubmit ngSubmit} directive on the form element * - {@link ng.directive:ngClick ngClick} directive on the first * button or input field of type submit (input[type=submit]) * * To prevent double execution of the handler, use only one of ngSubmit or ngClick directives. This * is because of the following form submission rules coming from the html spec: * * - If a form has only one input field then hitting enter in this field triggers form submit * (`ngSubmit`) * - if a form has has 2+ input fields and no buttons or input[type=submit] then hitting enter * doesn't trigger submit * - if a form has one or more input fields and one or more buttons or input[type=submit] then * hitting enter in any of the input fields will trigger the click handler on the *first* button or * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`) * * @param {string=} name Name of the form. If specified, the form controller will be published into * related scope, under this name. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.userType = 'guest'; } </script> <form name="myForm" ng-controller="Ctrl"> userType: <input name="input" ng-model="userType" required> <span class="error" ng-show="myForm.input.$error.REQUIRED">Required!</span><br> <tt>userType = {{userType}}</tt><br> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br> <tt>myForm.$valid = {{myForm.$valid}}</tt><br> <tt>myForm.$error.REQUIRED = {{!!myForm.$error.REQUIRED}}</tt><br> </form> </doc:source> <doc:scenario> it('should initialize to model', function() { expect(binding('userType')).toEqual('guest'); expect(binding('myForm.input.$valid')).toEqual('true'); }); it('should be invalid if empty', function() { input('userType').enter(''); expect(binding('userType')).toEqual(''); expect(binding('myForm.input.$valid')).toEqual('false'); }); </doc:scenario> </doc:example> */ var formDirectiveFactory = function(isNgForm) { return ['$timeout', function($timeout) { var formDirective = { name: 'form', restrict: 'E', controller: FormController, compile: function() { return { pre: function(scope, formElement, attr, controller) { if (!attr.action) { // we can't use jq events because if a form is destroyed during submission the default // action is not prevented. see #1238 // // IE 9 is not affected because it doesn't fire a submit event and try to do a full // page reload if the form was destroyed by submission of the form via a click handler // on a button in the form. Looks like an IE9 specific bug. var preventDefaultListener = function(event) { event.preventDefault ? event.preventDefault() : event.returnValue = false; // IE }; addEventListenerFn(formElement[0], 'submit', preventDefaultListener); // unregister the preventDefault listener so that we don't not leak memory but in a // way that will achieve the prevention of the default action. formElement.bind('$destroy', function() { $timeout(function() { removeEventListenerFn(formElement[0], 'submit', preventDefaultListener); }, 0, false); }); } var parentFormCtrl = formElement.parent().controller('form'), alias = attr.name || attr.ngForm; if (alias) { scope[alias] = controller; } if (parentFormCtrl) { formElement.bind('$destroy', function() { parentFormCtrl.$removeControl(controller); if (alias) { scope[alias] = undefined; } extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards }); } } }; } }; return isNgForm ? extend(copy(formDirective), {restrict: 'EAC'}) : formDirective; }]; }; var formDirective = formDirectiveFactory(); var ngFormDirective = formDirectiveFactory(true); var URL_REGEXP = /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/; var EMAIL_REGEXP = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/; var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))\s*$/; var inputType = { /** * @ngdoc inputType * @name ng.directive:input.text * * @description * Standard HTML text input with angular data binding. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} required Sets `required` validation error key if the value is not entered. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than * minlength. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than * maxlength. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for * patterns defined as scope expressions. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.text = 'guest'; $scope.word = /^\w*$/; } </script> <form name="myForm" ng-controller="Ctrl"> Single word: <input type="text" name="input" ng-model="text" ng-pattern="word" required> <span class="error" ng-show="myForm.input.$error.required"> Required!</span> <span class="error" ng-show="myForm.input.$error.pattern"> Single word only!</span> <tt>text = {{text}}</tt><br/> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> </form> </doc:source> <doc:scenario> it('should initialize to model', function() { expect(binding('text')).toEqual('guest'); expect(binding('myForm.input.$valid')).toEqual('true'); }); it('should be invalid if empty', function() { input('text').enter(''); expect(binding('text')).toEqual(''); expect(binding('myForm.input.$valid')).toEqual('false'); }); it('should be invalid if multi word', function() { input('text').enter('hello world'); expect(binding('myForm.input.$valid')).toEqual('false'); }); </doc:scenario> </doc:example> */ 'text': textInputType, /** * @ngdoc inputType * @name ng.directive:input.number * * @description * Text input with number validation and transformation. Sets the `number` validation * error if not a valid number. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} min Sets the `min` validation error key if the value entered is less then `min`. * @param {string=} max Sets the `max` validation error key if the value entered is greater then `min`. * @param {string=} required Sets `required` validation error key if the value is not entered. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than * minlength. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than * maxlength. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for * patterns defined as scope expressions. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.value = 12; } </script> <form name="myForm" ng-controller="Ctrl"> Number: <input type="number" name="input" ng-model="value" min="0" max="99" required> <span class="error" ng-show="myForm.list.$error.required"> Required!</span> <span class="error" ng-show="myForm.list.$error.number"> Not valid number!</span> <tt>value = {{value}}</tt><br/> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> </form> </doc:source> <doc:scenario> it('should initialize to model', function() { expect(binding('value')).toEqual('12'); expect(binding('myForm.input.$valid')).toEqual('true'); }); it('should be invalid if empty', function() { input('value').enter(''); expect(binding('value')).toEqual(''); expect(binding('myForm.input.$valid')).toEqual('false'); }); it('should be invalid if over max', function() { input('value').enter('123'); expect(binding('value')).toEqual(''); expect(binding('myForm.input.$valid')).toEqual('false'); }); </doc:scenario> </doc:example> */ 'number': numberInputType, /** * @ngdoc inputType * @name ng.directive:input.url * * @description * Text input with URL validation. Sets the `url` validation error key if the content is not a * valid URL. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} required Sets `required` validation error key if the value is not entered. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than * minlength. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than * maxlength. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for * patterns defined as scope expressions. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.text = 'http://google.com'; } </script> <form name="myForm" ng-controller="Ctrl"> URL: <input type="url" name="input" ng-model="text" required> <span class="error" ng-show="myForm.input.$error.required"> Required!</span> <span class="error" ng-show="myForm.input.$error.url"> Not valid url!</span> <tt>text = {{text}}</tt><br/> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> <tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/> </form> </doc:source> <doc:scenario> it('should initialize to model', function() { expect(binding('text')).toEqual('http://google.com'); expect(binding('myForm.input.$valid')).toEqual('true'); }); it('should be invalid if empty', function() { input('text').enter(''); expect(binding('text')).toEqual(''); expect(binding('myForm.input.$valid')).toEqual('false'); }); it('should be invalid if not url', function() { input('text').enter('xxx'); expect(binding('myForm.input.$valid')).toEqual('false'); }); </doc:scenario> </doc:example> */ 'url': urlInputType, /** * @ngdoc inputType * @name ng.directive:input.email * * @description * Text input with email validation. Sets the `email` validation error key if not a valid email * address. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} required Sets `required` validation error key if the value is not entered. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than * minlength. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than * maxlength. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for * patterns defined as scope expressions. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.text = '[email protected]'; } </script> <form name="myForm" ng-controller="Ctrl"> Email: <input type="email" name="input" ng-model="text" required> <span class="error" ng-show="myForm.input.$error.required"> Required!</span> <span class="error" ng-show="myForm.input.$error.email"> Not valid email!</span> <tt>text = {{text}}</tt><br/> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> <tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/> </form> </doc:source> <doc:scenario> it('should initialize to model', function() { expect(binding('text')).toEqual('[email protected]'); expect(binding('myForm.input.$valid')).toEqual('true'); }); it('should be invalid if empty', function() { input('text').enter(''); expect(binding('text')).toEqual(''); expect(binding('myForm.input.$valid')).toEqual('false'); }); it('should be invalid if not email', function() { input('text').enter('xxx'); expect(binding('myForm.input.$valid')).toEqual('false'); }); </doc:scenario> </doc:example> */ 'email': emailInputType, /** * @ngdoc inputType * @name ng.directive:input.radio * * @description * HTML radio button. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string} value The value to which the expression should be set when selected. * @param {string=} name Property name of the form under which the control is published. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.color = 'blue'; } </script> <form name="myForm" ng-controller="Ctrl"> <input type="radio" ng-model="color" value="red"> Red <br/> <input type="radio" ng-model="color" value="green"> Green <br/> <input type="radio" ng-model="color" value="blue"> Blue <br/> <tt>color = {{color}}</tt><br/> </form> </doc:source> <doc:scenario> it('should change state', function() { expect(binding('color')).toEqual('blue'); input('color').select('red'); expect(binding('color')).toEqual('red'); }); </doc:scenario> </doc:example> */ 'radio': radioInputType, /** * @ngdoc inputType * @name ng.directive:input.checkbox * * @description * HTML checkbox. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} ngTrueValue The value to which the expression should be set when selected. * @param {string=} ngFalseValue The value to which the expression should be set when not selected. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.value1 = true; $scope.value2 = 'YES' } </script> <form name="myForm" ng-controller="Ctrl"> Value1: <input type="checkbox" ng-model="value1"> <br/> Value2: <input type="checkbox" ng-model="value2" ng-true-value="YES" ng-false-value="NO"> <br/> <tt>value1 = {{value1}}</tt><br/> <tt>value2 = {{value2}}</tt><br/> </form> </doc:source> <doc:scenario> it('should change state', function() { expect(binding('value1')).toEqual('true'); expect(binding('value2')).toEqual('YES'); input('value1').check(); input('value2').check(); expect(binding('value1')).toEqual('false'); expect(binding('value2')).toEqual('NO'); }); </doc:scenario> </doc:example> */ 'checkbox': checkboxInputType, 'hidden': noop, 'button': noop, 'submit': noop, 'reset': noop }; function isEmpty(value) { return isUndefined(value) || value === '' || value === null || value !== value; } function textInputType(scope, element, attr, ctrl, $sniffer, $browser) { var listener = function() { var value = trim(element.val()); if (ctrl.$viewValue !== value) { scope.$apply(function() { ctrl.$setViewValue(value); }); } }; // if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the // input event on backspace, delete or cut if ($sniffer.hasEvent('input')) { element.bind('input', listener); } else { var timeout; element.bind('keydown', function(event) { var key = event.keyCode; // ignore // command modifiers arrows if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return; if (!timeout) { timeout = $browser.defer(function() { listener(); timeout = null; }); } }); // if user paste into input using mouse, we need "change" event to catch it element.bind('change', listener); } ctrl.$render = function() { element.val(isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue); }; // pattern validator var pattern = attr.ngPattern, patternValidator; var validate = function(regexp, value) { if (isEmpty(value) || regexp.test(value)) { ctrl.$setValidity('pattern', true); return value; } else { ctrl.$setValidity('pattern', false); return undefined; } }; if (pattern) { if (pattern.match(/^\/(.*)\/$/)) { pattern = new RegExp(pattern.substr(1, pattern.length - 2)); patternValidator = function(value) { return validate(pattern, value) }; } else { patternValidator = function(value) { var patternObj = scope.$eval(pattern); if (!patternObj || !patternObj.test) { throw new Error('Expected ' + pattern + ' to be a RegExp but was ' + patternObj); } return validate(patternObj, value); }; } ctrl.$formatters.push(patternValidator); ctrl.$parsers.push(patternValidator); } // min length validator if (attr.ngMinlength) { var minlength = int(attr.ngMinlength); var minLengthValidator = function(value) { if (!isEmpty(value) && value.length < minlength) { ctrl.$setValidity('minlength', false); return undefined; } else { ctrl.$setValidity('minlength', true); return value; } }; ctrl.$parsers.push(minLengthValidator); ctrl.$formatters.push(minLengthValidator); } // max length validator if (attr.ngMaxlength) { var maxlength = int(attr.ngMaxlength); var maxLengthValidator = function(value) { if (!isEmpty(value) && value.length > maxlength) { ctrl.$setValidity('maxlength', false); return undefined; } else { ctrl.$setValidity('maxlength', true); return value; } }; ctrl.$parsers.push(maxLengthValidator); ctrl.$formatters.push(maxLengthValidator); } } function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) { textInputType(scope, element, attr, ctrl, $sniffer, $browser); ctrl.$parsers.push(function(value) { var empty = isEmpty(value); if (empty || NUMBER_REGEXP.test(value)) { ctrl.$setValidity('number', true); return value === '' ? null : (empty ? value : parseFloat(value)); } else { ctrl.$setValidity('number', false); return undefined; } }); ctrl.$formatters.push(function(value) { return isEmpty(value) ? '' : '' + value; }); if (attr.min) { var min = parseFloat(attr.min); var minValidator = function(value) { if (!isEmpty(value) && value < min) { ctrl.$setValidity('min', false); return undefined; } else { ctrl.$setValidity('min', true); return value; } }; ctrl.$parsers.push(minValidator); ctrl.$formatters.push(minValidator); } if (attr.max) { var max = parseFloat(attr.max); var maxValidator = function(value) { if (!isEmpty(value) && value > max) { ctrl.$setValidity('max', false); return undefined; } else { ctrl.$setValidity('max', true); return value; } }; ctrl.$parsers.push(maxValidator); ctrl.$formatters.push(maxValidator); } ctrl.$formatters.push(function(value) { if (isEmpty(value) || isNumber(value)) { ctrl.$setValidity('number', true); return value; } else { ctrl.$setValidity('number', false); return undefined; } }); } function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) { textInputType(scope, element, attr, ctrl, $sniffer, $browser); var urlValidator = function(value) { if (isEmpty(value) || URL_REGEXP.test(value)) { ctrl.$setValidity('url', true); return value; } else { ctrl.$setValidity('url', false); return undefined; } }; ctrl.$formatters.push(urlValidator); ctrl.$parsers.push(urlValidator); } function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) { textInputType(scope, element, attr, ctrl, $sniffer, $browser); var emailValidator = function(value) { if (isEmpty(value) || EMAIL_REGEXP.test(value)) { ctrl.$setValidity('email', true); return value; } else { ctrl.$setValidity('email', false); return undefined; } }; ctrl.$formatters.push(emailValidator); ctrl.$parsers.push(emailValidator); } function radioInputType(scope, element, attr, ctrl) { // make the name unique, if not defined if (isUndefined(attr.name)) { element.attr('name', nextUid()); } element.bind('click', function() { if (element[0].checked) { scope.$apply(function() { ctrl.$setViewValue(attr.value); }); } }); ctrl.$render = function() { var value = attr.value; element[0].checked = (value == ctrl.$viewValue); }; attr.$observe('value', ctrl.$render); } function checkboxInputType(scope, element, attr, ctrl) { var trueValue = attr.ngTrueValue, falseValue = attr.ngFalseValue; if (!isString(trueValue)) trueValue = true; if (!isString(falseValue)) falseValue = false; element.bind('click', function() { scope.$apply(function() { ctrl.$setViewValue(element[0].checked); }); }); ctrl.$render = function() { element[0].checked = ctrl.$viewValue; }; ctrl.$formatters.push(function(value) { return value === trueValue; }); ctrl.$parsers.push(function(value) { return value ? trueValue : falseValue; }); } /** * @ngdoc directive * @name ng.directive:textarea * @restrict E * * @description * HTML textarea element control with angular data-binding. The data-binding and validation * properties of this element are exactly the same as those of the * {@link ng.directive:input input element}. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} required Sets `required` validation error key if the value is not entered. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than * minlength. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than * maxlength. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for * patterns defined as scope expressions. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. */ /** * @ngdoc directive * @name ng.directive:input * @restrict E * * @description * HTML input element control with angular data-binding. Input control follows HTML5 input types * and polyfills the HTML5 validation behavior for older browsers. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} required Sets `required` validation error key if the value is not entered. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than * minlength. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than * maxlength. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for * patterns defined as scope expressions. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.user = {name: 'guest', last: 'visitor'}; } </script> <div ng-controller="Ctrl"> <form name="myForm"> User name: <input type="text" name="userName" ng-model="user.name" required> <span class="error" ng-show="myForm.userName.$error.required"> Required!</span><br> Last name: <input type="text" name="lastName" ng-model="user.last" ng-minlength="3" ng-maxlength="10"> <span class="error" ng-show="myForm.lastName.$error.minlength"> Too short!</span> <span class="error" ng-show="myForm.lastName.$error.maxlength"> Too long!</span><br> </form> <hr> <tt>user = {{user}}</tt><br/> <tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br> <tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br> <tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br> <tt>myForm.userName.$error = {{myForm.lastName.$error}}</tt><br> <tt>myForm.$valid = {{myForm.$valid}}</tt><br> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br> <tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br> <tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br> </div> </doc:source> <doc:scenario> it('should initialize to model', function() { expect(binding('user')).toEqual('{"name":"guest","last":"visitor"}'); expect(binding('myForm.userName.$valid')).toEqual('true'); expect(binding('myForm.$valid')).toEqual('true'); }); it('should be invalid if empty when required', function() { input('user.name').enter(''); expect(binding('user')).toEqual('{"last":"visitor"}'); expect(binding('myForm.userName.$valid')).toEqual('false'); expect(binding('myForm.$valid')).toEqual('false'); }); it('should be valid if empty when min length is set', function() { input('user.last').enter(''); expect(binding('user')).toEqual('{"name":"guest","last":""}'); expect(binding('myForm.lastName.$valid')).toEqual('true'); expect(binding('myForm.$valid')).toEqual('true'); }); it('should be invalid if less than required min length', function() { input('user.last').enter('xx'); expect(binding('user')).toEqual('{"name":"guest"}'); expect(binding('myForm.lastName.$valid')).toEqual('false'); expect(binding('myForm.lastName.$error')).toMatch(/minlength/); expect(binding('myForm.$valid')).toEqual('false'); }); it('should be invalid if longer than max length', function() { input('user.last').enter('some ridiculously long name'); expect(binding('user')) .toEqual('{"name":"guest"}'); expect(binding('myForm.lastName.$valid')).toEqual('false'); expect(binding('myForm.lastName.$error')).toMatch(/maxlength/); expect(binding('myForm.$valid')).toEqual('false'); }); </doc:scenario> </doc:example> */ var inputDirective = ['$browser', '$sniffer', function($browser, $sniffer) { return { restrict: 'E', require: '?ngModel', link: function(scope, element, attr, ctrl) { if (ctrl) { (inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrl, $sniffer, $browser); } } }; }]; var VALID_CLASS = 'ng-valid', INVALID_CLASS = 'ng-invalid', PRISTINE_CLASS = 'ng-pristine', DIRTY_CLASS = 'ng-dirty'; /** * @ngdoc object * @name ng.directive:ngModel.NgModelController * * @property {string} $viewValue Actual string value in the view. * @property {*} $modelValue The value in the model, that the control is bound to. * @property {Array.<Function>} $parsers Whenever the control reads value from the DOM, it executes * all of these functions to sanitize / convert the value as well as validate. * * @property {Array.<Function>} $formatters Whenever the model value changes, it executes all of * these functions to convert the value as well as validate. * * @property {Object} $error An bject hash with all errors as keys. * * @property {boolean} $pristine True if user has not interacted with the control yet. * @property {boolean} $dirty True if user has already interacted with the control. * @property {boolean} $valid True if there is no error. * @property {boolean} $invalid True if at least one error on the control. * * @description * * `NgModelController` provides API for the `ng-model` directive. The controller contains * services for data-binding, validation, CSS update, value formatting and parsing. It * specifically does not contain any logic which deals with DOM rendering or listening to * DOM events. The `NgModelController` is meant to be extended by other directives where, the * directive provides DOM manipulation and the `NgModelController` provides the data-binding. * * This example shows how to use `NgModelController` with a custom control to achieve * data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`) * collaborate together to achieve the desired result. * * <example module="customControl"> <file name="style.css"> [contenteditable] { border: 1px solid black; background-color: white; min-height: 20px; } .ng-invalid { border: 1px solid red; } </file> <file name="script.js"> angular.module('customControl', []). directive('contenteditable', function() { return { restrict: 'A', // only activate on element attribute require: '?ngModel', // get a hold of NgModelController link: function(scope, element, attrs, ngModel) { if(!ngModel) return; // do nothing if no ng-model // Specify how UI should be updated ngModel.$render = function() { element.html(ngModel.$viewValue || ''); }; // Listen for change events to enable binding element.bind('blur keyup change', function() { scope.$apply(read); }); read(); // initialize // Write data to the model function read() { ngModel.$setViewValue(element.html()); } } }; }); </file> <file name="index.html"> <form name="myForm"> <div contenteditable name="myWidget" ng-model="userContent" required>Change me!</div> <span ng-show="myForm.myWidget.$error.required">Required!</span> <hr> <textarea ng-model="userContent"></textarea> </form> </file> <file name="scenario.js"> it('should data-bind and become invalid', function() { var contentEditable = element('[contenteditable]'); expect(contentEditable.text()).toEqual('Change me!'); input('userContent').enter(''); expect(contentEditable.text()).toEqual(''); expect(contentEditable.prop('className')).toMatch(/ng-invalid-required/); }); </file> * </example> * */ var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', function($scope, $exceptionHandler, $attr, $element, $parse) { this.$viewValue = Number.NaN; this.$modelValue = Number.NaN; this.$parsers = []; this.$formatters = []; this.$viewChangeListeners = []; this.$pristine = true; this.$dirty = false; this.$valid = true; this.$invalid = false; this.$name = $attr.name; var ngModelGet = $parse($attr.ngModel), ngModelSet = ngModelGet.assign; if (!ngModelSet) { throw Error(NON_ASSIGNABLE_MODEL_EXPRESSION + $attr.ngModel + ' (' + startingTag($element) + ')'); } /** * @ngdoc function * @name ng.directive:ngModel.NgModelController#$render * @methodOf ng.directive:ngModel.NgModelController * * @description * Called when the view needs to be updated. It is expected that the user of the ng-model * directive will implement this method. */ this.$render = noop; var parentForm = $element.inheritedData('$formController') || nullFormCtrl, invalidCount = 0, // used to easily determine if we are valid $error = this.$error = {}; // keep invalid keys here // Setup initial state of the control $element.addClass(PRISTINE_CLASS); toggleValidCss(true); // convenience method for easy toggling of classes function toggleValidCss(isValid, validationErrorKey) { validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : ''; $element. removeClass((isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey). addClass((isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey); } /** * @ngdoc function * @name ng.directive:ngModel.NgModelController#$setValidity * @methodOf ng.directive:ngModel.NgModelController * * @description * Change the validity state, and notifies the form when the control changes validity. (i.e. it * does not notify form if given validator is already marked as invalid). * * This method should be called by validators - i.e. the parser or formatter functions. * * @param {string} validationErrorKey Name of the validator. the `validationErrorKey` will assign * to `$error[validationErrorKey]=isValid` so that it is available for data-binding. * The `validationErrorKey` should be in camelCase and will get converted into dash-case * for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error` * class and can be bound to as `{{someForm.someControl.$error.myError}}` . * @param {boolean} isValid Whether the current state is valid (true) or invalid (false). */ this.$setValidity = function(validationErrorKey, isValid) { if ($error[validationErrorKey] === !isValid) return; if (isValid) { if ($error[validationErrorKey]) invalidCount--; if (!invalidCount) { toggleValidCss(true); this.$valid = true; this.$invalid = false; } } else { toggleValidCss(false); this.$invalid = true; this.$valid = false; invalidCount++; } $error[validationErrorKey] = !isValid; toggleValidCss(isValid, validationErrorKey); parentForm.$setValidity(validationErrorKey, isValid, this); }; /** * @ngdoc function * @name ng.directive:ngModel.NgModelController#$setViewValue * @methodOf ng.directive:ngModel.NgModelController * * @description * Read a value from view. * * This method should be called from within a DOM event handler. * For example {@link ng.directive:input input} or * {@link ng.directive:select select} directives call it. * * It internally calls all `formatters` and if resulted value is valid, updates the model and * calls all registered change listeners. * * @param {string} value Value from the view. */ this.$setViewValue = function(value) { this.$viewValue = value; // change to dirty if (this.$pristine) { this.$dirty = true; this.$pristine = false; $element.removeClass(PRISTINE_CLASS).addClass(DIRTY_CLASS); parentForm.$setDirty(); } forEach(this.$parsers, function(fn) { value = fn(value); }); if (this.$modelValue !== value) { this.$modelValue = value; ngModelSet($scope, value); forEach(this.$viewChangeListeners, function(listener) { try { listener(); } catch(e) { $exceptionHandler(e); } }) } }; // model -> value var ctrl = this; $scope.$watch(ngModelGet, function(value) { // ignore change from view if (ctrl.$modelValue === value) return; var formatters = ctrl.$formatters, idx = formatters.length; ctrl.$modelValue = value; while(idx--) { value = formatters[idx](value); } if (ctrl.$viewValue !== value) { ctrl.$viewValue = value; ctrl.$render(); } }); }]; /** * @ngdoc directive * @name ng.directive:ngModel * * @element input * * @description * Is directive that tells Angular to do two-way data binding. It works together with `input`, * `select`, `textarea`. You can easily write your own directives to use `ngModel` as well. * * `ngModel` is responsible for: * * - binding the view into the model, which other directives such as `input`, `textarea` or `select` * require, * - providing validation behavior (i.e. required, number, email, url), * - keeping state of the control (valid/invalid, dirty/pristine, validation errors), * - setting related css class onto the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`), * - register the control with parent {@link ng.directive:form form}. * * For basic examples, how to use `ngModel`, see: * * - {@link ng.directive:input input} * - {@link ng.directive:input.text text} * - {@link ng.directive:input.checkbox checkbox} * - {@link ng.directive:input.radio radio} * - {@link ng.directive:input.number number} * - {@link ng.directive:input.email email} * - {@link ng.directive:input.url url} * - {@link ng.directive:select select} * - {@link ng.directive:textarea textarea} * */ var ngModelDirective = function() { return { require: ['ngModel', '^?form'], controller: NgModelController, link: function(scope, element, attr, ctrls) { // notify others, especially parent forms var modelCtrl = ctrls[0], formCtrl = ctrls[1] || nullFormCtrl; formCtrl.$addControl(modelCtrl); element.bind('$destroy', function() { formCtrl.$removeControl(modelCtrl); }); } }; }; /** * @ngdoc directive * @name ng.directive:ngChange * @restrict E * * @description * Evaluate given expression when user changes the input. * The expression is not evaluated when the value change is coming from the model. * * Note, this directive requires `ngModel` to be present. * * @element input * * @example * <doc:example> * <doc:source> * <script> * function Controller($scope) { * $scope.counter = 0; * $scope.change = function() { * $scope.counter++; * }; * } * </script> * <div ng-controller="Controller"> * <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" /> * <input type="checkbox" ng-model="confirmed" id="ng-change-example2" /> * <label for="ng-change-example2">Confirmed</label><br /> * debug = {{confirmed}}<br /> * counter = {{counter}} * </div> * </doc:source> * <doc:scenario> * it('should evaluate the expression if changing from view', function() { * expect(binding('counter')).toEqual('0'); * element('#ng-change-example1').click(); * expect(binding('counter')).toEqual('1'); * expect(binding('confirmed')).toEqual('true'); * }); * * it('should not evaluate the expression if changing from model', function() { * element('#ng-change-example2').click(); * expect(binding('counter')).toEqual('0'); * expect(binding('confirmed')).toEqual('true'); * }); * </doc:scenario> * </doc:example> */ var ngChangeDirective = valueFn({ require: 'ngModel', link: function(scope, element, attr, ctrl) { ctrl.$viewChangeListeners.push(function() { scope.$eval(attr.ngChange); }); } }); var requiredDirective = function() { return { require: '?ngModel', link: function(scope, elm, attr, ctrl) { if (!ctrl) return; attr.required = true; // force truthy in case we are on non input element var validator = function(value) { if (attr.required && (isEmpty(value) || value === false)) { ctrl.$setValidity('required', false); return; } else { ctrl.$setValidity('required', true); return value; } }; ctrl.$formatters.push(validator); ctrl.$parsers.unshift(validator); attr.$observe('required', function() { validator(ctrl.$viewValue); }); } }; }; /** * @ngdoc directive * @name ng.directive:ngList * * @description * Text input that converts between comma-seperated string into an array of strings. * * @element input * @param {string=} ngList optional delimiter that should be used to split the value. If * specified in form `/something/` then the value will be converted into a regular expression. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.names = ['igor', 'misko', 'vojta']; } </script> <form name="myForm" ng-controller="Ctrl"> List: <input name="namesInput" ng-model="names" ng-list required> <span class="error" ng-show="myForm.list.$error.required"> Required!</span> <tt>names = {{names}}</tt><br/> <tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/> <tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> </form> </doc:source> <doc:scenario> it('should initialize to model', function() { expect(binding('names')).toEqual('["igor","misko","vojta"]'); expect(binding('myForm.namesInput.$valid')).toEqual('true'); }); it('should be invalid if empty', function() { input('names').enter(''); expect(binding('names')).toEqual('[]'); expect(binding('myForm.namesInput.$valid')).toEqual('false'); }); </doc:scenario> </doc:example> */ var ngListDirective = function() { return { require: 'ngModel', link: function(scope, element, attr, ctrl) { var match = /\/(.*)\//.exec(attr.ngList), separator = match && new RegExp(match[1]) || attr.ngList || ','; var parse = function(viewValue) { var list = []; if (viewValue) { forEach(viewValue.split(separator), function(value) { if (value) list.push(trim(value)); }); } return list; }; ctrl.$parsers.push(parse); ctrl.$formatters.push(function(value) { if (isArray(value)) { return value.join(', '); } return undefined; }); } }; }; var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/; var ngValueDirective = function() { return { priority: 100, compile: function(tpl, tplAttr) { if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) { return function(scope, elm, attr) { attr.$set('value', scope.$eval(attr.ngValue)); }; } else { return function(scope, elm, attr) { scope.$watch(attr.ngValue, function(value) { attr.$set('value', value, false); }); }; } } }; }; /** * @ngdoc directive * @name ng.directive:ngBind * * @description * The `ngBind` attribute tells Angular to replace the text content of the specified HTML element * with the value of a given expression, and to update the text content when the value of that * expression changes. * * Typically, you don't use `ngBind` directly, but instead you use the double curly markup like * `{{ expression }}` which is similar but less verbose. * * Once scenario in which the use of `ngBind` is prefered over `{{ expression }}` binding is when * it's desirable to put bindings into template that is momentarily displayed by the browser in its * raw state before Angular compiles it. Since `ngBind` is an element attribute, it makes the * bindings invisible to the user while the page is loading. * * An alternative solution to this problem would be using the * {@link ng.directive:ngCloak ngCloak} directive. * * * @element ANY * @param {expression} ngBind {@link guide/expression Expression} to evaluate. * * @example * Enter a name in the Live Preview text box; the greeting below the text box changes instantly. <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.name = 'Whirled'; } </script> <div ng-controller="Ctrl"> Enter name: <input type="text" ng-model="name"><br> Hello <span ng-bind="name"></span>! </div> </doc:source> <doc:scenario> it('should check ng-bind', function() { expect(using('.doc-example-live').binding('name')).toBe('Whirled'); using('.doc-example-live').input('name').enter('world'); expect(using('.doc-example-live').binding('name')).toBe('world'); }); </doc:scenario> </doc:example> */ var ngBindDirective = ngDirective(function(scope, element, attr) { element.addClass('ng-binding').data('$binding', attr.ngBind); scope.$watch(attr.ngBind, function(value) { element.text(value == undefined ? '' : value); }); }); /** * @ngdoc directive * @name ng.directive:ngBindTemplate * * @description * The `ngBindTemplate` directive specifies that the element * text should be replaced with the template in ngBindTemplate. * Unlike ngBind the ngBindTemplate can contain multiple `{{` `}}` * expressions. (This is required since some HTML elements * can not have SPAN elements such as TITLE, or OPTION to name a few.) * * @element ANY * @param {string} ngBindTemplate template of form * <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval. * * @example * Try it here: enter text in text box and watch the greeting change. <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.salutation = 'Hello'; $scope.name = 'World'; } </script> <div ng-controller="Ctrl"> Salutation: <input type="text" ng-model="salutation"><br> Name: <input type="text" ng-model="name"><br> <pre ng-bind-template="{{salutation}} {{name}}!"></pre> </div> </doc:source> <doc:scenario> it('should check ng-bind', function() { expect(using('.doc-example-live').binding('salutation')). toBe('Hello'); expect(using('.doc-example-live').binding('name')). toBe('World'); using('.doc-example-live').input('salutation').enter('Greetings'); using('.doc-example-live').input('name').enter('user'); expect(using('.doc-example-live').binding('salutation')). toBe('Greetings'); expect(using('.doc-example-live').binding('name')). toBe('user'); }); </doc:scenario> </doc:example> */ var ngBindTemplateDirective = ['$interpolate', function($interpolate) { return function(scope, element, attr) { // TODO: move this to scenario runner var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate)); element.addClass('ng-binding').data('$binding', interpolateFn); attr.$observe('ngBindTemplate', function(value) { element.text(value); }); } }]; /** * @ngdoc directive * @name ng.directive:ngBindHtmlUnsafe * * @description * Creates a binding that will innerHTML the result of evaluating the `expression` into the current * element. *The innerHTML-ed content will not be sanitized!* You should use this directive only if * {@link ngSanitize.directive:ngBindHtml ngBindHtml} directive is too * restrictive and when you absolutely trust the source of the content you are binding to. * * See {@link ngSanitize.$sanitize $sanitize} docs for examples. * * @element ANY * @param {expression} ngBindHtmlUnsafe {@link guide/expression Expression} to evaluate. */ var ngBindHtmlUnsafeDirective = [function() { return function(scope, element, attr) { element.addClass('ng-binding').data('$binding', attr.ngBindHtmlUnsafe); scope.$watch(attr.ngBindHtmlUnsafe, function(value) { element.html(value || ''); }); }; }]; function classDirective(name, selector) { name = 'ngClass' + name; return ngDirective(function(scope, element, attr) { scope.$watch(attr[name], function(newVal, oldVal) { if (selector === true || scope.$index % 2 === selector) { if (oldVal && (newVal !== oldVal)) { if (isObject(oldVal) && !isArray(oldVal)) oldVal = map(oldVal, function(v, k) { if (v) return k }); element.removeClass(isArray(oldVal) ? oldVal.join(' ') : oldVal); } if (isObject(newVal) && !isArray(newVal)) newVal = map(newVal, function(v, k) { if (v) return k }); if (newVal) element.addClass(isArray(newVal) ? newVal.join(' ') : newVal); } }, true); }); } /** * @ngdoc directive * @name ng.directive:ngClass * * @description * The `ngClass` allows you to set CSS class on HTML element dynamically by databinding an * expression that represents all classes to be added. * * The directive won't add duplicate classes if a particular class was already set. * * When the expression changes, the previously added classes are removed and only then the classes * new classes are added. * * @element ANY * @param {expression} ngClass {@link guide/expression Expression} to eval. The result * of the evaluation can be a string representing space delimited class * names, an array, or a map of class names to boolean values. * * @example <example> <file name="index.html"> <input type="button" value="set" ng-click="myVar='my-class'"> <input type="button" value="clear" ng-click="myVar=''"> <br> <span ng-class="myVar">Sample Text</span> </file> <file name="style.css"> .my-class { color: red; } </file> <file name="scenario.js"> it('should check ng-class', function() { expect(element('.doc-example-live span').prop('className')).not(). toMatch(/my-class/); using('.doc-example-live').element(':button:first').click(); expect(element('.doc-example-live span').prop('className')). toMatch(/my-class/); using('.doc-example-live').element(':button:last').click(); expect(element('.doc-example-live span').prop('className')).not(). toMatch(/my-class/); }); </file> </example> */ var ngClassDirective = classDirective('', true); /** * @ngdoc directive * @name ng.directive:ngClassOdd * * @description * The `ngClassOdd` and `ngClassEven` directives work exactly as * {@link ng.directive:ngClass ngClass}, except it works in * conjunction with `ngRepeat` and takes affect only on odd (even) rows. * * This directive can be applied only within a scope of an * {@link ng.directive:ngRepeat ngRepeat}. * * @element ANY * @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result * of the evaluation can be a string representing space delimited class names or an array. * * @example <example> <file name="index.html"> <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']"> <li ng-repeat="name in names"> <span ng-class-odd="'odd'" ng-class-even="'even'"> {{name}} </span> </li> </ol> </file> <file name="style.css"> .odd { color: red; } .even { color: blue; } </file> <file name="scenario.js"> it('should check ng-class-odd and ng-class-even', function() { expect(element('.doc-example-live li:first span').prop('className')). toMatch(/odd/); expect(element('.doc-example-live li:last span').prop('className')). toMatch(/even/); }); </file> </example> */ var ngClassOddDirective = classDirective('Odd', 0); /** * @ngdoc directive * @name ng.directive:ngClassEven * * @description * The `ngClassOdd` and `ngClassEven` works exactly as * {@link ng.directive:ngClass ngClass}, except it works in * conjunction with `ngRepeat` and takes affect only on odd (even) rows. * * This directive can be applied only within a scope of an * {@link ng.directive:ngRepeat ngRepeat}. * * @element ANY * @param {expression} ngClassEven {@link guide/expression Expression} to eval. The * result of the evaluation can be a string representing space delimited class names or an array. * * @example <example> <file name="index.html"> <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']"> <li ng-repeat="name in names"> <span ng-class-odd="'odd'" ng-class-even="'even'"> {{name}} &nbsp; &nbsp; &nbsp; </span> </li> </ol> </file> <file name="style.css"> .odd { color: red; } .even { color: blue; } </file> <file name="scenario.js"> it('should check ng-class-odd and ng-class-even', function() { expect(element('.doc-example-live li:first span').prop('className')). toMatch(/odd/); expect(element('.doc-example-live li:last span').prop('className')). toMatch(/even/); }); </file> </example> */ var ngClassEvenDirective = classDirective('Even', 1); /** * @ngdoc directive * @name ng.directive:ngCloak * * @description * The `ngCloak` directive is used to prevent the Angular html template from being briefly * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this * directive to avoid the undesirable flicker effect caused by the html template display. * * The directive can be applied to the `<body>` element, but typically a fine-grained application is * prefered in order to benefit from progressive rendering of the browser view. * * `ngCloak` works in cooperation with a css rule that is embedded within `angular.js` and * `angular.min.js` files. Following is the css rule: * * <pre> * [ng\:cloak], [ng-cloak], .ng-cloak { * display: none; * } * </pre> * * When this css rule is loaded by the browser, all html elements (including their children) that * are tagged with the `ng-cloak` directive are hidden. When Angular comes across this directive * during the compilation of the template it deletes the `ngCloak` element attribute, which * makes the compiled element visible. * * For the best result, `angular.js` script must be loaded in the head section of the html file; * alternatively, the css rule (above) must be included in the external stylesheet of the * application. * * Legacy browsers, like IE7, do not provide attribute selector support (added in CSS 2.1) so they * cannot match the `[ng\:cloak]` selector. To work around this limitation, you must add the css * class `ngCloak` in addition to `ngCloak` directive as shown in the example below. * * @element ANY * * @example <doc:example> <doc:source> <div id="template1" ng-cloak>{{ 'hello' }}</div> <div id="template2" ng-cloak class="ng-cloak">{{ 'hello IE7' }}</div> </doc:source> <doc:scenario> it('should remove the template directive and css class', function() { expect(element('.doc-example-live #template1').attr('ng-cloak')). not().toBeDefined(); expect(element('.doc-example-live #template2').attr('ng-cloak')). not().toBeDefined(); }); </doc:scenario> </doc:example> * */ var ngCloakDirective = ngDirective({ compile: function(element, attr) { attr.$set('ngCloak', undefined); element.removeClass('ng-cloak'); } }); /** * @ngdoc directive * @name ng.directive:ngController * * @description * The `ngController` directive assigns behavior to a scope. This is a key aspect of how angular * supports the principles behind the Model-View-Controller design pattern. * * MVC components in angular: * * * Model — The Model is data in scope properties; scopes are attached to the DOM. * * View — The template (HTML with data bindings) is rendered into the View. * * Controller — The `ngController` directive specifies a Controller class; the class has * methods that typically express the business logic behind the application. * * Note that an alternative way to define controllers is via the `{@link ng.$route}` * service. * * @element ANY * @scope * @param {expression} ngController Name of a globally accessible constructor function or an * {@link guide/expression expression} that on the current scope evaluates to a * constructor function. * * @example * Here is a simple form for editing user contact information. Adding, removing, clearing, and * greeting are methods declared on the controller (see source tab). These methods can * easily be called from the angular markup. Notice that the scope becomes the `this` for the * controller's instance. This allows for easy access to the view data from the controller. Also * notice that any changes to the data are automatically reflected in the View without the need * for a manual update. <doc:example> <doc:source> <script> function SettingsController($scope) { $scope.name = "John Smith"; $scope.contacts = [ {type:'phone', value:'408 555 1212'}, {type:'email', value:'[email protected]'} ]; $scope.greet = function() { alert(this.name); }; $scope.addContact = function() { this.contacts.push({type:'email', value:'[email protected]'}); }; $scope.removeContact = function(contactToRemove) { var index = this.contacts.indexOf(contactToRemove); this.contacts.splice(index, 1); }; $scope.clearContact = function(contact) { contact.type = 'phone'; contact.value = ''; }; } </script> <div ng-controller="SettingsController"> Name: <input type="text" ng-model="name"/> [ <a href="" ng-click="greet()">greet</a> ]<br/> Contact: <ul> <li ng-repeat="contact in contacts"> <select ng-model="contact.type"> <option>phone</option> <option>email</option> </select> <input type="text" ng-model="contact.value"/> [ <a href="" ng-click="clearContact(contact)">clear</a> | <a href="" ng-click="removeContact(contact)">X</a> ] </li> <li>[ <a href="" ng-click="addContact()">add</a> ]</li> </ul> </div> </doc:source> <doc:scenario> it('should check controller', function() { expect(element('.doc-example-live div>:input').val()).toBe('John Smith'); expect(element('.doc-example-live li:nth-child(1) input').val()) .toBe('408 555 1212'); expect(element('.doc-example-live li:nth-child(2) input').val()) .toBe('[email protected]'); element('.doc-example-live li:first a:contains("clear")').click(); expect(element('.doc-example-live li:first input').val()).toBe(''); element('.doc-example-live li:last a:contains("add")').click(); expect(element('.doc-example-live li:nth-child(3) input').val()) .toBe('[email protected]'); }); </doc:scenario> </doc:example> */ var ngControllerDirective = [function() { return { scope: true, controller: '@' }; }]; /** * @ngdoc directive * @name ng.directive:ngCsp * @priority 1000 * * @description * Enables [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) support. * This directive should be used on the root element of the application (typically the `<html>` * element or other element with the {@link ng.directive:ngApp ngApp} * directive). * * If enabled the performance of template expression evaluator will suffer slightly, so don't enable * this mode unless you need it. * * @element html */ var ngCspDirective = ['$sniffer', function($sniffer) { return { priority: 1000, compile: function() { $sniffer.csp = true; } }; }]; /** * @ngdoc directive * @name ng.directive:ngClick * * @description * The ngClick allows you to specify custom behavior when * element is clicked. * * @element ANY * @param {expression} ngClick {@link guide/expression Expression} to evaluate upon * click. (Event object is available as `$event`) * * @example <doc:example> <doc:source> <button ng-click="count = count + 1" ng-init="count=0"> Increment </button> count: {{count}} </doc:source> <doc:scenario> it('should check ng-click', function() { expect(binding('count')).toBe('0'); element('.doc-example-live :button').click(); expect(binding('count')).toBe('1'); }); </doc:scenario> </doc:example> */ /* * A directive that allows creation of custom onclick handlers that are defined as angular * expressions and are compiled and executed within the current scope. * * Events that are handled via these handler are always configured not to propagate further. */ var ngEventDirectives = {}; forEach( 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave'.split(' '), function(name) { var directiveName = directiveNormalize('ng-' + name); ngEventDirectives[directiveName] = ['$parse', function($parse) { return function(scope, element, attr) { var fn = $parse(attr[directiveName]); element.bind(lowercase(name), function(event) { scope.$apply(function() { fn(scope, {$event:event}); }); }); }; }]; } ); /** * @ngdoc directive * @name ng.directive:ngDblclick * * @description * The `ngDblclick` directive allows you to specify custom behavior on dblclick event. * * @element ANY * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon * dblclick. (Event object is available as `$event`) * * @example * See {@link ng.directive:ngClick ngClick} */ /** * @ngdoc directive * @name ng.directive:ngMousedown * * @description * The ngMousedown directive allows you to specify custom behavior on mousedown event. * * @element ANY * @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon * mousedown. (Event object is available as `$event`) * * @example * See {@link ng.directive:ngClick ngClick} */ /** * @ngdoc directive * @name ng.directive:ngMouseup * * @description * Specify custom behavior on mouseup event. * * @element ANY * @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon * mouseup. (Event object is available as `$event`) * * @example * See {@link ng.directive:ngClick ngClick} */ /** * @ngdoc directive * @name ng.directive:ngMouseover * * @description * Specify custom behavior on mouseover event. * * @element ANY * @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon * mouseover. (Event object is available as `$event`) * * @example * See {@link ng.directive:ngClick ngClick} */ /** * @ngdoc directive * @name ng.directive:ngMouseenter * * @description * Specify custom behavior on mouseenter event. * * @element ANY * @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon * mouseenter. (Event object is available as `$event`) * * @example * See {@link ng.directive:ngClick ngClick} */ /** * @ngdoc directive * @name ng.directive:ngMouseleave * * @description * Specify custom behavior on mouseleave event. * * @element ANY * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon * mouseleave. (Event object is available as `$event`) * * @example * See {@link ng.directive:ngClick ngClick} */ /** * @ngdoc directive * @name ng.directive:ngMousemove * * @description * Specify custom behavior on mousemove event. * * @element ANY * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon * mousemove. (Event object is available as `$event`) * * @example * See {@link ng.directive:ngClick ngClick} */ /** * @ngdoc directive * @name ng.directive:ngSubmit * * @description * Enables binding angular expressions to onsubmit events. * * Additionally it prevents the default action (which for form means sending the request to the * server and reloading the current page). * * @element form * @param {expression} ngSubmit {@link guide/expression Expression} to eval. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.list = []; $scope.text = 'hello'; $scope.submit = function() { if (this.text) { this.list.push(this.text); this.text = ''; } }; } </script> <form ng-submit="submit()" ng-controller="Ctrl"> Enter text and hit enter: <input type="text" ng-model="text" name="text" /> <input type="submit" id="submit" value="Submit" /> <pre>list={{list}}</pre> </form> </doc:source> <doc:scenario> it('should check ng-submit', function() { expect(binding('list')).toBe('[]'); element('.doc-example-live #submit').click(); expect(binding('list')).toBe('["hello"]'); expect(input('text').val()).toBe(''); }); it('should ignore empty strings', function() { expect(binding('list')).toBe('[]'); element('.doc-example-live #submit').click(); element('.doc-example-live #submit').click(); expect(binding('list')).toBe('["hello"]'); }); </doc:scenario> </doc:example> */ var ngSubmitDirective = ngDirective(function(scope, element, attrs) { element.bind('submit', function() { scope.$apply(attrs.ngSubmit); }); }); /** * @ngdoc directive * @name ng.directive:ngInclude * @restrict ECA * * @description * Fetches, compiles and includes an external HTML fragment. * * Keep in mind that Same Origin Policy applies to included resources * (e.g. ngInclude won't work for cross-domain requests on all browsers and for * file:// access on some browsers). * * @scope * * @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant, * make sure you wrap it in quotes, e.g. `src="'myPartialTemplate.html'"`. * @param {string=} onload Expression to evaluate when a new partial is loaded. * * @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll * $anchorScroll} to scroll the viewport after the content is loaded. * * - If the attribute is not set, disable scrolling. * - If the attribute is set without value, enable scrolling. * - Otherwise enable scrolling only if the expression evaluates to truthy value. * * @example <example> <file name="index.html"> <div ng-controller="Ctrl"> <select ng-model="template" ng-options="t.name for t in templates"> <option value="">(blank)</option> </select> url of the template: <tt>{{template.url}}</tt> <hr/> <div ng-include src="template.url"></div> </div> </file> <file name="script.js"> function Ctrl($scope) { $scope.templates = [ { name: 'template1.html', url: 'template1.html'} , { name: 'template2.html', url: 'template2.html'} ]; $scope.template = $scope.templates[0]; } </file> <file name="template1.html"> Content of template1.html </file> <file name="template2.html"> Content of template2.html </file> <file name="scenario.js"> it('should load template1.html', function() { expect(element('.doc-example-live [ng-include]').text()). toMatch(/Content of template1.html/); }); it('should load template2.html', function() { select('template').option('1'); expect(element('.doc-example-live [ng-include]').text()). toMatch(/Content of template2.html/); }); it('should change to blank', function() { select('template').option(''); expect(element('.doc-example-live [ng-include]').text()).toEqual(''); }); </file> </example> */ /** * @ngdoc event * @name ng.directive:ngInclude#$includeContentLoaded * @eventOf ng.directive:ngInclude * @eventType emit on the current ngInclude scope * @description * Emitted every time the ngInclude content is reloaded. */ var ngIncludeDirective = ['$http', '$templateCache', '$anchorScroll', '$compile', function($http, $templateCache, $anchorScroll, $compile) { return { restrict: 'ECA', terminal: true, compile: function(element, attr) { var srcExp = attr.ngInclude || attr.src, onloadExp = attr.onload || '', autoScrollExp = attr.autoscroll; return function(scope, element) { var changeCounter = 0, childScope; var clearContent = function() { if (childScope) { childScope.$destroy(); childScope = null; } element.html(''); }; scope.$watch(srcExp, function(src) { var thisChangeId = ++changeCounter; if (src) { $http.get(src, {cache: $templateCache}).success(function(response) { if (thisChangeId !== changeCounter) return; if (childScope) childScope.$destroy(); childScope = scope.$new(); element.html(response); $compile(element.contents())(childScope); if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) { $anchorScroll(); } childScope.$emit('$includeContentLoaded'); scope.$eval(onloadExp); }).error(function() { if (thisChangeId === changeCounter) clearContent(); }); } else clearContent(); }); }; } }; }]; /** * @ngdoc directive * @name ng.directive:ngInit * * @description * The `ngInit` directive specifies initialization tasks to be executed * before the template enters execution mode during bootstrap. * * @element ANY * @param {expression} ngInit {@link guide/expression Expression} to eval. * * @example <doc:example> <doc:source> <div ng-init="greeting='Hello'; person='World'"> {{greeting}} {{person}}! </div> </doc:source> <doc:scenario> it('should check greeting', function() { expect(binding('greeting')).toBe('Hello'); expect(binding('person')).toBe('World'); }); </doc:scenario> </doc:example> */ var ngInitDirective = ngDirective({ compile: function() { return { pre: function(scope, element, attrs) { scope.$eval(attrs.ngInit); } } } }); /** * @ngdoc directive * @name ng.directive:ngNonBindable * @priority 1000 * * @description * Sometimes it is necessary to write code which looks like bindings but which should be left alone * by angular. Use `ngNonBindable` to make angular ignore a chunk of HTML. * * @element ANY * * @example * In this example there are two location where a simple binding (`{{}}`) is present, but the one * wrapped in `ngNonBindable` is left alone. * * @example <doc:example> <doc:source> <div>Normal: {{1 + 2}}</div> <div ng-non-bindable>Ignored: {{1 + 2}}</div> </doc:source> <doc:scenario> it('should check ng-non-bindable', function() { expect(using('.doc-example-live').binding('1 + 2')).toBe('3'); expect(using('.doc-example-live').element('div:last').text()). toMatch(/1 \+ 2/); }); </doc:scenario> </doc:example> */ var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 }); /** * @ngdoc directive * @name ng.directive:ngPluralize * @restrict EA * * @description * # Overview * `ngPluralize` is a directive that displays messages according to en-US localization rules. * These rules are bundled with angular.js and the rules can be overridden * (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive * by specifying the mappings between * {@link http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html * plural categories} and the strings to be displayed. * * # Plural categories and explicit number rules * There are two * {@link http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html * plural categories} in Angular's default en-US locale: "one" and "other". * * While a pural category may match many numbers (for example, in en-US locale, "other" can match * any number that is not 1), an explicit number rule can only match one number. For example, the * explicit number rule for "3" matches the number 3. You will see the use of plural categories * and explicit number rules throughout later parts of this documentation. * * # Configuring ngPluralize * You configure ngPluralize by providing 2 attributes: `count` and `when`. * You can also provide an optional attribute, `offset`. * * The value of the `count` attribute can be either a string or an {@link guide/expression * Angular expression}; these are evaluated on the current scope for its bound value. * * The `when` attribute specifies the mappings between plural categories and the actual * string to be displayed. The value of the attribute should be a JSON object so that Angular * can interpret it correctly. * * The following example shows how to configure ngPluralize: * * <pre> * <ng-pluralize count="personCount" when="{'0': 'Nobody is viewing.', * 'one': '1 person is viewing.', * 'other': '{} people are viewing.'}"> * </ng-pluralize> *</pre> * * In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not * specify this rule, 0 would be matched to the "other" category and "0 people are viewing" * would be shown instead of "Nobody is viewing". You can specify an explicit number rule for * other numbers, for example 12, so that instead of showing "12 people are viewing", you can * show "a dozen people are viewing". * * You can use a set of closed braces(`{}`) as a placeholder for the number that you want substituted * into pluralized strings. In the previous example, Angular will replace `{}` with * <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder * for <span ng-non-bindable>{{numberExpression}}</span>. * * # Configuring ngPluralize with offset * The `offset` attribute allows further customization of pluralized text, which can result in * a better user experience. For example, instead of the message "4 people are viewing this document", * you might display "John, Kate and 2 others are viewing this document". * The offset attribute allows you to offset a number by any desired value. * Let's take a look at an example: * * <pre> * <ng-pluralize count="personCount" offset=2 * when="{'0': 'Nobody is viewing.', * '1': '{{person1}} is viewing.', * '2': '{{person1}} and {{person2}} are viewing.', * 'one': '{{person1}}, {{person2}} and one other person are viewing.', * 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}"> * </ng-pluralize> * </pre> * * Notice that we are still using two plural categories(one, other), but we added * three explicit number rules 0, 1 and 2. * When one person, perhaps John, views the document, "John is viewing" will be shown. * When three people view the document, no explicit number rule is found, so * an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category. * In this case, plural category 'one' is matched and "John, Marry and one other person are viewing" * is shown. * * Note that when you specify offsets, you must provide explicit number rules for * numbers from 0 up to and including the offset. If you use an offset of 3, for example, * you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for * plural categories "one" and "other". * * @param {string|expression} count The variable to be bounded to. * @param {string} when The mapping between plural category to its correspoding strings. * @param {number=} offset Offset to deduct from the total number. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.person1 = 'Igor'; $scope.person2 = 'Misko'; $scope.personCount = 1; } </script> <div ng-controller="Ctrl"> Person 1:<input type="text" ng-model="person1" value="Igor" /><br/> Person 2:<input type="text" ng-model="person2" value="Misko" /><br/> Number of People:<input type="text" ng-model="personCount" value="1" /><br/> <!--- Example with simple pluralization rules for en locale ---> Without Offset: <ng-pluralize count="personCount" when="{'0': 'Nobody is viewing.', 'one': '1 person is viewing.', 'other': '{} people are viewing.'}"> </ng-pluralize><br> <!--- Example with offset ---> With Offset(2): <ng-pluralize count="personCount" offset=2 when="{'0': 'Nobody is viewing.', '1': '{{person1}} is viewing.', '2': '{{person1}} and {{person2}} are viewing.', 'one': '{{person1}}, {{person2}} and one other person are viewing.', 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}"> </ng-pluralize> </div> </doc:source> <doc:scenario> it('should show correct pluralized string', function() { expect(element('.doc-example-live ng-pluralize:first').text()). toBe('1 person is viewing.'); expect(element('.doc-example-live ng-pluralize:last').text()). toBe('Igor is viewing.'); using('.doc-example-live').input('personCount').enter('0'); expect(element('.doc-example-live ng-pluralize:first').text()). toBe('Nobody is viewing.'); expect(element('.doc-example-live ng-pluralize:last').text()). toBe('Nobody is viewing.'); using('.doc-example-live').input('personCount').enter('2'); expect(element('.doc-example-live ng-pluralize:first').text()). toBe('2 people are viewing.'); expect(element('.doc-example-live ng-pluralize:last').text()). toBe('Igor and Misko are viewing.'); using('.doc-example-live').input('personCount').enter('3'); expect(element('.doc-example-live ng-pluralize:first').text()). toBe('3 people are viewing.'); expect(element('.doc-example-live ng-pluralize:last').text()). toBe('Igor, Misko and one other person are viewing.'); using('.doc-example-live').input('personCount').enter('4'); expect(element('.doc-example-live ng-pluralize:first').text()). toBe('4 people are viewing.'); expect(element('.doc-example-live ng-pluralize:last').text()). toBe('Igor, Misko and 2 other people are viewing.'); }); it('should show data-binded names', function() { using('.doc-example-live').input('personCount').enter('4'); expect(element('.doc-example-live ng-pluralize:last').text()). toBe('Igor, Misko and 2 other people are viewing.'); using('.doc-example-live').input('person1').enter('Di'); using('.doc-example-live').input('person2').enter('Vojta'); expect(element('.doc-example-live ng-pluralize:last').text()). toBe('Di, Vojta and 2 other people are viewing.'); }); </doc:scenario> </doc:example> */ var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interpolate) { var BRACE = /{}/g; return { restrict: 'EA', link: function(scope, element, attr) { var numberExp = attr.count, whenExp = element.attr(attr.$attr.when), // this is because we have {{}} in attrs offset = attr.offset || 0, whens = scope.$eval(whenExp), whensExpFns = {}, startSymbol = $interpolate.startSymbol(), endSymbol = $interpolate.endSymbol(); forEach(whens, function(expression, key) { whensExpFns[key] = $interpolate(expression.replace(BRACE, startSymbol + numberExp + '-' + offset + endSymbol)); }); scope.$watch(function() { var value = parseFloat(scope.$eval(numberExp)); if (!isNaN(value)) { //if explicit number rule such as 1, 2, 3... is defined, just use it. Otherwise, //check it against pluralization rules in $locale service if (!whens[value]) value = $locale.pluralCat(value - offset); return whensExpFns[value](scope, element, true); } else { return ''; } }, function(newVal) { element.text(newVal); }); } }; }]; /** * @ngdoc directive * @name ng.directive:ngRepeat * * @description * The `ngRepeat` directive instantiates a template once per item from a collection. Each template * instance gets its own scope, where the given loop variable is set to the current collection item, * and `$index` is set to the item index or key. * * Special properties are exposed on the local scope of each template instance, including: * * * `$index` – `{number}` – iterator offset of the repeated element (0..length-1) * * `$first` – `{boolean}` – true if the repeated element is first in the iterator. * * `$middle` – `{boolean}` – true if the repeated element is between the first and last in the iterator. * * `$last` – `{boolean}` – true if the repeated element is last in the iterator. * * * @element ANY * @scope * @priority 1000 * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. Two * formats are currently supported: * * * `variable in expression` – where variable is the user defined loop variable and `expression` * is a scope expression giving the collection to enumerate. * * For example: `track in cd.tracks`. * * * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers, * and `expression` is the scope expression giving the collection to enumerate. * * For example: `(name, age) in {'adam':10, 'amalie':12}`. * * @example * This example initializes the scope to a list of names and * then uses `ngRepeat` to display every person: <doc:example> <doc:source> <div ng-init="friends = [{name:'John', age:25}, {name:'Mary', age:28}]"> I have {{friends.length}} friends. They are: <ul> <li ng-repeat="friend in friends"> [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old. </li> </ul> </div> </doc:source> <doc:scenario> it('should check ng-repeat', function() { var r = using('.doc-example-live').repeater('ul li'); expect(r.count()).toBe(2); expect(r.row(0)).toEqual(["1","John","25"]); expect(r.row(1)).toEqual(["2","Mary","28"]); }); </doc:scenario> </doc:example> */ var ngRepeatDirective = ngDirective({ transclude: 'element', priority: 1000, terminal: true, compile: function(element, attr, linker) { return function(scope, iterStartElement, attr){ var expression = attr.ngRepeat; var match = expression.match(/^\s*(.+)\s+in\s+(.*)\s*$/), lhs, rhs, valueIdent, keyIdent; if (! match) { throw Error("Expected ngRepeat in form of '_item_ in _collection_' but got '" + expression + "'."); } lhs = match[1]; rhs = match[2]; match = lhs.match(/^(?:([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\))$/); if (!match) { throw Error("'item' in 'item in collection' should be identifier or (key, value) but got '" + lhs + "'."); } valueIdent = match[3] || match[1]; keyIdent = match[2]; // Store a list of elements from previous run. This is a hash where key is the item from the // iterator, and the value is an array of objects with following properties. // - scope: bound scope // - element: previous element. // - index: position // We need an array of these objects since the same object can be returned from the iterator. // We expect this to be a rare case. var lastOrder = new HashQueueMap(); scope.$watch(function(scope){ var index, length, collection = scope.$eval(rhs), collectionLength = size(collection, true), childScope, // Same as lastOrder but it has the current state. It will become the // lastOrder on the next iteration. nextOrder = new HashQueueMap(), key, value, // key/value of iteration array, last, // last object information {scope, element, index} cursor = iterStartElement; // current position of the node if (!isArray(collection)) { // if object, extract keys, sort them and use to determine order of iteration over obj props array = []; for(key in collection) { if (collection.hasOwnProperty(key) && key.charAt(0) != '$') { array.push(key); } } array.sort(); } else { array = collection || []; } // we are not using forEach for perf reasons (trying to avoid #call) for (index = 0, length = array.length; index < length; index++) { key = (collection === array) ? index : array[index]; value = collection[key]; last = lastOrder.shift(value); if (last) { // if we have already seen this object, then we need to reuse the // associated scope/element childScope = last.scope; nextOrder.push(value, last); if (index === last.index) { // do nothing cursor = last.element; } else { // existing item which got moved last.index = index; // This may be a noop, if the element is next, but I don't know of a good way to // figure this out, since it would require extra DOM access, so let's just hope that // the browsers realizes that it is noop, and treats it as such. cursor.after(last.element); cursor = last.element; } } else { // new item which we don't know about childScope = scope.$new(); } childScope[valueIdent] = value; if (keyIdent) childScope[keyIdent] = key; childScope.$index = index; childScope.$first = (index === 0); childScope.$last = (index === (collectionLength - 1)); childScope.$middle = !(childScope.$first || childScope.$last); if (!last) { linker(childScope, function(clone){ cursor.after(clone); last = { scope: childScope, element: (cursor = clone), index: index }; nextOrder.push(value, last); }); } } //shrink children for (key in lastOrder) { if (lastOrder.hasOwnProperty(key)) { array = lastOrder[key]; while(array.length) { value = array.pop(); value.element.remove(); value.scope.$destroy(); } } } lastOrder = nextOrder; }); }; } }); /** * @ngdoc directive * @name ng.directive:ngShow * * @description * The `ngShow` and `ngHide` directives show or hide a portion of the DOM tree (HTML) * conditionally. * * @element ANY * @param {expression} ngShow If the {@link guide/expression expression} is truthy * then the element is shown or hidden respectively. * * @example <doc:example> <doc:source> Click me: <input type="checkbox" ng-model="checked"><br/> Show: <span ng-show="checked">I show up when your checkbox is checked.</span> <br/> Hide: <span ng-hide="checked">I hide when your checkbox is checked.</span> </doc:source> <doc:scenario> it('should check ng-show / ng-hide', function() { expect(element('.doc-example-live span:first:hidden').count()).toEqual(1); expect(element('.doc-example-live span:last:visible').count()).toEqual(1); input('checked').check(); expect(element('.doc-example-live span:first:visible').count()).toEqual(1); expect(element('.doc-example-live span:last:hidden').count()).toEqual(1); }); </doc:scenario> </doc:example> */ //TODO(misko): refactor to remove element from the DOM var ngShowDirective = ngDirective(function(scope, element, attr){ scope.$watch(attr.ngShow, function(value){ element.css('display', toBoolean(value) ? '' : 'none'); }); }); /** * @ngdoc directive * @name ng.directive:ngHide * * @description * The `ngHide` and `ngShow` directives hide or show a portion * of the HTML conditionally. * * @element ANY * @param {expression} ngHide If the {@link guide/expression expression} truthy then * the element is shown or hidden respectively. * * @example <doc:example> <doc:source> Click me: <input type="checkbox" ng-model="checked"><br/> Show: <span ng-show="checked">I show up when you checkbox is checked?</span> <br/> Hide: <span ng-hide="checked">I hide when you checkbox is checked?</span> </doc:source> <doc:scenario> it('should check ng-show / ng-hide', function() { expect(element('.doc-example-live span:first:hidden').count()).toEqual(1); expect(element('.doc-example-live span:last:visible').count()).toEqual(1); input('checked').check(); expect(element('.doc-example-live span:first:visible').count()).toEqual(1); expect(element('.doc-example-live span:last:hidden').count()).toEqual(1); }); </doc:scenario> </doc:example> */ //TODO(misko): refactor to remove element from the DOM var ngHideDirective = ngDirective(function(scope, element, attr){ scope.$watch(attr.ngHide, function(value){ element.css('display', toBoolean(value) ? 'none' : ''); }); }); /** * @ngdoc directive * @name ng.directive:ngStyle * * @description * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally. * * @element ANY * @param {expression} ngStyle {@link guide/expression Expression} which evals to an * object whose keys are CSS style names and values are corresponding values for those CSS * keys. * * @example <example> <file name="index.html"> <input type="button" value="set" ng-click="myStyle={color:'red'}"> <input type="button" value="clear" ng-click="myStyle={}"> <br/> <span ng-style="myStyle">Sample Text</span> <pre>myStyle={{myStyle}}</pre> </file> <file name="style.css"> span { color: black; } </file> <file name="scenario.js"> it('should check ng-style', function() { expect(element('.doc-example-live span').css('color')).toBe('rgb(0, 0, 0)'); element('.doc-example-live :button[value=set]').click(); expect(element('.doc-example-live span').css('color')).toBe('rgb(255, 0, 0)'); element('.doc-example-live :button[value=clear]').click(); expect(element('.doc-example-live span').css('color')).toBe('rgb(0, 0, 0)'); }); </file> </example> */ var ngStyleDirective = ngDirective(function(scope, element, attr) { scope.$watch(attr.ngStyle, function(newStyles, oldStyles) { if (oldStyles && (newStyles !== oldStyles)) { forEach(oldStyles, function(val, style) { element.css(style, '');}); } if (newStyles) element.css(newStyles); }, true); }); /** * @ngdoc directive * @name ng.directive:ngSwitch * @restrict EA * * @description * Conditionally change the DOM structure. * * @usageContent * <ANY ng-switch-when="matchValue1">...</ANY> * <ANY ng-switch-when="matchValue2">...</ANY> * ... * <ANY ng-switch-default>...</ANY> * * @scope * @param {*} ngSwitch|on expression to match against <tt>ng-switch-when</tt>. * @paramDescription * On child elments add: * * * `ngSwitchWhen`: the case statement to match against. If match then this * case will be displayed. * * `ngSwitchDefault`: the default case when no other casses match. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.items = ['settings', 'home', 'other']; $scope.selection = $scope.items[0]; } </script> <div ng-controller="Ctrl"> <select ng-model="selection" ng-options="item for item in items"> </select> <tt>selection={{selection}}</tt> <hr/> <div ng-switch on="selection" > <div ng-switch-when="settings">Settings Div</div> <span ng-switch-when="home">Home Span</span> <span ng-switch-default>default</span> </div> </div> </doc:source> <doc:scenario> it('should start in settings', function() { expect(element('.doc-example-live [ng-switch]').text()).toMatch(/Settings Div/); }); it('should change to home', function() { select('selection').option('home'); expect(element('.doc-example-live [ng-switch]').text()).toMatch(/Home Span/); }); it('should select deafault', function() { select('selection').option('other'); expect(element('.doc-example-live [ng-switch]').text()).toMatch(/default/); }); </doc:scenario> </doc:example> */ var NG_SWITCH = 'ng-switch'; var ngSwitchDirective = valueFn({ restrict: 'EA', compile: function(element, attr) { var watchExpr = attr.ngSwitch || attr.on, cases = {}; element.data(NG_SWITCH, cases); return function(scope, element){ var selectedTransclude, selectedElement, selectedScope; scope.$watch(watchExpr, function(value) { if (selectedElement) { selectedScope.$destroy(); selectedElement.remove(); selectedElement = selectedScope = null; } if ((selectedTransclude = cases['!' + value] || cases['?'])) { scope.$eval(attr.change); selectedScope = scope.$new(); selectedTransclude(selectedScope, function(caseElement) { selectedElement = caseElement; element.append(caseElement); }); } }); }; } }); var ngSwitchWhenDirective = ngDirective({ transclude: 'element', priority: 500, compile: function(element, attrs, transclude) { var cases = element.inheritedData(NG_SWITCH); assertArg(cases); cases['!' + attrs.ngSwitchWhen] = transclude; } }); var ngSwitchDefaultDirective = ngDirective({ transclude: 'element', priority: 500, compile: function(element, attrs, transclude) { var cases = element.inheritedData(NG_SWITCH); assertArg(cases); cases['?'] = transclude; } }); /** * @ngdoc directive * @name ng.directive:ngTransclude * * @description * Insert the transcluded DOM here. * * @element ANY * * @example <doc:example module="transclude"> <doc:source> <script> function Ctrl($scope) { $scope.title = 'Lorem Ipsum'; $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...'; } angular.module('transclude', []) .directive('pane', function(){ return { restrict: 'E', transclude: true, scope: 'isolate', locals: { title:'bind' }, template: '<div style="border: 1px solid black;">' + '<div style="background-color: gray">{{title}}</div>' + '<div ng-transclude></div>' + '</div>' }; }); </script> <div ng-controller="Ctrl"> <input ng-model="title"><br> <textarea ng-model="text"></textarea> <br/> <pane title="{{title}}">{{text}}</pane> </div> </doc:source> <doc:scenario> it('should have transcluded', function() { input('title').enter('TITLE'); input('text').enter('TEXT'); expect(binding('title')).toEqual('TITLE'); expect(binding('text')).toEqual('TEXT'); }); </doc:scenario> </doc:example> * */ var ngTranscludeDirective = ngDirective({ controller: ['$transclude', '$element', function($transclude, $element) { $transclude(function(clone) { $element.append(clone); }); }] }); /** * @ngdoc directive * @name ng.directive:ngView * @restrict ECA * * @description * # Overview * `ngView` is a directive that complements the {@link ng.$route $route} service by * including the rendered template of the current route into the main layout (`index.html`) file. * Every time the current route changes, the included view changes with it according to the * configuration of the `$route` service. * * @scope * @example <example module="ngView"> <file name="index.html"> <div ng-controller="MainCntl"> Choose: <a href="Book/Moby">Moby</a> | <a href="Book/Moby/ch/1">Moby: Ch1</a> | <a href="Book/Gatsby">Gatsby</a> | <a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> | <a href="Book/Scarlet">Scarlet Letter</a><br/> <div ng-view></div> <hr /> <pre>$location.path() = {{$location.path()}}</pre> <pre>$route.current.template = {{$route.current.template}}</pre> <pre>$route.current.params = {{$route.current.params}}</pre> <pre>$route.current.scope.name = {{$route.current.scope.name}}</pre> <pre>$routeParams = {{$routeParams}}</pre> </div> </file> <file name="book.html"> controller: {{name}}<br /> Book Id: {{params.bookId}}<br /> </file> <file name="chapter.html"> controller: {{name}}<br /> Book Id: {{params.bookId}}<br /> Chapter Id: {{params.chapterId}} </file> <file name="script.js"> angular.module('ngView', [], function($routeProvider, $locationProvider) { $routeProvider.when('/Book/:bookId', { templateUrl: 'book.html', controller: BookCntl }); $routeProvider.when('/Book/:bookId/ch/:chapterId', { templateUrl: 'chapter.html', controller: ChapterCntl }); // configure html5 to get links working on jsfiddle $locationProvider.html5Mode(true); }); function MainCntl($scope, $route, $routeParams, $location) { $scope.$route = $route; $scope.$location = $location; $scope.$routeParams = $routeParams; } function BookCntl($scope, $routeParams) { $scope.name = "BookCntl"; $scope.params = $routeParams; } function ChapterCntl($scope, $routeParams) { $scope.name = "ChapterCntl"; $scope.params = $routeParams; } </file> <file name="scenario.js"> it('should load and compile correct template', function() { element('a:contains("Moby: Ch1")').click(); var content = element('.doc-example-live [ng-view]').text(); expect(content).toMatch(/controller\: ChapterCntl/); expect(content).toMatch(/Book Id\: Moby/); expect(content).toMatch(/Chapter Id\: 1/); element('a:contains("Scarlet")').click(); content = element('.doc-example-live [ng-view]').text(); expect(content).toMatch(/controller\: BookCntl/); expect(content).toMatch(/Book Id\: Scarlet/); }); </file> </example> */ /** * @ngdoc event * @name ng.directive:ngView#$viewContentLoaded * @eventOf ng.directive:ngView * @eventType emit on the current ngView scope * @description * Emitted every time the ngView content is reloaded. */ var ngViewDirective = ['$http', '$templateCache', '$route', '$anchorScroll', '$compile', '$controller', function($http, $templateCache, $route, $anchorScroll, $compile, $controller) { return { restrict: 'ECA', terminal: true, link: function(scope, element, attr) { var lastScope, onloadExp = attr.onload || ''; scope.$on('$routeChangeSuccess', update); update(); function destroyLastScope() { if (lastScope) { lastScope.$destroy(); lastScope = null; } } function clearContent() { element.html(''); destroyLastScope(); } function update() { var locals = $route.current && $route.current.locals, template = locals && locals.$template; if (template) { element.html(template); destroyLastScope(); var link = $compile(element.contents()), current = $route.current, controller; lastScope = current.scope = scope.$new(); if (current.controller) { locals.$scope = lastScope; controller = $controller(current.controller, locals); element.contents().data('$ngControllerController', controller); } link(lastScope); lastScope.$emit('$viewContentLoaded'); lastScope.$eval(onloadExp); // $anchorScroll might listen on event... $anchorScroll(); } else { clearContent(); } } } }; }]; /** * @ngdoc directive * @name ng.directive:script * * @description * Load content of a script tag, with type `text/ng-template`, into `$templateCache`, so that the * template can be used by `ngInclude`, `ngView` or directive templates. * * @restrict E * @param {'text/ng-template'} type must be set to `'text/ng-template'` * * @example <doc:example> <doc:source> <script type="text/ng-template" id="/tpl.html"> Content of the template. </script> <a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a> <div id="tpl-content" ng-include src="currentTpl"></div> </doc:source> <doc:scenario> it('should load template defined inside script tag', function() { element('#tpl-link').click(); expect(element('#tpl-content').text()).toMatch(/Content of the template/); }); </doc:scenario> </doc:example> */ var scriptDirective = ['$templateCache', function($templateCache) { return { restrict: 'E', terminal: true, compile: function(element, attr) { if (attr.type == 'text/ng-template') { var templateUrl = attr.id, // IE is not consistent, in scripts we have to read .text but in other nodes we have to read .textContent text = element[0].text; $templateCache.put(templateUrl, text); } } }; }]; /** * @ngdoc directive * @name ng.directive:select * @restrict E * * @description * HTML `SELECT` element with angular data-binding. * * # `ngOptions` * * Optionally `ngOptions` attribute can be used to dynamically generate a list of `<option>` * elements for a `<select>` element using an array or an object obtained by evaluating the * `ngOptions` expression. *˝˝ * When an item in the select menu is select, the value of array element or object property * represented by the selected option will be bound to the model identified by the `ngModel` * directive of the parent select element. * * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can * be nested into the `<select>` element. This element will then represent `null` or "not selected" * option. See example below for demonstration. * * Note: `ngOptions` provides iterator facility for `<option>` element which should be used instead * of {@link ng.directive:ngRepeat ngRepeat} when you want the * `select` model to be bound to a non-string value. This is because an option element can currently * be bound to string values only. * * @param {string} name assignable expression to data-bind to. * @param {string=} required The control is considered valid only if value is entered. * @param {comprehension_expression=} ngOptions in one of the following forms: * * * for array data sources: * * `label` **`for`** `value` **`in`** `array` * * `select` **`as`** `label` **`for`** `value` **`in`** `array` * * `label` **`group by`** `group` **`for`** `value` **`in`** `array` * * `select` **`as`** `label` **`group by`** `group` **`for`** `value` **`in`** `array` * * for object data sources: * * `label` **`for (`**`key` **`,`** `value`**`) in`** `object` * * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object` * * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object` * * `select` **`as`** `label` **`group by`** `group` * **`for` `(`**`key`**`,`** `value`**`) in`** `object` * * Where: * * * `array` / `object`: an expression which evaluates to an array / object to iterate over. * * `value`: local variable which will refer to each item in the `array` or each property value * of `object` during iteration. * * `key`: local variable which will refer to a property name in `object` during iteration. * * `label`: The result of this expression will be the label for `<option>` element. The * `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`). * * `select`: The result of this expression will be bound to the model of the parent `<select>` * element. If not specified, `select` expression will default to `value`. * * `group`: The result of this expression will be used to group options using the `<optgroup>` * DOM element. * * @example <doc:example> <doc:source> <script> function MyCntrl($scope) { $scope.colors = [ {name:'black', shade:'dark'}, {name:'white', shade:'light'}, {name:'red', shade:'dark'}, {name:'blue', shade:'dark'}, {name:'yellow', shade:'light'} ]; $scope.color = $scope.colors[2]; // red } </script> <div ng-controller="MyCntrl"> <ul> <li ng-repeat="color in colors"> Name: <input ng-model="color.name"> [<a href ng-click="colors.splice($index, 1)">X</a>] </li> <li> [<a href ng-click="colors.push({})">add</a>] </li> </ul> <hr/> Color (null not allowed): <select ng-model="color" ng-options="c.name for c in colors"></select><br> Color (null allowed): <span class="nullable"> <select ng-model="color" ng-options="c.name for c in colors"> <option value="">-- chose color --</option> </select> </span><br/> Color grouped by shade: <select ng-model="color" ng-options="c.name group by c.shade for c in colors"> </select><br/> Select <a href ng-click="color={name:'not in list'}">bogus</a>.<br> <hr/> Currently selected: {{ {selected_color:color} }} <div style="border:solid 1px black; height:20px" ng-style="{'background-color':color.name}"> </div> </div> </doc:source> <doc:scenario> it('should check ng-options', function() { expect(binding('{selected_color:color}')).toMatch('red'); select('color').option('0'); expect(binding('{selected_color:color}')).toMatch('black'); using('.nullable').select('color').option(''); expect(binding('{selected_color:color}')).toMatch('null'); }); </doc:scenario> </doc:example> */ var ngOptionsDirective = valueFn({ terminal: true }); var selectDirective = ['$compile', '$parse', function($compile, $parse) { //00001111100000000000222200000000000000000000003333000000000000044444444444444444000000000555555555555555550000000666666666666666660000000000000007777 var NG_OPTIONS_REGEXP = /^\s*(.*?)(?:\s+as\s+(.*?))?(?:\s+group\s+by\s+(.*))?\s+for\s+(?:([\$\w][\$\w\d]*)|(?:\(\s*([\$\w][\$\w\d]*)\s*,\s*([\$\w][\$\w\d]*)\s*\)))\s+in\s+(.*)$/, nullModelCtrl = {$setViewValue: noop}; return { restrict: 'E', require: ['select', '?ngModel'], controller: ['$element', '$scope', '$attrs', function($element, $scope, $attrs) { var self = this, optionsMap = {}, ngModelCtrl = nullModelCtrl, nullOption, unknownOption; self.databound = $attrs.ngModel; self.init = function(ngModelCtrl_, nullOption_, unknownOption_) { ngModelCtrl = ngModelCtrl_; nullOption = nullOption_; unknownOption = unknownOption_; } self.addOption = function(value) { optionsMap[value] = true; if (ngModelCtrl.$viewValue == value) { $element.val(value); if (unknownOption.parent()) unknownOption.remove(); } }; self.removeOption = function(value) { if (this.hasOption(value)) { delete optionsMap[value]; if (ngModelCtrl.$viewValue == value) { this.renderUnknownOption(value); } } }; self.renderUnknownOption = function(val) { var unknownVal = '? ' + hashKey(val) + ' ?'; unknownOption.val(unknownVal); $element.prepend(unknownOption); $element.val(unknownVal); unknownOption.prop('selected', true); // needed for IE } self.hasOption = function(value) { return optionsMap.hasOwnProperty(value); } $scope.$on('$destroy', function() { // disable unknown option so that we don't do work when the whole select is being destroyed self.renderUnknownOption = noop; }); }], link: function(scope, element, attr, ctrls) { // if ngModel is not defined, we don't need to do anything if (!ctrls[1]) return; var selectCtrl = ctrls[0], ngModelCtrl = ctrls[1], multiple = attr.multiple, optionsExp = attr.ngOptions, nullOption = false, // if false, user will not be able to select it (used by ngOptions) emptyOption, // we can't just jqLite('<option>') since jqLite is not smart enough // to create it in <select> and IE barfs otherwise. optionTemplate = jqLite(document.createElement('option')), optGroupTemplate =jqLite(document.createElement('optgroup')), unknownOption = optionTemplate.clone(); // find "null" option for(var i = 0, children = element.children(), ii = children.length; i < ii; i++) { if (children[i].value == '') { emptyOption = nullOption = children.eq(i); break; } } selectCtrl.init(ngModelCtrl, nullOption, unknownOption); // required validator if (multiple && (attr.required || attr.ngRequired)) { var requiredValidator = function(value) { ngModelCtrl.$setValidity('required', !attr.required || (value && value.length)); return value; }; ngModelCtrl.$parsers.push(requiredValidator); ngModelCtrl.$formatters.unshift(requiredValidator); attr.$observe('required', function() { requiredValidator(ngModelCtrl.$viewValue); }); } if (optionsExp) Options(scope, element, ngModelCtrl); else if (multiple) Multiple(scope, element, ngModelCtrl); else Single(scope, element, ngModelCtrl, selectCtrl); //////////////////////////// function Single(scope, selectElement, ngModelCtrl, selectCtrl) { ngModelCtrl.$render = function() { var viewValue = ngModelCtrl.$viewValue; if (selectCtrl.hasOption(viewValue)) { if (unknownOption.parent()) unknownOption.remove(); selectElement.val(viewValue); if (viewValue === '') emptyOption.prop('selected', true); // to make IE9 happy } else { if (isUndefined(viewValue) && emptyOption) { selectElement.val(''); } else { selectCtrl.renderUnknownOption(viewValue); } } }; selectElement.bind('change', function() { scope.$apply(function() { if (unknownOption.parent()) unknownOption.remove(); ngModelCtrl.$setViewValue(selectElement.val()); }); }); } function Multiple(scope, selectElement, ctrl) { var lastView; ctrl.$render = function() { var items = new HashMap(ctrl.$viewValue); forEach(selectElement.children(), function(option) { option.selected = isDefined(items.get(option.value)); }); }; // we have to do it on each watch since ngModel watches reference, but // we need to work of an array, so we need to see if anything was inserted/removed scope.$watch(function() { if (!equals(lastView, ctrl.$viewValue)) { lastView = copy(ctrl.$viewValue); ctrl.$render(); } }); selectElement.bind('change', function() { scope.$apply(function() { var array = []; forEach(selectElement.children(), function(option) { if (option.selected) { array.push(option.value); } }); ctrl.$setViewValue(array); }); }); } function Options(scope, selectElement, ctrl) { var match; if (! (match = optionsExp.match(NG_OPTIONS_REGEXP))) { throw Error( "Expected ngOptions in form of '_select_ (as _label_)? for (_key_,)?_value_ in _collection_'" + " but got '" + optionsExp + "'."); } var displayFn = $parse(match[2] || match[1]), valueName = match[4] || match[6], keyName = match[5], groupByFn = $parse(match[3] || ''), valueFn = $parse(match[2] ? match[1] : valueName), valuesFn = $parse(match[7]), // This is an array of array of existing option groups in DOM. We try to reuse these if possible // optionGroupsCache[0] is the options with no option group // optionGroupsCache[?][0] is the parent: either the SELECT or OPTGROUP element optionGroupsCache = [[{element: selectElement, label:''}]]; if (nullOption) { // compile the element since there might be bindings in it $compile(nullOption)(scope); // remove the class, which is added automatically because we recompile the element and it // becomes the compilation root nullOption.removeClass('ng-scope'); // we need to remove it before calling selectElement.html('') because otherwise IE will // remove the label from the element. wtf? nullOption.remove(); } // clear contents, we'll add what's needed based on the model selectElement.html(''); selectElement.bind('change', function() { scope.$apply(function() { var optionGroup, collection = valuesFn(scope) || [], locals = {}, key, value, optionElement, index, groupIndex, length, groupLength; if (multiple) { value = []; for (groupIndex = 0, groupLength = optionGroupsCache.length; groupIndex < groupLength; groupIndex++) { // list of options for that group. (first item has the parent) optionGroup = optionGroupsCache[groupIndex]; for(index = 1, length = optionGroup.length; index < length; index++) { if ((optionElement = optionGroup[index].element)[0].selected) { key = optionElement.val(); if (keyName) locals[keyName] = key; locals[valueName] = collection[key]; value.push(valueFn(scope, locals)); } } } } else { key = selectElement.val(); if (key == '?') { value = undefined; } else if (key == ''){ value = null; } else { locals[valueName] = collection[key]; if (keyName) locals[keyName] = key; value = valueFn(scope, locals); } } ctrl.$setViewValue(value); }); }); ctrl.$render = render; // TODO(vojta): can't we optimize this ? scope.$watch(render); function render() { var optionGroups = {'':[]}, // Temporary location for the option groups before we render them optionGroupNames = [''], optionGroupName, optionGroup, option, existingParent, existingOptions, existingOption, modelValue = ctrl.$modelValue, values = valuesFn(scope) || [], keys = keyName ? sortedKeys(values) : values, groupLength, length, groupIndex, index, locals = {}, selected, selectedSet = false, // nothing is selected yet lastElement, element; if (multiple) { selectedSet = new HashMap(modelValue); } else if (modelValue === null || nullOption) { // if we are not multiselect, and we are null then we have to add the nullOption optionGroups[''].push({selected:modelValue === null, id:'', label:''}); selectedSet = true; } // We now build up the list of options we need (we merge later) for (index = 0; length = keys.length, index < length; index++) { locals[valueName] = values[keyName ? locals[keyName]=keys[index]:index]; optionGroupName = groupByFn(scope, locals) || ''; if (!(optionGroup = optionGroups[optionGroupName])) { optionGroup = optionGroups[optionGroupName] = []; optionGroupNames.push(optionGroupName); } if (multiple) { selected = selectedSet.remove(valueFn(scope, locals)) != undefined; } else { selected = modelValue === valueFn(scope, locals); selectedSet = selectedSet || selected; // see if at least one item is selected } optionGroup.push({ id: keyName ? keys[index] : index, // either the index into array or key from object label: displayFn(scope, locals) || '', // what will be seen by the user selected: selected // determine if we should be selected }); } if (!multiple && !selectedSet) { // nothing was selected, we have to insert the undefined item optionGroups[''].unshift({id:'?', label:'', selected:true}); } // Now we need to update the list of DOM nodes to match the optionGroups we computed above for (groupIndex = 0, groupLength = optionGroupNames.length; groupIndex < groupLength; groupIndex++) { // current option group name or '' if no group optionGroupName = optionGroupNames[groupIndex]; // list of options for that group. (first item has the parent) optionGroup = optionGroups[optionGroupName]; if (optionGroupsCache.length <= groupIndex) { // we need to grow the optionGroups existingParent = { element: optGroupTemplate.clone().attr('label', optionGroupName), label: optionGroup.label }; existingOptions = [existingParent]; optionGroupsCache.push(existingOptions); selectElement.append(existingParent.element); } else { existingOptions = optionGroupsCache[groupIndex]; existingParent = existingOptions[0]; // either SELECT (no group) or OPTGROUP element // update the OPTGROUP label if not the same. if (existingParent.label != optionGroupName) { existingParent.element.attr('label', existingParent.label = optionGroupName); } } lastElement = null; // start at the beginning for(index = 0, length = optionGroup.length; index < length; index++) { option = optionGroup[index]; if ((existingOption = existingOptions[index+1])) { // reuse elements lastElement = existingOption.element; if (existingOption.label !== option.label) { lastElement.text(existingOption.label = option.label); } if (existingOption.id !== option.id) { lastElement.val(existingOption.id = option.id); } if (existingOption.element.selected !== option.selected) { lastElement.prop('selected', (existingOption.selected = option.selected)); } } else { // grow elements // if it's a null option if (option.id === '' && nullOption) { // put back the pre-compiled element element = nullOption; } else { // jQuery(v1.4.2) Bug: We should be able to chain the method calls, but // in this version of jQuery on some browser the .text() returns a string // rather then the element. (element = optionTemplate.clone()) .val(option.id) .attr('selected', option.selected) .text(option.label); } existingOptions.push(existingOption = { element: element, label: option.label, id: option.id, selected: option.selected }); if (lastElement) { lastElement.after(element); } else { existingParent.element.append(element); } lastElement = element; } } // remove any excessive OPTIONs in a group index++; // increment since the existingOptions[0] is parent element not OPTION while(existingOptions.length > index) { existingOptions.pop().element.remove(); } } // remove any excessive OPTGROUPs from select while(optionGroupsCache.length > groupIndex) { optionGroupsCache.pop()[0].element.remove(); } } } } } }]; var optionDirective = ['$interpolate', function($interpolate) { var nullSelectCtrl = { addOption: noop, removeOption: noop }; return { restrict: 'E', priority: 100, compile: function(element, attr) { if (isUndefined(attr.value)) { var interpolateFn = $interpolate(element.text(), true); if (!interpolateFn) { attr.$set('value', element.text()); } } return function (scope, element, attr) { var selectCtrlName = '$selectController', parent = element.parent(), selectCtrl = parent.data(selectCtrlName) || parent.parent().data(selectCtrlName); // in case we are in optgroup if (selectCtrl && selectCtrl.databound) { // For some reason Opera defaults to true and if not overridden this messes up the repeater. // We don't want the view to drive the initialization of the model anyway. element.prop('selected', false); } else { selectCtrl = nullSelectCtrl; } if (interpolateFn) { scope.$watch(interpolateFn, function(newVal, oldVal) { attr.$set('value', newVal); if (newVal !== oldVal) selectCtrl.removeOption(oldVal); selectCtrl.addOption(newVal); }); } else { selectCtrl.addOption(attr.value); } element.bind('$destroy', function() { selectCtrl.removeOption(attr.value); }); }; } } }]; var styleDirective = valueFn({ restrict: 'E', terminal: true }); /** * Setup file for the Scenario. * Must be first in the compilation/bootstrap list. */ // Public namespace angular.scenario = angular.scenario || {}; /** * Defines a new output format. * * @param {string} name the name of the new output format * @param {function()} fn function(context, runner) that generates the output */ angular.scenario.output = angular.scenario.output || function(name, fn) { angular.scenario.output[name] = fn; }; /** * Defines a new DSL statement. If your factory function returns a Future * it's returned, otherwise the result is assumed to be a map of functions * for chaining. Chained functions are subject to the same rules. * * Note: All functions on the chain are bound to the chain scope so values * set on "this" in your statement function are available in the chained * functions. * * @param {string} name The name of the statement * @param {function()} fn Factory function(), return a function for * the statement. */ angular.scenario.dsl = angular.scenario.dsl || function(name, fn) { angular.scenario.dsl[name] = function() { function executeStatement(statement, args) { var result = statement.apply(this, args); if (angular.isFunction(result) || result instanceof angular.scenario.Future) return result; var self = this; var chain = angular.extend({}, result); angular.forEach(chain, function(value, name) { if (angular.isFunction(value)) { chain[name] = function() { return executeStatement.call(self, value, arguments); }; } else { chain[name] = value; } }); return chain; } var statement = fn.apply(this, arguments); return function() { return executeStatement.call(this, statement, arguments); }; }; }; /** * Defines a new matcher for use with the expects() statement. The value * this.actual (like in Jasmine) is available in your matcher to compare * against. Your function should return a boolean. The future is automatically * created for you. * * @param {string} name The name of the matcher * @param {function()} fn The matching function(expected). */ angular.scenario.matcher = angular.scenario.matcher || function(name, fn) { angular.scenario.matcher[name] = function(expected) { var prefix = 'expect ' + this.future.name + ' '; if (this.inverse) { prefix += 'not '; } var self = this; this.addFuture(prefix + name + ' ' + angular.toJson(expected), function(done) { var error; self.actual = self.future.value; if ((self.inverse && fn.call(self, expected)) || (!self.inverse && !fn.call(self, expected))) { error = 'expected ' + angular.toJson(expected) + ' but was ' + angular.toJson(self.actual); } done(error); }); }; }; /** * Initialize the scenario runner and run ! * * Access global window and document object * Access $runner through closure * * @param {Object=} config Config options */ angular.scenario.setUpAndRun = function(config) { var href = window.location.href; var body = _jQuery(document.body); var output = []; var objModel = new angular.scenario.ObjectModel($runner); if (config && config.scenario_output) { output = config.scenario_output.split(','); } angular.forEach(angular.scenario.output, function(fn, name) { if (!output.length || indexOf(output,name) != -1) { var context = body.append('<div></div>').find('div:last'); context.attr('id', name); fn.call({}, context, $runner, objModel); } }); if (!/^http/.test(href) && !/^https/.test(href)) { body.append('<p id="system-error"></p>'); body.find('#system-error').text( 'Scenario runner must be run using http or https. The protocol ' + href.split(':')[0] + ':// is not supported.' ); return; } var appFrame = body.append('<div id="application"></div>').find('#application'); var application = new angular.scenario.Application(appFrame); $runner.on('RunnerEnd', function() { appFrame.css('display', 'none'); appFrame.find('iframe').attr('src', 'about:blank'); }); $runner.on('RunnerError', function(error) { if (window.console) { console.log(formatException(error)); } else { // Do something for IE alert(error); } }); $runner.run(application); }; /** * Iterates through list with iterator function that must call the * continueFunction to continute iterating. * * @param {Array} list list to iterate over * @param {function()} iterator Callback function(value, continueFunction) * @param {function()} done Callback function(error, result) called when * iteration finishes or an error occurs. */ function asyncForEach(list, iterator, done) { var i = 0; function loop(error, index) { if (index && index > i) { i = index; } if (error || i >= list.length) { done(error); } else { try { iterator(list[i++], loop); } catch (e) { done(e); } } } loop(); } /** * Formats an exception into a string with the stack trace, but limits * to a specific line length. * * @param {Object} error The exception to format, can be anything throwable * @param {Number=} [maxStackLines=5] max lines of the stack trace to include * default is 5. */ function formatException(error, maxStackLines) { maxStackLines = maxStackLines || 5; var message = error.toString(); if (error.stack) { var stack = error.stack.split('\n'); if (stack[0].indexOf(message) === -1) { maxStackLines++; stack.unshift(error.message); } message = stack.slice(0, maxStackLines).join('\n'); } return message; } /** * Returns a function that gets the file name and line number from a * location in the stack if available based on the call site. * * Note: this returns another function because accessing .stack is very * expensive in Chrome. * * @param {Number} offset Number of stack lines to skip */ function callerFile(offset) { var error = new Error(); return function() { var line = (error.stack || '').split('\n')[offset]; // Clean up the stack trace line if (line) { if (line.indexOf('@') !== -1) { // Firefox line = line.substring(line.indexOf('@')+1); } else { // Chrome line = line.substring(line.indexOf('(')+1).replace(')', ''); } } return line || ''; }; } /** * Triggers a browser event. Attempts to choose the right event if one is * not specified. * * @param {Object} element Either a wrapped jQuery/jqLite node or a DOMElement * @param {string} type Optional event type. * @param {Array.<string>=} keys Optional list of pressed keys * (valid values: 'alt', 'meta', 'shift', 'ctrl') */ function browserTrigger(element, type, keys) { if (element && !element.nodeName) element = element[0]; if (!element) return; if (!type) { type = { 'text': 'change', 'textarea': 'change', 'hidden': 'change', 'password': 'change', 'button': 'click', 'submit': 'click', 'reset': 'click', 'image': 'click', 'checkbox': 'click', 'radio': 'click', 'select-one': 'change', 'select-multiple': 'change' }[lowercase(element.type)] || 'click'; } if (lowercase(nodeName_(element)) == 'option') { element.parentNode.value = element.value; element = element.parentNode; type = 'change'; } keys = keys || []; function pressed(key) { return indexOf(keys, key) !== -1; } if (msie < 9) { switch(element.type) { case 'radio': case 'checkbox': element.checked = !element.checked; break; } // WTF!!! Error: Unspecified error. // Don't know why, but some elements when detached seem to be in inconsistent state and // calling .fireEvent() on them will result in very unhelpful error (Error: Unspecified error) // forcing the browser to compute the element position (by reading its CSS) // puts the element in consistent state. element.style.posLeft; // TODO(vojta): create event objects with pressed keys to get it working on IE<9 var ret = element.fireEvent('on' + type); if (lowercase(element.type) == 'submit') { while(element) { if (lowercase(element.nodeName) == 'form') { element.fireEvent('onsubmit'); break; } element = element.parentNode; } } return ret; } else { var evnt = document.createEvent('MouseEvents'), originalPreventDefault = evnt.preventDefault, iframe = _jQuery('#application iframe')[0], appWindow = iframe ? iframe.contentWindow : window, fakeProcessDefault = true, finalProcessDefault; // igor: temporary fix for https://bugzilla.mozilla.org/show_bug.cgi?id=684208 appWindow.angular['ff-684208-preventDefault'] = false; evnt.preventDefault = function() { fakeProcessDefault = false; return originalPreventDefault.apply(evnt, arguments); }; evnt.initMouseEvent(type, true, true, window, 0, 0, 0, 0, 0, pressed('ctrl'), pressed('alt'), pressed('shift'), pressed('meta'), 0, element); element.dispatchEvent(evnt); finalProcessDefault = !(appWindow.angular['ff-684208-preventDefault'] || !fakeProcessDefault); delete appWindow.angular['ff-684208-preventDefault']; return finalProcessDefault; } } /** * Don't use the jQuery trigger method since it works incorrectly. * * jQuery notifies listeners and then changes the state of a checkbox and * does not create a real browser event. A real click changes the state of * the checkbox and then notifies listeners. * * To work around this we instead use our own handler that fires a real event. */ (function(fn){ var parentTrigger = fn.trigger; fn.trigger = function(type) { if (/(click|change|keydown|blur|input)/.test(type)) { var processDefaults = []; this.each(function(index, node) { processDefaults.push(browserTrigger(node, type)); }); // this is not compatible with jQuery - we return an array of returned values, // so that scenario runner know whether JS code has preventDefault() of the event or not... return processDefaults; } return parentTrigger.apply(this, arguments); }; })(_jQuery.fn); /** * Finds all bindings with the substring match of name and returns an * array of their values. * * @param {string} bindExp The name to match * @return {Array.<string>} String of binding values */ _jQuery.fn.bindings = function(windowJquery, bindExp) { var result = [], match, bindSelector = '.ng-binding:visible'; if (angular.isString(bindExp)) { bindExp = bindExp.replace(/\s/g, ''); match = function (actualExp) { if (actualExp) { actualExp = actualExp.replace(/\s/g, ''); if (actualExp == bindExp) return true; if (actualExp.indexOf(bindExp) == 0) { return actualExp.charAt(bindExp.length) == '|'; } } } } else if (bindExp) { match = function(actualExp) { return actualExp && bindExp.exec(actualExp); } } else { match = function(actualExp) { return !!actualExp; }; } var selection = this.find(bindSelector); if (this.is(bindSelector)) { selection = selection.add(this); } function push(value) { if (value == undefined) { value = ''; } else if (typeof value != 'string') { value = angular.toJson(value); } result.push('' + value); } selection.each(function() { var element = windowJquery(this), binding; if (binding = element.data('$binding')) { if (typeof binding == 'string') { if (match(binding)) { push(element.scope().$eval(binding)); } } else { if (!angular.isArray(binding)) { binding = [binding]; } for(var fns, j=0, jj=binding.length; j<jj; j++) { fns = binding[j]; if (fns.parts) { fns = fns.parts; } else { fns = [fns]; } for (var scope, fn, i = 0, ii = fns.length; i < ii; i++) { if(match((fn = fns[i]).exp)) { push(fn(scope = scope || element.scope())); } } } } } }); return result; }; /** * Represents the application currently being tested and abstracts usage * of iframes or separate windows. * * @param {Object} context jQuery wrapper around HTML context. */ angular.scenario.Application = function(context) { this.context = context; context.append( '<h2>Current URL: <a href="about:blank">None</a></h2>' + '<div id="test-frames"></div>' ); }; /** * Gets the jQuery collection of frames. Don't use this directly because * frames may go stale. * * @private * @return {Object} jQuery collection */ angular.scenario.Application.prototype.getFrame_ = function() { return this.context.find('#test-frames iframe:last'); }; /** * Gets the window of the test runner frame. Always favor executeAction() * instead of this method since it prevents you from getting a stale window. * * @private * @return {Object} the window of the frame */ angular.scenario.Application.prototype.getWindow_ = function() { var contentWindow = this.getFrame_().prop('contentWindow'); if (!contentWindow) throw 'Frame window is not accessible.'; return contentWindow; }; /** * Changes the location of the frame. * * @param {string} url The URL. If it begins with a # then only the * hash of the page is changed. * @param {function()} loadFn function($window, $document) Called when frame loads. * @param {function()} errorFn function(error) Called if any error when loading. */ angular.scenario.Application.prototype.navigateTo = function(url, loadFn, errorFn) { var self = this; var frame = this.getFrame_(); //TODO(esprehn): Refactor to use rethrow() errorFn = errorFn || function(e) { throw e; }; if (url === 'about:blank') { errorFn('Sandbox Error: Navigating to about:blank is not allowed.'); } else if (url.charAt(0) === '#') { url = frame.attr('src').split('#')[0] + url; frame.attr('src', url); this.executeAction(loadFn); } else { frame.remove(); this.context.find('#test-frames').append('<iframe>'); frame = this.getFrame_(); frame.load(function() { frame.unbind(); try { self.executeAction(loadFn); } catch (e) { errorFn(e); } }).attr('src', url); } this.context.find('> h2 a').attr('href', url).text(url); }; /** * Executes a function in the context of the tested application. Will wait * for all pending angular xhr requests before executing. * * @param {function()} action The callback to execute. function($window, $document) * $document is a jQuery wrapped document. */ angular.scenario.Application.prototype.executeAction = function(action) { var self = this; var $window = this.getWindow_(); if (!$window.document) { throw 'Sandbox Error: Application document not accessible.'; } if (!$window.angular) { return action.call(this, $window, _jQuery($window.document)); } angularInit($window.document, function(element) { var $injector = $window.angular.element(element).injector(); var $element = _jQuery(element); $element.injector = function() { return $injector; }; $injector.invoke(function($browser){ $browser.notifyWhenNoOutstandingRequests(function() { action.call(self, $window, $element); }); }); }); }; /** * The representation of define blocks. Don't used directly, instead use * define() in your tests. * * @param {string} descName Name of the block * @param {Object} parent describe or undefined if the root. */ angular.scenario.Describe = function(descName, parent) { this.only = parent && parent.only; this.beforeEachFns = []; this.afterEachFns = []; this.its = []; this.children = []; this.name = descName; this.parent = parent; this.id = angular.scenario.Describe.id++; /** * Calls all before functions. */ var beforeEachFns = this.beforeEachFns; this.setupBefore = function() { if (parent) parent.setupBefore.call(this); angular.forEach(beforeEachFns, function(fn) { fn.call(this); }, this); }; /** * Calls all after functions. */ var afterEachFns = this.afterEachFns; this.setupAfter = function() { angular.forEach(afterEachFns, function(fn) { fn.call(this); }, this); if (parent) parent.setupAfter.call(this); }; }; // Shared Unique ID generator for every describe block angular.scenario.Describe.id = 0; // Shared Unique ID generator for every it (spec) angular.scenario.Describe.specId = 0; /** * Defines a block to execute before each it or nested describe. * * @param {function()} body Body of the block. */ angular.scenario.Describe.prototype.beforeEach = function(body) { this.beforeEachFns.push(body); }; /** * Defines a block to execute after each it or nested describe. * * @param {function()} body Body of the block. */ angular.scenario.Describe.prototype.afterEach = function(body) { this.afterEachFns.push(body); }; /** * Creates a new describe block that's a child of this one. * * @param {string} name Name of the block. Appended to the parent block's name. * @param {function()} body Body of the block. */ angular.scenario.Describe.prototype.describe = function(name, body) { var child = new angular.scenario.Describe(name, this); this.children.push(child); body.call(child); }; /** * Same as describe() but makes ddescribe blocks the only to run. * * @param {string} name Name of the test. * @param {function()} body Body of the block. */ angular.scenario.Describe.prototype.ddescribe = function(name, body) { var child = new angular.scenario.Describe(name, this); child.only = true; this.children.push(child); body.call(child); }; /** * Use to disable a describe block. */ angular.scenario.Describe.prototype.xdescribe = angular.noop; /** * Defines a test. * * @param {string} name Name of the test. * @param {function()} vody Body of the block. */ angular.scenario.Describe.prototype.it = function(name, body) { this.its.push({ id: angular.scenario.Describe.specId++, definition: this, only: this.only, name: name, before: this.setupBefore, body: body, after: this.setupAfter }); }; /** * Same as it() but makes iit tests the only test to run. * * @param {string} name Name of the test. * @param {function()} body Body of the block. */ angular.scenario.Describe.prototype.iit = function(name, body) { this.it.apply(this, arguments); this.its[this.its.length-1].only = true; }; /** * Use to disable a test block. */ angular.scenario.Describe.prototype.xit = angular.noop; /** * Gets an array of functions representing all the tests (recursively). * that can be executed with SpecRunner's. * * @return {Array<Object>} Array of it blocks { * definition : Object // parent Describe * only: boolean * name: string * before: Function * body: Function * after: Function * } */ angular.scenario.Describe.prototype.getSpecs = function() { var specs = arguments[0] || []; angular.forEach(this.children, function(child) { child.getSpecs(specs); }); angular.forEach(this.its, function(it) { specs.push(it); }); var only = []; angular.forEach(specs, function(it) { if (it.only) { only.push(it); } }); return (only.length && only) || specs; }; /** * A future action in a spec. * * @param {string} name of the future action * @param {function()} future callback(error, result) * @param {function()} Optional. function that returns the file/line number. */ angular.scenario.Future = function(name, behavior, line) { this.name = name; this.behavior = behavior; this.fulfilled = false; this.value = undefined; this.parser = angular.identity; this.line = line || function() { return ''; }; }; /** * Executes the behavior of the closure. * * @param {function()} doneFn Callback function(error, result) */ angular.scenario.Future.prototype.execute = function(doneFn) { var self = this; this.behavior(function(error, result) { self.fulfilled = true; if (result) { try { result = self.parser(result); } catch(e) { error = e; } } self.value = error || result; doneFn(error, result); }); }; /** * Configures the future to convert it's final with a function fn(value) * * @param {function()} fn function(value) that returns the parsed value */ angular.scenario.Future.prototype.parsedWith = function(fn) { this.parser = fn; return this; }; /** * Configures the future to parse it's final value from JSON * into objects. */ angular.scenario.Future.prototype.fromJson = function() { return this.parsedWith(angular.fromJson); }; /** * Configures the future to convert it's final value from objects * into JSON. */ angular.scenario.Future.prototype.toJson = function() { return this.parsedWith(angular.toJson); }; /** * Maintains an object tree from the runner events. * * @param {Object} runner The scenario Runner instance to connect to. * * TODO(esprehn): Every output type creates one of these, but we probably * want one global shared instance. Need to handle events better too * so the HTML output doesn't need to do spec model.getSpec(spec.id) * silliness. * * TODO(vojta) refactor on, emit methods (from all objects) - use inheritance */ angular.scenario.ObjectModel = function(runner) { var self = this; this.specMap = {}; this.listeners = []; this.value = { name: '', children: {} }; runner.on('SpecBegin', function(spec) { var block = self.value, definitions = []; angular.forEach(self.getDefinitionPath(spec), function(def) { if (!block.children[def.name]) { block.children[def.name] = { id: def.id, name: def.name, children: {}, specs: {} }; } block = block.children[def.name]; definitions.push(def.name); }); var it = self.specMap[spec.id] = block.specs[spec.name] = new angular.scenario.ObjectModel.Spec(spec.id, spec.name, definitions); // forward the event self.emit('SpecBegin', it); }); runner.on('SpecError', function(spec, error) { var it = self.getSpec(spec.id); it.status = 'error'; it.error = error; // forward the event self.emit('SpecError', it, error); }); runner.on('SpecEnd', function(spec) { var it = self.getSpec(spec.id); complete(it); // forward the event self.emit('SpecEnd', it); }); runner.on('StepBegin', function(spec, step) { var it = self.getSpec(spec.id); var step = new angular.scenario.ObjectModel.Step(step.name); it.steps.push(step); // forward the event self.emit('StepBegin', it, step); }); runner.on('StepEnd', function(spec) { var it = self.getSpec(spec.id); var step = it.getLastStep(); if (step.name !== step.name) throw 'Events fired in the wrong order. Step names don\'t match.'; complete(step); // forward the event self.emit('StepEnd', it, step); }); runner.on('StepFailure', function(spec, step, error) { var it = self.getSpec(spec.id), modelStep = it.getLastStep(); modelStep.setErrorStatus('failure', error, step.line()); it.setStatusFromStep(modelStep); // forward the event self.emit('StepFailure', it, modelStep, error); }); runner.on('StepError', function(spec, step, error) { var it = self.getSpec(spec.id), modelStep = it.getLastStep(); modelStep.setErrorStatus('error', error, step.line()); it.setStatusFromStep(modelStep); // forward the event self.emit('StepError', it, modelStep, error); }); runner.on('RunnerEnd', function() { self.emit('RunnerEnd'); }); function complete(item) { item.endTime = new Date().getTime(); item.duration = item.endTime - item.startTime; item.status = item.status || 'success'; } }; /** * Adds a listener for an event. * * @param {string} eventName Name of the event to add a handler for * @param {function()} listener Function that will be called when event is fired */ angular.scenario.ObjectModel.prototype.on = function(eventName, listener) { eventName = eventName.toLowerCase(); this.listeners[eventName] = this.listeners[eventName] || []; this.listeners[eventName].push(listener); }; /** * Emits an event which notifies listeners and passes extra * arguments. * * @param {string} eventName Name of the event to fire. */ angular.scenario.ObjectModel.prototype.emit = function(eventName) { var self = this, args = Array.prototype.slice.call(arguments, 1), eventName = eventName.toLowerCase(); if (this.listeners[eventName]) { angular.forEach(this.listeners[eventName], function(listener) { listener.apply(self, args); }); } }; /** * Computes the path of definition describe blocks that wrap around * this spec. * * @param spec Spec to compute the path for. * @return {Array<Describe>} The describe block path */ angular.scenario.ObjectModel.prototype.getDefinitionPath = function(spec) { var path = []; var currentDefinition = spec.definition; while (currentDefinition && currentDefinition.name) { path.unshift(currentDefinition); currentDefinition = currentDefinition.parent; } return path; }; /** * Gets a spec by id. * * @param {string} The id of the spec to get the object for. * @return {Object} the Spec instance */ angular.scenario.ObjectModel.prototype.getSpec = function(id) { return this.specMap[id]; }; /** * A single it block. * * @param {string} id Id of the spec * @param {string} name Name of the spec * @param {Array<string>=} definitionNames List of all describe block names that wrap this spec */ angular.scenario.ObjectModel.Spec = function(id, name, definitionNames) { this.id = id; this.name = name; this.startTime = new Date().getTime(); this.steps = []; this.fullDefinitionName = (definitionNames || []).join(' '); }; /** * Adds a new step to the Spec. * * @param {string} step Name of the step (really name of the future) * @return {Object} the added step */ angular.scenario.ObjectModel.Spec.prototype.addStep = function(name) { var step = new angular.scenario.ObjectModel.Step(name); this.steps.push(step); return step; }; /** * Gets the most recent step. * * @return {Object} the step */ angular.scenario.ObjectModel.Spec.prototype.getLastStep = function() { return this.steps[this.steps.length-1]; }; /** * Set status of the Spec from given Step * * @param {angular.scenario.ObjectModel.Step} step */ angular.scenario.ObjectModel.Spec.prototype.setStatusFromStep = function(step) { if (!this.status || step.status == 'error') { this.status = step.status; this.error = step.error; this.line = step.line; } }; /** * A single step inside a Spec. * * @param {string} step Name of the step */ angular.scenario.ObjectModel.Step = function(name) { this.name = name; this.startTime = new Date().getTime(); }; /** * Helper method for setting all error status related properties * * @param {string} status * @param {string} error * @param {string} line */ angular.scenario.ObjectModel.Step.prototype.setErrorStatus = function(status, error, line) { this.status = status; this.error = error; this.line = line; }; /** * The representation of define blocks. Don't used directly, instead use * define() in your tests. * * @param {string} descName Name of the block * @param {Object} parent describe or undefined if the root. */ angular.scenario.Describe = function(descName, parent) { this.only = parent && parent.only; this.beforeEachFns = []; this.afterEachFns = []; this.its = []; this.children = []; this.name = descName; this.parent = parent; this.id = angular.scenario.Describe.id++; /** * Calls all before functions. */ var beforeEachFns = this.beforeEachFns; this.setupBefore = function() { if (parent) parent.setupBefore.call(this); angular.forEach(beforeEachFns, function(fn) { fn.call(this); }, this); }; /** * Calls all after functions. */ var afterEachFns = this.afterEachFns; this.setupAfter = function() { angular.forEach(afterEachFns, function(fn) { fn.call(this); }, this); if (parent) parent.setupAfter.call(this); }; }; // Shared Unique ID generator for every describe block angular.scenario.Describe.id = 0; // Shared Unique ID generator for every it (spec) angular.scenario.Describe.specId = 0; /** * Defines a block to execute before each it or nested describe. * * @param {function()} body Body of the block. */ angular.scenario.Describe.prototype.beforeEach = function(body) { this.beforeEachFns.push(body); }; /** * Defines a block to execute after each it or nested describe. * * @param {function()} body Body of the block. */ angular.scenario.Describe.prototype.afterEach = function(body) { this.afterEachFns.push(body); }; /** * Creates a new describe block that's a child of this one. * * @param {string} name Name of the block. Appended to the parent block's name. * @param {function()} body Body of the block. */ angular.scenario.Describe.prototype.describe = function(name, body) { var child = new angular.scenario.Describe(name, this); this.children.push(child); body.call(child); }; /** * Same as describe() but makes ddescribe blocks the only to run. * * @param {string} name Name of the test. * @param {function()} body Body of the block. */ angular.scenario.Describe.prototype.ddescribe = function(name, body) { var child = new angular.scenario.Describe(name, this); child.only = true; this.children.push(child); body.call(child); }; /** * Use to disable a describe block. */ angular.scenario.Describe.prototype.xdescribe = angular.noop; /** * Defines a test. * * @param {string} name Name of the test. * @param {function()} vody Body of the block. */ angular.scenario.Describe.prototype.it = function(name, body) { this.its.push({ id: angular.scenario.Describe.specId++, definition: this, only: this.only, name: name, before: this.setupBefore, body: body, after: this.setupAfter }); }; /** * Same as it() but makes iit tests the only test to run. * * @param {string} name Name of the test. * @param {function()} body Body of the block. */ angular.scenario.Describe.prototype.iit = function(name, body) { this.it.apply(this, arguments); this.its[this.its.length-1].only = true; }; /** * Use to disable a test block. */ angular.scenario.Describe.prototype.xit = angular.noop; /** * Gets an array of functions representing all the tests (recursively). * that can be executed with SpecRunner's. * * @return {Array<Object>} Array of it blocks { * definition : Object // parent Describe * only: boolean * name: string * before: Function * body: Function * after: Function * } */ angular.scenario.Describe.prototype.getSpecs = function() { var specs = arguments[0] || []; angular.forEach(this.children, function(child) { child.getSpecs(specs); }); angular.forEach(this.its, function(it) { specs.push(it); }); var only = []; angular.forEach(specs, function(it) { if (it.only) { only.push(it); } }); return (only.length && only) || specs; }; /** * Runner for scenarios * * Has to be initialized before any test is loaded, * because it publishes the API into window (global space). */ angular.scenario.Runner = function($window) { this.listeners = []; this.$window = $window; this.rootDescribe = new angular.scenario.Describe(); this.currentDescribe = this.rootDescribe; this.api = { it: this.it, iit: this.iit, xit: angular.noop, describe: this.describe, ddescribe: this.ddescribe, xdescribe: angular.noop, beforeEach: this.beforeEach, afterEach: this.afterEach }; angular.forEach(this.api, angular.bind(this, function(fn, key) { this.$window[key] = angular.bind(this, fn); })); }; /** * Emits an event which notifies listeners and passes extra * arguments. * * @param {string} eventName Name of the event to fire. */ angular.scenario.Runner.prototype.emit = function(eventName) { var self = this; var args = Array.prototype.slice.call(arguments, 1); eventName = eventName.toLowerCase(); if (!this.listeners[eventName]) return; angular.forEach(this.listeners[eventName], function(listener) { listener.apply(self, args); }); }; /** * Adds a listener for an event. * * @param {string} eventName The name of the event to add a handler for * @param {string} listener The fn(...) that takes the extra arguments from emit() */ angular.scenario.Runner.prototype.on = function(eventName, listener) { eventName = eventName.toLowerCase(); this.listeners[eventName] = this.listeners[eventName] || []; this.listeners[eventName].push(listener); }; /** * Defines a describe block of a spec. * * @see Describe.js * * @param {string} name Name of the block * @param {function()} body Body of the block */ angular.scenario.Runner.prototype.describe = function(name, body) { var self = this; this.currentDescribe.describe(name, function() { var parentDescribe = self.currentDescribe; self.currentDescribe = this; try { body.call(this); } finally { self.currentDescribe = parentDescribe; } }); }; /** * Same as describe, but makes ddescribe the only blocks to run. * * @see Describe.js * * @param {string} name Name of the block * @param {function()} body Body of the block */ angular.scenario.Runner.prototype.ddescribe = function(name, body) { var self = this; this.currentDescribe.ddescribe(name, function() { var parentDescribe = self.currentDescribe; self.currentDescribe = this; try { body.call(this); } finally { self.currentDescribe = parentDescribe; } }); }; /** * Defines a test in a describe block of a spec. * * @see Describe.js * * @param {string} name Name of the block * @param {function()} body Body of the block */ angular.scenario.Runner.prototype.it = function(name, body) { this.currentDescribe.it(name, body); }; /** * Same as it, but makes iit tests the only tests to run. * * @see Describe.js * * @param {string} name Name of the block * @param {function()} body Body of the block */ angular.scenario.Runner.prototype.iit = function(name, body) { this.currentDescribe.iit(name, body); }; /** * Defines a function to be called before each it block in the describe * (and before all nested describes). * * @see Describe.js * * @param {function()} Callback to execute */ angular.scenario.Runner.prototype.beforeEach = function(body) { this.currentDescribe.beforeEach(body); }; /** * Defines a function to be called after each it block in the describe * (and before all nested describes). * * @see Describe.js * * @param {function()} Callback to execute */ angular.scenario.Runner.prototype.afterEach = function(body) { this.currentDescribe.afterEach(body); }; /** * Creates a new spec runner. * * @private * @param {Object} scope parent scope */ angular.scenario.Runner.prototype.createSpecRunner_ = function(scope) { var child = scope.$new(); var Cls = angular.scenario.SpecRunner; // Export all the methods to child scope manually as now we don't mess controllers with scopes // TODO(vojta): refactor scenario runner so that these objects are not tightly coupled as current for (var name in Cls.prototype) child[name] = angular.bind(child, Cls.prototype[name]); Cls.call(child); return child; }; /** * Runs all the loaded tests with the specified runner class on the * provided application. * * @param {angular.scenario.Application} application App to remote control. */ angular.scenario.Runner.prototype.run = function(application) { var self = this; var $root = angular.injector(['ng']).get('$rootScope'); angular.extend($root, this); angular.forEach(angular.scenario.Runner.prototype, function(fn, name) { $root[name] = angular.bind(self, fn); }); $root.application = application; $root.emit('RunnerBegin'); asyncForEach(this.rootDescribe.getSpecs(), function(spec, specDone) { var dslCache = {}; var runner = self.createSpecRunner_($root); angular.forEach(angular.scenario.dsl, function(fn, key) { dslCache[key] = fn.call($root); }); angular.forEach(angular.scenario.dsl, function(fn, key) { self.$window[key] = function() { var line = callerFile(3); var scope = runner.$new(); // Make the dsl accessible on the current chain scope.dsl = {}; angular.forEach(dslCache, function(fn, key) { scope.dsl[key] = function() { return dslCache[key].apply(scope, arguments); }; }); // Make these methods work on the current chain scope.addFuture = function() { Array.prototype.push.call(arguments, line); return angular.scenario.SpecRunner. prototype.addFuture.apply(scope, arguments); }; scope.addFutureAction = function() { Array.prototype.push.call(arguments, line); return angular.scenario.SpecRunner. prototype.addFutureAction.apply(scope, arguments); }; return scope.dsl[key].apply(scope, arguments); }; }); runner.run(spec, function() { runner.$destroy(); specDone.apply(this, arguments); }); }, function(error) { if (error) { self.emit('RunnerError', error); } self.emit('RunnerEnd'); }); }; /** * This class is the "this" of the it/beforeEach/afterEach method. * Responsibilities: * - "this" for it/beforeEach/afterEach * - keep state for single it/beforeEach/afterEach execution * - keep track of all of the futures to execute * - run single spec (execute each future) */ angular.scenario.SpecRunner = function() { this.futures = []; this.afterIndex = 0; }; /** * Executes a spec which is an it block with associated before/after functions * based on the describe nesting. * * @param {Object} spec A spec object * @param {function()} specDone function that is called when the spec finshes. Function(error, index) */ angular.scenario.SpecRunner.prototype.run = function(spec, specDone) { var self = this; this.spec = spec; this.emit('SpecBegin', spec); try { spec.before.call(this); spec.body.call(this); this.afterIndex = this.futures.length; spec.after.call(this); } catch (e) { this.emit('SpecError', spec, e); this.emit('SpecEnd', spec); specDone(); return; } var handleError = function(error, done) { if (self.error) { return done(); } self.error = true; done(null, self.afterIndex); }; asyncForEach( this.futures, function(future, futureDone) { self.step = future; self.emit('StepBegin', spec, future); try { future.execute(function(error) { if (error) { self.emit('StepFailure', spec, future, error); self.emit('StepEnd', spec, future); return handleError(error, futureDone); } self.emit('StepEnd', spec, future); self.$window.setTimeout(function() { futureDone(); }, 0); }); } catch (e) { self.emit('StepError', spec, future, e); self.emit('StepEnd', spec, future); handleError(e, futureDone); } }, function(e) { if (e) { self.emit('SpecError', spec, e); } self.emit('SpecEnd', spec); // Call done in a timeout so exceptions don't recursively // call this function self.$window.setTimeout(function() { specDone(); }, 0); } ); }; /** * Adds a new future action. * * Note: Do not pass line manually. It happens automatically. * * @param {string} name Name of the future * @param {function()} behavior Behavior of the future * @param {function()} line fn() that returns file/line number */ angular.scenario.SpecRunner.prototype.addFuture = function(name, behavior, line) { var future = new angular.scenario.Future(name, angular.bind(this, behavior), line); this.futures.push(future); return future; }; /** * Adds a new future action to be executed on the application window. * * Note: Do not pass line manually. It happens automatically. * * @param {string} name Name of the future * @param {function()} behavior Behavior of the future * @param {function()} line fn() that returns file/line number */ angular.scenario.SpecRunner.prototype.addFutureAction = function(name, behavior, line) { var self = this; var NG = /\[ng\\\:/; return this.addFuture(name, function(done) { this.application.executeAction(function($window, $document) { //TODO(esprehn): Refactor this so it doesn't need to be in here. $document.elements = function(selector) { var args = Array.prototype.slice.call(arguments, 1); selector = (self.selector || '') + ' ' + (selector || ''); selector = _jQuery.trim(selector) || '*'; angular.forEach(args, function(value, index) { selector = selector.replace('$' + (index + 1), value); }); var result = $document.find(selector); if (selector.match(NG)) { result = result.add(selector.replace(NG, '[ng-'), $document); } if (!result.length) { throw { type: 'selector', message: 'Selector ' + selector + ' did not match any elements.' }; } return result; }; try { behavior.call(self, $window, $document, done); } catch(e) { if (e.type && e.type === 'selector') { done(e.message); } else { throw e; } } }); }, line); }; /** * Shared DSL statements that are useful to all scenarios. */ /** * Usage: * pause() pauses until you call resume() in the console */ angular.scenario.dsl('pause', function() { return function() { return this.addFuture('pausing for you to resume', function(done) { this.emit('InteractivePause', this.spec, this.step); this.$window.resume = function() { done(); }; }); }; }); /** * Usage: * sleep(seconds) pauses the test for specified number of seconds */ angular.scenario.dsl('sleep', function() { return function(time) { return this.addFuture('sleep for ' + time + ' seconds', function(done) { this.$window.setTimeout(function() { done(null, time * 1000); }, time * 1000); }); }; }); /** * Usage: * browser().navigateTo(url) Loads the url into the frame * browser().navigateTo(url, fn) where fn(url) is called and returns the URL to navigate to * browser().reload() refresh the page (reload the same URL) * browser().window.href() window.location.href * browser().window.path() window.location.pathname * browser().window.search() window.location.search * browser().window.hash() window.location.hash without # prefix * browser().location().url() see ng.$location#url * browser().location().path() see ng.$location#path * browser().location().search() see ng.$location#search * browser().location().hash() see ng.$location#hash */ angular.scenario.dsl('browser', function() { var chain = {}; chain.navigateTo = function(url, delegate) { var application = this.application; return this.addFuture("browser navigate to '" + url + "'", function(done) { if (delegate) { url = delegate.call(this, url); } application.navigateTo(url, function() { done(null, url); }, done); }); }; chain.reload = function() { var application = this.application; return this.addFutureAction('browser reload', function($window, $document, done) { var href = $window.location.href; application.navigateTo(href, function() { done(null, href); }, done); }); }; chain.window = function() { var api = {}; api.href = function() { return this.addFutureAction('window.location.href', function($window, $document, done) { done(null, $window.location.href); }); }; api.path = function() { return this.addFutureAction('window.location.path', function($window, $document, done) { done(null, $window.location.pathname); }); }; api.search = function() { return this.addFutureAction('window.location.search', function($window, $document, done) { done(null, $window.location.search); }); }; api.hash = function() { return this.addFutureAction('window.location.hash', function($window, $document, done) { done(null, $window.location.hash.replace('#', '')); }); }; return api; }; chain.location = function() { var api = {}; api.url = function() { return this.addFutureAction('$location.url()', function($window, $document, done) { done(null, $document.injector().get('$location').url()); }); }; api.path = function() { return this.addFutureAction('$location.path()', function($window, $document, done) { done(null, $document.injector().get('$location').path()); }); }; api.search = function() { return this.addFutureAction('$location.search()', function($window, $document, done) { done(null, $document.injector().get('$location').search()); }); }; api.hash = function() { return this.addFutureAction('$location.hash()', function($window, $document, done) { done(null, $document.injector().get('$location').hash()); }); }; return api; }; return function() { return chain; }; }); /** * Usage: * expect(future).{matcher} where matcher is one of the matchers defined * with angular.scenario.matcher * * ex. expect(binding("name")).toEqual("Elliott") */ angular.scenario.dsl('expect', function() { var chain = angular.extend({}, angular.scenario.matcher); chain.not = function() { this.inverse = true; return chain; }; return function(future) { this.future = future; return chain; }; }); /** * Usage: * using(selector, label) scopes the next DSL element selection * * ex. * using('#foo', "'Foo' text field").input('bar') */ angular.scenario.dsl('using', function() { return function(selector, label) { this.selector = _jQuery.trim((this.selector||'') + ' ' + selector); if (angular.isString(label) && label.length) { this.label = label + ' ( ' + this.selector + ' )'; } else { this.label = this.selector; } return this.dsl; }; }); /** * Usage: * binding(name) returns the value of the first matching binding */ angular.scenario.dsl('binding', function() { return function(name) { return this.addFutureAction("select binding '" + name + "'", function($window, $document, done) { var values = $document.elements().bindings($window.angular.element, name); if (!values.length) { return done("Binding selector '" + name + "' did not match."); } done(null, values[0]); }); }; }); /** * Usage: * input(name).enter(value) enters value in input with specified name * input(name).check() checks checkbox * input(name).select(value) selects the radio button with specified name/value * input(name).val() returns the value of the input. */ angular.scenario.dsl('input', function() { var chain = {}; var supportInputEvent = 'oninput' in document.createElement('div'); chain.enter = function(value, event) { return this.addFutureAction("input '" + this.name + "' enter '" + value + "'", function($window, $document, done) { var input = $document.elements('[ng\\:model="$1"]', this.name).filter(':input'); input.val(value); input.trigger(event || supportInputEvent && 'input' || 'change'); done(); }); }; chain.check = function() { return this.addFutureAction("checkbox '" + this.name + "' toggle", function($window, $document, done) { var input = $document.elements('[ng\\:model="$1"]', this.name).filter(':checkbox'); input.trigger('click'); done(); }); }; chain.select = function(value) { return this.addFutureAction("radio button '" + this.name + "' toggle '" + value + "'", function($window, $document, done) { var input = $document. elements('[ng\\:model="$1"][value="$2"]', this.name, value).filter(':radio'); input.trigger('click'); done(); }); }; chain.val = function() { return this.addFutureAction("return input val", function($window, $document, done) { var input = $document.elements('[ng\\:model="$1"]', this.name).filter(':input'); done(null,input.val()); }); }; return function(name) { this.name = name; return chain; }; }); /** * Usage: * repeater('#products table', 'Product List').count() number of rows * repeater('#products table', 'Product List').row(1) all bindings in row as an array * repeater('#products table', 'Product List').column('product.name') all values across all rows in an array */ angular.scenario.dsl('repeater', function() { var chain = {}; chain.count = function() { return this.addFutureAction("repeater '" + this.label + "' count", function($window, $document, done) { try { done(null, $document.elements().length); } catch (e) { done(null, 0); } }); }; chain.column = function(binding) { return this.addFutureAction("repeater '" + this.label + "' column '" + binding + "'", function($window, $document, done) { done(null, $document.elements().bindings($window.angular.element, binding)); }); }; chain.row = function(index) { return this.addFutureAction("repeater '" + this.label + "' row '" + index + "'", function($window, $document, done) { var matches = $document.elements().slice(index, index + 1); if (!matches.length) return done('row ' + index + ' out of bounds'); done(null, matches.bindings($window.angular.element)); }); }; return function(selector, label) { this.dsl.using(selector, label); return chain; }; }); /** * Usage: * select(name).option('value') select one option * select(name).options('value1', 'value2', ...) select options from a multi select */ angular.scenario.dsl('select', function() { var chain = {}; chain.option = function(value) { return this.addFutureAction("select '" + this.name + "' option '" + value + "'", function($window, $document, done) { var select = $document.elements('select[ng\\:model="$1"]', this.name); var option = select.find('option[value="' + value + '"]'); if (option.length) { select.val(value); } else { option = select.find('option:contains("' + value + '")'); if (option.length) { select.val(option.val()); } } select.trigger('change'); done(); }); }; chain.options = function() { var values = arguments; return this.addFutureAction("select '" + this.name + "' options '" + values + "'", function($window, $document, done) { var select = $document.elements('select[multiple][ng\\:model="$1"]', this.name); select.val(values); select.trigger('change'); done(); }); }; return function(name) { this.name = name; return chain; }; }); /** * Usage: * element(selector, label).count() get the number of elements that match selector * element(selector, label).click() clicks an element * element(selector, label).query(fn) executes fn(selectedElements, done) * element(selector, label).{method}() gets the value (as defined by jQuery, ex. val) * element(selector, label).{method}(value) sets the value (as defined by jQuery, ex. val) * element(selector, label).{method}(key) gets the value (as defined by jQuery, ex. attr) * element(selector, label).{method}(key, value) sets the value (as defined by jQuery, ex. attr) */ angular.scenario.dsl('element', function() { var KEY_VALUE_METHODS = ['attr', 'css', 'prop']; var VALUE_METHODS = [ 'val', 'text', 'html', 'height', 'innerHeight', 'outerHeight', 'width', 'innerWidth', 'outerWidth', 'position', 'scrollLeft', 'scrollTop', 'offset' ]; var chain = {}; chain.count = function() { return this.addFutureAction("element '" + this.label + "' count", function($window, $document, done) { try { done(null, $document.elements().length); } catch (e) { done(null, 0); } }); }; chain.click = function() { return this.addFutureAction("element '" + this.label + "' click", function($window, $document, done) { var elements = $document.elements(); var href = elements.attr('href'); var eventProcessDefault = elements.trigger('click')[0]; if (href && elements[0].nodeName.toUpperCase() === 'A' && eventProcessDefault) { this.application.navigateTo(href, function() { done(); }, done); } else { done(); } }); }; chain.query = function(fn) { return this.addFutureAction('element ' + this.label + ' custom query', function($window, $document, done) { fn.call(this, $document.elements(), done); }); }; angular.forEach(KEY_VALUE_METHODS, function(methodName) { chain[methodName] = function(name, value) { var args = arguments, futureName = (args.length == 1) ? "element '" + this.label + "' get " + methodName + " '" + name + "'" : "element '" + this.label + "' set " + methodName + " '" + name + "' to " + "'" + value + "'"; return this.addFutureAction(futureName, function($window, $document, done) { var element = $document.elements(); done(null, element[methodName].apply(element, args)); }); }; }); angular.forEach(VALUE_METHODS, function(methodName) { chain[methodName] = function(value) { var args = arguments, futureName = (args.length == 0) ? "element '" + this.label + "' " + methodName : futureName = "element '" + this.label + "' set " + methodName + " to '" + value + "'"; return this.addFutureAction(futureName, function($window, $document, done) { var element = $document.elements(); done(null, element[methodName].apply(element, args)); }); }; }); return function(selector, label) { this.dsl.using(selector, label); return chain; }; }); /** * Matchers for implementing specs. Follows the Jasmine spec conventions. */ angular.scenario.matcher('toEqual', function(expected) { return angular.equals(this.actual, expected); }); angular.scenario.matcher('toBe', function(expected) { return this.actual === expected; }); angular.scenario.matcher('toBeDefined', function() { return angular.isDefined(this.actual); }); angular.scenario.matcher('toBeTruthy', function() { return this.actual; }); angular.scenario.matcher('toBeFalsy', function() { return !this.actual; }); angular.scenario.matcher('toMatch', function(expected) { return new RegExp(expected).test(this.actual); }); angular.scenario.matcher('toBeNull', function() { return this.actual === null; }); angular.scenario.matcher('toContain', function(expected) { return includes(this.actual, expected); }); angular.scenario.matcher('toBeLessThan', function(expected) { return this.actual < expected; }); angular.scenario.matcher('toBeGreaterThan', function(expected) { return this.actual > expected; }); /** * User Interface for the Scenario Runner. * * TODO(esprehn): This should be refactored now that ObjectModel exists * to use angular bindings for the UI. */ angular.scenario.output('html', function(context, runner, model) { var specUiMap = {}, lastStepUiMap = {}; context.append( '<div id="header">' + ' <h1><span class="angular">AngularJS</span>: Scenario Test Runner</h1>' + ' <ul id="status-legend" class="status-display">' + ' <li class="status-error">0 Errors</li>' + ' <li class="status-failure">0 Failures</li>' + ' <li class="status-success">0 Passed</li>' + ' </ul>' + '</div>' + '<div id="specs">' + ' <div class="test-children"></div>' + '</div>' ); runner.on('InteractivePause', function(spec) { var ui = lastStepUiMap[spec.id]; ui.find('.test-title'). html('paused... <a href="javascript:resume()">resume</a> when ready.'); }); runner.on('SpecBegin', function(spec) { var ui = findContext(spec); ui.find('> .tests').append( '<li class="status-pending test-it"></li>' ); ui = ui.find('> .tests li:last'); ui.append( '<div class="test-info">' + ' <p class="test-title">' + ' <span class="timer-result"></span>' + ' <span class="test-name"></span>' + ' </p>' + '</div>' + '<div class="scrollpane">' + ' <ol class="test-actions"></ol>' + '</div>' ); ui.find('> .test-info .test-name').text(spec.name); ui.find('> .test-info').click(function() { var scrollpane = ui.find('> .scrollpane'); var actions = scrollpane.find('> .test-actions'); var name = context.find('> .test-info .test-name'); if (actions.find(':visible').length) { actions.hide(); name.removeClass('open').addClass('closed'); } else { actions.show(); scrollpane.attr('scrollTop', scrollpane.attr('scrollHeight')); name.removeClass('closed').addClass('open'); } }); specUiMap[spec.id] = ui; }); runner.on('SpecError', function(spec, error) { var ui = specUiMap[spec.id]; ui.append('<pre></pre>'); ui.find('> pre').text(formatException(error)); }); runner.on('SpecEnd', function(spec) { var ui = specUiMap[spec.id]; spec = model.getSpec(spec.id); ui.removeClass('status-pending'); ui.addClass('status-' + spec.status); ui.find("> .test-info .timer-result").text(spec.duration + "ms"); if (spec.status === 'success') { ui.find('> .test-info .test-name').addClass('closed'); ui.find('> .scrollpane .test-actions').hide(); } updateTotals(spec.status); }); runner.on('StepBegin', function(spec, step) { var ui = specUiMap[spec.id]; spec = model.getSpec(spec.id); step = spec.getLastStep(); ui.find('> .scrollpane .test-actions').append('<li class="status-pending"></li>'); var stepUi = lastStepUiMap[spec.id] = ui.find('> .scrollpane .test-actions li:last'); stepUi.append( '<div class="timer-result"></div>' + '<div class="test-title"></div>' ); stepUi.find('> .test-title').text(step.name); var scrollpane = stepUi.parents('.scrollpane'); scrollpane.attr('scrollTop', scrollpane.attr('scrollHeight')); }); runner.on('StepFailure', function(spec, step, error) { var ui = lastStepUiMap[spec.id]; addError(ui, step.line, error); }); runner.on('StepError', function(spec, step, error) { var ui = lastStepUiMap[spec.id]; addError(ui, step.line, error); }); runner.on('StepEnd', function(spec, step) { var stepUi = lastStepUiMap[spec.id]; spec = model.getSpec(spec.id); step = spec.getLastStep(); stepUi.find('.timer-result').text(step.duration + 'ms'); stepUi.removeClass('status-pending'); stepUi.addClass('status-' + step.status); var scrollpane = specUiMap[spec.id].find('> .scrollpane'); scrollpane.attr('scrollTop', scrollpane.attr('scrollHeight')); }); /** * Finds the context of a spec block defined by the passed definition. * * @param {Object} The definition created by the Describe object. */ function findContext(spec) { var currentContext = context.find('#specs'); angular.forEach(model.getDefinitionPath(spec), function(defn) { var id = 'describe-' + defn.id; if (!context.find('#' + id).length) { currentContext.find('> .test-children').append( '<div class="test-describe" id="' + id + '">' + ' <h2></h2>' + ' <div class="test-children"></div>' + ' <ul class="tests"></ul>' + '</div>' ); context.find('#' + id).find('> h2').text('describe: ' + defn.name); } currentContext = context.find('#' + id); }); return context.find('#describe-' + spec.definition.id); } /** * Updates the test counter for the status. * * @param {string} the status. */ function updateTotals(status) { var legend = context.find('#status-legend .status-' + status); var parts = legend.text().split(' '); var value = (parts[0] * 1) + 1; legend.text(value + ' ' + parts[1]); } /** * Add an error to a step. * * @param {Object} The JQuery wrapped context * @param {function()} fn() that should return the file/line number of the error * @param {Object} the error. */ function addError(context, line, error) { context.find('.test-title').append('<pre></pre>'); var message = _jQuery.trim(line() + '\n\n' + formatException(error)); context.find('.test-title pre:last').text(message); } }); /** * Generates JSON output into a context. */ angular.scenario.output('json', function(context, runner, model) { model.on('RunnerEnd', function() { context.text(angular.toJson(model.value)); }); }); /** * Generates XML output into a context. */ angular.scenario.output('xml', function(context, runner, model) { var $ = function(args) {return new context.init(args);}; model.on('RunnerEnd', function() { var scenario = $('<scenario></scenario>'); context.append(scenario); serializeXml(scenario, model.value); }); /** * Convert the tree into XML. * * @param {Object} context jQuery context to add the XML to. * @param {Object} tree node to serialize */ function serializeXml(context, tree) { angular.forEach(tree.children, function(child) { var describeContext = $('<describe></describe>'); describeContext.attr('id', child.id); describeContext.attr('name', child.name); context.append(describeContext); serializeXml(describeContext, child); }); var its = $('<its></its>'); context.append(its); angular.forEach(tree.specs, function(spec) { var it = $('<it></it>'); it.attr('id', spec.id); it.attr('name', spec.name); it.attr('duration', spec.duration); it.attr('status', spec.status); its.append(it); angular.forEach(spec.steps, function(step) { var stepContext = $('<step></step>'); stepContext.attr('name', step.name); stepContext.attr('duration', step.duration); stepContext.attr('status', step.status); it.append(stepContext); if (step.error) { var error = $('<error></error>'); stepContext.append(error); error.text(formatException(stepContext.error)); } }); }); } }); /** * Creates a global value $result with the result of the runner. */ angular.scenario.output('object', function(context, runner, model) { runner.$window.$result = model.value; }); bindJQuery(); publishExternalAPI(angular); var $runner = new angular.scenario.Runner(window), scripts = document.getElementsByTagName('script'), script = scripts[scripts.length - 1], config = {}; angular.forEach(script.attributes, function(attr) { var match = attr.name.match(/ng[:\-](.*)/); if (match) { config[match[1]] = attr.value || true; } }); if (config.autotest) { JQLite(document).ready(function() { angular.scenario.setUpAndRun(config); }); } })(window, document); angular.element(document).find('head').append('<style type="text/css">@charset "UTF-8";\n\n[ng\\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak],\n.ng-cloak, .x-ng-cloak {\n display: none;\n}\n\nng\\:form {\n display: block;\n}\n</style>'); angular.element(document).find('head').append('<style type="text/css">@charset "UTF-8";\n/* CSS Document */\n\n/** Structure */\nbody {\n font-family: Arial, sans-serif;\n margin: 0;\n font-size: 14px;\n}\n\n#system-error {\n font-size: 1.5em;\n text-align: center;\n}\n\n#json, #xml {\n display: none;\n}\n\n#header {\n position: fixed;\n width: 100%;\n}\n\n#specs {\n padding-top: 50px;\n}\n\n#header .angular {\n font-family: Courier New, monospace;\n font-weight: bold;\n}\n\n#header h1 {\n font-weight: normal;\n float: left;\n font-size: 30px;\n line-height: 30px;\n margin: 0;\n padding: 10px 10px;\n height: 30px;\n}\n\n#application h2,\n#specs h2 {\n margin: 0;\n padding: 0.5em;\n font-size: 1.1em;\n}\n\n#status-legend {\n margin-top: 10px;\n margin-right: 10px;\n}\n\n#header,\n#application,\n.test-info,\n.test-actions li {\n overflow: hidden;\n}\n\n#application {\n margin: 10px;\n}\n\n#application iframe {\n width: 100%;\n height: 758px;\n}\n\n#application .popout {\n float: right;\n}\n\n#application iframe {\n border: none;\n}\n\n.tests li,\n.test-actions li,\n.test-it li,\n.test-it ol,\n.status-display {\n list-style-type: none;\n}\n\n.tests,\n.test-it ol,\n.status-display {\n margin: 0;\n padding: 0;\n}\n\n.test-info {\n margin-left: 1em;\n margin-top: 0.5em;\n border-radius: 8px 0 0 8px;\n -webkit-border-radius: 8px 0 0 8px;\n -moz-border-radius: 8px 0 0 8px;\n cursor: pointer;\n}\n\n.test-info:hover .test-name {\n text-decoration: underline;\n}\n\n.test-info .closed:before {\n content: \'\\25b8\\00A0\';\n}\n\n.test-info .open:before {\n content: \'\\25be\\00A0\';\n font-weight: bold;\n}\n\n.test-it ol {\n margin-left: 2.5em;\n}\n\n.status-display,\n.status-display li {\n float: right;\n}\n\n.status-display li {\n padding: 5px 10px;\n}\n\n.timer-result,\n.test-title {\n display: inline-block;\n margin: 0;\n padding: 4px;\n}\n\n.test-actions .test-title,\n.test-actions .test-result {\n display: table-cell;\n padding-left: 0.5em;\n padding-right: 0.5em;\n}\n\n.test-actions {\n display: table;\n}\n\n.test-actions li {\n display: table-row;\n}\n\n.timer-result {\n width: 4em;\n padding: 0 10px;\n text-align: right;\n font-family: monospace;\n}\n\n.test-it pre,\n.test-actions pre {\n clear: left;\n color: black;\n margin-left: 6em;\n}\n\n.test-describe {\n padding-bottom: 0.5em;\n}\n\n.test-describe .test-describe {\n margin: 5px 5px 10px 2em;\n}\n\n.test-actions .status-pending .test-title:before {\n content: \'\\00bb\\00A0\';\n}\n\n.scrollpane {\n max-height: 20em;\n overflow: auto;\n}\n\n/** Colors */\n\n#header {\n background-color: #F2C200;\n}\n\n#specs h2 {\n border-top: 2px solid #BABAD1;\n}\n\n#specs h2,\n#application h2 {\n background-color: #efefef;\n}\n\n#application {\n border: 1px solid #BABAD1;\n}\n\n.test-describe .test-describe {\n border-left: 1px solid #BABAD1;\n border-right: 1px solid #BABAD1;\n border-bottom: 1px solid #BABAD1;\n}\n\n.status-display {\n border: 1px solid #777;\n}\n\n.status-display .status-pending,\n.status-pending .test-info {\n background-color: #F9EEBC;\n}\n\n.status-display .status-success,\n.status-success .test-info {\n background-color: #B1D7A1;\n}\n\n.status-display .status-failure,\n.status-failure .test-info {\n background-color: #FF8286;\n}\n\n.status-display .status-error,\n.status-error .test-info {\n background-color: black;\n color: white;\n}\n\n.test-actions .status-success .test-title {\n color: #30B30A;\n}\n\n.test-actions .status-failure .test-title {\n color: #DF0000;\n}\n\n.test-actions .status-error .test-title {\n color: black;\n}\n\n.test-actions .timer-result {\n color: #888;\n}\n</style>');
test/ProgressBarSpec.js
dongtong/react-bootstrap
import React from 'react'; import ReactTestUtils from 'react/lib/ReactTestUtils'; import ProgressBar from '../src/ProgressBar'; import {shouldWarn} from './helpers'; const getProgressBarNode = wrapper => { return React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithClass(wrapper, 'progress-bar')); }; describe('ProgressBar', () => { it('Should output a progress bar with wrapper', () => { let instance = ReactTestUtils.renderIntoDocument( <ProgressBar min={0} max={10} now={0} /> ); assert.equal(React.findDOMNode(instance).nodeName, 'DIV'); assert.ok(React.findDOMNode(instance).className.match(/\bprogress\b/)); assert.ok(getProgressBarNode(instance).className.match(/\bprogress-bar\b/)); assert.equal(getProgressBarNode(instance).getAttribute('role'), 'progressbar'); }); it('Should have the default class', () => { let instance = ReactTestUtils.renderIntoDocument( <ProgressBar min={0} max={10} now={0} bsStyle='default' /> ); assert.ok(getProgressBarNode(instance).className.match(/\bprogress-bar-default\b/)); }); it('Should have the primary class', () => { let instance = ReactTestUtils.renderIntoDocument( <ProgressBar min={0} max={10} now={0} bsStyle='primary' /> ); assert.ok(getProgressBarNode(instance).className.match(/\bprogress-bar-primary\b/)); }); it('Should have the success class', () => { let instance = ReactTestUtils.renderIntoDocument( <ProgressBar min={0} max={10} now={0} bsStyle='success' /> ); assert.ok(getProgressBarNode(instance).className.match(/\bprogress-bar-success\b/)); }); it('Should have the warning class', () => { let instance = ReactTestUtils.renderIntoDocument( <ProgressBar min={0} max={10} now={0} bsStyle='warning' /> ); assert.ok(getProgressBarNode(instance).className.match(/\bprogress-bar-warning\b/)); }); it('Should default to min:0, max:100', () => { let instance = ReactTestUtils.renderIntoDocument( <ProgressBar now={5} /> ); let bar = getProgressBarNode(instance); assert.equal(bar.getAttribute('aria-valuemin'), '0'); assert.equal(bar.getAttribute('aria-valuemax'), '100'); }); it('Should have 0% computed width', () => { let instance = ReactTestUtils.renderIntoDocument( <ProgressBar min={0} max={10} now={0} /> ); assert.equal(getProgressBarNode(instance).style.width, '0%'); }); it('Should have 10% computed width', () => { let instance = ReactTestUtils.renderIntoDocument( <ProgressBar min={0} max={10} now={1} /> ); assert.equal(getProgressBarNode(instance).style.width, '10%'); }); it('Should have 100% computed width', () => { let instance = ReactTestUtils.renderIntoDocument( <ProgressBar min={0} max={10} now={10} /> ); assert.equal(getProgressBarNode(instance).style.width, '100%'); }); it('Should have 50% computed width with non-zero min', () => { let instance = ReactTestUtils.renderIntoDocument( <ProgressBar min={1} max={11} now={6} /> ); assert.equal(getProgressBarNode(instance).style.width, '50%'); }); it('Should not have label', () => { let instance = ReactTestUtils.renderIntoDocument( <ProgressBar min={0} max={10} now={5} bsStyle='primary' /> ); assert.equal(React.findDOMNode(instance).innerText, ''); }); it('Should have label', () => { let instance = ReactTestUtils.renderIntoDocument( <ProgressBar min={0} max={10} now={5} bsStyle='primary' label='min:%(min)s, max:%(max)s, now:%(now)s, percent:%(percent)s, bsStyle:%(bsStyle)s' /> ); assert.equal(React.findDOMNode(instance).innerText, 'min:0, max:10, now:5, percent:50, bsStyle:primary'); }); it('Should have screen reader only label', () => { let instance = ReactTestUtils.renderIntoDocument( <ProgressBar min={0} max={10} now={5} bsStyle='primary' srOnly label='min:%(min)s, max:%(max)s, now:%(now)s, percent:%(percent)s, bsStyle:%(bsStyle)s' /> ); let srLabel = ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'sr-only'); assert.equal(React.findDOMNode(srLabel).innerText, 'min:0, max:10, now:5, percent:50, bsStyle:primary'); }); it('Should have a label that is a React component', () => { let customLabel = ( <strong className="special-label">My label</strong> ); let instance = ReactTestUtils.renderIntoDocument( <ProgressBar min={0} max={10} now={5} bsStyle='primary' label={customLabel} /> ); assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'special-label')); }); it('Should have screen reader only label that wraps a React component', () => { let customLabel = ( <strong className="special-label">My label</strong> ); let instance = ReactTestUtils.renderIntoDocument( <ProgressBar min={0} max={10} now={5} bsStyle='primary' label={customLabel} srOnly /> ); let srLabel = ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'sr-only'); let component = ReactTestUtils.findRenderedDOMComponentWithClass(srLabel, 'special-label'); assert.ok(component); }); it('Should show striped bar', () => { let instance = ReactTestUtils.renderIntoDocument( <ProgressBar min={1} max={11} now={6} striped /> ); assert.ok(React.findDOMNode(instance).firstChild.className.match(/\bprogress-bar-striped\b/)); }); it('Should show animated striped bar', () => { let instance = ReactTestUtils.renderIntoDocument( <ProgressBar min={1} max={11} now={6} active /> ); const barClassName = React.findDOMNode(instance).firstChild.className; assert.ok(barClassName.match(/\bprogress-bar-striped\b/)); assert.ok(barClassName.match(/\bactive\b/)); }); it('Should show stacked bars', () => { let instance = ReactTestUtils.renderIntoDocument( <ProgressBar> <ProgressBar key={1} now={50} /> <ProgressBar key={2} now={30} /> </ProgressBar> ); let wrapper = React.findDOMNode(instance); let bar1 = wrapper.firstChild; let bar2 = wrapper.lastChild; assert.ok(wrapper.className.match(/\bprogress\b/)); assert.ok(bar1.className.match(/\bprogress-bar\b/)); assert.equal(bar1.style.width, '50%'); assert.ok(bar2.className.match(/\bprogress-bar\b/)); assert.equal(bar2.style.width, '30%'); }); it('Should render active and striped children in stacked bar too', () => { let instance = ReactTestUtils.renderIntoDocument( <ProgressBar> <ProgressBar active key={1} now={50} /> <ProgressBar striped key={2} now={30} /> </ProgressBar> ); let wrapper = React.findDOMNode(instance); let bar1 = wrapper.firstChild; let bar2 = wrapper.lastChild; assert.ok(wrapper.className.match(/\bprogress\b/)); assert.ok(bar1.className.match(/\bprogress-bar\b/)); assert.ok(bar1.className.match(/\bactive\b/)); assert.ok(bar1.className.match(/\bprogress-bar-striped\b/)); assert.ok(bar2.className.match(/\bprogress-bar\b/)); assert.ok(bar2.className.match(/\bprogress-bar-striped\b/)); assert.notOk(bar2.className.match(/\bactive\b/)); }); it('allows only ProgressBar in children', () => { ReactTestUtils.renderIntoDocument( <ProgressBar> <ProgressBar key={1} /> <div /> <ProgressBar key={2} /> </ProgressBar> ); shouldWarn('Failed propType'); }); });
app/javascript/mastodon/features/account_timeline/components/moved_note.js
WitchesTown/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { FormattedMessage } from 'react-intl'; import ImmutablePureComponent from 'react-immutable-pure-component'; import AvatarOverlay from '../../../components/avatar_overlay'; import DisplayName from '../../../components/display_name'; export default class MovedNote extends ImmutablePureComponent { static contextTypes = { router: PropTypes.object, }; static propTypes = { from: ImmutablePropTypes.map.isRequired, to: ImmutablePropTypes.map.isRequired, }; handleAccountClick = e => { if (e.button === 0) { e.preventDefault(); this.context.router.history.push(`/accounts/${this.props.to.get('id')}`); } e.stopPropagation(); } render () { const { from, to } = this.props; const displayNameHtml = { __html: from.get('display_name_html') }; return ( <div className='account__moved-note'> <div className='account__moved-note__message'> <div className='account__moved-note__icon-wrapper'><i className='fa fa-fw fa-suitcase account__moved-note__icon' /></div> <FormattedMessage id='account.moved_to' defaultMessage='{name} has moved to:' values={{ name: <bdi><strong dangerouslySetInnerHTML={displayNameHtml} /></bdi> }} /> </div> <a href={to.get('url')} onClick={this.handleAccountClick} className='detailed-status__display-name'> <div className='detailed-status__display-avatar'><AvatarOverlay account={to} friend={from} /></div> <DisplayName account={to} /> </a> </div> ); } }
tp-3/recursos/react-slingshot/src/components/Root.js
solp/sovos-reactivo-2017
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import App from './App'; import { BrowserRouter as Router } from 'react-router-dom'; export default class Root extends Component { render() { return ( <Router> <App /> </Router> ); } } Root.propTypes = { history: PropTypes.object };
imports/components/navbar.js
RGaldamez/MeteorReactScaffold
import React from 'react'; class Navbar extends React.Component { render() { return ( <nav class="navbar navbar-expand-sm navbar-light bg-light mb-3"> <div class="container"> <a class="navbar-brand" href="#">Navbar</a> <button class="navbar-toggler" data-toggle="collapse" data-target="#navbarNav1"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNav1"> <ul class="navbar-nav"> <li class="nav-item"> <a class="nav-link" href="#">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="#">About</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Services</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Contact</a> </li> </ul> </div> </div> </nav> ) } } export default Navbar;
es/components/Chat/NotificationMessages/NameChangedMessage.js
welovekpop/uwave-web-welovekpop.club
import _jsx from "@babel/runtime/helpers/builtin/jsx"; import React from 'react'; import PropTypes from 'prop-types'; import UserNotificationMessage from './UserNotificationMessage'; var UserNameChanged = function UserNameChanged(_ref) { var user = _ref.user, timestamp = _ref.timestamp, newUsername = _ref.newUsername; return _jsx(UserNotificationMessage, { type: "userNameChanged", className: "ChatMessage--userNameChanged", i18nKey: "chat.userNameChanged", user: user, timestamp: timestamp, newUsername: newUsername }); }; UserNameChanged.propTypes = process.env.NODE_ENV !== "production" ? { user: PropTypes.object.isRequired, newUsername: PropTypes.string.isRequired, timestamp: PropTypes.number.isRequired } : {}; export default UserNameChanged; //# sourceMappingURL=NameChangedMessage.js.map
docs/src/app/components/pages/components/List/ExampleSimple.js
andrejunges/material-ui
import React from 'react'; import MobileTearSheet from '../../../MobileTearSheet'; import {List, ListItem} from 'material-ui/List'; import ContentInbox from 'material-ui/svg-icons/content/inbox'; import ActionGrade from 'material-ui/svg-icons/action/grade'; import ContentSend from 'material-ui/svg-icons/content/send'; import ContentDrafts from 'material-ui/svg-icons/content/drafts'; import Divider from 'material-ui/Divider'; import ActionInfo from 'material-ui/svg-icons/action/info'; const ListExampleSimple = () => ( <MobileTearSheet> <List> <ListItem primaryText="Inbox" leftIcon={<ContentInbox />} /> <ListItem primaryText="Starred" leftIcon={<ActionGrade />} /> <ListItem primaryText="Sent mail" leftIcon={<ContentSend />} /> <ListItem primaryText="Drafts" leftIcon={<ContentDrafts />} /> <ListItem primaryText="Inbox" leftIcon={<ContentInbox />} /> </List> <Divider /> <List> <ListItem primaryText="All mail" rightIcon={<ActionInfo />} /> <ListItem primaryText="Trash" rightIcon={<ActionInfo />} /> <ListItem primaryText="Spam" rightIcon={<ActionInfo />} /> <ListItem primaryText="Follow up" rightIcon={<ActionInfo />} /> </List> </MobileTearSheet> ); export default ListExampleSimple;
Libraries/Components/TextInput/TextInput.js
mironiasty/react-native
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule TextInput * @flow */ 'use strict'; const ColorPropType = require('ColorPropType'); const DocumentSelectionState = require('DocumentSelectionState'); const EventEmitter = require('EventEmitter'); const NativeMethodsMixin = require('NativeMethodsMixin'); const Platform = require('Platform'); const React = require('React'); const PropTypes = require('prop-types'); const ReactNative = require('ReactNative'); const StyleSheet = require('StyleSheet'); const Text = require('Text'); const TextInputState = require('TextInputState'); const TimerMixin = require('react-timer-mixin'); const TouchableWithoutFeedback = require('TouchableWithoutFeedback'); const UIManager = require('UIManager'); const ViewPropTypes = require('ViewPropTypes'); const emptyFunction = require('fbjs/lib/emptyFunction'); const invariant = require('fbjs/lib/invariant'); const requireNativeComponent = require('requireNativeComponent'); const warning = require('fbjs/lib/warning'); const onlyMultiline = { onTextInput: true, children: true, }; if (Platform.OS === 'android') { var AndroidTextInput = requireNativeComponent('AndroidTextInput', null); } else if (Platform.OS === 'ios') { var RCTTextView = requireNativeComponent('RCTTextView', null); var RCTTextField = requireNativeComponent('RCTTextField', null); } type Event = Object; type Selection = { start: number, end?: number, }; const DataDetectorTypes = [ 'phoneNumber', 'link', 'address', 'calendarEvent', 'none', 'all', ]; /** * A foundational component for inputting text into the app via a * keyboard. Props provide configurability for several features, such as * auto-correction, auto-capitalization, placeholder text, and different keyboard * types, such as a numeric keypad. * * The simplest use case is to plop down a `TextInput` and subscribe to the * `onChangeText` events to read the user input. There are also other events, * such as `onSubmitEditing` and `onFocus` that can be subscribed to. A simple * example: * * ```ReactNativeWebPlayer * import React, { Component } from 'react'; * import { AppRegistry, TextInput } from 'react-native'; * * export default class UselessTextInput extends Component { * constructor(props) { * super(props); * this.state = { text: 'Useless Placeholder' }; * } * * render() { * return ( * <TextInput * style={{height: 40, borderColor: 'gray', borderWidth: 1}} * onChangeText={(text) => this.setState({text})} * value={this.state.text} * /> * ); * } * } * * // skip this line if using Create React Native App * AppRegistry.registerComponent('AwesomeProject', () => UselessTextInput); * ``` * * Note that some props are only available with `multiline={true/false}`. * Additionally, border styles that apply to only one side of the element * (e.g., `borderBottomColor`, `borderLeftWidth`, etc.) will not be applied if * `multiline=false`. To achieve the same effect, you can wrap your `TextInput` * in a `View`: * * ```ReactNativeWebPlayer * import React, { Component } from 'react'; * import { AppRegistry, View, TextInput } from 'react-native'; * * class UselessTextInput extends Component { * render() { * return ( * <TextInput * {...this.props} // Inherit any props passed to it; e.g., multiline, numberOfLines below * editable = {true} * maxLength = {40} * /> * ); * } * } * * export default class UselessTextInputMultiline extends Component { * constructor(props) { * super(props); * this.state = { * text: 'Useless Multiline Placeholder', * }; * } * * // If you type something in the text box that is a color, the background will change to that * // color. * render() { * return ( * <View style={{ * backgroundColor: this.state.text, * borderBottomColor: '#000000', * borderBottomWidth: 1 }} * > * <UselessTextInput * multiline = {true} * numberOfLines = {4} * onChangeText={(text) => this.setState({text})} * value={this.state.text} * /> * </View> * ); * } * } * * // skip these lines if using Create React Native App * AppRegistry.registerComponent( * 'AwesomeProject', * () => UselessTextInputMultiline * ); * ``` * * `TextInput` has by default a border at the bottom of its view. This border * has its padding set by the background image provided by the system, and it * cannot be changed. Solutions to avoid this is to either not set height * explicitly, case in which the system will take care of displaying the border * in the correct position, or to not display the border by setting * `underlineColorAndroid` to transparent. * * Note that on Android performing text selection in input can change * app's activity `windowSoftInputMode` param to `adjustResize`. * This may cause issues with components that have position: 'absolute' * while keyboard is active. To avoid this behavior either specify `windowSoftInputMode` * in AndroidManifest.xml ( https://developer.android.com/guide/topics/manifest/activity-element.html ) * or control this param programmatically with native code. * */ // $FlowFixMe(>=0.41.0) const TextInput = React.createClass({ statics: { /* TODO(brentvatne) docs are needed for this */ State: TextInputState, }, propTypes: { ...ViewPropTypes, /** * Can tell `TextInput` to automatically capitalize certain characters. * * - `characters`: all characters. * - `words`: first letter of each word. * - `sentences`: first letter of each sentence (*default*). * - `none`: don't auto capitalize anything. */ autoCapitalize: PropTypes.oneOf([ 'none', 'sentences', 'words', 'characters', ]), /** * If `false`, disables auto-correct. The default value is `true`. */ autoCorrect: PropTypes.bool, /** * If `false`, disables spell-check style (i.e. red underlines). * The default value is inherited from `autoCorrect`. * @platform ios */ spellCheck: PropTypes.bool, /** * If `true`, focuses the input on `componentDidMount`. * The default value is `false`. */ autoFocus: PropTypes.bool, /** * If `false`, text is not editable. The default value is `true`. */ editable: PropTypes.bool, /** * Determines which keyboard to open, e.g.`numeric`. * * The following values work across platforms: * * - `default` * - `numeric` * - `email-address` * - `phone-pad` */ keyboardType: PropTypes.oneOf([ // Cross-platform 'default', 'email-address', 'numeric', 'phone-pad', // iOS-only 'ascii-capable', 'numbers-and-punctuation', 'url', 'number-pad', 'name-phone-pad', 'decimal-pad', 'twitter', 'web-search', ]), /** * Determines the color of the keyboard. * @platform ios */ keyboardAppearance: PropTypes.oneOf([ 'default', 'light', 'dark', ]), /** * Determines how the return key should look. On Android you can also use * `returnKeyLabel`. * * *Cross platform* * * The following values work across platforms: * * - `done` * - `go` * - `next` * - `search` * - `send` * * *Android Only* * * The following values work on Android only: * * - `none` * - `previous` * * *iOS Only* * * The following values work on iOS only: * * - `default` * - `emergency-call` * - `google` * - `join` * - `route` * - `yahoo` */ returnKeyType: PropTypes.oneOf([ // Cross-platform 'done', 'go', 'next', 'search', 'send', // Android-only 'none', 'previous', // iOS-only 'default', 'emergency-call', 'google', 'join', 'route', 'yahoo', ]), /** * Sets the return key to the label. Use it instead of `returnKeyType`. * @platform android */ returnKeyLabel: PropTypes.string, /** * Limits the maximum number of characters that can be entered. Use this * instead of implementing the logic in JS to avoid flicker. */ maxLength: PropTypes.number, /** * Sets the number of lines for a `TextInput`. Use it with multiline set to * `true` to be able to fill the lines. * @platform android */ numberOfLines: PropTypes.number, /** * When `false`, if there is a small amount of space available around a text input * (e.g. landscape orientation on a phone), the OS may choose to have the user edit * the text inside of a full screen text input mode. When `true`, this feature is * disabled and users will always edit the text directly inside of the text input. * Defaults to `false`. * @platform android */ disableFullscreenUI: PropTypes.bool, /** * If `true`, the keyboard disables the return key when there is no text and * automatically enables it when there is text. The default value is `false`. * @platform ios */ enablesReturnKeyAutomatically: PropTypes.bool, /** * If `true`, the text input can be multiple lines. * The default value is `false`. */ multiline: PropTypes.bool, /** * Set text break strategy on Android API Level 23+, possible values are `simple`, `highQuality`, `balanced` * The default value is `simple`. * @platform android */ textBreakStrategy: PropTypes.oneOf(['simple', 'highQuality', 'balanced']), /** * Callback that is called when the text input is blurred. */ onBlur: PropTypes.func, /** * Callback that is called when the text input is focused. */ onFocus: PropTypes.func, /** * Callback that is called when the text input's text changes. */ onChange: PropTypes.func, /** * Callback that is called when the text input's text changes. * Changed text is passed as an argument to the callback handler. */ onChangeText: PropTypes.func, /** * Callback that is called when the text input's content size changes. * This will be called with * `{ nativeEvent: { contentSize: { width, height } } }`. * * Only called for multiline text inputs. */ onContentSizeChange: PropTypes.func, /** * Callback that is called when text input ends. */ onEndEditing: PropTypes.func, /** * Callback that is called when the text input selection is changed. * This will be called with * `{ nativeEvent: { selection: { start, end } } }`. */ onSelectionChange: PropTypes.func, /** * Callback that is called when the text input's submit button is pressed. * Invalid if `multiline={true}` is specified. */ onSubmitEditing: PropTypes.func, /** * Callback that is called when a key is pressed. * This will be called with `{ nativeEvent: { key: keyValue } }` * where `keyValue` is `'Enter'` or `'Backspace'` for respective keys and * the typed-in character otherwise including `' '` for space. * Fires before `onChange` callbacks. * @platform ios */ onKeyPress: PropTypes.func, /** * Invoked on mount and layout changes with `{x, y, width, height}`. */ onLayout: PropTypes.func, /** * Invoked on content scroll with `{ nativeEvent: { contentOffset: { x, y } } }`. * May also contain other properties from ScrollEvent but on Android contentSize * is not provided for performance reasons. */ onScroll: PropTypes.func, /** * The string that will be rendered before text input has been entered. */ placeholder: PropTypes.node, /** * The text color of the placeholder string. */ placeholderTextColor: ColorPropType, /** * If `true`, the text input obscures the text entered so that sensitive text * like passwords stay secure. The default value is `false`. */ secureTextEntry: PropTypes.bool, /** * The highlight and cursor color of the text input. */ selectionColor: ColorPropType, /** * An instance of `DocumentSelectionState`, this is some state that is responsible for * maintaining selection information for a document. * * Some functionality that can be performed with this instance is: * * - `blur()` * - `focus()` * - `update()` * * > You can reference `DocumentSelectionState` in * > [`vendor/document/selection/DocumentSelectionState.js`](https://github.com/facebook/react-native/blob/master/Libraries/vendor/document/selection/DocumentSelectionState.js) * * @platform ios */ selectionState: PropTypes.instanceOf(DocumentSelectionState), /** * The start and end of the text input's selection. Set start and end to * the same value to position the cursor. */ selection: PropTypes.shape({ start: PropTypes.number.isRequired, end: PropTypes.number, }), /** * The value to show for the text input. `TextInput` is a controlled * component, which means the native value will be forced to match this * value prop if provided. For most uses, this works great, but in some * cases this may cause flickering - one common cause is preventing edits * by keeping value the same. In addition to simply setting the same value, * either set `editable={false}`, or set/update `maxLength` to prevent * unwanted edits without flicker. */ value: PropTypes.string, /** * Provides an initial value that will change when the user starts typing. * Useful for simple use-cases where you do not want to deal with listening * to events and updating the value prop to keep the controlled state in sync. */ defaultValue: PropTypes.string, /** * When the clear button should appear on the right side of the text view. * @platform ios */ clearButtonMode: PropTypes.oneOf([ 'never', 'while-editing', 'unless-editing', 'always', ]), /** * If `true`, clears the text field automatically when editing begins. * @platform ios */ clearTextOnFocus: PropTypes.bool, /** * If `true`, all text will automatically be selected on focus. */ selectTextOnFocus: PropTypes.bool, /** * If `true`, the text field will blur when submitted. * The default value is true for single-line fields and false for * multiline fields. Note that for multiline fields, setting `blurOnSubmit` * to `true` means that pressing return will blur the field and trigger the * `onSubmitEditing` event instead of inserting a newline into the field. */ blurOnSubmit: PropTypes.bool, /** * Note that not all Text styles are supported, * see [Issue#7070](https://github.com/facebook/react-native/issues/7070) * for more detail. * * [Styles](docs/style.html) */ style: Text.propTypes.style, /** * The color of the `TextInput` underline. * @platform android */ underlineColorAndroid: ColorPropType, /** * If defined, the provided image resource will be rendered on the left. * @platform android */ inlineImageLeft: PropTypes.string, /** * Padding between the inline image, if any, and the text input itself. * @platform android */ inlineImagePadding: PropTypes.number, /** * Determines the types of data converted to clickable URLs in the text input. * Only valid if `multiline={true}` and `editable={false}`. * By default no data types are detected. * * You can provide one type or an array of many types. * * Possible values for `dataDetectorTypes` are: * * - `'phoneNumber'` * - `'link'` * - `'address'` * - `'calendarEvent'` * - `'none'` * - `'all'` * * @platform ios */ dataDetectorTypes: PropTypes.oneOfType([ PropTypes.oneOf(DataDetectorTypes), PropTypes.arrayOf(PropTypes.oneOf(DataDetectorTypes)), ]), /** * If `true`, caret is hidden. The default value is `false`. */ caretHidden: PropTypes.bool, }, /** * `NativeMethodsMixin` will look for this when invoking `setNativeProps`. We * make `this` look like an actual native component class. */ mixins: [NativeMethodsMixin, TimerMixin], /** * Returns `true` if the input is currently focused; `false` otherwise. */ isFocused: function(): boolean { return TextInputState.currentlyFocusedField() === ReactNative.findNodeHandle(this._inputRef); }, contextTypes: { onFocusRequested: PropTypes.func, focusEmitter: PropTypes.instanceOf(EventEmitter), }, _inputRef: (undefined: any), _focusSubscription: (undefined: ?Function), _lastNativeText: (undefined: ?string), _lastNativeSelection: (undefined: ?Selection), componentDidMount: function() { this._lastNativeText = this.props.value; if (!this.context.focusEmitter) { if (this.props.autoFocus) { this.requestAnimationFrame(this.focus); } return; } this._focusSubscription = this.context.focusEmitter.addListener( 'focus', (el) => { if (this === el) { this.requestAnimationFrame(this.focus); } else if (this.isFocused()) { this.blur(); } } ); if (this.props.autoFocus) { this.context.onFocusRequested(this); } }, componentWillUnmount: function() { this._focusSubscription && this._focusSubscription.remove(); if (this.isFocused()) { this.blur(); } }, getChildContext: function(): Object { return {isInAParentText: true}; }, childContextTypes: { isInAParentText: PropTypes.bool }, /** * Removes all text from the `TextInput`. */ clear: function() { this.setNativeProps({text: ''}); }, render: function() { if (Platform.OS === 'ios') { return this._renderIOS(); } else if (Platform.OS === 'android') { return this._renderAndroid(); } }, _getText: function(): ?string { return typeof this.props.value === 'string' ? this.props.value : ( typeof this.props.defaultValue === 'string' ? this.props.defaultValue : '' ); }, _setNativeRef: function(ref: any) { this._inputRef = ref; }, _renderIOS: function() { var textContainer; var props = Object.assign({}, this.props); props.style = [this.props.style]; if (props.selection && props.selection.end == null) { props.selection = {start: props.selection.start, end: props.selection.start}; } if (!props.multiline) { if (__DEV__) { for (var propKey in onlyMultiline) { if (props[propKey]) { const error = new Error( 'TextInput prop `' + propKey + '` is only supported with multiline.' ); warning(false, '%s', error.stack); } } } textContainer = <RCTTextField ref={this._setNativeRef} {...props} onFocus={this._onFocus} onBlur={this._onBlur} onChange={this._onChange} onSelectionChange={this._onSelectionChange} onSelectionChangeShouldSetResponder={emptyFunction.thatReturnsTrue} text={this._getText()} />; } else { var children = props.children; var childCount = 0; React.Children.forEach(children, () => ++childCount); invariant( !(props.value && childCount), 'Cannot specify both value and children.' ); if (childCount >= 1) { children = <Text style={props.style}>{children}</Text>; } if (props.inputView) { children = [children, props.inputView]; } props.style.unshift(styles.multilineInput); textContainer = <RCTTextView ref={this._setNativeRef} {...props} children={children} onFocus={this._onFocus} onBlur={this._onBlur} onChange={this._onChange} onContentSizeChange={this.props.onContentSizeChange} onSelectionChange={this._onSelectionChange} onTextInput={this._onTextInput} onSelectionChangeShouldSetResponder={emptyFunction.thatReturnsTrue} text={this._getText()} dataDetectorTypes={this.props.dataDetectorTypes} onScroll={this._onScroll} />; } return ( <TouchableWithoutFeedback onLayout={props.onLayout} onPress={this._onPress} rejectResponderTermination={true} accessible={props.accessible} accessibilityLabel={props.accessibilityLabel} accessibilityTraits={props.accessibilityTraits} nativeID={this.props.nativeID} testID={props.testID}> {textContainer} </TouchableWithoutFeedback> ); }, _renderAndroid: function() { const props = Object.assign({}, this.props); props.style = [this.props.style]; props.autoCapitalize = UIManager.AndroidTextInput.Constants.AutoCapitalizationType[this.props.autoCapitalize]; var children = this.props.children; var childCount = 0; React.Children.forEach(children, () => ++childCount); invariant( !(this.props.value && childCount), 'Cannot specify both value and children.' ); if (childCount > 1) { children = <Text>{children}</Text>; } if (props.selection && props.selection.end == null) { props.selection = {start: props.selection.start, end: props.selection.start}; } const textContainer = <AndroidTextInput ref={this._setNativeRef} {...props} mostRecentEventCount={0} onFocus={this._onFocus} onBlur={this._onBlur} onChange={this._onChange} onSelectionChange={this._onSelectionChange} onTextInput={this._onTextInput} text={this._getText()} children={children} disableFullscreenUI={this.props.disableFullscreenUI} textBreakStrategy={this.props.textBreakStrategy} onScroll={this._onScroll} />; return ( <TouchableWithoutFeedback onLayout={this.props.onLayout} onPress={this._onPress} accessible={this.props.accessible} accessibilityLabel={this.props.accessibilityLabel} accessibilityComponentType={this.props.accessibilityComponentType} nativeID={this.props.nativeID} testID={this.props.testID}> {textContainer} </TouchableWithoutFeedback> ); }, _onFocus: function(event: Event) { if (this.props.onFocus) { this.props.onFocus(event); } if (this.props.selectionState) { this.props.selectionState.focus(); } }, _onPress: function(event: Event) { if (this.props.editable || this.props.editable === undefined) { this.focus(); } }, _onChange: function(event: Event) { // Make sure to fire the mostRecentEventCount first so it is already set on // native when the text value is set. if (this._inputRef) { this._inputRef.setNativeProps({ mostRecentEventCount: event.nativeEvent.eventCount, }); } var text = event.nativeEvent.text; this.props.onChange && this.props.onChange(event); this.props.onChangeText && this.props.onChangeText(text); if (!this._inputRef) { // calling `this.props.onChange` or `this.props.onChangeText` // may clean up the input itself. Exits here. return; } this._lastNativeText = text; this.forceUpdate(); }, _onSelectionChange: function(event: Event) { this.props.onSelectionChange && this.props.onSelectionChange(event); if (!this._inputRef) { // calling `this.props.onSelectionChange` // may clean up the input itself. Exits here. return; } this._lastNativeSelection = event.nativeEvent.selection; if (this.props.selection || this.props.selectionState) { this.forceUpdate(); } }, componentDidUpdate: function () { // This is necessary in case native updates the text and JS decides // that the update should be ignored and we should stick with the value // that we have in JS. const nativeProps = {}; if (this._lastNativeText !== this.props.value && typeof this.props.value === 'string') { nativeProps.text = this.props.value; } // Selection is also a controlled prop, if the native value doesn't match // JS, update to the JS value. const {selection} = this.props; if (this._lastNativeSelection && selection && (this._lastNativeSelection.start !== selection.start || this._lastNativeSelection.end !== selection.end)) { nativeProps.selection = this.props.selection; } if (Object.keys(nativeProps).length > 0 && this._inputRef) { this._inputRef.setNativeProps(nativeProps); } if (this.props.selectionState && selection) { this.props.selectionState.update(selection.start, selection.end); } }, _onBlur: function(event: Event) { this.blur(); if (this.props.onBlur) { this.props.onBlur(event); } if (this.props.selectionState) { this.props.selectionState.blur(); } }, _onTextInput: function(event: Event) { this.props.onTextInput && this.props.onTextInput(event); }, _onScroll: function(event: Event) { this.props.onScroll && this.props.onScroll(event); }, }); var styles = StyleSheet.create({ multilineInput: { // This default top inset makes RCTTextView seem as close as possible // to single-line RCTTextField defaults, using the system defaults // of font size 17 and a height of 31 points. paddingTop: 5, }, }); module.exports = TextInput;
src/components/MainPage.js
anjren/UncleChenWebsite
import React from 'react'; import MainNav from './MainNav'; // Static Main Page export const MainPage = () => ( <div> <div className="row uc-landing__header-wrapper"> <img className="twelve column uc-landing__header" type="image/png" src="/img/delightful_food_for_a_healthy_life.png"/> </div> <div className="uc-workspace-grid--blocky"> <div className="uc-workspace-grid-box-nonclick"> </div> <div className="uc-workspace-grid-box-nonclick uc-workspace-grid-box-nonclick"> <h5>Serving Chinese Customers, Penetrating US Markets</h5> <p> <strong>Union (Lian How) Food</strong> is a family-owned business with a continuous operation for more than half a century. In 1965, Mr. Y. B. Huang, founder of the company, started producing and marketing the proprietarily fermented bean and chili pastes/sauces in Taiwan. By the 1970s, the company had expanded with processing and sales facilities in China, Thailand, South and Central America, and the US Union International Food (UIF) was established in California in 1985. Under the <strong>Uncle Chen®</strong> brand, the subsidiary extended its business to include edible oils, sauces, seasonings/spices, teas and dried Asian foods. UIF has always aimed to produce and maintain the uncompromising high quality on its tasty, healthful, and convenient food products with continuous innovations. By implementing HACCP operational protocol and obtaining USFDA certification, UIF can proudly affirm the product safety for our worldwide customers. </p> </div> <div className="uc-workspace-grid-box-nonclick uc-workspace-grid-box-nonclick--red"></div> <div className="uc-workspace-grid-box-nonclick uc-workspace-grid-box-nonclick"> <h5>A Committment to Good Health</h5> <p> It has been Mr. Y. B. Huang’s firm commitment ever since the founding of Union Food, to conduct the business with social responsibility. Taking advantage of traditional Chinese fermentation processing while adopting the advanced technologies, the company endeavors to produce the delightfully tasty, proven healthful, and welcomingly convenient products for the market, both in China and abroad. Throughout his life he emphasizes personal integrity, product quality, and charity. Therefore, he never sacrifices these standards for personal gains, always sells high quality products at modest prices, and continually makes contributions to the communities. Mr. Daniel Chen, general manager of the company, was named one of the “One Hundred Outstanding Youths” in 2005 by the Chinese Ministry of State. With his education and training in traditional Chinese medicine, he applies the “food for health” principle in formulating and manufacturing products marketed by UIF. Safety of products, innovation in R&D, and excellence in customer services are his priority and goals in conducting the business. Consequently, UIF’s corporate mission statement is: Producing and maintaining the uncompromising high quality of tasty, healthful, and convenient food products with continuous innovations, and the ever-improving customer services. </p> </div> <div className="uc-workspace-grid-box-nonclick uc-workspace-grid-box-nonclick--red"></div> <div className="uc-workspace-grid-box-nonclick uc-workspace-grid-box-nonclick"> <h5>American Standards for a Chinese Market</h5> <p> Horrendous incidents of food poisoning and contamination, such as, recycled waste oil used for human consumption, adulterated baby formula causing infant malnutrition and developmental damages, and health hazardous rice and bogus drugs on the market, were reported in recent years in China. People begin to be deeply concerned about food safety. Mr. Y.B. Huang and Daniel Chen felt the pain for the consumers there, and pondered, “Can’t we market our products sold in the United States for the past 30 years also on the shelves in China to lead the reform of its food industry?” “American standards for Chinese market!” has, thus, quickly become an idea enthusiastically received by our clients and supported by UIF associates. Consequently, entering Chinese market is now not only the hope, but determination and an aim for immediate actions of the corporation! </p> </div> <div></div> </div> <div className="uc-landing__contact-us"> <div> <h5>Store Hours & Location</h5> </div> <div> <p>Open daily 9am - 5pm</p> <p> 33035 Transit Avenue Union City, CA 94587 </p> </div> <div> <h5>Contact Us</h5> </div> <div> <p> <span className="socicon-instagram"></span> @HelloUncleChen </p> <p>For institutional clients: +15104718299</p> <p>For supermarkets: +15104716799</p> <p>For restaurants: +15104713799</p> <p>By fax: +15104719999</p> <p>By email: <a href="mailto:[email protected]">[email protected]</a></p> </div> </div> </div> ) export default MainPage;
components/Navigation/Navigation.js
rpowis/pusscat.lol
/** * React Static Boilerplate * https://github.com/koistya/react-static-boilerplate * Copyright (c) Konstantin Tarkus (@koistya) | MIT license */ import React, { Component } from 'react'; import './Navigation.scss'; import Link from '../Link'; export default class extends Component { render() { return ( <ul className="Navigation" role="menu"> <li className="Navigation-item"> <a className="Navigation-link" href="/" onClick={Link.handleClick}>Home</a> </li> <li className="Navigation-item"> <a className="Navigation-link" href="/about" onClick={Link.handleClick}>About</a> </li> </ul> ); } }
ajax/libs/angular-ui-select/0.18.1/select.js
AMoo-Miki/cdnjs
/*! * ui-select * http://github.com/angular-ui/ui-select * Version: 0.18.1 - 2016-07-10T00:18:10.535Z * License: MIT */ (function () { "use strict"; var KEY = { TAB: 9, ENTER: 13, ESC: 27, SPACE: 32, LEFT: 37, UP: 38, RIGHT: 39, DOWN: 40, SHIFT: 16, CTRL: 17, ALT: 18, PAGE_UP: 33, PAGE_DOWN: 34, HOME: 36, END: 35, BACKSPACE: 8, DELETE: 46, COMMAND: 91, MAP: { 91 : "COMMAND", 8 : "BACKSPACE" , 9 : "TAB" , 13 : "ENTER" , 16 : "SHIFT" , 17 : "CTRL" , 18 : "ALT" , 19 : "PAUSEBREAK" , 20 : "CAPSLOCK" , 27 : "ESC" , 32 : "SPACE" , 33 : "PAGE_UP", 34 : "PAGE_DOWN" , 35 : "END" , 36 : "HOME" , 37 : "LEFT" , 38 : "UP" , 39 : "RIGHT" , 40 : "DOWN" , 43 : "+" , 44 : "PRINTSCREEN" , 45 : "INSERT" , 46 : "DELETE", 48 : "0" , 49 : "1" , 50 : "2" , 51 : "3" , 52 : "4" , 53 : "5" , 54 : "6" , 55 : "7" , 56 : "8" , 57 : "9" , 59 : ";", 61 : "=" , 65 : "A" , 66 : "B" , 67 : "C" , 68 : "D" , 69 : "E" , 70 : "F" , 71 : "G" , 72 : "H" , 73 : "I" , 74 : "J" , 75 : "K" , 76 : "L", 77 : "M" , 78 : "N" , 79 : "O" , 80 : "P" , 81 : "Q" , 82 : "R" , 83 : "S" , 84 : "T" , 85 : "U" , 86 : "V" , 87 : "W" , 88 : "X" , 89 : "Y" , 90 : "Z", 96 : "0" , 97 : "1" , 98 : "2" , 99 : "3" , 100 : "4" , 101 : "5" , 102 : "6" , 103 : "7" , 104 : "8" , 105 : "9", 106 : "*" , 107 : "+" , 109 : "-" , 110 : "." , 111 : "/", 112 : "F1" , 113 : "F2" , 114 : "F3" , 115 : "F4" , 116 : "F5" , 117 : "F6" , 118 : "F7" , 119 : "F8" , 120 : "F9" , 121 : "F10" , 122 : "F11" , 123 : "F12", 144 : "NUMLOCK" , 145 : "SCROLLLOCK" , 186 : ";" , 187 : "=" , 188 : "," , 189 : "-" , 190 : "." , 191 : "/" , 192 : "`" , 219 : "[" , 220 : "\\" , 221 : "]" , 222 : "'" }, isControl: function (e) { var k = e.which; switch (k) { case KEY.COMMAND: case KEY.SHIFT: case KEY.CTRL: case KEY.ALT: return true; } if (e.metaKey || e.ctrlKey || e.altKey) return true; return false; }, isFunctionKey: function (k) { k = k.which ? k.which : k; return k >= 112 && k <= 123; }, isVerticalMovement: function (k){ return ~[KEY.UP, KEY.DOWN].indexOf(k); }, isHorizontalMovement: function (k){ return ~[KEY.LEFT,KEY.RIGHT,KEY.BACKSPACE,KEY.DELETE].indexOf(k); }, toSeparator: function (k) { var sep = {ENTER:"\n",TAB:"\t",SPACE:" "}[k]; if (sep) return sep; // return undefined for special keys other than enter, tab or space. // no way to use them to cut strings. return KEY[k] ? undefined : k; } }; /** * Add querySelectorAll() to jqLite. * * jqLite find() is limited to lookups by tag name. * TODO This will change with future versions of AngularJS, to be removed when this happens * * See jqLite.find - why not use querySelectorAll? https://github.com/angular/angular.js/issues/3586 * See feat(jqLite): use querySelectorAll instead of getElementsByTagName in jqLite.find https://github.com/angular/angular.js/pull/3598 */ if (angular.element.prototype.querySelectorAll === undefined) { angular.element.prototype.querySelectorAll = function(selector) { return angular.element(this[0].querySelectorAll(selector)); }; } /** * Add closest() to jqLite. */ if (angular.element.prototype.closest === undefined) { angular.element.prototype.closest = function( selector) { var elem = this[0]; var matchesSelector = elem.matches || elem.webkitMatchesSelector || elem.mozMatchesSelector || elem.msMatchesSelector; while (elem) { if (matchesSelector.bind(elem)(selector)) { return elem; } else { elem = elem.parentElement; } } return false; }; } var latestId = 0; var uis = angular.module('ui.select', []) .constant('uiSelectConfig', { theme: 'bootstrap', searchEnabled: true, sortable: false, placeholder: '', // Empty by default, like HTML tag <select> refreshDelay: 1000, // In milliseconds closeOnSelect: true, skipFocusser: false, dropdownPosition: 'auto', removeSelected: true, generateId: function() { return latestId++; }, appendToBody: false }) // See Rename minErr and make it accessible from outside https://github.com/angular/angular.js/issues/6913 .service('uiSelectMinErr', function() { var minErr = angular.$$minErr('ui.select'); return function() { var error = minErr.apply(this, arguments); var message = error.message.replace(new RegExp('\nhttp://errors.angularjs.org/.*'), ''); return new Error(message); }; }) // Recreates old behavior of ng-transclude. Used internally. .directive('uisTranscludeAppend', function () { return { link: function (scope, element, attrs, ctrl, transclude) { transclude(scope, function (clone) { element.append(clone); }); } }; }) /** * Highlights text that matches $select.search. * * Taken from AngularUI Bootstrap Typeahead * See https://github.com/angular-ui/bootstrap/blob/0.10.0/src/typeahead/typeahead.js#L340 */ .filter('highlight', function() { function escapeRegexp(queryToEscape) { return ('' + queryToEscape).replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1'); } return function(matchItem, query) { return query && matchItem ? ('' + matchItem).replace(new RegExp(escapeRegexp(query), 'gi'), '<span class="ui-select-highlight">$&</span>') : matchItem; }; }) /** * A read-only equivalent of jQuery's offset function: http://api.jquery.com/offset/ * * Taken from AngularUI Bootstrap Position: * See https://github.com/angular-ui/bootstrap/blob/master/src/position/position.js#L70 */ .factory('uisOffset', ['$document', '$window', function ($document, $window) { return function(element) { var boundingClientRect = element[0].getBoundingClientRect(); return { width: boundingClientRect.width || element.prop('offsetWidth'), height: boundingClientRect.height || element.prop('offsetHeight'), top: boundingClientRect.top + ($window.pageYOffset || $document[0].documentElement.scrollTop), left: boundingClientRect.left + ($window.pageXOffset || $document[0].documentElement.scrollLeft) }; }; }]); /** * Debounces functions * * Taken from UI Bootstrap $$debounce source code * See https://github.com/angular-ui/bootstrap/blob/master/src/debounce/debounce.js * */ uis.factory('$$uisDebounce', ['$timeout', function($timeout) { return function(callback, debounceTime) { var timeoutPromise; return function() { var self = this; var args = Array.prototype.slice.call(arguments); if (timeoutPromise) { $timeout.cancel(timeoutPromise); } timeoutPromise = $timeout(function() { callback.apply(self, args); }, debounceTime); }; }; }]); uis.directive('uiSelectChoices', ['uiSelectConfig', 'uisRepeatParser', 'uiSelectMinErr', '$compile', '$window', function(uiSelectConfig, RepeatParser, uiSelectMinErr, $compile, $window) { return { restrict: 'EA', require: '^uiSelect', replace: true, transclude: true, templateUrl: function(tElement) { // Needed so the uiSelect can detect the transcluded content tElement.addClass('ui-select-choices'); // Gets theme attribute from parent (ui-select) var theme = tElement.parent().attr('theme') || uiSelectConfig.theme; return theme + '/choices.tpl.html'; }, compile: function(tElement, tAttrs) { if (!tAttrs.repeat) throw uiSelectMinErr('repeat', "Expected 'repeat' expression."); // var repeat = RepeatParser.parse(attrs.repeat); var groupByExp = tAttrs.groupBy; var groupFilterExp = tAttrs.groupFilter; if (groupByExp) { var groups = tElement.querySelectorAll('.ui-select-choices-group'); if (groups.length !== 1) throw uiSelectMinErr('rows', "Expected 1 .ui-select-choices-group but got '{0}'.", groups.length); groups.attr('ng-repeat', RepeatParser.getGroupNgRepeatExpression()); } var parserResult = RepeatParser.parse(tAttrs.repeat); var choices = tElement.querySelectorAll('.ui-select-choices-row'); if (choices.length !== 1) { throw uiSelectMinErr('rows', "Expected 1 .ui-select-choices-row but got '{0}'.", choices.length); } choices.attr('ng-repeat', parserResult.repeatExpression(groupByExp)) .attr('ng-if', '$select.open'); //Prevent unnecessary watches when dropdown is closed var rowsInner = tElement.querySelectorAll('.ui-select-choices-row-inner'); if (rowsInner.length !== 1) { throw uiSelectMinErr('rows', "Expected 1 .ui-select-choices-row-inner but got '{0}'.", rowsInner.length); } rowsInner.attr('uis-transclude-append', ''); //Adding uisTranscludeAppend directive to row element after choices element has ngRepeat // If IE8 then need to target rowsInner to apply the ng-click attr as choices will not capture the event. var clickTarget = $window.document.addEventListener ? choices : rowsInner; clickTarget.attr('ng-click', '$select.select(' + parserResult.itemName + ',$select.skipFocusser,$event)'); return function link(scope, element, attrs, $select) { $select.parseRepeatAttr(attrs.repeat, groupByExp, groupFilterExp); //Result ready at $select.parserResult $select.disableChoiceExpression = attrs.uiDisableChoice; $select.onHighlightCallback = attrs.onHighlight; $select.dropdownPosition = attrs.position ? attrs.position.toLowerCase() : uiSelectConfig.dropdownPosition; scope.$on('$destroy', function() { choices.remove(); }); scope.$watch('$select.search', function(newValue) { if(newValue && !$select.open && $select.multiple) $select.activate(false, true); $select.activeIndex = $select.tagging.isActivated ? -1 : 0; if (!attrs.minimumInputLength || $select.search.length >= attrs.minimumInputLength) { $select.refresh(attrs.refresh); } else { $select.items = []; } }); attrs.$observe('refreshDelay', function() { // $eval() is needed otherwise we get a string instead of a number var refreshDelay = scope.$eval(attrs.refreshDelay); $select.refreshDelay = refreshDelay !== undefined ? refreshDelay : uiSelectConfig.refreshDelay; }); }; } }; }]); /** * Contains ui-select "intelligence". * * The goal is to limit dependency on the DOM whenever possible and * put as much logic in the controller (instead of the link functions) as possible so it can be easily tested. */ uis.controller('uiSelectCtrl', ['$scope', '$element', '$timeout', '$filter', '$$uisDebounce', 'uisRepeatParser', 'uiSelectMinErr', 'uiSelectConfig', '$parse', '$injector', '$window', function($scope, $element, $timeout, $filter, $$uisDebounce, RepeatParser, uiSelectMinErr, uiSelectConfig, $parse, $injector, $window) { var ctrl = this; var EMPTY_SEARCH = ''; ctrl.placeholder = uiSelectConfig.placeholder; ctrl.searchEnabled = uiSelectConfig.searchEnabled; ctrl.sortable = uiSelectConfig.sortable; ctrl.refreshDelay = uiSelectConfig.refreshDelay; ctrl.paste = uiSelectConfig.paste; ctrl.removeSelected = uiSelectConfig.removeSelected; //If selected item(s) should be removed from dropdown list ctrl.closeOnSelect = true; //Initialized inside uiSelect directive link function ctrl.skipFocusser = false; //Set to true to avoid returning focus to ctrl when item is selected ctrl.search = EMPTY_SEARCH; ctrl.activeIndex = 0; //Dropdown of choices ctrl.items = []; //All available choices ctrl.open = false; ctrl.focus = false; ctrl.disabled = false; ctrl.selected = undefined; ctrl.dropdownPosition = 'auto'; ctrl.focusser = undefined; //Reference to input element used to handle focus events ctrl.resetSearchInput = true; ctrl.multiple = undefined; // Initialized inside uiSelect directive link function ctrl.disableChoiceExpression = undefined; // Initialized inside uiSelectChoices directive link function ctrl.tagging = {isActivated: false, fct: undefined}; ctrl.taggingTokens = {isActivated: false, tokens: undefined}; ctrl.lockChoiceExpression = undefined; // Initialized inside uiSelectMatch directive link function ctrl.clickTriggeredSelect = false; ctrl.$filter = $filter; ctrl.$element = $element; // Use $injector to check for $animate and store a reference to it ctrl.$animate = (function () { try { return $injector.get('$animate'); } catch (err) { // $animate does not exist return null; } })(); ctrl.searchInput = $element.querySelectorAll('input.ui-select-search'); if (ctrl.searchInput.length !== 1) { throw uiSelectMinErr('searchInput', "Expected 1 input.ui-select-search but got '{0}'.", ctrl.searchInput.length); } ctrl.isEmpty = function() { return angular.isUndefined(ctrl.selected) || ctrl.selected === null || ctrl.selected === '' || (ctrl.multiple && ctrl.selected.length === 0); }; function _findIndex(collection, predicate, thisArg){ if (collection.findIndex){ return collection.findIndex(predicate, thisArg); } else { var list = Object(collection); var length = list.length >>> 0; var value; for (var i = 0; i < length; i++) { value = list[i]; if (predicate.call(thisArg, value, i, list)) { return i; } } return -1; } } // Most of the time the user does not want to empty the search input when in typeahead mode function _resetSearchInput() { if (ctrl.resetSearchInput || (ctrl.resetSearchInput === undefined && uiSelectConfig.resetSearchInput)) { ctrl.search = EMPTY_SEARCH; //reset activeIndex if (ctrl.selected && ctrl.items.length && !ctrl.multiple) { ctrl.activeIndex = _findIndex(ctrl.items, function(item){ return angular.equals(this, item); }, ctrl.selected); } } } function _groupsFilter(groups, groupNames) { var i, j, result = []; for(i = 0; i < groupNames.length ;i++){ for(j = 0; j < groups.length ;j++){ if(groups[j].name == [groupNames[i]]){ result.push(groups[j]); } } } return result; } // When the user clicks on ui-select, displays the dropdown list ctrl.activate = function(initSearchValue, avoidReset) { if (!ctrl.disabled && !ctrl.open) { if(!avoidReset) _resetSearchInput(); $scope.$broadcast('uis:activate'); ctrl.open = true; ctrl.activeIndex = ctrl.activeIndex >= ctrl.items.length ? 0 : ctrl.activeIndex; // ensure that the index is set to zero for tagging variants // that where first option is auto-selected if ( ctrl.activeIndex === -1 && ctrl.taggingLabel !== false ) { ctrl.activeIndex = 0; } var container = $element.querySelectorAll('.ui-select-choices-content'); var searchInput = $element.querySelectorAll('.ui-select-search'); if (ctrl.$animate && ctrl.$animate.on && ctrl.$animate.enabled(container[0])) { var animateHandler = function(elem, phase) { if (phase === 'start' && ctrl.items.length === 0) { // Only focus input after the animation has finished ctrl.$animate.off('removeClass', searchInput[0], animateHandler); $timeout(function () { ctrl.focusSearchInput(initSearchValue); }); } else if (phase === 'close') { // Only focus input after the animation has finished ctrl.$animate.off('enter', container[0], animateHandler); $timeout(function () { ctrl.focusSearchInput(initSearchValue); }); } }; if (ctrl.items.length > 0) { ctrl.$animate.on('enter', container[0], animateHandler); } else { ctrl.$animate.on('removeClass', searchInput[0], animateHandler); } } else { $timeout(function () { ctrl.focusSearchInput(initSearchValue); if(!ctrl.tagging.isActivated && ctrl.items.length > 1) { _ensureHighlightVisible(); } }); } } }; ctrl.focusSearchInput = function (initSearchValue) { ctrl.search = initSearchValue || ctrl.search; ctrl.searchInput[0].focus(); }; ctrl.findGroupByName = function(name) { return ctrl.groups && ctrl.groups.filter(function(group) { return group.name === name; })[0]; }; ctrl.parseRepeatAttr = function(repeatAttr, groupByExp, groupFilterExp) { function updateGroups(items) { var groupFn = $scope.$eval(groupByExp); ctrl.groups = []; angular.forEach(items, function(item) { var groupName = angular.isFunction(groupFn) ? groupFn(item) : item[groupFn]; var group = ctrl.findGroupByName(groupName); if(group) { group.items.push(item); } else { ctrl.groups.push({name: groupName, items: [item]}); } }); if(groupFilterExp){ var groupFilterFn = $scope.$eval(groupFilterExp); if( angular.isFunction(groupFilterFn)){ ctrl.groups = groupFilterFn(ctrl.groups); } else if(angular.isArray(groupFilterFn)){ ctrl.groups = _groupsFilter(ctrl.groups, groupFilterFn); } } ctrl.items = []; ctrl.groups.forEach(function(group) { ctrl.items = ctrl.items.concat(group.items); }); } function setPlainItems(items) { ctrl.items = items; } ctrl.setItemsFn = groupByExp ? updateGroups : setPlainItems; ctrl.parserResult = RepeatParser.parse(repeatAttr); ctrl.isGrouped = !!groupByExp; ctrl.itemProperty = ctrl.parserResult.itemName; //If collection is an Object, convert it to Array var originalSource = ctrl.parserResult.source; //When an object is used as source, we better create an array and use it as 'source' var createArrayFromObject = function(){ var origSrc = originalSource($scope); $scope.$uisSource = Object.keys(origSrc).map(function(v){ var result = {}; result[ctrl.parserResult.keyName] = v; result.value = origSrc[v]; return result; }); }; if (ctrl.parserResult.keyName){ // Check for (key,value) syntax createArrayFromObject(); ctrl.parserResult.source = $parse('$uisSource' + ctrl.parserResult.filters); $scope.$watch(originalSource, function(newVal, oldVal){ if (newVal !== oldVal) createArrayFromObject(); }, true); } ctrl.refreshItems = function (data){ data = data || ctrl.parserResult.source($scope); var selectedItems = ctrl.selected; //TODO should implement for single mode removeSelected if (ctrl.isEmpty() || (angular.isArray(selectedItems) && !selectedItems.length) || !ctrl.multiple || !ctrl.removeSelected) { ctrl.setItemsFn(data); }else{ if ( data !== undefined && data !== null ) { var filteredItems = data.filter(function(i) { return angular.isArray(selectedItems) ? selectedItems.every(function(selectedItem) { return !angular.equals(i, selectedItem); }) : !angular.equals(i, selectedItems); }); ctrl.setItemsFn(filteredItems); } } if (ctrl.dropdownPosition === 'auto' || ctrl.dropdownPosition === 'up'){ $scope.calculateDropdownPos(); } $scope.$broadcast('uis:refresh'); }; // See https://github.com/angular/angular.js/blob/v1.2.15/src/ng/directive/ngRepeat.js#L259 $scope.$watchCollection(ctrl.parserResult.source, function(items) { if (items === undefined || items === null) { // If the user specifies undefined or null => reset the collection // Special case: items can be undefined if the user did not initialized the collection on the scope // i.e $scope.addresses = [] is missing ctrl.items = []; } else { if (!angular.isArray(items)) { throw uiSelectMinErr('items', "Expected an array but got '{0}'.", items); } else { //Remove already selected items (ex: while searching) //TODO Should add a test ctrl.refreshItems(items); //update the view value with fresh data from items, if there is a valid model value if(angular.isDefined(ctrl.ngModel.$modelValue)) { ctrl.ngModel.$modelValue = null; //Force scope model value and ngModel value to be out of sync to re-run formatters } } } }); }; var _refreshDelayPromise; /** * Typeahead mode: lets the user refresh the collection using his own function. * * See Expose $select.search for external / remote filtering https://github.com/angular-ui/ui-select/pull/31 */ ctrl.refresh = function(refreshAttr) { if (refreshAttr !== undefined) { // Debounce // See https://github.com/angular-ui/bootstrap/blob/0.10.0/src/typeahead/typeahead.js#L155 // FYI AngularStrap typeahead does not have debouncing: https://github.com/mgcrea/angular-strap/blob/v2.0.0-rc.4/src/typeahead/typeahead.js#L177 if (_refreshDelayPromise) { $timeout.cancel(_refreshDelayPromise); } _refreshDelayPromise = $timeout(function() { $scope.$eval(refreshAttr); }, ctrl.refreshDelay); } }; ctrl.isActive = function(itemScope) { if ( !ctrl.open ) { return false; } var itemIndex = ctrl.items.indexOf(itemScope[ctrl.itemProperty]); var isActive = itemIndex == ctrl.activeIndex; if ( !isActive || itemIndex < 0 ) { return false; } if (isActive && !angular.isUndefined(ctrl.onHighlightCallback)) { itemScope.$eval(ctrl.onHighlightCallback); } return isActive; }; var _isItemSelected = function (item) { return (ctrl.selected && angular.isArray(ctrl.selected) && ctrl.selected.filter(function (selection) { return angular.equals(selection, item); }).length > 0); }; var disabledItems = []; function _updateItemDisabled(item, isDisabled) { var disabledItemIndex = disabledItems.indexOf(item); if (isDisabled && disabledItemIndex === -1) { disabledItems.push(item); } if (!isDisabled && disabledItemIndex > -1) { disabledItems.splice(disabledItemIndex, 0); } } function _isItemDisabled(item) { return disabledItems.indexOf(item) > -1; } ctrl.isDisabled = function(itemScope) { if (!ctrl.open) return; var item = itemScope[ctrl.itemProperty]; var itemIndex = ctrl.items.indexOf(item); var isDisabled = false; if (itemIndex >= 0 && (angular.isDefined(ctrl.disableChoiceExpression) || ctrl.multiple)) { if (item.isTag) return false; if (ctrl.multiple) { isDisabled = _isItemSelected(item); } if (!isDisabled && angular.isDefined(ctrl.disableChoiceExpression)) { isDisabled = !!(itemScope.$eval(ctrl.disableChoiceExpression)); } _updateItemDisabled(item, isDisabled); } return isDisabled; }; // When the user selects an item with ENTER or clicks the dropdown ctrl.select = function(item, skipFocusser, $event) { if (item === undefined || !_isItemDisabled(item)) { if ( ! ctrl.items && ! ctrl.search && ! ctrl.tagging.isActivated) return; if (!item || !_isItemDisabled(item)) { if(ctrl.tagging.isActivated) { // if taggingLabel is disabled and item is undefined we pull from ctrl.search if ( ctrl.taggingLabel === false ) { if ( ctrl.activeIndex < 0 ) { if (item === undefined) { item = ctrl.tagging.fct !== undefined ? ctrl.tagging.fct(ctrl.search) : ctrl.search; } if (!item || angular.equals( ctrl.items[0], item ) ) { return; } } else { // keyboard nav happened first, user selected from dropdown item = ctrl.items[ctrl.activeIndex]; } } else { // tagging always operates at index zero, taggingLabel === false pushes // the ctrl.search value without having it injected if ( ctrl.activeIndex === 0 ) { // ctrl.tagging pushes items to ctrl.items, so we only have empty val // for `item` if it is a detected duplicate if ( item === undefined ) return; // create new item on the fly if we don't already have one; // use tagging function if we have one if ( ctrl.tagging.fct !== undefined && typeof item === 'string' ) { item = ctrl.tagging.fct(item); if (!item) return; // if item type is 'string', apply the tagging label } else if ( typeof item === 'string' ) { // trim the trailing space item = item.replace(ctrl.taggingLabel,'').trim(); } } } // search ctrl.selected for dupes potentially caused by tagging and return early if found if (_isItemSelected(item)) { ctrl.close(skipFocusser); return; } } $scope.$broadcast('uis:select', item); var locals = {}; locals[ctrl.parserResult.itemName] = item; $timeout(function(){ ctrl.onSelectCallback($scope, { $item: item, $model: ctrl.parserResult.modelMapper($scope, locals) }); }); if (ctrl.closeOnSelect) { ctrl.close(skipFocusser); } if ($event && $event.type === 'click') { ctrl.clickTriggeredSelect = true; } } } }; // Closes the dropdown ctrl.close = function(skipFocusser) { if (!ctrl.open) return; if (ctrl.ngModel && ctrl.ngModel.$setTouched) ctrl.ngModel.$setTouched(); _resetSearchInput(); ctrl.open = false; $scope.$broadcast('uis:close', skipFocusser); }; ctrl.setFocus = function(){ if (!ctrl.focus) ctrl.focusInput[0].focus(); }; ctrl.clear = function($event) { ctrl.select(undefined); $event.stopPropagation(); $timeout(function() { ctrl.focusser[0].focus(); }, 0, false); }; // Toggle dropdown ctrl.toggle = function(e) { if (ctrl.open) { ctrl.close(); e.preventDefault(); e.stopPropagation(); } else { ctrl.activate(); } }; // Set default function for locked choices - avoids unnecessary // logic if functionality is not being used ctrl.isLocked = function () { return false; }; $scope.$watch(function () { return angular.isDefined(ctrl.lockChoiceExpression) && ctrl.lockChoiceExpression !== ""; }, _initaliseLockedChoices); function _initaliseLockedChoices(doInitalise) { if(!doInitalise) return; var lockedItems = []; function _updateItemLocked(item, isLocked) { var lockedItemIndex = lockedItems.indexOf(item); if (isLocked && lockedItemIndex === -1) { lockedItems.push(item); } if (!isLocked && lockedItemIndex > -1) { lockedItems.splice(lockedItemIndex, 0); } } function _isItemlocked(item) { return lockedItems.indexOf(item) > -1; } ctrl.isLocked = function (itemScope, itemIndex) { var isLocked = false, item = ctrl.selected[itemIndex]; if(item) { if (itemScope) { isLocked = !!(itemScope.$eval(ctrl.lockChoiceExpression)); _updateItemLocked(item, isLocked); } else { isLocked = _isItemlocked(item); } } return isLocked; }; } var sizeWatch = null; var updaterScheduled = false; ctrl.sizeSearchInput = function() { var input = ctrl.searchInput[0], container = ctrl.searchInput.parent().parent()[0], calculateContainerWidth = function() { // Return the container width only if the search input is visible return container.clientWidth * !!input.offsetParent; }, updateIfVisible = function(containerWidth) { if (containerWidth === 0) { return false; } var inputWidth = containerWidth - input.offsetLeft - 10; if (inputWidth < 50) inputWidth = containerWidth; ctrl.searchInput.css('width', inputWidth+'px'); return true; }; ctrl.searchInput.css('width', '10px'); $timeout(function() { //Give tags time to render correctly if (sizeWatch === null && !updateIfVisible(calculateContainerWidth())) { sizeWatch = $scope.$watch(function() { if (!updaterScheduled) { updaterScheduled = true; $scope.$$postDigest(function() { updaterScheduled = false; if (updateIfVisible(calculateContainerWidth())) { sizeWatch(); sizeWatch = null; } }); } }, angular.noop); } }); }; function _handleDropDownSelection(key) { var processed = true; switch (key) { case KEY.DOWN: if (!ctrl.open && ctrl.multiple) ctrl.activate(false, true); //In case its the search input in 'multiple' mode else if (ctrl.activeIndex < ctrl.items.length - 1) { ctrl.activeIndex++; } break; case KEY.UP: if (!ctrl.open && ctrl.multiple) ctrl.activate(false, true); //In case its the search input in 'multiple' mode else if (ctrl.activeIndex > 0 || (ctrl.search.length === 0 && ctrl.tagging.isActivated && ctrl.activeIndex > -1)) { ctrl.activeIndex--; } break; case KEY.TAB: if (!ctrl.multiple || ctrl.open) ctrl.select(ctrl.items[ctrl.activeIndex], true); break; case KEY.ENTER: if(ctrl.open && (ctrl.tagging.isActivated || ctrl.activeIndex >= 0)){ ctrl.select(ctrl.items[ctrl.activeIndex], ctrl.skipFocusser); // Make sure at least one dropdown item is highlighted before adding if not in tagging mode } else { ctrl.activate(false, true); //In case its the search input in 'multiple' mode } break; case KEY.ESC: ctrl.close(); break; default: processed = false; } return processed; } // Bind to keyboard shortcuts ctrl.searchInput.on('keydown', function(e) { var key = e.which; if (~[KEY.ENTER,KEY.ESC].indexOf(key)){ e.preventDefault(); e.stopPropagation(); } // if(~[KEY.ESC,KEY.TAB].indexOf(key)){ // //TODO: SEGURO? // ctrl.close(); // } $scope.$apply(function() { var tagged = false; if (ctrl.items.length > 0 || ctrl.tagging.isActivated) { _handleDropDownSelection(key); if ( ctrl.taggingTokens.isActivated ) { for (var i = 0; i < ctrl.taggingTokens.tokens.length; i++) { if ( ctrl.taggingTokens.tokens[i] === KEY.MAP[e.keyCode] ) { // make sure there is a new value to push via tagging if ( ctrl.search.length > 0 ) { tagged = true; } } } if ( tagged ) { $timeout(function() { ctrl.searchInput.triggerHandler('tagged'); var newItem = ctrl.search.replace(KEY.MAP[e.keyCode],'').trim(); if ( ctrl.tagging.fct ) { newItem = ctrl.tagging.fct( newItem ); } if (newItem) ctrl.select(newItem, true); }); } } } }); if(KEY.isVerticalMovement(key) && ctrl.items.length > 0){ _ensureHighlightVisible(); } if (key === KEY.ENTER || key === KEY.ESC) { e.preventDefault(); e.stopPropagation(); } }); ctrl.searchInput.on('paste', function (e) { var data; if (window.clipboardData && window.clipboardData.getData) { // IE data = window.clipboardData.getData('Text'); } else { data = (e.originalEvent || e).clipboardData.getData('text/plain'); } // Prepend the current input field text to the paste buffer. data = ctrl.search + data; if (data && data.length > 0) { // If tagging try to split by tokens and add items if (ctrl.taggingTokens.isActivated) { var items = []; for (var i = 0; i < ctrl.taggingTokens.tokens.length; i++) { // split by first token that is contained in data var separator = KEY.toSeparator(ctrl.taggingTokens.tokens[i]) || ctrl.taggingTokens.tokens[i]; if (data.indexOf(separator) > -1) { items = data.split(separator); break; // only split by one token } } if (items.length === 0) { items = [data]; } var oldsearch = ctrl.search; angular.forEach(items, function (item) { var newItem = ctrl.tagging.fct ? ctrl.tagging.fct(item) : item; if (newItem) { ctrl.select(newItem, true); } }); ctrl.search = oldsearch || EMPTY_SEARCH; e.preventDefault(); e.stopPropagation(); } else if (ctrl.paste) { ctrl.paste(data); ctrl.search = EMPTY_SEARCH; e.preventDefault(); e.stopPropagation(); } } }); ctrl.searchInput.on('tagged', function() { $timeout(function() { _resetSearchInput(); }); }); // See https://github.com/ivaynberg/select2/blob/3.4.6/select2.js#L1431 function _ensureHighlightVisible() { var container = $element.querySelectorAll('.ui-select-choices-content'); var choices = container.querySelectorAll('.ui-select-choices-row'); if (choices.length < 1) { throw uiSelectMinErr('choices', "Expected multiple .ui-select-choices-row but got '{0}'.", choices.length); } if (ctrl.activeIndex < 0) { return; } var highlighted = choices[ctrl.activeIndex]; var posY = highlighted.offsetTop + highlighted.clientHeight - container[0].scrollTop; var height = container[0].offsetHeight; if (posY > height) { container[0].scrollTop += posY - height; } else if (posY < highlighted.clientHeight) { if (ctrl.isGrouped && ctrl.activeIndex === 0) container[0].scrollTop = 0; //To make group header visible when going all the way up else container[0].scrollTop -= highlighted.clientHeight - posY; } } var onResize = $$uisDebounce(function() { ctrl.sizeSearchInput(); }, 50); angular.element($window).bind('resize', onResize); $scope.$on('$destroy', function() { ctrl.searchInput.off('keyup keydown tagged blur paste'); angular.element($window).off('resize', onResize); }); }]); uis.directive('uiSelect', ['$document', 'uiSelectConfig', 'uiSelectMinErr', 'uisOffset', '$compile', '$parse', '$timeout', function($document, uiSelectConfig, uiSelectMinErr, uisOffset, $compile, $parse, $timeout) { return { restrict: 'EA', templateUrl: function(tElement, tAttrs) { var theme = tAttrs.theme || uiSelectConfig.theme; return theme + (angular.isDefined(tAttrs.multiple) ? '/select-multiple.tpl.html' : '/select.tpl.html'); }, replace: true, transclude: true, require: ['uiSelect', '^ngModel'], scope: true, controller: 'uiSelectCtrl', controllerAs: '$select', compile: function(tElement, tAttrs) { // Allow setting ngClass on uiSelect var match = /{(.*)}\s*{(.*)}/.exec(tAttrs.ngClass); if(match) { var combined = '{'+ match[1] +', '+ match[2] +'}'; tAttrs.ngClass = combined; tElement.attr('ng-class', combined); } //Multiple or Single depending if multiple attribute presence if (angular.isDefined(tAttrs.multiple)) tElement.append('<ui-select-multiple/>').removeAttr('multiple'); else tElement.append('<ui-select-single/>'); if (tAttrs.inputId) tElement.querySelectorAll('input.ui-select-search')[0].id = tAttrs.inputId; return function(scope, element, attrs, ctrls, transcludeFn) { var $select = ctrls[0]; var ngModel = ctrls[1]; $select.generatedId = uiSelectConfig.generateId(); $select.baseTitle = attrs.title || 'Select box'; $select.focusserTitle = $select.baseTitle + ' focus'; $select.focusserId = 'focusser-' + $select.generatedId; $select.closeOnSelect = function() { if (angular.isDefined(attrs.closeOnSelect)) { return $parse(attrs.closeOnSelect)(); } else { return uiSelectConfig.closeOnSelect; } }(); scope.$watch('skipFocusser', function() { var skipFocusser = scope.$eval(attrs.skipFocusser); $select.skipFocusser = skipFocusser !== undefined ? skipFocusser : uiSelectConfig.skipFocusser; }); $select.onSelectCallback = $parse(attrs.onSelect); $select.onRemoveCallback = $parse(attrs.onRemove); //Set reference to ngModel from uiSelectCtrl $select.ngModel = ngModel; $select.choiceGrouped = function(group){ return $select.isGrouped && group && group.name; }; if(attrs.tabindex){ attrs.$observe('tabindex', function(value) { $select.focusInput.attr('tabindex', value); element.removeAttr('tabindex'); }); } scope.$watch(function () { return scope.$eval(attrs.searchEnabled); }, function(newVal) { $select.searchEnabled = newVal !== undefined ? newVal : uiSelectConfig.searchEnabled; }); scope.$watch('sortable', function() { var sortable = scope.$eval(attrs.sortable); $select.sortable = sortable !== undefined ? sortable : uiSelectConfig.sortable; }); attrs.$observe('limit', function() { //Limit the number of selections allowed $select.limit = (angular.isDefined(attrs.limit)) ? parseInt(attrs.limit, 10) : undefined; }); scope.$watch('removeSelected', function() { var removeSelected = scope.$eval(attrs.removeSelected); $select.removeSelected = removeSelected !== undefined ? removeSelected : uiSelectConfig.removeSelected; }); attrs.$observe('disabled', function() { // No need to use $eval() (thanks to ng-disabled) since we already get a boolean instead of a string $select.disabled = attrs.disabled !== undefined ? attrs.disabled : false; }); attrs.$observe('resetSearchInput', function() { // $eval() is needed otherwise we get a string instead of a boolean var resetSearchInput = scope.$eval(attrs.resetSearchInput); $select.resetSearchInput = resetSearchInput !== undefined ? resetSearchInput : true; }); attrs.$observe('paste', function() { $select.paste = scope.$eval(attrs.paste); }); attrs.$observe('tagging', function() { if(attrs.tagging !== undefined) { // $eval() is needed otherwise we get a string instead of a boolean var taggingEval = scope.$eval(attrs.tagging); $select.tagging = {isActivated: true, fct: taggingEval !== true ? taggingEval : undefined}; } else { $select.tagging = {isActivated: false, fct: undefined}; } }); attrs.$observe('taggingLabel', function() { if(attrs.tagging !== undefined ) { // check eval for FALSE, in this case, we disable the labels // associated with tagging if ( attrs.taggingLabel === 'false' ) { $select.taggingLabel = false; } else { $select.taggingLabel = attrs.taggingLabel !== undefined ? attrs.taggingLabel : '(new)'; } } }); attrs.$observe('taggingTokens', function() { if (attrs.tagging !== undefined) { var tokens = attrs.taggingTokens !== undefined ? attrs.taggingTokens.split('|') : [',','ENTER']; $select.taggingTokens = {isActivated: true, tokens: tokens }; } }); //Automatically gets focus when loaded if (angular.isDefined(attrs.autofocus)){ $timeout(function(){ $select.setFocus(); }); } //Gets focus based on scope event name (e.g. focus-on='SomeEventName') if (angular.isDefined(attrs.focusOn)){ scope.$on(attrs.focusOn, function() { $timeout(function(){ $select.setFocus(); }); }); } function onDocumentClick(e) { if (!$select.open) return; //Skip it if dropdown is close var contains = false; if (window.jQuery) { // Firefox 3.6 does not support element.contains() // See Node.contains https://developer.mozilla.org/en-US/docs/Web/API/Node.contains contains = window.jQuery.contains(element[0], e.target); } else { contains = element[0].contains(e.target); } if (!contains && !$select.clickTriggeredSelect) { var skipFocusser; if (!$select.skipFocusser) { //Will lose focus only with certain targets var focusableControls = ['input','button','textarea','select']; var targetController = angular.element(e.target).controller('uiSelect'); //To check if target is other ui-select skipFocusser = targetController && targetController !== $select; //To check if target is other ui-select if (!skipFocusser) skipFocusser = ~focusableControls.indexOf(e.target.tagName.toLowerCase()); //Check if target is input, button or textarea } else { skipFocusser = true; } $select.close(skipFocusser); scope.$digest(); } $select.clickTriggeredSelect = false; } // See Click everywhere but here event http://stackoverflow.com/questions/12931369 $document.on('click', onDocumentClick); scope.$on('$destroy', function() { $document.off('click', onDocumentClick); }); // Move transcluded elements to their correct position in main template transcludeFn(scope, function(clone) { // See Transclude in AngularJS http://blog.omkarpatil.com/2012/11/transclude-in-angularjs.html // One day jqLite will be replaced by jQuery and we will be able to write: // var transcludedElement = clone.filter('.my-class') // instead of creating a hackish DOM element: var transcluded = angular.element('<div>').append(clone); var transcludedMatch = transcluded.querySelectorAll('.ui-select-match'); transcludedMatch.removeAttr('ui-select-match'); //To avoid loop in case directive as attr transcludedMatch.removeAttr('data-ui-select-match'); // Properly handle HTML5 data-attributes if (transcludedMatch.length !== 1) { throw uiSelectMinErr('transcluded', "Expected 1 .ui-select-match but got '{0}'.", transcludedMatch.length); } element.querySelectorAll('.ui-select-match').replaceWith(transcludedMatch); var transcludedChoices = transcluded.querySelectorAll('.ui-select-choices'); transcludedChoices.removeAttr('ui-select-choices'); //To avoid loop in case directive as attr transcludedChoices.removeAttr('data-ui-select-choices'); // Properly handle HTML5 data-attributes if (transcludedChoices.length !== 1) { throw uiSelectMinErr('transcluded', "Expected 1 .ui-select-choices but got '{0}'.", transcludedChoices.length); } element.querySelectorAll('.ui-select-choices').replaceWith(transcludedChoices); var transcludedNoChoice = transcluded.querySelectorAll('.ui-select-no-choice'); transcludedNoChoice.removeAttr('ui-select-no-choice'); //To avoid loop in case directive as attr transcludedNoChoice.removeAttr('data-ui-select-no-choice'); // Properly handle HTML5 data-attributes if (transcludedNoChoice.length == 1) { element.querySelectorAll('.ui-select-no-choice').replaceWith(transcludedNoChoice); } }); // Support for appending the select field to the body when its open var appendToBody = scope.$eval(attrs.appendToBody); if (appendToBody !== undefined ? appendToBody : uiSelectConfig.appendToBody) { scope.$watch('$select.open', function(isOpen) { if (isOpen) { positionDropdown(); } else { resetDropdown(); } }); // Move the dropdown back to its original location when the scope is destroyed. Otherwise // it might stick around when the user routes away or the select field is otherwise removed scope.$on('$destroy', function() { resetDropdown(); }); } // Hold on to a reference to the .ui-select-container element for appendToBody support var placeholder = null, originalWidth = ''; function positionDropdown() { // Remember the absolute position of the element var offset = uisOffset(element); // Clone the element into a placeholder element to take its original place in the DOM placeholder = angular.element('<div class="ui-select-placeholder"></div>'); placeholder[0].style.width = offset.width + 'px'; placeholder[0].style.height = offset.height + 'px'; element.after(placeholder); // Remember the original value of the element width inline style, so it can be restored // when the dropdown is closed originalWidth = element[0].style.width; // Now move the actual dropdown element to the end of the body $document.find('body').append(element); element[0].style.position = 'absolute'; element[0].style.left = offset.left + 'px'; element[0].style.top = offset.top + 'px'; element[0].style.width = offset.width + 'px'; } function resetDropdown() { if (placeholder === null) { // The dropdown has not actually been display yet, so there's nothing to reset return; } // Move the dropdown element back to its original location in the DOM placeholder.replaceWith(element); placeholder = null; element[0].style.position = ''; element[0].style.left = ''; element[0].style.top = ''; element[0].style.width = originalWidth; // Set focus back on to the moved element $select.setFocus(); } // Hold on to a reference to the .ui-select-dropdown element for direction support. var dropdown = null, directionUpClassName = 'direction-up'; // Support changing the direction of the dropdown if there isn't enough space to render it. scope.$watch('$select.open', function() { if ($select.dropdownPosition === 'auto' || $select.dropdownPosition === 'up'){ scope.calculateDropdownPos(); } }); var setDropdownPosUp = function(offset, offsetDropdown){ offset = offset || uisOffset(element); offsetDropdown = offsetDropdown || uisOffset(dropdown); dropdown[0].style.position = 'absolute'; dropdown[0].style.top = (offsetDropdown.height * -1) + 'px'; element.addClass(directionUpClassName); }; var setDropdownPosDown = function(offset, offsetDropdown){ element.removeClass(directionUpClassName); offset = offset || uisOffset(element); offsetDropdown = offsetDropdown || uisOffset(dropdown); dropdown[0].style.position = ''; dropdown[0].style.top = ''; }; var calculateDropdownPosAfterAnimation = function() { // Delay positioning the dropdown until all choices have been added so its height is correct. $timeout(function() { if ($select.dropdownPosition === 'up') { //Go UP setDropdownPosUp(); } else { //AUTO element.removeClass(directionUpClassName); var offset = uisOffset(element); var offsetDropdown = uisOffset(dropdown); //https://code.google.com/p/chromium/issues/detail?id=342307#c4 var scrollTop = $document[0].documentElement.scrollTop || $document[0].body.scrollTop; //To make it cross browser (blink, webkit, IE, Firefox). // Determine if the direction of the dropdown needs to be changed. if (offset.top + offset.height + offsetDropdown.height > scrollTop + $document[0].documentElement.clientHeight) { //Go UP setDropdownPosUp(offset, offsetDropdown); }else{ //Go DOWN setDropdownPosDown(offset, offsetDropdown); } } // Display the dropdown once it has been positioned. dropdown[0].style.opacity = 1; }); }; scope.calculateDropdownPos = function() { if ($select.open) { dropdown = angular.element(element).querySelectorAll('.ui-select-dropdown'); if (dropdown.length === 0) { return; } // Hide the dropdown so there is no flicker until $timeout is done executing. dropdown[0].style.opacity = 0; if (!uisOffset(dropdown).height && $select.$animate && $select.$animate.on && $select.$animate.enabled(dropdown)) { var needsCalculated = true; $select.$animate.on('enter', dropdown, function (elem, phase) { if (phase === 'close' && needsCalculated) { calculateDropdownPosAfterAnimation(); needsCalculated = false; } }); } else { calculateDropdownPosAfterAnimation(); } } else { if (dropdown === null || dropdown.length === 0) { return; } // Reset the position of the dropdown. dropdown[0].style.opacity = 0; dropdown[0].style.position = ''; dropdown[0].style.top = ''; element.removeClass(directionUpClassName); } }; }; } }; }]); uis.directive('uiSelectMatch', ['uiSelectConfig', function(uiSelectConfig) { return { restrict: 'EA', require: '^uiSelect', replace: true, transclude: true, templateUrl: function(tElement) { // Needed so the uiSelect can detect the transcluded content tElement.addClass('ui-select-match'); var parent = tElement.parent(); // Gets theme attribute from parent (ui-select) var theme = getAttribute(parent, 'theme') || uiSelectConfig.theme; var multi = angular.isDefined(getAttribute(parent, 'multiple')); return theme + (multi ? '/match-multiple.tpl.html' : '/match.tpl.html'); }, link: function(scope, element, attrs, $select) { $select.lockChoiceExpression = attrs.uiLockChoice; attrs.$observe('placeholder', function(placeholder) { $select.placeholder = placeholder !== undefined ? placeholder : uiSelectConfig.placeholder; }); function setAllowClear(allow) { $select.allowClear = (angular.isDefined(allow)) ? (allow === '') ? true : (allow.toLowerCase() === 'true') : false; } attrs.$observe('allowClear', setAllowClear); setAllowClear(attrs.allowClear); if($select.multiple){ $select.sizeSearchInput(); } } }; function getAttribute(elem, attribute) { if (elem[0].hasAttribute(attribute)) return elem.attr(attribute); if (elem[0].hasAttribute('data-' + attribute)) return elem.attr('data-' + attribute); if (elem[0].hasAttribute('x-' + attribute)) return elem.attr('x-' + attribute); } }]); uis.directive('uiSelectMultiple', ['uiSelectMinErr','$timeout', function(uiSelectMinErr, $timeout) { return { restrict: 'EA', require: ['^uiSelect', '^ngModel'], controller: ['$scope','$timeout', function($scope, $timeout){ var ctrl = this, $select = $scope.$select, ngModel; if (angular.isUndefined($select.selected)) $select.selected = []; //Wait for link fn to inject it $scope.$evalAsync(function(){ ngModel = $scope.ngModel; }); ctrl.activeMatchIndex = -1; ctrl.updateModel = function(){ ngModel.$setViewValue(Date.now()); //Set timestamp as a unique string to force changes ctrl.refreshComponent(); }; ctrl.refreshComponent = function(){ //Remove already selected items //e.g. When user clicks on a selection, the selected array changes and //the dropdown should remove that item if($select.refreshItems){ $select.refreshItems(); } if($select.sizeSearchInput){ $select.sizeSearchInput(); } }; // Remove item from multiple select ctrl.removeChoice = function(index){ // if the choice is locked, don't remove it if($select.isLocked(null, index)) return false; var removedChoice = $select.selected[index]; var locals = {}; locals[$select.parserResult.itemName] = removedChoice; $select.selected.splice(index, 1); ctrl.activeMatchIndex = -1; $select.sizeSearchInput(); // Give some time for scope propagation. $timeout(function(){ $select.onRemoveCallback($scope, { $item: removedChoice, $model: $select.parserResult.modelMapper($scope, locals) }); }); ctrl.updateModel(); return true; }; ctrl.getPlaceholder = function(){ //Refactor single? if($select.selected && $select.selected.length) return; return $select.placeholder; }; }], controllerAs: '$selectMultiple', link: function(scope, element, attrs, ctrls) { var $select = ctrls[0]; var ngModel = scope.ngModel = ctrls[1]; var $selectMultiple = scope.$selectMultiple; //$select.selected = raw selected objects (ignoring any property binding) $select.multiple = true; //Input that will handle focus $select.focusInput = $select.searchInput; //Properly check for empty if set to multiple ngModel.$isEmpty = function(value) { return !value || value.length === 0; }; //From view --> model ngModel.$parsers.unshift(function () { var locals = {}, result, resultMultiple = []; for (var j = $select.selected.length - 1; j >= 0; j--) { locals = {}; locals[$select.parserResult.itemName] = $select.selected[j]; result = $select.parserResult.modelMapper(scope, locals); resultMultiple.unshift(result); } return resultMultiple; }); // From model --> view ngModel.$formatters.unshift(function (inputValue) { var data = $select.parserResult && $select.parserResult.source (scope, { $select : {search:''}}), //Overwrite $search locals = {}, result; if (!data) return inputValue; var resultMultiple = []; var checkFnMultiple = function(list, value){ if (!list || !list.length) return; for (var p = list.length - 1; p >= 0; p--) { locals[$select.parserResult.itemName] = list[p]; result = $select.parserResult.modelMapper(scope, locals); if($select.parserResult.trackByExp){ var propsItemNameMatches = /(\w*)\./.exec($select.parserResult.trackByExp); var matches = /\.([^\s]+)/.exec($select.parserResult.trackByExp); if(propsItemNameMatches && propsItemNameMatches.length > 0 && propsItemNameMatches[1] == $select.parserResult.itemName){ if(matches && matches.length>0 && result[matches[1]] == value[matches[1]]){ resultMultiple.unshift(list[p]); return true; } } } if (angular.equals(result,value)){ resultMultiple.unshift(list[p]); return true; } } return false; }; if (!inputValue) return resultMultiple; //If ngModel was undefined for (var k = inputValue.length - 1; k >= 0; k--) { //Check model array of currently selected items if (!checkFnMultiple($select.selected, inputValue[k])){ //Check model array of all items available if (!checkFnMultiple(data, inputValue[k])){ //If not found on previous lists, just add it directly to resultMultiple resultMultiple.unshift(inputValue[k]); } } } return resultMultiple; }); //Watch for external model changes scope.$watchCollection(function(){ return ngModel.$modelValue; }, function(newValue, oldValue) { if (oldValue != newValue){ //update the view value with fresh data from items, if there is a valid model value if(angular.isDefined(ngModel.$modelValue)) { ngModel.$modelValue = null; //Force scope model value and ngModel value to be out of sync to re-run formatters } $selectMultiple.refreshComponent(); } }); ngModel.$render = function() { // Make sure that model value is array if(!angular.isArray(ngModel.$viewValue)){ // Have tolerance for null or undefined values if(angular.isUndefined(ngModel.$viewValue) || ngModel.$viewValue === null){ ngModel.$viewValue = []; } else { throw uiSelectMinErr('multiarr', "Expected model value to be array but got '{0}'", ngModel.$viewValue); } } $select.selected = ngModel.$viewValue; $selectMultiple.refreshComponent(); scope.$evalAsync(); //To force $digest }; scope.$on('uis:select', function (event, item) { if($select.selected.length >= $select.limit) { return; } $select.selected.push(item); $selectMultiple.updateModel(); }); scope.$on('uis:activate', function () { $selectMultiple.activeMatchIndex = -1; }); scope.$watch('$select.disabled', function(newValue, oldValue) { // As the search input field may now become visible, it may be necessary to recompute its size if (oldValue && !newValue) $select.sizeSearchInput(); }); $select.searchInput.on('keydown', function(e) { var key = e.which; scope.$apply(function() { var processed = false; // var tagged = false; //Checkme if(KEY.isHorizontalMovement(key)){ processed = _handleMatchSelection(key); } if (processed && key != KEY.TAB) { //TODO Check si el tab selecciona aun correctamente //Crear test e.preventDefault(); e.stopPropagation(); } }); }); function _getCaretPosition(el) { if(angular.isNumber(el.selectionStart)) return el.selectionStart; // selectionStart is not supported in IE8 and we don't want hacky workarounds so we compromise else return el.value.length; } // Handles selected options in "multiple" mode function _handleMatchSelection(key){ var caretPosition = _getCaretPosition($select.searchInput[0]), length = $select.selected.length, // none = -1, first = 0, last = length-1, curr = $selectMultiple.activeMatchIndex, next = $selectMultiple.activeMatchIndex+1, prev = $selectMultiple.activeMatchIndex-1, newIndex = curr; if(caretPosition > 0 || ($select.search.length && key == KEY.RIGHT)) return false; $select.close(); function getNewActiveMatchIndex(){ switch(key){ case KEY.LEFT: // Select previous/first item if(~$selectMultiple.activeMatchIndex) return prev; // Select last item else return last; break; case KEY.RIGHT: // Open drop-down if(!~$selectMultiple.activeMatchIndex || curr === last){ $select.activate(); return false; } // Select next/last item else return next; break; case KEY.BACKSPACE: // Remove selected item and select previous/first if(~$selectMultiple.activeMatchIndex){ if($selectMultiple.removeChoice(curr)) { return prev; } else { return curr; } } else { // If nothing yet selected, select last item return last; } break; case KEY.DELETE: // Remove selected item and select next item if(~$selectMultiple.activeMatchIndex){ $selectMultiple.removeChoice($selectMultiple.activeMatchIndex); return curr; } else return false; } } newIndex = getNewActiveMatchIndex(); if(!$select.selected.length || newIndex === false) $selectMultiple.activeMatchIndex = -1; else $selectMultiple.activeMatchIndex = Math.min(last,Math.max(first,newIndex)); return true; } $select.searchInput.on('keyup', function(e) { if ( ! KEY.isVerticalMovement(e.which) ) { scope.$evalAsync( function () { $select.activeIndex = $select.taggingLabel === false ? -1 : 0; }); } // Push a "create new" item into array if there is a search string if ( $select.tagging.isActivated && $select.search.length > 0 ) { // return early with these keys if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e) || e.which === KEY.ESC || KEY.isVerticalMovement(e.which) ) { return; } // always reset the activeIndex to the first item when tagging $select.activeIndex = $select.taggingLabel === false ? -1 : 0; // taggingLabel === false bypasses all of this if ($select.taggingLabel === false) return; var items = angular.copy( $select.items ); var stashArr = angular.copy( $select.items ); var newItem; var item; var hasTag = false; var dupeIndex = -1; var tagItems; var tagItem; // case for object tagging via transform `$select.tagging.fct` function if ( $select.tagging.fct !== undefined) { tagItems = $select.$filter('filter')(items,{'isTag': true}); if ( tagItems.length > 0 ) { tagItem = tagItems[0]; } // remove the first element, if it has the `isTag` prop we generate a new one with each keyup, shaving the previous if ( items.length > 0 && tagItem ) { hasTag = true; items = items.slice(1,items.length); stashArr = stashArr.slice(1,stashArr.length); } newItem = $select.tagging.fct($select.search); // verify the new tag doesn't match the value of a possible selection choice or an already selected item. if ( stashArr.some(function (origItem) { return angular.equals(origItem, newItem); }) || $select.selected.some(function (origItem) { return angular.equals(origItem, newItem); }) ) { scope.$evalAsync(function () { $select.activeIndex = 0; $select.items = items; }); return; } if (newItem) newItem.isTag = true; // handle newItem string and stripping dupes in tagging string context } else { // find any tagging items already in the $select.items array and store them tagItems = $select.$filter('filter')(items,function (item) { return item.match($select.taggingLabel); }); if ( tagItems.length > 0 ) { tagItem = tagItems[0]; } item = items[0]; // remove existing tag item if found (should only ever be one tag item) if ( item !== undefined && items.length > 0 && tagItem ) { hasTag = true; items = items.slice(1,items.length); stashArr = stashArr.slice(1,stashArr.length); } newItem = $select.search+' '+$select.taggingLabel; if ( _findApproxDupe($select.selected, $select.search) > -1 ) { return; } // verify the the tag doesn't match the value of an existing item from // the searched data set or the items already selected if ( _findCaseInsensitiveDupe(stashArr.concat($select.selected)) ) { // if there is a tag from prev iteration, strip it / queue the change // and return early if ( hasTag ) { items = stashArr; scope.$evalAsync( function () { $select.activeIndex = 0; $select.items = items; }); } return; } if ( _findCaseInsensitiveDupe(stashArr) ) { // if there is a tag from prev iteration, strip it if ( hasTag ) { $select.items = stashArr.slice(1,stashArr.length); } return; } } if ( hasTag ) dupeIndex = _findApproxDupe($select.selected, newItem); // dupe found, shave the first item if ( dupeIndex > -1 ) { items = items.slice(dupeIndex+1,items.length-1); } else { items = []; if (newItem) items.push(newItem); items = items.concat(stashArr); } scope.$evalAsync( function () { $select.activeIndex = 0; $select.items = items; if ($select.isGrouped) { // update item references in groups, so that indexOf will work after angular.copy var itemsWithoutTag = newItem ? items.slice(1) : items; $select.setItemsFn(itemsWithoutTag); if (newItem) { // add tag item as a new group $select.items.unshift(newItem); $select.groups.unshift({name: '', items: [newItem], tagging: true}); } } }); } }); function _findCaseInsensitiveDupe(arr) { if ( arr === undefined || $select.search === undefined ) { return false; } var hasDupe = arr.filter( function (origItem) { if ( $select.search.toUpperCase() === undefined || origItem === undefined ) { return false; } return origItem.toUpperCase() === $select.search.toUpperCase(); }).length > 0; return hasDupe; } function _findApproxDupe(haystack, needle) { var dupeIndex = -1; if(angular.isArray(haystack)) { var tempArr = angular.copy(haystack); for (var i = 0; i <tempArr.length; i++) { // handle the simple string version of tagging if ( $select.tagging.fct === undefined ) { // search the array for the match if ( tempArr[i]+' '+$select.taggingLabel === needle ) { dupeIndex = i; } // handle the object tagging implementation } else { var mockObj = tempArr[i]; if (angular.isObject(mockObj)) { mockObj.isTag = true; } if ( angular.equals(mockObj, needle) ) { dupeIndex = i; } } } } return dupeIndex; } $select.searchInput.on('blur', function() { $timeout(function() { $selectMultiple.activeMatchIndex = -1; }); }); } }; }]); uis.directive('uiSelectNoChoice', ['uiSelectConfig', function (uiSelectConfig) { return { restrict: 'EA', require: '^uiSelect', replace: true, transclude: true, templateUrl: function (tElement) { // Needed so the uiSelect can detect the transcluded content tElement.addClass('ui-select-no-choice'); // Gets theme attribute from parent (ui-select) var theme = tElement.parent().attr('theme') || uiSelectConfig.theme; return theme + '/no-choice.tpl.html'; } }; }]); uis.directive('uiSelectSingle', ['$timeout','$compile', function($timeout, $compile) { return { restrict: 'EA', require: ['^uiSelect', '^ngModel'], link: function(scope, element, attrs, ctrls) { var $select = ctrls[0]; var ngModel = ctrls[1]; //From view --> model ngModel.$parsers.unshift(function (inputValue) { var locals = {}, result; locals[$select.parserResult.itemName] = inputValue; result = $select.parserResult.modelMapper(scope, locals); return result; }); //From model --> view ngModel.$formatters.unshift(function (inputValue) { var data = $select.parserResult && $select.parserResult.source (scope, { $select : {search:''}}), //Overwrite $search locals = {}, result; if (data){ var checkFnSingle = function(d){ locals[$select.parserResult.itemName] = d; result = $select.parserResult.modelMapper(scope, locals); return result === inputValue; }; //If possible pass same object stored in $select.selected if ($select.selected && checkFnSingle($select.selected)) { return $select.selected; } for (var i = data.length - 1; i >= 0; i--) { if (checkFnSingle(data[i])) return data[i]; } } return inputValue; }); //Update viewValue if model change scope.$watch('$select.selected', function(newValue) { if (ngModel.$viewValue !== newValue) { ngModel.$setViewValue(newValue); } }); ngModel.$render = function() { $select.selected = ngModel.$viewValue; }; scope.$on('uis:select', function (event, item) { $select.selected = item; }); scope.$on('uis:close', function (event, skipFocusser) { $timeout(function(){ $select.focusser.prop('disabled', false); if (!skipFocusser) $select.focusser[0].focus(); },0,false); }); scope.$on('uis:activate', function () { focusser.prop('disabled', true); //Will reactivate it on .close() }); //Idea from: https://github.com/ivaynberg/select2/blob/79b5bf6db918d7560bdd959109b7bcfb47edaf43/select2.js#L1954 var focusser = angular.element("<input ng-disabled='$select.disabled' class='ui-select-focusser ui-select-offscreen' type='text' id='{{ $select.focusserId }}' aria-label='{{ $select.focusserTitle }}' aria-haspopup='true' role='button' />"); $compile(focusser)(scope); $select.focusser = focusser; //Input that will handle focus $select.focusInput = focusser; element.parent().append(focusser); focusser.bind("focus", function(){ scope.$evalAsync(function(){ $select.focus = true; }); }); focusser.bind("blur", function(){ scope.$evalAsync(function(){ $select.focus = false; }); }); focusser.bind("keydown", function(e){ if (e.which === KEY.BACKSPACE) { e.preventDefault(); e.stopPropagation(); $select.select(undefined); scope.$apply(); return; } if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e) || e.which === KEY.ESC) { return; } if (e.which == KEY.DOWN || e.which == KEY.UP || e.which == KEY.ENTER || e.which == KEY.SPACE){ e.preventDefault(); e.stopPropagation(); $select.activate(); } scope.$digest(); }); focusser.bind("keyup input", function(e){ if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e) || e.which === KEY.ESC || e.which == KEY.ENTER || e.which === KEY.BACKSPACE) { return; } $select.activate(focusser.val()); //User pressed some regular key, so we pass it to the search input focusser.val(''); scope.$digest(); }); } }; }]); // Make multiple matches sortable uis.directive('uiSelectSort', ['$timeout', 'uiSelectConfig', 'uiSelectMinErr', function($timeout, uiSelectConfig, uiSelectMinErr) { return { require: ['^^uiSelect', '^ngModel'], link: function(scope, element, attrs, ctrls) { if (scope[attrs.uiSelectSort] === null) { throw uiSelectMinErr('sort', 'Expected a list to sort'); } var $select = ctrls[0]; var $ngModel = ctrls[1]; var options = angular.extend({ axis: 'horizontal' }, scope.$eval(attrs.uiSelectSortOptions)); var axis = options.axis; var draggingClassName = 'dragging'; var droppingClassName = 'dropping'; var droppingBeforeClassName = 'dropping-before'; var droppingAfterClassName = 'dropping-after'; scope.$watch(function(){ return $select.sortable; }, function(newValue){ if (newValue) { element.attr('draggable', true); } else { element.removeAttr('draggable'); } }); element.on('dragstart', function(event) { element.addClass(draggingClassName); (event.dataTransfer || event.originalEvent.dataTransfer).setData('text', scope.$index.toString()); }); element.on('dragend', function() { removeClass(draggingClassName); }); var move = function(from, to) { /*jshint validthis: true */ this.splice(to, 0, this.splice(from, 1)[0]); }; var removeClass = function(className) { angular.forEach($select.$element.querySelectorAll('.' + className), function(el){ angular.element(el).removeClass(className); }); }; var dragOverHandler = function(event) { event.preventDefault(); var offset = axis === 'vertical' ? event.offsetY || event.layerY || (event.originalEvent ? event.originalEvent.offsetY : 0) : event.offsetX || event.layerX || (event.originalEvent ? event.originalEvent.offsetX : 0); if (offset < (this[axis === 'vertical' ? 'offsetHeight' : 'offsetWidth'] / 2)) { removeClass(droppingAfterClassName); element.addClass(droppingBeforeClassName); } else { removeClass(droppingBeforeClassName); element.addClass(droppingAfterClassName); } }; var dropTimeout; var dropHandler = function(event) { event.preventDefault(); var droppedItemIndex = parseInt((event.dataTransfer || event.originalEvent.dataTransfer).getData('text'), 10); // prevent event firing multiple times in firefox $timeout.cancel(dropTimeout); dropTimeout = $timeout(function() { _dropHandler(droppedItemIndex); }, 20); }; var _dropHandler = function(droppedItemIndex) { var theList = scope.$eval(attrs.uiSelectSort); var itemToMove = theList[droppedItemIndex]; var newIndex = null; if (element.hasClass(droppingBeforeClassName)) { if (droppedItemIndex < scope.$index) { newIndex = scope.$index - 1; } else { newIndex = scope.$index; } } else { if (droppedItemIndex < scope.$index) { newIndex = scope.$index; } else { newIndex = scope.$index + 1; } } move.apply(theList, [droppedItemIndex, newIndex]); $ngModel.$setViewValue(Date.now()); scope.$apply(function() { scope.$emit('uiSelectSort:change', { array: theList, item: itemToMove, from: droppedItemIndex, to: newIndex }); }); removeClass(droppingClassName); removeClass(droppingBeforeClassName); removeClass(droppingAfterClassName); element.off('drop', dropHandler); }; element.on('dragenter', function() { if (element.hasClass(draggingClassName)) { return; } element.addClass(droppingClassName); element.on('dragover', dragOverHandler); element.on('drop', dropHandler); }); element.on('dragleave', function(event) { if (event.target != element) { return; } removeClass(droppingClassName); removeClass(droppingBeforeClassName); removeClass(droppingAfterClassName); element.off('dragover', dragOverHandler); element.off('drop', dropHandler); }); } }; }]); /** * Parses "repeat" attribute. * * Taken from AngularJS ngRepeat source code * See https://github.com/angular/angular.js/blob/v1.2.15/src/ng/directive/ngRepeat.js#L211 * * Original discussion about parsing "repeat" attribute instead of fully relying on ng-repeat: * https://github.com/angular-ui/ui-select/commit/5dd63ad#commitcomment-5504697 */ uis.service('uisRepeatParser', ['uiSelectMinErr','$parse', function(uiSelectMinErr, $parse) { var self = this; /** * Example: * expression = "address in addresses | filter: {street: $select.search} track by $index" * itemName = "address", * source = "addresses | filter: {street: $select.search}", * trackByExp = "$index", */ self.parse = function(expression) { var match; //var isObjectCollection = /\(\s*([\$\w][\$\w]*)\s*,\s*([\$\w][\$\w]*)\s*\)/.test(expression); // If an array is used as collection // if (isObjectCollection){ // 000000000000000000000000000000111111111000000000000000222222222222220033333333333333333333330000444444444444444444000000000000000055555555555000000000000000000000066666666600000000 match = expression.match(/^\s*(?:([\s\S]+?)\s+as\s+)?(?:([\$\w][\$\w]*)|(?:\(\s*([\$\w][\$\w]*)\s*,\s*([\$\w][\$\w]*)\s*\)))\s+in\s+(\s*[\s\S]+?)?(?:\s+track\s+by\s+([\s\S]+?))?\s*$/); // 1 Alias // 2 Item // 3 Key on (key,value) // 4 Value on (key,value) // 5 Source expression (including filters) // 6 Track by if (!match) { throw uiSelectMinErr('iexp', "Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.", expression); } var source = match[5], filters = ''; // When using (key,value) ui-select requires filters to be extracted, since the object // is converted to an array for $select.items // (in which case the filters need to be reapplied) if (match[3]) { // Remove any enclosing parenthesis source = match[5].replace(/(^\()|(\)$)/g, ''); // match all after | but not after || var filterMatch = match[5].match(/^\s*(?:[\s\S]+?)(?:[^\|]|\|\|)+([\s\S]*)\s*$/); if(filterMatch && filterMatch[1].trim()) { filters = filterMatch[1]; source = source.replace(filters, ''); } } return { itemName: match[4] || match[2], // (lhs) Left-hand side, keyName: match[3], //for (key, value) syntax source: $parse(source), filters: filters, trackByExp: match[6], modelMapper: $parse(match[1] || match[4] || match[2]), repeatExpression: function (grouped) { var expression = this.itemName + ' in ' + (grouped ? '$group.items' : '$select.items'); if (this.trackByExp) { expression += ' track by ' + this.trackByExp; } return expression; } }; }; self.getGroupNgRepeatExpression = function() { return '$group in $select.groups'; }; }]); }()); angular.module("ui.select").run(["$templateCache", function($templateCache) {$templateCache.put("bootstrap/choices.tpl.html","<ul class=\"ui-select-choices ui-select-choices-content ui-select-dropdown dropdown-menu\" role=\"listbox\" ng-show=\"$select.open && $select.items.length > 0\"><li class=\"ui-select-choices-group\" id=\"ui-select-choices-{{ $select.generatedId }}\"><div class=\"divider\" ng-show=\"$select.isGrouped && $index > 0\"></div><div ng-show=\"$select.isGrouped\" class=\"ui-select-choices-group-label dropdown-header\" ng-bind=\"$group.name\"></div><div ng-attr-id=\"ui-select-choices-row-{{ $select.generatedId }}-{{$index}}\" class=\"ui-select-choices-row\" ng-class=\"{active: $select.isActive(this), disabled: $select.isDisabled(this)}\" role=\"option\"><a href=\"\" class=\"ui-select-choices-row-inner\"></a></div></li></ul>"); $templateCache.put("bootstrap/match-multiple.tpl.html","<span class=\"ui-select-match\"><span ng-repeat=\"$item in $select.selected track by $index\"><span class=\"ui-select-match-item btn btn-default btn-xs\" tabindex=\"-1\" type=\"button\" ng-disabled=\"$select.disabled\" ng-click=\"$selectMultiple.activeMatchIndex = $index;\" ng-class=\"{\'btn-primary\':$selectMultiple.activeMatchIndex === $index, \'select-locked\':$select.isLocked(this, $index)}\" ui-select-sort=\"$select.selected\"><span class=\"close ui-select-match-close\" ng-hide=\"$select.disabled\" ng-click=\"$selectMultiple.removeChoice($index)\">&nbsp;&times;</span> <span uis-transclude-append=\"\"></span></span></span></span>"); $templateCache.put("bootstrap/match.tpl.html","<div class=\"ui-select-match\" ng-hide=\"$select.open && $select.searchEnabled\" ng-disabled=\"$select.disabled\" ng-class=\"{\'btn-default-focus\':$select.focus}\"><span tabindex=\"-1\" class=\"btn btn-default form-control ui-select-toggle\" aria-label=\"{{ $select.baseTitle }} activate\" ng-disabled=\"$select.disabled\" ng-click=\"$select.activate()\" style=\"outline: 0;\"><span ng-show=\"$select.isEmpty()\" class=\"ui-select-placeholder text-muted\">{{$select.placeholder}}</span> <span ng-hide=\"$select.isEmpty()\" class=\"ui-select-match-text pull-left\" ng-class=\"{\'ui-select-allow-clear\': $select.allowClear && !$select.isEmpty()}\" ng-transclude=\"\"></span> <i class=\"caret pull-right\" ng-click=\"$select.toggle($event)\"></i> <a ng-show=\"$select.allowClear && !$select.isEmpty() && ($select.disabled !== true)\" aria-label=\"{{ $select.baseTitle }} clear\" style=\"margin-right: 10px\" ng-click=\"$select.clear($event)\" class=\"btn btn-xs btn-link pull-right\"><i class=\"glyphicon glyphicon-remove\" aria-hidden=\"true\"></i></a></span></div>"); $templateCache.put("bootstrap/no-choice.tpl.html","<ul class=\"ui-select-no-choice dropdown-menu\" ng-show=\"$select.items.length == 0\"><li ng-transclude=\"\"></li></ul>"); $templateCache.put("bootstrap/select-multiple.tpl.html","<div class=\"ui-select-container ui-select-multiple ui-select-bootstrap dropdown form-control\" ng-class=\"{open: $select.open}\"><div><div class=\"ui-select-match\"></div><input type=\"search\" autocomplete=\"off\" autocorrect=\"off\" autocapitalize=\"off\" spellcheck=\"false\" class=\"ui-select-search input-xs\" placeholder=\"{{$selectMultiple.getPlaceholder()}}\" ng-disabled=\"$select.disabled\" ng-hide=\"$select.disabled\" ng-click=\"$select.activate()\" ng-model=\"$select.search\" role=\"combobox\" aria-label=\"{{ $select.baseTitle }}\" ondrop=\"return false;\"></div><div class=\"ui-select-choices\"></div><div class=\"ui-select-no-choice\"></div></div>"); $templateCache.put("bootstrap/select.tpl.html","<div class=\"ui-select-container ui-select-bootstrap dropdown\" ng-class=\"{open: $select.open}\"><div class=\"ui-select-match\"></div><input type=\"search\" autocomplete=\"off\" tabindex=\"-1\" aria-expanded=\"true\" aria-label=\"{{ $select.baseTitle }}\" aria-owns=\"ui-select-choices-{{ $select.generatedId }}\" aria-activedescendant=\"ui-select-choices-row-{{ $select.generatedId }}-{{ $select.activeIndex }}\" class=\"form-control ui-select-search\" placeholder=\"{{$select.placeholder}}\" ng-model=\"$select.search\" ng-show=\"$select.searchEnabled && $select.open\"><div class=\"ui-select-choices\"></div><div class=\"ui-select-no-choice\"></div></div>"); $templateCache.put("select2/choices.tpl.html","<ul tabindex=\"-1\" class=\"ui-select-choices ui-select-choices-content select2-results\"><li class=\"ui-select-choices-group\" ng-class=\"{\'select2-result-with-children\': $select.choiceGrouped($group) }\"><div ng-show=\"$select.choiceGrouped($group)\" class=\"ui-select-choices-group-label select2-result-label\" ng-bind=\"$group.name\"></div><ul role=\"listbox\" id=\"ui-select-choices-{{ $select.generatedId }}\" ng-class=\"{\'select2-result-sub\': $select.choiceGrouped($group), \'select2-result-single\': !$select.choiceGrouped($group) }\"><li role=\"option\" ng-attr-id=\"ui-select-choices-row-{{ $select.generatedId }}-{{$index}}\" class=\"ui-select-choices-row\" ng-class=\"{\'select2-highlighted\': $select.isActive(this), \'select2-disabled\': $select.isDisabled(this)}\"><div class=\"select2-result-label ui-select-choices-row-inner\"></div></li></ul></li></ul>"); $templateCache.put("select2/match-multiple.tpl.html","<span class=\"ui-select-match\"><li class=\"ui-select-match-item select2-search-choice\" ng-repeat=\"$item in $select.selected track by $index\" ng-class=\"{\'select2-search-choice-focus\':$selectMultiple.activeMatchIndex === $index, \'select2-locked\':$select.isLocked(this, $index)}\" ui-select-sort=\"$select.selected\"><span uis-transclude-append=\"\"></span> <a href=\"javascript:;\" class=\"ui-select-match-close select2-search-choice-close\" ng-click=\"$selectMultiple.removeChoice($index)\" tabindex=\"-1\"></a></li></span>"); $templateCache.put("select2/match.tpl.html","<a class=\"select2-choice ui-select-match\" ng-class=\"{\'select2-default\': $select.isEmpty()}\" ng-click=\"$select.toggle($event)\" aria-label=\"{{ $select.baseTitle }} select\"><span ng-show=\"$select.isEmpty()\" class=\"select2-chosen\">{{$select.placeholder}}</span> <span ng-hide=\"$select.isEmpty()\" class=\"select2-chosen\" ng-transclude=\"\"></span> <abbr ng-if=\"$select.allowClear && !$select.isEmpty()\" class=\"select2-search-choice-close\" ng-click=\"$select.clear($event)\"></abbr> <span class=\"select2-arrow ui-select-toggle\"><b></b></span></a>"); $templateCache.put("select2/no-choice.tpl.html","<div class=\"ui-select-no-choice dropdown\" ng-show=\"$select.items.length == 0\"><div class=\"dropdown-content\"><div data-selectable=\"\" ng-transclude=\"\"></div></div></div>"); $templateCache.put("select2/select-multiple.tpl.html","<div class=\"ui-select-container ui-select-multiple select2 select2-container select2-container-multi\" ng-class=\"{\'select2-container-active select2-dropdown-open open\': $select.open, \'select2-container-disabled\': $select.disabled}\"><ul class=\"select2-choices\"><span class=\"ui-select-match\"></span><li class=\"select2-search-field\"><input type=\"search\" autocomplete=\"off\" autocorrect=\"off\" autocapitalize=\"off\" spellcheck=\"false\" role=\"combobox\" aria-expanded=\"true\" aria-owns=\"ui-select-choices-{{ $select.generatedId }}\" aria-label=\"{{ $select.baseTitle }}\" aria-activedescendant=\"ui-select-choices-row-{{ $select.generatedId }}-{{ $select.activeIndex }}\" class=\"select2-input ui-select-search\" placeholder=\"{{$selectMultiple.getPlaceholder()}}\" ng-disabled=\"$select.disabled\" ng-hide=\"$select.disabled\" ng-model=\"$select.search\" ng-click=\"$select.activate()\" style=\"width: 34px;\" ondrop=\"return false;\"></li></ul><div class=\"ui-select-dropdown select2-drop select2-with-searchbox select2-drop-active\" ng-class=\"{\'select2-display-none\': !$select.open || $select.items.length === 0}\"><div class=\"ui-select-choices\"></div></div></div>"); $templateCache.put("select2/select.tpl.html","<div class=\"ui-select-container select2 select2-container\" ng-class=\"{\'select2-container-active select2-dropdown-open open\': $select.open, \'select2-container-disabled\': $select.disabled, \'select2-container-active\': $select.focus, \'select2-allowclear\': $select.allowClear && !$select.isEmpty()}\"><div class=\"ui-select-match\"></div><div class=\"ui-select-dropdown select2-drop select2-with-searchbox select2-drop-active\" ng-class=\"{\'select2-display-none\': !$select.open}\"><div class=\"select2-search\" ng-show=\"$select.searchEnabled\"><input type=\"search\" autocomplete=\"off\" autocorrect=\"off\" autocapitalize=\"off\" spellcheck=\"false\" role=\"combobox\" aria-expanded=\"true\" aria-owns=\"ui-select-choices-{{ $select.generatedId }}\" aria-label=\"{{ $select.baseTitle }}\" aria-activedescendant=\"ui-select-choices-row-{{ $select.generatedId }}-{{ $select.activeIndex }}\" class=\"ui-select-search select2-input\" ng-model=\"$select.search\"></div><div class=\"ui-select-choices\"></div><div class=\"ui-select-no-choice\"></div></div></div>"); $templateCache.put("selectize/choices.tpl.html","<div ng-show=\"$select.open\" class=\"ui-select-choices ui-select-dropdown selectize-dropdown single\"><div class=\"ui-select-choices-content selectize-dropdown-content\"><div class=\"ui-select-choices-group optgroup\" role=\"listbox\"><div ng-show=\"$select.isGrouped\" class=\"ui-select-choices-group-label optgroup-header\" ng-bind=\"$group.name\"></div><div role=\"option\" class=\"ui-select-choices-row\" ng-class=\"{active: $select.isActive(this), disabled: $select.isDisabled(this)}\"><div class=\"option ui-select-choices-row-inner\" data-selectable=\"\"></div></div></div></div></div>"); $templateCache.put("selectize/match.tpl.html","<div ng-hide=\"$select.searchEnabled && ($select.open || $select.isEmpty())\" class=\"ui-select-match\" ng-transclude=\"\"></div>"); $templateCache.put("selectize/no-choice.tpl.html","<div class=\"ui-select-no-choice selectize-dropdown\" ng-show=\"$select.items.length == 0\"><div class=\"selectize-dropdown-content\"><div data-selectable=\"\" ng-transclude=\"\"></div></div></div>"); $templateCache.put("selectize/select.tpl.html","<div class=\"ui-select-container selectize-control single\" ng-class=\"{\'open\': $select.open}\"><div class=\"selectize-input\" ng-class=\"{\'focus\': $select.open, \'disabled\': $select.disabled, \'selectize-focus\' : $select.focus}\" ng-click=\"$select.open && !$select.searchEnabled ? $select.toggle($event) : $select.activate()\"><div class=\"ui-select-match\"></div><input type=\"search\" autocomplete=\"off\" tabindex=\"-1\" class=\"ui-select-search ui-select-toggle\" ng-click=\"$select.toggle($event)\" placeholder=\"{{$select.placeholder}}\" ng-model=\"$select.search\" ng-hide=\"!$select.searchEnabled || (!$select.isEmpty() && !$select.open)\" ng-disabled=\"$select.disabled\" aria-label=\"{{ $select.baseTitle }}\"></div><div class=\"ui-select-choices\"></div><div class=\"ui-select-no-choice\"></div></div>");}]);
rojak-ui-web/src/app/home/SearchForm.js
reinarduswindy/rojak
import React from 'react' class SearchForm extends React.Component { static propTypes = { keyword: React.PropTypes.string, onKeywordChange: React.PropTypes.func.isRequired } constructor (props) { super(props) this.state = { keyword: '' } this.throttleKeyChange = null } componentDidMount () { const { keyword } = this.props keyword && this.setState({ keyword }) } componentWillReceiveProps (nextProps) { const { keyword } = this.props if (nextProps.keyword !== keyword) { this.setState({ keyword: nextProps.keyword }) } } get handleKeywordChange () { const { onKeywordChange } = this.props return (e) => { const keyword = e.target.value this.setState({ keyword }) if (this.throttleKeyChange) { clearTimeout(this.throttleKeyChange) } this.throttleKeyChange = setTimeout(() => { onKeywordChange(keyword) }, 300) } } render () { const { keyword } = this.state return ( <form className="uk-form"> <input type="text" placeholder="cari dari nama kandidat, pasangan, atau media" className="uk-form-large uk-form-width-large" value={keyword} onChange={this.handleKeywordChange} style={{ padding: '10px 15px', borderRadius: '0px' }} /> </form> ) } } export default SearchForm
app/routes.js
bird-system/bs-label-convertor
// @flow import React from 'react'; import { Route, IndexRoute } from 'react-router'; import App from './containers/App'; import HomePage from './containers/HomePage'; import CounterPage from './containers/CounterPage'; import ScanPage from './containers/ScanPage'; export default ( <Route path="/" component={App}> <IndexRoute component={HomePage} /> <Route path="/counter" component={CounterPage} /> <Route path="/scan" component={ScanPage} /> </Route> );
src/components/AccountForm/index.js
varatep/anax-ui
import React from 'react'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import * as actions from '../../actions'; import AccountForm from './presenter'; function mapStateToProps(state) { return { accountForm: state.accountForm, device: state.device, configuration: state.configuration }; } function mapDispatchToProps(dispatch) { return { accountFormFieldChange: bindActionCreators(actions.accountFormFieldChange, dispatch), accountFormMultiFieldChange: bindActionCreators(actions.accountFormMultiFieldChange, dispatch), accountFormPasswordReset: bindActionCreators(actions.accountFormPasswordReset, dispatch), accountFormDataSubmit: bindActionCreators(actions.accountFormDataSubmit, dispatch), setExpectExistingAccount: bindActionCreators(actions.setExpectExistingAccount, dispatch), onCheckAccountCredentials: bindActionCreators(actions.checkAccountCredentials, dispatch), onGenerateNodeToken: bindActionCreators(actions.generateNodeToken, dispatch), onCreateExchangeUserAccount: bindActionCreators(actions.createExchangeUserAccount, dispatch), onSetExpectExistingToken: bindActionCreators(actions.setExpectExistingToken, dispatch), }; } export default connect(mapStateToProps, mapDispatchToProps)(AccountForm);
docs/app/Examples/modules/Accordion/Types/AccordionExamplePanelsProp.js
clemensw/stardust
import React from 'react' import { Accordion } from 'semantic-ui-react' import faker from 'faker' import _ from 'lodash' const panels = _.times(3, () => ({ title: faker.lorem.sentence(), content: faker.lorem.paragraphs(), })) const AccordionExamplePanelsProp = () => ( <Accordion panels={panels} /> ) export default AccordionExamplePanelsProp
src/editor/Editor.js
mcanthony/brackets
/* * Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ /*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */ /*global define, $, window */ /** * Editor is a 1-to-1 wrapper for a CodeMirror editor instance. It layers on Brackets-specific * functionality and provides APIs that cleanly pass through the bits of CodeMirror that the rest * of our codebase may want to interact with. An Editor is always backed by a Document, and stays * in sync with its content; because Editor keeps the Document alive, it's important to always * destroy() an Editor that's going away so it can release its Document ref. * * For now, there's a distinction between the "master" Editor for a Document - which secretly acts * as the Document's internal model of the text state - and the multitude of "slave" secondary Editors * which, via Document, sync their changes to and from that master. * * For now, direct access to the underlying CodeMirror object is still possible via `_codeMirror` -- * but this is considered deprecated and may go away. * * The Editor object dispatches the following events: * - keydown, keypress, keyup -- When any key event happens in the editor (whether it changes the * text or not). Handlers are passed `(BracketsEvent, Editor, KeyboardEvent)`. The 3nd arg is the * raw DOM event. Note: most listeners will only want to listen for "keypress". * - cursorActivity -- When the user moves the cursor or changes the selection, or an edit occurs. * Note: do not listen to this in order to be generally informed of edits--listen to the * "change" event on Document instead. * - scroll -- When the editor is scrolled, either by user action or programmatically. * - lostContent -- When the backing Document changes in such a way that this Editor is no longer * able to display accurate text. This occurs if the Document's file is deleted, or in certain * Document->editor syncing edge cases that we do not yet support (the latter cause will * eventually go away). * - optionChange -- Triggered when an option for the editor is changed. The 2nd arg to the listener * is a string containing the editor option that is changing. The 3rd arg, which can be any * data type, is the new value for the editor option. * - beforeDestroy - Triggered before the object is about to dispose of all its internal state data * so that listeners can cache things like scroll pos, etc... * * The Editor also dispatches "change" events internally, but you should listen for those on * Documents, not Editors. * * To listen for events, do something like this: (see EventDispatcher for details on this pattern) * `editorInstance.on("eventname", handler);` */ define(function (require, exports, module) { "use strict"; var AnimationUtils = require("utils/AnimationUtils"), Async = require("utils/Async"), CodeMirror = require("thirdparty/CodeMirror/lib/codemirror"), LanguageManager = require("language/LanguageManager"), EventDispatcher = require("utils/EventDispatcher"), Menus = require("command/Menus"), PerfUtils = require("utils/PerfUtils"), PopUpManager = require("widgets/PopUpManager"), PreferencesManager = require("preferences/PreferencesManager"), Strings = require("strings"), TextRange = require("document/TextRange").TextRange, TokenUtils = require("utils/TokenUtils"), ValidationUtils = require("utils/ValidationUtils"), ViewUtils = require("utils/ViewUtils"), _ = require("thirdparty/lodash"); /** Editor preferences */ var CLOSE_BRACKETS = "closeBrackets", CLOSE_TAGS = "closeTags", DRAG_DROP = "dragDropText", HIGHLIGHT_MATCHES = "highlightMatches", SCROLL_PAST_END = "scrollPastEnd", SHOW_CURSOR_SELECT = "showCursorWhenSelecting", SHOW_LINE_NUMBERS = "showLineNumbers", SMART_INDENT = "smartIndent", SOFT_TABS = "softTabs", SPACE_UNITS = "spaceUnits", STYLE_ACTIVE_LINE = "styleActiveLine", TAB_SIZE = "tabSize", UPPERCASE_COLORS = "uppercaseColors", USE_TAB_CHAR = "useTabChar", WORD_WRAP = "wordWrap"; var cmOptions = {}; /** * Constants * @type {number} */ var MIN_SPACE_UNITS = 1, MIN_TAB_SIZE = 1, DEFAULT_SPACE_UNITS = 4, DEFAULT_TAB_SIZE = 4, MAX_SPACE_UNITS = 10, MAX_TAB_SIZE = 10; // Mappings from Brackets preferences to CodeMirror options cmOptions[CLOSE_BRACKETS] = "autoCloseBrackets"; cmOptions[CLOSE_TAGS] = "autoCloseTags"; cmOptions[DRAG_DROP] = "dragDrop"; cmOptions[HIGHLIGHT_MATCHES] = "highlightSelectionMatches"; cmOptions[SCROLL_PAST_END] = "scrollPastEnd"; cmOptions[SHOW_CURSOR_SELECT] = "showCursorWhenSelecting"; cmOptions[SHOW_LINE_NUMBERS] = "lineNumbers"; cmOptions[SMART_INDENT] = "smartIndent"; cmOptions[SPACE_UNITS] = "indentUnit"; cmOptions[STYLE_ACTIVE_LINE] = "styleActiveLine"; cmOptions[TAB_SIZE] = "tabSize"; cmOptions[USE_TAB_CHAR] = "indentWithTabs"; cmOptions[WORD_WRAP] = "lineWrapping"; PreferencesManager.definePreference(CLOSE_BRACKETS, "boolean", true, { description: Strings.DESCRIPTION_CLOSE_BRACKETS }); PreferencesManager.definePreference(CLOSE_TAGS, "object", { whenOpening: true, whenClosing: true, indentTags: [] }, { description: Strings.DESCRIPTION_CLOSE_TAGS, keys: { dontCloseTags: { type: "array", description: Strings.DESCRIPTION_CLOSE_TAGS_DONT_CLOSE_TAGS }, whenOpening: { type: "boolean", description: Strings.DESCRIPTION_CLOSE_TAGS_WHEN_OPENING, initial: true }, whenClosing: { type: "boolean", description: Strings.DESCRIPTION_CLOSE_TAGS_WHEN_CLOSING, initial: true }, indentTags: { type: "array", description: Strings.DESCRIPTION_CLOSE_TAGS_INDENT_TAGS } } }); PreferencesManager.definePreference(DRAG_DROP, "boolean", false, { description: Strings.DESCRIPTION_DRAG_DROP_TEXT }); PreferencesManager.definePreference(HIGHLIGHT_MATCHES, "boolean", false, { description: Strings.DESCRIPTION_HIGHLIGHT_MATCHES, keys: { showToken: { type: "boolean", description: Strings.DESCRIPTION_HIGHLIGHT_MATCHES_SHOW_TOKEN, initial: false }, wordsOnly: { type: "boolean", description: Strings.DESCRIPTION_HIGHLIGHT_MATCHES_WORDS_ONLY, initial: false } } }); PreferencesManager.definePreference(SCROLL_PAST_END, "boolean", false, { description: Strings.DESCRIPTION_SCROLL_PAST_END }); PreferencesManager.definePreference(SHOW_CURSOR_SELECT, "boolean", false, { description: Strings.DESCRIPTION_SHOW_CURSOR_WHEN_SELECTING }); PreferencesManager.definePreference(SHOW_LINE_NUMBERS, "boolean", true, { description: Strings.DESCRIPTION_SHOW_LINE_NUMBERS }); PreferencesManager.definePreference(SMART_INDENT, "boolean", true, { description: Strings.DESCRIPTION_SMART_INDENT }); PreferencesManager.definePreference(SOFT_TABS, "boolean", true, { description: Strings.DESCRIPTION_SOFT_TABS }); PreferencesManager.definePreference(SPACE_UNITS, "number", DEFAULT_SPACE_UNITS, { validator: _.partialRight(ValidationUtils.isIntegerInRange, MIN_SPACE_UNITS, MAX_SPACE_UNITS), description: Strings.DESCRIPTION_SPACE_UNITS }); PreferencesManager.definePreference(STYLE_ACTIVE_LINE, "boolean", false, { description: Strings.DESCRIPTION_STYLE_ACTIVE_LINE }); PreferencesManager.definePreference(TAB_SIZE, "number", DEFAULT_TAB_SIZE, { validator: _.partialRight(ValidationUtils.isIntegerInRange, MIN_TAB_SIZE, MAX_TAB_SIZE), description: Strings.DESCRIPTION_TAB_SIZE }); PreferencesManager.definePreference(UPPERCASE_COLORS, "boolean", false, { description: Strings.DESCRIPTION_UPPERCASE_COLORS }); PreferencesManager.definePreference(USE_TAB_CHAR, "boolean", false, { description: Strings.DESCRIPTION_USE_TAB_CHAR }); PreferencesManager.definePreference(WORD_WRAP, "boolean", true, { description: Strings.DESCRIPTION_WORD_WRAP }); var editorOptions = Object.keys(cmOptions); /** Editor preferences */ /** * Guard flag to prevent focus() reentrancy (via blur handlers), even across Editors * @type {boolean} */ var _duringFocus = false; /** * Constant: ignore upper boundary when centering text * @type {number} */ var BOUNDARY_CHECK_NORMAL = 0, BOUNDARY_IGNORE_TOP = 1; /** * @private * Create a copy of the given CodeMirror position * @param {!CodeMirror.Pos} pos * @return {CodeMirror.Pos} */ function _copyPos(pos) { return new CodeMirror.Pos(pos.line, pos.ch); } /** * Helper functions to check options. * @param {number} options BOUNDARY_CHECK_NORMAL or BOUNDARY_IGNORE_TOP */ function _checkTopBoundary(options) { return (options !== BOUNDARY_IGNORE_TOP); } function _checkBottomBoundary(options) { return true; } /** * Helper function to build preferences context based on the full path of * the file. * * @param {string} fullPath Full path of the file * * @return {*} A context for the specified file name */ function _buildPreferencesContext(fullPath) { return PreferencesManager._buildContext(fullPath, fullPath ? LanguageManager.getLanguageForPath(fullPath).getId() : undefined); } /** * List of all current (non-destroy()ed) Editor instances. Needed when changing global preferences * that affect all editors, e.g. tabbing or color scheme settings. * @type {Array.<Editor>} */ var _instances = []; /** * Creates a new CodeMirror editor instance bound to the given Document. The Document need not have * a "master" Editor realized yet, even if makeMasterEditor is false; in that case, the first time * an edit occurs we will automatically ask EditorManager to create a "master" editor to render the * Document modifiable. * * ALWAYS call destroy() when you are done with an Editor - otherwise it will leak a Document ref. * * @constructor * * @param {!Document} document * @param {!boolean} makeMasterEditor If true, this Editor will set itself as the (secret) "master" * Editor for the Document. If false, this Editor will attach to the Document as a "slave"/ * secondary editor. * @param {!jQueryObject|DomNode} container Container to add the editor to. * @param {{startLine: number, endLine: number}=} range If specified, range of lines within the document * to display in this editor. Inclusive. * @param {!Object} options If specified, contains editor options that can be passed to CodeMirror */ function Editor(document, makeMasterEditor, container, range, options) { var self = this; var isReadOnly = options && options.isReadOnly; _instances.push(this); // Attach to document: add ref & handlers this.document = document; document.addRef(); if (container.jquery) { // CodeMirror wants a DOM element, not a jQuery wrapper container = container.get(0); } var $container = $(container); if (range) { // attach this first: want range updated before we process a change this._visibleRange = new TextRange(document, range.startLine, range.endLine); } // store this-bound version of listeners so we can remove them later this._handleDocumentChange = this._handleDocumentChange.bind(this); this._handleDocumentDeleted = this._handleDocumentDeleted.bind(this); this._handleDocumentLanguageChanged = this._handleDocumentLanguageChanged.bind(this); document.on("change", this._handleDocumentChange); document.on("deleted", this._handleDocumentDeleted); document.on("languageChanged", this._handleDocumentLanguageChanged); var mode = this._getModeFromDocument(); // (if makeMasterEditor, we attach the Doc back to ourselves below once we're fully initialized) this._inlineWidgets = []; this._inlineWidgetQueues = {}; this._hideMarks = []; this._lastEditorWidth = null; this._$messagePopover = null; // Editor supplies some standard keyboard behavior extensions of its own var codeMirrorKeyMap = { "Tab": function () { self._handleTabKey(); }, "Shift-Tab": "indentLess", "Left": function (instance) { self._handleSoftTabNavigation(-1, "moveH"); }, "Right": function (instance) { self._handleSoftTabNavigation(1, "moveH"); }, "Backspace": function (instance) { self._handleSoftTabNavigation(-1, "deleteH"); }, "Delete": function (instance) { self._handleSoftTabNavigation(1, "deleteH"); }, "Esc": function (instance) { if (self.getSelections().length > 1) { CodeMirror.commands.singleSelection(instance); } else { self.removeAllInlineWidgets(); } }, "Home": "goLineLeftSmart", "Cmd-Left": "goLineLeftSmart", "End": "goLineRight", "Cmd-Right": "goLineRight" }; var currentOptions = this._currentOptions = _.zipObject( editorOptions, _.map(editorOptions, function (prefName) { return self._getOption(prefName); }) ); // When panes are created *after* the showLineNumbers option has been turned off // we need to apply the show-line-padding class or the text will be juxtaposed // to the edge of the editor which makes it not easy to read. The code below to handle // that the option change only applies the class to panes that have already been created // This line ensures that the class is applied to any editor created after the fact $container.toggleClass("show-line-padding", Boolean(!this._getOption("showLineNumbers"))); // Create the CodeMirror instance // (note: CodeMirror doesn't actually require using 'new', but jslint complains without it) this._codeMirror = new CodeMirror(container, { autoCloseBrackets : currentOptions[CLOSE_BRACKETS], autoCloseTags : currentOptions[CLOSE_TAGS], coverGutterNextToScrollbar : true, cursorScrollMargin : 3, dragDrop : currentOptions[DRAG_DROP], electricChars : true, extraKeys : codeMirrorKeyMap, highlightSelectionMatches : currentOptions[HIGHLIGHT_MATCHES], indentUnit : currentOptions[USE_TAB_CHAR] ? currentOptions[TAB_SIZE] : currentOptions[SPACE_UNITS], indentWithTabs : currentOptions[USE_TAB_CHAR], inputStyle : "textarea", // the "contenteditable" mode used on mobiles could cause issues lineNumbers : currentOptions[SHOW_LINE_NUMBERS], lineWrapping : currentOptions[WORD_WRAP], matchBrackets : { maxScanLineLength: 50000, maxScanLines: 1000 }, matchTags : { bothTags: true }, scrollPastEnd : !range && currentOptions[SCROLL_PAST_END], showCursorWhenSelecting : currentOptions[SHOW_CURSOR_SELECT], smartIndent : currentOptions[SMART_INDENT], styleActiveLine : currentOptions[STYLE_ACTIVE_LINE], tabSize : currentOptions[TAB_SIZE], readOnly : isReadOnly }); // Can't get CodeMirror's focused state without searching for // CodeMirror-focused. Instead, track focus via onFocus and onBlur // options and track state with this._focused this._focused = false; this._installEditorListeners(); this.on("cursorActivity", function (event, editor) { self._handleCursorActivity(event); }); this.on("keypress", function (event, editor, domEvent) { self._handleKeypressEvents(domEvent); }); this.on("change", function (event, editor, changeList) { self._handleEditorChange(changeList); }); // Set code-coloring mode BEFORE populating with text, to avoid a flash of uncolored text this._codeMirror.setOption("mode", mode); // Initially populate with text. This will send a spurious change event, so need to make // sure this is understood as a 'sync from document' case, not a genuine edit this._duringSync = true; this._resetText(document.getText()); this._duringSync = false; if (range) { this._updateHiddenLines(); this.setCursorPos(range.startLine, 0); } // Now that we're fully initialized, we can point the document back at us if needed if (makeMasterEditor) { document._makeEditable(this); } // Add scrollTop property to this object for the scroll shadow code to use Object.defineProperty(this, "scrollTop", { get: function () { return this._codeMirror.getScrollInfo().top; } }); // Add an $el getter for Pane Views Object.defineProperty(this, "$el", { get: function () { return $(this.getRootElement()); } }); } EventDispatcher.makeEventDispatcher(Editor.prototype); EventDispatcher.markDeprecated(Editor.prototype, "keyEvent", "'keydown/press/up'"); /** * Removes this editor from the DOM and detaches from the Document. If this is the "master" * Editor that is secretly providing the Document's backing state, then the Document reverts to * a read-only string-backed mode. */ Editor.prototype.destroy = function () { this.trigger("beforeDestroy", this); // CodeMirror docs for getWrapperElement() say all you have to do is "Remove this from your // tree to delete an editor instance." $(this.getRootElement()).remove(); _instances.splice(_instances.indexOf(this), 1); // Disconnect from Document this.document.releaseRef(); this.document.off("change", this._handleDocumentChange); this.document.off("deleted", this._handleDocumentDeleted); this.document.off("languageChanged", this._handleDocumentLanguageChanged); if (this._visibleRange) { // TextRange also refs the Document this._visibleRange.dispose(); } // If we're the Document's master editor, disconnecting from it has special meaning if (this.document._masterEditor === this) { this.document._makeNonEditable(); } // Destroying us destroys any inline widgets we're hosting. Make sure their closeCallbacks // run, at least, since they may also need to release Document refs var self = this; this._inlineWidgets.forEach(function (inlineWidget) { self._removeInlineWidgetInternal(inlineWidget); }); }; /** * @private * Handle any cursor movement in editor, including selecting and unselecting text. * @param {!Event} event */ Editor.prototype._handleCursorActivity = function (event) { this._updateStyleActiveLine(); }; /** * @private * Removes any whitespace after one of ]{}) to prevent trailing whitespace when auto-indenting */ Editor.prototype._handleWhitespaceForElectricChars = function () { var self = this, instance = this._codeMirror, selections, lineStr; selections = this.getSelections().map(function (sel) { lineStr = instance.getLine(sel.end.line); if (lineStr && !/\S/.test(lineStr)) { // if the line is all whitespace, move the cursor to the end of the line // before indenting so that embedded whitespace such as indents are not // orphaned to the right of the electric char being inserted sel.end.ch = self.document.getLine(sel.end.line).length; } return sel; }); this.setSelections(selections); }; /** * @private * Handle CodeMirror key events. * @param {!Event} event */ Editor.prototype._handleKeypressEvents = function (event) { var keyStr = String.fromCharCode(event.which || event.keyCode); if (/[\]\{\}\)]/.test(keyStr)) { this._handleWhitespaceForElectricChars(); } }; /** * @private * Helper function for `_handleTabKey()` (case 2) - see comment in that function. * @param {Array.<{start:{line:number, ch:number}, end:{line:number, ch:number}, reversed:boolean, primary:boolean}>} selections * The selections to indent. */ Editor.prototype._addIndentAtEachSelection = function (selections) { var instance = this._codeMirror, usingTabs = instance.getOption("indentWithTabs"), indentUnit = instance.getOption("indentUnit"), edits = []; _.each(selections, function (sel) { var indentStr = "", i, numSpaces; if (usingTabs) { indentStr = "\t"; } else { numSpaces = indentUnit - (sel.start.ch % indentUnit); for (i = 0; i < numSpaces; i++) { indentStr += " "; } } edits.push({edit: {text: indentStr, start: sel.start}}); }); this.document.doMultipleEdits(edits); }; /** * @private * Helper function for `_handleTabKey()` (case 3) - see comment in that function. * @param {Array.<{start:{line:number, ch:number}, end:{line:number, ch:number}, reversed:boolean, primary:boolean}>} selections * The selections to indent. */ Editor.prototype._autoIndentEachSelection = function (selections) { // Capture all the line lengths, so we can tell if anything changed. // Note that this function should only be called if all selections are within a single line. var instance = this._codeMirror, lineLengths = {}; _.each(selections, function (sel) { lineLengths[sel.start.line] = instance.getLine(sel.start.line).length; }); // First, try to do a smart indent on all selections. CodeMirror.commands.indentAuto(instance); // If there were no code or selection changes, then indent each selection one more indent. var changed = false, newSelections = this.getSelections(); if (newSelections.length === selections.length) { _.each(selections, function (sel, index) { var newSel = newSelections[index]; if (CodeMirror.cmpPos(sel.start, newSel.start) !== 0 || CodeMirror.cmpPos(sel.end, newSel.end) !== 0 || instance.getLine(sel.start.line).length !== lineLengths[sel.start.line]) { changed = true; // Bail - we don't need to look any further once we've found a change. return false; } }); } else { changed = true; } if (!changed) { CodeMirror.commands.indentMore(instance); } }; /** * @private * Handle Tab key press. */ Editor.prototype._handleTabKey = function () { // Tab key handling is done as follows: // 1. If any of the selections are multiline, just add one indent level to the // beginning of all lines that intersect any selection. // 2. Otherwise, if any of the selections is a cursor or single-line range that // ends at or after the first non-whitespace character in a line: // - if indentation is set to tabs, just insert a hard tab before each selection. // - if indentation is set to spaces, insert the appropriate number of spaces before // each selection to get to its next soft tab stop. // 3. Otherwise (all selections are cursors or single-line, and are in the whitespace // before their respective lines), try to autoindent each line based on the mode. // If none of the cursors moved and no space was added, then add one indent level // to the beginning of all lines. // Note that in case 2, we do the "dumb" insertion even if the cursor is immediately // before the first non-whitespace character in a line. It might seem more convenient // to do autoindent in that case. However, the problem is if that line is already // indented past its "proper" location. In that case, we don't want Tab to // *outdent* the line. If we had more control over the autoindent algorithm or // implemented it ourselves, we could handle that case separately. var instance = this._codeMirror, selectionType = "indentAuto", selections = this.getSelections(); _.each(selections, function (sel) { if (sel.start.line !== sel.end.line) { // Case 1 - we found a multiline selection. We can bail as soon as we find one of these. selectionType = "indentAtBeginning"; return false; } else if (sel.end.ch > 0 && sel.end.ch >= instance.getLine(sel.end.line).search(/\S/)) { // Case 2 - we found a selection that ends at or after the first non-whitespace // character on the line. We need to keep looking in case we find a later multiline // selection though. selectionType = "indentAtSelection"; } }); switch (selectionType) { case "indentAtBeginning": // Case 1 CodeMirror.commands.indentMore(instance); break; case "indentAtSelection": // Case 2 this._addIndentAtEachSelection(selections); break; case "indentAuto": // Case 3 this._autoIndentEachSelection(selections); break; } }; /** * @private * Handle left arrow, right arrow, backspace and delete keys when soft tabs are used. * @param {number} direction Direction of movement: 1 for forward, -1 for backward * @param {string} functionName name of the CodeMirror function to call if we handle the key */ Editor.prototype._handleSoftTabNavigation = function (direction, functionName) { var instance = this._codeMirror, overallJump = null; if (!instance.getOption("indentWithTabs") && PreferencesManager.get(SOFT_TABS)) { var indentUnit = instance.getOption("indentUnit"); _.each(this.getSelections(), function (sel) { if (CodeMirror.cmpPos(sel.start, sel.end) !== 0) { // This is a range - it will just collapse/be deleted regardless of the jump we set, so // we can just ignore it and continue. (We don't want to return false in this case since // we want to keep looking at other ranges.) return; } var cursor = sel.start, jump = (indentUnit === 0) ? 1 : cursor.ch % indentUnit, line = instance.getLine(cursor.line); // Don't do any soft tab handling if there are non-whitespace characters before the cursor in // any of the selections. if (line.substr(0, cursor.ch).search(/\S/) !== -1) { jump = null; } else if (direction === 1) { // right if (indentUnit) { jump = indentUnit - jump; } // Don't jump if it would take us past the end of the line, or if there are // non-whitespace characters within the jump distance. if (cursor.ch + jump > line.length || line.substr(cursor.ch, jump).search(/\S/) !== -1) { jump = null; } } else { // left // If we are on the tab boundary, jump by the full amount, // but not beyond the start of the line. if (jump === 0) { jump = indentUnit; } if (cursor.ch - jump < 0) { jump = null; } else { // We're moving left, so negate the jump. jump = -jump; } } // Did we calculate a jump, and is this jump value either the first one or // consistent with all the other jumps? If so, we're good. Otherwise, bail // out of the foreach, since as soon as we hit an inconsistent jump we don't // have to look any further. if (jump !== null && (overallJump === null || overallJump === jump)) { overallJump = jump; } else { overallJump = null; return false; } }); } if (overallJump === null) { // Just do the default move, which is one char in the given direction. overallJump = direction; } instance[functionName](overallJump, "char"); }; /** * Determine the mode to use from the document's language * Uses "text/plain" if the language does not define a mode * @return {string} The mode to use */ Editor.prototype._getModeFromDocument = function () { // We'd like undefined/null/"" to mean plain text mode. CodeMirror defaults to plaintext for any // unrecognized mode, but it complains on the console in that fallback case: so, convert // here so we're always explicit, avoiding console noise. return this.document.getLanguage().getMode() || "text/plain"; }; /** * Selects all text and maintains the current scroll position. */ Editor.prototype.selectAllNoScroll = function () { var cm = this._codeMirror, info = this._codeMirror.getScrollInfo(); // Note that we do not have to check for the visible range here. This // concern is handled internally by code mirror. cm.operation(function () { cm.scrollTo(info.left, info.top); cm.execCommand("selectAll"); }); }; /** * @return {boolean} True if editor is not showing the entire text of the document (i.e. an inline editor) */ Editor.prototype.isTextSubset = function () { return Boolean(this._visibleRange); }; /** * Ensures that the lines that are actually hidden in the inline editor correspond to * the desired visible range. */ Editor.prototype._updateHiddenLines = function () { if (this._visibleRange) { var cm = this._codeMirror, self = this; cm.operation(function () { self._hideMarks.forEach(function (mark) { if (mark) { mark.clear(); } }); self._hideMarks = []; self._hideMarks.push(self._hideLines(0, self._visibleRange.startLine)); self._hideMarks.push(self._hideLines(self._visibleRange.endLine + 1, self.lineCount())); }); } }; Editor.prototype._applyChanges = function (changeList) { // _visibleRange has already updated via its own Document listener. See if this change caused // it to lose sync. If so, our whole view is stale - signal our owner to close us. if (this._visibleRange) { if (this._visibleRange.startLine === null || this._visibleRange.endLine === null) { this.trigger("lostContent"); return; } } // Apply text changes to CodeMirror editor var cm = this._codeMirror; cm.operation(function () { var change, newText, i; for (i = 0; i < changeList.length; i++) { change = changeList[i]; newText = change.text.join('\n'); if (!change.from || !change.to) { if (change.from || change.to) { console.error("Change record received with only one end undefined--replacing entire text"); } cm.setValue(newText); } else { cm.replaceRange(newText, change.from, change.to, change.origin); } } }); // The update above may have inserted new lines - must hide any that fall outside our range this._updateHiddenLines(); }; /** * Responds to changes in the CodeMirror editor's text, syncing the changes to the Document. * There are several cases where we want to ignore a CodeMirror change: * - if we're the master editor, editor changes can be ignored because Document is already listening * for our changes * - if we're a secondary editor, editor changes should be ignored if they were caused by us reacting * to a Document change */ Editor.prototype._handleEditorChange = function (changeList) { // we're currently syncing from the Document, so don't echo back TO the Document if (this._duringSync) { return; } // Secondary editor: force creation of "master" editor backing the model, if doesn't exist yet this.document._ensureMasterEditor(); if (this.document._masterEditor !== this) { // Secondary editor: // we're not the ground truth; if we got here, this was a real editor change (not a // sync from the real ground truth), so we need to sync from us into the document // (which will directly push the change into the master editor). // FUTURE: Technically we should add a replaceRange() method to Document and go through // that instead of talking to its master editor directly. It's not clear yet exactly // what the right Document API would be, though. this._duringSync = true; this.document._masterEditor._applyChanges(changeList); this._duringSync = false; // Update which lines are hidden inside our editor, since we're not going to go through // _applyChanges() in our own editor. this._updateHiddenLines(); } // Else, Master editor: // we're the ground truth; nothing else to do, since Document listens directly to us // note: this change might have been a real edit made by the user, OR this might have // been a change synced from another editor // The "editorChange" event is mostly for the use of the CodeHintManager. // It differs from the normal "change" event, that it's actually publicly usable, // whereas the "change" event should be listened to on the document. Also the // Editor dispatches a change event before this event is dispatched, because // CodeHintManager needs to hook in here when other things are already done. this.trigger("editorChange", this, changeList); }; /** * Responds to changes in the Document's text, syncing the changes into our CodeMirror instance. * There are several cases where we want to ignore a Document change: * - if we're the master editor, Document changes should be ignored because we already have the right * text (either the change originated with us, or it has already been set into us by Document) * - if we're a secondary editor, Document changes should be ignored if they were caused by us sending * the document an editor change that originated with us */ Editor.prototype._handleDocumentChange = function (event, doc, changeList) { // we're currently syncing to the Document, so don't echo back FROM the Document if (this._duringSync) { return; } if (this.document._masterEditor !== this) { // Secondary editor: // we're not the ground truth; and if we got here, this was a Document change that // didn't come from us (e.g. a sync from another editor, a direct programmatic change // to the document, or a sync from external disk changes)... so sync from the Document this._duringSync = true; this._applyChanges(changeList); this._duringSync = false; } // Else, Master editor: // we're the ground truth; nothing to do since Document change is just echoing our // editor changes }; /** * Responds to the Document's underlying file being deleted. The Document is now basically dead, * so we must close. */ Editor.prototype._handleDocumentDeleted = function (event) { // Pass the delete event along as the cause (needed in MultiRangeInlineEditor) this.trigger("lostContent", event); }; /** * Responds to language changes, for instance when the file extension is changed. */ Editor.prototype._handleDocumentLanguageChanged = function (event) { this._codeMirror.setOption("mode", this._getModeFromDocument()); }; /** * Install event handlers on the CodeMirror instance, translating them into * jQuery events on the Editor instance. */ Editor.prototype._installEditorListeners = function () { var self = this; // Redispatch these CodeMirror key events as Editor events function _onKeyEvent(instance, event) { self.trigger("keyEvent", self, event); // deprecated self.trigger(event.type, self, event); return event.defaultPrevented; // false tells CodeMirror we didn't eat the event } this._codeMirror.on("keydown", _onKeyEvent); this._codeMirror.on("keypress", _onKeyEvent); this._codeMirror.on("keyup", _onKeyEvent); // FUTURE: if this list grows longer, consider making this a more generic mapping // NOTE: change is a "private" event--others shouldn't listen to it on Editor, only on // Document // Also, note that we use the new "changes" event in v4, which provides an array of // change objects. Our own event is still called just "change". this._codeMirror.on("changes", function (instance, changeList) { self.trigger("change", self, changeList); }); this._codeMirror.on("beforeChange", function (instance, changeObj) { self.trigger("beforeChange", self, changeObj); }); this._codeMirror.on("cursorActivity", function (instance) { self.trigger("cursorActivity", self); }); this._codeMirror.on("scroll", function (instance) { // If this editor is visible, close all dropdowns on scroll. // (We don't want to do this if we're just scrolling in a non-visible editor // in response to some document change event.) if (self.isFullyVisible()) { Menus.closeAll(); } self.trigger("scroll", self); }); // Convert CodeMirror onFocus events to EditorManager activeEditorChanged this._codeMirror.on("focus", function () { self._focused = true; self.trigger("focus", self); }); this._codeMirror.on("blur", function () { self._focused = false; self.trigger("blur", self); }); this._codeMirror.on("update", function (instance) { self.trigger("update", self); }); this._codeMirror.on("overwriteToggle", function (instance, newstate) { self.trigger("overwriteToggle", self, newstate); }); // Disable CodeMirror's drop handling if a file/folder is dropped this._codeMirror.on("drop", function (cm, event) { var files = event.dataTransfer.files; if (files && files.length) { event.preventDefault(); } }); }; /** * Sets the contents of the editor, clears the undo/redo history and marks the document clean. Dispatches a change event. * Semi-private: only Document should call this. * @param {!string} text */ Editor.prototype._resetText = function (text) { var perfTimerName = PerfUtils.markStart("Editor._resetText()\t" + (!this.document || this.document.file.fullPath)); var cursorPos = this.getCursorPos(), scrollPos = this.getScrollPos(); // This *will* fire a change event, but we clear the undo immediately afterward this._codeMirror.setValue(text); this._codeMirror.refresh(); // Make sure we can't undo back to the empty state before setValue(), and mark // the document clean. this._codeMirror.clearHistory(); this._codeMirror.markClean(); // restore cursor and scroll positions this.setCursorPos(cursorPos); this.setScrollPos(scrollPos.x, scrollPos.y); PerfUtils.addMeasurement(perfTimerName); }; /** * Gets the file associated with this editor * This is a required Pane-View interface method * @return {!File} the file associated with this editor */ Editor.prototype.getFile = function () { return this.document.file; }; /** * Gets the current cursor position within the editor. * @param {boolean} expandTabs If true, return the actual visual column number instead of the character offset in * the "ch" property. * @param {?string} which Optional string indicating which end of the * selection to return. It may be "start", "end", "head" (the side of the * selection that moves when you press shift+arrow), or "anchor" (the * fixed side of the selection). Omitting the argument is the same as * passing "head". A {line, ch} object will be returned.) * @return {!{line:number, ch:number}} */ Editor.prototype.getCursorPos = function (expandTabs, which) { // Translate "start" and "end" to the official CM names (it actually // supports them as-is, but that isn't documented and we don't want to // rely on it). if (which === "start") { which = "from"; } else if (which === "end") { which = "to"; } var cursor = _copyPos(this._codeMirror.getCursor(which)); if (expandTabs) { cursor.ch = this.getColOffset(cursor); } return cursor; }; /** * Returns the display column (zero-based) for a given string-based pos. Differs from pos.ch only * when the line contains preceding \t chars. Result depends on the current tab size setting. * @param {!{line:number, ch:number}} pos * @return {number} */ Editor.prototype.getColOffset = function (pos) { var line = this._codeMirror.getRange({line: pos.line, ch: 0}, pos), tabSize = null, column = 0, i; for (i = 0; i < line.length; i++) { if (line[i] === '\t') { if (tabSize === null) { tabSize = Editor.getTabSize(); } if (tabSize > 0) { column += (tabSize - (column % tabSize)); } } else { column++; } } return column; }; /** * Returns the string-based pos for a given display column (zero-based) in given line. Differs from column * only when the line contains preceding \t chars. Result depends on the current tab size setting. * @param {number} lineNum Line number * @param {number} column Display column number * @return {number} */ Editor.prototype.getCharIndexForColumn = function (lineNum, column) { var line = this._codeMirror.getLine(lineNum), tabSize = null, iCol = 0, i; for (i = 0; iCol < column; i++) { if (line[i] === '\t') { if (tabSize === null) { tabSize = Editor.getTabSize(); } if (tabSize > 0) { iCol += (tabSize - (iCol % tabSize)); } } else { iCol++; } } return i; }; /** * Sets the cursor position within the editor. Removes any selection. * @param {number} line The 0 based line number. * @param {number} ch The 0 based character position; treated as 0 if unspecified. * @param {boolean=} center True if the view should be centered on the new cursor position. * @param {boolean=} expandTabs If true, use the actual visual column number instead of the character offset as * the "ch" parameter. */ Editor.prototype.setCursorPos = function (line, ch, center, expandTabs) { if (expandTabs) { ch = this.getColOffset({line: line, ch: ch}); } this._codeMirror.setCursor(line, ch); if (center) { this.centerOnCursor(); } }; /** * Set the editor size in pixels or percentage * @param {(number|string)} width * @param {(number|string)} height */ Editor.prototype.setSize = function (width, height) { this._codeMirror.setSize(width, height); }; /** @const */ var CENTERING_MARGIN = 0.15; /** * Scrolls the editor viewport to vertically center the line with the cursor, * but only if the cursor is currently near the edges of the viewport or * entirely outside the viewport. * * This does not alter the horizontal scroll position. * * @param {number} centerOptions Option value, or 0 for no options; one of the BOUNDARY_* constants above. */ Editor.prototype.centerOnCursor = function (centerOptions) { var $scrollerElement = $(this.getScrollerElement()); var editorHeight = $scrollerElement.height(); // we need to make adjustments for the statusbar's padding on the bottom and the menu bar on top. var statusBarHeight = $scrollerElement.outerHeight() - editorHeight; var menuBarHeight = $scrollerElement.offset().top; var documentCursorPosition = this._codeMirror.cursorCoords(null, "local").bottom; var screenCursorPosition = this._codeMirror.cursorCoords(null, "page").bottom - menuBarHeight; // If the cursor is already reasonably centered, we won't // make any change. "Reasonably centered" is defined as // not being within CENTERING_MARGIN of the top or bottom // of the editor (where CENTERING_MARGIN is a percentage // of the editor height). // For finding the first item (i.e. find while typing), do // not center if hit is in first half of screen because this // appears to be an unnecesary scroll. if ((_checkTopBoundary(centerOptions) && (screenCursorPosition < editorHeight * CENTERING_MARGIN)) || (_checkBottomBoundary(centerOptions) && (screenCursorPosition > editorHeight * (1 - CENTERING_MARGIN)))) { var pos = documentCursorPosition - editorHeight / 2 + statusBarHeight; var info = this._codeMirror.getScrollInfo(); pos = Math.min(Math.max(pos, 0), (info.height - info.clientHeight)); this.setScrollPos(null, pos); } }; /** * Given a position, returns its index within the text (assuming \n newlines) * @param {!{line:number, ch:number}} * @return {number} */ Editor.prototype.indexFromPos = function (coords) { return this._codeMirror.indexFromPos(coords); }; /** * Returns true if pos is between start and end (INclusive at start; EXclusive at end by default, * but overridable via the endInclusive flag). * @param {{line:number, ch:number}} pos * @param {{line:number, ch:number}} start * @param {{line:number, ch:number}} end * @param {boolean} endInclusive * */ Editor.prototype.posWithinRange = function (pos, start, end, endInclusive) { if (start.line <= pos.line && end.line >= pos.line) { if (endInclusive) { return (start.line < pos.line || start.ch <= pos.ch) && // inclusive (end.line > pos.line || end.ch >= pos.ch); // inclusive } else { return (start.line < pos.line || start.ch <= pos.ch) && // inclusive (end.line > pos.line || end.ch > pos.ch); // exclusive } } return false; }; /** * @return {boolean} True if there's a text selection; false if there's just an insertion point */ Editor.prototype.hasSelection = function () { return this._codeMirror.somethingSelected(); }; /** * @private * Takes an anchor/head pair and returns a start/end pair where the start is guaranteed to be <= end, and a "reversed" flag indicating * if the head is before the anchor. * @param {!{line: number, ch: number}} anchorPos * @param {!{line: number, ch: number}} headPos * @return {!{start:{line:number, ch:number}, end:{line:number, ch:number}}, reversed:boolean} the normalized range with start <= end */ function _normalizeRange(anchorPos, headPos) { if (headPos.line < anchorPos.line || (headPos.line === anchorPos.line && headPos.ch < anchorPos.ch)) { return {start: _copyPos(headPos), end: _copyPos(anchorPos), reversed: true}; } else { return {start: _copyPos(anchorPos), end: _copyPos(headPos), reversed: false}; } } /** * Gets the current selection; if there is more than one selection, returns the primary selection * (generally the last one made). Start is inclusive, end is exclusive. If there is no selection, * returns the current cursor position as both the start and end of the range (i.e. a selection * of length zero). If `reversed` is set, then the head of the selection (the end of the selection * that would be changed if the user extended the selection) is before the anchor. * @return {!{start:{line:number, ch:number}, end:{line:number, ch:number}}, reversed:boolean} */ Editor.prototype.getSelection = function () { return _normalizeRange(this.getCursorPos(false, "anchor"), this.getCursorPos(false, "head")); }; /** * Returns an array of current selections, nonoverlapping and sorted in document order. * Each selection is a start/end pair, with the start guaranteed to come before the end. * Cursors are represented as a range whose start is equal to the end. * If `reversed` is set, then the head of the selection * (the end of the selection that would be changed if the user extended the selection) * is before the anchor. * If `primary` is set, then that selection is the primary selection. * @return {Array.<{start:{line:number, ch:number}, end:{line:number, ch:number}, reversed:boolean, primary:boolean}>} */ Editor.prototype.getSelections = function () { var primarySel = this.getSelection(); return _.map(this._codeMirror.listSelections(), function (sel) { var result = _normalizeRange(sel.anchor, sel.head); if (result.start.line === primarySel.start.line && result.start.ch === primarySel.start.ch && result.end.line === primarySel.end.line && result.end.ch === primarySel.end.ch) { result.primary = true; } else { result.primary = false; } return result; }); }; /** * Takes the given selections, and expands each selection so it encompasses whole lines. Merges * adjacent line selections together. Keeps track of each original selection associated with a given * line selection (there might be multiple if individual selections were merged into a single line selection). * Useful for doing multiple-selection-aware line edits. * * @param {Array.<{start:{line:number, ch:number}, end:{line:number, ch:number}, reversed:boolean, primary:boolean}>} selections * The selections to expand. * @param {{expandEndAtStartOfLine: boolean, mergeAdjacent: boolean}} options * expandEndAtStartOfLine: true if a range selection that ends at the beginning of a line should be expanded * to encompass the line. Default false. * mergeAdjacent: true if adjacent line ranges should be merged. Default true. * @return {Array.<{selectionForEdit: {start:{line:number, ch:number}, end:{line:number, ch:number}, reversed:boolean, primary:boolean}, * selectionsToTrack: Array.<{start:{line:number, ch:number}, end:{line:number, ch:number}, reversed:boolean, primary:boolean}>}>} * The combined line selections. For each selection, `selectionForEdit` is the line selection, and `selectionsToTrack` is * the set of original selections that combined to make up the given line selection. Note that the selectionsToTrack will * include the original objects passed in `selections`, so if it is later mutated the original passed-in selections will be * mutated as well. */ Editor.prototype.convertToLineSelections = function (selections, options) { var self = this; options = options || {}; _.defaults(options, { expandEndAtStartOfLine: false, mergeAdjacent: true }); // Combine adjacent lines with selections so they don't collide with each other, as they would // if we did them individually. var combinedSelections = [], prevSel; _.each(selections, function (sel) { var newSel = _.cloneDeep(sel); // Adjust selection to encompass whole lines. newSel.start.ch = 0; // The end of the selection becomes the start of the next line, if it isn't already // or if expandEndAtStartOfLine is set. var hasSelection = (newSel.start.line !== newSel.end.line) || (newSel.start.ch !== newSel.end.ch); if (options.expandEndAtStartOfLine || !hasSelection || newSel.end.ch !== 0) { newSel.end = {line: newSel.end.line + 1, ch: 0}; } // If the start of the new selection is within the range of the previous (expanded) selection, merge // the two selections together, but keep track of all the original selections that were related to this // selection, so they can be properly adjusted. (We only have to check for the start being inside the previous // range - it can't be before it because the selections started out sorted.) if (prevSel && self.posWithinRange(newSel.start, prevSel.selectionForEdit.start, prevSel.selectionForEdit.end, options.mergeAdjacent)) { prevSel.selectionForEdit.end.line = newSel.end.line; prevSel.selectionsToTrack.push(sel); } else { prevSel = {selectionForEdit: newSel, selectionsToTrack: [sel]}; combinedSelections.push(prevSel); } }); return combinedSelections; }; /** * Returns the currently selected text, or "" if no selection. Includes \n if the * selection spans multiple lines (does NOT reflect the Document's line-endings style). By * default, returns only the contents of the primary selection, unless `allSelections` is true. * @param {boolean=} allSelections Whether to return the contents of all selections (separated * by newlines) instead of just the primary selection. Default false. * @return {!string} The selected text. */ Editor.prototype.getSelectedText = function (allSelections) { if (allSelections) { return this._codeMirror.getSelection(); } else { var sel = this.getSelection(); return this.document.getRange(sel.start, sel.end); } }; /** * Sets the current selection. Start is inclusive, end is exclusive. Places the cursor at the * end of the selection range. Optionally centers around the cursor after * making the selection * * @param {!{line:number, ch:number}} start * @param {{line:number, ch:number}=} end If not specified, defaults to start. * @param {boolean} center true to center the viewport * @param {number} centerOptions Option value, or 0 for no options; one of the BOUNDARY_* constants above. * @param {?string} origin An optional string that describes what other selection or edit operations this * should be merged with for the purposes of undo. See {@link Document#replaceRange} for more details. */ Editor.prototype.setSelection = function (start, end, center, centerOptions, origin) { this.setSelections([{start: start, end: end || start}], center, centerOptions, origin); }; /** * Sets a multiple selection, with the "primary" selection (the one returned by * getSelection() and getCursorPos()) defaulting to the last if not specified. * Overlapping ranges will be automatically merged, and the selection will be sorted. * Optionally centers around the primary selection after making the selection. * @param {!Array<{start:{line:number, ch:number}, end:{line:number, ch:number}, primary:boolean, reversed: boolean}>} selections * The selection ranges to set. If the start and end of a range are the same, treated as a cursor. * If reversed is true, set the anchor of the range to the end instead of the start. * If primary is true, this is the primary selection. Behavior is undefined if more than * one selection has primary set to true. If none has primary set to true, the last one is primary. * @param {boolean} center true to center the viewport around the primary selection. * @param {number} centerOptions Option value, or 0 for no options; one of the BOUNDARY_* constants above. * @param {?string} origin An optional string that describes what other selection or edit operations this * should be merged with for the purposes of undo. See {@link Document#replaceRange} for more details. */ Editor.prototype.setSelections = function (selections, center, centerOptions, origin) { var primIndex = selections.length - 1, options; if (origin) { options = { origin: origin }; } this._codeMirror.setSelections(_.map(selections, function (sel, index) { if (sel.primary) { primIndex = index; } return { anchor: sel.reversed ? sel.end : sel.start, head: sel.reversed ? sel.start : sel.end }; }), primIndex, options); if (center) { this.centerOnCursor(centerOptions); } }; /** * Sets the editors overwrite mode state. If null is passed, the state is toggled. * * @param {?boolean} start */ Editor.prototype.toggleOverwrite = function (state) { this._codeMirror.toggleOverwrite(state); }; /** * Selects word that the given pos lies within or adjacent to. If pos isn't touching a word * (e.g. within a token like "//"), moves the cursor to pos without selecting a range. * @param {!{line:number, ch:number}} */ Editor.prototype.selectWordAt = function (pos) { var word = this._codeMirror.findWordAt(pos); this.setSelection(word.anchor, word.head); }; /** * Gets the total number of lines in the the document (includes lines not visible in the viewport) * @return {!number} */ Editor.prototype.lineCount = function () { return this._codeMirror.lineCount(); }; /** * Deterines if line is fully visible. * @param {number} zero-based index of the line to test * @return {boolean} true if the line is fully visible, false otherwise */ Editor.prototype.isLineVisible = function (line) { var coords = this._codeMirror.charCoords({line: line, ch: 0}, "local"), scrollInfo = this._codeMirror.getScrollInfo(), top = scrollInfo.top, bottom = scrollInfo.top + scrollInfo.clientHeight; // Check top and bottom and return false for partially visible lines. return (coords.top >= top && coords.bottom <= bottom); }; /** * Gets the number of the first visible line in the editor. * @return {number} The 0-based index of the first visible line. */ Editor.prototype.getFirstVisibleLine = function () { return (this._visibleRange ? this._visibleRange.startLine : 0); }; /** * Gets the number of the last visible line in the editor. * @return {number} The 0-based index of the last visible line. */ Editor.prototype.getLastVisibleLine = function () { return (this._visibleRange ? this._visibleRange.endLine : this.lineCount() - 1); }; /* Hides the specified line number in the editor * @param {!from} line to start hiding from (inclusive) * @param {!to} line to end hiding at (exclusive) * @return {TextMarker} The CodeMirror mark object that's hiding the lines */ Editor.prototype._hideLines = function (from, to) { if (to <= from) { return; } // We set clearWhenEmpty: false so that if there's a blank line at the beginning or end of // the document, and that's the only hidden line, we can still actually hide it. Doing so // requires us to create a 0-length marked span, which would ordinarily be cleaned up by CM // if clearWithEmpty is true. See https://groups.google.com/forum/#!topic/codemirror/RB8VNF8ow2w var value = this._codeMirror.markText( {line: from, ch: 0}, {line: to - 1, ch: this._codeMirror.getLine(to - 1).length}, {collapsed: true, inclusiveLeft: true, inclusiveRight: true, clearWhenEmpty: false} ); return value; }; /** * Gets the total height of the document in pixels (not the viewport) * @return {!number} height in pixels */ Editor.prototype.totalHeight = function () { return this.getScrollerElement().scrollHeight; }; /** * Gets the scroller element from the editor. * @return {!HTMLDivElement} scroller */ Editor.prototype.getScrollerElement = function () { return this._codeMirror.getScrollerElement(); }; /** * Gets the root DOM node of the editor. * @return {!HTMLDivElement} The editor's root DOM node. */ Editor.prototype.getRootElement = function () { return this._codeMirror.getWrapperElement(); }; /** * Gets the lineSpace element within the editor (the container around the individual lines of code). * FUTURE: This is fairly CodeMirror-specific. Logic that depends on this may break if we switch * editors. * @return {!HTMLDivElement} The editor's lineSpace element. */ Editor.prototype._getLineSpaceElement = function () { return $(".CodeMirror-lines", this.getScrollerElement()).children().get(0); }; /** * Returns the current scroll position of the editor. * @return {{x:number, y:number}} The x,y scroll position in pixels */ Editor.prototype.getScrollPos = function () { var scrollInfo = this._codeMirror.getScrollInfo(); return { x: scrollInfo.left, y: scrollInfo.top }; }; /** * Restores and adjusts the current scroll position of the editor. * @param {{x:number, y:number}} scrollPos - The x,y scroll position in pixels * @param {!number} heightDelta - The amount of delta H to apply to the scroll position */ Editor.prototype.adjustScrollPos = function (scrollPos, heightDelta) { this._codeMirror.scrollTo(scrollPos.x, scrollPos.y + heightDelta); }; /** * Sets the current scroll position of the editor. * @param {number} x scrollLeft position in pixels * @param {number} y scrollTop position in pixels */ Editor.prototype.setScrollPos = function (x, y) { this._codeMirror.scrollTo(x, y); }; /* * Returns the current text height of the editor. * @return {number} Height of the text in pixels */ Editor.prototype.getTextHeight = function () { return this._codeMirror.defaultTextHeight(); }; /** * Adds an inline widget below the given line. If any inline widget was already open for that * line, it is closed without warning. * @param {!{line:number, ch:number}} pos Position in text to anchor the inline. * @param {!InlineWidget} inlineWidget The widget to add. * @param {boolean=} scrollLineIntoView Scrolls the associated line into view. Default true. * @return {$.Promise} A promise object that is resolved when the widget has been added (but might * still be animating open). Never rejected. */ Editor.prototype.addInlineWidget = function (pos, inlineWidget, scrollLineIntoView) { var self = this, queue = this._inlineWidgetQueues[pos.line], deferred = new $.Deferred(); if (!queue) { queue = new Async.PromiseQueue(); this._inlineWidgetQueues[pos.line] = queue; } queue.add(function () { self._addInlineWidgetInternal(pos, inlineWidget, scrollLineIntoView, deferred); return deferred.promise(); }); return deferred.promise(); }; /** * @private * Does the actual work of addInlineWidget(). */ Editor.prototype._addInlineWidgetInternal = function (pos, inlineWidget, scrollLineIntoView, deferred) { var self = this; this.removeAllInlineWidgetsForLine(pos.line).done(function () { if (scrollLineIntoView === undefined) { scrollLineIntoView = true; } if (scrollLineIntoView) { self._codeMirror.scrollIntoView(pos); } inlineWidget.info = self._codeMirror.addLineWidget(pos.line, inlineWidget.htmlContent, { coverGutter: true, noHScroll: true }); CodeMirror.on(inlineWidget.info.line, "delete", function () { self._removeInlineWidgetInternal(inlineWidget); }); self._inlineWidgets.push(inlineWidget); // Set up the widget to start closed, then animate open when its initial height is set. inlineWidget.$htmlContent.height(0); AnimationUtils.animateUsingClass(inlineWidget.htmlContent, "animating") .done(function () { deferred.resolve(); }); // Callback to widget once parented to the editor. The widget should call back to // setInlineWidgetHeight() in order to set its initial height and animate open. inlineWidget.onAdded(); }); }; /** * Removes all inline widgets */ Editor.prototype.removeAllInlineWidgets = function () { // copy the array because _removeInlineWidgetInternal will modify the original var widgets = [].concat(this.getInlineWidgets()); return Async.doInParallel( widgets, this.removeInlineWidget.bind(this) ); }; /** * Removes the given inline widget. * @param {number} inlineWidget The widget to remove. * @return {$.Promise} A promise that is resolved when the inline widget is fully closed and removed from the DOM. */ Editor.prototype.removeInlineWidget = function (inlineWidget) { var deferred = new $.Deferred(), self = this; function finishRemoving() { self._codeMirror.removeLineWidget(inlineWidget.info); self._removeInlineWidgetInternal(inlineWidget); deferred.resolve(); } if (!inlineWidget.closePromise) { // Remove the inline widget from our internal list immediately, so // everyone external to us knows it's essentially already gone. We // don't want to wait until it's done animating closed (but we do want // the other stuff in _removeInlineWidgetInternal to wait until then). self._removeInlineWidgetFromList(inlineWidget); // If we're not visible (in which case the widget will have 0 client height), // don't try to do the animation, because nothing will happen and we won't get // called back right away. (The animation would happen later when we switch // back to the editor.) if (self.isFullyVisible()) { AnimationUtils.animateUsingClass(inlineWidget.htmlContent, "animating") .done(finishRemoving); inlineWidget.$htmlContent.height(0); } else { finishRemoving(); } inlineWidget.closePromise = deferred.promise(); } return inlineWidget.closePromise; }; /** * Removes all inline widgets for a given line * @param {number} lineNum The line number to modify */ Editor.prototype.removeAllInlineWidgetsForLine = function (lineNum) { var lineInfo = this._codeMirror.lineInfo(lineNum), widgetInfos = (lineInfo && lineInfo.widgets) ? [].concat(lineInfo.widgets) : null, self = this; if (widgetInfos && widgetInfos.length) { // Map from CodeMirror LineWidget to Brackets InlineWidget var inlineWidget, allWidgetInfos = this._inlineWidgets.map(function (w) { return w.info; }); return Async.doInParallel( widgetInfos, function (info) { // Lookup the InlineWidget object using the same index inlineWidget = self._inlineWidgets[allWidgetInfos.indexOf(info)]; if (inlineWidget) { return self.removeInlineWidget(inlineWidget); } else { return new $.Deferred().resolve().promise(); } } ); } else { return new $.Deferred().resolve().promise(); } }; /** * Cleans up the given inline widget from our internal list of widgets. It's okay * to call this multiple times for the same widget--it will just do nothing if * the widget has already been removed. * @param {InlineWidget} inlineWidget an inline widget. */ Editor.prototype._removeInlineWidgetFromList = function (inlineWidget) { var l = this._inlineWidgets.length, i; for (i = 0; i < l; i++) { if (this._inlineWidgets[i] === inlineWidget) { this._inlineWidgets.splice(i, 1); break; } } }; /** * Removes the inline widget from the editor and notifies it to clean itself up. * @param {InlineWidget} inlineWidget an inline widget. */ Editor.prototype._removeInlineWidgetInternal = function (inlineWidget) { if (!inlineWidget.isClosed) { this._removeInlineWidgetFromList(inlineWidget); inlineWidget.onClosed(); inlineWidget.isClosed = true; } }; /** * Returns a list of all inline widgets currently open in this editor. Each entry contains the * inline's id, and the data parameter that was passed to addInlineWidget(). * @return {!Array.<{id:number, data:Object}>} */ Editor.prototype.getInlineWidgets = function () { return this._inlineWidgets; }; /** * Returns the currently focused inline widget, if any. * @return {?InlineWidget} */ Editor.prototype.getFocusedInlineWidget = function () { var result = null; this.getInlineWidgets().forEach(function (widget) { if (widget.hasFocus()) { result = widget; } }); return result; }; /** * Display temporary popover message at current cursor position. Display message above * cursor if space allows, otherwise below. * * @param {string} errorMsg Error message to display */ Editor.prototype.displayErrorMessageAtCursor = function (errorMsg) { var arrowBelow, cursorPos, cursorCoord, popoverRect, top, left, clip, arrowCenter, arrowLeft, self = this, POPOVER_MARGIN = 10, POPOVER_ARROW_HALF_WIDTH = 10, POPOVER_ARROW_HALF_BASE = POPOVER_ARROW_HALF_WIDTH + 3; // 3 is border radius function _removeListeners() { self.off(".msgbox"); } // PopUpManager.removePopUp() callback function _clearMessagePopover() { if (self._$messagePopover && self._$messagePopover.length > 0) { // self._$messagePopover.remove() is done by PopUpManager self._$messagePopover = null; } _removeListeners(); } // PopUpManager.removePopUp() is called either directly by this closure, or by // PopUpManager as a result of another popup being invoked. function _removeMessagePopover() { if (self._$messagePopover) { PopUpManager.removePopUp(self._$messagePopover); } } function _addListeners() { self .on("blur.msgbox", _removeMessagePopover) .on("change.msgbox", _removeMessagePopover) .on("cursorActivity.msgbox", _removeMessagePopover) .on("update.msgbox", _removeMessagePopover); } // Only 1 message at a time if (this._$messagePopover) { _removeMessagePopover(); } // Make sure cursor is in view cursorPos = this.getCursorPos(); this._codeMirror.scrollIntoView(cursorPos); // Determine if arrow is above or below cursorCoord = this._codeMirror.charCoords(cursorPos); // Assume popover height is max of 2 lines arrowBelow = (cursorCoord.top > 100); // Text is dynamic, so build popover first so we can measure final width this._$messagePopover = $("<div/>").addClass("popover-message").appendTo($("body")); if (!arrowBelow) { $("<div/>").addClass("arrowAbove").appendTo(this._$messagePopover); } $("<div/>").addClass("text").appendTo(this._$messagePopover).html(errorMsg); if (arrowBelow) { $("<div/>").addClass("arrowBelow").appendTo(this._$messagePopover); } // Estimate where to position popover. top = (arrowBelow) ? cursorCoord.top - this._$messagePopover.height() - POPOVER_MARGIN : cursorCoord.bottom + POPOVER_MARGIN; left = cursorCoord.left - (this._$messagePopover.width() / 2); popoverRect = { top: top, left: left, height: this._$messagePopover.height(), width: this._$messagePopover.width() }; // See if popover is clipped on any side clip = ViewUtils.getElementClipSize($("#editor-holder"), popoverRect); // Prevent horizontal clipping if (clip.left > 0) { left += clip.left; } else if (clip.right > 0) { left -= clip.right; } // Popover text and arrow are positioned individually this._$messagePopover.css({"top": top, "left": left}); // Position popover arrow centered over/under cursor... arrowCenter = cursorCoord.left - left; // ... but don't let it slide off text box arrowCenter = Math.min(popoverRect.width - POPOVER_ARROW_HALF_BASE, Math.max(arrowCenter, POPOVER_ARROW_HALF_BASE)); arrowLeft = arrowCenter - POPOVER_ARROW_HALF_WIDTH; if (arrowBelow) { this._$messagePopover.find(".arrowBelow").css({"margin-left": arrowLeft}); } else { this._$messagePopover.find(".arrowAbove").css({"margin-left": arrowLeft}); } // Add listeners PopUpManager.addPopUp(this._$messagePopover, _clearMessagePopover, true); _addListeners(); // Animate open AnimationUtils.animateUsingClass(this._$messagePopover[0], "animateOpen").done(function () { // Make sure we still have a popover if (self._$messagePopover && self._$messagePopover.length > 0) { self._$messagePopover.addClass("open"); // Don't add scroll listeners until open so we don't get event // from scrolling cursor into view self.on("scroll.msgbox", _removeMessagePopover); // Animate closed -- which includes delay to show message AnimationUtils.animateUsingClass(self._$messagePopover[0], "animateClose", 6000) .done(_removeMessagePopover); } }); }; /** * Returns the offset of the top of the virtual scroll area relative to the browser window (not the editor * itself). Mainly useful for calculations related to scrollIntoView(), where you're starting with the * offset() of a child widget (relative to the browser window) and need to figure out how far down it is from * the top of the virtual scroll area (excluding the top padding). * @return {number} */ Editor.prototype.getVirtualScrollAreaTop = function () { var topPadding = this._getLineSpaceElement().offsetTop, // padding within mover scroller = this.getScrollerElement(); return $(scroller).offset().top - scroller.scrollTop + topPadding; }; /** * Sets the height of an inline widget in this editor. * @param {!InlineWidget} inlineWidget The widget whose height should be set. * @param {!number} height The height of the widget. * @param {boolean=} ensureVisible Whether to scroll the entire widget into view. Default false. */ Editor.prototype.setInlineWidgetHeight = function (inlineWidget, height, ensureVisible) { var self = this, node = inlineWidget.htmlContent, oldHeight = (node && $(node).height()) || 0, changed = (oldHeight !== height), isAttached = inlineWidget.info !== undefined; function updateHeight() { // Notify CodeMirror for the height change. if (isAttached) { inlineWidget.info.changed(); } } function setOuterHeight() { function finishAnimating(e) { if (e.target === node) { updateHeight(); $(node).off("webkitTransitionEnd", finishAnimating); } } $(node).height(height); if ($(node).hasClass("animating")) { $(node).on("webkitTransitionEnd", finishAnimating); } else { updateHeight(); } } // Make sure we set an explicit height on the widget, so children can use things like // min-height if they want. if (changed || !node.style.height) { // If we're animating, set the wrapper's height on a timeout so the layout is finished before we animate. if ($(node).hasClass("animating")) { window.setTimeout(setOuterHeight, 0); } else { setOuterHeight(); } } if (ensureVisible && isAttached) { var offset = $(node).offset(), // offset relative to document position = $(node).position(), // position within parent linespace scrollerTop = self.getVirtualScrollAreaTop(); self._codeMirror.scrollIntoView({ left: position.left, top: offset.top - scrollerTop, right: position.left, // don't try to make the right edge visible bottom: offset.top + height - scrollerTop }); } }; /** * @private * Get the starting line number for an inline widget. * @param {!InlineWidget} inlineWidget * @return {number} The line number of the widget or -1 if not found. */ Editor.prototype._getInlineWidgetLineNumber = function (inlineWidget) { return this._codeMirror.getLineNumber(inlineWidget.info.line); }; /** Gives focus to the editor control */ Editor.prototype.focus = function () { // Focusing an editor synchronously triggers focus/blur handlers. If a blur handler attemps to focus // another editor, we'll put CM in a bad state (because CM assumes programmatically focusing itself // will always succeed, and if you're in the middle of another focus change that appears to be untrue). // So instead, we simply ignore reentrant focus attempts. // See bug #2951 for an example of this happening and badly hosing things. if (_duringFocus) { return; } _duringFocus = true; try { this._codeMirror.focus(); } finally { _duringFocus = false; } }; /** Returns true if the editor has focus */ Editor.prototype.hasFocus = function () { return this._focused; }; /* * @typedef {scrollPos:{x:number, y:number},Array.<{start:{line:number, ch:number},end:{line:number, ch:number}}>} EditorViewState */ /* * returns the view state for the editor * @return {!EditorViewState} */ Editor.prototype.getViewState = function () { return { selections: this.getSelections(), scrollPos: this.getScrollPos() }; }; /* * Restores the view state * @param {!EditorViewState} viewState - the view state object to restore */ Editor.prototype.restoreViewState = function (viewState) { if (viewState.selection) { // We no longer write out single-selection, but there might be some view state // from an older version. this.setSelection(viewState.selection.start, viewState.selection.end); } if (viewState.selections) { this.setSelections(viewState.selections); } if (viewState.scrollPos) { this.setScrollPos(viewState.scrollPos.x, viewState.scrollPos.y); } }; /** * Re-renders the editor UI * @param {boolean=} handleResize true if this is in response to resizing the editor. Default false. */ Editor.prototype.refresh = function (handleResize) { // If focus is currently in a child of the CodeMirror editor (e.g. in an inline widget), but not in // the CodeMirror input field itself, remember the focused item so we can restore focus after the // refresh (which might cause the widget to be removed from the display list temporarily). var focusedItem = window.document.activeElement, restoreFocus = $.contains(this._codeMirror.getScrollerElement(), focusedItem); this._codeMirror.refresh(); if (restoreFocus) { focusedItem.focus(); } }; /** * Re-renders the editor, and all children inline editors. * @param {boolean=} handleResize true if this is in response to resizing the editor. Default false. */ Editor.prototype.refreshAll = function (handleResize) { this.refresh(handleResize); this.getInlineWidgets().forEach(function (inlineWidget) { inlineWidget.refresh(); }); }; /** Undo the last edit. */ Editor.prototype.undo = function () { this._codeMirror.undo(); }; /** Redo the last un-done edit. */ Editor.prototype.redo = function () { this._codeMirror.redo(); }; /** * View API Visibility Change Notification handler. This is also * called by the native "setVisible" API which refresh can be optimized * @param {boolean} show true to show the editor, false to hide it * @param {boolean} refresh true (default) to refresh the editor, false to skip refreshing it */ Editor.prototype.notifyVisibilityChange = function (show, refresh) { if (show && (refresh || refresh === undefined)) { this.refresh(); } if (show) { this._inlineWidgets.forEach(function (inlineWidget) { inlineWidget.onParentShown(); }); } }; /** * Shows or hides the editor within its parent. Does not force its ancestors to * become visible. * @param {boolean} show true to show the editor, false to hide it * @param {boolean} refresh true (default) to refresh the editor, false to skip refreshing it */ Editor.prototype.setVisible = function (show, refresh) { this.$el.css("display", (show ? "" : "none")); this.notifyVisibilityChange(show, refresh); }; /** * Returns true if the editor is fully visible--i.e., is in the DOM, all ancestors are * visible, and has a non-zero width/height. */ Editor.prototype.isFullyVisible = function () { return $(this.getRootElement()).is(":visible"); }; /** * Gets the syntax-highlighting mode for the given range. * Returns null if the mode at the start of the selection differs from the mode at the end - * an *approximation* of whether the mode is consistent across the whole range (a pattern like * A-B-A would return A as the mode, not null). * * @param {!{line: number, ch: number}} start The start of the range to check. * @param {!{line: number, ch: number}} end The end of the range to check. * @param {boolean=} knownMixed Whether we already know we're in a mixed mode and need to check both * the start and end. * @return {?(Object|string)} Name of syntax-highlighting mode, or object containing a "name" property * naming the mode along with configuration options required by the mode. * @see {@link LanguageManager::#getLanguageForPath} and {@link LanguageManager::Language#getMode}. */ Editor.prototype.getModeForRange = function (start, end, knownMixed) { var outerMode = this._codeMirror.getMode(), startMode = TokenUtils.getModeAt(this._codeMirror, start), endMode = TokenUtils.getModeAt(this._codeMirror, end); if (!knownMixed && outerMode.name === startMode.name) { // Mode does not vary: just use the editor-wide mode name return this._codeMirror.getOption("mode"); } else if (!startMode || !endMode || startMode.name !== endMode.name) { return null; } else { return startMode; } }; /** * Gets the syntax-highlighting mode for the current selection or cursor position. (The mode may * vary within one file due to embedded languages, e.g. JS embedded in an HTML script block). See * `getModeForRange()` for how this is determined for a single selection. * * If there are multiple selections, this will return a mode only if all the selections are individually * consistent and resolve to the same mode. * * @return {?(Object|string)} Name of syntax-highlighting mode, or object containing a "name" property * naming the mode along with configuration options required by the mode. * @see {@link LanguageManager::#getLanguageForPath} and {@link LanguageManager::Language#getMode}. */ Editor.prototype.getModeForSelection = function () { // Check for mixed mode info var self = this, sels = this.getSelections(), primarySel = this.getSelection(), outerMode = this._codeMirror.getMode(), startMode = TokenUtils.getModeAt(this._codeMirror, primarySel.start), isMixed = (outerMode.name !== startMode.name); if (isMixed) { // Shortcut the first check to avoid getModeAt(), which can be expensive if (primarySel.start.line !== primarySel.end.line || primarySel.start.ch !== primarySel.end.ch) { var endMode = TokenUtils.getModeAt(this._codeMirror, primarySel.end); if (startMode.name !== endMode.name) { return null; } } // If mixed mode, check that mode is the same at start & end of each selection var hasMixedSel = _.some(sels, function (sel) { if (sels === primarySel) { // We already checked this before, so we know it's not mixed. return false; } var rangeMode = self.getModeForRange(sel.start, sel.end, true); return (!rangeMode || rangeMode.name !== startMode.name); }); if (hasMixedSel) { return null; } return startMode.name; } else { // Mode does not vary: just use the editor-wide mode return this._codeMirror.getOption("mode"); } }; /* * gets the language for the selection. (Javascript selected from an HTML document or CSS selected from an HTML document, etc...) * @return {!Language} */ Editor.prototype.getLanguageForSelection = function () { return this.document.getLanguage().getLanguageForMode(this.getModeForSelection()); }; /** * Gets the syntax-highlighting mode for the document. * * @return {Object|String} Object or Name of syntax-highlighting mode * @see {@link LanguageManager::#getLanguageForPath|LanguageManager.getLanguageForPath} and {@link LanguageManager::Language#getMode|Language.getMode}. */ Editor.prototype.getModeForDocument = function () { return this._codeMirror.getOption("mode"); }; /** * The Document we're bound to * @type {!Document} */ Editor.prototype.document = null; /** * The Editor's last known width. * Used in conjunction with updateLayout to recompute the layout * if the the parent container changes its size since our last layout update. * @type {?number} */ Editor.prototype._lastEditorWidth = null; /** * If true, we're in the middle of syncing to/from the Document. Used to ignore spurious change * events caused by us (vs. change events caused by others, which we need to pay attention to). * @type {!boolean} */ Editor.prototype._duringSync = false; /** * @private * NOTE: this is actually "semi-private": EditorManager also accesses this field... as well as * a few other modules. However, we should try to gradually move most code away from talking to * CodeMirror directly. * @type {!CodeMirror} */ Editor.prototype._codeMirror = null; /** * @private * @type {!Array.<{id:number, data:Object}>} */ Editor.prototype._inlineWidgets = null; /** * @private * @type {?TextRange} */ Editor.prototype._visibleRange = null; /** * @private * @type {Object} * Promise queues for inline widgets being added to a given line. */ Editor.prototype._inlineWidgetQueues = null; /** * @private * @type {Array} * A list of objects corresponding to the markers that are hiding lines in the current editor. */ Editor.prototype._hideMarks = null; /** * @private * * Retrieve the value of the named preference for this document. * * @param {string} prefName Name of preference to retrieve. * @return {*} current value of that pref */ Editor.prototype._getOption = function (prefName) { return PreferencesManager.get(prefName, PreferencesManager._buildContext(this.document.file.fullPath, this.document.getLanguage().getId())); }; /** * @private * * Updates the editor to the current value of prefName for the file being edited. * * @param {string} prefName Name of the preference to visibly update */ Editor.prototype._updateOption = function (prefName) { var oldValue = this._currentOptions[prefName], newValue = this._getOption(prefName); if (oldValue !== newValue) { this._currentOptions[prefName] = newValue; if (prefName === USE_TAB_CHAR) { this._codeMirror.setOption(cmOptions[prefName], newValue); this._codeMirror.setOption("indentUnit", newValue === true ? this._currentOptions[TAB_SIZE] : this._currentOptions[SPACE_UNITS] ); } else if (prefName === STYLE_ACTIVE_LINE) { this._updateStyleActiveLine(); } else if (prefName === SCROLL_PAST_END && this._visibleRange) { // Do not apply this option to inline editors return; } else if (prefName === SHOW_LINE_NUMBERS) { Editor._toggleLinePadding(!newValue); this._codeMirror.setOption(cmOptions[SHOW_LINE_NUMBERS], newValue); this.refreshAll(); } else { this._codeMirror.setOption(cmOptions[prefName], newValue); } this.trigger("optionChange", prefName, newValue); } }; /** * @private * * Used to ensure that "style active line" is turned off when there is a selection. */ Editor.prototype._updateStyleActiveLine = function () { if (this.hasSelection()) { if (this._codeMirror.getOption("styleActiveLine")) { this._codeMirror.setOption("styleActiveLine", false); } } else { this._codeMirror.setOption("styleActiveLine", this._currentOptions[STYLE_ACTIVE_LINE]); } }; /** * resizes the editor to fill its parent container * should not be used on inline editors * @param {boolean=} forceRefresh - forces the editor to update its layout * even if it already matches the container's height / width */ Editor.prototype.updateLayout = function (forceRefresh) { var curRoot = this.getRootElement(), curWidth = $(curRoot).width(), $editorHolder = this.$el.parent(), editorAreaHt = $editorHolder.height(); if (!curRoot.style.height || $(curRoot).height() !== editorAreaHt) { // Call setSize() instead of $.height() to allow CodeMirror to // check for options like line wrapping this.setSize(null, editorAreaHt); if (forceRefresh === undefined) { forceRefresh = true; } } else if (curWidth !== this._lastEditorWidth) { if (forceRefresh === undefined) { forceRefresh = true; } } this._lastEditorWidth = curWidth; if (forceRefresh) { this.refreshAll(forceRefresh); } }; // Global settings that affect Editor instances that share the same preference locations /** * Sets whether to use tab characters (vs. spaces) when inserting new text. * Affects any editors that share the same preference location. * @param {boolean} value * @param {string=} fullPath Path to file to get preference for * @return {boolean} true if value was valid */ Editor.setUseTabChar = function (value, fullPath) { var options = fullPath && {context: fullPath}; return PreferencesManager.set(USE_TAB_CHAR, value, options); }; /** * Gets whether the specified or current file uses tab characters (vs. spaces) when inserting new text * @param {string=} fullPath Path to file to get preference for * @return {boolean} */ Editor.getUseTabChar = function (fullPath) { return PreferencesManager.get(USE_TAB_CHAR, _buildPreferencesContext(fullPath)); }; /** * Sets tab character width. * Affects any editors that share the same preference location. * @param {number} value * @param {string=} fullPath Path to file to get preference for * @return {boolean} true if value was valid */ Editor.setTabSize = function (value, fullPath) { var options = fullPath && {context: fullPath}; return PreferencesManager.set(TAB_SIZE, value, options); }; /** * Get indent unit * @param {string=} fullPath Path to file to get preference for * @return {number} */ Editor.getTabSize = function (fullPath) { return PreferencesManager.get(TAB_SIZE, _buildPreferencesContext(fullPath)); }; /** * Sets indentation width. * Affects any editors that share the same preference location. * @param {number} value * @param {string=} fullPath Path to file to get preference for * @return {boolean} true if value was valid */ Editor.setSpaceUnits = function (value, fullPath) { var options = fullPath && {context: fullPath}; return PreferencesManager.set(SPACE_UNITS, value, options); }; /** * Get indentation width * @param {string=} fullPath Path to file to get preference for * @return {number} */ Editor.getSpaceUnits = function (fullPath) { return PreferencesManager.get(SPACE_UNITS, _buildPreferencesContext(fullPath)); }; /** * Sets the auto close brackets. * Affects any editors that share the same preference location. * @param {boolean} value * @param {string=} fullPath Path to file to get preference for * @return {boolean} true if value was valid */ Editor.setCloseBrackets = function (value, fullPath) { var options = fullPath && {context: fullPath}; return PreferencesManager.set(CLOSE_BRACKETS, value, options); }; /** * Gets whether the specified or current file uses auto close brackets * @param {string=} fullPath Path to file to get preference for * @return {boolean} */ Editor.getCloseBrackets = function (fullPath) { return PreferencesManager.get(CLOSE_BRACKETS, _buildPreferencesContext(fullPath)); }; /** * Sets show line numbers option. * Affects any editors that share the same preference location. * @param {boolean} value * @param {string=} fullPath Path to file to get preference for * @return {boolean} true if value was valid */ Editor.setShowLineNumbers = function (value, fullPath) { var options = fullPath && {context: fullPath}; return PreferencesManager.set(SHOW_LINE_NUMBERS, value, options); }; /** * Returns true if show line numbers is enabled for the specified or current file * @param {string=} fullPath Path to file to get preference for * @return {boolean} */ Editor.getShowLineNumbers = function (fullPath) { return PreferencesManager.get(SHOW_LINE_NUMBERS, _buildPreferencesContext(fullPath)); }; /** * Sets show active line option. * Affects any editors that share the same preference location. * @param {boolean} value * @param {string=} fullPath Path to file to get preference for * @return {boolean} true if value was valid */ Editor.setShowActiveLine = function (value, fullPath) { return PreferencesManager.set(STYLE_ACTIVE_LINE, value); }; /** * Returns true if show active line is enabled for the specified or current file * @param {string=} fullPath Path to file to get preference for * @return {boolean} */ Editor.getShowActiveLine = function (fullPath) { return PreferencesManager.get(STYLE_ACTIVE_LINE, _buildPreferencesContext(fullPath)); }; /** * Sets word wrap option. * Affects any editors that share the same preference location. * @param {boolean} value * @param {string=} fullPath Path to file to get preference for * @return {boolean} true if value was valid */ Editor.setWordWrap = function (value, fullPath) { var options = fullPath && {context: fullPath}; return PreferencesManager.set(WORD_WRAP, value, options); }; /** * Returns true if word wrap is enabled for the specified or current file * @param {string=} fullPath Path to file to get preference for * @return {boolean} */ Editor.getWordWrap = function (fullPath) { return PreferencesManager.get(WORD_WRAP, _buildPreferencesContext(fullPath)); }; /** * Runs callback for every Editor instance that currently exists * @param {!function(!Editor)} callback */ Editor.forEveryEditor = function (callback) { _instances.forEach(callback); }; /** * @private * Toggles the left padding of all code editors. Used to provide more * space between the code text and the left edge of the editor when * line numbers are hidden. * @param {boolean} showLinePadding */ Editor._toggleLinePadding = function (showLinePadding) { // apply class to all pane DOM nodes var $holders = []; _instances.forEach(function (editor) { var $editorHolder = editor.$el.parent(); if ($holders.indexOf($editorHolder) === -1) { $holders.push($editorHolder); } }); _.each($holders, function ($holder) { $holder.toggleClass("show-line-padding", Boolean(showLinePadding)); }); }; // Set up listeners for preference changes editorOptions.forEach(function (prefName) { PreferencesManager.on("change", prefName, function () { _instances.forEach(function (editor) { editor._updateOption(prefName); }); }); }); /** * @private * * Manage the conversion from old-style localStorage prefs to the new file-based ones. */ function _convertPreferences() { var rules = {}; editorOptions.forEach(function (setting) { rules[setting] = "user"; }); PreferencesManager.convertPreferences(module, rules); } _convertPreferences(); // Define public API exports.Editor = Editor; exports.BOUNDARY_CHECK_NORMAL = BOUNDARY_CHECK_NORMAL; exports.BOUNDARY_IGNORE_TOP = BOUNDARY_IGNORE_TOP; });
packages/material-ui-icons/src/RedeemSharp.js
Kagami/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><path d="M22 6h-4.18c.11-.31.18-.65.18-1 0-1.66-1.34-3-3-3-1.05 0-1.96.54-2.5 1.35l-.5.67-.5-.68C10.96 2.54 10.05 2 9 2 7.34 2 6 3.34 6 5c0 .35.07.69.18 1H2v15h20V6zm-7-2c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zM9 4c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zm11 15H4v-2h16v2zm0-5H4V8h5.08L7 10.83 8.62 12 12 7.4l3.38 4.6L17 10.83 14.92 8H20v6z" /></React.Fragment> , 'RedeemSharp');
src/Components/Map.js
jsconfcn/ningjs
import React, { Component } from 'react'; import { render } from 'react-dom'; import { Map, Marker, Popup, TileLayer } from 'react-leaflet'; const position = [32.06257,118.7781]; export default class MapComponent extends Component { render() { return ( <Map center={position} zoom={13}> <TileLayer url='http://{s}.tile.osm.org/{z}/{x}/{y}.png' attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors' /> <Marker position={position}> <Popup> <span><strong></strong><span>鼓楼区中央路1号(地铁1号线鼓楼站4A口出北行170米)</span> </Popup> </Marker> </Map> ) } }
test/ButtonGroupSpec.js
jontewks/react-bootstrap
import React from 'react'; import ReactTestUtils from 'react/lib/ReactTestUtils'; import ButtonGroup from '../src/ButtonGroup'; import Button from '../src/Button'; import { shouldWarn } from './helpers'; describe('ButtonGroup', function () { it('Should output a button group', function () { let instance = ReactTestUtils.renderIntoDocument( <ButtonGroup> <Button> Title </Button> </ButtonGroup> ); assert.equal(React.findDOMNode(instance).nodeName, 'DIV'); assert.ok(React.findDOMNode(instance).className.match(/\bbtn-group\b/)); }); it('Should add size', function () { let instance = ReactTestUtils.renderIntoDocument( <ButtonGroup bsSize='large'> <Button> Title </Button> </ButtonGroup> ); assert.ok(React.findDOMNode(instance).className.match(/\bbtn-group-lg\b/)); }); it('Should add vertical variation', function () { let instance = ReactTestUtils.renderIntoDocument( <ButtonGroup vertical> <Button> Title </Button> </ButtonGroup> ); assert.equal(React.findDOMNode(instance).className.trim(), 'btn-group-vertical'); }); it('Should add block variation', function () { let instance = ReactTestUtils.renderIntoDocument( <ButtonGroup vertical block> <Button> Title </Button> </ButtonGroup> ); assert.ok(React.findDOMNode(instance).className.match(/\bbtn-block\b/)); }); it('Should warn about block without vertical', function () { ReactTestUtils.renderIntoDocument( <ButtonGroup block> <Button> Title </Button> </ButtonGroup> ); shouldWarn('The block property requires the vertical property to be set to have any effect'); }); it('Should add justified variation', function () { let instance = ReactTestUtils.renderIntoDocument( <ButtonGroup justified> <Button> Title </Button> </ButtonGroup> ); assert.ok(React.findDOMNode(instance).className.match(/\bbtn-group-justified\b/)); }); });
src/components/LoginScreen/LoginScreen.js
z81/PolarOS_Next
import React, {Component, PropTypes} from 'react' import bgAnim from './bgAnim' import styles from './LoginScreen.scss' import { Button, Input } from '../../components/Elements' class LoginScreen extends Component { static propTypes = { children: PropTypes.any, onLogin: PropTypes.func }; constructor(props) { super(props) this.state = { isRegMode: false } } componentDidMount() { bgAnim('#login-screen') } _onSubmit() { this.props.onLogin({ login: this.refs.login.getValue(), pass: this.refs.pass.getValue() }) } render() { return ( <div id="login-screen" className={styles.screen}> <div className={styles.form}> <div> Логин: <Input ref="login" /> </div> <div> Пароль: <Input ref="pass" type="password"/> </div> <div style={{paddingTop: '10px'}}> <Button onClick={this._onSubmit.bind(this)} ptStyle="primary" text="Войти" /> </div> </div> </div>) } } export default LoginScreen
lavalab/html/node_modules/react-bootstrap/es/MediaListItem.js
LavaLabUSC/usclavalab.org
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils'; var MediaListItem = function (_React$Component) { _inherits(MediaListItem, _React$Component); function MediaListItem() { _classCallCheck(this, MediaListItem); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } MediaListItem.prototype.render = function render() { var _props = this.props, className = _props.className, props = _objectWithoutProperties(_props, ['className']); var _splitBsProps = splitBsProps(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = getClassSet(bsProps); return React.createElement('li', _extends({}, elementProps, { className: classNames(className, classes) })); }; return MediaListItem; }(React.Component); export default bsClass('media', MediaListItem);
ajax/libs/ionic/0.9.15-alpha/js/ionic.js
abbychau/cdnjs
/*! * Copyright 2013 Drifty Co. * http://drifty.com/ * * Ionic, v0.9.14 * A powerful HTML5 mobile app framework. * http://ionicframework.com/ * * By @maxlynch, @helloimben, @adamdbradley <3 * * Licensed under the MIT license. Please see LICENSE for more information. * */; // Create namespaces window.ionic = { controllers: {}, views: {}, version: '0.9.14' };; (function(ionic) { var bezierCoord = function (x,y) { if(!x) x=0; if(!y) y=0; return {x: x, y: y}; }; function B1(t) { return t*t*t; } function B2(t) { return 3*t*t*(1-t); } function B3(t) { return 3*t*(1-t)*(1-t); } function B4(t) { return (1-t)*(1-t)*(1-t); } ionic.Animator = { // Quadratic bezier solver getQuadraticBezier: function(percent,C1,C2,C3,C4) { var pos = new bezierCoord(); pos.x = C1.x*B1(percent) + C2.x*B2(percent) + C3.x*B3(percent) + C4.x*B4(percent); pos.y = C1.y*B1(percent) + C2.y*B2(percent) + C3.y*B3(percent) + C4.y*B4(percent); return pos; }, // Cubic bezier solver from https://github.com/arian/cubic-bezier (MIT) getCubicBezier: function(x1, y1, x2, y2, duration) { // Precision epsilon = (1000 / 60 / duration) / 4; var curveX = function(t){ var v = 1 - t; return 3 * v * v * t * x1 + 3 * v * t * t * x2 + t * t * t; }; var curveY = function(t){ var v = 1 - t; return 3 * v * v * t * y1 + 3 * v * t * t * y2 + t * t * t; }; var derivativeCurveX = function(t){ var v = 1 - t; return 3 * (2 * (t - 1) * t + v * v) * x1 + 3 * (- t * t * t + 2 * v * t) * x2; }; return function(t) { var x = t, t0, t1, t2, x2, d2, i; // First try a few iterations of Newton's method -- normally very fast. for (t2 = x, i = 0; i < 8; i++){ x2 = curveX(t2) - x; if (Math.abs(x2) < epsilon) return curveY(t2); d2 = derivativeCurveX(t2); if (Math.abs(d2) < 1e-6) break; t2 = t2 - x2 / d2; } t0 = 0, t1 = 1, t2 = x; if (t2 < t0) return curveY(t0); if (t2 > t1) return curveY(t1); // Fallback to the bisection method for reliability. while (t0 < t1){ x2 = curveX(t2); if (Math.abs(x2 - x) < epsilon) return curveY(t2); if (x > x2) t0 = t2; else t1 = t2; t2 = (t1 - t0) * 0.5 + t0; } // Failure return curveY(t2); }; }, animate: function(element, className, fn) { return { leave: function() { var endFunc = function() { element.classList.remove('leave'); element.classList.remove('leave-active'); element.removeEventListener('webkitTransitionEnd', endFunc); element.removeEventListener('transitionEnd', endFunc); }; element.addEventListener('webkitTransitionEnd', endFunc); element.addEventListener('transitionEnd', endFunc); element.classList.add('leave'); element.classList.add('leave-active'); return this; }, enter: function() { var endFunc = function() { element.classList.remove('enter'); element.classList.remove('enter-active'); element.removeEventListener('webkitTransitionEnd', endFunc); element.removeEventListener('transitionEnd', endFunc); }; element.addEventListener('webkitTransitionEnd', endFunc); element.addEventListener('transitionEnd', endFunc); element.classList.add('enter'); element.classList.add('enter-active'); return this; } }; } }; })(ionic); ; (function(ionic) { ionic.DomUtil = { getTextBounds: function(textNode) { if(document.createRange) { var range = document.createRange(); range.selectNodeContents(textNode); if(range.getBoundingClientRect) { var rect = range.getBoundingClientRect(); var sx = window.scrollX; var sy = window.scrollY; return { top: rect.top + sy, left: rect.left + sx, right: rect.left + sx + rect.width, bottom: rect.top + sy + rect.height, width: rect.width, height: rect.height }; } } return null; }, getChildIndex: function(element, type) { if(type) { var ch = element.parentNode.children; var c; for(var i = 0, k = 0, j = ch.length; i < j; i++) { c = ch[i]; if(c.nodeName && c.nodeName.toLowerCase() == type) { if(c == element) { return k; } k++; } } } return Array.prototype.slice.call(element.parentNode.children).indexOf(element); }, swapNodes: function(src, dest) { dest.parentNode.insertBefore(src, dest); }, /** * {returns} the closest parent matching the className */ getParentWithClass: function(e, className) { while(e.parentNode) { if(e.parentNode.classList && e.parentNode.classList.contains(className)) { return e.parentNode; } e = e.parentNode; } return null; }, /** * {returns} the closest parent or self matching the className */ getParentOrSelfWithClass: function(e, className) { while(e) { if(e.classList && e.classList.contains(className)) { return e; } e = e.parentNode; } return null; } }; })(window.ionic); ; /** * ion-events.js * * Author: Max Lynch <[email protected]> * * Framework events handles various mobile browser events, and * detects special events like tap/swipe/etc. and emits them * as custom events that can be used in an app. * * Portions lovingly adapted from github.com/maker/ratchet and github.com/alexgibson/tap.js - thanks guys! */ (function(ionic) { // Custom event polyfill if(!window.CustomEvent) { (function() { var CustomEvent; CustomEvent = function(event, params) { var evt; params = params || { bubbles: false, cancelable: false, detail: undefined }; evt = document.createEvent("CustomEvent"); evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail); return evt; }; CustomEvent.prototype = window.Event.prototype; window.CustomEvent = CustomEvent; })(); } ionic.EventController = { VIRTUALIZED_EVENTS: ['tap', 'swipe', 'swiperight', 'swipeleft', 'drag', 'hold', 'release'], // Trigger a new event trigger: function(eventType, data) { var event = new CustomEvent(eventType, { detail: data }); // Make sure to trigger the event on the given target, or dispatch it from // the window if we don't have an event target data && data.target && data.target.dispatchEvent(event) || window.dispatchEvent(event); }, // Bind an event on: function(type, callback, element) { var e = element || window; // Bind a gesture if it's a virtual event for(var i = 0, j = this.VIRTUALIZED_EVENTS.length; i < j; i++) { if(type == this.VIRTUALIZED_EVENTS[i]) { var gesture = new ionic.Gesture(element); gesture.on(type, callback); return gesture; } } // Otherwise bind a normal event e.addEventListener(type, callback); }, off: function(type, callback, element) { element.removeEventListener(type, callback); }, // Register for a new gesture event on the given element onGesture: function(type, callback, element) { var gesture = new ionic.Gesture(element); gesture.on(type, callback); return gesture; }, // Unregister a previous gesture event offGesture: function(gesture, type, callback) { gesture.off(type, callback); }, handlePopState: function(event) { }, }; // Map some convenient top-level functions for event handling ionic.on = function() { ionic.EventController.on.apply(ionic.EventController, arguments); }; ionic.off = function() { ionic.EventController.off.apply(ionic.EventController, arguments); }; ionic.trigger = ionic.EventController.trigger;//function() { ionic.EventController.trigger.apply(ionic.EventController.trigger, arguments); }; ionic.onGesture = function() { return ionic.EventController.onGesture.apply(ionic.EventController.onGesture, arguments); }; ionic.offGesture = function() { return ionic.EventController.offGesture.apply(ionic.EventController.offGesture, arguments); }; })(window.ionic); ; /** * Simple gesture controllers with some common gestures that emit * gesture events. * * Ported from github.com/EightMedia/ionic.Gestures.js - thanks! */ (function(ionic) { /** * ionic.Gestures * use this to create instances * @param {HTMLElement} element * @param {Object} options * @returns {ionic.Gestures.Instance} * @constructor */ ionic.Gesture = function(element, options) { return new ionic.Gestures.Instance(element, options || {}); }; ionic.Gestures = {}; // default settings ionic.Gestures.defaults = { // add styles and attributes to the element to prevent the browser from doing // its native behavior. this doesnt prevent the scrolling, but cancels // the contextmenu, tap highlighting etc // set to false to disable this stop_browser_behavior: { // this also triggers onselectstart=false for IE userSelect: 'none', // this makes the element blocking in IE10 >, you could experiment with the value // see for more options this issue; https://github.com/EightMedia/hammer.js/issues/241 touchAction: 'none', touchCallout: 'none', contentZooming: 'none', userDrag: 'none', tapHighlightColor: 'rgba(0,0,0,0)' } // more settings are defined per gesture at gestures.js }; // detect touchevents ionic.Gestures.HAS_POINTEREVENTS = window.navigator.pointerEnabled || window.navigator.msPointerEnabled; ionic.Gestures.HAS_TOUCHEVENTS = ('ontouchstart' in window); // dont use mouseevents on mobile devices ionic.Gestures.MOBILE_REGEX = /mobile|tablet|ip(ad|hone|od)|android|silk/i; ionic.Gestures.NO_MOUSEEVENTS = ionic.Gestures.HAS_TOUCHEVENTS && window.navigator.userAgent.match(ionic.Gestures.MOBILE_REGEX); // eventtypes per touchevent (start, move, end) // are filled by ionic.Gestures.event.determineEventTypes on setup ionic.Gestures.EVENT_TYPES = {}; // direction defines ionic.Gestures.DIRECTION_DOWN = 'down'; ionic.Gestures.DIRECTION_LEFT = 'left'; ionic.Gestures.DIRECTION_UP = 'up'; ionic.Gestures.DIRECTION_RIGHT = 'right'; // pointer type ionic.Gestures.POINTER_MOUSE = 'mouse'; ionic.Gestures.POINTER_TOUCH = 'touch'; ionic.Gestures.POINTER_PEN = 'pen'; // touch event defines ionic.Gestures.EVENT_START = 'start'; ionic.Gestures.EVENT_MOVE = 'move'; ionic.Gestures.EVENT_END = 'end'; // hammer document where the base events are added at ionic.Gestures.DOCUMENT = window.document; // plugins namespace ionic.Gestures.plugins = {}; // if the window events are set... ionic.Gestures.READY = false; /** * setup events to detect gestures on the document */ function setup() { if(ionic.Gestures.READY) { return; } // find what eventtypes we add listeners to ionic.Gestures.event.determineEventTypes(); // Register all gestures inside ionic.Gestures.gestures for(var name in ionic.Gestures.gestures) { if(ionic.Gestures.gestures.hasOwnProperty(name)) { ionic.Gestures.detection.register(ionic.Gestures.gestures[name]); } } // Add touch events on the document ionic.Gestures.event.onTouch(ionic.Gestures.DOCUMENT, ionic.Gestures.EVENT_MOVE, ionic.Gestures.detection.detect); ionic.Gestures.event.onTouch(ionic.Gestures.DOCUMENT, ionic.Gestures.EVENT_END, ionic.Gestures.detection.detect); // ionic.Gestures is ready...! ionic.Gestures.READY = true; } /** * create new hammer instance * all methods should return the instance itself, so it is chainable. * @param {HTMLElement} element * @param {Object} [options={}] * @returns {ionic.Gestures.Instance} * @constructor */ ionic.Gestures.Instance = function(element, options) { var self = this; // A null element was passed into the instance, which means // whatever lookup was done to find this element failed to find it // so we can't listen for events on it. if(element === null) { console.error('Null element passed to gesture (element does not exist). Not listening for gesture'); return; } // setup ionic.GesturesJS window events and register all gestures // this also sets up the default options setup(); this.element = element; // start/stop detection option this.enabled = true; // merge options this.options = ionic.Gestures.utils.extend( ionic.Gestures.utils.extend({}, ionic.Gestures.defaults), options || {}); // add some css to the element to prevent the browser from doing its native behavoir if(this.options.stop_browser_behavior) { ionic.Gestures.utils.stopDefaultBrowserBehavior(this.element, this.options.stop_browser_behavior); } // start detection on touchstart ionic.Gestures.event.onTouch(element, ionic.Gestures.EVENT_START, function(ev) { if(self.enabled) { ionic.Gestures.detection.startDetect(self, ev); } }); // return instance return this; }; ionic.Gestures.Instance.prototype = { /** * bind events to the instance * @param {String} gesture * @param {Function} handler * @returns {ionic.Gestures.Instance} */ on: function onEvent(gesture, handler){ var gestures = gesture.split(' '); for(var t=0; t<gestures.length; t++) { this.element.addEventListener(gestures[t], handler, false); } return this; }, /** * unbind events to the instance * @param {String} gesture * @param {Function} handler * @returns {ionic.Gestures.Instance} */ off: function offEvent(gesture, handler){ var gestures = gesture.split(' '); for(var t=0; t<gestures.length; t++) { this.element.removeEventListener(gestures[t], handler, false); } return this; }, /** * trigger gesture event * @param {String} gesture * @param {Object} eventData * @returns {ionic.Gestures.Instance} */ trigger: function triggerEvent(gesture, eventData){ // create DOM event var event = ionic.Gestures.DOCUMENT.createEvent('Event'); event.initEvent(gesture, true, true); event.gesture = eventData; // trigger on the target if it is in the instance element, // this is for event delegation tricks var element = this.element; if(ionic.Gestures.utils.hasParent(eventData.target, element)) { element = eventData.target; } element.dispatchEvent(event); return this; }, /** * enable of disable hammer.js detection * @param {Boolean} state * @returns {ionic.Gestures.Instance} */ enable: function enable(state) { this.enabled = state; return this; } }; /** * this holds the last move event, * used to fix empty touchend issue * see the onTouch event for an explanation * @type {Object} */ var last_move_event = null; /** * when the mouse is hold down, this is true * @type {Boolean} */ var enable_detect = false; /** * when touch events have been fired, this is true * @type {Boolean} */ var touch_triggered = false; ionic.Gestures.event = { /** * simple addEventListener * @param {HTMLElement} element * @param {String} type * @param {Function} handler */ bindDom: function(element, type, handler) { var types = type.split(' '); for(var t=0; t<types.length; t++) { element.addEventListener(types[t], handler, false); } }, /** * touch events with mouse fallback * @param {HTMLElement} element * @param {String} eventType like ionic.Gestures.EVENT_MOVE * @param {Function} handler */ onTouch: function onTouch(element, eventType, handler) { var self = this; this.bindDom(element, ionic.Gestures.EVENT_TYPES[eventType], function bindDomOnTouch(ev) { var sourceEventType = ev.type.toLowerCase(); // onmouseup, but when touchend has been fired we do nothing. // this is for touchdevices which also fire a mouseup on touchend if(sourceEventType.match(/mouse/) && touch_triggered) { return; } // mousebutton must be down or a touch event else if( sourceEventType.match(/touch/) || // touch events are always on screen sourceEventType.match(/pointerdown/) || // pointerevents touch (sourceEventType.match(/mouse/) && ev.which === 1) // mouse is pressed ){ enable_detect = true; } // mouse isn't pressed else if(sourceEventType.match(/mouse/) && ev.which !== 1) { enable_detect = false; } // we are in a touch event, set the touch triggered bool to true, // this for the conflicts that may occur on ios and android if(sourceEventType.match(/touch|pointer/)) { touch_triggered = true; } // count the total touches on the screen var count_touches = 0; // when touch has been triggered in this detection session // and we are now handling a mouse event, we stop that to prevent conflicts if(enable_detect) { // update pointerevent if(ionic.Gestures.HAS_POINTEREVENTS && eventType != ionic.Gestures.EVENT_END) { count_touches = ionic.Gestures.PointerEvent.updatePointer(eventType, ev); } // touch else if(sourceEventType.match(/touch/)) { count_touches = ev.touches.length; } // mouse else if(!touch_triggered) { count_touches = sourceEventType.match(/up/) ? 0 : 1; } // if we are in a end event, but when we remove one touch and // we still have enough, set eventType to move if(count_touches > 0 && eventType == ionic.Gestures.EVENT_END) { eventType = ionic.Gestures.EVENT_MOVE; } // no touches, force the end event else if(!count_touches) { eventType = ionic.Gestures.EVENT_END; } // store the last move event if(count_touches || last_move_event === null) { last_move_event = ev; } // trigger the handler handler.call(ionic.Gestures.detection, self.collectEventData(element, eventType, self.getTouchList(last_move_event, eventType), ev)); // remove pointerevent from list if(ionic.Gestures.HAS_POINTEREVENTS && eventType == ionic.Gestures.EVENT_END) { count_touches = ionic.Gestures.PointerEvent.updatePointer(eventType, ev); } } //debug(sourceEventType +" "+ eventType); // on the end we reset everything if(!count_touches) { last_move_event = null; enable_detect = false; touch_triggered = false; ionic.Gestures.PointerEvent.reset(); } }); }, /** * we have different events for each device/browser * determine what we need and set them in the ionic.Gestures.EVENT_TYPES constant */ determineEventTypes: function determineEventTypes() { // determine the eventtype we want to set var types; // pointerEvents magic if(ionic.Gestures.HAS_POINTEREVENTS) { types = ionic.Gestures.PointerEvent.getEvents(); } // on Android, iOS, blackberry, windows mobile we dont want any mouseevents else if(ionic.Gestures.NO_MOUSEEVENTS) { types = [ 'touchstart', 'touchmove', 'touchend touchcancel']; } // for non pointer events browsers and mixed browsers, // like chrome on windows8 touch laptop else { types = [ 'touchstart mousedown', 'touchmove mousemove', 'touchend touchcancel mouseup']; } ionic.Gestures.EVENT_TYPES[ionic.Gestures.EVENT_START] = types[0]; ionic.Gestures.EVENT_TYPES[ionic.Gestures.EVENT_MOVE] = types[1]; ionic.Gestures.EVENT_TYPES[ionic.Gestures.EVENT_END] = types[2]; }, /** * create touchlist depending on the event * @param {Object} ev * @param {String} eventType used by the fakemultitouch plugin */ getTouchList: function getTouchList(ev/*, eventType*/) { // get the fake pointerEvent touchlist if(ionic.Gestures.HAS_POINTEREVENTS) { return ionic.Gestures.PointerEvent.getTouchList(); } // get the touchlist else if(ev.touches) { return ev.touches; } // make fake touchlist from mouse position else { ev.indentifier = 1; return [ev]; } }, /** * collect event data for ionic.Gestures js * @param {HTMLElement} element * @param {String} eventType like ionic.Gestures.EVENT_MOVE * @param {Object} eventData */ collectEventData: function collectEventData(element, eventType, touches, ev) { // find out pointerType var pointerType = ionic.Gestures.POINTER_TOUCH; if(ev.type.match(/mouse/) || ionic.Gestures.PointerEvent.matchType(ionic.Gestures.POINTER_MOUSE, ev)) { pointerType = ionic.Gestures.POINTER_MOUSE; } return { center : ionic.Gestures.utils.getCenter(touches), timeStamp : new Date().getTime(), target : ev.target, touches : touches, eventType : eventType, pointerType : pointerType, srcEvent : ev, /** * prevent the browser default actions * mostly used to disable scrolling of the browser */ preventDefault: function() { if(this.srcEvent.preventManipulation) { this.srcEvent.preventManipulation(); } if(this.srcEvent.preventDefault) { //this.srcEvent.preventDefault(); } }, /** * stop bubbling the event up to its parents */ stopPropagation: function() { this.srcEvent.stopPropagation(); }, /** * immediately stop gesture detection * might be useful after a swipe was detected * @return {*} */ stopDetect: function() { return ionic.Gestures.detection.stopDetect(); } }; } }; ionic.Gestures.PointerEvent = { /** * holds all pointers * @type {Object} */ pointers: {}, /** * get a list of pointers * @returns {Array} touchlist */ getTouchList: function() { var self = this; var touchlist = []; // we can use forEach since pointerEvents only is in IE10 Object.keys(self.pointers).sort().forEach(function(id) { touchlist.push(self.pointers[id]); }); return touchlist; }, /** * update the position of a pointer * @param {String} type ionic.Gestures.EVENT_END * @param {Object} pointerEvent */ updatePointer: function(type, pointerEvent) { if(type == ionic.Gestures.EVENT_END) { this.pointers = {}; } else { pointerEvent.identifier = pointerEvent.pointerId; this.pointers[pointerEvent.pointerId] = pointerEvent; } return Object.keys(this.pointers).length; }, /** * check if ev matches pointertype * @param {String} pointerType ionic.Gestures.POINTER_MOUSE * @param {PointerEvent} ev */ matchType: function(pointerType, ev) { if(!ev.pointerType) { return false; } var types = {}; types[ionic.Gestures.POINTER_MOUSE] = (ev.pointerType == ev.MSPOINTER_TYPE_MOUSE || ev.pointerType == ionic.Gestures.POINTER_MOUSE); types[ionic.Gestures.POINTER_TOUCH] = (ev.pointerType == ev.MSPOINTER_TYPE_TOUCH || ev.pointerType == ionic.Gestures.POINTER_TOUCH); types[ionic.Gestures.POINTER_PEN] = (ev.pointerType == ev.MSPOINTER_TYPE_PEN || ev.pointerType == ionic.Gestures.POINTER_PEN); return types[pointerType]; }, /** * get events */ getEvents: function() { return [ 'pointerdown MSPointerDown', 'pointermove MSPointerMove', 'pointerup pointercancel MSPointerUp MSPointerCancel' ]; }, /** * reset the list */ reset: function() { this.pointers = {}; } }; ionic.Gestures.utils = { /** * extend method, * also used for cloning when dest is an empty object * @param {Object} dest * @param {Object} src * @parm {Boolean} merge do a merge * @returns {Object} dest */ extend: function extend(dest, src, merge) { for (var key in src) { if(dest[key] !== undefined && merge) { continue; } dest[key] = src[key]; } return dest; }, /** * find if a node is in the given parent * used for event delegation tricks * @param {HTMLElement} node * @param {HTMLElement} parent * @returns {boolean} has_parent */ hasParent: function(node, parent) { while(node){ if(node == parent) { return true; } node = node.parentNode; } return false; }, /** * get the center of all the touches * @param {Array} touches * @returns {Object} center */ getCenter: function getCenter(touches) { var valuesX = [], valuesY = []; for(var t= 0,len=touches.length; t<len; t++) { valuesX.push(touches[t].pageX); valuesY.push(touches[t].pageY); } return { pageX: ((Math.min.apply(Math, valuesX) + Math.max.apply(Math, valuesX)) / 2), pageY: ((Math.min.apply(Math, valuesY) + Math.max.apply(Math, valuesY)) / 2) }; }, /** * calculate the velocity between two points * @param {Number} delta_time * @param {Number} delta_x * @param {Number} delta_y * @returns {Object} velocity */ getVelocity: function getVelocity(delta_time, delta_x, delta_y) { return { x: Math.abs(delta_x / delta_time) || 0, y: Math.abs(delta_y / delta_time) || 0 }; }, /** * calculate the angle between two coordinates * @param {Touch} touch1 * @param {Touch} touch2 * @returns {Number} angle */ getAngle: function getAngle(touch1, touch2) { var y = touch2.pageY - touch1.pageY, x = touch2.pageX - touch1.pageX; return Math.atan2(y, x) * 180 / Math.PI; }, /** * angle to direction define * @param {Touch} touch1 * @param {Touch} touch2 * @returns {String} direction constant, like ionic.Gestures.DIRECTION_LEFT */ getDirection: function getDirection(touch1, touch2) { var x = Math.abs(touch1.pageX - touch2.pageX), y = Math.abs(touch1.pageY - touch2.pageY); if(x >= y) { return touch1.pageX - touch2.pageX > 0 ? ionic.Gestures.DIRECTION_LEFT : ionic.Gestures.DIRECTION_RIGHT; } else { return touch1.pageY - touch2.pageY > 0 ? ionic.Gestures.DIRECTION_UP : ionic.Gestures.DIRECTION_DOWN; } }, /** * calculate the distance between two touches * @param {Touch} touch1 * @param {Touch} touch2 * @returns {Number} distance */ getDistance: function getDistance(touch1, touch2) { var x = touch2.pageX - touch1.pageX, y = touch2.pageY - touch1.pageY; return Math.sqrt((x*x) + (y*y)); }, /** * calculate the scale factor between two touchLists (fingers) * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out * @param {Array} start * @param {Array} end * @returns {Number} scale */ getScale: function getScale(start, end) { // need two fingers... if(start.length >= 2 && end.length >= 2) { return this.getDistance(end[0], end[1]) / this.getDistance(start[0], start[1]); } return 1; }, /** * calculate the rotation degrees between two touchLists (fingers) * @param {Array} start * @param {Array} end * @returns {Number} rotation */ getRotation: function getRotation(start, end) { // need two fingers if(start.length >= 2 && end.length >= 2) { return this.getAngle(end[1], end[0]) - this.getAngle(start[1], start[0]); } return 0; }, /** * boolean if the direction is vertical * @param {String} direction * @returns {Boolean} is_vertical */ isVertical: function isVertical(direction) { return (direction == ionic.Gestures.DIRECTION_UP || direction == ionic.Gestures.DIRECTION_DOWN); }, /** * stop browser default behavior with css props * @param {HtmlElement} element * @param {Object} css_props */ stopDefaultBrowserBehavior: function stopDefaultBrowserBehavior(element, css_props) { var prop, vendors = ['webkit','khtml','moz','Moz','ms','o','']; if(!css_props || !element.style) { return; } // with css properties for modern browsers for(var i = 0; i < vendors.length; i++) { for(var p in css_props) { if(css_props.hasOwnProperty(p)) { prop = p; // vender prefix at the property if(vendors[i]) { prop = vendors[i] + prop.substring(0, 1).toUpperCase() + prop.substring(1); } // set the style element.style[prop] = css_props[p]; } } } // also the disable onselectstart if(css_props.userSelect == 'none') { element.onselectstart = function() { return false; }; } } }; ionic.Gestures.detection = { // contains all registred ionic.Gestures.gestures in the correct order gestures: [], // data of the current ionic.Gestures.gesture detection session current: null, // the previous ionic.Gestures.gesture session data // is a full clone of the previous gesture.current object previous: null, // when this becomes true, no gestures are fired stopped: false, /** * start ionic.Gestures.gesture detection * @param {ionic.Gestures.Instance} inst * @param {Object} eventData */ startDetect: function startDetect(inst, eventData) { // already busy with a ionic.Gestures.gesture detection on an element if(this.current) { return; } this.stopped = false; this.current = { inst : inst, // reference to ionic.GesturesInstance we're working for startEvent : ionic.Gestures.utils.extend({}, eventData), // start eventData for distances, timing etc lastEvent : false, // last eventData name : '' // current gesture we're in/detected, can be 'tap', 'hold' etc }; this.detect(eventData); }, /** * ionic.Gestures.gesture detection * @param {Object} eventData */ detect: function detect(eventData) { if(!this.current || this.stopped) { return; } // extend event data with calculations about scale, distance etc eventData = this.extendEventData(eventData); // instance options var inst_options = this.current.inst.options; // call ionic.Gestures.gesture handlers for(var g=0,len=this.gestures.length; g<len; g++) { var gesture = this.gestures[g]; // only when the instance options have enabled this gesture if(!this.stopped && inst_options[gesture.name] !== false) { // if a handler returns false, we stop with the detection if(gesture.handler.call(gesture, eventData, this.current.inst) === false) { this.stopDetect(); break; } } } // store as previous event event if(this.current) { this.current.lastEvent = eventData; } // endevent, but not the last touch, so dont stop if(eventData.eventType == ionic.Gestures.EVENT_END && !eventData.touches.length-1) { this.stopDetect(); } return eventData; }, /** * clear the ionic.Gestures.gesture vars * this is called on endDetect, but can also be used when a final ionic.Gestures.gesture has been detected * to stop other ionic.Gestures.gestures from being fired */ stopDetect: function stopDetect() { // clone current data to the store as the previous gesture // used for the double tap gesture, since this is an other gesture detect session this.previous = ionic.Gestures.utils.extend({}, this.current); // reset the current this.current = null; // stopped! this.stopped = true; }, /** * extend eventData for ionic.Gestures.gestures * @param {Object} ev * @returns {Object} ev */ extendEventData: function extendEventData(ev) { var startEv = this.current.startEvent; // if the touches change, set the new touches over the startEvent touches // this because touchevents don't have all the touches on touchstart, or the // user must place his fingers at the EXACT same time on the screen, which is not realistic // but, sometimes it happens that both fingers are touching at the EXACT same time if(startEv && (ev.touches.length != startEv.touches.length || ev.touches === startEv.touches)) { // extend 1 level deep to get the touchlist with the touch objects startEv.touches = []; for(var i=0,len=ev.touches.length; i<len; i++) { startEv.touches.push(ionic.Gestures.utils.extend({}, ev.touches[i])); } } var delta_time = ev.timeStamp - startEv.timeStamp, delta_x = ev.center.pageX - startEv.center.pageX, delta_y = ev.center.pageY - startEv.center.pageY, velocity = ionic.Gestures.utils.getVelocity(delta_time, delta_x, delta_y); ionic.Gestures.utils.extend(ev, { deltaTime : delta_time, deltaX : delta_x, deltaY : delta_y, velocityX : velocity.x, velocityY : velocity.y, distance : ionic.Gestures.utils.getDistance(startEv.center, ev.center), angle : ionic.Gestures.utils.getAngle(startEv.center, ev.center), direction : ionic.Gestures.utils.getDirection(startEv.center, ev.center), scale : ionic.Gestures.utils.getScale(startEv.touches, ev.touches), rotation : ionic.Gestures.utils.getRotation(startEv.touches, ev.touches), startEvent : startEv }); return ev; }, /** * register new gesture * @param {Object} gesture object, see gestures.js for documentation * @returns {Array} gestures */ register: function register(gesture) { // add an enable gesture options if there is no given var options = gesture.defaults || {}; if(options[gesture.name] === undefined) { options[gesture.name] = true; } // extend ionic.Gestures default options with the ionic.Gestures.gesture options ionic.Gestures.utils.extend(ionic.Gestures.defaults, options, true); // set its index gesture.index = gesture.index || 1000; // add ionic.Gestures.gesture to the list this.gestures.push(gesture); // sort the list by index this.gestures.sort(function(a, b) { if (a.index < b.index) { return -1; } if (a.index > b.index) { return 1; } return 0; }); return this.gestures; } }; ionic.Gestures.gestures = ionic.Gestures.gestures || {}; /** * Custom gestures * ============================== * * Gesture object * -------------------- * The object structure of a gesture: * * { name: 'mygesture', * index: 1337, * defaults: { * mygesture_option: true * } * handler: function(type, ev, inst) { * // trigger gesture event * inst.trigger(this.name, ev); * } * } * @param {String} name * this should be the name of the gesture, lowercase * it is also being used to disable/enable the gesture per instance config. * * @param {Number} [index=1000] * the index of the gesture, where it is going to be in the stack of gestures detection * like when you build an gesture that depends on the drag gesture, it is a good * idea to place it after the index of the drag gesture. * * @param {Object} [defaults={}] * the default settings of the gesture. these are added to the instance settings, * and can be overruled per instance. you can also add the name of the gesture, * but this is also added by default (and set to true). * * @param {Function} handler * this handles the gesture detection of your custom gesture and receives the * following arguments: * * @param {Object} eventData * event data containing the following properties: * timeStamp {Number} time the event occurred * target {HTMLElement} target element * touches {Array} touches (fingers, pointers, mouse) on the screen * pointerType {String} kind of pointer that was used. matches ionic.Gestures.POINTER_MOUSE|TOUCH * center {Object} center position of the touches. contains pageX and pageY * deltaTime {Number} the total time of the touches in the screen * deltaX {Number} the delta on x axis we haved moved * deltaY {Number} the delta on y axis we haved moved * velocityX {Number} the velocity on the x * velocityY {Number} the velocity on y * angle {Number} the angle we are moving * direction {String} the direction we are moving. matches ionic.Gestures.DIRECTION_UP|DOWN|LEFT|RIGHT * distance {Number} the distance we haved moved * scale {Number} scaling of the touches, needs 2 touches * rotation {Number} rotation of the touches, needs 2 touches * * eventType {String} matches ionic.Gestures.EVENT_START|MOVE|END * srcEvent {Object} the source event, like TouchStart or MouseDown * * startEvent {Object} contains the same properties as above, * but from the first touch. this is used to calculate * distances, deltaTime, scaling etc * * @param {ionic.Gestures.Instance} inst * the instance we are doing the detection for. you can get the options from * the inst.options object and trigger the gesture event by calling inst.trigger * * * Handle gestures * -------------------- * inside the handler you can get/set ionic.Gestures.detectionic.current. This is the current * detection sessionic. It has the following properties * @param {String} name * contains the name of the gesture we have detected. it has not a real function, * only to check in other gestures if something is detected. * like in the drag gesture we set it to 'drag' and in the swipe gesture we can * check if the current gesture is 'drag' by accessing ionic.Gestures.detectionic.current.name * * @readonly * @param {ionic.Gestures.Instance} inst * the instance we do the detection for * * @readonly * @param {Object} startEvent * contains the properties of the first gesture detection in this sessionic. * Used for calculations about timing, distance, etc. * * @readonly * @param {Object} lastEvent * contains all the properties of the last gesture detect in this sessionic. * * after the gesture detection session has been completed (user has released the screen) * the ionic.Gestures.detectionic.current object is copied into ionic.Gestures.detectionic.previous, * this is usefull for gestures like doubletap, where you need to know if the * previous gesture was a tap * * options that have been set by the instance can be received by calling inst.options * * You can trigger a gesture event by calling inst.trigger("mygesture", event). * The first param is the name of your gesture, the second the event argument * * * Register gestures * -------------------- * When an gesture is added to the ionic.Gestures.gestures object, it is auto registered * at the setup of the first ionic.Gestures instance. You can also call ionic.Gestures.detectionic.register * manually and pass your gesture object as a param * */ /** * Hold * Touch stays at the same place for x time * @events hold */ ionic.Gestures.gestures.Hold = { name: 'hold', index: 10, defaults: { hold_timeout : 500, hold_threshold : 1 }, timer: null, handler: function holdGesture(ev, inst) { switch(ev.eventType) { case ionic.Gestures.EVENT_START: // clear any running timers clearTimeout(this.timer); // set the gesture so we can check in the timeout if it still is ionic.Gestures.detection.current.name = this.name; // set timer and if after the timeout it still is hold, // we trigger the hold event this.timer = setTimeout(function() { if(ionic.Gestures.detection.current.name == 'hold') { inst.trigger('hold', ev); } }, inst.options.hold_timeout); break; // when you move or end we clear the timer case ionic.Gestures.EVENT_MOVE: if(ev.distance > inst.options.hold_threshold) { clearTimeout(this.timer); } break; case ionic.Gestures.EVENT_END: clearTimeout(this.timer); break; } } }; /** * Tap/DoubleTap * Quick touch at a place or double at the same place * @events tap, doubletap */ ionic.Gestures.gestures.Tap = { name: 'tap', index: 100, defaults: { tap_max_touchtime : 250, tap_max_distance : 10, tap_always : true, doubletap_distance : 20, doubletap_interval : 300 }, handler: function tapGesture(ev, inst) { if(ev.eventType == ionic.Gestures.EVENT_END) { // previous gesture, for the double tap since these are two different gesture detections var prev = ionic.Gestures.detection.previous, did_doubletap = false; // when the touchtime is higher then the max touch time // or when the moving distance is too much if(ev.deltaTime > inst.options.tap_max_touchtime || ev.distance > inst.options.tap_max_distance) { return; } // check if double tap if(prev && prev.name == 'tap' && (ev.timeStamp - prev.lastEvent.timeStamp) < inst.options.doubletap_interval && ev.distance < inst.options.doubletap_distance) { inst.trigger('doubletap', ev); did_doubletap = true; } // do a single tap if(!did_doubletap || inst.options.tap_always) { ionic.Gestures.detection.current.name = 'tap'; inst.trigger(ionic.Gestures.detection.current.name, ev); } } } }; /** * Swipe * triggers swipe events when the end velocity is above the threshold * @events swipe, swipeleft, swiperight, swipeup, swipedown */ ionic.Gestures.gestures.Swipe = { name: 'swipe', index: 40, defaults: { // set 0 for unlimited, but this can conflict with transform swipe_max_touches : 1, swipe_velocity : 0.7 }, handler: function swipeGesture(ev, inst) { if(ev.eventType == ionic.Gestures.EVENT_END) { // max touches if(inst.options.swipe_max_touches > 0 && ev.touches.length > inst.options.swipe_max_touches) { return; } // when the distance we moved is too small we skip this gesture // or we can be already in dragging if(ev.velocityX > inst.options.swipe_velocity || ev.velocityY > inst.options.swipe_velocity) { // trigger swipe events inst.trigger(this.name, ev); inst.trigger(this.name + ev.direction, ev); } } } }; /** * Drag * Move with x fingers (default 1) around on the page. Blocking the scrolling when * moving left and right is a good practice. When all the drag events are blocking * you disable scrolling on that area. * @events drag, drapleft, dragright, dragup, dragdown */ ionic.Gestures.gestures.Drag = { name: 'drag', index: 50, defaults: { drag_min_distance : 10, // Set correct_for_drag_min_distance to true to make the starting point of the drag // be calculated from where the drag was triggered, not from where the touch started. // Useful to avoid a jerk-starting drag, which can make fine-adjustments // through dragging difficult, and be visually unappealing. correct_for_drag_min_distance : true, // set 0 for unlimited, but this can conflict with transform drag_max_touches : 1, // prevent default browser behavior when dragging occurs // be careful with it, it makes the element a blocking element // when you are using the drag gesture, it is a good practice to set this true drag_block_horizontal : true, drag_block_vertical : true, // drag_lock_to_axis keeps the drag gesture on the axis that it started on, // It disallows vertical directions if the initial direction was horizontal, and vice versa. drag_lock_to_axis : false, // drag lock only kicks in when distance > drag_lock_min_distance // This way, locking occurs only when the distance has become large enough to reliably determine the direction drag_lock_min_distance : 25 }, triggered: false, handler: function dragGesture(ev, inst) { // current gesture isnt drag, but dragged is true // this means an other gesture is busy. now call dragend if(ionic.Gestures.detection.current.name != this.name && this.triggered) { inst.trigger(this.name +'end', ev); this.triggered = false; return; } // max touches if(inst.options.drag_max_touches > 0 && ev.touches.length > inst.options.drag_max_touches) { return; } switch(ev.eventType) { case ionic.Gestures.EVENT_START: this.triggered = false; break; case ionic.Gestures.EVENT_MOVE: // when the distance we moved is too small we skip this gesture // or we can be already in dragging if(ev.distance < inst.options.drag_min_distance && ionic.Gestures.detection.current.name != this.name) { return; } // we are dragging! if(ionic.Gestures.detection.current.name != this.name) { ionic.Gestures.detection.current.name = this.name; if (inst.options.correct_for_drag_min_distance) { // When a drag is triggered, set the event center to drag_min_distance pixels from the original event center. // Without this correction, the dragged distance would jumpstart at drag_min_distance pixels instead of at 0. // It might be useful to save the original start point somewhere var factor = Math.abs(inst.options.drag_min_distance/ev.distance); ionic.Gestures.detection.current.startEvent.center.pageX += ev.deltaX * factor; ionic.Gestures.detection.current.startEvent.center.pageY += ev.deltaY * factor; // recalculate event data using new start point ev = ionic.Gestures.detection.extendEventData(ev); } } // lock drag to axis? if(ionic.Gestures.detection.current.lastEvent.drag_locked_to_axis || (inst.options.drag_lock_to_axis && inst.options.drag_lock_min_distance<=ev.distance)) { ev.drag_locked_to_axis = true; } var last_direction = ionic.Gestures.detection.current.lastEvent.direction; if(ev.drag_locked_to_axis && last_direction !== ev.direction) { // keep direction on the axis that the drag gesture started on if(ionic.Gestures.utils.isVertical(last_direction)) { ev.direction = (ev.deltaY < 0) ? ionic.Gestures.DIRECTION_UP : ionic.Gestures.DIRECTION_DOWN; } else { ev.direction = (ev.deltaX < 0) ? ionic.Gestures.DIRECTION_LEFT : ionic.Gestures.DIRECTION_RIGHT; } } // first time, trigger dragstart event if(!this.triggered) { inst.trigger(this.name +'start', ev); this.triggered = true; } // trigger normal event inst.trigger(this.name, ev); // direction event, like dragdown inst.trigger(this.name + ev.direction, ev); // block the browser events if( (inst.options.drag_block_vertical && ionic.Gestures.utils.isVertical(ev.direction)) || (inst.options.drag_block_horizontal && !ionic.Gestures.utils.isVertical(ev.direction))) { ev.preventDefault(); } break; case ionic.Gestures.EVENT_END: // trigger dragend if(this.triggered) { inst.trigger(this.name +'end', ev); } this.triggered = false; break; } } }; /** * Transform * User want to scale or rotate with 2 fingers * @events transform, pinch, pinchin, pinchout, rotate */ ionic.Gestures.gestures.Transform = { name: 'transform', index: 45, defaults: { // factor, no scale is 1, zoomin is to 0 and zoomout until higher then 1 transform_min_scale : 0.01, // rotation in degrees transform_min_rotation : 1, // prevent default browser behavior when two touches are on the screen // but it makes the element a blocking element // when you are using the transform gesture, it is a good practice to set this true transform_always_block : false }, triggered: false, handler: function transformGesture(ev, inst) { // current gesture isnt drag, but dragged is true // this means an other gesture is busy. now call dragend if(ionic.Gestures.detection.current.name != this.name && this.triggered) { inst.trigger(this.name +'end', ev); this.triggered = false; return; } // atleast multitouch if(ev.touches.length < 2) { return; } // prevent default when two fingers are on the screen if(inst.options.transform_always_block) { ev.preventDefault(); } switch(ev.eventType) { case ionic.Gestures.EVENT_START: this.triggered = false; break; case ionic.Gestures.EVENT_MOVE: var scale_threshold = Math.abs(1-ev.scale); var rotation_threshold = Math.abs(ev.rotation); // when the distance we moved is too small we skip this gesture // or we can be already in dragging if(scale_threshold < inst.options.transform_min_scale && rotation_threshold < inst.options.transform_min_rotation) { return; } // we are transforming! ionic.Gestures.detection.current.name = this.name; // first time, trigger dragstart event if(!this.triggered) { inst.trigger(this.name +'start', ev); this.triggered = true; } inst.trigger(this.name, ev); // basic transform event // trigger rotate event if(rotation_threshold > inst.options.transform_min_rotation) { inst.trigger('rotate', ev); } // trigger pinch event if(scale_threshold > inst.options.transform_min_scale) { inst.trigger('pinch', ev); inst.trigger('pinch'+ ((ev.scale < 1) ? 'in' : 'out'), ev); } break; case ionic.Gestures.EVENT_END: // trigger dragend if(this.triggered) { inst.trigger(this.name +'end', ev); } this.triggered = false; break; } } }; /** * Touch * Called as first, tells the user has touched the screen * @events touch */ ionic.Gestures.gestures.Touch = { name: 'touch', index: -Infinity, defaults: { // call preventDefault at touchstart, and makes the element blocking by // disabling the scrolling of the page, but it improves gestures like // transforming and dragging. // be careful with using this, it can be very annoying for users to be stuck // on the page prevent_default: false, // disable mouse events, so only touch (or pen!) input triggers events prevent_mouseevents: false }, handler: function touchGesture(ev, inst) { if(inst.options.prevent_mouseevents && ev.pointerType == ionic.Gestures.POINTER_MOUSE) { ev.stopDetect(); return; } if(inst.options.prevent_default) { ev.preventDefault(); } if(ev.eventType == ionic.Gestures.EVENT_START) { inst.trigger(this.name, ev); } } }; /** * Release * Called as last, tells the user has released the screen * @events release */ ionic.Gestures.gestures.Release = { name: 'release', index: Infinity, handler: function releaseGesture(ev, inst) { if(ev.eventType == ionic.Gestures.EVENT_END) { inst.trigger(this.name, ev); } } }; })(window.ionic); ; (function(ionic) { ionic.Platform = { detect: function() { var platforms = []; this._checkPlatforms(platforms); var classify = function() { if(!document.body) { return; } for(var i = 0; i < platforms.length; i++) { document.body.classList.add('platform-' + platforms[i]); } }; document.addEventListener( "DOMContentLoaded", function(){ classify(); }); classify(); }, _checkPlatforms: function(platforms) { if(this.isCordova()) { platforms.push('cordova'); } if(this.isIOS7()) { platforms.push('ios7'); } if(this.isIPad()) { platforms.push('ipad'); } if(this.isAndroid()) { platforms.push('android'); } }, // Check if we are running in Cordova, which will have // window.device available. isCordova: function() { return (window.cordova || window.PhoneGap || window.phonegap); //&& /^file:\/{3}[^\/]/i.test(window.location.href) //&& /ios|iphone|ipod|ipad|android/i.test(navigator.userAgent); }, isIPad: function() { return navigator.userAgent.toLowerCase().indexOf('ipad') >= 0; }, isIOS7: function() { if(!window.device) { return false; } return parseFloat(window.device.version) >= 7.0; }, isAndroid: function() { if(!window.device) { return navigator.userAgent.toLowerCase().indexOf('android') >= 0; } return device.platform === "Android"; } }; ionic.Platform.detect(); })(window.ionic); ; (function(window, document, ionic) { 'use strict'; // From the man himself, Mr. Paul Irish. // The requestAnimationFrame polyfill window.rAF = (function(){ return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function( callback ){ window.setTimeout(callback, 1000 / 60); }; })(); // Ionic CSS polyfills ionic.CSS = {}; (function() { var d = document.createElement('div'); var keys = ['webkitTransform', 'transform', '-webkit-transform', 'webkit-transform', '-moz-transform', 'moz-transform', 'MozTransform', 'mozTransform']; for(var i = 0; i < keys.length; i++) { if(d.style[keys[i]] !== undefined) { ionic.CSS.TRANSFORM = keys[i]; break; } } })(); // polyfill use to simulate native "tap" function inputTapPolyfill(ele, e) { if(ele.type === "radio") { ele.checked = !ele.checked; ionic.trigger('click', { target: ele }); } else if(ele.type === "checkbox") { ele.checked = !ele.checked; ionic.trigger('change', { target: ele }); } else if(ele.type === "submit" || ele.type === "button") { ionic.trigger('click', { target: ele }); } else { ele.focus(); } e.stopPropagation(); e.preventDefault(); return false; } function tapPolyfill(e) { // if the source event wasn't from a touch event then don't use this polyfill if(!e.gesture || e.gesture.pointerType !== "touch" || !e.gesture.srcEvent) return; // An internal Ionic indicator for angular directives that contain // elements that normally need poly behavior, but are already processed // (like the radio directive that has a radio button in it, but handles // the tap stuff itself). This is in contrast to preventDefault which will // mess up other operations like change events and such if(e.alreadyHandled) { return; } e = e.gesture.srcEvent; // evaluate the actual source event, not the created event by gestures.js var ele = e.target; while(ele) { if( ele.tagName === "INPUT" || ele.tagName === "TEXTAREA" || ele.tagName === "SELECT" ) { return inputTapPolyfill(ele, e); } else if( ele.tagName === "LABEL" ) { if(ele.control) { return inputTapPolyfill(ele.control, e); } } else if( ele.tagName === "A" || ele.tagName === "BUTTON" ) { ionic.trigger('click', { target: ele }); e.stopPropagation(); e.preventDefault(); return false; } ele = ele.parentElement; } // they didn't tap one of the above elements // if the currently active element is an input, and they tapped outside // of the current input, then unset its focus (blur) so the keyboard goes away var activeElement = document.activeElement; if(activeElement && (activeElement.tagName === "INPUT" || activeElement.tagName === "TEXTAREA" || activeElement.tagName === "SELECT")) { activeElement.blur(); e.stopPropagation(); e.preventDefault(); return false; } } // global tap event listener polyfill for HTML elements that were "tapped" by the user ionic.on("tap", tapPolyfill, window); })(this, document, ionic); ; (function(ionic) { /** * Various utilities used throughout Ionic * * Some of these are adopted from underscore.js and backbone.js, both also MIT licensed. */ ionic.Utils = { arrayMove: function (arr, old_index, new_index) { if (new_index >= arr.length) { var k = new_index - arr.length; while ((k--) + 1) { arr.push(undefined); } } arr.splice(new_index, 0, arr.splice(old_index, 1)[0]); return arr; }, /** * Return a function that will be called with the given context */ proxy: function(func, context) { var args = Array.prototype.slice.call(arguments, 2); return function() { return func.apply(context, args.concat(Array.prototype.slice.call(arguments))); }; }, /** * Only call a function once in the given interval. * * @param func {Function} the function to call * @param wait {int} how long to wait before/after to allow function calls * @param immediate {boolean} whether to call immediately or after the wait interval */ debounce: function(func, wait, immediate) { var timeout, args, context, timestamp, result; return function() { context = this; args = arguments; timestamp = new Date(); var later = function() { var last = (new Date()) - timestamp; if (last < wait) { timeout = setTimeout(later, wait - last); } else { timeout = null; if (!immediate) result = func.apply(context, args); } }; var callNow = immediate && !timeout; if (!timeout) { timeout = setTimeout(later, wait); } if (callNow) result = func.apply(context, args); return result; }; }, /** * Throttle the given fun, only allowing it to be * called at most every `wait` ms. */ throttle: function(func, wait, options) { var context, args, result; var timeout = null; var previous = 0; options || (options = {}); var later = function() { previous = options.leading === false ? 0 : Date.now(); timeout = null; result = func.apply(context, args); }; return function() { var now = Date.now(); if (!previous && options.leading === false) previous = now; var remaining = wait - (now - previous); context = this; args = arguments; if (remaining <= 0) { clearTimeout(timeout); timeout = null; previous = now; result = func.apply(context, args); } else if (!timeout && options.trailing !== false) { timeout = setTimeout(later, remaining); } return result; }; }, // Borrowed from Backbone.js's extend // 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. inherit: function(protoProps, staticProps) { var parent = this; var child; // The constructor function for the new subclass is either defined by you // (the "constructor" property in your `extend` definition), or defaulted // by us to simply call the parent's constructor. if (protoProps && protoProps.hasOwnProperty('constructor')) { child = protoProps.constructor; } else { child = function(){ return parent.apply(this, arguments); }; } // Add static properties to the constructor function, if supplied. ionic.extend(child, parent, staticProps); // Set the prototype chain to inherit from `parent`, without calling // `parent`'s constructor function. var Surrogate = function(){ this.constructor = child; }; Surrogate.prototype = parent.prototype; child.prototype = new Surrogate; // Add prototype properties (instance properties) to the subclass, // if supplied. if (protoProps) ionic.extend(child.prototype, protoProps); // Set a convenience property in case the parent's prototype is needed // later. child.__super__ = parent.prototype; return child; }, // Extend adapted from Underscore.js extend: function(obj) { var args = Array.prototype.slice.call(arguments, 1); for(var i = 0; i < args.length; i++) { var source = args[i]; if (source) { for (var prop in source) { obj[prop] = source[prop]; } } } return obj; } }; // Bind a few of the most useful functions to the ionic scope ionic.inherit = ionic.Utils.inherit; ionic.extend = ionic.Utils.extend; ionic.throttle = ionic.Utils.throttle; ionic.proxy = ionic.Utils.proxy; ionic.debounce = ionic.Utils.debounce; })(window.ionic); ; (function(ionic) { 'use strict'; ionic.views.View = function() { this.initialize.apply(this, arguments); }; ionic.views.View.inherit = ionic.inherit; ionic.extend(ionic.views.View.prototype, { initialize: function() {} }); })(window.ionic); ; /* * Scroller * http://github.com/zynga/scroller * * Copyright 2011, Zynga Inc. * Licensed under the MIT License. * https://raw.github.com/zynga/scroller/master/MIT-LICENSE.txt * * Based on the work of: Unify Project (unify-project.org) * http://unify-project.org * Copyright 2011, Deutsche Telekom AG * License: MIT + Apache (V2) */ /** * Generic animation class with support for dropped frames both optional easing and duration. * * Optional duration is useful when the lifetime is defined by another condition than time * e.g. speed of an animating object, etc. * * Dropped frame logic allows to keep using the same updater logic independent from the actual * rendering. This eases a lot of cases where it might be pretty complex to break down a state * based on the pure time difference. */ (function(global) { var time = Date.now || function() { return +new Date(); }; var desiredFrames = 60; var millisecondsPerSecond = 1000; var running = {}; var counter = 1; // Create namespaces if (!global.core) { global.core = { effect : {} }; } else if (!core.effect) { core.effect = {}; } core.effect.Animate = { /** * A requestAnimationFrame wrapper / polyfill. * * @param callback {Function} The callback to be invoked before the next repaint. * @param root {HTMLElement} The root element for the repaint */ requestAnimationFrame: (function() { // Check for request animation Frame support var requestFrame = global.requestAnimationFrame || global.webkitRequestAnimationFrame || global.mozRequestAnimationFrame || global.oRequestAnimationFrame; var isNative = !!requestFrame; if (requestFrame && !/requestAnimationFrame\(\)\s*\{\s*\[native code\]\s*\}/i.test(requestFrame.toString())) { isNative = false; } if (isNative) { return function(callback, root) { requestFrame(callback, root) }; } var TARGET_FPS = 60; var requests = {}; var requestCount = 0; var rafHandle = 1; var intervalHandle = null; var lastActive = +new Date(); return function(callback, root) { var callbackHandle = rafHandle++; // Store callback requests[callbackHandle] = callback; requestCount++; // Create timeout at first request if (intervalHandle === null) { intervalHandle = setInterval(function() { var time = +new Date(); var currentRequests = requests; // Reset data structure before executing callbacks requests = {}; requestCount = 0; for(var key in currentRequests) { if (currentRequests.hasOwnProperty(key)) { currentRequests[key](time); lastActive = time; } } // Disable the timeout when nothing happens for a certain // period of time if (time - lastActive > 2500) { clearInterval(intervalHandle); intervalHandle = null; } }, 1000 / TARGET_FPS); } return callbackHandle; }; })(), /** * Stops the given animation. * * @param id {Integer} Unique animation ID * @return {Boolean} Whether the animation was stopped (aka, was running before) */ stop: function(id) { var cleared = running[id] != null; if (cleared) { running[id] = null; } return cleared; }, /** * Whether the given animation is still running. * * @param id {Integer} Unique animation ID * @return {Boolean} Whether the animation is still running */ isRunning: function(id) { return running[id] != null; }, /** * Start the animation. * * @param stepCallback {Function} Pointer to function which is executed on every step. * Signature of the method should be `function(percent, now, virtual) { return continueWithAnimation; }` * @param verifyCallback {Function} Executed before every animation step. * Signature of the method should be `function() { return continueWithAnimation; }` * @param completedCallback {Function} * Signature of the method should be `function(droppedFrames, finishedAnimation) {}` * @param duration {Integer} Milliseconds to run the animation * @param easingMethod {Function} Pointer to easing function * Signature of the method should be `function(percent) { return modifiedValue; }` * @param root {Element ? document.body} Render root, when available. Used for internal * usage of requestAnimationFrame. * @return {Integer} Identifier of animation. Can be used to stop it any time. */ start: function(stepCallback, verifyCallback, completedCallback, duration, easingMethod, root) { var start = time(); var lastFrame = start; var percent = 0; var dropCounter = 0; var id = counter++; if (!root) { root = document.body; } // Compacting running db automatically every few new animations if (id % 20 === 0) { var newRunning = {}; for (var usedId in running) { newRunning[usedId] = true; } running = newRunning; } // This is the internal step method which is called every few milliseconds var step = function(virtual) { // Normalize virtual value var render = virtual !== true; // Get current time var now = time(); // Verification is executed before next animation step if (!running[id] || (verifyCallback && !verifyCallback(id))) { running[id] = null; completedCallback && completedCallback(desiredFrames - (dropCounter / ((now - start) / millisecondsPerSecond)), id, false); return; } // For the current rendering to apply let's update omitted steps in memory. // This is important to bring internal state variables up-to-date with progress in time. if (render) { var droppedFrames = Math.round((now - lastFrame) / (millisecondsPerSecond / desiredFrames)) - 1; for (var j = 0; j < Math.min(droppedFrames, 4); j++) { step(true); dropCounter++; } } // Compute percent value if (duration) { percent = (now - start) / duration; if (percent > 1) { percent = 1; } } // Execute step callback, then... var value = easingMethod ? easingMethod(percent) : percent; if ((stepCallback(value, now, render) === false || percent === 1) && render) { running[id] = null; completedCallback && completedCallback(desiredFrames - (dropCounter / ((now - start) / millisecondsPerSecond)), id, percent === 1 || duration == null); } else if (render) { lastFrame = now; core.effect.Animate.requestAnimationFrame(step, root); } }; // Mark as running running[id] = true; // Init first step core.effect.Animate.requestAnimationFrame(step, root); // Return unique animation ID return id; } }; })(this); /* * Scroller * http://github.com/zynga/scroller * * Copyright 2011, Zynga Inc. * Licensed under the MIT License. * https://raw.github.com/zynga/scroller/master/MIT-LICENSE.txt * * Based on the work of: Unify Project (unify-project.org) * http://unify-project.org * Copyright 2011, Deutsche Telekom AG * License: MIT + Apache (V2) */ var Scroller; (function(ionic) { var NOOP = function(){}; // Easing Equations (c) 2003 Robert Penner, all rights reserved. // Open source under the BSD License. /** * @param pos {Number} position between 0 (start of effect) and 1 (end of effect) **/ var easeOutCubic = function(pos) { return (Math.pow((pos - 1), 3) + 1); }; /** * @param pos {Number} position between 0 (start of effect) and 1 (end of effect) **/ var easeInOutCubic = function(pos) { if ((pos /= 0.5) < 1) { return 0.5 * Math.pow(pos, 3); } return 0.5 * (Math.pow((pos - 2), 3) + 2); }; /** * A pure logic 'component' for 'virtual' scrolling/zooming. */ ionic.views.Scroll = ionic.views.View.inherit({ initialize: function(options) { var self = this; this.__container = options.el; this.__content = options.el.firstElementChild; this.options = { /** Disable scrolling on x-axis by default */ scrollingX: false, /** Enable scrolling on y-axis */ scrollingY: true, /** Enable animations for deceleration, snap back, zooming and scrolling */ animating: true, /** duration for animations triggered by scrollTo/zoomTo */ animationDuration: 250, /** Enable bouncing (content can be slowly moved outside and jumps back after releasing) */ bouncing: true, /** Enable locking to the main axis if user moves only slightly on one of them at start */ locking: true, /** Enable pagination mode (switching between full page content panes) */ paging: false, /** Enable snapping of content to a configured pixel grid */ snapping: false, /** Enable zooming of content via API, fingers and mouse wheel */ zooming: false, /** Minimum zoom level */ minZoom: 0.5, /** Maximum zoom level */ maxZoom: 3, /** Multiply or decrease scrolling speed **/ speedMultiplier: 1, /** Callback that is fired on the later of touch end or deceleration end, provided that another scrolling action has not begun. Used to know when to fade out a scrollbar. */ scrollingComplete: NOOP, /** This configures the amount of change applied to deceleration when reaching boundaries **/ penetrationDeceleration : 0.03, /** This configures the amount of change applied to acceleration when reaching boundaries **/ penetrationAcceleration : 0.08, // The ms interval for triggering scroll events scrollEventInterval: 50 }; for (var key in options) { this.options[key] = options[key]; } this.hintResize = ionic.debounce(function() { self.resize(); }, 1000, true); this.triggerScrollEvent = ionic.throttle(function() { ionic.trigger('scroll', { scrollTop: self.__scrollTop, scrollLeft: self.__scrollLeft, target: self.__container }); }, this.options.scrollEventInterval); this.triggerScrollEndEvent = function() { ionic.trigger('scrollend', { scrollTop: self.__scrollTop, scrollLeft: self.__scrollLeft, target: self.__container }); }; // Get the render update function, initialize event handlers, // and calculate the size of the scroll container this.__callback = this.getRenderFn(); this.__initEventHandlers(); this.resize(); }, /* --------------------------------------------------------------------------- INTERNAL FIELDS :: STATUS --------------------------------------------------------------------------- */ /** {Boolean} Whether only a single finger is used in touch handling */ __isSingleTouch: false, /** {Boolean} Whether a touch event sequence is in progress */ __isTracking: false, /** {Boolean} Whether a deceleration animation went to completion. */ __didDecelerationComplete: false, /** * {Boolean} Whether a gesture zoom/rotate event is in progress. Activates when * a gesturestart event happens. This has higher priority than dragging. */ __isGesturing: false, /** * {Boolean} Whether the user has moved by such a distance that we have enabled * dragging mode. Hint: It's only enabled after some pixels of movement to * not interrupt with clicks etc. */ __isDragging: false, /** * {Boolean} Not touching and dragging anymore, and smoothly animating the * touch sequence using deceleration. */ __isDecelerating: false, /** * {Boolean} Smoothly animating the currently configured change */ __isAnimating: false, /* --------------------------------------------------------------------------- INTERNAL FIELDS :: DIMENSIONS --------------------------------------------------------------------------- */ /** {Integer} Available outer left position (from document perspective) */ __clientLeft: 0, /** {Integer} Available outer top position (from document perspective) */ __clientTop: 0, /** {Integer} Available outer width */ __clientWidth: 0, /** {Integer} Available outer height */ __clientHeight: 0, /** {Integer} Outer width of content */ __contentWidth: 0, /** {Integer} Outer height of content */ __contentHeight: 0, /** {Integer} Snapping width for content */ __snapWidth: 100, /** {Integer} Snapping height for content */ __snapHeight: 100, /** {Integer} Height to assign to refresh area */ __refreshHeight: null, /** {Boolean} Whether the refresh process is enabled when the event is released now */ __refreshActive: false, /** {Function} Callback to execute on activation. This is for signalling the user about a refresh is about to happen when he release */ __refreshActivate: null, /** {Function} Callback to execute on deactivation. This is for signalling the user about the refresh being cancelled */ __refreshDeactivate: null, /** {Function} Callback to execute to start the actual refresh. Call {@link #refreshFinish} when done */ __refreshStart: null, /** {Number} Zoom level */ __zoomLevel: 1, /** {Number} Scroll position on x-axis */ __scrollLeft: 0, /** {Number} Scroll position on y-axis */ __scrollTop: 0, /** {Integer} Maximum allowed scroll position on x-axis */ __maxScrollLeft: 0, /** {Integer} Maximum allowed scroll position on y-axis */ __maxScrollTop: 0, /* {Number} Scheduled left position (final position when animating) */ __scheduledLeft: 0, /* {Number} Scheduled top position (final position when animating) */ __scheduledTop: 0, /* {Number} Scheduled zoom level (final scale when animating) */ __scheduledZoom: 0, /* --------------------------------------------------------------------------- INTERNAL FIELDS :: LAST POSITIONS --------------------------------------------------------------------------- */ /** {Number} Left position of finger at start */ __lastTouchLeft: null, /** {Number} Top position of finger at start */ __lastTouchTop: null, /** {Date} Timestamp of last move of finger. Used to limit tracking range for deceleration speed. */ __lastTouchMove: null, /** {Array} List of positions, uses three indexes for each state: left, top, timestamp */ __positions: null, /* --------------------------------------------------------------------------- INTERNAL FIELDS :: DECELERATION SUPPORT --------------------------------------------------------------------------- */ /** {Integer} Minimum left scroll position during deceleration */ __minDecelerationScrollLeft: null, /** {Integer} Minimum top scroll position during deceleration */ __minDecelerationScrollTop: null, /** {Integer} Maximum left scroll position during deceleration */ __maxDecelerationScrollLeft: null, /** {Integer} Maximum top scroll position during deceleration */ __maxDecelerationScrollTop: null, /** {Number} Current factor to modify horizontal scroll position with on every step */ __decelerationVelocityX: null, /** {Number} Current factor to modify vertical scroll position with on every step */ __decelerationVelocityY: null, __initEventHandlers: function() { var self = this; // Event Handler var container = this.__container; if ('ontouchstart' in window) { container.addEventListener("touchstart", function(e) { // Don't react if initial down happens on a form element if (e.target.tagName.match(/input|textarea|select/i)) { return; } self.doTouchStart(e.touches, e.timeStamp); e.preventDefault(); }, false); document.addEventListener("touchmove", function(e) { if(e.defaultPrevented) { return; } self.doTouchMove(e.touches, e.timeStamp); }, false); document.addEventListener("touchend", function(e) { self.doTouchEnd(e.timeStamp); }, false); } else { var mousedown = false; container.addEventListener("mousedown", function(e) { // Don't react if initial down happens on a form element if (e.target.tagName.match(/input|textarea|select/i)) { return; } self.doTouchStart([{ pageX: e.pageX, pageY: e.pageY }], e.timeStamp); mousedown = true; }, false); document.addEventListener("mousemove", function(e) { if (!mousedown || e.defaultPrevented) { return; } self.doTouchMove([{ pageX: e.pageX, pageY: e.pageY }], e.timeStamp); mousedown = true; }, false); document.addEventListener("mouseup", function(e) { if (!mousedown) { return; } self.doTouchEnd(e.timeStamp); mousedown = false; }, false); } }, resize: function() { // Update Scroller dimensions for changed content // Add padding to bottom of content this.setDimensions( this.__container.clientWidth, this.__container.clientHeight, this.__content.offsetWidth, this.__content.offsetHeight+20); }, /* --------------------------------------------------------------------------- PUBLIC API --------------------------------------------------------------------------- */ getRenderFn: function() { var self = this; var content = this.__content; var docStyle = document.documentElement.style; var engine; if ('MozAppearance' in docStyle) { engine = 'gecko'; } else if ('WebkitAppearance' in docStyle) { engine = 'webkit'; } else if (typeof navigator.cpuClass === 'string') { engine = 'trident'; } var vendorPrefix = { trident: 'ms', gecko: 'Moz', webkit: 'Webkit', presto: 'O' }[engine]; var helperElem = document.createElement("div"); var undef; var perspectiveProperty = vendorPrefix + "Perspective"; var transformProperty = vendorPrefix + "Transform"; if (helperElem.style[perspectiveProperty] !== undef) { return function(left, top, zoom) { content.style[transformProperty] = 'translate3d(' + (-left) + 'px,' + (-top) + 'px,0)'; self.triggerScrollEvent(); }; } else if (helperElem.style[transformProperty] !== undef) { return function(left, top, zoom) { content.style[transformProperty] = 'translate(' + (-left) + 'px,' + (-top) + 'px)'; self.triggerScrollEvent(); }; } else { return function(left, top, zoom) { content.style.marginLeft = left ? (-left/zoom) + 'px' : ''; content.style.marginTop = top ? (-top/zoom) + 'px' : ''; content.style.zoom = zoom || ''; self.triggerScrollEvent(); }; } }, /** * Configures the dimensions of the client (outer) and content (inner) elements. * Requires the available space for the outer element and the outer size of the inner element. * All values which are falsy (null or zero etc.) are ignored and the old value is kept. * * @param clientWidth {Integer ? null} Inner width of outer element * @param clientHeight {Integer ? null} Inner height of outer element * @param contentWidth {Integer ? null} Outer width of inner element * @param contentHeight {Integer ? null} Outer height of inner element */ setDimensions: function(clientWidth, clientHeight, contentWidth, contentHeight) { var self = this; // Only update values which are defined if (clientWidth === +clientWidth) { self.__clientWidth = clientWidth; } if (clientHeight === +clientHeight) { self.__clientHeight = clientHeight; } if (contentWidth === +contentWidth) { self.__contentWidth = contentWidth; } if (contentHeight === +contentHeight) { self.__contentHeight = contentHeight; } // Refresh maximums self.__computeScrollMax(); // Refresh scroll position self.scrollTo(self.__scrollLeft, self.__scrollTop, true); }, /** * Sets the client coordinates in relation to the document. * * @param left {Integer ? 0} Left position of outer element * @param top {Integer ? 0} Top position of outer element */ setPosition: function(left, top) { var self = this; self.__clientLeft = left || 0; self.__clientTop = top || 0; }, /** * Configures the snapping (when snapping is active) * * @param width {Integer} Snapping width * @param height {Integer} Snapping height */ setSnapSize: function(width, height) { var self = this; self.__snapWidth = width; self.__snapHeight = height; }, /** * Activates pull-to-refresh. A special zone on the top of the list to start a list refresh whenever * the user event is released during visibility of this zone. This was introduced by some apps on iOS like * the official Twitter client. * * @param height {Integer} Height of pull-to-refresh zone on top of rendered list * @param activateCallback {Function} Callback to execute on activation. This is for signalling the user about a refresh is about to happen when he release. * @param deactivateCallback {Function} Callback to execute on deactivation. This is for signalling the user about the refresh being cancelled. * @param startCallback {Function} Callback to execute to start the real async refresh action. Call {@link #finishPullToRefresh} after finish of refresh. */ activatePullToRefresh: function(height, activateCallback, deactivateCallback, startCallback) { var self = this; self.__refreshHeight = height; self.__refreshActivate = activateCallback; self.__refreshDeactivate = deactivateCallback; self.__refreshStart = startCallback; }, /** * Starts pull-to-refresh manually. */ triggerPullToRefresh: function() { // Use publish instead of scrollTo to allow scrolling to out of boundary position // We don't need to normalize scrollLeft, zoomLevel, etc. here because we only y-scrolling when pull-to-refresh is enabled this.__publish(this.__scrollLeft, -this.__refreshHeight, this.__zoomLevel, true); if (this.__refreshStart) { this.__refreshStart(); } }, /** * Signalizes that pull-to-refresh is finished. */ finishPullToRefresh: function() { var self = this; self.__refreshActive = false; if (self.__refreshDeactivate) { self.__refreshDeactivate(); } self.scrollTo(self.__scrollLeft, self.__scrollTop, true); }, /** * Returns the scroll position and zooming values * * @return {Map} `left` and `top` scroll position and `zoom` level */ getValues: function() { var self = this; return { left: self.__scrollLeft, top: self.__scrollTop, zoom: self.__zoomLevel }; }, /** * Returns the maximum scroll values * * @return {Map} `left` and `top` maximum scroll values */ getScrollMax: function() { var self = this; return { left: self.__maxScrollLeft, top: self.__maxScrollTop }; }, /** * Zooms to the given level. Supports optional animation. Zooms * the center when no coordinates are given. * * @param level {Number} Level to zoom to * @param animate {Boolean ? false} Whether to use animation * @param originLeft {Number ? null} Zoom in at given left coordinate * @param originTop {Number ? null} Zoom in at given top coordinate */ zoomTo: function(level, animate, originLeft, originTop) { var self = this; if (!self.options.zooming) { throw new Error("Zooming is not enabled!"); } // Stop deceleration if (self.__isDecelerating) { core.effect.Animate.stop(self.__isDecelerating); self.__isDecelerating = false; } var oldLevel = self.__zoomLevel; // Normalize input origin to center of viewport if not defined if (originLeft == null) { originLeft = self.__clientWidth / 2; } if (originTop == null) { originTop = self.__clientHeight / 2; } // Limit level according to configuration level = Math.max(Math.min(level, self.options.maxZoom), self.options.minZoom); // Recompute maximum values while temporary tweaking maximum scroll ranges self.__computeScrollMax(level); // Recompute left and top coordinates based on new zoom level var left = ((originLeft + self.__scrollLeft) * level / oldLevel) - originLeft; var top = ((originTop + self.__scrollTop) * level / oldLevel) - originTop; // Limit x-axis if (left > self.__maxScrollLeft) { left = self.__maxScrollLeft; } else if (left < 0) { left = 0; } // Limit y-axis if (top > self.__maxScrollTop) { top = self.__maxScrollTop; } else if (top < 0) { top = 0; } // Push values out self.__publish(left, top, level, animate); }, /** * Zooms the content by the given factor. * * @param factor {Number} Zoom by given factor * @param animate {Boolean ? false} Whether to use animation * @param originLeft {Number ? 0} Zoom in at given left coordinate * @param originTop {Number ? 0} Zoom in at given top coordinate */ zoomBy: function(factor, animate, originLeft, originTop) { var self = this; self.zoomTo(self.__zoomLevel * factor, animate, originLeft, originTop); }, /** * Scrolls to the given position. Respect limitations and snapping automatically. * * @param left {Number?null} Horizontal scroll position, keeps current if value is <code>null</code> * @param top {Number?null} Vertical scroll position, keeps current if value is <code>null</code> * @param animate {Boolean?false} Whether the scrolling should happen using an animation * @param zoom {Number?null} Zoom level to go to */ scrollTo: function(left, top, animate, zoom) { var self = this; // Stop deceleration if (self.__isDecelerating) { core.effect.Animate.stop(self.__isDecelerating); self.__isDecelerating = false; } // Correct coordinates based on new zoom level if (zoom != null && zoom !== self.__zoomLevel) { if (!self.options.zooming) { throw new Error("Zooming is not enabled!"); } left *= zoom; top *= zoom; // Recompute maximum values while temporary tweaking maximum scroll ranges self.__computeScrollMax(zoom); } else { // Keep zoom when not defined zoom = self.__zoomLevel; } if (!self.options.scrollingX) { left = self.__scrollLeft; } else { if (self.options.paging) { left = Math.round(left / self.__clientWidth) * self.__clientWidth; } else if (self.options.snapping) { left = Math.round(left / self.__snapWidth) * self.__snapWidth; } } if (!self.options.scrollingY) { top = self.__scrollTop; } else { if (self.options.paging) { top = Math.round(top / self.__clientHeight) * self.__clientHeight; } else if (self.options.snapping) { top = Math.round(top / self.__snapHeight) * self.__snapHeight; } } // Limit for allowed ranges left = Math.max(Math.min(self.__maxScrollLeft, left), 0); top = Math.max(Math.min(self.__maxScrollTop, top), 0); // Don't animate when no change detected, still call publish to make sure // that rendered position is really in-sync with internal data if (left === self.__scrollLeft && top === self.__scrollTop) { animate = false; } // Publish new values self.__publish(left, top, zoom, animate); }, /** * Scroll by the given offset * * @param left {Number ? 0} Scroll x-axis by given offset * @param top {Number ? 0} Scroll x-axis by given offset * @param animate {Boolean ? false} Whether to animate the given change */ scrollBy: function(left, top, animate) { var self = this; var startLeft = self.__isAnimating ? self.__scheduledLeft : self.__scrollLeft; var startTop = self.__isAnimating ? self.__scheduledTop : self.__scrollTop; self.scrollTo(startLeft + (left || 0), startTop + (top || 0), animate); }, /* --------------------------------------------------------------------------- EVENT CALLBACKS --------------------------------------------------------------------------- */ /** * Mouse wheel handler for zooming support */ doMouseZoom: function(wheelDelta, timeStamp, pageX, pageY) { var self = this; var change = wheelDelta > 0 ? 0.97 : 1.03; return self.zoomTo(self.__zoomLevel * change, false, pageX - self.__clientLeft, pageY - self.__clientTop); }, /** * Touch start handler for scrolling support */ doTouchStart: function(touches, timeStamp) { this.hintResize(); // Array-like check is enough here if (touches.length == null) { throw new Error("Invalid touch list: " + touches); } if (timeStamp instanceof Date) { timeStamp = timeStamp.valueOf(); } if (typeof timeStamp !== "number") { throw new Error("Invalid timestamp value: " + timeStamp); } var self = this; // Reset interruptedAnimation flag self.__interruptedAnimation = true; // Stop deceleration if (self.__isDecelerating) { core.effect.Animate.stop(self.__isDecelerating); self.__isDecelerating = false; self.__interruptedAnimation = true; } // Stop animation if (self.__isAnimating) { core.effect.Animate.stop(self.__isAnimating); self.__isAnimating = false; self.__interruptedAnimation = true; } // Use center point when dealing with two fingers var currentTouchLeft, currentTouchTop; var isSingleTouch = touches.length === 1; if (isSingleTouch) { currentTouchLeft = touches[0].pageX; currentTouchTop = touches[0].pageY; } else { currentTouchLeft = Math.abs(touches[0].pageX + touches[1].pageX) / 2; currentTouchTop = Math.abs(touches[0].pageY + touches[1].pageY) / 2; } // Store initial positions self.__initialTouchLeft = currentTouchLeft; self.__initialTouchTop = currentTouchTop; // Store current zoom level self.__zoomLevelStart = self.__zoomLevel; // Store initial touch positions self.__lastTouchLeft = currentTouchLeft; self.__lastTouchTop = currentTouchTop; // Store initial move time stamp self.__lastTouchMove = timeStamp; // Reset initial scale self.__lastScale = 1; // Reset locking flags self.__enableScrollX = !isSingleTouch && self.options.scrollingX; self.__enableScrollY = !isSingleTouch && self.options.scrollingY; // Reset tracking flag self.__isTracking = true; // Reset deceleration complete flag self.__didDecelerationComplete = false; // Dragging starts directly with two fingers, otherwise lazy with an offset self.__isDragging = !isSingleTouch; // Some features are disabled in multi touch scenarios self.__isSingleTouch = isSingleTouch; // Clearing data structure self.__positions = []; }, /** * Touch move handler for scrolling support */ doTouchMove: function(touches, timeStamp, scale) { // Array-like check is enough here if (touches.length == null) { throw new Error("Invalid touch list: " + touches); } if (timeStamp instanceof Date) { timeStamp = timeStamp.valueOf(); } if (typeof timeStamp !== "number") { throw new Error("Invalid timestamp value: " + timeStamp); } var self = this; // Ignore event when tracking is not enabled (event might be outside of element) if (!self.__isTracking) { return; } var currentTouchLeft, currentTouchTop; // Compute move based around of center of fingers if (touches.length === 2) { currentTouchLeft = Math.abs(touches[0].pageX + touches[1].pageX) / 2; currentTouchTop = Math.abs(touches[0].pageY + touches[1].pageY) / 2; } else { currentTouchLeft = touches[0].pageX; currentTouchTop = touches[0].pageY; } var positions = self.__positions; // Are we already is dragging mode? if (self.__isDragging) { // Compute move distance var moveX = currentTouchLeft - self.__lastTouchLeft; var moveY = currentTouchTop - self.__lastTouchTop; // Read previous scroll position and zooming var scrollLeft = self.__scrollLeft; var scrollTop = self.__scrollTop; var level = self.__zoomLevel; // Work with scaling if (scale != null && self.options.zooming) { var oldLevel = level; // Recompute level based on previous scale and new scale level = level / self.__lastScale * scale; // Limit level according to configuration level = Math.max(Math.min(level, self.options.maxZoom), self.options.minZoom); // Only do further compution when change happened if (oldLevel !== level) { // Compute relative event position to container var currentTouchLeftRel = currentTouchLeft - self.__clientLeft; var currentTouchTopRel = currentTouchTop - self.__clientTop; // Recompute left and top coordinates based on new zoom level scrollLeft = ((currentTouchLeftRel + scrollLeft) * level / oldLevel) - currentTouchLeftRel; scrollTop = ((currentTouchTopRel + scrollTop) * level / oldLevel) - currentTouchTopRel; // Recompute max scroll values self.__computeScrollMax(level); } } if (self.__enableScrollX) { scrollLeft -= moveX * this.options.speedMultiplier; var maxScrollLeft = self.__maxScrollLeft; if (scrollLeft > maxScrollLeft || scrollLeft < 0) { // Slow down on the edges if (self.options.bouncing) { scrollLeft += (moveX / 2 * this.options.speedMultiplier); } else if (scrollLeft > maxScrollLeft) { scrollLeft = maxScrollLeft; } else { scrollLeft = 0; } } } // Compute new vertical scroll position if (self.__enableScrollY) { scrollTop -= moveY * this.options.speedMultiplier; var maxScrollTop = self.__maxScrollTop; if (scrollTop > maxScrollTop || scrollTop < 0) { // Slow down on the edges if (self.options.bouncing) { scrollTop += (moveY / 2 * this.options.speedMultiplier); // Support pull-to-refresh (only when only y is scrollable) if (!self.__enableScrollX && self.__refreshHeight != null) { if (!self.__refreshActive && scrollTop <= -self.__refreshHeight) { self.__refreshActive = true; if (self.__refreshActivate) { self.__refreshActivate(); } } else if (self.__refreshActive && scrollTop > -self.__refreshHeight) { self.__refreshActive = false; if (self.__refreshDeactivate) { self.__refreshDeactivate(); } } } } else if (scrollTop > maxScrollTop) { scrollTop = maxScrollTop; } else { scrollTop = 0; } } } // Keep list from growing infinitely (holding min 10, max 20 measure points) if (positions.length > 60) { positions.splice(0, 30); } // Track scroll movement for decleration positions.push(scrollLeft, scrollTop, timeStamp); // Sync scroll position self.__publish(scrollLeft, scrollTop, level); // Otherwise figure out whether we are switching into dragging mode now. } else { var minimumTrackingForScroll = self.options.locking ? 3 : 0; var minimumTrackingForDrag = 5; var distanceX = Math.abs(currentTouchLeft - self.__initialTouchLeft); var distanceY = Math.abs(currentTouchTop - self.__initialTouchTop); self.__enableScrollX = self.options.scrollingX && distanceX >= minimumTrackingForScroll; self.__enableScrollY = self.options.scrollingY && distanceY >= minimumTrackingForScroll; positions.push(self.__scrollLeft, self.__scrollTop, timeStamp); self.__isDragging = (self.__enableScrollX || self.__enableScrollY) && (distanceX >= minimumTrackingForDrag || distanceY >= minimumTrackingForDrag); if (self.__isDragging) { self.__interruptedAnimation = false; } } // Update last touch positions and time stamp for next event self.__lastTouchLeft = currentTouchLeft; self.__lastTouchTop = currentTouchTop; self.__lastTouchMove = timeStamp; self.__lastScale = scale; }, /** * Touch end handler for scrolling support */ doTouchEnd: function(timeStamp) { if (timeStamp instanceof Date) { timeStamp = timeStamp.valueOf(); } if (typeof timeStamp !== "number") { throw new Error("Invalid timestamp value: " + timeStamp); } var self = this; // Ignore event when tracking is not enabled (no touchstart event on element) // This is required as this listener ('touchmove') sits on the document and not on the element itself. if (!self.__isTracking) { return; } // Not touching anymore (when two finger hit the screen there are two touch end events) self.__isTracking = false; // Be sure to reset the dragging flag now. Here we also detect whether // the finger has moved fast enough to switch into a deceleration animation. if (self.__isDragging) { // Reset dragging flag self.__isDragging = false; // Start deceleration // Verify that the last move detected was in some relevant time frame if (self.__isSingleTouch && self.options.animating && (timeStamp - self.__lastTouchMove) <= 100) { // Then figure out what the scroll position was about 100ms ago var positions = self.__positions; var endPos = positions.length - 1; var startPos = endPos; // Move pointer to position measured 100ms ago for (var i = endPos; i > 0 && positions[i] > (self.__lastTouchMove - 100); i -= 3) { startPos = i; } // If start and stop position is identical in a 100ms timeframe, // we cannot compute any useful deceleration. if (startPos !== endPos) { // Compute relative movement between these two points var timeOffset = positions[endPos] - positions[startPos]; var movedLeft = self.__scrollLeft - positions[startPos - 2]; var movedTop = self.__scrollTop - positions[startPos - 1]; // Based on 50ms compute the movement to apply for each render step self.__decelerationVelocityX = movedLeft / timeOffset * (1000 / 60); self.__decelerationVelocityY = movedTop / timeOffset * (1000 / 60); // How much velocity is required to start the deceleration var minVelocityToStartDeceleration = self.options.paging || self.options.snapping ? 4 : 1; // Verify that we have enough velocity to start deceleration if (Math.abs(self.__decelerationVelocityX) > minVelocityToStartDeceleration || Math.abs(self.__decelerationVelocityY) > minVelocityToStartDeceleration) { // Deactivate pull-to-refresh when decelerating if (!self.__refreshActive) { self.__startDeceleration(timeStamp); } } } else { self.options.scrollingComplete(); } } else if ((timeStamp - self.__lastTouchMove) > 100) { self.options.scrollingComplete(); } } // If this was a slower move it is per default non decelerated, but this // still means that we want snap back to the bounds which is done here. // This is placed outside the condition above to improve edge case stability // e.g. touchend fired without enabled dragging. This should normally do not // have modified the scroll positions or even showed the scrollbars though. if (!self.__isDecelerating) { if (self.__refreshActive && self.__refreshStart) { // Use publish instead of scrollTo to allow scrolling to out of boundary position // We don't need to normalize scrollLeft, zoomLevel, etc. here because we only y-scrolling when pull-to-refresh is enabled self.__publish(self.__scrollLeft, -self.__refreshHeight, self.__zoomLevel, true); if (self.__refreshStart) { self.__refreshStart(); } } else { if (self.__interruptedAnimation || self.__isDragging) { self.options.scrollingComplete(); } self.scrollTo(self.__scrollLeft, self.__scrollTop, true, self.__zoomLevel); // Directly signalize deactivation (nothing todo on refresh?) if (self.__refreshActive) { self.__refreshActive = false; if (self.__refreshDeactivate) { self.__refreshDeactivate(); } } } } // Fully cleanup list self.__positions.length = 0; }, /* --------------------------------------------------------------------------- PRIVATE API --------------------------------------------------------------------------- */ /** * Applies the scroll position to the content element * * @param left {Number} Left scroll position * @param top {Number} Top scroll position * @param animate {Boolean?false} Whether animation should be used to move to the new coordinates */ __publish: function(left, top, zoom, animate) { var self = this; // Remember whether we had an animation, then we try to continue based on the current "drive" of the animation var wasAnimating = self.__isAnimating; if (wasAnimating) { core.effect.Animate.stop(wasAnimating); self.__isAnimating = false; } if (animate && self.options.animating) { // Keep scheduled positions for scrollBy/zoomBy functionality self.__scheduledLeft = left; self.__scheduledTop = top; self.__scheduledZoom = zoom; var oldLeft = self.__scrollLeft; var oldTop = self.__scrollTop; var oldZoom = self.__zoomLevel; var diffLeft = left - oldLeft; var diffTop = top - oldTop; var diffZoom = zoom - oldZoom; var step = function(percent, now, render) { if (render) { self.__scrollLeft = oldLeft + (diffLeft * percent); self.__scrollTop = oldTop + (diffTop * percent); self.__zoomLevel = oldZoom + (diffZoom * percent); // Push values out if (self.__callback) { self.__callback(self.__scrollLeft, self.__scrollTop, self.__zoomLevel); } } }; var verify = function(id) { return self.__isAnimating === id; }; var completed = function(renderedFramesPerSecond, animationId, wasFinished) { if (animationId === self.__isAnimating) { self.__isAnimating = false; } if (self.__didDecelerationComplete || wasFinished) { self.options.scrollingComplete(); } if (self.options.zooming) { self.__computeScrollMax(); } }; // When continuing based on previous animation we choose an ease-out animation instead of ease-in-out self.__isAnimating = core.effect.Animate.start(step, verify, completed, self.options.animationDuration, wasAnimating ? easeOutCubic : easeInOutCubic); } else { self.__scheduledLeft = self.__scrollLeft = left; self.__scheduledTop = self.__scrollTop = top; self.__scheduledZoom = self.__zoomLevel = zoom; // Push values out if (self.__callback) { self.__callback(left, top, zoom); } // Fix max scroll ranges if (self.options.zooming) { self.__computeScrollMax(); } } }, /** * Recomputes scroll minimum values based on client dimensions and content dimensions. */ __computeScrollMax: function(zoomLevel) { var self = this; if (zoomLevel == null) { zoomLevel = self.__zoomLevel; } self.__maxScrollLeft = Math.max((self.__contentWidth * zoomLevel) - self.__clientWidth, 0); self.__maxScrollTop = Math.max((self.__contentHeight * zoomLevel) - self.__clientHeight, 0); }, /* --------------------------------------------------------------------------- ANIMATION (DECELERATION) SUPPORT --------------------------------------------------------------------------- */ /** * Called when a touch sequence end and the speed of the finger was high enough * to switch into deceleration mode. */ __startDeceleration: function(timeStamp) { var self = this; if (self.options.paging) { var scrollLeft = Math.max(Math.min(self.__scrollLeft, self.__maxScrollLeft), 0); var scrollTop = Math.max(Math.min(self.__scrollTop, self.__maxScrollTop), 0); var clientWidth = self.__clientWidth; var clientHeight = self.__clientHeight; // We limit deceleration not to the min/max values of the allowed range, but to the size of the visible client area. // Each page should have exactly the size of the client area. self.__minDecelerationScrollLeft = Math.floor(scrollLeft / clientWidth) * clientWidth; self.__minDecelerationScrollTop = Math.floor(scrollTop / clientHeight) * clientHeight; self.__maxDecelerationScrollLeft = Math.ceil(scrollLeft / clientWidth) * clientWidth; self.__maxDecelerationScrollTop = Math.ceil(scrollTop / clientHeight) * clientHeight; } else { self.__minDecelerationScrollLeft = 0; self.__minDecelerationScrollTop = 0; self.__maxDecelerationScrollLeft = self.__maxScrollLeft; self.__maxDecelerationScrollTop = self.__maxScrollTop; } // Wrap class method var step = function(percent, now, render) { self.__stepThroughDeceleration(render); }; // How much velocity is required to keep the deceleration running var minVelocityToKeepDecelerating = self.options.snapping ? 4 : 0.1; // Detect whether it's still worth to continue animating steps // If we are already slow enough to not being user perceivable anymore, we stop the whole process here. var verify = function() { var shouldContinue = Math.abs(self.__decelerationVelocityX) >= minVelocityToKeepDecelerating || Math.abs(self.__decelerationVelocityY) >= minVelocityToKeepDecelerating; if (!shouldContinue) { self.__didDecelerationComplete = true; } return shouldContinue; }; var completed = function(renderedFramesPerSecond, animationId, wasFinished) { self.__isDecelerating = false; if (self.__didDecelerationComplete) { self.options.scrollingComplete(); } // Animate to grid when snapping is active, otherwise just fix out-of-boundary positions self.scrollTo(self.__scrollLeft, self.__scrollTop, self.options.snapping); }; // Start animation and switch on flag self.__isDecelerating = core.effect.Animate.start(step, verify, completed); }, /** * Called on every step of the animation * * @param inMemory {Boolean?false} Whether to not render the current step, but keep it in memory only. Used internally only! */ __stepThroughDeceleration: function(render) { var self = this; // // COMPUTE NEXT SCROLL POSITION // // Add deceleration to scroll position var scrollLeft = self.__scrollLeft + self.__decelerationVelocityX; var scrollTop = self.__scrollTop + self.__decelerationVelocityY; // // HARD LIMIT SCROLL POSITION FOR NON BOUNCING MODE // if (!self.options.bouncing) { var scrollLeftFixed = Math.max(Math.min(self.__maxDecelerationScrollLeft, scrollLeft), self.__minDecelerationScrollLeft); if (scrollLeftFixed !== scrollLeft) { scrollLeft = scrollLeftFixed; self.__decelerationVelocityX = 0; } var scrollTopFixed = Math.max(Math.min(self.__maxDecelerationScrollTop, scrollTop), self.__minDecelerationScrollTop); if (scrollTopFixed !== scrollTop) { scrollTop = scrollTopFixed; self.__decelerationVelocityY = 0; } } // // UPDATE SCROLL POSITION // if (render) { self.__publish(scrollLeft, scrollTop, self.__zoomLevel); } else { self.__scrollLeft = scrollLeft; self.__scrollTop = scrollTop; } // // SLOW DOWN // // Slow down velocity on every iteration if (!self.options.paging) { // This is the factor applied to every iteration of the animation // to slow down the process. This should emulate natural behavior where // objects slow down when the initiator of the movement is removed var frictionFactor = 0.95; self.__decelerationVelocityX *= frictionFactor; self.__decelerationVelocityY *= frictionFactor; } // // BOUNCING SUPPORT // if (self.options.bouncing) { var scrollOutsideX = 0; var scrollOutsideY = 0; // This configures the amount of change applied to deceleration/acceleration when reaching boundaries var penetrationDeceleration = self.options.penetrationDeceleration; var penetrationAcceleration = self.options.penetrationAcceleration; // Check limits if (scrollLeft < self.__minDecelerationScrollLeft) { scrollOutsideX = self.__minDecelerationScrollLeft - scrollLeft; } else if (scrollLeft > self.__maxDecelerationScrollLeft) { scrollOutsideX = self.__maxDecelerationScrollLeft - scrollLeft; } if (scrollTop < self.__minDecelerationScrollTop) { scrollOutsideY = self.__minDecelerationScrollTop - scrollTop; } else if (scrollTop > self.__maxDecelerationScrollTop) { scrollOutsideY = self.__maxDecelerationScrollTop - scrollTop; } // Slow down until slow enough, then flip back to snap position if (scrollOutsideX !== 0) { if (scrollOutsideX * self.__decelerationVelocityX <= 0) { self.__decelerationVelocityX += scrollOutsideX * penetrationDeceleration; } else { self.__decelerationVelocityX = scrollOutsideX * penetrationAcceleration; } } if (scrollOutsideY !== 0) { if (scrollOutsideY * self.__decelerationVelocityY <= 0) { self.__decelerationVelocityY += scrollOutsideY * penetrationDeceleration; } else { self.__decelerationVelocityY = scrollOutsideY * penetrationAcceleration; } } } } }); })(ionic); ; (function(ionic) { 'use strict'; /** * An ActionSheet is the slide up menu popularized on iOS. * * You see it all over iOS apps, where it offers a set of options * triggered after an action. */ ionic.views.ActionSheet = ionic.views.View.inherit({ initialize: function(opts) { this.el = opts.el; }, show: function() { // Force a reflow so the animation will actually run this.el.offsetWidth; this.el.classList.add('active'); }, hide: function() { // Force a reflow so the animation will actually run this.el.offsetWidth; this.el.classList.remove('active'); } }); })(ionic); ; (function(ionic) { 'use strict'; ionic.views.HeaderBar = ionic.views.View.inherit({ initialize: function(opts) { this.el = opts.el; ionic.extend(this, { alignTitle: 'center' }, opts); this.align(); }, /** * Align the title text given the buttons in the header * so that the header text size is maximized and aligned * correctly as long as possible. */ align: function() { var _this = this; window.rAF(ionic.proxy(function() { var i, c, childSize; var childNodes = this.el.childNodes; // Find the title element var title = this.el.querySelector('.title'); if(!title) { return; } var leftWidth = 0; var rightWidth = 0; var titlePos = Array.prototype.indexOf.call(childNodes, title); // Compute how wide the left children are for(i = 0; i < titlePos; i++) { childSize = null; c = childNodes[i]; if(c.nodeType == 3) { childSize = ionic.DomUtil.getTextBounds(c); } else if(c.nodeType == 1) { childSize = c.getBoundingClientRect(); } if(childSize) { leftWidth += childSize.width; } } // Compute how wide the right children are for(i = titlePos + 1; i < childNodes.length; i++) { childSize = null; c = childNodes[i]; if(c.nodeType == 3) { childSize = ionic.DomUtil.getTextBounds(c); } else if(c.nodeType == 1) { childSize = c.getBoundingClientRect(); } if(childSize) { rightWidth += childSize.width; } } var margin = Math.max(leftWidth, rightWidth) + 10; // Size and align the header title based on the sizes of the left and // right children, and the desired alignment mode if(this.alignTitle == 'center') { if(margin > 10) { title.style.left = margin + 'px'; title.style.right = margin + 'px'; } if(title.offsetWidth < title.scrollWidth) { if(rightWidth > 0) { title.style.right = (rightWidth + 5) + 'px'; } } } else if(this.alignTitle == 'left') { title.classList.add('title-left'); if(leftWidth > 0) { title.style.left = (leftWidth + 15) + 'px'; } } else if(this.alignTitle == 'right') { title.classList.add('title-right'); if(rightWidth > 0) { title.style.right = (rightWidth + 15) + 'px'; } } }, this)); } }); })(ionic); ; (function(ionic) { 'use strict'; var ITEM_CLASS = 'item'; var ITEM_CONTENT_CLASS = 'item-content'; var ITEM_SLIDING_CLASS = 'item-sliding'; var ITEM_OPTIONS_CLASS = 'item-options'; var ITEM_PLACEHOLDER_CLASS = 'item-placeholder'; var ITEM_REORDERING_CLASS = 'item-reordering'; var ITEM_DRAG_CLASS = 'item-drag'; var DragOp = function() {}; DragOp.prototype = { start: function(e) { }, drag: function(e) { }, end: function(e) { } }; var SlideDrag = function(opts) { this.dragThresholdX = opts.dragThresholdX || 10; this.el = opts.el; }; SlideDrag.prototype = new DragOp(); SlideDrag.prototype.start = function(e) { var content, buttons, offsetX, buttonsWidth; if(e.target.classList.contains(ITEM_CONTENT_CLASS)) { content = e.target; } else if(e.target.classList.contains(ITEM_CLASS)) { content = e.target.querySelector('.' + ITEM_CONTENT_CLASS); } // If we don't have a content area as one of our children (or ourselves), skip if(!content) { return; } // Make sure we aren't animating as we slide content.classList.remove(ITEM_SLIDING_CLASS); // Grab the starting X point for the item (for example, so we can tell whether it is open or closed to start) offsetX = parseFloat(content.style.webkitTransform.replace('translate3d(', '').split(',')[0]) || 0; // Grab the buttons buttons = content.parentNode.querySelector('.' + ITEM_OPTIONS_CLASS); if(!buttons) { return; } buttonsWidth = buttons.offsetWidth; this._currentDrag = { buttonsWidth: buttonsWidth, content: content, startOffsetX: offsetX }; }; SlideDrag.prototype.drag = function(e) { var _this = this, buttonsWidth; window.rAF(function() { // We really aren't dragging if(!_this._currentDrag) { return; } // Check if we should start dragging. Check if we've dragged past the threshold, // or we are starting from the open state. if(!_this._isDragging && ((Math.abs(e.gesture.deltaX) > _this.dragThresholdX) || (Math.abs(_this._currentDrag.startOffsetX) > 0))) { _this._isDragging = true; } if(_this._isDragging) { buttonsWidth = _this._currentDrag.buttonsWidth; // Grab the new X point, capping it at zero var newX = Math.min(0, _this._currentDrag.startOffsetX + e.gesture.deltaX); // If the new X position is past the buttons, we need to slow down the drag (rubber band style) if(newX < -buttonsWidth) { // Calculate the new X position, capped at the top of the buttons newX = Math.min(-buttonsWidth, -buttonsWidth + (((e.gesture.deltaX + buttonsWidth) * 0.4))); } _this._currentDrag.content.style.webkitTransform = 'translate3d(' + newX + 'px, 0, 0)'; } }); }; SlideDrag.prototype.end = function(e, doneCallback) { var _this = this; // There is no drag, just end immediately if(!this._currentDrag) { doneCallback && doneCallback(); return; } // If we are currently dragging, we want to snap back into place // The final resting point X will be the width of the exposed buttons var restingPoint = -this._currentDrag.buttonsWidth; // Check if the drag didn't clear the buttons mid-point // and we aren't moving fast enough to swipe open if(e.gesture.deltaX > -(this._currentDrag.buttonsWidth/2)) { // If we are going left but too slow, or going right, go back to resting if(e.gesture.direction == "left" && Math.abs(e.gesture.velocityX) < 0.3) { restingPoint = 0; } else if(e.gesture.direction == "right") { restingPoint = 0; } } var content = this._currentDrag.content; var onRestingAnimationEnd = function(e) { if(e.propertyName == '-webkit-transform') { content.classList.remove(ITEM_SLIDING_CLASS); } e.target.removeEventListener('webkitTransitionEnd', onRestingAnimationEnd); }; window.rAF(function() { var currentX = parseFloat(_this._currentDrag.content.style.webkitTransform.replace('translate3d(', '').split(',')[0]) || 0; if(currentX !== restingPoint) { _this._currentDrag.content.classList.add(ITEM_SLIDING_CLASS); _this._currentDrag.content.addEventListener('webkitTransitionEnd', onRestingAnimationEnd); } _this._currentDrag.content.style.webkitTransform = 'translate3d(' + restingPoint + 'px, 0, 0)'; // Kill the current drag _this._currentDrag = null; // We are done, notify caller doneCallback && doneCallback(); }); }; var ReorderDrag = function(opts) { this.dragThresholdY = opts.dragThresholdY || 0; this.onReorder = opts.onReorder; this.el = opts.el; }; ReorderDrag.prototype = new DragOp(); ReorderDrag.prototype.start = function(e) { var content; // Grab the starting Y point for the item var offsetY = this.el.offsetTop;//parseFloat(this.el.style.webkitTransform.replace('translate3d(', '').split(',')[1]) || 0; var startIndex = ionic.DomUtil.getChildIndex(this.el, this.el.nodeName.toLowerCase()); var placeholder = this.el.cloneNode(true); placeholder.classList.add(ITEM_PLACEHOLDER_CLASS); this.el.parentNode.insertBefore(placeholder, this.el); this.el.classList.add(ITEM_REORDERING_CLASS); this._currentDrag = { startOffsetTop: offsetY, startIndex: startIndex, placeholder: placeholder }; }; ReorderDrag.prototype.drag = function(e) { var _this = this; window.rAF(function() { // We really aren't dragging if(!_this._currentDrag) { return; } // Check if we should start dragging. Check if we've dragged past the threshold, // or we are starting from the open state. if(!_this._isDragging && Math.abs(e.gesture.deltaY) > _this.dragThresholdY) { _this._isDragging = true; } if(_this._isDragging) { var newY = _this._currentDrag.startOffsetTop + e.gesture.deltaY; _this.el.style.top = newY + 'px'; _this._currentDrag.currentY = newY; _this._reorderItems(); } }); }; // When an item is dragged, we need to reorder any items for sorting purposes ReorderDrag.prototype._reorderItems = function() { var placeholder = this._currentDrag.placeholder; var siblings = Array.prototype.slice.call(this._currentDrag.placeholder.parentNode.children); // Remove the floating element from the child search list siblings.splice(siblings.indexOf(this.el), 1); var index = siblings.indexOf(this._currentDrag.placeholder); var topSibling = siblings[Math.max(0, index - 1)]; var bottomSibling = siblings[Math.min(siblings.length, index+1)]; var thisOffsetTop = this._currentDrag.currentY;// + this._currentDrag.startOffsetTop; if(topSibling && (thisOffsetTop < topSibling.offsetTop + topSibling.offsetHeight/2)) { ionic.DomUtil.swapNodes(this._currentDrag.placeholder, topSibling); return index - 1; } else if(bottomSibling && thisOffsetTop > (bottomSibling.offsetTop + bottomSibling.offsetHeight/2)) { ionic.DomUtil.swapNodes(bottomSibling, this._currentDrag.placeholder); return index + 1; } }; ReorderDrag.prototype.end = function(e, doneCallback) { if(!this._currentDrag) { doneCallback && doneCallback(); return; } var placeholder = this._currentDrag.placeholder; // Reposition the element this.el.classList.remove(ITEM_REORDERING_CLASS); this.el.style.top = 0; var finalPosition = ionic.DomUtil.getChildIndex(placeholder, placeholder.nodeName.toLowerCase()); placeholder.parentNode.insertBefore(this.el, placeholder); placeholder.parentNode.removeChild(placeholder); this.onReorder && this.onReorder(this.el, this._currentDrag.startIndex, finalPosition); this._currentDrag = null; doneCallback && doneCallback(); }; /** * The ListView handles a list of items. It will process drag animations, edit mode, * and other operations that are common on mobile lists or table views. */ ionic.views.ListView = ionic.views.View.inherit({ initialize: function(opts) { var _this = this; opts = ionic.extend({ onReorder: function(el, oldIndex, newIndex) {}, virtualRemoveThreshold: -200, virtualAddThreshold: 200 }, opts); ionic.extend(this, opts); if(!this.itemHeight && this.listEl) { this.itemHeight = this.listEl.children[0] && parseInt(this.listEl.children[0].style.height, 10); } //ionic.views.ListView.__super__.initialize.call(this, opts); this.onRefresh = opts.onRefresh || function() {}; this.onRefreshOpening = opts.onRefreshOpening || function() {}; this.onRefreshHolding = opts.onRefreshHolding || function() {}; window.ionic.onGesture('touch', function(e) { _this._handleTouch(e); }, this.el); window.ionic.onGesture('release', function(e) { _this._handleTouchRelease(e); }, this.el); // Start the drag states this._initDrag(); }, /** * Called to tell the list to stop refreshing. This is useful * if you are refreshing the list and are done with refreshing. */ stopRefreshing: function() { var refresher = this.el.querySelector('.list-refresher'); refresher.style.height = '0px'; }, /** * If we scrolled and have virtual mode enabled, compute the window * of active elements in order to figure out the viewport to render. */ didScroll: function(e) { if(this.isVirtual) { var itemHeight = this.itemHeight; // TODO: This would be inaccurate if we are windowed var totalItems = this.listEl.children.length; // Grab the total height of the list var scrollHeight = e.target.scrollHeight; // Get the viewport height var viewportHeight = this.el.parentNode.offsetHeight; // scrollTop is the current scroll position var scrollTop = e.scrollTop; // High water is the pixel position of the first element to include (everything before // that will be removed) var highWater = Math.max(0, e.scrollTop + this.virtualRemoveThreshold); // Low water is the pixel position of the last element to include (everything after // that will be removed) var lowWater = Math.min(scrollHeight, Math.abs(e.scrollTop) + viewportHeight + this.virtualAddThreshold); // Compute how many items per viewport size can show var itemsPerViewport = Math.floor((lowWater - highWater) / itemHeight); // Get the first and last elements in the list based on how many can fit // between the pixel range of lowWater and highWater var first = parseInt(Math.abs(highWater / itemHeight), 10); var last = parseInt(Math.abs(lowWater / itemHeight), 10); // Get the items we need to remove this._virtualItemsToRemove = Array.prototype.slice.call(this.listEl.children, 0, first); // Grab the nodes we will be showing var nodes = Array.prototype.slice.call(this.listEl.children, first, first + itemsPerViewport); this.renderViewport && this.renderViewport(highWater, lowWater, first, last); } }, didStopScrolling: function(e) { if(this.isVirtual) { for(var i = 0; i < this._virtualItemsToRemove.length; i++) { var el = this._virtualItemsToRemove[i]; //el.parentNode.removeChild(el); this.didHideItem && this.didHideItem(i); } // Once scrolling stops, check if we need to remove old items } }, _initDrag: function() { //ionic.views.ListView.__super__._initDrag.call(this); //this._isDragging = false; this._dragOp = null; }, // Return the list item from the given target _getItem: function(target) { while(target) { if(target.classList.contains(ITEM_CLASS)) { return target; } target = target.parentNode; } return null; }, _startDrag: function(e) { var _this = this; this._isDragging = false; // Check if this is a reorder drag if(ionic.DomUtil.getParentOrSelfWithClass(e.target, ITEM_DRAG_CLASS) && (e.gesture.direction == 'up' || e.gesture.direction == 'down')) { var item = this._getItem(e.target); if(item) { this._dragOp = new ReorderDrag({ el: item, onReorder: function(el, start, end) { _this.onReorder && _this.onReorder(el, start, end); } }); this._dragOp.start(e); e.preventDefault(); return; } } // Or check if this is a swipe to the side drag else if((e.gesture.direction == 'left' || e.gesture.direction == 'right') && Math.abs(e.gesture.deltaX) > 5) { this._dragOp = new SlideDrag({ el: this.el }); this._dragOp.start(e); e.preventDefault(); return; } // We aren't handling it, so pass it up the chain //ionic.views.ListView.__super__._startDrag.call(this, e); }, _handleEndDrag: function(e) { var _this = this; if(!this._dragOp) { //ionic.views.ListView.__super__._handleEndDrag.call(this, e); return; } this._dragOp.end(e, function() { _this._initDrag(); }); }, /** * Process the drag event to move the item to the left or right. */ _handleDrag: function(e) { var _this = this, content, buttons; // If the user has a touch timeout to highlight an element, clear it if we // get sufficient draggage if(Math.abs(e.gesture.deltaX) > 10 || Math.abs(e.gesture.deltaY) > 10) { clearTimeout(this._touchTimeout); } clearTimeout(this._touchTimeout); // If we get a drag event, make sure we aren't in another drag, then check if we should // start one if(!this.isDragging && !this._dragOp) { this._startDrag(e); } // No drag still, pass it up if(!this._dragOp) { //ionic.views.ListView.__super__._handleDrag.call(this, e); return; } e.preventDefault(); this._dragOp.drag(e); }, /** * Handle the touch event to show the active state on an item if necessary. */ _handleTouch: function(e) { var _this = this; var item = ionic.DomUtil.getParentOrSelfWithClass(e.target, ITEM_CLASS); if(!item) { return; } this._touchTimeout = setTimeout(function() { var items = _this.el.querySelectorAll('.item'); for(var i = 0, l = items.length; i < l; i++) { items[i].classList.remove('active'); } item.classList.add('active'); }, 250); }, /** * Handle the release event to remove the active state on an item if necessary. */ _handleTouchRelease: function(e) { var _this = this; // Cancel touch timeout clearTimeout(this._touchTimeout); var items = _this.el.querySelectorAll('.item'); for(var i = 0, l = items.length; i < l; i++) { items[i].classList.remove('active'); } } }); })(ionic); ; (function(ionic) { 'use strict'; /** * An ActionSheet is the slide up menu popularized on iOS. * * You see it all over iOS apps, where it offers a set of options * triggered after an action. */ ionic.views.Loading = ionic.views.View.inherit({ initialize: function(opts) { var _this = this; this.el = opts.el; this.maxWidth = opts.maxWidth || 200; this._loadingBox = this.el.querySelector('.loading'); }, show: function() { var _this = this; if(this._loadingBox) { var lb = _this._loadingBox; var width = Math.min(_this.maxWidth, Math.max(window.outerWidth - 40, lb.offsetWidth)); lb.style.width = width; lb.style.marginLeft = (-lb.offsetWidth) / 2 + 'px'; lb.style.marginTop = (-lb.offsetHeight) / 2 + 'px'; _this.el.classList.add('active'); } }, hide: function() { // Force a reflow so the animation will actually run this.el.offsetWidth; this.el.classList.remove('active'); } }); })(ionic); ; (function(ionic) { 'use strict'; ionic.views.Modal = ionic.views.View.inherit({ initialize: function(opts) { opts = ionic.extend({ focusFirstInput: false, unfocusOnHide: true }, opts); ionic.extend(this, opts); this.el = opts.el; }, show: function() { this.el.classList.add('active'); if(this.focusFirstInput) { var input = this.el.querySelector('input, textarea'); input && input.focus && input.focus(); } }, hide: function() { this.el.classList.remove('active'); // Unfocus all elements if(this.unfocusOnHide) { var inputs = this.el.querySelectorAll('input, textarea'); for(var i = 0; i < inputs.length; i++) { inputs[i].blur && inputs[i].blur(); } } } }); })(ionic); ; (function(ionic) { 'use strict'; ionic.views.NavBar = ionic.views.View.inherit({ initialize: function(opts) { this.el = opts.el; this._titleEl = this.el.querySelector('.title'); if(opts.hidden) { this.hide(); } }, hide: function() { this.el.classList.add('hidden'); }, show: function() { this.el.classList.remove('hidden'); }, shouldGoBack: function() {}, setTitle: function(title) { if(!this._titleEl) { return; } this._titleEl.innerHTML = title; }, showBackButton: function(shouldShow) { var _this = this; if(!this._currentBackButton) { var back = document.createElement('a'); back.className = 'button back'; back.innerHTML = 'Back'; this._currentBackButton = back; this._currentBackButton.onclick = function(event) { _this.shouldGoBack && _this.shouldGoBack(); }; } if(shouldShow && !this._currentBackButton.parentNode) { // Prepend the back button this.el.insertBefore(this._currentBackButton, this.el.firstChild); } else if(!shouldShow && this._currentBackButton.parentNode) { // Remove the back button if it's there this._currentBackButton.parentNode.removeChild(this._currentBackButton); } } }); })(ionic); ; (function(ionic) { 'use strict'; /** * An ActionSheet is the slide up menu popularized on iOS. * * You see it all over iOS apps, where it offers a set of options * triggered after an action. */ ionic.views.Popup = ionic.views.View.inherit({ initialize: function(opts) { var _this = this; this.el = opts.el; }, setTitle: function(title) { var titleEl = el.querySelector('.popup-title'); if(titleEl) { titleEl.innerHTML = title; } }, alert: function(message) { var _this = this; window.rAF(function() { _this.setTitle(message); _this.el.classList.add('active'); }); }, hide: function() { // Force a reflow so the animation will actually run this.el.offsetWidth; this.el.classList.remove('active'); } }); })(ionic); ; (function(ionic) { 'use strict'; /** * The side menu view handles one of the side menu's in a Side Menu Controller * configuration. * It takes a DOM reference to that side menu element. */ ionic.views.SideMenu = ionic.views.View.inherit({ initialize: function(opts) { this.el = opts.el; this.width = opts.width; this.isEnabled = opts.isEnabled || true; }, getFullWidth: function() { return this.width; }, setIsEnabled: function(isEnabled) { this.isEnabled = isEnabled; }, bringUp: function() { this.el.style.zIndex = 0; }, pushDown: function() { this.el.style.zIndex = -1; } }); ionic.views.SideMenuContent = ionic.views.View.inherit({ initialize: function(opts) { var _this = this; ionic.extend(this, { animationClass: 'menu-animated', onDrag: function(e) {}, onEndDrag: function(e) {}, }, opts); ionic.onGesture('drag', ionic.proxy(this._onDrag, this), this.el); ionic.onGesture('release', ionic.proxy(this._onEndDrag, this), this.el); }, _onDrag: function(e) { this.onDrag && this.onDrag(e); }, _onEndDrag: function(e) { this.onEndDrag && this.onEndDrag(e); }, disableAnimation: function() { this.el.classList.remove(this.animationClass); }, enableAnimation: function() { this.el.classList.add(this.animationClass); }, getTranslateX: function() { return parseFloat(this.el.style.webkitTransform.replace('translate3d(', '').split(',')[0]); }, setTranslateX: function(x) { this.el.style.webkitTransform = 'translate3d(' + x + 'px, 0, 0)'; } }); })(ionic); ; /** * The SlideBox is a swipeable, slidable, slideshowable box. Think of any image gallery * or iOS "dot" pager gallery, or maybe a carousel. * * Each screen fills the full width and height of the viewport, and screens can * be swiped between, or set to automatically transition. */ (function(ionic) { 'use strict'; ionic.views.SlideBox = ionic.views.View.inherit({ initialize: function(opts) { var _this = this; this.slideChanged = opts.slideChanged || function() {}; this.el = opts.el; this.pager = this.el.querySelector('.slide-box-pager'); // The drag threshold is the pixel delta that will trigger a drag (to // avoid accidental dragging) this.dragThresholdX = opts.dragThresholdX || 10; // The velocity threshold is a velocity of drag that indicates a "swipe". This // number is taken from hammer.js's calculations this.velocityXThreshold = opts.velocityXThreshold || 0.3; // Initialize the slide index to the first page and update the pager this.slideIndex = 0; this._updatePager(); // Listen for drag and release events window.ionic.onGesture('drag', function(e) { _this._handleDrag(e); e.gesture.srcEvent.preventDefault(); }, this.el); window.ionic.onGesture('release', function(e) { _this._handleEndDrag(e); }, this.el); }, /** * Tell the pager to update itself if content is added or * removed. */ update: function() { this._updatePager(); }, prependSlide: function(el) { var content = this.el.firstElementChild; if(!content) { return; } var slideWidth = content.offsetWidth; var offsetX = parseFloat(content.style.webkitTransform.replace('translate3d(', '').split(',')[0]) || 0; var newOffsetX = Math.min(0, offsetX - slideWidth); content.insertBefore(el, content.firstChild); content.classList.remove('slide-box-animating'); content.style.webkitTransform = 'translate3d(' + newOffsetX + 'px, 0, 0)'; this._prependPagerIcon(); this.slideIndex = (this.slideIndex + 1) % content.children.length; this._updatePager(); }, appendSlide: function(el) { var content = this.el.firstElementChild; if(!content) { return; } content.classList.remove('slide-box-animating'); content.appendChild(el); this._appendPagerIcon(); this._updatePager(); }, removeSlide: function(index) { var content = this.el.firstElementChild; if(!content) { return; } var items = this.el.firstElementChild; items.removeChild(items.firstElementChild); var slideWidth = content.offsetWidth; var offsetX = parseFloat(content.style.webkitTransform.replace('translate3d(', '').split(',')[0]) || 0; var newOffsetX = Math.min(0, offsetX + slideWidth); content.classList.remove('slide-box-animating'); content.style.webkitTransform = 'translate3d(' + newOffsetX + 'px, 0, 0)'; this._removePagerIcon(); this.slideIndex = Math.max(0, (this.slideIndex - 1) % content.children.length); this._updatePager(); }, /** * Slide to the given slide index. * * @param {int} the index of the slide to animate to. */ slideToSlide: function(index) { var content = this.el.firstElementChild; if(!content) { return; } // Get the width of one slide var slideWidth = content.offsetWidth; // Calculate the new offsetX position which is just // N slides to the left, where N is the given index var offsetX = index * slideWidth; // Calculate the max X position we'd allow based on how many slides // there are. var maxX = Math.max(0, content.children.length - 1) * slideWidth; // Bounds the offset X position in the range maxX >= offsetX >= 0 offsetX = offsetX < 0 ? 0 : offsetX > maxX ? maxX : offsetX; // Animate and slide the slides over content.classList.add('slide-box-animating'); content.style.webkitTransform = 'translate3d(' + -offsetX + 'px, 0, 0)'; var lastSlide = this.slideIndex; // Update the slide index this.slideIndex = Math.ceil(offsetX / slideWidth); if(lastSlide !== this.slideIndex) { this.slideChanged && this.slideChanged(this.slideIndex); } this._updatePager(); }, /** * Get the currently set slide index. This method * is updated before any transitions run, so the * value could be early. * * @return {int} the current slide index */ getSlideIndex: function() { return this.slideIndex; }, _appendPagerIcon: function() { if(!this.pager || !this.pager.children.length) { return; } var newPagerChild = this.pager.children[0].cloneNode(); this.pager.appendChild(newPagerChild); }, _prependPagerIcon: function() { if(!this.pager || !this.pager.children.length) { return; } var newPagerChild = this.pager.children[0].cloneNode(); this.pager.insertBefore(newPagerChild, this.pager.firstChild); }, _removePagerIcon: function() { if(!this.pager || !this.pager.children.length) { return; } this.pager.removeChild(this.pager.firstElementChild); }, /** * If we have a pager, update the active page when the current slide * changes. */ _updatePager: function() { if(!this.pager) { return; } var numPagerChildren = this.pager.children.length; if(!numPagerChildren) { // No children to update return; } // Update the active state of the pager icons for(var i = 0, j = this.pager.children.length; i < j; i++) { if(i == this.slideIndex) { this.pager.children[i].classList.add('active'); } else { this.pager.children[i].classList.remove('active'); } } }, _initDrag: function() { this._isDragging = false; this._drag = null; }, _handleEndDrag: function(e) { var _this = this, finalOffsetX, content, ratio, slideWidth, totalWidth, offsetX; window.rAF(function() { // We didn't have a drag, so just init and leave if(!_this._drag) { _this._initDrag(); return; } // We did have a drag, so we need to snap to the correct spot // Grab the content layer content = _this._drag.content; // Enable transition duration content.classList.add('slide-box-animating'); // Grab the current offset X position offsetX = parseFloat(content.style.webkitTransform.replace('translate3d(', '').split(',')[0]) || 0; // Calculate how wide a single slide is, and their total width slideWidth = content.offsetWidth; totalWidth = content.offsetWidth * content.children.length; // Calculate how far in this slide we've dragged ratio = (offsetX % slideWidth) / slideWidth; if(ratio >= 0) { // Anything greater than zero is too far left, this is an extreme case // TODO: Do we need this anymore? finalOffsetX = 0; } else if(ratio >= -0.5) { // We are less than half-way through a drag // Sliiide to the left finalOffsetX = Math.max(0, Math.floor(Math.abs(offsetX) / slideWidth) * slideWidth); } else { // We are more than half-way through a drag // Sliiide to the right finalOffsetX = Math.min(totalWidth - slideWidth, Math.ceil(Math.abs(offsetX) / slideWidth) * slideWidth); } if(e.gesture.velocityX > _this.velocityXThreshold) { if(e.gesture.direction == 'left') { _this.slideToSlide(_this.slideIndex + 1); } else if(e.gesture.direction == 'right') { _this.slideToSlide(_this.slideIndex - 1); } } else { // Calculate the new slide index (or "page") _this.slideIndex = Math.ceil(finalOffsetX / slideWidth); // Negative offsetX to slide correctly content.style.webkitTransform = 'translate3d(' + -finalOffsetX + 'px, 0, 0)'; } _this._initDrag(); }); }, /** * Initialize a drag by grabbing the content area to drag, and any other * info we might need for the dragging. */ _startDrag: function(e) { var offsetX, content; this._initDrag(); // Make sure to grab the element we will slide as our target content = ionic.DomUtil.getParentOrSelfWithClass(e.target, 'slide-box-slides'); if(!content) { return; } // Disable transitions during drag content.classList.remove('slide-box-animating'); // Grab the starting X point for the item (for example, so we can tell whether it is open or closed to start) offsetX = parseFloat(content.style.webkitTransform.replace('translate3d(', '').split(',')[0]) || 0; this._drag = { content: content, startOffsetX: offsetX, resist: 1 }; }, /** * Process the drag event to move the item to the left or right. */ _handleDrag: function(e) { var _this = this; window.rAF(function() { var content; // We really aren't dragging if(!_this._drag) { _this._startDrag(e); } // Sanity if(!_this._drag) { return; } // Stop any default events during the drag e.preventDefault(); // Check if we should start dragging. Check if we've dragged past the threshold. if(!_this._isDragging && (Math.abs(e.gesture.deltaX) > _this.dragThresholdX)) { _this._isDragging = true; } if(_this._isDragging) { content = _this._drag.content; var newX = _this._drag.startOffsetX + (e.gesture.deltaX / _this._drag.resist); var rightMostX = -(content.offsetWidth * Math.max(0, content.children.length - 1)); if(newX > 0) { // We are dragging past the leftmost pane, rubber band _this._drag.resist = (newX / content.offsetWidth) + 1.4; } else if(newX < rightMostX) { // Dragging past the rightmost pane, rubber band //newX = Math.min(rightMostX, + (((e.gesture.deltaX + buttonsWidth) * 0.4))); _this._drag.resist = (Math.abs(newX) / content.offsetWidth) - 0.6; } _this._drag.content.style.webkitTransform = 'translate3d(' + newX + 'px, 0, 0)'; } }); } }); })(window.ionic); ; (function(ionic) { 'use strict'; ionic.views.TabBarItem = ionic.views.View.inherit({ initialize: function(el) { this.el = el; this._buildItem(); }, // Factory for creating an item from a given javascript object create: function(itemData) { var item = document.createElement('a'); item.className = 'tab-item'; // If there is an icon, add the icon element if(itemData.icon) { var icon = document.createElement('i'); icon.className = itemData.icon; item.appendChild(icon); } item.appendChild(document.createTextNode(itemData.title)); return new ionic.views.TabBarItem(item); }, _buildItem: function() { var _this = this, child, children = Array.prototype.slice.call(this.el.children); for(var i = 0, j = children.length; i < j; i++) { child = children[i]; // Test if this is a "i" tag with icon in the class name // TODO: This heuristic might not be sufficient if(child.tagName.toLowerCase() == 'i' && /icon/.test(child.className)) { this.icon = child.className; break; } } // Set the title to the text content of the tab. this.title = this.el.textContent.trim(); this._tapHandler = function(e) { _this.onTap && _this.onTap(e); }; ionic.on('tap', this._tapHandler, this.el); }, onTap: function(e) { }, // Remove the event listeners from this object destroy: function() { ionic.off('tap', this._tapHandler, this.el); }, getIcon: function() { return this.icon; }, getTitle: function() { return this.title; }, setSelected: function(isSelected) { this.isSelected = isSelected; if(isSelected) { this.el.classList.add('active'); } else { this.el.classList.remove('active'); } } }); ionic.views.TabBar = ionic.views.View.inherit({ initialize: function(opts) { this.el = opts.el; this.items = []; this._buildItems(); }, // get all the items for the TabBar getItems: function() { return this.items; }, // Add an item to the tab bar addItem: function(item) { // Create a new TabItem var tabItem = ionic.views.TabBarItem.prototype.create(item); this.appendItemElement(tabItem); this.items.push(tabItem); this._bindEventsOnItem(tabItem); }, appendItemElement: function(item) { if(!this.el) { return; } this.el.appendChild(item.el); }, // Remove an item from the tab bar removeItem: function(index) { var item = this.items[index]; if(!item) { return; } item.onTap = undefined; item.destroy(); }, _bindEventsOnItem: function(item) { var _this = this; if(!this._itemTapHandler) { this._itemTapHandler = function(e) { //_this.selectItem(this); _this.trySelectItem(this); }; } item.onTap = this._itemTapHandler; }, // Get the currently selected item getSelectedItem: function() { return this.selectedItem; }, // Set the currently selected item by index setSelectedItem: function(index) { this.selectedItem = this.items[index]; // Deselect all for(var i = 0, j = this.items.length; i < j; i += 1) { this.items[i].setSelected(false); } // Select the new item if(this.selectedItem) { this.selectedItem.setSelected(true); //this.onTabSelected && this.onTabSelected(this.selectedItem, index); } }, // Select the given item assuming we can find it in our // item list. selectItem: function(item) { for(var i = 0, j = this.items.length; i < j; i += 1) { if(this.items[i] == item) { this.setSelectedItem(i); return; } } }, // Try to select a given item. This triggers an event such // that the view controller managing this tab bar can decide // whether to select the item or cancel it. trySelectItem: function(item) { for(var i = 0, j = this.items.length; i < j; i += 1) { if(this.items[i] == item) { this.tryTabSelect && this.tryTabSelect(i); return; } } }, // Build the initial items list from the given DOM node. _buildItems: function() { var item, items = Array.prototype.slice.call(this.el.children); for(var i = 0, j = items.length; i < j; i += 1) { item = new ionic.views.TabBarItem(items[i]); this.items[i] = item; this._bindEventsOnItem(item); } if(this.items.length > 0) { this.selectedItem = this.items[0]; } }, // Destroy this tab bar destroy: function() { for(var i = 0, j = this.items.length; i < j; i += 1) { this.items[i].destroy(); } this.items.length = 0; } }); })(window.ionic); ; (function(ionic) { 'use strict'; ionic.views.Toggle = ionic.views.View.inherit({ initialize: function(opts) { this.el = opts.el; this.checkbox = opts.checkbox; this.handle = opts.handle; this.openPercent = -1; }, tap: function(e) { this.val( !this.checkbox.checked ); }, drag: function(e) { var slidePageLeft = this.checkbox.offsetLeft + (this.handle.offsetWidth / 2); var slidePageRight = this.checkbox.offsetLeft + this.checkbox.offsetWidth - (this.handle.offsetWidth / 2); if(e.pageX >= slidePageRight - 4) { this.val(true); } else if(e.pageX <= slidePageLeft) { this.val(false); } else { this.setOpenPercent( Math.round( (1 - ((slidePageRight - e.pageX) / (slidePageRight - slidePageLeft) )) * 100) ); } }, setOpenPercent: function(openPercent) { // only make a change if the new open percent has changed if(this.openPercent < 0 || (openPercent < (this.openPercent - 3) || openPercent > (this.openPercent + 3) ) ) { this.openPercent = openPercent; if(openPercent === 0) { this.val(false); } else if(openPercent === 100) { this.val(true); } else { var openPixel = Math.round( (openPercent / 100) * this.checkbox.offsetWidth - (this.handle.offsetWidth) ); openPixel = (openPixel < 1 ? 0 : openPixel); this.handle.style.webkitTransform = 'translate3d(' + openPixel + 'px,0,0)'; } } }, release: function(e) { this.val( this.openPercent >= 50 ); }, val: function(value) { if(value === true || value === false) { if(this.handle.style.webkitTransform !== "") { this.handle.style.webkitTransform = ""; } this.checkbox.checked = value; this.openPercent = (value ? 100 : 0); } return this.checkbox.checked; } }); })(ionic); ; (function(ionic) { 'use strict'; ionic.controllers.ViewController = function(options) { this.initialize.apply(this, arguments); }; ionic.controllers.ViewController.inherit = ionic.inherit; ionic.extend(ionic.controllers.ViewController.prototype, { initialize: function() {}, // Destroy this view controller, including all child views destroy: function() { } }); })(window.ionic); ; (function(ionic) { 'use strict'; /** * The NavController makes it easy to have a stack * of views or screens that can be pushed and popped * for a dynamic navigation flow. This API is modelled * off of the UINavigationController in iOS. * * The NavController can drive a nav bar to show a back button * if the stack can be poppped to go back to the last view, and * it will handle updating the title of the nav bar and processing animations. */ ionic.controllers.NavController = ionic.controllers.ViewController.inherit({ initialize: function(opts) { var _this = this; this.navBar = opts.navBar; this.content = opts.content; this.controllers = opts.controllers || []; this._updateNavBar(); // TODO: Is this the best way? this.navBar.shouldGoBack = function() { _this.pop(); }; }, /** * @return {array} the array of controllers on the stack. */ getControllers: function() { return this.controllers; }, /** * @return {object} the controller at the top of the stack. */ getTopController: function() { return this.controllers[this.controllers.length-1]; }, /** * Push a new controller onto the navigation stack. The new controller * will automatically become the new visible view. * * @param {object} controller the controller to push on the stack. */ push: function(controller) { var last = this.controllers[this.controllers.length - 1]; this.controllers.push(controller); // Indicate we are switching controllers var shouldSwitch = this.switchingController && this.switchingController(controller) || true; // Return if navigation cancelled if(shouldSwitch === false) return; // Actually switch the active controllers if(last) { last.isVisible = false; last.visibilityChanged && last.visibilityChanged('push'); } // Grab the top controller on the stack var next = this.controllers[this.controllers.length - 1]; next.isVisible = true; // Trigger visibility change, but send 'first' if this is the first page next.visibilityChanged && next.visibilityChanged(last ? 'push' : 'first'); this._updateNavBar(); return controller; }, /** * Pop the top controller off the stack, and show the last one. This is the * "back" operation. * * @return {object} the last popped controller */ pop: function() { var next, last; // Make sure we keep one on the stack at all times if(this.controllers.length < 2) { return; } // Grab the controller behind the top one on the stack last = this.controllers.pop(); if(last) { last.isVisible = false; last.visibilityChanged && last.visibilityChanged('pop'); } // Remove the old one //last && last.detach(); next = this.controllers[this.controllers.length - 1]; // TODO: No DOM stuff here //this.content.el.appendChild(next.el); next.isVisible = true; next.visibilityChanged && next.visibilityChanged('pop'); // Switch to it (TODO: Animate or such things here) this._updateNavBar(); return last; }, /** * Show the NavBar (if any) */ showNavBar: function() { if(this.navBar) { this.navBar.show(); } }, /** * Hide the NavBar (if any) */ hideNavBar: function() { if(this.navBar) { this.navBar.hide(); } }, // Update the nav bar after a push or pop _updateNavBar: function() { if(!this.getTopController() || !this.navBar) { return; } this.navBar.setTitle(this.getTopController().title); if(this.controllers.length > 1) { this.navBar.showBackButton(true); } else { this.navBar.showBackButton(false); } } }); })(window.ionic); ; (function(ionic) { 'use strict'; /** * The SideMenuController is a controller with a left and/or right menu that * can be slid out and toggled. Seen on many an app. * * The right or left menu can be disabled or not used at all, if desired. */ ionic.controllers.SideMenuController = ionic.controllers.ViewController.inherit({ initialize: function(options) { var self = this; this.left = options.left; this.right = options.right; this.content = options.content; this.dragThresholdX = options.dragThresholdX || 10; this._rightShowing = false; this._leftShowing = false; this._isDragging = false; if(this.content) { this.content.onDrag = function(e) { self._handleDrag(e); }; this.content.onEndDrag =function(e) { self._endDrag(e); }; } }, /** * Set the content view controller if not passed in the constructor options. * * @param {object} content */ setContent: function(content) { var self = this; this.content = content; this.content.onDrag = function(e) { self._handleDrag(e); }; this.content.endDrag = function(e) { self._endDrag(e); }; }, /** * Toggle the left menu to open 100% */ toggleLeft: function() { var openAmount = this.getOpenAmount(); if(openAmount > 0) { this.openPercentage(0); } else { this.openPercentage(100); } }, /** * Toggle the right menu to open 100% */ toggleRight: function() { var openAmount = this.getOpenAmount(); if(openAmount < 0) { this.openPercentage(0); } else { this.openPercentage(-100); } }, /** * Close all menus. */ close: function() { this.openPercentage(0); }, /** * @return {float} The amount the side menu is open, either positive or negative for left (positive), or right (negative) */ getOpenAmount: function() { return this.content.getTranslateX() || 0; }, /** * @return {float} The ratio of open amount over menu width. For example, a * menu of width 100 open 50 pixels would be open 50% or a ratio of 0.5. Value is negative * for right menu. */ getOpenRatio: function() { var amount = this.getOpenAmount(); if(amount >= 0) { return amount / this.left.width; } return amount / this.right.width; }, isOpen: function() { return this.getOpenRatio() == 1; }, /** * @return {float} The percentage of open amount over menu width. For example, a * menu of width 100 open 50 pixels would be open 50%. Value is negative * for right menu. */ getOpenPercentage: function() { return this.getOpenRatio() * 100; }, /** * Open the menu with a given percentage amount. * @param {float} percentage The percentage (positive or negative for left/right) to open the menu. */ openPercentage: function(percentage) { var p = percentage / 100; if(this.left && percentage >= 0) { this.openAmount(this.left.width * p); } else if(this.right && percentage < 0) { var maxRight = this.right.width; this.openAmount(this.right.width * p); } }, /** * Open the menu the given pixel amount. * @param {float} amount the pixel amount to open the menu. Positive value for left menu, * negative value for right menu (only one menu will be visible at a time). */ openAmount: function(amount) { var maxLeft = this.left && this.left.width || 0; var maxRight = this.right && this.right.width || 0; // Check if we can move to that side, depending if the left/right panel is enabled if((!(this.left && this.left.isEnabled) && amount > 0) || (!(this.right && this.right.isEnabled) && amount < 0)) { return; } if((this._leftShowing && amount > maxLeft) || (this._rightShowing && amount < -maxRight)) { return; } this.content.setTranslateX(amount); if(amount >= 0) { this._leftShowing = true; this._rightShowing = false; // Push the z-index of the right menu down this.right && this.right.pushDown && this.right.pushDown(); // Bring the z-index of the left menu up this.left && this.left.bringUp && this.left.bringUp(); } else { this._rightShowing = true; this._leftShowing = false; // Bring the z-index of the right menu up this.right && this.right.bringUp && this.right.bringUp(); // Push the z-index of the left menu down this.left && this.left.pushDown && this.left.pushDown(); } }, /** * Given an event object, find the final resting position of this side * menu. For example, if the user "throws" the content to the right and * releases the touch, the left menu should snap open (animated, of course). * * @param {Event} e the gesture event to use for snapping */ snapToRest: function(e) { // We want to animate at the end of this this.content.enableAnimation(); this._isDragging = false; // Check how much the panel is open after the drag, and // what the drag velocity is var ratio = this.getOpenRatio(); if(ratio === 0) return; var velocityThreshold = 0.3; var velocityX = e.gesture.velocityX; var direction = e.gesture.direction; // Less than half, going left //if(ratio > 0 && ratio < 0.5 && direction == 'left' && velocityX < velocityThreshold) { //this.openPercentage(0); //} // Going right, less than half, too slow (snap back) if(ratio > 0 && ratio < 0.5 && direction == 'right' && velocityX < velocityThreshold) { this.openPercentage(0); } // Going left, more than half, too slow (snap back) else if(ratio > 0.5 && direction == 'left' && velocityX < velocityThreshold) { this.openPercentage(100); } // Going left, less than half, too slow (snap back) else if(ratio < 0 && ratio > -0.5 && direction == 'left' && velocityX < velocityThreshold) { this.openPercentage(0); } // Going right, more than half, too slow (snap back) else if(ratio < 0.5 && direction == 'right' && velocityX < velocityThreshold) { this.openPercentage(-100); } // Going right, more than half, or quickly (snap open) else if(direction == 'right' && ratio >= 0 && (ratio >= 0.5 || velocityX > velocityThreshold)) { this.openPercentage(100); } // Going left, more than half, or quickly (span open) else if(direction == 'left' && ratio <= 0 && (ratio <= -0.5 || velocityX > velocityThreshold)) { this.openPercentage(-100); } // Snap back for safety else { this.openPercentage(0); } }, // End a drag with the given event _endDrag: function(e) { this.snapToRest(e); this._startX = null; this._lastX = null; this._offsetX = null; }, // Handle a drag event _handleDrag: function(e) { // If we don't have start coords, grab and store them if(!this._startX) { this._startX = e.gesture.touches[0].pageX; this._lastX = this._startX; } else { // Grab the current tap coords this._lastX = e.gesture.touches[0].pageX; } // Calculate difference from the tap points if(!this._isDragging && Math.abs(this._lastX - this._startX) > this.dragThresholdX) { // if the difference is greater than threshold, start dragging using the current // point as the starting point this._startX = this._lastX; this._isDragging = true; // Initialize dragging this.content.disableAnimation(); this._offsetX = this.getOpenAmount(); } if(this._isDragging) { this.openAmount(this._offsetX + (this._lastX - this._startX)); } } }); })(ionic); ; (function(ionic) { 'use strict'; /** * The TabBarController handles a set of view controllers powered by a tab strip * at the bottom (or possibly top) of a screen. * * The API here is somewhat modelled off of UITabController in the sense that the * controllers actually define what the tab will look like (title, icon, etc.). * * Tabs shouldn't be interacted with through your own code. Instead, use the controller * methods which will power the tab bar. */ ionic.controllers.TabBarController = ionic.controllers.ViewController.inherit({ initialize: function(options) { this.tabBar = options.tabBar; this._bindEvents(); this.controllers = []; var controllers = options.controllers || []; for(var i = 0; i < controllers.length; i++) { this.addController(controllers[i]); } // Bind or set our tabWillChange callback this.controllerWillChange = options.controllerWillChange || function(controller) {}; this.controllerChanged = options.controllerChanged || function(controller) {}; // Try to select the first controller if we have one this.setSelectedController(0); }, // Start listening for events on our tab bar _bindEvents: function() { var _this = this; this.tabBar.tryTabSelect = function(index) { _this.setSelectedController(index); }; }, selectController: function(index) { var shouldChange = true; // Check if we should switch to this tab. This lets the app // cancel tab switches if the context isn't right, for example. if(this.controllerWillChange) { if(this.controllerWillChange(this.controllers[index], index) === false) { shouldChange = false; } } if(shouldChange) { this.setSelectedController(index); } }, // Force the selection of a controller at the given index setSelectedController: function(index) { if(index >= this.controllers.length) { return; } var lastController = this.selectedController; var lastIndex = this.selectedIndex; this.selectedController = this.controllers[index]; this.selectedIndex = index; this._showController(index); this.tabBar.setSelectedItem(index); this.controllerChanged && this.controllerChanged(lastController, lastIndex, this.selectedController, this.selectedIndex); }, _showController: function(index) { var c; for(var i = 0, j = this.controllers.length; i < j; i ++) { c = this.controllers[i]; //c.detach && c.detach(); c.isVisible = false; c.visibilityChanged && c.visibilityChanged(); } c = this.controllers[index]; //c.attach && c.attach(); c.isVisible = true; c.visibilityChanged && c.visibilityChanged(); }, _clearSelected: function() { this.selectedController = null; this.selectedIndex = -1; }, // Return the tab at the given index getController: function(index) { return this.controllers[index]; }, // Return the current tab list getControllers: function() { return this.controllers; }, // Get the currently selected controller getSelectedController: function() { return this.selectedController; }, // Get the index of the currently selected controller getSelectedControllerIndex: function() { return this.selectedIndex; }, // Add a tab addController: function(controller) { this.controllers.push(controller); this.tabBar.addItem({ title: controller.title, icon: controller.icon }); // If we don't have a selected controller yet, select the first one. if(!this.selectedController) { this.setSelectedController(0); } }, // Set the tabs and select the first setControllers: function(controllers) { this.controllers = controllers; this._clearSelected(); this.selectController(0); }, }); })(window.ionic);
js/components/list/index.js
LetsBuildSomething/vmag_mobile
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { actions } from 'react-native-navigation-redux-helpers'; import { Container, Header, Title, Content, Button, Icon, Text, Left, Right, Body, List, ListItem } from 'native-base'; import { Actions } from 'react-native-router-flux'; import { openDrawer, closeDrawer } from '../../actions/drawer'; import styles from './styles'; const { pushRoute, } = actions; const datas = [ { route: 'basicList', text: 'Basic List', }, { route: 'listDivider', text: 'List Divider', }, { route: 'listHeader', text: 'List Headers', }, { route: 'listIcon', text: 'List Icon', }, { route: 'listAvatar', text: 'List Avatar', }, { route: 'listThumbnail', text: 'List Thumbnail', },, { route: 'listSeparator', text: 'List Separator', }, ]; class NHList extends Component { static propTypes = { openDrawer: React.PropTypes.func, pushRoute: React.PropTypes.func, navigation: React.PropTypes.shape({ key: React.PropTypes.string, }), } pushRoute(route) { this.props.pushRoute({ key: route, index: 1 }, this.props.navigation.key); } render() { return ( <Container style={styles.container}> <Header> <Left> <Button transparent onPress={this.props.openDrawer}> <Icon name="menu" /> </Button> </Left> <Body> <Title>List</Title> </Body> <Right /> </Header> <Content> <List dataArray={datas} renderRow={data => <ListItem button onPress={() => { Actions[data.route](); this.props.closeDrawer() }} > <Text>{data.text}</Text> <Right> <Icon name="arrow-forward" /> </Right> </ListItem> } /> </Content> </Container> ); } } function bindAction(dispatch) { return { openDrawer: () => dispatch(openDrawer()), closeDrawer: () => dispatch(closeDrawer()), pushRoute: (route, key) => dispatch(pushRoute(route, key)), }; } const mapStateToProps = state => ({ navigation: state.cardNavigation, themeState: state.drawer.themeState, }); export default connect(mapStateToProps, bindAction)(NHList);
test/pages/NotFound_spec.js
aggelog/React-Redux-Boilerplate
import React from 'react'; import { mount } from 'enzyme'; import test from 'ava'; import { Provider } from 'react-redux'; import sinon from 'sinon'; import { browserHistory } from 'react-router'; import configureStore from '../../src/store/configureStore.js'; import NotFound from '../../src/pages/NotFound'; test('Page: - NotFound', t => { const stub = sinon.stub(browserHistory, 'push'); const { store } = configureStore(); mount(<Provider store={store}><NotFound/></Provider>); t.true(stub.calledWith('/')); });
frontend/src/containers/NewBackup/index.js
XiaocongDong/mongodb-backup-manager
import React, { Component } from 'react'; import BackupConfig from 'components/BackupConfig'; export default class NewBackup extends Component { render() { return ( <BackupConfig /> ) } }
src/svg-icons/av/volume-up.js
pomerantsev/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvVolumeUp = (props) => ( <SvgIcon {...props}> <path d="M3 9v6h4l5 5V4L7 9H3zm13.5 3c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02zM14 3.23v2.06c2.89.86 5 3.54 5 6.71s-2.11 5.85-5 6.71v2.06c4.01-.91 7-4.49 7-8.77s-2.99-7.86-7-8.77z"/> </SvgIcon> ); AvVolumeUp = pure(AvVolumeUp); AvVolumeUp.displayName = 'AvVolumeUp'; AvVolumeUp.muiName = 'SvgIcon'; export default AvVolumeUp;
src/BlockUi.js
Availity/react-block-ui
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import DefaultLoader from './Loader'; import safeActiveElement from './safeActiveElement'; const defaultProps = { tag: 'div', renderChildren: true, loader: DefaultLoader, }; class BlockUi extends Component { constructor(props) { super(props); this.tabbedUpTop = this.tabbedUpTop.bind(this); this.tabbedDownTop = this.tabbedDownTop.bind(this); this.tabbedUpBottom = this.tabbedUpBottom.bind(this); this.tabbedDownBottom = this.tabbedDownBottom.bind(this); this.setHelper = this.setRef.bind(this, 'helper'); this.setBlocker = this.setRef.bind(this, 'blocker'); this.setTopFocus = this.setRef.bind(this, 'topFocus'); this.setContainer = this.setRef.bind(this, 'container'); this.setMessageContainer = this.setRef.bind(this, 'messageContainer'); this.handleScroll = this.handleScroll.bind(this); this.state = { top: '50%' }; } componentWillReceiveProps(nextProps) { if (nextProps.blocking !== this.props.blocking) { if (nextProps.blocking) { // blocking started if (this.helper && this.helper.parentNode && this.helper.parentNode.contains && this.helper.parentNode.contains(safeActiveElement())) { this.focused = safeActiveElement(); // https://www.tjvantoll.com/2013/08/30/bugs-with-document-activeelement-in-internet-explorer/#blurring-the-body-switches-windows-in-ie9-and-ie10 if (this.focused && this.focused !== document.body) { (window.setImmediate || setTimeout)(() => this.focused && typeof this.focused.blur === 'function' && this.focused.blur()); } } } else { this.detachListeners(); const ae = safeActiveElement(); if (this.focused && (!ae || ae === document.body || ae === this.topFocus)) { if (typeof this.focused.focus === 'function') { this.focused.focus(); } this.focused = null; } } } if (nextProps.keepInView && (nextProps.keepInView !== this.props.keepInView || (nextProps.blocking && nextProps.blocking !== this.props.blocking))) { this.attachListeners(); this.keepInView(nextProps); } } componentWillUnmount() { this.detachListeners(); } setRef(name, ref) { this[name] = ref; if (ref && name === 'container') { this.keepInView(); } } attachListeners() { window.addEventListener('scroll', this.handleScroll); } detachListeners() { window.removeEventListener('scroll', this.handleScroll); } blockingTab(e, withShift = false) { // eslint-disable-next-line eqeqeq return this.props.blocking && (e.key === 'Tab' || e.keyCode === 9) && e.shiftKey == withShift; } tabbedUpTop(e) { if (this.blockingTab(e)) { this.blocker.focus(); } } tabbedDownTop(e) { if (this.blockingTab(e)) { e.preventDefault(); this.blocker.focus(); } } tabbedUpBottom(e) { if (this.blockingTab(e, true)) { this.topFocus.focus(); } } tabbedDownBottom(e) { if (this.blockingTab(e, true)) { e.preventDefault(); this.topFocus.focus(); } } keepInView(props = this.props) { if (props.blocking && props.keepInView && this.container) { const containerBounds = this.container.getBoundingClientRect(); const windowHeight = window.innerHeight; if (containerBounds.top > windowHeight || containerBounds.bottom < 0) return; if (containerBounds.top >= 0 && containerBounds.bottom <= windowHeight) { if (this.state.top !== '50%') { this.setState({ top: '50%' }); } return; } const messageBoundsHeight = this.messageContainer ? this.messageContainer.getBoundingClientRect().height : 0; let top = Math.max(Math.min(windowHeight, containerBounds.bottom) - Math.max(containerBounds.top, 0), messageBoundsHeight) / 2; if (containerBounds.top < 0) { top = Math.min(top - containerBounds.top, containerBounds.height - (messageBoundsHeight / 2)); } if (this.state.top !== top) { this.setState({top}); } } } handleScroll() { this.keepInView(); } render() { const { tag: Tag, blocking, className, children, message, loader: Loader, renderChildren, keepInView, ...attributes } = this.props; const classes = blocking ? `block-ui ${className}` : className; const renderChilds = !blocking || renderChildren; return ( <Tag {...attributes} className={classes} aria-busy={blocking}> {blocking && <div tabIndex="0" onKeyUp={this.tabbedUpTop} onKeyDown={this.tabbedDownTop} ref={this.setTopFocus} />} {renderChilds && children} {blocking && <div className="block-ui-container" tabIndex="0" ref={this.setBlocker} onKeyUp={this.tabbedUpBottom} onKeyDown={this.tabbedDownBottom} > <div className="block-ui-overlay" ref={this.setContainer} /> <div className="block-ui-message-container" ref={this.setMessageContainer} style={{ top: keepInView ? this.state.top : undefined }} > <div className="block-ui-message"> {message} {React.isValidElement(Loader) ? Loader : <Loader />} </div> </div> </div> } <span ref={this.setHelper} /> </Tag> ); } } BlockUi.propTypes = { blocking: PropTypes.bool, children: PropTypes.node, renderChildren: PropTypes.bool, keepInView: PropTypes.bool, className: PropTypes.string, message: PropTypes.oneOfType([ PropTypes.string, PropTypes.node, ]), loader: PropTypes.oneOfType([ PropTypes.string, PropTypes.func, PropTypes.node, ]), tag: PropTypes.oneOfType([ PropTypes.string, PropTypes.func, PropTypes.shape({ $$typeof: PropTypes.symbol, render: PropTypes.func }), ]), }; BlockUi.defaultProps = defaultProps; export default BlockUi;
examples/provider/app.js
sheaivey/react-axios
import { AxiosProvider, Get } from 'react-axios' import axios from 'axios' import React from 'react' import ReactDOM from 'react-dom' const axiosProvider = axios.create({ baseURL: '/api/provider/', timeout: 2000, headers: { 'X-Custom-Header': 'foobar' }, }) const axiosProp = axios.create({ baseURL: '/api/props/', timeout: 2000, headers: { 'X-Custom-Header': 'foobar' }, }) class App extends React.Component { renderResponse(error, response, isLoading) { if(error) { return (<div>Something bad happened: {error.message}</div>) } else if(isLoading) { return (<div className="loader"></div>) } else if(response !== null) { return (<div>{response.data.message}</div>) } return null } render() { return ( <div> <h2>Default Axios Instance</h2> <code> <Get url="/api/test"> {this.renderResponse} </Get> </code> <h2>Axios Instance from Props</h2> <code> <Get url="test" instance={axiosProp}> {this.renderResponse} </Get> </code> <h2>Axios Instance from a Provider</h2> <AxiosProvider instance={axiosProvider} > <code> <Get url="test"> {this.renderResponse} </Get> </code> </AxiosProvider> </div> ) } } ReactDOM.render( <React.StrictMode> <App /> </React.StrictMode>, document.getElementById('app') )
src/routes/savoringYourPetAfterPayment/index.js
goldylucks/adamgoldman.me
import React from 'react' import SavoringYourPetAfterPayment from './savoringYourPetAfterPayment' function action({ path }) { return { chunks: ['savoringYourPetAfterPayment'], title: 'Savoring Your Pet - Success', path, description: 'Success page', component: <SavoringYourPetAfterPayment path={path} />, } } export default action
src/clincoded/static/components/pubmed_notes_box.js
ClinGen/clincoded
import React from 'react'; import PropTypes from 'prop-types'; import { property } from 'underscore'; import { Form, Input } from '../libs/bootstrap/form'; const propTypes = { updateMsg: PropTypes.node, submitBusy: PropTypes.bool.isRequired, isEditingNotes: PropTypes.bool.isRequired, annotation: PropTypes.object.isRequired, currPmidNotes: PropTypes.object.isRequired, setEditMode: PropTypes.func.isRequired, handleSaveNotes: PropTypes.func.isRequired, handleTextChange: PropTypes.func.isRequired, handleCheckboxChange: PropTypes.func.isRequired, }; const defaultProps = { updateMsg: null, }; const PubMedNotesBox = ({ updateMsg, submitBusy, isEditingNotes, annotation, currPmidNotes, setEditMode, handleSaveNotes, handleTextChange, handleCheckboxChange, }) => ( <div> { isEditingNotes ? ( <Form submitHandler={(e) => handleSaveNotes(e, annotation)} formClassName="form-horizontal pubmed-notes-box"> <div className="form-group"> <Input type="checkbox" label="Non-scorable evidence" labelClassName="col-sm-10 no-padding" groupClassName="col-sm-4" checked={property(['nonscorable', 'checked'])(currPmidNotes)} defaultChecked="false" handleChange={(ref, e) => handleCheckboxChange(e, 'nonscorableCheckbox')} /> <Input type="textarea" controlledValue={property(['nonscorable', 'text'])(currPmidNotes)} wrapperClassName="col-sm-8" handleChange={(ref, e) => handleTextChange(e, 'nonscorableText')} /> </div> <div className="form-group"> <Input type="checkbox" label="Other comments on PMID" labelClassName="col-sm-10 no-padding" groupClassName="col-sm-4" checked={property(['other', 'checked'])(currPmidNotes)} defaultChecked="false" handleChange={(ref, e) => handleCheckboxChange(e, 'otherCheckbox')} /> <Input type="textarea" controlledValue={property(['other', 'text'])(currPmidNotes)} wrapperClassName="col-sm-8" handleChange={(ref, e) => handleTextChange(e, 'otherText')} /> </div> <div className="flex-right"> { updateMsg && <div className="submit-info pull-right">{ updateMsg }</div> } <Input type="submit" id="submit" inputClassName="btn-primary pull-right" title="Save" submitBusy={submitBusy} /> </div> </Form> ) : ( <div className="form-horizontal pubmed-notes-box"> <div className="form-group"> <div className="col-sm-4"> <label className="col-sm-10 no-padding">Non-scorable evidence</label> { property(['nonscorable', 'checked'])(currPmidNotes) && <i className="icon icon-check" /> } </div> <div className="col-sm-8"> { property(['articleNotes', 'nonscorable', 'text'])(annotation) ? <span>{ annotation.articleNotes.nonscorable.text }</span> : <i className="empty-text-placeholder">None</i> } </div> </div> <div className="form-group"> <div className="col-sm-4"> <label htmlFor="other" className="col-sm-10 no-padding">Other comments on PMID</label> { property(['other', 'checked'])(currPmidNotes) && <i className="icon icon-check" /> } </div> <div className="col-sm-8"> { property(['articleNotes', 'other', 'text'])(annotation) ? <span>{ annotation.articleNotes.other.text }</span> : <i className="empty-text-placeholder">None</i> } </div> </div> <div className="flex-right"> { updateMsg && <div className="submit-info pull-right">{ updateMsg }</div> } <Input type="button" id="edit" inputClassName="btn-primary pull-right" title="Edit" clickHandler={() => setEditMode(true)} /> </div> </div> ) } </div> ); PubMedNotesBox.propTypes = propTypes; PubMedNotesBox.defaultProps = defaultProps; export default PubMedNotesBox;
ajax/libs/riot/2.6.4/riot+compiler.js
ahocevar/cdnjs
/* Riot v2.6.4, @license MIT */ ;(function(window, undefined) { 'use strict'; var riot = { version: 'v2.6.4', settings: {} }, // be aware, internal usage // ATTENTION: prefix the global dynamic variables with `__` // counter to give a unique id to all the Tag instances __uid = 0, // tags instances cache __virtualDom = [], // tags implementation cache __tagImpl = {}, /** * Const */ GLOBAL_MIXIN = '__global_mixin', // riot specific prefixes RIOT_PREFIX = 'riot-', RIOT_TAG = RIOT_PREFIX + 'tag', RIOT_TAG_IS = 'data-is', // for typeof == '' comparisons T_STRING = 'string', T_OBJECT = 'object', T_UNDEF = 'undefined', T_FUNCTION = 'function', XLINK_NS = 'http://www.w3.org/1999/xlink', XLINK_REGEX = /^xlink:(\w+)/, // special native tags that cannot be treated like the others SPECIAL_TAGS_REGEX = /^(?:t(?:body|head|foot|[rhd])|caption|col(?:group)?|opt(?:ion|group))$/, RESERVED_WORDS_BLACKLIST = /^(?:_(?:item|id|parent)|update|root|(?:un)?mount|mixin|is(?:Mounted|Loop)|tags|parent|opts|trigger|o(?:n|ff|ne))$/, // SVG tags list https://www.w3.org/TR/SVG/attindex.html#PresentationAttributes SVG_TAGS_LIST = ['altGlyph', 'animate', 'animateColor', 'circle', 'clipPath', 'defs', 'ellipse', 'feBlend', 'feColorMatrix', 'feComponentTransfer', 'feComposite', 'feConvolveMatrix', 'feDiffuseLighting', 'feDisplacementMap', 'feFlood', 'feGaussianBlur', 'feImage', 'feMerge', 'feMorphology', 'feOffset', 'feSpecularLighting', 'feTile', 'feTurbulence', 'filter', 'font', 'foreignObject', 'g', 'glyph', 'glyphRef', 'image', 'line', 'linearGradient', 'marker', 'mask', 'missing-glyph', 'path', 'pattern', 'polygon', 'polyline', 'radialGradient', 'rect', 'stop', 'svg', 'switch', 'symbol', 'text', 'textPath', 'tref', 'tspan', 'use'], // version# for IE 8-11, 0 for others IE_VERSION = (window && window.document || {}).documentMode | 0, // detect firefox to fix #1374 FIREFOX = window && !!window.InstallTrigger /* istanbul ignore next */ riot.observable = function(el) { /** * Extend the original object or create a new empty one * @type { Object } */ el = el || {} /** * Private variables */ var callbacks = {}, slice = Array.prototype.slice /** * Private Methods */ /** * Helper function needed to get and loop all the events in a string * @param { String } e - event string * @param {Function} fn - callback */ function onEachEvent(e, fn) { var es = e.split(' '), l = es.length, i = 0 for (; i < l; i++) { var name = es[i] if (name) fn(name, i) } } /** * Public Api */ // extend the el object adding the observable methods Object.defineProperties(el, { /** * Listen to the given space separated list of `events` and * execute the `callback` each time an event is triggered. * @param { String } events - events ids * @param { Function } fn - callback function * @returns { Object } el */ on: { value: function(events, fn) { if (typeof fn != 'function') return el onEachEvent(events, function(name, pos) { (callbacks[name] = callbacks[name] || []).push(fn) fn.typed = pos > 0 }) return el }, enumerable: false, writable: false, configurable: false }, /** * Removes the given space separated list of `events` listeners * @param { String } events - events ids * @param { Function } fn - callback function * @returns { Object } el */ off: { value: function(events, fn) { if (events == '*' && !fn) callbacks = {} else { onEachEvent(events, function(name, pos) { if (fn) { var arr = callbacks[name] for (var i = 0, cb; cb = arr && arr[i]; ++i) { if (cb == fn) arr.splice(i--, 1) } } else delete callbacks[name] }) } return el }, enumerable: false, writable: false, configurable: false }, /** * Listen to the given space separated list of `events` and * execute the `callback` at most once * @param { String } events - events ids * @param { Function } fn - callback function * @returns { Object } el */ one: { value: function(events, fn) { function on() { el.off(events, on) fn.apply(el, arguments) } return el.on(events, on) }, enumerable: false, writable: false, configurable: false }, /** * Execute all callback functions that listen to * the given space separated list of `events` * @param { String } events - events ids * @returns { Object } el */ trigger: { value: function(events) { // getting the arguments var arglen = arguments.length - 1, args = new Array(arglen), fns for (var i = 0; i < arglen; i++) { args[i] = arguments[i + 1] // skip first argument } onEachEvent(events, function(name, pos) { fns = slice.call(callbacks[name] || [], 0) for (var i = 0, fn; fn = fns[i]; ++i) { if (fn.busy) continue fn.busy = 1 fn.apply(el, fn.typed ? [name].concat(args) : args) if (fns[i] !== fn) { i-- } fn.busy = 0 } if (callbacks['*'] && name != '*') el.trigger.apply(el, ['*', name].concat(args)) }) return el }, enumerable: false, writable: false, configurable: false } }) return el } /* istanbul ignore next */ ;(function(riot) { /** * Simple client-side router * @module riot-route */ var RE_ORIGIN = /^.+?\/\/+[^\/]+/, EVENT_LISTENER = 'EventListener', REMOVE_EVENT_LISTENER = 'remove' + EVENT_LISTENER, ADD_EVENT_LISTENER = 'add' + EVENT_LISTENER, HAS_ATTRIBUTE = 'hasAttribute', REPLACE = 'replace', POPSTATE = 'popstate', HASHCHANGE = 'hashchange', TRIGGER = 'trigger', MAX_EMIT_STACK_LEVEL = 3, win = typeof window != 'undefined' && window, doc = typeof document != 'undefined' && document, hist = win && history, loc = win && (hist.location || win.location), // see html5-history-api prot = Router.prototype, // to minify more clickEvent = doc && doc.ontouchstart ? 'touchstart' : 'click', started = false, central = riot.observable(), routeFound = false, debouncedEmit, base, current, parser, secondParser, emitStack = [], emitStackLevel = 0 /** * Default parser. You can replace it via router.parser method. * @param {string} path - current path (normalized) * @returns {array} array */ function DEFAULT_PARSER(path) { return path.split(/[/?#]/) } /** * Default parser (second). You can replace it via router.parser method. * @param {string} path - current path (normalized) * @param {string} filter - filter string (normalized) * @returns {array} array */ function DEFAULT_SECOND_PARSER(path, filter) { var re = new RegExp('^' + filter[REPLACE](/\*/g, '([^/?#]+?)')[REPLACE](/\.\./, '.*') + '$'), args = path.match(re) if (args) return args.slice(1) } /** * Simple/cheap debounce implementation * @param {function} fn - callback * @param {number} delay - delay in seconds * @returns {function} debounced function */ function debounce(fn, delay) { var t return function () { clearTimeout(t) t = setTimeout(fn, delay) } } /** * Set the window listeners to trigger the routes * @param {boolean} autoExec - see route.start */ function start(autoExec) { debouncedEmit = debounce(emit, 1) win[ADD_EVENT_LISTENER](POPSTATE, debouncedEmit) win[ADD_EVENT_LISTENER](HASHCHANGE, debouncedEmit) doc[ADD_EVENT_LISTENER](clickEvent, click) if (autoExec) emit(true) } /** * Router class */ function Router() { this.$ = [] riot.observable(this) // make it observable central.on('stop', this.s.bind(this)) central.on('emit', this.e.bind(this)) } function normalize(path) { return path[REPLACE](/^\/|\/$/, '') } function isString(str) { return typeof str == 'string' } /** * Get the part after domain name * @param {string} href - fullpath * @returns {string} path from root */ function getPathFromRoot(href) { return (href || loc.href)[REPLACE](RE_ORIGIN, '') } /** * Get the part after base * @param {string} href - fullpath * @returns {string} path from base */ function getPathFromBase(href) { return base[0] == '#' ? (href || loc.href || '').split(base)[1] || '' : (loc ? getPathFromRoot(href) : href || '')[REPLACE](base, '') } function emit(force) { // the stack is needed for redirections var isRoot = emitStackLevel == 0, first if (MAX_EMIT_STACK_LEVEL <= emitStackLevel) return emitStackLevel++ emitStack.push(function() { var path = getPathFromBase() if (force || path != current) { central[TRIGGER]('emit', path) current = path } }) if (isRoot) { while (first = emitStack.shift()) first() // stack increses within this call emitStackLevel = 0 } } function click(e) { if ( e.which != 1 // not left click || e.metaKey || e.ctrlKey || e.shiftKey // or meta keys || e.defaultPrevented // or default prevented ) return var el = e.target while (el && el.nodeName != 'A') el = el.parentNode if ( !el || el.nodeName != 'A' // not A tag || el[HAS_ATTRIBUTE]('download') // has download attr || !el[HAS_ATTRIBUTE]('href') // has no href attr || el.target && el.target != '_self' // another window or frame || el.href.indexOf(loc.href.match(RE_ORIGIN)[0]) == -1 // cross origin ) return if (el.href != loc.href && ( el.href.split('#')[0] == loc.href.split('#')[0] // internal jump || base[0] != '#' && getPathFromRoot(el.href).indexOf(base) !== 0 // outside of base || base[0] == '#' && el.href.split(base)[0] != loc.href.split(base)[0] // outside of #base || !go(getPathFromBase(el.href), el.title || doc.title) // route not found )) return e.preventDefault() } /** * Go to the path * @param {string} path - destination path * @param {string} title - page title * @param {boolean} shouldReplace - use replaceState or pushState * @returns {boolean} - route not found flag */ function go(path, title, shouldReplace) { // Server-side usage: directly execute handlers for the path if (!hist) return central[TRIGGER]('emit', getPathFromBase(path)) path = base + normalize(path) title = title || doc.title // browsers ignores the second parameter `title` shouldReplace ? hist.replaceState(null, title, path) : hist.pushState(null, title, path) // so we need to set it manually doc.title = title routeFound = false emit() return routeFound } /** * Go to path or set action * a single string: go there * two strings: go there with setting a title * two strings and boolean: replace history with setting a title * a single function: set an action on the default route * a string/RegExp and a function: set an action on the route * @param {(string|function)} first - path / action / filter * @param {(string|RegExp|function)} second - title / action * @param {boolean} third - replace flag */ prot.m = function(first, second, third) { if (isString(first) && (!second || isString(second))) go(first, second, third || false) else if (second) this.r(first, second) else this.r('@', first) } /** * Stop routing */ prot.s = function() { this.off('*') this.$ = [] } /** * Emit * @param {string} path - path */ prot.e = function(path) { this.$.concat('@').some(function(filter) { var args = (filter == '@' ? parser : secondParser)(normalize(path), normalize(filter)) if (typeof args != 'undefined') { this[TRIGGER].apply(null, [filter].concat(args)) return routeFound = true // exit from loop } }, this) } /** * Register route * @param {string} filter - filter for matching to url * @param {function} action - action to register */ prot.r = function(filter, action) { if (filter != '@') { filter = '/' + normalize(filter) this.$.push(filter) } this.on(filter, action) } var mainRouter = new Router() var route = mainRouter.m.bind(mainRouter) /** * Create a sub router * @returns {function} the method of a new Router object */ route.create = function() { var newSubRouter = new Router() // assign sub-router's main method var router = newSubRouter.m.bind(newSubRouter) // stop only this sub-router router.stop = newSubRouter.s.bind(newSubRouter) return router } /** * Set the base of url * @param {(str|RegExp)} arg - a new base or '#' or '#!' */ route.base = function(arg) { base = arg || '#' current = getPathFromBase() // recalculate current path } /** Exec routing right now **/ route.exec = function() { emit(true) } /** * Replace the default router to yours * @param {function} fn - your parser function * @param {function} fn2 - your secondParser function */ route.parser = function(fn, fn2) { if (!fn && !fn2) { // reset parser for testing... parser = DEFAULT_PARSER secondParser = DEFAULT_SECOND_PARSER } if (fn) parser = fn if (fn2) secondParser = fn2 } /** * Helper function to get url query as an object * @returns {object} parsed query */ route.query = function() { var q = {} var href = loc.href || current href[REPLACE](/[?&](.+?)=([^&]*)/g, function(_, k, v) { q[k] = v }) return q } /** Stop routing **/ route.stop = function () { if (started) { if (win) { win[REMOVE_EVENT_LISTENER](POPSTATE, debouncedEmit) win[REMOVE_EVENT_LISTENER](HASHCHANGE, debouncedEmit) doc[REMOVE_EVENT_LISTENER](clickEvent, click) } central[TRIGGER]('stop') started = false } } /** * Start routing * @param {boolean} autoExec - automatically exec after starting if true */ route.start = function (autoExec) { if (!started) { if (win) { if (document.readyState == 'complete') start(autoExec) // the timeout is needed to solve // a weird safari bug https://github.com/riot/route/issues/33 else win[ADD_EVENT_LISTENER]('load', function() { setTimeout(function() { start(autoExec) }, 1) }) } started = true } } /** Prepare the router **/ route.base() route.parser() riot.route = route })(riot) /* istanbul ignore next */ /** * The riot template engine * @version v2.4.2 */ /** * riot.util.brackets * * - `brackets ` - Returns a string or regex based on its parameter * - `brackets.set` - Change the current riot brackets * * @module */ var brackets = (function (UNDEF) { var REGLOB = 'g', R_MLCOMMS = /\/\*[^*]*\*+(?:[^*\/][^*]*\*+)*\//g, R_STRINGS = /"[^"\\]*(?:\\[\S\s][^"\\]*)*"|'[^'\\]*(?:\\[\S\s][^'\\]*)*'/g, S_QBLOCKS = R_STRINGS.source + '|' + /(?:\breturn\s+|(?:[$\w\)\]]|\+\+|--)\s*(\/)(?![*\/]))/.source + '|' + /\/(?=[^*\/])[^[\/\\]*(?:(?:\[(?:\\.|[^\]\\]*)*\]|\\.)[^[\/\\]*)*?(\/)[gim]*/.source, UNSUPPORTED = RegExp('[\\' + 'x00-\\x1F<>a-zA-Z0-9\'",;\\\\]'), NEED_ESCAPE = /(?=[[\]()*+?.^$|])/g, FINDBRACES = { '(': RegExp('([()])|' + S_QBLOCKS, REGLOB), '[': RegExp('([[\\]])|' + S_QBLOCKS, REGLOB), '{': RegExp('([{}])|' + S_QBLOCKS, REGLOB) }, DEFAULT = '{ }' var _pairs = [ '{', '}', '{', '}', /{[^}]*}/, /\\([{}])/g, /\\({)|{/g, RegExp('\\\\(})|([[({])|(})|' + S_QBLOCKS, REGLOB), DEFAULT, /^\s*{\^?\s*([$\w]+)(?:\s*,\s*(\S+))?\s+in\s+(\S.*)\s*}/, /(^|[^\\]){=[\S\s]*?}/ ] var cachedBrackets = UNDEF, _regex, _cache = [], _settings function _loopback (re) { return re } function _rewrite (re, bp) { if (!bp) bp = _cache return new RegExp( re.source.replace(/{/g, bp[2]).replace(/}/g, bp[3]), re.global ? REGLOB : '' ) } function _create (pair) { if (pair === DEFAULT) return _pairs var arr = pair.split(' ') if (arr.length !== 2 || UNSUPPORTED.test(pair)) { throw new Error('Unsupported brackets "' + pair + '"') } arr = arr.concat(pair.replace(NEED_ESCAPE, '\\').split(' ')) arr[4] = _rewrite(arr[1].length > 1 ? /{[\S\s]*?}/ : _pairs[4], arr) arr[5] = _rewrite(pair.length > 3 ? /\\({|})/g : _pairs[5], arr) arr[6] = _rewrite(_pairs[6], arr) arr[7] = RegExp('\\\\(' + arr[3] + ')|([[({])|(' + arr[3] + ')|' + S_QBLOCKS, REGLOB) arr[8] = pair return arr } function _brackets (reOrIdx) { return reOrIdx instanceof RegExp ? _regex(reOrIdx) : _cache[reOrIdx] } _brackets.split = function split (str, tmpl, _bp) { // istanbul ignore next: _bp is for the compiler if (!_bp) _bp = _cache var parts = [], match, isexpr, start, pos, re = _bp[6] isexpr = start = re.lastIndex = 0 while ((match = re.exec(str))) { pos = match.index if (isexpr) { if (match[2]) { re.lastIndex = skipBraces(str, match[2], re.lastIndex) continue } if (!match[3]) { continue } } if (!match[1]) { unescapeStr(str.slice(start, pos)) start = re.lastIndex re = _bp[6 + (isexpr ^= 1)] re.lastIndex = start } } if (str && start < str.length) { unescapeStr(str.slice(start)) } return parts function unescapeStr (s) { if (tmpl || isexpr) { parts.push(s && s.replace(_bp[5], '$1')) } else { parts.push(s) } } function skipBraces (s, ch, ix) { var match, recch = FINDBRACES[ch] recch.lastIndex = ix ix = 1 while ((match = recch.exec(s))) { if (match[1] && !(match[1] === ch ? ++ix : --ix)) break } return ix ? s.length : recch.lastIndex } } _brackets.hasExpr = function hasExpr (str) { return _cache[4].test(str) } _brackets.loopKeys = function loopKeys (expr) { var m = expr.match(_cache[9]) return m ? { key: m[1], pos: m[2], val: _cache[0] + m[3].trim() + _cache[1] } : { val: expr.trim() } } _brackets.array = function array (pair) { return pair ? _create(pair) : _cache } function _reset (pair) { if ((pair || (pair = DEFAULT)) !== _cache[8]) { _cache = _create(pair) _regex = pair === DEFAULT ? _loopback : _rewrite _cache[9] = _regex(_pairs[9]) } cachedBrackets = pair } function _setSettings (o) { var b o = o || {} b = o.brackets Object.defineProperty(o, 'brackets', { set: _reset, get: function () { return cachedBrackets }, enumerable: true }) _settings = o _reset(b) } Object.defineProperty(_brackets, 'settings', { set: _setSettings, get: function () { return _settings } }) /* istanbul ignore next: in the browser riot is always in the scope */ _brackets.settings = typeof riot !== 'undefined' && riot.settings || {} _brackets.set = _reset _brackets.R_STRINGS = R_STRINGS _brackets.R_MLCOMMS = R_MLCOMMS _brackets.S_QBLOCKS = S_QBLOCKS return _brackets })() /** * @module tmpl * * tmpl - Root function, returns the template value, render with data * tmpl.hasExpr - Test the existence of a expression inside a string * tmpl.loopKeys - Get the keys for an 'each' loop (used by `_each`) */ var tmpl = (function () { var _cache = {} function _tmpl (str, data) { if (!str) return str return (_cache[str] || (_cache[str] = _create(str))).call(data, _logErr) } _tmpl.haveRaw = brackets.hasRaw _tmpl.hasExpr = brackets.hasExpr _tmpl.loopKeys = brackets.loopKeys // istanbul ignore next _tmpl.clearCache = function () { _cache = {} } _tmpl.errorHandler = null function _logErr (err, ctx) { if (_tmpl.errorHandler) { err.riotData = { tagName: ctx && ctx.root && ctx.root.tagName, _riot_id: ctx && ctx._riot_id //eslint-disable-line camelcase } _tmpl.errorHandler(err) } } function _create (str) { var expr = _getTmpl(str) if (expr.slice(0, 11) !== 'try{return ') expr = 'return ' + expr return new Function('E', expr + ';') // eslint-disable-line no-new-func } var CH_IDEXPR = String.fromCharCode(0x2057), RE_CSNAME = /^(?:(-?[_A-Za-z\xA0-\xFF][-\w\xA0-\xFF]*)|\u2057(\d+)~):/, RE_QBLOCK = RegExp(brackets.S_QBLOCKS, 'g'), RE_DQUOTE = /\u2057/g, RE_QBMARK = /\u2057(\d+)~/g function _getTmpl (str) { var qstr = [], expr, parts = brackets.split(str.replace(RE_DQUOTE, '"'), 1) if (parts.length > 2 || parts[0]) { var i, j, list = [] for (i = j = 0; i < parts.length; ++i) { expr = parts[i] if (expr && (expr = i & 1 ? _parseExpr(expr, 1, qstr) : '"' + expr .replace(/\\/g, '\\\\') .replace(/\r\n?|\n/g, '\\n') .replace(/"/g, '\\"') + '"' )) list[j++] = expr } expr = j < 2 ? list[0] : '[' + list.join(',') + '].join("")' } else { expr = _parseExpr(parts[1], 0, qstr) } if (qstr[0]) { expr = expr.replace(RE_QBMARK, function (_, pos) { return qstr[pos] .replace(/\r/g, '\\r') .replace(/\n/g, '\\n') }) } return expr } var RE_BREND = { '(': /[()]/g, '[': /[[\]]/g, '{': /[{}]/g } function _parseExpr (expr, asText, qstr) { expr = expr .replace(RE_QBLOCK, function (s, div) { return s.length > 2 && !div ? CH_IDEXPR + (qstr.push(s) - 1) + '~' : s }) .replace(/\s+/g, ' ').trim() .replace(/\ ?([[\({},?\.:])\ ?/g, '$1') if (expr) { var list = [], cnt = 0, match while (expr && (match = expr.match(RE_CSNAME)) && !match.index ) { var key, jsb, re = /,|([[{(])|$/g expr = RegExp.rightContext key = match[2] ? qstr[match[2]].slice(1, -1).trim().replace(/\s+/g, ' ') : match[1] while (jsb = (match = re.exec(expr))[1]) skipBraces(jsb, re) jsb = expr.slice(0, match.index) expr = RegExp.rightContext list[cnt++] = _wrapExpr(jsb, 1, key) } expr = !cnt ? _wrapExpr(expr, asText) : cnt > 1 ? '[' + list.join(',') + '].join(" ").trim()' : list[0] } return expr function skipBraces (ch, re) { var mm, lv = 1, ir = RE_BREND[ch] ir.lastIndex = re.lastIndex while (mm = ir.exec(expr)) { if (mm[0] === ch) ++lv else if (!--lv) break } re.lastIndex = lv ? expr.length : ir.lastIndex } } // istanbul ignore next: not both var // eslint-disable-next-line max-len JS_CONTEXT = '"in this?this:' + (typeof window !== 'object' ? 'global' : 'window') + ').', JS_VARNAME = /[,{][\$\w]+(?=:)|(^ *|[^$\w\.{])(?!(?:typeof|true|false|null|undefined|in|instanceof|is(?:Finite|NaN)|void|NaN|new|Date|RegExp|Math)(?![$\w]))([$_A-Za-z][$\w]*)/g, JS_NOPROPS = /^(?=(\.[$\w]+))\1(?:[^.[(]|$)/ function _wrapExpr (expr, asText, key) { var tb expr = expr.replace(JS_VARNAME, function (match, p, mvar, pos, s) { if (mvar) { pos = tb ? 0 : pos + match.length if (mvar !== 'this' && mvar !== 'global' && mvar !== 'window') { match = p + '("' + mvar + JS_CONTEXT + mvar if (pos) tb = (s = s[pos]) === '.' || s === '(' || s === '[' } else if (pos) { tb = !JS_NOPROPS.test(s.slice(pos)) } } return match }) if (tb) { expr = 'try{return ' + expr + '}catch(e){E(e,this)}' } if (key) { expr = (tb ? 'function(){' + expr + '}.call(this)' : '(' + expr + ')' ) + '?"' + key + '":""' } else if (asText) { expr = 'function(v){' + (tb ? expr.replace('return ', 'v=') : 'v=(' + expr + ')' ) + ';return v||v===0?v:""}.call(this)' } return expr } _tmpl.version = brackets.version = 'v2.4.2' return _tmpl })() /* lib/browser/tag/mkdom.js Includes hacks needed for the Internet Explorer version 9 and below See: http://kangax.github.io/compat-table/es5/#ie8 http://codeplanet.io/dropping-ie8/ */ var mkdom = (function _mkdom() { var reHasYield = /<yield\b/i, reYieldAll = /<yield\s*(?:\/>|>([\S\s]*?)<\/yield\s*>|>)/ig, reYieldSrc = /<yield\s+to=['"]([^'">]*)['"]\s*>([\S\s]*?)<\/yield\s*>/ig, reYieldDest = /<yield\s+from=['"]?([-\w]+)['"]?\s*(?:\/>|>([\S\s]*?)<\/yield\s*>)/ig var rootEls = { tr: 'tbody', th: 'tr', td: 'tr', col: 'colgroup' }, tblTags = IE_VERSION && IE_VERSION < 10 ? SPECIAL_TAGS_REGEX : /^(?:t(?:body|head|foot|[rhd])|caption|col(?:group)?)$/ /** * Creates a DOM element to wrap the given content. Normally an `DIV`, but can be * also a `TABLE`, `SELECT`, `TBODY`, `TR`, or `COLGROUP` element. * * @param {string} templ - The template coming from the custom tag definition * @param {string} [html] - HTML content that comes from the DOM element where you * will mount the tag, mostly the original tag in the page * @returns {HTMLElement} DOM element with _templ_ merged through `YIELD` with the _html_. */ function _mkdom(templ, html) { var match = templ && templ.match(/^\s*<([-\w]+)/), tagName = match && match[1].toLowerCase(), el = mkEl('div', isSVGTag(tagName)) // replace all the yield tags with the tag inner html templ = replaceYield(templ, html) /* istanbul ignore next */ if (tblTags.test(tagName)) el = specialTags(el, templ, tagName) else setInnerHTML(el, templ) el.stub = true return el } /* Creates the root element for table or select child elements: tr/th/td/thead/tfoot/tbody/caption/col/colgroup/option/optgroup */ function specialTags(el, templ, tagName) { var select = tagName[0] === 'o', parent = select ? 'select>' : 'table>' // trim() is important here, this ensures we don't have artifacts, // so we can check if we have only one element inside the parent el.innerHTML = '<' + parent + templ.trim() + '</' + parent parent = el.firstChild // returns the immediate parent if tr/th/td/col is the only element, if not // returns the whole tree, as this can include additional elements if (select) { parent.selectedIndex = -1 // for IE9, compatible w/current riot behavior } else { // avoids insertion of cointainer inside container (ex: tbody inside tbody) var tname = rootEls[tagName] if (tname && parent.childElementCount === 1) parent = $(tname, parent) } return parent } /* Replace the yield tag from any tag template with the innerHTML of the original tag in the page */ function replaceYield(templ, html) { // do nothing if no yield if (!reHasYield.test(templ)) return templ // be careful with #1343 - string on the source having `$1` var src = {} html = html && html.replace(reYieldSrc, function (_, ref, text) { src[ref] = src[ref] || text // preserve first definition return '' }).trim() return templ .replace(reYieldDest, function (_, ref, def) { // yield with from - to attrs return src[ref] || def || '' }) .replace(reYieldAll, function (_, def) { // yield without any "from" return html || def || '' }) } return _mkdom })() /** * Convert the item looped into an object used to extend the child tag properties * @param { Object } expr - object containing the keys used to extend the children tags * @param { * } key - value to assign to the new object returned * @param { * } val - value containing the position of the item in the array * @returns { Object } - new object containing the values of the original item * * The variables 'key' and 'val' are arbitrary. * They depend on the collection type looped (Array, Object) * and on the expression used on the each tag * */ function mkitem(expr, key, val) { var item = {} item[expr.key] = key if (expr.pos) item[expr.pos] = val return item } /** * Unmount the redundant tags * @param { Array } items - array containing the current items to loop * @param { Array } tags - array containing all the children tags */ function unmountRedundant(items, tags) { var i = tags.length, j = items.length, t while (i > j) { t = tags[--i] tags.splice(i, 1) t.unmount() } } /** * Move the nested custom tags in non custom loop tags * @param { Object } child - non custom loop tag * @param { Number } i - current position of the loop tag */ function moveNestedTags(child, i) { Object.keys(child.tags).forEach(function(tagName) { var tag = child.tags[tagName] if (isArray(tag)) each(tag, function (t) { moveChildTag(t, tagName, i) }) else moveChildTag(tag, tagName, i) }) } /** * Adds the elements for a virtual tag * @param { Tag } tag - the tag whose root's children will be inserted or appended * @param { Node } src - the node that will do the inserting or appending * @param { Tag } target - only if inserting, insert before this tag's first child */ function addVirtual(tag, src, target) { var el = tag._root, sib tag._virts = [] while (el) { sib = el.nextSibling if (target) src.insertBefore(el, target._root) else src.appendChild(el) tag._virts.push(el) // hold for unmounting el = sib } } /** * Move virtual tag and all child nodes * @param { Tag } tag - first child reference used to start move * @param { Node } src - the node that will do the inserting * @param { Tag } target - insert before this tag's first child * @param { Number } len - how many child nodes to move */ function moveVirtual(tag, src, target, len) { var el = tag._root, sib, i = 0 for (; i < len; i++) { sib = el.nextSibling src.insertBefore(el, target._root) el = sib } } /** * Manage tags having the 'each' * @param { Object } dom - DOM node we need to loop * @param { Tag } parent - parent tag instance where the dom node is contained * @param { String } expr - string contained in the 'each' attribute */ function _each(dom, parent, expr) { // remove the each property from the original tag remAttr(dom, 'each') var mustReorder = typeof getAttr(dom, 'no-reorder') !== T_STRING || remAttr(dom, 'no-reorder'), tagName = getTagName(dom), impl = __tagImpl[tagName] || { tmpl: getOuterHTML(dom) }, useRoot = SPECIAL_TAGS_REGEX.test(tagName), root = dom.parentNode, ref = document.createTextNode(''), child = getTag(dom), isOption = tagName.toLowerCase() === 'option', // the option tags must be treated differently tags = [], oldItems = [], hasKeys, isVirtual = dom.tagName == 'VIRTUAL' // parse the each expression expr = tmpl.loopKeys(expr) // insert a marked where the loop tags will be injected root.insertBefore(ref, dom) // clean template code parent.one('before-mount', function () { // remove the original DOM node dom.parentNode.removeChild(dom) if (root.stub) root = parent.root }).on('update', function () { // get the new items collection var items = tmpl(expr.val, parent), // create a fragment to hold the new DOM nodes to inject in the parent tag frag = document.createDocumentFragment() // object loop. any changes cause full redraw if (!isArray(items)) { hasKeys = items || false items = hasKeys ? Object.keys(items).map(function (key) { return mkitem(expr, key, items[key]) }) : [] } // loop all the new items var i = 0, itemsLength = items.length for (; i < itemsLength; i++) { // reorder only if the items are objects var item = items[i], _mustReorder = mustReorder && typeof item == T_OBJECT && !hasKeys, oldPos = oldItems.indexOf(item), pos = ~oldPos && _mustReorder ? oldPos : i, // does a tag exist in this position? tag = tags[pos] item = !hasKeys && expr.key ? mkitem(expr, item, i) : item // new tag if ( !_mustReorder && !tag // with no-reorder we just update the old tags || _mustReorder && !~oldPos || !tag // by default we always try to reorder the DOM elements ) { tag = new Tag(impl, { parent: parent, isLoop: true, hasImpl: !!__tagImpl[tagName], root: useRoot ? root : dom.cloneNode(), item: item }, dom.innerHTML) tag.mount() if (isVirtual) tag._root = tag.root.firstChild // save reference for further moves or inserts // this tag must be appended if (i == tags.length || !tags[i]) { // fix 1581 if (isVirtual) addVirtual(tag, frag) else frag.appendChild(tag.root) } // this tag must be insert else { if (isVirtual) addVirtual(tag, root, tags[i]) else root.insertBefore(tag.root, tags[i].root) // #1374 some browsers reset selected here oldItems.splice(i, 0, item) } tags.splice(i, 0, tag) pos = i // handled here so no move } else tag.update(item, true) // reorder the tag if it's not located in its previous position if ( pos !== i && _mustReorder && tags[i] // fix 1581 unable to reproduce it in a test! ) { // update the DOM if (isVirtual) moveVirtual(tag, root, tags[i], dom.childNodes.length) else if (tags[i].root.parentNode) root.insertBefore(tag.root, tags[i].root) // update the position attribute if it exists if (expr.pos) tag[expr.pos] = i // move the old tag instance tags.splice(i, 0, tags.splice(pos, 1)[0]) // move the old item oldItems.splice(i, 0, oldItems.splice(pos, 1)[0]) // if the loop tags are not custom // we need to move all their custom tags into the right position if (!child && tag.tags) moveNestedTags(tag, i) } // cache the original item to use it in the events bound to this node // and its children tag._item = item // cache the real parent tag internally defineProperty(tag, '_parent', parent) } // remove the redundant tags unmountRedundant(items, tags) // insert the new nodes root.insertBefore(frag, ref) if (isOption) { // #1374 FireFox bug in <option selected={expression}> if (FIREFOX && !root.multiple) { for (var n = 0; n < root.length; n++) { if (root[n].__riot1374) { root.selectedIndex = n // clear other options delete root[n].__riot1374 break } } } } // set the 'tags' property of the parent tag // if child is 'undefined' it means that we don't need to set this property // for example: // we don't need store the `myTag.tags['div']` property if we are looping a div tag // but we need to track the `myTag.tags['child']` property looping a custom child node named `child` if (child) parent.tags[tagName] = tags // clone the items array oldItems = items.slice() }) } /** * Object that will be used to inject and manage the css of every tag instance */ var styleManager = (function(_riot) { if (!window) return { // skip injection on the server add: function () {}, inject: function () {} } var styleNode = (function () { // create a new style element with the correct type var newNode = mkEl('style') setAttr(newNode, 'type', 'text/css') // replace any user node or insert the new one into the head var userNode = $('style[type=riot]') if (userNode) { if (userNode.id) newNode.id = userNode.id userNode.parentNode.replaceChild(newNode, userNode) } else document.getElementsByTagName('head')[0].appendChild(newNode) return newNode })() // Create cache and shortcut to the correct property var cssTextProp = styleNode.styleSheet, stylesToInject = '' // Expose the style node in a non-modificable property Object.defineProperty(_riot, 'styleNode', { value: styleNode, writable: true }) /** * Public api */ return { /** * Save a tag style to be later injected into DOM * @param { String } css [description] */ add: function(css) { stylesToInject += css }, /** * Inject all previously saved tag styles into DOM * innerHTML seems slow: http://jsperf.com/riot-insert-style */ inject: function() { if (stylesToInject) { if (cssTextProp) cssTextProp.cssText += stylesToInject else styleNode.innerHTML += stylesToInject stylesToInject = '' } } } })(riot) function parseNamedElements(root, tag, childTags, forceParsingNamed) { walk(root, function(dom) { if (dom.nodeType == 1) { dom.isLoop = dom.isLoop || (dom.parentNode && dom.parentNode.isLoop || getAttr(dom, 'each')) ? 1 : 0 // custom child tag if (childTags) { var child = getTag(dom) if (child && !dom.isLoop) childTags.push(initChildTag(child, {root: dom, parent: tag}, dom.innerHTML, tag)) } if (!dom.isLoop || forceParsingNamed) setNamed(dom, tag, []) } }) } function parseExpressions(root, tag, expressions) { function addExpr(dom, val, extra) { if (tmpl.hasExpr(val)) { expressions.push(extend({ dom: dom, expr: val }, extra)) } } walk(root, function(dom) { var type = dom.nodeType, attr // text node if (type == 3 && dom.parentNode.tagName != 'STYLE') addExpr(dom, dom.nodeValue) if (type != 1) return /* element */ // loop attr = getAttr(dom, 'each') if (attr) { _each(dom, tag, attr); return false } // attribute expressions each(dom.attributes, function(attr) { var name = attr.name, bool = name.split('__')[1] addExpr(dom, attr.value, { attr: bool || name, bool: bool }) if (bool) { remAttr(dom, name); return false } }) // skip custom tags if (getTag(dom)) return false }) } function Tag(impl, conf, innerHTML) { var self = riot.observable(this), opts = inherit(conf.opts) || {}, parent = conf.parent, isLoop = conf.isLoop, hasImpl = conf.hasImpl, item = cleanUpData(conf.item), expressions = [], childTags = [], root = conf.root, tagName = root.tagName.toLowerCase(), attr = {}, propsInSyncWithParent = [], dom // only call unmount if we have a valid __tagImpl (has name property) if (impl.name && root._tag) root._tag.unmount(true) // not yet mounted this.isMounted = false root.isLoop = isLoop // keep a reference to the tag just created // so we will be able to mount this tag multiple times root._tag = this // create a unique id to this tag // it could be handy to use it also to improve the virtual dom rendering speed defineProperty(this, '_riot_id', ++__uid) // base 1 allows test !t._riot_id extend(this, { parent: parent, root: root, opts: opts}, item) // protect the "tags" property from being overridden defineProperty(this, 'tags', {}) // grab attributes each(root.attributes, function(el) { var val = el.value // remember attributes with expressions only if (tmpl.hasExpr(val)) attr[el.name] = val }) dom = mkdom(impl.tmpl, innerHTML) // options function updateOpts() { var ctx = hasImpl && isLoop ? self : parent || self // update opts from current DOM attributes each(root.attributes, function(el) { var val = el.value opts[toCamel(el.name)] = tmpl.hasExpr(val) ? tmpl(val, ctx) : val }) // recover those with expressions each(Object.keys(attr), function(name) { opts[toCamel(name)] = tmpl(attr[name], ctx) }) } function normalizeData(data) { for (var key in item) { if (typeof self[key] !== T_UNDEF && isWritable(self, key)) self[key] = data[key] } } function inheritFrom(target) { each(Object.keys(target), function(k) { // some properties must be always in sync with the parent tag var mustSync = !RESERVED_WORDS_BLACKLIST.test(k) && contains(propsInSyncWithParent, k) if (typeof self[k] === T_UNDEF || mustSync) { // track the property to keep in sync // so we can keep it updated if (!mustSync) propsInSyncWithParent.push(k) self[k] = target[k] } }) } /** * Update the tag expressions and options * @param { * } data - data we want to use to extend the tag properties * @param { Boolean } isInherited - is this update coming from a parent tag? * @returns { self } */ defineProperty(this, 'update', function(data, isInherited) { // make sure the data passed will not override // the component core methods data = cleanUpData(data) // inherit properties from the parent in loop if (isLoop) { inheritFrom(self.parent) } // normalize the tag properties in case an item object was initially passed if (data && isObject(item)) { normalizeData(data) item = data } extend(self, data) updateOpts() self.trigger('update', data) update(expressions, self) // the updated event will be triggered // once the DOM will be ready and all the re-flows are completed // this is useful if you want to get the "real" root properties // 4 ex: root.offsetWidth ... if (isInherited && self.parent) // closes #1599 self.parent.one('updated', function() { self.trigger('updated') }) else rAF(function() { self.trigger('updated') }) return this }) defineProperty(this, 'mixin', function() { each(arguments, function(mix) { var instance, props = [], obj mix = typeof mix === T_STRING ? riot.mixin(mix) : mix // check if the mixin is a function if (isFunction(mix)) { // create the new mixin instance instance = new mix() } else instance = mix var proto = Object.getPrototypeOf(instance) // build multilevel prototype inheritance chain property list do props = props.concat(Object.getOwnPropertyNames(obj || instance)) while (obj = Object.getPrototypeOf(obj || instance)) // loop the keys in the function prototype or the all object keys each(props, function(key) { // bind methods to self // allow mixins to override other properties/parent mixins if (key != 'init') { // check for getters/setters var descriptor = Object.getOwnPropertyDescriptor(instance, key) || Object.getOwnPropertyDescriptor(proto, key) var hasGetterSetter = descriptor && (descriptor.get || descriptor.set) // apply method only if it does not already exist on the instance if (!self.hasOwnProperty(key) && hasGetterSetter) { Object.defineProperty(self, key, descriptor) } else { self[key] = isFunction(instance[key]) ? instance[key].bind(self) : instance[key] } } }) // init method will be called automatically if (instance.init) instance.init.bind(self)() }) return this }) defineProperty(this, 'mount', function() { updateOpts() // add global mixins var globalMixin = riot.mixin(GLOBAL_MIXIN) if (globalMixin) for (var i in globalMixin) if (globalMixin.hasOwnProperty(i)) self.mixin(globalMixin[i]) // children in loop should inherit from true parent if (self._parent && self._parent.root.isLoop) { inheritFrom(self._parent) } // initialiation if (impl.fn) impl.fn.call(self, opts) // parse layout after init. fn may calculate args for nested custom tags parseExpressions(dom, self, expressions) // mount the child tags toggle(true) // update the root adding custom attributes coming from the compiler // it fixes also #1087 if (impl.attrs) walkAttributes(impl.attrs, function (k, v) { setAttr(root, k, v) }) if (impl.attrs || hasImpl) parseExpressions(self.root, self, expressions) if (!self.parent || isLoop) self.update(item) // internal use only, fixes #403 self.trigger('before-mount') if (isLoop && !hasImpl) { // update the root attribute for the looped elements root = dom.firstChild } else { while (dom.firstChild) root.appendChild(dom.firstChild) if (root.stub) root = parent.root } defineProperty(self, 'root', root) // parse the named dom nodes in the looped child // adding them to the parent as well if (isLoop) parseNamedElements(self.root, self.parent, null, true) // if it's not a child tag we can trigger its mount event if (!self.parent || self.parent.isMounted) { self.isMounted = true self.trigger('mount') } // otherwise we need to wait that the parent event gets triggered else self.parent.one('mount', function() { // avoid to trigger the `mount` event for the tags // not visible included in an if statement if (!isInStub(self.root)) { self.parent.isMounted = self.isMounted = true self.trigger('mount') } }) }) defineProperty(this, 'unmount', function(keepRootTag) { var el = root, p = el.parentNode, ptag, tagIndex = __virtualDom.indexOf(self) self.trigger('before-unmount') // remove this tag instance from the global virtualDom variable if (~tagIndex) __virtualDom.splice(tagIndex, 1) if (p) { if (parent) { ptag = getImmediateCustomParentTag(parent) // remove this tag from the parent tags object // if there are multiple nested tags with same name.. // remove this element form the array if (isArray(ptag.tags[tagName])) each(ptag.tags[tagName], function(tag, i) { if (tag._riot_id == self._riot_id) ptag.tags[tagName].splice(i, 1) }) else // otherwise just delete the tag instance ptag.tags[tagName] = undefined } else while (el.firstChild) el.removeChild(el.firstChild) if (!keepRootTag) p.removeChild(el) else { // the riot-tag and the data-is attributes aren't needed anymore, remove them remAttr(p, RIOT_TAG_IS) remAttr(p, RIOT_TAG) // this will be removed in riot 3.0.0 } } if (this._virts) { each(this._virts, function(v) { if (v.parentNode) v.parentNode.removeChild(v) }) } self.trigger('unmount') toggle() self.off('*') self.isMounted = false delete root._tag }) // proxy function to bind updates // dispatched from a parent tag function onChildUpdate(data) { self.update(data, true) } function toggle(isMount) { // mount/unmount children each(childTags, function(child) { child[isMount ? 'mount' : 'unmount']() }) // listen/unlisten parent (events flow one way from parent to children) if (!parent) return var evt = isMount ? 'on' : 'off' // the loop tags will be always in sync with the parent automatically if (isLoop) parent[evt]('unmount', self.unmount) else { parent[evt]('update', onChildUpdate)[evt]('unmount', self.unmount) } } // named elements available for fn parseNamedElements(dom, this, childTags) } /** * Attach an event to a DOM node * @param { String } name - event name * @param { Function } handler - event callback * @param { Object } dom - dom node * @param { Tag } tag - tag instance */ function setEventHandler(name, handler, dom, tag) { dom[name] = function(e) { var ptag = tag._parent, item = tag._item, el if (!item) while (ptag && !item) { item = ptag._item ptag = ptag._parent } // cross browser event fix e = e || window.event // override the event properties if (isWritable(e, 'currentTarget')) e.currentTarget = dom if (isWritable(e, 'target')) e.target = e.srcElement if (isWritable(e, 'which')) e.which = e.charCode || e.keyCode e.item = item // prevent default behaviour (by default) if (handler.call(tag, e) !== true && !/radio|check/.test(dom.type)) { if (e.preventDefault) e.preventDefault() e.returnValue = false } if (!e.preventUpdate) { el = item ? getImmediateCustomParentTag(ptag) : tag el.update() } } } /** * Insert a DOM node replacing another one (used by if- attribute) * @param { Object } root - parent node * @param { Object } node - node replaced * @param { Object } before - node added */ function insertTo(root, node, before) { if (!root) return root.insertBefore(before, node) root.removeChild(node) } /** * Update the expressions in a Tag instance * @param { Array } expressions - expression that must be re evaluated * @param { Tag } tag - tag instance */ function update(expressions, tag) { each(expressions, function(expr, i) { var dom = expr.dom, attrName = expr.attr, value = tmpl(expr.expr, tag), parent = expr.parent || expr.dom.parentNode if (expr.bool) { value = !!value } else if (value == null) { value = '' } // #1638: regression of #1612, update the dom only if the value of the // expression was changed if (expr.value === value) { return } expr.value = value // textarea and text nodes has no attribute name if (!attrName) { // about #815 w/o replace: the browser converts the value to a string, // the comparison by "==" does too, but not in the server value += '' // test for parent avoids error with invalid assignment to nodeValue if (parent) { // cache the parent node because somehow it will become null on IE // on the next iteration expr.parent = parent if (parent.tagName === 'TEXTAREA') { parent.value = value // #1113 if (!IE_VERSION) dom.nodeValue = value // #1625 IE throws here, nodeValue } // will be available on 'updated' else dom.nodeValue = value } return } // ~~#1612: look for changes in dom.value when updating the value~~ if (attrName === 'value') { if (dom.value !== value) { dom.value = value setAttr(dom, attrName, value) } return } else { // remove original attribute remAttr(dom, attrName) } // event handler if (isFunction(value)) { setEventHandler(attrName, value, dom, tag) // if- conditional } else if (attrName == 'if') { var stub = expr.stub, add = function() { insertTo(stub.parentNode, stub, dom) }, remove = function() { insertTo(dom.parentNode, dom, stub) } // add to DOM if (value) { if (stub) { add() dom.inStub = false // avoid to trigger the mount event if the tags is not visible yet // maybe we can optimize this avoiding to mount the tag at all if (!isInStub(dom)) { walk(dom, function(el) { if (el._tag && !el._tag.isMounted) el._tag.isMounted = !!el._tag.trigger('mount') }) } } // remove from DOM } else { stub = expr.stub = stub || document.createTextNode('') // if the parentNode is defined we can easily replace the tag if (dom.parentNode) remove() // otherwise we need to wait the updated event else (tag.parent || tag).one('updated', remove) dom.inStub = true } // show / hide } else if (attrName === 'show') { dom.style.display = value ? '' : 'none' } else if (attrName === 'hide') { dom.style.display = value ? 'none' : '' } else if (expr.bool) { dom[attrName] = value if (value) setAttr(dom, attrName, attrName) if (FIREFOX && attrName === 'selected' && dom.tagName === 'OPTION') { dom.__riot1374 = value // #1374 } } else if (value === 0 || value && typeof value !== T_OBJECT) { // <img src="{ expr }"> if (startsWith(attrName, RIOT_PREFIX) && attrName != RIOT_TAG) { attrName = attrName.slice(RIOT_PREFIX.length) } setAttr(dom, attrName, value) } }) } /** * Specialized function for looping an array-like collection with `each={}` * @param { Array } els - collection of items * @param {Function} fn - callback function * @returns { Array } the array looped */ function each(els, fn) { var len = els ? els.length : 0 for (var i = 0, el; i < len; i++) { el = els[i] // return false -> current item was removed by fn during the loop if (el != null && fn(el, i) === false) i-- } return els } /** * Detect if the argument passed is a function * @param { * } v - whatever you want to pass to this function * @returns { Boolean } - */ function isFunction(v) { return typeof v === T_FUNCTION || false // avoid IE problems } /** * Get the outer html of any DOM node SVGs included * @param { Object } el - DOM node to parse * @returns { String } el.outerHTML */ function getOuterHTML(el) { if (el.outerHTML) return el.outerHTML // some browsers do not support outerHTML on the SVGs tags else { var container = mkEl('div') container.appendChild(el.cloneNode(true)) return container.innerHTML } } /** * Set the inner html of any DOM node SVGs included * @param { Object } container - DOM node where we will inject the new html * @param { String } html - html to inject */ function setInnerHTML(container, html) { if (typeof container.innerHTML != T_UNDEF) container.innerHTML = html // some browsers do not support innerHTML on the SVGs tags else { var doc = new DOMParser().parseFromString(html, 'application/xml') container.appendChild( container.ownerDocument.importNode(doc.documentElement, true) ) } } /** * Checks wether a DOM node must be considered part of an svg document * @param { String } name - tag name * @returns { Boolean } - */ function isSVGTag(name) { return ~SVG_TAGS_LIST.indexOf(name) } /** * Detect if the argument passed is an object, exclude null. * NOTE: Use isObject(x) && !isArray(x) to excludes arrays. * @param { * } v - whatever you want to pass to this function * @returns { Boolean } - */ function isObject(v) { return v && typeof v === T_OBJECT // typeof null is 'object' } /** * Remove any DOM attribute from a node * @param { Object } dom - DOM node we want to update * @param { String } name - name of the property we want to remove */ function remAttr(dom, name) { dom.removeAttribute(name) } /** * Convert a string containing dashes to camel case * @param { String } string - input string * @returns { String } my-string -> myString */ function toCamel(string) { return string.replace(/-(\w)/g, function(_, c) { return c.toUpperCase() }) } /** * Get the value of any DOM attribute on a node * @param { Object } dom - DOM node we want to parse * @param { String } name - name of the attribute we want to get * @returns { String | undefined } name of the node attribute whether it exists */ function getAttr(dom, name) { return dom.getAttribute(name) } /** * Set any DOM/SVG attribute * @param { Object } dom - DOM node we want to update * @param { String } name - name of the property we want to set * @param { String } val - value of the property we want to set */ function setAttr(dom, name, val) { var xlink = XLINK_REGEX.exec(name) if (xlink && xlink[1]) dom.setAttributeNS(XLINK_NS, xlink[1], val) else dom.setAttribute(name, val) } /** * Detect the tag implementation by a DOM node * @param { Object } dom - DOM node we need to parse to get its tag implementation * @returns { Object } it returns an object containing the implementation of a custom tag (template and boot function) */ function getTag(dom) { return dom.tagName && __tagImpl[getAttr(dom, RIOT_TAG_IS) || getAttr(dom, RIOT_TAG) || dom.tagName.toLowerCase()] } /** * Add a child tag to its parent into the `tags` object * @param { Object } tag - child tag instance * @param { String } tagName - key where the new tag will be stored * @param { Object } parent - tag instance where the new child tag will be included */ function addChildTag(tag, tagName, parent) { var cachedTag = parent.tags[tagName] // if there are multiple children tags having the same name if (cachedTag) { // if the parent tags property is not yet an array // create it adding the first cached tag if (!isArray(cachedTag)) // don't add the same tag twice if (cachedTag !== tag) parent.tags[tagName] = [cachedTag] // add the new nested tag to the array if (!contains(parent.tags[tagName], tag)) parent.tags[tagName].push(tag) } else { parent.tags[tagName] = tag } } /** * Move the position of a custom tag in its parent tag * @param { Object } tag - child tag instance * @param { String } tagName - key where the tag was stored * @param { Number } newPos - index where the new tag will be stored */ function moveChildTag(tag, tagName, newPos) { var parent = tag.parent, tags // no parent no move if (!parent) return tags = parent.tags[tagName] if (isArray(tags)) tags.splice(newPos, 0, tags.splice(tags.indexOf(tag), 1)[0]) else addChildTag(tag, tagName, parent) } /** * Create a new child tag including it correctly into its parent * @param { Object } child - child tag implementation * @param { Object } opts - tag options containing the DOM node where the tag will be mounted * @param { String } innerHTML - inner html of the child node * @param { Object } parent - instance of the parent tag including the child custom tag * @returns { Object } instance of the new child tag just created */ function initChildTag(child, opts, innerHTML, parent) { var tag = new Tag(child, opts, innerHTML), tagName = getTagName(opts.root), ptag = getImmediateCustomParentTag(parent) // fix for the parent attribute in the looped elements tag.parent = ptag // store the real parent tag // in some cases this could be different from the custom parent tag // for example in nested loops tag._parent = parent // add this tag to the custom parent tag addChildTag(tag, tagName, ptag) // and also to the real parent tag if (ptag !== parent) addChildTag(tag, tagName, parent) // empty the child node once we got its template // to avoid that its children get compiled multiple times opts.root.innerHTML = '' return tag } /** * Loop backward all the parents tree to detect the first custom parent tag * @param { Object } tag - a Tag instance * @returns { Object } the instance of the first custom parent tag found */ function getImmediateCustomParentTag(tag) { var ptag = tag while (!getTag(ptag.root)) { if (!ptag.parent) break ptag = ptag.parent } return ptag } /** * Helper function to set an immutable property * @param { Object } el - object where the new property will be set * @param { String } key - object key where the new property will be stored * @param { * } value - value of the new property * @param { Object } options - set the propery overriding the default options * @returns { Object } - the initial object */ function defineProperty(el, key, value, options) { Object.defineProperty(el, key, extend({ value: value, enumerable: false, writable: false, configurable: true }, options)) return el } /** * Get the tag name of any DOM node * @param { Object } dom - DOM node we want to parse * @returns { String } name to identify this dom node in riot */ function getTagName(dom) { var child = getTag(dom), namedTag = getAttr(dom, 'name'), tagName = namedTag && !tmpl.hasExpr(namedTag) ? namedTag : child ? child.name : dom.tagName.toLowerCase() return tagName } /** * Extend any object with other properties * @param { Object } src - source object * @returns { Object } the resulting extended object * * var obj = { foo: 'baz' } * extend(obj, {bar: 'bar', foo: 'bar'}) * console.log(obj) => {bar: 'bar', foo: 'bar'} * */ function extend(src) { var obj, args = arguments for (var i = 1; i < args.length; ++i) { if (obj = args[i]) { for (var key in obj) { // check if this property of the source object could be overridden if (isWritable(src, key)) src[key] = obj[key] } } } return src } /** * Check whether an array contains an item * @param { Array } arr - target array * @param { * } item - item to test * @returns { Boolean } Does 'arr' contain 'item'? */ function contains(arr, item) { return ~arr.indexOf(item) } /** * Check whether an object is a kind of array * @param { * } a - anything * @returns {Boolean} is 'a' an array? */ function isArray(a) { return Array.isArray(a) || a instanceof Array } /** * Detect whether a property of an object could be overridden * @param { Object } obj - source object * @param { String } key - object property * @returns { Boolean } is this property writable? */ function isWritable(obj, key) { var props = Object.getOwnPropertyDescriptor(obj, key) return typeof obj[key] === T_UNDEF || props && props.writable } /** * With this function we avoid that the internal Tag methods get overridden * @param { Object } data - options we want to use to extend the tag instance * @returns { Object } clean object without containing the riot internal reserved words */ function cleanUpData(data) { if (!(data instanceof Tag) && !(data && typeof data.trigger == T_FUNCTION)) return data var o = {} for (var key in data) { if (!RESERVED_WORDS_BLACKLIST.test(key)) o[key] = data[key] } return o } /** * Walk down recursively all the children tags starting dom node * @param { Object } dom - starting node where we will start the recursion * @param { Function } fn - callback to transform the child node just found */ function walk(dom, fn) { if (dom) { // stop the recursion if (fn(dom) === false) return else { dom = dom.firstChild while (dom) { walk(dom, fn) dom = dom.nextSibling } } } } /** * Minimize risk: only zero or one _space_ between attr & value * @param { String } html - html string we want to parse * @param { Function } fn - callback function to apply on any attribute found */ function walkAttributes(html, fn) { var m, re = /([-\w]+) ?= ?(?:"([^"]*)|'([^']*)|({[^}]*}))/g while (m = re.exec(html)) { fn(m[1].toLowerCase(), m[2] || m[3] || m[4]) } } /** * Check whether a DOM node is in stub mode, useful for the riot 'if' directive * @param { Object } dom - DOM node we want to parse * @returns { Boolean } - */ function isInStub(dom) { while (dom) { if (dom.inStub) return true dom = dom.parentNode } return false } /** * Create a generic DOM node * @param { String } name - name of the DOM node we want to create * @param { Boolean } isSvg - should we use a SVG as parent node? * @returns { Object } DOM node just created */ function mkEl(name, isSvg) { return isSvg ? document.createElementNS('http://www.w3.org/2000/svg', 'svg') : document.createElement(name) } /** * Shorter and fast way to select multiple nodes in the DOM * @param { String } selector - DOM selector * @param { Object } ctx - DOM node where the targets of our search will is located * @returns { Object } dom nodes found */ function $$(selector, ctx) { return (ctx || document).querySelectorAll(selector) } /** * Shorter and fast way to select a single node in the DOM * @param { String } selector - unique dom selector * @param { Object } ctx - DOM node where the target of our search will is located * @returns { Object } dom node found */ function $(selector, ctx) { return (ctx || document).querySelector(selector) } /** * Simple object prototypal inheritance * @param { Object } parent - parent object * @returns { Object } child instance */ function inherit(parent) { return Object.create(parent || null) } /** * Get the name property needed to identify a DOM node in riot * @param { Object } dom - DOM node we need to parse * @returns { String | undefined } give us back a string to identify this dom node */ function getNamedKey(dom) { return getAttr(dom, 'id') || getAttr(dom, 'name') } /** * Set the named properties of a tag element * @param { Object } dom - DOM node we need to parse * @param { Object } parent - tag instance where the named dom element will be eventually added * @param { Array } keys - list of all the tag instance properties */ function setNamed(dom, parent, keys) { // get the key value we want to add to the tag instance var key = getNamedKey(dom), isArr, // add the node detected to a tag instance using the named property add = function(value) { // avoid to override the tag properties already set if (contains(keys, key)) return // check whether this value is an array isArr = isArray(value) // if the key was never set if (!value) // set it once on the tag instance parent[key] = dom // if it was an array and not yet set else if (!isArr || isArr && !contains(value, dom)) { // add the dom node into the array if (isArr) value.push(dom) else parent[key] = [value, dom] } } // skip the elements with no named properties if (!key) return // check whether this key has been already evaluated if (tmpl.hasExpr(key)) // wait the first updated event only once parent.one('mount', function() { key = getNamedKey(dom) add(parent[key]) }) else add(parent[key]) } /** * Faster String startsWith alternative * @param { String } src - source string * @param { String } str - test string * @returns { Boolean } - */ function startsWith(src, str) { return src.slice(0, str.length) === str } /** * requestAnimationFrame function * Adapted from https://gist.github.com/paulirish/1579671, license MIT */ var rAF = (function (w) { var raf = w.requestAnimationFrame || w.mozRequestAnimationFrame || w.webkitRequestAnimationFrame if (!raf || /iP(ad|hone|od).*OS 6/.test(w.navigator.userAgent)) { // buggy iOS6 var lastTime = 0 raf = function (cb) { var nowtime = Date.now(), timeout = Math.max(16 - (nowtime - lastTime), 0) setTimeout(function () { cb(lastTime = nowtime + timeout) }, timeout) } } return raf })(window || {}) /** * Mount a tag creating new Tag instance * @param { Object } root - dom node where the tag will be mounted * @param { String } tagName - name of the riot tag we want to mount * @param { Object } opts - options to pass to the Tag instance * @returns { Tag } a new Tag instance */ function mountTo(root, tagName, opts) { var tag = __tagImpl[tagName], // cache the inner HTML to fix #855 innerHTML = root._innerHTML = root._innerHTML || root.innerHTML // clear the inner html root.innerHTML = '' if (tag && root) tag = new Tag(tag, { root: root, opts: opts }, innerHTML) if (tag && tag.mount) { tag.mount() // add this tag to the virtualDom variable if (!contains(__virtualDom, tag)) __virtualDom.push(tag) } return tag } /** * Riot public api */ // share methods for other riot parts, e.g. compiler riot.util = { brackets: brackets, tmpl: tmpl } /** * Create a mixin that could be globally shared across all the tags */ riot.mixin = (function() { var mixins = {}, globals = mixins[GLOBAL_MIXIN] = {}, _id = 0 /** * Create/Return a mixin by its name * @param { String } name - mixin name (global mixin if object) * @param { Object } mixin - mixin logic * @param { Boolean } g - is global? * @returns { Object } the mixin logic */ return function(name, mixin, g) { // Unnamed global if (isObject(name)) { riot.mixin('__unnamed_'+_id++, name, true) return } var store = g ? globals : mixins // Getter if (!mixin) { if (typeof store[name] === T_UNDEF) { throw new Error('Unregistered mixin: ' + name) } return store[name] } // Setter if (isFunction(mixin)) { extend(mixin.prototype, store[name] || {}) store[name] = mixin } else { store[name] = extend(store[name] || {}, mixin) } } })() /** * Create a new riot tag implementation * @param { String } name - name/id of the new riot tag * @param { String } html - tag template * @param { String } css - custom tag css * @param { String } attrs - root tag attributes * @param { Function } fn - user function * @returns { String } name/id of the tag just created */ riot.tag = function(name, html, css, attrs, fn) { if (isFunction(attrs)) { fn = attrs if (/^[\w\-]+\s?=/.test(css)) { attrs = css css = '' } else attrs = '' } if (css) { if (isFunction(css)) fn = css else styleManager.add(css) } name = name.toLowerCase() __tagImpl[name] = { name: name, tmpl: html, attrs: attrs, fn: fn } return name } /** * Create a new riot tag implementation (for use by the compiler) * @param { String } name - name/id of the new riot tag * @param { String } html - tag template * @param { String } css - custom tag css * @param { String } attrs - root tag attributes * @param { Function } fn - user function * @returns { String } name/id of the tag just created */ riot.tag2 = function(name, html, css, attrs, fn) { if (css) styleManager.add(css) //if (bpair) riot.settings.brackets = bpair __tagImpl[name] = { name: name, tmpl: html, attrs: attrs, fn: fn } return name } /** * Mount a tag using a specific tag implementation * @param { String } selector - tag DOM selector * @param { String } tagName - tag implementation name * @param { Object } opts - tag logic * @returns { Array } new tags instances */ riot.mount = function(selector, tagName, opts) { var els, allTags, tags = [] // helper functions function addRiotTags(arr) { var list = '' each(arr, function (e) { if (!/[^-\w]/.test(e)) { e = e.trim().toLowerCase() list += ',[' + RIOT_TAG_IS + '="' + e + '"],[' + RIOT_TAG + '="' + e + '"]' } }) return list } function selectAllTags() { var keys = Object.keys(__tagImpl) return keys + addRiotTags(keys) } function pushTags(root) { if (root.tagName) { var riotTag = getAttr(root, RIOT_TAG_IS) || getAttr(root, RIOT_TAG) // have tagName? force riot-tag to be the same if (tagName && riotTag !== tagName) { riotTag = tagName setAttr(root, RIOT_TAG_IS, tagName) setAttr(root, RIOT_TAG, tagName) // this will be removed in riot 3.0.0 } var tag = mountTo(root, riotTag || root.tagName.toLowerCase(), opts) if (tag) tags.push(tag) } else if (root.length) { each(root, pushTags) // assume nodeList } } // ----- mount code ----- // inject styles into DOM styleManager.inject() if (isObject(tagName)) { opts = tagName tagName = 0 } // crawl the DOM to find the tag if (typeof selector === T_STRING) { if (selector === '*') // select all the tags registered // and also the tags found with the riot-tag attribute set selector = allTags = selectAllTags() else // or just the ones named like the selector selector += addRiotTags(selector.split(/, */)) // make sure to pass always a selector // to the querySelectorAll function els = selector ? $$(selector) : [] } else // probably you have passed already a tag or a NodeList els = selector // select all the registered and mount them inside their root elements if (tagName === '*') { // get all custom tags tagName = allTags || selectAllTags() // if the root els it's just a single tag if (els.tagName) els = $$(tagName, els) else { // select all the children for all the different root elements var nodeList = [] each(els, function (_el) { nodeList.push($$(tagName, _el)) }) els = nodeList } // get rid of the tagName tagName = 0 } pushTags(els) return tags } /** * Update all the tags instances created * @returns { Array } all the tags instances */ riot.update = function() { return each(__virtualDom, function(tag) { tag.update() }) } /** * Export the Virtual DOM */ riot.vdom = __virtualDom /** * Export the Tag constructor */ riot.Tag = Tag /* istanbul ignore next */ // istanbul ignore next function safeRegex (re) { var src = re.source var opt = re.global ? 'g' : '' if (re.ignoreCase) opt += 'i' if (re.multiline) opt += 'm' for (var i = 1; i < arguments.length; i++) { src = src.replace('@', '\\' + arguments[i]) } return new RegExp(src, opt) } /** * @module parsers */ var parsers = (function (win) { var _p = {} function _r (name) { var parser = win[name] if (parser) return parser throw new Error('Parser "' + name + '" not loaded.') } function _req (name) { var parts = name.split('.') if (parts.length !== 2) throw new Error('Bad format for parsers._req') var parser = _p[parts[0]][parts[1]] if (parser) return parser throw new Error('Parser "' + name + '" not found.') } function extend (obj, props) { if (props) { for (var prop in props) { /* istanbul ignore next */ if (props.hasOwnProperty(prop)) { obj[prop] = props[prop] } } } return obj } function renderPug (compilerName, html, opts, url) { opts = extend({ pretty: true, filename: url, doctype: 'html' }, opts) return _r(compilerName).render(html, opts) } _p.html = { jade: function (html, opts, url) { /* eslint-disable */ console.log('DEPRECATION WARNING: jade was renamed "pug" - The jade parser will be removed in [email protected]!') /* eslint-enable */ return renderPug('jade', html, opts, url) }, pug: function (html, opts, url) { return renderPug('pug', html, opts, url) } } _p.css = { less: function (tag, css, opts, url) { var ret opts = extend({ sync: true, syncImport: true, filename: url }, opts) _r('less').render(css, opts, function (err, result) { // istanbul ignore next if (err) throw err ret = result.css }) return ret } } _p.js = { es6: function (js, opts) { opts = extend({ blacklist: ['useStrict', 'strict', 'react'], sourceMaps: false, comments: false }, opts) return _r('babel').transform(js, opts).code }, babel: function (js, opts, url) { return _r('babel').transform(js, extend({ filename: url }, opts)).code }, buble: function (js, opts, url) { opts = extend({ source: url, modules: false }, opts) return _r('buble').transform(js, opts).code }, coffee: function (js, opts) { return _r('CoffeeScript').compile(js, extend({ bare: true }, opts)) }, livescript: function (js, opts) { return _r('livescript').compile(js, extend({ bare: true, header: false }, opts)) }, typescript: function (js, opts) { return _r('typescript')(js, opts) }, none: function (js) { return js } } _p.js.javascript = _p.js.none _p.js.coffeescript = _p.js.coffee _p._req = _req _p.utils = { extend: extend } return _p })(window || global) riot.parsers = parsers /** * Compiler for riot custom tags * @version v2.5.5 */ var compile = (function () { var extend = parsers.utils.extend /* eslint-enable */ var S_LINESTR = /"[^"\n\\]*(?:\\[\S\s][^"\n\\]*)*"|'[^'\n\\]*(?:\\[\S\s][^'\n\\]*)*'/.source var S_STRINGS = brackets.R_STRINGS.source var HTML_ATTRS = / *([-\w:\xA0-\xFF]+) ?(?:= ?('[^']*'|"[^"]*"|\S+))?/g var HTML_COMMS = RegExp(/<!--(?!>)[\S\s]*?-->/.source + '|' + S_LINESTR, 'g') var HTML_TAGS = /<(-?[A-Za-z][-\w\xA0-\xFF]*)(?:\s+([^"'\/>]*(?:(?:"[^"]*"|'[^']*'|\/[^>])[^'"\/>]*)*)|\s*)(\/?)>/g var HTML_PACK = />[ \t]+<(-?[A-Za-z]|\/[-A-Za-z])/g var BOOL_ATTRS = RegExp( '^(?:disabled|checked|readonly|required|allowfullscreen|auto(?:focus|play)|' + 'compact|controls|default|formnovalidate|hidden|ismap|itemscope|loop|' + 'multiple|muted|no(?:resize|shade|validate|wrap)?|open|reversed|seamless|' + 'selected|sortable|truespeed|typemustmatch)$') var RIOT_ATTRS = ['style', 'src', 'd'] var VOID_TAGS = /^(?:input|img|br|wbr|hr|area|base|col|embed|keygen|link|meta|param|source|track)$/ var PRE_TAGS = /<pre(?:\s+(?:[^">]*|"[^"]*")*)?>([\S\s]+?)<\/pre\s*>/gi var SPEC_TYPES = /^"(?:number|date(?:time)?|time|month|email|color)\b/i var IMPORT_STATEMENT = /^\s*import(?:\s*[*{]|\s+[$_a-zA-Z'"]).*\n?/gm var TRIM_TRAIL = /[ \t]+$/gm var RE_HASEXPR = safeRegex(/@#\d/, 'x01'), RE_REPEXPR = safeRegex(/@#(\d+)/g, 'x01'), CH_IDEXPR = '\x01#', CH_DQCODE = '\u2057', DQ = '"', SQ = "'" function cleanSource (src) { var mm, re = HTML_COMMS if (~src.indexOf('\r')) { src = src.replace(/\r\n?/g, '\n') } re.lastIndex = 0 while ((mm = re.exec(src))) { if (mm[0][0] === '<') { src = RegExp.leftContext + RegExp.rightContext re.lastIndex = mm[3] + 1 } } return src } function parseAttribs (str, pcex) { var list = [], match, type, vexp HTML_ATTRS.lastIndex = 0 str = str.replace(/\s+/g, ' ') while ((match = HTML_ATTRS.exec(str))) { var k = match[1].toLowerCase(), v = match[2] if (!v) { list.push(k) } else { if (v[0] !== DQ) { v = DQ + (v[0] === SQ ? v.slice(1, -1) : v) + DQ } if (k === 'type' && SPEC_TYPES.test(v)) { type = v } else { if (RE_HASEXPR.test(v)) { if (k === 'value') vexp = 1 else if (BOOL_ATTRS.test(k)) k = '__' + k else if (~RIOT_ATTRS.indexOf(k)) k = 'riot-' + k } list.push(k + '=' + v) } } } if (type) { if (vexp) type = DQ + pcex._bp[0] + SQ + type.slice(1, -1) + SQ + pcex._bp[1] + DQ list.push('type=' + type) } return list.join(' ') } function splitHtml (html, opts, pcex) { var _bp = pcex._bp if (html && _bp[4].test(html)) { var jsfn = opts.expr && (opts.parser || opts.type) ? _compileJS : 0, list = brackets.split(html, 0, _bp), expr for (var i = 1; i < list.length; i += 2) { expr = list[i] if (expr[0] === '^') { expr = expr.slice(1) } else if (jsfn) { expr = jsfn(expr, opts).trim() if (expr.slice(-1) === ';') expr = expr.slice(0, -1) } list[i] = CH_IDEXPR + (pcex.push(expr) - 1) + _bp[1] } html = list.join('') } return html } function restoreExpr (html, pcex) { if (pcex.length) { html = html.replace(RE_REPEXPR, function (_, d) { return pcex._bp[0] + pcex[d].trim().replace(/[\r\n]+/g, ' ').replace(/"/g, CH_DQCODE) }) } return html } function _compileHTML (html, opts, pcex) { if (!/\S/.test(html)) return '' html = splitHtml(html, opts, pcex) .replace(HTML_TAGS, function (_, name, attr, ends) { name = name.toLowerCase() ends = ends && !VOID_TAGS.test(name) ? '></' + name : '' if (attr) name += ' ' + parseAttribs(attr, pcex) return '<' + name + ends + '>' }) if (!opts.whitespace) { var p = [] if (/<pre[\s>]/.test(html)) { html = html.replace(PRE_TAGS, function (q) { p.push(q) return '\u0002' }) } html = html.trim().replace(/\s+/g, ' ') if (p.length) html = html.replace(/\u0002/g, function () { return p.shift() }) } if (opts.compact) html = html.replace(HTML_PACK, '><$1') return restoreExpr(html, pcex).replace(TRIM_TRAIL, '') } function compileHTML (html, opts, pcex) { if (Array.isArray(opts)) { pcex = opts opts = {} } else { if (!pcex) pcex = [] if (!opts) opts = {} } pcex._bp = brackets.array(opts.brackets) return _compileHTML(cleanSource(html), opts, pcex) } var JS_ES6SIGN = /^[ \t]*([$_A-Za-z][$\w]*)\s*\([^()]*\)\s*{/m var JS_ES6END = RegExp('[{}]|' + brackets.S_QBLOCKS, 'g') var JS_COMMS = RegExp(brackets.R_MLCOMMS.source + '|//[^\r\n]*|' + brackets.S_QBLOCKS, 'g') function riotjs (js) { var parts = [], match, toes5, pos, name, RE = RegExp if (~js.indexOf('/')) js = rmComms(js, JS_COMMS) while ((match = js.match(JS_ES6SIGN))) { parts.push(RE.leftContext) js = RE.rightContext pos = skipBody(js, JS_ES6END) name = match[1] toes5 = !/^(?:if|while|for|switch|catch|function)$/.test(name) name = toes5 ? match[0].replace(name, 'this.' + name + ' = function') : match[0] parts.push(name, js.slice(0, pos)) js = js.slice(pos) if (toes5 && !/^\s*.\s*bind\b/.test(js)) parts.push('.bind(this)') } return parts.length ? parts.join('') + js : js function rmComms (s, r, m) { r.lastIndex = 0 while ((m = r.exec(s))) { if (m[0][0] === '/' && !m[1] && !m[2]) { s = RE.leftContext + ' ' + RE.rightContext r.lastIndex = m[3] + 1 } } return s } function skipBody (s, r) { var m, i = 1 r.lastIndex = 0 while (i && (m = r.exec(s))) { if (m[0] === '{') ++i else if (m[0] === '}') --i } return i ? s.length : r.lastIndex } } function _compileJS (js, opts, type, parserOpts, url) { if (!/\S/.test(js)) return '' if (!type) type = opts.type var parser = opts.parser || type && parsers._req('js.' + type, true) || riotjs return parser(js, parserOpts, url).replace(/\r\n?/g, '\n').replace(TRIM_TRAIL, '') } function compileJS (js, opts, type, userOpts) { if (typeof opts === 'string') { userOpts = type type = opts opts = {} } if (type && typeof type === 'object') { userOpts = type type = '' } if (!userOpts) userOpts = {} return _compileJS(js, opts || {}, type, userOpts.parserOptions, userOpts.url) } var CSS_SELECTOR = RegExp('([{}]|^)[ ;]*([^@ ;{}][^{}]*)(?={)|' + S_LINESTR, 'g') function scopedCSS (tag, css) { var scope = ':scope' return css.replace(CSS_SELECTOR, function (m, p1, p2) { if (!p2) return m p2 = p2.replace(/[^,]+/g, function (sel) { var s = sel.trim() if (!s || s === 'from' || s === 'to' || s.slice(-1) === '%') { return sel } if (s.indexOf(scope) < 0) { s = tag + ' ' + s + ',[riot-tag="' + tag + '"] ' + s + ',[data-is="' + tag + '"] ' + s } else { s = s.replace(scope, tag) + ',' + s.replace(scope, '[riot-tag="' + tag + '"]') + ',' + s.replace(scope, '[data-is="' + tag + '"]') } return s }) return p1 ? p1 + ' ' + p2 : p2 }) } function _compileCSS (css, tag, type, opts) { var scoped = (opts || (opts = {})).scoped if (type) { if (type === 'scoped-css') { scoped = true } else if (type !== 'css') { var parser = parsers._req('css.' + type, true) css = parser(tag, css, opts.parserOpts || {}, opts.url) } } css = css.replace(brackets.R_MLCOMMS, '').replace(/\s+/g, ' ').trim() if (scoped) { if (!tag) { throw new Error('Can not parse scoped CSS without a tagName') } css = scopedCSS(tag, css) } return css } function compileCSS (css, type, opts) { if (type && typeof type === 'object') { opts = type type = '' } else if (!opts) opts = {} return _compileCSS(css, opts.tagName, type, opts) } var TYPE_ATTR = /\stype\s*=\s*(?:(['"])(.+?)\1|(\S+))/i var MISC_ATTR = '\\s*=\\s*(' + S_STRINGS + '|{[^}]+}|\\S+)' var END_TAGS = /\/>\n|^<(?:\/?-?[A-Za-z][-\w\xA0-\xFF]*\s*|-?[A-Za-z][-\w\xA0-\xFF]*\s+[-\w:\xA0-\xFF][\S\s]*?)>\n/ function _q (s, r) { if (!s) return "''" s = SQ + s.replace(/\\/g, '\\\\').replace(/'/g, "\\'") + SQ return r && ~s.indexOf('\n') ? s.replace(/\n/g, '\\n') : s } function mktag (name, html, css, attr, js, imports, opts) { var c = opts.debug ? ',\n ' : ', ', s = '});' if (js && js.slice(-1) !== '\n') s = '\n' + s return imports + 'riot.tag2(\'' + name + SQ + c + _q(html, 1) + c + _q(css) + c + _q(attr) + ', function(opts) {\n' + js + s } function splitBlocks (str) { if (/<[-\w]/.test(str)) { var m, k = str.lastIndexOf('<'), n = str.length while (~k) { m = str.slice(k, n).match(END_TAGS) if (m) { k += m.index + m[0].length m = str.slice(0, k) if (m.slice(-5) === '<-/>\n') m = m.slice(0, -5) return [m, str.slice(k)] } n = k k = str.lastIndexOf('<', k - 1) } } return ['', str] } function getType (attribs) { if (attribs) { var match = attribs.match(TYPE_ATTR) match = match && (match[2] || match[3]) if (match) { return match.replace('text/', '') } } return '' } function getAttrib (attribs, name) { if (attribs) { var match = attribs.match(RegExp('\\s' + name + MISC_ATTR, 'i')) match = match && match[1] if (match) { return (/^['"]/).test(match) ? match.slice(1, -1) : match } } return '' } function unescapeHTML (str) { return str .replace(/&amp;/g, '&') .replace(/&lt;/g, '<') .replace(/&gt;/g, '>') .replace(/&quot;/g, '"') .replace(/&#039;/g, '\'') } function getParserOptions (attribs) { var opts = unescapeHTML(getAttrib(attribs, 'options')) return opts ? JSON.parse(opts) : null } function getCode (code, opts, attribs, base) { var type = getType(attribs), src = getAttrib(attribs, 'src'), jsParserOptions = extend({}, opts.parserOptions.js) if (src) return false return _compileJS( code, opts, type, extend(jsParserOptions, getParserOptions(attribs)), base ) } function cssCode (code, opts, attribs, url, tag) { var parserStyleOptions = extend({}, opts.parserOptions.style), extraOpts = { parserOpts: extend(parserStyleOptions, getParserOptions(attribs)), scoped: attribs && /\sscoped(\s|=|$)/i.test(attribs), url: url } return _compileCSS(code, tag, getType(attribs) || opts.style, extraOpts) } function compileTemplate (html, url, lang, opts) { var parser = parsers._req('html.' + lang, true) return parser(html, opts, url) } var CUST_TAG = RegExp(/^([ \t]*)<(-?[A-Za-z][-\w\xA0-\xFF]*)(?:\s+([^'"\/>]+(?:(?:@|\/[^>])[^'"\/>]*)*)|\s*)?(?:\/>|>[ \t]*\n?([\S\s]*)^\1<\/\2\s*>|>(.*)<\/\2\s*>)/ .source.replace('@', S_STRINGS), 'gim'), SCRIPTS = /<script(\s+[^>]*)?>\n?([\S\s]*?)<\/script\s*>/gi, STYLES = /<style(\s+[^>]*)?>\n?([\S\s]*?)<\/style\s*>/gi function compile (src, opts, url) { var parts = [], included, defaultParserptions = { template: {}, js: {}, style: {} } if (!opts) opts = {} opts.parserOptions = extend(defaultParserptions, opts.parserOptions || {}) included = opts.exclude ? function (s) { return opts.exclude.indexOf(s) < 0 } : function () { return 1 } if (!url) url = '' var _bp = brackets.array(opts.brackets) if (opts.template) { src = compileTemplate(src, url, opts.template, opts.parserOptions.template) } src = cleanSource(src) .replace(CUST_TAG, function (_, indent, tagName, attribs, body, body2) { var jscode = '', styles = '', html = '', imports = '', pcex = [] pcex._bp = _bp tagName = tagName.toLowerCase() attribs = attribs && included('attribs') ? restoreExpr( parseAttribs( splitHtml(attribs, opts, pcex), pcex), pcex) : '' if ((body || (body = body2)) && /\S/.test(body)) { if (body2) { if (included('html')) html = _compileHTML(body2, opts, pcex) } else { body = body.replace(RegExp('^' + indent, 'gm'), '') body = body.replace(STYLES, function (_m, _attrs, _style) { if (included('css')) { styles += (styles ? ' ' : '') + cssCode(_style, opts, _attrs, url, tagName) } return '' }) body = body.replace(SCRIPTS, function (_m, _attrs, _script) { if (included('js')) { var code = getCode(_script, opts, _attrs, url) if (code) jscode += (jscode ? '\n' : '') + code } return '' }) var blocks = splitBlocks(body.replace(TRIM_TRAIL, '')) if (included('html')) { html = _compileHTML(blocks[0], opts, pcex) } if (included('js')) { body = _compileJS(blocks[1], opts, null, null, url) if (body) jscode += (jscode ? '\n' : '') + body jscode = jscode.replace(IMPORT_STATEMENT, function (s) { imports += s.trim() + '\n' return '' }) } } } jscode = /\S/.test(jscode) ? jscode.replace(/\n{3,}/g, '\n\n') : '' if (opts.entities) { parts.push({ tagName: tagName, html: html, css: styles, attribs: attribs, js: jscode, imports: imports }) return '' } return mktag(tagName, html, styles, attribs, jscode, imports, opts) }) if (opts.entities) return parts return src } riot.util.compiler = { compile: compile, html: compileHTML, css: compileCSS, js: compileJS, version: 'v2.5.5' } return compile })() /* Compilation for the browser */ riot.compile = (function () { var promise, // emits the 'ready' event and runs the first callback ready // all the scripts were compiled? // gets the source of an external tag with an async call function GET (url, fn, opts) { var req = new XMLHttpRequest() req.onreadystatechange = function () { if (req.readyState === 4 && (req.status === 200 || !req.status && req.responseText.length)) { fn(req.responseText, opts, url) } } req.open('GET', url, true) req.send('') } // evaluates a compiled tag within the global context function globalEval (js, url) { if (typeof js === T_STRING) { var node = mkEl('script'), root = document.documentElement // make the source available in the "(no domain)" tab // of Chrome DevTools, with a .js extension if (url) js += '\n//# sourceURL=' + url + '.js' node.text = js root.appendChild(node) root.removeChild(node) } } // compiles all the internal and external tags on the page function compileScripts (fn, xopt) { var scripts = $$('script[type="riot/tag"]'), scriptsAmount = scripts.length function done() { promise.trigger('ready') ready = true if (fn) fn() } function compileTag (src, opts, url) { var code = compile(src, opts, url) globalEval(code, url) if (!--scriptsAmount) done() } if (!scriptsAmount) done() else { for (var i = 0; i < scripts.length; ++i) { var script = scripts[i], opts = extend({template: getAttr(script, 'template')}, xopt), url = getAttr(script, 'src') url ? GET(url, compileTag, opts) : compileTag(script.innerHTML, opts) } } } //// Entry point ----- return function (arg, fn, opts) { if (typeof arg === T_STRING) { // 2nd parameter is optional, but can be null if (isObject(fn)) { opts = fn fn = false } // `riot.compile(tag [, callback | true][, options])` if (/^\s*</m.test(arg)) { var js = compile(arg, opts) if (fn !== true) globalEval(js) if (isFunction(fn)) fn(js, arg, opts) return js } // `riot.compile(url [, callback][, options])` GET(arg, function (str, opts, url) { var js = compile(str, opts, url) globalEval(js, url) if (fn) fn(js, str, opts) }, opts) } else { // `riot.compile([callback][, options])` if (isFunction(arg)) { opts = fn fn = arg } else { opts = arg fn = undefined } if (ready) { return fn && fn() } if (promise) { if (fn) promise.on('ready', fn) } else { promise = riot.observable() compileScripts(fn, opts) } } } })() // reassign mount methods ----- var mount = riot.mount riot.mount = function (a, b, c) { var ret riot.compile(function () { ret = mount(a, b, c) }) return ret } // support CommonJS, AMD & browser /* istanbul ignore next */ if (typeof exports === T_OBJECT) module.exports = riot else if (typeof define === T_FUNCTION && typeof define.amd !== T_UNDEF) define(function() { return riot }) else window.riot = riot })(typeof window != 'undefined' ? window : void 0);
lib/atom/commands.js
atom/github
import React from 'react'; import PropTypes from 'prop-types'; import {Disposable} from 'event-kit'; import {DOMNodePropType, RefHolderPropType} from '../prop-types'; import RefHolder from '../models/ref-holder'; export default class Commands extends React.Component { static propTypes = { registry: PropTypes.object.isRequired, target: PropTypes.oneOfType([ PropTypes.string, DOMNodePropType, RefHolderPropType, ]).isRequired, children: PropTypes.oneOfType([ PropTypes.element, PropTypes.arrayOf(PropTypes.element), ]).isRequired, } render() { const {registry, target} = this.props; return ( <div> {React.Children.map(this.props.children, child => { return child ? React.cloneElement(child, {registry, target}) : null; })} </div> ); } } export class Command extends React.Component { static propTypes = { registry: PropTypes.object, target: PropTypes.oneOfType([ PropTypes.string, DOMNodePropType, RefHolderPropType, ]), command: PropTypes.string.isRequired, callback: PropTypes.func.isRequired, } constructor(props, context) { super(props, context); this.subTarget = new Disposable(); this.subCommand = new Disposable(); } componentDidMount() { this.observeTarget(this.props); } componentWillReceiveProps(newProps) { if (['registry', 'target', 'command', 'callback'].some(p => newProps[p] !== this.props[p])) { this.observeTarget(newProps); } } componentWillUnmount() { this.subTarget.dispose(); this.subCommand.dispose(); } observeTarget(props) { this.subTarget.dispose(); this.subTarget = RefHolder.on(props.target).observe(t => this.registerCommand(t, props)); } registerCommand(target, {registry, command, callback}) { this.subCommand.dispose(); this.subCommand = registry.add(target, command, callback); } render() { return null; } }
javascript/components/static-input.js
kdoran/moriana-react
import React from 'react' export default class StaticInput extends React.Component { render () { const { label, value, onEditClick, className } = this.props let classes = className ? `${className} row` : 'row' return ( <div className={classes}> <label>{label}</label> <div className='input-group'> <span>{value}</span> {(onEditClick && <span>&nbsp;(<a onClick={onEditClick}>edit</a>)</span>)} </div> </div> ) } }
src/Tooltip.js
azmenak/react-bootstrap
import React from 'react'; import classNames from 'classnames'; import BootstrapMixin from './BootstrapMixin'; import CustomPropTypes from './utils/CustomPropTypes'; const Tooltip = React.createClass({ mixins: [BootstrapMixin], propTypes: { /** * An html id attribute, necessary for accessibility * @type {string} * @required */ id: CustomPropTypes.isRequiredForA11y(React.PropTypes.string), /** * Sets the direction the Tooltip is positioned towards. */ placement: React.PropTypes.oneOf(['top', 'right', 'bottom', 'left']), /** * The "left" position value for the Tooltip. */ positionLeft: React.PropTypes.number, /** * The "top" position value for the Tooltip. */ positionTop: React.PropTypes.number, /** * The "left" position value for the Tooltip arrow. */ arrowOffsetLeft: React.PropTypes.oneOfType([ React.PropTypes.number, React.PropTypes.string ]), /** * The "top" position value for the Tooltip arrow. */ arrowOffsetTop: React.PropTypes.oneOfType([ React.PropTypes.number, React.PropTypes.string ]), /** * Title text */ title: React.PropTypes.node }, getDefaultProps() { return { placement: 'right' }; }, render() { const classes = { 'tooltip': true, [this.props.placement]: true }; const style = { 'left': this.props.positionLeft, 'top': this.props.positionTop, // we don't want to expose the `style` property ...this.props.style // eslint-disable-line react/prop-types }; const arrowStyle = { 'left': this.props.arrowOffsetLeft, 'top': this.props.arrowOffsetTop }; return ( <div role='tooltip' {...this.props} className={classNames(this.props.className, classes)} style={style}> <div className="tooltip-arrow" style={arrowStyle} /> <div className="tooltip-inner"> {this.props.children} </div> </div> ); } }); export default Tooltip;
ajax/libs/material-ui/5.0.0-beta.5/Breadcrumbs/Breadcrumbs.min.js
cdnjs/cdnjs
import _extends from"@babel/runtime/helpers/esm/extends";import _objectWithoutPropertiesLoose from"@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";const _excluded=["children","className","component","expandText","itemsAfterCollapse","itemsBeforeCollapse","maxItems","separator"];import*as React from"react";import{isFragment}from"react-is";import PropTypes from"prop-types";import clsx from"clsx";import{integerPropType}from"@material-ui/utils";import{unstable_composeClasses as composeClasses}from"@material-ui/unstyled";import styled from"../styles/styled";import useThemeProps from"../styles/useThemeProps";import Typography from"../Typography";import BreadcrumbCollapsed from"./BreadcrumbCollapsed";import breadcrumbsClasses,{getBreadcrumbsUtilityClass}from"./breadcrumbsClasses";import{jsx as _jsx}from"react/jsx-runtime";const useUtilityClasses=e=>{var e=e["classes"];return composeClasses({root:["root"],li:["li"],ol:["ol"],separator:["separator"]},getBreadcrumbsUtilityClass,e)},BreadcrumbsRoot=styled(Typography,{name:"MuiBreadcrumbs",slot:"Root",overridesResolver:(e,r)=>[{[`& .${breadcrumbsClasses.li}`]:r.li},r.root]})({}),BreadcrumbsOl=styled("ol",{name:"MuiBreadcrumbs",slot:"Ol",overridesResolver:(e,r)=>r.ol})({display:"flex",flexWrap:"wrap",alignItems:"center",padding:0,margin:0,listStyle:"none"}),BreadcrumbsSeparator=styled("li",{name:"MuiBreadcrumbs",slot:"Separator",overridesResolver:(e,r)=>r.separator})({display:"flex",userSelect:"none",marginLeft:8,marginRight:8});function insertSeparators(o,t,a,l){return o.reduce((e,r,s)=>(s<o.length-1?e=e.concat(r,_jsx(BreadcrumbsSeparator,{"aria-hidden":!0,className:t,ownerState:l,children:a},`separator-${s}`)):e.push(r),e),[])}const Breadcrumbs=React.forwardRef(function(e,r){e=useThemeProps({props:e,name:"MuiBreadcrumbs"});const{children:s,className:o,component:t="nav",expandText:a="Show path",itemsAfterCollapse:l=1,itemsBeforeCollapse:p=1,maxItems:i=8,separator:n="/"}=e,m=_objectWithoutPropertiesLoose(e,_excluded),[c,d]=React.useState(!1);e=_extends({},e,{component:t,expanded:c,expandText:a,itemsAfterCollapse:l,itemsBeforeCollapse:p,maxItems:i,separator:n});const u=useUtilityClasses(e),b=React.useRef(null);var f,y=React.Children.toArray(s).filter(e=>("production"!==process.env.NODE_ENV&&isFragment(e)&&console.error(["Material-UI: The Breadcrumbs component doesn't accept a Fragment as a child.","Consider providing an array instead."].join("\n")),React.isValidElement(e))).map((e,r)=>_jsx("li",{className:u.li,children:e},`child-${r}`));return _jsx(BreadcrumbsRoot,_extends({ref:r,component:t,color:"text.secondary",className:clsx(u.root,o),ownerState:e},m,{children:_jsx(BreadcrumbsOl,{className:u.ol,ref:b,ownerState:e,children:insertSeparators(c||i&&y.length<=i?y:p+l>=(f=y).length?("production"!==process.env.NODE_ENV&&console.error(["Material-UI: You have provided an invalid combination of props to the Breadcrumbs.",`itemsAfterCollapse={${l}} + itemsBeforeCollapse={${p}} >= maxItems={${i}}`].join("\n")),f):[...f.slice(0,p),_jsx(BreadcrumbCollapsed,{"aria-label":a,onClick:()=>{d(!0);const e=b.current.querySelector("a[href],button,[tabindex]");e&&e.focus()}},"ellipsis"),...f.slice(f.length-l,f.length)],u.separator,n,e)})}))});"production"!==process.env.NODE_ENV&&(Breadcrumbs.propTypes={children:PropTypes.node,classes:PropTypes.object,className:PropTypes.string,component:PropTypes.elementType,expandText:PropTypes.string,itemsAfterCollapse:integerPropType,itemsBeforeCollapse:integerPropType,maxItems:integerPropType,separator:PropTypes.node,sx:PropTypes.object});export default Breadcrumbs;
config/componentData.js
arnarleifs/ps-react-arnar
module.exports = [{"name":"EyeIcon","description":"SVG Eye Icon","code":"import React from 'react';\r\n\r\n/** SVG Eye Icon */\r\nfunction EyeIcon() {\r\n // Attribution: Fabián Alexis at https://commons.wikimedia.org/wiki/File:Antu_view-preview.svg\r\n return (\r\n <svg width=\"16\" height=\"16\" xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 22 22\">\r\n <g transform=\"matrix(.02146 0 0 .02146 1 1)\" fill=\"#4d4d4d\">\r\n <path d=\"m466.07 161.53c-205.6 0-382.8 121.2-464.2 296.1-2.5 5.3-2.5 11.5 0 16.9 81.4 174.9 258.6 296.1 464.2 296.1 205.6 0 382.8-121.2 464.2-296.1 2.5-5.3 2.5-11.5 0-16.9-81.4-174.9-258.6-296.1-464.2-296.1m0 514.7c-116.1 0-210.1-94.1-210.1-210.1 0-116.1 94.1-210.1 210.1-210.1 116.1 0 210.1 94.1 210.1 210.1 0 116-94.1 210.1-210.1 210.1\" />\r\n <circle cx=\"466.08\" cy=\"466.02\" r=\"134.5\" />\r\n </g>\r\n </svg>\r\n )\r\n}\r\n\r\nexport default EyeIcon;\r\n","examples":[{"name":"Example","description":"","code":"import React from 'react';\r\nimport EyeIcon from 'ps-react/EyeIcon';\r\n\r\nexport default function EyeIconExample() {\r\n return <EyeIcon />;\r\n};"}]},{"name":"HelloWorld","description":"A Hello World component","props":{"message":{"type":{"name":"string"},"required":true,"description":"Message to display","defaultValue":{"value":"'World'","computed":false}}},"code":"import React from 'react';\r\nimport PropTypes from 'prop-types';\r\n\r\n/** A Hello World component */\r\nconst HelloWorld = ({ message }) => {\r\n return <div>Hello {message}</div>;\r\n};\r\n\r\nHelloWorld.propTypes = {\r\n /** Message to display */\r\n message: PropTypes.string.isRequired\r\n};\r\n\r\nHelloWorld.defaultProps = {\r\n message: 'World'\r\n};\r\n\r\nexport default HelloWorld;","examples":[{"name":"ExampleHelloWorld","description":"Custom message","code":"import React from 'react';\r\nimport HelloWorld from 'ps-react/HelloWorld';\r\n\r\n/** Custom message */\r\nexport default function ExampleHelloWorld() {\r\n return <HelloWorld message=\"UTS!\" />;\r\n}\r\n"}]},{"name":"Label","description":"","props":{"htmlFor":{"type":{"name":"string"},"required":true,"description":"HTML ID for associated input element"},"label":{"type":{"name":"string"},"required":true,"description":"Label text"},"required":{"type":{"name":"bool"},"required":false,"description":"Display asterisk after label if true"}},"code":"import React from 'react';\r\nimport PropTypes from 'prop-types';\r\n\r\nfunction Label({ htmlFor, label, required }) {\r\n return (\r\n <label style={{ display: 'block' }} htmlFor={htmlFor}>\r\n {label} { required && <span style={{ color: 'red' }}> *</span> }\r\n </label>\r\n );\r\n};\r\n\r\nLabel.propTypes = {\r\n /** HTML ID for associated input element */\r\n htmlFor: PropTypes.string.isRequired,\r\n\r\n /** Label text */\r\n label: PropTypes.string.isRequired,\r\n\r\n /** Display asterisk after label if true */\r\n required: PropTypes.bool\r\n};\r\n\r\nexport default Label;","examples":[{"name":"ExampleOptional","description":"Optional label","code":"import React from 'react';\r\nimport Label from 'ps-react/Label';\r\n\r\n/** Optional label */\r\nexport default function ExampleOptional() {\r\n return <Label htmlFor='test' label='test' />\r\n};"},{"name":"ExampleRequired","description":"Optional label","code":"import React from 'react';\r\nimport Label from 'ps-react/Label';\r\n\r\n/** Optional label */\r\nexport default function ExampleRequired() {\r\n return <Label htmlFor='test' label='test' required />\r\n};"}]},{"name":"PasswordInput","description":"Password input with integrated label, quality tips, and show password toggle.","props":{"htmlId":{"type":{"name":"string"},"required":true,"description":"Unique HTML ID. Used for tying label to HTML input. Handy hook for automated testing."},"name":{"type":{"name":"string"},"required":true,"description":"Input name. Recommend setting this to match object's property so a single change handler can be used by convention."},"value":{"type":{"name":"any"},"required":false,"description":"Password value"},"label":{"type":{"name":"string"},"required":false,"description":"Input label","defaultValue":{"value":"'Password'","computed":false}},"onChange":{"type":{"name":"func"},"required":true,"description":"Function called when password input value changes"},"maxLength":{"type":{"name":"number"},"required":false,"description":"Max password length accepted","defaultValue":{"value":"50","computed":false}},"placeholder":{"type":{"name":"string"},"required":false,"description":"Placeholder displayed when no password is entered"},"showVisibilityToggle":{"type":{"name":"bool"},"required":false,"description":"Set to true to show the toggle for displaying the currently entered password","defaultValue":{"value":"false","computed":false}},"quality":{"type":{"name":"number"},"required":false,"description":"Display password quality visually via ProgressBar, accepts a number between 0 and 100"},"error":{"type":{"name":"string"},"required":false,"description":"Validation error to display"}},"code":"import React from 'react';\r\nimport PropTypes from 'prop-types';\r\nimport ProgressBar from '../ProgressBar';\r\nimport EyeIcon from '../EyeIcon';\r\nimport TextInput from '../TextInput';\r\n\r\n/** Password input with integrated label, quality tips, and show password toggle. */\r\nclass PasswordInput extends React.Component {\r\n constructor(props) {\r\n super(props);\r\n this.state = {\r\n showPassword: false\r\n }\r\n }\r\n\r\n toggleShowPassword = event => {\r\n this.setState(prevState => {\r\n return { showPassword: !prevState.showPassword };\r\n });\r\n if (event) event.preventDefault();\r\n }\r\n\r\n render() {\r\n const { htmlId, value, label, error, onChange, placeholder, maxLength, showVisibilityToggle, quality, ...props } = this.props;\r\n const { showPassword } = this.state;\r\n\r\n return (\r\n <TextInput\r\n htmlId={htmlId}\r\n label={label}\r\n placeholder={placeholder}\r\n type={showPassword ? 'text' : 'password'}\r\n onChange={onChange}\r\n value={value}\r\n maxLength={maxLength}\r\n error={error}\r\n required\r\n {...props}>\r\n {\r\n showVisibilityToggle &&\r\n <a\r\n href=\"#\"\r\n onClick={this.toggleShowPassword}\r\n style={{ marginLeft: 5 }}>\r\n <EyeIcon />\r\n </a>\r\n }\r\n {\r\n value.length > 0 && quality && <ProgressBar percent={quality} width={130} />\r\n }\r\n </TextInput>\r\n );\r\n }\r\n}\r\n\r\nPasswordInput.propTypes = {\r\n /** Unique HTML ID. Used for tying label to HTML input. Handy hook for automated testing. */\r\n htmlId: PropTypes.string.isRequired,\r\n\r\n /** Input name. Recommend setting this to match object's property so a single change handler can be used by convention.*/\r\n name: PropTypes.string.isRequired,\r\n\r\n /** Password value */\r\n value: PropTypes.any,\r\n\r\n /** Input label */\r\n label: PropTypes.string,\r\n\r\n /** Function called when password input value changes */\r\n onChange: PropTypes.func.isRequired,\r\n\r\n /** Max password length accepted */\r\n maxLength: PropTypes.number,\r\n\r\n /** Placeholder displayed when no password is entered */\r\n placeholder: PropTypes.string,\r\n\r\n /** Set to true to show the toggle for displaying the currently entered password */\r\n showVisibilityToggle: PropTypes.bool,\r\n\r\n /** Display password quality visually via ProgressBar, accepts a number between 0 and 100 */\r\n quality: PropTypes.number,\r\n\r\n /** Validation error to display */\r\n error: PropTypes.string\r\n};\r\n\r\nPasswordInput.defaultProps = {\r\n maxLength: 50,\r\n showVisibilityToggle: false,\r\n label: 'Password'\r\n};\r\n\r\nexport default PasswordInput;\r\n","examples":[{"name":"ExampleAllFeatures","description":"All features enabled","code":"import React from 'react';\r\nimport PasswordInput from 'ps-react/PasswordInput';\r\n\r\n/** All features enabled */\r\nclass ExampleAllFeatures extends React.Component {\r\n constructor(props) {\r\n super(props);\r\n\r\n this.state = {\r\n password: ''\r\n };\r\n }\r\n\r\n getQuality() {\r\n const length = this.state.password.length;\r\n return length > 10 ? 100 : length * 10;\r\n }\r\n\r\n render() {\r\n return (\r\n <div>\r\n <PasswordInput\r\n htmlId=\"password-input-example-all-features\"\r\n name=\"password\"\r\n onChange={ event => this.setState({ password: event.target.value })}\r\n value={this.state.password}\r\n minLength={8}\r\n placeholder=\"Enter password\"\r\n showVisibilityToggle\r\n quality={this.getQuality()}\r\n {...this.props} />\r\n </div>\r\n )\r\n }\r\n}\r\n\r\nexport default ExampleAllFeatures;\r\n"}]},{"name":"ProgressBar","description":"","props":{"percent":{"type":{"name":"number"},"required":true,"description":"Percent of progress completed"},"width":{"type":{"name":"number"},"required":true,"description":"The width of the progress bar"},"height":{"type":{"name":"number"},"required":true,"description":"The height of the progress bar","defaultValue":{"value":"5","computed":false}}},"code":"import React from 'react';\r\nimport PropTypes from 'prop-types';\r\n\r\nclass ProgressBar extends React.Component {\r\n getColor = (percent) => {\r\n if (this.props.percent === 100) return 'green';\r\n return this.props.percent > 50 ? 'lightgreen' : 'red';\r\n }\r\n\r\n getWidthAsPercentOfTotalWidth = () => {\r\n return parseInt(this.props.width * (this.props.percent / 100), 10);\r\n }\r\n\r\n render() {\r\n const { percent, width, height } = this.props;\r\n return (\r\n <div style={{ border: 'solid 1px lightgray', width: width }}>\r\n <div style={{ \r\n width: this.getWidthAsPercentOfTotalWidth(),\r\n height,\r\n backgroundColor: this.getColor(percent) \r\n }} />\r\n </div>\r\n );\r\n }\r\n};\r\n\r\nProgressBar.propTypes = {\r\n /** Percent of progress completed */\r\n percent: PropTypes.number.isRequired,\r\n /** The width of the progress bar */\r\n width: PropTypes.number.isRequired,\r\n /** The height of the progress bar */\r\n height: PropTypes.number.isRequired\r\n};\r\n\r\nProgressBar.defaultProps = {\r\n height: 5\r\n};\r\n\r\nexport default ProgressBar;","examples":[{"name":"Example100Percent","description":"100% progress","code":"import React from 'react';\r\nimport ProgressBar from 'ps-react/ProgressBar';\r\n\r\n/** 100% progress */\r\nexport default function Example100Percent() {\r\n return <ProgressBar percent={100} width={150} height={20} />\r\n};"},{"name":"Example10Percent","description":"10% progress","code":"import React from 'react';\r\nimport ProgressBar from 'ps-react/ProgressBar';\r\n\r\n/** 10% progress */\r\nexport default function Example10Percent() {\r\n return <ProgressBar percent={10} width={150} />\r\n};"},{"name":"Example70Percent","description":"70% progress","code":"import React from 'react';\r\nimport ProgressBar from 'ps-react/ProgressBar';\r\n\r\n/** 70% progress */\r\nexport default function Example70Percent() {\r\n return <ProgressBar percent={70} width={150} />\r\n};"}]},{"name":"RegistrationForm","description":"Registration form with built-in validation.","props":{"confirmationMessage":{"type":{"name":"string"},"required":false,"description":"Message displayed upon successful submission","defaultValue":{"value":"\"Thanks for registering!\"","computed":false}},"onSubmit":{"type":{"name":"func"},"required":true,"description":"Called when form is submitted"},"minPasswordLength":{"type":{"name":"number"},"required":false,"description":"Minimum password length","defaultValue":{"value":"8","computed":false}}},"code":"import React from 'react';\r\nimport PropTypes from 'prop-types';\r\nimport TextInput from '../TextInput';\r\nimport PasswordInput from '../PasswordInput';\r\n\r\n/** Registration form with built-in validation. */\r\nclass RegistrationForm extends React.Component {\r\n constructor(props) {\r\n super(props);\r\n\r\n this.state = {\r\n user: {\r\n email: '',\r\n password: ''\r\n },\r\n errors: {},\r\n submitted: false,\r\n };\r\n }\r\n\r\n onChange = (event) => {\r\n const user = this.state.user;\r\n user[event.target.name] = event.target.value;\r\n this.setState({user});\r\n }\r\n\r\n // Returns a number from 0 to 100 that represents password quality.\r\n // For simplicity, just returning % of min length entered.\r\n // Could enhance with checks for number, special char, unique characters, etc.\r\n passwordQuality(password) {\r\n if (!password) return null;\r\n if (password.length >= this.props.minPasswordLength) return 100;\r\n const percentOfMinLength = parseInt(password.length/this.props.minPasswordLength * 100, 10);\r\n return percentOfMinLength;\r\n }\r\n\r\n validate({email, password}) {\r\n const errors = {};\r\n const {minPasswordLength} = this.props;\r\n\r\n if (!email) errors.email = 'Email required.';\r\n if (password.length < minPasswordLength) errors.password = `Password must be at least ${minPasswordLength} characters.`;\r\n\r\n this.setState({errors});\r\n const formIsValid = Object.getOwnPropertyNames(errors).length === 0;\r\n return formIsValid;\r\n }\r\n\r\n onSubmit = () => {\r\n const {user} = this.state;\r\n const formIsValid = this.validate(user);\r\n if (formIsValid) {\r\n this.props.onSubmit(user);\r\n this.setState({submitted: true});\r\n }\r\n }\r\n\r\n render() {\r\n const {errors, submitted} = this.state;\r\n const {email, password} = this.state.user;\r\n\r\n return (\r\n submitted ?\r\n <h2>{this.props.confirmationMessage}</h2> :\r\n <div>\r\n <TextInput\r\n htmlId=\"registration-form-email\"\r\n name=\"email\"\r\n onChange={this.onChange}\r\n label=\"Email\"\r\n value={email}\r\n error={errors.email}\r\n required />\r\n\r\n <PasswordInput\r\n htmlId=\"registration-form-password\"\r\n name=\"password\"\r\n value={password}\r\n onChange={this.onChange}\r\n quality={this.passwordQuality(password)}\r\n showVisibilityToggle\r\n maxLength={50}\r\n error={errors.password} />\r\n\r\n <input type=\"submit\" value=\"Register\" onClick={this.onSubmit} />\r\n </div>\r\n )\r\n }\r\n}\r\n\r\nRegistrationForm.propTypes = {\r\n /** Message displayed upon successful submission */\r\n confirmationMessage: PropTypes.string,\r\n\r\n /** Called when form is submitted */\r\n onSubmit: PropTypes.func.isRequired,\r\n\r\n /** Minimum password length */\r\n minPasswordLength: PropTypes.number\r\n}\r\n\r\nRegistrationForm.defaultProps = {\r\n confirmationMessage: \"Thanks for registering!\",\r\n minPasswordLength: 8\r\n};\r\n\r\nexport default RegistrationForm;\r\n","examples":[{"name":"ExampleRegistrationForm","description":"","code":"import React from 'react';\r\nimport RegistrationForm from 'ps-react/RegistrationForm';\r\n\r\nexport default class ExampleRegistrationForm extends React.Component {\r\n onSubmit = (user) => {\r\n console.log(user);\r\n }\r\n\r\n render() {\r\n return <RegistrationForm onSubmit={this.onSubmit} />\r\n }\r\n}\r\n"}]},{"name":"TextInput","description":"Text input with integrated label to enforce consistency in layout, error display, label placement","props":{"htmlId":{"type":{"name":"string"},"required":true,"description":"Unique HTML ID. Used for tying label to HTML input. Handy hook for automated testing."},"name":{"type":{"name":"string"},"required":true,"description":"Input name. Recommend setting this to match object's property so a single change handler"},"label":{"type":{"name":"string"},"required":true,"description":"Input label"},"type":{"type":{"name":"enum","value":[{"value":"'text'","computed":false},{"value":"'number'","computed":false},{"value":"'password'","computed":false}]},"required":false,"description":"Input type","defaultValue":{"value":"'text'","computed":false}},"required":{"type":{"name":"bool"},"required":false,"description":"Mark label with asterisk if set to true","defaultValue":{"value":"false","computed":false}},"onChange":{"type":{"name":"func"},"required":true,"description":"Function to call onChange"},"placeholder":{"type":{"name":"string"},"required":false,"description":"Placeholder to display when empty"},"error":{"type":{"name":"string"},"required":false,"description":"String to display when error occurs"},"children":{"type":{"name":"node"},"required":false,"description":"Child component to display next to the input"}},"code":"import React from 'react';\r\nimport PropTypes from 'prop-types';\r\nimport Label from '../Label';\r\n\r\n/** Text input with integrated label to enforce consistency in layout, error display, label placement */\r\nfunction TextInput({ htmlId, name, label, type = 'text', required = false, onChange, placeholder, value, error, children, ...props }) {\r\n return (\r\n <div style={{ marginBottom: 16 }}>\r\n <Label htmlFor={htmlId} label={label} required={required} />\r\n <input\r\n id={htmlId}\r\n type={type}\r\n name={name}\r\n placeholder={placeholder}\r\n value={value}\r\n onChange={onChange}\r\n style={error && { border: 'solid 1px red' }}\r\n {...props} />\r\n {children}\r\n { error && <div className='error' style={{ color: 'red' }}>{error}</div> }\r\n </div>\r\n );\r\n};\r\n\r\nTextInput.propTypes = {\r\n /** Unique HTML ID. Used for tying label to HTML input. Handy hook for automated testing. */\r\n htmlId: PropTypes.string.isRequired,\r\n\r\n /** Input name. Recommend setting this to match object's property so a single change handler */\r\n name: PropTypes.string.isRequired,\r\n\r\n /** Input label */\r\n label: PropTypes.string.isRequired,\r\n\r\n /** Input type */\r\n type: PropTypes.oneOf(['text', 'number', 'password']),\r\n\r\n /** Mark label with asterisk if set to true */\r\n required: PropTypes.bool,\r\n\r\n /** Function to call onChange */\r\n onChange: PropTypes.func.isRequired,\r\n\r\n /** Placeholder to display when empty */\r\n placeholder: PropTypes.string,\r\n\r\n /** String to display when error occurs */\r\n error: PropTypes.string,\r\n\r\n /** Child component to display next to the input */\r\n children: PropTypes.node\r\n};\r\n\r\nexport default TextInput;","examples":[{"name":"ExampleError","description":"Required TextBox with error","code":"import React from 'react';\r\nimport TextInput from 'ps-react/TextInput';\r\n\r\n/** Required TextBox with error */\r\nexport default class ExampleOptional extends React.Component {\r\n render() {\r\n return (\r\n <TextInput\r\n htmlId='example-optional'\r\n label='First Name'\r\n name='firstname'\r\n required={true}\r\n error='First name is required.'\r\n onChange={() => {}} />\r\n );\r\n }\r\n};"},{"name":"ExampleOptional","description":"Optional TextBox","code":"import React from 'react';\r\nimport TextInput from 'ps-react/TextInput';\r\n\r\n/** Optional TextBox */\r\nexport default class ExampleOptional extends React.Component {\r\n render() {\r\n return (\r\n <TextInput\r\n htmlId='example-optional'\r\n label='First Name'\r\n name='firstname'\r\n onChange={() => {}} />\r\n );\r\n }\r\n};"}]},{"name":"TextInputBEM","description":"Text input with integrated label to enforce consistency in layout, error display, label placement","props":{"htmlId":{"type":{"name":"string"},"required":true,"description":"Unique HTML ID. Used for tying label to HTML input. Handy hook for automated testing."},"name":{"type":{"name":"string"},"required":true,"description":"Input name. Recommend setting this to match object's property so a single change handler"},"label":{"type":{"name":"string"},"required":true,"description":"Input label"},"type":{"type":{"name":"enum","value":[{"value":"'text'","computed":false},{"value":"'number'","computed":false},{"value":"'password'","computed":false}]},"required":false,"description":"Input type","defaultValue":{"value":"'text'","computed":false}},"required":{"type":{"name":"bool"},"required":false,"description":"Mark label with asterisk if set to true","defaultValue":{"value":"false","computed":false}},"onChange":{"type":{"name":"func"},"required":true,"description":"Function to call onChange"},"placeholder":{"type":{"name":"string"},"required":false,"description":"Placeholder to display when empty"},"error":{"type":{"name":"string"},"required":false,"description":"String to display when error occurs"},"children":{"type":{"name":"node"},"required":false,"description":"Child component to display next to the input"}},"code":"import React from 'react';\r\nimport PropTypes from 'prop-types';\r\nimport Label from '../Label';\r\n\r\n/** Text input with integrated label to enforce consistency in layout, error display, label placement */\r\nfunction TextInputBEM({ htmlId, name, label, type = 'text', required = false, onChange, placeholder, value, error, children, ...props }) {\r\n return (\r\n <div className=\"textinput\">\r\n <Label htmlFor={htmlId} label={label} required={required} />\r\n <input\r\n id={htmlId}\r\n type={type}\r\n name={name}\r\n placeholder={placeholder}\r\n value={value}\r\n onChange={onChange}\r\n className={error && 'textinput__input--state-error'}\r\n {...props} />\r\n {children}\r\n { error && <div className='textinput__error'>{error}</div> }\r\n </div>\r\n );\r\n};\r\n\r\nTextInputBEM.propTypes = {\r\n /** Unique HTML ID. Used for tying label to HTML input. Handy hook for automated testing. */\r\n htmlId: PropTypes.string.isRequired,\r\n\r\n /** Input name. Recommend setting this to match object's property so a single change handler */\r\n name: PropTypes.string.isRequired,\r\n\r\n /** Input label */\r\n label: PropTypes.string.isRequired,\r\n\r\n /** Input type */\r\n type: PropTypes.oneOf(['text', 'number', 'password']),\r\n\r\n /** Mark label with asterisk if set to true */\r\n required: PropTypes.bool,\r\n\r\n /** Function to call onChange */\r\n onChange: PropTypes.func.isRequired,\r\n\r\n /** Placeholder to display when empty */\r\n placeholder: PropTypes.string,\r\n\r\n /** String to display when error occurs */\r\n error: PropTypes.string,\r\n\r\n /** Child component to display next to the input */\r\n children: PropTypes.node\r\n};\r\n\r\nexport default TextInputBEM;","examples":[{"name":"ExampleError","description":"Required TextBox with error","code":"import React from 'react';\r\nimport TextInputBEM from 'ps-react/TextInputBEM';\r\n\r\n/** Required TextBox with error */\r\nexport default class ExampleError extends React.Component {\r\n render() {\r\n return (\r\n <TextInputBEM\r\n htmlId=\"example-optional\"\r\n label=\"First Name\"\r\n name=\"firstname\"\r\n onChange={() => {}}\r\n required\r\n error=\"First name is required.\"\r\n />\r\n )\r\n }\r\n}\r\n"}]},{"name":"TextInputStyledComponents","description":"Text input with integrated label to enforce consistency in layout, error display, label placement","props":{"htmlId":{"type":{"name":"string"},"required":true,"description":"Unique HTML ID. Used for tying label to HTML input. Handy hook for automated testing."},"name":{"type":{"name":"string"},"required":true,"description":"Input name. Recommend setting this to match object's property so a single change handler"},"label":{"type":{"name":"string"},"required":true,"description":"Input label"},"type":{"type":{"name":"enum","value":[{"value":"'text'","computed":false},{"value":"'number'","computed":false},{"value":"'password'","computed":false}]},"required":false,"description":"Input type","defaultValue":{"value":"'text'","computed":false}},"required":{"type":{"name":"bool"},"required":false,"description":"Mark label with asterisk if set to true","defaultValue":{"value":"false","computed":false}},"onChange":{"type":{"name":"func"},"required":true,"description":"Function to call onChange"},"placeholder":{"type":{"name":"string"},"required":false,"description":"Placeholder to display when empty"},"error":{"type":{"name":"string"},"required":false,"description":"String to display when error occurs"},"children":{"type":{"name":"node"},"required":false,"description":"Child component to display next to the input"}},"code":"import React from 'react';\r\nimport PropTypes from 'prop-types';\r\nimport Label from '../Label';\r\nimport styled from 'styled-components';\r\n\r\n/** Text input with integrated label to enforce consistency in layout, error display, label placement */\r\nfunction TextInputStyledComponents({ htmlId, name, label, type = 'text', required = false, onChange, placeholder, value, error, children, ...props }) {\r\n return (\r\n <div style={{ marginBottom: 16 }}>\r\n <Label htmlFor={htmlId} label={label} required={required} />\r\n <input\r\n id={htmlId}\r\n type={type}\r\n name={name}\r\n placeholder={placeholder}\r\n value={value}\r\n onChange={onChange}\r\n style={error && { border: 'solid 1px red' }}\r\n {...props} />\r\n {children}\r\n { error && <div className='error' style={{ color: 'red' }}>{error}</div> }\r\n </div>\r\n );\r\n};\r\n\r\nTextInputStyledComponents.propTypes = {\r\n /** Unique HTML ID. Used for tying label to HTML input. Handy hook for automated testing. */\r\n htmlId: PropTypes.string.isRequired,\r\n\r\n /** Input name. Recommend setting this to match object's property so a single change handler */\r\n name: PropTypes.string.isRequired,\r\n\r\n /** Input label */\r\n label: PropTypes.string.isRequired,\r\n\r\n /** Input type */\r\n type: PropTypes.oneOf(['text', 'number', 'password']),\r\n\r\n /** Mark label with asterisk if set to true */\r\n required: PropTypes.bool,\r\n\r\n /** Function to call onChange */\r\n onChange: PropTypes.func.isRequired,\r\n\r\n /** Placeholder to display when empty */\r\n placeholder: PropTypes.string,\r\n\r\n /** String to display when error occurs */\r\n error: PropTypes.string,\r\n\r\n /** Child component to display next to the input */\r\n children: PropTypes.node\r\n};\r\n\r\nexport default TextInputStyledComponents;","examples":[]}]
src/routes/dashboard/components/recentSales.js
terryli1643/thinkmore
import React from 'react' import PropTypes from 'prop-types' import { Table, Tag } from 'antd' import styles from './recentSales.less' import { color } from '../../../utils' const status = { 1: { color: color.green, text: 'SALE', }, 2: { color: color.yellow, text: 'REJECT', }, 3: { color: color.red, text: 'TAX', }, 4: { color: color.blue, text: 'EXTENDED', }, } function RecentSales ({ data }) { const columns = [ { title: 'NAME', dataIndex: 'name', }, { title: 'STATUS', dataIndex: 'status', render: text => <Tag color={status[text].color}>{status[text].text}</Tag>, }, { title: 'DATE', dataIndex: 'date', render: text => new Date(text).format('yyyy-MM-dd'), }, { title: 'PRICE', dataIndex: 'price', render: (text, it) => <span style={{ color: status[it.status].color }}>${text}</span>, }, ] return ( <div className={styles.recentsales}> <Table pagination={false} columns={columns} rowKey={(record, key) => key} dataSource={data.filter((item, key) => key < 5)} /> </div> ) } RecentSales.propTypes = { data: PropTypes.array, } export default RecentSales
test/trans.render.list.spec.js
i18next/react-i18next
import React from 'react'; import { render } from '@testing-library/react'; import './i18n'; import { Trans } from '../src/Trans'; describe('Trans should render nested components', () => { it('should render dynamic ul as components property', () => { const list = ['li1', 'li2']; const TestComponent = () => ( <Trans i18nKey="testTrans4KeyWithNestedComponent" components={[ <ul> {list.map(item => ( <li key={item}>{item}</li> ))} </ul>, ]} /> ); const { container } = render(<TestComponent />); expect(container.firstChild).toMatchInlineSnapshot(` <div> Result should be a list: <ul> <li> li1 </li> <li> li2 </li> </ul> </div> `); }); it('should render dynamic ul as components property when pass as a children', () => { const list = ['li1', 'li2']; const TestComponent = () => ( <Trans i18nKey="testTrans5KeyWithNestedComponent"> My list: <ul> {list.map(item => ( <li key={item}>{item}</li> ))} </ul> </Trans> ); const { container } = render(<TestComponent />); expect(container.firstChild).toMatchInlineSnapshot(` <div> Result should be a list: <ul> <li> li1 </li> <li> li2 </li> </ul> </div> `); }); });
app/scripts/tests/pages/ShowMobilizationTest.js
igr-santos/bonde-client
import React from 'react' import TestUtils from 'react-addons-test-utils' import DocumentMeta from 'react-document-meta' import ShowMobilization from './../../pages/ShowMobilization' import { Navbar, Block } from './../../components' let component let metaData const mobilization = { id: 1, name: 'My Mobilization', goal: 'My goal', facebook_share_title: 'My Facebook share title', facebook_share_description: 'My Facebook share description', facebook_share_image: 'http://localhost:3001/my_facebook_share_image.png', color_scheme: 'my-color-scheme', header_font: 'my-header-font', body_font: 'my-header-font' } const block1 = { hidden: false, id: 1 } const block2 = { hidden: false, id: 2 } const block3 = { hidden: true, id: 3 } const blocks = { data: [block1, block2, block3] } const widgets = { data: [{}, {}] } describe('ShowMobilization', () => { before(() => { component = TestUtils.renderIntoDocument( <ShowMobilization mobilization={mobilization} blocks={blocks} widgets={widgets} /> ) }) describe('#render', () => { it('should render not hidden blocks', () => { expect( TestUtils.scryRenderedComponentsWithType(component, Block) ).to.have.length(2) }) it('should render a Navbar', () => { expect( TestUtils.scryRenderedComponentsWithType(component, Navbar) ).to.have.length(1) }) it('should render a DocumentMeta', () => { expect( TestUtils.scryRenderedComponentsWithType(component, DocumentMeta) ).to.have.length(1) }) it('should render a div with the mobilization color scheme', () => { expect( TestUtils.scryRenderedDOMComponentsWithClass(component, mobilization.color_scheme) ).to.have.length(1) }) it('should render a div with the mobilizations color scheme', () => { expect( TestUtils.scryRenderedDOMComponentsWithClass(component, mobilization.color_scheme) ).to.have.length(1) }) it('should render a div with the mobilizations header font', () => { expect( TestUtils.scryRenderedDOMComponentsWithClass(component, `${mobilization.header_font}-header`) ).to.have.length.above(0) }) it('should render a div with the mobilizations body font', () => { expect( TestUtils.scryRenderedDOMComponentsWithClass(component, `${mobilization.body_font}-body`) ).to.have.length.above(0) }) }) describe('#metaData', () => { before(() => { metaData = component.metaData(mobilization) }) it('should set mobilizations name as title', () => { expect(metaData.title).to.be.eql(mobilization.name) }) it('should set mobilizations goal as description', () => { expect(metaData.description).to.be.eql(mobilization.goal) }) it('should set mobilizations Facebook share title as og:title', () => { expect(metaData.meta.name['og:title']).to.be.eql(mobilization.facebook_share_title) }) it('should set mobilizations Facebook share description as og:description', () => { expect(metaData.meta.name['og:description']).to.be.eql(mobilization.facebook_share_description) }) it('should set mobilizations Facebook share image as og:image', () => { expect(metaData.meta.name['og:image']).to.be.eql(mobilization.facebook_share_image) }) it('should set a responsive viewport', () => { expect(metaData.meta.name.viewport).to.be.eql('width=device-width, initial-scale=1') }) }) })
ajax/libs/rxjs/2.3.12/rx.js
cdnjs/cdnjs
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. ;(function (undefined) { var objectTypes = { 'boolean': false, 'function': true, 'object': true, 'number': false, 'string': false, 'undefined': false }; var root = (objectTypes[typeof window] && window) || this, freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, freeModule = objectTypes[typeof module] && module && !module.nodeType && module, moduleExports = freeModule && freeModule.exports === freeExports && freeExports, freeGlobal = objectTypes[typeof global] && global; if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { root = freeGlobal; } var Rx = { internals: {}, config: { Promise: root.Promise // Detect if promise exists }, helpers: { } }; // Defaults var noop = Rx.helpers.noop = function () { }, notDefined = Rx.helpers.notDefined = function (x) { return typeof x === 'undefined'; }, isScheduler = Rx.helpers.isScheduler = function (x) { return x instanceof Rx.Scheduler; }, identity = Rx.helpers.identity = function (x) { return x; }, pluck = Rx.helpers.pluck = function (property) { return function (x) { return x[property]; }; }, just = Rx.helpers.just = function (value) { return function () { return value; }; }, defaultNow = Rx.helpers.defaultNow = Date.now, defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); }, defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); }, defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); }, defaultError = Rx.helpers.defaultError = function (err) { throw err; }, isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.then === 'function'; }, asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); }, not = Rx.helpers.not = function (a) { return !a; }, isFunction = Rx.helpers.isFunction = (function () { var isFn = function (value) { return typeof value == 'function' || false; } // fallback for older versions of Chrome and Safari if (isFn(/x/)) { isFn = function(value) { return typeof value == 'function' && toString.call(value) == '[object Function]'; }; } return isFn; }()); // Errors var sequenceContainsNoElements = 'Sequence contains no elements.'; var argumentOutOfRange = 'Argument out of range'; var objectDisposed = 'Object has been disposed'; function checkDisposed() { if (this.isDisposed) { throw new Error(objectDisposed); } } // Shim in iterator support var $iterator$ = (typeof Symbol === 'function' && Symbol.iterator) || '_es6shim_iterator_'; // Bug for mozilla version if (root.Set && typeof new root.Set()['@@iterator'] === 'function') { $iterator$ = '@@iterator'; } var doneEnumerator = Rx.doneEnumerator = { done: true, value: undefined }; Rx.iterator = $iterator$; /** `Object#toString` result shortcuts */ var argsClass = '[object Arguments]', arrayClass = '[object Array]', boolClass = '[object Boolean]', dateClass = '[object Date]', errorClass = '[object Error]', funcClass = '[object Function]', numberClass = '[object Number]', objectClass = '[object Object]', regexpClass = '[object RegExp]', stringClass = '[object String]'; var toString = Object.prototype.toString, hasOwnProperty = Object.prototype.hasOwnProperty, supportsArgsClass = toString.call(arguments) == argsClass, // For less <IE9 && FF<4 suportNodeClass, errorProto = Error.prototype, objectProto = Object.prototype, propertyIsEnumerable = objectProto.propertyIsEnumerable; try { suportNodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + '')); } catch(e) { suportNodeClass = true; } var shadowedProps = [ 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf' ]; var nonEnumProps = {}; nonEnumProps[arrayClass] = nonEnumProps[dateClass] = nonEnumProps[numberClass] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true }; nonEnumProps[boolClass] = nonEnumProps[stringClass] = { 'constructor': true, 'toString': true, 'valueOf': true }; nonEnumProps[errorClass] = nonEnumProps[funcClass] = nonEnumProps[regexpClass] = { 'constructor': true, 'toString': true }; nonEnumProps[objectClass] = { 'constructor': true }; var support = {}; (function () { var ctor = function() { this.x = 1; }, props = []; ctor.prototype = { 'valueOf': 1, 'y': 1 }; for (var key in new ctor) { props.push(key); } for (key in arguments) { } // Detect if `name` or `message` properties of `Error.prototype` are enumerable by default. support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || propertyIsEnumerable.call(errorProto, 'name'); // Detect if `prototype` properties are enumerable by default. support.enumPrototypes = propertyIsEnumerable.call(ctor, 'prototype'); // Detect if `arguments` object indexes are non-enumerable support.nonEnumArgs = key != 0; // Detect if properties shadowing those on `Object.prototype` are non-enumerable. support.nonEnumShadows = !/valueOf/.test(props); }(1)); function isObject(value) { // check if the value is the ECMAScript language type of Object // http://es5.github.io/#x8 // and avoid a V8 bug // https://code.google.com/p/v8/issues/detail?id=2291 var type = typeof value; return value && (type == 'function' || type == 'object') || false; } function keysIn(object) { var result = []; if (!isObject(object)) { return result; } if (support.nonEnumArgs && object.length && isArguments(object)) { object = slice.call(object); } var skipProto = support.enumPrototypes && typeof object == 'function', skipErrorProps = support.enumErrorProps && (object === errorProto || object instanceof Error); for (var key in object) { if (!(skipProto && key == 'prototype') && !(skipErrorProps && (key == 'message' || key == 'name'))) { result.push(key); } } if (support.nonEnumShadows && object !== objectProto) { var ctor = object.constructor, index = -1, length = shadowedProps.length; if (object === (ctor && ctor.prototype)) { var className = object === stringProto ? stringClass : object === errorProto ? errorClass : toString.call(object), nonEnum = nonEnumProps[className]; } while (++index < length) { key = shadowedProps[index]; if (!(nonEnum && nonEnum[key]) && hasOwnProperty.call(object, key)) { result.push(key); } } } return result; } function internalFor(object, callback, keysFunc) { var index = -1, props = keysFunc(object), length = props.length; while (++index < length) { var key = props[index]; if (callback(object[key], key, object) === false) { break; } } return object; } function internalForIn(object, callback) { return internalFor(object, callback, keysIn); } function isNode(value) { // IE < 9 presents DOM nodes as `Object` objects except they have `toString` // methods that are `typeof` "string" and still can coerce nodes to strings return typeof value.toString != 'function' && typeof (value + '') == 'string'; } function isArguments(value) { return (value && typeof value == 'object') ? toString.call(value) == argsClass : false; } // fallback for browsers that can't detect `arguments` objects by [[Class]] if (!supportsArgsClass) { isArguments = function(value) { return (value && typeof value == 'object') ? hasOwnProperty.call(value, 'callee') : false; }; } var isEqual = Rx.internals.isEqual = function (x, y) { return deepEquals(x, y, [], []); }; /** @private * Used for deep comparison **/ function deepEquals(a, b, stackA, stackB) { // exit early for identical values if (a === b) { // treat `+0` vs. `-0` as not equal return a !== 0 || (1 / a == 1 / b); } var type = typeof a, otherType = typeof b; // exit early for unlike primitive values if (a === a && (a == null || b == null || (type != 'function' && type != 'object' && otherType != 'function' && otherType != 'object'))) { return false; } // compare [[Class]] names var className = toString.call(a), otherClass = toString.call(b); if (className == argsClass) { className = objectClass; } if (otherClass == argsClass) { otherClass = objectClass; } if (className != otherClass) { return false; } switch (className) { case boolClass: case dateClass: // coerce dates and booleans to numbers, dates to milliseconds and booleans // to `1` or `0` treating invalid dates coerced to `NaN` as not equal return +a == +b; case numberClass: // treat `NaN` vs. `NaN` as equal return (a != +a) ? b != +b // but treat `-0` vs. `+0` as not equal : (a == 0 ? (1 / a == 1 / b) : a == +b); case regexpClass: case stringClass: // coerce regexes to strings (http://es5.github.io/#x15.10.6.4) // treat string primitives and their corresponding object instances as equal return a == String(b); } var isArr = className == arrayClass; if (!isArr) { // exit for functions and DOM nodes if (className != objectClass || (!support.nodeClass && (isNode(a) || isNode(b)))) { return false; } // in older versions of Opera, `arguments` objects have `Array` constructors var ctorA = !support.argsObject && isArguments(a) ? Object : a.constructor, ctorB = !support.argsObject && isArguments(b) ? Object : b.constructor; // non `Object` object instances with different constructors are not equal if (ctorA != ctorB && !(hasOwnProperty.call(a, 'constructor') && hasOwnProperty.call(b, 'constructor')) && !(isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB) && ('constructor' in a && 'constructor' in b) ) { return false; } } // assume cyclic structures are equal // the algorithm for detecting cyclic structures is adapted from ES 5.1 // section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3) var initedStack = !stackA; stackA || (stackA = []); stackB || (stackB = []); var length = stackA.length; while (length--) { if (stackA[length] == a) { return stackB[length] == b; } } var size = 0; result = true; // add `a` and `b` to the stack of traversed objects stackA.push(a); stackB.push(b); // recursively compare objects and arrays (susceptible to call stack limits) if (isArr) { // compare lengths to determine if a deep comparison is necessary length = a.length; size = b.length; result = size == length; if (result) { // deep compare the contents, ignoring non-numeric properties while (size--) { var index = length, value = b[size]; if (!(result = deepEquals(a[size], value, stackA, stackB))) { break; } } } } else { // deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys` // which, in this case, is more costly internalForIn(b, function(value, key, b) { if (hasOwnProperty.call(b, key)) { // count the number of properties. size++; // deep compare each property value. return (result = hasOwnProperty.call(a, key) && deepEquals(a[key], value, stackA, stackB)); } }); if (result) { // ensure both objects have the same number of properties internalForIn(a, function(value, key, a) { if (hasOwnProperty.call(a, key)) { // `size` will be `-1` if `a` has more properties than `b` return (result = --size > -1); } }); } } stackA.pop(); stackB.pop(); return result; } var slice = Array.prototype.slice; function argsOrArray(args, idx) { return args.length === 1 && Array.isArray(args[idx]) ? args[idx] : slice.call(args); } var hasProp = {}.hasOwnProperty; var inherits = this.inherits = Rx.internals.inherits = function (child, parent) { function __() { this.constructor = child; } __.prototype = parent.prototype; child.prototype = new __(); }; var addProperties = Rx.internals.addProperties = function (obj) { var sources = slice.call(arguments, 1); for (var i = 0, len = sources.length; i < len; i++) { var source = sources[i]; for (var prop in source) { obj[prop] = source[prop]; } } }; // Rx Utils var addRef = Rx.internals.addRef = function (xs, r) { return new AnonymousObservable(function (observer) { return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer)); }); }; function arrayInitialize(count, factory) { var a = new Array(count); for (var i = 0; i < count; i++) { a[i] = factory(); } return a; } // Collections function IndexedItem(id, value) { this.id = id; this.value = value; } IndexedItem.prototype.compareTo = function (other) { var c = this.value.compareTo(other.value); c === 0 && (c = this.id - other.id); return c; }; // Priority Queue for Scheduling var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) { this.items = new Array(capacity); this.length = 0; }; var priorityProto = PriorityQueue.prototype; priorityProto.isHigherPriority = function (left, right) { return this.items[left].compareTo(this.items[right]) < 0; }; priorityProto.percolate = function (index) { if (index >= this.length || index < 0) { return; } var parent = index - 1 >> 1; if (parent < 0 || parent === index) { return; } if (this.isHigherPriority(index, parent)) { var temp = this.items[index]; this.items[index] = this.items[parent]; this.items[parent] = temp; this.percolate(parent); } }; priorityProto.heapify = function (index) { +index || (index = 0); if (index >= this.length || index < 0) { return; } var left = 2 * index + 1, right = 2 * index + 2, first = index; if (left < this.length && this.isHigherPriority(left, first)) { first = left; } if (right < this.length && this.isHigherPriority(right, first)) { first = right; } if (first !== index) { var temp = this.items[index]; this.items[index] = this.items[first]; this.items[first] = temp; this.heapify(first); } }; priorityProto.peek = function () { return this.items[0].value; }; priorityProto.removeAt = function (index) { this.items[index] = this.items[--this.length]; delete this.items[this.length]; this.heapify(); }; priorityProto.dequeue = function () { var result = this.peek(); this.removeAt(0); return result; }; priorityProto.enqueue = function (item) { var index = this.length++; this.items[index] = new IndexedItem(PriorityQueue.count++, item); this.percolate(index); }; priorityProto.remove = function (item) { for (var i = 0; i < this.length; i++) { if (this.items[i].value === item) { this.removeAt(i); return true; } } return false; }; PriorityQueue.count = 0; /** * Represents a group of disposable resources that are disposed together. * @constructor */ var CompositeDisposable = Rx.CompositeDisposable = function () { this.disposables = argsOrArray(arguments, 0); this.isDisposed = false; this.length = this.disposables.length; }; var CompositeDisposablePrototype = CompositeDisposable.prototype; /** * Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed. * @param {Mixed} item Disposable to add. */ CompositeDisposablePrototype.add = function (item) { if (this.isDisposed) { item.dispose(); } else { this.disposables.push(item); this.length++; } }; /** * Removes and disposes the first occurrence of a disposable from the CompositeDisposable. * @param {Mixed} item Disposable to remove. * @returns {Boolean} true if found; false otherwise. */ CompositeDisposablePrototype.remove = function (item) { var shouldDispose = false; if (!this.isDisposed) { var idx = this.disposables.indexOf(item); if (idx !== -1) { shouldDispose = true; this.disposables.splice(idx, 1); this.length--; item.dispose(); } } return shouldDispose; }; /** * Disposes all disposables in the group and removes them from the group. */ CompositeDisposablePrototype.dispose = function () { if (!this.isDisposed) { this.isDisposed = true; var currentDisposables = this.disposables.slice(0); this.disposables = []; this.length = 0; for (var i = 0, len = currentDisposables.length; i < len; i++) { currentDisposables[i].dispose(); } } }; /** * Converts the existing CompositeDisposable to an array of disposables * @returns {Array} An array of disposable objects. */ CompositeDisposablePrototype.toArray = function () { return this.disposables.slice(0); }; /** * Provides a set of static methods for creating Disposables. * * @constructor * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. */ var Disposable = Rx.Disposable = function (action) { this.isDisposed = false; this.action = action || noop; }; /** Performs the task of cleaning up resources. */ Disposable.prototype.dispose = function () { if (!this.isDisposed) { this.action(); this.isDisposed = true; } }; /** * Creates a disposable object that invokes the specified action when disposed. * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. * @return {Disposable} The disposable object that runs the given action upon disposal. */ var disposableCreate = Disposable.create = function (action) { return new Disposable(action); }; /** * Gets the disposable that does nothing when disposed. */ var disposableEmpty = Disposable.empty = { dispose: noop }; var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = (function () { function BooleanDisposable () { this.isDisposed = false; this.current = null; } var booleanDisposablePrototype = BooleanDisposable.prototype; /** * Gets the underlying disposable. * @return The underlying disposable. */ booleanDisposablePrototype.getDisposable = function () { return this.current; }; /** * Sets the underlying disposable. * @param {Disposable} value The new underlying disposable. */ booleanDisposablePrototype.setDisposable = function (value) { var shouldDispose = this.isDisposed, old; if (!shouldDispose) { old = this.current; this.current = value; } old && old.dispose(); shouldDispose && value && value.dispose(); }; /** * Disposes the underlying disposable as well as all future replacements. */ booleanDisposablePrototype.dispose = function () { var old; if (!this.isDisposed) { this.isDisposed = true; old = this.current; this.current = null; } old && old.dispose(); }; return BooleanDisposable; }()); var SerialDisposable = Rx.SerialDisposable = SingleAssignmentDisposable; /** * Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed. */ var RefCountDisposable = Rx.RefCountDisposable = (function () { function InnerDisposable(disposable) { this.disposable = disposable; this.disposable.count++; this.isInnerDisposed = false; } InnerDisposable.prototype.dispose = function () { if (!this.disposable.isDisposed) { if (!this.isInnerDisposed) { this.isInnerDisposed = true; this.disposable.count--; if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) { this.disposable.isDisposed = true; this.disposable.underlyingDisposable.dispose(); } } } }; /** * Initializes a new instance of the RefCountDisposable with the specified disposable. * @constructor * @param {Disposable} disposable Underlying disposable. */ function RefCountDisposable(disposable) { this.underlyingDisposable = disposable; this.isDisposed = false; this.isPrimaryDisposed = false; this.count = 0; } /** * Disposes the underlying disposable only when all dependent disposables have been disposed */ RefCountDisposable.prototype.dispose = function () { if (!this.isDisposed) { if (!this.isPrimaryDisposed) { this.isPrimaryDisposed = true; if (this.count === 0) { this.isDisposed = true; this.underlyingDisposable.dispose(); } } } }; /** * Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable. * @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime. */ RefCountDisposable.prototype.getDisposable = function () { return this.isDisposed ? disposableEmpty : new InnerDisposable(this); }; return RefCountDisposable; })(); function ScheduledDisposable(scheduler, disposable) { this.scheduler = scheduler; this.disposable = disposable; this.isDisposed = false; } ScheduledDisposable.prototype.dispose = function () { var parent = this; this.scheduler.schedule(function () { if (!parent.isDisposed) { parent.isDisposed = true; parent.disposable.dispose(); } }); }; var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) { this.scheduler = scheduler; this.state = state; this.action = action; this.dueTime = dueTime; this.comparer = comparer || defaultSubComparer; this.disposable = new SingleAssignmentDisposable(); } ScheduledItem.prototype.invoke = function () { this.disposable.setDisposable(this.invokeCore()); }; ScheduledItem.prototype.compareTo = function (other) { return this.comparer(this.dueTime, other.dueTime); }; ScheduledItem.prototype.isCancelled = function () { return this.disposable.isDisposed; }; ScheduledItem.prototype.invokeCore = function () { return this.action(this.scheduler, this.state); }; /** Provides a set of static properties to access commonly used schedulers. */ var Scheduler = Rx.Scheduler = (function () { function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) { this.now = now; this._schedule = schedule; this._scheduleRelative = scheduleRelative; this._scheduleAbsolute = scheduleAbsolute; } function invokeRecImmediate(scheduler, pair) { var state = pair.first, action = pair.second, group = new CompositeDisposable(), recursiveAction = function (state1) { action(state1, function (state2) { var isAdded = false, isDone = false, d = scheduler.scheduleWithState(state2, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); }; recursiveAction(state); return group; } function invokeRecDate(scheduler, pair, method) { var state = pair.first, action = pair.second, group = new CompositeDisposable(), recursiveAction = function (state1) { action(state1, function (state2, dueTime1) { var isAdded = false, isDone = false, d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); }; recursiveAction(state); return group; } function invokeAction(scheduler, action) { action(); return disposableEmpty; } var schedulerProto = Scheduler.prototype; /** * Schedules an action to be executed. * @param {Function} action Action to execute. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.schedule = function (action) { return this._schedule(action, invokeAction); }; /** * Schedules an action to be executed. * @param state State passed to the action to be executed. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithState = function (state, action) { return this._schedule(state, action); }; /** * Schedules an action to be executed after the specified relative due time. * @param {Function} action Action to execute. * @param {Number} dueTime Relative time after which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithRelative = function (dueTime, action) { return this._scheduleRelative(action, dueTime, invokeAction); }; /** * Schedules an action to be executed after dueTime. * @param state State passed to the action to be executed. * @param {Function} action Action to be executed. * @param {Number} dueTime Relative time after which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) { return this._scheduleRelative(state, dueTime, action); }; /** * Schedules an action to be executed at the specified absolute due time. * @param {Function} action Action to execute. * @param {Number} dueTime Absolute time at which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithAbsolute = function (dueTime, action) { return this._scheduleAbsolute(action, dueTime, invokeAction); }; /** * Schedules an action to be executed at dueTime. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to be executed. * @param {Number}dueTime Absolute time at which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) { return this._scheduleAbsolute(state, dueTime, action); }; /** Gets the current time according to the local machine's system clock. */ Scheduler.now = defaultNow; /** * Normalizes the specified TimeSpan value to a positive value. * @param {Number} timeSpan The time span value to normalize. * @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0 */ Scheduler.normalize = function (timeSpan) { timeSpan < 0 && (timeSpan = 0); return timeSpan; }; return Scheduler; }()); var normalizeTime = Scheduler.normalize; (function (schedulerProto) { function invokeRecImmediate(scheduler, pair) { var state = pair.first, action = pair.second, group = new CompositeDisposable(), recursiveAction = function (state1) { action(state1, function (state2) { var isAdded = false, isDone = false, d = scheduler.scheduleWithState(state2, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); }; recursiveAction(state); return group; } function invokeRecDate(scheduler, pair, method) { var state = pair.first, action = pair.second, group = new CompositeDisposable(), recursiveAction = function (state1) { action(state1, function (state2, dueTime1) { var isAdded = false, isDone = false, d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); }; recursiveAction(state); return group; } function scheduleInnerRecursive(action, self) { action(function(dt) { self(action, dt); }); } /** * Schedules an action to be executed recursively. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursive = function (action) { return this.scheduleRecursiveWithState(action, function (_action, self) { _action(function () { self(_action); }); }); }; /** * Schedules an action to be executed recursively. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithState = function (state, action) { return this.scheduleWithState({ first: state, second: action }, invokeRecImmediate); }; /** * Schedules an action to be executed recursively after a specified relative due time. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time. * @param {Number}dueTime Relative time after which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) { return this.scheduleRecursiveWithRelativeAndState(action, dueTime, scheduleInnerRecursive); }; /** * Schedules an action to be executed recursively after a specified relative due time. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. * @param {Number}dueTime Relative time after which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) { return this._scheduleRelative({ first: state, second: action }, dueTime, function (s, p) { return invokeRecDate(s, p, 'scheduleWithRelativeAndState'); }); }; /** * Schedules an action to be executed recursively at a specified absolute due time. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time. * @param {Number}dueTime Absolute time at which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) { return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, scheduleInnerRecursive); }; /** * Schedules an action to be executed recursively at a specified absolute due time. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. * @param {Number}dueTime Absolute time at which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) { return this._scheduleAbsolute({ first: state, second: action }, dueTime, function (s, p) { return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState'); }); }; }(Scheduler.prototype)); (function (schedulerProto) { /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ Scheduler.prototype.schedulePeriodic = function (period, action) { return this.schedulePeriodicWithState(null, period, action); }; /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. * @param {Mixed} state Initial state passed to the action upon the first iteration. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed, potentially updating the state. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ Scheduler.prototype.schedulePeriodicWithState = function(state, period, action) { if (typeof root.setInterval === 'undefined') { throw new Error('Periodic scheduling not supported.'); } var s = state; var id = root.setInterval(function () { s = action(s); }, period); return disposableCreate(function () { root.clearInterval(id); }); }; }(Scheduler.prototype)); (function (schedulerProto) { /** * Returns a scheduler that wraps the original scheduler, adding exception handling for scheduled actions. * @param {Function} handler Handler that's run if an exception is caught. The exception will be rethrown if the handler returns false. * @returns {Scheduler} Wrapper around the original scheduler, enforcing exception handling. */ schedulerProto.catchError = schedulerProto['catch'] = function (handler) { return new CatchScheduler(this, handler); }; }(Scheduler.prototype)); var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () { function tick(command, recurse) { recurse(0, this._period); try { this._state = this._action(this._state); } catch (e) { this._cancel.dispose(); throw e; } } function SchedulePeriodicRecursive(scheduler, state, period, action) { this._scheduler = scheduler; this._state = state; this._period = period; this._action = action; } SchedulePeriodicRecursive.prototype.start = function () { var d = new SingleAssignmentDisposable(); this._cancel = d; d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this))); return d; }; return SchedulePeriodicRecursive; }()); /** * Gets a scheduler that schedules work immediately on the current thread. */ var immediateScheduler = Scheduler.immediate = (function () { function scheduleNow(state, action) { return action(this, state); } function scheduleRelative(state, dueTime, action) { var dt = normalizeTime(dt); while (dt - this.now() > 0) { } return action(this, state); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); }()); /** * Gets a scheduler that schedules work as soon as possible on the current thread. */ var currentThreadScheduler = Scheduler.currentThread = (function () { var queue; function runTrampoline (q) { var item; while (q.length > 0) { item = q.dequeue(); if (!item.isCancelled()) { // Note, do not schedule blocking work! while (item.dueTime - Scheduler.now() > 0) { } if (!item.isCancelled()) { item.invoke(); } } } } function scheduleNow(state, action) { return this.scheduleWithRelativeAndState(state, 0, action); } function scheduleRelative(state, dueTime, action) { var dt = this.now() + Scheduler.normalize(dueTime), si = new ScheduledItem(this, state, action, dt); if (!queue) { queue = new PriorityQueue(4); queue.enqueue(si); try { runTrampoline(queue); } catch (e) { throw e; } finally { queue = null; } } else { queue.enqueue(si); } return si.disposable; } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } var currentScheduler = new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); currentScheduler.scheduleRequired = function () { return !queue; }; currentScheduler.ensureTrampoline = function (action) { if (!queue) { this.schedule(action); } else { action(); } }; return currentScheduler; }()); var scheduleMethod, clearMethod = noop; var localTimer = (function () { var localSetTimeout, localClearTimeout = noop; if ('WScript' in this) { localSetTimeout = function (fn, time) { WScript.Sleep(time); fn(); }; } else if (!!root.setTimeout) { localSetTimeout = root.setTimeout; localClearTimeout = root.clearTimeout; } else { throw new Error('No concurrency detected!'); } return { setTimeout: localSetTimeout, clearTimeout: localClearTimeout }; }()); var localSetTimeout = localTimer.setTimeout, localClearTimeout = localTimer.clearTimeout; (function () { var reNative = RegExp('^' + String(toString) .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') .replace(/toString| for [^\]]+/g, '.*?') + '$' ); var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' && !reNative.test(setImmediate) && setImmediate, clearImmediate = typeof (clearImmediate = freeGlobal && moduleExports && freeGlobal.clearImmediate) == 'function' && !reNative.test(clearImmediate) && clearImmediate; function postMessageSupported () { // Ensure not in a worker if (!root.postMessage || root.importScripts) { return false; } var isAsync = false, oldHandler = root.onmessage; // Test for async root.onmessage = function () { isAsync = true; }; root.postMessage('','*'); root.onmessage = oldHandler; return isAsync; } // Use in order, nextTick, setImmediate, postMessage, MessageChannel, script readystatechanged, setTimeout if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { scheduleMethod = process.nextTick; } else if (typeof setImmediate === 'function') { scheduleMethod = setImmediate; clearMethod = clearImmediate; } else if (postMessageSupported()) { var MSG_PREFIX = 'ms.rx.schedule' + Math.random(), tasks = {}, taskId = 0; function onGlobalPostMessage(event) { // Only if we're a match to avoid any other global events if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) { var handleId = event.data.substring(MSG_PREFIX.length), action = tasks[handleId]; action(); delete tasks[handleId]; } } if (root.addEventListener) { root.addEventListener('message', onGlobalPostMessage, false); } else { root.attachEvent('onmessage', onGlobalPostMessage, false); } scheduleMethod = function (action) { var currentId = taskId++; tasks[currentId] = action; root.postMessage(MSG_PREFIX + currentId, '*'); }; } else if (!!root.MessageChannel) { var channel = new root.MessageChannel(), channelTasks = {}, channelTaskId = 0; channel.port1.onmessage = function (event) { var id = event.data, action = channelTasks[id]; action(); delete channelTasks[id]; }; scheduleMethod = function (action) { var id = channelTaskId++; channelTasks[id] = action; channel.port2.postMessage(id); }; } else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) { scheduleMethod = function (action) { var scriptElement = root.document.createElement('script'); scriptElement.onreadystatechange = function () { action(); scriptElement.onreadystatechange = null; scriptElement.parentNode.removeChild(scriptElement); scriptElement = null; }; root.document.documentElement.appendChild(scriptElement); }; } else { scheduleMethod = function (action) { return localSetTimeout(action, 0); }; clearMethod = localClearTimeout; } }()); /** * Gets a scheduler that schedules work via a timed callback based upon platform. */ var timeoutScheduler = Scheduler.timeout = (function () { function scheduleNow(state, action) { var scheduler = this, disposable = new SingleAssignmentDisposable(); var id = scheduleMethod(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }); return new CompositeDisposable(disposable, disposableCreate(function () { clearMethod(id); })); } function scheduleRelative(state, dueTime, action) { var scheduler = this, dt = Scheduler.normalize(dueTime); if (dt === 0) { return scheduler.scheduleWithState(state, action); } var disposable = new SingleAssignmentDisposable(); var id = localSetTimeout(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }, dt); return new CompositeDisposable(disposable, disposableCreate(function () { localClearTimeout(id); })); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); })(); /** @private */ var CatchScheduler = (function (_super) { function localNow() { return this._scheduler.now(); } function scheduleNow(state, action) { return this._scheduler.scheduleWithState(state, this._wrap(action)); } function scheduleRelative(state, dueTime, action) { return this._scheduler.scheduleWithRelativeAndState(state, dueTime, this._wrap(action)); } function scheduleAbsolute(state, dueTime, action) { return this._scheduler.scheduleWithAbsoluteAndState(state, dueTime, this._wrap(action)); } inherits(CatchScheduler, _super); /** @private */ function CatchScheduler(scheduler, handler) { this._scheduler = scheduler; this._handler = handler; this._recursiveOriginal = null; this._recursiveWrapper = null; _super.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute); } /** @private */ CatchScheduler.prototype._clone = function (scheduler) { return new CatchScheduler(scheduler, this._handler); }; /** @private */ CatchScheduler.prototype._wrap = function (action) { var parent = this; return function (self, state) { try { return action(parent._getRecursiveWrapper(self), state); } catch (e) { if (!parent._handler(e)) { throw e; } return disposableEmpty; } }; }; /** @private */ CatchScheduler.prototype._getRecursiveWrapper = function (scheduler) { if (this._recursiveOriginal !== scheduler) { this._recursiveOriginal = scheduler; var wrapper = this._clone(scheduler); wrapper._recursiveOriginal = scheduler; wrapper._recursiveWrapper = wrapper; this._recursiveWrapper = wrapper; } return this._recursiveWrapper; }; /** @private */ CatchScheduler.prototype.schedulePeriodicWithState = function (state, period, action) { var self = this, failed = false, d = new SingleAssignmentDisposable(); d.setDisposable(this._scheduler.schedulePeriodicWithState(state, period, function (state1) { if (failed) { return null; } try { return action(state1); } catch (e) { failed = true; if (!self._handler(e)) { throw e; } d.dispose(); return null; } })); return d; }; return CatchScheduler; }(Scheduler)); /** * Represents a notification to an observer. */ var Notification = Rx.Notification = (function () { function Notification(kind, hasValue) { this.hasValue = hasValue == null ? false : hasValue; this.kind = kind; } /** * Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result. * * @memberOf Notification * @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on.. * @param {Function} onError Delegate to invoke for an OnError notification. * @param {Function} onCompleted Delegate to invoke for an OnCompleted notification. * @returns {Any} Result produced by the observation. */ Notification.prototype.accept = function (observerOrOnNext, onError, onCompleted) { return observerOrOnNext && typeof observerOrOnNext === 'object' ? this._acceptObservable(observerOrOnNext) : this._accept(observerOrOnNext, onError, onCompleted); }; /** * Returns an observable sequence with a single notification. * * @memberOf Notifications * @param {Scheduler} [scheduler] Scheduler to send out the notification calls on. * @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription. */ Notification.prototype.toObservable = function (scheduler) { var notification = this; isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { notification._acceptObservable(observer); notification.kind === 'N' && observer.onCompleted(); }); }); }; return Notification; })(); /** * Creates an object that represents an OnNext notification to an observer. * @param {Any} value The value contained in the notification. * @returns {Notification} The OnNext notification containing the value. */ var notificationCreateOnNext = Notification.createOnNext = (function () { function _accept (onNext) { return onNext(this.value); } function _acceptObservable(observer) { return observer.onNext(this.value); } function toString () { return 'OnNext(' + this.value + ')'; } return function (value) { var notification = new Notification('N', true); notification.value = value; notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); /** * Creates an object that represents an OnError notification to an observer. * @param {Any} error The exception contained in the notification. * @returns {Notification} The OnError notification containing the exception. */ var notificationCreateOnError = Notification.createOnError = (function () { function _accept (onNext, onError) { return onError(this.exception); } function _acceptObservable(observer) { return observer.onError(this.exception); } function toString () { return 'OnError(' + this.exception + ')'; } return function (exception) { var notification = new Notification('E'); notification.exception = exception; notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); /** * Creates an object that represents an OnCompleted notification to an observer. * @returns {Notification} The OnCompleted notification. */ var notificationCreateOnCompleted = Notification.createOnCompleted = (function () { function _accept (onNext, onError, onCompleted) { return onCompleted(); } function _acceptObservable(observer) { return observer.onCompleted(); } function toString () { return 'OnCompleted()'; } return function () { var notification = new Notification('C'); notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); var Enumerator = Rx.internals.Enumerator = function (next) { this._next = next; }; Enumerator.prototype.next = function () { return this._next(); }; Enumerator.prototype[$iterator$] = function () { return this; } var Enumerable = Rx.internals.Enumerable = function (iterator) { this._iterator = iterator; }; Enumerable.prototype[$iterator$] = function () { return this._iterator(); }; Enumerable.prototype.concat = function () { var sources = this; return new AnonymousObservable(function (observer) { var e; try { e = sources[$iterator$](); } catch(err) { observer.onError(); return; } var isDisposed, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { var currentItem; if (isDisposed) { return; } try { currentItem = e.next(); } catch (ex) { observer.onError(ex); return; } if (currentItem.done) { observer.onCompleted(); return; } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(currentValue.subscribe( observer.onNext.bind(observer), observer.onError.bind(observer), function () { self(); }) ); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; Enumerable.prototype.catchException = function () { var sources = this; return new AnonymousObservable(function (observer) { var e; try { e = sources[$iterator$](); } catch(err) { observer.onError(); return; } var isDisposed, lastException, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { if (isDisposed) { return; } var currentItem; try { currentItem = e.next(); } catch (ex) { observer.onError(ex); return; } if (currentItem.done) { if (lastException) { observer.onError(lastException); } else { observer.onCompleted(); } return; } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(currentValue.subscribe( observer.onNext.bind(observer), function (exn) { lastException = exn; self(); }, observer.onCompleted.bind(observer))); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) { if (repeatCount == null) { repeatCount = -1; } return new Enumerable(function () { var left = repeatCount; return new Enumerator(function () { if (left === 0) { return doneEnumerator; } if (left > 0) { left--; } return { done: false, value: value }; }); }); }; var enumerableOf = Enumerable.of = function (source, selector, thisArg) { selector || (selector = identity); return new Enumerable(function () { var index = -1; return new Enumerator( function () { return ++index < source.length ? { done: false, value: selector.call(thisArg, source[index], index, source) } : doneEnumerator; }); }); }; /** * Supports push-style iteration over an observable sequence. */ var Observer = Rx.Observer = function () { }; /** * Creates a notification callback from an observer. * @returns The action that forwards its input notification to the underlying observer. */ Observer.prototype.toNotifier = function () { var observer = this; return function (n) { return n.accept(observer); }; }; /** * Hides the identity of an observer. * @returns An observer that hides the identity of the specified observer. */ Observer.prototype.asObserver = function () { return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this)); }; /** * Checks access to the observer for grammar violations. This includes checking for multiple OnError or OnCompleted calls, as well as reentrancy in any of the observer methods. * If a violation is detected, an Error is thrown from the offending observer method call. * @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer. */ Observer.prototype.checked = function () { return new CheckedObserver(this); }; /** * Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions. * @param {Function} [onNext] Observer's OnNext action implementation. * @param {Function} [onError] Observer's OnError action implementation. * @param {Function} [onCompleted] Observer's OnCompleted action implementation. * @returns {Observer} The observer object implemented using the given actions. */ var observerCreate = Observer.create = function (onNext, onError, onCompleted) { onNext || (onNext = noop); onError || (onError = defaultError); onCompleted || (onCompleted = noop); return new AnonymousObserver(onNext, onError, onCompleted); }; /** * Creates an observer from a notification callback. * * @static * @memberOf Observer * @param {Function} handler Action that handles a notification. * @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives. */ Observer.fromNotifier = function (handler, thisArg) { return new AnonymousObserver(function (x) { return handler.call(thisArg, notificationCreateOnNext(x)); }, function (e) { return handler.call(thisArg, notificationCreateOnError(e)); }, function () { return handler.call(thisArg, notificationCreateOnCompleted()); }); }; /** * Schedules the invocation of observer methods on the given scheduler. * @param {Scheduler} scheduler Scheduler to schedule observer messages on. * @returns {Observer} Observer whose messages are scheduled on the given scheduler. */ Observer.notifyOn = function (scheduler) { return new ObserveOnObserver(scheduler, this); }; /** * Abstract base class for implementations of the Observer class. * This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages. */ var AbstractObserver = Rx.internals.AbstractObserver = (function (__super__) { inherits(AbstractObserver, __super__); /** * Creates a new observer in a non-stopped state. */ function AbstractObserver() { this.isStopped = false; __super__.call(this); } /** * Notifies the observer of a new element in the sequence. * @param {Any} value Next element in the sequence. */ AbstractObserver.prototype.onNext = function (value) { if (!this.isStopped) { this.next(value); } }; /** * Notifies the observer that an exception has occurred. * @param {Any} error The error that has occurred. */ AbstractObserver.prototype.onError = function (error) { if (!this.isStopped) { this.isStopped = true; this.error(error); } }; /** * Notifies the observer of the end of the sequence. */ AbstractObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.completed(); } }; /** * Disposes the observer, causing it to transition to the stopped state. */ AbstractObserver.prototype.dispose = function () { this.isStopped = true; }; AbstractObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.error(e); return true; } return false; }; return AbstractObserver; }(Observer)); /** * Class to create an Observer instance from delegate-based implementations of the on* methods. */ var AnonymousObserver = Rx.AnonymousObserver = (function (__super__) { inherits(AnonymousObserver, __super__); /** * Creates an observer from the specified OnNext, OnError, and OnCompleted actions. * @param {Any} onNext Observer's OnNext action implementation. * @param {Any} onError Observer's OnError action implementation. * @param {Any} onCompleted Observer's OnCompleted action implementation. */ function AnonymousObserver(onNext, onError, onCompleted) { __super__.call(this); this._onNext = onNext; this._onError = onError; this._onCompleted = onCompleted; } /** * Calls the onNext action. * @param {Any} value Next element in the sequence. */ AnonymousObserver.prototype.next = function (value) { this._onNext(value); }; /** * Calls the onError action. * @param {Any} error The error that has occurred. */ AnonymousObserver.prototype.error = function (error) { this._onError(error); }; /** * Calls the onCompleted action. */ AnonymousObserver.prototype.completed = function () { this._onCompleted(); }; return AnonymousObserver; }(AbstractObserver)); var CheckedObserver = (function (_super) { inherits(CheckedObserver, _super); function CheckedObserver(observer) { _super.call(this); this._observer = observer; this._state = 0; // 0 - idle, 1 - busy, 2 - done } var CheckedObserverPrototype = CheckedObserver.prototype; CheckedObserverPrototype.onNext = function (value) { this.checkAccess(); try { this._observer.onNext(value); } catch (e) { throw e; } finally { this._state = 0; } }; CheckedObserverPrototype.onError = function (err) { this.checkAccess(); try { this._observer.onError(err); } catch (e) { throw e; } finally { this._state = 2; } }; CheckedObserverPrototype.onCompleted = function () { this.checkAccess(); try { this._observer.onCompleted(); } catch (e) { throw e; } finally { this._state = 2; } }; CheckedObserverPrototype.checkAccess = function () { if (this._state === 1) { throw new Error('Re-entrancy detected'); } if (this._state === 2) { throw new Error('Observer completed'); } if (this._state === 0) { this._state = 1; } }; return CheckedObserver; }(Observer)); var ScheduledObserver = Rx.internals.ScheduledObserver = (function (__super__) { inherits(ScheduledObserver, __super__); function ScheduledObserver(scheduler, observer) { __super__.call(this); this.scheduler = scheduler; this.observer = observer; this.isAcquired = false; this.hasFaulted = false; this.queue = []; this.disposable = new SerialDisposable(); } ScheduledObserver.prototype.next = function (value) { var self = this; this.queue.push(function () { self.observer.onNext(value); }); }; ScheduledObserver.prototype.error = function (err) { var self = this; this.queue.push(function () { self.observer.onError(err); }); }; ScheduledObserver.prototype.completed = function () { var self = this; this.queue.push(function () { self.observer.onCompleted(); }); }; ScheduledObserver.prototype.ensureActive = function () { var isOwner = false, parent = this; if (!this.hasFaulted && this.queue.length > 0) { isOwner = !this.isAcquired; this.isAcquired = true; } if (isOwner) { this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) { var work; if (parent.queue.length > 0) { work = parent.queue.shift(); } else { parent.isAcquired = false; return; } try { work(); } catch (ex) { parent.queue = []; parent.hasFaulted = true; throw ex; } self(); })); } }; ScheduledObserver.prototype.dispose = function () { __super__.prototype.dispose.call(this); this.disposable.dispose(); }; return ScheduledObserver; }(AbstractObserver)); var ObserveOnObserver = (function (__super__) { inherits(ObserveOnObserver, __super__); function ObserveOnObserver() { __super__.apply(this, arguments); } ObserveOnObserver.prototype.next = function (value) { __super__.prototype.next.call(this, value); this.ensureActive(); }; ObserveOnObserver.prototype.error = function (e) { __super__.prototype.error.call(this, e); this.ensureActive(); }; ObserveOnObserver.prototype.completed = function () { __super__.prototype.completed.call(this); this.ensureActive(); }; return ObserveOnObserver; })(ScheduledObserver); var observableProto; /** * Represents a push-style collection. */ var Observable = Rx.Observable = (function () { function Observable(subscribe) { this._subscribe = subscribe; } observableProto = Observable.prototype; /** * Subscribes an observer to the observable sequence. * @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. * @returns {Diposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) { return this._subscribe(typeof observerOrOnNext === 'object' ? observerOrOnNext : observerCreate(observerOrOnNext, onError, onCompleted)); }; /** * Subscribes to the next value in the sequence with an optional "this" argument. * @param {Function} onNext The function to invoke on each element in the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribeOnNext = function (onNext, thisArg) { return this._subscribe(observerCreate(arguments.length === 2 ? function(x) { onNext.call(thisArg, x); } : onNext)); }; /** * Subscribes to an exceptional condition in the sequence with an optional "this" argument. * @param {Function} onError The function to invoke upon exceptional termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribeOnError = function (onError, thisArg) { return this._subscribe(observerCreate(null, arguments.length === 2 ? function(e) { onError.call(thisArg, e); } : onError)); }; /** * Subscribes to the next value in the sequence with an optional "this" argument. * @param {Function} onCompleted The function to invoke upon graceful termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribeOnCompleted = function (onCompleted, thisArg) { return this._subscribe(observerCreate(null, null, arguments.length === 2 ? function() { onCompleted.call(thisArg); } : onCompleted)); }; return Observable; })(); /** * Wraps the source sequence in order to run its observer callbacks on the specified scheduler. * * This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects * that require to be run on a scheduler, use subscribeOn. * * @param {Scheduler} scheduler Scheduler to notify observers on. * @returns {Observable} The source sequence whose observations happen on the specified scheduler. */ observableProto.observeOn = function (scheduler) { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(new ObserveOnObserver(scheduler, observer)); }); }; /** * Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used; * see the remarks section for more information on the distinction between subscribeOn and observeOn. * This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer * callbacks on a scheduler, use observeOn. * @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on. * @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. */ observableProto.subscribeOn = function (scheduler) { var source = this; return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), d = new SerialDisposable(); d.setDisposable(m); m.setDisposable(scheduler.schedule(function () { d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(observer))); })); return d; }); }; /** * Converts a Promise to an Observable sequence * @param {Promise} An ES6 Compliant promise. * @returns {Observable} An Observable sequence which wraps the existing promise success and failure. */ var observableFromPromise = Observable.fromPromise = function (promise) { return observableDefer(function () { var subject = new Rx.AsyncSubject(); promise.then( function (value) { if (!subject.isDisposed) { subject.onNext(value); subject.onCompleted(); } }, subject.onError.bind(subject)); return subject; }); }; /* * Converts an existing observable sequence to an ES6 Compatible Promise * @example * var promise = Rx.Observable.return(42).toPromise(RSVP.Promise); * * // With config * Rx.config.Promise = RSVP.Promise; * var promise = Rx.Observable.return(42).toPromise(); * @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise. * @returns {Promise} An ES6 compatible promise with the last value from the observable sequence. */ observableProto.toPromise = function (promiseCtor) { promiseCtor || (promiseCtor = Rx.config.Promise); if (!promiseCtor) { throw new TypeError('Promise type not provided nor in Rx.config.Promise'); } var source = this; return new promiseCtor(function (resolve, reject) { // No cancellation can be done var value, hasValue = false; source.subscribe(function (v) { value = v; hasValue = true; }, reject, function () { hasValue && resolve(value); }); }); }; /** * Creates a list from an observable sequence. * @returns An observable sequence containing a single element with a list containing all the elements of the source sequence. */ observableProto.toArray = function () { var self = this; return new AnonymousObservable(function(observer) { var arr = []; return self.subscribe( arr.push.bind(arr), observer.onError.bind(observer), function () { observer.onNext(arr); observer.onCompleted(); }); }); }; /** * Creates an observable sequence from a specified subscribe method implementation. * * @example * var res = Rx.Observable.create(function (observer) { return function () { } ); * var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } ); * var res = Rx.Observable.create(function (observer) { } ); * * @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable. * @returns {Observable} The observable sequence with the specified implementation for the Subscribe method. */ Observable.create = Observable.createWithDisposable = function (subscribe) { return new AnonymousObservable(subscribe); }; /** * Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. * * @example * var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); }); * @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise. * @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function. */ var observableDefer = Observable.defer = function (observableFactory) { return new AnonymousObservable(function (observer) { var result; try { result = observableFactory(); } catch (e) { return observableThrow(e).subscribe(observer); } isPromise(result) && (result = observableFromPromise(result)); return result.subscribe(observer); }); }; /** * Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message. * * @example * var res = Rx.Observable.empty(); * var res = Rx.Observable.empty(Rx.Scheduler.timeout); * @param {Scheduler} [scheduler] Scheduler to send the termination call on. * @returns {Observable} An observable sequence with no elements. */ var observableEmpty = Observable.empty = function (scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onCompleted(); }); }); }; var maxSafeInteger = Math.pow(2, 53) - 1; function numberIsFinite(value) { return typeof value === 'number' && root.isFinite(value); } function isNan(n) { return n !== n; } function isIterable(o) { return o[$iterator$] !== undefined; } function sign(value) { var number = +value; if (number === 0) { return number; } if (isNaN(number)) { return number; } return number < 0 ? -1 : 1; } function toLength(o) { var len = +o.length; if (isNaN(len)) { return 0; } if (len === 0 || !numberIsFinite(len)) { return len; } len = sign(len) * Math.floor(Math.abs(len)); if (len <= 0) { return 0; } if (len > maxSafeInteger) { return maxSafeInteger; } return len; } function isCallable(f) { return Object.prototype.toString.call(f) === '[object Function]' && typeof f === 'function'; } /** * This method creates a new Observable sequence from an array-like or iterable object. * @param {Any} arrayLike An array-like or iterable object to convert to an Observable sequence. * @param {Function} [mapFn] Map function to call on every element of the array. * @param {Any} [thisArg] The context to use calling the mapFn if provided. * @param {Scheduler} [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread. */ Observable.from = function (iterable, mapFn, thisArg, scheduler) { if (iterable == null) { throw new Error('iterable cannot be null.') } if (mapFn && !isCallable(mapFn)) { throw new Error('mapFn when provided must be a function'); } isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var list = Object(iterable), objIsIterable = isIterable(list), len = objIsIterable ? 0 : toLength(list), it = objIsIterable ? list[$iterator$]() : null, i = 0; return scheduler.scheduleRecursive(function (self) { if (i < len || objIsIterable) { var result; if (objIsIterable) { var next = it.next(); if (next.done) { observer.onCompleted(); return; } result = next.value; } else { result = list[i]; } if (mapFn && isCallable(mapFn)) { try { result = thisArg ? mapFn.call(thisArg, result, i) : mapFn(result, i); } catch (e) { observer.onError(e); return; } } observer.onNext(result); i++; self(); } else { observer.onCompleted(); } }); }); }; /** * Converts an array to an observable sequence, using an optional scheduler to enumerate the array. * * @example * var res = Rx.Observable.fromArray([1,2,3]); * var res = Rx.Observable.fromArray([1,2,3], Rx.Scheduler.timeout); * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. * @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence. */ var observableFromArray = Observable.fromArray = function (array, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var count = 0, len = array.length; return scheduler.scheduleRecursive(function (self) { if (count < len) { observer.onNext(array[count++]); self(); } else { observer.onCompleted(); } }); }); }; /** * Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }); * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout); * @param {Mixed} initialState Initial state. * @param {Function} condition Condition to terminate generation (upon returning false). * @param {Function} iterate Iteration step function. * @param {Function} resultSelector Selector function for results produced in the sequence. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread. * @returns {Observable} The generated sequence. */ Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var first = true, state = initialState; return scheduler.scheduleRecursive(function (self) { var hasResult, result; try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); if (hasResult) { result = resultSelector(state); } } catch (exception) { observer.onError(exception); return; } if (hasResult) { observer.onNext(result); self(); } else { observer.onCompleted(); } }); }); }; /** * Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins). * @returns {Observable} An observable sequence whose observers will never get called. */ var observableNever = Observable.never = function () { return new AnonymousObservable(function () { return disposableEmpty; }); }; /** * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. * @example * var res = Rx.Observable.of(1,2,3); * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. */ Observable.of = function () { var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } return observableFromArray(args); }; /** * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. * @example * var res = Rx.Observable.of(1,2,3); * @param {Scheduler} scheduler A scheduler to use for scheduling the arguments. * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. */ var observableOf = Observable.ofWithScheduler = function (scheduler) { var len = arguments.length - 1, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i + 1]; } return observableFromArray(args, scheduler); }; /** * Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.range(0, 10); * var res = Rx.Observable.range(0, 10, Rx.Scheduler.timeout); * @param {Number} start The value of the first integer in the sequence. * @param {Number} count The number of sequential integers to generate. * @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread. * @returns {Observable} An observable sequence that contains a range of sequential integral numbers. */ Observable.range = function (start, count, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { return scheduler.scheduleRecursiveWithState(0, function (i, self) { if (i < count) { observer.onNext(start + i); self(i + 1); } else { observer.onCompleted(); } }); }); }; /** * Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.repeat(42); * var res = Rx.Observable.repeat(42, 4); * 3 - res = Rx.Observable.repeat(42, 4, Rx.Scheduler.timeout); * 4 - res = Rx.Observable.repeat(42, null, Rx.Scheduler.timeout); * @param {Mixed} value Element to repeat. * @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely. * @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence that repeats the given element the specified number of times. */ Observable.repeat = function (value, repeatCount, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return observableReturn(value, scheduler).repeat(repeatCount == null ? -1 : repeatCount); }; /** * Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages. * There is an alias called 'just', and 'returnValue' for browsers <IE9. * * @example * var res = Rx.Observable.return(42); * var res = Rx.Observable.return(42, Rx.Scheduler.timeout); * @param {Mixed} value Single element in the resulting observable sequence. * @param {Scheduler} scheduler Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence containing the single specified element. */ var observableReturn = Observable['return'] = Observable.returnValue = Observable.just = function (value, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onNext(value); observer.onCompleted(); }); }); }; /** * Returns an observable sequence that terminates with an exception, using the specified scheduler to send out the single onError message. * There is an alias to this method called 'throwError' for browsers <IE9. * @param {Mixed} exception An object used for the sequence's termination. * @param {Scheduler} scheduler Scheduler to send the exceptional termination call on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} The observable sequence that terminates exceptionally with the specified exception object. */ var observableThrow = Observable['throw'] = Observable.throwException = Observable.throwError = function (exception, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onError(exception); }); }); }; /** * Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime. * @param {Function} resourceFactory Factory function to obtain a resource object. * @param {Function} observableFactory Factory function to obtain an observable sequence that depends on the obtained resource. * @returns {Observable} An observable sequence whose lifetime controls the lifetime of the dependent resource object. */ Observable.using = function (resourceFactory, observableFactory) { return new AnonymousObservable(function (observer) { var disposable = disposableEmpty, resource, source; try { resource = resourceFactory(); resource && (disposable = resource); source = observableFactory(resource); } catch (exception) { return new CompositeDisposable(observableThrow(exception).subscribe(observer), disposable); } return new CompositeDisposable(source.subscribe(observer), disposable); }); }; /** * Propagates the observable sequence or Promise that reacts first. * @param {Observable} rightSource Second observable sequence or Promise. * @returns {Observable} {Observable} An observable sequence that surfaces either of the given sequences, whichever reacted first. */ observableProto.amb = function (rightSource) { var leftSource = this; return new AnonymousObservable(function (observer) { var choice, leftChoice = 'L', rightChoice = 'R', leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable(); isPromise(rightSource) && (rightSource = observableFromPromise(rightSource)); function choiceL() { if (!choice) { choice = leftChoice; rightSubscription.dispose(); } } function choiceR() { if (!choice) { choice = rightChoice; leftSubscription.dispose(); } } leftSubscription.setDisposable(leftSource.subscribe(function (left) { choiceL(); if (choice === leftChoice) { observer.onNext(left); } }, function (err) { choiceL(); if (choice === leftChoice) { observer.onError(err); } }, function () { choiceL(); if (choice === leftChoice) { observer.onCompleted(); } })); rightSubscription.setDisposable(rightSource.subscribe(function (right) { choiceR(); if (choice === rightChoice) { observer.onNext(right); } }, function (err) { choiceR(); if (choice === rightChoice) { observer.onError(err); } }, function () { choiceR(); if (choice === rightChoice) { observer.onCompleted(); } })); return new CompositeDisposable(leftSubscription, rightSubscription); }); }; /** * Propagates the observable sequence or Promise that reacts first. * * @example * var = Rx.Observable.amb(xs, ys, zs); * @returns {Observable} An observable sequence that surfaces any of the given sequences, whichever reacted first. */ Observable.amb = function () { var acc = observableNever(), items = argsOrArray(arguments, 0); function func(previous, current) { return previous.amb(current); } for (var i = 0, len = items.length; i < len; i++) { acc = func(acc, items[i]); } return acc; }; function observableCatchHandler(source, handler) { return new AnonymousObservable(function (observer) { var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable(); subscription.setDisposable(d1); d1.setDisposable(source.subscribe(observer.onNext.bind(observer), function (exception) { var d, result; try { result = handler(exception); } catch (ex) { observer.onError(ex); return; } isPromise(result) && (result = observableFromPromise(result)); d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(result.subscribe(observer)); }, observer.onCompleted.bind(observer))); return subscription; }); } /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * @example * 1 - xs.catchException(ys) * 2 - xs.catchException(function (ex) { return ys(ex); }) * @param {Mixed} handlerOrSecond Exception handler function that returns an observable sequence given the error that occurred in the first sequence, or a second observable sequence used to produce results when an error occurred in the first sequence. * @returns {Observable} An observable sequence containing the first sequence's elements, followed by the elements of the handler sequence in case an exception occurred. */ observableProto['catch'] = observableProto.catchError = observableProto.catchException = function (handlerOrSecond) { return typeof handlerOrSecond === 'function' ? observableCatchHandler(this, handlerOrSecond) : observableCatch([this, handlerOrSecond]); }; /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * @param {Array | Arguments} args Arguments or an array to use as the next sequence if an error occurs. * @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully. */ var observableCatch = Observable.catchException = Observable.catchError = Observable['catch'] = function () { return enumerableOf(argsOrArray(arguments, 0)).catchException(); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element. * This can be in the form of an argument list of observables or an array. * * @example * 1 - obs = observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ observableProto.combineLatest = function () { var args = slice.call(arguments); if (Array.isArray(args[0])) { args[0].unshift(this); } else { args.unshift(this); } return combineLatest.apply(this, args); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element. * * @example * 1 - obs = Rx.Observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = Rx.Observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ var combineLatest = Observable.combineLatest = function () { var args = slice.call(arguments), resultSelector = args.pop(); if (Array.isArray(args[0])) { args = args[0]; } return new AnonymousObservable(function (observer) { var falseFactory = function () { return false; }, n = args.length, hasValue = arrayInitialize(n, falseFactory), hasValueAll = false, isDone = arrayInitialize(n, falseFactory), values = new Array(n); function next(i) { var res; hasValue[i] = true; if (hasValueAll || (hasValueAll = hasValue.every(identity))) { try { res = resultSelector.apply(null, values); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); } } function done (i) { isDone[i] = true; if (isDone.every(identity)) { observer.onCompleted(); } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { var source = args[i], sad = new SingleAssignmentDisposable(); isPromise(source) && (source = observableFromPromise(source)); sad.setDisposable(source.subscribe(function (x) { values[i] = x; next(i); }, observer.onError.bind(observer), function () { done(i); })); subscriptions[i] = sad; }(idx)); } return new CompositeDisposable(subscriptions); }); }; /** * Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate. * * @example * 1 - concatenated = xs.concat(ys, zs); * 2 - concatenated = xs.concat([ys, zs]); * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ observableProto.concat = function () { var items = slice.call(arguments, 0); items.unshift(this); return observableConcat.apply(this, items); }; /** * Concatenates all the observable sequences. * @param {Array | Arguments} args Arguments or an array to concat to the observable sequence. * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ var observableConcat = Observable.concat = function () { return enumerableOf(argsOrArray(arguments, 0)).concat(); }; /** * Concatenates an observable sequence of observable sequences. * @returns {Observable} An observable sequence that contains the elements of each observed inner sequence, in sequential order. */ observableProto.concatObservable = observableProto.concatAll =function () { return this.merge(1); }; /** * Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences. * Or merges two observable sequences into a single observable sequence. * * @example * 1 - merged = sources.merge(1); * 2 - merged = source.merge(otherSource); * @param {Mixed} [maxConcurrentOrOther] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence. * @returns {Observable} The observable sequence that merges the elements of the inner sequences. */ observableProto.merge = function (maxConcurrentOrOther) { if (typeof maxConcurrentOrOther !== 'number') { return observableMerge(this, maxConcurrentOrOther); } var sources = this; return new AnonymousObservable(function (observer) { var activeCount = 0, group = new CompositeDisposable(), isStopped = false, q = []; function subscribe(xs) { var subscription = new SingleAssignmentDisposable(); group.add(subscription); // Check for promises support isPromise(xs) && (xs = observableFromPromise(xs)); subscription.setDisposable(xs.subscribe(observer.onNext.bind(observer), observer.onError.bind(observer), function () { group.remove(subscription); if (q.length > 0) { subscribe(q.shift()); } else { activeCount--; isStopped && activeCount === 0 && observer.onCompleted(); } })); } group.add(sources.subscribe(function (innerSource) { if (activeCount < maxConcurrentOrOther) { activeCount++; subscribe(innerSource); } else { q.push(innerSource); } }, observer.onError.bind(observer), function () { isStopped = true; activeCount === 0 && observer.onCompleted(); })); return group; }); }; /** * Merges all the observable sequences into a single observable sequence. * The scheduler is optional and if not specified, the immediate scheduler is used. * * @example * 1 - merged = Rx.Observable.merge(xs, ys, zs); * 2 - merged = Rx.Observable.merge([xs, ys, zs]); * 3 - merged = Rx.Observable.merge(scheduler, xs, ys, zs); * 4 - merged = Rx.Observable.merge(scheduler, [xs, ys, zs]); * @returns {Observable} The observable sequence that merges the elements of the observable sequences. */ var observableMerge = Observable.merge = function () { var scheduler, sources; if (!arguments[0]) { scheduler = immediateScheduler; sources = slice.call(arguments, 1); } else if (arguments[0].now) { scheduler = arguments[0]; sources = slice.call(arguments, 1); } else { scheduler = immediateScheduler; sources = slice.call(arguments, 0); } if (Array.isArray(sources[0])) { sources = sources[0]; } return observableFromArray(sources, scheduler).mergeObservable(); }; /** * Merges an observable sequence of observable sequences into an observable sequence. * @returns {Observable} The observable sequence that merges the elements of the inner sequences. */ observableProto.mergeObservable = observableProto.mergeAll = function () { var sources = this; return new AnonymousObservable(function (observer) { var group = new CompositeDisposable(), isStopped = false, m = new SingleAssignmentDisposable(); group.add(m); m.setDisposable(sources.subscribe(function (innerSource) { var innerSubscription = new SingleAssignmentDisposable(); group.add(innerSubscription); // Check for promises support isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); innerSubscription.setDisposable(innerSource.subscribe(observer.onNext.bind(observer), observer.onError.bind(observer), function () { group.remove(innerSubscription); isStopped && group.length === 1 && observer.onCompleted(); })); }, observer.onError.bind(observer), function () { isStopped = true; group.length === 1 && observer.onCompleted(); })); return group; }); }; /** * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. * @param {Observable} second Second observable sequence used to produce results after the first sequence terminates. * @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally. */ observableProto.onErrorResumeNext = function (second) { if (!second) { throw new Error('Second observable is required'); } return onErrorResumeNext([this, second]); }; /** * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. * * @example * 1 - res = Rx.Observable.onErrorResumeNext(xs, ys, zs); * 1 - res = Rx.Observable.onErrorResumeNext([xs, ys, zs]); * @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally. */ var onErrorResumeNext = Observable.onErrorResumeNext = function () { var sources = argsOrArray(arguments, 0); return new AnonymousObservable(function (observer) { var pos = 0, subscription = new SerialDisposable(), cancelable = immediateScheduler.scheduleRecursive(function (self) { var current, d; if (pos < sources.length) { current = sources[pos++]; isPromise(current) && (current = observableFromPromise(current)); d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(current.subscribe(observer.onNext.bind(observer), self, self)); } else { observer.onCompleted(); } }); return new CompositeDisposable(subscription, cancelable); }); }; /** * Returns the values from the source observable sequence only after the other observable sequence produces a value. * @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence. * @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation. */ observableProto.skipUntil = function (other) { var source = this; return new AnonymousObservable(function (observer) { var isOpen = false; var disposables = new CompositeDisposable(source.subscribe(function (left) { isOpen && observer.onNext(left); }, observer.onError.bind(observer), function () { isOpen && observer.onCompleted(); })); isPromise(other) && (other = observableFromPromise(other)); var rightSubscription = new SingleAssignmentDisposable(); disposables.add(rightSubscription); rightSubscription.setDisposable(other.subscribe(function () { isOpen = true; rightSubscription.dispose(); }, observer.onError.bind(observer), function () { rightSubscription.dispose(); })); return disposables; }); }; /** * Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ observableProto['switch'] = observableProto.switchLatest = function () { var sources = this; return new AnonymousObservable(function (observer) { var hasLatest = false, innerSubscription = new SerialDisposable(), isStopped = false, latest = 0, subscription = sources.subscribe( function (innerSource) { var d = new SingleAssignmentDisposable(), id = ++latest; hasLatest = true; innerSubscription.setDisposable(d); // Check if Promise or Observable isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); d.setDisposable(innerSource.subscribe( function (x) { latest === id && observer.onNext(x); }, function (e) { latest === id && observer.onError(e); }, function () { if (latest === id) { hasLatest = false; isStopped && observer.onCompleted(); } })); }, observer.onError.bind(observer), function () { isStopped = true; !hasLatest && observer.onCompleted(); }); return new CompositeDisposable(subscription, innerSubscription); }); }; /** * Returns the values from the source observable sequence until the other observable sequence produces a value. * @param {Observable | Promise} other Observable sequence or Promise that terminates propagation of elements of the source sequence. * @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. */ observableProto.takeUntil = function (other) { var source = this; return new AnonymousObservable(function (observer) { isPromise(other) && (other = observableFromPromise(other)); return new CompositeDisposable( source.subscribe(observer), other.subscribe(observer.onCompleted.bind(observer), observer.onError.bind(observer), noop) ); }); }; function zipArray(second, resultSelector) { var first = this; return new AnonymousObservable(function (observer) { var index = 0, len = second.length; return first.subscribe(function (left) { if (index < len) { var right = second[index++], result; try { result = resultSelector(left, right); } catch (e) { observer.onError(e); return; } observer.onNext(result); } else { observer.onCompleted(); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); } /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index. * The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the sources. * * @example * 1 - res = obs1.zip(obs2, fn); * 1 - res = x1.zip([1,2,3], fn); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ observableProto.zip = function () { if (Array.isArray(arguments[0])) { return zipArray.apply(this, arguments); } var parent = this, sources = slice.call(arguments), resultSelector = sources.pop(); sources.unshift(parent); return new AnonymousObservable(function (observer) { var n = sources.length, queues = arrayInitialize(n, function () { return []; }), isDone = arrayInitialize(n, function () { return false; }); function next(i) { var res, queuedValues; if (queues.every(function (x) { return x.length > 0; })) { try { queuedValues = queues.map(function (x) { return x.shift(); }); res = resultSelector.apply(parent, queuedValues); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); } }; function done(i) { isDone[i] = true; if (isDone.every(function (x) { return x; })) { observer.onCompleted(); } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { var source = sources[i], sad = new SingleAssignmentDisposable(); isPromise(source) && (source = observableFromPromise(source)); sad.setDisposable(source.subscribe(function (x) { queues[i].push(x); next(i); }, observer.onError.bind(observer), function () { done(i); })); subscriptions[i] = sad; })(idx); } return new CompositeDisposable(subscriptions); }); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. * @param arguments Observable sources. * @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources. * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ Observable.zip = function () { var args = slice.call(arguments, 0), first = args.shift(); return first.zip.apply(first, args); }; /** * Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes. * @param arguments Observable sources. * @returns {Observable} An observable sequence containing lists of elements at corresponding indexes. */ Observable.zipArray = function () { var sources = argsOrArray(arguments, 0); return new AnonymousObservable(function (observer) { var n = sources.length, queues = arrayInitialize(n, function () { return []; }), isDone = arrayInitialize(n, function () { return false; }); function next(i) { if (queues.every(function (x) { return x.length > 0; })) { var res = queues.map(function (x) { return x.shift(); }); observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); return; } }; function done(i) { isDone[i] = true; if (isDone.every(identity)) { observer.onCompleted(); return; } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { subscriptions[i] = new SingleAssignmentDisposable(); subscriptions[i].setDisposable(sources[i].subscribe(function (x) { queues[i].push(x); next(i); }, observer.onError.bind(observer), function () { done(i); })); })(idx); } var compositeDisposable = new CompositeDisposable(subscriptions); compositeDisposable.add(disposableCreate(function () { for (var qIdx = 0, qLen = queues.length; qIdx < qLen; qIdx++) { queues[qIdx] = []; } })); return compositeDisposable; }); }; /** * Hides the identity of an observable sequence. * @returns {Observable} An observable sequence that hides the identity of the source sequence. */ observableProto.asObservable = function () { return new AnonymousObservable(this.subscribe.bind(this)); }; /** * Projects each element of an observable sequence into zero or more buffers which are produced based on element count information. * * @example * var res = xs.bufferWithCount(10); * var res = xs.bufferWithCount(10, 1); * @param {Number} count Length of each buffer. * @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count. * @returns {Observable} An observable sequence of buffers. */ observableProto.bufferWithCount = function (count, skip) { if (typeof skip !== 'number') { skip = count; } return this.windowWithCount(count, skip).selectMany(function (x) { return x.toArray(); }).where(function (x) { return x.length > 0; }); }; /** * Dematerializes the explicit notification values of an observable sequence as implicit notifications. * @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values. */ observableProto.dematerialize = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(function (x) { return x.accept(observer); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer. * * var obs = observable.distinctUntilChanged(); * var obs = observable.distinctUntilChanged(function (x) { return x.id; }); * var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; }); * * @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value. * @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function. * @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence. */ observableProto.distinctUntilChanged = function (keySelector, comparer) { var source = this; keySelector || (keySelector = identity); comparer || (comparer = defaultComparer); return new AnonymousObservable(function (observer) { var hasCurrentKey = false, currentKey; return source.subscribe(function (value) { var comparerEquals = false, key; try { key = keySelector(value); } catch (exception) { observer.onError(exception); return; } if (hasCurrentKey) { try { comparerEquals = comparer(currentKey, key); } catch (exception) { observer.onError(exception); return; } } if (!hasCurrentKey || !comparerEquals) { hasCurrentKey = true; currentKey = key; observer.onNext(value); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function | Observer} observerOrOnNext Action to invoke for each element in the observable sequence or an observer. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto['do'] = observableProto.doAction = observableProto.tap = function (observerOrOnNext, onError, onCompleted) { var source = this, onNextFunc; if (typeof observerOrOnNext === 'function') { onNextFunc = observerOrOnNext; } else { onNextFunc = observerOrOnNext.onNext.bind(observerOrOnNext); onError = observerOrOnNext.onError.bind(observerOrOnNext); onCompleted = observerOrOnNext.onCompleted.bind(observerOrOnNext); } return new AnonymousObservable(function (observer) { return source.subscribe(function (x) { try { onNextFunc(x); } catch (e) { observer.onError(e); } observer.onNext(x); }, function (err) { if (onError) { try { onError(err); } catch (e) { observer.onError(e); } } observer.onError(err); }, function () { if (onCompleted) { try { onCompleted(); } catch (e) { observer.onError(e); } } observer.onCompleted(); }); }); }; /** * Invokes an action for each element in the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function} onNext Action to invoke for each element in the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto.doOnNext = observableProto.tapOnNext = function (onNext, thisArg) { return this.tap(arguments.length === 2 ? function (x) { onNext.call(thisArg, x); } : onNext); }; /** * Invokes an action upon exceptional termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function} onError Action to invoke upon exceptional termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto.doOnError = observableProto.tapOnError = function (onError, thisArg) { return this.tap(noop, arguments.length === 2 ? function (e) { onError.call(thisArg, e); } : onError); }; /** * Invokes an action upon graceful termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function} onCompleted Action to invoke upon graceful termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto.doOnCompleted = observableProto.tapOnCompleted = function (onCompleted, thisArg) { return this.tap(noop, null, arguments.length === 2 ? function () { onCompleted.call(thisArg); } : onCompleted); }; /** * Invokes a specified action after the source observable sequence terminates gracefully or exceptionally. * * @example * var res = observable.finallyAction(function () { console.log('sequence ended'; }); * @param {Function} finallyAction Action to invoke after the source observable sequence terminates. * @returns {Observable} Source sequence with the action-invoking termination behavior applied. */ observableProto['finally'] = observableProto.finallyAction = function (action) { var source = this; return new AnonymousObservable(function (observer) { var subscription; try { subscription = source.subscribe(observer); } catch (e) { action(); throw e; } return disposableCreate(function () { try { subscription.dispose(); } catch (e) { throw e; } finally { action(); } }); }); }; /** * Ignores all elements in an observable sequence leaving only the termination messages. * @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence. */ observableProto.ignoreElements = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(noop, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Materializes the implicit notifications of an observable sequence as explicit notification values. * @returns {Observable} An observable sequence containing the materialized notification values from the source sequence. */ observableProto.materialize = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(function (value) { observer.onNext(notificationCreateOnNext(value)); }, function (e) { observer.onNext(notificationCreateOnError(e)); observer.onCompleted(); }, function () { observer.onNext(notificationCreateOnCompleted()); observer.onCompleted(); }); }); }; /** * Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely. * * @example * var res = repeated = source.repeat(); * var res = repeated = source.repeat(42); * @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely. * @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly. */ observableProto.repeat = function (repeatCount) { return enumerableRepeat(this, repeatCount).concat(); }; /** * Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely. * Note if you encounter an error and want it to retry once, then you must use .retry(2); * * @example * var res = retried = retry.repeat(); * var res = retried = retry.repeat(2); * @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely. * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. */ observableProto.retry = function (retryCount) { return enumerableRepeat(this, retryCount).catchException(); }; /** * Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value. * For aggregation behavior with no intermediate results, see Observable.aggregate. * @example * var res = source.scan(function (acc, x) { return acc + x; }); * var res = source.scan(0, function (acc, x) { return acc + x; }); * @param {Mixed} [seed] The initial accumulator value. * @param {Function} accumulator An accumulator function to be invoked on each element. * @returns {Observable} An observable sequence containing the accumulated values. */ observableProto.scan = function () { var hasSeed = false, seed, accumulator, source = this; if (arguments.length === 2) { hasSeed = true; seed = arguments[0]; accumulator = arguments[1]; } else { accumulator = arguments[0]; } return new AnonymousObservable(function (observer) { var hasAccumulation, accumulation, hasValue; return source.subscribe ( function (x) { !hasValue && (hasValue = true); try { if (hasAccumulation) { accumulation = accumulator(accumulation, x); } else { accumulation = hasSeed ? accumulator(seed, x) : x; hasAccumulation = true; } } catch (e) { observer.onError(e); return; } observer.onNext(accumulation); }, observer.onError.bind(observer), function () { !hasValue && hasSeed && observer.onNext(seed); observer.onCompleted(); } ); }); }; /** * Bypasses a specified number of elements at the end of an observable sequence. * @description * This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are * received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed. * @param count Number of elements to bypass at the end of the source sequence. * @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end. */ observableProto.skipLast = function (count) { var source = this; return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && observer.onNext(q.shift()); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend. * @example * var res = source.startWith(1, 2, 3); * var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3); * @param {Arguments} args The specified values to prepend to the observable sequence * @returns {Observable} The source sequence prepended with the specified values. */ observableProto.startWith = function () { var values, scheduler, start = 0; if (!!arguments.length && isScheduler(arguments[0])) { scheduler = arguments[0]; start = 1; } else { scheduler = immediateScheduler; } values = slice.call(arguments, start); return enumerableOf([observableFromArray(values, scheduler), this]).concat(); }; /** * Returns a specified number of contiguous elements from the end of an observable sequence. * @description * This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of * the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed. * @param {Number} count Number of elements to take from the end of the source sequence. * @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence. */ observableProto.takeLast = function (count) { var source = this; return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && q.shift(); }, observer.onError.bind(observer), function () { while(q.length > 0) { observer.onNext(q.shift()); } observer.onCompleted(); }); }); }; /** * Returns an array with the specified number of contiguous elements from the end of an observable sequence. * * @description * This operator accumulates a buffer with a length enough to store count elements. Upon completion of the * source sequence, this buffer is produced on the result sequence. * @param {Number} count Number of elements to take from the end of the source sequence. * @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence. */ observableProto.takeLastBuffer = function (count) { var source = this; return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && q.shift(); }, observer.onError.bind(observer), function () { observer.onNext(q); observer.onCompleted(); }); }); }; /** * Projects each element of an observable sequence into zero or more windows which are produced based on element count information. * * var res = xs.windowWithCount(10); * var res = xs.windowWithCount(10, 1); * @param {Number} count Length of each window. * @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count. * @returns {Observable} An observable sequence of windows. */ observableProto.windowWithCount = function (count, skip) { var source = this; +count || (count = 0); Math.abs(count) === Infinity && (count = 0); if (count <= 0) { throw new Error(argumentOutOfRange); } skip == null && (skip = count); +skip || (skip = 0); Math.abs(skip) === Infinity && (skip = 0); if (skip <= 0) { throw new Error(argumentOutOfRange); } return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), refCountDisposable = new RefCountDisposable(m), n = 0, q = []; function createWindow () { var s = new Subject(); q.push(s); observer.onNext(addRef(s, refCountDisposable)); } createWindow(); m.setDisposable(source.subscribe( function (x) { for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); } var c = n - count + 1; c >=0 && c % skip === 0 && q.shift().onCompleted(); ++n % skip === 0 && createWindow(); }, function (e) { while (q.length > 0) { q.shift().onError(e); } observer.onError(e); }, function () { while (q.length > 0) { q.shift().onCompleted(); } observer.onCompleted(); } )); return refCountDisposable; }); }; function concatMap(source, selector, thisArg) { return source.map(function (x, i) { var result = selector.call(thisArg, x, i); return isPromise(result) ? observableFromPromise(result) : result; }).concatAll(); } /** * One of the Following: * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * * @example * var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }); * Or: * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. * * var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); * Or: * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. * * var res = source.concatMap(Rx.Observable.fromArray([1,2,3])); * @param selector A transform function to apply to each element or an observable sequence to project each element from the * source sequence onto which could be either an observable or Promise. * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. */ observableProto.selectConcat = observableProto.concatMap = function (selector, resultSelector, thisArg) { if (resultSelector) { return this.concatMap(function (x, i) { var selectorResult = selector(x, i), result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult; return result.map(function (y) { return resultSelector(x, y, i); }); }); } return typeof selector === 'function' ? concatMap(this, selector, thisArg) : concatMap(this, function () { return selector; }); }; /** * Projects each notification of an observable sequence to an observable sequence and concats the resulting observable sequences into one observable sequence. * @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element. * @param {Function} onError A transform function to apply when an error occurs in the source sequence. * @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached. * @param {Any} [thisArg] An optional "this" to use to invoke each transform. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence. */ observableProto.concatMapObserver = observableProto.selectConcatObserver = function(onNext, onError, onCompleted, thisArg) { var source = this; return new AnonymousObservable(function (observer) { var index = 0; return source.subscribe( function (x) { var result; try { result = onNext.call(thisArg, x, index++); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); }, function (err) { var result; try { result = onError.call(thisArg, err); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); observer.onCompleted(); }, function () { var result; try { result = onCompleted.call(thisArg); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); observer.onCompleted(); }); }).concatAll(); }; /** * Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty. * * var res = obs = xs.defaultIfEmpty(); * 2 - obs = xs.defaultIfEmpty(false); * * @memberOf Observable# * @param defaultValue The value to return if the sequence is empty. If not provided, this defaults to null. * @returns {Observable} An observable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself. */ observableProto.defaultIfEmpty = function (defaultValue) { var source = this; if (defaultValue === undefined) { defaultValue = null; } return new AnonymousObservable(function (observer) { var found = false; return source.subscribe(function (x) { found = true; observer.onNext(x); }, observer.onError.bind(observer), function () { if (!found) { observer.onNext(defaultValue); } observer.onCompleted(); }); }); }; // Swap out for Array.findIndex function arrayIndexOfComparer(array, item, comparer) { for (var i = 0, len = array.length; i < len; i++) { if (comparer(array[i], item)) { return i; } } return -1; } function HashSet(comparer) { this.comparer = comparer; this.set = []; } HashSet.prototype.push = function(value) { var retValue = arrayIndexOfComparer(this.set, value, this.comparer) === -1; retValue && this.set.push(value); return retValue; }; /** * Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer. * Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large. * * @example * var res = obs = xs.distinct(); * 2 - obs = xs.distinct(function (x) { return x.id; }); * 2 - obs = xs.distinct(function (x) { return x.id; }, function (a,b) { return a === b; }); * @param {Function} [keySelector] A function to compute the comparison key for each element. * @param {Function} [comparer] Used to compare items in the collection. * @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence. */ observableProto.distinct = function (keySelector, comparer) { var source = this; comparer || (comparer = defaultComparer); return new AnonymousObservable(function (observer) { var hashSet = new HashSet(comparer); return source.subscribe(function (x) { var key = x; if (keySelector) { try { key = keySelector(x); } catch (e) { observer.onError(e); return; } } hashSet.push(key) && observer.onNext(x); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Projects each element of an observable sequence into a new form by incorporating the element's index. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source. */ observableProto.select = observableProto.map = function (selector, thisArg) { var parent = this; return new AnonymousObservable(function (observer) { var count = 0; return parent.subscribe(function (value) { var result; try { result = selector.call(thisArg, value, count++, parent); } catch (e) { observer.onError(e); return; } observer.onNext(result); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Retrieves the value of a specified property from all elements in the Observable sequence. * @param {String} prop The property to pluck. * @returns {Observable} Returns a new Observable sequence of property values. */ observableProto.pluck = function (prop) { return this.map(function (x) { return x[prop]; }); }; /** * Projects each notification of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element. * @param {Function} onError A transform function to apply when an error occurs in the source sequence. * @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached. * @param {Any} [thisArg] An optional "this" to use to invoke each transform. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence. */ observableProto.flatMapObserver = observableProto.selectManyObserver = function (onNext, onError, onCompleted, thisArg) { var source = this; return new AnonymousObservable(function (observer) { var index = 0; return source.subscribe( function (x) { var result; try { result = onNext.call(thisArg, x, index++); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); }, function (err) { var result; try { result = onError.call(thisArg, err); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); observer.onCompleted(); }, function () { var result; try { result = onCompleted.call(thisArg); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); observer.onCompleted(); }); }).mergeAll(); }; function flatMap(source, selector, thisArg) { return source.map(function (x, i) { var result = selector.call(thisArg, x, i); return isPromise(result) ? observableFromPromise(result) : result; }).mergeObservable(); } /** * One of the Following: * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * * @example * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }); * Or: * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. * * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); * Or: * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. * * var res = source.selectMany(Rx.Observable.fromArray([1,2,3])); * @param selector A transform function to apply to each element or an observable sequence to project each element from the * source sequence onto which could be either an observable or Promise. * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. */ observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector, thisArg) { if (resultSelector) { return this.flatMap(function (x, i) { var selectorResult = selector(x, i), result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult; return result.map(function (y) { return resultSelector(x, y, i); }); }, thisArg); } return typeof selector === 'function' ? flatMap(this, selector, thisArg) : flatMap(this, function () { return selector; }); }; /** * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ observableProto.selectSwitch = observableProto.flatMapLatest = observableProto.switchMap = function (selector, thisArg) { return this.select(selector, thisArg).switchLatest(); }; /** * Bypasses a specified number of elements in an observable sequence and then returns the remaining elements. * @param {Number} count The number of elements to skip before returning the remaining elements. * @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence. */ observableProto.skip = function (count) { if (count < 0) { throw new Error(argumentOutOfRange); } var source = this; return new AnonymousObservable(function (observer) { var remaining = count; return source.subscribe(function (x) { if (remaining <= 0) { observer.onNext(x); } else { remaining--; } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements. * The element's index is used in the logic of the predicate function. * * var res = source.skipWhile(function (value) { return value < 10; }); * var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; }); * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. */ observableProto.skipWhile = function (predicate, thisArg) { var source = this; return new AnonymousObservable(function (observer) { var i = 0, running = false; return source.subscribe(function (x) { if (!running) { try { running = !predicate.call(thisArg, x, i++, source); } catch (e) { observer.onError(e); return; } } running && observer.onNext(x); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0). * * var res = source.take(5); * var res = source.take(0, Rx.Scheduler.timeout); * @param {Number} count The number of elements to return. * @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case <paramref name="count count</paramref> is set to 0. * @returns {Observable} An observable sequence that contains the specified number of elements from the start of the input sequence. */ observableProto.take = function (count, scheduler) { if (count < 0) { throw new RangeError(argumentOutOfRange); } if (count === 0) { return observableEmpty(scheduler); } var observable = this; return new AnonymousObservable(function (observer) { var remaining = count; return observable.subscribe(function (x) { if (remaining-- > 0) { observer.onNext(x); remaining === 0 && observer.onCompleted(); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Returns elements from an observable sequence as long as a specified condition is true. * The element's index is used in the logic of the predicate function. * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes. */ observableProto.takeWhile = function (predicate, thisArg) { var observable = this; return new AnonymousObservable(function (observer) { var i = 0, running = true; return observable.subscribe(function (x) { if (running) { try { running = predicate.call(thisArg, x, i++, observable); } catch (e) { observer.onError(e); return; } if (running) { observer.onNext(x); } else { observer.onCompleted(); } } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Filters the elements of an observable sequence based on a predicate by incorporating the element's index. * * @example * var res = source.where(function (value) { return value < 10; }); * var res = source.where(function (value, index) { return value < 10 || index < 10; }); * @param {Function} predicate A function to test each source element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains elements from the input sequence that satisfy the condition. */ observableProto.where = observableProto.filter = function (predicate, thisArg) { var parent = this; return new AnonymousObservable(function (observer) { var count = 0; return parent.subscribe(function (value) { var shouldRun; try { shouldRun = predicate.call(thisArg, value, count++, parent); } catch (e) { observer.onError(e); return; } shouldRun && observer.onNext(value); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /* * Performs a exclusive waiting for the first to finish before subscribing to another observable. * Observables that come in between subscriptions will be dropped on the floor. * @returns {Observable} A exclusive observable with only the results that happen when subscribed. */ observableProto.exclusive = function () { var sources = this; return new AnonymousObservable(function (observer) { var hasCurrent = false, isStopped = false, m = new SingleAssignmentDisposable(), g = new CompositeDisposable(); g.add(m); m.setDisposable(sources.subscribe( function (innerSource) { if (!hasCurrent) { hasCurrent = true; isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); var innerSubscription = new SingleAssignmentDisposable(); g.add(innerSubscription); innerSubscription.setDisposable(innerSource.subscribe( observer.onNext.bind(observer), observer.onError.bind(observer), function () { g.remove(innerSubscription); hasCurrent = false; if (isStopped && g.length === 1) { observer.onCompleted(); } })); } }, observer.onError.bind(observer), function () { isStopped = true; if (!hasCurrent && g.length === 1) { observer.onCompleted(); } })); return g; }); }; /* * Performs a exclusive map waiting for the first to finish before subscribing to another observable. * Observables that come in between subscriptions will be dropped on the floor. * @param {Function} selector Selector to invoke for every item in the current subscription. * @param {Any} [thisArg] An optional context to invoke with the selector parameter. * @returns {Observable} An exclusive observable with only the results that happen when subscribed. */ observableProto.exclusiveMap = function (selector, thisArg) { var sources = this; return new AnonymousObservable(function (observer) { var index = 0, hasCurrent = false, isStopped = true, m = new SingleAssignmentDisposable(), g = new CompositeDisposable(); g.add(m); m.setDisposable(sources.subscribe( function (innerSource) { if (!hasCurrent) { hasCurrent = true; innerSubscription = new SingleAssignmentDisposable(); g.add(innerSubscription); isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); innerSubscription.setDisposable(innerSource.subscribe( function (x) { var result; try { result = selector.call(thisArg, x, index++, innerSource); } catch (e) { observer.onError(e); return; } observer.onNext(result); }, observer.onError.bind(observer), function () { g.remove(innerSubscription); hasCurrent = false; if (isStopped && g.length === 1) { observer.onCompleted(); } })); } }, observer.onError.bind(observer), function () { isStopped = true; if (g.length === 1 && !hasCurrent) { observer.onCompleted(); } })); return g; }); }; var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) { inherits(AnonymousObservable, __super__); // Fix subscriber to check for undefined or function returned to decorate as Disposable function fixSubscriber(subscriber) { if (subscriber && typeof subscriber.dispose === 'function') { return subscriber; } return typeof subscriber === 'function' ? disposableCreate(subscriber) : disposableEmpty; } function AnonymousObservable(subscribe) { if (!(this instanceof AnonymousObservable)) { return new AnonymousObservable(subscribe); } function s(observer) { var setDisposable = function () { try { autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver))); } catch (e) { if (!autoDetachObserver.fail(e)) { throw e; } } }; var autoDetachObserver = new AutoDetachObserver(observer); if (currentThreadScheduler.scheduleRequired()) { currentThreadScheduler.schedule(setDisposable); } else { setDisposable(); } return autoDetachObserver; } __super__.call(this, s); } return AnonymousObservable; }(Observable)); /** @private */ var AutoDetachObserver = (function (_super) { inherits(AutoDetachObserver, _super); function AutoDetachObserver(observer) { _super.call(this); this.observer = observer; this.m = new SingleAssignmentDisposable(); } var AutoDetachObserverPrototype = AutoDetachObserver.prototype; AutoDetachObserverPrototype.next = function (value) { var noError = false; try { this.observer.onNext(value); noError = true; } catch (e) { throw e; } finally { if (!noError) { this.dispose(); } } }; AutoDetachObserverPrototype.error = function (exn) { try { this.observer.onError(exn); } catch (e) { throw e; } finally { this.dispose(); } }; AutoDetachObserverPrototype.completed = function () { try { this.observer.onCompleted(); } catch (e) { throw e; } finally { this.dispose(); } }; AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); }; AutoDetachObserverPrototype.getDisposable = function (value) { return this.m.getDisposable(); }; /* @private */ AutoDetachObserverPrototype.disposable = function (value) { return arguments.length ? this.getDisposable() : setDisposable(value); }; AutoDetachObserverPrototype.dispose = function () { _super.prototype.dispose.call(this); this.m.dispose(); }; return AutoDetachObserver; }(AbstractObserver)); /** @private */ var InnerSubscription = function (subject, observer) { this.subject = subject; this.observer = observer; }; /** * @private * @memberOf InnerSubscription */ InnerSubscription.prototype.dispose = function () { if (!this.subject.isDisposed && this.observer !== null) { var idx = this.subject.observers.indexOf(this.observer); this.subject.observers.splice(idx, 1); this.observer = null; } }; /** * Represents an object that is both an observable sequence as well as an observer. * Each notification is broadcasted to all subscribed observers. */ var Subject = Rx.Subject = (function (_super) { function subscribe(observer) { checkDisposed.call(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } if (this.exception) { observer.onError(this.exception); return disposableEmpty; } observer.onCompleted(); return disposableEmpty; } inherits(Subject, _super); /** * Creates a subject. * @constructor */ function Subject() { _super.call(this, subscribe); this.isDisposed = false, this.isStopped = false, this.observers = []; } addProperties(Subject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; for (var i = 0, len = os.length; i < len; i++) { os[i].onCompleted(); } this.observers = []; } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (exception) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; this.exception = exception; for (var i = 0, len = os.length; i < len; i++) { os[i].onError(exception); } this.observers = []; } }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); for (var i = 0, len = os.length; i < len; i++) { os[i].onNext(value); } } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; } }); /** * Creates a subject from the specified observer and observable. * @param {Observer} observer The observer used to send messages to the subject. * @param {Observable} observable The observable used to subscribe to messages sent from the subject. * @returns {Subject} Subject implemented using the given observer and observable. */ Subject.create = function (observer, observable) { return new AnonymousSubject(observer, observable); }; return Subject; }(Observable)); /** * Represents the result of an asynchronous operation. * The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers. */ var AsyncSubject = Rx.AsyncSubject = (function (__super__) { function subscribe(observer) { checkDisposed.call(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } var ex = this.exception, hv = this.hasValue, v = this.value; if (ex) { observer.onError(ex); } else if (hv) { observer.onNext(v); observer.onCompleted(); } else { observer.onCompleted(); } return disposableEmpty; } inherits(AsyncSubject, __super__); /** * Creates a subject that can only receive one value and that value is cached for all future observations. * @constructor */ function AsyncSubject() { __super__.call(this, subscribe); this.isDisposed = false; this.isStopped = false; this.value = null; this.hasValue = false; this.observers = []; this.exception = null; } addProperties(AsyncSubject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { checkDisposed.call(this); return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any). */ onCompleted: function () { var o, i, len; checkDisposed.call(this); if (!this.isStopped) { this.isStopped = true; var os = this.observers.slice(0), v = this.value, hv = this.hasValue; if (hv) { for (i = 0, len = os.length; i < len; i++) { o = os[i]; o.onNext(v); o.onCompleted(); } } else { for (i = 0, len = os.length; i < len; i++) { os[i].onCompleted(); } } this.observers = []; } }, /** * Notifies all subscribed observers about the error. * @param {Mixed} error The Error to send to all observers. */ onError: function (error) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; this.exception = error; for (var i = 0, len = os.length; i < len; i++) { os[i].onError(error); } this.observers = []; } }, /** * Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers. * @param {Mixed} value The value to store in the subject. */ onNext: function (value) { checkDisposed.call(this); if (this.isStopped) { return; } this.value = value; this.hasValue = true; }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; this.exception = null; this.value = null; } }); return AsyncSubject; }(Observable)); var AnonymousSubject = Rx.AnonymousSubject = (function (__super__) { inherits(AnonymousSubject, __super__); function AnonymousSubject(observer, observable) { this.observer = observer; this.observable = observable; __super__.call(this, this.observable.subscribe.bind(this.observable)); } addProperties(AnonymousSubject.prototype, Observer, { onCompleted: function () { this.observer.onCompleted(); }, onError: function (exception) { this.observer.onError(exception); }, onNext: function (value) { this.observer.onNext(value); } }); return AnonymousSubject; }(Observable)); if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { root.Rx = Rx; define(function() { return Rx; }); } else if (freeExports && freeModule) { // in Node.js or RingoJS if (moduleExports) { (freeModule.exports = Rx).Rx = Rx; } else { freeExports.Rx = Rx; } } else { // in a browser or Rhino root.Rx = Rx; } }.call(this));
frontend/Article 3/src/index.js
thebillkidy/TodoListFluxReactHapi
import React from 'react'; import routes from './routes'; // Install the routes React.render(routes, document.body);
packages/material-ui/src/OutlinedInput/OutlinedInput.js
kybarg/material-ui
import React from 'react'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import { refType } from '@material-ui/utils'; import InputBase from '../InputBase'; import NotchedOutline from './NotchedOutline'; import withStyles from '../styles/withStyles'; export const styles = theme => { const borderColor = theme.palette.type === 'light' ? 'rgba(0, 0, 0, 0.23)' : 'rgba(255, 255, 255, 0.23)'; return { /* Styles applied to the root element. */ root: { position: 'relative', '&:hover $notchedOutline': { borderColor: theme.palette.text.primary, }, // Reset on touch devices, it doesn't add specificity '@media (hover: none)': { '&:hover $notchedOutline': { borderColor, }, }, '&$focused $notchedOutline': { borderColor: theme.palette.primary.main, borderWidth: 2, }, '&$error $notchedOutline': { borderColor: theme.palette.error.main, }, '&$disabled $notchedOutline': { borderColor: theme.palette.action.disabled, }, }, /* Styles applied to the root element if the component is focused. */ focused: {}, /* Styles applied to the root element if `disabled={true}`. */ disabled: {}, /* Styles applied to the root element if `startAdornment` is provided. */ adornedStart: { paddingLeft: 14, }, /* Styles applied to the root element if `endAdornment` is provided. */ adornedEnd: { paddingRight: 14, }, /* Styles applied to the root element if `error={true}`. */ error: {}, /* Styles applied to the `input` element if `margin="dense"`. */ marginDense: {}, /* Styles applied to the root element if `multiline={true}`. */ multiline: { padding: '18.5px 14px', '&$marginDense': { paddingTop: 10.5, paddingBottom: 10.5, }, }, /* Styles applied to the `NotchedOutline` element. */ notchedOutline: { borderColor, }, /* Styles applied to the `input` element. */ input: { padding: '18.5px 14px', }, /* Styles applied to the `input` element if `margin="dense"`. */ inputMarginDense: { paddingTop: 10.5, paddingBottom: 10.5, }, /* Styles applied to the `input` element if `select={true}`. */ inputSelect: { paddingRight: 24, }, /* Styles applied to the `input` element if `multiline={true}`. */ inputMultiline: { padding: 0, }, /* Styles applied to the `input` element if `startAdornment` is provided. */ inputAdornedStart: { paddingLeft: 0, }, /* Styles applied to the `input` element if `endAdornment` is provided. */ inputAdornedEnd: { paddingRight: 0, }, }; }; const OutlinedInput = React.forwardRef(function OutlinedInput(props, ref) { const { classes, fullWidth = false, inputComponent = 'input', labelWidth = 0, multiline = false, notched, type = 'text', ...other } = props; return ( <InputBase renderSuffix={state => ( <NotchedOutline className={classes.notchedOutline} labelWidth={labelWidth} notched={ typeof notched !== 'undefined' ? notched : Boolean(state.startAdornment || state.filled || state.focused) } /> )} classes={{ ...classes, root: clsx(classes.root, classes.underline), notchedOutline: null, }} fullWidth={fullWidth} inputComponent={inputComponent} multiline={multiline} ref={ref} type={type} {...other} /> ); }); OutlinedInput.propTypes = { /** * This prop helps users to fill forms faster, especially on mobile devices. * The name can be confusing, as it's more like an autofill. * You can learn more about it [following the specification](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofill). */ autoComplete: PropTypes.string, /** * If `true`, the `input` element will be focused during the first mount. */ autoFocus: PropTypes.bool, /** * Override or extend the styles applied to the component. * See [CSS API](#css) below for more details. */ classes: PropTypes.object.isRequired, /** * The CSS class name of the wrapper element. */ className: PropTypes.string, /** * The default `input` element value. Use when the component is not controlled. */ defaultValue: PropTypes.any, /** * If `true`, the `input` element will be disabled. */ disabled: PropTypes.bool, /** * End `InputAdornment` for this component. */ endAdornment: PropTypes.node, /** * If `true`, the input will indicate an error. This is normally obtained via context from * FormControl. */ error: PropTypes.bool, /** * If `true`, the input will take up the full width of its container. */ fullWidth: PropTypes.bool, /** * The id of the `input` element. */ id: PropTypes.string, /** * The component used for the native input. * Either a string to use a DOM element or a component. */ inputComponent: PropTypes.elementType, /** * [Attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Attributes) applied to the `input` element. */ inputProps: PropTypes.object, /** * Pass a ref to the `input` element. */ inputRef: refType, /** * The width of the label. */ labelWidth: PropTypes.number, /** * If `dense`, will adjust vertical spacing. This is normally obtained via context from * FormControl. */ margin: PropTypes.oneOf(['dense', 'none']), /** * If `true`, a textarea element will be rendered. */ multiline: PropTypes.bool, /** * Name attribute of the `input` element. */ name: PropTypes.string, /** * If `true`, the outline is notched to accommodate the label. */ notched: PropTypes.bool, /** * Callback fired when the value is changed. * * @param {object} event The event source of the callback. * You can pull out the new value by accessing `event.target.value` (string). */ onChange: PropTypes.func, /** * The short hint displayed in the input before the user enters a value. */ placeholder: PropTypes.string, /** * It prevents the user from changing the value of the field * (not from interacting with the field). */ readOnly: PropTypes.bool, /** * If `true`, the `input` element will be required. */ required: PropTypes.bool, /** * Number of rows to display when multiline option is set to true. */ rows: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), /** * Maximum number of rows to display when multiline option is set to true. */ rowsMax: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), /** * Start `InputAdornment` for this component. */ startAdornment: PropTypes.node, /** * Type of the `input` element. It should be [a valid HTML5 input type](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Form_%3Cinput%3E_types). */ type: PropTypes.string, /** * The value of the `input` element, required for a controlled component. */ value: PropTypes.any, }; OutlinedInput.muiName = 'Input'; export default withStyles(styles, { name: 'MuiOutlinedInput' })(OutlinedInput);
src/react-image-lightbox.js
fritz-c/react-image-lightbox
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Modal from 'react-modal'; import { translate, getWindowWidth, getWindowHeight, getHighestSafeWindowContext, } from './util'; import { KEYS, MIN_ZOOM_LEVEL, MAX_ZOOM_LEVEL, ZOOM_RATIO, WHEEL_MOVE_X_THRESHOLD, WHEEL_MOVE_Y_THRESHOLD, ZOOM_BUTTON_INCREMENT_SIZE, ACTION_NONE, ACTION_MOVE, ACTION_SWIPE, ACTION_PINCH, SOURCE_ANY, SOURCE_MOUSE, SOURCE_TOUCH, SOURCE_POINTER, MIN_SWIPE_DISTANCE, } from './constant'; import './style.css'; class ReactImageLightbox extends Component { static isTargetMatchImage(target) { return target && /ril-image-current/.test(target.className); } static parseMouseEvent(mouseEvent) { return { id: 'mouse', source: SOURCE_MOUSE, x: parseInt(mouseEvent.clientX, 10), y: parseInt(mouseEvent.clientY, 10), }; } static parseTouchPointer(touchPointer) { return { id: touchPointer.identifier, source: SOURCE_TOUCH, x: parseInt(touchPointer.clientX, 10), y: parseInt(touchPointer.clientY, 10), }; } static parsePointerEvent(pointerEvent) { return { id: pointerEvent.pointerId, source: SOURCE_POINTER, x: parseInt(pointerEvent.clientX, 10), y: parseInt(pointerEvent.clientY, 10), }; } // Request to transition to the previous image static getTransform({ x = 0, y = 0, zoom = 1, width, targetWidth }) { let nextX = x; const windowWidth = getWindowWidth(); if (width > windowWidth) { nextX += (windowWidth - width) / 2; } const scaleFactor = zoom * (targetWidth / width); return { transform: `translate3d(${nextX}px,${y}px,0) scale3d(${scaleFactor},${scaleFactor},1)`, }; } constructor(props) { super(props); this.state = { //----------------------------- // Animation //----------------------------- // Lightbox is closing // When Lightbox is mounted, if animation is enabled it will open with the reverse of the closing animation isClosing: !props.animationDisabled, // Component parts should animate (e.g., when images are moving, or image is being zoomed) shouldAnimate: false, //----------------------------- // Zoom settings //----------------------------- // Zoom level of image zoomLevel: MIN_ZOOM_LEVEL, //----------------------------- // Image position settings //----------------------------- // Horizontal offset from center offsetX: 0, // Vertical offset from center offsetY: 0, // image load error for srcType loadErrorStatus: {}, }; // Refs this.outerEl = React.createRef(); this.zoomInBtn = React.createRef(); this.zoomOutBtn = React.createRef(); this.caption = React.createRef(); this.closeIfClickInner = this.closeIfClickInner.bind(this); this.handleImageDoubleClick = this.handleImageDoubleClick.bind(this); this.handleImageMouseWheel = this.handleImageMouseWheel.bind(this); this.handleKeyInput = this.handleKeyInput.bind(this); this.handleMouseUp = this.handleMouseUp.bind(this); this.handleMouseDown = this.handleMouseDown.bind(this); this.handleMouseMove = this.handleMouseMove.bind(this); this.handleOuterMousewheel = this.handleOuterMousewheel.bind(this); this.handleTouchStart = this.handleTouchStart.bind(this); this.handleTouchMove = this.handleTouchMove.bind(this); this.handleTouchEnd = this.handleTouchEnd.bind(this); this.handlePointerEvent = this.handlePointerEvent.bind(this); this.handleCaptionMousewheel = this.handleCaptionMousewheel.bind(this); this.handleWindowResize = this.handleWindowResize.bind(this); this.handleZoomInButtonClick = this.handleZoomInButtonClick.bind(this); this.handleZoomOutButtonClick = this.handleZoomOutButtonClick.bind(this); this.requestClose = this.requestClose.bind(this); this.requestMoveNext = this.requestMoveNext.bind(this); this.requestMovePrev = this.requestMovePrev.bind(this); } // eslint-disable-next-line camelcase UNSAFE_componentWillMount() { // Timeouts - always clear it before umount this.timeouts = []; // Current action this.currentAction = ACTION_NONE; // Events source this.eventsSource = SOURCE_ANY; // Empty pointers list this.pointerList = []; // Prevent inner close this.preventInnerClose = false; this.preventInnerCloseTimeout = null; // Used to disable animation when changing props.mainSrc|nextSrc|prevSrc this.keyPressed = false; // Used to store load state / dimensions of images this.imageCache = {}; // Time the last keydown event was called (used in keyboard action rate limiting) this.lastKeyDownTime = 0; // Used for debouncing window resize event this.resizeTimeout = null; // Used to determine when actions are triggered by the scroll wheel this.wheelActionTimeout = null; this.resetScrollTimeout = null; this.scrollX = 0; this.scrollY = 0; // Used in panning zoomed images this.moveStartX = 0; this.moveStartY = 0; this.moveStartOffsetX = 0; this.moveStartOffsetY = 0; // Used to swipe this.swipeStartX = 0; this.swipeStartY = 0; this.swipeEndX = 0; this.swipeEndY = 0; // Used to pinch this.pinchTouchList = null; this.pinchDistance = 0; // Used to differentiate between images with identical src this.keyCounter = 0; // Used to detect a move when all src's remain unchanged (four or more of the same image in a row) this.moveRequested = false; if (!this.props.animationDisabled) { // Make opening animation play this.setState({ isClosing: false }); } } componentDidMount() { // Prevents cross-origin errors when using a cross-origin iframe this.windowContext = getHighestSafeWindowContext(); this.listeners = { resize: this.handleWindowResize, mouseup: this.handleMouseUp, touchend: this.handleTouchEnd, touchcancel: this.handleTouchEnd, pointerdown: this.handlePointerEvent, pointermove: this.handlePointerEvent, pointerup: this.handlePointerEvent, pointercancel: this.handlePointerEvent, }; Object.keys(this.listeners).forEach(type => { this.windowContext.addEventListener(type, this.listeners[type]); }); this.loadAllImages(); } // eslint-disable-next-line camelcase UNSAFE_componentWillReceiveProps(nextProps) { // Iterate through the source types for prevProps and nextProps to // determine if any of the sources changed let sourcesChanged = false; const prevSrcDict = {}; const nextSrcDict = {}; this.getSrcTypes().forEach(srcType => { if (this.props[srcType.name] !== nextProps[srcType.name]) { sourcesChanged = true; prevSrcDict[this.props[srcType.name]] = true; nextSrcDict[nextProps[srcType.name]] = true; } }); if (sourcesChanged || this.moveRequested) { // Reset the loaded state for images not rendered next Object.keys(prevSrcDict).forEach(prevSrc => { if (!(prevSrc in nextSrcDict) && prevSrc in this.imageCache) { this.imageCache[prevSrc].loaded = false; } }); this.moveRequested = false; // Load any new images this.loadAllImages(nextProps); } } shouldComponentUpdate() { // Wait for move... return !this.moveRequested; } componentWillUnmount() { this.didUnmount = true; Object.keys(this.listeners).forEach(type => { this.windowContext.removeEventListener(type, this.listeners[type]); }); this.timeouts.forEach(tid => clearTimeout(tid)); } setTimeout(func, time) { const id = setTimeout(() => { this.timeouts = this.timeouts.filter(tid => tid !== id); func(); }, time); this.timeouts.push(id); return id; } setPreventInnerClose() { if (this.preventInnerCloseTimeout) { this.clearTimeout(this.preventInnerCloseTimeout); } this.preventInnerClose = true; this.preventInnerCloseTimeout = this.setTimeout(() => { this.preventInnerClose = false; this.preventInnerCloseTimeout = null; }, 100); } // Get info for the best suited image to display with the given srcType getBestImageForType(srcType) { let imageSrc = this.props[srcType]; let fitSizes = {}; if (this.isImageLoaded(imageSrc)) { // Use full-size image if available fitSizes = this.getFitSizes( this.imageCache[imageSrc].width, this.imageCache[imageSrc].height ); } else if (this.isImageLoaded(this.props[`${srcType}Thumbnail`])) { // Fall back to using thumbnail if the image has not been loaded imageSrc = this.props[`${srcType}Thumbnail`]; fitSizes = this.getFitSizes( this.imageCache[imageSrc].width, this.imageCache[imageSrc].height, true ); } else { return null; } return { src: imageSrc, height: this.imageCache[imageSrc].height, width: this.imageCache[imageSrc].width, targetHeight: fitSizes.height, targetWidth: fitSizes.width, }; } // Get sizing for when an image is larger than the window getFitSizes(width, height, stretch) { const boxSize = this.getLightboxRect(); let maxHeight = boxSize.height - this.props.imagePadding * 2; let maxWidth = boxSize.width - this.props.imagePadding * 2; if (!stretch) { maxHeight = Math.min(maxHeight, height); maxWidth = Math.min(maxWidth, width); } const maxRatio = maxWidth / maxHeight; const srcRatio = width / height; if (maxRatio > srcRatio) { // height is the constraining dimension of the photo return { width: (width * maxHeight) / height, height: maxHeight, }; } return { width: maxWidth, height: (height * maxWidth) / width, }; } getMaxOffsets(zoomLevel = this.state.zoomLevel) { const currentImageInfo = this.getBestImageForType('mainSrc'); if (currentImageInfo === null) { return { maxX: 0, minX: 0, maxY: 0, minY: 0 }; } const boxSize = this.getLightboxRect(); const zoomMultiplier = this.getZoomMultiplier(zoomLevel); let maxX = 0; if (zoomMultiplier * currentImageInfo.width - boxSize.width < 0) { // if there is still blank space in the X dimension, don't limit except to the opposite edge maxX = (boxSize.width - zoomMultiplier * currentImageInfo.width) / 2; } else { maxX = (zoomMultiplier * currentImageInfo.width - boxSize.width) / 2; } let maxY = 0; if (zoomMultiplier * currentImageInfo.height - boxSize.height < 0) { // if there is still blank space in the Y dimension, don't limit except to the opposite edge maxY = (boxSize.height - zoomMultiplier * currentImageInfo.height) / 2; } else { maxY = (zoomMultiplier * currentImageInfo.height - boxSize.height) / 2; } return { maxX, maxY, minX: -1 * maxX, minY: -1 * maxY, }; } // Get image src types getSrcTypes() { return [ { name: 'mainSrc', keyEnding: `i${this.keyCounter}`, }, { name: 'mainSrcThumbnail', keyEnding: `t${this.keyCounter}`, }, { name: 'nextSrc', keyEnding: `i${this.keyCounter + 1}`, }, { name: 'nextSrcThumbnail', keyEnding: `t${this.keyCounter + 1}`, }, { name: 'prevSrc', keyEnding: `i${this.keyCounter - 1}`, }, { name: 'prevSrcThumbnail', keyEnding: `t${this.keyCounter - 1}`, }, ]; } /** * Get sizing when the image is scaled */ getZoomMultiplier(zoomLevel = this.state.zoomLevel) { return ZOOM_RATIO ** zoomLevel; } /** * Get the size of the lightbox in pixels */ getLightboxRect() { if (this.outerEl.current) { return this.outerEl.current.getBoundingClientRect(); } return { width: getWindowWidth(), height: getWindowHeight(), top: 0, right: 0, bottom: 0, left: 0, }; } clearTimeout(id) { this.timeouts = this.timeouts.filter(tid => tid !== id); clearTimeout(id); } // Change zoom level changeZoom(zoomLevel, clientX, clientY) { // Ignore if zoom disabled if (!this.props.enableZoom) { return; } // Constrain zoom level to the set bounds const nextZoomLevel = Math.max( MIN_ZOOM_LEVEL, Math.min(MAX_ZOOM_LEVEL, zoomLevel) ); // Ignore requests that don't change the zoom level if (nextZoomLevel === this.state.zoomLevel) { return; } if (nextZoomLevel === MIN_ZOOM_LEVEL) { // Snap back to center if zoomed all the way out this.setState({ zoomLevel: nextZoomLevel, offsetX: 0, offsetY: 0, }); return; } const imageBaseSize = this.getBestImageForType('mainSrc'); if (imageBaseSize === null) { return; } const currentZoomMultiplier = this.getZoomMultiplier(); const nextZoomMultiplier = this.getZoomMultiplier(nextZoomLevel); // Default to the center of the image to zoom when no mouse position specified const boxRect = this.getLightboxRect(); const pointerX = typeof clientX !== 'undefined' ? clientX - boxRect.left : boxRect.width / 2; const pointerY = typeof clientY !== 'undefined' ? clientY - boxRect.top : boxRect.height / 2; const currentImageOffsetX = (boxRect.width - imageBaseSize.width * currentZoomMultiplier) / 2; const currentImageOffsetY = (boxRect.height - imageBaseSize.height * currentZoomMultiplier) / 2; const currentImageRealOffsetX = currentImageOffsetX - this.state.offsetX; const currentImageRealOffsetY = currentImageOffsetY - this.state.offsetY; const currentPointerXRelativeToImage = (pointerX - currentImageRealOffsetX) / currentZoomMultiplier; const currentPointerYRelativeToImage = (pointerY - currentImageRealOffsetY) / currentZoomMultiplier; const nextImageRealOffsetX = pointerX - currentPointerXRelativeToImage * nextZoomMultiplier; const nextImageRealOffsetY = pointerY - currentPointerYRelativeToImage * nextZoomMultiplier; const nextImageOffsetX = (boxRect.width - imageBaseSize.width * nextZoomMultiplier) / 2; const nextImageOffsetY = (boxRect.height - imageBaseSize.height * nextZoomMultiplier) / 2; let nextOffsetX = nextImageOffsetX - nextImageRealOffsetX; let nextOffsetY = nextImageOffsetY - nextImageRealOffsetY; // When zooming out, limit the offset so things don't get left askew if (this.currentAction !== ACTION_PINCH) { const maxOffsets = this.getMaxOffsets(); if (this.state.zoomLevel > nextZoomLevel) { nextOffsetX = Math.max( maxOffsets.minX, Math.min(maxOffsets.maxX, nextOffsetX) ); nextOffsetY = Math.max( maxOffsets.minY, Math.min(maxOffsets.maxY, nextOffsetY) ); } } this.setState({ zoomLevel: nextZoomLevel, offsetX: nextOffsetX, offsetY: nextOffsetY, }); } closeIfClickInner(event) { if ( !this.preventInnerClose && event.target.className.search(/\bril-inner\b/) > -1 ) { this.requestClose(event); } } /** * Handle user keyboard actions */ handleKeyInput(event) { event.stopPropagation(); // Ignore key input during animations if (this.isAnimating()) { return; } // Allow slightly faster navigation through the images when user presses keys repeatedly if (event.type === 'keyup') { this.lastKeyDownTime -= this.props.keyRepeatKeyupBonus; return; } const keyCode = event.which || event.keyCode; // Ignore key presses that happen too close to each other (when rapid fire key pressing or holding down the key) // But allow it if it's a lightbox closing action const currentTime = new Date(); if ( currentTime.getTime() - this.lastKeyDownTime < this.props.keyRepeatLimit && keyCode !== KEYS.ESC ) { return; } this.lastKeyDownTime = currentTime.getTime(); switch (keyCode) { // ESC key closes the lightbox case KEYS.ESC: event.preventDefault(); this.requestClose(event); break; // Left arrow key moves to previous image case KEYS.LEFT_ARROW: if (!this.props.prevSrc) { return; } event.preventDefault(); this.keyPressed = true; this.requestMovePrev(event); break; // Right arrow key moves to next image case KEYS.RIGHT_ARROW: if (!this.props.nextSrc) { return; } event.preventDefault(); this.keyPressed = true; this.requestMoveNext(event); break; default: } } /** * Handle a mouse wheel event over the lightbox container */ handleOuterMousewheel(event) { // Prevent scrolling of the background event.stopPropagation(); const xThreshold = WHEEL_MOVE_X_THRESHOLD; let actionDelay = 0; const imageMoveDelay = 500; this.clearTimeout(this.resetScrollTimeout); this.resetScrollTimeout = this.setTimeout(() => { this.scrollX = 0; this.scrollY = 0; }, 300); // Prevent rapid-fire zoom behavior if (this.wheelActionTimeout !== null || this.isAnimating()) { return; } if (Math.abs(event.deltaY) < Math.abs(event.deltaX)) { // handle horizontal scrolls with image moves this.scrollY = 0; this.scrollX += event.deltaX; const bigLeapX = xThreshold / 2; // If the scroll amount has accumulated sufficiently, or a large leap was taken if (this.scrollX >= xThreshold || event.deltaX >= bigLeapX) { // Scroll right moves to next this.requestMoveNext(event); actionDelay = imageMoveDelay; this.scrollX = 0; } else if ( this.scrollX <= -1 * xThreshold || event.deltaX <= -1 * bigLeapX ) { // Scroll left moves to previous this.requestMovePrev(event); actionDelay = imageMoveDelay; this.scrollX = 0; } } // Allow successive actions after the set delay if (actionDelay !== 0) { this.wheelActionTimeout = this.setTimeout(() => { this.wheelActionTimeout = null; }, actionDelay); } } handleImageMouseWheel(event) { const yThreshold = WHEEL_MOVE_Y_THRESHOLD; if (Math.abs(event.deltaY) >= Math.abs(event.deltaX)) { event.stopPropagation(); // If the vertical scroll amount was large enough, perform a zoom if (Math.abs(event.deltaY) < yThreshold) { return; } this.scrollX = 0; this.scrollY += event.deltaY; this.changeZoom( this.state.zoomLevel - event.deltaY, event.clientX, event.clientY ); } } /** * Handle a double click on the current image */ handleImageDoubleClick(event) { if (this.state.zoomLevel > MIN_ZOOM_LEVEL) { // A double click when zoomed in zooms all the way out this.changeZoom(MIN_ZOOM_LEVEL, event.clientX, event.clientY); } else { // A double click when zoomed all the way out zooms in this.changeZoom( this.state.zoomLevel + ZOOM_BUTTON_INCREMENT_SIZE, event.clientX, event.clientY ); } } shouldHandleEvent(source) { if (this.eventsSource === source) { return true; } if (this.eventsSource === SOURCE_ANY) { this.eventsSource = source; return true; } switch (source) { case SOURCE_MOUSE: return false; case SOURCE_TOUCH: this.eventsSource = SOURCE_TOUCH; this.filterPointersBySource(); return true; case SOURCE_POINTER: if (this.eventsSource === SOURCE_MOUSE) { this.eventsSource = SOURCE_POINTER; this.filterPointersBySource(); return true; } return false; default: return false; } } addPointer(pointer) { this.pointerList.push(pointer); } removePointer(pointer) { this.pointerList = this.pointerList.filter(({ id }) => id !== pointer.id); } filterPointersBySource() { this.pointerList = this.pointerList.filter( ({ source }) => source === this.eventsSource ); } handleMouseDown(event) { if ( this.shouldHandleEvent(SOURCE_MOUSE) && ReactImageLightbox.isTargetMatchImage(event.target) ) { this.addPointer(ReactImageLightbox.parseMouseEvent(event)); this.multiPointerStart(event); } } handleMouseMove(event) { if (this.shouldHandleEvent(SOURCE_MOUSE)) { this.multiPointerMove(event, [ReactImageLightbox.parseMouseEvent(event)]); } } handleMouseUp(event) { if (this.shouldHandleEvent(SOURCE_MOUSE)) { this.removePointer(ReactImageLightbox.parseMouseEvent(event)); this.multiPointerEnd(event); } } handlePointerEvent(event) { if (this.shouldHandleEvent(SOURCE_POINTER)) { switch (event.type) { case 'pointerdown': if (ReactImageLightbox.isTargetMatchImage(event.target)) { this.addPointer(ReactImageLightbox.parsePointerEvent(event)); this.multiPointerStart(event); } break; case 'pointermove': this.multiPointerMove(event, [ ReactImageLightbox.parsePointerEvent(event), ]); break; case 'pointerup': case 'pointercancel': this.removePointer(ReactImageLightbox.parsePointerEvent(event)); this.multiPointerEnd(event); break; default: break; } } } handleTouchStart(event) { if ( this.shouldHandleEvent(SOURCE_TOUCH) && ReactImageLightbox.isTargetMatchImage(event.target) ) { [].forEach.call(event.changedTouches, eventTouch => this.addPointer(ReactImageLightbox.parseTouchPointer(eventTouch)) ); this.multiPointerStart(event); } } handleTouchMove(event) { if (this.shouldHandleEvent(SOURCE_TOUCH)) { this.multiPointerMove( event, [].map.call(event.changedTouches, eventTouch => ReactImageLightbox.parseTouchPointer(eventTouch) ) ); } } handleTouchEnd(event) { if (this.shouldHandleEvent(SOURCE_TOUCH)) { [].map.call(event.changedTouches, touch => this.removePointer(ReactImageLightbox.parseTouchPointer(touch)) ); this.multiPointerEnd(event); } } decideMoveOrSwipe(pointer) { if (this.state.zoomLevel <= MIN_ZOOM_LEVEL) { this.handleSwipeStart(pointer); } else { this.handleMoveStart(pointer); } } multiPointerStart(event) { this.handleEnd(null); switch (this.pointerList.length) { case 1: { event.preventDefault(); this.decideMoveOrSwipe(this.pointerList[0]); break; } case 2: { event.preventDefault(); this.handlePinchStart(this.pointerList); break; } default: break; } } multiPointerMove(event, pointerList) { switch (this.currentAction) { case ACTION_MOVE: { event.preventDefault(); this.handleMove(pointerList[0]); break; } case ACTION_SWIPE: { event.preventDefault(); this.handleSwipe(pointerList[0]); break; } case ACTION_PINCH: { event.preventDefault(); this.handlePinch(pointerList); break; } default: break; } } multiPointerEnd(event) { if (this.currentAction !== ACTION_NONE) { this.setPreventInnerClose(); this.handleEnd(event); } switch (this.pointerList.length) { case 0: { this.eventsSource = SOURCE_ANY; break; } case 1: { event.preventDefault(); this.decideMoveOrSwipe(this.pointerList[0]); break; } case 2: { event.preventDefault(); this.handlePinchStart(this.pointerList); break; } default: break; } } handleEnd(event) { switch (this.currentAction) { case ACTION_MOVE: this.handleMoveEnd(event); break; case ACTION_SWIPE: this.handleSwipeEnd(event); break; case ACTION_PINCH: this.handlePinchEnd(event); break; default: break; } } // Handle move start over the lightbox container // This happens: // - On a mouseDown event // - On a touchstart event handleMoveStart({ x: clientX, y: clientY }) { if (!this.props.enableZoom) { return; } this.currentAction = ACTION_MOVE; this.moveStartX = clientX; this.moveStartY = clientY; this.moveStartOffsetX = this.state.offsetX; this.moveStartOffsetY = this.state.offsetY; } // Handle dragging over the lightbox container // This happens: // - After a mouseDown and before a mouseUp event // - After a touchstart and before a touchend event handleMove({ x: clientX, y: clientY }) { const newOffsetX = this.moveStartX - clientX + this.moveStartOffsetX; const newOffsetY = this.moveStartY - clientY + this.moveStartOffsetY; if ( this.state.offsetX !== newOffsetX || this.state.offsetY !== newOffsetY ) { this.setState({ offsetX: newOffsetX, offsetY: newOffsetY, }); } } handleMoveEnd() { this.currentAction = ACTION_NONE; this.moveStartX = 0; this.moveStartY = 0; this.moveStartOffsetX = 0; this.moveStartOffsetY = 0; // Snap image back into frame if outside max offset range const maxOffsets = this.getMaxOffsets(); const nextOffsetX = Math.max( maxOffsets.minX, Math.min(maxOffsets.maxX, this.state.offsetX) ); const nextOffsetY = Math.max( maxOffsets.minY, Math.min(maxOffsets.maxY, this.state.offsetY) ); if ( nextOffsetX !== this.state.offsetX || nextOffsetY !== this.state.offsetY ) { this.setState({ offsetX: nextOffsetX, offsetY: nextOffsetY, shouldAnimate: true, }); this.setTimeout(() => { this.setState({ shouldAnimate: false }); }, this.props.animationDuration); } } handleSwipeStart({ x: clientX, y: clientY }) { this.currentAction = ACTION_SWIPE; this.swipeStartX = clientX; this.swipeStartY = clientY; this.swipeEndX = clientX; this.swipeEndY = clientY; } handleSwipe({ x: clientX, y: clientY }) { this.swipeEndX = clientX; this.swipeEndY = clientY; } handleSwipeEnd(event) { const xDiff = this.swipeEndX - this.swipeStartX; const xDiffAbs = Math.abs(xDiff); const yDiffAbs = Math.abs(this.swipeEndY - this.swipeStartY); this.currentAction = ACTION_NONE; this.swipeStartX = 0; this.swipeStartY = 0; this.swipeEndX = 0; this.swipeEndY = 0; if (!event || this.isAnimating() || xDiffAbs < yDiffAbs * 1.5) { return; } if (xDiffAbs < MIN_SWIPE_DISTANCE) { const boxRect = this.getLightboxRect(); if (xDiffAbs < boxRect.width / 4) { return; } } if (xDiff > 0 && this.props.prevSrc) { event.preventDefault(); this.requestMovePrev(); } else if (xDiff < 0 && this.props.nextSrc) { event.preventDefault(); this.requestMoveNext(); } } calculatePinchDistance([a, b] = this.pinchTouchList) { return Math.sqrt((a.x - b.x) ** 2 + (a.y - b.y) ** 2); } calculatePinchCenter([a, b] = this.pinchTouchList) { return { x: a.x - (a.x - b.x) / 2, y: a.y - (a.y - b.y) / 2, }; } handlePinchStart(pointerList) { if (!this.props.enableZoom) { return; } this.currentAction = ACTION_PINCH; this.pinchTouchList = pointerList.map(({ id, x, y }) => ({ id, x, y })); this.pinchDistance = this.calculatePinchDistance(); } handlePinch(pointerList) { this.pinchTouchList = this.pinchTouchList.map(oldPointer => { for (let i = 0; i < pointerList.length; i += 1) { if (pointerList[i].id === oldPointer.id) { return pointerList[i]; } } return oldPointer; }); const newDistance = this.calculatePinchDistance(); const zoomLevel = this.state.zoomLevel + newDistance - this.pinchDistance; this.pinchDistance = newDistance; const { x: clientX, y: clientY } = this.calculatePinchCenter( this.pinchTouchList ); this.changeZoom(zoomLevel, clientX, clientY); } handlePinchEnd() { this.currentAction = ACTION_NONE; this.pinchTouchList = null; this.pinchDistance = 0; } // Handle the window resize event handleWindowResize() { this.clearTimeout(this.resizeTimeout); this.resizeTimeout = this.setTimeout(this.forceUpdate.bind(this), 100); } handleZoomInButtonClick() { const nextZoomLevel = this.state.zoomLevel + ZOOM_BUTTON_INCREMENT_SIZE; this.changeZoom(nextZoomLevel); if (nextZoomLevel === MAX_ZOOM_LEVEL) { this.zoomOutBtn.current.focus(); } } handleZoomOutButtonClick() { const nextZoomLevel = this.state.zoomLevel - ZOOM_BUTTON_INCREMENT_SIZE; this.changeZoom(nextZoomLevel); if (nextZoomLevel === MIN_ZOOM_LEVEL) { this.zoomInBtn.current.focus(); } } handleCaptionMousewheel(event) { event.stopPropagation(); if (!this.caption.current) { return; } const { height } = this.caption.current.getBoundingClientRect(); const { scrollHeight, scrollTop } = this.caption.current; if ( (event.deltaY > 0 && height + scrollTop >= scrollHeight) || (event.deltaY < 0 && scrollTop <= 0) ) { event.preventDefault(); } } // Detach key and mouse input events isAnimating() { return this.state.shouldAnimate || this.state.isClosing; } // Check if image is loaded isImageLoaded(imageSrc) { return ( imageSrc && imageSrc in this.imageCache && this.imageCache[imageSrc].loaded ); } // Load image from src and call callback with image width and height on load loadImage(srcType, imageSrc, done) { // Return the image info if it is already cached if (this.isImageLoaded(imageSrc)) { this.setTimeout(() => { done(); }, 1); return; } const inMemoryImage = new global.Image(); if (this.props.imageCrossOrigin) { inMemoryImage.crossOrigin = this.props.imageCrossOrigin; } inMemoryImage.onerror = errorEvent => { this.props.onImageLoadError(imageSrc, srcType, errorEvent); // failed to load so set the state loadErrorStatus this.setState(prevState => ({ loadErrorStatus: { ...prevState.loadErrorStatus, [srcType]: true }, })); done(errorEvent); }; inMemoryImage.onload = () => { this.props.onImageLoad(imageSrc, srcType, inMemoryImage); this.imageCache[imageSrc] = { loaded: true, width: inMemoryImage.width, height: inMemoryImage.height, }; done(); }; inMemoryImage.src = imageSrc; } // Load all images and their thumbnails loadAllImages(props = this.props) { const generateLoadDoneCallback = (srcType, imageSrc) => err => { // Give up showing image on error if (err) { return; } // Don't rerender if the src is not the same as when the load started // or if the component has unmounted if (this.props[srcType] !== imageSrc || this.didUnmount) { return; } // Force rerender with the new image this.forceUpdate(); }; // Load the images this.getSrcTypes().forEach(srcType => { const type = srcType.name; // there is no error when we try to load it initially if (props[type] && this.state.loadErrorStatus[type]) { this.setState(prevState => ({ loadErrorStatus: { ...prevState.loadErrorStatus, [type]: false }, })); } // Load unloaded images if (props[type] && !this.isImageLoaded(props[type])) { this.loadImage( type, props[type], generateLoadDoneCallback(type, props[type]) ); } }); } // Request that the lightbox be closed requestClose(event) { // Call the parent close request const closeLightbox = () => this.props.onCloseRequest(event); if ( this.props.animationDisabled || (event.type === 'keydown' && !this.props.animationOnKeyInput) ) { // No animation closeLightbox(); return; } // With animation // Start closing animation this.setState({ isClosing: true }); // Perform the actual closing at the end of the animation this.setTimeout(closeLightbox, this.props.animationDuration); } requestMove(direction, event) { // Reset the zoom level on image move const nextState = { zoomLevel: MIN_ZOOM_LEVEL, offsetX: 0, offsetY: 0, }; // Enable animated states if ( !this.props.animationDisabled && (!this.keyPressed || this.props.animationOnKeyInput) ) { nextState.shouldAnimate = true; this.setTimeout( () => this.setState({ shouldAnimate: false }), this.props.animationDuration ); } this.keyPressed = false; this.moveRequested = true; if (direction === 'prev') { this.keyCounter -= 1; this.setState(nextState); this.props.onMovePrevRequest(event); } else { this.keyCounter += 1; this.setState(nextState); this.props.onMoveNextRequest(event); } } // Request to transition to the next image requestMoveNext(event) { this.requestMove('next', event); } // Request to transition to the previous image requestMovePrev(event) { this.requestMove('prev', event); } render() { const { animationDisabled, animationDuration, clickOutsideToClose, discourageDownloads, enableZoom, imageTitle, nextSrc, prevSrc, toolbarButtons, reactModalStyle, onAfterOpen, imageCrossOrigin, reactModalProps, } = this.props; const { zoomLevel, offsetX, offsetY, isClosing, loadErrorStatus, } = this.state; const boxSize = this.getLightboxRect(); let transitionStyle = {}; // Transition settings for sliding animations if (!animationDisabled && this.isAnimating()) { transitionStyle = { ...transitionStyle, transition: `transform ${animationDuration}ms`, }; } // Key endings to differentiate between images with the same src const keyEndings = {}; this.getSrcTypes().forEach(({ name, keyEnding }) => { keyEndings[name] = keyEnding; }); // Images to be displayed const images = []; const addImage = (srcType, imageClass, transforms) => { // Ignore types that have no source defined for their full size image if (!this.props[srcType]) { return; } const bestImageInfo = this.getBestImageForType(srcType); const imageStyle = { ...transitionStyle, ...ReactImageLightbox.getTransform({ ...transforms, ...bestImageInfo, }), }; if (zoomLevel > MIN_ZOOM_LEVEL) { imageStyle.cursor = 'move'; } // support IE 9 and 11 const hasTrueValue = object => Object.keys(object).some(key => object[key]); // when error on one of the loads then push custom error stuff if (bestImageInfo === null && hasTrueValue(loadErrorStatus)) { images.push( <div className={`${imageClass} ril__image ril-errored`} style={imageStyle} key={this.props[srcType] + keyEndings[srcType]} > <div className="ril__errorContainer"> {this.props.imageLoadErrorMessage} </div> </div> ); return; } if (bestImageInfo === null) { const loadingIcon = ( <div className="ril-loading-circle ril__loadingCircle ril__loadingContainer__icon"> {[...new Array(12)].map((_, index) => ( <div // eslint-disable-next-line react/no-array-index-key key={index} className="ril-loading-circle-point ril__loadingCirclePoint" /> ))} </div> ); // Fall back to loading icon if the thumbnail has not been loaded images.push( <div className={`${imageClass} ril__image ril-not-loaded`} style={imageStyle} key={this.props[srcType] + keyEndings[srcType]} > <div className="ril__loadingContainer">{loadingIcon}</div> </div> ); return; } const imageSrc = bestImageInfo.src; if (discourageDownloads) { imageStyle.backgroundImage = `url('${imageSrc}')`; images.push( <div className={`${imageClass} ril__image ril__imageDiscourager`} onDoubleClick={this.handleImageDoubleClick} onWheel={this.handleImageMouseWheel} style={imageStyle} key={imageSrc + keyEndings[srcType]} > <div className="ril-download-blocker ril__downloadBlocker" /> </div> ); } else { images.push( <img {...(imageCrossOrigin ? { crossOrigin: imageCrossOrigin } : {})} className={`${imageClass} ril__image`} onDoubleClick={this.handleImageDoubleClick} onWheel={this.handleImageMouseWheel} onDragStart={e => e.preventDefault()} style={imageStyle} src={imageSrc} key={imageSrc + keyEndings[srcType]} alt={ typeof imageTitle === 'string' ? imageTitle : translate('Image') } draggable={false} /> ); } }; const zoomMultiplier = this.getZoomMultiplier(); // Next Image (displayed on the right) addImage('nextSrc', 'ril-image-next ril__imageNext', { x: boxSize.width, }); // Main Image addImage('mainSrc', 'ril-image-current', { x: -1 * offsetX, y: -1 * offsetY, zoom: zoomMultiplier, }); // Previous Image (displayed on the left) addImage('prevSrc', 'ril-image-prev ril__imagePrev', { x: -1 * boxSize.width, }); const modalStyle = { overlay: { zIndex: 1000, backgroundColor: 'transparent', ...reactModalStyle.overlay, // Allow style overrides via props }, content: { backgroundColor: 'transparent', overflow: 'hidden', // Needed, otherwise keyboard shortcuts scroll the page border: 'none', borderRadius: 0, padding: 0, top: 0, left: 0, right: 0, bottom: 0, ...reactModalStyle.content, // Allow style overrides via props }, }; return ( <Modal isOpen onRequestClose={clickOutsideToClose ? this.requestClose : undefined} onAfterOpen={() => { // Focus on the div with key handlers if (this.outerEl.current) { this.outerEl.current.focus(); } onAfterOpen(); }} style={modalStyle} contentLabel={translate('Lightbox')} appElement={ typeof global.window !== 'undefined' ? global.window.document.body : undefined } {...reactModalProps} > <div // eslint-disable-line jsx-a11y/no-static-element-interactions // Floating modal with closing animations className={`ril-outer ril__outer ril__outerAnimating ${ this.props.wrapperClassName } ${isClosing ? 'ril-closing ril__outerClosing' : ''}`} style={{ transition: `opacity ${animationDuration}ms`, animationDuration: `${animationDuration}ms`, animationDirection: isClosing ? 'normal' : 'reverse', }} ref={this.outerEl} onWheel={this.handleOuterMousewheel} onMouseMove={this.handleMouseMove} onMouseDown={this.handleMouseDown} onTouchStart={this.handleTouchStart} onTouchMove={this.handleTouchMove} tabIndex="-1" // Enables key handlers on div onKeyDown={this.handleKeyInput} onKeyUp={this.handleKeyInput} > <div // eslint-disable-line jsx-a11y/no-static-element-interactions, jsx-a11y/click-events-have-key-events // Image holder className="ril-inner ril__inner" onClick={clickOutsideToClose ? this.closeIfClickInner : undefined} > {images} </div> {prevSrc && ( <button // Move to previous image button type="button" className="ril-prev-button ril__navButtons ril__navButtonPrev" key="prev" aria-label={this.props.prevLabel} onClick={!this.isAnimating() ? this.requestMovePrev : undefined} // Ignore clicks during animation /> )} {nextSrc && ( <button // Move to next image button type="button" className="ril-next-button ril__navButtons ril__navButtonNext" key="next" aria-label={this.props.nextLabel} onClick={!this.isAnimating() ? this.requestMoveNext : undefined} // Ignore clicks during animation /> )} <div // Lightbox toolbar className="ril-toolbar ril__toolbar" > <ul className="ril-toolbar-left ril__toolbarSide ril__toolbarLeftSide"> <li className="ril-toolbar__item ril__toolbarItem"> <span className="ril-toolbar__item__child ril__toolbarItemChild"> {imageTitle} </span> </li> </ul> <ul className="ril-toolbar-right ril__toolbarSide ril__toolbarRightSide"> {toolbarButtons && toolbarButtons.map((button, i) => ( <li key={`button_${i + 1}`} className="ril-toolbar__item ril__toolbarItem" > {button} </li> ))} {enableZoom && ( <li className="ril-toolbar__item ril__toolbarItem"> <button // Lightbox zoom in button type="button" key="zoom-in" aria-label={this.props.zoomInLabel} className={[ 'ril-zoom-in', 'ril__toolbarItemChild', 'ril__builtinButton', 'ril__zoomInButton', ...(zoomLevel === MAX_ZOOM_LEVEL ? ['ril__builtinButtonDisabled'] : []), ].join(' ')} ref={this.zoomInBtn} disabled={ this.isAnimating() || zoomLevel === MAX_ZOOM_LEVEL } onClick={ !this.isAnimating() && zoomLevel !== MAX_ZOOM_LEVEL ? this.handleZoomInButtonClick : undefined } /> </li> )} {enableZoom && ( <li className="ril-toolbar__item ril__toolbarItem"> <button // Lightbox zoom out button type="button" key="zoom-out" aria-label={this.props.zoomOutLabel} className={[ 'ril-zoom-out', 'ril__toolbarItemChild', 'ril__builtinButton', 'ril__zoomOutButton', ...(zoomLevel === MIN_ZOOM_LEVEL ? ['ril__builtinButtonDisabled'] : []), ].join(' ')} ref={this.zoomOutBtn} disabled={ this.isAnimating() || zoomLevel === MIN_ZOOM_LEVEL } onClick={ !this.isAnimating() && zoomLevel !== MIN_ZOOM_LEVEL ? this.handleZoomOutButtonClick : undefined } /> </li> )} <li className="ril-toolbar__item ril__toolbarItem"> <button // Lightbox close button type="button" key="close" aria-label={this.props.closeLabel} className="ril-close ril-toolbar__item__child ril__toolbarItemChild ril__builtinButton ril__closeButton" onClick={!this.isAnimating() ? this.requestClose : undefined} // Ignore clicks during animation /> </li> </ul> </div> {this.props.imageCaption && ( // eslint-disable-next-line jsx-a11y/no-static-element-interactions <div // Image caption onWheel={this.handleCaptionMousewheel} onMouseDown={event => event.stopPropagation()} className="ril-caption ril__caption" ref={this.caption} > <div className="ril-caption-content ril__captionContent"> {this.props.imageCaption} </div> </div> )} </div> </Modal> ); } } ReactImageLightbox.propTypes = { //----------------------------- // Image sources //----------------------------- // Main display image url mainSrc: PropTypes.string.isRequired, // eslint-disable-line react/no-unused-prop-types // Previous display image url (displayed to the left) // If left undefined, movePrev actions will not be performed, and the button not displayed prevSrc: PropTypes.string, // Next display image url (displayed to the right) // If left undefined, moveNext actions will not be performed, and the button not displayed nextSrc: PropTypes.string, //----------------------------- // Image thumbnail sources //----------------------------- // Thumbnail image url corresponding to props.mainSrc mainSrcThumbnail: PropTypes.string, // eslint-disable-line react/no-unused-prop-types // Thumbnail image url corresponding to props.prevSrc prevSrcThumbnail: PropTypes.string, // eslint-disable-line react/no-unused-prop-types // Thumbnail image url corresponding to props.nextSrc nextSrcThumbnail: PropTypes.string, // eslint-disable-line react/no-unused-prop-types //----------------------------- // Event Handlers //----------------------------- // Close window event // Should change the parent state such that the lightbox is not rendered onCloseRequest: PropTypes.func.isRequired, // Move to previous image event // Should change the parent state such that props.prevSrc becomes props.mainSrc, // props.mainSrc becomes props.nextSrc, etc. onMovePrevRequest: PropTypes.func, // Move to next image event // Should change the parent state such that props.nextSrc becomes props.mainSrc, // props.mainSrc becomes props.prevSrc, etc. onMoveNextRequest: PropTypes.func, // Called when an image fails to load // (imageSrc: string, srcType: string, errorEvent: object): void onImageLoadError: PropTypes.func, // Called when image successfully loads onImageLoad: PropTypes.func, // Open window event onAfterOpen: PropTypes.func, //----------------------------- // Download discouragement settings //----------------------------- // Enable download discouragement (prevents [right-click -> Save Image As...]) discourageDownloads: PropTypes.bool, //----------------------------- // Animation settings //----------------------------- // Disable all animation animationDisabled: PropTypes.bool, // Disable animation on actions performed with keyboard shortcuts animationOnKeyInput: PropTypes.bool, // Animation duration (ms) animationDuration: PropTypes.number, //----------------------------- // Keyboard shortcut settings //----------------------------- // Required interval of time (ms) between key actions // (prevents excessively fast navigation of images) keyRepeatLimit: PropTypes.number, // Amount of time (ms) restored after each keyup // (makes rapid key presses slightly faster than holding down the key to navigate images) keyRepeatKeyupBonus: PropTypes.number, //----------------------------- // Image info //----------------------------- // Image title imageTitle: PropTypes.node, // Image caption imageCaption: PropTypes.node, // Optional crossOrigin attribute imageCrossOrigin: PropTypes.string, //----------------------------- // Lightbox style //----------------------------- // Set z-index style, etc., for the parent react-modal (format: https://github.com/reactjs/react-modal#styles ) reactModalStyle: PropTypes.shape({}), // Padding (px) between the edge of the window and the lightbox imagePadding: PropTypes.number, wrapperClassName: PropTypes.string, //----------------------------- // Other //----------------------------- // Array of custom toolbar buttons toolbarButtons: PropTypes.arrayOf(PropTypes.node), // When true, clicks outside of the image close the lightbox clickOutsideToClose: PropTypes.bool, // Set to false to disable zoom functionality and hide zoom buttons enableZoom: PropTypes.bool, // Override props set on react-modal (https://github.com/reactjs/react-modal) reactModalProps: PropTypes.shape({}), // Aria-labels nextLabel: PropTypes.string, prevLabel: PropTypes.string, zoomInLabel: PropTypes.string, zoomOutLabel: PropTypes.string, closeLabel: PropTypes.string, imageLoadErrorMessage: PropTypes.node, }; ReactImageLightbox.defaultProps = { imageTitle: null, imageCaption: null, toolbarButtons: null, reactModalProps: {}, animationDisabled: false, animationDuration: 300, animationOnKeyInput: false, clickOutsideToClose: true, closeLabel: 'Close lightbox', discourageDownloads: false, enableZoom: true, imagePadding: 10, imageCrossOrigin: null, keyRepeatKeyupBonus: 40, keyRepeatLimit: 180, mainSrcThumbnail: null, nextLabel: 'Next image', nextSrc: null, nextSrcThumbnail: null, onAfterOpen: () => {}, onImageLoadError: () => {}, onImageLoad: () => {}, onMoveNextRequest: () => {}, onMovePrevRequest: () => {}, prevLabel: 'Previous image', prevSrc: null, prevSrcThumbnail: null, reactModalStyle: {}, wrapperClassName: '', zoomInLabel: 'Zoom in', zoomOutLabel: 'Zoom out', imageLoadErrorMessage: 'This image failed to load', }; export default ReactImageLightbox;
src/img/imgs/icon_fullcontrol.js
mikah1337/null-terminator
import React from 'react'; export default class Icon_Fullcontrol extends React.Component { constructor(props) { super(props); this.state = { height: this.props.height || "70%", color: this.props.color || "#d2d4d8" } } render() { return ( <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 40 40" height={this.state.height} width={this.state.height} aria-labelledby="Full Control Content Toggle"> <g id="Layer_2" data-name="Layer 2"> <g id="Layer_1-2" data-name="Layer 1"> <circle cx="71.54" cy="71.54" r="71.54" fill="#d2d4d8" /> <path d="M97.44,101c-.22,0-.41.29-.42.66s.19.75.44.75.43-.35.41-.75S97.65,101,97.44,101Z" fill="#fff" /> <path d="M98.14,100.72a.5.5,0,0,1,.08.2l.14,1.07c0,.36-.25.69-.71.77h0l0,.7c0,.1-.09.18-.21.18a.2.2,0,0,1-.22-.18v-.7h0c-.46-.08-.78-.41-.74-.77l.1-1.07a.5.5,0,0,1,.08-.2,2.91,2.91,0,0,0-2.4,1.54l-.83,2.27c-.79,2.14.8,4.68,3.89,4.68h.4c3.09,0,4.59-2.54,3.72-4.68l-.92-2.27A3,3,0,0,0,98.14,100.72Z" fill="#fff" /> <path d="M91.84,108.25s0,0,0,0l-.07-.12-4.07-7,0,0c-.12-.19-.41-.28-.82-.29H58.33q-.64,0-.81.3l0,0-4.08,7,0,.07a.3.3,0,0,0,0,.1h0v1.52H91.84v-1.52Zm-7.4-6.73h1.48c.16,0,.23,0,.26.1l.18.35.18.35c0,.07,0,.1-.16.1H84.81q-.19,0-.24-.09c-.11-.25-.22-.49-.32-.73C84.23,101.55,84.29,101.52,84.44,101.52Zm-.33,1.37h2.61c.16,0,.24,0,.28.11l.4.77c0,.09,0,.12-.18.12H84.54c-.21,0-.28,0-.32-.13q-.15-.39-.3-.75C83.88,102.92,83.93,102.89,84.11,102.89Zm-2.5-1.37h1.53c.12,0,.2,0,.22.08l.3.73c0,.06,0,.09-.17.09H81.92c-.15,0-.22,0-.24-.1-.09-.24-.16-.48-.24-.71C81.42,101.55,81.47,101.52,81.61,101.52Zm-.55,1.37h1.59c.14,0,.22,0,.24.1.1.26.19.52.29.79,0,.07,0,.1-.17.11H81.37c-.18,0-.25,0-.27-.12-.08-.26-.16-.52-.23-.77C80.85,102.92,80.9,102.89,81.06,102.89Zm.69,2.63H80c-.16,0-.23,0-.25-.11s-.08-.3-.11-.45-.07-.29-.1-.43,0-.11.19-.11c.56,0,1.13,0,1.69,0,.16,0,.23,0,.26.12l.21.69a.84.84,0,0,1,0,.17C82,105.48,81.91,105.52,81.75,105.52Zm-3-4h1.54c.13,0,.2,0,.22.1s.11.37.17.56,0,.1,0,.15,0,.09-.17.09H79c-.14,0-.21,0-.23-.1-.06-.24-.11-.48-.16-.71C78.61,101.55,78.66,101.52,78.79,101.52Zm.84,1.37c.12,0,.2,0,.21.1.08.26.15.53.21.8,0,.06,0,.09-.19.1H78.22c-.17,0-.24,0-.25-.12l-.15-.78c0-.06,0-.1.18-.1Zm-1.22,2.63H76.69c-.17,0-.25,0-.26-.13,0-.29-.08-.58-.11-.86,0-.08.05-.11.21-.11.56,0,1.13,0,1.7,0,.14,0,.21,0,.23.11s.05.29.08.43l.09.43C78.65,105.49,78.59,105.52,78.41,105.52Zm-2.42-4h1.52c.14,0,.2,0,.22.09s0,.24.07.36l.06.35c0,.07,0,.1-.19.1H76.11c-.15,0-.21,0-.22-.1l-.09-.71C75.79,101.55,75.85,101.52,76,101.52Zm.58,1.37c.15,0,.22,0,.23.11q.06.38.12.78c0,.07,0,.11-.21.11H75.06c-.15,0-.22,0-.22-.11s0-.27,0-.4,0-.26,0-.38,0-.11.21-.11Zm-4.64,1c-.17,0-.23,0-.23-.12,0-.26,0-.52,0-.78,0-.07.07-.1.21-.1h1.63c.12,0,.19,0,.19.1,0,.26,0,.52,0,.8,0,.07-.06.09-.21.1H71.93Zm.1.63c0,.29,0,.59,0,.89,0,.07-.07.11-.21.11H70.08c-.22,0-.28,0-.27-.14s0-.29,0-.43,0-.28,0-.42.07-.11.23-.11c.57,0,1.14,0,1.7,0C72,104.42,72,104.45,72,104.52Zm1.3-.1c.28,0,.56,0,.85,0s.55,0,.82,0,.24,0,.24.11c0,.28.06.57.08.87,0,.08,0,.12-.22.12H73.35c-.15,0-.23,0-.23-.11,0-.3,0-.6,0-.89C73.11,104.45,73.17,104.42,73.33,104.42Zm-.16-2.9h1.55c.11,0,.18,0,.19.08l.06.73c0,.06-.06.09-.19.09H73.21c-.15,0-.21,0-.21-.1,0-.24,0-.48,0-.71Q73,101.52,73.17,101.52Zm-3,.09c0-.06.08-.09.22-.09H71.9c.13,0,.19,0,.19.09,0,.23,0,.47,0,.72,0,.06-.07.09-.21.09H70.31c-.15,0-.22,0-.21-.11Zm.32,1.28c.17,0,.23,0,.22.11s0,.25,0,.38l0,.39c0,.08-.06.12-.23.12H68.77c-.15,0-.21,0-.2-.11,0-.27.07-.53.11-.79,0-.07.08-.1.25-.1h1.55Zm-5,.89c.06-.27.13-.53.19-.79,0-.07.09-.1.26-.1h1.58c.14,0,.2,0,.19.1s0,.26-.07.39,0,.26-.07.39-.08.12-.25.12H65.63C65.47,103.89,65.42,103.85,65.44,103.78Zm.16.75q-.09.43-.21.87c0,.09-.09.12-.26.12H63.39c-.16,0-.22,0-.2-.12.09-.3.19-.59.28-.88,0-.07.09-.1.25-.1s.56,0,.85,0,.54,0,.81,0S65.62,104.44,65.6,104.53Zm.91.86.09-.44c0-.14.05-.28.08-.42s.08-.11.24-.11c.57,0,1.13,0,1.7,0,.14,0,.21,0,.2.1l-.12.89c0,.08-.09.11-.26.11H66.73C66.54,105.52,66.49,105.49,66.51,105.39Zm.7-3.07c.05-.24.09-.48.14-.71q0-.09.21-.09H69.1c.12,0,.18,0,.17.09,0,.23,0,.47-.08.72,0,.06-.08.09-.22.09H67.4C67.25,102.42,67.2,102.39,67.21,102.32Zm-2.89,0,.21-.71c0-.06.09-.09.23-.09h1.52q.19,0,.18.09c-.06.23-.11.47-.17.72,0,.06-.09.09-.22.09H64.5C64.35,102.42,64.3,102.39,64.32,102.32Zm-2.9,0,.29-.71c0-.06.11-.09.26-.09h1.48c.16,0,.21,0,.19.1l-.12.35-.12.35c0,.07-.09.1-.25.1H61.59C61.45,102.42,61.39,102.39,61.42,102.32Zm-2.89,0,.37-.71c0-.06.1-.09.24-.09h1.53c.12,0,.18,0,.15.08-.1.24-.21.48-.32.73,0,.06-.11.09-.24.09H58.69C58.54,102.42,58.5,102.39,58.53,102.32Zm-.74,1.44q.2-.39.39-.75c0-.09.11-.12.29-.12h2.9c.17,0,.22,0,.19.11l-.3.77c0,.09-.11.12-.29.12H58C57.77,103.89,57.74,103.86,57.79,103.76Zm4,2.49c-.11.31-.22.64-.34,1,0,.1-.12.14-.3.14-1.66,0-3.31,0-5,0-.18,0-.23,0-.18-.13l.5-1c.05-.09.13-.13.31-.13h4.76C61.77,106.11,61.82,106.14,61.79,106.25Zm.59-1.7c-.1.27-.19.55-.29.84,0,.1-.11.13-.31.13H57.13c-.19,0-.23,0-.18-.13l.44-.85c0-.1.12-.12.31-.12.75,0,1.5,0,2.25,0h2.21C62.37,104.42,62.41,104.44,62.38,104.55Zm-.08-.77.15-.4c0-.13.09-.26.14-.39s.09-.1.24-.1h1.61c.13,0,.19,0,.17.1-.07.26-.15.53-.23.8,0,.06-.09.09-.22.09q-.85,0-1.71,0C62.33,103.88,62.28,103.85,62.3,103.78Zm20,3.58H62.81c-.2,0-.25,0-.22-.15q.15-.49.3-1c0-.11.1-.14.3-.14H81.86c.25,0,.31,0,.35.16l.29.92C82.54,107.32,82.48,107.36,82.26,107.36Zm.79-2c-.1-.29-.2-.57-.29-.85,0-.1,0-.12.2-.12.76,0,1.52,0,2.27,0h2.23c.22,0,.28,0,.34.13l.43.84c0,.1,0,.13-.19.13H83.35C83.16,105.52,83.08,105.49,83.05,105.39Zm5.87,2H84c-.23,0-.31,0-.35-.17-.11-.32-.22-.63-.32-.94,0-.11,0-.14.21-.14h4.75c.19,0,.26,0,.32.14l.49,1C89.18,107.32,89.13,107.35,88.92,107.35Z" fill="#fff" /> <path d="M112.22,75.58c-.22,0-.4.29-.41.66s.18.75.43.75.43-.35.41-.75S112.44,75.58,112.22,75.58Z" fill="#fff" /> <path d="M112.92,75.35a.32.32,0,0,1,.08.2l.15,1.07c0,.36-.26.69-.72.77,0,0,0,0,0,0l.06.7a.2.2,0,0,1-.22.18.19.19,0,0,1-.21-.18v-.7s0,0,0,0a.8.8,0,0,1-.75-.77l.11-1.07a.37.37,0,0,1,.07-.2,2.92,2.92,0,0,0-2.4,1.54l-.83,2.27c-.79,2.14.81,4.68,3.9,4.68h.39c3.1,0,4.59-2.54,3.73-4.68l-.92-2.27A3.06,3.06,0,0,0,112.92,75.35Z" fill="#fff" /> <path d="M106.62,82.88a.08.08,0,0,0,0,0l-.06-.13c-1.59-2.72-2.93-5-4.08-7,0,0,0,0,0,0-.12-.19-.41-.28-.81-.29H89.89v-.81h7c.31,0,.44-.19.3-.5a7.7,7.7,0,0,1-.43-.92.8.8,0,0,0-.92-.58c-1.08,0-2.17,0-3.26,0-.5,0-.79-.24-.8-.7,0-.87,0-1.75,0-2.7h11.18a1.6,1.6,0,0,0,1.76-1.75V47.53a1.61,1.61,0,0,0-1.76-1.75H71.82a1.6,1.6,0,0,0-1.75,1.74V67.35a1.6,1.6,0,0,0,1.79,1.79H82.51v2H57a1.61,1.61,0,0,0-1.76,1.74V92.72a1.6,1.6,0,0,0,1.8,1.79H67.73V97c0,.84-.16,1-1,1-1.21,0-2.43,0-3.64,0a.78.78,0,0,0-.55.28,10.47,10.47,0,0,0-.6,1.21c-.14.32,0,.46.31.49.11,0,.23,0,.34,0H81.74c.11,0,.23,0,.34,0,.31,0,.44-.19.3-.5a6.46,6.46,0,0,1-.44-.92.79.79,0,0,0-.91-.58c-1.09,0-2.17,0-3.26,0-.51,0-.8-.24-.81-.7,0-.87,0-1.75,0-2.7H88.14a1.59,1.59,0,0,0,1.75-1.75V84.4h16.73V82.88Zm-7.4-6.73h1.48c.16,0,.23,0,.27.1l.18.34.18.36c0,.07,0,.1-.16.1H99.59q-.2,0-.24-.09L99,76.23C99,76.17,99.07,76.15,99.22,76.15Zm-.32,1.37h2.6c.17,0,.24,0,.28.11.14.25.27.51.4.77,0,.09,0,.11-.18.12H99.32c-.2,0-.27,0-.31-.14s-.21-.5-.31-.74S98.72,77.52,98.9,77.52Zm-2.51-1.37h1.53c.12,0,.2,0,.23.08.1.24.19.48.29.73,0,.06,0,.09-.17.09H96.7c-.15,0-.22,0-.24-.1l-.24-.71C96.2,76.18,96.25,76.15,96.39,76.15Zm-.55,1.37h1.59c.15,0,.22,0,.25.1.09.26.19.52.29.79,0,.07,0,.1-.18.1H96.15c-.18,0-.24,0-.27-.12-.08-.26-.15-.52-.23-.77C95.63,77.55,95.68,77.52,95.84,77.52Zm.69,2.63H94.78c-.15,0-.23,0-.25-.11s-.07-.31-.11-.45-.06-.29-.1-.43,0-.11.2-.11h1.69c.15,0,.23,0,.25.12s.14.45.22.69a1.54,1.54,0,0,0,0,.17C96.75,80.11,96.7,80.15,96.53,80.15Zm-3-4h1.54c.13,0,.19,0,.21.1s.11.37.17.56a.83.83,0,0,1,0,.15c0,.06,0,.09-.17.09H93.8c-.15,0-.22,0-.23-.1-.06-.24-.12-.48-.17-.71Q93.39,76.15,93.58,76.15Zm.83,1.37c.13,0,.2,0,.22.09l.21.81c0,.06,0,.09-.2.09H93c-.18,0-.24,0-.26-.12,0-.26-.1-.52-.14-.78,0-.06,0-.1.18-.1Zm-1.22,2.63H91.47c-.17,0-.24,0-.25-.13,0-.29-.08-.58-.11-.86,0-.08,0-.11.2-.11H93c.15,0,.21,0,.23.11l.09.43c0,.14.06.29.08.43S93.38,80.15,93.19,80.15Zm-2.41-4H92.3q.2,0,.21.09c0,.12,0,.24.07.36s0,.23.07.35,0,.1-.19.1H90.89c-.14,0-.21,0-.22-.1,0-.24-.06-.48-.08-.71C90.58,76.18,90.64,76.15,90.78,76.15Zm.57,1.37c.15,0,.22,0,.24.11,0,.25.08.51.11.78,0,.07,0,.1-.2.1H89.84c-.15,0-.21,0-.22-.1l0-.4,0-.38c0-.08,0-.11.21-.11h1.58ZM76.56,80.15H71.92c-.19,0-.24,0-.19-.13l.44-.85c0-.1.12-.13.32-.13h4.45c.22,0,.26,0,.22.14l-.29.84C76.84,80.12,76.76,80.15,76.56,80.15Zm0,.73c-.11.31-.22.64-.33,1,0,.1-.12.14-.31.14H71c-.17,0-.23,0-.18-.13.17-.34.34-.66.51-1,0-.09.13-.13.3-.13h4.76C76.56,80.74,76.61,80.77,76.57,80.88Zm-.41-3.36c.17,0,.22,0,.18.11-.09.25-.19.51-.3.77,0,.09-.11.12-.29.12h-3c-.21,0-.25,0-.2-.13l.39-.75c.05-.09.12-.12.3-.12ZM73.32,77l.36-.71c0-.06.11-.09.25-.09h1.53c.12,0,.17,0,.15.08-.1.24-.21.48-.32.73q0,.09-.24.09H73.48C73.32,77.05,73.28,77,73.32,77Zm2.89,0c.09-.24.19-.48.29-.71,0-.06.1-.09.26-.09h1.48c.15,0,.2,0,.18.1l-.12.34-.12.36c0,.07-.09.1-.24.1H76.38C76.23,77.05,76.18,77,76.21,77Zm.88,1.46c0-.13.1-.27.14-.41s.09-.25.14-.38.1-.1.24-.1h1.62c.13,0,.18,0,.17.1-.08.26-.15.53-.23.8,0,.06-.1.09-.22.09H77.23C77.11,78.51,77.07,78.48,77.09,78.41Zm2-1.46c.07-.24.14-.48.22-.71,0-.06.08-.09.23-.09h1.51q.19,0,.18.09c0,.23-.11.47-.17.72,0,.06-.08.09-.22.09H79.29C79.13,77.05,79.08,77,79.1,77ZM78,80l.27-.88c0-.07.1-.1.25-.1h1.67c.18,0,.23,0,.21.12-.06.29-.13.57-.2.87,0,.09-.1.12-.27.12H78.17C78,80.15,78,80.12,78,80Zm2.24-1.62c.07-.27.13-.53.2-.79,0-.07.09-.1.26-.1h1.58c.13,0,.19,0,.18.1s0,.26-.07.39,0,.26-.07.39-.07.11-.24.12H80.41C80.26,78.51,80.2,78.48,80.22,78.41ZM82,77c.05-.24.1-.48.14-.71,0-.06.08-.09.22-.09h1.53c.12,0,.19,0,.18.09q0,.35-.09.72,0,.09-.21.09H82.19C82,77.05,82,77,82,77ZM81.29,80l.09-.44.09-.42c0-.08.08-.11.23-.11h1.7c.14,0,.21,0,.2.1,0,.29-.07.59-.11.89,0,.08-.1.11-.27.11h-1.7C81.33,80.15,81.27,80.12,81.29,80Zm2.26-1.51c-.15,0-.21,0-.2-.1,0-.27.07-.53.11-.79,0-.07.09-.1.25-.1h1.56c.16,0,.22,0,.22.11l0,.38c0,.13,0,.26,0,.39s-.07.11-.23.11Zm1.34-1.57.06-.7c0-.06.07-.09.21-.09h1.52c.13,0,.19,0,.19.08,0,.24,0,.48,0,.73,0,.06-.07.09-.2.09H85.09C84.94,77.05,84.88,77,84.89,76.94ZM84.6,80c0-.15,0-.29,0-.43s0-.28,0-.42.07-.11.23-.11h1.7c.14,0,.21,0,.2.1,0,.29,0,.59,0,.89,0,.07-.08.11-.22.11H84.86C84.64,80.15,84.59,80.12,84.6,80Zm2.11-1.49c-.16,0-.23,0-.22-.12,0-.26,0-.52,0-.78,0-.07.07-.1.21-.1h1.62c.13,0,.19,0,.19.1,0,.26,0,.52,0,.8,0,.06-.06.09-.22.1H86.71Zm1.06-2.28c0-.06.06-.09.19-.09H89.5c.12,0,.19,0,.19.08,0,.24,0,.49.07.73,0,.06-.07.09-.2.09H88c-.15,0-.21,0-.21-.1C87.78,76.71,87.77,76.47,87.77,76.24Zm.34,2.81h1.78c.09,0,.13,0,.14.11,0,.28,0,.57.08.87,0,.08-.06.12-.22.12H88.14c-.16,0-.23,0-.23-.11,0-.31,0-.6,0-.89C87.89,79.08,88,79.05,88.11,79.05Zm1.81-8.3H84.44c-.46,0-.75-.22-.75-.57s.32-.58.76-.58h5.48c.47,0,.74.23.74.59S90.4,70.75,89.92,70.75ZM71.64,67.36V47.56h31.48v19.8Zm3.5,28.76H69.66c-.47,0-.76-.22-.75-.57s.31-.58.76-.58c1.82,0,3.65,0,5.48,0,.46,0,.73.23.73.59S75.61,96.12,75.14,96.12Zm2.13-23.19c-.21.36-.37.75-.54,1.12s0,.46.31.49h11.3v.81H73.12q-.65,0-.81.3l0,0-4.08,7a.43.43,0,0,1,0,.07l0,.1h0V84.4h20.2v8.33H56.85V72.93M97,82H77.6c-.2,0-.26,0-.23-.14q.15-.5.3-1c0-.11.11-.14.31-.14H96.65c.25,0,.31,0,.35.16.09.3.19.61.28.92C97.32,82,97.26,82,97,82Zm.79-2c-.1-.29-.19-.57-.29-.85,0-.1,0-.13.21-.13h4.5c.21,0,.28,0,.33.14.14.27.29.55.43.84.06.1,0,.13-.19.13H98.13C97.94,80.15,97.87,80.12,97.83,80Zm5.87,2H98.8c-.23,0-.3,0-.35-.16-.11-.32-.21-.63-.32-.94,0-.11,0-.14.22-.14h4.74c.19,0,.27,0,.32.14.17.31.33.63.5,1C104,82,103.91,82,103.7,82Z" fill="#fff" /> <path d="M68.34,69.06c0-3.91,0-7.82,0-11.72,0-.5-.25-.66-.63-.77-2.64-.77-5.27-1.55-7.92-2.27-.27-.07-7.41,5.26-21.3.28a.46.46,0,0,0-.26,0c-6.32,1.5-11.07,6.65-11.53,9.87s.11,5.46.39,8.16c.21,2.08,1.87,12.48,2.21,14.63a.45.45,0,0,0,.46.38l16.1,0,7,0a.47.47,0,0,0,.46-.47V70a.47.47,0,0,1,.46-.46h14.1a.45.45,0,0,0,.46-.44Z" fill="#fff" /> <circle cx="49.99" cy="41.8" r="12.49" fill="#fff" /> </g> </g> </svg> ) } }