target
stringlengths
5
300
feat_repo_name
stringlengths
6
76
text
stringlengths
26
1.05M
grunt/config/compress.js
studiowangfei/react
'use strict'; var grunt = require('grunt'); var version = grunt.config.data.pkg.version; module.exports = { starter: { options: { archive: './build/react-' + version + '.zip', }, files: [ {cwd: './build/starter', src: ['**'], dest: 'react-' + version + '/'}, ], }, };
src/svg-icons/notification/airline-seat-recline-normal.js
lawrence-yu/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationAirlineSeatReclineNormal = (props) => ( <SvgIcon {...props}> <path d="M7.59 5.41c-.78-.78-.78-2.05 0-2.83.78-.78 2.05-.78 2.83 0 .78.78.78 2.05 0 2.83-.79.79-2.05.79-2.83 0zM6 16V7H4v9c0 2.76 2.24 5 5 5h6v-2H9c-1.66 0-3-1.34-3-3zm14 4.07L14.93 15H11.5v-3.68c1.4 1.15 3.6 2.16 5.5 2.16v-2.16c-1.66.02-3.61-.87-4.67-2.04l-1.4-1.55c-.19-.21-.43-.38-.69-.5-.29-.14-.62-.23-.96-.23h-.03C8.01 7 7 8.01 7 9.25V15c0 1.66 1.34 3 3 3h5.07l3.5 3.5L20 20.07z"/> </SvgIcon> ); NotificationAirlineSeatReclineNormal = pure(NotificationAirlineSeatReclineNormal); NotificationAirlineSeatReclineNormal.displayName = 'NotificationAirlineSeatReclineNormal'; NotificationAirlineSeatReclineNormal.muiName = 'SvgIcon'; export default NotificationAirlineSeatReclineNormal;
ui/src/pages/portfolio/index.js
danielbh/danielhollcraft.com-gatsbyjs
import React from 'react' import './index.scss' export default ({ data }) => { return ( <section> <div className="container"> <header className="major"> <h2>Portfolio</h2> </header> <div className="features"> {data.allMarkdownRemark.edges.map(({ node }) => { const { frontmatter } = node const { previewImage, appStore, googlePlay, web, source, title } = frontmatter return ( <article key={node.id}> <img className="image" src={`${previewImage.childImageSharp.responsiveSizes.src}`} alt="" /> <div key={node.id} className="inner"> <h3 className="project-title">{title}</h3> <p>{node.excerpt}</p> <ul className="actions"> {appStore && <li><a href={appStore} className="button">App Store</a></li>} {googlePlay && <li><a href={googlePlay} className="button">Google Play</a></li>} {web && <li><a href={web} className="button">Web</a></li>} {source && <li><a href={source} className="button">Source</a></li>} </ul> </div> </article> ) }) } </div> </div> </section> ) } export const query = graphql` query PortfolioListQuery { allMarkdownRemark( filter: {fileAbsolutePath: {regex: "portfolio/projects/.*\\.md$/"}}, sort: { fields: [frontmatter___priority], order: DESC } ) { edges { node { id frontmatter { priority web source appStore googlePlay previewImage { childImageSharp { responsiveSizes(maxWidth: 870) { src } } } title path } excerpt } } } } `
components/DiscussionPost.js
concensus/react-native-ios-concensus
import React from 'react'; import { Text, View } from 'react-native'; export default function DiscussionPost({ post }) { const authorFirstLetter = post.author[0].toUpperCase(); return ( <View style={{ flex: 1, marginTop: 5, marginBottom: 7 }}> <View style={{ flex: 1, flexDirection: 'row' }}> <View style={{ width: 30, height: 30, borderRadius: 15, backgroundColor: stringToColor(post.author), }}> <Text style={{ backgroundColor: 'transparent', color: '#FFF', fontFamily: 'Baskerville', textAlign: 'center', fontSize: 23, }}> {authorFirstLetter} </Text> </View> <View style={{ paddingLeft: 5 }}> <Text style={{ fontWeight: 'bold' }}>{post.author}</Text> <Text style={{ fontFamily: 'Baskerville', fontSize: 18 }}>{post.body}</Text> </View> </View> </View> ); } function stringToColor(str) { var hash = 0; for (var i = 0; i < str.length; i++) { hash = str.charCodeAt(i) + ((hash << 5) - hash); } var colour = '#'; for (var i = 0; i < 3; i++) { var value = (hash >> (i * 8)) & 0xff; colour += ('00' + value.toString(16)).substr(-2); } return colour; }
app/js/pages/QuestionAnswerPage.js
niksoc/srmconnect
import React from 'react'; import {Nav, NavItem, PageHeader} from 'react-bootstrap'; import PageTitle from '../components/PageTitle'; import SimpleDetailViewPage from './SimpleDetailViewPage'; import DetailView from '../components/ModelViews/DetailView'; import axios from 'axios'; import {BASE_URL} from '../constants'; import FEATURES from '../features'; class QuestionAnswerPage extends React.Component{ constructor(){ super(); this.state = { answers:[] }; } updateData(props = this.props){ axios.get(`/api/list/answer/?id=${props.params.id}`) .then(({data})=> {if(!this.ignoreLastFetch) this.setState({answers:data});}) .catch((error)=> console.error(error)); } init(){ this.updateData(); } componentDidMount(){ this.init(); } componentWillUnmount(){ this.ignoreLastFetch = true; } componentWillReceiveProps(newProps){ if(newProps.pk !== this.props.pk){ this.init(); } } render(){ const question = <SimpleDetailViewPage route={this.props.route} params={this.props.params}/>; const answers = this.state.answers.map((ans,i)=><DetailView key={i} route={{votes:true, comments:true, model:'answer'}} fields={ans}/>); return (<div>{question} <PageTitle title='Answer' src={`/api/create/answer/?id=${this.props.params.id}`} /> {answers}</div>); } }; export default QuestionAnswerPage;
fields/types/email/EmailField.js
kwangkim/keystone
import Field from '../Field'; import React from 'react'; import { FormInput } from 'elemental'; /* TODO: - gravatar - validate email address */ module.exports = Field.create({ displayName: 'EmailField', renderValue () { return this.props.value ? ( <FormInput noedit href={'mailto:' + this.props.value}>{this.props.value}</FormInput> ) : ( <FormInput noedit>(not set)</FormInput> ); } });
react/features/device-selection/components/DeviceSelection.js
jitsi/jitsi-meet
// @flow import React from 'react'; import AbstractDialogTab, { type Props as AbstractDialogTabProps } from '../../base/dialog/components/web/AbstractDialogTab'; import { translate } from '../../base/i18n/functions'; import { createLocalTrack } from '../../base/lib-jitsi-meet/functions'; import logger from '../logger'; import AudioInputPreview from './AudioInputPreview'; import AudioOutputPreview from './AudioOutputPreview'; import DeviceSelector from './DeviceSelector'; import VideoInputPreview from './VideoInputPreview'; /** * The type of the React {@code Component} props of {@link DeviceSelection}. */ export type Props = { ...$Exact<AbstractDialogTabProps>, /** * All known audio and video devices split by type. This prop comes from * the app state. */ availableDevices: Object, /** * Whether or not the audio selector can be interacted with. If true, * the audio input selector will be rendered as disabled. This is * specifically used to prevent audio device changing in Firefox, which * currently does not work due to a browser-side regression. */ disableAudioInputChange: boolean, /** * True if device changing is configured to be disallowed. Selectors * will display as disabled. */ disableDeviceChange: boolean, /** * Whether video input dropdown should be enabled or not. */ disableVideoInputSelect: boolean, /** * Whether or not the audio permission was granted. */ hasAudioPermission: boolean, /** * Whether or not the audio permission was granted. */ hasVideoPermission: boolean, /** * If true, the audio meter will not display. Necessary for browsers or * configurations that do not support local stats to prevent a * non-responsive mic preview from displaying. */ hideAudioInputPreview: boolean, /** * If true, the button to play a test sound on the selected speaker will not be displayed. * This needs to be hidden on browsers that do not support selecting an audio output device. */ hideAudioOutputPreview: boolean, /** * Whether or not the audio output source selector should display. If * true, the audio output selector and test audio link will not be * rendered. */ hideAudioOutputSelect: boolean, /** * Whether video input preview should be displayed or not. * (In the case of iOS Safari). */ hideVideoInputPreview: boolean, /** * An optional callback to invoke after the component has completed its * mount logic. */ mountCallback?: Function, /** * The id of the audio input device to preview. */ selectedAudioInputId: string, /** * The id of the audio output device to preview. */ selectedAudioOutputId: string, /** * The id of the video input device to preview. */ selectedVideoInputId: string, /** * Invoked to obtain translated strings. */ t: Function }; /** * The type of the React {@code Component} state of {@link DeviceSelection}. */ type State = { /** * The JitsiTrack to use for previewing audio input. */ previewAudioTrack: ?Object, /** * The JitsiTrack to use for previewing video input. */ previewVideoTrack: ?Object, /** * The error message from trying to use a video input device. */ previewVideoTrackError: ?string }; /** * React {@code Component} for previewing audio and video input/output devices. * * @augments Component */ class DeviceSelection extends AbstractDialogTab<Props, State> { /** * Whether current component is mounted or not. * * In component did mount we start a Promise to create tracks and * set the tracks in the state, if we unmount the component in the meanwhile * tracks will be created and will never been disposed (dispose tracks is * in componentWillUnmount). When tracks are created and component is * unmounted we dispose the tracks. */ _unMounted: boolean; /** * Initializes a new DeviceSelection instance. * * @param {Object} props - The read-only React Component props with which * the new instance is to be initialized. */ constructor(props: Props) { super(props); this.state = { previewAudioTrack: null, previewVideoTrack: null, previewVideoTrackError: null }; this._unMounted = true; } /** * Generate the initial previews for audio input and video input. * * @inheritdoc */ componentDidMount() { this._unMounted = false; Promise.all([ this._createAudioInputTrack(this.props.selectedAudioInputId), this._createVideoInputTrack(this.props.selectedVideoInputId) ]) .catch(err => logger.warn('Failed to initialize preview tracks', err)) .then(() => this.props.mountCallback && this.props.mountCallback()); } /** * Checks if audio / video permissions were granted. Updates audio input and * video input previews. * * @param {Object} prevProps - Previous props this component received. * @returns {void} */ componentDidUpdate(prevProps) { if (prevProps.selectedAudioInputId !== this.props.selectedAudioInputId) { this._createAudioInputTrack(this.props.selectedAudioInputId); } if (prevProps.selectedVideoInputId !== this.props.selectedVideoInputId) { this._createVideoInputTrack(this.props.selectedVideoInputId); } } /** * Ensure preview tracks are destroyed to prevent continued use. * * @inheritdoc */ componentWillUnmount() { this._unMounted = true; this._disposeAudioInputPreview(); this._disposeVideoInputPreview(); } /** * Implements React's {@link Component#render()}. * * @inheritdoc */ render() { const { hideAudioInputPreview, hideAudioOutputPreview, hideVideoInputPreview, selectedAudioOutputId } = this.props; return ( <div className = { `device-selection${hideVideoInputPreview ? ' video-hidden' : ''}` }> <div className = 'device-selection-column column-video'> { !hideVideoInputPreview && <div className = 'device-selection-video-container'> <VideoInputPreview error = { this.state.previewVideoTrackError } track = { this.state.previewVideoTrack } /> </div> } { !hideAudioInputPreview && <AudioInputPreview track = { this.state.previewAudioTrack } /> } </div> <div className = 'device-selection-column column-selectors'> <div aria-live = 'polite all' className = 'device-selectors'> { this._renderSelectors() } </div> { !hideAudioOutputPreview && <AudioOutputPreview deviceId = { selectedAudioOutputId } /> } </div> </div> ); } /** * Creates the JitiTrack for the audio input preview. * * @param {string} deviceId - The id of audio input device to preview. * @private * @returns {void} */ _createAudioInputTrack(deviceId) { const { hideAudioInputPreview } = this.props; if (hideAudioInputPreview) { return; } return this._disposeAudioInputPreview() .then(() => createLocalTrack('audio', deviceId, 5000)) .then(jitsiLocalTrack => { if (this._unMounted) { jitsiLocalTrack.dispose(); return; } this.setState({ previewAudioTrack: jitsiLocalTrack }); }) .catch(() => { this.setState({ previewAudioTrack: null }); }); } /** * Creates the JitiTrack for the video input preview. * * @param {string} deviceId - The id of video device to preview. * @private * @returns {void} */ _createVideoInputTrack(deviceId) { const { hideVideoInputPreview } = this.props; if (hideVideoInputPreview) { return; } return this._disposeVideoInputPreview() .then(() => createLocalTrack('video', deviceId, 5000)) .then(jitsiLocalTrack => { if (!jitsiLocalTrack) { return Promise.reject(); } if (this._unMounted) { jitsiLocalTrack.dispose(); return; } this.setState({ previewVideoTrack: jitsiLocalTrack, previewVideoTrackError: null }); }) .catch(() => { this.setState({ previewVideoTrack: null, previewVideoTrackError: this.props.t('deviceSelection.previewUnavailable') }); }); } /** * Utility function for disposing the current audio input preview. * * @private * @returns {Promise} */ _disposeAudioInputPreview(): Promise<*> { return this.state.previewAudioTrack ? this.state.previewAudioTrack.dispose() : Promise.resolve(); } /** * Utility function for disposing the current video input preview. * * @private * @returns {Promise} */ _disposeVideoInputPreview(): Promise<*> { return this.state.previewVideoTrack ? this.state.previewVideoTrack.dispose() : Promise.resolve(); } /** * Creates a DeviceSelector instance based on the passed in configuration. * * @private * @param {Object} deviceSelectorProps - The props for the DeviceSelector. * @returns {ReactElement} */ _renderSelector(deviceSelectorProps) { return ( <div key = { deviceSelectorProps.label }> <label className = 'device-selector-label' htmlFor = { deviceSelectorProps.id }> { this.props.t(deviceSelectorProps.label) } </label> <DeviceSelector { ...deviceSelectorProps } /> </div> ); } /** * Creates DeviceSelector instances for video output, audio input, and audio * output. * * @private * @returns {Array<ReactElement>} DeviceSelector instances. */ _renderSelectors() { const { availableDevices, hasAudioPermission, hasVideoPermission } = this.props; const configurations = [ { devices: availableDevices.audioInput, hasPermission: hasAudioPermission, icon: 'icon-microphone', isDisabled: this.props.disableAudioInputChange || this.props.disableDeviceChange, key: 'audioInput', id: 'audioInput', label: 'settings.selectMic', onSelect: selectedAudioInputId => super._onChange({ selectedAudioInputId }), selectedDeviceId: this.state.previewAudioTrack ? this.state.previewAudioTrack.getDeviceId() : this.props.selectedAudioInputId }, { devices: availableDevices.videoInput, hasPermission: hasVideoPermission, icon: 'icon-camera', isDisabled: this.props.disableVideoInputSelect || this.props.disableDeviceChange, key: 'videoInput', id: 'videoInput', label: 'settings.selectCamera', onSelect: selectedVideoInputId => super._onChange({ selectedVideoInputId }), selectedDeviceId: this.state.previewVideoTrack ? this.state.previewVideoTrack.getDeviceId() : this.props.selectedVideoInputId } ]; if (!this.props.hideAudioOutputSelect) { configurations.push({ devices: availableDevices.audioOutput, hasPermission: hasAudioPermission || hasVideoPermission, icon: 'icon-speaker', isDisabled: this.props.disableDeviceChange, key: 'audioOutput', id: 'audioOutput', label: 'settings.selectAudioOutput', onSelect: selectedAudioOutputId => super._onChange({ selectedAudioOutputId }), selectedDeviceId: this.props.selectedAudioOutputId }); } return configurations.map(config => this._renderSelector(config)); } } export default translate(DeviceSelection);
ajax/libs/jointjs/0.9.4/joint.clean.js
taydakov/cdnjs
/*! JointJS v0.9.3 - JavaScript diagramming library 2015-07-23 This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ // JointJS library. // (c) 2011-2013 client IO // Global namespace. var joint = { version: '0.9.3', // `joint.dia` namespace. dia: {}, // `joint.ui` namespace. ui: {}, // `joint.layout` namespace. layout: {}, // `joint.shapes` namespace. shapes: {}, // `joint.format` namespace. format: {}, // `joint.connectors` namespace. connectors: {}, // `joint.routers` namespace. routers: {}, util: { // Return a simple hash code from a string. See http://werxltd.com/wp/2010/05/13/javascript-implementation-of-javas-string-hashcode-method/. hashCode: function(str) { var hash = 0; if (str.length == 0) return hash; for (var i = 0; i < str.length; i++) { var c = str.charCodeAt(i); hash = ((hash << 5) - hash) + c; hash = hash & hash; // Convert to 32bit integer } return hash; }, getByPath: function(obj, path, delim) { delim = delim || '/'; var keys = path.split(delim); var key; while (keys.length) { key = keys.shift(); if (Object(obj) === obj && key in obj) { obj = obj[key]; } else { return undefined; } } return obj; }, setByPath: function(obj, path, value, delim) { delim = delim || '/'; var keys = path.split(delim); var diver = obj; var i = 0; if (path.indexOf(delim) > -1) { for (var len = keys.length; i < len - 1; i++) { // diver creates an empty object if there is no nested object under such a key. // This means that one can populate an empty nested object with setByPath(). diver = diver[keys[i]] || (diver[keys[i]] = {}); } diver[keys[len - 1]] = value; } else { obj[path] = value; } return obj; }, unsetByPath: function(obj, path, delim) { delim = delim || '/'; // index of the last delimiter var i = path.lastIndexOf(delim); if (i > -1) { // unsetting a nested attribute var parent = joint.util.getByPath(obj, path.substr(0, i), delim); if (parent) { delete parent[path.slice(i + 1)]; } } else { // unsetting a primitive attribute delete obj[path]; } return obj; }, flattenObject: function(obj, delim, stop) { delim = delim || '/'; var ret = {}; for (var key in obj) { if (!obj.hasOwnProperty(key)) continue; var shouldGoDeeper = typeof obj[key] === 'object'; if (shouldGoDeeper && stop && stop(obj[key])) { shouldGoDeeper = false; } if (shouldGoDeeper) { var flatObject = this.flattenObject(obj[key], delim, stop); for (var flatKey in flatObject) { if (!flatObject.hasOwnProperty(flatKey)) continue; ret[key + delim + flatKey] = flatObject[flatKey]; } } else { ret[key] = obj[key]; } } return ret; }, uuid: function() { // credit: http://stackoverflow.com/posts/2117523/revisions return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = Math.random() * 16|0; var v = c == 'x' ? r : (r&0x3|0x8); return v.toString(16); }); }, // Generate global unique id for obj and store it as a property of the object. guid: function(obj) { this.guid.id = this.guid.id || 1; obj.id = (obj.id === undefined ? 'j_' + this.guid.id++ : obj.id); return obj.id; }, // Copy all the properties to the first argument from the following arguments. // All the properties will be overwritten by the properties from the following // arguments. Inherited properties are ignored. mixin: function() { var target = arguments[0]; for (var i = 1, l = arguments.length; i < l; i++) { var extension = arguments[i]; // Only functions and objects can be mixined. if ((Object(extension) !== extension) && !_.isFunction(extension) && (extension === null || extension === undefined)) { continue; } _.each(extension, function(copy, key) { if (this.mixin.deep && (Object(copy) === copy)) { if (!target[key]) { target[key] = _.isArray(copy) ? [] : {}; } this.mixin(target[key], copy); return; } if (target[key] !== copy) { if (!this.mixin.supplement || !target.hasOwnProperty(key)) { target[key] = copy; } } }, this); } return target; }, // Copy all properties to the first argument from the following // arguments only in case if they don't exists in the first argument. // All the function propererties in the first argument will get // additional property base pointing to the extenders same named // property function's call method. supplement: function() { this.mixin.supplement = true; var ret = this.mixin.apply(this, arguments); this.mixin.supplement = false; return ret; }, // Same as `mixin()` but deep version. deepMixin: function() { this.mixin.deep = true; var ret = this.mixin.apply(this, arguments); this.mixin.deep = false; return ret; }, // Same as `supplement()` but deep version. deepSupplement: function() { this.mixin.deep = this.mixin.supplement = true; var ret = this.mixin.apply(this, arguments); this.mixin.deep = this.mixin.supplement = false; return ret; }, normalizeEvent: function(evt) { return (evt.originalEvent && evt.originalEvent.changedTouches && evt.originalEvent.changedTouches.length) ? evt.originalEvent.changedTouches[0] : evt; }, nextFrame:(function() { var raf; var client = typeof window != 'undefined'; if (client) { raf = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame; } if (!raf) { var lastTime = 0; raf = function(callback) { var currTime = new Date().getTime(); var timeToCall = Math.max(0, 16 - (currTime - lastTime)); var id = setTimeout(function() { callback(currTime + timeToCall); }, timeToCall); lastTime = currTime + timeToCall; return id; }; } return client ? _.bind(raf, window) : raf; })(), cancelFrame: (function() { var caf; var client = typeof window != 'undefined'; if (client) { caf = window.cancelAnimationFrame || window.webkitCancelAnimationFrame || window.webkitCancelRequestAnimationFrame || window.msCancelAnimationFrame || window.msCancelRequestAnimationFrame || window.oCancelAnimationFrame || window.oCancelRequestAnimationFrame || window.mozCancelAnimationFrame || window.mozCancelRequestAnimationFrame; } caf = caf || clearTimeout; return client ? _.bind(caf, window) : caf; })(), shapePerimeterConnectionPoint: function(linkView, view, magnet, reference) { var bbox; var spot; if (!magnet) { // There is no magnet, try to make the best guess what is the // wrapping SVG element. This is because we want this "smart" // connection points to work out of the box without the // programmer to put magnet marks to any of the subelements. // For example, we want the functoin to work on basic.Path elements // without any special treatment of such elements. // The code below guesses the wrapping element based on // one simple assumption. The wrapping elemnet is the // first child of the scalable group if such a group exists // or the first child of the rotatable group if not. // This makese sense because usually the wrapping element // is below any other sub element in the shapes. var scalable = view.$('.scalable')[0]; var rotatable = view.$('.rotatable')[0]; if (scalable && scalable.firstChild) { magnet = scalable.firstChild; } else if (rotatable && rotatable.firstChild) { magnet = rotatable.firstChild; } } if (magnet) { spot = V(magnet).findIntersection(reference, linkView.paper.viewport); if (!spot) { bbox = g.rect(V(magnet).bbox(false, linkView.paper.viewport)); } } else { bbox = view.model.getBBox(); spot = bbox.intersectionWithLineFromCenterToPoint(reference); } return spot || bbox.center(); }, breakText: function(text, size, styles, opt) { opt = opt || {}; var width = size.width; var height = size.height; var svgDocument = opt.svgDocument || V('svg').node; var textElement = V('<text><tspan></tspan></text>').attr(styles || {}).node; var textSpan = textElement.firstChild; var textNode = document.createTextNode(''); textSpan.appendChild(textNode); svgDocument.appendChild(textElement); if (!opt.svgDocument) { document.body.appendChild(svgDocument); } var words = text.split(' '); var full = []; var lines = []; var p; for (var i = 0, l = 0, len = words.length; i < len; i++) { var word = words[i]; textNode.data = lines[l] ? lines[l] + ' ' + word : word; if (textSpan.getComputedTextLength() <= width) { // the current line fits lines[l] = textNode.data; if (p) { // We were partitioning. Put rest of the word onto next line full[l++] = true; // cancel partitioning p = 0; } } else { if (!lines[l] || p) { var partition = !!p; p = word.length - 1; if (partition || !p) { // word has only one character. if (!p) { if (!lines[l]) { // we won't fit this text within our rect lines = []; break; } // partitioning didn't help on the non-empty line // try again, but this time start with a new line // cancel partitions created words.splice(i, 2, word + words[i + 1]); // adjust word length len--; full[l++] = true; i--; continue; } // move last letter to the beginning of the next word words[i] = word.substring(0, p); words[i + 1] = word.substring(p) + words[i + 1]; } else { // We initiate partitioning // split the long word into two words words.splice(i, 1, word.substring(0, p), word.substring(p)); // adjust words length len++; if (l && !full[l - 1]) { // if the previous line is not full, try to fit max part of // the current word there l--; } } i--; continue; } l++; i--; } // if size.height is defined we have to check whether the height of the entire // text exceeds the rect height if (typeof height !== 'undefined') { // get line height as text height / 0.8 (as text height is approx. 0.8em // and line height is 1em. See vectorizer.text()) var lh = lh || textElement.getBBox().height * 1.25; if (lh * lines.length > height) { // remove overflowing lines lines.splice(Math.floor(height / lh)); break; } } } if (opt.svgDocument) { // svg document was provided, remove the text element only svgDocument.removeChild(textElement); } else { // clean svg document document.body.removeChild(svgDocument); } return lines.join('\n'); }, imageToDataUri: function(url, callback) { if (!url || url.substr(0, 'data:'.length) === 'data:') { // No need to convert to data uri if it is already in data uri. // This not only convenient but desired. For example, // IE throws a security error if data:image/svg+xml is used to render // an image to the canvas and an attempt is made to read out data uri. // Now if our image is already in data uri, there is no need to render it to the canvas // and so we can bypass this error. // Keep the async nature of the function. return setTimeout(function() { callback(null, url); }, 0); } var canvas = document.createElement('canvas'); var img = document.createElement('img'); img.onload = function() { var ctx = canvas.getContext('2d'); canvas.width = img.width; canvas.height = img.height; ctx.drawImage(img, 0, 0); try { // Guess the type of the image from the url suffix. var suffix = (url.split('.').pop()) || 'png'; // A little correction for JPEGs. There is no image/jpg mime type but image/jpeg. var type = 'image/' + (suffix === 'jpg') ? 'jpeg' : suffix; var dataUri = canvas.toDataURL(type); } catch (e) { if (/\.svg$/.test(url)) { // IE throws a security error if we try to render an SVG into the canvas. // Luckily for us, we don't need canvas at all to convert // SVG to data uri. We can just use AJAX to load the SVG string // and construct the data uri ourselves. var xhr = window.XMLHttpRequest ? new XMLHttpRequest : new ActiveXObject('Microsoft.XMLHTTP'); xhr.open('GET', url, false); xhr.send(null); var svg = xhr.responseText; return callback(null, 'data:image/svg+xml,' + encodeURIComponent(svg)); } console.error(img.src, 'fails to convert', e); } callback(null, dataUri); }; img.ononerror = function() { callback(new Error('Failed to load image.')); }; img.src = url; }, getElementBBox: function(el) { var $el = $(el); var offset = $el.offset(); var bbox; if (el.ownerSVGElement) { // Use Vectorizer to get the dimensions of the element if it is an SVG element. bbox = V(el).bbox(); // getBoundingClientRect() used in jQuery.fn.offset() takes into account `stroke-width` // in Firefox only. So clientRect width/height and getBBox width/height in FF don't match. // To unify this across all browsers we add the `stroke-width` (left & top) back to // the calculated offset. var crect = el.getBoundingClientRect(); var strokeWidthX = (crect.width - bbox.width) / 2; var strokeWidthY = (crect.height - bbox.height) / 2; // The `bbox()` returns coordinates relative to the SVG viewport, therefore, use the // ones returned from the `offset()` method that are relative to the document. bbox.x = offset.left + strokeWidthX; bbox.y = offset.top + strokeWidthY; } else { bbox = { x: offset.left, y: offset.top, width: $el.outerWidth(), height: $el.outerHeight() }; } return bbox; }, // Highly inspired by the jquery.sortElements plugin by Padolsey. // See http://james.padolsey.com/javascript/sorting-elements-with-jquery/. sortElements: function(elements, comparator) { var $elements = $(elements); var placements = $elements.map(function() { var sortElement = this; var parentNode = sortElement.parentNode; // Since the element itself will change position, we have // to have some way of storing it's original position in // the DOM. The easiest way is to have a 'flag' node: var nextSibling = parentNode.insertBefore(document.createTextNode(''), sortElement.nextSibling); return function() { if (parentNode === this) { throw new Error('You can\'t sort elements if any one is a descendant of another.'); } // Insert before flag: parentNode.insertBefore(this, nextSibling); // Remove flag: parentNode.removeChild(nextSibling); }; }); return Array.prototype.sort.call($elements, comparator).each(function(i) { placements[i].call(this); }); }, // Return a new object with all for sides (top, bottom, left and right) in it. // Value of each side is taken from the given argument (either number or object). // Default value for a side is 0. // Examples: // joint.util.normalizeSides(5) --> { top: 5, left: 5, right: 5, bottom: 5 } // joint.util.normalizeSides({ left: 5 }) --> { top: 0, left: 5, right: 0, bottom: 0 } normalizeSides: function(box) { if (Object(box) !== box) { box = box || 0; return { top: box, bottom: box, left: box, right: box }; } return { top: box.top || 0, bottom: box.bottom || 0, left: box.left || 0, right: box.right || 0 }; }, timing: { linear: function(t) { return t; }, quad: function(t) { return t * t; }, cubic: function(t) { return t * t * t; }, inout: function(t) { if (t <= 0) return 0; if (t >= 1) return 1; var t2 = t * t; var t3 = t2 * t; return 4 * (t < .5 ? t3 : 3 * (t - t2) + t3 - .75); }, exponential: function(t) { return Math.pow(2, 10 * (t - 1)); }, bounce: function(t) { for (var a = 0, b = 1; 1; a += b, b /= 2) { if (t >= (7 - 4 * a) / 11) { var q = (11 - 6 * a - 11 * t) / 4; return -q * q + b * b; } } }, reverse: function(f) { return function(t) { return 1 - f(1 - t); }; }, reflect: function(f) { return function(t) { return .5 * (t < .5 ? f(2 * t) : (2 - f(2 - 2 * t))); }; }, clamp: function(f, n, x) { n = n || 0; x = x || 1; return function(t) { var r = f(t); return r < n ? n : r > x ? x : r; }; }, back: function(s) { if (!s) s = 1.70158; return function(t) { return t * t * ((s + 1) * t - s); }; }, elastic: function(x) { if (!x) x = 1.5; return function(t) { return Math.pow(2, 10 * (t - 1)) * Math.cos(20 * Math.PI * x / 3 * t); }; } }, interpolate: { number: function(a, b) { var d = b - a; return function(t) { return a + d * t; }; }, object: function(a, b) { var s = _.keys(a); return function(t) { var i, p; var r = {}; for (i = s.length - 1; i != -1; i--) { p = s[i]; r[p] = a[p] + (b[p] - a[p]) * t; } return r; }; }, hexColor: function(a, b) { var ca = parseInt(a.slice(1), 16); var cb = parseInt(b.slice(1), 16); var ra = ca & 0x0000ff; var rd = (cb & 0x0000ff) - ra; var ga = ca & 0x00ff00; var gd = (cb & 0x00ff00) - ga; var ba = ca & 0xff0000; var bd = (cb & 0xff0000) - ba; return function(t) { var r = (ra + rd * t) & 0x000000ff; var g = (ga + gd * t) & 0x0000ff00; var b = (ba + bd * t) & 0x00ff0000; return '#' + (1 << 24 | r | g | b ).toString(16).slice(1); }; }, unit: function(a, b) { var r = /(-?[0-9]*.[0-9]*)(px|em|cm|mm|in|pt|pc|%)/; var ma = r.exec(a); var mb = r.exec(b); var p = mb[1].indexOf('.'); var f = p > 0 ? mb[1].length - p - 1 : 0; a = +ma[1]; var d = +mb[1] - a; var u = ma[2]; return function(t) { return (a + d * t).toFixed(f) + u; }; } }, // SVG filters. filter: { // `color` ... outline color // `width`... outline width // `opacity` ... outline opacity // `margin` ... gap between outline and the element outline: function(args) { var tpl = '<filter><feFlood flood-color="${color}" flood-opacity="${opacity}" result="colored"/><feMorphology in="SourceAlpha" result="morphedOuter" operator="dilate" radius="${outerRadius}" /><feMorphology in="SourceAlpha" result="morphedInner" operator="dilate" radius="${innerRadius}" /><feComposite result="morphedOuterColored" in="colored" in2="morphedOuter" operator="in"/><feComposite operator="xor" in="morphedOuterColored" in2="morphedInner" result="outline"/><feMerge><feMergeNode in="outline"/><feMergeNode in="SourceGraphic"/></feMerge></filter>'; var margin = _.isFinite(args.margin) ? args.margin : 2; var width = _.isFinite(args.width) ? args.width : 1; return _.template(tpl, { color: args.color || 'blue', opacity: _.isFinite(args.opacity) ? args.opacity : 1, outerRadius: margin + width, innerRadius: margin }); }, // `color` ... color // `width`... width // `blur` ... blur // `opacity` ... opacity highlight: function(args) { var tpl = '<filter><feFlood flood-color="${color}" flood-opacity="${opacity}" result="colored"/><feMorphology result="morphed" in="SourceGraphic" operator="dilate" radius="${width}"/><feComposite result="composed" in="colored" in2="morphed" operator="in"/><feGaussianBlur result="blured" in="composed" stdDeviation="${blur}"/><feBlend in="SourceGraphic" in2="blured" mode="normal"/></filter>'; return _.template(tpl, { color: args.color || 'red', width: _.isFinite(args.width) ? args.width : 1, blur: _.isFinite(args.blur) ? args.blur : 0, opacity: _.isFinite(args.opacity) ? args.opacity : 1 }); }, // `x` ... horizontal blur // `y` ... vertical blur (optional) blur: function(args) { var x = _.isFinite(args.x) ? args.x : 2; return _.template('<filter><feGaussianBlur stdDeviation="${stdDeviation}"/></filter>', { stdDeviation: _.isFinite(args.y) ? [x, args.y] : x }); }, // `dx` ... horizontal shift // `dy` ... vertical shift // `blur` ... blur // `color` ... color // `opacity` ... opacity dropShadow: function(args) { var tpl = 'SVGFEDropShadowElement' in window ? '<filter><feDropShadow stdDeviation="${blur}" dx="${dx}" dy="${dy}" flood-color="${color}" flood-opacity="${opacity}"/></filter>' : '<filter><feGaussianBlur in="SourceAlpha" stdDeviation="${blur}"/><feOffset dx="${dx}" dy="${dy}" result="offsetblur"/><feFlood flood-color="${color}"/><feComposite in2="offsetblur" operator="in"/><feComponentTransfer><feFuncA type="linear" slope="${opacity}"/></feComponentTransfer><feMerge><feMergeNode/><feMergeNode in="SourceGraphic"/></feMerge></filter>'; return _.template(tpl, { dx: args.dx || 0, dy: args.dy || 0, opacity: _.isFinite(args.opacity) ? args.opacity : 1, color: args.color || 'black', blur: _.isFinite(args.blur) ? args.blur : 4 }); }, // `amount` ... the proportion of the conversion. A value of 1 is completely grayscale. A value of 0 leaves the input unchanged. grayscale: function(args) { var amount = _.isFinite(args.amount) ? args.amount : 1; return _.template('<filter><feColorMatrix type="matrix" values="${a} ${b} ${c} 0 0 ${d} ${e} ${f} 0 0 ${g} ${b} ${h} 0 0 0 0 0 1 0"/></filter>', { a: 0.2126 + 0.7874 * (1 - amount), b: 0.7152 - 0.7152 * (1 - amount), c: 0.0722 - 0.0722 * (1 - amount), d: 0.2126 - 0.2126 * (1 - amount), e: 0.7152 + 0.2848 * (1 - amount), f: 0.0722 - 0.0722 * (1 - amount), g: 0.2126 - 0.2126 * (1 - amount), h: 0.0722 + 0.9278 * (1 - amount) }); }, // `amount` ... the proportion of the conversion. A value of 1 is completely sepia. A value of 0 leaves the input unchanged. sepia: function(args) { var amount = _.isFinite(args.amount) ? args.amount : 1; return _.template('<filter><feColorMatrix type="matrix" values="${a} ${b} ${c} 0 0 ${d} ${e} ${f} 0 0 ${g} ${h} ${i} 0 0 0 0 0 1 0"/></filter>', { a: 0.393 + 0.607 * (1 - amount), b: 0.769 - 0.769 * (1 - amount), c: 0.189 - 0.189 * (1 - amount), d: 0.349 - 0.349 * (1 - amount), e: 0.686 + 0.314 * (1 - amount), f: 0.168 - 0.168 * (1 - amount), g: 0.272 - 0.272 * (1 - amount), h: 0.534 - 0.534 * (1 - amount), i: 0.131 + 0.869 * (1 - amount) }); }, // `amount` ... the proportion of the conversion. A value of 0 is completely un-saturated. A value of 1 leaves the input unchanged. saturate: function(args) { var amount = _.isFinite(args.amount) ? args.amount : 1; return _.template('<filter><feColorMatrix type="saturate" values="${amount}"/></filter>', { amount: 1 - amount }); }, // `angle` ... the number of degrees around the color circle the input samples will be adjusted. hueRotate: function(args) { return _.template('<filter><feColorMatrix type="hueRotate" values="${angle}"/></filter>', { angle: args.angle || 0 }); }, // `amount` ... the proportion of the conversion. A value of 1 is completely inverted. A value of 0 leaves the input unchanged. invert: function(args) { var amount = _.isFinite(args.amount) ? args.amount : 1; return _.template('<filter><feComponentTransfer><feFuncR type="table" tableValues="${amount} ${amount2}"/><feFuncG type="table" tableValues="${amount} ${amount2}"/><feFuncB type="table" tableValues="${amount} ${amount2}"/></feComponentTransfer></filter>', { amount: amount, amount2: 1 - amount }); }, // `amount` ... proportion of the conversion. A value of 0 will create an image that is completely black. A value of 1 leaves the input unchanged. brightness: function(args) { return _.template('<filter><feComponentTransfer><feFuncR type="linear" slope="${amount}"/><feFuncG type="linear" slope="${amount}"/><feFuncB type="linear" slope="${amount}"/></feComponentTransfer></filter>', { amount: _.isFinite(args.amount) ? args.amount : 1 }); }, // `amount` ... proportion of the conversion. A value of 0 will create an image that is completely black. A value of 1 leaves the input unchanged. contrast: function(args) { var amount = _.isFinite(args.amount) ? args.amount : 1; return _.template('<filter><feComponentTransfer><feFuncR type="linear" slope="${amount}" intercept="${amount2}"/><feFuncG type="linear" slope="${amount}" intercept="${amount2}"/><feFuncB type="linear" slope="${amount}" intercept="${amount2}"/></feComponentTransfer></filter>', { amount: amount, amount2: .5 - amount / 2 }); } }, format: { // Formatting numbers via the Python Format Specification Mini-language. // See http://docs.python.org/release/3.1.3/library/string.html#format-specification-mini-language. // Heavilly inspired by the D3.js library implementation. number: function(specifier, value, locale) { locale = locale || { currency: ['$', ''], decimal: '.', thousands: ',', grouping: [3] }; // See Python format specification mini-language: http://docs.python.org/release/3.1.3/library/string.html#format-specification-mini-language. // [[fill]align][sign][symbol][0][width][,][.precision][type] var re = /(?:([^{])?([<>=^]))?([+\- ])?([$#])?(0)?(\d+)?(,)?(\.-?\d+)?([a-z%])?/i; var match = re.exec(specifier); var fill = match[1] || ' '; var align = match[2] || '>'; var sign = match[3] || ''; var symbol = match[4] || ''; var zfill = match[5]; var width = +match[6]; var comma = match[7]; var precision = match[8]; var type = match[9]; var scale = 1; var prefix = ''; var suffix = ''; var integer = false; if (precision) precision = +precision.substring(1); if (zfill || fill === '0' && align === '=') { zfill = fill = '0'; align = '='; if (comma) width -= Math.floor((width - 1) / 4); } switch (type) { case 'n': comma = true; type = 'g'; break; case '%': scale = 100; suffix = '%'; type = 'f'; break; case 'p': scale = 100; suffix = '%'; type = 'r'; break; case 'b': case 'o': case 'x': case 'X': if (symbol === '#') prefix = '0' + type.toLowerCase(); case 'c': case 'd': integer = true; precision = 0; break; case 's': scale = -1; type = 'r'; break; } if (symbol === '$') { prefix = locale.currency[0]; suffix = locale.currency[1]; } // If no precision is specified for `'r'`, fallback to general notation. if (type == 'r' && !precision) type = 'g'; // Ensure that the requested precision is in the supported range. if (precision != null) { if (type == 'g') precision = Math.max(1, Math.min(21, precision)); else if (type == 'e' || type == 'f') precision = Math.max(0, Math.min(20, precision)); } var zcomma = zfill && comma; // Return the empty string for floats formatted as ints. if (integer && (value % 1)) return ''; // Convert negative to positive, and record the sign prefix. var negative = value < 0 || value === 0 && 1 / value < 0 ? (value = -value, '-') : sign; var fullSuffix = suffix; // Apply the scale, computing it from the value's exponent for si format. // Preserve the existing suffix, if any, such as the currency symbol. if (scale < 0) { var unit = this.prefix(value, precision); value = unit.scale(value); fullSuffix = unit.symbol + suffix; } else { value *= scale; } // Convert to the desired precision. value = this.convert(type, value, precision); // Break the value into the integer part (before) and decimal part (after). var i = value.lastIndexOf('.'); var before = i < 0 ? value : value.substring(0, i); var after = i < 0 ? '' : locale.decimal + value.substring(i + 1); function formatGroup(value) { var i = value.length; var t = []; var j = 0; var g = locale.grouping[0]; while (i > 0 && g > 0) { t.push(value.substring(i -= g, i + g)); g = locale.grouping[j = (j + 1) % locale.grouping.length]; } return t.reverse().join(locale.thousands); } // If the fill character is not `'0'`, grouping is applied before padding. if (!zfill && comma && locale.grouping) { before = formatGroup(before); } var length = prefix.length + before.length + after.length + (zcomma ? 0 : negative.length); var padding = length < width ? new Array(length = width - length + 1).join(fill) : ''; // If the fill character is `'0'`, grouping is applied after padding. if (zcomma) before = formatGroup(padding + before); // Apply prefix. negative += prefix; // Rejoin integer and decimal parts. value = before + after; return (align === '<' ? negative + value + padding : align === '>' ? padding + negative + value : align === '^' ? padding.substring(0, length >>= 1) + negative + value + padding.substring(length) : negative + (zcomma ? value : padding + value)) + fullSuffix; }, // Formatting string via the Python Format string. // See https://docs.python.org/2/library/string.html#format-string-syntax) string: function(formatString, value) { var fieldDelimiterIndex; var fieldDelimiter = '{'; var endPlaceholder = false; var formattedStringArray = []; while ((fieldDelimiterIndex = formatString.indexOf(fieldDelimiter)) !== -1) { var pieceFormatedString, formatSpec, fieldName; pieceFormatedString = formatString.slice(0, fieldDelimiterIndex); if (endPlaceholder) { formatSpec = pieceFormatedString.split(':'); fieldName = formatSpec.shift().split('.'); pieceFormatedString = value; for (var i = 0; i < fieldName.length; i++) pieceFormatedString = pieceFormatedString[fieldName[i]]; if (formatSpec.length) pieceFormatedString = this.number(formatSpec, pieceFormatedString); } formattedStringArray.push(pieceFormatedString); formatString = formatString.slice(fieldDelimiterIndex + 1); fieldDelimiter = (endPlaceholder = !endPlaceholder) ? '}' : '{'; } formattedStringArray.push(formatString); return formattedStringArray.join(''); }, convert: function(type, value, precision) { switch (type) { case 'b': return value.toString(2); case 'c': return String.fromCharCode(value); case 'o': return value.toString(8); case 'x': return value.toString(16); case 'X': return value.toString(16).toUpperCase(); case 'g': return value.toPrecision(precision); case 'e': return value.toExponential(precision); case 'f': return value.toFixed(precision); case 'r': return (value = this.round(value, this.precision(value, precision))).toFixed(Math.max(0, Math.min(20, this.precision(value * (1 + 1e-15), precision)))); default: return value + ''; } }, round: function(value, precision) { return precision ? Math.round(value * (precision = Math.pow(10, precision))) / precision : Math.round(value); }, precision: function(value, precision) { return precision - (value ? Math.ceil(Math.log(value) / Math.LN10) : 1); }, prefix: function(value, precision) { var prefixes = _.map(['y', 'z', 'a', 'f', 'p', 'n', 'µ', 'm', '', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'], function(d, i) { var k = Math.pow(10, abs(8 - i) * 3); return { scale: i > 8 ? function(d) { return d / k; } : function(d) { return d * k; }, symbol: d }; }); var i = 0; if (value) { if (value < 0) value *= -1; if (precision) value = this.round(value, this.precision(value, precision)); i = 1 + Math.floor(1e-12 + Math.log(value) / Math.LN10); i = Math.max(-24, Math.min(24, Math.floor((i <= 0 ? i + 1 : i - 1) / 3) * 3)); } return prefixes[8 + i / 3]; } } } }; // JointJS, the JavaScript diagramming library. // (c) 2011-2013 client IO joint.dia.GraphCells = Backbone.Collection.extend({ initialize: function() { // Backbone automatically doesn't trigger re-sort if models attributes are changed later when // they're already in the collection. Therefore, we're triggering sort manually here. this.on('change:z', this.sort, this); }, model: function(attrs, options) { if (attrs.type === 'link') { return new joint.dia.Link(attrs, options); } var module = attrs.type.split('.')[0]; var entity = attrs.type.split('.')[1]; if (joint.shapes[module] && joint.shapes[module][entity]) { return new joint.shapes[module][entity](attrs, options); } return new joint.dia.Element(attrs, options); }, // `comparator` makes it easy to sort cells based on their `z` index. comparator: function(model) { return model.get('z') || 0; }, // Get all inbound and outbound links connected to the cell `model`. getConnectedLinks: function(model, opt) { opt = opt || {}; if (_.isUndefined(opt.inbound) && _.isUndefined(opt.outbound)) { opt.inbound = opt.outbound = true; } var links = this.filter(function(cell) { var source = cell.get('source'); var target = cell.get('target'); return (source && source.id === model.id && opt.outbound) || (target && target.id === model.id && opt.inbound); }); // option 'deep' returns all links that are connected to any of the descendent cell // and are not descendents itself if (opt.deep) { var embeddedCells = model.getEmbeddedCells({ deep: true }); _.each(this.difference(links, embeddedCells), function(cell) { if (opt.outbound) { var source = cell.get('source'); if (source && source.id && _.find(embeddedCells, { id: source.id })) { links.push(cell); return; // prevent a loop link to be pushed twice } } if (opt.inbound) { var target = cell.get('target'); if (target && target.id && _.find(embeddedCells, { id: target.id })) { links.push(cell); } } }); } return links; }, getCommonAncestor: function(/* cells */) { var cellsAncestors = _.map(arguments, function(cell) { var ancestors = [cell.id]; var parentId = cell.get('parent'); while (parentId) { ancestors.push(parentId); parentId = this.get(parentId).get('parent'); } return ancestors; }, this); cellsAncestors = _.sortBy(cellsAncestors, 'length'); var commonAncestor = _.find(cellsAncestors.shift(), function(ancestor) { return _.every(cellsAncestors, function(cellAncestors) { return _.contains(cellAncestors, ancestor); }); }); return this.get(commonAncestor); }, // Return the bounding box of all cells in array provided. If no array // provided returns bounding box of all cells. Links are being ignored. getBBox: function(cells) { cells = cells || this.models; var origin = { x: Infinity, y: Infinity }; var corner = { x: -Infinity, y: -Infinity }; _.each(cells, function(cell) { // Links has no bounding box defined on the model. if (cell.isLink()) return; var bbox = cell.getBBox(); origin.x = Math.min(origin.x, bbox.x); origin.y = Math.min(origin.y, bbox.y); corner.x = Math.max(corner.x, bbox.x + bbox.width); corner.y = Math.max(corner.y, bbox.y + bbox.height); }); return g.rect(origin.x, origin.y, corner.x - origin.x, corner.y - origin.y); } }); joint.dia.Graph = Backbone.Model.extend({ initialize: function(attrs, opt) { // Passing `cellModel` function in the options object to graph allows for // setting models based on attribute objects. This is especially handy // when processing JSON graphs that are in a different than JointJS format. this.set('cells', new joint.dia.GraphCells([], { model: opt && opt.cellModel })); // Make all the events fired in the `cells` collection available. // to the outside world. this.get('cells').on('all', this.trigger, this); this.get('cells').on('remove', this.removeCell, this); }, toJSON: function() { // Backbone does not recursively call `toJSON()` on attributes that are themselves models/collections. // It just clones the attributes. Therefore, we must call `toJSON()` on the cells collection explicitely. var json = Backbone.Model.prototype.toJSON.apply(this, arguments); json.cells = this.get('cells').toJSON(); return json; }, fromJSON: function(json, opt) { if (!json.cells) { throw new Error('Graph JSON must contain cells array.'); } this.set(_.omit(json, 'cells'), opt); this.resetCells(json.cells, opt); }, clear: function(opt) { this.trigger('batch:start'); this.get('cells').remove(this.get('cells').models, opt); this.trigger('batch:stop'); }, _prepareCell: function(cell) { if (cell instanceof Backbone.Model && _.isUndefined(cell.get('z'))) { cell.set('z', this.maxZIndex() + 1, { silent: true }); } else if (_.isUndefined(cell.z)) { cell.z = this.maxZIndex() + 1; } return cell; }, maxZIndex: function() { var lastCell = this.get('cells').last(); return lastCell ? (lastCell.get('z') || 0) : 0; }, addCell: function(cell, options) { if (_.isArray(cell)) { return this.addCells(cell, options); } this.get('cells').add(this._prepareCell(cell), options || {}); return this; }, addCells: function(cells, options) { options = options || {}; options.position = cells.length; _.each(cells, function(cell) { options.position--; this.addCell(cell, options); }, this); return this; }, // When adding a lot of cells, it is much more efficient to // reset the entire cells collection in one go. // Useful for bulk operations and optimizations. resetCells: function(cells, opt) { this.get('cells').reset(_.map(cells, this._prepareCell, this), opt); return this; }, removeCell: function(cell, collection, options) { // Applications might provide a `disconnectLinks` option set to `true` in order to // disconnect links when a cell is removed rather then removing them. The default // is to remove all the associated links. if (options && options.disconnectLinks) { this.disconnectLinks(cell, options); } else { this.removeLinks(cell, options); } // Silently remove the cell from the cells collection. Silently, because // `joint.dia.Cell.prototype.remove` already triggers the `remove` event which is // then propagated to the graph model. If we didn't remove the cell silently, two `remove` events // would be triggered on the graph model. this.get('cells').remove(cell, { silent: true }); }, // Get a cell by `id`. getCell: function(id) { return this.get('cells').get(id); }, getElements: function() { return this.get('cells').filter(function(cell) { return cell instanceof joint.dia.Element; }); }, getLinks: function() { return this.get('cells').filter(function(cell) { return cell instanceof joint.dia.Link; }); }, // Get all inbound and outbound links connected to the cell `model`. getConnectedLinks: function(model, opt) { return this.get('cells').getConnectedLinks(model, opt); }, getNeighbors: function(el) { var links = this.getConnectedLinks(el); var neighbors = []; var cells = this.get('cells'); _.each(links, function(link) { var source = link.get('source'); var target = link.get('target'); // Discard if it is a point. if (!source.x) { var sourceElement = cells.get(source.id); if (sourceElement !== el) { neighbors.push(sourceElement); } } if (!target.x) { var targetElement = cells.get(target.id); if (targetElement !== el) { neighbors.push(targetElement); } } }); return neighbors; }, // Disconnect links connected to the cell `model`. disconnectLinks: function(model, options) { _.each(this.getConnectedLinks(model), function(link) { link.set(link.get('source').id === model.id ? 'source' : 'target', g.point(0, 0), options); }); }, // Remove links connected to the cell `model` completely. removeLinks: function(model, options) { _.invoke(this.getConnectedLinks(model), 'remove', options); }, // Find all views at given point findModelsFromPoint: function(p) { return _.filter(this.getElements(), function(el) { return el.getBBox().containsPoint(p); }); }, // Find all views in given area findModelsInArea: function(r) { return _.filter(this.getElements(), function(el) { return el.getBBox().intersect(r); }); }, // Return the bounding box of all `elements`. getBBox: function(/* elements */) { var collection = this.get('cells'); return collection.getBBox.apply(collection, arguments); }, getCommonAncestor: function(/* cells */) { var collection = this.get('cells'); return collection.getCommonAncestor.apply(collection, arguments); } }); // JointJS. // (c) 2011-2013 client IO // joint.dia.Cell base model. // -------------------------- joint.dia.Cell = Backbone.Model.extend({ // This is the same as Backbone.Model with the only difference that is uses _.merge // instead of just _.extend. The reason is that we want to mixin attributes set in upper classes. constructor: function(attributes, options) { var defaults; var attrs = attributes || {}; this.cid = _.uniqueId('c'); this.attributes = {}; if (options && options.collection) this.collection = options.collection; if (options && options.parse) attrs = this.parse(attrs, options) || {}; if (defaults = _.result(this, 'defaults')) { //<custom code> // Replaced the call to _.defaults with _.merge. attrs = _.merge({}, defaults, attrs); //</custom code> } this.set(attrs, options); this.changed = {}; this.initialize.apply(this, arguments); }, toJSON: function() { var defaultAttrs = this.constructor.prototype.defaults.attrs || {}; var attrs = this.attributes.attrs; var finalAttrs = {}; // Loop through all the attributes and // omit the default attributes as they are implicitly reconstructable by the cell 'type'. _.each(attrs, function(attr, selector) { var defaultAttr = defaultAttrs[selector]; _.each(attr, function(value, name) { // attr is mainly flat though it might have one more level (consider the `style` attribute). // Check if the `value` is object and if yes, go one level deep. if (_.isObject(value) && !_.isArray(value)) { _.each(value, function(value2, name2) { if (!defaultAttr || !defaultAttr[name] || !_.isEqual(defaultAttr[name][name2], value2)) { finalAttrs[selector] = finalAttrs[selector] || {}; (finalAttrs[selector][name] || (finalAttrs[selector][name] = {}))[name2] = value2; } }); } else if (!defaultAttr || !_.isEqual(defaultAttr[name], value)) { // `value` is not an object, default attribute for such a selector does not exist // or it is different than the attribute value set on the model. finalAttrs[selector] = finalAttrs[selector] || {}; finalAttrs[selector][name] = value; } }); }); var attributes = _.cloneDeep(_.omit(this.attributes, 'attrs')); //var attributes = JSON.parse(JSON.stringify(_.omit(this.attributes, 'attrs'))); attributes.attrs = finalAttrs; return attributes; }, initialize: function(options) { if (!options || !options.id) { this.set('id', joint.util.uuid(), { silent: true }); } this._transitionIds = {}; // Collect ports defined in `attrs` and keep collecting whenever `attrs` object changes. this.processPorts(); this.on('change:attrs', this.processPorts, this); }, processPorts: function() { // Whenever `attrs` changes, we extract ports from the `attrs` object and store it // in a more accessible way. Also, if any port got removed and there were links that had `target`/`source` // set to that port, we remove those links as well (to follow the same behaviour as // with a removed element). var previousPorts = this.ports; // Collect ports from the `attrs` object. var ports = {}; _.each(this.get('attrs'), function(attrs, selector) { if (attrs && attrs.port) { // `port` can either be directly an `id` or an object containing an `id` (and potentially other data). if (!_.isUndefined(attrs.port.id)) { ports[attrs.port.id] = attrs.port; } else { ports[attrs.port] = { id: attrs.port }; } } }); // Collect ports that have been removed (compared to the previous ports) - if any. // Use hash table for quick lookup. var removedPorts = {}; _.each(previousPorts, function(port, id) { if (!ports[id]) removedPorts[id] = true; }); // Remove all the incoming/outgoing links that have source/target port set to any of the removed ports. if (this.collection && !_.isEmpty(removedPorts)) { var inboundLinks = this.collection.getConnectedLinks(this, { inbound: true }); _.each(inboundLinks, function(link) { if (removedPorts[link.get('target').port]) link.remove(); }); var outboundLinks = this.collection.getConnectedLinks(this, { outbound: true }); _.each(outboundLinks, function(link) { if (removedPorts[link.get('source').port]) link.remove(); }); } // Update the `ports` object. this.ports = ports; }, remove: function(opt) { opt = opt || {}; var collection = this.collection; if (collection) { collection.trigger('batch:start', { batchName: 'remove' }); } // First, unembed this cell from its parent cell if there is one. var parentCellId = this.get('parent'); if (parentCellId) { var parentCell = this.collection && this.collection.get(parentCellId); parentCell.unembed(this); } _.invoke(this.getEmbeddedCells(), 'remove', opt); this.trigger('remove', this, this.collection, opt); if (collection) { collection.trigger('batch:stop', { batchName: 'remove' }); } return this; }, toFront: function(opt) { if (this.collection) { opt = opt || {}; var z = (this.collection.last().get('z') || 0) + 1; this.trigger('batch:start', { batchName: 'to-front' }).set('z', z, opt); if (opt.deep) { var cells = this.getEmbeddedCells({ deep: true, breadthFirst: true }); _.each(cells, function(cell) { cell.set('z', ++z, opt); }); } this.trigger('batch:stop', { batchName: 'to-front' }); } return this; }, toBack: function(opt) { if (this.collection) { opt = opt || {}; var z = (this.collection.first().get('z') || 0) - 1; this.trigger('batch:start', { batchName: 'to-back' }); if (opt.deep) { var cells = this.getEmbeddedCells({ deep: true, breadthFirst: true }); _.eachRight(cells, function(cell) { cell.set('z', z--, opt); }); } this.set('z', z, opt).trigger('batch:stop', { batchName: 'to-back' }); } return this; }, embed: function(cell, opt) { if (this == cell || this.isEmbeddedIn(cell)) { throw new Error('Recursive embedding not allowed.'); } else { this.trigger('batch:start', { batchName: 'embed' }); var embeds = _.clone(this.get('embeds') || []); // We keep all element ids after links ids. embeds[cell.isLink() ? 'unshift' : 'push'](cell.id); cell.set('parent', this.id, opt); this.set('embeds', _.uniq(embeds), opt); this.trigger('batch:stop', { batchName: 'embed' }); } return this; }, unembed: function(cell, opt) { this.trigger('batch:start', { batchName: 'unembed' }); cell.unset('parent', opt); this.set('embeds', _.without(this.get('embeds'), cell.id), opt); this.trigger('batch:stop', { batchName: 'unembed' }); return this; }, // Return an array of ancestor cells. // The array is ordered from the parent of the cell // to the most distant ancestor. getAncestors: function() { var ancestors = []; var parentId = this.get('parent'); if (this.collection === undefined) return ancestors; while (parentId !== undefined) { var parent = this.collection.get(parentId); if (parent !== undefined) { ancestors.push(parent); parentId = parent.get('parent'); } else { break; } } return ancestors; }, getEmbeddedCells: function(opt) { opt = opt || {}; // Cell models can only be retrieved when this element is part of a collection. // There is no way this element knows about other cells otherwise. // This also means that calling e.g. `translate()` on an element with embeds before // adding it to a graph does not translate its embeds. if (this.collection) { var cells; if (opt.deep) { if (opt.breadthFirst) { // breadthFirst algorithm cells = []; var queue = this.getEmbeddedCells(); while (queue.length > 0) { var parent = queue.shift(); cells.push(parent); queue.push.apply(queue, parent.getEmbeddedCells()); } } else { // depthFirst algorithm cells = this.getEmbeddedCells(); _.each(cells, function(cell) { cells.push.apply(cells, cell.getEmbeddedCells(opt)); }); } } else { cells = _.map(this.get('embeds'), this.collection.get, this.collection); } return cells; } return []; }, isEmbeddedIn: function(cell, opt) { var cellId = _.isString(cell) ? cell : cell.id; var parentId = this.get('parent'); opt = _.defaults({ deep: true }, opt); // See getEmbeddedCells(). if (this.collection && opt.deep) { while (parentId) { if (parentId == cellId) { return true; } parentId = this.collection.get(parentId).get('parent'); } return false; } else { // When this cell is not part of a collection check // at least whether it's a direct child of given cell. return parentId == cellId; } }, clone: function(opt) { opt = opt || {}; var clone = Backbone.Model.prototype.clone.apply(this, arguments); // We don't want the clone to have the same ID as the original. clone.set('id', joint.util.uuid(), { silent: true }); clone.set('embeds', ''); if (!opt.deep) return clone; // The rest of the `clone()` method deals with embeds. If `deep` option is set to `true`, // the return value is an array of all the embedded clones created. var embeds = _.sortBy(this.getEmbeddedCells(), function(cell) { // Sort embeds that links come before elements. return cell instanceof joint.dia.Element; }); var clones = [clone]; // This mapping stores cloned links under the `id`s of they originals. // This prevents cloning a link more then once. Consider a link 'self loop' for example. var linkCloneMapping = {}; _.each(embeds, function(embed) { var embedClones = embed.clone({ deep: true }); // Embed the first clone returned from `clone({ deep: true })` above. The first // cell is always the clone of the cell that called the `clone()` method, i.e. clone of `embed` in this case. clone.embed(embedClones[0]); _.each(embedClones, function(embedClone) { if (embedClone instanceof joint.dia.Link) { if (embedClone.get('source').id == this.id) { embedClone.prop('source', { id: clone.id }); } if (embedClone.get('target').id == this.id) { embedClone.prop('target', { id: clone.id }); } linkCloneMapping[embed.id] = embedClone; // Skip links. Inbound/outbound links are not relevant for them. return; } clones.push(embedClone); // Collect all inbound links, clone them (if not done already) and set their target to the `embedClone.id`. var inboundLinks = this.collection.getConnectedLinks(embed, { inbound: true }); _.each(inboundLinks, function(link) { var linkClone = linkCloneMapping[link.id] || link.clone(); // Make sure we don't clone a link more then once. linkCloneMapping[link.id] = linkClone; linkClone.prop('target', { id: embedClone.id }); }); // Collect all inbound links, clone them (if not done already) and set their source to the `embedClone.id`. var outboundLinks = this.collection.getConnectedLinks(embed, { outbound: true }); _.each(outboundLinks, function(link) { var linkClone = linkCloneMapping[link.id] || link.clone(); // Make sure we don't clone a link more then once. linkCloneMapping[link.id] = linkClone; linkClone.prop('source', { id: embedClone.id }); }); }, this); }, this); // Add link clones to the array of all the new clones. clones = clones.concat(_.values(linkCloneMapping)); return clones; }, // A convenient way to set nested properties. // This method merges the properties you'd like to set with the ones // stored in the cell and makes sure change events are properly triggered. // You can either set a nested property with one object // or use a property path. // The most simple use case is: // `cell.prop('name/first', 'John')` or // `cell.prop({ name: { first: 'John' } })`. // Nested arrays are supported too: // `cell.prop('series/0/data/0/degree', 50)` or // `cell.prop({ series: [ { data: [ { degree: 50 } ] } ] })`. prop: function(props, value, opt) { var delim = '/'; if (_.isString(props)) { // Get/set an attribute by a special path syntax that delimits // nested objects by the colon character. if (arguments.length > 1) { var path = props; var pathArray = path.split('/'); var property = pathArray[0]; opt = opt || {}; opt.propertyPath = path; opt.propertyValue = value; if (pathArray.length == 1) { // Property is not nested. We can simply use `set()`. return this.set(property, value, opt); } var update = {}; // Initialize the nested object. Subobjects are either arrays or objects. // An empty array is created if the sub-key is an integer. Otherwise, an empty object is created. // Note that this imposes a limitation on object keys one can use with Inspector. // Pure integer keys will cause issues and are therefore not allowed. var initializer = update; var prevProperty = property; _.each(_.rest(pathArray), function(key) { initializer = initializer[prevProperty] = (_.isFinite(Number(key)) ? [] : {}); prevProperty = key; }); // Fill update with the `value` on `path`. update = joint.util.setByPath(update, path, value, '/'); var baseAttributes = _.merge({}, this.attributes); // if rewrite mode enabled, we replace value referenced by path with // the new one (we don't merge). opt.rewrite && joint.util.unsetByPath(baseAttributes, path, '/'); // Merge update with the model attributes. var attributes = _.merge(baseAttributes, update); // Finally, set the property to the updated attributes. return this.set(property, attributes[property], opt); } else { return joint.util.getByPath(this.attributes, props, delim); } } return this.set(_.merge({}, this.attributes, props), value); }, // A convient way to unset nested properties removeProp: function(path, opt) { // Once a property is removed from the `attrs` attribute // the cellView will recognize a `dirty` flag and rerender itself // in order to remove the attribute from SVG element. opt = opt || {}; opt.dirty = true; var pathArray = path.split('/'); if (pathArray.length === 1) { // A top level property return this.unset(path, opt); } // A nested property var property = pathArray[0]; var nestedPath = pathArray.slice(1).join('/'); var propertyValue = _.merge({}, this.get(property)); joint.util.unsetByPath(propertyValue, nestedPath, '/'); return this.set(property, propertyValue, opt); }, // A convenient way to set nested attributes. attr: function(attrs, value, opt) { var args = Array.prototype.slice.call(arguments); if (_.isString(attrs)) { // Get/set an attribute by a special path syntax that delimits // nested objects by the colon character. args[0] = 'attrs/' + attrs; } else { args[0] = { 'attrs' : attrs }; } return this.prop.apply(this, args); }, // A convenient way to unset nested attributes removeAttr: function(path, opt) { if (_.isArray(path)) { _.each(path, function(p) { this.removeAttr(p, opt); }, this); return this; } return this.removeProp('attrs/' + path, opt); }, transition: function(path, value, opt, delim) { delim = delim || '/'; var defaults = { duration: 100, delay: 10, timingFunction: joint.util.timing.linear, valueFunction: joint.util.interpolate.number }; opt = _.extend(defaults, opt); var firstFrameTime = 0; var interpolatingFunction; var setter = _.bind(function(runtime) { var id, progress, propertyValue, status; firstFrameTime = firstFrameTime || runtime; runtime -= firstFrameTime; progress = runtime / opt.duration; if (progress < 1) { this._transitionIds[path] = id = joint.util.nextFrame(setter); } else { progress = 1; delete this._transitionIds[path]; } propertyValue = interpolatingFunction(opt.timingFunction(progress)); opt.transitionId = id; this.prop(path, propertyValue, opt); if (!id) this.trigger('transition:end', this, path); }, this); var initiator = _.bind(function(callback) { this.stopTransitions(path); interpolatingFunction = opt.valueFunction(joint.util.getByPath(this.attributes, path, delim), value); this._transitionIds[path] = joint.util.nextFrame(callback); this.trigger('transition:start', this, path); }, this); return _.delay(initiator, opt.delay, setter); }, getTransitions: function() { return _.keys(this._transitionIds); }, stopTransitions: function(path, delim) { delim = delim || '/'; var pathArray = path && path.split(delim); _(this._transitionIds).keys().filter(pathArray && function(key) { return _.isEqual(pathArray, key.split(delim).slice(0, pathArray.length)); }).each(function(key) { joint.util.cancelFrame(this._transitionIds[key]); delete this._transitionIds[key]; this.trigger('transition:end', this, key); }, this); return this; }, // A shorcut making it easy to create constructs like the following: // `var el = (new joint.shapes.basic.Rect).addTo(graph)`. addTo: function(graph, opt) { graph.addCell(this, opt); return this; }, // A shortcut for an equivalent call: `paper.findViewByModel(cell)` // making it easy to create constructs like the following: // `cell.findView(paper).highlight()` findView: function(paper) { return paper.findViewByModel(this); }, isLink: function() { return false; } }); // joint.dia.CellView base view and controller. // -------------------------------------------- // This is the base view and controller for `joint.dia.ElementView` and `joint.dia.LinkView`. joint.dia.CellView = Backbone.View.extend({ tagName: 'g', attributes: function() { return { 'model-id': this.model.id }; }, constructor: function(options) { this._configure(options); Backbone.View.apply(this, arguments); }, _configure: function(options) { if (this.options) options = _.extend({}, _.result(this, 'options'), options); this.options = options; // Make sure a global unique id is assigned to this view. Store this id also to the properties object. // The global unique id makes sure that the same view can be rendered on e.g. different machines and // still be associated to the same object among all those clients. This is necessary for real-time // collaboration mechanism. this.options.id = this.options.id || joint.util.guid(this); }, initialize: function() { _.bindAll(this, 'remove', 'update'); // Store reference to this to the <g> DOM element so that the view is accessible through the DOM tree. this.$el.data('view', this); this.listenTo(this.model, 'remove', this.remove); this.listenTo(this.model, 'change:attrs', this.onChangeAttrs); }, onChangeAttrs: function(cell, attrs, opt) { if (opt.dirty) { // dirty flag could be set when a model attribute was removed and it needs to be cleared // also from the DOM element. See cell.removeAttr(). return this.render(); } return this.update(); }, // Override the Backbone `_ensureElement()` method in order to create a `<g>` node that wraps // all the nodes of the Cell view. _ensureElement: function() { var el; if (!this.el) { var attrs = _.extend({ id: this.id }, _.result(this, 'attributes')); if (this.className) attrs['class'] = _.result(this, 'className'); el = V(_.result(this, 'tagName'), attrs).node; } else { el = _.result(this, 'el'); } this.setElement(el, false); }, // Utilize an alternative DOM manipulation API by // adding an element reference wrapped in Vectorizer. _setElement: function(el) { this.$el = el instanceof Backbone.$ ? el : Backbone.$(el); this.el = this.$el[0]; this.vel = V(this.el); }, findBySelector: function(selector) { // These are either descendants of `this.$el` of `this.$el` itself. // `.` is a special selector used to select the wrapping `<g>` element. var $selected = selector === '.' ? this.$el : this.$el.find(selector); return $selected; }, notify: function(evt) { if (this.paper) { var args = Array.prototype.slice.call(arguments, 1); // Trigger the event on both the element itself and also on the paper. this.trigger.apply(this, [evt].concat(args)); // Paper event handlers receive the view object as the first argument. this.paper.trigger.apply(this.paper, [evt, this].concat(args)); } }, getStrokeBBox: function(el) { // Return a bounding box rectangle that takes into account stroke. // Note that this is a naive and ad-hoc implementation that does not // works only in certain cases and should be replaced as soon as browsers will // start supporting the getStrokeBBox() SVG method. // @TODO any better solution is very welcome! var isMagnet = !!el; el = el || this.el; var bbox = V(el).bbox(false, this.paper.viewport); var strokeWidth; if (isMagnet) { strokeWidth = V(el).attr('stroke-width'); } else { strokeWidth = this.model.attr('rect/stroke-width') || this.model.attr('circle/stroke-width') || this.model.attr('ellipse/stroke-width') || this.model.attr('path/stroke-width'); } strokeWidth = parseFloat(strokeWidth) || 0; return g.rect(bbox).moveAndExpand({ x: -strokeWidth / 2, y: -strokeWidth / 2, width: strokeWidth, height: strokeWidth }); }, getBBox: function() { return g.rect(this.vel.bbox()); }, highlight: function(el, opt) { el = !el ? this.el : this.$(el)[0] || this.el; // set partial flag if the highlighted element is not the entire view. opt = opt || {}; opt.partial = el != this.el; this.notify('cell:highlight', el, opt); return this; }, unhighlight: function(el, opt) { el = !el ? this.el : this.$(el)[0] || this.el; opt = opt || {}; opt.partial = el != this.el; this.notify('cell:unhighlight', el, opt); return this; }, // Find the closest element that has the `magnet` attribute set to `true`. If there was not such // an element found, return the root element of the cell view. findMagnet: function(el) { var $el = this.$(el); if ($el.length === 0 || $el[0] === this.el) { // If the overall cell has set `magnet === false`, then return `undefined` to // announce there is no magnet found for this cell. // This is especially useful to set on cells that have 'ports'. In this case, // only the ports have set `magnet === true` and the overall element has `magnet === false`. var attrs = this.model.get('attrs') || {}; if (attrs['.'] && attrs['.']['magnet'] === false) { return undefined; } return this.el; } if ($el.attr('magnet')) { return $el[0]; } return this.findMagnet($el.parent()); }, // `selector` is a CSS selector or `'.'`. `filter` must be in the special JointJS filter format: // `{ name: <name of the filter>, args: { <arguments>, ... }`. // An example is: `{ filter: { name: 'blur', args: { radius: 5 } } }`. applyFilter: function(selector, filter) { var $selected = _.isString(selector) ? this.findBySelector(selector) : $(selector); // Generate a hash code from the stringified filter definition. This gives us // a unique filter ID for different definitions. var filterId = filter.name + this.paper.svg.id + joint.util.hashCode(JSON.stringify(filter)); // If the filter already exists in the document, // we're done and we can just use it (reference it using `url()`). // If not, create one. if (!this.paper.svg.getElementById(filterId)) { var filterSVGString = joint.util.filter[filter.name] && joint.util.filter[filter.name](filter.args || {}); if (!filterSVGString) { throw new Error('Non-existing filter ' + filter.name); } var filterElement = V(filterSVGString); // Set the filter area to be 3x the bounding box of the cell // and center the filter around the cell. filterElement.attr({ filterUnits: 'objectBoundingBox', x: -1, y: -1, width: 3, height: 3 }); if (filter.attrs) filterElement.attr(filter.attrs); filterElement.node.id = filterId; V(this.paper.svg).defs().append(filterElement); } $selected.each(function() { V(this).attr('filter', 'url(#' + filterId + ')'); }); }, // `selector` is a CSS selector or `'.'`. `attr` is either a `'fill'` or `'stroke'`. // `gradient` must be in the special JointJS gradient format: // `{ type: <linearGradient|radialGradient>, stops: [ { offset: <offset>, color: <color> }, ... ]`. // An example is: `{ fill: { type: 'linearGradient', stops: [ { offset: '10%', color: 'green' }, { offset: '50%', color: 'blue' } ] } }`. applyGradient: function(selector, attr, gradient) { var $selected = _.isString(selector) ? this.findBySelector(selector) : $(selector); // Generate a hash code from the stringified filter definition. This gives us // a unique filter ID for different definitions. var gradientId = gradient.type + this.paper.svg.id + joint.util.hashCode(JSON.stringify(gradient)); // If the gradient already exists in the document, // we're done and we can just use it (reference it using `url()`). // If not, create one. if (!this.paper.svg.getElementById(gradientId)) { var gradientSVGString = [ '<' + gradient.type + '>', _.map(gradient.stops, function(stop) { return '<stop offset="' + stop.offset + '" stop-color="' + stop.color + '" stop-opacity="' + (_.isFinite(stop.opacity) ? stop.opacity : 1) + '" />'; }).join(''), '</' + gradient.type + '>' ].join(''); var gradientElement = V(gradientSVGString); if (gradient.attrs) { gradientElement.attr(gradient.attrs); } gradientElement.node.id = gradientId; V(this.paper.svg).defs().append(gradientElement); } $selected.each(function() { V(this).attr(attr, 'url(#' + gradientId + ')'); }); }, // Construct a unique selector for the `el` element within this view. // `prevSelector` is being collected through the recursive call. // No value for `prevSelector` is expected when using this method. getSelector: function(el, prevSelector) { if (el === this.el) { return prevSelector; } var nthChild = V(el).index() + 1; var selector = el.tagName + ':nth-child(' + nthChild + ')'; if (prevSelector) { selector += ' > ' + prevSelector; } return this.getSelector(el.parentNode, selector); }, // Interaction. The controller part. // --------------------------------- // Interaction is handled by the paper and delegated to the view in interest. // `x` & `y` parameters passed to these functions represent the coordinates already snapped to the paper grid. // If necessary, real coordinates can be obtained from the `evt` event object. // These functions are supposed to be overriden by the views that inherit from `joint.dia.Cell`, // i.e. `joint.dia.Element` and `joint.dia.Link`. pointerdblclick: function(evt, x, y) { this.notify('cell:pointerdblclick', evt, x, y); }, pointerclick: function(evt, x, y) { this.notify('cell:pointerclick', evt, x, y); }, pointerdown: function(evt, x, y) { if (this.model.collection) { this.model.trigger('batch:start', { batchName: 'pointer' }); this._collection = this.model.collection; } this.notify('cell:pointerdown', evt, x, y); }, pointermove: function(evt, x, y) { this.notify('cell:pointermove', evt, x, y); }, pointerup: function(evt, x, y) { this.notify('cell:pointerup', evt, x, y); if (this._collection) { // we don't want to trigger event on model as model doesn't // need to be member of collection anymore (remove) this._collection.trigger('batch:stop', { batchName: 'pointer' }); delete this._collection; } }, mouseover: function(evt) { this.notify('cell:mouseover', evt); }, mouseout: function(evt) { this.notify('cell:mouseout', evt); }, contextmenu: function(evt, x, y) { this.notify('cell:contextmenu', evt, x, y); } }); // JointJS library. // (c) 2011-2013 client IO // joint.dia.Element base model. // ----------------------------- joint.dia.Element = joint.dia.Cell.extend({ defaults: { position: { x: 0, y: 0 }, size: { width: 1, height: 1 }, angle: 0 }, position: function(x, y, opt) { var isSetter = _.isNumber(y); opt = (isSetter ? opt : x) || {}; // option `parentRelative` for setting the position relative to the element's parent. if (opt.parentRelative) { // Getting the parent's position requires the collection. // Cell.get('parent') helds cell id only. if (!this.collection) throw new Error('Element must be part of a collection.'); var parent = this.collection.get(this.get('parent')); var parentPosition = parent && !parent.isLink() ? parent.get('position') : { x: 0, y: 0 }; } if (isSetter) { if (opt.parentRelative) { x += parentPosition.x; y += parentPosition.y; } return this.set('position', { x: x, y: y }, opt); } else { // Getter returns a geometry point. var elementPosition = g.point(this.get('position')); return opt.parentRelative ? elementPosition.difference(parentPosition) : elementPosition; } }, translate: function(tx, ty, opt) { ty = ty || 0; if (tx === 0 && ty === 0) { // Like nothing has happened. return this; } opt = opt || {}; // Pass the initiator of the translation. opt.translateBy = opt.translateBy || this.id; // To find out by how much an element was translated in event 'change:position' handlers. opt.tx = tx; opt.ty = ty; var position = this.get('position') || { x: 0, y: 0 }; var translatedPosition = { x: position.x + tx || 0, y: position.y + ty || 0 }; if (opt.transition) { if (!_.isObject(opt.transition)) opt.transition = {}; this.transition('position', translatedPosition, _.extend({}, opt.transition, { valueFunction: joint.util.interpolate.object })); } else { this.set('position', translatedPosition, opt); // Recursively call `translate()` on all the embeds cells. _.invoke(this.getEmbeddedCells(), 'translate', tx, ty, opt); } return this; }, resize: function(width, height, opt) { this.trigger('batch:start', { batchName: 'resize' }); this.set('size', { width: width, height: height }, opt); this.trigger('batch:stop', { batchName: 'resize' }); return this; }, fitEmbeds: function(opt) { opt = opt || 0; var collection = this.collection; // Getting the children's size and position requires the collection. // Cell.get('embdes') helds an array of cell ids only. if (!collection) throw new Error('Element must be part of a collection.'); var embeddedCells = this.getEmbeddedCells(); if (embeddedCells.length > 0) { this.trigger('batch:start', { batchName: 'fit-embeds' }); if (opt.deep) { // Recursively apply fitEmbeds on all embeds first. _.invoke(embeddedCells, 'fitEmbeds', opt); } // Compute cell's size and position based on the children bbox // and given padding. var bbox = collection.getBBox(embeddedCells); var padding = joint.util.normalizeSides(opt.padding); // Apply padding computed above to the bbox. bbox.moveAndExpand({ x: - padding.left, y: - padding.top, width: padding.right + padding.left, height: padding.bottom + padding.top }); // Set new element dimensions finally. this.set({ position: { x: bbox.x, y: bbox.y }, size: { width: bbox.width, height: bbox.height } }, opt); this.trigger('batch:stop', { batchName: 'fit-embeds' }); } return this; }, // Rotate element by `angle` degrees, optionally around `origin` point. // If `origin` is not provided, it is considered to be the center of the element. // If `absolute` is `true`, the `angle` is considered is abslute, i.e. it is not // the difference from the previous angle. rotate: function(angle, absolute, origin) { if (origin) { var center = this.getBBox().center(); var size = this.get('size'); var position = this.get('position'); center.rotate(origin, this.get('angle') - angle); var dx = center.x - size.width / 2 - position.x; var dy = center.y - size.height / 2 - position.y; this.trigger('batch:start', { batchName: 'rotate' }); this.translate(dx, dy); this.rotate(angle, absolute); this.trigger('batch:stop', { batchName: 'rotate' }); } else { this.set('angle', absolute ? angle : (this.get('angle') + angle) % 360); } return this; }, getBBox: function() { var position = this.get('position'); var size = this.get('size'); return g.rect(position.x, position.y, size.width, size.height); } }); // joint.dia.Element base view and controller. // ------------------------------------------- joint.dia.ElementView = joint.dia.CellView.extend({ SPECIAL_ATTRIBUTES: [ 'style', 'text', 'html', 'ref-x', 'ref-y', 'ref-dx', 'ref-dy', 'ref-width', 'ref-height', 'ref', 'x-alignment', 'y-alignment', 'port' ], className: function() { return 'element ' + this.model.get('type').replace('.', ' ', 'g'); }, initialize: function() { _.bindAll(this, 'translate', 'resize', 'rotate'); joint.dia.CellView.prototype.initialize.apply(this, arguments); this.listenTo(this.model, 'change:position', this.translate); this.listenTo(this.model, 'change:size', this.resize); this.listenTo(this.model, 'change:angle', this.rotate); }, // Default is to process the `attrs` object and set attributes on subelements based on the selectors. update: function(cell, renderingOnlyAttrs) { var allAttrs = this.model.get('attrs'); var rotatable = this.rotatableNode; if (rotatable) { var rotation = rotatable.attr('transform'); rotatable.attr('transform', ''); } var relativelyPositioned = []; var nodesBySelector = {}; _.each(renderingOnlyAttrs || allAttrs, function(attrs, selector) { // Elements that should be updated. var $selected = this.findBySelector(selector); // No element matched by the `selector` was found. We're done then. if ($selected.length === 0) return; nodesBySelector[selector] = $selected; // Special attributes are treated by JointJS, not by SVG. var specialAttributes = this.SPECIAL_ATTRIBUTES.slice(); // If the `filter` attribute is an object, it is in the special JointJS filter format and so // it becomes a special attribute and is treated separately. if (_.isObject(attrs.filter)) { specialAttributes.push('filter'); this.applyFilter($selected, attrs.filter); } // If the `fill` or `stroke` attribute is an object, it is in the special JointJS gradient format and so // it becomes a special attribute and is treated separately. if (_.isObject(attrs.fill)) { specialAttributes.push('fill'); this.applyGradient($selected, 'fill', attrs.fill); } if (_.isObject(attrs.stroke)) { specialAttributes.push('stroke'); this.applyGradient($selected, 'stroke', attrs.stroke); } // Make special case for `text` attribute. So that we can set text content of the `<text>` element // via the `attrs` object as well. // Note that it's important to set text before applying the rest of the final attributes. // Vectorizer `text()` method sets on the element its own attributes and it has to be possible // to rewrite them, if needed. (i.e display: 'none') if (!_.isUndefined(attrs.text)) { $selected.each(function() { V(this).text(attrs.text + '', { lineHeight: attrs.lineHeight, textPath: attrs.textPath, annotations: attrs.annotations }); }); specialAttributes.push('lineHeight', 'textPath', 'annotations'); } // Set regular attributes on the `$selected` subelement. Note that we cannot use the jQuery attr() // method as some of the attributes might be namespaced (e.g. xlink:href) which fails with jQuery attr(). var finalAttributes = _.omit(attrs, specialAttributes); $selected.each(function() { V(this).attr(finalAttributes); }); // `port` attribute contains the `id` of the port that the underlying magnet represents. if (attrs.port) { $selected.attr('port', _.isUndefined(attrs.port.id) ? attrs.port : attrs.port.id); } // `style` attribute is special in the sense that it sets the CSS style of the subelement. if (attrs.style) { $selected.css(attrs.style); } if (!_.isUndefined(attrs.html)) { $selected.each(function() { $(this).html(attrs.html + ''); }); } // Special `ref-x` and `ref-y` attributes make it possible to set both absolute or // relative positioning of subelements. if (!_.isUndefined(attrs['ref-x']) || !_.isUndefined(attrs['ref-y']) || !_.isUndefined(attrs['ref-dx']) || !_.isUndefined(attrs['ref-dy']) || !_.isUndefined(attrs['x-alignment']) || !_.isUndefined(attrs['y-alignment']) || !_.isUndefined(attrs['ref-width']) || !_.isUndefined(attrs['ref-height']) ) { _.each($selected, function(el, index, list) { var $el = $(el); // copy original list selector to the element $el.selector = list.selector; relativelyPositioned.push($el); }); } }, this); // We don't want the sub elements to affect the bounding box of the root element when // positioning the sub elements relatively to the bounding box. //_.invoke(relativelyPositioned, 'hide'); //_.invoke(relativelyPositioned, 'show'); // Note that we're using the bounding box without transformation because we are already inside // a transformed coordinate system. var size = this.model.get('size'); var bbox = { x: 0, y: 0, width: size.width, height: size.height }; renderingOnlyAttrs = renderingOnlyAttrs || {}; _.each(relativelyPositioned, function($el) { // if there was a special attribute affecting the position amongst renderingOnlyAttributes // we have to merge it with rest of the element's attributes as they are necessary // to update the position relatively (i.e `ref`) var renderingOnlyElAttrs = renderingOnlyAttrs[$el.selector]; var elAttrs = renderingOnlyElAttrs ? _.merge({}, allAttrs[$el.selector], renderingOnlyElAttrs) : allAttrs[$el.selector]; this.positionRelative(V($el[0]), bbox, elAttrs, nodesBySelector); }, this); if (rotatable) { rotatable.attr('transform', rotation || ''); } }, positionRelative: function(vel, bbox, attributes, nodesBySelector) { var ref = attributes['ref']; var refDx = parseFloat(attributes['ref-dx']); var refDy = parseFloat(attributes['ref-dy']); var yAlignment = attributes['y-alignment']; var xAlignment = attributes['x-alignment']; // 'ref-y', 'ref-x', 'ref-width', 'ref-height' can be defined // by value or by percentage e.g 4, 0.5, '200%'. var refY = attributes['ref-y']; var refYPercentage = _.isString(refY) && refY.slice(-1) === '%'; refY = parseFloat(refY); if (refYPercentage) { refY /= 100; } var refX = attributes['ref-x']; var refXPercentage = _.isString(refX) && refX.slice(-1) === '%'; refX = parseFloat(refX); if (refXPercentage) { refX /= 100; } var refWidth = attributes['ref-width']; var refWidthPercentage = _.isString(refWidth) && refWidth.slice(-1) === '%'; refWidth = parseFloat(refWidth); if (refWidthPercentage) { refWidth /= 100; } var refHeight = attributes['ref-height']; var refHeightPercentage = _.isString(refHeight) && refHeight.slice(-1) === '%'; refHeight = parseFloat(refHeight); if (refHeightPercentage) { refHeight /= 100; } // Check if the node is a descendant of the scalable group. var scalable = vel.findParentByClass('scalable', this.el); // `ref` is the selector of the reference element. If no `ref` is passed, reference // element is the root element. if (ref) { var vref; if (nodesBySelector && nodesBySelector[ref]) { // First we check if the same selector has been already used. vref = V(nodesBySelector[ref][0]); } else { // Other wise we find the ref ourselves. vref = ref === '.' ? this.vel : this.vel.findOne(ref); } if (!vref) { throw new Error('dia.ElementView: reference does not exists.'); } // Get the bounding box of the reference element relative to the root `<g>` element. bbox = vref.bbox(false, this.el); } // Remove the previous translate() from the transform attribute and translate the element // relative to the root bounding box following the `ref-x` and `ref-y` attributes. if (vel.attr('transform')) { vel.attr('transform', vel.attr('transform').replace(/translate\([^)]*\)/g, '').trim() || ''); } // 'ref-width'/'ref-height' defines the width/height of the subelement relatively to // the reference element size // val in 0..1 ref-width = 0.75 sets the width to 75% of the ref. el. width // val < 0 || val > 1 ref-height = -20 sets the height to the the ref. el. height shorter by 20 if (isFinite(refWidth)) { if (refWidthPercentage || refWidth >= 0 && refWidth <= 1) { vel.attr('width', refWidth * bbox.width); } else { vel.attr('width', Math.max(refWidth + bbox.width, 0)); } } if (isFinite(refHeight)) { if (refHeightPercentage || refHeight >= 0 && refHeight <= 1) { vel.attr('height', refHeight * bbox.height); } else { vel.attr('height', Math.max(refHeight + bbox.height, 0)); } } // The final translation of the subelement. var tx = 0; var ty = 0; var scale; // `ref-dx` and `ref-dy` define the offset of the subelement relative to the right and/or bottom // coordinate of the reference element. if (isFinite(refDx)) { if (scalable) { // Compensate for the scale grid in case the elemnt is in the scalable group. scale = scale || scalable.scale(); tx = bbox.x + bbox.width + refDx / scale.sx; } else { tx = bbox.x + bbox.width + refDx; } } if (isFinite(refDy)) { if (scalable) { // Compensate for the scale grid in case the elemnt is in the scalable group. scale = scale || scalable.scale(); ty = bbox.y + bbox.height + refDy / scale.sy; } else { ty = bbox.y + bbox.height + refDy; } } // if `refX` is in [0, 1] then `refX` is a fraction of bounding box width // if `refX` is < 0 then `refX`'s absolute values is the right coordinate of the bounding box // otherwise, `refX` is the left coordinate of the bounding box // Analogical rules apply for `refY`. if (isFinite(refX)) { if (refXPercentage || refX > 0 && refX < 1) { tx = bbox.x + bbox.width * refX; } else if (scalable) { // Compensate for the scale grid in case the elemnt is in the scalable group. scale = scale || scalable.scale(); tx = bbox.x + refX / scale.sx; } else { tx = bbox.x + refX; } } if (isFinite(refY)) { if (refXPercentage || refY > 0 && refY < 1) { ty = bbox.y + bbox.height * refY; } else if (scalable) { // Compensate for the scale grid in case the elemnt is in the scalable group. scale = scale || scalable.scale(); ty = bbox.y + refY / scale.sy; } else { ty = bbox.y + refY; } } if (!_.isUndefined(yAlignment) || !_.isUndefined(xAlignment)) { var velBBox = vel.bbox(false, this.paper.viewport); // `y-alignment` when set to `middle` causes centering of the subelement around its new y coordinate. if (yAlignment === 'middle') { ty -= velBBox.height / 2; } else if (isFinite(yAlignment)) { ty += (yAlignment > -1 && yAlignment < 1) ? velBBox.height * yAlignment : yAlignment; } // `x-alignment` when set to `middle` causes centering of the subelement around its new x coordinate. if (xAlignment === 'middle') { tx -= velBBox.width / 2; } else if (isFinite(xAlignment)) { tx += (xAlignment > -1 && xAlignment < 1) ? velBBox.width * xAlignment : xAlignment; } } vel.translate(tx, ty); }, // `prototype.markup` is rendered by default. Set the `markup` attribute on the model if the // default markup is not desirable. renderMarkup: function() { var markup = this.model.markup || this.model.get('markup'); if (markup) { var nodes = V(markup); this.vel.append(nodes); } else { throw new Error('properties.markup is missing while the default render() implementation is used.'); } }, render: function() { this.$el.empty(); this.renderMarkup(); this.rotatableNode = this.vel.findOne('.rotatable'); this.scalableNode = this.vel.findOne('.scalable'); this.update(); this.resize(); this.rotate(); this.translate(); return this; }, // Scale the whole `<g>` group. Note the difference between `scale()` and `resize()` here. // `resize()` doesn't scale the whole `<g>` group but rather adjusts the `box.sx`/`box.sy` only. // `update()` is then responsible for scaling only those elements that have the `follow-scale` // attribute set to `true`. This is desirable in elements that have e.g. a `<text>` subelement // that is not supposed to be scaled together with a surrounding `<rect>` element that IS supposed // be be scaled. scale: function(sx, sy) { // TODO: take into account the origin coordinates `ox` and `oy`. this.vel.scale(sx, sy); }, resize: function() { var size = this.model.get('size') || { width: 1, height: 1 }; var angle = this.model.get('angle') || 0; var scalable = this.scalableNode; if (!scalable) { // If there is no scalable elements, than there is nothing to resize. return; } var scalableBbox = scalable.bbox(true); // Make sure `scalableBbox.width` and `scalableBbox.height` are not zero which can happen if the element does not have any content. By making // the width/height 1, we prevent HTML errors of the type `scale(Infinity, Infinity)`. scalable.attr('transform', 'scale(' + (size.width / (scalableBbox.width || 1)) + ',' + (size.height / (scalableBbox.height || 1)) + ')'); // Now the interesting part. The goal is to be able to store the object geometry via just `x`, `y`, `angle`, `width` and `height` // Order of transformations is significant but we want to reconstruct the object always in the order: // resize(), rotate(), translate() no matter of how the object was transformed. For that to work, // we must adjust the `x` and `y` coordinates of the object whenever we resize it (because the origin of the // rotation changes). The new `x` and `y` coordinates are computed by canceling the previous rotation // around the center of the resized object (which is a different origin then the origin of the previous rotation) // and getting the top-left corner of the resulting object. Then we clean up the rotation back to what it originally was. // Cancel the rotation but now around a different origin, which is the center of the scaled object. var rotatable = this.rotatableNode; var rotation = rotatable && rotatable.attr('transform'); if (rotation && rotation !== 'null') { rotatable.attr('transform', rotation + ' rotate(' + (-angle) + ',' + (size.width / 2) + ',' + (size.height / 2) + ')'); var rotatableBbox = scalable.bbox(false, this.paper.viewport); // Store new x, y and perform rotate() again against the new rotation origin. this.model.set('position', { x: rotatableBbox.x, y: rotatableBbox.y }); this.rotate(); } // Update must always be called on non-rotated element. Otherwise, relative positioning // would work with wrong (rotated) bounding boxes. this.update(); }, translate: function(model, changes, opt) { var position = this.model.get('position') || { x: 0, y: 0 }; this.vel.attr('transform', 'translate(' + position.x + ',' + position.y + ')'); }, rotate: function() { var rotatable = this.rotatableNode; if (!rotatable) { // If there is no rotatable elements, then there is nothing to rotate. return; } var angle = this.model.get('angle') || 0; var size = this.model.get('size') || { width: 1, height: 1 }; var ox = size.width / 2; var oy = size.height / 2; rotatable.attr('transform', 'rotate(' + angle + ',' + ox + ',' + oy + ')'); }, getBBox: function(opt) { if (opt && opt.useModelGeometry) { var noTransformationBBox = this.model.getBBox().bbox(this.model.get('angle')); var transformationMatrix = this.paper.viewport.getCTM(); return g.rect(V.transformRect(noTransformationBBox, transformationMatrix)); } return joint.dia.CellView.prototype.getBBox.apply(this, arguments); }, // Embedding mode methods // ---------------------- findParentsByKey: function(key) { var bbox = this.model.getBBox(); return key == 'bbox' ? this.paper.model.findModelsInArea(bbox) : this.paper.model.findModelsFromPoint(bbox[key]()); }, prepareEmbedding: function() { // Bring the model to the front with all his embeds. this.model.toFront({ deep: true, ui: true }); // Move to front also all the inbound and outbound links that are connected // to any of the element descendant. If we bring to front only embedded elements, // links connected to them would stay in the background. _.invoke(this.paper.model.getConnectedLinks(this.model, { deep: true }), 'toFront', { ui: true }); // Before we start looking for suitable parent we remove the current one. var parentId = this.model.get('parent'); parentId && this.paper.model.getCell(parentId).unembed(this.model, { ui: true }); }, processEmbedding: function(opt) { opt = opt || this.paper.options; var candidates = this.findParentsByKey(opt.findParentBy); // don't account element itself or any of its descendents candidates = _.reject(candidates, function(el) { return this.model.id == el.id || el.isEmbeddedIn(this.model); }, this); if (opt.frontParentOnly) { // pick the element with the highest `z` index candidates = candidates.slice(-1); } var newCandidateView = null; var prevCandidateView = this._candidateEmbedView; // iterate over all candidates starting from the last one (has the highest z-index). for (var i = candidates.length - 1; i >= 0; i--) { var candidate = candidates[i]; if (prevCandidateView && prevCandidateView.model.id == candidate.id) { // candidate remains the same newCandidateView = prevCandidateView; break; } else { var view = candidate.findView(this.paper); if (opt.validateEmbedding.call(this.paper, this, view)) { // flip to the new candidate newCandidateView = view; break; } } } if (newCandidateView && newCandidateView != prevCandidateView) { // A new candidate view found. Highlight the new one. prevCandidateView && prevCandidateView.unhighlight(null, { embedding: true }); this._candidateEmbedView = newCandidateView.highlight(null, { embedding: true }); } if (!newCandidateView && prevCandidateView) { // No candidate view found. Unhighlight the previous candidate. prevCandidateView.unhighlight(null, { embedding: true }); delete this._candidateEmbedView; } }, finalizeEmbedding: function() { var candidateView = this._candidateEmbedView; if (candidateView) { // We finished embedding. Candidate view is chosen to become the parent of the model. candidateView.model.embed(this.model, { ui: true }); candidateView.unhighlight(null, { embedding: true }); delete this._candidateEmbedView; } _.invoke(this.paper.model.getConnectedLinks(this.model, { deep: true }), 'reparent', { ui: true }); }, // Interaction. The controller part. // --------------------------------- pointerdown: function(evt, x, y) { // target is a valid magnet start linking if (evt.target.getAttribute('magnet') && this.paper.options.validateMagnet.call(this.paper, this, evt.target)) { this.model.trigger('batch:start', { batchName: 'add-link' }); var link = this.paper.getDefaultLink(this, evt.target); link.set({ source: { id: this.model.id, selector: this.getSelector(evt.target), port: $(evt.target).attr('port') }, target: { x: x, y: y } }); this.paper.model.addCell(link); this._linkView = this.paper.findViewByModel(link); this._linkView.pointerdown(evt, x, y); this._linkView.startArrowheadMove('target'); } else { this._dx = x; this._dy = y; joint.dia.CellView.prototype.pointerdown.apply(this, arguments); this.notify('element:pointerdown', evt, x, y); } }, pointermove: function(evt, x, y) { if (this._linkView) { // let the linkview deal with this event this._linkView.pointermove(evt, x, y); } else { var grid = this.paper.options.gridSize; var interactive = _.isFunction(this.options.interactive) ? this.options.interactive(this, 'pointermove') : this.options.interactive; if (interactive !== false) { var position = this.model.get('position'); // Make sure the new element's position always snaps to the current grid after // translate as the previous one could be calculated with a different grid size. this.model.translate( g.snapToGrid(position.x, grid) - position.x + g.snapToGrid(x - this._dx, grid), g.snapToGrid(position.y, grid) - position.y + g.snapToGrid(y - this._dy, grid) ); if (this.paper.options.embeddingMode) { if (!this._inProcessOfEmbedding) { // Prepare the element for embedding only if the pointer moves. // We don't want to do unnecessary action with the element // if an user only clicks/dblclicks on it. this.prepareEmbedding(); this._inProcessOfEmbedding = true; } this.processEmbedding(); } } this._dx = g.snapToGrid(x, grid); this._dy = g.snapToGrid(y, grid); joint.dia.CellView.prototype.pointermove.apply(this, arguments); this.notify('element:pointermove', evt, x, y); } }, pointerup: function(evt, x, y) { if (this._linkView) { // let the linkview deal with this event this._linkView.pointerup(evt, x, y); delete this._linkView; this.model.trigger('batch:stop', { batchName: 'add-link' }); } else { if (this._inProcessOfEmbedding) { this.finalizeEmbedding(); this._inProcessOfEmbedding = false; } this.notify('element:pointerup', evt, x, y); joint.dia.CellView.prototype.pointerup.apply(this, arguments); } } }); // JointJS diagramming library. // (c) 2011-2013 client IO // joint.dia.Link base model. // -------------------------- joint.dia.Link = joint.dia.Cell.extend({ // The default markup for links. markup: [ '<path class="connection" stroke="black"/>', '<path class="marker-source" fill="black" stroke="black" />', '<path class="marker-target" fill="black" stroke="black" />', '<path class="connection-wrap"/>', '<g class="labels"/>', '<g class="marker-vertices"/>', '<g class="marker-arrowheads"/>', '<g class="link-tools"/>' ].join(''), labelMarkup: [ '<g class="label">', '<rect />', '<text />', '</g>' ].join(''), toolMarkup: [ '<g class="link-tool">', '<g class="tool-remove" event="remove">', '<circle r="11" />', '<path transform="scale(.8) translate(-16, -16)" d="M24.778,21.419 19.276,15.917 24.777,10.415 21.949,7.585 16.447,13.087 10.945,7.585 8.117,10.415 13.618,15.917 8.116,21.419 10.946,24.248 16.447,18.746 21.948,24.248z"/>', '<title>Remove link.</title>', '</g>', '<g class="tool-options" event="link:options">', '<circle r="11" transform="translate(25)"/>', '<path fill="white" transform="scale(.55) translate(29, -16)" d="M31.229,17.736c0.064-0.571,0.104-1.148,0.104-1.736s-0.04-1.166-0.104-1.737l-4.377-1.557c-0.218-0.716-0.504-1.401-0.851-2.05l1.993-4.192c-0.725-0.91-1.549-1.734-2.458-2.459l-4.193,1.994c-0.647-0.347-1.334-0.632-2.049-0.849l-1.558-4.378C17.165,0.708,16.588,0.667,16,0.667s-1.166,0.041-1.737,0.105L12.707,5.15c-0.716,0.217-1.401,0.502-2.05,0.849L6.464,4.005C5.554,4.73,4.73,5.554,4.005,6.464l1.994,4.192c-0.347,0.648-0.632,1.334-0.849,2.05l-4.378,1.557C0.708,14.834,0.667,15.412,0.667,16s0.041,1.165,0.105,1.736l4.378,1.558c0.217,0.715,0.502,1.401,0.849,2.049l-1.994,4.193c0.725,0.909,1.549,1.733,2.459,2.458l4.192-1.993c0.648,0.347,1.334,0.633,2.05,0.851l1.557,4.377c0.571,0.064,1.148,0.104,1.737,0.104c0.588,0,1.165-0.04,1.736-0.104l1.558-4.377c0.715-0.218,1.399-0.504,2.049-0.851l4.193,1.993c0.909-0.725,1.733-1.549,2.458-2.458l-1.993-4.193c0.347-0.647,0.633-1.334,0.851-2.049L31.229,17.736zM16,20.871c-2.69,0-4.872-2.182-4.872-4.871c0-2.69,2.182-4.872,4.872-4.872c2.689,0,4.871,2.182,4.871,4.872C20.871,18.689,18.689,20.871,16,20.871z"/>', '<title>Link options.</title>', '</g>', '</g>' ].join(''), // The default markup for showing/removing vertices. These elements are the children of the .marker-vertices element (see `this.markup`). // Only .marker-vertex and .marker-vertex-remove element have special meaning. The former is used for // dragging vertices (changin their position). The latter is used for removing vertices. vertexMarkup: [ '<g class="marker-vertex-group" transform="translate(<%= x %>, <%= y %>)">', '<circle class="marker-vertex" idx="<%= idx %>" r="10" />', '<path class="marker-vertex-remove-area" idx="<%= idx %>" d="M16,5.333c-7.732,0-14,4.701-14,10.5c0,1.982,0.741,3.833,2.016,5.414L2,25.667l5.613-1.441c2.339,1.317,5.237,2.107,8.387,2.107c7.732,0,14-4.701,14-10.5C30,10.034,23.732,5.333,16,5.333z" transform="translate(5, -33)"/>', '<path class="marker-vertex-remove" idx="<%= idx %>" transform="scale(.8) translate(9.5, -37)" d="M24.778,21.419 19.276,15.917 24.777,10.415 21.949,7.585 16.447,13.087 10.945,7.585 8.117,10.415 13.618,15.917 8.116,21.419 10.946,24.248 16.447,18.746 21.948,24.248z">', '<title>Remove vertex.</title>', '</path>', '</g>' ].join(''), arrowheadMarkup: [ '<g class="marker-arrowhead-group marker-arrowhead-group-<%= end %>">', '<path class="marker-arrowhead" end="<%= end %>" d="M 26 0 L 0 13 L 26 26 z" />', '</g>' ].join(''), defaults: { type: 'link', source: {}, target: {} }, disconnect: function() { return this.set({ source: g.point(0, 0), target: g.point(0, 0) }); }, // A convenient way to set labels. Currently set values will be mixined with `value` if used as a setter. label: function(idx, value) { idx = idx || 0; var labels = this.get('labels') || []; // Is it a getter? if (arguments.length === 0 || arguments.length === 1) { return labels[idx]; } var newValue = _.merge({}, labels[idx], value); var newLabels = labels.slice(); newLabels[idx] = newValue; return this.set({ labels: newLabels }); }, translate: function(tx, ty, opt) { var attrs = {}; var source = this.get('source'); var target = this.get('target'); var vertices = this.get('vertices'); if (!source.id) { attrs.source = { x: source.x + tx, y: source.y + ty }; } if (!target.id) { attrs.target = { x: target.x + tx, y: target.y + ty }; } if (vertices && vertices.length) { attrs.vertices = _.map(vertices, function(vertex) { return { x: vertex.x + tx, y: vertex.y + ty }; }); } return this.set(attrs, opt); }, reparent: function(opt) { var newParent; if (this.collection) { var source = this.collection.get(this.get('source').id); var target = this.collection.get(this.get('target').id); var prevParent = this.collection.get(this.get('parent')); if (source && target) { newParent = this.collection.getCommonAncestor(source, target); } if (prevParent && (!newParent || newParent.id != prevParent.id)) { // Unembed the link if source and target has no common ancestor // or common ancestor changed prevParent.unembed(this, opt); } if (newParent) { newParent.embed(this, opt); } } return newParent; }, isLink: function() { return true; }, hasLoop: function() { var sourceId = this.get('source').id; var targetId = this.get('target').id; return sourceId && targetId && sourceId == targetId; } }); // joint.dia.Link base view and controller. // ---------------------------------------- joint.dia.LinkView = joint.dia.CellView.extend({ className: function() { return _.unique(this.model.get('type').split('.').concat('link')).join(' '); }, options: { shortLinkLength: 100, doubleLinkTools: false, longLinkLength: 160, linkToolsOffset: 40, doubleLinkToolsOffset: 60, sampleInterval: 50 }, initialize: function(options) { joint.dia.CellView.prototype.initialize.apply(this, arguments); // create methods in prototype, so they can be accessed from any instance and // don't need to be create over and over if (typeof this.constructor.prototype.watchSource !== 'function') { this.constructor.prototype.watchSource = this.createWatcher('source'); this.constructor.prototype.watchTarget = this.createWatcher('target'); } // `_.labelCache` is a mapping of indexes of labels in the `this.get('labels')` array to // `<g class="label">` nodes wrapped by Vectorizer. This allows for quick access to the // nodes in `updateLabelPosition()` in order to update the label positions. this._labelCache = {}; // keeps markers bboxes and positions again for quicker access this._markerCache = {}; // bind events this.startListening(); }, startListening: function() { var model = this.model; this.listenTo(model, 'change:markup', this.render); this.listenTo(model, 'change:smooth change:manhattan change:router change:connector', this.update); this.listenTo(model, 'change:toolMarkup', this.onToolsChange); this.listenTo(model, 'change:labels change:labelMarkup', this.onLabelsChange); this.listenTo(model, 'change:vertices change:vertexMarkup', this.onVerticesChange); this.listenTo(model, 'change:source', this.onSourceChange); this.listenTo(model, 'change:target', this.onTargetChange); }, onSourceChange: function(cell, source) { this.watchSource(cell, source).update(); }, onTargetChange: function(cell, target) { this.watchTarget(cell, target).update(); }, onVerticesChange: function(cell, changed, opt) { this.renderVertexMarkers(); // If the vertices have been changed by a translation we do update only if the link was // the only link that was translated. If the link was translated via another element which the link // is embedded in, this element will be translated as well and that triggers an update. // Note that all embeds in a model are sorted - first comes links, then elements. if (!opt.translateBy || opt.translateBy === this.model.id || this.model.hasLoop()) { // Vertices were changed (not as a reaction on translate) or link.translate() was called or // we're dealing with a loop link that is embedded. this.update(); } }, onToolsChange: function() { this.renderTools().updateToolsPosition(); }, onLabelsChange: function() { this.renderLabels().updateLabelPositions(); }, // Rendering //---------- render: function() { this.$el.empty(); // A special markup can be given in the `properties.markup` property. This might be handy // if e.g. arrowhead markers should be `<image>` elements or any other element than `<path>`s. // `.connection`, `.connection-wrap`, `.marker-source` and `.marker-target` selectors // of elements with special meaning though. Therefore, those classes should be preserved in any // special markup passed in `properties.markup`. var children = V(this.model.get('markup') || this.model.markup); // custom markup may contain only one children if (!_.isArray(children)) children = [children]; // Cache all children elements for quicker access. this._V = {}; // vectorized markup; _.each(children, function(child) { var c = child.attr('class'); c && (this._V[$.camelCase(c)] = child); }, this); // Only the connection path is mandatory if (!this._V.connection) throw new Error('link: no connection path in the markup'); // partial rendering this.renderTools(); this.renderVertexMarkers(); this.renderArrowheadMarkers(); this.vel.append(children); // rendering labels has to be run after the link is appended to DOM tree. (otherwise <Text> bbox // returns zero values) this.renderLabels(); // start watching the ends of the link for changes this.watchSource(this.model, this.model.get('source')) .watchTarget(this.model, this.model.get('target')) .update(); return this; }, renderLabels: function() { if (!this._V.labels) return this; this._labelCache = {}; var $labels = $(this._V.labels.node).empty(); var labels = this.model.get('labels') || []; if (!labels.length) return this; var labelTemplate = _.template(this.model.get('labelMarkup') || this.model.labelMarkup); // This is a prepared instance of a vectorized SVGDOM node for the label element resulting from // compilation of the labelTemplate. The purpose is that all labels will just `clone()` this // node to create a duplicate. var labelNodeInstance = V(labelTemplate()); var canLabelMove = this.can('labelMove'); _.each(labels, function(label, idx) { var labelNode = labelNodeInstance.clone().node; V(labelNode).attr('label-idx', idx); if (canLabelMove) { V(labelNode).attr('cursor', 'move'); } // Cache label nodes so that the `updateLabels()` can just update the label node positions. this._labelCache[idx] = V(labelNode); var $text = $(labelNode).find('text'); var $rect = $(labelNode).find('rect'); // Text attributes with the default `text-anchor` and font-size set. var textAttributes = _.extend({ 'text-anchor': 'middle', 'font-size': 14 }, joint.util.getByPath(label, 'attrs/text', '/')); $text.attr(_.omit(textAttributes, 'text')); if (!_.isUndefined(textAttributes.text)) { V($text[0]).text(textAttributes.text + ''); } // Note that we first need to append the `<text>` element to the DOM in order to // get its bounding box. $labels.append(labelNode); // `y-alignment` - center the text element around its y coordinate. var textBbox = V($text[0]).bbox(true, $labels[0]); V($text[0]).translate(0, -textBbox.height / 2); // Add default values. var rectAttributes = _.extend({ fill: 'white', rx: 3, ry: 3 }, joint.util.getByPath(label, 'attrs/rect', '/')); $rect.attr(_.extend(rectAttributes, { x: textBbox.x, y: textBbox.y - textBbox.height / 2, // Take into account the y-alignment translation. width: textBbox.width, height: textBbox.height })); }, this); return this; }, renderTools: function() { if (!this._V.linkTools) return this; // Tools are a group of clickable elements that manipulate the whole link. // A good example of this is the remove tool that removes the whole link. // Tools appear after hovering the link close to the `source` element/point of the link // but are offset a bit so that they don't cover the `marker-arrowhead`. var $tools = $(this._V.linkTools.node).empty(); var toolTemplate = _.template(this.model.get('toolMarkup') || this.model.toolMarkup); var tool = V(toolTemplate()); $tools.append(tool.node); // Cache the tool node so that the `updateToolsPosition()` can update the tool position quickly. this._toolCache = tool; // If `doubleLinkTools` is enabled, we render copy of the tools on the other side of the // link as well but only if the link is longer than `longLinkLength`. if (this.options.doubleLinkTools) { var tool2 = tool.clone(); $tools.append(tool2.node); this._tool2Cache = tool2; } return this; }, renderVertexMarkers: function() { if (!this._V.markerVertices) return this; var $markerVertices = $(this._V.markerVertices.node).empty(); // A special markup can be given in the `properties.vertexMarkup` property. This might be handy // if default styling (elements) are not desired. This makes it possible to use any // SVG elements for .marker-vertex and .marker-vertex-remove tools. var markupTemplate = _.template(this.model.get('vertexMarkup') || this.model.vertexMarkup); _.each(this.model.get('vertices'), function(vertex, idx) { $markerVertices.append(V(markupTemplate(_.extend({ idx: idx }, vertex))).node); }); return this; }, renderArrowheadMarkers: function() { // Custom markups might not have arrowhead markers. Therefore, jump of this function immediately if that's the case. if (!this._V.markerArrowheads) return this; var $markerArrowheads = $(this._V.markerArrowheads.node); $markerArrowheads.empty(); // A special markup can be given in the `properties.vertexMarkup` property. This might be handy // if default styling (elements) are not desired. This makes it possible to use any // SVG elements for .marker-vertex and .marker-vertex-remove tools. var markupTemplate = _.template(this.model.get('arrowheadMarkup') || this.model.arrowheadMarkup); this._V.sourceArrowhead = V(markupTemplate({ end: 'source' })); this._V.targetArrowhead = V(markupTemplate({ end: 'target' })); $markerArrowheads.append(this._V.sourceArrowhead.node, this._V.targetArrowhead.node); return this; }, // Updating //--------- // Default is to process the `attrs` object and set attributes on subelements based on the selectors. update: function() { // Update attributes. _.each(this.model.get('attrs'), function(attrs, selector) { var processedAttributes = []; // If the `fill` or `stroke` attribute is an object, it is in the special JointJS gradient format and so // it becomes a special attribute and is treated separately. if (_.isObject(attrs.fill)) { this.applyGradient(selector, 'fill', attrs.fill); processedAttributes.push('fill'); } if (_.isObject(attrs.stroke)) { this.applyGradient(selector, 'stroke', attrs.stroke); processedAttributes.push('stroke'); } // If the `filter` attribute is an object, it is in the special JointJS filter format and so // it becomes a special attribute and is treated separately. if (_.isObject(attrs.filter)) { this.applyFilter(selector, attrs.filter); processedAttributes.push('filter'); } // remove processed special attributes from attrs if (processedAttributes.length > 0) { processedAttributes.unshift(attrs); attrs = _.omit.apply(_, processedAttributes); } this.findBySelector(selector).attr(attrs); }, this); // Path finding var vertices = this.route = this.findRoute(this.model.get('vertices') || []); // finds all the connection points taking new vertices into account this._findConnectionPoints(vertices); var pathData = this.getPathData(vertices); // The markup needs to contain a `.connection` this._V.connection.attr('d', pathData); this._V.connectionWrap && this._V.connectionWrap.attr('d', pathData); this._translateAndAutoOrientArrows(this._V.markerSource, this._V.markerTarget); //partials updates this.updateLabelPositions(); this.updateToolsPosition(); this.updateArrowheadMarkers(); delete this.options.perpendicular; // Mark that postponed update has been already executed. this.updatePostponed = false; return this; }, _findConnectionPoints: function(vertices) { // cache source and target points var sourcePoint, targetPoint, sourceMarkerPoint, targetMarkerPoint; var firstVertex = _.first(vertices); sourcePoint = this.getConnectionPoint( 'source', this.model.get('source'), firstVertex || this.model.get('target') ).round(); var lastVertex = _.last(vertices); targetPoint = this.getConnectionPoint( 'target', this.model.get('target'), lastVertex || sourcePoint ).round(); // Move the source point by the width of the marker taking into account // its scale around x-axis. Note that scale is the only transform that // makes sense to be set in `.marker-source` attributes object // as all other transforms (translate/rotate) will be replaced // by the `translateAndAutoOrient()` function. var cache = this._markerCache; if (this._V.markerSource) { cache.sourceBBox = cache.sourceBBox || this._V.markerSource.bbox(true); sourceMarkerPoint = g.point(sourcePoint).move( firstVertex || targetPoint, cache.sourceBBox.width * this._V.markerSource.scale().sx * -1 ).round(); } if (this._V.markerTarget) { cache.targetBBox = cache.targetBBox || this._V.markerTarget.bbox(true); targetMarkerPoint = g.point(targetPoint).move( lastVertex || sourcePoint, cache.targetBBox.width * this._V.markerTarget.scale().sx * -1 ).round(); } // if there was no markup for the marker, use the connection point. cache.sourcePoint = sourceMarkerPoint || sourcePoint; cache.targetPoint = targetMarkerPoint || targetPoint; // make connection points public this.sourcePoint = sourcePoint; this.targetPoint = targetPoint; }, updateLabelPositions: function() { if (!this._V.labels) return this; // This method assumes all the label nodes are stored in the `this._labelCache` hash table // by their indexes in the `this.get('labels')` array. This is done in the `renderLabels()` method. var labels = this.model.get('labels') || []; if (!labels.length) return this; var connectionElement = this._V.connection.node; var connectionLength = connectionElement.getTotalLength(); // Firefox returns connectionLength=NaN in odd cases (for bezier curves). // In that case we won't update labels at all. if (!_.isNaN(connectionLength)) { var samples; _.each(labels, function(label, idx) { var position = label.position; var distance = _.isObject(position) ? position.distance : position; var offset = _.isObject(position) ? position.offset : { x: 0, y: 0 }; distance = (distance > connectionLength) ? connectionLength : distance; // sanity check distance = (distance < 0) ? connectionLength + distance : distance; distance = (distance > 1) ? distance : connectionLength * distance; var labelCoordinates = connectionElement.getPointAtLength(distance); if (_.isObject(offset)) { // Just offset the label by the x,y provided in the offset object. labelCoordinates = g.point(labelCoordinates).offset(offset.x, offset.y); } else if (_.isNumber(offset)) { if (!samples) { samples = this._samples || this._V.connection.sample(this.options.sampleInterval); } // Offset the label by the amount provided in `offset` to an either // side of the link. // 1. Find the closest sample & its left and right neighbours. var minSqDistance = Infinity; var closestSample; var closestSampleIndex; var p; var sqDistance; for (var i = 0, len = samples.length; i < len; i++) { p = samples[i]; sqDistance = g.line(p, labelCoordinates).squaredLength(); if (sqDistance < minSqDistance) { minSqDistance = sqDistance; closestSample = p; closestSampleIndex = i; } } var prevSample = samples[closestSampleIndex - 1]; var nextSample = samples[closestSampleIndex + 1]; // 2. Offset the label on the perpendicular line between // the current label coordinate ("at `distance`") and // the next sample. var angle = 0; if (nextSample) { angle = g.point(labelCoordinates).theta(nextSample); } else if (prevSample) { angle = g.point(prevSample).theta(labelCoordinates); } labelCoordinates = g.point(labelCoordinates).offset(offset).rotate(labelCoordinates, angle - 90); } this._labelCache[idx].attr('transform', 'translate(' + labelCoordinates.x + ', ' + labelCoordinates.y + ')'); }, this); } return this; }, updateToolsPosition: function() { if (!this._V.linkTools) return this; // Move the tools a bit to the target position but don't cover the `sourceArrowhead` marker. // Note that the offset is hardcoded here. The offset should be always // more than the `this.$('.marker-arrowhead[end="source"]')[0].bbox().width` but looking // this up all the time would be slow. var scale = ''; var offset = this.options.linkToolsOffset; var connectionLength = this.getConnectionLength(); // Firefox returns connectionLength=NaN in odd cases (for bezier curves). // In that case we won't update tools position at all. if (!_.isNaN(connectionLength)) { // If the link is too short, make the tools half the size and the offset twice as low. if (connectionLength < this.options.shortLinkLength) { scale = 'scale(.5)'; offset /= 2; } var toolPosition = this.getPointAtLength(offset); this._toolCache.attr('transform', 'translate(' + toolPosition.x + ', ' + toolPosition.y + ') ' + scale); if (this.options.doubleLinkTools && connectionLength >= this.options.longLinkLength) { var doubleLinkToolsOffset = this.options.doubleLinkToolsOffset || offset; toolPosition = this.getPointAtLength(connectionLength - doubleLinkToolsOffset); this._tool2Cache.attr('transform', 'translate(' + toolPosition.x + ', ' + toolPosition.y + ') ' + scale); this._tool2Cache.attr('visibility', 'visible'); } else if (this.options.doubleLinkTools) { this._tool2Cache.attr('visibility', 'hidden'); } } return this; }, updateArrowheadMarkers: function() { if (!this._V.markerArrowheads) return this; // getting bbox of an element with `display="none"` in IE9 ends up with access violation if ($.css(this._V.markerArrowheads.node, 'display') === 'none') return this; var sx = this.getConnectionLength() < this.options.shortLinkLength ? .5 : 1; this._V.sourceArrowhead.scale(sx); this._V.targetArrowhead.scale(sx); this._translateAndAutoOrientArrows(this._V.sourceArrowhead, this._V.targetArrowhead); return this; }, // Returns a function observing changes on an end of the link. If a change happens and new end is a new model, // it stops listening on the previous one and starts listening to the new one. createWatcher: function(endType) { // create handler for specific end type (source|target). var onModelChange = _.partial(this.onEndModelChange, endType); function watchEndModel(link, end) { end = end || {}; var endModel = null; var previousEnd = link.previous(endType) || {}; if (previousEnd.id) { this.stopListening(this.paper.getModelById(previousEnd.id), 'change', onModelChange); } if (end.id) { // If the observed model changes, it caches a new bbox and do the link update. endModel = this.paper.getModelById(end.id); this.listenTo(endModel, 'change', onModelChange); } onModelChange.call(this, endModel, { cacheOnly: true }); return this; } return watchEndModel; }, onEndModelChange: function(endType, endModel, opt) { var doUpdate = !opt.cacheOnly; var end = this.model.get(endType) || {}; if (endModel) { var selector = this.constructor.makeSelector(end); var oppositeEndType = endType == 'source' ? 'target' : 'source'; var oppositeEnd = this.model.get(oppositeEndType) || {}; var oppositeSelector = oppositeEnd.id && this.constructor.makeSelector(oppositeEnd); // Caching end models bounding boxes. // If `opt.handleBy` equals the client-side ID of this link view and it is a loop link, then we already cached // the bounding boxes in the previous turn (e.g. for loop link, the change:source event is followed // by change:target and so on change:source, we already chached the bounding boxes of - the same - element). if (opt.handleBy === this.cid && selector == oppositeSelector) { // Source and target elements are identical. We're dealing with a loop link. We are handling `change` event for the // second time now. There is no need to calculate bbox and find magnet element again. // It was calculated already for opposite link end. this[endType + 'BBox'] = this[oppositeEndType + 'BBox']; this[endType + 'View'] = this[oppositeEndType + 'View']; this[endType + 'Magnet'] = this[oppositeEndType + 'Magnet']; } else if (opt.translateBy) { // `opt.translateBy` optimizes the way we calculate bounding box of the source/target element. // If `opt.translateBy` is an ID of the element that was originally translated. This allows us // to just offset the cached bounding box by the translation instead of calculating the bounding // box from scratch on every translate. var bbox = this[endType + 'BBox']; bbox.x += opt.tx; bbox.y += opt.ty; } else { // The slowest path, source/target could have been rotated or resized or any attribute // that affects the bounding box of the view might have been changed. var view = this.paper.findViewByModel(end.id); var magnetElement = view.el.querySelector(selector); this[endType + 'BBox'] = view.getStrokeBBox(magnetElement); this[endType + 'View'] = view; this[endType + 'Magnet'] = magnetElement; } if (opt.handleBy === this.cid && opt.translateBy && this.model.isEmbeddedIn(endModel) && !_.isEmpty(this.model.get('vertices'))) { // Loop link whose element was translated and that has vertices (that need to be translated with // the parent in which my element is embedded). // If the link is embedded, has a loop and vertices and the end model // has been translated, do not update yet. There are vertices still to be updated (change:vertices // event will come in the next turn). doUpdate = false; } if (!this.updatePostponed && oppositeEnd.id) { // The update was not postponed (that can happen e.g. on the first change event) and the opposite // end is a model (opposite end is the opposite end of the link we're just updating, e.g. if // we're reacting on change:source event, the oppositeEnd is the target model). var oppositeEndModel = this.paper.getModelById(oppositeEnd.id); // Passing `handleBy` flag via event option. // Note that if we are listening to the same model for event 'change' twice. // The same event will be handled by this method also twice. if (end.id === oppositeEnd.id) { // We're dealing with a loop link. Tell the handlers in the next turn that they should update // the link instead of me. (We know for sure there will be a next turn because // loop links react on at least two events: change on the source model followed by a change on // the target model). opt.handleBy = this.cid; } if (opt.handleBy === this.cid || (opt.translateBy && oppositeEndModel.isEmbeddedIn(opt.translateBy))) { // Here are two options: // - Source and target are connected to the same model (not necessarily the same port). // - Both end models are translated by the same ancestor. We know that opposite end // model will be translated in the next turn as well. // In both situations there will be more changes on the model that trigger an // update. So there is no need to update the linkView yet. this.updatePostponed = true; doUpdate = false; } } } else { // the link end is a point ~ rect 1x1 this[endType + 'BBox'] = g.rect(end.x || 0, end.y || 0, 1, 1); this[endType + 'View'] = this[endType + 'Magnet'] = null; } // keep track which end had been changed very last this.lastEndChange = endType; doUpdate && this.update(); }, _translateAndAutoOrientArrows: function(sourceArrow, targetArrow) { // Make the markers "point" to their sticky points being auto-oriented towards // `targetPosition`/`sourcePosition`. And do so only if there is a markup for them. if (sourceArrow) { sourceArrow.translateAndAutoOrient( this.sourcePoint, _.first(this.route) || this.targetPoint, this.paper.viewport ); } if (targetArrow) { targetArrow.translateAndAutoOrient( this.targetPoint, _.last(this.route) || this.sourcePoint, this.paper.viewport ); } }, removeVertex: function(idx) { var vertices = _.clone(this.model.get('vertices')); if (vertices && vertices.length) { vertices.splice(idx, 1); this.model.set('vertices', vertices, { ui: true }); } return this; }, // This method ads a new vertex to the `vertices` array of `.connection`. This method // uses a heuristic to find the index at which the new `vertex` should be placed at assuming // the new vertex is somewhere on the path. addVertex: function(vertex) { // As it is very hard to find a correct index of the newly created vertex, // a little heuristics is taking place here. // The heuristics checks if length of the newly created // path is lot more than length of the old path. If this is the case, // new vertex was probably put into a wrong index. // Try to put it into another index and repeat the heuristics again. var vertices = (this.model.get('vertices') || []).slice(); // Store the original vertices for a later revert if needed. var originalVertices = vertices.slice(); // A `<path>` element used to compute the length of the path during heuristics. var path = this._V.connection.node.cloneNode(false); // Length of the original path. var originalPathLength = path.getTotalLength(); // Current path length. var pathLength; // Tolerance determines the highest possible difference between the length // of the old and new path. The number has been chosen heuristically. var pathLengthTolerance = 20; // Total number of vertices including source and target points. var idx = vertices.length + 1; // Loop through all possible indexes and check if the difference between // path lengths changes significantly. If not, the found index is // most probably the right one. while (idx--) { vertices.splice(idx, 0, vertex); V(path).attr('d', this.getPathData(this.findRoute(vertices))); pathLength = path.getTotalLength(); // Check if the path lengths changed significantly. if (pathLength - originalPathLength > pathLengthTolerance) { // Revert vertices to the original array. The path length has changed too much // so that the index was not found yet. vertices = originalVertices.slice(); } else { break; } } if (idx === -1) { // If no suitable index was found for such a vertex, make the vertex the first one. idx = 0; vertices.splice(idx, 0, vertex); } this.model.set('vertices', vertices, { ui: true }); return idx; }, // Send a token (an SVG element, usually a circle) along the connection path. // Example: `paper.findViewByModel(link).sendToken(V('circle', { r: 7, fill: 'green' }).node)` // `duration` is optional and is a time in milliseconds that the token travels from the source to the target of the link. Default is `1000`. // `callback` is optional and is a function to be called once the token reaches the target. sendToken: function(token, duration, callback) { duration = duration || 1000; V(this.paper.viewport).append(token); V(token).animateAlongPath({ dur: duration + 'ms', repeatCount: 1 }, this._V.connection.node); _.delay(function() { V(token).remove(); callback && callback(); }, duration); }, findRoute: function(oldVertices) { var router = this.model.get('router'); if (!router) { if (this.model.get('manhattan')) { // backwards compability router = { name: 'orthogonal' }; } else { return oldVertices; } } var fn = joint.routers[router.name]; if (!_.isFunction(fn)) { throw 'unknown router: ' + router.name; } var newVertices = fn.call(this, oldVertices || [], router.args || {}, this); return newVertices; }, // Return the `d` attribute value of the `<path>` element representing the link // between `source` and `target`. getPathData: function(vertices) { var connector = this.model.get('connector'); if (!connector) { // backwards compability connector = this.model.get('smooth') ? { name: 'smooth' } : { name: 'normal' }; } if (!_.isFunction(joint.connectors[connector.name])) { throw 'unknown connector: ' + connector.name; } var pathData = joint.connectors[connector.name].call( this, this._markerCache.sourcePoint, // Note that the value is translated by the size this._markerCache.targetPoint, // of the marker. (We'r not using this.sourcePoint) vertices || (this.model.get('vertices') || {}), connector.args || {}, // options this ); return pathData; }, // Find a point that is the start of the connection. // If `selectorOrPoint` is a point, then we're done and that point is the start of the connection. // If the `selectorOrPoint` is an element however, we need to know a reference point (or element) // that the link leads to in order to determine the start of the connection on the original element. getConnectionPoint: function(end, selectorOrPoint, referenceSelectorOrPoint) { var spot; // If the `selectorOrPoint` (or `referenceSelectorOrPoint`) is `undefined`, the `source`/`target` of the link model is `undefined`. // We want to allow this however so that one can create links such as `var link = new joint.dia.Link` and // set the `source`/`target` later. _.isEmpty(selectorOrPoint) && (selectorOrPoint = { x: 0, y: 0 }); _.isEmpty(referenceSelectorOrPoint) && (referenceSelectorOrPoint = { x: 0, y: 0 }); if (!selectorOrPoint.id) { // If the source is a point, we don't need a reference point to find the sticky point of connection. spot = g.point(selectorOrPoint); } else { // If the source is an element, we need to find a point on the element boundary that is closest // to the reference point (or reference element). // Get the bounding box of the spot relative to the paper viewport. This is necessary // in order to follow paper viewport transformations (scale/rotate). // `_sourceBbox` (`_targetBbox`) comes from `_sourceBboxUpdate` (`_sourceBboxUpdate`) // method, it exists since first render and are automatically updated var spotBbox = end === 'source' ? this.sourceBBox : this.targetBBox; var reference; if (!referenceSelectorOrPoint.id) { // Reference was passed as a point, therefore, we're ready to find the sticky point of connection on the source element. reference = g.point(referenceSelectorOrPoint); } else { // Reference was passed as an element, therefore we need to find a point on the reference // element boundary closest to the source element. // Get the bounding box of the spot relative to the paper viewport. This is necessary // in order to follow paper viewport transformations (scale/rotate). var referenceBbox = end === 'source' ? this.targetBBox : this.sourceBBox; reference = g.rect(referenceBbox).intersectionWithLineFromCenterToPoint(g.rect(spotBbox).center()); reference = reference || g.rect(referenceBbox).center(); } // If `perpendicularLinks` flag is set on the paper and there are vertices // on the link, then try to find a connection point that makes the link perpendicular // even though the link won't point to the center of the targeted object. if (this.paper.options.perpendicularLinks || this.options.perpendicular) { var horizontalLineRect = g.rect(0, reference.y, this.paper.options.width, 1); var verticalLineRect = g.rect(reference.x, 0, 1, this.paper.options.height); var nearestSide; if (horizontalLineRect.intersect(g.rect(spotBbox))) { nearestSide = g.rect(spotBbox).sideNearestToPoint(reference); switch (nearestSide) { case 'left': spot = g.point(spotBbox.x, reference.y); break; case 'right': spot = g.point(spotBbox.x + spotBbox.width, reference.y); break; default: spot = g.rect(spotBbox).center(); break; } } else if (verticalLineRect.intersect(g.rect(spotBbox))) { nearestSide = g.rect(spotBbox).sideNearestToPoint(reference); switch (nearestSide) { case 'top': spot = g.point(reference.x, spotBbox.y); break; case 'bottom': spot = g.point(reference.x, spotBbox.y + spotBbox.height); break; default: spot = g.rect(spotBbox).center(); break; } } else { // If there is no intersection horizontally or vertically with the object bounding box, // then we fall back to the regular situation finding straight line (not perpendicular) // between the object and the reference point. spot = g.rect(spotBbox).intersectionWithLineFromCenterToPoint(reference); spot = spot || g.rect(spotBbox).center(); } } else if (this.paper.options.linkConnectionPoint) { var view = end === 'target' ? this.targetView : this.sourceView; var magnet = end === 'target' ? this.targetMagnet : this.sourceMagnet; spot = this.paper.options.linkConnectionPoint(this, view, magnet, reference); } else { spot = g.rect(spotBbox).intersectionWithLineFromCenterToPoint(reference); spot = spot || g.rect(spotBbox).center(); } } return spot; }, // Public API // ---------- getConnectionLength: function() { return this._V.connection.node.getTotalLength(); }, getPointAtLength: function(length) { return this._V.connection.node.getPointAtLength(length); }, // Interaction. The controller part. // --------------------------------- _beforeArrowheadMove: function() { this._z = this.model.get('z'); this.model.toFront(); // Let the pointer propagate throught the link view elements so that // the `evt.target` is another element under the pointer, not the link itself. this.el.style.pointerEvents = 'none'; if (this.paper.options.markAvailable) { this._markAvailableMagnets(); } }, _afterArrowheadMove: function() { if (this._z) { this.model.set('z', this._z, { ui: true }); delete this._z; } // Put `pointer-events` back to its original value. See `startArrowheadMove()` for explanation. // Value `auto` doesn't work in IE9. We force to use `visiblePainted` instead. // See `https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events`. this.el.style.pointerEvents = 'visiblePainted'; if (this.paper.options.markAvailable) { this._unmarkAvailableMagnets(); } }, _createValidateConnectionArgs: function(arrowhead) { // It makes sure the arguments for validateConnection have the following form: // (source view, source magnet, target view, target magnet and link view) var args = []; args[4] = arrowhead; args[5] = this; var oppositeArrowhead; var i = 0; var j = 0; if (arrowhead === 'source') { i = 2; oppositeArrowhead = 'target'; } else { j = 2; oppositeArrowhead = 'source'; } var end = this.model.get(oppositeArrowhead); if (end.id) { args[i] = this.paper.findViewByModel(end.id); args[i + 1] = end.selector && args[i].el.querySelector(end.selector); } function validateConnectionArgs(cellView, magnet) { args[j] = cellView; args[j + 1] = cellView.el === magnet ? undefined : magnet; return args; } return validateConnectionArgs; }, _markAvailableMagnets: function() { var elements = this.paper.model.getElements(); var validate = this.paper.options.validateConnection; _.chain(elements).map(this.paper.findViewByModel, this.paper).each(function(view) { var isElementAvailable = view.el.getAttribute('magnet') !== 'false' && validate.apply(this.paper, this._validateConnectionArgs(view, null)); var availableMagnets = _.filter(view.el.querySelectorAll('[magnet]'), function(magnet) { return validate.apply(this.paper, this._validateConnectionArgs(view, magnet)); }, this); if (isElementAvailable) { V(view.el).addClass('available-magnet'); } _.each(availableMagnets, function(magnet) { V(magnet).addClass('available-magnet'); }); if (isElementAvailable || availableMagnets.length) { V(view.el).addClass('available-cell'); } }, this); }, _unmarkAvailableMagnets: function() { _.each(this.paper.el.querySelectorAll('.available-cell, .available-magnet'), function(magnet) { V(magnet).removeClass('available-magnet').removeClass('available-cell'); }); }, startArrowheadMove: function(end) { // Allow to delegate events from an another view to this linkView in order to trigger arrowhead // move without need to click on the actual arrowhead dom element. this._action = 'arrowhead-move'; this._arrowhead = end; this._validateConnectionArgs = this._createValidateConnectionArgs(this._arrowhead); this._beforeArrowheadMove(); }, // Return `true` if the link is allowed to perform a certain UI `feature`. // Example: `can('vertexMove')`, `can('labelMove')`. can: function(feature) { var interactive = _.isFunction(this.options.interactive) ? this.options.interactive(this, 'pointerdown') : this.options.interactive; if (!_.isObject(interactive) || interactive[feature] !== false) return true; return false; }, pointerdown: function(evt, x, y) { joint.dia.CellView.prototype.pointerdown.apply(this, arguments); this.notify('link:pointerdown', evt, x, y); this._dx = x; this._dy = y; // if are simulating pointerdown on a link during a magnet click, skip link interactions if (evt.target.getAttribute('magnet') != null) return; var interactive = _.isFunction(this.options.interactive) ? this.options.interactive(this, 'pointerdown') : this.options.interactive; if (interactive === false) return; var className = evt.target.getAttribute('class'); var parentClassName = evt.target.parentNode.getAttribute('class'); var labelNode; if (parentClassName === 'label') { className = parentClassName; labelNode = evt.target.parentNode; } else { labelNode = evt.target; } switch (className) { case 'marker-vertex': if (this.can('vertexMove')) { this._action = 'vertex-move'; this._vertexIdx = evt.target.getAttribute('idx'); } break; case 'marker-vertex-remove': case 'marker-vertex-remove-area': if (this.can('vertexRemove')) { this.removeVertex(evt.target.getAttribute('idx')); } break; case 'marker-arrowhead': if (this.can('arrowheadMove')) { this.startArrowheadMove(evt.target.getAttribute('end')); } break; case 'label': if (this.can('labelMove')) { this._action = 'label-move'; this._labelIdx = parseInt(V(labelNode).attr('label-idx'), 10); // Precalculate samples so that we don't have to do that // over and over again while dragging the label. this._samples = this._V.connection.sample(1); this._linkLength = this._V.connection.node.getTotalLength(); } break; default: var targetParentEvent = evt.target.parentNode.getAttribute('event'); if (targetParentEvent) { // `remove` event is built-in. Other custom events are triggered on the paper. if (targetParentEvent === 'remove') { this.model.remove(); } else { this.paper.trigger(targetParentEvent, evt, this, x, y); } } else { if (this.can('vertexAdd')) { // Store the index at which the new vertex has just been placed. // We'll be update the very same vertex position in `pointermove()`. this._vertexIdx = this.addVertex({ x: x, y: y }); this._action = 'vertex-move'; } } } }, pointermove: function(evt, x, y) { switch (this._action) { case 'vertex-move': var vertices = _.clone(this.model.get('vertices')); vertices[this._vertexIdx] = { x: x, y: y }; this.model.set('vertices', vertices, { ui: true }); break; case 'label-move': var dragPoint = { x: x, y: y }; var label = this.model.get('labels')[this._labelIdx]; var samples = this._samples; var minSqDistance = Infinity; var closestSample; var closestSampleIndex; var p; var sqDistance; for (var i = 0, len = samples.length; i < len; i++) { p = samples[i]; sqDistance = g.line(p, dragPoint).squaredLength(); if (sqDistance < minSqDistance) { minSqDistance = sqDistance; closestSample = p; closestSampleIndex = i; } } var prevSample = samples[closestSampleIndex - 1]; var nextSample = samples[closestSampleIndex + 1]; var closestSampleDistance = g.point(closestSample).distance(dragPoint); var offset = 0; if (prevSample && nextSample) { offset = g.line(prevSample, nextSample).pointOffset(dragPoint); } else if (prevSample) { offset = g.line(prevSample, closestSample).pointOffset(dragPoint); } else if (nextSample) { offset = g.line(closestSample, nextSample).pointOffset(dragPoint); } this.model.label(this._labelIdx, { position: { distance: closestSample.distance / this._linkLength, offset: offset } }); break; case 'arrowhead-move': if (this.paper.options.snapLinks) { // checking view in close area of the pointer var r = this.paper.options.snapLinks.radius || 50; var viewsInArea = this.paper.findViewsInArea({ x: x - r, y: y - r, width: 2 * r, height: 2 * r }); this._closestView && this._closestView.unhighlight(this._closestEnd.selector, { connecting: true, snapping: true }); this._closestView = this._closestEnd = null; var distance; var minDistance = Number.MAX_VALUE; var pointer = g.point(x, y); _.each(viewsInArea, function(view) { // skip connecting to the element in case '.': { magnet: false } attribute present if (view.el.getAttribute('magnet') !== 'false') { // find distance from the center of the model to pointer coordinates distance = view.model.getBBox().center().distance(pointer); // the connection is looked up in a circle area by `distance < r` if (distance < r && distance < minDistance) { if (this.paper.options.validateConnection.apply( this.paper, this._validateConnectionArgs(view, null) )) { minDistance = distance; this._closestView = view; this._closestEnd = { id: view.model.id }; } } } view.$('[magnet]').each(_.bind(function(index, magnet) { var bbox = V(magnet).bbox(false, this.paper.viewport); distance = pointer.distance({ x: bbox.x + bbox.width / 2, y: bbox.y + bbox.height / 2 }); if (distance < r && distance < minDistance) { if (this.paper.options.validateConnection.apply( this.paper, this._validateConnectionArgs(view, magnet) )) { minDistance = distance; this._closestView = view; this._closestEnd = { id: view.model.id, selector: view.getSelector(magnet), port: magnet.getAttribute('port') }; } } }, this)); }, this); this._closestView && this._closestView.highlight(this._closestEnd.selector, { connecting: true, snapping: true }); this.model.set(this._arrowhead, this._closestEnd || { x: x, y: y }, { ui: true }); } else { // checking views right under the pointer // Touchmove event's target is not reflecting the element under the coordinates as mousemove does. // It holds the element when a touchstart triggered. var target = (evt.type === 'mousemove') ? evt.target : document.elementFromPoint(evt.clientX, evt.clientY); if (this._targetEvent !== target) { // Unhighlight the previous view under pointer if there was one. this._magnetUnderPointer && this._viewUnderPointer.unhighlight(this._magnetUnderPointer, { connecting: true }); this._viewUnderPointer = this.paper.findView(target); if (this._viewUnderPointer) { // If we found a view that is under the pointer, we need to find the closest // magnet based on the real target element of the event. this._magnetUnderPointer = this._viewUnderPointer.findMagnet(target); if (this._magnetUnderPointer && this.paper.options.validateConnection.apply( this.paper, this._validateConnectionArgs(this._viewUnderPointer, this._magnetUnderPointer) )) { // If there was no magnet found, do not highlight anything and assume there // is no view under pointer we're interested in reconnecting to. // This can only happen if the overall element has the attribute `'.': { magnet: false }`. this._magnetUnderPointer && this._viewUnderPointer.highlight(this._magnetUnderPointer, { connecting: true }); } else { // This type of connection is not valid. Disregard this magnet. this._magnetUnderPointer = null; } } else { // Make sure we'll delete previous magnet this._magnetUnderPointer = null; } } this._targetEvent = target; this.model.set(this._arrowhead, { x: x, y: y }, { ui: true }); } break; } this._dx = x; this._dy = y; joint.dia.CellView.prototype.pointermove.apply(this, arguments); this.notify('link:pointermove', evt, x, y); }, pointerup: function(evt, x, y) { if (this._action === 'label-move') { this._samples = null; } else if (this._action === 'arrowhead-move') { if (this.paper.options.snapLinks) { this._closestView && this._closestView.unhighlight(this._closestEnd.selector, { connecting: true, snapping: true }); this._closestView = this._closestEnd = null; } else { if (this._magnetUnderPointer) { this._viewUnderPointer.unhighlight(this._magnetUnderPointer, { connecting: true }); // Find a unique `selector` of the element under pointer that is a magnet. If the // `this._magnetUnderPointer` is the root element of the `this._viewUnderPointer` itself, // the returned `selector` will be `undefined`. That means we can directly pass it to the // `source`/`target` attribute of the link model below. this.model.set(this._arrowhead, { id: this._viewUnderPointer.model.id, selector: this._viewUnderPointer.getSelector(this._magnetUnderPointer), port: $(this._magnetUnderPointer).attr('port') }, { ui: true }); } delete this._viewUnderPointer; delete this._magnetUnderPointer; } // Reparent the link if embedding is enabled if (this.paper.options.embeddingMode && this.model.reparent()) { // Make sure we don't reverse to the original 'z' index (see afterArrowheadMove()). delete this._z; } this._afterArrowheadMove(); } delete this._action; this.notify('link:pointerup', evt, x, y); joint.dia.CellView.prototype.pointerup.apply(this, arguments); } }, { makeSelector: function(end) { var selector = '[model-id="' + end.id + '"]'; // `port` has a higher precendence over `selector`. This is because the selector to the magnet // might change while the name of the port can stay the same. if (end.port) { selector += ' [port="' + end.port + '"]'; } else if (end.selector) { selector += ' ' + end.selector; } return selector; } }); // JointJS library. // (c) 2011-2013 client IO joint.dia.Paper = Backbone.View.extend({ className: 'paper', options: { width: 800, height: 600, origin: { x: 0, y: 0 }, // x,y coordinates in top-left corner gridSize: 50, perpendicularLinks: false, elementView: joint.dia.ElementView, linkView: joint.dia.LinkView, snapLinks: false, // false, true, { radius: value } // Marks all available magnets with 'available-magnet' class name and all available cells with // 'available-cell' class name. Marks them when dragging a link is started and unmark // when the dragging is stopped. markAvailable: false, // Defines what link model is added to the graph after an user clicks on an active magnet. // Value could be the Backbone.model or a function returning the Backbone.model // defaultLink: function(elementView, magnet) { return condition ? new customLink1() : new customLink2() } defaultLink: new joint.dia.Link, /* CONNECTING */ // Check whether to add a new link to the graph when user clicks on an a magnet. validateMagnet: function(cellView, magnet) { return magnet.getAttribute('magnet') !== 'passive'; }, // Check whether to allow or disallow the link connection while an arrowhead end (source/target) // being changed. validateConnection: function(cellViewS, magnetS, cellViewT, magnetT, end, linkView) { return (end === 'target' ? cellViewT : cellViewS) instanceof joint.dia.ElementView; }, /* EMBEDDING */ // Enables embedding. Reparents the dragged element with elements under it and makes sure that // all links and elements are visible taken the level of embedding into account. embeddingMode: false, // Check whether to allow or disallow the element embedding while an element being translated. validateEmbedding: function(childView, parentView) { // by default all elements can be in relation child-parent return true; }, // Determines the way how a cell finds a suitable parent when it's dragged over the paper. // The cell with the highest z-index (visually on the top) will be choosen. findParentBy: 'bbox', // 'bbox'|'center'|'origin'|'corner'|'topRight'|'bottomLeft' // If enabled only the element on the very front is taken into account for the embedding. // If disabled the elements under the dragged view are tested one by one // (from front to back) until a valid parent found. frontParentOnly: true, // Interactive flags. See online docs for the complete list of interactive flags. interactive: { labelMove: false } }, events: { 'mousedown': 'pointerdown', 'dblclick': 'mousedblclick', 'click': 'mouseclick', 'touchstart': 'pointerdown', 'mousemove': 'pointermove', 'touchmove': 'pointermove', 'mouseover .element': 'cellMouseover', 'mouseover .link': 'cellMouseover', 'mouseout .element': 'cellMouseout', 'mouseout .link': 'cellMouseout', 'contextmenu': 'contextmenu' }, constructor: function(options) { this._configure(options); Backbone.View.apply(this, arguments); }, _configure: function(options) { if (this.options) options = _.extend({}, _.result(this, 'options'), options); this.options = options; }, initialize: function() { _.bindAll(this, 'addCell', 'sortCells', 'resetCells', 'pointerup', 'asyncRenderCells'); this.svg = V('svg').node; this.viewport = V('g').addClass('viewport').node; this.defs = V('defs').node; // Append `<defs>` element to the SVG document. This is useful for filters and gradients. V(this.svg).append([this.viewport, this.defs]); this.$el.append(this.svg); this.setOrigin(); this.setDimensions(); this.listenTo(this.model, 'add', this.onAddCell); this.listenTo(this.model, 'reset', this.resetCells); this.listenTo(this.model, 'sort', this.sortCells); $(document).on('mouseup touchend', this.pointerup); // Hold the value when mouse has been moved: when mouse moved, no click event will be triggered. this._mousemoved = false; // default cell highlighting this.on({ 'cell:highlight': this.onCellHighlight, 'cell:unhighlight': this.onCellUnhighlight }); }, remove: function() { //clean up all DOM elements/views to prevent memory leaks this.removeCells(); $(document).off('mouseup touchend', this.pointerup); Backbone.View.prototype.remove.call(this); }, setDimensions: function(width, height) { width = this.options.width = width || this.options.width; height = this.options.height = height || this.options.height; V(this.svg).attr({ width: width, height: height }); this.trigger('resize', width, height); }, setOrigin: function(ox, oy) { this.options.origin.x = ox || 0; this.options.origin.y = oy || 0; V(this.viewport).translate(ox, oy, { absolute: true }); this.trigger('translate', ox, oy); }, // Expand/shrink the paper to fit the content. Snap the width/height to the grid // defined in `gridWidth`, `gridHeight`. `padding` adds to the resulting width/height of the paper. // When options { fitNegative: true } it also translates the viewport in order to make all // the content visible. fitToContent: function(gridWidth, gridHeight, padding, opt) { // alternatively function(opt) if (_.isObject(gridWidth)) { // first parameter is an option object opt = gridWidth; gridWidth = opt.gridWidth || 1; gridHeight = opt.gridHeight || 1; padding = opt.padding || 0; } else { opt = opt || {}; gridWidth = gridWidth || 1; gridHeight = gridHeight || 1; padding = padding || 0; } padding = joint.util.normalizeSides(padding); // Calculate the paper size to accomodate all the graph's elements. var bbox = V(this.viewport).bbox(true, this.svg); var currentScale = V(this.viewport).scale(); bbox.x *= currentScale.sx; bbox.y *= currentScale.sy; bbox.width *= currentScale.sx; bbox.height *= currentScale.sy; var calcWidth = Math.max(Math.ceil((bbox.width + bbox.x) / gridWidth), 1) * gridWidth; var calcHeight = Math.max(Math.ceil((bbox.height + bbox.y) / gridHeight), 1) * gridHeight; var tx = 0; var ty = 0; if ((opt.allowNewOrigin == 'negative' && bbox.x < 0) || (opt.allowNewOrigin == 'positive' && bbox.x >= 0) || opt.allowNewOrigin == 'any') { tx = Math.ceil(-bbox.x / gridWidth) * gridWidth; tx += padding.left; calcWidth += tx; } if ((opt.allowNewOrigin == 'negative' && bbox.y < 0) || (opt.allowNewOrigin == 'positive' && bbox.y >= 0) || opt.allowNewOrigin == 'any') { ty = Math.ceil(-bbox.y / gridHeight) * gridHeight; ty += padding.top; calcHeight += ty; } calcWidth += padding.right; calcHeight += padding.bottom; // Make sure the resulting width and height are greater than minimum. calcWidth = Math.max(calcWidth, opt.minWidth || 0); calcHeight = Math.max(calcHeight, opt.minHeight || 0); // Make sure the resulting width and height are lesser than maximum. calcWidth = Math.min(calcWidth, opt.maxWidth || Number.MAX_VALUE); calcHeight = Math.min(calcHeight, opt.maxHeight || Number.MAX_VALUE); var dimensionChange = calcWidth != this.options.width || calcHeight != this.options.height; var originChange = tx != this.options.origin.x || ty != this.options.origin.y; // Change the dimensions only if there is a size discrepency or an origin change if (originChange) { this.setOrigin(tx, ty); } if (dimensionChange) { this.setDimensions(calcWidth, calcHeight); } }, scaleContentToFit: function(opt) { var contentBBox = this.getContentBBox(); if (!contentBBox.width || !contentBBox.height) return; opt = opt || {}; _.defaults(opt, { padding: 0, preserveAspectRatio: true, scaleGrid: null, minScale: 0, maxScale: Number.MAX_VALUE //minScaleX //minScaleY //maxScaleX //maxScaleY //fittingBBox }); var padding = opt.padding; var minScaleX = opt.minScaleX || opt.minScale; var maxScaleX = opt.maxScaleX || opt.maxScale; var minScaleY = opt.minScaleY || opt.minScale; var maxScaleY = opt.maxScaleY || opt.maxScale; var fittingBBox = opt.fittingBBox || ({ x: this.options.origin.x, y: this.options.origin.y, width: this.options.width, height: this.options.height }); fittingBBox = g.rect(fittingBBox).moveAndExpand({ x: padding, y: padding, width: -2 * padding, height: -2 * padding }); var currentScale = V(this.viewport).scale(); var newSx = fittingBBox.width / contentBBox.width * currentScale.sx; var newSy = fittingBBox.height / contentBBox.height * currentScale.sy; if (opt.preserveAspectRatio) { newSx = newSy = Math.min(newSx, newSy); } // snap scale to a grid if (opt.scaleGrid) { var gridSize = opt.scaleGrid; newSx = gridSize * Math.floor(newSx / gridSize); newSy = gridSize * Math.floor(newSy / gridSize); } // scale min/max boundaries newSx = Math.min(maxScaleX, Math.max(minScaleX, newSx)); newSy = Math.min(maxScaleY, Math.max(minScaleY, newSy)); this.scale(newSx, newSy); var contentTranslation = this.getContentBBox(); var newOx = fittingBBox.x - contentTranslation.x; var newOy = fittingBBox.y - contentTranslation.y; this.setOrigin(newOx, newOy); }, getContentBBox: function() { var crect = this.viewport.getBoundingClientRect(); // Using Screen CTM was the only way to get the real viewport bounding box working in both // Google Chrome and Firefox. var screenCTM = this.viewport.getScreenCTM(); // for non-default origin we need to take the viewport translation into account var viewportCTM = this.viewport.getCTM(); var bbox = g.rect({ x: crect.left - screenCTM.e + viewportCTM.e, y: crect.top - screenCTM.f + viewportCTM.f, width: crect.width, height: crect.height }); return bbox; }, createViewForModel: function(cell) { var view; var type = cell.get('type'); var module = type.split('.')[0]; var entity = type.split('.')[1]; // If there is a special view defined for this model, use that one instead of the default `elementView`/`linkView`. if (joint.shapes[module] && joint.shapes[module][entity + 'View']) { view = new joint.shapes[module][entity + 'View']({ model: cell, interactive: this.options.interactive }); } else if (cell instanceof joint.dia.Element) { view = new this.options.elementView({ model: cell, interactive: this.options.interactive }); } else { view = new this.options.linkView({ model: cell, interactive: this.options.interactive }); } return view; }, onAddCell: function(cell, graph, options) { if (this.options.async && options.async !== false && _.isNumber(options.position)) { this._asyncCells = this._asyncCells || []; this._asyncCells.push(cell); if (options.position == 0) { if (this._frameId) throw 'another asynchronous rendering in progress'; this.asyncRenderCells(this._asyncCells); delete this._asyncCells; } } else { this.addCell(cell); } }, addCell: function(cell) { var view = this.createViewForModel(cell); V(this.viewport).append(view.el); view.paper = this; view.render(); // This is the only way to prevent image dragging in Firefox that works. // Setting -moz-user-select: none, draggable="false" attribute or user-drag: none didn't help. $(view.el).find('image').on('dragstart', function() { return false; }); }, beforeRenderCells: function(cells) { // Make sure links are always added AFTER elements. // They wouldn't find their sources/targets in the DOM otherwise. cells.sort(function(a, b) { return a instanceof joint.dia.Link ? 1 : -1; }); return cells; }, afterRenderCells: function() { this.sortCells(); }, resetCells: function(cellsCollection, opt) { $(this.viewport).empty(); var cells = cellsCollection.models.slice(); cells = this.beforeRenderCells(cells, opt); if (this._frameId) { joint.util.cancelFrame(this._frameId); delete this._frameId; } if (this.options.async) { this.asyncRenderCells(cells, opt); // Sort the cells once all elements rendered (see asyncRenderCells()). } else { _.each(cells, this.addCell, this); // Sort the cells in the DOM manually as we might have changed the order they // were added to the DOM (see above). this.sortCells(); } }, removeCells: function() { this.model.get('cells').each(function(cell) { var view = this.findViewByModel(cell); view && view.remove(); }, this); }, asyncBatchAdded: _.identity, asyncRenderCells: function(cells, opt) { var done = false; if (this._frameId) { _.each(_.range(this.options.async && this.options.async.batchSize || 50), function() { var cell = cells.shift(); done = !cell; if (!done) this.addCell(cell); }, this); this.asyncBatchAdded(); } if (done) { delete this._frameId; this.afterRenderCells(opt); this.trigger('render:done', opt); } else { this._frameId = joint.util.nextFrame(_.bind(function() { this.asyncRenderCells(cells, opt); }, this)); } }, sortCells: function() { // Run insertion sort algorithm in order to efficiently sort DOM elements according to their // associated model `z` attribute. var $cells = $(this.viewport).children('[model-id]'); var cells = this.model.get('cells'); joint.util.sortElements($cells, function(a, b) { var cellA = cells.get($(a).attr('model-id')); var cellB = cells.get($(b).attr('model-id')); return (cellA.get('z') || 0) > (cellB.get('z') || 0) ? 1 : -1; }); }, scale: function(sx, sy, ox, oy) { sy = sy || sx; if (_.isUndefined(ox)) { ox = 0; oy = 0; } // Remove previous transform so that the new scale is not affected by previous scales, especially // the old translate() does not affect the new translate if an origin is specified. V(this.viewport).attr('transform', ''); var oldTx = this.options.origin.x; var oldTy = this.options.origin.y; // TODO: V.scale() doesn't support setting scale origin. #Fix if (ox || oy || oldTx || oldTy) { var newTx = oldTx - ox * (sx - 1); var newTy = oldTy - oy * (sy - 1); this.setOrigin(newTx, newTy); } V(this.viewport).scale(sx, sy); this.trigger('scale', sx, sy, ox, oy); return this; }, rotate: function(deg, ox, oy) { // If the origin is not set explicitely, rotate around the center. Note that // we must use the plain bounding box (`this.el.getBBox()` instead of the one that gives us // the real bounding box (`bbox()`) including transformations). if (_.isUndefined(ox)) { var bbox = this.viewport.getBBox(); ox = bbox.width / 2; oy = bbox.height / 2; } V(this.viewport).rotate(deg, ox, oy); }, // Find the first view climbing up the DOM tree starting at element `el`. Note that `el` can also // be a selector or a jQuery object. findView: function(el) { var $el = this.$(el); if ($el.length === 0 || $el[0] === this.el) { return undefined; } return $el.data('view') || this.findView($el.parent()); }, // Find a view for a model `cell`. `cell` can also be a string representing a model `id`. findViewByModel: function(cell) { var id = _.isString(cell) ? cell : cell.id; var $view = this.$('[model-id="' + id + '"]'); return $view.length ? $view.data('view') : undefined; }, // Find all views at given point findViewsFromPoint: function(p) { p = g.point(p); var views = _.map(this.model.getElements(), this.findViewByModel); return _.filter(views, function(view) { return view && g.rect(V(view.el).bbox(false, this.viewport)).containsPoint(p); }, this); }, // Find all views in given area findViewsInArea: function(r) { r = g.rect(r); var views = _.map(this.model.getElements(), this.findViewByModel); return _.filter(views, function(view) { return view && r.intersect(g.rect(V(view.el).bbox(false, this.viewport))); }, this); }, getModelById: function(id) { return this.model.getCell(id); }, snapToGrid: function(p) { // Convert global coordinates to the local ones of the `viewport`. Otherwise, // improper transformation would be applied when the viewport gets transformed (scaled/rotated). var localPoint = V(this.viewport).toLocalPoint(p.x, p.y); return { x: g.snapToGrid(localPoint.x, this.options.gridSize), y: g.snapToGrid(localPoint.y, this.options.gridSize) }; }, // Transform client coordinates to the paper local coordinates. // Useful when you have a mouse event object and you'd like to get coordinates // inside the paper that correspond to `evt.clientX` and `evt.clientY` point. // Exmaple: var paperPoint = paper.clientToLocalPoint({ x: evt.clientX, y: evt.clientY }); clientToLocalPoint: function(p) { var svgPoint = this.svg.createSVGPoint(); svgPoint.x = p.x; svgPoint.y = p.y; // This is a hack for Firefox! If there wasn't a fake (non-visible) rectangle covering the // whole SVG area, `$(paper.svg).offset()` used below won't work. var fakeRect = V('rect', { width: this.options.width, height: this.options.height, x: 0, y: 0, opacity: 0 }); V(this.svg).prepend(fakeRect); var paperOffset = $(this.svg).offset(); // Clean up the fake rectangle once we have the offset of the SVG document. fakeRect.remove(); var scrollTop = document.body.scrollTop || document.documentElement.scrollTop; var scrollLeft = document.body.scrollLeft || document.documentElement.scrollLeft; svgPoint.x += scrollLeft - paperOffset.left; svgPoint.y += scrollTop - paperOffset.top; // Transform point into the viewport coordinate system. var pointTransformed = svgPoint.matrixTransform(this.viewport.getCTM().inverse()); return pointTransformed; }, getDefaultLink: function(cellView, magnet) { return _.isFunction(this.options.defaultLink) // default link is a function producing link model ? this.options.defaultLink.call(this, cellView, magnet) // default link is the Backbone model : this.options.defaultLink.clone(); }, // Cell highlighting // ----------------- onCellHighlight: function(cellView, el) { V(el).addClass('highlighted'); }, onCellUnhighlight: function(cellView, el) { V(el).removeClass('highlighted'); }, // Interaction. // ------------ mousedblclick: function(evt) { evt.preventDefault(); evt = joint.util.normalizeEvent(evt); var view = this.findView(evt.target); if (this.guard(evt, view)) return; var localPoint = this.snapToGrid({ x: evt.clientX, y: evt.clientY }); if (view) { view.pointerdblclick(evt, localPoint.x, localPoint.y); } else { this.trigger('blank:pointerdblclick', evt, localPoint.x, localPoint.y); } }, mouseclick: function(evt) { // Trigger event when mouse not moved. if (!this._mousemoved) { evt = joint.util.normalizeEvent(evt); var view = this.findView(evt.target); if (this.guard(evt, view)) return; var localPoint = this.snapToGrid({ x: evt.clientX, y: evt.clientY }); if (view) { view.pointerclick(evt, localPoint.x, localPoint.y); } else { this.trigger('blank:pointerclick', evt, localPoint.x, localPoint.y); } } this._mousemoved = false; }, // Guard guards the event received. If the event is not interesting, guard returns `true`. // Otherwise, it return `false`. guard: function(evt, view) { if (view && view.model && (view.model instanceof joint.dia.Cell)) { return false; } else if (this.svg === evt.target || this.el === evt.target || $.contains(this.svg, evt.target)) { return false; } return true; // Event guarded. Paper should not react on it in any way. }, contextmenu: function(evt) { evt = joint.util.normalizeEvent(evt); var view = this.findView(evt.target); if (this.guard(evt, view)) return; var localPoint = this.snapToGrid({ x: evt.clientX, y: evt.clientY }); if (view) { view.contextmenu(evt, localPoint.x, localPoint.y); } else { this.trigger('blank:contextmenu', evt, localPoint.x, localPoint.y); } }, pointerdown: function(evt) { evt = joint.util.normalizeEvent(evt); var view = this.findView(evt.target); if (this.guard(evt, view)) return; var localPoint = this.snapToGrid({ x: evt.clientX, y: evt.clientY }); if (view) { this.sourceView = view; view.pointerdown(evt, localPoint.x, localPoint.y); } else { this.trigger('blank:pointerdown', evt, localPoint.x, localPoint.y); } }, pointermove: function(evt) { evt.preventDefault(); evt = joint.util.normalizeEvent(evt); if (this.sourceView) { // Mouse moved. this._mousemoved = true; var localPoint = this.snapToGrid({ x: evt.clientX, y: evt.clientY }); this.sourceView.pointermove(evt, localPoint.x, localPoint.y); } }, pointerup: function(evt) { evt = joint.util.normalizeEvent(evt); var localPoint = this.snapToGrid({ x: evt.clientX, y: evt.clientY }); if (this.sourceView) { this.sourceView.pointerup(evt, localPoint.x, localPoint.y); //"delete sourceView" occasionally throws an error in chrome (illegal access exception) this.sourceView = null; } else { this.trigger('blank:pointerup', evt, localPoint.x, localPoint.y); } }, cellMouseover: function(evt) { evt = joint.util.normalizeEvent(evt); var view = this.findView(evt.target); if (view) { if (this.guard(evt, view)) return; view.mouseover(evt); } }, cellMouseout: function(evt) { evt = joint.util.normalizeEvent(evt); var view = this.findView(evt.target); if (view) { if (this.guard(evt, view)) return; view.mouseout(evt); } } }); // JointJS library. // (c) 2011-2013 client IO joint.shapes.basic = {}; joint.shapes.basic.Generic = joint.dia.Element.extend({ defaults: joint.util.deepSupplement({ type: 'basic.Generic', attrs: { '.': { fill: '#ffffff', stroke: 'none' } } }, joint.dia.Element.prototype.defaults) }); joint.shapes.basic.Rect = joint.shapes.basic.Generic.extend({ markup: '<g class="rotatable"><g class="scalable"><rect/></g><text/></g>', defaults: joint.util.deepSupplement({ type: 'basic.Rect', attrs: { 'rect': { fill: '#ffffff', stroke: '#000000', width: 100, height: 60 }, 'text': { fill: '#000000', text: '', 'font-size': 14, 'ref-x': .5, 'ref-y': .5, 'text-anchor': 'middle', 'y-alignment': 'middle', 'font-family': 'Arial, helvetica, sans-serif' } } }, joint.shapes.basic.Generic.prototype.defaults) }); joint.shapes.basic.TextView = joint.dia.ElementView.extend({ initialize: function() { joint.dia.ElementView.prototype.initialize.apply(this, arguments); // The element view is not automatically rescaled to fit the model size // when the attribute 'attrs' is changed. this.listenTo(this.model, 'change:attrs', this.resize); } }); joint.shapes.basic.Text = joint.shapes.basic.Generic.extend({ markup: '<g class="rotatable"><g class="scalable"><text/></g></g>', defaults: joint.util.deepSupplement({ type: 'basic.Text', attrs: { 'text': { 'font-size': 18, fill: '#000000' } } }, joint.shapes.basic.Generic.prototype.defaults) }); joint.shapes.basic.Circle = joint.shapes.basic.Generic.extend({ markup: '<g class="rotatable"><g class="scalable"><circle/></g><text/></g>', defaults: joint.util.deepSupplement({ type: 'basic.Circle', size: { width: 60, height: 60 }, attrs: { 'circle': { fill: '#ffffff', stroke: '#000000', r: 30, cx: 30, cy: 30 }, 'text': { 'font-size': 14, text: '', 'text-anchor': 'middle', 'ref-x': .5, 'ref-y': .5, 'y-alignment': 'middle', fill: '#000000', 'font-family': 'Arial, helvetica, sans-serif' } } }, joint.shapes.basic.Generic.prototype.defaults) }); joint.shapes.basic.Ellipse = joint.shapes.basic.Generic.extend({ markup: '<g class="rotatable"><g class="scalable"><ellipse/></g><text/></g>', defaults: joint.util.deepSupplement({ type: 'basic.Ellipse', size: { width: 60, height: 40 }, attrs: { 'ellipse': { fill: '#ffffff', stroke: '#000000', rx: 30, ry: 20, cx: 30, cy: 20 }, 'text': { 'font-size': 14, text: '', 'text-anchor': 'middle', 'ref-x': .5, 'ref-y': .5, 'y-alignment': 'middle', fill: '#000000', 'font-family': 'Arial, helvetica, sans-serif' } } }, joint.shapes.basic.Generic.prototype.defaults) }); joint.shapes.basic.Polygon = joint.shapes.basic.Generic.extend({ markup: '<g class="rotatable"><g class="scalable"><polygon/></g><text/></g>', defaults: joint.util.deepSupplement({ type: 'basic.Polygon', size: { width: 60, height: 40 }, attrs: { 'polygon': { fill: '#ffffff', stroke: '#000000' }, 'text': { 'font-size': 14, text: '', 'text-anchor': 'middle', 'ref-x': .5, 'ref-dy': 20, 'y-alignment': 'middle', fill: '#000000', 'font-family': 'Arial, helvetica, sans-serif' } } }, joint.shapes.basic.Generic.prototype.defaults) }); joint.shapes.basic.Polyline = joint.shapes.basic.Generic.extend({ markup: '<g class="rotatable"><g class="scalable"><polyline/></g><text/></g>', defaults: joint.util.deepSupplement({ type: 'basic.Polyline', size: { width: 60, height: 40 }, attrs: { 'polyline': { fill: '#ffffff', stroke: '#000000' }, 'text': { 'font-size': 14, text: '', 'text-anchor': 'middle', 'ref-x': .5, 'ref-dy': 20, 'y-alignment': 'middle', fill: '#000000', 'font-family': 'Arial, helvetica, sans-serif' } } }, joint.shapes.basic.Generic.prototype.defaults) }); joint.shapes.basic.Image = joint.shapes.basic.Generic.extend({ markup: '<g class="rotatable"><g class="scalable"><image/></g><text/></g>', defaults: joint.util.deepSupplement({ type: 'basic.Image', attrs: { 'text': { 'font-size': 14, text: '', 'text-anchor': 'middle', 'ref-x': .5, 'ref-dy': 20, 'y-alignment': 'middle', fill: '#000000', 'font-family': 'Arial, helvetica, sans-serif' } } }, joint.shapes.basic.Generic.prototype.defaults) }); joint.shapes.basic.Path = joint.shapes.basic.Generic.extend({ markup: '<g class="rotatable"><g class="scalable"><path/></g><text/></g>', defaults: joint.util.deepSupplement({ type: 'basic.Path', size: { width: 60, height: 60 }, attrs: { 'path': { fill: '#ffffff', stroke: '#000000' }, 'text': { 'font-size': 14, text: '', 'text-anchor': 'middle', 'ref': 'path', 'ref-x': .5, 'ref-dy': 10, fill: '#000000', 'font-family': 'Arial, helvetica, sans-serif' } } }, joint.shapes.basic.Generic.prototype.defaults) }); joint.shapes.basic.Rhombus = joint.shapes.basic.Path.extend({ defaults: joint.util.deepSupplement({ type: 'basic.Rhombus', attrs: { 'path': { d: 'M 30 0 L 60 30 30 60 0 30 z' }, 'text': { 'ref-y': .5, 'y-alignment': 'middle' } } }, joint.shapes.basic.Path.prototype.defaults) }); // PortsModelInterface is a common interface for shapes that have ports. This interface makes it easy // to create new shapes with ports functionality. It is assumed that the new shapes have // `inPorts` and `outPorts` array properties. Only these properties should be used to set ports. // In other words, using this interface, it is no longer recommended to set ports directly through the // `attrs` object. // Usage: // joint.shapes.custom.MyElementWithPorts = joint.shapes.basic.Path.extend(_.extend({}, joint.shapes.basic.PortsModelInterface, { // getPortAttrs: function(portName, index, total, selector, type) { // var attrs = {}; // var portClass = 'port' + index; // var portSelector = selector + '>.' + portClass; // var portTextSelector = portSelector + '>text'; // var portCircleSelector = portSelector + '>circle'; // // attrs[portTextSelector] = { text: portName }; // attrs[portCircleSelector] = { port: { id: portName || _.uniqueId(type) , type: type } }; // attrs[portSelector] = { ref: 'rect', 'ref-y': (index + 0.5) * (1 / total) }; // // if (selector === '.outPorts') { attrs[portSelector]['ref-dx'] = 0; } // // return attrs; // } //})); joint.shapes.basic.PortsModelInterface = { initialize: function() { this.updatePortsAttrs(); this.on('change:inPorts change:outPorts', this.updatePortsAttrs, this); // Call the `initialize()` of the parent. this.constructor.__super__.constructor.__super__.initialize.apply(this, arguments); }, updatePortsAttrs: function(eventName) { // Delete previously set attributes for ports. var currAttrs = this.get('attrs'); _.each(this._portSelectors, function(selector) { if (currAttrs[selector]) delete currAttrs[selector]; }); // This holds keys to the `attrs` object for all the port specific attribute that // we set in this method. This is necessary in order to remove previously set // attributes for previous ports. this._portSelectors = []; var attrs = {}; _.each(this.get('inPorts'), function(portName, index, ports) { var portAttributes = this.getPortAttrs(portName, index, ports.length, '.inPorts', 'in'); this._portSelectors = this._portSelectors.concat(_.keys(portAttributes)); _.extend(attrs, portAttributes); }, this); _.each(this.get('outPorts'), function(portName, index, ports) { var portAttributes = this.getPortAttrs(portName, index, ports.length, '.outPorts', 'out'); this._portSelectors = this._portSelectors.concat(_.keys(portAttributes)); _.extend(attrs, portAttributes); }, this); // Silently set `attrs` on the cell so that noone knows the attrs have changed. This makes sure // that, for example, command manager does not register `change:attrs` command but only // the important `change:inPorts`/`change:outPorts` command. this.attr(attrs, { silent: true }); // Manually call the `processPorts()` method that is normally called on `change:attrs` (that we just made silent). this.processPorts(); // Let the outside world (mainly the `ModelView`) know that we're done configuring the `attrs` object. this.trigger('process:ports'); }, getPortSelector: function(name) { var selector = '.inPorts'; var index = this.get('inPorts').indexOf(name); if (index < 0) { selector = '.outPorts'; index = this.get('outPorts').indexOf(name); if (index < 0) throw new Error("getPortSelector(): Port doesn't exist."); } return selector + '>g:nth-child(' + (index + 1) + ')>circle'; } }; joint.shapes.basic.PortsViewInterface = { initialize: function() { // `Model` emits the `process:ports` whenever it's done configuring the `attrs` object for ports. this.listenTo(this.model, 'process:ports', this.update); joint.dia.ElementView.prototype.initialize.apply(this, arguments); }, update: function() { // First render ports so that `attrs` can be applied to those newly created DOM elements // in `ElementView.prototype.update()`. this.renderPorts(); joint.dia.ElementView.prototype.update.apply(this, arguments); }, renderPorts: function() { var $inPorts = this.$('.inPorts').empty(); var $outPorts = this.$('.outPorts').empty(); var portTemplate = _.template(this.model.portMarkup); _.each(_.filter(this.model.ports, function(p) { return p.type === 'in'; }), function(port, index) { $inPorts.append(V(portTemplate({ id: index, port: port })).node); }); _.each(_.filter(this.model.ports, function(p) { return p.type === 'out'; }), function(port, index) { $outPorts.append(V(portTemplate({ id: index, port: port })).node); }); } }; joint.shapes.basic.TextBlock = joint.shapes.basic.Generic.extend({ markup: ['<g class="rotatable"><g class="scalable"><rect/></g><switch>', // if foreignObject supported '<foreignObject requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility" class="fobj">', '<body xmlns="http://www.w3.org/1999/xhtml"><div/></body>', '</foreignObject>', // else foreignObject is not supported (fallback for IE) '<text class="content"/>', '</switch></g>'].join(''), defaults: joint.util.deepSupplement({ type: 'basic.TextBlock', // see joint.css for more element styles attrs: { rect: { fill: '#ffffff', stroke: '#000000', width: 80, height: 100 }, text: { fill: '#000000', 'font-size': 14, 'font-family': 'Arial, helvetica, sans-serif' }, '.content': { text: '', ref: 'rect', 'ref-x': .5, 'ref-y': .5, 'y-alignment': 'middle', 'x-alignment': 'middle' } }, content: '' }, joint.shapes.basic.Generic.prototype.defaults), initialize: function() { if (typeof SVGForeignObjectElement !== 'undefined') { // foreignObject supported this.setForeignObjectSize(this, this.get('size')); this.setDivContent(this, this.get('content')); this.listenTo(this, 'change:size', this.setForeignObjectSize); this.listenTo(this, 'change:content', this.setDivContent); } joint.shapes.basic.Generic.prototype.initialize.apply(this, arguments); }, setForeignObjectSize: function(cell, size) { // Selector `foreignObject' doesn't work accross all browsers, we'r using class selector instead. // We have to clone size as we don't want attributes.div.style to be same object as attributes.size. cell.attr({ '.fobj': _.clone(size), div: { style: _.clone(size) } }); }, setDivContent: function(cell, content) { // Append the content to div as html. cell.attr({ div : { html: content }}); } }); // TextBlockView implements the fallback for IE when no foreignObject exists and // the text needs to be manually broken. joint.shapes.basic.TextBlockView = joint.dia.ElementView.extend({ initialize: function() { joint.dia.ElementView.prototype.initialize.apply(this, arguments); if (typeof SVGForeignObjectElement === 'undefined') { this.noSVGForeignObjectElement = true; this.listenTo(this.model, 'change:content', function(cell) { // avoiding pass of extra paramters this.updateContent(cell); }); } }, update: function(cell, renderingOnlyAttrs) { if (this.noSVGForeignObjectElement) { var model = this.model; // Update everything but the content first. var noTextAttrs = _.omit(renderingOnlyAttrs || model.get('attrs'), '.content'); joint.dia.ElementView.prototype.update.call(this, model, noTextAttrs); if (!renderingOnlyAttrs || _.has(renderingOnlyAttrs, '.content')) { // Update the content itself. this.updateContent(model, renderingOnlyAttrs); } } else { joint.dia.ElementView.prototype.update.call(this, model, renderingOnlyAttrs); } }, updateContent: function(cell, renderingOnlyAttrs) { // Create copy of the text attributes var textAttrs = _.merge({}, (renderingOnlyAttrs || cell.get('attrs'))['.content']); delete textAttrs.text; // Break the content to fit the element size taking into account the attributes // set on the model. var text = joint.util.breakText(cell.get('content'), cell.get('size'), textAttrs, { // measuring sandbox svg document svgDocument: this.paper.svg }); // Create a new attrs with same structure as the model attrs { text: { *textAttributes* }} var attrs = joint.util.setByPath({}, '.content', textAttrs, '/'); // Replace text attribute with the one we just processed. attrs['.content'].text = text; // Update the view using renderingOnlyAttributes parameter. joint.dia.ElementView.prototype.update.call(this, cell, attrs); } }); joint.routers.orthogonal = (function() { // bearing -> opposite bearing var opposite = { N: 'S', S: 'N', E: 'W', W: 'E' }; // bearing -> radians var radians = { N: -Math.PI / 2 * 3, S: -Math.PI / 2, E: 0, W: Math.PI }; // HELPERS // // simple bearing method (calculates only orthogonal cardinals) function bearing(from, to) { if (from.x == to.x) return from.y > to.y ? 'N' : 'S'; if (from.y == to.y) return from.x > to.x ? 'W' : 'E'; return null; } // returns either width or height of a bbox based on the given bearing function boxSize(bbox, brng) { return bbox[brng == 'W' || brng == 'E' ? 'width' : 'height']; } // expands a box by specific value function expand(bbox, val) { return g.rect(bbox).moveAndExpand({ x: -val, y: -val, width: 2 * val, height: 2 * val }); } // transform point to a rect function pointBox(p) { return g.rect(p.x, p.y, 0, 0); } // returns a minimal rect which covers the given boxes function boundary(bbox1, bbox2) { var x1 = Math.min(bbox1.x, bbox2.x); var y1 = Math.min(bbox1.y, bbox2.y); var x2 = Math.max(bbox1.x + bbox1.width, bbox2.x + bbox2.width); var y2 = Math.max(bbox1.y + bbox1.height, bbox2.y + bbox2.height); return g.rect(x1, y1, x2 - x1, y2 - y1); } // returns a point `p` where lines p,p1 and p,p2 are perpendicular and p is not contained // in the given box function freeJoin(p1, p2, bbox) { var p = g.point(p1.x, p2.y); if (bbox.containsPoint(p)) p = g.point(p2.x, p1.y); // kept for reference // if (bbox.containsPoint(p)) p = null; return p; } // PARTIAL ROUTERS // function vertexVertex(from, to, brng) { var p1 = g.point(from.x, to.y); var p2 = g.point(to.x, from.y); var d1 = bearing(from, p1); var d2 = bearing(from, p2); var xBrng = opposite[brng]; var p = (d1 == brng || (d1 != xBrng && (d2 == xBrng || d2 != brng))) ? p1 : p2; return { points: [p], direction: bearing(p, to) }; } function elementVertex(from, to, fromBBox) { var p = freeJoin(from, to, fromBBox); return { points: [p], direction: bearing(p, to) }; } function vertexElement(from, to, toBBox, brng) { var route = {}; var pts = [g.point(from.x, to.y), g.point(to.x, from.y)]; var freePts = _.filter(pts, function(pt) { return !toBBox.containsPoint(pt); }); var freeBrngPts = _.filter(freePts, function(pt) { return bearing(pt, from) != brng; }); var p; if (freeBrngPts.length > 0) { // try to pick a point which bears the same direction as the previous segment p = _.filter(freeBrngPts, function(pt) { return bearing(from, pt) == brng; }).pop(); p = p || freeBrngPts[0]; route.points = [p]; route.direction = bearing(p, to); } else { // Here we found only points which are either contained in the element or they would create // a link segment going in opposite direction from the previous one. // We take the point inside element and move it outside the element in the direction the // route is going. Now we can join this point with the current end (using freeJoin). p = _.difference(pts, freePts)[0]; var p2 = g.point(to).move(p, -boxSize(toBBox, brng) / 2); var p1 = freeJoin(p2, from, toBBox); route.points = [p1, p2]; route.direction = bearing(p2, to); } return route; } function elementElement(from, to, fromBBox, toBBox) { var route = elementVertex(to, from, toBBox); var p1 = route.points[0]; if (fromBBox.containsPoint(p1)) { route = elementVertex(from, to, fromBBox); var p2 = route.points[0]; if (toBBox.containsPoint(p2)) { var fromBorder = g.point(from).move(p2, -boxSize(fromBBox, bearing(from, p2)) / 2); var toBorder = g.point(to).move(p1, -boxSize(toBBox, bearing(to, p1)) / 2); var mid = g.line(fromBorder, toBorder).midpoint(); var startRoute = elementVertex(from, mid, fromBBox); var endRoute = vertexVertex(mid, to, startRoute.direction); route.points = [startRoute.points[0], endRoute.points[0]]; route.direction = endRoute.direction; } } return route; } // Finds route for situations where one of end is inside the other. // Typically the route is conduct outside the outer element first and // let go back to the inner element. function insideElement(from, to, fromBBox, toBBox, brng) { var route = {}; var bndry = expand(boundary(fromBBox, toBBox), 1); // start from the point which is closer to the boundary var reversed = bndry.center().distance(to) > bndry.center().distance(from); var start = reversed ? to : from; var end = reversed ? from : to; var p1, p2, p3; if (brng) { // Points on circle with radius equals 'W + H` are always outside the rectangle // with width W and height H if the center of that circle is the center of that rectangle. p1 = g.point.fromPolar(bndry.width + bndry.height, radians[brng], start); p1 = bndry.pointNearestToPoint(p1).move(p1, -1); } else { p1 = bndry.pointNearestToPoint(start).move(start, 1); } p2 = freeJoin(p1, end, bndry); if (p1.round().equals(p2.round())) { p2 = g.point.fromPolar(bndry.width + bndry.height, g.toRad(p1.theta(start)) + Math.PI / 2, end); p2 = bndry.pointNearestToPoint(p2).move(end, 1).round(); p3 = freeJoin(p1, p2, bndry); route.points = reversed ? [p2, p3, p1] : [p1, p3, p2]; } else { route.points = reversed ? [p2, p1] : [p1, p2]; } route.direction = reversed ? bearing(p1, to) : bearing(p2, to); return route; } // MAIN ROUTER // // Return points that one needs to draw a connection through in order to have a orthogonal link // routing from source to target going through `vertices`. function findOrthogonalRoute(vertices, opt, linkView) { var padding = opt.elementPadding || 20; var orthogonalVertices = []; var sourceBBox = expand(linkView.sourceBBox, padding); var targetBBox = expand(linkView.targetBBox, padding); vertices = _.map(vertices, g.point); vertices.unshift(sourceBBox.center()); vertices.push(targetBBox.center()); var brng; for (var i = 0, max = vertices.length - 1; i < max; i++) { var route = null; var from = vertices[i]; var to = vertices[i + 1]; var isOrthogonal = !!bearing(from, to); if (i == 0) { if (i + 1 == max) { // route source -> target // Expand one of elements by 1px so we detect also situations when they // are positioned one next other with no gap between. if (sourceBBox.intersect(expand(targetBBox, 1))) { route = insideElement(from, to, sourceBBox, targetBBox); } else if (!isOrthogonal) { route = elementElement(from, to, sourceBBox, targetBBox); } } else { // route source -> vertex if (sourceBBox.containsPoint(to)) { route = insideElement(from, to, sourceBBox, expand(pointBox(to), padding)); } else if (!isOrthogonal) { route = elementVertex(from, to, sourceBBox); } } } else if (i + 1 == max) { // route vertex -> target var orthogonalLoop = isOrthogonal && bearing(to, from) == brng; if (targetBBox.containsPoint(from) || orthogonalLoop) { route = insideElement(from, to, expand(pointBox(from), padding), targetBBox, brng); } else if (!isOrthogonal) { route = vertexElement(from, to, targetBBox, brng); } } else if (!isOrthogonal) { // route vertex -> vertex route = vertexVertex(from, to, brng); } if (route) { Array.prototype.push.apply(orthogonalVertices, route.points); brng = route.direction; } else { // orthogonal route and not looped brng = bearing(from, to); } if (i + 1 < max) { orthogonalVertices.push(to); } } return orthogonalVertices; }; return findOrthogonalRoute; })(); joint.routers.manhattan = (function() { 'use strict'; var config = { // size of the step to find a route step: 10, // use of the perpendicular linkView option to connect center of element with first vertex perpendicular: true, // tells how to divide the paper when creating the elements map mapGridSize: 100, // should be source or target not to be consider as an obstacle excludeEnds: [], // 'source', 'target' // should be any element with a certain type not to be consider as an obstacle excludeTypes: ['basic.Text'], // if number of route finding loops exceed the maximum, stops searching and returns // fallback route maximumLoops: 500, // possible starting directions from an element startDirections: ['left', 'right', 'top', 'bottom'], // possible ending directions to an element endDirections: ['left', 'right', 'top', 'bottom'], // specify directions above directionMap: { right: { x: 1, y: 0 }, bottom: { x: 0, y: 1 }, left: { x: -1, y: 0 }, top: { x: 0, y: -1 } }, // maximum change of the direction maxAllowedDirectionChange: 1, // padding applied on the element bounding boxes paddingBox: function() { var step = this.step; return { x: -step, y: -step, width: 2 * step, height: 2 * step }; }, // an array of directions to find next points on the route directions: function() { var step = this.step; return [ { offsetX: step , offsetY: 0 , cost: step }, { offsetX: 0 , offsetY: step , cost: step }, { offsetX: -step , offsetY: 0 , cost: step }, { offsetX: 0 , offsetY: -step , cost: step } ]; }, // a penalty received for direction change penalties: function() { return [0, this.step / 2, this.step]; }, // heurestic method to determine the distance between two points estimateCost: function(from, to) { return from.manhattanDistance(to); }, // a simple route used in situations, when main routing method fails // (exceed loops, inaccessible). fallbackRoute: function(from, to, opts) { // Find an orthogonal route ignoring obstacles. var prevDirIndexes = opts.prevDirIndexes || {}; var point = (prevDirIndexes[from] || 0) % 2 ? g.point(from.x, to.y) : g.point(to.x, from.y); return [point, to]; }, // if a function is provided, it's used to route the link while dragging an end // i.e. function(from, to, opts) { return []; } draggingRoute: null }; // reconstructs a route by concating points with their parents function reconstructRoute(parents, point) { var route = []; var prevDiff = { x: 0, y: 0 }; var current = point; var parent; while ((parent = parents[current])) { var diff = parent.difference(current); if (!diff.equals(prevDiff)) { route.unshift(current); prevDiff = diff; } current = parent; } route.unshift(current); return route; }; // find points around the rectangle taking given directions in the account function getRectPoints(bbox, directionList, opts) { var step = opts.step; var center = bbox.center(); var startPoints = _.chain(opts.directionMap).pick(directionList).map(function(direction) { var x = direction.x * bbox.width / 2; var y = direction.y * bbox.height / 2; var point = g.point(center).offset(x, y).snapToGrid(step); if (bbox.containsPoint(point)) { point.offset(direction.x * step, direction.y * step); } return point; }).value(); return startPoints; }; // returns a direction index from start point to end point function getDirection(start, end, dirLen) { var dirAngle = 360 / dirLen; var q = Math.floor(start.theta(end) / dirAngle); return dirLen - q; } // finds the route between to points/rectangles implementing A* alghoritm function findRoute(start, end, map, opt) { var startDirections = opt.reversed ? opt.endDirections : opt.startDirections; var endDirections = opt.reversed ? opt.startDirections : opt.endDirections; // set of points we start pathfinding from var startSet = start instanceof g.rect ? getRectPoints(start, startDirections, opt) : [start]; // set of points we want the pathfinding to finish at var endSet = end instanceof g.rect ? getRectPoints(end, endDirections, opt) : [end]; var startCenter = startSet.length > 1 ? start.center() : startSet[0]; var endCenter = endSet.length > 1 ? end.center() : endSet[0]; // take into account only accessible end points var endPoints = _.filter(endSet, function(point) { var mapKey = g.point(point).snapToGrid(opt.mapGridSize).toString(); var accesible = _.every(map[mapKey], function(obstacle) { return !obstacle.containsPoint(point); }); return accesible; }); if (endPoints.length) { var step = opt.step; var penalties = opt.penalties; // choose the end point with the shortest estimated path cost var endPoint = _.chain(endPoints).invoke('snapToGrid', step).min(function(point) { return opt.estimateCost(startCenter, point); }).value(); var parents = {}; var costFromStart = {}; var totalCost = {}; // directions var dirs = opt.directions; var dirLen = dirs.length; var dirHalfLen = dirLen / 2; var dirIndexes = opt.previousDirIndexes || {}; // The set of point already evaluated. var closeHash = {}; // keeps only information whether a point was evaluated' // The set of tentative points to be evaluated, initially containing the start points var openHash = {}; // keeps only information whether a point is to be evaluated' var openSet = _.chain(startSet).invoke('snapToGrid', step).each(function(point) { var key = point.toString(); costFromStart[key] = 0; // Cost from start along best known path. totalCost[key] = opt.estimateCost(point, endPoint); dirIndexes[key] = dirIndexes[key] || getDirection(startCenter, point, dirLen); openHash[key] = true; }).map(function(point) { return point.toString(); }).sortBy(function(pointKey) { return totalCost[pointKey]; }).value(); var loopCounter = opt.maximumLoops; var maxAllowedDirectionChange = opt.maxAllowedDirectionChange; // main route finding loop while (openSet.length && loopCounter--) { var currentKey = openSet[0]; var currentPoint = g.point(currentKey); if (endPoint.equals(currentPoint)) { opt.previousDirIndexes = _.pick(dirIndexes, currentKey); return reconstructRoute(parents, currentPoint); } // remove current from the open list openSet.splice(0, 1); openHash[neighborKey] = null; // add current to the close list closeHash[neighborKey] = true; var currentDirIndex = dirIndexes[currentKey]; var currentDist = costFromStart[currentKey]; for (var dirIndex = 0; dirIndex < dirLen; dirIndex++) { var dirChange = Math.abs(dirIndex - currentDirIndex); if (dirChange > dirHalfLen) { dirChange = dirLen - dirChange; } // if the direction changed rapidly don't use this point if (dirChange > maxAllowedDirectionChange) { continue; } var dir = dirs[dirIndex]; var neighborPoint = g.point(currentPoint).offset(dir.offsetX, dir.offsetY); var neighborKey = neighborPoint.toString(); if (closeHash[neighborKey]) { continue; } // is point accesible - no obstacle in the way var mapKey = g.point(neighborPoint).snapToGrid(opt.mapGridSize).toString(); var isAccesible = _.every(map[mapKey], function(obstacle) { return !obstacle.containsPoint(neighborPoint); }); if (!isAccesible) { continue; } var inOpenSet = _.has(openHash, neighborKey); var costToNeighbor = currentDist + dir.cost; if (!inOpenSet || costToNeighbor < costFromStart[neighborKey]) { parents[neighborKey] = currentPoint; dirIndexes[neighborKey] = dirIndex; costFromStart[neighborKey] = costToNeighbor; totalCost[neighborKey] = costToNeighbor + opt.estimateCost(neighborPoint, endPoint) + penalties[dirChange]; if (!inOpenSet) { var openIndex = _.sortedIndex(openSet, neighborKey, function(openKey) { return totalCost[openKey]; }); openSet.splice(openIndex, 0, neighborKey); openHash[neighborKey] = true; } }; }; } } // no route found ('to' point wasn't either accessible or finding route took // way to much calculations) return opt.fallbackRoute(startCenter, endCenter, opt); }; // initiation of the route finding function router(oldVertices, opt) { // resolve some of the options opt.directions = _.result(opt, 'directions'); opt.penalties = _.result(opt, 'penalties'); opt.paddingBox = _.result(opt, 'paddingBox'); // enable/disable linkView perpendicular option this.options.perpendicular = !!opt.perpendicular; // As route changes its shape rapidly when we start finding route from different point // it's necessary to start from the element that was not interacted with // (the position was changed) at very last. var reverseRouting = opt.reversed = (this.lastEndChange === 'source'); var sourceBBox = reverseRouting ? g.rect(this.targetBBox) : g.rect(this.sourceBBox); var targetBBox = reverseRouting ? g.rect(this.sourceBBox) : g.rect(this.targetBBox); // expand boxes by specific padding sourceBBox.moveAndExpand(opt.paddingBox); targetBBox.moveAndExpand(opt.paddingBox); // building an elements map var link = this.model; var graph = this.paper.model; // source or target element could be excluded from set of obstacles var excludedEnds = _.chain(opt.excludeEnds) .map(link.get, link) .pluck('id') .map(graph.getCell, graph).value(); var mapGridSize = opt.mapGridSize; var excludeAncestors = []; var sourceId = link.get('source').id; if (sourceId !== undefined) { var source = graph.getCell(sourceId); if (source !== undefined) { excludeAncestors = _.union(excludeAncestors, _.map(source.getAncestors(), 'id')); }; } var targetId = link.get('target').id; if (targetId !== undefined) { var target = graph.getCell(targetId); if (target !== undefined) { excludeAncestors = _.union(excludeAncestors, _.map(target.getAncestors(), 'id')); } } // builds a map of all elements for quicker obstacle queries (i.e. is a point contained // in any obstacle?) (a simplified grid search) // The paper is divided to smaller cells, where each of them holds an information which // elements belong to it. When we query whether a point is in an obstacle we don't need // to go through all obstacles, we check only those in a particular cell. var map = _.chain(graph.getElements()) // remove source and target element if required .difference(excludedEnds) // remove all elements whose type is listed in excludedTypes array .reject(function(element) { // reject any element which is an ancestor of either source or target return _.contains(opt.excludeTypes, element.get('type')) || _.contains(excludeAncestors, element.id); }) // change elements (models) to their bounding boxes .invoke('getBBox') // expand their boxes by specific padding .invoke('moveAndExpand', opt.paddingBox) // build the map .foldl(function(res, bbox) { var origin = bbox.origin().snapToGrid(mapGridSize); var corner = bbox.corner().snapToGrid(mapGridSize); for (var x = origin.x; x <= corner.x; x += mapGridSize) { for (var y = origin.y; y <= corner.y; y += mapGridSize) { var gridKey = x + '@' + y; res[gridKey] = res[gridKey] || []; res[gridKey].push(bbox); } } return res; }, {}).value(); // pathfinding var newVertices = []; var points = _.map(oldVertices, g.point); var tailPoint = sourceBBox.center(); // find a route by concating all partial routes (routes need to go through the vertices) // startElement -> vertex[1] -> ... -> vertex[n] -> endElement for (var i = 0, len = points.length; i <= len; i++) { var partialRoute = null; var from = to || sourceBBox; var to = points[i]; if (!to) { to = targetBBox; // 'to' is not a vertex. If the target is a point (i.e. it's not an element), we // might use dragging route instead of main routing method if that is enabled. var endingAtPoint = !this.model.get('source').id || !this.model.get('target').id; if (endingAtPoint && _.isFunction(opt.draggingRoute)) { // Make sure we passing points only (not rects). var dragFrom = from instanceof g.rect ? from.center() : from; partialRoute = opt.draggingRoute(dragFrom, to.origin(), opt); } } // if partial route has not been calculated yet use the main routing method to find one partialRoute = partialRoute || findRoute(from, to, map, opt); var leadPoint = _.first(partialRoute); if (leadPoint && leadPoint.equals(tailPoint)) { // remove the first point if the previous partial route had the same point as last partialRoute.shift(); } tailPoint = _.last(partialRoute) || tailPoint; newVertices = newVertices.concat(partialRoute); }; // we might have to reverse the result if we swapped source and target at the beginning return reverseRouting ? newVertices.reverse() : newVertices; }; // public function return function(vertices, opt, linkView) { return router.call(linkView, vertices, _.extend({}, config, opt)); }; })(); joint.routers.metro = (function() { if (!_.isFunction(joint.routers.manhattan)) { throw('Metro requires the manhattan router.'); } var config = { // cost of a diagonal step (calculated if not defined). diagonalCost: null, // an array of directions to find next points on the route directions: function() { var step = this.step; var diagonalCost = this.diagonalCost || Math.ceil(Math.sqrt(step * step << 1)); return [ { offsetX: step , offsetY: 0 , cost: step }, { offsetX: step , offsetY: step , cost: diagonalCost }, { offsetX: 0 , offsetY: step , cost: step }, { offsetX: -step , offsetY: step , cost: diagonalCost }, { offsetX: -step , offsetY: 0 , cost: step }, { offsetX: -step , offsetY: -step , cost: diagonalCost }, { offsetX: 0 , offsetY: -step , cost: step }, { offsetX: step , offsetY: -step , cost: diagonalCost } ]; }, // a simple route used in situations, when main routing method fails // (exceed loops, inaccessible). fallbackRoute: function(from, to, opts) { // Find a route which breaks by 45 degrees ignoring all obstacles. var theta = from.theta(to); var a = { x: to.x, y: from.y }; var b = { x: from.x, y: to.y }; if (theta % 180 > 90) { var t = a; a = b; b = t; } var p1 = (theta % 90) < 45 ? a : b; var l1 = g.line(from, p1); var alpha = 90 * Math.ceil(theta / 90); var p2 = g.point.fromPolar(l1.squaredLength(), g.toRad(alpha + 135), p1); var l2 = g.line(to, p2); var point = l1.intersection(l2); return point ? [point.round(), to] : [to]; } }; // public function return function(vertices, opts, linkView) { return joint.routers.manhattan(vertices, _.extend({}, config, opts), linkView); }; })(); joint.connectors.normal = function(sourcePoint, targetPoint, vertices) { // Construct the `d` attribute of the `<path>` element. var d = ['M', sourcePoint.x, sourcePoint.y]; _.each(vertices, function(vertex) { d.push(vertex.x, vertex.y); }); d.push(targetPoint.x, targetPoint.y); return d.join(' '); }; joint.connectors.rounded = function(sourcePoint, targetPoint, vertices, opts) { var offset = opts.radius || 10; var c1, c2, d1, d2, prev, next; // Construct the `d` attribute of the `<path>` element. var d = ['M', sourcePoint.x, sourcePoint.y]; _.each(vertices, function(vertex, index) { // the closest vertices prev = vertices[index - 1] || sourcePoint; next = vertices[index + 1] || targetPoint; // a half distance to the closest vertex d1 = d2 || g.point(vertex).distance(prev) / 2; d2 = g.point(vertex).distance(next) / 2; // control points c1 = g.point(vertex).move(prev, -Math.min(offset, d1)).round(); c2 = g.point(vertex).move(next, -Math.min(offset, d2)).round(); d.push(c1.x, c1.y, 'S', vertex.x, vertex.y, c2.x, c2.y, 'L'); }); d.push(targetPoint.x, targetPoint.y); return d.join(' '); }; joint.connectors.smooth = function(sourcePoint, targetPoint, vertices) { var d; if (vertices.length) { d = g.bezier.curveThroughPoints([sourcePoint].concat(vertices).concat([targetPoint])); } else { // if we have no vertices use a default cubic bezier curve, cubic bezier requires // two control points. The two control points are both defined with X as mid way // between the source and target points. SourceControlPoint Y is equal to sourcePoint Y // and targetControlPointY being equal to targetPointY. Handle situation were // sourcePointX is greater or less then targetPointX. var controlPointX = (sourcePoint.x < targetPoint.x) ? targetPoint.x - ((targetPoint.x - sourcePoint.x) / 2) : sourcePoint.x - ((sourcePoint.x - targetPoint.x) / 2); d = [ 'M', sourcePoint.x, sourcePoint.y, 'C', controlPointX, sourcePoint.y, controlPointX, targetPoint.y, targetPoint.x, targetPoint.y ]; } return d.join(' '); };
src/js/components/GrommetHero/index.js
grommet/grommet-cms-boilerplate
import React from 'react'; export default function GrommetHero() { return ( <svg className='logo grommet-hero' version="1.1" width="848" height="172" viewBox="0 0 848 172"> <g fill="none"> <path className='logo' stroke="#865CD6" strokeWidth="11" d="M185,79 C185,52.490332 206.490332,31 233,31 C259.509668,31 281,52.490332 281,79 C281,105.509668 259.509668,127 233,127 C206.490332,127 185,105.509668 185,79 Z"/> <path className='text' fill="#333333" d="M63.126,117.416 L37.842,117.416 C23.534,117.416 17.066,112.32 17.066,104.676 C17.066,97.62 22.946,92.328 33.726,91.152 C37.842,91.936 42.35,92.524 47.054,92.524 C71.162,92.524 87.038,79.784 87.038,60.38 C87.038,50.58 82.922,42.348 75.866,36.664 C77.042,26.864 84.49,21.768 96.642,21.768 L94.094,11.968 C80.766,11.968 70.77,19.612 68.81,32.352 C62.734,29.608 55.482,28.04 47.054,28.04 C22.946,28.04 7.07,40.78 7.07,60.38 C7.07,72.336 12.95,81.548 23.142,87.036 C13.342,89.78 6.482,96.64 6.482,106.244 C6.482,113.888 11.774,119.768 18.83,123.296 C8.246,126.628 1.778,134.076 1.778,144.072 C1.778,159.164 16.674,170.14 47.446,170.14 C74.886,170.14 94.682,158.38 94.682,139.956 C94.682,126.432 82.922,117.416 63.126,117.416 Z M47.054,37.448 C64.89,37.448 75.67,46.268 75.67,60.38 C75.67,74.492 64.89,83.116 47.054,83.116 C29.414,83.116 18.438,74.492 18.438,60.38 C18.438,46.268 29.414,37.448 47.054,37.448 Z M48.818,160.732 C24.71,160.732 11.97,153.676 11.97,142.308 C11.97,133.292 20.986,127.02 35.49,127.02 L60.774,127.02 C77.238,127.02 84.49,132.704 84.49,141.328 C84.49,152.108 71.162,160.732 48.818,160.732 Z M154.618,28.04 C139.134,28.04 128.158,35.684 123.062,49.012 L121.69,30 L112.282,30 L112.282,128 L123.454,128 L123.454,73.512 C123.454,52.148 137.37,38.428 151.482,38.428 C157.362,38.428 161.086,39.8 163.83,41.564 L166.574,30.98 C163.634,29.02 159.322,28.04 154.618,28.04 Z M427.214,27.844 C412.318,27.844 396.442,35.684 390.758,49.992 C385.466,35.292 371.746,28.04 356.066,28.04 C341.562,28.04 328.038,35.096 321.374,48.424 L320.786,30 L310.79,30 L310.79,128 L321.962,128 L321.962,73.316 C321.962,50.384 338.426,37.84 355.086,37.84 C370.766,37.84 381.938,46.856 381.938,65.868 L381.938,128 L393.11,128 L393.11,72.336 C393.11,51.56 408.202,37.644 426.234,37.644 C441.914,37.644 453.282,46.66 453.282,65.672 L453.282,127.804 L464.454,127.804 L464.454,64.496 C464.454,39.8 447.402,27.844 427.214,27.844 Z M612.982,27.844 C598.086,27.844 582.21,35.684 576.526,49.992 C571.234,35.292 557.514,28.04 541.834,28.04 C527.33,28.04 513.806,35.096 507.142,48.424 L506.554,30 L496.558,30 L496.558,128 L507.73,128 L507.73,73.316 C507.73,50.384 524.194,37.84 540.854,37.84 C556.534,37.84 567.706,46.856 567.706,65.868 L567.706,128 L578.878,128 L578.878,72.336 C578.878,51.56 593.97,37.644 612.002,37.644 C627.682,37.644 639.05,46.66 639.05,65.672 L639.05,127.804 L650.222,127.804 L650.222,64.496 C650.222,39.8 633.17,27.844 612.982,27.844 Z M764.45,76.06 C764.45,48.228 748.966,28.04 721.526,28.04 C692.714,28.04 676.054,47.248 676.054,79 C676.054,110.752 693.498,129.96 722.506,129.96 C742.498,129.96 755.63,121.728 762.882,107.812 L753.67,102.912 C748.966,113.888 737.598,120.16 722.506,120.16 C701.73,120.16 688.598,106.636 687.226,83.508 L764.058,83.508 C764.254,81.548 764.45,79 764.45,76.06 Z M721.526,37.84 C740.93,37.84 752.298,51.364 753.866,73.512 L687.226,73.512 C688.794,50.972 701.142,37.84 721.526,37.84 Z M842.222,112.32 C837.714,117.024 832.422,119.572 825.366,119.572 C814.782,119.572 808.706,113.496 808.706,101.736 L808.706,39.604 L845.554,39.604 L845.554,30 L808.706,30 L808.706,2.756 L797.534,5.696 L797.534,30 L777.934,30 L777.934,39.604 L797.534,39.604 L797.534,103.5 C797.534,121.924 808.314,129.96 823.406,129.96 C833.206,129.96 841.046,126.628 846.338,121.728 L842.222,112.32 Z"/> </g> </svg> ); }
docs/src/modules/components/Link.js
allanalexandre/material-ui
/* eslint-disable jsx-a11y/anchor-has-content */ import React from 'react'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import { withRouter } from 'next/router'; import NextLink from 'next/link'; import MuiLink from '@material-ui/core/Link'; import { connect } from 'react-redux'; import compose from 'docs/src/modules/utils/compose'; const NextComposed = React.forwardRef(function NextComposed(props, ref) { const { as, href, prefetch, ...other } = props; return ( <NextLink href={href} prefetch={prefetch} as={as}> <a ref={ref} {...other} /> </NextLink> ); }); NextComposed.propTypes = { as: PropTypes.string, href: PropTypes.string, prefetch: PropTypes.bool, }; // A styled version of the Next.js Link component: // https://nextjs.org/docs/#with-link function Link(props) { const { activeClassName, className: classNameProps, dispatch, innerRef, naked, router, userLanguage, ...other } = props; const className = clsx(classNameProps, { [activeClassName]: router.pathname === props.href && activeClassName, }); if (userLanguage !== 'en' && other.href.indexOf('/') === 0) { other.as = `/${userLanguage}${other.href}`; } if (naked) { return <NextComposed className={className} ref={innerRef} {...other} />; } return <MuiLink component={NextComposed} className={className} ref={innerRef} {...other} />; } Link.propTypes = { activeClassName: PropTypes.string, as: PropTypes.string, className: PropTypes.string, dispatch: PropTypes.func, href: PropTypes.string, innerRef: PropTypes.oneOfType([PropTypes.func, PropTypes.object]), naked: PropTypes.bool, onClick: PropTypes.func, prefetch: PropTypes.bool, router: PropTypes.shape({ pathname: PropTypes.string.isRequired, }).isRequired, userLanguage: PropTypes.string.isRequired, }; Link.defaultProps = { activeClassName: 'active', }; const RouterLink = compose( withRouter, connect(state => ({ userLanguage: state.options.userLanguage, })), )(Link); export default React.forwardRef((props, ref) => <RouterLink {...props} innerRef={ref} />);
src/imports/ui/builder/components/wizard/NextQuestionButton.js
hwillson/meteor-recommendation-builder
import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import { Button } from 'react-bootstrap'; class NextQuestionButton extends Component { render() { return ( <Button ref={(button) => { this.nextQuestionButton = button; }} bsStyle="link" className="next-question-button" onClick={() => { ReactDOM.findDOMNode(this.nextQuestionButton).blur(); this.props.moveToNextQuestion(); }} > Next Question <i className="fa fa-arrow-right" /> </Button> ); } } NextQuestionButton.propTypes = { moveToNextQuestion: React.PropTypes.func.isRequired, }; export default NextQuestionButton;
ajax/libs/aui/5.4.3/aui/js/aui-dependencies.js
pimterry/cdnjs
(function(t,e){function i(t){var e=fe[t]={};return G.each(t.split(ee),function(t,i){e[i]=!0}),e}function n(t,i,n){if(n===e&&1===t.nodeType){var r="data-"+i.replace(me,"-$1").toLowerCase();if(n=t.getAttribute(r),"string"==typeof n){try{n="true"===n?!0:"false"===n?!1:"null"===n?null:+n+""===n?+n:ge.test(n)?G.parseJSON(n):n}catch(a){}G.data(t,i,n)}else n=e}return n}function r(t){var e;for(e in t)if(("data"!==e||!G.isEmptyObject(t[e]))&&"toJSON"!==e)return!1;return!0}function a(){return!1}function s(){return!0}function o(t){return!t||!t.parentNode||11===t.parentNode.nodeType}function l(t,e){do t=t[e];while(t&&1!==t.nodeType);return t}function u(t,e,i){if(e=e||0,G.isFunction(e))return G.grep(t,function(t,n){var r=!!e.call(t,n,t);return r===i});if(e.nodeType)return G.grep(t,function(t){return t===e===i});if("string"==typeof e){var n=G.grep(t,function(t){return 1===t.nodeType});if(Le.test(e))return G.filter(e,n,!i);e=G.filter(e,n)}return G.grep(t,function(t){return G.inArray(t,e)>=0===i})}function c(t){var e=Oe.split("|"),i=t.createDocumentFragment();if(i.createElement)for(;e.length;)i.createElement(e.pop());return i}function h(t,e){return t.getElementsByTagName(e)[0]||t.appendChild(t.ownerDocument.createElement(e))}function d(t,e){if(1===e.nodeType&&G.hasData(t)){var i,n,r,a=G._data(t),s=G._data(e,a),o=a.events;if(o){delete s.handle,s.events={};for(i in o)for(n=0,r=o[i].length;r>n;n++)G.event.add(e,i,o[i][n])}s.data&&(s.data=G.extend({},s.data))}}function p(t,e){var i;1===e.nodeType&&(e.clearAttributes&&e.clearAttributes(),e.mergeAttributes&&e.mergeAttributes(t),i=e.nodeName.toLowerCase(),"object"===i?(e.parentNode&&(e.outerHTML=t.outerHTML),G.support.html5Clone&&t.innerHTML&&!G.trim(e.innerHTML)&&(e.innerHTML=t.innerHTML)):"input"===i&&Ve.test(t.type)?(e.defaultChecked=e.checked=t.checked,e.value!==t.value&&(e.value=t.value)):"option"===i?e.selected=t.defaultSelected:"input"===i||"textarea"===i?e.defaultValue=t.defaultValue:"script"===i&&e.text!==t.text&&(e.text=t.text),e.removeAttribute(G.expando))}function f(t){return t.getElementsByTagName!==e?t.getElementsByTagName("*"):t.querySelectorAll!==e?t.querySelectorAll("*"):[]}function g(t){Ve.test(t.type)&&(t.defaultChecked=t.checked)}function m(t,e){if(e in t)return e;for(var i=e.charAt(0).toUpperCase()+e.slice(1),n=e,r=vi.length;r--;)if(e=vi[r]+i,e in t)return e;return n}function v(t,e){return t=e||t,"none"===G.css(t,"display")||!G.contains(t.ownerDocument,t)}function y(t,e){for(var i,n,r=[],a=0,s=t.length;s>a;a++)i=t[a],i.style&&(r[a]=G._data(i,"olddisplay"),e?(r[a]||"none"!==i.style.display||(i.style.display=""),""===i.style.display&&v(i)&&(r[a]=G._data(i,"olddisplay",_(i.nodeName)))):(n=ii(i,"display"),r[a]||"none"===n||G._data(i,"olddisplay",n)));for(a=0;s>a;a++)i=t[a],i.style&&(e&&"none"!==i.style.display&&""!==i.style.display||(i.style.display=e?r[a]||"":"none"));return t}function b(t,e,i){var n=ci.exec(e);return n?Math.max(0,n[1]-(i||0))+(n[2]||"px"):e}function x(t,e,i,n){for(var r=i===(n?"border":"content")?4:"width"===e?1:0,a=0;4>r;r+=2)"margin"===i&&(a+=G.css(t,i+mi[r],!0)),n?("content"===i&&(a-=parseFloat(ii(t,"padding"+mi[r]))||0),"margin"!==i&&(a-=parseFloat(ii(t,"border"+mi[r]+"Width"))||0)):(a+=parseFloat(ii(t,"padding"+mi[r]))||0,"padding"!==i&&(a+=parseFloat(ii(t,"border"+mi[r]+"Width"))||0));return a}function w(t,e,i){var n="width"===e?t.offsetWidth:t.offsetHeight,r=!0,a=G.support.boxSizing&&"border-box"===G.css(t,"boxSizing");if(0>=n||null==n){if(n=ii(t,e),(0>n||null==n)&&(n=t.style[e]),hi.test(n))return n;r=a&&(G.support.boxSizingReliable||n===t.style[e]),n=parseFloat(n)||0}return n+x(t,e,i||(a?"border":"content"),r)+"px"}function _(t){if(pi[t])return pi[t];var e=G("<"+t+">").appendTo(H.body),i=e.css("display");return e.remove(),("none"===i||""===i)&&(ni=H.body.appendChild(ni||G.extend(H.createElement("iframe"),{frameBorder:0,width:0,height:0})),ri&&ni.createElement||(ri=(ni.contentWindow||ni.contentDocument).document,ri.write("<!doctype html><html><body>"),ri.close()),e=ri.body.appendChild(ri.createElement(t)),i=ii(e,"display"),H.body.removeChild(ni)),pi[t]=i,i}function k(t,e,i,n){var r;if(G.isArray(e))G.each(e,function(e,r){i||xi.test(t)?n(t,r):k(t+"["+("object"==typeof r?e:"")+"]",r,i,n)});else if(i||"object"!==G.type(e))n(t,e);else for(r in e)k(t+"["+r+"]",e[r],i,n)}function S(t){return function(e,i){"string"!=typeof e&&(i=e,e="*");var n,r,a,s=e.toLowerCase().split(ee),o=0,l=s.length;if(G.isFunction(i))for(;l>o;o++)n=s[o],a=/^\+/.test(n),a&&(n=n.substr(1)||"*"),r=t[n]=t[n]||[],r[a?"unshift":"push"](i)}}function A(t,i,n,r,a,s){a=a||i.dataTypes[0],s=s||{},s[a]=!0;for(var o,l=t[a],u=0,c=l?l.length:0,h=t===Li;c>u&&(h||!o);u++)o=l[u](i,n,r),"string"==typeof o&&(!h||s[o]?o=e:(i.dataTypes.unshift(o),o=A(t,i,n,r,o,s)));return!h&&o||s["*"]||(o=A(t,i,n,r,"*",s)),o}function D(t,i){var n,r,a=G.ajaxSettings.flatOptions||{};for(n in i)i[n]!==e&&((a[n]?t:r||(r={}))[n]=i[n]);r&&G.extend(!0,t,r)}function C(t,i,n){var r,a,s,o,l=t.contents,u=t.dataTypes,c=t.responseFields;for(a in c)a in n&&(i[c[a]]=n[a]);for(;"*"===u[0];)u.shift(),r===e&&(r=t.mimeType||i.getResponseHeader("content-type"));if(r)for(a in l)if(l[a]&&l[a].test(r)){u.unshift(a);break}if(u[0]in n)s=u[0];else{for(a in n){if(!u[0]||t.converters[a+" "+u[0]]){s=a;break}o||(o=a)}s=s||o}return s?(s!==u[0]&&u.unshift(s),n[s]):e}function T(t,e){var i,n,r,a,s=t.dataTypes.slice(),o=s[0],l={},u=0;if(t.dataFilter&&(e=t.dataFilter(e,t.dataType)),s[1])for(i in t.converters)l[i.toLowerCase()]=t.converters[i];for(;r=s[++u];)if("*"!==r){if("*"!==o&&o!==r){if(i=l[o+" "+r]||l["* "+r],!i)for(n in l)if(a=n.split(" "),a[1]===r&&(i=l[o+" "+a[0]]||l["* "+a[0]])){i===!0?i=l[n]:l[n]!==!0&&(r=a[0],s.splice(u--,0,r));break}if(i!==!0)if(i&&t["throws"])e=i(e);else try{e=i(e)}catch(c){return{state:"parsererror",error:i?c:"No conversion from "+o+" to "+r}}}o=r}return{state:"success",data:e}}function M(){try{return new t.XMLHttpRequest}catch(e){}}function N(){try{return new t.ActiveXObject("Microsoft.XMLHTTP")}catch(e){}}function P(){return setTimeout(function(){Ui=e},0),Ui=G.now()}function J(t,e){G.each(e,function(e,i){for(var n=(Zi[e]||[]).concat(Zi["*"]),r=0,a=n.length;a>r;r++)if(n[r].call(t,e,i))return})}function $(t,e,i){var n,r=0,a=Gi.length,s=G.Deferred().always(function(){delete o.elem}),o=function(){for(var e=Ui||P(),i=Math.max(0,l.startTime+l.duration-e),n=i/l.duration||0,r=1-n,a=0,o=l.tweens.length;o>a;a++)l.tweens[a].run(r);return s.notifyWith(t,[l,r,i]),1>r&&o?i:(s.resolveWith(t,[l]),!1)},l=s.promise({elem:t,props:G.extend({},e),opts:G.extend(!0,{specialEasing:{}},i),originalProperties:e,originalOptions:i,startTime:Ui||P(),duration:i.duration,tweens:[],createTween:function(e,i){var n=G.Tween(t,l.opts,e,i,l.opts.specialEasing[e]||l.opts.easing);return l.tweens.push(n),n},stop:function(e){for(var i=0,n=e?l.tweens.length:0;n>i;i++)l.tweens[i].run(1);return e?s.resolveWith(t,[l,e]):s.rejectWith(t,[l,e]),this}}),u=l.props;for(E(u,l.opts.specialEasing);a>r;r++)if(n=Gi[r].call(l,t,u,l.opts))return n;return J(l,u),G.isFunction(l.opts.start)&&l.opts.start.call(t,l),G.fx.timer(G.extend(o,{anim:l,queue:l.opts.queue,elem:t})),l.progress(l.opts.progress).done(l.opts.done,l.opts.complete).fail(l.opts.fail).always(l.opts.always)}function E(t,e){var i,n,r,a,s;for(i in t)if(n=G.camelCase(i),r=e[n],a=t[i],G.isArray(a)&&(r=a[1],a=t[i]=a[0]),i!==n&&(t[n]=a,delete t[i]),s=G.cssHooks[n],s&&"expand"in s){a=s.expand(a),delete t[n];for(i in a)i in t||(t[i]=a[i],e[i]=r)}else e[n]=r}function I(t,e,i){var n,r,a,s,o,l,u,c,h,d=this,p=t.style,f={},g=[],m=t.nodeType&&v(t);i.queue||(c=G._queueHooks(t,"fx"),null==c.unqueued&&(c.unqueued=0,h=c.empty.fire,c.empty.fire=function(){c.unqueued||h()}),c.unqueued++,d.always(function(){d.always(function(){c.unqueued--,G.queue(t,"fx").length||c.empty.fire()})})),1===t.nodeType&&("height"in e||"width"in e)&&(i.overflow=[p.overflow,p.overflowX,p.overflowY],"inline"===G.css(t,"display")&&"none"===G.css(t,"float")&&(G.support.inlineBlockNeedsLayout&&"inline"!==_(t.nodeName)?p.zoom=1:p.display="inline-block")),i.overflow&&(p.overflow="hidden",G.support.shrinkWrapBlocks||d.done(function(){p.overflow=i.overflow[0],p.overflowX=i.overflow[1],p.overflowY=i.overflow[2]}));for(n in e)if(a=e[n],Vi.exec(a)){if(delete e[n],l=l||"toggle"===a,a===(m?"hide":"show"))continue;g.push(n)}if(s=g.length){o=G._data(t,"fxshow")||G._data(t,"fxshow",{}),"hidden"in o&&(m=o.hidden),l&&(o.hidden=!m),m?G(t).show():d.done(function(){G(t).hide()}),d.done(function(){var e;G.removeData(t,"fxshow",!0);for(e in f)G.style(t,e,f[e])});for(n=0;s>n;n++)r=g[n],u=d.createTween(r,m?o[r]:0),f[r]=o[r]||G.style(t,r),r in o||(o[r]=u.start,m&&(u.end=u.start,u.start="width"===r||"height"===r?1:0))}}function L(t,e,i,n,r){return new L.prototype.init(t,e,i,n,r)}function j(t,e){var i,n={height:t},r=0;for(e=e?1:0;4>r;r+=2-e)i=mi[r],n["margin"+i]=n["padding"+i]=t;return e&&(n.opacity=n.width=t),n}function F(t){return G.isWindow(t)?t:9===t.nodeType?t.defaultView||t.parentWindow:!1}var O,R,H=t.document,B=t.location,z=t.navigator,Y=t.jQuery,W=t.$,q=Array.prototype.push,U=Array.prototype.slice,X=Array.prototype.indexOf,V=Object.prototype.toString,K=Object.prototype.hasOwnProperty,Q=String.prototype.trim,G=function(t,e){return new G.fn.init(t,e,O)},Z=/[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source,te=/\S/,ee=/\s+/,ie=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,ne=/^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,re=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,ae=/^[\],:{}\s]*$/,se=/(?:^|:|,)(?:\s*\[)+/g,oe=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,le=/"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,ue=/^-ms-/,ce=/-([\da-z])/gi,he=function(t,e){return(e+"").toUpperCase()},de=function(){H.addEventListener?(H.removeEventListener("DOMContentLoaded",de,!1),G.ready()):"complete"===H.readyState&&(H.detachEvent("onreadystatechange",de),G.ready())},pe={};G.fn=G.prototype={constructor:G,init:function(t,i,n){var r,a,s;if(!t)return this;if(t.nodeType)return this.context=this[0]=t,this.length=1,this;if("string"==typeof t){if(r="<"===t.charAt(0)&&">"===t.charAt(t.length-1)&&t.length>=3?[null,t,null]:ne.exec(t),!r||!r[1]&&i)return!i||i.jquery?(i||n).find(t):this.constructor(i).find(t);if(r[1])return i=i instanceof G?i[0]:i,s=i&&i.nodeType?i.ownerDocument||i:H,t=G.parseHTML(r[1],s,!0),re.test(r[1])&&G.isPlainObject(i)&&this.attr.call(t,i,!0),G.merge(this,t);if(a=H.getElementById(r[2]),a&&a.parentNode){if(a.id!==r[2])return n.find(t);this.length=1,this[0]=a}return this.context=H,this.selector=t,this}return G.isFunction(t)?n.ready(t):(t.selector!==e&&(this.selector=t.selector,this.context=t.context),G.makeArray(t,this))},selector:"",jquery:"1.8.3",length:0,size:function(){return this.length},toArray:function(){return U.call(this)},get:function(t){return null==t?this.toArray():0>t?this[this.length+t]:this[t]},pushStack:function(t,e,i){var n=G.merge(this.constructor(),t);return n.prevObject=this,n.context=this.context,"find"===e?n.selector=this.selector+(this.selector?" ":"")+i:e&&(n.selector=this.selector+"."+e+"("+i+")"),n},each:function(t,e){return G.each(this,t,e)},ready:function(t){return G.ready.promise().done(t),this},eq:function(t){return t=+t,-1===t?this.slice(t):this.slice(t,t+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(U.apply(this,arguments),"slice",U.call(arguments).join(","))},map:function(t){return this.pushStack(G.map(this,function(e,i){return t.call(e,i,e)}))},end:function(){return this.prevObject||this.constructor(null)},push:q,sort:[].sort,splice:[].splice},G.fn.init.prototype=G.fn,G.extend=G.fn.extend=function(){var t,i,n,r,a,s,o=arguments[0]||{},l=1,u=arguments.length,c=!1;for("boolean"==typeof o&&(c=o,o=arguments[1]||{},l=2),"object"==typeof o||G.isFunction(o)||(o={}),u===l&&(o=this,--l);u>l;l++)if(null!=(t=arguments[l]))for(i in t)n=o[i],r=t[i],o!==r&&(c&&r&&(G.isPlainObject(r)||(a=G.isArray(r)))?(a?(a=!1,s=n&&G.isArray(n)?n:[]):s=n&&G.isPlainObject(n)?n:{},o[i]=G.extend(c,s,r)):r!==e&&(o[i]=r));return o},G.extend({noConflict:function(e){return t.$===G&&(t.$=W),e&&t.jQuery===G&&(t.jQuery=Y),G},isReady:!1,readyWait:1,holdReady:function(t){t?G.readyWait++:G.ready(!0)},ready:function(t){if(t===!0?!--G.readyWait:!G.isReady){if(!H.body)return setTimeout(G.ready,1);G.isReady=!0,t!==!0&&--G.readyWait>0||(R.resolveWith(H,[G]),G.fn.trigger&&G(H).trigger("ready").off("ready"))}},isFunction:function(t){return"function"===G.type(t)},isArray:Array.isArray||function(t){return"array"===G.type(t)},isWindow:function(t){return null!=t&&t==t.window},isNumeric:function(t){return!isNaN(parseFloat(t))&&isFinite(t)},type:function(t){return null==t?t+"":pe[V.call(t)]||"object"},isPlainObject:function(t){if(!t||"object"!==G.type(t)||t.nodeType||G.isWindow(t))return!1;try{if(t.constructor&&!K.call(t,"constructor")&&!K.call(t.constructor.prototype,"isPrototypeOf"))return!1}catch(i){return!1}var n;for(n in t);return n===e||K.call(t,n)},isEmptyObject:function(t){var e;for(e in t)return!1;return!0},error:function(t){throw Error(t)},parseHTML:function(t,e,i){var n;return t&&"string"==typeof t?("boolean"==typeof e&&(i=e,e=0),e=e||H,(n=re.exec(t))?[e.createElement(n[1])]:(n=G.buildFragment([t],e,i?null:[]),G.merge([],(n.cacheable?G.clone(n.fragment):n.fragment).childNodes))):null},parseJSON:function(i){return i&&"string"==typeof i?(i=G.trim(i),t.JSON&&t.JSON.parse?t.JSON.parse(i):ae.test(i.replace(oe,"@").replace(le,"]").replace(se,""))?Function("return "+i)():(G.error("Invalid JSON: "+i),e)):null},parseXML:function(i){var n,r;if(!i||"string"!=typeof i)return null;try{t.DOMParser?(r=new DOMParser,n=r.parseFromString(i,"text/xml")):(n=new ActiveXObject("Microsoft.XMLDOM"),n.async="false",n.loadXML(i))}catch(a){n=e}return n&&n.documentElement&&!n.getElementsByTagName("parsererror").length||G.error("Invalid XML: "+i),n},noop:function(){},globalEval:function(e){e&&te.test(e)&&(t.execScript||function(e){t.eval.call(t,e)})(e)},camelCase:function(t){return t.replace(ue,"ms-").replace(ce,he)},nodeName:function(t,e){return t.nodeName&&t.nodeName.toLowerCase()===e.toLowerCase()},each:function(t,i,n){var r,a=0,s=t.length,o=s===e||G.isFunction(t);if(n)if(o){for(r in t)if(i.apply(t[r],n)===!1)break}else for(;s>a&&i.apply(t[a++],n)!==!1;);else if(o){for(r in t)if(i.call(t[r],r,t[r])===!1)break}else for(;s>a&&i.call(t[a],a,t[a++])!==!1;);return t},trim:Q&&!Q.call("\ufeff\u00a0")?function(t){return null==t?"":Q.call(t)}:function(t){return null==t?"":(t+"").replace(ie,"")},makeArray:function(t,e){var i,n=e||[];return null!=t&&(i=G.type(t),null==t.length||"string"===i||"function"===i||"regexp"===i||G.isWindow(t)?q.call(n,t):G.merge(n,t)),n},inArray:function(t,e,i){var n;if(e){if(X)return X.call(e,t,i);for(n=e.length,i=i?0>i?Math.max(0,n+i):i:0;n>i;i++)if(i in e&&e[i]===t)return i}return-1},merge:function(t,i){var n=i.length,r=t.length,a=0;if("number"==typeof n)for(;n>a;a++)t[r++]=i[a];else for(;i[a]!==e;)t[r++]=i[a++];return t.length=r,t},grep:function(t,e,i){var n,r=[],a=0,s=t.length;for(i=!!i;s>a;a++)n=!!e(t[a],a),i!==n&&r.push(t[a]);return r},map:function(t,i,n){var r,a,s=[],o=0,l=t.length,u=t instanceof G||l!==e&&"number"==typeof l&&(l>0&&t[0]&&t[l-1]||0===l||G.isArray(t));if(u)for(;l>o;o++)r=i(t[o],o,n),null!=r&&(s[s.length]=r);else for(a in t)r=i(t[a],a,n),null!=r&&(s[s.length]=r);return s.concat.apply([],s)},guid:1,proxy:function(t,i){var n,r,a;return"string"==typeof i&&(n=t[i],i=t,t=n),G.isFunction(t)?(r=U.call(arguments,2),a=function(){return t.apply(i,r.concat(U.call(arguments)))},a.guid=t.guid=t.guid||G.guid++,a):e},access:function(t,i,n,r,a,s,o){var l,u=null==n,c=0,h=t.length;if(n&&"object"==typeof n){for(c in n)G.access(t,i,c,n[c],1,s,r);a=1}else if(r!==e){if(l=o===e&&G.isFunction(r),u&&(l?(l=i,i=function(t,e,i){return l.call(G(t),i)}):(i.call(t,r),i=null)),i)for(;h>c;c++)i(t[c],n,l?r.call(t[c],c,i(t[c],n)):r,o);a=1}return a?t:u?i.call(t):h?i(t[0],n):s},now:function(){return(new Date).getTime()}}),G.ready.promise=function(e){if(!R)if(R=G.Deferred(),"complete"===H.readyState)setTimeout(G.ready,1);else if(H.addEventListener)H.addEventListener("DOMContentLoaded",de,!1),t.addEventListener("load",G.ready,!1);else{H.attachEvent("onreadystatechange",de),t.attachEvent("onload",G.ready);var i=!1;try{i=null==t.frameElement&&H.documentElement}catch(n){}i&&i.doScroll&&function r(){if(!G.isReady){try{i.doScroll("left")}catch(t){return setTimeout(r,50)}G.ready()}}()}return R.promise(e)},G.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(t,e){pe["[object "+e+"]"]=e.toLowerCase()}),O=G(H);var fe={};G.Callbacks=function(t){t="string"==typeof t?fe[t]||i(t):G.extend({},t);var n,r,a,s,o,l,u=[],c=!t.once&&[],h=function(e){for(n=t.memory&&e,r=!0,l=s||0,s=0,o=u.length,a=!0;u&&o>l;l++)if(u[l].apply(e[0],e[1])===!1&&t.stopOnFalse){n=!1;break}a=!1,u&&(c?c.length&&h(c.shift()):n?u=[]:d.disable())},d={add:function(){if(u){var e=u.length;(function i(e){G.each(e,function(e,n){var r=G.type(n);"function"===r?t.unique&&d.has(n)||u.push(n):n&&n.length&&"string"!==r&&i(n)})})(arguments),a?o=u.length:n&&(s=e,h(n))}return this},remove:function(){return u&&G.each(arguments,function(t,e){for(var i;(i=G.inArray(e,u,i))>-1;)u.splice(i,1),a&&(o>=i&&o--,l>=i&&l--)}),this},has:function(t){return G.inArray(t,u)>-1},empty:function(){return u=[],this},disable:function(){return u=c=n=e,this},disabled:function(){return!u},lock:function(){return c=e,n||d.disable(),this},locked:function(){return!c},fireWith:function(t,e){return e=e||[],e=[t,e.slice?e.slice():e],!u||r&&!c||(a?c.push(e):h(e)),this},fire:function(){return d.fireWith(this,arguments),this},fired:function(){return!!r}};return d},G.extend({Deferred:function(t){var e=[["resolve","done",G.Callbacks("once memory"),"resolved"],["reject","fail",G.Callbacks("once memory"),"rejected"],["notify","progress",G.Callbacks("memory")]],i="pending",n={state:function(){return i},always:function(){return r.done(arguments).fail(arguments),this},then:function(){var t=arguments;return G.Deferred(function(i){G.each(e,function(e,n){var a=n[0],s=t[e];r[n[1]](G.isFunction(s)?function(){var t=s.apply(this,arguments);t&&G.isFunction(t.promise)?t.promise().done(i.resolve).fail(i.reject).progress(i.notify):i[a+"With"](this===r?i:this,[t])}:i[a])}),t=null}).promise()},promise:function(t){return null!=t?G.extend(t,n):n}},r={};return n.pipe=n.then,G.each(e,function(t,a){var s=a[2],o=a[3];n[a[1]]=s.add,o&&s.add(function(){i=o},e[1^t][2].disable,e[2][2].lock),r[a[0]]=s.fire,r[a[0]+"With"]=s.fireWith}),n.promise(r),t&&t.call(r,r),r},when:function(t){var e,i,n,r=0,a=U.call(arguments),s=a.length,o=1!==s||t&&G.isFunction(t.promise)?s:0,l=1===o?t:G.Deferred(),u=function(t,i,n){return function(r){i[t]=this,n[t]=arguments.length>1?U.call(arguments):r,n===e?l.notifyWith(i,n):--o||l.resolveWith(i,n)}};if(s>1)for(e=Array(s),i=Array(s),n=Array(s);s>r;r++)a[r]&&G.isFunction(a[r].promise)?a[r].promise().done(u(r,n,a)).fail(l.reject).progress(u(r,i,e)):--o;return o||l.resolveWith(n,a),l.promise()}}),G.support=function(){var i,n,r,a,s,o,l,u,c,h,d,p=H.createElement("div");if(p.setAttribute("className","t"),p.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",n=p.getElementsByTagName("*"),r=p.getElementsByTagName("a")[0],!n||!r||!n.length)return{};a=H.createElement("select"),s=a.appendChild(H.createElement("option")),o=p.getElementsByTagName("input")[0],r.style.cssText="top:1px;float:left;opacity:.5",i={leadingWhitespace:3===p.firstChild.nodeType,tbody:!p.getElementsByTagName("tbody").length,htmlSerialize:!!p.getElementsByTagName("link").length,style:/top/.test(r.getAttribute("style")),hrefNormalized:"/a"===r.getAttribute("href"),opacity:/^0.5/.test(r.style.opacity),cssFloat:!!r.style.cssFloat,checkOn:"on"===o.value,optSelected:s.selected,getSetAttribute:"t"!==p.className,enctype:!!H.createElement("form").enctype,html5Clone:"<:nav></:nav>"!==H.createElement("nav").cloneNode(!0).outerHTML,boxModel:"CSS1Compat"===H.compatMode,submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},o.checked=!0,i.noCloneChecked=o.cloneNode(!0).checked,a.disabled=!0,i.optDisabled=!s.disabled;try{delete p.test}catch(f){i.deleteExpando=!1}if(!p.addEventListener&&p.attachEvent&&p.fireEvent&&(p.attachEvent("onclick",d=function(){i.noCloneEvent=!1}),p.cloneNode(!0).fireEvent("onclick"),p.detachEvent("onclick",d)),o=H.createElement("input"),o.value="t",o.setAttribute("type","radio"),i.radioValue="t"===o.value,o.setAttribute("checked","checked"),o.setAttribute("name","t"),p.appendChild(o),l=H.createDocumentFragment(),l.appendChild(p.lastChild),i.checkClone=l.cloneNode(!0).cloneNode(!0).lastChild.checked,i.appendChecked=o.checked,l.removeChild(o),l.appendChild(p),p.attachEvent)for(c in{submit:!0,change:!0,focusin:!0})u="on"+c,h=u in p,h||(p.setAttribute(u,"return;"),h="function"==typeof p[u]),i[c+"Bubbles"]=h;return G(function(){var n,r,a,s,o="padding:0;margin:0;border:0;display:block;overflow:hidden;",l=H.getElementsByTagName("body")[0];l&&(n=H.createElement("div"),n.style.cssText="visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px",l.insertBefore(n,l.firstChild),r=H.createElement("div"),n.appendChild(r),r.innerHTML="<table><tr><td></td><td>t</td></tr></table>",a=r.getElementsByTagName("td"),a[0].style.cssText="padding:0;margin:0;border:0;display:none",h=0===a[0].offsetHeight,a[0].style.display="",a[1].style.display="none",i.reliableHiddenOffsets=h&&0===a[0].offsetHeight,r.innerHTML="",r.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",i.boxSizing=4===r.offsetWidth,i.doesNotIncludeMarginInBodyOffset=1!==l.offsetTop,t.getComputedStyle&&(i.pixelPosition="1%"!==(t.getComputedStyle(r,null)||{}).top,i.boxSizingReliable="4px"===(t.getComputedStyle(r,null)||{width:"4px"}).width,s=H.createElement("div"),s.style.cssText=r.style.cssText=o,s.style.marginRight=s.style.width="0",r.style.width="1px",r.appendChild(s),i.reliableMarginRight=!parseFloat((t.getComputedStyle(s,null)||{}).marginRight)),r.style.zoom!==e&&(r.innerHTML="",r.style.cssText=o+"width:1px;padding:1px;display:inline;zoom:1",i.inlineBlockNeedsLayout=3===r.offsetWidth,r.style.display="block",r.style.overflow="visible",r.innerHTML="<div></div>",r.firstChild.style.width="5px",i.shrinkWrapBlocks=3!==r.offsetWidth,n.style.zoom=1),l.removeChild(n),n=r=a=s=null)}),l.removeChild(p),n=r=a=s=o=l=p=null,i}();var ge=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,me=/([A-Z])/g;G.extend({cache:{},deletedIds:[],uuid:0,expando:"jQuery"+(G.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(t){return t=t.nodeType?G.cache[t[G.expando]]:t[G.expando],!!t&&!r(t)},data:function(t,i,n,r){if(G.acceptData(t)){var a,s,o=G.expando,l="string"==typeof i,u=t.nodeType,c=u?G.cache:t,h=u?t[o]:t[o]&&o;if(h&&c[h]&&(r||c[h].data)||!l||n!==e)return h||(u?t[o]=h=G.deletedIds.pop()||G.guid++:h=o),c[h]||(c[h]={},u||(c[h].toJSON=G.noop)),("object"==typeof i||"function"==typeof i)&&(r?c[h]=G.extend(c[h],i):c[h].data=G.extend(c[h].data,i)),a=c[h],r||(a.data||(a.data={}),a=a.data),n!==e&&(a[G.camelCase(i)]=n),l?(s=a[i],null==s&&(s=a[G.camelCase(i)])):s=a,s}},removeData:function(t,e,i){if(G.acceptData(t)){var n,a,s,o=t.nodeType,l=o?G.cache:t,u=o?t[G.expando]:G.expando;if(l[u]){if(e&&(n=i?l[u]:l[u].data)){G.isArray(e)||(e in n?e=[e]:(e=G.camelCase(e),e=e in n?[e]:e.split(" ")));for(a=0,s=e.length;s>a;a++)delete n[e[a]];if(!(i?r:G.isEmptyObject)(n))return}(i||(delete l[u].data,r(l[u])))&&(o?G.cleanData([t],!0):G.support.deleteExpando||l!=l.window?delete l[u]:l[u]=null)}}},_data:function(t,e,i){return G.data(t,e,i,!0)},acceptData:function(t){var e=t.nodeName&&G.noData[t.nodeName.toLowerCase()];return!e||e!==!0&&t.getAttribute("classid")===e}}),G.fn.extend({data:function(t,i){var r,a,s,o,l,u=this[0],c=0,h=null;if(t===e){if(this.length&&(h=G.data(u),1===u.nodeType&&!G._data(u,"parsedAttrs"))){for(s=u.attributes,l=s.length;l>c;c++)o=s[c].name,o.indexOf("data-")||(o=G.camelCase(o.substring(5)),n(u,o,h[o]));G._data(u,"parsedAttrs",!0)}return h}return"object"==typeof t?this.each(function(){G.data(this,t)}):(r=t.split(".",2),r[1]=r[1]?"."+r[1]:"",a=r[1]+"!",G.access(this,function(i){return i===e?(h=this.triggerHandler("getData"+a,[r[0]]),h===e&&u&&(h=G.data(u,t),h=n(u,t,h)),h===e&&r[1]?this.data(r[0]):h):(r[1]=i,this.each(function(){var e=G(this);e.triggerHandler("setData"+a,r),G.data(this,t,i),e.triggerHandler("changeData"+a,r)}),e)},null,i,arguments.length>1,null,!1))},removeData:function(t){return this.each(function(){G.removeData(this,t)})}}),G.extend({queue:function(t,i,n){var r;return t?(i=(i||"fx")+"queue",r=G._data(t,i),n&&(!r||G.isArray(n)?r=G._data(t,i,G.makeArray(n)):r.push(n)),r||[]):e},dequeue:function(t,e){e=e||"fx";var i=G.queue(t,e),n=i.length,r=i.shift(),a=G._queueHooks(t,e),s=function(){G.dequeue(t,e)};"inprogress"===r&&(r=i.shift(),n--),r&&("fx"===e&&i.unshift("inprogress"),delete a.stop,r.call(t,s,a)),!n&&a&&a.empty.fire()},_queueHooks:function(t,e){var i=e+"queueHooks";return G._data(t,i)||G._data(t,i,{empty:G.Callbacks("once memory").add(function(){G.removeData(t,e+"queue",!0),G.removeData(t,i,!0)})})}}),G.fn.extend({queue:function(t,i){var n=2;return"string"!=typeof t&&(i=t,t="fx",n--),n>arguments.length?G.queue(this[0],t):i===e?this:this.each(function(){var e=G.queue(this,t,i);G._queueHooks(this,t),"fx"===t&&"inprogress"!==e[0]&&G.dequeue(this,t)})},dequeue:function(t){return this.each(function(){G.dequeue(this,t)})},delay:function(t,e){return t=G.fx?G.fx.speeds[t]||t:t,e=e||"fx",this.queue(e,function(e,i){var n=setTimeout(e,t);i.stop=function(){clearTimeout(n)}})},clearQueue:function(t){return this.queue(t||"fx",[])},promise:function(t,i){var n,r=1,a=G.Deferred(),s=this,o=this.length,l=function(){--r||a.resolveWith(s,[s])};for("string"!=typeof t&&(i=t,t=e),t=t||"fx";o--;)n=G._data(s[o],t+"queueHooks"),n&&n.empty&&(r++,n.empty.add(l));return l(),a.promise(i)}});var ve,ye,be,xe=/[\t\r\n]/g,we=/\r/g,_e=/^(?:button|input)$/i,ke=/^(?:button|input|object|select|textarea)$/i,Se=/^a(?:rea|)$/i,Ae=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,De=G.support.getSetAttribute;G.fn.extend({attr:function(t,e){return G.access(this,G.attr,t,e,arguments.length>1)},removeAttr:function(t){return this.each(function(){G.removeAttr(this,t)})},prop:function(t,e){return G.access(this,G.prop,t,e,arguments.length>1)},removeProp:function(t){return t=G.propFix[t]||t,this.each(function(){try{this[t]=e,delete this[t]}catch(i){}})},addClass:function(t){var e,i,n,r,a,s,o;if(G.isFunction(t))return this.each(function(e){G(this).addClass(t.call(this,e,this.className))});if(t&&"string"==typeof t)for(e=t.split(ee),i=0,n=this.length;n>i;i++)if(r=this[i],1===r.nodeType)if(r.className||1!==e.length){for(a=" "+r.className+" ",s=0,o=e.length;o>s;s++)0>a.indexOf(" "+e[s]+" ")&&(a+=e[s]+" ");r.className=G.trim(a)}else r.className=t;return this},removeClass:function(t){var i,n,r,a,s,o,l;if(G.isFunction(t))return this.each(function(e){G(this).removeClass(t.call(this,e,this.className))});if(t&&"string"==typeof t||t===e)for(i=(t||"").split(ee),o=0,l=this.length;l>o;o++)if(r=this[o],1===r.nodeType&&r.className){for(n=(" "+r.className+" ").replace(xe," "),a=0,s=i.length;s>a;a++)for(;n.indexOf(" "+i[a]+" ")>=0;)n=n.replace(" "+i[a]+" "," ");r.className=t?G.trim(n):""}return this},toggleClass:function(t,e){var i=typeof t,n="boolean"==typeof e;return G.isFunction(t)?this.each(function(i){G(this).toggleClass(t.call(this,i,this.className,e),e)}):this.each(function(){if("string"===i)for(var r,a=0,s=G(this),o=e,l=t.split(ee);r=l[a++];)o=n?o:!s.hasClass(r),s[o?"addClass":"removeClass"](r);else("undefined"===i||"boolean"===i)&&(this.className&&G._data(this,"__className__",this.className),this.className=this.className||t===!1?"":G._data(this,"__className__")||"")})},hasClass:function(t){for(var e=" "+t+" ",i=0,n=this.length;n>i;i++)if(1===this[i].nodeType&&(" "+this[i].className+" ").replace(xe," ").indexOf(e)>=0)return!0;return!1},val:function(t){var i,n,r,a=this[0];{if(arguments.length)return r=G.isFunction(t),this.each(function(n){var a,s=G(this);1===this.nodeType&&(a=r?t.call(this,n,s.val()):t,null==a?a="":"number"==typeof a?a+="":G.isArray(a)&&(a=G.map(a,function(t){return null==t?"":t+""})),i=G.valHooks[this.type]||G.valHooks[this.nodeName.toLowerCase()],i&&"set"in i&&i.set(this,a,"value")!==e||(this.value=a))});if(a)return i=G.valHooks[a.type]||G.valHooks[a.nodeName.toLowerCase()],i&&"get"in i&&(n=i.get(a,"value"))!==e?n:(n=a.value,"string"==typeof n?n.replace(we,""):null==n?"":n)}}}),G.extend({valHooks:{option:{get:function(t){var e=t.attributes.value;return!e||e.specified?t.value:t.text}},select:{get:function(t){for(var e,i,n=t.options,r=t.selectedIndex,a="select-one"===t.type||0>r,s=a?null:[],o=a?r+1:n.length,l=0>r?o:a?r:0;o>l;l++)if(i=n[l],!(!i.selected&&l!==r||(G.support.optDisabled?i.disabled:null!==i.getAttribute("disabled"))||i.parentNode.disabled&&G.nodeName(i.parentNode,"optgroup"))){if(e=G(i).val(),a)return e;s.push(e)}return s},set:function(t,e){var i=G.makeArray(e);return G(t).find("option").each(function(){this.selected=G.inArray(G(this).val(),i)>=0}),i.length||(t.selectedIndex=-1),i}}},attrFn:{},attr:function(t,i,n,r){var a,s,o,l=t.nodeType;if(t&&3!==l&&8!==l&&2!==l)return r&&G.isFunction(G.fn[i])?G(t)[i](n):t.getAttribute===e?G.prop(t,i,n):(o=1!==l||!G.isXMLDoc(t),o&&(i=i.toLowerCase(),s=G.attrHooks[i]||(Ae.test(i)?ye:ve)),n!==e?null===n?(G.removeAttr(t,i),e):s&&"set"in s&&o&&(a=s.set(t,n,i))!==e?a:(t.setAttribute(i,n+""),n):s&&"get"in s&&o&&null!==(a=s.get(t,i))?a:(a=t.getAttribute(i),null===a?e:a))},removeAttr:function(t,e){var i,n,r,a,s=0;if(e&&1===t.nodeType)for(n=e.split(ee);n.length>s;s++)r=n[s],r&&(i=G.propFix[r]||r,a=Ae.test(r),a||G.attr(t,r,""),t.removeAttribute(De?r:i),a&&i in t&&(t[i]=!1))},attrHooks:{type:{set:function(t,e){if(_e.test(t.nodeName)&&t.parentNode)G.error("type property can't be changed");else if(!G.support.radioValue&&"radio"===e&&G.nodeName(t,"input")){var i=t.value;return t.setAttribute("type",e),i&&(t.value=i),e}}},value:{get:function(t,e){return ve&&G.nodeName(t,"button")?ve.get(t,e):e in t?t.value:null},set:function(t,i,n){return ve&&G.nodeName(t,"button")?ve.set(t,i,n):(t.value=i,e)}}},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(t,i,n){var r,a,s,o=t.nodeType;if(t&&3!==o&&8!==o&&2!==o)return s=1!==o||!G.isXMLDoc(t),s&&(i=G.propFix[i]||i,a=G.propHooks[i]),n!==e?a&&"set"in a&&(r=a.set(t,n,i))!==e?r:t[i]=n:a&&"get"in a&&null!==(r=a.get(t,i))?r:t[i]},propHooks:{tabIndex:{get:function(t){var i=t.getAttributeNode("tabindex");return i&&i.specified?parseInt(i.value,10):ke.test(t.nodeName)||Se.test(t.nodeName)&&t.href?0:e}}}}),ye={get:function(t,i){var n,r=G.prop(t,i);return r===!0||"boolean"!=typeof r&&(n=t.getAttributeNode(i))&&n.nodeValue!==!1?i.toLowerCase():e},set:function(t,e,i){var n;return e===!1?G.removeAttr(t,i):(n=G.propFix[i]||i,n in t&&(t[n]=!0),t.setAttribute(i,i.toLowerCase())),i}},De||(be={name:!0,id:!0,coords:!0},ve=G.valHooks.button={get:function(t,i){var n;return n=t.getAttributeNode(i),n&&(be[i]?""!==n.value:n.specified)?n.value:e},set:function(t,e,i){var n=t.getAttributeNode(i);return n||(n=H.createAttribute(i),t.setAttributeNode(n)),n.value=e+""}},G.each(["width","height"],function(t,i){G.attrHooks[i]=G.extend(G.attrHooks[i],{set:function(t,n){return""===n?(t.setAttribute(i,"auto"),n):e}})}),G.attrHooks.contenteditable={get:ve.get,set:function(t,e,i){""===e&&(e="false"),ve.set(t,e,i) }}),G.support.hrefNormalized||G.each(["href","src","width","height"],function(t,i){G.attrHooks[i]=G.extend(G.attrHooks[i],{get:function(t){var n=t.getAttribute(i,2);return null===n?e:n}})}),G.support.style||(G.attrHooks.style={get:function(t){return t.style.cssText.toLowerCase()||e},set:function(t,e){return t.style.cssText=e+""}}),G.support.optSelected||(G.propHooks.selected=G.extend(G.propHooks.selected,{get:function(t){var e=t.parentNode;return e&&(e.selectedIndex,e.parentNode&&e.parentNode.selectedIndex),null}})),G.support.enctype||(G.propFix.enctype="encoding"),G.support.checkOn||G.each(["radio","checkbox"],function(){G.valHooks[this]={get:function(t){return null===t.getAttribute("value")?"on":t.value}}}),G.each(["radio","checkbox"],function(){G.valHooks[this]=G.extend(G.valHooks[this],{set:function(t,i){return G.isArray(i)?t.checked=G.inArray(G(t).val(),i)>=0:e}})});var Ce=/^(?:textarea|input|select)$/i,Te=/^([^\.]*|)(?:\.(.+)|)$/,Me=/(?:^|\s)hover(\.\S+|)\b/,Ne=/^key/,Pe=/^(?:mouse|contextmenu)|click/,Je=/^(?:focusinfocus|focusoutblur)$/,$e=function(t){return G.event.special.hover?t:t.replace(Me,"mouseenter$1 mouseleave$1")};G.event={add:function(t,i,n,r,a){var s,o,l,u,c,h,d,p,f,g,m;if(3!==t.nodeType&&8!==t.nodeType&&i&&n&&(s=G._data(t))){for(n.handler&&(f=n,n=f.handler,a=f.selector),n.guid||(n.guid=G.guid++),l=s.events,l||(s.events=l={}),o=s.handle,o||(s.handle=o=function(t){return G===e||t&&G.event.triggered===t.type?e:G.event.dispatch.apply(o.elem,arguments)},o.elem=t),i=G.trim($e(i)).split(" "),u=0;i.length>u;u++)c=Te.exec(i[u])||[],h=c[1],d=(c[2]||"").split(".").sort(),m=G.event.special[h]||{},h=(a?m.delegateType:m.bindType)||h,m=G.event.special[h]||{},p=G.extend({type:h,origType:c[1],data:r,handler:n,guid:n.guid,selector:a,needsContext:a&&G.expr.match.needsContext.test(a),namespace:d.join(".")},f),g=l[h],g||(g=l[h]=[],g.delegateCount=0,m.setup&&m.setup.call(t,r,d,o)!==!1||(t.addEventListener?t.addEventListener(h,o,!1):t.attachEvent&&t.attachEvent("on"+h,o))),m.add&&(m.add.call(t,p),p.handler.guid||(p.handler.guid=n.guid)),a?g.splice(g.delegateCount++,0,p):g.push(p),G.event.global[h]=!0;t=null}},global:{},remove:function(t,e,i,n,r){var a,s,o,l,u,c,h,d,p,f,g,m=G.hasData(t)&&G._data(t);if(m&&(d=m.events)){for(e=G.trim($e(e||"")).split(" "),a=0;e.length>a;a++)if(s=Te.exec(e[a])||[],o=l=s[1],u=s[2],o){for(p=G.event.special[o]||{},o=(n?p.delegateType:p.bindType)||o,f=d[o]||[],c=f.length,u=u?RegExp("(^|\\.)"+u.split(".").sort().join("\\.(?:.*\\.|)")+"(\\.|$)"):null,h=0;f.length>h;h++)g=f[h],!r&&l!==g.origType||i&&i.guid!==g.guid||u&&!u.test(g.namespace)||n&&n!==g.selector&&("**"!==n||!g.selector)||(f.splice(h--,1),g.selector&&f.delegateCount--,p.remove&&p.remove.call(t,g));0===f.length&&c!==f.length&&(p.teardown&&p.teardown.call(t,u,m.handle)!==!1||G.removeEvent(t,o,m.handle),delete d[o])}else for(o in d)G.event.remove(t,o+e[a],i,n,!0);G.isEmptyObject(d)&&(delete m.handle,G.removeData(t,"events",!0))}},customEvent:{getData:!0,setData:!0,changeData:!0},trigger:function(i,n,r,a){if(!r||3!==r.nodeType&&8!==r.nodeType){var s,o,l,u,c,h,d,p,f,g,m=i.type||i,v=[];if(!Je.test(m+G.event.triggered)&&(m.indexOf("!")>=0&&(m=m.slice(0,-1),o=!0),m.indexOf(".")>=0&&(v=m.split("."),m=v.shift(),v.sort()),r&&!G.event.customEvent[m]||G.event.global[m]))if(i="object"==typeof i?i[G.expando]?i:new G.Event(m,i):new G.Event(m),i.type=m,i.isTrigger=!0,i.exclusive=o,i.namespace=v.join("."),i.namespace_re=i.namespace?RegExp("(^|\\.)"+v.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,h=0>m.indexOf(":")?"on"+m:"",r){if(i.result=e,i.target||(i.target=r),n=null!=n?G.makeArray(n):[],n.unshift(i),d=G.event.special[m]||{},!d.trigger||d.trigger.apply(r,n)!==!1){if(f=[[r,d.bindType||m]],!a&&!d.noBubble&&!G.isWindow(r)){for(g=d.delegateType||m,u=Je.test(g+m)?r:r.parentNode,c=r;u;u=u.parentNode)f.push([u,g]),c=u;c===(r.ownerDocument||H)&&f.push([c.defaultView||c.parentWindow||t,g])}for(l=0;f.length>l&&!i.isPropagationStopped();l++)u=f[l][0],i.type=f[l][1],p=(G._data(u,"events")||{})[i.type]&&G._data(u,"handle"),p&&p.apply(u,n),p=h&&u[h],p&&G.acceptData(u)&&p.apply&&p.apply(u,n)===!1&&i.preventDefault();return i.type=m,a||i.isDefaultPrevented()||d._default&&d._default.apply(r.ownerDocument,n)!==!1||"click"===m&&G.nodeName(r,"a")||!G.acceptData(r)||h&&r[m]&&("focus"!==m&&"blur"!==m||0!==i.target.offsetWidth)&&!G.isWindow(r)&&(c=r[h],c&&(r[h]=null),G.event.triggered=m,r[m](),G.event.triggered=e,c&&(r[h]=c)),i.result}}else{s=G.cache;for(l in s)s[l].events&&s[l].events[m]&&G.event.trigger(i,n,s[l].handle.elem,!0)}}},dispatch:function(i){i=G.event.fix(i||t.event);var n,r,a,s,o,l,u,c,h,d=(G._data(this,"events")||{})[i.type]||[],p=d.delegateCount,f=U.call(arguments),g=!i.exclusive&&!i.namespace,m=G.event.special[i.type]||{},v=[];if(f[0]=i,i.delegateTarget=this,!m.preDispatch||m.preDispatch.call(this,i)!==!1){if(p&&(!i.button||"click"!==i.type))for(a=i.target;a!=this;a=a.parentNode||this)if(a.disabled!==!0||"click"!==i.type){for(o={},u=[],n=0;p>n;n++)c=d[n],h=c.selector,o[h]===e&&(o[h]=c.needsContext?G(h,this).index(a)>=0:G.find(h,this,null,[a]).length),o[h]&&u.push(c);u.length&&v.push({elem:a,matches:u})}for(d.length>p&&v.push({elem:this,matches:d.slice(p)}),n=0;v.length>n&&!i.isPropagationStopped();n++)for(l=v[n],i.currentTarget=l.elem,r=0;l.matches.length>r&&!i.isImmediatePropagationStopped();r++)c=l.matches[r],(g||!i.namespace&&!c.namespace||i.namespace_re&&i.namespace_re.test(c.namespace))&&(i.data=c.data,i.handleObj=c,s=((G.event.special[c.origType]||{}).handle||c.handler).apply(l.elem,f),s!==e&&(i.result=s,s===!1&&(i.preventDefault(),i.stopPropagation())));return m.postDispatch&&m.postDispatch.call(this,i),i.result}},props:"attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(t,e){return null==t.which&&(t.which=null!=e.charCode?e.charCode:e.keyCode),t}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(t,i){var n,r,a,s=i.button,o=i.fromElement;return null==t.pageX&&null!=i.clientX&&(n=t.target.ownerDocument||H,r=n.documentElement,a=n.body,t.pageX=i.clientX+(r&&r.scrollLeft||a&&a.scrollLeft||0)-(r&&r.clientLeft||a&&a.clientLeft||0),t.pageY=i.clientY+(r&&r.scrollTop||a&&a.scrollTop||0)-(r&&r.clientTop||a&&a.clientTop||0)),!t.relatedTarget&&o&&(t.relatedTarget=o===t.target?i.toElement:o),t.which||s===e||(t.which=1&s?1:2&s?3:4&s?2:0),t}},fix:function(t){if(t[G.expando])return t;var e,i,n=t,r=G.event.fixHooks[t.type]||{},a=r.props?this.props.concat(r.props):this.props;for(t=G.Event(n),e=a.length;e;)i=a[--e],t[i]=n[i];return t.target||(t.target=n.srcElement||H),3===t.target.nodeType&&(t.target=t.target.parentNode),t.metaKey=!!t.metaKey,r.filter?r.filter(t,n):t},special:{load:{noBubble:!0},focus:{delegateType:"focusin"},blur:{delegateType:"focusout"},beforeunload:{setup:function(t,e,i){G.isWindow(this)&&(this.onbeforeunload=i)},teardown:function(t,e){this.onbeforeunload===e&&(this.onbeforeunload=null)}}},simulate:function(t,e,i,n){var r=G.extend(new G.Event,i,{type:t,isSimulated:!0,originalEvent:{}});n?G.event.trigger(r,null,e):G.event.dispatch.call(e,r),r.isDefaultPrevented()&&i.preventDefault()}},G.event.handle=G.event.dispatch,G.removeEvent=H.removeEventListener?function(t,e,i){t.removeEventListener&&t.removeEventListener(e,i,!1)}:function(t,i,n){var r="on"+i;t.detachEvent&&(t[r]===e&&(t[r]=null),t.detachEvent(r,n))},G.Event=function(t,i){return this instanceof G.Event?(t&&t.type?(this.originalEvent=t,this.type=t.type,this.isDefaultPrevented=t.defaultPrevented||t.returnValue===!1||t.getPreventDefault&&t.getPreventDefault()?s:a):this.type=t,i&&G.extend(this,i),this.timeStamp=t&&t.timeStamp||G.now(),this[G.expando]=!0,e):new G.Event(t,i)},G.Event.prototype={preventDefault:function(){this.isDefaultPrevented=s;var t=this.originalEvent;t&&(t.preventDefault?t.preventDefault():t.returnValue=!1)},stopPropagation:function(){this.isPropagationStopped=s;var t=this.originalEvent;t&&(t.stopPropagation&&t.stopPropagation(),t.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=s,this.stopPropagation()},isDefaultPrevented:a,isPropagationStopped:a,isImmediatePropagationStopped:a},G.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(t,e){G.event.special[t]={delegateType:e,bindType:e,handle:function(t){var i,n=this,r=t.relatedTarget,a=t.handleObj;return a.selector,(!r||r!==n&&!G.contains(n,r))&&(t.type=a.origType,i=a.handler.apply(this,arguments),t.type=e),i}}}),G.support.submitBubbles||(G.event.special.submit={setup:function(){return G.nodeName(this,"form")?!1:(G.event.add(this,"click._submit keypress._submit",function(t){var i=t.target,n=G.nodeName(i,"input")||G.nodeName(i,"button")?i.form:e;n&&!G._data(n,"_submit_attached")&&(G.event.add(n,"submit._submit",function(t){t._submit_bubble=!0}),G._data(n,"_submit_attached",!0))}),e)},postDispatch:function(t){t._submit_bubble&&(delete t._submit_bubble,this.parentNode&&!t.isTrigger&&G.event.simulate("submit",this.parentNode,t,!0))},teardown:function(){return G.nodeName(this,"form")?!1:(G.event.remove(this,"._submit"),e)}}),G.support.changeBubbles||(G.event.special.change={setup:function(){return Ce.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(G.event.add(this,"propertychange._change",function(t){"checked"===t.originalEvent.propertyName&&(this._just_changed=!0)}),G.event.add(this,"click._change",function(t){this._just_changed&&!t.isTrigger&&(this._just_changed=!1),G.event.simulate("change",this,t,!0)})),!1):(G.event.add(this,"beforeactivate._change",function(t){var e=t.target;Ce.test(e.nodeName)&&!G._data(e,"_change_attached")&&(G.event.add(e,"change._change",function(t){!this.parentNode||t.isSimulated||t.isTrigger||G.event.simulate("change",this.parentNode,t,!0)}),G._data(e,"_change_attached",!0))}),e)},handle:function(t){var i=t.target;return this!==i||t.isSimulated||t.isTrigger||"radio"!==i.type&&"checkbox"!==i.type?t.handleObj.handler.apply(this,arguments):e},teardown:function(){return G.event.remove(this,"._change"),!Ce.test(this.nodeName)}}),G.support.focusinBubbles||G.each({focus:"focusin",blur:"focusout"},function(t,e){var i=0,n=function(t){G.event.simulate(e,t.target,G.event.fix(t),!0)};G.event.special[e]={setup:function(){0===i++&&H.addEventListener(t,n,!0)},teardown:function(){0===--i&&H.removeEventListener(t,n,!0)}}}),G.fn.extend({on:function(t,i,n,r,s){var o,l;if("object"==typeof t){"string"!=typeof i&&(n=n||i,i=e);for(l in t)this.on(l,i,n,t[l],s);return this}if(null==n&&null==r?(r=i,n=i=e):null==r&&("string"==typeof i?(r=n,n=e):(r=n,n=i,i=e)),r===!1)r=a;else if(!r)return this;return 1===s&&(o=r,r=function(t){return G().off(t),o.apply(this,arguments)},r.guid=o.guid||(o.guid=G.guid++)),this.each(function(){G.event.add(this,t,r,n,i)})},one:function(t,e,i,n){return this.on(t,e,i,n,1)},off:function(t,i,n){var r,s;if(t&&t.preventDefault&&t.handleObj)return r=t.handleObj,G(t.delegateTarget).off(r.namespace?r.origType+"."+r.namespace:r.origType,r.selector,r.handler),this;if("object"==typeof t){for(s in t)this.off(s,i,t[s]);return this}return(i===!1||"function"==typeof i)&&(n=i,i=e),n===!1&&(n=a),this.each(function(){G.event.remove(this,t,n,i)})},bind:function(t,e,i){return this.on(t,null,e,i)},unbind:function(t,e){return this.off(t,null,e)},live:function(t,e,i){return G(this.context).on(t,this.selector,e,i),this},die:function(t,e){return G(this.context).off(t,this.selector||"**",e),this},delegate:function(t,e,i,n){return this.on(e,t,i,n)},undelegate:function(t,e,i){return 1===arguments.length?this.off(t,"**"):this.off(e,t||"**",i)},trigger:function(t,e){return this.each(function(){G.event.trigger(t,e,this)})},triggerHandler:function(t,i){return this[0]?G.event.trigger(t,i,this[0],!0):e},toggle:function(t){var e=arguments,i=t.guid||G.guid++,n=0,r=function(i){var r=(G._data(this,"lastToggle"+t.guid)||0)%n;return G._data(this,"lastToggle"+t.guid,r+1),i.preventDefault(),e[r].apply(this,arguments)||!1};for(r.guid=i;e.length>n;)e[n++].guid=i;return this.click(r)},hover:function(t,e){return this.mouseenter(t).mouseleave(e||t)}}),G.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(t,e){G.fn[e]=function(t,i){return null==i&&(i=t,t=null),arguments.length>0?this.on(e,null,t,i):this.trigger(e)},Ne.test(e)&&(G.event.fixHooks[e]=G.event.keyHooks),Pe.test(e)&&(G.event.fixHooks[e]=G.event.mouseHooks)}),function(t,e){function i(t,e,i,n){i=i||[],e=e||P;var r,a,s,o,l=e.nodeType;if(!t||"string"!=typeof t)return i;if(1!==l&&9!==l)return[];if(s=w(e),!s&&!n&&(r=ie.exec(t)))if(o=r[1]){if(9===l){if(a=e.getElementById(o),!a||!a.parentNode)return i;if(a.id===o)return i.push(a),i}else if(e.ownerDocument&&(a=e.ownerDocument.getElementById(o))&&_(e,a)&&a.id===o)return i.push(a),i}else{if(r[2])return L.apply(i,j.call(e.getElementsByTagName(t),0)),i;if((o=r[3])&&de&&e.getElementsByClassName)return L.apply(i,j.call(e.getElementsByClassName(o),0)),i}return g(t.replace(Q,"$1"),e,i,n,s)}function n(t){return function(e){var i=e.nodeName.toLowerCase();return"input"===i&&e.type===t}}function r(t){return function(e){var i=e.nodeName.toLowerCase();return("input"===i||"button"===i)&&e.type===t}}function a(t){return O(function(e){return e=+e,O(function(i,n){for(var r,a=t([],i.length,e),s=a.length;s--;)i[r=a[s]]&&(i[r]=!(n[r]=i[r]))})})}function s(t,e,i){if(t===e)return i;for(var n=t.nextSibling;n;){if(n===e)return-1;n=n.nextSibling}return 1}function o(t,e){var n,r,a,s,o,l,u,c=B[M][t+" "];if(c)return e?0:c.slice(0);for(o=t,l=[],u=b.preFilter;o;){(!n||(r=Z.exec(o)))&&(r&&(o=o.slice(r[0].length)||o),l.push(a=[])),n=!1,(r=te.exec(o))&&(a.push(n=new N(r.shift())),o=o.slice(n.length),n.type=r[0].replace(Q," "));for(s in b.filter)!(r=oe[s].exec(o))||u[s]&&!(r=u[s](r))||(a.push(n=new N(r.shift())),o=o.slice(n.length),n.type=s,n.matches=r);if(!n)break}return e?o.length:o?i.error(t):B(t,l).slice(0)}function l(t,e,i){var n=e.dir,r=i&&"parentNode"===e.dir,a=E++;return e.first?function(e,i,a){for(;e=e[n];)if(r||1===e.nodeType)return t(e,i,a)}:function(e,i,s){if(s){for(;e=e[n];)if((r||1===e.nodeType)&&t(e,i,s))return e}else for(var o,l=$+" "+a+" ",u=l+v;e=e[n];)if(r||1===e.nodeType){if((o=e[M])===u)return e.sizset;if("string"==typeof o&&0===o.indexOf(l)){if(e.sizset)return e}else{if(e[M]=u,t(e,i,s))return e.sizset=!0,e;e.sizset=!1}}}}function u(t){return t.length>1?function(e,i,n){for(var r=t.length;r--;)if(!t[r](e,i,n))return!1;return!0}:t[0]}function c(t,e,i,n,r){for(var a,s=[],o=0,l=t.length,u=null!=e;l>o;o++)(a=t[o])&&(!i||i(a,n,r))&&(s.push(a),u&&e.push(o));return s}function h(t,e,i,n,r,a){return n&&!n[M]&&(n=h(n)),r&&!r[M]&&(r=h(r,a)),O(function(a,s,o,l){var u,h,d,p=[],g=[],m=s.length,v=a||f(e||"*",o.nodeType?[o]:o,[]),y=!t||!a&&e?v:c(v,p,t,o,l),b=i?r||(a?t:m||n)?[]:s:y;if(i&&i(y,b,o,l),n)for(u=c(b,g),n(u,[],o,l),h=u.length;h--;)(d=u[h])&&(b[g[h]]=!(y[g[h]]=d));if(a){if(r||t){if(r){for(u=[],h=b.length;h--;)(d=b[h])&&u.push(y[h]=d);r(null,b=[],u,l)}for(h=b.length;h--;)(d=b[h])&&(u=r?F.call(a,d):p[h])>-1&&(a[u]=!(s[u]=d))}}else b=c(b===s?b.splice(m,b.length):b),r?r(null,s,b,l):L.apply(s,b)})}function d(t){for(var e,i,n,r=t.length,a=b.relative[t[0].type],s=a||b.relative[" "],o=a?1:0,c=l(function(t){return t===e},s,!0),p=l(function(t){return F.call(e,t)>-1},s,!0),f=[function(t,i,n){return!a&&(n||i!==D)||((e=i).nodeType?c(t,i,n):p(t,i,n))}];r>o;o++)if(i=b.relative[t[o].type])f=[l(u(f),i)];else{if(i=b.filter[t[o].type].apply(null,t[o].matches),i[M]){for(n=++o;r>n&&!b.relative[t[n].type];n++);return h(o>1&&u(f),o>1&&t.slice(0,o-1).join("").replace(Q,"$1"),i,n>o&&d(t.slice(o,n)),r>n&&d(t=t.slice(n)),r>n&&t.join(""))}f.push(i)}return u(f)}function p(t,e){var n=e.length>0,r=t.length>0,a=function(s,o,l,u,h){var d,p,f,g=[],m=0,y="0",x=s&&[],w=null!=h,_=D,k=s||r&&b.find.TAG("*",h&&o.parentNode||o),S=$+=null==_?1:Math.E;for(w&&(D=o!==P&&o,v=a.el);null!=(d=k[y]);y++){if(r&&d){for(p=0;f=t[p];p++)if(f(d,o,l)){u.push(d);break}w&&($=S,v=++a.el)}n&&((d=!f&&d)&&m--,s&&x.push(d))}if(m+=y,n&&y!==m){for(p=0;f=e[p];p++)f(x,g,o,l);if(s){if(m>0)for(;y--;)x[y]||g[y]||(g[y]=I.call(u));g=c(g)}L.apply(u,g),w&&!s&&g.length>0&&m+e.length>1&&i.uniqueSort(u)}return w&&($=S,D=_),x};return a.el=0,n?O(a):a}function f(t,e,n){for(var r=0,a=e.length;a>r;r++)i(t,e[r],n);return n}function g(t,e,i,n,r){var a,s,l,u,c,h=o(t);if(h.length,!n&&1===h.length){if(s=h[0]=h[0].slice(0),s.length>2&&"ID"===(l=s[0]).type&&9===e.nodeType&&!r&&b.relative[s[1].type]){if(e=b.find.ID(l.matches[0].replace(se,""),e,r)[0],!e)return i;t=t.slice(s.shift().length)}for(a=oe.POS.test(t)?-1:s.length-1;a>=0&&(l=s[a],!b.relative[u=l.type]);a--)if((c=b.find[u])&&(n=c(l.matches[0].replace(se,""),ne.test(s[0].type)&&e.parentNode||e,r))){if(s.splice(a,1),t=n.length&&s.join(""),!t)return L.apply(i,j.call(n,0)),i;break}}return k(t,h)(n,e,r,i,ne.test(t)),i}function m(){}var v,y,b,x,w,_,k,S,A,D,C=!0,T="undefined",M=("sizcache"+Math.random()).replace(".",""),N=String,P=t.document,J=P.documentElement,$=0,E=0,I=[].pop,L=[].push,j=[].slice,F=[].indexOf||function(t){for(var e=0,i=this.length;i>e;e++)if(this[e]===t)return e;return-1},O=function(t,e){return t[M]=null==e||e,t},R=function(){var t={},e=[];return O(function(i,n){return e.push(i)>b.cacheLength&&delete t[e.shift()],t[i+" "]=n},t)},H=R(),B=R(),z=R(),Y="[\\x20\\t\\r\\n\\f]",W="(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",q=W.replace("w","w#"),U="([*^$|!~]?=)",X="\\["+Y+"*("+W+")"+Y+"*(?:"+U+Y+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+q+")|)|)"+Y+"*\\]",V=":("+W+")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:"+X+")|[^:]|\\\\.)*|.*))\\)|)",K=":(even|odd|eq|gt|lt|nth|first|last)(?:\\("+Y+"*((?:-\\d)?\\d*)"+Y+"*\\)|)(?=[^-]|$)",Q=RegExp("^"+Y+"+|((?:^|[^\\\\])(?:\\\\.)*)"+Y+"+$","g"),Z=RegExp("^"+Y+"*,"+Y+"*"),te=RegExp("^"+Y+"*([\\x20\\t\\r\\n\\f>+~])"+Y+"*"),ee=RegExp(V),ie=/^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,ne=/[\x20\t\r\n\f]*[+~]/,re=/h\d/i,ae=/input|select|textarea|button/i,se=/\\(?!\\)/g,oe={ID:RegExp("^#("+W+")"),CLASS:RegExp("^\\.("+W+")"),NAME:RegExp("^\\[name=['\"]?("+W+")['\"]?\\]"),TAG:RegExp("^("+W.replace("w","w*")+")"),ATTR:RegExp("^"+X),PSEUDO:RegExp("^"+V),POS:RegExp(K,"i"),CHILD:RegExp("^:(only|nth|first|last)-child(?:\\("+Y+"*(even|odd|(([+-]|)(\\d*)n|)"+Y+"*(?:([+-]|)"+Y+"*(\\d+)|))"+Y+"*\\)|)","i"),needsContext:RegExp("^"+Y+"*[>+~]|"+K,"i")},le=function(t){var e=P.createElement("div");try{return t(e)}catch(i){return!1}finally{e=null}},ue=le(function(t){return t.appendChild(P.createComment("")),!t.getElementsByTagName("*").length}),ce=le(function(t){return t.innerHTML="<a href='#'></a>",t.firstChild&&typeof t.firstChild.getAttribute!==T&&"#"===t.firstChild.getAttribute("href")}),he=le(function(t){t.innerHTML="<select></select>";var e=typeof t.lastChild.getAttribute("multiple");return"boolean"!==e&&"string"!==e}),de=le(function(t){return t.innerHTML="<div class='hidden e'></div><div class='hidden'></div>",t.getElementsByClassName&&t.getElementsByClassName("e").length?(t.lastChild.className="e",2===t.getElementsByClassName("e").length):!1}),pe=le(function(t){t.id=M+0,t.innerHTML="<a name='"+M+"'></a><div name='"+M+"'></div>",J.insertBefore(t,J.firstChild);var e=P.getElementsByName&&P.getElementsByName(M).length===2+P.getElementsByName(M+0).length;return y=!P.getElementById(M),J.removeChild(t),e});try{j.call(J.childNodes,0)[0].nodeType}catch(fe){j=function(t){for(var e,i=[];e=this[t];t++)i.push(e);return i}}i.matches=function(t,e){return i(t,null,null,e)},i.matchesSelector=function(t,e){return i(e,null,null,[t]).length>0},x=i.getText=function(t){var e,i="",n=0,r=t.nodeType;if(r){if(1===r||9===r||11===r){if("string"==typeof t.textContent)return t.textContent;for(t=t.firstChild;t;t=t.nextSibling)i+=x(t)}else if(3===r||4===r)return t.nodeValue}else for(;e=t[n];n++)i+=x(e);return i},w=i.isXML=function(t){var e=t&&(t.ownerDocument||t).documentElement;return e?"HTML"!==e.nodeName:!1},_=i.contains=J.contains?function(t,e){var i=9===t.nodeType?t.documentElement:t,n=e&&e.parentNode;return t===n||!!(n&&1===n.nodeType&&i.contains&&i.contains(n))}:J.compareDocumentPosition?function(t,e){return e&&!!(16&t.compareDocumentPosition(e))}:function(t,e){for(;e=e.parentNode;)if(e===t)return!0;return!1},i.attr=function(t,e){var i,n=w(t);return n||(e=e.toLowerCase()),(i=b.attrHandle[e])?i(t):n||he?t.getAttribute(e):(i=t.getAttributeNode(e),i?"boolean"==typeof t[e]?t[e]?e:null:i.specified?i.value:null:null)},b=i.selectors={cacheLength:50,createPseudo:O,match:oe,attrHandle:ce?{}:{href:function(t){return t.getAttribute("href",2)},type:function(t){return t.getAttribute("type")}},find:{ID:y?function(t,e,i){if(typeof e.getElementById!==T&&!i){var n=e.getElementById(t);return n&&n.parentNode?[n]:[]}}:function(t,i,n){if(typeof i.getElementById!==T&&!n){var r=i.getElementById(t);return r?r.id===t||typeof r.getAttributeNode!==T&&r.getAttributeNode("id").value===t?[r]:e:[]}},TAG:ue?function(t,i){return typeof i.getElementsByTagName!==T?i.getElementsByTagName(t):e}:function(t,e){var i=e.getElementsByTagName(t);if("*"===t){for(var n,r=[],a=0;n=i[a];a++)1===n.nodeType&&r.push(n);return r}return i},NAME:pe&&function(t,i){return typeof i.getElementsByName!==T?i.getElementsByName(name):e},CLASS:de&&function(t,i,n){return typeof i.getElementsByClassName===T||n?e:i.getElementsByClassName(t)}},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(t){return t[1]=t[1].replace(se,""),t[3]=(t[4]||t[5]||"").replace(se,""),"~="===t[2]&&(t[3]=" "+t[3]+" "),t.slice(0,4)},CHILD:function(t){return t[1]=t[1].toLowerCase(),"nth"===t[1]?(t[2]||i.error(t[0]),t[3]=+(t[3]?t[4]+(t[5]||1):2*("even"===t[2]||"odd"===t[2])),t[4]=+(t[6]+t[7]||"odd"===t[2])):t[2]&&i.error(t[0]),t},PSEUDO:function(t){var e,i;return oe.CHILD.test(t[0])?null:(t[3]?t[2]=t[3]:(e=t[4])&&(ee.test(e)&&(i=o(e,!0))&&(i=e.indexOf(")",e.length-i)-e.length)&&(e=e.slice(0,i),t[0]=t[0].slice(0,i)),t[2]=e),t.slice(0,3))}},filter:{ID:y?function(t){return t=t.replace(se,""),function(e){return e.getAttribute("id")===t}}:function(t){return t=t.replace(se,""),function(e){var i=typeof e.getAttributeNode!==T&&e.getAttributeNode("id");return i&&i.value===t}},TAG:function(t){return"*"===t?function(){return!0}:(t=t.replace(se,"").toLowerCase(),function(e){return e.nodeName&&e.nodeName.toLowerCase()===t})},CLASS:function(t){var e=H[M][t+" "];return e||(e=RegExp("(^|"+Y+")"+t+"("+Y+"|$)"))&&H(t,function(t){return e.test(t.className||typeof t.getAttribute!==T&&t.getAttribute("class")||"")})},ATTR:function(t,e,n){return function(r){var a=i.attr(r,t);return null==a?"!="===e:e?(a+="","="===e?a===n:"!="===e?a!==n:"^="===e?n&&0===a.indexOf(n):"*="===e?n&&a.indexOf(n)>-1:"$="===e?n&&a.substr(a.length-n.length)===n:"~="===e?(" "+a+" ").indexOf(n)>-1:"|="===e?a===n||a.substr(0,n.length+1)===n+"-":!1):!0}},CHILD:function(t,e,i,n){return"nth"===t?function(t){var e,r,a=t.parentNode;if(1===i&&0===n)return!0;if(a)for(r=0,e=a.firstChild;e&&(1!==e.nodeType||(r++,t!==e));e=e.nextSibling);return r-=n,r===i||0===r%i&&r/i>=0}:function(e){var i=e;switch(t){case"only":case"first":for(;i=i.previousSibling;)if(1===i.nodeType)return!1;if("first"===t)return!0;i=e;case"last":for(;i=i.nextSibling;)if(1===i.nodeType)return!1;return!0}}},PSEUDO:function(t,e){var n,r=b.pseudos[t]||b.setFilters[t.toLowerCase()]||i.error("unsupported pseudo: "+t);return r[M]?r(e):r.length>1?(n=[t,t,"",e],b.setFilters.hasOwnProperty(t.toLowerCase())?O(function(t,i){for(var n,a=r(t,e),s=a.length;s--;)n=F.call(t,a[s]),t[n]=!(i[n]=a[s])}):function(t){return r(t,0,n)}):r}},pseudos:{not:O(function(t){var e=[],i=[],n=k(t.replace(Q,"$1"));return n[M]?O(function(t,e,i,r){for(var a,s=n(t,null,r,[]),o=t.length;o--;)(a=s[o])&&(t[o]=!(e[o]=a))}):function(t,r,a){return e[0]=t,n(e,null,a,i),!i.pop()}}),has:O(function(t){return function(e){return i(t,e).length>0}}),contains:O(function(t){return function(e){return(e.textContent||e.innerText||x(e)).indexOf(t)>-1}}),enabled:function(t){return t.disabled===!1},disabled:function(t){return t.disabled===!0},checked:function(t){var e=t.nodeName.toLowerCase();return"input"===e&&!!t.checked||"option"===e&&!!t.selected},selected:function(t){return t.parentNode&&t.parentNode.selectedIndex,t.selected===!0},parent:function(t){return!b.pseudos.empty(t)},empty:function(t){var e;for(t=t.firstChild;t;){if(t.nodeName>"@"||3===(e=t.nodeType)||4===e)return!1;t=t.nextSibling}return!0},header:function(t){return re.test(t.nodeName)},text:function(t){var e,i;return"input"===t.nodeName.toLowerCase()&&"text"===(e=t.type)&&(null==(i=t.getAttribute("type"))||i.toLowerCase()===e)},radio:n("radio"),checkbox:n("checkbox"),file:n("file"),password:n("password"),image:n("image"),submit:r("submit"),reset:r("reset"),button:function(t){var e=t.nodeName.toLowerCase();return"input"===e&&"button"===t.type||"button"===e},input:function(t){return ae.test(t.nodeName)},focus:function(t){var e=t.ownerDocument;return t===e.activeElement&&(!e.hasFocus||e.hasFocus())&&!!(t.type||t.href||~t.tabIndex)},active:function(t){return t===t.ownerDocument.activeElement},first:a(function(){return[0]}),last:a(function(t,e){return[e-1]}),eq:a(function(t,e,i){return[0>i?i+e:i]}),even:a(function(t,e){for(var i=0;e>i;i+=2)t.push(i);return t}),odd:a(function(t,e){for(var i=1;e>i;i+=2)t.push(i);return t}),lt:a(function(t,e,i){for(var n=0>i?i+e:i;--n>=0;)t.push(n);return t}),gt:a(function(t,e,i){for(var n=0>i?i+e:i;e>++n;)t.push(n);return t})}},S=J.compareDocumentPosition?function(t,e){return t===e?(A=!0,0):(t.compareDocumentPosition&&e.compareDocumentPosition?4&t.compareDocumentPosition(e):t.compareDocumentPosition)?-1:1}:function(t,e){if(t===e)return A=!0,0;if(t.sourceIndex&&e.sourceIndex)return t.sourceIndex-e.sourceIndex;var i,n,r=[],a=[],o=t.parentNode,l=e.parentNode,u=o;if(o===l)return s(t,e);if(!o)return-1;if(!l)return 1;for(;u;)r.unshift(u),u=u.parentNode;for(u=l;u;)a.unshift(u),u=u.parentNode;i=r.length,n=a.length;for(var c=0;i>c&&n>c;c++)if(r[c]!==a[c])return s(r[c],a[c]);return c===i?s(t,a[c],-1):s(r[c],e,1)},[0,0].sort(S),C=!A,i.uniqueSort=function(t){var e,i=[],n=1,r=0;if(A=C,t.sort(S),A){for(;e=t[n];n++)e===t[n-1]&&(r=i.push(n));for(;r--;)t.splice(i[r],1)}return t},i.error=function(t){throw Error("Syntax error, unrecognized expression: "+t)},k=i.compile=function(t,e){var i,n=[],r=[],a=z[M][t+" "];if(!a){for(e||(e=o(t)),i=e.length;i--;)a=d(e[i]),a[M]?n.push(a):r.push(a);a=z(t,p(r,n))}return a},P.querySelectorAll&&function(){var t,e=g,n=/'|\\/g,r=/\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,a=[":focus"],s=[":active"],l=J.matchesSelector||J.mozMatchesSelector||J.webkitMatchesSelector||J.oMatchesSelector||J.msMatchesSelector;le(function(t){t.innerHTML="<select><option selected=''></option></select>",t.querySelectorAll("[selected]").length||a.push("\\["+Y+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),t.querySelectorAll(":checked").length||a.push(":checked")}),le(function(t){t.innerHTML="<p test=''></p>",t.querySelectorAll("[test^='']").length&&a.push("[*^$]="+Y+"*(?:\"\"|'')"),t.innerHTML="<input type='hidden'/>",t.querySelectorAll(":enabled").length||a.push(":enabled",":disabled")}),a=RegExp(a.join("|")),g=function(t,i,r,s,l){if(!s&&!l&&!a.test(t)){var u,c,h=!0,d=M,p=i,f=9===i.nodeType&&t;if(1===i.nodeType&&"object"!==i.nodeName.toLowerCase()){for(u=o(t),(h=i.getAttribute("id"))?d=h.replace(n,"\\$&"):i.setAttribute("id",d),d="[id='"+d+"'] ",c=u.length;c--;)u[c]=d+u[c].join("");p=ne.test(t)&&i.parentNode||i,f=u.join(",")}if(f)try{return L.apply(r,j.call(p.querySelectorAll(f),0)),r}catch(g){}finally{h||i.removeAttribute("id")}}return e(t,i,r,s,l)},l&&(le(function(e){t=l.call(e,"div");try{l.call(e,"[test!='']:sizzle"),s.push("!=",V)}catch(i){}}),s=RegExp(s.join("|")),i.matchesSelector=function(e,n){if(n=n.replace(r,"='$1']"),!w(e)&&!s.test(n)&&!a.test(n))try{var o=l.call(e,n);if(o||t||e.document&&11!==e.document.nodeType)return o}catch(u){}return i(n,null,null,[e]).length>0})}(),b.pseudos.nth=b.pseudos.eq,b.filters=m.prototype=b.pseudos,b.setFilters=new m,i.attr=G.attr,G.find=i,G.expr=i.selectors,G.expr[":"]=G.expr.pseudos,G.unique=i.uniqueSort,G.text=i.getText,G.isXMLDoc=i.isXML,G.contains=i.contains}(t);var Ee=/Until$/,Ie=/^(?:parents|prev(?:Until|All))/,Le=/^.[^:#\[\.,]*$/,je=G.expr.match.needsContext,Fe={children:!0,contents:!0,next:!0,prev:!0};G.fn.extend({find:function(t){var e,i,n,r,a,s,o=this;if("string"!=typeof t)return G(t).filter(function(){for(e=0,i=o.length;i>e;e++)if(G.contains(o[e],this))return!0});for(s=this.pushStack("","find",t),e=0,i=this.length;i>e;e++)if(n=s.length,G.find(t,this[e],s),e>0)for(r=n;s.length>r;r++)for(a=0;n>a;a++)if(s[a]===s[r]){s.splice(r--,1);break}return s},has:function(t){var e,i=G(t,this),n=i.length;return this.filter(function(){for(e=0;n>e;e++)if(G.contains(this,i[e]))return!0})},not:function(t){return this.pushStack(u(this,t,!1),"not",t)},filter:function(t){return this.pushStack(u(this,t,!0),"filter",t)},is:function(t){return!!t&&("string"==typeof t?je.test(t)?G(t,this.context).index(this[0])>=0:G.filter(t,this).length>0:this.filter(t).length>0)},closest:function(t,e){for(var i,n=0,r=this.length,a=[],s=je.test(t)||"string"!=typeof t?G(t,e||this.context):0;r>n;n++)for(i=this[n];i&&i.ownerDocument&&i!==e&&11!==i.nodeType;){if(s?s.index(i)>-1:G.find.matchesSelector(i,t)){a.push(i);break}i=i.parentNode}return a=a.length>1?G.unique(a):a,this.pushStack(a,"closest",t)},index:function(t){return t?"string"==typeof t?G.inArray(this[0],G(t)):G.inArray(t.jquery?t[0]:t,this):this[0]&&this[0].parentNode?this.prevAll().length:-1},add:function(t,e){var i="string"==typeof t?G(t,e):G.makeArray(t&&t.nodeType?[t]:t),n=G.merge(this.get(),i);return this.pushStack(o(i[0])||o(n[0])?n:G.unique(n))},addBack:function(t){return this.add(null==t?this.prevObject:this.prevObject.filter(t))}}),G.fn.andSelf=G.fn.addBack,G.each({parent:function(t){var e=t.parentNode;return e&&11!==e.nodeType?e:null},parents:function(t){return G.dir(t,"parentNode")},parentsUntil:function(t,e,i){return G.dir(t,"parentNode",i)},next:function(t){return l(t,"nextSibling")},prev:function(t){return l(t,"previousSibling")},nextAll:function(t){return G.dir(t,"nextSibling")},prevAll:function(t){return G.dir(t,"previousSibling")},nextUntil:function(t,e,i){return G.dir(t,"nextSibling",i)},prevUntil:function(t,e,i){return G.dir(t,"previousSibling",i)},siblings:function(t){return G.sibling((t.parentNode||{}).firstChild,t)},children:function(t){return G.sibling(t.firstChild)},contents:function(t){return G.nodeName(t,"iframe")?t.contentDocument||t.contentWindow.document:G.merge([],t.childNodes)}},function(t,e){G.fn[t]=function(i,n){var r=G.map(this,e,i);return Ee.test(t)||(n=i),n&&"string"==typeof n&&(r=G.filter(n,r)),r=this.length>1&&!Fe[t]?G.unique(r):r,this.length>1&&Ie.test(t)&&(r=r.reverse()),this.pushStack(r,t,U.call(arguments).join(","))}}),G.extend({filter:function(t,e,i){return i&&(t=":not("+t+")"),1===e.length?G.find.matchesSelector(e[0],t)?[e[0]]:[]:G.find.matches(t,e)},dir:function(t,i,n){for(var r=[],a=t[i];a&&9!==a.nodeType&&(n===e||1!==a.nodeType||!G(a).is(n));)1===a.nodeType&&r.push(a),a=a[i];return r},sibling:function(t,e){for(var i=[];t;t=t.nextSibling)1===t.nodeType&&t!==e&&i.push(t);return i}});var Oe="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",Re=/ jQuery\d+="(?:null|\d+)"/g,He=/^\s+/,Be=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,ze=/<([\w:]+)/,Ye=/<tbody/i,We=/<|&#?\w+;/,qe=/<(?:script|style|link)/i,Ue=/<(?:script|object|embed|option|style)/i,Xe=RegExp("<(?:"+Oe+")[\\s/>]","i"),Ve=/^(?:checkbox|radio)$/,Ke=/checked\s*(?:[^=]|=\s*.checked.)/i,Qe=/\/(java|ecma)script/i,Ge=/^\s*<!(?:\[CDATA\[|\-\-)|[\]\-]{2}>\s*$/g,Ze={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,"",""]},ti=c(H),ei=ti.appendChild(H.createElement("div")); Ze.optgroup=Ze.option,Ze.tbody=Ze.tfoot=Ze.colgroup=Ze.caption=Ze.thead,Ze.th=Ze.td,G.support.htmlSerialize||(Ze._default=[1,"X<div>","</div>"]),G.fn.extend({text:function(t){return G.access(this,function(t){return t===e?G.text(this):this.empty().append((this[0]&&this[0].ownerDocument||H).createTextNode(t))},null,t,arguments.length)},wrapAll:function(t){if(G.isFunction(t))return this.each(function(e){G(this).wrapAll(t.call(this,e))});if(this[0]){var e=G(t,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&e.insertBefore(this[0]),e.map(function(){for(var t=this;t.firstChild&&1===t.firstChild.nodeType;)t=t.firstChild;return t}).append(this)}return this},wrapInner:function(t){return G.isFunction(t)?this.each(function(e){G(this).wrapInner(t.call(this,e))}):this.each(function(){var e=G(this),i=e.contents();i.length?i.wrapAll(t):e.append(t)})},wrap:function(t){var e=G.isFunction(t);return this.each(function(i){G(this).wrapAll(e?t.call(this,i):t)})},unwrap:function(){return this.parent().each(function(){G.nodeName(this,"body")||G(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(t){(1===this.nodeType||11===this.nodeType)&&this.appendChild(t)})},prepend:function(){return this.domManip(arguments,!0,function(t){(1===this.nodeType||11===this.nodeType)&&this.insertBefore(t,this.firstChild)})},before:function(){if(!o(this[0]))return this.domManip(arguments,!1,function(t){this.parentNode.insertBefore(t,this)});if(arguments.length){var t=G.clean(arguments);return this.pushStack(G.merge(t,this),"before",this.selector)}},after:function(){if(!o(this[0]))return this.domManip(arguments,!1,function(t){this.parentNode.insertBefore(t,this.nextSibling)});if(arguments.length){var t=G.clean(arguments);return this.pushStack(G.merge(this,t),"after",this.selector)}},remove:function(t,e){for(var i,n=0;null!=(i=this[n]);n++)(!t||G.filter(t,[i]).length)&&(e||1!==i.nodeType||(G.cleanData(i.getElementsByTagName("*")),G.cleanData([i])),i.parentNode&&i.parentNode.removeChild(i));return this},empty:function(){for(var t,e=0;null!=(t=this[e]);e++)for(1===t.nodeType&&G.cleanData(t.getElementsByTagName("*"));t.firstChild;)t.removeChild(t.firstChild);return this},clone:function(t,e){return t=null==t?!1:t,e=null==e?t:e,this.map(function(){return G.clone(this,t,e)})},html:function(t){return G.access(this,function(t){var i=this[0]||{},n=0,r=this.length;if(t===e)return 1===i.nodeType?i.innerHTML.replace(Re,""):e;if(!("string"!=typeof t||qe.test(t)||!G.support.htmlSerialize&&Xe.test(t)||!G.support.leadingWhitespace&&He.test(t)||Ze[(ze.exec(t)||["",""])[1].toLowerCase()])){t=t.replace(Be,"<$1></$2>");try{for(;r>n;n++)i=this[n]||{},1===i.nodeType&&(G.cleanData(i.getElementsByTagName("*")),i.innerHTML=t);i=0}catch(a){}}i&&this.empty().append(t)},null,t,arguments.length)},replaceWith:function(t){return o(this[0])?this.length?this.pushStack(G(G.isFunction(t)?t():t),"replaceWith",t):this:G.isFunction(t)?this.each(function(e){var i=G(this),n=i.html();i.replaceWith(t.call(this,e,n))}):("string"!=typeof t&&(t=G(t).detach()),this.each(function(){var e=this.nextSibling,i=this.parentNode;G(this).remove(),e?G(e).before(t):G(i).append(t)}))},detach:function(t){return this.remove(t,!0)},domManip:function(t,i,n){t=[].concat.apply([],t);var r,a,s,o,l=0,u=t[0],c=[],d=this.length;if(!G.support.checkClone&&d>1&&"string"==typeof u&&Ke.test(u))return this.each(function(){G(this).domManip(t,i,n)});if(G.isFunction(u))return this.each(function(r){var a=G(this);t[0]=u.call(this,r,i?a.html():e),a.domManip(t,i,n)});if(this[0]){if(r=G.buildFragment(t,this,c),s=r.fragment,a=s.firstChild,1===s.childNodes.length&&(s=a),a)for(i=i&&G.nodeName(a,"tr"),o=r.cacheable||d-1;d>l;l++)n.call(i&&G.nodeName(this[l],"table")?h(this[l],"tbody"):this[l],l===o?s:G.clone(s,!0,!0));s=a=null,c.length&&G.each(c,function(t,e){e.src?G.ajax?G.ajax({url:e.src,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0}):G.error("no ajax"):G.globalEval((e.text||e.textContent||e.innerHTML||"").replace(Ge,"")),e.parentNode&&e.parentNode.removeChild(e)})}return this}}),G.buildFragment=function(t,i,n){var r,a,s,o=t[0];return i=i||H,i=!i.nodeType&&i[0]||i,i=i.ownerDocument||i,!(1===t.length&&"string"==typeof o&&512>o.length&&i===H&&"<"===o.charAt(0))||Ue.test(o)||!G.support.checkClone&&Ke.test(o)||!G.support.html5Clone&&Xe.test(o)||(a=!0,r=G.fragments[o],s=r!==e),r||(r=i.createDocumentFragment(),G.clean(t,i,r,n),a&&(G.fragments[o]=s&&r)),{fragment:r,cacheable:a}},G.fragments={},G.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(t,e){G.fn[t]=function(i){var n,r=0,a=[],s=G(i),o=s.length,l=1===this.length&&this[0].parentNode;if((null==l||l&&11===l.nodeType&&1===l.childNodes.length)&&1===o)return s[e](this[0]),this;for(;o>r;r++)n=(r>0?this.clone(!0):this).get(),G(s[r])[e](n),a=a.concat(n);return this.pushStack(a,t,s.selector)}}),G.extend({clone:function(t,e,i){var n,r,a,s;if(G.support.html5Clone||G.isXMLDoc(t)||!Xe.test("<"+t.nodeName+">")?s=t.cloneNode(!0):(ei.innerHTML=t.outerHTML,ei.removeChild(s=ei.firstChild)),!(G.support.noCloneEvent&&G.support.noCloneChecked||1!==t.nodeType&&11!==t.nodeType||G.isXMLDoc(t)))for(p(t,s),n=f(t),r=f(s),a=0;n[a];++a)r[a]&&p(n[a],r[a]);if(e&&(d(t,s),i))for(n=f(t),r=f(s),a=0;n[a];++a)d(n[a],r[a]);return n=r=null,s},clean:function(t,i,n,r){var a,s,o,l,u,h,d,p,f,m,v,y=i===H&&ti,b=[];for(i&&i.createDocumentFragment!==e||(i=H),a=0;null!=(o=t[a]);a++)if("number"==typeof o&&(o+=""),o){if("string"==typeof o)if(We.test(o)){for(y=y||c(i),d=i.createElement("div"),y.appendChild(d),o=o.replace(Be,"<$1></$2>"),l=(ze.exec(o)||["",""])[1].toLowerCase(),u=Ze[l]||Ze._default,h=u[0],d.innerHTML=u[1]+o+u[2];h--;)d=d.lastChild;if(!G.support.tbody)for(p=Ye.test(o),f="table"!==l||p?"<table>"!==u[1]||p?[]:d.childNodes:d.firstChild&&d.firstChild.childNodes,s=f.length-1;s>=0;--s)G.nodeName(f[s],"tbody")&&!f[s].childNodes.length&&f[s].parentNode.removeChild(f[s]);!G.support.leadingWhitespace&&He.test(o)&&d.insertBefore(i.createTextNode(He.exec(o)[0]),d.firstChild),o=d.childNodes,d.parentNode.removeChild(d)}else o=i.createTextNode(o);o.nodeType?b.push(o):G.merge(b,o)}if(d&&(o=d=y=null),!G.support.appendChecked)for(a=0;null!=(o=b[a]);a++)G.nodeName(o,"input")?g(o):o.getElementsByTagName!==e&&G.grep(o.getElementsByTagName("input"),g);if(n)for(m=function(t){return!t.type||Qe.test(t.type)?r?r.push(t.parentNode?t.parentNode.removeChild(t):t):n.appendChild(t):e},a=0;null!=(o=b[a]);a++)G.nodeName(o,"script")&&m(o)||(n.appendChild(o),o.getElementsByTagName!==e&&(v=G.grep(G.merge([],o.getElementsByTagName("script")),m),b.splice.apply(b,[a+1,0].concat(v)),a+=v.length));return b},cleanData:function(t,e){for(var i,n,r,a,s=0,o=G.expando,l=G.cache,u=G.support.deleteExpando,c=G.event.special;null!=(r=t[s]);s++)if((e||G.acceptData(r))&&(n=r[o],i=n&&l[n])){if(i.events)for(a in i.events)c[a]?G.event.remove(r,a):G.removeEvent(r,a,i.handle);l[n]&&(delete l[n],u?delete r[o]:r.removeAttribute?r.removeAttribute(o):r[o]=null,G.deletedIds.push(n))}}}),function(){var t,e;G.uaMatch=function(t){t=t.toLowerCase();var e=/(chrome)[ \/]([\w.]+)/.exec(t)||/(webkit)[ \/]([\w.]+)/.exec(t)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(t)||/(msie) ([\w.]+)/.exec(t)||0>t.indexOf("compatible")&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(t)||[];return{browser:e[1]||"",version:e[2]||"0"}},t=G.uaMatch(z.userAgent),e={},t.browser&&(e[t.browser]=!0,e.version=t.version),e.chrome?e.webkit=!0:e.webkit&&(e.safari=!0),G.browser=e,G.sub=function(){function t(e,i){return new t.fn.init(e,i)}G.extend(!0,t,this),t.superclass=this,t.fn=t.prototype=this(),t.fn.constructor=t,t.sub=this.sub,t.fn.init=function(i,n){return n&&n instanceof G&&!(n instanceof t)&&(n=t(n)),G.fn.init.call(this,i,n,e)},t.fn.init.prototype=t.fn;var e=t(H);return t}}();var ii,ni,ri,ai=/alpha\([^)]*\)/i,si=/opacity=([^)]*)/,oi=/^(top|right|bottom|left)$/,li=/^(none|table(?!-c[ea]).+)/,ui=/^margin/,ci=RegExp("^("+Z+")(.*)$","i"),hi=RegExp("^("+Z+")(?!px)[a-z%]+$","i"),di=RegExp("^([-+])=("+Z+")","i"),pi={BODY:"block"},fi={position:"absolute",visibility:"hidden",display:"block"},gi={letterSpacing:0,fontWeight:400},mi=["Top","Right","Bottom","Left"],vi=["Webkit","O","Moz","ms"],yi=G.fn.toggle;G.fn.extend({css:function(t,i){return G.access(this,function(t,i,n){return n!==e?G.style(t,i,n):G.css(t,i)},t,i,arguments.length>1)},show:function(){return y(this,!0)},hide:function(){return y(this)},toggle:function(t,e){var i="boolean"==typeof t;return G.isFunction(t)&&G.isFunction(e)?yi.apply(this,arguments):this.each(function(){(i?t:v(this))?G(this).show():G(this).hide()})}}),G.extend({cssHooks:{opacity:{get:function(t,e){if(e){var i=ii(t,"opacity");return""===i?"1":i}}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":G.support.cssFloat?"cssFloat":"styleFloat"},style:function(t,i,n,r){if(t&&3!==t.nodeType&&8!==t.nodeType&&t.style){var a,s,o,l=G.camelCase(i),u=t.style;if(i=G.cssProps[l]||(G.cssProps[l]=m(u,l)),o=G.cssHooks[i]||G.cssHooks[l],n===e)return o&&"get"in o&&(a=o.get(t,!1,r))!==e?a:u[i];if(s=typeof n,"string"===s&&(a=di.exec(n))&&(n=(a[1]+1)*a[2]+parseFloat(G.css(t,i)),s="number"),!(null==n||"number"===s&&isNaN(n)||("number"!==s||G.cssNumber[l]||(n+="px"),o&&"set"in o&&(n=o.set(t,n,r))===e)))try{u[i]=n}catch(c){}}},css:function(t,i,n,r){var a,s,o,l=G.camelCase(i);return i=G.cssProps[l]||(G.cssProps[l]=m(t.style,l)),o=G.cssHooks[i]||G.cssHooks[l],o&&"get"in o&&(a=o.get(t,!0,r)),a===e&&(a=ii(t,i)),"normal"===a&&i in gi&&(a=gi[i]),n||r!==e?(s=parseFloat(a),n||G.isNumeric(s)?s||0:a):a},swap:function(t,e,i){var n,r,a={};for(r in e)a[r]=t.style[r],t.style[r]=e[r];n=i.call(t);for(r in e)t.style[r]=a[r];return n}}),t.getComputedStyle?ii=function(e,i){var n,r,a,s,o=t.getComputedStyle(e,null),l=e.style;return o&&(n=o.getPropertyValue(i)||o[i],""!==n||G.contains(e.ownerDocument,e)||(n=G.style(e,i)),hi.test(n)&&ui.test(i)&&(r=l.width,a=l.minWidth,s=l.maxWidth,l.minWidth=l.maxWidth=l.width=n,n=o.width,l.width=r,l.minWidth=a,l.maxWidth=s)),n}:H.documentElement.currentStyle&&(ii=function(t,e){var i,n,r=t.currentStyle&&t.currentStyle[e],a=t.style;return null==r&&a&&a[e]&&(r=a[e]),hi.test(r)&&!oi.test(e)&&(i=a.left,n=t.runtimeStyle&&t.runtimeStyle.left,n&&(t.runtimeStyle.left=t.currentStyle.left),a.left="fontSize"===e?"1em":r,r=a.pixelLeft+"px",a.left=i,n&&(t.runtimeStyle.left=n)),""===r?"auto":r}),G.each(["height","width"],function(t,i){G.cssHooks[i]={get:function(t,n,r){return n?0===t.offsetWidth&&li.test(ii(t,"display"))?G.swap(t,fi,function(){return w(t,i,r)}):w(t,i,r):e},set:function(t,e,n){return b(t,e,n?x(t,i,n,G.support.boxSizing&&"border-box"===G.css(t,"boxSizing")):0)}}}),G.support.opacity||(G.cssHooks.opacity={get:function(t,e){return si.test((e&&t.currentStyle?t.currentStyle.filter:t.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":e?"1":""},set:function(t,e){var i=t.style,n=t.currentStyle,r=G.isNumeric(e)?"alpha(opacity="+100*e+")":"",a=n&&n.filter||i.filter||"";i.zoom=1,e>=1&&""===G.trim(a.replace(ai,""))&&i.removeAttribute&&(i.removeAttribute("filter"),n&&!n.filter)||(i.filter=ai.test(a)?a.replace(ai,r):a+" "+r)}}),G(function(){G.support.reliableMarginRight||(G.cssHooks.marginRight={get:function(t,i){return G.swap(t,{display:"inline-block"},function(){return i?ii(t,"marginRight"):e})}}),!G.support.pixelPosition&&G.fn.position&&G.each(["top","left"],function(t,e){G.cssHooks[e]={get:function(t,i){if(i){var n=ii(t,e);return hi.test(n)?G(t).position()[e]+"px":n}}}})}),G.expr&&G.expr.filters&&(G.expr.filters.hidden=function(t){return 0===t.offsetWidth&&0===t.offsetHeight||!G.support.reliableHiddenOffsets&&"none"===(t.style&&t.style.display||ii(t,"display"))},G.expr.filters.visible=function(t){return!G.expr.filters.hidden(t)}),G.each({margin:"",padding:"",border:"Width"},function(t,e){G.cssHooks[t+e]={expand:function(i){var n,r="string"==typeof i?i.split(" "):[i],a={};for(n=0;4>n;n++)a[t+mi[n]+e]=r[n]||r[n-2]||r[0];return a}},ui.test(t)||(G.cssHooks[t+e].set=b)});var bi=/%20/g,xi=/\[\]$/,wi=/\r?\n/g,_i=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,ki=/^(?:select|textarea)/i;G.fn.extend({serialize:function(){return G.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?G.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||ki.test(this.nodeName)||_i.test(this.type))}).map(function(t,e){var i=G(this).val();return null==i?null:G.isArray(i)?G.map(i,function(t){return{name:e.name,value:t.replace(wi,"\r\n")}}):{name:e.name,value:i.replace(wi,"\r\n")}}).get()}}),G.param=function(t,i){var n,r=[],a=function(t,e){e=G.isFunction(e)?e():null==e?"":e,r[r.length]=encodeURIComponent(t)+"="+encodeURIComponent(e)};if(i===e&&(i=G.ajaxSettings&&G.ajaxSettings.traditional),G.isArray(t)||t.jquery&&!G.isPlainObject(t))G.each(t,function(){a(this.name,this.value)});else for(n in t)k(n,t[n],i,a);return r.join("&").replace(bi,"+")};var Si,Ai,Di=/#.*$/,Ci=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Ti=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,Mi=/^(?:GET|HEAD)$/,Ni=/^\/\//,Pi=/\?/,Ji=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,$i=/([?&])_=[^&]*/,Ei=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,Ii=G.fn.load,Li={},ji={},Fi=["*/"]+["*"];try{Ai=B.href}catch(Oi){Ai=H.createElement("a"),Ai.href="",Ai=Ai.href}Si=Ei.exec(Ai.toLowerCase())||[],G.fn.load=function(t,i,n){if("string"!=typeof t&&Ii)return Ii.apply(this,arguments);if(!this.length)return this;var r,a,s,o=this,l=t.indexOf(" ");return l>=0&&(r=t.slice(l,t.length),t=t.slice(0,l)),G.isFunction(i)?(n=i,i=e):i&&"object"==typeof i&&(a="POST"),G.ajax({url:t,type:a,dataType:"html",data:i,complete:function(t,e){n&&o.each(n,s||[t.responseText,e,t])}}).done(function(t){s=arguments,o.html(r?G("<div>").append(t.replace(Ji,"")).find(r):t)}),this},G.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(t,e){G.fn[e]=function(t){return this.on(e,t)}}),G.each(["get","post"],function(t,i){G[i]=function(t,n,r,a){return G.isFunction(n)&&(a=a||r,r=n,n=e),G.ajax({type:i,url:t,data:n,success:r,dataType:a})}}),G.extend({getScript:function(t,i){return G.get(t,e,i,"script")},getJSON:function(t,e,i){return G.get(t,e,i,"json")},ajaxSetup:function(t,e){return e?D(t,G.ajaxSettings):(e=t,t=G.ajaxSettings),D(t,e),t},ajaxSettings:{url:Ai,isLocal:Ti.test(Si[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded; charset=UTF-8",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":Fi},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":t.String,"text html":!0,"text json":G.parseJSON,"text xml":G.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:S(Li),ajaxTransport:S(ji),ajax:function(t,i){function n(t,i,n,s){var u,h,y,b,w,k=i;2!==x&&(x=2,l&&clearTimeout(l),o=e,a=s||"",_.readyState=t>0?4:0,n&&(b=C(d,_,n)),t>=200&&300>t||304===t?(d.ifModified&&(w=_.getResponseHeader("Last-Modified"),w&&(G.lastModified[r]=w),w=_.getResponseHeader("Etag"),w&&(G.etag[r]=w)),304===t?(k="notmodified",u=!0):(u=T(d,b),k=u.state,h=u.data,y=u.error,u=!y)):(y=k,(!k||t)&&(k="error",0>t&&(t=0))),_.status=t,_.statusText=(i||k)+"",u?g.resolveWith(p,[h,k,_]):g.rejectWith(p,[_,k,y]),_.statusCode(v),v=e,c&&f.trigger("ajax"+(u?"Success":"Error"),[_,d,u?h:y]),m.fireWith(p,[_,k]),c&&(f.trigger("ajaxComplete",[_,d]),--G.active||G.event.trigger("ajaxStop")))}"object"==typeof t&&(i=t,t=e),i=i||{};var r,a,s,o,l,u,c,h,d=G.ajaxSetup({},i),p=d.context||d,f=p!==d&&(p.nodeType||p instanceof G)?G(p):G.event,g=G.Deferred(),m=G.Callbacks("once memory"),v=d.statusCode||{},y={},b={},x=0,w="canceled",_={readyState:0,setRequestHeader:function(t,e){if(!x){var i=t.toLowerCase();t=b[i]=b[i]||t,y[t]=e}return this},getAllResponseHeaders:function(){return 2===x?a:null},getResponseHeader:function(t){var i;if(2===x){if(!s)for(s={};i=Ci.exec(a);)s[i[1].toLowerCase()]=i[2];i=s[t.toLowerCase()]}return i===e?null:i},overrideMimeType:function(t){return x||(d.mimeType=t),this},abort:function(t){return t=t||w,o&&o.abort(t),n(0,t),this}};if(g.promise(_),_.success=_.done,_.error=_.fail,_.complete=m.add,_.statusCode=function(t){if(t){var e;if(2>x)for(e in t)v[e]=[v[e],t[e]];else e=t[_.status],_.always(e)}return this},d.url=((t||d.url)+"").replace(Di,"").replace(Ni,Si[1]+"//"),d.dataTypes=G.trim(d.dataType||"*").toLowerCase().split(ee),null==d.crossDomain&&(u=Ei.exec(d.url.toLowerCase()),d.crossDomain=!(!u||u[1]===Si[1]&&u[2]===Si[2]&&(u[3]||("http:"===u[1]?80:443))==(Si[3]||("http:"===Si[1]?80:443)))),d.data&&d.processData&&"string"!=typeof d.data&&(d.data=G.param(d.data,d.traditional)),A(Li,d,i,_),2===x)return _;if(c=d.global,d.type=d.type.toUpperCase(),d.hasContent=!Mi.test(d.type),c&&0===G.active++&&G.event.trigger("ajaxStart"),!d.hasContent&&(d.data&&(d.url+=(Pi.test(d.url)?"&":"?")+d.data,delete d.data),r=d.url,d.cache===!1)){var k=G.now(),S=d.url.replace($i,"$1_="+k);d.url=S+(S===d.url?(Pi.test(d.url)?"&":"?")+"_="+k:"")}(d.data&&d.hasContent&&d.contentType!==!1||i.contentType)&&_.setRequestHeader("Content-Type",d.contentType),d.ifModified&&(r=r||d.url,G.lastModified[r]&&_.setRequestHeader("If-Modified-Since",G.lastModified[r]),G.etag[r]&&_.setRequestHeader("If-None-Match",G.etag[r])),_.setRequestHeader("Accept",d.dataTypes[0]&&d.accepts[d.dataTypes[0]]?d.accepts[d.dataTypes[0]]+("*"!==d.dataTypes[0]?", "+Fi+"; q=0.01":""):d.accepts["*"]);for(h in d.headers)_.setRequestHeader(h,d.headers[h]);if(d.beforeSend&&(d.beforeSend.call(p,_,d)===!1||2===x))return _.abort();w="abort";for(h in{success:1,error:1,complete:1})_[h](d[h]);if(o=A(ji,d,i,_)){_.readyState=1,c&&f.trigger("ajaxSend",[_,d]),d.async&&d.timeout>0&&(l=setTimeout(function(){_.abort("timeout")},d.timeout));try{x=1,o.send(y,n)}catch(D){if(!(2>x))throw D;n(-1,D)}}else n(-1,"No Transport");return _},active:0,lastModified:{},etag:{}});var Ri=[],Hi=/\?/,Bi=/(=)\?(?=&|$)|\?\?/,zi=G.now();G.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var t=Ri.pop()||G.expando+"_"+zi++;return this[t]=!0,t}}),G.ajaxPrefilter("json jsonp",function(i,n,r){var a,s,o,l=i.data,u=i.url,c=i.jsonp!==!1,h=c&&Bi.test(u),d=c&&!h&&"string"==typeof l&&!(i.contentType||"").indexOf("application/x-www-form-urlencoded")&&Bi.test(l);return"jsonp"===i.dataTypes[0]||h||d?(a=i.jsonpCallback=G.isFunction(i.jsonpCallback)?i.jsonpCallback():i.jsonpCallback,s=t[a],h?i.url=u.replace(Bi,"$1"+a):d?i.data=l.replace(Bi,"$1"+a):c&&(i.url+=(Hi.test(u)?"&":"?")+i.jsonp+"="+a),i.converters["script json"]=function(){return o||G.error(a+" was not called"),o[0]},i.dataTypes[0]="json",t[a]=function(){o=arguments},r.always(function(){t[a]=s,i[a]&&(i.jsonpCallback=n.jsonpCallback,Ri.push(a)),o&&G.isFunction(s)&&s(o[0]),o=s=e}),"script"):e}),G.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(t){return G.globalEval(t),t}}}),G.ajaxPrefilter("script",function(t){t.cache===e&&(t.cache=!1),t.crossDomain&&(t.type="GET",t.global=!1)}),G.ajaxTransport("script",function(t){if(t.crossDomain){var i,n=H.head||H.getElementsByTagName("head")[0]||H.documentElement;return{send:function(r,a){i=H.createElement("script"),i.async="async",t.scriptCharset&&(i.charset=t.scriptCharset),i.src=t.url,i.onload=i.onreadystatechange=function(t,r){(r||!i.readyState||/loaded|complete/.test(i.readyState))&&(i.onload=i.onreadystatechange=null,n&&i.parentNode&&n.removeChild(i),i=e,r||a(200,"success"))},n.insertBefore(i,n.firstChild)},abort:function(){i&&i.onload(0,1)}}}});var Yi,Wi=t.ActiveXObject?function(){for(var t in Yi)Yi[t](0,1)}:!1,qi=0;G.ajaxSettings.xhr=t.ActiveXObject?function(){return!this.isLocal&&M()||N()}:M,function(t){G.extend(G.support,{ajax:!!t,cors:!!t&&"withCredentials"in t})}(G.ajaxSettings.xhr()),G.support.ajax&&G.ajaxTransport(function(i){if(!i.crossDomain||G.support.cors){var n;return{send:function(r,a){var s,o,l=i.xhr();if(i.username?l.open(i.type,i.url,i.async,i.username,i.password):l.open(i.type,i.url,i.async),i.xhrFields)for(o in i.xhrFields)l[o]=i.xhrFields[o];i.mimeType&&l.overrideMimeType&&l.overrideMimeType(i.mimeType),i.crossDomain||r["X-Requested-With"]||(r["X-Requested-With"]="XMLHttpRequest");try{for(o in r)l.setRequestHeader(o,r[o])}catch(u){}l.send(i.hasContent&&i.data||null),n=function(t,r){var o,u,c,h,d;try{if(n&&(r||4===l.readyState))if(n=e,s&&(l.onreadystatechange=G.noop,Wi&&delete Yi[s]),r)4!==l.readyState&&l.abort();else{o=l.status,c=l.getAllResponseHeaders(),h={},d=l.responseXML,d&&d.documentElement&&(h.xml=d);try{h.text=l.responseText}catch(p){}try{u=l.statusText}catch(p){u=""}o||!i.isLocal||i.crossDomain?1223===o&&(o=204):o=h.text?200:404}}catch(f){r||a(-1,f)}h&&a(o,u,h,c)},i.async?4===l.readyState?setTimeout(n,0):(s=++qi,Wi&&(Yi||(Yi={},G(t).unload(Wi)),Yi[s]=n),l.onreadystatechange=n):n()},abort:function(){n&&n(0,1)}}}});var Ui,Xi,Vi=/^(?:toggle|show|hide)$/,Ki=RegExp("^(?:([-+])=|)("+Z+")([a-z%]*)$","i"),Qi=/queueHooks$/,Gi=[I],Zi={"*":[function(t,e){var i,n,r=this.createTween(t,e),a=Ki.exec(e),s=r.cur(),o=+s||0,l=1,u=20;if(a){if(i=+a[2],n=a[3]||(G.cssNumber[t]?"":"px"),"px"!==n&&o){o=G.css(r.elem,t,!0)||i||1;do l=l||".5",o/=l,G.style(r.elem,t,o+n);while(l!==(l=r.cur()/s)&&1!==l&&--u)}r.unit=n,r.start=o,r.end=a[1]?o+(a[1]+1)*i:i}return r}]};G.Animation=G.extend($,{tweener:function(t,e){G.isFunction(t)?(e=t,t=["*"]):t=t.split(" ");for(var i,n=0,r=t.length;r>n;n++)i=t[n],Zi[i]=Zi[i]||[],Zi[i].unshift(e)},prefilter:function(t,e){e?Gi.unshift(t):Gi.push(t)}}),G.Tween=L,L.prototype={constructor:L,init:function(t,e,i,n,r,a){this.elem=t,this.prop=i,this.easing=r||"swing",this.options=e,this.start=this.now=this.cur(),this.end=n,this.unit=a||(G.cssNumber[i]?"":"px")},cur:function(){var t=L.propHooks[this.prop];return t&&t.get?t.get(this):L.propHooks._default.get(this)},run:function(t){var e,i=L.propHooks[this.prop];return this.pos=e=this.options.duration?G.easing[this.easing](t,this.options.duration*t,0,1,this.options.duration):t,this.now=(this.end-this.start)*e+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),i&&i.set?i.set(this):L.propHooks._default.set(this),this}},L.prototype.init.prototype=L.prototype,L.propHooks={_default:{get:function(t){var e;return null==t.elem[t.prop]||t.elem.style&&null!=t.elem.style[t.prop]?(e=G.css(t.elem,t.prop,!1,""),e&&"auto"!==e?e:0):t.elem[t.prop]},set:function(t){G.fx.step[t.prop]?G.fx.step[t.prop](t):t.elem.style&&(null!=t.elem.style[G.cssProps[t.prop]]||G.cssHooks[t.prop])?G.style(t.elem,t.prop,t.now+t.unit):t.elem[t.prop]=t.now}}},L.propHooks.scrollTop=L.propHooks.scrollLeft={set:function(t){t.elem.nodeType&&t.elem.parentNode&&(t.elem[t.prop]=t.now)}},G.each(["toggle","show","hide"],function(t,e){var i=G.fn[e];G.fn[e]=function(n,r,a){return null==n||"boolean"==typeof n||!t&&G.isFunction(n)&&G.isFunction(r)?i.apply(this,arguments):this.animate(j(e,!0),n,r,a)}}),G.fn.extend({fadeTo:function(t,e,i,n){return this.filter(v).css("opacity",0).show().end().animate({opacity:e},t,i,n)},animate:function(t,e,i,n){var r=G.isEmptyObject(t),a=G.speed(e,i,n),s=function(){var e=$(this,G.extend({},t),a);r&&e.stop(!0)};return r||a.queue===!1?this.each(s):this.queue(a.queue,s)},stop:function(t,i,n){var r=function(t){var e=t.stop;delete t.stop,e(n)};return"string"!=typeof t&&(n=i,i=t,t=e),i&&t!==!1&&this.queue(t||"fx",[]),this.each(function(){var e=!0,i=null!=t&&t+"queueHooks",a=G.timers,s=G._data(this);if(i)s[i]&&s[i].stop&&r(s[i]);else for(i in s)s[i]&&s[i].stop&&Qi.test(i)&&r(s[i]);for(i=a.length;i--;)a[i].elem!==this||null!=t&&a[i].queue!==t||(a[i].anim.stop(n),e=!1,a.splice(i,1));(e||!n)&&G.dequeue(this,t)})}}),G.each({slideDown:j("show"),slideUp:j("hide"),slideToggle:j("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(t,e){G.fn[t]=function(t,i,n){return this.animate(e,t,i,n)}}),G.speed=function(t,e,i){var n=t&&"object"==typeof t?G.extend({},t):{complete:i||!i&&e||G.isFunction(t)&&t,duration:t,easing:i&&e||e&&!G.isFunction(e)&&e};return n.duration=G.fx.off?0:"number"==typeof n.duration?n.duration:n.duration in G.fx.speeds?G.fx.speeds[n.duration]:G.fx.speeds._default,(null==n.queue||n.queue===!0)&&(n.queue="fx"),n.old=n.complete,n.complete=function(){G.isFunction(n.old)&&n.old.call(this),n.queue&&G.dequeue(this,n.queue)},n},G.easing={linear:function(t){return t},swing:function(t){return.5-Math.cos(t*Math.PI)/2}},G.timers=[],G.fx=L.prototype.init,G.fx.tick=function(){var t,i=G.timers,n=0;for(Ui=G.now();i.length>n;n++)t=i[n],t()||i[n]!==t||i.splice(n--,1);i.length||G.fx.stop(),Ui=e},G.fx.timer=function(t){t()&&G.timers.push(t)&&!Xi&&(Xi=setInterval(G.fx.tick,G.fx.interval))},G.fx.interval=13,G.fx.stop=function(){clearInterval(Xi),Xi=null},G.fx.speeds={slow:600,fast:200,_default:400},G.fx.step={},G.expr&&G.expr.filters&&(G.expr.filters.animated=function(t){return G.grep(G.timers,function(e){return t===e.elem}).length});var tn=/^(?:body|html)$/i;G.fn.offset=function(t){if(arguments.length)return t===e?this:this.each(function(e){G.offset.setOffset(this,t,e)});var i,n,r,a,s,o,l,u={top:0,left:0},c=this[0],h=c&&c.ownerDocument;if(h)return(n=h.body)===c?G.offset.bodyOffset(c):(i=h.documentElement,G.contains(i,c)?(c.getBoundingClientRect!==e&&(u=c.getBoundingClientRect()),r=F(h),a=i.clientTop||n.clientTop||0,s=i.clientLeft||n.clientLeft||0,o=r.pageYOffset||i.scrollTop,l=r.pageXOffset||i.scrollLeft,{top:u.top+o-a,left:u.left+l-s}):u)},G.offset={bodyOffset:function(t){var e=t.offsetTop,i=t.offsetLeft;return G.support.doesNotIncludeMarginInBodyOffset&&(e+=parseFloat(G.css(t,"marginTop"))||0,i+=parseFloat(G.css(t,"marginLeft"))||0),{top:e,left:i}},setOffset:function(t,e,i){var n=G.css(t,"position");"static"===n&&(t.style.position="relative");var r,a,s=G(t),o=s.offset(),l=G.css(t,"top"),u=G.css(t,"left"),c=("absolute"===n||"fixed"===n)&&G.inArray("auto",[l,u])>-1,h={},d={};c?(d=s.position(),r=d.top,a=d.left):(r=parseFloat(l)||0,a=parseFloat(u)||0),G.isFunction(e)&&(e=e.call(t,i,o)),null!=e.top&&(h.top=e.top-o.top+r),null!=e.left&&(h.left=e.left-o.left+a),"using"in e?e.using.call(t,h):s.css(h)}},G.fn.extend({position:function(){if(this[0]){var t=this[0],e=this.offsetParent(),i=this.offset(),n=tn.test(e[0].nodeName)?{top:0,left:0}:e.offset();return i.top-=parseFloat(G.css(t,"marginTop"))||0,i.left-=parseFloat(G.css(t,"marginLeft"))||0,n.top+=parseFloat(G.css(e[0],"borderTopWidth"))||0,n.left+=parseFloat(G.css(e[0],"borderLeftWidth"))||0,{top:i.top-n.top,left:i.left-n.left}}},offsetParent:function(){return this.map(function(){for(var t=this.offsetParent||H.body;t&&!tn.test(t.nodeName)&&"static"===G.css(t,"position");)t=t.offsetParent;return t||H.body})}}),G.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(t,i){var n=/Y/.test(i);G.fn[t]=function(r){return G.access(this,function(t,r,a){var s=F(t);return a===e?s?i in s?s[i]:s.document.documentElement[r]:t[r]:(s?s.scrollTo(n?G(s).scrollLeft():a,n?a:G(s).scrollTop()):t[r]=a,e)},t,r,arguments.length,null)}}),G.each({Height:"height",Width:"width"},function(t,i){G.each({padding:"inner"+t,content:i,"":"outer"+t},function(n,r){G.fn[r]=function(r,a){var s=arguments.length&&(n||"boolean"!=typeof r),o=n||(r===!0||a===!0?"margin":"border");return G.access(this,function(i,n,r){var a;return G.isWindow(i)?i.document.documentElement["client"+t]:9===i.nodeType?(a=i.documentElement,Math.max(i.body["scroll"+t],a["scroll"+t],i.body["offset"+t],a["offset"+t],a["client"+t])):r===e?G.css(i,n,r,o):G.style(i,n,r,o)},i,s?r:e,s,null)}})}),t.jQuery=t.$=G,"function"==typeof define&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return G})})(window),function(t){var e,i,n="0.3.4",r="hasOwnProperty",a=/[\.\/]/,s="*",o=function(){},l=function(t,e){return t-e},u={n:{}},c=function(t,n){var r,a=i,s=Array.prototype.slice.call(arguments,2),o=c.listeners(t),u=0,h=[],d={},p=[],f=e;e=t,i=0;for(var g=0,m=o.length;m>g;g++)"zIndex"in o[g]&&(h.push(o[g].zIndex),0>o[g].zIndex&&(d[o[g].zIndex]=o[g]));for(h.sort(l);0>h[u];)if(r=d[h[u++]],p.push(r.apply(n,s)),i)return i=a,p;for(g=0;m>g;g++)if(r=o[g],"zIndex"in r)if(r.zIndex==h[u]){if(p.push(r.apply(n,s)),i)break;do if(u++,r=d[h[u]],r&&p.push(r.apply(n,s)),i)break;while(r)}else d[r.zIndex]=r;else if(p.push(r.apply(n,s)),i)break;return i=a,e=f,p.length?p:null};c.listeners=function(t){var e,i,n,r,o,l,c,h,d=t.split(a),p=u,f=[p],g=[];for(r=0,o=d.length;o>r;r++){for(h=[],l=0,c=f.length;c>l;l++)for(p=f[l].n,i=[p[d[r]],p[s]],n=2;n--;)e=i[n],e&&(h.push(e),g=g.concat(e.f||[]));f=h}return g},c.on=function(t,e){for(var i=t.split(a),n=u,r=0,s=i.length;s>r;r++)n=n.n,!n[i[r]]&&(n[i[r]]={n:{}}),n=n[i[r]];for(n.f=n.f||[],r=0,s=n.f.length;s>r;r++)if(n.f[r]==e)return o;return n.f.push(e),function(t){+t==+t&&(e.zIndex=+t)}},c.stop=function(){i=1},c.nt=function(t){return t?RegExp("(?:\\.|\\/|^)"+t+"(?:\\.|\\/|$)").test(e):e},c.off=c.unbind=function(t,e){var i,n,o,l,c,h,d,p=t.split(a),f=[u];for(l=0,c=p.length;c>l;l++)for(h=0;f.length>h;h+=o.length-2){if(o=[h,1],i=f[h].n,p[l]!=s)i[p[l]]&&o.push(i[p[l]]);else for(n in i)i[r](n)&&o.push(i[n]);f.splice.apply(f,o)}for(l=0,c=f.length;c>l;l++)for(i=f[l];i.n;){if(e){if(i.f){for(h=0,d=i.f.length;d>h;h++)if(i.f[h]==e){i.f.splice(h,1);break}!i.f.length&&delete i.f}for(n in i.n)if(i.n[r](n)&&i.n[n].f){var g=i.n[n].f;for(h=0,d=g.length;d>h;h++)if(g[h]==e){g.splice(h,1);break}!g.length&&delete i.n[n].f}}else{delete i.f;for(n in i.n)i.n[r](n)&&i.n[n].f&&delete i.n[n].f}i=i.n}},c.once=function(t,e){var i=function(){var n=e.apply(this,arguments);return c.unbind(t,i),n};return c.on(t,i)},c.version=n,c.toString=function(){return"You are running Eve "+n},"undefined"!=typeof module&&module.exports?module.exports=c:"undefined"!=typeof define?define("eve",[],function(){return c}):t.eve=c}(this),window.eve||"function"!=typeof define||"function"!=typeof require||(window.eve=require("eve")),function(){function t(e){if(t.is(e,"function"))return y?e():eve.on("raphael.DOMload",e);if(t.is(e,W))return t._engine.create[C](t,e.splice(0,3+t.is(e[0],z))).add(e);var i=Array.prototype.slice.call(arguments,0);if(t.is(i[i.length-1],"function")){var n=i.pop();return y?n.call(t._engine.create[C](t,i)):eve.on("raphael.DOMload",function(){n.call(t._engine.create[C](t,i))})}return t._engine.create[C](t,arguments)}function e(t){if(Object(t)!==t)return t;var i=new t.constructor;for(var n in t)t[k](n)&&(i[n]=e(t[n]));return i}function i(t,e){for(var i=0,n=t.length;n>i;i++)if(t[i]===e)return t.push(t.splice(i,1)[0])}function n(t,e,n){function r(){var a=Array.prototype.slice.call(arguments,0),s=a.join("\u2400"),o=r.cache=r.cache||{},l=r.count=r.count||[];return o[k](s)?(i(l,s),n?n(o[s]):o[s]):(l.length>=1e3&&delete o[l.shift()],l.push(s),o[s]=t[C](e,a),n?n(o[s]):o[s])}return r}function r(){return this.hex}function a(t,e){for(var i=[],n=0,r=t.length;r-2*!e>n;n+=2){var a=[{x:+t[n-2],y:+t[n-1]},{x:+t[n],y:+t[n+1]},{x:+t[n+2],y:+t[n+3]},{x:+t[n+4],y:+t[n+5]}];e?n?r-4==n?a[3]={x:+t[0],y:+t[1]}:r-2==n&&(a[2]={x:+t[0],y:+t[1]},a[3]={x:+t[2],y:+t[3]}):a[0]={x:+t[r-2],y:+t[r-1]}:r-4==n?a[3]=a[2]:n||(a[0]={x:+t[n],y:+t[n+1]}),i.push(["C",(-a[0].x+6*a[1].x+a[2].x)/6,(-a[0].y+6*a[1].y+a[2].y)/6,(a[1].x+6*a[2].x-a[3].x)/6,(a[1].y+6*a[2].y-a[3].y)/6,a[2].x,a[2].y])}return i}function s(t,e,i,n,r){var a=-3*e+9*i-9*n+3*r,s=t*a+6*e-12*i+6*n;return t*s-3*e+3*i}function o(t,e,i,n,r,a,o,l,u){null==u&&(u=1),u=u>1?1:0>u?0:u;for(var c=u/2,h=12,d=[-.1252,.1252,-.3678,.3678,-.5873,.5873,-.7699,.7699,-.9041,.9041,-.9816,.9816],p=[.2491,.2491,.2335,.2335,.2032,.2032,.1601,.1601,.1069,.1069,.0472,.0472],f=0,g=0;h>g;g++){var m=c*d[g]+c,v=s(m,t,i,r,o),y=s(m,e,n,a,l),b=v*v+y*y;f+=p[g]*j.sqrt(b)}return c*f }function l(t,e,i,n,r,a,s,l,u){if(!(0>u||u>o(t,e,i,n,r,a,s,l))){var c,h=1,d=h/2,p=h-d,f=.01;for(c=o(t,e,i,n,r,a,s,l,p);R(c-u)>f;)d/=2,p+=(u>c?1:-1)*d,c=o(t,e,i,n,r,a,s,l,p);return p}}function u(t,e,i,n,r,a,s,o){if(!(F(t,i)<O(r,s)||O(t,i)>F(r,s)||F(e,n)<O(a,o)||O(e,n)>F(a,o))){var l=(t*n-e*i)*(r-s)-(t-i)*(r*o-a*s),u=(t*n-e*i)*(a-o)-(e-n)*(r*o-a*s),c=(t-i)*(a-o)-(e-n)*(r-s);if(c){var h=l/c,d=u/c,p=+h.toFixed(2),f=+d.toFixed(2);if(!(+O(t,i).toFixed(2)>p||p>+F(t,i).toFixed(2)||+O(r,s).toFixed(2)>p||p>+F(r,s).toFixed(2)||+O(e,n).toFixed(2)>f||f>+F(e,n).toFixed(2)||+O(a,o).toFixed(2)>f||f>+F(a,o).toFixed(2)))return{x:h,y:d}}}}function c(e,i,n){var r=t.bezierBBox(e),a=t.bezierBBox(i);if(!t.isBBoxIntersect(r,a))return n?0:[];for(var s=o.apply(0,e),l=o.apply(0,i),c=~~(s/5),h=~~(l/5),d=[],p=[],f={},g=n?0:[],m=0;c+1>m;m++){var v=t.findDotsAtSegment.apply(t,e.concat(m/c));d.push({x:v.x,y:v.y,t:m/c})}for(m=0;h+1>m;m++)v=t.findDotsAtSegment.apply(t,i.concat(m/h)),p.push({x:v.x,y:v.y,t:m/h});for(m=0;c>m;m++)for(var y=0;h>y;y++){var b=d[m],x=d[m+1],w=p[y],_=p[y+1],k=.001>R(x.x-b.x)?"y":"x",S=.001>R(_.x-w.x)?"y":"x",A=u(b.x,b.y,x.x,x.y,w.x,w.y,_.x,_.y);if(A){if(f[A.x.toFixed(4)]==A.y.toFixed(4))continue;f[A.x.toFixed(4)]=A.y.toFixed(4);var D=b.t+R((A[k]-b[k])/(x[k]-b[k]))*(x.t-b.t),C=w.t+R((A[S]-w[S])/(_[S]-w[S]))*(_.t-w.t);D>=0&&1>=D&&C>=0&&1>=C&&(n?g++:g.push({x:A.x,y:A.y,t1:D,t2:C}))}}return g}function h(e,i,n){e=t._path2curve(e),i=t._path2curve(i);for(var r,a,s,o,l,u,h,d,p,f,g=n?0:[],m=0,v=e.length;v>m;m++){var y=e[m];if("M"==y[0])r=l=y[1],a=u=y[2];else{"C"==y[0]?(p=[r,a].concat(y.slice(1)),r=p[6],a=p[7]):(p=[r,a,r,a,l,u,l,u],r=l,a=u);for(var b=0,x=i.length;x>b;b++){var w=i[b];if("M"==w[0])s=h=w[1],o=d=w[2];else{"C"==w[0]?(f=[s,o].concat(w.slice(1)),s=f[6],o=f[7]):(f=[s,o,s,o,h,d,h,d],s=h,o=d);var _=c(p,f,n);if(n)g+=_;else{for(var k=0,S=_.length;S>k;k++)_[k].segment1=m,_[k].segment2=b,_[k].bez1=p,_[k].bez2=f;g=g.concat(_)}}}}}return g}function d(t,e,i,n,r,a){null!=t?(this.a=+t,this.b=+e,this.c=+i,this.d=+n,this.e=+r,this.f=+a):(this.a=1,this.b=0,this.c=0,this.d=1,this.e=0,this.f=0)}function p(){return this.x+P+this.y+P+this.width+" \u00d7 "+this.height}function f(t,e,i,n,r,a){function s(t){return((h*t+c)*t+u)*t}function o(t,e){var i=l(t,e);return((f*i+p)*i+d)*i}function l(t,e){var i,n,r,a,o,l;for(r=t,l=0;8>l;l++){if(a=s(r)-t,e>R(a))return r;if(o=(3*h*r+2*c)*r+u,1e-6>R(o))break;r-=a/o}if(i=0,n=1,r=t,i>r)return i;if(r>n)return n;for(;n>i;){if(a=s(r),e>R(a-t))return r;t>a?i=r:n=r,r=(n-i)/2+i}return r}var u=3*e,c=3*(n-e)-u,h=1-u-c,d=3*i,p=3*(r-i)-d,f=1-d-p;return o(t,1/(200*a))}function g(t,e){var i=[],n={};if(this.ms=e,this.times=1,t){for(var r in t)t[k](r)&&(n[Q(r)]=t[r],i.push(Q(r)));i.sort(ue)}this.anim=n,this.top=i[i.length-1],this.percents=i}function m(e,i,n,r,a,s){n=Q(n);var o,l,u,c,h,p,g=e.ms,m={},v={},y={};if(r)for(w=0,_=ai.length;_>w;w++){var b=ai[w];if(b.el.id==i.id&&b.anim==e){b.percent!=n?(ai.splice(w,1),u=1):l=b,i.attr(b.totalOrigin);break}}else r=+v;for(var w=0,_=e.percents.length;_>w;w++){if(e.percents[w]==n||e.percents[w]>r*e.top){n=e.percents[w],h=e.percents[w-1]||0,g=g/e.top*(n-h),c=e.percents[w+1],o=e.anim[n];break}r&&i.attr(e.anim[e.percents[w]])}if(o){if(l)l.initstatus=r,l.start=new Date-l.ms*r;else{for(var S in o)if(o[k](S)&&(ee[k](S)||i.paper.customAttributes[k](S)))switch(m[S]=i.attr(S),null==m[S]&&(m[S]=te[S]),v[S]=o[S],ee[S]){case z:y[S]=(v[S]-m[S])/g;break;case"colour":m[S]=t.getRGB(m[S]);var A=t.getRGB(v[S]);y[S]={r:(A.r-m[S].r)/g,g:(A.g-m[S].g)/g,b:(A.b-m[S].b)/g};break;case"path":var D=Ee(m[S],v[S]),C=D[1];for(m[S]=D[0],y[S]=[],w=0,_=m[S].length;_>w;w++){y[S][w]=[0];for(var M=1,N=m[S][w].length;N>M;M++)y[S][w][M]=(C[w][M]-m[S][w][M])/g}break;case"transform":var P=i._,E=Oe(P[S],v[S]);if(E)for(m[S]=E.from,v[S]=E.to,y[S]=[],y[S].real=!0,w=0,_=m[S].length;_>w;w++)for(y[S][w]=[m[S][w][0]],M=1,N=m[S][w].length;N>M;M++)y[S][w][M]=(v[S][w][M]-m[S][w][M])/g;else{var I=i.matrix||new d,L={_:{transform:P.transform},getBBox:function(){return i.getBBox(1)}};m[S]=[I.a,I.b,I.c,I.d,I.e,I.f],je(L,v[S]),v[S]=L._.transform,y[S]=[(L.matrix.a-I.a)/g,(L.matrix.b-I.b)/g,(L.matrix.c-I.c)/g,(L.matrix.d-I.d)/g,(L.matrix.e-I.e)/g,(L.matrix.f-I.f)/g]}break;case"csv":var j=J(o[S])[$](x),F=J(m[S])[$](x);if("clip-rect"==S)for(m[S]=F,y[S]=[],w=F.length;w--;)y[S][w]=(j[w]-m[S][w])/g;v[S]=j;break;default:for(j=[][T](o[S]),F=[][T](m[S]),y[S]=[],w=i.paper.customAttributes[S].length;w--;)y[S][w]=((j[w]||0)-(F[w]||0))/g}var O=o.easing,R=t.easing_formulas[O];if(!R)if(R=J(O).match(V),R&&5==R.length){var H=R;R=function(t){return f(t,+H[1],+H[2],+H[3],+H[4],g)}}else R=he;if(p=o.start||e.start||+new Date,b={anim:e,percent:n,timestamp:p,start:p+(e.del||0),status:0,initstatus:r||0,stop:!1,ms:g,easing:R,from:m,diff:y,to:v,el:i,callback:o.callback,prev:h,next:c,repeat:s||e.times,origin:i.attr(),totalOrigin:a},ai.push(b),r&&!l&&!u&&(b.stop=!0,b.start=new Date-g*r,1==ai.length))return oi();u&&(b.start=new Date-b.ms*r),1==ai.length&&si(oi)}eve("raphael.anim.start."+i.id,i,e)}}function v(t){for(var e=0;ai.length>e;e++)ai[e].el.paper==t&&ai.splice(e--,1)}t.version="2.1.0",t.eve=eve;var y,b,x=/[, ]+/,w={circle:1,rect:1,path:1,ellipse:1,text:1,image:1},_=/\{(\d+)\}/g,k="hasOwnProperty",S={doc:document,win:window},A={was:Object.prototype[k].call(S.win,"Raphael"),is:S.win.Raphael},D=function(){this.ca=this.customAttributes={}},C="apply",T="concat",M="createTouch"in S.doc,N="",P=" ",J=String,$="split",E="click dblclick mousedown mousemove mouseout mouseover mouseup touchstart touchmove touchend touchcancel"[$](P),I={mousedown:"touchstart",mousemove:"touchmove",mouseup:"touchend"},L=J.prototype.toLowerCase,j=Math,F=j.max,O=j.min,R=j.abs,H=j.pow,B=j.PI,z="number",Y="string",W="array",q=Object.prototype.toString,U=(t._ISURL=/^url\(['"]?([^\)]+?)['"]?\)$/i,/^\s*((#[a-f\d]{6})|(#[a-f\d]{3})|rgba?\(\s*([\d\.]+%?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+%?(?:\s*,\s*[\d\.]+%?)?)\s*\)|hsba?\(\s*([\d\.]+(?:deg|\xb0|%)?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+(?:%?\s*,\s*[\d\.]+)?)%?\s*\)|hsla?\(\s*([\d\.]+(?:deg|\xb0|%)?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+(?:%?\s*,\s*[\d\.]+)?)%?\s*\))\s*$/i),X={NaN:1,Infinity:1,"-Infinity":1},V=/^(?:cubic-)?bezier\(([^,]+),([^,]+),([^,]+),([^\)]+)\)/,K=j.round,Q=parseFloat,G=parseInt,Z=J.prototype.toUpperCase,te=t._availableAttrs={"arrow-end":"none","arrow-start":"none",blur:0,"clip-rect":"0 0 1e9 1e9",cursor:"default",cx:0,cy:0,fill:"#fff","fill-opacity":1,font:'10px "Arial"',"font-family":'"Arial"',"font-size":"10","font-style":"normal","font-weight":400,gradient:0,height:0,href:"http://raphaeljs.com/","letter-spacing":0,opacity:1,path:"M0,0",r:0,rx:0,ry:0,src:"",stroke:"#000","stroke-dasharray":"","stroke-linecap":"butt","stroke-linejoin":"butt","stroke-miterlimit":0,"stroke-opacity":1,"stroke-width":1,target:"_blank","text-anchor":"middle",title:"Raphael",transform:"",width:0,x:0,y:0},ee=t._availableAnimAttrs={blur:z,"clip-rect":"csv",cx:z,cy:z,fill:"colour","fill-opacity":z,"font-size":z,height:z,opacity:z,path:"path",r:z,rx:z,ry:z,stroke:"colour","stroke-opacity":z,"stroke-width":z,transform:"transform",width:z,x:z,y:z},ie=/[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*,[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*/,ne={hs:1,rg:1},re=/,?([achlmqrstvxz]),?/gi,ae=/([achlmrqstvz])[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029,]*((-?\d*\.?\d*(?:e[\-+]?\d+)?[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*,?[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*)+)/gi,se=/([rstm])[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029,]*((-?\d*\.?\d*(?:e[\-+]?\d+)?[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*,?[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*)+)/gi,oe=/(-?\d*\.?\d*(?:e[\-+]?\d+)?)[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*,?[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*/gi,le=(t._radial_gradient=/^r(?:\(([^,]+?)[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*,[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*([^\)]+?)\))?/,{}),ue=function(t,e){return Q(t)-Q(e)},ce=function(){},he=function(t){return t},de=t._rectPath=function(t,e,i,n,r){return r?[["M",t+r,e],["l",i-2*r,0],["a",r,r,0,0,1,r,r],["l",0,n-2*r],["a",r,r,0,0,1,-r,r],["l",2*r-i,0],["a",r,r,0,0,1,-r,-r],["l",0,2*r-n],["a",r,r,0,0,1,r,-r],["z"]]:[["M",t,e],["l",i,0],["l",0,n],["l",-i,0],["z"]]},pe=function(t,e,i,n){return null==n&&(n=i),[["M",t,e],["m",0,-n],["a",i,n,0,1,1,0,2*n],["a",i,n,0,1,1,0,-2*n],["z"]]},fe=t._getPath={path:function(t){return t.attr("path")},circle:function(t){var e=t.attrs;return pe(e.cx,e.cy,e.r)},ellipse:function(t){var e=t.attrs;return pe(e.cx,e.cy,e.rx,e.ry)},rect:function(t){var e=t.attrs;return de(e.x,e.y,e.width,e.height,e.r)},image:function(t){var e=t.attrs;return de(e.x,e.y,e.width,e.height)},text:function(t){var e=t._getBBox();return de(e.x,e.y,e.width,e.height)}},ge=t.mapPath=function(t,e){if(!e)return t;var i,n,r,a,s,o,l;for(t=Ee(t),r=0,s=t.length;s>r;r++)for(l=t[r],a=1,o=l.length;o>a;a+=2)i=e.x(l[a],l[a+1]),n=e.y(l[a],l[a+1]),l[a]=i,l[a+1]=n;return t};if(t._g=S,t.type=S.win.SVGAngle||S.doc.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure","1.1")?"SVG":"VML","VML"==t.type){var me,ve=S.doc.createElement("div");if(ve.innerHTML='<v:shape adj="1"/>',me=ve.firstChild,me.style.behavior="url(#default#VML)",!me||"object"!=typeof me.adj)return t.type=N;ve=null}t.svg=!(t.vml="VML"==t.type),t._Paper=D,t.fn=b=D.prototype=t.prototype,t._id=0,t._oid=0,t.is=function(t,e){return e=L.call(e),"finite"==e?!X[k](+t):"array"==e?t instanceof Array:"null"==e&&null===t||e==typeof t&&null!==t||"object"==e&&t===Object(t)||"array"==e&&Array.isArray&&Array.isArray(t)||q.call(t).slice(8,-1).toLowerCase()==e},t.angle=function(e,i,n,r,a,s){if(null==a){var o=e-n,l=i-r;return o||l?(180+180*j.atan2(-l,-o)/B+360)%360:0}return t.angle(e,i,a,s)-t.angle(n,r,a,s)},t.rad=function(t){return t%360*B/180},t.deg=function(t){return 180*t/B%360},t.snapTo=function(e,i,n){if(n=t.is(n,"finite")?n:10,t.is(e,W)){for(var r=e.length;r--;)if(n>=R(e[r]-i))return e[r]}else{e=+e;var a=i%e;if(n>a)return i-a;if(a>e-n)return i-a+e}return i},t.createUUID=function(t,e){return function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(t,e).toUpperCase()}}(/[xy]/g,function(t){var e=0|16*j.random(),i="x"==t?e:8|3&e;return i.toString(16)}),t.setWindow=function(e){eve("raphael.setWindow",t,S.win,e),S.win=e,S.doc=S.win.document,t._engine.initWin&&t._engine.initWin(S.win)};var ye=function(e){if(t.vml){var i,r=/^\s+|\s+$/g;try{var a=new ActiveXObject("htmlfile");a.write("<body>"),a.close(),i=a.body}catch(s){i=createPopup().document.body}var o=i.createTextRange();ye=n(function(t){try{i.style.color=J(t).replace(r,N);var e=o.queryCommandValue("ForeColor");return e=(255&e)<<16|65280&e|(16711680&e)>>>16,"#"+("000000"+e.toString(16)).slice(-6)}catch(n){return"none"}})}else{var l=S.doc.createElement("i");l.title="Rapha\u00ebl Colour Picker",l.style.display="none",S.doc.body.appendChild(l),ye=n(function(t){return l.style.color=t,S.doc.defaultView.getComputedStyle(l,N).getPropertyValue("color")})}return ye(e)},be=function(){return"hsb("+[this.h,this.s,this.b]+")"},xe=function(){return"hsl("+[this.h,this.s,this.l]+")"},we=function(){return this.hex},_e=function(e,i,n){if(null==i&&t.is(e,"object")&&"r"in e&&"g"in e&&"b"in e&&(n=e.b,i=e.g,e=e.r),null==i&&t.is(e,Y)){var r=t.getRGB(e);e=r.r,i=r.g,n=r.b}return(e>1||i>1||n>1)&&(e/=255,i/=255,n/=255),[e,i,n]},ke=function(e,i,n,r){e*=255,i*=255,n*=255;var a={r:e,g:i,b:n,hex:t.rgb(e,i,n),toString:we};return t.is(r,"finite")&&(a.opacity=r),a};t.color=function(e){var i;return t.is(e,"object")&&"h"in e&&"s"in e&&"b"in e?(i=t.hsb2rgb(e),e.r=i.r,e.g=i.g,e.b=i.b,e.hex=i.hex):t.is(e,"object")&&"h"in e&&"s"in e&&"l"in e?(i=t.hsl2rgb(e),e.r=i.r,e.g=i.g,e.b=i.b,e.hex=i.hex):(t.is(e,"string")&&(e=t.getRGB(e)),t.is(e,"object")&&"r"in e&&"g"in e&&"b"in e?(i=t.rgb2hsl(e),e.h=i.h,e.s=i.s,e.l=i.l,i=t.rgb2hsb(e),e.v=i.b):(e={hex:"none"},e.r=e.g=e.b=e.h=e.s=e.v=e.l=-1)),e.toString=we,e},t.hsb2rgb=function(t,e,i,n){this.is(t,"object")&&"h"in t&&"s"in t&&"b"in t&&(i=t.b,e=t.s,t=t.h,n=t.o),t*=360;var r,a,s,o,l;return t=t%360/60,l=i*e,o=l*(1-R(t%2-1)),r=a=s=i-l,t=~~t,r+=[l,o,0,0,o,l][t],a+=[o,l,l,o,0,0][t],s+=[0,0,o,l,l,o][t],ke(r,a,s,n)},t.hsl2rgb=function(t,e,i,n){this.is(t,"object")&&"h"in t&&"s"in t&&"l"in t&&(i=t.l,e=t.s,t=t.h),(t>1||e>1||i>1)&&(t/=360,e/=100,i/=100),t*=360;var r,a,s,o,l;return t=t%360/60,l=2*e*(.5>i?i:1-i),o=l*(1-R(t%2-1)),r=a=s=i-l/2,t=~~t,r+=[l,o,0,0,o,l][t],a+=[o,l,l,o,0,0][t],s+=[0,0,o,l,l,o][t],ke(r,a,s,n)},t.rgb2hsb=function(t,e,i){i=_e(t,e,i),t=i[0],e=i[1],i=i[2];var n,r,a,s;return a=F(t,e,i),s=a-O(t,e,i),n=0==s?null:a==t?(e-i)/s:a==e?(i-t)/s+2:(t-e)/s+4,n=60*((n+360)%6)/360,r=0==s?0:s/a,{h:n,s:r,b:a,toString:be}},t.rgb2hsl=function(t,e,i){i=_e(t,e,i),t=i[0],e=i[1],i=i[2];var n,r,a,s,o,l;return s=F(t,e,i),o=O(t,e,i),l=s-o,n=0==l?null:s==t?(e-i)/l:s==e?(i-t)/l+2:(t-e)/l+4,n=60*((n+360)%6)/360,a=(s+o)/2,r=0==l?0:.5>a?l/(2*a):l/(2-2*a),{h:n,s:r,l:a,toString:xe}},t._path2string=function(){return this.join(",").replace(re,"$1")},t._preload=function(t,e){var i=S.doc.createElement("img");i.style.cssText="position:absolute;left:-9999em;top:-9999em",i.onload=function(){e.call(this),this.onload=null,S.doc.body.removeChild(this)},i.onerror=function(){S.doc.body.removeChild(this)},S.doc.body.appendChild(i),i.src=t},t.getRGB=n(function(e){if(!e||(e=J(e)).indexOf("-")+1)return{r:-1,g:-1,b:-1,hex:"none",error:1,toString:r};if("none"==e)return{r:-1,g:-1,b:-1,hex:"none",toString:r};!(ne[k](e.toLowerCase().substring(0,2))||"#"==e.charAt())&&(e=ye(e));var i,n,a,s,o,l,u=e.match(U);return u?(u[2]&&(a=G(u[2].substring(5),16),n=G(u[2].substring(3,5),16),i=G(u[2].substring(1,3),16)),u[3]&&(a=G((o=u[3].charAt(3))+o,16),n=G((o=u[3].charAt(2))+o,16),i=G((o=u[3].charAt(1))+o,16)),u[4]&&(l=u[4][$](ie),i=Q(l[0]),"%"==l[0].slice(-1)&&(i*=2.55),n=Q(l[1]),"%"==l[1].slice(-1)&&(n*=2.55),a=Q(l[2]),"%"==l[2].slice(-1)&&(a*=2.55),"rgba"==u[1].toLowerCase().slice(0,4)&&(s=Q(l[3])),l[3]&&"%"==l[3].slice(-1)&&(s/=100)),u[5]?(l=u[5][$](ie),i=Q(l[0]),"%"==l[0].slice(-1)&&(i*=2.55),n=Q(l[1]),"%"==l[1].slice(-1)&&(n*=2.55),a=Q(l[2]),"%"==l[2].slice(-1)&&(a*=2.55),("deg"==l[0].slice(-3)||"\u00b0"==l[0].slice(-1))&&(i/=360),"hsba"==u[1].toLowerCase().slice(0,4)&&(s=Q(l[3])),l[3]&&"%"==l[3].slice(-1)&&(s/=100),t.hsb2rgb(i,n,a,s)):u[6]?(l=u[6][$](ie),i=Q(l[0]),"%"==l[0].slice(-1)&&(i*=2.55),n=Q(l[1]),"%"==l[1].slice(-1)&&(n*=2.55),a=Q(l[2]),"%"==l[2].slice(-1)&&(a*=2.55),("deg"==l[0].slice(-3)||"\u00b0"==l[0].slice(-1))&&(i/=360),"hsla"==u[1].toLowerCase().slice(0,4)&&(s=Q(l[3])),l[3]&&"%"==l[3].slice(-1)&&(s/=100),t.hsl2rgb(i,n,a,s)):(u={r:i,g:n,b:a,toString:r},u.hex="#"+(16777216|a|n<<8|i<<16).toString(16).slice(1),t.is(s,"finite")&&(u.opacity=s),u)):{r:-1,g:-1,b:-1,hex:"none",error:1,toString:r}},t),t.hsb=n(function(e,i,n){return t.hsb2rgb(e,i,n).hex}),t.hsl=n(function(e,i,n){return t.hsl2rgb(e,i,n).hex}),t.rgb=n(function(t,e,i){return"#"+(16777216|i|e<<8|t<<16).toString(16).slice(1)}),t.getColor=function(t){var e=this.getColor.start=this.getColor.start||{h:0,s:1,b:t||.75},i=this.hsb2rgb(e.h,e.s,e.b);return e.h+=.075,e.h>1&&(e.h=0,e.s-=.2,0>=e.s&&(this.getColor.start={h:0,s:1,b:e.b})),i.hex},t.getColor.reset=function(){delete this.start},t.parsePathString=function(e){if(!e)return null;var i=Se(e);if(i.arr)return De(i.arr);var n={a:7,c:6,h:1,l:2,m:2,r:4,q:4,s:4,t:2,v:1,z:0},r=[];return t.is(e,W)&&t.is(e[0],W)&&(r=De(e)),r.length||J(e).replace(ae,function(t,e,i){var a=[],s=e.toLowerCase();if(i.replace(oe,function(t,e){e&&a.push(+e)}),"m"==s&&a.length>2&&(r.push([e][T](a.splice(0,2))),s="l",e="m"==e?"l":"L"),"r"==s)r.push([e][T](a));else for(;a.length>=n[s]&&(r.push([e][T](a.splice(0,n[s]))),n[s]););}),r.toString=t._path2string,i.arr=De(r),r},t.parseTransformString=n(function(e){if(!e)return null;var i=[];return t.is(e,W)&&t.is(e[0],W)&&(i=De(e)),i.length||J(e).replace(se,function(t,e,n){var r=[];L.call(e),n.replace(oe,function(t,e){e&&r.push(+e)}),i.push([e][T](r))}),i.toString=t._path2string,i});var Se=function(t){var e=Se.ps=Se.ps||{};return e[t]?e[t].sleep=100:e[t]={sleep:100},setTimeout(function(){for(var i in e)e[k](i)&&i!=t&&(e[i].sleep--,!e[i].sleep&&delete e[i])}),e[t]};t.findDotsAtSegment=function(t,e,i,n,r,a,s,o,l){var u=1-l,c=H(u,3),h=H(u,2),d=l*l,p=d*l,f=c*t+3*h*l*i+3*u*l*l*r+p*s,g=c*e+3*h*l*n+3*u*l*l*a+p*o,m=t+2*l*(i-t)+d*(r-2*i+t),v=e+2*l*(n-e)+d*(a-2*n+e),y=i+2*l*(r-i)+d*(s-2*r+i),b=n+2*l*(a-n)+d*(o-2*a+n),x=u*t+l*i,w=u*e+l*n,_=u*r+l*s,k=u*a+l*o,S=90-180*j.atan2(m-y,v-b)/B;return(m>y||b>v)&&(S+=180),{x:f,y:g,m:{x:m,y:v},n:{x:y,y:b},start:{x:x,y:w},end:{x:_,y:k},alpha:S}},t.bezierBBox=function(e,i,n,r,a,s,o,l){t.is(e,"array")||(e=[e,i,n,r,a,s,o,l]);var u=$e.apply(null,e);return{x:u.min.x,y:u.min.y,x2:u.max.x,y2:u.max.y,width:u.max.x-u.min.x,height:u.max.y-u.min.y}},t.isPointInsideBBox=function(t,e,i){return e>=t.x&&t.x2>=e&&i>=t.y&&t.y2>=i},t.isBBoxIntersect=function(e,i){var n=t.isPointInsideBBox;return n(i,e.x,e.y)||n(i,e.x2,e.y)||n(i,e.x,e.y2)||n(i,e.x2,e.y2)||n(e,i.x,i.y)||n(e,i.x2,i.y)||n(e,i.x,i.y2)||n(e,i.x2,i.y2)||(e.x<i.x2&&e.x>i.x||i.x<e.x2&&i.x>e.x)&&(e.y<i.y2&&e.y>i.y||i.y<e.y2&&i.y>e.y)},t.pathIntersection=function(t,e){return h(t,e)},t.pathIntersectionNumber=function(t,e){return h(t,e,1)},t.isPointInsidePath=function(e,i,n){var r=t.pathBBox(e);return t.isPointInsideBBox(r,i,n)&&1==h(e,[["M",i,n],["H",r.x2+10]],1)%2},t._removedFactory=function(t){return function(){eve("raphael.log",null,"Rapha\u00ebl: you are calling to method \u201c"+t+"\u201d of removed object",t)}};var Ae=t.pathBBox=function(t){var i=Se(t);if(i.bbox)return i.bbox;if(!t)return{x:0,y:0,width:0,height:0,x2:0,y2:0};t=Ee(t);for(var n,r=0,a=0,s=[],o=[],l=0,u=t.length;u>l;l++)if(n=t[l],"M"==n[0])r=n[1],a=n[2],s.push(r),o.push(a);else{var c=$e(r,a,n[1],n[2],n[3],n[4],n[5],n[6]);s=s[T](c.min.x,c.max.x),o=o[T](c.min.y,c.max.y),r=n[5],a=n[6]}var h=O[C](0,s),d=O[C](0,o),p=F[C](0,s),f=F[C](0,o),g={x:h,y:d,x2:p,y2:f,width:p-h,height:f-d};return i.bbox=e(g),g},De=function(i){var n=e(i);return n.toString=t._path2string,n},Ce=t._pathToRelative=function(e){var i=Se(e);if(i.rel)return De(i.rel);t.is(e,W)&&t.is(e&&e[0],W)||(e=t.parsePathString(e));var n=[],r=0,a=0,s=0,o=0,l=0;"M"==e[0][0]&&(r=e[0][1],a=e[0][2],s=r,o=a,l++,n.push(["M",r,a]));for(var u=l,c=e.length;c>u;u++){var h=n[u]=[],d=e[u];if(d[0]!=L.call(d[0]))switch(h[0]=L.call(d[0]),h[0]){case"a":h[1]=d[1],h[2]=d[2],h[3]=d[3],h[4]=d[4],h[5]=d[5],h[6]=+(d[6]-r).toFixed(3),h[7]=+(d[7]-a).toFixed(3);break;case"v":h[1]=+(d[1]-a).toFixed(3);break;case"m":s=d[1],o=d[2];default:for(var p=1,f=d.length;f>p;p++)h[p]=+(d[p]-(p%2?r:a)).toFixed(3)}else{h=n[u]=[],"m"==d[0]&&(s=d[1]+r,o=d[2]+a);for(var g=0,m=d.length;m>g;g++)n[u][g]=d[g]}var v=n[u].length;switch(n[u][0]){case"z":r=s,a=o;break;case"h":r+=+n[u][v-1];break;case"v":a+=+n[u][v-1];break;default:r+=+n[u][v-2],a+=+n[u][v-1]}}return n.toString=t._path2string,i.rel=De(n),n},Te=t._pathToAbsolute=function(e){var i=Se(e);if(i.abs)return De(i.abs);if(t.is(e,W)&&t.is(e&&e[0],W)||(e=t.parsePathString(e)),!e||!e.length)return[["M",0,0]];var n=[],r=0,s=0,o=0,l=0,u=0;"M"==e[0][0]&&(r=+e[0][1],s=+e[0][2],o=r,l=s,u++,n[0]=["M",r,s]);for(var c,h,d=3==e.length&&"M"==e[0][0]&&"R"==e[1][0].toUpperCase()&&"Z"==e[2][0].toUpperCase(),p=u,f=e.length;f>p;p++){if(n.push(c=[]),h=e[p],h[0]!=Z.call(h[0]))switch(c[0]=Z.call(h[0]),c[0]){case"A":c[1]=h[1],c[2]=h[2],c[3]=h[3],c[4]=h[4],c[5]=h[5],c[6]=+(h[6]+r),c[7]=+(h[7]+s);break;case"V":c[1]=+h[1]+s;break;case"H":c[1]=+h[1]+r;break;case"R":for(var g=[r,s][T](h.slice(1)),m=2,v=g.length;v>m;m++)g[m]=+g[m]+r,g[++m]=+g[m]+s;n.pop(),n=n[T](a(g,d));break;case"M":o=+h[1]+r,l=+h[2]+s;default:for(m=1,v=h.length;v>m;m++)c[m]=+h[m]+(m%2?r:s)}else if("R"==h[0])g=[r,s][T](h.slice(1)),n.pop(),n=n[T](a(g,d)),c=["R"][T](h.slice(-2));else for(var y=0,b=h.length;b>y;y++)c[y]=h[y];switch(c[0]){case"Z":r=o,s=l;break;case"H":r=c[1];break;case"V":s=c[1];break;case"M":o=c[c.length-2],l=c[c.length-1];default:r=c[c.length-2],s=c[c.length-1]}}return n.toString=t._path2string,i.abs=De(n),n},Me=function(t,e,i,n){return[t,e,i,n,i,n]},Ne=function(t,e,i,n,r,a){var s=1/3,o=2/3;return[s*t+o*i,s*e+o*n,s*r+o*i,s*a+o*n,r,a]},Pe=function(t,e,i,r,a,s,o,l,u,c){var h,d=120*B/180,p=B/180*(+a||0),f=[],g=n(function(t,e,i){var n=t*j.cos(i)-e*j.sin(i),r=t*j.sin(i)+e*j.cos(i);return{x:n,y:r}});if(c)S=c[0],A=c[1],_=c[2],k=c[3];else{h=g(t,e,-p),t=h.x,e=h.y,h=g(l,u,-p),l=h.x,u=h.y;var m=(j.cos(B/180*a),j.sin(B/180*a),(t-l)/2),v=(e-u)/2,y=m*m/(i*i)+v*v/(r*r);y>1&&(y=j.sqrt(y),i=y*i,r=y*r);var b=i*i,x=r*r,w=(s==o?-1:1)*j.sqrt(R((b*x-b*v*v-x*m*m)/(b*v*v+x*m*m))),_=w*i*v/r+(t+l)/2,k=w*-r*m/i+(e+u)/2,S=j.asin(((e-k)/r).toFixed(9)),A=j.asin(((u-k)/r).toFixed(9));S=_>t?B-S:S,A=_>l?B-A:A,0>S&&(S=2*B+S),0>A&&(A=2*B+A),o&&S>A&&(S-=2*B),!o&&A>S&&(A-=2*B)}var D=A-S;if(R(D)>d){var C=A,M=l,N=u;A=S+d*(o&&A>S?1:-1),l=_+i*j.cos(A),u=k+r*j.sin(A),f=Pe(l,u,i,r,a,0,o,M,N,[A,C,_,k])}D=A-S;var P=j.cos(S),J=j.sin(S),E=j.cos(A),I=j.sin(A),L=j.tan(D/4),F=4/3*i*L,O=4/3*r*L,H=[t,e],z=[t+F*J,e-O*P],Y=[l+F*I,u-O*E],W=[l,u];if(z[0]=2*H[0]-z[0],z[1]=2*H[1]-z[1],c)return[z,Y,W][T](f);f=[z,Y,W][T](f).join()[$](",");for(var q=[],U=0,X=f.length;X>U;U++)q[U]=U%2?g(f[U-1],f[U],p).y:g(f[U],f[U+1],p).x;return q},Je=function(t,e,i,n,r,a,s,o,l){var u=1-l;return{x:H(u,3)*t+3*H(u,2)*l*i+3*u*l*l*r+H(l,3)*s,y:H(u,3)*e+3*H(u,2)*l*n+3*u*l*l*a+H(l,3)*o}},$e=n(function(t,e,i,n,r,a,s,o){var l,u=r-2*i+t-(s-2*r+i),c=2*(i-t)-2*(r-i),h=t-i,d=(-c+j.sqrt(c*c-4*u*h))/2/u,p=(-c-j.sqrt(c*c-4*u*h))/2/u,f=[e,o],g=[t,s];return R(d)>"1e12"&&(d=.5),R(p)>"1e12"&&(p=.5),d>0&&1>d&&(l=Je(t,e,i,n,r,a,s,o,d),g.push(l.x),f.push(l.y)),p>0&&1>p&&(l=Je(t,e,i,n,r,a,s,o,p),g.push(l.x),f.push(l.y)),u=a-2*n+e-(o-2*a+n),c=2*(n-e)-2*(a-n),h=e-n,d=(-c+j.sqrt(c*c-4*u*h))/2/u,p=(-c-j.sqrt(c*c-4*u*h))/2/u,R(d)>"1e12"&&(d=.5),R(p)>"1e12"&&(p=.5),d>0&&1>d&&(l=Je(t,e,i,n,r,a,s,o,d),g.push(l.x),f.push(l.y)),p>0&&1>p&&(l=Je(t,e,i,n,r,a,s,o,p),g.push(l.x),f.push(l.y)),{min:{x:O[C](0,g),y:O[C](0,f)},max:{x:F[C](0,g),y:F[C](0,f)}}}),Ee=t._path2curve=n(function(t,e){var i=!e&&Se(t);if(!e&&i.curve)return De(i.curve);for(var n=Te(t),r=e&&Te(e),a={x:0,y:0,bx:0,by:0,X:0,Y:0,qx:null,qy:null},s={x:0,y:0,bx:0,by:0,X:0,Y:0,qx:null,qy:null},o=(function(t,e){var i,n;if(!t)return["C",e.x,e.y,e.x,e.y,e.x,e.y];switch(!(t[0]in{T:1,Q:1})&&(e.qx=e.qy=null),t[0]){case"M":e.X=t[1],e.Y=t[2];break;case"A":t=["C"][T](Pe[C](0,[e.x,e.y][T](t.slice(1))));break;case"S":i=e.x+(e.x-(e.bx||e.x)),n=e.y+(e.y-(e.by||e.y)),t=["C",i,n][T](t.slice(1));break;case"T":e.qx=e.x+(e.x-(e.qx||e.x)),e.qy=e.y+(e.y-(e.qy||e.y)),t=["C"][T](Ne(e.x,e.y,e.qx,e.qy,t[1],t[2]));break;case"Q":e.qx=t[1],e.qy=t[2],t=["C"][T](Ne(e.x,e.y,t[1],t[2],t[3],t[4]));break;case"L":t=["C"][T](Me(e.x,e.y,t[1],t[2]));break;case"H":t=["C"][T](Me(e.x,e.y,t[1],e.y));break;case"V":t=["C"][T](Me(e.x,e.y,e.x,t[1]));break;case"Z":t=["C"][T](Me(e.x,e.y,e.X,e.Y))}return t}),l=function(t,e){if(t[e].length>7){t[e].shift();for(var i=t[e];i.length;)t.splice(e++,0,["C"][T](i.splice(0,6)));t.splice(e,1),h=F(n.length,r&&r.length||0)}},u=function(t,e,i,a,s){t&&e&&"M"==t[s][0]&&"M"!=e[s][0]&&(e.splice(s,0,["M",a.x,a.y]),i.bx=0,i.by=0,i.x=t[s][1],i.y=t[s][2],h=F(n.length,r&&r.length||0))},c=0,h=F(n.length,r&&r.length||0);h>c;c++){n[c]=o(n[c],a),l(n,c),r&&(r[c]=o(r[c],s)),r&&l(r,c),u(n,r,a,s,c),u(r,n,s,a,c);var d=n[c],p=r&&r[c],f=d.length,g=r&&p.length;a.x=d[f-2],a.y=d[f-1],a.bx=Q(d[f-4])||a.x,a.by=Q(d[f-3])||a.y,s.bx=r&&(Q(p[g-4])||s.x),s.by=r&&(Q(p[g-3])||s.y),s.x=r&&p[g-2],s.y=r&&p[g-1]}return r||(i.curve=De(n)),r?[n,r]:n},null,De),Ie=(t._parseDots=n(function(e){for(var i=[],n=0,r=e.length;r>n;n++){var a={},s=e[n].match(/^([^:]*):?([\d\.]*)/);if(a.color=t.getRGB(s[1]),a.color.error)return null;a.color=a.color.hex,s[2]&&(a.offset=s[2]+"%"),i.push(a)}for(n=1,r=i.length-1;r>n;n++)if(!i[n].offset){for(var o=Q(i[n-1].offset||0),l=0,u=n+1;r>u;u++)if(i[u].offset){l=i[u].offset;break}l||(l=100,u=r),l=Q(l);for(var c=(l-o)/(u-n+1);u>n;n++)o+=c,i[n].offset=o+"%"}return i}),t._tear=function(t,e){t==e.top&&(e.top=t.prev),t==e.bottom&&(e.bottom=t.next),t.next&&(t.next.prev=t.prev),t.prev&&(t.prev.next=t.next)}),Le=(t._tofront=function(t,e){e.top!==t&&(Ie(t,e),t.next=null,t.prev=e.top,e.top.next=t,e.top=t)},t._toback=function(t,e){e.bottom!==t&&(Ie(t,e),t.next=e.bottom,t.prev=null,e.bottom.prev=t,e.bottom=t)},t._insertafter=function(t,e,i){Ie(t,i),e==i.top&&(i.top=t),e.next&&(e.next.prev=t),t.next=e.next,t.prev=e,e.next=t},t._insertbefore=function(t,e,i){Ie(t,i),e==i.bottom&&(i.bottom=t),e.prev&&(e.prev.next=t),t.prev=e.prev,e.prev=t,t.next=e},t.toMatrix=function(t,e){var i=Ae(t),n={_:{transform:N},getBBox:function(){return i}};return je(n,e),n.matrix}),je=(t.transformPath=function(t,e){return ge(t,Le(t,e))},t._extractTransform=function(e,i){if(null==i)return e._.transform;i=J(i).replace(/\.{3}|\u2026/g,e._.transform||N);var n=t.parseTransformString(i),r=0,a=0,s=0,o=1,l=1,u=e._,c=new d;if(u.transform=n||[],n)for(var h=0,p=n.length;p>h;h++){var f,g,m,v,y,b=n[h],x=b.length,w=J(b[0]).toLowerCase(),_=b[0]!=w,k=_?c.invert():0;"t"==w&&3==x?_?(f=k.x(0,0),g=k.y(0,0),m=k.x(b[1],b[2]),v=k.y(b[1],b[2]),c.translate(m-f,v-g)):c.translate(b[1],b[2]):"r"==w?2==x?(y=y||e.getBBox(1),c.rotate(b[1],y.x+y.width/2,y.y+y.height/2),r+=b[1]):4==x&&(_?(m=k.x(b[2],b[3]),v=k.y(b[2],b[3]),c.rotate(b[1],m,v)):c.rotate(b[1],b[2],b[3]),r+=b[1]):"s"==w?2==x||3==x?(y=y||e.getBBox(1),c.scale(b[1],b[x-1],y.x+y.width/2,y.y+y.height/2),o*=b[1],l*=b[x-1]):5==x&&(_?(m=k.x(b[3],b[4]),v=k.y(b[3],b[4]),c.scale(b[1],b[2],m,v)):c.scale(b[1],b[2],b[3],b[4]),o*=b[1],l*=b[2]):"m"==w&&7==x&&c.add(b[1],b[2],b[3],b[4],b[5],b[6]),u.dirtyT=1,e.matrix=c}e.matrix=c,u.sx=o,u.sy=l,u.deg=r,u.dx=a=c.e,u.dy=s=c.f,1==o&&1==l&&!r&&u.bbox?(u.bbox.x+=+a,u.bbox.y+=+s):u.dirtyT=1}),Fe=function(t){var e=t[0];switch(e.toLowerCase()){case"t":return[e,0,0];case"m":return[e,1,0,0,1,0,0];case"r":return 4==t.length?[e,0,t[2],t[3]]:[e,0];case"s":return 5==t.length?[e,1,1,t[3],t[4]]:3==t.length?[e,1,1]:[e,1]}},Oe=t._equaliseTransform=function(e,i){i=J(i).replace(/\.{3}|\u2026/g,e),e=t.parseTransformString(e)||[],i=t.parseTransformString(i)||[];for(var n,r,a,s,o=F(e.length,i.length),l=[],u=[],c=0;o>c;c++){if(a=e[c]||Fe(i[c]),s=i[c]||Fe(a),a[0]!=s[0]||"r"==a[0].toLowerCase()&&(a[2]!=s[2]||a[3]!=s[3])||"s"==a[0].toLowerCase()&&(a[3]!=s[3]||a[4]!=s[4]))return;for(l[c]=[],u[c]=[],n=0,r=F(a.length,s.length);r>n;n++)n in a&&(l[c][n]=a[n]),n in s&&(u[c][n]=s[n])}return{from:l,to:u}};t._getContainer=function(e,i,n,r){var a;return a=null!=r||t.is(e,"object")?e:S.doc.getElementById(e),null!=a?a.tagName?null==i?{container:a,width:a.style.pixelWidth||a.offsetWidth,height:a.style.pixelHeight||a.offsetHeight}:{container:a,width:i,height:n}:{container:1,x:e,y:i,width:n,height:r}:void 0},t.pathToRelative=Ce,t._engine={},t.path2curve=Ee,t.matrix=function(t,e,i,n,r,a){return new d(t,e,i,n,r,a)},function(e){function i(t){return t[0]*t[0]+t[1]*t[1]}function n(t){var e=j.sqrt(i(t));t[0]&&(t[0]/=e),t[1]&&(t[1]/=e)}e.add=function(t,e,i,n,r,a){var s,o,l,u,c=[[],[],[]],h=[[this.a,this.c,this.e],[this.b,this.d,this.f],[0,0,1]],p=[[t,i,r],[e,n,a],[0,0,1]];for(t&&t instanceof d&&(p=[[t.a,t.c,t.e],[t.b,t.d,t.f],[0,0,1]]),s=0;3>s;s++)for(o=0;3>o;o++){for(u=0,l=0;3>l;l++)u+=h[s][l]*p[l][o];c[s][o]=u}this.a=c[0][0],this.b=c[1][0],this.c=c[0][1],this.d=c[1][1],this.e=c[0][2],this.f=c[1][2]},e.invert=function(){var t=this,e=t.a*t.d-t.b*t.c;return new d(t.d/e,-t.b/e,-t.c/e,t.a/e,(t.c*t.f-t.d*t.e)/e,(t.b*t.e-t.a*t.f)/e)},e.clone=function(){return new d(this.a,this.b,this.c,this.d,this.e,this.f)},e.translate=function(t,e){this.add(1,0,0,1,t,e)},e.scale=function(t,e,i,n){null==e&&(e=t),(i||n)&&this.add(1,0,0,1,i,n),this.add(t,0,0,e,0,0),(i||n)&&this.add(1,0,0,1,-i,-n)},e.rotate=function(e,i,n){e=t.rad(e),i=i||0,n=n||0;var r=+j.cos(e).toFixed(9),a=+j.sin(e).toFixed(9);this.add(r,a,-a,r,i,n),this.add(1,0,0,1,-i,-n)},e.x=function(t,e){return t*this.a+e*this.c+this.e},e.y=function(t,e){return t*this.b+e*this.d+this.f},e.get=function(t){return+this[J.fromCharCode(97+t)].toFixed(4)},e.toString=function(){return t.svg?"matrix("+[this.get(0),this.get(1),this.get(2),this.get(3),this.get(4),this.get(5)].join()+")":[this.get(0),this.get(2),this.get(1),this.get(3),0,0].join()},e.toFilter=function(){return"progid:DXImageTransform.Microsoft.Matrix(M11="+this.get(0)+", M12="+this.get(2)+", M21="+this.get(1)+", M22="+this.get(3)+", Dx="+this.get(4)+", Dy="+this.get(5)+", sizingmethod='auto expand')"},e.offset=function(){return[this.e.toFixed(4),this.f.toFixed(4)]},e.split=function(){var e={};e.dx=this.e,e.dy=this.f;var r=[[this.a,this.c],[this.b,this.d]];e.scalex=j.sqrt(i(r[0])),n(r[0]),e.shear=r[0][0]*r[1][0]+r[0][1]*r[1][1],r[1]=[r[1][0]-r[0][0]*e.shear,r[1][1]-r[0][1]*e.shear],e.scaley=j.sqrt(i(r[1])),n(r[1]),e.shear/=e.scaley;var a=-r[0][1],s=r[1][1];return 0>s?(e.rotate=t.deg(j.acos(s)),0>a&&(e.rotate=360-e.rotate)):e.rotate=t.deg(j.asin(a)),e.isSimple=!(+e.shear.toFixed(9)||e.scalex.toFixed(9)!=e.scaley.toFixed(9)&&e.rotate),e.isSuperSimple=!+e.shear.toFixed(9)&&e.scalex.toFixed(9)==e.scaley.toFixed(9)&&!e.rotate,e.noRotation=!+e.shear.toFixed(9)&&!e.rotate,e},e.toTransformString=function(t){var e=t||this[$]();return e.isSimple?(e.scalex=+e.scalex.toFixed(4),e.scaley=+e.scaley.toFixed(4),e.rotate=+e.rotate.toFixed(4),(e.dx||e.dy?"t"+[e.dx,e.dy]:N)+(1!=e.scalex||1!=e.scaley?"s"+[e.scalex,e.scaley,0,0]:N)+(e.rotate?"r"+[e.rotate,0,0]:N)):"m"+[this.get(0),this.get(1),this.get(2),this.get(3),this.get(4),this.get(5)]}}(d.prototype);var Re=navigator.userAgent.match(/Version\/(.*?)\s/)||navigator.userAgent.match(/Chrome\/(\d+)/);b.safari="Apple Computer, Inc."==navigator.vendor&&(Re&&4>Re[1]||"iP"==navigator.platform.slice(0,2))||"Google Inc."==navigator.vendor&&Re&&8>Re[1]?function(){var t=this.rect(-99,-99,this.width+99,this.height+99).attr({stroke:"none"});setTimeout(function(){t.remove()})}:ce;for(var He=function(){this.returnValue=!1},Be=function(){return this.originalEvent.preventDefault()},ze=function(){this.cancelBubble=!0},Ye=function(){return this.originalEvent.stopPropagation()},We=function(){return S.doc.addEventListener?function(t,e,i,n){var r=M&&I[e]?I[e]:e,a=function(r){var a=S.doc.documentElement.scrollTop||S.doc.body.scrollTop,s=S.doc.documentElement.scrollLeft||S.doc.body.scrollLeft,o=r.clientX+s,l=r.clientY+a;if(M&&I[k](e))for(var u=0,c=r.targetTouches&&r.targetTouches.length;c>u;u++)if(r.targetTouches[u].target==t){var h=r;r=r.targetTouches[u],r.originalEvent=h,r.preventDefault=Be,r.stopPropagation=Ye;break}return i.call(n,r,o,l)};return t.addEventListener(r,a,!1),function(){return t.removeEventListener(r,a,!1),!0}}:S.doc.attachEvent?function(t,e,i,n){var r=function(t){t=t||S.win.event;var e=S.doc.documentElement.scrollTop||S.doc.body.scrollTop,r=S.doc.documentElement.scrollLeft||S.doc.body.scrollLeft,a=t.clientX+r,s=t.clientY+e;return t.preventDefault=t.preventDefault||He,t.stopPropagation=t.stopPropagation||ze,i.call(n,t,a,s) };t.attachEvent("on"+e,r);var a=function(){return t.detachEvent("on"+e,r),!0};return a}:void 0}(),qe=[],Ue=function(t){for(var e,i=t.clientX,n=t.clientY,r=S.doc.documentElement.scrollTop||S.doc.body.scrollTop,a=S.doc.documentElement.scrollLeft||S.doc.body.scrollLeft,s=qe.length;s--;){if(e=qe[s],M){for(var o,l=t.touches.length;l--;)if(o=t.touches[l],o.identifier==e.el._drag.id){i=o.clientX,n=o.clientY,(t.originalEvent?t.originalEvent:t).preventDefault();break}}else t.preventDefault();var u,c=e.el.node,h=c.nextSibling,d=c.parentNode,p=c.style.display;S.win.opera&&d.removeChild(c),c.style.display="none",u=e.el.paper.getElementByPoint(i,n),c.style.display=p,S.win.opera&&(h?d.insertBefore(c,h):d.appendChild(c)),u&&eve("raphael.drag.over."+e.el.id,e.el,u),i+=a,n+=r,eve("raphael.drag.move."+e.el.id,e.move_scope||e.el,i-e.el._drag.x,n-e.el._drag.y,i,n,t)}},Xe=function(e){t.unmousemove(Ue).unmouseup(Xe);for(var i,n=qe.length;n--;)i=qe[n],i.el._drag={},eve("raphael.drag.end."+i.el.id,i.end_scope||i.start_scope||i.move_scope||i.el,e);qe=[]},Ve=t.el={},Ke=E.length;Ke--;)(function(e){t[e]=Ve[e]=function(i,n){return t.is(i,"function")&&(this.events=this.events||[],this.events.push({name:e,f:i,unbind:We(this.shape||this.node||S.doc,e,i,n||this)})),this},t["un"+e]=Ve["un"+e]=function(t){for(var i=this.events||[],n=i.length;n--;)if(i[n].name==e&&i[n].f==t)return i[n].unbind(),i.splice(n,1),!i.length&&delete this.events,this;return this}})(E[Ke]);Ve.data=function(e,i){var n=le[this.id]=le[this.id]||{};if(1==arguments.length){if(t.is(e,"object")){for(var r in e)e[k](r)&&this.data(r,e[r]);return this}return eve("raphael.data.get."+this.id,this,n[e],e),n[e]}return n[e]=i,eve("raphael.data.set."+this.id,this,i,e),this},Ve.removeData=function(t){return null==t?le[this.id]={}:le[this.id]&&delete le[this.id][t],this},Ve.hover=function(t,e,i,n){return this.mouseover(t,i).mouseout(e,n||i)},Ve.unhover=function(t,e){return this.unmouseover(t).unmouseout(e)};var Qe=[];Ve.drag=function(e,i,n,r,a,s){function o(o){(o.originalEvent||o).preventDefault();var l=S.doc.documentElement.scrollTop||S.doc.body.scrollTop,u=S.doc.documentElement.scrollLeft||S.doc.body.scrollLeft;this._drag.x=o.clientX+u,this._drag.y=o.clientY+l,this._drag.id=o.identifier,!qe.length&&t.mousemove(Ue).mouseup(Xe),qe.push({el:this,move_scope:r,start_scope:a,end_scope:s}),i&&eve.on("raphael.drag.start."+this.id,i),e&&eve.on("raphael.drag.move."+this.id,e),n&&eve.on("raphael.drag.end."+this.id,n),eve("raphael.drag.start."+this.id,a||r||this,o.clientX+u,o.clientY+l,o)}return this._drag={},Qe.push({el:this,start:o}),this.mousedown(o),this},Ve.onDragOver=function(t){t?eve.on("raphael.drag.over."+this.id,t):eve.unbind("raphael.drag.over."+this.id)},Ve.undrag=function(){for(var e=Qe.length;e--;)Qe[e].el==this&&(this.unmousedown(Qe[e].start),Qe.splice(e,1),eve.unbind("raphael.drag.*."+this.id));!Qe.length&&t.unmousemove(Ue).unmouseup(Xe)},b.circle=function(e,i,n){var r=t._engine.circle(this,e||0,i||0,n||0);return this.__set__&&this.__set__.push(r),r},b.rect=function(e,i,n,r,a){var s=t._engine.rect(this,e||0,i||0,n||0,r||0,a||0);return this.__set__&&this.__set__.push(s),s},b.ellipse=function(e,i,n,r){var a=t._engine.ellipse(this,e||0,i||0,n||0,r||0);return this.__set__&&this.__set__.push(a),a},b.path=function(e){e&&!t.is(e,Y)&&!t.is(e[0],W)&&(e+=N);var i=t._engine.path(t.format[C](t,arguments),this);return this.__set__&&this.__set__.push(i),i},b.image=function(e,i,n,r,a){var s=t._engine.image(this,e||"about:blank",i||0,n||0,r||0,a||0);return this.__set__&&this.__set__.push(s),s},b.text=function(e,i,n){var r=t._engine.text(this,e||0,i||0,J(n));return this.__set__&&this.__set__.push(r),r},b.set=function(e){!t.is(e,"array")&&(e=Array.prototype.splice.call(arguments,0,arguments.length));var i=new ui(e);return this.__set__&&this.__set__.push(i),i},b.setStart=function(t){this.__set__=t||this.set()},b.setFinish=function(){var t=this.__set__;return delete this.__set__,t},b.setSize=function(e,i){return t._engine.setSize.call(this,e,i)},b.setViewBox=function(e,i,n,r,a){return t._engine.setViewBox.call(this,e,i,n,r,a)},b.top=b.bottom=null,b.raphael=t;var Ge=function(t){var e=t.getBoundingClientRect(),i=t.ownerDocument,n=i.body,r=i.documentElement,a=r.clientTop||n.clientTop||0,s=r.clientLeft||n.clientLeft||0,o=e.top+(S.win.pageYOffset||r.scrollTop||n.scrollTop)-a,l=e.left+(S.win.pageXOffset||r.scrollLeft||n.scrollLeft)-s;return{y:o,x:l}};b.getElementByPoint=function(t,e){var i=this,n=i.canvas,r=S.doc.elementFromPoint(t,e);if(S.win.opera&&"svg"==r.tagName){var a=Ge(n),s=n.createSVGRect();s.x=t-a.x,s.y=e-a.y,s.width=s.height=1;var o=n.getIntersectionList(s,null);o.length&&(r=o[o.length-1])}if(!r)return null;for(;r.parentNode&&r!=n.parentNode&&!r.raphael;)r=r.parentNode;return r==i.canvas.parentNode&&(r=n),r=r&&r.raphael?i.getById(r.raphaelid):null},b.getById=function(t){for(var e=this.bottom;e;){if(e.id==t)return e;e=e.next}return null},b.forEach=function(t,e){for(var i=this.bottom;i;){if(t.call(e,i)===!1)return this;i=i.next}return this},b.getElementsByPoint=function(t,e){var i=this.set();return this.forEach(function(n){n.isPointInside(t,e)&&i.push(n)}),i},Ve.isPointInside=function(e,i){var n=this.realPath=this.realPath||fe[this.type](this);return t.isPointInsidePath(n,e,i)},Ve.getBBox=function(t){if(this.removed)return{};var e=this._;return t?((e.dirty||!e.bboxwt)&&(this.realPath=fe[this.type](this),e.bboxwt=Ae(this.realPath),e.bboxwt.toString=p,e.dirty=0),e.bboxwt):((e.dirty||e.dirtyT||!e.bbox)&&((e.dirty||!this.realPath)&&(e.bboxwt=0,this.realPath=fe[this.type](this)),e.bbox=Ae(ge(this.realPath,this.matrix)),e.bbox.toString=p,e.dirty=e.dirtyT=0),e.bbox)},Ve.clone=function(){if(this.removed)return null;var t=this.paper[this.type]().attr(this.attr());return this.__set__&&this.__set__.push(t),t},Ve.glow=function(t){if("text"==this.type)return null;t=t||{};var e={width:(t.width||10)+(+this.attr("stroke-width")||1),fill:t.fill||!1,opacity:t.opacity||.5,offsetx:t.offsetx||0,offsety:t.offsety||0,color:t.color||"#000"},i=e.width/2,n=this.paper,r=n.set(),a=this.realPath||fe[this.type](this);a=this.matrix?ge(a,this.matrix):a;for(var s=1;i+1>s;s++)r.push(n.path(a).attr({stroke:e.color,fill:e.fill?e.color:"none","stroke-linejoin":"round","stroke-linecap":"round","stroke-width":+(e.width/i*s).toFixed(3),opacity:+(e.opacity/i).toFixed(3)}));return r.insertBefore(this).translate(e.offsetx,e.offsety)};var Ze=function(e,i,n,r,a,s,u,c,h){return null==h?o(e,i,n,r,a,s,u,c):t.findDotsAtSegment(e,i,n,r,a,s,u,c,l(e,i,n,r,a,s,u,c,h))},ti=function(e,i){return function(n,r,a){n=Ee(n);for(var s,o,l,u,c,h="",d={},p=0,f=0,g=n.length;g>f;f++){if(l=n[f],"M"==l[0])s=+l[1],o=+l[2];else{if(u=Ze(s,o,l[1],l[2],l[3],l[4],l[5],l[6]),p+u>r){if(i&&!d.start){if(c=Ze(s,o,l[1],l[2],l[3],l[4],l[5],l[6],r-p),h+=["C"+c.start.x,c.start.y,c.m.x,c.m.y,c.x,c.y],a)return h;d.start=h,h=["M"+c.x,c.y+"C"+c.n.x,c.n.y,c.end.x,c.end.y,l[5],l[6]].join(),p+=u,s=+l[5],o=+l[6];continue}if(!e&&!i)return c=Ze(s,o,l[1],l[2],l[3],l[4],l[5],l[6],r-p),{x:c.x,y:c.y,alpha:c.alpha}}p+=u,s=+l[5],o=+l[6]}h+=l.shift()+l}return d.end=h,c=e?p:i?d:t.findDotsAtSegment(s,o,l[0],l[1],l[2],l[3],l[4],l[5],1),c.alpha&&(c={x:c.x,y:c.y,alpha:c.alpha}),c}},ei=ti(1),ii=ti(),ni=ti(0,1);t.getTotalLength=ei,t.getPointAtLength=ii,t.getSubpath=function(t,e,i){if(1e-6>this.getTotalLength(t)-i)return ni(t,e).end;var n=ni(t,i,1);return e?ni(n,e).end:n},Ve.getTotalLength=function(){return"path"==this.type?this.node.getTotalLength?this.node.getTotalLength():ei(this.attrs.path):void 0},Ve.getPointAtLength=function(t){return"path"==this.type?ii(this.attrs.path,t):void 0},Ve.getSubpath=function(e,i){return"path"==this.type?t.getSubpath(this.attrs.path,e,i):void 0};var ri=t.easing_formulas={linear:function(t){return t},"<":function(t){return H(t,1.7)},">":function(t){return H(t,.48)},"<>":function(t){var e=.48-t/1.04,i=j.sqrt(.1734+e*e),n=i-e,r=H(R(n),1/3)*(0>n?-1:1),a=-i-e,s=H(R(a),1/3)*(0>a?-1:1),o=r+s+.5;return 3*(1-o)*o*o+o*o*o},backIn:function(t){var e=1.70158;return t*t*((e+1)*t-e)},backOut:function(t){t-=1;var e=1.70158;return t*t*((e+1)*t+e)+1},elastic:function(t){return t==!!t?t:H(2,-10*t)*j.sin((t-.075)*2*B/.3)+1},bounce:function(t){var e,i=7.5625,n=2.75;return 1/n>t?e=i*t*t:2/n>t?(t-=1.5/n,e=i*t*t+.75):2.5/n>t?(t-=2.25/n,e=i*t*t+.9375):(t-=2.625/n,e=i*t*t+.984375),e}};ri.easeIn=ri["ease-in"]=ri["<"],ri.easeOut=ri["ease-out"]=ri[">"],ri.easeInOut=ri["ease-in-out"]=ri["<>"],ri["back-in"]=ri.backIn,ri["back-out"]=ri.backOut;var ai=[],si=window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||function(t){setTimeout(t,16)},oi=function(){for(var e=+new Date,i=0;ai.length>i;i++){var n=ai[i];if(!n.el.removed&&!n.paused){var r,a,s=e-n.start,o=n.ms,l=n.easing,u=n.from,c=n.diff,h=n.to,d=(n.t,n.el),p={},f={};if(n.initstatus?(s=(n.initstatus*n.anim.top-n.prev)/(n.percent-n.prev)*o,n.status=n.initstatus,delete n.initstatus,n.stop&&ai.splice(i--,1)):n.status=(n.prev+(n.percent-n.prev)*(s/o))/n.anim.top,!(0>s))if(o>s){var g=l(s/o);for(var v in u)if(u[k](v)){switch(ee[v]){case z:r=+u[v]+g*o*c[v];break;case"colour":r="rgb("+[li(K(u[v].r+g*o*c[v].r)),li(K(u[v].g+g*o*c[v].g)),li(K(u[v].b+g*o*c[v].b))].join(",")+")";break;case"path":r=[];for(var y=0,b=u[v].length;b>y;y++){r[y]=[u[v][y][0]];for(var x=1,w=u[v][y].length;w>x;x++)r[y][x]=+u[v][y][x]+g*o*c[v][y][x];r[y]=r[y].join(P)}r=r.join(P);break;case"transform":if(c[v].real)for(r=[],y=0,b=u[v].length;b>y;y++)for(r[y]=[u[v][y][0]],x=1,w=u[v][y].length;w>x;x++)r[y][x]=u[v][y][x]+g*o*c[v][y][x];else{var _=function(t){return+u[v][t]+g*o*c[v][t]};r=[["m",_(0),_(1),_(2),_(3),_(4),_(5)]]}break;case"csv":if("clip-rect"==v)for(r=[],y=4;y--;)r[y]=+u[v][y]+g*o*c[v][y];break;default:var S=[][T](u[v]);for(r=[],y=d.paper.customAttributes[v].length;y--;)r[y]=+S[y]+g*o*c[v][y]}p[v]=r}d.attr(p),function(t,e,i){setTimeout(function(){eve("raphael.anim.frame."+t,e,i)})}(d.id,d,n.anim)}else{if(function(e,i,n){setTimeout(function(){eve("raphael.anim.frame."+i.id,i,n),eve("raphael.anim.finish."+i.id,i,n),t.is(e,"function")&&e.call(i)})}(n.callback,d,n.anim),d.attr(h),ai.splice(i--,1),n.repeat>1&&!n.next){for(a in h)h[k](a)&&(f[a]=n.totalOrigin[a]);n.el.attr(f),m(n.anim,n.el,n.anim.percents[0],null,n.totalOrigin,n.repeat-1)}n.next&&!n.stop&&m(n.anim,n.el,n.next,null,n.totalOrigin,n.repeat)}}}t.svg&&d&&d.paper&&d.paper.safari(),ai.length&&si(oi)},li=function(t){return t>255?255:0>t?0:t};Ve.animateWith=function(e,i,n,r,a,s){var o=this;if(o.removed)return s&&s.call(o),o;var l=n instanceof g?n:t.animation(n,r,a,s);m(l,o,l.percents[0],null,o.attr());for(var u=0,c=ai.length;c>u;u++)if(ai[u].anim==i&&ai[u].el==e){ai[c-1].start=ai[u].start;break}return o},Ve.onAnimation=function(t){return t?eve.on("raphael.anim.frame."+this.id,t):eve.unbind("raphael.anim.frame."+this.id),this},g.prototype.delay=function(t){var e=new g(this.anim,this.ms);return e.times=this.times,e.del=+t||0,e},g.prototype.repeat=function(t){var e=new g(this.anim,this.ms);return e.del=this.del,e.times=j.floor(F(t,0))||1,e},t.animation=function(e,i,n,r){if(e instanceof g)return e;(t.is(n,"function")||!n)&&(r=r||n||null,n=null),e=Object(e),i=+i||0;var a,s,o={};for(s in e)e[k](s)&&Q(s)!=s&&Q(s)+"%"!=s&&(a=!0,o[s]=e[s]);return a?(n&&(o.easing=n),r&&(o.callback=r),new g({100:o},i)):new g(e,i)},Ve.animate=function(e,i,n,r){var a=this;if(a.removed)return r&&r.call(a),a;var s=e instanceof g?e:t.animation(e,i,n,r);return m(s,a,s.percents[0],null,a.attr()),a},Ve.setTime=function(t,e){return t&&null!=e&&this.status(t,O(e,t.ms)/t.ms),this},Ve.status=function(t,e){var i,n,r=[],a=0;if(null!=e)return m(t,this,-1,O(e,1)),this;for(i=ai.length;i>a;a++)if(n=ai[a],n.el.id==this.id&&(!t||n.anim==t)){if(t)return n.status;r.push({anim:n.anim,status:n.status})}return t?0:r},Ve.pause=function(t){for(var e=0;ai.length>e;e++)ai[e].el.id!=this.id||t&&ai[e].anim!=t||eve("raphael.anim.pause."+this.id,this,ai[e].anim)!==!1&&(ai[e].paused=!0);return this},Ve.resume=function(t){for(var e=0;ai.length>e;e++)if(ai[e].el.id==this.id&&(!t||ai[e].anim==t)){var i=ai[e];eve("raphael.anim.resume."+this.id,this,i.anim)!==!1&&(delete i.paused,this.status(i.anim,i.status))}return this},Ve.stop=function(t){for(var e=0;ai.length>e;e++)ai[e].el.id!=this.id||t&&ai[e].anim!=t||eve("raphael.anim.stop."+this.id,this,ai[e].anim)!==!1&&ai.splice(e--,1);return this},eve.on("raphael.remove",v),eve.on("raphael.clear",v),Ve.toString=function(){return"Rapha\u00ebl\u2019s object"};var ui=function(t){if(this.items=[],this.length=0,this.type="set",t)for(var e=0,i=t.length;i>e;e++)!t[e]||t[e].constructor!=Ve.constructor&&t[e].constructor!=ui||(this[this.items.length]=this.items[this.items.length]=t[e],this.length++)},ci=ui.prototype;ci.push=function(){for(var t,e,i=0,n=arguments.length;n>i;i++)t=arguments[i],!t||t.constructor!=Ve.constructor&&t.constructor!=ui||(e=this.items.length,this[e]=this.items[e]=t,this.length++);return this},ci.pop=function(){return this.length&&delete this[this.length--],this.items.pop()},ci.forEach=function(t,e){for(var i=0,n=this.items.length;n>i;i++)if(t.call(e,this.items[i],i)===!1)return this;return this};for(var hi in Ve)Ve[k](hi)&&(ci[hi]=function(t){return function(){var e=arguments;return this.forEach(function(i){i[t][C](i,e)})}}(hi));ci.attr=function(e,i){if(e&&t.is(e,W)&&t.is(e[0],"object"))for(var n=0,r=e.length;r>n;n++)this.items[n].attr(e[n]);else for(var a=0,s=this.items.length;s>a;a++)this.items[a].attr(e,i);return this},ci.clear=function(){for(;this.length;)this.pop()},ci.splice=function(t,e){t=0>t?F(this.length+t,0):t,e=F(0,O(this.length-t,e));var i,n=[],r=[],a=[];for(i=2;arguments.length>i;i++)a.push(arguments[i]);for(i=0;e>i;i++)r.push(this[t+i]);for(;this.length-t>i;i++)n.push(this[t+i]);var s=a.length;for(i=0;s+n.length>i;i++)this.items[t+i]=this[t+i]=s>i?a[i]:n[i-s];for(i=this.items.length=this.length-=e-s;this[i];)delete this[i++];return new ui(r)},ci.exclude=function(t){for(var e=0,i=this.length;i>e;e++)if(this[e]==t)return this.splice(e,1),!0},ci.animate=function(e,i,n,r){(t.is(n,"function")||!n)&&(r=n||null);var a,s,o=this.items.length,l=o,u=this;if(!o)return this;r&&(s=function(){!--o&&r.call(u)}),n=t.is(n,Y)?n:s;var c=t.animation(e,i,n,s);for(a=this.items[--l].animate(c);l--;)this.items[l]&&!this.items[l].removed&&this.items[l].animateWith(a,c,c);return this},ci.insertAfter=function(t){for(var e=this.items.length;e--;)this.items[e].insertAfter(t);return this},ci.getBBox=function(){for(var t=[],e=[],i=[],n=[],r=this.items.length;r--;)if(!this.items[r].removed){var a=this.items[r].getBBox();t.push(a.x),e.push(a.y),i.push(a.x+a.width),n.push(a.y+a.height)}return t=O[C](0,t),e=O[C](0,e),i=F[C](0,i),n=F[C](0,n),{x:t,y:e,x2:i,y2:n,width:i-t,height:n-e}},ci.clone=function(t){t=new ui;for(var e=0,i=this.items.length;i>e;e++)t.push(this.items[e].clone());return t},ci.toString=function(){return"Rapha\u00ebl\u2018s set"},t.registerFont=function(t){if(!t.face)return t;this.fonts=this.fonts||{};var e={w:t.w,face:{},glyphs:{}},i=t.face["font-family"];for(var n in t.face)t.face[k](n)&&(e.face[n]=t.face[n]);if(this.fonts[i]?this.fonts[i].push(e):this.fonts[i]=[e],!t.svg){e.face["units-per-em"]=G(t.face["units-per-em"],10);for(var r in t.glyphs)if(t.glyphs[k](r)){var a=t.glyphs[r];if(e.glyphs[r]={w:a.w,k:{},d:a.d&&"M"+a.d.replace(/[mlcxtrv]/g,function(t){return{l:"L",c:"C",x:"z",t:"m",r:"l",v:"c"}[t]||"M"})+"z"},a.k)for(var s in a.k)a[k](s)&&(e.glyphs[r].k[s]=a.k[s])}}return t},b.getFont=function(e,i,n,r){if(r=r||"normal",n=n||"normal",i=+i||{normal:400,bold:700,lighter:300,bolder:800}[i]||400,t.fonts){var a=t.fonts[e];if(!a){var s=RegExp("(^|\\s)"+e.replace(/[^\w\d\s+!~.:_-]/g,N)+"(\\s|$)","i");for(var o in t.fonts)if(t.fonts[k](o)&&s.test(o)){a=t.fonts[o];break}}var l;if(a)for(var u=0,c=a.length;c>u&&(l=a[u],l.face["font-weight"]!=i||l.face["font-style"]!=n&&l.face["font-style"]||l.face["font-stretch"]!=r);u++);return l}},b.print=function(e,i,n,r,a,s,o){s=s||"middle",o=F(O(o||0,1),-1);var l,u=J(n)[$](N),c=0,h=0,d=N;if(t.is(r,n)&&(r=this.getFont(r)),r){l=(a||16)/r.face["units-per-em"];for(var p=r.face.bbox[$](x),f=+p[0],g=p[3]-p[1],m=0,v=+p[1]+("baseline"==s?g+ +r.face.descent:g/2),y=0,b=u.length;b>y;y++){if("\n"==u[y])c=0,_=0,h=0,m+=g;else{var w=h&&r.glyphs[u[y-1]]||{},_=r.glyphs[u[y]];c+=h?(w.w||r.w)+(w.k&&w.k[u[y]]||0)+r.w*o:0,h=1}_&&_.d&&(d+=t.transformPath(_.d,["t",c*l,m*l,"s",l,l,f,v,"t",(e-f)/l,(i-v)/l]))}}return this.path(d).attr({fill:"#000",stroke:"none"})},b.add=function(e){if(t.is(e,"array"))for(var i,n=this.set(),r=0,a=e.length;a>r;r++)i=e[r]||{},w[k](i.type)&&n.push(this[i.type]().attr(i));return n},t.format=function(e,i){var n=t.is(i,W)?[0][T](i):arguments;return e&&t.is(e,Y)&&n.length-1&&(e=e.replace(_,function(t,e){return null==n[++e]?N:n[e]})),e||N},t.fullfill=function(){var t=/\{([^\}]+)\}/g,e=/(?:(?:^|\.)(.+?)(?=\[|\.|$|\()|\[('|")(.+?)\2\])(\(\))?/g,i=function(t,i,n){var r=n;return i.replace(e,function(t,e,i,n,a){e=e||n,r&&(e in r&&(r=r[e]),"function"==typeof r&&a&&(r=r()))}),r=(null==r||r==n?t:r)+""};return function(e,n){return(e+"").replace(t,function(t,e){return i(t,e,n)})}}(),t.ninja=function(){return A.was?S.win.Raphael=A.is:delete Raphael,t},t.st=ci,function(e,i,n){function r(){/in/.test(e.readyState)?setTimeout(r,9):t.eve("raphael.DOMload")}null==e.readyState&&e.addEventListener&&(e.addEventListener(i,n=function(){e.removeEventListener(i,n,!1),e.readyState="complete"},!1),e.readyState="loading"),r()}(document,"DOMContentLoaded"),A.was?S.win.Raphael=t:Raphael=t,eve.on("raphael.DOMload",function(){y=!0})}(),window.Raphael&&window.Raphael.svg&&function(t){var e="hasOwnProperty",i=String,n=parseFloat,r=parseInt,a=Math,s=a.max,o=a.abs,l=a.pow,u=/[, ]+/,c=t.eve,h="",d=" ",p="http://www.w3.org/1999/xlink",f={block:"M5,0 0,2.5 5,5z",classic:"M5,0 0,2.5 5,5 3.5,3 3.5,2z",diamond:"M2.5,0 5,2.5 2.5,5 0,2.5z",open:"M6,1 1,3.5 6,6",oval:"M2.5,0A2.5,2.5,0,0,1,2.5,5 2.5,2.5,0,0,1,2.5,0z"},g={};t.toString=function(){return"Your browser supports SVG.\nYou are running Rapha\u00ebl "+this.version};var m=function(n,r){if(r){"string"==typeof n&&(n=m(n));for(var a in r)r[e](a)&&("xlink:"==a.substring(0,6)?n.setAttributeNS(p,a.substring(6),i(r[a])):n.setAttribute(a,i(r[a])))}else n=t._g.doc.createElementNS("http://www.w3.org/2000/svg",n),n.style&&(n.style.webkitTapHighlightColor="rgba(0,0,0,0)");return n},v=function(e,r){var u="linear",c=e.id+r,d=.5,p=.5,f=e.node,g=e.paper,v=f.style,y=t._g.doc.getElementById(c);if(!y){if(r=i(r).replace(t._radial_gradient,function(t,e,i){if(u="radial",e&&i){d=n(e),p=n(i);var r=2*(p>.5)-1;l(d-.5,2)+l(p-.5,2)>.25&&(p=a.sqrt(.25-l(d-.5,2))*r+.5)&&.5!=p&&(p=p.toFixed(5)-1e-5*r)}return h}),r=r.split(/\s*\-\s*/),"linear"==u){var b=r.shift();if(b=-n(b),isNaN(b))return null;var x=[0,0,a.cos(t.rad(b)),a.sin(t.rad(b))],w=1/(s(o(x[2]),o(x[3]))||1);x[2]*=w,x[3]*=w,0>x[2]&&(x[0]=-x[2],x[2]=0),0>x[3]&&(x[1]=-x[3],x[3]=0)}var _=t._parseDots(r);if(!_)return null;if(c=c.replace(/[\(\)\s,\xb0#]/g,"_"),e.gradient&&c!=e.gradient.id&&(g.defs.removeChild(e.gradient),delete e.gradient),!e.gradient){y=m(u+"Gradient",{id:c}),e.gradient=y,m(y,"radial"==u?{fx:d,fy:p}:{x1:x[0],y1:x[1],x2:x[2],y2:x[3],gradientTransform:e.matrix.invert()}),g.defs.appendChild(y);for(var k=0,S=_.length;S>k;k++)y.appendChild(m("stop",{offset:_[k].offset?_[k].offset:k?"100%":"0%","stop-color":_[k].color||"#fff"}))}}return m(f,{fill:"url(#"+c+")",opacity:1,"fill-opacity":1}),v.fill=h,v.opacity=1,v.fillOpacity=1,1},y=function(t){var e=t.getBBox(1);m(t.pattern,{patternTransform:t.matrix.invert()+" translate("+e.x+","+e.y+")"})},b=function(n,r,a){if("path"==n.type){for(var s,o,l,u,c,d=i(r).toLowerCase().split("-"),p=n.paper,v=a?"end":"start",y=n.node,b=n.attrs,x=b["stroke-width"],w=d.length,_="classic",k=3,S=3,A=5;w--;)switch(d[w]){case"block":case"classic":case"oval":case"diamond":case"open":case"none":_=d[w];break;case"wide":S=5;break;case"narrow":S=2;break;case"long":k=5;break;case"short":k=2}if("open"==_?(k+=2,S+=2,A+=2,l=1,u=a?4:1,c={fill:"none",stroke:b.stroke}):(u=l=k/2,c={fill:b.stroke,stroke:"none"}),n._.arrows?a?(n._.arrows.endPath&&g[n._.arrows.endPath]--,n._.arrows.endMarker&&g[n._.arrows.endMarker]--):(n._.arrows.startPath&&g[n._.arrows.startPath]--,n._.arrows.startMarker&&g[n._.arrows.startMarker]--):n._.arrows={},"none"!=_){var D="raphael-marker-"+_,C="raphael-marker-"+v+_+k+S;t._g.doc.getElementById(D)?g[D]++:(p.defs.appendChild(m(m("path"),{"stroke-linecap":"round",d:f[_],id:D})),g[D]=1);var T,M=t._g.doc.getElementById(C);M?(g[C]++,T=M.getElementsByTagName("use")[0]):(M=m(m("marker"),{id:C,markerHeight:S,markerWidth:k,orient:"auto",refX:u,refY:S/2}),T=m(m("use"),{"xlink:href":"#"+D,transform:(a?"rotate(180 "+k/2+" "+S/2+") ":h)+"scale("+k/A+","+S/A+")","stroke-width":(1/((k/A+S/A)/2)).toFixed(4)}),M.appendChild(T),p.defs.appendChild(M),g[C]=1),m(T,c);var N=l*("diamond"!=_&&"oval"!=_);a?(s=n._.arrows.startdx*x||0,o=t.getTotalLength(b.path)-N*x):(s=N*x,o=t.getTotalLength(b.path)-(n._.arrows.enddx*x||0)),c={},c["marker-"+v]="url(#"+C+")",(o||s)&&(c.d=Raphael.getSubpath(b.path,s,o)),m(y,c),n._.arrows[v+"Path"]=D,n._.arrows[v+"Marker"]=C,n._.arrows[v+"dx"]=N,n._.arrows[v+"Type"]=_,n._.arrows[v+"String"]=r}else a?(s=n._.arrows.startdx*x||0,o=t.getTotalLength(b.path)-s):(s=0,o=t.getTotalLength(b.path)-(n._.arrows.enddx*x||0)),n._.arrows[v+"Path"]&&m(y,{d:Raphael.getSubpath(b.path,s,o)}),delete n._.arrows[v+"Path"],delete n._.arrows[v+"Marker"],delete n._.arrows[v+"dx"],delete n._.arrows[v+"Type"],delete n._.arrows[v+"String"];for(c in g)if(g[e](c)&&!g[c]){var P=t._g.doc.getElementById(c);P&&P.parentNode.removeChild(P)}}},x={"":[0],none:[0],"-":[3,1],".":[1,1],"-.":[3,1,1,1],"-..":[3,1,1,1,1,1],". ":[1,3],"- ":[4,3],"--":[8,3],"- .":[4,3,1,3],"--.":[8,3,1,3],"--..":[8,3,1,3,1,3]},w=function(t,e,n){if(e=x[i(e).toLowerCase()]){for(var r=t.attrs["stroke-width"]||"1",a={round:r,square:r,butt:0}[t.attrs["stroke-linecap"]||n["stroke-linecap"]]||0,s=[],o=e.length;o--;)s[o]=e[o]*r+(o%2?1:-1)*a;m(t.node,{"stroke-dasharray":s.join(",")})}},_=function(n,a){var l=n.node,c=n.attrs,d=l.style.visibility;l.style.visibility="hidden";for(var f in a)if(a[e](f)){if(!t._availableAttrs[e](f))continue;var g=a[f];switch(c[f]=g,f){case"blur":n.blur(g);break;case"href":case"title":case"target":var x=l.parentNode;if("a"!=x.tagName.toLowerCase()){var _=m("a");x.insertBefore(_,l),_.appendChild(l),x=_}"target"==f?x.setAttributeNS(p,"show","blank"==g?"new":g):x.setAttributeNS(p,f,g);break;case"cursor":l.style.cursor=g;break;case"transform":n.transform(g);break;case"arrow-start":b(n,g);break;case"arrow-end":b(n,g,1);break;case"clip-rect":var k=i(g).split(u);if(4==k.length){n.clip&&n.clip.parentNode.parentNode.removeChild(n.clip.parentNode);var A=m("clipPath"),D=m("rect");A.id=t.createUUID(),m(D,{x:k[0],y:k[1],width:k[2],height:k[3]}),A.appendChild(D),n.paper.defs.appendChild(A),m(l,{"clip-path":"url(#"+A.id+")"}),n.clip=D}if(!g){var C=l.getAttribute("clip-path");if(C){var T=t._g.doc.getElementById(C.replace(/(^url\(#|\)$)/g,h));T&&T.parentNode.removeChild(T),m(l,{"clip-path":h}),delete n.clip}}break;case"path":"path"==n.type&&(m(l,{d:g?c.path=t._pathToAbsolute(g):"M0,0"}),n._.dirty=1,n._.arrows&&("startString"in n._.arrows&&b(n,n._.arrows.startString),"endString"in n._.arrows&&b(n,n._.arrows.endString,1)));break;case"width":if(l.setAttribute(f,g),n._.dirty=1,!c.fx)break;f="x",g=c.x;case"x":c.fx&&(g=-c.x-(c.width||0));case"rx":if("rx"==f&&"rect"==n.type)break;case"cx":l.setAttribute(f,g),n.pattern&&y(n),n._.dirty=1;break;case"height":if(l.setAttribute(f,g),n._.dirty=1,!c.fy)break;f="y",g=c.y;case"y":c.fy&&(g=-c.y-(c.height||0));case"ry":if("ry"==f&&"rect"==n.type)break;case"cy":l.setAttribute(f,g),n.pattern&&y(n),n._.dirty=1;break;case"r":"rect"==n.type?m(l,{rx:g,ry:g}):l.setAttribute(f,g),n._.dirty=1;break;case"src":"image"==n.type&&l.setAttributeNS(p,"href",g);break;case"stroke-width":(1!=n._.sx||1!=n._.sy)&&(g/=s(o(n._.sx),o(n._.sy))||1),n.paper._vbSize&&(g*=n.paper._vbSize),l.setAttribute(f,g),c["stroke-dasharray"]&&w(n,c["stroke-dasharray"],a),n._.arrows&&("startString"in n._.arrows&&b(n,n._.arrows.startString),"endString"in n._.arrows&&b(n,n._.arrows.endString,1));break;case"stroke-dasharray":w(n,g,a);break;case"fill":var M=i(g).match(t._ISURL);if(M){A=m("pattern");var N=m("image");A.id=t.createUUID(),m(A,{x:0,y:0,patternUnits:"userSpaceOnUse",height:1,width:1}),m(N,{x:0,y:0,"xlink:href":M[1]}),A.appendChild(N),function(e){t._preload(M[1],function(){var t=this.offsetWidth,i=this.offsetHeight;m(e,{width:t,height:i}),m(N,{width:t,height:i}),n.paper.safari()})}(A),n.paper.defs.appendChild(A),m(l,{fill:"url(#"+A.id+")"}),n.pattern=A,n.pattern&&y(n);break}var P=t.getRGB(g);if(P.error){if(("circle"==n.type||"ellipse"==n.type||"r"!=i(g).charAt())&&v(n,g)){if("opacity"in c||"fill-opacity"in c){var J=t._g.doc.getElementById(l.getAttribute("fill").replace(/^url\(#|\)$/g,h));if(J){var $=J.getElementsByTagName("stop");m($[$.length-1],{"stop-opacity":("opacity"in c?c.opacity:1)*("fill-opacity"in c?c["fill-opacity"]:1)})}}c.gradient=g,c.fill="none";break}}else delete a.gradient,delete c.gradient,!t.is(c.opacity,"undefined")&&t.is(a.opacity,"undefined")&&m(l,{opacity:c.opacity}),!t.is(c["fill-opacity"],"undefined")&&t.is(a["fill-opacity"],"undefined")&&m(l,{"fill-opacity":c["fill-opacity"]});P[e]("opacity")&&m(l,{"fill-opacity":P.opacity>1?P.opacity/100:P.opacity});case"stroke":P=t.getRGB(g),l.setAttribute(f,P.hex),"stroke"==f&&P[e]("opacity")&&m(l,{"stroke-opacity":P.opacity>1?P.opacity/100:P.opacity}),"stroke"==f&&n._.arrows&&("startString"in n._.arrows&&b(n,n._.arrows.startString),"endString"in n._.arrows&&b(n,n._.arrows.endString,1));break;case"gradient":("circle"==n.type||"ellipse"==n.type||"r"!=i(g).charAt())&&v(n,g);break;case"opacity":c.gradient&&!c[e]("stroke-opacity")&&m(l,{"stroke-opacity":g>1?g/100:g});case"fill-opacity":if(c.gradient){J=t._g.doc.getElementById(l.getAttribute("fill").replace(/^url\(#|\)$/g,h)),J&&($=J.getElementsByTagName("stop"),m($[$.length-1],{"stop-opacity":g}));break}default:"font-size"==f&&(g=r(g,10)+"px");var E=f.replace(/(\-.)/g,function(t){return t.substring(1).toUpperCase()});l.style[E]=g,n._.dirty=1,l.setAttribute(f,g)}}S(n,a),l.style.visibility=d},k=1.2,S=function(n,a){if("text"==n.type&&(a[e]("text")||a[e]("font")||a[e]("font-size")||a[e]("x")||a[e]("y"))){var s=n.attrs,o=n.node,l=o.firstChild?r(t._g.doc.defaultView.getComputedStyle(o.firstChild,h).getPropertyValue("font-size"),10):10;if(a[e]("text")){for(s.text=a.text;o.firstChild;)o.removeChild(o.firstChild);for(var u,c=i(a.text).split("\n"),d=[],p=0,f=c.length;f>p;p++)u=m("tspan"),p&&m(u,{dy:l*k,x:s.x}),u.appendChild(t._g.doc.createTextNode(c[p])),o.appendChild(u),d[p]=u}else for(d=o.getElementsByTagName("tspan"),p=0,f=d.length;f>p;p++)p?m(d[p],{dy:l*k,x:s.x}):m(d[0],{dy:0});m(o,{x:s.x,y:s.y}),n._.dirty=1;var g=n._getBBox(),v=s.y-(g.y+g.height/2);v&&t.is(v,"finite")&&m(d[0],{dy:v})}},A=function(e,i){this[0]=this.node=e,e.raphael=!0,this.id=t._oid++,e.raphaelid=this.id,this.matrix=t.matrix(),this.realPath=null,this.paper=i,this.attrs=this.attrs||{},this._={transform:[],sx:1,sy:1,deg:0,dx:0,dy:0,dirty:1},!i.bottom&&(i.bottom=this),this.prev=i.top,i.top&&(i.top.next=this),i.top=this,this.next=null},D=t.el;A.prototype=D,D.constructor=A,t._engine.path=function(t,e){var i=m("path");e.canvas&&e.canvas.appendChild(i);var n=new A(i,e);return n.type="path",_(n,{fill:"none",stroke:"#000",path:t}),n},D.rotate=function(t,e,r){if(this.removed)return this;if(t=i(t).split(u),t.length-1&&(e=n(t[1]),r=n(t[2])),t=n(t[0]),null==r&&(e=r),null==e||null==r){var a=this.getBBox(1);e=a.x+a.width/2,r=a.y+a.height/2}return this.transform(this._.transform.concat([["r",t,e,r]])),this},D.scale=function(t,e,r,a){if(this.removed)return this;if(t=i(t).split(u),t.length-1&&(e=n(t[1]),r=n(t[2]),a=n(t[3])),t=n(t[0]),null==e&&(e=t),null==a&&(r=a),null==r||null==a)var s=this.getBBox(1);return r=null==r?s.x+s.width/2:r,a=null==a?s.y+s.height/2:a,this.transform(this._.transform.concat([["s",t,e,r,a]])),this},D.translate=function(t,e){return this.removed?this:(t=i(t).split(u),t.length-1&&(e=n(t[1])),t=n(t[0])||0,e=+e||0,this.transform(this._.transform.concat([["t",t,e]])),this)},D.transform=function(i){var n=this._;if(null==i)return n.transform;if(t._extractTransform(this,i),this.clip&&m(this.clip,{transform:this.matrix.invert()}),this.pattern&&y(this),this.node&&m(this.node,{transform:this.matrix}),1!=n.sx||1!=n.sy){var r=this.attrs[e]("stroke-width")?this.attrs["stroke-width"]:1;this.attr({"stroke-width":r})}return this},D.hide=function(){return!this.removed&&this.paper.safari(this.node.style.display="none"),this},D.show=function(){return!this.removed&&this.paper.safari(this.node.style.display=""),this},D.remove=function(){if(!this.removed&&this.node.parentNode){var e=this.paper;e.__set__&&e.__set__.exclude(this),c.unbind("raphael.*.*."+this.id),this.gradient&&e.defs.removeChild(this.gradient),t._tear(this,e),"a"==this.node.parentNode.tagName.toLowerCase()?this.node.parentNode.parentNode.removeChild(this.node.parentNode):this.node.parentNode.removeChild(this.node);for(var i in this)this[i]="function"==typeof this[i]?t._removedFactory(i):null;this.removed=!0}},D._getBBox=function(){if("none"==this.node.style.display){this.show();var t=!0}var e={};try{e=this.node.getBBox()}catch(i){}finally{e=e||{}}return t&&this.hide(),e},D.attr=function(i,n){if(this.removed)return this;if(null==i){var r={};for(var a in this.attrs)this.attrs[e](a)&&(r[a]=this.attrs[a]);return r.gradient&&"none"==r.fill&&(r.fill=r.gradient)&&delete r.gradient,r.transform=this._.transform,r}if(null==n&&t.is(i,"string")){if("fill"==i&&"none"==this.attrs.fill&&this.attrs.gradient)return this.attrs.gradient;if("transform"==i)return this._.transform;for(var s=i.split(u),o={},l=0,h=s.length;h>l;l++)i=s[l],o[i]=i in this.attrs?this.attrs[i]:t.is(this.paper.customAttributes[i],"function")?this.paper.customAttributes[i].def:t._availableAttrs[i];return h-1?o:o[s[0]]}if(null==n&&t.is(i,"array")){for(o={},l=0,h=i.length;h>l;l++)o[i[l]]=this.attr(i[l]);return o}if(null!=n){var d={};d[i]=n}else null!=i&&t.is(i,"object")&&(d=i);for(var p in d)c("raphael.attr."+p+"."+this.id,this,d[p]);for(p in this.paper.customAttributes)if(this.paper.customAttributes[e](p)&&d[e](p)&&t.is(this.paper.customAttributes[p],"function")){var f=this.paper.customAttributes[p].apply(this,[].concat(d[p]));this.attrs[p]=d[p];for(var g in f)f[e](g)&&(d[g]=f[g])}return _(this,d),this},D.toFront=function(){if(this.removed)return this;"a"==this.node.parentNode.tagName.toLowerCase()?this.node.parentNode.parentNode.appendChild(this.node.parentNode):this.node.parentNode.appendChild(this.node);var e=this.paper;return e.top!=this&&t._tofront(this,e),this},D.toBack=function(){if(this.removed)return this;var e=this.node.parentNode;return"a"==e.tagName.toLowerCase()?e.parentNode.insertBefore(this.node.parentNode,this.node.parentNode.parentNode.firstChild):e.firstChild!=this.node&&e.insertBefore(this.node,this.node.parentNode.firstChild),t._toback(this,this.paper),this.paper,this},D.insertAfter=function(e){if(this.removed)return this;var i=e.node||e[e.length-1].node;return i.nextSibling?i.parentNode.insertBefore(this.node,i.nextSibling):i.parentNode.appendChild(this.node),t._insertafter(this,e,this.paper),this},D.insertBefore=function(e){if(this.removed)return this;var i=e.node||e[0].node;return i.parentNode.insertBefore(this.node,i),t._insertbefore(this,e,this.paper),this},D.blur=function(e){var i=this;if(0!==+e){var n=m("filter"),r=m("feGaussianBlur");i.attrs.blur=e,n.id=t.createUUID(),m(r,{stdDeviation:+e||1.5}),n.appendChild(r),i.paper.defs.appendChild(n),i._blur=n,m(i.node,{filter:"url(#"+n.id+")"})}else i._blur&&(i._blur.parentNode.removeChild(i._blur),delete i._blur,delete i.attrs.blur),i.node.removeAttribute("filter")},t._engine.circle=function(t,e,i,n){var r=m("circle");t.canvas&&t.canvas.appendChild(r); var a=new A(r,t);return a.attrs={cx:e,cy:i,r:n,fill:"none",stroke:"#000"},a.type="circle",m(r,a.attrs),a},t._engine.rect=function(t,e,i,n,r,a){var s=m("rect");t.canvas&&t.canvas.appendChild(s);var o=new A(s,t);return o.attrs={x:e,y:i,width:n,height:r,r:a||0,rx:a||0,ry:a||0,fill:"none",stroke:"#000"},o.type="rect",m(s,o.attrs),o},t._engine.ellipse=function(t,e,i,n,r){var a=m("ellipse");t.canvas&&t.canvas.appendChild(a);var s=new A(a,t);return s.attrs={cx:e,cy:i,rx:n,ry:r,fill:"none",stroke:"#000"},s.type="ellipse",m(a,s.attrs),s},t._engine.image=function(t,e,i,n,r,a){var s=m("image");m(s,{x:i,y:n,width:r,height:a,preserveAspectRatio:"none"}),s.setAttributeNS(p,"href",e),t.canvas&&t.canvas.appendChild(s);var o=new A(s,t);return o.attrs={x:i,y:n,width:r,height:a,src:e},o.type="image",o},t._engine.text=function(e,i,n,r){var a=m("text");e.canvas&&e.canvas.appendChild(a);var s=new A(a,e);return s.attrs={x:i,y:n,"text-anchor":"middle",text:r,font:t._availableAttrs.font,stroke:"none",fill:"#000"},s.type="text",_(s,s.attrs),s},t._engine.setSize=function(t,e){return this.width=t||this.width,this.height=e||this.height,this.canvas.setAttribute("width",this.width),this.canvas.setAttribute("height",this.height),this._viewBox&&this.setViewBox.apply(this,this._viewBox),this},t._engine.create=function(){var e=t._getContainer.apply(0,arguments),i=e&&e.container,n=e.x,r=e.y,a=e.width,s=e.height;if(!i)throw Error("SVG container not found.");var o,l=m("svg"),u="overflow:hidden;";return n=n||0,r=r||0,a=a||512,s=s||342,m(l,{height:s,version:1.1,width:a,xmlns:"http://www.w3.org/2000/svg"}),1==i?(l.style.cssText=u+"position:absolute;left:"+n+"px;top:"+r+"px",t._g.doc.body.appendChild(l),o=1):(l.style.cssText=u+"position:relative",i.firstChild?i.insertBefore(l,i.firstChild):i.appendChild(l)),i=new t._Paper,i.width=a,i.height=s,i.canvas=l,i.clear(),i._left=i._top=0,o&&(i.renderfix=function(){}),i.renderfix(),i},t._engine.setViewBox=function(t,e,i,n,r){c("raphael.setViewBox",this,this._viewBox,[t,e,i,n,r]);var a,o,l=s(i/this.width,n/this.height),u=this.top,h=r?"meet":"xMinYMin";for(null==t?(this._vbSize&&(l=1),delete this._vbSize,a="0 0 "+this.width+d+this.height):(this._vbSize=l,a=t+d+e+d+i+d+n),m(this.canvas,{viewBox:a,preserveAspectRatio:h});l&&u;)o="stroke-width"in u.attrs?u.attrs["stroke-width"]:1,u.attr({"stroke-width":o}),u._.dirty=1,u._.dirtyT=1,u=u.prev;return this._viewBox=[t,e,i,n,!!r],this},t.prototype.renderfix=function(){var t,e=this.canvas,i=e.style;try{t=e.getScreenCTM()||e.createSVGMatrix()}catch(n){t=e.createSVGMatrix()}var r=-t.e%1,a=-t.f%1;(r||a)&&(r&&(this._left=(this._left+r)%1,i.left=this._left+"px"),a&&(this._top=(this._top+a)%1,i.top=this._top+"px"))},t.prototype.clear=function(){t.eve("raphael.clear",this);for(var e=this.canvas;e.firstChild;)e.removeChild(e.firstChild);this.bottom=this.top=null,(this.desc=m("desc")).appendChild(t._g.doc.createTextNode("Created with Rapha\u00ebl "+t.version)),e.appendChild(this.desc),e.appendChild(this.defs=m("defs"))},t.prototype.remove=function(){c("raphael.remove",this),this.canvas.parentNode&&this.canvas.parentNode.removeChild(this.canvas);for(var e in this)this[e]="function"==typeof this[e]?t._removedFactory(e):null};var C=t.st;for(var T in D)D[e](T)&&!C[e](T)&&(C[T]=function(t){return function(){var e=arguments;return this.forEach(function(i){i[t].apply(i,e)})}}(T))}(window.Raphael),window.Raphael&&window.Raphael.vml&&function(t){var e="hasOwnProperty",i=String,n=parseFloat,r=Math,a=r.round,s=r.max,o=r.min,l=r.abs,u="fill",c=/[, ]+/,h=t.eve,d=" progid:DXImageTransform.Microsoft",p=" ",f="",g={M:"m",L:"l",C:"c",Z:"x",m:"t",l:"r",c:"v",z:"x"},m=/([clmz]),?([^clmz]*)/gi,v=/ progid:\S+Blur\([^\)]+\)/g,y=/-?[^,\s-]+/g,b="position:absolute;left:0;top:0;width:1px;height:1px",x=21600,w={path:1,rect:1,image:1},_={circle:1,ellipse:1},k=function(e){var n=/[ahqstv]/gi,r=t._pathToAbsolute;if(i(e).match(n)&&(r=t._path2curve),n=/[clmz]/g,r==t._pathToAbsolute&&!i(e).match(n)){var s=i(e).replace(m,function(t,e,i){var n=[],r="m"==e.toLowerCase(),s=g[e];return i.replace(y,function(t){r&&2==n.length&&(s+=n+g["m"==e?"l":"L"],n=[]),n.push(a(t*x))}),s+n});return s}var o,l,u=r(e);s=[];for(var c=0,h=u.length;h>c;c++){o=u[c],l=u[c][0].toLowerCase(),"z"==l&&(l="x");for(var d=1,v=o.length;v>d;d++)l+=a(o[d]*x)+(d!=v-1?",":f);s.push(l)}return s.join(p)},S=function(e,i,n){var r=t.matrix();return r.rotate(-e,.5,.5),{dx:r.x(i,n),dy:r.y(i,n)}},A=function(t,e,i,n,r,a){var s=t._,o=t.matrix,c=s.fillpos,h=t.node,d=h.style,f=1,g="",m=x/e,v=x/i;if(d.visibility="hidden",e&&i){if(h.coordsize=l(m)+p+l(v),d.rotation=a*(0>e*i?-1:1),a){var y=S(a,n,r);n=y.dx,r=y.dy}if(0>e&&(g+="x"),0>i&&(g+=" y")&&(f=-1),d.flip=g,h.coordorigin=n*-m+p+r*-v,c||s.fillsize){var b=h.getElementsByTagName(u);b=b&&b[0],h.removeChild(b),c&&(y=S(a,o.x(c[0],c[1]),o.y(c[0],c[1])),b.position=y.dx*f+p+y.dy*f),s.fillsize&&(b.size=s.fillsize[0]*l(e)+p+s.fillsize[1]*l(i)),h.appendChild(b)}d.visibility="visible"}};t.toString=function(){return"Your browser doesn\u2019t support SVG. Falling down to VML.\nYou are running Rapha\u00ebl "+this.version};var D=function(t,e,n){for(var r=i(e).toLowerCase().split("-"),a=n?"end":"start",s=r.length,o="classic",l="medium",u="medium";s--;)switch(r[s]){case"block":case"classic":case"oval":case"diamond":case"open":case"none":o=r[s];break;case"wide":case"narrow":u=r[s];break;case"long":case"short":l=r[s]}var c=t.node.getElementsByTagName("stroke")[0];c[a+"arrow"]=o,c[a+"arrowlength"]=l,c[a+"arrowwidth"]=u},C=function(r,l){r.attrs=r.attrs||{};var h=r.node,d=r.attrs,g=h.style,m=w[r.type]&&(l.x!=d.x||l.y!=d.y||l.width!=d.width||l.height!=d.height||l.cx!=d.cx||l.cy!=d.cy||l.rx!=d.rx||l.ry!=d.ry||l.r!=d.r),v=_[r.type]&&(d.cx!=l.cx||d.cy!=l.cy||d.r!=l.r||d.rx!=l.rx||d.ry!=l.ry),y=r;for(var b in l)l[e](b)&&(d[b]=l[b]);if(m&&(d.path=t._getPath[r.type](r),r._.dirty=1),l.href&&(h.href=l.href),l.title&&(h.title=l.title),l.target&&(h.target=l.target),l.cursor&&(g.cursor=l.cursor),"blur"in l&&r.blur(l.blur),(l.path&&"path"==r.type||m)&&(h.path=k(~i(d.path).toLowerCase().indexOf("r")?t._pathToAbsolute(d.path):d.path),"image"==r.type&&(r._.fillpos=[d.x,d.y],r._.fillsize=[d.width,d.height],A(r,1,1,0,0,0))),"transform"in l&&r.transform(l.transform),v){var S=+d.cx,C=+d.cy,M=+d.rx||+d.r||0,N=+d.ry||+d.r||0;h.path=t.format("ar{0},{1},{2},{3},{4},{1},{4},{1}x",a((S-M)*x),a((C-N)*x),a((S+M)*x),a((C+N)*x),a(S*x))}if("clip-rect"in l){var J=i(l["clip-rect"]).split(c);if(4==J.length){J[2]=+J[2]+ +J[0],J[3]=+J[3]+ +J[1];var $=h.clipRect||t._g.doc.createElement("div"),E=$.style;E.clip=t.format("rect({1}px {2}px {3}px {0}px)",J),h.clipRect||(E.position="absolute",E.top=0,E.left=0,E.width=r.paper.width+"px",E.height=r.paper.height+"px",h.parentNode.insertBefore($,h),$.appendChild(h),h.clipRect=$)}l["clip-rect"]||h.clipRect&&(h.clipRect.style.clip="auto")}if(r.textpath){var I=r.textpath.style;l.font&&(I.font=l.font),l["font-family"]&&(I.fontFamily='"'+l["font-family"].split(",")[0].replace(/^['"]+|['"]+$/g,f)+'"'),l["font-size"]&&(I.fontSize=l["font-size"]),l["font-weight"]&&(I.fontWeight=l["font-weight"]),l["font-style"]&&(I.fontStyle=l["font-style"])}if("arrow-start"in l&&D(y,l["arrow-start"]),"arrow-end"in l&&D(y,l["arrow-end"],1),null!=l.opacity||null!=l["stroke-width"]||null!=l.fill||null!=l.src||null!=l.stroke||null!=l["stroke-width"]||null!=l["stroke-opacity"]||null!=l["fill-opacity"]||null!=l["stroke-dasharray"]||null!=l["stroke-miterlimit"]||null!=l["stroke-linejoin"]||null!=l["stroke-linecap"]){var L=h.getElementsByTagName(u),j=!1;if(L=L&&L[0],!L&&(j=L=P(u)),"image"==r.type&&l.src&&(L.src=l.src),l.fill&&(L.on=!0),(null==L.on||"none"==l.fill||null===l.fill)&&(L.on=!1),L.on&&l.fill){var F=i(l.fill).match(t._ISURL);if(F){L.parentNode==h&&h.removeChild(L),L.rotate=!0,L.src=F[1],L.type="tile";var O=r.getBBox(1);L.position=O.x+p+O.y,r._.fillpos=[O.x,O.y],t._preload(F[1],function(){r._.fillsize=[this.offsetWidth,this.offsetHeight]})}else L.color=t.getRGB(l.fill).hex,L.src=f,L.type="solid",t.getRGB(l.fill).error&&(y.type in{circle:1,ellipse:1}||"r"!=i(l.fill).charAt())&&T(y,l.fill,L)&&(d.fill="none",d.gradient=l.fill,L.rotate=!1)}if("fill-opacity"in l||"opacity"in l){var R=((+d["fill-opacity"]+1||2)-1)*((+d.opacity+1||2)-1)*((+t.getRGB(l.fill).o+1||2)-1);R=o(s(R,0),1),L.opacity=R,L.src&&(L.color="none")}h.appendChild(L);var H=h.getElementsByTagName("stroke")&&h.getElementsByTagName("stroke")[0],B=!1;!H&&(B=H=P("stroke")),(l.stroke&&"none"!=l.stroke||l["stroke-width"]||null!=l["stroke-opacity"]||l["stroke-dasharray"]||l["stroke-miterlimit"]||l["stroke-linejoin"]||l["stroke-linecap"])&&(H.on=!0),("none"==l.stroke||null===l.stroke||null==H.on||0==l.stroke||0==l["stroke-width"])&&(H.on=!1);var z=t.getRGB(l.stroke);H.on&&l.stroke&&(H.color=z.hex),R=((+d["stroke-opacity"]+1||2)-1)*((+d.opacity+1||2)-1)*((+z.o+1||2)-1);var Y=.75*(n(l["stroke-width"])||1);if(R=o(s(R,0),1),null==l["stroke-width"]&&(Y=d["stroke-width"]),l["stroke-width"]&&(H.weight=Y),Y&&1>Y&&(R*=Y)&&(H.weight=1),H.opacity=R,l["stroke-linejoin"]&&(H.joinstyle=l["stroke-linejoin"]||"miter"),H.miterlimit=l["stroke-miterlimit"]||8,l["stroke-linecap"]&&(H.endcap="butt"==l["stroke-linecap"]?"flat":"square"==l["stroke-linecap"]?"square":"round"),l["stroke-dasharray"]){var W={"-":"shortdash",".":"shortdot","-.":"shortdashdot","-..":"shortdashdotdot",". ":"dot","- ":"dash","--":"longdash","- .":"dashdot","--.":"longdashdot","--..":"longdashdotdot"};H.dashstyle=W[e](l["stroke-dasharray"])?W[l["stroke-dasharray"]]:f}B&&h.appendChild(H)}if("text"==y.type){y.paper.canvas.style.display=f;var q=y.paper.span,U=100,X=d.font&&d.font.match(/\d+(?:\.\d*)?(?=px)/);g=q.style,d.font&&(g.font=d.font),d["font-family"]&&(g.fontFamily=d["font-family"]),d["font-weight"]&&(g.fontWeight=d["font-weight"]),d["font-style"]&&(g.fontStyle=d["font-style"]),X=n(d["font-size"]||X&&X[0])||10,g.fontSize=X*U+"px",y.textpath.string&&(q.innerHTML=i(y.textpath.string).replace(/</g,"&#60;").replace(/&/g,"&#38;").replace(/\n/g,"<br>"));var V=q.getBoundingClientRect();y.W=d.w=(V.right-V.left)/U,y.H=d.h=(V.bottom-V.top)/U,y.X=d.x,y.Y=d.y+y.H/2,("x"in l||"y"in l)&&(y.path.v=t.format("m{0},{1}l{2},{1}",a(d.x*x),a(d.y*x),a(d.x*x)+1));for(var K=["x","y","text","font","font-family","font-weight","font-style","font-size"],Q=0,G=K.length;G>Q;Q++)if(K[Q]in l){y._.dirty=1;break}switch(d["text-anchor"]){case"start":y.textpath.style["v-text-align"]="left",y.bbx=y.W/2;break;case"end":y.textpath.style["v-text-align"]="right",y.bbx=-y.W/2;break;default:y.textpath.style["v-text-align"]="center",y.bbx=0}y.textpath.style["v-text-kern"]=!0}},T=function(e,a,s){e.attrs=e.attrs||{};var o=(e.attrs,Math.pow),l="linear",u=".5 .5";if(e.attrs.gradient=a,a=i(a).replace(t._radial_gradient,function(t,e,i){return l="radial",e&&i&&(e=n(e),i=n(i),o(e-.5,2)+o(i-.5,2)>.25&&(i=r.sqrt(.25-o(e-.5,2))*(2*(i>.5)-1)+.5),u=e+p+i),f}),a=a.split(/\s*\-\s*/),"linear"==l){var c=a.shift();if(c=-n(c),isNaN(c))return null}var h=t._parseDots(a);if(!h)return null;if(e=e.shape||e.node,h.length){e.removeChild(s),s.on=!0,s.method="none",s.color=h[0].color,s.color2=h[h.length-1].color;for(var d=[],g=0,m=h.length;m>g;g++)h[g].offset&&d.push(h[g].offset+p+h[g].color);s.colors=d.length?d.join():"0% "+s.color,"radial"==l?(s.type="gradientTitle",s.focus="100%",s.focussize="0 0",s.focusposition=u,s.angle=0):(s.type="gradient",s.angle=(270-c)%360),e.appendChild(s)}return 1},M=function(e,i){this[0]=this.node=e,e.raphael=!0,this.id=t._oid++,e.raphaelid=this.id,this.X=0,this.Y=0,this.attrs={},this.paper=i,this.matrix=t.matrix(),this._={transform:[],sx:1,sy:1,dx:0,dy:0,deg:0,dirty:1,dirtyT:1},!i.bottom&&(i.bottom=this),this.prev=i.top,i.top&&(i.top.next=this),i.top=this,this.next=null},N=t.el;M.prototype=N,N.constructor=M,N.transform=function(e){if(null==e)return this._.transform;var n,r=this.paper._viewBoxShift,a=r?"s"+[r.scale,r.scale]+"-1-1t"+[r.dx,r.dy]:f;r&&(n=e=i(e).replace(/\.{3}|\u2026/g,this._.transform||f)),t._extractTransform(this,a+e);var s,o=this.matrix.clone(),l=this.skew,u=this.node,c=~i(this.attrs.fill).indexOf("-"),h=!i(this.attrs.fill).indexOf("url(");if(o.translate(-.5,-.5),h||c||"image"==this.type)if(l.matrix="1 0 0 1",l.offset="0 0",s=o.split(),c&&s.noRotation||!s.isSimple){u.style.filter=o.toFilter();var d=this.getBBox(),g=this.getBBox(1),m=d.x-g.x,v=d.y-g.y;u.coordorigin=m*-x+p+v*-x,A(this,1,1,m,v,0)}else u.style.filter=f,A(this,s.scalex,s.scaley,s.dx,s.dy,s.rotate);else u.style.filter=f,l.matrix=i(o),l.offset=o.offset();return n&&(this._.transform=n),this},N.rotate=function(t,e,r){if(this.removed)return this;if(null!=t){if(t=i(t).split(c),t.length-1&&(e=n(t[1]),r=n(t[2])),t=n(t[0]),null==r&&(e=r),null==e||null==r){var a=this.getBBox(1);e=a.x+a.width/2,r=a.y+a.height/2}return this._.dirtyT=1,this.transform(this._.transform.concat([["r",t,e,r]])),this}},N.translate=function(t,e){return this.removed?this:(t=i(t).split(c),t.length-1&&(e=n(t[1])),t=n(t[0])||0,e=+e||0,this._.bbox&&(this._.bbox.x+=t,this._.bbox.y+=e),this.transform(this._.transform.concat([["t",t,e]])),this)},N.scale=function(t,e,r,a){if(this.removed)return this;if(t=i(t).split(c),t.length-1&&(e=n(t[1]),r=n(t[2]),a=n(t[3]),isNaN(r)&&(r=null),isNaN(a)&&(a=null)),t=n(t[0]),null==e&&(e=t),null==a&&(r=a),null==r||null==a)var s=this.getBBox(1);return r=null==r?s.x+s.width/2:r,a=null==a?s.y+s.height/2:a,this.transform(this._.transform.concat([["s",t,e,r,a]])),this._.dirtyT=1,this},N.hide=function(){return!this.removed&&(this.node.style.display="none"),this},N.show=function(){return!this.removed&&(this.node.style.display=f),this},N._getBBox=function(){return this.removed?{}:{x:this.X+(this.bbx||0)-this.W/2,y:this.Y-this.H,width:this.W,height:this.H}},N.remove=function(){if(!this.removed&&this.node.parentNode){this.paper.__set__&&this.paper.__set__.exclude(this),t.eve.unbind("raphael.*.*."+this.id),t._tear(this,this.paper),this.node.parentNode.removeChild(this.node),this.shape&&this.shape.parentNode.removeChild(this.shape);for(var e in this)this[e]="function"==typeof this[e]?t._removedFactory(e):null;this.removed=!0}},N.attr=function(i,n){if(this.removed)return this;if(null==i){var r={};for(var a in this.attrs)this.attrs[e](a)&&(r[a]=this.attrs[a]);return r.gradient&&"none"==r.fill&&(r.fill=r.gradient)&&delete r.gradient,r.transform=this._.transform,r}if(null==n&&t.is(i,"string")){if(i==u&&"none"==this.attrs.fill&&this.attrs.gradient)return this.attrs.gradient;for(var s=i.split(c),o={},l=0,d=s.length;d>l;l++)i=s[l],o[i]=i in this.attrs?this.attrs[i]:t.is(this.paper.customAttributes[i],"function")?this.paper.customAttributes[i].def:t._availableAttrs[i];return d-1?o:o[s[0]]}if(this.attrs&&null==n&&t.is(i,"array")){for(o={},l=0,d=i.length;d>l;l++)o[i[l]]=this.attr(i[l]);return o}var p;null!=n&&(p={},p[i]=n),null==n&&t.is(i,"object")&&(p=i);for(var f in p)h("raphael.attr."+f+"."+this.id,this,p[f]);if(p){for(f in this.paper.customAttributes)if(this.paper.customAttributes[e](f)&&p[e](f)&&t.is(this.paper.customAttributes[f],"function")){var g=this.paper.customAttributes[f].apply(this,[].concat(p[f]));this.attrs[f]=p[f];for(var m in g)g[e](m)&&(p[m]=g[m])}p.text&&"text"==this.type&&(this.textpath.string=p.text),C(this,p)}return this},N.toFront=function(){return!this.removed&&this.node.parentNode.appendChild(this.node),this.paper&&this.paper.top!=this&&t._tofront(this,this.paper),this},N.toBack=function(){return this.removed?this:(this.node.parentNode.firstChild!=this.node&&(this.node.parentNode.insertBefore(this.node,this.node.parentNode.firstChild),t._toback(this,this.paper)),this)},N.insertAfter=function(e){return this.removed?this:(e.constructor==t.st.constructor&&(e=e[e.length-1]),e.node.nextSibling?e.node.parentNode.insertBefore(this.node,e.node.nextSibling):e.node.parentNode.appendChild(this.node),t._insertafter(this,e,this.paper),this)},N.insertBefore=function(e){return this.removed?this:(e.constructor==t.st.constructor&&(e=e[0]),e.node.parentNode.insertBefore(this.node,e.node),t._insertbefore(this,e,this.paper),this)},N.blur=function(e){var i=this.node.runtimeStyle,n=i.filter;n=n.replace(v,f),0!==+e?(this.attrs.blur=e,i.filter=n+p+d+".Blur(pixelradius="+(+e||1.5)+")",i.margin=t.format("-{0}px 0 0 -{0}px",a(+e||1.5))):(i.filter=n,i.margin=0,delete this.attrs.blur)},t._engine.path=function(t,e){var i=P("shape");i.style.cssText=b,i.coordsize=x+p+x,i.coordorigin=e.coordorigin;var n=new M(i,e),r={fill:"none",stroke:"#000"};t&&(r.path=t),n.type="path",n.path=[],n.Path=f,C(n,r),e.canvas.appendChild(i);var a=P("skew");return a.on=!0,i.appendChild(a),n.skew=a,n.transform(f),n},t._engine.rect=function(e,i,n,r,a,s){var o=t._rectPath(i,n,r,a,s),l=e.path(o),u=l.attrs;return l.X=u.x=i,l.Y=u.y=n,l.W=u.width=r,l.H=u.height=a,u.r=s,u.path=o,l.type="rect",l},t._engine.ellipse=function(t,e,i,n,r){var a=t.path();return a.attrs,a.X=e-n,a.Y=i-r,a.W=2*n,a.H=2*r,a.type="ellipse",C(a,{cx:e,cy:i,rx:n,ry:r}),a},t._engine.circle=function(t,e,i,n){var r=t.path();return r.attrs,r.X=e-n,r.Y=i-n,r.W=r.H=2*n,r.type="circle",C(r,{cx:e,cy:i,r:n}),r},t._engine.image=function(e,i,n,r,a,s){var o=t._rectPath(n,r,a,s),l=e.path(o).attr({stroke:"none"}),c=l.attrs,h=l.node,d=h.getElementsByTagName(u)[0];return c.src=i,l.X=c.x=n,l.Y=c.y=r,l.W=c.width=a,l.H=c.height=s,c.path=o,l.type="image",d.parentNode==h&&h.removeChild(d),d.rotate=!0,d.src=i,d.type="tile",l._.fillpos=[n,r],l._.fillsize=[a,s],h.appendChild(d),A(l,1,1,0,0,0),l},t._engine.text=function(e,n,r,s){var o=P("shape"),l=P("path"),u=P("textpath");n=n||0,r=r||0,s=s||"",l.v=t.format("m{0},{1}l{2},{1}",a(n*x),a(r*x),a(n*x)+1),l.textpathok=!0,u.string=i(s),u.on=!0,o.style.cssText=b,o.coordsize=x+p+x,o.coordorigin="0 0";var c=new M(o,e),h={fill:"#000",stroke:"none",font:t._availableAttrs.font,text:s};c.shape=o,c.path=l,c.textpath=u,c.type="text",c.attrs.text=i(s),c.attrs.x=n,c.attrs.y=r,c.attrs.w=1,c.attrs.h=1,C(c,h),o.appendChild(u),o.appendChild(l),e.canvas.appendChild(o);var d=P("skew");return d.on=!0,o.appendChild(d),c.skew=d,c.transform(f),c},t._engine.setSize=function(e,i){var n=this.canvas.style;return this.width=e,this.height=i,e==+e&&(e+="px"),i==+i&&(i+="px"),n.width=e,n.height=i,n.clip="rect(0 "+e+" "+i+" 0)",this._viewBox&&t._engine.setViewBox.apply(this,this._viewBox),this},t._engine.setViewBox=function(e,i,n,r,a){t.eve("raphael.setViewBox",this,this._viewBox,[e,i,n,r,a]);var o,l,u=this.width,c=this.height,h=1/s(n/u,r/c);return a&&(o=c/r,l=u/n,u>n*o&&(e-=(u-n*o)/2/o),c>r*l&&(i-=(c-r*l)/2/l)),this._viewBox=[e,i,n,r,!!a],this._viewBoxShift={dx:-e,dy:-i,scale:h},this.forEach(function(t){t.transform("...")}),this};var P;t._engine.initWin=function(t){var e=t.document;e.createStyleSheet().addRule(".rvml","behavior:url(#default#VML)");try{!e.namespaces.rvml&&e.namespaces.add("rvml","urn:schemas-microsoft-com:vml"),P=function(t){return e.createElement("<rvml:"+t+' class="rvml">')}}catch(i){P=function(t){return e.createElement("<"+t+' xmlns="urn:schemas-microsoft.com:vml" class="rvml">')}}},t._engine.initWin(t._g.win),t._engine.create=function(){var e=t._getContainer.apply(0,arguments),i=e.container,n=e.height,r=e.width,a=e.x,s=e.y;if(!i)throw Error("VML container not found.");var o=new t._Paper,l=o.canvas=t._g.doc.createElement("div"),u=l.style;return a=a||0,s=s||0,r=r||512,n=n||342,o.width=r,o.height=n,r==+r&&(r+="px"),n==+n&&(n+="px"),o.coordsize=1e3*x+p+1e3*x,o.coordorigin="0 0",o.span=t._g.doc.createElement("span"),o.span.style.cssText="position:absolute;left:-9999em;top:-9999em;padding:0;margin:0;line-height:1;",l.appendChild(o.span),u.cssText=t.format("top:0;left:0;width:{0};height:{1};display:inline-block;position:relative;clip:rect(0 {0} {1} 0);overflow:hidden",r,n),1==i?(t._g.doc.body.appendChild(l),u.left=a+"px",u.top=s+"px",u.position="absolute"):i.firstChild?i.insertBefore(l,i.firstChild):i.appendChild(l),o.renderfix=function(){},o},t.prototype.clear=function(){t.eve("raphael.clear",this),this.canvas.innerHTML=f,this.span=t._g.doc.createElement("span"),this.span.style.cssText="position:absolute;left:-9999em;top:-9999em;padding:0;margin:0;line-height:1;display:inline;",this.canvas.appendChild(this.span),this.bottom=this.top=null},t.prototype.remove=function(){t.eve("raphael.remove",this),this.canvas.parentNode.removeChild(this.canvas);for(var e in this)this[e]="function"==typeof this[e]?t._removedFactory(e):null;return!0};var J=t.st;for(var $ in N)N[e]($)&&!J[e]($)&&(J[$]=function(t){return function(){var e=arguments;return this.forEach(function(i){i[t].apply(i,e)})}}($))}(window.Raphael),function(t,e){function i(e,i){var r=e.nodeName.toLowerCase();if("area"===r){var a,s=e.parentNode,o=s.name;return e.href&&o&&"map"===s.nodeName.toLowerCase()?(a=t("img[usemap=#"+o+"]")[0],!!a&&n(a)):!1}return(/input|select|textarea|button|object/.test(r)?!e.disabled:"a"==r?e.href||i:i)&&n(e)}function n(e){return!t(e).parents().andSelf().filter(function(){return"hidden"===t.curCSS(this,"visibility")||t.expr.filters.hidden(this)}).length}t.ui=t.ui||{},t.ui.version||(t.extend(t.ui,{version:"1.8.24",keyCode:{ALT:18,BACKSPACE:8,CAPS_LOCK:20,COMMA:188,COMMAND:91,COMMAND_LEFT:91,COMMAND_RIGHT:93,CONTROL:17,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,INSERT:45,LEFT:37,MENU:93,NUMPAD_ADD:107,NUMPAD_DECIMAL:110,NUMPAD_DIVIDE:111,NUMPAD_ENTER:108,NUMPAD_MULTIPLY:106,NUMPAD_SUBTRACT:109,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SHIFT:16,SPACE:32,TAB:9,UP:38,WINDOWS:91}}),t.fn.extend({propAttr:t.fn.prop||t.fn.attr,_focus:t.fn.focus,focus:function(e,i){return"number"==typeof e?this.each(function(){var n=this;setTimeout(function(){t(n).focus(),i&&i.call(n)},e)}):this._focus.apply(this,arguments)},scrollParent:function(){var e;return e=t.browser.msie&&/(static|relative)/.test(this.css("position"))||/absolute/.test(this.css("position"))?this.parents().filter(function(){return/(relative|absolute|fixed)/.test(t.curCSS(this,"position",1))&&/(auto|scroll)/.test(t.curCSS(this,"overflow",1)+t.curCSS(this,"overflow-y",1)+t.curCSS(this,"overflow-x",1))}).eq(0):this.parents().filter(function(){return/(auto|scroll)/.test(t.curCSS(this,"overflow",1)+t.curCSS(this,"overflow-y",1)+t.curCSS(this,"overflow-x",1))}).eq(0),/fixed/.test(this.css("position"))||!e.length?t(document):e},zIndex:function(i){if(i!==e)return this.css("zIndex",i);if(this.length)for(var n,r,a=t(this[0]);a.length&&a[0]!==document;){if(n=a.css("position"),("absolute"===n||"relative"===n||"fixed"===n)&&(r=parseInt(a.css("zIndex"),10),!isNaN(r)&&0!==r))return r;a=a.parent()}return 0},disableSelection:function(){return this.bind((t.support.selectstart?"selectstart":"mousedown")+".ui-disableSelection",function(t){t.preventDefault()})},enableSelection:function(){return this.unbind(".ui-disableSelection")}}),t("<a>").outerWidth(1).jquery||t.each(["Width","Height"],function(i,n){function r(e,i,n,r){return t.each(a,function(){i-=parseFloat(t.curCSS(e,"padding"+this,!0))||0,n&&(i-=parseFloat(t.curCSS(e,"border"+this+"Width",!0))||0),r&&(i-=parseFloat(t.curCSS(e,"margin"+this,!0))||0)}),i}var a="Width"===n?["Left","Right"]:["Top","Bottom"],s=n.toLowerCase(),o={innerWidth:t.fn.innerWidth,innerHeight:t.fn.innerHeight,outerWidth:t.fn.outerWidth,outerHeight:t.fn.outerHeight};t.fn["inner"+n]=function(i){return i===e?o["inner"+n].call(this):this.each(function(){t(this).css(s,r(this,i)+"px")})},t.fn["outer"+n]=function(e,i){return"number"!=typeof e?o["outer"+n].call(this,e):this.each(function(){t(this).css(s,r(this,e,!0,i)+"px")})}}),t.extend(t.expr[":"],{data:t.expr.createPseudo?t.expr.createPseudo(function(e){return function(i){return!!t.data(i,e)}}):function(e,i,n){return!!t.data(e,n[3])},focusable:function(e){return i(e,!isNaN(t.attr(e,"tabindex")))},tabbable:function(e){var n=t.attr(e,"tabindex"),r=isNaN(n);return(r||n>=0)&&i(e,!r)}}),t(function(){var e=document.body,i=e.appendChild(i=document.createElement("div"));i.offsetHeight,t.extend(i.style,{minHeight:"100px",height:"auto",padding:0,borderWidth:0}),t.support.minHeight=100===i.offsetHeight,t.support.selectstart="onselectstart"in i,e.removeChild(i).style.display="none"}),t.curCSS||(t.curCSS=t.css),t.extend(t.ui,{plugin:{add:function(e,i,n){var r=t.ui[e].prototype;for(var a in n)r.plugins[a]=r.plugins[a]||[],r.plugins[a].push([i,n[a]])},call:function(t,e,i){var n=t.plugins[e];if(n&&t.element[0].parentNode)for(var r=0;n.length>r;r++)t.options[n[r][0]]&&n[r][1].apply(t.element,i)}},contains:function(t,e){return document.compareDocumentPosition?16&t.compareDocumentPosition(e):t!==e&&t.contains(e)},hasScroll:function(e,i){if("hidden"===t(e).css("overflow"))return!1;var n=i&&"left"===i?"scrollLeft":"scrollTop",r=!1;return e[n]>0?!0:(e[n]=1,r=e[n]>0,e[n]=0,r)},isOverAxis:function(t,e,i){return t>e&&e+i>t},isOver:function(e,i,n,r,a,s){return t.ui.isOverAxis(e,n,a)&&t.ui.isOverAxis(i,r,s)}}))}(jQuery),function(t,e){if(t.cleanData){var i=t.cleanData;t.cleanData=function(e){for(var n,r=0;null!=(n=e[r]);r++)try{t(n).triggerHandler("remove")}catch(a){}i(e)}}else{var n=t.fn.remove;t.fn.remove=function(e,i){return this.each(function(){return i||(!e||t.filter(e,[this]).length)&&t("*",this).add([this]).each(function(){try{t(this).triggerHandler("remove")}catch(e){}}),n.call(t(this),e,i)})}}t.widget=function(e,i,n){var r,a=e.split(".")[0];e=e.split(".")[1],r=a+"-"+e,n||(n=i,i=t.Widget),t.expr[":"][r]=function(i){return!!t.data(i,e)},t[a]=t[a]||{},t[a][e]=function(t,e){arguments.length&&this._createWidget(t,e)};var s=new i;s.options=t.extend(!0,{},s.options),t[a][e].prototype=t.extend(!0,s,{namespace:a,widgetName:e,widgetEventPrefix:t[a][e].prototype.widgetEventPrefix||e,widgetBaseClass:r},n),t.widget.bridge(e,t[a][e])},t.widget.bridge=function(i,n){t.fn[i]=function(r){var a="string"==typeof r,s=Array.prototype.slice.call(arguments,1),o=this;return r=!a&&s.length?t.extend.apply(null,[!0,r].concat(s)):r,a&&"_"===r.charAt(0)?o:(a?this.each(function(){var n=t.data(this,i),a=n&&t.isFunction(n[r])?n[r].apply(n,s):n;return a!==n&&a!==e?(o=a,!1):e}):this.each(function(){var e=t.data(this,i);e?e.option(r||{})._init():t.data(this,i,new n(r,this))}),o)}},t.Widget=function(t,e){arguments.length&&this._createWidget(t,e)},t.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",options:{disabled:!1},_createWidget:function(e,i){t.data(i,this.widgetName,this),this.element=t(i),this.options=t.extend(!0,{},this.options,this._getCreateOptions(),e);var n=this;this.element.bind("remove."+this.widgetName,function(){n.destroy()}),this._create(),this._trigger("create"),this._init()},_getCreateOptions:function(){return t.metadata&&t.metadata.get(this.element[0])[this.widgetName]},_create:function(){},_init:function(){},destroy:function(){this.element.unbind("."+this.widgetName).removeData(this.widgetName),this.widget().unbind("."+this.widgetName).removeAttr("aria-disabled").removeClass(this.widgetBaseClass+"-disabled "+"ui-state-disabled")},widget:function(){return this.element},option:function(i,n){var r=i;if(0===arguments.length)return t.extend({},this.options);if("string"==typeof i){if(n===e)return this.options[i];r={},r[i]=n}return this._setOptions(r),this},_setOptions:function(e){var i=this;return t.each(e,function(t,e){i._setOption(t,e)}),this},_setOption:function(t,e){return this.options[t]=e,"disabled"===t&&this.widget()[e?"addClass":"removeClass"](this.widgetBaseClass+"-disabled"+" "+"ui-state-disabled").attr("aria-disabled",e),this},enable:function(){return this._setOption("disabled",!1)},disable:function(){return this._setOption("disabled",!0)},_trigger:function(e,i,n){var r,a,s=this.options[e];if(n=n||{},i=t.Event(i),i.type=(e===this.widgetEventPrefix?e:this.widgetEventPrefix+e).toLowerCase(),i.target=this.element[0],a=i.originalEvent)for(r in a)r in i||(i[r]=a[r]);return this.element.trigger(i,n),!(t.isFunction(s)&&s.call(this.element[0],i,n)===!1||i.isDefaultPrevented())}}}(jQuery),function(t){var e=!1;t(document).mouseup(function(){e=!1}),t.widget("ui.mouse",{options:{cancel:":input,option",distance:1,delay:0},_mouseInit:function(){var e=this;this.element.bind("mousedown."+this.widgetName,function(t){return e._mouseDown(t)}).bind("click."+this.widgetName,function(i){return!0===t.data(i.target,e.widgetName+".preventClickEvent")?(t.removeData(i.target,e.widgetName+".preventClickEvent"),i.stopImmediatePropagation(),!1):undefined}),this.started=!1},_mouseDestroy:function(){this.element.unbind("."+this.widgetName),this._mouseMoveDelegate&&t(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate)},_mouseDown:function(i){if(!e){this._mouseStarted&&this._mouseUp(i),this._mouseDownEvent=i;var n=this,r=1==i.which,a="string"==typeof this.options.cancel&&i.target.nodeName?t(i.target).closest(this.options.cancel).length:!1;return r&&!a&&this._mouseCapture(i)?(this.mouseDelayMet=!this.options.delay,this.mouseDelayMet||(this._mouseDelayTimer=setTimeout(function(){n.mouseDelayMet=!0},this.options.delay)),this._mouseDistanceMet(i)&&this._mouseDelayMet(i)&&(this._mouseStarted=this._mouseStart(i)!==!1,!this._mouseStarted)?(i.preventDefault(),!0):(!0===t.data(i.target,this.widgetName+".preventClickEvent")&&t.removeData(i.target,this.widgetName+".preventClickEvent"),this._mouseMoveDelegate=function(t){return n._mouseMove(t)},this._mouseUpDelegate=function(t){return n._mouseUp(t)},t(document).bind("mousemove."+this.widgetName,this._mouseMoveDelegate).bind("mouseup."+this.widgetName,this._mouseUpDelegate),i.preventDefault(),e=!0,!0)):!0}},_mouseMove:function(e){return!t.browser.msie||document.documentMode>=9||e.button?this._mouseStarted?(this._mouseDrag(e),e.preventDefault()):(this._mouseDistanceMet(e)&&this._mouseDelayMet(e)&&(this._mouseStarted=this._mouseStart(this._mouseDownEvent,e)!==!1,this._mouseStarted?this._mouseDrag(e):this._mouseUp(e)),!this._mouseStarted):this._mouseUp(e)},_mouseUp:function(e){return t(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate),this._mouseStarted&&(this._mouseStarted=!1,e.target==this._mouseDownEvent.target&&t.data(e.target,this.widgetName+".preventClickEvent",!0),this._mouseStop(e)),!1},_mouseDistanceMet:function(t){return Math.max(Math.abs(this._mouseDownEvent.pageX-t.pageX),Math.abs(this._mouseDownEvent.pageY-t.pageY))>=this.options.distance},_mouseDelayMet:function(){return this.mouseDelayMet},_mouseStart:function(){},_mouseDrag:function(){},_mouseStop:function(){},_mouseCapture:function(){return!0}})}(jQuery),function(t){t.widget("ui.draggable",t.ui.mouse,{widgetEventPrefix:"drag",options:{addClasses:!0,appendTo:"parent",axis:!1,connectToSortable:!1,containment:!1,cursor:"auto",cursorAt:!1,grid:!1,handle:!1,helper:"original",iframeFix:!1,opacity:!1,refreshPositions:!1,revert:!1,revertDuration:500,scope:"default",scroll:!0,scrollSensitivity:20,scrollSpeed:20,snap:!1,snapMode:"both",snapTolerance:20,stack:!1,zIndex:!1},_create:function(){"original"!=this.options.helper||/^(?:r|a|f)/.test(this.element.css("position"))||(this.element[0].style.position="relative"),this.options.addClasses&&this.element.addClass("ui-draggable"),this.options.disabled&&this.element.addClass("ui-draggable-disabled"),this._mouseInit()},destroy:function(){return this.element.data("draggable")?(this.element.removeData("draggable").unbind(".draggable").removeClass("ui-draggable ui-draggable-dragging ui-draggable-disabled"),this._mouseDestroy(),this):undefined},_mouseCapture:function(e){var i=this.options;return this.helper||i.disabled||t(e.target).is(".ui-resizable-handle")?!1:(this.handle=this._getHandle(e),this.handle?(i.iframeFix&&t(i.iframeFix===!0?"iframe":i.iframeFix).each(function(){t('<div class="ui-draggable-iframeFix" style="background: #fff;"></div>').css({width:this.offsetWidth+"px",height:this.offsetHeight+"px",position:"absolute",opacity:"0.001",zIndex:1e3}).css(t(this).offset()).appendTo("body")}),!0):!1)},_mouseStart:function(e){var i=this.options;return this.helper=this._createHelper(e),this.helper.addClass("ui-draggable-dragging"),this._cacheHelperProportions(),t.ui.ddmanager&&(t.ui.ddmanager.current=this),this._cacheMargins(),this.cssPosition=this.helper.css("position"),this.scrollParent=this.helper.scrollParent(),this.offset=this.positionAbs=this.element.offset(),this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left},t.extend(this.offset,{click:{left:e.pageX-this.offset.left,top:e.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()}),this.originalPosition=this.position=this._generatePosition(e),this.originalPageX=e.pageX,this.originalPageY=e.pageY,i.cursorAt&&this._adjustOffsetFromHelper(i.cursorAt),i.containment&&this._setContainment(),this._trigger("start",e)===!1?(this._clear(),!1):(this._cacheHelperProportions(),t.ui.ddmanager&&!i.dropBehaviour&&t.ui.ddmanager.prepareOffsets(this,e),this._mouseDrag(e,!0),t.ui.ddmanager&&t.ui.ddmanager.dragStart(this,e),!0) },_mouseDrag:function(e,i){if(this.position=this._generatePosition(e),this.positionAbs=this._convertPositionTo("absolute"),!i){var n=this._uiHash();if(this._trigger("drag",e,n)===!1)return this._mouseUp({}),!1;this.position=n.position}return this.options.axis&&"y"==this.options.axis||(this.helper[0].style.left=this.position.left+"px"),this.options.axis&&"x"==this.options.axis||(this.helper[0].style.top=this.position.top+"px"),t.ui.ddmanager&&t.ui.ddmanager.drag(this,e),!1},_mouseStop:function(e){var i=!1;t.ui.ddmanager&&!this.options.dropBehaviour&&(i=t.ui.ddmanager.drop(this,e)),this.dropped&&(i=this.dropped,this.dropped=!1);for(var n=this.element[0],r=!1;n&&(n=n.parentNode);)n==document&&(r=!0);if(!r&&"original"===this.options.helper)return!1;if("invalid"==this.options.revert&&!i||"valid"==this.options.revert&&i||this.options.revert===!0||t.isFunction(this.options.revert)&&this.options.revert.call(this.element,i)){var a=this;t(this.helper).animate(this.originalPosition,parseInt(this.options.revertDuration,10),function(){a._trigger("stop",e)!==!1&&a._clear()})}else this._trigger("stop",e)!==!1&&this._clear();return!1},_mouseUp:function(e){return t("div.ui-draggable-iframeFix").each(function(){this.parentNode.removeChild(this)}),t.ui.ddmanager&&t.ui.ddmanager.dragStop(this,e),t.ui.mouse.prototype._mouseUp.call(this,e)},cancel:function(){return this.helper.is(".ui-draggable-dragging")?this._mouseUp({}):this._clear(),this},_getHandle:function(e){var i=this.options.handle&&t(this.options.handle,this.element).length?!1:!0;return t(this.options.handle,this.element).find("*").andSelf().each(function(){this==e.target&&(i=!0)}),i},_createHelper:function(e){var i=this.options,n=t.isFunction(i.helper)?t(i.helper.apply(this.element[0],[e])):"clone"==i.helper?this.element.clone().removeAttr("id"):this.element;return n.parents("body").length||n.appendTo("parent"==i.appendTo?this.element[0].parentNode:i.appendTo),n[0]==this.element[0]||/(fixed|absolute)/.test(n.css("position"))||n.css("position","absolute"),n},_adjustOffsetFromHelper:function(e){"string"==typeof e&&(e=e.split(" ")),t.isArray(e)&&(e={left:+e[0],top:+e[1]||0}),"left"in e&&(this.offset.click.left=e.left+this.margins.left),"right"in e&&(this.offset.click.left=this.helperProportions.width-e.right+this.margins.left),"top"in e&&(this.offset.click.top=e.top+this.margins.top),"bottom"in e&&(this.offset.click.top=this.helperProportions.height-e.bottom+this.margins.top)},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var e=this.offsetParent.offset();return"absolute"==this.cssPosition&&this.scrollParent[0]!=document&&t.ui.contains(this.scrollParent[0],this.offsetParent[0])&&(e.left+=this.scrollParent.scrollLeft(),e.top+=this.scrollParent.scrollTop()),(this.offsetParent[0]==document.body||this.offsetParent[0].tagName&&"html"==this.offsetParent[0].tagName.toLowerCase()&&t.browser.msie)&&(e={top:0,left:0}),{top:e.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:e.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if("relative"==this.cssPosition){var t=this.element.position();return{top:t.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:t.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}return{top:0,left:0}},_cacheMargins:function(){this.margins={left:parseInt(this.element.css("marginLeft"),10)||0,top:parseInt(this.element.css("marginTop"),10)||0,right:parseInt(this.element.css("marginRight"),10)||0,bottom:parseInt(this.element.css("marginBottom"),10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var e=this.options;if("parent"==e.containment&&(e.containment=this.helper[0].parentNode),("document"==e.containment||"window"==e.containment)&&(this.containment=["document"==e.containment?0:t(window).scrollLeft()-this.offset.relative.left-this.offset.parent.left,"document"==e.containment?0:t(window).scrollTop()-this.offset.relative.top-this.offset.parent.top,("document"==e.containment?0:t(window).scrollLeft())+t("document"==e.containment?document:window).width()-this.helperProportions.width-this.margins.left,("document"==e.containment?0:t(window).scrollTop())+(t("document"==e.containment?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top]),/^(document|window|parent)$/.test(e.containment)||e.containment.constructor==Array)e.containment.constructor==Array&&(this.containment=e.containment);else{var i=t(e.containment),n=i[0];if(!n)return;i.offset();var r="hidden"!=t(n).css("overflow");this.containment=[(parseInt(t(n).css("borderLeftWidth"),10)||0)+(parseInt(t(n).css("paddingLeft"),10)||0),(parseInt(t(n).css("borderTopWidth"),10)||0)+(parseInt(t(n).css("paddingTop"),10)||0),(r?Math.max(n.scrollWidth,n.offsetWidth):n.offsetWidth)-(parseInt(t(n).css("borderLeftWidth"),10)||0)-(parseInt(t(n).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left-this.margins.right,(r?Math.max(n.scrollHeight,n.offsetHeight):n.offsetHeight)-(parseInt(t(n).css("borderTopWidth"),10)||0)-(parseInt(t(n).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top-this.margins.bottom],this.relative_container=i}},_convertPositionTo:function(e,i){i||(i=this.position);var n="absolute"==e?1:-1,r=(this.options,"absolute"!=this.cssPosition||this.scrollParent[0]!=document&&t.ui.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent),a=/(html|body)/i.test(r[0].tagName);return{top:i.top+this.offset.relative.top*n+this.offset.parent.top*n-(t.browser.safari&&526>t.browser.version&&"fixed"==this.cssPosition?0:("fixed"==this.cssPosition?-this.scrollParent.scrollTop():a?0:r.scrollTop())*n),left:i.left+this.offset.relative.left*n+this.offset.parent.left*n-(t.browser.safari&&526>t.browser.version&&"fixed"==this.cssPosition?0:("fixed"==this.cssPosition?-this.scrollParent.scrollLeft():a?0:r.scrollLeft())*n)}},_generatePosition:function(e){var i=this.options,n="absolute"!=this.cssPosition||this.scrollParent[0]!=document&&t.ui.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,r=/(html|body)/i.test(n[0].tagName),a=e.pageX,s=e.pageY;if(this.originalPosition){var o;if(this.containment){if(this.relative_container){var l=this.relative_container.offset();o=[this.containment[0]+l.left,this.containment[1]+l.top,this.containment[2]+l.left,this.containment[3]+l.top]}else o=this.containment;e.pageX-this.offset.click.left<o[0]&&(a=o[0]+this.offset.click.left),e.pageY-this.offset.click.top<o[1]&&(s=o[1]+this.offset.click.top),e.pageX-this.offset.click.left>o[2]&&(a=o[2]+this.offset.click.left),e.pageY-this.offset.click.top>o[3]&&(s=o[3]+this.offset.click.top)}if(i.grid){var u=i.grid[1]?this.originalPageY+Math.round((s-this.originalPageY)/i.grid[1])*i.grid[1]:this.originalPageY;s=o?u-this.offset.click.top<o[1]||u-this.offset.click.top>o[3]?u-this.offset.click.top<o[1]?u+i.grid[1]:u-i.grid[1]:u:u;var c=i.grid[0]?this.originalPageX+Math.round((a-this.originalPageX)/i.grid[0])*i.grid[0]:this.originalPageX;a=o?c-this.offset.click.left<o[0]||c-this.offset.click.left>o[2]?c-this.offset.click.left<o[0]?c+i.grid[0]:c-i.grid[0]:c:c}}return{top:s-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+(t.browser.safari&&526>t.browser.version&&"fixed"==this.cssPosition?0:"fixed"==this.cssPosition?-this.scrollParent.scrollTop():r?0:n.scrollTop()),left:a-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+(t.browser.safari&&526>t.browser.version&&"fixed"==this.cssPosition?0:"fixed"==this.cssPosition?-this.scrollParent.scrollLeft():r?0:n.scrollLeft())}},_clear:function(){this.helper.removeClass("ui-draggable-dragging"),this.helper[0]==this.element[0]||this.cancelHelperRemoval||this.helper.remove(),this.helper=null,this.cancelHelperRemoval=!1},_trigger:function(e,i,n){return n=n||this._uiHash(),t.ui.plugin.call(this,e,[i,n]),"drag"==e&&(this.positionAbs=this._convertPositionTo("absolute")),t.Widget.prototype._trigger.call(this,e,i,n)},plugins:{},_uiHash:function(){return{helper:this.helper,position:this.position,originalPosition:this.originalPosition,offset:this.positionAbs}}}),t.extend(t.ui.draggable,{version:"1.8.24"}),t.ui.plugin.add("draggable","connectToSortable",{start:function(e,i){var n=t(this).data("draggable"),r=n.options,a=t.extend({},i,{item:n.element});n.sortables=[],t(r.connectToSortable).each(function(){var i=t.data(this,"sortable");i&&!i.options.disabled&&(n.sortables.push({instance:i,shouldRevert:i.options.revert}),i.refreshPositions(),i._trigger("activate",e,a))})},stop:function(e,i){var n=t(this).data("draggable"),r=t.extend({},i,{item:n.element});t.each(n.sortables,function(){this.instance.isOver?(this.instance.isOver=0,n.cancelHelperRemoval=!0,this.instance.cancelHelperRemoval=!1,this.shouldRevert&&(this.instance.options.revert=!0),this.instance._mouseStop(e),this.instance.options.helper=this.instance.options._helper,"original"==n.options.helper&&this.instance.currentItem.css({top:"auto",left:"auto"})):(this.instance.cancelHelperRemoval=!1,this.instance._trigger("deactivate",e,r))})},drag:function(e,i){var n=t(this).data("draggable"),r=this;t.each(n.sortables,function(){this.instance.positionAbs=n.positionAbs,this.instance.helperProportions=n.helperProportions,this.instance.offset.click=n.offset.click,this.instance._intersectsWith(this.instance.containerCache)?(this.instance.isOver||(this.instance.isOver=1,this.instance.currentItem=t(r).clone().removeAttr("id").appendTo(this.instance.element).data("sortable-item",!0),this.instance.options._helper=this.instance.options.helper,this.instance.options.helper=function(){return i.helper[0]},e.target=this.instance.currentItem[0],this.instance._mouseCapture(e,!0),this.instance._mouseStart(e,!0,!0),this.instance.offset.click.top=n.offset.click.top,this.instance.offset.click.left=n.offset.click.left,this.instance.offset.parent.left-=n.offset.parent.left-this.instance.offset.parent.left,this.instance.offset.parent.top-=n.offset.parent.top-this.instance.offset.parent.top,n._trigger("toSortable",e),n.dropped=this.instance.element,n.currentItem=n.element,this.instance.fromOutside=n),this.instance.currentItem&&this.instance._mouseDrag(e)):this.instance.isOver&&(this.instance.isOver=0,this.instance.cancelHelperRemoval=!0,this.instance.options.revert=!1,this.instance._trigger("out",e,this.instance._uiHash(this.instance)),this.instance._mouseStop(e,!0),this.instance.options.helper=this.instance.options._helper,this.instance.currentItem.remove(),this.instance.placeholder&&this.instance.placeholder.remove(),n._trigger("fromSortable",e),n.dropped=!1)})}}),t.ui.plugin.add("draggable","cursor",{start:function(){var e=t("body"),i=t(this).data("draggable").options;e.css("cursor")&&(i._cursor=e.css("cursor")),e.css("cursor",i.cursor)},stop:function(){var e=t(this).data("draggable").options;e._cursor&&t("body").css("cursor",e._cursor)}}),t.ui.plugin.add("draggable","opacity",{start:function(e,i){var n=t(i.helper),r=t(this).data("draggable").options;n.css("opacity")&&(r._opacity=n.css("opacity")),n.css("opacity",r.opacity)},stop:function(e,i){var n=t(this).data("draggable").options;n._opacity&&t(i.helper).css("opacity",n._opacity)}}),t.ui.plugin.add("draggable","scroll",{start:function(){var e=t(this).data("draggable");e.scrollParent[0]!=document&&"HTML"!=e.scrollParent[0].tagName&&(e.overflowOffset=e.scrollParent.offset())},drag:function(e){var i=t(this).data("draggable"),n=i.options,r=!1;i.scrollParent[0]!=document&&"HTML"!=i.scrollParent[0].tagName?(n.axis&&"x"==n.axis||(i.overflowOffset.top+i.scrollParent[0].offsetHeight-e.pageY<n.scrollSensitivity?i.scrollParent[0].scrollTop=r=i.scrollParent[0].scrollTop+n.scrollSpeed:e.pageY-i.overflowOffset.top<n.scrollSensitivity&&(i.scrollParent[0].scrollTop=r=i.scrollParent[0].scrollTop-n.scrollSpeed)),n.axis&&"y"==n.axis||(i.overflowOffset.left+i.scrollParent[0].offsetWidth-e.pageX<n.scrollSensitivity?i.scrollParent[0].scrollLeft=r=i.scrollParent[0].scrollLeft+n.scrollSpeed:e.pageX-i.overflowOffset.left<n.scrollSensitivity&&(i.scrollParent[0].scrollLeft=r=i.scrollParent[0].scrollLeft-n.scrollSpeed))):(n.axis&&"x"==n.axis||(e.pageY-t(document).scrollTop()<n.scrollSensitivity?r=t(document).scrollTop(t(document).scrollTop()-n.scrollSpeed):t(window).height()-(e.pageY-t(document).scrollTop())<n.scrollSensitivity&&(r=t(document).scrollTop(t(document).scrollTop()+n.scrollSpeed))),n.axis&&"y"==n.axis||(e.pageX-t(document).scrollLeft()<n.scrollSensitivity?r=t(document).scrollLeft(t(document).scrollLeft()-n.scrollSpeed):t(window).width()-(e.pageX-t(document).scrollLeft())<n.scrollSensitivity&&(r=t(document).scrollLeft(t(document).scrollLeft()+n.scrollSpeed)))),r!==!1&&t.ui.ddmanager&&!n.dropBehaviour&&t.ui.ddmanager.prepareOffsets(i,e)}}),t.ui.plugin.add("draggable","snap",{start:function(){var e=t(this).data("draggable"),i=e.options;e.snapElements=[],t(i.snap.constructor!=String?i.snap.items||":data(draggable)":i.snap).each(function(){var i=t(this),n=i.offset();this!=e.element[0]&&e.snapElements.push({item:this,width:i.outerWidth(),height:i.outerHeight(),top:n.top,left:n.left})})},drag:function(e,i){for(var n=t(this).data("draggable"),r=n.options,a=r.snapTolerance,s=i.offset.left,o=s+n.helperProportions.width,l=i.offset.top,u=l+n.helperProportions.height,c=n.snapElements.length-1;c>=0;c--){var h=n.snapElements[c].left,d=h+n.snapElements[c].width,p=n.snapElements[c].top,f=p+n.snapElements[c].height;if(s>h-a&&d+a>s&&l>p-a&&f+a>l||s>h-a&&d+a>s&&u>p-a&&f+a>u||o>h-a&&d+a>o&&l>p-a&&f+a>l||o>h-a&&d+a>o&&u>p-a&&f+a>u){if("inner"!=r.snapMode){var g=a>=Math.abs(p-u),m=a>=Math.abs(f-l),v=a>=Math.abs(h-o),y=a>=Math.abs(d-s);g&&(i.position.top=n._convertPositionTo("relative",{top:p-n.helperProportions.height,left:0}).top-n.margins.top),m&&(i.position.top=n._convertPositionTo("relative",{top:f,left:0}).top-n.margins.top),v&&(i.position.left=n._convertPositionTo("relative",{top:0,left:h-n.helperProportions.width}).left-n.margins.left),y&&(i.position.left=n._convertPositionTo("relative",{top:0,left:d}).left-n.margins.left)}var b=g||m||v||y;if("outer"!=r.snapMode){var g=a>=Math.abs(p-l),m=a>=Math.abs(f-u),v=a>=Math.abs(h-s),y=a>=Math.abs(d-o);g&&(i.position.top=n._convertPositionTo("relative",{top:p,left:0}).top-n.margins.top),m&&(i.position.top=n._convertPositionTo("relative",{top:f-n.helperProportions.height,left:0}).top-n.margins.top),v&&(i.position.left=n._convertPositionTo("relative",{top:0,left:h}).left-n.margins.left),y&&(i.position.left=n._convertPositionTo("relative",{top:0,left:d-n.helperProportions.width}).left-n.margins.left)}!n.snapElements[c].snapping&&(g||m||v||y||b)&&n.options.snap.snap&&n.options.snap.snap.call(n.element,e,t.extend(n._uiHash(),{snapItem:n.snapElements[c].item})),n.snapElements[c].snapping=g||m||v||y||b}else n.snapElements[c].snapping&&n.options.snap.release&&n.options.snap.release.call(n.element,e,t.extend(n._uiHash(),{snapItem:n.snapElements[c].item})),n.snapElements[c].snapping=!1}}}),t.ui.plugin.add("draggable","stack",{start:function(){var e=t(this).data("draggable").options,i=t.makeArray(t(e.stack)).sort(function(e,i){return(parseInt(t(e).css("zIndex"),10)||0)-(parseInt(t(i).css("zIndex"),10)||0)});if(i.length){var n=parseInt(i[0].style.zIndex)||0;t(i).each(function(t){this.style.zIndex=n+t}),this[0].style.zIndex=n+i.length}}}),t.ui.plugin.add("draggable","zIndex",{start:function(e,i){var n=t(i.helper),r=t(this).data("draggable").options;n.css("zIndex")&&(r._zIndex=n.css("zIndex")),n.css("zIndex",r.zIndex)},stop:function(e,i){var n=t(this).data("draggable").options;n._zIndex&&t(i.helper).css("zIndex",n._zIndex)}})}(jQuery),function(t){t.widget("ui.sortable",t.ui.mouse,{widgetEventPrefix:"sort",ready:!1,options:{appendTo:"parent",axis:!1,connectWith:!1,containment:!1,cursor:"auto",cursorAt:!1,dropOnEmpty:!0,forcePlaceholderSize:!1,forceHelperSize:!1,grid:!1,handle:!1,helper:"original",items:"> *",opacity:!1,placeholder:!1,revert:!1,scroll:!0,scrollSensitivity:20,scrollSpeed:20,scope:"default",tolerance:"intersect",zIndex:1e3},_create:function(){var t=this.options;this.containerCache={},this.element.addClass("ui-sortable"),this.refresh(),this.floating=this.items.length?"x"===t.axis||/left|right/.test(this.items[0].item.css("float"))||/inline|table-cell/.test(this.items[0].item.css("display")):!1,this.offset=this.element.offset(),this._mouseInit(),this.ready=!0},destroy:function(){t.Widget.prototype.destroy.call(this),this.element.removeClass("ui-sortable ui-sortable-disabled"),this._mouseDestroy();for(var e=this.items.length-1;e>=0;e--)this.items[e].item.removeData(this.widgetName+"-item");return this},_setOption:function(e,i){"disabled"===e?(this.options[e]=i,this.widget()[i?"addClass":"removeClass"]("ui-sortable-disabled")):t.Widget.prototype._setOption.apply(this,arguments)},_mouseCapture:function(e,i){var n=this;if(this.reverting)return!1;if(this.options.disabled||"static"==this.options.type)return!1;this._refreshItems(e);var r=null,a=this;if(t(e.target).parents().each(function(){return t.data(this,n.widgetName+"-item")==a?(r=t(this),!1):undefined}),t.data(e.target,n.widgetName+"-item")==a&&(r=t(e.target)),!r)return!1;if(this.options.handle&&!i){var s=!1;if(t(this.options.handle,r).find("*").andSelf().each(function(){this==e.target&&(s=!0)}),!s)return!1}return this.currentItem=r,this._removeCurrentsFromItems(),!0},_mouseStart:function(e,i,n){var r=this.options,a=this;if(this.currentContainer=this,this.refreshPositions(),this.helper=this._createHelper(e),this._cacheHelperProportions(),this._cacheMargins(),this.scrollParent=this.helper.scrollParent(),this.offset=this.currentItem.offset(),this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left},t.extend(this.offset,{click:{left:e.pageX-this.offset.left,top:e.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()}),this.helper.css("position","absolute"),this.cssPosition=this.helper.css("position"),this.originalPosition=this._generatePosition(e),this.originalPageX=e.pageX,this.originalPageY=e.pageY,r.cursorAt&&this._adjustOffsetFromHelper(r.cursorAt),this.domPosition={prev:this.currentItem.prev()[0],parent:this.currentItem.parent()[0]},this.helper[0]!=this.currentItem[0]&&this.currentItem.hide(),this._createPlaceholder(),r.containment&&this._setContainment(),r.cursor&&(t("body").css("cursor")&&(this._storedCursor=t("body").css("cursor")),t("body").css("cursor",r.cursor)),r.opacity&&(this.helper.css("opacity")&&(this._storedOpacity=this.helper.css("opacity")),this.helper.css("opacity",r.opacity)),r.zIndex&&(this.helper.css("zIndex")&&(this._storedZIndex=this.helper.css("zIndex")),this.helper.css("zIndex",r.zIndex)),this.scrollParent[0]!=document&&"HTML"!=this.scrollParent[0].tagName&&(this.overflowOffset=this.scrollParent.offset()),this._trigger("start",e,this._uiHash()),this._preserveHelperProportions||this._cacheHelperProportions(),!n)for(var s=this.containers.length-1;s>=0;s--)this.containers[s]._trigger("activate",e,a._uiHash(this));return t.ui.ddmanager&&(t.ui.ddmanager.current=this),t.ui.ddmanager&&!r.dropBehaviour&&t.ui.ddmanager.prepareOffsets(this,e),this.dragging=!0,this.helper.addClass("ui-sortable-helper"),this._mouseDrag(e),!0},_mouseDrag:function(e){if(this.position=this._generatePosition(e),this.positionAbs=this._convertPositionTo("absolute"),this.lastPositionAbs||(this.lastPositionAbs=this.positionAbs),this.options.scroll){var i=this.options,n=!1;this.scrollParent[0]!=document&&"HTML"!=this.scrollParent[0].tagName?(this.overflowOffset.top+this.scrollParent[0].offsetHeight-e.pageY<i.scrollSensitivity?this.scrollParent[0].scrollTop=n=this.scrollParent[0].scrollTop+i.scrollSpeed:e.pageY-this.overflowOffset.top<i.scrollSensitivity&&(this.scrollParent[0].scrollTop=n=this.scrollParent[0].scrollTop-i.scrollSpeed),this.overflowOffset.left+this.scrollParent[0].offsetWidth-e.pageX<i.scrollSensitivity?this.scrollParent[0].scrollLeft=n=this.scrollParent[0].scrollLeft+i.scrollSpeed:e.pageX-this.overflowOffset.left<i.scrollSensitivity&&(this.scrollParent[0].scrollLeft=n=this.scrollParent[0].scrollLeft-i.scrollSpeed)):(e.pageY-t(document).scrollTop()<i.scrollSensitivity?n=t(document).scrollTop(t(document).scrollTop()-i.scrollSpeed):t(window).height()-(e.pageY-t(document).scrollTop())<i.scrollSensitivity&&(n=t(document).scrollTop(t(document).scrollTop()+i.scrollSpeed)),e.pageX-t(document).scrollLeft()<i.scrollSensitivity?n=t(document).scrollLeft(t(document).scrollLeft()-i.scrollSpeed):t(window).width()-(e.pageX-t(document).scrollLeft())<i.scrollSensitivity&&(n=t(document).scrollLeft(t(document).scrollLeft()+i.scrollSpeed))),n!==!1&&t.ui.ddmanager&&!i.dropBehaviour&&t.ui.ddmanager.prepareOffsets(this,e)}this.positionAbs=this._convertPositionTo("absolute"),this.options.axis&&"y"==this.options.axis||(this.helper[0].style.left=this.position.left+"px"),this.options.axis&&"x"==this.options.axis||(this.helper[0].style.top=this.position.top+"px");for(var r=this.items.length-1;r>=0;r--){var a=this.items[r],s=a.item[0],o=this._intersectsWithPointer(a);if(o&&a.instance===this.currentContainer&&s!=this.currentItem[0]&&this.placeholder[1==o?"next":"prev"]()[0]!=s&&!t.ui.contains(this.placeholder[0],s)&&("semi-dynamic"==this.options.type?!t.ui.contains(this.element[0],s):!0)){if(this.direction=1==o?"down":"up","pointer"!=this.options.tolerance&&!this._intersectsWithSides(a))break;this._rearrange(e,a),this._trigger("change",e,this._uiHash());break}}return this._contactContainers(e),t.ui.ddmanager&&t.ui.ddmanager.drag(this,e),this._trigger("sort",e,this._uiHash()),this.lastPositionAbs=this.positionAbs,!1},_mouseStop:function(e,i){if(e){if(t.ui.ddmanager&&!this.options.dropBehaviour&&t.ui.ddmanager.drop(this,e),this.options.revert){var n=this,r=n.placeholder.offset();n.reverting=!0,t(this.helper).animate({left:r.left-this.offset.parent.left-n.margins.left+(this.offsetParent[0]==document.body?0:this.offsetParent[0].scrollLeft),top:r.top-this.offset.parent.top-n.margins.top+(this.offsetParent[0]==document.body?0:this.offsetParent[0].scrollTop)},parseInt(this.options.revert,10)||500,function(){n._clear(e)})}else this._clear(e,i);return!1}},cancel:function(){var e=this;if(this.dragging){this._mouseUp({target:null}),"original"==this.options.helper?this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper"):this.currentItem.show();for(var i=this.containers.length-1;i>=0;i--)this.containers[i]._trigger("deactivate",null,e._uiHash(this)),this.containers[i].containerCache.over&&(this.containers[i]._trigger("out",null,e._uiHash(this)),this.containers[i].containerCache.over=0)}return this.placeholder&&(this.placeholder[0].parentNode&&this.placeholder[0].parentNode.removeChild(this.placeholder[0]),"original"!=this.options.helper&&this.helper&&this.helper[0].parentNode&&this.helper.remove(),t.extend(this,{helper:null,dragging:!1,reverting:!1,_noFinalSort:null}),this.domPosition.prev?t(this.domPosition.prev).after(this.currentItem):t(this.domPosition.parent).prepend(this.currentItem)),this},serialize:function(e){var i=this._getItemsAsjQuery(e&&e.connected),n=[];return e=e||{},t(i).each(function(){var i=(t(e.item||this).attr(e.attribute||"id")||"").match(e.expression||/(.+)[-=_](.+)/);i&&n.push((e.key||i[1]+"[]")+"="+(e.key&&e.expression?i[1]:i[2]))}),!n.length&&e.key&&n.push(e.key+"="),n.join("&")},toArray:function(e){var i=this._getItemsAsjQuery(e&&e.connected),n=[];return e=e||{},i.each(function(){n.push(t(e.item||this).attr(e.attribute||"id")||"")}),n},_intersectsWith:function(t){var e=this.positionAbs.left,i=e+this.helperProportions.width,n=this.positionAbs.top,r=n+this.helperProportions.height,a=t.left,s=a+t.width,o=t.top,l=o+t.height,u=this.offset.click.top,c=this.offset.click.left,h=n+u>o&&l>n+u&&e+c>a&&s>e+c;return"pointer"==this.options.tolerance||this.options.forcePointerForContainers||"pointer"!=this.options.tolerance&&this.helperProportions[this.floating?"width":"height"]>t[this.floating?"width":"height"]?h:e+this.helperProportions.width/2>a&&s>i-this.helperProportions.width/2&&n+this.helperProportions.height/2>o&&l>r-this.helperProportions.height/2},_intersectsWithPointer:function(e){var i="x"===this.options.axis||t.ui.isOverAxis(this.positionAbs.top+this.offset.click.top,e.top,e.height),n="y"===this.options.axis||t.ui.isOverAxis(this.positionAbs.left+this.offset.click.left,e.left,e.width),r=i&&n,a=this._getDragVerticalDirection(),s=this._getDragHorizontalDirection();return r?this.floating?s&&"right"==s||"down"==a?2:1:a&&("down"==a?2:1):!1},_intersectsWithSides:function(e){var i=t.ui.isOverAxis(this.positionAbs.top+this.offset.click.top,e.top+e.height/2,e.height),n=t.ui.isOverAxis(this.positionAbs.left+this.offset.click.left,e.left+e.width/2,e.width),r=this._getDragVerticalDirection(),a=this._getDragHorizontalDirection();return this.floating&&a?"right"==a&&n||"left"==a&&!n:r&&("down"==r&&i||"up"==r&&!i)},_getDragVerticalDirection:function(){var t=this.positionAbs.top-this.lastPositionAbs.top;return 0!=t&&(t>0?"down":"up")},_getDragHorizontalDirection:function(){var t=this.positionAbs.left-this.lastPositionAbs.left;return 0!=t&&(t>0?"right":"left")},refresh:function(t){return this._refreshItems(t),this.refreshPositions(),this},_connectWith:function(){var t=this.options;return t.connectWith.constructor==String?[t.connectWith]:t.connectWith},_getItemsAsjQuery:function(e){var i=[],n=[],r=this._connectWith();if(r&&e)for(var a=r.length-1;a>=0;a--)for(var s=t(r[a]),o=s.length-1;o>=0;o--){var l=t.data(s[o],this.widgetName);l&&l!=this&&!l.options.disabled&&n.push([t.isFunction(l.options.items)?l.options.items.call(l.element):t(l.options.items,l.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),l])}n.push([t.isFunction(this.options.items)?this.options.items.call(this.element,null,{options:this.options,item:this.currentItem}):t(this.options.items,this.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),this]);for(var a=n.length-1;a>=0;a--)n[a][0].each(function(){i.push(this)});return t(i)},_removeCurrentsFromItems:function(){for(var t=this.currentItem.find(":data("+this.widgetName+"-item)"),e=0;this.items.length>e;e++)for(var i=0;t.length>i;i++)t[i]==this.items[e].item[0]&&this.items.splice(e,1)},_refreshItems:function(e){this.items=[],this.containers=[this];var i=this.items,n=[[t.isFunction(this.options.items)?this.options.items.call(this.element[0],e,{item:this.currentItem}):t(this.options.items,this.element),this]],r=this._connectWith();if(r&&this.ready)for(var a=r.length-1;a>=0;a--)for(var s=t(r[a]),o=s.length-1;o>=0;o--){var l=t.data(s[o],this.widgetName);l&&l!=this&&!l.options.disabled&&(n.push([t.isFunction(l.options.items)?l.options.items.call(l.element[0],e,{item:this.currentItem}):t(l.options.items,l.element),l]),this.containers.push(l))}for(var a=n.length-1;a>=0;a--)for(var u=n[a][1],c=n[a][0],o=0,h=c.length;h>o;o++){var d=t(c[o]);d.data(this.widgetName+"-item",u),i.push({item:d,instance:u,width:0,height:0,left:0,top:0})}},refreshPositions:function(e){this.offsetParent&&this.helper&&(this.offset.parent=this._getParentOffset());for(var i=this.items.length-1;i>=0;i--){var n=this.items[i];if(n.instance==this.currentContainer||!this.currentContainer||n.item[0]==this.currentItem[0]){var r=this.options.toleranceElement?t(this.options.toleranceElement,n.item):n.item;e||(n.width=r.outerWidth(),n.height=r.outerHeight());var a=r.offset();n.left=a.left,n.top=a.top}}if(this.options.custom&&this.options.custom.refreshContainers)this.options.custom.refreshContainers.call(this);else for(var i=this.containers.length-1;i>=0;i--){var a=this.containers[i].element.offset();this.containers[i].containerCache.left=a.left,this.containers[i].containerCache.top=a.top,this.containers[i].containerCache.width=this.containers[i].element.outerWidth(),this.containers[i].containerCache.height=this.containers[i].element.outerHeight()}return this},_createPlaceholder:function(e){var i=e||this,n=i.options;if(!n.placeholder||n.placeholder.constructor==String){var r=n.placeholder;n.placeholder={element:function(){var e=t(document.createElement(i.currentItem[0].nodeName)).addClass(r||i.currentItem[0].className+" ui-sortable-placeholder").removeClass("ui-sortable-helper")[0];return r||(e.style.visibility="hidden"),e},update:function(t,e){(!r||n.forcePlaceholderSize)&&(e.height()||e.height(i.currentItem.innerHeight()-parseInt(i.currentItem.css("paddingTop")||0,10)-parseInt(i.currentItem.css("paddingBottom")||0,10)),e.width()||e.width(i.currentItem.innerWidth()-parseInt(i.currentItem.css("paddingLeft")||0,10)-parseInt(i.currentItem.css("paddingRight")||0,10)))}}}i.placeholder=t(n.placeholder.element.call(i.element,i.currentItem)),i.currentItem.after(i.placeholder),n.placeholder.update(i,i.placeholder)},_contactContainers:function(e){for(var i=null,n=null,r=this.containers.length-1;r>=0;r--)if(!t.ui.contains(this.currentItem[0],this.containers[r].element[0]))if(this._intersectsWith(this.containers[r].containerCache)){if(i&&t.ui.contains(this.containers[r].element[0],i.element[0]))continue;i=this.containers[r],n=r}else this.containers[r].containerCache.over&&(this.containers[r]._trigger("out",e,this._uiHash(this)),this.containers[r].containerCache.over=0);if(i)if(1===this.containers.length)this.containers[n]._trigger("over",e,this._uiHash(this)),this.containers[n].containerCache.over=1;else if(this.currentContainer!=this.containers[n]){for(var a=1e4,s=null,o=this.positionAbs[this.containers[n].floating?"left":"top"],l=this.items.length-1;l>=0;l--)if(t.ui.contains(this.containers[n].element[0],this.items[l].item[0])){var u=this.containers[n].floating?this.items[l].item.offset().left:this.items[l].item.offset().top;a>Math.abs(u-o)&&(a=Math.abs(u-o),s=this.items[l],this.direction=u-o>0?"down":"up")}if(!s&&!this.options.dropOnEmpty)return;this.currentContainer=this.containers[n],s?this._rearrange(e,s,null,!0):this._rearrange(e,null,this.containers[n].element,!0),this._trigger("change",e,this._uiHash()),this.containers[n]._trigger("change",e,this._uiHash(this)),this.options.placeholder.update(this.currentContainer,this.placeholder),this.containers[n]._trigger("over",e,this._uiHash(this)),this.containers[n].containerCache.over=1}},_createHelper:function(e){var i=this.options,n=t.isFunction(i.helper)?t(i.helper.apply(this.element[0],[e,this.currentItem])):"clone"==i.helper?this.currentItem.clone():this.currentItem;return n.parents("body").length||t("parent"!=i.appendTo?i.appendTo:this.currentItem[0].parentNode)[0].appendChild(n[0]),n[0]==this.currentItem[0]&&(this._storedCSS={width:this.currentItem[0].style.width,height:this.currentItem[0].style.height,position:this.currentItem.css("position"),top:this.currentItem.css("top"),left:this.currentItem.css("left")}),(""==n[0].style.width||i.forceHelperSize)&&n.width(this.currentItem.width()),(""==n[0].style.height||i.forceHelperSize)&&n.height(this.currentItem.height()),n},_adjustOffsetFromHelper:function(e){"string"==typeof e&&(e=e.split(" ")),t.isArray(e)&&(e={left:+e[0],top:+e[1]||0}),"left"in e&&(this.offset.click.left=e.left+this.margins.left),"right"in e&&(this.offset.click.left=this.helperProportions.width-e.right+this.margins.left),"top"in e&&(this.offset.click.top=e.top+this.margins.top),"bottom"in e&&(this.offset.click.top=this.helperProportions.height-e.bottom+this.margins.top)},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var e=this.offsetParent.offset();return"absolute"==this.cssPosition&&this.scrollParent[0]!=document&&t.ui.contains(this.scrollParent[0],this.offsetParent[0])&&(e.left+=this.scrollParent.scrollLeft(),e.top+=this.scrollParent.scrollTop()),(this.offsetParent[0]==document.body||this.offsetParent[0].tagName&&"html"==this.offsetParent[0].tagName.toLowerCase()&&t.browser.msie)&&(e={top:0,left:0}),{top:e.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:e.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)} },_getRelativeOffset:function(){if("relative"==this.cssPosition){var t=this.currentItem.position();return{top:t.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:t.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}return{top:0,left:0}},_cacheMargins:function(){this.margins={left:parseInt(this.currentItem.css("marginLeft"),10)||0,top:parseInt(this.currentItem.css("marginTop"),10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var e=this.options;if("parent"==e.containment&&(e.containment=this.helper[0].parentNode),("document"==e.containment||"window"==e.containment)&&(this.containment=[0-this.offset.relative.left-this.offset.parent.left,0-this.offset.relative.top-this.offset.parent.top,t("document"==e.containment?document:window).width()-this.helperProportions.width-this.margins.left,(t("document"==e.containment?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top]),!/^(document|window|parent)$/.test(e.containment)){var i=t(e.containment)[0],n=t(e.containment).offset(),r="hidden"!=t(i).css("overflow");this.containment=[n.left+(parseInt(t(i).css("borderLeftWidth"),10)||0)+(parseInt(t(i).css("paddingLeft"),10)||0)-this.margins.left,n.top+(parseInt(t(i).css("borderTopWidth"),10)||0)+(parseInt(t(i).css("paddingTop"),10)||0)-this.margins.top,n.left+(r?Math.max(i.scrollWidth,i.offsetWidth):i.offsetWidth)-(parseInt(t(i).css("borderLeftWidth"),10)||0)-(parseInt(t(i).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left,n.top+(r?Math.max(i.scrollHeight,i.offsetHeight):i.offsetHeight)-(parseInt(t(i).css("borderTopWidth"),10)||0)-(parseInt(t(i).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top]}},_convertPositionTo:function(e,i){i||(i=this.position);var n="absolute"==e?1:-1,r=(this.options,"absolute"!=this.cssPosition||this.scrollParent[0]!=document&&t.ui.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent),a=/(html|body)/i.test(r[0].tagName);return{top:i.top+this.offset.relative.top*n+this.offset.parent.top*n-(t.browser.safari&&"fixed"==this.cssPosition?0:("fixed"==this.cssPosition?-this.scrollParent.scrollTop():a?0:r.scrollTop())*n),left:i.left+this.offset.relative.left*n+this.offset.parent.left*n-(t.browser.safari&&"fixed"==this.cssPosition?0:("fixed"==this.cssPosition?-this.scrollParent.scrollLeft():a?0:r.scrollLeft())*n)}},_generatePosition:function(e){var i=this.options,n="absolute"!=this.cssPosition||this.scrollParent[0]!=document&&t.ui.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,r=/(html|body)/i.test(n[0].tagName);"relative"!=this.cssPosition||this.scrollParent[0]!=document&&this.scrollParent[0]!=this.offsetParent[0]||(this.offset.relative=this._getRelativeOffset());var a=e.pageX,s=e.pageY;if(this.originalPosition&&(this.containment&&(e.pageX-this.offset.click.left<this.containment[0]&&(a=this.containment[0]+this.offset.click.left),e.pageY-this.offset.click.top<this.containment[1]&&(s=this.containment[1]+this.offset.click.top),e.pageX-this.offset.click.left>this.containment[2]&&(a=this.containment[2]+this.offset.click.left),e.pageY-this.offset.click.top>this.containment[3]&&(s=this.containment[3]+this.offset.click.top)),i.grid)){var o=this.originalPageY+Math.round((s-this.originalPageY)/i.grid[1])*i.grid[1];s=this.containment?o-this.offset.click.top<this.containment[1]||o-this.offset.click.top>this.containment[3]?o-this.offset.click.top<this.containment[1]?o+i.grid[1]:o-i.grid[1]:o:o;var l=this.originalPageX+Math.round((a-this.originalPageX)/i.grid[0])*i.grid[0];a=this.containment?l-this.offset.click.left<this.containment[0]||l-this.offset.click.left>this.containment[2]?l-this.offset.click.left<this.containment[0]?l+i.grid[0]:l-i.grid[0]:l:l}return{top:s-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+(t.browser.safari&&"fixed"==this.cssPosition?0:"fixed"==this.cssPosition?-this.scrollParent.scrollTop():r?0:n.scrollTop()),left:a-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+(t.browser.safari&&"fixed"==this.cssPosition?0:"fixed"==this.cssPosition?-this.scrollParent.scrollLeft():r?0:n.scrollLeft())}},_rearrange:function(t,e,i,n){i?i[0].appendChild(this.placeholder[0]):e.item[0].parentNode.insertBefore(this.placeholder[0],"down"==this.direction?e.item[0]:e.item[0].nextSibling),this.counter=this.counter?++this.counter:1;var r=this,a=this.counter;window.setTimeout(function(){a==r.counter&&r.refreshPositions(!n)},0)},_clear:function(e,i){this.reverting=!1;var n=[];if(!this._noFinalSort&&this.currentItem.parent().length&&this.placeholder.before(this.currentItem),this._noFinalSort=null,this.helper[0]==this.currentItem[0]){for(var r in this._storedCSS)("auto"==this._storedCSS[r]||"static"==this._storedCSS[r])&&(this._storedCSS[r]="");this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper")}else this.currentItem.show();this.fromOutside&&!i&&n.push(function(t){this._trigger("receive",t,this._uiHash(this.fromOutside))}),!this.fromOutside&&this.domPosition.prev==this.currentItem.prev().not(".ui-sortable-helper")[0]&&this.domPosition.parent==this.currentItem.parent()[0]||i||n.push(function(t){this._trigger("update",t,this._uiHash())}),this!==this.currentContainer&&(i||(n.push(function(t){this._trigger("remove",t,this._uiHash())}),n.push(function(t){return function(e){t._trigger("receive",e,this._uiHash(this))}}.call(this,this.currentContainer)),n.push(function(t){return function(e){t._trigger("update",e,this._uiHash(this))}}.call(this,this.currentContainer))));for(var r=this.containers.length-1;r>=0;r--)i||n.push(function(t){return function(e){t._trigger("deactivate",e,this._uiHash(this))}}.call(this,this.containers[r])),this.containers[r].containerCache.over&&(n.push(function(t){return function(e){t._trigger("out",e,this._uiHash(this))}}.call(this,this.containers[r])),this.containers[r].containerCache.over=0);if(this._storedCursor&&t("body").css("cursor",this._storedCursor),this._storedOpacity&&this.helper.css("opacity",this._storedOpacity),this._storedZIndex&&this.helper.css("zIndex","auto"==this._storedZIndex?"":this._storedZIndex),this.dragging=!1,this.cancelHelperRemoval){if(!i){this._trigger("beforeStop",e,this._uiHash());for(var r=0;n.length>r;r++)n[r].call(this,e);this._trigger("stop",e,this._uiHash())}return this.fromOutside=!1,!1}if(i||this._trigger("beforeStop",e,this._uiHash()),this.placeholder[0].parentNode.removeChild(this.placeholder[0]),this.helper[0]!=this.currentItem[0]&&this.helper.remove(),this.helper=null,!i){for(var r=0;n.length>r;r++)n[r].call(this,e);this._trigger("stop",e,this._uiHash())}return this.fromOutside=!1,!0},_trigger:function(){t.Widget.prototype._trigger.apply(this,arguments)===!1&&this.cancel()},_uiHash:function(e){var i=e||this;return{helper:i.helper,placeholder:i.placeholder||t([]),position:i.position,originalPosition:i.originalPosition,offset:i.positionAbs,item:i.currentItem,sender:e?e.element:null}}}),t.extend(t.ui.sortable,{version:"1.8.24"})}(jQuery);
src/js/components/search-results.js
UNECE/Classification-Explorer
import React from 'react'; import { sparqlConnect } from '../sparql/configure-sparql'; import { uriToLink, connectFromRoute } from '../router-mapping'; import { LOADING, FAILED } from 'sparql-connect'; import { Link } from 'react-router'; import { groupBy } from '../utils'; import ItemResult from './item-result'; import Loading from './loading'; import TreeView from 'react-treeview'; function SearchResults({ loaded, items, keyword, searchForCode, hash }) { if (loaded === LOADING) return <Loading from="search results" plural={true} />; if (loaded === FAILED) return <span>Failed loading results for {keyword}</span>; if (items.length === 0) return <span>There are no results for {keyword}</span>; const clns = groupBy(items, 'classification', 'classificationLabel'); return ( <ul className="list-group"> {Object.keys(clns).reduce((agregate, clnId) => { const cln = clns[clnId]; const clnEntries = cln.entries; const clnEl = ( <li key={clnId} className="list-group-item"> <TreeView key={cln.props.classificationLabel} nodeLabel={ <Link to={uriToLink.classificationDetails(clnId)}> {cln.props.classificationLabel} </Link> } > <ul> {clnEntries.map((rslt, i) => ( //no obvious meaning ful key, so we use an index <li key={i}> <ItemResult {...rslt} /> </li> ))} </ul> </TreeView> </li> ); agregate.push(clnEl); return agregate; }, [])} </ul> ); } export default connectFromRoute(sparqlConnect.searchItems(SearchResults));
examples/huge-apps/routes/Course/routes/Assignments/components/Assignments.js
andreftavares/react-router
import React from 'react' class Assignments extends React.Component { render() { return ( <div> <h3>Assignments</h3> {this.props.children || <p>Choose an assignment from the sidebar.</p>} </div> ) } } export default Assignments
spec/coffeescripts/jsx/dashboard_card/DashboardCardBoxSpec.js
djbender/canvas-lms
/* * Copyright (C) 2015 - present Instructure, Inc. * * This file is part of Canvas. * * Canvas is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, version 3 of the License. * * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ import React from 'react' import ReactDOM from 'react-dom' import TestUtils from 'react-dom/test-utils' import ReactDndTestBackend from 'react-dnd-test-backend' import sinon from 'sinon' import {wait} from '@testing-library/react' import getDroppableDashboardCardBox from 'jsx/dashboard_card/getDroppableDashboardCardBox' import CourseActivitySummaryStore from 'jsx/dashboard_card/CourseActivitySummaryStore' QUnit.module('DashboardCardBox', suiteHooks => { let $container let component let props let server suiteHooks.beforeEach(() => { $container = document.createElement('div') document.body.appendChild($container) props = { courseCards: [ { id: '1', isFavorited: true, courseName: 'Bio 101' }, { id: '2', isFavorited: true, courseName: 'Philosophy 201' } ] } server = sinon.fakeServer.create({respondImmediately: true}) return sandbox.stub(CourseActivitySummaryStore, 'getStateForCourse').returns({}) }) suiteHooks.afterEach(async () => { ReactDOM.unmountComponentAtNode($container) $container.remove() server.restore() }) function mountComponent() { const bindRef = ref => { component = ref } const Box = getDroppableDashboardCardBox(ReactDndTestBackend) const CardBox = ( <Box connectDropTarget={el => el} courseCards={props.courseCards} ref={bindRef} /> ) ReactDOM.render(CardBox, $container) } function getDashboardBoxElement() { return document.querySelector('.ic-DashboardCard__box') } function getDashboardCardElements() { return [...getDashboardBoxElement().querySelectorAll('.ic-DashboardCard')] } function getPopoverButton(card) { return card.querySelector('.icon-more') } function getMoveTab() { return [...document.querySelectorAll('[role="tab"]')].find($tab => $tab.textContent.includes('Move') ) } function getDashboardMenu() { return document.querySelector('[aria-label="Dashboard Card Movement Menu"]') } function getUnfavoriteButton() { return [...getDashboardMenu().querySelectorAll('.DashboardCardMenu__MovementItem')].find( $button => $button.textContent.includes('Unfavorite') ) } function getModal() { return document.querySelector('[aria-label="Confirm unfavorite course"]') } function getSubmitButton() { return [...getModal().querySelectorAll('Button')].find($button => $button.textContent.includes('Submit') ) } function removeCardFromFavorites(card) { getPopoverButton(card).click() getMoveTab().click() getUnfavoriteButton().click() getSubmitButton().click() } async function getNoFavoritesAlert() { const noFavoritesAlert = await getDashboardBoxElement().querySelector( '.no-favorites-alert-container' ) return noFavoritesAlert } QUnit.module('#render()', () => { test('should render div.ic-DashboardCard per provided courseCard', () => { mountComponent() const cards = getDashboardCardElements() strictEqual(cards.length, props.courseCards.length) }) }) QUnit.module('#handleRerenderCards', () => { test('removes unfavorited card from dashboard cards', async () => { function waitForRerender(card) { if (!card.isFavorited) { return true } } mountComponent() const card = getDashboardCardElements()[0] const url = '/api/v1/users/self/favorites/courses/1' server.respondWith('DELETE', url, [200, {}, '']) server.respond() removeCardFromFavorites(card) await wait(() => waitForRerender(card)) const rerendered = getDashboardCardElements() strictEqual(rerendered.length, 1) }) test('shows no favorites alert when last course is unfavorited', () => { props.courseCards = [props.courseCards[0]] mountComponent() const card = getDashboardCardElements()[0] removeCardFromFavorites(card) ok(getNoFavoritesAlert()) }) }) })
resources/src/js/sections/Favorites/index.js
aberon10/thermomusic.com
'use strict'; import React from 'react'; import { Link } from 'react-router-dom'; import Ajax from '../../Libs/Ajax'; import MainContent from '../../components/Main'; import ContentSpacing from '../../components/Containers/ContentSpacing'; import TrackList from '../../sections/components/TrackList'; import Notification from '../../components/Notification/index'; import { checkXMLHTTPResponse } from '../../app/utils/Utils'; export default class Favorites extends React.Component { constructor(props) { super(props); this.state = { element: null }; this.loadData = this.loadData.bind(this); } componentDidMount() { Ajax.post({ url: '/music/favorites', responseType: 'json', data: null }).then((response) => { checkXMLHTTPResponse(response); this.setState({ element: this.loadData(response) }); }).catch((error) => { console.log(error); }); } loadData(response) { let element = <Notification message={ <Link to='/user' style={{color: '#fff'}}> Oops! Al parecer no tienes pistas favoritas. Vamos, animate! de seguro encuentras una que te gusta. </Link> } classes='blue' />; if (response.data && response.data.length) { let tracks = []; response.data.forEach((item) => { tracks.push({ id: item.id_cancion, src: item.src_audio, trackName: item.nombre_cancion, duration: item.duracion, counter: item.contador, srcAlbum: encodeURI(item.src_img), artist: `por ${item.nombre_artista}`, playlist: null, idPlaylist: null, favorite: true, inFavoritePage: true }); }); element = ( <MainContent> <ContentSpacing title="Tú Música favorita"> <div className="album-container"> <div className="album-container__content"> <TrackList data={tracks} /> </div> </div> </ContentSpacing> </MainContent> ); } return element; } render() { return ( <div> {this.state.element} </div> ); } }
assets/javascripts/kitten/components/structure/line/index.js
KissKissBankBank/kitten
import React from 'react' import classNames from 'classnames' import styled from 'styled-components' import { pxToRem } from '../../../helpers/utils/typography' const StyledLine = styled.div` display: flex; align-items: center; gap: ${pxToRem(10)}; ` export const Line = props => { return ( <StyledLine {...props} className={classNames('k-Line', props.className)} /> ) } Line.Item = props => { return ( <div {...props} className={classNames('k-Line__item', props.className)} /> ) } Line.defaultProps = { className: null, children: null, } Line.Item.defaultProps = { className: null, children: null, }
app/src/index.js
tafkanator/drupal-react
import React from 'react'; import ReactDOM from 'react-dom'; import { Router, browserHistory } from 'react-router'; import routes from './routes'; import './gfx/main.scss'; // scroll top on page change let prevLocation = {}; browserHistory.listenBefore(location => { const pathChanged = prevLocation.pathname !== location.pathname; const hashChanged = prevLocation.hash !== location.hash; if (pathChanged || hashChanged) { window.scrollTo(0, 0); } prevLocation = location; }); ReactDOM.render( <Router history={browserHistory} routes={routes} />, document.getElementById('root') );
ajax/libs/angular-ui-grid/3.0.6/ui-grid.js
hare1039/cdnjs
/*! * ui-grid - v3.0.6 - 2015-09-10 * Copyright (c) 2015 ; License: MIT */ (function () { 'use strict'; angular.module('ui.grid.i18n', []); angular.module('ui.grid', ['ui.grid.i18n']); })(); (function () { 'use strict'; angular.module('ui.grid').constant('uiGridConstants', { LOG_DEBUG_MESSAGES: true, LOG_WARN_MESSAGES: true, LOG_ERROR_MESSAGES: true, CUSTOM_FILTERS: /CUSTOM_FILTERS/g, COL_FIELD: /COL_FIELD/g, MODEL_COL_FIELD: /MODEL_COL_FIELD/g, TOOLTIP: /title=\"TOOLTIP\"/g, DISPLAY_CELL_TEMPLATE: /DISPLAY_CELL_TEMPLATE/g, TEMPLATE_REGEXP: /<.+>/, FUNC_REGEXP: /(\([^)]*\))?$/, DOT_REGEXP: /\./g, APOS_REGEXP: /'/g, BRACKET_REGEXP: /^(.*)((?:\s*\[\s*\d+\s*\]\s*)|(?:\s*\[\s*"(?:[^"\\]|\\.)*"\s*\]\s*)|(?:\s*\[\s*'(?:[^'\\]|\\.)*'\s*\]\s*))(.*)$/, COL_CLASS_PREFIX: 'ui-grid-col', events: { GRID_SCROLL: 'uiGridScroll', COLUMN_MENU_SHOWN: 'uiGridColMenuShown', ITEM_DRAGGING: 'uiGridItemDragStart', // For any item being dragged COLUMN_HEADER_CLICK: 'uiGridColumnHeaderClick' }, // copied from http://www.lsauer.com/2011/08/javascript-keymap-keycodes-in-json.html keymap: { TAB: 9, STRG: 17, CAPSLOCK: 20, CTRL: 17, CTRLRIGHT: 18, CTRLR: 18, SHIFT: 16, RETURN: 13, ENTER: 13, BACKSPACE: 8, BCKSP: 8, ALT: 18, ALTR: 17, ALTRIGHT: 17, SPACE: 32, WIN: 91, MAC: 91, FN: null, PG_UP: 33, PG_DOWN: 34, UP: 38, DOWN: 40, LEFT: 37, RIGHT: 39, ESC: 27, DEL: 46, F1: 112, F2: 113, F3: 114, F4: 115, F5: 116, F6: 117, F7: 118, F8: 119, F9: 120, F10: 121, F11: 122, F12: 123 }, ASC: 'asc', DESC: 'desc', filter: { STARTS_WITH: 2, ENDS_WITH: 4, EXACT: 8, CONTAINS: 16, GREATER_THAN: 32, GREATER_THAN_OR_EQUAL: 64, LESS_THAN: 128, LESS_THAN_OR_EQUAL: 256, NOT_EQUAL: 512, SELECT: 'select', INPUT: 'input' }, aggregationTypes: { sum: 2, count: 4, avg: 8, min: 16, max: 32 }, // TODO(c0bra): Create full list of these somehow. NOTE: do any allow a space before or after them? CURRENCY_SYMBOLS: ['ƒ', '$', '£', '$', '¤', '¥', '៛', '₩', '₱', '฿', '₫'], scrollDirection: { UP: 'up', DOWN: 'down', LEFT: 'left', RIGHT: 'right', NONE: 'none' }, dataChange: { ALL: 'all', EDIT: 'edit', ROW: 'row', COLUMN: 'column', OPTIONS: 'options' }, scrollbars: { NEVER: 0, ALWAYS: 1 //WHEN_NEEDED: 2 } }); })(); angular.module('ui.grid').directive('uiGridCell', ['$compile', '$parse', 'gridUtil', 'uiGridConstants', function ($compile, $parse, gridUtil, uiGridConstants) { var uiGridCell = { priority: 0, scope: false, require: '?^uiGrid', compile: function() { return { pre: function($scope, $elm, $attrs, uiGridCtrl) { function compileTemplate() { var compiledElementFn = $scope.col.compiledElementFn; compiledElementFn($scope, function(clonedElement, scope) { $elm.append(clonedElement); }); } // If the grid controller is present, use it to get the compiled cell template function if (uiGridCtrl && $scope.col.compiledElementFn) { compileTemplate(); } // No controller, compile the element manually (for unit tests) else { if ( uiGridCtrl && !$scope.col.compiledElementFn ){ // gridUtil.logError('Render has been called before precompile. Please log a ui-grid issue'); $scope.col.getCompiledElementFn() .then(function (compiledElementFn) { compiledElementFn($scope, function(clonedElement, scope) { $elm.append(clonedElement); }); }); } else { var html = $scope.col.cellTemplate .replace(uiGridConstants.MODEL_COL_FIELD, 'row.entity.' + gridUtil.preEval($scope.col.field)) .replace(uiGridConstants.COL_FIELD, 'grid.getCellValue(row, col)'); var cellElement = $compile(html)($scope); $elm.append(cellElement); } } }, post: function($scope, $elm, $attrs, uiGridCtrl) { var initColClass = $scope.col.getColClass(false); $elm.addClass(initColClass); var classAdded; var updateClass = function( grid ){ var contents = $elm; if ( classAdded ){ contents.removeClass( classAdded ); classAdded = null; } if (angular.isFunction($scope.col.cellClass)) { classAdded = $scope.col.cellClass($scope.grid, $scope.row, $scope.col, $scope.rowRenderIndex, $scope.colRenderIndex); } else { classAdded = $scope.col.cellClass; } contents.addClass(classAdded); }; if ($scope.col.cellClass) { updateClass(); } // Register a data change watch that would get triggered whenever someone edits a cell or modifies column defs var dataChangeDereg = $scope.grid.registerDataChangeCallback( updateClass, [uiGridConstants.dataChange.COLUMN, uiGridConstants.dataChange.EDIT]); // watch the col and row to see if they change - which would indicate that we've scrolled or sorted or otherwise // changed the row/col that this cell relates to, and we need to re-evaluate cell classes and maybe other things var cellChangeFunction = function( n, o ){ if ( n !== o ) { if ( classAdded || $scope.col.cellClass ){ updateClass(); } // See if the column's internal class has changed var newColClass = $scope.col.getColClass(false); if (newColClass !== initColClass) { $elm.removeClass(initColClass); $elm.addClass(newColClass); initColClass = newColClass; } } }; // TODO(c0bra): Turn this into a deep array watch /* shouldn't be needed any more given track by col.name var colWatchDereg = $scope.$watch( 'col', cellChangeFunction ); */ var rowWatchDereg = $scope.$watch( 'row', cellChangeFunction ); var deregisterFunction = function() { dataChangeDereg(); // colWatchDereg(); rowWatchDereg(); }; $scope.$on( '$destroy', deregisterFunction ); $elm.on( '$destroy', deregisterFunction ); } }; } }; return uiGridCell; }]); (function(){ angular.module('ui.grid') .service('uiGridColumnMenuService', [ 'i18nService', 'uiGridConstants', 'gridUtil', function ( i18nService, uiGridConstants, gridUtil ) { /** * @ngdoc service * @name ui.grid.service:uiGridColumnMenuService * * @description Services for working with column menus, factored out * to make the code easier to understand */ var service = { /** * @ngdoc method * @methodOf ui.grid.service:uiGridColumnMenuService * @name initialize * @description Sets defaults, puts a reference to the $scope on * the uiGridController * @param {$scope} $scope the $scope from the uiGridColumnMenu * @param {controller} uiGridCtrl the uiGridController for the grid * we're on * */ initialize: function( $scope, uiGridCtrl ){ $scope.grid = uiGridCtrl.grid; // Store a reference to this link/controller in the main uiGrid controller // to allow showMenu later uiGridCtrl.columnMenuScope = $scope; // Save whether we're shown or not so the columns can check $scope.menuShown = false; }, /** * @ngdoc method * @methodOf ui.grid.service:uiGridColumnMenuService * @name setColMenuItemWatch * @description Setup a watch on $scope.col.menuItems, and update * menuItems based on this. $scope.col needs to be set by the column * before calling the menu. * @param {$scope} $scope the $scope from the uiGridColumnMenu * @param {controller} uiGridCtrl the uiGridController for the grid * we're on * */ setColMenuItemWatch: function ( $scope ){ var deregFunction = $scope.$watch('col.menuItems', function (n, o) { if (typeof(n) !== 'undefined' && n && angular.isArray(n)) { n.forEach(function (item) { if (typeof(item.context) === 'undefined' || !item.context) { item.context = {}; } item.context.col = $scope.col; }); $scope.menuItems = $scope.defaultMenuItems.concat(n); } else { $scope.menuItems = $scope.defaultMenuItems; } }); $scope.$on( '$destroy', deregFunction ); }, /** * @ngdoc boolean * @name enableSorting * @propertyOf ui.grid.class:GridOptions.columnDef * @description (optional) True by default. When enabled, this setting adds sort * widgets to the column header, allowing sorting of the data in the individual column. */ /** * @ngdoc method * @methodOf ui.grid.service:uiGridColumnMenuService * @name sortable * @description determines whether this column is sortable * @param {$scope} $scope the $scope from the uiGridColumnMenu * */ sortable: function( $scope ) { if ( $scope.grid.options.enableSorting && typeof($scope.col) !== 'undefined' && $scope.col && $scope.col.enableSorting) { return true; } else { return false; } }, /** * @ngdoc method * @methodOf ui.grid.service:uiGridColumnMenuService * @name isActiveSort * @description determines whether the requested sort direction is current active, to * allow highlighting in the menu * @param {$scope} $scope the $scope from the uiGridColumnMenu * @param {string} direction the direction that we'd have selected for us to be active * */ isActiveSort: function( $scope, direction ){ return (typeof($scope.col) !== 'undefined' && typeof($scope.col.sort) !== 'undefined' && typeof($scope.col.sort.direction) !== 'undefined' && $scope.col.sort.direction === direction); }, /** * @ngdoc method * @methodOf ui.grid.service:uiGridColumnMenuService * @name suppressRemoveSort * @description determines whether we should suppress the removeSort option * @param {$scope} $scope the $scope from the uiGridColumnMenu * */ suppressRemoveSort: function( $scope ) { if ($scope.col && $scope.col.suppressRemoveSort) { return true; } else { return false; } }, /** * @ngdoc boolean * @name enableHiding * @propertyOf ui.grid.class:GridOptions.columnDef * @description (optional) True by default. When set to false, this setting prevents a user from hiding the column * using the column menu or the grid menu. */ /** * @ngdoc method * @methodOf ui.grid.service:uiGridColumnMenuService * @name hideable * @description determines whether a column can be hidden, by checking the enableHiding columnDef option * @param {$scope} $scope the $scope from the uiGridColumnMenu * */ hideable: function( $scope ) { if (typeof($scope.col) !== 'undefined' && $scope.col && $scope.col.colDef && $scope.col.colDef.enableHiding === false ) { return false; } else { return true; } }, /** * @ngdoc method * @methodOf ui.grid.service:uiGridColumnMenuService * @name getDefaultMenuItems * @description returns the default menu items for a column menu * @param {$scope} $scope the $scope from the uiGridColumnMenu * */ getDefaultMenuItems: function( $scope ){ return [ { title: i18nService.getSafeText('sort.ascending'), icon: 'ui-grid-icon-sort-alt-up', action: function($event) { $event.stopPropagation(); $scope.sortColumn($event, uiGridConstants.ASC); }, shown: function () { return service.sortable( $scope ); }, active: function() { return service.isActiveSort( $scope, uiGridConstants.ASC); } }, { title: i18nService.getSafeText('sort.descending'), icon: 'ui-grid-icon-sort-alt-down', action: function($event) { $event.stopPropagation(); $scope.sortColumn($event, uiGridConstants.DESC); }, shown: function() { return service.sortable( $scope ); }, active: function() { return service.isActiveSort( $scope, uiGridConstants.DESC); } }, { title: i18nService.getSafeText('sort.remove'), icon: 'ui-grid-icon-cancel', action: function ($event) { $event.stopPropagation(); $scope.unsortColumn(); }, shown: function() { return service.sortable( $scope ) && typeof($scope.col) !== 'undefined' && (typeof($scope.col.sort) !== 'undefined' && typeof($scope.col.sort.direction) !== 'undefined') && $scope.col.sort.direction !== null && !service.suppressRemoveSort( $scope ); } }, { title: i18nService.getSafeText('column.hide'), icon: 'ui-grid-icon-cancel', shown: function() { return service.hideable( $scope ); }, action: function ($event) { $event.stopPropagation(); $scope.hideColumn(); } }, { title: i18nService.getSafeText('columnMenu.close'), screenReaderOnly: true, shown: function(){ return true; }, action: function($event){ $event.stopPropagation(); } } ]; }, /** * @ngdoc method * @methodOf ui.grid.service:uiGridColumnMenuService * @name getColumnElementPosition * @description gets the position information needed to place the column * menu below the column header * @param {$scope} $scope the $scope from the uiGridColumnMenu * @param {GridCol} column the column we want to position below * @param {element} $columnElement the column element we want to position below * @returns {hash} containing left, top, offset, height, width * */ getColumnElementPosition: function( $scope, column, $columnElement ){ var positionData = {}; positionData.left = $columnElement[0].offsetLeft; positionData.top = $columnElement[0].offsetTop; positionData.parentLeft = $columnElement[0].offsetParent.offsetLeft; // Get the grid scrollLeft positionData.offset = 0; if (column.grid.options.offsetLeft) { positionData.offset = column.grid.options.offsetLeft; } positionData.height = gridUtil.elementHeight($columnElement, true); positionData.width = gridUtil.elementWidth($columnElement, true); return positionData; }, /** * @ngdoc method * @methodOf ui.grid.service:uiGridColumnMenuService * @name repositionMenu * @description Reposition the menu below the new column. If the menu has no child nodes * (i.e. it's not currently visible) then we guess it's width at 100, we'll be called again * later to fix it * @param {$scope} $scope the $scope from the uiGridColumnMenu * @param {GridCol} column the column we want to position below * @param {hash} positionData a hash containing left, top, offset, height, width * @param {element} $elm the column menu element that we want to reposition * @param {element} $columnElement the column element that we want to reposition underneath * */ repositionMenu: function( $scope, column, positionData, $elm, $columnElement ) { var menu = $elm[0].querySelectorAll('.ui-grid-menu'); var containerId = column.renderContainer ? column.renderContainer : 'body'; var renderContainer = column.grid.renderContainers[containerId]; // It's possible that the render container of the column we're attaching to is // offset from the grid (i.e. pinned containers), we need to get the difference in the offsetLeft // between the render container and the grid var renderContainerElm = gridUtil.closestElm($columnElement, '.ui-grid-render-container'); var renderContainerOffset = renderContainerElm.getBoundingClientRect().left - $scope.grid.element[0].getBoundingClientRect().left; var containerScrollLeft = renderContainerElm.querySelectorAll('.ui-grid-viewport')[0].scrollLeft; // default value the last width for _this_ column, otherwise last width for _any_ column, otherwise default to 170 var myWidth = column.lastMenuWidth ? column.lastMenuWidth : ( $scope.lastMenuWidth ? $scope.lastMenuWidth : 170); var paddingRight = column.lastMenuPaddingRight ? column.lastMenuPaddingRight : ( $scope.lastMenuPaddingRight ? $scope.lastMenuPaddingRight : 10); if ( menu.length !== 0 ){ var mid = menu[0].querySelectorAll('.ui-grid-menu-mid'); if ( mid.length !== 0 && !angular.element(mid).hasClass('ng-hide') ) { myWidth = gridUtil.elementWidth(menu, true); $scope.lastMenuWidth = myWidth; column.lastMenuWidth = myWidth; // TODO(c0bra): use padding-left/padding-right based on document direction (ltr/rtl), place menu on proper side // Get the column menu right padding paddingRight = parseInt(gridUtil.getStyles(angular.element(menu)[0])['paddingRight'], 10); $scope.lastMenuPaddingRight = paddingRight; column.lastMenuPaddingRight = paddingRight; } } var left = positionData.left + renderContainerOffset - containerScrollLeft + positionData.parentLeft + positionData.width - myWidth + paddingRight; if (left < positionData.offset){ left = positionData.offset; } $elm.css('left', left + 'px'); $elm.css('top', (positionData.top + positionData.height) + 'px'); } }; return service; }]) .directive('uiGridColumnMenu', ['$timeout', 'gridUtil', 'uiGridConstants', 'uiGridColumnMenuService', '$document', function ($timeout, gridUtil, uiGridConstants, uiGridColumnMenuService, $document) { /** * @ngdoc directive * @name ui.grid.directive:uiGridColumnMenu * @description Provides the column menu framework, leverages uiGridMenu underneath * */ var uiGridColumnMenu = { priority: 0, scope: true, require: '^uiGrid', templateUrl: 'ui-grid/uiGridColumnMenu', replace: true, link: function ($scope, $elm, $attrs, uiGridCtrl) { var self = this; uiGridColumnMenuService.initialize( $scope, uiGridCtrl ); $scope.defaultMenuItems = uiGridColumnMenuService.getDefaultMenuItems( $scope ); // Set the menu items for use with the column menu. The user can later add additional items via the watch $scope.menuItems = $scope.defaultMenuItems; uiGridColumnMenuService.setColMenuItemWatch( $scope ); /** * @ngdoc method * @methodOf ui.grid.directive:uiGridColumnMenu * @name showMenu * @description Shows the column menu. If the menu is already displayed it * calls the menu to ask it to hide (it will animate), then it repositions the menu * to the right place whilst hidden (it will make an assumption on menu width), * then it asks the menu to show (it will animate), then it repositions the menu again * once we can calculate it's size. * @param {GridCol} column the column we want to position below * @param {element} $columnElement the column element we want to position below */ $scope.showMenu = function(column, $columnElement, event) { // Swap to this column $scope.col = column; // Get the position information for the column element var colElementPosition = uiGridColumnMenuService.getColumnElementPosition( $scope, column, $columnElement ); if ($scope.menuShown) { // we want to hide, then reposition, then show, but we want to wait for animations // we set a variable, and then rely on the menu-hidden event to call the reposition and show $scope.colElement = $columnElement; $scope.colElementPosition = colElementPosition; $scope.hideThenShow = true; $scope.$broadcast('hide-menu', { originalEvent: event }); } else { self.shown = $scope.menuShown = true; uiGridColumnMenuService.repositionMenu( $scope, column, colElementPosition, $elm, $columnElement ); $scope.colElement = $columnElement; $scope.colElementPosition = colElementPosition; $scope.$broadcast('show-menu', { originalEvent: event }); } }; /** * @ngdoc method * @methodOf ui.grid.directive:uiGridColumnMenu * @name hideMenu * @description Hides the column menu. * @param {boolean} broadcastTrigger true if we were triggered by a broadcast * from the menu itself - in which case don't broadcast again as we'll get * an infinite loop */ $scope.hideMenu = function( broadcastTrigger ) { $scope.menuShown = false; if ( !broadcastTrigger ){ $scope.$broadcast('hide-menu'); } }; $scope.$on('menu-hidden', function() { if ( $scope.hideThenShow ){ delete $scope.hideThenShow; uiGridColumnMenuService.repositionMenu( $scope, $scope.col, $scope.colElementPosition, $elm, $scope.colElement ); $scope.$broadcast('show-menu'); $scope.menuShown = true; } else { $scope.hideMenu( true ); if ($scope.col) { //Focus on the menu button gridUtil.focus.bySelector($document, '.ui-grid-header-cell.' + $scope.col.getColClass()+ ' .ui-grid-column-menu-button', $scope.col.grid, false); } } }); $scope.$on('menu-shown', function() { $timeout( function() { uiGridColumnMenuService.repositionMenu( $scope, $scope.col, $scope.colElementPosition, $elm, $scope.colElement ); delete $scope.colElementPosition; delete $scope.columnElement; }, 200); }); /* Column methods */ $scope.sortColumn = function (event, dir) { event.stopPropagation(); $scope.grid.sortColumn($scope.col, dir, true) .then(function () { $scope.grid.refresh(); $scope.hideMenu(); }); }; $scope.unsortColumn = function () { $scope.col.unsort(); $scope.grid.refresh(); $scope.hideMenu(); }; //Since we are hiding this column the default hide action will fail so we need to focus somewhere else. var setFocusOnHideColumn = function(){ $timeout(function(){ // Get the UID of the first var focusToGridMenu = function(){ return gridUtil.focus.byId('grid-menu', $scope.grid); }; var thisIndex; $scope.grid.columns.some(function(element, index){ if (angular.equals(element, $scope.col)) { thisIndex = index; return true; } }); var previousVisibleCol; // Try and find the next lower or nearest column to focus on $scope.grid.columns.some(function(element, index){ if (!element.visible){ return false; } // This columns index is below the current column index else if ( index < thisIndex){ previousVisibleCol = element; } // This elements index is above this column index and we haven't found one that is lower else if ( index > thisIndex && !previousVisibleCol) { // This is the next best thing previousVisibleCol = element; // We've found one so use it. return true; } // We've reached an element with an index above this column and the previousVisibleCol variable has been set else if (index > thisIndex && previousVisibleCol) { // We are done. return true; } }); // If found then focus on it if (previousVisibleCol){ var colClass = previousVisibleCol.getColClass(); gridUtil.focus.bySelector($document, '.ui-grid-header-cell.' + colClass+ ' .ui-grid-header-cell-primary-focus', true).then(angular.noop, function(reason){ if (reason !== 'canceled'){ // If this is canceled then don't perform the action //The fallback action is to focus on the grid menu return focusToGridMenu(); } }); } else { // Fallback action to focus on the grid menu focusToGridMenu(); } }); }; $scope.hideColumn = function () { $scope.col.colDef.visible = false; $scope.col.visible = false; $scope.grid.queueGridRefresh(); $scope.hideMenu(); $scope.grid.api.core.notifyDataChange( uiGridConstants.dataChange.COLUMN ); $scope.grid.api.core.raise.columnVisibilityChanged( $scope.col ); // We are hiding so the default action of focusing on the button that opened this menu will fail. setFocusOnHideColumn(); }; }, controller: ['$scope', function ($scope) { var self = this; $scope.$watch('menuItems', function (n, o) { self.menuItems = n; }); }] }; return uiGridColumnMenu; }]); })(); (function(){ 'use strict'; angular.module('ui.grid').directive('uiGridFilter', ['$compile', '$templateCache', 'i18nService', 'gridUtil', function ($compile, $templateCache, i18nService, gridUtil) { return { compile: function() { return { pre: function ($scope, $elm, $attrs, controllers) { $scope.col.updateFilters = function( filterable ){ $elm.children().remove(); if ( filterable ){ var template = $scope.col.filterHeaderTemplate; $elm.append($compile(template)($scope)); } }; $scope.$on( '$destroy', function() { delete $scope.col.updateFilters; }); }, post: function ($scope, $elm, $attrs, controllers){ $scope.aria = i18nService.getSafeText('headerCell.aria'); $scope.removeFilter = function(colFilter, index){ colFilter.term = null; //Set the focus to the filter input after the action disables the button gridUtil.focus.bySelector($elm, '.ui-grid-filter-input-' + index); }; } }; } }; }]); })(); (function () { 'use strict'; angular.module('ui.grid').directive('uiGridFooterCell', ['$timeout', 'gridUtil', 'uiGridConstants', '$compile', function ($timeout, gridUtil, uiGridConstants, $compile) { var uiGridFooterCell = { priority: 0, scope: { col: '=', row: '=', renderIndex: '=' }, replace: true, require: '^uiGrid', compile: function compile(tElement, tAttrs, transclude) { return { pre: function ($scope, $elm, $attrs, uiGridCtrl) { var cellFooter = $compile($scope.col.footerCellTemplate)($scope); $elm.append(cellFooter); }, post: function ($scope, $elm, $attrs, uiGridCtrl) { //$elm.addClass($scope.col.getColClass(false)); $scope.grid = uiGridCtrl.grid; var initColClass = $scope.col.getColClass(false); $elm.addClass(initColClass); // apply any footerCellClass var classAdded; var updateClass = function( grid ){ var contents = $elm; if ( classAdded ){ contents.removeClass( classAdded ); classAdded = null; } if (angular.isFunction($scope.col.footerCellClass)) { classAdded = $scope.col.footerCellClass($scope.grid, $scope.row, $scope.col, $scope.rowRenderIndex, $scope.colRenderIndex); } else { classAdded = $scope.col.footerCellClass; } contents.addClass(classAdded); }; if ($scope.col.footerCellClass) { updateClass(); } $scope.col.updateAggregationValue(); // Watch for column changes so we can alter the col cell class properly /* shouldn't be needed any more, given track by col.name $scope.$watch('col', function (n, o) { if (n !== o) { // See if the column's internal class has changed var newColClass = $scope.col.getColClass(false); if (newColClass !== initColClass) { $elm.removeClass(initColClass); $elm.addClass(newColClass); initColClass = newColClass; } } }); */ // Register a data change watch that would get triggered whenever someone edits a cell or modifies column defs var dataChangeDereg = $scope.grid.registerDataChangeCallback( updateClass, [uiGridConstants.dataChange.COLUMN]); // listen for visible rows change and update aggregation values $scope.grid.api.core.on.rowsRendered( $scope, $scope.col.updateAggregationValue ); $scope.grid.api.core.on.rowsRendered( $scope, updateClass ); $scope.$on( '$destroy', dataChangeDereg ); } }; } }; return uiGridFooterCell; }]); })(); (function () { 'use strict'; angular.module('ui.grid').directive('uiGridFooter', ['$templateCache', '$compile', 'uiGridConstants', 'gridUtil', '$timeout', function ($templateCache, $compile, uiGridConstants, gridUtil, $timeout) { return { restrict: 'EA', replace: true, // priority: 1000, require: ['^uiGrid', '^uiGridRenderContainer'], scope: true, compile: function ($elm, $attrs) { return { pre: function ($scope, $elm, $attrs, controllers) { var uiGridCtrl = controllers[0]; var containerCtrl = controllers[1]; $scope.grid = uiGridCtrl.grid; $scope.colContainer = containerCtrl.colContainer; containerCtrl.footer = $elm; var footerTemplate = $scope.grid.options.footerTemplate; gridUtil.getTemplate(footerTemplate) .then(function (contents) { var template = angular.element(contents); var newElm = $compile(template)($scope); $elm.append(newElm); if (containerCtrl) { // Inject a reference to the footer viewport (if it exists) into the grid controller for use in the horizontal scroll handler below var footerViewport = $elm[0].getElementsByClassName('ui-grid-footer-viewport')[0]; if (footerViewport) { containerCtrl.footerViewport = footerViewport; } } }); }, post: function ($scope, $elm, $attrs, controllers) { var uiGridCtrl = controllers[0]; var containerCtrl = controllers[1]; // gridUtil.logDebug('ui-grid-footer link'); var grid = uiGridCtrl.grid; // Don't animate footer cells gridUtil.disableAnimations($elm); containerCtrl.footer = $elm; var footerViewport = $elm[0].getElementsByClassName('ui-grid-footer-viewport')[0]; if (footerViewport) { containerCtrl.footerViewport = footerViewport; } } }; } }; }]); })(); (function () { 'use strict'; angular.module('ui.grid').directive('uiGridGridFooter', ['$templateCache', '$compile', 'uiGridConstants', 'gridUtil', '$timeout', function ($templateCache, $compile, uiGridConstants, gridUtil, $timeout) { return { restrict: 'EA', replace: true, // priority: 1000, require: '^uiGrid', scope: true, compile: function ($elm, $attrs) { return { pre: function ($scope, $elm, $attrs, uiGridCtrl) { $scope.grid = uiGridCtrl.grid; var footerTemplate = $scope.grid.options.gridFooterTemplate; gridUtil.getTemplate(footerTemplate) .then(function (contents) { var template = angular.element(contents); var newElm = $compile(template)($scope); $elm.append(newElm); }); }, post: function ($scope, $elm, $attrs, controllers) { } }; } }; }]); })(); (function(){ 'use strict'; angular.module('ui.grid').directive('uiGridGroupPanel', ["$compile", "uiGridConstants", "gridUtil", function($compile, uiGridConstants, gridUtil) { var defaultTemplate = 'ui-grid/ui-grid-group-panel'; return { restrict: 'EA', replace: true, require: '?^uiGrid', scope: false, compile: function($elm, $attrs) { return { pre: function ($scope, $elm, $attrs, uiGridCtrl) { var groupPanelTemplate = $scope.grid.options.groupPanelTemplate || defaultTemplate; gridUtil.getTemplate(groupPanelTemplate) .then(function (contents) { var template = angular.element(contents); var newElm = $compile(template)($scope); $elm.append(newElm); }); }, post: function ($scope, $elm, $attrs, uiGridCtrl) { $elm.bind('$destroy', function() { // scrollUnbinder(); }); } }; } }; }]); })(); (function(){ 'use strict'; angular.module('ui.grid').directive('uiGridHeaderCell', ['$compile', '$timeout', '$window', '$document', 'gridUtil', 'uiGridConstants', 'ScrollEvent', 'i18nService', function ($compile, $timeout, $window, $document, gridUtil, uiGridConstants, ScrollEvent, i18nService) { // Do stuff after mouse has been down this many ms on the header cell var mousedownTimeout = 500; var changeModeTimeout = 500; // length of time between a touch event and a mouse event being recognised again, and vice versa var uiGridHeaderCell = { priority: 0, scope: { col: '=', row: '=', renderIndex: '=' }, require: ['^uiGrid', '^uiGridRenderContainer'], replace: true, compile: function() { return { pre: function ($scope, $elm, $attrs) { var cellHeader = $compile($scope.col.headerCellTemplate)($scope); $elm.append(cellHeader); }, post: function ($scope, $elm, $attrs, controllers) { var uiGridCtrl = controllers[0]; var renderContainerCtrl = controllers[1]; $scope.i18n = { headerCell: i18nService.getSafeText('headerCell'), sort: i18nService.getSafeText('sort') }; $scope.getSortDirectionAriaLabel = function(){ var col = $scope.col; //Trying to recreate this sort of thing but it was getting messy having it in the template. //Sort direction {{col.sort.direction == asc ? 'ascending' : ( col.sort.direction == desc ? 'descending':'none')}}. {{col.sort.priority ? {{columnPriorityText}} {{col.sort.priority}} : ''} var sortDirectionText = col.sort.direction === uiGridConstants.ASC ? $scope.i18n.sort.ascending : ( col.sort.direction === uiGridConstants.DESC ? $scope.i18n.sort.descending : $scope.i18n.sort.none); var label = sortDirectionText; //Append the priority if it exists if (col.sort.priority) { label = label + '. ' + $scope.i18n.headerCell.priority + ' ' + col.sort.priority; } return label; }; $scope.grid = uiGridCtrl.grid; $scope.renderContainer = uiGridCtrl.grid.renderContainers[renderContainerCtrl.containerId]; var initColClass = $scope.col.getColClass(false); $elm.addClass(initColClass); // Hide the menu by default $scope.menuShown = false; // Put asc and desc sort directions in scope $scope.asc = uiGridConstants.ASC; $scope.desc = uiGridConstants.DESC; // Store a reference to menu element var $colMenu = angular.element( $elm[0].querySelectorAll('.ui-grid-header-cell-menu') ); var $contentsElm = angular.element( $elm[0].querySelectorAll('.ui-grid-cell-contents') ); // apply any headerCellClass var classAdded; var previousMouseX; // filter watchers var filterDeregisters = []; /* * Our basic approach here for event handlers is that we listen for a down event (mousedown or touchstart). * Once we have a down event, we need to work out whether we have a click, a drag, or a * hold. A click would sort the grid (if sortable). A drag would be used by moveable, so * we ignore it. A hold would open the menu. * * So, on down event, we put in place handlers for move and up events, and a timer. If the * timer expires before we see a move or up, then we have a long press and hence a column menu open. * If the up happens before the timer, then we have a click, and we sort if the column is sortable. * If a move happens before the timer, then we are doing column move, so we do nothing, the moveable feature * will handle it. * * To deal with touch enabled devices that also have mice, we only create our handlers when * we get the down event, and we create the corresponding handlers - if we're touchstart then * we get touchmove and touchend, if we're mousedown then we get mousemove and mouseup. * * We also suppress the click action whilst this is happening - otherwise after the mouseup there * will be a click event and that can cause the column menu to close * */ $scope.downFn = function( event ){ event.stopPropagation(); if (typeof(event.originalEvent) !== 'undefined' && event.originalEvent !== undefined) { event = event.originalEvent; } // Don't show the menu if it's not the left button if (event.button && event.button !== 0) { return; } previousMouseX = event.pageX; $scope.mousedownStartTime = (new Date()).getTime(); $scope.mousedownTimeout = $timeout(function() { }, mousedownTimeout); $scope.mousedownTimeout.then(function () { if ( $scope.colMenu ) { uiGridCtrl.columnMenuScope.showMenu($scope.col, $elm, event); } }); uiGridCtrl.fireEvent(uiGridConstants.events.COLUMN_HEADER_CLICK, {event: event, columnName: $scope.col.colDef.name}); $scope.offAllEvents(); if ( event.type === 'touchstart'){ $document.on('touchend', $scope.upFn); $document.on('touchmove', $scope.moveFn); } else if ( event.type === 'mousedown' ){ $document.on('mouseup', $scope.upFn); $document.on('mousemove', $scope.moveFn); } }; $scope.upFn = function( event ){ event.stopPropagation(); $timeout.cancel($scope.mousedownTimeout); $scope.offAllEvents(); $scope.onDownEvents(event.type); var mousedownEndTime = (new Date()).getTime(); var mousedownTime = mousedownEndTime - $scope.mousedownStartTime; if (mousedownTime > mousedownTimeout) { // long click, handled above with mousedown } else { // short click if ( $scope.sortable ){ $scope.handleClick(event); } } }; $scope.moveFn = function( event ){ // Chrome is known to fire some bogus move events. var changeValue = event.pageX - previousMouseX; if ( changeValue === 0 ){ return; } // we're a move, so do nothing and leave for column move (if enabled) to take over $timeout.cancel($scope.mousedownTimeout); $scope.offAllEvents(); $scope.onDownEvents(event.type); }; $scope.clickFn = function ( event ){ event.stopPropagation(); $contentsElm.off('click', $scope.clickFn); }; $scope.offAllEvents = function(){ $contentsElm.off('touchstart', $scope.downFn); $contentsElm.off('mousedown', $scope.downFn); $document.off('touchend', $scope.upFn); $document.off('mouseup', $scope.upFn); $document.off('touchmove', $scope.moveFn); $document.off('mousemove', $scope.moveFn); $contentsElm.off('click', $scope.clickFn); }; $scope.onDownEvents = function( type ){ // If there is a previous event, then wait a while before // activating the other mode - i.e. if the last event was a touch event then // don't enable mouse events for a wee while (500ms or so) // Avoids problems with devices that emulate mouse events when you have touch events switch (type){ case 'touchmove': case 'touchend': $contentsElm.on('click', $scope.clickFn); $contentsElm.on('touchstart', $scope.downFn); $timeout(function(){ $contentsElm.on('mousedown', $scope.downFn); }, changeModeTimeout); break; case 'mousemove': case 'mouseup': $contentsElm.on('click', $scope.clickFn); $contentsElm.on('mousedown', $scope.downFn); $timeout(function(){ $contentsElm.on('touchstart', $scope.downFn); }, changeModeTimeout); break; default: $contentsElm.on('click', $scope.clickFn); $contentsElm.on('touchstart', $scope.downFn); $contentsElm.on('mousedown', $scope.downFn); } }; var updateHeaderOptions = function( grid ){ var contents = $elm; if ( classAdded ){ contents.removeClass( classAdded ); classAdded = null; } if (angular.isFunction($scope.col.headerCellClass)) { classAdded = $scope.col.headerCellClass($scope.grid, $scope.row, $scope.col, $scope.rowRenderIndex, $scope.colRenderIndex); } else { classAdded = $scope.col.headerCellClass; } contents.addClass(classAdded); var rightMostContainer = $scope.grid.renderContainers['right'] ? $scope.grid.renderContainers['right'] : $scope.grid.renderContainers['body']; $scope.isLastCol = ( $scope.col === rightMostContainer.visibleColumnCache[ rightMostContainer.visibleColumnCache.length - 1 ] ); // Figure out whether this column is sortable or not if (uiGridCtrl.grid.options.enableSorting && $scope.col.enableSorting) { $scope.sortable = true; } else { $scope.sortable = false; } // Figure out whether this column is filterable or not var oldFilterable = $scope.filterable; if (uiGridCtrl.grid.options.enableFiltering && $scope.col.enableFiltering) { $scope.filterable = true; } else { $scope.filterable = false; } if ( oldFilterable !== $scope.filterable){ if ( typeof($scope.col.updateFilters) !== 'undefined' ){ $scope.col.updateFilters($scope.filterable); } // if column is filterable add a filter watcher if ($scope.filterable) { $scope.col.filters.forEach( function(filter, i) { filterDeregisters.push($scope.$watch('col.filters[' + i + '].term', function(n, o) { if (n !== o) { uiGridCtrl.grid.api.core.raise.filterChanged(); uiGridCtrl.grid.api.core.notifyDataChange( uiGridConstants.dataChange.COLUMN ); uiGridCtrl.grid.queueGridRefresh(); } })); }); $scope.$on('$destroy', function() { filterDeregisters.forEach( function(filterDeregister) { filterDeregister(); }); }); } else { filterDeregisters.forEach( function(filterDeregister) { filterDeregister(); }); } } // figure out whether we support column menus if ($scope.col.grid.options && $scope.col.grid.options.enableColumnMenus !== false && $scope.col.colDef && $scope.col.colDef.enableColumnMenu !== false){ $scope.colMenu = true; } else { $scope.colMenu = false; } /** * @ngdoc property * @name enableColumnMenu * @propertyOf ui.grid.class:GridOptions.columnDef * @description if column menus are enabled, controls the column menus for this specific * column (i.e. if gridOptions.enableColumnMenus, then you can control column menus * using this option. If gridOptions.enableColumnMenus === false then you get no column * menus irrespective of the value of this option ). Defaults to true. * */ /** * @ngdoc property * @name enableColumnMenus * @propertyOf ui.grid.class:GridOptions.columnDef * @description Override for column menus everywhere - if set to false then you get no * column menus. Defaults to true. * */ $scope.offAllEvents(); if ($scope.sortable || $scope.colMenu) { $scope.onDownEvents(); $scope.$on('$destroy', function () { $scope.offAllEvents(); }); } }; /* $scope.$watch('col', function (n, o) { if (n !== o) { // See if the column's internal class has changed var newColClass = $scope.col.getColClass(false); if (newColClass !== initColClass) { $elm.removeClass(initColClass); $elm.addClass(newColClass); initColClass = newColClass; } } }); */ updateHeaderOptions(); // Register a data change watch that would get triggered whenever someone edits a cell or modifies column defs var dataChangeDereg = $scope.grid.registerDataChangeCallback( updateHeaderOptions, [uiGridConstants.dataChange.COLUMN]); $scope.$on( '$destroy', dataChangeDereg ); $scope.handleClick = function(event) { // If the shift key is being held down, add this column to the sort var add = false; if (event.shiftKey) { add = true; } // Sort this column then rebuild the grid's rows uiGridCtrl.grid.sortColumn($scope.col, add) .then(function () { if (uiGridCtrl.columnMenuScope) { uiGridCtrl.columnMenuScope.hideMenu(); } uiGridCtrl.grid.refresh(); }); }; $scope.toggleMenu = function(event) { event.stopPropagation(); // If the menu is already showing... if (uiGridCtrl.columnMenuScope.menuShown) { // ... and we're the column the menu is on... if (uiGridCtrl.columnMenuScope.col === $scope.col) { // ... hide it uiGridCtrl.columnMenuScope.hideMenu(); } // ... and we're NOT the column the menu is on else { // ... move the menu to our column uiGridCtrl.columnMenuScope.showMenu($scope.col, $elm); } } // If the menu is NOT showing else { // ... show it on our column uiGridCtrl.columnMenuScope.showMenu($scope.col, $elm); } }; } }; } }; return uiGridHeaderCell; }]); })(); (function(){ 'use strict'; angular.module('ui.grid').directive('uiGridHeader', ['$templateCache', '$compile', 'uiGridConstants', 'gridUtil', '$timeout', 'ScrollEvent', function($templateCache, $compile, uiGridConstants, gridUtil, $timeout, ScrollEvent) { var defaultTemplate = 'ui-grid/ui-grid-header'; var emptyTemplate = 'ui-grid/ui-grid-no-header'; return { restrict: 'EA', // templateUrl: 'ui-grid/ui-grid-header', replace: true, // priority: 1000, require: ['^uiGrid', '^uiGridRenderContainer'], scope: true, compile: function($elm, $attrs) { return { pre: function ($scope, $elm, $attrs, controllers) { var uiGridCtrl = controllers[0]; var containerCtrl = controllers[1]; $scope.grid = uiGridCtrl.grid; $scope.colContainer = containerCtrl.colContainer; updateHeaderReferences(); var headerTemplate; if (!$scope.grid.options.showHeader) { headerTemplate = emptyTemplate; } else { headerTemplate = ($scope.grid.options.headerTemplate) ? $scope.grid.options.headerTemplate : defaultTemplate; } gridUtil.getTemplate(headerTemplate) .then(function (contents) { var template = angular.element(contents); var newElm = $compile(template)($scope); $elm.replaceWith(newElm); // And update $elm to be the new element $elm = newElm; updateHeaderReferences(); if (containerCtrl) { // Inject a reference to the header viewport (if it exists) into the grid controller for use in the horizontal scroll handler below var headerViewport = $elm[0].getElementsByClassName('ui-grid-header-viewport')[0]; if (headerViewport) { containerCtrl.headerViewport = headerViewport; angular.element(headerViewport).on('scroll', scrollHandler); $scope.$on('$destroy', function () { angular.element(headerViewport).off('scroll', scrollHandler); }); } } $scope.grid.queueRefresh(); }); function updateHeaderReferences() { containerCtrl.header = containerCtrl.colContainer.header = $elm; var headerCanvases = $elm[0].getElementsByClassName('ui-grid-header-canvas'); if (headerCanvases.length > 0) { containerCtrl.headerCanvas = containerCtrl.colContainer.headerCanvas = headerCanvases[0]; } else { containerCtrl.headerCanvas = null; } } function scrollHandler(evt) { if (uiGridCtrl.grid.isScrollingHorizontally) { return; } var newScrollLeft = gridUtil.normalizeScrollLeft(containerCtrl.headerViewport, uiGridCtrl.grid); var horizScrollPercentage = containerCtrl.colContainer.scrollHorizontal(newScrollLeft); var scrollEvent = new ScrollEvent(uiGridCtrl.grid, null, containerCtrl.colContainer, ScrollEvent.Sources.ViewPortScroll); scrollEvent.newScrollLeft = newScrollLeft; if ( horizScrollPercentage > -1 ){ scrollEvent.x = { percentage: horizScrollPercentage }; } uiGridCtrl.grid.scrollContainers(null, scrollEvent); } }, post: function ($scope, $elm, $attrs, controllers) { var uiGridCtrl = controllers[0]; var containerCtrl = controllers[1]; // gridUtil.logDebug('ui-grid-header link'); var grid = uiGridCtrl.grid; // Don't animate header cells gridUtil.disableAnimations($elm); function updateColumnWidths() { // this styleBuilder always runs after the renderContainer, so we can rely on the column widths // already being populated correctly var columnCache = containerCtrl.colContainer.visibleColumnCache; // Build the CSS // uiGridCtrl.grid.columns.forEach(function (column) { var ret = ''; var canvasWidth = 0; columnCache.forEach(function (column) { ret = ret + column.getColClassDefinition(); canvasWidth += column.drawnWidth; }); containerCtrl.colContainer.canvasWidth = canvasWidth; // Return the styles back to buildStyles which pops them into the `customStyles` scope variable return ret; } containerCtrl.header = $elm; var headerViewport = $elm[0].getElementsByClassName('ui-grid-header-viewport')[0]; if (headerViewport) { containerCtrl.headerViewport = headerViewport; } //todo: remove this if by injecting gridCtrl into unit tests if (uiGridCtrl) { uiGridCtrl.grid.registerStyleComputation({ priority: 15, func: updateColumnWidths }); } } }; } }; }]); })(); (function(){ angular.module('ui.grid') .service('uiGridGridMenuService', [ 'gridUtil', 'i18nService', 'uiGridConstants', function( gridUtil, i18nService, uiGridConstants ) { /** * @ngdoc service * @name ui.grid.gridMenuService * * @description Methods for working with the grid menu */ var service = { /** * @ngdoc method * @methodOf ui.grid.gridMenuService * @name initialize * @description Sets up the gridMenu. Most importantly, sets our * scope onto the grid object as grid.gridMenuScope, allowing us * to operate when passed only the grid. Second most importantly, * we register the 'addToGridMenu' and 'removeFromGridMenu' methods * on the core api. * @param {$scope} $scope the scope of this gridMenu * @param {Grid} grid the grid to which this gridMenu is associated */ initialize: function( $scope, grid ){ grid.gridMenuScope = $scope; $scope.grid = grid; $scope.registeredMenuItems = []; // not certain this is needed, but would be bad to create a memory leak $scope.$on('$destroy', function() { if ( $scope.grid && $scope.grid.gridMenuScope ){ $scope.grid.gridMenuScope = null; } if ( $scope.grid ){ $scope.grid = null; } if ( $scope.registeredMenuItems ){ $scope.registeredMenuItems = null; } }); $scope.registeredMenuItems = []; /** * @ngdoc function * @name addToGridMenu * @methodOf ui.grid.core.api:PublicApi * @description add items to the grid menu. Used by features * to add their menu items if they are enabled, can also be used by * end users to add menu items. This method has the advantage of allowing * remove again, which can simplify management of which items are included * in the menu when. (Noting that in most cases the shown and active functions * provide a better way to handle visibility of menu items) * @param {Grid} grid the grid on which we are acting * @param {array} items menu items in the format as described in the tutorial, with * the added note that if you want to use remove you must also specify an `id` field, * which is provided when you want to remove an item. The id should be unique. * */ grid.api.registerMethod( 'core', 'addToGridMenu', service.addToGridMenu ); /** * @ngdoc function * @name removeFromGridMenu * @methodOf ui.grid.core.api:PublicApi * @description Remove an item from the grid menu based on a provided id. Assumes * that the id is unique, removes only the last instance of that id. Does nothing if * the specified id is not found * @param {Grid} grid the grid on which we are acting * @param {string} id the id we'd like to remove from the menu * */ grid.api.registerMethod( 'core', 'removeFromGridMenu', service.removeFromGridMenu ); }, /** * @ngdoc function * @name addToGridMenu * @propertyOf ui.grid.gridMenuService * @description add items to the grid menu. Used by features * to add their menu items if they are enabled, can also be used by * end users to add menu items. This method has the advantage of allowing * remove again, which can simplify management of which items are included * in the menu when. (Noting that in most cases the shown and active functions * provide a better way to handle visibility of menu items) * @param {Grid} grid the grid on which we are acting * @param {array} items menu items in the format as described in the tutorial, with * the added note that if you want to use remove you must also specify an `id` field, * which is provided when you want to remove an item. The id should be unique. * */ addToGridMenu: function( grid, menuItems ) { if ( !angular.isArray( menuItems ) ) { gridUtil.logError( 'addToGridMenu: menuItems must be an array, and is not, not adding any items'); } else { if ( grid.gridMenuScope ){ grid.gridMenuScope.registeredMenuItems = grid.gridMenuScope.registeredMenuItems ? grid.gridMenuScope.registeredMenuItems : []; grid.gridMenuScope.registeredMenuItems = grid.gridMenuScope.registeredMenuItems.concat( menuItems ); } else { gridUtil.logError( 'Asked to addToGridMenu, but gridMenuScope not present. Timing issue? Please log issue with ui-grid'); } } }, /** * @ngdoc function * @name removeFromGridMenu * @methodOf ui.grid.gridMenuService * @description Remove an item from the grid menu based on a provided id. Assumes * that the id is unique, removes only the last instance of that id. Does nothing if * the specified id is not found. If there is no gridMenuScope or registeredMenuItems * then do nothing silently - the desired result is those menu items not be present and they * aren't. * @param {Grid} grid the grid on which we are acting * @param {string} id the id we'd like to remove from the menu * */ removeFromGridMenu: function( grid, id ){ var foundIndex = -1; if ( grid && grid.gridMenuScope ){ grid.gridMenuScope.registeredMenuItems.forEach( function( value, index ) { if ( value.id === id ){ if (foundIndex > -1) { gridUtil.logError( 'removeFromGridMenu: found multiple items with the same id, removing only the last' ); } else { foundIndex = index; } } }); } if ( foundIndex > -1 ){ grid.gridMenuScope.registeredMenuItems.splice( foundIndex, 1 ); } }, /** * @ngdoc array * @name gridMenuCustomItems * @propertyOf ui.grid.class:GridOptions * @description (optional) An array of menu items that should be added to * the gridMenu. Follow the format documented in the tutorial for column * menu customisation. The context provided to the action function will * include context.grid. An alternative if working with dynamic menus is to use the * provided api - core.addToGridMenu and core.removeFromGridMenu, which handles * some of the management of items for you. * */ /** * @ngdoc boolean * @name gridMenuShowHideColumns * @propertyOf ui.grid.class:GridOptions * @description true by default, whether the grid menu should allow hide/show * of columns * */ /** * @ngdoc method * @methodOf ui.grid.gridMenuService * @name getMenuItems * @description Decides the menu items to show in the menu. This is a * combination of: * * - the default menu items that are always included, * - any menu items that have been provided through the addMenuItem api. These * are typically added by features within the grid * - any menu items included in grid.options.gridMenuCustomItems. These can be * changed dynamically, as they're always recalculated whenever we show the * menu * @param {$scope} $scope the scope of this gridMenu, from which we can find all * the information that we need * @returns {array} an array of menu items that can be shown */ getMenuItems: function( $scope ) { var menuItems = [ // this is where we add any menu items we want to always include ]; if ( $scope.grid.options.gridMenuCustomItems ){ if ( !angular.isArray( $scope.grid.options.gridMenuCustomItems ) ){ gridUtil.logError( 'gridOptions.gridMenuCustomItems must be an array, and is not'); } else { menuItems = menuItems.concat( $scope.grid.options.gridMenuCustomItems ); } } var clearFilters = [{ title: i18nService.getSafeText('gridMenu.clearAllFilters'), action: function ($event) { $scope.grid.clearAllFilters(undefined, true, undefined); }, shown: function() { return $scope.grid.options.enableFiltering; }, order: 100 }]; menuItems = menuItems.concat( clearFilters ); menuItems = menuItems.concat( $scope.registeredMenuItems ); if ( $scope.grid.options.gridMenuShowHideColumns !== false ){ menuItems = menuItems.concat( service.showHideColumns( $scope ) ); } menuItems.sort(function(a, b){ return a.order - b.order; }); return menuItems; }, /** * @ngdoc array * @name gridMenuTitleFilter * @propertyOf ui.grid.class:GridOptions * @description (optional) A function that takes a title string * (usually the col.displayName), and converts it into a display value. The function * must return either a string or a promise. * * Used for internationalization of the grid menu column names - for angular-translate * you can pass $translate as the function, for i18nService you can pass getSafeText as the * function * @example * <pre> * gridOptions = { * gridMenuTitleFilter: $translate * } * </pre> */ /** * @ngdoc method * @methodOf ui.grid.gridMenuService * @name showHideColumns * @description Adds two menu items for each of the columns in columnDefs. One * menu item for hide, one menu item for show. Each is visible when appropriate * (show when column is not visible, hide when column is visible). Each toggles * the visible property on the columnDef using toggleColumnVisibility * @param {$scope} $scope of a gridMenu, which contains a reference to the grid */ showHideColumns: function( $scope ){ var showHideColumns = []; if ( !$scope.grid.options.columnDefs || $scope.grid.options.columnDefs.length === 0 || $scope.grid.columns.length === 0 ) { return showHideColumns; } // add header for columns showHideColumns.push({ title: i18nService.getSafeText('gridMenu.columns'), order: 300 }); $scope.grid.options.gridMenuTitleFilter = $scope.grid.options.gridMenuTitleFilter ? $scope.grid.options.gridMenuTitleFilter : function( title ) { return title; }; $scope.grid.options.columnDefs.forEach( function( colDef, index ){ if ( colDef.enableHiding !== false ){ // add hide menu item - shows an OK icon as we only show when column is already visible var menuItem = { icon: 'ui-grid-icon-ok', action: function($event) { $event.stopPropagation(); service.toggleColumnVisibility( this.context.gridCol ); }, shown: function() { return this.context.gridCol.colDef.visible === true || this.context.gridCol.colDef.visible === undefined; }, context: { gridCol: $scope.grid.getColumn(colDef.name || colDef.field) }, leaveOpen: true, order: 301 + index * 2 }; service.setMenuItemTitle( menuItem, colDef, $scope.grid ); showHideColumns.push( menuItem ); // add show menu item - shows no icon as we only show when column is invisible menuItem = { icon: 'ui-grid-icon-cancel', action: function($event) { $event.stopPropagation(); service.toggleColumnVisibility( this.context.gridCol ); }, shown: function() { return !(this.context.gridCol.colDef.visible === true || this.context.gridCol.colDef.visible === undefined); }, context: { gridCol: $scope.grid.getColumn(colDef.name || colDef.field) }, leaveOpen: true, order: 301 + index * 2 + 1 }; service.setMenuItemTitle( menuItem, colDef, $scope.grid ); showHideColumns.push( menuItem ); } }); return showHideColumns; }, /** * @ngdoc method * @methodOf ui.grid.gridMenuService * @name setMenuItemTitle * @description Handles the response from gridMenuTitleFilter, adding it directly to the menu * item if it returns a string, otherwise waiting for the promise to resolve or reject then * putting the result into the title * @param {object} menuItem the menuItem we want to put the title on * @param {object} colDef the colDef from which we can get displayName, name or field * @param {Grid} grid the grid, from which we can get the options.gridMenuTitleFilter * */ setMenuItemTitle: function( menuItem, colDef, grid ){ var title = grid.options.gridMenuTitleFilter( colDef.displayName || gridUtil.readableColumnName(colDef.name) || colDef.field ); if ( typeof(title) === 'string' ){ menuItem.title = title; } else if ( title.then ){ // must be a promise menuItem.title = ""; title.then( function( successValue ) { menuItem.title = successValue; }, function( errorValue ) { menuItem.title = errorValue; }); } else { gridUtil.logError('Expected gridMenuTitleFilter to return a string or a promise, it has returned neither, bad config'); menuItem.title = 'badconfig'; } }, /** * @ngdoc method * @methodOf ui.grid.gridMenuService * @name toggleColumnVisibility * @description Toggles the visibility of an individual column. Expects to be * provided a context that has on it a gridColumn, which is the column that * we'll operate upon. We change the visibility, and refresh the grid as appropriate * @param {GridCol} gridCol the column that we want to toggle * */ toggleColumnVisibility: function( gridCol ) { gridCol.colDef.visible = !( gridCol.colDef.visible === true || gridCol.colDef.visible === undefined ); gridCol.grid.refresh(); gridCol.grid.api.core.notifyDataChange( uiGridConstants.dataChange.COLUMN ); gridCol.grid.api.core.raise.columnVisibilityChanged( gridCol ); } }; return service; }]) .directive('uiGridMenuButton', ['gridUtil', 'uiGridConstants', 'uiGridGridMenuService', 'i18nService', function (gridUtil, uiGridConstants, uiGridGridMenuService, i18nService) { return { priority: 0, scope: true, require: ['^uiGrid'], templateUrl: 'ui-grid/ui-grid-menu-button', replace: true, link: function ($scope, $elm, $attrs, controllers) { var uiGridCtrl = controllers[0]; // For the aria label $scope.i18n = { aria: i18nService.getSafeText('gridMenu.aria') }; uiGridGridMenuService.initialize($scope, uiGridCtrl.grid); $scope.shown = false; $scope.toggleMenu = function () { if ( $scope.shown ){ $scope.$broadcast('hide-menu'); $scope.shown = false; } else { $scope.menuItems = uiGridGridMenuService.getMenuItems( $scope ); $scope.$broadcast('show-menu'); $scope.shown = true; } }; $scope.$on('menu-hidden', function() { $scope.shown = false; gridUtil.focus.bySelector($elm, '.ui-grid-icon-container'); }); } }; }]); })(); (function(){ /** * @ngdoc directive * @name ui.grid.directive:uiGridMenu * @element style * @restrict A * * @description * Allows us to interpolate expressions in `<style>` elements. Angular doesn't do this by default as it can/will/might? break in IE8. * * @example <doc:example module="app"> <doc:source> <script> var app = angular.module('app', ['ui.grid']); app.controller('MainCtrl', ['$scope', function ($scope) { }]); </script> <div ng-controller="MainCtrl"> <div ui-grid-menu shown="true" ></div> </div> </doc:source> <doc:scenario> </doc:scenario> </doc:example> */ angular.module('ui.grid') .directive('uiGridMenu', ['$compile', '$timeout', '$window', '$document', 'gridUtil', 'uiGridConstants', 'i18nService', function ($compile, $timeout, $window, $document, gridUtil, uiGridConstants, i18nService) { var uiGridMenu = { priority: 0, scope: { // shown: '&', menuItems: '=', autoHide: '=?' }, require: '?^uiGrid', templateUrl: 'ui-grid/uiGridMenu', replace: false, link: function ($scope, $elm, $attrs, uiGridCtrl) { var self = this; var menuMid; var $animate; $scope.i18n = { close: i18nService.getSafeText('columnMenu.close') }; // *** Show/Hide functions ****** self.showMenu = $scope.showMenu = function(event, args) { if ( !$scope.shown ){ /* * In order to animate cleanly we remove the ng-if, wait a digest cycle, then * animate the removal of the ng-hide. We can't successfully (so far as I can tell) * animate removal of the ng-if, as the menu items aren't there yet. And we don't want * to rely on ng-show only, as that leaves elements in the DOM that are needlessly evaluated * on scroll events. * * Note when testing animation that animations don't run on the tutorials. When debugging it looks * like they do, but angular has a default $animate provider that is just a stub, and that's what's * being called. ALso don't be fooled by the fact that your browser has actually loaded the * angular-translate.js, it's not using it. You need to test animations in an external application. */ $scope.shown = true; $timeout( function() { $scope.shownMid = true; $scope.$emit('menu-shown'); }); } else if ( !$scope.shownMid ) { // we're probably doing a hide then show, so we don't need to wait for ng-if $scope.shownMid = true; $scope.$emit('menu-shown'); } var docEventType = 'click'; if (args && args.originalEvent && args.originalEvent.type && args.originalEvent.type === 'touchstart') { docEventType = args.originalEvent.type; } // Turn off an existing document click handler angular.element(document).off('click touchstart', applyHideMenu); // Turn on the document click handler, but in a timeout so it doesn't apply to THIS click if there is one $timeout(function() { angular.element(document).on(docEventType, applyHideMenu); }); //automatically set the focus to the first button element in the now open menu. gridUtil.focus.bySelector($elm, 'button[type=button]', true); }; self.hideMenu = $scope.hideMenu = function(event, args) { if ( $scope.shown ){ /* * In order to animate cleanly we animate the addition of ng-hide, then use a $timeout to * set the ng-if (shown = false) after the animation runs. In theory we can cascade off the * callback on the addClass method, but it is very unreliable with unit tests for no discernable reason. * * The user may have clicked on the menu again whilst * we're waiting, so we check that the mid isn't shown before applying the ng-if. */ $scope.shownMid = false; $timeout( function() { if ( !$scope.shownMid ){ $scope.shown = false; $scope.$emit('menu-hidden'); } }, 200); } angular.element(document).off('click touchstart', applyHideMenu); }; $scope.$on('hide-menu', function (event, args) { $scope.hideMenu(event, args); }); $scope.$on('show-menu', function (event, args) { $scope.showMenu(event, args); }); // *** Auto hide when click elsewhere ****** var applyHideMenu = function(){ if ($scope.shown) { $scope.$apply(function () { $scope.hideMenu(); }); } }; if (typeof($scope.autoHide) === 'undefined' || $scope.autoHide === undefined) { $scope.autoHide = true; } if ($scope.autoHide) { angular.element($window).on('resize', applyHideMenu); } $scope.$on('$destroy', function () { angular.element(document).off('click touchstart', applyHideMenu); }); $scope.$on('$destroy', function() { angular.element($window).off('resize', applyHideMenu); }); if (uiGridCtrl) { $scope.$on('$destroy', uiGridCtrl.grid.api.core.on.scrollBegin($scope, applyHideMenu )); } $scope.$on('$destroy', $scope.$on(uiGridConstants.events.ITEM_DRAGGING, applyHideMenu )); }, controller: ['$scope', '$element', '$attrs', function ($scope, $element, $attrs) { var self = this; }] }; return uiGridMenu; }]) .directive('uiGridMenuItem', ['gridUtil', '$compile', 'i18nService', function (gridUtil, $compile, i18nService) { var uiGridMenuItem = { priority: 0, scope: { name: '=', active: '=', action: '=', icon: '=', shown: '=', context: '=', templateUrl: '=', leaveOpen: '=', screenReaderOnly: '=' }, require: ['?^uiGrid', '^uiGridMenu'], templateUrl: 'ui-grid/uiGridMenuItem', replace: false, compile: function($elm, $attrs) { return { pre: function ($scope, $elm, $attrs, controllers) { var uiGridCtrl = controllers[0], uiGridMenuCtrl = controllers[1]; if ($scope.templateUrl) { gridUtil.getTemplate($scope.templateUrl) .then(function (contents) { var template = angular.element(contents); var newElm = $compile(template)($scope); $elm.replaceWith(newElm); }); } }, post: function ($scope, $elm, $attrs, controllers) { var uiGridCtrl = controllers[0], uiGridMenuCtrl = controllers[1]; // TODO(c0bra): validate that shown and active are functions if they're defined. An exception is already thrown above this though // if (typeof($scope.shown) !== 'undefined' && $scope.shown && typeof($scope.shown) !== 'function') { // throw new TypeError("$scope.shown is defined but not a function"); // } if (typeof($scope.shown) === 'undefined' || $scope.shown === null) { $scope.shown = function() { return true; }; } $scope.itemShown = function () { var context = {}; if ($scope.context) { context.context = $scope.context; } if (typeof(uiGridCtrl) !== 'undefined' && uiGridCtrl) { context.grid = uiGridCtrl.grid; } return $scope.shown.call(context); }; $scope.itemAction = function($event,title) { gridUtil.logDebug('itemAction'); $event.stopPropagation(); if (typeof($scope.action) === 'function') { var context = {}; if ($scope.context) { context.context = $scope.context; } // Add the grid to the function call context if the uiGrid controller is present if (typeof(uiGridCtrl) !== 'undefined' && uiGridCtrl) { context.grid = uiGridCtrl.grid; } $scope.action.call(context, $event, title); if ( !$scope.leaveOpen ){ $scope.$emit('hide-menu'); } else { /* * XXX: Fix after column refactor * Ideally the focus would remain on the item. * However, since there are two menu items that have their 'show' property toggled instead. This is a quick fix. */ gridUtil.focus.bySelector(angular.element(gridUtil.closestElm($elm, ".ui-grid-menu-items")), 'button[type=button]', true); } } }; $scope.i18n = i18nService.get(); } }; } }; return uiGridMenuItem; }]); })(); (function(){ 'use strict'; /** * @ngdoc overview * @name ui.grid.directive:uiGridOneBind * @summary A group of directives that provide a one time bind to a dom element. * @description A group of directives that provide a one time bind to a dom element. * As one time bindings are not supported in Angular 1.2.* this directive provdes this capability. * This is done to reduce the number of watchers on the dom. * <br/> * <h2>Short Example ({@link ui.grid.directive:uiGridOneBindSrc ui-grid-one-bind-src})</h2> * <pre> <div ng-init="imageName = 'myImageDir.jpg'"> <img ui-grid-one-bind-src="imageName"></img> </div> </pre> * Will become: * <pre> <div ng-init="imageName = 'myImageDir.jpg'"> <img ui-grid-one-bind-src="imageName" src="myImageDir.jpg"></img> </div> </pre> </br> <h2>Short Example ({@link ui.grid.directive:uiGridOneBindText ui-grid-one-bind-text})</h2> * <pre> <div ng-init="text='Add this text'" ui-grid-one-bind-text="text"></div> </pre> * Will become: * <pre> <div ng-init="text='Add this text'" ui-grid-one-bind-text="text">Add this text</div> </pre> </br> * <b>Note:</b> This behavior is slightly different for the {@link ui.grid.directive:uiGridOneBindIdGrid uiGridOneBindIdGrid} * and {@link ui.grid.directive:uiGridOneBindAriaLabelledbyGrid uiGridOneBindAriaLabelledbyGrid} directives. * */ //https://github.com/joshkurz/Black-Belt-AngularJS-Directives/blob/master/directives/Optimization/oneBind.js var oneBinders = angular.module('ui.grid'); angular.forEach([ /** * @ngdoc directive * @name ui.grid.directive:uiGridOneBindSrc * @memberof ui.grid.directive:uiGridOneBind * @element img * @restrict A * @param {String} uiGridOneBindSrc The angular string you want to bind. Does not support interpolation. Don't use <code>{{scopeElt}}</code> instead use <code>scopeElt</code>. * @description One time binding for the src dom tag. * */ {tag: 'Src', method: 'attr'}, /** * @ngdoc directive * @name ui.grid.directive:uiGridOneBindText * @element div * @restrict A * @param {String} uiGridOneBindText The angular string you want to bind. Does not support interpolation. Don't use <code>{{scopeElt}}</code> instead use <code>scopeElt</code>. * @description One time binding for the text dom tag. */ {tag: 'Text', method: 'text'}, /** * @ngdoc directive * @name ui.grid.directive:uiGridOneBindHref * @element div * @restrict A * @param {String} uiGridOneBindHref The angular string you want to bind. Does not support interpolation. Don't use <code>{{scopeElt}}</code> instead use <code>scopeElt</code>. * @description One time binding for the href dom tag. For more information see {@link ui.grid.directive:uiGridOneBind}. */ {tag: 'Href', method: 'attr'}, /** * @ngdoc directive * @name ui.grid.directive:uiGridOneBindClass * @element div * @restrict A * @param {String} uiGridOneBindClass The angular string you want to bind. Does not support interpolation. Don't use <code>{{scopeElt}}</code> instead use <code>scopeElt</code>. * @param {Object} uiGridOneBindClass The object that you want to bind. At least one of the values in the object must be something other than null or undefined for the watcher to be removed. * this is to prevent the watcher from being removed before the scope is initialized. * @param {Array} uiGridOneBindClass An array of classes to bind to this element. * @description One time binding for the class dom tag. For more information see {@link ui.grid.directive:uiGridOneBind}. */ {tag: 'Class', method: 'addClass'}, /** * @ngdoc directive * @name ui.grid.directive:uiGridOneBindHtml * @element div * @restrict A * @param {String} uiGridOneBindHtml The angular string you want to bind. Does not support interpolation. Don't use <code>{{scopeElt}}</code> instead use <code>scopeElt</code>. * @description One time binding for the html method on a dom element. For more information see {@link ui.grid.directive:uiGridOneBind}. */ {tag: 'Html', method: 'html'}, /** * @ngdoc directive * @name ui.grid.directive:uiGridOneBindAlt * @element div * @restrict A * @param {String} uiGridOneBindAlt The angular string you want to bind. Does not support interpolation. Don't use <code>{{scopeElt}}</code> instead use <code>scopeElt</code>. * @description One time binding for the alt dom tag. For more information see {@link ui.grid.directive:uiGridOneBind}. */ {tag: 'Alt', method: 'attr'}, /** * @ngdoc directive * @name ui.grid.directive:uiGridOneBindStyle * @element div * @restrict A * @param {String} uiGridOneBindStyle The angular string you want to bind. Does not support interpolation. Don't use <code>{{scopeElt}}</code> instead use <code>scopeElt</code>. * @description One time binding for the style dom tag. For more information see {@link ui.grid.directive:uiGridOneBind}. */ {tag: 'Style', method: 'css'}, /** * @ngdoc directive * @name ui.grid.directive:uiGridOneBindValue * @element div * @restrict A * @param {String} uiGridOneBindValue The angular string you want to bind. Does not support interpolation. Don't use <code>{{scopeElt}}</code> instead use <code>scopeElt</code>. * @description One time binding for the value dom tag. For more information see {@link ui.grid.directive:uiGridOneBind}. */ {tag: 'Value', method: 'attr'}, /** * @ngdoc directive * @name ui.grid.directive:uiGridOneBindId * @element div * @restrict A * @param {String} uiGridOneBindId The angular string you want to bind. Does not support interpolation. Don't use <code>{{scopeElt}}</code> instead use <code>scopeElt</code>. * @description One time binding for the value dom tag. For more information see {@link ui.grid.directive:uiGridOneBind}. */ {tag: 'Id', method: 'attr'}, /** * @ngdoc directive * @name ui.grid.directive:uiGridOneBindIdGrid * @element div * @restrict A * @param {String} uiGridOneBindIdGrid The angular string you want to bind. Does not support interpolation. Don't use <code>{{scopeElt}}</code> instead use <code>scopeElt</code>. * @description One time binding for the id dom tag. * <h1>Important Note!</h1> * If the id tag passed as a parameter does <b>not</b> contain the grid id as a substring * then the directive will search the scope and the parent controller (if it is a uiGridController) for the grid.id value. * If this value is found then it is appended to the begining of the id tag. If the grid is not found then the directive throws an error. * This is done in order to ensure uniqueness of id tags across the grid. * This is to prevent two grids in the same document having duplicate id tags. */ {tag: 'Id', directiveName:'IdGrid', method: 'attr', appendGridId: true}, /** * @ngdoc directive * @name ui.grid.directive:uiGridOneBindTitle * @element div * @restrict A * @param {String} uiGridOneBindTitle The angular string you want to bind. Does not support interpolation. Don't use <code>{{scopeElt}}</code> instead use <code>scopeElt</code>. * @description One time binding for the title dom tag. For more information see {@link ui.grid.directive:uiGridOneBind}. */ {tag: 'Title', method: 'attr'}, /** * @ngdoc directive * @name ui.grid.directive:uiGridOneBindAriaLabel * @element div * @restrict A * @param {String} uiGridOneBindAriaLabel The angular string you want to bind. Does not support interpolation. Don't use <code>{{scopeElt}}</code> instead use <code>scopeElt</code>. * @description One time binding for the aria-label dom tag. For more information see {@link ui.grid.directive:uiGridOneBind}. *<br/> * <pre> <div ng-init="text='Add this text'" ui-grid-one-bind-aria-label="text"></div> </pre> * Will become: * <pre> <div ng-init="text='Add this text'" ui-grid-one-bind-aria-label="text" aria-label="Add this text"></div> </pre> */ {tag: 'Label', method: 'attr', aria:true}, /** * @ngdoc directive * @name ui.grid.directive:uiGridOneBindAriaLabelledby * @element div * @restrict A * @param {String} uiGridOneBindAriaLabelledby The angular string you want to bind. Does not support interpolation. Don't use <code>{{scopeElt}}</code> instead use <code>scopeElt</code>. * @description One time binding for the aria-labelledby dom tag. For more information see {@link ui.grid.directive:uiGridOneBind}. *<br/> * <pre> <div ng-init="anId = 'gridID32'" ui-grid-one-bind-aria-labelledby="anId"></div> </pre> * Will become: * <pre> <div ng-init="anId = 'gridID32'" ui-grid-one-bind-aria-labelledby="anId" aria-labelledby="gridID32"></div> </pre> */ {tag: 'Labelledby', method: 'attr', aria:true}, /** * @ngdoc directive * @name ui.grid.directive:uiGridOneBindAriaLabelledbyGrid * @element div * @restrict A * @param {String} uiGridOneBindAriaLabelledbyGrid The angular string you want to bind. Does not support interpolation. Don't use <code>{{scopeElt}}</code> instead use <code>scopeElt</code>. * @description One time binding for the aria-labelledby dom tag. For more information see {@link ui.grid.directive:uiGridOneBind}. * Works somewhat like {@link ui.grid.directive:uiGridOneBindIdGrid} however this one supports a list of ids (seperated by a space) and will dynamically add the * grid id to each one. *<br/> * <pre> <div ng-init="anId = 'gridID32'" ui-grid-one-bind-aria-labelledby-grid="anId"></div> </pre> * Will become ([grid.id] will be replaced by the actual grid id): * <pre> <div ng-init="anId = 'gridID32'" ui-grid-one-bind-aria-labelledby-grid="anId" aria-labelledby-Grid="[grid.id]-gridID32"></div> </pre> */ {tag: 'Labelledby', directiveName:'LabelledbyGrid', appendGridId:true, method: 'attr', aria:true}, /** * @ngdoc directive * @name ui.grid.directive:uiGridOneBindAriaDescribedby * @element ANY * @restrict A * @param {String} uiGridOneBindAriaDescribedby The angular string you want to bind. Does not support interpolation. Don't use <code>{{scopeElt}}</code> instead use <code>scopeElt</code>. * @description One time binding for the aria-describedby dom tag. For more information see {@link ui.grid.directive:uiGridOneBind}. *<br/> * <pre> <div ng-init="anId = 'gridID32'" ui-grid-one-bind-aria-describedby="anId"></div> </pre> * Will become: * <pre> <div ng-init="anId = 'gridID32'" ui-grid-one-bind-aria-describedby="anId" aria-describedby="gridID32"></div> </pre> */ {tag: 'Describedby', method: 'attr', aria:true}, /** * @ngdoc directive * @name ui.grid.directive:uiGridOneBindAriaDescribedbyGrid * @element ANY * @restrict A * @param {String} uiGridOneBindAriaDescribedbyGrid The angular string you want to bind. Does not support interpolation. Don't use <code>{{scopeElt}}</code> instead use <code>scopeElt</code>. * @description One time binding for the aria-labelledby dom tag. For more information see {@link ui.grid.directive:uiGridOneBind}. * Works somewhat like {@link ui.grid.directive:uiGridOneBindIdGrid} however this one supports a list of ids (seperated by a space) and will dynamically add the * grid id to each one. *<br/> * <pre> <div ng-init="anId = 'gridID32'" ui-grid-one-bind-aria-describedby-grid="anId"></div> </pre> * Will become ([grid.id] will be replaced by the actual grid id): * <pre> <div ng-init="anId = 'gridID32'" ui-grid-one-bind-aria-describedby-grid="anId" aria-describedby="[grid.id]-gridID32"></div> </pre> */ {tag: 'Describedby', directiveName:'DescribedbyGrid', appendGridId:true, method: 'attr', aria:true}], function(v){ var baseDirectiveName = 'uiGridOneBind'; //If it is an aria tag then append the aria label seperately //This is done because the aria tags are formatted aria-* and the directive name can't have a '-' character in it. //If the diretiveName has to be overridden then it does so here. This is because the tag being modified and the directive sometimes don't match up. var directiveName = (v.aria ? baseDirectiveName + 'Aria' : baseDirectiveName) + (v.directiveName ? v.directiveName : v.tag); oneBinders.directive(directiveName, ['gridUtil', function(gridUtil){ return { restrict: 'A', require: ['?uiGrid','?^uiGrid'], link: function(scope, iElement, iAttrs, controllers){ /* Appends the grid id to the beginnig of the value. */ var appendGridId = function(val){ var grid; //Get an instance of the grid if its available //If its available in the scope then we don't need to try to find it elsewhere if (scope.grid) { grid = scope.grid; } //Another possible location to try to find the grid else if (scope.col && scope.col.grid){ grid = scope.col.grid; } //Last ditch effort: Search through the provided controllers. else if (!controllers.some( //Go through the controllers till one has the element we need function(controller){ if (controller && controller.grid) { grid = controller.grid; return true; //We've found the grid } })){ //We tried our best to find it for you gridUtil.logError("["+directiveName+"] A valid grid could not be found to bind id. Are you using this directive " + "within the correct scope? Trying to generate id: [gridID]-" + val); throw new Error("No valid grid could be found"); } if (grid){ var idRegex = new RegExp(grid.id.toString()); //If the grid id hasn't been appended already in the template declaration if (!idRegex.test(val)){ val = grid.id.toString() + '-' + val; } } return val; }; // The watch returns a function to remove itself. var rmWatcher = scope.$watch(iAttrs[directiveName], function(newV){ if (newV){ //If we are trying to add an id element then we also apply the grid id if it isn't already there if (v.appendGridId) { var newIdString = null; //Append the id to all of the new ids. angular.forEach( newV.split(' '), function(s){ newIdString = (newIdString ? (newIdString + ' ') : '') + appendGridId(s); }); newV = newIdString; } // Append this newValue to the dom element. switch (v.method) { case 'attr': //The attr method takes two paraams the tag and the value if (v.aria) { //If it is an aria element then append the aria prefix iElement[v.method]('aria-' + v.tag.toLowerCase(),newV); } else { iElement[v.method](v.tag.toLowerCase(),newV); } break; case 'addClass': //Pulled from https://github.com/Pasvaz/bindonce/blob/master/bindonce.js if (angular.isObject(newV) && !angular.isArray(newV)) { var results = []; var nonNullFound = false; //We don't want to remove the binding unless the key is actually defined angular.forEach(newV, function (value, index) { if (value !== null && typeof(value) !== "undefined"){ nonNullFound = true; //A non null value for a key was found so the object must have been initialized if (value) {results.push(index);} } }); //A non null value for a key wasn't found so assume that the scope values haven't been fully initialized if (!nonNullFound){ return; // If not initialized then the watcher should not be removed yet. } newV = results; } if (newV) { iElement.addClass(angular.isArray(newV) ? newV.join(' ') : newV); } else { return; } break; default: iElement[v.method](newV); break; } //Removes the watcher on itself after the bind rmWatcher(); } // True ensures that equality is determined using angular.equals instead of === }, true); //End rm watchers } //End compile function }; //End directive return } // End directive function ]); //End directive }); // End angular foreach })(); (function () { 'use strict'; var module = angular.module('ui.grid'); module.directive('uiGridRenderContainer', ['$timeout', '$document', 'uiGridConstants', 'gridUtil', 'ScrollEvent', function($timeout, $document, uiGridConstants, gridUtil, ScrollEvent) { return { replace: true, transclude: true, templateUrl: 'ui-grid/uiGridRenderContainer', require: ['^uiGrid', 'uiGridRenderContainer'], scope: { containerId: '=', rowContainerName: '=', colContainerName: '=', bindScrollHorizontal: '=', bindScrollVertical: '=', enableVerticalScrollbar: '=', enableHorizontalScrollbar: '=' }, controller: 'uiGridRenderContainer as RenderContainer', compile: function () { return { pre: function prelink($scope, $elm, $attrs, controllers) { var uiGridCtrl = controllers[0]; var containerCtrl = controllers[1]; var grid = $scope.grid = uiGridCtrl.grid; // Verify that the render container for this element exists if (!$scope.rowContainerName) { throw "No row render container name specified"; } if (!$scope.colContainerName) { throw "No column render container name specified"; } if (!grid.renderContainers[$scope.rowContainerName]) { throw "Row render container '" + $scope.rowContainerName + "' is not registered."; } if (!grid.renderContainers[$scope.colContainerName]) { throw "Column render container '" + $scope.colContainerName + "' is not registered."; } var rowContainer = $scope.rowContainer = grid.renderContainers[$scope.rowContainerName]; var colContainer = $scope.colContainer = grid.renderContainers[$scope.colContainerName]; containerCtrl.containerId = $scope.containerId; containerCtrl.rowContainer = rowContainer; containerCtrl.colContainer = colContainer; }, post: function postlink($scope, $elm, $attrs, controllers) { var uiGridCtrl = controllers[0]; var containerCtrl = controllers[1]; var grid = uiGridCtrl.grid; var rowContainer = containerCtrl.rowContainer; var colContainer = containerCtrl.colContainer; var scrollTop = null; var scrollLeft = null; var renderContainer = grid.renderContainers[$scope.containerId]; // Put the container name on this element as a class $elm.addClass('ui-grid-render-container-' + $scope.containerId); // Scroll the render container viewport when the mousewheel is used gridUtil.on.mousewheel($elm, function (event) { var scrollEvent = new ScrollEvent(grid, rowContainer, colContainer, ScrollEvent.Sources.RenderContainerMouseWheel); if (event.deltaY !== 0) { var scrollYAmount = event.deltaY * -1 * event.deltaFactor; scrollTop = containerCtrl.viewport[0].scrollTop; // Get the scroll percentage scrollEvent.verticalScrollLength = rowContainer.getVerticalScrollLength(); var scrollYPercentage = (scrollTop + scrollYAmount) / scrollEvent.verticalScrollLength; // If we should be scrolled 100%, make sure the scrollTop matches the maximum scroll length // Viewports that have "overflow: hidden" don't let the mousewheel scroll all the way to the bottom without this check if (scrollYPercentage >= 1 && scrollTop < scrollEvent.verticalScrollLength) { containerCtrl.viewport[0].scrollTop = scrollEvent.verticalScrollLength; } // Keep scrollPercentage within the range 0-1. if (scrollYPercentage < 0) { scrollYPercentage = 0; } else if (scrollYPercentage > 1) { scrollYPercentage = 1; } scrollEvent.y = { percentage: scrollYPercentage, pixels: scrollYAmount }; } if (event.deltaX !== 0) { var scrollXAmount = event.deltaX * event.deltaFactor; // Get the scroll percentage scrollLeft = gridUtil.normalizeScrollLeft(containerCtrl.viewport, grid); scrollEvent.horizontalScrollLength = (colContainer.getCanvasWidth() - colContainer.getViewportWidth()); var scrollXPercentage = (scrollLeft + scrollXAmount) / scrollEvent.horizontalScrollLength; // Keep scrollPercentage within the range 0-1. if (scrollXPercentage < 0) { scrollXPercentage = 0; } else if (scrollXPercentage > 1) { scrollXPercentage = 1; } scrollEvent.x = { percentage: scrollXPercentage, pixels: scrollXAmount }; } // Let the parent container scroll if the grid is already at the top/bottom if ((event.deltaY !== 0 && (scrollEvent.atTop(scrollTop) || scrollEvent.atBottom(scrollTop))) || (event.deltaX !== 0 && (scrollEvent.atLeft(scrollLeft) || scrollEvent.atRight(scrollLeft)))) { //parent controller scrolls } else { event.preventDefault(); event.stopPropagation(); scrollEvent.fireThrottledScrollingEvent('', scrollEvent); } }); $elm.bind('$destroy', function() { $elm.unbind('keydown'); ['touchstart', 'touchmove', 'touchend','keydown', 'wheel', 'mousewheel', 'DomMouseScroll', 'MozMousePixelScroll'].forEach(function (eventName) { $elm.unbind(eventName); }); }); // TODO(c0bra): Handle resizing the inner canvas based on the number of elements function update() { var ret = ''; var canvasWidth = colContainer.canvasWidth; var viewportWidth = colContainer.getViewportWidth(); var canvasHeight = rowContainer.getCanvasHeight(); //add additional height for scrollbar on left and right container //if ($scope.containerId !== 'body') { // canvasHeight -= grid.scrollbarHeight; //} var viewportHeight = rowContainer.getViewportHeight(); //shorten the height to make room for a scrollbar placeholder if (colContainer.needsHScrollbarPlaceholder()) { viewportHeight -= grid.scrollbarHeight; } var headerViewportWidth, footerViewportWidth; headerViewportWidth = footerViewportWidth = colContainer.getHeaderViewportWidth(); // Set canvas dimensions ret += '\n .grid' + uiGridCtrl.grid.id + ' .ui-grid-render-container-' + $scope.containerId + ' .ui-grid-canvas { width: ' + canvasWidth + 'px; height: ' + canvasHeight + 'px; }'; ret += '\n .grid' + uiGridCtrl.grid.id + ' .ui-grid-render-container-' + $scope.containerId + ' .ui-grid-header-canvas { width: ' + (canvasWidth + grid.scrollbarWidth) + 'px; }'; if (renderContainer.explicitHeaderCanvasHeight) { ret += '\n .grid' + uiGridCtrl.grid.id + ' .ui-grid-render-container-' + $scope.containerId + ' .ui-grid-header-canvas { height: ' + renderContainer.explicitHeaderCanvasHeight + 'px; }'; } else { ret += '\n .grid' + uiGridCtrl.grid.id + ' .ui-grid-render-container-' + $scope.containerId + ' .ui-grid-header-canvas { height: inherit; }'; } ret += '\n .grid' + uiGridCtrl.grid.id + ' .ui-grid-render-container-' + $scope.containerId + ' .ui-grid-viewport { width: ' + viewportWidth + 'px; height: ' + viewportHeight + 'px; }'; ret += '\n .grid' + uiGridCtrl.grid.id + ' .ui-grid-render-container-' + $scope.containerId + ' .ui-grid-header-viewport { width: ' + headerViewportWidth + 'px; }'; ret += '\n .grid' + uiGridCtrl.grid.id + ' .ui-grid-render-container-' + $scope.containerId + ' .ui-grid-footer-canvas { width: ' + (canvasWidth + grid.scrollbarWidth) + 'px; }'; ret += '\n .grid' + uiGridCtrl.grid.id + ' .ui-grid-render-container-' + $scope.containerId + ' .ui-grid-footer-viewport { width: ' + footerViewportWidth + 'px; }'; return ret; } uiGridCtrl.grid.registerStyleComputation({ priority: 6, func: update }); } }; } }; }]); module.controller('uiGridRenderContainer', ['$scope', 'gridUtil', function ($scope, gridUtil) { }]); })(); (function(){ 'use strict'; angular.module('ui.grid').directive('uiGridRow', ['gridUtil', function(gridUtil) { return { replace: true, // priority: 2001, // templateUrl: 'ui-grid/ui-grid-row', require: ['^uiGrid', '^uiGridRenderContainer'], scope: { row: '=uiGridRow', //rowRenderIndex is added to scope to give the true visual index of the row to any directives that need it rowRenderIndex: '=' }, compile: function() { return { pre: function($scope, $elm, $attrs, controllers) { var uiGridCtrl = controllers[0]; var containerCtrl = controllers[1]; var grid = uiGridCtrl.grid; $scope.grid = uiGridCtrl.grid; $scope.colContainer = containerCtrl.colContainer; // Function for attaching the template to this scope var clonedElement, cloneScope; function compileTemplate() { $scope.row.getRowTemplateFn.then(function (compiledElementFn) { // var compiledElementFn = $scope.row.compiledElementFn; // Create a new scope for the contents of this row, so we can destroy it later if need be var newScope = $scope.$new(); compiledElementFn(newScope, function (newElm, scope) { // If we already have a cloned element, we need to remove it and destroy its scope if (clonedElement) { clonedElement.remove(); cloneScope.$destroy(); } // Empty the row and append the new element $elm.empty().append(newElm); // Save the new cloned element and scope clonedElement = newElm; cloneScope = newScope; }); }); } // Initially attach the compiled template to this scope compileTemplate(); // If the row's compiled element function changes, we need to replace this element's contents with the new compiled template $scope.$watch('row.getRowTemplateFn', function (newFunc, oldFunc) { if (newFunc !== oldFunc) { compileTemplate(); } }); }, post: function($scope, $elm, $attrs, controllers) { } }; } }; }]); })(); (function(){ // 'use strict'; /** * @ngdoc directive * @name ui.grid.directive:uiGridStyle * @element style * @restrict A * * @description * Allows us to interpolate expressions in `<style>` elements. Angular doesn't do this by default as it can/will/might? break in IE8. * * @example <doc:example module="app"> <doc:source> <script> var app = angular.module('app', ['ui.grid']); app.controller('MainCtrl', ['$scope', function ($scope) { $scope.myStyle = '.blah { border: 1px solid }'; }]); </script> <div ng-controller="MainCtrl"> <style ui-grid-style>{{ myStyle }}</style> <span class="blah">I am in a box.</span> </div> </doc:source> <doc:scenario> it('should apply the right class to the element', function () { element(by.css('.blah')).getCssValue('border-top-width') .then(function(c) { expect(c).toContain('1px'); }); }); </doc:scenario> </doc:example> */ angular.module('ui.grid').directive('uiGridStyle', ['gridUtil', '$interpolate', function(gridUtil, $interpolate) { return { // restrict: 'A', // priority: 1000, // require: '?^uiGrid', link: function($scope, $elm, $attrs, uiGridCtrl) { // gridUtil.logDebug('ui-grid-style link'); // if (uiGridCtrl === undefined) { // gridUtil.logWarn('[ui-grid-style link] uiGridCtrl is undefined!'); // } var interpolateFn = $interpolate($elm.text(), true); if (interpolateFn) { $scope.$watch(interpolateFn, function(value) { $elm.text(value); }); } // uiGridCtrl.recalcRowStyles = function() { // var offset = (scope.options.offsetTop || 0) - (scope.options.excessRows * scope.options.rowHeight); // var rowHeight = scope.options.rowHeight; // var ret = ''; // var rowStyleCount = uiGridCtrl.minRowsToRender() + (scope.options.excessRows * 2); // for (var i = 1; i <= rowStyleCount; i++) { // ret = ret + ' .grid' + scope.gridId + ' .ui-grid-row:nth-child(' + i + ') { top: ' + offset + 'px; }'; // offset = offset + rowHeight; // } // scope.rowStyles = ret; // }; // uiGridCtrl.styleComputions.push(uiGridCtrl.recalcRowStyles); } }; }]); })(); (function(){ 'use strict'; angular.module('ui.grid').directive('uiGridViewport', ['gridUtil','ScrollEvent','uiGridConstants', '$log', function(gridUtil, ScrollEvent, uiGridConstants, $log) { return { replace: true, scope: {}, controllerAs: 'Viewport', templateUrl: 'ui-grid/uiGridViewport', require: ['^uiGrid', '^uiGridRenderContainer'], link: function($scope, $elm, $attrs, controllers) { // gridUtil.logDebug('viewport post-link'); var uiGridCtrl = controllers[0]; var containerCtrl = controllers[1]; $scope.containerCtrl = containerCtrl; var rowContainer = containerCtrl.rowContainer; var colContainer = containerCtrl.colContainer; var grid = uiGridCtrl.grid; $scope.grid = uiGridCtrl.grid; // Put the containers in scope so we can get rows and columns from them $scope.rowContainer = containerCtrl.rowContainer; $scope.colContainer = containerCtrl.colContainer; // Register this viewport with its container containerCtrl.viewport = $elm; $elm.on('scroll', scrollHandler); var ignoreScroll = false; function scrollHandler(evt) { //Leaving in this commented code in case it can someday be used //It does improve performance, but because the horizontal scroll is normalized, // using this code will lead to the column header getting slightly out of line with columns // //if (ignoreScroll && (grid.isScrollingHorizontally || grid.isScrollingHorizontally)) { // //don't ask for scrollTop if we just set it // ignoreScroll = false; // return; //} //ignoreScroll = true; var newScrollTop = $elm[0].scrollTop; var newScrollLeft = gridUtil.normalizeScrollLeft($elm, grid); var vertScrollPercentage = rowContainer.scrollVertical(newScrollTop); var horizScrollPercentage = colContainer.scrollHorizontal(newScrollLeft); var scrollEvent = new ScrollEvent(grid, rowContainer, colContainer, ScrollEvent.Sources.ViewPortScroll); scrollEvent.newScrollLeft = newScrollLeft; scrollEvent.newScrollTop = newScrollTop; if ( horizScrollPercentage > -1 ){ scrollEvent.x = { percentage: horizScrollPercentage }; } if ( vertScrollPercentage > -1 ){ scrollEvent.y = { percentage: vertScrollPercentage }; } grid.scrollContainers($scope.$parent.containerId, scrollEvent); } if ($scope.$parent.bindScrollVertical) { grid.addVerticalScrollSync($scope.$parent.containerId, syncVerticalScroll); } if ($scope.$parent.bindScrollHorizontal) { grid.addHorizontalScrollSync($scope.$parent.containerId, syncHorizontalScroll); grid.addHorizontalScrollSync($scope.$parent.containerId + 'header', syncHorizontalHeader); grid.addHorizontalScrollSync($scope.$parent.containerId + 'footer', syncHorizontalFooter); } function syncVerticalScroll(scrollEvent){ containerCtrl.prevScrollArgs = scrollEvent; var newScrollTop = scrollEvent.getNewScrollTop(rowContainer,containerCtrl.viewport); $elm[0].scrollTop = newScrollTop; } function syncHorizontalScroll(scrollEvent){ containerCtrl.prevScrollArgs = scrollEvent; var newScrollLeft = scrollEvent.getNewScrollLeft(colContainer, containerCtrl.viewport); $elm[0].scrollLeft = gridUtil.denormalizeScrollLeft(containerCtrl.viewport,newScrollLeft, grid); } function syncHorizontalHeader(scrollEvent){ var newScrollLeft = scrollEvent.getNewScrollLeft(colContainer, containerCtrl.viewport); if (containerCtrl.headerViewport) { containerCtrl.headerViewport.scrollLeft = gridUtil.denormalizeScrollLeft(containerCtrl.viewport,newScrollLeft, grid); } } function syncHorizontalFooter(scrollEvent){ var newScrollLeft = scrollEvent.getNewScrollLeft(colContainer, containerCtrl.viewport); if (containerCtrl.footerViewport) { containerCtrl.footerViewport.scrollLeft = gridUtil.denormalizeScrollLeft(containerCtrl.viewport,newScrollLeft, grid); } } }, controller: ['$scope', function ($scope) { this.rowStyle = function (index) { var rowContainer = $scope.rowContainer; var colContainer = $scope.colContainer; var styles = {}; if (index === 0 && rowContainer.currentTopRow !== 0) { // The row offset-top is just the height of the rows above the current top-most row, which are no longer rendered var hiddenRowWidth = (rowContainer.currentTopRow) * rowContainer.grid.options.rowHeight; // return { 'margin-top': hiddenRowWidth + 'px' }; styles['margin-top'] = hiddenRowWidth + 'px'; } if (colContainer.currentFirstColumn !== 0) { if (colContainer.grid.isRTL()) { styles['margin-right'] = colContainer.columnOffset + 'px'; } else { styles['margin-left'] = colContainer.columnOffset + 'px'; } } return styles; }; }] }; } ]); })(); (function() { angular.module('ui.grid') .directive('uiGridVisible', function uiGridVisibleAction() { return function ($scope, $elm, $attr) { $scope.$watch($attr.uiGridVisible, function (visible) { // $elm.css('visibility', visible ? 'visible' : 'hidden'); $elm[visible ? 'removeClass' : 'addClass']('ui-grid-invisible'); }); }; }); })(); (function () { 'use strict'; angular.module('ui.grid').controller('uiGridController', ['$scope', '$element', '$attrs', 'gridUtil', '$q', 'uiGridConstants', '$templateCache', 'gridClassFactory', '$timeout', '$parse', '$compile', function ($scope, $elm, $attrs, gridUtil, $q, uiGridConstants, $templateCache, gridClassFactory, $timeout, $parse, $compile) { // gridUtil.logDebug('ui-grid controller'); var self = this; self.grid = gridClassFactory.createGrid($scope.uiGrid); //assign $scope.$parent if appScope not already assigned self.grid.appScope = self.grid.appScope || $scope.$parent; $elm.addClass('grid' + self.grid.id); self.grid.rtl = gridUtil.getStyles($elm[0])['direction'] === 'rtl'; // angular.extend(self.grid.options, ); //all properties of grid are available on scope $scope.grid = self.grid; if ($attrs.uiGridColumns) { $attrs.$observe('uiGridColumns', function(value) { self.grid.options.columnDefs = value; self.grid.buildColumns() .then(function(){ self.grid.preCompileCellTemplates(); self.grid.refreshCanvas(true); }); }); } // if fastWatch is set we watch only the length and the reference, not every individual object var deregFunctions = []; if (self.grid.options.fastWatch) { self.uiGrid = $scope.uiGrid; if (angular.isString($scope.uiGrid.data)) { deregFunctions.push( $scope.$parent.$watch($scope.uiGrid.data, dataWatchFunction) ); deregFunctions.push( $scope.$parent.$watch(function() { if ( self.grid.appScope[$scope.uiGrid.data] ){ return self.grid.appScope[$scope.uiGrid.data].length; } else { return undefined; } }, dataWatchFunction) ); } else { deregFunctions.push( $scope.$parent.$watch(function() { return $scope.uiGrid.data; }, dataWatchFunction) ); deregFunctions.push( $scope.$parent.$watch(function() { return $scope.uiGrid.data.length; }, dataWatchFunction) ); } deregFunctions.push( $scope.$parent.$watch(function() { return $scope.uiGrid.columnDefs; }, columnDefsWatchFunction) ); deregFunctions.push( $scope.$parent.$watch(function() { return $scope.uiGrid.columnDefs.length; }, columnDefsWatchFunction) ); } else { if (angular.isString($scope.uiGrid.data)) { deregFunctions.push( $scope.$parent.$watchCollection($scope.uiGrid.data, dataWatchFunction) ); } else { deregFunctions.push( $scope.$parent.$watchCollection(function() { return $scope.uiGrid.data; }, dataWatchFunction) ); } deregFunctions.push( $scope.$parent.$watchCollection(function() { return $scope.uiGrid.columnDefs; }, columnDefsWatchFunction) ); } function columnDefsWatchFunction(n, o) { if (n && n !== o) { self.grid.options.columnDefs = n; self.grid.buildColumns({ orderByColumnDefs: true }) .then(function(){ self.grid.preCompileCellTemplates(); self.grid.callDataChangeCallbacks(uiGridConstants.dataChange.COLUMN); }); } } function dataWatchFunction(newData) { // gridUtil.logDebug('dataWatch fired'); var promises = []; if ( self.grid.options.fastWatch ){ if (angular.isString($scope.uiGrid.data)) { newData = self.grid.appScope[$scope.uiGrid.data]; } else { newData = $scope.uiGrid.data; } } if (newData) { if ( // If we have no columns (i.e. columns length is either 0 or equal to the number of row header columns, which don't count because they're created automatically) self.grid.columns.length === (self.grid.rowHeaderColumns ? self.grid.rowHeaderColumns.length : 0) && // ... and we don't have a ui-grid-columns attribute, which would define columns for us !$attrs.uiGridColumns && // ... and we have no pre-defined columns self.grid.options.columnDefs.length === 0 && // ... but we DO have data newData.length > 0 ) { // ... then build the column definitions from the data that we have self.grid.buildColumnDefsFromData(newData); } // If we either have some columns defined, or some data defined if (self.grid.options.columnDefs.length > 0 || newData.length > 0) { // Build the column set, then pre-compile the column cell templates promises.push(self.grid.buildColumns() .then(function() { self.grid.preCompileCellTemplates(); })); } $q.all(promises).then(function() { self.grid.modifyRows(newData) .then(function () { // if (self.viewport) { self.grid.redrawInPlace(true); // } $scope.$evalAsync(function() { self.grid.refreshCanvas(true); self.grid.callDataChangeCallbacks(uiGridConstants.dataChange.ROW); }); }); }); } } var styleWatchDereg = $scope.$watch(function () { return self.grid.styleComputations; }, function() { self.grid.refreshCanvas(true); }); $scope.$on('$destroy', function() { deregFunctions.forEach( function( deregFn ){ deregFn(); }); styleWatchDereg(); }); self.fireEvent = function(eventName, args) { // Add the grid to the event arguments if it's not there if (typeof(args) === 'undefined' || args === undefined) { args = {}; } if (typeof(args.grid) === 'undefined' || args.grid === undefined) { args.grid = self.grid; } $scope.$broadcast(eventName, args); }; self.innerCompile = function innerCompile(elm) { $compile(elm)($scope); }; }]); /** * @ngdoc directive * @name ui.grid.directive:uiGrid * @element div * @restrict EA * @param {Object} uiGrid Options for the grid to use * * @description Create a very basic grid. * * @example <example module="app"> <file name="app.js"> var app = angular.module('app', ['ui.grid']); app.controller('MainCtrl', ['$scope', function ($scope) { $scope.data = [ { name: 'Bob', title: 'CEO' }, { name: 'Frank', title: 'Lowly Developer' } ]; }]); </file> <file name="index.html"> <div ng-controller="MainCtrl"> <div ui-grid="{ data: data }"></div> </div> </file> </example> */ angular.module('ui.grid').directive('uiGrid', uiGridDirective); uiGridDirective.$inject = ['$compile', '$templateCache', '$timeout', '$window', 'gridUtil', 'uiGridConstants']; function uiGridDirective($compile, $templateCache, $timeout, $window, gridUtil, uiGridConstants) { return { templateUrl: 'ui-grid/ui-grid', scope: { uiGrid: '=' }, replace: true, transclude: true, controller: 'uiGridController', compile: function () { return { post: function ($scope, $elm, $attrs, uiGridCtrl) { var grid = uiGridCtrl.grid; // Initialize scrollbars (TODO: move to controller??) uiGridCtrl.scrollbars = []; grid.element = $elm; // See if the grid has a rendered width, if not, wait a bit and try again var sizeCheckInterval = 100; // ms var maxSizeChecks = 20; // 2 seconds total var sizeChecks = 0; // Setup (event listeners) the grid setup(); // And initialize it init(); // Mark rendering complete so API events can happen grid.renderingComplete(); // If the grid doesn't have size currently, wait for a bit to see if it gets size checkSize(); /*-- Methods --*/ function checkSize() { // If the grid has no width and we haven't checked more than <maxSizeChecks> times, check again in <sizeCheckInterval> milliseconds if ($elm[0].offsetWidth <= 0 && sizeChecks < maxSizeChecks) { setTimeout(checkSize, sizeCheckInterval); sizeChecks++; } else { $timeout(init); } } // Setup event listeners and watchers function setup() { // Bind to window resize events angular.element($window).on('resize', gridResize); // Unbind from window resize events when the grid is destroyed $elm.on('$destroy', function () { angular.element($window).off('resize', gridResize); }); // If we add a left container after render, we need to watch and react $scope.$watch(function () { return grid.hasLeftContainer();}, function (newValue, oldValue) { if (newValue === oldValue) { return; } grid.refreshCanvas(true); }); // If we add a right container after render, we need to watch and react $scope.$watch(function () { return grid.hasRightContainer();}, function (newValue, oldValue) { if (newValue === oldValue) { return; } grid.refreshCanvas(true); }); } // Initialize the directive function init() { grid.gridWidth = $scope.gridWidth = gridUtil.elementWidth($elm); // Default canvasWidth to the grid width, in case we don't get any column definitions to calculate it from grid.canvasWidth = uiGridCtrl.grid.gridWidth; grid.gridHeight = $scope.gridHeight = gridUtil.elementHeight($elm); // If the grid isn't tall enough to fit a single row, it's kind of useless. Resize it to fit a minimum number of rows if (grid.gridHeight < grid.options.rowHeight && grid.options.enableMinHeightCheck) { autoAdjustHeight(); } // Run initial canvas refresh grid.refreshCanvas(true); } // Set the grid's height ourselves in the case that its height would be unusably small function autoAdjustHeight() { // Figure out the new height var contentHeight = grid.options.minRowsToShow * grid.options.rowHeight; var headerHeight = grid.options.showHeader ? grid.options.headerRowHeight : 0; var footerHeight = grid.calcFooterHeight(); var scrollbarHeight = 0; if (grid.options.enableHorizontalScrollbar === uiGridConstants.scrollbars.ALWAYS) { scrollbarHeight = gridUtil.getScrollbarWidth(); } var maxNumberOfFilters = 0; // Calculates the maximum number of filters in the columns angular.forEach(grid.options.columnDefs, function(col) { if (col.hasOwnProperty('filter')) { if (maxNumberOfFilters < 1) { maxNumberOfFilters = 1; } } else if (col.hasOwnProperty('filters')) { if (maxNumberOfFilters < col.filters.length) { maxNumberOfFilters = col.filters.length; } } }); if (grid.options.enableFiltering) { var allColumnsHaveFilteringTurnedOff = grid.options.columnDefs.every(function(col) { return col.enableFiltering === false; }); if (!allColumnsHaveFilteringTurnedOff) { maxNumberOfFilters++; } } var filterHeight = maxNumberOfFilters * headerHeight; var newHeight = headerHeight + contentHeight + footerHeight + scrollbarHeight + filterHeight; $elm.css('height', newHeight + 'px'); grid.gridHeight = $scope.gridHeight = gridUtil.elementHeight($elm); } // Resize the grid on window resize events function gridResize($event) { grid.gridWidth = $scope.gridWidth = gridUtil.elementWidth($elm); grid.gridHeight = $scope.gridHeight = gridUtil.elementHeight($elm); grid.refreshCanvas(true); } } }; } }; } })(); (function(){ 'use strict'; // TODO: rename this file to ui-grid-pinned-container.js angular.module('ui.grid').directive('uiGridPinnedContainer', ['gridUtil', function (gridUtil) { return { restrict: 'EA', replace: true, template: '<div class="ui-grid-pinned-container"><div ui-grid-render-container container-id="side" row-container-name="\'body\'" col-container-name="side" bind-scroll-vertical="true" class="{{ side }} ui-grid-render-container-{{ side }}"></div></div>', scope: { side: '=uiGridPinnedContainer' }, require: '^uiGrid', compile: function compile() { return { post: function ($scope, $elm, $attrs, uiGridCtrl) { // gridUtil.logDebug('ui-grid-pinned-container ' + $scope.side + ' link'); var grid = uiGridCtrl.grid; var myWidth = 0; $elm.addClass('ui-grid-pinned-container-' + $scope.side); // Monkey-patch the viewport width function if ($scope.side === 'left' || $scope.side === 'right') { grid.renderContainers[$scope.side].getViewportWidth = monkeyPatchedGetViewportWidth; } function monkeyPatchedGetViewportWidth() { /*jshint validthis: true */ var self = this; var viewportWidth = 0; self.visibleColumnCache.forEach(function (column) { viewportWidth += column.drawnWidth; }); var adjustment = self.getViewportAdjustment(); viewportWidth = viewportWidth + adjustment.width; return viewportWidth; } function updateContainerWidth() { if ($scope.side === 'left' || $scope.side === 'right') { var cols = grid.renderContainers[$scope.side].visibleColumnCache; var width = 0; for (var i = 0; i < cols.length; i++) { var col = cols[i]; width += col.drawnWidth || col.width || 0; } return width; } } function updateContainerDimensions() { var ret = ''; // Column containers if ($scope.side === 'left' || $scope.side === 'right') { myWidth = updateContainerWidth(); // gridUtil.logDebug('myWidth', myWidth); // TODO(c0bra): Subtract sum of col widths from grid viewport width and update it $elm.attr('style', null); // var myHeight = grid.renderContainers.body.getViewportHeight(); // + grid.horizontalScrollbarHeight; ret += '.grid' + grid.id + ' .ui-grid-pinned-container-' + $scope.side + ', .grid' + grid.id + ' .ui-grid-pinned-container-' + $scope.side + ' .ui-grid-render-container-' + $scope.side + ' .ui-grid-viewport { width: ' + myWidth + 'px; } '; } return ret; } grid.renderContainers.body.registerViewportAdjuster(function (adjustment) { myWidth = updateContainerWidth(); // Subtract our own width adjustment.width -= myWidth; adjustment.side = $scope.side; return adjustment; }); // Register style computation to adjust for columns in `side`'s render container grid.registerStyleComputation({ priority: 15, func: updateContainerDimensions }); } }; } }; }]); })(); (function(){ angular.module('ui.grid') .factory('Grid', ['$q', '$compile', '$parse', 'gridUtil', 'uiGridConstants', 'GridOptions', 'GridColumn', 'GridRow', 'GridApi', 'rowSorter', 'rowSearcher', 'GridRenderContainer', '$timeout','ScrollEvent', function($q, $compile, $parse, gridUtil, uiGridConstants, GridOptions, GridColumn, GridRow, GridApi, rowSorter, rowSearcher, GridRenderContainer, $timeout, ScrollEvent) { /** * @ngdoc object * @name ui.grid.core.api:PublicApi * @description Public Api for the core grid features * */ /** * @ngdoc function * @name ui.grid.class:Grid * @description Grid is the main viewModel. Any properties or methods needed to maintain state are defined in * this prototype. One instance of Grid is created per Grid directive instance. * @param {object} options Object map of options to pass into the grid. An 'id' property is expected. */ var Grid = function Grid(options) { var self = this; // Get the id out of the options, then remove it if (options !== undefined && typeof(options.id) !== 'undefined' && options.id) { if (!/^[_a-zA-Z0-9-]+$/.test(options.id)) { throw new Error("Grid id '" + options.id + '" is invalid. It must follow CSS selector syntax rules.'); } } else { throw new Error('No ID provided. An ID must be given when creating a grid.'); } self.id = options.id; delete options.id; // Get default options self.options = GridOptions.initialize( options ); /** * @ngdoc object * @name appScope * @propertyOf ui.grid.class:Grid * @description reference to the application scope (the parent scope of the ui-grid element). Assigned in ui-grid controller * <br/> * use gridOptions.appScopeProvider to override the default assignment of $scope.$parent with any reference */ self.appScope = self.options.appScopeProvider; self.headerHeight = self.options.headerRowHeight; /** * @ngdoc object * @name footerHeight * @propertyOf ui.grid.class:Grid * @description returns the total footer height gridFooter + columnFooter */ self.footerHeight = self.calcFooterHeight(); /** * @ngdoc object * @name columnFooterHeight * @propertyOf ui.grid.class:Grid * @description returns the total column footer height */ self.columnFooterHeight = self.calcColumnFooterHeight(); self.rtl = false; self.gridHeight = 0; self.gridWidth = 0; self.columnBuilders = []; self.rowBuilders = []; self.rowsProcessors = []; self.columnsProcessors = []; self.styleComputations = []; self.viewportAdjusters = []; self.rowHeaderColumns = []; self.dataChangeCallbacks = {}; self.verticalScrollSyncCallBackFns = {}; self.horizontalScrollSyncCallBackFns = {}; // self.visibleRowCache = []; // Set of 'render' containers for self grid, which can render sets of rows self.renderContainers = {}; // Create a self.renderContainers.body = new GridRenderContainer('body', self); self.cellValueGetterCache = {}; // Cached function to use with custom row templates self.getRowTemplateFn = null; //representation of the rows on the grid. //these are wrapped references to the actual data rows (options.data) self.rows = []; //represents the columns on the grid self.columns = []; /** * @ngdoc boolean * @name isScrollingVertically * @propertyOf ui.grid.class:Grid * @description set to true when Grid is scrolling vertically. Set to false via debounced method */ self.isScrollingVertically = false; /** * @ngdoc boolean * @name isScrollingHorizontally * @propertyOf ui.grid.class:Grid * @description set to true when Grid is scrolling horizontally. Set to false via debounced method */ self.isScrollingHorizontally = false; /** * @ngdoc property * @name scrollDirection * @propertyOf ui.grid.class:Grid * @description set one of the uiGridConstants.scrollDirection values (UP, DOWN, LEFT, RIGHT, NONE), which tells * us which direction we are scrolling. Set to NONE via debounced method */ self.scrollDirection = uiGridConstants.scrollDirection.NONE; //if true, grid will not respond to any scroll events self.disableScrolling = false; function vertical (scrollEvent) { self.isScrollingVertically = false; self.api.core.raise.scrollEnd(scrollEvent); self.scrollDirection = uiGridConstants.scrollDirection.NONE; } var debouncedVertical = gridUtil.debounce(vertical, self.options.scrollDebounce); var debouncedVerticalMinDelay = gridUtil.debounce(vertical, 0); function horizontal (scrollEvent) { self.isScrollingHorizontally = false; self.api.core.raise.scrollEnd(scrollEvent); self.scrollDirection = uiGridConstants.scrollDirection.NONE; } var debouncedHorizontal = gridUtil.debounce(horizontal, self.options.scrollDebounce); var debouncedHorizontalMinDelay = gridUtil.debounce(horizontal, 0); /** * @ngdoc function * @name flagScrollingVertically * @methodOf ui.grid.class:Grid * @description sets isScrollingVertically to true and sets it to false in a debounced function */ self.flagScrollingVertically = function(scrollEvent) { if (!self.isScrollingVertically && !self.isScrollingHorizontally) { self.api.core.raise.scrollBegin(scrollEvent); } self.isScrollingVertically = true; if (self.options.scrollDebounce === 0 || !scrollEvent.withDelay) { debouncedVerticalMinDelay(scrollEvent); } else { debouncedVertical(scrollEvent); } }; /** * @ngdoc function * @name flagScrollingHorizontally * @methodOf ui.grid.class:Grid * @description sets isScrollingHorizontally to true and sets it to false in a debounced function */ self.flagScrollingHorizontally = function(scrollEvent) { if (!self.isScrollingVertically && !self.isScrollingHorizontally) { self.api.core.raise.scrollBegin(scrollEvent); } self.isScrollingHorizontally = true; if (self.options.scrollDebounce === 0 || !scrollEvent.withDelay) { debouncedHorizontalMinDelay(scrollEvent); } else { debouncedHorizontal(scrollEvent); } }; self.scrollbarHeight = 0; self.scrollbarWidth = 0; if (self.options.enableHorizontalScrollbar === uiGridConstants.scrollbars.ALWAYS) { self.scrollbarHeight = gridUtil.getScrollbarWidth(); } if (self.options.enableVerticalScrollbar === uiGridConstants.scrollbars.ALWAYS) { self.scrollbarWidth = gridUtil.getScrollbarWidth(); } self.api = new GridApi(self); /** * @ngdoc function * @name refresh * @methodOf ui.grid.core.api:PublicApi * @description Refresh the rendered grid on screen. * The refresh method re-runs both the columnProcessors and the * rowProcessors, as well as calling refreshCanvas to update all * the grid sizing. In general you should prefer to use queueGridRefresh * instead, which is basically a debounced version of refresh. * * If you only want to resize the grid, not regenerate all the rows * and columns, you should consider directly calling refreshCanvas instead. * */ self.api.registerMethod( 'core', 'refresh', this.refresh ); /** * @ngdoc function * @name queueGridRefresh * @methodOf ui.grid.core.api:PublicApi * @description Request a refresh of the rendered grid on screen, if multiple * calls to queueGridRefresh are made within a digest cycle only one will execute. * The refresh method re-runs both the columnProcessors and the * rowProcessors, as well as calling refreshCanvas to update all * the grid sizing. In general you should prefer to use queueGridRefresh * instead, which is basically a debounced version of refresh. * */ self.api.registerMethod( 'core', 'queueGridRefresh', this.queueGridRefresh ); /** * @ngdoc function * @name refreshRows * @methodOf ui.grid.core.api:PublicApi * @description Runs only the rowProcessors, columns remain as they were. * It then calls redrawInPlace and refreshCanvas, which adjust the grid sizing. * @returns {promise} promise that is resolved when render completes? * */ self.api.registerMethod( 'core', 'refreshRows', this.refreshRows ); /** * @ngdoc function * @name queueRefresh * @methodOf ui.grid.core.api:PublicApi * @description Requests execution of refreshCanvas, if multiple requests are made * during a digest cycle only one will run. RefreshCanvas updates the grid sizing. * @returns {promise} promise that is resolved when render completes? * */ self.api.registerMethod( 'core', 'queueRefresh', this.queueRefresh ); /** * @ngdoc function * @name handleWindowResize * @methodOf ui.grid.core.api:PublicApi * @description Trigger a grid resize, normally this would be picked * up by a watch on window size, but in some circumstances it is necessary * to call this manually * @returns {promise} promise that is resolved when render completes? * */ self.api.registerMethod( 'core', 'handleWindowResize', this.handleWindowResize ); /** * @ngdoc function * @name addRowHeaderColumn * @methodOf ui.grid.core.api:PublicApi * @description adds a row header column to the grid * @param {object} column def * */ self.api.registerMethod( 'core', 'addRowHeaderColumn', this.addRowHeaderColumn ); /** * @ngdoc function * @name scrollToIfNecessary * @methodOf ui.grid.core.api:PublicApi * @description Scrolls the grid to make a certain row and column combo visible, * in the case that it is not completely visible on the screen already. * @param {GridRow} gridRow row to make visible * @param {GridCol} gridCol column to make visible * @returns {promise} a promise that is resolved when scrolling is complete * */ self.api.registerMethod( 'core', 'scrollToIfNecessary', function(gridRow, gridCol) { return self.scrollToIfNecessary(gridRow, gridCol);} ); /** * @ngdoc function * @name scrollTo * @methodOf ui.grid.core.api:PublicApi * @description Scroll the grid such that the specified * row and column is in view * @param {object} rowEntity gridOptions.data[] array instance to make visible * @param {object} colDef to make visible * @returns {promise} a promise that is resolved after any scrolling is finished */ self.api.registerMethod( 'core', 'scrollTo', function (rowEntity, colDef) { return self.scrollTo(rowEntity, colDef);} ); /** * @ngdoc function * @name registerRowsProcessor * @methodOf ui.grid.core.api:PublicApi * @description * Register a "rows processor" function. When the rows are updated, * the grid calls each registered "rows processor", which has a chance * to alter the set of rows (sorting, etc) as long as the count is not * modified. * * @param {function(renderedRowsToProcess, columns )} processorFunction rows processor function, which * is run in the context of the grid (i.e. this for the function will be the grid), and must * return the updated rows list, which is passed to the next processor in the chain * @param {number} priority the priority of this processor. In general we try to do them in 100s to leave room * for other people to inject rows processors at intermediate priorities. Lower priority rowsProcessors run earlier. * * At present allRowsVisible is running at 50, sort manipulations running at 60-65, filter is running at 100, * sort is at 200, grouping and treeview at 400-410, selectable rows at 500, pagination at 900 (pagination will generally want to be last) */ self.api.registerMethod( 'core', 'registerRowsProcessor', this.registerRowsProcessor ); /** * @ngdoc function * @name registerColumnsProcessor * @methodOf ui.grid.core.api:PublicApi * @description * Register a "columns processor" function. When the columns are updated, * the grid calls each registered "columns processor", which has a chance * to alter the set of columns as long as the count is not * modified. * * @param {function(renderedColumnsToProcess, rows )} processorFunction columns processor function, which * is run in the context of the grid (i.e. this for the function will be the grid), and must * return the updated columns list, which is passed to the next processor in the chain * @param {number} priority the priority of this processor. In general we try to do them in 100s to leave room * for other people to inject columns processors at intermediate priorities. Lower priority columnsProcessors run earlier. * * At present allRowsVisible is running at 50, filter is running at 100, sort is at 200, grouping at 400, selectable rows at 500, pagination at 900 (pagination will generally want to be last) */ self.api.registerMethod( 'core', 'registerColumnsProcessor', this.registerColumnsProcessor ); /** * @ngdoc function * @name sortHandleNulls * @methodOf ui.grid.core.api:PublicApi * @description A null handling method that can be used when building custom sort * functions * @example * <pre> * mySortFn = function(a, b) { * var nulls = $scope.gridApi.core.sortHandleNulls(a, b); * if ( nulls !== null ){ * return nulls; * } else { * // your code for sorting here * }; * </pre> * @param {object} a sort value a * @param {object} b sort value b * @returns {number} null if there were no nulls/undefineds, otherwise returns * a sort value that should be passed back from the sort function * */ self.api.registerMethod( 'core', 'sortHandleNulls', rowSorter.handleNulls ); /** * @ngdoc function * @name sortChanged * @methodOf ui.grid.core.api:PublicApi * @description The sort criteria on one or more columns has * changed. Provides as parameters the grid and the output of * getColumnSorting, which is an array of gridColumns * that have sorting on them, sorted in priority order. * * @param {$scope} scope The scope of the controller. This is used to deregister this event when the scope is destroyed. * @param {Function} callBack Will be called when the event is emited. The function passes back an array of columns with * sorts on them, in priority order. * * @example * <pre> * gridApi.core.on.sortChanged( $scope, function(sortColumns){ * // do something * }); * </pre> */ self.api.registerEvent( 'core', 'sortChanged' ); /** * @ngdoc function * @name columnVisibilityChanged * @methodOf ui.grid.core.api:PublicApi * @description The visibility of a column has changed, * the column itself is passed out as a parameter of the event. * * @param {$scope} scope The scope of the controller. This is used to deregister this event when the scope is destroyed. * @param {Function} callBack Will be called when the event is emited. The function passes back the GridCol that has changed. * * @example * <pre> * gridApi.core.on.columnVisibilityChanged( $scope, function (column) { * // do something * } ); * </pre> */ self.api.registerEvent( 'core', 'columnVisibilityChanged' ); /** * @ngdoc method * @name notifyDataChange * @methodOf ui.grid.core.api:PublicApi * @description Notify the grid that a data or config change has occurred, * where that change isn't something the grid was otherwise noticing. This * might be particularly relevant where you've changed values within the data * and you'd like cell classes to be re-evaluated, or changed config within * the columnDef and you'd like headerCellClasses to be re-evaluated. * @param {string} type one of the * uiGridConstants.dataChange values (ALL, ROW, EDIT, COLUMN), which tells * us which refreshes to fire. * */ self.api.registerMethod( 'core', 'notifyDataChange', this.notifyDataChange ); /** * @ngdoc method * @name clearAllFilters * @methodOf ui.grid.core.api:PublicApi * @description Clears all filters and optionally refreshes the visible rows. * @param {object} refreshRows Defaults to true. * @param {object} clearConditions Defaults to false. * @param {object} clearFlags Defaults to false. * @returns {promise} If `refreshRows` is true, returns a promise of the rows refreshing. */ self.api.registerMethod('core', 'clearAllFilters', this.clearAllFilters); self.registerDataChangeCallback( self.columnRefreshCallback, [uiGridConstants.dataChange.COLUMN]); self.registerDataChangeCallback( self.processRowsCallback, [uiGridConstants.dataChange.EDIT]); self.registerDataChangeCallback( self.updateFooterHeightCallback, [uiGridConstants.dataChange.OPTIONS]); self.registerStyleComputation({ priority: 10, func: self.getFooterStyles }); }; Grid.prototype.calcFooterHeight = function () { if (!this.hasFooter()) { return 0; } var height = 0; if (this.options.showGridFooter) { height += this.options.gridFooterHeight; } height += this.calcColumnFooterHeight(); return height; }; Grid.prototype.calcColumnFooterHeight = function () { var height = 0; if (this.options.showColumnFooter) { height += this.options.columnFooterHeight; } return height; }; Grid.prototype.getFooterStyles = function () { var style = '.grid' + this.id + ' .ui-grid-footer-aggregates-row { height: ' + this.options.columnFooterHeight + 'px; }'; style += ' .grid' + this.id + ' .ui-grid-footer-info { height: ' + this.options.gridFooterHeight + 'px; }'; return style; }; Grid.prototype.hasFooter = function () { return this.options.showGridFooter || this.options.showColumnFooter; }; /** * @ngdoc function * @name isRTL * @methodOf ui.grid.class:Grid * @description Returns true if grid is RightToLeft */ Grid.prototype.isRTL = function () { return this.rtl; }; /** * @ngdoc function * @name registerColumnBuilder * @methodOf ui.grid.class:Grid * @description When the build creates columns from column definitions, the columnbuilders will be called to add * additional properties to the column. * @param {function(colDef, col, gridOptions)} columnBuilder function to be called */ Grid.prototype.registerColumnBuilder = function registerColumnBuilder(columnBuilder) { this.columnBuilders.push(columnBuilder); }; /** * @ngdoc function * @name buildColumnDefsFromData * @methodOf ui.grid.class:Grid * @description Populates columnDefs from the provided data * @param {function(colDef, col, gridOptions)} rowBuilder function to be called */ Grid.prototype.buildColumnDefsFromData = function (dataRows){ this.options.columnDefs = gridUtil.getColumnsFromData(dataRows, this.options.excludeProperties); }; /** * @ngdoc function * @name registerRowBuilder * @methodOf ui.grid.class:Grid * @description When the build creates rows from gridOptions.data, the rowBuilders will be called to add * additional properties to the row. * @param {function(row, gridOptions)} rowBuilder function to be called */ Grid.prototype.registerRowBuilder = function registerRowBuilder(rowBuilder) { this.rowBuilders.push(rowBuilder); }; /** * @ngdoc function * @name registerDataChangeCallback * @methodOf ui.grid.class:Grid * @description When a data change occurs, the data change callbacks of the specified type * will be called. The rules are: * * - when the data watch fires, that is considered a ROW change (the data watch only notices * added or removed rows) * - when the api is called to inform us of a change, the declared type of that change is used * - when a cell edit completes, the EDIT callbacks are triggered * - when the columnDef watch fires, the COLUMN callbacks are triggered * - when the options watch fires, the OPTIONS callbacks are triggered * * For a given event: * - ALL calls ROW, EDIT, COLUMN, OPTIONS and ALL callbacks * - ROW calls ROW and ALL callbacks * - EDIT calls EDIT and ALL callbacks * - COLUMN calls COLUMN and ALL callbacks * - OPTIONS calls OPTIONS and ALL callbacks * * @param {function(grid)} callback function to be called * @param {array} types the types of data change you want to be informed of. Values from * the uiGridConstants.dataChange values ( ALL, EDIT, ROW, COLUMN, OPTIONS ). Optional and defaults to * ALL * @returns {function} deregister function - a function that can be called to deregister this callback */ Grid.prototype.registerDataChangeCallback = function registerDataChangeCallback(callback, types, _this) { var uid = gridUtil.nextUid(); if ( !types ){ types = [uiGridConstants.dataChange.ALL]; } if ( !Array.isArray(types)){ gridUtil.logError("Expected types to be an array or null in registerDataChangeCallback, value passed was: " + types ); } this.dataChangeCallbacks[uid] = { callback: callback, types: types, _this:_this }; var self = this; var deregisterFunction = function() { delete self.dataChangeCallbacks[uid]; }; return deregisterFunction; }; /** * @ngdoc function * @name callDataChangeCallbacks * @methodOf ui.grid.class:Grid * @description Calls the callbacks based on the type of data change that * has occurred. Always calls the ALL callbacks, calls the ROW, EDIT, COLUMN and OPTIONS callbacks if the * event type is matching, or if the type is ALL. * @param {number} type the type of event that occurred - one of the * uiGridConstants.dataChange values (ALL, ROW, EDIT, COLUMN, OPTIONS) */ Grid.prototype.callDataChangeCallbacks = function callDataChangeCallbacks(type, options) { angular.forEach( this.dataChangeCallbacks, function( callback, uid ){ if ( callback.types.indexOf( uiGridConstants.dataChange.ALL ) !== -1 || callback.types.indexOf( type ) !== -1 || type === uiGridConstants.dataChange.ALL ) { if (callback._this) { callback.callback.apply(callback._this,this); } else { callback.callback( this ); } } }, this); }; /** * @ngdoc function * @name notifyDataChange * @methodOf ui.grid.class:Grid * @description Notifies us that a data change has occurred, used in the public * api for users to tell us when they've changed data or some other event that * our watches cannot pick up * @param {string} type the type of event that occurred - one of the * uiGridConstants.dataChange values (ALL, ROW, EDIT, COLUMN) */ Grid.prototype.notifyDataChange = function notifyDataChange(type) { var constants = uiGridConstants.dataChange; if ( type === constants.ALL || type === constants.COLUMN || type === constants.EDIT || type === constants.ROW || type === constants.OPTIONS ){ this.callDataChangeCallbacks( type ); } else { gridUtil.logError("Notified of a data change, but the type was not recognised, so no action taken, type was: " + type); } }; /** * @ngdoc function * @name columnRefreshCallback * @methodOf ui.grid.class:Grid * @description refreshes the grid when a column refresh * is notified, which triggers handling of the visible flag. * This is called on uiGridConstants.dataChange.COLUMN, and is * registered as a dataChangeCallback in grid.js * @param {string} name column name */ Grid.prototype.columnRefreshCallback = function columnRefreshCallback( grid ){ grid.buildColumns(); grid.queueGridRefresh(); }; /** * @ngdoc function * @name processRowsCallback * @methodOf ui.grid.class:Grid * @description calls the row processors, specifically * intended to reset the sorting when an edit is called, * registered as a dataChangeCallback on uiGridConstants.dataChange.EDIT * @param {string} name column name */ Grid.prototype.processRowsCallback = function processRowsCallback( grid ){ grid.queueGridRefresh(); }; /** * @ngdoc function * @name updateFooterHeightCallback * @methodOf ui.grid.class:Grid * @description recalculates the footer height, * registered as a dataChangeCallback on uiGridConstants.dataChange.OPTIONS * @param {string} name column name */ Grid.prototype.updateFooterHeightCallback = function updateFooterHeightCallback( grid ){ grid.footerHeight = grid.calcFooterHeight(); grid.columnFooterHeight = grid.calcColumnFooterHeight(); }; /** * @ngdoc function * @name getColumn * @methodOf ui.grid.class:Grid * @description returns a grid column for the column name * @param {string} name column name */ Grid.prototype.getColumn = function getColumn(name) { var columns = this.columns.filter(function (column) { return column.colDef.name === name; }); return columns.length > 0 ? columns[0] : null; }; /** * @ngdoc function * @name getColDef * @methodOf ui.grid.class:Grid * @description returns a grid colDef for the column name * @param {string} name column.field */ Grid.prototype.getColDef = function getColDef(name) { var colDefs = this.options.columnDefs.filter(function (colDef) { return colDef.name === name; }); return colDefs.length > 0 ? colDefs[0] : null; }; /** * @ngdoc function * @name assignTypes * @methodOf ui.grid.class:Grid * @description uses the first row of data to assign colDef.type for any types not defined. */ /** * @ngdoc property * @name type * @propertyOf ui.grid.class:GridOptions.columnDef * @description the type of the column, used in sorting. If not provided then the * grid will guess the type. Add this only if the grid guessing is not to your * satisfaction. One of: * - 'string' * - 'boolean' * - 'number' * - 'date' * - 'object' * - 'numberStr' * Note that if you choose date, your dates should be in a javascript date type * */ Grid.prototype.assignTypes = function(){ var self = this; self.options.columnDefs.forEach(function (colDef, index) { //Assign colDef type if not specified if (!colDef.type) { var col = new GridColumn(colDef, index, self); var firstRow = self.rows.length > 0 ? self.rows[0] : null; if (firstRow) { colDef.type = gridUtil.guessType(self.getCellValue(firstRow, col)); } else { colDef.type = 'string'; } } }); }; /** * @ngdoc function * @name isRowHeaderColumn * @methodOf ui.grid.class:Grid * @description returns true if the column is a row Header * @param {object} column column */ Grid.prototype.isRowHeaderColumn = function isRowHeaderColumn(column) { return this.rowHeaderColumns.indexOf(column) !== -1; }; /** * @ngdoc function * @name addRowHeaderColumn * @methodOf ui.grid.class:Grid * @description adds a row header column to the grid * @param {object} column def */ Grid.prototype.addRowHeaderColumn = function addRowHeaderColumn(colDef) { var self = this; var rowHeaderCol = new GridColumn(colDef, gridUtil.nextUid(), self); rowHeaderCol.isRowHeader = true; if (self.isRTL()) { self.createRightContainer(); rowHeaderCol.renderContainer = 'right'; } else { self.createLeftContainer(); rowHeaderCol.renderContainer = 'left'; } // relies on the default column builder being first in array, as it is instantiated // as part of grid creation self.columnBuilders[0](colDef,rowHeaderCol,self.options) .then(function(){ rowHeaderCol.enableFiltering = false; rowHeaderCol.enableSorting = false; rowHeaderCol.enableHiding = false; self.rowHeaderColumns.push(rowHeaderCol); self.buildColumns() .then( function() { self.preCompileCellTemplates(); self.queueGridRefresh(); }); }); }; /** * @ngdoc function * @name getOnlyDataColumns * @methodOf ui.grid.class:Grid * @description returns all columns except for rowHeader columns */ Grid.prototype.getOnlyDataColumns = function getOnlyDataColumns() { var self = this; var cols = []; self.columns.forEach(function (col) { if (self.rowHeaderColumns.indexOf(col) === -1) { cols.push(col); } }); return cols; }; /** * @ngdoc function * @name buildColumns * @methodOf ui.grid.class:Grid * @description creates GridColumn objects from the columnDefinition. Calls each registered * columnBuilder to further process the column * @param {object} options An object contains options to use when building columns * * * **orderByColumnDefs**: defaults to **false**. When true, `buildColumns` will reorder existing columns according to the order within the column definitions. * * @returns {Promise} a promise to load any needed column resources */ Grid.prototype.buildColumns = function buildColumns(opts) { var options = { orderByColumnDefs: false }; angular.extend(options, opts); // gridUtil.logDebug('buildColumns'); var self = this; var builderPromises = []; var headerOffset = self.rowHeaderColumns.length; var i; // Remove any columns for which a columnDef cannot be found // Deliberately don't use forEach, as it doesn't like splice being called in the middle // Also don't cache columns.length, as it will change during this operation for (i = 0; i < self.columns.length; i++){ if (!self.getColDef(self.columns[i].name)) { self.columns.splice(i, 1); i--; } } //add row header columns to the grid columns array _after_ columns without columnDefs have been removed self.rowHeaderColumns.forEach(function (rowHeaderColumn) { self.columns.unshift(rowHeaderColumn); }); // look at each column def, and update column properties to match. If the column def // doesn't have a column, then splice in a new gridCol self.options.columnDefs.forEach(function (colDef, index) { self.preprocessColDef(colDef); var col = self.getColumn(colDef.name); if (!col) { col = new GridColumn(colDef, gridUtil.nextUid(), self); self.columns.splice(index + headerOffset, 0, col); } else { // tell updateColumnDef that the column was pre-existing col.updateColumnDef(colDef, false); } self.columnBuilders.forEach(function (builder) { builderPromises.push(builder.call(self, colDef, col, self.options)); }); }); /*** Reorder columns if necessary ***/ if (!!options.orderByColumnDefs) { // Create a shallow copy of the columns as a cache var columnCache = self.columns.slice(0); // We need to allow for the "row headers" when mapping from the column defs array to the columns array // If we have a row header in columns[0] and don't account for it we'll overwrite it with the column in columnDefs[0] // Go through all the column defs, use the shorter of columns length and colDefs.length because if a user has given two columns the same name then // columns will be shorter than columnDefs. In this situation we'll avoid an error, but the user will still get an unexpected result var len = Math.min(self.options.columnDefs.length, self.columns.length); for (i = 0; i < len; i++) { // If the column at this index has a different name than the column at the same index in the column defs... if (self.columns[i + headerOffset].name !== self.options.columnDefs[i].name) { // Replace the one in the cache with the appropriate column columnCache[i + headerOffset] = self.getColumn(self.options.columnDefs[i].name); } else { // Otherwise just copy over the one from the initial columns columnCache[i + headerOffset] = self.columns[i + headerOffset]; } } // Empty out the columns array, non-destructively self.columns.length = 0; // And splice in the updated, ordered columns from the cache Array.prototype.splice.apply(self.columns, [0, 0].concat(columnCache)); } return $q.all(builderPromises).then(function(){ if (self.rows.length > 0){ self.assignTypes(); } }); }; /** * @ngdoc function * @name preCompileCellTemplates * @methodOf ui.grid.class:Grid * @description precompiles all cell templates */ Grid.prototype.preCompileCellTemplates = function() { var self = this; var preCompileTemplate = function( col ) { var html = col.cellTemplate.replace(uiGridConstants.MODEL_COL_FIELD, self.getQualifiedColField(col)); html = html.replace(uiGridConstants.COL_FIELD, 'grid.getCellValue(row, col)'); var compiledElementFn = $compile(html); col.compiledElementFn = compiledElementFn; if (col.compiledElementFnDefer) { col.compiledElementFnDefer.resolve(col.compiledElementFn); } }; this.columns.forEach(function (col) { if ( col.cellTemplate ){ preCompileTemplate( col ); } else if ( col.cellTemplatePromise ){ col.cellTemplatePromise.then( function() { preCompileTemplate( col ); }); } }); }; /** * @ngdoc function * @name getGridQualifiedColField * @methodOf ui.grid.class:Grid * @description Returns the $parse-able accessor for a column within its $scope * @param {GridColumn} col col object */ Grid.prototype.getQualifiedColField = function (col) { return 'row.entity.' + gridUtil.preEval(col.field); }; /** * @ngdoc function * @name createLeftContainer * @methodOf ui.grid.class:Grid * @description creates the left render container if it doesn't already exist */ Grid.prototype.createLeftContainer = function() { if (!this.hasLeftContainer()) { this.renderContainers.left = new GridRenderContainer('left', this, { disableColumnOffset: true }); } }; /** * @ngdoc function * @name createRightContainer * @methodOf ui.grid.class:Grid * @description creates the right render container if it doesn't already exist */ Grid.prototype.createRightContainer = function() { if (!this.hasRightContainer()) { this.renderContainers.right = new GridRenderContainer('right', this, { disableColumnOffset: true }); } }; /** * @ngdoc function * @name hasLeftContainer * @methodOf ui.grid.class:Grid * @description returns true if leftContainer exists */ Grid.prototype.hasLeftContainer = function() { return this.renderContainers.left !== undefined; }; /** * @ngdoc function * @name hasRightContainer * @methodOf ui.grid.class:Grid * @description returns true if rightContainer exists */ Grid.prototype.hasRightContainer = function() { return this.renderContainers.right !== undefined; }; /** * undocumented function * @name preprocessColDef * @methodOf ui.grid.class:Grid * @description defaults the name property from field to maintain backwards compatibility with 2.x * validates that name or field is present */ Grid.prototype.preprocessColDef = function preprocessColDef(colDef) { var self = this; if (!colDef.field && !colDef.name) { throw new Error('colDef.name or colDef.field property is required'); } //maintain backwards compatibility with 2.x //field was required in 2.x. now name is required if (colDef.name === undefined && colDef.field !== undefined) { // See if the column name already exists: var newName = colDef.field, counter = 2; while (self.getColumn(newName)) { newName = colDef.field + counter.toString(); counter++; } colDef.name = newName; } }; // Return a list of items that exist in the `n` array but not the `o` array. Uses optional property accessors passed as third & fourth parameters Grid.prototype.newInN = function newInN(o, n, oAccessor, nAccessor) { var self = this; var t = []; for (var i = 0; i < n.length; i++) { var nV = nAccessor ? n[i][nAccessor] : n[i]; var found = false; for (var j = 0; j < o.length; j++) { var oV = oAccessor ? o[j][oAccessor] : o[j]; if (self.options.rowEquality(nV, oV)) { found = true; break; } } if (!found) { t.push(nV); } } return t; }; /** * @ngdoc function * @name getRow * @methodOf ui.grid.class:Grid * @description returns the GridRow that contains the rowEntity * @param {object} rowEntity the gridOptions.data array element instance * @param {array} rows [optional] the rows to look in - if not provided then * looks in grid.rows */ Grid.prototype.getRow = function getRow(rowEntity, lookInRows) { var self = this; lookInRows = typeof(lookInRows) === 'undefined' ? self.rows : lookInRows; var rows = lookInRows.filter(function (row) { return self.options.rowEquality(row.entity, rowEntity); }); return rows.length > 0 ? rows[0] : null; }; /** * @ngdoc function * @name modifyRows * @methodOf ui.grid.class:Grid * @description creates or removes GridRow objects from the newRawData array. Calls each registered * rowBuilder to further process the row * * This method aims to achieve three things: * 1. the resulting rows array is in the same order as the newRawData, we'll call * rowsProcessors immediately after to sort the data anyway * 2. if we have row hashing available, we try to use the rowHash to find the row * 3. no memory leaks - rows that are no longer in newRawData need to be garbage collected * * The basic logic flow makes use of the newRawData, oldRows and oldHash, and creates * the newRows and newHash * * ``` * newRawData.forEach newEntity * if (hashing enabled) * check oldHash for newEntity * else * look for old row directly in oldRows * if !oldRowFound // must be a new row * create newRow * append to the newRows and add to newHash * run the processors * * Rows are identified using the hashKey if configured. If not configured, then rows * are identified using the gridOptions.rowEquality function */ Grid.prototype.modifyRows = function modifyRows(newRawData) { var self = this; var oldRows = self.rows.slice(0); var oldRowHash = self.rowHashMap || self.createRowHashMap(); self.rowHashMap = self.createRowHashMap(); self.rows.length = 0; newRawData.forEach( function( newEntity, i ) { var newRow; if ( self.options.enableRowHashing ){ // if hashing is enabled, then this row will be in the hash if we already know about it newRow = oldRowHash.get( newEntity ); } else { // otherwise, manually search the oldRows to see if we can find this row newRow = self.getRow(newEntity, oldRows); } // if we didn't find the row, it must be new, so create it if ( !newRow ){ newRow = self.processRowBuilders(new GridRow(newEntity, i, self)); } self.rows.push( newRow ); self.rowHashMap.put( newEntity, newRow ); }); self.assignTypes(); var p1 = $q.when(self.processRowsProcessors(self.rows)) .then(function (renderableRows) { return self.setVisibleRows(renderableRows); }); var p2 = $q.when(self.processColumnsProcessors(self.columns)) .then(function (renderableColumns) { return self.setVisibleColumns(renderableColumns); }); return $q.all([p1, p2]); }; /** * Private Undocumented Method * @name addRows * @methodOf ui.grid.class:Grid * @description adds the newRawData array of rows to the grid and calls all registered * rowBuilders. this keyword will reference the grid */ Grid.prototype.addRows = function addRows(newRawData) { var self = this; var existingRowCount = self.rows.length; for (var i = 0; i < newRawData.length; i++) { var newRow = self.processRowBuilders(new GridRow(newRawData[i], i + existingRowCount, self)); if (self.options.enableRowHashing) { var found = self.rowHashMap.get(newRow.entity); if (found) { found.row = newRow; } } self.rows.push(newRow); } }; /** * @ngdoc function * @name processRowBuilders * @methodOf ui.grid.class:Grid * @description processes all RowBuilders for the gridRow * @param {GridRow} gridRow reference to gridRow * @returns {GridRow} the gridRow with all additional behavior added */ Grid.prototype.processRowBuilders = function processRowBuilders(gridRow) { var self = this; self.rowBuilders.forEach(function (builder) { builder.call(self, gridRow, self.options); }); return gridRow; }; /** * @ngdoc function * @name registerStyleComputation * @methodOf ui.grid.class:Grid * @description registered a styleComputation function * * If the function returns a value it will be appended into the grid's `<style>` block * @param {function($scope)} styleComputation function */ Grid.prototype.registerStyleComputation = function registerStyleComputation(styleComputationInfo) { this.styleComputations.push(styleComputationInfo); }; // NOTE (c0bra): We already have rowBuilders. I think these do exactly the same thing... // Grid.prototype.registerRowFilter = function(filter) { // // TODO(c0bra): validate filter? // this.rowFilters.push(filter); // }; // Grid.prototype.removeRowFilter = function(filter) { // var idx = this.rowFilters.indexOf(filter); // if (typeof(idx) !== 'undefined' && idx !== undefined) { // this.rowFilters.slice(idx, 1); // } // }; // Grid.prototype.processRowFilters = function(rows) { // var self = this; // self.rowFilters.forEach(function (filter) { // filter.call(self, rows); // }); // }; /** * @ngdoc function * @name registerRowsProcessor * @methodOf ui.grid.class:Grid * @description * * Register a "rows processor" function. When the rows are updated, * the grid calls each registered "rows processor", which has a chance * to alter the set of rows (sorting, etc) as long as the count is not * modified. * * @param {function(renderedRowsToProcess, columns )} processorFunction rows processor function, which * is run in the context of the grid (i.e. this for the function will be the grid), and must * return the updated rows list, which is passed to the next processor in the chain * @param {number} priority the priority of this processor. In general we try to do them in 100s to leave room * for other people to inject rows processors at intermediate priorities. Lower priority rowsProcessors run earlier. * * At present all rows visible is running at 50, filter is running at 100, sort is at 200, grouping at 400, selectable rows at 500, pagination at 900 (pagination will generally want to be last) * */ Grid.prototype.registerRowsProcessor = function registerRowsProcessor(processor, priority) { if (!angular.isFunction(processor)) { throw 'Attempt to register non-function rows processor: ' + processor; } this.rowsProcessors.push({processor: processor, priority: priority}); this.rowsProcessors.sort(function sortByPriority( a, b ){ return a.priority - b.priority; }); }; /** * @ngdoc function * @name removeRowsProcessor * @methodOf ui.grid.class:Grid * @param {function(renderableRows)} rows processor function * @description Remove a registered rows processor */ Grid.prototype.removeRowsProcessor = function removeRowsProcessor(processor) { var idx = -1; this.rowsProcessors.forEach(function(rowsProcessor, index){ if ( rowsProcessor.processor === processor ){ idx = index; } }); if ( idx !== -1 ) { this.rowsProcessors.splice(idx, 1); } }; /** * Private Undocumented Method * @name processRowsProcessors * @methodOf ui.grid.class:Grid * @param {Array[GridRow]} The array of "renderable" rows * @param {Array[GridColumn]} The array of columns * @description Run all the registered rows processors on the array of renderable rows */ Grid.prototype.processRowsProcessors = function processRowsProcessors(renderableRows) { var self = this; // Create a shallow copy of the rows so that we can safely sort them without altering the original grid.rows sort order var myRenderableRows = renderableRows.slice(0); // Return myRenderableRows with no processing if we have no rows processors if (self.rowsProcessors.length === 0) { return $q.when(myRenderableRows); } // Counter for iterating through rows processors var i = 0; // Promise for when we're done with all the processors var finished = $q.defer(); // This function will call the processor in self.rowsProcessors at index 'i', and then // when done will call the next processor in the list, using the output from the processor // at i as the argument for 'renderedRowsToProcess' on the next iteration. // // If we're at the end of the list of processors, we resolve our 'finished' callback with // the result. function startProcessor(i, renderedRowsToProcess) { // Get the processor at 'i' var processor = self.rowsProcessors[i].processor; // Call the processor, passing in the rows to process and the current columns // (note: it's wrapped in $q.when() in case the processor does not return a promise) return $q.when( processor.call(self, renderedRowsToProcess, self.columns) ) .then(function handleProcessedRows(processedRows) { // Check for errors if (!processedRows) { throw "Processor at index " + i + " did not return a set of renderable rows"; } if (!angular.isArray(processedRows)) { throw "Processor at index " + i + " did not return an array"; } // Processor is done, increment the counter i++; // If we're not done with the processors, call the next one if (i <= self.rowsProcessors.length - 1) { return startProcessor(i, processedRows); } // We're done! Resolve the 'finished' promise else { finished.resolve(processedRows); } }); } // Start on the first processor startProcessor(0, myRenderableRows); return finished.promise; }; Grid.prototype.setVisibleRows = function setVisibleRows(rows) { var self = this; // Reset all the render container row caches for (var i in self.renderContainers) { var container = self.renderContainers[i]; container.canvasHeightShouldUpdate = true; if ( typeof(container.visibleRowCache) === 'undefined' ){ container.visibleRowCache = []; } else { container.visibleRowCache.length = 0; } } // rows.forEach(function (row) { for (var ri = 0; ri < rows.length; ri++) { var row = rows[ri]; var targetContainer = (typeof(row.renderContainer) !== 'undefined' && row.renderContainer) ? row.renderContainer : 'body'; // If the row is visible if (row.visible) { self.renderContainers[targetContainer].visibleRowCache.push(row); } } self.api.core.raise.rowsRendered(this.api); }; /** * @ngdoc function * @name registerColumnsProcessor * @methodOf ui.grid.class:Grid * @param {function(renderedColumnsToProcess, rows)} columnProcessor column processor function, which * is run in the context of the grid (i.e. this for the function will be the grid), and * which must return an updated renderedColumnsToProcess which can be passed to the next processor * in the chain * @param {number} priority the priority of this processor. In general we try to do them in 100s to leave room * for other people to inject columns processors at intermediate priorities. Lower priority columnsProcessors run earlier. * * At present all rows visible is running at 50, filter is running at 100, sort is at 200, grouping at 400, selectable rows at 500, pagination at 900 (pagination will generally want to be last) * @description Register a "columns processor" function. When the columns are updated, the grid calls each registered "columns processor", which has a chance to alter the set of columns, as long as the count is not modified. */ Grid.prototype.registerColumnsProcessor = function registerColumnsProcessor(processor, priority) { if (!angular.isFunction(processor)) { throw 'Attempt to register non-function rows processor: ' + processor; } this.columnsProcessors.push({processor: processor, priority: priority}); this.columnsProcessors.sort(function sortByPriority( a, b ){ return a.priority - b.priority; }); }; Grid.prototype.removeColumnsProcessor = function removeColumnsProcessor(processor) { var idx = this.columnsProcessors.indexOf(processor); if (typeof(idx) !== 'undefined' && idx !== undefined) { this.columnsProcessors.splice(idx, 1); } }; Grid.prototype.processColumnsProcessors = function processColumnsProcessors(renderableColumns) { var self = this; // Create a shallow copy of the rows so that we can safely sort them without altering the original grid.rows sort order var myRenderableColumns = renderableColumns.slice(0); // Return myRenderableRows with no processing if we have no rows processors if (self.columnsProcessors.length === 0) { return $q.when(myRenderableColumns); } // Counter for iterating through rows processors var i = 0; // Promise for when we're done with all the processors var finished = $q.defer(); // This function will call the processor in self.rowsProcessors at index 'i', and then // when done will call the next processor in the list, using the output from the processor // at i as the argument for 'renderedRowsToProcess' on the next iteration. // // If we're at the end of the list of processors, we resolve our 'finished' callback with // the result. function startProcessor(i, renderedColumnsToProcess) { // Get the processor at 'i' var processor = self.columnsProcessors[i].processor; // Call the processor, passing in the rows to process and the current columns // (note: it's wrapped in $q.when() in case the processor does not return a promise) return $q.when( processor.call(self, renderedColumnsToProcess, self.rows) ) .then(function handleProcessedRows(processedColumns) { // Check for errors if (!processedColumns) { throw "Processor at index " + i + " did not return a set of renderable rows"; } if (!angular.isArray(processedColumns)) { throw "Processor at index " + i + " did not return an array"; } // Processor is done, increment the counter i++; // If we're not done with the processors, call the next one if (i <= self.columnsProcessors.length - 1) { return startProcessor(i, myRenderableColumns); } // We're done! Resolve the 'finished' promise else { finished.resolve(myRenderableColumns); } }); } // Start on the first processor startProcessor(0, myRenderableColumns); return finished.promise; }; Grid.prototype.setVisibleColumns = function setVisibleColumns(columns) { // gridUtil.logDebug('setVisibleColumns'); var self = this; // Reset all the render container row caches for (var i in self.renderContainers) { var container = self.renderContainers[i]; container.visibleColumnCache.length = 0; } for (var ci = 0; ci < columns.length; ci++) { var column = columns[ci]; // If the column is visible if (column.visible) { // If the column has a container specified if (typeof(column.renderContainer) !== 'undefined' && column.renderContainer) { self.renderContainers[column.renderContainer].visibleColumnCache.push(column); } // If not, put it into the body container else { self.renderContainers.body.visibleColumnCache.push(column); } } } }; /** * @ngdoc function * @name handleWindowResize * @methodOf ui.grid.class:Grid * @description Triggered when the browser window resizes; automatically resizes the grid */ Grid.prototype.handleWindowResize = function handleWindowResize($event) { var self = this; self.gridWidth = gridUtil.elementWidth(self.element); self.gridHeight = gridUtil.elementHeight(self.element); self.queueRefresh(); }; /** * @ngdoc function * @name queueRefresh * @methodOf ui.grid.class:Grid * @description queues a grid refreshCanvas, a way of debouncing all the refreshes we might otherwise issue */ Grid.prototype.queueRefresh = function queueRefresh() { var self = this; if (self.refreshCanceller) { $timeout.cancel(self.refreshCanceller); } self.refreshCanceller = $timeout(function () { self.refreshCanvas(true); }); self.refreshCanceller.then(function () { self.refreshCanceller = null; }); return self.refreshCanceller; }; /** * @ngdoc function * @name queueGridRefresh * @methodOf ui.grid.class:Grid * @description queues a grid refresh, a way of debouncing all the refreshes we might otherwise issue */ Grid.prototype.queueGridRefresh = function queueGridRefresh() { var self = this; if (self.gridRefreshCanceller) { $timeout.cancel(self.gridRefreshCanceller); } self.gridRefreshCanceller = $timeout(function () { self.refresh(true); }); self.gridRefreshCanceller.then(function () { self.gridRefreshCanceller = null; }); return self.gridRefreshCanceller; }; /** * @ngdoc function * @name updateCanvasHeight * @methodOf ui.grid.class:Grid * @description flags all render containers to update their canvas height */ Grid.prototype.updateCanvasHeight = function updateCanvasHeight() { var self = this; for (var containerId in self.renderContainers) { if (self.renderContainers.hasOwnProperty(containerId)) { var container = self.renderContainers[containerId]; container.canvasHeightShouldUpdate = true; } } }; /** * @ngdoc function * @name buildStyles * @methodOf ui.grid.class:Grid * @description calls each styleComputation function */ // TODO: this used to take $scope, but couldn't see that it was used Grid.prototype.buildStyles = function buildStyles() { // gridUtil.logDebug('buildStyles'); var self = this; self.customStyles = ''; self.styleComputations .sort(function(a, b) { if (a.priority === null) { return 1; } if (b.priority === null) { return -1; } if (a.priority === null && b.priority === null) { return 0; } return a.priority - b.priority; }) .forEach(function (compInfo) { // this used to provide $scope as a second parameter, but I couldn't find any // style builders that used it, so removed it as part of moving to grid from controller var ret = compInfo.func.call(self); if (angular.isString(ret)) { self.customStyles += '\n' + ret; } }); }; Grid.prototype.minColumnsToRender = function minColumnsToRender() { var self = this; var viewport = this.getViewportWidth(); var min = 0; var totalWidth = 0; self.columns.forEach(function(col, i) { if (totalWidth < viewport) { totalWidth += col.drawnWidth; min++; } else { var currWidth = 0; for (var j = i; j >= i - min; j--) { currWidth += self.columns[j].drawnWidth; } if (currWidth < viewport) { min++; } } }); return min; }; Grid.prototype.getBodyHeight = function getBodyHeight() { // Start with the viewportHeight var bodyHeight = this.getViewportHeight(); // Add the horizontal scrollbar height if there is one //if (typeof(this.horizontalScrollbarHeight) !== 'undefined' && this.horizontalScrollbarHeight !== undefined && this.horizontalScrollbarHeight > 0) { // bodyHeight = bodyHeight + this.horizontalScrollbarHeight; //} return bodyHeight; }; // NOTE: viewport drawable height is the height of the grid minus the header row height (including any border) // TODO(c0bra): account for footer height Grid.prototype.getViewportHeight = function getViewportHeight() { var self = this; var viewPortHeight = this.gridHeight - this.headerHeight - this.footerHeight; // Account for native horizontal scrollbar, if present //if (typeof(this.horizontalScrollbarHeight) !== 'undefined' && this.horizontalScrollbarHeight !== undefined && this.horizontalScrollbarHeight > 0) { // viewPortHeight = viewPortHeight - this.horizontalScrollbarHeight; //} var adjustment = self.getViewportAdjustment(); viewPortHeight = viewPortHeight + adjustment.height; //gridUtil.logDebug('viewPortHeight', viewPortHeight); return viewPortHeight; }; Grid.prototype.getViewportWidth = function getViewportWidth() { var self = this; var viewPortWidth = this.gridWidth; //if (typeof(this.verticalScrollbarWidth) !== 'undefined' && this.verticalScrollbarWidth !== undefined && this.verticalScrollbarWidth > 0) { // viewPortWidth = viewPortWidth - this.verticalScrollbarWidth; //} var adjustment = self.getViewportAdjustment(); viewPortWidth = viewPortWidth + adjustment.width; //gridUtil.logDebug('getviewPortWidth', viewPortWidth); return viewPortWidth; }; Grid.prototype.getHeaderViewportWidth = function getHeaderViewportWidth() { var viewPortWidth = this.getViewportWidth(); //if (typeof(this.verticalScrollbarWidth) !== 'undefined' && this.verticalScrollbarWidth !== undefined && this.verticalScrollbarWidth > 0) { // viewPortWidth = viewPortWidth + this.verticalScrollbarWidth; //} return viewPortWidth; }; Grid.prototype.addVerticalScrollSync = function (containerId, callBackFn) { this.verticalScrollSyncCallBackFns[containerId] = callBackFn; }; Grid.prototype.addHorizontalScrollSync = function (containerId, callBackFn) { this.horizontalScrollSyncCallBackFns[containerId] = callBackFn; }; /** * Scroll needed containers by calling their ScrollSyncs * @param sourceContainerId the containerId that has already set it's top/left. * can be empty string which means all containers need to set top/left * @param scrollEvent */ Grid.prototype.scrollContainers = function (sourceContainerId, scrollEvent) { if (scrollEvent.y) { //default for no container Id (ex. mousewheel means that all containers must set scrollTop/Left) var verts = ['body','left', 'right']; this.flagScrollingVertically(scrollEvent); if (sourceContainerId === 'body') { verts = ['left', 'right']; } else if (sourceContainerId === 'left') { verts = ['body', 'right']; } else if (sourceContainerId === 'right') { verts = ['body', 'left']; } for (var i = 0; i < verts.length; i++) { var id = verts[i]; if (this.verticalScrollSyncCallBackFns[id]) { this.verticalScrollSyncCallBackFns[id](scrollEvent); } } } if (scrollEvent.x) { //default for no container Id (ex. mousewheel means that all containers must set scrollTop/Left) var horizs = ['body','bodyheader', 'bodyfooter']; this.flagScrollingHorizontally(scrollEvent); if (sourceContainerId === 'body') { horizs = ['bodyheader', 'bodyfooter']; } for (var j = 0; j < horizs.length; j++) { var idh = horizs[j]; if (this.horizontalScrollSyncCallBackFns[idh]) { this.horizontalScrollSyncCallBackFns[idh](scrollEvent); } } } }; Grid.prototype.registerViewportAdjuster = function registerViewportAdjuster(func) { this.viewportAdjusters.push(func); }; Grid.prototype.removeViewportAdjuster = function registerViewportAdjuster(func) { var idx = this.viewportAdjusters.indexOf(func); if (typeof(idx) !== 'undefined' && idx !== undefined) { this.viewportAdjusters.splice(idx, 1); } }; Grid.prototype.getViewportAdjustment = function getViewportAdjustment() { var self = this; var adjustment = { height: 0, width: 0 }; self.viewportAdjusters.forEach(function (func) { adjustment = func.call(this, adjustment); }); return adjustment; }; Grid.prototype.getVisibleRowCount = function getVisibleRowCount() { // var count = 0; // this.rows.forEach(function (row) { // if (row.visible) { // count++; // } // }); // return this.visibleRowCache.length; return this.renderContainers.body.visibleRowCache.length; }; Grid.prototype.getVisibleRows = function getVisibleRows() { return this.renderContainers.body.visibleRowCache; }; Grid.prototype.getVisibleColumnCount = function getVisibleColumnCount() { // var count = 0; // this.rows.forEach(function (row) { // if (row.visible) { // count++; // } // }); // return this.visibleRowCache.length; return this.renderContainers.body.visibleColumnCache.length; }; Grid.prototype.searchRows = function searchRows(renderableRows) { return rowSearcher.search(this, renderableRows, this.columns); }; Grid.prototype.sortByColumn = function sortByColumn(renderableRows) { return rowSorter.sort(this, renderableRows, this.columns); }; /** * @ngdoc function * @name getCellValue * @methodOf ui.grid.class:Grid * @description Gets the value of a cell for a particular row and column * @param {GridRow} row Row to access * @param {GridColumn} col Column to access */ Grid.prototype.getCellValue = function getCellValue(row, col){ if ( typeof(row.entity[ '$$' + col.uid ]) !== 'undefined' ) { return row.entity[ '$$' + col.uid].rendered; } else if (this.options.flatEntityAccess && typeof(col.field) !== 'undefined' ){ return row.entity[col.field]; } else { if (!col.cellValueGetterCache) { col.cellValueGetterCache = $parse(row.getEntityQualifiedColField(col)); } return col.cellValueGetterCache(row); } }; /** * @ngdoc function * @name getCellDisplayValue * @methodOf ui.grid.class:Grid * @description Gets the displayed value of a cell after applying any the `cellFilter` * @param {GridRow} row Row to access * @param {GridColumn} col Column to access */ Grid.prototype.getCellDisplayValue = function getCellDisplayValue(row, col) { if ( !col.cellDisplayGetterCache ) { var custom_filter = col.cellFilter ? " | " + col.cellFilter : ""; if (typeof(row.entity['$$' + col.uid]) !== 'undefined') { col.cellDisplayGetterCache = $parse(row.entity['$$' + col.uid].rendered + custom_filter); } else if (this.options.flatEntityAccess && typeof(col.field) !== 'undefined') { col.cellDisplayGetterCache = $parse(row.entity[col.field] + custom_filter); } else { col.cellDisplayGetterCache = $parse(row.getEntityQualifiedColField(col) + custom_filter); } } return col.cellDisplayGetterCache(row); }; Grid.prototype.getNextColumnSortPriority = function getNextColumnSortPriority() { var self = this, p = 0; self.columns.forEach(function (col) { if (col.sort && col.sort.priority && col.sort.priority > p) { p = col.sort.priority; } }); return p + 1; }; /** * @ngdoc function * @name resetColumnSorting * @methodOf ui.grid.class:Grid * @description Return the columns that the grid is currently being sorted by * @param {GridColumn} [excludedColumn] Optional GridColumn to exclude from having its sorting reset */ Grid.prototype.resetColumnSorting = function resetColumnSorting(excludeCol) { var self = this; self.columns.forEach(function (col) { if (col !== excludeCol && !col.suppressRemoveSort) { col.sort = {}; } }); }; /** * @ngdoc function * @name getColumnSorting * @methodOf ui.grid.class:Grid * @description Return the columns that the grid is currently being sorted by * @returns {Array[GridColumn]} An array of GridColumn objects */ Grid.prototype.getColumnSorting = function getColumnSorting() { var self = this; var sortedCols = [], myCols; // Iterate through all the columns, sorted by priority // Make local copy of column list, because sorting is in-place and we do not want to // change the original sequence of columns myCols = self.columns.slice(0); myCols.sort(rowSorter.prioritySort).forEach(function (col) { if (col.sort && typeof(col.sort.direction) !== 'undefined' && col.sort.direction && (col.sort.direction === uiGridConstants.ASC || col.sort.direction === uiGridConstants.DESC)) { sortedCols.push(col); } }); return sortedCols; }; /** * @ngdoc function * @name sortColumn * @methodOf ui.grid.class:Grid * @description Set the sorting on a given column, optionally resetting any existing sorting on the Grid. * Emits the sortChanged event whenever the sort criteria are changed. * @param {GridColumn} column Column to set the sorting on * @param {uiGridConstants.ASC|uiGridConstants.DESC} [direction] Direction to sort by, either descending or ascending. * If not provided, the column will iterate through the sort directions: ascending, descending, unsorted. * @param {boolean} [add] Add this column to the sorting. If not provided or set to `false`, the Grid will reset any existing sorting and sort * by this column only * @returns {Promise} A resolved promise that supplies the column. */ Grid.prototype.sortColumn = function sortColumn(column, directionOrAdd, add) { var self = this, direction = null; if (typeof(column) === 'undefined' || !column) { throw new Error('No column parameter provided'); } // Second argument can either be a direction or whether to add this column to the existing sort. // If it's a boolean, it's an add, otherwise, it's a direction if (typeof(directionOrAdd) === 'boolean') { add = directionOrAdd; } else { direction = directionOrAdd; } if (!add) { self.resetColumnSorting(column); column.sort.priority = 0; // Get the actual priority since there may be columns which have suppressRemoveSort set column.sort.priority = self.getNextColumnSortPriority(); } else if (!column.sort.priority){ column.sort.priority = self.getNextColumnSortPriority(); } if (!direction) { // Figure out the sort direction if (column.sort.direction && column.sort.direction === uiGridConstants.ASC) { column.sort.direction = uiGridConstants.DESC; } else if (column.sort.direction && column.sort.direction === uiGridConstants.DESC) { if ( column.colDef && column.suppressRemoveSort ){ column.sort.direction = uiGridConstants.ASC; } else { column.sort = {}; } } else { column.sort.direction = uiGridConstants.ASC; } } else { column.sort.direction = direction; } self.api.core.raise.sortChanged( self, self.getColumnSorting() ); return $q.when(column); }; /** * communicate to outside world that we are done with initial rendering */ Grid.prototype.renderingComplete = function(){ if (angular.isFunction(this.options.onRegisterApi)) { this.options.onRegisterApi(this.api); } this.api.core.raise.renderingComplete( this.api ); }; Grid.prototype.createRowHashMap = function createRowHashMap() { var self = this; var hashMap = new RowHashMap(); hashMap.grid = self; return hashMap; }; /** * @ngdoc function * @name refresh * @methodOf ui.grid.class:Grid * @description Refresh the rendered grid on screen. * @param {boolean} [rowsAltered] Optional flag for refreshing when the number of rows has changed. */ Grid.prototype.refresh = function refresh(rowsAltered) { var self = this; var p1 = self.processRowsProcessors(self.rows).then(function (renderableRows) { self.setVisibleRows(renderableRows); }); var p2 = self.processColumnsProcessors(self.columns).then(function (renderableColumns) { self.setVisibleColumns(renderableColumns); }); return $q.all([p1, p2]).then(function () { self.redrawInPlace(rowsAltered); self.refreshCanvas(true); }); }; /** * @ngdoc function * @name refreshRows * @methodOf ui.grid.class:Grid * @description Refresh the rendered rows on screen? Note: not functional at present * @returns {promise} promise that is resolved when render completes? * */ Grid.prototype.refreshRows = function refreshRows() { var self = this; return self.processRowsProcessors(self.rows) .then(function (renderableRows) { self.setVisibleRows(renderableRows); self.redrawInPlace(); self.refreshCanvas( true ); }); }; /** * @ngdoc function * @name refreshCanvas * @methodOf ui.grid.class:Grid * @description Builds all styles and recalculates much of the grid sizing * @param {object} buildStyles optional parameter. Use TBD * @returns {promise} promise that is resolved when the canvas * has been refreshed * */ Grid.prototype.refreshCanvas = function(buildStyles) { var self = this; if (buildStyles) { self.buildStyles(); } var p = $q.defer(); // Get all the header heights var containerHeadersToRecalc = []; for (var containerId in self.renderContainers) { if (self.renderContainers.hasOwnProperty(containerId)) { var container = self.renderContainers[containerId]; // Skip containers that have no canvasWidth set yet if (container.canvasWidth === null || isNaN(container.canvasWidth)) { continue; } if (container.header || container.headerCanvas) { container.explicitHeaderHeight = container.explicitHeaderHeight || null; container.explicitHeaderCanvasHeight = container.explicitHeaderCanvasHeight || null; containerHeadersToRecalc.push(container); } } } /* * * Here we loop through the headers, measuring each element as well as any header "canvas" it has within it. * * If any header is less than the largest header height, it will be resized to that so that we don't have headers * with different heights, which looks like a rendering problem * * We'll do the same thing with the header canvases, and give the header CELLS an explicit height if their canvas * is smaller than the largest canvas height. That was header cells without extra controls like filtering don't * appear shorter than other cells. * */ if (containerHeadersToRecalc.length > 0) { // Build the styles without the explicit header heights if (buildStyles) { self.buildStyles(); } // Putting in a timeout as it's not calculating after the grid element is rendered and filled out $timeout(function() { // var oldHeaderHeight = self.grid.headerHeight; // self.grid.headerHeight = gridUtil.outerElementHeight(self.header); var rebuildStyles = false; // Get all the header heights var maxHeaderHeight = 0; var maxHeaderCanvasHeight = 0; var i, container; var getHeight = function(oldVal, newVal){ if ( oldVal !== newVal){ rebuildStyles = true; } return newVal; }; for (i = 0; i < containerHeadersToRecalc.length; i++) { container = containerHeadersToRecalc[i]; // Skip containers that have no canvasWidth set yet if (container.canvasWidth === null || isNaN(container.canvasWidth)) { continue; } if (container.header) { var headerHeight = container.headerHeight = getHeight(container.headerHeight, parseInt(gridUtil.outerElementHeight(container.header), 10)); // Get the "inner" header height, that is the height minus the top and bottom borders, if present. We'll use it to make sure all the headers have a consistent height var topBorder = gridUtil.getBorderSize(container.header, 'top'); var bottomBorder = gridUtil.getBorderSize(container.header, 'bottom'); var innerHeaderHeight = parseInt(headerHeight - topBorder - bottomBorder, 10); innerHeaderHeight = innerHeaderHeight < 0 ? 0 : innerHeaderHeight; container.innerHeaderHeight = innerHeaderHeight; // If the header doesn't have an explicit height set, save the largest header height for use later // Explicit header heights are based off of the max we are calculating here. We never want to base the max on something we're setting explicitly if (!container.explicitHeaderHeight && innerHeaderHeight > maxHeaderHeight) { maxHeaderHeight = innerHeaderHeight; } } if (container.headerCanvas) { var headerCanvasHeight = container.headerCanvasHeight = getHeight(container.headerCanvasHeight, parseInt(gridUtil.outerElementHeight(container.headerCanvas), 10)); // If the header doesn't have an explicit canvas height, save the largest header canvas height for use later // Explicit header heights are based off of the max we are calculating here. We never want to base the max on something we're setting explicitly if (!container.explicitHeaderCanvasHeight && headerCanvasHeight > maxHeaderCanvasHeight) { maxHeaderCanvasHeight = headerCanvasHeight; } } } // Go through all the headers for (i = 0; i < containerHeadersToRecalc.length; i++) { container = containerHeadersToRecalc[i]; /* If: 1. We have a max header height 2. This container has a header height defined 3. And either this container has an explicit header height set, OR its header height is less than the max then: Give this container's header an explicit height so it will line up with the tallest header */ if ( maxHeaderHeight > 0 && typeof(container.headerHeight) !== 'undefined' && container.headerHeight !== null && (container.explicitHeaderHeight || container.headerHeight < maxHeaderHeight) ) { container.explicitHeaderHeight = getHeight(container.explicitHeaderHeight, maxHeaderHeight); } // Do the same as above except for the header canvas if ( maxHeaderCanvasHeight > 0 && typeof(container.headerCanvasHeight) !== 'undefined' && container.headerCanvasHeight !== null && (container.explicitHeaderCanvasHeight || container.headerCanvasHeight < maxHeaderCanvasHeight) ) { container.explicitHeaderCanvasHeight = getHeight(container.explicitHeaderCanvasHeight, maxHeaderCanvasHeight); } } // Rebuild styles if the header height has changed // The header height is used in body/viewport calculations and those are then used in other styles so we need it to be available if (buildStyles && rebuildStyles) { self.buildStyles(); } p.resolve(); }); } else { // Timeout still needs to be here to trigger digest after styles have been rebuilt $timeout(function() { p.resolve(); }); } return p.promise; }; /** * @ngdoc function * @name redrawCanvas * @methodOf ui.grid.class:Grid * @description Redraw the rows and columns based on our current scroll position * @param {boolean} [rowsAdded] Optional to indicate rows are added and the scroll percentage must be recalculated * */ Grid.prototype.redrawInPlace = function redrawInPlace(rowsAdded) { // gridUtil.logDebug('redrawInPlace'); var self = this; for (var i in self.renderContainers) { var container = self.renderContainers[i]; // gridUtil.logDebug('redrawing container', i); if (rowsAdded) { container.adjustRows(container.prevScrollTop, null); container.adjustColumns(container.prevScrollLeft, null); } else { container.adjustRows(null, container.prevScrolltopPercentage); container.adjustColumns(null, container.prevScrollleftPercentage); } } }; /** * @ngdoc function * @name hasLeftContainerColumns * @methodOf ui.grid.class:Grid * @description returns true if leftContainer has columns */ Grid.prototype.hasLeftContainerColumns = function () { return this.hasLeftContainer() && this.renderContainers.left.renderedColumns.length > 0; }; /** * @ngdoc function * @name hasRightContainerColumns * @methodOf ui.grid.class:Grid * @description returns true if rightContainer has columns */ Grid.prototype.hasRightContainerColumns = function () { return this.hasRightContainer() && this.renderContainers.right.renderedColumns.length > 0; }; /** * @ngdoc method * @methodOf ui.grid.class:Grid * @name scrollToIfNecessary * @description Scrolls the grid to make a certain row and column combo visible, * in the case that it is not completely visible on the screen already. * @param {GridRow} gridRow row to make visible * @param {GridCol} gridCol column to make visible * @returns {promise} a promise that is resolved when scrolling is complete */ Grid.prototype.scrollToIfNecessary = function (gridRow, gridCol) { var self = this; var scrollEvent = new ScrollEvent(self, 'uiGrid.scrollToIfNecessary'); // Alias the visible row and column caches var visRowCache = self.renderContainers.body.visibleRowCache; var visColCache = self.renderContainers.body.visibleColumnCache; /*-- Get the top, left, right, and bottom "scrolled" edges of the grid --*/ // The top boundary is the current Y scroll position PLUS the header height, because the header can obscure rows when the grid is scrolled downwards var topBound = self.renderContainers.body.prevScrollTop + self.headerHeight; // Don't the let top boundary be less than 0 topBound = (topBound < 0) ? 0 : topBound; // The left boundary is the current X scroll position var leftBound = self.renderContainers.body.prevScrollLeft; // The bottom boundary is the current Y scroll position, plus the height of the grid, but minus the header height. // Basically this is the viewport height added on to the scroll position var bottomBound = self.renderContainers.body.prevScrollTop + self.gridHeight - self.renderContainers.body.headerHeight - self.footerHeight - self.scrollbarWidth; // If there's a horizontal scrollbar, remove its height from the bottom boundary, otherwise we'll be letting it obscure rows //if (self.horizontalScrollbarHeight) { // bottomBound = bottomBound - self.horizontalScrollbarHeight; //} // The right position is the current X scroll position minus the grid width var rightBound = self.renderContainers.body.prevScrollLeft + Math.ceil(self.gridWidth); // If there's a vertical scrollbar, subtract it from the right boundary or we'll allow it to obscure cells //if (self.verticalScrollbarWidth) { // rightBound = rightBound - self.verticalScrollbarWidth; //} // We were given a row to scroll to if (gridRow !== null) { // This is the index of the row we want to scroll to, within the list of rows that can be visible var seekRowIndex = visRowCache.indexOf(gridRow); // Total vertical scroll length of the grid var scrollLength = (self.renderContainers.body.getCanvasHeight() - self.renderContainers.body.getViewportHeight()); // Add the height of the native horizontal scrollbar to the scroll length, if it's there. Otherwise it will mask over the final row //if (self.horizontalScrollbarHeight && self.horizontalScrollbarHeight > 0) { // scrollLength = scrollLength + self.horizontalScrollbarHeight; //} // This is the minimum amount of pixels we need to scroll vertical in order to see this row. var pixelsToSeeRow = ((seekRowIndex + 1) * self.options.rowHeight); // Don't let the pixels required to see the row be less than zero pixelsToSeeRow = (pixelsToSeeRow < 0) ? 0 : pixelsToSeeRow; var scrollPixels, percentage; // If the scroll position we need to see the row is LESS than the top boundary, i.e. obscured above the top of the self... if (pixelsToSeeRow < topBound) { // Get the different between the top boundary and the required scroll position and subtract it from the current scroll position\ // to get the full position we need scrollPixels = self.renderContainers.body.prevScrollTop - (topBound - pixelsToSeeRow); // Turn the scroll position into a percentage and make it an argument for a scroll event percentage = scrollPixels / scrollLength; scrollEvent.y = { percentage: percentage }; } // Otherwise if the scroll position we need to see the row is MORE than the bottom boundary, i.e. obscured below the bottom of the self... else if (pixelsToSeeRow > bottomBound) { // Get the different between the bottom boundary and the required scroll position and add it to the current scroll position // to get the full position we need scrollPixels = pixelsToSeeRow - bottomBound + self.renderContainers.body.prevScrollTop; // Turn the scroll position into a percentage and make it an argument for a scroll event percentage = scrollPixels / scrollLength; scrollEvent.y = { percentage: percentage }; } } // We were given a column to scroll to if (gridCol !== null) { // This is the index of the row we want to scroll to, within the list of rows that can be visible var seekColumnIndex = visColCache.indexOf(gridCol); // Total vertical scroll length of the grid var horizScrollLength = (self.renderContainers.body.getCanvasWidth() - self.renderContainers.body.getViewportWidth()); // Add the height of the native horizontal scrollbar to the scroll length, if it's there. Otherwise it will mask over the final row // if (self.verticalScrollbarWidth && self.verticalScrollbarWidth > 0) { // horizScrollLength = horizScrollLength + self.verticalScrollbarWidth; // } // This is the minimum amount of pixels we need to scroll vertical in order to see this column var columnLeftEdge = 0; for (var i = 0; i < seekColumnIndex; i++) { var col = visColCache[i]; columnLeftEdge += col.drawnWidth; } columnLeftEdge = (columnLeftEdge < 0) ? 0 : columnLeftEdge; var columnRightEdge = columnLeftEdge + gridCol.drawnWidth; // Don't let the pixels required to see the column be less than zero columnRightEdge = (columnRightEdge < 0) ? 0 : columnRightEdge; var horizScrollPixels, horizPercentage; // If the scroll position we need to see the row is LESS than the top boundary, i.e. obscured above the top of the self... if (columnLeftEdge < leftBound) { // Get the different between the top boundary and the required scroll position and subtract it from the current scroll position\ // to get the full position we need horizScrollPixels = self.renderContainers.body.prevScrollLeft - (leftBound - columnLeftEdge); // Turn the scroll position into a percentage and make it an argument for a scroll event horizPercentage = horizScrollPixels / horizScrollLength; horizPercentage = (horizPercentage > 1) ? 1 : horizPercentage; scrollEvent.x = { percentage: horizPercentage }; } // Otherwise if the scroll position we need to see the row is MORE than the bottom boundary, i.e. obscured below the bottom of the self... else if (columnRightEdge > rightBound) { // Get the different between the bottom boundary and the required scroll position and add it to the current scroll position // to get the full position we need horizScrollPixels = columnRightEdge - rightBound + self.renderContainers.body.prevScrollLeft; // Turn the scroll position into a percentage and make it an argument for a scroll event horizPercentage = horizScrollPixels / horizScrollLength; horizPercentage = (horizPercentage > 1) ? 1 : horizPercentage; scrollEvent.x = { percentage: horizPercentage }; } } var deferred = $q.defer(); // If we need to scroll on either the x or y axes, fire a scroll event if (scrollEvent.y || scrollEvent.x) { scrollEvent.withDelay = false; self.scrollContainers('',scrollEvent); var dereg = self.api.core.on.scrollEnd(null,function() { deferred.resolve(scrollEvent); dereg(); }); } else { deferred.resolve(); } return deferred.promise; }; /** * @ngdoc method * @methodOf ui.grid.class:Grid * @name scrollTo * @description Scroll the grid such that the specified * row and column is in view * @param {object} rowEntity gridOptions.data[] array instance to make visible * @param {object} colDef to make visible * @returns {promise} a promise that is resolved after any scrolling is finished */ Grid.prototype.scrollTo = function (rowEntity, colDef) { var gridRow = null, gridCol = null; if (rowEntity !== null && typeof(rowEntity) !== 'undefined' ) { gridRow = this.getRow(rowEntity); } if (colDef !== null && typeof(colDef) !== 'undefined' ) { gridCol = this.getColumn(colDef.name ? colDef.name : colDef.field); } return this.scrollToIfNecessary(gridRow, gridCol); }; /** * @ngdoc function * @name clearAllFilters * @methodOf ui.grid.class:Grid * @description Clears all filters and optionally refreshes the visible rows. * @param {object} refreshRows Defaults to true. * @param {object} clearConditions Defaults to false. * @param {object} clearFlags Defaults to false. * @returns {promise} If `refreshRows` is true, returns a promise of the rows refreshing. */ Grid.prototype.clearAllFilters = function clearAllFilters(refreshRows, clearConditions, clearFlags) { // Default `refreshRows` to true because it will be the most commonly desired behaviour. if (refreshRows === undefined) { refreshRows = true; } if (clearConditions === undefined) { clearConditions = false; } if (clearFlags === undefined) { clearFlags = false; } this.columns.forEach(function(column) { column.filters.forEach(function(filter) { filter.term = undefined; if (clearConditions) { filter.condition = undefined; } if (clearFlags) { filter.flags = undefined; } }); }); if (refreshRows) { return this.refreshRows(); } }; // Blatantly stolen from Angular as it isn't exposed (yet? 2.0?) function RowHashMap() {} RowHashMap.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[this.grid.options.rowIdentity(key)] = value; }, /** * @param key * @returns {Object} the value for the key */ get: function(key) { return this[this.grid.options.rowIdentity(key)]; }, /** * Remove the key/value pair * @param key */ remove: function(key) { var value = this[key = this.grid.options.rowIdentity(key)]; delete this[key]; return value; } }; return Grid; }]); })(); (function () { angular.module('ui.grid') .factory('GridApi', ['$q', '$rootScope', 'gridUtil', 'uiGridConstants', 'GridRow', 'uiGridGridMenuService', function ($q, $rootScope, gridUtil, uiGridConstants, GridRow, uiGridGridMenuService) { /** * @ngdoc function * @name ui.grid.class:GridApi * @description GridApi provides the ability to register public methods events inside the grid and allow * for other components to use the api via featureName.raise.methodName and featureName.on.eventName(function(args){}. * <br/> * To listen to events, you must add a callback to gridOptions.onRegisterApi * <pre> * $scope.gridOptions.onRegisterApi = function(gridApi){ * gridApi.cellNav.on.navigate($scope,function(newRowCol, oldRowCol){ * $log.log('navigation event'); * }); * }; * </pre> * @param {object} grid grid that owns api */ var GridApi = function GridApi(grid) { this.grid = grid; this.listeners = []; /** * @ngdoc function * @name renderingComplete * @methodOf ui.grid.core.api:PublicApi * @description Rendering is complete, called at the same * time as `onRegisterApi`, but provides a way to obtain * that same event within features without stopping end * users from getting at the onRegisterApi method. * * Included in gridApi so that it's always there - otherwise * there is still a timing problem with when a feature can * call this. * * @param {GridApi} gridApi the grid api, as normally * returned in the onRegisterApi method * * @example * <pre> * gridApi.core.on.renderingComplete( grid ); * </pre> */ this.registerEvent( 'core', 'renderingComplete' ); /** * @ngdoc event * @name filterChanged * @eventOf ui.grid.core.api:PublicApi * @description is raised after the filter is changed. The nature * of the watch expression doesn't allow notification of what changed, * so the receiver of this event will need to re-extract the filter * conditions from the columns. * */ this.registerEvent( 'core', 'filterChanged' ); /** * @ngdoc function * @name setRowInvisible * @methodOf ui.grid.core.api:PublicApi * @description Sets an override on the row to make it always invisible, * which will override any filtering or other visibility calculations. * If the row is currently visible then sets it to invisible and calls * both grid refresh and emits the rowsVisibleChanged event * @param {object} rowEntity gridOptions.data[] array instance */ this.registerMethod( 'core', 'setRowInvisible', GridRow.prototype.setRowInvisible ); /** * @ngdoc function * @name clearRowInvisible * @methodOf ui.grid.core.api:PublicApi * @description Clears any override on visibility for the row so that it returns to * using normal filtering and other visibility calculations. * If the row is currently invisible then sets it to visible and calls * both grid refresh and emits the rowsVisibleChanged event * TODO: if a filter is active then we can't just set it to visible? * @param {object} rowEntity gridOptions.data[] array instance */ this.registerMethod( 'core', 'clearRowInvisible', GridRow.prototype.clearRowInvisible ); /** * @ngdoc function * @name getVisibleRows * @methodOf ui.grid.core.api:PublicApi * @description Returns all visible rows * @param {Grid} grid the grid you want to get visible rows from * @returns {array} an array of gridRow */ this.registerMethod( 'core', 'getVisibleRows', this.grid.getVisibleRows ); /** * @ngdoc event * @name rowsVisibleChanged * @eventOf ui.grid.core.api:PublicApi * @description is raised after the rows that are visible * change. The filtering is zero-based, so it isn't possible * to say which rows changed (unlike in the selection feature). * We can plausibly know which row was changed when setRowInvisible * is called, but in that situation the user already knows which row * they changed. When a filter runs we don't know what changed, * and that is the one that would have been useful. * */ this.registerEvent( 'core', 'rowsVisibleChanged' ); /** * @ngdoc event * @name rowsRendered * @eventOf ui.grid.core.api:PublicApi * @description is raised after the cache of visible rows is changed. */ this.registerEvent( 'core', 'rowsRendered' ); /** * @ngdoc event * @name scrollBegin * @eventOf ui.grid.core.api:PublicApi * @description is raised when scroll begins. Is throttled, so won't be raised too frequently */ this.registerEvent( 'core', 'scrollBegin' ); /** * @ngdoc event * @name scrollEnd * @eventOf ui.grid.core.api:PublicApi * @description is raised when scroll has finished. Is throttled, so won't be raised too frequently */ this.registerEvent( 'core', 'scrollEnd' ); /** * @ngdoc event * @name canvasHeightChanged * @eventOf ui.grid.core.api:PublicApi * @description is raised when the canvas height has changed * <br/> * arguments: oldHeight, newHeight */ this.registerEvent( 'core', 'canvasHeightChanged'); }; /** * @ngdoc function * @name ui.grid.class:suppressEvents * @methodOf ui.grid.class:GridApi * @description Used to execute a function while disabling the specified event listeners. * Disables the listenerFunctions, executes the callbackFn, and then enables * the listenerFunctions again * @param {object} listenerFuncs listenerFunc or array of listenerFuncs to suppress. These must be the same * functions that were used in the .on.eventName method * @param {object} callBackFn function to execute * @example * <pre> * var navigate = function (newRowCol, oldRowCol){ * //do something on navigate * } * * gridApi.cellNav.on.navigate(scope,navigate); * * * //call the scrollTo event and suppress our navigate listener * //scrollTo will still raise the event for other listeners * gridApi.suppressEvents(navigate, function(){ * gridApi.cellNav.scrollTo(aRow, aCol); * }); * * </pre> */ GridApi.prototype.suppressEvents = function (listenerFuncs, callBackFn) { var self = this; var listeners = angular.isArray(listenerFuncs) ? listenerFuncs : [listenerFuncs]; //find all registered listeners var foundListeners = self.listeners.filter(function(listener) { return listeners.some(function(l) { return listener.handler === l; }); }); //deregister all the listeners foundListeners.forEach(function(l){ l.dereg(); }); callBackFn(); //reregister all the listeners foundListeners.forEach(function(l){ l.dereg = registerEventWithAngular(l.eventId, l.handler, self.grid, l._this); }); }; /** * @ngdoc function * @name registerEvent * @methodOf ui.grid.class:GridApi * @description Registers a new event for the given feature. The event will get a * .raise and .on prepended to it * <br> * .raise.eventName() - takes no arguments * <br/> * <br/> * .on.eventName(scope, callBackFn, _this) * <br/> * scope - a scope reference to add a deregister call to the scopes .$on('destroy'). Scope is optional and can be a null value, * but in this case you must deregister it yourself via the returned deregister function * <br/> * callBackFn - The function to call * <br/> * _this - optional this context variable for callbackFn. If omitted, grid.api will be used for the context * <br/> * .on.eventName returns a dereg funtion that will remove the listener. It's not necessary to use it as the listener * will be removed when the scope is destroyed. * @param {string} featureName name of the feature that raises the event * @param {string} eventName name of the event */ GridApi.prototype.registerEvent = function (featureName, eventName) { var self = this; if (!self[featureName]) { self[featureName] = {}; } var feature = self[featureName]; if (!feature.on) { feature.on = {}; feature.raise = {}; } var eventId = self.grid.id + featureName + eventName; // gridUtil.logDebug('Creating raise event method ' + featureName + '.raise.' + eventName); feature.raise[eventName] = function () { $rootScope.$emit.apply($rootScope, [eventId].concat(Array.prototype.slice.call(arguments))); }; // gridUtil.logDebug('Creating on event method ' + featureName + '.on.' + eventName); feature.on[eventName] = function (scope, handler, _this) { if ( scope !== null && typeof(scope.$on) === 'undefined' ){ gridUtil.logError('asked to listen on ' + featureName + '.on.' + eventName + ' but scope wasn\'t passed in the input parameters. It is legitimate to pass null, but you\'ve passed something else, so you probably forgot to provide scope rather than did it deliberately, not registering'); return; } var deregAngularOn = registerEventWithAngular(eventId, handler, self.grid, _this); //track our listener so we can turn off and on var listener = {handler: handler, dereg: deregAngularOn, eventId: eventId, scope: scope, _this:_this}; self.listeners.push(listener); var removeListener = function(){ listener.dereg(); var index = self.listeners.indexOf(listener); self.listeners.splice(index,1); }; //destroy tracking when scope is destroyed if (scope) { scope.$on('$destroy', function() { removeListener(); }); } return removeListener; }; }; function registerEventWithAngular(eventId, handler, grid, _this) { return $rootScope.$on(eventId, function (event) { var args = Array.prototype.slice.call(arguments); args.splice(0, 1); //remove evt argument handler.apply(_this ? _this : grid.api, args); }); } /** * @ngdoc function * @name registerEventsFromObject * @methodOf ui.grid.class:GridApi * @description Registers features and events from a simple objectMap. * eventObjectMap must be in this format (multiple features allowed) * <pre> * {featureName: * { * eventNameOne:function(args){}, * eventNameTwo:function(args){} * } * } * </pre> * @param {object} eventObjectMap map of feature/event names */ GridApi.prototype.registerEventsFromObject = function (eventObjectMap) { var self = this; var features = []; angular.forEach(eventObjectMap, function (featProp, featPropName) { var feature = {name: featPropName, events: []}; angular.forEach(featProp, function (prop, propName) { feature.events.push(propName); }); features.push(feature); }); features.forEach(function (feature) { feature.events.forEach(function (event) { self.registerEvent(feature.name, event); }); }); }; /** * @ngdoc function * @name registerMethod * @methodOf ui.grid.class:GridApi * @description Registers a new event for the given feature * @param {string} featureName name of the feature * @param {string} methodName name of the method * @param {object} callBackFn function to execute * @param {object} _this binds callBackFn 'this' to _this. Defaults to gridApi.grid */ GridApi.prototype.registerMethod = function (featureName, methodName, callBackFn, _this) { if (!this[featureName]) { this[featureName] = {}; } var feature = this[featureName]; feature[methodName] = gridUtil.createBoundedWrapper(_this || this.grid, callBackFn); }; /** * @ngdoc function * @name registerMethodsFromObject * @methodOf ui.grid.class:GridApi * @description Registers features and methods from a simple objectMap. * eventObjectMap must be in this format (multiple features allowed) * <br> * {featureName: * { * methodNameOne:function(args){}, * methodNameTwo:function(args){} * } * @param {object} eventObjectMap map of feature/event names * @param {object} _this binds this to _this for all functions. Defaults to gridApi.grid */ GridApi.prototype.registerMethodsFromObject = function (methodMap, _this) { var self = this; var features = []; angular.forEach(methodMap, function (featProp, featPropName) { var feature = {name: featPropName, methods: []}; angular.forEach(featProp, function (prop, propName) { feature.methods.push({name: propName, fn: prop}); }); features.push(feature); }); features.forEach(function (feature) { feature.methods.forEach(function (method) { self.registerMethod(feature.name, method.name, method.fn, _this); }); }); }; return GridApi; }]); })(); (function(){ angular.module('ui.grid') .factory('GridColumn', ['gridUtil', 'uiGridConstants', 'i18nService', function(gridUtil, uiGridConstants, i18nService) { /** * ****************************************************************************************** * PaulL1: Ugly hack here in documentation. These properties are clearly properties of GridColumn, * and need to be noted as such for those extending and building ui-grid itself. * However, from an end-developer perspective, they interact with all these through columnDefs, * and they really need to be documented there. I feel like they're relatively static, and * I can't find an elegant way for ngDoc to reference to both....so I've duplicated each * comment block. Ugh. * */ /** * @ngdoc property * @name name * @propertyOf ui.grid.class:GridColumn * @description (mandatory) each column should have a name, although for backward * compatibility with 2.x name can be omitted if field is present * */ /** * @ngdoc property * @name name * @propertyOf ui.grid.class:GridOptions.columnDef * @description (mandatory) each column should have a name, although for backward * compatibility with 2.x name can be omitted if field is present * */ /** * @ngdoc property * @name displayName * @propertyOf ui.grid.class:GridColumn * @description Column name that will be shown in the header. If displayName is not * provided then one is generated using the name. * */ /** * @ngdoc property * @name displayName * @propertyOf ui.grid.class:GridOptions.columnDef * @description Column name that will be shown in the header. If displayName is not * provided then one is generated using the name. * */ /** * @ngdoc property * @name field * @propertyOf ui.grid.class:GridColumn * @description field must be provided if you wish to bind to a * property in the data source. Should be an angular expression that evaluates against grid.options.data * array element. Can be a complex expression: <code>employee.address.city</code>, or can be a function: <code>employee.getFullAddress()</code>. * See the angular docs on binding expressions. * */ /** * @ngdoc property * @name field * @propertyOf ui.grid.class:GridOptions.columnDef * @description field must be provided if you wish to bind to a * property in the data source. Should be an angular expression that evaluates against grid.options.data * array element. Can be a complex expression: <code>employee.address.city</code>, or can be a function: <code>employee.getFullAddress()</code>. * See the angular docs on binding expressions. * */ /** * @ngdoc property * @name filter * @propertyOf ui.grid.class:GridColumn * @description Filter on this column. * @example * <pre>{ term: 'text', condition: uiGridConstants.filter.STARTS_WITH, placeholder: 'type to filter...', ariaLabel: 'Filter for text, flags: { caseSensitive: false }, type: uiGridConstants.filter.SELECT, [ { value: 1, label: 'male' }, { value: 2, label: 'female' } ] }</pre> * */ /** * @ngdoc object * @name ui.grid.class:GridColumn * @description Represents the viewModel for each column. Any state or methods needed for a Grid Column * are defined on this prototype * @param {ColumnDef} colDef the column def to associate with this column * @param {number} uid the unique and immutable uid we'd like to allocate to this column * @param {Grid} grid the grid we'd like to create this column in */ function GridColumn(colDef, uid, grid) { var self = this; self.grid = grid; self.uid = uid; self.updateColumnDef(colDef, true); /** * @ngdoc function * @name hideColumn * @methodOf ui.grid.class:GridColumn * @description Hides the column by setting colDef.visible = false */ GridColumn.prototype.hideColumn = function() { this.colDef.visible = false; }; self.aggregationValue = undefined; // The footer cell registers to listen for the rowsRendered event, and calls this. Needed to be // in something with a scope so that the dereg would get called self.updateAggregationValue = function() { // gridUtil.logDebug('getAggregationValue for Column ' + self.colDef.name); /** * @ngdoc property * @name aggregationType * @propertyOf ui.grid.class:GridOptions.columnDef * @description The aggregation that you'd like to show in the columnFooter for this * column. Valid values are in uiGridConstants, and currently include `uiGridConstants.aggregationTypes.count`, * `uiGridConstants.aggregationTypes.sum`, `uiGridConstants.aggregationTypes.avg`, `uiGridConstants.aggregationTypes.min`, * `uiGridConstants.aggregationTypes.max`. * * You can also provide a function as the aggregation type, in this case your function needs to accept the full * set of visible rows, and return a value that should be shown */ if (!self.aggregationType) { self.aggregationValue = undefined; return; } var result = 0; var visibleRows = self.grid.getVisibleRows(); var cellValues = function(){ var values = []; visibleRows.forEach(function (row) { var cellValue = self.grid.getCellValue(row, self); var cellNumber = Number(cellValue); if (!isNaN(cellNumber)) { values.push(cellNumber); } }); return values; }; if (angular.isFunction(self.aggregationType)) { self.aggregationValue = self.aggregationType(visibleRows, self); } else if (self.aggregationType === uiGridConstants.aggregationTypes.count) { self.aggregationValue = self.grid.getVisibleRowCount(); } else if (self.aggregationType === uiGridConstants.aggregationTypes.sum) { cellValues().forEach(function (value) { result += value; }); self.aggregationValue = result; } else if (self.aggregationType === uiGridConstants.aggregationTypes.avg) { cellValues().forEach(function (value) { result += value; }); result = result / cellValues().length; self.aggregationValue = result; } else if (self.aggregationType === uiGridConstants.aggregationTypes.min) { self.aggregationValue = Math.min.apply(null, cellValues()); } else if (self.aggregationType === uiGridConstants.aggregationTypes.max) { self.aggregationValue = Math.max.apply(null, cellValues()); } else { self.aggregationValue = '\u00A0'; } }; // var throttledUpdateAggregationValue = gridUtil.throttle(updateAggregationValue, self.grid.options.aggregationCalcThrottle, { trailing: true, context: self.name }); /** * @ngdoc function * @name getAggregationValue * @methodOf ui.grid.class:GridColumn * @description gets the aggregation value based on the aggregation type for this column. * Debounced using scrollDebounce option setting */ this.getAggregationValue = function() { // if (!self.grid.isScrollingVertically && !self.grid.isScrollingHorizontally) { // throttledUpdateAggregationValue(); // } return self.aggregationValue; }; } /** * @ngdoc method * @methodOf ui.grid.class:GridColumn * @name setPropertyOrDefault * @description Sets a property on the column using the passed in columnDef, and * setting the defaultValue if the value cannot be found on the colDef * @param {ColumnDef} colDef the column def to look in for the property value * @param {string} propName the property name we'd like to set * @param {object} defaultValue the value to use if the colDef doesn't provide the setting */ GridColumn.prototype.setPropertyOrDefault = function (colDef, propName, defaultValue) { var self = this; // Use the column definition filter if we were passed it if (typeof(colDef[propName]) !== 'undefined' && colDef[propName]) { self[propName] = colDef[propName]; } // Otherwise use our own if it's set else if (typeof(self[propName]) !== 'undefined') { self[propName] = self[propName]; } // Default to empty object for the filter else { self[propName] = defaultValue ? defaultValue : {}; } }; /** * @ngdoc property * @name width * @propertyOf ui.grid.class:GridOptions.columnDef * @description sets the column width. Can be either * a number or a percentage, or an * for auto. * @example * <pre> $scope.gridOptions.columnDefs = [ { field: 'field1', width: 100}, * { field: 'field2', width: '20%'}, * { field: 'field3', width: '*' }]; </pre> * */ /** * @ngdoc property * @name minWidth * @propertyOf ui.grid.class:GridOptions.columnDef * @description sets the minimum column width. Should be a number. * @example * <pre> $scope.gridOptions.columnDefs = [ { field: 'field1', minWidth: 100}]; </pre> * */ /** * @ngdoc property * @name maxWidth * @propertyOf ui.grid.class:GridOptions.columnDef * @description sets the maximum column width. Should be a number. * @example * <pre> $scope.gridOptions.columnDefs = [ { field: 'field1', maxWidth: 100}]; </pre> * */ /** * @ngdoc property * @name visible * @propertyOf ui.grid.class:GridOptions.columnDef * @description sets whether or not the column is visible * </br>Default is true * @example * <pre> $scope.gridOptions.columnDefs = [ * { field: 'field1', visible: true}, * { field: 'field2', visible: false } * ]; </pre> * */ /** * @ngdoc property * @name sort * @propertyOf ui.grid.class:GridOptions.columnDef * @description An object of sort information, attributes are: * * - direction: values are uiGridConstants.ASC or uiGridConstants.DESC * - ignoreSort: if set to true this sort is ignored (used by tree to manipulate the sort functionality) * - priority: says what order to sort the columns in (lower priority gets sorted first). * @example * <pre> * $scope.gridOptions.columnDefs = [{ * field: 'field1', * sort: { * direction: uiGridConstants.ASC, * ignoreSort: true, * priority: 0 * } * }]; * </pre> */ /** * @ngdoc property * @name sortingAlgorithm * @propertyOf ui.grid.class:GridColumn * @description Algorithm to use for sorting this column. Takes 'a' and 'b' parameters * like any normal sorting function. * */ /** * @ngdoc property * @name sortingAlgorithm * @propertyOf ui.grid.class:GridOptions.columnDef * @description Algorithm to use for sorting this column. Takes 'a' and 'b' parameters * like any normal sorting function. * */ /** * @ngdoc array * @name filters * @propertyOf ui.grid.class:GridOptions.columnDef * @description Specify multiple filter fields. * @example * <pre>$scope.gridOptions.columnDefs = [ * { * field: 'field1', filters: [ * { * term: 'aa', * condition: uiGridConstants.filter.STARTS_WITH, * placeholder: 'starts with...', * ariaLabel: 'Filter for field1', * flags: { caseSensitive: false }, * type: uiGridConstants.filter.SELECT, * selectOptions: [ { value: 1, label: 'male' }, { value: 2, label: 'female' } ] * }, * { * condition: uiGridConstants.filter.ENDS_WITH, * placeholder: 'ends with...' * } * ] * } * ]; </pre> * * */ /** * @ngdoc array * @name filters * @propertyOf ui.grid.class:GridColumn * @description Filters for this column. Includes 'term' property bound to filter input elements. * @example * <pre>[ * { * term: 'foo', // ngModel for <input> * condition: uiGridConstants.filter.STARTS_WITH, * placeholder: 'starts with...', * ariaLabel: 'Filter for foo', * flags: { caseSensitive: false }, * type: uiGridConstants.filter.SELECT, * selectOptions: [ { value: 1, label: 'male' }, { value: 2, label: 'female' } ] * }, * { * term: 'baz', * condition: uiGridConstants.filter.ENDS_WITH, * placeholder: 'ends with...' * } * ] </pre> * * */ /** * @ngdoc array * @name menuItems * @propertyOf ui.grid.class:GridOptions.columnDef * @description used to add menu items to a column. Refer to the tutorial on this * functionality. A number of settings are supported: * * - title: controls the title that is displayed in the menu * - icon: the icon shown alongside that title * - action: the method to call when the menu is clicked * - shown: a function to evaluate to determine whether or not to show the item * - active: a function to evaluate to determine whether or not the item is currently selected * - context: context to pass to the action function, available in this.context in your handler * - leaveOpen: if set to true, the menu should stay open after the action, defaults to false * @example * <pre> $scope.gridOptions.columnDefs = [ * { field: 'field1', menuItems: [ * { * title: 'Outer Scope Alert', * icon: 'ui-grid-icon-info-circled', * action: function($event) { * this.context.blargh(); // $scope.blargh() would work too, this is just an example * }, * shown: function() { return true; }, * active: function() { return true; }, * context: $scope * }, * { * title: 'Grid ID', * action: function() { * alert('Grid ID: ' + this.grid.id); * } * } * ] }]; </pre> * */ /** * @ngdoc method * @methodOf ui.grid.class:GridColumn * @name updateColumnDef * @description Moves settings from the columnDef down onto the column, * and sets properties as appropriate * @param {ColumnDef} colDef the column def to look in for the property value * @param {boolean} isNew whether the column is being newly created, if not * we're updating an existing column, and some items such as the sort shouldn't * be copied down */ GridColumn.prototype.updateColumnDef = function(colDef, isNew) { var self = this; self.colDef = colDef; if (colDef.name === undefined) { throw new Error('colDef.name is required for column at index ' + self.grid.options.columnDefs.indexOf(colDef)); } self.displayName = (colDef.displayName === undefined) ? gridUtil.readableColumnName(colDef.name) : colDef.displayName; if (!angular.isNumber(self.width) || !self.hasCustomWidth || colDef.allowCustomWidthOverride) { var colDefWidth = colDef.width; var parseErrorMsg = "Cannot parse column width '" + colDefWidth + "' for column named '" + colDef.name + "'"; self.hasCustomWidth = false; if (!angular.isString(colDefWidth) && !angular.isNumber(colDefWidth)) { self.width = '*'; } else if (angular.isString(colDefWidth)) { // See if it ends with a percent if (gridUtil.endsWith(colDefWidth, '%')) { // If so we should be able to parse the non-percent-sign part to a number var percentStr = colDefWidth.replace(/%/g, ''); var percent = parseInt(percentStr, 10); if (isNaN(percent)) { throw new Error(parseErrorMsg); } self.width = colDefWidth; } // And see if it's a number string else if (colDefWidth.match(/^(\d+)$/)) { self.width = parseInt(colDefWidth.match(/^(\d+)$/)[1], 10); } // Otherwise it should be a string of asterisks else if (colDefWidth.match(/^\*+$/)) { self.width = colDefWidth; } // No idea, throw an Error else { throw new Error(parseErrorMsg); } } // Is a number, use it as the width else { self.width = colDefWidth; } } ['minWidth', 'maxWidth'].forEach(function (name) { var minOrMaxWidth = colDef[name]; var parseErrorMsg = "Cannot parse column " + name + " '" + minOrMaxWidth + "' for column named '" + colDef.name + "'"; if (!angular.isString(minOrMaxWidth) && !angular.isNumber(minOrMaxWidth)) { //Sets default minWidth and maxWidth values self[name] = ((name === 'minWidth') ? 30 : 9000); } else if (angular.isString(minOrMaxWidth)) { if (minOrMaxWidth.match(/^(\d+)$/)) { self[name] = parseInt(minOrMaxWidth.match(/^(\d+)$/)[1], 10); } else { throw new Error(parseErrorMsg); } } else { self[name] = minOrMaxWidth; } }); //use field if it is defined; name if it is not self.field = (colDef.field === undefined) ? colDef.name : colDef.field; if ( typeof( self.field ) !== 'string' ){ gridUtil.logError( 'Field is not a string, this is likely to break the code, Field is: ' + self.field ); } self.name = colDef.name; // Use colDef.displayName as long as it's not undefined, otherwise default to the field name self.displayName = (colDef.displayName === undefined) ? gridUtil.readableColumnName(colDef.name) : colDef.displayName; //self.originalIndex = index; self.aggregationType = angular.isDefined(colDef.aggregationType) ? colDef.aggregationType : null; self.footerCellTemplate = angular.isDefined(colDef.footerCellTemplate) ? colDef.footerCellTemplate : null; /** * @ngdoc property * @name cellTooltip * @propertyOf ui.grid.class:GridOptions.columnDef * @description Whether or not to show a tooltip when a user hovers over the cell. * If set to false, no tooltip. If true, the cell value is shown in the tooltip (useful * if you have long values in your cells), if a function then that function is called * passing in the row and the col `cellTooltip( row, col )`, and the return value is shown in the tooltip, * if it is a static string then displays that static string. * * Defaults to false * */ if ( typeof(colDef.cellTooltip) === 'undefined' || colDef.cellTooltip === false ) { self.cellTooltip = false; } else if ( colDef.cellTooltip === true ){ self.cellTooltip = function(row, col) { return self.grid.getCellValue( row, col ); }; } else if (typeof(colDef.cellTooltip) === 'function' ){ self.cellTooltip = colDef.cellTooltip; } else { self.cellTooltip = function ( row, col ){ return col.colDef.cellTooltip; }; } /** * @ngdoc property * @name headerTooltip * @propertyOf ui.grid.class:GridOptions.columnDef * @description Whether or not to show a tooltip when a user hovers over the header cell. * If set to false, no tooltip. If true, the displayName is shown in the tooltip (useful * if you have long values in your headers), if a function then that function is called * passing in the row and the col `headerTooltip( col )`, and the return value is shown in the tooltip, * if a static string then shows that static string. * * Defaults to false * */ if ( typeof(colDef.headerTooltip) === 'undefined' || colDef.headerTooltip === false ) { self.headerTooltip = false; } else if ( colDef.headerTooltip === true ){ self.headerTooltip = function(col) { return col.displayName; }; } else if (typeof(colDef.headerTooltip) === 'function' ){ self.headerTooltip = colDef.headerTooltip; } else { self.headerTooltip = function ( col ) { return col.colDef.headerTooltip; }; } /** * @ngdoc property * @name footerCellClass * @propertyOf ui.grid.class:GridOptions.columnDef * @description footerCellClass can be a string specifying the class to append to a cell * or it can be a function(row,rowRenderIndex, col, colRenderIndex) that returns a class name * */ self.footerCellClass = colDef.footerCellClass; /** * @ngdoc property * @name cellClass * @propertyOf ui.grid.class:GridOptions.columnDef * @description cellClass can be a string specifying the class to append to a cell * or it can be a function(row,rowRenderIndex, col, colRenderIndex) that returns a class name * */ self.cellClass = colDef.cellClass; /** * @ngdoc property * @name headerCellClass * @propertyOf ui.grid.class:GridOptions.columnDef * @description headerCellClass can be a string specifying the class to append to a cell * or it can be a function(row,rowRenderIndex, col, colRenderIndex) that returns a class name * */ self.headerCellClass = colDef.headerCellClass; /** * @ngdoc property * @name cellFilter * @propertyOf ui.grid.class:GridOptions.columnDef * @description cellFilter is a filter to apply to the content of each cell * @example * <pre> * gridOptions.columnDefs[0].cellFilter = 'date' * */ self.cellFilter = colDef.cellFilter ? colDef.cellFilter : ""; /** * @ngdoc boolean * @name sortCellFiltered * @propertyOf ui.grid.class:GridOptions.columnDef * @description (optional) False by default. When `true` uiGrid will apply the cellFilter before * sorting the data. Note that when using this option uiGrid will assume that the displayed value is * a string, and use the {@link ui.grid.class:RowSorter#sortAlpha sortAlpha} `sortFn`. It is possible * to return a non-string value from an angularjs filter, in which case you should define a {@link ui.grid.class:GridOptions.columnDef#sortingAlgorithm sortingAlgorithm} * for the column which hanldes the returned type. You may specify one of the `sortingAlgorithms` * found in the {@link ui.grid.RowSorter rowSorter} service. */ self.sortCellFiltered = colDef.sortCellFiltered ? true : false; /** * @ngdoc boolean * @name filterCellFiltered * @propertyOf ui.grid.class:GridOptions.columnDef * @description (optional) False by default. When `true` uiGrid will apply the cellFilter before * applying "search" `filters`. */ self.filterCellFiltered = colDef.filterCellFiltered ? true : false; /** * @ngdoc property * @name headerCellFilter * @propertyOf ui.grid.class:GridOptions.columnDef * @description headerCellFilter is a filter to apply to the content of the column header * @example * <pre> * gridOptions.columnDefs[0].headerCellFilter = 'translate' * */ self.headerCellFilter = colDef.headerCellFilter ? colDef.headerCellFilter : ""; /** * @ngdoc property * @name footerCellFilter * @propertyOf ui.grid.class:GridOptions.columnDef * @description footerCellFilter is a filter to apply to the content of the column footer * @example * <pre> * gridOptions.columnDefs[0].footerCellFilter = 'date' * */ self.footerCellFilter = colDef.footerCellFilter ? colDef.footerCellFilter : ""; self.visible = gridUtil.isNullOrUndefined(colDef.visible) || colDef.visible; self.headerClass = colDef.headerClass; //self.cursor = self.sortable ? 'pointer' : 'default'; // Turn on sorting by default self.enableSorting = typeof(colDef.enableSorting) !== 'undefined' ? colDef.enableSorting : true; self.sortingAlgorithm = colDef.sortingAlgorithm; /** * @ngdoc boolean * @name suppressRemoveSort * @propertyOf ui.grid.class:GridOptions.columnDef * @description (optional) False by default. When enabled, this setting hides the removeSort option * in the menu, and prevents users from manually removing the sort */ if ( typeof(self.suppressRemoveSort) === 'undefined'){ self.suppressRemoveSort = typeof(colDef.suppressRemoveSort) !== 'undefined' ? colDef.suppressRemoveSort : false; } /** * @ngdoc property * @name enableFiltering * @propertyOf ui.grid.class:GridOptions.columnDef * @description turn off filtering for an individual column, where * you've turned on filtering for the overall grid * @example * <pre> * gridOptions.columnDefs[0].enableFiltering = false; * */ // Turn on filtering by default (it's disabled by default at the Grid level) self.enableFiltering = typeof(colDef.enableFiltering) !== 'undefined' ? colDef.enableFiltering : true; // self.menuItems = colDef.menuItems; self.setPropertyOrDefault(colDef, 'menuItems', []); // Use the column definition sort if we were passed it, but only if this is a newly added column if ( isNew ){ self.setPropertyOrDefault(colDef, 'sort'); } // Set up default filters array for when one is not provided. // In other words, this (in column def): // // filter: { term: 'something', flags: {}, condition: [CONDITION] } // // is just shorthand for this: // // filters: [{ term: 'something', flags: {}, condition: [CONDITION] }] // var defaultFilters = []; if (colDef.filter) { defaultFilters.push(colDef.filter); } else if ( colDef.filters ){ defaultFilters = colDef.filters; } else { // Add an empty filter definition object, which will // translate to a guessed condition and no pre-populated // value for the filter <input>. defaultFilters.push({}); } /** * @ngdoc property * @name filter * @propertyOf ui.grid.class:GridOptions.columnDef * @description Specify a single filter field on this column. * * A filter consists of a condition, a term, and a placeholder: * * - condition defines how rows are chosen as matching the filter term. This can be set to * one of the constants in uiGridConstants.filter, or you can supply a custom filter function * that gets passed the following arguments: [searchTerm, cellValue, row, column]. * - term: If set, the filter field will be pre-populated * with this value. * - placeholder: String that will be set to the `<input>.placeholder` attribute. * - ariaLabel: String that will be set to the `<input>.ariaLabel` attribute. This is what is read as a label to screen reader users. * - noTerm: set this to true if you have defined a custom function in condition, and * your custom function doesn't require a term (so it can run even when the term is null) * - flags: only flag currently available is `caseSensitive`, set to false if you don't want * case sensitive matching * - type: defaults to uiGridConstants.filter.INPUT, which gives a text box. If set to uiGridConstants.filter.SELECT * then a select box will be shown with options selectOptions * - selectOptions: options in the format `[ { value: 1, label: 'male' }]`. No i18n filter is provided, you need * to perform the i18n on the values before you provide them * - disableCancelFilterButton: defaults to false. If set to true then the 'x' button that cancels/clears the filter * will not be shown. * @example * <pre>$scope.gridOptions.columnDefs = [ * { * field: 'field1', * filter: { * term: 'xx', * condition: uiGridConstants.filter.STARTS_WITH, * placeholder: 'starts with...', * ariaLabel: 'Starts with filter for field1', * flags: { caseSensitive: false }, * type: uiGridConstants.filter.SELECT, * selectOptions: [ { value: 1, label: 'male' }, { value: 2, label: 'female' } ], * disableCancelFilterButton: true * } * } * ]; </pre> * */ /* /* self.filters = [ { term: 'search term' condition: uiGridConstants.filter.CONTAINS, placeholder: 'my placeholder', ariaLabel: 'Starts with filter for field1', flags: { caseSensitive: true } } ] */ // Only set filter if this is a newly added column, if we're updating an existing // column then we don't want to put the default filter back if the user may have already // removed it. // However, we do want to keep the settings if they change, just not the term if ( isNew ) { self.setPropertyOrDefault(colDef, 'filter'); self.setPropertyOrDefault(colDef, 'filters', defaultFilters); } else if ( self.filters.length === defaultFilters.length ) { self.filters.forEach( function( filter, index ){ if (typeof(defaultFilters[index].placeholder) !== 'undefined') { filter.placeholder = defaultFilters[index].placeholder; } if (typeof(defaultFilters[index].ariaLabel) !== 'undefined') { filter.ariaLabel = defaultFilters[index].ariaLabel; } if (typeof(defaultFilters[index].flags) !== 'undefined') { filter.flags = defaultFilters[index].flags; } if (typeof(defaultFilters[index].type) !== 'undefined') { filter.type = defaultFilters[index].type; } if (typeof(defaultFilters[index].selectOptions) !== 'undefined') { filter.selectOptions = defaultFilters[index].selectOptions; } }); } // Remove this column from the grid sorting, include inside build columns so has // access to self - all seems a bit dodgy but doesn't work otherwise so have left // as is GridColumn.prototype.unsort = function () { this.sort = {}; self.grid.api.core.raise.sortChanged( self.grid, self.grid.getColumnSorting() ); }; }; /** * @ngdoc function * @name getColClass * @methodOf ui.grid.class:GridColumn * @description Returns the class name for the column * @param {bool} prefixDot if true, will return .className instead of className */ GridColumn.prototype.getColClass = function (prefixDot) { var cls = uiGridConstants.COL_CLASS_PREFIX + this.uid; return prefixDot ? '.' + cls : cls; }; /** * @ngdoc function * @name isPinnedLeft * @methodOf ui.grid.class:GridColumn * @description Returns true if column is in the left render container */ GridColumn.prototype.isPinnedLeft = function () { return this.renderContainer === 'left'; }; /** * @ngdoc function * @name isPinnedRight * @methodOf ui.grid.class:GridColumn * @description Returns true if column is in the right render container */ GridColumn.prototype.isPinnedRight = function () { return this.renderContainer === 'right'; }; /** * @ngdoc function * @name getColClassDefinition * @methodOf ui.grid.class:GridColumn * @description Returns the class definition for th column */ GridColumn.prototype.getColClassDefinition = function () { return ' .grid' + this.grid.id + ' ' + this.getColClass(true) + ' { min-width: ' + this.drawnWidth + 'px; max-width: ' + this.drawnWidth + 'px; }'; }; /** * @ngdoc function * @name getRenderContainer * @methodOf ui.grid.class:GridColumn * @description Returns the render container object that this column belongs to. * * Columns will be default be in the `body` render container if they aren't allocated to one specifically. */ GridColumn.prototype.getRenderContainer = function getRenderContainer() { var self = this; var containerId = self.renderContainer; if (containerId === null || containerId === '' || containerId === undefined) { containerId = 'body'; } return self.grid.renderContainers[containerId]; }; /** * @ngdoc function * @name showColumn * @methodOf ui.grid.class:GridColumn * @description Makes the column visible by setting colDef.visible = true */ GridColumn.prototype.showColumn = function() { this.colDef.visible = true; }; /** * @ngdoc property * @name aggregationHideLabel * @propertyOf ui.grid.class:GridOptions.columnDef * @description defaults to false, if set to true hides the label text * in the aggregation footer, so only the value is displayed. * */ /** * @ngdoc function * @name getAggregationText * @methodOf ui.grid.class:GridColumn * @description Gets the aggregation label from colDef.aggregationLabel if * specified or by using i18n, including deciding whether or not to display * based on colDef.aggregationHideLabel. * * @param {string} label the i18n lookup value to use for the column label * */ GridColumn.prototype.getAggregationText = function () { var self = this; if ( self.colDef.aggregationHideLabel ){ return ''; } else if ( self.colDef.aggregationLabel ) { return self.colDef.aggregationLabel; } else { switch ( self.colDef.aggregationType ){ case uiGridConstants.aggregationTypes.count: return i18nService.getSafeText('aggregation.count'); case uiGridConstants.aggregationTypes.sum: return i18nService.getSafeText('aggregation.sum'); case uiGridConstants.aggregationTypes.avg: return i18nService.getSafeText('aggregation.avg'); case uiGridConstants.aggregationTypes.min: return i18nService.getSafeText('aggregation.min'); case uiGridConstants.aggregationTypes.max: return i18nService.getSafeText('aggregation.max'); default: return ''; } } }; GridColumn.prototype.getCellTemplate = function () { var self = this; return self.cellTemplatePromise; }; GridColumn.prototype.getCompiledElementFn = function () { var self = this; return self.compiledElementFnDefer.promise; }; return GridColumn; }]); })(); (function(){ angular.module('ui.grid') .factory('GridOptions', ['gridUtil','uiGridConstants', function(gridUtil,uiGridConstants) { /** * @ngdoc function * @name ui.grid.class:GridOptions * @description Default GridOptions class. GridOptions are defined by the application developer and overlaid * over this object. Setting gridOptions within your controller is the most common method for an application * developer to configure the behaviour of their ui-grid * * @example To define your gridOptions within your controller: * <pre>$scope.gridOptions = { * data: $scope.myData, * columnDefs: [ * { name: 'field1', displayName: 'pretty display name' }, * { name: 'field2', visible: false } * ] * };</pre> * * You can then use this within your html template, when you define your grid: * <pre>&lt;div ui-grid="gridOptions"&gt;&lt;/div&gt;</pre> * * To provide default options for all of the grids within your application, use an angular * decorator to modify the GridOptions factory. * <pre> * app.config(function($provide){ * $provide.decorator('GridOptions',function($delegate){ * var gridOptions; * gridOptions = angular.copy($delegate); * gridOptions.initialize = function(options) { * var initOptions; * initOptions = $delegate.initialize(options); * initOptions.enableColumnMenus = false; * return initOptions; * }; * return gridOptions; * }); * }); * </pre> */ return { initialize: function( baseOptions ){ /** * @ngdoc function * @name onRegisterApi * @propertyOf ui.grid.class:GridOptions * @description A callback that returns the gridApi once the grid is instantiated, which is * then used to interact with the grid programatically. * * Note that the gridApi.core.renderingComplete event is identical to this * callback, but has the advantage that it can be called from multiple places * if needed * * @example * <pre> * $scope.gridOptions.onRegisterApi = function ( gridApi ) { * $scope.gridApi = gridApi; * $scope.gridApi.selection.selectAllRows( $scope.gridApi.grid ); * }; * </pre> * */ baseOptions.onRegisterApi = baseOptions.onRegisterApi || angular.noop(); /** * @ngdoc object * @name data * @propertyOf ui.grid.class:GridOptions * @description (mandatory) Array of data to be rendered into the grid, providing the data source or data binding for * the grid. * * Most commonly the data is an array of objects, where each object has a number of attributes. * Each attribute automatically becomes a column in your grid. This array could, for example, be sourced from * an angularJS $resource query request. The array can also contain complex objects, refer the binding tutorial * for examples of that. * * The most flexible usage is to set your data on $scope: * * `$scope.data = data;` * * And then direct the grid to resolve whatever is in $scope.data: * * `$scope.gridOptions.data = 'data';` * * This is the most flexible approach as it allows you to replace $scope.data whenever you feel like it without * getting pointer issues. * * Alternatively you can directly set the data array: * * `$scope.gridOptions.data = [ ];` * or * * `$http.get('/data/100.json') * .success(function(data) { * $scope.myData = data; * $scope.gridOptions.data = $scope.myData; * });` * * Where you do this, you need to take care in updating the data - you can't just update `$scope.myData` to some other * array, you need to update $scope.gridOptions.data to point to that new array as well. * */ baseOptions.data = baseOptions.data || []; /** * @ngdoc array * @name columnDefs * @propertyOf ui.grid.class:GridOptions * @description Array of columnDef objects. Only required property is name. * The individual options available in columnDefs are documented in the * {@link ui.grid.class:GridOptions.columnDef columnDef} section * </br>_field property can be used in place of name for backwards compatibility with 2.x_ * @example * * <pre>var columnDefs = [{name:'field1'}, {name:'field2'}];</pre> * */ baseOptions.columnDefs = baseOptions.columnDefs || []; /** * @ngdoc object * @name ui.grid.class:GridOptions.columnDef * @description Definition / configuration of an individual column, which would typically be * one of many column definitions within the gridOptions.columnDefs array * @example * <pre>{name:'field1', field: 'field1', filter: { term: 'xxx' }}</pre> * */ /** * @ngdoc array * @name excludeProperties * @propertyOf ui.grid.class:GridOptions * @description Array of property names in data to ignore when auto-generating column names. Provides the * inverse of columnDefs - columnDefs is a list of columns to include, excludeProperties is a list of columns * to exclude. * * If columnDefs is defined, this will be ignored. * * Defaults to ['$$hashKey'] */ baseOptions.excludeProperties = baseOptions.excludeProperties || ['$$hashKey']; /** * @ngdoc boolean * @name enableRowHashing * @propertyOf ui.grid.class:GridOptions * @description True by default. When enabled, this setting allows uiGrid to add * `$$hashKey`-type properties (similar to Angular) to elements in the `data` array. This allows * the grid to maintain state while vastly speeding up the process of altering `data` by adding/moving/removing rows. * * Note that this DOES add properties to your data that you may not want, but they are stripped out when using `angular.toJson()`. IF * you do not want this at all you can disable this setting but you will take a performance hit if you are using large numbers of rows * and are altering the data set often. */ baseOptions.enableRowHashing = baseOptions.enableRowHashing !== false; /** * @ngdoc function * @name rowIdentity * @methodOf ui.grid.class:GridOptions * @description This function is used to get and, if necessary, set the value uniquely identifying this row (i.e. if an identity is not present it will set one). * * By default it returns the `$$hashKey` property if it exists. If it doesn't it uses gridUtil.nextUid() to generate one */ baseOptions.rowIdentity = baseOptions.rowIdentity || function rowIdentity(row) { return gridUtil.hashKey(row); }; /** * @ngdoc function * @name getRowIdentity * @methodOf ui.grid.class:GridOptions * @description This function returns the identity value uniquely identifying this row, if one is not present it does not set it. * * By default it returns the `$$hashKey` property but can be overridden to use any property or set of properties you want. */ baseOptions.getRowIdentity = baseOptions.getRowIdentity || function getRowIdentity(row) { return row.$$hashKey; }; /** * @ngdoc property * @name flatEntityAccess * @propertyOf ui.grid.class:GridOptions * @description Set to true if your columns are all related directly to fields in a flat object structure - i.e. * each of your columns associate directly with a property on each of the entities in your data array. * * In that situation we can avoid all the logic associated with complex binding to functions or to properties of sub-objects, * which can provide a significant speed improvement with large data sets when filtering or sorting. * * By default false */ baseOptions.flatEntityAccess = baseOptions.flatEntityAccess === true; /** * @ngdoc property * @name showHeader * @propertyOf ui.grid.class:GridOptions * @description True by default. When set to false, this setting will replace the * standard header template with '<div></div>', resulting in no header being shown. */ baseOptions.showHeader = typeof(baseOptions.showHeader) !== "undefined" ? baseOptions.showHeader : true; /* (NOTE): Don't show this in the docs. We only use it internally * @ngdoc property * @name headerRowHeight * @propertyOf ui.grid.class:GridOptions * @description The height of the header in pixels, defaults to 30 * */ if (!baseOptions.showHeader) { baseOptions.headerRowHeight = 0; } else { baseOptions.headerRowHeight = typeof(baseOptions.headerRowHeight) !== "undefined" ? baseOptions.headerRowHeight : 30; } /** * @ngdoc property * @name rowHeight * @propertyOf ui.grid.class:GridOptions * @description The height of the row in pixels, defaults to 30 * */ baseOptions.rowHeight = baseOptions.rowHeight || 30; /** * @ngdoc integer * @name minRowsToShow * @propertyOf ui.grid.class:GridOptions * @description Minimum number of rows to show when the grid doesn't have a defined height. Defaults to "10". */ baseOptions.minRowsToShow = typeof(baseOptions.minRowsToShow) !== "undefined" ? baseOptions.minRowsToShow : 10; /** * @ngdoc property * @name showGridFooter * @propertyOf ui.grid.class:GridOptions * @description Whether or not to show the footer, defaults to false * The footer display Total Rows and Visible Rows (filtered rows) */ baseOptions.showGridFooter = baseOptions.showGridFooter === true; /** * @ngdoc property * @name showColumnFooter * @propertyOf ui.grid.class:GridOptions * @description Whether or not to show the column footer, defaults to false * The column footer displays column aggregates */ baseOptions.showColumnFooter = baseOptions.showColumnFooter === true; /** * @ngdoc property * @name columnFooterHeight * @propertyOf ui.grid.class:GridOptions * @description The height of the footer rows (column footer and grid footer) in pixels * */ baseOptions.columnFooterHeight = typeof(baseOptions.columnFooterHeight) !== "undefined" ? baseOptions.columnFooterHeight : 30; baseOptions.gridFooterHeight = typeof(baseOptions.gridFooterHeight) !== "undefined" ? baseOptions.gridFooterHeight : 30; baseOptions.columnWidth = typeof(baseOptions.columnWidth) !== "undefined" ? baseOptions.columnWidth : 50; /** * @ngdoc property * @name maxVisibleColumnCount * @propertyOf ui.grid.class:GridOptions * @description Defaults to 200 * */ baseOptions.maxVisibleColumnCount = typeof(baseOptions.maxVisibleColumnCount) !== "undefined" ? baseOptions.maxVisibleColumnCount : 200; /** * @ngdoc property * @name virtualizationThreshold * @propertyOf ui.grid.class:GridOptions * @description Turn virtualization on when number of data elements goes over this number, defaults to 20 */ baseOptions.virtualizationThreshold = typeof(baseOptions.virtualizationThreshold) !== "undefined" ? baseOptions.virtualizationThreshold : 20; /** * @ngdoc property * @name columnVirtualizationThreshold * @propertyOf ui.grid.class:GridOptions * @description Turn virtualization on when number of columns goes over this number, defaults to 10 */ baseOptions.columnVirtualizationThreshold = typeof(baseOptions.columnVirtualizationThreshold) !== "undefined" ? baseOptions.columnVirtualizationThreshold : 10; /** * @ngdoc property * @name excessRows * @propertyOf ui.grid.class:GridOptions * @description Extra rows to to render outside of the viewport, which helps with smoothness of scrolling. * Defaults to 4 */ baseOptions.excessRows = typeof(baseOptions.excessRows) !== "undefined" ? baseOptions.excessRows : 4; /** * @ngdoc property * @name scrollThreshold * @propertyOf ui.grid.class:GridOptions * @description Defaults to 4 */ baseOptions.scrollThreshold = typeof(baseOptions.scrollThreshold) !== "undefined" ? baseOptions.scrollThreshold : 4; /** * @ngdoc property * @name excessColumns * @propertyOf ui.grid.class:GridOptions * @description Extra columns to to render outside of the viewport, which helps with smoothness of scrolling. * Defaults to 4 */ baseOptions.excessColumns = typeof(baseOptions.excessColumns) !== "undefined" ? baseOptions.excessColumns : 4; /** * @ngdoc property * @name horizontalScrollThreshold * @propertyOf ui.grid.class:GridOptions * @description Defaults to 4 */ baseOptions.horizontalScrollThreshold = typeof(baseOptions.horizontalScrollThreshold) !== "undefined" ? baseOptions.horizontalScrollThreshold : 2; /** * @ngdoc property * @name aggregationCalcThrottle * @propertyOf ui.grid.class:GridOptions * @description Default time in milliseconds to throttle aggregation calcuations, defaults to 500ms */ baseOptions.aggregationCalcThrottle = typeof(baseOptions.aggregationCalcThrottle) !== "undefined" ? baseOptions.aggregationCalcThrottle : 500; /** * @ngdoc property * @name wheelScrollThrottle * @propertyOf ui.grid.class:GridOptions * @description Default time in milliseconds to throttle scroll events to, defaults to 70ms */ baseOptions.wheelScrollThrottle = typeof(baseOptions.wheelScrollThrottle) !== "undefined" ? baseOptions.wheelScrollThrottle : 70; /** * @ngdoc property * @name scrollDebounce * @propertyOf ui.grid.class:GridOptions * @description Default time in milliseconds to debounce scroll events, defaults to 300ms */ baseOptions.scrollDebounce = typeof(baseOptions.scrollDebounce) !== "undefined" ? baseOptions.scrollDebounce : 300; /** * @ngdoc boolean * @name enableSorting * @propertyOf ui.grid.class:GridOptions * @description True by default. When enabled, this setting adds sort * widgets to the column headers, allowing sorting of the data for the entire grid. * Sorting can then be disabled on individual columns using the columnDefs. */ baseOptions.enableSorting = baseOptions.enableSorting !== false; /** * @ngdoc boolean * @name enableFiltering * @propertyOf ui.grid.class:GridOptions * @description False by default. When enabled, this setting adds filter * boxes to each column header, allowing filtering within the column for the entire grid. * Filtering can then be disabled on individual columns using the columnDefs. */ baseOptions.enableFiltering = baseOptions.enableFiltering === true; /** * @ngdoc boolean * @name enableColumnMenus * @propertyOf ui.grid.class:GridOptions * @description True by default. When enabled, this setting displays a column * menu within each column. */ baseOptions.enableColumnMenus = baseOptions.enableColumnMenus !== false; /** * @ngdoc boolean * @name enableVerticalScrollbar * @propertyOf ui.grid.class:GridOptions * @description uiGridConstants.scrollbars.ALWAYS by default. This settings controls the vertical scrollbar for the grid. * Supported values: uiGridConstants.scrollbars.ALWAYS, uiGridConstants.scrollbars.NEVER */ baseOptions.enableVerticalScrollbar = typeof(baseOptions.enableVerticalScrollbar) !== "undefined" ? baseOptions.enableVerticalScrollbar : uiGridConstants.scrollbars.ALWAYS; /** * @ngdoc boolean * @name enableHorizontalScrollbar * @propertyOf ui.grid.class:GridOptions * @description uiGridConstants.scrollbars.ALWAYS by default. This settings controls the horizontal scrollbar for the grid. * Supported values: uiGridConstants.scrollbars.ALWAYS, uiGridConstants.scrollbars.NEVER */ baseOptions.enableHorizontalScrollbar = typeof(baseOptions.enableHorizontalScrollbar) !== "undefined" ? baseOptions.enableHorizontalScrollbar : uiGridConstants.scrollbars.ALWAYS; /** * @ngdoc boolean * @name enableMinHeightCheck * @propertyOf ui.grid.class:GridOptions * @description True by default. When enabled, a newly initialized grid will check to see if it is tall enough to display * at least one row of data. If the grid is not tall enough, it will resize the DOM element to display minRowsToShow number * of rows. */ baseOptions.enableMinHeightCheck = baseOptions.enableMinHeightCheck !== false; /** * @ngdoc boolean * @name minimumColumnSize * @propertyOf ui.grid.class:GridOptions * @description Columns can't be smaller than this, defaults to 10 pixels */ baseOptions.minimumColumnSize = typeof(baseOptions.minimumColumnSize) !== "undefined" ? baseOptions.minimumColumnSize : 10; /** * @ngdoc function * @name rowEquality * @methodOf ui.grid.class:GridOptions * @description By default, rows are compared using object equality. This option can be overridden * to compare on any data item property or function * @param {object} entityA First Data Item to compare * @param {object} entityB Second Data Item to compare */ baseOptions.rowEquality = baseOptions.rowEquality || function(entityA, entityB) { return entityA === entityB; }; /** * @ngdoc string * @name headerTemplate * @propertyOf ui.grid.class:GridOptions * @description Null by default. When provided, this setting uses a custom header * template, rather than the default template. Can be set to either the name of a template file: * <pre> $scope.gridOptions.headerTemplate = 'header_template.html';</pre> * inline html * <pre> $scope.gridOptions.headerTemplate = '<div class="ui-grid-top-panel" style="text-align: center">I am a Custom Grid Header</div>'</pre> * or the id of a precompiled template (TBD how to use this). * </br>Refer to the custom header tutorial for more information. * If you want no header at all, you can set to an empty div: * <pre> $scope.gridOptions.headerTemplate = '<div></div>';</pre> * * If you want to only have a static header, then you can set to static content. If * you want to tailor the existing column headers, then you should look at the * current 'ui-grid-header.html' template in github as your starting point. * */ baseOptions.headerTemplate = baseOptions.headerTemplate || null; /** * @ngdoc string * @name footerTemplate * @propertyOf ui.grid.class:GridOptions * @description (optional) ui-grid/ui-grid-footer by default. This footer shows the per-column * aggregation totals. * When provided, this setting uses a custom footer template. Can be set to either the name of a template file 'footer_template.html', inline html * <pre>'<div class="ui-grid-bottom-panel" style="text-align: center">I am a Custom Grid Footer</div>'</pre>, or the id * of a precompiled template (TBD how to use this). Refer to the custom footer tutorial for more information. */ baseOptions.footerTemplate = baseOptions.footerTemplate || 'ui-grid/ui-grid-footer'; /** * @ngdoc string * @name gridFooterTemplate * @propertyOf ui.grid.class:GridOptions * @description (optional) ui-grid/ui-grid-grid-footer by default. This template by default shows the * total items at the bottom of the grid, and the selected items if selection is enabled. */ baseOptions.gridFooterTemplate = baseOptions.gridFooterTemplate || 'ui-grid/ui-grid-grid-footer'; /** * @ngdoc string * @name rowTemplate * @propertyOf ui.grid.class:GridOptions * @description 'ui-grid/ui-grid-row' by default. When provided, this setting uses a * custom row template. Can be set to either the name of a template file: * <pre> $scope.gridOptions.rowTemplate = 'row_template.html';</pre> * inline html * <pre> $scope.gridOptions.rowTemplate = '<div style="background-color: aquamarine" ng-click="grid.appScope.fnOne(row)" ng-repeat="col in colContainer.renderedColumns track by col.colDef.name" class="ui-grid-cell" ui-grid-cell></div>';</pre> * or the id of a precompiled template (TBD how to use this) can be provided. * </br>Refer to the custom row template tutorial for more information. */ baseOptions.rowTemplate = baseOptions.rowTemplate || 'ui-grid/ui-grid-row'; /** * @ngdoc object * @name appScopeProvider * @propertyOf ui.grid.class:GridOptions * @description by default, the parent scope of the ui-grid element will be assigned to grid.appScope * this property allows you to assign any reference you want to grid.appScope */ baseOptions.appScopeProvider = baseOptions.appScopeProvider || null; return baseOptions; } }; }]); })(); (function(){ angular.module('ui.grid') /** * @ngdoc function * @name ui.grid.class:GridRenderContainer * @description The grid has render containers, allowing the ability to have pinned columns. If the grid * is right-to-left then there may be a right render container, if left-to-right then there may * be a left render container. There is always a body render container. * @param {string} name The name of the render container ('body', 'left', or 'right') * @param {Grid} grid the grid the render container is in * @param {object} options the render container options */ .factory('GridRenderContainer', ['gridUtil', 'uiGridConstants', function(gridUtil, uiGridConstants) { function GridRenderContainer(name, grid, options) { var self = this; // if (gridUtil.type(grid) !== 'Grid') { // throw new Error('Grid argument is not a Grid object'); // } self.name = name; self.grid = grid; // self.rowCache = []; // self.columnCache = []; self.visibleRowCache = []; self.visibleColumnCache = []; self.renderedRows = []; self.renderedColumns = []; self.prevScrollTop = 0; self.prevScrolltopPercentage = 0; self.prevRowScrollIndex = 0; self.prevScrollLeft = 0; self.prevScrollleftPercentage = 0; self.prevColumnScrollIndex = 0; self.columnStyles = ""; self.viewportAdjusters = []; /** * @ngdoc boolean * @name hasHScrollbar * @propertyOf ui.grid.class:GridRenderContainer * @description flag to signal that container has a horizontal scrollbar */ self.hasHScrollbar = false; /** * @ngdoc boolean * @name hasVScrollbar * @propertyOf ui.grid.class:GridRenderContainer * @description flag to signal that container has a vertical scrollbar */ self.hasVScrollbar = false; /** * @ngdoc boolean * @name canvasHeightShouldUpdate * @propertyOf ui.grid.class:GridRenderContainer * @description flag to signal that container should recalculate the canvas size */ self.canvasHeightShouldUpdate = true; /** * @ngdoc boolean * @name canvasHeight * @propertyOf ui.grid.class:GridRenderContainer * @description last calculated canvas height value */ self.$$canvasHeight = 0; if (options && angular.isObject(options)) { angular.extend(self, options); } grid.registerStyleComputation({ priority: 5, func: function () { self.updateColumnWidths(); return self.columnStyles; } }); } GridRenderContainer.prototype.reset = function reset() { // this.rowCache.length = 0; // this.columnCache.length = 0; this.visibleColumnCache.length = 0; this.visibleRowCache.length = 0; this.renderedRows.length = 0; this.renderedColumns.length = 0; }; // TODO(c0bra): calculate size?? Should this be in a stackable directive? GridRenderContainer.prototype.containsColumn = function (col) { return this.visibleColumnCache.indexOf(col) !== -1; }; GridRenderContainer.prototype.minRowsToRender = function minRowsToRender() { var self = this; var minRows = 0; var rowAddedHeight = 0; var viewPortHeight = self.getViewportHeight(); for (var i = self.visibleRowCache.length - 1; rowAddedHeight < viewPortHeight && i >= 0; i--) { rowAddedHeight += self.visibleRowCache[i].height; minRows++; } return minRows; }; GridRenderContainer.prototype.minColumnsToRender = function minColumnsToRender() { var self = this; var viewportWidth = this.getViewportWidth(); var min = 0; var totalWidth = 0; // self.columns.forEach(function(col, i) { for (var i = 0; i < self.visibleColumnCache.length; i++) { var col = self.visibleColumnCache[i]; if (totalWidth < viewportWidth) { totalWidth += col.drawnWidth ? col.drawnWidth : 0; min++; } else { var currWidth = 0; for (var j = i; j >= i - min; j--) { currWidth += self.visibleColumnCache[j].drawnWidth ? self.visibleColumnCache[j].drawnWidth : 0; } if (currWidth < viewportWidth) { min++; } } } return min; }; GridRenderContainer.prototype.getVisibleRowCount = function getVisibleRowCount() { return this.visibleRowCache.length; }; /** * @ngdoc function * @name registerViewportAdjuster * @methodOf ui.grid.class:GridRenderContainer * @description Registers an adjuster to the render container's available width or height. Adjusters are used * to tell the render container that there is something else consuming space, and to adjust it's size * appropriately. * @param {function} func the adjuster function we want to register */ GridRenderContainer.prototype.registerViewportAdjuster = function registerViewportAdjuster(func) { this.viewportAdjusters.push(func); }; /** * @ngdoc function * @name removeViewportAdjuster * @methodOf ui.grid.class:GridRenderContainer * @description Removes an adjuster, should be used when your element is destroyed * @param {function} func the adjuster function we want to remove */ GridRenderContainer.prototype.removeViewportAdjuster = function removeViewportAdjuster(func) { var idx = this.viewportAdjusters.indexOf(func); if (idx > -1) { this.viewportAdjusters.splice(idx, 1); } }; /** * @ngdoc function * @name getViewportAdjustment * @methodOf ui.grid.class:GridRenderContainer * @description Gets the adjustment based on the viewportAdjusters. * @returns {object} a hash of { height: x, width: y }. Usually the values will be negative */ GridRenderContainer.prototype.getViewportAdjustment = function getViewportAdjustment() { var self = this; var adjustment = { height: 0, width: 0 }; self.viewportAdjusters.forEach(function (func) { adjustment = func.call(this, adjustment); }); return adjustment; }; GridRenderContainer.prototype.getMargin = function getMargin(side) { var self = this; var amount = 0; self.viewportAdjusters.forEach(function (func) { var adjustment = func.call(this, { height: 0, width: 0 }); if (adjustment.side && adjustment.side === side) { amount += adjustment.width * -1; } }); return amount; }; GridRenderContainer.prototype.getViewportHeight = function getViewportHeight() { var self = this; var headerHeight = (self.headerHeight) ? self.headerHeight : self.grid.headerHeight; var viewPortHeight = self.grid.gridHeight - headerHeight - self.grid.footerHeight; var adjustment = self.getViewportAdjustment(); viewPortHeight = viewPortHeight + adjustment.height; return viewPortHeight; }; GridRenderContainer.prototype.getViewportWidth = function getViewportWidth() { var self = this; var viewportWidth = self.grid.gridWidth; //if (typeof(self.grid.verticalScrollbarWidth) !== 'undefined' && self.grid.verticalScrollbarWidth !== undefined && self.grid.verticalScrollbarWidth > 0) { // viewPortWidth = viewPortWidth - self.grid.verticalScrollbarWidth; //} // var viewportWidth = 0;\ // self.visibleColumnCache.forEach(function (column) { // viewportWidth += column.drawnWidth; // }); var adjustment = self.getViewportAdjustment(); viewportWidth = viewportWidth + adjustment.width; return viewportWidth; }; GridRenderContainer.prototype.getHeaderViewportWidth = function getHeaderViewportWidth() { var self = this; var viewportWidth = this.getViewportWidth(); //if (typeof(self.grid.verticalScrollbarWidth) !== 'undefined' && self.grid.verticalScrollbarWidth !== undefined && self.grid.verticalScrollbarWidth > 0) { // viewPortWidth = viewPortWidth + self.grid.verticalScrollbarWidth; //} // var adjustment = self.getViewportAdjustment(); // viewPortWidth = viewPortWidth + adjustment.width; return viewportWidth; }; /** * @ngdoc function * @name getCanvasHeight * @methodOf ui.grid.class:GridRenderContainer * @description Returns the total canvas height. Only recalculates if canvasHeightShouldUpdate = false * @returns {number} total height of all the visible rows in the container */ GridRenderContainer.prototype.getCanvasHeight = function getCanvasHeight() { var self = this; if (!self.canvasHeightShouldUpdate) { return self.$$canvasHeight; } var oldCanvasHeight = self.$$canvasHeight; self.$$canvasHeight = 0; self.visibleRowCache.forEach(function(row){ self.$$canvasHeight += row.height; }); self.canvasHeightShouldUpdate = false; self.grid.api.core.raise.canvasHeightChanged(oldCanvasHeight, self.$$canvasHeight); return self.$$canvasHeight; }; GridRenderContainer.prototype.getVerticalScrollLength = function getVerticalScrollLength() { return this.getCanvasHeight() - this.getViewportHeight() + this.grid.scrollbarHeight; }; GridRenderContainer.prototype.getCanvasWidth = function getCanvasWidth() { var self = this; var ret = self.canvasWidth; return ret; }; GridRenderContainer.prototype.setRenderedRows = function setRenderedRows(newRows) { this.renderedRows.length = newRows.length; for (var i = 0; i < newRows.length; i++) { this.renderedRows[i] = newRows[i]; } }; GridRenderContainer.prototype.setRenderedColumns = function setRenderedColumns(newColumns) { var self = this; // OLD: this.renderedColumns.length = newColumns.length; for (var i = 0; i < newColumns.length; i++) { this.renderedColumns[i] = newColumns[i]; } this.updateColumnOffset(); }; GridRenderContainer.prototype.updateColumnOffset = function updateColumnOffset() { // Calculate the width of the columns on the left side that are no longer rendered. // That will be the offset for the columns as we scroll horizontally. var hiddenColumnsWidth = 0; for (var i = 0; i < this.currentFirstColumn; i++) { hiddenColumnsWidth += this.visibleColumnCache[i].drawnWidth; } this.columnOffset = hiddenColumnsWidth; }; GridRenderContainer.prototype.scrollVertical = function (newScrollTop) { var vertScrollPercentage = -1; if (newScrollTop !== this.prevScrollTop) { var yDiff = newScrollTop - this.prevScrollTop; if (yDiff > 0 ) { this.grid.scrollDirection = uiGridConstants.scrollDirection.DOWN; } if (yDiff < 0 ) { this.grid.scrollDirection = uiGridConstants.scrollDirection.UP; } var vertScrollLength = this.getVerticalScrollLength(); vertScrollPercentage = newScrollTop / vertScrollLength; // console.log('vert', vertScrollPercentage, newScrollTop, vertScrollLength); if (vertScrollPercentage > 1) { vertScrollPercentage = 1; } if (vertScrollPercentage < 0) { vertScrollPercentage = 0; } this.adjustScrollVertical(newScrollTop, vertScrollPercentage); return vertScrollPercentage; } }; GridRenderContainer.prototype.scrollHorizontal = function(newScrollLeft){ var horizScrollPercentage = -1; // Handle RTL here if (newScrollLeft !== this.prevScrollLeft) { var xDiff = newScrollLeft - this.prevScrollLeft; if (xDiff > 0) { this.grid.scrollDirection = uiGridConstants.scrollDirection.RIGHT; } if (xDiff < 0) { this.grid.scrollDirection = uiGridConstants.scrollDirection.LEFT; } var horizScrollLength = (this.canvasWidth - this.getViewportWidth()); if (horizScrollLength !== 0) { horizScrollPercentage = newScrollLeft / horizScrollLength; } else { horizScrollPercentage = 0; } this.adjustScrollHorizontal(newScrollLeft, horizScrollPercentage); return horizScrollPercentage; } }; GridRenderContainer.prototype.adjustScrollVertical = function adjustScrollVertical(scrollTop, scrollPercentage, force) { if (this.prevScrollTop === scrollTop && !force) { return; } if (typeof(scrollTop) === 'undefined' || scrollTop === undefined || scrollTop === null) { scrollTop = (this.getCanvasHeight() - this.getViewportHeight()) * scrollPercentage; } this.adjustRows(scrollTop, scrollPercentage, false); this.prevScrollTop = scrollTop; this.prevScrolltopPercentage = scrollPercentage; this.grid.queueRefresh(); }; GridRenderContainer.prototype.adjustScrollHorizontal = function adjustScrollHorizontal(scrollLeft, scrollPercentage, force) { if (this.prevScrollLeft === scrollLeft && !force) { return; } if (typeof(scrollLeft) === 'undefined' || scrollLeft === undefined || scrollLeft === null) { scrollLeft = (this.getCanvasWidth() - this.getViewportWidth()) * scrollPercentage; } this.adjustColumns(scrollLeft, scrollPercentage); this.prevScrollLeft = scrollLeft; this.prevScrollleftPercentage = scrollPercentage; this.grid.queueRefresh(); }; GridRenderContainer.prototype.adjustRows = function adjustRows(scrollTop, scrollPercentage, postDataLoaded) { var self = this; var minRows = self.minRowsToRender(); var rowCache = self.visibleRowCache; var maxRowIndex = rowCache.length - minRows; // console.log('scroll%1', scrollPercentage); // Calculate the scroll percentage according to the scrollTop location, if no percentage was provided if ((typeof(scrollPercentage) === 'undefined' || scrollPercentage === null) && scrollTop) { scrollPercentage = scrollTop / self.getVerticalScrollLength(); } var rowIndex = Math.ceil(Math.min(maxRowIndex, maxRowIndex * scrollPercentage)); // console.log('maxRowIndex / scroll%', maxRowIndex, scrollPercentage, rowIndex); // Define a max row index that we can't scroll past if (rowIndex > maxRowIndex) { rowIndex = maxRowIndex; } var newRange = []; if (rowCache.length > self.grid.options.virtualizationThreshold) { if (!(typeof(scrollTop) === 'undefined' || scrollTop === null)) { // Have we hit the threshold going down? if ( !self.grid.suppressParentScrollDown && self.prevScrollTop < scrollTop && rowIndex < self.prevRowScrollIndex + self.grid.options.scrollThreshold && rowIndex < maxRowIndex) { return; } //Have we hit the threshold going up? if ( !self.grid.suppressParentScrollUp && self.prevScrollTop > scrollTop && rowIndex > self.prevRowScrollIndex - self.grid.options.scrollThreshold && rowIndex < maxRowIndex) { return; } } var rangeStart = {}; var rangeEnd = {}; rangeStart = Math.max(0, rowIndex - self.grid.options.excessRows); rangeEnd = Math.min(rowCache.length, rowIndex + minRows + self.grid.options.excessRows); newRange = [rangeStart, rangeEnd]; } else { var maxLen = self.visibleRowCache.length; newRange = [0, Math.max(maxLen, minRows + self.grid.options.excessRows)]; } self.updateViewableRowRange(newRange); self.prevRowScrollIndex = rowIndex; }; GridRenderContainer.prototype.adjustColumns = function adjustColumns(scrollLeft, scrollPercentage) { var self = this; var minCols = self.minColumnsToRender(); var columnCache = self.visibleColumnCache; var maxColumnIndex = columnCache.length - minCols; // Calculate the scroll percentage according to the scrollLeft location, if no percentage was provided if ((typeof(scrollPercentage) === 'undefined' || scrollPercentage === null) && scrollLeft) { var horizScrollLength = (self.getCanvasWidth() - self.getViewportWidth()); scrollPercentage = scrollLeft / horizScrollLength; } var colIndex = Math.ceil(Math.min(maxColumnIndex, maxColumnIndex * scrollPercentage)); // Define a max row index that we can't scroll past if (colIndex > maxColumnIndex) { colIndex = maxColumnIndex; } var newRange = []; if (columnCache.length > self.grid.options.columnVirtualizationThreshold && self.getCanvasWidth() > self.getViewportWidth()) { /* Commented the following lines because otherwise the moved column wasn't visible immediately on the new position * in the case of many columns with horizontal scroll, one had to scroll left or right and then return in order to see it // Have we hit the threshold going down? if (self.prevScrollLeft < scrollLeft && colIndex < self.prevColumnScrollIndex + self.grid.options.horizontalScrollThreshold && colIndex < maxColumnIndex) { return; } //Have we hit the threshold going up? if (self.prevScrollLeft > scrollLeft && colIndex > self.prevColumnScrollIndex - self.grid.options.horizontalScrollThreshold && colIndex < maxColumnIndex) { return; }*/ var rangeStart = Math.max(0, colIndex - self.grid.options.excessColumns); var rangeEnd = Math.min(columnCache.length, colIndex + minCols + self.grid.options.excessColumns); newRange = [rangeStart, rangeEnd]; } else { var maxLen = self.visibleColumnCache.length; newRange = [0, Math.max(maxLen, minCols + self.grid.options.excessColumns)]; } self.updateViewableColumnRange(newRange); self.prevColumnScrollIndex = colIndex; }; // Method for updating the visible rows GridRenderContainer.prototype.updateViewableRowRange = function updateViewableRowRange(renderedRange) { // Slice out the range of rows from the data // var rowArr = uiGridCtrl.grid.rows.slice(renderedRange[0], renderedRange[1]); var rowArr = this.visibleRowCache.slice(renderedRange[0], renderedRange[1]); // Define the top-most rendered row this.currentTopRow = renderedRange[0]; this.setRenderedRows(rowArr); }; // Method for updating the visible columns GridRenderContainer.prototype.updateViewableColumnRange = function updateViewableColumnRange(renderedRange) { // Slice out the range of rows from the data // var columnArr = uiGridCtrl.grid.columns.slice(renderedRange[0], renderedRange[1]); var columnArr = this.visibleColumnCache.slice(renderedRange[0], renderedRange[1]); // Define the left-most rendered columns this.currentFirstColumn = renderedRange[0]; this.setRenderedColumns(columnArr); }; GridRenderContainer.prototype.headerCellWrapperStyle = function () { var self = this; if (self.currentFirstColumn !== 0) { var offset = self.columnOffset; if (self.grid.isRTL()) { return { 'margin-right': offset + 'px' }; } else { return { 'margin-left': offset + 'px' }; } } return null; }; /** * @ngdoc boolean * @name updateColumnWidths * @propertyOf ui.grid.class:GridRenderContainer * @description Determine the appropriate column width of each column across all render containers. * * Column width is easy when each column has a specified width. When columns are variable width (i.e. * have an * or % of the viewport) then we try to calculate so that things fit in. The problem is that * we have multiple render containers, and we don't want one render container to just take the whole viewport * when it doesn't need to - we want things to balance out across the render containers. * * To do this, we use this method to calculate all the renderContainers, recognising that in a given render * cycle it'll get called once per render container, so it needs to return the same values each time. * * The constraints on this method are therefore: * - must return the same value when called multiple times, to do this it needs to rely on properties of the * columns, but not properties that change when this is called (so it shouldn't rely on drawnWidth) * * The general logic of this method is: * - calculate our total available width * - look at all the columns across all render containers, and work out which have widths and which have * constraints such as % or * or something else * - for those with *, count the total number of * we see and add it onto a running total, add this column to an * array * - for those with a %, allocate the % as a percentage of the viewport, having consideration of min and max * - for those with manual width (in pixels) we set the drawnWidth to the specified width * - we end up with an asterisks array still to process * - we look at our remaining width. If it's greater than zero, we divide it up among the asterisk columns, then process * them for min and max width constraints * - if it's zero or less, we set the asterisk columns to their minimum widths * - we use parseInt quite a bit, as we try to make all our column widths integers */ GridRenderContainer.prototype.updateColumnWidths = function () { var self = this; var asterisksArray = [], asteriskNum = 0, usedWidthSum = 0, ret = ''; // Get the width of the viewport var availableWidth = self.grid.getViewportWidth() - self.grid.scrollbarWidth; // get all the columns across all render containers, we have to calculate them all or one render container // could consume the whole viewport var columnCache = []; angular.forEach(self.grid.renderContainers, function( container, name){ columnCache = columnCache.concat(container.visibleColumnCache); }); // look at each column, process any manual values or %, put the * into an array to look at later columnCache.forEach(function(column, i) { var width = 0; // Skip hidden columns if (!column.visible) { return; } if (angular.isNumber(column.width)) { // pixel width, set to this value width = parseInt(column.width, 10); usedWidthSum = usedWidthSum + width; column.drawnWidth = width; } else if (gridUtil.endsWith(column.width, "%")) { // percentage width, set to percentage of the viewport width = parseInt(parseInt(column.width.replace(/%/g, ''), 10) / 100 * availableWidth); if ( width > column.maxWidth ){ width = column.maxWidth; } if ( width < column.minWidth ){ width = column.minWidth; } usedWidthSum = usedWidthSum + width; column.drawnWidth = width; } else if (angular.isString(column.width) && column.width.indexOf('*') !== -1) { // is an asterisk column, the gridColumn already checked the string consists only of '****' asteriskNum = asteriskNum + column.width.length; asterisksArray.push(column); } }); // Get the remaining width (available width subtracted by the used widths sum) var remainingWidth = availableWidth - usedWidthSum; var i, column, colWidth; if (asterisksArray.length > 0) { // the width that each asterisk value would be assigned (this can be negative) var asteriskVal = remainingWidth / asteriskNum; asterisksArray.forEach(function( column ){ var width = parseInt(column.width.length * asteriskVal, 10); if ( width > column.maxWidth ){ width = column.maxWidth; } if ( width < column.minWidth ){ width = column.minWidth; } usedWidthSum = usedWidthSum + width; column.drawnWidth = width; }); } // If the grid width didn't divide evenly into the column widths and we have pixels left over, or our // calculated widths would have the grid narrower than the available space, // dole the remainder out one by one to make everything fit var processColumnUpwards = function(column){ if ( column.drawnWidth < column.maxWidth && leftoverWidth > 0) { column.drawnWidth++; usedWidthSum++; leftoverWidth--; columnsToChange = true; } }; var leftoverWidth = availableWidth - usedWidthSum; var columnsToChange = true; while (leftoverWidth > 0 && columnsToChange) { columnsToChange = false; asterisksArray.forEach(processColumnUpwards); } // We can end up with too much width even though some columns aren't at their max width, in this situation // we can trim the columns a little var processColumnDownwards = function(column){ if ( column.drawnWidth > column.minWidth && excessWidth > 0) { column.drawnWidth--; usedWidthSum--; excessWidth--; columnsToChange = true; } }; var excessWidth = usedWidthSum - availableWidth; columnsToChange = true; while (excessWidth > 0 && columnsToChange) { columnsToChange = false; asterisksArray.forEach(processColumnDownwards); } // all that was across all the renderContainers, now we need to work out what that calculation decided for // our renderContainer var canvasWidth = 0; self.visibleColumnCache.forEach(function(column){ if ( column.visible ){ canvasWidth = canvasWidth + column.drawnWidth; } }); // Build the CSS columnCache.forEach(function (column) { ret = ret + column.getColClassDefinition(); }); self.canvasWidth = canvasWidth; // Return the styles back to buildStyles which pops them into the `customStyles` scope variable // return ret; // Set this render container's column styles so they can be used in style computation this.columnStyles = ret; }; GridRenderContainer.prototype.needsHScrollbarPlaceholder = function () { return this.grid.options.enableHorizontalScrollbar && !this.hasHScrollbar; }; GridRenderContainer.prototype.getViewportStyle = function () { var self = this; var styles = {}; self.hasHScrollbar = false; self.hasVScrollbar = false; if (self.grid.disableScrolling) { styles['overflow-x'] = 'hidden'; styles['overflow-y'] = 'hidden'; return styles; } if (self.name === 'body') { self.hasHScrollbar = self.grid.options.enableHorizontalScrollbar !== uiGridConstants.scrollbars.NEVER; if (!self.grid.isRTL()) { if (!self.grid.hasRightContainerColumns()) { self.hasVScrollbar = self.grid.options.enableVerticalScrollbar !== uiGridConstants.scrollbars.NEVER; } } else { if (!self.grid.hasLeftContainerColumns()) { self.hasVScrollbar = self.grid.options.enableVerticalScrollbar !== uiGridConstants.scrollbars.NEVER; } } } else if (self.name === 'left') { self.hasVScrollbar = self.grid.isRTL() ? self.grid.options.enableVerticalScrollbar !== uiGridConstants.scrollbars.NEVER : false; } else { self.hasVScrollbar = !self.grid.isRTL() ? self.grid.options.enableVerticalScrollbar !== uiGridConstants.scrollbars.NEVER : false; } styles['overflow-x'] = self.hasHScrollbar ? 'scroll' : 'hidden'; styles['overflow-y'] = self.hasVScrollbar ? 'scroll' : 'hidden'; return styles; }; return GridRenderContainer; }]); })(); (function(){ angular.module('ui.grid') .factory('GridRow', ['gridUtil', function(gridUtil) { /** * @ngdoc function * @name ui.grid.class:GridRow * @description GridRow is the viewModel for one logical row on the grid. A grid Row is not necessarily a one-to-one * relation to gridOptions.data. * @param {object} entity the array item from GridOptions.data * @param {number} index the current position of the row in the array * @param {Grid} reference to the parent grid */ function GridRow(entity, index, grid) { /** * @ngdoc object * @name grid * @propertyOf ui.grid.class:GridRow * @description A reference back to the grid */ this.grid = grid; /** * @ngdoc object * @name entity * @propertyOf ui.grid.class:GridRow * @description A reference to an item in gridOptions.data[] */ this.entity = entity; /** * @ngdoc object * @name uid * @propertyOf ui.grid.class:GridRow * @description UniqueId of row */ this.uid = gridUtil.nextUid(); /** * @ngdoc object * @name visible * @propertyOf ui.grid.class:GridRow * @description If true, the row will be rendered */ // Default to true this.visible = true; this.$$height = grid.options.rowHeight; } /** * @ngdoc object * @name height * @propertyOf ui.grid.class:GridRow * @description height of each individual row. changing the height will flag all * row renderContainers to recalculate their canvas height */ Object.defineProperty(GridRow.prototype, 'height', { get: function() { return this.$$height; }, set: function(height) { if (height !== this.$$height) { this.grid.updateCanvasHeight(); this.$$height = height; } } }); /** * @ngdoc function * @name getQualifiedColField * @methodOf ui.grid.class:GridRow * @description returns the qualified field name as it exists on scope * ie: row.entity.fieldA * @param {GridCol} col column instance * @returns {string} resulting name that can be evaluated on scope */ GridRow.prototype.getQualifiedColField = function(col) { return 'row.' + this.getEntityQualifiedColField(col); }; /** * @ngdoc function * @name getEntityQualifiedColField * @methodOf ui.grid.class:GridRow * @description returns the qualified field name minus the row path * ie: entity.fieldA * @param {GridCol} col column instance * @returns {string} resulting name that can be evaluated against a row */ GridRow.prototype.getEntityQualifiedColField = function(col) { return gridUtil.preEval('entity.' + col.field); }; /** * @ngdoc function * @name setRowInvisible * @methodOf ui.grid.class:GridRow * @description Sets an override on the row that forces it to always * be invisible. Emits the rowsVisibleChanged event if it changed the row visibility. * * This method can be called from the api, passing in the gridRow we want * altered. It should really work by calling gridRow.setRowInvisible, but that's * not the way I coded it, and too late to change now. Changed to just call * the internal function row.setThisRowInvisible(). * * @param {GridRow} row the row we want to set to invisible * */ GridRow.prototype.setRowInvisible = function ( row ) { if (row && row.setThisRowInvisible){ row.setThisRowInvisible( 'user' ); } }; /** * @ngdoc function * @name clearRowInvisible * @methodOf ui.grid.class:GridRow * @description Clears an override on the row that forces it to always * be invisible. Emits the rowsVisibleChanged event if it changed the row visibility. * * This method can be called from the api, passing in the gridRow we want * altered. It should really work by calling gridRow.clearRowInvisible, but that's * not the way I coded it, and too late to change now. Changed to just call * the internal function row.clearThisRowInvisible(). * * @param {GridRow} row the row we want to clear the invisible flag * */ GridRow.prototype.clearRowInvisible = function ( row ) { if (row && row.clearThisRowInvisible){ row.clearThisRowInvisible( 'user' ); } }; /** * @ngdoc function * @name setThisRowInvisible * @methodOf ui.grid.class:GridRow * @description Sets an override on the row that forces it to always * be invisible. Emits the rowsVisibleChanged event if it changed the row visibility * * @param {string} reason the reason (usually the module) for the row to be invisible. * E.g. grouping, user, filter * @param {boolean} fromRowsProcessor whether we were called from a rowsProcessor, passed through to evaluateRowVisibility */ GridRow.prototype.setThisRowInvisible = function ( reason, fromRowsProcessor ) { if ( !this.invisibleReason ){ this.invisibleReason = {}; } this.invisibleReason[reason] = true; this.evaluateRowVisibility( fromRowsProcessor); }; /** * @ngdoc function * @name clearRowInvisible * @methodOf ui.grid.class:GridRow * @description Clears any override on the row visibility, returning it * to normal visibility calculations. Emits the rowsVisibleChanged * event * * @param {string} reason the reason (usually the module) for the row to be invisible. * E.g. grouping, user, filter * @param {boolean} fromRowsProcessor whether we were called from a rowsProcessor, passed through to evaluateRowVisibility */ GridRow.prototype.clearThisRowInvisible = function ( reason, fromRowsProcessor ) { if (typeof(this.invisibleReason) !== 'undefined' ) { delete this.invisibleReason[reason]; } this.evaluateRowVisibility( fromRowsProcessor ); }; /** * @ngdoc function * @name evaluateRowVisibility * @methodOf ui.grid.class:GridRow * @description Determines whether the row should be visible based on invisibleReason, * and if it changes the row visibility, then emits the rowsVisibleChanged event. * * Queues a grid refresh, but doesn't call it directly to avoid hitting lots of grid refreshes. * @param {boolean} fromRowProcessor if true, then it won't raise events or queue the refresh, the * row processor does that already */ GridRow.prototype.evaluateRowVisibility = function ( fromRowProcessor ) { var newVisibility = true; if ( typeof(this.invisibleReason) !== 'undefined' ){ angular.forEach(this.invisibleReason, function( value, key ){ if ( value ){ newVisibility = false; } }); } if ( typeof(this.visible) === 'undefined' || this.visible !== newVisibility ){ this.visible = newVisibility; if ( !fromRowProcessor ){ this.grid.queueGridRefresh(); this.grid.api.core.raise.rowsVisibleChanged(this); } } }; return GridRow; }]); })(); (function(){ 'use strict'; /** * @ngdoc object * @name ui.grid.class:GridRowColumn * @param {GridRow} row The row for this pair * @param {GridColumn} column The column for this pair * @description A row and column pair that represents the intersection of these two entities. * Must be instantiated as a constructor using the `new` keyword. */ angular.module('ui.grid') .factory('GridRowColumn', ['$parse', '$filter', function GridRowColumnFactory($parse, $filter){ var GridRowColumn = function GridRowColumn(row, col) { if ( !(this instanceof GridRowColumn)){ throw "Using GridRowColumn as a function insead of as a constructor. Must be called with `new` keyword"; } /** * @ngdoc object * @name row * @propertyOf ui.grid.class:GridRowColumn * @description {@link ui.grid.class:GridRow } */ this.row = row; /** * @ngdoc object * @name col * @propertyOf ui.grid.class:GridRowColumn * @description {@link ui.grid.class:GridColumn } */ this.col = col; }; /** * @ngdoc function * @name getIntersectionValueRaw * @methodOf ui.grid.class:GridRowColumn * @description Gets the intersection of where the row and column meet. * @returns {String|Number|Object} The value from the grid data that this GridRowColumn points too. * If the column has a cellFilter this will NOT return the filtered value. */ GridRowColumn.prototype.getIntersectionValueRaw = function(){ var getter = $parse(this.row.getEntityQualifiedColField(this.col)); var context = this.row; return getter(context); }; /** * @ngdoc function * @name getIntersectionValueFiltered * @methodOf ui.grid.class:GridRowColumn * @description Gets the intersection of where the row and column meet. * @returns {String|Number|Object} The value from the grid data that this GridRowColumn points too. * If the column has a cellFilter this will also apply the filter to it and return the value that the filter displays. */ GridRowColumn.prototype.getIntersectionValueFiltered = function(){ var value = this.getIntersectionValueRaw(); if (this.col.cellFilter && this.col.cellFilter !== ''){ var getFilterIfExists = function(filterName){ try { return $filter(filterName); } catch (e){ return null; } }; var filter = getFilterIfExists(this.col.cellFilter); if (filter) { // Check if this is filter name or a filter string value = filter(value); } else { // We have the template version of a filter so we need to parse it apart // Get the filter params out using a regex // Test out this regex here https://regex101.com/r/rC5eR5/2 var re = /([^:]*):([^:]*):?([\s\S]+)?/; var matches; if ((matches = re.exec(this.col.cellFilter)) !== null) { // View your result using the matches-variable. // eg matches[0] etc. value = $filter(matches[1])(value, matches[2], matches[3]); } } } return value; }; return GridRowColumn; } ]); })(); (function () { angular.module('ui.grid') .factory('ScrollEvent', ['gridUtil', function (gridUtil) { /** * @ngdoc function * @name ui.grid.class:ScrollEvent * @description Model for all scrollEvents * @param {Grid} grid that owns the scroll event * @param {GridRenderContainer} sourceRowContainer that owns the scroll event. Can be null * @param {GridRenderContainer} sourceColContainer that owns the scroll event. Can be null * @param {string} source the source of the event - from uiGridConstants.scrollEventSources or a string value of directive/service/factory.functionName */ function ScrollEvent(grid, sourceRowContainer, sourceColContainer, source) { var self = this; if (!grid) { throw new Error("grid argument is required"); } /** * @ngdoc object * @name grid * @propertyOf ui.grid.class:ScrollEvent * @description A reference back to the grid */ self.grid = grid; /** * @ngdoc object * @name source * @propertyOf ui.grid.class:ScrollEvent * @description the source of the scroll event. limited to values from uiGridConstants.scrollEventSources */ self.source = source; /** * @ngdoc object * @name noDelay * @propertyOf ui.grid.class:ScrollEvent * @description most scroll events from the mouse or trackpad require delay to operate properly * set to false to eliminate delay. Useful for scroll events that the grid causes, such as scrolling to make a row visible. */ self.withDelay = true; self.sourceRowContainer = sourceRowContainer; self.sourceColContainer = sourceColContainer; self.newScrollLeft = null; self.newScrollTop = null; self.x = null; self.y = null; self.verticalScrollLength = -9999999; self.horizontalScrollLength = -999999; /** * @ngdoc function * @name fireThrottledScrollingEvent * @methodOf ui.grid.class:ScrollEvent * @description fires a throttled event using grid.api.core.raise.scrollEvent */ self.fireThrottledScrollingEvent = gridUtil.throttle(function(sourceContainerId) { self.grid.scrollContainers(sourceContainerId, self); }, self.grid.options.wheelScrollThrottle, {trailing: true}); } /** * @ngdoc function * @name getNewScrollLeft * @methodOf ui.grid.class:ScrollEvent * @description returns newScrollLeft property if available; calculates a new value if it isn't */ ScrollEvent.prototype.getNewScrollLeft = function(colContainer, viewport){ var self = this; if (!self.newScrollLeft){ var scrollWidth = (colContainer.getCanvasWidth() - colContainer.getViewportWidth()); var oldScrollLeft = gridUtil.normalizeScrollLeft(viewport, self.grid); var scrollXPercentage; if (typeof(self.x.percentage) !== 'undefined' && self.x.percentage !== undefined) { scrollXPercentage = self.x.percentage; } else if (typeof(self.x.pixels) !== 'undefined' && self.x.pixels !== undefined) { scrollXPercentage = self.x.percentage = (oldScrollLeft + self.x.pixels) / scrollWidth; } else { throw new Error("No percentage or pixel value provided for scroll event X axis"); } return Math.max(0, scrollXPercentage * scrollWidth); } return self.newScrollLeft; }; /** * @ngdoc function * @name getNewScrollTop * @methodOf ui.grid.class:ScrollEvent * @description returns newScrollTop property if available; calculates a new value if it isn't */ ScrollEvent.prototype.getNewScrollTop = function(rowContainer, viewport){ var self = this; if (!self.newScrollTop){ var scrollLength = rowContainer.getVerticalScrollLength(); var oldScrollTop = viewport[0].scrollTop; var scrollYPercentage; if (typeof(self.y.percentage) !== 'undefined' && self.y.percentage !== undefined) { scrollYPercentage = self.y.percentage; } else if (typeof(self.y.pixels) !== 'undefined' && self.y.pixels !== undefined) { scrollYPercentage = self.y.percentage = (oldScrollTop + self.y.pixels) / scrollLength; } else { throw new Error("No percentage or pixel value provided for scroll event Y axis"); } return Math.max(0, scrollYPercentage * scrollLength); } return self.newScrollTop; }; ScrollEvent.prototype.atTop = function(scrollTop) { return (this.y && (this.y.percentage === 0 || this.verticalScrollLength < 0) && scrollTop === 0); }; ScrollEvent.prototype.atBottom = function(scrollTop) { return (this.y && (this.y.percentage === 1 || this.verticalScrollLength === 0) && scrollTop > 0); }; ScrollEvent.prototype.atLeft = function(scrollLeft) { return (this.x && (this.x.percentage === 0 || this.horizontalScrollLength < 0) && scrollLeft === 0); }; ScrollEvent.prototype.atRight = function(scrollLeft) { return (this.x && (this.x.percentage === 1 || this.horizontalScrollLength ===0) && scrollLeft > 0); }; ScrollEvent.Sources = { ViewPortScroll: 'ViewPortScroll', RenderContainerMouseWheel: 'RenderContainerMouseWheel', RenderContainerTouchMove: 'RenderContainerTouchMove', Other: 99 }; return ScrollEvent; }]); })(); (function () { 'use strict'; /** * @ngdoc object * @name ui.grid.service:gridClassFactory * * @description factory to return dom specific instances of a grid * */ angular.module('ui.grid').service('gridClassFactory', ['gridUtil', '$q', '$compile', '$templateCache', 'uiGridConstants', 'Grid', 'GridColumn', 'GridRow', function (gridUtil, $q, $compile, $templateCache, uiGridConstants, Grid, GridColumn, GridRow) { var service = { /** * @ngdoc method * @name createGrid * @methodOf ui.grid.service:gridClassFactory * @description Creates a new grid instance. Each instance will have a unique id * @param {object} options An object map of options to pass into the created grid instance. * @returns {Grid} grid */ createGrid : function(options) { options = (typeof(options) !== 'undefined') ? options : {}; options.id = gridUtil.newId(); var grid = new Grid(options); // NOTE/TODO: rowTemplate should always be defined... if (grid.options.rowTemplate) { var rowTemplateFnPromise = $q.defer(); grid.getRowTemplateFn = rowTemplateFnPromise.promise; gridUtil.getTemplate(grid.options.rowTemplate) .then( function (template) { var rowTemplateFn = $compile(template); rowTemplateFnPromise.resolve(rowTemplateFn); }, function (res) { // Todo handle response error here? throw new Error("Couldn't fetch/use row template '" + grid.options.rowTemplate + "'"); }); } grid.registerColumnBuilder(service.defaultColumnBuilder); // Row builder for custom row templates grid.registerRowBuilder(service.rowTemplateAssigner); // Reset all rows to visible initially grid.registerRowsProcessor(function allRowsVisible(rows) { rows.forEach(function (row) { row.evaluateRowVisibility( true ); }, 50); return rows; }); grid.registerColumnsProcessor(function allColumnsVisible(columns) { columns.forEach(function (column) { column.visible = true; }); return columns; }, 50); grid.registerColumnsProcessor(function(renderableColumns) { renderableColumns.forEach(function (column) { if (column.colDef.visible === false) { column.visible = false; } }); return renderableColumns; }, 50); grid.registerRowsProcessor(grid.searchRows, 100); // Register the default row processor, it sorts rows by selected columns if (grid.options.externalSort && angular.isFunction(grid.options.externalSort)) { grid.registerRowsProcessor(grid.options.externalSort, 200); } else { grid.registerRowsProcessor(grid.sortByColumn, 200); } return grid; }, /** * @ngdoc function * @name defaultColumnBuilder * @methodOf ui.grid.service:gridClassFactory * @description Processes designTime column definitions and applies them to col for the * core grid features * @param {object} colDef reference to column definition * @param {GridColumn} col reference to gridCol * @param {object} gridOptions reference to grid options */ defaultColumnBuilder: function (colDef, col, gridOptions) { var templateGetPromises = []; // Abstracts the standard template processing we do for every template type. var processTemplate = function( templateType, providedType, defaultTemplate, filterType, tooltipType ) { if ( !colDef[templateType] ){ col[providedType] = defaultTemplate; } else { col[providedType] = colDef[templateType]; } templateGetPromises.push(gridUtil.getTemplate(col[providedType]) .then( function (template) { if ( angular.isFunction(template) ) { template = template(); } var tooltipCall = ( tooltipType === 'cellTooltip' ) ? 'col.cellTooltip(row,col)' : 'col.headerTooltip(col)'; if ( tooltipType && col[tooltipType] === false ){ template = template.replace(uiGridConstants.TOOLTIP, ''); } else if ( tooltipType && col[tooltipType] ){ template = template.replace(uiGridConstants.TOOLTIP, 'title="{{' + tooltipCall + ' CUSTOM_FILTERS }}"'); } if ( filterType ){ col[templateType] = template.replace(uiGridConstants.CUSTOM_FILTERS, function() { return col[filterType] ? "|" + col[filterType] : ""; }); } else { col[templateType] = template; } }, function (res) { throw new Error("Couldn't fetch/use colDef." + templateType + " '" + colDef[templateType] + "'"); }) ); }; /** * @ngdoc property * @name cellTemplate * @propertyOf ui.grid.class:GridOptions.columnDef * @description a custom template for each cell in this column. The default * is ui-grid/uiGridCell. If you are using the cellNav feature, this template * must contain a div that can receive focus. * */ processTemplate( 'cellTemplate', 'providedCellTemplate', 'ui-grid/uiGridCell', 'cellFilter', 'cellTooltip' ); col.cellTemplatePromise = templateGetPromises[0]; /** * @ngdoc property * @name headerCellTemplate * @propertyOf ui.grid.class:GridOptions.columnDef * @description a custom template for the header for this column. The default * is ui-grid/uiGridHeaderCell * */ processTemplate( 'headerCellTemplate', 'providedHeaderCellTemplate', 'ui-grid/uiGridHeaderCell', 'headerCellFilter', 'headerTooltip' ); /** * @ngdoc property * @name footerCellTemplate * @propertyOf ui.grid.class:GridOptions.columnDef * @description a custom template for the footer for this column. The default * is ui-grid/uiGridFooterCell * */ processTemplate( 'footerCellTemplate', 'providedFooterCellTemplate', 'ui-grid/uiGridFooterCell', 'footerCellFilter' ); /** * @ngdoc property * @name filterHeaderTemplate * @propertyOf ui.grid.class:GridOptions.columnDef * @description a custom template for the filter input. The default is ui-grid/ui-grid-filter * */ processTemplate( 'filterHeaderTemplate', 'providedFilterHeaderTemplate', 'ui-grid/ui-grid-filter' ); // Create a promise for the compiled element function col.compiledElementFnDefer = $q.defer(); return $q.all(templateGetPromises); }, rowTemplateAssigner: function rowTemplateAssigner(row) { var grid = this; // Row has no template assigned to it if (!row.rowTemplate) { // Use the default row template from the grid row.rowTemplate = grid.options.rowTemplate; // Use the grid's function for fetching the compiled row template function row.getRowTemplateFn = grid.getRowTemplateFn; } // Row has its own template assigned else { // Create a promise for the compiled row template function var perRowTemplateFnPromise = $q.defer(); row.getRowTemplateFn = perRowTemplateFnPromise.promise; // Get the row template gridUtil.getTemplate(row.rowTemplate) .then(function (template) { // Compile the template var rowTemplateFn = $compile(template); // Resolve the compiled template function promise perRowTemplateFnPromise.resolve(rowTemplateFn); }, function (res) { // Todo handle response error here? throw new Error("Couldn't fetch/use row template '" + row.rowTemplate + "'"); }); } return row.getRowTemplateFn; } }; //class definitions (moved to separate factories) return service; }]); })(); (function() { var module = angular.module('ui.grid'); function escapeRegExp(str) { return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); } /** * @ngdoc service * @name ui.grid.service:rowSearcher * * @description Service for searching/filtering rows based on column value conditions. */ module.service('rowSearcher', ['gridUtil', 'uiGridConstants', function (gridUtil, uiGridConstants) { var defaultCondition = uiGridConstants.filter.CONTAINS; var rowSearcher = {}; /** * @ngdoc function * @name getTerm * @methodOf ui.grid.service:rowSearcher * @description Get the term from a filter * Trims leading and trailing whitespace * @param {object} filter object to use * @returns {object} Parsed term */ rowSearcher.getTerm = function getTerm(filter) { if (typeof(filter.term) === 'undefined') { return filter.term; } var term = filter.term; // Strip leading and trailing whitespace if the term is a string if (typeof(term) === 'string') { term = term.trim(); } return term; }; /** * @ngdoc function * @name stripTerm * @methodOf ui.grid.service:rowSearcher * @description Remove leading and trailing asterisk (*) from the filter's term * @param {object} filter object to use * @returns {uiGridConstants.filter<int>} Value representing the condition constant value */ rowSearcher.stripTerm = function stripTerm(filter) { var term = rowSearcher.getTerm(filter); if (typeof(term) === 'string') { return escapeRegExp(term.replace(/(^\*|\*$)/g, '')); } else { return term; } }; /** * @ngdoc function * @name guessCondition * @methodOf ui.grid.service:rowSearcher * @description Guess the condition for a filter based on its term * <br> * Defaults to STARTS_WITH. Uses CONTAINS for strings beginning and ending with *s (*bob*). * Uses STARTS_WITH for strings ending with * (bo*). Uses ENDS_WITH for strings starting with * (*ob). * @param {object} filter object to use * @returns {uiGridConstants.filter<int>} Value representing the condition constant value */ rowSearcher.guessCondition = function guessCondition(filter) { if (typeof(filter.term) === 'undefined' || !filter.term) { return defaultCondition; } var term = rowSearcher.getTerm(filter); if (/\*/.test(term)) { var regexpFlags = ''; if (!filter.flags || !filter.flags.caseSensitive) { regexpFlags += 'i'; } var reText = term.replace(/(\\)?\*/g, function ($0, $1) { return $1 ? $0 : '[\\s\\S]*?'; }); return new RegExp('^' + reText + '$', regexpFlags); } // Otherwise default to default condition else { return defaultCondition; } }; /** * @ngdoc function * @name setupFilters * @methodOf ui.grid.service:rowSearcher * @description For a given columns filters (either col.filters, or [col.filter] can be passed in), * do all the parsing and pre-processing and store that data into a new filters object. The object * has the condition, the flags, the stripped term, and a parsed reg exp if there was one. * * We could use a forEach in here, since it's much less performance sensitive, but since we're using * for loops everywhere else in this module... * * @param {array} filters the filters from the column (col.filters or [col.filter]) * @returns {array} An array of parsed/preprocessed filters */ rowSearcher.setupFilters = function setupFilters( filters ){ var newFilters = []; var filtersLength = filters.length; for ( var i = 0; i < filtersLength; i++ ){ var filter = filters[i]; if ( filter.noTerm || !gridUtil.isNullOrUndefined(filter.term) ){ var newFilter = {}; var regexpFlags = ''; if (!filter.flags || !filter.flags.caseSensitive) { regexpFlags += 'i'; } if ( !gridUtil.isNullOrUndefined(filter.term) ){ // it is possible to have noTerm. We don't need to copy that across, it was just a flag to avoid // getting the filter ignored if the filter was a function that didn't use a term newFilter.term = rowSearcher.stripTerm(filter); } if ( filter.condition ){ newFilter.condition = filter.condition; } else { newFilter.condition = rowSearcher.guessCondition(filter); } newFilter.flags = angular.extend( { caseSensitive: false, date: false }, filter.flags ); if (newFilter.condition === uiGridConstants.filter.STARTS_WITH) { newFilter.startswithRE = new RegExp('^' + newFilter.term, regexpFlags); } if (newFilter.condition === uiGridConstants.filter.ENDS_WITH) { newFilter.endswithRE = new RegExp(newFilter.term + '$', regexpFlags); } if (newFilter.condition === uiGridConstants.filter.CONTAINS) { newFilter.containsRE = new RegExp(newFilter.term, regexpFlags); } if (newFilter.condition === uiGridConstants.filter.EXACT) { newFilter.exactRE = new RegExp('^' + newFilter.term + '$', regexpFlags); } newFilters.push(newFilter); } } return newFilters; }; /** * @ngdoc function * @name runColumnFilter * @methodOf ui.grid.service:rowSearcher * @description Runs a single pre-parsed filter against a cell, returning true * if the cell matches that one filter. * * @param {Grid} grid the grid we're working against * @param {GridRow} row the row we're matching against * @param {GridCol} column the column that we're working against * @param {object} filter the specific, preparsed, filter that we want to test * @returns {boolean} true if we match (row stays visible) */ rowSearcher.runColumnFilter = function runColumnFilter(grid, row, column, filter) { // Cache typeof condition var conditionType = typeof(filter.condition); // Term to search for. var term = filter.term; // Get the column value for this row var value; if ( column.filterCellFiltered ){ value = grid.getCellDisplayValue(row, column); } else { value = grid.getCellValue(row, column); } // If the filter's condition is a RegExp, then use it if (filter.condition instanceof RegExp) { return filter.condition.test(value); } // If the filter's condition is a function, run it if (conditionType === 'function') { return filter.condition(term, value, row, column); } if (filter.startswithRE) { return filter.startswithRE.test(value); } if (filter.endswithRE) { return filter.endswithRE.test(value); } if (filter.containsRE) { return filter.containsRE.test(value); } if (filter.exactRE) { return filter.exactRE.test(value); } if (filter.condition === uiGridConstants.filter.NOT_EQUAL) { var regex = new RegExp('^' + term + '$'); return !regex.exec(value); } if (typeof(value) === 'number' && typeof(term) === 'string' ){ // if the term has a decimal in it, it comes through as '9\.4', we need to take out the \ // the same for negative numbers // TODO: I suspect the right answer is to look at escapeRegExp at the top of this code file, maybe it's not needed? var tempFloat = parseFloat(term.replace(/\\\./,'.').replace(/\\\-/,'-')); if (!isNaN(tempFloat)) { term = tempFloat; } } if (filter.flags.date === true) { value = new Date(value); // If the term has a dash in it, it comes through as '\-' -- we need to take out the '\'. term = new Date(term.replace(/\\/g, '')); } if (filter.condition === uiGridConstants.filter.GREATER_THAN) { return (value > term); } if (filter.condition === uiGridConstants.filter.GREATER_THAN_OR_EQUAL) { return (value >= term); } if (filter.condition === uiGridConstants.filter.LESS_THAN) { return (value < term); } if (filter.condition === uiGridConstants.filter.LESS_THAN_OR_EQUAL) { return (value <= term); } return true; }; /** * @ngdoc boolean * @name useExternalFiltering * @propertyOf ui.grid.class:GridOptions * @description False by default. When enabled, this setting suppresses the internal filtering. * All UI logic will still operate, allowing filter conditions to be set and modified. * * The external filter logic can listen for the `filterChange` event, which fires whenever * a filter has been adjusted. */ /** * @ngdoc function * @name searchColumn * @methodOf ui.grid.service:rowSearcher * @description Process provided filters on provided column against a given row. If the row meets * the conditions on all the filters, return true. * @param {Grid} grid Grid to search in * @param {GridRow} row Row to search on * @param {GridCol} column Column with the filters to use * @param {array} filters array of pre-parsed/preprocessed filters to apply * @returns {boolean} Whether the column matches or not. */ rowSearcher.searchColumn = function searchColumn(grid, row, column, filters) { if (grid.options.useExternalFiltering) { return true; } var filtersLength = filters.length; for (var i = 0; i < filtersLength; i++) { var filter = filters[i]; var ret = rowSearcher.runColumnFilter(grid, row, column, filter); if (!ret) { return false; } } return true; }; /** * @ngdoc function * @name search * @methodOf ui.grid.service:rowSearcher * @description Run a search across the given rows and columns, marking any rows that don't * match the stored col.filters or col.filter as invisible. * @param {Grid} grid Grid instance to search inside * @param {Array[GridRow]} rows GridRows to filter * @param {Array[GridColumn]} columns GridColumns with filters to process */ rowSearcher.search = function search(grid, rows, columns) { /* * Added performance optimisations into this code base, as this logic creates deeply nested * loops and is therefore very performance sensitive. In particular, avoiding forEach as * this impacts some browser optimisers (particularly Chrome), using iterators instead */ // Don't do anything if we weren't passed any rows if (!rows) { return; } // don't filter if filtering currently disabled if (!grid.options.enableFiltering){ return rows; } // Build list of filters to apply var filterData = []; var colsLength = columns.length; var hasTerm = function( filters ) { var hasTerm = false; filters.forEach( function (filter) { if ( !gridUtil.isNullOrUndefined(filter.term) && filter.term !== '' || filter.noTerm ){ hasTerm = true; } }); return hasTerm; }; for (var i = 0; i < colsLength; i++) { var col = columns[i]; if (typeof(col.filters) !== 'undefined' && hasTerm(col.filters) ) { filterData.push( { col: col, filters: rowSearcher.setupFilters(col.filters) } ); } } if (filterData.length > 0) { // define functions outside the loop, performance optimisation var foreachRow = function(grid, row, col, filters){ if ( row.visible && !rowSearcher.searchColumn(grid, row, col, filters) ) { row.visible = false; } }; var foreachFilterCol = function(grid, filterData){ var rowsLength = rows.length; for ( var i = 0; i < rowsLength; i++){ foreachRow(grid, rows[i], filterData.col, filterData.filters); } }; // nested loop itself - foreachFilterCol, which in turn calls foreachRow var filterDataLength = filterData.length; for ( var j = 0; j < filterDataLength; j++){ foreachFilterCol( grid, filterData[j] ); } if (grid.api.core.raise.rowsVisibleChanged) { grid.api.core.raise.rowsVisibleChanged(); } // drop any invisible rows // keeping these, as needed with filtering for trees - we have to come back and make parent nodes visible if child nodes are selected in the filter // rows = rows.filter(function(row){ return row.visible; }); } return rows; }; return rowSearcher; }]); })(); (function() { var module = angular.module('ui.grid'); /** * @ngdoc object * @name ui.grid.class:RowSorter * @description RowSorter provides the default sorting mechanisms, * including guessing column types and applying appropriate sort * algorithms * */ module.service('rowSorter', ['$parse', 'uiGridConstants', function ($parse, uiGridConstants) { var currencyRegexStr = '(' + uiGridConstants.CURRENCY_SYMBOLS .map(function (a) { return '\\' + a; }) // Escape all the currency symbols ($ at least will jack up this regex) .join('|') + // Join all the symbols together with |s ')?'; // /^[-+]?[£$¤¥]?[\d,.]+%?$/ var numberStrRegex = new RegExp('^[-+]?' + currencyRegexStr + '[\\d,.]+' + currencyRegexStr + '%?$'); var rowSorter = { // Cache of sorting functions. Once we create them, we don't want to keep re-doing it // this takes a piece of data from the cell and tries to determine its type and what sorting // function to use for it colSortFnCache: {} }; /** * @ngdoc method * @methodOf ui.grid.class:RowSorter * @name guessSortFn * @description Assigns a sort function to use based on the itemType in the column * @param {string} itemType one of 'number', 'boolean', 'string', 'date', 'object'. And * error will be thrown for any other type. * @returns {function} a sort function that will sort that type */ rowSorter.guessSortFn = function guessSortFn(itemType) { switch (itemType) { case "number": return rowSorter.sortNumber; case "numberStr": return rowSorter.sortNumberStr; case "boolean": return rowSorter.sortBool; case "string": return rowSorter.sortAlpha; case "date": return rowSorter.sortDate; case "object": return rowSorter.basicSort; default: throw new Error('No sorting function found for type:' + itemType); } }; /** * @ngdoc method * @methodOf ui.grid.class:RowSorter * @name handleNulls * @description Sorts nulls and undefined to the bottom (top when * descending). Called by each of the internal sorters before * attempting to sort. Note that this method is available on the core api * via gridApi.core.sortHandleNulls * @param {object} a sort value a * @param {object} b sort value b * @returns {number} null if there were no nulls/undefineds, otherwise returns * a sort value that should be passed back from the sort function */ rowSorter.handleNulls = function handleNulls(a, b) { // We want to allow zero values and false values to be evaluated in the sort function if ((!a && a !== 0 && a !== false) || (!b && b !== 0 && b !== false)) { // We want to force nulls and such to the bottom when we sort... which effectively is "greater than" if ((!a && a !== 0 && a !== false) && (!b && b !== 0 && b !== false)) { return 0; } else if (!a && a !== 0 && a !== false) { return 1; } else if (!b && b !== 0 && b !== false) { return -1; } } return null; }; /** * @ngdoc method * @methodOf ui.grid.class:RowSorter * @name basicSort * @description Sorts any values that provide the < method, including strings * or numbers. Handles nulls and undefined through calling handleNulls * @param {object} a sort value a * @param {object} b sort value b * @returns {number} normal sort function, returns -ve, 0, +ve */ rowSorter.basicSort = function basicSort(a, b) { var nulls = rowSorter.handleNulls(a, b); if ( nulls !== null ){ return nulls; } else { if (a === b) { return 0; } if (a < b) { return -1; } return 1; } }; /** * @ngdoc method * @methodOf ui.grid.class:RowSorter * @name sortNumber * @description Sorts numerical values. Handles nulls and undefined through calling handleNulls * @param {object} a sort value a * @param {object} b sort value b * @returns {number} normal sort function, returns -ve, 0, +ve */ rowSorter.sortNumber = function sortNumber(a, b) { var nulls = rowSorter.handleNulls(a, b); if ( nulls !== null ){ return nulls; } else { return a - b; } }; /** * @ngdoc method * @methodOf ui.grid.class:RowSorter * @name sortNumberStr * @description Sorts numerical values that are stored in a string (i.e. parses them to numbers first). * Handles nulls and undefined through calling handleNulls * @param {object} a sort value a * @param {object} b sort value b * @returns {number} normal sort function, returns -ve, 0, +ve */ rowSorter.sortNumberStr = function sortNumberStr(a, b) { var nulls = rowSorter.handleNulls(a, b); if ( nulls !== null ){ return nulls; } else { var numA, // The parsed number form of 'a' numB, // The parsed number form of 'b' badA = false, badB = false; // Try to parse 'a' to a float numA = parseFloat(a.replace(/[^0-9.-]/g, '')); // If 'a' couldn't be parsed to float, flag it as bad if (isNaN(numA)) { badA = true; } // Try to parse 'b' to a float numB = parseFloat(b.replace(/[^0-9.-]/g, '')); // If 'b' couldn't be parsed to float, flag it as bad if (isNaN(numB)) { badB = true; } // We want bad ones to get pushed to the bottom... which effectively is "greater than" if (badA && badB) { return 0; } if (badA) { return 1; } if (badB) { return -1; } return numA - numB; } }; /** * @ngdoc method * @methodOf ui.grid.class:RowSorter * @name sortAlpha * @description Sorts string values. Handles nulls and undefined through calling handleNulls * @param {object} a sort value a * @param {object} b sort value b * @returns {number} normal sort function, returns -ve, 0, +ve */ rowSorter.sortAlpha = function sortAlpha(a, b) { var nulls = rowSorter.handleNulls(a, b); if ( nulls !== null ){ return nulls; } else { var strA = a.toString().toLowerCase(), strB = b.toString().toLowerCase(); return strA === strB ? 0 : (strA < strB ? -1 : 1); } }; /** * @ngdoc method * @methodOf ui.grid.class:RowSorter * @name sortDate * @description Sorts date values. Handles nulls and undefined through calling handleNulls. * Handles date strings by converting to Date object if not already an instance of Date * @param {object} a sort value a * @param {object} b sort value b * @returns {number} normal sort function, returns -ve, 0, +ve */ rowSorter.sortDate = function sortDate(a, b) { var nulls = rowSorter.handleNulls(a, b); if ( nulls !== null ){ return nulls; } else { if (!(a instanceof Date)) { a = new Date(a); } if (!(b instanceof Date)){ b = new Date(b); } var timeA = a.getTime(), timeB = b.getTime(); return timeA === timeB ? 0 : (timeA < timeB ? -1 : 1); } }; /** * @ngdoc method * @methodOf ui.grid.class:RowSorter * @name sortBool * @description Sorts boolean values, true is considered larger than false. * Handles nulls and undefined through calling handleNulls * @param {object} a sort value a * @param {object} b sort value b * @returns {number} normal sort function, returns -ve, 0, +ve */ rowSorter.sortBool = function sortBool(a, b) { var nulls = rowSorter.handleNulls(a, b); if ( nulls !== null ){ return nulls; } else { if (a && b) { return 0; } if (!a && !b) { return 0; } else { return a ? 1 : -1; } } }; /** * @ngdoc method * @methodOf ui.grid.class:RowSorter * @name getSortFn * @description Get the sort function for the column. Looks first in * rowSorter.colSortFnCache using the column name, failing that it * looks at col.sortingAlgorithm (and puts it in the cache), failing that * it guesses the sort algorithm based on the data type. * * The cache currently seems a bit pointless, as none of the work we do is * processor intensive enough to need caching. Presumably in future we might * inspect the row data itself to guess the sort function, and in that case * it would make sense to have a cache, the infrastructure is in place to allow * that. * * @param {Grid} grid the grid to consider * @param {GridCol} col the column to find a function for * @param {array} rows an array of grid rows. Currently unused, but presumably in future * we might inspect the rows themselves to decide what sort of data might be there * @returns {function} the sort function chosen for the column */ rowSorter.getSortFn = function getSortFn(grid, col, rows) { var sortFn, item; // See if we already figured out what to use to sort the column and have it in the cache if (rowSorter.colSortFnCache[col.colDef.name]) { sortFn = rowSorter.colSortFnCache[col.colDef.name]; } // If the column has its OWN sorting algorithm, use that else if (col.sortingAlgorithm !== undefined) { sortFn = col.sortingAlgorithm; rowSorter.colSortFnCache[col.colDef.name] = col.sortingAlgorithm; } // Always default to sortAlpha when sorting after a cellFilter else if ( col.sortCellFiltered && col.cellFilter ){ sortFn = rowSorter.sortAlpha; rowSorter.colSortFnCache[col.colDef.name] = sortFn; } // Try and guess what sort function to use else { // Guess the sort function sortFn = rowSorter.guessSortFn(col.colDef.type); // If we found a sort function, cache it if (sortFn) { rowSorter.colSortFnCache[col.colDef.name] = sortFn; } else { // We assign the alpha sort because anything that is null/undefined will never get passed to // the actual sorting function. It will get caught in our null check and returned to be sorted // down to the bottom sortFn = rowSorter.sortAlpha; } } return sortFn; }; /** * @ngdoc method * @methodOf ui.grid.class:RowSorter * @name prioritySort * @description Used where multiple columns are present in the sort criteria, * we determine which column should take precedence in the sort by sorting * the columns based on their sort.priority * * @param {gridColumn} a column a * @param {gridColumn} b column b * @returns {number} normal sort function, returns -ve, 0, +ve */ rowSorter.prioritySort = function (a, b) { // Both columns have a sort priority if (a.sort.priority !== undefined && b.sort.priority !== undefined) { // A is higher priority if (a.sort.priority < b.sort.priority) { return -1; } // Equal else if (a.sort.priority === b.sort.priority) { return 0; } // B is higher else { return 1; } } // Only A has a priority else if (a.sort.priority || a.sort.priority === 0) { return -1; } // Only B has a priority else if (b.sort.priority || b.sort.priority === 0) { return 1; } // Neither has a priority else { return 0; } }; /** * @ngdoc object * @name useExternalSorting * @propertyOf ui.grid.class:GridOptions * @description Prevents the internal sorting from executing. Events will * still be fired when the sort changes, and the sort information on * the columns will be updated, allowing an external sorter (for example, * server sorting) to be implemented. Defaults to false. * */ /** * @ngdoc method * @methodOf ui.grid.class:RowSorter * @name sort * @description sorts the grid * @param {Object} grid the grid itself * @param {array} rows the rows to be sorted * @param {array} columns the columns in which to look * for sort criteria * @returns {array} sorted rows */ rowSorter.sort = function rowSorterSort(grid, rows, columns) { // first make sure we are even supposed to do work if (!rows) { return; } if (grid.options.useExternalSorting){ return rows; } // Build the list of columns to sort by var sortCols = []; columns.forEach(function (col) { if (col.sort && !col.sort.ignoreSort && col.sort.direction && (col.sort.direction === uiGridConstants.ASC || col.sort.direction === uiGridConstants.DESC)) { sortCols.push(col); } }); // Sort the "sort columns" by their sort priority sortCols = sortCols.sort(rowSorter.prioritySort); // Now rows to sort by, maintain original order if (sortCols.length === 0) { return rows; } // Re-usable variables var col, direction; // put a custom index field on each row, used to make a stable sort out of unstable sorts (e.g. Chrome) var setIndex = function( row, idx ){ row.entity.$$uiGridIndex = idx; }; rows.forEach(setIndex); // IE9-11 HACK.... the 'rows' variable would be empty where we call rowSorter.getSortFn(...) below. We have to use a separate reference // var d = data.slice(0); var r = rows.slice(0); // Now actually sort the data var rowSortFn = function (rowA, rowB) { var tem = 0, idx = 0, sortFn; while (tem === 0 && idx < sortCols.length) { // grab the metadata for the rest of the logic col = sortCols[idx]; direction = sortCols[idx].sort.direction; sortFn = rowSorter.getSortFn(grid, col, r); var propA, propB; if ( col.sortCellFiltered ){ propA = grid.getCellDisplayValue(rowA, col); propB = grid.getCellDisplayValue(rowB, col); } else { propA = grid.getCellValue(rowA, col); propB = grid.getCellValue(rowB, col); } tem = sortFn(propA, propB); idx++; } // Chrome doesn't implement a stable sort function. If our sort returns 0 // (i.e. the items are equal), and we're at the last sort column in the list, // then return the previous order using our custom // index variable if (tem === 0 ) { return rowA.entity.$$uiGridIndex - rowB.entity.$$uiGridIndex; } // Made it this far, we don't have to worry about null & undefined if (direction === uiGridConstants.ASC) { return tem; } else { return 0 - tem; } }; var newRows = rows.sort(rowSortFn); // remove the custom index field on each row, used to make a stable sort out of unstable sorts (e.g. Chrome) var clearIndex = function( row, idx ){ delete row.entity.$$uiGridIndex; }; rows.forEach(clearIndex); return newRows; }; return rowSorter; }]); })(); (function() { var module = angular.module('ui.grid'); var bindPolyfill; if (typeof Function.prototype.bind !== "function") { bindPolyfill = function() { var slice = Array.prototype.slice; return function(context) { var fn = this, args = slice.call(arguments, 1); if (args.length) { return function() { return arguments.length ? fn.apply(context, args.concat(slice.call(arguments))) : fn.apply(context, args); }; } return function() { return arguments.length ? fn.apply(context, arguments) : fn.call(context); }; }; }; } function getStyles (elem) { var e = elem; if (typeof(e.length) !== 'undefined' && e.length) { e = elem[0]; } return e.ownerDocument.defaultView.getComputedStyle(e, null); } var rnumnonpx = new RegExp( "^(" + (/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/).source + ")(?!px)[a-z%]+$", "i" ), // swappable if display is none or starts with table except "table", "table-cell", or "table-caption" // see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display rdisplayswap = /^(block|none|table(?!-c[ea]).+)/, cssShow = { position: "absolute", visibility: "hidden", display: "block" }; function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) { var i = extra === ( isBorderBox ? 'border' : 'content' ) ? // If we already have the right measurement, avoid augmentation 4 : // Otherwise initialize for horizontal or vertical properties name === 'width' ? 1 : 0, val = 0; var sides = ['Top', 'Right', 'Bottom', 'Left']; for ( ; i < 4; i += 2 ) { var side = sides[i]; // dump('side', side); // both box models exclude margin, so add it if we want it if ( extra === 'margin' ) { var marg = parseFloat(styles[extra + side]); if (!isNaN(marg)) { val += marg; } } // dump('val1', val); if ( isBorderBox ) { // border-box includes padding, so remove it if we want content if ( extra === 'content' ) { var padd = parseFloat(styles['padding' + side]); if (!isNaN(padd)) { val -= padd; // dump('val2', val); } } // at this point, extra isn't border nor margin, so remove border if ( extra !== 'margin' ) { var bordermarg = parseFloat(styles['border' + side + 'Width']); if (!isNaN(bordermarg)) { val -= bordermarg; // dump('val3', val); } } } else { // at this point, extra isn't content, so add padding var nocontentPad = parseFloat(styles['padding' + side]); if (!isNaN(nocontentPad)) { val += nocontentPad; // dump('val4', val); } // at this point, extra isn't content nor padding, so add border if ( extra !== 'padding') { var nocontentnopad = parseFloat(styles['border' + side + 'Width']); if (!isNaN(nocontentnopad)) { val += nocontentnopad; // dump('val5', val); } } } } // dump('augVal', val); return val; } function getWidthOrHeight( elem, name, extra ) { // Start with offset property, which is equivalent to the border-box value var valueIsBorderBox = true, val, // = name === 'width' ? elem.offsetWidth : elem.offsetHeight, styles = getStyles(elem), isBorderBox = styles['boxSizing'] === 'border-box'; // some non-html elements return undefined for offsetWidth, so check for null/undefined // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285 // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668 if ( val <= 0 || val == null ) { // Fall back to computed then uncomputed css if necessary val = styles[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; } // we need the check for style in case a browser which returns unreliable values // for getComputedStyle silently falls back to the reliable elem.style valueIsBorderBox = isBorderBox && ( true || val === elem.style[ name ] ); // use 'true' instead of 'support.boxSizingReliable()' // Normalize "", auto, and prepare for extra val = parseFloat( val ) || 0; } // use the active box-sizing model to add/subtract irrelevant styles var ret = ( val + augmentWidthOrHeight( elem, name, extra || ( isBorderBox ? "border" : "content" ), valueIsBorderBox, styles ) ); // dump('ret', ret, val); return ret; } function getLineHeight(elm) { elm = angular.element(elm)[0]; var parent = elm.parentElement; if (!parent) { parent = document.getElementsByTagName('body')[0]; } return parseInt( getStyles(parent).fontSize ) || parseInt( getStyles(elm).fontSize ) || 16; } var uid = ['0', '0', '0', '0']; var uidPrefix = 'uiGrid-'; /** * @ngdoc service * @name ui.grid.service:GridUtil * * @description Grid utility functions */ module.service('gridUtil', ['$log', '$window', '$document', '$http', '$templateCache', '$timeout', '$interval', '$injector', '$q', '$interpolate', 'uiGridConstants', function ($log, $window, $document, $http, $templateCache, $timeout, $interval, $injector, $q, $interpolate, uiGridConstants) { var s = { augmentWidthOrHeight: augmentWidthOrHeight, getStyles: getStyles, /** * @ngdoc method * @name createBoundedWrapper * @methodOf ui.grid.service:GridUtil * * @param {object} Object to bind 'this' to * @param {method} Method to bind * @returns {Function} The wrapper that performs the binding * * @description * Binds given method to given object. * * By means of a wrapper, ensures that ``method`` is always bound to * ``object`` regardless of its calling environment. * Iow, inside ``method``, ``this`` always points to ``object``. * * See http://alistapart.com/article/getoutbindingsituations * */ createBoundedWrapper: function(object, method) { return function() { return method.apply(object, arguments); }; }, /** * @ngdoc method * @name readableColumnName * @methodOf ui.grid.service:GridUtil * * @param {string} columnName Column name as a string * @returns {string} Column name appropriately capitalized and split apart * @example <example module="app"> <file name="app.js"> var app = angular.module('app', ['ui.grid']); app.controller('MainCtrl', ['$scope', 'gridUtil', function ($scope, gridUtil) { $scope.name = 'firstName'; $scope.columnName = function(name) { return gridUtil.readableColumnName(name); }; }]); </file> <file name="index.html"> <div ng-controller="MainCtrl"> <strong>Column name:</strong> <input ng-model="name" /> <br> <strong>Output:</strong> <span ng-bind="columnName(name)"></span> </div> </file> </example> */ readableColumnName: function (columnName) { // Convert underscores to spaces if (typeof(columnName) === 'undefined' || columnName === undefined || columnName === null) { return columnName; } if (typeof(columnName) !== 'string') { columnName = String(columnName); } return columnName.replace(/_+/g, ' ') // Replace a completely all-capsed word with a first-letter-capitalized version .replace(/^[A-Z]+$/, function (match) { return angular.lowercase(angular.uppercase(match.charAt(0)) + match.slice(1)); }) // Capitalize the first letter of words .replace(/([\w\u00C0-\u017F]+)/g, function (match) { return angular.uppercase(match.charAt(0)) + match.slice(1); }) // Put a space in between words that have partial capilizations (i.e. 'firstName' becomes 'First Name') // .replace(/([A-Z]|[A-Z]\w+)([A-Z])/g, "$1 $2"); // .replace(/(\w+?|\w)([A-Z])/g, "$1 $2"); .replace(/(\w+?(?=[A-Z]))/g, '$1 '); }, /** * @ngdoc method * @name getColumnsFromData * @methodOf ui.grid.service:GridUtil * @description Return a list of column names, given a data set * * @param {string} data Data array for grid * @returns {Object} Column definitions with field accessor and column name * * @example <pre> var data = [ { firstName: 'Bob', lastName: 'Jones' }, { firstName: 'Frank', lastName: 'Smith' } ]; var columnDefs = GridUtil.getColumnsFromData(data, excludeProperties); columnDefs == [ { field: 'firstName', name: 'First Name' }, { field: 'lastName', name: 'Last Name' } ]; </pre> */ getColumnsFromData: function (data, excludeProperties) { var columnDefs = []; if (!data || typeof(data[0]) === 'undefined' || data[0] === undefined) { return []; } if (angular.isUndefined(excludeProperties)) { excludeProperties = []; } var item = data[0]; angular.forEach(item,function (prop, propName) { if ( excludeProperties.indexOf(propName) === -1){ columnDefs.push({ name: propName }); } }); return columnDefs; }, /** * @ngdoc method * @name newId * @methodOf ui.grid.service:GridUtil * @description Return a unique ID string * * @returns {string} Unique string * * @example <pre> var id = GridUtil.newId(); # 1387305700482; </pre> */ newId: (function() { var seedId = new Date().getTime(); return function() { return seedId += 1; }; })(), /** * @ngdoc method * @name getTemplate * @methodOf ui.grid.service:GridUtil * @description Get's template from cache / element / url * * @param {string|element|promise} Either a string representing the template id, a string representing the template url, * an jQuery/Angualr element, or a promise that returns the template contents to use. * @returns {object} a promise resolving to template contents * * @example <pre> GridUtil.getTemplate(url).then(function (contents) { alert(contents); }) </pre> */ getTemplate: function (template) { // Try to fetch the template out of the templateCache if ($templateCache.get(template)) { return s.postProcessTemplate($templateCache.get(template)); } // See if the template is itself a promise if (template.hasOwnProperty('then')) { return template.then(s.postProcessTemplate); } // If the template is an element, return the element try { if (angular.element(template).length > 0) { return $q.when(template).then(s.postProcessTemplate); } } catch (err){ //do nothing; not valid html } s.logDebug('fetching url', template); // Default to trying to fetch the template as a url with $http return $http({ method: 'GET', url: template}) .then( function (result) { var templateHtml = result.data.trim(); //put in templateCache for next call $templateCache.put(template, templateHtml); return templateHtml; }, function (err) { throw new Error("Could not get template " + template + ": " + err); } ) .then(s.postProcessTemplate); }, // postProcessTemplate: function (template) { var startSym = $interpolate.startSymbol(), endSym = $interpolate.endSymbol(); // If either of the interpolation symbols have been changed, we need to alter this template if (startSym !== '{{' || endSym !== '}}') { template = template.replace(/\{\{/g, startSym); template = template.replace(/\}\}/g, endSym); } return $q.when(template); }, /** * @ngdoc method * @name guessType * @methodOf ui.grid.service:GridUtil * @description guesses the type of an argument * * @param {string/number/bool/object} item variable to examine * @returns {string} one of the following * - 'string' * - 'boolean' * - 'number' * - 'date' * - 'object' */ guessType : function (item) { var itemType = typeof(item); // Check for numbers and booleans switch (itemType) { case "number": case "boolean": case "string": return itemType; default: if (angular.isDate(item)) { return "date"; } return "object"; } }, /** * @ngdoc method * @name elementWidth * @methodOf ui.grid.service:GridUtil * * @param {element} element DOM element * @param {string} [extra] Optional modifier for calculation. Use 'margin' to account for margins on element * * @returns {number} Element width in pixels, accounting for any borders, etc. */ elementWidth: function (elem) { }, /** * @ngdoc method * @name elementHeight * @methodOf ui.grid.service:GridUtil * * @param {element} element DOM element * @param {string} [extra] Optional modifier for calculation. Use 'margin' to account for margins on element * * @returns {number} Element height in pixels, accounting for any borders, etc. */ elementHeight: function (elem) { }, // Thanks to http://stackoverflow.com/a/13382873/888165 getScrollbarWidth: function() { var outer = document.createElement("div"); outer.style.visibility = "hidden"; outer.style.width = "100px"; outer.style.msOverflowStyle = "scrollbar"; // needed for WinJS apps document.body.appendChild(outer); var widthNoScroll = outer.offsetWidth; // force scrollbars outer.style.overflow = "scroll"; // add innerdiv var inner = document.createElement("div"); inner.style.width = "100%"; outer.appendChild(inner); var widthWithScroll = inner.offsetWidth; // remove divs outer.parentNode.removeChild(outer); return widthNoScroll - widthWithScroll; }, swap: function( elem, options, callback, args ) { var ret, name, old = {}; // Remember the old values, and insert the new ones for ( name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } ret = callback.apply( elem, args || [] ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } return ret; }, fakeElement: function( elem, options, callback, args ) { var ret, name, newElement = angular.element(elem).clone()[0]; for ( name in options ) { newElement.style[ name ] = options[ name ]; } angular.element(document.body).append(newElement); ret = callback.call( newElement, newElement ); angular.element(newElement).remove(); return ret; }, /** * @ngdoc method * @name normalizeWheelEvent * @methodOf ui.grid.service:GridUtil * * @param {event} event A mouse wheel event * * @returns {event} A normalized event * * @description * Given an event from this list: * * `wheel, mousewheel, DomMouseScroll, MozMousePixelScroll` * * "normalize" it * so that it stays consistent no matter what browser it comes from (i.e. scale it correctly and make sure the direction is right.) */ normalizeWheelEvent: function (event) { // var toFix = ['wheel', 'mousewheel', 'DOMMouseScroll', 'MozMousePixelScroll']; // var toBind = 'onwheel' in document || document.documentMode >= 9 ? ['wheel'] : ['mousewheel', 'DomMouseScroll', 'MozMousePixelScroll']; var lowestDelta, lowestDeltaXY; var orgEvent = event || window.event, args = [].slice.call(arguments, 1), delta = 0, deltaX = 0, deltaY = 0, absDelta = 0, absDeltaXY = 0, fn; // event = $.event.fix(orgEvent); // event.type = 'mousewheel'; // NOTE: jQuery masks the event and stores it in the event as originalEvent if (orgEvent.originalEvent) { orgEvent = orgEvent.originalEvent; } // Old school scrollwheel delta if ( orgEvent.wheelDelta ) { delta = orgEvent.wheelDelta; } if ( orgEvent.detail ) { delta = orgEvent.detail * -1; } // At a minimum, setup the deltaY to be delta deltaY = delta; // Firefox < 17 related to DOMMouseScroll event if ( orgEvent.axis !== undefined && orgEvent.axis === orgEvent.HORIZONTAL_AXIS ) { deltaY = 0; deltaX = delta * -1; } // New school wheel delta (wheel event) if ( orgEvent.deltaY ) { deltaY = orgEvent.deltaY * -1; delta = deltaY; } if ( orgEvent.deltaX ) { deltaX = orgEvent.deltaX; delta = deltaX * -1; } // Webkit if ( orgEvent.wheelDeltaY !== undefined ) { deltaY = orgEvent.wheelDeltaY; } if ( orgEvent.wheelDeltaX !== undefined ) { deltaX = orgEvent.wheelDeltaX; } // Look for lowest delta to normalize the delta values absDelta = Math.abs(delta); if ( !lowestDelta || absDelta < lowestDelta ) { lowestDelta = absDelta; } absDeltaXY = Math.max(Math.abs(deltaY), Math.abs(deltaX)); if ( !lowestDeltaXY || absDeltaXY < lowestDeltaXY ) { lowestDeltaXY = absDeltaXY; } // Get a whole value for the deltas fn = delta > 0 ? 'floor' : 'ceil'; delta = Math[fn](delta / lowestDelta); deltaX = Math[fn](deltaX / lowestDeltaXY); deltaY = Math[fn](deltaY / lowestDeltaXY); return { delta: delta, deltaX: deltaX, deltaY: deltaY }; }, // Stolen from Modernizr // TODO: make this, and everythign that flows from it, robust //http://www.stucox.com/blog/you-cant-detect-a-touchscreen/ isTouchEnabled: function() { var bool; if (('ontouchstart' in $window) || $window.DocumentTouch && $document instanceof DocumentTouch) { bool = true; } return bool; }, isNullOrUndefined: function(obj) { if (obj === undefined || obj === null) { return true; } return false; }, endsWith: function(str, suffix) { if (!str || !suffix || typeof str !== "string") { return false; } return str.indexOf(suffix, str.length - suffix.length) !== -1; }, arrayContainsObjectWithProperty: function(array, propertyName, propertyValue) { var found = false; angular.forEach(array, function (object) { if (object[propertyName] === propertyValue) { found = true; } }); return found; }, //// Shim requestAnimationFrame //requestAnimationFrame: $window.requestAnimationFrame && $window.requestAnimationFrame.bind($window) || // $window.webkitRequestAnimationFrame && $window.webkitRequestAnimationFrame.bind($window) || // function(fn) { // return $timeout(fn, 10, false); // }, numericAndNullSort: function (a, b) { if (a === null) { return 1; } if (b === null) { return -1; } if (a === null && b === null) { return 0; } return a - b; }, // Disable ngAnimate animations on an element disableAnimations: function (element) { var $animate; try { $animate = $injector.get('$animate'); // See: http://brianhann.com/angular-1-4-breaking-changes-to-be-aware-of/#animate if (angular.version.major > 1 || (angular.version.major === 1 && angular.version.minor >= 4)) { $animate.enabled(element, false); } else { $animate.enabled(false, element); } } catch (e) {} }, enableAnimations: function (element) { var $animate; try { $animate = $injector.get('$animate'); // See: http://brianhann.com/angular-1-4-breaking-changes-to-be-aware-of/#animate if (angular.version.major > 1 || (angular.version.major === 1 && angular.version.minor >= 4)) { $animate.enabled(element, true); } else { $animate.enabled(true, element); } return $animate; } catch (e) {} }, // Blatantly stolen from Angular as it isn't exposed (yet. 2.0 maybe?) nextUid: function nextUid() { var index = uid.length; var digit; while (index) { index--; digit = uid[index].charCodeAt(0); if (digit === 57 /*'9'*/) { uid[index] = 'A'; return uidPrefix + uid.join(''); } if (digit === 90 /*'Z'*/) { uid[index] = '0'; } else { uid[index] = String.fromCharCode(digit + 1); return uidPrefix + uid.join(''); } } uid.unshift('0'); return uidPrefix + uid.join(''); }, // Blatantly stolen from Angular as it isn't exposed (yet. 2.0 maybe?) hashKey: 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 (typeof(obj.$$hashKey) !== 'undefined' && obj.$$hashKey) { key = obj.$$hashKey; } else if (key === undefined) { key = obj.$$hashKey = s.nextUid(); } } else { key = obj; } return objType + ':' + key; }, resetUids: function () { uid = ['0', '0', '0']; }, /** * @ngdoc method * @methodOf ui.grid.service:GridUtil * @name logError * @description wraps the $log method, allowing us to choose different * treatment within ui-grid if we so desired. At present we only log * error messages if uiGridConstants.LOG_ERROR_MESSAGES is set to true * @param {string} logMessage message to be logged to the console * */ logError: function( logMessage ){ if ( uiGridConstants.LOG_ERROR_MESSAGES ){ $log.error( logMessage ); } }, /** * @ngdoc method * @methodOf ui.grid.service:GridUtil * @name logWarn * @description wraps the $log method, allowing us to choose different * treatment within ui-grid if we so desired. At present we only log * warning messages if uiGridConstants.LOG_WARN_MESSAGES is set to true * @param {string} logMessage message to be logged to the console * */ logWarn: function( logMessage ){ if ( uiGridConstants.LOG_WARN_MESSAGES ){ $log.warn( logMessage ); } }, /** * @ngdoc method * @methodOf ui.grid.service:GridUtil * @name logDebug * @description wraps the $log method, allowing us to choose different * treatment within ui-grid if we so desired. At present we only log * debug messages if uiGridConstants.LOG_DEBUG_MESSAGES is set to true * */ logDebug: function() { if ( uiGridConstants.LOG_DEBUG_MESSAGES ){ $log.debug.apply($log, arguments); } } }; /** * @ngdoc object * @name focus * @propertyOf ui.grid.service:GridUtil * @description Provies a set of methods to set the document focus inside the grid. * See {@link ui.grid.service:GridUtil.focus} for more information. */ /** * @ngdoc object * @name ui.grid.service:GridUtil.focus * @description Provies a set of methods to set the document focus inside the grid. * Timeouts are utilized to ensure that the focus is invoked after any other event has been triggered. * e.g. click events that need to run before the focus or * inputs elements that are in a disabled state but are enabled when those events * are triggered. */ s.focus = { queue: [], //http://stackoverflow.com/questions/25596399/set-element-focus-in-angular-way /** * @ngdoc method * @methodOf ui.grid.service:GridUtil.focus * @name byId * @description Sets the focus of the document to the given id value. * If provided with the grid object it will automatically append the grid id. * This is done to encourage unique dom id's as it allows for multiple grids on a * page. * @param {String} id the id of the dom element to set the focus on * @param {Object=} Grid the grid object for this grid instance. See: {@link ui.grid.class:Grid} * @param {Number} Grid.id the unique id for this grid. Already set on an initialized grid object. * @returns {Promise} The `$timeout` promise that will be resolved once focus is set. If another focus is requested before this request is evaluated. * then the promise will fail with the `'canceled'` reason. */ byId: function (id, Grid) { this._purgeQueue(); var promise = $timeout(function() { var elementID = (Grid && Grid.id ? Grid.id + '-' : '') + id; var element = $window.document.getElementById(elementID); if (element) { element.focus(); } else { s.logWarn('[focus.byId] Element id ' + elementID + ' was not found.'); } }); this.queue.push(promise); return promise; }, /** * @ngdoc method * @methodOf ui.grid.service:GridUtil.focus * @name byElement * @description Sets the focus of the document to the given dom element. * @param {(element|angular.element)} element the DOM element to set the focus on * @returns {Promise} The `$timeout` promise that will be resolved once focus is set. If another focus is requested before this request is evaluated. * then the promise will fail with the `'canceled'` reason. */ byElement: function(element){ if (!angular.isElement(element)){ s.logWarn("Trying to focus on an element that isn\'t an element."); return $q.reject('not-element'); } element = angular.element(element); this._purgeQueue(); var promise = $timeout(function(){ if (element){ element[0].focus(); } }); this.queue.push(promise); return promise; }, /** * @ngdoc method * @methodOf ui.grid.service:GridUtil.focus * @name bySelector * @description Sets the focus of the document to the given dom element. * @param {(element|angular.element)} parentElement the parent/ancestor of the dom element that you are selecting using the query selector * @param {String} querySelector finds the dom element using the {@link http://www.w3schools.com/jsref/met_document_queryselector.asp querySelector} * @param {boolean} [aSync=false] If true then the selector will be querried inside of a timeout. Otherwise the selector will be querried imidately * then the focus will be called. * @returns {Promise} The `$timeout` promise that will be resolved once focus is set. If another focus is requested before this request is evaluated. * then the promise will fail with the `'canceled'` reason. */ bySelector: function(parentElement, querySelector, aSync){ var self = this; if (!angular.isElement(parentElement)){ throw new Error("The parent element is not an element."); } // Ensure that this is an angular element. // It is fine if this is already an angular element. parentElement = angular.element(parentElement); var focusBySelector = function(){ var element = parentElement[0].querySelector(querySelector); return self.byElement(element); }; this._purgeQueue(); if (aSync){ //Do this asynchronysly var promise = $timeout(focusBySelector); this.queue.push($timeout(focusBySelector)); return promise; } else { return focusBySelector(); } }, _purgeQueue: function(){ this.queue.forEach(function(element){ $timeout.cancel(element); }); this.queue = []; } }; ['width', 'height'].forEach(function (name) { var capsName = angular.uppercase(name.charAt(0)) + name.substr(1); s['element' + capsName] = function (elem, extra) { var e = elem; if (e && typeof(e.length) !== 'undefined' && e.length) { e = elem[0]; } if (e) { var styles = getStyles(e); return e.offsetWidth === 0 && rdisplayswap.test(styles.display) ? s.swap(e, cssShow, function() { return getWidthOrHeight(e, name, extra ); }) : getWidthOrHeight( e, name, extra ); } else { return null; } }; s['outerElement' + capsName] = function (elem, margin) { return elem ? s['element' + capsName].call(this, elem, margin ? 'margin' : 'border') : null; }; }); // http://stackoverflow.com/a/24107550/888165 s.closestElm = function closestElm(el, selector) { if (typeof(el.length) !== 'undefined' && el.length) { el = el[0]; } var matchesFn; // find vendor prefix ['matches','webkitMatchesSelector','mozMatchesSelector','msMatchesSelector','oMatchesSelector'].some(function(fn) { if (typeof document.body[fn] === 'function') { matchesFn = fn; return true; } return false; }); // traverse parents var parent; while (el !== null) { parent = el.parentElement; if (parent !== null && parent[matchesFn](selector)) { return parent; } el = parent; } return null; }; s.type = function (obj) { var text = Function.prototype.toString.call(obj.constructor); return text.match(/function (.*?)\(/)[1]; }; s.getBorderSize = function getBorderSize(elem, borderType) { if (typeof(elem.length) !== 'undefined' && elem.length) { elem = elem[0]; } var styles = getStyles(elem); // If a specific border is supplied, like 'top', read the 'borderTop' style property if (borderType) { borderType = 'border' + borderType.charAt(0).toUpperCase() + borderType.slice(1); } else { borderType = 'border'; } borderType += 'Width'; var val = parseInt(styles[borderType], 10); if (isNaN(val)) { return 0; } else { return val; } }; // http://stackoverflow.com/a/22948274/888165 // TODO: Opera? Mobile? s.detectBrowser = function detectBrowser() { var userAgent = $window.navigator.userAgent; var browsers = {chrome: /chrome/i, safari: /safari/i, firefox: /firefox/i, ie: /internet explorer|trident\//i}; for (var key in browsers) { if (browsers[key].test(userAgent)) { return key; } } return 'unknown'; }; // Borrowed from https://github.com/othree/jquery.rtl-scroll-type // Determine the scroll "type" this browser is using for RTL s.rtlScrollType = function rtlScrollType() { if (rtlScrollType.type) { return rtlScrollType.type; } var definer = angular.element('<div dir="rtl" style="font-size: 14px; width: 1px; height: 1px; position: absolute; top: -1000px; overflow: scroll">A</div>')[0], type = 'reverse'; document.body.appendChild(definer); if (definer.scrollLeft > 0) { type = 'default'; } else { definer.scrollLeft = 1; if (definer.scrollLeft === 0) { type = 'negative'; } } angular.element(definer).remove(); rtlScrollType.type = type; return type; }; /** * @ngdoc method * @name normalizeScrollLeft * @methodOf ui.grid.service:GridUtil * * @param {element} element The element to get the `scrollLeft` from. * @param {grid} grid - grid used to normalize (uses the rtl property) * * @returns {number} A normalized scrollLeft value for the current browser. * * @description * Browsers currently handle RTL in different ways, resulting in inconsistent scrollLeft values. This method normalizes them */ s.normalizeScrollLeft = function normalizeScrollLeft(element, grid) { if (typeof(element.length) !== 'undefined' && element.length) { element = element[0]; } var scrollLeft = element.scrollLeft; if (grid.isRTL()) { switch (s.rtlScrollType()) { case 'default': return element.scrollWidth - scrollLeft - element.clientWidth; case 'negative': return Math.abs(scrollLeft); case 'reverse': return scrollLeft; } } return scrollLeft; }; /** * @ngdoc method * @name denormalizeScrollLeft * @methodOf ui.grid.service:GridUtil * * @param {element} element The element to normalize the `scrollLeft` value for * @param {number} scrollLeft The `scrollLeft` value to denormalize. * @param {grid} grid The grid that owns the scroll event. * * @returns {number} A normalized scrollLeft value for the current browser. * * @description * Browsers currently handle RTL in different ways, resulting in inconsistent scrollLeft values. This method denormalizes a value for the current browser. */ s.denormalizeScrollLeft = function denormalizeScrollLeft(element, scrollLeft, grid) { if (typeof(element.length) !== 'undefined' && element.length) { element = element[0]; } if (grid.isRTL()) { switch (s.rtlScrollType()) { case 'default': // Get the max scroll for the element var maxScrollLeft = element.scrollWidth - element.clientWidth; // Subtract the current scroll amount from the max scroll return maxScrollLeft - scrollLeft; case 'negative': return scrollLeft * -1; case 'reverse': return scrollLeft; } } return scrollLeft; }; /** * @ngdoc method * @name preEval * @methodOf ui.grid.service:GridUtil * * @param {string} path Path to evaluate * * @returns {string} A path that is normalized. * * @description * Takes a field path and converts it to bracket notation to allow for special characters in path * @example * <pre> * gridUtil.preEval('property') == 'property' * gridUtil.preEval('nested.deep.prop-erty') = "nested['deep']['prop-erty']" * </pre> */ s.preEval = function (path) { var m = uiGridConstants.BRACKET_REGEXP.exec(path); if (m) { return (m[1] ? s.preEval(m[1]) : m[1]) + m[2] + (m[3] ? s.preEval(m[3]) : m[3]); } else { path = path.replace(uiGridConstants.APOS_REGEXP, '\\\''); var parts = path.split(uiGridConstants.DOT_REGEXP); var preparsed = [parts.shift()]; // first item must be var notation, thus skip angular.forEach(parts, function (part) { preparsed.push(part.replace(uiGridConstants.FUNC_REGEXP, '\']$1')); }); return preparsed.join('[\''); } }; /** * @ngdoc method * @name debounce * @methodOf ui.grid.service:GridUtil * * @param {function} func function to debounce * @param {number} wait milliseconds to delay * @param {boolean} immediate execute before delay * * @returns {function} A function that can be executed as debounced function * * @description * Copied from https://github.com/shahata/angular-debounce * Takes a function, decorates it to execute only 1 time after multiple calls, and returns the decorated function * @example * <pre> * var debouncedFunc = gridUtil.debounce(function(){alert('debounced');}, 500); * debouncedFunc(); * debouncedFunc(); * debouncedFunc(); * </pre> */ s.debounce = function (func, wait, immediate) { var timeout, args, context, result; function debounce() { /* jshint validthis:true */ context = this; args = arguments; var later = function () { timeout = null; if (!immediate) { result = func.apply(context, args); } }; var callNow = immediate && !timeout; if (timeout) { $timeout.cancel(timeout); } timeout = $timeout(later, wait); if (callNow) { result = func.apply(context, args); } return result; } debounce.cancel = function () { $timeout.cancel(timeout); timeout = null; }; return debounce; }; /** * @ngdoc method * @name throttle * @methodOf ui.grid.service:GridUtil * * @param {function} func function to throttle * @param {number} wait milliseconds to delay after first trigger * @param {Object} params to use in throttle. * * @returns {function} A function that can be executed as throttled function * * @description * Adapted from debounce function (above) * Potential keys for Params Object are: * trailing (bool) - whether to trigger after throttle time ends if called multiple times * Updated to use $interval rather than $timeout, as protractor (e2e tests) is able to work with $interval, * but not with $timeout * * Note that when using throttle, you need to use throttle to create a new function upfront, then use the function * return from that call each time you need to call throttle. If you call throttle itself repeatedly, the lastCall * variable will get overwritten and the throttling won't work * * @example * <pre> * var throttledFunc = gridUtil.throttle(function(){console.log('throttled');}, 500, {trailing: true}); * throttledFunc(); //=> logs throttled * throttledFunc(); //=> queues attempt to log throttled for ~500ms (since trailing param is truthy) * throttledFunc(); //=> updates arguments to keep most-recent request, but does not do anything else. * </pre> */ s.throttle = function(func, wait, options){ options = options || {}; var lastCall = 0, queued = null, context, args; function runFunc(endDate){ lastCall = +new Date(); func.apply(context, args); $interval(function(){ queued = null; }, 0, 1); } return function(){ /* jshint validthis:true */ context = this; args = arguments; if (queued === null){ var sinceLast = +new Date() - lastCall; if (sinceLast > wait){ runFunc(); } else if (options.trailing){ queued = $interval(runFunc, wait - sinceLast, 1); } } }; }; s.on = {}; s.off = {}; s._events = {}; s.addOff = function (eventName) { s.off[eventName] = function (elm, fn) { var idx = s._events[eventName].indexOf(fn); if (idx > 0) { s._events[eventName].removeAt(idx); } }; }; var mouseWheeltoBind = ( 'onwheel' in document || document.documentMode >= 9 ) ? ['wheel'] : ['mousewheel', 'DomMouseScroll', 'MozMousePixelScroll'], nullLowestDeltaTimeout, lowestDelta; s.on.mousewheel = function (elm, fn) { if (!elm || !fn) { return; } var $elm = angular.element(elm); // Store the line height and page height for this particular element $elm.data('mousewheel-line-height', getLineHeight($elm)); $elm.data('mousewheel-page-height', s.elementHeight($elm)); if (!$elm.data('mousewheel-callbacks')) { $elm.data('mousewheel-callbacks', {}); } var cbs = $elm.data('mousewheel-callbacks'); cbs[fn] = (Function.prototype.bind || bindPolyfill).call(mousewheelHandler, $elm[0], fn); // Bind all the mousew heel events for ( var i = mouseWheeltoBind.length; i; ) { $elm.on(mouseWheeltoBind[--i], cbs[fn]); } }; s.off.mousewheel = function (elm, fn) { var $elm = angular.element(elm); var cbs = $elm.data('mousewheel-callbacks'); var handler = cbs[fn]; if (handler) { for ( var i = mouseWheeltoBind.length; i; ) { $elm.off(mouseWheeltoBind[--i], handler); } } delete cbs[fn]; if (Object.keys(cbs).length === 0) { $elm.removeData('mousewheel-line-height'); $elm.removeData('mousewheel-page-height'); $elm.removeData('mousewheel-callbacks'); } }; function mousewheelHandler(fn, event) { var $elm = angular.element(this); var delta = 0, deltaX = 0, deltaY = 0, absDelta = 0, offsetX = 0, offsetY = 0; // jQuery masks events if (event.originalEvent) { event = event.originalEvent; } if ( 'detail' in event ) { deltaY = event.detail * -1; } if ( 'wheelDelta' in event ) { deltaY = event.wheelDelta; } if ( 'wheelDeltaY' in event ) { deltaY = event.wheelDeltaY; } if ( 'wheelDeltaX' in event ) { deltaX = event.wheelDeltaX * -1; } // Firefox < 17 horizontal scrolling related to DOMMouseScroll event if ( 'axis' in event && event.axis === event.HORIZONTAL_AXIS ) { deltaX = deltaY * -1; deltaY = 0; } // Set delta to be deltaY or deltaX if deltaY is 0 for backwards compatabilitiy delta = deltaY === 0 ? deltaX : deltaY; // New school wheel delta (wheel event) if ( 'deltaY' in event ) { deltaY = event.deltaY * -1; delta = deltaY; } if ( 'deltaX' in event ) { deltaX = event.deltaX; if ( deltaY === 0 ) { delta = deltaX * -1; } } // No change actually happened, no reason to go any further if ( deltaY === 0 && deltaX === 0 ) { return; } // Need to convert lines and pages to pixels if we aren't already in pixels // There are three delta modes: // * deltaMode 0 is by pixels, nothing to do // * deltaMode 1 is by lines // * deltaMode 2 is by pages if ( event.deltaMode === 1 ) { var lineHeight = $elm.data('mousewheel-line-height'); delta *= lineHeight; deltaY *= lineHeight; deltaX *= lineHeight; } else if ( event.deltaMode === 2 ) { var pageHeight = $elm.data('mousewheel-page-height'); delta *= pageHeight; deltaY *= pageHeight; deltaX *= pageHeight; } // Store lowest absolute delta to normalize the delta values absDelta = Math.max( Math.abs(deltaY), Math.abs(deltaX) ); if ( !lowestDelta || absDelta < lowestDelta ) { lowestDelta = absDelta; // Adjust older deltas if necessary if ( shouldAdjustOldDeltas(event, absDelta) ) { lowestDelta /= 40; } } // Get a whole, normalized value for the deltas delta = Math[ delta >= 1 ? 'floor' : 'ceil' ](delta / lowestDelta); deltaX = Math[ deltaX >= 1 ? 'floor' : 'ceil' ](deltaX / lowestDelta); deltaY = Math[ deltaY >= 1 ? 'floor' : 'ceil' ](deltaY / lowestDelta); event.deltaMode = 0; // Normalise offsetX and offsetY properties // if ($elm[0].getBoundingClientRect ) { // var boundingRect = $(elm)[0].getBoundingClientRect(); // offsetX = event.clientX - boundingRect.left; // offsetY = event.clientY - boundingRect.top; // } // event.deltaX = deltaX; // event.deltaY = deltaY; // event.deltaFactor = lowestDelta; var newEvent = { originalEvent: event, deltaX: deltaX, deltaY: deltaY, deltaFactor: lowestDelta, preventDefault: function () { event.preventDefault(); }, stopPropagation: function () { event.stopPropagation(); } }; // Clearout lowestDelta after sometime to better // handle multiple device types that give // a different lowestDelta // Ex: trackpad = 3 and mouse wheel = 120 if (nullLowestDeltaTimeout) { clearTimeout(nullLowestDeltaTimeout); } nullLowestDeltaTimeout = setTimeout(nullLowestDelta, 200); fn.call($elm[0], newEvent); } function nullLowestDelta() { lowestDelta = null; } function shouldAdjustOldDeltas(orgEvent, absDelta) { // If this is an older event and the delta is divisable by 120, // then we are assuming that the browser is treating this as an // older mouse wheel event and that we should divide the deltas // by 40 to try and get a more usable deltaFactor. // Side note, this actually impacts the reported scroll distance // in older browsers and can cause scrolling to be slower than native. // Turn this off by setting $.event.special.mousewheel.settings.adjustOldDeltas to false. return orgEvent.type === 'mousewheel' && absDelta % 120 === 0; } return s; }]); // Add 'px' to the end of a number string if it doesn't have it already module.filter('px', function() { return function(str) { if (str.match(/^[\d\.]+$/)) { return str + 'px'; } else { return str; } }; }); })(); (function () { angular.module('ui.grid').config(['$provide', function($provide) { $provide.decorator('i18nService', ['$delegate', function($delegate) { var lang = { aggregate: { label: 'položky' }, groupPanel: { description: 'Přesuntě záhlaví zde pro vytvoření skupiny dle sloupce.' }, search: { placeholder: 'Hledat...', showingItems: 'Zobrazuji položky:', selectedItems: 'Vybrané položky:', totalItems: 'Celkem položek:', size: 'Velikost strany:', first: 'První strana', next: 'Další strana', previous: 'Předchozí strana', last: 'Poslední strana' }, menu: { text: 'Vyberte sloupec:' }, sort: { ascending: 'Seřadit od A-Z', descending: 'Seřadit od Z-A', remove: 'Odebrat seřazení' }, column: { hide: 'Schovat sloupec' }, aggregation: { count: 'celkem řádků: ', sum: 'celkem: ', avg: 'avg: ', min: 'min.: ', max: 'max.: ' }, pinning: { pinLeft: 'Zamknout v levo', pinRight: 'Zamknout v pravo', unpin: 'Odemknout' }, gridMenu: { columns: 'Sloupce:', importerTitle: 'Importovat soubor', exporterAllAsCsv: 'Exportovat všechny data do csv', exporterVisibleAsCsv: 'Exportovat viditelné data do csv', exporterSelectedAsCsv: 'Exportovat vybranné data do csv', exporterAllAsPdf: 'Exportovat všechny data do pdf', exporterVisibleAsPdf: 'Exportovat viditelné data do pdf', exporterSelectedAsPdf: 'Exportovat vybranné data do pdf', clearAllFilters: 'Vyčistěte všechny filtry' }, importer: { noHeaders: 'Názvy sloupců se nepodařilo získat, obsahuje soubor záhlaví?', noObjects: 'Data se nepodařilo zpracovat, obsahuje soubor řádky mimo záhlaví?', invalidCsv: 'Soubor nelze zpracovat, jedná se CSV?', invalidJson: 'Soubor nelze zpracovat, je to JSON?', jsonNotArray: 'Soubor musí obsahovat json. Ukončuji..' }, pagination: { sizes: 'položek na stránku', totalItems: 'položek' }, grouping: { group: 'Seskupit', ungroup: 'Odebrat seskupení', aggregate_count: 'Agregace: Count', aggregate_sum: 'Agregace: Sum', aggregate_max: 'Agregace: Max', aggregate_min: 'Agregace: Min', aggregate_avg: 'Agregace: Avg', aggregate_remove: 'Agregace: Odebrat' } }; // support varianty of different czech keys. $delegate.add('cs', lang); $delegate.add('cz', lang); $delegate.add('cs-cz', lang); $delegate.add('cs-CZ', lang); return $delegate; }]); }]); })(); (function(){ angular.module('ui.grid').config(['$provide', function($provide) { $provide.decorator('i18nService', ['$delegate', function($delegate) { $delegate.add('da', { aggregate:{ label: 'artikler' }, groupPanel:{ description: 'Grupér rækker udfra en kolonne ved at trække dens overskift hertil.' }, search:{ placeholder: 'Søg...', showingItems: 'Viste rækker:', selectedItems: 'Valgte rækker:', totalItems: 'Rækker totalt:', size: 'Side størrelse:', first: 'Første side', next: 'Næste side', previous: 'Forrige side', last: 'Sidste side' }, menu:{ text: 'Vælg kolonner:' }, column: { hide: 'Skjul kolonne' }, aggregation: { count: 'samlede rækker: ', sum: 'smalede: ', avg: 'gns: ', min: 'min: ', max: 'max: ' }, gridMenu: { columns: 'Columns:', importerTitle: 'Import file', exporterAllAsCsv: 'Export all data as csv', exporterVisibleAsCsv: 'Export visible data as csv', exporterSelectedAsCsv: 'Export selected data as csv', exporterAllAsPdf: 'Export all data as pdf', exporterVisibleAsPdf: 'Export visible data as pdf', exporterSelectedAsPdf: 'Export selected data as pdf', clearAllFilters: 'Clear all filters' }, importer: { noHeaders: 'Column names were unable to be derived, does the file have a header?', noObjects: 'Objects were not able to be derived, was there data in the file other than headers?', invalidCsv: 'File was unable to be processed, is it valid CSV?', invalidJson: 'File was unable to be processed, is it valid Json?', jsonNotArray: 'Imported json file must contain an array, aborting.' } }); return $delegate; }]); }]); })(); (function () { angular.module('ui.grid').config(['$provide', function ($provide) { $provide.decorator('i18nService', ['$delegate', function ($delegate) { $delegate.add('de', { aggregate: { label: 'Eintrag' }, groupPanel: { description: 'Ziehen Sie eine Spaltenüberschrift hierhin, um nach dieser Spalte zu gruppieren.' }, search: { placeholder: 'Suche...', showingItems: 'Zeige Einträge:', selectedItems: 'Ausgewählte Einträge:', totalItems: 'Einträge gesamt:', size: 'Einträge pro Seite:', first: 'Erste Seite', next: 'Nächste Seite', previous: 'Vorherige Seite', last: 'Letzte Seite' }, menu: { text: 'Spalten auswählen:' }, sort: { ascending: 'aufsteigend sortieren', descending: 'absteigend sortieren', remove: 'Sortierung zurücksetzen' }, column: { hide: 'Spalte ausblenden' }, aggregation: { count: 'Zeilen insgesamt: ', sum: 'gesamt: ', avg: 'Durchschnitt: ', min: 'min: ', max: 'max: ' }, pinning: { pinLeft: 'Links anheften', pinRight: 'Rechts anheften', unpin: 'Lösen' }, gridMenu: { columns: 'Spalten:', importerTitle: 'Datei importieren', exporterAllAsCsv: 'Alle Daten als CSV exportieren', exporterVisibleAsCsv: 'sichtbare Daten als CSV exportieren', exporterSelectedAsCsv: 'markierte Daten als CSV exportieren', exporterAllAsPdf: 'Alle Daten als PDF exportieren', exporterVisibleAsPdf: 'sichtbare Daten als PDF exportieren', exporterSelectedAsPdf: 'markierte Daten als CSV exportieren', clearAllFilters: 'Alle filter reinigen' }, importer: { noHeaders: 'Es konnten keine Spaltennamen ermittelt werden. Sind in der Datei Spaltendefinitionen enthalten?', noObjects: 'Es konnten keine Zeileninformationen gelesen werden, Sind in der Datei außer den Spaltendefinitionen auch Daten enthalten?', invalidCsv: 'Die Datei konnte nicht eingelesen werden, ist es eine gültige CSV-Datei?', invalidJson: 'Die Datei konnte nicht eingelesen werden. Enthält sie gültiges JSON?', jsonNotArray: 'Die importierte JSON-Datei muß ein Array enthalten. Breche Import ab.' }, pagination: { sizes: 'Einträge pro Seite', totalItems: 'Einträge' }, grouping: { group: 'Gruppieren', ungroup: 'Gruppierung aufheben', aggregate_count: 'Agg: Anzahl', aggregate_sum: 'Agg: Summe', aggregate_max: 'Agg: Maximum', aggregate_min: 'Agg: Minimum', aggregate_avg: 'Agg: Mittelwert', aggregate_remove: 'Aggregation entfernen' } }); return $delegate; }]); }]); })(); (function () { angular.module('ui.grid').config(['$provide', function($provide) { $provide.decorator('i18nService', ['$delegate', function($delegate) { $delegate.add('en', { headerCell: { aria: { defaultFilterLabel: 'Filter for column', removeFilter: 'Remove Filter', columnMenuButtonLabel: 'Column Menu' }, priority: 'Priority:', filterLabel: "Filter for column: " }, aggregate: { label: 'items' }, groupPanel: { description: 'Drag a column header here and drop it to group by that column.' }, search: { placeholder: 'Search...', showingItems: 'Showing Items:', selectedItems: 'Selected Items:', totalItems: 'Total Items:', size: 'Page Size:', first: 'First Page', next: 'Next Page', previous: 'Previous Page', last: 'Last Page' }, menu: { text: 'Choose Columns:' }, sort: { ascending: 'Sort Ascending', descending: 'Sort Descending', none: 'Sort None', remove: 'Remove Sort' }, column: { hide: 'Hide Column' }, aggregation: { count: 'total rows: ', sum: 'total: ', avg: 'avg: ', min: 'min: ', max: 'max: ' }, pinning: { pinLeft: 'Pin Left', pinRight: 'Pin Right', unpin: 'Unpin' }, columnMenu: { close: 'Close' }, gridMenu: { aria: { buttonLabel: 'Grid Menu' }, columns: 'Columns:', importerTitle: 'Import file', exporterAllAsCsv: 'Export all data as csv', exporterVisibleAsCsv: 'Export visible data as csv', exporterSelectedAsCsv: 'Export selected data as csv', exporterAllAsPdf: 'Export all data as pdf', exporterVisibleAsPdf: 'Export visible data as pdf', exporterSelectedAsPdf: 'Export selected data as pdf', clearAllFilters: 'Clear all filters' }, importer: { noHeaders: 'Column names were unable to be derived, does the file have a header?', noObjects: 'Objects were not able to be derived, was there data in the file other than headers?', invalidCsv: 'File was unable to be processed, is it valid CSV?', invalidJson: 'File was unable to be processed, is it valid Json?', jsonNotArray: 'Imported json file must contain an array, aborting.' }, pagination: { aria: { pageToFirst: 'Page to first', pageBack: 'Page back', pageSelected: 'Selected page', pageForward: 'Page forward', pageToLast: 'Page to last' }, sizes: 'items per page', totalItems: 'items', through: 'through', of: 'of' }, grouping: { group: 'Group', ungroup: 'Ungroup', aggregate_count: 'Agg: Count', aggregate_sum: 'Agg: Sum', aggregate_max: 'Agg: Max', aggregate_min: 'Agg: Min', aggregate_avg: 'Agg: Avg', aggregate_remove: 'Agg: Remove' } }); return $delegate; }]); }]); })(); (function () { angular.module('ui.grid').config(['$provide', function($provide) { $provide.decorator('i18nService', ['$delegate', function($delegate) { $delegate.add('es', { aggregate: { label: 'Artículos' }, groupPanel: { description: 'Arrastre un encabezado de columna aquí y suéltelo para agrupar por esa columna.' }, search: { placeholder: 'Buscar...', showingItems: 'Artículos Mostrados:', selectedItems: 'Artículos Seleccionados:', totalItems: 'Artículos Totales:', size: 'Tamaño de Página:', first: 'Primera Página', next: 'Página Siguiente', previous: 'Página Anterior', last: 'Última Página' }, menu: { text: 'Elegir columnas:' }, sort: { ascending: 'Orden Ascendente', descending: 'Orden Descendente', remove: 'Sin Ordenar' }, column: { hide: 'Ocultar la columna' }, aggregation: { count: 'filas totales: ', sum: 'total: ', avg: 'media: ', min: 'min: ', max: 'max: ' }, pinning: { pinLeft: 'Fijar a la Izquierda', pinRight: 'Fijar a la Derecha', unpin: 'Quitar Fijación' }, gridMenu: { columns: 'Columnas:', importerTitle: 'Importar archivo', exporterAllAsCsv: 'Exportar todo como csv', exporterVisibleAsCsv: 'Exportar vista como csv', exporterSelectedAsCsv: 'Exportar selección como csv', exporterAllAsPdf: 'Exportar todo como pdf', exporterVisibleAsPdf: 'Exportar vista como pdf', exporterSelectedAsPdf: 'Exportar selección como pdf', clearAllFilters: 'Limpiar todos los filtros' }, importer: { noHeaders: 'No fue posible derivar los nombres de las columnas, ¿tiene encabezados el archivo?', noObjects: 'No fue posible obtener registros, ¿contiene datos el archivo, aparte de los encabezados?', invalidCsv: 'No fue posible procesar el archivo, ¿es un CSV válido?', invalidJson: 'No fue posible procesar el archivo, ¿es un Json válido?', jsonNotArray: 'El archivo json importado debe contener un array, abortando.' }, pagination: { sizes: 'registros por página', totalItems: 'registros', of: 'de' }, grouping: { group: 'Agrupar', ungroup: 'Desagrupar', aggregate_count: 'Agr: Cont', aggregate_sum: 'Agr: Sum', aggregate_max: 'Agr: Máx', aggregate_min: 'Agr: Min', aggregate_avg: 'Agr: Prom', aggregate_remove: 'Agr: Quitar' } }); return $delegate; }]); }]); })(); /** * Translated by: R. Salarmehr * M. Hosseynzade * Using Vajje.com online dictionary. */ (function () { angular.module('ui.grid').config(['$provide', function ($provide) { $provide.decorator('i18nService', ['$delegate', function ($delegate) { $delegate.add('fa', { aggregate: { label: 'قلم' }, groupPanel: { description: 'عنوان یک ستون را بگیر و به گروهی از آن ستون رها کن.' }, search: { placeholder: 'جستجو...', showingItems: 'نمایش اقلام:', selectedItems: 'قلم\u200cهای انتخاب شده:', totalItems: 'مجموع اقلام:', size: 'اندازه\u200cی صفحه:', first: 'اولین صفحه', next: 'صفحه\u200cی\u200cبعدی', previous: 'صفحه\u200cی\u200c قبلی', last: 'آخرین صفحه' }, menu: { text: 'ستون\u200cهای انتخابی:' }, sort: { ascending: 'ترتیب صعودی', descending: 'ترتیب نزولی', remove: 'حذف مرتب کردن' }, column: { hide: 'پنهان\u200cکردن ستون' }, aggregation: { count: 'تعداد: ', sum: 'مجموع: ', avg: 'میانگین: ', min: 'کمترین: ', max: 'بیشترین: ' }, pinning: { pinLeft: 'پین کردن سمت چپ', pinRight: 'پین کردن سمت راست', unpin: 'حذف پین' }, gridMenu: { columns: 'ستون\u200cها:', importerTitle: 'وارد کردن فایل', exporterAllAsCsv: 'خروجی تمام داده\u200cها در فایل csv', exporterVisibleAsCsv: 'خروجی داده\u200cهای قابل مشاهده در فایل csv', exporterSelectedAsCsv: 'خروجی داده\u200cهای انتخاب\u200cشده در فایل csv', exporterAllAsPdf: 'خروجی تمام داده\u200cها در فایل pdf', exporterVisibleAsPdf: 'خروجی داده\u200cهای قابل مشاهده در فایل pdf', exporterSelectedAsPdf: 'خروجی داده\u200cهای انتخاب\u200cشده در فایل pdf', clearAllFilters: 'پاک کردن تمام فیلتر' }, importer: { noHeaders: 'نام ستون قابل استخراج نیست. آیا فایل عنوان دارد؟', noObjects: 'اشیا قابل استخراج نیستند. آیا به جز عنوان\u200cها در فایل داده وجود دارد؟', invalidCsv: 'فایل قابل پردازش نیست. آیا فرمت csv معتبر است؟', invalidJson: 'فایل قابل پردازش نیست. آیا فرمت json معتبر است؟', jsonNotArray: 'فایل json وارد شده باید حاوی آرایه باشد. عملیات ساقط شد.' }, pagination: { sizes: 'اقلام در هر صفحه', totalItems: 'اقلام', of: 'از' }, grouping: { group: 'گروه\u200cبندی', ungroup: 'حذف گروه\u200cبندی', aggregate_count: 'Agg: تعداد', aggregate_sum: 'Agg: جمع', aggregate_max: 'Agg: بیشینه', aggregate_min: 'Agg: کمینه', aggregate_avg: 'Agg: میانگین', aggregate_remove: 'Agg: حذف' } }); return $delegate; }]); }]); })(); (function () { angular.module('ui.grid').config(['$provide', function($provide) { $provide.decorator('i18nService', ['$delegate', function($delegate) { $delegate.add('fi', { aggregate: { label: 'rivit' }, groupPanel: { description: 'Raahaa ja pudota otsikko tähän ryhmittääksesi sarakkeen mukaan.' }, search: { placeholder: 'Hae...', showingItems: 'Näytetään rivejä:', selectedItems: 'Valitut rivit:', totalItems: 'Rivejä yht.:', size: 'Näytä:', first: 'Ensimmäinen sivu', next: 'Seuraava sivu', previous: 'Edellinen sivu', last: 'Viimeinen sivu' }, menu: { text: 'Valitse sarakkeet:' }, sort: { ascending: 'Järjestä nouseva', descending: 'Järjestä laskeva', remove: 'Poista järjestys' }, column: { hide: 'Piilota sarake' }, aggregation: { count: 'Rivejä yht.: ', sum: 'Summa: ', avg: 'K.a.: ', min: 'Min: ', max: 'Max: ' }, pinning: { pinLeft: 'Lukitse vasemmalle', pinRight: 'Lukitse oikealle', unpin: 'Poista lukitus' }, gridMenu: { columns: 'Sarakkeet:', importerTitle: 'Tuo tiedosto', exporterAllAsCsv: 'Vie tiedot csv-muodossa', exporterVisibleAsCsv: 'Vie näkyvä tieto csv-muodossa', exporterSelectedAsCsv: 'Vie valittu tieto csv-muodossa', exporterAllAsPdf: 'Vie tiedot pdf-muodossa', exporterVisibleAsPdf: 'Vie näkyvä tieto pdf-muodossa', exporterSelectedAsPdf: 'Vie valittu tieto pdf-muodossa', clearAllFilters: 'Puhdista kaikki suodattimet' }, importer: { noHeaders: 'Sarakkeen nimiä ei voitu päätellä, onko tiedostossa otsikkoriviä?', noObjects: 'Tietoja ei voitu lukea, onko tiedostossa muuta kuin otsikkot?', invalidCsv: 'Tiedostoa ei voitu käsitellä, oliko se CSV-muodossa?', invalidJson: 'Tiedostoa ei voitu käsitellä, oliko se JSON-muodossa?', jsonNotArray: 'Tiedosto ei sisältänyt taulukkoa, lopetetaan.' } }); return $delegate; }]); }]); })(); (function () { angular.module('ui.grid').config(['$provide', function($provide) { $provide.decorator('i18nService', ['$delegate', function($delegate) { $delegate.add('fr', { aggregate: { label: 'éléments' }, groupPanel: { description: 'Faites glisser une en-tête de colonne ici pour créer un groupe de colonnes.' }, search: { placeholder: 'Recherche...', showingItems: 'Affichage des éléments :', selectedItems: 'Éléments sélectionnés :', totalItems: 'Nombre total d\'éléments:', size: 'Taille de page:', first: 'Première page', next: 'Page Suivante', previous: 'Page précédente', last: 'Dernière page' }, menu: { text: 'Choisir des colonnes :' }, sort: { ascending: 'Trier par ordre croissant', descending: 'Trier par ordre décroissant', remove: 'Enlever le tri' }, column: { hide: 'Cacher la colonne' }, aggregation: { count: 'lignes totales: ', sum: 'total: ', avg: 'moy: ', min: 'min: ', max: 'max: ' }, pinning: { pinLeft: 'Épingler à gauche', pinRight: 'Épingler à droite', unpin: 'Détacher' }, gridMenu: { columns: 'Colonnes:', importerTitle: 'Importer un fichier', exporterAllAsCsv: 'Exporter toutes les données en CSV', exporterVisibleAsCsv: 'Exporter les données visibles en CSV', exporterSelectedAsCsv: 'Exporter les données sélectionnées en CSV', exporterAllAsPdf: 'Exporter toutes les données en PDF', exporterVisibleAsPdf: 'Exporter les données visibles en PDF', exporterSelectedAsPdf: 'Exporter les données sélectionnées en PDF', clearAllFilters: 'Nettoyez tous les filtres' }, importer: { noHeaders: 'Impossible de déterminer le nom des colonnes, le fichier possède-t-il une en-tête ?', noObjects: 'Aucun objet trouvé, le fichier possède-t-il des données autres que l\'en-tête ?', invalidCsv: 'Le fichier n\'a pas pu être traité, le CSV est-il valide ?', invalidJson: 'Le fichier n\'a pas pu être traité, le JSON est-il valide ?', jsonNotArray: 'Le fichier JSON importé doit contenir un tableau, abandon.' }, pagination: { sizes: 'éléments par page', totalItems: 'éléments', of: 'sur' }, grouping: { group: 'Grouper', ungroup: 'Dégrouper', aggregate_count: 'Agg: Compte', aggregate_sum: 'Agg: Somme', aggregate_max: 'Agg: Max', aggregate_min: 'Agg: Min', aggregate_avg: 'Agg: Moy', aggregate_remove: 'Agg: Retirer' } }); return $delegate; }]); }]); })(); (function () { angular.module('ui.grid').config(['$provide', function ($provide) { $provide.decorator('i18nService', ['$delegate', function ($delegate) { $delegate.add('he', { aggregate: { label: 'items' }, groupPanel: { description: 'גרור עמודה לכאן ושחרר בכדי לקבץ עמודה זו.' }, search: { placeholder: 'חפש...', showingItems: 'מציג:', selectedItems: 'סה"כ נבחרו:', totalItems: 'סה"כ רשומות:', size: 'תוצאות בדף:', first: 'דף ראשון', next: 'דף הבא', previous: 'דף קודם', last: 'דף אחרון' }, menu: { text: 'בחר עמודות:' }, sort: { ascending: 'סדר עולה', descending: 'סדר יורד', remove: 'בטל' }, column: { hide: 'טור הסתר' }, aggregation: { count: 'total rows: ', sum: 'total: ', avg: 'avg: ', min: 'min: ', max: 'max: ' }, gridMenu: { columns: 'Columns:', importerTitle: 'Import file', exporterAllAsCsv: 'Export all data as csv', exporterVisibleAsCsv: 'Export visible data as csv', exporterSelectedAsCsv: 'Export selected data as csv', exporterAllAsPdf: 'Export all data as pdf', exporterVisibleAsPdf: 'Export visible data as pdf', exporterSelectedAsPdf: 'Export selected data as pdf', clearAllFilters: 'Clean all filters' }, importer: { noHeaders: 'Column names were unable to be derived, does the file have a header?', noObjects: 'Objects were not able to be derived, was there data in the file other than headers?', invalidCsv: 'File was unable to be processed, is it valid CSV?', invalidJson: 'File was unable to be processed, is it valid Json?', jsonNotArray: 'Imported json file must contain an array, aborting.' } }); return $delegate; }]); }]); })(); (function () { angular.module('ui.grid').config(['$provide', function($provide) { $provide.decorator('i18nService', ['$delegate', function($delegate) { $delegate.add('hy', { aggregate: { label: 'տվյալներ' }, groupPanel: { description: 'Ըստ սյան խմբավորելու համար քաշեք և գցեք վերնագիրն այստեղ։' }, search: { placeholder: 'Փնտրում...', showingItems: 'Ցուցադրված տվյալներ՝', selectedItems: 'Ընտրված:', totalItems: 'Ընդամենը՝', size: 'Տողերի քանակը էջում՝', first: 'Առաջին էջ', next: 'Հաջորդ էջ', previous: 'Նախորդ էջ', last: 'Վերջին էջ' }, menu: { text: 'Ընտրել սյուները:' }, sort: { ascending: 'Աճման կարգով', descending: 'Նվազման կարգով', remove: 'Հանել ' }, column: { hide: 'Թաքցնել սյունը' }, aggregation: { count: 'ընդամենը տող՝ ', sum: 'ընդամենը՝ ', avg: 'միջին՝ ', min: 'մին՝ ', max: 'մաքս՝ ' }, pinning: { pinLeft: 'Կպցնել ձախ կողմում', pinRight: 'Կպցնել աջ կողմում', unpin: 'Արձակել' }, gridMenu: { columns: 'Սյուներ:', importerTitle: 'Ներմուծել ֆայլ', exporterAllAsCsv: 'Արտահանել ամբողջը CSV', exporterVisibleAsCsv: 'Արտահանել երևացող տվյալները CSV', exporterSelectedAsCsv: 'Արտահանել ընտրված տվյալները CSV', exporterAllAsPdf: 'Արտահանել PDF', exporterVisibleAsPdf: 'Արտահանել երևացող տվյալները PDF', exporterSelectedAsPdf: 'Արտահանել ընտրված տվյալները PDF', clearAllFilters: 'Մաքրել բոլոր ֆիլտրերը' }, importer: { noHeaders: 'Հնարավոր չեղավ որոշել սյան վերնագրերը։ Արդյո՞ք ֆայլը ունի վերնագրեր։', noObjects: 'Հնարավոր չեղավ կարդալ տվյալները։ Արդյո՞ք ֆայլում կան տվյալներ։', invalidCsv: 'Հնարավոր չեղավ մշակել ֆայլը։ Արդյո՞ք այն վավեր CSV է։', invalidJson: 'Հնարավոր չեղավ մշակել ֆայլը։ Արդյո՞ք այն վավեր Json է։', jsonNotArray: 'Ներմուծված json ֆայլը պետք է պարունակի զանգված, կասեցվում է։' } }); return $delegate; }]); }]); })(); (function () { angular.module('ui.grid').config(['$provide', function($provide) { $provide.decorator('i18nService', ['$delegate', function($delegate) { $delegate.add('it', { aggregate: { label: 'elementi' }, groupPanel: { description: 'Trascina un\'intestazione all\'interno del gruppo della colonna.' }, search: { placeholder: 'Ricerca...', showingItems: 'Mostra:', selectedItems: 'Selezionati:', totalItems: 'Totali:', size: 'Tot Pagine:', first: 'Prima', next: 'Prossima', previous: 'Precedente', last: 'Ultima' }, menu: { text: 'Scegli le colonne:' }, sort: { ascending: 'Asc.', descending: 'Desc.', remove: 'Annulla ordinamento' }, column: { hide: 'Nascondi' }, aggregation: { count: 'righe totali: ', sum: 'tot: ', avg: 'media: ', min: 'minimo: ', max: 'massimo: ' }, pinning: { pinLeft: 'Blocca a sx', pinRight: 'Blocca a dx', unpin: 'Blocca in alto' }, gridMenu: { columns: 'Colonne:', importerTitle: 'Importa', exporterAllAsCsv: 'Esporta tutti i dati in CSV', exporterVisibleAsCsv: 'Esporta i dati visibili in CSV', exporterSelectedAsCsv: 'Esporta i dati selezionati in CSV', exporterAllAsPdf: 'Esporta tutti i dati in PDF', exporterVisibleAsPdf: 'Esporta i dati visibili in PDF', exporterSelectedAsPdf: 'Esporta i dati selezionati in PDF', clearAllFilters: 'Pulire tutti i filtri' }, importer: { noHeaders: 'Impossibile reperire i nomi delle colonne, sicuro che siano indicati all\'interno del file?', noObjects: 'Impossibile reperire gli oggetti, sicuro che siano indicati all\'interno del file?', invalidCsv: 'Impossibile elaborare il file, sicuro che sia un CSV?', invalidJson: 'Impossibile elaborare il file, sicuro che sia un JSON valido?', jsonNotArray: 'Errore! Il file JSON da importare deve contenere un array.' }, grouping: { group: 'Raggruppa', ungroup: 'Separa', aggregate_count: 'Agg: N. Elem.', aggregate_sum: 'Agg: Somma', aggregate_max: 'Agg: Massimo', aggregate_min: 'Agg: Minimo', aggregate_avg: 'Agg: Media', aggregate_remove: 'Agg: Rimuovi' } }); return $delegate; }]); }]); })(); (function() { angular.module('ui.grid').config(['$provide', function($provide) { $provide.decorator('i18nService', ['$delegate', function($delegate) { $delegate.add('ja', { aggregate: { label: '項目' }, groupPanel: { description: 'ここに列ヘッダをドラッグアンドドロップして、その列でグループ化します。' }, search: { placeholder: '検索...', showingItems: '表示中の項目:', selectedItems: '選択した項目:', totalItems: '項目の総数:', size: 'ページサイズ:', first: '最初のページ', next: '次のページ', previous: '前のページ', last: '前のページ' }, menu: { text: '列の選択:' }, sort: { ascending: '昇順に並べ替え', descending: '降順に並べ替え', remove: '並べ替えの解除' }, column: { hide: '列の非表示' }, aggregation: { count: '合計行数: ', sum: '合計: ', avg: '平均: ', min: '最小: ', max: '最大: ' }, pinning: { pinLeft: '左に固定', pinRight: '右に固定', unpin: '固定解除' }, gridMenu: { columns: '列:', importerTitle: 'ファイルのインポート', exporterAllAsCsv: 'すべてのデータをCSV形式でエクスポート', exporterVisibleAsCsv: '表示中のデータをCSV形式でエクスポート', exporterSelectedAsCsv: '選択したデータをCSV形式でエクスポート', exporterAllAsPdf: 'すべてのデータをPDF形式でエクスポート', exporterVisibleAsPdf: '表示中のデータをPDF形式でエクスポート', exporterSelectedAsPdf: '選択したデータをPDF形式でエクスポート', clearAllFilters: 'すべてのフィルタを清掃してください' }, importer: { noHeaders: '列名を取得できません。ファイルにヘッダが含まれていることを確認してください。', noObjects: 'オブジェクトを取得できません。ファイルにヘッダ以外のデータが含まれていることを確認してください。', invalidCsv: 'ファイルを処理できません。ファイルが有効なCSV形式であることを確認してください。', invalidJson: 'ファイルを処理できません。ファイルが有効なJSON形式であることを確認してください。', jsonNotArray: 'インポートしたJSONファイルには配列が含まれている必要があります。処理を中止します。' }, pagination: { sizes: '項目/ページ', totalItems: '項目' } }); return $delegate; }]); }]); })(); (function () { angular.module('ui.grid').config(['$provide', function($provide) { $provide.decorator('i18nService', ['$delegate', function($delegate) { $delegate.add('ko', { aggregate: { label: '아이템' }, groupPanel: { description: '컬럼으로 그룹핑하기 위해서는 컬럼 헤더를 끌어 떨어뜨려 주세요.' }, search: { placeholder: '검색...', showingItems: '항목 보여주기:', selectedItems: '선택 항목:', totalItems: '전체 항목:', size: '페이지 크기:', first: '첫번째 페이지', next: '다음 페이지', previous: '이전 페이지', last: '마지막 페이지' }, menu: { text: '컬럼을 선택하세요:' }, sort: { ascending: '오름차순 정렬', descending: '내림차순 정렬', remove: '소팅 제거' }, column: { hide: '컬럼 제거' }, aggregation: { count: '전체 갯수: ', sum: '전체: ', avg: '평균: ', min: '최소: ', max: '최대: ' }, pinning: { pinLeft: '왼쪽 핀', pinRight: '오른쪽 핀', unpin: '핀 제거' }, gridMenu: { columns: '컬럼:', importerTitle: '파일 가져오기', exporterAllAsCsv: 'csv로 모든 데이터 내보내기', exporterVisibleAsCsv: 'csv로 보이는 데이터 내보내기', exporterSelectedAsCsv: 'csv로 선택된 데이터 내보내기', exporterAllAsPdf: 'pdf로 모든 데이터 내보내기', exporterVisibleAsPdf: 'pdf로 보이는 데이터 내보내기', exporterSelectedAsPdf: 'pdf로 선택 데이터 내보내기', clearAllFilters: '모든 필터를 청소' }, importer: { noHeaders: '컬럼명이 지정되어 있지 않습니다. 파일에 헤더가 명시되어 있는지 확인해 주세요.', noObjects: '데이터가 지정되어 있지 않습니다. 데이터가 파일에 있는지 확인해 주세요.', invalidCsv: '파일을 처리할 수 없습니다. 올바른 csv인지 확인해 주세요.', invalidJson: '파일을 처리할 수 없습니다. 올바른 json인지 확인해 주세요.', jsonNotArray: 'json 파일은 배열을 포함해야 합니다.' }, pagination: { sizes: '페이지당 항목', totalItems: '전체 항목' } }); return $delegate; }]); }]); })(); (function () { angular.module('ui.grid').config(['$provide', function($provide) { $provide.decorator('i18nService', ['$delegate', function($delegate) { $delegate.add('nl', { aggregate: { label: 'items' }, groupPanel: { description: 'Sleep hier een kolomnaam heen om op te groeperen.' }, search: { placeholder: 'Zoeken...', showingItems: 'Getoonde items:', selectedItems: 'Geselecteerde items:', totalItems: 'Totaal aantal items:', size: 'Items per pagina:', first: 'Eerste pagina', next: 'Volgende pagina', previous: 'Vorige pagina', last: 'Laatste pagina' }, menu: { text: 'Kies kolommen:' }, sort: { ascending: 'Sorteer oplopend', descending: 'Sorteer aflopend', remove: 'Verwijder sortering' }, column: { hide: 'Verberg kolom' }, aggregation: { count: 'Aantal rijen: ', sum: 'Som: ', avg: 'Gemiddelde: ', min: 'Min: ', max: 'Max: ' }, pinning: { pinLeft: 'Zet links vast', pinRight: 'Zet rechts vast', unpin: 'Maak los' }, gridMenu: { columns: 'Kolommen:', importerTitle: 'Importeer bestand', exporterAllAsCsv: 'Exporteer alle data als csv', exporterVisibleAsCsv: 'Exporteer zichtbare data als csv', exporterSelectedAsCsv: 'Exporteer geselecteerde data als csv', exporterAllAsPdf: 'Exporteer alle data als pdf', exporterVisibleAsPdf: 'Exporteer zichtbare data als pdf', exporterSelectedAsPdf: 'Exporteer geselecteerde data als pdf', clearAllFilters: 'Reinig alle filters' }, importer: { noHeaders: 'Kolomnamen kunnen niet worden afgeleid. Heeft het bestand een header?', noObjects: 'Objecten kunnen niet worden afgeleid. Bevat het bestand data naast de headers?', invalidCsv: 'Het bestand kan niet verwerkt worden. Is het een valide csv bestand?', invalidJson: 'Het bestand kan niet verwerkt worden. Is het valide json?', jsonNotArray: 'Het json bestand moet een array bevatten. De actie wordt geannuleerd.' }, pagination: { sizes: 'items per pagina', totalItems: 'items' }, grouping: { group: 'Groepeer', ungroup: 'Groepering opheffen', aggregate_count: 'Agg: Aantal', aggregate_sum: 'Agg: Som', aggregate_max: 'Agg: Max', aggregate_min: 'Agg: Min', aggregate_avg: 'Agg: Gem', aggregate_remove: 'Agg: Verwijder' } }); return $delegate; }]); }]); })(); (function () { angular.module('ui.grid').config(['$provide', function($provide) { $provide.decorator('i18nService', ['$delegate', function($delegate) { $delegate.add('pt-br', { aggregate: { label: 'itens' }, groupPanel: { description: 'Arraste e solte uma coluna aqui para agrupar por essa coluna' }, search: { placeholder: 'Procurar...', showingItems: 'Mostrando os Itens:', selectedItems: 'Items Selecionados:', totalItems: 'Total de Itens:', size: 'Tamanho da Página:', first: 'Primeira Página', next: 'Próxima Página', previous: 'Página Anterior', last: 'Última Página' }, menu: { text: 'Selecione as colunas:' }, sort: { ascending: 'Ordenar Ascendente', descending: 'Ordenar Descendente', remove: 'Remover Ordenação' }, column: { hide: 'Esconder coluna' }, aggregation: { count: 'total de linhas: ', sum: 'total: ', avg: 'med: ', min: 'min: ', max: 'max: ' }, pinning: { pinLeft: 'Fixar Esquerda', pinRight: 'Fixar Direita', unpin: 'Desprender' }, gridMenu: { columns: 'Colunas:', importerTitle: 'Importar arquivo', exporterAllAsCsv: 'Exportar todos os dados como csv', exporterVisibleAsCsv: 'Exportar dados visíveis como csv', exporterSelectedAsCsv: 'Exportar dados selecionados como csv', exporterAllAsPdf: 'Exportar todos os dados como pdf', exporterVisibleAsPdf: 'Exportar dados visíveis como pdf', exporterSelectedAsPdf: 'Exportar dados selecionados como pdf', clearAllFilters: 'Limpar todos os filtros' }, importer: { noHeaders: 'Nomes de colunas não puderam ser derivados. O arquivo tem um cabeçalho?', noObjects: 'Objetos não puderam ser derivados. Havia dados no arquivo, além dos cabeçalhos?', invalidCsv: 'Arquivo não pode ser processado. É um CSV válido?', invalidJson: 'Arquivo não pode ser processado. É um Json válido?', jsonNotArray: 'Arquivo json importado tem que conter um array. Abortando.' }, pagination: { sizes: 'itens por página', totalItems: 'itens' }, grouping: { group: 'Agrupar', ungroup: 'Desagrupar', aggregate_count: 'Agr: Contar', aggregate_sum: 'Agr: Soma', aggregate_max: 'Agr: Max', aggregate_min: 'Agr: Min', aggregate_avg: 'Agr: Med', aggregate_remove: 'Agr: Remover' } }); return $delegate; }]); }]); })(); (function () { angular.module('ui.grid').config(['$provide', function($provide) { $provide.decorator('i18nService', ['$delegate', function($delegate) { $delegate.add('pt', { aggregate: { label: 'itens' }, groupPanel: { description: 'Arraste e solte uma coluna aqui para agrupar por essa coluna' }, search: { placeholder: 'Procurar...', showingItems: 'Mostrando os Itens:', selectedItems: 'Itens Selecionados:', totalItems: 'Total de Itens:', size: 'Tamanho da Página:', first: 'Primeira Página', next: 'Próxima Página', previous: 'Página Anterior', last: 'Última Página' }, menu: { text: 'Selecione as colunas:' }, sort: { ascending: 'Ordenar Ascendente', descending: 'Ordenar Descendente', remove: 'Remover Ordenação' }, column: { hide: 'Esconder coluna' }, aggregation: { count: 'total de linhas: ', sum: 'total: ', avg: 'med: ', min: 'min: ', max: 'max: ' }, pinning: { pinLeft: 'Fixar Esquerda', pinRight: 'Fixar Direita', unpin: 'Desprender' }, gridMenu: { columns: 'Colunas:', importerTitle: 'Importar ficheiro', exporterAllAsCsv: 'Exportar todos os dados como csv', exporterVisibleAsCsv: 'Exportar dados visíveis como csv', exporterSelectedAsCsv: 'Exportar dados selecionados como csv', exporterAllAsPdf: 'Exportar todos os dados como pdf', exporterVisibleAsPdf: 'Exportar dados visíveis como pdf', exporterSelectedAsPdf: 'Exportar dados selecionados como pdf', clearAllFilters: 'Limpar todos os filtros' }, importer: { noHeaders: 'Nomes de colunas não puderam ser derivados. O ficheiro tem um cabeçalho?', noObjects: 'Objetos não puderam ser derivados. Havia dados no ficheiro, além dos cabeçalhos?', invalidCsv: 'Ficheiro não pode ser processado. É um CSV válido?', invalidJson: 'Ficheiro não pode ser processado. É um Json válido?', jsonNotArray: 'Ficheiro json importado tem que conter um array. Interrompendo.' }, pagination: { sizes: 'itens por página', totalItems: 'itens', of: 'de' }, grouping: { group: 'Agrupar', ungroup: 'Desagrupar', aggregate_count: 'Agr: Contar', aggregate_sum: 'Agr: Soma', aggregate_max: 'Agr: Max', aggregate_min: 'Agr: Min', aggregate_avg: 'Agr: Med', aggregate_remove: 'Agr: Remover' } }); return $delegate; }]); }]); })(); (function () { angular.module('ui.grid').config(['$provide', function($provide) { $provide.decorator('i18nService', ['$delegate', function($delegate) { $delegate.add('ru', { aggregate: { label: 'элементы' }, groupPanel: { description: 'Для группировки по столбцу перетащите сюда его название.' }, search: { placeholder: 'Поиск...', showingItems: 'Показать элементы:', selectedItems: 'Выбранные элементы:', totalItems: 'Всего элементов:', size: 'Размер страницы:', first: 'Первая страница', next: 'Следующая страница', previous: 'Предыдущая страница', last: 'Последняя страница' }, menu: { text: 'Выбрать столбцы:' }, sort: { ascending: 'По возрастанию', descending: 'По убыванию', remove: 'Убрать сортировку' }, column: { hide: 'Спрятать столбец' }, aggregation: { count: 'всего строк: ', sum: 'итого: ', avg: 'среднее: ', min: 'мин: ', max: 'макс: ' }, pinning: { pinLeft: 'Закрепить слева', pinRight: 'Закрепить справа', unpin: 'Открепить' }, gridMenu: { columns: 'Столбцы:', importerTitle: 'Import file', exporterAllAsCsv: 'Экспортировать всё в CSV', exporterVisibleAsCsv: 'Экспортировать видимые данные в CSV', exporterSelectedAsCsv: 'Экспортировать выбранные данные в CSV', exporterAllAsPdf: 'Экспортировать всё в PDF', exporterVisibleAsPdf: 'Экспортировать видимые данные в PDF', exporterSelectedAsPdf: 'Экспортировать выбранные данные в PDF', clearAllFilters: 'Очистите все фильтры' }, importer: { noHeaders: 'Column names were unable to be derived, does the file have a header?', noObjects: 'Objects were not able to be derived, was there data in the file other than headers?', invalidCsv: 'File was unable to be processed, is it valid CSV?', invalidJson: 'File was unable to be processed, is it valid Json?', jsonNotArray: 'Imported json file must contain an array, aborting.' } }); return $delegate; }]); }]); })(); (function () { angular.module('ui.grid').config(['$provide', function($provide) { $provide.decorator('i18nService', ['$delegate', function($delegate) { $delegate.add('sk', { aggregate: { label: 'items' }, groupPanel: { description: 'Pretiahni sem názov stĺpca pre zoskupenie podľa toho stĺpca.' }, search: { placeholder: 'Hľadaj...', showingItems: 'Zobrazujem položky:', selectedItems: 'Vybraté položky:', totalItems: 'Počet položiek:', size: 'Počet:', first: 'Prvá strana', next: 'Ďalšia strana', previous: 'Predchádzajúca strana', last: 'Posledná strana' }, menu: { text: 'Vyberte stĺpce:' }, sort: { ascending: 'Zotriediť vzostupne', descending: 'Zotriediť zostupne', remove: 'Vymazať triedenie' }, aggregation: { count: 'total rows: ', sum: 'total: ', avg: 'avg: ', min: 'min: ', max: 'max: ' }, gridMenu: { columns: 'Columns:', importerTitle: 'Import file', exporterAllAsCsv: 'Export all data as csv', exporterVisibleAsCsv: 'Export visible data as csv', exporterSelectedAsCsv: 'Export selected data as csv', exporterAllAsPdf: 'Export all data as pdf', exporterVisibleAsPdf: 'Export visible data as pdf', exporterSelectedAsPdf: 'Export selected data as pdf', clearAllFilters: 'Clear all filters' }, importer: { noHeaders: 'Column names were unable to be derived, does the file have a header?', noObjects: 'Objects were not able to be derived, was there data in the file other than headers?', invalidCsv: 'File was unable to be processed, is it valid CSV?', invalidJson: 'File was unable to be processed, is it valid Json?', jsonNotArray: 'Imported json file must contain an array, aborting.' } }); return $delegate; }]); }]); })(); (function () { angular.module('ui.grid').config(['$provide', function($provide) { $provide.decorator('i18nService', ['$delegate', function($delegate) { $delegate.add('sv', { aggregate: { label: 'Artiklar' }, groupPanel: { description: 'Dra en kolumnrubrik hit och släpp den för att gruppera efter den kolumnen.' }, search: { placeholder: 'Sök...', showingItems: 'Visar artiklar:', selectedItems: 'Valda artiklar:', totalItems: 'Antal artiklar:', size: 'Sidstorlek:', first: 'Första sidan', next: 'Nästa sida', previous: 'Föregående sida', last: 'Sista sidan' }, menu: { text: 'Välj kolumner:' }, sort: { ascending: 'Sortera stigande', descending: 'Sortera fallande', remove: 'Inaktivera sortering' }, column: { hide: 'Göm kolumn' }, aggregation: { count: 'Antal rader: ', sum: 'Summa: ', avg: 'Genomsnitt: ', min: 'Min: ', max: 'Max: ' }, pinning: { pinLeft: 'Fäst vänster', pinRight: 'Fäst höger', unpin: 'Lösgör' }, gridMenu: { columns: 'Kolumner:', importerTitle: 'Importera fil', exporterAllAsCsv: 'Exportera all data som CSV', exporterVisibleAsCsv: 'Exportera synlig data som CSV', exporterSelectedAsCsv: 'Exportera markerad data som CSV', exporterAllAsPdf: 'Exportera all data som PDF', exporterVisibleAsPdf: 'Exportera synlig data som PDF', exporterSelectedAsPdf: 'Exportera markerad data som PDF', clearAllFilters: 'Rengör alla filter' }, importer: { noHeaders: 'Kolumnnamn kunde inte härledas. Har filen ett sidhuvud?', noObjects: 'Objekt kunde inte härledas. Har filen data undantaget sidhuvud?', invalidCsv: 'Filen kunde inte behandlas, är den en giltig CSV?', invalidJson: 'Filen kunde inte behandlas, är den en giltig JSON?', jsonNotArray: 'Importerad JSON-fil måste innehålla ett fält. Import avbruten.' }, pagination: { sizes: 'Artiklar per sida', totalItems: 'Artiklar' } }); return $delegate; }]); }]); })(); (function () { angular.module('ui.grid').config(['$provide', function($provide) { $provide.decorator('i18nService', ['$delegate', function($delegate) { $delegate.add('ta', { aggregate: { label: 'உருப்படிகள்' }, groupPanel: { description: 'ஒரு பத்தியை குழுவாக அமைக்க அப்பத்தியின் தலைப்பை இங்கே இழுத்து வரவும் ' }, search: { placeholder: 'தேடல் ...', showingItems: 'உருப்படிகளை காண்பித்தல்:', selectedItems: 'தேர்ந்தெடுக்கப்பட்ட உருப்படிகள்:', totalItems: 'மொத்த உருப்படிகள்:', size: 'பக்க அளவு: ', first: 'முதல் பக்கம்', next: 'அடுத்த பக்கம்', previous: 'முந்தைய பக்கம் ', last: 'இறுதி பக்கம்' }, menu: { text: 'பத்திகளை தேர்ந்தெடு:' }, sort: { ascending: 'மேலிருந்து கீழாக', descending: 'கீழிருந்து மேலாக', remove: 'வரிசையை நீக்கு' }, column: { hide: 'பத்தியை மறைத்து வை ' }, aggregation: { count: 'மொத்த வரிகள்:', sum: 'மொத்தம்: ', avg: 'சராசரி: ', min: 'குறைந்தபட்ச: ', max: 'அதிகபட்ச: ' }, pinning: { pinLeft: 'இடதுபுறமாக தைக்க ', pinRight: 'வலதுபுறமாக தைக்க', unpin: 'பிரி' }, gridMenu: { columns: 'பத்திகள்:', importerTitle: 'கோப்பு : படித்தல்', exporterAllAsCsv: 'எல்லா தரவுகளையும் கோப்பாக்கு: csv', exporterVisibleAsCsv: 'இருக்கும் தரவுகளை கோப்பாக்கு: csv', exporterSelectedAsCsv: 'தேர்ந்தெடுத்த தரவுகளை கோப்பாக்கு: csv', exporterAllAsPdf: 'எல்லா தரவுகளையும் கோப்பாக்கு: pdf', exporterVisibleAsPdf: 'இருக்கும் தரவுகளை கோப்பாக்கு: pdf', exporterSelectedAsPdf: 'தேர்ந்தெடுத்த தரவுகளை கோப்பாக்கு: pdf', clearAllFilters: 'Clear all filters' }, importer: { noHeaders: 'பத்தியின் தலைப்புகளை பெற இயலவில்லை, கோப்பிற்கு தலைப்பு உள்ளதா?', noObjects: 'இலக்குகளை உருவாக்க முடியவில்லை, கோப்பில் தலைப்புகளை தவிர தரவு ஏதேனும் உள்ளதா? ', invalidCsv: 'சரிவர நடைமுறை படுத்த இயலவில்லை, கோப்பு சரிதானா? - csv', invalidJson: 'சரிவர நடைமுறை படுத்த இயலவில்லை, கோப்பு சரிதானா? - json', jsonNotArray: 'படித்த கோப்பில் வரிசைகள் உள்ளது, நடைமுறை ரத்து செய் : json' }, pagination: { sizes : 'உருப்படிகள் / பக்கம்', totalItems : 'உருப்படிகள் ' }, grouping: { group : 'குழு', ungroup : 'பிரி', aggregate_count : 'மதிப்பீட்டு : எண்ணு', aggregate_sum : 'மதிப்பீட்டு : கூட்டல்', aggregate_max : 'மதிப்பீட்டு : அதிகபட்சம்', aggregate_min : 'மதிப்பீட்டு : குறைந்தபட்சம்', aggregate_avg : 'மதிப்பீட்டு : சராசரி', aggregate_remove : 'மதிப்பீட்டு : நீக்கு' } }); return $delegate; }]); }]); })(); /** * @ngdoc overview * @name ui.grid.i18n * @description * * # ui.grid.i18n * This module provides i18n functions to ui.grid and any application that wants to use it * * <div doc-module-components="ui.grid.i18n"></div> */ (function () { var DIRECTIVE_ALIASES = ['uiT', 'uiTranslate']; var FILTER_ALIASES = ['t', 'uiTranslate']; var module = angular.module('ui.grid.i18n'); /** * @ngdoc object * @name ui.grid.i18n.constant:i18nConstants * * @description constants available in i18n module */ module.constant('i18nConstants', { MISSING: '[MISSING]', UPDATE_EVENT: '$uiI18n', LOCALE_DIRECTIVE_ALIAS: 'uiI18n', // default to english DEFAULT_LANG: 'en' }); // module.config(['$provide', function($provide) { // $provide.decorator('i18nService', ['$delegate', function($delegate) {}])}]); /** * @ngdoc service * @name ui.grid.i18n.service:i18nService * * @description Services for i18n */ module.service('i18nService', ['$log', 'i18nConstants', '$rootScope', function ($log, i18nConstants, $rootScope) { var langCache = { _langs: {}, current: null, get: function (lang) { return this._langs[lang.toLowerCase()]; }, add: function (lang, strings) { var lower = lang.toLowerCase(); if (!this._langs[lower]) { this._langs[lower] = {}; } angular.extend(this._langs[lower], strings); }, getAllLangs: function () { var langs = []; if (!this._langs) { return langs; } for (var key in this._langs) { langs.push(key); } return langs; }, setCurrent: function (lang) { this.current = lang.toLowerCase(); }, getCurrentLang: function () { return this.current; } }; var service = { /** * @ngdoc service * @name add * @methodOf ui.grid.i18n.service:i18nService * @description Adds the languages and strings to the cache. Decorate this service to * add more translation strings * @param {string} lang language to add * @param {object} stringMaps of strings to add grouped by property names * @example * <pre> * i18nService.add('en', { * aggregate: { * label1: 'items', * label2: 'some more items' * } * }, * groupPanel: { * description: 'Drag a column header here and drop it to group by that column.' * } * } * </pre> */ add: function (langs, stringMaps) { if (typeof(langs) === 'object') { angular.forEach(langs, function (lang) { if (lang) { langCache.add(lang, stringMaps); } }); } else { langCache.add(langs, stringMaps); } }, /** * @ngdoc service * @name getAllLangs * @methodOf ui.grid.i18n.service:i18nService * @description return all currently loaded languages * @returns {array} string */ getAllLangs: function () { return langCache.getAllLangs(); }, /** * @ngdoc service * @name get * @methodOf ui.grid.i18n.service:i18nService * @description return all currently loaded languages * @param {string} lang to return. If not specified, returns current language * @returns {object} the translation string maps for the language */ get: function (lang) { var language = lang ? lang : service.getCurrentLang(); return langCache.get(language); }, /** * @ngdoc service * @name getSafeText * @methodOf ui.grid.i18n.service:i18nService * @description returns the text specified in the path or a Missing text if text is not found * @param {string} path property path to use for retrieving text from string map * @param {string} lang to return. If not specified, returns current language * @returns {object} the translation for the path * @example * <pre> * i18nService.getSafeText('sort.ascending') * </pre> */ getSafeText: function (path, lang) { var language = lang ? lang : service.getCurrentLang(); var trans = langCache.get(language); if (!trans) { return i18nConstants.MISSING; } var paths = path.split('.'); var current = trans; for (var i = 0; i < paths.length; ++i) { if (current[paths[i]] === undefined || current[paths[i]] === null) { return i18nConstants.MISSING; } else { current = current[paths[i]]; } } return current; }, /** * @ngdoc service * @name setCurrentLang * @methodOf ui.grid.i18n.service:i18nService * @description sets the current language to use in the application * $broadcasts the Update_Event on the $rootScope * @param {string} lang to set * @example * <pre> * i18nService.setCurrentLang('fr'); * </pre> */ setCurrentLang: function (lang) { if (lang) { langCache.setCurrent(lang); $rootScope.$broadcast(i18nConstants.UPDATE_EVENT); } }, /** * @ngdoc service * @name getCurrentLang * @methodOf ui.grid.i18n.service:i18nService * @description returns the current language used in the application */ getCurrentLang: function () { var lang = langCache.getCurrentLang(); if (!lang) { lang = i18nConstants.DEFAULT_LANG; langCache.setCurrent(lang); } return lang; } }; return service; }]); var localeDirective = function (i18nService, i18nConstants) { return { compile: function () { return { pre: function ($scope, $elm, $attrs) { var alias = i18nConstants.LOCALE_DIRECTIVE_ALIAS; // check for watchable property var lang = $scope.$eval($attrs[alias]); if (lang) { $scope.$watch($attrs[alias], function () { i18nService.setCurrentLang(lang); }); } else if ($attrs.$$observers) { $attrs.$observe(alias, function () { i18nService.setCurrentLang($attrs[alias] || i18nConstants.DEFAULT_LANG); }); } } }; } }; }; module.directive('uiI18n', ['i18nService', 'i18nConstants', localeDirective]); // directive syntax var uitDirective = function ($parse, i18nService, i18nConstants) { return { restrict: 'EA', compile: function () { return { pre: function ($scope, $elm, $attrs) { var alias1 = DIRECTIVE_ALIASES[0], alias2 = DIRECTIVE_ALIASES[1]; var token = $attrs[alias1] || $attrs[alias2] || $elm.html(); var missing = i18nConstants.MISSING + token; var observer; if ($attrs.$$observers) { var prop = $attrs[alias1] ? alias1 : alias2; observer = $attrs.$observe(prop, function (result) { if (result) { $elm.html($parse(result)(i18nService.getCurrentLang()) || missing); } }); } var getter = $parse(token); var listener = $scope.$on(i18nConstants.UPDATE_EVENT, function (evt) { if (observer) { observer($attrs[alias1] || $attrs[alias2]); } else { // set text based on i18n current language $elm.html(getter(i18nService.get()) || missing); } }); $scope.$on('$destroy', listener); $elm.html(getter(i18nService.get()) || missing); } }; } }; }; angular.forEach( DIRECTIVE_ALIASES, function ( alias ) { module.directive( alias, ['$parse', 'i18nService', 'i18nConstants', uitDirective] ); } ); // optional filter syntax var uitFilter = function ($parse, i18nService, i18nConstants) { return function (data) { var getter = $parse(data); // set text based on i18n current language return getter(i18nService.get()) || i18nConstants.MISSING + data; }; }; angular.forEach( FILTER_ALIASES, function ( alias ) { module.filter( alias, ['$parse', 'i18nService', 'i18nConstants', uitFilter] ); } ); })(); (function() { angular.module('ui.grid').config(['$provide', function($provide) { $provide.decorator('i18nService', ['$delegate', function($delegate) { $delegate.add('zh-cn', { headerCell: { aria: { defaultFilterLabel: '列过滤器', removeFilter: '移除过滤器', columnMenuButtonLabel: '列菜单' }, priority: '优先级:', filterLabel: "列过滤器: " }, aggregate: { label: '行' }, groupPanel: { description: '拖曳表头到此处进行分组' }, search: { placeholder: '查找', showingItems: '已显示行数:', selectedItems: '已选择行数:', totalItems: '总行数:', size: '每页显示行数:', first: '首页', next: '下一页', previous: '上一页', last: '末页' }, menu: { text: '选择列:' }, sort: { ascending: '升序', descending: '降序', none: '无序', remove: '取消排序' }, column: { hide: '隐藏列' }, aggregation: { count: '计数:', sum: '求和:', avg: '均值:', min: '最小值:', max: '最大值:' }, pinning: { pinLeft: '左侧固定', pinRight: '右侧固定', unpin: '取消固定' }, columnMenu: { close: '关闭' }, gridMenu: { aria: { buttonLabel: '表格菜单' }, columns: '列:', importerTitle: '导入文件', exporterAllAsCsv: '导出全部数据到CSV', exporterVisibleAsCsv: '导出可见数据到CSV', exporterSelectedAsCsv: '导出已选数据到CSV', exporterAllAsPdf: '导出全部数据到PDF', exporterVisibleAsPdf: '导出可见数据到PDF', exporterSelectedAsPdf: '导出已选数据到PDF', clearAllFilters: '清除所有过滤器' }, importer: { noHeaders: '无法获取列名,确定文件包含表头?', noObjects: '无法获取数据,确定文件包含数据?', invalidCsv: '无法处理文件,确定是合法的CSV文件?', invalidJson: '无法处理文件,确定是合法的JSON文件?', jsonNotArray: '导入的文件不是JSON数组!' }, pagination: { aria: { pageToFirst: '第一页', pageBack: '上一页', pageSelected: '当前页', pageForward: '下一页', pageToLast: '最后一页' }, sizes: '行每页', totalItems: '行', through: '至', of: '共' }, grouping: { group: '分组', ungroup: '取消分组', aggregate_count: '合计: 计数', aggregate_sum: '合计: 求和', aggregate_max: '合计: 最大', aggregate_min: '合计: 最小', aggregate_avg: '合计: 平均', aggregate_remove: '合计: 移除' } }); return $delegate; }]); }]); })(); (function() { angular.module('ui.grid').config(['$provide', function($provide) { $provide.decorator('i18nService', ['$delegate', function($delegate) { $delegate.add('zh-tw', { aggregate: { label: '行' }, groupPanel: { description: '拖曳表頭到此處進行分組' }, search: { placeholder: '查找', showingItems: '已顯示行數:', selectedItems: '已選擇行數:', totalItems: '總行數:', size: '每頁顯示行數:', first: '首頁', next: '下壹頁', previous: '上壹頁', last: '末頁' }, menu: { text: '選擇列:' }, sort: { ascending: '升序', descending: '降序', remove: '取消排序' }, column: { hide: '隱藏列' }, aggregation: { count: '計數:', sum: '求和:', avg: '均值:', min: '最小值:', max: '最大值:' }, pinning: { pinLeft: '左側固定', pinRight: '右側固定', unpin: '取消固定' }, gridMenu: { columns: '列:', importerTitle: '導入文件', exporterAllAsCsv: '導出全部數據到CSV', exporterVisibleAsCsv: '導出可見數據到CSV', exporterSelectedAsCsv: '導出已選數據到CSV', exporterAllAsPdf: '導出全部數據到PDF', exporterVisibleAsPdf: '導出可見數據到PDF', exporterSelectedAsPdf: '導出已選數據到PDF', clearAllFilters: '清除所有过滤器' }, importer: { noHeaders: '無法獲取列名,確定文件包含表頭?', noObjects: '無法獲取數據,確定文件包含數據?', invalidCsv: '無法處理文件,確定是合法的CSV文件?', invalidJson: '無法處理文件,確定是合法的JSON文件?', jsonNotArray: '導入的文件不是JSON數組!' }, pagination: { sizes: '行每頁', totalItems: '行' } }); return $delegate; }]); }]); })(); (function() { 'use strict'; /** * @ngdoc overview * @name ui.grid.autoResize * * @description * * #ui.grid.autoResize * * <div class="alert alert-warning" role="alert"><strong>Beta</strong> This feature is ready for testing, but it either hasn't seen a lot of use or has some known bugs.</div> * * This module provides auto-resizing functionality to UI-Grid. */ var module = angular.module('ui.grid.autoResize', ['ui.grid']); module.directive('uiGridAutoResize', ['$timeout', 'gridUtil', function ($timeout, gridUtil) { return { require: 'uiGrid', scope: false, link: function ($scope, $elm, $attrs, uiGridCtrl) { var prevGridWidth, prevGridHeight; function getDimensions() { prevGridHeight = gridUtil.elementHeight($elm); prevGridWidth = gridUtil.elementWidth($elm); } // Initialize the dimensions getDimensions(); var resizeTimeoutId; function startTimeout() { clearTimeout(resizeTimeoutId); resizeTimeoutId = setTimeout(function () { var newGridHeight = gridUtil.elementHeight($elm); var newGridWidth = gridUtil.elementWidth($elm); if (newGridHeight !== prevGridHeight || newGridWidth !== prevGridWidth) { uiGridCtrl.grid.gridHeight = newGridHeight; uiGridCtrl.grid.gridWidth = newGridWidth; $scope.$apply(function () { uiGridCtrl.grid.refresh() .then(function () { getDimensions(); startTimeout(); }); }); } else { startTimeout(); } }, 250); } startTimeout(); $scope.$on('$destroy', function() { clearTimeout(resizeTimeoutId); }); } }; }]); })(); (function () { 'use strict'; /** * @ngdoc overview * @name ui.grid.cellNav * * @description #ui.grid.cellNav <div class="alert alert-success" role="alert"><strong>Stable</strong> This feature is stable. There should no longer be breaking api changes without a deprecation warning.</div> This module provides auto-resizing functionality to UI-Grid. */ var module = angular.module('ui.grid.cellNav', ['ui.grid']); /** * @ngdoc object * @name ui.grid.cellNav.constant:uiGridCellNavConstants * * @description constants available in cellNav */ module.constant('uiGridCellNavConstants', { FEATURE_NAME: 'gridCellNav', CELL_NAV_EVENT: 'cellNav', direction: {LEFT: 0, RIGHT: 1, UP: 2, DOWN: 3, PG_UP: 4, PG_DOWN: 5}, EVENT_TYPE: { KEYDOWN: 0, CLICK: 1, CLEAR: 2 } }); module.factory('uiGridCellNavFactory', ['gridUtil', 'uiGridConstants', 'uiGridCellNavConstants', 'GridRowColumn', '$q', function (gridUtil, uiGridConstants, uiGridCellNavConstants, GridRowColumn, $q) { /** * @ngdoc object * @name ui.grid.cellNav.object:CellNav * @description returns a CellNav prototype function * @param {object} rowContainer container for rows * @param {object} colContainer parent column container * @param {object} leftColContainer column container to the left of parent * @param {object} rightColContainer column container to the right of parent */ var UiGridCellNav = function UiGridCellNav(rowContainer, colContainer, leftColContainer, rightColContainer) { this.rows = rowContainer.visibleRowCache; this.columns = colContainer.visibleColumnCache; this.leftColumns = leftColContainer ? leftColContainer.visibleColumnCache : []; this.rightColumns = rightColContainer ? rightColContainer.visibleColumnCache : []; this.bodyContainer = rowContainer; }; /** returns focusable columns of all containers */ UiGridCellNav.prototype.getFocusableCols = function () { var allColumns = this.leftColumns.concat(this.columns, this.rightColumns); return allColumns.filter(function (col) { return col.colDef.allowCellFocus; }); }; /** * @ngdoc object * @name ui.grid.cellNav.api:GridRow * * @description GridRow settings for cellNav feature, these are available to be * set only internally (for example, by other features) */ /** * @ngdoc object * @name allowCellFocus * @propertyOf ui.grid.cellNav.api:GridRow * @description Enable focus on a cell within this row. If set to false then no cells * in this row can be focused - group header rows as an example would set this to false. * <br/>Defaults to true */ /** returns focusable rows */ UiGridCellNav.prototype.getFocusableRows = function () { return this.rows.filter(function(row) { return row.allowCellFocus !== false; }); }; UiGridCellNav.prototype.getNextRowCol = function (direction, curRow, curCol) { switch (direction) { case uiGridCellNavConstants.direction.LEFT: return this.getRowColLeft(curRow, curCol); case uiGridCellNavConstants.direction.RIGHT: return this.getRowColRight(curRow, curCol); case uiGridCellNavConstants.direction.UP: return this.getRowColUp(curRow, curCol); case uiGridCellNavConstants.direction.DOWN: return this.getRowColDown(curRow, curCol); case uiGridCellNavConstants.direction.PG_UP: return this.getRowColPageUp(curRow, curCol); case uiGridCellNavConstants.direction.PG_DOWN: return this.getRowColPageDown(curRow, curCol); } }; UiGridCellNav.prototype.initializeSelection = function () { var focusableCols = this.getFocusableCols(); var focusableRows = this.getFocusableRows(); if (focusableCols.length === 0 || focusableRows.length === 0) { return null; } var curRowIndex = 0; var curColIndex = 0; return new GridRowColumn(focusableRows[0], focusableCols[0]); //return same row }; UiGridCellNav.prototype.getRowColLeft = function (curRow, curCol) { var focusableCols = this.getFocusableCols(); var focusableRows = this.getFocusableRows(); var curColIndex = focusableCols.indexOf(curCol); var curRowIndex = focusableRows.indexOf(curRow); //could not find column in focusable Columns so set it to 1 if (curColIndex === -1) { curColIndex = 1; } var nextColIndex = curColIndex === 0 ? focusableCols.length - 1 : curColIndex - 1; //get column to left if (nextColIndex > curColIndex) { // On the first row // if (curRowIndex === 0 && curColIndex === 0) { // return null; // } if (curRowIndex === 0) { return new GridRowColumn(curRow, focusableCols[nextColIndex]); //return same row } else { //up one row and far right column return new GridRowColumn(focusableRows[curRowIndex - 1], focusableCols[nextColIndex]); } } else { return new GridRowColumn(curRow, focusableCols[nextColIndex]); } }; UiGridCellNav.prototype.getRowColRight = function (curRow, curCol) { var focusableCols = this.getFocusableCols(); var focusableRows = this.getFocusableRows(); var curColIndex = focusableCols.indexOf(curCol); var curRowIndex = focusableRows.indexOf(curRow); //could not find column in focusable Columns so set it to 0 if (curColIndex === -1) { curColIndex = 0; } var nextColIndex = curColIndex === focusableCols.length - 1 ? 0 : curColIndex + 1; if (nextColIndex < curColIndex) { if (curRowIndex === focusableRows.length - 1) { return new GridRowColumn(curRow, focusableCols[nextColIndex]); //return same row } else { //down one row and far left column return new GridRowColumn(focusableRows[curRowIndex + 1], focusableCols[nextColIndex]); } } else { return new GridRowColumn(curRow, focusableCols[nextColIndex]); } }; UiGridCellNav.prototype.getRowColDown = function (curRow, curCol) { var focusableCols = this.getFocusableCols(); var focusableRows = this.getFocusableRows(); var curColIndex = focusableCols.indexOf(curCol); var curRowIndex = focusableRows.indexOf(curRow); //could not find column in focusable Columns so set it to 0 if (curColIndex === -1) { curColIndex = 0; } if (curRowIndex === focusableRows.length - 1) { return new GridRowColumn(curRow, focusableCols[curColIndex]); //return same row } else { //down one row return new GridRowColumn(focusableRows[curRowIndex + 1], focusableCols[curColIndex]); } }; UiGridCellNav.prototype.getRowColPageDown = function (curRow, curCol) { var focusableCols = this.getFocusableCols(); var focusableRows = this.getFocusableRows(); var curColIndex = focusableCols.indexOf(curCol); var curRowIndex = focusableRows.indexOf(curRow); //could not find column in focusable Columns so set it to 0 if (curColIndex === -1) { curColIndex = 0; } var pageSize = this.bodyContainer.minRowsToRender(); if (curRowIndex >= focusableRows.length - pageSize) { return new GridRowColumn(focusableRows[focusableRows.length - 1], focusableCols[curColIndex]); //return last row } else { //down one page return new GridRowColumn(focusableRows[curRowIndex + pageSize], focusableCols[curColIndex]); } }; UiGridCellNav.prototype.getRowColUp = function (curRow, curCol) { var focusableCols = this.getFocusableCols(); var focusableRows = this.getFocusableRows(); var curColIndex = focusableCols.indexOf(curCol); var curRowIndex = focusableRows.indexOf(curRow); //could not find column in focusable Columns so set it to 0 if (curColIndex === -1) { curColIndex = 0; } if (curRowIndex === 0) { return new GridRowColumn(curRow, focusableCols[curColIndex]); //return same row } else { //up one row return new GridRowColumn(focusableRows[curRowIndex - 1], focusableCols[curColIndex]); } }; UiGridCellNav.prototype.getRowColPageUp = function (curRow, curCol) { var focusableCols = this.getFocusableCols(); var focusableRows = this.getFocusableRows(); var curColIndex = focusableCols.indexOf(curCol); var curRowIndex = focusableRows.indexOf(curRow); //could not find column in focusable Columns so set it to 0 if (curColIndex === -1) { curColIndex = 0; } var pageSize = this.bodyContainer.minRowsToRender(); if (curRowIndex - pageSize < 0) { return new GridRowColumn(focusableRows[0], focusableCols[curColIndex]); //return first row } else { //up one page return new GridRowColumn(focusableRows[curRowIndex - pageSize], focusableCols[curColIndex]); } }; return UiGridCellNav; }]); /** * @ngdoc service * @name ui.grid.cellNav.service:uiGridCellNavService * * @description Services for cell navigation features. If you don't like the key maps we use, * or the direction cells navigation, override with a service decorator (see angular docs) */ module.service('uiGridCellNavService', ['gridUtil', 'uiGridConstants', 'uiGridCellNavConstants', '$q', 'uiGridCellNavFactory', 'GridRowColumn', 'ScrollEvent', function (gridUtil, uiGridConstants, uiGridCellNavConstants, $q, UiGridCellNav, GridRowColumn, ScrollEvent) { var service = { initializeGrid: function (grid) { grid.registerColumnBuilder(service.cellNavColumnBuilder); /** * @ngdoc object * @name ui.grid.cellNav:Grid.cellNav * @description cellNav properties added to grid class */ grid.cellNav = {}; grid.cellNav.lastRowCol = null; grid.cellNav.focusedCells = []; service.defaultGridOptions(grid.options); /** * @ngdoc object * @name ui.grid.cellNav.api:PublicApi * * @description Public Api for cellNav feature */ var publicApi = { events: { cellNav: { /** * @ngdoc event * @name navigate * @eventOf ui.grid.cellNav.api:PublicApi * @description raised when the active cell is changed * <pre> * gridApi.cellNav.on.navigate(scope,function(newRowcol, oldRowCol){}) * </pre> * @param {object} newRowCol new position * @param {object} oldRowCol old position */ navigate: function (newRowCol, oldRowCol) {}, /** * @ngdoc event * @name viewPortKeyDown * @eventOf ui.grid.cellNav.api:PublicApi * @description is raised when the viewPort receives a keyDown event. Cells never get focus in uiGrid * due to the difficulties of setting focus on a cell that is not visible in the viewport. Use this * event whenever you need a keydown event on a cell * <br/> * @param {object} event keydown event * @param {object} rowCol current rowCol position */ viewPortKeyDown: function (event, rowCol) {}, /** * @ngdoc event * @name viewPortKeyPress * @eventOf ui.grid.cellNav.api:PublicApi * @description is raised when the viewPort receives a keyPress event. Cells never get focus in uiGrid * due to the difficulties of setting focus on a cell that is not visible in the viewport. Use this * event whenever you need a keypress event on a cell * <br/> * @param {object} event keypress event * @param {object} rowCol current rowCol position */ viewPortKeyPress: function (event, rowCol) {} } }, methods: { cellNav: { /** * @ngdoc function * @name scrollToFocus * @methodOf ui.grid.cellNav.api:PublicApi * @description brings the specified row and column into view, and sets focus * to that cell * @param {object} rowEntity gridOptions.data[] array instance to make visible and set focus * @param {object} colDef to make visible and set focus * @returns {promise} a promise that is resolved after any scrolling is finished */ scrollToFocus: function (rowEntity, colDef) { return service.scrollToFocus(grid, rowEntity, colDef); }, /** * @ngdoc function * @name getFocusedCell * @methodOf ui.grid.cellNav.api:PublicApi * @description returns the current (or last if Grid does not have focus) focused row and column * <br> value is null if no selection has occurred */ getFocusedCell: function () { return grid.cellNav.lastRowCol; }, /** * @ngdoc function * @name getCurrentSelection * @methodOf ui.grid.cellNav.api:PublicApi * @description returns an array containing the current selection * <br> array is empty if no selection has occurred */ getCurrentSelection: function () { return grid.cellNav.focusedCells; }, /** * @ngdoc function * @name rowColSelectIndex * @methodOf ui.grid.cellNav.api:PublicApi * @description returns the index in the order in which the GridRowColumn was selected, returns -1 if the GridRowColumn * isn't selected * @param {object} rowCol the rowCol to evaluate */ rowColSelectIndex: function (rowCol) { //return gridUtil.arrayContainsObjectWithProperty(grid.cellNav.focusedCells, 'col.uid', rowCol.col.uid) && var index = -1; for (var i = 0; i < grid.cellNav.focusedCells.length; i++) { if (grid.cellNav.focusedCells[i].col.uid === rowCol.col.uid && grid.cellNav.focusedCells[i].row.uid === rowCol.row.uid) { index = i; break; } } return index; } } } }; grid.api.registerEventsFromObject(publicApi.events); grid.api.registerMethodsFromObject(publicApi.methods); }, defaultGridOptions: function (gridOptions) { /** * @ngdoc object * @name ui.grid.cellNav.api:GridOptions * * @description GridOptions for cellNav feature, these are available to be * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions} */ /** * @ngdoc object * @name modifierKeysToMultiSelectCells * @propertyOf ui.grid.cellNav.api:GridOptions * @description Enable multiple cell selection only when using the ctrlKey or shiftKey. * <br/>Defaults to false */ gridOptions.modifierKeysToMultiSelectCells = gridOptions.modifierKeysToMultiSelectCells === true; }, /** * @ngdoc service * @name decorateRenderContainers * @methodOf ui.grid.cellNav.service:uiGridCellNavService * @description decorates grid renderContainers with cellNav functions */ decorateRenderContainers: function (grid) { var rightContainer = grid.hasRightContainer() ? grid.renderContainers.right : null; var leftContainer = grid.hasLeftContainer() ? grid.renderContainers.left : null; if (leftContainer !== null) { grid.renderContainers.left.cellNav = new UiGridCellNav(grid.renderContainers.body, leftContainer, rightContainer, grid.renderContainers.body); } if (rightContainer !== null) { grid.renderContainers.right.cellNav = new UiGridCellNav(grid.renderContainers.body, rightContainer, grid.renderContainers.body, leftContainer); } grid.renderContainers.body.cellNav = new UiGridCellNav(grid.renderContainers.body, grid.renderContainers.body, leftContainer, rightContainer); }, /** * @ngdoc service * @name getDirection * @methodOf ui.grid.cellNav.service:uiGridCellNavService * @description determines which direction to for a given keyDown event * @returns {uiGridCellNavConstants.direction} direction */ getDirection: function (evt) { if (evt.keyCode === uiGridConstants.keymap.LEFT || (evt.keyCode === uiGridConstants.keymap.TAB && evt.shiftKey)) { return uiGridCellNavConstants.direction.LEFT; } if (evt.keyCode === uiGridConstants.keymap.RIGHT || evt.keyCode === uiGridConstants.keymap.TAB) { return uiGridCellNavConstants.direction.RIGHT; } if (evt.keyCode === uiGridConstants.keymap.UP || (evt.keyCode === uiGridConstants.keymap.ENTER && evt.shiftKey) ) { return uiGridCellNavConstants.direction.UP; } if (evt.keyCode === uiGridConstants.keymap.PG_UP){ return uiGridCellNavConstants.direction.PG_UP; } if (evt.keyCode === uiGridConstants.keymap.DOWN || evt.keyCode === uiGridConstants.keymap.ENTER && !(evt.ctrlKey || evt.altKey)) { return uiGridCellNavConstants.direction.DOWN; } if (evt.keyCode === uiGridConstants.keymap.PG_DOWN){ return uiGridCellNavConstants.direction.PG_DOWN; } return null; }, /** * @ngdoc service * @name cellNavColumnBuilder * @methodOf ui.grid.cellNav.service:uiGridCellNavService * @description columnBuilder function that adds cell navigation properties to grid column * @returns {promise} promise that will load any needed templates when resolved */ cellNavColumnBuilder: function (colDef, col, gridOptions) { var promises = []; /** * @ngdoc object * @name ui.grid.cellNav.api:ColumnDef * * @description Column Definitions for cellNav feature, these are available to be * set using the ui-grid {@link ui.grid.class:GridOptions.columnDef gridOptions.columnDefs} */ /** * @ngdoc object * @name allowCellFocus * @propertyOf ui.grid.cellNav.api:ColumnDef * @description Enable focus on a cell within this column. * <br/>Defaults to true */ colDef.allowCellFocus = colDef.allowCellFocus === undefined ? true : colDef.allowCellFocus; return $q.all(promises); }, /** * @ngdoc method * @methodOf ui.grid.cellNav.service:uiGridCellNavService * @name scrollToFocus * @description Scroll the grid such that the specified * row and column is in view, and set focus to the cell in that row and column * @param {Grid} grid the grid you'd like to act upon, usually available * from gridApi.grid * @param {object} rowEntity gridOptions.data[] array instance to make visible and set focus to * @param {object} colDef to make visible and set focus to * @returns {promise} a promise that is resolved after any scrolling is finished */ scrollToFocus: function (grid, rowEntity, colDef) { var gridRow = null, gridCol = null; if (typeof(rowEntity) !== 'undefined' && rowEntity !== null) { gridRow = grid.getRow(rowEntity); } if (typeof(colDef) !== 'undefined' && colDef !== null) { gridCol = grid.getColumn(colDef.name ? colDef.name : colDef.field); } return grid.api.core.scrollToIfNecessary(gridRow, gridCol).then(function () { var rowCol = { row: gridRow, col: gridCol }; // Broadcast the navigation if (gridRow !== null && gridCol !== null) { grid.cellNav.broadcastCellNav(rowCol); } }); }, /** * @ngdoc method * @methodOf ui.grid.cellNav.service:uiGridCellNavService * @name getLeftWidth * @description Get the current drawn width of the columns in the * grid up to the numbered column, and add an apportionment for the * column that we're on. So if we are on column 0, we want to scroll * 0% (i.e. exclude this column from calc). If we're on the last column * we want to scroll to 100% (i.e. include this column in the calc). So * we include (thisColIndex / totalNumberCols) % of this column width * @param {Grid} grid the grid you'd like to act upon, usually available * from gridApi.grid * @param {gridCol} upToCol the column to total up to and including */ getLeftWidth: function (grid, upToCol) { var width = 0; if (!upToCol) { return width; } var lastIndex = grid.renderContainers.body.visibleColumnCache.indexOf( upToCol ); // total column widths up-to but not including the passed in column grid.renderContainers.body.visibleColumnCache.forEach( function( col, index ) { if ( index < lastIndex ){ width += col.drawnWidth; } }); // pro-rata the final column based on % of total columns. var percentage = lastIndex === 0 ? 0 : (lastIndex + 1) / grid.renderContainers.body.visibleColumnCache.length; width += upToCol.drawnWidth * percentage; return width; } }; return service; }]); /** * @ngdoc directive * @name ui.grid.cellNav.directive:uiCellNav * @element div * @restrict EA * * @description Adds cell navigation features to the grid columns * * @example <example module="app"> <file name="app.js"> var app = angular.module('app', ['ui.grid', 'ui.grid.cellNav']); app.controller('MainCtrl', ['$scope', function ($scope) { $scope.data = [ { name: 'Bob', title: 'CEO' }, { name: 'Frank', title: 'Lowly Developer' } ]; $scope.columnDefs = [ {name: 'name'}, {name: 'title'} ]; }]); </file> <file name="index.html"> <div ng-controller="MainCtrl"> <div ui-grid="{ data: data, columnDefs: columnDefs }" ui-grid-cellnav></div> </div> </file> </example> */ module.directive('uiGridCellnav', ['gridUtil', 'uiGridCellNavService', 'uiGridCellNavConstants', 'uiGridConstants', 'GridRowColumn', '$timeout', '$compile', function (gridUtil, uiGridCellNavService, uiGridCellNavConstants, uiGridConstants, GridRowColumn, $timeout, $compile) { return { replace: true, priority: -150, require: '^uiGrid', scope: false, controller: function () {}, compile: function () { return { pre: function ($scope, $elm, $attrs, uiGridCtrl) { var _scope = $scope; var grid = uiGridCtrl.grid; uiGridCellNavService.initializeGrid(grid); uiGridCtrl.cellNav = {}; //Ensure that the object has all of the methods we expect it to uiGridCtrl.cellNav.makeRowCol = function (obj) { if (!(obj instanceof GridRowColumn)) { obj = new GridRowColumn(obj.row, obj.col); } return obj; }; uiGridCtrl.cellNav.getActiveCell = function () { var elms = $elm[0].getElementsByClassName('ui-grid-cell-focus'); if (elms.length > 0){ return elms[0]; } return undefined; }; uiGridCtrl.cellNav.broadcastCellNav = grid.cellNav.broadcastCellNav = function (newRowCol, modifierDown, originEvt) { modifierDown = !(modifierDown === undefined || !modifierDown); newRowCol = uiGridCtrl.cellNav.makeRowCol(newRowCol); uiGridCtrl.cellNav.broadcastFocus(newRowCol, modifierDown, originEvt); _scope.$broadcast(uiGridCellNavConstants.CELL_NAV_EVENT, newRowCol, modifierDown, originEvt); }; uiGridCtrl.cellNav.clearFocus = grid.cellNav.clearFocus = function () { grid.cellNav.focusedCells = []; _scope.$broadcast(uiGridCellNavConstants.CELL_NAV_EVENT); }; uiGridCtrl.cellNav.broadcastFocus = function (rowCol, modifierDown, originEvt) { modifierDown = !(modifierDown === undefined || !modifierDown); rowCol = uiGridCtrl.cellNav.makeRowCol(rowCol); var row = rowCol.row, col = rowCol.col; var rowColSelectIndex = uiGridCtrl.grid.api.cellNav.rowColSelectIndex(rowCol); if (grid.cellNav.lastRowCol === null || rowColSelectIndex === -1) { var newRowCol = new GridRowColumn(row, col); grid.api.cellNav.raise.navigate(newRowCol, grid.cellNav.lastRowCol); grid.cellNav.lastRowCol = newRowCol; if (uiGridCtrl.grid.options.modifierKeysToMultiSelectCells && modifierDown) { grid.cellNav.focusedCells.push(rowCol); } else { grid.cellNav.focusedCells = [rowCol]; } } else if (grid.options.modifierKeysToMultiSelectCells && modifierDown && rowColSelectIndex >= 0) { grid.cellNav.focusedCells.splice(rowColSelectIndex, 1); } }; uiGridCtrl.cellNav.handleKeyDown = function (evt) { var direction = uiGridCellNavService.getDirection(evt); if (direction === null) { return null; } var containerId = 'body'; if (evt.uiGridTargetRenderContainerId) { containerId = evt.uiGridTargetRenderContainerId; } // Get the last-focused row+col combo var lastRowCol = uiGridCtrl.grid.api.cellNav.getFocusedCell(); if (lastRowCol) { // Figure out which new row+combo we're navigating to var rowCol = uiGridCtrl.grid.renderContainers[containerId].cellNav.getNextRowCol(direction, lastRowCol.row, lastRowCol.col); var focusableCols = uiGridCtrl.grid.renderContainers[containerId].cellNav.getFocusableCols(); var rowColSelectIndex = uiGridCtrl.grid.api.cellNav.rowColSelectIndex(rowCol); // Shift+tab on top-left cell should exit cellnav on render container if ( // Navigating left direction === uiGridCellNavConstants.direction.LEFT && // New col is last col (i.e. wrap around) rowCol.col === focusableCols[focusableCols.length - 1] && // Staying on same row, which means we're at first row rowCol.row === lastRowCol.row && evt.keyCode === uiGridConstants.keymap.TAB && evt.shiftKey ) { grid.cellNav.focusedCells.splice(rowColSelectIndex, 1); uiGridCtrl.cellNav.clearFocus(); return true; } // Tab on bottom-right cell should exit cellnav on render container else if ( direction === uiGridCellNavConstants.direction.RIGHT && // New col is first col (i.e. wrap around) rowCol.col === focusableCols[0] && // Staying on same row, which means we're at first row rowCol.row === lastRowCol.row && evt.keyCode === uiGridConstants.keymap.TAB && !evt.shiftKey ) { grid.cellNav.focusedCells.splice(rowColSelectIndex, 1); uiGridCtrl.cellNav.clearFocus(); return true; } // Scroll to the new cell, if it's not completely visible within the render container's viewport grid.scrollToIfNecessary(rowCol.row, rowCol.col).then(function () { uiGridCtrl.cellNav.broadcastCellNav(rowCol); }); evt.stopPropagation(); evt.preventDefault(); return false; } }; }, post: function ($scope, $elm, $attrs, uiGridCtrl) { var _scope = $scope; var grid = uiGridCtrl.grid; function addAriaLiveRegion(){ // Thanks to google docs for the inspiration behind how to do this // XXX: Why is this entire mess nessasary? // Because browsers take a lot of coercing to get them to read out live regions //http://www.paciellogroup.com/blog/2012/06/html5-accessibility-chops-aria-rolealert-browser-support/ var ariaNotifierDomElt = '<div ' + 'id="' + grid.id +'-aria-speakable" ' + 'class="ui-grid-a11y-ariascreenreader-speakable ui-grid-offscreen" ' + 'aria-live="assertive" ' + 'role="region" ' + 'aria-atomic="true" ' + 'aria-hidden="false" ' + 'aria-relevant="additions" ' + '>' + '&nbsp;' + '</div>'; var ariaNotifier = $compile(ariaNotifierDomElt)($scope); $elm.prepend(ariaNotifier); $scope.$on(uiGridCellNavConstants.CELL_NAV_EVENT, function (evt, rowCol, modifierDown, originEvt) { /* * If the cell nav event was because of a focus event then we don't want to * change the notifier text. * Reasoning: Voice Over fires a focus events when moving arround the grid. * If the screen reader is handing the grid nav properly then we don't need to * use the alert to notify the user of the movement. * In all other cases we do want a notification event. */ if (originEvt && originEvt.type === 'focus'){return;} function setNotifyText(text){ if (text === ariaNotifier.text()){return;} ariaNotifier[0].style.clip = 'rect(0px,0px,0px,0px)'; /* * This is how google docs handles clearing the div. Seems to work better than setting the text of the div to '' */ ariaNotifier[0].innerHTML = ""; ariaNotifier[0].style.visibility = 'hidden'; ariaNotifier[0].style.visibility = 'visible'; if (text !== ''){ ariaNotifier[0].style.clip = 'auto'; /* * The space after the text is something that google docs does. */ ariaNotifier[0].appendChild(document.createTextNode(text + " ")); ariaNotifier[0].style.visibility = 'hidden'; ariaNotifier[0].style.visibility = 'visible'; } } var values = []; var currentSelection = grid.api.cellNav.getCurrentSelection(); for (var i = 0; i < currentSelection.length; i++) { values.push(currentSelection[i].getIntersectionValueFiltered()); } var cellText = values.toString(); setNotifyText(cellText); }); } addAriaLiveRegion(); } }; } }; }]); module.directive('uiGridRenderContainer', ['$timeout', '$document', 'gridUtil', 'uiGridConstants', 'uiGridCellNavService', '$compile','uiGridCellNavConstants', function ($timeout, $document, gridUtil, uiGridConstants, uiGridCellNavService, $compile, uiGridCellNavConstants) { return { replace: true, priority: -99999, //this needs to run very last require: ['^uiGrid', 'uiGridRenderContainer', '?^uiGridCellnav'], scope: false, compile: function () { return { post: function ($scope, $elm, $attrs, controllers) { var uiGridCtrl = controllers[0], renderContainerCtrl = controllers[1], uiGridCellnavCtrl = controllers[2]; // Skip attaching cell-nav specific logic if the directive is not attached above us if (!uiGridCtrl.grid.api.cellNav) { return; } var containerId = renderContainerCtrl.containerId; var grid = uiGridCtrl.grid; //run each time a render container is created uiGridCellNavService.decorateRenderContainers(grid); // focusser only created for body if (containerId !== 'body') { return; } if (uiGridCtrl.grid.options.modifierKeysToMultiSelectCells){ $elm.attr('aria-multiselectable', true); } else { $elm.attr('aria-multiselectable', false); } //add an element with no dimensions that can be used to set focus and capture keystrokes var focuser = $compile('<div class="ui-grid-focuser" role="region" aria-live="assertive" aria-atomic="false" tabindex="0" aria-controls="' + grid.id +'-aria-speakable '+ grid.id + '-grid-container' +'" aria-owns="' + grid.id + '-grid-container' + '"></div>')($scope); $elm.append(focuser); focuser.on('focus', function (evt) { evt.uiGridTargetRenderContainerId = containerId; var rowCol = uiGridCtrl.grid.api.cellNav.getFocusedCell(); if (rowCol === null) { rowCol = uiGridCtrl.grid.renderContainers[containerId].cellNav.getNextRowCol(uiGridCellNavConstants.direction.DOWN, null, null); if (rowCol.row && rowCol.col) { uiGridCtrl.cellNav.broadcastCellNav(rowCol); } } }); uiGridCellnavCtrl.setAriaActivedescendant = function(id){ $elm.attr('aria-activedescendant', id); }; uiGridCellnavCtrl.removeAriaActivedescendant = function(id){ if ($elm.attr('aria-activedescendant') === id){ $elm.attr('aria-activedescendant', ''); } }; uiGridCtrl.focus = function () { gridUtil.focus.byElement(focuser[0]); //allow for first time grid focus }; var viewPortKeyDownWasRaisedForRowCol = null; // Bind to keydown events in the render container focuser.on('keydown', function (evt) { evt.uiGridTargetRenderContainerId = containerId; var rowCol = uiGridCtrl.grid.api.cellNav.getFocusedCell(); var result = uiGridCtrl.cellNav.handleKeyDown(evt); if (result === null) { uiGridCtrl.grid.api.cellNav.raise.viewPortKeyDown(evt, rowCol); viewPortKeyDownWasRaisedForRowCol = rowCol; } }); //Bind to keypress events in the render container //keypress events are needed by edit function so the key press //that initiated an edit is not lost //must fire the event in a timeout so the editor can //initialize and subscribe to the event on another event loop focuser.on('keypress', function (evt) { if (viewPortKeyDownWasRaisedForRowCol) { $timeout(function () { uiGridCtrl.grid.api.cellNav.raise.viewPortKeyPress(evt, viewPortKeyDownWasRaisedForRowCol); },4); viewPortKeyDownWasRaisedForRowCol = null; } }); $scope.$on('$destroy', function(){ //Remove all event handlers associated with this focuser. focuser.off(); }); } }; } }; }]); module.directive('uiGridViewport', ['$timeout', '$document', 'gridUtil', 'uiGridConstants', 'uiGridCellNavService', 'uiGridCellNavConstants','$log','$compile', function ($timeout, $document, gridUtil, uiGridConstants, uiGridCellNavService, uiGridCellNavConstants, $log, $compile) { return { replace: true, priority: -99999, //this needs to run very last require: ['^uiGrid', '^uiGridRenderContainer', '?^uiGridCellnav'], scope: false, compile: function () { return { pre: function ($scope, $elm, $attrs, uiGridCtrl) { }, post: function ($scope, $elm, $attrs, controllers) { var uiGridCtrl = controllers[0], renderContainerCtrl = controllers[1]; // Skip attaching cell-nav specific logic if the directive is not attached above us if (!uiGridCtrl.grid.api.cellNav) { return; } var containerId = renderContainerCtrl.containerId; //no need to process for other containers if (containerId !== 'body') { return; } var grid = uiGridCtrl.grid; grid.api.core.on.scrollBegin($scope, function (args) { // Skip if there's no currently-focused cell var lastRowCol = uiGridCtrl.grid.api.cellNav.getFocusedCell(); if (lastRowCol === null) { return; } //if not in my container, move on //todo: worry about horiz scroll if (!renderContainerCtrl.colContainer.containsColumn(lastRowCol.col)) { return; } uiGridCtrl.cellNav.clearFocus(); }); grid.api.core.on.scrollEnd($scope, function (args) { // Skip if there's no currently-focused cell var lastRowCol = uiGridCtrl.grid.api.cellNav.getFocusedCell(); if (lastRowCol === null) { return; } //if not in my container, move on //todo: worry about horiz scroll if (!renderContainerCtrl.colContainer.containsColumn(lastRowCol.col)) { return; } uiGridCtrl.cellNav.broadcastCellNav(lastRowCol); }); grid.api.cellNav.on.navigate($scope, function () { //focus again because it can be lost uiGridCtrl.focus(); }); } }; } }; }]); /** * @ngdoc directive * @name ui.grid.cellNav.directive:uiGridCell * @element div * @restrict A * @description Stacks on top of ui.grid.uiGridCell to provide cell navigation */ module.directive('uiGridCell', ['$timeout', '$document', 'uiGridCellNavService', 'gridUtil', 'uiGridCellNavConstants', 'uiGridConstants', 'GridRowColumn', function ($timeout, $document, uiGridCellNavService, gridUtil, uiGridCellNavConstants, uiGridConstants, GridRowColumn) { return { priority: -150, // run after default uiGridCell directive and ui.grid.edit uiGridCell restrict: 'A', require: ['^uiGrid', '?^uiGridCellnav'], scope: false, link: function ($scope, $elm, $attrs, controllers) { var uiGridCtrl = controllers[0], uiGridCellnavCtrl = controllers[1]; // Skip attaching cell-nav specific logic if the directive is not attached above us if (!uiGridCtrl.grid.api.cellNav) { return; } if (!$scope.col.colDef.allowCellFocus) { return; } //Convinience local variables var grid = uiGridCtrl.grid; $scope.focused = false; // Make this cell focusable but only with javascript/a mouse click $elm.attr('tabindex', -1); // When a cell is clicked, broadcast a cellNav event saying that this row+col combo is now focused $elm.find('div').on('click', function (evt) { uiGridCtrl.cellNav.broadcastCellNav(new GridRowColumn($scope.row, $scope.col), evt.ctrlKey || evt.metaKey, evt); evt.stopPropagation(); $scope.$apply(); }); /* * XXX Hack for screen readers. * This allows the grid to focus using only the screen reader cursor. * Since the focus event doesn't include key press information we can't use it * as our primary source of the event. */ $elm.on('mousedown', preventMouseDown); //turn on and off for edit events if (uiGridCtrl.grid.api.edit) { uiGridCtrl.grid.api.edit.on.beginCellEdit($scope, function () { $elm.off('mousedown', preventMouseDown); }); uiGridCtrl.grid.api.edit.on.afterCellEdit($scope, function () { $elm.on('mousedown', preventMouseDown); }); uiGridCtrl.grid.api.edit.on.cancelCellEdit($scope, function () { $elm.on('mousedown', preventMouseDown); }); } function preventMouseDown(evt) { //Prevents the foucus event from firing if the click event is already going to fire. //If both events fire it will cause bouncing behavior. evt.preventDefault(); } //You can only focus on elements with a tabindex value $elm.on('focus', function (evt) { uiGridCtrl.cellNav.broadcastCellNav(new GridRowColumn($scope.row, $scope.col), false, evt); evt.stopPropagation(); $scope.$apply(); }); // This event is fired for all cells. If the cell matches, then focus is set $scope.$on(uiGridCellNavConstants.CELL_NAV_EVENT, function (evt, rowCol, modifierDown) { var isFocused = grid.cellNav.focusedCells.some(function(focusedRowCol, index){ return (focusedRowCol.row === $scope.row && focusedRowCol.col === $scope.col); }); if (isFocused){ setFocused(); } else { clearFocus(); } }); function setFocused() { if (!$scope.focused){ var div = $elm.find('div'); div.addClass('ui-grid-cell-focus'); $elm.attr('aria-selected', true); uiGridCellnavCtrl.setAriaActivedescendant($elm.attr('id')); $scope.focused = true; } } function clearFocus() { if ($scope.focused){ var div = $elm.find('div'); div.removeClass('ui-grid-cell-focus'); $elm.attr('aria-selected', false); uiGridCellnavCtrl.removeAriaActivedescendant($elm.attr('id')); $scope.focused = false; } } $scope.$on('$destroy', function () { //.off withouth paramaters removes all handlers $elm.find('div').off(); $elm.off(); }); } }; }]); })(); (function () { 'use strict'; /** * @ngdoc overview * @name ui.grid.edit * @description * * # ui.grid.edit * * <div class="alert alert-success" role="alert"><strong>Stable</strong> This feature is stable. There should no longer be breaking api changes without a deprecation warning.</div> * * This module provides cell editing capability to ui.grid. The goal was to emulate keying data in a spreadsheet via * a keyboard. * <br/> * <br/> * To really get the full spreadsheet-like data entry, the ui.grid.cellNav module should be used. This will allow the * user to key data and then tab, arrow, or enter to the cells beside or below. * * <div doc-module-components="ui.grid.edit"></div> */ var module = angular.module('ui.grid.edit', ['ui.grid']); /** * @ngdoc object * @name ui.grid.edit.constant:uiGridEditConstants * * @description constants available in edit module */ module.constant('uiGridEditConstants', { EDITABLE_CELL_TEMPLATE: /EDITABLE_CELL_TEMPLATE/g, //must be lowercase because template bulder converts to lower EDITABLE_CELL_DIRECTIVE: /editable_cell_directive/g, events: { BEGIN_CELL_EDIT: 'uiGridEventBeginCellEdit', END_CELL_EDIT: 'uiGridEventEndCellEdit', CANCEL_CELL_EDIT: 'uiGridEventCancelCellEdit' } }); /** * @ngdoc service * @name ui.grid.edit.service:uiGridEditService * * @description Services for editing features */ module.service('uiGridEditService', ['$q', 'uiGridConstants', 'gridUtil', function ($q, uiGridConstants, gridUtil) { var service = { initializeGrid: function (grid) { service.defaultGridOptions(grid.options); grid.registerColumnBuilder(service.editColumnBuilder); grid.edit = {}; /** * @ngdoc object * @name ui.grid.edit.api:PublicApi * * @description Public Api for edit feature */ var publicApi = { events: { edit: { /** * @ngdoc event * @name afterCellEdit * @eventOf ui.grid.edit.api:PublicApi * @description raised when cell editing is complete * <pre> * gridApi.edit.on.afterCellEdit(scope,function(rowEntity, colDef){}) * </pre> * @param {object} rowEntity the options.data element that was edited * @param {object} colDef the column that was edited * @param {object} newValue new value * @param {object} oldValue old value */ afterCellEdit: function (rowEntity, colDef, newValue, oldValue) { }, /** * @ngdoc event * @name beginCellEdit * @eventOf ui.grid.edit.api:PublicApi * @description raised when cell editing starts on a cell * <pre> * gridApi.edit.on.beginCellEdit(scope,function(rowEntity, colDef){}) * </pre> * @param {object} rowEntity the options.data element that was edited * @param {object} colDef the column that was edited * @param {object} triggerEvent the event that triggered the edit. Useful to prevent losing keystrokes on some * complex editors */ beginCellEdit: function (rowEntity, colDef, triggerEvent) { }, /** * @ngdoc event * @name cancelCellEdit * @eventOf ui.grid.edit.api:PublicApi * @description raised when cell editing is cancelled on a cell * <pre> * gridApi.edit.on.cancelCellEdit(scope,function(rowEntity, colDef){}) * </pre> * @param {object} rowEntity the options.data element that was edited * @param {object} colDef the column that was edited */ cancelCellEdit: function (rowEntity, colDef) { } } }, methods: { edit: { } } }; grid.api.registerEventsFromObject(publicApi.events); //grid.api.registerMethodsFromObject(publicApi.methods); }, defaultGridOptions: function (gridOptions) { /** * @ngdoc object * @name ui.grid.edit.api:GridOptions * * @description Options for configuring the edit feature, these are available to be * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions} */ /** * @ngdoc object * @name enableCellEdit * @propertyOf ui.grid.edit.api:GridOptions * @description If defined, sets the default value for the editable flag on each individual colDefs * if their individual enableCellEdit configuration is not defined. Defaults to undefined. */ /** * @ngdoc object * @name cellEditableCondition * @propertyOf ui.grid.edit.api:GridOptions * @description If specified, either a value or function to be used by all columns before editing. * If falsy, then editing of cell is not allowed. * @example * <pre> * function($scope){ * //use $scope.row.entity and $scope.col.colDef to determine if editing is allowed * return true; * } * </pre> */ gridOptions.cellEditableCondition = gridOptions.cellEditableCondition === undefined ? true : gridOptions.cellEditableCondition; /** * @ngdoc object * @name editableCellTemplate * @propertyOf ui.grid.edit.api:GridOptions * @description If specified, cellTemplate to use as the editor for all columns. * <br/> defaults to 'ui-grid/cellTextEditor' */ /** * @ngdoc object * @name enableCellEditOnFocus * @propertyOf ui.grid.edit.api:GridOptions * @description If true, then editor is invoked as soon as cell receives focus. Default false. * <br/>_requires cellNav feature and the edit feature to be enabled_ */ //enableCellEditOnFocus can only be used if cellnav module is used gridOptions.enableCellEditOnFocus = gridOptions.enableCellEditOnFocus === undefined ? false : gridOptions.enableCellEditOnFocus; }, /** * @ngdoc service * @name editColumnBuilder * @methodOf ui.grid.edit.service:uiGridEditService * @description columnBuilder function that adds edit properties to grid column * @returns {promise} promise that will load any needed templates when resolved */ editColumnBuilder: function (colDef, col, gridOptions) { var promises = []; /** * @ngdoc object * @name ui.grid.edit.api:ColumnDef * * @description Column Definition for edit feature, these are available to be * set using the ui-grid {@link ui.grid.class:GridOptions.columnDef gridOptions.columnDefs} */ /** * @ngdoc object * @name enableCellEdit * @propertyOf ui.grid.edit.api:ColumnDef * @description enable editing on column */ colDef.enableCellEdit = colDef.enableCellEdit === undefined ? (gridOptions.enableCellEdit === undefined ? (colDef.type !== 'object') : gridOptions.enableCellEdit) : colDef.enableCellEdit; /** * @ngdoc object * @name cellEditableCondition * @propertyOf ui.grid.edit.api:ColumnDef * @description If specified, either a value or function evaluated before editing cell. If falsy, then editing of cell is not allowed. * @example * <pre> * function($scope){ * //use $scope.row.entity and $scope.col.colDef to determine if editing is allowed * return true; * } * </pre> */ colDef.cellEditableCondition = colDef.cellEditableCondition === undefined ? gridOptions.cellEditableCondition : colDef.cellEditableCondition; /** * @ngdoc object * @name editableCellTemplate * @propertyOf ui.grid.edit.api:ColumnDef * @description cell template to be used when editing this column. Can be Url or text template * <br/>Defaults to gridOptions.editableCellTemplate */ if (colDef.enableCellEdit) { colDef.editableCellTemplate = colDef.editableCellTemplate || gridOptions.editableCellTemplate || 'ui-grid/cellEditor'; promises.push(gridUtil.getTemplate(colDef.editableCellTemplate) .then( function (template) { col.editableCellTemplate = template; }, function (res) { // Todo handle response error here? throw new Error("Couldn't fetch/use colDef.editableCellTemplate '" + colDef.editableCellTemplate + "'"); })); } /** * @ngdoc object * @name enableCellEditOnFocus * @propertyOf ui.grid.edit.api:ColumnDef * @requires ui.grid.cellNav * @description If true, then editor is invoked as soon as cell receives focus. Default false. * <br>_requires both the cellNav feature and the edit feature to be enabled_ */ //enableCellEditOnFocus can only be used if cellnav module is used colDef.enableCellEditOnFocus = colDef.enableCellEditOnFocus === undefined ? gridOptions.enableCellEditOnFocus : colDef.enableCellEditOnFocus; /** * @ngdoc string * @name editModelField * @propertyOf ui.grid.edit.api:ColumnDef * @description a bindable string value that is used when binding to edit controls instead of colDef.field * <br/> example: You have a complex property on and object like state:{abbrev:'MS',name:'Mississippi'}. The * grid should display state.name in the cell and sort/filter based on the state.name property but the editor * requires the full state object. * <br/>colDef.field = 'state.name' * <br/>colDef.editModelField = 'state' */ //colDef.editModelField return $q.all(promises); }, /** * @ngdoc service * @name isStartEditKey * @methodOf ui.grid.edit.service:uiGridEditService * @description Determines if a keypress should start editing. Decorate this service to override with your * own key events. See service decorator in angular docs. * @param {Event} evt keydown event * @returns {boolean} true if an edit should start */ isStartEditKey: function (evt) { if (evt.metaKey || evt.keyCode === uiGridConstants.keymap.ESC || evt.keyCode === uiGridConstants.keymap.SHIFT || evt.keyCode === uiGridConstants.keymap.CTRL || evt.keyCode === uiGridConstants.keymap.ALT || evt.keyCode === uiGridConstants.keymap.WIN || evt.keyCode === uiGridConstants.keymap.CAPSLOCK || evt.keyCode === uiGridConstants.keymap.LEFT || (evt.keyCode === uiGridConstants.keymap.TAB && evt.shiftKey) || evt.keyCode === uiGridConstants.keymap.RIGHT || evt.keyCode === uiGridConstants.keymap.TAB || evt.keyCode === uiGridConstants.keymap.UP || (evt.keyCode === uiGridConstants.keymap.ENTER && evt.shiftKey) || evt.keyCode === uiGridConstants.keymap.DOWN || evt.keyCode === uiGridConstants.keymap.ENTER) { return false; } return true; } }; return service; }]); /** * @ngdoc directive * @name ui.grid.edit.directive:uiGridEdit * @element div * @restrict A * * @description Adds editing features to the ui-grid directive. * * @example <example module="app"> <file name="app.js"> var app = angular.module('app', ['ui.grid', 'ui.grid.edit']); app.controller('MainCtrl', ['$scope', function ($scope) { $scope.data = [ { name: 'Bob', title: 'CEO' }, { name: 'Frank', title: 'Lowly Developer' } ]; $scope.columnDefs = [ {name: 'name', enableCellEdit: true}, {name: 'title', enableCellEdit: true} ]; }]); </file> <file name="index.html"> <div ng-controller="MainCtrl"> <div ui-grid="{ data: data, columnDefs: columnDefs }" ui-grid-edit></div> </div> </file> </example> */ module.directive('uiGridEdit', ['gridUtil', 'uiGridEditService', function (gridUtil, uiGridEditService) { return { replace: true, priority: 0, require: '^uiGrid', scope: false, compile: function () { return { pre: function ($scope, $elm, $attrs, uiGridCtrl) { uiGridEditService.initializeGrid(uiGridCtrl.grid); }, post: function ($scope, $elm, $attrs, uiGridCtrl) { } }; } }; }]); /** * @ngdoc directive * @name ui.grid.edit.directive:uiGridRenderContainer * @element div * @restrict A * * @description Adds keydown listeners to renderContainer element so we can capture when to begin edits * */ module.directive('uiGridViewport', [ 'uiGridEditConstants', function ( uiGridEditConstants) { return { replace: true, priority: -99998, //run before cellNav require: ['^uiGrid', '^uiGridRenderContainer'], scope: false, compile: function () { return { post: function ($scope, $elm, $attrs, controllers) { var uiGridCtrl = controllers[0]; // Skip attaching if edit and cellNav is not enabled if (!uiGridCtrl.grid.api.edit || !uiGridCtrl.grid.api.cellNav) { return; } var containerId = controllers[1].containerId; //no need to process for other containers if (containerId !== 'body') { return; } //refocus on the grid $scope.$on(uiGridEditConstants.events.CANCEL_CELL_EDIT, function () { uiGridCtrl.focus(); }); $scope.$on(uiGridEditConstants.events.END_CELL_EDIT, function () { uiGridCtrl.focus(); }); } }; } }; }]); /** * @ngdoc directive * @name ui.grid.edit.directive:uiGridCell * @element div * @restrict A * * @description Stacks on top of ui.grid.uiGridCell to provide in-line editing capabilities to the cell * Editing Actions. * * Binds edit start events to the uiGridCell element. When the events fire, the gridCell element is appended * with the columnDef.editableCellTemplate element ('cellEditor.html' by default). * * The editableCellTemplate should respond to uiGridEditConstants.events.BEGIN\_CELL\_EDIT angular event * and do the initial steps needed to edit the cell (setfocus on input element, etc). * * When the editableCellTemplate recognizes that the editing is ended (blur event, Enter key, etc.) * it should emit the uiGridEditConstants.events.END\_CELL\_EDIT event. * * If editableCellTemplate recognizes that the editing has been cancelled (esc key) * it should emit the uiGridEditConstants.events.CANCEL\_CELL\_EDIT event. The original value * will be set back on the model by the uiGridCell directive. * * Events that invoke editing: * - dblclick * - F2 keydown (when using cell selection) * * Events that end editing: * - Dependent on the specific editableCellTemplate * - Standards should be blur and enter keydown * * Events that cancel editing: * - Dependent on the specific editableCellTemplate * - Standards should be Esc keydown * * Grid Events that end editing: * - uiGridConstants.events.GRID_SCROLL * */ /** * @ngdoc object * @name ui.grid.edit.api:GridRow * * @description GridRow options for edit feature, these are available to be * set internally only, by other features */ /** * @ngdoc object * @name enableCellEdit * @propertyOf ui.grid.edit.api:GridRow * @description enable editing on row, grouping for example might disable editing on group header rows */ module.directive('uiGridCell', ['$compile', '$injector', '$timeout', 'uiGridConstants', 'uiGridEditConstants', 'gridUtil', '$parse', 'uiGridEditService', '$rootScope', function ($compile, $injector, $timeout, uiGridConstants, uiGridEditConstants, gridUtil, $parse, uiGridEditService, $rootScope) { var touchstartTimeout = 500; if ($injector.has('uiGridCellNavService')) { var uiGridCellNavService = $injector.get('uiGridCellNavService'); } return { priority: -100, // run after default uiGridCell directive restrict: 'A', scope: false, require: '?^uiGrid', link: function ($scope, $elm, $attrs, uiGridCtrl) { var html; var origCellValue; var inEdit = false; var cellModel; var cancelTouchstartTimeout; var editCellScope; if (!$scope.col.colDef.enableCellEdit) { return; } var cellNavNavigateDereg = function() {}; var viewPortKeyDownDereg = function() {}; var setEditable = function() { if ($scope.col.colDef.enableCellEdit && $scope.row.enableCellEdit !== false) { if (!$scope.beginEditEventsWired) { //prevent multiple attachments registerBeginEditEvents(); } } else { if ($scope.beginEditEventsWired) { cancelBeginEditEvents(); } } }; setEditable(); var rowWatchDereg = $scope.$watch('row', function (n, o) { if (n !== o) { setEditable(); } }); $scope.$on( '$destroy', rowWatchDereg ); function registerBeginEditEvents() { $elm.on('dblclick', beginEdit); // Add touchstart handling. If the users starts a touch and it doesn't end after X milliseconds, then start the edit $elm.on('touchstart', touchStart); if (uiGridCtrl && uiGridCtrl.grid.api.cellNav) { viewPortKeyDownDereg = uiGridCtrl.grid.api.cellNav.on.viewPortKeyDown($scope, function (evt, rowCol) { if (rowCol === null) { return; } if (rowCol.row === $scope.row && rowCol.col === $scope.col && !$scope.col.colDef.enableCellEditOnFocus) { //important to do this before scrollToIfNecessary beginEditKeyDown(evt); } }); cellNavNavigateDereg = uiGridCtrl.grid.api.cellNav.on.navigate($scope, function (newRowCol, oldRowCol) { if ($scope.col.colDef.enableCellEditOnFocus) { // Don't begin edit if the cell hasn't changed if ((!oldRowCol || newRowCol.row !== oldRowCol.row || newRowCol.col !== oldRowCol.col) && newRowCol.row === $scope.row && newRowCol.col === $scope.col) { $timeout(function () { beginEdit(); }); } } }); } $scope.beginEditEventsWired = true; } function touchStart(event) { // jQuery masks events if (typeof(event.originalEvent) !== 'undefined' && event.originalEvent !== undefined) { event = event.originalEvent; } // Bind touchend handler $elm.on('touchend', touchEnd); // Start a timeout cancelTouchstartTimeout = $timeout(function() { }, touchstartTimeout); // Timeout's done! Start the edit cancelTouchstartTimeout.then(function () { // Use setTimeout to start the edit because beginEdit expects to be outside of $digest setTimeout(beginEdit, 0); // Undbind the touchend handler, we don't need it anymore $elm.off('touchend', touchEnd); }); } // Cancel any touchstart timeout function touchEnd(event) { $timeout.cancel(cancelTouchstartTimeout); $elm.off('touchend', touchEnd); } function cancelBeginEditEvents() { $elm.off('dblclick', beginEdit); $elm.off('keydown', beginEditKeyDown); $elm.off('touchstart', touchStart); cellNavNavigateDereg(); viewPortKeyDownDereg(); $scope.beginEditEventsWired = false; } function beginEditKeyDown(evt) { if (uiGridEditService.isStartEditKey(evt)) { beginEdit(evt); } } function shouldEdit(col, row) { return !row.isSaving && ( angular.isFunction(col.colDef.cellEditableCondition) ? col.colDef.cellEditableCondition($scope) : col.colDef.cellEditableCondition ); } function beginEdit(triggerEvent) { //we need to scroll the cell into focus before invoking the editor $scope.grid.api.core.scrollToIfNecessary($scope.row, $scope.col) .then(function () { beginEditAfterScroll(triggerEvent); }); } /** * @ngdoc property * @name editDropdownOptionsArray * @propertyOf ui.grid.edit.api:ColumnDef * @description an array of values in the format * [ {id: xxx, value: xxx} ], which is populated * into the edit dropdown * */ /** * @ngdoc property * @name editDropdownIdLabel * @propertyOf ui.grid.edit.api:ColumnDef * @description the label for the "id" field * in the editDropdownOptionsArray. Defaults * to 'id' * @example * <pre> * $scope.gridOptions = { * columnDefs: [ * {name: 'status', editableCellTemplate: 'ui-grid/dropdownEditor', * editDropdownOptionsArray: [{code: 1, status: 'active'}, {code: 2, status: 'inactive'}], * editDropdownIdLabel: 'code', editDropdownValueLabel: 'status' } * ], * </pre> * */ /** * @ngdoc property * @name editDropdownRowEntityOptionsArrayPath * @propertyOf ui.grid.edit.api:ColumnDef * @description a path to a property on row.entity containing an * array of values in the format * [ {id: xxx, value: xxx} ], which will be used to populate * the edit dropdown. This can be used when the dropdown values are dependent on * the backing row entity. * If this property is set then editDropdownOptionsArray will be ignored. * @example * <pre> * $scope.gridOptions = { * columnDefs: [ * {name: 'status', editableCellTemplate: 'ui-grid/dropdownEditor', * editDropdownRowEntityOptionsArrayPath: 'foo.bars[0].baz', * editDropdownIdLabel: 'code', editDropdownValueLabel: 'status' } * ], * </pre> * */ /** * @ngdoc property * @name editDropdownValueLabel * @propertyOf ui.grid.edit.api:ColumnDef * @description the label for the "value" field * in the editDropdownOptionsArray. Defaults * to 'value' * @example * <pre> * $scope.gridOptions = { * columnDefs: [ * {name: 'status', editableCellTemplate: 'ui-grid/dropdownEditor', * editDropdownOptionsArray: [{code: 1, status: 'active'}, {code: 2, status: 'inactive'}], * editDropdownIdLabel: 'code', editDropdownValueLabel: 'status' } * ], * </pre> * */ /** * @ngdoc property * @name editDropdownFilter * @propertyOf ui.grid.edit.api:ColumnDef * @description A filter that you would like to apply to the values in the options list * of the dropdown. For example if you were using angular-translate you might set this * to `'translate'` * @example * <pre> * $scope.gridOptions = { * columnDefs: [ * {name: 'status', editableCellTemplate: 'ui-grid/dropdownEditor', * editDropdownOptionsArray: [{code: 1, status: 'active'}, {code: 2, status: 'inactive'}], * editDropdownIdLabel: 'code', editDropdownValueLabel: 'status', editDropdownFilter: 'translate' } * ], * </pre> * */ function beginEditAfterScroll(triggerEvent) { // If we are already editing, then just skip this so we don't try editing twice... if (inEdit) { return; } if (!shouldEdit($scope.col, $scope.row)) { return; } cellModel = $parse($scope.row.getQualifiedColField($scope.col)); //get original value from the cell origCellValue = cellModel($scope); html = $scope.col.editableCellTemplate; if ($scope.col.colDef.editModelField) { html = html.replace(uiGridConstants.MODEL_COL_FIELD, gridUtil.preEval('row.entity.' + $scope.col.colDef.editModelField)); } else { html = html.replace(uiGridConstants.MODEL_COL_FIELD, $scope.row.getQualifiedColField($scope.col)); } html = html.replace(uiGridConstants.COL_FIELD, 'grid.getCellValue(row, col)'); var optionFilter = $scope.col.colDef.editDropdownFilter ? '|' + $scope.col.colDef.editDropdownFilter : ''; html = html.replace(uiGridConstants.CUSTOM_FILTERS, optionFilter); var inputType = 'text'; switch ($scope.col.colDef.type){ case 'boolean': inputType = 'checkbox'; break; case 'number': inputType = 'number'; break; case 'date': inputType = 'date'; break; } html = html.replace('INPUT_TYPE', inputType); var editDropdownRowEntityOptionsArrayPath = $scope.col.colDef.editDropdownRowEntityOptionsArrayPath; if (editDropdownRowEntityOptionsArrayPath) { $scope.editDropdownOptionsArray = resolveObjectFromPath($scope.row.entity, editDropdownRowEntityOptionsArrayPath); } else { $scope.editDropdownOptionsArray = $scope.col.colDef.editDropdownOptionsArray; } $scope.editDropdownIdLabel = $scope.col.colDef.editDropdownIdLabel ? $scope.col.colDef.editDropdownIdLabel : 'id'; $scope.editDropdownValueLabel = $scope.col.colDef.editDropdownValueLabel ? $scope.col.colDef.editDropdownValueLabel : 'value'; var cellElement; var createEditor = function(){ inEdit = true; cancelBeginEditEvents(); var cellElement = angular.element(html); $elm.append(cellElement); editCellScope = $scope.$new(); $compile(cellElement)(editCellScope); var gridCellContentsEl = angular.element($elm.children()[0]); gridCellContentsEl.addClass('ui-grid-cell-contents-hidden'); }; if (!$rootScope.$$phase) { $scope.$apply(createEditor); } else { createEditor(); } //stop editing when grid is scrolled var deregOnGridScroll = $scope.col.grid.api.core.on.scrollBegin($scope, function () { endEdit(); $scope.grid.api.edit.raise.afterCellEdit($scope.row.entity, $scope.col.colDef, cellModel($scope), origCellValue); deregOnGridScroll(); deregOnEndCellEdit(); deregOnCancelCellEdit(); }); //end editing var deregOnEndCellEdit = $scope.$on(uiGridEditConstants.events.END_CELL_EDIT, function () { endEdit(); $scope.grid.api.edit.raise.afterCellEdit($scope.row.entity, $scope.col.colDef, cellModel($scope), origCellValue); deregOnEndCellEdit(); deregOnGridScroll(); deregOnCancelCellEdit(); }); //cancel editing var deregOnCancelCellEdit = $scope.$on(uiGridEditConstants.events.CANCEL_CELL_EDIT, function () { cancelEdit(); deregOnCancelCellEdit(); deregOnGridScroll(); deregOnEndCellEdit(); }); $scope.$broadcast(uiGridEditConstants.events.BEGIN_CELL_EDIT, triggerEvent); $timeout(function () { //execute in a timeout to give any complex editor templates a cycle to completely render $scope.grid.api.edit.raise.beginCellEdit($scope.row.entity, $scope.col.colDef, triggerEvent); }); } function endEdit() { $scope.grid.disableScrolling = false; if (!inEdit) { return; } //sometimes the events can't keep up with the keyboard and grid focus is lost, so always focus //back to grid here. The focus call needs to be before the $destroy and removal of the control, //otherwise ng-model-options of UpdateOn: 'blur' will not work. if (uiGridCtrl && uiGridCtrl.grid.api.cellNav) { uiGridCtrl.focus(); } var gridCellContentsEl = angular.element($elm.children()[0]); //remove edit element editCellScope.$destroy(); angular.element($elm.children()[1]).remove(); gridCellContentsEl.removeClass('ui-grid-cell-contents-hidden'); inEdit = false; registerBeginEditEvents(); $scope.grid.api.core.notifyDataChange( uiGridConstants.dataChange.EDIT ); } function cancelEdit() { $scope.grid.disableScrolling = false; if (!inEdit) { return; } cellModel.assign($scope, origCellValue); $scope.$apply(); $scope.grid.api.edit.raise.cancelCellEdit($scope.row.entity, $scope.col.colDef); endEdit(); } // resolves a string path against the given object // shamelessly borrowed from // http://stackoverflow.com/questions/6491463/accessing-nested-javascript-objects-with-string-key function resolveObjectFromPath(object, path) { path = path.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties path = path.replace(/^\./, ''); // strip a leading dot var a = path.split('.'); while (a.length) { var n = a.shift(); if (n in object) { object = object[n]; } else { return; } } return object; } } }; }]); /** * @ngdoc directive * @name ui.grid.edit.directive:uiGridEditor * @element div * @restrict A * * @description input editor directive for editable fields. * Provides EndEdit and CancelEdit events * * Events that end editing: * blur and enter keydown * * Events that cancel editing: * - Esc keydown * */ module.directive('uiGridEditor', ['gridUtil', 'uiGridConstants', 'uiGridEditConstants','$timeout', 'uiGridEditService', function (gridUtil, uiGridConstants, uiGridEditConstants, $timeout, uiGridEditService) { return { scope: true, require: ['?^uiGrid', '?^uiGridRenderContainer', 'ngModel'], compile: function () { return { pre: function ($scope, $elm, $attrs) { }, post: function ($scope, $elm, $attrs, controllers) { var uiGridCtrl, renderContainerCtrl, ngModel; if (controllers[0]) { uiGridCtrl = controllers[0]; } if (controllers[1]) { renderContainerCtrl = controllers[1]; } if (controllers[2]) { ngModel = controllers[2]; } //set focus at start of edit $scope.$on(uiGridEditConstants.events.BEGIN_CELL_EDIT, function (evt,triggerEvent) { $timeout(function () { $elm[0].focus(); //only select text if it is not being replaced below in the cellNav viewPortKeyPress if ($scope.col.colDef.enableCellEditOnFocus || !(uiGridCtrl && uiGridCtrl.grid.api.cellNav)) { $elm[0].select(); } else { //some browsers (Chrome) stupidly, imo, support the w3 standard that number, email, ... //fields should not allow setSelectionRange. We ignore the error for those browsers //https://www.w3.org/Bugs/Public/show_bug.cgi?id=24796 try { $elm[0].setSelectionRange($elm[0].value.length, $elm[0].value.length); } catch (ex) { //ignore } } }); //set the keystroke that started the edit event //we must do this because the BeginEdit is done in a different event loop than the intitial //keydown event //fire this event for the keypress that is received if (uiGridCtrl && uiGridCtrl.grid.api.cellNav) { var viewPortKeyDownUnregister = uiGridCtrl.grid.api.cellNav.on.viewPortKeyPress($scope, function (evt, rowCol) { if (uiGridEditService.isStartEditKey(evt)) { ngModel.$setViewValue(String.fromCharCode(evt.keyCode), evt); ngModel.$render(); } viewPortKeyDownUnregister(); }); } $elm.on('blur', function (evt) { $scope.stopEdit(evt); }); }); $scope.deepEdit = false; $scope.stopEdit = function (evt) { if ($scope.inputForm && !$scope.inputForm.$valid) { evt.stopPropagation(); $scope.$emit(uiGridEditConstants.events.CANCEL_CELL_EDIT); } else { $scope.$emit(uiGridEditConstants.events.END_CELL_EDIT); } $scope.deepEdit = false; }; $elm.on('click', function (evt) { if ($elm[0].type !== 'checkbox') { $scope.deepEdit = true; $timeout(function () { $scope.grid.disableScrolling = true; }); } }); $elm.on('keydown', function (evt) { switch (evt.keyCode) { case uiGridConstants.keymap.ESC: evt.stopPropagation(); $scope.$emit(uiGridEditConstants.events.CANCEL_CELL_EDIT); break; } if ($scope.deepEdit && (evt.keyCode === uiGridConstants.keymap.LEFT || evt.keyCode === uiGridConstants.keymap.RIGHT || evt.keyCode === uiGridConstants.keymap.UP || evt.keyCode === uiGridConstants.keymap.DOWN)) { evt.stopPropagation(); } // Pass the keydown event off to the cellNav service, if it exists else if (uiGridCtrl && uiGridCtrl.grid.api.cellNav) { evt.uiGridTargetRenderContainerId = renderContainerCtrl.containerId; if (uiGridCtrl.cellNav.handleKeyDown(evt) !== null) { $scope.stopEdit(evt); } } else { //handle enter and tab for editing not using cellNav switch (evt.keyCode) { case uiGridConstants.keymap.ENTER: // Enter (Leave Field) case uiGridConstants.keymap.TAB: evt.stopPropagation(); evt.preventDefault(); $scope.stopEdit(evt); break; } } return true; }); } }; } }; }]); /** * @ngdoc directive * @name ui.grid.edit.directive:input * @element input * @restrict E * * @description directive to provide binding between input[date] value and ng-model for angular 1.2 * It is similar to input[date] directive of angular 1.3 * * Supported date format for input is 'yyyy-MM-dd' * The directive will set the $valid property of input element and the enclosing form to false if * model is invalid date or value of input is entered wrong. * */ module.directive('uiGridEditor', ['$filter', function ($filter) { function parseDateString(dateString) { if (typeof(dateString) === 'undefined' || dateString === '') { return null; } var parts = dateString.split('-'); if (parts.length !== 3) { return null; } var year = parseInt(parts[0], 10); var month = parseInt(parts[1], 10); var day = parseInt(parts[2], 10); if (month < 1 || year < 1 || day < 1) { return null; } return new Date(year, (month - 1), day); } return { priority: -100, // run after default uiGridEditor directive require: '?ngModel', link: function (scope, element, attrs, ngModel) { if (angular.version.minor === 2 && attrs.type && attrs.type === 'date' && ngModel) { ngModel.$formatters.push(function (modelValue) { ngModel.$setValidity(null,(!modelValue || !isNaN(modelValue.getTime()))); return $filter('date')(modelValue, 'yyyy-MM-dd'); }); ngModel.$parsers.push(function (viewValue) { if (viewValue && viewValue.length > 0) { var dateValue = parseDateString(viewValue); ngModel.$setValidity(null, (dateValue && !isNaN(dateValue.getTime()))); return dateValue; } else { ngModel.$setValidity(null, true); return null; } }); } } }; }]); /** * @ngdoc directive * @name ui.grid.edit.directive:uiGridEditDropdown * @element div * @restrict A * * @description dropdown editor for editable fields. * Provides EndEdit and CancelEdit events * * Events that end editing: * blur and enter keydown, and any left/right nav * * Events that cancel editing: * - Esc keydown * */ module.directive('uiGridEditDropdown', ['uiGridConstants', 'uiGridEditConstants', function (uiGridConstants, uiGridEditConstants) { return { require: ['?^uiGrid', '?^uiGridRenderContainer'], scope: true, compile: function () { return { pre: function ($scope, $elm, $attrs) { }, post: function ($scope, $elm, $attrs, controllers) { var uiGridCtrl = controllers[0]; var renderContainerCtrl = controllers[1]; //set focus at start of edit $scope.$on(uiGridEditConstants.events.BEGIN_CELL_EDIT, function () { $elm[0].focus(); $elm[0].style.width = ($elm[0].parentElement.offsetWidth - 1) + 'px'; $elm.on('blur', function (evt) { $scope.stopEdit(evt); }); }); $scope.stopEdit = function (evt) { // no need to validate a dropdown - invalid values shouldn't be // available in the list $scope.$emit(uiGridEditConstants.events.END_CELL_EDIT); }; $elm.on('keydown', function (evt) { switch (evt.keyCode) { case uiGridConstants.keymap.ESC: evt.stopPropagation(); $scope.$emit(uiGridEditConstants.events.CANCEL_CELL_EDIT); break; } if (uiGridCtrl && uiGridCtrl.grid.api.cellNav) { evt.uiGridTargetRenderContainerId = renderContainerCtrl.containerId; if (uiGridCtrl.cellNav.handleKeyDown(evt) !== null) { $scope.stopEdit(evt); } } else { //handle enter and tab for editing not using cellNav switch (evt.keyCode) { case uiGridConstants.keymap.ENTER: // Enter (Leave Field) case uiGridConstants.keymap.TAB: evt.stopPropagation(); evt.preventDefault(); $scope.stopEdit(evt); break; } } return true; }); } }; } }; }]); /** * @ngdoc directive * @name ui.grid.edit.directive:uiGridEditFileChooser * @element div * @restrict A * * @description input editor directive for editable fields. * Provides EndEdit and CancelEdit events * * Events that end editing: * blur and enter keydown * * Events that cancel editing: * - Esc keydown * */ module.directive('uiGridEditFileChooser', ['gridUtil', 'uiGridConstants', 'uiGridEditConstants','$timeout', function (gridUtil, uiGridConstants, uiGridEditConstants, $timeout) { return { scope: true, require: ['?^uiGrid', '?^uiGridRenderContainer'], compile: function () { return { pre: function ($scope, $elm, $attrs) { }, post: function ($scope, $elm, $attrs, controllers) { var uiGridCtrl, renderContainerCtrl; if (controllers[0]) { uiGridCtrl = controllers[0]; } if (controllers[1]) { renderContainerCtrl = controllers[1]; } var grid = uiGridCtrl.grid; var handleFileSelect = function( event ){ var target = event.srcElement || event.target; if (target && target.files && target.files.length > 0) { /** * @ngdoc property * @name editFileChooserCallback * @propertyOf ui.grid.edit.api:ColumnDef * @description A function that should be called when any files have been chosen * by the user. You should use this to process the files appropriately for your * application. * * It passes the gridCol, the gridRow (from which you can get gridRow.entity), * and the files. The files are in the format as returned from the file chooser, * an array of files, with each having useful information such as: * - `files[0].lastModifiedDate` * - `files[0].name` * - `files[0].size` (appears to be in bytes) * - `files[0].type` (MIME type by the looks) * * Typically you would do something with these files - most commonly you would * use the filename or read the file itself in. The example function does both. * * @example * <pre> * editFileChooserCallBack: function(gridRow, gridCol, files ){ * // ignore all but the first file, it can only choose one anyway * // set the filename into this column * gridRow.entity.filename = file[0].name; * * // read the file and set it into a hidden column, which we may do stuff with later * var setFile = function(fileContent){ * gridRow.entity.file = fileContent.currentTarget.result; * }; * var reader = new FileReader(); * reader.onload = setFile; * reader.readAsText( files[0] ); * } * </pre> */ if ( typeof($scope.col.colDef.editFileChooserCallback) === 'function' ) { $scope.col.colDef.editFileChooserCallback($scope.row, $scope.col, target.files); } else { gridUtil.logError('You need to set colDef.editFileChooserCallback to use the file chooser'); } target.form.reset(); $scope.$emit(uiGridEditConstants.events.END_CELL_EDIT); } else { $scope.$emit(uiGridEditConstants.events.CANCEL_CELL_EDIT); } }; $elm[0].addEventListener('change', handleFileSelect, false); // TODO: why the false on the end? Google $scope.$on(uiGridEditConstants.events.BEGIN_CELL_EDIT, function () { $elm[0].focus(); $elm[0].select(); $elm.on('blur', function (evt) { $scope.$emit(uiGridEditConstants.events.END_CELL_EDIT); }); }); } }; } }; }]); })(); (function () { 'use strict'; /** * @ngdoc overview * @name ui.grid.expandable * @description * * # ui.grid.expandable * * <div class="alert alert-warning" role="alert"><strong>Alpha</strong> This feature is in development. There will almost certainly be breaking api changes, or there are major outstanding bugs.</div> * * This module provides the ability to create subgrids with the ability to expand a row * to show the subgrid. * * <div doc-module-components="ui.grid.expandable"></div> */ var module = angular.module('ui.grid.expandable', ['ui.grid']); /** * @ngdoc service * @name ui.grid.expandable.service:uiGridExpandableService * * @description Services for the expandable grid */ module.service('uiGridExpandableService', ['gridUtil', '$compile', function (gridUtil, $compile) { var service = { initializeGrid: function (grid) { grid.expandable = {}; grid.expandable.expandedAll = false; /** * @ngdoc object * @name enableExpandable * @propertyOf ui.grid.expandable.api:GridOptions * @description Whether or not to use expandable feature, allows you to turn off expandable on specific grids * within your application, or in specific modes on _this_ grid. Defaults to true. * @example * <pre> * $scope.gridOptions = { * enableExpandable: false * } * </pre> */ grid.options.enableExpandable = grid.options.enableExpandable !== false; /** * @ngdoc object * @name expandableRowHeight * @propertyOf ui.grid.expandable.api:GridOptions * @description Height in pixels of the expanded subgrid. Defaults to * 150 * @example * <pre> * $scope.gridOptions = { * expandableRowHeight: 150 * } * </pre> */ grid.options.expandableRowHeight = grid.options.expandableRowHeight || 150; /** * @ngdoc object * @name * @propertyOf ui.grid.expandable.api:GridOptions * @description Width in pixels of the expandable column. Defaults to 40 * @example * <pre> * $scope.gridOptions = { * expandableRowHeaderWidth: 40 * } * </pre> */ grid.options.expandableRowHeaderWidth = grid.options.expandableRowHeaderWidth || 40; /** * @ngdoc object * @name expandableRowTemplate * @propertyOf ui.grid.expandable.api:GridOptions * @description Mandatory. The template for your expanded row * @example * <pre> * $scope.gridOptions = { * expandableRowTemplate: 'expandableRowTemplate.html' * } * </pre> */ if ( grid.options.enableExpandable && !grid.options.expandableRowTemplate ){ gridUtil.logError( 'You have not set the expandableRowTemplate, disabling expandable module' ); grid.options.enableExpandable = false; } /** * @ngdoc object * @name ui.grid.expandable.api:PublicApi * * @description Public Api for expandable feature */ /** * @ngdoc object * @name ui.grid.expandable.api:GridOptions * * @description Options for configuring the expandable feature, these are available to be * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions} */ var publicApi = { events: { expandable: { /** * @ngdoc event * @name rowExpandedStateChanged * @eventOf ui.grid.expandable.api:PublicApi * @description raised when cell editing is complete * <pre> * gridApi.expandable.on.rowExpandedStateChanged(scope,function(row){}) * </pre> * @param {GridRow} row the row that was expanded */ rowExpandedStateChanged: function (scope, row) { } } }, methods: { expandable: { /** * @ngdoc method * @name toggleRowExpansion * @methodOf ui.grid.expandable.api:PublicApi * @description Toggle a specific row * <pre> * gridApi.expandable.toggleRowExpansion(rowEntity); * </pre> * @param {object} rowEntity the data entity for the row you want to expand */ toggleRowExpansion: function (rowEntity) { var row = grid.getRow(rowEntity); if (row !== null) { service.toggleRowExpansion(grid, row); } }, /** * @ngdoc method * @name expandAllRows * @methodOf ui.grid.expandable.api:PublicApi * @description Expand all subgrids. * <pre> * gridApi.expandable.expandAllRows(); * </pre> */ expandAllRows: function() { service.expandAllRows(grid); }, /** * @ngdoc method * @name collapseAllRows * @methodOf ui.grid.expandable.api:PublicApi * @description Collapse all subgrids. * <pre> * gridApi.expandable.collapseAllRows(); * </pre> */ collapseAllRows: function() { service.collapseAllRows(grid); }, /** * @ngdoc method * @name toggleAllRows * @methodOf ui.grid.expandable.api:PublicApi * @description Toggle all subgrids. * <pre> * gridApi.expandable.toggleAllRows(); * </pre> */ toggleAllRows: function() { service.toggleAllRows(grid); } } } }; grid.api.registerEventsFromObject(publicApi.events); grid.api.registerMethodsFromObject(publicApi.methods); }, toggleRowExpansion: function (grid, row) { row.isExpanded = !row.isExpanded; if (row.isExpanded) { row.height = row.grid.options.rowHeight + grid.options.expandableRowHeight; } else { row.height = row.grid.options.rowHeight; grid.expandable.expandedAll = false; } grid.api.expandable.raise.rowExpandedStateChanged(row); }, expandAllRows: function(grid, $scope) { grid.renderContainers.body.visibleRowCache.forEach( function(row) { if (!row.isExpanded) { service.toggleRowExpansion(grid, row); } }); grid.expandable.expandedAll = true; grid.queueGridRefresh(); }, collapseAllRows: function(grid) { grid.renderContainers.body.visibleRowCache.forEach( function(row) { if (row.isExpanded) { service.toggleRowExpansion(grid, row); } }); grid.expandable.expandedAll = false; grid.queueGridRefresh(); }, toggleAllRows: function(grid) { if (grid.expandable.expandedAll) { service.collapseAllRows(grid); } else { service.expandAllRows(grid); } } }; return service; }]); /** * @ngdoc object * @name enableExpandableRowHeader * @propertyOf ui.grid.expandable.api:GridOptions * @description Show a rowHeader to provide the expandable buttons. If set to false then implies * you're going to use a custom method for expanding and collapsing the subgrids. Defaults to true. * @example * <pre> * $scope.gridOptions = { * enableExpandableRowHeader: false * } * </pre> */ module.directive('uiGridExpandable', ['uiGridExpandableService', '$templateCache', function (uiGridExpandableService, $templateCache) { return { replace: true, priority: 0, require: '^uiGrid', scope: false, compile: function () { return { pre: function ($scope, $elm, $attrs, uiGridCtrl) { if ( uiGridCtrl.grid.options.enableExpandableRowHeader !== false ) { var expandableRowHeaderColDef = { name: 'expandableButtons', displayName: '', exporterSuppressExport: true, enableColumnResizing: false, enableColumnMenu: false, width: uiGridCtrl.grid.options.expandableRowHeaderWidth || 40 }; expandableRowHeaderColDef.cellTemplate = $templateCache.get('ui-grid/expandableRowHeader'); expandableRowHeaderColDef.headerCellTemplate = $templateCache.get('ui-grid/expandableTopRowHeader'); uiGridCtrl.grid.addRowHeaderColumn(expandableRowHeaderColDef); } uiGridExpandableService.initializeGrid(uiGridCtrl.grid); }, post: function ($scope, $elm, $attrs, uiGridCtrl) { } }; } }; }]); /** * @ngdoc directive * @name ui.grid.expandable.directive:uiGrid * @description stacks on the uiGrid directive to register child grid with parent row when child is created */ module.directive('uiGrid', ['uiGridExpandableService', '$templateCache', function (uiGridExpandableService, $templateCache) { return { replace: true, priority: 599, require: '^uiGrid', scope: false, compile: function () { return { pre: function ($scope, $elm, $attrs, uiGridCtrl) { uiGridCtrl.grid.api.core.on.renderingComplete($scope, function() { //if a parent grid row is on the scope, then add the parentRow property to this childGrid if ($scope.row && $scope.row.grid && $scope.row.grid.options && $scope.row.grid.options.enableExpandable) { /** * @ngdoc directive * @name ui.grid.expandable.class:Grid * @description Additional Grid properties added by expandable module */ /** * @ngdoc object * @name parentRow * @propertyOf ui.grid.expandable.class:Grid * @description reference to the expanded parent row that owns this grid */ uiGridCtrl.grid.parentRow = $scope.row; //todo: adjust height on parent row when child grid height changes. we need some sort of gridHeightChanged event // uiGridCtrl.grid.core.on.canvasHeightChanged($scope, function(oldHeight, newHeight) { // uiGridCtrl.grid.parentRow = newHeight; // }); } }); }, post: function ($scope, $elm, $attrs, uiGridCtrl) { } }; } }; }]); /** * @ngdoc directive * @name ui.grid.expandable.directive:uiGridExpandableRow * @description directive to render the expandable row template */ module.directive('uiGridExpandableRow', ['uiGridExpandableService', '$timeout', '$compile', 'uiGridConstants','gridUtil','$interval', '$log', function (uiGridExpandableService, $timeout, $compile, uiGridConstants, gridUtil, $interval, $log) { return { replace: false, priority: 0, scope: false, compile: function () { return { pre: function ($scope, $elm, $attrs, uiGridCtrl) { gridUtil.getTemplate($scope.grid.options.expandableRowTemplate).then( function (template) { if ($scope.grid.options.expandableRowScope) { var expandableRowScope = $scope.grid.options.expandableRowScope; for (var property in expandableRowScope) { if (expandableRowScope.hasOwnProperty(property)) { $scope[property] = expandableRowScope[property]; } } } var expandedRowElement = $compile(template)($scope); $elm.append(expandedRowElement); $scope.row.expandedRendered = true; }); }, post: function ($scope, $elm, $attrs, uiGridCtrl) { $scope.$on('$destroy', function() { $scope.row.expandedRendered = false; }); } }; } }; }]); /** * @ngdoc directive * @name ui.grid.expandable.directive:uiGridRow * @description stacks on the uiGridRow directive to add support for expandable rows */ module.directive('uiGridRow', ['$compile', 'gridUtil', '$templateCache', function ($compile, gridUtil, $templateCache) { return { priority: -200, scope: false, compile: function ($elm, $attrs) { return { pre: function ($scope, $elm, $attrs, controllers) { $scope.expandableRow = {}; $scope.expandableRow.shouldRenderExpand = function () { var ret = $scope.colContainer.name === 'body' && $scope.grid.options.enableExpandable !== false && $scope.row.isExpanded && (!$scope.grid.isScrollingVertically || $scope.row.expandedRendered); return ret; }; $scope.expandableRow.shouldRenderFiller = function () { var ret = $scope.row.isExpanded && ( $scope.colContainer.name !== 'body' || ($scope.grid.isScrollingVertically && !$scope.row.expandedRendered)); return ret; }; /* * Commented out @PaulL1. This has no purpose that I can see, and causes #2964. If this code needs to be reinstated for some * reason it needs to use drawnWidth, not width, and needs to check column visibility. It should really use render container * visible column cache also instead of checking column.renderContainer. function updateRowContainerWidth() { var grid = $scope.grid; var colWidth = 0; grid.columns.forEach( function (column) { if (column.renderContainer === 'left') { colWidth += column.width; } }); colWidth = Math.floor(colWidth); return '.grid' + grid.id + ' .ui-grid-pinned-container-' + $scope.colContainer.name + ', .grid' + grid.id + ' .ui-grid-pinned-container-' + $scope.colContainer.name + ' .ui-grid-render-container-' + $scope.colContainer.name + ' .ui-grid-viewport .ui-grid-canvas .ui-grid-row { width: ' + colWidth + 'px; }'; } if ($scope.colContainer.name === 'left') { $scope.grid.registerStyleComputation({ priority: 15, func: updateRowContainerWidth }); }*/ }, post: function ($scope, $elm, $attrs, controllers) { } }; } }; }]); /** * @ngdoc directive * @name ui.grid.expandable.directive:uiGridViewport * @description stacks on the uiGridViewport directive to append the expandable row html elements to the * default gridRow template */ module.directive('uiGridViewport', ['$compile', 'gridUtil', '$templateCache', function ($compile, gridUtil, $templateCache) { return { priority: -200, scope: false, compile: function ($elm, $attrs) { var rowRepeatDiv = angular.element($elm.children().children()[0]); var expandedRowFillerElement = $templateCache.get('ui-grid/expandableScrollFiller'); var expandedRowElement = $templateCache.get('ui-grid/expandableRow'); rowRepeatDiv.append(expandedRowElement); rowRepeatDiv.append(expandedRowFillerElement); return { pre: function ($scope, $elm, $attrs, controllers) { }, post: function ($scope, $elm, $attrs, controllers) { } }; } }; }]); })(); /* global console */ (function () { 'use strict'; /** * @ngdoc overview * @name ui.grid.exporter * @description * * # ui.grid.exporter * * <div class="alert alert-success" role="alert"><strong>Stable</strong> This feature is stable. There should no longer be breaking api changes without a deprecation warning.</div> * * This module provides the ability to exporter data from the grid. * * Data can be exported in a range of formats, and all data, visible * data, or selected rows can be exported, with all columns or visible * columns. * * No UI is provided, the caller should provide their own UI/buttons * as appropriate, or enable the gridMenu * * <br/> * <br/> * * <div doc-module-components="ui.grid.exporter"></div> */ var module = angular.module('ui.grid.exporter', ['ui.grid']); /** * @ngdoc object * @name ui.grid.exporter.constant:uiGridExporterConstants * * @description constants available in exporter module */ /** * @ngdoc property * @propertyOf ui.grid.exporter.constant:uiGridExporterConstants * @name ALL * @description export all data, including data not visible. Can * be set for either rowTypes or colTypes */ /** * @ngdoc property * @propertyOf ui.grid.exporter.constant:uiGridExporterConstants * @name VISIBLE * @description export only visible data, including data not visible. Can * be set for either rowTypes or colTypes */ /** * @ngdoc property * @propertyOf ui.grid.exporter.constant:uiGridExporterConstants * @name SELECTED * @description export all data, including data not visible. Can * be set only for rowTypes, selection of only some columns is * not supported */ module.constant('uiGridExporterConstants', { featureName: 'exporter', ALL: 'all', VISIBLE: 'visible', SELECTED: 'selected', CSV_CONTENT: 'CSV_CONTENT', BUTTON_LABEL: 'BUTTON_LABEL', FILE_NAME: 'FILE_NAME' }); /** * @ngdoc service * @name ui.grid.exporter.service:uiGridExporterService * * @description Services for exporter feature */ module.service('uiGridExporterService', ['$q', 'uiGridExporterConstants', 'gridUtil', '$compile', '$interval', 'i18nService', function ($q, uiGridExporterConstants, gridUtil, $compile, $interval, i18nService) { var service = { delay: 100, initializeGrid: function (grid) { //add feature namespace and any properties to grid for needed state grid.exporter = {}; this.defaultGridOptions(grid.options); /** * @ngdoc object * @name ui.grid.exporter.api:PublicApi * * @description Public Api for exporter feature */ var publicApi = { events: { exporter: { } }, methods: { exporter: { /** * @ngdoc function * @name csvExport * @methodOf ui.grid.exporter.api:PublicApi * @description Exports rows from the grid in csv format, * the data exported is selected based on the provided options * @param {string} rowTypes which rows to export, valid values are * uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE, * uiGridExporterConstants.SELECTED * @param {string} colTypes which columns to export, valid values are * uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE */ csvExport: function (rowTypes, colTypes) { service.csvExport(grid, rowTypes, colTypes); }, /** * @ngdoc function * @name pdfExport * @methodOf ui.grid.exporter.api:PublicApi * @description Exports rows from the grid in pdf format, * the data exported is selected based on the provided options * Note that this function has a dependency on pdfMake, all * going well this has been installed for you. * The resulting pdf opens in a new browser window. * @param {string} rowTypes which rows to export, valid values are * uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE, * uiGridExporterConstants.SELECTED * @param {string} colTypes which columns to export, valid values are * uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE */ pdfExport: function (rowTypes, colTypes) { service.pdfExport(grid, rowTypes, colTypes); } } } }; grid.api.registerEventsFromObject(publicApi.events); grid.api.registerMethodsFromObject(publicApi.methods); if (grid.api.core.addToGridMenu){ service.addToMenu( grid ); } else { // order of registration is not guaranteed, register in a little while $interval( function() { if (grid.api.core.addToGridMenu){ service.addToMenu( grid ); } }, this.delay, 1); } }, defaultGridOptions: function (gridOptions) { //default option to true unless it was explicitly set to false /** * @ngdoc object * @name ui.grid.exporter.api:GridOptions * * @description GridOptions for exporter feature, these are available to be * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions} */ /** * @ngdoc object * @name ui.grid.exporter.api:ColumnDef * @description ColumnDef settings for exporter */ /** * @ngdoc object * @name exporterSuppressMenu * @propertyOf ui.grid.exporter.api:GridOptions * @description Don't show the export menu button, implying the user * will roll their own UI for calling the exporter * <br/>Defaults to false */ gridOptions.exporterSuppressMenu = gridOptions.exporterSuppressMenu === true; /** * @ngdoc object * @name exporterMenuLabel * @propertyOf ui.grid.exporter.api:GridOptions * @description The text to show on the exporter menu button * link * <br/>Defaults to 'Export' */ gridOptions.exporterMenuLabel = gridOptions.exporterMenuLabel ? gridOptions.exporterMenuLabel : 'Export'; /** * @ngdoc object * @name exporterSuppressColumns * @propertyOf ui.grid.exporter.api:GridOptions * @description Columns that should not be exported. The selectionRowHeader is already automatically * suppressed, but if you had a button column or some other "system" column that shouldn't be shown in the * output then add it in this list. You should provide an array of column names. * <br/>Defaults to: [] * <pre> * gridOptions.exporterSuppressColumns = [ 'buttons' ]; * </pre> */ gridOptions.exporterSuppressColumns = gridOptions.exporterSuppressColumns ? gridOptions.exporterSuppressColumns : []; /** * @ngdoc object * @name exporterCsvColumnSeparator * @propertyOf ui.grid.exporter.api:GridOptions * @description The character to use as column separator * link * <br/>Defaults to ',' */ gridOptions.exporterCsvColumnSeparator = gridOptions.exporterCsvColumnSeparator ? gridOptions.exporterCsvColumnSeparator : ','; /** * @ngdoc object * @name exporterCsvFilename * @propertyOf ui.grid.exporter.api:GridOptions * @description The default filename to use when saving the downloaded csv. * This will only work in some browsers. * <br/>Defaults to 'download.csv' */ gridOptions.exporterCsvFilename = gridOptions.exporterCsvFilename ? gridOptions.exporterCsvFilename : 'download.csv'; /** * @ngdoc object * @name exporterPdfFilename * @propertyOf ui.grid.exporter.api:GridOptions * @description The default filename to use when saving the downloaded pdf, only used in IE (other browsers open pdfs in a new window) * <br/>Defaults to 'download.pdf' */ gridOptions.exporterPdfFilename = gridOptions.exporterPdfFilename ? gridOptions.exporterPdfFilename : 'download.pdf'; /** * @ngdoc object * @name exporterOlderExcelCompatibility * @propertyOf ui.grid.exporter.api:GridOptions * @description Some versions of excel don't like the utf-16 BOM on the front, and it comes * through as  in the first column header. Setting this option to false will suppress this, at the * expense of proper utf-16 handling in applications that do recognise the BOM * <br/>Defaults to false */ gridOptions.exporterOlderExcelCompatibility = gridOptions.exporterOlderExcelCompatibility === true; /** * @ngdoc object * @name exporterPdfDefaultStyle * @propertyOf ui.grid.exporter.api:GridOptions * @description The default style in pdfMake format * <br/>Defaults to: * <pre> * { * fontSize: 11 * } * </pre> */ gridOptions.exporterPdfDefaultStyle = gridOptions.exporterPdfDefaultStyle ? gridOptions.exporterPdfDefaultStyle : { fontSize: 11 }; /** * @ngdoc object * @name exporterPdfTableStyle * @propertyOf ui.grid.exporter.api:GridOptions * @description The table style in pdfMake format * <br/>Defaults to: * <pre> * { * margin: [0, 5, 0, 15] * } * </pre> */ gridOptions.exporterPdfTableStyle = gridOptions.exporterPdfTableStyle ? gridOptions.exporterPdfTableStyle : { margin: [0, 5, 0, 15] }; /** * @ngdoc object * @name exporterPdfTableHeaderStyle * @propertyOf ui.grid.exporter.api:GridOptions * @description The tableHeader style in pdfMake format * <br/>Defaults to: * <pre> * { * bold: true, * fontSize: 12, * color: 'black' * } * </pre> */ gridOptions.exporterPdfTableHeaderStyle = gridOptions.exporterPdfTableHeaderStyle ? gridOptions.exporterPdfTableHeaderStyle : { bold: true, fontSize: 12, color: 'black' }; /** * @ngdoc object * @name exporterPdfHeader * @propertyOf ui.grid.exporter.api:GridOptions * @description The header section for pdf exports. Can be * simple text: * <pre> * gridOptions.exporterPdfHeader = 'My Header'; * </pre> * Can be a more complex object in pdfMake format: * <pre> * gridOptions.exporterPdfHeader = { * columns: [ * 'Left part', * { text: 'Right part', alignment: 'right' } * ] * }; * </pre> * Or can be a function, allowing page numbers and the like * <pre> * gridOptions.exporterPdfHeader: function(currentPage, pageCount) { return currentPage.toString() + ' of ' + pageCount; }; * </pre> */ gridOptions.exporterPdfHeader = gridOptions.exporterPdfHeader ? gridOptions.exporterPdfHeader : null; /** * @ngdoc object * @name exporterPdfFooter * @propertyOf ui.grid.exporter.api:GridOptions * @description The header section for pdf exports. Can be * simple text: * <pre> * gridOptions.exporterPdfFooter = 'My Footer'; * </pre> * Can be a more complex object in pdfMake format: * <pre> * gridOptions.exporterPdfFooter = { * columns: [ * 'Left part', * { text: 'Right part', alignment: 'right' } * ] * }; * </pre> * Or can be a function, allowing page numbers and the like * <pre> * gridOptions.exporterPdfFooter: function(currentPage, pageCount) { return currentPage.toString() + ' of ' + pageCount; }; * </pre> */ gridOptions.exporterPdfFooter = gridOptions.exporterPdfFooter ? gridOptions.exporterPdfFooter : null; /** * @ngdoc object * @name exporterPdfOrientation * @propertyOf ui.grid.exporter.api:GridOptions * @description The orientation, should be a valid pdfMake value, * 'landscape' or 'portrait' * <br/>Defaults to landscape */ gridOptions.exporterPdfOrientation = gridOptions.exporterPdfOrientation ? gridOptions.exporterPdfOrientation : 'landscape'; /** * @ngdoc object * @name exporterPdfPageSize * @propertyOf ui.grid.exporter.api:GridOptions * @description The orientation, should be a valid pdfMake * paper size, usually 'A4' or 'LETTER' * {@link https://github.com/bpampuch/pdfmake/blob/master/src/standardPageSizes.js pdfMake page sizes} * <br/>Defaults to A4 */ gridOptions.exporterPdfPageSize = gridOptions.exporterPdfPageSize ? gridOptions.exporterPdfPageSize : 'A4'; /** * @ngdoc object * @name exporterPdfMaxGridWidth * @propertyOf ui.grid.exporter.api:GridOptions * @description The maxium grid width - the current grid width * will be scaled to match this, with any fixed width columns * being adjusted accordingly. * <br/>Defaults to 720 (for A4 landscape), use 670 for LETTER */ gridOptions.exporterPdfMaxGridWidth = gridOptions.exporterPdfMaxGridWidth ? gridOptions.exporterPdfMaxGridWidth : 720; /** * @ngdoc object * @name exporterPdfTableLayout * @propertyOf ui.grid.exporter.api:GridOptions * @description A tableLayout in pdfMake format, * controls gridlines and the like. We use the default * layout usually. * <br/>Defaults to null, which means no layout */ /** * @ngdoc object * @name exporterMenuAllData * @porpertyOf ui.grid.exporter.api:GridOptions * @description Add export all data as cvs/pdf menu items to the ui-grid grid menu, if it's present. Defaults to true. */ gridOptions.exporterMenuAllData = gridOptions.exporterMenuAllData !== undefined ? gridOptions.exporterMenuAllData : true; /** * @ngdoc object * @name exporterMenuCsv * @propertyOf ui.grid.exporter.api:GridOptions * @description Add csv export menu items to the ui-grid grid menu, if it's present. Defaults to true. */ gridOptions.exporterMenuCsv = gridOptions.exporterMenuCsv !== undefined ? gridOptions.exporterMenuCsv : true; /** * @ngdoc object * @name exporterMenuPdf * @propertyOf ui.grid.exporter.api:GridOptions * @description Add pdf export menu items to the ui-grid grid menu, if it's present. Defaults to true. */ gridOptions.exporterMenuPdf = gridOptions.exporterMenuPdf !== undefined ? gridOptions.exporterMenuPdf : true; /** * @ngdoc object * @name exporterPdfCustomFormatter * @propertyOf ui.grid.exporter.api:GridOptions * @description A custom callback routine that changes the pdf document, adding any * custom styling or content that is supported by pdfMake. Takes in the complete docDefinition, and * must return an updated docDefinition ready for pdfMake. * @example * In this example we add a style to the style array, so that we can use it in our * footer definition. * <pre> * gridOptions.exporterPdfCustomFormatter = function ( docDefinition ) { * docDefinition.styles.footerStyle = { bold: true, fontSize: 10 }; * return docDefinition; * } * * gridOptions.exporterPdfFooter = { text: 'My footer', style: 'footerStyle' } * </pre> */ gridOptions.exporterPdfCustomFormatter = ( gridOptions.exporterPdfCustomFormatter && typeof( gridOptions.exporterPdfCustomFormatter ) === 'function' ) ? gridOptions.exporterPdfCustomFormatter : function ( docDef ) { return docDef; }; /** * @ngdoc object * @name exporterHeaderFilterUseName * @propertyOf ui.grid.exporter.api:GridOptions * @description Defaults to false, which leads to `displayName` being passed into the headerFilter. * If set to true, then will pass `name` instead. * * * @example * <pre> * gridOptions.exporterHeaderFilterUseName = true; * </pre> */ gridOptions.exporterHeaderFilterUseName = gridOptions.exporterHeaderFilterUseName === true; /** * @ngdoc object * @name exporterHeaderFilter * @propertyOf ui.grid.exporter.api:GridOptions * @description A function to apply to the header displayNames before exporting. Useful for internationalisation, * for example if you were using angular-translate you'd set this to `$translate.instant`. Note that this * call must be synchronous, it cannot be a call that returns a promise. * * Behaviour can be changed to pass in `name` instead of `displayName` through use of `exporterHeaderFilterUseName: true`. * * @example * <pre> * gridOptions.exporterHeaderFilter = function( displayName ){ return 'col: ' + name; }; * </pre> * OR * <pre> * gridOptions.exporterHeaderFilter = $translate.instant; * </pre> */ /** * @ngdoc function * @name exporterFieldCallback * @propertyOf ui.grid.exporter.api:GridOptions * @description A function to call for each field before exporting it. Allows * massaging of raw data into a display format, for example if you have applied * filters to convert codes into decodes, or you require * a specific date format in the exported content. * * The method is called once for each field exported, and provides the grid, the * gridCol and the GridRow for you to use as context in massaging the data. * * @param {Grid} grid provides the grid in case you have need of it * @param {GridRow} row the row from which the data comes * @param {GridCol} col the column from which the data comes * @param {object} value the value for your massaging * @returns {object} you must return the massaged value ready for exporting * * @example * <pre> * gridOptions.exporterFieldCallback = function ( grid, row, col, value ){ * if ( col.name === 'status' ){ * value = decodeStatus( value ); * } * return value; * } * </pre> */ gridOptions.exporterFieldCallback = gridOptions.exporterFieldCallback ? gridOptions.exporterFieldCallback : function( grid, row, col, value ) { return value; }; /** * @ngdoc function * @name exporterAllDataFn * @propertyOf ui.grid.exporter.api:GridOptions * @description This promise is needed when exporting all rows, * and the data need to be provided by server side. Default is null. * @returns {Promise} a promise to load all data from server * * @example * <pre> * gridOptions.exporterAllDataFn = function () { * return $http.get('/data/100.json') * } * </pre> */ gridOptions.exporterAllDataFn = gridOptions.exporterAllDataFn ? gridOptions.exporterAllDataFn : null; /** * @ngdoc function * @name exporterAllDataPromise * @propertyOf ui.grid.exporter.api:GridOptions * @description DEPRECATED - exporterAllDataFn used to be * called this, but it wasn't a promise, it was a function that returned * a promise. Deprecated, but supported for backward compatibility, use * exporterAllDataFn instead. * @returns {Promise} a promise to load all data from server * * @example * <pre> * gridOptions.exporterAllDataFn = function () { * return $http.get('/data/100.json') * } * </pre> */ if ( gridOptions.exporterAllDataFn == null && gridOptions.exporterAllDataPromise ) { gridOptions.exporterAllDataFn = gridOptions.exporterAllDataPromise; } }, /** * @ngdoc function * @name addToMenu * @methodOf ui.grid.exporter.service:uiGridExporterService * @description Adds export items to the grid menu, * allowing the user to select export options * @param {Grid} grid the grid from which data should be exported */ addToMenu: function ( grid ) { grid.api.core.addToGridMenu( grid, [ { title: i18nService.getSafeText('gridMenu.exporterAllAsCsv'), action: function ($event) { this.grid.api.exporter.csvExport( uiGridExporterConstants.ALL, uiGridExporterConstants.ALL ); }, shown: function() { return this.grid.options.exporterMenuCsv && this.grid.options.exporterMenuAllData; }, order: 200 }, { title: i18nService.getSafeText('gridMenu.exporterVisibleAsCsv'), action: function ($event) { this.grid.api.exporter.csvExport( uiGridExporterConstants.VISIBLE, uiGridExporterConstants.VISIBLE ); }, shown: function() { return this.grid.options.exporterMenuCsv; }, order: 201 }, { title: i18nService.getSafeText('gridMenu.exporterSelectedAsCsv'), action: function ($event) { this.grid.api.exporter.csvExport( uiGridExporterConstants.SELECTED, uiGridExporterConstants.VISIBLE ); }, shown: function() { return this.grid.options.exporterMenuCsv && ( this.grid.api.selection && this.grid.api.selection.getSelectedRows().length > 0 ); }, order: 202 }, { title: i18nService.getSafeText('gridMenu.exporterAllAsPdf'), action: function ($event) { this.grid.api.exporter.pdfExport( uiGridExporterConstants.ALL, uiGridExporterConstants.ALL ); }, shown: function() { return this.grid.options.exporterMenuPdf && this.grid.options.exporterMenuAllData; }, order: 203 }, { title: i18nService.getSafeText('gridMenu.exporterVisibleAsPdf'), action: function ($event) { this.grid.api.exporter.pdfExport( uiGridExporterConstants.VISIBLE, uiGridExporterConstants.VISIBLE ); }, shown: function() { return this.grid.options.exporterMenuPdf; }, order: 204 }, { title: i18nService.getSafeText('gridMenu.exporterSelectedAsPdf'), action: function ($event) { this.grid.api.exporter.pdfExport( uiGridExporterConstants.SELECTED, uiGridExporterConstants.VISIBLE ); }, shown: function() { return this.grid.options.exporterMenuPdf && ( this.grid.api.selection && this.grid.api.selection.getSelectedRows().length > 0 ); }, order: 205 } ]); }, /** * @ngdoc function * @name csvExport * @methodOf ui.grid.exporter.service:uiGridExporterService * @description Exports rows from the grid in csv format, * the data exported is selected based on the provided options * @param {Grid} grid the grid from which data should be exported * @param {string} rowTypes which rows to export, valid values are * uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE, * uiGridExporterConstants.SELECTED * @param {string} colTypes which columns to export, valid values are * uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE, * uiGridExporterConstants.SELECTED */ csvExport: function (grid, rowTypes, colTypes) { var self = this; this.loadAllDataIfNeeded(grid, rowTypes, colTypes).then(function() { var exportColumnHeaders = self.getColumnHeaders(grid, colTypes); var exportData = self.getData(grid, rowTypes, colTypes); var csvContent = self.formatAsCsv(exportColumnHeaders, exportData, grid.options.exporterCsvColumnSeparator); self.downloadFile (grid.options.exporterCsvFilename, csvContent, grid.options.exporterOlderExcelCompatibility); }); }, /** * @ngdoc function * @name loadAllDataIfNeeded * @methodOf ui.grid.exporter.service:uiGridExporterService * @description When using server side pagination, use exporterAllDataFn to * load all data before continuing processing. * When using client side pagination, return a resolved promise so processing * continues immediately * @param {Grid} grid the grid from which data should be exported * @param {string} rowTypes which rows to export, valid values are * uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE, * uiGridExporterConstants.SELECTED * @param {string} colTypes which columns to export, valid values are * uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE, * uiGridExporterConstants.SELECTED */ loadAllDataIfNeeded: function (grid, rowTypes, colTypes) { if ( rowTypes === uiGridExporterConstants.ALL && grid.rows.length !== grid.options.totalItems && grid.options.exporterAllDataFn) { return grid.options.exporterAllDataFn() .then(function() { grid.modifyRows(grid.options.data); }); } else { var deferred = $q.defer(); deferred.resolve(); return deferred.promise; } }, /** * @ngdoc property * @propertyOf ui.grid.exporter.api:ColumnDef * @name exporterSuppressExport * @description Suppresses export for this column. Used by selection and expandable. */ /** * @ngdoc function * @name getColumnHeaders * @methodOf ui.grid.exporter.service:uiGridExporterService * @description Gets the column headers from the grid to use * as a title row for the exported file, all headers have * headerCellFilters applied as appropriate. * * Column headers are an array of objects, each object has * name, displayName, width and align attributes. Only name is * used for csv, all attributes are used for pdf. * * @param {Grid} grid the grid from which data should be exported * @param {string} colTypes which columns to export, valid values are * uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE, * uiGridExporterConstants.SELECTED */ getColumnHeaders: function (grid, colTypes) { var headers = []; var columns; if ( colTypes === uiGridExporterConstants.ALL ){ columns = grid.columns; } else { var leftColumns = grid.renderContainers.left ? grid.renderContainers.left.visibleColumnCache.filter( function( column ){ return column.visible; } ) : []; var bodyColumns = grid.renderContainers.body ? grid.renderContainers.body.visibleColumnCache.filter( function( column ){ return column.visible; } ) : []; var rightColumns = grid.renderContainers.right ? grid.renderContainers.right.visibleColumnCache.filter( function( column ){ return column.visible; } ) : []; columns = leftColumns.concat(bodyColumns,rightColumns); } columns.forEach( function( gridCol, index ) { if ( gridCol.colDef.exporterSuppressExport !== true && grid.options.exporterSuppressColumns.indexOf( gridCol.name ) === -1 ){ headers.push({ name: gridCol.field, displayName: grid.options.exporterHeaderFilter ? ( grid.options.exporterHeaderFilterUseName ? grid.options.exporterHeaderFilter(gridCol.name) : grid.options.exporterHeaderFilter(gridCol.displayName) ) : gridCol.displayName, width: gridCol.drawnWidth ? gridCol.drawnWidth : gridCol.width, align: gridCol.colDef.type === 'number' ? 'right' : 'left' }); } }); return headers; }, /** * @ngdoc property * @propertyOf ui.grid.exporter.api:ColumnDef * @name exporterPdfAlign * @description the alignment you'd like for this specific column when * exported into a pdf. Can be 'left', 'right', 'center' or any other * valid pdfMake alignment option. */ /** * @ngdoc object * @name ui.grid.exporter.api:GridRow * @description GridRow settings for exporter */ /** * @ngdoc object * @name exporterEnableExporting * @propertyOf ui.grid.exporter.api:GridRow * @description If set to false, then don't export this row, notwithstanding visible or * other settings * <br/>Defaults to true */ /** * @ngdoc function * @name getData * @methodOf ui.grid.exporter.service:uiGridExporterService * @description Gets data from the grid based on the provided options, * all cells have cellFilters applied as appropriate. Any rows marked * `exporterEnableExporting: false` will not be exported * @param {Grid} grid the grid from which data should be exported * @param {string} rowTypes which rows to export, valid values are * uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE, * uiGridExporterConstants.SELECTED * @param {string} colTypes which columns to export, valid values are * uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE, * uiGridExporterConstants.SELECTED */ getData: function (grid, rowTypes, colTypes) { var data = []; var rows; var columns; switch ( rowTypes ) { case uiGridExporterConstants.ALL: rows = grid.rows; break; case uiGridExporterConstants.VISIBLE: rows = grid.getVisibleRows(); break; case uiGridExporterConstants.SELECTED: if ( grid.api.selection ){ rows = grid.api.selection.getSelectedGridRows(); } else { gridUtil.logError('selection feature must be enabled to allow selected rows to be exported'); } break; } if ( colTypes === uiGridExporterConstants.ALL ){ columns = grid.columns; } else { var leftColumns = grid.renderContainers.left ? grid.renderContainers.left.visibleColumnCache.filter( function( column ){ return column.visible; } ) : []; var bodyColumns = grid.renderContainers.body ? grid.renderContainers.body.visibleColumnCache.filter( function( column ){ return column.visible; } ) : []; var rightColumns = grid.renderContainers.right ? grid.renderContainers.right.visibleColumnCache.filter( function( column ){ return column.visible; } ) : []; columns = leftColumns.concat(bodyColumns,rightColumns); } rows.forEach( function( row, index ) { if (row.exporterEnableExporting !== false) { var extractedRow = []; columns.forEach( function( gridCol, index ) { if ( (gridCol.visible || colTypes === uiGridExporterConstants.ALL ) && gridCol.colDef.exporterSuppressExport !== true && grid.options.exporterSuppressColumns.indexOf( gridCol.name ) === -1 ){ var extractedField = { value: grid.options.exporterFieldCallback( grid, row, gridCol, grid.getCellValue( row, gridCol ) ) }; if ( gridCol.colDef.exporterPdfAlign ) { extractedField.alignment = gridCol.colDef.exporterPdfAlign; } extractedRow.push(extractedField); } }); data.push(extractedRow); } }); return data; }, /** * @ngdoc function * @name formatAsCSV * @methodOf ui.grid.exporter.service:uiGridExporterService * @description Formats the column headers and data as a CSV, * and sends that data to the user * @param {array} exportColumnHeaders an array of column headers, * where each header is an object with name, width and maybe alignment * @param {array} exportData an array of rows, where each row is * an array of column data * @returns {string} csv the formatted csv as a string */ formatAsCsv: function (exportColumnHeaders, exportData, separator) { var self = this; var bareHeaders = exportColumnHeaders.map(function(header){return { value: header.displayName };}); var csv = self.formatRowAsCsv(this, separator)(bareHeaders) + '\n'; csv += exportData.map(this.formatRowAsCsv(this, separator)).join('\n'); return csv; }, /** * @ngdoc function * @name formatRowAsCsv * @methodOf ui.grid.exporter.service:uiGridExporterService * @description Renders a single field as a csv field, including * quotes around the value * @param {exporterService} exporter pass in exporter * @param {array} row the row to be turned into a csv string * @returns {string} a csv-ified version of the row */ formatRowAsCsv: function (exporter, separator) { return function (row) { return row.map(exporter.formatFieldAsCsv).join(separator); }; }, /** * @ngdoc function * @name formatFieldAsCsv * @methodOf ui.grid.exporter.service:uiGridExporterService * @description Renders a single field as a csv field, including * quotes around the value * @param {field} field the field to be turned into a csv string, * may be of any type * @returns {string} a csv-ified version of the field */ formatFieldAsCsv: function (field) { if (field.value == null) { // we want to catch anything null-ish, hence just == not === return ''; } if (typeof(field.value) === 'number') { return field.value; } if (typeof(field.value) === 'boolean') { return (field.value ? 'TRUE' : 'FALSE') ; } if (typeof(field.value) === 'string') { return '"' + field.value.replace(/"/g,'""') + '"'; } return JSON.stringify(field.value); }, /** * @ngdoc function * @name isIE * @methodOf ui.grid.exporter.service:uiGridExporterService * @description Checks whether current browser is IE and returns it's version if it is */ isIE: function () { var match = navigator.userAgent.match(/(?:MSIE |Trident\/.*; rv:)(\d+)/); return match ? parseInt(match[1]) : false; }, /** * @ngdoc function * @name downloadFile * @methodOf ui.grid.exporter.service:uiGridExporterService * @description Triggers download of a csv file. Logic provided * by @cssensei (from his colleagues at https://github.com/ifeelgoods) in issue #2391 * @param {string} fileName the filename we'd like our file to be * given * @param {string} csvContent the csv content that we'd like to * download as a file * @param {boolean} exporterOlderExcelCompatibility whether or not we put a utf-16 BOM on the from (\uFEFF) */ downloadFile: function (fileName, csvContent, exporterOlderExcelCompatibility) { var D = document; var a = D.createElement('a'); var strMimeType = 'application/octet-stream;charset=utf-8'; var rawFile; var ieVersion; ieVersion = this.isIE(); if (ieVersion && ieVersion < 10) { var frame = D.createElement('iframe'); document.body.appendChild(frame); frame.contentWindow.document.open("text/html", "replace"); frame.contentWindow.document.write('sep=,\r\n' + csvContent); frame.contentWindow.document.close(); frame.contentWindow.focus(); frame.contentWindow.document.execCommand('SaveAs', true, fileName); document.body.removeChild(frame); return true; } // IE10+ if (navigator.msSaveBlob) { return navigator.msSaveOrOpenBlob( new Blob( [exporterOlderExcelCompatibility ? "\uFEFF" : '', csvContent], { type: strMimeType } ), fileName ); } //html5 A[download] if ('download' in a) { var blob = new Blob( [exporterOlderExcelCompatibility ? "\uFEFF" : '', csvContent], { type: strMimeType } ); rawFile = URL.createObjectURL(blob); a.setAttribute('download', fileName); } else { rawFile = 'data:' + strMimeType + ',' + encodeURIComponent(csvContent); a.setAttribute('target', '_blank'); } a.href = rawFile; a.setAttribute('style', 'display:none;'); D.body.appendChild(a); setTimeout(function() { if (a.click) { a.click(); // Workaround for Safari 5 } else if (document.createEvent) { var eventObj = document.createEvent('MouseEvents'); eventObj.initEvent('click', true, true); a.dispatchEvent(eventObj); } D.body.removeChild(a); }, this.delay); }, /** * @ngdoc function * @name pdfExport * @methodOf ui.grid.exporter.service:uiGridExporterService * @description Exports rows from the grid in pdf format, * the data exported is selected based on the provided options. * Note that this function has a dependency on pdfMake, which must * be installed. The resulting pdf opens in a new * browser window. * @param {Grid} grid the grid from which data should be exported * @param {string} rowTypes which rows to export, valid values are * uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE, * uiGridExporterConstants.SELECTED * @param {string} colTypes which columns to export, valid values are * uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE, * uiGridExporterConstants.SELECTED */ pdfExport: function (grid, rowTypes, colTypes) { var self = this; this.loadAllDataIfNeeded(grid, rowTypes, colTypes).then(function () { var exportColumnHeaders = self.getColumnHeaders(grid, colTypes); var exportData = self.getData(grid, rowTypes, colTypes); var docDefinition = self.prepareAsPdf(grid, exportColumnHeaders, exportData); if (self.isIE()) { self.downloadPDF(grid.options.exporterPdfFilename, docDefinition); } else { pdfMake.createPdf(docDefinition).open(); } }); }, /** * @ngdoc function * @name downloadPdf * @methodOf ui.grid.exporter.service:uiGridExporterService * @description Generates and retrieves the pdf as a blob, then downloads * it as a file. Only used in IE, in all other browsers we use the native * pdfMake.open function to just open the PDF * @param {string} fileName the filename to give to the pdf, can be set * through exporterPdfFilename * @param {object} docDefinition a pdf docDefinition that we can generate * and get a blob from */ downloadPDF: function (fileName, docDefinition) { var D = document; var a = D.createElement('a'); var strMimeType = 'application/octet-stream;charset=utf-8'; var rawFile; var ieVersion; ieVersion = this.isIE(); var doc = pdfMake.createPdf(docDefinition); var blob; doc.getBuffer( function (buffer) { blob = new Blob([buffer]); if (ieVersion && ieVersion < 10) { var frame = D.createElement('iframe'); document.body.appendChild(frame); frame.contentWindow.document.open("text/html", "replace"); frame.contentWindow.document.write(blob); frame.contentWindow.document.close(); frame.contentWindow.focus(); frame.contentWindow.document.execCommand('SaveAs', true, fileName); document.body.removeChild(frame); return true; } // IE10+ if (navigator.msSaveBlob) { return navigator.msSaveBlob( blob, fileName ); } }); }, /** * @ngdoc function * @name renderAsPdf * @methodOf ui.grid.exporter.service:uiGridExporterService * @description Renders the data into a pdf, and opens that pdf. * * @param {Grid} grid the grid from which data should be exported * @param {array} exportColumnHeaders an array of column headers, * where each header is an object with name, width and maybe alignment * @param {array} exportData an array of rows, where each row is * an array of column data * @returns {object} a pdfMake format document definition, ready * for generation */ prepareAsPdf: function(grid, exportColumnHeaders, exportData) { var headerWidths = this.calculatePdfHeaderWidths( grid, exportColumnHeaders ); var headerColumns = exportColumnHeaders.map( function( header ) { return { text: header.displayName, style: 'tableHeader' }; }); var stringData = exportData.map(this.formatRowAsPdf(this)); var allData = [headerColumns].concat(stringData); var docDefinition = { pageOrientation: grid.options.exporterPdfOrientation, pageSize: grid.options.exporterPdfPageSize, content: [{ style: 'tableStyle', table: { headerRows: 1, widths: headerWidths, body: allData } }], styles: { tableStyle: grid.options.exporterPdfTableStyle, tableHeader: grid.options.exporterPdfTableHeaderStyle }, defaultStyle: grid.options.exporterPdfDefaultStyle }; if ( grid.options.exporterPdfLayout ){ docDefinition.layout = grid.options.exporterPdfLayout; } if ( grid.options.exporterPdfHeader ){ docDefinition.header = grid.options.exporterPdfHeader; } if ( grid.options.exporterPdfFooter ){ docDefinition.footer = grid.options.exporterPdfFooter; } if ( grid.options.exporterPdfCustomFormatter ){ docDefinition = grid.options.exporterPdfCustomFormatter( docDefinition ); } return docDefinition; }, /** * @ngdoc function * @name calculatePdfHeaderWidths * @methodOf ui.grid.exporter.service:uiGridExporterService * @description Determines the column widths base on the * widths we got from the grid. If the column is drawn * then we have a drawnWidth. If the column is not visible * then we have '*', 'x%' or a width. When columns are * not visible they don't contribute to the overall gridWidth, * so we need to adjust to allow for extra columns * * Our basic heuristic is to take the current gridWidth, plus * numeric columns and call this the base gridwidth. * * To that we add 100 for any '*' column, and x% of the base gridWidth * for any column that is a % * * @param {Grid} grid the grid from which data should be exported * @param {array} exportHeaders array of header information * @returns {object} an array of header widths */ calculatePdfHeaderWidths: function ( grid, exportHeaders ) { var baseGridWidth = 0; exportHeaders.forEach( function(value){ if (typeof(value.width) === 'number'){ baseGridWidth += value.width; } }); var extraColumns = 0; exportHeaders.forEach( function(value){ if (value.width === '*'){ extraColumns += 100; } if (typeof(value.width) === 'string' && value.width.match(/(\d)*%/)) { var percent = parseInt(value.width.match(/(\d)*%/)[0]); value.width = baseGridWidth * percent / 100; extraColumns += value.width; } }); var gridWidth = baseGridWidth + extraColumns; return exportHeaders.map(function( header ) { return header.width === '*' ? header.width : header.width * grid.options.exporterPdfMaxGridWidth / gridWidth; }); }, /** * @ngdoc function * @name formatRowAsPdf * @methodOf ui.grid.exporter.service:uiGridExporterService * @description Renders a row in a format consumable by PDF, * mainly meaning casting everything to a string * @param {exporterService} exporter pass in exporter * @param {array} row the row to be turned into a csv string * @returns {string} a csv-ified version of the row */ formatRowAsPdf: function ( exporter ) { return function( row ) { return row.map(exporter.formatFieldAsPdfString); }; }, /** * @ngdoc function * @name formatFieldAsCsv * @methodOf ui.grid.exporter.service:uiGridExporterService * @description Renders a single field as a pdf-able field, which * is different from a csv field only in that strings don't have quotes * around them * @param {field} field the field to be turned into a pdf string, * may be of any type * @returns {string} a string-ified version of the field */ formatFieldAsPdfString: function (field) { var returnVal; if (field.value == null) { // we want to catch anything null-ish, hence just == not === returnVal = ''; } else if (typeof(field.value) === 'number') { returnVal = field.value.toString(); } else if (typeof(field.value) === 'boolean') { returnVal = (field.value ? 'TRUE' : 'FALSE') ; } else if (typeof(field.value) === 'string') { returnVal = field.value.replace(/"/g,'""'); } else { returnVal = JSON.stringify(field.value).replace(/^"/,'').replace(/"$/,''); } if (field.alignment && typeof(field.alignment) === 'string' ){ returnVal = { text: returnVal, alignment: field.alignment }; } return returnVal; } }; return service; } ]); /** * @ngdoc directive * @name ui.grid.exporter.directive:uiGridExporter * @element div * @restrict A * * @description Adds exporter features to grid * * @example <example module="app"> <file name="app.js"> var app = angular.module('app', ['ui.grid', 'ui.grid.exporter']); app.controller('MainCtrl', ['$scope', function ($scope) { $scope.data = [ { name: 'Bob', title: 'CEO' }, { name: 'Frank', title: 'Lowly Developer' } ]; $scope.gridOptions = { enableGridMenu: true, exporterMenuCsv: false, columnDefs: [ {name: 'name', enableCellEdit: true}, {name: 'title', enableCellEdit: true} ], data: $scope.data }; }]); </file> <file name="index.html"> <div ng-controller="MainCtrl"> <div ui-grid="gridOptions" ui-grid-exporter></div> </div> </file> </example> */ module.directive('uiGridExporter', ['uiGridExporterConstants', 'uiGridExporterService', 'gridUtil', '$compile', function (uiGridExporterConstants, uiGridExporterService, gridUtil, $compile) { return { replace: true, priority: 0, require: '^uiGrid', scope: false, link: function ($scope, $elm, $attrs, uiGridCtrl) { uiGridExporterService.initializeGrid(uiGridCtrl.grid); uiGridCtrl.grid.exporter.$scope = $scope; } }; } ]); })(); (function () { 'use strict'; /** * @ngdoc overview * @name ui.grid.grouping * @description * * # ui.grid.grouping * * <div class="alert alert-warning" role="alert"><strong>Beta</strong> This feature is ready for testing, but it either hasn't seen a lot of use or has some known bugs.</div> * * This module provides grouping of rows based on the data in them, similar * in concept to excel grouping. You can group multiple columns, resulting in * nested grouping. * * In concept this feature is similar to sorting + grid footer/aggregation, it * sorts the data based on the grouped columns, then creates group rows that * reflect a break in the data. Each of those group rows can have aggregations for * the data within that group. * * This feature leverages treeBase to provide the tree functionality itself, * the key thing this feature does therefore is to set treeLevels on the rows * and insert the group headers. * * Design information: * ------------------- * * Each column will get new menu items - group by, and aggregate by. Group by * will cause this column to be sorted (if not already), and will move this column * to the front of the sorted columns (i.e. grouped columns take precedence over * sorted columns). It will respect the sort order already set if there is one, * and it will allow the sorting logic to change that sort order, it just forces * the column to the front of the sorting. You can group by multiple columns, the * logic will add this column to the sorting after any already grouped columns. * * Once a grouping is defined, grouping logic is added to the rowsProcessors. This * will process the rows, identifying a break in the data value, and inserting a grouping row. * Grouping rows have specific attributes on them: * * - internalRow = true: tells us that this isn't a real row, so we can ignore it * from any processing that it looking at core data rows. This is used by the core * logic (or will be one day), as it's not grouping specific * - groupHeader = true: tells us this is a groupHeader. This is used by the grouping logic * to know if this is a groupHeader row or not * * Since the logic is baked into the rowsProcessors, it should get triggered whenever * row order or filtering or anything like that is changed. In order to avoid the row instantiation * time, and to preserve state across invocations, we hold a cache of the rows that we created * last time, and we use them again this time if we can. * * By default rows are collapsed, which means all data rows have their visible property * set to false, and only level 0 group rows are set to visible. * * <br/> * <br/> * * <div doc-module-components="ui.grid.grouping"></div> */ var module = angular.module('ui.grid.grouping', ['ui.grid', 'ui.grid.treeBase']); /** * @ngdoc object * @name ui.grid.grouping.constant:uiGridGroupingConstants * * @description constants available in grouping module, this includes * all the constants declared in the treeBase module (these are manually copied * as there isn't an easy way to include constants in another constants file, and * we don't want to make users include treeBase) * */ module.constant('uiGridGroupingConstants', { featureName: "grouping", rowHeaderColName: 'treeBaseRowHeaderCol', EXPANDED: 'expanded', COLLAPSED: 'collapsed', aggregation: { COUNT: 'count', SUM: 'sum', MAX: 'max', MIN: 'min', AVG: 'avg' } }); /** * @ngdoc service * @name ui.grid.grouping.service:uiGridGroupingService * * @description Services for grouping features */ module.service('uiGridGroupingService', ['$q', 'uiGridGroupingConstants', 'gridUtil', 'rowSorter', 'GridRow', 'gridClassFactory', 'i18nService', 'uiGridConstants', 'uiGridTreeBaseService', function ($q, uiGridGroupingConstants, gridUtil, rowSorter, GridRow, gridClassFactory, i18nService, uiGridConstants, uiGridTreeBaseService) { var service = { initializeGrid: function (grid, $scope) { uiGridTreeBaseService.initializeGrid( grid, $scope ); //add feature namespace and any properties to grid for needed /** * @ngdoc object * @name ui.grid.grouping.grid:grouping * * @description Grid properties and functions added for grouping */ grid.grouping = {}; /** * @ngdoc property * @propertyOf ui.grid.grouping.grid:grouping * @name groupHeaderCache * * @description Cache that holds the group header rows we created last time, we'll * reuse these next time, not least because they hold our expanded states. * * We need to take care with these that they don't become a memory leak, we * create a new cache each time using the values from the old cache. This works * so long as we're creating group rows for invisible rows as well. * * The cache is a nested hash, indexed on the value we grouped by. So if we * grouped by gender then age, we'd maybe have something like: * ``` * { * male: { * row: <pointer to the old row>, * children: { * 22: { row: <pointer to the old row> }, * 31: { row: <pointer to the old row> } * }, * female: { * row: <pointer to the old row>, * children: { * 28: { row: <pointer to the old row> }, * 55: { row: <pointer to the old row> } * } * } * ``` * * We create new rows for any missing rows, this means that they come in as collapsed. * */ grid.grouping.groupHeaderCache = {}; service.defaultGridOptions(grid.options); grid.registerRowsProcessor(service.groupRows, 400); grid.registerColumnBuilder( service.groupingColumnBuilder); grid.registerColumnsProcessor(service.groupingColumnProcessor, 400); /** * @ngdoc object * @name ui.grid.grouping.api:PublicApi * * @description Public Api for grouping feature */ var publicApi = { events: { grouping: { /** * @ngdoc event * @eventOf ui.grid.grouping.api:PublicApi * @name aggregationChanged * @description raised whenever aggregation is changed, added or removed from a column * * <pre> * gridApi.grouping.on.aggregationChanged(scope,function(col){}) * </pre> * @param {gridCol} col the column which on which aggregation changed. The aggregation * type is available as `col.treeAggregation.type` */ aggregationChanged: {}, /** * @ngdoc event * @eventOf ui.grid.grouping.api:PublicApi * @name groupingChanged * @description raised whenever the grouped columns changes * * <pre> * gridApi.grouping.on.groupingChanged(scope,function(col){}) * </pre> * @param {gridCol} col the column which on which grouping changed. The new grouping is * available as `col.grouping` */ groupingChanged: {} } }, methods: { grouping: { /** * @ngdoc function * @name getGrouping * @methodOf ui.grid.grouping.api:PublicApi * @description Get the grouping configuration for this grid, * used by the saveState feature. Adds expandedState to the information * provided by the internal getGrouping, and removes any aggregations that have a source * of grouping (i.e. will be automatically reapplied when we regroup the column) * Returned grouping is an object * `{ grouping: groupArray, treeAggregations: aggregateArray, expandedState: hash }` * where grouping contains an array of objects: * `{ field: column.field, colName: column.name, groupPriority: column.grouping.groupPriority }` * and aggregations contains an array of objects: * `{ field: column.field, colName: column.name, aggregation: column.grouping.aggregation }` * and expandedState is a hash of the currently expanded nodes * * The groupArray will be sorted by groupPriority. * * @param {boolean} getExpanded whether or not to return the expanded state * @returns {object} grouping configuration */ getGrouping: function ( getExpanded ) { var grouping = service.getGrouping(grid); grouping.grouping.forEach( function( group ) { group.colName = group.col.name; delete group.col; }); grouping.aggregations.forEach( function( aggregation ) { aggregation.colName = aggregation.col.name; delete aggregation.col; }); grouping.aggregations = grouping.aggregations.filter( function( aggregation ){ return !aggregation.aggregation.source || aggregation.aggregation.source !== 'grouping'; }); if ( getExpanded ){ grouping.rowExpandedStates = service.getRowExpandedStates( grid.grouping.groupingHeaderCache ); } return grouping; }, /** * @ngdoc function * @name setGrouping * @methodOf ui.grid.grouping.api:PublicApi * @description Set the grouping configuration for this grid, * used by the saveState feature, but can also be used by any * user to specify a combined grouping and aggregation configuration * @param {object} config the config you want to apply, in the format * provided out by getGrouping */ setGrouping: function ( config ) { service.setGrouping(grid, config); }, /** * @ngdoc function * @name groupColumn * @methodOf ui.grid.grouping.api:PublicApi * @description Adds this column to the existing grouping, at the end of the priority order. * If the column doesn't have a sort, adds one, by default ASC * * This column will move to the left of any non-group columns, the * move is handled in a columnProcessor, so gets called as part of refresh * * @param {string} columnName the name of the column we want to group */ groupColumn: function( columnName ) { var column = grid.getColumn(columnName); service.groupColumn(grid, column); }, /** * @ngdoc function * @name ungroupColumn * @methodOf ui.grid.grouping.api:PublicApi * @description Removes the groupPriority from this column. If the * column was previously aggregated the aggregation will come back. * The sort will remain. * * This column will move to the right of any other group columns, the * move is handled in a columnProcessor, so gets called as part of refresh * * @param {string} columnName the name of the column we want to ungroup */ ungroupColumn: function( columnName ) { var column = grid.getColumn(columnName); service.ungroupColumn(grid, column); }, /** * @ngdoc function * @name clearGrouping * @methodOf ui.grid.grouping.api:PublicApi * @description Clear any grouped columns and any aggregations. Doesn't remove sorting, * as we don't know whether that sorting was added by grouping or was there beforehand * */ clearGrouping: function() { service.clearGrouping(grid); }, /** * @ngdoc function * @name aggregateColumn * @methodOf ui.grid.grouping.api:PublicApi * @description Sets the aggregation type on a column, if the * column is currently grouped then it removes the grouping first. * If the aggregationDef is null then will result in the aggregation * being removed * * @param {string} columnName the column we want to aggregate * @param {string} or {function} aggregationDef one of the recognised types * from uiGridGroupingConstants or a custom aggregation function. * @param {string} aggregationLabel (optional) The label to use for this aggregation. */ aggregateColumn: function( columnName, aggregationDef, aggregationLabel){ var column = grid.getColumn(columnName); service.aggregateColumn( grid, column, aggregationDef, aggregationLabel); } } } }; grid.api.registerEventsFromObject(publicApi.events); grid.api.registerMethodsFromObject(publicApi.methods); grid.api.core.on.sortChanged( $scope, service.tidyPriorities); }, defaultGridOptions: function (gridOptions) { //default option to true unless it was explicitly set to false /** * @ngdoc object * @name ui.grid.grouping.api:GridOptions * * @description GridOptions for grouping feature, these are available to be * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions} */ /** * @ngdoc object * @name enableGrouping * @propertyOf ui.grid.grouping.api:GridOptions * @description Enable row grouping for entire grid. * <br/>Defaults to true */ gridOptions.enableGrouping = gridOptions.enableGrouping !== false; /** * @ngdoc object * @name groupingShowCounts * @propertyOf ui.grid.grouping.api:GridOptions * @description shows counts on the groupHeader rows. Not that if you are using a cellFilter or a * sortingAlgorithm which relies on a specific format or data type, showing counts may cause that * to break, since the group header rows will always be a string with groupingShowCounts enabled. * <br/>Defaults to true except on columns of type 'date' */ gridOptions.groupingShowCounts = gridOptions.groupingShowCounts !== false; /** * @ngdoc object * @name groupingNullLabel * @propertyOf ui.grid.grouping.api:GridOptions * @description The string to use for the grouping header row label on rows which contain a null or undefined value in the grouped column. * <br/>Defaults to "Null" */ gridOptions.groupingNullLabel = typeof(gridOptions.groupingNullLabel) === 'undefined' ? 'Null' : gridOptions.groupingNullLabel; /** * @ngdoc object * @name enableGroupHeaderSelection * @propertyOf ui.grid.grouping.api:GridOptions * @description Allows group header rows to be selected. * <br/>Defaults to false */ gridOptions.enableGroupHeaderSelection = gridOptions.enableGroupHeaderSelection === true; }, /** * @ngdoc function * @name groupingColumnBuilder * @methodOf ui.grid.grouping.service:uiGridGroupingService * @description Sets the grouping defaults based on the columnDefs * * @param {object} colDef columnDef we're basing on * @param {GridCol} col the column we're to update * @param {object} gridOptions the options we should use * @returns {promise} promise for the builder - actually we do it all inline so it's immediately resolved */ groupingColumnBuilder: function (colDef, col, gridOptions) { /** * @ngdoc object * @name ui.grid.grouping.api:ColumnDef * * @description ColumnDef for grouping feature, these are available to be * set using the ui-grid {@link ui.grid.class:GridOptions.columnDef gridOptions.columnDefs} */ /** * @ngdoc object * @name enableGrouping * @propertyOf ui.grid.grouping.api:ColumnDef * @description Enable grouping on this column * <br/>Defaults to true. */ if (colDef.enableGrouping === false){ return; } /** * @ngdoc object * @name grouping * @propertyOf ui.grid.grouping.api:ColumnDef * @description Set the grouping for a column. Format is: * ``` * { * groupPriority: <number, starts at 0, if less than 0 or undefined then we're aggregating in this column> * } * ``` * * **Note that aggregation used to be included in grouping, but is now separately set on the column via treeAggregation * setting in treeBase** * * We group in the priority order given, this will also put these columns to the high order of the sort irrespective * of the sort priority given them. If there is no sort defined then we sort ascending, if there is a sort defined then * we use that sort. * * If the groupPriority is undefined or less than 0, then we expect to be aggregating, and we look at the * aggregation types to determine what sort of aggregation we can do. Values are in the constants file, but * include SUM, COUNT, MAX, MIN * * groupPriorities should generally be sequential, if they're not then the next time getGrouping is called * we'll renumber them to be sequential. * <br/>Defaults to undefined. */ if ( typeof(col.grouping) === 'undefined' && typeof(colDef.grouping) !== 'undefined') { col.grouping = angular.copy(colDef.grouping); if ( typeof(col.grouping.groupPriority) !== 'undefined' && col.grouping.groupPriority > -1 ){ col.treeAggregationFn = uiGridTreeBaseService.nativeAggregations()[uiGridGroupingConstants.aggregation.COUNT].aggregationFn; col.treeAggregationFinalizerFn = service.groupedFinalizerFn; } } else if (typeof(col.grouping) === 'undefined'){ col.grouping = {}; } if (typeof(col.grouping) !== 'undefined' && typeof(col.grouping.groupPriority) !== 'undefined' && col.grouping.groupPriority >= 0){ col.suppressRemoveSort = true; } var groupColumn = { name: 'ui.grid.grouping.group', title: i18nService.get().grouping.group, icon: 'ui-grid-icon-indent-right', shown: function () { return typeof(this.context.col.grouping) === 'undefined' || typeof(this.context.col.grouping.groupPriority) === 'undefined' || this.context.col.grouping.groupPriority < 0; }, action: function () { service.groupColumn( this.context.col.grid, this.context.col ); } }; var ungroupColumn = { name: 'ui.grid.grouping.ungroup', title: i18nService.get().grouping.ungroup, icon: 'ui-grid-icon-indent-left', shown: function () { return typeof(this.context.col.grouping) !== 'undefined' && typeof(this.context.col.grouping.groupPriority) !== 'undefined' && this.context.col.grouping.groupPriority >= 0; }, action: function () { service.ungroupColumn( this.context.col.grid, this.context.col ); } }; var aggregateRemove = { name: 'ui.grid.grouping.aggregateRemove', title: i18nService.get().grouping.aggregate_remove, shown: function () { return typeof(this.context.col.treeAggregationFn) !== 'undefined'; }, action: function () { service.aggregateColumn( this.context.col.grid, this.context.col, null); } }; // generic adder for the aggregation menus, which follow a pattern var addAggregationMenu = function(type, title){ title = title || i18nService.get().grouping['aggregate_' + type] || type; var menuItem = { name: 'ui.grid.grouping.aggregate' + type, title: title, shown: function () { return typeof(this.context.col.treeAggregation) === 'undefined' || typeof(this.context.col.treeAggregation.type) === 'undefined' || this.context.col.treeAggregation.type !== type; }, action: function () { service.aggregateColumn( this.context.col.grid, this.context.col, type); } }; if (!gridUtil.arrayContainsObjectWithProperty(col.menuItems, 'name', 'ui.grid.grouping.aggregate' + type)) { col.menuItems.push(menuItem); } }; /** * @ngdoc object * @name groupingShowGroupingMenu * @propertyOf ui.grid.grouping.api:ColumnDef * @description Show the grouping (group and ungroup items) menu on this column * <br/>Defaults to true. */ if ( col.colDef.groupingShowGroupingMenu !== false ){ if (!gridUtil.arrayContainsObjectWithProperty(col.menuItems, 'name', 'ui.grid.grouping.group')) { col.menuItems.push(groupColumn); } if (!gridUtil.arrayContainsObjectWithProperty(col.menuItems, 'name', 'ui.grid.grouping.ungroup')) { col.menuItems.push(ungroupColumn); } } /** * @ngdoc object * @name groupingShowAggregationMenu * @propertyOf ui.grid.grouping.api:ColumnDef * @description Show the aggregation menu on this column * <br/>Defaults to true. */ if ( col.colDef.groupingShowAggregationMenu !== false ){ angular.forEach(uiGridTreeBaseService.nativeAggregations(), function(aggregationDef, name){ addAggregationMenu(name); }); angular.forEach(gridOptions.treeCustomAggregations, function(aggregationDef, name){ addAggregationMenu(name, aggregationDef.menuTitle); }); if (!gridUtil.arrayContainsObjectWithProperty(col.menuItems, 'name', 'ui.grid.grouping.aggregateRemove')) { col.menuItems.push(aggregateRemove); } } }, /** * @ngdoc function * @name groupingColumnProcessor * @methodOf ui.grid.grouping.service:uiGridGroupingService * @description Moves the columns around based on which are grouped * * @param {array} columns the columns to consider rendering * @param {array} rows the grid rows, which we don't use but are passed to us * @returns {array} updated columns array */ groupingColumnProcessor: function( columns, rows ) { var grid = this; columns = service.moveGroupColumns(this, columns, rows); return columns; }, /** * @ngdoc function * @name groupedFinalizerFn * @methodOf ui.grid.grouping.service:uiGridGroupingService * @description Used on group columns to display the rendered value and optionally * display the count of rows. * * @param {aggregation} the aggregation entity for a grouped column */ groupedFinalizerFn: function( aggregation ){ var col = this; if ( typeof(aggregation.groupVal) !== 'undefined') { aggregation.rendered = aggregation.groupVal; if ( col.grid.options.groupingShowCounts && col.colDef.type !== 'date' ){ aggregation.rendered += (' (' + aggregation.value + ')'); } } else { aggregation.rendered = null; } }, /** * @ngdoc function * @name moveGroupColumns * @methodOf ui.grid.grouping.service:uiGridGroupingService * @description Moves the column order so that the grouped columns are lined up * to the left (well, unless you're RTL, then it's the right). By doing this in * the columnsProcessor, we make it transient - when the column is ungrouped it'll * go back to where it was. * * Does nothing if the option `moveGroupColumns` is set to false. * * @param {Grid} grid grid object * @param {array} columns the columns that we should process/move * @param {array} rows the grid rows * @returns {array} updated columns */ moveGroupColumns: function( grid, columns, rows ){ if ( grid.options.moveGroupColumns === false){ return columns; } columns.forEach( function(column, index){ // position used to make stable sort in moveGroupColumns column.groupingPosition = index; }); columns.sort(function(a, b){ var a_group, b_group; if (a.isRowHeader){ a_group = -1000; } else if ( typeof(a.grouping) === 'undefined' || typeof(a.grouping.groupPriority) === 'undefined' || a.grouping.groupPriority < 0){ a_group = null; } else { a_group = a.grouping.groupPriority; } if (b.isRowHeader){ b_group = -1000; } else if ( typeof(b.grouping) === 'undefined' || typeof(b.grouping.groupPriority) === 'undefined' || b.grouping.groupPriority < 0){ b_group = null; } else { b_group = b.grouping.groupPriority; } // groups get sorted to the top if ( a_group !== null && b_group === null) { return -1; } if ( b_group !== null && a_group === null) { return 1; } if ( a_group !== null && b_group !== null) {return a_group - b_group; } return a.groupingPosition - b.groupingPosition; }); columns.forEach( function(column, index) { delete column.groupingPosition; }); return columns; }, /** * @ngdoc function * @name groupColumn * @methodOf ui.grid.grouping.service:uiGridGroupingService * @description Adds this column to the existing grouping, at the end of the priority order. * If the column doesn't have a sort, adds one, by default ASC * * This column will move to the left of any non-group columns, the * move is handled in a columnProcessor, so gets called as part of refresh * * @param {Grid} grid grid object * @param {GridCol} column the column we want to group */ groupColumn: function( grid, column){ if ( typeof(column.grouping) === 'undefined' ){ column.grouping = {}; } // set the group priority to the next number in the hierarchy var existingGrouping = service.getGrouping( grid ); column.grouping.groupPriority = existingGrouping.grouping.length; // add sort if not present if ( !column.sort ){ column.sort = { direction: uiGridConstants.ASC }; } else if ( typeof(column.sort.direction) === 'undefined' || column.sort.direction === null ){ column.sort.direction = uiGridConstants.ASC; } column.treeAggregation = { type: uiGridGroupingConstants.aggregation.COUNT, source: 'grouping' }; column.treeAggregationFn = uiGridTreeBaseService.nativeAggregations()[uiGridGroupingConstants.aggregation.COUNT].aggregationFn; column.treeAggregationFinalizerFn = service.groupedFinalizerFn; grid.api.grouping.raise.groupingChanged(column); // This indirectly calls service.tidyPriorities( grid ); grid.api.core.raise.sortChanged(grid, grid.getColumnSorting()); grid.queueGridRefresh(); }, /** * @ngdoc function * @name ungroupColumn * @methodOf ui.grid.grouping.service:uiGridGroupingService * @description Removes the groupPriority from this column. If the * column was previously aggregated the aggregation will come back. * The sort will remain. * * This column will move to the right of any other group columns, the * move is handled in a columnProcessor, so gets called as part of refresh * * @param {Grid} grid grid object * @param {GridCol} column the column we want to ungroup */ ungroupColumn: function( grid, column){ if ( typeof(column.grouping) === 'undefined' ){ return; } delete column.grouping.groupPriority; delete column.treeAggregation; delete column.customTreeAggregationFinalizer; service.tidyPriorities( grid ); grid.api.grouping.raise.groupingChanged(column); grid.queueGridRefresh(); }, /** * @ngdoc function * @name aggregateColumn * @methodOf ui.grid.grouping.service:uiGridGroupingService * @description Sets the aggregation type on a column, if the * column is currently grouped then it removes the grouping first. * * @param {Grid} grid grid object * @param {GridCol} column the column we want to aggregate * @param {string} one of the recognised types from uiGridGroupingConstants or one of the custom aggregations from gridOptions */ aggregateColumn: function( grid, column, aggregationType){ if (typeof(column.grouping) !== 'undefined' && typeof(column.grouping.groupPriority) !== 'undefined' && column.grouping.groupPriority >= 0){ service.ungroupColumn( grid, column ); } var aggregationDef = {}; if ( typeof(grid.options.treeCustomAggregations[aggregationType]) !== 'undefined' ){ aggregationDef = grid.options.treeCustomAggregations[aggregationType]; } else if ( typeof(uiGridTreeBaseService.nativeAggregations()[aggregationType]) !== 'undefined' ){ aggregationDef = uiGridTreeBaseService.nativeAggregations()[aggregationType]; } column.treeAggregation = { type: aggregationType, label: i18nService.get().aggregation[aggregationDef.label] || aggregationDef.label }; column.treeAggregationFn = aggregationDef.aggregationFn; column.treeAggregationFinalizerFn = aggregationDef.finalizerFn; grid.api.grouping.raise.aggregationChanged(column); grid.queueGridRefresh(); }, /** * @ngdoc function * @name setGrouping * @methodOf ui.grid.grouping.service:uiGridGroupingService * @description Set the grouping based on a config object, used by the save state feature * (more specifically, by the restore function in that feature ) * * @param {Grid} grid grid object * @param {object} config the config we want to set, same format as that returned by getGrouping */ setGrouping: function ( grid, config ){ if ( typeof(config) === 'undefined' ){ return; } // first remove any existing grouping service.clearGrouping(grid); if ( config.grouping && config.grouping.length && config.grouping.length > 0 ){ config.grouping.forEach( function( group ) { var col = grid.getColumn(group.colName); if ( col ) { service.groupColumn( grid, col ); } }); } if ( config.aggregations && config.aggregations.length ){ config.aggregations.forEach( function( aggregation ) { var col = grid.getColumn(aggregation.colName); if ( col ) { service.aggregateColumn( grid, col, aggregation.aggregation.type ); } }); } if ( config.rowExpandedStates ){ service.applyRowExpandedStates( grid.grouping.groupingHeaderCache, config.rowExpandedStates ); } }, /** * @ngdoc function * @name clearGrouping * @methodOf ui.grid.grouping.service:uiGridGroupingService * @description Clear any grouped columns and any aggregations. Doesn't remove sorting, * as we don't know whether that sorting was added by grouping or was there beforehand * * @param {Grid} grid grid object */ clearGrouping: function( grid ) { var currentGrouping = service.getGrouping(grid); if ( currentGrouping.grouping.length > 0 ){ currentGrouping.grouping.forEach( function( group ) { if (!group.col){ // should have a group.colName if there's no col group.col = grid.getColumn(group.colName); } service.ungroupColumn(grid, group.col); }); } if ( currentGrouping.aggregations.length > 0 ){ currentGrouping.aggregations.forEach( function( aggregation ){ if (!aggregation.col){ // should have a group.colName if there's no col aggregation.col = grid.getColumn(aggregation.colName); } service.aggregateColumn(grid, aggregation.col, null); }); } }, /** * @ngdoc function * @name tidyPriorities * @methodOf ui.grid.grouping.service:uiGridGroupingService * @description Renumbers groupPriority and sortPriority such that * groupPriority is contiguous, and sortPriority either matches * groupPriority (for group columns), and otherwise is contiguous and * higher than groupPriority. * * @param {Grid} grid grid object */ tidyPriorities: function( grid ){ // if we're called from sortChanged, grid is in this, not passed as param, the param can be a column or undefined if ( ( typeof(grid) === 'undefined' || typeof(grid.grid) !== 'undefined' ) && typeof(this.grid) !== 'undefined' ) { grid = this.grid; } var groupArray = []; var sortArray = []; grid.columns.forEach( function(column, index){ if ( typeof(column.grouping) !== 'undefined' && typeof(column.grouping.groupPriority) !== 'undefined' && column.grouping.groupPriority >= 0){ groupArray.push(column); } else if ( typeof(column.sort) !== 'undefined' && typeof(column.sort.priority) !== 'undefined' && column.sort.priority >= 0){ sortArray.push(column); } }); groupArray.sort(function(a, b){ return a.grouping.groupPriority - b.grouping.groupPriority; }); groupArray.forEach( function(column, index){ column.grouping.groupPriority = index; column.suppressRemoveSort = true; if ( typeof(column.sort) === 'undefined'){ column.sort = {}; } column.sort.priority = index; }); var i = groupArray.length; sortArray.sort(function(a, b){ return a.sort.priority - b.sort.priority; }); sortArray.forEach( function(column, index){ column.sort.priority = i; column.suppressRemoveSort = column.colDef.suppressRemoveSort; i++; }); }, /** * @ngdoc function * @name groupRows * @methodOf ui.grid.grouping.service:uiGridGroupingService * @description The rowProcessor that creates the groupHeaders (i.e. does * the actual grouping). * * Assumes it is always called after the sorting processor, guaranteed by the priority setting * * Processes all the rows in order, inserting a groupHeader row whenever there is a change * in value of a grouped row, based on the sortAlgorithm used for the column. The group header row * is looked up in the groupHeaderCache, and used from there if there is one. The entity is reset * to {} if one is found. * * As it processes it maintains a `processingState` array. This records, for each level of grouping we're * working with, the following information: * ``` * { * fieldName: name, * col: col, * initialised: boolean, * currentValue: value, * currentRow: gridRow, * } * ``` * We look for changes in the currentValue at any of the levels. Where we find a change we: * * - create a new groupHeader row in the array * * @param {array} renderableRows the rows we want to process, usually the output from the previous rowProcessor * @returns {array} the updated rows, including our new group rows */ groupRows: function( renderableRows ) { if (renderableRows.length === 0){ return renderableRows; } var grid = this; grid.grouping.oldGroupingHeaderCache = grid.grouping.groupingHeaderCache || {}; grid.grouping.groupingHeaderCache = {}; var processingState = service.initialiseProcessingState( grid ); // processes each of the fields we are grouping by, checks if the value has changed and inserts a groupHeader // Broken out as shouldn't create functions in a loop. var updateProcessingState = function( groupFieldState, stateIndex ) { var fieldValue = grid.getCellValue(row, groupFieldState.col); // look for change of value - and insert a header if ( !groupFieldState.initialised || rowSorter.getSortFn(grid, groupFieldState.col, renderableRows)(fieldValue, groupFieldState.currentValue) !== 0 ){ service.insertGroupHeader( grid, renderableRows, i, processingState, stateIndex ); i++; } }; // use a for loop because it's tolerant of the array length changing whilst we go - we can // manipulate the iterator when we insert groupHeader rows for (var i = 0; i < renderableRows.length; i++ ){ var row = renderableRows[i]; if ( row.visible ){ processingState.forEach( updateProcessingState ); } } delete grid.grouping.oldGroupingHeaderCache; return renderableRows; }, /** * @ngdoc function * @name initialiseProcessingState * @methodOf ui.grid.grouping.service:uiGridGroupingService * @description Creates the processing state array that is used * for groupRows. * * @param {Grid} grid grid object * @returns {array} an array in the format described in the groupRows method, * initialised with blank values */ initialiseProcessingState: function( grid ){ var processingState = []; var columnSettings = service.getGrouping( grid ); columnSettings.grouping.forEach( function( groupItem, index){ processingState.push({ fieldName: groupItem.field, col: groupItem.col, initialised: false, currentValue: null, currentRow: null }); }); return processingState; }, /** * @ngdoc function * @name getGrouping * @methodOf ui.grid.grouping.service:uiGridGroupingService * @description Get the grouping settings from the columns. As a side effect * this always renumbers the grouping starting at 0 * @param {Grid} grid grid object * @returns {array} an array of the group fields, in order of priority */ getGrouping: function( grid ){ var groupArray = []; var aggregateArray = []; // get all the grouping grid.columns.forEach( function(column, columnIndex){ if ( column.grouping ){ if ( typeof(column.grouping.groupPriority) !== 'undefined' && column.grouping.groupPriority >= 0){ groupArray.push({ field: column.field, col: column, groupPriority: column.grouping.groupPriority, grouping: column.grouping }); } } if ( column.treeAggregation && column.treeAggregation.type ){ aggregateArray.push({ field: column.field, col: column, aggregation: column.treeAggregation }); } }); // sort grouping into priority order groupArray.sort( function(a, b){ return a.groupPriority - b.groupPriority; }); // renumber the priority in case it was somewhat messed up, then remove the grouping reference groupArray.forEach( function( group, index) { group.grouping.groupPriority = index; group.groupPriority = index; delete group.grouping; }); return { grouping: groupArray, aggregations: aggregateArray }; }, /** * @ngdoc function * @name insertGroupHeader * @methodOf ui.grid.grouping.service:uiGridGroupingService * @description Create a group header row, and link it to the various configuration * items that we use. * * Look for the row in the oldGroupingHeaderCache, write the row into the new groupingHeaderCache. * * @param {Grid} grid grid object * @param {array} renderableRows the rows that we are processing * @param {number} rowIndex the row we were up to processing * @param {array} processingState the current processing state * @param {number} stateIndex the processing state item that we were on when we triggered a new group header - * i.e. the column that we want to create a header for */ insertGroupHeader: function( grid, renderableRows, rowIndex, processingState, stateIndex ) { // set the value that caused the end of a group into the header row and the processing state var fieldName = processingState[stateIndex].fieldName; var col = processingState[stateIndex].col; var newValue = grid.getCellValue(renderableRows[rowIndex], col); var newDisplayValue = newValue; if ( typeof(newValue) === 'undefined' || newValue === null ) { newDisplayValue = grid.options.groupingNullLabel; } var cacheItem = grid.grouping.oldGroupingHeaderCache; for ( var i = 0; i < stateIndex; i++ ){ if ( cacheItem && cacheItem[processingState[i].currentValue] ){ cacheItem = cacheItem[processingState[i].currentValue].children; } } var headerRow; if ( cacheItem && cacheItem[newValue]){ headerRow = cacheItem[newValue].row; headerRow.entity = {}; } else { headerRow = new GridRow( {}, null, grid ); gridClassFactory.rowTemplateAssigner.call(grid, headerRow); } headerRow.entity['$$' + processingState[stateIndex].col.uid] = { groupVal: newDisplayValue }; headerRow.treeLevel = stateIndex; headerRow.groupHeader = true; headerRow.internalRow = true; headerRow.enableCellEdit = false; headerRow.enableSelection = grid.options.enableGroupHeaderSelection; processingState[stateIndex].initialised = true; processingState[stateIndex].currentValue = newValue; processingState[stateIndex].currentRow = headerRow; // set all processing states below this one to not be initialised - change of this state // means all those need to start again service.finaliseProcessingState( processingState, stateIndex + 1); // insert our new header row renderableRows.splice(rowIndex, 0, headerRow); // add our new header row to the cache cacheItem = grid.grouping.groupingHeaderCache; for ( i = 0; i < stateIndex; i++ ){ cacheItem = cacheItem[processingState[i].currentValue].children; } cacheItem[newValue] = { row: headerRow, children: {} }; }, /** * @ngdoc function * @name finaliseProcessingState * @methodOf ui.grid.grouping.service:uiGridGroupingService * @description Set all processing states lower than the one that had a break in value to * no longer be initialised. Render the counts into the entity ready for display. * * @param {Grid} grid grid object * @param {array} processingState the current processing state * @param {number} stateIndex the processing state item that we were on when we triggered a new group header, all * processing states after this need to be finalised */ finaliseProcessingState: function( processingState, stateIndex ){ for ( var i = stateIndex; i < processingState.length; i++){ processingState[i].initialised = false; processingState[i].currentRow = null; processingState[i].currentValue = null; } }, /** * @ngdoc function * @name getRowExpandedStates * @methodOf ui.grid.grouping.service:uiGridGroupingService * @description Extract the groupHeaderCache hash, pulling out only the states. * * The example below shows a grid that is grouped by gender then age * * <pre> * { * male: { * state: 'expanded', * children: { * 22: { state: 'expanded' }, * 30: { state: 'collapsed' } * } * }, * female: { * state: 'expanded', * children: { * 28: { state: 'expanded' }, * 55: { state: 'collapsed' } * } * } * } * </pre> * * @param {Grid} grid grid object * @returns {hash} the expanded states as a hash */ getRowExpandedStates: function(treeChildren){ if ( typeof(treeChildren) === 'undefined' ){ return {}; } var newChildren = {}; angular.forEach( treeChildren, function( value, key ){ newChildren[key] = { state: value.row.treeNode.state }; if ( value.children ){ newChildren[key].children = service.getRowExpandedStates( value.children ); } else { newChildren[key].children = {}; } }); return newChildren; }, /** * @ngdoc function * @name applyRowExpandedStates * @methodOf ui.grid.grouping.service:uiGridGroupingService * @description Take a hash in the format as created by getRowExpandedStates, * and apply it to the grid.grouping.groupHeaderCache. * * Takes a treeSubset, and applies to a treeSubset - so can be called * recursively. * * @param {object} currentNode can be grid.grouping.groupHeaderCache, or any of * the children of that hash * @returns {hash} expandedStates can be the full expanded states, or children * of that expanded states (which hopefully matches the subset of the groupHeaderCache) */ applyRowExpandedStates: function( currentNode, expandedStates ){ if ( typeof(expandedStates) === 'undefined' ){ return; } angular.forEach(expandedStates, function( value, key ) { if ( currentNode[key] ){ currentNode[key].row.treeNode.state = value.state; if (value.children && currentNode[key].children){ service.applyRowExpandedStates( currentNode[key].children, value.children ); } } }); } }; return service; }]); /** * @ngdoc directive * @name ui.grid.grouping.directive:uiGridGrouping * @element div * @restrict A * * @description Adds grouping features to grid * * @example <example module="app"> <file name="app.js"> var app = angular.module('app', ['ui.grid', 'ui.grid.grouping']); app.controller('MainCtrl', ['$scope', function ($scope) { $scope.data = [ { name: 'Bob', title: 'CEO' }, { name: 'Frank', title: 'Lowly Developer' } ]; $scope.columnDefs = [ {name: 'name', enableCellEdit: true}, {name: 'title', enableCellEdit: true} ]; $scope.gridOptions = { columnDefs: $scope.columnDefs, data: $scope.data }; }]); </file> <file name="index.html"> <div ng-controller="MainCtrl"> <div ui-grid="gridOptions" ui-grid-grouping></div> </div> </file> </example> */ module.directive('uiGridGrouping', ['uiGridGroupingConstants', 'uiGridGroupingService', '$templateCache', function (uiGridGroupingConstants, uiGridGroupingService, $templateCache) { return { replace: true, priority: 0, require: '^uiGrid', scope: false, compile: function () { return { pre: function ($scope, $elm, $attrs, uiGridCtrl) { if (uiGridCtrl.grid.options.enableGrouping !== false){ uiGridGroupingService.initializeGrid(uiGridCtrl.grid, $scope); } }, post: function ($scope, $elm, $attrs, uiGridCtrl) { } }; } }; }]); })(); (function () { 'use strict'; /** * @ngdoc overview * @name ui.grid.importer * @description * * # ui.grid.importer * * <div class="alert alert-success" role="alert"><strong>Stable</strong> This feature is stable. There should no longer be breaking api changes without a deprecation warning.</div> * * This module provides the ability to import data into the grid. It * uses the column defs to work out which data belongs in which column, * and creates entities from a configured class (typically a $resource). * * If the rowEdit feature is enabled, it also calls save on those newly * created objects, and then displays any errors in the imported data. * * Currently the importer imports only CSV and json files, although provision has been * made to process other file formats, and these can be added over time. * * For json files, the properties within each object in the json must match the column names * (to put it another way, the importer doesn't process the json, it just copies the objects * within the json into a new instance of the specified object type) * * For CSV import, the default column identification relies on each column in the * header row matching a column.name or column.displayName. Optionally, a column identification * callback can be used. This allows matching using other attributes, which is particularly * useful if your application has internationalised column headings (i.e. the headings that * the user sees don't match the column names). * * The importer makes use of the grid menu as the UI for requesting an * import. * * <div ui-grid-importer></div> */ var module = angular.module('ui.grid.importer', ['ui.grid']); /** * @ngdoc object * @name ui.grid.importer.constant:uiGridImporterConstants * * @description constants available in importer module */ module.constant('uiGridImporterConstants', { featureName: 'importer' }); /** * @ngdoc service * @name ui.grid.importer.service:uiGridImporterService * * @description Services for importer feature */ module.service('uiGridImporterService', ['$q', 'uiGridConstants', 'uiGridImporterConstants', 'gridUtil', '$compile', '$interval', 'i18nService', '$window', function ($q, uiGridConstants, uiGridImporterConstants, gridUtil, $compile, $interval, i18nService, $window) { var service = { initializeGrid: function ($scope, grid) { //add feature namespace and any properties to grid for needed state grid.importer = { $scope: $scope }; this.defaultGridOptions(grid.options); /** * @ngdoc object * @name ui.grid.importer.api:PublicApi * * @description Public Api for importer feature */ var publicApi = { events: { importer: { } }, methods: { importer: { /** * @ngdoc function * @name importFile * @methodOf ui.grid.importer.api:PublicApi * @description Imports a file into the grid using the file object * provided. Bypasses the grid menu * @param {File} fileObject the file we want to import, as a javascript * File object */ importFile: function ( fileObject ) { service.importThisFile( grid, fileObject ); } } } }; grid.api.registerEventsFromObject(publicApi.events); grid.api.registerMethodsFromObject(publicApi.methods); if ( grid.options.enableImporter && grid.options.importerShowMenu ){ if ( grid.api.core.addToGridMenu ){ service.addToMenu( grid ); } else { // order of registration is not guaranteed, register in a little while $interval( function() { if (grid.api.core.addToGridMenu){ service.addToMenu( grid ); } }, 100, 1); } } }, defaultGridOptions: function (gridOptions) { //default option to true unless it was explicitly set to false /** * @ngdoc object * @name ui.grid.importer.api:GridOptions * * @description GridOptions for importer feature, these are available to be * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions} */ /** * @ngdoc property * @propertyOf ui.grid.importer.api:GridOptions * @name enableImporter * @description Whether or not importer is enabled. Automatically set * to false if the user's browser does not support the required fileApi. * Otherwise defaults to true. * */ if (gridOptions.enableImporter || gridOptions.enableImporter === undefined) { if ( !($window.hasOwnProperty('File') && $window.hasOwnProperty('FileReader') && $window.hasOwnProperty('FileList') && $window.hasOwnProperty('Blob')) ) { gridUtil.logError('The File APIs are not fully supported in this browser, grid importer cannot be used.'); gridOptions.enableImporter = false; } else { gridOptions.enableImporter = true; } } else { gridOptions.enableImporter = false; } /** * @ngdoc method * @name importerProcessHeaders * @methodOf ui.grid.importer.api:GridOptions * @description A callback function that will process headers using custom * logic. Set this callback function if the headers that your user will provide in their * import file don't necessarily match the grid header or field names. This might commonly * occur where your application is internationalised, and therefore the field names * that the user recognises are in a different language than the field names that * ui-grid knows about. * * Defaults to the internal `processHeaders` method, which seeks to match using both * displayName and column.name. Any non-matching columns are discarded. * * Your callback routine should respond by processing the header array, and returning an array * of matching column names. A null value in any given position means "don't import this column" * * <pre> * gridOptions.importerProcessHeaders: function( headerArray ) { * var myHeaderColumns = []; * var thisCol; * headerArray.forEach( function( value, index ) { * thisCol = mySpecialLookupFunction( value ); * myHeaderColumns.push( thisCol.name ); * }); * * return myHeaderCols; * }) * </pre> * @param {Grid} grid the grid we're importing into * @param {array} headerArray an array of the text from the first row of the csv file, * which you need to match to column.names * @returns {array} array of matching column names, in the same order as the headerArray * */ gridOptions.importerProcessHeaders = gridOptions.importerProcessHeaders || service.processHeaders; /** * @ngdoc method * @name importerHeaderFilter * @methodOf ui.grid.importer.api:GridOptions * @description A callback function that will filter (usually translate) a single * header. Used when you want to match the passed in column names to the column * displayName after the header filter. * * Your callback routine needs to return the filtered header value. * <pre> * gridOptions.importerHeaderFilter: function( displayName ) { * return $translate.instant( displayName ); * }) * </pre> * * or: * <pre> * gridOptions.importerHeaderFilter: $translate.instant * </pre> * @param {string} displayName the displayName that we'd like to translate * @returns {string} the translated name * */ gridOptions.importerHeaderFilter = gridOptions.importerHeaderFilter || function( displayName ) { return displayName; }; /** * @ngdoc method * @name importerErrorCallback * @methodOf ui.grid.importer.api:GridOptions * @description A callback function that provides custom error handling, rather * than the standard grid behaviour of an alert box and a console message. You * might use this to internationalise the console log messages, or to write to a * custom logging routine that returned errors to the server. * * <pre> * gridOptions.importerErrorCallback: function( grid, errorKey, consoleMessage, context ) { * myUserDisplayRoutine( errorKey ); * myLoggingRoutine( consoleMessage, context ); * }) * </pre> * @param {Grid} grid the grid we're importing into, may be useful if you're positioning messages * in some way * @param {string} errorKey one of the i18n keys the importer can return - importer.noHeaders, * importer.noObjects, importer.invalidCsv, importer.invalidJson, importer.jsonNotArray * @param {string} consoleMessage the English console message that importer would have written * @param {object} context the context data that importer would have appended to that console message, * often the file content itself or the element that is in error * */ if ( !gridOptions.importerErrorCallback || typeof(gridOptions.importerErrorCallback) !== 'function' ){ delete gridOptions.importerErrorCallback; } /** * @ngdoc method * @name importerDataAddCallback * @methodOf ui.grid.importer.api:GridOptions * @description A mandatory callback function that adds data to the source data array. The grid * generally doesn't add rows to the source data array, it is tidier to handle this through a user * callback. * * <pre> * gridOptions.importerDataAddCallback: function( grid, newObjects ) { * $scope.myData = $scope.myData.concat( newObjects ); * }) * </pre> * @param {Grid} grid the grid we're importing into, may be useful in some way * @param {array} newObjects an array of new objects that you should add to your data * */ if ( gridOptions.enableImporter === true && !gridOptions.importerDataAddCallback ) { gridUtil.logError("You have not set an importerDataAddCallback, importer is disabled"); gridOptions.enableImporter = false; } /** * @ngdoc object * @name importerNewObject * @propertyOf ui.grid.importer.api:GridOptions * @description An object on which we call `new` to create each new row before inserting it into * the data array. Typically this would be a $resource entity, which means that if you're using * the rowEdit feature, you can directly call save on this entity when the save event is triggered. * * Defaults to a vanilla javascript object * * @example * <pre> * gridOptions.importerNewObject = MyRes; * </pre> * */ /** * @ngdoc property * @propertyOf ui.grid.importer.api:GridOptions * @name importerShowMenu * @description Whether or not to show an item in the grid menu. Defaults to true. * */ gridOptions.importerShowMenu = gridOptions.importerShowMenu !== false; /** * @ngdoc method * @methodOf ui.grid.importer.api:GridOptions * @name importerObjectCallback * @description A callback that massages the data for each object. For example, * you might have data stored as a code value, but display the decode. This callback * can be used to change the decoded value back into a code. Defaults to doing nothing. * @param {Grid} grid in case you need it * @param {object} newObject the new object as importer has created it, modify it * then return the modified version * @returns {object} the modified object * @example * <pre> * gridOptions.importerObjectCallback = function ( grid, newObject ) { * switch newObject.status { * case 'Active': * newObject.status = 1; * break; * case 'Inactive': * newObject.status = 2; * break; * } * return newObject; * }; * </pre> */ gridOptions.importerObjectCallback = gridOptions.importerObjectCallback || function( grid, newObject ) { return newObject; }; }, /** * @ngdoc function * @name addToMenu * @methodOf ui.grid.importer.service:uiGridImporterService * @description Adds import menu item to the grid menu, * allowing the user to request import of a file * @param {Grid} grid the grid into which data should be imported */ addToMenu: function ( grid ) { grid.api.core.addToGridMenu( grid, [ { title: i18nService.getSafeText('gridMenu.importerTitle'), order: 150 }, { templateUrl: 'ui-grid/importerMenuItemContainer', action: function ($event) { this.grid.api.importer.importAFile( grid ); }, order: 151 } ]); }, /** * @ngdoc function * @name importThisFile * @methodOf ui.grid.importer.service:uiGridImporterService * @description Imports the provided file into the grid using the file object * provided. Bypasses the grid menu * @param {Grid} grid the grid we're importing into * @param {File} fileObject the file we want to import, as returned from the File * javascript object */ importThisFile: function ( grid, fileObject ) { if (!fileObject){ gridUtil.logError( 'No file object provided to importThisFile, should be impossible, aborting'); return; } var reader = new FileReader(); switch ( fileObject.type ){ case 'application/json': reader.onload = service.importJsonClosure( grid ); break; default: reader.onload = service.importCsvClosure( grid ); break; } reader.readAsText( fileObject ); }, /** * @ngdoc function * @name importJson * @methodOf ui.grid.importer.service:uiGridImporterService * @description Creates a function that imports a json file into the grid. * The json data is imported into new objects of type `gridOptions.importerNewObject`, * and if the rowEdit feature is enabled the rows are marked as dirty * @param {Grid} grid the grid we want to import into * @param {FileObject} importFile the file that we want to import, as * a FileObject */ importJsonClosure: function( grid ) { return function( importFile ){ var newObjects = []; var newObject; var importArray = service.parseJson( grid, importFile ); if (importArray === null){ return; } importArray.forEach( function( value, index ) { newObject = service.newObject( grid ); angular.extend( newObject, value ); newObject = grid.options.importerObjectCallback( grid, newObject ); newObjects.push( newObject ); }); service.addObjects( grid, newObjects ); }; }, /** * @ngdoc function * @name parseJson * @methodOf ui.grid.importer.service:uiGridImporterService * @description Parses a json file, returns the parsed data. * Displays an error if file doesn't parse * @param {Grid} grid the grid that we want to import into * @param {FileObject} importFile the file that we want to import, as * a FileObject * @returns {array} array of objects from the imported json */ parseJson: function( grid, importFile ){ var loadedObjects; try { loadedObjects = JSON.parse( importFile.target.result ); } catch (e) { service.alertError( grid, 'importer.invalidJson', 'File could not be processed, is it valid json? Content was: ', importFile.target.result ); return; } if ( !Array.isArray( loadedObjects ) ){ service.alertError( grid, 'importer.jsonNotarray', 'Import failed, file is not an array, file was: ', importFile.target.result ); return []; } else { return loadedObjects; } }, /** * @ngdoc function * @name importCsvClosure * @methodOf ui.grid.importer.service:uiGridImporterService * @description Creates a function that imports a csv file into the grid * (allowing it to be used in the reader.onload event) * @param {Grid} grid the grid that we want to import into * @param {FileObject} importFile the file that we want to import, as * a file object */ importCsvClosure: function( grid ) { return function( importFile ){ var importArray = service.parseCsv( importFile ); if ( !importArray || importArray.length < 1 ){ service.alertError( grid, 'importer.invalidCsv', 'File could not be processed, is it valid csv? Content was: ', importFile.target.result ); return; } var newObjects = service.createCsvObjects( grid, importArray ); if ( !newObjects || newObjects.length === 0 ){ service.alertError( grid, 'importer.noObjects', 'Objects were not able to be derived, content was: ', importFile.target.result ); return; } service.addObjects( grid, newObjects ); }; }, /** * @ngdoc function * @name parseCsv * @methodOf ui.grid.importer.service:uiGridImporterService * @description Parses a csv file into an array of arrays, with the first * array being the headers, and the remaining arrays being the data. * The logic for this comes from https://github.com/thetalecrafter/excel.js/blob/master/src/csv.js, * which is noted as being under the MIT license. The code is modified to pass the jscs yoda condition * checker * @param {FileObject} importFile the file that we want to import, as a * file object */ parseCsv: function( importFile ) { var csv = importFile.target.result; // use the CSV-JS library to parse return CSV.parse(csv); }, /** * @ngdoc function * @name createCsvObjects * @methodOf ui.grid.importer.service:uiGridImporterService * @description Converts an array of arrays (representing the csv file) * into a set of objects. Uses the provided `gridOptions.importerNewObject` * to create the objects, and maps the header row into the individual columns * using either `gridOptions.importerProcessHeaders`, or by using a native method * of matching to either the displayName, column name or column field of * the columns in the column defs. The resulting objects will have attributes * that are named based on the column.field or column.name, in that order. * @param {Grid} grid the grid that we want to import into * @param {Array} importArray the data that we want to import, as an array */ createCsvObjects: function( grid, importArray ){ // pull off header row and turn into headers var headerMapping = grid.options.importerProcessHeaders( grid, importArray.shift() ); if ( !headerMapping || headerMapping.length === 0 ){ service.alertError( grid, 'importer.noHeaders', 'Column names could not be derived, content was: ', importArray ); return []; } var newObjects = []; var newObject; importArray.forEach( function( row, index ) { newObject = service.newObject( grid ); if ( row !== null ){ row.forEach( function( field, index ){ if ( headerMapping[index] !== null ){ newObject[ headerMapping[index] ] = field; } }); } newObject = grid.options.importerObjectCallback( grid, newObject ); newObjects.push( newObject ); }); return newObjects; }, /** * @ngdoc function * @name processHeaders * @methodOf ui.grid.importer.service:uiGridImporterService * @description Determines the columns that the header row from * a csv (or other) file represents. * @param {Grid} grid the grid we're importing into * @param {array} headerRow the header row that we wish to match against * the column definitions * @returns {array} an array of the attribute names that should be used * for that column, based on matching the headers or creating the headers * */ processHeaders: function( grid, headerRow ) { var headers = []; if ( !grid.options.columnDefs || grid.options.columnDefs.length === 0 ){ // we are going to create new columnDefs for all these columns, so just remove // spaces from the names to create fields headerRow.forEach( function( value, index ) { headers.push( value.replace( /[^0-9a-zA-Z\-_]/g, '_' ) ); }); return headers; } else { var lookupHash = service.flattenColumnDefs( grid, grid.options.columnDefs ); headerRow.forEach( function( value, index ) { if ( lookupHash[value] ) { headers.push( lookupHash[value] ); } else if ( lookupHash[ value.toLowerCase() ] ) { headers.push( lookupHash[ value.toLowerCase() ] ); } else { headers.push( null ); } }); return headers; } }, /** * @name flattenColumnDefs * @methodOf ui.grid.importer.service:uiGridImporterService * @description Runs through the column defs and creates a hash of * the displayName, name and field, and of each of those values forced to lower case, * with each pointing to the field or name * (whichever is present). Used to lookup column headers and decide what * attribute name to give to the resulting field. * @param {Grid} grid the grid we're importing into * @param {array} columnDefs the columnDefs that we should flatten * @returns {hash} the flattened version of the column def information, allowing * us to look up a value by `flattenedHash[ headerValue ]` */ flattenColumnDefs: function( grid, columnDefs ){ var flattenedHash = {}; columnDefs.forEach( function( columnDef, index) { if ( columnDef.name ){ flattenedHash[ columnDef.name ] = columnDef.field || columnDef.name; flattenedHash[ columnDef.name.toLowerCase() ] = columnDef.field || columnDef.name; } if ( columnDef.field ){ flattenedHash[ columnDef.field ] = columnDef.field || columnDef.name; flattenedHash[ columnDef.field.toLowerCase() ] = columnDef.field || columnDef.name; } if ( columnDef.displayName ){ flattenedHash[ columnDef.displayName ] = columnDef.field || columnDef.name; flattenedHash[ columnDef.displayName.toLowerCase() ] = columnDef.field || columnDef.name; } if ( columnDef.displayName && grid.options.importerHeaderFilter ){ flattenedHash[ grid.options.importerHeaderFilter(columnDef.displayName) ] = columnDef.field || columnDef.name; flattenedHash[ grid.options.importerHeaderFilter(columnDef.displayName).toLowerCase() ] = columnDef.field || columnDef.name; } }); return flattenedHash; }, /** * @ngdoc function * @name addObjects * @methodOf ui.grid.importer.service:uiGridImporterService * @description Inserts our new objects into the grid data, and * sets the rows to dirty if the rowEdit feature is being used * * Does this by registering a watch on dataChanges, which essentially * is waiting on the result of the grid data watch, and downstream processing. * * When the callback is called, it deregisters itself - we don't want to run * again next time data is added. * * If we never get called, we deregister on destroy. * * @param {Grid} grid the grid we're importing into * @param {array} newObjects the objects we want to insert into the grid data * @returns {object} the new object */ addObjects: function( grid, newObjects, $scope ){ if ( grid.api.rowEdit ){ var dataChangeDereg = grid.registerDataChangeCallback( function() { grid.api.rowEdit.setRowsDirty( newObjects ); dataChangeDereg(); }, [uiGridConstants.dataChange.ROW] ); grid.importer.$scope.$on( '$destroy', dataChangeDereg ); } grid.importer.$scope.$apply( grid.options.importerDataAddCallback( grid, newObjects ) ); }, /** * @ngdoc function * @name newObject * @methodOf ui.grid.importer.service:uiGridImporterService * @description Makes a new object based on `gridOptions.importerNewObject`, * or based on an empty object if not present * @param {Grid} grid the grid we're importing into * @returns {object} the new object */ newObject: function( grid ){ if ( typeof(grid.options) !== "undefined" && typeof(grid.options.importerNewObject) !== "undefined" ){ return new grid.options.importerNewObject(); } else { return {}; } }, /** * @ngdoc function * @name alertError * @methodOf ui.grid.importer.service:uiGridImporterService * @description Provides an internationalised user alert for the failure, * and logs a console message including diagnostic content. * Optionally, if the the `gridOptions.importerErrorCallback` routine * is defined, then calls that instead, allowing user specified error routines * @param {Grid} grid the grid we're importing into * @param {array} headerRow the header row that we wish to match against * the column definitions */ alertError: function( grid, alertI18nToken, consoleMessage, context ){ if ( grid.options.importerErrorCallback ){ grid.options.importerErrorCallback( grid, alertI18nToken, consoleMessage, context ); } else { $window.alert(i18nService.getSafeText( alertI18nToken )); gridUtil.logError(consoleMessage + context ); } } }; return service; } ]); /** * @ngdoc directive * @name ui.grid.importer.directive:uiGridImporter * @element div * @restrict A * * @description Adds importer features to grid * */ module.directive('uiGridImporter', ['uiGridImporterConstants', 'uiGridImporterService', 'gridUtil', '$compile', function (uiGridImporterConstants, uiGridImporterService, gridUtil, $compile) { return { replace: true, priority: 0, require: '^uiGrid', scope: false, link: function ($scope, $elm, $attrs, uiGridCtrl) { uiGridImporterService.initializeGrid($scope, uiGridCtrl.grid); } }; } ]); /** * @ngdoc directive * @name ui.grid.importer.directive:uiGridImporterMenuItem * @element div * @restrict A * * @description Handles the processing from the importer menu item - once a file is * selected * */ module.directive('uiGridImporterMenuItem', ['uiGridImporterConstants', 'uiGridImporterService', 'gridUtil', '$compile', function (uiGridImporterConstants, uiGridImporterService, gridUtil, $compile) { return { replace: true, priority: 0, require: '^uiGrid', scope: false, templateUrl: 'ui-grid/importerMenuItem', link: function ($scope, $elm, $attrs, uiGridCtrl) { var handleFileSelect = function( event ){ var target = event.srcElement || event.target; if (target && target.files && target.files.length === 1) { var fileObject = target.files[0]; uiGridImporterService.importThisFile( grid, fileObject ); target.form.reset(); } }; var fileChooser = $elm[0].querySelectorAll('.ui-grid-importer-file-chooser'); var grid = uiGridCtrl.grid; if ( fileChooser.length !== 1 ){ gridUtil.logError('Found > 1 or < 1 file choosers within the menu item, error, cannot continue'); } else { fileChooser[0].addEventListener('change', handleFileSelect, false); // TODO: why the false on the end? Google } } }; } ]); })(); (function() { 'use strict'; /** * @ngdoc overview * @name ui.grid.infiniteScroll * * @description * * #ui.grid.infiniteScroll * * <div class="alert alert-warning" role="alert"><strong>Beta</strong> This feature is ready for testing, but it either hasn't seen a lot of use or has some known bugs.</div> * * This module provides infinite scroll functionality to ui-grid * */ var module = angular.module('ui.grid.infiniteScroll', ['ui.grid']); /** * @ngdoc service * @name ui.grid.infiniteScroll.service:uiGridInfiniteScrollService * * @description Service for infinite scroll features */ module.service('uiGridInfiniteScrollService', ['gridUtil', '$compile', '$timeout', 'uiGridConstants', 'ScrollEvent', '$q', function (gridUtil, $compile, $timeout, uiGridConstants, ScrollEvent, $q) { var service = { /** * @ngdoc function * @name initializeGrid * @methodOf ui.grid.infiniteScroll.service:uiGridInfiniteScrollService * @description This method register events and methods into grid public API */ initializeGrid: function(grid, $scope) { service.defaultGridOptions(grid.options); if (!grid.options.enableInfiniteScroll){ return; } grid.infiniteScroll = { dataLoading: false }; service.setScrollDirections( grid, grid.options.infiniteScrollUp, grid.options.infiniteScrollDown ); grid.api.core.on.scrollEnd($scope, service.handleScroll); /** * @ngdoc object * @name ui.grid.infiniteScroll.api:PublicAPI * * @description Public API for infinite scroll feature */ var publicApi = { events: { infiniteScroll: { /** * @ngdoc event * @name needLoadMoreData * @eventOf ui.grid.infiniteScroll.api:PublicAPI * @description This event fires when scroll reaches bottom percentage of grid * and needs to load data */ needLoadMoreData: function ($scope, fn) { }, /** * @ngdoc event * @name needLoadMoreDataTop * @eventOf ui.grid.infiniteScroll.api:PublicAPI * @description This event fires when scroll reaches top percentage of grid * and needs to load data */ needLoadMoreDataTop: function ($scope, fn) { } } }, methods: { infiniteScroll: { /** * @ngdoc function * @name dataLoaded * @methodOf ui.grid.infiniteScroll.api:PublicAPI * @description Call this function when you have loaded the additional data * requested. You should set scrollUp and scrollDown to indicate * whether there are still more pages in each direction. * * If you call dataLoaded without first calling `saveScrollPercentage` then we will * scroll the user to the start of the newly loaded data, which usually gives a smooth scroll * experience, but can give a jumpy experience with large `infiniteScrollRowsFromEnd` values, and * on variable speed internet connections. Using `saveScrollPercentage` as demonstrated in the tutorial * should give a smoother scrolling experience for users. * * See infinite_scroll tutorial for example of usage * @param {boolean} scrollUp if set to false flags that there are no more pages upwards, so don't fire * any more infinite scroll events upward * @param {boolean} scrollDown if set to false flags that there are no more pages downwards, so don't * fire any more infinite scroll events downward * @returns {promise} a promise that is resolved when the grid scrolling is fully adjusted. If you're * planning to remove pages, you should wait on this promise first, or you'll break the scroll positioning */ dataLoaded: function( scrollUp, scrollDown ) { service.setScrollDirections(grid, scrollUp, scrollDown); var promise = service.adjustScroll(grid).then(function() { grid.infiniteScroll.dataLoading = false; }); return promise; }, /** * @ngdoc function * @name resetScroll * @methodOf ui.grid.infiniteScroll.api:PublicAPI * @description Call this function when you have taken some action that makes the current * scroll position invalid. For example, if you're using external sorting and you've resorted * then you might reset the scroll, or if you've otherwise substantially changed the data, perhaps * you've reused an existing grid for a new data set * * You must tell us whether there is data upwards or downwards after the reset * * @param {boolean} scrollUp flag that there are pages upwards, fire * infinite scroll events upward * @param {boolean} scrollDown flag that there are pages downwards, so * fire infinite scroll events downward * @returns {promise} promise that is resolved when the scroll reset is complete */ resetScroll: function( scrollUp, scrollDown ) { service.setScrollDirections( grid, scrollUp, scrollDown); return service.adjustInfiniteScrollPosition(grid, 0); }, /** * @ngdoc function * @name saveScrollPercentage * @methodOf ui.grid.infiniteScroll.api:PublicAPI * @description Saves the scroll percentage and number of visible rows before you adjust the data, * used if you're subsequently going to call `dataRemovedTop` or `dataRemovedBottom` */ saveScrollPercentage: function() { grid.infiniteScroll.prevScrollTop = grid.renderContainers.body.prevScrollTop; grid.infiniteScroll.previousVisibleRows = grid.getVisibleRowCount(); }, /** * @ngdoc function * @name dataRemovedTop * @methodOf ui.grid.infiniteScroll.api:PublicAPI * @description Adjusts the scroll position after you've removed data at the top * @param {boolean} scrollUp flag that there are pages upwards, fire * infinite scroll events upward * @param {boolean} scrollDown flag that there are pages downwards, so * fire infinite scroll events downward */ dataRemovedTop: function( scrollUp, scrollDown ) { service.dataRemovedTop( grid, scrollUp, scrollDown ); }, /** * @ngdoc function * @name dataRemovedBottom * @methodOf ui.grid.infiniteScroll.api:PublicAPI * @description Adjusts the scroll position after you've removed data at the bottom * @param {boolean} scrollUp flag that there are pages upwards, fire * infinite scroll events upward * @param {boolean} scrollDown flag that there are pages downwards, so * fire infinite scroll events downward */ dataRemovedBottom: function( scrollUp, scrollDown ) { service.dataRemovedBottom( grid, scrollUp, scrollDown ); }, /** * @ngdoc function * @name setScrollDirections * @methodOf ui.grid.infiniteScroll.service:uiGridInfiniteScrollService * @description Sets the scrollUp and scrollDown flags, handling nulls and undefined, * and also sets the grid.suppressParentScroll * @param {boolean} scrollUp whether there are pages available up - defaults to false * @param {boolean} scrollDown whether there are pages available down - defaults to true */ setScrollDirections: function ( scrollUp, scrollDown ) { service.setScrollDirections( grid, scrollUp, scrollDown ); } } } }; grid.api.registerEventsFromObject(publicApi.events); grid.api.registerMethodsFromObject(publicApi.methods); }, defaultGridOptions: function (gridOptions) { //default option to true unless it was explicitly set to false /** * @ngdoc object * @name ui.grid.infiniteScroll.api:GridOptions * * @description GridOptions for infinite scroll feature, these are available to be * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions} */ /** * @ngdoc object * @name enableInfiniteScroll * @propertyOf ui.grid.infiniteScroll.api:GridOptions * @description Enable infinite scrolling for this grid * <br/>Defaults to true */ gridOptions.enableInfiniteScroll = gridOptions.enableInfiniteScroll !== false; /** * @ngdoc property * @name infiniteScrollRowsFromEnd * @propertyOf ui.grid.class:GridOptions * @description This setting controls how close to the end of the dataset a user gets before * more data is requested by the infinite scroll, whether scrolling up or down. This allows you to * 'prefetch' rows before the user actually runs out of scrolling. * * Note that if you set this value too high it may give jumpy scrolling behaviour, if you're getting * this behaviour you could use the `saveScrollPercentageMethod` right before loading your data, and we'll * preserve that scroll position * * <br> Defaults to 20 */ gridOptions.infiniteScrollRowsFromEnd = gridOptions.infiniteScrollRowsFromEnd || 20; /** * @ngdoc property * @name infiniteScrollUp * @propertyOf ui.grid.class:GridOptions * @description Whether you allow infinite scroll up, implying that the first page of data * you have displayed is in the middle of your data set. If set to true then we trigger the * needMoreDataTop event when the user hits the top of the scrollbar. * <br> Defaults to false */ gridOptions.infiniteScrollUp = gridOptions.infiniteScrollUp === true; /** * @ngdoc property * @name infiniteScrollDown * @propertyOf ui.grid.class:GridOptions * @description Whether you allow infinite scroll down, implying that the first page of data * you have displayed is in the middle of your data set. If set to true then we trigger the * needMoreData event when the user hits the bottom of the scrollbar. * <br> Defaults to true */ gridOptions.infiniteScrollDown = gridOptions.infiniteScrollDown !== false; }, /** * @ngdoc function * @name setScrollDirections * @methodOf ui.grid.infiniteScroll.service:uiGridInfiniteScrollService * @description Sets the scrollUp and scrollDown flags, handling nulls and undefined, * and also sets the grid.suppressParentScroll * @param {grid} grid the grid we're operating on * @param {boolean} scrollUp whether there are pages available up - defaults to false * @param {boolean} scrollDown whether there are pages available down - defaults to true */ setScrollDirections: function ( grid, scrollUp, scrollDown ) { grid.infiniteScroll.scrollUp = ( scrollUp === true ); grid.suppressParentScrollUp = ( scrollUp === true ); grid.infiniteScroll.scrollDown = ( scrollDown !== false); grid.suppressParentScrollDown = ( scrollDown !== false); }, /** * @ngdoc function * @name handleScroll * @methodOf ui.grid.infiniteScroll.service:uiGridInfiniteScrollService * @description Called whenever the grid scrolls, determines whether the scroll should * trigger an infinite scroll request for more data * @param {object} args the args from the event */ handleScroll: function (args) { // don't request data if already waiting for data, or if source is coming from ui.grid.adjustInfiniteScrollPosition() function if ( args.grid.infiniteScroll && args.grid.infiniteScroll.dataLoading || args.source === 'ui.grid.adjustInfiniteScrollPosition' ){ return; } if (args.y) { var percentage; var targetPercentage = args.grid.options.infiniteScrollRowsFromEnd / args.grid.renderContainers.body.visibleRowCache.length; if (args.grid.scrollDirection === uiGridConstants.scrollDirection.UP ) { percentage = args.y.percentage; if (percentage <= targetPercentage){ service.loadData(args.grid); } } else if (args.grid.scrollDirection === uiGridConstants.scrollDirection.DOWN) { percentage = 1 - args.y.percentage; if (percentage <= targetPercentage){ service.loadData(args.grid); } } } }, /** * @ngdoc function * @name loadData * @methodOf ui.grid.infiniteScroll.service:uiGridInfiniteScrollService * @description This function fires 'needLoadMoreData' or 'needLoadMoreDataTop' event based on scrollDirection * and whether there are more pages upwards or downwards. It also stores the number of rows that we had previously, * and clears out any saved scroll position so that we know whether or not the user calls `saveScrollPercentage` * @param {Grid} grid the grid we're working on */ loadData: function (grid) { // save number of currently visible rows to calculate new scroll position later - we know that we want // to be at approximately the row we're currently at grid.infiniteScroll.previousVisibleRows = grid.renderContainers.body.visibleRowCache.length; grid.infiniteScroll.direction = grid.scrollDirection; delete grid.infiniteScroll.prevScrollTop; if (grid.scrollDirection === uiGridConstants.scrollDirection.UP && grid.infiniteScroll.scrollUp ) { grid.infiniteScroll.dataLoading = true; grid.api.infiniteScroll.raise.needLoadMoreDataTop(); } else if (grid.scrollDirection === uiGridConstants.scrollDirection.DOWN && grid.infiniteScroll.scrollDown ) { grid.infiniteScroll.dataLoading = true; grid.api.infiniteScroll.raise.needLoadMoreData(); } }, /** * @ngdoc function * @name adjustScroll * @methodOf ui.grid.infiniteScroll.service:uiGridInfiniteScrollService * @description Once we are informed that data has been loaded, adjust the scroll position to account for that * addition and to make things look clean. * * If we're scrolling up we scroll to the first row of the old data set - * so we're assuming that you would have gotten to the top of the grid (from the 20% need more data trigger) by * the time the data comes back. If we're scrolling down we scoll to the last row of the old data set - so we're * assuming that you would have gotten to the bottom of the grid (from the 80% need more data trigger) by the time * the data comes back. * * Neither of these are good assumptions, but making this a smoother experience really requires * that trigger to not be a percentage, and to be much closer to the end of the data (say, 5 rows off the end). Even then * it'd be better still to actually run into the end. But if the data takes a while to come back, they may have scrolled * somewhere else in the mean-time, in which case they'll get a jump back to the new data. Anyway, this will do for * now, until someone wants to do better. * @param {Grid} grid the grid we're working on * @returns {promise} a promise that is resolved when scrolling has finished */ adjustScroll: function(grid){ var promise = $q.defer(); $timeout(function () { var newPercentage, viewportHeight, rowHeight, newVisibleRows, oldTop, newTop; viewportHeight = grid.getViewportHeight() + grid.headerHeight - grid.renderContainers.body.headerHeight - grid.scrollbarHeight; rowHeight = grid.options.rowHeight; if ( grid.infiniteScroll.direction === undefined ){ // called from initialize, tweak our scroll up a little service.adjustInfiniteScrollPosition(grid, 0); } newVisibleRows = grid.getVisibleRowCount(); if ( grid.infiniteScroll.direction === uiGridConstants.scrollDirection.UP ){ oldTop = grid.infiniteScroll.prevScrollTop || 0; newTop = oldTop + (newVisibleRows - grid.infiniteScroll.previousVisibleRows)*rowHeight; service.adjustInfiniteScrollPosition(grid, newTop); $timeout( function() { promise.resolve(); }); } if ( grid.infiniteScroll.direction === uiGridConstants.scrollDirection.DOWN ){ newTop = grid.infiniteScroll.prevScrollTop || (grid.infiniteScroll.previousVisibleRows*rowHeight - viewportHeight); service.adjustInfiniteScrollPosition(grid, newTop); $timeout( function() { promise.resolve(); }); } }, 0); return promise.promise; }, /** * @ngdoc function * @name adjustInfiniteScrollPosition * @methodOf ui.grid.infiniteScroll.service:uiGridInfiniteScrollService * @description This function fires 'needLoadMoreData' or 'needLoadMoreDataTop' event based on scrollDirection * @param {Grid} grid the grid we're working on * @param {number} scrollTop the position through the grid that we want to scroll to * @returns {promise} a promise that is resolved when the scrolling finishes */ adjustInfiniteScrollPosition: function (grid, scrollTop) { var scrollEvent = new ScrollEvent(grid, null, null, 'ui.grid.adjustInfiniteScrollPosition'), visibleRows = grid.getVisibleRowCount(), viewportHeight = grid.getViewportHeight() + grid.headerHeight - grid.renderContainers.body.headerHeight - grid.scrollbarHeight, rowHeight = grid.options.rowHeight, scrollHeight = visibleRows*rowHeight-viewportHeight; //for infinite scroll, if there are pages upwards then never allow it to be at the zero position so the up button can be active if (scrollTop === 0 && grid.infiniteScroll.scrollUp) { // using pixels results in a relative scroll, hence we have to use percentage scrollEvent.y = {percentage: 1/scrollHeight}; } else { scrollEvent.y = {percentage: scrollTop/scrollHeight}; } grid.scrollContainers('', scrollEvent); }, /** * @ngdoc function * @name dataRemovedTop * @methodOf ui.grid.infiniteScroll.api:PublicAPI * @description Adjusts the scroll position after you've removed data at the top. You should * have called `saveScrollPercentage` before you remove the data, and if you're doing this in * response to a `needMoreData` you should wait until the promise from `loadData` has resolved * before you start removing data * @param {Grid} grid the grid we're working on * @param {boolean} scrollUp flag that there are pages upwards, fire * infinite scroll events upward * @param {boolean} scrollDown flag that there are pages downwards, so * fire infinite scroll events downward * @returns {promise} a promise that is resolved when the scrolling finishes */ dataRemovedTop: function( grid, scrollUp, scrollDown ) { var newVisibleRows, oldTop, newTop, rowHeight; service.setScrollDirections( grid, scrollUp, scrollDown ); newVisibleRows = grid.renderContainers.body.visibleRowCache.length; oldTop = grid.infiniteScroll.prevScrollTop; rowHeight = grid.options.rowHeight; // since we removed from the top, our new scroll row will be the old scroll row less the number // of rows removed newTop = oldTop - ( grid.infiniteScroll.previousVisibleRows - newVisibleRows )*rowHeight; return service.adjustInfiniteScrollPosition( grid, newTop ); }, /** * @ngdoc function * @name dataRemovedBottom * @methodOf ui.grid.infiniteScroll.api:PublicAPI * @description Adjusts the scroll position after you've removed data at the bottom. You should * have called `saveScrollPercentage` before you remove the data, and if you're doing this in * response to a `needMoreData` you should wait until the promise from `loadData` has resolved * before you start removing data * @param {Grid} grid the grid we're working on * @param {boolean} scrollUp flag that there are pages upwards, fire * infinite scroll events upward * @param {boolean} scrollDown flag that there are pages downwards, so * fire infinite scroll events downward */ dataRemovedBottom: function( grid, scrollUp, scrollDown ) { var newTop; service.setScrollDirections( grid, scrollUp, scrollDown ); newTop = grid.infiniteScroll.prevScrollTop; return service.adjustInfiniteScrollPosition( grid, newTop ); } }; return service; }]); /** * @ngdoc directive * @name ui.grid.infiniteScroll.directive:uiGridInfiniteScroll * @element div * @restrict A * * @description Adds infinite scroll features to grid * * @example <example module="app"> <file name="app.js"> var app = angular.module('app', ['ui.grid', 'ui.grid.infiniteScroll']); app.controller('MainCtrl', ['$scope', function ($scope) { $scope.data = [ { name: 'Alex', car: 'Toyota' }, { name: 'Sam', car: 'Lexus' } ]; $scope.columnDefs = [ {name: 'name'}, {name: 'car'} ]; }]); </file> <file name="index.html"> <div ng-controller="MainCtrl"> <div ui-grid="{ data: data, columnDefs: columnDefs }" ui-grid-infinite-scroll="20"></div> </div> </file> </example> */ module.directive('uiGridInfiniteScroll', ['uiGridInfiniteScrollService', function (uiGridInfiniteScrollService) { return { priority: -200, scope: false, require: '^uiGrid', compile: function($scope, $elm, $attr){ return { pre: function($scope, $elm, $attr, uiGridCtrl) { uiGridInfiniteScrollService.initializeGrid(uiGridCtrl.grid, $scope); }, post: function($scope, $elm, $attr) { } }; } }; }]); })(); (function () { 'use strict'; /** * @ngdoc overview * @name ui.grid.moveColumns * @description * * # ui.grid.moveColumns * * <div class="alert alert-warning" role="alert"><strong>Alpha</strong> This feature is in development. There will almost certainly be breaking api changes, or there are major outstanding bugs.</div> * * This module provides column moving capability to ui.grid. It enables to change the position of columns. * <div doc-module-components="ui.grid.moveColumns"></div> */ var module = angular.module('ui.grid.moveColumns', ['ui.grid']); /** * @ngdoc service * @name ui.grid.moveColumns.service:uiGridMoveColumnService * @description Service for column moving feature. */ module.service('uiGridMoveColumnService', ['$q', '$timeout', '$log', 'ScrollEvent', 'uiGridConstants', 'gridUtil', function ($q, $timeout, $log, ScrollEvent, uiGridConstants, gridUtil) { var service = { initializeGrid: function (grid) { var self = this; this.registerPublicApi(grid); this.defaultGridOptions(grid.options); grid.moveColumns = {orderCache: []}; // Used to cache the order before columns are rebuilt grid.registerColumnBuilder(self.movableColumnBuilder); grid.registerDataChangeCallback(self.verifyColumnOrder, [uiGridConstants.dataChange.COLUMN]); }, registerPublicApi: function (grid) { var self = this; /** * @ngdoc object * @name ui.grid.moveColumns.api:PublicApi * @description Public Api for column moving feature. */ var publicApi = { events: { /** * @ngdoc event * @name columnPositionChanged * @eventOf ui.grid.moveColumns.api:PublicApi * @description raised when column is moved * <pre> * gridApi.colMovable.on.columnPositionChanged(scope,function(colDef, originalPosition, newPosition){}) * </pre> * @param {object} colDef the column that was moved * @param {integer} originalPosition of the column * @param {integer} finalPosition of the column */ colMovable: { columnPositionChanged: function (colDef, originalPosition, newPosition) { } } }, methods: { /** * @ngdoc method * @name moveColumn * @methodOf ui.grid.moveColumns.api:PublicApi * @description Method can be used to change column position. * <pre> * gridApi.colMovable.moveColumn(oldPosition, newPosition) * </pre> * @param {integer} originalPosition of the column * @param {integer} finalPosition of the column */ colMovable: { moveColumn: function (originalPosition, finalPosition) { var columns = grid.columns; if (!angular.isNumber(originalPosition) || !angular.isNumber(finalPosition)) { gridUtil.logError('MoveColumn: Please provide valid values for originalPosition and finalPosition'); return; } var nonMovableColumns = 0; for (var i = 0; i < columns.length; i++) { if ((angular.isDefined(columns[i].colDef.visible) && columns[i].colDef.visible === false) || columns[i].isRowHeader === true) { nonMovableColumns++; } } if (originalPosition >= (columns.length - nonMovableColumns) || finalPosition >= (columns.length - nonMovableColumns)) { gridUtil.logError('MoveColumn: Invalid values for originalPosition, finalPosition'); return; } var findPositionForRenderIndex = function (index) { var position = index; for (var i = 0; i <= position; i++) { if (angular.isDefined(columns[i]) && ((angular.isDefined(columns[i].colDef.visible) && columns[i].colDef.visible === false) || columns[i].isRowHeader === true)) { position++; } } return position; }; self.redrawColumnAtPosition(grid, findPositionForRenderIndex(originalPosition), findPositionForRenderIndex(finalPosition)); } } } }; grid.api.registerEventsFromObject(publicApi.events); grid.api.registerMethodsFromObject(publicApi.methods); }, defaultGridOptions: function (gridOptions) { /** * @ngdoc object * @name ui.grid.moveColumns.api:GridOptions * * @description Options for configuring the move column feature, these are available to be * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions} */ /** * @ngdoc object * @name enableColumnMoving * @propertyOf ui.grid.moveColumns.api:GridOptions * @description If defined, sets the default value for the colMovable flag on each individual colDefs * if their individual enableColumnMoving configuration is not defined. Defaults to true. */ gridOptions.enableColumnMoving = gridOptions.enableColumnMoving !== false; }, movableColumnBuilder: function (colDef, col, gridOptions) { var promises = []; /** * @ngdoc object * @name ui.grid.moveColumns.api:ColumnDef * * @description Column Definition for move column feature, these are available to be * set using the ui-grid {@link ui.grid.class:GridOptions.columnDef gridOptions.columnDefs} */ /** * @ngdoc object * @name enableColumnMoving * @propertyOf ui.grid.moveColumns.api:ColumnDef * @description Enable column moving for the column. */ colDef.enableColumnMoving = colDef.enableColumnMoving === undefined ? gridOptions.enableColumnMoving : colDef.enableColumnMoving; return $q.all(promises); }, /** * @ngdoc method * @name updateColumnCache * @methodOf ui.grid.moveColumns * @description Cache the current order of columns, so we can restore them after new columnDefs are defined */ updateColumnCache: function(grid){ grid.moveColumns.orderCache = grid.getOnlyDataColumns(); }, /** * @ngdoc method * @name verifyColumnOrder * @methodOf ui.grid.moveColumns * @description dataChangeCallback which uses the cached column order to restore the column order * when it is reset by altering the columnDefs array. */ verifyColumnOrder: function(grid){ var headerRowOffset = grid.rowHeaderColumns.length; var newIndex; angular.forEach(grid.moveColumns.orderCache, function(cacheCol, cacheIndex){ newIndex = grid.columns.indexOf(cacheCol); if ( newIndex !== -1 && newIndex - headerRowOffset !== cacheIndex ){ var column = grid.columns.splice(newIndex, 1)[0]; grid.columns.splice(cacheIndex + headerRowOffset, 0, column); } }); }, redrawColumnAtPosition: function (grid, originalPosition, newPosition) { var columns = grid.columns; var originalColumn = columns[originalPosition]; if (originalColumn.colDef.enableColumnMoving) { if (originalPosition > newPosition) { for (var i1 = originalPosition; i1 > newPosition; i1--) { columns[i1] = columns[i1 - 1]; } } else if (newPosition > originalPosition) { for (var i2 = originalPosition; i2 < newPosition; i2++) { columns[i2] = columns[i2 + 1]; } } columns[newPosition] = originalColumn; service.updateColumnCache(grid); grid.queueGridRefresh(); $timeout(function () { grid.api.core.notifyDataChange( uiGridConstants.dataChange.COLUMN ); grid.api.colMovable.raise.columnPositionChanged(originalColumn.colDef, originalPosition, newPosition); }); } } }; return service; }]); /** * @ngdoc directive * @name ui.grid.moveColumns.directive:uiGridMoveColumns * @element div * @restrict A * @description Adds column moving features to the ui-grid directive. * @example <example module="app"> <file name="app.js"> var app = angular.module('app', ['ui.grid', 'ui.grid.moveColumns']); app.controller('MainCtrl', ['$scope', function ($scope) { $scope.data = [ { name: 'Bob', title: 'CEO', age: 45 }, { name: 'Frank', title: 'Lowly Developer', age: 25 }, { name: 'Jenny', title: 'Highly Developer', age: 35 } ]; $scope.columnDefs = [ {name: 'name'}, {name: 'title'}, {name: 'age'} ]; }]); </file> <file name="main.css"> .grid { width: 100%; height: 150px; } </file> <file name="index.html"> <div ng-controller="MainCtrl"> <div class="grid" ui-grid="{ data: data, columnDefs: columnDefs }" ui-grid-move-columns></div> </div> </file> </example> */ module.directive('uiGridMoveColumns', ['uiGridMoveColumnService', function (uiGridMoveColumnService) { return { replace: true, priority: 0, require: '^uiGrid', scope: false, compile: function () { return { pre: function ($scope, $elm, $attrs, uiGridCtrl) { uiGridMoveColumnService.initializeGrid(uiGridCtrl.grid); }, post: function ($scope, $elm, $attrs, uiGridCtrl) { } }; } }; }]); /** * @ngdoc directive * @name ui.grid.moveColumns.directive:uiGridHeaderCell * @element div * @restrict A * * @description Stacks on top of ui.grid.uiGridHeaderCell to provide capability to be able to move it to reposition column. * * On receiving mouseDown event headerCell is cloned, now as the mouse moves the cloned header cell also moved in the grid. * In case the moving cloned header cell reaches the left or right extreme of grid, grid scrolling is triggered (if horizontal scroll exists). * On mouseUp event column is repositioned at position where mouse is released and cloned header cell is removed. * * Events that invoke cloning of header cell: * - mousedown * * Events that invoke movement of cloned header cell: * - mousemove * * Events that invoke repositioning of column: * - mouseup */ module.directive('uiGridHeaderCell', ['$q', 'gridUtil', 'uiGridMoveColumnService', '$document', '$log', 'uiGridConstants', 'ScrollEvent', function ($q, gridUtil, uiGridMoveColumnService, $document, $log, uiGridConstants, ScrollEvent) { return { priority: -10, require: '^uiGrid', compile: function () { return { post: function ($scope, $elm, $attrs, uiGridCtrl) { if ($scope.col.colDef.enableColumnMoving) { /* * Our general approach to column move is that we listen to a touchstart or mousedown * event over the column header. When we hear one, then we wait for a move of the same type * - if we are a touchstart then we listen for a touchmove, if we are a mousedown we listen for * a mousemove (i.e. a drag) before we decide that there's a move underway. If there's never a move, * and we instead get a mouseup or a touchend, then we just drop out again and do nothing. * */ var $contentsElm = angular.element( $elm[0].querySelectorAll('.ui-grid-cell-contents') ); var gridLeft; var previousMouseX; var totalMouseMovement; var rightMoveLimit; var elmCloned = false; var movingElm; var reducedWidth; var moveOccurred = false; var downFn = function( event ){ //Setting some variables required for calculations. gridLeft = $scope.grid.element[0].getBoundingClientRect().left; if ( $scope.grid.hasLeftContainer() ){ gridLeft += $scope.grid.renderContainers.left.header[0].getBoundingClientRect().width; } previousMouseX = event.pageX; totalMouseMovement = 0; rightMoveLimit = gridLeft + $scope.grid.getViewportWidth(); if ( event.type === 'mousedown' ){ $document.on('mousemove', moveFn); $document.on('mouseup', upFn); } else if ( event.type === 'touchstart' ){ $document.on('touchmove', moveFn); $document.on('touchend', upFn); } }; var moveFn = function( event ) { var changeValue = event.pageX - previousMouseX; if ( changeValue === 0 ){ return; } //Disable text selection in Chrome during column move document.onselectstart = function() { return false; }; moveOccurred = true; if (!elmCloned) { cloneElement(); } else if (elmCloned) { moveElement(changeValue); previousMouseX = event.pageX; } }; var upFn = function( event ){ //Re-enable text selection after column move document.onselectstart = null; //Remove the cloned element on mouse up. if (movingElm) { movingElm.remove(); elmCloned = false; } offAllEvents(); onDownEvents(); if (!moveOccurred){ return; } var columns = $scope.grid.columns; var columnIndex = 0; for (var i = 0; i < columns.length; i++) { if (columns[i].colDef.name !== $scope.col.colDef.name) { columnIndex++; } else { break; } } //Case where column should be moved to a position on its left if (totalMouseMovement < 0) { var totalColumnsLeftWidth = 0; for (var il = columnIndex - 1; il >= 0; il--) { if (angular.isUndefined(columns[il].colDef.visible) || columns[il].colDef.visible === true) { totalColumnsLeftWidth += columns[il].drawnWidth || columns[il].width || columns[il].colDef.width; if (totalColumnsLeftWidth > Math.abs(totalMouseMovement)) { uiGridMoveColumnService.redrawColumnAtPosition ($scope.grid, columnIndex, il + 1); break; } } } //Case where column should be moved to beginning of the grid. if (totalColumnsLeftWidth < Math.abs(totalMouseMovement)) { uiGridMoveColumnService.redrawColumnAtPosition ($scope.grid, columnIndex, 0); } } //Case where column should be moved to a position on its right else if (totalMouseMovement > 0) { var totalColumnsRightWidth = 0; for (var ir = columnIndex + 1; ir < columns.length; ir++) { if (angular.isUndefined(columns[ir].colDef.visible) || columns[ir].colDef.visible === true) { totalColumnsRightWidth += columns[ir].drawnWidth || columns[ir].width || columns[ir].colDef.width; if (totalColumnsRightWidth > totalMouseMovement) { uiGridMoveColumnService.redrawColumnAtPosition ($scope.grid, columnIndex, ir - 1); break; } } } //Case where column should be moved to end of the grid. if (totalColumnsRightWidth < totalMouseMovement) { uiGridMoveColumnService.redrawColumnAtPosition ($scope.grid, columnIndex, columns.length - 1); } } }; var onDownEvents = function(){ $contentsElm.on('touchstart', downFn); $contentsElm.on('mousedown', downFn); }; var offAllEvents = function() { $contentsElm.off('touchstart', downFn); $contentsElm.off('mousedown', downFn); $document.off('mousemove', moveFn); $document.off('touchmove', moveFn); $document.off('mouseup', upFn); $document.off('touchend', upFn); }; onDownEvents(); var cloneElement = function () { elmCloned = true; //Cloning header cell and appending to current header cell. movingElm = $elm.clone(); $elm.parent().append(movingElm); //Left of cloned element should be aligned to original header cell. movingElm.addClass('movingColumn'); var movingElementStyles = {}; var elmLeft; if (gridUtil.detectBrowser() === 'safari') { //Correction for Safari getBoundingClientRect, //which does not correctly compute when there is an horizontal scroll elmLeft = $elm[0].offsetLeft + $elm[0].offsetWidth - $elm[0].getBoundingClientRect().width; } else { elmLeft = $elm[0].getBoundingClientRect().left; } movingElementStyles.left = (elmLeft - gridLeft) + 'px'; var gridRight = $scope.grid.element[0].getBoundingClientRect().right; var elmRight = $elm[0].getBoundingClientRect().right; if (elmRight > gridRight) { reducedWidth = $scope.col.drawnWidth + (gridRight - elmRight); movingElementStyles.width = reducedWidth + 'px'; } movingElm.css(movingElementStyles); }; var moveElement = function (changeValue) { //Calculate total column width var columns = $scope.grid.columns; var totalColumnWidth = 0; for (var i = 0; i < columns.length; i++) { if (angular.isUndefined(columns[i].colDef.visible) || columns[i].colDef.visible === true) { totalColumnWidth += columns[i].drawnWidth || columns[i].width || columns[i].colDef.width; } } //Calculate new position of left of column var currentElmLeft = movingElm[0].getBoundingClientRect().left - 1; var currentElmRight = movingElm[0].getBoundingClientRect().right; var newElementLeft; newElementLeft = currentElmLeft - gridLeft + changeValue; newElementLeft = newElementLeft < rightMoveLimit ? newElementLeft : rightMoveLimit; //Update css of moving column to adjust to new left value or fire scroll in case column has reached edge of grid if ((currentElmLeft >= gridLeft || changeValue > 0) && (currentElmRight <= rightMoveLimit || changeValue < 0)) { movingElm.css({visibility: 'visible', 'left': newElementLeft + 'px'}); } else if (totalColumnWidth > Math.ceil(uiGridCtrl.grid.gridWidth)) { changeValue *= 8; var scrollEvent = new ScrollEvent($scope.col.grid, null, null, 'uiGridHeaderCell.moveElement'); scrollEvent.x = {pixels: changeValue}; scrollEvent.grid.scrollContainers('',scrollEvent); } //Calculate total width of columns on the left of the moving column and the mouse movement var totalColumnsLeftWidth = 0; for (var il = 0; il < columns.length; il++) { if (angular.isUndefined(columns[il].colDef.visible) || columns[il].colDef.visible === true) { if (columns[il].colDef.name !== $scope.col.colDef.name) { totalColumnsLeftWidth += columns[il].drawnWidth || columns[il].width || columns[il].colDef.width; } else { break; } } } if ($scope.newScrollLeft === undefined) { totalMouseMovement += changeValue; } else { totalMouseMovement = $scope.newScrollLeft + newElementLeft - totalColumnsLeftWidth; } //Increase width of moving column, in case the rightmost column was moved and its width was //decreased because of overflow if (reducedWidth < $scope.col.drawnWidth) { reducedWidth += Math.abs(changeValue); movingElm.css({'width': reducedWidth + 'px'}); } }; } } }; } }; }]); })(); (function() { 'use strict'; /** * @ngdoc overview * @name ui.grid.pagination * * @description * * # ui.grid.pagination * * <div class="alert alert-warning" role="alert"><strong>Alpha</strong> This feature is in development. There will almost certainly be breaking api changes, or there are major outstanding bugs.</div> * * This module provides pagination support to ui-grid */ var module = angular.module('ui.grid.pagination', ['ng', 'ui.grid']); /** * @ngdoc service * @name ui.grid.pagination.service:uiGridPaginationService * * @description Service for the pagination feature */ module.service('uiGridPaginationService', ['gridUtil', function (gridUtil) { var service = { /** * @ngdoc method * @name initializeGrid * @methodOf ui.grid.pagination.service:uiGridPaginationService * @description Attaches the service to a certain grid * @param {Grid} grid The grid we want to work with */ initializeGrid: function (grid) { service.defaultGridOptions(grid.options); /** * @ngdoc object * @name ui.grid.pagination.api:PublicAPI * * @description Public API for the pagination feature */ var publicApi = { events: { pagination: { /** * @ngdoc event * @name paginationChanged * @eventOf ui.grid.pagination.api:PublicAPI * @description This event fires when the pageSize or currentPage changes * @param {int} currentPage requested page number * @param {int} pageSize requested page size */ paginationChanged: function (currentPage, pageSize) { } } }, methods: { pagination: { /** * @ngdoc method * @name getPage * @methodOf ui.grid.pagination.api:PublicAPI * @description Returns the number of the current page */ getPage: function () { return grid.options.enablePagination ? grid.options.paginationCurrentPage : null; }, /** * @ngdoc method * @name getTotalPages * @methodOf ui.grid.pagination.api:PublicAPI * @description Returns the total number of pages */ getTotalPages: function () { if (!grid.options.enablePagination) { return null; } return (grid.options.totalItems === 0) ? 1 : Math.ceil(grid.options.totalItems / grid.options.paginationPageSize); }, /** * @ngdoc method * @name nextPage * @methodOf ui.grid.pagination.api:PublicAPI * @description Moves to the next page, if possible */ nextPage: function () { if (!grid.options.enablePagination) { return; } if (grid.options.totalItems > 0) { grid.options.paginationCurrentPage = Math.min( grid.options.paginationCurrentPage + 1, publicApi.methods.pagination.getTotalPages() ); } else { grid.options.paginationCurrentPage++; } }, /** * @ngdoc method * @name previousPage * @methodOf ui.grid.pagination.api:PublicAPI * @description Moves to the previous page, if we're not on the first page */ previousPage: function () { if (!grid.options.enablePagination) { return; } grid.options.paginationCurrentPage = Math.max(grid.options.paginationCurrentPage - 1, 1); }, /** * @ngdoc method * @name seek * @methodOf ui.grid.pagination.api:PublicAPI * @description Moves to the requested page * @param {int} page The number of the page that should be displayed */ seek: function (page) { if (!grid.options.enablePagination) { return; } if (!angular.isNumber(page) || page < 1) { throw 'Invalid page number: ' + page; } grid.options.paginationCurrentPage = Math.min(page, publicApi.methods.pagination.getTotalPages()); } } } }; grid.api.registerEventsFromObject(publicApi.events); grid.api.registerMethodsFromObject(publicApi.methods); var processPagination = function( renderableRows ){ if (grid.options.useExternalPagination || !grid.options.enablePagination) { return renderableRows; } //client side pagination var pageSize = parseInt(grid.options.paginationPageSize, 10); var currentPage = parseInt(grid.options.paginationCurrentPage, 10); var visibleRows = renderableRows.filter(function (row) { return row.visible; }); grid.options.totalItems = visibleRows.length; var firstRow = (currentPage - 1) * pageSize; if (firstRow > visibleRows.length) { currentPage = grid.options.paginationCurrentPage = 1; firstRow = (currentPage - 1) * pageSize; } return visibleRows.slice(firstRow, firstRow + pageSize); }; grid.registerRowsProcessor(processPagination, 900 ); }, defaultGridOptions: function (gridOptions) { /** * @ngdoc object * @name ui.grid.pagination.api:GridOptions * * @description GridOptions for the pagination feature, these are available to be * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions} */ /** * @ngdoc property * @name enablePagination * @propertyOf ui.grid.pagination.api:GridOptions * @description Enables pagination, defaults to true */ gridOptions.enablePagination = gridOptions.enablePagination !== false; /** * @ngdoc property * @name enablePaginationControls * @propertyOf ui.grid.pagination.api:GridOptions * @description Enables the paginator at the bottom of the grid. Turn this off, if you want to implement your * own controls outside the grid. */ gridOptions.enablePaginationControls = gridOptions.enablePaginationControls !== false; /** * @ngdoc property * @name useExternalPagination * @propertyOf ui.grid.pagination.api:GridOptions * @description Disables client side pagination. When true, handle the paginationChanged event and set data * and totalItems, defaults to `false` */ gridOptions.useExternalPagination = gridOptions.useExternalPagination === true; /** * @ngdoc property * @name totalItems * @propertyOf ui.grid.pagination.api:GridOptions * @description Total number of items, set automatically when client side pagination, needs set by user * for server side pagination */ if (gridUtil.isNullOrUndefined(gridOptions.totalItems)) { gridOptions.totalItems = 0; } /** * @ngdoc property * @name paginationPageSizes * @propertyOf ui.grid.pagination.api:GridOptions * @description Array of page sizes, defaults to `[250, 500, 1000]` */ if (gridUtil.isNullOrUndefined(gridOptions.paginationPageSizes)) { gridOptions.paginationPageSizes = [250, 500, 1000]; } /** * @ngdoc property * @name paginationPageSize * @propertyOf ui.grid.pagination.api:GridOptions * @description Page size, defaults to the first item in paginationPageSizes, or 0 if paginationPageSizes is empty */ if (gridUtil.isNullOrUndefined(gridOptions.paginationPageSize)) { if (gridOptions.paginationPageSizes.length > 0) { gridOptions.paginationPageSize = gridOptions.paginationPageSizes[0]; } else { gridOptions.paginationPageSize = 0; } } /** * @ngdoc property * @name paginationCurrentPage * @propertyOf ui.grid.pagination.api:GridOptions * @description Current page number, defaults to 1 */ if (gridUtil.isNullOrUndefined(gridOptions.paginationCurrentPage)) { gridOptions.paginationCurrentPage = 1; } /** * @ngdoc property * @name paginationTemplate * @propertyOf ui.grid.pagination.api:GridOptions * @description A custom template for the pager, defaults to `ui-grid/pagination` */ if (gridUtil.isNullOrUndefined(gridOptions.paginationTemplate)) { gridOptions.paginationTemplate = 'ui-grid/pagination'; } }, /** * @ngdoc method * @methodOf ui.grid.pagination.service:uiGridPaginationService * @name uiGridPaginationService * @description Raises paginationChanged and calls refresh for client side pagination * @param {Grid} grid the grid for which the pagination changed * @param {int} currentPage requested page number * @param {int} pageSize requested page size */ onPaginationChanged: function (grid, currentPage, pageSize) { grid.api.pagination.raise.paginationChanged(currentPage, pageSize); if (!grid.options.useExternalPagination) { grid.queueGridRefresh(); //client side pagination } } }; return service; } ]); /** * @ngdoc directive * @name ui.grid.pagination.directive:uiGridPagination * @element div * @restrict A * * @description Adds pagination features to grid * @example <example module="app"> <file name="app.js"> var app = angular.module('app', ['ui.grid', 'ui.grid.pagination']); app.controller('MainCtrl', ['$scope', function ($scope) { $scope.data = [ { name: 'Alex', car: 'Toyota' }, { name: 'Sam', car: 'Lexus' }, { name: 'Joe', car: 'Dodge' }, { name: 'Bob', car: 'Buick' }, { name: 'Cindy', car: 'Ford' }, { name: 'Brian', car: 'Audi' }, { name: 'Malcom', car: 'Mercedes Benz' }, { name: 'Dave', car: 'Ford' }, { name: 'Stacey', car: 'Audi' }, { name: 'Amy', car: 'Acura' }, { name: 'Scott', car: 'Toyota' }, { name: 'Ryan', car: 'BMW' }, ]; $scope.gridOptions = { data: 'data', paginationPageSizes: [5, 10, 25], paginationPageSize: 5, columnDefs: [ {name: 'name'}, {name: 'car'} ] } }]); </file> <file name="index.html"> <div ng-controller="MainCtrl"> <div ui-grid="gridOptions" ui-grid-pagination></div> </div> </file> </example> */ module.directive('uiGridPagination', ['gridUtil', 'uiGridPaginationService', function (gridUtil, uiGridPaginationService) { return { priority: -200, scope: false, require: 'uiGrid', link: { pre: function ($scope, $elm, $attr, uiGridCtrl) { uiGridPaginationService.initializeGrid(uiGridCtrl.grid); gridUtil.getTemplate(uiGridCtrl.grid.options.paginationTemplate) .then(function (contents) { var template = angular.element(contents); $elm.append(template); uiGridCtrl.innerCompile(template); }); } } }; } ]); /** * @ngdoc directive * @name ui.grid.pagination.directive:uiGridPager * @element div * * @description Panel for handling pagination */ module.directive('uiGridPager', ['uiGridPaginationService', 'uiGridConstants', 'gridUtil', 'i18nService', function (uiGridPaginationService, uiGridConstants, gridUtil, i18nService) { return { priority: -200, scope: true, require: '^uiGrid', link: function ($scope, $elm, $attr, uiGridCtrl) { var defaultFocusElementSelector = '.ui-grid-pager-control-input'; $scope.aria = i18nService.getSafeText('pagination.aria'); //Returns an object with all of the aria labels $scope.paginationApi = uiGridCtrl.grid.api.pagination; $scope.sizesLabel = i18nService.getSafeText('pagination.sizes'); $scope.totalItemsLabel = i18nService.getSafeText('pagination.totalItems'); $scope.paginationOf = i18nService.getSafeText('pagination.of'); $scope.paginationThrough = i18nService.getSafeText('pagination.through'); var options = uiGridCtrl.grid.options; uiGridCtrl.grid.renderContainers.body.registerViewportAdjuster(function (adjustment) { adjustment.height = adjustment.height - gridUtil.elementHeight($elm); return adjustment; }); var dataChangeDereg = uiGridCtrl.grid.registerDataChangeCallback(function (grid) { if (!grid.options.useExternalPagination) { grid.options.totalItems = grid.rows.length; } }, [uiGridConstants.dataChange.ROW]); $scope.$on('$destroy', dataChangeDereg); var setShowing = function () { $scope.showingLow = ((options.paginationCurrentPage - 1) * options.paginationPageSize) + 1; $scope.showingHigh = Math.min(options.paginationCurrentPage * options.paginationPageSize, options.totalItems); }; var deregT = $scope.$watch('grid.options.totalItems + grid.options.paginationPageSize', setShowing); var deregP = $scope.$watch('grid.options.paginationCurrentPage + grid.options.paginationPageSize', function (newValues, oldValues) { if (newValues === oldValues || oldValues === undefined) { return; } if (!angular.isNumber(options.paginationCurrentPage) || options.paginationCurrentPage < 1) { options.paginationCurrentPage = 1; return; } if (options.totalItems > 0 && options.paginationCurrentPage > $scope.paginationApi.getTotalPages()) { options.paginationCurrentPage = $scope.paginationApi.getTotalPages(); return; } setShowing(); uiGridPaginationService.onPaginationChanged($scope.grid, options.paginationCurrentPage, options.paginationPageSize); } ); $scope.$on('$destroy', function() { deregT(); deregP(); }); $scope.cantPageForward = function () { if (options.totalItems > 0) { return options.paginationCurrentPage >= $scope.paginationApi.getTotalPages(); } else { return options.data.length < 1; } }; $scope.cantPageToLast = function () { if (options.totalItems > 0) { return $scope.cantPageForward(); } else { return true; } }; $scope.cantPageBackward = function () { return options.paginationCurrentPage <= 1; }; var focusToInputIf = function(condition){ if (condition){ gridUtil.focus.bySelector($elm, defaultFocusElementSelector); } }; //Takes care of setting focus to the middle element when focus is lost $scope.pageFirstPageClick = function () { $scope.paginationApi.seek(1); focusToInputIf($scope.cantPageBackward()); }; $scope.pagePreviousPageClick = function () { $scope.paginationApi.previousPage(); focusToInputIf($scope.cantPageBackward()); }; $scope.pageNextPageClick = function () { $scope.paginationApi.nextPage(); focusToInputIf($scope.cantPageForward()); }; $scope.pageLastPageClick = function () { $scope.paginationApi.seek($scope.paginationApi.getTotalPages()); focusToInputIf($scope.cantPageToLast()); }; } }; } ]); })(); (function () { 'use strict'; /** * @ngdoc overview * @name ui.grid.pinning * @description * * # ui.grid.pinning * * <div class="alert alert-success" role="alert"><strong>Stable</strong> This feature is stable. There should no longer be breaking api changes without a deprecation warning.</div> * * This module provides column pinning to the end user via menu options in the column header * * <div doc-module-components="ui.grid.pinning"></div> */ var module = angular.module('ui.grid.pinning', ['ui.grid']); module.constant('uiGridPinningConstants', { container: { LEFT: 'left', RIGHT: 'right', NONE: '' } }); module.service('uiGridPinningService', ['gridUtil', 'GridRenderContainer', 'i18nService', 'uiGridPinningConstants', function (gridUtil, GridRenderContainer, i18nService, uiGridPinningConstants) { var service = { initializeGrid: function (grid) { service.defaultGridOptions(grid.options); // Register a column builder to add new menu items for pinning left and right grid.registerColumnBuilder(service.pinningColumnBuilder); /** * @ngdoc object * @name ui.grid.pinning.api:PublicApi * * @description Public Api for pinning feature */ var publicApi = { events: { pinning: { /** * @ngdoc event * @name columnPin * @eventOf ui.grid.pinning.api:PublicApi * @description raised when column pin state has changed * <pre> * gridApi.pinning.on.columnPinned(scope, function(colDef){}) * </pre> * @param {object} colDef the column that was changed * @param {string} container the render container the column is in ('left', 'right', '') */ columnPinned: function(colDef, container) { } } }, methods: { pinning: { /** * @ngdoc function * @name pinColumn * @methodOf ui.grid.pinning.api:PublicApi * @description pin column left, right, or none * <pre> * gridApi.pinning.pinColumn(col, uiGridPinningConstants.container.LEFT) * </pre> * @param {gridColumn} col the column being pinned * @param {string} container one of the recognised types * from uiGridPinningConstants */ pinColumn: function(col, container) { service.pinColumn(grid, col, container); } } } }; grid.api.registerEventsFromObject(publicApi.events); grid.api.registerMethodsFromObject(publicApi.methods); }, defaultGridOptions: function (gridOptions) { //default option to true unless it was explicitly set to false /** * @ngdoc object * @name ui.grid.pinning.api:GridOptions * * @description GridOptions for pinning feature, these are available to be * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions} */ /** * @ngdoc object * @name enablePinning * @propertyOf ui.grid.pinning.api:GridOptions * @description Enable pinning for the entire grid. * <br/>Defaults to true */ gridOptions.enablePinning = gridOptions.enablePinning !== false; }, pinningColumnBuilder: function (colDef, col, gridOptions) { //default to true unless gridOptions or colDef is explicitly false /** * @ngdoc object * @name ui.grid.pinning.api:ColumnDef * * @description ColumnDef for pinning feature, these are available to be * set using the ui-grid {@link ui.grid.class:GridOptions.columnDef gridOptions.columnDefs} */ /** * @ngdoc object * @name enablePinning * @propertyOf ui.grid.pinning.api:ColumnDef * @description Enable pinning for the individual column. * <br/>Defaults to true */ colDef.enablePinning = colDef.enablePinning === undefined ? gridOptions.enablePinning : colDef.enablePinning; /** * @ngdoc object * @name pinnedLeft * @propertyOf ui.grid.pinning.api:ColumnDef * @description Column is pinned left when grid is rendered * <br/>Defaults to false */ /** * @ngdoc object * @name pinnedRight * @propertyOf ui.grid.pinning.api:ColumnDef * @description Column is pinned right when grid is rendered * <br/>Defaults to false */ if (colDef.pinnedLeft) { col.renderContainer = 'left'; col.grid.createLeftContainer(); } else if (colDef.pinnedRight) { col.renderContainer = 'right'; col.grid.createRightContainer(); } if (!colDef.enablePinning) { return; } var pinColumnLeftAction = { name: 'ui.grid.pinning.pinLeft', title: i18nService.get().pinning.pinLeft, icon: 'ui-grid-icon-left-open', shown: function () { return typeof(this.context.col.renderContainer) === 'undefined' || !this.context.col.renderContainer || this.context.col.renderContainer !== 'left'; }, action: function () { service.pinColumn(this.context.col.grid, this.context.col, uiGridPinningConstants.container.LEFT); } }; var pinColumnRightAction = { name: 'ui.grid.pinning.pinRight', title: i18nService.get().pinning.pinRight, icon: 'ui-grid-icon-right-open', shown: function () { return typeof(this.context.col.renderContainer) === 'undefined' || !this.context.col.renderContainer || this.context.col.renderContainer !== 'right'; }, action: function () { service.pinColumn(this.context.col.grid, this.context.col, uiGridPinningConstants.container.RIGHT); } }; var removePinAction = { name: 'ui.grid.pinning.unpin', title: i18nService.get().pinning.unpin, icon: 'ui-grid-icon-cancel', shown: function () { return typeof(this.context.col.renderContainer) !== 'undefined' && this.context.col.renderContainer !== null && this.context.col.renderContainer !== 'body'; }, action: function () { service.pinColumn(this.context.col.grid, this.context.col, uiGridPinningConstants.container.UNPIN); } }; if (!gridUtil.arrayContainsObjectWithProperty(col.menuItems, 'name', 'ui.grid.pinning.pinLeft')) { col.menuItems.push(pinColumnLeftAction); } if (!gridUtil.arrayContainsObjectWithProperty(col.menuItems, 'name', 'ui.grid.pinning.pinRight')) { col.menuItems.push(pinColumnRightAction); } if (!gridUtil.arrayContainsObjectWithProperty(col.menuItems, 'name', 'ui.grid.pinning.unpin')) { col.menuItems.push(removePinAction); } }, pinColumn: function(grid, col, container) { if (container === uiGridPinningConstants.container.NONE) { col.renderContainer = null; } else { col.renderContainer = container; if (container === uiGridPinningConstants.container.LEFT) { grid.createLeftContainer(); } else if (container === uiGridPinningConstants.container.RIGHT) { grid.createRightContainer(); } } grid.refresh() .then(function() { grid.api.pinning.raise.columnPinned( col.colDef, container ); }); } }; return service; }]); module.directive('uiGridPinning', ['gridUtil', 'uiGridPinningService', function (gridUtil, uiGridPinningService) { return { require: 'uiGrid', scope: false, compile: function () { return { pre: function ($scope, $elm, $attrs, uiGridCtrl) { uiGridPinningService.initializeGrid(uiGridCtrl.grid); }, post: function ($scope, $elm, $attrs, uiGridCtrl) { } }; } }; }]); })(); (function(){ 'use strict'; /** * @ngdoc overview * @name ui.grid.resizeColumns * @description * * # ui.grid.resizeColumns * * <div class="alert alert-success" role="alert"><strong>Stable</strong> This feature is stable. There should no longer be breaking api changes without a deprecation warning.</div> * * This module allows columns to be resized. */ var module = angular.module('ui.grid.resizeColumns', ['ui.grid']); module.service('uiGridResizeColumnsService', ['gridUtil', '$q', '$timeout', function (gridUtil, $q, $timeout) { var service = { defaultGridOptions: function(gridOptions){ //default option to true unless it was explicitly set to false /** * @ngdoc object * @name ui.grid.resizeColumns.api:GridOptions * * @description GridOptions for resizeColumns feature, these are available to be * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions} */ /** * @ngdoc object * @name enableColumnResizing * @propertyOf ui.grid.resizeColumns.api:GridOptions * @description Enable column resizing on the entire grid * <br/>Defaults to true */ gridOptions.enableColumnResizing = gridOptions.enableColumnResizing !== false; //legacy support //use old name if it is explicitly false if (gridOptions.enableColumnResize === false){ gridOptions.enableColumnResizing = false; } }, colResizerColumnBuilder: function (colDef, col, gridOptions) { var promises = []; /** * @ngdoc object * @name ui.grid.resizeColumns.api:ColumnDef * * @description ColumnDef for resizeColumns feature, these are available to be * set using the ui-grid {@link ui.grid.class:GridOptions.columnDef gridOptions.columnDefs} */ /** * @ngdoc object * @name enableColumnResizing * @propertyOf ui.grid.resizeColumns.api:ColumnDef * @description Enable column resizing on an individual column * <br/>Defaults to GridOptions.enableColumnResizing */ //default to true unless gridOptions or colDef is explicitly false colDef.enableColumnResizing = colDef.enableColumnResizing === undefined ? gridOptions.enableColumnResizing : colDef.enableColumnResizing; //legacy support of old option name if (colDef.enableColumnResize === false){ colDef.enableColumnResizing = false; } return $q.all(promises); }, registerPublicApi: function (grid) { /** * @ngdoc object * @name ui.grid.resizeColumns.api:PublicApi * @description Public Api for column resize feature. */ var publicApi = { events: { /** * @ngdoc event * @name columnSizeChanged * @eventOf ui.grid.resizeColumns.api:PublicApi * @description raised when column is resized * <pre> * gridApi.colResizable.on.columnSizeChanged(scope,function(colDef, deltaChange){}) * </pre> * @param {object} colDef the column that was resized * @param {integer} delta of the column size change */ colResizable: { columnSizeChanged: function (colDef, deltaChange) { } } } }; grid.api.registerEventsFromObject(publicApi.events); }, fireColumnSizeChanged: function (grid, colDef, deltaChange) { $timeout(function () { if ( grid.api.colResizable ){ grid.api.colResizable.raise.columnSizeChanged(colDef, deltaChange); } else { gridUtil.logError("The resizeable api is not registered, this may indicate that you've included the module but not added the 'ui-grid-resize-columns' directive to your grid definition. Cannot raise any events."); } }); }, // get either this column, or the column next to this column, to resize, // returns the column we're going to resize findTargetCol: function(col, position, rtlMultiplier){ var renderContainer = col.getRenderContainer(); if (position === 'left') { // Get the column to the left of this one var colIndex = renderContainer.visibleColumnCache.indexOf(col); return renderContainer.visibleColumnCache[colIndex - 1 * rtlMultiplier]; } else { return col; } } }; return service; }]); /** * @ngdoc directive * @name ui.grid.resizeColumns.directive:uiGridResizeColumns * @element div * @restrict A * @description * Enables resizing for all columns on the grid. If, for some reason, you want to use the ui-grid-resize-columns directive, but not allow column resizing, you can explicitly set the * option to false. This prevents resizing for the entire grid, regardless of individual columnDef options. * * @example <doc:example module="app"> <doc:source> <script> var app = angular.module('app', ['ui.grid', 'ui.grid.resizeColumns']); app.controller('MainCtrl', ['$scope', function ($scope) { $scope.gridOpts = { data: [ { "name": "Ethel Price", "gender": "female", "company": "Enersol" }, { "name": "Claudine Neal", "gender": "female", "company": "Sealoud" }, { "name": "Beryl Rice", "gender": "female", "company": "Velity" }, { "name": "Wilder Gonzales", "gender": "male", "company": "Geekko" } ] }; }]); </script> <div ng-controller="MainCtrl"> <div class="testGrid" ui-grid="gridOpts" ui-grid-resize-columns ></div> </div> </doc:source> <doc:scenario> </doc:scenario> </doc:example> */ module.directive('uiGridResizeColumns', ['gridUtil', 'uiGridResizeColumnsService', function (gridUtil, uiGridResizeColumnsService) { return { replace: true, priority: 0, require: '^uiGrid', scope: false, compile: function () { return { pre: function ($scope, $elm, $attrs, uiGridCtrl) { uiGridResizeColumnsService.defaultGridOptions(uiGridCtrl.grid.options); uiGridCtrl.grid.registerColumnBuilder( uiGridResizeColumnsService.colResizerColumnBuilder); uiGridResizeColumnsService.registerPublicApi(uiGridCtrl.grid); }, post: function ($scope, $elm, $attrs, uiGridCtrl) { } }; } }; }]); // Extend the uiGridHeaderCell directive module.directive('uiGridHeaderCell', ['gridUtil', '$templateCache', '$compile', '$q', 'uiGridResizeColumnsService', 'uiGridConstants', '$timeout', function (gridUtil, $templateCache, $compile, $q, uiGridResizeColumnsService, uiGridConstants, $timeout) { return { // Run after the original uiGridHeaderCell priority: -10, require: '^uiGrid', // scope: false, compile: function() { return { post: function ($scope, $elm, $attrs, uiGridCtrl) { var grid = uiGridCtrl.grid; if (grid.options.enableColumnResizing) { var columnResizerElm = $templateCache.get('ui-grid/columnResizer'); var rtlMultiplier = 1; //when in RTL mode reverse the direction using the rtlMultiplier and change the position to left if (grid.isRTL()) { $scope.position = 'left'; rtlMultiplier = -1; } var displayResizers = function(){ // remove any existing resizers. var resizers = $elm[0].getElementsByClassName('ui-grid-column-resizer'); for ( var i = 0; i < resizers.length; i++ ){ angular.element(resizers[i]).remove(); } // get the target column for the left resizer var otherCol = uiGridResizeColumnsService.findTargetCol($scope.col, 'left', rtlMultiplier); var renderContainer = $scope.col.getRenderContainer(); // Don't append the left resizer if this is the first column or the column to the left of this one has resizing disabled if (otherCol && renderContainer.visibleColumnCache.indexOf($scope.col) !== 0 && otherCol.colDef.enableColumnResizing !== false) { var resizerLeft = angular.element(columnResizerElm).clone(); resizerLeft.attr('position', 'left'); $elm.prepend(resizerLeft); $compile(resizerLeft)($scope); } // Don't append the right resizer if this column has resizing disabled if ($scope.col.colDef.enableColumnResizing !== false) { var resizerRight = angular.element(columnResizerElm).clone(); resizerRight.attr('position', 'right'); $elm.append(resizerRight); $compile(resizerRight)($scope); } }; displayResizers(); var waitDisplay = function(){ $timeout(displayResizers); }; var dataChangeDereg = grid.registerDataChangeCallback( waitDisplay, [uiGridConstants.dataChange.COLUMN] ); $scope.$on( '$destroy', dataChangeDereg ); } } }; } }; }]); /** * @ngdoc directive * @name ui.grid.resizeColumns.directive:uiGridColumnResizer * @element div * @restrict A * * @description * Draggable handle that controls column resizing. * * @example <doc:example module="app"> <doc:source> <script> var app = angular.module('app', ['ui.grid', 'ui.grid.resizeColumns']); app.controller('MainCtrl', ['$scope', function ($scope) { $scope.gridOpts = { enableColumnResizing: true, data: [ { "name": "Ethel Price", "gender": "female", "company": "Enersol" }, { "name": "Claudine Neal", "gender": "female", "company": "Sealoud" }, { "name": "Beryl Rice", "gender": "female", "company": "Velity" }, { "name": "Wilder Gonzales", "gender": "male", "company": "Geekko" } ] }; }]); </script> <div ng-controller="MainCtrl"> <div class="testGrid" ui-grid="gridOpts"></div> </div> </doc:source> <doc:scenario> // TODO: e2e specs? // TODO: post-resize a horizontal scroll event should be fired </doc:scenario> </doc:example> */ module.directive('uiGridColumnResizer', ['$document', 'gridUtil', 'uiGridConstants', 'uiGridResizeColumnsService', function ($document, gridUtil, uiGridConstants, uiGridResizeColumnsService) { var resizeOverlay = angular.element('<div class="ui-grid-resize-overlay"></div>'); var resizer = { priority: 0, scope: { col: '=', position: '@', renderIndex: '=' }, require: '?^uiGrid', link: function ($scope, $elm, $attrs, uiGridCtrl) { var startX = 0, x = 0, gridLeft = 0, rtlMultiplier = 1; //when in RTL mode reverse the direction using the rtlMultiplier and change the position to left if (uiGridCtrl.grid.isRTL()) { $scope.position = 'left'; rtlMultiplier = -1; } if ($scope.position === 'left') { $elm.addClass('left'); } else if ($scope.position === 'right') { $elm.addClass('right'); } // Refresh the grid canvas // takes an argument representing the diff along the X-axis that the resize had function refreshCanvas(xDiff) { // Then refresh the grid canvas, rebuilding the styles so that the scrollbar updates its size uiGridCtrl.grid.refreshCanvas(true).then( function() { uiGridCtrl.grid.queueGridRefresh(); }); } // Check that the requested width isn't wider than the maxWidth, or narrower than the minWidth // Returns the new recommended with, after constraints applied function constrainWidth(col, width){ var newWidth = width; // If the new width would be less than the column's allowably minimum width, don't allow it if (col.minWidth && newWidth < col.minWidth) { newWidth = col.minWidth; } else if (col.maxWidth && newWidth > col.maxWidth) { newWidth = col.maxWidth; } return newWidth; } /* * Our approach to event handling aims to deal with both touch devices and mouse devices * We register down handlers on both touch and mouse. When a touchstart or mousedown event * occurs, we register the corresponding touchmove/touchend, or mousemove/mouseend events. * * This way we can listen for both without worrying about the fact many touch devices also emulate * mouse events - basically whichever one we hear first is what we'll go with. */ function moveFunction(event, args) { if (event.originalEvent) { event = event.originalEvent; } event.preventDefault(); x = (event.targetTouches ? event.targetTouches[0] : event).clientX - gridLeft; if (x < 0) { x = 0; } else if (x > uiGridCtrl.grid.gridWidth) { x = uiGridCtrl.grid.gridWidth; } var col = uiGridResizeColumnsService.findTargetCol($scope.col, $scope.position, rtlMultiplier); // Don't resize if it's disabled on this column if (col.colDef.enableColumnResizing === false) { return; } if (!uiGridCtrl.grid.element.hasClass('column-resizing')) { uiGridCtrl.grid.element.addClass('column-resizing'); } // Get the diff along the X axis var xDiff = x - startX; // Get the width that this mouse would give the column var newWidth = parseInt(col.drawnWidth + xDiff * rtlMultiplier, 10); // check we're not outside the allowable bounds for this column x = x + ( constrainWidth(col, newWidth) - newWidth ) * rtlMultiplier; resizeOverlay.css({ left: x + 'px' }); uiGridCtrl.fireEvent(uiGridConstants.events.ITEM_DRAGGING); } function upFunction(event, args) { if (event.originalEvent) { event = event.originalEvent; } event.preventDefault(); uiGridCtrl.grid.element.removeClass('column-resizing'); resizeOverlay.remove(); // Resize the column x = (event.changedTouches ? event.changedTouches[0] : event).clientX - gridLeft; var xDiff = x - startX; if (xDiff === 0) { // no movement, so just reset event handlers, including turning back on both // down events - we turned one off when this event started offAllEvents(); onDownEvents(); return; } var col = uiGridResizeColumnsService.findTargetCol($scope.col, $scope.position, rtlMultiplier); // Don't resize if it's disabled on this column if (col.colDef.enableColumnResizing === false) { return; } // Get the new width var newWidth = parseInt(col.drawnWidth + xDiff * rtlMultiplier, 10); // check we're not outside the allowable bounds for this column col.width = constrainWidth(col, newWidth); col.hasCustomWidth = true; refreshCanvas(xDiff); uiGridResizeColumnsService.fireColumnSizeChanged(uiGridCtrl.grid, col.colDef, xDiff); // stop listening of up and move events - wait for next down // reset the down events - we will have turned one off when this event started offAllEvents(); onDownEvents(); } var downFunction = function(event, args) { if (event.originalEvent) { event = event.originalEvent; } event.stopPropagation(); // Get the left offset of the grid // gridLeft = uiGridCtrl.grid.element[0].offsetLeft; gridLeft = uiGridCtrl.grid.element[0].getBoundingClientRect().left; // Get the starting X position, which is the X coordinate of the click minus the grid's offset startX = (event.targetTouches ? event.targetTouches[0] : event).clientX - gridLeft; // Append the resizer overlay uiGridCtrl.grid.element.append(resizeOverlay); // Place the resizer overlay at the start position resizeOverlay.css({ left: startX }); // Add handlers for move and up events - if we were mousedown then we listen for mousemove and mouseup, if // we were touchdown then we listen for touchmove and touchup. Also remove the handler for the equivalent // down event - so if we're touchdown, then remove the mousedown handler until this event is over, if we're // mousedown then remove the touchdown handler until this event is over, this avoids processing duplicate events if ( event.type === 'touchstart' ){ $document.on('touchend', upFunction); $document.on('touchmove', moveFunction); $elm.off('mousedown', downFunction); } else { $document.on('mouseup', upFunction); $document.on('mousemove', moveFunction); $elm.off('touchstart', downFunction); } }; var onDownEvents = function() { $elm.on('mousedown', downFunction); $elm.on('touchstart', downFunction); }; var offAllEvents = function() { $document.off('mouseup', upFunction); $document.off('touchend', upFunction); $document.off('mousemove', moveFunction); $document.off('touchmove', moveFunction); $elm.off('mousedown', downFunction); $elm.off('touchstart', downFunction); }; onDownEvents(); // On doubleclick, resize to fit all rendered cells var dblClickFn = function(event, args){ event.stopPropagation(); var col = uiGridResizeColumnsService.findTargetCol($scope.col, $scope.position, rtlMultiplier); // Don't resize if it's disabled on this column if (col.colDef.enableColumnResizing === false) { return; } // Go through the rendered rows and find out the max size for the data in this column var maxWidth = 0; var xDiff = 0; // Get the parent render container element var renderContainerElm = gridUtil.closestElm($elm, '.ui-grid-render-container'); // Get the cell contents so we measure correctly. For the header cell we have to account for the sort icon and the menu buttons, if present var cells = renderContainerElm.querySelectorAll('.' + uiGridConstants.COL_CLASS_PREFIX + col.uid + ' .ui-grid-cell-contents'); Array.prototype.forEach.call(cells, function (cell) { // Get the cell width // gridUtil.logDebug('width', gridUtil.elementWidth(cell)); // Account for the menu button if it exists var menuButton; if (angular.element(cell).parent().hasClass('ui-grid-header-cell')) { menuButton = angular.element(cell).parent()[0].querySelectorAll('.ui-grid-column-menu-button'); } gridUtil.fakeElement(cell, {}, function(newElm) { // Make the element float since it's a div and can expand to fill its container var e = angular.element(newElm); e.attr('style', 'float: left'); var width = gridUtil.elementWidth(e); if (menuButton) { var menuButtonWidth = gridUtil.elementWidth(menuButton); width = width + menuButtonWidth; } if (width > maxWidth) { maxWidth = width; xDiff = maxWidth - width; } }); }); // check we're not outside the allowable bounds for this column col.width = constrainWidth(col, maxWidth); col.hasCustomWidth = true; refreshCanvas(xDiff); uiGridResizeColumnsService.fireColumnSizeChanged(uiGridCtrl.grid, col.colDef, xDiff); }; $elm.on('dblclick', dblClickFn); $elm.on('$destroy', function() { $elm.off('dblclick', dblClickFn); offAllEvents(); }); } }; return resizer; }]); })(); (function () { 'use strict'; /** * @ngdoc overview * @name ui.grid.rowEdit * @description * * # ui.grid.rowEdit * * <div class="alert alert-success" role="alert"><strong>Stable</strong> This feature is stable. There should no longer be breaking api changes without a deprecation warning.</div> * * This module extends the edit feature to provide tracking and saving of rows * of data. The tutorial provides more information on how this feature is best * used {@link tutorial/205_row_editable here}. * <br/> * This feature depends on usage of the ui-grid-edit feature, and also benefits * from use of ui-grid-cellNav to provide the full spreadsheet-like editing * experience * */ var module = angular.module('ui.grid.rowEdit', ['ui.grid', 'ui.grid.edit', 'ui.grid.cellNav']); /** * @ngdoc object * @name ui.grid.rowEdit.constant:uiGridRowEditConstants * * @description constants available in row edit module */ module.constant('uiGridRowEditConstants', { }); /** * @ngdoc service * @name ui.grid.rowEdit.service:uiGridRowEditService * * @description Services for row editing features */ module.service('uiGridRowEditService', ['$interval', '$q', 'uiGridConstants', 'uiGridRowEditConstants', 'gridUtil', function ($interval, $q, uiGridConstants, uiGridRowEditConstants, gridUtil) { var service = { initializeGrid: function (scope, grid) { /** * @ngdoc object * @name ui.grid.rowEdit.api:PublicApi * * @description Public Api for rowEdit feature */ grid.rowEdit = {}; var publicApi = { events: { rowEdit: { /** * @ngdoc event * @eventOf ui.grid.rowEdit.api:PublicApi * @name saveRow * @description raised when a row is ready for saving. Once your * row has saved you may need to use angular.extend to update the * data entity with any changed data from your save (for example, * lock version information if you're using optimistic locking, * or last update time/user information). * * Your method should call setSavePromise somewhere in the body before * returning control. The feature will then wait, with the gridRow greyed out * whilst this promise is being resolved. * * <pre> * gridApi.rowEdit.on.saveRow(scope,function(rowEntity){}) * </pre> * and somewhere within the event handler: * <pre> * gridApi.rowEdit.setSavePromise( rowEntity, savePromise) * </pre> * @param {object} rowEntity the options.data element that was edited * @returns {promise} Your saveRow method should return a promise, the * promise should either be resolved (implying successful save), or * rejected (implying an error). */ saveRow: function (rowEntity) { } } }, methods: { rowEdit: { /** * @ngdoc method * @methodOf ui.grid.rowEdit.api:PublicApi * @name setSavePromise * @description Sets the promise associated with the row save, mandatory that * the saveRow event handler calls this method somewhere before returning. * <pre> * gridApi.rowEdit.setSavePromise(rowEntity, savePromise) * </pre> * @param {object} rowEntity a data row from the grid for which a save has * been initiated * @param {promise} savePromise the promise that will be resolved when the * save is successful, or rejected if the save fails * */ setSavePromise: function ( rowEntity, savePromise) { service.setSavePromise(grid, rowEntity, savePromise); }, /** * @ngdoc method * @methodOf ui.grid.rowEdit.api:PublicApi * @name getDirtyRows * @description Returns all currently dirty rows * <pre> * gridApi.rowEdit.getDirtyRows(grid) * </pre> * @returns {array} An array of gridRows that are currently dirty * */ getDirtyRows: function () { return grid.rowEdit.dirtyRows ? grid.rowEdit.dirtyRows : []; }, /** * @ngdoc method * @methodOf ui.grid.rowEdit.api:PublicApi * @name getErrorRows * @description Returns all currently errored rows * <pre> * gridApi.rowEdit.getErrorRows(grid) * </pre> * @returns {array} An array of gridRows that are currently in error * */ getErrorRows: function () { return grid.rowEdit.errorRows ? grid.rowEdit.errorRows : []; }, /** * @ngdoc method * @methodOf ui.grid.rowEdit.api:PublicApi * @name flushDirtyRows * @description Triggers a save event for all currently dirty rows, could * be used where user presses a save button or navigates away from the page * <pre> * gridApi.rowEdit.flushDirtyRows(grid) * </pre> * @returns {promise} a promise that represents the aggregate of all * of the individual save promises - i.e. it will be resolved when all * the individual save promises have been resolved. * */ flushDirtyRows: function () { return service.flushDirtyRows(grid); }, /** * @ngdoc method * @methodOf ui.grid.rowEdit.api:PublicApi * @name setRowsDirty * @description Sets each of the rows passed in dataRows * to be dirty. note that if you have only just inserted the * rows into your data you will need to wait for a $digest cycle * before the gridRows are present - so often you would wrap this * call in a $interval or $timeout * <pre> * $interval( function() { * gridApi.rowEdit.setRowsDirty(myDataRows); * }, 0, 1); * </pre> * @param {array} dataRows the data entities for which the gridRows * should be set dirty. * */ setRowsDirty: function ( dataRows) { service.setRowsDirty(grid, dataRows); }, /** * @ngdoc method * @methodOf ui.grid.rowEdit.api:PublicApi * @name setRowsClean * @description Sets each of the rows passed in dataRows * to be clean, removing them from the dirty cache and the error cache, * and clearing the error flag and the dirty flag * <pre> * var gridRows = $scope.gridApi.rowEdit.getDirtyRows(); * var dataRows = gridRows.map( function( gridRow ) { return gridRow.entity; }); * $scope.gridApi.rowEdit.setRowsClean( dataRows ); * </pre> * @param {array} dataRows the data entities for which the gridRows * should be set clean. * */ setRowsClean: function ( dataRows) { service.setRowsClean(grid, dataRows); } } } }; grid.api.registerEventsFromObject(publicApi.events); grid.api.registerMethodsFromObject(publicApi.methods); grid.api.core.on.renderingComplete( scope, function ( gridApi ) { grid.api.edit.on.afterCellEdit( scope, service.endEditCell ); grid.api.edit.on.beginCellEdit( scope, service.beginEditCell ); grid.api.edit.on.cancelCellEdit( scope, service.cancelEditCell ); if ( grid.api.cellNav ) { grid.api.cellNav.on.navigate( scope, service.navigate ); } }); }, defaultGridOptions: function (gridOptions) { /** * @ngdoc object * @name ui.grid.rowEdit.api:GridOptions * * @description Options for configuring the rowEdit feature, these are available to be * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions} */ }, /** * @ngdoc method * @methodOf ui.grid.rowEdit.service:uiGridRowEditService * @name saveRow * @description Returns a function that saves the specified row from the grid, * and returns a promise * @param {object} grid the grid for which dirty rows should be flushed * @param {GridRow} gridRow the row that should be saved * @returns {function} the saveRow function returns a function. That function * in turn, when called, returns a promise relating to the save callback */ saveRow: function ( grid, gridRow ) { var self = this; return function() { gridRow.isSaving = true; if ( gridRow.rowEditSavePromise ){ // don't save the row again if it's already saving - that causes stale object exceptions return gridRow.rowEditSavePromise; } var promise = grid.api.rowEdit.raise.saveRow( gridRow.entity ); if ( gridRow.rowEditSavePromise ){ gridRow.rowEditSavePromise.then( self.processSuccessPromise( grid, gridRow ), self.processErrorPromise( grid, gridRow )); } else { gridUtil.logError( 'A promise was not returned when saveRow event was raised, either nobody is listening to event, or event handler did not return a promise' ); } return promise; }; }, /** * @ngdoc method * @methodOf ui.grid.rowEdit.service:uiGridRowEditService * @name setSavePromise * @description Sets the promise associated with the row save, mandatory that * the saveRow event handler calls this method somewhere before returning. * <pre> * gridApi.rowEdit.setSavePromise(grid, rowEntity) * </pre> * @param {object} grid the grid for which dirty rows should be returned * @param {object} rowEntity a data row from the grid for which a save has * been initiated * @param {promise} savePromise the promise that will be resolved when the * save is successful, or rejected if the save fails * */ setSavePromise: function (grid, rowEntity, savePromise) { var gridRow = grid.getRow( rowEntity ); gridRow.rowEditSavePromise = savePromise; }, /** * @ngdoc method * @methodOf ui.grid.rowEdit.service:uiGridRowEditService * @name processSuccessPromise * @description Returns a function that processes the successful * resolution of a save promise * @param {object} grid the grid for which the promise should be processed * @param {GridRow} gridRow the row that has been saved * @returns {function} the success handling function */ processSuccessPromise: function ( grid, gridRow ) { var self = this; return function() { delete gridRow.isSaving; delete gridRow.isDirty; delete gridRow.isError; delete gridRow.rowEditSaveTimer; delete gridRow.rowEditSavePromise; self.removeRow( grid.rowEdit.errorRows, gridRow ); self.removeRow( grid.rowEdit.dirtyRows, gridRow ); }; }, /** * @ngdoc method * @methodOf ui.grid.rowEdit.service:uiGridRowEditService * @name processErrorPromise * @description Returns a function that processes the failed * resolution of a save promise * @param {object} grid the grid for which the promise should be processed * @param {GridRow} gridRow the row that is now in error * @returns {function} the error handling function */ processErrorPromise: function ( grid, gridRow ) { return function() { delete gridRow.isSaving; delete gridRow.rowEditSaveTimer; delete gridRow.rowEditSavePromise; gridRow.isError = true; if (!grid.rowEdit.errorRows){ grid.rowEdit.errorRows = []; } if (!service.isRowPresent( grid.rowEdit.errorRows, gridRow ) ){ grid.rowEdit.errorRows.push( gridRow ); } }; }, /** * @ngdoc method * @methodOf ui.grid.rowEdit.service:uiGridRowEditService * @name removeRow * @description Removes a row from a cache of rows - either * grid.rowEdit.errorRows or grid.rowEdit.dirtyRows. If the row * is not present silently does nothing. * @param {array} rowArray the array from which to remove the row * @param {GridRow} gridRow the row that should be removed */ removeRow: function( rowArray, removeGridRow ){ if (typeof(rowArray) === 'undefined' || rowArray === null){ return; } rowArray.forEach( function( gridRow, index ){ if ( gridRow.uid === removeGridRow.uid ){ rowArray.splice( index, 1); } }); }, /** * @ngdoc method * @methodOf ui.grid.rowEdit.service:uiGridRowEditService * @name isRowPresent * @description Checks whether a row is already present * in the given array * @param {array} rowArray the array in which to look for the row * @param {GridRow} gridRow the row that should be looked for */ isRowPresent: function( rowArray, removeGridRow ){ var present = false; rowArray.forEach( function( gridRow, index ){ if ( gridRow.uid === removeGridRow.uid ){ present = true; } }); return present; }, /** * @ngdoc method * @methodOf ui.grid.rowEdit.service:uiGridRowEditService * @name flushDirtyRows * @description Triggers a save event for all currently dirty rows, could * be used where user presses a save button or navigates away from the page * <pre> * gridApi.rowEdit.flushDirtyRows(grid) * </pre> * @param {object} grid the grid for which dirty rows should be flushed * @returns {promise} a promise that represents the aggregate of all * of the individual save promises - i.e. it will be resolved when all * the individual save promises have been resolved. * */ flushDirtyRows: function(grid){ var promises = []; grid.api.rowEdit.getDirtyRows().forEach( function( gridRow ){ service.saveRow( grid, gridRow )(); promises.push( gridRow.rowEditSavePromise ); }); return $q.all( promises ); }, /** * @ngdoc method * @methodOf ui.grid.rowEdit.service:uiGridRowEditService * @name endEditCell * @description Receives an afterCellEdit event from the edit function, * and sets flags as appropriate. Only the rowEntity parameter * is processed, although other params are available. Grid * is automatically provided by the gridApi. * @param {object} rowEntity the data entity for which the cell * was edited */ endEditCell: function( rowEntity, colDef, newValue, previousValue ){ var grid = this.grid; var gridRow = grid.getRow( rowEntity ); if ( !gridRow ){ gridUtil.logError( 'Unable to find rowEntity in grid data, dirty flag cannot be set' ); return; } if ( newValue !== previousValue || gridRow.isDirty ){ if ( !grid.rowEdit.dirtyRows ){ grid.rowEdit.dirtyRows = []; } if ( !gridRow.isDirty ){ gridRow.isDirty = true; grid.rowEdit.dirtyRows.push( gridRow ); } delete gridRow.isError; service.considerSetTimer( grid, gridRow ); } }, /** * @ngdoc method * @methodOf ui.grid.rowEdit.service:uiGridRowEditService * @name beginEditCell * @description Receives a beginCellEdit event from the edit function, * and cancels any rowEditSaveTimers if present, as the user is still editing * this row. Only the rowEntity parameter * is processed, although other params are available. Grid * is automatically provided by the gridApi. * @param {object} rowEntity the data entity for which the cell * editing has commenced */ beginEditCell: function( rowEntity, colDef ){ var grid = this.grid; var gridRow = grid.getRow( rowEntity ); if ( !gridRow ){ gridUtil.logError( 'Unable to find rowEntity in grid data, timer cannot be cancelled' ); return; } service.cancelTimer( grid, gridRow ); }, /** * @ngdoc method * @methodOf ui.grid.rowEdit.service:uiGridRowEditService * @name cancelEditCell * @description Receives a cancelCellEdit event from the edit function, * and if the row was already dirty, restarts the save timer. If the row * was not already dirty, then it's not dirty now either and does nothing. * * Only the rowEntity parameter * is processed, although other params are available. Grid * is automatically provided by the gridApi. * * @param {object} rowEntity the data entity for which the cell * editing was cancelled */ cancelEditCell: function( rowEntity, colDef ){ var grid = this.grid; var gridRow = grid.getRow( rowEntity ); if ( !gridRow ){ gridUtil.logError( 'Unable to find rowEntity in grid data, timer cannot be set' ); return; } service.considerSetTimer( grid, gridRow ); }, /** * @ngdoc method * @methodOf ui.grid.rowEdit.service:uiGridRowEditService * @name navigate * @description cellNav tells us that the selected cell has changed. If * the new row had a timer running, then stop it similar to in a beginCellEdit * call. If the old row is dirty and not the same as the new row, then * start a timer on it. * @param {object} newRowCol the row and column that were selected * @param {object} oldRowCol the row and column that was left * */ navigate: function( newRowCol, oldRowCol ){ var grid = this.grid; if ( newRowCol.row.rowEditSaveTimer ){ service.cancelTimer( grid, newRowCol.row ); } if ( oldRowCol && oldRowCol.row && oldRowCol.row !== newRowCol.row ){ service.considerSetTimer( grid, oldRowCol.row ); } }, /** * @ngdoc property * @propertyOf ui.grid.rowEdit.api:GridOptions * @name rowEditWaitInterval * @description How long the grid should wait for another change on this row * before triggering a save (in milliseconds). If set to -1, then saves are * never triggered by timer (implying that the user will call flushDirtyRows() * manually) * * @example * Setting the wait interval to 4 seconds * <pre> * $scope.gridOptions = { rowEditWaitInterval: 4000 } * </pre> * */ /** * @ngdoc method * @methodOf ui.grid.rowEdit.service:uiGridRowEditService * @name considerSetTimer * @description Consider setting a timer on this row (if it is dirty). if there is a timer running * on the row and the row isn't currently saving, cancel it, using cancelTimer, then if the row is * dirty and not currently saving then set a new timer * @param {object} grid the grid for which we are processing * @param {GridRow} gridRow the row for which the timer should be adjusted * */ considerSetTimer: function( grid, gridRow ){ service.cancelTimer( grid, gridRow ); if ( gridRow.isDirty && !gridRow.isSaving ){ if ( grid.options.rowEditWaitInterval !== -1 ){ var waitTime = grid.options.rowEditWaitInterval ? grid.options.rowEditWaitInterval : 2000; gridRow.rowEditSaveTimer = $interval( service.saveRow( grid, gridRow ), waitTime, 1); } } }, /** * @ngdoc method * @methodOf ui.grid.rowEdit.service:uiGridRowEditService * @name cancelTimer * @description cancel the $interval for any timer running on this row * then delete the timer itself * @param {object} grid the grid for which we are processing * @param {GridRow} gridRow the row for which the timer should be adjusted * */ cancelTimer: function( grid, gridRow ){ if ( gridRow.rowEditSaveTimer && !gridRow.isSaving ){ $interval.cancel(gridRow.rowEditSaveTimer); delete gridRow.rowEditSaveTimer; } }, /** * @ngdoc method * @methodOf ui.grid.rowEdit.service:uiGridRowEditService * @name setRowsDirty * @description Sets each of the rows passed in dataRows * to be dirty. note that if you have only just inserted the * rows into your data you will need to wait for a $digest cycle * before the gridRows are present - so often you would wrap this * call in a $interval or $timeout * <pre> * $interval( function() { * gridApi.rowEdit.setRowsDirty( myDataRows); * }, 0, 1); * </pre> * @param {object} grid the grid for which rows should be set dirty * @param {array} dataRows the data entities for which the gridRows * should be set dirty. * */ setRowsDirty: function( grid, myDataRows ) { var gridRow; myDataRows.forEach( function( value, index ){ gridRow = grid.getRow( value ); if ( gridRow ){ if ( !grid.rowEdit.dirtyRows ){ grid.rowEdit.dirtyRows = []; } if ( !gridRow.isDirty ){ gridRow.isDirty = true; grid.rowEdit.dirtyRows.push( gridRow ); } delete gridRow.isError; service.considerSetTimer( grid, gridRow ); } else { gridUtil.logError( "requested row not found in rowEdit.setRowsDirty, row was: " + value ); } }); }, /** * @ngdoc method * @methodOf ui.grid.rowEdit.service:uiGridRowEditService * @name setRowsClean * @description Sets each of the rows passed in dataRows * to be clean, clearing the dirty flag and the error flag, and removing * the rows from the dirty and error caches. * @param {object} grid the grid for which rows should be set clean * @param {array} dataRows the data entities for which the gridRows * should be set clean. * */ setRowsClean: function( grid, myDataRows ) { var gridRow; myDataRows.forEach( function( value, index ){ gridRow = grid.getRow( value ); if ( gridRow ){ delete gridRow.isDirty; service.removeRow( grid.rowEdit.dirtyRows, gridRow ); service.cancelTimer( grid, gridRow ); delete gridRow.isError; service.removeRow( grid.rowEdit.errorRows, gridRow ); } else { gridUtil.logError( "requested row not found in rowEdit.setRowsClean, row was: " + value ); } }); } }; return service; }]); /** * @ngdoc directive * @name ui.grid.rowEdit.directive:uiGridEdit * @element div * @restrict A * * @description Adds row editing features to the ui-grid-edit directive. * */ module.directive('uiGridRowEdit', ['gridUtil', 'uiGridRowEditService', 'uiGridEditConstants', function (gridUtil, uiGridRowEditService, uiGridEditConstants) { return { replace: true, priority: 0, require: '^uiGrid', scope: false, compile: function () { return { pre: function ($scope, $elm, $attrs, uiGridCtrl) { uiGridRowEditService.initializeGrid($scope, uiGridCtrl.grid); }, post: function ($scope, $elm, $attrs, uiGridCtrl) { } }; } }; }]); /** * @ngdoc directive * @name ui.grid.rowEdit.directive:uiGridViewport * @element div * * @description Stacks on top of ui.grid.uiGridViewport to alter the attributes used * for the grid row to allow coloring of saving and error rows */ module.directive('uiGridViewport', ['$compile', 'uiGridConstants', 'gridUtil', '$parse', function ($compile, uiGridConstants, gridUtil, $parse) { return { priority: -200, // run after default directive scope: false, compile: function ($elm, $attrs) { var rowRepeatDiv = angular.element($elm.children().children()[0]); var existingNgClass = rowRepeatDiv.attr("ng-class"); var newNgClass = ''; if ( existingNgClass ) { newNgClass = existingNgClass.slice(0, -1) + ", 'ui-grid-row-dirty': row.isDirty, 'ui-grid-row-saving': row.isSaving, 'ui-grid-row-error': row.isError}"; } else { newNgClass = "{'ui-grid-row-dirty': row.isDirty, 'ui-grid-row-saving': row.isSaving, 'ui-grid-row-error': row.isError}"; } rowRepeatDiv.attr("ng-class", newNgClass); return { pre: function ($scope, $elm, $attrs, controllers) { }, post: function ($scope, $elm, $attrs, controllers) { } }; } }; }]); })(); (function () { 'use strict'; /** * @ngdoc overview * @name ui.grid.saveState * @description * * # ui.grid.saveState * * <div class="alert alert-success" role="alert"><strong>Stable</strong> This feature is stable. There should no longer be breaking api changes without a deprecation warning.</div> * * This module provides the ability to save the grid state, and restore * it when the user returns to the page. * * No UI is provided, the caller should provide their own UI/buttons * as appropriate. Usually the navigate events would be used to save * the grid state and restore it. * * <br/> * <br/> * * <div doc-module-components="ui.grid.save-state"></div> */ var module = angular.module('ui.grid.saveState', ['ui.grid', 'ui.grid.selection', 'ui.grid.cellNav', 'ui.grid.grouping', 'ui.grid.pinning', 'ui.grid.treeView']); /** * @ngdoc object * @name ui.grid.saveState.constant:uiGridSaveStateConstants * * @description constants available in save state module */ module.constant('uiGridSaveStateConstants', { featureName: 'saveState' }); /** * @ngdoc service * @name ui.grid.saveState.service:uiGridSaveStateService * * @description Services for saveState feature */ module.service('uiGridSaveStateService', ['$q', 'uiGridSaveStateConstants', 'gridUtil', '$compile', '$interval', 'uiGridConstants', function ($q, uiGridSaveStateConstants, gridUtil, $compile, $interval, uiGridConstants ) { var service = { initializeGrid: function (grid) { //add feature namespace and any properties to grid for needed state grid.saveState = {}; this.defaultGridOptions(grid.options); /** * @ngdoc object * @name ui.grid.saveState.api:PublicApi * * @description Public Api for saveState feature */ var publicApi = { events: { saveState: { } }, methods: { saveState: { /** * @ngdoc function * @name save * @methodOf ui.grid.saveState.api:PublicApi * @description Packages the current state of the grid into * an object, and provides it to the user for saving * @returns {object} the state as a javascript object that can be saved */ save: function () { return service.save(grid); }, /** * @ngdoc function * @name restore * @methodOf ui.grid.saveState.api:PublicApi * @description Restores the provided state into the grid * @param {scope} $scope a scope that we can broadcast on * @param {object} state the state that should be restored into the grid */ restore: function ( $scope, state) { service.restore(grid, $scope, state); } } } }; grid.api.registerEventsFromObject(publicApi.events); grid.api.registerMethodsFromObject(publicApi.methods); }, defaultGridOptions: function (gridOptions) { //default option to true unless it was explicitly set to false /** * @ngdoc object * @name ui.grid.saveState.api:GridOptions * * @description GridOptions for saveState feature, these are available to be * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions} */ /** * @ngdoc object * @name saveWidths * @propertyOf ui.grid.saveState.api:GridOptions * @description Save the current column widths. Note that unless * you've provided the user with some way to resize their columns (say * the resize columns feature), then this makes little sense. * <br/>Defaults to true */ gridOptions.saveWidths = gridOptions.saveWidths !== false; /** * @ngdoc object * @name saveOrder * @propertyOf ui.grid.saveState.api:GridOptions * @description Restore the current column order. Note that unless * you've provided the user with some way to reorder their columns (for * example the move columns feature), this makes little sense. * <br/>Defaults to true */ gridOptions.saveOrder = gridOptions.saveOrder !== false; /** * @ngdoc object * @name saveScroll * @propertyOf ui.grid.saveState.api:GridOptions * @description Save the current scroll position. Note that this * is saved as the percentage of the grid scrolled - so if your * user returns to a grid with a significantly different number of * rows (perhaps some data has been deleted) then the scroll won't * actually show the same rows as before. If you want to scroll to * a specific row then you should instead use the saveFocus option, which * is the default. * * Note that this element will only be saved if the cellNav feature is * enabled * <br/>Defaults to false */ gridOptions.saveScroll = gridOptions.saveScroll === true; /** * @ngdoc object * @name saveFocus * @propertyOf ui.grid.saveState.api:GridOptions * @description Save the current focused cell. On returning * to this focused cell we'll also scroll. This option is * preferred to the saveScroll option, so is set to true by * default. If saveScroll is set to true then this option will * be disabled. * * By default this option saves the current row number and column * number, and returns to that row and column. However, if you define * a saveRowIdentity function, then it will return you to the currently * selected column within that row (in a business sense - so if some * rows have been deleted, it will still find the same data, presuming it * still exists in the list. If it isn't in the list then it will instead * return to the same row number - i.e. scroll percentage) * * Note that this option will do nothing if the cellNav * feature is not enabled. * * <br/>Defaults to true (unless saveScroll is true) */ gridOptions.saveFocus = gridOptions.saveScroll !== true && gridOptions.saveFocus !== false; /** * @ngdoc object * @name saveRowIdentity * @propertyOf ui.grid.saveState.api:GridOptions * @description A function that can be called, passing in a rowEntity, * and that will return a unique id for that row. This might simply * return the `id` field from that row (if you have one), or it might * concatenate some fields within the row to make a unique value. * * This value will be used to find the same row again and set the focus * to it, if it exists when we return. * * <br/>Defaults to undefined */ /** * @ngdoc object * @name saveVisible * @propertyOf ui.grid.saveState.api:GridOptions * @description Save whether or not columns are visible. * * <br/>Defaults to true */ gridOptions.saveVisible = gridOptions.saveVisible !== false; /** * @ngdoc object * @name saveSort * @propertyOf ui.grid.saveState.api:GridOptions * @description Save the current sort state for each column * * <br/>Defaults to true */ gridOptions.saveSort = gridOptions.saveSort !== false; /** * @ngdoc object * @name saveFilter * @propertyOf ui.grid.saveState.api:GridOptions * @description Save the current filter state for each column * * <br/>Defaults to true */ gridOptions.saveFilter = gridOptions.saveFilter !== false; /** * @ngdoc object * @name saveSelection * @propertyOf ui.grid.saveState.api:GridOptions * @description Save the currently selected rows. If the `saveRowIdentity` callback * is defined, then it will save the id of the row and select that. If not, then * it will attempt to select the rows by row number, which will give the wrong results * if the data set has changed in the mean-time. * * Note that this option only does anything * if the selection feature is enabled. * * <br/>Defaults to true */ gridOptions.saveSelection = gridOptions.saveSelection !== false; /** * @ngdoc object * @name saveGrouping * @propertyOf ui.grid.saveState.api:GridOptions * @description Save the grouping configuration. If set to true and the * grouping feature is not enabled then does nothing. * * <br/>Defaults to true */ gridOptions.saveGrouping = gridOptions.saveGrouping !== false; /** * @ngdoc object * @name saveGroupingExpandedStates * @propertyOf ui.grid.saveState.api:GridOptions * @description Save the grouping row expanded states. If set to true and the * grouping feature is not enabled then does nothing. * * This can be quite a bit of data, in many cases you wouldn't want to save this * information. * * <br/>Defaults to false */ gridOptions.saveGroupingExpandedStates = gridOptions.saveGroupingExpandedStates === true; /** * @ngdoc object * @name savePinning * @propertyOf ui.grid.saveState.api:GridOptions * @description Save pinning state for columns. * * <br/>Defaults to true */ gridOptions.savePinning = gridOptions.savePinning !== false; /** * @ngdoc object * @name saveTreeView * @propertyOf ui.grid.saveState.api:GridOptions * @description Save the treeView configuration. If set to true and the * treeView feature is not enabled then does nothing. * * <br/>Defaults to true */ gridOptions.saveTreeView = gridOptions.saveTreeView !== false; }, /** * @ngdoc function * @name save * @methodOf ui.grid.saveState.service:uiGridSaveStateService * @description Saves the current grid state into an object, and * passes that object back to the caller * @param {Grid} grid the grid whose state we'd like to save * @returns {object} the state ready to be saved */ save: function (grid) { var savedState = {}; savedState.columns = service.saveColumns( grid ); savedState.scrollFocus = service.saveScrollFocus( grid ); savedState.selection = service.saveSelection( grid ); savedState.grouping = service.saveGrouping( grid ); savedState.treeView = service.saveTreeView( grid ); return savedState; }, /** * @ngdoc function * @name restore * @methodOf ui.grid.saveState.service:uiGridSaveStateService * @description Applies the provided state to the grid * * @param {Grid} grid the grid whose state we'd like to restore * @param {scope} $scope a scope that we can broadcast on * @param {object} state the state we'd like to restore */ restore: function( grid, $scope, state ){ if ( state.columns ) { service.restoreColumns( grid, state.columns ); } if ( state.scrollFocus ){ service.restoreScrollFocus( grid, $scope, state.scrollFocus ); } if ( state.selection ){ service.restoreSelection( grid, state.selection ); } if ( state.grouping ){ service.restoreGrouping( grid, state.grouping ); } if ( state.treeView ){ service.restoreTreeView( grid, state.treeView ); } grid.refresh(); }, /** * @ngdoc function * @name saveColumns * @methodOf ui.grid.saveState.service:uiGridSaveStateService * @description Saves the column setup, including sort, filters, ordering, * pinning and column widths. * * Works through the current columns, storing them in order. Stores the * column name, then the visible flag, width, sort and filters for each column. * * @param {Grid} grid the grid whose state we'd like to save * @returns {array} the columns state ready to be saved */ saveColumns: function( grid ) { var columns = []; grid.getOnlyDataColumns().forEach( function( column ) { var savedColumn = {}; savedColumn.name = column.name; if ( grid.options.saveVisible ){ savedColumn.visible = column.visible; } if ( grid.options.saveWidths ){ savedColumn.width = column.width; } // these two must be copied, not just pointed too - otherwise our saved state is pointing to the same object as current state if ( grid.options.saveSort ){ savedColumn.sort = angular.copy( column.sort ); } if ( grid.options.saveFilter ){ savedColumn.filters = []; column.filters.forEach( function( filter ){ var copiedFilter = {}; angular.forEach( filter, function( value, key) { if ( key !== 'condition' && key !== '$$hashKey' && key !== 'placeholder'){ copiedFilter[key] = value; } }); savedColumn.filters.push(copiedFilter); }); } if ( !!grid.api.pinning && grid.options.savePinning ){ savedColumn.pinned = column.renderContainer ? column.renderContainer : ''; } columns.push( savedColumn ); }); return columns; }, /** * @ngdoc function * @name saveScrollFocus * @methodOf ui.grid.saveState.service:uiGridSaveStateService * @description Saves the currently scroll or focus. * * If cellNav isn't present then does nothing - we can't return * to the scroll position without cellNav anyway. * * If the cellNav module is present, and saveFocus is true, then * it saves the currently focused cell. If rowIdentity is present * then saves using rowIdentity, otherwise saves visibleRowNum. * * If the cellNav module is not present, and saveScroll is true, then * it approximates the current scroll row and column, and saves that. * * @param {Grid} grid the grid whose state we'd like to save * @returns {object} the selection state ready to be saved */ saveScrollFocus: function( grid ){ if ( !grid.api.cellNav ){ return {}; } var scrollFocus = {}; if ( grid.options.saveFocus ){ scrollFocus.focus = true; var rowCol = grid.api.cellNav.getFocusedCell(); if ( rowCol !== null ) { if ( rowCol.col !== null ){ scrollFocus.colName = rowCol.col.colDef.name; } if ( rowCol.row !== null ){ scrollFocus.rowVal = service.getRowVal( grid, rowCol.row ); } } } if ( grid.options.saveScroll || grid.options.saveFocus && !scrollFocus.colName && !scrollFocus.rowVal ) { scrollFocus.focus = false; if ( grid.renderContainers.body.prevRowScrollIndex ){ scrollFocus.rowVal = service.getRowVal( grid, grid.renderContainers.body.visibleRowCache[ grid.renderContainers.body.prevRowScrollIndex ]); } if ( grid.renderContainers.body.prevColScrollIndex ){ scrollFocus.colName = grid.renderContainers.body.visibleColumnCache[ grid.renderContainers.body.prevColScrollIndex ].name; } } return scrollFocus; }, /** * @ngdoc function * @name saveSelection * @methodOf ui.grid.saveState.service:uiGridSaveStateService * @description Saves the currently selected rows, if the selection feature is enabled * @param {Grid} grid the grid whose state we'd like to save * @returns {array} the selection state ready to be saved */ saveSelection: function( grid ){ if ( !grid.api.selection || !grid.options.saveSelection ){ return []; } var selection = grid.api.selection.getSelectedGridRows().map( function( gridRow ) { return service.getRowVal( grid, gridRow ); }); return selection; }, /** * @ngdoc function * @name saveGrouping * @methodOf ui.grid.saveState.service:uiGridSaveStateService * @description Saves the grouping state, if the grouping feature is enabled * @param {Grid} grid the grid whose state we'd like to save * @returns {object} the grouping state ready to be saved */ saveGrouping: function( grid ){ if ( !grid.api.grouping || !grid.options.saveGrouping ){ return {}; } return grid.api.grouping.getGrouping( grid.options.saveGroupingExpandedStates ); }, /** * @ngdoc function * @name saveTreeView * @methodOf ui.grid.saveState.service:uiGridSaveStateService * @description Saves the tree view state, if the tree feature is enabled * @param {Grid} grid the grid whose state we'd like to save * @returns {object} the tree view state ready to be saved */ saveTreeView: function( grid ){ if ( !grid.api.treeView || !grid.options.saveTreeView ){ return {}; } return grid.api.treeView.getTreeView(); }, /** * @ngdoc function * @name getRowVal * @methodOf ui.grid.saveState.service:uiGridSaveStateService * @description Helper function that gets either the rowNum or * the saveRowIdentity, given a gridRow * @param {Grid} grid the grid the row is in * @param {GridRow} gridRow the row we want the rowNum for * @returns {object} an object containing { identity: true/false, row: rowNumber/rowIdentity } * */ getRowVal: function( grid, gridRow ){ if ( !gridRow ) { return null; } var rowVal = {}; if ( grid.options.saveRowIdentity ){ rowVal.identity = true; rowVal.row = grid.options.saveRowIdentity( gridRow.entity ); } else { rowVal.identity = false; rowVal.row = grid.renderContainers.body.visibleRowCache.indexOf( gridRow ); } return rowVal; }, /** * @ngdoc function * @name restoreColumns * @methodOf ui.grid.saveState.service:uiGridSaveStateService * @description Restores the columns, including order, visible, width, * pinning, sort and filters. * * @param {Grid} grid the grid whose state we'd like to restore * @param {object} columnsState the list of columns we had before, with their state */ restoreColumns: function( grid, columnsState ){ var isSortChanged = false; columnsState.forEach( function( columnState, index ) { var currentCol = grid.getColumn( columnState.name ); if ( currentCol && !grid.isRowHeaderColumn(currentCol) ){ if ( grid.options.saveVisible && ( currentCol.visible !== columnState.visible || currentCol.colDef.visible !== columnState.visible ) ){ currentCol.visible = columnState.visible; currentCol.colDef.visible = columnState.visible; grid.api.core.raise.columnVisibilityChanged(currentCol); } if ( grid.options.saveWidths ){ currentCol.width = columnState.width; } if ( grid.options.saveSort && !angular.equals(currentCol.sort, columnState.sort) && !( currentCol.sort === undefined && angular.isEmpty(columnState.sort) ) ){ currentCol.sort = angular.copy( columnState.sort ); isSortChanged = true; } if ( grid.options.saveFilter && !angular.equals(currentCol.filters, columnState.filters ) ){ columnState.filters.forEach( function( filter, index ){ angular.extend( currentCol.filters[index], filter ); if ( typeof(filter.term) === 'undefined' || filter.term === null ){ delete currentCol.filters[index].term; } }); grid.api.core.raise.filterChanged(); } if ( !!grid.api.pinning && grid.options.savePinning && currentCol.renderContainer !== columnState.pinned ){ grid.api.pinning.pinColumn(currentCol, columnState.pinned); } var currentIndex = grid.getOnlyDataColumns().indexOf( currentCol ); if (currentIndex !== -1) { if (grid.options.saveOrder && currentIndex !== index) { var column = grid.columns.splice(currentIndex + grid.rowHeaderColumns.length, 1)[0]; grid.columns.splice(index + grid.rowHeaderColumns.length, 0, column); } } } }); if ( isSortChanged ) { grid.api.core.raise.sortChanged( grid, grid.getColumnSorting() ); } }, /** * @ngdoc function * @name restoreScrollFocus * @methodOf ui.grid.saveState.service:uiGridSaveStateService * @description Scrolls to the position that was saved. If focus is true, then * sets focus to the specified row/col. If focus is false, then scrolls to the * specified row/col. * * @param {Grid} grid the grid whose state we'd like to restore * @param {scope} $scope a scope that we can broadcast on * @param {object} scrollFocusState the scroll/focus state ready to be restored */ restoreScrollFocus: function( grid, $scope, scrollFocusState ){ if ( !grid.api.cellNav ){ return; } var colDef, row; if ( scrollFocusState.colName ){ var colDefs = grid.options.columnDefs.filter( function( colDef ) { return colDef.name === scrollFocusState.colName; }); if ( colDefs.length > 0 ){ colDef = colDefs[0]; } } if ( scrollFocusState.rowVal && scrollFocusState.rowVal.row ){ if ( scrollFocusState.rowVal.identity ){ row = service.findRowByIdentity( grid, scrollFocusState.rowVal ); } else { row = grid.renderContainers.body.visibleRowCache[ scrollFocusState.rowVal.row ]; } } var entity = row && row.entity ? row.entity : null ; if ( colDef || entity ) { if (scrollFocusState.focus ){ grid.api.cellNav.scrollToFocus( entity, colDef ); } else { grid.scrollTo( entity, colDef ); } } }, /** * @ngdoc function * @name restoreSelection * @methodOf ui.grid.saveState.service:uiGridSaveStateService * @description Selects the rows that are provided in the selection * state. If you are using `saveRowIdentity` and more than one row matches the identity * function then only the first is selected. * @param {Grid} grid the grid whose state we'd like to restore * @param {object} selectionState the selection state ready to be restored */ restoreSelection: function( grid, selectionState ){ if ( !grid.api.selection ){ return; } grid.api.selection.clearSelectedRows(); selectionState.forEach( function( rowVal ) { if ( rowVal.identity ){ var foundRow = service.findRowByIdentity( grid, rowVal ); if ( foundRow ){ grid.api.selection.selectRow( foundRow.entity ); } } else { grid.api.selection.selectRowByVisibleIndex( rowVal.row ); } }); }, /** * @ngdoc function * @name restoreGrouping * @methodOf ui.grid.saveState.service:uiGridSaveStateService * @description Restores the grouping configuration, if the grouping feature * is enabled. * @param {Grid} grid the grid whose state we'd like to restore * @param {object} groupingState the grouping state ready to be restored */ restoreGrouping: function( grid, groupingState ){ if ( !grid.api.grouping || typeof(groupingState) === 'undefined' || groupingState === null || angular.equals(groupingState, {}) ){ return; } grid.api.grouping.setGrouping( groupingState ); }, /** * @ngdoc function * @name restoreTreeView * @methodOf ui.grid.saveState.service:uiGridSaveStateService * @description Restores the tree view configuration, if the tree view feature * is enabled. * @param {Grid} grid the grid whose state we'd like to restore * @param {object} treeViewState the tree view state ready to be restored */ restoreTreeView: function( grid, treeViewState ){ if ( !grid.api.treeView || typeof(treeViewState) === 'undefined' || treeViewState === null || angular.equals(treeViewState, {}) ){ return; } grid.api.treeView.setTreeView( treeViewState ); }, /** * @ngdoc function * @name findRowByIdentity * @methodOf ui.grid.saveState.service:uiGridSaveStateService * @description Finds a row given it's identity value, returns the first found row * if any are found, otherwise returns null if no rows are found. * @param {Grid} grid the grid whose state we'd like to restore * @param {object} rowVal the row we'd like to find * @returns {gridRow} the found row, or null if none found */ findRowByIdentity: function( grid, rowVal ){ if ( !grid.options.saveRowIdentity ){ return null; } var filteredRows = grid.rows.filter( function( gridRow ) { if ( grid.options.saveRowIdentity( gridRow.entity ) === rowVal.row ){ return true; } else { return false; } }); if ( filteredRows.length > 0 ){ return filteredRows[0]; } else { return null; } } }; return service; } ]); /** * @ngdoc directive * @name ui.grid.saveState.directive:uiGridSaveState * @element div * @restrict A * * @description Adds saveState features to grid * * @example <example module="app"> <file name="app.js"> var app = angular.module('app', ['ui.grid', 'ui.grid.saveState']); app.controller('MainCtrl', ['$scope', function ($scope) { $scope.data = [ { name: 'Bob', title: 'CEO' }, { name: 'Frank', title: 'Lowly Developer' } ]; $scope.gridOptions = { columnDefs: [ {name: 'name'}, {name: 'title', enableCellEdit: true} ], data: $scope.data }; }]); </file> <file name="index.html"> <div ng-controller="MainCtrl"> <div ui-grid="gridOptions" ui-grid-save-state></div> </div> </file> </example> */ module.directive('uiGridSaveState', ['uiGridSaveStateConstants', 'uiGridSaveStateService', 'gridUtil', '$compile', function (uiGridSaveStateConstants, uiGridSaveStateService, gridUtil, $compile) { return { replace: true, priority: 0, require: '^uiGrid', scope: false, link: function ($scope, $elm, $attrs, uiGridCtrl) { uiGridSaveStateService.initializeGrid(uiGridCtrl.grid); } }; } ]); })(); (function () { 'use strict'; /** * @ngdoc overview * @name ui.grid.selection * @description * * # ui.grid.selection * This module provides row selection * * <div class="alert alert-success" role="alert"><strong>Stable</strong> This feature is stable. There should no longer be breaking api changes without a deprecation warning.</div> * * <div doc-module-components="ui.grid.selection"></div> */ var module = angular.module('ui.grid.selection', ['ui.grid']); /** * @ngdoc object * @name ui.grid.selection.constant:uiGridSelectionConstants * * @description constants available in selection module */ module.constant('uiGridSelectionConstants', { featureName: "selection", selectionRowHeaderColName: 'selectionRowHeaderCol' }); //add methods to GridRow angular.module('ui.grid').config(['$provide', function($provide) { $provide.decorator('GridRow', ['$delegate', function($delegate) { /** * @ngdoc object * @name ui.grid.selection.api:GridRow * * @description GridRow prototype functions added for selection */ /** * @ngdoc object * @name enableSelection * @propertyOf ui.grid.selection.api:GridRow * @description Enable row selection for this row, only settable by internal code. * * The grouping feature, for example, might set group header rows to not be selectable. * <br/>Defaults to true */ /** * @ngdoc object * @name isSelected * @propertyOf ui.grid.selection.api:GridRow * @description Selected state of row. Should be readonly. Make any changes to selected state using setSelected(). * <br/>Defaults to false */ /** * @ngdoc function * @name setSelected * @methodOf ui.grid.selection.api:GridRow * @description Sets the isSelected property and updates the selectedCount * Changes to isSelected state should only be made via this function * @param {bool} selected value to set */ $delegate.prototype.setSelected = function(selected) { this.isSelected = selected; if (selected) { this.grid.selection.selectedCount++; } else { this.grid.selection.selectedCount--; } }; return $delegate; }]); }]); /** * @ngdoc service * @name ui.grid.selection.service:uiGridSelectionService * * @description Services for selection features */ module.service('uiGridSelectionService', ['$q', '$templateCache', 'uiGridSelectionConstants', 'gridUtil', function ($q, $templateCache, uiGridSelectionConstants, gridUtil) { var service = { initializeGrid: function (grid) { //add feature namespace and any properties to grid for needed /** * @ngdoc object * @name ui.grid.selection.grid:selection * * @description Grid properties and functions added for selection */ grid.selection = {}; grid.selection.lastSelectedRow = null; grid.selection.selectAll = false; /** * @ngdoc object * @name selectedCount * @propertyOf ui.grid.selection.grid:selection * @description Current count of selected rows * @example * var count = grid.selection.selectedCount */ grid.selection.selectedCount = 0; service.defaultGridOptions(grid.options); /** * @ngdoc object * @name ui.grid.selection.api:PublicApi * * @description Public Api for selection feature */ var publicApi = { events: { selection: { /** * @ngdoc event * @name rowSelectionChanged * @eventOf ui.grid.selection.api:PublicApi * @description is raised after the row.isSelected state is changed * @param {GridRow} row the row that was selected/deselected * @param {Event} event object if raised from an event */ rowSelectionChanged: function (scope, row, evt) { }, /** * @ngdoc event * @name rowSelectionChangedBatch * @eventOf ui.grid.selection.api:PublicApi * @description is raised after the row.isSelected state is changed * in bulk, if the `enableSelectionBatchEvent` option is set to true * (which it is by default). This allows more efficient processing * of bulk events. * @param {array} rows the rows that were selected/deselected * @param {Event} event object if raised from an event */ rowSelectionChangedBatch: function (scope, rows, evt) { } } }, methods: { selection: { /** * @ngdoc function * @name toggleRowSelection * @methodOf ui.grid.selection.api:PublicApi * @description Toggles data row as selected or unselected * @param {object} rowEntity gridOptions.data[] array instance * @param {Event} event object if raised from an event */ toggleRowSelection: function (rowEntity, evt) { var row = grid.getRow(rowEntity); if (row !== null) { service.toggleRowSelection(grid, row, evt, grid.options.multiSelect, grid.options.noUnselect); } }, /** * @ngdoc function * @name selectRow * @methodOf ui.grid.selection.api:PublicApi * @description Select the data row * @param {object} rowEntity gridOptions.data[] array instance * @param {Event} event object if raised from an event */ selectRow: function (rowEntity, evt) { var row = grid.getRow(rowEntity); if (row !== null && !row.isSelected) { service.toggleRowSelection(grid, row, evt, grid.options.multiSelect, grid.options.noUnselect); } }, /** * @ngdoc function * @name selectRowByVisibleIndex * @methodOf ui.grid.selection.api:PublicApi * @description Select the specified row by visible index (i.e. if you * specify row 0 you'll get the first visible row selected). In this context * visible means of those rows that are theoretically visible (i.e. not filtered), * rather than rows currently rendered on the screen. * @param {number} index index within the rowsVisible array * @param {Event} event object if raised from an event */ selectRowByVisibleIndex: function ( rowNum, evt ) { var row = grid.renderContainers.body.visibleRowCache[rowNum]; if (row !== null && typeof(row) !== 'undefined' && !row.isSelected) { service.toggleRowSelection(grid, row, evt, grid.options.multiSelect, grid.options.noUnselect); } }, /** * @ngdoc function * @name unSelectRow * @methodOf ui.grid.selection.api:PublicApi * @description UnSelect the data row * @param {object} rowEntity gridOptions.data[] array instance * @param {Event} event object if raised from an event */ unSelectRow: function (rowEntity, evt) { var row = grid.getRow(rowEntity); if (row !== null && row.isSelected) { service.toggleRowSelection(grid, row, evt, grid.options.multiSelect, grid.options.noUnselect); } }, /** * @ngdoc function * @name selectAllRows * @methodOf ui.grid.selection.api:PublicApi * @description Selects all rows. Does nothing if multiSelect = false * @param {Event} event object if raised from an event */ selectAllRows: function (evt) { if (grid.options.multiSelect === false) { return; } var changedRows = []; grid.rows.forEach(function (row) { if ( !row.isSelected && row.enableSelection !== false ){ row.setSelected(true); service.decideRaiseSelectionEvent( grid, row, changedRows, evt ); } }); service.decideRaiseSelectionBatchEvent( grid, changedRows, evt ); grid.selection.selectAll = true; }, /** * @ngdoc function * @name selectAllVisibleRows * @methodOf ui.grid.selection.api:PublicApi * @description Selects all visible rows. Does nothing if multiSelect = false * @param {Event} event object if raised from an event */ selectAllVisibleRows: function (evt) { if (grid.options.multiSelect === false) { return; } var changedRows = []; grid.rows.forEach(function (row) { if (row.visible) { if (!row.isSelected && row.enableSelection !== false){ row.setSelected(true); service.decideRaiseSelectionEvent( grid, row, changedRows, evt ); } } else { if (row.isSelected){ row.setSelected(false); service.decideRaiseSelectionEvent( grid, row, changedRows, evt ); } } }); service.decideRaiseSelectionBatchEvent( grid, changedRows, evt ); grid.selection.selectAll = true; }, /** * @ngdoc function * @name clearSelectedRows * @methodOf ui.grid.selection.api:PublicApi * @description Unselects all rows * @param {Event} event object if raised from an event */ clearSelectedRows: function (evt) { service.clearSelectedRows(grid, evt); }, /** * @ngdoc function * @name getSelectedRows * @methodOf ui.grid.selection.api:PublicApi * @description returns all selectedRow's entity references */ getSelectedRows: function () { return service.getSelectedRows(grid).map(function (gridRow) { return gridRow.entity; }); }, /** * @ngdoc function * @name getSelectedGridRows * @methodOf ui.grid.selection.api:PublicApi * @description returns all selectedRow's as gridRows */ getSelectedGridRows: function () { return service.getSelectedRows(grid); }, /** * @ngdoc function * @name setMultiSelect * @methodOf ui.grid.selection.api:PublicApi * @description Sets the current gridOption.multiSelect to true or false * @param {bool} multiSelect true to allow multiple rows */ setMultiSelect: function (multiSelect) { grid.options.multiSelect = multiSelect; }, /** * @ngdoc function * @name setModifierKeysToMultiSelect * @methodOf ui.grid.selection.api:PublicApi * @description Sets the current gridOption.modifierKeysToMultiSelect to true or false * @param {bool} modifierKeysToMultiSelect true to only allow multiple rows when using ctrlKey or shiftKey is used */ setModifierKeysToMultiSelect: function (modifierKeysToMultiSelect) { grid.options.modifierKeysToMultiSelect = modifierKeysToMultiSelect; }, /** * @ngdoc function * @name getSelectAllState * @methodOf ui.grid.selection.api:PublicApi * @description Returns whether or not the selectAll checkbox is currently ticked. The * grid doesn't automatically select rows when you add extra data - so when you add data * you need to explicitly check whether the selectAll is set, and then call setVisible rows * if it is */ getSelectAllState: function () { return grid.selection.selectAll; } } } }; grid.api.registerEventsFromObject(publicApi.events); grid.api.registerMethodsFromObject(publicApi.methods); }, defaultGridOptions: function (gridOptions) { //default option to true unless it was explicitly set to false /** * @ngdoc object * @name ui.grid.selection.api:GridOptions * * @description GridOptions for selection feature, these are available to be * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions} */ /** * @ngdoc object * @name enableRowSelection * @propertyOf ui.grid.selection.api:GridOptions * @description Enable row selection for entire grid. * <br/>Defaults to true */ gridOptions.enableRowSelection = gridOptions.enableRowSelection !== false; /** * @ngdoc object * @name multiSelect * @propertyOf ui.grid.selection.api:GridOptions * @description Enable multiple row selection for entire grid * <br/>Defaults to true */ gridOptions.multiSelect = gridOptions.multiSelect !== false; /** * @ngdoc object * @name noUnselect * @propertyOf ui.grid.selection.api:GridOptions * @description Prevent a row from being unselected. Works in conjunction * with `multiselect = false` and `gridApi.selection.selectRow()` to allow * you to create a single selection only grid - a row is always selected, you * can only select different rows, you can't unselect the row. * <br/>Defaults to false */ gridOptions.noUnselect = gridOptions.noUnselect === true; /** * @ngdoc object * @name modifierKeysToMultiSelect * @propertyOf ui.grid.selection.api:GridOptions * @description Enable multiple row selection only when using the ctrlKey or shiftKey. Requires multiSelect to be true. * <br/>Defaults to false */ gridOptions.modifierKeysToMultiSelect = gridOptions.modifierKeysToMultiSelect === true; /** * @ngdoc object * @name enableRowHeaderSelection * @propertyOf ui.grid.selection.api:GridOptions * @description Enable a row header to be used for selection * <br/>Defaults to true */ gridOptions.enableRowHeaderSelection = gridOptions.enableRowHeaderSelection !== false; /** * @ngdoc object * @name enableFullRowSelection * @propertyOf ui.grid.selection.api:GridOptions * @description Enable selection by clicking anywhere on the row. Defaults to * false if `enableRowHeaderSelection` is true, otherwise defaults to false. */ if ( typeof(gridOptions.enableFullRowSelection) === 'undefined' ){ gridOptions.enableFullRowSelection = !gridOptions.enableRowHeaderSelection; } /** * @ngdoc object * @name enableSelectAll * @propertyOf ui.grid.selection.api:GridOptions * @description Enable the select all checkbox at the top of the selectionRowHeader * <br/>Defaults to true */ gridOptions.enableSelectAll = gridOptions.enableSelectAll !== false; /** * @ngdoc object * @name enableSelectionBatchEvent * @propertyOf ui.grid.selection.api:GridOptions * @description If selected rows are changed in bulk, either via the API or * via the selectAll checkbox, then a separate event is fired. Setting this * option to false will cause the rowSelectionChanged event to be called multiple times * instead * <br/>Defaults to true */ gridOptions.enableSelectionBatchEvent = gridOptions.enableSelectionBatchEvent !== false; /** * @ngdoc object * @name selectionRowHeaderWidth * @propertyOf ui.grid.selection.api:GridOptions * @description can be used to set a custom width for the row header selection column * <br/>Defaults to 30px */ gridOptions.selectionRowHeaderWidth = angular.isDefined(gridOptions.selectionRowHeaderWidth) ? gridOptions.selectionRowHeaderWidth : 30; /** * @ngdoc object * @name enableFooterTotalSelected * @propertyOf ui.grid.selection.api:GridOptions * @description Shows the total number of selected items in footer if true. * <br/>Defaults to true. * <br/>GridOptions.showGridFooter must also be set to true. */ gridOptions.enableFooterTotalSelected = gridOptions.enableFooterTotalSelected !== false; /** * @ngdoc object * @name isRowSelectable * @propertyOf ui.grid.selection.api:GridOptions * @description Makes it possible to specify a method that evaluates for each row and sets its "enableSelection" property. */ gridOptions.isRowSelectable = angular.isDefined(gridOptions.isRowSelectable) ? gridOptions.isRowSelectable : angular.noop; }, /** * @ngdoc function * @name toggleRowSelection * @methodOf ui.grid.selection.service:uiGridSelectionService * @description Toggles row as selected or unselected * @param {Grid} grid grid object * @param {GridRow} row row to select or deselect * @param {Event} event object if resulting from event * @param {bool} multiSelect if false, only one row at time can be selected * @param {bool} noUnselect if true then rows cannot be unselected */ toggleRowSelection: function (grid, row, evt, multiSelect, noUnselect) { var selected = row.isSelected; if ( row.enableSelection === false && !selected ){ return; } if (!multiSelect && !selected) { service.clearSelectedRows(grid, evt); } else if (!multiSelect && selected) { var selectedRows = service.getSelectedRows(grid); if (selectedRows.length > 1) { selected = false; // Enable reselect of the row service.clearSelectedRows(grid, evt); } } if (selected && noUnselect){ // don't deselect the row } else { row.setSelected(!selected); if (row.isSelected === true) { grid.selection.lastSelectedRow = row; } else { grid.selection.selectAll = false; } grid.api.selection.raise.rowSelectionChanged(row, evt); } }, /** * @ngdoc function * @name shiftSelect * @methodOf ui.grid.selection.service:uiGridSelectionService * @description selects a group of rows from the last selected row using the shift key * @param {Grid} grid grid object * @param {GridRow} clicked row * @param {Event} event object if raised from an event * @param {bool} multiSelect if false, does nothing this is for multiSelect only */ shiftSelect: function (grid, row, evt, multiSelect) { if (!multiSelect) { return; } var selectedRows = service.getSelectedRows(grid); var fromRow = selectedRows.length > 0 ? grid.renderContainers.body.visibleRowCache.indexOf(grid.selection.lastSelectedRow) : 0; var toRow = grid.renderContainers.body.visibleRowCache.indexOf(row); //reverse select direction if (fromRow > toRow) { var tmp = fromRow; fromRow = toRow; toRow = tmp; } var changedRows = []; for (var i = fromRow; i <= toRow; i++) { var rowToSelect = grid.renderContainers.body.visibleRowCache[i]; if (rowToSelect) { if ( !rowToSelect.isSelected && rowToSelect.enableSelection !== false ){ rowToSelect.setSelected(true); grid.selection.lastSelectedRow = rowToSelect; service.decideRaiseSelectionEvent( grid, rowToSelect, changedRows, evt ); } } } service.decideRaiseSelectionBatchEvent( grid, changedRows, evt ); }, /** * @ngdoc function * @name getSelectedRows * @methodOf ui.grid.selection.service:uiGridSelectionService * @description Returns all the selected rows * @param {Grid} grid grid object */ getSelectedRows: function (grid) { return grid.rows.filter(function (row) { return row.isSelected; }); }, /** * @ngdoc function * @name clearSelectedRows * @methodOf ui.grid.selection.service:uiGridSelectionService * @description Clears all selected rows * @param {Grid} grid grid object * @param {Event} event object if raised from an event */ clearSelectedRows: function (grid, evt) { var changedRows = []; service.getSelectedRows(grid).forEach(function (row) { if ( row.isSelected ){ row.setSelected(false); service.decideRaiseSelectionEvent( grid, row, changedRows, evt ); } }); service.decideRaiseSelectionBatchEvent( grid, changedRows, evt ); grid.selection.selectAll = false; }, /** * @ngdoc function * @name decideRaiseSelectionEvent * @methodOf ui.grid.selection.service:uiGridSelectionService * @description Decides whether to raise a single event or a batch event * @param {Grid} grid grid object * @param {GridRow} row row that has changed * @param {array} changedRows an array to which we can append the changed * @param {Event} event object if raised from an event * row if we're doing batch events */ decideRaiseSelectionEvent: function( grid, row, changedRows, evt ){ if ( !grid.options.enableSelectionBatchEvent ){ grid.api.selection.raise.rowSelectionChanged(row, evt); } else { changedRows.push(row); } }, /** * @ngdoc function * @name raiseSelectionEvent * @methodOf ui.grid.selection.service:uiGridSelectionService * @description Decides whether we need to raise a batch event, and * raises it if we do. * @param {Grid} grid grid object * @param {array} changedRows an array of changed rows, only populated * @param {Event} event object if raised from an event * if we're doing batch events */ decideRaiseSelectionBatchEvent: function( grid, changedRows, evt ){ if ( changedRows.length > 0 ){ grid.api.selection.raise.rowSelectionChangedBatch(changedRows, evt); } } }; return service; }]); /** * @ngdoc directive * @name ui.grid.selection.directive:uiGridSelection * @element div * @restrict A * * @description Adds selection features to grid * * @example <example module="app"> <file name="app.js"> var app = angular.module('app', ['ui.grid', 'ui.grid.selection']); app.controller('MainCtrl', ['$scope', function ($scope) { $scope.data = [ { name: 'Bob', title: 'CEO' }, { name: 'Frank', title: 'Lowly Developer' } ]; $scope.columnDefs = [ {name: 'name', enableCellEdit: true}, {name: 'title', enableCellEdit: true} ]; }]); </file> <file name="index.html"> <div ng-controller="MainCtrl"> <div ui-grid="{ data: data, columnDefs: columnDefs }" ui-grid-selection></div> </div> </file> </example> */ module.directive('uiGridSelection', ['uiGridSelectionConstants', 'uiGridSelectionService', '$templateCache', 'uiGridConstants', function (uiGridSelectionConstants, uiGridSelectionService, $templateCache, uiGridConstants) { return { replace: true, priority: 0, require: '^uiGrid', scope: false, compile: function () { return { pre: function ($scope, $elm, $attrs, uiGridCtrl) { uiGridSelectionService.initializeGrid(uiGridCtrl.grid); if (uiGridCtrl.grid.options.enableRowHeaderSelection) { var selectionRowHeaderDef = { name: uiGridSelectionConstants.selectionRowHeaderColName, displayName: '', width: uiGridCtrl.grid.options.selectionRowHeaderWidth, minWidth: 10, cellTemplate: 'ui-grid/selectionRowHeader', headerCellTemplate: 'ui-grid/selectionHeaderCell', enableColumnResizing: false, enableColumnMenu: false, exporterSuppressExport: true, allowCellFocus: true }; uiGridCtrl.grid.addRowHeaderColumn(selectionRowHeaderDef); } var processorSet = false; var processSelectableRows = function( rows ){ rows.forEach(function(row){ row.enableSelection = uiGridCtrl.grid.options.isRowSelectable(row); }); return rows; }; var updateOptions = function(){ if (uiGridCtrl.grid.options.isRowSelectable !== angular.noop && processorSet !== true) { uiGridCtrl.grid.registerRowsProcessor(processSelectableRows, 500); processorSet = true; } }; updateOptions(); var dataChangeDereg = uiGridCtrl.grid.registerDataChangeCallback( updateOptions, [uiGridConstants.dataChange.OPTIONS] ); $scope.$on( '$destroy', dataChangeDereg); }, post: function ($scope, $elm, $attrs, uiGridCtrl) { } }; } }; }]); module.directive('uiGridSelectionRowHeaderButtons', ['$templateCache', 'uiGridSelectionService', 'gridUtil', function ($templateCache, uiGridSelectionService, gridUtil) { return { replace: true, restrict: 'E', template: $templateCache.get('ui-grid/selectionRowHeaderButtons'), scope: true, require: '^uiGrid', link: function($scope, $elm, $attrs, uiGridCtrl) { var self = uiGridCtrl.grid; $scope.selectButtonClick = selectButtonClick; // On IE, prevent mousedowns on the select button from starting a selection. // If this is not done and you shift+click on another row, the browser will select a big chunk of text if (gridUtil.detectBrowser() === 'ie') { $elm.on('mousedown', selectButtonMouseDown); } function selectButtonClick(row, evt) { evt.stopPropagation(); if (evt.shiftKey) { uiGridSelectionService.shiftSelect(self, row, evt, self.options.multiSelect); } else if (evt.ctrlKey || evt.metaKey) { uiGridSelectionService.toggleRowSelection(self, row, evt, self.options.multiSelect, self.options.noUnselect); } else { uiGridSelectionService.toggleRowSelection(self, row, evt, (self.options.multiSelect && !self.options.modifierKeysToMultiSelect), self.options.noUnselect); } } function selectButtonMouseDown(evt) { if (evt.ctrlKey || evt.shiftKey) { evt.target.onselectstart = function () { return false; }; window.setTimeout(function () { evt.target.onselectstart = null; }, 0); } } } }; }]); module.directive('uiGridSelectionSelectAllButtons', ['$templateCache', 'uiGridSelectionService', function ($templateCache, uiGridSelectionService) { return { replace: true, restrict: 'E', template: $templateCache.get('ui-grid/selectionSelectAllButtons'), scope: false, link: function($scope, $elm, $attrs, uiGridCtrl) { var self = $scope.col.grid; $scope.headerButtonClick = function(row, evt) { if ( self.selection.selectAll ){ uiGridSelectionService.clearSelectedRows(self, evt); if ( self.options.noUnselect ){ self.api.selection.selectRowByVisibleIndex(0, evt); } self.selection.selectAll = false; } else { if ( self.options.multiSelect ){ self.api.selection.selectAllVisibleRows(evt); self.selection.selectAll = true; } } }; } }; }]); /** * @ngdoc directive * @name ui.grid.selection.directive:uiGridViewport * @element div * * @description Stacks on top of ui.grid.uiGridViewport to alter the attributes used * for the grid row */ module.directive('uiGridViewport', ['$compile', 'uiGridConstants', 'uiGridSelectionConstants', 'gridUtil', '$parse', 'uiGridSelectionService', function ($compile, uiGridConstants, uiGridSelectionConstants, gridUtil, $parse, uiGridSelectionService) { return { priority: -200, // run after default directive scope: false, compile: function ($elm, $attrs) { var rowRepeatDiv = angular.element($elm.children().children()[0]); var existingNgClass = rowRepeatDiv.attr("ng-class"); var newNgClass = ''; if ( existingNgClass ) { newNgClass = existingNgClass.slice(0, -1) + ",'ui-grid-row-selected': row.isSelected}"; } else { newNgClass = "{'ui-grid-row-selected': row.isSelected}"; } rowRepeatDiv.attr("ng-class", newNgClass); return { pre: function ($scope, $elm, $attrs, controllers) { }, post: function ($scope, $elm, $attrs, controllers) { } }; } }; }]); /** * @ngdoc directive * @name ui.grid.selection.directive:uiGridCell * @element div * @restrict A * * @description Stacks on top of ui.grid.uiGridCell to provide selection feature */ module.directive('uiGridCell', ['$compile', 'uiGridConstants', 'uiGridSelectionConstants', 'gridUtil', '$parse', 'uiGridSelectionService', '$timeout', function ($compile, uiGridConstants, uiGridSelectionConstants, gridUtil, $parse, uiGridSelectionService, $timeout) { return { priority: -200, // run after default uiGridCell directive restrict: 'A', require: '?^uiGrid', scope: false, link: function ($scope, $elm, $attrs, uiGridCtrl) { var touchStartTime = 0; var touchTimeout = 300; // Bind to keydown events in the render container if (uiGridCtrl.grid.api.cellNav) { uiGridCtrl.grid.api.cellNav.on.viewPortKeyDown($scope, function (evt, rowCol) { if (rowCol === null || rowCol.row !== $scope.row || rowCol.col !== $scope.col) { return; } if (evt.keyCode === 32 && $scope.col.colDef.name === "selectionRowHeaderCol") { uiGridSelectionService.toggleRowSelection($scope.grid, $scope.row, evt, ($scope.grid.options.multiSelect && !$scope.grid.options.modifierKeysToMultiSelect), $scope.grid.options.noUnselect); $scope.$apply(); } // uiGridCellNavService.scrollToIfNecessary(uiGridCtrl.grid, rowCol.row, rowCol.col); }); } //$elm.bind('keydown', function (evt) { // if (evt.keyCode === 32 && $scope.col.colDef.name === "selectionRowHeaderCol") { // uiGridSelectionService.toggleRowSelection($scope.grid, $scope.row, evt, ($scope.grid.options.multiSelect && !$scope.grid.options.modifierKeysToMultiSelect), $scope.grid.options.noUnselect); // $scope.$apply(); // } //}); var selectCells = function(evt){ // if we get a click, then stop listening for touchend $elm.off('touchend', touchEnd); if (evt.shiftKey) { uiGridSelectionService.shiftSelect($scope.grid, $scope.row, evt, $scope.grid.options.multiSelect); } else if (evt.ctrlKey || evt.metaKey) { uiGridSelectionService.toggleRowSelection($scope.grid, $scope.row, evt, $scope.grid.options.multiSelect, $scope.grid.options.noUnselect); } else { uiGridSelectionService.toggleRowSelection($scope.grid, $scope.row, evt, ($scope.grid.options.multiSelect && !$scope.grid.options.modifierKeysToMultiSelect), $scope.grid.options.noUnselect); } $scope.$apply(); // don't re-enable the touchend handler for a little while - some devices generate both, and it will // take a little while to move your hand from the mouse to the screen if you have both modes of input $timeout(function() { $elm.on('touchend', touchEnd); }, touchTimeout); }; var touchStart = function(evt){ touchStartTime = (new Date()).getTime(); // if we get a touch event, then stop listening for click $elm.off('click', selectCells); }; var touchEnd = function(evt) { var touchEndTime = (new Date()).getTime(); var touchTime = touchEndTime - touchStartTime; if (touchTime < touchTimeout ) { // short touch selectCells(evt); } // don't re-enable the click handler for a little while - some devices generate both, and it will // take a little while to move your hand from the screen to the mouse if you have both modes of input $timeout(function() { $elm.on('click', selectCells); }, touchTimeout); }; function registerRowSelectionEvents() { if ($scope.grid.options.enableRowSelection && $scope.grid.options.enableFullRowSelection) { $elm.addClass('ui-grid-disable-selection'); $elm.on('touchstart', touchStart); $elm.on('touchend', touchEnd); $elm.on('click', selectCells); $scope.registered = true; } } function deregisterRowSelectionEvents() { if ($scope.registered){ $elm.removeClass('ui-grid-disable-selection'); $elm.off('touchstart', touchStart); $elm.off('touchend', touchEnd); $elm.off('click', selectCells); $scope.registered = false; } } registerRowSelectionEvents(); // register a dataChange callback so that we can change the selection configuration dynamically // if the user changes the options var dataChangeDereg = $scope.grid.registerDataChangeCallback( function() { if ( $scope.grid.options.enableRowSelection && $scope.grid.options.enableFullRowSelection && !$scope.registered ){ registerRowSelectionEvents(); } else if ( ( !$scope.grid.options.enableRowSelection || !$scope.grid.options.enableFullRowSelection ) && $scope.registered ){ deregisterRowSelectionEvents(); } }, [uiGridConstants.dataChange.OPTIONS] ); $elm.on( '$destroy', dataChangeDereg); } }; }]); module.directive('uiGridGridFooter', ['$compile', 'uiGridConstants', 'gridUtil', function ($compile, uiGridConstants, gridUtil) { return { restrict: 'EA', replace: true, priority: -1000, require: '^uiGrid', scope: true, compile: function ($elm, $attrs) { return { pre: function ($scope, $elm, $attrs, uiGridCtrl) { if (!uiGridCtrl.grid.options.showGridFooter) { return; } gridUtil.getTemplate('ui-grid/gridFooterSelectedItems') .then(function (contents) { var template = angular.element(contents); var newElm = $compile(template)($scope); angular.element($elm[0].getElementsByClassName('ui-grid-grid-footer')[0]).append(newElm); }); }, post: function ($scope, $elm, $attrs, controllers) { } }; } }; }]); })(); (function () { 'use strict'; /** * @ngdoc overview * @name ui.grid.treeBase * @description * * # ui.grid.treeBase * * <div class="alert alert-warning" role="alert"><strong>Beta</strong> This feature is ready for testing, but it either hasn't seen a lot of use or has some known bugs.</div> * * This module provides base tree handling functions that are shared by other features, notably grouping * and treeView. It provides a tree view of the data, with nodes in that * tree and leaves. * * Design information: * ------------------- * * The raw data that is provided must come with a $$treeLevel on any non-leaf node. Grouping will create * these on all the group header rows, treeView will expect these to be set in the raw data by the user. * TreeBase will run a rowsProcessor that: * - builds `treeBase.tree` out of the provided rows * - permits a recursive sort of the tree * - maintains the expand/collapse state of each node * - provides the expand/collapse all button and the expand/collapse buttons * - maintains the count of children for each node * * Each row is updated with a link to the tree node that represents it. Refer {@link ui.grid.treeBase.grid:treeBase.tree tree documentation} * for information. * * TreeBase adds information to the rows * - treeLevel: if present and > -1 tells us the level (level 0 is the top level) * - treeNode: pointer to the node in the grid.treeBase.tree that refers * to this row, allowing us to manipulate the state * * Since the logic is baked into the rowsProcessors, it should get triggered whenever * row order or filtering or anything like that is changed. We recall the expanded state * across invocations of the rowsProcessors by the reference to the treeNode on the individual * rows. We rebuild the tree itself quite frequently, when we do this we use the saved treeNodes to * get the state, but we overwrite the other data in that treeNode. * * By default rows are collapsed, which means all data rows have their visible property * set to false, and only level 0 group rows are set to visible. * * We rely on the rowsProcessors to do the actual expanding and collapsing, so we set the flags we want into * grid.treeBase.tree, then call refresh. This is because we can't easily change the visible * row cache without calling the processors, and once we've built the logic into the rowProcessors we may as * well use it all the time. * * Tree base provides sorting (on non-grouped columns). * * Sorting works in two passes. The standard sorting is performed for any columns that are important to building * the tree (for example, any grouped columns). Then after the tree is built, a recursive tree sort is performed * for the remaining sort columns (including the original sort) - these columns are sorted within each tree level * (so all the level 1 nodes are sorted, then all the level 2 nodes within each level 1 node etc). * * To achieve this we make use of the `ignoreSort` property on the sort configuration. The parent feature (treeView or grouping) * must provide a rowsProcessor that runs with very low priority (typically in the 60-65 range), and that sets * the `ignoreSort`on any sort that it wants to run on the tree. TreeBase will clear the ignoreSort on all sorts - so it * will turn on any sorts that haven't run. It will then call a recursive sort on the tree. * * Tree base provides treeAggregation. It checks the treeAggregation configuration on each column, and aggregates based on * the logic provided as it builds the tree. Footer aggregation from the uiGrid core should not be used with treeBase aggregation, * since it operates on all visible rows, as opposed to to leaf nodes only. Setting `showColumnFooter: true` will show the * treeAggregations in the column footer. Aggregation information will be collected in the format: * * ``` * { * type: 'count', * value: 4, * label: 'count: ', * rendered: 'count: 4' * } * ``` * * A callback is provided to format the value once it is finalised (aka a valueFilter). * * <br/> * <br/> * * <div doc-module-components="ui.grid.treeBase"></div> */ var module = angular.module('ui.grid.treeBase', ['ui.grid']); /** * @ngdoc object * @name ui.grid.treeBase.constant:uiGridTreeBaseConstants * * @description constants available in treeBase module. * * These constants are manually copied into grouping and treeView, * as I haven't found a way to simply include them, and it's not worth * investing time in for something that changes very infrequently. * */ module.constant('uiGridTreeBaseConstants', { featureName: "treeBase", rowHeaderColName: 'treeBaseRowHeaderCol', EXPANDED: 'expanded', COLLAPSED: 'collapsed', aggregation: { COUNT: 'count', SUM: 'sum', MAX: 'max', MIN: 'min', AVG: 'avg' } }); /** * @ngdoc service * @name ui.grid.treeBase.service:uiGridTreeBaseService * * @description Services for treeBase feature */ /** * @ngdoc object * @name ui.grid.treeBase.api:ColumnDef * * @description ColumnDef for tree feature, these are available to be * set using the ui-grid {@link ui.grid.class:GridOptions.columnDef gridOptions.columnDefs} */ module.service('uiGridTreeBaseService', ['$q', 'uiGridTreeBaseConstants', 'gridUtil', 'GridRow', 'gridClassFactory', 'i18nService', 'uiGridConstants', 'rowSorter', function ($q, uiGridTreeBaseConstants, gridUtil, GridRow, gridClassFactory, i18nService, uiGridConstants, rowSorter) { var service = { initializeGrid: function (grid, $scope) { //add feature namespace and any properties to grid for needed /** * @ngdoc object * @name ui.grid.treeBase.grid:treeBase * * @description Grid properties and functions added for treeBase */ grid.treeBase = {}; /** * @ngdoc property * @propertyOf ui.grid.treeBase.grid:treeBase * @name numberLevels * * @description Total number of tree levels currently used, calculated by the rowsProcessor by * retaining the highest tree level it sees */ grid.treeBase.numberLevels = 0; /** * @ngdoc property * @propertyOf ui.grid.treeBase.grid:treeBase * @name expandAll * * @description Whether or not the expandAll box is selected */ grid.treeBase.expandAll = false; /** * @ngdoc property * @propertyOf ui.grid.treeBase.grid:treeBase * @name tree * * @description Tree represented as a nested array that holds the state of each node, along with a * pointer to the row. The array order is material - we will display the children in the order * they are stored in the array * * Each node stores: * * - the state of this node * - an array of children of this node * - a pointer to the parent of this node (reverse pointer, allowing us to walk up the tree) * - the number of children of this node * - aggregation information calculated from the nodes * * ``` * [{ * state: 'expanded', * row: <reference to row>, * parentRow: null, * aggregations: [{ * type: 'count', * col: <gridCol>, * value: 2, * label: 'count: ', * rendered: 'count: 2' * }], * children: [ * { * state: 'expanded', * row: <reference to row>, * parentRow: <reference to row>, * aggregations: [{ * type: 'count', * col: '<gridCol>, * value: 4, * label: 'count: ', * rendered: 'count: 4' * }], * children: [ * { state: 'expanded', row: <reference to row>, parentRow: <reference to row> }, * { state: 'collapsed', row: <reference to row>, parentRow: <reference to row> }, * { state: 'expanded', row: <reference to row>, parentRow: <reference to row> }, * { state: 'collapsed', row: <reference to row>, parentRow: <reference to row> } * ] * }, * { * state: 'collapsed', * row: <reference to row>, * parentRow: <reference to row>, * aggregations: [{ * type: 'count', * col: <gridCol>, * value: 3, * label: 'count: ', * rendered: 'count: 3' * }], * children: [ * { state: 'expanded', row: <reference to row>, parentRow: <reference to row> }, * { state: 'collapsed', row: <reference to row>, parentRow: <reference to row> }, * { state: 'expanded', row: <reference to row>, parentRow: <reference to row> } * ] * } * ] * }, {<another level 0 node maybe>} ] * ``` * Missing state values are false - meaning they aren't expanded. * * This is used because the rowProcessors run every time the grid is refreshed, so * we'd lose the expanded state every time the grid was refreshed. This instead gives * us a reliable lookup that persists across rowProcessors. * * This tree is rebuilt every time we run the rowsProcessors. Since each row holds a pointer * to it's tree node we can persist expand/collapse state across calls to rowsProcessor, we discard * all transient information on the tree (children, childCount) and recalculate it * */ grid.treeBase.tree = {}; service.defaultGridOptions(grid.options); grid.registerRowsProcessor(service.treeRows, 410); grid.registerColumnBuilder( service.treeBaseColumnBuilder ); service.createRowHeader( grid ); /** * @ngdoc object * @name ui.grid.treeBase.api:PublicApi * * @description Public Api for treeBase feature */ var publicApi = { events: { treeBase: { /** * @ngdoc event * @eventOf ui.grid.treeBase.api:PublicApi * @name rowExpanded * @description raised whenever a row is expanded. If you are dynamically * rendering your tree you can listen to this event, and then retrieve * the children of this row and load them into the grid data. * * When the data is loaded the grid will automatically refresh to show these new rows * * <pre> * gridApi.treeBase.on.rowExpanded(scope,function(row){}) * </pre> * @param {gridRow} row the row that was expanded. You can also * retrieve the grid from this row with row.grid */ rowExpanded: {}, /** * @ngdoc event * @eventOf ui.grid.treeBase.api:PublicApi * @name rowCollapsed * @description raised whenever a row is collapsed. Doesn't really have * a purpose at the moment, included for symmetry * * <pre> * gridApi.treeBase.on.rowCollapsed(scope,function(row){}) * </pre> * @param {gridRow} row the row that was collapsed. You can also * retrieve the grid from this row with row.grid */ rowCollapsed: {} } }, methods: { treeBase: { /** * @ngdoc function * @name expandAllRows * @methodOf ui.grid.treeBase.api:PublicApi * @description Expands all tree rows */ expandAllRows: function () { service.expandAllRows(grid); }, /** * @ngdoc function * @name collapseAllRows * @methodOf ui.grid.treeBase.api:PublicApi * @description collapse all tree rows */ collapseAllRows: function () { service.collapseAllRows(grid); }, /** * @ngdoc function * @name toggleRowTreeState * @methodOf ui.grid.treeBase.api:PublicApi * @description call expand if the row is collapsed, collapse if it is expanded * @param {gridRow} row the row you wish to toggle */ toggleRowTreeState: function (row) { service.toggleRowTreeState(grid, row); }, /** * @ngdoc function * @name expandRow * @methodOf ui.grid.treeBase.api:PublicApi * @description expand the immediate children of the specified row * @param {gridRow} row the row you wish to expand */ expandRow: function (row) { service.expandRow(grid, row); }, /** * @ngdoc function * @name expandRowChildren * @methodOf ui.grid.treeBase.api:PublicApi * @description expand all children of the specified row * @param {gridRow} row the row you wish to expand */ expandRowChildren: function (row) { service.expandRowChildren(grid, row); }, /** * @ngdoc function * @name collapseRow * @methodOf ui.grid.treeBase.api:PublicApi * @description collapse the specified row. When * you expand the row again, all grandchildren will retain their state * @param {gridRow} row the row you wish to collapse */ collapseRow: function ( row ) { service.collapseRow(grid, row); }, /** * @ngdoc function * @name collapseRowChildren * @methodOf ui.grid.treeBase.api:PublicApi * @description collapse all children of the specified row. When * you expand the row again, all grandchildren will be collapsed * @param {gridRow} row the row you wish to collapse children for */ collapseRowChildren: function ( row ) { service.collapseRowChildren(grid, row); }, /** * @ngdoc function * @name getTreeState * @methodOf ui.grid.treeBase.api:PublicApi * @description Get the tree state for this grid, * used by the saveState feature * Returned treeState as an object * `{ expandedState: { uid: 'expanded', uid: 'collapsed' } }` * where expandedState is a hash of row uid and the current expanded state * * @returns {object} tree state * * TODO - this needs work - we need an identifier that persists across instantiations, * not uid. This really means we need a row identity defined, but that won't work for * grouping. Perhaps this needs to be moved up to treeView and grouping, rather than * being in base. */ getTreeExpandedState: function () { return { expandedState: service.getTreeState(grid) }; }, /** * @ngdoc function * @name setTreeState * @methodOf ui.grid.treeBase.api:PublicApi * @description Set the expanded states of the tree * @param {object} config the config you want to apply, in the format * provided by getTreeState */ setTreeState: function ( config ) { service.setTreeState( grid, config ); }, /** * @ngdoc function * @name getRowChildren * @methodOf ui.grid.treeBase.api:PublicApi * @description Get the children of the specified row * @param {GridRow} row the row you want the children of * @returns {Array} array of children of this row, the children * are all gridRows */ getRowChildren: function ( row ){ return row.treeNode.children.map( function( childNode ){ return childNode.row; }); } } } }; grid.api.registerEventsFromObject(publicApi.events); grid.api.registerMethodsFromObject(publicApi.methods); }, defaultGridOptions: function (gridOptions) { //default option to true unless it was explicitly set to false /** * @ngdoc object * @name ui.grid.treeBase.api:GridOptions * * @description GridOptions for treeBase feature, these are available to be * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions} */ /** * @ngdoc object * @name treeRowHeaderBaseWidth * @propertyOf ui.grid.treeBase.api:GridOptions * @description Base width of the tree header, provides for a single level of tree. This * is incremented by `treeIndent` for each extra level * <br/>Defaults to 30 */ gridOptions.treeRowHeaderBaseWidth = gridOptions.treeRowHeaderBaseWidth || 30; /** * @ngdoc object * @name treeIndent * @propertyOf ui.grid.treeBase.api:GridOptions * @description Number of pixels of indent for the icon at each tree level, wider indents are visually more pleasing, * but will make the tree row header wider * <br/>Defaults to 10 */ gridOptions.treeIndent = gridOptions.treeIndent || 10; /** * @ngdoc object * @name showTreeRowHeader * @propertyOf ui.grid.treeBase.api:GridOptions * @description If set to false, don't create the row header. Youll need to programatically control the expand * states * <br/>Defaults to true */ gridOptions.showTreeRowHeader = gridOptions.showTreeRowHeader !== false; /** * @ngdoc object * @name showTreeExpandNoChildren * @propertyOf ui.grid.treeBase.api:GridOptions * @description If set to true, show the expand/collapse button even if there are no * children of a node. You'd use this if you're planning to dynamically load the children * * <br/>Defaults to true, grouping overrides to false */ gridOptions.showTreeExpandNoChildren = gridOptions.showTreeExpandNoChildren !== false; /** * @ngdoc object * @name treeRowHeaderAlwaysVisible * @propertyOf ui.grid.treeBase.api:GridOptions * @description If set to true, row header even if there are no tree nodes * * <br/>Defaults to true */ gridOptions.treeRowHeaderAlwaysVisible = gridOptions.treeRowHeaderAlwaysVisible !== false; /** * @ngdoc object * @name treeCustomAggregations * @propertyOf ui.grid.treeBase.api:GridOptions * @description Define custom aggregation functions. The properties of this object will be * aggregation types available for use on columnDef with {@link ui.grid.treeBase.api:ColumnDef treeAggregationType} or through the column menu. * If a function defined here uses the same name as one of the native aggregations, this one will take precedence. * The object format is: * * <pre> * { * aggregationName: { * label: (optional) string, * aggregationFn: function( aggregation, fieldValue, numValue, row ){...}, * finalizerFn: (optional) function( aggregation ){...} * }, * mean: { * label: 'mean', * aggregationFn: function( aggregation, fieldValue, numValue ){ * aggregation.count = (aggregation.count || 1) + 1; * aggregation.sum = (aggregation.sum || 0) + numValue; * }, * finalizerFn: function( aggregation ){ * aggregation.value = aggregation.sum / aggregation.count * } * } * } * </pre> * * <br/>The `finalizerFn` may be used to manipulate the value before rendering, or to * apply a custom rendered value. If `aggregation.rendered` is left undefined, the value will be * rendered. Note that the native aggregation functions use an `finalizerFn` to concatenate * the label and the value. * * <br/>Defaults to {} */ gridOptions.treeCustomAggregations = gridOptions.treeCustomAggregations || {}; }, /** * @ngdoc function * @name treeBaseColumnBuilder * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description Sets the tree defaults based on the columnDefs * * @param {object} colDef columnDef we're basing on * @param {GridCol} col the column we're to update * @param {object} gridOptions the options we should use * @returns {promise} promise for the builder - actually we do it all inline so it's immediately resolved */ treeBaseColumnBuilder: function (colDef, col, gridOptions) { /** * @ngdoc object * @name customTreeAggregationFn * @propertyOf ui.grid.treeBase.api:ColumnDef * @description A custom function that aggregates rows into some form of * total. Aggregations run row-by-row, the function needs to be capable of * creating a running total. * * The function will be provided the aggregation item (in which you can store running * totals), the row value that is to be aggregated, and that same row value converted to * a number (most aggregations work on numbers) * @example * <pre> * customTreeAggregationFn = function ( aggregation, fieldValue, numValue, row ){ * // calculates the average of the squares of the values * if ( typeof(aggregation.count) === 'undefined' ){ * aggregation.count = 0; * } * aggregation.count++; * * if ( !isNaN(numValue) ){ * if ( typeof(aggregation.total) === 'undefined' ){ * aggregation.total = 0; * } * aggregation.total = aggregation.total + numValue * numValue; * } * * aggregation.value = aggregation.total / aggregation.count; * } * </pre> * <br/>Defaults to undefined. May be overwritten by treeAggregationType, the two options should not be used together. */ if ( typeof(colDef.customTreeAggregationFn) !== 'undefined' ){ col.treeAggregationFn = colDef.customTreeAggregationFn; } /** * @ngdoc object * @name treeAggregationType * @propertyOf ui.grid.treeBase.api:ColumnDef * @description Use one of the native or grid-level aggregation methods for calculating aggregations on this column. * Native method are in the constants file and include: SUM, COUNT, MIN, MAX, AVG. This may also be the property the * name of an aggregation function defined with {@link ui.grid.treeBase.api:GridOptions treeCustomAggregations}. * * <pre> * treeAggregationType = uiGridTreeBaseConstants.aggregation.SUM, * } * </pre> * * If you are using aggregations you should either: * * - also use grouping, in which case the aggregations are displayed in the group header, OR * - use treeView, in which case you can set `treeAggregationUpdateEntity: true` in the colDef, and * treeBase will store the aggregation information in the entity, or you can set `treeAggregationUpdateEntity: false` * in the colDef, and you need to manual retrieve the calculated aggregations from the row.treeNode.aggregations * * <br/>Takes precendence over a treeAggregationFn, the two options should not be used together. * <br/>Defaults to undefined. */ if ( typeof(colDef.treeAggregationType) !== 'undefined' ){ col.treeAggregation = { type: colDef.treeAggregationType }; if ( typeof(gridOptions.treeCustomAggregations[colDef.treeAggregationType]) !== 'undefined' ){ col.treeAggregationFn = gridOptions.treeCustomAggregations[colDef.treeAggregationType].aggregationFn; col.treeAggregationFinalizerFn = gridOptions.treeCustomAggregations[colDef.treeAggregationType].finalizerFn; col.treeAggregation.label = gridOptions.treeCustomAggregations[colDef.treeAggregationType].label; } else if ( typeof(service.nativeAggregations()[colDef.treeAggregationType]) !== 'undefined' ){ col.treeAggregationFn = service.nativeAggregations()[colDef.treeAggregationType].aggregationFn; col.treeAggregation.label = service.nativeAggregations()[colDef.treeAggregationType].label; } } /** * @ngdoc object * @name treeAggregationLabel * @propertyOf ui.grid.treeBase.api:ColumnDef * @description A custom label to use for this aggregation. If provided we don't use native i18n. */ if ( typeof(colDef.treeAggregationLabel) !== 'undefined' ){ if (typeof(col.treeAggregation) === 'undefined' ){ col.treeAggregation = {}; } col.treeAggregation.label = colDef.treeAggregationLabel; } /** * @ngdoc object * @name treeAggregationUpdateEntity * @propertyOf ui.grid.treeBase.api:ColumnDef * @description Store calculated aggregations into the entity, allowing them * to be displayed in the grid using a standard cellTemplate. This defaults to true, * if you are using grouping then you shouldn't set it to false, as then the aggregations won't * display. * * If you are using treeView in most cases you'll want to set this to true. This will result in * getCellValue returning the aggregation rather than whatever was stored in the cell attribute on * the entity. If you want to render the underlying entity value (and do something else with the aggregation) * then you could use a custom cellTemplate to display `row.entity.myAttribute`, rather than using getCellValue. * * <br/>Defaults to true * * @example * <pre> * gridOptions.columns = [{ * name: 'myCol', * treeAggregation: { type: uiGridTreeBaseConstants.aggregation.SUM }, * treeAggregationUpdateEntity: true * cellTemplate: '<div>{{row.entity.myCol + " " + row.treeNode.aggregations[0].rendered}}</div>' * }]; * </pre> */ col.treeAggregationUpdateEntity = colDef.treeAggregationUpdateEntity !== false; /** * @ngdoc object * @name customTreeAggregationFinalizerFn * @propertyOf ui.grid.treeBase.api:ColumnDef * @description A custom function that populates aggregation.rendered, this is called when * a particular aggregation has been fully calculated, and we want to render the value. * * With the native aggregation options we just concatenate `aggregation.label` and * `aggregation.value`, but if you wanted to apply a filter or otherwise manipulate the label * or the value, you can do so with this function. This function will be called after the * the default `finalizerFn`. * * @example * <pre> * customTreeAggregationFinalizerFn = function ( aggregation ){ * aggregation.rendered = aggregation.label + aggregation.value / 100 + '%'; * } * </pre> * <br/>Defaults to undefined. */ if ( typeof(col.customTreeAggregationFinalizerFn) === 'undefined' ){ col.customTreeAggregationFinalizerFn = colDef.customTreeAggregationFinalizerFn; } }, /** * @ngdoc function * @name createRowHeader * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description Create the rowHeader. If treeRowHeaderAlwaysVisible then * set it to visible, otherwise set it to invisible * * @param {Grid} grid grid object */ createRowHeader: function( grid ){ var rowHeaderColumnDef = { name: uiGridTreeBaseConstants.rowHeaderColName, displayName: '', width: grid.options.treeRowHeaderBaseWidth, minWidth: 10, cellTemplate: 'ui-grid/treeBaseRowHeader', headerCellTemplate: 'ui-grid/treeBaseHeaderCell', enableColumnResizing: false, enableColumnMenu: false, exporterSuppressExport: true, allowCellFocus: true }; rowHeaderColumnDef.visible = grid.options.treeRowHeaderAlwaysVisible; grid.addRowHeaderColumn( rowHeaderColumnDef ); }, /** * @ngdoc function * @name expandAllRows * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description Expands all nodes in the tree * * @param {Grid} grid grid object */ expandAllRows: function (grid) { grid.treeBase.tree.forEach( function( node ) { service.setAllNodes( grid, node, uiGridTreeBaseConstants.EXPANDED); }); grid.treeBase.expandAll = true; grid.queueGridRefresh(); }, /** * @ngdoc function * @name collapseAllRows * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description Collapses all nodes in the tree * * @param {Grid} grid grid object */ collapseAllRows: function (grid) { grid.treeBase.tree.forEach( function( node ) { service.setAllNodes( grid, node, uiGridTreeBaseConstants.COLLAPSED); }); grid.treeBase.expandAll = false; grid.queueGridRefresh(); }, /** * @ngdoc function * @name setAllNodes * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description Works through a subset of grid.treeBase.rowExpandedStates, setting * all child nodes (and their descendents) of the provided node to the given state. * * Calls itself recursively on all nodes so as to achieve this. * * @param {Grid} grid the grid we're operating on (so we can raise events) * @param {object} treeNode a node in the tree that we want to update * @param {string} targetState the state we want to set it to */ setAllNodes: function (grid, treeNode, targetState) { if ( typeof(treeNode.state) !== 'undefined' && treeNode.state !== targetState ){ treeNode.state = targetState; if ( targetState === uiGridTreeBaseConstants.EXPANDED ){ grid.api.treeBase.raise.rowExpanded(treeNode.row); } else { grid.api.treeBase.raise.rowCollapsed(treeNode.row); } } // set all child nodes if ( treeNode.children ){ treeNode.children.forEach(function( childNode ){ service.setAllNodes(grid, childNode, targetState); }); } }, /** * @ngdoc function * @name toggleRowTreeState * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description Toggles the expand or collapse state of this grouped row, if * it's a parent row * * @param {Grid} grid grid object * @param {GridRow} row the row we want to toggle */ toggleRowTreeState: function ( grid, row ){ if ( typeof(row.treeLevel) === 'undefined' || row.treeLevel === null || row.treeLevel < 0 ){ return; } if (row.treeNode.state === uiGridTreeBaseConstants.EXPANDED){ service.collapseRow(grid, row); } else { service.expandRow(grid, row); } grid.queueGridRefresh(); }, /** * @ngdoc function * @name expandRow * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description Expands this specific row, showing only immediate children. * * @param {Grid} grid grid object * @param {GridRow} row the row we want to expand */ expandRow: function ( grid, row ){ if ( typeof(row.treeLevel) === 'undefined' || row.treeLevel === null || row.treeLevel < 0 ){ return; } if ( row.treeNode.state !== uiGridTreeBaseConstants.EXPANDED ){ row.treeNode.state = uiGridTreeBaseConstants.EXPANDED; grid.api.treeBase.raise.rowExpanded(row); grid.treeBase.expandAll = service.allExpanded(grid.treeBase.tree); grid.queueGridRefresh(); } }, /** * @ngdoc function * @name expandRowChildren * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description Expands this specific row, showing all children. * * @param {Grid} grid grid object * @param {GridRow} row the row we want to expand */ expandRowChildren: function ( grid, row ){ if ( typeof(row.treeLevel) === 'undefined' || row.treeLevel === null || row.treeLevel < 0 ){ return; } service.setAllNodes(grid, row.treeNode, uiGridTreeBaseConstants.EXPANDED); grid.treeBase.expandAll = service.allExpanded(grid.treeBase.tree); grid.queueGridRefresh(); }, /** * @ngdoc function * @name collapseRow * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description Collapses this specific row * * @param {Grid} grid grid object * @param {GridRow} row the row we want to collapse */ collapseRow: function( grid, row ){ if ( typeof(row.treeLevel) === 'undefined' || row.treeLevel === null || row.treeLevel < 0 ){ return; } if ( row.treeNode.state !== uiGridTreeBaseConstants.COLLAPSED ){ row.treeNode.state = uiGridTreeBaseConstants.COLLAPSED; grid.treeBase.expandAll = false; grid.api.treeBase.raise.rowCollapsed(row); grid.queueGridRefresh(); } }, /** * @ngdoc function * @name collapseRowChildren * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description Collapses this specific row and all children * * @param {Grid} grid grid object * @param {GridRow} row the row we want to collapse */ collapseRowChildren: function( grid, row ){ if ( typeof(row.treeLevel) === 'undefined' || row.treeLevel === null || row.treeLevel < 0 ){ return; } service.setAllNodes(grid, row.treeNode, uiGridTreeBaseConstants.COLLAPSED); grid.treeBase.expandAll = false; grid.queueGridRefresh(); }, /** * @ngdoc function * @name allExpanded * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description Returns true if all rows are expanded, false * if they're not. Walks the tree to determine this. Used * to set the expandAll state. * * If the node has no children, then return true (it's immaterial * whether it is expanded). If the node has children, then return * false if this node is collapsed, or if any child node is not all expanded * * @param {object} tree the grid to check * @returns {boolean} whether or not the tree is all expanded */ allExpanded: function( tree ){ var allExpanded = true; tree.forEach( function( node ){ if ( !service.allExpandedInternal( node ) ){ allExpanded = false; } }); return allExpanded; }, allExpandedInternal: function( treeNode ){ if ( treeNode.children && treeNode.children.length > 0 ){ if ( treeNode.state === uiGridTreeBaseConstants.COLLAPSED ){ return false; } var allExpanded = true; treeNode.children.forEach( function( node ){ if ( !service.allExpandedInternal( node ) ){ allExpanded = false; } }); return allExpanded; } else { return true; } }, /** * @ngdoc function * @name treeRows * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description The rowProcessor that adds the nodes to the tree, and sets the visible * state of each row based on it's parent state * * Assumes it is always called after the sorting processor, and the grouping processor if there is one. * Performs any tree sorts itself after having built the tree * * Processes all the rows in order, setting the group level based on the $$treeLevel in the associated * entity, and setting the visible state based on the parent's state. * * Calculates the deepest level of tree whilst it goes, and updates that so that the header column can be correctly * sized. * * Aggregates if necessary along the way. * * @param {array} renderableRows the rows we want to process, usually the output from the previous rowProcessor * @returns {array} the updated rows */ treeRows: function( renderableRows ) { if (renderableRows.length === 0){ return renderableRows; } var grid = this; var currentLevel = 0; var currentState = uiGridTreeBaseConstants.EXPANDED; var parents = []; grid.treeBase.tree = service.createTree( grid, renderableRows ); service.updateRowHeaderWidth( grid ); service.sortTree( grid ); service.fixFilter( grid ); return service.renderTree( grid.treeBase.tree ); }, /** * @ngdoc function * @name createOrUpdateRowHeaderWidth * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description Calculates the rowHeader width. * * If rowHeader is always present, updates the width. * * If rowHeader is only sometimes present (`treeRowHeaderAlwaysVisible: false`), determines whether there * should be one, then creates or removes it as appropriate, with the created rowHeader having the * right width. * * If there's never a rowHeader then never creates one: `showTreeRowHeader: false` * * @param {Grid} grid the grid we want to set the row header on */ updateRowHeaderWidth: function( grid ){ var rowHeader = grid.getColumn(uiGridTreeBaseConstants.rowHeaderColName); var newWidth = grid.options.treeRowHeaderBaseWidth + grid.options.treeIndent * Math.max(grid.treeBase.numberLevels - 1, 0); if ( rowHeader && newWidth !== rowHeader.width ){ rowHeader.width = newWidth; grid.queueRefresh(); } var newVisibility = true; if ( grid.options.showTreeRowHeader === false ){ newVisibility = false; } if ( grid.options.treeRowHeaderAlwaysVisible === false && grid.treeBase.numberLevels <= 0 ){ newVisibility = false; } if ( rowHeader.visible !== newVisibility ) { rowHeader.visible = newVisibility; rowHeader.colDef.visible = newVisibility; grid.queueGridRefresh(); } }, /** * @ngdoc function * @name renderTree * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description Creates an array of rows based on the tree, exporting only * the visible nodes and leaves * * @param {array} nodeList the list of nodes - can be grid.treeBase.tree, or can be node.children when * we're calling recursively * @returns {array} renderable rows */ renderTree: function( nodeList ){ var renderableRows = []; nodeList.forEach( function ( node ){ if ( node.row.visible ){ renderableRows.push( node.row ); } if ( node.state === uiGridTreeBaseConstants.EXPANDED && node.children && node.children.length > 0 ){ renderableRows = renderableRows.concat( service.renderTree( node.children ) ); } }); return renderableRows; }, /** * @ngdoc function * @name createTree * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description Creates a tree from the renderableRows * * @param {Grid} grid the grid * @param {array} renderableRows the rows we want to create a tree from * @returns {object} the tree we've build */ createTree: function( grid, renderableRows ) { var currentLevel = -1; var parents = []; var currentState; grid.treeBase.tree = []; grid.treeBase.numberLevels = 0; var aggregations = service.getAggregations( grid ); var createNode = function( row ){ if ( typeof(row.entity.$$treeLevel) !== 'undefined' && row.treeLevel !== row.entity.$$treeLevel ){ row.treeLevel = row.entity.$$treeLevel; } if ( row.treeLevel <= currentLevel ){ // pop any levels that aren't parents of this level, formatting the aggregation at the same time while ( row.treeLevel <= currentLevel ){ var lastParent = parents.pop(); service.finaliseAggregations( lastParent ); currentLevel--; } // reset our current state based on the new parent, set to expanded if this is a level 0 node if ( parents.length > 0 ){ currentState = service.setCurrentState(parents); } else { currentState = uiGridTreeBaseConstants.EXPANDED; } } // aggregate if this is a leaf node if ( ( typeof(row.treeLevel) === 'undefined' || row.treeLevel === null || row.treeLevel < 0 ) && row.visible ){ service.aggregate( grid, row, parents ); } // add this node to the tree service.addOrUseNode(grid, row, parents, aggregations); if ( typeof(row.treeLevel) !== 'undefined' && row.treeLevel !== null && row.treeLevel >= 0 ){ parents.push(row); currentLevel++; currentState = service.setCurrentState(parents); } // update the tree number of levels, so we can set header width if we need to if ( grid.treeBase.numberLevels < row.treeLevel + 1){ grid.treeBase.numberLevels = row.treeLevel + 1; } }; renderableRows.forEach( createNode ); // finalise remaining aggregations while ( parents.length > 0 ){ var lastParent = parents.pop(); service.finaliseAggregations( lastParent ); } return grid.treeBase.tree; }, /** * @ngdoc function * @name addOrUseNode * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description Creates a tree node for this row. If this row already has a treeNode * recorded against it, preserves the state, but otherwise overwrites the data. * * @param {grid} grid the grid we're operating on * @param {gridRow} row the row we want to set * @param {array} parents an array of the parents this row should have * @param {array} aggregationBase empty aggregation information * @returns {undefined} updates the parents array, updates the row to have a treeNode, and updates the * grid.treeBase.tree */ addOrUseNode: function( grid, row, parents, aggregationBase ){ var newAggregations = []; aggregationBase.forEach( function(aggregation){ newAggregations.push(service.buildAggregationObject(aggregation.col)); }); var newNode = { state: uiGridTreeBaseConstants.COLLAPSED, row: row, parentRow: null, aggregations: newAggregations, children: [] }; if ( row.treeNode ){ newNode.state = row.treeNode.state; } if ( parents.length > 0 ){ newNode.parentRow = parents[parents.length - 1]; } row.treeNode = newNode; if ( parents.length === 0 ){ grid.treeBase.tree.push( newNode ); } else { parents[parents.length - 1].treeNode.children.push( newNode ); } }, /** * @ngdoc function * @name setCurrentState * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description Looks at the parents array to determine our current state. * If any node in the hierarchy is collapsed, then return collapsed, otherwise return * expanded. * * @param {array} parents an array of the parents this row should have * @returns {string} the state we should be setting to any nodes we see */ setCurrentState: function( parents ){ var currentState = uiGridTreeBaseConstants.EXPANDED; parents.forEach( function(parent){ if ( parent.treeNode.state === uiGridTreeBaseConstants.COLLAPSED ){ currentState = uiGridTreeBaseConstants.COLLAPSED; } }); return currentState; }, /** * @ngdoc function * @name sortTree * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description Performs a recursive sort on the tree nodes, sorting the * children of each node and putting them back into the children array. * * Before doing this it turns back on all the sortIgnore - things that were previously * ignored we process now. Since we're sorting within the nodes, presumably anything * that was already sorted is how we derived the nodes, we can keep those sorts too. * * We only sort tree nodes that are expanded - no point in wasting effort sorting collapsed * nodes * * @param {Grid} grid the grid to get the aggregation information from * @returns {array} the aggregation information */ sortTree: function( grid ){ grid.columns.forEach( function( column ) { if ( column.sort && column.sort.ignoreSort ){ delete column.sort.ignoreSort; } }); grid.treeBase.tree = service.sortInternal( grid, grid.treeBase.tree ); }, sortInternal: function( grid, treeList ){ var rows = treeList.map( function( node ){ return node.row; }); rows = rowSorter.sort( grid, rows, grid.columns ); var treeNodes = rows.map( function( row ){ return row.treeNode; }); treeNodes.forEach( function( node ){ if ( node.state === uiGridTreeBaseConstants.EXPANDED && node.children && node.children.length > 0 ){ node.children = service.sortInternal( grid, node.children ); } }); return treeNodes; }, /** * @ngdoc function * @name fixFilter * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description After filtering has run, we need to go back through the tree * and make sure the parent rows are always visible if any of the child rows * are visible (filtering may make a child visible, but the parent may not * match the filter criteria) * * This has a risk of being computationally expensive, we do it by walking * the tree and remembering whether there are any invisible nodes on the * way down. * * @param {Grid} grid the grid to fix filters on */ fixFilter: function( grid ){ var parentsVisible; grid.treeBase.tree.forEach( function( node ){ if ( node.children && node.children.length > 0 ){ parentsVisible = node.row.visible; service.fixFilterInternal( node.children, parentsVisible ); } }); }, fixFilterInternal: function( nodes, parentsVisible) { nodes.forEach( function( node ){ if ( node.row.visible && !parentsVisible ){ service.setParentsVisible( node ); parentsVisible = true; } if ( node.children && node.children.length > 0 ){ if ( service.fixFilterInternal( node.children, ( parentsVisible && node.row.visible ) ) ) { parentsVisible = true; } } }); return parentsVisible; }, setParentsVisible: function( node ){ while ( node.parentRow ){ node.parentRow.visible = true; node = node.parentRow.treeNode; } }, /** * @ngdoc function * @name buildAggregationObject * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description Build the object which is stored on the column for holding meta-data about the aggregation. * This method should only be called with columns which have an aggregation. * * @param {Column} the column which this object relates to * @returns {object} {col: Column object, label: string, type: string (optional)} */ buildAggregationObject: function( column ){ var newAggregation = { col: column }; if ( column.treeAggregation && column.treeAggregation.type ){ newAggregation.type = column.treeAggregation.type; } if ( column.treeAggregation && column.treeAggregation.label ){ newAggregation.label = column.treeAggregation.label; } return newAggregation; }, /** * @ngdoc function * @name getAggregations * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description Looks through the grid columns to find those with aggregations, * and collates the aggregation information into an array, returns that array * * @param {Grid} grid the grid to get the aggregation information from * @returns {array} the aggregation information */ getAggregations: function( grid ){ var aggregateArray = []; grid.columns.forEach( function(column){ if ( typeof(column.treeAggregationFn) !== 'undefined' ){ aggregateArray.push( service.buildAggregationObject(column) ); if ( grid.options.showColumnFooter && typeof(column.colDef.aggregationType) === 'undefined' && column.treeAggregation ){ // Add aggregation object for footer column.treeFooterAggregation = service.buildAggregationObject(column); column.aggregationType = service.treeFooterAggregationType; } } }); return aggregateArray; }, /** * @ngdoc function * @name aggregate * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description Accumulate the data from this row onto the aggregations for each parent * * Iterate over the parents, then iterate over the aggregations for each of those parents, * and perform the aggregation for each individual aggregation * * @param {Grid} grid grid object * @param {GridRow} row the row we want to set grouping visibility on * @param {array} parents the parents that we would want to aggregate onto */ aggregate: function( grid, row, parents ){ if ( parents.length === 0 && row.treeNode && row.treeNode.aggregations ){ row.treeNode.aggregations.forEach(function(aggregation){ // Calculate aggregations for footer even if there are no grouped rows if ( typeof(aggregation.col.treeFooterAggregation) !== 'undefined' ) { var fieldValue = grid.getCellValue(row, aggregation.col); var numValue = Number(fieldValue); aggregation.col.treeAggregationFn(aggregation.col.treeFooterAggregation, fieldValue, numValue, row); } }); } parents.forEach( function( parent, index ){ if ( parent.treeNode.aggregations ){ parent.treeNode.aggregations.forEach( function( aggregation ){ var fieldValue = grid.getCellValue(row, aggregation.col); var numValue = Number(fieldValue); aggregation.col.treeAggregationFn(aggregation, fieldValue, numValue, row); if ( index === 0 && typeof(aggregation.col.treeFooterAggregation) !== 'undefined' ){ aggregation.col.treeAggregationFn(aggregation.col.treeFooterAggregation, fieldValue, numValue, row); } }); } }); }, // Aggregation routines - no doco needed as self evident nativeAggregations: function() { var nativeAggregations = { count: { label: i18nService.get().aggregation.count, menuTitle: i18nService.get().grouping.aggregate_count, aggregationFn: function (aggregation, fieldValue, numValue) { if (typeof(aggregation.value) === 'undefined') { aggregation.value = 1; } else { aggregation.value++; } } }, sum: { label: i18nService.get().aggregation.sum, menuTitle: i18nService.get().grouping.aggregate_sum, aggregationFn: function( aggregation, fieldValue, numValue ) { if (!isNaN(numValue)) { if (typeof(aggregation.value) === 'undefined') { aggregation.value = numValue; } else { aggregation.value += numValue; } } } }, min: { label: i18nService.get().aggregation.min, menuTitle: i18nService.get().grouping.aggregate_min, aggregationFn: function( aggregation, fieldValue, numValue ) { if (typeof(aggregation.value) === 'undefined') { aggregation.value = fieldValue; } else { if (typeof(fieldValue) !== 'undefined' && fieldValue !== null && (fieldValue < aggregation.value || aggregation.value === null)) { aggregation.value = fieldValue; } } } }, max: { label: i18nService.get().aggregation.max, menuTitle: i18nService.get().grouping.aggregate_max, aggregationFn: function( aggregation, fieldValue, numValue ){ if ( typeof(aggregation.value) === 'undefined' ){ aggregation.value = fieldValue; } else { if ( typeof(fieldValue) !== 'undefined' && fieldValue !== null && (fieldValue > aggregation.value || aggregation.value === null)){ aggregation.value = fieldValue; } } } }, avg: { label: i18nService.get().aggregation.avg, menuTitle: i18nService.get().grouping.aggregate_avg, aggregationFn: function( aggregation, fieldValue, numValue ){ if ( typeof(aggregation.count) === 'undefined' ){ aggregation.count = 1; } else { aggregation.count++; } if ( isNaN(numValue) ){ return; } if ( typeof(aggregation.value) === 'undefined' || typeof(aggregation.sum) === 'undefined' ){ aggregation.value = numValue; aggregation.sum = numValue; } else { aggregation.sum += numValue; aggregation.value = aggregation.sum / aggregation.count; } } } }; return nativeAggregations; }, /** * @ngdoc function * @name finaliseAggregation * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description Helper function used to finalize aggregation nodes and footer cells * * @param {gridRow} row the parent we're finalising * @param {aggregation} the aggregation object manipulated by the aggregationFn */ finaliseAggregation: function(row, aggregation){ if ( aggregation.col.treeAggregationUpdateEntity && typeof(row) !== 'undefined' && typeof(row.entity[ '$$' + aggregation.col.uid ]) !== 'undefined' ){ angular.extend( aggregation, row.entity[ '$$' + aggregation.col.uid ]); } if ( typeof(aggregation.col.treeAggregationFinalizerFn) === 'function' ){ aggregation.col.treeAggregationFinalizerFn( aggregation ); } if ( typeof(aggregation.col.customTreeAggregationFinalizerFn) === 'function' ){ aggregation.col.customTreeAggregationFinalizerFn( aggregation ); } if ( typeof(aggregation.rendered) === 'undefined' ){ aggregation.rendered = aggregation.label ? aggregation.label + aggregation.value : aggregation.value; } }, /** * @ngdoc function * @name finaliseAggregations * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description Format the data from the aggregation into the rendered text * e.g. if we had label: 'sum: ' and value: 25, we'd create 'sum: 25'. * * As part of this we call any formatting callback routines we've been provided. * * We write our aggregation out to the row.entity if treeAggregationUpdateEntity is * set on the column - we don't overwrite any information that's already there, we append * to it so that grouping can have set the groupVal beforehand without us overwriting it. * * We need to copy the data from the row.entity first before we finalise the aggregation, * we need that information for the finaliserFn * * @param {gridRow} row the parent we're finalising */ finaliseAggregations: function( row ){ if ( typeof(row.treeNode.aggregations) === 'undefined' ){ return; } row.treeNode.aggregations.forEach( function( aggregation ) { service.finaliseAggregation(row, aggregation); if ( aggregation.col.treeAggregationUpdateEntity ){ var aggregationCopy = {}; angular.forEach( aggregation, function( value, key ){ if ( aggregation.hasOwnProperty(key) && key !== 'col' ){ aggregationCopy[key] = value; } }); row.entity[ '$$' + aggregation.col.uid ] = aggregationCopy; } }); }, /** * @ngdoc function * @name treeFooterAggregationType * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description Uses the tree aggregation functions and finalizers to set the * column footer aggregations. * * @param {rows} visible rows. not used, but accepted to match signature of GridColumn.aggregationType * @param {gridColumn} the column we are finalizing */ treeFooterAggregationType: function( rows, column ) { service.finaliseAggregation(undefined, column.treeFooterAggregation); if ( typeof(column.treeFooterAggregation.value) === 'undefined' || column.treeFooterAggregation.rendered === null ){ // The was apparently no aggregation performed (perhaps this is a grouped column return ''; } return column.treeFooterAggregation.rendered; } }; return service; }]); /** * @ngdoc directive * @name ui.grid.treeBase.directive:uiGridTreeRowHeaderButtons * @element div * * @description Provides the expand/collapse button on rows */ module.directive('uiGridTreeBaseRowHeaderButtons', ['$templateCache', 'uiGridTreeBaseService', function ($templateCache, uiGridTreeBaseService) { return { replace: true, restrict: 'E', template: $templateCache.get('ui-grid/treeBaseRowHeaderButtons'), scope: true, require: '^uiGrid', link: function($scope, $elm, $attrs, uiGridCtrl) { var self = uiGridCtrl.grid; $scope.treeButtonClick = function(row, evt) { uiGridTreeBaseService.toggleRowTreeState(self, row, evt); }; } }; }]); /** * @ngdoc directive * @name ui.grid.treeBase.directive:uiGridTreeBaseExpandAllButtons * @element div * * @description Provides the expand/collapse all button */ module.directive('uiGridTreeBaseExpandAllButtons', ['$templateCache', 'uiGridTreeBaseService', function ($templateCache, uiGridTreeBaseService) { return { replace: true, restrict: 'E', template: $templateCache.get('ui-grid/treeBaseExpandAllButtons'), scope: false, link: function($scope, $elm, $attrs, uiGridCtrl) { var self = $scope.col.grid; $scope.headerButtonClick = function(row, evt) { if ( self.treeBase.expandAll ){ uiGridTreeBaseService.collapseAllRows(self, evt); } else { uiGridTreeBaseService.expandAllRows(self, evt); } }; } }; }]); /** * @ngdoc directive * @name ui.grid.treeBase.directive:uiGridViewport * @element div * * @description Stacks on top of ui.grid.uiGridViewport to set formatting on a tree header row */ module.directive('uiGridViewport', ['$compile', 'uiGridConstants', 'gridUtil', '$parse', function ($compile, uiGridConstants, gridUtil, $parse) { return { priority: -200, // run after default directive scope: false, compile: function ($elm, $attrs) { var rowRepeatDiv = angular.element($elm.children().children()[0]); var existingNgClass = rowRepeatDiv.attr("ng-class"); var newNgClass = ''; if ( existingNgClass ) { newNgClass = existingNgClass.slice(0, -1) + ",'ui-grid-tree-header-row': row.treeLevel > -1}"; } else { newNgClass = "{'ui-grid-tree-header-row': row.treeLevel > -1}"; } rowRepeatDiv.attr("ng-class", newNgClass); return { pre: function ($scope, $elm, $attrs, controllers) { }, post: function ($scope, $elm, $attrs, controllers) { } }; } }; }]); })(); (function () { 'use strict'; /** * @ngdoc overview * @name ui.grid.treeView * @description * * # ui.grid.treeView * * <div class="alert alert-warning" role="alert"><strong>Beta</strong> This feature is ready for testing, but it either hasn't seen a lot of use or has some known bugs.</div> * * This module provides a tree view of the data that it is provided, with nodes in that * tree and leaves. Unlike grouping, the tree is an inherent property of the data and must * be provided with your data array. * * Design information: * ------------------- * * TreeView uses treeBase for the underlying functionality, and is a very thin wrapper around * that logic. Most of the design information has now moved to treebase. * <br/> * <br/> * * <div doc-module-components="ui.grid.treeView"></div> */ var module = angular.module('ui.grid.treeView', ['ui.grid', 'ui.grid.treeBase']); /** * @ngdoc object * @name ui.grid.treeView.constant:uiGridTreeViewConstants * * @description constants available in treeView module, this includes * all the constants declared in the treeBase module (these are manually copied * as there isn't an easy way to include constants in another constants file, and * we don't want to make users include treeBase) * */ module.constant('uiGridTreeViewConstants', { featureName: "treeView", rowHeaderColName: 'treeBaseRowHeaderCol', EXPANDED: 'expanded', COLLAPSED: 'collapsed', aggregation: { COUNT: 'count', SUM: 'sum', MAX: 'max', MIN: 'min', AVG: 'avg' } }); /** * @ngdoc service * @name ui.grid.treeView.service:uiGridTreeViewService * * @description Services for treeView features */ module.service('uiGridTreeViewService', ['$q', 'uiGridTreeViewConstants', 'uiGridTreeBaseConstants', 'uiGridTreeBaseService', 'gridUtil', 'GridRow', 'gridClassFactory', 'i18nService', 'uiGridConstants', function ($q, uiGridTreeViewConstants, uiGridTreeBaseConstants, uiGridTreeBaseService, gridUtil, GridRow, gridClassFactory, i18nService, uiGridConstants) { var service = { initializeGrid: function (grid, $scope) { uiGridTreeBaseService.initializeGrid( grid, $scope ); /** * @ngdoc object * @name ui.grid.treeView.grid:treeView * * @description Grid properties and functions added for treeView */ grid.treeView = {}; grid.registerRowsProcessor(service.adjustSorting, 60); /** * @ngdoc object * @name ui.grid.treeView.api:PublicApi * * @description Public Api for treeView feature */ var publicApi = { events: { treeView: { } }, methods: { treeView: { } } }; grid.api.registerEventsFromObject(publicApi.events); grid.api.registerMethodsFromObject(publicApi.methods); }, defaultGridOptions: function (gridOptions) { //default option to true unless it was explicitly set to false /** * @ngdoc object * @name ui.grid.treeView.api:GridOptions * * @description GridOptions for treeView feature, these are available to be * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions} * * Many tree options are set on treeBase, make sure to look at that feature in * conjunction with these options. */ /** * @ngdoc object * @name enableTreeView * @propertyOf ui.grid.treeView.api:GridOptions * @description Enable row tree view for entire grid. * <br/>Defaults to true */ gridOptions.enableTreeView = gridOptions.enableTreeView !== false; }, /** * @ngdoc function * @name adjustSorting * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description Trees cannot be sorted the same as flat lists of rows - * trees are sorted recursively within each level - so the children of each * node are sorted, but not the full set of rows. * * To achieve this, we suppress the normal sorting by setting ignoreSort on * each of the sort columns. When the treeBase rowsProcessor runs it will then * unignore these, and will perform a recursive sort against the tree that it builds. * * @param {array} renderableRows the rows that we need to pass on through * @returns {array} renderableRows that we passed on through */ adjustSorting: function( renderableRows ) { var grid = this; grid.columns.forEach( function( column ){ if ( column.sort ){ column.sort.ignoreSort = true; } }); return renderableRows; } }; return service; }]); /** * @ngdoc directive * @name ui.grid.treeView.directive:uiGridTreeView * @element div * @restrict A * * @description Adds treeView features to grid * * @example <example module="app"> <file name="app.js"> var app = angular.module('app', ['ui.grid', 'ui.grid.treeView']); app.controller('MainCtrl', ['$scope', function ($scope) { $scope.data = [ { name: 'Bob', title: 'CEO' }, { name: 'Frank', title: 'Lowly Developer' } ]; $scope.columnDefs = [ {name: 'name', enableCellEdit: true}, {name: 'title', enableCellEdit: true} ]; $scope.gridOptions = { columnDefs: $scope.columnDefs, data: $scope.data }; }]); </file> <file name="index.html"> <div ng-controller="MainCtrl"> <div ui-grid="gridOptions" ui-grid-tree-view></div> </div> </file> </example> */ module.directive('uiGridTreeView', ['uiGridTreeViewConstants', 'uiGridTreeViewService', '$templateCache', function (uiGridTreeViewConstants, uiGridTreeViewService, $templateCache) { return { replace: true, priority: 0, require: '^uiGrid', scope: false, compile: function () { return { pre: function ($scope, $elm, $attrs, uiGridCtrl) { if (uiGridCtrl.grid.options.enableTreeView !== false){ uiGridTreeViewService.initializeGrid(uiGridCtrl.grid, $scope); } }, post: function ($scope, $elm, $attrs, uiGridCtrl) { } }; } }; }]); })(); angular.module('ui.grid').run(['$templateCache', function($templateCache) { 'use strict'; $templateCache.put('ui-grid/ui-grid-filter', "<div class=\"ui-grid-filter-container\" ng-repeat=\"colFilter in col.filters\" ng-class=\"{'ui-grid-filter-cancel-button-hidden' : colFilter.disableCancelFilterButton === true }\"><div ng-if=\"colFilter.type !== 'select'\"><input type=\"text\" class=\"ui-grid-filter-input ui-grid-filter-input-{{$index}}\" ng-model=\"colFilter.term\" ng-attr-placeholder=\"{{colFilter.placeholder || ''}}\" aria-label=\"{{colFilter.ariaLabel || aria.defaultFilterLabel}}\"><div role=\"button\" class=\"ui-grid-filter-button\" ng-click=\"removeFilter(colFilter, $index)\" ng-if=\"!colFilter.disableCancelFilterButton\" ng-disabled=\"colFilter.term === undefined || colFilter.term === null || colFilter.term === ''\" ng-show=\"colFilter.term !== undefined && colFilter.term !== null && colFilter.term !== ''\"><i class=\"ui-grid-icon-cancel\" ui-grid-one-bind-aria-label=\"aria.removeFilter\">&nbsp;</i></div></div><div ng-if=\"colFilter.type === 'select'\"><select class=\"ui-grid-filter-select ui-grid-filter-input-{{$index}}\" ng-model=\"colFilter.term\" ng-attr-placeholder=\"{{colFilter.placeholder || aria.defaultFilterLabel}}\" aria-label=\"{{colFilter.ariaLabel || ''}}\" ng-options=\"option.value as option.label for option in colFilter.selectOptions\"><option value=\"\"></option></select><div role=\"button\" class=\"ui-grid-filter-button-select\" ng-click=\"removeFilter(colFilter, $index)\" ng-if=\"!colFilter.disableCancelFilterButton\" ng-disabled=\"colFilter.term === undefined || colFilter.term === null || colFilter.term === ''\" ng-show=\"colFilter.term !== undefined && colFilter.term != null\"><i class=\"ui-grid-icon-cancel\" ui-grid-one-bind-aria-label=\"aria.removeFilter\">&nbsp;</i></div></div></div>" ); $templateCache.put('ui-grid/ui-grid-footer', "<div class=\"ui-grid-footer-panel ui-grid-footer-aggregates-row\"><!-- tfooter --><div class=\"ui-grid-footer ui-grid-footer-viewport\"><div class=\"ui-grid-footer-canvas\"><div class=\"ui-grid-footer-cell-wrapper\" ng-style=\"colContainer.headerCellWrapperStyle()\"><div role=\"row\" class=\"ui-grid-footer-cell-row\"><div ui-grid-footer-cell role=\"gridcell\" ng-repeat=\"col in colContainer.renderedColumns track by col.uid\" col=\"col\" render-index=\"$index\" class=\"ui-grid-footer-cell ui-grid-clearfix\"></div></div></div></div></div></div>" ); $templateCache.put('ui-grid/ui-grid-grid-footer', "<div class=\"ui-grid-footer-info ui-grid-grid-footer\"><span>{{'search.totalItems' | t}} {{grid.rows.length}}</span> <span ng-if=\"grid.renderContainers.body.visibleRowCache.length !== grid.rows.length\" class=\"ngLabel\">({{\"search.showingItems\" | t}} {{grid.renderContainers.body.visibleRowCache.length}})</span></div>" ); $templateCache.put('ui-grid/ui-grid-group-panel', "<div class=\"ui-grid-group-panel\"><div ui-t=\"groupPanel.description\" class=\"description\" ng-show=\"groupings.length == 0\"></div><ul ng-show=\"groupings.length > 0\" class=\"ngGroupList\"><li class=\"ngGroupItem\" ng-repeat=\"group in configGroups\"><span class=\"ngGroupElement\"><span class=\"ngGroupName\">{{group.displayName}} <span ng-click=\"removeGroup($index)\" class=\"ngRemoveGroup\">x</span></span> <span ng-hide=\"$last\" class=\"ngGroupArrow\"></span></span></li></ul></div>" ); $templateCache.put('ui-grid/ui-grid-header', "<div role=\"rowgroup\" class=\"ui-grid-header\"><!-- theader --><div class=\"ui-grid-top-panel\"><div class=\"ui-grid-header-viewport\"><div class=\"ui-grid-header-canvas\"><div class=\"ui-grid-header-cell-wrapper\" ng-style=\"colContainer.headerCellWrapperStyle()\"><div role=\"row\" class=\"ui-grid-header-cell-row\"><div class=\"ui-grid-header-cell ui-grid-clearfix\" ng-repeat=\"col in colContainer.renderedColumns track by col.uid\" ui-grid-header-cell col=\"col\" render-index=\"$index\"></div></div></div></div></div></div></div>" ); $templateCache.put('ui-grid/ui-grid-menu-button', "<div class=\"ui-grid-menu-button\"><div role=\"button\" ui-grid-one-bind-id-grid=\"'grid-menu'\" class=\"ui-grid-icon-container\" ng-click=\"toggleMenu()\" aria-haspopup=\"true\"><i class=\"ui-grid-icon-menu\" ui-grid-one-bind-aria-label=\"i18n.aria.buttonLabel\">&nbsp;</i></div><div ui-grid-menu menu-items=\"menuItems\"></div></div>" ); $templateCache.put('ui-grid/ui-grid-no-header', "<div class=\"ui-grid-top-panel\"></div>" ); $templateCache.put('ui-grid/ui-grid-row', "<div ng-repeat=\"(colRenderIndex, col) in colContainer.renderedColumns track by col.uid\" ui-grid-one-bind-id-grid=\"rowRenderIndex + '-' + col.uid + '-cell'\" class=\"ui-grid-cell\" ng-class=\"{ 'ui-grid-row-header-cell': col.isRowHeader }\" role=\"{{col.isRowHeader ? 'rowheader' : 'gridcell'}}\" ui-grid-cell></div>" ); $templateCache.put('ui-grid/ui-grid', "<div ui-i18n=\"en\" class=\"ui-grid\"><!-- TODO (c0bra): add \"scoped\" attr here, eventually? --><style ui-grid-style>.grid{{ grid.id }} {\n" + " /* Styles for the grid */\n" + " }\n" + "\n" + " .grid{{ grid.id }} .ui-grid-row, .grid{{ grid.id }} .ui-grid-cell, .grid{{ grid.id }} .ui-grid-cell .ui-grid-vertical-bar {\n" + " height: {{ grid.options.rowHeight }}px;\n" + " }\n" + "\n" + " .grid{{ grid.id }} .ui-grid-row:last-child .ui-grid-cell {\n" + " border-bottom-width: {{ ((grid.getTotalRowHeight() < grid.getViewportHeight()) && '1') || '0' }}px;\n" + " }\n" + "\n" + " {{ grid.verticalScrollbarStyles }}\n" + " {{ grid.horizontalScrollbarStyles }}\n" + "\n" + " /*\n" + " .ui-grid[dir=rtl] .ui-grid-viewport {\n" + " padding-left: {{ grid.verticalScrollbarWidth }}px;\n" + " }\n" + " */\n" + "\n" + " {{ grid.customStyles }}</style><div class=\"ui-grid-contents-wrapper\"><div ui-grid-menu-button ng-if=\"grid.options.enableGridMenu\"></div><div ng-if=\"grid.hasLeftContainer()\" style=\"width: 0\" ui-grid-pinned-container=\"'left'\"></div><div ui-grid-render-container container-id=\"'body'\" col-container-name=\"'body'\" row-container-name=\"'body'\" bind-scroll-horizontal=\"true\" bind-scroll-vertical=\"true\" enable-horizontal-scrollbar=\"grid.options.enableHorizontalScrollbar\" enable-vertical-scrollbar=\"grid.options.enableVerticalScrollbar\"></div><div ng-if=\"grid.hasRightContainer()\" style=\"width: 0\" ui-grid-pinned-container=\"'right'\"></div><div ui-grid-grid-footer ng-if=\"grid.options.showGridFooter\"></div><div ui-grid-column-menu ng-if=\"grid.options.enableColumnMenus\"></div><div ng-transclude></div></div></div>" ); $templateCache.put('ui-grid/uiGridCell', "<div class=\"ui-grid-cell-contents\" title=\"TOOLTIP\">{{COL_FIELD CUSTOM_FILTERS}}</div>" ); $templateCache.put('ui-grid/uiGridColumnMenu', "<div class=\"ui-grid-column-menu\"><div ui-grid-menu menu-items=\"menuItems\"><!-- <div class=\"ui-grid-column-menu\">\n" + " <div class=\"inner\" ng-show=\"menuShown\">\n" + " <ul>\n" + " <div ng-show=\"grid.options.enableSorting\">\n" + " <li ng-click=\"sortColumn($event, asc)\" ng-class=\"{ 'selected' : col.sort.direction == asc }\"><i class=\"ui-grid-icon-sort-alt-up\"></i> Sort Ascending</li>\n" + " <li ng-click=\"sortColumn($event, desc)\" ng-class=\"{ 'selected' : col.sort.direction == desc }\"><i class=\"ui-grid-icon-sort-alt-down\"></i> Sort Descending</li>\n" + " <li ng-show=\"col.sort.direction\" ng-click=\"unsortColumn()\"><i class=\"ui-grid-icon-cancel\"></i> Remove Sort</li>\n" + " </div>\n" + " </ul>\n" + " </div>\n" + " </div> --></div></div>" ); $templateCache.put('ui-grid/uiGridFooterCell', "<div class=\"ui-grid-cell-contents\" col-index=\"renderIndex\"><div>{{ col.getAggregationText() + ( col.getAggregationValue() CUSTOM_FILTERS ) }}</div></div>" ); $templateCache.put('ui-grid/uiGridHeaderCell', "<div role=\"columnheader\" ng-class=\"{ 'sortable': sortable }\" ui-grid-one-bind-aria-labelledby-grid=\"col.uid + '-header-text ' + col.uid + '-sortdir-text'\" aria-sort=\"{{col.sort.direction == asc ? 'ascending' : ( col.sort.direction == desc ? 'descending' : (!col.sort.direction ? 'none' : 'other'))}}\"><div role=\"button\" tabindex=\"0\" class=\"ui-grid-cell-contents ui-grid-header-cell-primary-focus\" col-index=\"renderIndex\" title=\"TOOLTIP\"><span ui-grid-one-bind-id-grid=\"col.uid + '-header-text'\">{{ col.displayName CUSTOM_FILTERS }}</span> <span ui-grid-one-bind-id-grid=\"col.uid + '-sortdir-text'\" ui-grid-visible=\"col.sort.direction\" aria-label=\"{{getSortDirectionAriaLabel()}}\"><i ng-class=\"{ 'ui-grid-icon-up-dir': col.sort.direction == asc, 'ui-grid-icon-down-dir': col.sort.direction == desc, 'ui-grid-icon-blank': !col.sort.direction }\" title=\"{{col.sort.priority ? i18n.headerCell.priority + ' ' + col.sort.priority : null}}\" aria-hidden=\"true\">&nbsp;</i></span></div><div role=\"button\" tabindex=\"0\" ui-grid-one-bind-id-grid=\"col.uid + '-menu-button'\" class=\"ui-grid-column-menu-button\" ng-if=\"grid.options.enableColumnMenus && !col.isRowHeader && col.colDef.enableColumnMenu !== false\" ng-click=\"toggleMenu($event)\" ng-class=\"{'ui-grid-column-menu-button-last-col': isLastCol}\" ui-grid-one-bind-aria-label=\"i18n.headerCell.aria.columnMenuButtonLabel\" aria-haspopup=\"true\"><i class=\"ui-grid-icon-angle-down\" aria-hidden=\"true\">&nbsp;</i></div><div ui-grid-filter></div></div>" ); $templateCache.put('ui-grid/uiGridMenu', "<div class=\"ui-grid-menu\" ng-if=\"shown\"><div class=\"ui-grid-menu-mid\" ng-show=\"shownMid\"><div class=\"ui-grid-menu-inner\"><button type=\"button\" ng-focus=\"focus=true\" ng-blur=\"focus=false\" class=\"ui-grid-menu-close-button\" ng-class=\"{'ui-grid-sr-only': (!focus)}\"><i class=\"ui-grid-icon-cancel\" ui-grid-one-bind-aria-label=\"i18n.close\"></i></button><ul role=\"menu\" class=\"ui-grid-menu-items\"><li ng-repeat=\"item in menuItems\" role=\"menuitem\" ui-grid-menu-item ui-grid-one-bind-id=\"'menuitem-'+$index\" action=\"item.action\" name=\"item.title\" active=\"item.active\" icon=\"item.icon\" shown=\"item.shown\" context=\"item.context\" template-url=\"item.templateUrl\" leave-open=\"item.leaveOpen\" screen-reader-only=\"item.screenReaderOnly\"></li></ul></div></div></div>" ); $templateCache.put('ui-grid/uiGridMenuItem', "<button type=\"button\" class=\"ui-grid-menu-item\" ng-click=\"itemAction($event, title)\" ng-show=\"itemShown()\" ng-class=\"{ 'ui-grid-menu-item-active': active(), 'ui-grid-sr-only': (!focus && screenReaderOnly) }\" aria-pressed=\"{{active()}}\" tabindex=\"0\" ng-focus=\"focus=true\" ng-blur=\"focus=false\"><i ng-class=\"icon\" aria-hidden=\"true\">&nbsp;</i> {{ name }}</button>" ); $templateCache.put('ui-grid/uiGridRenderContainer', "<div role=\"grid\" ui-grid-one-bind-id-grid=\"'grid-container'\" class=\"ui-grid-render-container\" ng-style=\"{ 'margin-left': colContainer.getMargin('left') + 'px', 'margin-right': colContainer.getMargin('right') + 'px' }\"><!-- All of these dom elements are replaced in place --><div ui-grid-header></div><div ui-grid-viewport></div><div ng-if=\"colContainer.needsHScrollbarPlaceholder()\" class=\"ui-grid-scrollbar-placeholder\" ng-style=\"{height:colContainer.grid.scrollbarHeight + 'px'}\"></div><ui-grid-footer ng-if=\"grid.options.showColumnFooter\"></ui-grid-footer></div>" ); $templateCache.put('ui-grid/uiGridViewport', "<div role=\"rowgroup\" class=\"ui-grid-viewport\" ng-style=\"colContainer.getViewportStyle()\"><!-- tbody --><div class=\"ui-grid-canvas\"><div ng-repeat=\"(rowRenderIndex, row) in rowContainer.renderedRows track by $index\" class=\"ui-grid-row\" ng-style=\"Viewport.rowStyle(rowRenderIndex)\"><div role=\"row\" ui-grid-row=\"row\" row-render-index=\"rowRenderIndex\"></div></div></div></div>" ); $templateCache.put('ui-grid/cellEditor', "<div><form name=\"inputForm\"><input type=\"INPUT_TYPE\" ng-class=\"'colt' + col.uid\" ui-grid-editor ng-model=\"MODEL_COL_FIELD\"></form></div>" ); $templateCache.put('ui-grid/dropdownEditor', "<div><form name=\"inputForm\"><select ng-class=\"'colt' + col.uid\" ui-grid-edit-dropdown ng-model=\"MODEL_COL_FIELD\" ng-options=\"field[editDropdownIdLabel] as field[editDropdownValueLabel] CUSTOM_FILTERS for field in editDropdownOptionsArray\"></select></form></div>" ); $templateCache.put('ui-grid/fileChooserEditor', "<div><form name=\"inputForm\"><input ng-class=\"'colt' + col.uid\" ui-grid-edit-file-chooser type=\"file\" id=\"files\" name=\"files[]\" ng-model=\"MODEL_COL_FIELD\"></form></div>" ); $templateCache.put('ui-grid/expandableRow', "<div ui-grid-expandable-row ng-if=\"expandableRow.shouldRenderExpand()\" class=\"expandableRow\" style=\"float:left; margin-top: 1px; margin-bottom: 1px\" ng-style=\"{width: (grid.renderContainers.body.getCanvasWidth()) + 'px', height: grid.options.expandableRowHeight + 'px'}\"></div>" ); $templateCache.put('ui-grid/expandableRowHeader', "<div class=\"ui-grid-row-header-cell ui-grid-expandable-buttons-cell\"><div class=\"ui-grid-cell-contents\"><i ng-class=\"{ 'ui-grid-icon-plus-squared' : !row.isExpanded, 'ui-grid-icon-minus-squared' : row.isExpanded }\" ng-click=\"grid.api.expandable.toggleRowExpansion(row.entity)\"></i></div></div>" ); $templateCache.put('ui-grid/expandableScrollFiller', "<div ng-if=\"expandableRow.shouldRenderFiller()\" ng-class=\"{scrollFiller:true, scrollFillerClass:(colContainer.name === 'body')}\" ng-style=\"{ width: (grid.getViewportWidth()) + 'px', height: grid.options.expandableRowHeight + 2 + 'px', 'margin-left': grid.options.rowHeader.rowHeaderWidth + 'px' }\"><i class=\"ui-grid-icon-spin5 ui-grid-animate-spin\" ng-style=\"{'margin-top': ( grid.options.expandableRowHeight/2 - 5) + 'px', 'margin-left' : ((grid.getViewportWidth() - grid.options.rowHeader.rowHeaderWidth)/2 - 5) + 'px'}\"></i></div>" ); $templateCache.put('ui-grid/expandableTopRowHeader', "<div class=\"ui-grid-row-header-cell ui-grid-expandable-buttons-cell\"><div class=\"ui-grid-cell-contents\"><i ng-class=\"{ 'ui-grid-icon-plus-squared' : !grid.expandable.expandedAll, 'ui-grid-icon-minus-squared' : grid.expandable.expandedAll }\" ng-click=\"grid.api.expandable.toggleAllRows()\"></i></div></div>" ); $templateCache.put('ui-grid/csvLink', "<span class=\"ui-grid-exporter-csv-link-span\"><a href=\"data:text/csv;charset=UTF-8,CSV_CONTENT\" download=\"FILE_NAME\">LINK_LABEL</a></span>" ); $templateCache.put('ui-grid/importerMenuItem', "<li class=\"ui-grid-menu-item\"><form><input class=\"ui-grid-importer-file-chooser\" type=\"file\" id=\"files\" name=\"files[]\"></form></li>" ); $templateCache.put('ui-grid/importerMenuItemContainer', "<div ui-grid-importer-menu-item></div>" ); $templateCache.put('ui-grid/pagination', "<div role=\"contentinfo\" class=\"ui-grid-pager-panel\" ui-grid-pager ng-show=\"grid.options.enablePaginationControls\"><div role=\"navigation\" class=\"ui-grid-pager-container\"><div role=\"menubar\" class=\"ui-grid-pager-control\"><button type=\"button\" role=\"menuitem\" class=\"ui-grid-pager-first\" ui-grid-one-bind-title=\"aria.pageToFirst\" ui-grid-one-bind-aria-label=\"aria.pageToFirst\" ng-click=\"pageFirstPageClick()\" ng-disabled=\"cantPageBackward()\"><div class=\"first-triangle\"><div class=\"first-bar\"></div></div></button> <button type=\"button\" role=\"menuitem\" class=\"ui-grid-pager-previous\" ui-grid-one-bind-title=\"aria.pageBack\" ui-grid-one-bind-aria-label=\"aria.pageBack\" ng-click=\"pagePreviousPageClick()\" ng-disabled=\"cantPageBackward()\"><div class=\"first-triangle prev-triangle\"></div></button> <input type=\"number\" ui-grid-one-bind-title=\"aria.pageSelected\" ui-grid-one-bind-aria-label=\"aria.pageSelected\" class=\"ui-grid-pager-control-input\" ng-model=\"grid.options.paginationCurrentPage\" min=\"1\" max=\"{{ paginationApi.getTotalPages() }}\" required> <span class=\"ui-grid-pager-max-pages-number\" ng-show=\"paginationApi.getTotalPages() > 0\"><abbr ui-grid-one-bind-title=\"paginationOf\">/</abbr> {{ paginationApi.getTotalPages() }}</span> <button type=\"button\" role=\"menuitem\" class=\"ui-grid-pager-next\" ui-grid-one-bind-title=\"aria.pageForward\" ui-grid-one-bind-aria-label=\"aria.pageForward\" ng-click=\"pageNextPageClick()\" ng-disabled=\"cantPageForward()\"><div class=\"last-triangle next-triangle\"></div></button> <button type=\"button\" role=\"menuitem\" class=\"ui-grid-pager-last\" ui-grid-one-bind-title=\"aria.pageToLast\" ui-grid-one-bind-aria-label=\"aria.pageToLast\" ng-click=\"pageLastPageClick()\" ng-disabled=\"cantPageToLast()\"><div class=\"last-triangle\"><div class=\"last-bar\"></div></div></button></div><div class=\"ui-grid-pager-row-count-picker\" ng-if=\"grid.options.paginationPageSizes.length > 1\"><select ui-grid-one-bind-aria-labelledby-grid=\"'items-per-page-label'\" ng-model=\"grid.options.paginationPageSize\" ng-options=\"o as o for o in grid.options.paginationPageSizes\"></select><span ui-grid-one-bind-id-grid=\"'items-per-page-label'\" class=\"ui-grid-pager-row-count-label\">&nbsp;{{sizesLabel}}</span></div><span ng-if=\"grid.options.paginationPageSizes.length <= 1\" class=\"ui-grid-pager-row-count-label\">{{grid.options.paginationPageSize}}&nbsp;{{sizesLabel}}</span></div><div class=\"ui-grid-pager-count-container\"><div class=\"ui-grid-pager-count\"><span ng-show=\"grid.options.totalItems > 0\">{{showingLow}} <abbr ui-grid-one-bind-title=\"paginationThrough\">-</abbr> {{showingHigh}} {{paginationOf}} {{grid.options.totalItems}} {{totalItemsLabel}}</span></div></div></div>" ); $templateCache.put('ui-grid/columnResizer', "<div ui-grid-column-resizer ng-if=\"grid.options.enableColumnResizing\" class=\"ui-grid-column-resizer\" col=\"col\" position=\"right\" render-index=\"renderIndex\" unselectable=\"on\"></div>" ); $templateCache.put('ui-grid/gridFooterSelectedItems', "<span ng-if=\"grid.selection.selectedCount !== 0 && grid.options.enableFooterTotalSelected\">({{\"search.selectedItems\" | t}} {{grid.selection.selectedCount}})</span>" ); $templateCache.put('ui-grid/selectionHeaderCell', "<div><!-- <div class=\"ui-grid-vertical-bar\">&nbsp;</div> --><div class=\"ui-grid-cell-contents\" col-index=\"renderIndex\"><ui-grid-selection-select-all-buttons ng-if=\"grid.options.enableSelectAll\"></ui-grid-selection-select-all-buttons></div></div>" ); $templateCache.put('ui-grid/selectionRowHeader', "<div class=\"ui-grid-disable-selection\"><div class=\"ui-grid-cell-contents\"><ui-grid-selection-row-header-buttons></ui-grid-selection-row-header-buttons></div></div>" ); $templateCache.put('ui-grid/selectionRowHeaderButtons', "<div class=\"ui-grid-selection-row-header-buttons ui-grid-icon-ok\" ng-class=\"{'ui-grid-row-selected': row.isSelected}\" ng-click=\"selectButtonClick(row, $event)\">&nbsp;</div>" ); $templateCache.put('ui-grid/selectionSelectAllButtons', "<div class=\"ui-grid-selection-row-header-buttons ui-grid-icon-ok\" ng-class=\"{'ui-grid-all-selected': grid.selection.selectAll}\" ng-click=\"headerButtonClick($event)\"></div>" ); $templateCache.put('ui-grid/treeBaseExpandAllButtons', "<div class=\"ui-grid-tree-base-row-header-buttons\" ng-class=\"{'ui-grid-icon-minus-squared': grid.treeBase.numberLevels > 0 && grid.treeBase.expandAll, 'ui-grid-icon-plus-squared': grid.treeBase.numberLevels > 0 && !grid.treeBase.expandAll}\" ng-click=\"headerButtonClick($event)\"></div>" ); $templateCache.put('ui-grid/treeBaseHeaderCell', "<div><div class=\"ui-grid-cell-contents\" col-index=\"renderIndex\"><ui-grid-tree-base-expand-all-buttons></ui-grid-tree-base-expand-all-buttons></div></div>" ); $templateCache.put('ui-grid/treeBaseRowHeader', "<div class=\"ui-grid-cell-contents\"><ui-grid-tree-base-row-header-buttons></ui-grid-tree-base-row-header-buttons></div>" ); $templateCache.put('ui-grid/treeBaseRowHeaderButtons', "<div class=\"ui-grid-tree-base-row-header-buttons\" ng-class=\"{'ui-grid-tree-base-header': row.treeLevel > -1 }\" ng-click=\"treeButtonClick(row, $event)\"><i ng-class=\"{'ui-grid-icon-minus-squared': ( ( grid.options.showTreeExpandNoChildren && row.treeLevel > -1 ) || ( row.treeNode.children && row.treeNode.children.length > 0 ) ) && row.treeNode.state === 'expanded', 'ui-grid-icon-plus-squared': ( ( grid.options.showTreeExpandNoChildren && row.treeLevel > -1 ) || ( row.treeNode.children && row.treeNode.children.length > 0 ) ) && row.treeNode.state === 'collapsed'}\" ng-style=\"{'padding-left': grid.options.treeIndent * row.treeLevel + 'px'}\"></i> &nbsp;</div>" ); }]);
third_party/prometheus_ui/base/web/ui/node_modules/reactstrap/es/UncontrolledAlert.js
GoogleCloudPlatform/prometheus-engine
import _extends from "@babel/runtime/helpers/esm/extends"; import _assertThisInitialized from "@babel/runtime/helpers/esm/assertThisInitialized"; import _inheritsLoose from "@babel/runtime/helpers/esm/inheritsLoose"; import React, { Component } from 'react'; import Alert from './Alert'; var UncontrolledAlert = /*#__PURE__*/function (_Component) { _inheritsLoose(UncontrolledAlert, _Component); function UncontrolledAlert(props) { var _this; _this = _Component.call(this, props) || this; _this.state = { isOpen: true }; _this.toggle = _this.toggle.bind(_assertThisInitialized(_this)); return _this; } var _proto = UncontrolledAlert.prototype; _proto.toggle = function toggle() { this.setState({ isOpen: !this.state.isOpen }); }; _proto.render = function render() { return /*#__PURE__*/React.createElement(Alert, _extends({ isOpen: this.state.isOpen, toggle: this.toggle }, this.props)); }; return UncontrolledAlert; }(Component); export default UncontrolledAlert;
inventapp/src/App/App.js
ladanv/learn-react-js
import React, { Component } from 'react'; import Header from './Header'; import SideNav from './SideNav'; import styles from './App.scss'; const App = ({ children }) => ( <div className="App"> <Header /> <SideNav /> <div className={styles.main}> {children} </div> </div> ); export default App;
files/rxjs/2.4.3/rx.lite.extras.js
dnbard/jsdelivr
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. ;(function (factory) { var objectTypes = { 'boolean': false, 'function': true, 'object': true, 'number': false, 'string': false, 'undefined': false }; var root = (objectTypes[typeof window] && window) || this, freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, freeModule = objectTypes[typeof module] && module && !module.nodeType && module, moduleExports = freeModule && freeModule.exports === freeExports && freeExports, freeGlobal = objectTypes[typeof global] && global; if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { root = freeGlobal; } // Because of build optimizers if (typeof define === 'function' && define.amd) { define(['rx-lite'], function (Rx, exports) { return factory(root, exports, Rx); }); } else if (typeof module === 'object' && module && module.exports === freeExports) { module.exports = factory(root, module.exports, require('./rx-lite')); } else { root.Rx = factory(root, {}, root.Rx); } }.call(this, function (root, exp, Rx, undefined) { // References var Observable = Rx.Observable, observableProto = Observable.prototype, observableNever = Observable.never, observableThrow = Observable.throwException, AnonymousObservable = Rx.AnonymousObservable, AnonymousObserver = Rx.AnonymousObserver, notificationCreateOnNext = Rx.Notification.createOnNext, notificationCreateOnError = Rx.Notification.createOnError, notificationCreateOnCompleted = Rx.Notification.createOnCompleted, Observer = Rx.Observer, Subject = Rx.Subject, internals = Rx.internals, helpers = Rx.helpers, ScheduledObserver = internals.ScheduledObserver, SerialDisposable = Rx.SerialDisposable, SingleAssignmentDisposable = Rx.SingleAssignmentDisposable, CompositeDisposable = Rx.CompositeDisposable, RefCountDisposable = Rx.RefCountDisposable, disposableEmpty = Rx.Disposable.empty, immediateScheduler = Rx.Scheduler.immediate, defaultKeySerializer = helpers.defaultKeySerializer, addRef = Rx.internals.addRef, identity = helpers.identity, isPromise = helpers.isPromise, inherits = internals.inherits, bindCallback = internals.bindCallback, noop = helpers.noop, isScheduler = helpers.isScheduler, observableFromPromise = Observable.fromPromise, ArgumentOutOfRangeError = Rx.ArgumentOutOfRangeError; function ScheduledDisposable(scheduler, disposable) { this.scheduler = scheduler; this.disposable = disposable; this.isDisposed = false; } function scheduleItem(s, self) { if (!self.isDisposed) { self.isDisposed = true; self.disposable.dispose(); } } ScheduledDisposable.prototype.dispose = function () { this.scheduler.scheduleWithState(this, scheduleItem); }; var CheckedObserver = (function (__super__) { inherits(CheckedObserver, __super__); function CheckedObserver(observer) { __super__.call(this); this._observer = observer; this._state = 0; // 0 - idle, 1 - busy, 2 - done } var CheckedObserverPrototype = CheckedObserver.prototype; CheckedObserverPrototype.onNext = function (value) { this.checkAccess(); var res = tryCatch(this._observer.onNext).call(this._observer, value); this._state = 0; res === errorObj && thrower(res.e); }; CheckedObserverPrototype.onError = function (err) { this.checkAccess(); var res = tryCatch(this._observer.onError).call(this._observer, err); this._state = 2; res === errorObj && thrower(res.e); }; CheckedObserverPrototype.onCompleted = function () { this.checkAccess(); var res = tryCatch(this._observer.onCompleted).call(this._observer); this._state = 2; res === errorObj && thrower(res.e); }; CheckedObserverPrototype.checkAccess = function () { if (this._state === 1) { throw new Error('Re-entrancy detected'); } if (this._state === 2) { throw new Error('Observer completed'); } if (this._state === 0) { this._state = 1; } }; return CheckedObserver; }(Observer)); var ObserveOnObserver = (function (__super__) { inherits(ObserveOnObserver, __super__); function ObserveOnObserver(scheduler, observer, cancel) { __super__.call(this, scheduler, observer); this._cancel = cancel; } ObserveOnObserver.prototype.next = function (value) { __super__.prototype.next.call(this, value); this.ensureActive(); }; ObserveOnObserver.prototype.error = function (e) { __super__.prototype.error.call(this, e); this.ensureActive(); }; ObserveOnObserver.prototype.completed = function () { __super__.prototype.completed.call(this); this.ensureActive(); }; ObserveOnObserver.prototype.dispose = function () { __super__.prototype.dispose.call(this); this._cancel && this._cancel.dispose(); this._cancel = null; }; return ObserveOnObserver; })(ScheduledObserver); /** * 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); }; /** * 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); }; /** * Creates an observer from a notification callback. * @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) { var handlerFunc = bindCallback(handler, thisArg, 1); return new AnonymousObserver(function (x) { return handlerFunc(notificationCreateOnNext(x)); }, function (e) { return handlerFunc(notificationCreateOnError(e)); }, function () { return handlerFunc(notificationCreateOnCompleted()); }); }; /** * 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 () { var source = this; return new AnonymousObserver( function (x) { source.onNext(x); }, function (e) { source.onError(e); }, function () { source.onCompleted(); } ); }; /** * Wraps the source sequence in order to run its observer callbacks on the specified scheduler. * * This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects * that require to be run on a scheduler, use subscribeOn. * * @param {Scheduler} scheduler Scheduler to notify observers on. * @returns {Observable} The source sequence whose observations happen on the specified scheduler. */ observableProto.observeOn = function (scheduler) { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(new ObserveOnObserver(scheduler, observer)); }, source); }; /** * Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used; * see the remarks section for more information on the distinction between subscribeOn and observeOn. * This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer * callbacks on a scheduler, use observeOn. * @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on. * @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. */ observableProto.subscribeOn = function (scheduler) { var source = this; return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), d = new SerialDisposable(); d.setDisposable(m); m.setDisposable(scheduler.schedule(function () { d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(observer))); })); return d; }, source); }; /** * Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }); * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout); * @param {Mixed} initialState Initial state. * @param {Function} condition Condition to terminate generation (upon returning false). * @param {Function} iterate Iteration step function. * @param {Function} resultSelector Selector function for results produced in the sequence. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread. * @returns {Observable} The generated sequence. */ Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var first = true, state = initialState; return scheduler.scheduleRecursive(function (self) { var hasResult, result; try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); if (hasResult) { result = resultSelector(state); } } catch (exception) { observer.onError(exception); return; } if (hasResult) { observer.onNext(result); self(); } else { observer.onCompleted(); } }); }); }; /** * Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime. * @param {Function} resourceFactory Factory function to obtain a resource object. * @param {Function} observableFactory Factory function to obtain an observable sequence that depends on the obtained resource. * @returns {Observable} An observable sequence whose lifetime controls the lifetime of the dependent resource object. */ Observable.using = function (resourceFactory, observableFactory) { return new AnonymousObservable(function (observer) { var disposable = disposableEmpty, resource, source; try { resource = resourceFactory(); resource && (disposable = resource); source = observableFactory(resource); } catch (exception) { return new CompositeDisposable(observableThrow(exception).subscribe(observer), disposable); } return new CompositeDisposable(source.subscribe(observer), disposable); }); }; /** * Propagates the observable sequence or Promise that reacts first. * @param {Observable} rightSource Second observable sequence or Promise. * @returns {Observable} {Observable} An observable sequence that surfaces either of the given sequences, whichever reacted first. */ observableProto.amb = function (rightSource) { var leftSource = this; return new AnonymousObservable(function (observer) { var choice, leftChoice = 'L', rightChoice = 'R', leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable(); isPromise(rightSource) && (rightSource = observableFromPromise(rightSource)); function choiceL() { if (!choice) { choice = leftChoice; rightSubscription.dispose(); } } function choiceR() { if (!choice) { choice = rightChoice; leftSubscription.dispose(); } } leftSubscription.setDisposable(leftSource.subscribe(function (left) { choiceL(); if (choice === leftChoice) { observer.onNext(left); } }, function (err) { choiceL(); if (choice === leftChoice) { observer.onError(err); } }, function () { choiceL(); if (choice === leftChoice) { observer.onCompleted(); } })); rightSubscription.setDisposable(rightSource.subscribe(function (right) { choiceR(); if (choice === rightChoice) { observer.onNext(right); } }, function (err) { choiceR(); if (choice === rightChoice) { observer.onError(err); } }, function () { choiceR(); if (choice === rightChoice) { observer.onCompleted(); } })); return new CompositeDisposable(leftSubscription, rightSubscription); }); }; /** * Propagates the observable sequence or Promise that reacts first. * * @example * var = Rx.Observable.amb(xs, ys, zs); * @returns {Observable} An observable sequence that surfaces any of the given sequences, whichever reacted first. */ Observable.amb = function () { var acc = observableNever(), items = []; if (Array.isArray(arguments[0])) { items = arguments[0]; } else { for(var i = 0, len = arguments.length; i < len; i++) { items.push(arguments[i]); } } function func(previous, current) { return previous.amb(current); } for (var i = 0, len = items.length; i < len; i++) { acc = func(acc, items[i]); } return acc; }; /** * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. * @param {Observable} second Second observable sequence used to produce results after the first sequence terminates. * @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally. */ observableProto.onErrorResumeNext = function (second) { if (!second) { throw new Error('Second observable is required'); } return onErrorResumeNext([this, second]); }; /** * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. * * @example * 1 - res = Rx.Observable.onErrorResumeNext(xs, ys, zs); * 1 - res = Rx.Observable.onErrorResumeNext([xs, ys, zs]); * @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally. */ var onErrorResumeNext = Observable.onErrorResumeNext = function () { var sources = []; if (Array.isArray(arguments[0])) { sources = arguments[0]; } else { for(var i = 0, len = arguments.length; i < len; i++) { sources.push(arguments[i]); } } return new AnonymousObservable(function (observer) { var pos = 0, subscription = new SerialDisposable(), cancelable = immediateScheduler.scheduleRecursive(function (self) { var current, d; if (pos < sources.length) { current = sources[pos++]; isPromise(current) && (current = observableFromPromise(current)); d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(current.subscribe(observer.onNext.bind(observer), self, self)); } else { observer.onCompleted(); } }); return new CompositeDisposable(subscription, cancelable); }); }; /** * Projects each element of an observable sequence into zero or more buffers which are produced based on element count information. * * @example * var res = xs.bufferWithCount(10); * var res = xs.bufferWithCount(10, 1); * @param {Number} count Length of each buffer. * @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count. * @returns {Observable} An observable sequence of buffers. */ observableProto.bufferWithCount = function (count, skip) { if (typeof skip !== 'number') { skip = count; } return this.windowWithCount(count, skip).selectMany(function (x) { return x.toArray(); }).where(function (x) { return x.length > 0; }); }; /** * Projects each element of an observable sequence into zero or more windows which are produced based on element count information. * * var res = xs.windowWithCount(10); * var res = xs.windowWithCount(10, 1); * @param {Number} count Length of each window. * @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count. * @returns {Observable} An observable sequence of windows. */ observableProto.windowWithCount = function (count, skip) { var source = this; +count || (count = 0); Math.abs(count) === Infinity && (count = 0); if (count <= 0) { throw new ArgumentOutOfRangeError(); } skip == null && (skip = count); +skip || (skip = 0); Math.abs(skip) === Infinity && (skip = 0); if (skip <= 0) { throw new ArgumentOutOfRangeError(); } return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), refCountDisposable = new RefCountDisposable(m), n = 0, q = []; function createWindow () { var s = new Subject(); q.push(s); observer.onNext(addRef(s, refCountDisposable)); } createWindow(); m.setDisposable(source.subscribe( function (x) { for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); } var c = n - count + 1; c >= 0 && c % skip === 0 && q.shift().onCompleted(); ++n % skip === 0 && createWindow(); }, function (e) { while (q.length > 0) { q.shift().onError(e); } observer.onError(e); }, function () { while (q.length > 0) { q.shift().onCompleted(); } observer.onCompleted(); } )); return refCountDisposable; }, source); }; /** * Returns an array with the specified number of contiguous elements from the end of an observable sequence. * * @description * This operator accumulates a buffer with a length enough to store count elements. Upon completion of the * source sequence, this buffer is produced on the result sequence. * @param {Number} count Number of elements to take from the end of the source sequence. * @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence. */ observableProto.takeLastBuffer = function (count) { var source = this; return new AnonymousObservable(function (o) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && q.shift(); }, function (e) { o.onError(e); }, function () { o.onNext(q); o.onCompleted(); }); }, source); }; /** * Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty. * * var res = obs = xs.defaultIfEmpty(); * 2 - obs = xs.defaultIfEmpty(false); * * @memberOf Observable# * @param defaultValue The value to return if the sequence is empty. If not provided, this defaults to null. * @returns {Observable} An observable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself. */ observableProto.defaultIfEmpty = function (defaultValue) { var source = this; defaultValue === undefined && (defaultValue = null); return new AnonymousObservable(function (observer) { var found = false; return source.subscribe(function (x) { found = true; observer.onNext(x); }, function (e) { observer.onError(e); }, function () { !found && observer.onNext(defaultValue); observer.onCompleted(); }); }, source); }; // Swap out for Array.findIndex function arrayIndexOfComparer(array, item, comparer) { for (var i = 0, len = array.length; i < len; i++) { if (comparer(array[i], item)) { return i; } } return -1; } function HashSet(comparer) { this.comparer = comparer; this.set = []; } HashSet.prototype.push = function(value) { var retValue = arrayIndexOfComparer(this.set, value, this.comparer) === -1; retValue && this.set.push(value); return retValue; }; /** * Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer. * Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large. * * @example * var res = obs = xs.distinct(); * 2 - obs = xs.distinct(function (x) { return x.id; }); * 2 - obs = xs.distinct(function (x) { return x.id; }, function (a,b) { return a === b; }); * @param {Function} [keySelector] A function to compute the comparison key for each element. * @param {Function} [comparer] Used to compare items in the collection. * @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence. */ observableProto.distinct = function (keySelector, comparer) { var source = this; comparer || (comparer = defaultComparer); return new AnonymousObservable(function (o) { var hashSet = new HashSet(comparer); return source.subscribe(function (x) { var key = x; if (keySelector) { try { key = keySelector(x); } catch (e) { o.onError(e); return; } } hashSet.push(key) && o.onNext(x); }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, this); }; return Rx; }));
src/components/Slider.js
niekert/soundify
import React from 'react'; import PropTypes from 'prop-types'; import styled, { css } from 'styled-components'; import { lighten, alpha } from 'utils/color'; import { compose, withState, withHandlers } from 'recompose'; import { prop, ifProp } from 'styled-tools'; const Bar = styled.div` flex: 1; position: relative; `; const seekLine = css` -webkit-appearance: none; position: absolute; background: none; width: 100%; margin: 0; `; const Seek = styled.input` ${seekLine}; top: -10px; height: 20px; &::-webkit-slider-runnable-track { -webkit-appearance: none; } &::-webkit-slider-thumb { -webkit-appearance: none; pointer-events: none; opacity: ${ifProp('highlight', 1, 0)}; z-index: 30; width: 10px; height: 10px; top: -1px; background: ${prop('theme.colors.primaryText')}; border-radius: 50%; position: relative; } `; const Progress = styled.progress` ${seekLine} top: -3px; pointer-events: none; height: 4px; z-index: 20; &::-webkit-progress-value { -webkit-appearance: none; background: ${props => props.active ? props.theme.colors.active : alpha(props.theme.colors.primaryText, 0.7)}; height: 4px; border-radius: 6px; z-index: 50; } &::-webkit-progress-bar { border-radius: 6px; background: ${props => lighten(props.theme.colors.secondaryActive, 0.3)}; border-radius: 5px; height: 4px; } `; const enhance = compose( withState('hoverActive', 'setHoverState', false), withHandlers({ mouseEnter: ({ setHoverState }) => () => setHoverState(true), mouseLeave: ({ setHoverState }) => () => setHoverState(false), }), ); const Slider = enhance( ({ onChange, percentage = 0, hoverActive, mouseEnter, mouseLeave }) => <Bar> <Seek onMouseEnter={mouseEnter} onMouseLeave={mouseLeave} highlight={hoverActive} type="range" value={percentage} onChange={onChange} /> <Progress value={percentage} max={100} active={hoverActive} /> </Bar>, ); Slider.propTypes = { onChange: PropTypes.func.isRequired, percentage: PropTypes.number, }; export default Slider;
front/src/index.js
ajparedes10/parcial1-web
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; ReactDOM.render(<App />, document.getElementById('root'));
ajax/libs/yui/3.10.0/event-focus/event-focus-coverage.js
CarlosOhh/cdnjs
if (typeof __coverage__ === 'undefined') { __coverage__ = {}; } if (!__coverage__['build/event-focus/event-focus.js']) { __coverage__['build/event-focus/event-focus.js'] = {"path":"build/event-focus/event-focus.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},"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]},"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},"fnMap":{"1":{"name":"(anonymous_1)","line":1,"loc":{"start":{"line":1,"column":23},"end":{"line":1,"column":42}}},"2":{"name":"(anonymous_2)","line":17,"loc":{"start":{"line":17,"column":19},"end":{"line":17,"column":30}}},"3":{"name":"define","line":45,"loc":{"start":{"line":45,"column":0},"end":{"line":45,"column":42}}},"4":{"name":"(anonymous_4)","line":52,"loc":{"start":{"line":52,"column":17},"end":{"line":52,"column":51}}},"5":{"name":"(anonymous_5)","line":54,"loc":{"start":{"line":54,"column":44},"end":{"line":54,"column":57}}},"6":{"name":"(anonymous_6)","line":64,"loc":{"start":{"line":64,"column":16},"end":{"line":64,"column":49}}},"7":{"name":"(anonymous_7)","line":113,"loc":{"start":{"line":113,"column":17},"end":{"line":113,"column":41}}},"8":{"name":"(anonymous_8)","line":143,"loc":{"start":{"line":143,"column":31},"end":{"line":143,"column":47}}},"9":{"name":"(anonymous_9)","line":231,"loc":{"start":{"line":231,"column":12},"end":{"line":231,"column":43}}},"10":{"name":"(anonymous_10)","line":235,"loc":{"start":{"line":235,"column":16},"end":{"line":235,"column":37}}},"11":{"name":"(anonymous_11)","line":239,"loc":{"start":{"line":239,"column":18},"end":{"line":239,"column":57}}},"12":{"name":"(anonymous_12)","line":241,"loc":{"start":{"line":241,"column":29},"end":{"line":241,"column":47}}},"13":{"name":"(anonymous_13)","line":250,"loc":{"start":{"line":250,"column":24},"end":{"line":250,"column":45}}}},"statementMap":{"1":{"start":{"line":1,"column":0},"end":{"line":273,"column":51}},"2":{"start":{"line":9,"column":0},"end":{"line":43,"column":9}},"3":{"start":{"line":23,"column":8},"end":{"line":25,"column":14}},"4":{"start":{"line":27,"column":8},"end":{"line":40,"column":9}},"5":{"start":{"line":29,"column":12},"end":{"line":29,"column":39}},"6":{"start":{"line":30,"column":12},"end":{"line":30,"column":52}},"7":{"start":{"line":39,"column":12},"end":{"line":39,"column":59}},"8":{"start":{"line":42,"column":8},"end":{"line":42,"column":25}},"9":{"start":{"line":45,"column":0},"end":{"line":254,"column":1}},"10":{"start":{"line":46,"column":4},"end":{"line":46,"column":47}},"11":{"start":{"line":48,"column":4},"end":{"line":253,"column":13}},"12":{"start":{"line":53,"column":12},"end":{"line":61,"column":13}},"13":{"start":{"line":54,"column":16},"end":{"line":56,"column":24}},"14":{"start":{"line":55,"column":20},"end":{"line":55,"column":37}},"15":{"start":{"line":58,"column":16},"end":{"line":60,"column":39}},"16":{"start":{"line":65,"column":12},"end":{"line":70,"column":26}},"17":{"start":{"line":72,"column":12},"end":{"line":72,"column":73}},"18":{"start":{"line":73,"column":12},"end":{"line":73,"column":71}},"19":{"start":{"line":79,"column":12},"end":{"line":100,"column":13}},"20":{"start":{"line":80,"column":16},"end":{"line":80,"column":31}},"21":{"start":{"line":81,"column":16},"end":{"line":81,"column":55}},"22":{"start":{"line":85,"column":16},"end":{"line":89,"column":17}},"23":{"start":{"line":86,"column":20},"end":{"line":87,"column":71}},"24":{"start":{"line":88,"column":20},"end":{"line":88,"column":42}},"25":{"start":{"line":99,"column":16},"end":{"line":99,"column":29}},"26":{"start":{"line":102,"column":12},"end":{"line":104,"column":13}},"27":{"start":{"line":103,"column":16},"end":{"line":103,"column":37}},"28":{"start":{"line":106,"column":12},"end":{"line":106,"column":43}},"29":{"start":{"line":108,"column":12},"end":{"line":110,"column":13}},"30":{"start":{"line":109,"column":16},"end":{"line":109,"column":32}},"31":{"start":{"line":114,"column":12},"end":{"line":124,"column":80}},"32":{"start":{"line":127,"column":12},"end":{"line":127,"column":49}},"33":{"start":{"line":130,"column":12},"end":{"line":130,"column":42}},"34":{"start":{"line":133,"column":12},"end":{"line":135,"column":13}},"35":{"start":{"line":134,"column":16},"end":{"line":134,"column":39}},"36":{"start":{"line":138,"column":12},"end":{"line":138,"column":39}},"37":{"start":{"line":140,"column":12},"end":{"line":160,"column":13}},"38":{"start":{"line":142,"column":16},"end":{"line":142,"column":28}},"39":{"start":{"line":143,"column":16},"end":{"line":158,"column":19}},"40":{"start":{"line":144,"column":20},"end":{"line":146,"column":31}},"41":{"start":{"line":148,"column":20},"end":{"line":155,"column":21}},"42":{"start":{"line":149,"column":24},"end":{"line":149,"column":32}},"43":{"start":{"line":150,"column":24},"end":{"line":154,"column":25}},"44":{"start":{"line":151,"column":28},"end":{"line":153,"column":29}},"45":{"start":{"line":152,"column":32},"end":{"line":152,"column":61}},"46":{"start":{"line":157,"column":20},"end":{"line":157,"column":34}},"47":{"start":{"line":159,"column":16},"end":{"line":159,"column":28}},"48":{"start":{"line":164,"column":12},"end":{"line":228,"column":13}},"49":{"start":{"line":165,"column":16},"end":{"line":165,"column":39}},"50":{"start":{"line":167,"column":16},"end":{"line":167,"column":47}},"51":{"start":{"line":169,"column":16},"end":{"line":201,"column":17}},"52":{"start":{"line":170,"column":20},"end":{"line":197,"column":21}},"53":{"start":{"line":171,"column":24},"end":{"line":171,"column":48}},"54":{"start":{"line":172,"column":24},"end":{"line":172,"column":55}},"55":{"start":{"line":173,"column":24},"end":{"line":173,"column":40}},"56":{"start":{"line":175,"column":24},"end":{"line":175,"column":49}},"57":{"start":{"line":177,"column":24},"end":{"line":186,"column":25}},"58":{"start":{"line":178,"column":28},"end":{"line":179,"column":68}},"59":{"start":{"line":184,"column":28},"end":{"line":185,"column":68}},"60":{"start":{"line":188,"column":24},"end":{"line":192,"column":25}},"61":{"start":{"line":190,"column":28},"end":{"line":190,"column":61}},"62":{"start":{"line":191,"column":28},"end":{"line":191,"column":51}},"63":{"start":{"line":194,"column":24},"end":{"line":196,"column":25}},"64":{"start":{"line":195,"column":28},"end":{"line":195,"column":34}},"65":{"start":{"line":199,"column":20},"end":{"line":199,"column":43}},"66":{"start":{"line":200,"column":20},"end":{"line":200,"column":28}},"67":{"start":{"line":203,"column":16},"end":{"line":223,"column":17}},"68":{"start":{"line":207,"column":20},"end":{"line":222,"column":21}},"69":{"start":{"line":208,"column":24},"end":{"line":208,"column":48}},"70":{"start":{"line":209,"column":24},"end":{"line":209,"column":50}},"71":{"start":{"line":211,"column":24},"end":{"line":217,"column":25}},"72":{"start":{"line":214,"column":28},"end":{"line":214,"column":61}},"73":{"start":{"line":215,"column":28},"end":{"line":215,"column":53}},"74":{"start":{"line":216,"column":28},"end":{"line":216,"column":51}},"75":{"start":{"line":219,"column":24},"end":{"line":221,"column":25}},"76":{"start":{"line":220,"column":28},"end":{"line":220,"column":34}},"77":{"start":{"line":225,"column":16},"end":{"line":227,"column":17}},"78":{"start":{"line":226,"column":20},"end":{"line":226,"column":26}},"79":{"start":{"line":232,"column":12},"end":{"line":232,"column":60}},"80":{"start":{"line":236,"column":12},"end":{"line":236,"column":32}},"81":{"start":{"line":240,"column":12},"end":{"line":245,"column":13}},"82":{"start":{"line":241,"column":16},"end":{"line":244,"column":18}},"83":{"start":{"line":242,"column":20},"end":{"line":243,"column":61}},"84":{"start":{"line":247,"column":12},"end":{"line":247,"column":66}},"85":{"start":{"line":251,"column":12},"end":{"line":251,"column":32}},"86":{"start":{"line":263,"column":0},"end":{"line":270,"column":1}},"87":{"start":{"line":265,"column":4},"end":{"line":265,"column":51}},"88":{"start":{"line":266,"column":4},"end":{"line":266,"column":52}},"89":{"start":{"line":268,"column":4},"end":{"line":268,"column":38}},"90":{"start":{"line":269,"column":4},"end":{"line":269,"column":37}}},"branchMap":{"1":{"line":27,"type":"if","locations":[{"start":{"line":27,"column":8},"end":{"line":27,"column":8}},{"start":{"line":27,"column":8},"end":{"line":27,"column":8}}]},"2":{"line":53,"type":"if","locations":[{"start":{"line":53,"column":12},"end":{"line":53,"column":12}},{"start":{"line":53,"column":12},"end":{"line":53,"column":12}}]},"3":{"line":69,"type":"binary-expr","locations":[{"start":{"line":69,"column":33},"end":{"line":69,"column":44}},{"start":{"line":69,"column":48},"end":{"line":69,"column":72}}]},"4":{"line":72,"type":"cond-expr","locations":[{"start":{"line":72,"column":50},"end":{"line":72,"column":56}},{"start":{"line":72,"column":59},"end":{"line":72,"column":72}}]},"5":{"line":73,"type":"cond-expr","locations":[{"start":{"line":73,"column":50},"end":{"line":73,"column":63}},{"start":{"line":73,"column":66},"end":{"line":73,"column":70}}]},"6":{"line":79,"type":"if","locations":[{"start":{"line":79,"column":12},"end":{"line":79,"column":12}},{"start":{"line":79,"column":12},"end":{"line":79,"column":12}}]},"7":{"line":85,"type":"if","locations":[{"start":{"line":85,"column":16},"end":{"line":85,"column":16}},{"start":{"line":85,"column":16},"end":{"line":85,"column":16}}]},"8":{"line":102,"type":"if","locations":[{"start":{"line":102,"column":12},"end":{"line":102,"column":12}},{"start":{"line":102,"column":12},"end":{"line":102,"column":12}}]},"9":{"line":108,"type":"if","locations":[{"start":{"line":108,"column":12},"end":{"line":108,"column":12}},{"start":{"line":108,"column":12},"end":{"line":108,"column":12}}]},"10":{"line":121,"type":"cond-expr","locations":[{"start":{"line":122,"column":36},"end":{"line":122,"column":70}},{"start":{"line":123,"column":36},"end":{"line":123,"column":37}}]},"11":{"line":133,"type":"if","locations":[{"start":{"line":133,"column":12},"end":{"line":133,"column":12}},{"start":{"line":133,"column":12},"end":{"line":133,"column":12}}]},"12":{"line":140,"type":"if","locations":[{"start":{"line":140,"column":12},"end":{"line":140,"column":12}},{"start":{"line":140,"column":12},"end":{"line":140,"column":12}}]},"13":{"line":148,"type":"if","locations":[{"start":{"line":148,"column":20},"end":{"line":148,"column":20}},{"start":{"line":148,"column":20},"end":{"line":148,"column":20}}]},"14":{"line":151,"type":"if","locations":[{"start":{"line":151,"column":28},"end":{"line":151,"column":28}},{"start":{"line":151,"column":28},"end":{"line":151,"column":28}}]},"15":{"line":164,"type":"binary-expr","locations":[{"start":{"line":164,"column":19},"end":{"line":164,"column":24}},{"start":{"line":164,"column":29},"end":{"line":164,"column":55}}]},"16":{"line":169,"type":"if","locations":[{"start":{"line":169,"column":16},"end":{"line":169,"column":16}},{"start":{"line":169,"column":16},"end":{"line":169,"column":16}}]},"17":{"line":177,"type":"if","locations":[{"start":{"line":177,"column":24},"end":{"line":177,"column":24}},{"start":{"line":177,"column":24},"end":{"line":177,"column":24}}]},"18":{"line":179,"type":"binary-expr","locations":[{"start":{"line":179,"column":51},"end":{"line":179,"column":59}},{"start":{"line":179,"column":63},"end":{"line":179,"column":65}}]},"19":{"line":188,"type":"if","locations":[{"start":{"line":188,"column":24},"end":{"line":188,"column":24}},{"start":{"line":188,"column":24},"end":{"line":188,"column":24}}]},"20":{"line":194,"type":"if","locations":[{"start":{"line":194,"column":24},"end":{"line":194,"column":24}},{"start":{"line":194,"column":24},"end":{"line":194,"column":24}}]},"21":{"line":194,"type":"binary-expr","locations":[{"start":{"line":194,"column":28},"end":{"line":194,"column":41}},{"start":{"line":194,"column":45},"end":{"line":194,"column":60}}]},"22":{"line":203,"type":"if","locations":[{"start":{"line":203,"column":16},"end":{"line":203,"column":16}},{"start":{"line":203,"column":16},"end":{"line":203,"column":16}}]},"23":{"line":211,"type":"if","locations":[{"start":{"line":211,"column":24},"end":{"line":211,"column":24}},{"start":{"line":211,"column":24},"end":{"line":211,"column":24}}]},"24":{"line":212,"type":"binary-expr","locations":[{"start":{"line":212,"column":47},"end":{"line":212,"column":55}},{"start":{"line":212,"column":59},"end":{"line":212,"column":61}}]},"25":{"line":219,"type":"if","locations":[{"start":{"line":219,"column":24},"end":{"line":219,"column":24}},{"start":{"line":219,"column":24},"end":{"line":219,"column":24}}]},"26":{"line":219,"type":"binary-expr","locations":[{"start":{"line":219,"column":28},"end":{"line":219,"column":41}},{"start":{"line":219,"column":45},"end":{"line":219,"column":60}}]},"27":{"line":225,"type":"if","locations":[{"start":{"line":225,"column":16},"end":{"line":225,"column":16}},{"start":{"line":225,"column":16},"end":{"line":225,"column":16}}]},"28":{"line":240,"type":"if","locations":[{"start":{"line":240,"column":12},"end":{"line":240,"column":12}},{"start":{"line":240,"column":12},"end":{"line":240,"column":12}}]},"29":{"line":243,"type":"cond-expr","locations":[{"start":{"line":243,"column":42},"end":{"line":243,"column":46}},{"start":{"line":243,"column":49},"end":{"line":243,"column":59}}]},"30":{"line":263,"type":"if","locations":[{"start":{"line":263,"column":0},"end":{"line":263,"column":0}},{"start":{"line":263,"column":0},"end":{"line":263,"column":0}}]}},"code":["(function () { YUI.add('event-focus', function (Y, NAME) {","","/**"," * Adds bubbling and delegation support to DOM events focus and blur."," * "," * @module event"," * @submodule event-focus"," */","var Event = Y.Event,",""," YLang = Y.Lang,",""," isString = YLang.isString,",""," arrayIndex = Y.Array.indexOf,",""," useActivate = (function() {",""," // Changing the structure of this test, so that it doesn't use inline JS in HTML,"," // which throws an exception in Win8 packaged apps, due to additional security restrictions:"," // http://msdn.microsoft.com/en-us/library/windows/apps/hh465380.aspx#differences",""," var supported = false,"," doc = Y.config.doc,"," p;",""," if (doc) {",""," p = doc.createElement(\"p\");"," p.setAttribute(\"onbeforeactivate\", \";\");",""," // onbeforeactivate is a function in IE8+."," // onbeforeactivate is a string in IE6,7 (unfortunate, otherwise we could have just checked for function below)."," // onbeforeactivate is a function in IE10, in a Win8 App environment (no exception running the test).",""," // onbeforeactivate is undefined in Webkit/Gecko."," // onbeforeactivate is a function in Webkit/Gecko if it's a supported event (e.g. onclick).",""," supported = (p.onbeforeactivate !== undefined);"," }",""," return supported;"," }());","","function define(type, proxy, directEvent) {"," var nodeDataKey = '_' + type + 'Notifiers';",""," Y.Event.define(type, {",""," _useActivate : useActivate,",""," _attach: function (el, notifier, delegate) {"," if (Y.DOM.isWindow(el)) {"," return Event._attach([type, function (e) {"," notifier.fire(e);"," }, el]);"," } else {"," return Event._attach("," [proxy, this._proxy, el, this, notifier, delegate],"," { capture: true });"," }"," },",""," _proxy: function (e, notifier, delegate) {"," var target = e.target,"," currentTarget = e.currentTarget,"," notifiers = target.getData(nodeDataKey),"," yuid = Y.stamp(currentTarget._node),"," defer = (useActivate || target !== currentTarget),"," directSub;"," "," notifier.currentTarget = (delegate) ? target : currentTarget;"," notifier.container = (delegate) ? currentTarget : null;",""," // Maintain a list to handle subscriptions from nested"," // containers div#a>div#b>input #a.on(focus..) #b.on(focus..),"," // use one focus or blur subscription that fires notifiers from"," // #b then #a to emulate bubble sequence."," if (!notifiers) {"," notifiers = {};"," target.setData(nodeDataKey, notifiers);",""," // only subscribe to the element's focus if the target is"," // not the current target ("," if (defer) {"," directSub = Event._attach("," [directEvent, this._notify, target._node]).sub;"," directSub.once = true;"," }"," } else {"," // In old IE, defer is always true. In capture-phase browsers,"," // The delegate subscriptions will be encountered first, which"," // will establish the notifiers data and direct subscription"," // on the node. If there is also a direct subscription to the"," // node's focus/blur, it should not call _notify because the"," // direct subscription from the delegate sub(s) exists, which"," // will call _notify. So this avoids _notify being called"," // twice, unnecessarily."," defer = true;"," }",""," if (!notifiers[yuid]) {"," notifiers[yuid] = [];"," }",""," notifiers[yuid].push(notifier);",""," if (!defer) {"," this._notify(e);"," }"," },",""," _notify: function (e, container) {"," var currentTarget = e.currentTarget,"," notifierData = currentTarget.getData(nodeDataKey),"," axisNodes = currentTarget.ancestors(),"," doc = currentTarget.get('ownerDocument'),"," delegates = [],"," // Used to escape loops when there are no more"," // notifiers to consider"," count = notifierData ?"," Y.Object.keys(notifierData).length :"," 0,"," target, notifiers, notifier, yuid, match, tmp, i, len, sub, ret;",""," // clear the notifications list (mainly for delegation)"," currentTarget.clearData(nodeDataKey);",""," // Order the delegate subs by their placement in the parent axis"," axisNodes.push(currentTarget);"," // document.get('ownerDocument') returns null"," // which we'll use to prevent having duplicate Nodes in the list"," if (doc) {"," axisNodes.unshift(doc);"," }",""," // ancestors() returns the Nodes from top to bottom"," axisNodes._nodes.reverse();",""," if (count) {"," // Store the count for step 2"," tmp = count;"," axisNodes.some(function (node) {"," var yuid = Y.stamp(node),"," notifiers = notifierData[yuid],"," i, len;",""," if (notifiers) {"," count--;"," for (i = 0, len = notifiers.length; i < len; ++i) {"," if (notifiers[i].handle.sub.filter) {"," delegates.push(notifiers[i]);"," }"," }"," }",""," return !count;"," });"," count = tmp;"," }",""," // Walk up the parent axis, notifying direct subscriptions and"," // testing delegate filters."," while (count && (target = axisNodes.shift())) {"," yuid = Y.stamp(target);",""," notifiers = notifierData[yuid];",""," if (notifiers) {"," for (i = 0, len = notifiers.length; i < len; ++i) {"," notifier = notifiers[i];"," sub = notifier.handle.sub;"," match = true;",""," e.currentTarget = target;",""," if (sub.filter) {"," match = sub.filter.apply(target,"," [target, e].concat(sub.args || []));",""," // No longer necessary to test against this"," // delegate subscription for the nodes along"," // the parent axis."," delegates.splice("," arrayIndex(delegates, notifier), 1);"," }",""," if (match) {"," // undefined for direct subs"," e.container = notifier.container;"," ret = notifier.fire(e);"," }",""," if (ret === false || e.stopped === 2) {"," break;"," }"," }"," "," delete notifiers[yuid];"," count--;"," }",""," if (e.stopped !== 2) {"," // delegates come after subs targeting this specific node"," // because they would not normally report until they'd"," // bubbled to the container node."," for (i = 0, len = delegates.length; i < len; ++i) {"," notifier = delegates[i];"," sub = notifier.handle.sub;",""," if (sub.filter.apply(target,"," [target, e].concat(sub.args || []))) {",""," e.container = notifier.container;"," e.currentTarget = target;"," ret = notifier.fire(e);"," }",""," if (ret === false || e.stopped === 2) {"," break;"," }"," }"," }",""," if (e.stopped) {"," break;"," }"," }"," },",""," on: function (node, sub, notifier) {"," sub.handle = this._attach(node._node, notifier);"," },",""," detach: function (node, sub) {"," sub.handle.detach();"," },",""," delegate: function (node, sub, notifier, filter) {"," if (isString(filter)) {"," sub.filter = function (target) {"," return Y.Selector.test(target._node, filter,"," node === target ? null : node._node);"," };"," }",""," sub.handle = this._attach(node._node, notifier, true);"," },",""," detachDelegate: function (node, sub) {"," sub.handle.detach();"," }"," }, true);","}","","// For IE, we need to defer to focusin rather than focus because","// `el.focus(); doSomething();` executes el.onbeforeactivate, el.onactivate,","// el.onfocusin, doSomething, then el.onfocus. All others support capture","// phase focus, which executes before doSomething. To guarantee consistent","// behavior for this use case, IE's direct subscriptions are made against","// focusin so subscribers will be notified before js following el.focus() is","// executed.","if (useActivate) {"," // name capture phase direct subscription"," define(\"focus\", \"beforeactivate\", \"focusin\");"," define(\"blur\", \"beforedeactivate\", \"focusout\");","} else {"," define(\"focus\", \"focus\", \"focus\");"," define(\"blur\", \"blur\", \"blur\");","}","","","}, '@VERSION@', {\"requires\": [\"event-synthetic\"]});","","}());"]}; } var __cov_6QPN5D0gRV5cd0sDuZmrgw = __coverage__['build/event-focus/event-focus.js']; __cov_6QPN5D0gRV5cd0sDuZmrgw.s['1']++;YUI.add('event-focus',function(Y,NAME){__cov_6QPN5D0gRV5cd0sDuZmrgw.f['1']++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['2']++;var Event=Y.Event,YLang=Y.Lang,isString=YLang.isString,arrayIndex=Y.Array.indexOf,useActivate=function(){__cov_6QPN5D0gRV5cd0sDuZmrgw.f['2']++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['3']++;var supported=false,doc=Y.config.doc,p;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['4']++;if(doc){__cov_6QPN5D0gRV5cd0sDuZmrgw.b['1'][0]++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['5']++;p=doc.createElement('p');__cov_6QPN5D0gRV5cd0sDuZmrgw.s['6']++;p.setAttribute('onbeforeactivate',';');__cov_6QPN5D0gRV5cd0sDuZmrgw.s['7']++;supported=p.onbeforeactivate!==undefined;}else{__cov_6QPN5D0gRV5cd0sDuZmrgw.b['1'][1]++;}__cov_6QPN5D0gRV5cd0sDuZmrgw.s['8']++;return supported;}();__cov_6QPN5D0gRV5cd0sDuZmrgw.s['9']++;function define(type,proxy,directEvent){__cov_6QPN5D0gRV5cd0sDuZmrgw.f['3']++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['10']++;var nodeDataKey='_'+type+'Notifiers';__cov_6QPN5D0gRV5cd0sDuZmrgw.s['11']++;Y.Event.define(type,{_useActivate:useActivate,_attach:function(el,notifier,delegate){__cov_6QPN5D0gRV5cd0sDuZmrgw.f['4']++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['12']++;if(Y.DOM.isWindow(el)){__cov_6QPN5D0gRV5cd0sDuZmrgw.b['2'][0]++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['13']++;return Event._attach([type,function(e){__cov_6QPN5D0gRV5cd0sDuZmrgw.f['5']++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['14']++;notifier.fire(e);},el]);}else{__cov_6QPN5D0gRV5cd0sDuZmrgw.b['2'][1]++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['15']++;return Event._attach([proxy,this._proxy,el,this,notifier,delegate],{capture:true});}},_proxy:function(e,notifier,delegate){__cov_6QPN5D0gRV5cd0sDuZmrgw.f['6']++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['16']++;var target=e.target,currentTarget=e.currentTarget,notifiers=target.getData(nodeDataKey),yuid=Y.stamp(currentTarget._node),defer=(__cov_6QPN5D0gRV5cd0sDuZmrgw.b['3'][0]++,useActivate)||(__cov_6QPN5D0gRV5cd0sDuZmrgw.b['3'][1]++,target!==currentTarget),directSub;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['17']++;notifier.currentTarget=delegate?(__cov_6QPN5D0gRV5cd0sDuZmrgw.b['4'][0]++,target):(__cov_6QPN5D0gRV5cd0sDuZmrgw.b['4'][1]++,currentTarget);__cov_6QPN5D0gRV5cd0sDuZmrgw.s['18']++;notifier.container=delegate?(__cov_6QPN5D0gRV5cd0sDuZmrgw.b['5'][0]++,currentTarget):(__cov_6QPN5D0gRV5cd0sDuZmrgw.b['5'][1]++,null);__cov_6QPN5D0gRV5cd0sDuZmrgw.s['19']++;if(!notifiers){__cov_6QPN5D0gRV5cd0sDuZmrgw.b['6'][0]++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['20']++;notifiers={};__cov_6QPN5D0gRV5cd0sDuZmrgw.s['21']++;target.setData(nodeDataKey,notifiers);__cov_6QPN5D0gRV5cd0sDuZmrgw.s['22']++;if(defer){__cov_6QPN5D0gRV5cd0sDuZmrgw.b['7'][0]++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['23']++;directSub=Event._attach([directEvent,this._notify,target._node]).sub;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['24']++;directSub.once=true;}else{__cov_6QPN5D0gRV5cd0sDuZmrgw.b['7'][1]++;}}else{__cov_6QPN5D0gRV5cd0sDuZmrgw.b['6'][1]++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['25']++;defer=true;}__cov_6QPN5D0gRV5cd0sDuZmrgw.s['26']++;if(!notifiers[yuid]){__cov_6QPN5D0gRV5cd0sDuZmrgw.b['8'][0]++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['27']++;notifiers[yuid]=[];}else{__cov_6QPN5D0gRV5cd0sDuZmrgw.b['8'][1]++;}__cov_6QPN5D0gRV5cd0sDuZmrgw.s['28']++;notifiers[yuid].push(notifier);__cov_6QPN5D0gRV5cd0sDuZmrgw.s['29']++;if(!defer){__cov_6QPN5D0gRV5cd0sDuZmrgw.b['9'][0]++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['30']++;this._notify(e);}else{__cov_6QPN5D0gRV5cd0sDuZmrgw.b['9'][1]++;}},_notify:function(e,container){__cov_6QPN5D0gRV5cd0sDuZmrgw.f['7']++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['31']++;var currentTarget=e.currentTarget,notifierData=currentTarget.getData(nodeDataKey),axisNodes=currentTarget.ancestors(),doc=currentTarget.get('ownerDocument'),delegates=[],count=notifierData?(__cov_6QPN5D0gRV5cd0sDuZmrgw.b['10'][0]++,Y.Object.keys(notifierData).length):(__cov_6QPN5D0gRV5cd0sDuZmrgw.b['10'][1]++,0),target,notifiers,notifier,yuid,match,tmp,i,len,sub,ret;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['32']++;currentTarget.clearData(nodeDataKey);__cov_6QPN5D0gRV5cd0sDuZmrgw.s['33']++;axisNodes.push(currentTarget);__cov_6QPN5D0gRV5cd0sDuZmrgw.s['34']++;if(doc){__cov_6QPN5D0gRV5cd0sDuZmrgw.b['11'][0]++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['35']++;axisNodes.unshift(doc);}else{__cov_6QPN5D0gRV5cd0sDuZmrgw.b['11'][1]++;}__cov_6QPN5D0gRV5cd0sDuZmrgw.s['36']++;axisNodes._nodes.reverse();__cov_6QPN5D0gRV5cd0sDuZmrgw.s['37']++;if(count){__cov_6QPN5D0gRV5cd0sDuZmrgw.b['12'][0]++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['38']++;tmp=count;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['39']++;axisNodes.some(function(node){__cov_6QPN5D0gRV5cd0sDuZmrgw.f['8']++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['40']++;var yuid=Y.stamp(node),notifiers=notifierData[yuid],i,len;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['41']++;if(notifiers){__cov_6QPN5D0gRV5cd0sDuZmrgw.b['13'][0]++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['42']++;count--;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['43']++;for(i=0,len=notifiers.length;i<len;++i){__cov_6QPN5D0gRV5cd0sDuZmrgw.s['44']++;if(notifiers[i].handle.sub.filter){__cov_6QPN5D0gRV5cd0sDuZmrgw.b['14'][0]++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['45']++;delegates.push(notifiers[i]);}else{__cov_6QPN5D0gRV5cd0sDuZmrgw.b['14'][1]++;}}}else{__cov_6QPN5D0gRV5cd0sDuZmrgw.b['13'][1]++;}__cov_6QPN5D0gRV5cd0sDuZmrgw.s['46']++;return!count;});__cov_6QPN5D0gRV5cd0sDuZmrgw.s['47']++;count=tmp;}else{__cov_6QPN5D0gRV5cd0sDuZmrgw.b['12'][1]++;}__cov_6QPN5D0gRV5cd0sDuZmrgw.s['48']++;while((__cov_6QPN5D0gRV5cd0sDuZmrgw.b['15'][0]++,count)&&(__cov_6QPN5D0gRV5cd0sDuZmrgw.b['15'][1]++,target=axisNodes.shift())){__cov_6QPN5D0gRV5cd0sDuZmrgw.s['49']++;yuid=Y.stamp(target);__cov_6QPN5D0gRV5cd0sDuZmrgw.s['50']++;notifiers=notifierData[yuid];__cov_6QPN5D0gRV5cd0sDuZmrgw.s['51']++;if(notifiers){__cov_6QPN5D0gRV5cd0sDuZmrgw.b['16'][0]++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['52']++;for(i=0,len=notifiers.length;i<len;++i){__cov_6QPN5D0gRV5cd0sDuZmrgw.s['53']++;notifier=notifiers[i];__cov_6QPN5D0gRV5cd0sDuZmrgw.s['54']++;sub=notifier.handle.sub;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['55']++;match=true;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['56']++;e.currentTarget=target;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['57']++;if(sub.filter){__cov_6QPN5D0gRV5cd0sDuZmrgw.b['17'][0]++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['58']++;match=sub.filter.apply(target,[target,e].concat((__cov_6QPN5D0gRV5cd0sDuZmrgw.b['18'][0]++,sub.args)||(__cov_6QPN5D0gRV5cd0sDuZmrgw.b['18'][1]++,[])));__cov_6QPN5D0gRV5cd0sDuZmrgw.s['59']++;delegates.splice(arrayIndex(delegates,notifier),1);}else{__cov_6QPN5D0gRV5cd0sDuZmrgw.b['17'][1]++;}__cov_6QPN5D0gRV5cd0sDuZmrgw.s['60']++;if(match){__cov_6QPN5D0gRV5cd0sDuZmrgw.b['19'][0]++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['61']++;e.container=notifier.container;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['62']++;ret=notifier.fire(e);}else{__cov_6QPN5D0gRV5cd0sDuZmrgw.b['19'][1]++;}__cov_6QPN5D0gRV5cd0sDuZmrgw.s['63']++;if((__cov_6QPN5D0gRV5cd0sDuZmrgw.b['21'][0]++,ret===false)||(__cov_6QPN5D0gRV5cd0sDuZmrgw.b['21'][1]++,e.stopped===2)){__cov_6QPN5D0gRV5cd0sDuZmrgw.b['20'][0]++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['64']++;break;}else{__cov_6QPN5D0gRV5cd0sDuZmrgw.b['20'][1]++;}}__cov_6QPN5D0gRV5cd0sDuZmrgw.s['65']++;delete notifiers[yuid];__cov_6QPN5D0gRV5cd0sDuZmrgw.s['66']++;count--;}else{__cov_6QPN5D0gRV5cd0sDuZmrgw.b['16'][1]++;}__cov_6QPN5D0gRV5cd0sDuZmrgw.s['67']++;if(e.stopped!==2){__cov_6QPN5D0gRV5cd0sDuZmrgw.b['22'][0]++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['68']++;for(i=0,len=delegates.length;i<len;++i){__cov_6QPN5D0gRV5cd0sDuZmrgw.s['69']++;notifier=delegates[i];__cov_6QPN5D0gRV5cd0sDuZmrgw.s['70']++;sub=notifier.handle.sub;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['71']++;if(sub.filter.apply(target,[target,e].concat((__cov_6QPN5D0gRV5cd0sDuZmrgw.b['24'][0]++,sub.args)||(__cov_6QPN5D0gRV5cd0sDuZmrgw.b['24'][1]++,[])))){__cov_6QPN5D0gRV5cd0sDuZmrgw.b['23'][0]++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['72']++;e.container=notifier.container;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['73']++;e.currentTarget=target;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['74']++;ret=notifier.fire(e);}else{__cov_6QPN5D0gRV5cd0sDuZmrgw.b['23'][1]++;}__cov_6QPN5D0gRV5cd0sDuZmrgw.s['75']++;if((__cov_6QPN5D0gRV5cd0sDuZmrgw.b['26'][0]++,ret===false)||(__cov_6QPN5D0gRV5cd0sDuZmrgw.b['26'][1]++,e.stopped===2)){__cov_6QPN5D0gRV5cd0sDuZmrgw.b['25'][0]++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['76']++;break;}else{__cov_6QPN5D0gRV5cd0sDuZmrgw.b['25'][1]++;}}}else{__cov_6QPN5D0gRV5cd0sDuZmrgw.b['22'][1]++;}__cov_6QPN5D0gRV5cd0sDuZmrgw.s['77']++;if(e.stopped){__cov_6QPN5D0gRV5cd0sDuZmrgw.b['27'][0]++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['78']++;break;}else{__cov_6QPN5D0gRV5cd0sDuZmrgw.b['27'][1]++;}}},on:function(node,sub,notifier){__cov_6QPN5D0gRV5cd0sDuZmrgw.f['9']++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['79']++;sub.handle=this._attach(node._node,notifier);},detach:function(node,sub){__cov_6QPN5D0gRV5cd0sDuZmrgw.f['10']++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['80']++;sub.handle.detach();},delegate:function(node,sub,notifier,filter){__cov_6QPN5D0gRV5cd0sDuZmrgw.f['11']++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['81']++;if(isString(filter)){__cov_6QPN5D0gRV5cd0sDuZmrgw.b['28'][0]++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['82']++;sub.filter=function(target){__cov_6QPN5D0gRV5cd0sDuZmrgw.f['12']++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['83']++;return Y.Selector.test(target._node,filter,node===target?(__cov_6QPN5D0gRV5cd0sDuZmrgw.b['29'][0]++,null):(__cov_6QPN5D0gRV5cd0sDuZmrgw.b['29'][1]++,node._node));};}else{__cov_6QPN5D0gRV5cd0sDuZmrgw.b['28'][1]++;}__cov_6QPN5D0gRV5cd0sDuZmrgw.s['84']++;sub.handle=this._attach(node._node,notifier,true);},detachDelegate:function(node,sub){__cov_6QPN5D0gRV5cd0sDuZmrgw.f['13']++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['85']++;sub.handle.detach();}},true);}__cov_6QPN5D0gRV5cd0sDuZmrgw.s['86']++;if(useActivate){__cov_6QPN5D0gRV5cd0sDuZmrgw.b['30'][0]++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['87']++;define('focus','beforeactivate','focusin');__cov_6QPN5D0gRV5cd0sDuZmrgw.s['88']++;define('blur','beforedeactivate','focusout');}else{__cov_6QPN5D0gRV5cd0sDuZmrgw.b['30'][1]++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['89']++;define('focus','focus','focus');__cov_6QPN5D0gRV5cd0sDuZmrgw.s['90']++;define('blur','blur','blur');}},'@VERSION@',{'requires':['event-synthetic']});
ui/src/js/profile/edit/EditUserDetails.js
Dica-Developer/weplantaforest
import axios from 'axios'; import counterpart from 'counterpart'; import moment from 'dayjs'; import React, { Component } from 'react'; import IconButton from '../../common/components/IconButton'; import Notification from '../../common/components/Notification'; import EditDropdownItem from './EditDropdownItem'; import EditItem from './EditItem'; import EditNameItem from './EditNameItem'; import EditPasswordItem from './EditPasswordItem'; import FileChooseAndUploadButton from './FileChooseAndUploadButton'; require('./editUserDetails.less'); export default class EditUserDetails extends Component { constructor(props) { super(props); } showProfile() { this.props.showProfile(); } editUser(toEdit, newEntry) { var that = this; var config = { headers: { 'X-AUTH-TOKEN': localStorage.getItem('jwt') } }; axios .post('http://localhost:8081/user/edit?userName=' + encodeURIComponent(this.props.user.userName) + '&toEdit=' + toEdit + '&newEntry=' + encodeURIComponent(newEntry), {}, config) .then(function(response) { that.refs[toEdit].saveChanges(); }) .catch(function(error) { that.refs[toEdit].undoChanges(); that.refs.notification.handleError(error); }); if (toEdit == 'LANGUAGE') { this.props.updateLanguage(newEntry); } } editUsername(newEntry) { var that = this; var config = { headers: { 'X-AUTH-TOKEN': localStorage.getItem('jwt') } }; axios .post('http://localhost:8081/user/edit?userName=' + encodeURIComponent(this.props.user.userName) + '&toEdit=NAME&newEntry=' + encodeURIComponent(newEntry), {}, config) .then(function(response) { that.props.logout(); }) .catch(function(error) { that.refs.name.undoChanges(that.props.user.userName); that.refs.notification.handleError(error); }); } updateImageName(imageName) { this.props.updateImageName(imageName); } render() { return ( <div> <div className="editUserDetails" onClick={this.clearErrorMessage}> <h1>{counterpart.translate('EDIT_PROFILE')}</h1> <div className="summary"> <span className="name">{this.props.user.userName}</span> <br /> <span className="bold">{counterpart.translate('MEMBER_SINCE')}:&nbsp;</span> {moment(this.props.user.regDate).format('DD.MM.YYYY')} <br /> <span className="bold">{counterpart.translate('RANK')}:&nbsp;</span> {this.props.user.rank} </div> </div> <FileChooseAndUploadButton imageId="edit-logo-img" imageFileName={this.props.user.imageFileName} updateImageName={this.updateImageName.bind(this)} /> <EditNameItem text={counterpart.translate('USERNAME')} content={this.props.user.userName} toEdit="NAME" editUsername={this.editUsername.bind(this)} ref="name" /> <EditItem text={counterpart.translate('ABOUT_ME')} content={this.props.user.aboutMe} toEdit="ABOUTME" editUser={this.editUser.bind(this)} ref="ABOUTME" /> <EditItem text={counterpart.translate('LOCATION')} content={this.props.user.location} toEdit="LOCATION" editUser={this.editUser.bind(this)} ref="LOCATION" /> <EditItem text={counterpart.translate('ORGANISATION')} content={this.props.user.organisation} toEdit="ORGANISATION" editUser={this.editUser.bind(this)} ref="ORGANISATION" /> <EditItem text={counterpart.translate('WEBSITE')} content={this.props.user.homepage} toEdit="HOMEPAGE" editUser={this.editUser.bind(this)} ref="HOMEPAGE" /> <EditDropdownItem text={counterpart.translate('LANGUAGE')} toEdit="LANGUAGE" content={this.props.user.lang} editUser={this.editUser.bind(this)} width="100" ref="LANGUAGE"> <option value="DEUTSCH">{counterpart.translate('GERMAN')}</option> <option value="ENGLISH">{counterpart.translate('ENGLISH')}</option> </EditDropdownItem> <EditItem text={counterpart.translate('MAIL')} content={this.props.user.mail} toEdit="MAIL" editUser={this.editUser.bind(this)} ref="MAIL" /> <EditDropdownItem text={counterpart.translate('TYPE')} toEdit="ORGANIZATION_TYPE" content={this.props.user.organizationType} editUser={this.editUser.bind(this)} width="180" ref="ORGANIZATION_TYPE" > <option value="PRIVATE">{counterpart.translate('RANKING_TYPES.PRIVATE')}</option> <option value="COMMERCIAL">{counterpart.translate('RANKING_TYPES.COMMERCIAL')}</option> <option value="NONPROFIT">{counterpart.translate('RANKING_TYPES.NONPROFIT')}</option> <option value="EDUCATIONAL">{counterpart.translate('RANKING_TYPES.EDUCATIONAL')}</option> </EditDropdownItem> <EditPasswordItem text={counterpart.translate('PASSWORD')} toEdit="PASSWORD" editUser={this.editUser.bind(this)} ref="PASSWORD" /> <div className="align-center bottomButton"> <IconButton text={counterpart.translate('VIEW')} glyphIcon="glyphicon-eye-open" onClick={this.showProfile.bind(this)} /> </div> <Notification ref="notification" /> </div> ); } } /* vim: set softtabstop=2:shiftwidth=2:expandtab */
src/components/InputField/index.js
supromikali/my-app
import React from 'react'; import { Field } from 'redux-form' const renderField = ({ input, label, type, meta: { touched, error, warning } }) => ( <div> <input {...input} placeholder={label} type={type} className="form-control" /> {touched && ((error && <span className="text-danger">{error}</span>) || (warning && <span>{warning}</span>))} </div> ); const InputField = ({ name }) => { return ( <div className="form-group"> <label className="control-label">{ name }:</label> <Field name={ name } component={renderField} type="text" /> </div> ); }; export default InputField
demo/src/index.js
moroshko/react-baseline
import React from 'react'; import { render } from 'react-dom'; import App from 'App'; render( <App />, document.getElementById('demo') );
3.StockQuote/src/scripts/components/popup.js
TravelingTechGuy/svcc-chrome-extension
import React from 'react'; import Footer from './footer'; import './popup.css'; export default class Popup extends React.Component { constructor(props) { super(props); this.state = { quotes: [], date: 'Updating...' }; chrome.runtime.sendMessage({action: 'getQuotes'}, function(response) { this.setState(response); }.bind(this)); } showBadge(badgeText = '', badgeTitle = '', badgeColor = []) { chrome.browserAction.setTitle({title: badgeTitle}); chrome.browserAction.setBadgeText({text: badgeText}); if(badgeColor.length) { chrome.browserAction.setBadgeBackgroundColor({color: badgeColor}); } } showSymbols() { if(this.state.quotes.length) { return ( <table> <thead> <tr> <th>Symbol</th> <th>Current</th> <th>Change</th> <th>Percent</th> </tr> </thead> <tbody> { this.state.quotes.map(quote => { return ( <tr key={quote.symbol}> <td><a href={`https://www.google.com/finance?q=${quote.symbol}`} target="_blank">{quote.symbol}</a></td> <td className="price">{quote.current}</td> <td className={'change ' + (quote.change.startsWith('-') ? 'minus': 'plus')}>{quote.change}</td> <td className={'change pct ' + (quote.changePct.startsWith('-') ? 'minus': 'plus')}>{quote.changePct}</td> </tr> ); }) } </tbody> </table> ); } else { return <div>Please add symbols in the Options page</div>; } } render() { return ( <div className="container"> <div className="header"> <img src="../icons/svcc.png" width="19" height="19" /> <span> StockQuote Extension</span> </div> <div className="content"> {this.showSymbols()} <p/> <div className="date">As of {this.state.date}</div> </div> <Footer size="small" /> </div> ); } }
app/components/AdminAppBar/index.js
vlastoun/picture-uploader-crud
import React from 'react'; import PropTypes from 'prop-types'; import AppBar from 'material-ui/AppBar'; import FlatButton from 'material-ui/FlatButton'; import { LINKS } from 'constants/AdminLinks'; import LeftDrawer from './LeftDrawer'; const appBarStyle = { postition: 'fixed', top: 0, width: '100%', }; /* eslint-disable react/prefer-stateless-function */ class AdminAppBar extends React.Component { constructor(props) { super(props); this.state = { width: '0', height: '0' }; this.updateWindowDimensions = this.updateWindowDimensions.bind(this); this.showDrawer = this.showDrawer.bind(this); } componentDidMount() { this.updateWindowDimensions(); window.addEventListener('resize', this.updateWindowDimensions); } componentWillUnmount() { window.removeEventListener('resize', this.updateWindowDimensions); } updateWindowDimensions() { this.setState({ width: window.innerWidth, height: window.innerHeight }); } showDrawer() { this.props.toggleDrawer(true); } render() { return ( <div> <AppBar title="Title" onLeftIconButtonTouchTap={this.showDrawer} iconElementRight={<FlatButton label="Logout" onClick={this.props.logout} />} style={appBarStyle} /> <LeftDrawer toggleDrawer={this.props.toggleDrawer} drawerState={this.props.drawerState} items={LINKS} activeUrl={this.props.activeUrl} clickedLink={this.props.clickedLink} /> </div> ); } } AdminAppBar.propTypes = { logout: PropTypes.func.isRequired, toggleDrawer: PropTypes.func.isRequired, drawerState: PropTypes.bool.isRequired, activeUrl: PropTypes.string.isRequired, clickedLink: PropTypes.func.isRequired, }; export default AdminAppBar;
fixtures/packaging/systemjs-builder/dev/input.js
mjackson/react
import React from 'react'; import ReactDOM from 'react-dom'; ReactDOM.render( React.createElement('h1', null, 'Hello World!'), document.getElementById('container') );
src/webapp/components/Timeline.js
craft-ai/morning-routine
import React from 'react'; import _ from 'lodash'; import createClass from 'create-react-class'; import Measure from 'react-measure'; import moment from 'moment-timezone'; import vis from 'vis'; import constants from '../constants'; import { debug } from '../../utils'; import 'vis/dist/vis.css'; import './Timeline.css'; const { ITEMS_CONTENT, ITEMS_TOOLTIP } = constants; const { DataSet } = vis; const log = debug(); const Timeline = createClass({ getInitialState() { return { dimensions: { width: -1, height: -1 } }; }, setDimensions(dimensions) { this.setState({ dimensions }); }, componentWillMount() { this.dom = { timeline: null }; }, componentDidMount() { log('Rendering the "vis" timeline...'); const { items, groups, options } = this.computeTimelineArgs(); this.timeline = new vis.Timeline(this.dom.timeline, items, groups, options); }, componentWillUnmount(dimensions) { this.timeline.destroy(); this.timeline = null; }, componentDidUpdate() { this.updateTimeline(); }, updateTimeline: _.throttle(function() { log('Updating the "vis" timeline...'); const { timeline } = this; const { items, groups, options } = this.computeTimelineArgs(); timeline.setItems(items); timeline.setGroups(groups); timeline.setOptions(options); timeline.fit({ animation: { duration: 800, easingFunction: 'linear' } }); }, 300), computeTimelineArgs() { const { dimensions } = this.state; const { items } = this.props; return { options: { width: `${dimensions.width}px`, height: `${dimensions.height}px`, showMajorLabels: false, showCurrentTime: false, moveable: false, selectable: false, zoomMin: 60 * 60 * 1000, stack: true, locale: 'en', moment: date => moment(date).tz('Europe/Paris'), groupOrder: 'slug', timeAxis: { scale: 'minute', step: 15 } }, items: new DataSet(items.map(({ t, slug }, index) => ({ id: index, title: ITEMS_TOOLTIP[slug], content: ITEMS_CONTENT[slug] || slug, group: slug, className: slug, start: _.isArray(t) ? t[0] : t, end: _.isArray(t) ? t[1] : undefined }))), groups: _(items) .sortBy('slug') .sortedUniqBy('slug') .map(({ slug }) => ({ id: slug, content: '' })) .value() }; }, render() { return ( <Measure onMeasure={ this.setDimensions }> <div className='Timeline' ref={ node => this.dom.timeline = node } style={ this.props.style } /> </Measure> ); } }); module.exports = Timeline;
node_modules/react-router/es6/withRouter.js
Karthik9321/ReduxSimpleStarter
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; import invariant from 'invariant'; import React from 'react'; import hoistStatics from 'hoist-non-react-statics'; import { routerShape } from './PropTypes'; function getDisplayName(WrappedComponent) { return WrappedComponent.displayName || WrappedComponent.name || 'Component'; } export default function withRouter(WrappedComponent, options) { var withRef = options && options.withRef; var WithRouter = React.createClass({ displayName: 'WithRouter', contextTypes: { router: routerShape }, propTypes: { router: routerShape }, getWrappedInstance: function getWrappedInstance() { !withRef ? process.env.NODE_ENV !== 'production' ? invariant(false, 'To access the wrapped instance, you need to specify ' + '`{ withRef: true }` as the second argument of the withRouter() call.') : invariant(false) : void 0; return this.wrappedInstance; }, render: function render() { var _this = this; var router = this.props.router || this.context.router; var props = _extends({}, this.props, { router: router }); if (withRef) { props.ref = function (c) { _this.wrappedInstance = c; }; } return React.createElement(WrappedComponent, props); } }); WithRouter.displayName = 'withRouter(' + getDisplayName(WrappedComponent) + ')'; WithRouter.WrappedComponent = WrappedComponent; return hoistStatics(WithRouter, WrappedComponent); }
app/components/Dashboard/index.js
Blacksage959/Michael.McCann
/** * * Dashboard * */ import React from 'react'; class Dashboard extends React.PureComponent { render() { return ( <div> </div> ); } } export default Dashboard;
ajax/libs/react-widgets/4.0.0-beta.2/react-widgets-simple-number.js
jonobr1/cdnjs
/*! (c) 2014 - present: Jason Quense | https://github.com/jquense/react-widgets/blob/master/License.txt */ /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { /*** IMPORTS FROM imports-loader ***/ var createLocalizer = __webpack_require__(1); var args = []; 'use strict'; /*** IMPORTS FROM imports-loader ***/ var define = false; if (typeof createLocalizer === 'function') { createLocalizer.apply(null, args || []); } /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /*** IMPORTS FROM imports-loader ***/ var define = false; 'use strict'; exports.__esModule = true; exports.default = globalizeLocalizers; var _react = __webpack_require__(2); var _configure = __webpack_require__(3); var _configure2 = _interopRequireDefault(_configure); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function endOfDecade(date) { date = new Date(date); date.setFullYear(date.getFullYear() + 10); date.setMilliseconds(date.getMilliseconds() - 1); return date; } function endOfCentury(date) { date = new Date(date); date.setFullYear(date.getFullYear() + 100); date.setMilliseconds(date.getMilliseconds() - 1); return date; } function globalizeLocalizers(globalize) { var localizers = globalize.locale && !globalize.cultures ? newGlobalize(globalize) : oldGlobalize(globalize); _configure2.default.setLocalizers(localizers); return localizers; } function newGlobalize(globalize) { var locale = function locale(culture) { return culture ? globalize(culture) : globalize; }; var date = { formats: { date: { date: 'short' }, time: { time: 'short' }, default: { datetime: 'medium' }, header: 'MMMM yyyy', footer: { date: 'full' }, weekday: 'eeeeee', dayOfMonth: 'dd', month: 'MMM', year: 'yyyy', decade: function decade(dt, culture, l) { return l.format(dt, l.formats.year, culture) + ' - ' + l.format(endOfDecade(dt), l.formats.year, culture); }, century: function century(dt, culture, l) { return l.format(dt, l.formats.year, culture) + ' - ' + l.format(endOfCentury(dt), l.formats.year, culture); } }, propType: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.object, _react.PropTypes.func]), firstOfWeek: function firstOfWeek(culture) { var date = new Date(); //cldr-data doesn't seem to be zero based var localeDay = Math.max(parseInt(locale(culture).formatDate(date, { raw: 'e' }), 10) - 1, 0); return Math.abs(date.getDay() - localeDay); }, parse: function parse(value, format, culture) { format = typeof format === 'string' ? { raw: format } : format; return locale(culture).parseDate(value, format); }, format: function format(value, _format, culture) { _format = typeof _format === 'string' ? { raw: _format } : _format; return locale(culture).formatDate(value, _format); } }; var number = { formats: { default: { maximumFractionDigits: 0 } }, propType: _react.PropTypes.oneOfType([_react.PropTypes.object, _react.PropTypes.func]), // TODO major bump consistent ordering parse: function parse(value, culture) { return locale(culture).parseNumber(value); }, format: function format(value, _format2, culture) { if (value == null) return value; if (_format2 && _format2.currency) return locale(culture).formatCurrency(value, _format2.currency, _format2); return locale(culture).formatNumber(value, _format2); }, decimalChar: function decimalChar(format, culture) { var str = this.format(1.1, { raw: '0.0' }, culture); return str[str.length - 2] || '.'; }, precision: function precision(format) { return !format || format.maximumFractionDigits == null ? null : format.maximumFractionDigits; } }; return { date: date, number: number }; } function oldGlobalize(globalize) { var shortNames = Object.create(null); function getCulture(culture) { return culture ? globalize.findClosestCulture(culture) : globalize.culture(); } function firstOfWeek(culture) { culture = getCulture(culture); return culture && culture.calendar.firstDay || 0; } function shortDay(dayOfTheWeek) { var culture = getCulture(arguments[1]), name = culture.name, days = function days() { return culture.calendar.days.namesShort.slice(); }; var names = shortNames[name] || (shortNames[name] = days()); return names[dayOfTheWeek.getDay()]; } var date = { formats: { date: 'd', time: 't', default: 'f', header: 'MMMM yyyy', footer: 'D', weekday: shortDay, dayOfMonth: 'dd', month: 'MMM', year: 'yyyy', decade: function decade(dt, culture, l) { return l.format(dt, l.formats.year, culture) + ' - ' + l.format(endOfDecade(dt), l.formats.year, culture); }, century: function century(dt, culture, l) { return l.format(dt, l.formats.year, culture) + ' - ' + l.format(endOfCentury(dt), l.formats.year, culture); } }, firstOfWeek: firstOfWeek, parse: function parse(value, format, culture) { return globalize.parseDate(value, format, culture); }, format: function format(value, _format3, culture) { return globalize.format(value, _format3, culture); } }; function formatData(format, _culture) { var culture = getCulture(_culture), numFormat = culture.numberFormat; if (typeof format === 'string') { if (format.indexOf('p') !== -1) numFormat = numFormat.percent; if (format.indexOf('c') !== -1) numFormat = numFormat.curency; } return numFormat; } var number = { formats: { default: 'D' }, // TODO major bump consistent ordering parse: function parse(value, culture) { return globalize.parseFloat(value, 10, culture); }, format: function format(value, _format4, culture) { return globalize.format(value, _format4, culture); }, decimalChar: function decimalChar(format, culture) { var data = formatData(format, culture); return data['.'] || '.'; }, precision: function precision(format, _culture) { var data = formatData(format, _culture); if (typeof format === 'string' && format.length > 1) return parseFloat(format.substr(1)); return data ? data.decimals : null; } }; return { date: date, number: number }; } module.exports = exports['default']; /***/ }, /* 2 */ /***/ function(module, exports) { module.exports = window.React; /***/ }, /* 3 */ /***/ function(module, exports) { module.exports = window.ReactWidgets; /***/ } /******/ ]);
ajax/libs/yui/3.1.2/event-custom/event-custom-base-debug.js
adatapost/cdnjs
YUI.add('event-custom-base', function(Y) { /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom */ Y.Env.evt = { handles: {}, plugins: {} }; /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ (function() { /** * Allows for the insertion of methods that are executed before or after * a specified method * @class Do * @static */ var BEFORE = 0, AFTER = 1; Y.Do = { /** * Cache of objects touched by the utility * @property objs * @static */ objs: {}, /** * Execute the supplied method before the specified function * @method before * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * when the event fires. * @return {string} handle for the subscription * @static */ before: function(fn, obj, sFn, c) { // Y.log('Do before: ' + sFn, 'info', 'event'); var f = fn, a; if (c) { a = [fn, c].concat(Y.Array(arguments, 4, true)); f = Y.rbind.apply(Y, a); } return this._inject(BEFORE, f, obj, sFn); }, /** * Execute the supplied method after the specified function * @method after * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * @return {string} handle for the subscription * @static */ after: function(fn, obj, sFn, c) { var f = fn, a; if (c) { a = [fn, c].concat(Y.Array(arguments, 4, true)); f = Y.rbind.apply(Y, a); } return this._inject(AFTER, f, obj, sFn); }, /** * Execute the supplied method after the specified function * @method _inject * @param when {string} before or after * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @return {string} handle for the subscription * @private * @static */ _inject: function(when, fn, obj, sFn) { // object id var id = Y.stamp(obj), o, sid; if (! this.objs[id]) { // create a map entry for the obj if it doesn't exist this.objs[id] = {}; } o = this.objs[id]; if (! o[sFn]) { // create a map entry for the method if it doesn't exist o[sFn] = new Y.Do.Method(obj, sFn); // re-route the method to our wrapper obj[sFn] = function() { return o[sFn].exec.apply(o[sFn], arguments); }; } // subscriber id sid = id + Y.stamp(fn) + sFn; // register the callback o[sFn].register(sid, fn, when); return new Y.EventHandle(o[sFn], sid); }, /** * Detach a before or after subscription * @method detach * @param handle {string} the subscription handle */ detach: function(handle) { if (handle.detach) { handle.detach(); } }, _unload: function(e, me) { } }; ////////////////////////////////////////////////////////////////////////// /** * Wrapper for a displaced method with aop enabled * @class Do.Method * @constructor * @param obj The object to operate on * @param sFn The name of the method to displace */ Y.Do.Method = function(obj, sFn) { this.obj = obj; this.methodName = sFn; this.method = obj[sFn]; this.before = {}; this.after = {}; }; /** * Register a aop subscriber * @method register * @param sid {string} the subscriber id * @param fn {Function} the function to execute * @param when {string} when to execute the function */ Y.Do.Method.prototype.register = function (sid, fn, when) { if (when) { this.after[sid] = fn; } else { this.before[sid] = fn; } }; /** * Unregister a aop subscriber * @method delete * @param sid {string} the subscriber id * @param fn {Function} the function to execute * @param when {string} when to execute the function */ Y.Do.Method.prototype._delete = function (sid) { // Y.log('Y.Do._delete: ' + sid, 'info', 'Event'); delete this.before[sid]; delete this.after[sid]; }; /** * Execute the wrapped method * @method exec */ Y.Do.Method.prototype.exec = function () { var args = Y.Array(arguments, 0, true), i, ret, newRet, bf = this.before, af = this.after, prevented = false; // execute before for (i in bf) { if (bf.hasOwnProperty(i)) { ret = bf[i].apply(this.obj, args); if (ret) { switch (ret.constructor) { case Y.Do.Halt: return ret.retVal; case Y.Do.AlterArgs: args = ret.newArgs; break; case Y.Do.Prevent: prevented = true; break; default: } } } } // execute method if (!prevented) { ret = this.method.apply(this.obj, args); } // execute after methods. for (i in af) { if (af.hasOwnProperty(i)) { newRet = af[i].apply(this.obj, args); // Stop processing if a Halt object is returned if (newRet && newRet.constructor == Y.Do.Halt) { return newRet.retVal; // Check for a new return value } else if (newRet && newRet.constructor == Y.Do.AlterReturn) { ret = newRet.newRetVal; } } } return ret; }; ////////////////////////////////////////////////////////////////////////// /** * Return an AlterArgs object when you want to change the arguments that * were passed into the function. An example would be a service that scrubs * out illegal characters prior to executing the core business logic. * @class Do.AlterArgs */ Y.Do.AlterArgs = function(msg, newArgs) { this.msg = msg; this.newArgs = newArgs; }; /** * Return an AlterReturn object when you want to change the result returned * from the core method to the caller * @class Do.AlterReturn */ Y.Do.AlterReturn = function(msg, newRetVal) { this.msg = msg; this.newRetVal = newRetVal; }; /** * Return a Halt object when you want to terminate the execution * of all subsequent subscribers as well as the wrapped method * if it has not exectued yet. * @class Do.Halt */ Y.Do.Halt = function(msg, retVal) { this.msg = msg; this.retVal = retVal; }; /** * Return a Prevent object when you want to prevent the wrapped function * from executing, but want the remaining listeners to execute * @class Do.Prevent */ Y.Do.Prevent = function(msg) { this.msg = msg; }; /** * Return an Error object when you want to terminate the execution * of all subsequent method calls. * @class Do.Error * @deprecated use Y.Do.Halt or Y.Do.Prevent */ Y.Do.Error = Y.Do.Halt; ////////////////////////////////////////////////////////////////////////// // Y["Event"] && Y.Event.addListener(window, "unload", Y.Do._unload, Y.Do); })(); /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ /** * Return value from all subscribe operations * @class EventHandle * @constructor * @param evt {CustomEvent} the custom event * @param sub {Subscriber} the subscriber */ // var onsubscribeType = "_event:onsub", var AFTER = 'after', CONFIGS = [ 'broadcast', 'monitored', 'bubbles', 'context', 'contextFn', 'currentTarget', 'defaultFn', 'defaultTargetOnly', 'details', 'emitFacade', 'fireOnce', 'async', 'host', 'preventable', 'preventedFn', 'queuable', 'silent', 'stoppedFn', 'target', 'type' ], YUI3_SIGNATURE = 9, YUI_LOG = 'yui:log'; Y.EventHandle = function(evt, sub) { /** * The custom event * @type CustomEvent */ this.evt = evt; /** * The subscriber object * @type Subscriber */ this.sub = sub; }; Y.EventHandle.prototype = { /** * Detaches this subscriber * @method detach */ detach: function() { var evt = this.evt, detached = 0, i; if (evt) { // Y.log('EventHandle.detach: ' + this.sub, 'info', 'Event'); if (Y.Lang.isArray(evt)) { for (i=0; i<evt.length; i++) { detached += evt[i].detach(); } } else { evt._delete(this.sub); detached = 1; } } return detached; }, /** * Monitor the event state for the subscribed event. The first parameter * is what should be monitored, the rest are the normal parameters when * subscribing to an event. * @method monitor * @param what {string} what to monitor ('attach', 'detach', 'publish') * @return {EventHandle} return value from the monitor event subscription */ monitor: function(what) { return this.evt.monitor.apply(this.evt, arguments); } }; /** * The CustomEvent class lets you define events for your application * that can be subscribed to by one or more independent component. * * @param {String} type The type of event, which is passed to the callback * when the event fires * @param o configuration object * @class CustomEvent * @constructor */ Y.CustomEvent = function(type, o) { // if (arguments.length > 2) { // this.log('CustomEvent context and silent are now in the config', 'warn', 'Event'); // } o = o || {}; this.id = Y.stamp(this); /** * The type of event, returned to subscribers when the event fires * @property type * @type string */ this.type = type; /** * The context the the event will fire from by default. Defaults to the YUI * instance. * @property context * @type object */ this.context = Y; /** * Monitor when an event is attached or detached. * * @property monitored * @type boolean */ // this.monitored = false; this.logSystem = (type == YUI_LOG); /** * If 0, this event does not broadcast. If 1, the YUI instance is notified * every time this event fires. If 2, the YUI instance and the YUI global * (if event is enabled on the global) are notified every time this event * fires. * @property broadcast * @type int */ // this.broadcast = 0; /** * By default all custom events are logged in the debug build, set silent * to true to disable debug outpu for this event. * @property silent * @type boolean */ this.silent = this.logSystem; /** * Specifies whether this event should be queued when the host is actively * processing an event. This will effect exectution order of the callbacks * for the various events. * @property queuable * @type boolean * @default false */ // this.queuable = false; /** * The subscribers to this event * @property subscribers * @type Subscriber{} */ this.subscribers = {}; /** * 'After' subscribers * @property afters * @type Subscriber{} */ this.afters = {}; /** * This event has fired if true * * @property fired * @type boolean * @default false; */ // this.fired = false; /** * An array containing the arguments the custom event * was last fired with. * @property firedWith * @type Array */ // this.firedWith; /** * This event should only fire one time if true, and if * it has fired, any new subscribers should be notified * immediately. * * @property fireOnce * @type boolean * @default false; */ // this.fireOnce = false; /** * fireOnce listeners will fire syncronously unless async * is set to true * @property async * @type boolean * @default false */ //this.async = false; /** * Flag for stopPropagation that is modified during fire() * 1 means to stop propagation to bubble targets. 2 means * to also stop additional subscribers on this target. * @property stopped * @type int */ // this.stopped = 0; /** * Flag for preventDefault that is modified during fire(). * if it is not 0, the default behavior for this event * @property prevented * @type int */ // this.prevented = 0; /** * Specifies the host for this custom event. This is used * to enable event bubbling * @property host * @type EventTarget */ // this.host = null; /** * The default function to execute after event listeners * have fire, but only if the default action was not * prevented. * @property defaultFn * @type Function */ // this.defaultFn = null; /** * The function to execute if a subscriber calls * stopPropagation or stopImmediatePropagation * @property stoppedFn * @type Function */ // this.stoppedFn = null; /** * The function to execute if a subscriber calls * preventDefault * @property preventedFn * @type Function */ // this.preventedFn = null; /** * Specifies whether or not this event's default function * can be cancelled by a subscriber by executing preventDefault() * on the event facade * @property preventable * @type boolean * @default true */ this.preventable = true; /** * Specifies whether or not a subscriber can stop the event propagation * via stopPropagation(), stopImmediatePropagation(), or halt() * * Events can only bubble if emitFacade is true. * * @property bubbles * @type boolean * @default true */ this.bubbles = true; /** * Supports multiple options for listener signatures in order to * port YUI 2 apps. * @property signature * @type int * @default 9 */ this.signature = YUI3_SIGNATURE; this.subCount = 0; this.afterCount = 0; // this.hasSubscribers = false; // this.hasAfters = false; /** * If set to true, the custom event will deliver an EventFacade object * that is similar to a DOM event object. * @property emitFacade * @type boolean * @default false */ // this.emitFacade = false; this.applyConfig(o, true); // this.log("Creating " + this.type); }; Y.CustomEvent.prototype = { hasSubs: function(when) { var s = this.subCount, a = this.afterCount, sib = this.sibling; if (sib) { s += sib.subCount; a += sib.afterCount; } if (when) { return (when == 'after') ? a : s; } return (s + a); }, /** * Monitor the event state for the subscribed event. The first parameter * is what should be monitored, the rest are the normal parameters when * subscribing to an event. * @method monitor * @param what {string} what to monitor ('detach', 'attach', 'publish') * @return {EventHandle} return value from the monitor event subscription */ monitor: function(what) { this.monitored = true; var type = this.id + '|' + this.type + '_' + what, args = Y.Array(arguments, 0, true); args[0] = type; return this.host.on.apply(this.host, args); }, /** * Get all of the subscribers to this event and any sibling event * @return {Array} first item is the on subscribers, second the after */ getSubs: function() { var s = Y.merge(this.subscribers), a = Y.merge(this.afters), sib = this.sibling; if (sib) { Y.mix(s, sib.subscribers); Y.mix(a, sib.afters); } return [s, a]; }, /** * Apply configuration properties. Only applies the CONFIG whitelist * @method applyConfig * @param o hash of properties to apply * @param force {boolean} if true, properties that exist on the event * will be overwritten. */ applyConfig: function(o, force) { if (o) { Y.mix(this, o, force, CONFIGS); } }, _on: function(fn, context, args, when) { if (!fn) { this.log("Invalid callback for CE: " + this.type); } var s = new Y.Subscriber(fn, context, args, when); if (this.fireOnce && this.fired) { if (this.async) { setTimeout(Y.bind(this._notify, this, s, this.firedWith), 0); } else { this._notify(s, this.firedWith); } } if (when == AFTER) { this.afters[s.id] = s; this.afterCount++; } else { this.subscribers[s.id] = s; this.subCount++; } return new Y.EventHandle(this, s); }, /** * Listen for this event * @method subscribe * @param {Function} fn The function to execute * @return {EventHandle} Unsubscribe handle * @deprecated use on */ subscribe: function(fn, context) { Y.log('ce.subscribe deprecated, use "on"', 'warn', 'deprecated'); var a = (arguments.length > 2) ? Y.Array(arguments, 2, true): null; return this._on(fn, context, a, true); }, /** * Listen for this event * @method on * @param {Function} fn The function to execute * @param context {object} optional execution context. * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * when the event fires. * @return {EventHandle} An object with a detach method to detch the handler(s) */ on: function(fn, context) { var a = (arguments.length > 2) ? Y.Array(arguments, 2, true): null; this.host._monitor('attach', this.type, { args: arguments }); return this._on(fn, context, a, true); }, /** * Listen for this event after the normal subscribers have been notified and * the default behavior has been applied. If a normal subscriber prevents the * default behavior, it also prevents after listeners from firing. * @method after * @param {Function} fn The function to execute * @param context {object} optional execution context. * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * when the event fires. * @return {EventHandle} handle Unsubscribe handle */ after: function(fn, context) { var a = (arguments.length > 2) ? Y.Array(arguments, 2, true): null; return this._on(fn, context, a, AFTER); }, /** * Detach listeners. * @method detach * @param {Function} fn The subscribed function to remove, if not supplied * all will be removed * @param {Object} context The context object passed to subscribe. * @return {int} returns the number of subscribers unsubscribed */ detach: function(fn, context) { // unsubscribe handle if (fn && fn.detach) { return fn.detach(); } var found = 0, subs = this.subscribers, i, s; for (i in subs) { if (subs.hasOwnProperty(i)) { s = subs[i]; if (s && (!fn || fn === s.fn)) { this._delete(s); found++; } } } return found; }, /** * Detach listeners. * @method unsubscribe * @param {Function} fn The subscribed function to remove, if not supplied * all will be removed * @param {Object} context The context object passed to subscribe. * @return {int|undefined} returns the number of subscribers unsubscribed * @deprecated use detach */ unsubscribe: function() { return this.detach.apply(this, arguments); }, /** * Notify a single subscriber * @method _notify * @param s {Subscriber} the subscriber * @param args {Array} the arguments array to apply to the listener * @private */ _notify: function(s, args, ef) { this.log(this.type + "->" + "sub: " + s.id); var ret; ret = s.notify(args, this); if (false === ret || this.stopped > 1) { this.log(this.type + " cancelled by subscriber"); return false; } return true; }, /** * Logger abstraction to centralize the application of the silent flag * @method log * @param msg {string} message to log * @param cat {string} log category */ log: function(msg, cat) { if (!this.silent) { Y.log(this.id + ': ' + msg, cat || "info", "event"); } }, /** * Notifies the subscribers. The callback functions will be executed * from the context specified when the event was created, and with the * following parameters: * <ul> * <li>The type of event</li> * <li>All of the arguments fire() was executed with as an array</li> * <li>The custom object (if any) that was passed into the subscribe() * method</li> * </ul> * @method fire * @param {Object*} arguments an arbitrary set of parameters to pass to * the handler. * @return {boolean} false if one of the subscribers returned false, * true otherwise * */ fire: function() { if (this.fireOnce && this.fired) { this.log('fireOnce event: ' + this.type + ' already fired'); return true; } else { var args = Y.Array(arguments, 0, true); // this doesn't happen if the event isn't published // this.host._monitor('fire', this.type, args); this.fired = true; this.firedWith = args; if (this.emitFacade) { return this.fireComplex(args); } else { return this.fireSimple(args); } } }, fireSimple: function(args) { this.stopped = 0; this.prevented = 0; if (this.hasSubs()) { // this._procSubs(Y.merge(this.subscribers, this.afters), args); var subs = this.getSubs(); this._procSubs(subs[0], args); this._procSubs(subs[1], args); } this._broadcast(args); return this.stopped ? false : true; }, // Requires the event-custom-complex module for full funcitonality. fireComplex: function(args) { Y.log('Missing event-custom-complex needed to emit a facade for: ' + this.type); args[0] = args[0] || {}; return this.fireSimple(args); }, _procSubs: function(subs, args, ef) { var s, i; for (i in subs) { if (subs.hasOwnProperty(i)) { s = subs[i]; if (s && s.fn) { if (false === this._notify(s, args, ef)) { this.stopped = 2; } if (this.stopped == 2) { return false; } } } } return true; }, _broadcast: function(args) { if (!this.stopped && this.broadcast) { var a = Y.Array(args); a.unshift(this.type); if (this.host !== Y) { Y.fire.apply(Y, a); } if (this.broadcast == 2) { Y.Global.fire.apply(Y.Global, a); } } }, /** * Removes all listeners * @method unsubscribeAll * @return {int} The number of listeners unsubscribed * @deprecated use detachAll */ unsubscribeAll: function() { return this.detachAll.apply(this, arguments); }, /** * Removes all listeners * @method detachAll * @return {int} The number of listeners unsubscribed */ detachAll: function() { return this.detach(); }, /** * @method _delete * @param subscriber object * @private */ _delete: function(s) { if (s) { delete s.fn; delete s.context; delete this.subscribers[s.id]; delete this.afters[s.id]; } this.host._monitor('detach', this.type, { ce: this, sub: s }); } }; ///////////////////////////////////////////////////////////////////// /** * Stores the subscriber information to be used when the event fires. * @param {Function} fn The wrapped function to execute * @param {Object} context The value of the keyword 'this' in the listener * @param {Array} args* 0..n additional arguments to supply the listener * * @class Subscriber * @constructor */ Y.Subscriber = function(fn, context, args) { /** * The callback that will be execute when the event fires * This is wrapped by Y.rbind if obj was supplied. * @property fn * @type Function */ this.fn = fn; /** * Optional 'this' keyword for the listener * @property context * @type Object */ this.context = context; /** * Unique subscriber id * @property id * @type String */ this.id = Y.stamp(this); /** * Additional arguments to propagate to the subscriber * @property args * @type Array */ this.args = args; /** * Custom events for a given fire transaction. * @property events * @type {EventTarget} */ // this.events = null; /** * This listener only reacts to the event once * @property once */ // this.once = false; }; Y.Subscriber.prototype = { _notify: function(c, args, ce) { var a = this.args, ret; switch (ce.signature) { case 0: ret = this.fn.call(c, ce.type, args, c); break; case 1: ret = this.fn.call(c, args[0] || null, c); break; default: if (a || args) { args = args || []; a = (a) ? args.concat(a) : args; ret = this.fn.apply(c, a); } else { ret = this.fn.call(c); } } if (this.once) { ce._delete(this); } return ret; }, /** * Executes the subscriber. * @method notify * @param args {Array} Arguments array for the subscriber * @param ce {CustomEvent} The custom event that sent the notification */ notify: function(args, ce) { var c = this.context, ret = true; if (!c) { c = (ce.contextFn) ? ce.contextFn() : ce.context; } // only catch errors if we will not re-throw them. if (Y.config.throwFail) { ret = this._notify(c, args, ce); } else { try { ret = this._notify(c, args, ce); } catch(e) { Y.error(this + ' failed: ' + e.message, e); } } return ret; }, /** * Returns true if the fn and obj match this objects properties. * Used by the unsubscribe method to match the right subscriber. * * @method contains * @param {Function} fn the function to execute * @param {Object} context optional 'this' keyword for the listener * @return {boolean} true if the supplied arguments match this * subscriber's signature. */ contains: function(fn, context) { if (context) { return ((this.fn == fn) && this.context == context); } else { return (this.fn == fn); } } }; /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ (function() { /** * EventTarget provides the implementation for any object to * publish, subscribe and fire to custom events, and also * alows other EventTargets to target the object with events * sourced from the other object. * EventTarget is designed to be used with Y.augment to wrap * EventCustom in an interface that allows events to be listened to * and fired by name. This makes it possible for implementing code to * subscribe to an event that either has not been created yet, or will * not be created at all. * @class EventTarget * @param opts a configuration object * @config emitFacade {boolean} if true, all events will emit event * facade payloads by default (default false) * @config prefix {string} the prefix to apply to non-prefixed event names * @config chain {boolean} if true, on/after/detach return the host to allow * chaining, otherwise they return an EventHandle (default false) */ var L = Y.Lang, PREFIX_DELIMITER = ':', CATEGORY_DELIMITER = '|', AFTER_PREFIX = '~AFTER~', _wildType = Y.cached(function(type) { return type.replace(/(.*)(:)(.*)/, "*$2$3"); }), /** * If the instance has a prefix attribute and the * event type is not prefixed, the instance prefix is * applied to the supplied type. * @method _getType * @private */ _getType = Y.cached(function(type, pre) { if (!pre || !L.isString(type) || type.indexOf(PREFIX_DELIMITER) > -1) { return type; } return pre + PREFIX_DELIMITER + type; }), /** * Returns an array with the detach key (if provided), * and the prefixed event name from _getType * Y.on('detachcategory| menu:click', fn) * @method _parseType * @private */ _parseType = Y.cached(function(type, pre) { var t = type, detachcategory, after, i; if (!L.isString(t)) { return t; } i = t.indexOf(AFTER_PREFIX); if (i > -1) { after = true; t = t.substr(AFTER_PREFIX.length); // Y.log(t); } i = t.indexOf(CATEGORY_DELIMITER); if (i > -1) { detachcategory = t.substr(0, (i)); t = t.substr(i+1); if (t == '*') { t = null; } } // detach category, full type with instance prefix, is this an after listener, short type return [detachcategory, (pre) ? _getType(t, pre) : t, after, t]; }), ET = function(opts) { // Y.log('EventTarget constructor executed: ' + this._yuid); var o = (L.isObject(opts)) ? opts : {}; this._yuievt = this._yuievt || { id: Y.guid(), events: {}, targets: {}, config: o, chain: ('chain' in o) ? o.chain : Y.config.chain, bubbling: false, defaults: { context: o.context || this, host: this, emitFacade: o.emitFacade, fireOnce: o.fireOnce, queuable: o.queuable, monitored: o.monitored, broadcast: o.broadcast, defaultTargetOnly: o.defaulTargetOnly, bubbles: ('bubbles' in o) ? o.bubbles : true } }; }; ET.prototype = { /** * Listen to a custom event hosted by this object one time. * This is the equivalent to <code>on</code> except the * listener is immediatelly detached when it is executed. * @method once * @param type {string} The type of the event * @param fn {Function} The callback * @param context {object} optional execution context. * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * @return the event target or a detach handle per 'chain' config */ once: function() { var handle = this.on.apply(this, arguments); handle.sub.once = true; return handle; }, /** * Subscribe to a custom event hosted by this object * @method on * @param type {string} The type of the event * @param fn {Function} The callback * @param context {object} optional execution context. * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * @return the event target or a detach handle per 'chain' config */ on: function(type, fn, context) { var parts = _parseType(type, this._yuievt.config.prefix), f, c, args, ret, ce, detachcategory, handle, store = Y.Env.evt.handles, after, adapt, shorttype, Node = Y.Node, n, domevent, isArr; // full name, args, detachcategory, after this._monitor('attach', parts[1], { args: arguments, category: parts[0], after: parts[2] }); if (L.isObject(type)) { if (L.isFunction(type)) { return Y.Do.before.apply(Y.Do, arguments); } f = fn; c = context; args = Y.Array(arguments, 0, true); ret = {}; if (L.isArray(type)) { isArr = true; } else { after = type._after; delete type._after; } Y.each(type, function(v, k) { if (L.isObject(v)) { f = v.fn || ((L.isFunction(v)) ? v : f); c = v.context || c; } args[0] = (isArr) ? v : ((after) ? AFTER_PREFIX + k : k); args[1] = f; args[2] = c; ret[k] = this.on.apply(this, args); }, this); return (this._yuievt.chain) ? this : new Y.EventHandle(ret); } detachcategory = parts[0]; after = parts[2]; shorttype = parts[3]; // extra redirection so we catch adaptor events too. take a look at this. if (Node && (this instanceof Node) && (shorttype in Node.DOM_EVENTS)) { args = Y.Array(arguments, 0, true); args.splice(2, 0, Node.getDOMNode(this)); // Y.log("Node detected, redirecting with these args: " + args); return Y.on.apply(Y, args); } type = parts[1]; if (this instanceof YUI) { adapt = Y.Env.evt.plugins[type]; args = Y.Array(arguments, 0, true); args[0] = shorttype; if (Node) { n = args[2]; if (n instanceof Y.NodeList) { n = Y.NodeList.getDOMNodes(n); } else if (n instanceof Node) { n = Node.getDOMNode(n); } domevent = (shorttype in Node.DOM_EVENTS); // Captures both DOM events and event plugins. if (domevent) { args[2] = n; } } // check for the existance of an event adaptor if (adapt) { Y.log('Using adaptor for ' + shorttype + ', ' + n, 'info', 'event'); handle = adapt.on.apply(Y, args); } else if ((!type) || domevent) { handle = Y.Event._attach(args); } } if (!handle) { ce = this._yuievt.events[type] || this.publish(type); handle = ce._on(fn, context, (arguments.length > 3) ? Y.Array(arguments, 3, true) : null, (after) ? 'after' : true); } if (detachcategory) { store[detachcategory] = store[detachcategory] || {}; store[detachcategory][type] = store[detachcategory][type] || []; store[detachcategory][type].push(handle); } return (this._yuievt.chain) ? this : handle; }, /** * subscribe to an event * @method subscribe * @deprecated use on */ subscribe: function() { Y.log('EventTarget subscribe() is deprecated, use on()', 'warn', 'deprecated'); return this.on.apply(this, arguments); }, /** * Detach one or more listeners the from the specified event * @method detach * @param type {string|Object} Either the handle to the subscriber or the * type of event. If the type * is not specified, it will attempt to remove * the listener from all hosted events. * @param fn {Function} The subscribed function to unsubscribe, if not * supplied, all subscribers will be removed. * @param context {Object} The custom object passed to subscribe. This is * optional, but if supplied will be used to * disambiguate multiple listeners that are the same * (e.g., you subscribe many object using a function * that lives on the prototype) * @return {EventTarget} the host */ detach: function(type, fn, context) { var evts = this._yuievt.events, i, Node = Y.Node, isNode = Node && (this instanceof Node); // detachAll disabled on the Y instance. if (!type && (this !== Y)) { for (i in evts) { if (evts.hasOwnProperty(i)) { evts[i].detach(fn, context); } } if (isNode) { Y.Event.purgeElement(Node.getDOMNode(this)); } return this; } var parts = _parseType(type, this._yuievt.config.prefix), detachcategory = L.isArray(parts) ? parts[0] : null, shorttype = (parts) ? parts[3] : null, handle, adapt, store = Y.Env.evt.handles, cat, args, ce, keyDetacher = function(lcat, ltype) { var handles = lcat[ltype]; if (handles) { while (handles.length) { handle = handles.pop(); handle.detach(); } } }; if (detachcategory) { cat = store[detachcategory]; type = parts[1]; if (cat) { if (type) { keyDetacher(cat, type); } else { for (i in cat) { if (cat.hasOwnProperty(i)) { keyDetacher(cat, i); } } } return this; } // If this is an event handle, use it to detach } else if (L.isObject(type) && type.detach) { type.detach(); return this; // extra redirection so we catch adaptor events too. take a look at this. } else if (isNode && ((!shorttype) || (shorttype in Node.DOM_EVENTS))) { args = Y.Array(arguments, 0, true); args[2] = Node.getDOMNode(this); Y.detach.apply(Y, args); return this; } adapt = Y.Env.evt.plugins[shorttype]; // The YUI instance handles DOM events and adaptors if (this instanceof YUI) { args = Y.Array(arguments, 0, true); // use the adaptor specific detach code if if (adapt && adapt.detach) { adapt.detach.apply(Y, args); return this; // DOM event fork } else if (!type || (!adapt && Node && (type in Node.DOM_EVENTS))) { args[0] = type; Y.Event.detach.apply(Y.Event, args); return this; } } // ce = evts[type]; ce = evts[parts[1]]; if (ce) { ce.detach(fn, context); } return this; }, /** * detach a listener * @method unsubscribe * @deprecated use detach */ unsubscribe: function() { Y.log('EventTarget unsubscribe() is deprecated, use detach()', 'warn', 'deprecated'); return this.detach.apply(this, arguments); }, /** * Removes all listeners from the specified event. If the event type * is not specified, all listeners from all hosted custom events will * be removed. * @method detachAll * @param type {string} The type, or name of the event */ detachAll: function(type) { return this.detach(type); }, /** * Removes all listeners from the specified event. If the event type * is not specified, all listeners from all hosted custom events will * be removed. * @method unsubscribeAll * @param type {string} The type, or name of the event * @deprecated use detachAll */ unsubscribeAll: function() { Y.log('EventTarget unsubscribeAll() is deprecated, use detachAll()', 'warn', 'deprecated'); return this.detachAll.apply(this, arguments); }, /** * Creates a new custom event of the specified type. If a custom event * by that name already exists, it will not be re-created. In either * case the custom event is returned. * * @method publish * * @param type {string} the type, or name of the event * @param opts {object} optional config params. Valid properties are: * * <ul> * <li> * 'broadcast': whether or not the YUI instance and YUI global are notified when the event is fired (false) * </li> * <li> * 'bubbles': whether or not this event bubbles (true) * Events can only bubble if emitFacade is true. * </li> * <li> * 'context': the default execution context for the listeners (this) * </li> * <li> * 'defaultFn': the default function to execute when this event fires if preventDefault was not called * </li> * <li> * 'emitFacade': whether or not this event emits a facade (false) * </li> * <li> * 'prefix': the prefix for this targets events, e.g., 'menu' in 'menu:click' * </li> * <li> * 'fireOnce': if an event is configured to fire once, new subscribers after * the fire will be notified immediately. * </li> * <li> * 'preventable': whether or not preventDefault() has an effect (true) * </li> * <li> * 'preventedFn': a function that is executed when preventDefault is called * </li> * <li> * 'queuable': whether or not this event can be queued during bubbling (false) * </li> * <li> * 'silent': if silent is true, debug messages are not provided for this event. * </li> * <li> * 'stoppedFn': a function that is executed when stopPropagation is called * </li> * * <li> * 'monitored': specifies whether or not this event should send notifications about * when the event has been attached, detached, or published. * </li> * <li> * 'type': the event type (valid option if not provided as the first parameter to publish) * </li> * </ul> * * @return {CustomEvent} the custom event * */ publish: function(type, opts) { var events, ce, ret, pre = this._yuievt.config.prefix; type = (pre) ? _getType(type, pre) : type; this._monitor('publish', type, { args: arguments }); if (L.isObject(type)) { ret = {}; Y.each(type, function(v, k) { ret[k] = this.publish(k, v || opts); }, this); return ret; } events = this._yuievt.events; ce = events[type]; if (ce) { // ce.log("publish applying new config to published event: '"+type+"' exists", 'info', 'event'); if (opts) { ce.applyConfig(opts, true); } } else { // apply defaults ce = new Y.CustomEvent(type, (opts) ? Y.mix(opts, this._yuievt.defaults) : this._yuievt.defaults); events[type] = ce; } // make sure we turn the broadcast flag off if this // event was published as a result of bubbling // if (opts instanceof Y.CustomEvent) { // events[type].broadcast = false; // } return events[type]; }, /** * This is the entry point for the event monitoring system. * You can monitor 'attach', 'detach', 'fire', and 'publish'. * When configured, these events generate an event. click -> * click_attach, click_detach, click_publish -- these can * be subscribed to like other events to monitor the event * system. Inividual published events can have monitoring * turned on or off (publish can't be turned off before it * it published) by setting the events 'monitor' config. * * @private */ _monitor: function(what, type, o) { var monitorevt, ce = this.getEvent(type); if ((this._yuievt.config.monitored && (!ce || ce.monitored)) || (ce && ce.monitored)) { monitorevt = type + '_' + what; // Y.log('monitoring: ' + monitorevt); o.monitored = what; this.fire.call(this, monitorevt, o); } }, /** * Fire a custom event by name. The callback functions will be executed * from the context specified when the event was created, and with the * following parameters. * * If the custom event object hasn't been created, then the event hasn't * been published and it has no subscribers. For performance sake, we * immediate exit in this case. This means the event won't bubble, so * if the intention is that a bubble target be notified, the event must * be published on this object first. * * The first argument is the event type, and any additional arguments are * passed to the listeners as parameters. If the first of these is an * object literal, and the event is configured to emit an event facade, * that object is mixed into the event facade and the facade is provided * in place of the original object. * * @method fire * @param type {String|Object} The type of the event, or an object that contains * a 'type' property. * @param arguments {Object*} an arbitrary set of parameters to pass to * the handler. If the first of these is an object literal and the event is * configured to emit an event facade, the event facade will replace that * parameter after the properties the object literal contains are copied to * the event facade. * @return {EventTarget} the event host * */ fire: function(type) { var typeIncluded = L.isString(type), t = (typeIncluded) ? type : (type && type.type), ce, ret, pre = this._yuievt.config.prefix, ce2, args = (typeIncluded) ? Y.Array(arguments, 1, true) : arguments; t = (pre) ? _getType(t, pre) : t; this._monitor('fire', t, { args: args }); ce = this.getEvent(t, true); ce2 = this.getSibling(t, ce); if (ce2 && !ce) { ce = this.publish(t); } // this event has not been published or subscribed to if (!ce) { if (this._yuievt.hasTargets) { return this.bubble({ type: t }, args, this); } // otherwise there is nothing to be done ret = true; } else { ce.sibling = ce2; ret = ce.fire.apply(ce, args); } return (this._yuievt.chain) ? this : ret; }, getSibling: function(type, ce) { var ce2; // delegate to *:type events if there are subscribers if (type.indexOf(PREFIX_DELIMITER) > -1) { type = _wildType(type); // console.log(type); ce2 = this.getEvent(type, true); if (ce2) { // console.log("GOT ONE: " + type); ce2.applyConfig(ce); ce2.bubbles = false; ce2.broadcast = 0; // ret = ce2.fire.apply(ce2, a); } } return ce2; }, /** * Returns the custom event of the provided type has been created, a * falsy value otherwise * @method getEvent * @param type {string} the type, or name of the event * @param prefixed {string} if true, the type is prefixed already * @return {CustomEvent} the custom event or null */ getEvent: function(type, prefixed) { var pre, e; if (!prefixed) { pre = this._yuievt.config.prefix; type = (pre) ? _getType(type, pre) : type; } e = this._yuievt.events; return e[type] || null; }, /** * Subscribe to a custom event hosted by this object. The * supplied callback will execute after any listeners add * via the subscribe method, and after the default function, * if configured for the event, has executed. * @method after * @param type {string} The type of the event * @param fn {Function} The callback * @param context {object} optional execution context. * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * @return the event target or a detach handle per 'chain' config */ after: function(type, fn) { var a = Y.Array(arguments, 0, true); switch (L.type(type)) { case 'function': return Y.Do.after.apply(Y.Do, arguments); case 'object': a[0]._after = true; break; default: a[0] = AFTER_PREFIX + type; } return this.on.apply(this, a); }, /** * Executes the callback before a DOM event, custom event * or method. If the first argument is a function, it * is assumed the target is a method. For DOM and custom * events, this is an alias for Y.on. * * For DOM and custom events: * type, callback, context, 0-n arguments * * For methods: * callback, object (method host), methodName, context, 0-n arguments * * @method before * @return detach handle */ before: function() { return this.on.apply(this, arguments); } }; Y.EventTarget = ET; // make Y an event target Y.mix(Y, ET.prototype, false, false, { bubbles: false }); ET.call(Y); YUI.Env.globalEvents = YUI.Env.globalEvents || new ET(); /** * Hosts YUI page level events. This is where events bubble to * when the broadcast config is set to 2. This property is * only available if the custom event module is loaded. * @property Global * @type EventTarget * @for YUI */ Y.Global = YUI.Env.globalEvents; // @TODO implement a global namespace function on Y.Global? })(); /** * <code>YUI</code>'s <code>on</code> method is a unified interface for subscribing to * most events exposed by YUI. This includes custom events, DOM events, and * function events. <code>detach</code> is also provided to remove listeners * serviced by this function. * * The signature that <code>on</code> accepts varies depending on the type * of event being consumed. Refer to the specific methods that will * service a specific request for additional information about subscribing * to that type of event. * * <ul> * <li>Custom events. These events are defined by various * modules in the library. This type of event is delegated to * <code>EventTarget</code>'s <code>on</code> method. * <ul> * <li>The type of the event</li> * <li>The callback to execute</li> * <li>An optional context object</li> * <li>0..n additional arguments to supply the callback.</li> * </ul> * Example: * <code>Y.on('domready', function() { // start work });</code> * </li> * <li>DOM events. These are moments reported by the browser related * to browser functionality and user interaction. * This type of event is delegated to <code>Event</code>'s * <code>attach</code> method. * <ul> * <li>The type of the event</li> * <li>The callback to execute</li> * <li>The specification for the Node(s) to attach the listener * to. This can be a selector, collections, or Node/Element * refereces.</li> * <li>An optional context object</li> * <li>0..n additional arguments to supply the callback.</li> * </ul> * Example: * <code>Y.on('click', function(e) { // something was clicked }, '#someelement');</code> * </li> * <li>Function events. These events can be used to react before or after a * function is executed. This type of event is delegated to <code>Event.Do</code>'s * <code>before</code> method. * <ul> * <li>The callback to execute</li> * <li>The object that has the function that will be listened for.</li> * <li>The name of the function to listen for.</li> * <li>An optional context object</li> * <li>0..n additional arguments to supply the callback.</li> * </ul> * Example <code>Y.on(function(arg1, arg2, etc) { // obj.methodname was executed }, obj 'methodname');</code> * </li> * </ul> * * <code>on</code> corresponds to the moment before any default behavior of * the event. <code>after</code> works the same way, but these listeners * execute after the event's default behavior. <code>before</code> is an * alias for <code>on</code>. * * @method on * @param type** event type (this parameter does not apply for function events) * @param fn the callback * @param target** a descriptor for the target (applies to custom events only). * For function events, this is the object that contains the function to * execute. * @param extra** 0..n Extra information a particular event may need. These * will be documented with the event. In the case of function events, this * is the name of the function to execute on the host. In the case of * delegate listeners, this is the event delegation specification. * @param context optionally change the value of 'this' in the callback * @param args* 0..n additional arguments to pass to the callback. * @return the event target or a detach handle per 'chain' config * @for YUI */ /** * Listen for an event one time. Equivalent to <code>on</code>, except that * the listener is immediately detached when executed. * @see on * @method once * @param type** event type (this parameter does not apply for function events) * @param fn the callback * @param target** a descriptor for the target (applies to custom events only). * For function events, this is the object that contains the function to * execute. * @param extra** 0..n Extra information a particular event may need. These * will be documented with the event. In the case of function events, this * is the name of the function to execute on the host. In the case of * delegate listeners, this is the event delegation specification. * @param context optionally change the value of 'this' in the callback * @param args* 0..n additional arguments to pass to the callback. * @return the event target or a detach handle per 'chain' config * @for YUI */ /** * after() is a unified interface for subscribing to * most events exposed by YUI. This includes custom events, * DOM events, and AOP events. This works the same way as * the on() function, only it operates after any default * behavior for the event has executed. @see <code>on</code> for more * information. * @method after * @param type event type (this parameter does not apply for function events) * @param fn the callback * @param target a descriptor for the target (applies to custom events only). * For function events, this is the object that contains the function to * execute. * @param extra 0..n Extra information a particular event may need. These * will be documented with the event. In the case of function events, this * is the name of the function to execute on the host. In the case of * delegate listeners, this is the event delegation specification. * @param context optionally change the value of 'this' in the callback * @param args* 0..n additional arguments to pass to the callback. * @return the event target or a detach handle per 'chain' config * @for YUI */ }, '@VERSION@' ,{requires:['oop']});
src/components/video_detail.js
iAmNawa/ReactJS
import React from 'react'; const VideoDetail = ({video}) => { if (!video) { return <div>Loading...</div> } const videoId = video.id.videoId; const url = `https://www.youtube.com/embed/${videoId}`; return ( <div className="video-detail col-md-8"> <div className="embed-responsive embed-responsive-16by9"> <iframe className="embed-responsive-item" src={url}></iframe> </div> <div className="details"> <div>{video.snippet.title}</div> <div>{video.snippet.description}</div> </div> </div> ); }; export default VideoDetail;
app/javascript/mastodon/components/status_content.js
ikuradon/mastodon
import React from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import { FormattedMessage } from 'react-intl'; import Permalink from './permalink'; import classnames from 'classnames'; import PollContainer from 'mastodon/containers/poll_container'; import Icon from 'mastodon/components/icon'; import { autoPlayGif } from 'mastodon/initial_state'; const MAX_HEIGHT = 642; // 20px * 32 (+ 2px padding at the top) export default class StatusContent extends React.PureComponent { static contextTypes = { router: PropTypes.object, }; static propTypes = { status: ImmutablePropTypes.map.isRequired, expanded: PropTypes.bool, showThread: PropTypes.bool, onExpandedToggle: PropTypes.func, onClick: PropTypes.func, collapsable: PropTypes.bool, onCollapsedToggle: PropTypes.func, quote: PropTypes.bool, }; state = { hidden: true, }; _updateStatusLinks () { const node = this.node; if (!node) { return; } const links = node.querySelectorAll('a'); for (var i = 0; i < links.length; ++i) { let link = links[i]; if (link.classList.contains('status-link')) { continue; } link.classList.add('status-link'); let mention = this.props.status.get('mentions').find(item => link.href === item.get('url')); if (mention) { link.addEventListener('click', this.onMentionClick.bind(this, mention), false); link.setAttribute('title', mention.get('acct')); } else if (link.textContent[0] === '#' || (link.previousSibling && link.previousSibling.textContent && link.previousSibling.textContent[link.previousSibling.textContent.length - 1] === '#')) { link.addEventListener('click', this.onHashtagClick.bind(this, link.text), false); } else { link.setAttribute('title', link.href); link.classList.add('unhandled-link'); } link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener noreferrer'); } if (this.props.status.get('collapsed', null) === null) { let collapsed = this.props.collapsable && this.props.onClick && node.clientHeight > MAX_HEIGHT && this.props.status.get('spoiler_text').length === 0; if(this.props.onCollapsedToggle) this.props.onCollapsedToggle(collapsed); this.props.status.set('collapsed', collapsed); } } handleMouseEnter = ({ currentTarget }) => { if (autoPlayGif) { return; } const emojis = currentTarget.querySelectorAll('.custom-emoji'); for (var i = 0; i < emojis.length; i++) { let emoji = emojis[i]; emoji.src = emoji.getAttribute('data-original'); } } handleMouseLeave = ({ currentTarget }) => { if (autoPlayGif) { return; } const emojis = currentTarget.querySelectorAll('.custom-emoji'); for (var i = 0; i < emojis.length; i++) { let emoji = emojis[i]; emoji.src = emoji.getAttribute('data-static'); } } componentDidMount () { this._updateStatusLinks(); } componentDidUpdate () { this._updateStatusLinks(); } onMentionClick = (mention, e) => { if (this.context.router && e.button === 0 && !(e.ctrlKey || e.metaKey)) { e.preventDefault(); this.context.router.history.push(`/@${mention.get('acct')}`); } } onHashtagClick = (hashtag, e) => { hashtag = hashtag.replace(/^#/, ''); if (this.context.router && e.button === 0 && !(e.ctrlKey || e.metaKey)) { e.preventDefault(); this.context.router.history.push(`/tags/${hashtag}`); } } handleMouseDown = (e) => { this.startXY = [e.clientX, e.clientY]; } handleMouseUp = (e) => { if (!this.startXY) { return; } const [ startX, startY ] = this.startXY; const [ deltaX, deltaY ] = [Math.abs(e.clientX - startX), Math.abs(e.clientY - startY)]; let element = e.target; while (element) { if (element.localName === 'button' || element.localName === 'a' || element.localName === 'label') { return; } element = element.parentNode; } if (deltaX + deltaY < 5 && e.button === 0 && this.props.onClick) { this.props.onClick(); } this.startXY = null; } handleSpoilerClick = (e) => { e.preventDefault(); if (this.props.onExpandedToggle) { // The parent manages the state this.props.onExpandedToggle(); } else { this.setState({ hidden: !this.state.hidden }); } } setRef = (c) => { this.node = c; } render () { const { status, quote } = this.props; const hidden = this.props.onExpandedToggle ? !this.props.expanded : this.state.hidden; const renderReadMore = this.props.onClick && status.get('collapsed'); const renderViewThread = this.props.showThread && status.get('in_reply_to_id') && status.get('in_reply_to_account_id') === status.getIn(['account', 'id']); const content = { __html: status.get('contentHtml') }; const spoilerContent = { __html: status.get('spoilerHtml') }; const classNames = classnames('status__content', { 'status__content--with-action': this.props.onClick && this.context.router, 'status__content--with-spoiler': status.get('spoiler_text').length > 0, 'status__content--collapsed': renderReadMore, }); const showThreadButton = ( <button className='status__content__read-more-button' onClick={this.props.onClick}> <FormattedMessage id='status.show_thread' defaultMessage='Show thread' /> </button> ); const readMoreButton = ( <button className='status__content__read-more-button' onClick={this.props.onClick} key='read-more'> <FormattedMessage id='status.read_more' defaultMessage='Read more' /><Icon id='angle-right' fixedWidth /> </button> ); if (status.get('spoiler_text').length > 0) { let mentionsPlaceholder = ''; const mentionLinks = status.get('mentions').map(item => ( <Permalink to={`/@${item.get('acct')}`} href={item.get('url')} key={item.get('id')} className='mention'> @<span>{item.get('username')}</span> </Permalink> )).reduce((aggregate, item) => [...aggregate, item, ' '], []); const toggleText = hidden ? <FormattedMessage id='status.show_more' defaultMessage='Show more' /> : <FormattedMessage id='status.show_less' defaultMessage='Show less' />; if (hidden) { mentionsPlaceholder = <div>{mentionLinks}</div>; } return ( <div className={classNames} ref={this.setRef} tabIndex='0' onMouseDown={this.handleMouseDown} onMouseUp={this.handleMouseUp} onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave}> <p style={{ marginBottom: hidden && status.get('mentions').isEmpty() ? '0px' : null }}> <span dangerouslySetInnerHTML={spoilerContent} className='translate' /> {' '} <button tabIndex='0' className={`status__content__spoiler-link ${hidden ? 'status__content__spoiler-link--show-more' : 'status__content__spoiler-link--show-less'}`} onClick={this.handleSpoilerClick}>{toggleText}</button> </p> {mentionsPlaceholder} <div tabIndex={!hidden ? 0 : null} className={`status__content__text ${!hidden ? 'status__content__text--visible' : ''} translate`} dangerouslySetInnerHTML={content} /> {!hidden && !!status.get('poll') && <PollContainer pollId={status.get('poll')} />} {renderViewThread && showThreadButton} {!quote && !hidden && !!status.get('poll') && <PollContainer pollId={status.get('poll')} />} </div> ); } else if (this.props.onClick) { const output = [ <div className={classNames} ref={this.setRef} tabIndex='0' onMouseDown={this.handleMouseDown} onMouseUp={this.handleMouseUp} key='status-content' onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave}> <div className='status__content__text status__content__text--visible translate' dangerouslySetInnerHTML={content} /> {!!status.get('poll') && <PollContainer pollId={status.get('poll')} />} {renderViewThread && showThreadButton} {!quote && !!status.get('poll') && <PollContainer pollId={status.get('poll')} />} </div>, ]; if (renderReadMore) { output.push(readMoreButton); } return output; } else { return ( <div className={classNames} ref={this.setRef} tabIndex='0' onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave}> <div className='status__content__text status__content__text--visible translate' dangerouslySetInnerHTML={content} /> {!!status.get('poll') && <PollContainer pollId={status.get('poll')} />} {renderViewThread && showThreadButton} {!quote && !!status.get('poll') && <PollContainer pollId={status.get('poll')} />} </div> ); } } }
resources/public/js/compiled/out/reagent/core.js
Reefersleep/appstates
// Compiled by ClojureScript 0.0-3297 {} goog.provide('reagent.core'); goog.require('cljs.core'); goog.require('reagent.impl.util'); goog.require('reagent.impl.component'); goog.require('reagent.interop'); goog.require('reagent.ratom'); goog.require('cljsjs.react'); goog.require('reagent.impl.template'); goog.require('reagent.impl.batching'); goog.require('reagent.debug'); reagent.core.is_client = reagent.impl.util.is_client; /** * Create a native React element, by calling React.createElement directly. * * That means the second argument must be a javascript object (or nil), and * that any Reagent hiccup forms must be processed with as-element. For example * like this: * * (r/create-element "div" #js{:className "foo"} * "Hi " (r/as-element [:strong "world!"]) * * which is equivalent to * * [:div.foo "Hi" [:strong "world!"]] */ reagent.core.create_element = (function reagent$core$create_element(){ var G__18308 = arguments.length; switch (G__18308) { case 1: return reagent.core.create_element.cljs$core$IFn$_invoke$arity$1((arguments[(0)])); break; case 2: return reagent.core.create_element.cljs$core$IFn$_invoke$arity$2((arguments[(0)]),(arguments[(1)])); break; case 3: return reagent.core.create_element.cljs$core$IFn$_invoke$arity$3((arguments[(0)]),(arguments[(1)]),(arguments[(2)])); break; default: var argseq__17088__auto__ = (new cljs.core.IndexedSeq(Array.prototype.slice.call(arguments,(3)),(0))); return reagent.core.create_element.cljs$core$IFn$_invoke$arity$variadic((arguments[(0)]),(arguments[(1)]),(arguments[(2)]),argseq__17088__auto__); } }); reagent.core.create_element.cljs$core$IFn$_invoke$arity$1 = (function (type){ return reagent.core.create_element.call(null,type,null); }); reagent.core.create_element.cljs$core$IFn$_invoke$arity$2 = (function (type,props){ if(!(cljs.core.map_QMARK_.call(null,props))){ } else { throw (new Error([cljs.core.str("Assert failed: "),cljs.core.str(cljs.core.pr_str.call(null,cljs.core.list(new cljs.core.Symbol(null,"not","not",1044554643,null),cljs.core.list(new cljs.core.Symbol(null,"map?","map?",-1780568534,null),new cljs.core.Symbol(null,"props","props",2093813254,null)))))].join(''))); } return React.createElement(type,props); }); reagent.core.create_element.cljs$core$IFn$_invoke$arity$3 = (function (type,props,child){ if(!(cljs.core.map_QMARK_.call(null,props))){ } else { throw (new Error([cljs.core.str("Assert failed: "),cljs.core.str(cljs.core.pr_str.call(null,cljs.core.list(new cljs.core.Symbol(null,"not","not",1044554643,null),cljs.core.list(new cljs.core.Symbol(null,"map?","map?",-1780568534,null),new cljs.core.Symbol(null,"props","props",2093813254,null)))))].join(''))); } return React.createElement(type,props,child); }); reagent.core.create_element.cljs$core$IFn$_invoke$arity$variadic = (function (type,props,child,children){ if(!(cljs.core.map_QMARK_.call(null,props))){ } else { throw (new Error([cljs.core.str("Assert failed: "),cljs.core.str(cljs.core.pr_str.call(null,cljs.core.list(new cljs.core.Symbol(null,"not","not",1044554643,null),cljs.core.list(new cljs.core.Symbol(null,"map?","map?",-1780568534,null),new cljs.core.Symbol(null,"props","props",2093813254,null)))))].join(''))); } return cljs.core.apply.call(null,React.createElement,type,props,child,children); }); reagent.core.create_element.cljs$lang$applyTo = (function (seq18303){ var G__18304 = cljs.core.first.call(null,seq18303); var seq18303__$1 = cljs.core.next.call(null,seq18303); var G__18305 = cljs.core.first.call(null,seq18303__$1); var seq18303__$2 = cljs.core.next.call(null,seq18303__$1); var G__18306 = cljs.core.first.call(null,seq18303__$2); var seq18303__$3 = cljs.core.next.call(null,seq18303__$2); return reagent.core.create_element.cljs$core$IFn$_invoke$arity$variadic(G__18304,G__18305,G__18306,seq18303__$3); }); reagent.core.create_element.cljs$lang$maxFixedArity = (3); /** * Turns a vector of Hiccup syntax into a React element. Returns form unchanged if it is not a vector. */ reagent.core.as_element = (function reagent$core$as_element(form){ return reagent.impl.template.as_element.call(null,form); }); /** * Returns an adapter for a native React class, that may be used * just like a Reagent component function or class in Hiccup forms. */ reagent.core.adapt_react_class = (function reagent$core$adapt_react_class(c){ return reagent.impl.template.adapt_react_class.call(null,c); }); /** * Returns an adapter for a Reagent component, that may be used from * React, for example in JSX. A single argument, props, is passed to * the component, converted to a map. */ reagent.core.reactify_component = (function reagent$core$reactify_component(c){ return reagent.impl.component.reactify_component.call(null,c); }); /** * Render a Reagent component into the DOM. The first argument may be * either a vector (using Reagent's Hiccup syntax), or a React element. The second argument should be a DOM node. * * Optionally takes a callback that is called when the component is in place. * * Returns the mounted component instance. */ reagent.core.render = (function reagent$core$render(){ var G__18311 = arguments.length; switch (G__18311) { case 2: return reagent.core.render.cljs$core$IFn$_invoke$arity$2((arguments[(0)]),(arguments[(1)])); break; case 3: return reagent.core.render.cljs$core$IFn$_invoke$arity$3((arguments[(0)]),(arguments[(1)]),(arguments[(2)])); break; default: throw (new Error([cljs.core.str("Invalid arity: "),cljs.core.str(arguments.length)].join(''))); } }); reagent.core.render.cljs$core$IFn$_invoke$arity$2 = (function (comp,container){ return reagent.core.render.call(null,comp,container,null); }); reagent.core.render.cljs$core$IFn$_invoke$arity$3 = (function (comp,container,callback){ var f = (function (){ return reagent.core.as_element.call(null,((cljs.core.fn_QMARK_.call(null,comp))?comp.call(null):comp)); }); return reagent.impl.util.render_component.call(null,f,container,callback); }); reagent.core.render.cljs$lang$maxFixedArity = 3; /** * Remove a component from the given DOM node. */ reagent.core.unmount_component_at_node = (function reagent$core$unmount_component_at_node(container){ return reagent.impl.util.unmount_component_at_node.call(null,container); }); /** * Turns a component into an HTML string. */ reagent.core.render_to_string = (function reagent$core$render_to_string(component){ var _STAR_non_reactive_STAR_18314 = reagent.impl.component._STAR_non_reactive_STAR_; reagent.impl.component._STAR_non_reactive_STAR_ = true; try{return (React["renderToString"])(reagent.core.as_element.call(null,component)); }finally {reagent.impl.component._STAR_non_reactive_STAR_ = _STAR_non_reactive_STAR_18314; }}); reagent.core.as_component = reagent.core.as_element; reagent.core.render_component = reagent.core.render; reagent.core.render_component_to_string = reagent.core.render_to_string; /** * Turns a component into an HTML string, without data-react-id attributes, etc. */ reagent.core.render_to_static_markup = (function reagent$core$render_to_static_markup(component){ var _STAR_non_reactive_STAR_18316 = reagent.impl.component._STAR_non_reactive_STAR_; reagent.impl.component._STAR_non_reactive_STAR_ = true; try{return (React["renderToStaticMarkup"])(reagent.core.as_element.call(null,component)); }finally {reagent.impl.component._STAR_non_reactive_STAR_ = _STAR_non_reactive_STAR_18316; }}); /** * Force re-rendering of all mounted Reagent components. This is * probably only useful in a development environment, when you want to * update components in response to some dynamic changes to code. * * Note that force-update-all may not update root components. This * happens if a component 'foo' is mounted with `(render [foo])` (since * functions are passed by value, and not by reference, in * ClojureScript). To get around this you'll have to introduce a layer * of indirection, for example by using `(render [#'foo])` instead. */ reagent.core.force_update_all = (function reagent$core$force_update_all(){ return reagent.impl.util.force_update_all.call(null); }); goog.exportSymbol('reagent.core.force_update_all', reagent.core.force_update_all); /** * Create a component, React style. Should be called with a map, * looking like this: * {:get-initial-state (fn [this]) * :component-will-receive-props (fn [this new-argv]) * :should-component-update (fn [this old-argv new-argv]) * :component-will-mount (fn [this]) * :component-did-mount (fn [this]) * :component-will-update (fn [this new-argv]) * :component-did-update (fn [this old-argv]) * :component-will-unmount (fn [this]) * :reagent-render (fn [args....]) ;; or :render (fn [this]) * } * * Everything is optional, except either :reagent-render or :render. */ reagent.core.create_class = (function reagent$core$create_class(spec){ return reagent.impl.component.create_class.call(null,spec); }); /** * Returns the current React component (a.k.a this) in a component * function. */ reagent.core.current_component = (function reagent$core$current_component(){ return reagent.impl.component._STAR_current_component_STAR_; }); /** * Returns an atom containing a components state. */ reagent.core.state_atom = (function reagent$core$state_atom(this$){ if(cljs.core.truth_(reagent.impl.util.reagent_component_QMARK_.call(null,this$))){ } else { throw (new Error([cljs.core.str("Assert failed: "),cljs.core.str(cljs.core.pr_str.call(null,cljs.core.list(new cljs.core.Symbol("util","reagent-component?","util/reagent-component?",1508385933,null),new cljs.core.Symbol(null,"this","this",1028897902,null))))].join(''))); } return reagent.impl.component.state_atom.call(null,this$); }); /** * Returns the state of a component, as set with replace-state or set-state. * Equivalent to (deref (r/state-atom this)) */ reagent.core.state = (function reagent$core$state(this$){ if(cljs.core.truth_(reagent.impl.util.reagent_component_QMARK_.call(null,this$))){ } else { throw (new Error([cljs.core.str("Assert failed: "),cljs.core.str(cljs.core.pr_str.call(null,cljs.core.list(new cljs.core.Symbol("util","reagent-component?","util/reagent-component?",1508385933,null),new cljs.core.Symbol(null,"this","this",1028897902,null))))].join(''))); } return cljs.core.deref.call(null,reagent.core.state_atom.call(null,this$)); }); /** * Set state of a component. * Equivalent to (reset! (state-atom this) new-state) */ reagent.core.replace_state = (function reagent$core$replace_state(this$,new_state){ if(cljs.core.truth_(reagent.impl.util.reagent_component_QMARK_.call(null,this$))){ } else { throw (new Error([cljs.core.str("Assert failed: "),cljs.core.str(cljs.core.pr_str.call(null,cljs.core.list(new cljs.core.Symbol("util","reagent-component?","util/reagent-component?",1508385933,null),new cljs.core.Symbol(null,"this","this",1028897902,null))))].join(''))); } if(((new_state == null)) || (cljs.core.map_QMARK_.call(null,new_state))){ } else { throw (new Error([cljs.core.str("Assert failed: "),cljs.core.str(cljs.core.pr_str.call(null,cljs.core.list(new cljs.core.Symbol(null,"or","or",1876275696,null),cljs.core.list(new cljs.core.Symbol(null,"nil?","nil?",1612038930,null),new cljs.core.Symbol(null,"new-state","new-state",1150182315,null)),cljs.core.list(new cljs.core.Symbol(null,"map?","map?",-1780568534,null),new cljs.core.Symbol(null,"new-state","new-state",1150182315,null)))))].join(''))); } return cljs.core.reset_BANG_.call(null,reagent.core.state_atom.call(null,this$),new_state); }); /** * Merge component state with new-state. * Equivalent to (swap! (state-atom this) merge new-state) */ reagent.core.set_state = (function reagent$core$set_state(this$,new_state){ if(cljs.core.truth_(reagent.impl.util.reagent_component_QMARK_.call(null,this$))){ } else { throw (new Error([cljs.core.str("Assert failed: "),cljs.core.str(cljs.core.pr_str.call(null,cljs.core.list(new cljs.core.Symbol("util","reagent-component?","util/reagent-component?",1508385933,null),new cljs.core.Symbol(null,"this","this",1028897902,null))))].join(''))); } if(((new_state == null)) || (cljs.core.map_QMARK_.call(null,new_state))){ } else { throw (new Error([cljs.core.str("Assert failed: "),cljs.core.str(cljs.core.pr_str.call(null,cljs.core.list(new cljs.core.Symbol(null,"or","or",1876275696,null),cljs.core.list(new cljs.core.Symbol(null,"nil?","nil?",1612038930,null),new cljs.core.Symbol(null,"new-state","new-state",1150182315,null)),cljs.core.list(new cljs.core.Symbol(null,"map?","map?",-1780568534,null),new cljs.core.Symbol(null,"new-state","new-state",1150182315,null)))))].join(''))); } return cljs.core.swap_BANG_.call(null,reagent.core.state_atom.call(null,this$),cljs.core.merge,new_state); }); /** * Force a component to re-render immediately. * * If the second argument is true, child components will also be * re-rendered, even is their arguments have not changed. */ reagent.core.force_update = (function reagent$core$force_update(){ var G__18318 = arguments.length; switch (G__18318) { case 1: return reagent.core.force_update.cljs$core$IFn$_invoke$arity$1((arguments[(0)])); break; case 2: return reagent.core.force_update.cljs$core$IFn$_invoke$arity$2((arguments[(0)]),(arguments[(1)])); break; default: throw (new Error([cljs.core.str("Invalid arity: "),cljs.core.str(arguments.length)].join(''))); } }); reagent.core.force_update.cljs$core$IFn$_invoke$arity$1 = (function (this$){ return reagent.core.force_update.call(null,this$,false); }); reagent.core.force_update.cljs$core$IFn$_invoke$arity$2 = (function (this$,deep){ return reagent.impl.util.force_update.call(null,this$,deep); }); reagent.core.force_update.cljs$lang$maxFixedArity = 2; /** * Returns the props passed to a component. */ reagent.core.props = (function reagent$core$props(this$){ if(cljs.core.truth_(reagent.impl.util.reagent_component_QMARK_.call(null,this$))){ } else { throw (new Error([cljs.core.str("Assert failed: "),cljs.core.str(cljs.core.pr_str.call(null,cljs.core.list(new cljs.core.Symbol("util","reagent-component?","util/reagent-component?",1508385933,null),new cljs.core.Symbol(null,"this","this",1028897902,null))))].join(''))); } return reagent.impl.util.get_props.call(null,this$); }); /** * Returns the children passed to a component. */ reagent.core.children = (function reagent$core$children(this$){ if(cljs.core.truth_(reagent.impl.util.reagent_component_QMARK_.call(null,this$))){ } else { throw (new Error([cljs.core.str("Assert failed: "),cljs.core.str(cljs.core.pr_str.call(null,cljs.core.list(new cljs.core.Symbol("util","reagent-component?","util/reagent-component?",1508385933,null),new cljs.core.Symbol(null,"this","this",1028897902,null))))].join(''))); } return reagent.impl.util.get_children.call(null,this$); }); /** * Returns the entire Hiccup form passed to the component. */ reagent.core.argv = (function reagent$core$argv(this$){ if(cljs.core.truth_(reagent.impl.util.reagent_component_QMARK_.call(null,this$))){ } else { throw (new Error([cljs.core.str("Assert failed: "),cljs.core.str(cljs.core.pr_str.call(null,cljs.core.list(new cljs.core.Symbol("util","reagent-component?","util/reagent-component?",1508385933,null),new cljs.core.Symbol(null,"this","this",1028897902,null))))].join(''))); } return reagent.impl.util.get_argv.call(null,this$); }); /** * Returns the root DOM node of a mounted component. */ reagent.core.dom_node = (function reagent$core$dom_node(this$){ return (this$["getDOMNode"])(); }); /** * Utility function that merges two maps, handling :class and :style * specially, like React's transferPropsTo. */ reagent.core.merge_props = (function reagent$core$merge_props(defaults,props){ return reagent.impl.util.merge_props.call(null,defaults,props); }); /** * Render dirty components immediately to the DOM. * * Note that this may not work in event handlers, since React.js does * batching of updates there. */ reagent.core.flush = (function reagent$core$flush(){ return reagent.impl.batching.flush.call(null); }); /** * Like clojure.core/atom, except that it keeps track of derefs. * Reagent components that derefs one of these are automatically * re-rendered. */ reagent.core.atom = (function reagent$core$atom(){ var G__18323 = arguments.length; switch (G__18323) { case 1: return reagent.core.atom.cljs$core$IFn$_invoke$arity$1((arguments[(0)])); break; default: var argseq__17088__auto__ = (new cljs.core.IndexedSeq(Array.prototype.slice.call(arguments,(1)),(0))); return reagent.core.atom.cljs$core$IFn$_invoke$arity$variadic((arguments[(0)]),argseq__17088__auto__); } }); reagent.core.atom.cljs$core$IFn$_invoke$arity$1 = (function (x){ return reagent.ratom.atom.call(null,x); }); reagent.core.atom.cljs$core$IFn$_invoke$arity$variadic = (function (x,rest){ return cljs.core.apply.call(null,reagent.ratom.atom,x,rest); }); reagent.core.atom.cljs$lang$applyTo = (function (seq18320){ var G__18321 = cljs.core.first.call(null,seq18320); var seq18320__$1 = cljs.core.next.call(null,seq18320); return reagent.core.atom.cljs$core$IFn$_invoke$arity$variadic(G__18321,seq18320__$1); }); reagent.core.atom.cljs$lang$maxFixedArity = (1); /** * Provide a combination of value and callback, that looks like an atom. * * The first argument can be any value, that will be returned when the * result is deref'ed. * * The second argument should be a function, that is called with the * optional extra arguments provided to wrap, and the new value of the * resulting 'atom'. * * Use for example like this: * * (wrap (:foo @state) * swap! state assoc :foo) * * Probably useful only for passing to child components. */ reagent.core.wrap = (function reagent$core$wrap(){ var argseq__17077__auto__ = ((((2) < arguments.length))?(new cljs.core.IndexedSeq(Array.prototype.slice.call(arguments,(2)),(0))):null); return reagent.core.wrap.cljs$core$IFn$_invoke$arity$variadic((arguments[(0)]),(arguments[(1)]),argseq__17077__auto__); }); reagent.core.wrap.cljs$core$IFn$_invoke$arity$variadic = (function (value,reset_fn,args){ if(cljs.core.ifn_QMARK_.call(null,reset_fn)){ } else { throw (new Error([cljs.core.str("Assert failed: "),cljs.core.str(cljs.core.pr_str.call(null,cljs.core.list(new cljs.core.Symbol(null,"ifn?","ifn?",-2106461064,null),new cljs.core.Symbol(null,"reset-fn","reset-fn",949643977,null))))].join(''))); } return reagent.ratom.make_wrapper.call(null,value,reset_fn,args); }); reagent.core.wrap.cljs$lang$maxFixedArity = (2); reagent.core.wrap.cljs$lang$applyTo = (function (seq18325){ var G__18326 = cljs.core.first.call(null,seq18325); var seq18325__$1 = cljs.core.next.call(null,seq18325); var G__18327 = cljs.core.first.call(null,seq18325__$1); var seq18325__$2 = cljs.core.next.call(null,seq18325__$1); return reagent.core.wrap.cljs$core$IFn$_invoke$arity$variadic(G__18326,G__18327,seq18325__$2); }); /** * Provide a cursor into a Reagent atom. * * Behaves like a Reagent atom but focuses updates and derefs to * the specified path within the wrapped Reagent atom. e.g., * (let [c (cursor ra [:nested :content])] * ... @c ;; equivalent to (get-in @ra [:nested :content]) * ... (reset! c 42) ;; equivalent to (swap! ra assoc-in [:nested :content] 42) * ... (swap! c inc) ;; equivalence to (swap! ra update-in [:nested :content] inc) * ) * * The first parameter can also be a function, that should look something * like this: * * (defn set-get * ([k] (get-in @state k)) * ([k v] (swap! state assoc-in k v))) * * The function will be called with one argument – the path passed to * cursor – when the cursor is deref'ed, and two arguments (path and new * value) when the cursor is modified. * * Given that set-get function, (and that state is a Reagent atom, or * another cursor) these cursors are equivalent: * (cursor state [:foo]) and (cursor set-get [:foo]). */ reagent.core.cursor = (function reagent$core$cursor(src,path){ return reagent.ratom.cursor.call(null,src,path); }); /** * Run f using requestAnimationFrame or equivalent. */ reagent.core.next_tick = (function reagent$core$next_tick(f){ return reagent.impl.batching.next_tick.call(null,f); }); /** * Works just like clojure.core/partial, except that it is an IFn, and * the result can be compared with = */ reagent.core.partial = (function reagent$core$partial(){ var argseq__17077__auto__ = ((((1) < arguments.length))?(new cljs.core.IndexedSeq(Array.prototype.slice.call(arguments,(1)),(0))):null); return reagent.core.partial.cljs$core$IFn$_invoke$arity$variadic((arguments[(0)]),argseq__17077__auto__); }); reagent.core.partial.cljs$core$IFn$_invoke$arity$variadic = (function (f,args){ return (new reagent.impl.util.partial_ifn(f,args,null)); }); reagent.core.partial.cljs$lang$maxFixedArity = (1); reagent.core.partial.cljs$lang$applyTo = (function (seq18328){ var G__18329 = cljs.core.first.call(null,seq18328); var seq18328__$1 = cljs.core.next.call(null,seq18328); return reagent.core.partial.cljs$core$IFn$_invoke$arity$variadic(G__18329,seq18328__$1); }); //# sourceMappingURL=core.js.map?rel=1440502152717
app/js/containers/CircleDetailContainer.js
sgt39007/waji_redux
import React, { PropTypes } from 'react'; import { connect } from 'react-redux'; import * as DetailActions from '../redux/actions/DetailActions'; import { bindActionCreators } from 'redux'; import * as AppActions from '../redux/actions/AppActions'; import { FriendDetail } from '../components' import { View, } from 'amazeui-touch'; class CircleDetailContainer extends React.Component { componentWillMount() { const { appActions } = this.props; appActions.hideTabbar(true); appActions.hideNavLeft(false); appActions.setNavTitle('详细信息'); const { type } = this.props.params; appActions.setNavBackLink(`/circle/${type}`); } renderComponent = () => { const { detail, detailActions, friends, worlds, params } = this.props; const { item, catid} = this.props.location.query; let circles; if (params.type == 'friend') { circles = friends; } else { circles = worlds; } return ( <FriendDetail circles={circles} item={item} catid={catid} id={params.id} detail={detail} detailActions={detailActions}/> ); }; render() { return ( <View> {this.renderComponent()} </View> ); } } CircleDetailContainer.propTypes = { friends: PropTypes.object.isRequired, worlds: PropTypes.object.isRequired, detail: PropTypes.object.isRequired, appActions: PropTypes.object.isRequired, detailActions: PropTypes.object.isRequired }; function mapStateToProps(state) { return { friends: state.friends, worlds: state.worlds, detail:state.detail } } function mapDispatchToProps(dispatch) { return { appActions : bindActionCreators(AppActions, dispatch), detailActions : bindActionCreators(DetailActions, dispatch) } } export default connect(mapStateToProps, mapDispatchToProps)(CircleDetailContainer)
src/app.js
dhis2/datim-data-export-log
if (process.env.NODE_ENV !== 'production') { jQuery.ajaxSetup({ headers: { Authorization: 'Basic ' + btoa('admin:district'), }, }); } import 'babel-polyfill'; import 'd2-ui/scss/DataTable.scss'; import React from 'react'; import {render, findDOMNode} from 'react-dom'; import HeaderBarComponent from 'd2-ui/lib/app-header/HeaderBar'; import headerBarStore$ from 'd2-ui/lib/app-header/headerBar.store'; import withStateFrom from 'd2-ui/lib/component-helpers/withStateFrom'; import {init, config, getInstance, getManifest} from 'd2/lib/d2'; import actions from './dataExportLog.actions'; import store from './dataExportLog.store'; import DataTable from 'd2-ui/lib/data-table/DataTable.component'; import reactTapEventPlugin from 'react-tap-event-plugin'; import RaisedButton from 'material-ui/RaisedButton'; import TextField from 'material-ui/TextField'; import log from 'loglevel'; import {helpers} from 'rx'; import LoadingMask from 'd2-ui/lib/loading-mask/LoadingMask.component'; import LinearProgress from 'material-ui/LinearProgress'; import FontIcon from 'material-ui/FontIcon'; import Paper from 'material-ui/Paper'; import Popover from 'material-ui/Popover/Popover'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import Checkbox from 'material-ui/Checkbox'; import DropDownMenu from 'material-ui/DropDownMenu'; import MenuItem from 'material-ui/MenuItem'; import DetailsBox from './DetailsBox.component'; import KeyboardArrowDownIcon from 'material-ui/svg-icons/hardware/keyboard-arrow-down'; import KeyboardArrowRightIcon from 'material-ui/svg-icons/hardware/keyboard-arrow-right'; import CheckCircleIcon from 'material-ui/svg-icons/action/check-circle'; import HighlightOffIcon from 'material-ui/svg-icons/action/highlight-off'; import '../css//bootstrap.css'; import '../css/stylesheet.css'; import '../js/bootstrap.min.js'; const HeaderBar = withStateFrom(headerBarStore$, HeaderBarComponent); config.i18n.strings.add('exported_at'); config.i18n.strings.add('exported_by'); reactTapEventPlugin(); const getStepLabel = function(stepIndex) { switch (stepIndex) { case 0: return 'Initiation'; case 1: return 'Metadata \nSynchronization'; case 2: return 'Adx Message \nGeneration'; case 3: return 'Success'; default: return 'Invalid step'; }; }; const getStatusStyle = function(status){ switch (status) { case STATUS_SUCCESS: return "success"; break; case STATUS_FAILURE: return "error"; break; default: return "warning"; break; } } getInstance() .then(d2 => { d2.i18n.translations.exported_at = 'Exported At'; d2.i18n.translations.exported_at = 'Export Type'; d2.i18n.translations.exported_by = 'Exported By'; d2.i18n.translations.created = 'Created'; d2.i18n.translations.id = 'Id'; d2.i18n.translations.href = 'Api URL'; d2.i18n.translations.download_adx = 'Download ADX Message'; d2.i18n.translations.status = 'Status'; d2.i18n.translations.period = 'Period'; }); const STATUS_SUCCESS = "SUCCESS"; const STATUS_FAILURE = "FAILURE"; const STATUS_WARNING = "WARNING"; const STATUS_INPROGRESS = "IN PROGRESS"; const OK = "ok checkmark"; const REMOVE = "remove checkmark"; const BUTTON_WARNING = "ok checkmark"; const BUTTON_STYLE_DEFAULT="default"; const ROLE_ALLOW_EXPORT =1; const ROLE_ALLOW_VIEW = 2; const ROLE_ALLOW_NOACCESS = 3; var accessPermission = ROLE_ALLOW_NOACCESS; var isSuperUser = false; function getUserRolesForCurrentUser(d2) { // Request all the roles for the currentUser from the api return d2.models.userRoles.list({ filter: `users.id:eq:${d2.currentUser.id}`, fields: 'id,name' }) .then(collection => collection.toArray()) .then(roles => new Set(roles.map(role => role.name))); } function formatDate(date) { var shortMonthNames = ["Jan", "Feb", "March", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; return shortMonthNames[date.getMonth()] + ' ' + date.getDate() + ', ' + date.getFullYear() + ' ' + date.getHours() + ':' + ('0'+ date.getMinutes()).slice(-2) + ':'+ ('0'+ date.getSeconds()).slice(-2); } const ExportLogList = React.createClass({ getInitialState() { return { log: [], isLoading: true, baseUrl: "", detailBox:{ open: false } }; }, componentWillMount() { getInstance().then(d2 => { const api = d2.Api.getApi(); this.setState({ baseUrl: api.baseUrl }); } ); actions.load() .subscribe(() => {}, (e) => { console.error(e); this.setState({ isLoading: false }); }); store.subscribe(storeState => this.setState({ isLoading: false, ...storeState }), (e) => { console.error(e); } ); }, handleRowSelect(logId){ const self=this; const logSource = this.state.log.filter(logItem=>{ if(logItem["id"]===logId){ return logItem; } }); const selectedLog = logSource[0]; const detailsObject = { exportedBy : selectedLog.exportedBy, created : selectedLog.exportedAt, id : selectedLog.id, href : self.state.baseUrl + "/dataStore/adxAdapter/" + selectedLog.id, downloadAdx : self.state.dataStoreUrlLocation + "/download/" + selectedLog.id, hasAdxMessage : selectedLog.hasAdxMessage, viewSummary : selectedLog.summary } self.setState({ detailBox: { open: true, source: detailsObject } }); }, renderLog() { const tableColumns = ['exportedAt', 'exportType', 'period', 'status']; const styles = { tableBorder: { borderCollapse: 'collapse', width:'90%', } }; if (this.state.isLoading) { return ( <div> <LinearProgress mode="indeterminate" /> <div style={{paddingTop: '1rem'}}>Loading export log...</div> </div> ); } if (this.state.log.length === 0) { return ( <div> <Paper> <div style={{fontSize: '1.5rem', margin: '.5em', padding: '2rem', color: 'red'}}>Could not find any previous export</div> </Paper> </div> ); } var logList = []; this.state.log.map(function(log, index) { const hasAdxMessage = (log.hasAdxMessage === undefined || !log.hasAdxMessage) ? false : true; var lastProcessedStepIndex = log.lastStepIndex; const isDryrun = log.dryrun; const uploadSummary = log.uploadSummary; // lastProcessedStepIndex should not be undefined, but it is so for those created before this was added to the log item. if (lastProcessedStepIndex === undefined) { //console.log("lastProcessedStepIndex is undefined, set it to be 3 if status is success to 0 for failure"); lastProcessedStepIndex = log.status.toUpperCase() === STATUS_SUCCESS.toUpperCase() ? 3: 0; } var statusDisplay = log.status + " " + (isDryrun ? "(dry run)" : "") ; if (log.status.toUpperCase() === STATUS_FAILURE.toUpperCase() && lastProcessedStepIndex < 3) { statusDisplay = log.status + " at " + getStepLabel(lastProcessedStepIndex) + " " + (isDryrun ? "(dry run)" : "") ; } if (log.status.toUpperCase() === STATUS_WARNING.toUpperCase() && uploadSummary && uploadSummary.ignored){ statusDisplay = log.status + " " + uploadSummary.ignored +" Data Values were Ignored" } const stepRowCollapseStyle = (index === 0 ) ? "" : "collapse"; const displayGlyphicon = "glyphicon glyphicon-menu-right"; const dryrunStyle = isDryrun ? "dryrun" : ""; logList.push( <tr onClick={()=>this.handleRowSelect(log.id)} key={"tr_"+ log.id}> <td key={"k1_" + log.id}>{formatDate(new Date(log.exportedAt))}</td> <td key={"k2_" + log.id}>{log.exportType.charAt(0).toUpperCase() + log.exportType.slice(1)}</td> <td key={"k3_" + log.id}>{log.period}</td> <td className={getStatusStyle(log.status)} key={"k4_" + log.id}> {statusDisplay}</td> <td key={"k5_" + log.id}><span className={displayGlyphicon} key={"k5_" + log.id}></span></td> </tr> ); } , this); const paperStyle = {maxWidth: 500, minWidth: 320, position: "-webkit-sticky", position: "sticky", top: 60}; const parentStyle = { flex:1, flexOrientation: "row", display: "flex" }; const leftStyle = { display:"flex", flexDirection: "column", flexGrow:2 }; const rightStyle = { flex: 1, marginLeft: "1rem", opacity : 1, flexGrow : 0, }; return ( <div className="container-fluid"> <h2>Data Exporting Records</h2> <div style={parentStyle}> <div style={leftStyle}> <Paper> <table className="table table-hover"> <thead> <tr> <th>Exported Time</th> <th>Type</th> <th>Period</th> <th>Status</th> <th>&nbsp;</th> </tr> </thead> <tbody> {logList} </tbody> </table> </Paper> </div> { this.state.detailBox.open? <div style={rightStyle}> <Paper zDepth={1} rounded={false} style={paperStyle}> <DetailsBox fields={["exportedBy", "created", "id", "href", "downloadAdx", "viewSummary"]} source={this.state.detailBox.source} showDetailBox={this.state.detailBox.open} onClose={() => this.setState({detailBox: {open: false}})} /> </Paper> </div>:null } </div> </div> ); }, render() { if (accessPermission === ROLE_ALLOW_EXPORT || accessPermission === ROLE_ALLOW_VIEW) { return this.renderLog() ; } else { return null; } } }); const ExportActionBar = React.createClass({ getMessage(data){ var step = data[1].step; var msg = "Started at: " + data[0].exportedAt; var lastProcessedStepIndex = data[0].lastStepIndex; if (step === 3 ){ msg = (lastProcessedStepIndex === 3 || lastProcessedStepIndex > 3 ) ? data[0].summary : (data[0].status.toUpperCase() === STATUS_SUCCESS.toUpperCase() ? data[0].summary : ""); } else if (step === 2 ){ msg = (lastProcessedStepIndex === 2 || lastProcessedStepIndex > 2 ) ? data[0].summary : (data[0].status.toUpperCase() === STATUS_SUCCESS.toUpperCase() ? data[0].summary: ""); } else if (step === 1 ){ msg = lastProcessedStepIndex === 1 ? data[0].summary : (lastProcessedStepIndex > 1? "Successfully Synchronized Metadata" : (data[0].status.toUpperCase() === STATUS_SUCCESS.toUpperCase() ? "Successfully Synchronized Metadata": "")); } return msg; }, getInitialState() { return { inProgress: true, dryrunChecked: false, passwordErrorMsg: "", isSnackbarOpen: false, password: "", popover: {}, dataType: "", dataTypes: [], periodDateSelected: "", periodDates: {}, }; }, handleTouchTap(data, event) { event.preventDefault(); this.setState({ popover: { open: true, anchorEl: event.currentTarget, message: this.getMessage(data) } }); }, /* lastProcessedStepIndex: the index of the last step which can be success or failure status: the status of the last processed step associated with lastProcessedStepIndex if status is success: the lastProcessedStepIndex should be 3, as only when all the steps are success, the status can be success if the status is failure: the lastProcessedStepIndex can be 1, 2 or 3 lastProcessedStepIndex: 0 based */ getStepButtonStyle(lastProcessedStepIndex, status){ const mapStepToButtonStyle = new Map(); if (status.toUpperCase() === STATUS_INPROGRESS.toUpperCase()){ switch (lastProcessedStepIndex) { case 0: return mapStepToButtonStyle.set(0, 'default').set(1,'default').set(2,'default').set(3,'default'); case 1: return mapStepToButtonStyle.set(0, 'success').set(1, 'default').set(2,'default').set(3,'default') ; case 2: return mapStepToButtonStyle.set(0, 'success').set(1, 'success').set(2,'default').set(3,'default') ; case 3: return mapStepToButtonStyle.set(0, 'success').set(1, 'success').set(2, 'success').set(3, 'default'); default: return mmapStepToButtonStyle.set(0, 'default').set(1,'default').set(2,'default').set(3,'default'); } } else if (status.toUpperCase() === STATUS_SUCCESS.toUpperCase() ){ return mapStepToButtonStyle.set(0, 'success').set(1, 'success').set(2, 'success').set(3, 'success'); } else if (status.toUpperCase() === STATUS_WARNING.toUpperCase() ){ return mapStepToButtonStyle.set(0, 'success').set(1, 'success').set(2, 'success').set(3, 'warning'); }else { switch (lastProcessedStepIndex) { case 0: return mapStepToButtonStyle.set(0, 'failure').set(1,'default').set(2,'default').set(3,'default'); case 1: return mapStepToButtonStyle.set(0, 'success').set(1, 'failure').set(2,'default').set(3,'default') ; case 2: return mapStepToButtonStyle.set(0, 'success').set(1, 'success').set(2,'failure').set(3,'default') ; case 3: return mapStepToButtonStyle.set(0, 'success').set(1, 'success').set(2, 'success').set(3, 'failure'); default: return mmapStepToButtonStyle.set(0, 'default').set(1,'default').set(2,'default').set(3,'default'); } } return ''; }, getExportDate(){ var date = new Date(); var quarter = Math.floor(date.getMonth() / 3), year = date.getFullYear(); quarter -= 1; if(quarter < 0) { var yearsChanged = Math.ceil(-quarter / 4); year -= yearsChanged; quarter += 4 * yearsChanged; } return year + " Q" + (quarter + 1) ; }, componentWillMount() { store.subscribe(storeState => this.setState(storeState)); actions.loadDataTypes() .subscribe(() => {}, (e) => { console.error(e); }); store.subscribe(storeState => this.setState({ ...storeState }), (e) => { console.error(e); } ); }, startExport() { actions.startExport({ dataType: this.state.dataType, periodDate: this.state.periodDateSelected}) .subscribe( helpers.identity, (errorMessage) => { this.setState({ snackbarMessage: errorMessage, passwordErrorMsg: errorMessage, isSnackbarOpen: true, }); } ); this.setState( { password: "", dryrunChecked: false, passwordErrorMsg: "", dataType: "", periodDateSelected: "" } ) }, setPassword() { this.setState({ password: this.refs.password.getValue(), }); if (this.refs.password.getValue() === "") { this.setState({ passwordErrorMsg: "" }); } }, handleDryrunCheck() { this.setState({ dryrunChecked: !this.state.dryrunChecked, }); }, handleDataTypeChange(event, index, value){ if (value != "" && value != this.state.dataType) { actions.loadPeriods({dataType: value}) .subscribe(() => {}, (e) => { console.error(e); }); store.subscribe(storeState => this.setState({ ...storeState }), (e) => { console.error(e); } ); } this.setState({ dataType: value, passwordErrorMsg: "", periodDateSelected: "", }); }, handlePeriodDateChange(event, index, value){ this.setState({ periodDateSelected: value, }); }, closeSnackbar() { this.setState({ isSnackbarOpen: false, }); }, getRestCall(url) { $.get( url, // deleteLastUri(this.state.dataStoreUrlLocation)+"/terminate/"+latestLog.id, function(data) { console.log("data is="+data); } )}, renderPassword() { const styles = { buttonBarStyle: { //textAlign: 'left', marginBottom: '2rem', marginTop: '70px', }, buttonStyle: { marginleft: 1, width: 300, }, underlineStyle: { borderColor: '#00BCD4', }, }; const menuStyle = { marginBottom: '1rem', marginLeft: '3rm' , borderColor: '#00a7e0 ', }; const selectedMenuItemStyle = { borderColor: '#00a7e0', borderStyle: 'solid', borderWidth: '1px', } const inputCriteriaStyle={ border: '2px solid #FFE4C4', backgroundColor: '#F5F5DC', paddingTop: '10px', paddingBottom: '10px', paddingLeft: '20px', marginBottom: '15px', marginTop: '20px', borderRadius: '5px', width: '500px', } const inputRowStyle={ padding: '2px 0' } const selectionLabelStyle= { display: 'inline-block', width: '110px' } var msg = (this.state.dryrunChecked) ? "checked" : "unchecked" ; var fullwidth = true; var lastExported = (this.state.log != null && this.state.log.length > 0) ? formatDate(new Date(this.state.log[0].exportedAt)) : ""; var lastStatus = (this.state.log != null && this.state.log.length > 0) ? this.state.log[0].status : ""; var lastStatusStyle = (this.state.log != null && this.state.log.length > 0)? getStatusStyle(this.state.log[0].status):"error"; const buttonText = this.state.inProgress ? 'Export in progress. Check back later.' : !this.state.password ? 'Export' : 'Export'; //console.error("snackbar message:"+this.state.snackbarMessage); var menuItemList = []; menuItemList.push(<MenuItem value="" primaryText="Select a data type" key="dataType_default"/>); for (var prop in this.state.dataTypes) { if (this.state.dataTypes[prop].code != "test" || (this.state.dataTypes[prop].code === "test" && isSuperUser)) { menuItemList.push(<MenuItem value={this.state.dataTypes[prop].code} primaryText={this.state.dataTypes[prop].value} key={this.state.dataTypes[prop].code}/>); } } var menuItemListPeriodsDates = []; menuItemListPeriodsDates.push(<MenuItem value="" primaryText="Select a period" disabled={this.state.dataType === ""} key="period_default"/>); if (this.state.dataType != "" && this.state.periodDates.currentPeriod != null) { menuItemListPeriodsDates.push(<MenuItem value={this.state.periodDates.currentPeriod.code} primaryText={this.state.periodDates.currentPeriod.value} key={this.state.periodDates.currentPeriod.code}/>); for (var prop in this.state.periodDates.previousPeriod) { menuItemListPeriodsDates.push(<MenuItem value={this.state.periodDates.previousPeriod[prop].code} primaryText={this.state.periodDates.previousPeriod[prop].value} key={this.state.periodDates.previousPeriod[prop].code}/>); } } let latestLog = (this.state.log != null && this.state.log.length > 0)?this.state.log[0]:null; const mapStepButtonStyle = latestLog ? this.getStepButtonStyle(latestLog.lastStepIndex, latestLog.status) : null; const rowStyle = latestLog ? (latestLog.status.toUpperCase() === STATUS_INPROGRESS.toUpperCase() ) ? "inprogress-stage" + latestLog.lastStepIndex + "-row" : latestLog.status.toUpperCase() === STATUS_WARNING.toUpperCase() ? "warning-row" : latestLog.status.toUpperCase() === STATUS_SUCCESS.toUpperCase() ? "success-row" : "failure-stage" + latestLog.lastStepIndex + "-row" : null; let stepsArr = []; //display the bubble process if (this.state.log != null && this.state.log.length > 0){ const totalSteps = 4; for (let i = 0; i < totalSteps; i++){ let logWithSteps = []; logWithSteps.push(latestLog); logWithSteps.push({step: i}); //based on lastProcessedStepIndex (lastStepIndex), should this step i be disabled? var disabledButton = (latestLog.status.toUpperCase() === STATUS_FAILURE.toUpperCase() && latestLog.lastStepIndex < i )? "disabled=disabled" : ""; var opts = {}; if (disabledButton) { opts['disabled'] = 'disabled'; } stepsArr.push( <div className="stepwizard-step" id={"step_" + i + latestLog.id} key={"div_step" + i + log.id}> <a href="#" ref={"link_" + i + log.id} key={"alink_" + i+ latestLog.id} tabIndex={i} className={mapStepButtonStyle.get(i)} > <button type="button" className={"btn btn-default btn-circle " + mapStepButtonStyle.get(i) + "-circle"} id={"stepButton_" + i + latestLog.id} ref={"stepButton_" + i + latestLog.id} key={"stepButtonID_" + i+ latestLog.id} onClick={this.handleTouchTap.bind(this, logWithSteps)} {...opts }> <span className={"glyphicon glyphicon-" + (mapStepButtonStyle.get(i).toUpperCase()===STATUS_SUCCESS.toUpperCase() ? OK : mapStepButtonStyle.get(i).toUpperCase()===STATUS_WARNING.toUpperCase() ? BUTTON_WARNING : mapStepButtonStyle.get(i).toUpperCase()=== STATUS_FAILURE.toUpperCase() ? REMOVE : BUTTON_STYLE_DEFAULT ) } aria-hidden="true" key={"arrow_" + i + latestLog.id}></span> </button> </a> <p>{getStepLabel(i)}</p> </div> ); } } var msgLen = this.state.popover.message!= null? this.state.popover.message.length : 0; const popoverStyle = msgLen > 500 ? { marginLeft: '1rem', padding: '1rem', maxWidth: '60%', color: '#333333', backgroundColor: '#fffae6', border: '1px solid #A0A0A0', overflow: 'auto', width:500, height: 370 } : { marginLeft: '1rem', padding: '1rem', maxWidth: '60%', color: '#333333', backgroundColor: '#fffae6', border: '1px solid #A0A0A0', overflow: 'auto', width:500 }; var deleteLastUri = function(url){ return url.split('adxAdapter')[0] + "adxAdapter"; } //if superuser, allow to terminate adx exchange. var terminateButton = this.state.dataStoreUrlLocation!=null && latestLog!=null ? latestLog.status === STATUS_INPROGRESS ? isSuperUser ? (<span className="last-export-terminate"> <a href={deleteLastUri(this.state.dataStoreUrlLocation)+"/terminate/"+latestLog.id} target="_blank"> Terminate Exchange</a> </span>) :"" : "" : "" ; return ( <div className="container-fluid"> <h1>Data Submission</h1> <div style={inputCriteriaStyle} key="inputCriteria"> <div style={inputRowStyle} key="inputRowDataType"> <div style={selectionLabelStyle}>Select Data Type:</div> <DropDownMenu name="dataType" style={menuStyle} iconStyle ={{ color: '#00a7e0', fill: '#00a7e0' }} underlineStyle={selectedMenuItemStyle} ref="dataType" value={this.state.dataType} onChange={this.handleDataTypeChange}> {menuItemList} </DropDownMenu> </div> <div style={inputRowStyle} key="inputRowPeriod"> <div style={selectionLabelStyle}>Select Period:</div> <DropDownMenu name="periodDatesDropDown" disabled={this.state.dataType === ""} style={menuStyle} iconStyle ={{ color: '#00a7e0', fill: '#00a7e0' }} underlineStyle={selectedMenuItemStyle} ref="periodDate" value={this.state.periodDateSelected} onChange={this.handlePeriodDateChange}> {menuItemListPeriodsDates} </DropDownMenu> </div> </div> <RaisedButton backgroundColor='#00BCD4' labelColor='#ffffff' onClick={this.startExport} disabled={this.state.inProgress || this.state.periodDateSelected === "" } label={buttonText} /> <span style={{ color: 'red', paddingLeft: '5px' }}>{this.state.passwordErrorMsg}</span> <Paper style={{padding: '2rem', margin: '1em 0 1em 0'}} zDepth={1} > <h2>Most Recent Export</h2> <div className="explanation"> <span className="last-export-time"><span className="explanation-title">Last Export Time: </span>{lastExported} </span> <span className="last-export-status"><span className="explanation-title"> Last Export Status: </span><span className={lastStatusStyle}>{lastStatus}</span></span> &nbsp;{terminateButton} <div className="stepwizard" key={"div_stepwizard_" + log.id}> <div className={"stepwizard-row " + rowStyle} key={"divstep_row_" + log.id}> {stepsArr} </div> </div> </div> </Paper> <div> <Popover open={this.state.popover.open} anchorEl={this.state.popover.anchorEl} anchorOrigin={{vertical: 'bottom', horizontal: 'left'}} targetOrigin={{horizontal: 'left', vertical: 'top'}} canAutoPosition={false} onRequestClose={() => this.setState({popover: {open: false}})} style={popoverStyle}> <div>{this.state.popover.message}</div> </Popover> </div> </div> ); }, renderNoAccess() { return( <div className="container"> <h1>Data Submission</h1> <div> <Paper> <div style={{fontSize: '1.5rem', margin: '.5em', padding: '2rem', color: 'red'}}>You don't have permission to access this page.</div> </Paper> </div> </div> ) }, render() { if (accessPermission === ROLE_ALLOW_EXPORT) { return this.renderPassword() ; }else if (accessPermission === ROLE_ALLOW_VIEW) { return (<div className="container"><h1>Data Submission</h1></div>); } else { return this.renderNoAccess() ; } } }); const App = React.createClass({ childContextTypes: { d2: React.PropTypes.object, }, getChildContext() { return { d2: this.props.d2, }; }, render() { const appContentStyle = { width: '80%', margin: '5rem auto 0', }; // const paperStyle = { maxWidth: 500, minWidth: 300, marginTop: document.querySelector('body').scrollTop }; return ( <MuiThemeProvider> <div> <HeaderBar /> <div style={appContentStyle}> <ExportActionBar /> <ExportLogList /> </div> </div> </MuiThemeProvider> ); } }); render(<MuiThemeProvider><LoadingMask /></MuiThemeProvider>, document.getElementById('app')); getManifest('manifest.webapp') .then(manifest => { if ((process.env.NODE_ENV !== 'production') && process.env.DEVELOPMENT_SERVER_ADDRESS) { // console.log(process.env.DEVELOPMENT_SERVER_ADDRESS); config.baseUrl = `${process.env.DEVELOPMENT_SERVER_ADDRESS}/api`; return; } config.baseUrl = manifest.getBaseUrl() + '/api' }) .then(() => { init() .then(d2 => { return getUserRolesForCurrentUser(d2) .then(roles => { if (roles.has('Superuser ALL authorities') || roles.has('ADX Exporter')){ accessPermission = ROLE_ALLOW_EXPORT; if (roles.has('Superuser ALL authorities')) { isSuperUser = true; } }else if (roles.has('ADX User')) { accessPermission = ROLE_ALLOW_VIEW; } else { accessPermission = ROLE_ALLOW_NOACCESS; } return d2; }); }) .then(d2 => { const dataStoreUrl = 'dataStore/adxAdapter'; const api = d2.Api.getApi(); const datastoreurl = api.get(`${dataStoreUrl}/location`); render(<App d2={d2} />, document.getElementById('app')); }) .catch(errorMessage => { log.error('Unable to load d2', errorMessage); }); });
packages/icons/src/md/social/SentimentNeutral.js
suitejs/suitejs
import React from 'react'; import IconBase from '@suitejs/icon-base'; function MdSentimentNeutral(props) { return ( <IconBase viewBox="0 0 48 48" {...props}> <path d="M18 28h12v3H18v-3zm13-12c-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3-1.34-3-3-3zm-11 3c0-1.66-1.34-3-3-3s-3 1.34-3 3 1.34 3 3 3 3-1.34 3-3zm3.98-15C35.04 4 44 12.96 44 24s-8.96 20-20.02 20C12.94 44 4 35.04 4 24S12.94 4 23.98 4zM24 40c8.84 0 16-7.16 16-16S32.84 8 24 8 8 15.16 8 24s7.16 16 16 16z" /> </IconBase> ); } export default MdSentimentNeutral;
client/extensions/woocommerce/woocommerce-services/views/shipping-label/label-purchase-modal/index.js
Automattic/woocommerce-services
/** @format */ /** * External dependencies */ import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { localize } from 'i18n-calypso'; import { Modal } from '@wordpress/components'; /** * Internal dependencies */ import AddressStep from './address-step'; import PackagesStep from './packages-step'; import CustomsStep from './customs-step'; import RatesStep from './rates-step'; import Sidebar from './sidebar'; import { exitPrintingFlow } from 'woocommerce/woocommerce-services/state/shipping-label/actions'; import { getShippingLabel, isLoaded, isCustomsFormRequired, } from 'woocommerce/woocommerce-services/state/shipping-label/selectors'; const LabelPurchaseModal = props => { const { loaded, translate, showPurchaseDialog } = props; if ( ! loaded ) { return null; } const onClose = () => props.exitPrintingFlow( props.orderId, props.siteId, false ); return ( showPurchaseDialog ? ( <Modal className="woocommerce label-purchase-modal wcc-root" shouldCloseOnClickOutside={ false } onRequestClose={ onClose } title={ translate( 'Create shipping label', 'Create shipping labels', { count: Object.keys( props.form.packages.selected ).length } ) } > <div className="label-purchase-modal__content"> <div className="label-purchase-modal__main-section"> <AddressStep type="origin" title={ translate( 'Origin address' ) } siteId={ props.siteId } orderId={ props.orderId } /> <AddressStep type="destination" title={ translate( 'Destination address' ) } siteId={ props.siteId } orderId={ props.orderId } /> <PackagesStep siteId={ props.siteId } orderId={ props.orderId } /> { props.isCustomsFormRequired && ( <CustomsStep siteId={ props.siteId } orderId={ props.orderId } /> ) } <RatesStep siteId={ props.siteId } orderId={ props.orderId } /> </div> <Sidebar siteId={ props.siteId } orderId={ props.orderId } /> </div> </Modal> ) : null ); }; LabelPurchaseModal.propTypes = { siteId: PropTypes.number.isRequired, orderId: PropTypes.number.isRequired, }; const mapStateToProps = ( state, { orderId, siteId } ) => { const loaded = isLoaded( state, orderId, siteId ); const shippingLabel = getShippingLabel( state, orderId, siteId ); return { loaded, form: loaded && shippingLabel.form, showPurchaseDialog: shippingLabel.showPurchaseDialog, isCustomsFormRequired: isCustomsFormRequired( state, orderId, siteId ), }; }; const mapDispatchToProps = dispatch => { return bindActionCreators( { exitPrintingFlow }, dispatch ); }; export default connect( mapStateToProps, mapDispatchToProps )( localize( LabelPurchaseModal ) );
node_modules/react-bootstrap/es/Collapse.js
jkahrs595/website
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 css from 'dom-helpers/style'; import React from 'react'; import Transition from 'react-overlays/lib/Transition'; import capitalize from './utils/capitalize'; import createChainedFunction from './utils/createChainedFunction'; var MARGINS = { height: ['marginTop', 'marginBottom'], width: ['marginLeft', 'marginRight'] }; // reading a dimension prop will cause the browser to recalculate, // which will let our animations work function triggerBrowserReflow(node) { node.offsetHeight; // eslint-disable-line no-unused-expressions } function getDimensionValue(dimension, elem) { var value = elem['offset' + capitalize(dimension)]; var margins = MARGINS[dimension]; return value + parseInt(css(elem, margins[0]), 10) + parseInt(css(elem, margins[1]), 10); } var propTypes = { /** * Show the component; triggers the expand or collapse animation */ 'in': React.PropTypes.bool, /** * Unmount the component (remove it from the DOM) when it is collapsed */ unmountOnExit: React.PropTypes.bool, /** * Run the expand animation when the component mounts, if it is initially * shown */ transitionAppear: React.PropTypes.bool, /** * Duration of the collapse animation in milliseconds, to ensure that * finishing callbacks are fired even if the original browser transition end * events are canceled */ timeout: React.PropTypes.number, /** * Callback fired before the component expands */ onEnter: React.PropTypes.func, /** * Callback fired after the component starts to expand */ onEntering: React.PropTypes.func, /** * Callback fired after the component has expanded */ onEntered: React.PropTypes.func, /** * Callback fired before the component collapses */ onExit: React.PropTypes.func, /** * Callback fired after the component starts to collapse */ onExiting: React.PropTypes.func, /** * Callback fired after the component has collapsed */ onExited: React.PropTypes.func, /** * The dimension used when collapsing, or a function that returns the * dimension * * _Note: Bootstrap only partially supports 'width'! * You will need to supply your own CSS animation for the `.width` CSS class._ */ dimension: React.PropTypes.oneOfType([React.PropTypes.oneOf(['height', 'width']), React.PropTypes.func]), /** * Function that returns the height or width of the animating DOM node * * Allows for providing some custom logic for how much the Collapse component * should animate in its specified dimension. Called with the current * dimension prop value and the DOM node. */ getDimensionValue: React.PropTypes.func, /** * ARIA role of collapsible element */ role: React.PropTypes.string }; var defaultProps = { 'in': false, timeout: 300, unmountOnExit: false, transitionAppear: false, dimension: 'height', getDimensionValue: getDimensionValue }; var Collapse = function (_React$Component) { _inherits(Collapse, _React$Component); function Collapse(props, context) { _classCallCheck(this, Collapse); var _this = _possibleConstructorReturn(this, _React$Component.call(this, props, context)); _this.handleEnter = _this.handleEnter.bind(_this); _this.handleEntering = _this.handleEntering.bind(_this); _this.handleEntered = _this.handleEntered.bind(_this); _this.handleExit = _this.handleExit.bind(_this); _this.handleExiting = _this.handleExiting.bind(_this); return _this; } /* -- Expanding -- */ Collapse.prototype.handleEnter = function handleEnter(elem) { var dimension = this._dimension(); elem.style[dimension] = '0'; }; Collapse.prototype.handleEntering = function handleEntering(elem) { var dimension = this._dimension(); elem.style[dimension] = this._getScrollDimensionValue(elem, dimension); }; Collapse.prototype.handleEntered = function handleEntered(elem) { var dimension = this._dimension(); elem.style[dimension] = null; }; /* -- Collapsing -- */ Collapse.prototype.handleExit = function handleExit(elem) { var dimension = this._dimension(); elem.style[dimension] = this.props.getDimensionValue(dimension, elem) + 'px'; triggerBrowserReflow(elem); }; Collapse.prototype.handleExiting = function handleExiting(elem) { var dimension = this._dimension(); elem.style[dimension] = '0'; }; Collapse.prototype._dimension = function _dimension() { return typeof this.props.dimension === 'function' ? this.props.dimension() : this.props.dimension; }; // for testing Collapse.prototype._getScrollDimensionValue = function _getScrollDimensionValue(elem, dimension) { return elem['scroll' + capitalize(dimension)] + 'px'; }; Collapse.prototype.render = function render() { var _props = this.props; var onEnter = _props.onEnter; var onEntering = _props.onEntering; var onEntered = _props.onEntered; var onExit = _props.onExit; var onExiting = _props.onExiting; var className = _props.className; var props = _objectWithoutProperties(_props, ['onEnter', 'onEntering', 'onEntered', 'onExit', 'onExiting', 'className']); delete props.dimension; delete props.getDimensionValue; var handleEnter = createChainedFunction(this.handleEnter, onEnter); var handleEntering = createChainedFunction(this.handleEntering, onEntering); var handleEntered = createChainedFunction(this.handleEntered, onEntered); var handleExit = createChainedFunction(this.handleExit, onExit); var handleExiting = createChainedFunction(this.handleExiting, onExiting); var classes = { width: this._dimension() === 'width' }; return React.createElement(Transition, _extends({}, props, { 'aria-expanded': props.role ? props['in'] : null, className: classNames(className, classes), exitedClassName: 'collapse', exitingClassName: 'collapsing', enteredClassName: 'collapse in', enteringClassName: 'collapsing', onEnter: handleEnter, onEntering: handleEntering, onEntered: handleEntered, onExit: handleExit, onExiting: handleExiting })); }; return Collapse; }(React.Component); Collapse.propTypes = propTypes; Collapse.defaultProps = defaultProps; export default Collapse;
.storybook/preview.js
cloudbase/coriolis-web
import React from 'react' import { addDecorator } from '@storybook/react' import styled, { createGlobalStyle } from 'styled-components' import { ThemePalette, ThemeProps } from '@src/components/Theme' import Fonts from '@src/components/ui/Fonts' import { BrowserRouter as Router, Switch, Route } from 'react-router-dom' const Wrapper = styled.div` display: inline-block; background: ${ThemePalette.grayscale[7]}; padding: 32px; ` const GlobalStyle = createGlobalStyle` ${Fonts} body { color: ${ThemePalette.black}; font-family: Rubik; font-size: 14px; font-weight: ${ThemeProps.fontWeights.regular}; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } ` addDecorator(storyFn => ( <Router> <Switch> <Wrapper> <GlobalStyle /> {storyFn()} </Wrapper> </Switch> </Router> ) )
packages/icons/src/md/notification/DoNotDisturbOff.js
suitejs/suitejs
import React from 'react'; import IconBase from '@suitejs/icon-base'; function MdDoNotDisturbOff(props) { return ( <IconBase viewBox="0 0 48 48" {...props}> <path d="M35 21v4h-2.92l9.36 9.36A19.84 19.84 0 0 0 45 23c0-11.04-8.96-20-20-20-4.22 0-8.14 1.32-11.36 3.56L28.08 21H35zM5.54 3.54L23 21l21.46 21.46L41.92 45l-5.56-5.56A19.84 19.84 0 0 1 25 43C13.96 43 5 34.04 5 23c0-4.22 1.32-8.14 3.56-11.36L3 6.08l2.54-2.54zM15 25h6.92l-4-4H15v4z" /> </IconBase> ); } export default MdDoNotDisturbOff;
internals/templates/appContainer.js
Rohitbels/KolheshwariIndustries
/** * * App.react.js * * This component is the skeleton around the actual pages, and should only * contain code that should be seen on all pages. (e.g. navigation bar) * * NOTE: while this component should technically be a stateless functional * component (SFC), hot reloading does not currently support SFCs. If hot * reloading is not a necessity for you then you can refactor it and remove * the linting exception. */ import React from 'react'; export default class App extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function static propTypes = { children: React.PropTypes.node, }; render() { return ( <div> {React.Children.toArray(this.props.children)} </div> ); } }
ajax/libs/ui-router-extras/0.0.11-pre1/ct-ui-router-extras.js
joeyparrish/cdnjs
/** * UI-Router Extras: Sticky states, Future States, Deep State Redirect, Transition promise * @version v0.0.11-pre1-BROKEN!!! * 0.0.11-pre1 is broken, please use 0.0.11-pre2 * @link http://christopherthielen.github.io/ui-router-extras/ * @license MIT License, http://www.opensource.org/licenses/MIT */ (function (window, angular, undefined) { angular.module("ct.ui.router.extras", [ 'ui.router' ]); var DEBUG = false; var forEach = angular.forEach; var extend = angular.extend; var isArray = angular.isArray; var map = function (collection, callback) { "use strict"; var result = []; forEach(collection, function (item, index) { result.push(callback(item, index)); }); return result; }; var keys = function (collection) { "use strict"; return map(collection, function (collection, key) { return key; }); }; var filter = function (collection, callback) { "use strict"; var result = []; forEach(collection, function (item, index) { if (callback(item, index)) { result.push(item); } }); return result; }; var filterObj = function (collection, callback) { "use strict"; var result = {}; forEach(collection, function (item, index) { if (callback(item, index)) { result[index] = item; } }); return result; }; // Duplicates code in UI-Router common.js function ancestors(first, second) { var path = []; for (var n in first.path) { if (first.path[n] !== second.path[n]) break; path.push(first.path[n]); } return path; } // Duplicates code in UI-Router common.js function objectKeys(object) { if (Object.keys) { return Object.keys(object); } var result = []; angular.forEach(object, function (val, key) { result.push(key); }); return result; } // Duplicates code in UI-Router common.js function arraySearch(array, value) { if (Array.prototype.indexOf) { return array.indexOf(value, Number(arguments[2]) || 0); } var len = array.length >>> 0, from = Number(arguments[2]) || 0; from = (from < 0) ? Math.ceil(from) : Math.floor(from); if (from < 0) from += len; for (; from < len; from++) { if (from in array && array[from] === value) return from; } return -1; } // Duplicates code in UI-Router common.js // Added compatibility code (isArray check) to support both 0.2.x and 0.3.x series of UI-Router. function inheritParams(currentParams, newParams, $current, $to) { var parents = ancestors($current, $to), parentParams, inherited = {}, inheritList = []; for (var i in parents) { if (!parents[i].params) continue; // This test allows compatibility with 0.2.x and 0.3.x (optional and object params) parentParams = isArray(parents[i].params) ? parents[i].params : objectKeys(parents[i].params); if (!parentParams.length) continue; for (var j in parentParams) { if (arraySearch(inheritList, parentParams[j]) >= 0) continue; inheritList.push(parentParams[j]); inherited[parentParams[j]] = currentParams[parentParams[j]]; } } return extend({}, inherited, newParams); } function inherit(parent, extra) { return extend(new (extend(function () { }, {prototype: parent}))(), extra); } var ignoreDsr; function resetIgnoreDsr() { ignoreDsr = undefined; } // Decorate $state.transitionTo to gain access to the last transition.options variable. // This is used to process the options.ignoreDsr option angular.module("ct.ui.router.extras").config([ "$provide", function ($provide) { var $state_transitionTo; $provide.decorator("$state", ['$delegate', '$q', function ($state, $q) { $state_transitionTo = $state.transitionTo; $state.transitionTo = function (to, toParams, options) { if (options.ignoreDsr) { ignoreDsr = options.ignoreDsr; } return $state_transitionTo.apply($state, arguments).then( function (result) { resetIgnoreDsr(); return result; }, function (err) { resetIgnoreDsr(); return $q.reject(err); } ); }; return $state; }]); }]); angular.module("ct.ui.router.extras").service("$deepStateRedirect", [ '$rootScope', '$state', '$injector', function ($rootScope, $state, $injector) { var lastSubstate = {}; var deepStateRedirectsByName = {}; var REDIRECT = "Redirect", ANCESTOR_REDIRECT = "AncestorRedirect"; function computeDeepStateStatus(state) { var name = state.name; if (deepStateRedirectsByName.hasOwnProperty(name)) return deepStateRedirectsByName[name]; recordDeepStateRedirectStatus(name); } function getConfig(state) { var declaration = state.deepStateRedirect; if (!declaration) return { dsr: false }; var dsrCfg = { dsr: true }; if (angular.isFunction(declaration)) dsrCfg.fn = declaration; else if (angular.isObject(declaration)) dsrCfg = angular.extend(dsrCfg, declaration); return dsrCfg; } function recordDeepStateRedirectStatus(stateName) { var state = $state.get(stateName); if (!state) return false; var cfg = getConfig(state); if (cfg.dsr) { deepStateRedirectsByName[state.name] = REDIRECT; if (lastSubstate[stateName] === undefined) lastSubstate[stateName] = {}; } var parent = state.$$state && state.$$state().parent; if (parent) { var parentStatus = recordDeepStateRedirectStatus(parent.self.name); if (parentStatus && deepStateRedirectsByName[state.name] === undefined) { deepStateRedirectsByName[state.name] = ANCESTOR_REDIRECT; } } return deepStateRedirectsByName[state.name] || false; } function getParamsString(params, dsrParams) { function safeString(input) { return !input ? input : input.toString(); } if (dsrParams === true) dsrParams = Object.keys(params); if (dsrParams === null || dsrParams === undefined) dsrParams = []; var paramsToString = {}; angular.forEach(dsrParams.sort(), function(name) { paramsToString[name] = safeString(params[name]); }); return angular.toJson(paramsToString); } $rootScope.$on("$stateChangeStart", function (event, toState, toParams, fromState, fromParams) { if (ignoreDsr || computeDeepStateStatus(toState) !== REDIRECT) return; // We're changing directly to one of the redirect (tab) states. // Get the DSR key for this state by calculating the DSRParams option var cfg = getConfig(toState); var key = getParamsString(toParams, cfg.params); var redirect = lastSubstate[toState.name][key]; // we have a last substate recorded var isDSR = (redirect && redirect.state != toState.name ? true : false); if (isDSR && cfg.fn) isDSR = $injector.invoke(cfg.fn, toState); if (!isDSR) return; event.preventDefault(); $state.go(redirect.state, redirect.params); }); $rootScope.$on("$stateChangeSuccess", function (event, toState, toParams, fromState, fromParams) { var deepStateStatus = computeDeepStateStatus(toState); if (deepStateStatus) { var name = toState.name; angular.forEach(lastSubstate, function (redirect, dsrState) { // update Last-SubState&params for each DSR that this transition matches. var cfg = getConfig($state.get(dsrState)); var key = getParamsString(toParams, cfg.params); if (name == dsrState || name.indexOf(dsrState + ".") != -1) { lastSubstate[dsrState][key] = { state: name, params: angular.copy(toParams) }; } }); } }); return { reset: function(stateOrName) { if (!stateOrName) { angular.forEach(lastSubstate, function(redirect, dsrState) { lastSubstate[dsrState] = {}; }); } else { var state = $state.get(stateOrName); if (!state) throw new Error("Unknown state: " + stateOrName); if (lastSubstate[state.name]) lastSubstate[state.name] = {}; } } }; }]); angular.module("ct.ui.router.extras").run(['$deepStateRedirect', function ($deepStateRedirect) { // Make sure $deepStateRedirect is instantiated }]); $StickyStateProvider.$inject = [ '$stateProvider' ]; function $StickyStateProvider($stateProvider) { // Holds all the states which are inactivated. Inactivated states can be either sticky states, or descendants of sticky states. var inactiveStates = {}; // state.name -> (state) var stickyStates = {}; // state.name -> true var $state; // Called by $stateProvider.registerState(); // registers a sticky state with $stickyStateProvider this.registerStickyState = function (state) { stickyStates[state.name] = state; // console.log("Registered sticky state: ", state); }; this.enableDebug = function (enabled) { DEBUG = enabled; }; this.$get = [ '$rootScope', '$state', '$stateParams', '$injector', '$log', function ($rootScope, $state, $stateParams, $injector, $log) { // Each inactive states is either a sticky state, or a child of a sticky state. // This function finds the closest ancestor sticky state, then find that state's parent. // Map all inactive states to their closest parent-to-sticky state. function mapInactives() { var mappedStates = {}; angular.forEach(inactiveStates, function (state, name) { var stickyAncestors = getStickyStateStack(state); for (var i = 0; i < stickyAncestors.length; i++) { var parent = stickyAncestors[i].parent; mappedStates[parent.name] = mappedStates[parent.name] || []; mappedStates[parent.name].push(state); } if (mappedStates['']) { // This is necessary to compute Transition.inactives when there are sticky states are children to root state. mappedStates['__inactives'] = mappedStates['']; // jshint ignore:line } }); return mappedStates; } // Given a state, returns all ancestor states which are sticky. // Walks up the view's state's ancestry tree and locates each ancestor state which is marked as sticky. // Returns an array populated with only those ancestor sticky states. function getStickyStateStack(state) { var stack = []; if (!state) return stack; do { if (state.sticky) stack.push(state); state = state.parent; } while (state); stack.reverse(); return stack; } // Used by processTransition to determine if what kind of sticky state transition this is. // returns { from: (bool), to: (bool) } function getStickyTransitionType(fromPath, toPath, keep) { if (fromPath[keep] === toPath[keep]) return { from: false, to: false }; var stickyFromState = keep < fromPath.length && fromPath[keep].self.sticky; var stickyToState = keep < toPath.length && toPath[keep].self.sticky; return { from: stickyFromState, to: stickyToState }; } // Returns a sticky transition type necessary to enter the state. // Transition can be: reactivate, updateStateParams, or enter // Note: if a state is being reactivated but params dont match, we treat // it as a Exit/Enter, thus the special "updateStateParams" transition. // If a parent inactivated state has "updateStateParams" transition type, then // all descendant states must also be exit/entered, thus the first line of this function. function getEnterTransition(state, stateParams, ancestorParamsChanged) { if (ancestorParamsChanged) return "updateStateParams"; var inactiveState = inactiveStates[state.self.name]; if (!inactiveState) return "enter"; // if (inactiveState.locals == null || inactiveState.locals.globals == null) debugger; var paramsMatch = equalForKeys(stateParams, inactiveState.locals.globals.$stateParams, state.ownParams); // if (DEBUG) $log.debug("getEnterTransition: " + state.name + (paramsMatch ? ": reactivate" : ": updateStateParams")); return paramsMatch ? "reactivate" : "updateStateParams"; } // Given a state and (optional) stateParams, returns the inactivated state from the inactive sticky state registry. function getInactivatedState(state, stateParams) { var inactiveState = inactiveStates[state.name]; if (!inactiveState) return null; if (!stateParams) return inactiveState; var paramsMatch = equalForKeys(stateParams, inactiveState.locals.globals.$stateParams, state.ownParams); return paramsMatch ? inactiveState : null; } // Duplicates logic in $state.transitionTo, primarily to find the pivot state (i.e., the "keep" value) function equalForKeys(a, b, keys) { if (!keys) { keys = []; for (var n in a) keys.push(n); // Used instead of Object.keys() for IE8 compatibility } for (var i = 0; i < keys.length; i++) { var k = keys[i]; if (a[k] != b[k]) return false; // Not '===', values aren't necessarily normalized } return true; } var stickySupport = { getInactiveStates: function () { var states = []; angular.forEach(inactiveStates, function (state) { states.push(state); }); return states; }, getInactiveStatesByParent: function () { return mapInactives(); }, // Main API for $stickyState, used by $state. // Processes a potential transition, returns an object with the following attributes: // { // inactives: Array of all states which will be inactive if the transition is completed. (both previously and newly inactivated) // enter: Enter transition type for all added states. This is a sticky array to "toStates" array in $state.transitionTo. // exit: Exit transition type for all removed states. This is a sticky array to "fromStates" array in $state.transitionTo. // } processTransition: function (transition) { // This object is returned var result = { inactives: [], enter: [], exit: [], keep: 0 }; var fromPath = transition.fromState.path, fromParams = transition.fromParams, toPath = transition.toState.path, toParams = transition.toParams, options = transition.options; var keep = 0, state = toPath[keep]; if (options.inherit) { toParams = inheritParams($stateParams, toParams || {}, $state.$current, transition.toState); } while (state && state === fromPath[keep] && equalForKeys(toParams, fromParams, state.ownParams)) { state = toPath[++keep]; } result.keep = keep; var idx, deepestUpdatedParams, deepestReactivate, reactivatedStatesByName = {}, pType = getStickyTransitionType(fromPath, toPath, keep); var ancestorUpdated = false; // When ancestor params change, treat reactivation as exit/enter // Calculate the "enter" transitions for new states in toPath // Enter transitions will be either "enter", "reactivate", or "updateStateParams" where // enter: full resolve, no special logic // reactivate: use previous locals // updateStateParams: like 'enter', except exit the inactive state before entering it. for (idx = keep; idx < toPath.length; idx++) { var enterTrans = !pType.to ? "enter" : getEnterTransition(toPath[idx], transition.toParams, ancestorUpdated); ancestorUpdated = (ancestorUpdated || enterTrans == 'updateStateParams'); result.enter[idx] = enterTrans; // If we're reactivating a state, make a note of it, so we can remove that state from the "inactive" list if (enterTrans == 'reactivate') deepestReactivate = reactivatedStatesByName[toPath[idx].name] = toPath[idx]; if (enterTrans == 'updateStateParams') deepestUpdatedParams = toPath[idx]; } deepestReactivate = deepestReactivate ? deepestReactivate.self.name + "." : ""; deepestUpdatedParams = deepestUpdatedParams ? deepestUpdatedParams.self.name + "." : ""; // Inactive states, before the transition is processed, mapped to the parent to the sticky state. var inactivesByParent = mapInactives(); // root ("") is always kept. Find the remaining names of the kept path. var keptStateNames = [""].concat(map(fromPath.slice(0, keep), function (state) { return state.self.name; })); // Locate currently and newly inactive states (at pivot and above) and store them in the output array 'inactives'. angular.forEach(keptStateNames, function (name) { var inactiveChildren = inactivesByParent[name]; for (var i = 0; inactiveChildren && i < inactiveChildren.length; i++) { var child = inactiveChildren[i]; // Don't organize state as inactive if we're about to reactivate it. if (!reactivatedStatesByName[child.name] && (!deepestReactivate || (child.self.name.indexOf(deepestReactivate) !== 0)) && (!deepestUpdatedParams || (child.self.name.indexOf(deepestUpdatedParams) !== 0))) result.inactives.push(child); } }); // Calculate the "exit" transition for states not kept, in fromPath. // Exit transition can be one of: // exit: standard state exit logic // inactivate: register state as an inactive state for (idx = keep; idx < fromPath.length; idx++) { var exitTrans = "exit"; if (pType.from) { // State is being inactivated, note this in result.inactives array result.inactives.push(fromPath[idx]); exitTrans = "inactivate"; } result.exit[idx] = exitTrans; } return result; }, // Adds a state to the inactivated sticky state registry. stateInactivated: function (state) { // Keep locals around. inactiveStates[state.self.name] = state; // Notify states they are being Inactivated (i.e., a different // sticky state tree is now active). state.self.status = 'inactive'; if (state.self.onInactivate) $injector.invoke(state.self.onInactivate, state.self, state.locals.globals); }, // Removes a previously inactivated state from the inactive sticky state registry stateReactivated: function (state) { if (inactiveStates[state.self.name]) { delete inactiveStates[state.self.name]; } state.self.status = 'entered'; // if (state.locals == null || state.locals.globals == null) debugger; if (state.self.onReactivate) $injector.invoke(state.self.onReactivate, state.self, state.locals.globals); }, // Exits all inactivated descendant substates when the ancestor state is exited. // When transitionTo is exiting a state, this function is called with the state being exited. It checks the // registry of inactivated states for descendants of the exited state and also exits those descendants. It then // removes the locals and de-registers the state from the inactivated registry. stateExiting: function (exiting, exitQueue, onExit) { var exitingNames = {}; angular.forEach(exitQueue, function (state) { exitingNames[state.self.name] = true; }); angular.forEach(inactiveStates, function (inactiveExiting, name) { // TODO: Might need to run the inactivations in the proper depth-first order? if (!exitingNames[name] && inactiveExiting.includes[exiting.name]) { if (DEBUG) $log.debug("Exiting " + name + " because it's a substate of " + exiting.name + " and wasn't found in ", exitingNames); if (inactiveExiting.self.onExit) $injector.invoke(inactiveExiting.self.onExit, inactiveExiting.self, inactiveExiting.locals.globals); angular.forEach(inactiveExiting.locals, function(localval, key) { delete inactivePseudoState.locals[key]; }); inactiveExiting.locals = null; inactiveExiting.self.status = 'exited'; delete inactiveStates[name]; } }); if (onExit) $injector.invoke(onExit, exiting.self, exiting.locals.globals); exiting.locals = null; exiting.self.status = 'exited'; delete inactiveStates[exiting.self.name]; }, // Removes a previously inactivated state from the inactive sticky state registry stateEntering: function (entering, params, onEnter) { var inactivatedState = getInactivatedState(entering); if (inactivatedState && !getInactivatedState(entering, params)) { var savedLocals = entering.locals; this.stateExiting(inactivatedState); entering.locals = savedLocals; } entering.self.status = 'entered'; if (onEnter) $injector.invoke(onEnter, entering.self, entering.locals.globals); }, reset: function reset(inactiveState, params) { var state = $state.get(inactiveState); var exiting = getInactivatedState(state, params); if (!exiting) return false; stickySupport.stateExiting(exiting); $rootScope.$broadcast("$viewContentLoading"); return true; } }; return stickySupport; }]; } angular.module("ct.ui.router.extras").provider("$stickyState", $StickyStateProvider); /** * Sticky States makes entire state trees "sticky". Sticky state trees are retained until their parent state is * exited. This can be useful to allow multiple modules, peers to each other, each module having its own independent * state tree. The peer modules can be activated and inactivated without any loss of their internal context, including * DOM content such as unvalidated/partially filled in forms, and even scroll position. * * DOM content is retained by declaring a named ui-view in the parent state, and filling it in with a named view from the * sticky state. * * Technical overview: * * ---PATHS--- * UI-Router uses state paths to manage entering and exiting of individual states. Each state "A.B.C.X" has its own path, starting * from the root state ("") and ending at the state "X". The path is composed the final state "X"'s ancestors, e.g., * [ "", "A", "B", "C", "X" ]. * * When a transition is processed, the previous path (fromState.path) is compared with the requested destination path * (toState.path). All states that the from and to paths have in common are "kept" during the transition. The last * "kept" element in the path is the "pivot". * * ---VIEWS--- * A View in UI-Router consists of a controller and a template. Each view belongs to one state, and a state can have many * views. Each view plugs into a ui-view element in the DOM of one of the parent state's view(s). * * View context is managed in UI-Router using a 'state locals' concept. When a state's views are fully loaded, those views * are placed on the states 'locals' object. Each locals object prototypally inherits from its parent state's locals object. * This means that state "A.B.C.X"'s locals object also has all of state "A.B.C"'s locals as well as those from "A.B" and "A". * The root state ("") defines no views, but it is included in the protypal inheritance chain. * * The locals object is used by the ui-view directive to load the template, render the content, create the child scope, * initialize the controller, etc. The ui-view directives caches the locals in a closure variable. If the locals are * identical (===), then the ui-view directive exits early, and does no rendering. * * In stock UI-Router, when a state is exited, that state's locals object is deleted and those views are cleaned up by * the ui-view directive shortly. * * ---Sticky States--- * UI-Router Extras keeps views for inactive states live, even when UI-Router thinks it has exited them. It does this * by creating a pseudo state called "__inactives" that is the parent of the root state. It also then defines a locals * object on the "__inactives" state, which the root state protoypally inherits from. By doing this, views for inactive * states are accessible through locals object's protoypal inheritance chain from any state in the system. * * ---Transitions--- * UI-Router Extras decorates the $state.transitionTo function. While a transition is in progress, the toState and * fromState internal state representations are modified in order to coerce stock UI-Router's transitionTo() into performing * the appropriate operations. When the transition promise is completed, the original toState and fromState values are * restored. * * Stock UI-Router's $state.transitionTo function uses toState.path and fromState.path to manage entering and exiting * states. UI-Router Extras takes advantage of those internal implementation details and prepares a toState.path and * fromState.path which coerces UI-Router into entering and exiting the correct states, or more importantly, not entering * and not exiting inactive or sticky states. It also replaces state.self.onEnter and state.self.onExit for elements in * the paths when they are being inactivated or reactivated. */ // ------------------------ Sticky State module-level variables ----------------------------------------------- var _StickyState; // internal reference to $stickyStateProvider var internalStates = {}; // Map { statename -> InternalStateObj } holds internal representation of all states var root, // Root state, internal representation pendingTransitions = [], // One transition may supersede another. This holds references to all pending transitions pendingRestore, // The restore function from the superseded transition inactivePseudoState, // This pseudo state holds all the inactive states' locals (resolved state data, such as views etc) versionHeuristics = { // Heuristics used to guess the current UI-Router Version hasParamSet: false }; // Creates a blank surrogate state function SurrogateState(type) { return { resolve: { }, locals: { globals: root && root.locals && root.locals.globals }, views: { }, self: { }, params: { }, ownParams: ( versionHeuristics.hasParamSet ? { $$equals: function() { return true; } } : []), surrogateType: type }; } // ------------------------ Sticky State registration and initialization code ---------------------------------- // Grab a copy of the $stickyState service for use by the transition management code angular.module("ct.ui.router.extras").run(["$stickyState", function ($stickyState) { _StickyState = $stickyState; }]); angular.module("ct.ui.router.extras").config( [ "$provide", "$stateProvider", '$stickyStateProvider', '$urlMatcherFactoryProvider', function ($provide, $stateProvider, $stickyStateProvider, $urlMatcherFactoryProvider) { versionHeuristics.hasParamSet = !!$urlMatcherFactoryProvider.ParamSet; // inactivePseudoState (__inactives) holds all the inactive locals which includes resolved states data, i.e., views, scope, etc inactivePseudoState = angular.extend(new SurrogateState("__inactives"), { self: { name: '__inactives' } }); // Reset other module scoped variables. This is to primarily to flush any previous state during karma runs. root = pendingRestore = undefined; pendingTransitions = []; // Decorate any state attribute in order to get access to the internal state representation. $stateProvider.decorator('parent', function (state, parentFn) { // Capture each internal UI-Router state representations as opposed to the user-defined state object. // The internal state is, e.g., the state returned by $state.$current as opposed to $state.current internalStates[state.self.name] = state; // Add an accessor for the internal state from the user defined state state.self.$$state = function () { return internalStates[state.self.name]; }; // Register the ones marked as "sticky" if (state.self.sticky === true) { $stickyStateProvider.registerStickyState(state.self); } return parentFn(state); }); var $state_transitionTo; // internal reference to the real $state.transitionTo function // Decorate the $state service, so we can decorate the $state.transitionTo() function with sticky state stuff. $provide.decorator("$state", ['$delegate', '$log', '$q', function ($state, $log, $q) { // Note: this code gets run only on the first state that is decorated root = $state.$current; internalStates[""] = root; root.parent = inactivePseudoState; // Make inactivePsuedoState the parent of root. "wat" inactivePseudoState.parent = undefined; // Make inactivePsuedoState the real root. root.locals = inherit(inactivePseudoState.locals, root.locals); // make root locals extend the __inactives locals. delete inactivePseudoState.locals.globals; // Hold on to the real $state.transitionTo in a module-scope variable. $state_transitionTo = $state.transitionTo; // ------------------------ Decorated transitionTo implementation begins here --------------------------- $state.transitionTo = function (to, toParams, options) { // TODO: Move this to module.run? // TODO: I'd rather have root.locals prototypally inherit from inactivePseudoState.locals // Link root.locals and inactives.locals. Do this at runtime, after root.locals has been set. if (!inactivePseudoState.locals) inactivePseudoState.locals = root.locals; var idx = pendingTransitions.length; if (pendingRestore) { pendingRestore(); if (DEBUG) { $log.debug("Restored paths from pending transition"); } } var fromState = $state.$current, fromParams = $state.params; var rel = options && options.relative || $state.$current; // Not sure if/when $state.$current is appropriate here. var toStateSelf = $state.get(to, rel); // exposes findState relative path functionality, returns state.self var savedToStatePath, savedFromStatePath, stickyTransitions; var reactivated = [], exited = [], terminalReactivatedState; var noop = function () { }; // Sticky states works by modifying the internal state objects of toState and fromState, especially their .path(s). // The restore() function is a closure scoped function that restores those states' definitions to their original values. var restore = function () { if (savedToStatePath) { toState.path = savedToStatePath; savedToStatePath = null; } if (savedFromStatePath) { fromState.path = savedFromStatePath; savedFromStatePath = null; } angular.forEach(restore.restoreFunctions, function (restoreFunction) { restoreFunction(); }); // Restore is done, now set the restore function to noop in case it gets called again. restore = noop; // pendingRestore keeps track of a transition that is in progress. It allows the decorated transitionTo // method to be re-entrant (for example, when superceding a transition, i.e., redirect). The decorated // transitionTo checks right away if there is a pending transition in progress and restores the paths // if so using pendingRestore. pendingRestore = null; pendingTransitions.splice(idx, 1); // Remove this transition from the list }; // All decorated transitions have their toState.path and fromState.path replaced. Surrogate states also make // additional changes to the states definition before handing the transition off to UI-Router. In particular, // certain types of surrogate states modify the state.self object's onEnter or onExit callbacks. // Those surrogate states must then register additional restore steps using restore.addRestoreFunction(fn) restore.restoreFunctions = []; restore.addRestoreFunction = function addRestoreFunction(fn) { this.restoreFunctions.push(fn); }; // --------------------- Surrogate State Functions ------------------------ // During a transition, the .path arrays in toState and fromState are replaced. Individual path elements // (states) which aren't being "kept" are replaced with surrogate elements (states). This section of the code // has factory functions for all the different types of surrogate states. function stateReactivatedSurrogatePhase1(state) { var surrogate = angular.extend(new SurrogateState("reactivate_phase1"), { locals: state.locals }); surrogate.self = angular.extend({}, state.self); return surrogate; } function stateReactivatedSurrogatePhase2(state) { var surrogate = angular.extend(new SurrogateState("reactivate_phase2"), state); var oldOnEnter = surrogate.self.onEnter; surrogate.resolve = {}; // Don't re-resolve when reactivating states (fixes issue #22) // TODO: Not 100% sure if this is necessary. I think resolveState will load the views if I don't do this. surrogate.views = {}; // Don't re-activate controllers when reactivating states (fixes issue #22) surrogate.self.onEnter = function () { // ui-router sets locals on the surrogate to a blank locals (because we gave it nothing to resolve) // Re-set it back to the already loaded state.locals here. surrogate.locals = state.locals; _StickyState.stateReactivated(state); }; restore.addRestoreFunction(function () { state.self.onEnter = oldOnEnter; }); return surrogate; } function stateInactivatedSurrogate(state) { var surrogate = new SurrogateState("inactivate"); surrogate.self = state.self; var oldOnExit = state.self.onExit; surrogate.self.onExit = function () { _StickyState.stateInactivated(state); }; restore.addRestoreFunction(function () { state.self.onExit = oldOnExit; }); return surrogate; } function stateEnteredSurrogate(state, toParams) { var oldOnEnter = state.self.onEnter; state.self.onEnter = function () { _StickyState.stateEntering(state, toParams, oldOnEnter); }; restore.addRestoreFunction(function () { state.self.onEnter = oldOnEnter; }); return state; } function stateExitedSurrogate(state) { var oldOnExit = state.self.onExit; state.self.onExit = function () { _StickyState.stateExiting(state, exited, oldOnExit); }; restore.addRestoreFunction(function () { state.self.onExit = oldOnExit; }); return state; } // --------------------- decorated .transitionTo() logic starts here ------------------------ if (toStateSelf) { var toState = internalStates[toStateSelf.name]; // have the state, now grab the internal state representation if (toState) { // Save the toState and fromState paths to be restored using restore() savedToStatePath = toState.path; savedFromStatePath = fromState.path; var currentTransition = {toState: toState, toParams: toParams || {}, fromState: fromState, fromParams: fromParams || {}, options: options}; pendingTransitions.push(currentTransition); // TODO: See if a list of pending transitions is necessary. pendingRestore = restore; // $StickyStateProvider.processTransition analyzes the states involved in the pending transition. It // returns an object that tells us: // 1) if we're involved in a sticky-type transition // 2) what types of exit transitions will occur for each "exited" path element // 3) what types of enter transitions will occur for each "entered" path element // 4) which states will be inactive if the transition succeeds. stickyTransitions = _StickyState.processTransition(currentTransition); if (DEBUG) debugTransition($log, currentTransition, stickyTransitions); // Begin processing of surrogate to and from paths. var surrogateToPath = toState.path.slice(0, stickyTransitions.keep); var surrogateFromPath = fromState.path.slice(0, stickyTransitions.keep); // Clear out and reload inactivePseudoState.locals each time transitionTo is called angular.forEach(inactivePseudoState.locals, function (local, name) { if (name.indexOf("@") != -1) delete inactivePseudoState.locals[name]; }); // Find all states that will be inactive once the transition succeeds. For each of those states, // place its view-locals on the __inactives pseudostate's .locals. This allows the ui-view directive // to access them and render the inactive views. for (var i = 0; i < stickyTransitions.inactives.length; i++) { var iLocals = stickyTransitions.inactives[i].locals; angular.forEach(iLocals, function (view, name) { if (iLocals.hasOwnProperty(name) && name.indexOf("@") != -1) { // Only grab this state's "view" locals inactivePseudoState.locals[name] = view; // Add all inactive views not already included. } }); } // Find all the states the transition will be entering. For each entered state, check entered-state-transition-type // Depending on the entered-state transition type, place the proper surrogate state on the surrogate toPath. angular.forEach(stickyTransitions.enter, function (value, idx) { var surrogate; if (value === "reactivate") { // Reactivated states require TWO surrogates. The "phase 1 reactivated surrogates" are added to both // to.path and from.path, and as such, are considered to be "kept" by UI-Router. // This is required to get UI-Router to add the surrogate locals to the protoypal locals object surrogate = stateReactivatedSurrogatePhase1(toState.path[idx]); surrogateToPath.push(surrogate); surrogateFromPath.push(surrogate); // so toPath[i] === fromPath[i] // The "phase 2 reactivated surrogate" is added to the END of the .path, after all the phase 1 // surrogates have been added. reactivated.push(stateReactivatedSurrogatePhase2(toState.path[idx])); terminalReactivatedState = surrogate; } else if (value === "updateStateParams") { // If the state params have been changed, we need to exit any inactive states and re-enter them. surrogate = stateEnteredSurrogate(toState.path[idx]); surrogateToPath.push(surrogate); terminalReactivatedState = surrogate; } else if (value === "enter") { // Standard enter transition. We still wrap it in a surrogate. surrogateToPath.push(stateEnteredSurrogate(toState.path[idx])); } }); // Find all the states the transition will be exiting. For each exited state, check the exited-state-transition-type. // Depending on the exited-state transition type, place a surrogate state on the surrogate fromPath. angular.forEach(stickyTransitions.exit, function (value, idx) { var exiting = fromState.path[idx]; if (value === "inactivate") { surrogateFromPath.push(stateInactivatedSurrogate(exiting)); exited.push(exiting); } else if (value === "exit") { surrogateFromPath.push(stateExitedSurrogate(exiting)); exited.push(exiting); } }); // Add surrogate for reactivated to ToPath again, this time without a matching FromPath entry // This is to get ui-router to call the surrogate's onEnter callback. if (reactivated.length) { angular.forEach(reactivated, function (surrogate) { surrogateToPath.push(surrogate); }); } // In some cases, we may be some state, but not its children states. If that's the case, we have to // exit all the children of the deepest reactivated state. if (terminalReactivatedState) { var prefix = terminalReactivatedState.self.name + "."; var inactiveStates = _StickyState.getInactiveStates(); var inactiveOrphans = []; inactiveStates.forEach(function (exiting) { if (exiting.self.name.indexOf(prefix) === 0) { inactiveOrphans.push(exiting); } }); inactiveOrphans.sort(); inactiveOrphans.reverse(); // Add surrogate exited states for all orphaned descendants of the Deepest Reactivated State surrogateFromPath = surrogateFromPath.concat(map(inactiveOrphans, function (exiting) { return stateExitedSurrogate(exiting); })); exited = exited.concat(inactiveOrphans); } // Replace the .path variables. toState.path and fromState.path are now ready for a sticky transition. toState.path = surrogateToPath; fromState.path = surrogateFromPath; var pathMessage = function (state) { return (state.surrogateType ? state.surrogateType + ":" : "") + state.self.name; }; if (DEBUG) $log.debug("SurrogateFromPath: ", map(surrogateFromPath, pathMessage)); if (DEBUG) $log.debug("SurrogateToPath: ", map(surrogateToPath, pathMessage)); } } // toState and fromState are all set up; now run stock UI-Router's $state.transitionTo(). var transitionPromise = $state_transitionTo.apply($state, arguments); // Add post-transition promise handlers, then return the promise to the original caller. return transitionPromise.then(function transitionSuccess(state) { // First, restore toState and fromState to their original values. restore(); if (DEBUG) debugViewsAfterSuccess($log, internalStates[state.name], $state); state.status = 'active'; // TODO: This status is used in statevis.js, and almost certainly belongs elsewhere. return state; }, function transitionFailed(err) { restore(); if (DEBUG && err.message !== "transition prevented" && err.message !== "transition aborted" && err.message !== "transition superseded") { $log.debug("transition failed", err); console.log(err.stack); } return $q.reject(err); }); }; return $state; }]); } ] ); function debugTransition($log, currentTransition, stickyTransition) { function message(path, index, state) { return (path[index] ? path[index].toUpperCase() + ": " + state.self.name : "(" + state.self.name + ")"); } var inactiveLogVar = map(stickyTransition.inactives, function (state) { return state.self.name; }); var enterLogVar = map(currentTransition.toState.path, function (state, index) { return message(stickyTransition.enter, index, state); }); var exitLogVar = map(currentTransition.fromState.path, function (state, index) { return message(stickyTransition.exit, index, state); }); var transitionMessage = currentTransition.fromState.self.name + ": " + angular.toJson(currentTransition.fromParams) + ": " + " -> " + currentTransition.toState.self.name + ": " + angular.toJson(currentTransition.toParams); $log.debug(" Current transition: ", transitionMessage); $log.debug("Before transition, inactives are: : ", map(_StickyState.getInactiveStates(), function (s) { return s.self.name; })); $log.debug("After transition, inactives will be: ", inactiveLogVar); $log.debug("Transition will exit: ", exitLogVar); $log.debug("Transition will enter: ", enterLogVar); } function debugViewsAfterSuccess($log, currentState, $state) { $log.debug("Current state: " + currentState.self.name + ", inactive states: ", map(_StickyState.getInactiveStates(), function (s) { return s.self.name; })); var viewMsg = function (local, name) { return "'" + name + "' (" + local.$$state.name + ")"; }; var statesOnly = function (local, name) { return name != 'globals' && name != 'resolve'; }; var viewsForState = function (state) { var views = map(filterObj(state.locals, statesOnly), viewMsg).join(", "); return "(" + (state.self.name ? state.self.name : "root") + ".locals" + (views.length ? ": " + views : "") + ")"; }; var message = viewsForState(currentState); var parent = currentState.parent; while (parent && parent !== currentState) { if (parent.self.name === "") { // Show the __inactives before showing root state. message = viewsForState($state.$current.path[0]) + " / " + message; } message = viewsForState(parent) + " / " + message; currentState = parent; parent = currentState.parent; } $log.debug("Views: " + message); } angular.module('ct.ui.router.extras').provider('$futureState', [ '$stateProvider', '$urlRouterProvider', '$urlMatcherFactoryProvider', function _futureStateProvider($stateProvider, $urlRouterProvider, $urlMatcherFactory) { var stateFactories = {}, futureStates = {}; var transitionPending = false, resolveFunctions = [], initPromise, initDone = false; var provider = this; // This function registers a promiseFn, to be resolved before the url/state matching code // will reject a route. The promiseFn is injected/executed using the runtime $injector. // The function should return a promise. // When all registered promises are resolved, then the route is re-sync'ed. // Example: function($http) { // return $http.get('//server.com/api/DynamicFutureStates').then(function(data) { // angular.forEach(data.futureStates, function(fstate) { $futureStateProvider.futureState(fstate); }); // }; // } this.addResolve = function (promiseFn) { resolveFunctions.push(promiseFn); }; // Register a state factory function for a particular future-state type. This factory, given a future-state object, // should create a ui-router state. // The factory function is injected/executed using the runtime $injector. The future-state is injected as 'futureState'. // Example: // $futureStateProvider.stateFactory('test', function(futureState) { // return { // name: futureState.stateName, // url: futureState.urlFragment, // template: '<h3>Future State Template</h3>', // controller: function() { // console.log("Entered state " + futureState.stateName); // } // } // }); this.stateFactory = function (futureStateType, factory) { stateFactories[futureStateType] = factory; }; this.futureState = function (futureState) { if (futureState.stateName) // backwards compat for now futureState.name = futureState.stateName; if (futureState.urlPrefix) // backwards compat for now futureState.url = "^" + futureState.urlPrefix; futureStates[futureState.name] = futureState; var parentMatcher, parentName = futureState.name.split(/\./).slice(0, -1).join("."), realParent = findState(futureState.parent || parentName); if (realParent) { parentMatcher = realParent.url; } else { var futureParent = findState((futureState.parent || parentName), true); if (!futureParent) throw new Error("Couldn't determine parent state of future state. FutureState:" + angular.toJson(futureState)); var pattern = futureParent.urlMatcher.source.replace(/\*rest$/, ""); parentMatcher = $urlMatcherFactory.compile(pattern); futureState.parentFutureState = futureParent; } futureState.urlMatcher = futureState.url.charAt(0) === "^" ? $urlMatcherFactory.compile(futureState.url.substring(1) + "*rest") : parentMatcher.concat(futureState.url + "*rest"); }; this.get = function () { return angular.extend({}, futureStates); }; function findState(stateOrName, findFutureState) { var statename = angular.isObject(stateOrName) ? stateOrName.name : stateOrName; return !findFutureState ? internalStates[statename] : futureStates[statename]; } /* options is an object with at least a name or url attribute */ function findFutureState($state, options) { if (options.name) { var nameComponents = options.name.split(/\./); if (options.name.charAt(0) === '.') nameComponents[0] = $state.current.name; while (nameComponents.length) { var stateName = nameComponents.join("."); if ($state.get(stateName, { relative: $state.current })) return null; // State is already defined; nothing to do if (futureStates[stateName]) return futureStates[stateName]; nameComponents.pop(); } } if (options.url) { var matches = []; for(var future in futureStates) { if (futureStates[future].urlMatcher.exec(options.url)) { matches.push(futureStates[future]); } } // Find most specific by ignoring matching parents from matches var copy = matches.slice(0); for (var i = matches.length - 1; i >= 0; i--) { for (var j = 0; j < copy.length; j++) { if (matches[i] === copy[j].parentFutureState) matches.splice(i, 1); } } return matches[0]; } } function lazyLoadState($injector, futureState) { if (!futureState) { var deferred = $q.defer(); deferred.reject("No lazyState passed in " + futureState); return deferred.promise; } var promise = $q.when(true), parentFuture = futureState.parentFutureState; if (parentFuture && futureStates[parentFuture.name]) { promise = lazyLoadState($injector, futureStates[parentFuture.name]); } var type = futureState.type; var factory = stateFactories[type]; if (!factory) throw Error("No state factory for futureState.type: " + (futureState && futureState.type)); return promise .then(function() { return $injector.invoke(factory, factory, { futureState: futureState }); }) .finally(function() { delete(futureStates[futureState.name]); }); } var otherwiseFunc = [ '$log', '$location', function otherwiseFunc($log, $location) { $log.debug("Unable to map " + $location.path()); }]; function futureState_otherwise($injector, $location) { var resyncing = false; var lazyLoadMissingState = ['$rootScope', '$urlRouter', '$state', function lazyLoadMissingState($rootScope, $urlRouter, $state) { if (!initDone) { // Asynchronously load state definitions, then resync URL initPromise().then(function initialResync() { resyncing = true; $urlRouter.sync(); resyncing = false; }); initDone = true; return; } var futureState = findFutureState($state, { url: $location.path() }); if (!futureState) { return $injector.invoke(otherwiseFunc); } transitionPending = true; // Config loaded. Asynchronously lazy-load state definition from URL fragment, if mapped. lazyLoadState($injector, futureState).then(function lazyLoadedStateCallback(state) { // TODO: Should have a specific resolve value that says 'dont register a state because I already did' if (state && (!$state.get(state) || (state.name && !$state.get(state.name)))) $stateProvider.state(state); resyncing = true; $urlRouter.sync(); resyncing = false; transitionPending = false; }, function lazyLoadStateAborted() { transitionPending = false; return $injector.invoke(otherwiseFunc); }); }]; if (transitionPending) return; var nextFn = resyncing ? otherwiseFunc : lazyLoadMissingState; return $injector.invoke(nextFn); } $urlRouterProvider.otherwise(futureState_otherwise); $urlRouterProvider.otherwise = function(rule) { if (angular.isString(rule)) { var redirect = rule; rule = function () { return redirect; }; } else if (!angular.isFunction(rule)) throw new Error("'rule' must be a function"); otherwiseFunc = rule; return $urlRouterProvider; }; var serviceObject = { getResolvePromise: function () { return initPromise(); } }; // Used in .run() block to init this.$get = [ '$injector', '$state', '$q', '$rootScope', '$urlRouter', '$timeout', '$log', function futureStateProvider_get($injector, $state, $q, $rootScope, $urlRouter, $timeout, $log) { function init() { $rootScope.$on("$stateNotFound", function futureState_notFound(event, unfoundState, fromState, fromParams) { if (transitionPending) return; $log.debug("event, unfoundState, fromState, fromParams", event, unfoundState, fromState, fromParams); var futureState = findFutureState($state, { name: unfoundState.to }); if (!futureState) return; event.preventDefault(); transitionPending = true; var promise = lazyLoadState($injector, futureState); promise.then(function (state) { // TODO: Should have a specific resolve value that says 'dont register a state because I already did' if (state && (!$state.get(state) || (state.name && !$state.get(state.name)))) $stateProvider.state(state); $state.go(unfoundState.to, unfoundState.toParams); transitionPending = false; }, function (error) { console.log("failed to lazy load state ", error); $state.go(fromState, fromParams); transitionPending = false; }); }); // Do this better. Want to load remote config once, before everything else if (!initPromise) { var promises = []; angular.forEach(resolveFunctions, function (promiseFn) { promises.push($injector.invoke(promiseFn)); }); initPromise = function () { return $q.all(promises); }; // initPromise = _.once(function flattenFutureStates() { // var allPromises = $q.all(promises); // return allPromises.then(function(data) { // return _.flatten(data); // }); // }); } // TODO: analyze this. I'm calling $urlRouter.sync() in two places for retry-initial-transition. // TODO: I should only need to do this once. Pick the better place and remove the extra resync. initPromise().then(function retryInitialState() { $timeout(function () { if ($state.transition) { $state.transition.then($urlRouter.sync, $urlRouter.sync); } else { $urlRouter.sync(); } }); }); } init(); serviceObject.state = $stateProvider.state; serviceObject.futureState = provider.futureState; serviceObject.get = provider.get; return serviceObject; }]; }]); angular.module('ct.ui.router.extras').run(['$futureState', // Just inject $futureState so it gets initialized. function ($futureState) { } ]); angular.module('ct.ui.router.extras').service("$previousState", [ '$rootScope', '$state', function ($rootScope, $state) { var previous = null; var memos = {}; var lastPrevious = null; $rootScope.$on("$stateChangeStart", function (evt, toState, toStateParams, fromState, fromStateParams) { // State change is starting. Keep track of the CURRENT previous state in case we have to restore it lastPrevious = previous; previous = { state: fromState, params: fromStateParams }; }); $rootScope.$on("$stateChangeError", function () { // State change did not occur due to an error. Restore the previous previous state. previous = lastPrevious; lastPrevious = null; }); $rootScope.$on("$stateChangeSuccess", function () { lastPrevious = null; }); var $previousState = { get: function (memoName) { return memoName ? memos[memoName] : previous; }, go: function (memoName, options) { var to = $previousState.get(memoName); return $state.go(to.state, to.params, options); }, memo: function (memoName, defaultStateName, defaultStateParams) { memos[memoName] = previous || { state: $state.get(defaultStateName), params: defaultStateParams }; }, forget: function (memoName) { delete memos[memoName]; } }; return $previousState; } ] ); angular.module('ct.ui.router.extras').run(['$previousState', function ($previousState) { // Inject $previousState so it can register $rootScope events }]); angular.module("ct.ui.router.extras").config( [ "$provide", function ($provide) { // Decorate the $state service, so we can replace $state.transitionTo() $provide.decorator("$state", ['$delegate', '$rootScope', '$q', '$injector', function ($state, $rootScope, $q, $injector) { // Keep an internal reference to the real $state.transitionTo function var $state_transitionTo = $state.transitionTo; // $state.transitionTo can be re-entered. Keep track of re-entrant stack var transitionDepth = -1; var tDataStack = []; var restoreFnStack = []; // This function decorates the $injector, adding { $transition$: tData } to invoke() and instantiate() locals. // It returns a function that restores $injector to its previous state. function decorateInjector(tData) { var oldinvoke = $injector.invoke; var oldinstantiate = $injector.instantiate; $injector.invoke = function (fn, self, locals) { return oldinvoke(fn, self, angular.extend({$transition$: tData}, locals)); }; $injector.instantiate = function (fn, locals) { return oldinstantiate(fn, angular.extend({$transition$: tData}, locals)); }; return function restoreItems() { $injector.invoke = oldinvoke; $injector.instantiate = oldinstantiate; }; } function popStack() { restoreFnStack.pop()(); tDataStack.pop(); transitionDepth--; } // This promise callback (for when the real transitionTo is successful) runs the restore function for the // current stack level, then broadcasts the $transitionSuccess event. function transitionSuccess(deferred, tSuccess) { return function successFn(data) { popStack(); $rootScope.$broadcast("$transitionSuccess", tSuccess); return deferred.resolve(data); }; } // This promise callback (for when the real transitionTo fails) runs the restore function for the // current stack level, then broadcasts the $transitionError event. function transitionFailure(deferred, tFail) { return function failureFn(error) { popStack(); $rootScope.$broadcast("$transitionError", tFail, error); return deferred.reject(error); }; } // Decorate $state.transitionTo. $state.transitionTo = function (to, toParams, options) { // Create a deferred/promise which can be used earlier than UI-Router's transition promise. var deferred = $q.defer(); // Place the promise in a transition data, and place it on the stack to be used in $stateChangeStart var tData = tDataStack[++transitionDepth] = { promise: deferred.promise }; // placeholder restoreFn in case transitionTo doesn't reach $stateChangeStart (state not found, etc) restoreFnStack[transitionDepth] = function() { }; // Invoke the real $state.transitionTo var tPromise = $state_transitionTo.apply($state, arguments); // insert our promise callbacks into the chain. return tPromise.then(transitionSuccess(deferred, tData), transitionFailure(deferred, tData)); }; // This event is handled synchronously in transitionTo call stack $rootScope.$on("$stateChangeStart", function (evt, toState, toParams, fromState, fromParams) { var depth = transitionDepth; // To/From is now normalized by ui-router. Add this information to the transition data object. var tData = angular.extend(tDataStack[depth], { to: { state: toState, params: toParams }, from: { state: fromState, params: fromParams } }); var restoreFn = decorateInjector(tData); restoreFnStack[depth] = restoreFn; $rootScope.$broadcast("$transitionStart", tData); } ); return $state; }]); } ] ); })(window, window.angular);
www/src/InstanceInfo.js
ctnitchie/ec2-dashboard
import React from 'react'; import {ec2Service, eventBus} from './services'; import autobind from 'react-autobind'; import moment from 'moment'; export default class InstanceInfo extends React.Component { constructor(props) { super(props); this.state = { state: props.record.state, launched: props.record.launched, expanded: false }; autobind(this); } getName() { if (this.props.record.tags.Name) { return this.props.record.tags.Name + " (" + this.props.record.id + ")"; } else { return this.props.record.id; } } getLastLaunched() { return moment(this.state.launched).format('MMMM Do, YYYY h:mm:ss a'); } onInstanceStateChange(data) { this.setState({state: data.state, launched: data.launched}); } expand() { this.setState({expanded: true}); } collapse() { this.setState({expanded: false}); } componentDidMount() { eventBus.on('instanceStateChanged.' + this.props.record.id, this.onInstanceStateChange); eventBus.on('expandAll', this.expand); eventBus.on('collapseAll', this.collapse); switch(this.state.state) { case 'pending': ec2Service.requestNotification('start', [this.props.record.id]); break; case 'stopping': ec2Service.requestNotification('stop', [this.props.record.id]); break; } } componentWillUnmount() { eventBus.removeListener('instanceStateChanged.' + this.props.record.id, this.onInstanceStateChange); eventBus.removeListener('expandAll', this.expand); eventBus.removeListener('collapseAll', this.collapse); } doStart() { if (confirm("Are you sure you want to start the instance \"" + this.getName() + "\"?")) { ec2Service.startInstances([this.props.record.id]); this.setState({state: 'startRequested'}); } } doStop() { if (confirm("Are you sure you want to stop the instance \"" + this.getName() + "\"?")) { ec2Service.stopInstances([this.props.record.id]); this.setState({state: 'stopRequested'}); } } toggle(evt) { this.setState({expanded: !this.state.expanded}); evt.preventDefault(); return false; } render() { let className = "instanceInfo col-sm-6 col-sm-offset-3 col-xs-12 " + this.state.state; let buttonNode = ''; switch(this.state.state) { case 'stopped': buttonNode = ( <button className="btn btn-success btn-xs" onClick={this.doStart}> <span className="glyphicon glyphicon-play"></span> &nbsp;Start </button> ); break; case 'running': buttonNode = ( <button className="btn btn-danger btn-xs" onClick={this.doStop}> <span className="glyphicon glyphicon-stop"></span> &nbsp;Stop </button> ); break; default: buttonNode = <span className="spinner"/>; break; } let publicIp = this.props.record.publicIp; let pubIdNode = ''; if (publicIp) { let href = "http://" + this.props.record.publicIp; pubIdNode = <li><b>Public IP:</b>&nbsp;<a href={href} target="_blank">{this.props.record.publicIp}</a></li>; } let tagNodes = []; Object.keys(this.props.record.tags).forEach((tag) => { tagNodes.push(<li key={tag} className="tag"><b>{tag}:</b>&nbsp;{this.props.record.tags[tag]}</li>); }); let togglerClass = "glyphicon glyphicon-triangle-" + (this.state.expanded ? 'bottom' : 'right'); let listClass = 'instanceDetails ' + (this.state.expanded ? 'expanded' : 'collapsed'); let securityGroupList = []; this.props.record.securityGroups.forEach(grp => { securityGroupList.push(<li key={grp}>{grp}</li>); }); return ( <div className={className}> <div className="row"> <div className="col-sm-9 col-xs-12"> <div className="instanceName"> <a href="#" onClick={this.toggle}> <span className={togglerClass}/> &nbsp; {this.getName()} </a> </div> <ul className={listClass}> <li><b>Last launched:</b>&nbsp;{this.getLastLaunched()}</li> <li><b>Instance type:</b>&nbsp;{this.props.record.type}</li> <li><b>Private IP:</b>&nbsp;{this.props.record.privateIp}</li> <li><b>Security Groups:</b><ul>{securityGroupList}</ul></li> {pubIdNode} {tagNodes} </ul> </div> <div className="col-sm-3 col-xs-12 text-right instanceActions"> {this.state.state} &nbsp; {buttonNode} </div> </div> </div> ); } }
src/parser/warrior/arms/modules/talents/ImpendingVictory.js
ronaldpereira/WoWAnalyzer
import React from 'react'; import SPELLS from 'common/SPELLS'; import { formatThousands } from 'common/format'; import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer'; import AbilityTracker from 'parser/shared/modules/AbilityTracker'; import SpellLink from 'common/SpellLink'; import StatisticListBoxItem from 'interface/others/StatisticListBoxItem'; import Events from 'parser/core/Events'; /** * Instantly attack the target, causing [ 39.31% of Attack Power ] damage * and healing you for 20% of your maximum health. * * Killing an enemy that yields experience or honor resets the cooldown of Impending Victory. */ class ImpendingVictory extends Analyzer { static dependencies = { abilityTracker: AbilityTracker, }; totalHeal = 0; constructor(...args) { super(...args); this.active = this.selectedCombatant.hasTalent(SPELLS.IMPENDING_VICTORY_TALENT.id); this.addEventListener(Events.heal.by(SELECTED_PLAYER).spell(SPELLS.IMPENDING_VICTORY_TALENT_HEAL), this._onImpendingVictoryHeal); } _onImpendingVictoryHeal(event) { this.totalHeal += event.amount; } subStatistic() { const impendingVictory = this.abilityTracker.getAbility(SPELLS.IMPENDING_VICTORY_TALENT.id); const total = impendingVictory.damageEffective || 0; const avg = this.totalHeal / (impendingVictory.casts || 1); return ( <StatisticListBoxItem title={<>Average <SpellLink id={SPELLS.IMPENDING_VICTORY_TALENT.id} /> heal</>} value={formatThousands(avg)} valueTooltip={( <> Total Impending Victory heal: {formatThousands(this.totalHeal)} <br /> Total Impending Victory damages: {formatThousands(total)} </> )} /> ); } } export default ImpendingVictory;
Inspector/js/app.js
zenzhu/WebDriverAgent
/** * 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. */ import React from 'react'; import HTTP from 'js/http'; import Screen from 'js/screen'; import ScreenshotFactory from 'js/screenshot_factory'; import Tree from 'js/tree'; import TreeNode from 'js/tree_node'; import TreeContext from 'js/tree_context'; import Inspector from 'js/inspector'; require('css/app.css') const SCREENSHOT_ENDPOINT = 'screenshot'; const TREE_ENDPOINT = 'source'; const ORIENTATION_ENDPOINT = 'orientation'; class App extends React.Component { constructor(props) { super(props); this.state = {}; } componentDidMount() { this.fetchScreenshot(); this.fetchTree(); } fetchScreenshot() { HTTP.get(ORIENTATION_ENDPOINT, (orientation) => { HTTP.get(SCREENSHOT_ENDPOINT, (base64EncodedImage) => { ScreenshotFactory.createScreenshot(orientation, base64EncodedImage, (screenshot) => { this.setState({ screenshot: screenshot, }); }); }); }); } fetchTree() { HTTP.get(TREE_ENDPOINT, (treeInfo) => { this.setState({ rootNode: TreeNode.buildNode(treeInfo.tree, new TreeContext()), }); }); } render() { return ( <div id="app"> <Screen highlightedNode={this.state.highlightedNode} screenshot={this.state.screenshot} rootNode={this.state.rootNode} /> <Tree onHighlightedNodeChange={(node) => { this.setState({ highlightedNode: node, }); }} onSelectedNodeChange={(node) => { this.setState({ selectedNode: node, }); }} rootNode={this.state.rootNode} selectedNode={this.state.selectedNode} /> <Inspector selectedNode={this.state.selectedNode} /> </div> ); } } React.render(<App />, document.body);
app/javascript/components/collection_index.js
nulib/avalon
/* * Copyright 2011-2020, The Trustees of Indiana University and Northwestern * University. 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. * --- END LICENSE_HEADER BLOCK --- */ import React from 'react'; import { render } from 'react-dom'; import CollectionList from './CollectionList'; const props = { baseUrl: 'https://spruce.dlib.indiana.edu/collections.json' // filter: 'Good Morning Dave' }; render(<CollectionList {...props} />, document.getElementById('root'));
app/src/components/Navigation.js
open-austin/budgetparty
import React from 'react' import { Link } from 'react-router-dom' import PropTypes from 'prop-types'; import TotalFundAvailable from './TotalFundAvailable' import ServiceFundsAvailable from './ServiceFundsAvailable' import avatar from '../images/avatar.svg' import back from '../images/back.svg' import close from '../images/close.svg' const Navigation = (props) => { const { centerText, history, showClose, showBack, showUser, showTotalFunds, showServiceFunds, funds, service, user, } = props return ( <nav className="Navigation"> { showBack && <Link to="/dashboard" className="flex"> <img src={back} alt="Go Back to Dashboard" className="Navigation__icon--left" /> </Link> } { showUser && <div className="Navigation__user-container"> <Link to="/user"> <img src={(user && user.photoURL) || avatar} alt="User Account" className="Navigation__icon--left" /> </Link> <p className="Navigation__welcome-message">{(user && user.displayName) || (user && user.email)}</p> </div> } { showTotalFunds && <TotalFundAvailable funds={funds} /> } { showServiceFunds && <ServiceFundsAvailable service={service} /> } { showClose && <div className="Navigation__special-header"> <div className="flex Navigation__center-text">{centerText}</div> <div className="flex"> <img src={close} alt="Go Back to Department" className="Navigation__icon--right" onClick={history.goBack} /> </div> </div> } </nav> ) } export default Navigation Navigation.propTypes = { showClose: PropTypes.bool, showBack: PropTypes.bool, showUser: PropTypes.bool, showTotalFunds: PropTypes.bool, showServiceFunds: PropTypes.bool, funds: PropTypes.shape({ generalFund: PropTypes.number, servicesSum: PropTypes.number, generalFund2016: PropTypes.number, }), service: PropTypes.shape({ title: PropTypes.string, amount: PropTypes.number, }), history: PropTypes.object, centerText: PropTypes.string, user: PropTypes.object, };
www/static/src/admin/components/UserPage.js
wmk223/firekylin
import React from 'react'; import autobind from 'autobind-decorator'; import BaseComponent from './BaseComponent'; @autobind class UserPage extends BaseComponent { componentDidMount() { this.subscribe( ); } render() { return ( <div className="UserPage page"> <div className="title"> <h2>用户管理</h2> </div> </div> ) } onChange(data) { } } export default UserPage;
src/svg-icons/av/video-label.js
mit-cml/iot-website-source
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvVideoLabel = (props) => ( <SvgIcon {...props}> <path d="M21 3H3c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 13H3V5h18v11z"/> </SvgIcon> ); AvVideoLabel = pure(AvVideoLabel); AvVideoLabel.displayName = 'AvVideoLabel'; AvVideoLabel.muiName = 'SvgIcon'; export default AvVideoLabel;
test/react-native-cli/features/fixtures/rn0_67/App.js
bugsnag/bugsnag-js
import React from 'react'; import Bugsnag from "@bugsnag/react-native"; import { SafeAreaView, StyleSheet, ScrollView, View, Text, StatusBar, Button, NativeModules } from 'react-native'; import { Colors } from 'react-native/Libraries/NewAppScreen'; function jsNotify() { try { // execute crashy code iMadeThisUp(); } catch (error) { console.log('Bugsnag.notify JS error') Bugsnag.notify(error); } } function nativeNotify() { console.log('Bugsnag.notify native error') NativeModules.CrashyCrashy.handledError() } const App: () => React$Node = () => { return ( <> <StatusBar barStyle="dark-content" /> <SafeAreaView> <ScrollView contentInsetAdjustmentBehavior="automatic" style={styles.scrollView}> {global.HermesInternal == null ? null : ( <View style={styles.engine}> <Text style={styles.footer}>Engine: Hermes</Text> </View> )} <View style={styles.body}> <Text>React Native CLI end-to-end test app</Text> <Button style={styles.clickyButton} accessibilityLabel='js_notify' title='JS Notify' onPress={jsNotify}/> <Button style={styles.clickyButton} accessibilityLabel='native_notify' title='Native Notify' onPress={nativeNotify}/> </View> </ScrollView> </SafeAreaView> </> ); }; const styles = StyleSheet.create({ scrollView: { backgroundColor: Colors.lighter, }, engine: { position: 'absolute', right: 0, }, body: { backgroundColor: Colors.white, }, sectionContainer: { marginTop: 32, paddingHorizontal: 24, }, sectionTitle: { fontSize: 24, fontWeight: '600', color: Colors.black, }, sectionDescription: { marginTop: 8, fontSize: 18, fontWeight: '400', color: Colors.dark, }, highlight: { fontWeight: '700', }, footer: { color: Colors.dark, fontSize: 12, fontWeight: '600', padding: 4, paddingRight: 12, textAlign: 'right', }, clickyButton: { backgroundColor: '#acbcef', borderWidth: 0.5, borderColor: '#000', borderRadius: 4, margin: 5, padding: 5 } }); export default App;
src/components/table/Row.js
f0zze/rosemary-ui
import React from 'react'; const PROPERTY_TYPES = { item: React.PropTypes.any }; const DEFAULT_PROPS = {}; class Row extends React.Component { constructor(props) { super(props); } shouldComponentUpdate(nextProps, nextState) { if (nextProps.className !== this.props.className) { return true; } return nextProps.item !== this.props.item; } render() { return ( <tr className={this.props.className} onClick={(e) => this.props.onClick && this.props.onClick(e)}> {this.props.children} </tr> ); } } Row.propTypes = PROPERTY_TYPES; Row.defaultProps = DEFAULT_PROPS; export default Row;
src/Tabs.js
HPate-Riptide/react-bootstrap
import React from 'react'; import requiredForA11y from 'react-prop-types/lib/isRequiredForA11y'; import uncontrollable from 'uncontrollable'; import Nav from './Nav'; import NavItem from './NavItem'; import UncontrolledTabContainer from './TabContainer'; import TabContent from './TabContent'; import { bsClass as setBsClass } from './utils/bootstrapUtils'; import ValidComponentChildren from './utils/ValidComponentChildren'; const TabContainer = UncontrolledTabContainer.ControlledComponent; const propTypes = { /** * Mark the Tab with a matching `eventKey` as active. * * @controllable onSelect */ activeKey: React.PropTypes.any, /** * Navigation style */ bsStyle: React.PropTypes.oneOf(['tabs', 'pills']), animation: React.PropTypes.bool, id: requiredForA11y(React.PropTypes.oneOfType([ React.PropTypes.string, React.PropTypes.number, ])), /** * Callback fired when a Tab is selected. * * ```js * function ( * Any eventKey, * SyntheticEvent event? * ) * ``` * * @controllable activeKey */ onSelect: React.PropTypes.func, /** * Unmount tabs (remove it from the DOM) when it is no longer visible */ unmountOnExit: React.PropTypes.bool, }; const defaultProps = { bsStyle: 'tabs', animation: true, unmountOnExit: false }; function getDefaultActiveKey(children) { let defaultActiveKey; ValidComponentChildren.forEach(children, child => { if (defaultActiveKey == null) { defaultActiveKey = child.props.eventKey; } }); return defaultActiveKey; } class Tabs extends React.Component { renderTab(child) { const { title, eventKey, disabled, tabClassName } = child.props; if (title == null) { return null; } return ( <NavItem eventKey={eventKey} disabled={disabled} className={tabClassName} > {title} </NavItem> ); } render() { const { id, onSelect, animation, unmountOnExit, bsClass, className, style, children, activeKey = getDefaultActiveKey(children), ...props } = this.props; return ( <TabContainer id={id} activeKey={activeKey} onSelect={onSelect} className={className} style={style} > <div> <Nav {...props} role="tablist" > {ValidComponentChildren.map(children, this.renderTab)} </Nav> <TabContent bsClass={bsClass} animation={animation} unmountOnExit={unmountOnExit} > {children} </TabContent> </div> </TabContainer> ); } } Tabs.propTypes = propTypes; Tabs.defaultProps = defaultProps; setBsClass('tab', Tabs); export default uncontrollable(Tabs, { activeKey: 'onSelect' });
local-cli/templates/HelloNavigation/components/ListItem.js
disparu86/react-native
'use strict'; import React, { Component } from 'react'; import { Platform, StyleSheet, Text, TouchableHighlight, TouchableNativeFeedback, View, } from 'react-native'; /** * Renders the right type of Touchable for the list item, based on platform. */ const Touchable = ({onPress, children}) => { const child = React.Children.only(children); if (Platform.OS === 'android') { return ( <TouchableNativeFeedback onPress={onPress}> {child} </TouchableNativeFeedback> ); } else { return ( <TouchableHighlight onPress={onPress} underlayColor="#ddd"> {child} </TouchableHighlight> ); } } const ListItem = ({label, onPress}) => ( <Touchable onPress={onPress}> <View style={styles.item}> <Text style={styles.label}>{label}</Text> </View> </Touchable> ); const styles = StyleSheet.create({ item: { height: 48, justifyContent: 'center', paddingLeft: 12, borderBottomWidth: StyleSheet.hairlineWidth, borderBottomColor: '#ddd', }, label: { fontSize: 16, } }); export default ListItem;
ui/src/components/featureValues/nonOption.js
jollopre/mps
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { debounce } from '../../utils/debounce'; import { putFeatureValue } from '../../actions/featureValues'; class NonOption extends Component { constructor(props) { super(props); this.onChangeHandler = this.onChangeHandler.bind(this); this.deferred = debounce(this.action.bind(this), 2000); const { featureValue } = this.props; const value = featureValue.value !== null ? featureValue.value : ''; this.state = { value }; } action() { const { feature, featureValue, putFeatureValue } = this.props; const { value } = this.state; if (feature.feature_type === "string"){ putFeatureValue(featureValue.id, value); } else if (feature.feature_type === "integer") { putFeatureValue(featureValue.id, Math.ceil(value*1)); } else if (feature.feature_type === "float") { putFeatureValue(featureValue.id, value*1); } } onChangeHandler(e) { const value = e.target.value; this.setState({ value }, this.deferred); } getType() { const { feature } = this.props; if (feature.feature_type === "integer" || feature.feature_type === "float") { return "number"; } return "string"; } componentWillReceiveProps(nextProps) { if (nextProps.featureValue.id !== this.props.featureValue.id && this.deferred.cancel()) { // Trigger action function before receiving new props since // action to change the value was deferred this.action(); } // This permits swaping JUST the input value for a featureValue whenever the enquiry changes if (nextProps.featureValue.value !== this.state.value) { this.setState({ value: nextProps.featureValue.value !== null ? nextProps.featureValue.value : '' }); } } render() { const { feature } = this.props; const { value } = this.state; return ( <form> <div className="form-group"> <label htmlFor={`${feature.feature_type}${feature.id}`}>{feature.feature_label.name} </label> <input type={this.getType()} className="form-control" id={`${feature.feature_type}${feature.id}`} value={value} placeholder={`Enter a ${feature.feature_type}`} onChange={this.onChangeHandler}> </input> </div> </form> ); } } const mapDispatchToProps = (dispatch) => { return { putFeatureValue: (id, value) => { dispatch(putFeatureValue({ id, value })); }, }; }; NonOption.propTypes = { feature: PropTypes.object.isRequired, featureValue: PropTypes.object.isRequired, } export default connect(null, mapDispatchToProps)(NonOption);
server/sonar-web/src/main/js/apps/code/components/Breadcrumbs.js
Builders-SonarSource/sonarqube-bis
/* * SonarQube * Copyright (C) 2009-2016 SonarSource SA * mailto:contact AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import React from 'react'; import Breadcrumb from './Breadcrumb'; const Breadcrumbs = ({ rootComponent, breadcrumbs }) => ( <ul className="code-breadcrumbs"> {breadcrumbs.map((component, index) => ( <li key={component.key}> <Breadcrumb rootComponent={rootComponent} component={component} canBrowse={index < breadcrumbs.length - 1}/> </li> ))} </ul> ); export default Breadcrumbs;
webpack.config.js
ErikCupal/the-black-cat-website
const path = require('path') const webpack = require('webpack') const nodeExternals = require('webpack-node-externals') const CompressionPlugin = require("compression-webpack-plugin") const server = (debug) => ({ target: 'node', entry: [ './src/server/index.tsx', ], output: { filename: 'server.js', path: debug ? path.resolve(__dirname, './build/development/') : path.resolve(__dirname, './build/production/') }, devtool: 'source-map', externals: [nodeExternals()], resolve: { extensions: ['.ts', '.tsx', '.js'], modules: ['node_modules'], }, module: { rules: [ { test: /\.tsx?$/, exclude: /node_modules/, use: [ { loader: 'imports-loader?React=react' }, { loader: 'babel-loader', options: { "plugins": [ // ES Next "babel-plugin-syntax-trailing-function-commas", "babel-plugin-transform-class-properties", "babel-plugin-transform-export-extensions", "babel-plugin-transform-object-rest-spread", // React "babel-plugin-syntax-jsx", "babel-plugin-transform-react-jsx", "babel-plugin-transform-react-display-name" ] } }, { loader: 'ts-loader' } ] }, ] }, plugins: debug ? [] : [ new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify('production') }), ] }) const client = () => ({ entry: [ 'babel-polyfill', './src/client/index.tsx', ], output: { filename: 'app.js', path: path.resolve(__dirname, 'build/production/') }, module: { rules: [ { test: /\.tsx?$/, exclude: /node_modules/, use: [ { loader: 'imports-loader?React=react' }, { loader: 'babel-loader', options: { 'presets': [ [ 'latest', { 'modules': false } ], 'stage-0', 'react' ] } }, { loader: 'ts-loader' } ] }, ] }, resolve: { extensions: ['.ts', '.tsx', '.js'], modules: ['node_modules'], }, plugins: [ new webpack.LoaderOptionsPlugin({ minimize: true, debug: false }), new webpack.DefinePlugin({ 'process.env': { 'NODE_ENV': JSON.stringify('production') } }), new webpack.optimize.UglifyJsPlugin({ beautify: false, mangle: { screw_ie8: true, keep_fnames: true }, compress: { screw_ie8: true, warnings: false, }, comments: false, sourceMap: false, }), new CompressionPlugin({ asset: "[path].gz[query]", algorithm: "gzip", test: /\.(js|html)$/, threshold: 10240, minRatio: 0.8 }), ], }) const getDevelopment = () => server(true) const getProduction = () => ([ server(false), client(), ]) module.exports = (env = {}) => { const debug = env.NODE_ENV !== 'production' switch (debug) { case false: return getProduction() default: return getDevelopment() } }
stories/components/quoteBanner/index.js
tal87/operationcode_frontend
import React from 'react'; import { storiesOf } from '@storybook/react'; import QuoteBanner from 'shared/components/quoteBanner/quoteBanner'; storiesOf('shared/components/quoteBanner', module) .add('Default', () => ( <QuoteBanner author="James bond" quote="I always enjoyed learning a new tongue" /> ));
src/svg-icons/action/bookmark.js
tan-jerene/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionBookmark = (props) => ( <SvgIcon {...props}> <path d="M17 3H7c-1.1 0-1.99.9-1.99 2L5 21l7-3 7 3V5c0-1.1-.9-2-2-2z"/> </SvgIcon> ); ActionBookmark = pure(ActionBookmark); ActionBookmark.displayName = 'ActionBookmark'; ActionBookmark.muiName = 'SvgIcon'; export default ActionBookmark;
__tests__/client/App/Shell/About/index.spec.js
noamokman/project-starter-sample
import React from 'react'; import {shallow} from 'enzyme'; import About from '../../../../../client/App/Shell/About'; describe('About component', () => { it('renders without crashing', () => { shallow(<About />); }); });
ajax/libs/instantsearch.js/0.7.0/instantsearch.min.js
boneskull/cdnjs
/*! instantsearch.js 0.7.0 | © Algolia Inc. and other contributors; Licensed MIT | github.com/algolia/instantsearch.js */ !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.instantsearch=t():e.instantsearch=t()}(this,function(){return function(e){function t(r){if(n[r])return n[r].exports;var o=n[r]={exports:{},id:r,loaded:!1};return e[r].call(o.exports,o,o.exports,t),o.loaded=!0,o.exports}var n={};return t.m=e,t.c=n,t.p="",t(0)}([function(e,t,n){"use strict";e.exports=n(1)},function(e,t,n){"use strict";n(2);var r=n(3),o=n(4),i=r(o),a=n(72);i.widgets={hierarchicalMenu:n(216),hits:n(382),hitsPerPageSelector:n(385),indexSelector:n(387),menu:n(388),refinementList:n(390),pagination:n(392),priceRanges:n(399),searchBox:n(403),rangeSlider:n(405),stats:n(413),toggle:n(416)},i.version=n(214),i.createQueryString=a.url.getQueryStringFromState,e.exports=i},function(){"use strict";Object.freeze||(Object.freeze=function(e){if(Object(e)!==e)throw new TypeError("Object.freeze can only be called on Objects.");return e})},function(e){"use strict";function t(e){var t=function(){for(var t=arguments.length,r=Array(t),o=0;t>o;o++)r[o]=arguments[o];return new(n.apply(e,[null].concat(r)))};return t.__proto__=e,t.prototype=e.prototype,t}var n=Function.prototype.bind;e.exports=t},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){if("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 i(){return"#"}function a(e,t){if(!t.getConfiguration)return e;var n=t.getConfiguration(e);return f({},e,n,function(e,t){return Array.isArray(e)?h(e,t):void 0})}var s=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),u=function(e,t,n){for(var r=!0;r;){var o=e,i=t,a=n;r=!1,null===o&&(o=Function.prototype);var s=Object.getOwnPropertyDescriptor(o,i);if(void 0!==s){if("value"in s)return s.value;var u=s.get;return void 0===u?void 0:u.call(a)}var c=Object.getPrototypeOf(o);if(null===c)return void 0;e=c,t=i,n=a,r=!0,s=c=void 0}},c=n(5),l=n(72),p=n(17),f=n(53),h=n(211),d=n(63).EventEmitter,v=n(213),m=function(e){function t(e){var n=e.appId,o=void 0===n?null:n,i=e.apiKey,a=void 0===i?null:i,s=e.indexName,l=void 0===s?null:s,p=e.numberLocale,f=void 0===p?"en-EN":p,h=e.searchParameters,d=void 0===h?{}:h,v=e.urlSync,m=void 0===v?null:v;if(r(this,t),u(Object.getPrototypeOf(t.prototype),"constructor",this).call(this),null===o||null===a||null===l){var g="\nUsage: instantsearch({\n appId: 'my_application_id',\n apiKey: 'my_search_api_key',\n indexName: 'my_index_name'\n});";throw new Error(g)}var y=c(o,a);this.client=y,this.helper=null,this.indexName=l,this.searchParameters=d||{},this.widgets=[],this.templatesConfig={helpers:{formatNumber:function(e,t){return Number(t(e)).toLocaleString(f)}},compileOptions:{}},this.urlSync=m}return o(t,e),s(t,[{key:"addWidget",value:function(e){this.widgets.push(e)}},{key:"start",value:function(){if(!this.widgets)throw new Error("No widgets were added to instantsearch.js");if(this.urlSync){var e=v(this.urlSync);this._createURL=e.createURL.bind(e),this.widgets.push(e)}else this._createURL=i;this.searchParameters=this.widgets.reduce(a,this.searchParameters);var t=l(this.client,this.searchParameters.index||this.indexName,this.searchParameters);this.helper=t,this._init(t.state,t),t.on("result",this._render.bind(this,t)),t.search()}},{key:"createURL",value:function(e){if(!this._createURL)throw new Error("You need to call start() before calling createURL()");return this._createURL(this.helper.state.setQueryParameters(e))}},{key:"_render",value:function(e,t,n){p(this.widgets,function(r){r.render&&r.render({templatesConfig:this.templatesConfig,results:t,state:n,helper:e,createURL:this._createURL})},this),this.emit("render")}},{key:"_init",value:function(e,t){p(this.widgets,function(n){n.init&&n.init(e,t,this.templatesConfig)},this)}}]),t}(d);e.exports=m},function(e,t,n){"use strict";function r(e,t,i){var a=n(69),s=n(70);return i=a(i||{}),void 0===i.protocol&&(i.protocol=s()),i._ua=i._ua||r.ua,new o(e,t,i)}function o(){s.apply(this,arguments)}e.exports=r;var i=n(6),a=window.Promise||n(7).Promise,s=n(12),u=n(16),c=n(64),l=n(68);r.version=n(71),r.ua="Algolia for vanilla JavaScript "+r.version,window.__algolia={debug:n(13),algoliasearch:r};var p={hasXMLHttpRequest:"XMLHttpRequest"in window,hasXDomainRequest:"XDomainRequest"in window,cors:"withCredentials"in new XMLHttpRequest,timeout:"timeout"in new XMLHttpRequest};i(o,s),o.prototype._request=function(e,t){return new a(function(n,r){function o(){if(!l){p.timeout||clearTimeout(s);var e;try{e={body:JSON.parse(h.responseText),responseText:h.responseText,statusCode:h.status,headers:h.getAllResponseHeaders&&h.getAllResponseHeaders()||{}}}catch(t){e=new u.UnparsableJSON({more:h.responseText})}e instanceof u.UnparsableJSON?r(e):n(e)}}function i(e){l||(p.timeout||clearTimeout(s),r(new u.Network({more:e})))}function a(){p.timeout||(l=!0,h.abort()),r(new u.RequestTimeout)}if(!p.cors&&!p.hasXDomainRequest)return void r(new u.Network("CORS not supported"));e=c(e,t.headers);var s,l,f=t.body,h=p.cors?new XMLHttpRequest:new XDomainRequest;h instanceof XMLHttpRequest?h.open(t.method,e,!0):h.open(t.method,e),p.cors&&(f&&("POST"===t.method?h.setRequestHeader("content-type","application/x-www-form-urlencoded"):h.setRequestHeader("content-type","application/json")),h.setRequestHeader("accept","application/json")),h.onprogress=function(){},h.onload=o,h.onerror=i,p.timeout?(h.timeout=t.timeout,h.ontimeout=a):s=setTimeout(a,t.timeout),h.send(f)})},o.prototype._request.fallback=function(e,t){return e=c(e,t.headers),new a(function(n,r){l(e,t,function(e,t){return e?void r(e):void n(t)})})},o.prototype._promise={reject:function(e){return a.reject(e)},resolve:function(e){return a.resolve(e)},delay:function(e){return new a(function(t){setTimeout(t,e)})}}},function(e){e.exports="function"==typeof Object.create?function(e,t){e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})}:function(e,t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}},function(e,t,n){var r;(function(e,o,i){(function(){"use strict";function a(e){return"function"==typeof e||"object"==typeof e&&null!==e}function s(e){return"function"==typeof e}function u(e){return"object"==typeof e&&null!==e}function c(e){Y=e}function l(e){J=e}function p(){return function(){e.nextTick(m)}}function f(){return function(){Q(m)}}function h(){var e=0,t=new ee(m),n=document.createTextNode("");return t.observe(n,{characterData:!0}),function(){n.data=e=++e%2}}function d(){var e=new MessageChannel;return e.port1.onmessage=m,function(){e.port2.postMessage(0)}}function v(){return function(){setTimeout(m,1)}}function m(){for(var e=0;$>e;e+=2){var t=re[e],n=re[e+1];t(n),re[e]=void 0,re[e+1]=void 0}$=0}function g(){try{var e=n(10);return Q=e.runOnLoop||e.runOnContext,f()}catch(t){return v()}}function y(){}function b(){return new TypeError("You cannot resolve a promise with itself")}function x(){return new TypeError("A promises callback cannot return that same promise.")}function w(e){try{return e.then}catch(t){return se.error=t,se}}function _(e,t,n,r){try{e.call(t,n,r)}catch(o){return o}}function P(e,t,n){J(function(e){var r=!1,o=_(n,t,function(n){r||(r=!0,t!==n?R(e,n):O(e,n))},function(t){r||(r=!0,S(e,t))},"Settle: "+(e._label||" unknown promise"));!r&&o&&(r=!0,S(e,o))},e)}function C(e,t){t._state===ie?O(e,t._result):t._state===ae?S(e,t._result):N(t,void 0,function(t){R(e,t)},function(t){S(e,t)})}function E(e,t){if(t.constructor===e.constructor)C(e,t);else{var n=w(t);n===se?S(e,se.error):void 0===n?O(e,t):s(n)?P(e,t,n):O(e,t)}}function R(e,t){e===t?S(e,b()):a(t)?E(e,t):O(e,t)}function T(e){e._onerror&&e._onerror(e._result),j(e)}function O(e,t){e._state===oe&&(e._result=t,e._state=ie,0!==e._subscribers.length&&J(j,e))}function S(e,t){e._state===oe&&(e._state=ae,e._result=t,J(T,e))}function N(e,t,n,r){var o=e._subscribers,i=o.length;e._onerror=null,o[i]=t,o[i+ie]=n,o[i+ae]=r,0===i&&e._state&&J(j,e)}function j(e){var t=e._subscribers,n=e._state;if(0!==t.length){for(var r,o,i=e._result,a=0;a<t.length;a+=3)r=t[a],o=t[a+n],r?D(n,r,o,i):o(i);e._subscribers.length=0}}function k(){this.error=null}function I(e,t){try{return e(t)}catch(n){return ue.error=n,ue}}function D(e,t,n,r){var o,i,a,u,c=s(n);if(c){if(o=I(n,r),o===ue?(u=!0,i=o.error,o=null):a=!0,t===o)return void S(t,x())}else o=r,a=!0;t._state!==oe||(c&&a?R(t,o):u?S(t,i):e===ie?O(t,o):e===ae&&S(t,o))}function A(e,t){try{t(function(t){R(e,t)},function(t){S(e,t)})}catch(n){S(e,n)}}function M(e,t){var n=this;n._instanceConstructor=e,n.promise=new e(y),n._validateInput(t)?(n._input=t,n.length=t.length,n._remaining=t.length,n._init(),0===n.length?O(n.promise,n._result):(n.length=n.length||0,n._enumerate(),0===n._remaining&&O(n.promise,n._result))):S(n.promise,n._validationError())}function F(e){return new ce(this,e).promise}function U(e){function t(e){R(o,e)}function n(e){S(o,e)}var r=this,o=new r(y);if(!G(e))return S(o,new TypeError("You must pass an array to race.")),o;for(var i=e.length,a=0;o._state===oe&&i>a;a++)N(r.resolve(e[a]),void 0,t,n);return o}function L(e){var t=this;if(e&&"object"==typeof e&&e.constructor===t)return e;var n=new t(y);return R(n,e),n}function B(e){var t=this,n=new t(y);return S(n,e),n}function q(){throw new TypeError("You must pass a resolver function as the first argument to the promise constructor")}function H(){throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.")}function V(e){this._id=de++,this._state=void 0,this._result=void 0,this._subscribers=[],y!==e&&(s(e)||q(),this instanceof V||H(),A(this,e))}function W(){var e;if("undefined"!=typeof o)e=o;else if("undefined"!=typeof self)e=self;else try{e=Function("return this")()}catch(t){throw new Error("polyfill failed because global object is unavailable in this environment")}var n=e.Promise;(!n||"[object Promise]"!==Object.prototype.toString.call(n.resolve())||n.cast)&&(e.Promise=ve)}var K;K=Array.isArray?Array.isArray:function(e){return"[object Array]"===Object.prototype.toString.call(e)};var Q,Y,z,G=K,$=0,J=({}.toString,function(e,t){re[$]=e,re[$+1]=t,$+=2,2===$&&(Y?Y(m):z())}),X="undefined"!=typeof window?window:void 0,Z=X||{},ee=Z.MutationObserver||Z.WebKitMutationObserver,te="undefined"!=typeof e&&"[object process]"==={}.toString.call(e),ne="undefined"!=typeof Uint8ClampedArray&&"undefined"!=typeof importScripts&&"undefined"!=typeof MessageChannel,re=new Array(1e3);z=te?p():ee?h():ne?d():void 0===X?g():v();var oe=void 0,ie=1,ae=2,se=new k,ue=new k;M.prototype._validateInput=function(e){return G(e)},M.prototype._validationError=function(){return new Error("Array Methods must be provided an Array")},M.prototype._init=function(){this._result=new Array(this.length)};var ce=M;M.prototype._enumerate=function(){for(var e=this,t=e.length,n=e.promise,r=e._input,o=0;n._state===oe&&t>o;o++)e._eachEntry(r[o],o)},M.prototype._eachEntry=function(e,t){var n=this,r=n._instanceConstructor;u(e)?e.constructor===r&&e._state!==oe?(e._onerror=null,n._settledAt(e._state,t,e._result)):n._willSettleAt(r.resolve(e),t):(n._remaining--,n._result[t]=e)},M.prototype._settledAt=function(e,t,n){var r=this,o=r.promise;o._state===oe&&(r._remaining--,e===ae?S(o,n):r._result[t]=n),0===r._remaining&&O(o,r._result)},M.prototype._willSettleAt=function(e,t){var n=this;N(e,void 0,function(e){n._settledAt(ie,t,e)},function(e){n._settledAt(ae,t,e)})};var le=F,pe=U,fe=L,he=B,de=0,ve=V;V.all=le,V.race=pe,V.resolve=fe,V.reject=he,V._setScheduler=c,V._setAsap=l,V._asap=J,V.prototype={constructor:V,then:function(e,t){var n=this,r=n._state;if(r===ie&&!e||r===ae&&!t)return this;var o=new this.constructor(y),i=n._result;if(r){var a=arguments[r-1];J(function(){D(r,o,a,i)})}else N(n,o,e,t);return o},"catch":function(e){return this.then(null,e)}};var me=W,ge={Promise:ve,polyfill:me};n(11).amd?(r=function(){return ge}.call(t,n,t,i),!(void 0!==r&&(i.exports=r))):"undefined"!=typeof i&&i.exports?i.exports=ge:"undefined"!=typeof this&&(this.ES6Promise=ge),me()}).call(this)}).call(t,n(8),function(){return this}(),n(9)(e))},function(e){function t(){u=!1,i.length?s=i.concat(s):c=-1,s.length&&n()}function n(){if(!u){var e=setTimeout(t);u=!0;for(var n=s.length;n;){for(i=s,s=[];++c<n;)i&&i[c].run();c=-1,n=s.length}i=null,u=!1,clearTimeout(e)}}function r(e,t){this.fun=e,this.array=t}function o(){}var i,a=e.exports={},s=[],u=!1,c=-1;a.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var o=1;o<arguments.length;o++)t[o-1]=arguments[o];s.push(new r(e,t)),1!==s.length||u||setTimeout(n,0)},r.prototype.run=function(){this.fun.apply(null,this.array)},a.title="browser",a.browser=!0,a.env={},a.argv=[],a.version="",a.versions={},a.on=o,a.addListener=o,a.once=o,a.off=o,a.removeListener=o,a.removeAllListeners=o,a.emit=o,a.binding=function(){throw new Error("process.binding is not supported")},a.cwd=function(){return"/"},a.chdir=function(){throw new Error("process.chdir is not supported")},a.umask=function(){return 0}},function(e){e.exports=function(e){return e.webpackPolyfill||(e.deprecate=function(){},e.paths=[],e.children=[],e.webpackPolyfill=1),e}},function(){},function(e){e.exports=function(){throw new Error("define cannot be used indirect")}},function(e,t,n){"use strict";function r(e,t,r){var a=n(13)("algoliasearch"),s=n(43),u=n(36),c="Usage: algoliasearch(applicationID, apiKey, opts)";if(!e)throw new f.AlgoliaSearchError("Please provide an application ID. "+c);if(!t)throw new f.AlgoliaSearchError("Please provide an API key. "+c);this.applicationID=e,this.apiKey=t;var l=[this.applicationID+"-1.algolianet.com",this.applicationID+"-2.algolianet.com",this.applicationID+"-3.algolianet.com"];this.hosts={read:[],write:[]},this.hostIndex={read:0,write:0},r=r||{};var p=r.protocol||"https:",h=void 0===r.timeout?2e3:r.timeout;if(/:$/.test(p)||(p+=":"),"http:"!==r.protocol&&"https:"!==r.protocol)throw new f.AlgoliaSearchError("protocol must be `http:` or `https:` (was `"+r.protocol+"`)");r.hosts?u(r.hosts)?(this.hosts.read=s(r.hosts),this.hosts.write=s(r.hosts)):(this.hosts.read=s(r.hosts.read),this.hosts.write=s(r.hosts.write)):(this.hosts.read=[this.applicationID+"-dsn.algolia.net"].concat(l),this.hosts.write=[this.applicationID+".algolia.net"].concat(l)),this.hosts.read=o(this.hosts.read,i(p)),this.hosts.write=o(this.hosts.write,i(p)),this.requestTimeout=h,this.extraHeaders=[],this.cache={},this._ua=r._ua,this._useCache=void 0===r._useCache?!0:r._useCache,this._setTimeout=r._setTimeout,a("init done, %j",this)}function o(e,t){for(var n=[],r=0;r<e.length;++r)n.push(t(e[r],r));return n}function i(e){return function(t){return e+"//"+t.toLowerCase()}}function a(){var e="Not implemented in this environment.\nIf you feel this is a mistake, write to [email protected]";throw new f.AlgoliaSearchError(e)}function s(e,t){var n=e.toLowerCase().replace(".","").replace("()","");return"algoliasearch: `"+e+"` was replaced by `"+t+"`. Please see https://github.com/algolia/algoliasearch-client-js/wiki/Deprecated#"+n}function u(e,t){t(e,0)}function c(e,t){function n(){return r||(console.log(t),r=!0),e.apply(this,arguments)}var r=!1;return n}function l(e){if(void 0===Array.prototype.toJSON)return JSON.stringify(e);var t=Array.prototype.toJSON;delete Array.prototype.toJSON;var n=JSON.stringify(e);return Array.prototype.toJSON=t,n}function p(e){return function(t,n,r){if("function"==typeof t&&"object"==typeof n||"object"==typeof r)throw new f.AlgoliaSearchError("index.search usage is index.search(query, params, cb)");0===arguments.length||"function"==typeof t?(r=t,t=""):(1===arguments.length||"function"==typeof n)&&(r=n,n=void 0),"object"==typeof t&&null!==t?(n=t,t=void 0):(void 0===t||null===t)&&(t="");var o="";return void 0!==t&&(o+=e+"="+encodeURIComponent(t)),void 0!==n&&(o=this.as._getSearchParams(n,o)),this._search(o,r)}}e.exports=r,"development"==={NODE_ENV:"production"}.APP_ENV&&n(13).enable("algoliasearch*");var f=n(16);r.prototype={deleteIndex:function(e,t){return this._jsonRequest({method:"DELETE",url:"/1/indexes/"+encodeURIComponent(e),hostType:"write",callback:t})},moveIndex:function(e,t,n){var r={operation:"move",destination:t};return this._jsonRequest({method:"POST",url:"/1/indexes/"+encodeURIComponent(e)+"/operation",body:r,hostType:"write",callback:n})},copyIndex:function(e,t,n){var r={operation:"copy",destination:t};return this._jsonRequest({method:"POST",url:"/1/indexes/"+encodeURIComponent(e)+"/operation",body:r,hostType:"write",callback:n})},getLogs:function(e,t,n){return 0===arguments.length||"function"==typeof e?(n=e,e=0,t=10):(1===arguments.length||"function"==typeof t)&&(n=t,t=10),this._jsonRequest({method:"GET",url:"/1/logs?offset="+e+"&length="+t,hostType:"read",callback:n})},listIndexes:function(e,t){var n="";return void 0===e||"function"==typeof e?t=e:n="?page="+e,this._jsonRequest({method:"GET",url:"/1/indexes"+n,hostType:"read",callback:t})},initIndex:function(e){return new this.Index(this,e)},listUserKeys:function(e){return this._jsonRequest({method:"GET",url:"/1/keys",hostType:"read",callback:e})},getUserKeyACL:function(e,t){return this._jsonRequest({method:"GET",url:"/1/keys/"+e,hostType:"read",callback:t})},deleteUserKey:function(e,t){return this._jsonRequest({method:"DELETE",url:"/1/keys/"+e,hostType:"write",callback:t})},addUserKey:function(e,t,n){(1===arguments.length||"function"==typeof t)&&(n=t,t=null);var r={acl:e};return t&&(r.validity=t.validity,r.maxQueriesPerIPPerHour=t.maxQueriesPerIPPerHour,r.maxHitsPerQuery=t.maxHitsPerQuery,r.indexes=t.indexes,r.description=t.description,t.queryParameters&&(r.queryParameters=this._getSearchParams(t.queryParameters,"")),r.referers=t.referers),this._jsonRequest({method:"POST",url:"/1/keys",body:r,hostType:"write",callback:n})},addUserKeyWithValidity:c(function(e,t,n){return this.addUserKey(e,t,n)},s("client.addUserKeyWithValidity()","client.addUserKey()")),updateUserKey:function(e,t,n,r){(2===arguments.length||"function"==typeof n)&&(r=n,n=null);var o={acl:t};return n&&(o.validity=n.validity,o.maxQueriesPerIPPerHour=n.maxQueriesPerIPPerHour,o.maxHitsPerQuery=n.maxHitsPerQuery,o.indexes=n.indexes,o.description=n.description,n.queryParameters&&(o.queryParameters=this._getSearchParams(n.queryParameters,"")),o.referers=n.referers),this._jsonRequest({method:"PUT",url:"/1/keys/"+e,body:o,hostType:"write",callback:r})},setSecurityTags:function(e){if("[object Array]"===Object.prototype.toString.call(e)){for(var t=[],n=0;n<e.length;++n)if("[object Array]"===Object.prototype.toString.call(e[n])){for(var r=[],o=0;o<e[n].length;++o)r.push(e[n][o]);t.push("("+r.join(",")+")")}else t.push(e[n]);e=t.join(",")}this.securityTags=e},setUserToken:function(e){this.userToken=e},startQueriesBatch:c(function(){this._batch=[]},s("client.startQueriesBatch()","client.search()")),addQueryInBatch:c(function(e,t,n){this._batch.push({indexName:e,query:t,params:n})},s("client.addQueryInBatch()","client.search()")),clearCache:function(){this.cache={}},sendQueriesBatch:c(function(e){return this.search(this._batch,e)},s("client.sendQueriesBatch()","client.search()")),setRequestTimeout:function(e){e&&(this.requestTimeout=parseInt(e,10))},search:function(e,t){var n=this,r={requests:o(e,function(e){var t="";return void 0!==e.query&&(t+="query="+encodeURIComponent(e.query)),{indexName:e.indexName,params:n._getSearchParams(e.params,t)}})};return this._jsonRequest({cache:this.cache,method:"POST",url:"/1/indexes/*/queries",body:r,hostType:"read",callback:t})},batch:function(e,t){return this._jsonRequest({method:"POST",url:"/1/indexes/*/batch",body:{requests:e},hostType:"write",callback:t})},destroy:a,enableRateLimitForward:a,disableRateLimitForward:a,useSecuredAPIKey:a,disableSecuredAPIKey:a,generateSecuredApiKey:a,Index:function(e,t){this.indexName=t,this.as=e,this.typeAheadArgs=null,this.typeAheadValueOption=null,this.cache={}},setExtraHeader:function(e,t){this.extraHeaders.push({name:e.toLowerCase(),value:t})},addAlgoliaAgent:function(e){this._ua+=";"+e},_sendQueriesBatch:function(e,t){function n(){for(var t="",n=0;n<e.requests.length;++n){var r="/1/indexes/"+encodeURIComponent(e.requests[n].indexName)+"?"+e.requests[n].params;t+=n+"="+encodeURIComponent(r)+"&"}return t}return this._jsonRequest({cache:this.cache,method:"POST",url:"/1/indexes/*/queries",body:e,hostType:"read",fallback:{method:"GET",url:"/1/indexes/*",body:{params:n()}},callback:t})},_jsonRequest:function(e){function t(n,u){function p(e){var t=e&&e.body&&e.body.message&&e.body.status||e.statusCode||e&&e.body&&200;o("received response: statusCode: %s, computed statusCode: %d, headers: %j",e.statusCode,t,e.headers),{NODE_ENV:"production"}.DEBUG&&-1!=={NODE_ENV:"production"}.DEBUG.indexOf("debugBody")&&o("body: %j",e.body);var n=200===t||201===t,r=!n&&4!==Math.floor(t/100)&&1!==Math.floor(t/100);if(a._useCache&&n&&i&&(i[v]=e.responseText),n)return e.body;if(r)return s+=1,d();var u=new f.AlgoliaSearchError(e.body&&e.body.message);return a._promise.reject(u)}function h(r){return o("error: %s, stack: %s",r.message,r.stack),r instanceof f.AlgoliaSearchError||(r=new f.Unknown(r&&r.message,r)),s+=1,r instanceof f.Unknown||r instanceof f.UnparsableJSON||s>=a.hosts[e.hostType].length&&(c||!e.fallback||!a._request.fallback)?a._promise.reject(r):(a.hostIndex[e.hostType]=++a.hostIndex[e.hostType]%a.hosts[e.hostType].length,r instanceof f.RequestTimeout?d():(a._request.fallback&&!a.useFallback&&(a.useFallback=!0),t(n,u)))}function d(){return a.hostIndex[e.hostType]=++a.hostIndex[e.hostType]%a.hosts[e.hostType].length,u.timeout=a.requestTimeout*(s+1),t(n,u)}var v;if(a._useCache&&(v=e.url),a._useCache&&r&&(v+="_body_"+u.body),a._useCache&&i&&void 0!==i[v])return o("serving response from cache"),a._promise.resolve(JSON.parse(i[v]));if(s>=a.hosts[e.hostType].length||a.useFallback&&!c)return e.fallback&&a._request.fallback&&!c?(o("switching to fallback"),s=0,u.method=e.fallback.method,u.url=e.fallback.url,u.jsonBody=e.fallback.body,u.jsonBody&&(u.body=l(u.jsonBody)),u.timeout=a.requestTimeout*(s+1),a.hostIndex[e.hostType]=0,c=!0,t(a._request.fallback,u)):(o("could not get any response"),a._promise.reject(new f.AlgoliaSearchError("Cannot connect to the AlgoliaSearch API. Send an email to [email protected] to report and resolve the issue. Application id was: "+a.applicationID)));var m=a.hosts[e.hostType][a.hostIndex[e.hostType]]+u.url,g={body:r,jsonBody:e.body,method:u.method,headers:a._computeRequestHeaders(),timeout:u.timeout,debug:o};return o("method: %s, url: %s, headers: %j, timeout: %d",g.method,m,g.headers,g.timeout),n===a._request.fallback&&o("using fallback"),n.call(a,m,g).then(p,h)}var r,o=n(13)("algoliasearch:"+e.url),i=e.cache,a=this,s=0,c=!1;void 0!==e.body&&(r=l(e.body)),o("request start");var p=a.useFallback&&e.fallback,h=p?e.fallback:e,d=t(p?a._request.fallback:a._request,{url:h.url,method:h.method,body:r,jsonBody:e.body,timeout:a.requestTimeout*(s+1)});return e.callback?void d.then(function(t){u(function(){e.callback(null,t)},a._setTimeout||setTimeout)},function(t){u(function(){e.callback(t)},a._setTimeout||setTimeout)}):d},_getSearchParams:function(e,t){if(this._isUndefined(e)||null===e)return t;for(var n in e)null!==n&&void 0!==e[n]&&e.hasOwnProperty(n)&&(t+=""===t?"":"&",t+=n+"="+encodeURIComponent("[object Array]"===Object.prototype.toString.call(e[n])?l(e[n]):e[n]));return t},_isUndefined:function(e){return void 0===e},_computeRequestHeaders:function(){var e=n(17),t={"x-algolia-api-key":this.apiKey,"x-algolia-application-id":this.applicationID,"x-algolia-agent":this._ua};return this.userToken&&(t["x-algolia-usertoken"]=this.userToken),this.securityTags&&(t["x-algolia-tagfilters"]=this.securityTags),this.extraHeaders&&e(this.extraHeaders,function(e){t[e.name]=e.value}),t}},r.prototype.Index.prototype={clearCache:function(){this.cache={}},addObject:function(e,t,n){var r=this;return(1===arguments.length||"function"==typeof t)&&(n=t,t=void 0),this.as._jsonRequest({method:void 0!==t?"PUT":"POST",url:"/1/indexes/"+encodeURIComponent(r.indexName)+(void 0!==t?"/"+encodeURIComponent(t):""),body:e,hostType:"write",callback:n})},addObjects:function(e,t){for(var n=this,r={requests:[]},o=0;o<e.length;++o){var i={action:"addObject",body:e[o]};r.requests.push(i)}return this.as._jsonRequest({method:"POST",url:"/1/indexes/"+encodeURIComponent(n.indexName)+"/batch",body:r,hostType:"write",callback:t})},getObject:function(e,t,n){var r=this;(1===arguments.length||"function"==typeof t)&&(n=t,t=void 0);var o="";if(void 0!==t){o="?attributes=";for(var i=0;i<t.length;++i)0!==i&&(o+=","),o+=t[i]}return this.as._jsonRequest({method:"GET",url:"/1/indexes/"+encodeURIComponent(r.indexName)+"/"+encodeURIComponent(e)+o,hostType:"read",callback:n})},getObjects:function(e,t,n){var r=this;(1===arguments.length||"function"==typeof t)&&(n=t,t=void 0);var i={requests:o(e,function(e){var n={indexName:r.indexName,objectID:e};return t&&(n.attributesToRetrieve=t.join(",")),n})};return this.as._jsonRequest({method:"POST",url:"/1/indexes/*/objects",hostType:"read",body:i,callback:n})},partialUpdateObject:function(e,t){var n=this;return this.as._jsonRequest({method:"POST",url:"/1/indexes/"+encodeURIComponent(n.indexName)+"/"+encodeURIComponent(e.objectID)+"/partial",body:e,hostType:"write",callback:t})},partialUpdateObjects:function(e,t){for(var n=this,r={requests:[]},o=0;o<e.length;++o){var i={action:"partialUpdateObject",objectID:e[o].objectID,body:e[o]};r.requests.push(i)}return this.as._jsonRequest({method:"POST",url:"/1/indexes/"+encodeURIComponent(n.indexName)+"/batch",body:r,hostType:"write",callback:t})},saveObject:function(e,t){var n=this;return this.as._jsonRequest({method:"PUT",url:"/1/indexes/"+encodeURIComponent(n.indexName)+"/"+encodeURIComponent(e.objectID),body:e,hostType:"write",callback:t})},saveObjects:function(e,t){for(var n=this,r={requests:[]},o=0;o<e.length;++o){var i={action:"updateObject",objectID:e[o].objectID,body:e[o]};r.requests.push(i)}return this.as._jsonRequest({method:"POST",url:"/1/indexes/"+encodeURIComponent(n.indexName)+"/batch",body:r,hostType:"write",callback:t})},deleteObject:function(e,t){if("function"==typeof e||"string"!=typeof e&&"number"!=typeof e){var n=new f.AlgoliaSearchError("Cannot delete an object without an objectID");return t=e,"function"==typeof t?t(n):this.as._promise.reject(n)}var r=this;return this.as._jsonRequest({method:"DELETE",url:"/1/indexes/"+encodeURIComponent(r.indexName)+"/"+encodeURIComponent(e),hostType:"write",callback:t})},deleteObjects:function(e,t){var n=this,r={requests:o(e,function(e){return{action:"deleteObject",objectID:e,body:{objectID:e}}})};return this.as._jsonRequest({method:"POST",url:"/1/indexes/"+encodeURIComponent(n.indexName)+"/batch",body:r,hostType:"write",callback:t})},deleteByQuery:function(e,t,r){function i(e){if(0===e.nbHits)return e;var t=o(e.hits,function(e){return e.objectID});return f.deleteObjects(t).then(a).then(s)}function a(e){return f.waitTask(e.taskID)}function s(){return f.deleteByQuery(e,t)}function c(){u(function(){r(null)},h._setTimeout||setTimeout)}function l(e){u(function(){r(e)},h._setTimeout||setTimeout)}var p=n(43),f=this,h=f.as;1===arguments.length||"function"==typeof t?(r=t,t={}):t=p(t),t.attributesToRetrieve="objectID",t.hitsPerPage=1e3,t.distinct=!1,this.clearCache();var d=this.search(e,t).then(i);return r?void d.then(c,l):d},search:p("query"),similarSearch:p("similarQuery"),browse:function(e,t,r){var o,i,a=n(53),s=this;0===arguments.length||1===arguments.length&&"function"==typeof arguments[0]?(o=0,r=arguments[0],e=void 0):"number"==typeof arguments[0]?(o=arguments[0],"number"==typeof arguments[1]?i=arguments[1]:"function"==typeof arguments[1]&&(r=arguments[1],i=void 0),e=void 0,t=void 0):"object"==typeof arguments[0]?("function"==typeof arguments[1]&&(r=arguments[1]),t=arguments[0],e=void 0):"string"==typeof arguments[0]&&"function"==typeof arguments[1]&&(r=arguments[1],t=void 0),t=a({},t||{},{page:o,hitsPerPage:i,query:e});var u=this.as._getSearchParams(t,"");return this.as._jsonRequest({method:"GET",url:"/1/indexes/"+encodeURIComponent(s.indexName)+"/browse?"+u,hostType:"read",callback:r})},browseFrom:function(e,t){return this.as._jsonRequest({method:"GET",url:"/1/indexes/"+encodeURIComponent(this.indexName)+"/browse?cursor="+encodeURIComponent(e),hostType:"read",callback:t})},browseAll:function(e,t){function r(e){if(!s._stopped){var t;t=void 0!==e?"cursor="+encodeURIComponent(e):l,u._jsonRequest({method:"GET",url:"/1/indexes/"+encodeURIComponent(c.indexName)+"/browse?"+t,hostType:"read",callback:o})}}function o(e,t){return s._stopped?void 0:e?void s._error(e):(s._result(t),void 0===t.cursor?void s._end():void r(t.cursor))}"object"==typeof e&&(t=e,e=void 0);var i=n(53),a=n(62),s=new a,u=this.as,c=this,l=u._getSearchParams(i({},t||{},{query:e}),"");return r(),s},ttAdapter:function(e){var t=this;return function(n,r,o){var i;i="function"==typeof o?o:r,t.search(n,e,function(e,t){return e?void i(e):void i(t.hits)})}},waitTask:function(e,t){function n(){return l._jsonRequest({method:"GET",hostType:"read",url:"/1/indexes/"+encodeURIComponent(c.indexName)+"/task/"+e}).then(function(e){s++;var t=i*s*s;return t>a&&(t=a),"published"!==e.status?l._promise.delay(t).then(n):e})}function r(e){u(function(){t(null,e)},l._setTimeout||setTimeout)}function o(e){u(function(){t(e)},l._setTimeout||setTimeout)}var i=100,a=5e3,s=0,c=this,l=c.as,p=n();return t?void p.then(r,o):p},clearIndex:function(e){var t=this;return this.as._jsonRequest({method:"POST",url:"/1/indexes/"+encodeURIComponent(t.indexName)+"/clear",hostType:"write",callback:e})},getSettings:function(e){var t=this;return this.as._jsonRequest({method:"GET",url:"/1/indexes/"+encodeURIComponent(t.indexName)+"/settings",hostType:"read",callback:e})},setSettings:function(e,t){var n=this;return this.as._jsonRequest({method:"PUT",url:"/1/indexes/"+encodeURIComponent(n.indexName)+"/settings",hostType:"write",body:e,callback:t})},listUserKeys:function(e){var t=this;return this.as._jsonRequest({method:"GET",url:"/1/indexes/"+encodeURIComponent(t.indexName)+"/keys",hostType:"read",callback:e})},getUserKeyACL:function(e,t){var n=this;return this.as._jsonRequest({method:"GET",url:"/1/indexes/"+encodeURIComponent(n.indexName)+"/keys/"+e,hostType:"read",callback:t})},deleteUserKey:function(e,t){var n=this;return this.as._jsonRequest({method:"DELETE",url:"/1/indexes/"+encodeURIComponent(n.indexName)+"/keys/"+e,hostType:"write",callback:t})},addUserKey:function(e,t,n){(1===arguments.length||"function"==typeof t)&&(n=t,t=null);var r={acl:e};return t&&(r.validity=t.validity,r.maxQueriesPerIPPerHour=t.maxQueriesPerIPPerHour,r.maxHitsPerQuery=t.maxHitsPerQuery,r.description=t.description,t.queryParameters&&(r.queryParameters=this.as._getSearchParams(t.queryParameters,"")),r.referers=t.referers),this.as._jsonRequest({method:"POST",url:"/1/indexes/"+encodeURIComponent(this.indexName)+"/keys",body:r,hostType:"write",callback:n})},addUserKeyWithValidity:c(function(e,t,n){return this.addUserKey(e,t,n)},s("index.addUserKeyWithValidity()","index.addUserKey()")),updateUserKey:function(e,t,n,r){(2===arguments.length||"function"==typeof n)&&(r=n,n=null);var o={acl:t};return n&&(o.validity=n.validity,o.maxQueriesPerIPPerHour=n.maxQueriesPerIPPerHour,o.maxHitsPerQuery=n.maxHitsPerQuery,o.description=n.description,n.queryParameters&&(o.queryParameters=this.as._getSearchParams(n.queryParameters,"")),o.referers=n.referers), this.as._jsonRequest({method:"PUT",url:"/1/indexes/"+encodeURIComponent(this.indexName)+"/keys/"+e,body:o,hostType:"write",callback:r})},_search:function(e,t){return this.as._jsonRequest({cache:this.cache,method:"POST",url:"/1/indexes/"+encodeURIComponent(this.indexName)+"/query",body:{params:e},hostType:"read",fallback:{method:"GET",url:"/1/indexes/"+encodeURIComponent(this.indexName),body:{params:e}},callback:t})},as:null,indexName:null,typeAheadArgs:null,typeAheadValueOption:null}},function(e,t,n){function r(){return"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 o(){var e=arguments,n=this.useColors;if(e[0]=(n?"%c":"")+this.namespace+(n?" %c":" ")+e[0]+(n?"%c ":" ")+"+"+t.humanize(this.diff),!n)return e;var r="color: "+this.color;e=[e[0],r,"color: inherit"].concat(Array.prototype.slice.call(e,1));var o=0,i=0;return e[0].replace(/%[a-z%]/g,function(e){"%%"!==e&&(o++,"%c"===e&&(i=o))}),e.splice(i,0,r),e}function i(){return"object"==typeof console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}function a(e){try{null==e?t.storage.removeItem("debug"):t.storage.debug=e}catch(n){}}function s(){var e;try{e=t.storage.debug}catch(n){}return e}function u(){try{return window.localStorage}catch(e){}}t=e.exports=n(14),t.log=i,t.formatArgs=o,t.save=a,t.load=s,t.useColors=r,t.storage="undefined"!=typeof chrome&&"undefined"!=typeof chrome.storage?chrome.storage.local:u(),t.colors=["lightseagreen","forestgreen","goldenrod","dodgerblue","darkorchid","crimson"],t.formatters.j=function(e){return JSON.stringify(e)},t.enable(s())},function(e,t,n){function r(){return t.colors[l++%t.colors.length]}function o(e){function n(){}function o(){var e=o,n=+new Date,i=n-(c||n);e.diff=i,e.prev=c,e.curr=n,c=n,null==e.useColors&&(e.useColors=t.useColors()),null==e.color&&e.useColors&&(e.color=r());var a=Array.prototype.slice.call(arguments);a[0]=t.coerce(a[0]),"string"!=typeof a[0]&&(a=["%o"].concat(a));var s=0;a[0]=a[0].replace(/%([a-z%])/g,function(n,r){if("%%"===n)return n;s++;var o=t.formatters[r];if("function"==typeof o){var i=a[s];n=o.call(e,i),a.splice(s,1),s--}return n}),"function"==typeof t.formatArgs&&(a=t.formatArgs.apply(e,a));var u=o.log||t.log||console.log.bind(console);u.apply(e,a)}n.enabled=!1,o.enabled=!0;var i=t.enabled(e)?o:n;return i.namespace=e,i}function i(e){t.save(e);for(var n=(e||"").split(/[\s,]+/),r=n.length,o=0;r>o;o++)n[o]&&(e=n[o].replace(/\*/g,".*?"),"-"===e[0]?t.skips.push(new RegExp("^"+e.substr(1)+"$")):t.names.push(new RegExp("^"+e+"$")))}function a(){t.enable("")}function s(e){var n,r;for(n=0,r=t.skips.length;r>n;n++)if(t.skips[n].test(e))return!1;for(n=0,r=t.names.length;r>n;n++)if(t.names[n].test(e))return!0;return!1}function u(e){return e instanceof Error?e.stack||e.message:e}t=e.exports=o,t.coerce=u,t.disable=a,t.enable=i,t.enabled=s,t.humanize=n(15),t.names=[],t.skips=[],t.formatters={};var c,l=0},function(e){function t(e){if(e=""+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 n=parseFloat(t[1]),r=(t[2]||"ms").toLowerCase();switch(r){case"years":case"year":case"yrs":case"yr":case"y":return n*c;case"days":case"day":case"d":return n*u;case"hours":case"hour":case"hrs":case"hr":case"h":return n*s;case"minutes":case"minute":case"mins":case"min":case"m":return n*a;case"seconds":case"second":case"secs":case"sec":case"s":return n*i;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n}}}}function n(e){return e>=u?Math.round(e/u)+"d":e>=s?Math.round(e/s)+"h":e>=a?Math.round(e/a)+"m":e>=i?Math.round(e/i)+"s":e+"ms"}function r(e){return o(e,u,"day")||o(e,s,"hour")||o(e,a,"minute")||o(e,i,"second")||e+" ms"}function o(e,t,n){return t>e?void 0:1.5*t>e?Math.floor(e/t)+" "+n:Math.ceil(e/t)+" "+n+"s"}var i=1e3,a=60*i,s=60*a,u=24*s,c=365.25*u;e.exports=function(e,o){return o=o||{},"string"==typeof e?t(e):o["long"]?r(e):n(e)}},function(e,t,n){"use strict";function r(e,t){var r=n(17),o=this;"function"==typeof Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):o.stack=(new Error).stack||"Cannot get a stacktrace, browser is too old",this.name=this.constructor.name,this.message=e||"Unknown error",t&&r(t,function(e,t){o[t]=e})}function o(e,t){function n(){var n=Array.prototype.slice.call(arguments,0);"string"!=typeof n[0]&&n.unshift(t),r.apply(this,n),this.name="AlgoliaSearch"+e+"Error"}return i(n,r),n}var i=n(6);i(r,Error),e.exports={AlgoliaSearchError:r,UnparsableJSON:o("UnparsableJSON","Could not parse the incoming response as JSON, see err.more for details"),RequestTimeout:o("RequestTimeout","Request timedout before getting a response"),Network:o("Network","Network issue, see err.more for details"),JSONPScriptFail:o("JSONPScriptFail","<script> was loaded but did not call our provided callback"),JSONPScriptError:o("JSONPScriptError","<script> unable to load due to an `error` event on it"),Unknown:o("Unknown","Unknown error occured")}},function(e,t,n){var r=n(18),o=n(19),i=n(40),a=i(r,o);e.exports=a},function(e){function t(e,t){for(var n=-1,r=e.length;++n<r&&t(e[n],n,e)!==!1;);return e}e.exports=t},function(e,t,n){var r=n(20),o=n(39),i=o(r);e.exports=i},function(e,t,n){function r(e,t){return o(e,t,i)}var o=n(21),i=n(25);e.exports=r},function(e,t,n){var r=n(22),o=r();e.exports=o},function(e,t,n){function r(e){return function(t,n,r){for(var i=o(t),a=r(t),s=a.length,u=e?s:-1;e?u--:++u<s;){var c=a[u];if(n(i[c],c,i)===!1)break}return t}}var o=n(23);e.exports=r},function(e,t,n){function r(e){return o(e)?e:Object(e)}var o=n(24);e.exports=r},function(e){function t(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}e.exports=t},function(e,t,n){var r=n(26),o=n(30),i=n(24),a=n(34),s=r(Object,"keys"),u=s?function(e){var t=null==e?void 0:e.constructor;return"function"==typeof t&&t.prototype===e||"function"!=typeof e&&o(e)?a(e):i(e)?s(e):[]}:a;e.exports=u},function(e,t,n){function r(e,t){var n=null==e?void 0:e[t];return o(n)?n:void 0}var o=n(27);e.exports=r},function(e,t,n){function r(e){return null==e?!1:o(e)?l.test(u.call(e)):i(e)&&a.test(e)}var o=n(28),i=n(29),a=/^\[object .+?Constructor\]$/,s=Object.prototype,u=Function.prototype.toString,c=s.hasOwnProperty,l=RegExp("^"+u.call(c).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");e.exports=r},function(e,t,n){function r(e){return o(e)&&s.call(e)==i}var o=n(24),i="[object Function]",a=Object.prototype,s=a.toString;e.exports=r},function(e){function t(e){return!!e&&"object"==typeof e}e.exports=t},function(e,t,n){function r(e){return null!=e&&i(o(e))}var o=n(31),i=n(33);e.exports=r},function(e,t,n){var r=n(32),o=r("length");e.exports=o},function(e){function t(e){return function(t){return null==t?void 0:t[e]}}e.exports=t},function(e){function t(e){return"number"==typeof e&&e>-1&&e%1==0&&n>=e}var n=9007199254740991;e.exports=t},function(e,t,n){function r(e){for(var t=u(e),n=t.length,r=n&&e.length,c=!!r&&s(r)&&(i(e)||o(e)),p=-1,f=[];++p<n;){var h=t[p];(c&&a(h,r)||l.call(e,h))&&f.push(h)}return f}var o=n(35),i=n(36),a=n(37),s=n(33),u=n(38),c=Object.prototype,l=c.hasOwnProperty;e.exports=r},function(e,t,n){function r(e){return i(e)&&o(e)&&s.call(e,"callee")&&!u.call(e,"callee")}var o=n(30),i=n(29),a=Object.prototype,s=a.hasOwnProperty,u=a.propertyIsEnumerable;e.exports=r},function(e,t,n){var r=n(26),o=n(33),i=n(29),a="[object Array]",s=Object.prototype,u=s.toString,c=r(Array,"isArray"),l=c||function(e){return i(e)&&o(e.length)&&u.call(e)==a};e.exports=l},function(e){function t(e,t){return e="number"==typeof e||n.test(e)?+e:-1,t=null==t?r:t,e>-1&&e%1==0&&t>e}var n=/^\d+$/,r=9007199254740991;e.exports=t},function(e,t,n){function r(e){if(null==e)return[];u(e)||(e=Object(e));var t=e.length;t=t&&s(t)&&(i(e)||o(e))&&t||0;for(var n=e.constructor,r=-1,c="function"==typeof n&&n.prototype===e,p=Array(t),f=t>0;++r<t;)p[r]=r+"";for(var h in e)f&&a(h,t)||"constructor"==h&&(c||!l.call(e,h))||p.push(h);return p}var o=n(35),i=n(36),a=n(37),s=n(33),u=n(24),c=Object.prototype,l=c.hasOwnProperty;e.exports=r},function(e,t,n){function r(e,t){return function(n,r){var s=n?o(n):0;if(!i(s))return e(n,r);for(var u=t?s:-1,c=a(n);(t?u--:++u<s)&&r(c[u],u,c)!==!1;);return n}}var o=n(31),i=n(33),a=n(23);e.exports=r},function(e,t,n){function r(e,t){return function(n,r,a){return"function"==typeof r&&void 0===a&&i(n)?e(n,r):t(n,o(r,a,3))}}var o=n(41),i=n(36);e.exports=r},function(e,t,n){function r(e,t,n){if("function"!=typeof e)return o;if(void 0===t)return e;switch(n){case 1:return function(n){return e.call(t,n)};case 3:return function(n,r,o){return e.call(t,n,r,o)};case 4:return function(n,r,o,i){return e.call(t,n,r,o,i)};case 5:return function(n,r,o,i,a){return e.call(t,n,r,o,i,a)}}return function(){return e.apply(t,arguments)}}var o=n(42);e.exports=r},function(e){function t(e){return e}e.exports=t},function(e,t,n){function r(e,t,n,r){return t&&"boolean"!=typeof t&&a(e,t,n)?t=!1:"function"==typeof t&&(r=n,n=t,t=!1),"function"==typeof n?o(e,t,i(n,r,3)):o(e,t)}var o=n(44),i=n(41),a=n(52);e.exports=r},function(e,t,n){function r(e,t,n,d,v,m,g){var b;if(n&&(b=v?n(e,d,v):n(e)),void 0!==b)return b;if(!f(e))return e;var x=p(e);if(x){if(b=u(e),!t)return o(e,b)}else{var _=U.call(e),P=_==y;if(_!=w&&_!=h&&(!P||v))return M[_]?c(e,_,t):v?e:{};if(b=l(P?{}:e),!t)return a(b,e)}m||(m=[]),g||(g=[]);for(var C=m.length;C--;)if(m[C]==e)return g[C];return m.push(e),g.push(b),(x?i:s)(e,function(o,i){b[i]=r(o,t,n,i,e,m,g)}),b}var o=n(45),i=n(18),a=n(46),s=n(20),u=n(48),c=n(49),l=n(51),p=n(36),f=n(24),h="[object Arguments]",d="[object Array]",v="[object Boolean]",m="[object Date]",g="[object Error]",y="[object Function]",b="[object Map]",x="[object Number]",w="[object Object]",_="[object RegExp]",P="[object Set]",C="[object String]",E="[object WeakMap]",R="[object ArrayBuffer]",T="[object Float32Array]",O="[object Float64Array]",S="[object Int8Array]",N="[object Int16Array]",j="[object Int32Array]",k="[object Uint8Array]",I="[object Uint8ClampedArray]",D="[object Uint16Array]",A="[object Uint32Array]",M={};M[h]=M[d]=M[R]=M[v]=M[m]=M[T]=M[O]=M[S]=M[N]=M[j]=M[x]=M[w]=M[_]=M[C]=M[k]=M[I]=M[D]=M[A]=!0,M[g]=M[y]=M[b]=M[P]=M[E]=!1;var F=Object.prototype,U=F.toString;e.exports=r},function(e){function t(e,t){var n=-1,r=e.length;for(t||(t=Array(r));++n<r;)t[n]=e[n];return t}e.exports=t},function(e,t,n){function r(e,t){return null==t?e:o(t,i(t),e)}var o=n(47),i=n(25);e.exports=r},function(e){function t(e,t,n){n||(n={});for(var r=-1,o=t.length;++r<o;){var i=t[r];n[i]=e[i]}return n}e.exports=t},function(e){function t(e){var t=e.length,n=new e.constructor(t);return t&&"string"==typeof e[0]&&r.call(e,"index")&&(n.index=e.index,n.input=e.input),n}var n=Object.prototype,r=n.hasOwnProperty;e.exports=t},function(e,t,n){function r(e,t,n){var r=e.constructor;switch(t){case l:return o(e);case i:case a:return new r(+e);case p:case f:case h:case d:case v:case m:case g:case y:case b:var w=e.buffer;return new r(n?o(w):w,e.byteOffset,e.length);case s:case c:return new r(e);case u:var _=new r(e.source,x.exec(e));_.lastIndex=e.lastIndex}return _}var o=n(50),i="[object Boolean]",a="[object Date]",s="[object Number]",u="[object RegExp]",c="[object String]",l="[object ArrayBuffer]",p="[object Float32Array]",f="[object Float64Array]",h="[object Int8Array]",d="[object Int16Array]",v="[object Int32Array]",m="[object Uint8Array]",g="[object Uint8ClampedArray]",y="[object Uint16Array]",b="[object Uint32Array]",x=/\w*$/;e.exports=r},function(e,t){(function(t){function n(e){var t=new r(e.byteLength),n=new o(t);return n.set(new o(e)),t}var r=t.ArrayBuffer,o=t.Uint8Array;e.exports=n}).call(t,function(){return this}())},function(e){function t(e){var t=e.constructor;return"function"==typeof t&&t instanceof t||(t=Object),new t}e.exports=t},function(e,t,n){function r(e,t,n){if(!a(n))return!1;var r=typeof t;if("number"==r?o(n)&&i(t,n.length):"string"==r&&t in n){var s=n[t];return e===e?e===s:s!==s}return!1}var o=n(30),i=n(37),a=n(24);e.exports=r},function(e,t,n){var r=n(54),o=n(60),i=o(r);e.exports=i},function(e,t,n){function r(e,t,n,f,h){if(!u(e))return e;var d=s(t)&&(a(t)||l(t)),v=d?void 0:p(t);return o(v||t,function(o,a){if(v&&(a=o,o=t[a]),c(o))f||(f=[]),h||(h=[]),i(e,t,a,r,n,f,h);else{var s=e[a],u=n?n(s,o,a,e,t):void 0,l=void 0===u;l&&(u=o),void 0===u&&(!d||a in e)||!l&&(u===u?u===s:s!==s)||(e[a]=u)}}),e}var o=n(18),i=n(55),a=n(36),s=n(30),u=n(24),c=n(29),l=n(58),p=n(25);e.exports=r},function(e,t,n){function r(e,t,n,r,p,f,h){for(var d=f.length,v=t[n];d--;)if(f[d]==v)return void(e[n]=h[d]);var m=e[n],g=p?p(m,v,n,e,t):void 0,y=void 0===g;y&&(g=v,s(v)&&(a(v)||c(v))?g=a(m)?m:s(m)?o(m):[]:u(v)||i(v)?g=i(m)?l(m):u(m)?m:{}:y=!1),f.push(v),h.push(g),y?e[n]=r(g,v,p,f,h):(g===g?g!==m:m===m)&&(e[n]=g)}var o=n(45),i=n(35),a=n(36),s=n(30),u=n(56),c=n(58),l=n(59);e.exports=r},function(e,t,n){function r(e){var t;if(!a(e)||l.call(e)!=s||i(e)||!c.call(e,"constructor")&&(t=e.constructor,"function"==typeof t&&!(t instanceof t)))return!1;var n;return o(e,function(e,t){n=t}),void 0===n||c.call(e,n)}var o=n(57),i=n(35),a=n(29),s="[object Object]",u=Object.prototype,c=u.hasOwnProperty,l=u.toString;e.exports=r},function(e,t,n){function r(e,t){return o(e,t,i)}var o=n(21),i=n(38);e.exports=r},function(e,t,n){function r(e){return i(e)&&o(e.length)&&!!S[j.call(e)]}var o=n(33),i=n(29),a="[object Arguments]",s="[object Array]",u="[object Boolean]",c="[object Date]",l="[object Error]",p="[object Function]",f="[object Map]",h="[object Number]",d="[object Object]",v="[object RegExp]",m="[object Set]",g="[object String]",y="[object WeakMap]",b="[object ArrayBuffer]",x="[object Float32Array]",w="[object Float64Array]",_="[object Int8Array]",P="[object Int16Array]",C="[object Int32Array]",E="[object Uint8Array]",R="[object Uint8ClampedArray]",T="[object Uint16Array]",O="[object Uint32Array]",S={};S[x]=S[w]=S[_]=S[P]=S[C]=S[E]=S[R]=S[T]=S[O]=!0,S[a]=S[s]=S[b]=S[u]=S[c]=S[l]=S[p]=S[f]=S[h]=S[d]=S[v]=S[m]=S[g]=S[y]=!1;var N=Object.prototype,j=N.toString;e.exports=r},function(e,t,n){function r(e){return o(e,i(e))}var o=n(47),i=n(38);e.exports=r},function(e,t,n){function r(e){return a(function(t,n){var r=-1,a=null==t?0:n.length,s=a>2?n[a-2]:void 0,u=a>2?n[2]:void 0,c=a>1?n[a-1]:void 0;for("function"==typeof s?(s=o(s,c,5),a-=2):(s="function"==typeof c?c:void 0,a-=s?1:0),u&&i(n[0],n[1],u)&&(s=3>a?void 0:s,a=1);++r<a;){var l=n[r];l&&e(t,l,s)}return t})}var o=n(41),i=n(52),a=n(61);e.exports=r},function(e){function t(e,t){if("function"!=typeof e)throw new TypeError(n);return t=r(void 0===t?e.length-1:+t||0,0),function(){for(var n=arguments,o=-1,i=r(n.length-t,0),a=Array(i);++o<i;)a[o]=n[t+o];switch(t){case 0:return e.call(this,a);case 1:return e.call(this,n[0],a);case 2:return e.call(this,n[0],n[1],a)}var s=Array(t+1);for(o=-1;++o<t;)s[o]=n[o];return s[t]=a,e.apply(this,s)}}var n="Expected a function",r=Math.max;e.exports=t},function(e,t,n){"use strict";function r(){}e.exports=r;var o=n(6),i=n(63).EventEmitter;o(r,i),r.prototype.stop=function(){this._stopped=!0,this._clean()},r.prototype._end=function(){this.emit("end"),this._clean()},r.prototype._error=function(e){this.emit("error",e),this._clean()},r.prototype._result=function(e){this.emit("result",e)},r.prototype._clean=function(){this.removeAllListeners("stop"),this.removeAllListeners("end"),this.removeAllListeners("error"),this.removeAllListeners("result")}},function(e){function t(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function n(e){return"function"==typeof e}function r(e){return"number"==typeof e}function o(e){return"object"==typeof e&&null!==e}function i(e){return void 0===e}e.exports=t,t.EventEmitter=t,t.prototype._events=void 0,t.prototype._maxListeners=void 0,t.defaultMaxListeners=10,t.prototype.setMaxListeners=function(e){if(!r(e)||0>e||isNaN(e))throw TypeError("n must be a positive number");return this._maxListeners=e,this},t.prototype.emit=function(e){var t,r,a,s,u,c;if(this._events||(this._events={}),"error"===e&&(!this._events.error||o(this._events.error)&&!this._events.error.length)){if(t=arguments[1],t instanceof Error)throw t;throw TypeError('Uncaught, unspecified "error" event.')}if(r=this._events[e],i(r))return!1;if(n(r))switch(arguments.length){case 1:r.call(this);break;case 2:r.call(this,arguments[1]);break;case 3:r.call(this,arguments[1],arguments[2]);break;default:s=Array.prototype.slice.call(arguments,1),r.apply(this,s)}else if(o(r))for(s=Array.prototype.slice.call(arguments,1),c=r.slice(),a=c.length,u=0;a>u;u++)c[u].apply(this,s);return!0},t.prototype.addListener=function(e,r){var a;if(!n(r))throw TypeError("listener must be a function");return this._events||(this._events={}),this._events.newListener&&this.emit("newListener",e,n(r.listener)?r.listener:r),this._events[e]?o(this._events[e])?this._events[e].push(r):this._events[e]=[this._events[e],r]:this._events[e]=r,o(this._events[e])&&!this._events[e].warned&&(a=i(this._maxListeners)?t.defaultMaxListeners:this._maxListeners,a&&a>0&&this._events[e].length>a&&(this._events[e].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[e].length),"function"==typeof console.trace&&console.trace())),this},t.prototype.on=t.prototype.addListener,t.prototype.once=function(e,t){function r(){this.removeListener(e,r),o||(o=!0,t.apply(this,arguments))}if(!n(t))throw TypeError("listener must be a function");var o=!1;return r.listener=t,this.on(e,r),this},t.prototype.removeListener=function(e,t){var r,i,a,s;if(!n(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;if(r=this._events[e],a=r.length,i=-1,r===t||n(r.listener)&&r.listener===t)delete this._events[e],this._events.removeListener&&this.emit("removeListener",e,t);else if(o(r)){for(s=a;s-->0;)if(r[s]===t||r[s].listener&&r[s].listener===t){i=s;break}if(0>i)return this;1===r.length?(r.length=0,delete this._events[e]):r.splice(i,1),this._events.removeListener&&this.emit("removeListener",e,t)}return this},t.prototype.removeAllListeners=function(e){var t,r;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[e]&&delete this._events[e],this;if(0===arguments.length){for(t in this._events)"removeListener"!==t&&this.removeAllListeners(t);return this.removeAllListeners("removeListener"),this._events={},this}if(r=this._events[e],n(r))this.removeListener(e,r);else if(r)for(;r.length;)this.removeListener(e,r[r.length-1]);return delete this._events[e],this},t.prototype.listeners=function(e){var t;return t=this._events&&this._events[e]?n(this._events[e])?[this._events[e]]:this._events[e].slice():[]},t.prototype.listenerCount=function(e){if(this._events){var t=this._events[e];if(n(t))return 1;if(t)return t.length}return 0},t.listenerCount=function(e,t){return e.listenerCount(t)}},function(e,t,n){"use strict";function r(e,t){return e+=/\?/.test(e)?"&":"?",e+o.encode(t)}e.exports=r;var o=n(65)},function(e,t,n){"use strict";t.decode=t.parse=n(66),t.encode=t.stringify=n(67)},function(e){"use strict";function t(e,t){return Object.prototype.hasOwnProperty.call(e,t)}e.exports=function(e,r,o,i){r=r||"&",o=o||"=";var a={};if("string"!=typeof e||0===e.length)return a;var s=/\+/g;e=e.split(r);var u=1e3;i&&"number"==typeof i.maxKeys&&(u=i.maxKeys);var c=e.length;u>0&&c>u&&(c=u);for(var l=0;c>l;++l){var p,f,h,d,v=e[l].replace(s,"%20"),m=v.indexOf(o);m>=0?(p=v.substr(0,m),f=v.substr(m+1)):(p=v,f=""),h=decodeURIComponent(p),d=decodeURIComponent(f),t(a,h)?n(a[h])?a[h].push(d):a[h]=[a[h],d]:a[h]=d}return a};var n=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)}},function(e){"use strict";function t(e,t){if(e.map)return e.map(t);for(var n=[],r=0;r<e.length;r++)n.push(t(e[r],r));return n}var n=function(e){switch(typeof e){case"string":return e;case"boolean":return e?"true":"false";case"number":return isFinite(e)?e:"";default:return""}};e.exports=function(e,i,a,s){return i=i||"&",a=a||"=",null===e&&(e=void 0),"object"==typeof e?t(o(e),function(o){var s=encodeURIComponent(n(o))+a;return r(e[o])?t(e[o],function(e){return s+encodeURIComponent(n(e))}).join(i):s+encodeURIComponent(n(e[o]))}).join(i):s?encodeURIComponent(n(s))+a+encodeURIComponent(n(e)):""};var r=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)},o=Object.keys||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t}},function(e,t,n){"use strict";function r(e,t,n){function r(){t.debug("JSONP: success"),v||p||(v=!0,l||(t.debug("JSONP: Fail. Script loaded but did not call the callback"),s(),n(new o.JSONPScriptFail)))}function a(){("loaded"===this.readyState||"complete"===this.readyState)&&r()}function s(){clearTimeout(m),h.onload=null,h.onreadystatechange=null,h.onerror=null,f.removeChild(h);try{delete window[d],delete window[d+"_loaded"]}catch(e){window[d]=null,window[d+"_loaded"]=null}}function u(){t.debug("JSONP: Script timeout"),p=!0,s(),n(new o.RequestTimeout)}function c(){t.debug("JSONP: Script error"),v||p||(s(),n(new o.JSONPScriptError))}if("GET"!==t.method)return void n(new Error("Method "+t.method+" "+e+" is not supported by JSONP."));t.debug("JSONP: start");var l=!1,p=!1;i+=1;var f=document.getElementsByTagName("head")[0],h=document.createElement("script"),d="algoliaJSONP_"+i,v=!1;window[d]=function(e){try{delete window[d]}catch(t){window[d]=void 0}p||(l=!0,s(),n(null,{body:e}))},e+="&callback="+d,t.jsonBody&&t.jsonBody.params&&(e+="&"+t.jsonBody.params);var m=setTimeout(u,t.timeout);h.onreadystatechange=a,h.onload=r,h.onerror=c,h.async=!0,h.defer=!0,h.src=e,f.appendChild(h)}e.exports=r;var o=n(16),i=0},function(e,t,n){function r(e,t,n){return"function"==typeof t?o(e,!0,i(t,n,3)):o(e,!0)}var o=n(44),i=n(41);e.exports=r},function(e){"use strict";function t(){var e=window.document.location.protocol;return"http:"!==e&&"https:"!==e&&(e="http:"),e}e.exports=t},function(e){"use strict";e.exports="3.9.0"},function(e,t,n){"use strict";function r(e,t,n){return new o(e,t,n)}var o=n(73),i=n(74),a=n(141);r.version=n(210),r.AlgoliaSearchHelper=o,r.SearchParameters=i,r.SearchResults=a,r.url=n(200),e.exports=r},function(e,t,n){"use strict";function r(e,t,n){this.client=e;var r=n||{};r.index=t,this.state=o.make(r),this.lastResults=null,this._queryId=0,this._lastQueryIdReceived=-1}var o=n(74),i=n(141),a=n(195),s=n(196),u=n(63),c=n(17),l=n(108),p=n(199),f=n(124),h=n(188),d=n(200);s.inherits(r,u.EventEmitter),r.prototype.search=function(){return this._search(),this},r.prototype.searchOnce=function(e,t){var n=this.state.setQueryParameters(e),r=a._getQueries(n.index,n);return t?this.client.search(r,function(e,r){t(e,new i(n,r),n)}):this.client.search(r).then(function(e){return{content:new i(n,e),state:n}})},r.prototype.setQuery=function(e){return this.state=this.state.setQuery(e),this._change(),this},r.prototype.clearRefinements=function(e){return this.state=this.state.clearRefinements(e),this._change(),this},r.prototype.clearTags=function(){return this.state=this.state.clearTags(),this._change(),this},r.prototype.addDisjunctiveFacetRefinement=function(e,t){return this.state=this.state.addDisjunctiveFacetRefinement(e,t),this._change(),this},r.prototype.addDisjunctiveRefine=function(){return this.addDisjunctiveFacetRefinement.apply(this,arguments)},r.prototype.addNumericRefinement=function(e,t,n){return this.state=this.state.addNumericRefinement(e,t,n),this._change(),this},r.prototype.addFacetRefinement=function(e,t){return this.state=this.state.addFacetRefinement(e,t),this._change(),this},r.prototype.addRefine=function(){return this.addFacetRefinement.apply(this,arguments)},r.prototype.addFacetExclusion=function(e,t){return this.state=this.state.addExcludeRefinement(e,t),this._change(),this},r.prototype.addExclude=function(){return this.addFacetExclusion.apply(this,arguments)},r.prototype.addTag=function(e){return this.state=this.state.addTagRefinement(e),this._change(),this},r.prototype.removeNumericRefinement=function(e,t,n){return this.state=this.state.removeNumericRefinement(e,t,n),this._change(),this},r.prototype.removeDisjunctiveFacetRefinement=function(e,t){return this.state=this.state.removeDisjunctiveFacetRefinement(e,t),this._change(),this},r.prototype.removeDisjunctiveRefine=function(){return this.removeDisjunctiveFacetRefinement.apply(this,arguments)},r.prototype.removeFacetRefinement=function(e,t){return this.state=this.state.removeFacetRefinement(e,t),this._change(),this},r.prototype.removeRefine=function(){return this.removeFacetRefinement.apply(this,arguments)},r.prototype.removeFacetExclusion=function(e,t){return this.state=this.state.removeExcludeRefinement(e,t),this._change(),this},r.prototype.removeExclude=function(){return this.removeFacetExclusion.apply(this,arguments)},r.prototype.removeTag=function(e){return this.state=this.state.removeTagRefinement(e),this._change(),this},r.prototype.toggleFacetExclusion=function(e,t){return this.state=this.state.toggleExcludeFacetRefinement(e,t),this._change(),this},r.prototype.toggleExclude=function(){return this.toggleFacetExclusion.apply(this,arguments)},r.prototype.toggleRefinement=function(e,t){return this.state=this.state.toggleRefinement(e,t),this._change(),this},r.prototype.toggleRefine=function(){return this.toggleRefinement.apply(this,arguments)},r.prototype.toggleTag=function(e){return this.state=this.state.toggleTagRefinement(e),this._change(),this},r.prototype.nextPage=function(){return this.setCurrentPage(this.state.page+1)},r.prototype.previousPage=function(){return this.setCurrentPage(this.state.page-1)},r.prototype.setCurrentPage=function(e){if(0>e)throw new Error("Page requested below 0.");return this.state=this.state.setPage(e),this._change(),this},r.prototype.setIndex=function(e){return this.state=this.state.setIndex(e),this._change(),this},r.prototype.setQueryParameter=function(e,t){var n=this.state.setQueryParameter(e,t);return this.state===n?this:(this.state=n,this._change(),this)},r.prototype.setState=function(e){return this.state=new o(e),this._change(),this},r.prototype.getState=function(e){return void 0===e?this.state:this.state.filter(e)},r.prototype.getStateAsQueryString=function(e){var t=e&&e.filters||["query","attribute:*"],n=this.getState(t);return d.getQueryStringFromState(n,e)},r.getConfigurationFromQueryString=d.getStateFromQueryString,r.getForeignConfigurationInQueryString=d.getUnrecognizedParametersInQueryString,r.prototype.setStateFromQueryString=function(e,t){var n=t&&t.triggerChange||!1,r=d.getStateFromQueryString(e,t),o=this.state.setQueryParameters(r);n?this.setState(o):this.overrideStateWithoutTriggeringChangeEvent(o)},r.prototype.overrideStateWithoutTriggeringChangeEvent=function(e){return this.state=new o(e),this},r.prototype.isRefined=function(e,t){if(this.state.isConjunctiveFacet(e))return this.state.isFacetRefined(e,t);if(this.state.isDisjunctiveFacet(e))return this.state.isDisjunctiveFacetRefined(e,t);throw new Error(e+" is not properly defined in this helper configuration(use the facets or disjunctiveFacets keys to configure it)")},r.prototype.hasRefinements=function(e){return f(this.state.getNumericRefinements(e))?this.state.isConjunctiveFacet(e)?this.state.isFacetRefined(e):this.state.isDisjunctiveFacet(e)?this.state.isDisjunctiveFacetRefined(e):this.state.isHierarchicalFacet(e)?this.state.isHierarchicalFacetRefined(e):!1:!0},r.prototype.isExcluded=function(e,t){return this.state.isExcludeRefined(e,t)},r.prototype.isDisjunctiveRefined=function(e,t){return this.state.isDisjunctiveFacetRefined(e,t)},r.prototype.hasTag=function(e){return this.state.isTagRefined(e)},r.prototype.isTagRefined=function(){return this.hasTagRefinements.apply(this,arguments)},r.prototype.getIndex=function(){return this.state.index},r.prototype.getCurrentPage=function(){return this.state.page},r.prototype.getTags=function(){return this.state.tagRefinements},r.prototype.getQueryParameter=function(e){return this.state.getQueryParameter(e)},r.prototype.getRefinements=function(e){var t=[];if(this.state.isConjunctiveFacet(e)){var n=this.state.getConjunctiveRefinements(e);c(n,function(e){t.push({value:e,type:"conjunctive"})});var r=this.state.getExcludeRefinements(e);c(r,function(e){t.push({value:e,type:"exclude"})})}else if(this.state.isDisjunctiveFacet(e)){var o=this.state.getDisjunctiveRefinements(e);c(o,function(e){t.push({value:e,type:"disjunctive"})})}var i=this.state.getNumericRefinements(e);return c(i,function(e,n){t.push({value:e,operator:n,type:"numeric"})}),t},r.prototype.getHierarchicalFacetBreadcrumb=function(e){return l(this.state.getHierarchicalRefinement(e)[0].split(this.state._getHierarchicalFacetSeparator(this.state.getHierarchicalFacetByName(e))),function(e){return h(e)})},r.prototype._search=function(){var e=this.state,t=a._getQueries(e.index,e);this.emit("search",e,this.lastResults),this.client.search(t,p(this._handleResponse,this,e,this._queryId++))},r.prototype._handleResponse=function(e,t,n,r){if(!(t<this._lastQueryIdReceived)){if(this._lastQueryIdReceived=t,n)return void this.emit("error",n);var o=this.lastResults=new i(e,r);this.emit("result",o,e)}},r.prototype.containsRefinement=function(e,t,n,r){return e||0!==t.length||0!==n.length||0!==r.length},r.prototype._hasDisjunctiveRefinements=function(e){return this.state.disjunctiveRefinements[e]&&this.state.disjunctiveRefinements[e].length>0},r.prototype._change=function(){this.emit("change",this.state,this.lastResults)},e.exports=r},function(e,t,n){"use strict";function r(e){var t=e?r._parseNumbers(e):{};this.index=t.index||"",this.query=t.query||"",this.facets=t.facets||[],this.disjunctiveFacets=t.disjunctiveFacets||[],this.hierarchicalFacets=t.hierarchicalFacets||[],this.facetsRefinements=t.facetsRefinements||{},this.facetsExcludes=t.facetsExcludes||{},this.disjunctiveFacetsRefinements=t.disjunctiveFacetsRefinements||{},this.numericRefinements=t.numericRefinements||{},this.tagRefinements=t.tagRefinements||[],this.hierarchicalFacetsRefinements=t.hierarchicalFacetsRefinements||{},this.numericFilters=t.numericFilters,this.tagFilters=t.tagFilters,this.hitsPerPage=t.hitsPerPage,this.maxValuesPerFacet=t.maxValuesPerFacet,this.page=t.page||0,this.queryType=t.queryType,this.typoTolerance=t.typoTolerance,this.minWordSizefor1Typo=t.minWordSizefor1Typo,this.minWordSizefor2Typos=t.minWordSizefor2Typos,this.allowTyposOnNumericTokens=t.allowTyposOnNumericTokens,this.ignorePlurals=t.ignorePlurals,this.restrictSearchableAttributes=t.restrictSearchableAttributes,this.advancedSyntax=t.advancedSyntax,this.analytics=t.analytics,this.analyticsTags=t.analyticsTags,this.synonyms=t.synonyms,this.replaceSynonymsInHighlight=t.replaceSynonymsInHighlight,this.optionalWords=t.optionalWords,this.removeWordsIfNoResults=t.removeWordsIfNoResults,this.attributesToRetrieve=t.attributesToRetrieve,this.attributesToHighlight=t.attributesToHighlight,this.highlightPreTag=t.highlightPreTag,this.highlightPostTag=t.highlightPostTag,this.attributesToSnippet=t.attributesToSnippet,this.getRankingInfo=t.getRankingInfo,this.distinct=t.distinct,this.aroundLatLng=t.aroundLatLng,this.aroundLatLngViaIP=t.aroundLatLngViaIP,this.aroundRadius=t.aroundRadius,this.minimumAroundRadius=t.minimumAroundRadius,this.aroundPrecision=t.aroundPrecision,this.insideBoundingBox=t.insideBoundingBox,this.insidePolygon=t.insidePolygon,this.offset=t.offset,this.length=t.length,a(t,function(e,t){this.hasOwnProperty(t)||window.console&&window.console.error("Unsupported SearchParameter: `"+t+"` (this will throw in the next version)")},this)}var o=n(25),i=n(75),a=n(82),s=n(17),u=n(84),c=n(108),l=n(111),p=n(115),f=n(121),h=n(36),d=n(124),v=n(126),m=n(125),g=n(127),y=n(28),b=n(128),x=n(132),w=n(133),_=n(53),P=n(138),C=n(139),E=n(140); r.PARAMETERS=o(new r),r._parseNumbers=function(e){var t={},n=["aroundPrecision","aroundRadius","getRankingInfo","minWordSizefor2Typos","minWordSizefor1Typo","page","maxValuesPerFacet"];if(s(n,function(n){var r=e[n];m(r)&&(t[n]=parseFloat(e[n]))}),e.numericRefinements){var r={};s(e.numericRefinements,function(e,t){r[t]={},s(e,function(e,n){var o=c(e,function(e){return h(e)?c(e,function(e){return m(e)?parseFloat(e):e}):m(e)?parseFloat(e):e});r[t][n]=o})}),t.numericRefinements=r}return _({},e,t)},r.make=function(e){var t=new r(e);return P(t)},r.validate=function(e,t){var n=t||{},r=o(n),i=u(r,function(t){return!e.hasOwnProperty(t)});return 1===i.length?new Error("Property "+i[0]+" is not defined on SearchParameters (see http://algolia.github.io/algoliasearch-helper-js/docs/SearchParameters.html)"):i.length>1?new Error("Properties "+i.join(" ")+" are not defined on SearchParameters (see http://algolia.github.io/algoliasearch-helper-js/docs/SearchParameters.html)"):e.tagFilters&&n.tagRefinements&&n.tagRefinements.length>0?new Error("[Tags] Cannot switch from the managed tag API to the advanced API. It is probably an error, if it is really what you want, you should first clear the tags with clearTags method."):e.tagRefinements.length>0&&n.tagFilters?new Error("[Tags] Cannot switch from the advanced tag API to the managed API. It is probably an error, if it is not, you should first clear the tags with clearTags method."):e.numericFilters&&n.numericRefinements&&!d(n.numericRefinements)?new Error("[Numeric filters] Can't switch from the advanced to the managed API. It is probably an error, if this is really what you want, you have to first clear the numeric filters."):!d(e.numericRefinements)&&n.numericFilters?new Error("[Numeric filters] Can't switch from the managed API to the advanced. It is probably an error, if this is really what you want, you have to first clear the numeric filters."):null},r.prototype={constructor:r,clearRefinements:function(e){var t=E.clearRefinement;return this.setQueryParameters({page:0,numericRefinements:this._clearNumericRefinements(e),facetsRefinements:t(this.facetsRefinements,e,"conjunctiveFacet"),facetsExcludes:t(this.facetsExcludes,e,"exclude"),disjunctiveFacetsRefinements:t(this.disjunctiveFacetsRefinements,e,"disjunctiveFacet"),hierarchicalFacetsRefinements:t(this.hierarchicalFacetsRefinements,e,"hierarchicalFacet")})},clearTags:function(){return void 0===this.tagFilters&&0===this.tagRefinements.length?this:this.setQueryParameters({page:0,tagFilters:void 0,tagRefinements:[]})},setIndex:function(e){return e===this.index?this:this.setQueryParameters({index:e,page:0})},setQuery:function(e){return e===this.query?this:this.setQueryParameters({query:e,page:0})},setPage:function(e){return e===this.page?this:this.setQueryParameters({page:e})},setFacets:function(e){return this.setQueryParameters({facets:e})},setDisjunctiveFacets:function(e){return this.setQueryParameters({disjunctiveFacets:e})},setHitsPerPage:function(e){return this.hitsPerPage===e?this:this.setQueryParameters({hitsPerPage:e,page:0})},setTypoTolerance:function(e){return this.typoTolerance===e?this:this.setQueryParameters({typoTolerance:e,page:0})},addNumericRefinement:function(e,t,n){var r;if(g(n))r=n;else if(m(n))r=parseFloat(n);else{if(!h(n))throw new Error("The value should be a number, a parseable string or an array of those.");r=c(n,function(e){return m(e)?parseFloat(e):e})}if(this.isNumericRefined(e,t,r))return this;var o=_({},this.numericRefinements);return o[e]=_({},o[e]),o[e][t]?(o[e][t]=o[e][t].slice(),o[e][t].push(r)):o[e][t]=[r],this.setQueryParameters({page:0,numericRefinements:o})},getConjunctiveRefinements:function(e){if(!this.isConjunctiveFacet(e))throw new Error(e+" is not defined in the facets attribute of the helper configuration");return this.facetsRefinements[e]||[]},getDisjunctiveRefinements:function(e){if(!this.isDisjunctiveFacet(e))throw new Error(e+" is not defined in the disjunctiveFacets attribute of the helper configuration");return this.disjunctiveFacetsRefinements[e]||[]},getHierarchicalRefinement:function(e){return this.hierarchicalFacetsRefinements[e]||[]},getExcludeRefinements:function(e){if(!this.isConjunctiveFacet(e))throw new Error(e+" is not defined in the facets attribute of the helper configuration");return this.facetsExcludes[e]||[]},removeNumericRefinement:function(e,t,n){return void 0!==n?this.isNumericRefined(e,t,n)?this.setQueryParameters({page:0,numericRefinements:this._clearNumericRefinements(function(r,o){return o===e&&r.op===t&&r.val===n})}):this:void 0!==t?this.isNumericRefined(e,t)?this.setQueryParameters({page:0,numericRefinements:this._clearNumericRefinements(function(n,r){return r===e&&n.op===t})}):this:this.isNumericRefined(e)?this.setQueryParameters({page:0,numericRefinements:this._clearNumericRefinements(function(t,n){return n===e})}):this},getNumericRefinements:function(e){return this.numericRefinements[e]||{}},getNumericRefinement:function(e,t){return this.numericRefinements[e]&&this.numericRefinements[e][t]},_clearNumericRefinements:function(e){return v(e)?{}:m(e)?p(this.numericRefinements,e):y(e)?l(this.numericRefinements,function(t,n,r){var o={};return s(n,function(t,n){var i=[];s(t,function(t){var o=e({val:t,op:n},r,"numeric");o||i.push(t)}),d(i)||(o[n]=i)}),d(o)||(t[r]=o),t},{}):void 0},addFacetRefinement:function(e,t){if(!this.isConjunctiveFacet(e))throw new Error(e+" is not defined in the facets attribute of the helper configuration");return E.isRefined(this.facetsRefinements,e,t)?this:this.setQueryParameters({page:0,facetsRefinements:E.addRefinement(this.facetsRefinements,e,t)})},addExcludeRefinement:function(e,t){if(!this.isConjunctiveFacet(e))throw new Error(e+" is not defined in the facets attribute of the helper configuration");return E.isRefined(this.facetsExcludes,e,t)?this:this.setQueryParameters({page:0,facetsExcludes:E.addRefinement(this.facetsExcludes,e,t)})},addDisjunctiveFacetRefinement:function(e,t){if(!this.isDisjunctiveFacet(e))throw new Error(e+" is not defined in the disjunctiveFacets attribute of the helper configuration");return E.isRefined(this.disjunctiveFacetsRefinements,e,t)?this:this.setQueryParameters({page:0,disjunctiveFacetsRefinements:E.addRefinement(this.disjunctiveFacetsRefinements,e,t)})},addTagRefinement:function(e){if(this.isTagRefined(e))return this;var t={page:0,tagRefinements:this.tagRefinements.concat(e)};return this.setQueryParameters(t)},removeFacetRefinement:function(e,t){if(!this.isConjunctiveFacet(e))throw new Error(e+" is not defined in the facets attribute of the helper configuration");return E.isRefined(this.facetsRefinements,e,t)?this.setQueryParameters({page:0,facetsRefinements:E.removeRefinement(this.facetsRefinements,e,t)}):this},removeExcludeRefinement:function(e,t){if(!this.isConjunctiveFacet(e))throw new Error(e+" is not defined in the facets attribute of the helper configuration");return E.isRefined(this.facetsExcludes,e,t)?this.setQueryParameters({page:0,facetsExcludes:E.removeRefinement(this.facetsExcludes,e,t)}):this},removeDisjunctiveFacetRefinement:function(e,t){if(!this.isDisjunctiveFacet(e))throw new Error(e+" is not defined in the disjunctiveFacets attribute of the helper configuration");return E.isRefined(this.disjunctiveFacetsRefinements,e,t)?this.setQueryParameters({page:0,disjunctiveFacetsRefinements:E.removeRefinement(this.disjunctiveFacetsRefinements,e,t)}):this},removeTagRefinement:function(e){if(!this.isTagRefined(e))return this;var t={page:0,tagRefinements:u(this.tagRefinements,function(t){return t!==e})};return this.setQueryParameters(t)},toggleRefinement:function(e,t){if(this.isHierarchicalFacet(e))return this.toggleHierarchicalFacetRefinement(e,t);if(this.isConjunctiveFacet(e))return this.toggleFacetRefinement(e,t);if(this.isDisjunctiveFacet(e))return this.toggleDisjunctiveFacetRefinement(e,t);throw new Error("Cannot refine the undeclared facet "+e+"; it should be added to the helper options facets, disjunctiveFacets or hierarchicalFacets")},toggleFacetRefinement:function(e,t){if(!this.isConjunctiveFacet(e))throw new Error(e+" is not defined in the facets attribute of the helper configuration");return this.setQueryParameters({page:0,facetsRefinements:E.toggleRefinement(this.facetsRefinements,e,t)})},toggleExcludeFacetRefinement:function(e,t){if(!this.isConjunctiveFacet(e))throw new Error(e+" is not defined in the facets attribute of the helper configuration");return this.setQueryParameters({page:0,facetsExcludes:E.toggleRefinement(this.facetsExcludes,e,t)})},toggleDisjunctiveFacetRefinement:function(e,t){if(!this.isDisjunctiveFacet(e))throw new Error(e+" is not defined in the disjunctiveFacets attribute of the helper configuration");return this.setQueryParameters({page:0,disjunctiveFacetsRefinements:E.toggleRefinement(this.disjunctiveFacetsRefinements,e,t)})},toggleHierarchicalFacetRefinement:function(e,t){if(!this.isHierarchicalFacet(e))throw new Error(e+" is not defined in the hierarchicalFacets attribute of the helper configuration");var n=this._getHierarchicalFacetSeparator(this.getHierarchicalFacetByName(e)),r={},o=void 0!==this.hierarchicalFacetsRefinements[e]&&this.hierarchicalFacetsRefinements[e].length>0&&(this.hierarchicalFacetsRefinements[e][0]===t||0===this.hierarchicalFacetsRefinements[e][0].indexOf(t+n));return r[e]=o?-1===t.indexOf(n)?[]:[t.slice(0,t.lastIndexOf(n))]:[t],this.setQueryParameters({hierarchicalFacetsRefinements:w({},r,this.hierarchicalFacetsRefinements)})},toggleTagRefinement:function(e){return this.isTagRefined(e)?this.removeTagRefinement(e):this.addTagRefinement(e)},isDisjunctiveFacet:function(e){return f(this.disjunctiveFacets,e)>-1},isHierarchicalFacet:function(e){return void 0!==this.getHierarchicalFacetByName(e)},isConjunctiveFacet:function(e){return f(this.facets,e)>-1},isFacetRefined:function(e,t){if(!this.isConjunctiveFacet(e))throw new Error(e+" is not defined in the facets attribute of the helper configuration");return E.isRefined(this.facetsRefinements,e,t)},isExcludeRefined:function(e,t){if(!this.isConjunctiveFacet(e))throw new Error(e+" is not defined in the facets attribute of the helper configuration");return E.isRefined(this.facetsExcludes,e,t)},isDisjunctiveFacetRefined:function(e,t){if(!this.isDisjunctiveFacet(e))throw new Error(e+" is not defined in the disjunctiveFacets attribute of the helper configuration");return E.isRefined(this.disjunctiveFacetsRefinements,e,t)},isHierarchicalFacetRefined:function(e,t){if(!this.isHierarchicalFacet(e))throw new Error(e+" is not defined in the hierarchicalFacets attribute of the helper configuration");var n=this.getHierarchicalRefinement(e);return t?-1!==f(n,t):n.length>0},isNumericRefined:function(e,t,n){if(v(n)&&v(t))return!!this.numericRefinements[e];if(v(n))return this.numericRefinements[e]&&!v(this.numericRefinements[e][t]);var r=parseFloat(n);return this.numericRefinements[e]&&!v(this.numericRefinements[e][t])&&-1!==f(this.numericRefinements[e][t],r)},isTagRefined:function(e){return-1!==f(this.tagRefinements,e)},getRefinedDisjunctiveFacets:function(){var e=i(o(this.numericRefinements),this.disjunctiveFacets);return o(this.disjunctiveFacetsRefinements).concat(e).concat(this.getRefinedHierarchicalFacets())},getRefinedHierarchicalFacets:function(){return i(x(this.hierarchicalFacets,"name"),o(this.hierarchicalFacetsRefinements))},getUnrefinedDisjunctiveFacets:function(){var e=this.getRefinedDisjunctiveFacets();return u(this.disjunctiveFacets,function(t){return-1===f(e,t)})},managedParameters:["index","facets","disjunctiveFacets","facetsRefinements","facetsExcludes","disjunctiveFacetsRefinements","numericRefinements","tagRefinements","hierarchicalFacets","hierarchicalFacetsRefinements"],getQueryParams:function(){var e=this.managedParameters,t={};return a(this,function(n,r){-1===f(e,r)&&void 0!==n&&(t[r]=n)}),t},getQueryParameter:function(e){if(!this.hasOwnProperty(e))throw new Error("Parameter '"+e+"' is not an attribute of SearchParameters (http://algolia.github.io/algoliasearch-helper-js/docs/SearchParameters.html)");return this[e]},setQueryParameter:function(e,t){if(this[e]===t)return this;var n={};return n[e]=t,this.setQueryParameters(n)},setQueryParameters:function(e){var t=r.validate(this,e);if(t)throw t;return this.mutateMe(function(t){var n=o(e);return s(n,function(n){t[n]=e[n]}),t})},filter:function(e){return C(this,e)},mutateMe:function(e){var t=new this.constructor(this);return e(t,this),P(t)},_getHierarchicalFacetSortBy:function(e){return e.sortBy||["isRefined:desc","name:asc"]},_getHierarchicalFacetSeparator:function(e){return e.separator||" > "},getHierarchicalFacetByName:function(e){return b(this.hierarchicalFacets,{name:e})}},e.exports=r},function(e,t,n){var r=n(76),o=n(78),i=n(79),a=n(30),s=n(61),u=s(function(e){for(var t=e.length,n=t,s=Array(d),u=r,c=!0,l=[];n--;){var p=e[n]=a(p=e[n])?p:[];s[n]=c&&p.length>=120?i(n&&p):null}var f=e[0],h=-1,d=f?f.length:0,v=s[0];e:for(;++h<d;)if(p=f[h],(v?o(v,p):u(l,p,0))<0){for(var n=t;--n;){var m=s[n];if((m?o(m,p):u(e[n],p,0))<0)continue e}v&&v.push(p),l.push(p)}return l});e.exports=u},function(e,t,n){function r(e,t,n){if(t!==t)return o(e,n);for(var r=n-1,i=e.length;++r<i;)if(e[r]===t)return r;return-1}var o=n(77);e.exports=r},function(e){function t(e,t,n){for(var r=e.length,o=t+(n?0:-1);n?o--:++o<r;){var i=e[o];if(i!==i)return o}return-1}e.exports=t},function(e,t,n){function r(e,t){var n=e.data,r="string"==typeof t||o(t)?n.set.has(t):n.hash[t];return r?0:-1}var o=n(24);e.exports=r},function(e,t,n){(function(t){function r(e){return s&&a?new o(e):null}var o=n(80),i=n(26),a=i(t,"Set"),s=i(Object,"create");e.exports=r}).call(t,function(){return this}())},function(e,t,n){(function(t){function r(e){var t=e?e.length:0;for(this.data={hash:s(null),set:new a};t--;)this.push(e[t])}var o=n(81),i=n(26),a=i(t,"Set"),s=i(Object,"create");r.prototype.push=o,e.exports=r}).call(t,function(){return this}())},function(e,t,n){function r(e){var t=this.data;"string"==typeof e||o(e)?t.set.add(e):t.hash[e]=!0}var o=n(24);e.exports=r},function(e,t,n){var r=n(20),o=n(83),i=o(r);e.exports=i},function(e,t,n){function r(e){return function(t,n,r){return("function"!=typeof n||void 0!==r)&&(n=o(n,r,3)),e(t,n)}}var o=n(41);e.exports=r},function(e,t,n){function r(e,t,n){var r=s(e)?o:a;return t=i(t,n,3),r(e,t)}var o=n(85),i=n(86),a=n(107),s=n(36);e.exports=r},function(e){function t(e,t){for(var n=-1,r=e.length,o=-1,i=[];++n<r;){var a=e[n];t(a,n,e)&&(i[++o]=a)}return i}e.exports=t},function(e,t,n){function r(e,t,n){var r=typeof e;return"function"==r?void 0===t?e:a(e,t,n):null==e?s:"object"==r?o(e):void 0===t?u(e):i(e,t)}var o=n(87),i=n(98),a=n(41),s=n(42),u=n(105);e.exports=r},function(e,t,n){function r(e){var t=i(e);if(1==t.length&&t[0][2]){var n=t[0][0],r=t[0][1];return function(e){return null==e?!1:e[n]===r&&(void 0!==r||n in a(e))}}return function(e){return o(e,t)}}var o=n(88),i=n(95),a=n(23);e.exports=r},function(e,t,n){function r(e,t,n){var r=t.length,a=r,s=!n;if(null==e)return!a;for(e=i(e);r--;){var u=t[r];if(s&&u[2]?u[1]!==e[u[0]]:!(u[0]in e))return!1}for(;++r<a;){u=t[r];var c=u[0],l=e[c],p=u[1];if(s&&u[2]){if(void 0===l&&!(c in e))return!1}else{var f=n?n(l,p,c):void 0;if(!(void 0===f?o(p,l,n,!0):f))return!1}}return!0}var o=n(89),i=n(23);e.exports=r},function(e,t,n){function r(e,t,n,s,u,c){return e===t?!0:null==e||null==t||!i(e)&&!a(t)?e!==e&&t!==t:o(e,t,r,n,s,u,c)}var o=n(90),i=n(24),a=n(29);e.exports=r},function(e,t,n){function r(e,t,n,r,f,v,m){var g=s(e),y=s(t),b=l,x=l;g||(b=d.call(e),b==c?b=p:b!=p&&(g=u(e))),y||(x=d.call(t),x==c?x=p:x!=p&&(y=u(t)));var w=b==p,_=x==p,P=b==x;if(P&&!g&&!w)return i(e,t,b);if(!f){var C=w&&h.call(e,"__wrapped__"),E=_&&h.call(t,"__wrapped__");if(C||E)return n(C?e.value():e,E?t.value():t,r,f,v,m)}if(!P)return!1;v||(v=[]),m||(m=[]);for(var R=v.length;R--;)if(v[R]==e)return m[R]==t;v.push(e),m.push(t);var T=(g?o:a)(e,t,n,r,f,v,m);return v.pop(),m.pop(),T}var o=n(91),i=n(93),a=n(94),s=n(36),u=n(58),c="[object Arguments]",l="[object Array]",p="[object Object]",f=Object.prototype,h=f.hasOwnProperty,d=f.toString;e.exports=r},function(e,t,n){function r(e,t,n,r,i,a,s){var u=-1,c=e.length,l=t.length;if(c!=l&&!(i&&l>c))return!1;for(;++u<c;){var p=e[u],f=t[u],h=r?r(i?f:p,i?p:f,u):void 0;if(void 0!==h){if(h)continue;return!1}if(i){if(!o(t,function(e){return p===e||n(p,e,r,i,a,s)}))return!1}else if(p!==f&&!n(p,f,r,i,a,s))return!1}return!0}var o=n(92);e.exports=r},function(e){function t(e,t){for(var n=-1,r=e.length;++n<r;)if(t(e[n],n,e))return!0;return!1}e.exports=t},function(e){function t(e,t,u){switch(u){case n:case r:return+e==+t;case o:return e.name==t.name&&e.message==t.message;case i:return e!=+e?t!=+t:e==+t;case a:case s:return e==t+""}return!1}var n="[object Boolean]",r="[object Date]",o="[object Error]",i="[object Number]",a="[object RegExp]",s="[object String]";e.exports=t},function(e,t,n){function r(e,t,n,r,i,s,u){var c=o(e),l=c.length,p=o(t),f=p.length;if(l!=f&&!i)return!1;for(var h=l;h--;){var d=c[h];if(!(i?d in t:a.call(t,d)))return!1}for(var v=i;++h<l;){d=c[h];var m=e[d],g=t[d],y=r?r(i?g:m,i?m:g,d):void 0;if(!(void 0===y?n(m,g,r,i,s,u):y))return!1;v||(v="constructor"==d)}if(!v){var b=e.constructor,x=t.constructor;if(b!=x&&"constructor"in e&&"constructor"in t&&!("function"==typeof b&&b instanceof b&&"function"==typeof x&&x instanceof x))return!1}return!0}var o=n(25),i=Object.prototype,a=i.hasOwnProperty;e.exports=r},function(e,t,n){function r(e){for(var t=i(e),n=t.length;n--;)t[n][2]=o(t[n][1]);return t}var o=n(96),i=n(97);e.exports=r},function(e,t,n){function r(e){return e===e&&!o(e)}var o=n(24);e.exports=r},function(e,t,n){function r(e){e=i(e);for(var t=-1,n=o(e),r=n.length,a=Array(r);++t<r;){var s=n[t];a[t]=[s,e[s]]}return a}var o=n(25),i=n(23);e.exports=r},function(e,t,n){function r(e,t){var n=s(e),r=u(e)&&c(t),h=e+"";return e=f(e),function(s){if(null==s)return!1;var u=h;if(s=p(s),!(!n&&r||u in s)){if(s=1==e.length?s:o(s,a(e,0,-1)),null==s)return!1;u=l(e),s=p(s)}return s[u]===t?void 0!==t||u in s:i(t,s[u],void 0,!0)}}var o=n(99),i=n(89),a=n(100),s=n(36),u=n(101),c=n(96),l=n(102),p=n(23),f=n(103);e.exports=r},function(e,t,n){function r(e,t,n){if(null!=e){void 0!==n&&n in o(e)&&(t=[n]);for(var r=0,i=t.length;null!=e&&i>r;)e=e[t[r++]];return r&&r==i?e:void 0}}var o=n(23);e.exports=r},function(e){function t(e,t,n){var r=-1,o=e.length;t=null==t?0:+t||0,0>t&&(t=-t>o?0:o+t),n=void 0===n||n>o?o:+n||0,0>n&&(n+=o),o=t>n?0:n-t>>>0,t>>>=0;for(var i=Array(o);++r<o;)i[r]=e[r+t];return i}e.exports=t},function(e,t,n){function r(e,t){var n=typeof e;if("string"==n&&s.test(e)||"number"==n)return!0;if(o(e))return!1;var r=!a.test(e);return r||null!=t&&e in i(t)}var o=n(36),i=n(23),a=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\n\\]|\\.)*?\1)\]/,s=/^\w*$/;e.exports=r},function(e){function t(e){var t=e?e.length:0;return t?e[t-1]:void 0}e.exports=t},function(e,t,n){function r(e){if(i(e))return e;var t=[];return o(e).replace(a,function(e,n,r,o){t.push(r?o.replace(s,"$1"):n||e)}),t}var o=n(104),i=n(36),a=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\n\\]|\\.)*?)\2)\]/g,s=/\\(\\)?/g;e.exports=r},function(e){function t(e){return null==e?"":e+""}e.exports=t},function(e,t,n){function r(e){return a(e)?o(e):i(e)}var o=n(32),i=n(106),a=n(101);e.exports=r},function(e,t,n){function r(e){var t=e+"";return e=i(e),function(n){return o(n,e,t)}}var o=n(99),i=n(103);e.exports=r},function(e,t,n){function r(e,t){var n=[];return o(e,function(e,r,o){t(e,r,o)&&n.push(e)}),n}var o=n(19);e.exports=r},function(e,t,n){function r(e,t,n){var r=s(e)?o:a;return t=i(t,n,3),r(e,t)}var o=n(109),i=n(86),a=n(110),s=n(36);e.exports=r},function(e){function t(e,t){for(var n=-1,r=e.length,o=Array(r);++n<r;)o[n]=t(e[n],n,e);return o}e.exports=t},function(e,t,n){function r(e,t){var n=-1,r=i(e)?Array(e.length):[];return o(e,function(e,o,i){r[++n]=t(e,o,i)}),r}var o=n(19),i=n(30);e.exports=r},function(e,t,n){var r=n(112),o=n(19),i=n(113),a=i(r,o);e.exports=a},function(e){function t(e,t,n,r){var o=-1,i=e.length;for(r&&i&&(n=e[++o]);++o<i;)n=t(n,e[o],o,e);return n}e.exports=t},function(e,t,n){function r(e,t){return function(n,r,s,u){var c=arguments.length<3;return"function"==typeof r&&void 0===u&&a(n)?e(n,r,s,c):i(n,o(r,u,4),s,c,t)}}var o=n(86),i=n(114),a=n(36);e.exports=r},function(e){function t(e,t,n,r,o){return o(e,function(e,o,i){n=r?(r=!1,e):t(n,e,o,i)}),n}e.exports=t},function(e,t,n){var r=n(109),o=n(116),i=n(117),a=n(41),s=n(38),u=n(119),c=n(120),l=n(61),p=l(function(e,t){if(null==e)return{};if("function"!=typeof t[0]){var t=r(i(t),String);return u(e,o(s(e),t))}var n=a(t[0],t[1],3);return c(e,function(e,t,r){return!n(e,t,r)})});e.exports=p},function(e,t,n){function r(e,t){var n=e?e.length:0,r=[];if(!n)return r;var u=-1,c=o,l=!0,p=l&&t.length>=s?a(t):null,f=t.length;p&&(c=i,l=!1,t=p);e:for(;++u<n;){var h=e[u];if(l&&h===h){for(var d=f;d--;)if(t[d]===h)continue e;r.push(h)}else c(t,h,0)<0&&r.push(h)}return r}var o=n(76),i=n(78),a=n(79),s=200;e.exports=r},function(e,t,n){function r(e,t,n,c){c||(c=[]);for(var l=-1,p=e.length;++l<p;){var f=e[l];u(f)&&s(f)&&(n||a(f)||i(f))?t?r(f,t,n,c):o(c,f):n||(c[c.length]=f)}return c}var o=n(118),i=n(35),a=n(36),s=n(30),u=n(29);e.exports=r},function(e){function t(e,t){for(var n=-1,r=t.length,o=e.length;++n<r;)e[o+n]=t[n];return e}e.exports=t},function(e,t,n){function r(e,t){e=o(e);for(var n=-1,r=t.length,i={};++n<r;){var a=t[n];a in e&&(i[a]=e[a])}return i}var o=n(23);e.exports=r},function(e,t,n){function r(e,t){var n={};return o(e,function(e,r,o){t(e,r,o)&&(n[r]=e)}),n}var o=n(57);e.exports=r},function(e,t,n){function r(e,t,n){var r=e?e.length:0;if(!r)return-1;if("number"==typeof n)n=0>n?a(r+n,0):n;else if(n){var s=i(e,t);return r>s&&(t===t?t===e[s]:e[s]!==e[s])?s:-1}return o(e,t,n||0)}var o=n(76),i=n(122),a=Math.max;e.exports=r},function(e,t,n){function r(e,t,n){var r=0,a=e?e.length:r;if("number"==typeof t&&t===t&&s>=a){for(;a>r;){var u=r+a>>>1,c=e[u];(n?t>=c:t>c)&&null!==c?r=u+1:a=u}return a}return o(e,t,i,n)}var o=n(123),i=n(42),a=4294967295,s=a>>>1;e.exports=r},function(e){function t(e,t,o,a){t=o(t);for(var s=0,u=e?e.length:0,c=t!==t,l=null===t,p=void 0===t;u>s;){var f=n((s+u)/2),h=o(e[f]),d=void 0!==h,v=h===h;if(c)var m=v||a;else m=l?v&&d&&(a||null!=h):p?v&&(a||d):null==h?!1:a?t>=h:t>h;m?s=f+1:u=f}return r(u,i)}var n=Math.floor,r=Math.min,o=4294967295,i=o-1;e.exports=t},function(e,t,n){function r(e){return null==e?!0:a(e)&&(i(e)||c(e)||o(e)||u(e)&&s(e.splice))?!e.length:!l(e).length}var o=n(35),i=n(36),a=n(30),s=n(28),u=n(29),c=n(125),l=n(25);e.exports=r},function(e,t,n){function r(e){return"string"==typeof e||o(e)&&s.call(e)==i}var o=n(29),i="[object String]",a=Object.prototype,s=a.toString;e.exports=r},function(e){function t(e){return void 0===e}e.exports=t},function(e,t,n){function r(e){return"number"==typeof e||o(e)&&s.call(e)==i}var o=n(29),i="[object Number]",a=Object.prototype,s=a.toString;e.exports=r},function(e,t,n){var r=n(19),o=n(129),i=o(r);e.exports=i},function(e,t,n){function r(e,t){return function(n,r,u){if(r=o(r,u,3),s(n)){var c=a(n,r,t);return c>-1?n[c]:void 0}return i(n,r,e)}}var o=n(86),i=n(130),a=n(131),s=n(36);e.exports=r},function(e){function t(e,t,n,r){var o;return n(e,function(e,n,i){return t(e,n,i)?(o=r?n:e,!1):void 0}),o}e.exports=t},function(e){function t(e,t,n){for(var r=e.length,o=n?r:-1;n?o--:++o<r;)if(t(e[o],o,e))return o;return-1}e.exports=t},function(e,t,n){function r(e,t){return o(e,i(t))}var o=n(108),i=n(105);e.exports=r},function(e,t,n){var r=n(134),o=n(136),i=n(137),a=i(r,o);e.exports=a},function(e,t,n){var r=n(135),o=n(46),i=n(60),a=i(function(e,t,n){return n?r(e,t,n):o(e,t)});e.exports=a},function(e,t,n){function r(e,t,n){for(var r=-1,i=o(t),a=i.length;++r<a;){var s=i[r],u=e[s],c=n(u,t[s],s,e,t);(c===c?c===u:u!==u)&&(void 0!==u||s in e)||(e[s]=c)}return e}var o=n(25);e.exports=r},function(e){function t(e,t){return void 0===e?t:e}e.exports=t},function(e,t,n){function r(e,t){return o(function(n){var r=n[0];return null==r?r:(n.push(t),e.apply(void 0,n))})}var o=n(61);e.exports=r},function(e,t,n){"use strict";var r=n(17),o=n(42),i=n(24),a=function(e){return i(e)?(r(e,a),Object.isFrozen(e)||Object.freeze(e),e):e};e.exports=Object.freeze?a:o},function(e,t,n){"use strict";function r(e,t){var n={},r=i(t,function(e){return-1!==e.indexOf("attribute:")}),c=a(r,function(e){return e.split(":")[1]});-1===u(c,"*")?o(c,function(t){e.isConjunctiveFacet(t)&&e.isFacetRefined(t)&&(n.facetsRefinements||(n.facetsRefinements={}),n.facetsRefinements[t]=e.facetsRefinements[t]),e.isDisjunctiveFacet(t)&&e.isDisjunctiveFacetRefined(t)&&(n.disjunctiveFacetsRefinements||(n.disjunctiveFacetsRefinements={}),n.disjunctiveFacetsRefinements[t]=e.disjunctiveFacetsRefinements[t]);var r=e.getNumericRefinements(t);s(r)||(n.numericRefinements||(n.numericRefinements={}),n.numericRefinements[t]=e.numericRefinements[t])}):(s(e.numericRefinements)||(n.numericRefinements=e.numericRefinements),s(e.facetsRefinements)||(n.facetsRefinements=e.facetsRefinements),s(e.disjunctiveFacetsRefinements)||(n.disjunctiveFacetsRefinements=e.disjunctiveFacetsRefinements),s(e.hierarchicalFacetsRefinements)||(n.hierarchicalFacetsRefinements=e.hierarchicalFacetsRefinements));var l=i(t,function(e){return-1===e.indexOf("attribute:")});return o(l,function(t){n[t]=e[t]}),n}var o=n(17),i=n(84),a=n(108),s=n(124),u=n(121);e.exports=r},function(e,t,n){"use strict";var r=n(126),o=n(125),i=n(28),a=n(124),s=n(133),u=n(111),c=n(84),l=n(115),p={addRefinement:function(e,t,n){if(p.isRefined(e,t,n))return e;var r=""+n,o=e[t]?e[t].concat(r):[r],i={};return i[t]=o,s({},i,e)},removeRefinement:function(e,t,n){if(r(n))return p.clearRefinement(e,t);var o=""+n;return p.clearRefinement(e,function(e,n){return t===n&&o===e})},toggleRefinement:function(e,t,n){if(r(n))throw new Error("toggleRefinement should be used with a value");return p.isRefined(e,t,n)?p.removeRefinement(e,t,n):p.addRefinement(e,t,n)},clearRefinement:function(e,t,n){return r(t)?{}:o(t)?l(e,t):i(t)?u(e,function(e,r,o){var i=c(r,function(e){return!t(e,o,n)});return a(i)||(e[o]=i),e},{}):void 0},isRefined:function(e,t,o){var i=n(121),a=!!e[t]&&e[t].length>0;if(r(o)||!a)return a;var s=""+o;return-1!==i(e[t],s)}};e.exports=p},function(e,t,n){"use strict";function r(e){var t={};return p(e,function(e,n){t[e]=n}),t}function o(e,t,n){t&&t[n]&&(e.stats=t[n])}function i(e,t){return m(e,function(e){return g(e.attributes,t)})}function a(e,t){var n=t.results[0];this.query=n.query,this.hits=n.hits,this.index=n.index,this.hitsPerPage=n.hitsPerPage,this.nbHits=n.nbHits,this.nbPages=n.nbPages,this.page=n.page,this.processingTimeMS=v(t.results,"processingTimeMS"),this.disjunctiveFacets=[],this.hierarchicalFacets=y(e.hierarchicalFacets,function(){return[]}),this.facets=[];var a=e.getRefinedDisjunctiveFacets(),s=r(e.facets),u=r(e.disjunctiveFacets),c=1;p(n.facets,function(t,r){var a=i(e.hierarchicalFacets,r);if(a)this.hierarchicalFacets[d(e.hierarchicalFacets,{name:a.name})].push({attribute:r,data:t,exhaustive:n.exhaustiveFacetsCount});else{var c,l=-1!==h(e.disjunctiveFacets,r),p=-1!==h(e.facets,r);l&&(c=u[r],this.disjunctiveFacets[c]={name:r,data:t,exhaustive:n.exhaustiveFacetsCount},o(this.disjunctiveFacets[c],n.facets_stats,r)),p&&(c=s[r],this.facets[c]={name:r,data:t,exhaustive:n.exhaustiveFacetsCount},o(this.facets[c],n.facets_stats,r))}},this),p(a,function(r){var i=t.results[c],a=e.getHierarchicalFacetByName(r);p(i.facets,function(t,r){var s;if(a){s=d(e.hierarchicalFacets,{name:a.name});var c=d(this.hierarchicalFacets[s],{attribute:r});this.hierarchicalFacets[s][c].data=w({},this.hierarchicalFacets[s][c].data,t)}else{s=u[r];var l=n.facets&&n.facets[r]||{};this.disjunctiveFacets[s]={name:r,data:x({},t,l),exhaustive:i.exhaustiveFacetsCount},o(this.disjunctiveFacets[s],i.facets_stats,r),e.disjunctiveFacetsRefinements[r]&&p(e.disjunctiveFacetsRefinements[r],function(t){!this.disjunctiveFacets[s].data[t]&&h(e.disjunctiveFacetsRefinements[r],t)>-1&&(this.disjunctiveFacets[s].data[t]=0)},this)}},this),c++},this),p(e.getRefinedHierarchicalFacets(),function(n){var r=e.getHierarchicalFacetByName(n),o=e.getHierarchicalRefinement(n);if(!(0===o.length||o[0].split(e._getHierarchicalFacetSeparator(r)).length<2)){var i=t.results[c];p(i.facets,function(t,n){var i=d(e.hierarchicalFacets,{name:r.name}),a=d(this.hierarchicalFacets[i],{attribute:n}),s={};if(o.length>0){var u=o[0].split(e._getHierarchicalFacetSeparator(r))[0];s[u]=this.hierarchicalFacets[i][a].data[u]}this.hierarchicalFacets[i][a].data=x(s,t,this.hierarchicalFacets[i][a].data)},this),c++}},this),p(e.facetsExcludes,function(e,t){var r=s[t];this.facets[r]={name:t,data:n.facets[t],exhaustive:n.exhaustiveFacetsCount},p(e,function(e){this.facets[r]=this.facets[r]||{name:t},this.facets[r].data=this.facets[r].data||{},this.facets[r].data[e]=0},this)},this),this.hierarchicalFacets=y(this.hierarchicalFacets,T(e)),this.facets=f(this.facets),this.disjunctiveFacets=f(this.disjunctiveFacets),this._state=e}function s(e,t){var n={name:t};if(e._state.isConjunctiveFacet(t)){var r=m(e.facets,n);return r?y(r.data,function(n,r){return{name:r,count:n,isRefined:e._state.isFacetRefined(t,r)}}):[]}if(e._state.isDisjunctiveFacet(t)){var o=m(e.disjunctiveFacets,n);return o?y(o.data,function(n,r){return{name:r,count:n,isRefined:e._state.isDisjunctiveFacetRefined(t,r)}}):[]}return e._state.isHierarchicalFacet(t)?m(e.hierarchicalFacets,n):void 0}function u(e,t){if(!t.data||0===t.data.length)return t;var n=y(t.data,C(u,e)),r=e(n),o=w({},t,{data:r});return o}function c(e,t){return t.sort(e)}function l(e,t){var n=m(e,{name:t});return n&&n.stats}var p=n(17),f=n(142),h=n(121),d=n(143),v=n(145),m=n(128),g=n(152),y=n(108),b=n(153),x=n(133),w=n(53),_=n(36),P=n(28),C=n(158),E=n(185),R=n(186),T=n(187);a.prototype.getFacetByName=function(e){var t={name:e};return m(this.facets,t)||m(this.disjunctiveFacets,t)||m(this.hierarchicalFacets,t)},a.DEFAULT_SORT=["isRefined:desc","count:desc","name:asc"],a.prototype.getFacetValues=function(e,t){var n=s(this,e);if(!n)throw new Error(e+" is not a retrieved facet.");var r=x({},t,{sortBy:a.DEFAULT_SORT});if(_(r.sortBy)){var o=R(r.sortBy);return _(n)?b(n,o[0],o[1]):u(E(b,o[0],o[1]),n)}if(P(r.sortBy))return _(n)?n.sort(r.sortBy):u(C(c,r.sortBy),n);throw new Error("options.sortBy is optional but if defined it must be either an array of string (predicates) or a sorting function")},a.prototype.getFacetStats=function(e){if(this._state.isConjunctiveFacet(e))return l(this.facets,e);if(this._state.isDisjunctiveFacet(e))return l(this.disjunctiveFacets,e);throw new Error(e+" is not present in `facets` or `disjunctiveFacets`")},e.exports=a},function(e){function t(e){for(var t=-1,n=e?e.length:0,r=-1,o=[];++t<n;){var i=e[t];i&&(o[++r]=i)}return o}e.exports=t},function(e,t,n){var r=n(144),o=r();e.exports=o},function(e,t,n){function r(e){return function(t,n,r){return t&&t.length?(n=o(n,r,3),i(t,n,e)):-1}}var o=n(86),i=n(131);e.exports=r},function(e,t,n){e.exports=n(146)},function(e,t,n){function r(e,t,n){return n&&u(e,t,n)&&(t=void 0),t=i(t,n,3),1==t.length?o(s(e)?e:c(e),t):a(e,t)}var o=n(147),i=n(86),a=n(148),s=n(36),u=n(52),c=n(149);e.exports=r},function(e){function t(e,t){for(var n=e.length,r=0;n--;)r+=+t(e[n])||0;return r}e.exports=t},function(e,t,n){function r(e,t){var n=0;return o(e,function(e,r,o){n+=+t(e,r,o)||0}),n}var o=n(19);e.exports=r},function(e,t,n){function r(e){return null==e?[]:o(e)?i(e)?e:Object(e):a(e)}var o=n(30),i=n(24),a=n(150);e.exports=r},function(e,t,n){function r(e){return o(e,i(e))}var o=n(151),i=n(25);e.exports=r},function(e){function t(e,t){for(var n=-1,r=t.length,o=Array(r);++n<r;)o[n]=e[t[n]];return o}e.exports=t},function(e,t,n){function r(e,t,n,r){var f=e?i(e):0;return u(f)||(e=l(e),f=e.length),n="number"!=typeof n||r&&s(t,n,r)?0:0>n?p(f+n,0):n||0,"string"==typeof e||!a(e)&&c(e)?f>=n&&e.indexOf(t,n)>-1:!!f&&o(e,t,n)>-1}var o=n(76),i=n(31),a=n(36),s=n(52),u=n(33),c=n(125),l=n(150),p=Math.max;e.exports=r},function(e,t,n){function r(e,t,n,r){return null==e?[]:(r&&a(t,n,r)&&(n=void 0), i(t)||(t=null==t?[]:[t]),i(n)||(n=null==n?[]:[n]),o(e,t,n))}var o=n(154),i=n(36),a=n(52);e.exports=r},function(e,t,n){function r(e,t,n){var r=-1;t=o(t,function(e){return i(e)});var c=a(e,function(e){var n=o(t,function(t){return t(e)});return{criteria:n,index:++r,value:e}});return s(c,function(e,t){return u(e,t,n)})}var o=n(109),i=n(86),a=n(110),s=n(155),u=n(156);e.exports=r},function(e){function t(e,t){var n=e.length;for(e.sort(t);n--;)e[n]=e[n].value;return e}e.exports=t},function(e,t,n){function r(e,t,n){for(var r=-1,i=e.criteria,a=t.criteria,s=i.length,u=n.length;++r<s;){var c=o(i[r],a[r]);if(c){if(r>=u)return c;var l=n[r];return c*("asc"===l||l===!0?1:-1)}}return e.index-t.index}var o=n(157);e.exports=r},function(e){function t(e,t){if(e!==t){var n=null===e,r=void 0===e,o=e===e,i=null===t,a=void 0===t,s=t===t;if(e>t&&!i||!o||n&&!a&&s||r&&s)return 1;if(t>e&&!n||!s||i&&!r&&o||a&&o)return-1}return 0}e.exports=t},function(e,t,n){var r=n(159),o=32,i=r(o);i.placeholder={},e.exports=i},function(e,t,n){function r(e){var t=a(function(n,r){var a=i(r,t.placeholder);return o(n,e,void 0,r,a)});return t}var o=n(160),i=n(180),a=n(61);e.exports=r},function(e,t,n){function r(e,t,n,r,g,y,b,x){var w=t&f;if(!w&&"function"!=typeof e)throw new TypeError(v);var _=r?r.length:0;if(_||(t&=~(h|d),r=g=void 0),_-=g?g.length:0,t&d){var P=r,C=g;r=g=void 0}var E=w?void 0:u(e),R=[e,t,n,r,g,P,C,y,b,x];if(E&&(c(R,E),t=R[1],x=R[9]),R[9]=null==x?w?0:e.length:m(x-_,0)||0,t==p)var T=i(R[0],R[2]);else T=t!=h&&t!=(p|h)||R[4].length?a.apply(void 0,R):s.apply(void 0,R);var O=E?o:l;return O(T,R)}var o=n(161),i=n(163),a=n(166),s=n(183),u=n(172),c=n(184),l=n(181),p=1,f=2,h=32,d=64,v="Expected a function",m=Math.max;e.exports=r},function(e,t,n){var r=n(42),o=n(162),i=o?function(e,t){return o.set(e,t),e}:r;e.exports=i},function(e,t,n){(function(t){var r=n(26),o=r(t,"WeakMap"),i=o&&new o;e.exports=i}).call(t,function(){return this}())},function(e,t,n){(function(t){function r(e,n){function r(){var o=this&&this!==t&&this instanceof r?i:e;return o.apply(n,arguments)}var i=o(e);return r}var o=n(164);e.exports=r}).call(t,function(){return this}())},function(e,t,n){function r(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 n=o(e.prototype),r=e.apply(n,t);return i(r)?r:n}}var o=n(165),i=n(24);e.exports=r},function(e,t,n){var r=n(24),o=function(){function e(){}return function(t){if(r(t)){e.prototype=t;var n=new e;e.prototype=void 0}return n||{}}}();e.exports=o},function(e,t,n){(function(t){function r(e,n,w,_,P,C,E,R,T,O){function S(){for(var d=arguments.length,v=d,m=Array(d);v--;)m[v]=arguments[v];if(_&&(m=i(m,_,P)),C&&(m=a(m,C,E)),I||A){var b=S.placeholder,F=l(m,b);if(d-=F.length,O>d){var U=R?o(R):void 0,L=x(O-d,0),B=I?F:void 0,q=I?void 0:F,H=I?m:void 0,V=I?void 0:m;n|=I?g:y,n&=~(I?y:g),D||(n&=~(f|h));var W=[e,n,w,H,B,V,q,U,T,L],K=r.apply(void 0,W);return u(e)&&p(K,W),K.placeholder=b,K}}var Q=j?w:this,Y=k?Q[e]:e;return R&&(m=c(m,R)),N&&T<m.length&&(m.length=T),this&&this!==t&&this instanceof S&&(Y=M||s(e)),Y.apply(Q,m)}var N=n&b,j=n&f,k=n&h,I=n&v,D=n&d,A=n&m,M=k?void 0:s(e);return S}var o=n(45),i=n(167),a=n(168),s=n(164),u=n(169),c=n(179),l=n(180),p=n(181),f=1,h=2,d=4,v=8,m=16,g=32,y=64,b=128,x=Math.max;e.exports=r}).call(t,function(){return this}())},function(e){function t(e,t,r){for(var o=r.length,i=-1,a=n(e.length-o,0),s=-1,u=t.length,c=Array(u+a);++s<u;)c[s]=t[s];for(;++i<o;)c[r[i]]=e[i];for(;a--;)c[s++]=e[i++];return c}var n=Math.max;e.exports=t},function(e){function t(e,t,r){for(var o=-1,i=r.length,a=-1,s=n(e.length-i,0),u=-1,c=t.length,l=Array(s+c);++a<s;)l[a]=e[a];for(var p=a;++u<c;)l[p+u]=t[u];for(;++o<i;)l[p+r[o]]=e[a++];return l}var n=Math.max;e.exports=t},function(e,t,n){function r(e){var t=a(e),n=s[t];if("function"!=typeof n||!(t in o.prototype))return!1;if(e===n)return!0;var r=i(n);return!!r&&e===r[0]}var o=n(170),i=n(172),a=n(174),s=n(176);e.exports=r},function(e,t,n){function r(e){this.__wrapped__=e,this.__actions__=[],this.__dir__=1,this.__filtered__=!1,this.__iteratees__=[],this.__takeCount__=a,this.__views__=[]}var o=n(165),i=n(171),a=Number.POSITIVE_INFINITY;r.prototype=o(i.prototype),r.prototype.constructor=r,e.exports=r},function(e){function t(){}e.exports=t},function(e,t,n){var r=n(162),o=n(173),i=r?function(e){return r.get(e)}:o;e.exports=i},function(e){function t(){}e.exports=t},function(e,t,n){function r(e){for(var t=e.name+"",n=o[t],r=n?n.length:0;r--;){var i=n[r],a=i.func;if(null==a||a==e)return i.name}return t}var o=n(175);e.exports=r},function(e){var t={};e.exports=t},function(e,t,n){function r(e){if(u(e)&&!s(e)&&!(e instanceof o)){if(e instanceof i)return e;if(p.call(e,"__chain__")&&p.call(e,"__wrapped__"))return c(e)}return new i(e)}var o=n(170),i=n(177),a=n(171),s=n(36),u=n(29),c=n(178),l=Object.prototype,p=l.hasOwnProperty;r.prototype=a.prototype,e.exports=r},function(e,t,n){function r(e,t,n){this.__wrapped__=e,this.__actions__=n||[],this.__chain__=!!t}var o=n(165),i=n(171);r.prototype=o(i.prototype),r.prototype.constructor=r,e.exports=r},function(e,t,n){function r(e){return e instanceof o?e.clone():new i(e.__wrapped__,e.__chain__,a(e.__actions__))}var o=n(170),i=n(177),a=n(45);e.exports=r},function(e,t,n){function r(e,t){for(var n=e.length,r=a(t.length,n),s=o(e);r--;){var u=t[r];e[r]=i(u,n)?s[u]:void 0}return e}var o=n(45),i=n(37),a=Math.min;e.exports=r},function(e){function t(e,t){for(var r=-1,o=e.length,i=-1,a=[];++r<o;)e[r]===t&&(e[r]=n,a[++i]=r);return a}var n="__lodash_placeholder__";e.exports=t},function(e,t,n){var r=n(161),o=n(182),i=150,a=16,s=function(){var e=0,t=0;return function(n,s){var u=o(),c=a-(u-t);if(t=u,c>0){if(++e>=i)return n}else e=0;return r(n,s)}}();e.exports=s},function(e,t,n){var r=n(26),o=r(Date,"now"),i=o||function(){return(new Date).getTime()};e.exports=i},function(e,t,n){(function(t){function r(e,n,r,a){function s(){for(var n=-1,o=arguments.length,i=-1,l=a.length,p=Array(l+o);++i<l;)p[i]=a[i];for(;o--;)p[i++]=arguments[++n];var f=this&&this!==t&&this instanceof s?c:e;return f.apply(u?r:this,p)}var u=n&i,c=o(e);return s}var o=n(164),i=1;e.exports=r}).call(t,function(){return this}())},function(e,t,n){function r(e,t){var n=e[1],r=t[1],v=n|r,m=p>v,g=r==p&&n==l||r==p&&n==f&&e[7].length<=t[8]||r==(p|f)&&n==l;if(!m&&!g)return e;r&u&&(e[2]=t[2],v|=n&u?0:c);var y=t[3];if(y){var b=e[3];e[3]=b?i(b,y,t[4]):o(y),e[4]=b?s(e[3],h):o(t[4])}return y=t[5],y&&(b=e[5],e[5]=b?a(b,y,t[6]):o(y),e[6]=b?s(e[5],h):o(t[6])),y=t[7],y&&(e[7]=o(y)),r&p&&(e[8]=null==e[8]?t[8]:d(e[8],t[8])),null==e[9]&&(e[9]=t[9]),e[0]=t[0],e[1]=v,e}var o=n(45),i=n(167),a=n(168),s=n(180),u=1,c=4,l=8,p=128,f=256,h="__lodash_placeholder__",d=Math.min;e.exports=r},function(e,t,n){var r=n(159),o=64,i=r(o);i.placeholder={},e.exports=i},function(e,t,n){"use strict";var r=n(111);e.exports=function(e){return r(e,function(e,t){var n=t.split(":");return e[0].push(n[0]),e[1].push(n[1]),e},[[],[]])}},function(e,t,n){"use strict";function r(e){return function(t,n){var r=e.hierarchicalFacets[n],i=e.hierarchicalFacetsRefinements[r.name]&&e.hierarchicalFacetsRefinements[r.name][0]||"",a=e._getHierarchicalFacetSeparator(r),s=d(e._getHierarchicalFacetSortBy(r)),u=o(s,a,i);return c(t,u,{name:e.hierarchicalFacets[n].name,count:null,isRefined:!0,path:null,data:null})}}function o(e,t,n){return function(r,o,s){var c=r;if(s>0){var p=0;for(c=r;s>p;)c=c&&f(c.data,{isRefined:!0}),p++}if(c){var d=i(c.path,n,t);c.data=l(u(h(o.data,d),a(t,n)),e[0],e[1])}return r}}function i(e,t,n){return function(r,o){return-1===o.indexOf(n)||-1===o.indexOf(n)&&-1===t.indexOf(n)||0===t.indexOf(o+n)||0===o.indexOf(e+n)}}function a(e,t){return function(n,r){return{name:p(s(r.split(e))),path:r,count:n,isRefined:t===r||0===t.indexOf(r+e),data:null}}}e.exports=r;var s=n(102),u=n(108),c=n(111),l=n(153),p=n(188),f=n(128),h=n(194),d=n(186)},function(e,t,n){function r(e,t,n){var r=e;return(e=o(e))?(n?s(r,t,n):null==t)?e.slice(u(e),c(e)+1):(t+="",e.slice(i(e,t),a(e,t)+1)):e}var o=n(104),i=n(189),a=n(190),s=n(52),u=n(191),c=n(193);e.exports=r},function(e){function t(e,t){for(var n=-1,r=e.length;++n<r&&t.indexOf(e.charAt(n))>-1;);return n}e.exports=t},function(e){function t(e,t){for(var n=e.length;n--&&t.indexOf(e.charAt(n))>-1;);return n}e.exports=t},function(e,t,n){function r(e){for(var t=-1,n=e.length;++t<n&&o(e.charCodeAt(t)););return t}var o=n(192);e.exports=r},function(e){function t(e){return 160>=e&&e>=9&&13>=e||32==e||160==e||5760==e||6158==e||e>=8192&&(8202>=e||8232==e||8233==e||8239==e||8287==e||12288==e||65279==e)}e.exports=t},function(e,t,n){function r(e){for(var t=e.length;t--&&o(e.charCodeAt(t)););return t}var o=n(192);e.exports=r},function(e,t,n){var r=n(117),o=n(41),i=n(119),a=n(120),s=n(61),u=s(function(e,t){return null==e?{}:"function"==typeof t[0]?a(e,o(t[0],t[1],3)):i(e,r(t))});e.exports=u},function(e,t,n){"use strict";var r=n(17),o=n(108),i=n(111),a=n(53),s=n(36),u={_getQueries:function(e,t){var n=[];return n.push({indexName:e,query:t.query,params:this._getHitsSearchParams(t)}),r(t.getRefinedDisjunctiveFacets(),function(r){n.push({indexName:e,query:t.query,params:this._getDisjunctiveFacetSearchParams(t,r)})},this),r(t.getRefinedHierarchicalFacets(),function(r){var o=t.getHierarchicalFacetByName(r),i=t.getHierarchicalRefinement(r);i.length>0&&i[0].split(t._getHierarchicalFacetSeparator(o)).length>1&&n.push({indexName:e,query:t.query,params:this._getDisjunctiveFacetSearchParams(t,r,!0)})},this),n},_getHitsSearchParams:function(e){var t=e.facets.concat(e.disjunctiveFacets).concat(this._getHitsHierarchicalFacetsAttributes(e)),n=this._getFacetFilters(e),r=this._getNumericFilters(e),o=this._getTagFilters(e),i={facets:t,tagFilters:o};return(e.distinct===!0||e.distinct===!1)&&(i.distinct=e.distinct),n.length>0&&(i.facetFilters=n),r.length>0&&(i.numericFilters=r),a(e.getQueryParams(),i)},_getDisjunctiveFacetSearchParams:function(e,t,n){var r=this._getFacetFilters(e,t,n),o=this._getNumericFilters(e,t),i=this._getTagFilters(e),s={hitsPerPage:1,page:0,attributesToRetrieve:[],attributesToHighlight:[],attributesToSnippet:[],tagFilters:i},u=e.getHierarchicalFacetByName(t);return s.facets=u?this._getDisjunctiveHierarchicalFacetAttribute(e,u,n):t,(e.distinct===!0||e.distinct===!1)&&(s.distinct=e.distinct),o.length>0&&(s.numericFilters=o),r.length>0&&(s.facetFilters=r),a(e.getQueryParams(),s)},_getNumericFilters:function(e,t){if(e.numericFilters)return e.numericFilters;var n=[];return r(e.numericRefinements,function(e,i){r(e,function(e,a){t!==i&&r(e,function(e){if(s(e)){var t=o(e,function(e){return i+a+e});n.push(t)}else n.push(i+a+e)})})}),n},_getTagFilters:function(e){return e.tagFilters?e.tagFilters:e.tagRefinements.join(",")},_getFacetFilters:function(e,t,n){var o=[];return r(e.facetsRefinements,function(e,t){r(e,function(e){o.push(t+":"+e)})}),r(e.facetsExcludes,function(e,t){r(e,function(e){o.push(t+":-"+e)})}),r(e.disjunctiveFacetsRefinements,function(e,n){if(n!==t&&e&&0!==e.length){var i=[];r(e,function(e){i.push(n+":"+e)}),o.push(i)}}),r(e.hierarchicalFacetsRefinements,function(r,i){var a=r[0];if(void 0!==a){var s,u=e.getHierarchicalFacetByName(i),c=e._getHierarchicalFacetSeparator(u);if(t===i){if(-1===a.indexOf(c)||n===!0)return;s=u.attributes[a.split(c).length-2],a=a.slice(0,a.lastIndexOf(c))}else s=u.attributes[a.split(c).length-1];o.push([s+":"+a])}}),o},_getHitsHierarchicalFacetsAttributes:function(e){var t=[];return i(e.hierarchicalFacets,function(t,n){var r=e.getHierarchicalRefinement(n.name)[0];if(!r)return t.push(n.attributes[0]),t;var o=r.split(e._getHierarchicalFacetSeparator(n)).length,i=n.attributes.slice(0,o+1);return t.concat(i)},t)},_getDisjunctiveHierarchicalFacetAttribute:function(e,t,n){if(n===!0)return[t.attributes[0]];var r=e.getHierarchicalRefinement(t.name)[0]||"",o=r.split(e._getHierarchicalFacetSeparator(t)).length-1;return t.attributes.slice(0,o+1)}};e.exports=u},function(e,t,n){(function(e,r){function o(e,n){var r={seen:[],stylize:a};return arguments.length>=3&&(r.depth=arguments[2]),arguments.length>=4&&(r.colors=arguments[3]),v(n)?r.showHidden=n:n&&t._extend(r,n),w(r.showHidden)&&(r.showHidden=!1),w(r.depth)&&(r.depth=2),w(r.colors)&&(r.colors=!1),w(r.customInspect)&&(r.customInspect=!0),r.colors&&(r.stylize=i),u(r,e,r.depth)}function i(e,t){var n=o.styles[t];return n?"["+o.colors[n][0]+"m"+e+"["+o.colors[n][1]+"m":e}function a(e){return e}function s(e){var t={};return e.forEach(function(e){t[e]=!0}),t}function u(e,n,r){if(e.customInspect&&n&&R(n.inspect)&&n.inspect!==t.inspect&&(!n.constructor||n.constructor.prototype!==n)){var o=n.inspect(r,e);return b(o)||(o=u(e,o,r)),o}var i=c(e,n);if(i)return i;var a=Object.keys(n),v=s(a);if(e.showHidden&&(a=Object.getOwnPropertyNames(n)),E(n)&&(a.indexOf("message")>=0||a.indexOf("description")>=0))return l(n);if(0===a.length){if(R(n)){var m=n.name?": "+n.name:"";return e.stylize("[Function"+m+"]","special")}if(_(n))return e.stylize(RegExp.prototype.toString.call(n),"regexp");if(C(n))return e.stylize(Date.prototype.toString.call(n),"date");if(E(n))return l(n)}var g="",y=!1,x=["{","}"];if(d(n)&&(y=!0,x=["[","]"]),R(n)){var w=n.name?": "+n.name:"";g=" [Function"+w+"]"}if(_(n)&&(g=" "+RegExp.prototype.toString.call(n)),C(n)&&(g=" "+Date.prototype.toUTCString.call(n)),E(n)&&(g=" "+l(n)),0===a.length&&(!y||0==n.length))return x[0]+g+x[1];if(0>r)return _(n)?e.stylize(RegExp.prototype.toString.call(n),"regexp"):e.stylize("[Object]","special");e.seen.push(n);var P;return P=y?p(e,n,r,v,a):a.map(function(t){return f(e,n,r,v,t,y)}),e.seen.pop(),h(P,g,x)}function c(e,t){if(w(t))return e.stylize("undefined","undefined");if(b(t)){var n="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(n,"string")}return y(t)?e.stylize(""+t,"number"):v(t)?e.stylize(""+t,"boolean"):m(t)?e.stylize("null","null"):void 0}function l(e){return"["+Error.prototype.toString.call(e)+"]"}function p(e,t,n,r,o){for(var i=[],a=0,s=t.length;s>a;++a)i.push(j(t,String(a))?f(e,t,n,r,String(a),!0):"");return o.forEach(function(o){o.match(/^\d+$/)||i.push(f(e,t,n,r,o,!0))}),i}function f(e,t,n,r,o,i){var a,s,c;if(c=Object.getOwnPropertyDescriptor(t,o)||{value:t[o]},c.get?s=c.set?e.stylize("[Getter/Setter]","special"):e.stylize("[Getter]","special"):c.set&&(s=e.stylize("[Setter]","special")),j(r,o)||(a="["+o+"]"),s||(e.seen.indexOf(c.value)<0?(s=m(n)?u(e,c.value,null):u(e,c.value,n-1),s.indexOf("\n")>-1&&(s=i?s.split("\n").map(function(e){return" "+e}).join("\n").substr(2):"\n"+s.split("\n").map(function(e){return" "+e}).join("\n"))):s=e.stylize("[Circular]","special")),w(a)){if(i&&o.match(/^\d+$/))return s;a=JSON.stringify(""+o),a.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(a=a.substr(1,a.length-2),a=e.stylize(a,"name")):(a=a.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),a=e.stylize(a,"string"))}return a+": "+s}function h(e,t,n){var r=0,o=e.reduce(function(e,t){return r++,t.indexOf("\n")>=0&&r++,e+t.replace(/\u001b\[\d\d?m/g,"").length+1},0);return o>60?n[0]+(""===t?"":t+"\n ")+" "+e.join(",\n ")+" "+n[1]:n[0]+t+" "+e.join(", ")+" "+n[1]}function d(e){return Array.isArray(e)}function v(e){return"boolean"==typeof e}function m(e){return null===e}function g(e){return null==e}function y(e){return"number"==typeof e}function b(e){return"string"==typeof e}function x(e){return"symbol"==typeof e}function w(e){return void 0===e}function _(e){return P(e)&&"[object RegExp]"===O(e)}function P(e){return"object"==typeof e&&null!==e}function C(e){return P(e)&&"[object Date]"===O(e)}function E(e){return P(e)&&("[object Error]"===O(e)||e instanceof Error)}function R(e){return"function"==typeof e}function T(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"==typeof e||"undefined"==typeof e}function O(e){return Object.prototype.toString.call(e)}function S(e){return 10>e?"0"+e.toString(10):e.toString(10)}function N(){var e=new Date,t=[S(e.getHours()),S(e.getMinutes()),S(e.getSeconds())].join(":");return[e.getDate(),A[e.getMonth()],t].join(" ")}function j(e,t){return Object.prototype.hasOwnProperty.call(e,t)}var k=/%[sdj%]/g;t.format=function(e){if(!b(e)){for(var t=[],n=0;n<arguments.length;n++)t.push(o(arguments[n]));return t.join(" ")}for(var n=1,r=arguments,i=r.length,a=String(e).replace(k,function(e){if("%%"===e)return"%";if(n>=i)return e;switch(e){case"%s":return String(r[n++]);case"%d":return Number(r[n++]);case"%j":try{return JSON.stringify(r[n++])}catch(t){return"[Circular]"}default:return e}}),s=r[n];i>n;s=r[++n])a+=m(s)||!P(s)?" "+s:" "+o(s);return a},t.deprecate=function(n,o){function i(){if(!a){if(r.throwDeprecation)throw new Error(o);r.traceDeprecation?console.trace(o):console.error(o),a=!0}return n.apply(this,arguments)}if(w(e.process))return function(){return t.deprecate(n,o).apply(this,arguments)};if(r.noDeprecation===!0)return n;var a=!1;return i};var I,D={};t.debuglog=function(e){if(w(I)&&(I={NODE_ENV:"production"}.NODE_DEBUG||""),e=e.toUpperCase(),!D[e])if(new RegExp("\\b"+e+"\\b","i").test(I)){var n=r.pid;D[e]=function(){var r=t.format.apply(t,arguments);console.error("%s %d: %s",e,n,r)}}else D[e]=function(){};return D[e]},t.inspect=o,o.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},o.styles={special:"cyan",number:"yellow","boolean":"yellow",undefined:"grey","null":"bold",string:"green",date:"magenta",regexp:"red"},t.isArray=d,t.isBoolean=v,t.isNull=m,t.isNullOrUndefined=g,t.isNumber=y,t.isString=b,t.isSymbol=x,t.isUndefined=w,t.isRegExp=_,t.isObject=P,t.isDate=C,t.isError=E,t.isFunction=R,t.isPrimitive=T,t.isBuffer=n(197);var A=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];t.log=function(){console.log("%s - %s",N(),t.format.apply(t,arguments))},t.inherits=n(198),t._extend=function(e,t){if(!t||!P(t))return e;for(var n=Object.keys(t),r=n.length;r--;)e[n[r]]=t[n[r]];return e}}).call(t,function(){return this}(),n(8))},function(e){e.exports=function(e){return e&&"object"==typeof e&&"function"==typeof e.copy&&"function"==typeof e.fill&&"function"==typeof e.readUInt8}},function(e){e.exports="function"==typeof Object.create?function(e,t){e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})}:function(e,t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}},function(e,t,n){var r=n(160),o=n(180),i=n(61),a=1,s=32,u=i(function(e,t,n){var i=a;if(n.length){var c=o(n,u.placeholder);i|=s}return r(e,i,t,n,c)});u.placeholder={},e.exports=u},function(e,t,n){"use strict";function r(e){return v(e)?h(e,r):m(e)?p(e,r):d(e)?g(e):e}function o(e,t,n){if(null!==e&&(t=t.replace(e,""),n=n.replace(e,"")),-1!==b.indexOf(t)||-1!==b.indexOf(n)){if("q"===t)return-1;if("q"===n)return 1;var r=-1!==y.indexOf(t),o=-1!==y.indexOf(n);if(r&&!o)return 1;if(o&&!r)return-1}return t.localeCompare(n)}var i=n(201),a=n(74),s=n(203),u=n(199),c=n(17),l=n(194),p=n(108),f=n(207),h=n(209),d=n(125),v=n(56),m=n(36),g=n(205).encode,y=["dFR","fR","nR","hFR","tR"],b=i.ENCODED_PARAMETERS;t.getStateFromQueryString=function(e,t){var n=t&&t.prefix||"",r=s.parse(e),o=new RegExp("^"+n),u=f(r,function(e,t){if(n&&o.test(t)){var r=t.replace(o,"");return i.decode(r)}var a=i.decode(t);return a||t}),c=a._parseNumbers(u);return l(c,a.PARAMETERS)},t.getUnrecognizedParametersInQueryString=function(e,t){var n=t&&t.prefix,r={},o=s.parse(e);if(n){var a=new RegExp("^"+n);c(o,function(e,t){a.test(t)||(r[t]=e)})}else c(o,function(e,t){i.decode(t)||(r[t]=e)});return r},t.getQueryStringFromState=function(e,t){var n=t&&t.moreAttributes,a=t&&t.prefix||"",c=r(e),l=f(c,function(e,t){var n=i.encode(t);return a+n}),p=""===a?null:new RegExp("^"+a),h=u(o,null,p);if(n){var d=s.stringify(l,{encode:!1,sort:h}),v=s.stringify(n,{encode:!1});return d?d+"&"+v:v}return s.stringify(l,{encode:!1,sort:h})}},function(e,t,n){"use strict";var r=n(202),o=n(25),i={advancedSyntax:"aS",allowTyposOnNumericTokens:"aTONT",analyticsTags:"aT",analytics:"a",aroundLatLngViaIP:"aLLVIP",aroundLatLng:"aLL",aroundPrecision:"aP",aroundRadius:"aR",attributesToHighlight:"aTH",attributesToRetrieve:"aTR",attributesToSnippet:"aTS",disjunctiveFacetsRefinements:"dFR",disjunctiveFacets:"dF",distinct:"d",facetsExcludes:"fE",facetsRefinements:"fR",facets:"f",getRankingInfo:"gRI",hierarchicalFacetsRefinements:"hFR",hierarchicalFacets:"hF",highlightPostTag:"hPoT",highlightPreTag:"hPrT",hitsPerPage:"hPP",ignorePlurals:"iP",index:"idx",insideBoundingBox:"iBB",insidePolygon:"iPg",length:"l",maxValuesPerFacet:"mVPF",minimumAroundRadius:"mAR",minWordSizefor1Typo:"mWS1T",minWordSizefor2Typos:"mWS2T",numericFilters:"nF",numericRefinements:"nR",offset:"o",optionalWords:"oW",page:"p",queryType:"qT",query:"q",removeWordsIfNoResults:"rWINR",replaceSynonymsInHighlight:"rSIH",restrictSearchableAttributes:"rSA",synonyms:"s",tagFilters:"tF",tagRefinements:"tR",typoTolerance:"tT"},a=r(i);e.exports={ENCODED_PARAMETERS:o(a),decode:function(e){return a[e]},encode:function(e){return i[e]}}},function(e,t,n){function r(e,t,n){n&&o(e,t,n)&&(t=void 0);for(var r=-1,a=i(e),u=a.length,c={};++r<u;){var l=a[r],p=e[l];t?s.call(c,p)?c[p].push(l):c[p]=[l]:c[p]=l}return c}var o=n(52),i=n(25),a=Object.prototype,s=a.hasOwnProperty;e.exports=r},function(e,t,n){var r=n(204),o=n(206);e.exports={stringify:r,parse:o}},function(e,t,n){var r=n(205),o={delimiter:"&",arrayPrefixGenerators:{brackets:function(e){return e+"[]"},indices:function(e,t){return e+"["+t+"]"},repeat:function(e){return e}},strictNullHandling:!1,skipNulls:!1,encode:!0};o.stringify=function(e,t,n,i,a,s,u,c){if("function"==typeof u)e=u(t,e);else if(r.isBuffer(e))e=e.toString();else if(e instanceof Date)e=e.toISOString();else if(null===e){if(i)return s?r.encode(t):t;e=""}if("string"==typeof e||"number"==typeof e||"boolean"==typeof e)return s?[r.encode(t)+"="+r.encode(e)]:[t+"="+e];var l=[];if("undefined"==typeof e)return l;var p;if(Array.isArray(u))p=u;else{var f=Object.keys(e);p=c?f.sort(c):f}for(var h=0,d=p.length;d>h;++h){var v=p[h];a&&null===e[v]||(l=l.concat(Array.isArray(e)?o.stringify(e[v],n(t,v),n,i,a,s,u):o.stringify(e[v],t+"["+v+"]",n,i,a,s,u)))}return l},e.exports=function(e,t){t=t||{};var n,r,i="undefined"==typeof t.delimiter?o.delimiter:t.delimiter,a="boolean"==typeof t.strictNullHandling?t.strictNullHandling:o.strictNullHandling,s="boolean"==typeof t.skipNulls?t.skipNulls:o.skipNulls,u="boolean"==typeof t.encode?t.encode:o.encode,c="function"==typeof t.sort?t.sort:null;"function"==typeof t.filter?(r=t.filter,e=r("",e)):Array.isArray(t.filter)&&(n=r=t.filter);var l=[];if("object"!=typeof e||null===e)return"";var p;p=t.arrayFormat in o.arrayPrefixGenerators?t.arrayFormat:"indices"in t?t.indices?"indices":"repeat":"indices";var f=o.arrayPrefixGenerators[p];n||(n=Object.keys(e)),c&&n.sort(c);for(var h=0,d=n.length;d>h;++h){var v=n[h];s&&null===e[v]||(l=l.concat(o.stringify(e[v],v,f,a,s,u,r,c)))}return l.join(i)}},function(e,t){var n={};n.hexTable=new Array(256);for(var r=0;256>r;++r)n.hexTable[r]="%"+((16>r?"0":"")+r.toString(16)).toUpperCase();t.arrayToObject=function(e,t){for(var n=t.plainObjects?Object.create(null):{},r=0,o=e.length;o>r;++r)"undefined"!=typeof e[r]&&(n[r]=e[r]);return n},t.merge=function(e,n,r){if(!n)return e;if("object"!=typeof n)return Array.isArray(e)?e.push(n):"object"==typeof e?e[n]=!0:e=[e,n],e;if("object"!=typeof e)return e=[e].concat(n);Array.isArray(e)&&!Array.isArray(n)&&(e=t.arrayToObject(e,r));for(var o=Object.keys(n),i=0,a=o.length;a>i;++i){var s=o[i],u=n[s];e[s]=Object.prototype.hasOwnProperty.call(e,s)?t.merge(e[s],u,r):u}return e},t.decode=function(e){try{return decodeURIComponent(e.replace(/\+/g," "))}catch(t){return e}},t.encode=function(e){if(0===e.length)return e;"string"!=typeof e&&(e=""+e);for(var t="",r=0,o=e.length;o>r;++r){var i=e.charCodeAt(r);45===i||46===i||95===i||126===i||i>=48&&57>=i||i>=65&&90>=i||i>=97&&122>=i?t+=e[r]:128>i?t+=n.hexTable[i]:2048>i?t+=n.hexTable[192|i>>6]+n.hexTable[128|63&i]:55296>i||i>=57344?t+=n.hexTable[224|i>>12]+n.hexTable[128|i>>6&63]+n.hexTable[128|63&i]:(++r,i=65536+((1023&i)<<10|1023&e.charCodeAt(r)),t+=n.hexTable[240|i>>18]+n.hexTable[128|i>>12&63]+n.hexTable[128|i>>6&63]+n.hexTable[128|63&i])}return t},t.compact=function(e,n){if("object"!=typeof e||null===e)return e;n=n||[];var r=n.indexOf(e);if(-1!==r)return n[r];if(n.push(e),Array.isArray(e)){for(var o=[],i=0,a=e.length;a>i;++i)"undefined"!=typeof e[i]&&o.push(e[i]);return o}var s=Object.keys(e);for(i=0,a=s.length;a>i;++i){var u=s[i];e[u]=t.compact(e[u],n)}return e},t.isRegExp=function(e){return"[object RegExp]"===Object.prototype.toString.call(e)},t.isBuffer=function(e){return null===e||"undefined"==typeof e?!1:!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}},function(e,t,n){var r=n(205),o={delimiter:"&",depth:5,arrayLimit:20,parameterLimit:1e3,strictNullHandling:!1,plainObjects:!1,allowPrototypes:!1,allowDots:!1};o.parseValues=function(e,t){for(var n={},o=e.split(t.delimiter,t.parameterLimit===1/0?void 0:t.parameterLimit),i=0,a=o.length;a>i;++i){var s=o[i],u=-1===s.indexOf("]=")?s.indexOf("="):s.indexOf("]=")+1;if(-1===u)n[r.decode(s)]="",t.strictNullHandling&&(n[r.decode(s)]=null);else{var c=r.decode(s.slice(0,u)),l=r.decode(s.slice(u+1));n[c]=Object.prototype.hasOwnProperty.call(n,c)?[].concat(n[c]).concat(l):l}}return n},o.parseObject=function(e,t,n){if(!e.length)return t;var r,i=e.shift();if("[]"===i)r=[],r=r.concat(o.parseObject(e,t,n));else{r=n.plainObjects?Object.create(null):{};var a="["===i[0]&&"]"===i[i.length-1]?i.slice(1,i.length-1):i,s=parseInt(a,10),u=""+s;!isNaN(s)&&i!==a&&u===a&&s>=0&&n.parseArrays&&s<=n.arrayLimit?(r=[],r[s]=o.parseObject(e,t,n)):r[a]=o.parseObject(e,t,n)}return r},o.parseKeys=function(e,t,n){if(e){n.allowDots&&(e=e.replace(/\.([^\.\[]+)/g,"[$1]"));var r=/^([^\[\]]*)/,i=/(\[[^\[\]]*\])/g,a=r.exec(e),s=[];if(a[1]){if(!n.plainObjects&&Object.prototype.hasOwnProperty(a[1])&&!n.allowPrototypes)return;s.push(a[1])}for(var u=0;null!==(a=i.exec(e))&&u<n.depth;)++u,(n.plainObjects||!Object.prototype.hasOwnProperty(a[1].replace(/\[|\]/g,""))||n.allowPrototypes)&&s.push(a[1]);return a&&s.push("["+e.slice(a.index)+"]"),o.parseObject(s,t,n)}},e.exports=function(e,t){if(t=t||{},t.delimiter="string"==typeof t.delimiter||r.isRegExp(t.delimiter)?t.delimiter:o.delimiter,t.depth="number"==typeof t.depth?t.depth:o.depth,t.arrayLimit="number"==typeof t.arrayLimit?t.arrayLimit:o.arrayLimit,t.parseArrays=t.parseArrays!==!1,t.allowDots="boolean"==typeof t.allowDots?t.allowDots:o.allowDots,t.plainObjects="boolean"==typeof t.plainObjects?t.plainObjects:o.plainObjects,t.allowPrototypes="boolean"==typeof t.allowPrototypes?t.allowPrototypes:o.allowPrototypes,t.parameterLimit="number"==typeof t.parameterLimit?t.parameterLimit:o.parameterLimit,t.strictNullHandling="boolean"==typeof t.strictNullHandling?t.strictNullHandling:o.strictNullHandling,""===e||null===e||"undefined"==typeof e)return t.plainObjects?Object.create(null):{};for(var n="string"==typeof e?o.parseValues(e,t):e,i=t.plainObjects?Object.create(null):{},a=Object.keys(n),s=0,u=a.length;u>s;++s){var c=a[s],l=o.parseKeys(c,n[c],t);i=r.merge(i,l,t)}return r.compact(i)}},function(e,t,n){var r=n(208),o=r(!0);e.exports=o},function(e,t,n){function r(e){return function(t,n,r){var a={};return n=o(n,r,3),i(t,function(t,r,o){var i=n(t,r,o);r=e?i:r,t=e?t:i,a[r]=t}),a}}var o=n(86),i=n(20);e.exports=r},function(e,t,n){var r=n(208),o=r();e.exports=o},function(e){"use strict";e.exports="2.6.3"},function(e,t,n){var r=n(117),o=n(212),i=n(61),a=i(function(e){return o(r(e,!1,!0))});e.exports=a},function(e,t,n){function r(e,t){var n=-1,r=o,u=e.length,c=!0,l=c&&u>=s,p=l?a():null,f=[];p?(r=i,c=!1):(l=!1,p=t?[]:f);e:for(;++n<u;){var h=e[n],d=t?t(h,n,e):h;if(c&&h===h){for(var v=p.length;v--;)if(p[v]===d)continue e;t&&p.push(d),f.push(h)}else r(p,d,0)<0&&((t||l)&&p.push(d),f.push(h))}return f}var o=n(76),i=n(78),a=n(79),s=200;e.exports=r},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e){var t=e;return function(){var e=Date.now(),n=e-t;return t=e,n}}function i(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],t=e.useHash||!1,n=t?f:h;return new d(n,e)}var a=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),s=n(72),u=s.AlgoliaSearchHelper,c=n(214).split(".")[0],l=n(215),p=n(53),f={character:"#",onpopstate:function(e){window.addEventListener("hashchange",e)},pushState:function(e){window.location.assign(this.createURL(e))},replaceState:function(e){window.location.replace(this.createURL(e))},createURL:function(e){return document.location.search+this.character+e},readUrl:function(){return window.location.hash.slice(1)}},h={character:"?",onpopstate:function(e){window.addEventListener("popstate",e)},pushState:function(e){window.history.pushState(null,"",this.createURL(e))},replaceState:function(e){window.history.replaceState(null,"",this.createURL(e))},createURL:function(e){return this.character+e+document.location.hash},readUrl:function(){return window.location.search.slice(1)}},d=function(){function e(t,n){r(this,e),this.__initLast=!0,this.urlUtils=t,this.originalConfig=null,this.timer=o(Date.now()),this.threshold=n.threshold||700,this.trackedParameters=n.trackedParameters||["query","attribute:*","index","page","hitsPerPage"]}return a(e,[{key:"getConfiguration",value:function(e){this.originalConfig=e;var t=this.urlUtils.readUrl(),n=u.getConfigurationFromQueryString(t);return n}},{key:"onPopState",value:function(e){var t=this.urlUtils.readUrl(),n=u.getConfigurationFromQueryString(t),r=p({},this.originalConfig,n),o=e.getState(this.trackedParameters),i=p({},this.originalConfig,o);l(i,r)||e.setState(r).search()}},{key:"init",value:function(e,t){this.urlUtils.onpopstate(this.onPopState.bind(this,t))}},{key:"render",value:function(e){var t=e.helper,n=t.getState(this.trackedParameters),r=this.urlUtils.readUrl(),o=u.getConfigurationFromQueryString(r);if(!l(n,o)){var i=u.getForeignConfigurationInQueryString(r);i.is_v=c;var a=t.getStateAsQueryString({filters:this.trackedParameters,moreAttributes:i});this.timer()<this.threshold?this.urlUtils.replaceState(a):this.urlUtils.pushState(a)}}},{key:"createURL",value:function(e){var t=this.urlUtils.readUrl(),n=e.filter(this.trackedParameters),r=s.url.getUnrecognizedParametersInQueryString(t);return r.is_v=c,this.urlUtils.createURL(s.url.getQueryStringFromState(n))}}]),e}();e.exports=i},function(e){"use strict";e.exports="0.7.0"},function(e,t,n){function r(e,t,n,r){n="function"==typeof n?i(n,r,3):void 0;var a=n?n(e,t):void 0;return void 0===a?o(e,t,n):!!a}var o=n(89),i=n(41);e.exports=r},function(e,t,n){"use strict";function r(e){var t=e.container,n=e.attributes,r=void 0===n?[]:n,p=e.separator,f=e.limit,v=void 0===f?100:f,m=e.sortBy,g=void 0===m?["name:asc"]:m,y=e.cssClasses,b=void 0===y?{}:y,x=e.hideContainerWhenNoResults,w=void 0===x?!0:x,_=e.templates,P=void 0===_?d:_,C=e.transformData,E=u.getContainerNode(t),R="Usage: hierarchicalMenu({container, attributes, [separator, sortBy, limit, cssClasses.{root, list, item}, templates.{header, item, footer}, transformData]})";if(!t||!r||!r.length)throw new Error(R);var T=r[0];return{getConfiguration:function(){return{hierarchicalFacets:[{name:T,attributes:r,separator:p}]}},render:function(e){var t=e.results,n=e.helper,r=e.templatesConfig,p=e.createURL,f=e.state,m=i(t,T,g),y=u.prepareTemplateProps({ transformData:C,defaultTemplates:d,templatesConfig:r,templates:P});b={root:l(c(null),b.root),header:l(c("header"),b.header),body:l(c("body"),b.body),footer:l(c("footer"),b.footer),list:l(c("list"),b.list),depth:c("list","lvl"),item:l(c("item"),b.item),active:l(c("item","active"),b.active),link:l(c("link"),b.link),count:l(c("count"),b.count)},s.render(a.createElement(h,{createURL:function(e){return p(f.toggleRefinement(T,e))},cssClasses:b,facetNameKey:"path",facetValues:m,hasResults:m.length>0,hideContainerWhenNoResults:w,limit:v,templateProps:y,toggleRefinement:o.bind(null,n,T)}),E)}}}function o(e,t,n){e.toggleRefinement(t,n).search()}function i(e,t,n){var r=e.getFacetValues(t,{sortBy:n});return r.data||[]}var a=n(217),s=n(368),u=n(369),c=u.bemHelper("ais-hierarchical-menu"),l=n(370),p=n(371),f=n(372),h=p(f(n(379))),d=n(381);e.exports=r},function(e,t,n){"use strict";e.exports=n(218)},function(e,t,n){"use strict";var r=n(219),o=n(358),i=n(362),a=n(254),s=n(367),u={};a(u,i),a(u,{findDOMNode:s("findDOMNode","ReactDOM","react-dom",r,r.findDOMNode),render:s("render","ReactDOM","react-dom",r,r.render),unmountComponentAtNode:s("unmountComponentAtNode","ReactDOM","react-dom",r,r.unmountComponentAtNode),renderToString:s("renderToString","ReactDOMServer","react-dom/server",o,o.renderToString),renderToStaticMarkup:s("renderToStaticMarkup","ReactDOMServer","react-dom/server",o,o.renderToStaticMarkup)}),u.__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=r,e.exports=u},function(e,t,n){"use strict";{var r=n(220),o=n(221),i=n(285),a=n(259),s=n(243),u=n(233),c=n(264),l=n(268),p=n(356),f=n(305),h=n(357);n(240)}i.inject();var d=u.measure("React","render",s.render),v={findDOMNode:f,render:d,unmountComponentAtNode:s.unmountComponentAtNode,version:p,unstable_batchedUpdates:l.batchedUpdates,unstable_renderSubtreeIntoContainer:h};"undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.inject&&__REACT_DEVTOOLS_GLOBAL_HOOK__.inject({CurrentOwner:r,InstanceHandles:a,Mount:s,Reconciler:c,TextComponent:o});e.exports=v},function(e){"use strict";var t={current:null};e.exports=t},function(e,t,n){"use strict";var r=n(222),o=n(237),i=n(241),a=n(243),s=n(254),u=n(236),c=n(235),l=(n(284),function(){});s(l.prototype,{construct:function(e){this._currentElement=e,this._stringText=""+e,this._rootNodeID=null,this._mountIndex=0},mountComponent:function(e,t,n){if(this._rootNodeID=e,t.useCreateElement){var r=n[a.ownerDocumentContextKey],i=r.createElement("span");return o.setAttributeForID(i,e),a.getID(i),c(i,this._stringText),i}var s=u(this._stringText);return t.renderToStaticMarkup?s:"<span "+o.createMarkupForID(e)+">"+s+"</span>"},receiveComponent:function(e){if(e!==this._currentElement){this._currentElement=e;var t=""+e;if(t!==this._stringText){this._stringText=t;var n=a.getNode(this._rootNodeID);r.updateTextContent(n,t)}}},unmountComponent:function(){i.unmountIDFromEnvironment(this._rootNodeID)}}),e.exports=l},function(e,t,n){"use strict";function r(e,t,n){var r=n>=e.childNodes.length?null:e.childNodes.item(n);e.insertBefore(t,r)}var o=n(223),i=n(231),a=n(233),s=n(234),u=n(235),c=n(228),l={dangerouslyReplaceNodeWithMarkup:o.dangerouslyReplaceNodeWithMarkup,updateTextContent:u,processUpdates:function(e,t){for(var n,a=null,l=null,p=0;p<e.length;p++)if(n=e[p],n.type===i.MOVE_EXISTING||n.type===i.REMOVE_NODE){var f=n.fromIndex,h=n.parentNode.childNodes[f],d=n.parentID;h?void 0:c(!1),a=a||{},a[d]=a[d]||[],a[d][f]=h,l=l||[],l.push(h)}var v;if(v=t.length&&"string"==typeof t[0]?o.dangerouslyRenderMarkup(t):t,l)for(var m=0;m<l.length;m++)l[m].parentNode.removeChild(l[m]);for(var g=0;g<e.length;g++)switch(n=e[g],n.type){case i.INSERT_MARKUP:r(n.parentNode,v[n.markupIndex],n.toIndex);break;case i.MOVE_EXISTING:r(n.parentNode,a[n.parentID][n.fromIndex],n.toIndex);break;case i.SET_MARKUP:s(n.parentNode,n.content);break;case i.TEXT_CONTENT:u(n.parentNode,n.content);break;case i.REMOVE_NODE:}}};a.measureMethods(l,"DOMChildrenOperations",{updateTextContent:"updateTextContent"}),e.exports=l},function(e,t,n){"use strict";function r(e){return e.substring(1,e.indexOf(" "))}var o=n(224),i=n(225),a=n(230),s=n(229),u=n(228),c=/^(<[^ \/>]+)/,l="data-danger-index",p={dangerouslyRenderMarkup:function(e){o.canUseDOM?void 0:u(!1);for(var t,n={},p=0;p<e.length;p++)e[p]?void 0:u(!1),t=r(e[p]),t=s(t)?t:"*",n[t]=n[t]||[],n[t][p]=e[p];var f=[],h=0;for(t in n)if(n.hasOwnProperty(t)){var d,v=n[t];for(d in v)if(v.hasOwnProperty(d)){var m=v[d];v[d]=m.replace(c,"$1 "+l+'="'+d+'" ')}for(var g=i(v.join(""),a),y=0;y<g.length;++y){var b=g[y];b.hasAttribute&&b.hasAttribute(l)&&(d=+b.getAttribute(l),b.removeAttribute(l),f.hasOwnProperty(d)?u(!1):void 0,f[d]=b,h+=1)}}return h!==f.length?u(!1):void 0,f.length!==e.length?u(!1):void 0,f},dangerouslyReplaceNodeWithMarkup:function(e,t){o.canUseDOM?void 0:u(!1),t?void 0:u(!1),"html"===e.tagName.toLowerCase()?u(!1):void 0;var n;n="string"==typeof t?i(t,a)[0]:t,e.parentNode.replaceChild(n,e)}};e.exports=p},function(e){"use strict";var t=!("undefined"==typeof window||!window.document||!window.document.createElement),n={canUseDOM:t,canUseWorkers:"undefined"!=typeof Worker,canUseEventListeners:t&&!(!window.addEventListener&&!window.attachEvent),canUseViewport:t&&!!window.screen,isInWorker:!t};e.exports=n},function(e,t,n){"use strict";function r(e){var t=e.match(l);return t&&t[1].toLowerCase()}function o(e,t){var n=c;c?void 0:u(!1);var o=r(e),i=o&&s(o);if(i){n.innerHTML=i[1]+e+i[2];for(var l=i[0];l--;)n=n.lastChild}else n.innerHTML=e;var p=n.getElementsByTagName("script");p.length&&(t?void 0:u(!1),a(p).forEach(t));for(var f=a(n.childNodes);n.lastChild;)n.removeChild(n.lastChild);return f}var i=n(224),a=n(226),s=n(229),u=n(228),c=i.canUseDOM?document.createElement("div"):null,l=/^\s*<(\w+)/;e.exports=o},function(e,t,n){"use strict";function r(e){return!!e&&("object"==typeof e||"function"==typeof e)&&"length"in e&&!("setInterval"in e)&&"number"!=typeof e.nodeType&&(Array.isArray(e)||"callee"in e||"item"in e)}function o(e){return r(e)?Array.isArray(e)?e.slice():i(e):[e]}var i=n(227);e.exports=o},function(e,t,n){"use strict";function r(e){var t=e.length;if(Array.isArray(e)||"object"!=typeof e&&"function"!=typeof e?o(!1):void 0,"number"!=typeof t?o(!1):void 0,0===t||t-1 in e?void 0:o(!1),e.hasOwnProperty)try{return Array.prototype.slice.call(e)}catch(n){}for(var r=Array(t),i=0;t>i;i++)r[i]=e[i];return r}var o=n(228);e.exports=r},function(e){"use strict";var t=function(e,t,n,r,o,i,a,s){if(!e){var u;if(void 0===t)u=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var c=[n,r,o,i,a,s],l=0;u=new Error("Invariant Violation: "+t.replace(/%s/g,function(){return c[l++]}))}throw u.framesToPop=1,u}};e.exports=t},function(e,t,n){"use strict";function r(e){return a?void 0:i(!1),f.hasOwnProperty(e)||(e="*"),s.hasOwnProperty(e)||(a.innerHTML="*"===e?"<link />":"<"+e+"></"+e+">",s[e]=!a.firstChild),s[e]?f[e]:null}var o=n(224),i=n(228),a=o.canUseDOM?document.createElement("div"):null,s={},u=[1,'<select multiple="true">',"</select>"],c=[1,"<table>","</table>"],l=[3,"<table><tbody><tr>","</tr></tbody></table>"],p=[1,'<svg xmlns="http://www.w3.org/2000/svg">',"</svg>"],f={"*":[1,"?<div>","</div>"],area:[1,"<map>","</map>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],legend:[1,"<fieldset>","</fieldset>"],param:[1,"<object>","</object>"],tr:[2,"<table><tbody>","</tbody></table>"],optgroup:u,option:u,caption:c,colgroup:c,tbody:c,tfoot:c,thead:c,td:l,th:l},h=["circle","clipPath","defs","ellipse","g","image","line","linearGradient","mask","path","pattern","polygon","polyline","radialGradient","rect","stop","text","tspan"];h.forEach(function(e){f[e]=p,s[e]=!0}),e.exports=r},function(e){"use strict";function t(e){return function(){return e}}function n(){}n.thatReturns=t,n.thatReturnsFalse=t(!1),n.thatReturnsTrue=t(!0),n.thatReturnsNull=t(null),n.thatReturnsThis=function(){return this},n.thatReturnsArgument=function(e){return e},e.exports=n},function(e,t,n){"use strict";var r=n(232),o=r({INSERT_MARKUP:null,MOVE_EXISTING:null,REMOVE_NODE:null,SET_MARKUP:null,TEXT_CONTENT:null});e.exports=o},function(e,t,n){"use strict";var r=n(228),o=function(e){var t,n={};e instanceof Object&&!Array.isArray(e)?void 0:r(!1);for(t in e)e.hasOwnProperty(t)&&(n[t]=t);return n};e.exports=o},function(e){"use strict";function t(e,t,n){return n}var n={enableMeasure:!1,storedMeasure:t,measureMethods:function(e,t,n){},measure:function(e,t,n){return n},injection:{injectMeasure:function(e){n.storedMeasure=e}}};e.exports=n},function(e,t,n){"use strict";var r=n(224),o=/^[ \r\n\t\f]/,i=/<(!--|link|noscript|meta|script|style)[ \r\n\t\f\/>]/,a=function(e,t){e.innerHTML=t};if("undefined"!=typeof MSApp&&MSApp.execUnsafeLocalFunction&&(a=function(e,t){MSApp.execUnsafeLocalFunction(function(){e.innerHTML=t})}),r.canUseDOM){var s=document.createElement("div");s.innerHTML=" ",""===s.innerHTML&&(a=function(e,t){if(e.parentNode&&e.parentNode.replaceChild(e,e),o.test(t)||"<"===t[0]&&i.test(t)){e.innerHTML=String.fromCharCode(65279)+t;var n=e.firstChild;1===n.data.length?e.removeChild(n):n.deleteData(0,1)}else e.innerHTML=t})}e.exports=a},function(e,t,n){"use strict";var r=n(224),o=n(236),i=n(234),a=function(e,t){e.textContent=t};r.canUseDOM&&("textContent"in document.documentElement||(a=function(e,t){i(e,o(t))})),e.exports=a},function(e){"use strict";function t(e){return r[e]}function n(e){return(""+e).replace(o,t)}var r={"&":"&amp;",">":"&gt;","<":"&lt;",'"':"&quot;","'":"&#x27;"},o=/[&><"']/g;e.exports=n},function(e,t,n){"use strict";function r(e){return l.hasOwnProperty(e)?!0:c.hasOwnProperty(e)?!1:u.test(e)?(l[e]=!0,!0):(c[e]=!0,!1)}function o(e,t){return null==t||e.hasBooleanValue&&!t||e.hasNumericValue&&isNaN(t)||e.hasPositiveNumericValue&&1>t||e.hasOverloadedBooleanValue&&t===!1}var i=n(238),a=n(233),s=n(239),u=(n(240),/^[a-zA-Z_][\w\.\-]*$/),c={},l={},p={createMarkupForID:function(e){return i.ID_ATTRIBUTE_NAME+"="+s(e)},setAttributeForID:function(e,t){e.setAttribute(i.ID_ATTRIBUTE_NAME,t)},createMarkupForProperty:function(e,t){var n=i.properties.hasOwnProperty(e)?i.properties[e]:null;if(n){if(o(n,t))return"";var r=n.attributeName;return n.hasBooleanValue||n.hasOverloadedBooleanValue&&t===!0?r+'=""':r+"="+s(t)}return i.isCustomAttribute(e)?null==t?"":e+"="+s(t):null},createMarkupForCustomAttribute:function(e,t){return r(e)&&null!=t?e+"="+s(t):""},setValueForProperty:function(e,t,n){var r=i.properties.hasOwnProperty(t)?i.properties[t]:null;if(r){var a=r.mutationMethod;if(a)a(e,n);else if(o(r,n))this.deleteValueForProperty(e,t);else if(r.mustUseAttribute){var s=r.attributeName,u=r.attributeNamespace;u?e.setAttributeNS(u,s,""+n):r.hasBooleanValue||r.hasOverloadedBooleanValue&&n===!0?e.setAttribute(s,""):e.setAttribute(s,""+n)}else{var c=r.propertyName;r.hasSideEffects&&""+e[c]==""+n||(e[c]=n)}}else i.isCustomAttribute(t)&&p.setValueForAttribute(e,t,n)},setValueForAttribute:function(e,t,n){r(t)&&(null==n?e.removeAttribute(t):e.setAttribute(t,""+n))},deleteValueForProperty:function(e,t){var n=i.properties.hasOwnProperty(t)?i.properties[t]:null;if(n){var r=n.mutationMethod;if(r)r(e,void 0);else if(n.mustUseAttribute)e.removeAttribute(n.attributeName);else{var o=n.propertyName,a=i.getDefaultValueForProperty(e.nodeName,o);n.hasSideEffects&&""+e[o]===a||(e[o]=a)}}else i.isCustomAttribute(t)&&e.removeAttribute(t)}};a.measureMethods(p,"DOMPropertyOperations",{setValueForProperty:"setValueForProperty",setValueForAttribute:"setValueForAttribute",deleteValueForProperty:"deleteValueForProperty"}),e.exports=p},function(e,t,n){"use strict";function r(e,t){return(e&t)===t}var o=n(228),i={MUST_USE_ATTRIBUTE:1,MUST_USE_PROPERTY:2,HAS_SIDE_EFFECTS:4,HAS_BOOLEAN_VALUE:8,HAS_NUMERIC_VALUE:16,HAS_POSITIVE_NUMERIC_VALUE:48,HAS_OVERLOADED_BOOLEAN_VALUE:64,injectDOMPropertyConfig:function(e){var t=i,n=e.Properties||{},a=e.DOMAttributeNamespaces||{},u=e.DOMAttributeNames||{},c=e.DOMPropertyNames||{},l=e.DOMMutationMethods||{};e.isCustomAttribute&&s._isCustomAttributeFunctions.push(e.isCustomAttribute);for(var p in n){s.properties.hasOwnProperty(p)?o(!1):void 0;var f=p.toLowerCase(),h=n[p],d={attributeName:f,attributeNamespace:null,propertyName:p,mutationMethod:null,mustUseAttribute:r(h,t.MUST_USE_ATTRIBUTE),mustUseProperty:r(h,t.MUST_USE_PROPERTY),hasSideEffects:r(h,t.HAS_SIDE_EFFECTS),hasBooleanValue:r(h,t.HAS_BOOLEAN_VALUE),hasNumericValue:r(h,t.HAS_NUMERIC_VALUE),hasPositiveNumericValue:r(h,t.HAS_POSITIVE_NUMERIC_VALUE),hasOverloadedBooleanValue:r(h,t.HAS_OVERLOADED_BOOLEAN_VALUE)};if(d.mustUseAttribute&&d.mustUseProperty?o(!1):void 0,!d.mustUseProperty&&d.hasSideEffects?o(!1):void 0,d.hasBooleanValue+d.hasNumericValue+d.hasOverloadedBooleanValue<=1?void 0:o(!1),u.hasOwnProperty(p)){var v=u[p];d.attributeName=v}a.hasOwnProperty(p)&&(d.attributeNamespace=a[p]),c.hasOwnProperty(p)&&(d.propertyName=c[p]),l.hasOwnProperty(p)&&(d.mutationMethod=l[p]),s.properties[p]=d}}},a={},s={ID_ATTRIBUTE_NAME:"data-reactid",properties:{},getPossibleStandardName:null,_isCustomAttributeFunctions:[],isCustomAttribute:function(e){for(var t=0;t<s._isCustomAttributeFunctions.length;t++){var n=s._isCustomAttributeFunctions[t];if(n(e))return!0}return!1},getDefaultValueForProperty:function(e,t){var n,r=a[e];return r||(a[e]=r={}),t in r||(n=document.createElement(e),r[t]=n[t]),r[t]},injection:i};e.exports=s},function(e,t,n){"use strict";function r(e){return'"'+o(e)+'"'}var o=n(236);e.exports=r},function(e,t,n){"use strict";var r=n(230),o=r;e.exports=o},function(e,t,n){"use strict";var r=n(242),o=n(243),i={processChildrenUpdates:r.dangerouslyProcessChildrenUpdates,replaceNodeWithMarkupByID:r.dangerouslyReplaceNodeWithMarkupByID,unmountIDFromEnvironment:function(e){o.purgeID(e)}};e.exports=i},function(e,t,n){"use strict";var r=n(222),o=n(237),i=n(243),a=n(233),s=n(228),u={dangerouslySetInnerHTML:"`dangerouslySetInnerHTML` must be set using `updateInnerHTMLByID()`.",style:"`style` must be set using `updateStylesByID()`."},c={updatePropertyByID:function(e,t,n){var r=i.getNode(e);u.hasOwnProperty(t)?s(!1):void 0,null!=n?o.setValueForProperty(r,t,n):o.deleteValueForProperty(r,t)},dangerouslyReplaceNodeWithMarkupByID:function(e,t){var n=i.getNode(e);r.dangerouslyReplaceNodeWithMarkup(n,t)},dangerouslyProcessChildrenUpdates:function(e,t){for(var n=0;n<e.length;n++)e[n].parentNode=i.getNode(e[n].parentID);r.processUpdates(e,t)}};a.measureMethods(c,"ReactDOMIDOperations",{dangerouslyReplaceNodeWithMarkupByID:"dangerouslyReplaceNodeWithMarkupByID",dangerouslyProcessChildrenUpdates:"dangerouslyProcessChildrenUpdates"}),e.exports=c},function(e,t,n){"use strict";function r(e,t){for(var n=Math.min(e.length,t.length),r=0;n>r;r++)if(e.charAt(r)!==t.charAt(r))return r;return e.length===t.length?-1:n}function o(e){return e?e.nodeType===H?e.documentElement:e.firstChild:null}function i(e){var t=o(e);return t&&$.getID(t)}function a(e){var t=s(e);if(t)if(B.hasOwnProperty(t)){var n=B[t];n!==e&&(p(n,t)?M(!1):void 0,B[t]=e)}else B[t]=e;return t}function s(e){return e&&e.getAttribute&&e.getAttribute(L)||""}function u(e,t){var n=s(e);n!==t&&delete B[n],e.setAttribute(L,t),B[t]=e}function c(e){return B.hasOwnProperty(e)&&p(B[e],e)||(B[e]=$.findReactNodeByID(e)),B[e]}function l(e){var t=R.get(e)._rootNodeID;return C.isNullComponentID(t)?null:(B.hasOwnProperty(t)&&p(B[t],t)||(B[t]=$.findReactNodeByID(t)),B[t])}function p(e,t){if(e){s(e)!==t?M(!1):void 0;var n=$.findReactContainerForID(t);if(n&&D(n,e))return!0}return!1}function f(e){delete B[e]}function h(e){var t=B[e];return t&&p(t,e)?void(z=t):!1}function d(e){z=null,E.traverseAncestors(e,h);var t=z;return z=null,t}function v(e,t,n,r,o,i){_.useCreateElement&&(i=k({},i),i[W]=n.nodeType===H?n:n.ownerDocument);var a=S.mountComponent(e,t,r,i);e._renderedComponent._topLevelWrapper=e,$._mountImageIntoNode(a,n,o,r)}function m(e,t,n,r,o){var i=j.ReactReconcileTransaction.getPooled(r);i.perform(v,null,e,t,n,i,r,o),j.ReactReconcileTransaction.release(i)}function g(e,t){for(S.unmountComponent(e),t.nodeType===H&&(t=t.documentElement);t.lastChild;)t.removeChild(t.lastChild)}function y(e){var t=i(e);return t?t!==E.getReactRootIDFromNodeID(t):!1}function b(e){for(;e&&e.parentNode!==e;e=e.parentNode)if(1===e.nodeType){var t=s(e);if(t){var n,r=E.getReactRootIDFromNodeID(t),o=e;do if(n=s(o),o=o.parentNode,null==o)return null;while(n!==r);if(o===Q[r])return e}}return null}var x=n(238),w=n(244),_=(n(220),n(256)),P=n(257),C=n(258),E=n(259),R=n(261),T=n(262),O=n(233),S=n(264),N=n(267),j=n(268),k=n(254),I=n(272),D=n(273),A=n(276),M=n(228),F=n(234),U=n(281),L=(n(284),n(240),x.ID_ATTRIBUTE_NAME),B={},q=1,H=9,V=11,W="__ReactMount_ownerDocument$"+Math.random().toString(36).slice(2),K={},Q={},Y=[],z=null,G=function(){};G.prototype.isReactComponent={},G.prototype.render=function(){return this.props};var $={TopLevelWrapper:G,_instancesByReactRootID:K,scrollMonitor:function(e,t){t()},_updateRootComponent:function(e,t,n,r){return $.scrollMonitor(n,function(){N.enqueueElementInternal(e,t),r&&N.enqueueCallbackInternal(e,r)}),e},_registerComponent:function(e,t){!t||t.nodeType!==q&&t.nodeType!==H&&t.nodeType!==V?M(!1):void 0,w.ensureScrollValueMonitoring();var n=$.registerContainer(t);return K[n]=e,n},_renderNewRootComponent:function(e,t,n,r){var o=A(e,null),i=$._registerComponent(o,t);return j.batchedUpdates(m,o,i,t,n,r),o},renderSubtreeIntoContainer:function(e,t,n,r){return null==e||null==e._reactInternalInstance?M(!1):void 0,$._renderSubtreeIntoContainer(e,t,n,r)},_renderSubtreeIntoContainer:function(e,t,n,r){P.isValidElement(t)?void 0:M(!1);var a=new P(G,null,null,null,null,null,t),u=K[i(n)];if(u){var c=u._currentElement,l=c.props;if(U(l,t))return $._updateRootComponent(u,a,n,r)._renderedComponent.getPublicInstance();$.unmountComponentAtNode(n)}var p=o(n),f=p&&!!s(p),h=y(n),d=f&&!u&&!h,v=$._renderNewRootComponent(a,n,d,null!=e?e._reactInternalInstance._processChildContext(e._reactInternalInstance._context):I)._renderedComponent.getPublicInstance();return r&&r.call(v),v},render:function(e,t,n){return $._renderSubtreeIntoContainer(null,e,t,n)},registerContainer:function(e){var t=i(e);return t&&(t=E.getReactRootIDFromNodeID(t)),t||(t=E.createReactRootID()),Q[t]=e,t},unmountComponentAtNode:function(e){!e||e.nodeType!==q&&e.nodeType!==H&&e.nodeType!==V?M(!1):void 0;var t=i(e),n=K[t];if(!n){{var r=(y(e),s(e));r&&r===E.getReactRootIDFromNodeID(r)}return!1}return j.batchedUpdates(g,n,e),delete K[t],delete Q[t],!0},findReactContainerForID:function(e){var t=E.getReactRootIDFromNodeID(e),n=Q[t];return n},findReactNodeByID:function(e){var t=$.findReactContainerForID(e);return $.findComponentRoot(t,e)},getFirstReactDOM:function(e){return b(e)},findComponentRoot:function(e,t){var n=Y,r=0,o=d(t)||e;for(n[0]=o.firstChild,n.length=1;r<n.length;){for(var i,a=n[r++];a;){var s=$.getID(a);s?t===s?i=a:E.isAncestorIDOf(s,t)&&(n.length=r=0,n.push(a.firstChild)):n.push(a.firstChild),a=a.nextSibling}if(i)return n.length=0,i}n.length=0,M(!1)},_mountImageIntoNode:function(e,t,n,i){if(!t||t.nodeType!==q&&t.nodeType!==H&&t.nodeType!==V?M(!1):void 0,n){var a=o(t);if(T.canReuseMarkup(e,a))return;var s=a.getAttribute(T.CHECKSUM_ATTR_NAME);a.removeAttribute(T.CHECKSUM_ATTR_NAME);var u=a.outerHTML;a.setAttribute(T.CHECKSUM_ATTR_NAME,s);{var c=e,l=r(c,u);" (client) "+c.substring(l-20,l+20)+"\n (server) "+u.substring(l-20,l+20)}t.nodeType===H?M(!1):void 0}if(t.nodeType===H?M(!1):void 0,i.useCreateElement){for(;t.lastChild;)t.removeChild(t.lastChild);t.appendChild(e)}else F(t,e)},ownerDocumentContextKey:W,getReactRootID:i,getID:a,setID:u,getNode:c,getNodeFromInstance:l,isValid:p,purgeID:f};O.measureMethods($,"ReactMount",{_renderNewRootComponent:"_renderNewRootComponent",_mountImageIntoNode:"_mountImageIntoNode"}),e.exports=$},function(e,t,n){"use strict";function r(e){return Object.prototype.hasOwnProperty.call(e,m)||(e[m]=d++,f[e[m]]={}),f[e[m]]}var o=n(245),i=n(246),a=n(247),s=n(252),u=n(233),c=n(253),l=n(254),p=n(255),f={},h=!1,d=0,v={topAbort:"abort",topBlur:"blur",topCanPlay:"canplay",topCanPlayThrough:"canplaythrough",topChange:"change",topClick:"click",topCompositionEnd:"compositionend",topCompositionStart:"compositionstart",topCompositionUpdate:"compositionupdate",topContextMenu:"contextmenu",topCopy:"copy",topCut:"cut",topDoubleClick:"dblclick",topDrag:"drag",topDragEnd:"dragend",topDragEnter:"dragenter",topDragExit:"dragexit",topDragLeave:"dragleave",topDragOver:"dragover",topDragStart:"dragstart",topDrop:"drop",topDurationChange:"durationchange",topEmptied:"emptied",topEncrypted:"encrypted",topEnded:"ended",topError:"error",topFocus:"focus",topInput:"input",topKeyDown:"keydown",topKeyPress:"keypress",topKeyUp:"keyup",topLoadedData:"loadeddata",topLoadedMetadata:"loadedmetadata",topLoadStart:"loadstart",topMouseDown:"mousedown",topMouseMove:"mousemove",topMouseOut:"mouseout",topMouseOver:"mouseover",topMouseUp:"mouseup",topPaste:"paste",topPause:"pause",topPlay:"play",topPlaying:"playing",topProgress:"progress",topRateChange:"ratechange",topScroll:"scroll",topSeeked:"seeked",topSeeking:"seeking",topSelectionChange:"selectionchange",topStalled:"stalled",topSuspend:"suspend",topTextInput:"textInput",topTimeUpdate:"timeupdate",topTouchCancel:"touchcancel",topTouchEnd:"touchend",topTouchMove:"touchmove",topTouchStart:"touchstart",topVolumeChange:"volumechange",topWaiting:"waiting",topWheel:"wheel"},m="_reactListenersID"+String(Math.random()).slice(2),g=l({},s,{ReactEventListener:null,injection:{injectReactEventListener:function(e){e.setHandleTopLevel(g.handleTopLevel),g.ReactEventListener=e}},setEnabled:function(e){g.ReactEventListener&&g.ReactEventListener.setEnabled(e)},isEnabled:function(){return!(!g.ReactEventListener||!g.ReactEventListener.isEnabled())},listenTo:function(e,t){for(var n=t,i=r(n),s=a.registrationNameDependencies[e],u=o.topLevelTypes,c=0;c<s.length;c++){var l=s[c];i.hasOwnProperty(l)&&i[l]||(l===u.topWheel?p("wheel")?g.ReactEventListener.trapBubbledEvent(u.topWheel,"wheel",n):p("mousewheel")?g.ReactEventListener.trapBubbledEvent(u.topWheel,"mousewheel",n):g.ReactEventListener.trapBubbledEvent(u.topWheel,"DOMMouseScroll",n):l===u.topScroll?p("scroll",!0)?g.ReactEventListener.trapCapturedEvent(u.topScroll,"scroll",n):g.ReactEventListener.trapBubbledEvent(u.topScroll,"scroll",g.ReactEventListener.WINDOW_HANDLE):l===u.topFocus||l===u.topBlur?(p("focus",!0)?(g.ReactEventListener.trapCapturedEvent(u.topFocus,"focus",n),g.ReactEventListener.trapCapturedEvent(u.topBlur,"blur",n)):p("focusin")&&(g.ReactEventListener.trapBubbledEvent(u.topFocus,"focusin",n),g.ReactEventListener.trapBubbledEvent(u.topBlur,"focusout",n)),i[u.topBlur]=!0,i[u.topFocus]=!0):v.hasOwnProperty(l)&&g.ReactEventListener.trapBubbledEvent(l,v[l],n),i[l]=!0)}},trapBubbledEvent:function(e,t,n){return g.ReactEventListener.trapBubbledEvent(e,t,n)},trapCapturedEvent:function(e,t,n){return g.ReactEventListener.trapCapturedEvent(e,t,n)},ensureScrollValueMonitoring:function(){if(!h){var e=c.refreshScrollValues;g.ReactEventListener.monitorScrollValue(e),h=!0}},eventNameDispatchConfigs:i.eventNameDispatchConfigs,registrationNameModules:i.registrationNameModules,putListener:i.putListener,getListener:i.getListener,deleteListener:i.deleteListener,deleteAllListeners:i.deleteAllListeners});u.measureMethods(g,"ReactBrowserEventEmitter",{putListener:"putListener",deleteListener:"deleteListener"}),e.exports=g},function(e,t,n){"use strict";var r=n(232),o=r({bubbled:null,captured:null}),i=r({topAbort:null,topBlur:null,topCanPlay:null,topCanPlayThrough:null,topChange:null,topClick:null,topCompositionEnd:null,topCompositionStart:null,topCompositionUpdate:null,topContextMenu:null,topCopy:null,topCut:null,topDoubleClick:null,topDrag:null,topDragEnd:null,topDragEnter:null,topDragExit:null,topDragLeave:null,topDragOver:null,topDragStart:null,topDrop:null,topDurationChange:null,topEmptied:null,topEncrypted:null,topEnded:null,topError:null,topFocus:null,topInput:null,topKeyDown:null,topKeyPress:null,topKeyUp:null,topLoad:null,topLoadedData:null,topLoadedMetadata:null,topLoadStart:null,topMouseDown:null,topMouseMove:null,topMouseOut:null,topMouseOver:null,topMouseUp:null,topPaste:null,topPause:null,topPlay:null,topPlaying:null,topProgress:null,topRateChange:null,topReset:null,topScroll:null,topSeeked:null,topSeeking:null,topSelectionChange:null,topStalled:null,topSubmit:null,topSuspend:null,topTextInput:null,topTimeUpdate:null,topTouchCancel:null,topTouchEnd:null,topTouchMove:null,topTouchStart:null,topVolumeChange:null,topWaiting:null,topWheel:null}),a={topLevelTypes:i,PropagationPhases:o};e.exports=a},function(e,t,n){"use strict";var r=n(247),o=n(248),i=n(249),a=n(250),s=n(251),u=n(228),c=(n(240),{}),l=null,p=function(e,t){e&&(o.executeDispatchesInOrder(e,t),e.isPersistent()||e.constructor.release(e))},f=function(e){return p(e,!0)},h=function(e){return p(e,!1)},d=null,v={injection:{injectMount:o.injection.injectMount,injectInstanceHandle:function(e){d=e},getInstanceHandle:function(){return d},injectEventPluginOrder:r.injectEventPluginOrder,injectEventPluginsByName:r.injectEventPluginsByName},eventNameDispatchConfigs:r.eventNameDispatchConfigs,registrationNameModules:r.registrationNameModules,putListener:function(e,t,n){"function"!=typeof n?u(!1):void 0;var o=c[t]||(c[t]={});o[e]=n;var i=r.registrationNameModules[t];i&&i.didPutListener&&i.didPutListener(e,t,n)},getListener:function(e,t){var n=c[t];return n&&n[e]},deleteListener:function(e,t){var n=r.registrationNameModules[t];n&&n.willDeleteListener&&n.willDeleteListener(e,t);var o=c[t];o&&delete o[e]},deleteAllListeners:function(e){for(var t in c)if(c[t][e]){var n=r.registrationNameModules[t];n&&n.willDeleteListener&&n.willDeleteListener(e,t),delete c[t][e]}},extractEvents:function(e,t,n,o,i){for(var s,u=r.plugins,c=0;c<u.length;c++){var l=u[c];if(l){var p=l.extractEvents(e,t,n,o,i);p&&(s=a(s,p))}}return s},enqueueEvents:function(e){e&&(l=a(l,e))},processEventQueue:function(e){var t=l;l=null,e?s(t,f):s(t,h),l?u(!1):void 0,i.rethrowCaughtError()},__purge:function(){c={}},__getListenerBank:function(){return c}};e.exports=v},function(e,t,n){"use strict";function r(){if(s)for(var e in u){var t=u[e],n=s.indexOf(e);if(n>-1?void 0:a(!1),!c.plugins[n]){t.extractEvents?void 0:a(!1),c.plugins[n]=t;var r=t.eventTypes;for(var i in r)o(r[i],t,i)?void 0:a(!1)}}}function o(e,t,n){c.eventNameDispatchConfigs.hasOwnProperty(n)?a(!1):void 0,c.eventNameDispatchConfigs[n]=e;var r=e.phasedRegistrationNames;if(r){for(var o in r)if(r.hasOwnProperty(o)){var s=r[o];i(s,t,n)}return!0}return e.registrationName?(i(e.registrationName,t,n),!0):!1}function i(e,t,n){c.registrationNameModules[e]?a(!1):void 0,c.registrationNameModules[e]=t,c.registrationNameDependencies[e]=t.eventTypes[n].dependencies}var a=n(228),s=null,u={},c={plugins:[],eventNameDispatchConfigs:{},registrationNameModules:{},registrationNameDependencies:{},injectEventPluginOrder:function(e){s?a(!1):void 0,s=Array.prototype.slice.call(e),r()},injectEventPluginsByName:function(e){var t=!1;for(var n in e)if(e.hasOwnProperty(n)){var o=e[n];u.hasOwnProperty(n)&&u[n]===o||(u[n]?a(!1):void 0,u[n]=o,t=!0)}t&&r()},getPluginModuleForEvent:function(e){var t=e.dispatchConfig;if(t.registrationName)return c.registrationNameModules[t.registrationName]||null;for(var n in t.phasedRegistrationNames)if(t.phasedRegistrationNames.hasOwnProperty(n)){var r=c.registrationNameModules[t.phasedRegistrationNames[n]];if(r)return r}return null},_resetEventPlugins:function(){s=null;for(var e in u)u.hasOwnProperty(e)&&delete u[e];c.plugins.length=0;var t=c.eventNameDispatchConfigs;for(var n in t)t.hasOwnProperty(n)&&delete t[n];var r=c.registrationNameModules;for(var o in r)r.hasOwnProperty(o)&&delete r[o]}};e.exports=c},function(e,t,n){"use strict";function r(e){return e===m.topMouseUp||e===m.topTouchEnd||e===m.topTouchCancel}function o(e){return e===m.topMouseMove||e===m.topTouchMove}function i(e){return e===m.topMouseDown||e===m.topTouchStart}function a(e,t,n,r){var o=e.type||"unknown-event";e.currentTarget=v.Mount.getNode(r),t?h.invokeGuardedCallbackWithCatch(o,n,e,r):h.invokeGuardedCallback(o,n,e,r),e.currentTarget=null}function s(e,t){var n=e._dispatchListeners,r=e._dispatchIDs;if(Array.isArray(n))for(var o=0;o<n.length&&!e.isPropagationStopped();o++)a(e,t,n[o],r[o]);else n&&a(e,t,n,r);e._dispatchListeners=null,e._dispatchIDs=null}function u(e){var t=e._dispatchListeners,n=e._dispatchIDs;if(Array.isArray(t)){for(var r=0;r<t.length&&!e.isPropagationStopped();r++)if(t[r](e,n[r]))return n[r]}else if(t&&t(e,n))return n;return null}function c(e){var t=u(e);return e._dispatchIDs=null,e._dispatchListeners=null,t}function l(e){var t=e._dispatchListeners,n=e._dispatchIDs;Array.isArray(t)?d(!1):void 0;var r=t?t(e,n):null;return e._dispatchListeners=null,e._dispatchIDs=null,r}function p(e){return!!e._dispatchListeners}var f=n(245),h=n(249),d=n(228),v=(n(240),{Mount:null,injectMount:function(e){v.Mount=e}}),m=f.topLevelTypes,g={isEndish:r,isMoveish:o,isStartish:i,executeDirectDispatch:l,executeDispatchesInOrder:s,executeDispatchesInOrderStopAtTrue:c,hasDispatches:p,getNode:function(e){return v.Mount.getNode(e)},getID:function(e){return v.Mount.getID(e)},injection:v};e.exports=g},function(e){"use strict";function t(e,t,r,o){try{return t(r,o)}catch(i){return void(null===n&&(n=i))}}var n=null,r={invokeGuardedCallback:t,invokeGuardedCallbackWithCatch:t,rethrowCaughtError:function(){if(n){var e=n;throw n=null,e}}};e.exports=r},function(e,t,n){"use strict";function r(e,t){if(null==t?o(!1):void 0,null==e)return t;var n=Array.isArray(e),r=Array.isArray(t);return n&&r?(e.push.apply(e,t),e):n?(e.push(t),e):r?[e].concat(t):[e,t]}var o=n(228);e.exports=r},function(e){"use strict";var t=function(e,t,n){Array.isArray(e)?e.forEach(t,n):e&&t.call(n,e)};e.exports=t},function(e,t,n){"use strict";function r(e){o.enqueueEvents(e),o.processEventQueue(!1)}var o=n(246),i={handleTopLevel:function(e,t,n,i,a){var s=o.extractEvents(e,t,n,i,a);r(s)}};e.exports=i},function(e){"use strict";var t={currentScrollLeft:0,currentScrollTop:0,refreshScrollValues:function(e){t.currentScrollLeft=e.x,t.currentScrollTop=e.y}};e.exports=t},function(e){"use strict";function t(e){if(null==e)throw new TypeError("Object.assign target cannot be null or undefined");for(var t=Object(e),n=Object.prototype.hasOwnProperty,r=1;r<arguments.length;r++){var o=arguments[r];if(null!=o){var i=Object(o);for(var a in i)n.call(i,a)&&(t[a]=i[a])}}return t}e.exports=t},function(e,t,n){"use strict";function r(e,t){if(!i.canUseDOM||t&&!("addEventListener"in document))return!1;var n="on"+e,r=n in document;if(!r){var a=document.createElement("div");a.setAttribute(n,"return;"),r="function"==typeof a[n]}return!r&&o&&"wheel"===e&&(r=document.implementation.hasFeature("Events.wheel","3.0")),r}var o,i=n(224);i.canUseDOM&&(o=document.implementation&&document.implementation.hasFeature&&document.implementation.hasFeature("","")!==!0),e.exports=r},function(e){"use strict";var t={useCreateElement:!1};e.exports=t},function(e,t,n){"use strict";var r=n(220),o=n(254),i="function"==typeof Symbol&&Symbol["for"]&&Symbol["for"]("react.element")||60103,a={key:!0,ref:!0,__self:!0,__source:!0},s=function(e,t,n,r,o,a,s){var u={$$typeof:i,type:e,key:t,ref:n,props:s,_owner:a};return u};s.createElement=function(e,t,n){var o,i={},u=null,c=null,l=null,p=null;if(null!=t){c=void 0===t.ref?null:t.ref,u=void 0===t.key?null:""+t.key,l=void 0===t.__self?null:t.__self,p=void 0===t.__source?null:t.__source;for(o in t)t.hasOwnProperty(o)&&!a.hasOwnProperty(o)&&(i[o]=t[o])}var f=arguments.length-2;if(1===f)i.children=n;else if(f>1){for(var h=Array(f),d=0;f>d;d++)h[d]=arguments[d+2];i.children=h}if(e&&e.defaultProps){var v=e.defaultProps;for(o in v)"undefined"==typeof i[o]&&(i[o]=v[o])}return s(e,u,c,l,p,r.current,i)},s.createFactory=function(e){var t=s.createElement.bind(null,e);return t.type=e,t},s.cloneAndReplaceKey=function(e,t){ var n=s(e.type,t,e.ref,e._self,e._source,e._owner,e.props);return n},s.cloneAndReplaceProps=function(e,t){var n=s(e.type,e.key,e.ref,e._self,e._source,e._owner,t);return n},s.cloneElement=function(e,t,n){var i,u=o({},e.props),c=e.key,l=e.ref,p=e._self,f=e._source,h=e._owner;if(null!=t){void 0!==t.ref&&(l=t.ref,h=r.current),void 0!==t.key&&(c=""+t.key);for(i in t)t.hasOwnProperty(i)&&!a.hasOwnProperty(i)&&(u[i]=t[i])}var d=arguments.length-2;if(1===d)u.children=n;else if(d>1){for(var v=Array(d),m=0;d>m;m++)v[m]=arguments[m+2];u.children=v}return s(e.type,c,l,p,f,h,u)},s.isValidElement=function(e){return"object"==typeof e&&null!==e&&e.$$typeof===i},e.exports=s},function(e){"use strict";function t(e){return!!o[e]}function n(e){o[e]=!0}function r(e){delete o[e]}var o={},i={isNullComponentID:t,registerNullComponentID:n,deregisterNullComponentID:r};e.exports=i},function(e,t,n){"use strict";function r(e){return h+e.toString(36)}function o(e,t){return e.charAt(t)===h||t===e.length}function i(e){return""===e||e.charAt(0)===h&&e.charAt(e.length-1)!==h}function a(e,t){return 0===t.indexOf(e)&&o(t,e.length)}function s(e){return e?e.substr(0,e.lastIndexOf(h)):""}function u(e,t){if(i(e)&&i(t)?void 0:f(!1),a(e,t)?void 0:f(!1),e===t)return e;var n,r=e.length+d;for(n=r;n<t.length&&!o(t,n);n++);return t.substr(0,n)}function c(e,t){var n=Math.min(e.length,t.length);if(0===n)return"";for(var r=0,a=0;n>=a;a++)if(o(e,a)&&o(t,a))r=a;else if(e.charAt(a)!==t.charAt(a))break;var s=e.substr(0,r);return i(s)?void 0:f(!1),s}function l(e,t,n,r,o,i){e=e||"",t=t||"",e===t?f(!1):void 0;var c=a(t,e);c||a(e,t)?void 0:f(!1);for(var l=0,p=c?s:u,h=e;;h=p(h,t)){var d;if(o&&h===e||i&&h===t||(d=n(h,c,r)),d===!1||h===t)break;l++<v?void 0:f(!1)}}var p=n(260),f=n(228),h=".",d=h.length,v=1e4,m={createReactRootID:function(){return r(p.createReactRootIndex())},createReactID:function(e,t){return e+t},getReactRootIDFromNodeID:function(e){if(e&&e.charAt(0)===h&&e.length>1){var t=e.indexOf(h,1);return t>-1?e.substr(0,t):e}return null},traverseEnterLeave:function(e,t,n,r,o){var i=c(e,t);i!==e&&l(e,i,n,r,!1,!0),i!==t&&l(i,t,n,o,!0,!1)},traverseTwoPhase:function(e,t,n){e&&(l("",e,t,n,!0,!1),l(e,"",t,n,!1,!0))},traverseTwoPhaseSkipTarget:function(e,t,n){e&&(l("",e,t,n,!0,!0),l(e,"",t,n,!0,!0))},traverseAncestors:function(e,t,n){l("",e,t,n,!0,!1)},getFirstCommonAncestorID:c,_getNextDescendantID:u,isAncestorIDOf:a,SEPARATOR:h};e.exports=m},function(e){"use strict";var t={injectCreateReactRootIndex:function(e){n.createReactRootIndex=e}},n={createReactRootIndex:null,injection:t};e.exports=n},function(e){"use strict";var t={remove:function(e){e._reactInternalInstance=void 0},get:function(e){return e._reactInternalInstance},has:function(e){return void 0!==e._reactInternalInstance},set:function(e,t){e._reactInternalInstance=t}};e.exports=t},function(e,t,n){"use strict";var r=n(263),o=/\/?>/,i={CHECKSUM_ATTR_NAME:"data-react-checksum",addChecksumToMarkup:function(e){var t=r(e);return e.replace(o," "+i.CHECKSUM_ATTR_NAME+'="'+t+'"$&')},canReuseMarkup:function(e,t){var n=t.getAttribute(i.CHECKSUM_ATTR_NAME);n=n&&parseInt(n,10);var o=r(e);return o===n}};e.exports=i},function(e){"use strict";function t(e){for(var t=1,r=0,o=0,i=e.length,a=-4&i;a>o;){for(;o<Math.min(o+4096,a);o+=4)r+=(t+=e.charCodeAt(o))+(t+=e.charCodeAt(o+1))+(t+=e.charCodeAt(o+2))+(t+=e.charCodeAt(o+3));t%=n,r%=n}for(;i>o;o++)r+=t+=e.charCodeAt(o);return t%=n,r%=n,t|r<<16}var n=65521;e.exports=t},function(e,t,n){"use strict";function r(){o.attachRefs(this,this._currentElement)}var o=n(265),i={mountComponent:function(e,t,n,o){var i=e.mountComponent(t,n,o);return e._currentElement&&null!=e._currentElement.ref&&n.getReactMountReady().enqueue(r,e),i},unmountComponent:function(e){o.detachRefs(e,e._currentElement),e.unmountComponent()},receiveComponent:function(e,t,n,i){var a=e._currentElement;if(t!==a||i!==e._context){var s=o.shouldUpdateRefs(a,t);s&&o.detachRefs(e,a),e.receiveComponent(t,n,i),s&&e._currentElement&&null!=e._currentElement.ref&&n.getReactMountReady().enqueue(r,e)}},performUpdateIfNecessary:function(e,t){e.performUpdateIfNecessary(t)}};e.exports=i},function(e,t,n){"use strict";function r(e,t,n){"function"==typeof e?e(t.getPublicInstance()):i.addComponentAsRefTo(t,e,n)}function o(e,t,n){"function"==typeof e?e(null):i.removeComponentAsRefFrom(t,e,n)}var i=n(266),a={};a.attachRefs=function(e,t){if(null!==t&&t!==!1){var n=t.ref;null!=n&&r(n,e,t._owner)}},a.shouldUpdateRefs=function(e,t){var n=null===e||e===!1,r=null===t||t===!1;return n||r||t._owner!==e._owner||t.ref!==e.ref},a.detachRefs=function(e,t){if(null!==t&&t!==!1){var n=t.ref;null!=n&&o(n,e,t._owner)}},e.exports=a},function(e,t,n){"use strict";var r=n(228),o={isValidOwner:function(e){return!(!e||"function"!=typeof e.attachRef||"function"!=typeof e.detachRef)},addComponentAsRefTo:function(e,t,n){o.isValidOwner(n)?void 0:r(!1),n.attachRef(t,e)},removeComponentAsRefFrom:function(e,t,n){o.isValidOwner(n)?void 0:r(!1),n.getPublicInstance().refs[t]===e.getPublicInstance()&&n.detachRef(t)}};e.exports=o},function(e,t,n){"use strict";function r(e){s.enqueueUpdate(e)}function o(e,t){var n=a.get(e);return n?n:null}var i=(n(220),n(257)),a=n(261),s=n(268),u=n(254),c=n(228),l=(n(240),{isMounted:function(e){var t=a.get(e);return t?!!t._renderedComponent:!1},enqueueCallback:function(e,t){"function"!=typeof t?c(!1):void 0;var n=o(e);return n?(n._pendingCallbacks?n._pendingCallbacks.push(t):n._pendingCallbacks=[t],void r(n)):null},enqueueCallbackInternal:function(e,t){"function"!=typeof t?c(!1):void 0,e._pendingCallbacks?e._pendingCallbacks.push(t):e._pendingCallbacks=[t],r(e)},enqueueForceUpdate:function(e){var t=o(e,"forceUpdate");t&&(t._pendingForceUpdate=!0,r(t))},enqueueReplaceState:function(e,t){var n=o(e,"replaceState");n&&(n._pendingStateQueue=[t],n._pendingReplaceState=!0,r(n))},enqueueSetState:function(e,t){var n=o(e,"setState");if(n){var i=n._pendingStateQueue||(n._pendingStateQueue=[]);i.push(t),r(n)}},enqueueSetProps:function(e,t){var n=o(e,"setProps");n&&l.enqueueSetPropsInternal(n,t)},enqueueSetPropsInternal:function(e,t){var n=e._topLevelWrapper;n?void 0:c(!1);var o=n._pendingElement||n._currentElement,a=o.props,s=u({},a.props,t);n._pendingElement=i.cloneAndReplaceProps(o,i.cloneAndReplaceProps(a,s)),r(n)},enqueueReplaceProps:function(e,t){var n=o(e,"replaceProps");n&&l.enqueueReplacePropsInternal(n,t)},enqueueReplacePropsInternal:function(e,t){var n=e._topLevelWrapper;n?void 0:c(!1);var o=n._pendingElement||n._currentElement,a=o.props;n._pendingElement=i.cloneAndReplaceProps(o,i.cloneAndReplaceProps(a,t)),r(n)},enqueueElementInternal:function(e,t){e._pendingElement=t,r(e)}});e.exports=l},function(e,t,n){"use strict";function r(){R.ReactReconcileTransaction&&x?void 0:m(!1)}function o(){this.reinitializeTransaction(),this.dirtyComponentsLength=null,this.callbackQueue=l.getPooled(),this.reconcileTransaction=R.ReactReconcileTransaction.getPooled(!1)}function i(e,t,n,o,i,a){r(),x.batchedUpdates(e,t,n,o,i,a)}function a(e,t){return e._mountOrder-t._mountOrder}function s(e){var t=e.dirtyComponentsLength;t!==g.length?m(!1):void 0,g.sort(a);for(var n=0;t>n;n++){var r=g[n],o=r._pendingCallbacks;if(r._pendingCallbacks=null,h.performUpdateIfNecessary(r,e.reconcileTransaction),o)for(var i=0;i<o.length;i++)e.callbackQueue.enqueue(o[i],r.getPublicInstance())}}function u(e){return r(),x.isBatchingUpdates?void g.push(e):void x.batchedUpdates(u,e)}function c(e,t){x.isBatchingUpdates?void 0:m(!1),y.enqueue(e,t),b=!0}var l=n(269),p=n(270),f=n(233),h=n(264),d=n(271),v=n(254),m=n(228),g=[],y=l.getPooled(),b=!1,x=null,w={initialize:function(){this.dirtyComponentsLength=g.length},close:function(){this.dirtyComponentsLength!==g.length?(g.splice(0,this.dirtyComponentsLength),C()):g.length=0}},_={initialize:function(){this.callbackQueue.reset()},close:function(){this.callbackQueue.notifyAll()}},P=[w,_];v(o.prototype,d.Mixin,{getTransactionWrappers:function(){return P},destructor:function(){this.dirtyComponentsLength=null,l.release(this.callbackQueue),this.callbackQueue=null,R.ReactReconcileTransaction.release(this.reconcileTransaction),this.reconcileTransaction=null},perform:function(e,t,n){return d.Mixin.perform.call(this,this.reconcileTransaction.perform,this.reconcileTransaction,e,t,n)}}),p.addPoolingTo(o);var C=function(){for(;g.length||b;){if(g.length){var e=o.getPooled();e.perform(s,null,e),o.release(e)}if(b){b=!1;var t=y;y=l.getPooled(),t.notifyAll(),l.release(t)}}};C=f.measure("ReactUpdates","flushBatchedUpdates",C);var E={injectReconcileTransaction:function(e){e?void 0:m(!1),R.ReactReconcileTransaction=e},injectBatchingStrategy:function(e){e?void 0:m(!1),"function"!=typeof e.batchedUpdates?m(!1):void 0,"boolean"!=typeof e.isBatchingUpdates?m(!1):void 0,x=e}},R={ReactReconcileTransaction:null,batchedUpdates:i,enqueueUpdate:u,flushBatchedUpdates:C,injection:E,asap:c};e.exports=R},function(e,t,n){"use strict";function r(){this._callbacks=null,this._contexts=null}var o=n(270),i=n(254),a=n(228);i(r.prototype,{enqueue:function(e,t){this._callbacks=this._callbacks||[],this._contexts=this._contexts||[],this._callbacks.push(e),this._contexts.push(t)},notifyAll:function(){var e=this._callbacks,t=this._contexts;if(e){e.length!==t.length?a(!1):void 0,this._callbacks=null,this._contexts=null;for(var n=0;n<e.length;n++)e[n].call(t[n]);e.length=0,t.length=0}},reset:function(){this._callbacks=null,this._contexts=null},destructor:function(){this.reset()}}),o.addPoolingTo(r),e.exports=r},function(e,t,n){"use strict";var r=n(228),o=function(e){var t=this;if(t.instancePool.length){var n=t.instancePool.pop();return t.call(n,e),n}return new t(e)},i=function(e,t){var n=this;if(n.instancePool.length){var r=n.instancePool.pop();return n.call(r,e,t),r}return new n(e,t)},a=function(e,t,n){var r=this;if(r.instancePool.length){var o=r.instancePool.pop();return r.call(o,e,t,n),o}return new r(e,t,n)},s=function(e,t,n,r){var o=this;if(o.instancePool.length){var i=o.instancePool.pop();return o.call(i,e,t,n,r),i}return new o(e,t,n,r)},u=function(e,t,n,r,o){var i=this;if(i.instancePool.length){var a=i.instancePool.pop();return i.call(a,e,t,n,r,o),a}return new i(e,t,n,r,o)},c=function(e){var t=this;e instanceof t?void 0:r(!1),e.destructor(),t.instancePool.length<t.poolSize&&t.instancePool.push(e)},l=10,p=o,f=function(e,t){var n=e;return n.instancePool=[],n.getPooled=t||p,n.poolSize||(n.poolSize=l),n.release=c,n},h={addPoolingTo:f,oneArgumentPooler:o,twoArgumentPooler:i,threeArgumentPooler:a,fourArgumentPooler:s,fiveArgumentPooler:u};e.exports=h},function(e,t,n){"use strict";var r=n(228),o={reinitializeTransaction:function(){this.transactionWrappers=this.getTransactionWrappers(),this.wrapperInitData?this.wrapperInitData.length=0:this.wrapperInitData=[],this._isInTransaction=!1},_isInTransaction:!1,getTransactionWrappers:null,isInTransaction:function(){return!!this._isInTransaction},perform:function(e,t,n,o,i,a,s,u){this.isInTransaction()?r(!1):void 0;var c,l;try{this._isInTransaction=!0,c=!0,this.initializeAll(0),l=e.call(t,n,o,i,a,s,u),c=!1}finally{try{if(c)try{this.closeAll(0)}catch(p){}else this.closeAll(0)}finally{this._isInTransaction=!1}}return l},initializeAll:function(e){for(var t=this.transactionWrappers,n=e;n<t.length;n++){var r=t[n];try{this.wrapperInitData[n]=i.OBSERVED_ERROR,this.wrapperInitData[n]=r.initialize?r.initialize.call(this):null}finally{if(this.wrapperInitData[n]===i.OBSERVED_ERROR)try{this.initializeAll(n+1)}catch(o){}}}},closeAll:function(e){this.isInTransaction()?void 0:r(!1);for(var t=this.transactionWrappers,n=e;n<t.length;n++){var o,a=t[n],s=this.wrapperInitData[n];try{o=!0,s!==i.OBSERVED_ERROR&&a.close&&a.close.call(this,s),o=!1}finally{if(o)try{this.closeAll(n+1)}catch(u){}}}this.wrapperInitData.length=0}},i={Mixin:o,OBSERVED_ERROR:{}};e.exports=i},function(e){"use strict";var t={};e.exports=t},function(e,t,n){"use strict";function r(e,t){var n=!0;e:for(;n;){var r=e,i=t;if(n=!1,r&&i){if(r===i)return!0;if(o(r))return!1;if(o(i)){e=r,t=i.parentNode,n=!0;continue e}return r.contains?r.contains(i):r.compareDocumentPosition?!!(16&r.compareDocumentPosition(i)):!1}return!1}}var o=n(274);e.exports=r},function(e,t,n){"use strict";function r(e){return o(e)&&3==e.nodeType}var o=n(275);e.exports=r},function(e){"use strict";function t(e){return!(!e||!("function"==typeof Node?e instanceof Node:"object"==typeof e&&"number"==typeof e.nodeType&&"string"==typeof e.nodeName))}e.exports=t},function(e,t,n){"use strict";function r(e){return"function"==typeof e&&"undefined"!=typeof e.prototype&&"function"==typeof e.prototype.mountComponent&&"function"==typeof e.prototype.receiveComponent}function o(e){var t;if(null===e||e===!1)t=new a(o);else if("object"==typeof e){var n=e;!n||"function"!=typeof n.type&&"string"!=typeof n.type?c(!1):void 0,t="string"==typeof n.type?s.createInternalComponent(n):r(n.type)?new n.type(n):new l}else"string"==typeof e||"number"==typeof e?t=s.createInstanceForText(e):c(!1);return t.construct(e),t._mountIndex=0,t._mountImage=null,t}var i=n(277),a=n(282),s=n(283),u=n(254),c=n(228),l=(n(240),function(){});u(l.prototype,i.Mixin,{_instantiateReactComponent:o}),e.exports=o},function(e,t,n){"use strict";function r(e){var t=e._currentElement._owner||null;if(t){var n=t.getName();if(n)return" Check the render method of `"+n+"`."}return""}function o(){}{var i=n(278),a=n(220),s=n(257),u=n(261),c=n(233),l=n(279),p=(n(280),n(264)),f=n(267),h=n(254),d=n(272),v=n(228),m=n(281);n(240)}o.prototype.render=function(){var e=u.get(this)._currentElement.type;return e(this.props,this.context,this.updater)};var g=1,y={construct:function(e){this._currentElement=e,this._rootNodeID=null,this._instance=null,this._pendingElement=null,this._pendingStateQueue=null,this._pendingReplaceState=!1,this._pendingForceUpdate=!1,this._renderedComponent=null,this._context=null,this._mountOrder=0,this._topLevelWrapper=null,this._pendingCallbacks=null},mountComponent:function(e,t,n){this._context=n,this._mountOrder=g++,this._rootNodeID=e;var r,i,a=this._processProps(this._currentElement.props),c=this._processContext(n),l=this._currentElement.type,h="prototype"in l;h&&(r=new l(a,c,f)),(!h||null===r||r===!1||s.isValidElement(r))&&(i=r,r=new o(l)),r.props=a,r.context=c,r.refs=d,r.updater=f,this._instance=r,u.set(r,this);var m=r.state;void 0===m&&(r.state=m=null),"object"!=typeof m||Array.isArray(m)?v(!1):void 0,this._pendingStateQueue=null,this._pendingReplaceState=!1,this._pendingForceUpdate=!1,r.componentWillMount&&(r.componentWillMount(),this._pendingStateQueue&&(r.state=this._processPendingState(r.props,r.context))),void 0===i&&(i=this._renderValidatedComponent()),this._renderedComponent=this._instantiateReactComponent(i);var y=p.mountComponent(this._renderedComponent,e,t,this._processChildContext(n));return r.componentDidMount&&t.getReactMountReady().enqueue(r.componentDidMount,r),y},unmountComponent:function(){var e=this._instance;e.componentWillUnmount&&e.componentWillUnmount(),p.unmountComponent(this._renderedComponent),this._renderedComponent=null,this._instance=null,this._pendingStateQueue=null,this._pendingReplaceState=!1,this._pendingForceUpdate=!1,this._pendingCallbacks=null,this._pendingElement=null,this._context=null,this._rootNodeID=null,this._topLevelWrapper=null,u.remove(e)},_maskContext:function(e){var t=null,n=this._currentElement.type,r=n.contextTypes;if(!r)return d;t={};for(var o in r)t[o]=e[o];return t},_processContext:function(e){var t=this._maskContext(e);return t},_processChildContext:function(e){var t=this._currentElement.type,n=this._instance,r=n.getChildContext&&n.getChildContext();if(r){"object"!=typeof t.childContextTypes?v(!1):void 0;for(var o in r)o in t.childContextTypes?void 0:v(!1);return h({},e,r)}return e},_processProps:function(e){return e},_checkPropTypes:function(e,t,n){var o=this.getName();for(var i in e)if(e.hasOwnProperty(i)){var a;try{"function"!=typeof e[i]?v(!1):void 0,a=e[i](t,i,o,n)}catch(s){a=s}if(a instanceof Error){{r(this)}n===l.prop}}},receiveComponent:function(e,t,n){var r=this._currentElement,o=this._context;this._pendingElement=null,this.updateComponent(t,r,e,o,n)},performUpdateIfNecessary:function(e){null!=this._pendingElement&&p.receiveComponent(this,this._pendingElement||this._currentElement,e,this._context),(null!==this._pendingStateQueue||this._pendingForceUpdate)&&this.updateComponent(e,this._currentElement,this._currentElement,this._context,this._context)},updateComponent:function(e,t,n,r,o){var i,a=this._instance,s=this._context===o?a.context:this._processContext(o);t===n?i=n.props:(i=this._processProps(n.props),a.componentWillReceiveProps&&a.componentWillReceiveProps(i,s));var u=this._processPendingState(i,s),c=this._pendingForceUpdate||!a.shouldComponentUpdate||a.shouldComponentUpdate(i,u,s);c?(this._pendingForceUpdate=!1,this._performComponentUpdate(n,i,u,s,e,o)):(this._currentElement=n,this._context=o,a.props=i,a.state=u,a.context=s)},_processPendingState:function(e,t){var n=this._instance,r=this._pendingStateQueue,o=this._pendingReplaceState;if(this._pendingReplaceState=!1,this._pendingStateQueue=null,!r)return n.state;if(o&&1===r.length)return r[0];for(var i=h({},o?r[0]:n.state),a=o?1:0;a<r.length;a++){var s=r[a];h(i,"function"==typeof s?s.call(n,i,e,t):s)}return i},_performComponentUpdate:function(e,t,n,r,o,i){var a,s,u,c=this._instance,l=Boolean(c.componentDidUpdate);l&&(a=c.props,s=c.state,u=c.context),c.componentWillUpdate&&c.componentWillUpdate(t,n,r),this._currentElement=e,this._context=i,c.props=t,c.state=n,c.context=r,this._updateRenderedComponent(o,i),l&&o.getReactMountReady().enqueue(c.componentDidUpdate.bind(c,a,s,u),c)},_updateRenderedComponent:function(e,t){var n=this._renderedComponent,r=n._currentElement,o=this._renderValidatedComponent();if(m(r,o))p.receiveComponent(n,o,e,this._processChildContext(t));else{var i=this._rootNodeID,a=n._rootNodeID;p.unmountComponent(n),this._renderedComponent=this._instantiateReactComponent(o);var s=p.mountComponent(this._renderedComponent,i,e,this._processChildContext(t));this._replaceNodeWithMarkupByID(a,s)}},_replaceNodeWithMarkupByID:function(e,t){i.replaceNodeWithMarkupByID(e,t)},_renderValidatedComponentWithoutOwnerOrContext:function(){var e=this._instance,t=e.render();return t},_renderValidatedComponent:function(){var e;a.current=this;try{e=this._renderValidatedComponentWithoutOwnerOrContext()}finally{a.current=null}return null===e||e===!1||s.isValidElement(e)?void 0:v(!1),e},attachRef:function(e,t){var n=this.getPublicInstance();null==n?v(!1):void 0;var r=t.getPublicInstance(),o=n.refs===d?n.refs={}:n.refs;o[e]=r},detachRef:function(e){var t=this.getPublicInstance().refs;delete t[e]},getName:function(){var e=this._currentElement.type,t=this._instance&&this._instance.constructor;return e.displayName||t&&t.displayName||e.name||t&&t.name||null},getPublicInstance:function(){var e=this._instance;return e instanceof o?null:e},_instantiateReactComponent:null};c.measureMethods(y,"ReactCompositeComponent",{mountComponent:"mountComponent",updateComponent:"updateComponent",_renderValidatedComponent:"_renderValidatedComponent"});var b={Mixin:y};e.exports=b},function(e,t,n){"use strict";var r=n(228),o=!1,i={unmountIDFromEnvironment:null,replaceNodeWithMarkupByID:null,processChildrenUpdates:null,injection:{injectEnvironment:function(e){o?r(!1):void 0,i.unmountIDFromEnvironment=e.unmountIDFromEnvironment,i.replaceNodeWithMarkupByID=e.replaceNodeWithMarkupByID,i.processChildrenUpdates=e.processChildrenUpdates,o=!0}}};e.exports=i},function(e,t,n){"use strict";var r=n(232),o=r({prop:null,context:null,childContext:null});e.exports=o},function(e){"use strict";var t={};e.exports=t},function(e){"use strict";function t(e,t){var n=null===e||e===!1,r=null===t||t===!1;if(n||r)return n===r;var o=typeof e,i=typeof t;return"string"===o||"number"===o?"string"===i||"number"===i:"object"===i&&e.type===t.type&&e.key===t.key}e.exports=t},function(e,t,n){"use strict";var r,o=n(257),i=n(258),a=n(264),s=n(254),u={injectEmptyComponent:function(e){r=o.createElement(e)}},c=function(e){this._currentElement=null,this._rootNodeID=null,this._renderedComponent=e(r)};s(c.prototype,{construct:function(){},mountComponent:function(e,t,n){return i.registerNullComponentID(e),this._rootNodeID=e,a.mountComponent(this._renderedComponent,e,t,n)},receiveComponent:function(){},unmountComponent:function(){a.unmountComponent(this._renderedComponent),i.deregisterNullComponentID(this._rootNodeID),this._rootNodeID=null,this._renderedComponent=null}}),c.injection=u,e.exports=c},function(e,t,n){"use strict";function r(e){if("function"==typeof e.type)return e.type;var t=e.type,n=p[t];return null==n&&(p[t]=n=c(t)),n}function o(e){return l?void 0:u(!1),new l(e.type,e.props)}function i(e){return new f(e)}function a(e){return e instanceof f}var s=n(254),u=n(228),c=null,l=null,p={},f=null,h={injectGenericComponentClass:function(e){l=e},injectTextComponentClass:function(e){f=e},injectComponentClasses:function(e){s(p,e)}},d={getComponentClassForElement:r,createInternalComponent:o,createInstanceForText:i,isTextComponent:a,injection:h};e.exports=d},function(e,t,n){"use strict";var r=(n(254),n(230)),o=(n(240),r);e.exports=o},function(e,t,n){"use strict";function r(){if(!E){E=!0,g.EventEmitter.injectReactEventListener(m),g.EventPluginHub.injectEventPluginOrder(s),g.EventPluginHub.injectInstanceHandle(y),g.EventPluginHub.injectMount(b),g.EventPluginHub.injectEventPluginsByName({SimpleEventPlugin:P,EnterLeaveEventPlugin:u,ChangeEventPlugin:i,SelectEventPlugin:w,BeforeInputEventPlugin:o}),g.NativeComponent.injectGenericComponentClass(d),g.NativeComponent.injectTextComponentClass(v),g.Class.injectMixin(p),g.DOMProperty.injectDOMPropertyConfig(l),g.DOMProperty.injectDOMPropertyConfig(C),g.EmptyComponent.injectEmptyComponent("noscript"),g.Updates.injectReconcileTransaction(x),g.Updates.injectBatchingStrategy(h),g.RootIndex.injectCreateReactRootIndex(c.canUseDOM?a.createReactRootIndex:_.createReactRootIndex),g.Component.injectEnvironment(f)}}var o=n(286),i=n(294),a=n(297),s=n(298),u=n(299),c=n(224),l=n(303),p=n(304),f=n(241),h=n(306),d=n(307),v=n(221),m=n(332),g=n(335),y=n(259),b=n(243),x=n(339),w=n(344),_=n(345),P=n(346),C=n(355),E=!1;e.exports={inject:r}},function(e,t,n){"use strict";function r(){var e=window.opera;return"object"==typeof e&&"function"==typeof e.version&&parseInt(e.version(),10)<=12}function o(e){return(e.ctrlKey||e.altKey||e.metaKey)&&!(e.ctrlKey&&e.altKey)}function i(e){switch(e){case O.topCompositionStart:return S.compositionStart;case O.topCompositionEnd:return S.compositionEnd;case O.topCompositionUpdate:return S.compositionUpdate}}function a(e,t){return e===O.topKeyDown&&t.keyCode===w}function s(e,t){switch(e){case O.topKeyUp:return-1!==x.indexOf(t.keyCode);case O.topKeyDown:return t.keyCode!==w;case O.topKeyPress:case O.topMouseDown:case O.topBlur:return!0;default:return!1}}function u(e){var t=e.detail;return"object"==typeof t&&"data"in t?t.data:null}function c(e,t,n,r,o){var c,l;if(_?c=i(e):j?s(e,r)&&(c=S.compositionEnd):a(e,r)&&(c=S.compositionStart),!c)return null;E&&(j||c!==S.compositionStart?c===S.compositionEnd&&j&&(l=j.getData()):j=m.getPooled(t));var p=g.getPooled(c,n,r,o);if(l)p.data=l;else{var f=u(r);null!==f&&(p.data=f)}return d.accumulateTwoPhaseDispatches(p),p}function l(e,t){switch(e){case O.topCompositionEnd:return u(t);case O.topKeyPress:var n=t.which;return n!==R?null:(N=!0,T);case O.topTextInput:var r=t.data;return r===T&&N?null:r;default:return null}}function p(e,t){if(j){if(e===O.topCompositionEnd||s(e,t)){var n=j.getData();return m.release(j),j=null,n}return null}switch(e){case O.topPaste:return null;case O.topKeyPress:return t.which&&!o(t)?String.fromCharCode(t.which):null;case O.topCompositionEnd:return E?null:t.data;default:return null}}function f(e,t,n,r,o){var i;if(i=C?l(e,r):p(e,r),!i)return null;var a=y.getPooled(S.beforeInput,n,r,o);return a.data=i,d.accumulateTwoPhaseDispatches(a),a}var h=n(245),d=n(287),v=n(224),m=n(288),g=n(290),y=n(292),b=n(293),x=[9,13,27,32],w=229,_=v.canUseDOM&&"CompositionEvent"in window,P=null;v.canUseDOM&&"documentMode"in document&&(P=document.documentMode);var C=v.canUseDOM&&"TextEvent"in window&&!P&&!r(),E=v.canUseDOM&&(!_||P&&P>8&&11>=P),R=32,T=String.fromCharCode(R),O=h.topLevelTypes,S={beforeInput:{phasedRegistrationNames:{bubbled:b({onBeforeInput:null}),captured:b({onBeforeInputCapture:null})},dependencies:[O.topCompositionEnd,O.topKeyPress,O.topTextInput,O.topPaste]},compositionEnd:{phasedRegistrationNames:{bubbled:b({onCompositionEnd:null}),captured:b({onCompositionEndCapture:null})},dependencies:[O.topBlur,O.topCompositionEnd,O.topKeyDown,O.topKeyPress,O.topKeyUp,O.topMouseDown]},compositionStart:{phasedRegistrationNames:{bubbled:b({onCompositionStart:null}),captured:b({onCompositionStartCapture:null})},dependencies:[O.topBlur,O.topCompositionStart,O.topKeyDown,O.topKeyPress,O.topKeyUp,O.topMouseDown]},compositionUpdate:{phasedRegistrationNames:{bubbled:b({onCompositionUpdate:null}),captured:b({onCompositionUpdateCapture:null})},dependencies:[O.topBlur,O.topCompositionUpdate,O.topKeyDown,O.topKeyPress,O.topKeyUp,O.topMouseDown]}},N=!1,j=null,k={eventTypes:S,extractEvents:function(e,t,n,r,o){return[c(e,t,n,r,o),f(e,t,n,r,o)]}};e.exports=k},function(e,t,n){"use strict";function r(e,t,n){var r=t.dispatchConfig.phasedRegistrationNames[n];return y(e,r)}function o(e,t,n){var o=t?g.bubbled:g.captured,i=r(e,n,o);i&&(n._dispatchListeners=v(n._dispatchListeners,i),n._dispatchIDs=v(n._dispatchIDs,e))}function i(e){e&&e.dispatchConfig.phasedRegistrationNames&&d.injection.getInstanceHandle().traverseTwoPhase(e.dispatchMarker,o,e)}function a(e){e&&e.dispatchConfig.phasedRegistrationNames&&d.injection.getInstanceHandle().traverseTwoPhaseSkipTarget(e.dispatchMarker,o,e)}function s(e,t,n){if(n&&n.dispatchConfig.registrationName){var r=n.dispatchConfig.registrationName,o=y(e,r);o&&(n._dispatchListeners=v(n._dispatchListeners,o),n._dispatchIDs=v(n._dispatchIDs,e))}}function u(e){e&&e.dispatchConfig.registrationName&&s(e.dispatchMarker,null,e)}function c(e){m(e,i)}function l(e){m(e,a)}function p(e,t,n,r){d.injection.getInstanceHandle().traverseEnterLeave(n,r,s,e,t)}function f(e){m(e,u)}var h=n(245),d=n(246),v=(n(240),n(250)),m=n(251),g=h.PropagationPhases,y=d.getListener,b={accumulateTwoPhaseDispatches:c,accumulateTwoPhaseDispatchesSkipTarget:l,accumulateDirectDispatches:f,accumulateEnterLeaveDispatches:p};e.exports=b},function(e,t,n){"use strict";function r(e){this._root=e,this._startText=this.getText(),this._fallbackText=null}var o=n(270),i=n(254),a=n(289);i(r.prototype,{destructor:function(){this._root=null,this._startText=null,this._fallbackText=null},getText:function(){return"value"in this._root?this._root.value:this._root[a()]},getData:function(){if(this._fallbackText)return this._fallbackText;var e,t,n=this._startText,r=n.length,o=this.getText(),i=o.length;for(e=0;r>e&&n[e]===o[e];e++);var a=r-e;for(t=1;a>=t&&n[r-t]===o[i-t];t++);var s=t>1?1-t:void 0;return this._fallbackText=o.slice(e,s),this._fallbackText}}),o.addPoolingTo(r),e.exports=r},function(e,t,n){"use strict";function r(){return!i&&o.canUseDOM&&(i="textContent"in document.documentElement?"textContent":"innerText"),i}var o=n(224),i=null;e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){o.call(this,e,t,n,r)}var o=n(291),i={data:null};o.augmentClass(r,i),e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){this.dispatchConfig=e,this.dispatchMarker=t,this.nativeEvent=n,this.target=r,this.currentTarget=r;var o=this.constructor.Interface;for(var i in o)if(o.hasOwnProperty(i)){var s=o[i];this[i]=s?s(n):n[i]}var u=null!=n.defaultPrevented?n.defaultPrevented:n.returnValue===!1;this.isDefaultPrevented=u?a.thatReturnsTrue:a.thatReturnsFalse,this.isPropagationStopped=a.thatReturnsFalse}var o=n(270),i=n(254),a=n(230),s=(n(240),{type:null,currentTarget:a.thatReturnsNull,eventPhase:null,bubbles:null,cancelable:null,timeStamp:function(e){return e.timeStamp||Date.now()},defaultPrevented:null,isTrusted:null});i(r.prototype,{preventDefault:function(){this.defaultPrevented=!0;var e=this.nativeEvent;e&&(e.preventDefault?e.preventDefault():e.returnValue=!1,this.isDefaultPrevented=a.thatReturnsTrue)},stopPropagation:function(){var e=this.nativeEvent;e&&(e.stopPropagation?e.stopPropagation():e.cancelBubble=!0,this.isPropagationStopped=a.thatReturnsTrue)},persist:function(){this.isPersistent=a.thatReturnsTrue},isPersistent:a.thatReturnsFalse,destructor:function(){var e=this.constructor.Interface;for(var t in e)this[t]=null;this.dispatchConfig=null,this.dispatchMarker=null,this.nativeEvent=null}}),r.Interface=s,r.augmentClass=function(e,t){var n=this,r=Object.create(n.prototype);i(r,e.prototype),e.prototype=r,e.prototype.constructor=e,e.Interface=i({},n.Interface,t),e.augmentClass=n.augmentClass,o.addPoolingTo(e,o.fourArgumentPooler)},o.addPoolingTo(r,o.fourArgumentPooler),e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){o.call(this,e,t,n,r)}var o=n(291),i={data:null};o.augmentClass(r,i),e.exports=r},function(e){"use strict";var t=function(e){var t;for(t in e)if(e.hasOwnProperty(t))return t;return null};e.exports=t},function(e,t,n){"use strict";function r(e){var t=e.nodeName&&e.nodeName.toLowerCase();return"select"===t||"input"===t&&"file"===e.type}function o(e){var t=P.getPooled(S.change,j,e,C(e));x.accumulateTwoPhaseDispatches(t),_.batchedUpdates(i,t)}function i(e){b.enqueueEvents(e),b.processEventQueue(!1)}function a(e,t){N=e,j=t,N.attachEvent("onchange",o)}function s(){N&&(N.detachEvent("onchange",o),N=null,j=null)}function u(e,t,n){return e===O.topChange?n:void 0}function c(e,t,n){e===O.topFocus?(s(),a(t,n)):e===O.topBlur&&s()}function l(e,t){N=e,j=t,k=e.value,I=Object.getOwnPropertyDescriptor(e.constructor.prototype,"value"),Object.defineProperty(N,"value",M),N.attachEvent("onpropertychange",f)}function p(){N&&(delete N.value,N.detachEvent("onpropertychange",f),N=null,j=null,k=null,I=null)}function f(e){if("value"===e.propertyName){var t=e.srcElement.value;t!==k&&(k=t,o(e))}}function h(e,t,n){return e===O.topInput?n:void 0}function d(e,t,n){e===O.topFocus?(p(),l(t,n)):e===O.topBlur&&p()}function v(e){return e!==O.topSelectionChange&&e!==O.topKeyUp&&e!==O.topKeyDown||!N||N.value===k?void 0:(k=N.value,j)}function m(e){return e.nodeName&&"input"===e.nodeName.toLowerCase()&&("checkbox"===e.type||"radio"===e.type)}function g(e,t,n){return e===O.topClick?n:void 0}var y=n(245),b=n(246),x=n(287),w=n(224),_=n(268),P=n(291),C=n(295),E=n(255),R=n(296),T=n(293),O=y.topLevelTypes,S={change:{phasedRegistrationNames:{bubbled:T({onChange:null}),captured:T({onChangeCapture:null})},dependencies:[O.topBlur,O.topChange,O.topClick,O.topFocus,O.topInput,O.topKeyDown,O.topKeyUp,O.topSelectionChange]}},N=null,j=null,k=null,I=null,D=!1;w.canUseDOM&&(D=E("change")&&(!("documentMode"in document)||document.documentMode>8));var A=!1;w.canUseDOM&&(A=E("input")&&(!("documentMode"in document)||document.documentMode>9));var M={get:function(){return I.get.call(this)},set:function(e){k=""+e,I.set.call(this,e)}},F={eventTypes:S,extractEvents:function(e,t,n,o,i){var a,s;if(r(t)?D?a=u:s=c:R(t)?A?a=h:(a=v,s=d):m(t)&&(a=g),a){var l=a(e,t,n);if(l){var p=P.getPooled(S.change,l,o,i);return p.type="change",x.accumulateTwoPhaseDispatches(p),p}}s&&s(e,t,n)}};e.exports=F},function(e){"use strict";function t(e){var t=e.target||e.srcElement||window;return 3===t.nodeType?t.parentNode:t}e.exports=t},function(e){"use strict";function t(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&("input"===t&&n[e.type]||"textarea"===t)}var n={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};e.exports=t},function(e){"use strict";var t=0,n={createReactRootIndex:function(){return t++}};e.exports=n},function(e,t,n){"use strict";var r=n(293),o=[r({ResponderEventPlugin:null}),r({SimpleEventPlugin:null}),r({TapEventPlugin:null}),r({EnterLeaveEventPlugin:null }),r({ChangeEventPlugin:null}),r({SelectEventPlugin:null}),r({BeforeInputEventPlugin:null})];e.exports=o},function(e,t,n){"use strict";var r=n(245),o=n(287),i=n(300),a=n(243),s=n(293),u=r.topLevelTypes,c=a.getFirstReactDOM,l={mouseEnter:{registrationName:s({onMouseEnter:null}),dependencies:[u.topMouseOut,u.topMouseOver]},mouseLeave:{registrationName:s({onMouseLeave:null}),dependencies:[u.topMouseOut,u.topMouseOver]}},p=[null,null],f={eventTypes:l,extractEvents:function(e,t,n,r,s){if(e===u.topMouseOver&&(r.relatedTarget||r.fromElement))return null;if(e!==u.topMouseOut&&e!==u.topMouseOver)return null;var f;if(t.window===t)f=t;else{var h=t.ownerDocument;f=h?h.defaultView||h.parentWindow:window}var d,v,m="",g="";if(e===u.topMouseOut?(d=t,m=n,v=c(r.relatedTarget||r.toElement),v?g=a.getID(v):v=f,v=v||f):(d=f,v=t,g=n),d===v)return null;var y=i.getPooled(l.mouseLeave,m,r,s);y.type="mouseleave",y.target=d,y.relatedTarget=v;var b=i.getPooled(l.mouseEnter,g,r,s);return b.type="mouseenter",b.target=v,b.relatedTarget=d,o.accumulateEnterLeaveDispatches(y,b,m,g),p[0]=y,p[1]=b,p}};e.exports=f},function(e,t,n){"use strict";function r(e,t,n,r){o.call(this,e,t,n,r)}var o=n(301),i=n(253),a=n(302),s={screenX:null,screenY:null,clientX:null,clientY:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,getModifierState:a,button:function(e){var t=e.button;return"which"in e?t:2===t?2:4===t?1:0},buttons:null,relatedTarget:function(e){return e.relatedTarget||(e.fromElement===e.srcElement?e.toElement:e.fromElement)},pageX:function(e){return"pageX"in e?e.pageX:e.clientX+i.currentScrollLeft},pageY:function(e){return"pageY"in e?e.pageY:e.clientY+i.currentScrollTop}};o.augmentClass(r,s),e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){o.call(this,e,t,n,r)}var o=n(291),i=n(295),a={view:function(e){if(e.view)return e.view;var t=i(e);if(null!=t&&t.window===t)return t;var n=t.ownerDocument;return n?n.defaultView||n.parentWindow:window},detail:function(e){return e.detail||0}};o.augmentClass(r,a),e.exports=r},function(e){"use strict";function t(e){var t=this,n=t.nativeEvent;if(n.getModifierState)return n.getModifierState(e);var o=r[e];return o?!!n[o]:!1}function n(){return t}var r={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};e.exports=n},function(e,t,n){"use strict";var r,o=n(238),i=n(224),a=o.injection.MUST_USE_ATTRIBUTE,s=o.injection.MUST_USE_PROPERTY,u=o.injection.HAS_BOOLEAN_VALUE,c=o.injection.HAS_SIDE_EFFECTS,l=o.injection.HAS_NUMERIC_VALUE,p=o.injection.HAS_POSITIVE_NUMERIC_VALUE,f=o.injection.HAS_OVERLOADED_BOOLEAN_VALUE;if(i.canUseDOM){var h=document.implementation;r=h&&h.hasFeature&&h.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure","1.1")}var d={isCustomAttribute:RegExp.prototype.test.bind(/^(data|aria)-[a-z_][a-z\d_.\-]*$/),Properties:{accept:null,acceptCharset:null,accessKey:null,action:null,allowFullScreen:a|u,allowTransparency:a,alt:null,async:u,autoComplete:null,autoPlay:u,capture:a|u,cellPadding:null,cellSpacing:null,charSet:a,challenge:a,checked:s|u,classID:a,className:r?a:s,cols:a|p,colSpan:null,content:null,contentEditable:null,contextMenu:a,controls:s|u,coords:null,crossOrigin:null,data:null,dateTime:a,defer:u,dir:null,disabled:a|u,download:f,draggable:null,encType:null,form:a,formAction:a,formEncType:a,formMethod:a,formNoValidate:u,formTarget:a,frameBorder:a,headers:null,height:a,hidden:a|u,high:null,href:null,hrefLang:null,htmlFor:null,httpEquiv:null,icon:null,id:s,inputMode:a,is:a,keyParams:a,keyType:a,label:null,lang:null,list:a,loop:s|u,low:null,manifest:a,marginHeight:null,marginWidth:null,max:null,maxLength:a,media:a,mediaGroup:null,method:null,min:null,minLength:a,multiple:s|u,muted:s|u,name:null,noValidate:u,open:u,optimum:null,pattern:null,placeholder:null,poster:null,preload:null,radioGroup:null,readOnly:s|u,rel:null,required:u,role:a,rows:a|p,rowSpan:null,sandbox:null,scope:null,scoped:u,scrolling:null,seamless:a|u,selected:s|u,shape:null,size:a|p,sizes:a,span:p,spellCheck:null,src:null,srcDoc:s,srcSet:a,start:l,step:null,style:null,summary:null,tabIndex:null,target:null,title:null,type:null,useMap:null,value:s|c,width:a,wmode:a,wrap:null,about:a,datatype:a,inlist:a,prefix:a,property:a,resource:a,"typeof":a,vocab:a,autoCapitalize:null,autoCorrect:null,autoSave:null,itemProp:a,itemScope:a|u,itemType:a,itemID:a,itemRef:a,results:null,security:a,unselectable:a},DOMAttributeNames:{acceptCharset:"accept-charset",className:"class",htmlFor:"for",httpEquiv:"http-equiv"},DOMPropertyNames:{autoCapitalize:"autocapitalize",autoComplete:"autocomplete",autoCorrect:"autocorrect",autoFocus:"autofocus",autoPlay:"autoplay",autoSave:"autosave",encType:"encoding",hrefLang:"hreflang",radioGroup:"radiogroup",spellCheck:"spellcheck",srcDoc:"srcdoc",srcSet:"srcset"}};e.exports=d},function(e,t,n){"use strict";var r=(n(261),n(305)),o=(n(240),"_getDOMNodeDidWarn"),i={getDOMNode:function(){return this.constructor[o]=!0,r(this)}};e.exports=i},function(e,t,n){"use strict";function r(e){return null==e?null:1===e.nodeType?e:o.has(e)?i.getNodeFromInstance(e):(null!=e.render&&"function"==typeof e.render?a(!1):void 0,void a(!1))}{var o=(n(220),n(261)),i=n(243),a=n(228);n(240)}e.exports=r},function(e,t,n){"use strict";function r(){this.reinitializeTransaction()}var o=n(268),i=n(271),a=n(254),s=n(230),u={initialize:s,close:function(){f.isBatchingUpdates=!1}},c={initialize:s,close:o.flushBatchedUpdates.bind(o)},l=[c,u];a(r.prototype,i.Mixin,{getTransactionWrappers:function(){return l}});var p=new r,f={isBatchingUpdates:!1,batchedUpdates:function(e,t,n,r,o,i){var a=f.isBatchingUpdates;f.isBatchingUpdates=!0,a?e(t,n,r,o,i):p.perform(e,null,t,n,r,o,i)}};e.exports=f},function(e,t,n){"use strict";function r(){return this}function o(){var e=this._reactInternalComponent;return!!e}function i(){}function a(e,t){var n=this._reactInternalComponent;n&&(k.enqueueSetPropsInternal(n,e),t&&k.enqueueCallbackInternal(n,t))}function s(e,t){var n=this._reactInternalComponent;n&&(k.enqueueReplacePropsInternal(n,e),t&&k.enqueueCallbackInternal(n,t))}function u(e,t){t&&(null!=t.dangerouslySetInnerHTML&&(null!=t.children?A(!1):void 0,"object"==typeof t.dangerouslySetInnerHTML&&"__html"in t.dangerouslySetInnerHTML?void 0:A(!1)),null!=t.style&&"object"!=typeof t.style?A(!1):void 0)}function c(e,t,n,r){var o=S.findReactContainerForID(e);if(o){var i=o.nodeType===W?o.ownerDocument:o;B(t,i)}r.getReactMountReady().enqueue(l,{id:e,registrationName:t,listener:n})}function l(){var e=this;_.putListener(e.id,e.registrationName,e.listener)}function p(){var e=this;e._rootNodeID?void 0:A(!1);var t=S.getNode(e._rootNodeID);switch(t?void 0:A(!1),e._tag){case"iframe":e._wrapperState.listeners=[_.trapBubbledEvent(w.topLevelTypes.topLoad,"load",t)];break;case"video":case"audio":e._wrapperState.listeners=[];for(var n in Y)Y.hasOwnProperty(n)&&e._wrapperState.listeners.push(_.trapBubbledEvent(w.topLevelTypes[n],Y[n],t));break;case"img":e._wrapperState.listeners=[_.trapBubbledEvent(w.topLevelTypes.topError,"error",t),_.trapBubbledEvent(w.topLevelTypes.topLoad,"load",t)];break;case"form":e._wrapperState.listeners=[_.trapBubbledEvent(w.topLevelTypes.topReset,"reset",t),_.trapBubbledEvent(w.topLevelTypes.topSubmit,"submit",t)]}}function f(){E.mountReadyWrapper(this)}function h(){T.postUpdateWrapper(this)}function d(e){X.call(J,e)||($.test(e)?void 0:A(!1),J[e]=!0)}function v(e,t){return e.indexOf("-")>=0||null!=t.is}function m(e){d(e),this._tag=e.toLowerCase(),this._renderedChildren=null,this._previousStyle=null,this._previousStyleCopy=null,this._rootNodeID=null,this._wrapperState=null,this._topLevelWrapper=null,this._nodeWithLegacyProperties=null}var g=n(308),y=n(310),b=n(238),x=n(237),w=n(245),_=n(244),P=n(241),C=n(318),E=n(319),R=n(323),T=n(326),O=n(327),S=n(243),N=n(328),j=n(233),k=n(267),I=n(254),D=n(236),A=n(228),M=(n(255),n(293)),F=n(234),U=n(235),L=(n(331),n(284),n(240),_.deleteListener),B=_.listenTo,q=_.registrationNameModules,H={string:!0,number:!0},V=M({style:null}),W=1,K=!1;try{Object.defineProperty({},"test",{get:function(){}}),K=!0}catch(Q){}var Y={topAbort:"abort",topCanPlay:"canplay",topCanPlayThrough:"canplaythrough",topDurationChange:"durationchange",topEmptied:"emptied",topEncrypted:"encrypted",topEnded:"ended",topError:"error",topLoadedData:"loadeddata",topLoadedMetadata:"loadedmetadata",topLoadStart:"loadstart",topPause:"pause",topPlay:"play",topPlaying:"playing",topProgress:"progress",topRateChange:"ratechange",topSeeked:"seeked",topSeeking:"seeking",topStalled:"stalled",topSuspend:"suspend",topTimeUpdate:"timeupdate",topVolumeChange:"volumechange",topWaiting:"waiting"},z={area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0},G={listing:!0,pre:!0,textarea:!0},$=(I({menuitem:!0},z),/^[a-zA-Z][a-zA-Z:_\.\-\d]*$/),J={},X={}.hasOwnProperty;m.displayName="ReactDOMComponent",m.Mixin={construct:function(e){this._currentElement=e},mountComponent:function(e,t,n){this._rootNodeID=e;var r=this._currentElement.props;switch(this._tag){case"iframe":case"img":case"form":case"video":case"audio":this._wrapperState={listeners:null},t.getReactMountReady().enqueue(p,this);break;case"button":r=C.getNativeProps(this,r,n);break;case"input":E.mountWrapper(this,r,n),r=E.getNativeProps(this,r,n);break;case"option":R.mountWrapper(this,r,n),r=R.getNativeProps(this,r,n);break;case"select":T.mountWrapper(this,r,n),r=T.getNativeProps(this,r,n),n=T.processChildContext(this,r,n);break;case"textarea":O.mountWrapper(this,r,n),r=O.getNativeProps(this,r,n)}u(this,r);var o;if(t.useCreateElement){var i=n[S.ownerDocumentContextKey],a=i.createElement(this._currentElement.type);x.setAttributeForID(a,this._rootNodeID),S.getID(a),this._updateDOMProperties({},r,t,a),this._createInitialChildren(t,r,n,a),o=a}else{var s=this._createOpenTagMarkupAndPutListeners(t,r),c=this._createContentMarkup(t,r,n);o=!c&&z[this._tag]?s+"/>":s+">"+c+"</"+this._currentElement.type+">"}switch(this._tag){case"input":t.getReactMountReady().enqueue(f,this);case"button":case"select":case"textarea":r.autoFocus&&t.getReactMountReady().enqueue(g.focusDOMComponent,this)}return o},_createOpenTagMarkupAndPutListeners:function(e,t){var n="<"+this._currentElement.type;for(var r in t)if(t.hasOwnProperty(r)){var o=t[r];if(null!=o)if(q.hasOwnProperty(r))o&&c(this._rootNodeID,r,o,e);else{r===V&&(o&&(o=this._previousStyleCopy=I({},t.style)),o=y.createMarkupForStyles(o));var i=null;i=null!=this._tag&&v(this._tag,t)?x.createMarkupForCustomAttribute(r,o):x.createMarkupForProperty(r,o),i&&(n+=" "+i)}}if(e.renderToStaticMarkup)return n;var a=x.createMarkupForID(this._rootNodeID);return n+" "+a},_createContentMarkup:function(e,t,n){var r="",o=t.dangerouslySetInnerHTML;if(null!=o)null!=o.__html&&(r=o.__html);else{var i=H[typeof t.children]?t.children:null,a=null!=i?null:t.children;if(null!=i)r=D(i);else if(null!=a){var s=this.mountChildren(a,e,n);r=s.join("")}}return G[this._tag]&&"\n"===r.charAt(0)?"\n"+r:r},_createInitialChildren:function(e,t,n,r){var o=t.dangerouslySetInnerHTML;if(null!=o)null!=o.__html&&F(r,o.__html);else{var i=H[typeof t.children]?t.children:null,a=null!=i?null:t.children;if(null!=i)U(r,i);else if(null!=a)for(var s=this.mountChildren(a,e,n),u=0;u<s.length;u++)r.appendChild(s[u])}},receiveComponent:function(e,t,n){var r=this._currentElement;this._currentElement=e,this.updateComponent(t,r,e,n)},updateComponent:function(e,t,n,r){var o=t.props,i=this._currentElement.props;switch(this._tag){case"button":o=C.getNativeProps(this,o),i=C.getNativeProps(this,i);break;case"input":E.updateWrapper(this),o=E.getNativeProps(this,o),i=E.getNativeProps(this,i);break;case"option":o=R.getNativeProps(this,o),i=R.getNativeProps(this,i);break;case"select":o=T.getNativeProps(this,o),i=T.getNativeProps(this,i);break;case"textarea":O.updateWrapper(this),o=O.getNativeProps(this,o),i=O.getNativeProps(this,i)}u(this,i),this._updateDOMProperties(o,i,e,null),this._updateDOMChildren(o,i,e,r),!K&&this._nodeWithLegacyProperties&&(this._nodeWithLegacyProperties.props=i),"select"===this._tag&&e.getReactMountReady().enqueue(h,this)},_updateDOMProperties:function(e,t,n,r){var o,i,a;for(o in e)if(!t.hasOwnProperty(o)&&e.hasOwnProperty(o))if(o===V){var s=this._previousStyleCopy;for(i in s)s.hasOwnProperty(i)&&(a=a||{},a[i]="");this._previousStyleCopy=null}else q.hasOwnProperty(o)?e[o]&&L(this._rootNodeID,o):(b.properties[o]||b.isCustomAttribute(o))&&(r||(r=S.getNode(this._rootNodeID)),x.deleteValueForProperty(r,o));for(o in t){var u=t[o],l=o===V?this._previousStyleCopy:e[o];if(t.hasOwnProperty(o)&&u!==l)if(o===V)if(u?u=this._previousStyleCopy=I({},u):this._previousStyleCopy=null,l){for(i in l)!l.hasOwnProperty(i)||u&&u.hasOwnProperty(i)||(a=a||{},a[i]="");for(i in u)u.hasOwnProperty(i)&&l[i]!==u[i]&&(a=a||{},a[i]=u[i])}else a=u;else q.hasOwnProperty(o)?u?c(this._rootNodeID,o,u,n):l&&L(this._rootNodeID,o):v(this._tag,t)?(r||(r=S.getNode(this._rootNodeID)),x.setValueForAttribute(r,o,u)):(b.properties[o]||b.isCustomAttribute(o))&&(r||(r=S.getNode(this._rootNodeID)),null!=u?x.setValueForProperty(r,o,u):x.deleteValueForProperty(r,o))}a&&(r||(r=S.getNode(this._rootNodeID)),y.setValueForStyles(r,a))},_updateDOMChildren:function(e,t,n,r){var o=H[typeof e.children]?e.children:null,i=H[typeof t.children]?t.children:null,a=e.dangerouslySetInnerHTML&&e.dangerouslySetInnerHTML.__html,s=t.dangerouslySetInnerHTML&&t.dangerouslySetInnerHTML.__html,u=null!=o?null:e.children,c=null!=i?null:t.children,l=null!=o||null!=a,p=null!=i||null!=s;null!=u&&null==c?this.updateChildren(null,n,r):l&&!p&&this.updateTextContent(""),null!=i?o!==i&&this.updateTextContent(""+i):null!=s?a!==s&&this.updateMarkup(""+s):null!=c&&this.updateChildren(c,n,r)},unmountComponent:function(){switch(this._tag){case"iframe":case"img":case"form":case"video":case"audio":var e=this._wrapperState.listeners;if(e)for(var t=0;t<e.length;t++)e[t].remove();break;case"input":E.unmountWrapper(this);break;case"html":case"head":case"body":A(!1)}if(this.unmountChildren(),_.deleteAllListeners(this._rootNodeID),P.unmountIDFromEnvironment(this._rootNodeID),this._rootNodeID=null,this._wrapperState=null,this._nodeWithLegacyProperties){var n=this._nodeWithLegacyProperties;n._reactInternalComponent=null,this._nodeWithLegacyProperties=null}},getPublicInstance:function(){if(!this._nodeWithLegacyProperties){var e=S.getNode(this._rootNodeID);e._reactInternalComponent=this,e.getDOMNode=r,e.isMounted=o,e.setState=i,e.replaceState=i,e.forceUpdate=i,e.setProps=a,e.replaceProps=s,e.props=this._currentElement.props,this._nodeWithLegacyProperties=e}return this._nodeWithLegacyProperties}},j.measureMethods(m,"ReactDOMComponent",{mountComponent:"mountComponent",updateComponent:"updateComponent"}),I(m.prototype,m.Mixin,N.Mixin),e.exports=m},function(e,t,n){"use strict";var r=n(243),o=n(305),i=n(309),a={componentDidMount:function(){this.props.autoFocus&&i(o(this))}},s={Mixin:a,focusDOMComponent:function(){i(r.getNode(this._rootNodeID))}};e.exports=s},function(e){"use strict";function t(e){try{e.focus()}catch(t){}}e.exports=t},function(e,t,n){"use strict";var r=n(311),o=n(224),i=n(233),a=(n(312),n(314)),s=n(315),u=n(317),c=(n(240),u(function(e){return s(e)})),l=!1,p="cssFloat";if(o.canUseDOM){var f=document.createElement("div").style;try{f.font=""}catch(h){l=!0}void 0===document.documentElement.style.cssFloat&&(p="styleFloat")}var d={createMarkupForStyles:function(e){var t="";for(var n in e)if(e.hasOwnProperty(n)){var r=e[n];null!=r&&(t+=c(n)+":",t+=a(n,r)+";")}return t||null},setValueForStyles:function(e,t){var n=e.style;for(var o in t)if(t.hasOwnProperty(o)){var i=a(o,t[o]);if("float"===o&&(o=p),i)n[o]=i;else{var s=l&&r.shorthandPropertyExpansions[o];if(s)for(var u in s)n[u]="";else n[o]=""}}}};i.measureMethods(d,"CSSPropertyOperations",{setValueForStyles:"setValueForStyles"}),e.exports=d},function(e){"use strict";function t(e,t){return e+t.charAt(0).toUpperCase()+t.substring(1)}var n={animationIterationCount:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,stopOpacity:!0,strokeDashoffset:!0,strokeOpacity:!0,strokeWidth:!0},r=["Webkit","ms","Moz","O"];Object.keys(n).forEach(function(e){r.forEach(function(r){n[t(r,e)]=n[e]})});var o={background:{backgroundAttachment:!0,backgroundColor:!0,backgroundImage:!0,backgroundPositionX:!0,backgroundPositionY:!0,backgroundRepeat:!0},backgroundPosition:{backgroundPositionX:!0,backgroundPositionY:!0},border:{borderWidth:!0,borderStyle:!0,borderColor:!0},borderBottom:{borderBottomWidth:!0,borderBottomStyle:!0,borderBottomColor:!0},borderLeft:{borderLeftWidth:!0,borderLeftStyle:!0,borderLeftColor:!0},borderRight:{borderRightWidth:!0,borderRightStyle:!0,borderRightColor:!0},borderTop:{borderTopWidth:!0,borderTopStyle:!0,borderTopColor:!0},font:{fontStyle:!0,fontVariant:!0,fontWeight:!0,fontSize:!0,lineHeight:!0,fontFamily:!0},outline:{outlineWidth:!0,outlineStyle:!0,outlineColor:!0}},i={isUnitlessNumber:n,shorthandPropertyExpansions:o};e.exports=i},function(e,t,n){"use strict";function r(e){return o(e.replace(i,"ms-"))}var o=n(313),i=/^-ms-/;e.exports=r},function(e){"use strict";function t(e){return e.replace(n,function(e,t){return t.toUpperCase()})}var n=/-(.)/g;e.exports=t},function(e,t,n){"use strict";function r(e,t){var n=null==t||"boolean"==typeof t||""===t;if(n)return"";var r=isNaN(t);return r||0===t||i.hasOwnProperty(e)&&i[e]?""+t:("string"==typeof t&&(t=t.trim()),t+"px")}var o=n(311),i=o.isUnitlessNumber;e.exports=r},function(e,t,n){"use strict";function r(e){return o(e).replace(i,"-ms-")}var o=n(316),i=/^ms-/;e.exports=r},function(e){"use strict";function t(e){return e.replace(n,"-$1").toLowerCase()}var n=/([A-Z])/g;e.exports=t},function(e){"use strict";function t(e){var t={};return function(n){return t.hasOwnProperty(n)||(t[n]=e.call(this,n)),t[n]}}e.exports=t},function(e){"use strict";var t={onClick:!0,onDoubleClick:!0,onMouseDown:!0,onMouseMove:!0,onMouseUp:!0,onClickCapture:!0,onDoubleClickCapture:!0,onMouseDownCapture:!0,onMouseMoveCapture:!0,onMouseUpCapture:!0},n={getNativeProps:function(e,n){if(!n.disabled)return n;var r={};for(var o in n)n.hasOwnProperty(o)&&!t[o]&&(r[o]=n[o]);return r}};e.exports=n},function(e,t,n){"use strict";function r(){this._rootNodeID&&f.updateWrapper(this)}function o(e){var t=this._currentElement.props,n=a.executeOnChange(t,e);u.asap(r,this);var o=t.name;if("radio"===t.type&&null!=o){for(var i=s.getNode(this._rootNodeID),c=i;c.parentNode;)c=c.parentNode;for(var f=c.querySelectorAll("input[name="+JSON.stringify(""+o)+'][type="radio"]'),h=0;h<f.length;h++){var d=f[h];if(d!==i&&d.form===i.form){var v=s.getID(d);v?void 0:l(!1);var m=p[v];m?void 0:l(!1),u.asap(r,m)}}}return n}var i=n(242),a=n(320),s=n(243),u=n(268),c=n(254),l=n(228),p={},f={getNativeProps:function(e,t){var n=a.getValue(t),r=a.getChecked(t),o=c({},t,{defaultChecked:void 0,defaultValue:void 0,value:null!=n?n:e._wrapperState.initialValue,checked:null!=r?r:e._wrapperState.initialChecked,onChange:e._wrapperState.onChange});return o},mountWrapper:function(e,t){var n=t.defaultValue;e._wrapperState={initialChecked:t.defaultChecked||!1,initialValue:null!=n?n:null,onChange:o.bind(e)}},mountReadyWrapper:function(e){p[e._rootNodeID]=e},unmountWrapper:function(e){delete p[e._rootNodeID]},updateWrapper:function(e){var t=e._currentElement.props,n=t.checked;null!=n&&i.updatePropertyByID(e._rootNodeID,"checked",n||!1);var r=a.getValue(t);null!=r&&i.updatePropertyByID(e._rootNodeID,"value",""+r)}};e.exports=f},function(e,t,n){"use strict";function r(e){null!=e.checkedLink&&null!=e.valueLink?c(!1):void 0}function o(e){r(e),null!=e.value||null!=e.onChange?c(!1):void 0}function i(e){r(e),null!=e.checked||null!=e.onChange?c(!1):void 0}function a(e){if(e){var t=e.getName();if(t)return" Check the render method of `"+t+"`."}return""}var s=n(321),u=n(279),c=n(228),l=(n(240),{button:!0,checkbox:!0,image:!0,hidden:!0,radio:!0,reset:!0,submit:!0}),p={value:function(e,t){return!e[t]||l[e.type]||e.onChange||e.readOnly||e.disabled?null:new Error("You provided a `value` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultValue`. Otherwise, set either `onChange` or `readOnly`.")},checked:function(e,t){return!e[t]||e.onChange||e.readOnly||e.disabled?null:new Error("You provided a `checked` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultChecked`. Otherwise, set either `onChange` or `readOnly`.")},onChange:s.func},f={},h={checkPropTypes:function(e,t,n){for(var r in p){if(p.hasOwnProperty(r))var o=p[r](t,r,e,u.prop);if(o instanceof Error&&!(o.message in f)){f[o.message]=!0;{a(n)}}}},getValue:function(e){return e.valueLink?(o(e),e.valueLink.value):e.value},getChecked:function(e){return e.checkedLink?(i(e),e.checkedLink.value):e.checked},executeOnChange:function(e,t){return e.valueLink?(o(e),e.valueLink.requestChange(t.target.value)):e.checkedLink?(i(e),e.checkedLink.requestChange(t.target.checked)):e.onChange?e.onChange.call(void 0,t):void 0}};e.exports=h},function(e,t,n){"use strict";function r(e){function t(t,n,r,o,i,a){if(o=o||_,a=a||r,null==n[r]){var s=b[i];return t?new Error("Required "+s+" `"+a+"` was not specified in "+("`"+o+"`.")):null}return e(n,r,o,i,a)}var n=t.bind(null,!1);return n.isRequired=t.bind(null,!0),n}function o(e){function t(t,n,r,o,i){var a=t[n],s=v(a);if(s!==e){var u=b[o],c=m(a);return new Error("Invalid "+u+" `"+i+"` of type "+("`"+c+"` supplied to `"+r+"`, expected ")+("`"+e+"`."))}return null}return r(t)}function i(){return r(x.thatReturns(null))}function a(e){function t(t,n,r,o,i){var a=t[n];if(!Array.isArray(a)){var s=b[o],u=v(a);return new Error("Invalid "+s+" `"+i+"` of type "+("`"+u+"` supplied to `"+r+"`, expected an array."))}for(var c=0;c<a.length;c++){var l=e(a,c,r,o,i+"["+c+"]");if(l instanceof Error)return l}return null}return r(t)}function s(){function e(e,t,n,r,o){if(!y.isValidElement(e[t])){var i=b[r];return new Error("Invalid "+i+" `"+o+"` supplied to "+("`"+n+"`, expected a single ReactElement."))}return null}return r(e)}function u(e){function t(t,n,r,o,i){if(!(t[n]instanceof e)){var a=b[o],s=e.name||_,u=g(t[n]);return new Error("Invalid "+a+" `"+i+"` of type "+("`"+u+"` supplied to `"+r+"`, expected ")+("instance of `"+s+"`."))}return null}return r(t)}function c(e){function t(t,n,r,o,i){for(var a=t[n],s=0;s<e.length;s++)if(a===e[s])return null;var u=b[o],c=JSON.stringify(e);return new Error("Invalid "+u+" `"+i+"` of value `"+a+"` "+("supplied to `"+r+"`, expected one of "+c+"."))}return r(Array.isArray(e)?t:function(){return new Error("Invalid argument supplied to oneOf, expected an instance of array.")})}function l(e){function t(t,n,r,o,i){var a=t[n],s=v(a);if("object"!==s){var u=b[o];return new Error("Invalid "+u+" `"+i+"` of type "+("`"+s+"` supplied to `"+r+"`, expected an object."))}for(var c in a)if(a.hasOwnProperty(c)){var l=e(a,c,r,o,i+"."+c);if(l instanceof Error)return l}return null}return r(t)}function p(e){function t(t,n,r,o,i){for(var a=0;a<e.length;a++){var s=e[a];if(null==s(t,n,r,o,i))return null}var u=b[o];return new Error("Invalid "+u+" `"+i+"` supplied to "+("`"+r+"`."))}return r(Array.isArray(e)?t:function(){return new Error("Invalid argument supplied to oneOfType, expected an instance of array.")})}function f(){function e(e,t,n,r,o){if(!d(e[t])){var i=b[r];return new Error("Invalid "+i+" `"+o+"` supplied to "+("`"+n+"`, expected a ReactNode."))}return null}return r(e)}function h(e){function t(t,n,r,o,i){var a=t[n],s=v(a);if("object"!==s){var u=b[o];return new Error("Invalid "+u+" `"+i+"` of type `"+s+"` "+("supplied to `"+r+"`, expected `object`."))}for(var c in e){var l=e[c];if(l){var p=l(a,c,r,o,i+"."+c);if(p)return p}}return null}return r(t)}function d(e){switch(typeof e){case"number":case"string":case"undefined":return!0;case"boolean":return!e;case"object":if(Array.isArray(e))return e.every(d);if(null===e||y.isValidElement(e))return!0;var t=w(e);if(!t)return!1;var n,r=t.call(e);if(t!==e.entries){for(;!(n=r.next()).done;)if(!d(n.value))return!1}else for(;!(n=r.next()).done;){var o=n.value;if(o&&!d(o[1]))return!1}return!0;default:return!1}}function v(e){var t=typeof e;return Array.isArray(e)?"array":e instanceof RegExp?"object":t}function m(e){var t=v(e);if("object"===t){if(e instanceof Date)return"date";if(e instanceof RegExp)return"regexp"}return t}function g(e){return e.constructor&&e.constructor.name?e.constructor.name:"<<anonymous>>"}var y=n(257),b=n(280),x=n(230),w=n(322),_="<<anonymous>>",P={array:o("array"),bool:o("boolean"),func:o("function"),number:o("number"),object:o("object"),string:o("string"),any:i(),arrayOf:a,element:s(),instanceOf:u,node:f(),objectOf:l,oneOf:c,oneOfType:p,shape:h};e.exports=P},function(e){"use strict";function t(e){var t=e&&(n&&e[n]||e[r]);return"function"==typeof t?t:void 0}var n="function"==typeof Symbol&&Symbol.iterator,r="@@iterator";e.exports=t},function(e,t,n){"use strict";var r=n(324),o=n(326),i=n(254),a=(n(240),o.valueContextKey),s={mountWrapper:function(e,t,n){var r=n[a],o=null;if(null!=r)if(o=!1,Array.isArray(r)){for(var i=0;i<r.length;i++)if(""+r[i]==""+t.value){o=!0;break}}else o=""+r==""+t.value;e._wrapperState={selected:o}},getNativeProps:function(e,t){var n=i({selected:void 0,children:void 0},t);null!=e._wrapperState.selected&&(n.selected=e._wrapperState.selected);var o="";return r.forEach(t.children,function(e){null!=e&&("string"==typeof e||"number"==typeof e)&&(o+=e)}),n.children=o,n}};e.exports=s},function(e,t,n){"use strict";function r(e){return(""+e).replace(x,"//")}function o(e,t){this.func=e,this.context=t,this.count=0}function i(e,t){var n=e.func,r=e.context;n.call(r,t,e.count++)}function a(e,t,n){if(null==e)return e;var r=o.getPooled(t,n);g(e,i,r),o.release(r)}function s(e,t,n,r){this.result=e,this.keyPrefix=t,this.func=n,this.context=r,this.count=0}function u(e,t,n){var o=e.result,i=e.keyPrefix,a=e.func,s=e.context,u=a.call(s,t,e.count++);Array.isArray(u)?c(u,o,n,m.thatReturnsArgument):null!=u&&(v.isValidElement(u)&&(u=v.cloneAndReplaceKey(u,i+(u!==t?r(u.key||"")+"/":"")+n)),o.push(u))}function c(e,t,n,o,i){var a="";null!=n&&(a=r(n)+"/");var c=s.getPooled(t,a,o,i);g(e,u,c),s.release(c)}function l(e,t,n){if(null==e)return e;var r=[];return c(e,r,null,t,n),r}function p(){return null}function f(e){return g(e,p,null)}function h(e){var t=[];return c(e,t,null,m.thatReturnsArgument),t}var d=n(270),v=n(257),m=n(230),g=n(325),y=d.twoArgumentPooler,b=d.fourArgumentPooler,x=/\/(?!\/)/g;o.prototype.destructor=function(){this.func=null,this.context=null,this.count=0},d.addPoolingTo(o,y),s.prototype.destructor=function(){this.result=null,this.keyPrefix=null,this.func=null,this.context=null,this.count=0},d.addPoolingTo(s,b);var w={forEach:a,map:l,mapIntoWithKeyPrefixInternal:c,count:f,toArray:h};e.exports=w},function(e,t,n){"use strict";function r(e){return v[e]}function o(e,t){return e&&null!=e.key?a(e.key):t.toString(36)}function i(e){return(""+e).replace(m,r)}function a(e){return"$"+i(e)}function s(e,t,n,r){var i=typeof e;if(("undefined"===i||"boolean"===i)&&(e=null),null===e||"string"===i||"number"===i||c.isValidElement(e))return n(r,e,""===t?h+o(e,0):t),1;var u,l,v=0,m=""===t?h:t+d;if(Array.isArray(e))for(var g=0;g<e.length;g++)u=e[g],l=m+o(u,g),v+=s(u,l,n,r);else{var y=p(e);if(y){var b,x=y.call(e);if(y!==e.entries)for(var w=0;!(b=x.next()).done;)u=b.value,l=m+o(u,w++),v+=s(u,l,n,r);else for(;!(b=x.next()).done;){var _=b.value;_&&(u=_[1],l=m+a(_[0])+d+o(u,0),v+=s(u,l,n,r))}}else if("object"===i){{String(e)}f(!1)}}return v}function u(e,t,n){return null==e?0:s(e,"",t,n)}var c=(n(220),n(257)),l=n(259),p=n(322),f=n(228),h=(n(240),l.SEPARATOR),d=":",v={"=":"=0",".":"=1",":":"=2"},m=/[=.:]/g;e.exports=u},function(e,t,n){"use strict";function r(){if(this._rootNodeID&&this._wrapperState.pendingUpdate){this._wrapperState.pendingUpdate=!1;var e=this._currentElement.props,t=a.getValue(e);null!=t&&o(this,e,t)}}function o(e,t,n){var r,o,i=s.getNode(e._rootNodeID).options;if(t){for(r={},o=0;o<n.length;o++)r[""+n[o]]=!0;for(o=0;o<i.length;o++){var a=r.hasOwnProperty(i[o].value);i[o].selected!==a&&(i[o].selected=a)}}else{for(r=""+n,o=0;o<i.length;o++)if(i[o].value===r)return void(i[o].selected=!0);i.length&&(i[0].selected=!0)}}function i(e){var t=this._currentElement.props,n=a.executeOnChange(t,e);return this._wrapperState.pendingUpdate=!0,u.asap(r,this),n}var a=n(320),s=n(243),u=n(268),c=n(254),l=(n(240),"__ReactDOMSelect_value$"+Math.random().toString(36).slice(2)),p={valueContextKey:l,getNativeProps:function(e,t){return c({},t,{onChange:e._wrapperState.onChange,value:void 0})},mountWrapper:function(e,t){var n=a.getValue(t);e._wrapperState={pendingUpdate:!1,initialValue:null!=n?n:t.defaultValue,onChange:i.bind(e),wasMultiple:Boolean(t.multiple)}},processChildContext:function(e,t,n){var r=c({},n);return r[l]=e._wrapperState.initialValue,r},postUpdateWrapper:function(e){var t=e._currentElement.props;e._wrapperState.initialValue=void 0;var n=e._wrapperState.wasMultiple;e._wrapperState.wasMultiple=Boolean(t.multiple);var r=a.getValue(t);null!=r?(e._wrapperState.pendingUpdate=!1,o(e,Boolean(t.multiple),r)):n!==Boolean(t.multiple)&&(null!=t.defaultValue?o(e,Boolean(t.multiple),t.defaultValue):o(e,Boolean(t.multiple),t.multiple?[]:""))}};e.exports=p},function(e,t,n){"use strict";function r(){this._rootNodeID&&l.updateWrapper(this)}function o(e){var t=this._currentElement.props,n=i.executeOnChange(t,e);return s.asap(r,this),n}var i=n(320),a=n(242),s=n(268),u=n(254),c=n(228),l=(n(240),{getNativeProps:function(e,t){null!=t.dangerouslySetInnerHTML?c(!1):void 0;var n=u({},t,{defaultValue:void 0,value:void 0,children:e._wrapperState.initialValue,onChange:e._wrapperState.onChange});return n},mountWrapper:function(e,t){var n=t.defaultValue,r=t.children;null!=r&&(null!=n?c(!1):void 0,Array.isArray(r)&&(r.length<=1?void 0:c(!1),r=r[0]),n=""+r),null==n&&(n="");var a=i.getValue(t);e._wrapperState={initialValue:""+(null!=a?a:n),onChange:o.bind(e)}},updateWrapper:function(e){var t=e._currentElement.props,n=i.getValue(t);null!=n&&a.updatePropertyByID(e._rootNodeID,"value",""+n)}});e.exports=l},function(e,t,n){"use strict";function r(e,t,n){m.push({parentID:e,parentNode:null,type:p.INSERT_MARKUP,markupIndex:g.push(t)-1,content:null,fromIndex:null,toIndex:n})}function o(e,t,n){m.push({parentID:e,parentNode:null,type:p.MOVE_EXISTING,markupIndex:null,content:null,fromIndex:t,toIndex:n})}function i(e,t){m.push({parentID:e,parentNode:null,type:p.REMOVE_NODE,markupIndex:null,content:null,fromIndex:t,toIndex:null})}function a(e,t){m.push({parentID:e,parentNode:null,type:p.SET_MARKUP,markupIndex:null,content:t,fromIndex:null,toIndex:null})}function s(e,t){m.push({parentID:e,parentNode:null,type:p.TEXT_CONTENT,markupIndex:null,content:t,fromIndex:null,toIndex:null})}function u(){m.length&&(l.processChildrenUpdates(m,g),c())}function c(){m.length=0,g.length=0}var l=n(278),p=n(231),f=(n(220),n(264)),h=n(329),d=n(330),v=0,m=[],g=[],y={Mixin:{_reconcilerInstantiateChildren:function(e,t,n){return h.instantiateChildren(e,t,n)},_reconcilerUpdateChildren:function(e,t,n,r){var o;return o=d(t),h.updateChildren(e,o,n,r)},mountChildren:function(e,t,n){var r=this._reconcilerInstantiateChildren(e,t,n);this._renderedChildren=r;var o=[],i=0;for(var a in r)if(r.hasOwnProperty(a)){var s=r[a],u=this._rootNodeID+a,c=f.mountComponent(s,u,t,n);s._mountIndex=i++,o.push(c)}return o},updateTextContent:function(e){v++;var t=!0;try{var n=this._renderedChildren;h.unmountChildren(n);for(var r in n)n.hasOwnProperty(r)&&this._unmountChild(n[r]);this.setTextContent(e),t=!1}finally{v--,v||(t?c():u())}},updateMarkup:function(e){v++;var t=!0;try{var n=this._renderedChildren;h.unmountChildren(n);for(var r in n)n.hasOwnProperty(r)&&this._unmountChildByName(n[r],r); this.setMarkup(e),t=!1}finally{v--,v||(t?c():u())}},updateChildren:function(e,t,n){v++;var r=!0;try{this._updateChildren(e,t,n),r=!1}finally{v--,v||(r?c():u())}},_updateChildren:function(e,t,n){var r=this._renderedChildren,o=this._reconcilerUpdateChildren(r,e,t,n);if(this._renderedChildren=o,o||r){var i,a=0,s=0;for(i in o)if(o.hasOwnProperty(i)){var u=r&&r[i],c=o[i];u===c?(this.moveChild(u,s,a),a=Math.max(u._mountIndex,a),u._mountIndex=s):(u&&(a=Math.max(u._mountIndex,a),this._unmountChild(u)),this._mountChildByNameAtIndex(c,i,s,t,n)),s++}for(i in r)!r.hasOwnProperty(i)||o&&o.hasOwnProperty(i)||this._unmountChild(r[i])}},unmountChildren:function(){var e=this._renderedChildren;h.unmountChildren(e),this._renderedChildren=null},moveChild:function(e,t,n){e._mountIndex<n&&o(this._rootNodeID,e._mountIndex,t)},createChild:function(e,t){r(this._rootNodeID,t,e._mountIndex)},removeChild:function(e){i(this._rootNodeID,e._mountIndex)},setTextContent:function(e){s(this._rootNodeID,e)},setMarkup:function(e){a(this._rootNodeID,e)},_mountChildByNameAtIndex:function(e,t,n,r,o){var i=this._rootNodeID+t,a=f.mountComponent(e,i,r,o);e._mountIndex=n,this.createChild(e,a)},_unmountChild:function(e){this.removeChild(e),e._mountIndex=null}}};e.exports=y},function(e,t,n){"use strict";function r(e,t,n){var r=void 0===e[n];null!=t&&r&&(e[n]=i(t,null))}var o=n(264),i=n(276),a=n(281),s=n(325),u=(n(240),{instantiateChildren:function(e){if(null==e)return null;var t={};return s(e,r,t),t},updateChildren:function(e,t,n,r){if(!t&&!e)return null;var s;for(s in t)if(t.hasOwnProperty(s)){var u=e&&e[s],c=u&&u._currentElement,l=t[s];if(null!=u&&a(c,l))o.receiveComponent(u,l,n,r),t[s]=u;else{u&&o.unmountComponent(u,s);var p=i(l,null);t[s]=p}}for(s in e)!e.hasOwnProperty(s)||t&&t.hasOwnProperty(s)||o.unmountComponent(e[s]);return t},unmountChildren:function(e){for(var t in e)if(e.hasOwnProperty(t)){var n=e[t];o.unmountComponent(n)}}});e.exports=u},function(e,t,n){"use strict";function r(e,t,n){var r=e,o=void 0===r[n];o&&null!=t&&(r[n]=t)}function o(e){if(null==e)return e;var t={};return i(e,r,t),t}{var i=n(325);n(240)}e.exports=o},function(e){"use strict";function t(e,t){if(e===t)return!0;if("object"!=typeof e||null===e||"object"!=typeof t||null===t)return!1;var r=Object.keys(e),o=Object.keys(t);if(r.length!==o.length)return!1;for(var i=n.bind(t),a=0;a<r.length;a++)if(!i(r[a])||e[r[a]]!==t[r[a]])return!1;return!0}var n=Object.prototype.hasOwnProperty;e.exports=t},function(e,t,n){"use strict";function r(e){var t=f.getID(e),n=p.getReactRootIDFromNodeID(t),r=f.findReactContainerForID(n),o=f.getFirstReactDOM(r);return o}function o(e,t){this.topLevelType=e,this.nativeEvent=t,this.ancestors=[]}function i(e){a(e)}function a(e){for(var t=f.getFirstReactDOM(v(e.nativeEvent))||window,n=t;n;)e.ancestors.push(n),n=r(n);for(var o=0;o<e.ancestors.length;o++){t=e.ancestors[o];var i=f.getID(t)||"";g._handleTopLevel(e.topLevelType,t,i,e.nativeEvent,v(e.nativeEvent))}}function s(e){var t=m(window);e(t)}var u=n(333),c=n(224),l=n(270),p=n(259),f=n(243),h=n(268),d=n(254),v=n(295),m=n(334);d(o.prototype,{destructor:function(){this.topLevelType=null,this.nativeEvent=null,this.ancestors.length=0}}),l.addPoolingTo(o,l.twoArgumentPooler);var g={_enabled:!0,_handleTopLevel:null,WINDOW_HANDLE:c.canUseDOM?window:null,setHandleTopLevel:function(e){g._handleTopLevel=e},setEnabled:function(e){g._enabled=!!e},isEnabled:function(){return g._enabled},trapBubbledEvent:function(e,t,n){var r=n;return r?u.listen(r,t,g.dispatchEvent.bind(null,e)):null},trapCapturedEvent:function(e,t,n){var r=n;return r?u.capture(r,t,g.dispatchEvent.bind(null,e)):null},monitorScrollValue:function(e){var t=s.bind(null,e);u.listen(window,"scroll",t)},dispatchEvent:function(e,t){if(g._enabled){var n=o.getPooled(e,t);try{h.batchedUpdates(i,n)}finally{o.release(n)}}}};e.exports=g},function(e,t,n){"use strict";var r=n(230),o={listen:function(e,t,n){return e.addEventListener?(e.addEventListener(t,n,!1),{remove:function(){e.removeEventListener(t,n,!1)}}):e.attachEvent?(e.attachEvent("on"+t,n),{remove:function(){e.detachEvent("on"+t,n)}}):void 0},capture:function(e,t,n){return e.addEventListener?(e.addEventListener(t,n,!0),{remove:function(){e.removeEventListener(t,n,!0)}}):{remove:r}},registerDefault:function(){}};e.exports=o},function(e){"use strict";function t(e){return e===window?{x:window.pageXOffset||document.documentElement.scrollLeft,y:window.pageYOffset||document.documentElement.scrollTop}:{x:e.scrollLeft,y:e.scrollTop}}e.exports=t},function(e,t,n){"use strict";var r=n(238),o=n(246),i=n(278),a=n(336),s=n(282),u=n(244),c=n(283),l=n(233),p=n(260),f=n(268),h={Component:i.injection,Class:a.injection,DOMProperty:r.injection,EmptyComponent:s.injection,EventPluginHub:o.injection,EventEmitter:u.injection,NativeComponent:c.injection,Perf:l.injection,RootIndex:p.injection,Updates:f.injection};e.exports=h},function(e,t,n){"use strict";function r(e,t){var n=_.hasOwnProperty(t)?_[t]:null;C.hasOwnProperty(t)&&(n!==x.OVERRIDE_BASE?m(!1):void 0),e.hasOwnProperty(t)&&(n!==x.DEFINE_MANY&&n!==x.DEFINE_MANY_MERGED?m(!1):void 0)}function o(e,t){if(t){"function"==typeof t?m(!1):void 0,f.isValidElement(t)?m(!1):void 0;var n=e.prototype;t.hasOwnProperty(b)&&P.mixins(e,t.mixins);for(var o in t)if(t.hasOwnProperty(o)&&o!==b){var i=t[o];if(r(n,o),P.hasOwnProperty(o))P[o](e,i);else{var a=_.hasOwnProperty(o),c=n.hasOwnProperty(o),l="function"==typeof i,p=l&&!a&&!c&&t.autobind!==!1;if(p)n.__reactAutoBindMap||(n.__reactAutoBindMap={}),n.__reactAutoBindMap[o]=i,n[o]=i;else if(c){var h=_[o];!a||h!==x.DEFINE_MANY_MERGED&&h!==x.DEFINE_MANY?m(!1):void 0,h===x.DEFINE_MANY_MERGED?n[o]=s(n[o],i):h===x.DEFINE_MANY&&(n[o]=u(n[o],i))}else n[o]=i}}}}function i(e,t){if(t)for(var n in t){var r=t[n];if(t.hasOwnProperty(n)){var o=n in P;o?m(!1):void 0;var i=n in e;i?m(!1):void 0,e[n]=r}}}function a(e,t){e&&t&&"object"==typeof e&&"object"==typeof t?void 0:m(!1);for(var n in t)t.hasOwnProperty(n)&&(void 0!==e[n]?m(!1):void 0,e[n]=t[n]);return e}function s(e,t){return function(){var n=e.apply(this,arguments),r=t.apply(this,arguments);if(null==n)return r;if(null==r)return n;var o={};return a(o,n),a(o,r),o}}function u(e,t){return function(){e.apply(this,arguments),t.apply(this,arguments)}}function c(e,t){var n=t.bind(e);return n}function l(e){for(var t in e.__reactAutoBindMap)if(e.__reactAutoBindMap.hasOwnProperty(t)){var n=e.__reactAutoBindMap[t];e[t]=c(e,n)}}var p=n(337),f=n(257),h=(n(279),n(280),n(338)),d=n(254),v=n(272),m=n(228),g=n(232),y=n(293),b=(n(240),y({mixins:null})),x=g({DEFINE_ONCE:null,DEFINE_MANY:null,OVERRIDE_BASE:null,DEFINE_MANY_MERGED:null}),w=[],_={mixins:x.DEFINE_MANY,statics:x.DEFINE_MANY,propTypes:x.DEFINE_MANY,contextTypes:x.DEFINE_MANY,childContextTypes:x.DEFINE_MANY,getDefaultProps:x.DEFINE_MANY_MERGED,getInitialState:x.DEFINE_MANY_MERGED,getChildContext:x.DEFINE_MANY_MERGED,render:x.DEFINE_ONCE,componentWillMount:x.DEFINE_MANY,componentDidMount:x.DEFINE_MANY,componentWillReceiveProps:x.DEFINE_MANY,shouldComponentUpdate:x.DEFINE_ONCE,componentWillUpdate:x.DEFINE_MANY,componentDidUpdate:x.DEFINE_MANY,componentWillUnmount:x.DEFINE_MANY,updateComponent:x.OVERRIDE_BASE},P={displayName:function(e,t){e.displayName=t},mixins:function(e,t){if(t)for(var n=0;n<t.length;n++)o(e,t[n])},childContextTypes:function(e,t){e.childContextTypes=d({},e.childContextTypes,t)},contextTypes:function(e,t){e.contextTypes=d({},e.contextTypes,t)},getDefaultProps:function(e,t){e.getDefaultProps=e.getDefaultProps?s(e.getDefaultProps,t):t},propTypes:function(e,t){e.propTypes=d({},e.propTypes,t)},statics:function(e,t){i(e,t)},autobind:function(){}},C={replaceState:function(e,t){this.updater.enqueueReplaceState(this,e),t&&this.updater.enqueueCallback(this,t)},isMounted:function(){return this.updater.isMounted(this)},setProps:function(e,t){this.updater.enqueueSetProps(this,e),t&&this.updater.enqueueCallback(this,t)},replaceProps:function(e,t){this.updater.enqueueReplaceProps(this,e),t&&this.updater.enqueueCallback(this,t)}},E=function(){};d(E.prototype,p.prototype,C);var R={createClass:function(e){var t=function(e,t,n){this.__reactAutoBindMap&&l(this),this.props=e,this.context=t,this.refs=v,this.updater=n||h,this.state=null;var r=this.getInitialState?this.getInitialState():null;"object"!=typeof r||Array.isArray(r)?m(!1):void 0,this.state=r};t.prototype=new E,t.prototype.constructor=t,w.forEach(o.bind(null,t)),o(t,e),t.getDefaultProps&&(t.defaultProps=t.getDefaultProps()),t.prototype.render?void 0:m(!1);for(var n in _)t.prototype[n]||(t.prototype[n]=null);return t},injection:{injectMixin:function(e){w.push(e)}}};e.exports=R},function(e,t,n){"use strict";function r(e,t,n){this.props=e,this.context=t,this.refs=i,this.updater=n||o}{var o=n(338),i=n(272),a=n(228);n(240)}r.prototype.isReactComponent={},r.prototype.setState=function(e,t){"object"!=typeof e&&"function"!=typeof e&&null!=e?a(!1):void 0,this.updater.enqueueSetState(this,e),t&&this.updater.enqueueCallback(this,t)},r.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this),e&&this.updater.enqueueCallback(this,e)};e.exports=r},function(e,t,n){"use strict";function r(e,t){}var o=(n(240),{isMounted:function(){return!1},enqueueCallback:function(){},enqueueForceUpdate:function(e){r(e,"forceUpdate")},enqueueReplaceState:function(e){r(e,"replaceState")},enqueueSetState:function(e){r(e,"setState")},enqueueSetProps:function(e){r(e,"setProps")},enqueueReplaceProps:function(e){r(e,"replaceProps")}});e.exports=o},function(e,t,n){"use strict";function r(e){this.reinitializeTransaction(),this.renderToStaticMarkup=!1,this.reactMountReady=o.getPooled(null),this.useCreateElement=!e&&s.useCreateElement}var o=n(269),i=n(270),a=n(244),s=n(256),u=n(340),c=n(271),l=n(254),p={initialize:u.getSelectionInformation,close:u.restoreSelection},f={initialize:function(){var e=a.isEnabled();return a.setEnabled(!1),e},close:function(e){a.setEnabled(e)}},h={initialize:function(){this.reactMountReady.reset()},close:function(){this.reactMountReady.notifyAll()}},d=[p,f,h],v={getTransactionWrappers:function(){return d},getReactMountReady:function(){return this.reactMountReady},destructor:function(){o.release(this.reactMountReady),this.reactMountReady=null}};l(r.prototype,c.Mixin,v),i.addPoolingTo(r),e.exports=r},function(e,t,n){"use strict";function r(e){return i(document.documentElement,e)}var o=n(341),i=n(273),a=n(309),s=n(343),u={hasSelectionCapabilities:function(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&("input"===t&&"text"===e.type||"textarea"===t||"true"===e.contentEditable)},getSelectionInformation:function(){var e=s();return{focusedElem:e,selectionRange:u.hasSelectionCapabilities(e)?u.getSelection(e):null}},restoreSelection:function(e){var t=s(),n=e.focusedElem,o=e.selectionRange;t!==n&&r(n)&&(u.hasSelectionCapabilities(n)&&u.setSelection(n,o),a(n))},getSelection:function(e){var t;if("selectionStart"in e)t={start:e.selectionStart,end:e.selectionEnd};else if(document.selection&&e.nodeName&&"input"===e.nodeName.toLowerCase()){var n=document.selection.createRange();n.parentElement()===e&&(t={start:-n.moveStart("character",-e.value.length),end:-n.moveEnd("character",-e.value.length)})}else t=o.getOffsets(e);return t||{start:0,end:0}},setSelection:function(e,t){var n=t.start,r=t.end;if("undefined"==typeof r&&(r=n),"selectionStart"in e)e.selectionStart=n,e.selectionEnd=Math.min(r,e.value.length);else if(document.selection&&e.nodeName&&"input"===e.nodeName.toLowerCase()){var i=e.createTextRange();i.collapse(!0),i.moveStart("character",n),i.moveEnd("character",r-n),i.select()}else o.setOffsets(e,t)}};e.exports=u},function(e,t,n){"use strict";function r(e,t,n,r){return e===n&&t===r}function o(e){var t=document.selection,n=t.createRange(),r=n.text.length,o=n.duplicate();o.moveToElementText(e),o.setEndPoint("EndToStart",n);var i=o.text.length,a=i+r;return{start:i,end:a}}function i(e){var t=window.getSelection&&window.getSelection();if(!t||0===t.rangeCount)return null;var n=t.anchorNode,o=t.anchorOffset,i=t.focusNode,a=t.focusOffset,s=t.getRangeAt(0);try{s.startContainer.nodeType,s.endContainer.nodeType}catch(u){return null}var c=r(t.anchorNode,t.anchorOffset,t.focusNode,t.focusOffset),l=c?0:s.toString().length,p=s.cloneRange();p.selectNodeContents(e),p.setEnd(s.startContainer,s.startOffset);var f=r(p.startContainer,p.startOffset,p.endContainer,p.endOffset),h=f?0:p.toString().length,d=h+l,v=document.createRange();v.setStart(n,o),v.setEnd(i,a);var m=v.collapsed;return{start:m?d:h,end:m?h:d}}function a(e,t){var n,r,o=document.selection.createRange().duplicate();"undefined"==typeof t.end?(n=t.start,r=n):t.start>t.end?(n=t.end,r=t.start):(n=t.start,r=t.end),o.moveToElementText(e),o.moveStart("character",n),o.setEndPoint("EndToStart",o),o.moveEnd("character",r-n),o.select()}function s(e,t){if(window.getSelection){var n=window.getSelection(),r=e[l()].length,o=Math.min(t.start,r),i="undefined"==typeof t.end?o:Math.min(t.end,r);if(!n.extend&&o>i){var a=i;i=o,o=a}var s=c(e,o),u=c(e,i);if(s&&u){var p=document.createRange();p.setStart(s.node,s.offset),n.removeAllRanges(),o>i?(n.addRange(p),n.extend(u.node,u.offset)):(p.setEnd(u.node,u.offset),n.addRange(p))}}}var u=n(224),c=n(342),l=n(289),p=u.canUseDOM&&"selection"in document&&!("getSelection"in window),f={getOffsets:p?o:i,setOffsets:p?a:s};e.exports=f},function(e){"use strict";function t(e){for(;e&&e.firstChild;)e=e.firstChild;return e}function n(e){for(;e;){if(e.nextSibling)return e.nextSibling;e=e.parentNode}}function r(e,r){for(var o=t(e),i=0,a=0;o;){if(3===o.nodeType){if(a=i+o.textContent.length,r>=i&&a>=r)return{node:o,offset:r-i};i=a}o=t(n(o))}}e.exports=r},function(e){"use strict";function t(){if("undefined"==typeof document)return null;try{return document.activeElement||document.body}catch(e){return document.body}}e.exports=t},function(e,t,n){"use strict";function r(e){if("selectionStart"in e&&u.hasSelectionCapabilities(e))return{start:e.selectionStart,end:e.selectionEnd};if(window.getSelection){var t=window.getSelection();return{anchorNode:t.anchorNode,anchorOffset:t.anchorOffset,focusNode:t.focusNode,focusOffset:t.focusOffset}}if(document.selection){var n=document.selection.createRange();return{parentElement:n.parentElement(),text:n.text,top:n.boundingTop,left:n.boundingLeft}}}function o(e,t){if(x||null==g||g!==l())return null;var n=r(g);if(!b||!h(b,n)){b=n;var o=c.getPooled(m.select,y,e,t);return o.type="select",o.target=g,a.accumulateTwoPhaseDispatches(o),o}return null}var i=n(245),a=n(287),s=n(224),u=n(340),c=n(291),l=n(343),p=n(296),f=n(293),h=n(331),d=i.topLevelTypes,v=s.canUseDOM&&"documentMode"in document&&document.documentMode<=11,m={select:{phasedRegistrationNames:{bubbled:f({onSelect:null}),captured:f({onSelectCapture:null})},dependencies:[d.topBlur,d.topContextMenu,d.topFocus,d.topKeyDown,d.topMouseDown,d.topMouseUp,d.topSelectionChange]}},g=null,y=null,b=null,x=!1,w=!1,_=f({onSelect:null}),P={eventTypes:m,extractEvents:function(e,t,n,r,i){if(!w)return null;switch(e){case d.topFocus:(p(t)||"true"===t.contentEditable)&&(g=t,y=n,b=null);break;case d.topBlur:g=null,y=null,b=null;break;case d.topMouseDown:x=!0;break;case d.topContextMenu:case d.topMouseUp:return x=!1,o(r,i);case d.topSelectionChange:if(v)break;case d.topKeyDown:case d.topKeyUp:return o(r,i)}return null},didPutListener:function(e,t){t===_&&(w=!0)}};e.exports=P},function(e){"use strict";var t=Math.pow(2,53),n={createReactRootIndex:function(){return Math.ceil(Math.random()*t)}};e.exports=n},function(e,t,n){"use strict";var r=n(245),o=n(333),i=n(287),a=n(243),s=n(347),u=n(291),c=n(348),l=n(349),p=n(300),f=n(352),h=n(353),d=n(301),v=n(354),m=n(230),g=n(350),y=n(228),b=n(293),x=r.topLevelTypes,w={abort:{phasedRegistrationNames:{bubbled:b({onAbort:!0}),captured:b({onAbortCapture:!0})}},blur:{phasedRegistrationNames:{bubbled:b({onBlur:!0}),captured:b({onBlurCapture:!0})}},canPlay:{phasedRegistrationNames:{bubbled:b({onCanPlay:!0}),captured:b({onCanPlayCapture:!0})}},canPlayThrough:{phasedRegistrationNames:{bubbled:b({onCanPlayThrough:!0}),captured:b({onCanPlayThroughCapture:!0})}},click:{phasedRegistrationNames:{bubbled:b({onClick:!0}),captured:b({onClickCapture:!0})}},contextMenu:{phasedRegistrationNames:{bubbled:b({onContextMenu:!0}),captured:b({onContextMenuCapture:!0})}},copy:{phasedRegistrationNames:{bubbled:b({onCopy:!0}),captured:b({onCopyCapture:!0})}},cut:{phasedRegistrationNames:{bubbled:b({onCut:!0}),captured:b({onCutCapture:!0})}},doubleClick:{phasedRegistrationNames:{bubbled:b({onDoubleClick:!0}),captured:b({onDoubleClickCapture:!0})}},drag:{phasedRegistrationNames:{bubbled:b({onDrag:!0}),captured:b({onDragCapture:!0})}},dragEnd:{phasedRegistrationNames:{bubbled:b({onDragEnd:!0}),captured:b({onDragEndCapture:!0})}},dragEnter:{phasedRegistrationNames:{bubbled:b({onDragEnter:!0}),captured:b({onDragEnterCapture:!0})}},dragExit:{phasedRegistrationNames:{bubbled:b({onDragExit:!0}),captured:b({onDragExitCapture:!0})}},dragLeave:{phasedRegistrationNames:{bubbled:b({onDragLeave:!0}),captured:b({onDragLeaveCapture:!0})}},dragOver:{phasedRegistrationNames:{bubbled:b({onDragOver:!0}),captured:b({onDragOverCapture:!0})}},dragStart:{phasedRegistrationNames:{bubbled:b({onDragStart:!0}),captured:b({onDragStartCapture:!0})}},drop:{phasedRegistrationNames:{bubbled:b({onDrop:!0}),captured:b({onDropCapture:!0})}},durationChange:{phasedRegistrationNames:{bubbled:b({onDurationChange:!0}),captured:b({onDurationChangeCapture:!0})}},emptied:{phasedRegistrationNames:{bubbled:b({onEmptied:!0}),captured:b({onEmptiedCapture:!0})}},encrypted:{phasedRegistrationNames:{bubbled:b({onEncrypted:!0}),captured:b({onEncryptedCapture:!0})}},ended:{phasedRegistrationNames:{bubbled:b({onEnded:!0}),captured:b({onEndedCapture:!0})}},error:{phasedRegistrationNames:{bubbled:b({onError:!0}),captured:b({onErrorCapture:!0})}},focus:{phasedRegistrationNames:{bubbled:b({onFocus:!0}),captured:b({onFocusCapture:!0})}},input:{phasedRegistrationNames:{bubbled:b({onInput:!0}),captured:b({onInputCapture:!0})}},keyDown:{phasedRegistrationNames:{bubbled:b({onKeyDown:!0}),captured:b({onKeyDownCapture:!0})}},keyPress:{phasedRegistrationNames:{bubbled:b({onKeyPress:!0}),captured:b({onKeyPressCapture:!0})}},keyUp:{phasedRegistrationNames:{bubbled:b({onKeyUp:!0}),captured:b({onKeyUpCapture:!0})}},load:{phasedRegistrationNames:{bubbled:b({onLoad:!0}),captured:b({onLoadCapture:!0})}},loadedData:{phasedRegistrationNames:{bubbled:b({onLoadedData:!0}),captured:b({onLoadedDataCapture:!0})}},loadedMetadata:{phasedRegistrationNames:{bubbled:b({onLoadedMetadata:!0}),captured:b({onLoadedMetadataCapture:!0})}},loadStart:{phasedRegistrationNames:{bubbled:b({onLoadStart:!0}),captured:b({onLoadStartCapture:!0})}},mouseDown:{phasedRegistrationNames:{bubbled:b({onMouseDown:!0}),captured:b({onMouseDownCapture:!0})}},mouseMove:{phasedRegistrationNames:{bubbled:b({onMouseMove:!0}),captured:b({onMouseMoveCapture:!0})}},mouseOut:{phasedRegistrationNames:{bubbled:b({onMouseOut:!0}),captured:b({onMouseOutCapture:!0})}},mouseOver:{phasedRegistrationNames:{bubbled:b({onMouseOver:!0}),captured:b({onMouseOverCapture:!0})}},mouseUp:{phasedRegistrationNames:{bubbled:b({onMouseUp:!0}),captured:b({onMouseUpCapture:!0})}},paste:{phasedRegistrationNames:{bubbled:b({onPaste:!0}),captured:b({onPasteCapture:!0})}},pause:{phasedRegistrationNames:{bubbled:b({onPause:!0}),captured:b({onPauseCapture:!0})}},play:{phasedRegistrationNames:{bubbled:b({onPlay:!0}),captured:b({onPlayCapture:!0})}},playing:{phasedRegistrationNames:{bubbled:b({onPlaying:!0}),captured:b({onPlayingCapture:!0})}},progress:{phasedRegistrationNames:{bubbled:b({onProgress:!0}),captured:b({onProgressCapture:!0})}},rateChange:{phasedRegistrationNames:{bubbled:b({onRateChange:!0}),captured:b({onRateChangeCapture:!0})}},reset:{phasedRegistrationNames:{bubbled:b({onReset:!0}),captured:b({onResetCapture:!0})}},scroll:{phasedRegistrationNames:{bubbled:b({onScroll:!0}),captured:b({onScrollCapture:!0})}},seeked:{phasedRegistrationNames:{bubbled:b({onSeeked:!0}),captured:b({onSeekedCapture:!0})}},seeking:{phasedRegistrationNames:{bubbled:b({onSeeking:!0}),captured:b({onSeekingCapture:!0})}},stalled:{phasedRegistrationNames:{bubbled:b({onStalled:!0}),captured:b({onStalledCapture:!0})}},submit:{phasedRegistrationNames:{bubbled:b({onSubmit:!0}),captured:b({onSubmitCapture:!0})}},suspend:{phasedRegistrationNames:{bubbled:b({onSuspend:!0}),captured:b({onSuspendCapture:!0})}},timeUpdate:{phasedRegistrationNames:{bubbled:b({onTimeUpdate:!0}),captured:b({onTimeUpdateCapture:!0})}},touchCancel:{phasedRegistrationNames:{bubbled:b({onTouchCancel:!0}),captured:b({onTouchCancelCapture:!0})}},touchEnd:{phasedRegistrationNames:{bubbled:b({onTouchEnd:!0}),captured:b({onTouchEndCapture:!0})}},touchMove:{phasedRegistrationNames:{bubbled:b({onTouchMove:!0}),captured:b({onTouchMoveCapture:!0})}},touchStart:{phasedRegistrationNames:{bubbled:b({onTouchStart:!0}),captured:b({onTouchStartCapture:!0})}},volumeChange:{phasedRegistrationNames:{bubbled:b({onVolumeChange:!0}),captured:b({onVolumeChangeCapture:!0})}},waiting:{phasedRegistrationNames:{bubbled:b({onWaiting:!0}),captured:b({onWaitingCapture:!0})}},wheel:{phasedRegistrationNames:{bubbled:b({onWheel:!0}),captured:b({onWheelCapture:!0})}}},_={topAbort:w.abort,topBlur:w.blur,topCanPlay:w.canPlay,topCanPlayThrough:w.canPlayThrough,topClick:w.click,topContextMenu:w.contextMenu,topCopy:w.copy,topCut:w.cut,topDoubleClick:w.doubleClick,topDrag:w.drag,topDragEnd:w.dragEnd,topDragEnter:w.dragEnter,topDragExit:w.dragExit,topDragLeave:w.dragLeave,topDragOver:w.dragOver,topDragStart:w.dragStart,topDrop:w.drop,topDurationChange:w.durationChange,topEmptied:w.emptied,topEncrypted:w.encrypted,topEnded:w.ended,topError:w.error,topFocus:w.focus,topInput:w.input,topKeyDown:w.keyDown,topKeyPress:w.keyPress,topKeyUp:w.keyUp,topLoad:w.load,topLoadedData:w.loadedData,topLoadedMetadata:w.loadedMetadata,topLoadStart:w.loadStart,topMouseDown:w.mouseDown,topMouseMove:w.mouseMove,topMouseOut:w.mouseOut,topMouseOver:w.mouseOver,topMouseUp:w.mouseUp,topPaste:w.paste,topPause:w.pause,topPlay:w.play,topPlaying:w.playing,topProgress:w.progress,topRateChange:w.rateChange,topReset:w.reset,topScroll:w.scroll,topSeeked:w.seeked,topSeeking:w.seeking,topStalled:w.stalled,topSubmit:w.submit,topSuspend:w.suspend,topTimeUpdate:w.timeUpdate,topTouchCancel:w.touchCancel,topTouchEnd:w.touchEnd,topTouchMove:w.touchMove,topTouchStart:w.touchStart,topVolumeChange:w.volumeChange,topWaiting:w.waiting,topWheel:w.wheel};for(var P in _)_[P].dependencies=[P];var C=b({onClick:null}),E={},R={eventTypes:w,extractEvents:function(e,t,n,r,o){var a=_[e];if(!a)return null;var m;switch(e){case x.topAbort:case x.topCanPlay:case x.topCanPlayThrough:case x.topDurationChange:case x.topEmptied:case x.topEncrypted:case x.topEnded:case x.topError:case x.topInput:case x.topLoad:case x.topLoadedData:case x.topLoadedMetadata:case x.topLoadStart:case x.topPause:case x.topPlay:case x.topPlaying:case x.topProgress:case x.topRateChange:case x.topReset:case x.topSeeked:case x.topSeeking:case x.topStalled:case x.topSubmit:case x.topSuspend:case x.topTimeUpdate:case x.topVolumeChange:case x.topWaiting:m=u;break;case x.topKeyPress:if(0===g(r))return null;case x.topKeyDown:case x.topKeyUp:m=l;break;case x.topBlur:case x.topFocus:m=c;break;case x.topClick:if(2===r.button)return null;case x.topContextMenu:case x.topDoubleClick:case x.topMouseDown:case x.topMouseMove:case x.topMouseOut:case x.topMouseOver:case x.topMouseUp:m=p;break;case x.topDrag:case x.topDragEnd:case x.topDragEnter:case x.topDragExit:case x.topDragLeave:case x.topDragOver:case x.topDragStart:case x.topDrop:m=f;break;case x.topTouchCancel:case x.topTouchEnd:case x.topTouchMove:case x.topTouchStart:m=h;break;case x.topScroll:m=d;break;case x.topWheel:m=v;break;case x.topCopy:case x.topCut:case x.topPaste:m=s}m?void 0:y(!1);var b=m.getPooled(a,n,r,o);return i.accumulateTwoPhaseDispatches(b),b},didPutListener:function(e,t){if(t===C){var n=a.getNode(e);E[e]||(E[e]=o.listen(n,"click",m))}},willDeleteListener:function(e,t){t===C&&(E[e].remove(),delete E[e])}};e.exports=R},function(e,t,n){"use strict";function r(e,t,n,r){o.call(this,e,t,n,r)}var o=n(291),i={clipboardData:function(e){return"clipboardData"in e?e.clipboardData:window.clipboardData}};o.augmentClass(r,i),e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){o.call(this,e,t,n,r)}var o=n(301),i={relatedTarget:null};o.augmentClass(r,i),e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){o.call(this,e,t,n,r)}var o=n(301),i=n(350),a=n(351),s=n(302),u={key:a,location:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,repeat:null,locale:null,getModifierState:s,charCode:function(e){return"keypress"===e.type?i(e):0},keyCode:function(e){return"keydown"===e.type||"keyup"===e.type?e.keyCode:0},which:function(e){return"keypress"===e.type?i(e):"keydown"===e.type||"keyup"===e.type?e.keyCode:0}};o.augmentClass(r,u),e.exports=r},function(e){"use strict";function t(e){var t,n=e.keyCode;return"charCode"in e?(t=e.charCode,0===t&&13===n&&(t=13)):t=n,t>=32||13===t?t:0}e.exports=t},function(e,t,n){"use strict";function r(e){if(e.key){var t=i[e.key]||e.key;if("Unidentified"!==t)return t}if("keypress"===e.type){var n=o(e);return 13===n?"Enter":String.fromCharCode(n)}return"keydown"===e.type||"keyup"===e.type?a[e.keyCode]||"Unidentified":""}var o=n(350),i={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},a={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",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",224:"Meta"};e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){o.call(this,e,t,n,r)}var o=n(300),i={dataTransfer:null};o.augmentClass(r,i),e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){o.call(this,e,t,n,r)}var o=n(301),i=n(302),a={touches:null,targetTouches:null,changedTouches:null,altKey:null,metaKey:null,ctrlKey:null,shiftKey:null,getModifierState:i};o.augmentClass(r,a),e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){o.call(this,e,t,n,r)}var o=n(300),i={deltaX:function(e){return"deltaX"in e?e.deltaX:"wheelDeltaX"in e?-e.wheelDeltaX:0},deltaY:function(e){return"deltaY"in e?e.deltaY:"wheelDeltaY"in e?-e.wheelDeltaY:"wheelDelta"in e?-e.wheelDelta:0},deltaZ:null,deltaMode:null};o.augmentClass(r,i),e.exports=r},function(e,t,n){"use strict";var r=n(238),o=r.injection.MUST_USE_ATTRIBUTE,i={xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace"},a={Properties:{clipPath:o,cx:o,cy:o,d:o,dx:o,dy:o,fill:o,fillOpacity:o,fontFamily:o,fontSize:o,fx:o,fy:o,gradientTransform:o,gradientUnits:o,markerEnd:o,markerMid:o,markerStart:o,offset:o,opacity:o,patternContentUnits:o,patternUnits:o,points:o,preserveAspectRatio:o,r:o,rx:o,ry:o,spreadMethod:o,stopColor:o,stopOpacity:o,stroke:o,strokeDasharray:o,strokeLinecap:o,strokeOpacity:o,strokeWidth:o,textAnchor:o,transform:o,version:o,viewBox:o,x1:o,x2:o,x:o,xlinkActuate:o,xlinkArcrole:o,xlinkHref:o,xlinkRole:o,xlinkShow:o,xlinkTitle:o,xlinkType:o,xmlBase:o,xmlLang:o,xmlSpace:o,y1:o,y2:o,y:o},DOMAttributeNamespaces:{xlinkActuate:i.xlink,xlinkArcrole:i.xlink,xlinkHref:i.xlink,xlinkRole:i.xlink,xlinkShow:i.xlink,xlinkTitle:i.xlink,xlinkType:i.xlink,xmlBase:i.xml,xmlLang:i.xml,xmlSpace:i.xml},DOMAttributeNames:{clipPath:"clip-path",fillOpacity:"fill-opacity",fontFamily:"font-family",fontSize:"font-size",gradientTransform:"gradientTransform",gradientUnits:"gradientUnits",markerEnd:"marker-end",markerMid:"marker-mid",markerStart:"marker-start",patternContentUnits:"patternContentUnits",patternUnits:"patternUnits",preserveAspectRatio:"preserveAspectRatio",spreadMethod:"spreadMethod",stopColor:"stop-color",stopOpacity:"stop-opacity",strokeDasharray:"stroke-dasharray",strokeLinecap:"stroke-linecap",strokeOpacity:"stroke-opacity",strokeWidth:"stroke-width",textAnchor:"text-anchor",viewBox:"viewBox",xlinkActuate:"xlink:actuate",xlinkArcrole:"xlink:arcrole",xlinkHref:"xlink:href",xlinkRole:"xlink:role",xlinkShow:"xlink:show",xlinkTitle:"xlink:title",xlinkType:"xlink:type",xmlBase:"xml:base",xmlLang:"xml:lang",xmlSpace:"xml:space"}};e.exports=a},function(e){"use strict";e.exports="0.14.0"},function(e,t,n){"use strict";var r=n(243);e.exports=r.renderSubtreeIntoContainer},function(e,t,n){"use strict";var r=n(285),o=n(359),i=n(356);r.inject();var a={renderToString:o.renderToString,renderToStaticMarkup:o.renderToStaticMarkup,version:i};e.exports=a},function(e,t,n){"use strict";function r(e){a.isValidElement(e)?void 0:d(!1);var t;try{p.injection.injectBatchingStrategy(c);var n=s.createReactRootID();return t=l.getPooled(!1),t.perform(function(){var r=h(e,null),o=r.mountComponent(n,t,f);return u.addChecksumToMarkup(o)},null)}finally{l.release(t),p.injection.injectBatchingStrategy(i)}}function o(e){a.isValidElement(e)?void 0:d(!1);var t;try{p.injection.injectBatchingStrategy(c);var n=s.createReactRootID();return t=l.getPooled(!0),t.perform(function(){var r=h(e,null);return r.mountComponent(n,t,f)},null)}finally{l.release(t),p.injection.injectBatchingStrategy(i)}}var i=n(306),a=n(257),s=n(259),u=n(262),c=n(360),l=n(361),p=n(268),f=n(272),h=n(276),d=n(228);e.exports={renderToString:r,renderToStaticMarkup:o}},function(e){"use strict";var t={isBatchingUpdates:!1,batchedUpdates:function(){}};e.exports=t},function(e,t,n){"use strict";function r(e){this.reinitializeTransaction(),this.renderToStaticMarkup=e,this.reactMountReady=i.getPooled(null),this.useCreateElement=!1}var o=n(270),i=n(269),a=n(271),s=n(254),u=n(230),c={initialize:function(){this.reactMountReady.reset()},close:u},l=[c],p={getTransactionWrappers:function(){return l},getReactMountReady:function(){return this.reactMountReady},destructor:function(){i.release(this.reactMountReady),this.reactMountReady=null}};s(r.prototype,a.Mixin,p),o.addPoolingTo(r),e.exports=r},function(e,t,n){"use strict";var r=n(324),o=n(337),i=n(336),a=n(363),s=n(257),u=(n(364),n(321)),c=n(356),l=n(254),p=n(366),f=s.createElement,h=s.createFactory,d=s.cloneElement,v={Children:{map:r.map,forEach:r.forEach,count:r.count,toArray:r.toArray,only:p},Component:o,createElement:f,cloneElement:d,isValidElement:s.isValidElement,PropTypes:u,createClass:i.createClass,createFactory:h,createMixin:function(e){return e},DOM:a,version:c,__spread:l};e.exports=v},function(e,t,n){"use strict";function r(e){return o.createFactory(e)}var o=n(257),i=(n(364),n(365)),a=i({a:"a",abbr:"abbr",address:"address",area:"area",article:"article",aside:"aside",audio:"audio",b:"b",base:"base",bdi:"bdi",bdo:"bdo",big:"big",blockquote:"blockquote",body:"body",br:"br",button:"button",canvas:"canvas",caption:"caption",cite:"cite",code:"code",col:"col",colgroup:"colgroup",data:"data",datalist:"datalist",dd:"dd",del:"del",details:"details",dfn:"dfn",dialog:"dialog",div:"div",dl:"dl",dt:"dt",em:"em",embed:"embed",fieldset:"fieldset",figcaption:"figcaption",figure:"figure",footer:"footer",form:"form",h1:"h1",h2:"h2",h3:"h3",h4:"h4",h5:"h5",h6:"h6",head:"head",header:"header",hgroup:"hgroup",hr:"hr",html:"html",i:"i",iframe:"iframe",img:"img",input:"input",ins:"ins",kbd:"kbd",keygen:"keygen",label:"label",legend:"legend",li:"li",link:"link",main:"main",map:"map",mark:"mark",menu:"menu",menuitem:"menuitem",meta:"meta",meter:"meter",nav:"nav",noscript:"noscript",object:"object",ol:"ol",optgroup:"optgroup",option:"option",output:"output",p:"p",param:"param",picture:"picture",pre:"pre",progress:"progress",q:"q",rp:"rp",rt:"rt",ruby:"ruby",s:"s",samp:"samp",script:"script",section:"section",select:"select",small:"small",source:"source",span:"span",strong:"strong", style:"style",sub:"sub",summary:"summary",sup:"sup",table:"table",tbody:"tbody",td:"td",textarea:"textarea",tfoot:"tfoot",th:"th",thead:"thead",time:"time",title:"title",tr:"tr",track:"track",u:"u",ul:"ul","var":"var",video:"video",wbr:"wbr",circle:"circle",clipPath:"clipPath",defs:"defs",ellipse:"ellipse",g:"g",image:"image",line:"line",linearGradient:"linearGradient",mask:"mask",path:"path",pattern:"pattern",polygon:"polygon",polyline:"polyline",radialGradient:"radialGradient",rect:"rect",stop:"stop",svg:"svg",text:"text",tspan:"tspan"},r);e.exports=a},function(e,t,n){"use strict";function r(){if(p.current){var e=p.current.getName();if(e)return" Check the render method of `"+e+"`."}return""}function o(e,t){if(e._store&&!e._store.validated&&null==e.key){e._store.validated=!0;{i("uniqueKey",e,t)}}}function i(e,t,n){var o=r();if(!o){var i="string"==typeof n?n:n.displayName||n.name;i&&(o=" Check the top-level render call using <"+i+">.")}var a=d[e]||(d[e]={});if(a[o])return null;a[o]=!0;var s={parentOrOwner:o,url:" See https://fb.me/react-warning-keys for more information.",childOwner:null};return t&&t._owner&&t._owner!==p.current&&(s.childOwner=" It was passed a child from "+t._owner.getName()+"."),s}function a(e,t){if("object"==typeof e)if(Array.isArray(e))for(var n=0;n<e.length;n++){var r=e[n];c.isValidElement(r)&&o(r,t)}else if(c.isValidElement(e))e._store&&(e._store.validated=!0);else if(e){var i=f(e);if(i&&i!==e.entries)for(var a,s=i.call(e);!(a=s.next()).done;)c.isValidElement(a.value)&&o(a.value,t)}}function s(e,t,n,o){for(var i in t)if(t.hasOwnProperty(i)){var a;try{"function"!=typeof t[i]?h(!1):void 0,a=t[i](n,i,e,o)}catch(s){a=s}if(a instanceof Error&&!(a.message in v)){v[a.message]=!0;{r()}}}}function u(e){var t=e.type;if("function"==typeof t){var n=t.displayName||t.name;t.propTypes&&s(n,t.propTypes,e.props,l.prop),"function"==typeof t.getDefaultProps}}var c=n(257),l=n(279),p=(n(280),n(220)),f=n(322),h=n(228),d=(n(240),{}),v={},m={createElement:function(e){var t="string"==typeof e||"function"==typeof e,n=c.createElement.apply(this,arguments);if(null==n)return n;if(t)for(var r=2;r<arguments.length;r++)a(arguments[r],e);return u(n),n},createFactory:function(e){var t=m.createElement.bind(null,e);return t.type=e,t},cloneElement:function(){for(var e=c.cloneElement.apply(this,arguments),t=2;t<arguments.length;t++)a(arguments[t],e.type);return u(e),e}};e.exports=m},function(e){"use strict";function t(e,t,r){if(!e)return null;var o={};for(var i in e)n.call(e,i)&&(o[i]=t.call(r,e[i],i,e));return o}var n=Object.prototype.hasOwnProperty;e.exports=t},function(e,t,n){"use strict";function r(e){return o.isValidElement(e)?void 0:i(!1),e}var o=n(257),i=n(228);e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r,o){return o}n(254),n(240);e.exports=r},function(e,t,n){"use strict";e.exports=n(219)},function(e,t,n){"use strict";function r(e){var t,n="string"==typeof e;if(t=n?document.querySelector(e):e,!o(t)){var r="Container must be `string` or `HTMLElement`.";throw n&&(r+=" Unable to find "+e),new Error(r)}return t}function o(e){return e instanceof HTMLElement||!!e&&e.nodeType>0}function i(e){return e.altKey||e.ctrlKey||e.metaKey||e.shiftKey}function a(e){return function(t,n){return t||n?t&&!n?e+"--"+t:t&&n?e+"--"+t+"__"+n:!t&&n?e+"__"+n:void 0:e}}function s(e){var t=e.transformData,n=e.defaultTemplates,r=e.templates,o=e.templatesConfig,i=u(n,r);return c({transformData:t,templatesConfig:o},i)}function u(e,t){return l(e,function(e,n,r){var o=t&&void 0!==t[r]&&t[r]!==n;return o?(e.templates[r]=t[r],e.useCustomCompileOptions[r]=!0):(e.templates[r]=n,e.useCustomCompileOptions[r]=!1),e},{templates:{},useCustomCompileOptions:{}})}var c=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},l=n(111),p={getContainerNode:r,bemHelper:a,prepareTemplateProps:s,isSpecialClick:i,isDomElement:o};e.exports=p},function(e,t,n){var r;!function(){"use strict";var o=function(){function e(e,t){for(var n=t.length,r=0;n>r;++r)o(e,t[r])}function t(e,t){e[t]=!0}function n(e,t){for(var n in t)a.call(t,n)&&(t[n]?e[n]=!0:delete e[n])}function r(e,t){for(var n=t.split(s),r=n.length,o=0;r>o;++o)e[n[o]]=!0}function o(o,i){if(i){var a=typeof i;"string"===a?r(o,i):Array.isArray(i)?e(o,i):"object"===a?n(o,i):"number"===a&&t(o,i)}}function i(){var t={};e(t,arguments);var n=[];for(var r in t)a.call(t,r)&&t[r]&&n.push(r);return n.join(" ")}var a={}.hasOwnProperty,s=/\s+/;return i}();"undefined"!=typeof e&&e.exports?e.exports=o:(r=function(){return o}.call(t,n,t,e),!(void 0!==r&&(e.exports=r)))}()},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){if("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 i(e){var t=function(t){function n(){r(this,n),s(Object.getPrototypeOf(n.prototype),"constructor",this).apply(this,arguments)}return o(n,t),a(n,[{key:"componentDidMount",value:function(){this._hideOrShowContainer(this.props)}},{key:"componentWillReceiveProps",value:function(e){this._hideOrShowContainer(e)}},{key:"_hideOrShowContainer",value:function(e){var t=c.findDOMNode(this).parentNode;e.hideContainerWhenNoResults===!0&&e.hasResults===!1?t.style.display="none":e.hideContainerWhenNoResults===!0&&(t.style.display="")}},{key:"render",value:function(){return this.props.hasResults===!1&&this.props.hideContainerWhenNoResults===!0?u.createElement("div",null):u.createElement(e,this.props)}}]),n}(u.Component);return t.propTypes={hasResults:u.PropTypes.bool.isRequired,hideContainerWhenNoResults:u.PropTypes.bool.isRequired},t.displayName=e.name+"-AutoHide",t}var a=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),s=function(e,t,n){for(var r=!0;r;){var o=e,i=t,a=n;r=!1,null===o&&(o=Function.prototype);var s=Object.getOwnPropertyDescriptor(o,i);if(void 0!==s){if("value"in s)return s.value;var u=s.get;return void 0===u?void 0:u.call(a)}var c=Object.getPrototypeOf(o);if(null===c)return void 0;e=c,t=i,n=a,r=!0,s=c=void 0}},u=n(217),c=n(368);e.exports=i},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){if("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 i(e){var t=function(t){function n(){r(this,n),u(Object.getPrototypeOf(n.prototype),"constructor",this).apply(this,arguments)}return o(n,t),s(n,[{key:"render",value:function(){var t=null,n=this.props.templateProps,r={root:this.props.cssClasses.root,header:l(this.props.cssClasses.header,"ais-header"),body:this.props.cssClasses.body,footer:l(this.props.cssClasses.footer,"ais-footer")};return c.createElement("div",{className:r.root},c.createElement("div",{className:r.header},c.createElement(p,a({templateKey:"header"},n,{transformData:t}))),c.createElement("div",{className:r.body},c.createElement(e,this.props)),c.createElement("div",{className:r.footer},c.createElement(p,a({templateKey:"footer"},n,{transformData:t}))))}}]),n}(c.Component);return t.propTypes={cssClasses:c.PropTypes.shape({root:c.PropTypes.string,header:c.PropTypes.string,body:c.PropTypes.string,footer:c.PropTypes.string}),templateProps:c.PropTypes.object},t.defaultProps={cssClasses:{}},t.displayName=e.name+"-HeaderFooter",t}var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},s=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),u=function(e,t,n){for(var r=!0;r;){var o=e,i=t,a=n;r=!1,null===o&&(o=Function.prototype);var s=Object.getOwnPropertyDescriptor(o,i);if(void 0!==s){if("value"in s)return s.value;var u=s.get;return void 0===u?void 0:u.call(a)}var c=Object.getPrototypeOf(o);if(null===c)return void 0;e=c,t=i,n=a,r=!0,s=c=void 0}},c=n(217),l=n(370),p=n(373);e.exports=i},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){if("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 i(e,t,n){if(!e)return n;var r;if("function"==typeof e)r=e(n);else{if("object"!=typeof e)throw new Error("`transformData` must be a function or an object");r=e[t]?e[t](n):n}var o=typeof r,i=typeof n;if(o!==i)throw new Error("`transformData` must return a `"+i+"`, got `"+o+"`.");return r}function a(e){var t=e.template,n=e.compileOptions,r=e.helpers,o=e.data,i="string"==typeof t,a="function"==typeof t;if(i||a){if(a)return t(o);var c=s(r,n,o),l=u({},o,{helpers:c});return d.compile(t,n).render(l)}throw new Error("Template must be `string` or `function`")}function s(e,t,n){return f(e,function(e){return h(function(r){var o=this,i=function(e){return d.compile(e,t).render(o)};return e.call(n,r,i)})})}var u=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},c=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),l=function(e,t,n){for(var r=!0;r;){var o=e,i=t,a=n;r=!1,null===o&&(o=Function.prototype);var s=Object.getOwnPropertyDescriptor(o,i);if(void 0!==s){if("value"in s)return s.value;var u=s.get;return void 0===u?void 0:u.call(a)}var c=Object.getPrototypeOf(o);if(null===c)return void 0;e=c,t=i,n=a,r=!0,s=c=void 0}},p=n(217),f=n(209),h=n(374),d=n(376),v=function(e){function t(){r(this,t),l(Object.getPrototypeOf(t.prototype),"constructor",this).apply(this,arguments)}return o(t,e),c(t,[{key:"render",value:function(){var e=this.props.useCustomCompileOptions[this.props.templateKey]?this.props.templatesConfig.compileOptions:{},t=a({template:this.props.templates[this.props.templateKey],compileOptions:e,helpers:this.props.templatesConfig.helpers,data:i(this.props.transformData,this.props.templateKey,this.props.data)});return null===t?null:p.createElement("div",{dangerouslySetInnerHTML:{__html:t}})}}]),t}(p.Component);v.propTypes={data:p.PropTypes.object,templateKey:p.PropTypes.string,templates:p.PropTypes.objectOf(p.PropTypes.oneOfType([p.PropTypes.string,p.PropTypes.func])),templatesConfig:p.PropTypes.shape({helpers:p.PropTypes.objectOf(p.PropTypes.func),compileOptions:p.PropTypes.shape({asString:p.PropTypes.bool,sectionTags:p.PropTypes.arrayOf(p.PropTypes.shape({o:p.PropTypes.string,c:p.PropTypes.string})),delimiters:p.PropTypes.string,disableLambda:p.PropTypes.bool})}),transformData:p.PropTypes.oneOfType([p.PropTypes.func,p.PropTypes.objectOf(p.PropTypes.func)]),useCustomCompileOptions:p.PropTypes.objectOf(p.PropTypes.bool)},v.defaultProps={data:{}},e.exports=v},function(e,t,n){var r=n(375),o=8,i=r(o);i.placeholder={},e.exports=i},function(e,t,n){function r(e){function t(n,r,a){a&&i(n,r,a)&&(r=void 0);var s=o(n,e,void 0,void 0,void 0,void 0,void 0,r);return s.placeholder=t.placeholder,s}return t}var o=n(160),i=n(52);e.exports=r},function(e,t,n){var r=n(377);r.Template=n(378).Template,r.template=r.Template,e.exports=r},function(e,t){!function(e){function t(e){"}"===e.n.substr(e.n.length-1)&&(e.n=e.n.substring(0,e.n.length-1))}function n(e){return e.trim?e.trim():e.replace(/^\s*|\s*$/g,"")}function r(e,t,n){if(t.charAt(n)!=e.charAt(0))return!1;for(var r=1,o=e.length;o>r;r++)if(t.charAt(n+r)!=e.charAt(r))return!1;return!0}function o(t,n,r,s){var u=[],c=null,l=null,p=null;for(l=r[r.length-1];t.length>0;){if(p=t.shift(),l&&"<"==l.tag&&!(p.tag in w))throw new Error("Illegal content in < super tag.");if(e.tags[p.tag]<=e.tags.$||i(p,s))r.push(p),p.nodes=o(t,p.tag,r,s);else{if("/"==p.tag){if(0===r.length)throw new Error("Closing tag without opener: /"+p.n);if(c=r.pop(),p.n!=c.n&&!a(p.n,c.n,s))throw new Error("Nesting error: "+c.n+" vs. "+p.n);return c.end=p.i,u}"\n"==p.tag&&(p.last=0==t.length||"\n"==t[0].tag)}u.push(p)}if(r.length>0)throw new Error("missing closing tag: "+r.pop().n);return u}function i(e,t){for(var n=0,r=t.length;r>n;n++)if(t[n].o==e.n)return e.tag="#",!0}function a(e,t,n){for(var r=0,o=n.length;o>r;r++)if(n[r].c==e&&n[r].o==t)return!0}function s(e){var t=[];for(var n in e)t.push('"'+c(n)+'": function(c,p,t,i) {'+e[n]+"}");return"{ "+t.join(",")+" }"}function u(e){var t=[];for(var n in e.partials)t.push('"'+c(n)+'":{name:"'+c(e.partials[n].name)+'", '+u(e.partials[n])+"}");return"partials: {"+t.join(",")+"}, subs: "+s(e.subs)}function c(e){return e.replace(y,"\\\\").replace(v,'\\"').replace(m,"\\n").replace(g,"\\r").replace(b,"\\u2028").replace(x,"\\u2029")}function l(e){return~e.indexOf(".")?"d":"f"}function p(e,t){var n="<"+(t.prefix||""),r=n+e.n+_++;return t.partials[r]={name:e.n,partials:{}},t.code+='t.b(t.rp("'+c(r)+'",c,p,"'+(e.indent||"")+'"));',r}function f(e,t){t.code+="t.b(t.t(t."+l(e.n)+'("'+c(e.n)+'",c,p,0)));'}function h(e){return"t.b("+e+");"}var d=/\S/,v=/\"/g,m=/\n/g,g=/\r/g,y=/\\/g,b=/\u2028/,x=/\u2029/;e.tags={"#":1,"^":2,"<":3,$:4,"/":5,"!":6,">":7,"=":8,_v:9,"{":10,"&":11,_t:12},e.scan=function(o,i){function a(){y.length>0&&(b.push({tag:"_t",text:new String(y)}),y="")}function s(){for(var t=!0,n=_;n<b.length;n++)if(t=e.tags[b[n].tag]<e.tags._v||"_t"==b[n].tag&&null===b[n].text.match(d),!t)return!1;return t}function u(e,t){if(a(),e&&s())for(var n,r=_;r<b.length;r++)b[r].text&&((n=b[r+1])&&">"==n.tag&&(n.indent=b[r].text.toString()),b.splice(r,1));else t||b.push({tag:"\n"});x=!1,_=b.length}function c(e,t){var r="="+C,o=e.indexOf(r,t),i=n(e.substring(e.indexOf("=",t)+1,o)).split(" ");return P=i[0],C=i[i.length-1],o+r.length-1}var l=o.length,p=0,f=1,h=2,v=p,m=null,g=null,y="",b=[],x=!1,w=0,_=0,P="{{",C="}}";for(i&&(i=i.split(" "),P=i[0],C=i[1]),w=0;l>w;w++)v==p?r(P,o,w)?(--w,a(),v=f):"\n"==o.charAt(w)?u(x):y+=o.charAt(w):v==f?(w+=P.length-1,g=e.tags[o.charAt(w+1)],m=g?o.charAt(w+1):"_v","="==m?(w=c(o,w),v=p):(g&&w++,v=h),x=w):r(C,o,w)?(b.push({tag:m,n:n(y),otag:P,ctag:C,i:"/"==m?x-P.length:w+C.length}),y="",w+=C.length-1,v=p,"{"==m&&("}}"==C?w++:t(b[b.length-1]))):y+=o.charAt(w);return u(x,!0),b};var w={_t:!0,"\n":!0,$:!0,"/":!0};e.stringify=function(t){return"{code: function (c,p,i) { "+e.wrapMain(t.code)+" },"+u(t)+"}"};var _=0;e.generate=function(t,n,r){_=0;var o={code:"",subs:{},partials:{}};return e.walk(t,o),r.asString?this.stringify(o,n,r):this.makeTemplate(o,n,r)},e.wrapMain=function(e){return'var t=this;t.b(i=i||"");'+e+"return t.fl();"},e.template=e.Template,e.makeTemplate=function(e,t,n){var r=this.makePartials(e);return r.code=new Function("c","p","i",this.wrapMain(e.code)),new this.template(r,t,this,n)},e.makePartials=function(e){var t,n={subs:{},partials:e.partials,name:e.name};for(t in n.partials)n.partials[t]=this.makePartials(n.partials[t]);for(t in e.subs)n.subs[t]=new Function("c","p","t","i",e.subs[t]);return n},e.codegen={"#":function(t,n){n.code+="if(t.s(t."+l(t.n)+'("'+c(t.n)+'",c,p,1),c,p,0,'+t.i+","+t.end+',"'+t.otag+" "+t.ctag+'")){t.rs(c,p,function(c,p,t){',e.walk(t.nodes,n),n.code+="});c.pop();}"},"^":function(t,n){n.code+="if(!t.s(t."+l(t.n)+'("'+c(t.n)+'",c,p,1),c,p,1,0,0,"")){',e.walk(t.nodes,n),n.code+="};"},">":p,"<":function(t,n){var r={partials:{},code:"",subs:{},inPartial:!0};e.walk(t.nodes,r);var o=n.partials[p(t,n)];o.subs=r.subs,o.partials=r.partials},$:function(t,n){var r={subs:{},code:"",partials:n.partials,prefix:t.n};e.walk(t.nodes,r),n.subs[t.n]=r.code,n.inPartial||(n.code+='t.sub("'+c(t.n)+'",c,p,i);')},"\n":function(e,t){t.code+=h('"\\n"'+(e.last?"":" + i"))},_v:function(e,t){t.code+="t.b(t.v(t."+l(e.n)+'("'+c(e.n)+'",c,p,0)));'},_t:function(e,t){t.code+=h('"'+c(e.text)+'"')},"{":f,"&":f},e.walk=function(t,n){for(var r,o=0,i=t.length;i>o;o++)r=e.codegen[t[o].tag],r&&r(t[o],n);return n},e.parse=function(e,t,n){return n=n||{},o(e,"",[],n.sectionTags||[])},e.cache={},e.cacheKey=function(e,t){return[e,!!t.asString,!!t.disableLambda,t.delimiters,!!t.modelGet].join("||")},e.compile=function(t,n){n=n||{};var r=e.cacheKey(t,n),o=this.cache[r];if(o){var i=o.partials;for(var a in i)delete i[a].instance;return o}return o=this.generate(this.parse(this.scan(t,n.delimiters),t,n),t,n),this.cache[r]=o}}(t)},function(e,t){!function(e){function t(e,t,n){var r;return t&&"object"==typeof t&&(void 0!==t[e]?r=t[e]:n&&t.get&&"function"==typeof t.get&&(r=t.get(e))),r}function n(e,t,n,r,o,i){function a(){}function s(){}a.prototype=e,s.prototype=e.subs;var u,c=new a;c.subs=new s,c.subsText={},c.buf="",r=r||{},c.stackSubs=r,c.subsText=i;for(u in t)r[u]||(r[u]=t[u]);for(u in r)c.subs[u]=r[u];o=o||{},c.stackPartials=o;for(u in n)o[u]||(o[u]=n[u]);for(u in o)c.partials[u]=o[u];return c}function r(e){return String(null===e||void 0===e?"":e)}function o(e){return e=r(e),l.test(e)?e.replace(i,"&amp;").replace(a,"&lt;").replace(s,"&gt;").replace(u,"&#39;").replace(c,"&quot;"):e}e.Template=function(e,t,n,r){e=e||{},this.r=e.code||this.r,this.c=n,this.options=r||{},this.text=t||"",this.partials=e.partials||{},this.subs=e.subs||{},this.buf=""},e.Template.prototype={r:function(){return""},v:o,t:r,render:function(e,t,n){return this.ri([e],t||{},n)},ri:function(e,t,n){return this.r(e,t,n)},ep:function(e,t){var r=this.partials[e],o=t[r.name];if(r.instance&&r.base==o)return r.instance;if("string"==typeof o){if(!this.c)throw new Error("No compiler available.");o=this.c.compile(o,this.options)}if(!o)return null;if(this.partials[e].base=o,r.subs){t.stackText||(t.stackText={});for(key in r.subs)t.stackText[key]||(t.stackText[key]=void 0!==this.activeSub&&t.stackText[this.activeSub]?t.stackText[this.activeSub]:this.text);o=n(o,r.subs,r.partials,this.stackSubs,this.stackPartials,t.stackText)}return this.partials[e].instance=o,o},rp:function(e,t,n,r){var o=this.ep(e,n);return o?o.ri(t,n,r):""},rs:function(e,t,n){var r=e[e.length-1];if(!p(r))return void n(e,t,this);for(var o=0;o<r.length;o++)e.push(r[o]),n(e,t,this),e.pop()},s:function(e,t,n,r,o,i,a){var s;return p(e)&&0===e.length?!1:("function"==typeof e&&(e=this.ms(e,t,n,r,o,i,a)),s=!!e,!r&&s&&t&&t.push("object"==typeof e?e:t[t.length-1]),s)},d:function(e,n,r,o){var i,a=e.split("."),s=this.f(a[0],n,r,o),u=this.options.modelGet,c=null;if("."===e&&p(n[n.length-2]))s=n[n.length-1];else for(var l=1;l<a.length;l++)i=t(a[l],s,u),void 0!==i?(c=s,s=i):s="";return o&&!s?!1:(o||"function"!=typeof s||(n.push(c),s=this.mv(s,n,r),n.pop()),s)},f:function(e,n,r,o){for(var i=!1,a=null,s=!1,u=this.options.modelGet,c=n.length-1;c>=0;c--)if(a=n[c],i=t(e,a,u),void 0!==i){s=!0;break}return s?(o||"function"!=typeof i||(i=this.mv(i,n,r)),i):o?!1:""},ls:function(e,t,n,o,i){var a=this.options.delimiters;return this.options.delimiters=i,this.b(this.ct(r(e.call(t,o)),t,n)),this.options.delimiters=a,!1},ct:function(e,t,n){if(this.options.disableLambda)throw new Error("Lambda features disabled.");return this.c.compile(e,this.options).render(t,n)},b:function(e){this.buf+=e},fl:function(){var e=this.buf;return this.buf="",e},ms:function(e,t,n,r,o,i,a){var s,u=t[t.length-1],c=e.call(u);return"function"==typeof c?r?!0:(s=this.activeSub&&this.subsText&&this.subsText[this.activeSub]?this.subsText[this.activeSub]:this.text,this.ls(c,u,n,s.substring(o,i),a)):c},mv:function(e,t,n){var o=t[t.length-1],i=e.call(o);return"function"==typeof i?this.ct(r(i.call(o)),o,n):i},sub:function(e,t,n,r){var o=this.subs[e];o&&(this.activeSub=e,o(t,n,this,r),this.activeSub=!1)}};var i=/&/g,a=/</g,s=/>/g,u=/\'/g,c=/\"/g,l=/[&<>\"\']/,p=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)}}(t)},function(e,t,n){"use strict";function r(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},s=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),u=function(e,t,n){for(var r=!0;r;){var o=e,i=t,a=n;r=!1,null===o&&(o=Function.prototype);var s=Object.getOwnPropertyDescriptor(o,i);if(void 0!==s){if("value"in s)return s.value;var u=s.get;return void 0===u?void 0:u.call(a)}var c=Object.getPrototypeOf(o);if(null===c)return void 0;e=c,t=i,n=a,r=!0,s=c=void 0}},c=n(217),l=n(380),p=n(373),f=n(369),h=f.isSpecialClick,d=function(e){function t(){o(this,t),u(Object.getPrototypeOf(t.prototype),"constructor",this).apply(this,arguments)}return i(t,e),s(t,[{key:"refine",value:function(e){this.props.toggleRefinement(e)}},{key:"_generateFacetItem",value:function(e){var n,o=e.data&&e.data.length>0;o&&(n=c.createElement(t,a({},this.props,{depth:this.props.depth+1,facetValues:e.data})));var i=e;this.props.createURL&&(i.url=this.props.createURL(e[this.props.facetNameKey]));var s=a({},e,{cssClasses:this.props.cssClasses}),u=l(this.props.cssClasses.item,r({},this.props.cssClasses.active,e.isRefined));return c.createElement("div",{className:u,key:e[this.props.facetNameKey],onClick:this.handleClick.bind(this,e[this.props.facetNameKey])},c.createElement(p,a({data:s,templateKey:"item"},this.props.templateProps)),n)}},{key:"handleClick",value:function(e,t){if(!h(t)){if("INPUT"===t.target.tagName)return void this.refine(e);for(var n=t.target;n!==t.currentTarget;){if("LABEL"===n.tagName&&n.querySelector('input[type="checkbox"]'))return;"A"===n.tagName&&n.href&&t.preventDefault(),n=n.parentNode}t.stopPropagation(),this.refine(e)}}},{key:"render",value:function(){var e=[this.props.cssClasses.list];return this.props.cssClasses.depth&&e.push(""+this.props.cssClasses.depth+this.props.depth),c.createElement("div",{className:l(e)},this.props.facetValues.map(this._generateFacetItem,this))}}]),t}(c.Component);d.propTypes={Template:c.PropTypes.func,createURL:c.PropTypes.func.isRequired,cssClasses:c.PropTypes.shape({active:c.PropTypes.string,depth:c.PropTypes.string,item:c.PropTypes.string,list:c.PropTypes.string}),depth:c.PropTypes.number,facetNameKey:c.PropTypes.string,facetValues:c.PropTypes.array,templateProps:c.PropTypes.object.isRequired,toggleRefinement:c.PropTypes.func.isRequired},d.defaultProps={cssClasses:{},depth:0,facetNameKey:"name"},e.exports=d},function(e,t,n){var r;!function(){"use strict";function o(){for(var e="",t=0;t<arguments.length;t++){var n=arguments[t];if(n){var r=typeof n;if("string"===r||"number"===r)e+=" "+n;else if(Array.isArray(n))e+=" "+o.apply(null,n);else if("object"===r)for(var a in n)i.call(n,a)&&n[a]&&(e+=" "+a)}}return e.substr(1)}var i={}.hasOwnProperty;"undefined"!=typeof e&&e.exports?e.exports=o:(r=function(){return o}.call(t,n,t,e),!(void 0!==r&&(e.exports=r)))}()},function(e){"use strict";e.exports={header:"",item:'<a class="{{cssClasses.link}}" href="{{url}}">{{name}} <span class="{{cssClasses.count}}">{{count}}</span></a>',footer:""}},function(e,t,n){"use strict";function r(e){var t=e.container,n=e.cssClasses,r=void 0===n?{}:n,p=e.templates,f=void 0===p?l:p,h=e.transformData,d=e.hitsPerPage,v=void 0===d?20:d,m=a.getContainerNode(t),g="Usage: hits({container, [cssClasses.{root,empty,item}, templates.{empty,item}, transformData.{empty,item}, hitsPerPage])";if(null===t)throw new Error(g);return r={root:u(s(null),r.root),item:u(s("item"),r.item),empty:u(s(null,"empty"),r.empty)},{getConfiguration:function(){return{hitsPerPage:v}},render:function(e){var t=e.results,n=e.templatesConfig,s=a.prepareTemplateProps({transformData:h,defaultTemplates:l,templatesConfig:n,templates:f});i.render(o.createElement(c,{cssClasses:r,hits:t.hits,results:t,templateProps:s}),m)}}}var o=n(217),i=n(368),a=n(369),s=a.bemHelper("ais-hits"),u=n(370),c=n(383),l=n(384);e.exports=r},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},a=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),s=function(e,t,n){for(var r=!0;r;){var o=e,i=t,a=n;r=!1,null===o&&(o=Function.prototype);var s=Object.getOwnPropertyDescriptor(o,i);if(void 0!==s){if("value"in s)return s.value;var u=s.get;return void 0===u?void 0:u.call(a)}var c=Object.getPrototypeOf(o);if(null===c)return void 0;e=c,t=i,n=a,r=!0,s=c=void 0}},u=n(217),c=n(108),l=n(373),p=function(e){function t(){r(this,t),s(Object.getPrototypeOf(t.prototype),"constructor",this).apply(this,arguments)}return o(t,e),a(t,[{key:"renderWithResults",value:function(){var e=this,t=c(this.props.results.hits,function(t){return u.createElement("div",{className:e.props.cssClasses.item,key:t.objectID},u.createElement(l,i({data:t,templateKey:"item"},e.props.templateProps)))});return u.createElement("div",{className:this.props.cssClasses.root},t)}},{key:"renderNoResults",value:function(){var e=this.props.cssClasses.root+" "+this.props.cssClasses.empty;return u.createElement("div",{className:e},u.createElement(l,i({data:this.props.results,templateKey:"empty"},this.props.templateProps)))}},{key:"render",value:function(){return this.props.results.hits.length>0?this.renderWithResults():this.renderNoResults()}}]),t}(u.Component);p.propTypes={cssClasses:u.PropTypes.shape({root:u.PropTypes.string,item:u.PropTypes.string,empty:u.PropTypes.string}),results:u.PropTypes.object,templateProps:u.PropTypes.object.isRequired},p.defaultProps={results:{hits:[]}},e.exports=p},function(e){"use strict";e.exports={empty:"No results",item:function(e){return JSON.stringify(e,null,2)}}},function(e,t,n){"use strict";function r(e){var t=e.container,r=e.options,p=e.cssClasses,f=void 0===p?{}:p,h=e.hideContainerWhenNoResults,d=void 0===h?!1:h,v=a.getContainerNode(t),m="Usage: hitsPerPageSelector({container, options[, cssClasses.{root,item}, hideContainerWhenNoResults]})";if(!t||!r)throw new Error(m);return{init:function(e){var t=s(r,function(t,n){return t||+e.hitsPerPage===+n.value},!1);if(!t)throw new Error("[hitsPerPageSelector]: No option in `options` with `value: "+e.hitsPerPage+"`")},setHitsPerPage:function(e,t){e.setQueryParameter("hitsPerPage",+t),e.search()},render:function(e){var t=e.helper,a=e.state,s=e.results,p=a.hitsPerPage,h=s.hits.length>0,m=this.setHitsPerPage.bind(this,t),g=l(n(386));f={root:c(u(null),f.root),item:c(u("item"),f.item)},i.render(o.createElement(g,{cssClasses:f,currentValue:p,hasResults:h,hideContainerWhenNoResults:d,options:r,setValue:m}),v)}}}var o=n(217),i=n(368),a=n(369),s=n(111),u=a.bemHelper("ais-hits-per-page-selector"),c=n(380),l=n(371);e.exports=r},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var i=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),a=function(e,t,n){for(var r=!0;r;){var o=e,i=t,a=n;r=!1,null===o&&(o=Function.prototype);var s=Object.getOwnPropertyDescriptor(o,i);if(void 0!==s){if("value"in s)return s.value;var u=s.get;return void 0===u?void 0:u.call(a)}var c=Object.getPrototypeOf(o);if(null===c)return void 0;e=c,t=i,n=a,r=!0,s=c=void 0}},s=n(217),u=function(e){function t(){r(this,t),a(Object.getPrototypeOf(t.prototype),"constructor",this).apply(this,arguments)}return o(t,e),i(t,[{key:"handleChange",value:function(e){this.props.setValue(e.target.value)}},{key:"render",value:function(){var e=this,t=this.props,n=t.currentValue,r=t.options,o=this.handleChange.bind(this);return s.createElement("select",{className:this.props.cssClasses.root,onChange:o,value:n},r.map(function(t){return s.createElement("option",{className:e.props.cssClasses.item,key:t.value,value:t.value},t.label)}))}}]),t}(s.Component);u.propTypes={cssClasses:s.PropTypes.shape({root:s.PropTypes.oneOfType([s.PropTypes.string,s.PropTypes.arrayOf(s.PropTypes.string)]),item:s.PropTypes.oneOfType([s.PropTypes.string,s.PropTypes.arrayOf(s.PropTypes.string)])}),currentValue:s.PropTypes.oneOfType([s.PropTypes.string,s.PropTypes.number]).isRequired,options:s.PropTypes.arrayOf(s.PropTypes.shape({value:s.PropTypes.oneOfType([s.PropTypes.string,s.PropTypes.number]).isRequired,label:s.PropTypes.string.isRequired})).isRequired,setValue:s.PropTypes.func.isRequired},e.exports=u},function(e,t,n){"use strict";function r(e){var t=e.container,r=e.indices,f=e.cssClasses,h=void 0===f?{}:f,d=e.hideContainerWhenNoResults,v=void 0===d?!1:d,m=u.getContainerNode(t),g="Usage: indexSelector({container, indices[, cssClasses.{root,item}, hideContainerWhenNoResults]})";if(!t||!r)throw new Error(g);var y=s(r,function(e){return{label:e.label,value:e.name}});return{init:function(e,t){var n=t.getIndex(),o=-1!==a(r,{name:n});if(!o)throw new Error("[indexSelector]: Index "+n+" not present in `indices`")},setIndex:function(e,t){e.setIndex(t),e.search()},render:function(e){var t=e.helper,r=e.results,a=t.getIndex(),s=r.hits.length>0,u=this.setIndex.bind(this,t),f=p(n(386));h={root:l(c(null),h.root),item:l(c("item"),h.item)},i.render(o.createElement(f,{cssClasses:h,currentValue:a,hasResults:s,hideContainerWhenNoResults:v,options:y,setValue:u}),m)}}}var o=n(217),i=n(368),a=n(143),s=n(108),u=n(369),c=u.bemHelper("ais-index-selector"),l=n(380),p=n(371);e.exports=r},function(e,t,n){"use strict";function r(e){var t=e.container,n=e.facetName,r=e.sortBy,p=void 0===r?["count:desc"]:r,f=e.limit,v=void 0===f?100:f,m=e.cssClasses,g=void 0===m?{}:m,y=e.templates,b=void 0===y?d:y,x=e.transformData,w=e.hideContainerWhenNoResults,_=void 0===w?!0:w,P=u.getContainerNode(t),C="Usage: menu({container, facetName, [sortBy, limit, cssClasses.{root,list,item}, templates.{header,item,footer}, transformData, hideWhenResults]})"; if(!t||!n)throw new Error(C);var E=n;return{getConfiguration:function(){return{hierarchicalFacets:[{name:E,attributes:[n]}]}},render:function(e){var t=e.results,n=e.helper,r=e.templatesConfig,f=e.state,m=e.createURL,y=i(t,E,p,v),w=u.prepareTemplateProps({transformData:x,defaultTemplates:d,templatesConfig:r,templates:b});g={root:l(c(null),g.root),header:l(c("header"),g.header),body:l(c("body"),g.body),footer:l(c("footer"),g.footer),list:l(c("list"),g.list),item:l(c("item"),g.item),active:l(c("item","active"),g.active),link:l(c("link"),g.link),count:l(c("count"),g.count)},s.render(a.createElement(h,{createURL:function(e){return m(f.toggleRefinement(E,e))},cssClasses:g,facetValues:y,hasResults:y.length>0,hideContainerWhenNoResults:_,templateProps:w,toggleRefinement:o.bind(null,n,E)}),P)}}}function o(e,t,n){e.toggleRefinement(t,n).search()}function i(e,t,n,r){var o=e.getFacetValues(t,{sortBy:n});return o.data&&o.data.slice(0,r)||[]}var a=n(217),s=n(368),u=n(369),c=u.bemHelper("ais-menu"),l=n(370),p=n(371),f=n(372),h=p(f(n(379))),d=n(389);e.exports=r},function(e){"use strict";e.exports={header:"",item:'<a class="{{cssClasses.link}}" href="{{url}}">{{name}} <span class="{{cssClasses.count}}">{{count}}</span></a>',footer:""}},function(e,t,n){"use strict";function r(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function o(e){var t=e.container,n=e.facetName,o=e.operator,p=void 0===o?"or":o,f=e.sortBy,v=void 0===f?["count:desc"]:f,m=e.limit,g=void 0===m?1e3:m,y=e.cssClasses,b=void 0===y?{}:y,x=e.templates,w=void 0===x?d:x,_=e.transformData,P=e.hideContainerWhenNoResults,C=void 0===P?!0:P,E=u.getContainerNode(t),R="Usage: refinementList({container, facetName, [operator, sortBy, limit, cssClasses.{root,header,body,footer,list,item,active,label,checkbox,count}, templates.{header,item,footer}, transformData, hideIfNoResults]})";if(!t||!n)throw new Error(R);if(p&&(p=p.toLowerCase(),"and"!==p&&"or"!==p))throw new Error(R);return{getConfiguration:function(e){var t=r({},"and"===p?"facets":"disjunctiveFacets",[n]);return(!e.maxValuesPerFacet||g>e.maxValuesPerFacet)&&(t.maxValuesPerFacet=g),t},render:function(e){var t=e.results,r=e.helper,o=e.templatesConfig,p=e.state,f=e.createURL,m=u.prepareTemplateProps({transformData:_,defaultTemplates:d,templatesConfig:o,templates:w}),y=t.getFacetValues(n,{sortBy:v}).slice(0,g);b={root:l(c(null),b.root),header:l(c("header"),b.header),body:l(c("body"),b.body),footer:l(c("footer"),b.footer),list:l(c("list"),b.list),item:l(c("item"),b.item),active:l(c("item","active"),b.active),label:l(c("label"),b.label),checkbox:l(c("checkbox"),b.checkbox),count:l(c("count"),b.count)},s.render(a.createElement(h,{createURL:function(e){return f(p.toggleRefinement(n,e))},cssClasses:b,facetValues:y,hasResults:y.length>0,hideContainerWhenNoResults:C,templateProps:m,toggleRefinement:i.bind(null,r,n)}),E)}}}function i(e,t,n){e.toggleRefinement(t,n).search()}var a=n(217),s=n(368),u=n(369),c=u.bemHelper("ais-refinement-list"),l=n(370),p=n(371),f=n(372),h=p(f(n(379))),d=n(391);e.exports=o},function(e){"use strict";e.exports={header:"",item:'<label class="{{cssClasses.label}}">\n <input type="checkbox" class="{{cssClasses.checkbox}}" value="{{name}}" {{#isRefined}}checked{{/isRefined}} />{{name}}\n <span class="{{cssClasses.count}}">{{count}}</span>\n</label>',footer:""}},function(e,t,n){"use strict";function r(e){var t=e.container,r=e.cssClasses,l=void 0===r?{}:r,p=e.labels,f=void 0===p?{}:p,h=e.maxPages,d=void 0===h?20:h,v=e.padding,m=void 0===v?3:v,g=e.showFirstLast,y=void 0===g?!0:g,b=e.hideContainerWhenNoResults,x=void 0===b?!0:b,w=e.scrollTo,_=void 0===w?"body":w;_===!0&&(_="body");var P=s.getContainerNode(t),C=_!==!1?s.getContainerNode(_):!1;if(!t)throw new Error("Usage: pagination({container[, cssClasses.{root,item,page,previous,next,first,last,active,disabled}, labels.{previous,next,first,last}, maxPages, showFirstLast, hideContainerWhenNoResults]})");return f=a(f,c),{setCurrentPage:function(e,t){e.setCurrentPage(t),C!==!1&&C.scrollIntoView(),e.search()},render:function(e){var t=e.results,r=e.helper,a=e.createURL,s=e.state,c=t.page,p=t.nbPages,h=t.nbHits,v=h>0;void 0!==d&&(p=Math.min(d,t.nbPages));var g=u(n(393));i.render(o.createElement(g,{createURL:function(e){return a(s.setPage(e))},cssClasses:l,currentPage:c,hasResults:v,hideContainerWhenNoResults:x,labels:f,nbHits:h,nbPages:p,padding:m,setCurrentPage:this.setCurrentPage.bind(this,r),showFirstLast:y}),P)}}}var o=n(217),i=n(368),a=n(133),s=n(369),u=n(371),c={previous:"‹",next:"›",first:"«",last:"»"};e.exports=r},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var i=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),a=function(e,t,n){for(var r=!0;r;){var o=e,i=t,a=n;r=!1,null===o&&(o=Function.prototype);var s=Object.getOwnPropertyDescriptor(o,i);if(void 0!==s){if("value"in s)return s.value;var u=s.get;return void 0===u?void 0:u.call(a)}var c=Object.getPrototypeOf(o);if(null===c)return void 0;e=c,t=i,n=a,r=!0,s=c=void 0}},s=n(217),u=n(17),c=n(394),l=n(369),p=l.isSpecialClick,f=n(396),h=n(398),d=n(369).bemHelper("ais-pagination"),v=n(380),m=function(e){function t(e){r(this,t),a(Object.getPrototypeOf(t.prototype),"constructor",this).call(this,c(e,t.defaultProps))}return o(t,e),i(t,[{key:"handleClick",value:function(e,t){p(t)||(t.preventDefault(),this.props.setCurrentPage(e))}},{key:"pageLink",value:function(e){var t=e.label,n=e.ariaLabel,r=e.pageNumber,o=e.className,i=void 0===o?null:o,a=e.isDisabled,u=void 0===a?!1:a,c=e.isActive,l=void 0===c?!1:c,p=e.createURL,f=this.handleClick.bind(this,r);i=v(d("item"),i),u&&(i=v(d("item","disabled"),this.props.cssClasses.disabled,i)),l&&(i=v(d("item-page","active"),this.props.cssClasses.active,i));var m=p&&!u?p(r):"#";return s.createElement(h,{ariaLabel:n,className:i,handleClick:f,key:t,label:t,url:m})}},{key:"previousPageLink",value:function(e,t){var n=v(d("item-previous"),this.props.cssClasses.previous);return this.pageLink({ariaLabel:"Previous",className:n,isDisabled:e.isFirstPage(),label:this.props.labels.previous,pageNumber:e.currentPage-1,createURL:t})}},{key:"nextPageLink",value:function(e,t){var n=v(d("item-next"),this.props.cssClasses.next);return this.pageLink({ariaLabel:"Next",className:n,isDisabled:e.isLastPage(),label:this.props.labels.next,pageNumber:e.currentPage+1,createURL:t})}},{key:"firstPageLink",value:function(e,t){var n=v(d("item-first"),this.props.cssClasses.first);return this.pageLink({ariaLabel:"First",className:n,isDisabled:e.isFirstPage(),label:this.props.labels.first,pageNumber:0,createURL:t})}},{key:"lastPageLink",value:function(e,t){var n=v(d("item-last"),this.props.cssClasses.last);return this.pageLink({ariaLabel:"Last",className:n,isDisabled:e.isLastPage(),label:this.props.labels.last,pageNumber:e.total-1,createURL:t})}},{key:"pages",value:function n(e,t){var r=this,n=[],o=v(d("item-page"),this.props.cssClasses.item);return u(e.pages(),function(i){var a=i===e.currentPage;n.push(r.pageLink({ariaLabel:i+1,className:o,isActive:a,label:i+1,pageNumber:i,createURL:t}))}),n}},{key:"render",value:function(){var e=new f({currentPage:this.props.currentPage,total:this.props.nbPages,padding:this.props.padding}),t=v(d(null),this.props.cssClasses.root),n=this.props.createURL;return s.createElement("ul",{className:t},this.props.showFirstLast?this.firstPageLink(e,n):null,this.previousPageLink(e,n),this.pages(e,n),this.nextPageLink(e,n),this.props.showFirstLast?this.lastPageLink(e,n):null)}}]),t}(s.Component);m.propTypes={createURL:s.PropTypes.func,cssClasses:s.PropTypes.shape({root:s.PropTypes.string,item:s.PropTypes.string,page:s.PropTypes.string,previous:s.PropTypes.string,next:s.PropTypes.string,first:s.PropTypes.string,last:s.PropTypes.string,active:s.PropTypes.string,disabled:s.PropTypes.string}),currentPage:s.PropTypes.number,labels:s.PropTypes.shape({first:s.PropTypes.string,last:s.PropTypes.string,next:s.PropTypes.string,previous:s.PropTypes.string}),nbHits:s.PropTypes.number,nbPages:s.PropTypes.number,padding:s.PropTypes.number,setCurrentPage:s.PropTypes.func.isRequired,showFirstLast:s.PropTypes.bool},m.defaultProps={nbHits:0,currentPage:0,nbPages:0},e.exports=m},function(e,t,n){var r=n(137),o=n(53),i=n(395),a=r(o,i);e.exports=a},function(e,t,n){function r(e,t){return void 0===e?t:o(e,t,r)}var o=n(53);e.exports=r},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var o=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),i=n(397),a=function(){function e(t){r(this,e),this.currentPage=t.currentPage,this.total=t.total,this.padding=t.padding}return o(e,[{key:"pages",value:function(){var e=this.currentPage,t=this.padding,n=Math.min(this.calculatePaddingLeft(e,t,this.total),this.total),r=Math.max(Math.min(2*t+1,this.total)-n,1),o=Math.max(e-n,0),a=e+r;return i(o,a)}},{key:"calculatePaddingLeft",value:function(e,t,n){return t>=e?e:e>=n-t?2*t+1-(n-e):t}},{key:"isLastPage",value:function(){return this.currentPage===this.total-1}},{key:"isFirstPage",value:function(){return 0===this.currentPage}}]),e}();e.exports=a},function(e,t,n){function r(e,t,n){n&&o(e,t,n)&&(t=n=void 0),e=+e||0,n=null==n?1:+n||0,null==t?(t=e,e=0):t=+t||0;for(var r=-1,s=a(i((t-e)/(n||1)),0),u=Array(s);++r<s;)u[r]=e,e+=n;return u}var o=n(52),i=Math.ceil,a=Math.max;e.exports=r},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var i=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),a=function(e,t,n){for(var r=!0;r;){var o=e,i=t,a=n;r=!1,null===o&&(o=Function.prototype);var s=Object.getOwnPropertyDescriptor(o,i);if(void 0!==s){if("value"in s)return s.value;var u=s.get;return void 0===u?void 0:u.call(a)}var c=Object.getPrototypeOf(o);if(null===c)return void 0;e=c,t=i,n=a,r=!0,s=c=void 0}},s=n(217),u=function(e){function t(){r(this,t),a(Object.getPrototypeOf(t.prototype),"constructor",this).apply(this,arguments)}return o(t,e),i(t,[{key:"render",value:function(){var e=this.props,t=e.className,n=e.label,r=e.ariaLabel,o=e.handleClick,i=e.url;return s.createElement("li",{className:t},s.createElement("a",{ariaLabel:r,className:t,dangerouslySetInnerHTML:{__html:n},href:i,onClick:o}))}}]),t}(s.Component);u.propTypes={ariaLabel:s.PropTypes.oneOfType([s.PropTypes.string,s.PropTypes.number]).isRequired,className:s.PropTypes.string,handleClick:s.PropTypes.func.isRequired,label:s.PropTypes.oneOfType([s.PropTypes.string,s.PropTypes.number]).isRequired,url:s.PropTypes.string},e.exports=u},function(e,t,n){"use strict";function r(e){var t=e.container,r=void 0===t?null:t,h=e.facetName,d=void 0===h?null:h,v=e.cssClasses,m=void 0===v?{}:v,g=e.templates,y=void 0===g?u:g,b=e.labels,x=void 0===b?{currency:"$",button:"Go",to:"to"}:b,w=e.hideContainerWhenNoResults,_=void 0===w?!0:w,P=a.getContainerNode(r),C="Usage: priceRanges({container, facetName, [cssClasses, templates, labels]})";if(null===r||null===d)throw new Error(C);return{getConfiguration:function(){return{facets:[d]}},_generateRanges:function(e){var t=e.getFacetStats(d);return s(t)},_extractRefinedRange:function(e){var t,n,r=e.getRefinements(d);return 0===r.length?[]:(r.forEach(function(e){-1!==e.operator.indexOf(">")?t=e.value[0]+1:-1!==e.operator.indexOf("<")&&(n=e.value[0]-1)}),[{from:t,to:n,isRefined:!0}])},_refine:function(e,t,n){var r=this._extractRefinedRange(e);e.clearRefinements(d),(0===r.length||r[0].from!==t||r[0].to!==n)&&("undefined"!=typeof t&&e.addNumericRefinement(d,">",t-1),"undefined"!=typeof n&&e.addNumericRefinement(d,"<",n+1)),e.search()},render:function(e){var t,r=e.results,s=e.helper,h=e.templatesConfig,v=e.state,g=e.createURL,b=c(l(n(402)));r.hits.length>0?(t=this._extractRefinedRange(s),0===t.length&&(t=this._generateRanges(r))):t=[];var w=a.prepareTemplateProps({defaultTemplates:u,templatesConfig:h,templates:y});m={root:f(p(null),m.root),header:f(p("header"),m.header),body:f(p("body"),m.body),footer:f(p("footer"),m.footer),range:f(p("range"),m.range),active:f(p("range","active"),m.active),input:f(p("input"),m.input),form:f(p("form"),m.form),button:f(p("button"),m.button)},i.render(o.createElement(b,{createURL:function(e,t,n){var r=v.clearRefinements(d);return n||("undefined"!=typeof e&&(r=r.addNumericRefinement(d,">",e-1)),"undefined"!=typeof t&&(r=r.addNumericRefinement(d,"<",t+1))),g(r)},cssClasses:m,facetValues:t,hasResults:r.hits.length>0,hideContainerWhenNoResults:_,labels:x,refine:this._refine.bind(this,s),templateProps:w}),P)}}}var o=n(217),i=n(368),a=n(369),s=n(400),u=n(401),c=n(371),l=n(372),p=a.bemHelper("ais-price-ranges"),f=n(370);e.exports=r},function(e){"use strict";function t(e,t){var n=Math.round(e/t)*t;return 1>n&&(n=1),n}function n(e){var n;n=e.avg<100?1:e.avg<1e3?10:100;for(var r=t(Math.round(e.avg),n),o=Math.ceil(e.min),i=t(Math.floor(e.max),n);i>e.max;)i-=n;var a,s,u=[];if(o!==i){for(a=t(o,n),u.push({to:a});r>a;)s=u[u.length-1].to,a=t(s+(r-o)/3,n),s>=a&&(a=s+1),u.push({from:s,to:a});for(;i>a;)s=u[u.length-1].to,a=t(s+(i-r)/3,n),s>=a&&(a=s+1),u.push({from:s,to:a});1===u.length&&a!==r&&(u.push({from:a,to:r}),a=r),1===u.length?(u[0].from=e.min,u[0].to=e.max):delete u[u.length-1].to}return u}e.exports=n},function(e){"use strict";e.exports={header:"",range:"\n {{#from}}\n {{^to}}\n &ge;\n {{/to}}\n ${{from}}\n {{/from}}\n {{#to}}\n {{#from}}\n -\n {{/from}}\n {{^from}}\n &le;\n {{/from}}\n ${{to}}\n {{/to}}\n <span>{{count}}</span>",footer:""}},function(e,t,n){"use strict";function r(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},s=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),u=function(e,t,n){for(var r=!0;r;){var o=e,i=t,a=n;r=!1,null===o&&(o=Function.prototype);var s=Object.getOwnPropertyDescriptor(o,i);if(void 0!==s){if("value"in s)return s.value;var u=s.get;return void 0===u?void 0:u.call(a)}var c=Object.getPrototypeOf(o);if(null===c)return void 0;e=c,t=i,n=a,r=!0,s=c=void 0}},c=n(217),l=n(373),p=n(380),f=function(e){function t(){o(this,t),u(Object.getPrototypeOf(t.prototype),"constructor",this).apply(this,arguments)}return i(t,e),s(t,[{key:"refine",value:function(e,t,n){n.preventDefault(),this.refs.from.value=this.refs.to.value="",this.props.refine(e,t)}},{key:"_handleSubmit",value:function(e){this.refine(+this.refs.from.value||void 0,+this.refs.to.value||void 0,e)}},{key:"render",value:function(){var e=this;return c.createElement("div",null,this.props.facetValues.map(function(t){var n,o=t.from+"_"+t.to;return n=e.props.createURL?e.props.createURL(t.from,t.to,t.isRefined):"#",c.createElement("a",{className:p(e.props.cssClasses.range,r({},e.props.cssClasses.active,t.isRefined)),href:n,key:o,onClick:e.refine.bind(e,t.from,t.to)},c.createElement(l,a({data:t,templateKey:"range"},e.props.templateProps)))}),c.createElement("form",{className:this.props.cssClasses.form,onSubmit:this._handleSubmit.bind(this),ref:"form"},c.createElement("label",null,this.props.labels.currency," ",c.createElement("input",{className:this.props.cssClasses.input,ref:"from",type:"number"}))," ",this.props.labels.to," ",c.createElement("label",null,this.props.labels.currency," ",c.createElement("input",{className:this.props.cssClasses.input,ref:"to",type:"number"}))," ",c.createElement("button",{className:this.props.cssClasses.button,type:"submit"},this.props.labels.button)))}}]),t}(c.Component);f.propTypes={createURL:c.PropTypes.func.isRequired,cssClasses:c.PropTypes.shape({active:c.PropTypes.string,form:c.PropTypes.string,range:c.PropTypes.string,input:c.PropTypes.string,button:c.PropTypes.string}),facetValues:c.PropTypes.array,labels:c.PropTypes.shape({button:c.PropTypes.string,currency:c.PropTypes.string,to:c.PropTypes.string}),refine:c.PropTypes.func.isRequired,templateProps:c.PropTypes.object.isRequired},e.exports=f},function(e,t,n){"use strict";function r(e){var t=e.container,r=e.placeholder,l=void 0===r?"":r,p=e.cssClasses,f=void 0===p?{}:p,h=e.poweredBy,d=void 0===h?!1:h,v=e.wrapInput,m=void 0===v?!0:v,g=e.autofocus,y=void 0===g?"auto":g;if(!t)throw new Error("Usage: searchBox({container[, placeholder, cssClasses.{input,poweredBy}, poweredBy, wrapInput, autofocus]})");return t=a.getContainerNode(t),"boolean"!=typeof y&&(y="auto"),{getInput:function(){return"INPUT"===t.tagName?t:document.createElement("input")},wrapInput:function(e){var t=document.createElement("div");return t.classList.add(c(u(null),f.root)),t.appendChild(e),t},addDefaultAttributesToInput:function(e,t){var n={autocapitalize:"off",autocomplete:"off",autocorrect:"off",placeholder:l,role:"textbox",spellcheck:"false",type:"text",value:t};s(n,function(t,n){e.hasAttribute(n)||e.setAttribute(n,t)}),e.classList.add(c(u("input"),f.input))},addPoweredBy:function(e){var t=n(404),r=document.createElement("div");e.parentNode.insertBefore(r,e.nextSibling);var a={root:c(u("powered-by"),f.poweredBy),link:u("powered-by-link")};i.render(o.createElement(t,{cssClasses:a}),r)},init:function(e,n){var r="INPUT"===t.tagName,o=this.getInput();if(this.addDefaultAttributesToInput(o,e.query),o.addEventListener("keyup",function(){n.setQuery(o.value).search()}),r){var i=document.createElement("div");o.parentNode.insertBefore(i,o);var a=o.parentNode,s=m?this.wrapInput(o):o;a.replaceChild(s,i)}else{var s=m?this.wrapInput(o):o;t.appendChild(s)}d&&this.addPoweredBy(o),n.on("change",function(e){o!==document.activeElement&&o.value!==e.query&&(o.value=e.query)}),(y===!0||"auto"===y&&""===n.state.query)&&o.focus()}}}var o=n(217),i=n(368),a=n(369),s=n(17),u=n(369).bemHelper("ais-search-box"),c=n(380);e.exports=r},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var i=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),a=function(e,t,n){for(var r=!0;r;){var o=e,i=t,a=n;r=!1,null===o&&(o=Function.prototype);var s=Object.getOwnPropertyDescriptor(o,i);if(void 0!==s){if("value"in s)return s.value;var u=s.get;return void 0===u?void 0:u.call(a)}var c=Object.getPrototypeOf(o);if(null===c)return void 0;e=c,t=i,n=a,r=!0,s=c=void 0}},s=n(217),u=function(e){function t(){r(this,t),a(Object.getPrototypeOf(t.prototype),"constructor",this).apply(this,arguments)}return o(t,e),i(t,[{key:"render",value:function(){return s.createElement("div",{className:this.props.cssClasses.root},"Powered by",s.createElement("a",{className:this.props.cssClasses.link,href:"https://www.algolia.com/",target:"_blank"},"Algolia"))}}]),t}(s.Component);u.propTypes={cssClasses:s.PropTypes.shape({root:s.PropTypes.string,link:s.PropTypes.string})},e.exports=u},function(e,t,n){"use strict";function r(e){var t=e.container,r=void 0===t?null:t,l=e.facetName,p=void 0===l?null:l,f=e.tooltips,h=void 0===f?!0:f,d=e.templates,v=void 0===d?c:d,m=e.cssClasses,g=void 0===m?{root:null,body:null}:m,y=e.hideContainerWhenNoResults,b=void 0===y?!0:y,x=a.getContainerNode(r);return{getConfiguration:function(){return{disjunctiveFacets:[p]}},_getCurrentRefinement:function(e){var t=e.state.getNumericRefinement(p,">="),n=e.state.getNumericRefinement(p,"<=");return t=t&&t.length?t[0]:-(1/0),n=n&&n.length?n[0]:1/0,{min:t,max:n}},_refine:function(e,t,n){e.clearRefinements(p),n[0]>t.min&&e.addNumericRefinement(p,">=",n[0]),n[1]<t.max&&e.addNumericRefinement(p,"<=",n[1]),e.search()},render:function(e){var t=e.results,r=e.helper,l=e.templatesConfig,f=t.getFacetStats(p),d=this._getCurrentRefinement(r);void 0===f&&(f={min:null,max:null});var m=a.prepareTemplateProps({defaultTemplates:c,templatesConfig:l,templates:v}),y=s(u(n(406)));i.render(o.createElement(y,{cssClasses:g,hasResults:null!==f.min&&null!==f.max,hideContainerWhenNoResults:b,onChange:this._refine.bind(this,r,f),range:{min:f.min,max:f.max},start:[d.min,d.max],templateProps:m,tooltips:h}),x)}}}var o=n(217),i=n(368),a=n(369),s=n(371),u=n(372),c={header:"",footer:""};e.exports=r},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},a=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),s=function(e,t,n){for(var r=!0;r;){var o=e,i=t,a=n;r=!1,null===o&&(o=Function.prototype);var s=Object.getOwnPropertyDescriptor(o,i);if(void 0!==s){if("value"in s)return s.value;var u=s.get;return void 0===u?void 0:u.call(a)}var c=Object.getPrototypeOf(o);if(null===c)return void 0;e=c,t=i,n=a,r=!0,s=c=void 0}},u=n(217),c=n(407),l="ais-range-slider--",p=function(e){function t(){r(this,t),s(Object.getPrototypeOf(t.prototype),"constructor",this).apply(this,arguments)}return o(t,e),a(t,[{key:"handleChange",value:function(e,t,n){this.props.onChange(n)}},{key:"render",value:function(){return u.createElement("div",null,u.createElement(c,i({},this.props,{animate:!1,behaviour:"snap",connect:!0,cssPrefix:l,onChange:this.handleChange.bind(this)})))}}]),t}(u.Component);p.propTypes={onChange:u.PropTypes.func,onSlide:u.PropTypes.func,range:u.PropTypes.object.isRequired,start:u.PropTypes.arrayOf(u.PropTypes.number).isRequired,tooltips:u.PropTypes.oneOfType([u.PropTypes.bool,u.PropTypes.object])},e.exports=p},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},s=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),u=function(e,t,n){for(var r=!0;r;){var o=e,i=t,a=n;r=!1,null===o&&(o=Function.prototype);var s=Object.getOwnPropertyDescriptor(o,i);if(void 0!==s){if("value"in s)return s.value;var u=s.get;return void 0===u?void 0:u.call(a)}var c=Object.getPrototypeOf(o);if(null===c)return void 0;e=c,t=i,n=a,r=!0,s=c=void 0}},c=n(217),l=r(c),p=n(408),f=r(p),h=function(e){function t(){o(this,t),u(Object.getPrototypeOf(t.prototype),"constructor",this).apply(this,arguments)}return i(t,e),s(t,[{key:"componentDidMount",value:function(){var e=this.slider=f["default"].create(this.sliderContainer,a({},this.props));this.props.onUpdate&&e.on("update",this.props.onUpdate),this.props.onChange&&e.on("change",this.props.onChange)}},{key:"componentWillReceiveProps",value:function(e){this.slider.updateOptions(a({},this.props)),this.slider.set(e.start)}},{key:"componentWillUnmount",value:function(){this.slider.destroy()}},{key:"render",value:function(){var e=this;return l["default"].createElement("div",{ref:function(t){e.sliderContainer=t}})}}]),t}(l["default"].Component);h.propTypes={animate:l["default"].PropTypes.bool,connect:l["default"].PropTypes.oneOfType([l["default"].PropTypes.oneOf(["lower","upper"]),l["default"].PropTypes.bool]),cssPrefix:l["default"].PropTypes.string,direction:l["default"].PropTypes.oneOf(["ltr","rtl"]),limit:l["default"].PropTypes.number,margin:l["default"].PropTypes.number,onChange:l["default"].PropTypes.func,onUpdate:l["default"].PropTypes.func,orientation:l["default"].PropTypes.oneOf(["horizontal","vertical"]),range:l["default"].PropTypes.object.isRequired,start:l["default"].PropTypes.arrayOf(l["default"].PropTypes.number).isRequired,step:l["default"].PropTypes.number,tooltips:l["default"].PropTypes.oneOfType([l["default"].PropTypes.bool,l["default"].PropTypes.object])},e.exports=h},function(e,t,n){var r,o,i;(function(n){!function(n){o=[],r=n,i="function"==typeof r?r.apply(t,o):r,!(void 0!==i&&(e.exports=i))}(function(){"use strict";function e(e){return e.filter(function(e){return this[e]?!1:this[e]=!0},{})}function t(e,t){return Math.round(e/t)*t}function r(e){var t=e.getBoundingClientRect(),n=e.ownerDocument,r=n.documentElement,o=h();return/webkit.*Chrome.*Mobile/i.test(navigator.userAgent)&&(o.x=0),{top:t.top+o.y-r.clientTop,left:t.left+o.x-r.clientLeft}}function o(e){return"number"==typeof e&&!isNaN(e)&&isFinite(e)}function i(e){var t=Math.pow(10,7);return Number((Math.round(e*t)/t).toFixed(7))}function a(e,t,n){l(e,t),setTimeout(function(){p(e,t)},n)}function s(e){return Math.max(Math.min(e,100),0)}function u(e){return Array.isArray(e)?e:[e]}function c(e){var t=e.split(".");return t.length>1?t[1].length:0}function l(e,t){e.classList?e.classList.add(t):e.className+=" "+t}function p(e,t){e.classList?e.classList.remove(t):e.className=e.className.replace(new RegExp("(^|\\b)"+t.split(" ").join("|")+"(\\b|$)","gi")," ")}function f(e,t){e.classList?e.classList.contains(t):new RegExp("(^| )"+t+"( |$)","gi").test(e.className)}function h(){var e=void 0!==window.pageXOffset,t="CSS1Compat"===(document.compatMode||""),n=e?window.pageXOffset:t?document.documentElement.scrollLeft:document.body.scrollLeft,r=e?window.pageYOffset:t?document.documentElement.scrollTop:document.body.scrollTop;return{x:n,y:r}}function d(e){return function(t){return e+t}}function v(e,t,r,o){function i(e,r){if(null===e)return null;if(0==r)return e;var a,l;if("object"!=typeof e)return e;if(v.__isArray(e))a=[];else if(v.__isRegExp(e))a=new RegExp(e.source,x(e)),e.lastIndex&&(a.lastIndex=e.lastIndex);else if(v.__isDate(e))a=new Date(e.getTime());else{if(c&&n.isBuffer(e))return a=new n(e.length),e.copy(a),a;"undefined"==typeof o?(l=Object.getPrototypeOf(e),a=Object.create(l)):(a=Object.create(o),l=o)}if(t){var p=s.indexOf(e);if(-1!=p)return u[p];s.push(e),u.push(a)}for(var f in e){var h;l&&(h=Object.getOwnPropertyDescriptor(l,f)),h&&null==h.set||(a[f]=i(e[f],r-1))}return a}var a;"object"==typeof t&&(r=t.depth,o=t.prototype,a=t.filter,t=t.circular);var s=[],u=[],c="undefined"!=typeof n;return"undefined"==typeof t&&(t=!0),"undefined"==typeof r&&(r=1/0),i(e,r)}function m(e){return Object.prototype.toString.call(e)}function g(e){return"object"==typeof e&&"[object Date]"===m(e)}function y(e){return"object"==typeof e&&"[object Array]"===m(e)}function b(e){return"object"==typeof e&&"[object RegExp]"===m(e)}function x(e){var t="";return e.global&&(t+="g"),e.ignoreCase&&(t+="i"),e.multiline&&(t+="m"),t}function w(e,t){return 100/(t-e)}function _(e,t){return 100*t/(e[1]-e[0])}function P(e,t){return _(e,e[0]<0?t+Math.abs(e[0]):t-e[0])}function C(e,t){return t*(e[1]-e[0])/100+e[0]}function E(e,t){for(var n=1;e>=t[n];)n+=1;return n}function R(e,t,n){if(n>=e.slice(-1)[0])return 100;var r,o,i,a,s=E(n,e);return r=e[s-1],o=e[s],i=t[s-1],a=t[s],i+P([r,o],n)/w(i,a)}function T(e,t,n){if(n>=100)return e.slice(-1)[0];var r,o,i,a,s=E(n,t);return r=e[s-1],o=e[s],i=t[s-1],a=t[s],C([r,o],(n-i)*w(i,a))}function O(e,n,r,o){if(100===o)return o;var i,a,s=E(o,e);return r?(i=e[s-1],a=e[s],o-i>(a-i)/2?a:i):n[s-1]?e[s-1]+t(o-e[s-1],n[s-1]):o}function S(e,t,n){var r;if("number"==typeof t&&(t=[t]),"[object Array]"!==Object.prototype.toString.call(t))throw new Error("noUiSlider: 'range' contains invalid value.");if(r="min"===e?0:"max"===e?100:parseFloat(e),!o(r)||!o(t[0]))throw new Error("noUiSlider: 'range' value isn't numeric.");n.xPct.push(r),n.xVal.push(t[0]),r?n.xSteps.push(isNaN(t[1])?!1:t[1]):isNaN(t[1])||(n.xSteps[0]=t[1])}function N(e,t,n){return t?void(n.xSteps[e]=_([n.xVal[e],n.xVal[e+1]],t)/w(n.xPct[e],n.xPct[e+1])):!0}function j(e,t,n,r){this.xPct=[],this.xVal=[],this.xSteps=[r||!1],this.xNumSteps=[!1],this.snap=t,this.direction=n;var o,i=[];for(o in e)e.hasOwnProperty(o)&&i.push([e[o],o]);for(i.sort(i.length&&"object"==typeof i[0][0]?function(e,t){return e[0][0]-t[0][0]}:function(e,t){return e[0]-t[0]}),o=0;o<i.length;o++)S(i[o][1],i[o][0],this);for(this.xNumSteps=this.xSteps.slice(0),o=0;o<this.xNumSteps.length;o++)N(o,this.xNumSteps[o],this)}function k(e,t){if(!o(t))throw new Error("noUiSlider: 'step' is not numeric.");e.singleStep=t}function I(e,t){if("object"!=typeof t||Array.isArray(t))throw new Error("noUiSlider: 'range' is not an object.");if(void 0===t.min||void 0===t.max)throw new Error("noUiSlider: Missing 'min' or 'max' in 'range'.");e.spectrum=new j(t,e.snap,e.dir,e.singleStep)}function D(e,t){if(t=u(t),!Array.isArray(t)||!t.length||t.length>2)throw new Error("noUiSlider: 'start' option is incorrect.");e.handles=t.length,e.start=t}function A(e,t){if(e.snap=t,"boolean"!=typeof t)throw new Error("noUiSlider: 'snap' option must be a boolean.")}function M(e,t){if(e.animate=t,"boolean"!=typeof t)throw new Error("noUiSlider: 'animate' option must be a boolean.")}function F(e,t){if("lower"===t&&1===e.handles)e.connect=1; else if("upper"===t&&1===e.handles)e.connect=2;else if(t===!0&&2===e.handles)e.connect=3;else{if(t!==!1)throw new Error("noUiSlider: 'connect' option doesn't match handle count.");e.connect=0}}function U(e,t){switch(t){case"horizontal":e.ort=0;break;case"vertical":e.ort=1;break;default:throw new Error("noUiSlider: 'orientation' option is invalid.")}}function L(e,t){if(!o(t))throw new Error("noUiSlider: 'margin' option must be numeric.");if(e.margin=e.spectrum.getMargin(t),!e.margin)throw new Error("noUiSlider: 'margin' option is only supported on linear sliders.")}function B(e,t){if(!o(t))throw new Error("noUiSlider: 'limit' option must be numeric.");if(e.limit=e.spectrum.getMargin(t),!e.limit)throw new Error("noUiSlider: 'limit' option is only supported on linear sliders.")}function q(e,t){switch(t){case"ltr":e.dir=0;break;case"rtl":e.dir=1,e.connect=[0,2,1,3][e.connect];break;default:throw new Error("noUiSlider: 'direction' option was not recognized.")}}function H(e,t){if("string"!=typeof t)throw new Error("noUiSlider: 'behaviour' must be a string containing options.");var n=t.indexOf("tap")>=0,r=t.indexOf("drag")>=0,o=t.indexOf("fixed")>=0,i=t.indexOf("snap")>=0;if(r&&!e.connect)throw new Error("noUiSlider: 'drag' behaviour must be used with 'connect': true.");e.events={tap:n||i,drag:r,fixed:o,snap:i}}function V(e,t){if(t===!0&&(e.tooltips=!0),t&&t.format){if("function"!=typeof t.format)throw new Error("noUiSlider: 'tooltips.format' must be an object.");e.tooltips={format:t.format}}}function W(e,t){if(e.format=t,"function"==typeof t.to&&"function"==typeof t.from)return!0;throw new Error("noUiSlider: 'format' requires 'to' and 'from' methods.")}function K(e,t){if(void 0!==t&&"string"!=typeof t)throw new Error("noUiSlider: 'cssPrefix' must be a string.");e.cssPrefix=t}function Q(e){var t,n={margin:0,limit:0,animate:!0,format:J};t={step:{r:!1,t:k},start:{r:!0,t:D},connect:{r:!0,t:F},direction:{r:!0,t:q},snap:{r:!1,t:A},animate:{r:!1,t:M},range:{r:!0,t:I},orientation:{r:!1,t:U},margin:{r:!1,t:L},limit:{r:!1,t:B},behaviour:{r:!0,t:H},format:{r:!1,t:W},tooltips:{r:!1,t:V},cssPrefix:{r:!1,t:K}};var r={connect:!1,direction:"ltr",behaviour:"tap",orientation:"horizontal"};return Object.keys(r).forEach(function(t){void 0===e[t]&&(e[t]=r[t])}),Object.keys(t).forEach(function(r){var o=t[r];if(void 0===e[r]){if(o.r)throw new Error("noUiSlider: '"+r+"' is required.");return!0}o.t(n,e[r])}),n.pips=e.pips,n.style=n.ort?"top":"left",n}function Y(t,n){function o(e,t,n){var r=e+t[0],o=e+t[1];return n?(0>r&&(o+=Math.abs(r)),o>100&&(r-=o-100),[s(r),s(o)]):[r,o]}function i(e,t){e.preventDefault();var n,r,o=0===e.type.indexOf("touch"),i=0===e.type.indexOf("mouse"),a=0===e.type.indexOf("pointer"),s=e;return 0===e.type.indexOf("MSPointer")&&(a=!0),o&&(n=e.changedTouches[0].pageX,r=e.changedTouches[0].pageY),t=t||h(),(i||a)&&(n=e.clientX+t.x,r=e.clientY+t.y),s.pageOffset=t,s.points=[n,r],s.cursor=i||a,s}function v(e,t){var n=document.createElement("div"),r=document.createElement("div"),o=["-lower","-upper"];return e&&o.reverse(),l(r,ee[3]),l(r,ee[3]+o[t]),l(n,ee[2]),n.appendChild(r),n}function m(e,t,n){switch(e){case 1:l(t,ee[7]),l(n[0],ee[6]);break;case 3:l(n[1],ee[6]);case 2:l(n[0],ee[7]);case 0:l(t,ee[6])}}function g(e,t,n){var r,o=[];for(r=0;e>r;r+=1)o.push(n.appendChild(v(t,r)));return o}function y(e,t,n){l(n,ee[0]),l(n,ee[8+e]),l(n,ee[4+t]);var r=document.createElement("div");return l(r,ee[1]),n.appendChild(r),r}function b(e){return e}function x(e){var t=document.createElement("div");return t.className=ee[18],e.firstChild.appendChild(t)}function w(e){var t=e.format?e.format:b,n=K.map(x);q("update",function(e,r,o){n[r].innerHTML=t(e[r],o[r])})}function _(e,t,n){if("range"===e||"steps"===e)return J.xVal;if("count"===e){var r,o=100/(t-1),i=0;for(t=[];(r=i++*o)<=100;)t.push(r);e="positions"}return"positions"===e?t.map(function(e){return J.fromStepping(n?J.getStep(e):e)}):"values"===e?n?t.map(function(e){return J.fromStepping(J.getStep(J.toStepping(e)))}):t:void 0}function P(t,n,r){function o(e,t){return(e+t).toFixed(7)/1}var i=J.direction,a={},s=J.xVal[0],u=J.xVal[J.xVal.length-1],c=!1,l=!1,p=0;return J.direction=0,r=e(r.slice().sort(function(e,t){return e-t})),r[0]!==s&&(r.unshift(s),c=!0),r[r.length-1]!==u&&(r.push(u),l=!0),r.forEach(function(e,i){var s,u,f,h,d,v,m,g,y,b,x=e,w=r[i+1];if("steps"===n&&(s=J.xNumSteps[i]),s||(s=w-x),x!==!1&&void 0!==w)for(u=x;w>=u;u=o(u,s)){for(h=J.toStepping(u),d=h-p,g=d/t,y=Math.round(g),b=d/y,f=1;y>=f;f+=1)v=p+f*b,a[v.toFixed(5)]=["x",0];m=r.indexOf(u)>-1?1:"steps"===n?2:0,!i&&c&&(m=0),u===w&&l||(a[h.toFixed(5)]=[u,m]),p=h}}),J.direction=i,a}function C(e,t,r){function o(e){return["-normal","-large","-sub"][e]}function i(e,t,r){return'class="'+t+" "+t+"-"+s+" "+t+o(r[1])+'" style="'+n.style+": "+e+'%"'}function a(e,n){J.direction&&(e=100-e),n[1]=n[1]&&t?t(n[0],n[1]):n[1],u.innerHTML+="<div "+i(e,"noUi-marker",n)+"></div>",n[1]&&(u.innerHTML+="<div "+i(e,"noUi-value",n)+">"+r.to(n[0])+"</div>")}var s=["horizontal","vertical"][n.ort],u=document.createElement("div");return l(u,"noUi-pips"),l(u,"noUi-pips-"+s),Object.keys(e).forEach(function(t){a(t,e[t])}),u}function E(e){var t=e.mode,n=e.density||1,r=e.filter||!1,o=e.values||!1,i=e.stepped||!1,a=_(t,o,i),s=P(n,t,a),u=e.format||{to:Math.round};return Y.appendChild(C(s,r,u))}function R(){return W["offset"+["Width","Height"][n.ort]]}function T(e,t){void 0!==t&&1!==n.handles&&(t=Math.abs(t-n.dir)),Object.keys(Z).forEach(function(n){var r=n.split(".")[0];e===r&&Z[n].forEach(function(e){e(u(U()),t,O(Array.prototype.slice.call(X)))})})}function O(e){return 1===e.length?e[0]:n.dir?e.reverse():e}function S(e,t,r,o){var a=function(t){return Y.hasAttribute("disabled")?!1:f(Y,ee[14])?!1:(t=i(t,o.pageOffset),e===G.start&&void 0!==t.buttons&&t.buttons>1?!1:(t.calcPoint=t.points[n.ort],void r(t,o)))},s=[];return e.split(" ").forEach(function(e){t.addEventListener(e,a,!1),s.push([e,a])}),s}function N(e,t){if(0===e.buttons&&0===e.which&&0!==t.buttonsProperty)return j(e,t);var n,r,i=t.handles||K,a=!1,s=100*(e.calcPoint-t.start)/t.baseSize,u=i[0]===K[0]?0:1;if(n=o(s,t.positions,i.length>1),a=A(i[0],n[u],1===i.length),i.length>1){if(a=A(i[1],n[u?0:1],!1)||a)for(r=0;r<t.handles.length;r++)T("slide",r)}else a&&T("slide",u)}function j(e,t){var n=W.querySelector("."+ee[15]),r=t.handles[0]===K[0]?0:1;null!==n&&p(n,ee[15]),e.cursor&&(document.body.style.cursor="",document.body.removeEventListener("selectstart",document.body.noUiListener));var o=document.documentElement;o.noUiListeners.forEach(function(e){o.removeEventListener(e[0],e[1])}),p(Y,ee[12]),T("set",r),T("change",r)}function k(e,t){var n=document.documentElement;if(1===t.handles.length&&(l(t.handles[0].children[0],ee[15]),t.handles[0].hasAttribute("disabled")))return!1;e.stopPropagation();var r=S(G.move,n,N,{start:e.calcPoint,baseSize:R(),pageOffset:e.pageOffset,handles:t.handles,buttonsProperty:e.buttons,positions:[z[0],z[K.length-1]]}),o=S(G.end,n,j,{handles:t.handles});if(n.noUiListeners=r.concat(o),e.cursor){document.body.style.cursor=getComputedStyle(e.target).cursor,K.length>1&&l(Y,ee[12]);var i=function(){return!1};document.body.noUiListener=i,document.body.addEventListener("selectstart",i,!1)}}function I(e){var t,o,i=e.calcPoint,s=0;return e.stopPropagation(),K.forEach(function(e){s+=r(e)[n.style]}),t=s/2>i||1===K.length?0:1,i-=r(W)[n.style],o=100*i/R(),n.events.snap||a(Y,ee[14],300),K[t].hasAttribute("disabled")?!1:(A(K[t],o),T("slide",t),T("set",t),T("change",t),void(n.events.snap&&k(e,{handles:[K[t]]})))}function D(e){var t,n;if(!e.fixed)for(t=0;t<K.length;t+=1)S(G.start,K[t].children[0],k,{handles:[K[t]]});e.tap&&S(G.start,W,I,{handles:K}),e.drag&&(n=[W.querySelector("."+ee[7])],l(n[0],ee[10]),e.fixed&&n.push(K[n[0]===K[0]?1:0].children[0]),n.forEach(function(e){S(G.start,e,k,{handles:K})}))}function A(e,t,r){var o=e!==K[0]?1:0,i=z[0]+n.margin,a=z[1]-n.margin,u=z[0]+n.limit,c=z[1]-n.limit,f=J.fromStepping(t);return K.length>1&&(t=o?Math.max(t,i):Math.min(t,a)),r!==!1&&n.limit&&K.length>1&&(t=o?Math.min(t,u):Math.max(t,c)),t=J.getStep(t),t=s(parseFloat(t.toFixed(7))),t===z[o]&&f===X[o]?!1:(window.requestAnimationFrame?window.requestAnimationFrame(function(){e.style[n.style]=t+"%"}):e.style[n.style]=t+"%",e.previousSibling||(p(e,ee[17]),t>50&&l(e,ee[17])),z[o]=t,X[o]=J.fromStepping(t),T("update",o),!0)}function M(e,t){var r,o,i;for(n.limit&&(e+=1),r=0;e>r;r+=1)o=r%2,i=t[o],null!==i&&i!==!1&&("number"==typeof i&&(i=String(i)),i=n.format.from(i),(i===!1||isNaN(i)||A(K[o],J.toStepping(i),r===3-n.dir)===!1)&&T("update",o))}function F(e){var t,r,o=u(e);for(n.dir&&n.handles>1&&o.reverse(),n.animate&&-1!==z[0]&&a(Y,ee[14],300),t=K.length>1?3:1,1===o.length&&(t=1),M(t,o),r=0;r<K.length;r++)T("set",r)}function U(){var e,t=[];for(e=0;e<n.handles;e+=1)t[e]=n.format.to(X[e]);return O(t)}function L(){ee.forEach(function(e){e&&p(Y,e)}),Y.innerHTML="",delete Y.noUiSlider}function B(){var e=z.map(function(e,t){var n=J.getApplicableStep(e),r=c(String(n[2])),o=X[t],i=100===e?null:n[2],a=Number((o-n[2]).toFixed(r)),s=0===e?null:a>=n[1]?n[2]:n[0]||!1;return[s,i]});return O(e)}function q(e,t){Z[e]=Z[e]||[],Z[e].push(t),"update"===e.split(".")[0]&&K.forEach(function(e,t){T("update",t)})}function H(e){var t=e.split(".")[0],n=e.substring(t.length);Object.keys(Z).forEach(function(e){var r=e.split(".")[0],o=e.substring(r.length);t&&t!==r||n&&n!==o||delete Z[e]})}function V(e){var t=Q({start:[0,0],margin:e.margin,limit:e.limit,step:e.step,range:e.range,animate:e.animate});n.margin=t.margin,n.limit=t.limit,n.step=t.step,n.range=t.range,n.animate=t.animate,J=t.spectrum}var W,K,Y=t,z=[-1,-1],J=n.spectrum,X=[],Z={},ee=["target","base","origin","handle","horizontal","vertical","background","connect","ltr","rtl","draggable","","state-drag","","state-tap","active","","stacking","tooltip"].map(d(n.cssPrefix||$));if(Y.noUiSlider)throw new Error("Slider was already initialized.");return W=y(n.dir,n.ort,Y),K=g(n.handles,n.dir,W),m(n.connect,Y,K),D(n.events),n.pips&&E(n.pips),n.tooltips&&w(n.tooltips),{destroy:L,steps:B,on:q,off:H,get:U,set:F,updateOptions:V}}function z(e,t){if(!e.nodeName)throw new Error("noUiSlider.create requires a single element.");var n=Q(v(t),e),r=Y(e,n);return r.set(n.start),e.noUiSlider=r,r}v.clonePrototype=function(e){if(null===e)return null;var t=function(){};return t.prototype=e,new t},v.__objToStr=m,v.__isDate=g,v.__isArray=y,v.__isRegExp=b,v.__getRegExpFlags=x;var G=window.navigator.pointerEnabled?{start:"pointerdown",move:"pointermove",end:"pointerup"}:window.navigator.msPointerEnabled?{start:"MSPointerDown",move:"MSPointerMove",end:"MSPointerUp"}:{start:"mousedown touchstart",move:"mousemove touchmove",end:"mouseup touchend"},$="noUi-";j.prototype.getMargin=function(e){return 2===this.xPct.length?_(this.xVal,e):!1},j.prototype.toStepping=function(e){return e=R(this.xVal,this.xPct,e),this.direction&&(e=100-e),e},j.prototype.fromStepping=function(e){return this.direction&&(e=100-e),i(T(this.xVal,this.xPct,e))},j.prototype.getStep=function(e){return this.direction&&(e=100-e),e=O(this.xPct,this.xSteps,this.snap,e),this.direction&&(e=100-e),e},j.prototype.getApplicableStep=function(e){var t=E(e,this.xPct),n=100===e?2:1;return[this.xNumSteps[t-2],this.xVal[t-n],this.xNumSteps[t-n]]},j.prototype.convert=function(e){return this.getStep(this.toStepping(e))};var J={to:function(e){return void 0!==e&&e.toFixed(2)},from:Number};return{create:z}})}).call(t,n(409).Buffer)},function(e,t,n){(function(e,r){function o(){function e(){}try{var t=new Uint8Array(1);return t.foo=function(){return 42},t.constructor=e,42===t.foo()&&t.constructor===e&&"function"==typeof t.subarray&&0===t.subarray(1,1).byteLength}catch(n){return!1}}function i(){return e.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function e(t){return this instanceof e?(this.length=0,this.parent=void 0,"number"==typeof t?a(this,t):"string"==typeof t?s(this,t,arguments.length>1?arguments[1]:"utf8"):u(this,t)):arguments.length>1?new e(t,arguments[1]):new e(t)}function a(t,n){if(t=v(t,0>n?0:0|m(n)),!e.TYPED_ARRAY_SUPPORT)for(var r=0;n>r;r++)t[r]=0;return t}function s(e,t,n){("string"!=typeof n||""===n)&&(n="utf8");var r=0|y(t,n);return e=v(e,r),e.write(t,n),e}function u(t,n){if(e.isBuffer(n))return c(t,n);if($(n))return l(t,n);if(null==n)throw new TypeError("must start with number, buffer, array or string");if("undefined"!=typeof ArrayBuffer){if(n.buffer instanceof ArrayBuffer)return p(t,n);if(n instanceof ArrayBuffer)return f(t,n)}return n.length?h(t,n):d(t,n)}function c(e,t){var n=0|m(t.length);return e=v(e,n),t.copy(e,0,0,n),e}function l(e,t){var n=0|m(t.length);e=v(e,n);for(var r=0;n>r;r+=1)e[r]=255&t[r];return e}function p(e,t){var n=0|m(t.length);e=v(e,n);for(var r=0;n>r;r+=1)e[r]=255&t[r];return e}function f(t,n){return e.TYPED_ARRAY_SUPPORT?(n.byteLength,t=e._augment(new Uint8Array(n))):t=p(t,new Uint8Array(n)),t}function h(e,t){var n=0|m(t.length);e=v(e,n);for(var r=0;n>r;r+=1)e[r]=255&t[r];return e}function d(e,t){var n,r=0;"Buffer"===t.type&&$(t.data)&&(n=t.data,r=0|m(n.length)),e=v(e,r);for(var o=0;r>o;o+=1)e[o]=255&n[o];return e}function v(t,n){e.TYPED_ARRAY_SUPPORT?(t=e._augment(new Uint8Array(n)),t.__proto__=e.prototype):(t.length=n,t._isBuffer=!0);var r=0!==n&&n<=e.poolSize>>>1;return r&&(t.parent=J),t}function m(e){if(e>=i())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i().toString(16)+" bytes");return 0|e}function g(t,n){if(!(this instanceof g))return new g(t,n);var r=new e(t,n);return delete r.parent,r}function y(e,t){"string"!=typeof e&&(e=""+e);var n=e.length;if(0===n)return 0;for(var r=!1;;)switch(t){case"ascii":case"binary":case"raw":case"raws":return n;case"utf8":case"utf-8":return V(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return Q(e).length;default:if(r)return V(e).length;t=(""+t).toLowerCase(),r=!0}}function b(e,t,n){var r=!1;if(t=0|t,n=void 0===n||n===1/0?this.length:0|n,e||(e="utf8"),0>t&&(t=0),n>this.length&&(n=this.length),t>=n)return"";for(;;)switch(e){case"hex":return j(this,t,n);case"utf8":case"utf-8":return T(this,t,n);case"ascii":return S(this,t,n);case"binary":return N(this,t,n);case"base64":return R(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return k(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function x(e,t,n,r){n=Number(n)||0;var o=e.length-n;r?(r=Number(r),r>o&&(r=o)):r=o;var i=t.length;if(i%2!==0)throw new Error("Invalid hex string");r>i/2&&(r=i/2);for(var a=0;r>a;a++){var s=parseInt(t.substr(2*a,2),16);if(isNaN(s))throw new Error("Invalid hex string");e[n+a]=s}return a}function w(e,t,n,r){return Y(V(t,e.length-n),e,n,r)}function _(e,t,n,r){return Y(W(t),e,n,r)}function P(e,t,n,r){return _(e,t,n,r)}function C(e,t,n,r){return Y(Q(t),e,n,r)}function E(e,t,n,r){return Y(K(t,e.length-n),e,n,r)}function R(e,t,n){return z.fromByteArray(0===t&&n===e.length?e:e.slice(t,n))}function T(e,t,n){n=Math.min(e.length,n);for(var r=[],o=t;n>o;){var i=e[o],a=null,s=i>239?4:i>223?3:i>191?2:1;if(n>=o+s){var u,c,l,p;switch(s){case 1:128>i&&(a=i);break;case 2:u=e[o+1],128===(192&u)&&(p=(31&i)<<6|63&u,p>127&&(a=p));break;case 3:u=e[o+1],c=e[o+2],128===(192&u)&&128===(192&c)&&(p=(15&i)<<12|(63&u)<<6|63&c,p>2047&&(55296>p||p>57343)&&(a=p));break;case 4:u=e[o+1],c=e[o+2],l=e[o+3],128===(192&u)&&128===(192&c)&&128===(192&l)&&(p=(15&i)<<18|(63&u)<<12|(63&c)<<6|63&l,p>65535&&1114112>p&&(a=p))}}null===a?(a=65533,s=1):a>65535&&(a-=65536,r.push(a>>>10&1023|55296),a=56320|1023&a),r.push(a),o+=s}return O(r)}function O(e){var t=e.length;if(X>=t)return String.fromCharCode.apply(String,e);for(var n="",r=0;t>r;)n+=String.fromCharCode.apply(String,e.slice(r,r+=X));return n}function S(e,t,n){var r="";n=Math.min(e.length,n);for(var o=t;n>o;o++)r+=String.fromCharCode(127&e[o]);return r}function N(e,t,n){var r="";n=Math.min(e.length,n);for(var o=t;n>o;o++)r+=String.fromCharCode(e[o]);return r}function j(e,t,n){var r=e.length;(!t||0>t)&&(t=0),(!n||0>n||n>r)&&(n=r);for(var o="",i=t;n>i;i++)o+=H(e[i]);return o}function k(e,t,n){for(var r=e.slice(t,n),o="",i=0;i<r.length;i+=2)o+=String.fromCharCode(r[i]+256*r[i+1]);return o}function I(e,t,n){if(e%1!==0||0>e)throw new RangeError("offset is not uint");if(e+t>n)throw new RangeError("Trying to access beyond buffer length")}function D(t,n,r,o,i,a){if(!e.isBuffer(t))throw new TypeError("buffer must be a Buffer instance");if(n>i||a>n)throw new RangeError("value is out of bounds");if(r+o>t.length)throw new RangeError("index out of range")}function A(e,t,n,r){0>t&&(t=65535+t+1);for(var o=0,i=Math.min(e.length-n,2);i>o;o++)e[n+o]=(t&255<<8*(r?o:1-o))>>>8*(r?o:1-o)}function M(e,t,n,r){0>t&&(t=4294967295+t+1);for(var o=0,i=Math.min(e.length-n,4);i>o;o++)e[n+o]=t>>>8*(r?o:3-o)&255}function F(e,t,n,r,o,i){if(t>o||i>t)throw new RangeError("value is out of bounds");if(n+r>e.length)throw new RangeError("index out of range");if(0>n)throw new RangeError("index out of range")}function U(e,t,n,r,o){return o||F(e,t,n,4,3.4028234663852886e38,-3.4028234663852886e38),G.write(e,t,n,r,23,4),n+4}function L(e,t,n,r,o){return o||F(e,t,n,8,1.7976931348623157e308,-1.7976931348623157e308),G.write(e,t,n,r,52,8),n+8}function B(e){if(e=q(e).replace(ee,""),e.length<2)return"";for(;e.length%4!==0;)e+="=";return e}function q(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}function H(e){return 16>e?"0"+e.toString(16):e.toString(16)}function V(e,t){t=t||1/0;for(var n,r=e.length,o=null,i=[],a=0;r>a;a++){if(n=e.charCodeAt(a),n>55295&&57344>n){if(!o){if(n>56319){(t-=3)>-1&&i.push(239,191,189);continue}if(a+1===r){(t-=3)>-1&&i.push(239,191,189);continue}o=n;continue}if(56320>n){(t-=3)>-1&&i.push(239,191,189),o=n;continue}n=o-55296<<10|n-56320|65536}else o&&(t-=3)>-1&&i.push(239,191,189);if(o=null,128>n){if((t-=1)<0)break;i.push(n)}else if(2048>n){if((t-=2)<0)break;i.push(n>>6|192,63&n|128)}else if(65536>n){if((t-=3)<0)break;i.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(1114112>n))throw new Error("Invalid code point");if((t-=4)<0)break;i.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return i}function W(e){for(var t=[],n=0;n<e.length;n++)t.push(255&e.charCodeAt(n));return t}function K(e,t){for(var n,r,o,i=[],a=0;a<e.length&&!((t-=2)<0);a++)n=e.charCodeAt(a),r=n>>8,o=n%256,i.push(o),i.push(r);return i}function Q(e){return z.toByteArray(B(e))}function Y(e,t,n,r){for(var o=0;r>o&&!(o+n>=t.length||o>=e.length);o++)t[o+n]=e[o];return o}var z=n(410),G=n(411),$=n(412);t.Buffer=e,t.SlowBuffer=g,t.INSPECT_MAX_BYTES=50,e.poolSize=8192;var J={};e.TYPED_ARRAY_SUPPORT=void 0!==r.TYPED_ARRAY_SUPPORT?r.TYPED_ARRAY_SUPPORT:o(),e.TYPED_ARRAY_SUPPORT&&(e.prototype.__proto__=Uint8Array.prototype,e.__proto__=Uint8Array),e.isBuffer=function(e){return!(null==e||!e._isBuffer)},e.compare=function(t,n){if(!e.isBuffer(t)||!e.isBuffer(n))throw new TypeError("Arguments must be Buffers");if(t===n)return 0;for(var r=t.length,o=n.length,i=0,a=Math.min(r,o);a>i&&t[i]===n[i];)++i;return i!==a&&(r=t[i],o=n[i]),o>r?-1:r>o?1:0},e.isEncoding=function(e){switch(String(e).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!0;default:return!1}},e.concat=function(t,n){if(!$(t))throw new TypeError("list argument must be an Array of Buffers.");if(0===t.length)return new e(0);var r;if(void 0===n)for(n=0,r=0;r<t.length;r++)n+=t[r].length;var o=new e(n),i=0;for(r=0;r<t.length;r++){var a=t[r];a.copy(o,i),i+=a.length}return o},e.byteLength=y,e.prototype.length=void 0,e.prototype.parent=void 0,e.prototype.toString=function(){var e=0|this.length;return 0===e?"":0===arguments.length?T(this,0,e):b.apply(this,arguments)},e.prototype.equals=function(t){if(!e.isBuffer(t))throw new TypeError("Argument must be a Buffer");return this===t?!0:0===e.compare(this,t)},e.prototype.inspect=function(){var e="",n=t.INSPECT_MAX_BYTES;return this.length>0&&(e=this.toString("hex",0,n).match(/.{2}/g).join(" "),this.length>n&&(e+=" ... ")),"<Buffer "+e+">"},e.prototype.compare=function(t){if(!e.isBuffer(t))throw new TypeError("Argument must be a Buffer");return this===t?0:e.compare(this,t)},e.prototype.indexOf=function(t,n){function r(e,t,n){for(var r=-1,o=0;n+o<e.length;o++)if(e[n+o]===t[-1===r?0:o-r]){if(-1===r&&(r=o),o-r+1===t.length)return n+r}else r=-1;return-1}if(n>2147483647?n=2147483647:-2147483648>n&&(n=-2147483648),n>>=0,0===this.length)return-1;if(n>=this.length)return-1;if(0>n&&(n=Math.max(this.length+n,0)),"string"==typeof t)return 0===t.length?-1:String.prototype.indexOf.call(this,t,n);if(e.isBuffer(t))return r(this,t,n);if("number"==typeof t)return e.TYPED_ARRAY_SUPPORT&&"function"===Uint8Array.prototype.indexOf?Uint8Array.prototype.indexOf.call(this,t,n):r(this,[t],n);throw new TypeError("val must be string, number or Buffer")},e.prototype.get=function(e){return console.log(".get() is deprecated. Access using array indexes instead."),this.readUInt8(e)},e.prototype.set=function(e,t){return console.log(".set() is deprecated. Access using array indexes instead."),this.writeUInt8(e,t)},e.prototype.write=function(e,t,n,r){if(void 0===t)r="utf8",n=this.length,t=0;else if(void 0===n&&"string"==typeof t)r=t,n=this.length,t=0;else if(isFinite(t))t=0|t,isFinite(n)?(n=0|n,void 0===r&&(r="utf8")):(r=n,n=void 0);else{var o=r;r=t,t=0|n,n=o}var i=this.length-t;if((void 0===n||n>i)&&(n=i),e.length>0&&(0>n||0>t)||t>this.length)throw new RangeError("attempt to write outside buffer bounds");r||(r="utf8");for(var a=!1;;)switch(r){case"hex":return x(this,e,t,n);case"utf8":case"utf-8":return w(this,e,t,n);case"ascii":return _(this,e,t,n);case"binary":return P(this,e,t,n);case"base64":return C(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return E(this,e,t,n);default:if(a)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),a=!0}},e.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var X=4096;e.prototype.slice=function(t,n){var r=this.length;t=~~t,n=void 0===n?r:~~n,0>t?(t+=r,0>t&&(t=0)):t>r&&(t=r),0>n?(n+=r,0>n&&(n=0)):n>r&&(n=r),t>n&&(n=t);var o;if(e.TYPED_ARRAY_SUPPORT)o=e._augment(this.subarray(t,n));else{var i=n-t;o=new e(i,void 0);for(var a=0;i>a;a++)o[a]=this[a+t]}return o.length&&(o.parent=this.parent||this),o},e.prototype.readUIntLE=function(e,t,n){e=0|e,t=0|t,n||I(e,t,this.length);for(var r=this[e],o=1,i=0;++i<t&&(o*=256);)r+=this[e+i]*o;return r},e.prototype.readUIntBE=function(e,t,n){e=0|e,t=0|t,n||I(e,t,this.length);for(var r=this[e+--t],o=1;t>0&&(o*=256);)r+=this[e+--t]*o;return r},e.prototype.readUInt8=function(e,t){return t||I(e,1,this.length),this[e]},e.prototype.readUInt16LE=function(e,t){return t||I(e,2,this.length),this[e]|this[e+1]<<8},e.prototype.readUInt16BE=function(e,t){return t||I(e,2,this.length),this[e]<<8|this[e+1]},e.prototype.readUInt32LE=function(e,t){return t||I(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},e.prototype.readUInt32BE=function(e,t){return t||I(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},e.prototype.readIntLE=function(e,t,n){e=0|e,t=0|t,n||I(e,t,this.length);for(var r=this[e],o=1,i=0;++i<t&&(o*=256);)r+=this[e+i]*o;return o*=128,r>=o&&(r-=Math.pow(2,8*t)),r},e.prototype.readIntBE=function(e,t,n){e=0|e,t=0|t,n||I(e,t,this.length);for(var r=t,o=1,i=this[e+--r];r>0&&(o*=256);)i+=this[e+--r]*o;return o*=128,i>=o&&(i-=Math.pow(2,8*t)),i},e.prototype.readInt8=function(e,t){return t||I(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},e.prototype.readInt16LE=function(e,t){t||I(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},e.prototype.readInt16BE=function(e,t){t||I(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},e.prototype.readInt32LE=function(e,t){return t||I(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},e.prototype.readInt32BE=function(e,t){return t||I(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},e.prototype.readFloatLE=function(e,t){return t||I(e,4,this.length),G.read(this,e,!0,23,4)},e.prototype.readFloatBE=function(e,t){return t||I(e,4,this.length),G.read(this,e,!1,23,4)},e.prototype.readDoubleLE=function(e,t){return t||I(e,8,this.length),G.read(this,e,!0,52,8)},e.prototype.readDoubleBE=function(e,t){return t||I(e,8,this.length),G.read(this,e,!1,52,8)},e.prototype.writeUIntLE=function(e,t,n,r){e=+e,t=0|t,n=0|n,r||D(this,e,t,n,Math.pow(2,8*n),0);var o=1,i=0;for(this[t]=255&e;++i<n&&(o*=256);)this[t+i]=e/o&255;return t+n},e.prototype.writeUIntBE=function(e,t,n,r){e=+e,t=0|t,n=0|n,r||D(this,e,t,n,Math.pow(2,8*n),0);var o=n-1,i=1;for(this[t+o]=255&e;--o>=0&&(i*=256);)this[t+o]=e/i&255;return t+n},e.prototype.writeUInt8=function(t,n,r){return t=+t,n=0|n,r||D(this,t,n,1,255,0),e.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),this[n]=255&t,n+1},e.prototype.writeUInt16LE=function(t,n,r){return t=+t,n=0|n,r||D(this,t,n,2,65535,0),e.TYPED_ARRAY_SUPPORT?(this[n]=255&t,this[n+1]=t>>>8):A(this,t,n,!0),n+2},e.prototype.writeUInt16BE=function(t,n,r){return t=+t,n=0|n,r||D(this,t,n,2,65535,0),e.TYPED_ARRAY_SUPPORT?(this[n]=t>>>8,this[n+1]=255&t):A(this,t,n,!1),n+2},e.prototype.writeUInt32LE=function(t,n,r){return t=+t,n=0|n,r||D(this,t,n,4,4294967295,0),e.TYPED_ARRAY_SUPPORT?(this[n+3]=t>>>24,this[n+2]=t>>>16,this[n+1]=t>>>8,this[n]=255&t):M(this,t,n,!0),n+4},e.prototype.writeUInt32BE=function(t,n,r){return t=+t,n=0|n,r||D(this,t,n,4,4294967295,0),e.TYPED_ARRAY_SUPPORT?(this[n]=t>>>24,this[n+1]=t>>>16,this[n+2]=t>>>8,this[n+3]=255&t):M(this,t,n,!1),n+4},e.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t=0|t,!r){var o=Math.pow(2,8*n-1);D(this,e,t,n,o-1,-o)}var i=0,a=1,s=0>e?1:0;for(this[t]=255&e;++i<n&&(a*=256);)this[t+i]=(e/a>>0)-s&255;return t+n},e.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t=0|t,!r){var o=Math.pow(2,8*n-1);D(this,e,t,n,o-1,-o)}var i=n-1,a=1,s=0>e?1:0;for(this[t+i]=255&e;--i>=0&&(a*=256);)this[t+i]=(e/a>>0)-s&255;return t+n},e.prototype.writeInt8=function(t,n,r){return t=+t,n=0|n,r||D(this,t,n,1,127,-128),e.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),0>t&&(t=255+t+1),this[n]=255&t,n+1},e.prototype.writeInt16LE=function(t,n,r){return t=+t,n=0|n,r||D(this,t,n,2,32767,-32768),e.TYPED_ARRAY_SUPPORT?(this[n]=255&t,this[n+1]=t>>>8):A(this,t,n,!0),n+2},e.prototype.writeInt16BE=function(t,n,r){return t=+t,n=0|n,r||D(this,t,n,2,32767,-32768),e.TYPED_ARRAY_SUPPORT?(this[n]=t>>>8,this[n+1]=255&t):A(this,t,n,!1),n+2},e.prototype.writeInt32LE=function(t,n,r){return t=+t,n=0|n,r||D(this,t,n,4,2147483647,-2147483648),e.TYPED_ARRAY_SUPPORT?(this[n]=255&t,this[n+1]=t>>>8,this[n+2]=t>>>16,this[n+3]=t>>>24):M(this,t,n,!0),n+4},e.prototype.writeInt32BE=function(t,n,r){return t=+t,n=0|n,r||D(this,t,n,4,2147483647,-2147483648),0>t&&(t=4294967295+t+1),e.TYPED_ARRAY_SUPPORT?(this[n]=t>>>24,this[n+1]=t>>>16,this[n+2]=t>>>8,this[n+3]=255&t):M(this,t,n,!1),n+4},e.prototype.writeFloatLE=function(e,t,n){return U(this,e,t,!0,n)},e.prototype.writeFloatBE=function(e,t,n){return U(this,e,t,!1,n)},e.prototype.writeDoubleLE=function(e,t,n){return L(this,e,t,!0,n)},e.prototype.writeDoubleBE=function(e,t,n){return L(this,e,t,!1,n)},e.prototype.copy=function(t,n,r,o){if(r||(r=0),o||0===o||(o=this.length),n>=t.length&&(n=t.length),n||(n=0),o>0&&r>o&&(o=r),o===r)return 0;if(0===t.length||0===this.length)return 0;if(0>n)throw new RangeError("targetStart out of bounds");if(0>r||r>=this.length)throw new RangeError("sourceStart out of bounds");if(0>o)throw new RangeError("sourceEnd out of bounds");o>this.length&&(o=this.length),t.length-n<o-r&&(o=t.length-n+r);var i,a=o-r;if(this===t&&n>r&&o>n)for(i=a-1;i>=0;i--)t[i+n]=this[i+r];else if(1e3>a||!e.TYPED_ARRAY_SUPPORT)for(i=0;a>i;i++)t[i+n]=this[i+r];else t._set(this.subarray(r,r+a),n);return a},e.prototype.fill=function(e,t,n){if(e||(e=0),t||(t=0),n||(n=this.length),t>n)throw new RangeError("end < start");if(n!==t&&0!==this.length){if(0>t||t>=this.length)throw new RangeError("start out of bounds");if(0>n||n>this.length)throw new RangeError("end out of bounds");var r;if("number"==typeof e)for(r=t;n>r;r++)this[r]=e;else{var o=V(e.toString()),i=o.length;for(r=t;n>r;r++)this[r]=o[r%i]}return this}},e.prototype.toArrayBuffer=function(){if("undefined"!=typeof Uint8Array){if(e.TYPED_ARRAY_SUPPORT)return new e(this).buffer;for(var t=new Uint8Array(this.length),n=0,r=t.length;r>n;n+=1)t[n]=this[n];return t.buffer}throw new TypeError("Buffer.toArrayBuffer not supported in this browser")};var Z=e.prototype;e._augment=function(t){return t.constructor=e,t._isBuffer=!0,t._set=t.set,t.get=Z.get,t.set=Z.set,t.write=Z.write,t.toString=Z.toString,t.toLocaleString=Z.toString,t.toJSON=Z.toJSON,t.equals=Z.equals,t.compare=Z.compare,t.indexOf=Z.indexOf,t.copy=Z.copy,t.slice=Z.slice,t.readUIntLE=Z.readUIntLE,t.readUIntBE=Z.readUIntBE,t.readUInt8=Z.readUInt8,t.readUInt16LE=Z.readUInt16LE,t.readUInt16BE=Z.readUInt16BE,t.readUInt32LE=Z.readUInt32LE,t.readUInt32BE=Z.readUInt32BE,t.readIntLE=Z.readIntLE,t.readIntBE=Z.readIntBE,t.readInt8=Z.readInt8,t.readInt16LE=Z.readInt16LE,t.readInt16BE=Z.readInt16BE,t.readInt32LE=Z.readInt32LE,t.readInt32BE=Z.readInt32BE,t.readFloatLE=Z.readFloatLE,t.readFloatBE=Z.readFloatBE,t.readDoubleLE=Z.readDoubleLE,t.readDoubleBE=Z.readDoubleBE,t.writeUInt8=Z.writeUInt8,t.writeUIntLE=Z.writeUIntLE,t.writeUIntBE=Z.writeUIntBE,t.writeUInt16LE=Z.writeUInt16LE,t.writeUInt16BE=Z.writeUInt16BE,t.writeUInt32LE=Z.writeUInt32LE,t.writeUInt32BE=Z.writeUInt32BE,t.writeIntLE=Z.writeIntLE,t.writeIntBE=Z.writeIntBE,t.writeInt8=Z.writeInt8,t.writeInt16LE=Z.writeInt16LE,t.writeInt16BE=Z.writeInt16BE,t.writeInt32LE=Z.writeInt32LE,t.writeInt32BE=Z.writeInt32BE,t.writeFloatLE=Z.writeFloatLE,t.writeFloatBE=Z.writeFloatBE,t.writeDoubleLE=Z.writeDoubleLE,t.writeDoubleBE=Z.writeDoubleBE,t.fill=Z.fill,t.inspect=Z.inspect,t.toArrayBuffer=Z.toArrayBuffer,t};var ee=/[^+\/0-9A-Za-z-_]/g}).call(t,n(409).Buffer,function(){return this}())},function(e,t){var n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";!function(e){"use strict";function t(e){var t=e.charCodeAt(0);return t===a||t===p?62:t===s||t===f?63:u>t?-1:u+10>t?t-u+26+26:l+26>t?t-l:c+26>t?t-c+26:void 0}function r(e){function n(e){c[p++]=e}var r,o,a,s,u,c;if(e.length%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var l=e.length;u="="===e.charAt(l-2)?2:"="===e.charAt(l-1)?1:0,c=new i(3*e.length/4-u),a=u>0?e.length-4:e.length;var p=0;for(r=0,o=0;a>r;r+=4,o+=3)s=t(e.charAt(r))<<18|t(e.charAt(r+1))<<12|t(e.charAt(r+2))<<6|t(e.charAt(r+3)),n((16711680&s)>>16),n((65280&s)>>8),n(255&s);return 2===u?(s=t(e.charAt(r))<<2|t(e.charAt(r+1))>>4,n(255&s)):1===u&&(s=t(e.charAt(r))<<10|t(e.charAt(r+1))<<4|t(e.charAt(r+2))>>2,n(s>>8&255),n(255&s)),c}function o(e){function t(e){return n.charAt(e)}function r(e){return t(e>>18&63)+t(e>>12&63)+t(e>>6&63)+t(63&e)}var o,i,a,s=e.length%3,u="";for(o=0,a=e.length-s;a>o;o+=3)i=(e[o]<<16)+(e[o+1]<<8)+e[o+2],u+=r(i);switch(s){case 1:i=e[e.length-1],u+=t(i>>2),u+=t(i<<4&63),u+="==";break;case 2:i=(e[e.length-2]<<8)+e[e.length-1],u+=t(i>>10),u+=t(i>>4&63),u+=t(i<<2&63),u+="="}return u}var i="undefined"!=typeof Uint8Array?Uint8Array:Array,a="+".charCodeAt(0),s="/".charCodeAt(0),u="0".charCodeAt(0),c="a".charCodeAt(0),l="A".charCodeAt(0),p="-".charCodeAt(0),f="_".charCodeAt(0);e.toByteArray=r,e.fromByteArray=o}(t)},function(e,t){t.read=function(e,t,n,r,o){var i,a,s=8*o-r-1,u=(1<<s)-1,c=u>>1,l=-7,p=n?o-1:0,f=n?-1:1,h=e[t+p];for(p+=f,i=h&(1<<-l)-1,h>>=-l,l+=s;l>0;i=256*i+e[t+p],p+=f,l-=8);for(a=i&(1<<-l)-1,i>>=-l,l+=r;l>0;a=256*a+e[t+p],p+=f,l-=8);if(0===i)i=1-c;else{if(i===u)return a?0/0:(h?-1:1)*(1/0);a+=Math.pow(2,r),i-=c}return(h?-1:1)*a*Math.pow(2,i-r)},t.write=function(e,t,n,r,o,i){var a,s,u,c=8*i-o-1,l=(1<<c)-1,p=l>>1,f=23===o?Math.pow(2,-24)-Math.pow(2,-77):0,h=r?0:i-1,d=r?1:-1,v=0>t||0===t&&0>1/t?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(s=isNaN(t)?1:0,a=l):(a=Math.floor(Math.log(t)/Math.LN2), t*(u=Math.pow(2,-a))<1&&(a--,u*=2),t+=a+p>=1?f/u:f*Math.pow(2,1-p),t*u>=2&&(a++,u/=2),a+p>=l?(s=0,a=l):a+p>=1?(s=(t*u-1)*Math.pow(2,o),a+=p):(s=t*Math.pow(2,p-1)*Math.pow(2,o),a=0));o>=8;e[n+h]=255&s,h+=d,s/=256,o-=8);for(a=a<<o|s,c+=o;c>0;e[n+h]=255&a,h+=d,a/=256,c-=8);e[n+h-d]|=128*v}},function(e){var t=Array.isArray,n=Object.prototype.toString;e.exports=t||function(e){return!!e&&"[object Array]"==n.call(e)}},function(e,t,n){"use strict";function r(e){var t=e.container,r=e.cssClasses,f=void 0===r?{}:r,h=e.hideContainerWhenNoResults,d=void 0===h?!0:h,v=e.templates,m=void 0===v?p:v,g=e.transformData,y=a.getContainerNode(t);if(!y)throw new Error("Usage: stats({container[, template, transformData]})");return{render:function(e){var t=e.results,r=e.templatesConfig,h=a.prepareTemplateProps({transformData:g,defaultTemplates:p,templatesConfig:r,templates:m}),v=s(u(n(415)));f={body:l(c("body"),f.body),footer:l(c("footer"),f.footer),header:l(c("header"),f.header),root:l(c(null),f.root),time:l(c("time"),f.time)},i.render(o.createElement(v,{cssClasses:f,hasResults:t.hits.length>0,hideContainerWhenNoResults:d,hitsPerPage:t.hitsPerPage,nbHits:t.nbHits,nbPages:t.nbPages,page:t.page,processingTimeMS:t.processingTimeMS,query:t.query,templateProps:h}),y)}}}var o=n(217),i=n(368),a=n(369),s=n(371),u=n(372),c=n(369).bemHelper("ais-stats"),l=n(370),p=n(414);e.exports=r},function(e){"use strict";e.exports={header:"",body:'{{#hasNoResults}}No results{{/hasNoResults}}\n {{#hasOneResult}}1 result{{/hasOneResult}}\n {{#hasManyResults}}{{#helpers.formatNumber}}{{nbHits}}{{/helpers.formatNumber}} results{{/hasManyResults}}\n <span class="{{cssClasses.time}}">found in {{processingTimeMS}}ms</span>',footer:""}},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},a=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),s=function(e,t,n){for(var r=!0;r;){var o=e,i=t,a=n;r=!1,null===o&&(o=Function.prototype);var s=Object.getOwnPropertyDescriptor(o,i);if(void 0!==s){if("value"in s)return s.value;var u=s.get;return void 0===u?void 0:u.call(a)}var c=Object.getPrototypeOf(o);if(null===c)return void 0;e=c,t=i,n=a,r=!0,s=c=void 0}},u=n(217),c=n(373),l=function(e){function t(){r(this,t),s(Object.getPrototypeOf(t.prototype),"constructor",this).apply(this,arguments)}return o(t,e),a(t,[{key:"render",value:function(){var e={hasManyResults:this.props.nbHits>1,hasNoResults:0===this.props.nbHits,hasOneResult:1===this.props.nbHits,hitsPerPage:this.props.hitsPerPage,nbHits:this.props.nbHits,nbPages:this.props.nbPages,page:this.props.page,processingTimeMS:this.props.processingTimeMS,query:this.props.query,cssClasses:this.props.cssClasses};return u.createElement(c,i({data:e,templateKey:"body"},this.props.templateProps))}}]),t}(u.Component);l.propTypes={cssClasses:u.PropTypes.shape({time:u.PropTypes.string}),hitsPerPage:u.PropTypes.number,nbHits:u.PropTypes.number,nbPages:u.PropTypes.number,page:u.PropTypes.number,processingTimeMS:u.PropTypes.number,query:u.PropTypes.string,templateProps:u.PropTypes.object.isRequired},e.exports=l},function(e,t,n){"use strict";function r(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],t=e.container,r=e.facetName,d=e.label,v=e.templates,m=void 0===v?h:v,g=e.cssClasses,y=void 0===g?{}:g,b=e.transformData,x=e.hideContainerWhenNoResults,w=void 0===x?!0:x,_=p(f(n(379))),P=u.getContainerNode(t),C="Usage: toggle({container, facetName, label[, cssClasses.{root,header,body,footer,list,item,active,label,checkbox,count}, templates.{header,item,footer}, transformData, hideContainerWhenNoResults]})";if(!t||!r||!d)throw new Error(C);return{getConfiguration:function(){return{facets:[r]}},render:function(e){var t=e.helper,n=e.results,p=e.templatesConfig,f=e.state,v=e.createURL,g=t.hasRefinements(r),x=i(n.getFacetValues(r),{name:g.toString()}),C=u.prepareTemplateProps({transformData:b,defaultTemplates:h,templatesConfig:p,templates:m}),E={name:d,isRefined:g,count:x&&x.count||null};y={root:l(c(null),y.root),header:l(c("header"),y.header),body:l(c("body"),y.body),footer:l(c("footer"),y.footer),list:l(c("list"),y.list),item:l(c("item"),y.item),active:l(c("item","active"),y.active),label:l(c("label"),y.label),checkbox:l(c("checkbox"),y.checkbox),count:l(c("count"),y.count)},s.render(a.createElement(_,{createURL:function(){return v(f.toggleRefinement(r,E.isRefined))},cssClasses:y,facetValues:[E],hasResults:n.hits.length>0,hideContainerWhenNoResults:w,templateProps:C,toggleRefinement:o.bind(null,t,r,E.isRefined)}),P)}}}function o(e,t,n){var r=n?"remove":"add";e[r+"FacetRefinement"](t,!0),e.search()}var i=n(128),a=n(217),s=n(368),u=n(369),c=u.bemHelper("ais-toggle"),l=n(370),p=n(371),f=n(372),h=n(417);e.exports=r},function(e){"use strict";e.exports={header:"",item:'<label class="{{cssClasses.label}}">\n <input type="checkbox" class="{{cssClasses.checkbox}}" value="{{name}}" {{#isRefined}}checked{{/isRefined}} />{{name}}\n <span class="{{cssClasses.count}}">{{count}}</span>\n</label>',footer:""}}])}); //# sourceMappingURL=instantsearch.min.map
app/containers/AdminNouvelleCommande/components/NouvelleCommandeParametres.js
Proxiweb/react-boilerplate
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import TextField from 'material-ui/TextField'; import DatePicker from 'material-ui/DatePicker'; import TimePicker from 'material-ui/TimePicker'; export default class NouvelleCommandeParametres extends Component { // eslint-disable-line static propTypes = { changeParam: PropTypes.func.isRequired, parametres: PropTypes.object.isRequired, }; render() { const { changeParam, parametres } = this.props; return ( <div className="row center-md" style={{ paddingTop: '2em' }}> <div className="col-md-6"> <TextField name="resume" fullWidth floatingLabelText="Texte résumant la commande (facultatif)" onChange={(event, value) => changeParam('resume', value)} value={parametres.resume} /> <div className="row center-md"> <div className="col-md"> <DatePicker hintText="Date limite" floatingLabelText="Date limite" fullWidth mode="landscape" autoOk locale="fr" okLabel="OK" cancelLabel="Annuler" DateTimeFormat={Intl.DateTimeFormat} onChange={(event, value) => changeParam('dateLimite', value)} value={parametres.dateLimite} /> </div> <div className="col-md"> <TimePicker format="24hr" floatingLabelText="Heure limite" hintText="Heure limite" autoOk fullWidth okLabel="OK" cancelLabel="Annuler" onChange={(event, value) => changeParam('heureLimite', value)} value={parametres.heureLimite} /> </div> </div> <div className="row center-md"> <div className="col-md-6"> <TextField name="montantMin" fullWidth floatingLabelText="montant min. global" onChange={(event, value) => changeParam('montantMin', value)} value={parametres.montantMin} /> </div> <div className="col-md-6"> <TextField name="montantMinRelai" fullWidth floatingLabelText="montant min / relais" onChange={(event, value) => changeParam('montantMinRelai', value)} value={parametres.montantMinRelai} /> </div> <div className="col-md-6"> <TextField name="qteMin" fullWidth floatingLabelText="quantité min. globale" onChange={(event, value) => changeParam('qteMin', value)} value={parametres.montantMin} /> </div> <div className="col-md-6"> <TextField name="qteMinRelais" fullWidth floatingLabelText="quantité min. / relais" onChange={(event, value) => changeParam('qteMinRelai', value)} value={parametres.montantMinRelai} /> </div> </div> </div> </div> ); } }
example-expo/NavBar.js
atFriendly/react-native-friendly-chat
/* eslint jsx-a11y/accessible-emoji: 0 */ import React from 'react'; import { Text } from 'react-native'; import NavBar, { NavTitle, NavButton } from 'react-native-nav'; import app from './app.json'; export default function NavBarCustom() { return ( <NavBar> <NavButton /> <NavTitle> 💬 Gifted Chat{'\n'} <Text style={{ fontSize: 10, color: '#aaa' }}>({app.expo.version})</Text> </NavTitle> <NavButton /> </NavBar> ); }
test/blink.spec.js
camlegleiter/react-blink
import React from 'react'; import { shallow } from 'enzyme'; import Blink from '../src/blink'; jest.useFakeTimers(); describe('<Blink />', () => { const text = 'hello world'; const props = { rate: 1000, className: 'custom-class', }; let component; beforeEach(() => { component = shallow(<Blink {...props}>{text}</Blink>); }); it('renders its children for blinking', () => { expect(component.children().text()).toEqual(text); }); it('displays the component by default', () => { expect(component.state('isVisible')).toEqual(true); expect(component.find('span').prop('style')).toEqual({ visibility: 'visible' }); }); describe('hiding the Blink component', () => { it('makes the component invisible after [props] rate', () => { expect(component.state('isVisible')).toEqual(true); component.instance().animate(); jest.runOnlyPendingTimers(); expect(setInterval.mock.calls[0][1]).toEqual(props.rate); expect(component.state('isVisible')).toEqual(false); expect(component.find('span').prop('style')).toEqual({ visibility: 'hidden' }); }); }); describe('showing the Blink component', () => { beforeEach(() => { component.instance().animate(); jest.runOnlyPendingTimers(); }); it('makes the component visible after [props] rate', () => { expect(component.state('isVisible')).toEqual(false); jest.runTimersToTime(props.rate); expect(setInterval.mock.calls[0][1]).toEqual(props.rate); expect(component.state('isVisible')).toEqual(true); expect(component.find('span').prop('style')).toEqual({ visibility: 'visible' }); }); }); describe('unmounting the Blink component', () => { it('stops animating', () => { const timer = component.blinkTimer; component.unmount(); expect(clearInterval.mock.calls[0][0]).toEqual(timer); }); }); });
examples/browser/create-splunk-react-app/src/App.js
splunk/splunk-sdk-javascript
import React from 'react'; import './App.css'; import SplunkJsExample from './SplunkJsExample'; function App() { return ( <div className="App"> <header className="App-header"> <p> 1. Edit <code>src/splunkConfig.js</code> to input your Splunk host/port information and restart this project using <code>npm start</code>. </p> <p> 2. Enter credentials below and click <code>Search</code> to login, run a sample search, and display the results. </p> <SplunkJsExample /> </header> </div> ); } export default App;
modules/__tests__/matchRoutes-test.js
meraki/react-router
import expect from 'expect' import React from 'react' import { createMemoryHistory } from 'history' import { createRoutes } from '../RouteUtils' import matchRoutes from '../matchRoutes' import Route from '../Route' import IndexRoute from '../IndexRoute' describe('matchRoutes', function () { let routes let RootRoute, UsersRoute, UsersIndexRoute, UserRoute, PostRoute, FilesRoute, AboutRoute, TeamRoute, ProfileRoute, GreedyRoute, OptionalRoute, OptionalRouteChild, CatchAllRoute let createLocation = createMemoryHistory().createLocation beforeEach(function () { /* <Route> <Route path="users"> <IndexRoute /> <Route path=":userID"> <Route path="/profile" /> </Route> <Route path="/team" /> </Route> </Route> <Route path="/about" /> <Route path="/(optional)"> <Route path="child" /> </Route> <Route path="*" /> */ routes = [ RootRoute = { childRoutes: [ UsersRoute = { path: 'users', indexRoute: (UsersIndexRoute = {}), childRoutes: [ UserRoute = { path: ':userID', childRoutes: [ ProfileRoute = { path: '/profile' }, PostRoute = { path: ':postID' } ] }, TeamRoute = { path: '/team' } ] } ] }, FilesRoute = { path: '/files/*/*.jpg' }, AboutRoute = { path: '/about' }, GreedyRoute = { path: '/**/f' }, OptionalRoute = { path: '/(optional)', childRoutes: [ OptionalRouteChild = { path: 'child' } ] }, CatchAllRoute = { path: '*' } ] }) function describeRoutes() { describe('when the location matches an index route', function () { it('matches the correct routes', function (done) { matchRoutes(routes, createLocation('/users'), function (error, match) { expect(match).toExist() expect(match.routes).toEqual([ RootRoute, UsersRoute, UsersIndexRoute ]) done() }) }) }) describe('when the location matches a nested route with params', function () { it('matches the correct routes and params', function (done) { matchRoutes(routes, createLocation('/users/5'), function (error, match) { expect(match).toExist() expect(match.routes).toEqual([ RootRoute, UsersRoute, UserRoute ]) expect(match.params).toEqual({ userID: '5' }) done() }) }) }) describe('when the location matches a deeply nested route with params', function () { it('matches the correct routes and params', function (done) { matchRoutes(routes, createLocation('/users/5/abc'), function (error, match) { expect(match).toExist() expect(match.routes).toEqual([ RootRoute, UsersRoute, UserRoute, PostRoute ]) expect(match.params).toEqual({ userID: '5', postID: 'abc' }) done() }) }) }) describe('when the location matches a nested route with multiple splat params', function () { it('matches the correct routes and params', function (done) { matchRoutes(routes, createLocation('/files/a/b/c.jpg'), function (error, match) { expect(match).toExist() expect(match.routes).toEqual([ FilesRoute ]) expect(match.params).toEqual({ splat: [ 'a', 'b/c' ] }) done() }) }) }) describe('when the location matches a nested route with a greedy splat param', function () { it('matches the correct routes and params', function (done) { matchRoutes(routes, createLocation('/foo/bar/f'), function (error, match) { expect(match).toExist() expect(match.routes).toEqual([ GreedyRoute ]) expect(match.params).toEqual({ splat: 'foo/bar' }) done() }) }) }) describe('when the location matches a route with hash', function () { it('matches the correct routes', function (done) { matchRoutes(routes, createLocation('/users#about'), function (error, match) { expect(match).toExist() expect(match.routes).toEqual([ RootRoute, UsersRoute, UsersIndexRoute ]) done() }) }) }) describe('when the location matches a deeply nested route with params and hash', function () { it('matches the correct routes and params', function (done) { matchRoutes(routes, createLocation('/users/5/abc#about'), function (error, match) { expect(match).toExist() expect(match.routes).toEqual([ RootRoute, UsersRoute, UserRoute, PostRoute ]) expect(match.params).toEqual({ userID: '5', postID: 'abc' }) done() }) }) }) describe('when the location matches an absolute route', function () { it('matches the correct routes', function (done) { matchRoutes(routes, createLocation('/about'), function (error, match) { expect(match).toExist() expect(match.routes).toEqual([ AboutRoute ]) done() }) }) }) describe('when the location matches an optional route', function () { it('matches when the optional pattern is missing', function (done) { matchRoutes(routes, createLocation('/'), function (error, match) { expect(match).toExist() expect(match.routes).toEqual([ OptionalRoute ]) done() }) }) it('matches when the optional pattern is present', function (done) { matchRoutes(routes, createLocation('/optional'), function (error, match) { expect(match).toExist() expect(match.routes).toEqual([ OptionalRoute ]) done() }) }) }) describe('when the location matches the child of an optional route', function () { it('matches when the optional pattern is missing', function (done) { matchRoutes(routes, createLocation('/child'), function (error, match) { expect(match).toExist() expect(match.routes).toEqual([ OptionalRoute, OptionalRouteChild ]) done() }) }) it('matches when the optional pattern is present', function (done) { matchRoutes(routes, createLocation('/optional/child'), function (error, match) { expect(match).toExist() expect(match.routes).toEqual([ OptionalRoute, OptionalRouteChild ]) done() }) }) }) describe('when the location does not match any routes', function () { it('matches the "catch-all" route', function (done) { matchRoutes(routes, createLocation('/not-found'), function (error, match) { expect(match).toExist() expect(match.routes).toEqual([ CatchAllRoute ]) done() }) }) it('matches the "catch-all" route on a deep miss', function (done) { matchRoutes(routes, createLocation('/not-found/foo'), function (error, match) { expect(match).toExist() expect(match.routes).toEqual([ CatchAllRoute ]) done() }) }) it('matches the "catch-all" route on missing path separators', function (done) { matchRoutes(routes, createLocation('/optionalchild'), function (error, match) { expect(match).toExist() expect(match.routes).toEqual([ CatchAllRoute ]) done() }) }) }) } describe('a synchronous route config', function () { describeRoutes() describe('when the location matches a nested absolute route', function () { it('matches the correct routes', function (done) { matchRoutes(routes, createLocation('/team'), function (error, match) { expect(match).toExist() expect(match.routes).toEqual([ RootRoute, UsersRoute, TeamRoute ]) done() }) }) }) describe('when the location matches an absolute route nested under a route with params', function () { it('matches the correct routes and params', function (done) { matchRoutes(routes, createLocation('/profile'), function (error, match) { expect(match).toExist() expect(match.routes).toEqual([ RootRoute, UsersRoute, UserRoute, ProfileRoute ]) expect(match.params).toEqual({}) // no userID param done() }) }) }) }) describe('an asynchronous route config', function () { function makeAsyncRouteConfig(routes) { routes.forEach(function (route) { const { childRoutes, indexRoute } = route if (childRoutes) { delete route.childRoutes route.getChildRoutes = function (location, callback) { setTimeout(function () { callback(null, childRoutes) }) } makeAsyncRouteConfig(childRoutes) } if (indexRoute) { delete route.indexRoute route.getIndexRoute = function (location, callback) { setTimeout(function () { callback(null, indexRoute) }) } } }) } beforeEach(function () { makeAsyncRouteConfig(routes) }) describeRoutes() }) describe('an asynchronous JSX route config', function () { let getChildRoutes, getIndexRoute, jsxRoutes beforeEach(function () { getChildRoutes = function (location, callback) { setTimeout(function () { callback(null, <Route path=":userID" />) }) } getIndexRoute = function (location, callback) { setTimeout(function () { callback(null, <Route name="jsx" />) }) } jsxRoutes = createRoutes([ <Route name="users" path="users" getChildRoutes={getChildRoutes} getIndexRoute={getIndexRoute} /> ]) }) it('when getChildRoutes callback returns reactElements', function (done) { matchRoutes(jsxRoutes, createLocation('/users/5'), function (error, match) { expect(match).toExist() expect(match.routes.map(r => r.path)).toEqual([ 'users', ':userID' ]) expect(match.params).toEqual({ userID: '5' }) done() }) }) it('when getIndexRoute callback returns reactElements', function (done) { matchRoutes(jsxRoutes, createLocation('/users'), function (error, match) { expect(match).toExist() expect(match.routes.map(r => r.name)).toEqual([ 'users', 'jsx' ]) done() }) }) }) describe('invalid route configs', function () { let invalidRoutes, errorSpy beforeEach(function () { errorSpy = expect.spyOn(console, 'error') }) afterEach(function () { errorSpy.restore() }) describe('index route with path', function () { beforeEach(function () { invalidRoutes = createRoutes( <Route path="/"> <IndexRoute path="foo" /> </Route> ) }) it('complains when matching', function (done) { matchRoutes(invalidRoutes, createLocation('/'), function (error, match) { expect(match).toExist() expect(errorSpy).toHaveBeenCalledWith('Warning: [react-router] Index routes should not have paths') done() }) }) }) }) })
src/svg-icons/device/signal-cellular-connected-no-internet-1-bar.js
hai-cea/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceSignalCellularConnectedNoInternet1Bar = (props) => ( <SvgIcon {...props}> <path fillOpacity=".3" d="M22 8V2L2 22h16V8z"/><path d="M20 10v8h2v-8h-2zm-8 12V12L2 22h10zm8 0h2v-2h-2v2z"/> </SvgIcon> ); DeviceSignalCellularConnectedNoInternet1Bar = pure(DeviceSignalCellularConnectedNoInternet1Bar); DeviceSignalCellularConnectedNoInternet1Bar.displayName = 'DeviceSignalCellularConnectedNoInternet1Bar'; DeviceSignalCellularConnectedNoInternet1Bar.muiName = 'SvgIcon'; export default DeviceSignalCellularConnectedNoInternet1Bar;
client/modules/core/components/post.js
mantrajs/mantra-sample-blog-app
import React from 'react'; import CommentList from '../../comments/containers/comment_list'; const Post = ({post}) => ( <div> {post.saving ? <p>Saving...</p> : null} <h2>{post.title}</h2> <p> {post.content} </p> <div> <h4>Comments</h4> <CommentList postId={post._id}/> </div> </div> ); export default Post;
website/js/jquery-1.10.2.min.js
asm-products/mista-condom
/*! 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/shared/__stories__/knob.stories.js
nattatorn-dev/currency-exchange
import React from 'react' import { storiesOf } from '@kadira/storybook' import moment from 'moment' import { withKnobs, number, object, boolean, text, select, date, array, color, } from '@kadira/storybook-addon-knobs' const stories = storiesOf( 'Example of Knobs', module ) stories.addDecorator( withKnobs ) stories.add( 'simple example', () => ( <button>{text( 'Label', 'Hello Button' )}</button> ) ) stories.add( 'with all knobs', () => { const name = text( 'Name', 'Tom Cary' ) const dob = date( 'DOB', new Date( 'January 20 1887' ) ) const bold = boolean( 'Bold', false ) const selectedColor = color( 'Color', 'black' ) const favoriteNumber = number( 'Favorite Number', 42 ) const comfortTemp = number( 'Comfort Temp', 72, { range: true, min: 60, max: 90, step: 1, } ) const passions = array( 'Passions', [ 'Fishing', 'Skiing' ] ) const customStyle = object( 'Style', { fontFamily: 'Arial', padding: 20, } ) const style = { ...customStyle, fontWeight: bold ? 800 : 400, favoriteNumber: favoriteNumber, color: selectedColor, } return ( <div style={style}> I'm {name} and I was born on "{moment( dob ).format( 'DD MMM YYYY' )}" I like: <ul>{passions.map( ( p, i ) => <li key={i}>{p}</li> )}</ul> <p>My favorite number is {favoriteNumber}.</p> <p> My most comfortable room temperature is {' '} {comfortTemp} {' '} degrees Fahrenheit. </p> </div> ) } ) stories.add( 'dates Knob', () => { const today = date( 'today' ) const dob = date( 'DOB', null ) const myDob = date( 'My DOB', new Date( 'July 07 1993' ) ) return ( <ul style={{ listStyleType: 'none', listStyle: 'none', paddingLeft: '15px' }} > <li> <p><b>Javascript Date</b> default value, passes date value</p> <blockquote> <code>const myDob = date('My DOB', new Date('July 07 1993'));</code> <pre>// I was born in: "{moment( myDob ).format( 'DD MMM YYYY' )}"</pre> </blockquote> </li> <li> <p><b>undefined</b> default value passes today's date</p> <blockquote> <code>const today = date('today');</code> <pre>// Today's date is: "{moment( today ).format( 'DD MMM YYYY' )}"</pre> </blockquote> </li> <li> <p><b>null</b> default value passes null value</p> <blockquote> <code>const dob = date('DOB', null);</code> <pre> // You were born in: " {dob ? moment( dob ).format( 'DD MMM YYYY' ) : 'Please select date.'} " </pre> </blockquote> </li> </ul> ) } ) stories.add( 'dynamic knobs', () => { const showOptional = select( 'Show optional', [ 'yes', 'no' ], 'yes' ) return ( <div> <div> {text( 'compulsary', 'I must be here' )} </div> {showOptional === 'yes' ? <div>{text( 'optional', 'I can disapear' )}</div> : null} </div> ) } ) stories.add( 'without any knob', () => <button>This is a button</button> )
classic/src/scenes/mailboxes/src/Scenes/SwitcherScene/SwitcherScene.js
wavebox/waveboxapp
import React from 'react' import PropTypes from 'prop-types' import shallowCompare from 'react-addons-shallow-compare' import { withStyles } from '@material-ui/core/styles' import Zoom from '@material-ui/core/Zoom' import SwitcherSceneContent from './SwitcherSceneContent' import { RouterDialog, RouterDialogStateProvider } from 'wbui/RouterDialog' import { WB_QUICK_SWITCH_NEXT, WB_QUICK_SWITCH_PREV, WB_QUICK_SWITCH_PRESENT_NEXT, WB_QUICK_SWITCH_PRESENT_PREV } from 'shared/ipcEvents' import { ipcRenderer } from 'electron' import { accountActions } from 'stores/account' const TRANSITION_DURATION = 50 const styles = { root: { maxWidth: '100%', backgroundColor: 'rgba(245, 245, 245, 0.95)', borderRadius: 10 } } @withStyles(styles) class SwitcherScene extends React.Component { /* **************************************************************************/ // Class /* **************************************************************************/ static propTypes = { routeName: PropTypes.string.isRequired } /* **************************************************************************/ // Component lifecycle /* **************************************************************************/ componentDidMount () { ipcRenderer.on(WB_QUICK_SWITCH_NEXT, this.handleIPCNext) ipcRenderer.on(WB_QUICK_SWITCH_PREV, this.handleIPCPrev) ipcRenderer.on(WB_QUICK_SWITCH_PRESENT_NEXT, this.handleIPCPresentNext) ipcRenderer.on(WB_QUICK_SWITCH_PRESENT_PREV, this.handleIPCPresentPrev) } componentWillUnmount () { ipcRenderer.removeListener(WB_QUICK_SWITCH_NEXT, this.handleIPCNext) ipcRenderer.removeListener(WB_QUICK_SWITCH_PREV, this.handleIPCPrev) ipcRenderer.removeListener(WB_QUICK_SWITCH_PRESENT_NEXT, this.handleIPCPresentNext) ipcRenderer.removeListener(WB_QUICK_SWITCH_PRESENT_PREV, this.handleIPCPresentPrev) } /* **************************************************************************/ // User Interaction /* **************************************************************************/ /** * Quick switches to the next account */ handleIPCNext = (evt) => { window.location.hash = '/' accountActions.quickSwitchNextService() } /** * Quick switches to the prev account */ handleIPCPrev = (evt) => { window.location.hash = '/' accountActions.quickSwitchPrevService() } /** * Launches quick switch in next mode */ handleIPCPresentNext = (evt) => { window.location.hash = '/switcher/next' } /** * Launches quick switch in prev mode */ handleIPCPresentPrev = (evt) => { window.location.hash = '/switcher/prev' } /** * Closes the modal */ handleClose = () => { window.location.hash = '/' } /* **************************************************************************/ // Rendering /* **************************************************************************/ shouldComponentUpdate (nextProps, nextState) { return shallowCompare(this, nextProps, nextState) } render () { const { classes, routeName } = this.props return ( <RouterDialog routeName={routeName} disableEnforceFocus transitionDuration={TRANSITION_DURATION} TransitionComponent={Zoom} onClose={this.handleClose} classes={{ paper: classes.root }}> <RouterDialogStateProvider routeName={routeName} Component={SwitcherSceneContent} /> </RouterDialog> ) } } export default SwitcherScene
ajax/libs/openlayers/2.11/lib/OpenLayers/Control/Panel.js
lobbin/cdnjs
/* Copyright (c) 2006-2011 by OpenLayers Contributors (see authors.txt for * full list of contributors). Published under the Clear BSD license. * See http://svn.openlayers.org/trunk/openlayers/license.txt for the * full text of the license. */ /** * @requires OpenLayers/Control.js */ /** * Class: OpenLayers.Control.Panel * The Panel control is a container for other controls. With it toolbars * may be composed. * * Inherits from: * - <OpenLayers.Control> */ OpenLayers.Control.Panel = OpenLayers.Class(OpenLayers.Control, { /** * Property: controls * {Array(<OpenLayers.Control>)} */ controls: null, /** * APIProperty: autoActivate * {Boolean} Activate the control when it is added to a map. Default is * true. */ autoActivate: true, /** * APIProperty: defaultControl * {<OpenLayers.Control>} The control which is activated when the control is * activated (turned on), which also happens at instantiation. * If <saveState> is true, <defaultControl> will be nullified after the * first activation of the panel. */ defaultControl: null, /** * APIProperty: saveState * {Boolean} If set to true, the active state of this panel's controls will * be stored on panel deactivation, and restored on reactivation. Default * is false. */ saveState: false, /** * APIProperty: allowDepress * {Boolean} If is true the <OpenLayers.Control.TYPE_TOOL> controls can * be deactivated by clicking the icon that represents them. Default * is false. */ allowDepress: false, /** * Property: activeState * {Object} stores the active state of this panel's controls. */ activeState: null, /** * Constructor: OpenLayers.Control.Panel * Create a new control panel. * * Each control in the panel is represented by an icon. When clicking * on an icon, the <activateControl> method is called. * * Specific properties for controls on a panel: * type - {Number} One of <OpenLayers.Control.TYPE_TOOL>, * <OpenLayers.Control.TYPE_TOGGLE>, <OpenLayers.Control.TYPE_BUTTON>. * If not provided, <OpenLayers.Control.TYPE_TOOL> is assumed. * title - {string} Text displayed when mouse is over the icon that * represents the control. * * The <OpenLayers.Control.type> of a control determines the behavior when * clicking its icon: * <OpenLayers.Control.TYPE_TOOL> - The control is activated and other * controls of this type in the same panel are deactivated. This is * the default type. * <OpenLayers.Control.TYPE_TOGGLE> - The active state of the control is * toggled. * <OpenLayers.Control.TYPE_BUTTON> - The * <OpenLayers.Control.Button.trigger> method of the control is called, * but its active state is not changed. * * If a control is <OpenLayers.Control.active>, it will be drawn with the * olControl[Name]ItemActive class, otherwise with the * olControl[Name]ItemInactive class. * * Parameters: * options - {Object} An optional object whose properties will be used * to extend the control. */ initialize: function(options) { OpenLayers.Control.prototype.initialize.apply(this, [options]); this.controls = []; this.activeState = {}; }, /** * APIMethod: destroy */ destroy: function() { OpenLayers.Control.prototype.destroy.apply(this, arguments); for (var ctl, i = this.controls.length - 1; i >= 0; i--) { ctl = this.controls[i]; if (ctl.events) { ctl.events.un({ activate: this.iconOn, deactivate: this.iconOff }); } OpenLayers.Event.stopObservingElement(ctl.panel_div); ctl.panel_div = null; } this.activeState = null; }, /** * APIMethod: activate */ activate: function() { if (OpenLayers.Control.prototype.activate.apply(this, arguments)) { var control; for (var i=0, len=this.controls.length; i<len; i++) { control = this.controls[i]; if (control === this.defaultControl || (this.saveState && this.activeState[control.id])) { control.activate(); } } if (this.saveState === true) { this.defaultControl = null; } this.redraw(); return true; } else { return false; } }, /** * APIMethod: deactivate */ deactivate: function() { if (OpenLayers.Control.prototype.deactivate.apply(this, arguments)) { var control; for (var i=0, len=this.controls.length; i<len; i++) { control = this.controls[i]; this.activeState[control.id] = control.deactivate(); } this.redraw(); return true; } else { return false; } }, /** * Method: draw * * Returns: * {DOMElement} */ draw: function() { OpenLayers.Control.prototype.draw.apply(this, arguments); this.addControlsToMap(this.controls); return this.div; }, /** * Method: redraw */ redraw: function() { for (var l=this.div.childNodes.length, i=l-1; i>=0; i--) { this.div.removeChild(this.div.childNodes[i]); } this.div.innerHTML = ""; if (this.active) { for (var i=0, len=this.controls.length; i<len; i++) { this.div.appendChild(this.controls[i].panel_div); } } }, /** * APIMethod: activateControl * This method is called when the user click on the icon representing a * control in the panel. * * Parameters: * control - {<OpenLayers.Control>} */ activateControl: function (control) { if (!this.active) { return false; } if (control.type == OpenLayers.Control.TYPE_BUTTON) { control.trigger(); return; } if (control.type == OpenLayers.Control.TYPE_TOGGLE) { if (control.active) { control.deactivate(); } else { control.activate(); } return; } if (this.allowDepress && control.active) { control.deactivate(); } else { var c; for (var i=0, len=this.controls.length; i<len; i++) { c = this.controls[i]; if (c != control && (c.type === OpenLayers.Control.TYPE_TOOL || c.type == null)) { c.deactivate(); } } control.activate(); } }, /** * APIMethod: addControls * To build a toolbar, you add a set of controls to it. addControls * lets you add a single control or a list of controls to the * Control Panel. * * Parameters: * controls - {<OpenLayers.Control>} Controls to add in the panel. */ addControls: function(controls) { if (!(OpenLayers.Util.isArray(controls))) { controls = [controls]; } this.controls = this.controls.concat(controls); // Give each control a panel_div which will be used later. // Access to this div is via the panel_div attribute of the // control added to the panel. // Also, stop mousedowns and clicks, but don't stop mouseup, // since they need to pass through. for (var i=0, len=controls.length; i<len; i++) { var element = document.createElement("div"); element.className = controls[i].displayClass + "ItemInactive"; controls[i].panel_div = element; if (controls[i].title != "") { controls[i].panel_div.title = controls[i].title; } OpenLayers.Event.observe(controls[i].panel_div, "click", OpenLayers.Function.bind(this.onClick, this, controls[i])); OpenLayers.Event.observe(controls[i].panel_div, "dblclick", OpenLayers.Function.bind(this.onDoubleClick, this, controls[i])); OpenLayers.Event.observe(controls[i].panel_div, "mousedown", OpenLayers.Function.bindAsEventListener(OpenLayers.Event.stop)); } if (this.map) { // map.addControl() has already been called on the panel this.addControlsToMap(controls); this.redraw(); } }, /** * Method: addControlsToMap * Only for internal use in draw() and addControls() methods. * * Parameters: * controls - {Array(<OpenLayers.Control>)} Controls to add into map. */ addControlsToMap: function (controls) { var control; for (var i=0, len=controls.length; i<len; i++) { control = controls[i]; if (control.autoActivate === true) { control.autoActivate = false; this.map.addControl(control); control.autoActivate = true; } else { this.map.addControl(control); control.deactivate(); } control.events.on({ activate: this.iconOn, deactivate: this.iconOff }); } }, /** * Method: iconOn * Internal use, for use only with "controls[i].events.on/un". */ iconOn: function() { var d = this.panel_div; // "this" refers to a control on panel! d.className = d.className.replace(/ItemInactive$/, "ItemActive"); }, /** * Method: iconOff * Internal use, for use only with "controls[i].events.on/un". */ iconOff: function() { var d = this.panel_div; // "this" refers to a control on panel! d.className = d.className.replace(/ItemActive$/, "ItemInactive"); }, /** * Method: onClick */ onClick: function (ctrl, evt) { OpenLayers.Event.stop(evt ? evt : window.event); this.activateControl(ctrl); }, /** * Method: onDoubleClick */ onDoubleClick: function(ctrl, evt) { OpenLayers.Event.stop(evt ? evt : window.event); }, /** * APIMethod: getControlsBy * Get a list of controls with properties matching the given criteria. * * Parameter: * property - {String} A control property to be matched. * match - {String | Object} A string to match. Can also be a regular * expression literal or object. In addition, it can be any object * with a method named test. For reqular expressions or other, if * match.test(control[property]) evaluates to true, the control will be * included in the array returned. If no controls are found, an empty * array is returned. * * Returns: * {Array(<OpenLayers.Control>)} A list of controls matching the given criteria. * An empty array is returned if no matches are found. */ getControlsBy: function(property, match) { var test = (typeof match.test == "function"); var found = OpenLayers.Array.filter(this.controls, function(item) { return item[property] == match || (test && match.test(item[property])); }); return found; }, /** * APIMethod: getControlsByName * Get a list of contorls with names matching the given name. * * Parameter: * match - {String | Object} A control name. The name can also be a regular * expression literal or object. In addition, it can be any object * with a method named test. For reqular expressions or other, if * name.test(control.name) evaluates to true, the control will be included * in the list of controls returned. If no controls are found, an empty * array is returned. * * Returns: * {Array(<OpenLayers.Control>)} A list of controls matching the given name. * An empty array is returned if no matches are found. */ getControlsByName: function(match) { return this.getControlsBy("name", match); }, /** * APIMethod: getControlsByClass * Get a list of controls of a given type (CLASS_NAME). * * Parameter: * match - {String | Object} A control class name. The type can also be a * regular expression literal or object. In addition, it can be any * object with a method named test. For reqular expressions or other, * if type.test(control.CLASS_NAME) evaluates to true, the control will * be included in the list of controls returned. If no controls are * found, an empty array is returned. * * Returns: * {Array(<OpenLayers.Control>)} A list of controls matching the given type. * An empty array is returned if no matches are found. */ getControlsByClass: function(match) { return this.getControlsBy("CLASS_NAME", match); }, CLASS_NAME: "OpenLayers.Control.Panel" });
packages/material-ui-icons/src/Adjust.js
kybarg/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M12 2C6.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 8zm3-8c0 1.66-1.34 3-3 3s-3-1.34-3-3 1.34-3 3-3 3 1.34 3 3z" /> , 'Adjust');
ajax/libs/datatables/1.10.4/js/jquery.js
JimBobSquarePants/cdnjs
/*! jQuery v1.11.1 | (c) 2005, 2014 jQuery Foundation, Inc. | jquery.org/license */ !function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k={},l="1.11.1",m=function(a,b){return new m.fn.init(a,b)},n=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,o=/^-ms-/,p=/-([\da-z])/gi,q=function(a,b){return b.toUpperCase()};m.fn=m.prototype={jquery:l,constructor:m,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=m.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return m.each(this,a,b)},map:function(a){return this.pushStack(m.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},m.extend=m.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||m.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(e=arguments[h]))for(d in e)a=g[d],c=e[d],g!==c&&(j&&c&&(m.isPlainObject(c)||(b=m.isArray(c)))?(b?(b=!1,f=a&&m.isArray(a)?a:[]):f=a&&m.isPlainObject(a)?a:{},g[d]=m.extend(j,f,c)):void 0!==c&&(g[d]=c));return g},m.extend({expando:"jQuery"+(l+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===m.type(a)},isArray:Array.isArray||function(a){return"array"===m.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){return!m.isArray(a)&&a-parseFloat(a)>=0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},isPlainObject:function(a){var b;if(!a||"object"!==m.type(a)||a.nodeType||m.isWindow(a))return!1;try{if(a.constructor&&!j.call(a,"constructor")&&!j.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}if(k.ownLast)for(b in a)return j.call(a,b);for(b in a);return void 0===b||j.call(a,b)},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(b){b&&m.trim(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(o,"ms-").replace(p,q)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=r(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(n,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(r(Object(a))?m.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){var d;if(b){if(g)return g.call(b,a,c);for(d=b.length,c=c?0>c?Math.max(0,d+c):c:0;d>c;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,b){var c=+b.length,d=0,e=a.length;while(c>d)a[e++]=b[d++];if(c!==c)while(void 0!==b[d])a[e++]=b[d++];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=r(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(f=a[b],b=a,a=f),m.isFunction(a)?(c=d.call(arguments,2),e=function(){return a.apply(b||this,c.concat(d.call(arguments)))},e.guid=a.guid=a.guid||m.guid++,e):void 0},now:function(){return+new Date},support:k}),m.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function r(a){var b=a.length,c=m.type(a);return"function"===c||m.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var s=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+-new Date,v=a.document,w=0,x=0,y=gb(),z=gb(),A=gb(),B=function(a,b){return a===b&&(l=!0),0},C="undefined",D=1<<31,E={}.hasOwnProperty,F=[],G=F.pop,H=F.push,I=F.push,J=F.slice,K=F.indexOf||function(a){for(var b=0,c=this.length;c>b;b++)if(this[b]===a)return b;return-1},L="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",M="[\\x20\\t\\r\\n\\f]",N="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",O=N.replace("w","w#"),P="\\["+M+"*("+N+")(?:"+M+"*([*^$|!~]?=)"+M+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+O+"))|)"+M+"*\\]",Q=":("+N+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+P+")*)|.*)\\)|)",R=new RegExp("^"+M+"+|((?:^|[^\\\\])(?:\\\\.)*)"+M+"+$","g"),S=new RegExp("^"+M+"*,"+M+"*"),T=new RegExp("^"+M+"*([>+~]|"+M+")"+M+"*"),U=new RegExp("="+M+"*([^\\]'\"]*?)"+M+"*\\]","g"),V=new RegExp(Q),W=new RegExp("^"+O+"$"),X={ID:new RegExp("^#("+N+")"),CLASS:new RegExp("^\\.("+N+")"),TAG:new RegExp("^("+N.replace("w","w*")+")"),ATTR:new RegExp("^"+P),PSEUDO:new RegExp("^"+Q),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+L+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},Y=/^(?:input|select|textarea|button)$/i,Z=/^h\d$/i,$=/^[^{]+\{\s*\[native \w/,_=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ab=/[+~]/,bb=/'|\\/g,cb=new RegExp("\\\\([\\da-f]{1,6}"+M+"?|("+M+")|.)","ig"),db=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)};try{I.apply(F=J.call(v.childNodes),v.childNodes),F[v.childNodes.length].nodeType}catch(eb){I={apply:F.length?function(a,b){H.apply(a,J.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function fb(a,b,d,e){var f,h,j,k,l,o,r,s,w,x;if((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,d=d||[],!a||"string"!=typeof a)return d;if(1!==(k=b.nodeType)&&9!==k)return[];if(p&&!e){if(f=_.exec(a))if(j=f[1]){if(9===k){if(h=b.getElementById(j),!h||!h.parentNode)return d;if(h.id===j)return d.push(h),d}else if(b.ownerDocument&&(h=b.ownerDocument.getElementById(j))&&t(b,h)&&h.id===j)return d.push(h),d}else{if(f[2])return I.apply(d,b.getElementsByTagName(a)),d;if((j=f[3])&&c.getElementsByClassName&&b.getElementsByClassName)return I.apply(d,b.getElementsByClassName(j)),d}if(c.qsa&&(!q||!q.test(a))){if(s=r=u,w=b,x=9===k&&a,1===k&&"object"!==b.nodeName.toLowerCase()){o=g(a),(r=b.getAttribute("id"))?s=r.replace(bb,"\\$&"):b.setAttribute("id",s),s="[id='"+s+"'] ",l=o.length;while(l--)o[l]=s+qb(o[l]);w=ab.test(a)&&ob(b.parentNode)||b,x=o.join(",")}if(x)try{return I.apply(d,w.querySelectorAll(x)),d}catch(y){}finally{r||b.removeAttribute("id")}}}return i(a.replace(R,"$1"),b,d,e)}function gb(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function hb(a){return a[u]=!0,a}function ib(a){var b=n.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function jb(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function kb(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||D)-(~a.sourceIndex||D);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function lb(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function mb(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function nb(a){return hb(function(b){return b=+b,hb(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function ob(a){return a&&typeof a.getElementsByTagName!==C&&a}c=fb.support={},f=fb.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},m=fb.setDocument=function(a){var b,e=a?a.ownerDocument||a:v,g=e.defaultView;return e!==n&&9===e.nodeType&&e.documentElement?(n=e,o=e.documentElement,p=!f(e),g&&g!==g.top&&(g.addEventListener?g.addEventListener("unload",function(){m()},!1):g.attachEvent&&g.attachEvent("onunload",function(){m()})),c.attributes=ib(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ib(function(a){return a.appendChild(e.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=$.test(e.getElementsByClassName)&&ib(function(a){return a.innerHTML="<div class='a'></div><div class='a i'></div>",a.firstChild.className="i",2===a.getElementsByClassName("i").length}),c.getById=ib(function(a){return o.appendChild(a).id=u,!e.getElementsByName||!e.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if(typeof b.getElementById!==C&&p){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(cb,db);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(cb,db);return function(a){var c=typeof a.getAttributeNode!==C&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return typeof b.getElementsByTagName!==C?b.getElementsByTagName(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return typeof b.getElementsByClassName!==C&&p?b.getElementsByClassName(a):void 0},r=[],q=[],(c.qsa=$.test(e.querySelectorAll))&&(ib(function(a){a.innerHTML="<select msallowclip=''><option selected=''></option></select>",a.querySelectorAll("[msallowclip^='']").length&&q.push("[*^$]="+M+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+M+"*(?:value|"+L+")"),a.querySelectorAll(":checked").length||q.push(":checked")}),ib(function(a){var b=e.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+M+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=$.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ib(function(a){c.disconnectedMatch=s.call(a,"div"),s.call(a,"[s!='']:x"),r.push("!=",Q)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=$.test(o.compareDocumentPosition),t=b||$.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===e||a.ownerDocument===v&&t(v,a)?-1:b===e||b.ownerDocument===v&&t(v,b)?1:k?K.call(k,a)-K.call(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,f=a.parentNode,g=b.parentNode,h=[a],i=[b];if(!f||!g)return a===e?-1:b===e?1:f?-1:g?1:k?K.call(k,a)-K.call(k,b):0;if(f===g)return kb(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)i.unshift(c);while(h[d]===i[d])d++;return d?kb(h[d],i[d]):h[d]===v?-1:i[d]===v?1:0},e):n},fb.matches=function(a,b){return fb(a,null,null,b)},fb.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(U,"='$1']"),!(!c.matchesSelector||!p||r&&r.test(b)||q&&q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return fb(b,n,null,[a]).length>0},fb.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},fb.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&E.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},fb.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},fb.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=fb.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=fb.selectors={cacheLength:50,createPseudo:hb,match:X,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(cb,db),a[3]=(a[3]||a[4]||a[5]||"").replace(cb,db),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||fb.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&fb.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return X.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&V.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(cb,db).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+M+")"+a+"("+M+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||typeof a.getAttribute!==C&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=fb.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){k=q[u]||(q[u]={}),j=k[a]||[],n=j[0]===w&&j[1],m=j[0]===w&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[w,n,m];break}}else if(s&&(j=(b[u]||(b[u]={}))[a])&&j[0]===w)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(s&&((l[u]||(l[u]={}))[a]=[w,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||fb.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?hb(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=K.call(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:hb(function(a){var b=[],c=[],d=h(a.replace(R,"$1"));return d[u]?hb(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),!c.pop()}}),has:hb(function(a){return function(b){return fb(a,b).length>0}}),contains:hb(function(a){return function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:hb(function(a){return W.test(a||"")||fb.error("unsupported lang: "+a),a=a.replace(cb,db).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return Z.test(a.nodeName)},input:function(a){return Y.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:nb(function(){return[0]}),last:nb(function(a,b){return[b-1]}),eq:nb(function(a,b,c){return[0>c?c+b:c]}),even:nb(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:nb(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:nb(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:nb(function(a,b,c){for(var d=0>c?c+b:c;++d<b;)a.push(d);return a})}},d.pseudos.nth=d.pseudos.eq;for(b in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})d.pseudos[b]=lb(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=mb(b);function pb(){}pb.prototype=d.filters=d.pseudos,d.setFilters=new pb,g=fb.tokenize=function(a,b){var c,e,f,g,h,i,j,k=z[a+" "];if(k)return b?0:k.slice(0);h=a,i=[],j=d.preFilter;while(h){(!c||(e=S.exec(h)))&&(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=T.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(R," ")}),h=h.slice(c.length));for(g in d.filter)!(e=X[g].exec(h))||j[g]&&!(e=j[g](e))||(c=e.shift(),f.push({value:c,type:g,matches:e}),h=h.slice(c.length));if(!c)break}return b?h.length:h?fb.error(a):z(a,i).slice(0)};function qb(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function rb(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=x++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[w,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(i=b[u]||(b[u]={}),(h=i[d])&&h[0]===w&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function sb(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function tb(a,b,c){for(var d=0,e=b.length;e>d;d++)fb(a,b[d],c);return c}function ub(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function vb(a,b,c,d,e,f){return d&&!d[u]&&(d=vb(d)),e&&!e[u]&&(e=vb(e,f)),hb(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||tb(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:ub(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=ub(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?K.call(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=ub(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):I.apply(g,r)})}function wb(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=rb(function(a){return a===b},h,!0),l=rb(function(a){return K.call(b,a)>-1},h,!0),m=[function(a,c,d){return!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d))}];f>i;i++)if(c=d.relative[a[i].type])m=[rb(sb(m),c)];else{if(c=d.filter[a[i].type].apply(null,a[i].matches),c[u]){for(e=++i;f>e;e++)if(d.relative[a[e].type])break;return vb(i>1&&sb(m),i>1&&qb(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(R,"$1"),c,e>i&&wb(a.slice(i,e)),f>e&&wb(a=a.slice(e)),f>e&&qb(a))}m.push(c)}return sb(m)}function xb(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,m,o,p=0,q="0",r=f&&[],s=[],t=j,u=f||e&&d.find.TAG("*",k),v=w+=null==t?1:Math.random()||.1,x=u.length;for(k&&(j=g!==n&&g);q!==x&&null!=(l=u[q]);q++){if(e&&l){m=0;while(o=a[m++])if(o(l,g,h)){i.push(l);break}k&&(w=v)}c&&((l=!o&&l)&&p--,f&&r.push(l))}if(p+=q,c&&q!==p){m=0;while(o=b[m++])o(r,s,g,h);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=G.call(i));s=ub(s)}I.apply(i,s),k&&!f&&s.length>0&&p+b.length>1&&fb.uniqueSort(i)}return k&&(w=v,j=t),r};return c?hb(f):f}return h=fb.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=wb(b[c]),f[u]?d.push(f):e.push(f);f=A(a,xb(e,d)),f.selector=a}return f},i=fb.select=function(a,b,e,f){var i,j,k,l,m,n="function"==typeof a&&a,o=!f&&g(a=n.selector||a);if(e=e||[],1===o.length){if(j=o[0]=o[0].slice(0),j.length>2&&"ID"===(k=j[0]).type&&c.getById&&9===b.nodeType&&p&&d.relative[j[1].type]){if(b=(d.find.ID(k.matches[0].replace(cb,db),b)||[])[0],!b)return e;n&&(b=b.parentNode),a=a.slice(j.shift().value.length)}i=X.needsContext.test(a)?0:j.length;while(i--){if(k=j[i],d.relative[l=k.type])break;if((m=d.find[l])&&(f=m(k.matches[0].replace(cb,db),ab.test(j[0].type)&&ob(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&qb(j),!a)return I.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,ab.test(a)&&ob(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ib(function(a){return 1&a.compareDocumentPosition(n.createElement("div"))}),ib(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||jb("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ib(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||jb("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),ib(function(a){return null==a.getAttribute("disabled")})||jb(L,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),fb}(a);m.find=s,m.expr=s.selectors,m.expr[":"]=m.expr.pseudos,m.unique=s.uniqueSort,m.text=s.getText,m.isXMLDoc=s.isXML,m.contains=s.contains;var t=m.expr.match.needsContext,u=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,v=/^.[^:#\[\.,]*$/;function w(a,b,c){if(m.isFunction(b))return m.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return m.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(v.test(b))return m.filter(b,a,c);b=m.filter(b,a)}return m.grep(a,function(a){return m.inArray(a,b)>=0!==c})}m.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?m.find.matchesSelector(d,a)?[d]:[]:m.find.matches(a,m.grep(b,function(a){return 1===a.nodeType}))},m.fn.extend({find:function(a){var b,c=[],d=this,e=d.length;if("string"!=typeof a)return this.pushStack(m(a).filter(function(){for(b=0;e>b;b++)if(m.contains(d[b],this))return!0}));for(b=0;e>b;b++)m.find(a,d[b],c);return c=this.pushStack(e>1?m.unique(c):c),c.selector=this.selector?this.selector+" "+a:a,c},filter:function(a){return this.pushStack(w(this,a||[],!1))},not:function(a){return this.pushStack(w(this,a||[],!0))},is:function(a){return!!w(this,"string"==typeof a&&t.test(a)?m(a):a||[],!1).length}});var x,y=a.document,z=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,A=m.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a.charAt(0)&&">"===a.charAt(a.length-1)&&a.length>=3?[null,a,null]:z.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||x).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof m?b[0]:b,m.merge(this,m.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:y,!0)),u.test(c[1])&&m.isPlainObject(b))for(c in b)m.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}if(d=y.getElementById(c[2]),d&&d.parentNode){if(d.id!==c[2])return x.find(a);this.length=1,this[0]=d}return this.context=y,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):m.isFunction(a)?"undefined"!=typeof x.ready?x.ready(a):a(m):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),m.makeArray(a,this))};A.prototype=m.fn,x=m(y);var B=/^(?:parents|prev(?:Until|All))/,C={children:!0,contents:!0,next:!0,prev:!0};m.extend({dir:function(a,b,c){var d=[],e=a[b];while(e&&9!==e.nodeType&&(void 0===c||1!==e.nodeType||!m(e).is(c)))1===e.nodeType&&d.push(e),e=e[b];return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),m.fn.extend({has:function(a){var b,c=m(a,this),d=c.length;return this.filter(function(){for(b=0;d>b;b++)if(m.contains(this,c[b]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=t.test(a)||"string"!=typeof a?m(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&m.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?m.unique(f):f)},index:function(a){return a?"string"==typeof a?m.inArray(this[0],m(a)):m.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(m.unique(m.merge(this.get(),m(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function D(a,b){do a=a[b];while(a&&1!==a.nodeType);return a}m.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return m.dir(a,"parentNode")},parentsUntil:function(a,b,c){return m.dir(a,"parentNode",c)},next:function(a){return D(a,"nextSibling")},prev:function(a){return D(a,"previousSibling")},nextAll:function(a){return m.dir(a,"nextSibling")},prevAll:function(a){return m.dir(a,"previousSibling")},nextUntil:function(a,b,c){return m.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return m.dir(a,"previousSibling",c)},siblings:function(a){return m.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return m.sibling(a.firstChild)},contents:function(a){return m.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:m.merge([],a.childNodes)}},function(a,b){m.fn[a]=function(c,d){var e=m.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=m.filter(d,e)),this.length>1&&(C[a]||(e=m.unique(e)),B.test(a)&&(e=e.reverse())),this.pushStack(e)}});var E=/\S+/g,F={};function G(a){var b=F[a]={};return m.each(a.match(E)||[],function(a,c){b[c]=!0}),b}m.Callbacks=function(a){a="string"==typeof a?F[a]||G(a):m.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(c=a.memory&&l,d=!0,f=g||0,g=0,e=h.length,b=!0;h&&e>f;f++)if(h[f].apply(l[0],l[1])===!1&&a.stopOnFalse){c=!1;break}b=!1,h&&(i?i.length&&j(i.shift()):c?h=[]:k.disable())},k={add:function(){if(h){var d=h.length;!function f(b){m.each(b,function(b,c){var d=m.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&f(c)})}(arguments),b?e=h.length:c&&(g=d,j(c))}return this},remove:function(){return h&&m.each(arguments,function(a,c){var d;while((d=m.inArray(c,h,d))>-1)h.splice(d,1),b&&(e>=d&&e--,f>=d&&f--)}),this},has:function(a){return a?m.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],e=0,this},disable:function(){return h=i=c=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,c||k.disable(),this},locked:function(){return!i},fireWith:function(a,c){return!h||d&&!i||(c=c||[],c=[a,c.slice?c.slice():c],b?i.push(c):j(c)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!d}};return k},m.extend({Deferred:function(a){var b=[["resolve","done",m.Callbacks("once memory"),"resolved"],["reject","fail",m.Callbacks("once memory"),"rejected"],["notify","progress",m.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return m.Deferred(function(c){m.each(b,function(b,f){var g=m.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&m.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?m.extend(a,d):d}},e={};return d.pipe=d.then,m.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&m.isFunction(a.promise)?e:0,g=1===f?a:m.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&m.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var H;m.fn.ready=function(a){return m.ready.promise().done(a),this},m.extend({isReady:!1,readyWait:1,holdReady:function(a){a?m.readyWait++:m.ready(!0)},ready:function(a){if(a===!0?!--m.readyWait:!m.isReady){if(!y.body)return setTimeout(m.ready);m.isReady=!0,a!==!0&&--m.readyWait>0||(H.resolveWith(y,[m]),m.fn.triggerHandler&&(m(y).triggerHandler("ready"),m(y).off("ready")))}}});function I(){y.addEventListener?(y.removeEventListener("DOMContentLoaded",J,!1),a.removeEventListener("load",J,!1)):(y.detachEvent("onreadystatechange",J),a.detachEvent("onload",J))}function J(){(y.addEventListener||"load"===event.type||"complete"===y.readyState)&&(I(),m.ready())}m.ready.promise=function(b){if(!H)if(H=m.Deferred(),"complete"===y.readyState)setTimeout(m.ready);else if(y.addEventListener)y.addEventListener("DOMContentLoaded",J,!1),a.addEventListener("load",J,!1);else{y.attachEvent("onreadystatechange",J),a.attachEvent("onload",J);var c=!1;try{c=null==a.frameElement&&y.documentElement}catch(d){}c&&c.doScroll&&!function e(){if(!m.isReady){try{c.doScroll("left")}catch(a){return setTimeout(e,50)}I(),m.ready()}}()}return H.promise(b)};var K="undefined",L;for(L in m(k))break;k.ownLast="0"!==L,k.inlineBlockNeedsLayout=!1,m(function(){var a,b,c,d;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(b.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1",k.inlineBlockNeedsLayout=a=3===b.offsetWidth,a&&(c.style.zoom=1)),c.removeChild(d))}),function(){var a=y.createElement("div");if(null==k.deleteExpando){k.deleteExpando=!0;try{delete a.test}catch(b){k.deleteExpando=!1}}a=null}(),m.acceptData=function(a){var b=m.noData[(a.nodeName+" ").toLowerCase()],c=+a.nodeType||1;return 1!==c&&9!==c?!1:!b||b!==!0&&a.getAttribute("classid")===b};var M=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,N=/([A-Z])/g;function O(a,b,c){if(void 0===c&&1===a.nodeType){var d="data-"+b.replace(N,"-$1").toLowerCase();if(c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:M.test(c)?m.parseJSON(c):c}catch(e){}m.data(a,b,c)}else c=void 0}return c}function P(a){var b;for(b in a)if(("data"!==b||!m.isEmptyObject(a[b]))&&"toJSON"!==b)return!1;return!0}function Q(a,b,d,e){if(m.acceptData(a)){var f,g,h=m.expando,i=a.nodeType,j=i?m.cache:a,k=i?a[h]:a[h]&&h; if(k&&j[k]&&(e||j[k].data)||void 0!==d||"string"!=typeof b)return k||(k=i?a[h]=c.pop()||m.guid++:h),j[k]||(j[k]=i?{}:{toJSON:m.noop}),("object"==typeof b||"function"==typeof b)&&(e?j[k]=m.extend(j[k],b):j[k].data=m.extend(j[k].data,b)),g=j[k],e||(g.data||(g.data={}),g=g.data),void 0!==d&&(g[m.camelCase(b)]=d),"string"==typeof b?(f=g[b],null==f&&(f=g[m.camelCase(b)])):f=g,f}}function R(a,b,c){if(m.acceptData(a)){var d,e,f=a.nodeType,g=f?m.cache:a,h=f?a[m.expando]:m.expando;if(g[h]){if(b&&(d=c?g[h]:g[h].data)){m.isArray(b)?b=b.concat(m.map(b,m.camelCase)):b in d?b=[b]:(b=m.camelCase(b),b=b in d?[b]:b.split(" ")),e=b.length;while(e--)delete d[b[e]];if(c?!P(d):!m.isEmptyObject(d))return}(c||(delete g[h].data,P(g[h])))&&(f?m.cleanData([a],!0):k.deleteExpando||g!=g.window?delete g[h]:g[h]=null)}}}m.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(a){return a=a.nodeType?m.cache[a[m.expando]]:a[m.expando],!!a&&!P(a)},data:function(a,b,c){return Q(a,b,c)},removeData:function(a,b){return R(a,b)},_data:function(a,b,c){return Q(a,b,c,!0)},_removeData:function(a,b){return R(a,b,!0)}}),m.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=m.data(f),1===f.nodeType&&!m._data(f,"parsedAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=m.camelCase(d.slice(5)),O(f,d,e[d])));m._data(f,"parsedAttrs",!0)}return e}return"object"==typeof a?this.each(function(){m.data(this,a)}):arguments.length>1?this.each(function(){m.data(this,a,b)}):f?O(f,a,m.data(f,a)):void 0},removeData:function(a){return this.each(function(){m.removeData(this,a)})}}),m.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=m._data(a,b),c&&(!d||m.isArray(c)?d=m._data(a,b,m.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=m.queue(a,b),d=c.length,e=c.shift(),f=m._queueHooks(a,b),g=function(){m.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return m._data(a,c)||m._data(a,c,{empty:m.Callbacks("once memory").add(function(){m._removeData(a,b+"queue"),m._removeData(a,c)})})}}),m.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?m.queue(this[0],a):void 0===b?this:this.each(function(){var c=m.queue(this,a,b);m._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&m.dequeue(this,a)})},dequeue:function(a){return this.each(function(){m.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=m.Deferred(),f=this,g=this.length,h=function(){--d||e.resolveWith(f,[f])};"string"!=typeof a&&(b=a,a=void 0),a=a||"fx";while(g--)c=m._data(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var S=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,T=["Top","Right","Bottom","Left"],U=function(a,b){return a=b||a,"none"===m.css(a,"display")||!m.contains(a.ownerDocument,a)},V=m.access=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===m.type(c)){e=!0;for(h in c)m.access(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,m.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(m(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},W=/^(?:checkbox|radio)$/i;!function(){var a=y.createElement("input"),b=y.createElement("div"),c=y.createDocumentFragment();if(b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",k.leadingWhitespace=3===b.firstChild.nodeType,k.tbody=!b.getElementsByTagName("tbody").length,k.htmlSerialize=!!b.getElementsByTagName("link").length,k.html5Clone="<:nav></:nav>"!==y.createElement("nav").cloneNode(!0).outerHTML,a.type="checkbox",a.checked=!0,c.appendChild(a),k.appendChecked=a.checked,b.innerHTML="<textarea>x</textarea>",k.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue,c.appendChild(b),b.innerHTML="<input type='radio' checked='checked' name='t'/>",k.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,k.noCloneEvent=!0,b.attachEvent&&(b.attachEvent("onclick",function(){k.noCloneEvent=!1}),b.cloneNode(!0).click()),null==k.deleteExpando){k.deleteExpando=!0;try{delete b.test}catch(d){k.deleteExpando=!1}}}(),function(){var b,c,d=y.createElement("div");for(b in{submit:!0,change:!0,focusin:!0})c="on"+b,(k[b+"Bubbles"]=c in a)||(d.setAttribute(c,"t"),k[b+"Bubbles"]=d.attributes[c].expando===!1);d=null}();var X=/^(?:input|select|textarea)$/i,Y=/^key/,Z=/^(?:mouse|pointer|contextmenu)|click/,$=/^(?:focusinfocus|focusoutblur)$/,_=/^([^.]*)(?:\.(.+)|)$/;function ab(){return!0}function bb(){return!1}function cb(){try{return y.activeElement}catch(a){}}m.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m._data(a);if(r){c.handler&&(i=c,c=i.handler,e=i.selector),c.guid||(c.guid=m.guid++),(g=r.events)||(g=r.events={}),(k=r.handle)||(k=r.handle=function(a){return typeof m===K||a&&m.event.triggered===a.type?void 0:m.event.dispatch.apply(k.elem,arguments)},k.elem=a),b=(b||"").match(E)||[""],h=b.length;while(h--)f=_.exec(b[h])||[],o=q=f[1],p=(f[2]||"").split(".").sort(),o&&(j=m.event.special[o]||{},o=(e?j.delegateType:j.bindType)||o,j=m.event.special[o]||{},l=m.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&m.expr.match.needsContext.test(e),namespace:p.join(".")},i),(n=g[o])||(n=g[o]=[],n.delegateCount=0,j.setup&&j.setup.call(a,d,p,k)!==!1||(a.addEventListener?a.addEventListener(o,k,!1):a.attachEvent&&a.attachEvent("on"+o,k))),j.add&&(j.add.call(a,l),l.handler.guid||(l.handler.guid=c.guid)),e?n.splice(n.delegateCount++,0,l):n.push(l),m.event.global[o]=!0);a=null}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m.hasData(a)&&m._data(a);if(r&&(k=r.events)){b=(b||"").match(E)||[""],j=b.length;while(j--)if(h=_.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=m.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,n=k[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),i=f=n.length;while(f--)g=n[f],!e&&q!==g.origType||c&&c.guid!==g.guid||h&&!h.test(g.namespace)||d&&d!==g.selector&&("**"!==d||!g.selector)||(n.splice(f,1),g.selector&&n.delegateCount--,l.remove&&l.remove.call(a,g));i&&!n.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||m.removeEvent(a,o,r.handle),delete k[o])}else for(o in k)m.event.remove(a,o+b[j],c,d,!0);m.isEmptyObject(k)&&(delete r.handle,m._removeData(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,l,n,o=[d||y],p=j.call(b,"type")?b.type:b,q=j.call(b,"namespace")?b.namespace.split("."):[];if(h=l=d=d||y,3!==d.nodeType&&8!==d.nodeType&&!$.test(p+m.event.triggered)&&(p.indexOf(".")>=0&&(q=p.split("."),p=q.shift(),q.sort()),g=p.indexOf(":")<0&&"on"+p,b=b[m.expando]?b:new m.Event(p,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=q.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+q.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:m.makeArray(c,[b]),k=m.event.special[p]||{},e||!k.trigger||k.trigger.apply(d,c)!==!1)){if(!e&&!k.noBubble&&!m.isWindow(d)){for(i=k.delegateType||p,$.test(i+p)||(h=h.parentNode);h;h=h.parentNode)o.push(h),l=h;l===(d.ownerDocument||y)&&o.push(l.defaultView||l.parentWindow||a)}n=0;while((h=o[n++])&&!b.isPropagationStopped())b.type=n>1?i:k.bindType||p,f=(m._data(h,"events")||{})[b.type]&&m._data(h,"handle"),f&&f.apply(h,c),f=g&&h[g],f&&f.apply&&m.acceptData(h)&&(b.result=f.apply(h,c),b.result===!1&&b.preventDefault());if(b.type=p,!e&&!b.isDefaultPrevented()&&(!k._default||k._default.apply(o.pop(),c)===!1)&&m.acceptData(d)&&g&&d[p]&&!m.isWindow(d)){l=d[g],l&&(d[g]=null),m.event.triggered=p;try{d[p]()}catch(r){}m.event.triggered=void 0,l&&(d[g]=l)}return b.result}},dispatch:function(a){a=m.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(m._data(this,"events")||{})[a.type]||[],k=m.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=m.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,g=0;while((e=f.handlers[g++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(e.namespace))&&(a.handleObj=e,a.data=e.data,c=((m.event.special[e.origType]||{}).handle||e.handler).apply(f.elem,i),void 0!==c&&(a.result=c)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!=this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(e=[],f=0;h>f;f++)d=b[f],c=d.selector+" ",void 0===e[c]&&(e[c]=d.needsContext?m(c,this).index(i)>=0:m.find(c,this,null,[i]).length),e[c]&&e.push(d);e.length&&g.push({elem:i,handlers:e})}return h<b.length&&g.push({elem:this,handlers:b.slice(h)}),g},fix:function(a){if(a[m.expando])return a;var b,c,d,e=a.type,f=a,g=this.fixHooks[e];g||(this.fixHooks[e]=g=Z.test(e)?this.mouseHooks:Y.test(e)?this.keyHooks:{}),d=g.props?this.props.concat(g.props):this.props,a=new m.Event(f),b=d.length;while(b--)c=d[b],a[c]=f[c];return a.target||(a.target=f.srcElement||y),3===a.target.nodeType&&(a.target=a.target.parentNode),a.metaKey=!!a.metaKey,g.filter?g.filter(a,f):a},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){return null==a.which&&(a.which=null!=b.charCode?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,b){var c,d,e,f=b.button,g=b.fromElement;return null==a.pageX&&null!=b.clientX&&(d=a.target.ownerDocument||y,e=d.documentElement,c=d.body,a.pageX=b.clientX+(e&&e.scrollLeft||c&&c.scrollLeft||0)-(e&&e.clientLeft||c&&c.clientLeft||0),a.pageY=b.clientY+(e&&e.scrollTop||c&&c.scrollTop||0)-(e&&e.clientTop||c&&c.clientTop||0)),!a.relatedTarget&&g&&(a.relatedTarget=g===a.target?b.toElement:g),a.which||void 0===f||(a.which=1&f?1:2&f?3:4&f?2:0),a}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==cb()&&this.focus)try{return this.focus(),!1}catch(a){}},delegateType:"focusin"},blur:{trigger:function(){return this===cb()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return m.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):void 0},_default:function(a){return m.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&a.originalEvent&&(a.originalEvent.returnValue=a.result)}}},simulate:function(a,b,c,d){var e=m.extend(new m.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?m.event.trigger(e,null,b):m.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},m.removeEvent=y.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){var d="on"+b;a.detachEvent&&(typeof a[d]===K&&(a[d]=null),a.detachEvent(d,c))},m.Event=function(a,b){return this instanceof m.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&a.returnValue===!1?ab:bb):this.type=a,b&&m.extend(this,b),this.timeStamp=a&&a.timeStamp||m.now(),void(this[m.expando]=!0)):new m.Event(a,b)},m.Event.prototype={isDefaultPrevented:bb,isPropagationStopped:bb,isImmediatePropagationStopped:bb,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=ab,a&&(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=ab,a&&(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){var a=this.originalEvent;this.isImmediatePropagationStopped=ab,a&&a.stopImmediatePropagation&&a.stopImmediatePropagation(),this.stopPropagation()}},m.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(a,b){m.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return(!e||e!==d&&!m.contains(d,e))&&(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),k.submitBubbles||(m.event.special.submit={setup:function(){return m.nodeName(this,"form")?!1:void m.event.add(this,"click._submit keypress._submit",function(a){var b=a.target,c=m.nodeName(b,"input")||m.nodeName(b,"button")?b.form:void 0;c&&!m._data(c,"submitBubbles")&&(m.event.add(c,"submit._submit",function(a){a._submit_bubble=!0}),m._data(c,"submitBubbles",!0))})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&m.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){return m.nodeName(this,"form")?!1:void m.event.remove(this,"._submit")}}),k.changeBubbles||(m.event.special.change={setup:function(){return X.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(m.event.add(this,"propertychange._change",function(a){"checked"===a.originalEvent.propertyName&&(this._just_changed=!0)}),m.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1),m.event.simulate("change",this,a,!0)})),!1):void m.event.add(this,"beforeactivate._change",function(a){var b=a.target;X.test(b.nodeName)&&!m._data(b,"changeBubbles")&&(m.event.add(b,"change._change",function(a){!this.parentNode||a.isSimulated||a.isTrigger||m.event.simulate("change",this.parentNode,a,!0)}),m._data(b,"changeBubbles",!0))})},handle:function(a){var b=a.target;return this!==b||a.isSimulated||a.isTrigger||"radio"!==b.type&&"checkbox"!==b.type?a.handleObj.handler.apply(this,arguments):void 0},teardown:function(){return m.event.remove(this,"._change"),!X.test(this.nodeName)}}),k.focusinBubbles||m.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){m.event.simulate(b,a.target,m.event.fix(a),!0)};m.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=m._data(d,b);e||d.addEventListener(a,c,!0),m._data(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=m._data(d,b)-1;e?m._data(d,b,e):(d.removeEventListener(a,c,!0),m._removeData(d,b))}}}),m.fn.extend({on:function(a,b,c,d,e){var f,g;if("object"==typeof a){"string"!=typeof b&&(c=c||b,b=void 0);for(f in a)this.on(f,b,c,a[f],e);return this}if(null==c&&null==d?(d=b,c=b=void 0):null==d&&("string"==typeof b?(d=c,c=void 0):(d=c,c=b,b=void 0)),d===!1)d=bb;else if(!d)return this;return 1===e&&(g=d,d=function(a){return m().off(a),g.apply(this,arguments)},d.guid=g.guid||(g.guid=m.guid++)),this.each(function(){m.event.add(this,a,d,c,b)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,b,c){var d,e;if(a&&a.preventDefault&&a.handleObj)return d=a.handleObj,m(a.delegateTarget).off(d.namespace?d.origType+"."+d.namespace:d.origType,d.selector,d.handler),this;if("object"==typeof a){for(e in a)this.off(e,b,a[e]);return this}return(b===!1||"function"==typeof b)&&(c=b,b=void 0),c===!1&&(c=bb),this.each(function(){m.event.remove(this,a,c,b)})},trigger:function(a,b){return this.each(function(){m.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?m.event.trigger(a,b,c,!0):void 0}});function db(a){var b=eb.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}var eb="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",fb=/ jQuery\d+="(?:null|\d+)"/g,gb=new RegExp("<(?:"+eb+")[\\s/>]","i"),hb=/^\s+/,ib=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,jb=/<([\w:]+)/,kb=/<tbody/i,lb=/<|&#?\w+;/,mb=/<(?:script|style|link)/i,nb=/checked\s*(?:[^=]|=\s*.checked.)/i,ob=/^$|\/(?:java|ecma)script/i,pb=/^true\/(.*)/,qb=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,rb={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:k.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},sb=db(y),tb=sb.appendChild(y.createElement("div"));rb.optgroup=rb.option,rb.tbody=rb.tfoot=rb.colgroup=rb.caption=rb.thead,rb.th=rb.td;function ub(a,b){var c,d,e=0,f=typeof a.getElementsByTagName!==K?a.getElementsByTagName(b||"*"):typeof a.querySelectorAll!==K?a.querySelectorAll(b||"*"):void 0;if(!f)for(f=[],c=a.childNodes||a;null!=(d=c[e]);e++)!b||m.nodeName(d,b)?f.push(d):m.merge(f,ub(d,b));return void 0===b||b&&m.nodeName(a,b)?m.merge([a],f):f}function vb(a){W.test(a.type)&&(a.defaultChecked=a.checked)}function wb(a,b){return m.nodeName(a,"table")&&m.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function xb(a){return a.type=(null!==m.find.attr(a,"type"))+"/"+a.type,a}function yb(a){var b=pb.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function zb(a,b){for(var c,d=0;null!=(c=a[d]);d++)m._data(c,"globalEval",!b||m._data(b[d],"globalEval"))}function Ab(a,b){if(1===b.nodeType&&m.hasData(a)){var c,d,e,f=m._data(a),g=m._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;e>d;d++)m.event.add(b,c,h[c][d])}g.data&&(g.data=m.extend({},g.data))}}function Bb(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!k.noCloneEvent&&b[m.expando]){e=m._data(b);for(d in e.events)m.removeEvent(b,d,e.handle);b.removeAttribute(m.expando)}"script"===c&&b.text!==a.text?(xb(b).text=a.text,yb(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),k.html5Clone&&a.innerHTML&&!m.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&W.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):"option"===c?b.defaultSelected=b.selected=a.defaultSelected:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}}m.extend({clone:function(a,b,c){var d,e,f,g,h,i=m.contains(a.ownerDocument,a);if(k.html5Clone||m.isXMLDoc(a)||!gb.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(tb.innerHTML=a.outerHTML,tb.removeChild(f=tb.firstChild)),!(k.noCloneEvent&&k.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||m.isXMLDoc(a)))for(d=ub(f),h=ub(a),g=0;null!=(e=h[g]);++g)d[g]&&Bb(e,d[g]);if(b)if(c)for(h=h||ub(a),d=d||ub(f),g=0;null!=(e=h[g]);g++)Ab(e,d[g]);else Ab(a,f);return d=ub(f,"script"),d.length>0&&zb(d,!i&&ub(a,"script")),d=h=e=null,f},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,l,n=a.length,o=db(b),p=[],q=0;n>q;q++)if(f=a[q],f||0===f)if("object"===m.type(f))m.merge(p,f.nodeType?[f]:f);else if(lb.test(f)){h=h||o.appendChild(b.createElement("div")),i=(jb.exec(f)||["",""])[1].toLowerCase(),l=rb[i]||rb._default,h.innerHTML=l[1]+f.replace(ib,"<$1></$2>")+l[2],e=l[0];while(e--)h=h.lastChild;if(!k.leadingWhitespace&&hb.test(f)&&p.push(b.createTextNode(hb.exec(f)[0])),!k.tbody){f="table"!==i||kb.test(f)?"<table>"!==l[1]||kb.test(f)?0:h:h.firstChild,e=f&&f.childNodes.length;while(e--)m.nodeName(j=f.childNodes[e],"tbody")&&!j.childNodes.length&&f.removeChild(j)}m.merge(p,h.childNodes),h.textContent="";while(h.firstChild)h.removeChild(h.firstChild);h=o.lastChild}else p.push(b.createTextNode(f));h&&o.removeChild(h),k.appendChecked||m.grep(ub(p,"input"),vb),q=0;while(f=p[q++])if((!d||-1===m.inArray(f,d))&&(g=m.contains(f.ownerDocument,f),h=ub(o.appendChild(f),"script"),g&&zb(h),c)){e=0;while(f=h[e++])ob.test(f.type||"")&&c.push(f)}return h=null,o},cleanData:function(a,b){for(var d,e,f,g,h=0,i=m.expando,j=m.cache,l=k.deleteExpando,n=m.event.special;null!=(d=a[h]);h++)if((b||m.acceptData(d))&&(f=d[i],g=f&&j[f])){if(g.events)for(e in g.events)n[e]?m.event.remove(d,e):m.removeEvent(d,e,g.handle);j[f]&&(delete j[f],l?delete d[i]:typeof d.removeAttribute!==K?d.removeAttribute(i):d[i]=null,c.push(f))}}}),m.fn.extend({text:function(a){return V(this,function(a){return void 0===a?m.text(this):this.empty().append((this[0]&&this[0].ownerDocument||y).createTextNode(a))},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wb(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wb(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?m.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||m.cleanData(ub(c)),c.parentNode&&(b&&m.contains(c.ownerDocument,c)&&zb(ub(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++){1===a.nodeType&&m.cleanData(ub(a,!1));while(a.firstChild)a.removeChild(a.firstChild);a.options&&m.nodeName(a,"select")&&(a.options.length=0)}return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return m.clone(this,a,b)})},html:function(a){return V(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(fb,""):void 0;if(!("string"!=typeof a||mb.test(a)||!k.htmlSerialize&&gb.test(a)||!k.leadingWhitespace&&hb.test(a)||rb[(jb.exec(a)||["",""])[1].toLowerCase()])){a=a.replace(ib,"<$1></$2>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(m.cleanData(ub(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,m.cleanData(ub(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,l=this.length,n=this,o=l-1,p=a[0],q=m.isFunction(p);if(q||l>1&&"string"==typeof p&&!k.checkClone&&nb.test(p))return this.each(function(c){var d=n.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(l&&(i=m.buildFragment(a,this[0].ownerDocument,!1,this),c=i.firstChild,1===i.childNodes.length&&(i=c),c)){for(g=m.map(ub(i,"script"),xb),f=g.length;l>j;j++)d=i,j!==o&&(d=m.clone(d,!0,!0),f&&m.merge(g,ub(d,"script"))),b.call(this[j],d,j);if(f)for(h=g[g.length-1].ownerDocument,m.map(g,yb),j=0;f>j;j++)d=g[j],ob.test(d.type||"")&&!m._data(d,"globalEval")&&m.contains(h,d)&&(d.src?m._evalUrl&&m._evalUrl(d.src):m.globalEval((d.text||d.textContent||d.innerHTML||"").replace(qb,"")));i=c=null}return this}}),m.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){m.fn[a]=function(a){for(var c,d=0,e=[],g=m(a),h=g.length-1;h>=d;d++)c=d===h?this:this.clone(!0),m(g[d])[b](c),f.apply(e,c.get());return this.pushStack(e)}});var Cb,Db={};function Eb(b,c){var d,e=m(c.createElement(b)).appendTo(c.body),f=a.getDefaultComputedStyle&&(d=a.getDefaultComputedStyle(e[0]))?d.display:m.css(e[0],"display");return e.detach(),f}function Fb(a){var b=y,c=Db[a];return c||(c=Eb(a,b),"none"!==c&&c||(Cb=(Cb||m("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=(Cb[0].contentWindow||Cb[0].contentDocument).document,b.write(),b.close(),c=Eb(a,b),Cb.detach()),Db[a]=c),c}!function(){var a;k.shrinkWrapBlocks=function(){if(null!=a)return a;a=!1;var b,c,d;return c=y.getElementsByTagName("body")[0],c&&c.style?(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(b.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:1px;width:1px;zoom:1",b.appendChild(y.createElement("div")).style.width="5px",a=3!==b.offsetWidth),c.removeChild(d),a):void 0}}();var Gb=/^margin/,Hb=new RegExp("^("+S+")(?!px)[a-z%]+$","i"),Ib,Jb,Kb=/^(top|right|bottom|left)$/;a.getComputedStyle?(Ib=function(a){return a.ownerDocument.defaultView.getComputedStyle(a,null)},Jb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ib(a),g=c?c.getPropertyValue(b)||c[b]:void 0,c&&(""!==g||m.contains(a.ownerDocument,a)||(g=m.style(a,b)),Hb.test(g)&&Gb.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f)),void 0===g?g:g+""}):y.documentElement.currentStyle&&(Ib=function(a){return a.currentStyle},Jb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ib(a),g=c?c[b]:void 0,null==g&&h&&h[b]&&(g=h[b]),Hb.test(g)&&!Kb.test(b)&&(d=h.left,e=a.runtimeStyle,f=e&&e.left,f&&(e.left=a.currentStyle.left),h.left="fontSize"===b?"1em":g,g=h.pixelLeft+"px",h.left=d,f&&(e.left=f)),void 0===g?g:g+""||"auto"});function Lb(a,b){return{get:function(){var c=a();if(null!=c)return c?void delete this.get:(this.get=b).apply(this,arguments)}}}!function(){var b,c,d,e,f,g,h;if(b=y.createElement("div"),b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",d=b.getElementsByTagName("a")[0],c=d&&d.style){c.cssText="float:left;opacity:.5",k.opacity="0.5"===c.opacity,k.cssFloat=!!c.cssFloat,b.style.backgroundClip="content-box",b.cloneNode(!0).style.backgroundClip="",k.clearCloneStyle="content-box"===b.style.backgroundClip,k.boxSizing=""===c.boxSizing||""===c.MozBoxSizing||""===c.WebkitBoxSizing,m.extend(k,{reliableHiddenOffsets:function(){return null==g&&i(),g},boxSizingReliable:function(){return null==f&&i(),f},pixelPosition:function(){return null==e&&i(),e},reliableMarginRight:function(){return null==h&&i(),h}});function i(){var b,c,d,i;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),b.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;display:block;margin-top:1%;top:1%;border:1px;padding:1px;width:4px;position:absolute",e=f=!1,h=!0,a.getComputedStyle&&(e="1%"!==(a.getComputedStyle(b,null)||{}).top,f="4px"===(a.getComputedStyle(b,null)||{width:"4px"}).width,i=b.appendChild(y.createElement("div")),i.style.cssText=b.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0",i.style.marginRight=i.style.width="0",b.style.width="1px",h=!parseFloat((a.getComputedStyle(i,null)||{}).marginRight)),b.innerHTML="<table><tr><td></td><td>t</td></tr></table>",i=b.getElementsByTagName("td"),i[0].style.cssText="margin:0;border:0;padding:0;display:none",g=0===i[0].offsetHeight,g&&(i[0].style.display="",i[1].style.display="none",g=0===i[0].offsetHeight),c.removeChild(d))}}}(),m.swap=function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e};var Mb=/alpha\([^)]*\)/i,Nb=/opacity\s*=\s*([^)]*)/,Ob=/^(none|table(?!-c[ea]).+)/,Pb=new RegExp("^("+S+")(.*)$","i"),Qb=new RegExp("^([+-])=("+S+")","i"),Rb={position:"absolute",visibility:"hidden",display:"block"},Sb={letterSpacing:"0",fontWeight:"400"},Tb=["Webkit","O","Moz","ms"];function Ub(a,b){if(b in a)return b;var c=b.charAt(0).toUpperCase()+b.slice(1),d=b,e=Tb.length;while(e--)if(b=Tb[e]+c,b in a)return b;return d}function Vb(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=m._data(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&U(d)&&(f[g]=m._data(d,"olddisplay",Fb(d.nodeName)))):(e=U(d),(c&&"none"!==c||!e)&&m._data(d,"olddisplay",e?c:m.css(d,"display"))));for(g=0;h>g;g++)d=a[g],d.style&&(b&&"none"!==d.style.display&&""!==d.style.display||(d.style.display=b?f[g]||"":"none"));return a}function Wb(a,b,c){var d=Pb.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function Xb(a,b,c,d,e){for(var f=c===(d?"border":"content")?4:"width"===b?1:0,g=0;4>f;f+=2)"margin"===c&&(g+=m.css(a,c+T[f],!0,e)),d?("content"===c&&(g-=m.css(a,"padding"+T[f],!0,e)),"margin"!==c&&(g-=m.css(a,"border"+T[f]+"Width",!0,e))):(g+=m.css(a,"padding"+T[f],!0,e),"padding"!==c&&(g+=m.css(a,"border"+T[f]+"Width",!0,e)));return g}function Yb(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=Ib(a),g=k.boxSizing&&"border-box"===m.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=Jb(a,b,f),(0>e||null==e)&&(e=a.style[b]),Hb.test(e))return e;d=g&&(k.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+Xb(a,b,c||(g?"border":"content"),d,f)+"px"}m.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=Jb(a,"opacity");return""===c?"1":c}}}},cssNumber:{columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":k.cssFloat?"cssFloat":"styleFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=m.camelCase(b),i=a.style;if(b=m.cssProps[h]||(m.cssProps[h]=Ub(i,h)),g=m.cssHooks[b]||m.cssHooks[h],void 0===c)return g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b];if(f=typeof c,"string"===f&&(e=Qb.exec(c))&&(c=(e[1]+1)*e[2]+parseFloat(m.css(a,b)),f="number"),null!=c&&c===c&&("number"!==f||m.cssNumber[h]||(c+="px"),k.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),!(g&&"set"in g&&void 0===(c=g.set(a,c,d)))))try{i[b]=c}catch(j){}}},css:function(a,b,c,d){var e,f,g,h=m.camelCase(b);return b=m.cssProps[h]||(m.cssProps[h]=Ub(a.style,h)),g=m.cssHooks[b]||m.cssHooks[h],g&&"get"in g&&(f=g.get(a,!0,c)),void 0===f&&(f=Jb(a,b,d)),"normal"===f&&b in Sb&&(f=Sb[b]),""===c||c?(e=parseFloat(f),c===!0||m.isNumeric(e)?e||0:f):f}}),m.each(["height","width"],function(a,b){m.cssHooks[b]={get:function(a,c,d){return c?Ob.test(m.css(a,"display"))&&0===a.offsetWidth?m.swap(a,Rb,function(){return Yb(a,b,d)}):Yb(a,b,d):void 0},set:function(a,c,d){var e=d&&Ib(a);return Wb(a,c,d?Xb(a,b,d,k.boxSizing&&"border-box"===m.css(a,"boxSizing",!1,e),e):0)}}}),k.opacity||(m.cssHooks.opacity={get:function(a,b){return Nb.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=m.isNumeric(b)?"alpha(opacity="+100*b+")":"",f=d&&d.filter||c.filter||"";c.zoom=1,(b>=1||""===b)&&""===m.trim(f.replace(Mb,""))&&c.removeAttribute&&(c.removeAttribute("filter"),""===b||d&&!d.filter)||(c.filter=Mb.test(f)?f.replace(Mb,e):f+" "+e)}}),m.cssHooks.marginRight=Lb(k.reliableMarginRight,function(a,b){return b?m.swap(a,{display:"inline-block"},Jb,[a,"marginRight"]):void 0}),m.each({margin:"",padding:"",border:"Width"},function(a,b){m.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+T[d]+b]=f[d]||f[d-2]||f[0];return e}},Gb.test(a)||(m.cssHooks[a+b].set=Wb)}),m.fn.extend({css:function(a,b){return V(this,function(a,b,c){var d,e,f={},g=0;if(m.isArray(b)){for(d=Ib(a),e=b.length;e>g;g++)f[b[g]]=m.css(a,b[g],!1,d);return f}return void 0!==c?m.style(a,b,c):m.css(a,b)},a,b,arguments.length>1)},show:function(){return Vb(this,!0)},hide:function(){return Vb(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){U(this)?m(this).show():m(this).hide()})}});function Zb(a,b,c,d,e){return new Zb.prototype.init(a,b,c,d,e)}m.Tween=Zb,Zb.prototype={constructor:Zb,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||"swing",this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(m.cssNumber[c]?"":"px") },cur:function(){var a=Zb.propHooks[this.prop];return a&&a.get?a.get(this):Zb.propHooks._default.get(this)},run:function(a){var b,c=Zb.propHooks[this.prop];return this.pos=b=this.options.duration?m.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):Zb.propHooks._default.set(this),this}},Zb.prototype.init.prototype=Zb.prototype,Zb.propHooks={_default:{get:function(a){var b;return null==a.elem[a.prop]||a.elem.style&&null!=a.elem.style[a.prop]?(b=m.css(a.elem,a.prop,""),b&&"auto"!==b?b:0):a.elem[a.prop]},set:function(a){m.fx.step[a.prop]?m.fx.step[a.prop](a):a.elem.style&&(null!=a.elem.style[m.cssProps[a.prop]]||m.cssHooks[a.prop])?m.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},Zb.propHooks.scrollTop=Zb.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},m.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},m.fx=Zb.prototype.init,m.fx.step={};var $b,_b,ac=/^(?:toggle|show|hide)$/,bc=new RegExp("^(?:([+-])=|)("+S+")([a-z%]*)$","i"),cc=/queueHooks$/,dc=[ic],ec={"*":[function(a,b){var c=this.createTween(a,b),d=c.cur(),e=bc.exec(b),f=e&&e[3]||(m.cssNumber[a]?"":"px"),g=(m.cssNumber[a]||"px"!==f&&+d)&&bc.exec(m.css(c.elem,a)),h=1,i=20;if(g&&g[3]!==f){f=f||g[3],e=e||[],g=+d||1;do h=h||".5",g/=h,m.style(c.elem,a,g+f);while(h!==(h=c.cur()/d)&&1!==h&&--i)}return e&&(g=c.start=+g||+d||0,c.unit=f,c.end=e[1]?g+(e[1]+1)*e[2]:+e[2]),c}]};function fc(){return setTimeout(function(){$b=void 0}),$b=m.now()}function gc(a,b){var c,d={height:a},e=0;for(b=b?1:0;4>e;e+=2-b)c=T[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function hc(a,b,c){for(var d,e=(ec[b]||[]).concat(ec["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function ic(a,b,c){var d,e,f,g,h,i,j,l,n=this,o={},p=a.style,q=a.nodeType&&U(a),r=m._data(a,"fxshow");c.queue||(h=m._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,n.always(function(){n.always(function(){h.unqueued--,m.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[p.overflow,p.overflowX,p.overflowY],j=m.css(a,"display"),l="none"===j?m._data(a,"olddisplay")||Fb(a.nodeName):j,"inline"===l&&"none"===m.css(a,"float")&&(k.inlineBlockNeedsLayout&&"inline"!==Fb(a.nodeName)?p.zoom=1:p.display="inline-block")),c.overflow&&(p.overflow="hidden",k.shrinkWrapBlocks()||n.always(function(){p.overflow=c.overflow[0],p.overflowX=c.overflow[1],p.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],ac.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(q?"hide":"show")){if("show"!==e||!r||void 0===r[d])continue;q=!0}o[d]=r&&r[d]||m.style(a,d)}else j=void 0;if(m.isEmptyObject(o))"inline"===("none"===j?Fb(a.nodeName):j)&&(p.display=j);else{r?"hidden"in r&&(q=r.hidden):r=m._data(a,"fxshow",{}),f&&(r.hidden=!q),q?m(a).show():n.done(function(){m(a).hide()}),n.done(function(){var b;m._removeData(a,"fxshow");for(b in o)m.style(a,b,o[b])});for(d in o)g=hc(q?r[d]:0,d,n),d in r||(r[d]=g.start,q&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function jc(a,b){var c,d,e,f,g;for(c in a)if(d=m.camelCase(c),e=b[d],f=a[c],m.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=m.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function kc(a,b,c){var d,e,f=0,g=dc.length,h=m.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=$b||fc(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;i>g;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),1>f&&i?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:m.extend({},b),opts:m.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:$b||fc(),duration:c.duration,tweens:[],createTween:function(b,c){var d=m.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;d>c;c++)j.tweens[c].run(1);return b?h.resolveWith(a,[j,b]):h.rejectWith(a,[j,b]),this}}),k=j.props;for(jc(k,j.opts.specialEasing);g>f;f++)if(d=dc[f].call(j,a,k,j.opts))return d;return m.map(k,hc,j),m.isFunction(j.opts.start)&&j.opts.start.call(a,j),m.fx.timer(m.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}m.Animation=m.extend(kc,{tweener:function(a,b){m.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");for(var c,d=0,e=a.length;e>d;d++)c=a[d],ec[c]=ec[c]||[],ec[c].unshift(b)},prefilter:function(a,b){b?dc.unshift(a):dc.push(a)}}),m.speed=function(a,b,c){var d=a&&"object"==typeof a?m.extend({},a):{complete:c||!c&&b||m.isFunction(a)&&a,duration:a,easing:c&&b||b&&!m.isFunction(b)&&b};return d.duration=m.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in m.fx.speeds?m.fx.speeds[d.duration]:m.fx.speeds._default,(null==d.queue||d.queue===!0)&&(d.queue="fx"),d.old=d.complete,d.complete=function(){m.isFunction(d.old)&&d.old.call(this),d.queue&&m.dequeue(this,d.queue)},d},m.fn.extend({fadeTo:function(a,b,c,d){return this.filter(U).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=m.isEmptyObject(a),f=m.speed(b,c,d),g=function(){var b=kc(this,m.extend({},a),f);(e||m._data(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=m.timers,g=m._data(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&cc.test(e)&&d(g[e]);for(e=f.length;e--;)f[e].elem!==this||null!=a&&f[e].queue!==a||(f[e].anim.stop(c),b=!1,f.splice(e,1));(b||!c)&&m.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=m._data(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=m.timers,g=d?d.length:0;for(c.finish=!0,m.queue(this,a,[]),e&&e.stop&&e.stop.call(this,!0),b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;g>b;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),m.each(["toggle","show","hide"],function(a,b){var c=m.fn[b];m.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(gc(b,!0),a,d,e)}}),m.each({slideDown:gc("show"),slideUp:gc("hide"),slideToggle:gc("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){m.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),m.timers=[],m.fx.tick=function(){var a,b=m.timers,c=0;for($b=m.now();c<b.length;c++)a=b[c],a()||b[c]!==a||b.splice(c--,1);b.length||m.fx.stop(),$b=void 0},m.fx.timer=function(a){m.timers.push(a),a()?m.fx.start():m.timers.pop()},m.fx.interval=13,m.fx.start=function(){_b||(_b=setInterval(m.fx.tick,m.fx.interval))},m.fx.stop=function(){clearInterval(_b),_b=null},m.fx.speeds={slow:600,fast:200,_default:400},m.fn.delay=function(a,b){return a=m.fx?m.fx.speeds[a]||a:a,b=b||"fx",this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},function(){var a,b,c,d,e;b=y.createElement("div"),b.setAttribute("className","t"),b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",d=b.getElementsByTagName("a")[0],c=y.createElement("select"),e=c.appendChild(y.createElement("option")),a=b.getElementsByTagName("input")[0],d.style.cssText="top:1px",k.getSetAttribute="t"!==b.className,k.style=/top/.test(d.getAttribute("style")),k.hrefNormalized="/a"===d.getAttribute("href"),k.checkOn=!!a.value,k.optSelected=e.selected,k.enctype=!!y.createElement("form").enctype,c.disabled=!0,k.optDisabled=!e.disabled,a=y.createElement("input"),a.setAttribute("value",""),k.input=""===a.getAttribute("value"),a.value="t",a.setAttribute("type","radio"),k.radioValue="t"===a.value}();var lc=/\r/g;m.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=m.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,m(this).val()):a,null==e?e="":"number"==typeof e?e+="":m.isArray(e)&&(e=m.map(e,function(a){return null==a?"":a+""})),b=m.valHooks[this.type]||m.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=m.valHooks[e.type]||m.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(lc,""):null==c?"":c)}}}),m.extend({valHooks:{option:{get:function(a){var b=m.find.attr(a,"value");return null!=b?b:m.trim(m.text(a))}},select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type||0>e,g=f?null:[],h=f?e+1:d.length,i=0>e?h:f?e:0;h>i;i++)if(c=d[i],!(!c.selected&&i!==e||(k.optDisabled?c.disabled:null!==c.getAttribute("disabled"))||c.parentNode.disabled&&m.nodeName(c.parentNode,"optgroup"))){if(b=m(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=m.makeArray(b),g=e.length;while(g--)if(d=e[g],m.inArray(m.valHooks.option.get(d),f)>=0)try{d.selected=c=!0}catch(h){d.scrollHeight}else d.selected=!1;return c||(a.selectedIndex=-1),e}}}}),m.each(["radio","checkbox"],function(){m.valHooks[this]={set:function(a,b){return m.isArray(b)?a.checked=m.inArray(m(a).val(),b)>=0:void 0}},k.checkOn||(m.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var mc,nc,oc=m.expr.attrHandle,pc=/^(?:checked|selected)$/i,qc=k.getSetAttribute,rc=k.input;m.fn.extend({attr:function(a,b){return V(this,m.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){m.removeAttr(this,a)})}}),m.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(a&&3!==f&&8!==f&&2!==f)return typeof a.getAttribute===K?m.prop(a,b,c):(1===f&&m.isXMLDoc(a)||(b=b.toLowerCase(),d=m.attrHooks[b]||(m.expr.match.bool.test(b)?nc:mc)),void 0===c?d&&"get"in d&&null!==(e=d.get(a,b))?e:(e=m.find.attr(a,b),null==e?void 0:e):null!==c?d&&"set"in d&&void 0!==(e=d.set(a,c,b))?e:(a.setAttribute(b,c+""),c):void m.removeAttr(a,b))},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(E);if(f&&1===a.nodeType)while(c=f[e++])d=m.propFix[c]||c,m.expr.match.bool.test(c)?rc&&qc||!pc.test(c)?a[d]=!1:a[m.camelCase("default-"+c)]=a[d]=!1:m.attr(a,c,""),a.removeAttribute(qc?c:d)},attrHooks:{type:{set:function(a,b){if(!k.radioValue&&"radio"===b&&m.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}}}),nc={set:function(a,b,c){return b===!1?m.removeAttr(a,c):rc&&qc||!pc.test(c)?a.setAttribute(!qc&&m.propFix[c]||c,c):a[m.camelCase("default-"+c)]=a[c]=!0,c}},m.each(m.expr.match.bool.source.match(/\w+/g),function(a,b){var c=oc[b]||m.find.attr;oc[b]=rc&&qc||!pc.test(b)?function(a,b,d){var e,f;return d||(f=oc[b],oc[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,oc[b]=f),e}:function(a,b,c){return c?void 0:a[m.camelCase("default-"+b)]?b.toLowerCase():null}}),rc&&qc||(m.attrHooks.value={set:function(a,b,c){return m.nodeName(a,"input")?void(a.defaultValue=b):mc&&mc.set(a,b,c)}}),qc||(mc={set:function(a,b,c){var d=a.getAttributeNode(c);return d||a.setAttributeNode(d=a.ownerDocument.createAttribute(c)),d.value=b+="","value"===c||b===a.getAttribute(c)?b:void 0}},oc.id=oc.name=oc.coords=function(a,b,c){var d;return c?void 0:(d=a.getAttributeNode(b))&&""!==d.value?d.value:null},m.valHooks.button={get:function(a,b){var c=a.getAttributeNode(b);return c&&c.specified?c.value:void 0},set:mc.set},m.attrHooks.contenteditable={set:function(a,b,c){mc.set(a,""===b?!1:b,c)}},m.each(["width","height"],function(a,b){m.attrHooks[b]={set:function(a,c){return""===c?(a.setAttribute(b,"auto"),c):void 0}}})),k.style||(m.attrHooks.style={get:function(a){return a.style.cssText||void 0},set:function(a,b){return a.style.cssText=b+""}});var sc=/^(?:input|select|textarea|button|object)$/i,tc=/^(?:a|area)$/i;m.fn.extend({prop:function(a,b){return V(this,m.prop,a,b,arguments.length>1)},removeProp:function(a){return a=m.propFix[a]||a,this.each(function(){try{this[a]=void 0,delete this[a]}catch(b){}})}}),m.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(a,b,c){var d,e,f,g=a.nodeType;if(a&&3!==g&&8!==g&&2!==g)return f=1!==g||!m.isXMLDoc(a),f&&(b=m.propFix[b]||b,e=m.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){var b=m.find.attr(a,"tabindex");return b?parseInt(b,10):sc.test(a.nodeName)||tc.test(a.nodeName)&&a.href?0:-1}}}}),k.hrefNormalized||m.each(["href","src"],function(a,b){m.propHooks[b]={get:function(a){return a.getAttribute(b,4)}}}),k.optSelected||(m.propHooks.selected={get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null}}),m.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){m.propFix[this.toLowerCase()]=this}),k.enctype||(m.propFix.enctype="encoding");var uc=/[\t\r\n\f]/g;m.fn.extend({addClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j="string"==typeof a&&a;if(m.isFunction(a))return this.each(function(b){m(this).addClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(E)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(uc," "):" ")){f=0;while(e=b[f++])d.indexOf(" "+e+" ")<0&&(d+=e+" ");g=m.trim(d),c.className!==g&&(c.className=g)}return this},removeClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j=0===arguments.length||"string"==typeof a&&a;if(m.isFunction(a))return this.each(function(b){m(this).removeClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(E)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(uc," "):"")){f=0;while(e=b[f++])while(d.indexOf(" "+e+" ")>=0)d=d.replace(" "+e+" "," ");g=a?m.trim(d):"",c.className!==g&&(c.className=g)}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):this.each(m.isFunction(a)?function(c){m(this).toggleClass(a.call(this,c,this.className,b),b)}:function(){if("string"===c){var b,d=0,e=m(this),f=a.match(E)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else(c===K||"boolean"===c)&&(this.className&&m._data(this,"__className__",this.className),this.className=this.className||a===!1?"":m._data(this,"__className__")||"")})},hasClass:function(a){for(var b=" "+a+" ",c=0,d=this.length;d>c;c++)if(1===this[c].nodeType&&(" "+this[c].className+" ").replace(uc," ").indexOf(b)>=0)return!0;return!1}}),m.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){m.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),m.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)}});var vc=m.now(),wc=/\?/,xc=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;m.parseJSON=function(b){if(a.JSON&&a.JSON.parse)return a.JSON.parse(b+"");var c,d=null,e=m.trim(b+"");return e&&!m.trim(e.replace(xc,function(a,b,e,f){return c&&b&&(d=0),0===d?a:(c=e||b,d+=!f-!e,"")}))?Function("return "+e)():m.error("Invalid JSON: "+b)},m.parseXML=function(b){var c,d;if(!b||"string"!=typeof b)return null;try{a.DOMParser?(d=new DOMParser,c=d.parseFromString(b,"text/xml")):(c=new ActiveXObject("Microsoft.XMLDOM"),c.async="false",c.loadXML(b))}catch(e){c=void 0}return c&&c.documentElement&&!c.getElementsByTagName("parsererror").length||m.error("Invalid XML: "+b),c};var yc,zc,Ac=/#.*$/,Bc=/([?&])_=[^&]*/,Cc=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Dc=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Ec=/^(?:GET|HEAD)$/,Fc=/^\/\//,Gc=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,Hc={},Ic={},Jc="*/".concat("*");try{zc=location.href}catch(Kc){zc=y.createElement("a"),zc.href="",zc=zc.href}yc=Gc.exec(zc.toLowerCase())||[];function Lc(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(E)||[];if(m.isFunction(c))while(d=f[e++])"+"===d.charAt(0)?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function Mc(a,b,c,d){var e={},f=a===Ic;function g(h){var i;return e[h]=!0,m.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function Nc(a,b){var c,d,e=m.ajaxSettings.flatOptions||{};for(d in b)void 0!==b[d]&&((e[d]?a:c||(c={}))[d]=b[d]);return c&&m.extend(!0,a,c),a}function Oc(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===e&&(e=a.mimeType||b.getResponseHeader("Content-Type"));if(e)for(g in h)if(h[g]&&h[g].test(e)){i.unshift(g);break}if(i[0]in c)f=i[0];else{for(g in c){if(!i[0]||a.converters[g+" "+i[0]]){f=g;break}d||(d=g)}f=f||d}return f?(f!==i[0]&&i.unshift(f),c[f]):void 0}function Pc(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}m.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:zc,type:"GET",isLocal:Dc.test(yc[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Jc,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":m.parseJSON,"text xml":m.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?Nc(Nc(a,m.ajaxSettings),b):Nc(m.ajaxSettings,a)},ajaxPrefilter:Lc(Hc),ajaxTransport:Lc(Ic),ajax:function(a,b){"object"==typeof a&&(b=a,a=void 0),b=b||{};var c,d,e,f,g,h,i,j,k=m.ajaxSetup({},b),l=k.context||k,n=k.context&&(l.nodeType||l.jquery)?m(l):m.event,o=m.Deferred(),p=m.Callbacks("once memory"),q=k.statusCode||{},r={},s={},t=0,u="canceled",v={readyState:0,getResponseHeader:function(a){var b;if(2===t){if(!j){j={};while(b=Cc.exec(f))j[b[1].toLowerCase()]=b[2]}b=j[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return 2===t?f:null},setRequestHeader:function(a,b){var c=a.toLowerCase();return t||(a=s[c]=s[c]||a,r[a]=b),this},overrideMimeType:function(a){return t||(k.mimeType=a),this},statusCode:function(a){var b;if(a)if(2>t)for(b in a)q[b]=[q[b],a[b]];else v.always(a[v.status]);return this},abort:function(a){var b=a||u;return i&&i.abort(b),x(0,b),this}};if(o.promise(v).complete=p.add,v.success=v.done,v.error=v.fail,k.url=((a||k.url||zc)+"").replace(Ac,"").replace(Fc,yc[1]+"//"),k.type=b.method||b.type||k.method||k.type,k.dataTypes=m.trim(k.dataType||"*").toLowerCase().match(E)||[""],null==k.crossDomain&&(c=Gc.exec(k.url.toLowerCase()),k.crossDomain=!(!c||c[1]===yc[1]&&c[2]===yc[2]&&(c[3]||("http:"===c[1]?"80":"443"))===(yc[3]||("http:"===yc[1]?"80":"443")))),k.data&&k.processData&&"string"!=typeof k.data&&(k.data=m.param(k.data,k.traditional)),Mc(Hc,k,b,v),2===t)return v;h=k.global,h&&0===m.active++&&m.event.trigger("ajaxStart"),k.type=k.type.toUpperCase(),k.hasContent=!Ec.test(k.type),e=k.url,k.hasContent||(k.data&&(e=k.url+=(wc.test(e)?"&":"?")+k.data,delete k.data),k.cache===!1&&(k.url=Bc.test(e)?e.replace(Bc,"$1_="+vc++):e+(wc.test(e)?"&":"?")+"_="+vc++)),k.ifModified&&(m.lastModified[e]&&v.setRequestHeader("If-Modified-Since",m.lastModified[e]),m.etag[e]&&v.setRequestHeader("If-None-Match",m.etag[e])),(k.data&&k.hasContent&&k.contentType!==!1||b.contentType)&&v.setRequestHeader("Content-Type",k.contentType),v.setRequestHeader("Accept",k.dataTypes[0]&&k.accepts[k.dataTypes[0]]?k.accepts[k.dataTypes[0]]+("*"!==k.dataTypes[0]?", "+Jc+"; q=0.01":""):k.accepts["*"]);for(d in k.headers)v.setRequestHeader(d,k.headers[d]);if(k.beforeSend&&(k.beforeSend.call(l,v,k)===!1||2===t))return v.abort();u="abort";for(d in{success:1,error:1,complete:1})v[d](k[d]);if(i=Mc(Ic,k,b,v)){v.readyState=1,h&&n.trigger("ajaxSend",[v,k]),k.async&&k.timeout>0&&(g=setTimeout(function(){v.abort("timeout")},k.timeout));try{t=1,i.send(r,x)}catch(w){if(!(2>t))throw w;x(-1,w)}}else x(-1,"No Transport");function x(a,b,c,d){var j,r,s,u,w,x=b;2!==t&&(t=2,g&&clearTimeout(g),i=void 0,f=d||"",v.readyState=a>0?4:0,j=a>=200&&300>a||304===a,c&&(u=Oc(k,v,c)),u=Pc(k,u,v,j),j?(k.ifModified&&(w=v.getResponseHeader("Last-Modified"),w&&(m.lastModified[e]=w),w=v.getResponseHeader("etag"),w&&(m.etag[e]=w)),204===a||"HEAD"===k.type?x="nocontent":304===a?x="notmodified":(x=u.state,r=u.data,s=u.error,j=!s)):(s=x,(a||!x)&&(x="error",0>a&&(a=0))),v.status=a,v.statusText=(b||x)+"",j?o.resolveWith(l,[r,x,v]):o.rejectWith(l,[v,x,s]),v.statusCode(q),q=void 0,h&&n.trigger(j?"ajaxSuccess":"ajaxError",[v,k,j?r:s]),p.fireWith(l,[v,x]),h&&(n.trigger("ajaxComplete",[v,k]),--m.active||m.event.trigger("ajaxStop")))}return v},getJSON:function(a,b,c){return m.get(a,b,c,"json")},getScript:function(a,b){return m.get(a,void 0,b,"script")}}),m.each(["get","post"],function(a,b){m[b]=function(a,c,d,e){return m.isFunction(c)&&(e=e||d,d=c,c=void 0),m.ajax({url:a,type:b,dataType:e,data:c,success:d})}}),m.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){m.fn[b]=function(a){return this.on(b,a)}}),m._evalUrl=function(a){return m.ajax({url:a,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},m.fn.extend({wrapAll:function(a){if(m.isFunction(a))return this.each(function(b){m(this).wrapAll(a.call(this,b))});if(this[0]){var b=m(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&1===a.firstChild.nodeType)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){return this.each(m.isFunction(a)?function(b){m(this).wrapInner(a.call(this,b))}:function(){var b=m(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=m.isFunction(a);return this.each(function(c){m(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){m.nodeName(this,"body")||m(this).replaceWith(this.childNodes)}).end()}}),m.expr.filters.hidden=function(a){return a.offsetWidth<=0&&a.offsetHeight<=0||!k.reliableHiddenOffsets()&&"none"===(a.style&&a.style.display||m.css(a,"display"))},m.expr.filters.visible=function(a){return!m.expr.filters.hidden(a)};var Qc=/%20/g,Rc=/\[\]$/,Sc=/\r?\n/g,Tc=/^(?:submit|button|image|reset|file)$/i,Uc=/^(?:input|select|textarea|keygen)/i;function Vc(a,b,c,d){var e;if(m.isArray(b))m.each(b,function(b,e){c||Rc.test(a)?d(a,e):Vc(a+"["+("object"==typeof e?b:"")+"]",e,c,d)});else if(c||"object"!==m.type(b))d(a,b);else for(e in b)Vc(a+"["+e+"]",b[e],c,d)}m.param=function(a,b){var c,d=[],e=function(a,b){b=m.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=m.ajaxSettings&&m.ajaxSettings.traditional),m.isArray(a)||a.jquery&&!m.isPlainObject(a))m.each(a,function(){e(this.name,this.value)});else for(c in a)Vc(c,a[c],b,e);return d.join("&").replace(Qc,"+")},m.fn.extend({serialize:function(){return m.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=m.prop(this,"elements");return a?m.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!m(this).is(":disabled")&&Uc.test(this.nodeName)&&!Tc.test(a)&&(this.checked||!W.test(a))}).map(function(a,b){var c=m(this).val();return null==c?null:m.isArray(c)?m.map(c,function(a){return{name:b.name,value:a.replace(Sc,"\r\n")}}):{name:b.name,value:c.replace(Sc,"\r\n")}}).get()}}),m.ajaxSettings.xhr=void 0!==a.ActiveXObject?function(){return!this.isLocal&&/^(get|post|head|put|delete|options)$/i.test(this.type)&&Zc()||$c()}:Zc;var Wc=0,Xc={},Yc=m.ajaxSettings.xhr();a.ActiveXObject&&m(a).on("unload",function(){for(var a in Xc)Xc[a](void 0,!0)}),k.cors=!!Yc&&"withCredentials"in Yc,Yc=k.ajax=!!Yc,Yc&&m.ajaxTransport(function(a){if(!a.crossDomain||k.cors){var b;return{send:function(c,d){var e,f=a.xhr(),g=++Wc;if(f.open(a.type,a.url,a.async,a.username,a.password),a.xhrFields)for(e in a.xhrFields)f[e]=a.xhrFields[e];a.mimeType&&f.overrideMimeType&&f.overrideMimeType(a.mimeType),a.crossDomain||c["X-Requested-With"]||(c["X-Requested-With"]="XMLHttpRequest");for(e in c)void 0!==c[e]&&f.setRequestHeader(e,c[e]+"");f.send(a.hasContent&&a.data||null),b=function(c,e){var h,i,j;if(b&&(e||4===f.readyState))if(delete Xc[g],b=void 0,f.onreadystatechange=m.noop,e)4!==f.readyState&&f.abort();else{j={},h=f.status,"string"==typeof f.responseText&&(j.text=f.responseText);try{i=f.statusText}catch(k){i=""}h||!a.isLocal||a.crossDomain?1223===h&&(h=204):h=j.text?200:404}j&&d(h,i,j,f.getAllResponseHeaders())},a.async?4===f.readyState?setTimeout(b):f.onreadystatechange=Xc[g]=b:b()},abort:function(){b&&b(void 0,!0)}}}});function Zc(){try{return new a.XMLHttpRequest}catch(b){}}function $c(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}m.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(a){return m.globalEval(a),a}}}),m.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),m.ajaxTransport("script",function(a){if(a.crossDomain){var b,c=y.head||m("head")[0]||y.documentElement;return{send:function(d,e){b=y.createElement("script"),b.async=!0,a.scriptCharset&&(b.charset=a.scriptCharset),b.src=a.url,b.onload=b.onreadystatechange=function(a,c){(c||!b.readyState||/loaded|complete/.test(b.readyState))&&(b.onload=b.onreadystatechange=null,b.parentNode&&b.parentNode.removeChild(b),b=null,c||e(200,"success"))},c.insertBefore(b,c.firstChild)},abort:function(){b&&b.onload(void 0,!0)}}}});var _c=[],ad=/(=)\?(?=&|$)|\?\?/;m.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=_c.pop()||m.expando+"_"+vc++;return this[a]=!0,a}}),m.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(ad.test(b.url)?"url":"string"==typeof b.data&&!(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&ad.test(b.data)&&"data");return h||"jsonp"===b.dataTypes[0]?(e=b.jsonpCallback=m.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(ad,"$1"+e):b.jsonp!==!1&&(b.url+=(wc.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||m.error(e+" was not called"),g[0]},b.dataTypes[0]="json",f=a[e],a[e]=function(){g=arguments},d.always(function(){a[e]=f,b[e]&&(b.jsonpCallback=c.jsonpCallback,_c.push(e)),g&&m.isFunction(f)&&f(g[0]),g=f=void 0}),"script"):void 0}),m.parseHTML=function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1),b=b||y;var d=u.exec(a),e=!c&&[];return d?[b.createElement(d[1])]:(d=m.buildFragment([a],b,e),e&&e.length&&m(e).remove(),m.merge([],d.childNodes))};var bd=m.fn.load;m.fn.load=function(a,b,c){if("string"!=typeof a&&bd)return bd.apply(this,arguments);var d,e,f,g=this,h=a.indexOf(" ");return h>=0&&(d=m.trim(a.slice(h,a.length)),a=a.slice(0,h)),m.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(f="POST"),g.length>0&&m.ajax({url:a,type:f,dataType:"html",data:b}).done(function(a){e=arguments,g.html(d?m("<div>").append(m.parseHTML(a)).find(d):a)}).complete(c&&function(a,b){g.each(c,e||[a.responseText,b,a])}),this},m.expr.filters.animated=function(a){return m.grep(m.timers,function(b){return a===b.elem}).length};var cd=a.document.documentElement;function dd(a){return m.isWindow(a)?a:9===a.nodeType?a.defaultView||a.parentWindow:!1}m.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=m.css(a,"position"),l=m(a),n={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=m.css(a,"top"),i=m.css(a,"left"),j=("absolute"===k||"fixed"===k)&&m.inArray("auto",[f,i])>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),m.isFunction(b)&&(b=b.call(a,c,h)),null!=b.top&&(n.top=b.top-h.top+g),null!=b.left&&(n.left=b.left-h.left+e),"using"in b?b.using.call(a,n):l.css(n)}},m.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){m.offset.setOffset(this,a,b)});var b,c,d={top:0,left:0},e=this[0],f=e&&e.ownerDocument;if(f)return b=f.documentElement,m.contains(b,e)?(typeof e.getBoundingClientRect!==K&&(d=e.getBoundingClientRect()),c=dd(f),{top:d.top+(c.pageYOffset||b.scrollTop)-(b.clientTop||0),left:d.left+(c.pageXOffset||b.scrollLeft)-(b.clientLeft||0)}):d},position:function(){if(this[0]){var a,b,c={top:0,left:0},d=this[0];return"fixed"===m.css(d,"position")?b=d.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),m.nodeName(a[0],"html")||(c=a.offset()),c.top+=m.css(a[0],"borderTopWidth",!0),c.left+=m.css(a[0],"borderLeftWidth",!0)),{top:b.top-c.top-m.css(d,"marginTop",!0),left:b.left-c.left-m.css(d,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||cd;while(a&&!m.nodeName(a,"html")&&"static"===m.css(a,"position"))a=a.offsetParent;return a||cd})}}),m.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,b){var c=/Y/.test(b);m.fn[a]=function(d){return V(this,function(a,d,e){var f=dd(a);return void 0===e?f?b in f?f[b]:f.document.documentElement[d]:a[d]:void(f?f.scrollTo(c?m(f).scrollLeft():e,c?e:m(f).scrollTop()):a[d]=e)},a,d,arguments.length,null)}}),m.each(["top","left"],function(a,b){m.cssHooks[b]=Lb(k.pixelPosition,function(a,c){return c?(c=Jb(a,b),Hb.test(c)?m(a).position()[b]+"px":c):void 0})}),m.each({Height:"height",Width:"width"},function(a,b){m.each({padding:"inner"+a,content:b,"":"outer"+a},function(c,d){m.fn[d]=function(d,e){var f=arguments.length&&(c||"boolean"!=typeof d),g=c||(d===!0||e===!0?"margin":"border");return V(this,function(b,c,d){var e;return m.isWindow(b)?b.document.documentElement["client"+a]:9===b.nodeType?(e=b.documentElement,Math.max(b.body["scroll"+a],e["scroll"+a],b.body["offset"+a],e["offset"+a],e["client"+a])):void 0===d?m.css(b,c,g):m.style(b,c,d,g)},b,f?d:void 0,f,null)}})}),m.fn.size=function(){return this.length},m.fn.andSelf=m.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return m});var ed=a.jQuery,fd=a.$;return m.noConflict=function(b){return a.$===m&&(a.$=fd),b&&a.jQuery===m&&(a.jQuery=ed),m},typeof b===K&&(a.jQuery=a.$=m),m});
ajax/libs/vue/2.5.1/vue.esm.js
sufuf3/cdnjs
/*! * Vue.js v2.5.1 * (c) 2014-2017 Evan You * Released under the MIT License. */ /* */ // these helpers produces better vm code in JS engines due to their // explicitness and function inlining function isUndef (v) { return v === undefined || v === null } function isDef (v) { return v !== undefined && v !== null } function isTrue (v) { return v === true } function isFalse (v) { return v === false } /** * Check if value is primitive */ function isPrimitive (value) { return ( typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean' ) } /** * Quick object check - this is primarily used to tell * Objects from primitive values when we know the value * is a JSON-compliant type. */ function isObject (obj) { return obj !== null && typeof obj === 'object' } /** * Get the raw type string of a value e.g. [object Object] */ var _toString = Object.prototype.toString; function toRawType (value) { return _toString.call(value).slice(8, -1) } /** * Strict object type check. Only returns true * for plain JavaScript objects. */ function isPlainObject (obj) { return _toString.call(obj) === '[object Object]' } function isRegExp (v) { return _toString.call(v) === '[object RegExp]' } /** * Check if val is a valid array index. */ function isValidArrayIndex (val) { var n = parseFloat(String(val)); return n >= 0 && Math.floor(n) === n && isFinite(val) } /** * Convert a value to a string that is actually rendered. */ function toString (val) { return val == null ? '' : typeof val === 'object' ? JSON.stringify(val, null, 2) : String(val) } /** * Convert a input value to a number for persistence. * If the conversion fails, return original string. */ function toNumber (val) { var n = parseFloat(val); return isNaN(n) ? val : n } /** * Make a map and return a function for checking if a key * is in that map. */ function makeMap ( str, expectsLowerCase ) { var map = Object.create(null); var list = str.split(','); for (var i = 0; i < list.length; i++) { map[list[i]] = true; } return expectsLowerCase ? function (val) { return map[val.toLowerCase()]; } : function (val) { return map[val]; } } /** * Check if a tag is a built-in tag. */ var isBuiltInTag = makeMap('slot,component', true); /** * Check if a attribute is a reserved attribute. */ var isReservedAttribute = makeMap('key,ref,slot,slot-scope,is'); /** * Remove an item from an array */ function remove (arr, item) { if (arr.length) { var index = arr.indexOf(item); if (index > -1) { return arr.splice(index, 1) } } } /** * Check whether the object has the property. */ var hasOwnProperty = Object.prototype.hasOwnProperty; function hasOwn (obj, key) { return hasOwnProperty.call(obj, key) } /** * Create a cached version of a pure function. */ function cached (fn) { var cache = Object.create(null); return (function cachedFn (str) { var hit = cache[str]; return hit || (cache[str] = fn(str)) }) } /** * Camelize a hyphen-delimited string. */ var camelizeRE = /-(\w)/g; var camelize = cached(function (str) { return str.replace(camelizeRE, function (_, c) { return c ? c.toUpperCase() : ''; }) }); /** * Capitalize a string. */ var capitalize = cached(function (str) { return str.charAt(0).toUpperCase() + str.slice(1) }); /** * Hyphenate a camelCase string. */ var hyphenateRE = /\B([A-Z])/g; var hyphenate = cached(function (str) { return str.replace(hyphenateRE, '-$1').toLowerCase() }); /** * Simple bind, faster than native */ function bind (fn, ctx) { function boundFn (a) { var l = arguments.length; return l ? l > 1 ? fn.apply(ctx, arguments) : fn.call(ctx, a) : fn.call(ctx) } // record original fn length boundFn._length = fn.length; return boundFn } /** * Convert an Array-like object to a real Array. */ function toArray (list, start) { start = start || 0; var i = list.length - start; var ret = new Array(i); while (i--) { ret[i] = list[i + start]; } return ret } /** * Mix properties into target object. */ function extend (to, _from) { for (var key in _from) { to[key] = _from[key]; } return to } /** * Merge an Array of Objects into a single Object. */ function toObject (arr) { var res = {}; for (var i = 0; i < arr.length; i++) { if (arr[i]) { extend(res, arr[i]); } } return res } /** * Perform no operation. * Stubbing args to make Flow happy without leaving useless transpiled code * with ...rest (https://flow.org/blog/2017/05/07/Strict-Function-Call-Arity/) */ function noop (a, b, c) {} /** * Always return false. */ var no = function (a, b, c) { return false; }; /** * Return same value */ var identity = function (_) { return _; }; /** * Generate a static keys string from compiler modules. */ function genStaticKeys (modules) { return modules.reduce(function (keys, m) { return keys.concat(m.staticKeys || []) }, []).join(',') } /** * Check if two values are loosely equal - that is, * if they are plain objects, do they have the same shape? */ function looseEqual (a, b) { if (a === b) { return true } var isObjectA = isObject(a); var isObjectB = isObject(b); if (isObjectA && isObjectB) { try { var isArrayA = Array.isArray(a); var isArrayB = Array.isArray(b); if (isArrayA && isArrayB) { return a.length === b.length && a.every(function (e, i) { return looseEqual(e, b[i]) }) } else if (!isArrayA && !isArrayB) { var keysA = Object.keys(a); var keysB = Object.keys(b); return keysA.length === keysB.length && keysA.every(function (key) { return looseEqual(a[key], b[key]) }) } else { /* istanbul ignore next */ return false } } catch (e) { /* istanbul ignore next */ return false } } else if (!isObjectA && !isObjectB) { return String(a) === String(b) } else { return false } } function looseIndexOf (arr, val) { for (var i = 0; i < arr.length; i++) { if (looseEqual(arr[i], val)) { return i } } return -1 } /** * Ensure a function is called only once. */ function once (fn) { var called = false; return function () { if (!called) { called = true; fn.apply(this, arguments); } } } var SSR_ATTR = 'data-server-rendered'; var ASSET_TYPES = [ 'component', 'directive', 'filter' ]; var LIFECYCLE_HOOKS = [ 'beforeCreate', 'created', 'beforeMount', 'mounted', 'beforeUpdate', 'updated', 'beforeDestroy', 'destroyed', 'activated', 'deactivated', 'errorCaptured' ]; /* */ var config = ({ /** * Option merge strategies (used in core/util/options) */ optionMergeStrategies: Object.create(null), /** * Whether to suppress warnings. */ silent: false, /** * Show production mode tip message on boot? */ productionTip: process.env.NODE_ENV !== 'production', /** * Whether to enable devtools */ devtools: process.env.NODE_ENV !== 'production', /** * Whether to record perf */ performance: false, /** * Error handler for watcher errors */ errorHandler: null, /** * Warn handler for watcher warns */ warnHandler: null, /** * Ignore certain custom elements */ ignoredElements: [], /** * Custom user key aliases for v-on */ keyCodes: Object.create(null), /** * Check if a tag is reserved so that it cannot be registered as a * component. This is platform-dependent and may be overwritten. */ isReservedTag: no, /** * Check if an attribute is reserved so that it cannot be used as a component * prop. This is platform-dependent and may be overwritten. */ isReservedAttr: no, /** * Check if a tag is an unknown element. * Platform-dependent. */ isUnknownElement: no, /** * Get the namespace of an element */ getTagNamespace: noop, /** * Parse the real tag name for the specific platform. */ parsePlatformTagName: identity, /** * Check if an attribute must be bound using property, e.g. value * Platform-dependent. */ mustUseProp: no, /** * Exposed for legacy reasons */ _lifecycleHooks: LIFECYCLE_HOOKS }); /* */ var emptyObject = Object.freeze({}); /** * Check if a string starts with $ or _ */ function isReserved (str) { var c = (str + '').charCodeAt(0); return c === 0x24 || c === 0x5F } /** * Define a property. */ function def (obj, key, val, enumerable) { Object.defineProperty(obj, key, { value: val, enumerable: !!enumerable, writable: true, configurable: true }); } /** * Parse simple path. */ var bailRE = /[^\w.$]/; function parsePath (path) { if (bailRE.test(path)) { return } var segments = path.split('.'); return function (obj) { for (var i = 0; i < segments.length; i++) { if (!obj) { return } obj = obj[segments[i]]; } return obj } } /* */ var warn = noop; var tip = noop; var generateComponentTrace = (noop); // work around flow check var formatComponentName = (noop); if (process.env.NODE_ENV !== 'production') { var hasConsole = typeof console !== 'undefined'; var classifyRE = /(?:^|[-_])(\w)/g; var classify = function (str) { return str .replace(classifyRE, function (c) { return c.toUpperCase(); }) .replace(/[-_]/g, ''); }; warn = function (msg, vm) { var trace = vm ? generateComponentTrace(vm) : ''; if (config.warnHandler) { config.warnHandler.call(null, msg, vm, trace); } else if (hasConsole && (!config.silent)) { console.error(("[Vue warn]: " + msg + trace)); } }; tip = function (msg, vm) { if (hasConsole && (!config.silent)) { console.warn("[Vue tip]: " + msg + ( vm ? generateComponentTrace(vm) : '' )); } }; formatComponentName = function (vm, includeFile) { if (vm.$root === vm) { return '<Root>' } var options = typeof vm === 'function' && vm.cid != null ? vm.options : vm._isVue ? vm.$options || vm.constructor.options : vm || {}; var name = options.name || options._componentTag; var file = options.__file; if (!name && file) { var match = file.match(/([^/\\]+)\.vue$/); name = match && match[1]; } return ( (name ? ("<" + (classify(name)) + ">") : "<Anonymous>") + (file && includeFile !== false ? (" at " + file) : '') ) }; var repeat = function (str, n) { var res = ''; while (n) { if (n % 2 === 1) { res += str; } if (n > 1) { str += str; } n >>= 1; } return res }; generateComponentTrace = function (vm) { if (vm._isVue && vm.$parent) { var tree = []; var currentRecursiveSequence = 0; while (vm) { if (tree.length > 0) { var last = tree[tree.length - 1]; if (last.constructor === vm.constructor) { currentRecursiveSequence++; vm = vm.$parent; continue } else if (currentRecursiveSequence > 0) { tree[tree.length - 1] = [last, currentRecursiveSequence]; currentRecursiveSequence = 0; } } tree.push(vm); vm = vm.$parent; } return '\n\nfound in\n\n' + tree .map(function (vm, i) { return ("" + (i === 0 ? '---> ' : repeat(' ', 5 + i * 2)) + (Array.isArray(vm) ? ((formatComponentName(vm[0])) + "... (" + (vm[1]) + " recursive calls)") : formatComponentName(vm))); }) .join('\n') } else { return ("\n\n(found in " + (formatComponentName(vm)) + ")") } }; } /* */ function handleError (err, vm, info) { if (vm) { var cur = vm; while ((cur = cur.$parent)) { var hooks = cur.$options.errorCaptured; if (hooks) { for (var i = 0; i < hooks.length; i++) { try { var capture = hooks[i].call(cur, err, vm, info) === false; if (capture) { return } } catch (e) { globalHandleError(e, cur, 'errorCaptured hook'); } } } } } globalHandleError(err, vm, info); } function globalHandleError (err, vm, info) { if (config.errorHandler) { try { return config.errorHandler.call(null, err, vm, info) } catch (e) { logError(e, null, 'config.errorHandler'); } } logError(err, vm, info); } function logError (err, vm, info) { if (process.env.NODE_ENV !== 'production') { warn(("Error in " + info + ": \"" + (err.toString()) + "\""), vm); } /* istanbul ignore else */ if (inBrowser && typeof console !== 'undefined') { console.error(err); } else { throw err } } /* */ /* globals MessageChannel */ // can we use __proto__? var hasProto = '__proto__' in {}; // Browser environment sniffing var inBrowser = typeof window !== 'undefined'; var UA = inBrowser && window.navigator.userAgent.toLowerCase(); var isIE = UA && /msie|trident/.test(UA); var isIE9 = UA && UA.indexOf('msie 9.0') > 0; var isEdge = UA && UA.indexOf('edge/') > 0; var isAndroid = UA && UA.indexOf('android') > 0; var isIOS = UA && /iphone|ipad|ipod|ios/.test(UA); var isChrome = UA && /chrome\/\d+/.test(UA) && !isEdge; // Firefox has a "watch" function on Object.prototype... var nativeWatch = ({}).watch; var supportsPassive = false; if (inBrowser) { try { var opts = {}; Object.defineProperty(opts, 'passive', ({ get: function get () { /* istanbul ignore next */ supportsPassive = true; } })); // https://github.com/facebook/flow/issues/285 window.addEventListener('test-passive', null, opts); } catch (e) {} } // this needs to be lazy-evaled because vue may be required before // vue-server-renderer can set VUE_ENV var _isServer; var isServerRendering = function () { if (_isServer === undefined) { /* istanbul ignore if */ if (!inBrowser && typeof global !== 'undefined') { // detect presence of vue-server-renderer and avoid // Webpack shimming the process _isServer = global['process'].env.VUE_ENV === 'server'; } else { _isServer = false; } } return _isServer }; // detect devtools var devtools = inBrowser && window.__VUE_DEVTOOLS_GLOBAL_HOOK__; /* istanbul ignore next */ function isNative (Ctor) { return typeof Ctor === 'function' && /native code/.test(Ctor.toString()) } var hasSymbol = typeof Symbol !== 'undefined' && isNative(Symbol) && typeof Reflect !== 'undefined' && isNative(Reflect.ownKeys); /** * Defer a task to execute it asynchronously. */ var nextTick = (function () { var callbacks = []; var pending = false; var timerFunc; function nextTickHandler () { pending = false; var copies = callbacks.slice(0); callbacks.length = 0; for (var i = 0; i < copies.length; i++) { copies[i](); } } // An asynchronous deferring mechanism. // In pre 2.4, we used to use microtasks (Promise/MutationObserver) // but microtasks actually has too high a priority and fires in between // supposedly sequential events (e.g. #4521, #6690) or even between // bubbling of the same event (#6566). Technically setImmediate should be // the ideal choice, but it's not available everywhere; and the only polyfill // that consistently queues the callback after all DOM events triggered in the // same loop is by using MessageChannel. /* istanbul ignore if */ if (typeof setImmediate !== 'undefined' && isNative(setImmediate)) { timerFunc = function () { setImmediate(nextTickHandler); }; } else if (typeof MessageChannel !== 'undefined' && ( isNative(MessageChannel) || // PhantomJS MessageChannel.toString() === '[object MessageChannelConstructor]' )) { var channel = new MessageChannel(); var port = channel.port2; channel.port1.onmessage = nextTickHandler; timerFunc = function () { port.postMessage(1); }; } else /* istanbul ignore next */ if (typeof Promise !== 'undefined' && isNative(Promise)) { // use microtask in non-DOM environments, e.g. Weex var p = Promise.resolve(); timerFunc = function () { p.then(nextTickHandler); }; } else { // fallback to setTimeout timerFunc = function () { setTimeout(nextTickHandler, 0); }; } return function queueNextTick (cb, ctx) { var _resolve; callbacks.push(function () { if (cb) { try { cb.call(ctx); } catch (e) { handleError(e, ctx, 'nextTick'); } } else if (_resolve) { _resolve(ctx); } }); if (!pending) { pending = true; timerFunc(); } // $flow-disable-line if (!cb && typeof Promise !== 'undefined') { return new Promise(function (resolve, reject) { _resolve = resolve; }) } } })(); var _Set; /* istanbul ignore if */ // $flow-disable-line if (typeof Set !== 'undefined' && isNative(Set)) { // use native Set when available. _Set = Set; } else { // a non-standard Set polyfill that only works with primitive keys. _Set = (function () { function Set () { this.set = Object.create(null); } Set.prototype.has = function has (key) { return this.set[key] === true }; Set.prototype.add = function add (key) { this.set[key] = true; }; Set.prototype.clear = function clear () { this.set = Object.create(null); }; return Set; }()); } /* */ var uid = 0; /** * A dep is an observable that can have multiple * directives subscribing to it. */ var Dep = function Dep () { this.id = uid++; this.subs = []; }; Dep.prototype.addSub = function addSub (sub) { this.subs.push(sub); }; Dep.prototype.removeSub = function removeSub (sub) { remove(this.subs, sub); }; Dep.prototype.depend = function depend () { if (Dep.target) { Dep.target.addDep(this); } }; Dep.prototype.notify = function notify () { // stabilize the subscriber list first var subs = this.subs.slice(); for (var i = 0, l = subs.length; i < l; i++) { subs[i].update(); } }; // the current target watcher being evaluated. // this is globally unique because there could be only one // watcher being evaluated at any time. Dep.target = null; var targetStack = []; function pushTarget (_target) { if (Dep.target) { targetStack.push(Dep.target); } Dep.target = _target; } function popTarget () { Dep.target = targetStack.pop(); } /* */ var VNode = function VNode ( tag, data, children, text, elm, context, componentOptions, asyncFactory ) { this.tag = tag; this.data = data; this.children = children; this.text = text; this.elm = elm; this.ns = undefined; this.context = context; this.functionalContext = undefined; this.functionalOptions = undefined; this.functionalScopeId = undefined; this.key = data && data.key; this.componentOptions = componentOptions; this.componentInstance = undefined; this.parent = undefined; this.raw = false; this.isStatic = false; this.isRootInsert = true; this.isComment = false; this.isCloned = false; this.isOnce = false; this.asyncFactory = asyncFactory; this.asyncMeta = undefined; this.isAsyncPlaceholder = false; }; var prototypeAccessors = { child: { configurable: true } }; // DEPRECATED: alias for componentInstance for backwards compat. /* istanbul ignore next */ prototypeAccessors.child.get = function () { return this.componentInstance }; Object.defineProperties( VNode.prototype, prototypeAccessors ); var createEmptyVNode = function (text) { if ( text === void 0 ) text = ''; var node = new VNode(); node.text = text; node.isComment = true; return node }; function createTextVNode (val) { return new VNode(undefined, undefined, undefined, String(val)) } // optimized shallow clone // used for static nodes and slot nodes because they may be reused across // multiple renders, cloning them avoids errors when DOM manipulations rely // on their elm reference. function cloneVNode (vnode, deep) { var cloned = new VNode( vnode.tag, vnode.data, vnode.children, vnode.text, vnode.elm, vnode.context, vnode.componentOptions, vnode.asyncFactory ); cloned.ns = vnode.ns; cloned.isStatic = vnode.isStatic; cloned.key = vnode.key; cloned.isComment = vnode.isComment; cloned.isCloned = true; if (deep && vnode.children) { cloned.children = cloneVNodes(vnode.children); } return cloned } function cloneVNodes (vnodes, deep) { var len = vnodes.length; var res = new Array(len); for (var i = 0; i < len; i++) { res[i] = cloneVNode(vnodes[i], deep); } return res } /* * not type checking this file because flow doesn't play well with * dynamically accessing methods on Array prototype */ var arrayProto = Array.prototype; var arrayMethods = Object.create(arrayProto);[ 'push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse' ] .forEach(function (method) { // cache original method var original = arrayProto[method]; def(arrayMethods, method, function mutator () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; var result = original.apply(this, args); var ob = this.__ob__; var inserted; switch (method) { case 'push': case 'unshift': inserted = args; break case 'splice': inserted = args.slice(2); break } if (inserted) { ob.observeArray(inserted); } // notify change ob.dep.notify(); return result }); }); /* */ var arrayKeys = Object.getOwnPropertyNames(arrayMethods); /** * By default, when a reactive property is set, the new value is * also converted to become reactive. However when passing down props, * we don't want to force conversion because the value may be a nested value * under a frozen data structure. Converting it would defeat the optimization. */ var observerState = { shouldConvert: true }; /** * Observer class that are attached to each observed * object. Once attached, the observer converts target * object's property keys into getter/setters that * collect dependencies and dispatches updates. */ var Observer = function Observer (value) { this.value = value; this.dep = new Dep(); this.vmCount = 0; def(value, '__ob__', this); if (Array.isArray(value)) { var augment = hasProto ? protoAugment : copyAugment; augment(value, arrayMethods, arrayKeys); this.observeArray(value); } else { this.walk(value); } }; /** * Walk through each property and convert them into * getter/setters. This method should only be called when * value type is Object. */ Observer.prototype.walk = function walk (obj) { var keys = Object.keys(obj); for (var i = 0; i < keys.length; i++) { defineReactive(obj, keys[i], obj[keys[i]]); } }; /** * Observe a list of Array items. */ Observer.prototype.observeArray = function observeArray (items) { for (var i = 0, l = items.length; i < l; i++) { observe(items[i]); } }; // helpers /** * Augment an target Object or Array by intercepting * the prototype chain using __proto__ */ function protoAugment (target, src, keys) { /* eslint-disable no-proto */ target.__proto__ = src; /* eslint-enable no-proto */ } /** * Augment an target Object or Array by defining * hidden properties. */ /* istanbul ignore next */ function copyAugment (target, src, keys) { for (var i = 0, l = keys.length; i < l; i++) { var key = keys[i]; def(target, key, src[key]); } } /** * Attempt to create an observer instance for a value, * returns the new observer if successfully observed, * or the existing observer if the value already has one. */ function observe (value, asRootData) { if (!isObject(value) || value instanceof VNode) { return } var ob; if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) { ob = value.__ob__; } else if ( observerState.shouldConvert && !isServerRendering() && (Array.isArray(value) || isPlainObject(value)) && Object.isExtensible(value) && !value._isVue ) { ob = new Observer(value); } if (asRootData && ob) { ob.vmCount++; } return ob } /** * Define a reactive property on an Object. */ function defineReactive ( obj, key, val, customSetter, shallow ) { var dep = new Dep(); var property = Object.getOwnPropertyDescriptor(obj, key); if (property && property.configurable === false) { return } // cater for pre-defined getter/setters var getter = property && property.get; var setter = property && property.set; var childOb = !shallow && observe(val); Object.defineProperty(obj, key, { enumerable: true, configurable: true, get: function reactiveGetter () { var value = getter ? getter.call(obj) : val; if (Dep.target) { dep.depend(); if (childOb) { childOb.dep.depend(); if (Array.isArray(value)) { dependArray(value); } } } return value }, set: function reactiveSetter (newVal) { var value = getter ? getter.call(obj) : val; /* eslint-disable no-self-compare */ if (newVal === value || (newVal !== newVal && value !== value)) { return } /* eslint-enable no-self-compare */ if (process.env.NODE_ENV !== 'production' && customSetter) { customSetter(); } if (setter) { setter.call(obj, newVal); } else { val = newVal; } childOb = !shallow && observe(newVal); dep.notify(); } }); } /** * Set a property on an object. Adds the new property and * triggers change notification if the property doesn't * already exist. */ function set (target, key, val) { if (Array.isArray(target) && isValidArrayIndex(key)) { target.length = Math.max(target.length, key); target.splice(key, 1, val); return val } if (hasOwn(target, key)) { target[key] = val; return val } var ob = (target).__ob__; if (target._isVue || (ob && ob.vmCount)) { process.env.NODE_ENV !== 'production' && warn( 'Avoid adding reactive properties to a Vue instance or its root $data ' + 'at runtime - declare it upfront in the data option.' ); return val } if (!ob) { target[key] = val; return val } defineReactive(ob.value, key, val); ob.dep.notify(); return val } /** * Delete a property and trigger change if necessary. */ function del (target, key) { if (Array.isArray(target) && isValidArrayIndex(key)) { target.splice(key, 1); return } var ob = (target).__ob__; if (target._isVue || (ob && ob.vmCount)) { process.env.NODE_ENV !== 'production' && warn( 'Avoid deleting properties on a Vue instance or its root $data ' + '- just set it to null.' ); return } if (!hasOwn(target, key)) { return } delete target[key]; if (!ob) { return } ob.dep.notify(); } /** * Collect dependencies on array elements when the array is touched, since * we cannot intercept array element access like property getters. */ function dependArray (value) { for (var e = (void 0), i = 0, l = value.length; i < l; i++) { e = value[i]; e && e.__ob__ && e.__ob__.dep.depend(); if (Array.isArray(e)) { dependArray(e); } } } /* */ /** * Option overwriting strategies are functions that handle * how to merge a parent option value and a child option * value into the final value. */ var strats = config.optionMergeStrategies; /** * Options with restrictions */ if (process.env.NODE_ENV !== 'production') { strats.el = strats.propsData = function (parent, child, vm, key) { if (!vm) { warn( "option \"" + key + "\" can only be used during instance " + 'creation with the `new` keyword.' ); } return defaultStrat(parent, child) }; } /** * Helper that recursively merges two data objects together. */ function mergeData (to, from) { if (!from) { return to } var key, toVal, fromVal; var keys = Object.keys(from); for (var i = 0; i < keys.length; i++) { key = keys[i]; toVal = to[key]; fromVal = from[key]; if (!hasOwn(to, key)) { set(to, key, fromVal); } else if (isPlainObject(toVal) && isPlainObject(fromVal)) { mergeData(toVal, fromVal); } } return to } /** * Data */ function mergeDataOrFn ( parentVal, childVal, vm ) { if (!vm) { // in a Vue.extend merge, both should be functions if (!childVal) { return parentVal } if (!parentVal) { return childVal } // when parentVal & childVal are both present, // we need to return a function that returns the // merged result of both functions... no need to // check if parentVal is a function here because // it has to be a function to pass previous merges. return function mergedDataFn () { return mergeData( typeof childVal === 'function' ? childVal.call(this) : childVal, typeof parentVal === 'function' ? parentVal.call(this) : parentVal ) } } else if (parentVal || childVal) { return function mergedInstanceDataFn () { // instance merge var instanceData = typeof childVal === 'function' ? childVal.call(vm) : childVal; var defaultData = typeof parentVal === 'function' ? parentVal.call(vm) : parentVal; if (instanceData) { return mergeData(instanceData, defaultData) } else { return defaultData } } } } strats.data = function ( parentVal, childVal, vm ) { if (!vm) { if (childVal && typeof childVal !== 'function') { process.env.NODE_ENV !== 'production' && warn( 'The "data" option should be a function ' + 'that returns a per-instance value in component ' + 'definitions.', vm ); return parentVal } return mergeDataOrFn.call(this, parentVal, childVal) } return mergeDataOrFn(parentVal, childVal, vm) }; /** * Hooks and props are merged as arrays. */ function mergeHook ( parentVal, childVal ) { return childVal ? parentVal ? parentVal.concat(childVal) : Array.isArray(childVal) ? childVal : [childVal] : parentVal } LIFECYCLE_HOOKS.forEach(function (hook) { strats[hook] = mergeHook; }); /** * Assets * * When a vm is present (instance creation), we need to do * a three-way merge between constructor options, instance * options and parent options. */ function mergeAssets ( parentVal, childVal, vm, key ) { var res = Object.create(parentVal || null); if (childVal) { process.env.NODE_ENV !== 'production' && assertObjectType(key, childVal, vm); return extend(res, childVal) } else { return res } } ASSET_TYPES.forEach(function (type) { strats[type + 's'] = mergeAssets; }); /** * Watchers. * * Watchers hashes should not overwrite one * another, so we merge them as arrays. */ strats.watch = function ( parentVal, childVal, vm, key ) { // work around Firefox's Object.prototype.watch... if (parentVal === nativeWatch) { parentVal = undefined; } if (childVal === nativeWatch) { childVal = undefined; } /* istanbul ignore if */ if (!childVal) { return Object.create(parentVal || null) } if (process.env.NODE_ENV !== 'production') { assertObjectType(key, childVal, vm); } if (!parentVal) { return childVal } var ret = {}; extend(ret, parentVal); for (var key$1 in childVal) { var parent = ret[key$1]; var child = childVal[key$1]; if (parent && !Array.isArray(parent)) { parent = [parent]; } ret[key$1] = parent ? parent.concat(child) : Array.isArray(child) ? child : [child]; } return ret }; /** * Other object hashes. */ strats.props = strats.methods = strats.inject = strats.computed = function ( parentVal, childVal, vm, key ) { if (childVal && process.env.NODE_ENV !== 'production') { assertObjectType(key, childVal, vm); } if (!parentVal) { return childVal } var ret = Object.create(null); extend(ret, parentVal); if (childVal) { extend(ret, childVal); } return ret }; strats.provide = mergeDataOrFn; /** * Default strategy. */ var defaultStrat = function (parentVal, childVal) { return childVal === undefined ? parentVal : childVal }; /** * Validate component names */ function checkComponents (options) { for (var key in options.components) { var lower = key.toLowerCase(); if (isBuiltInTag(lower) || config.isReservedTag(lower)) { warn( 'Do not use built-in or reserved HTML elements as component ' + 'id: ' + key ); } } } /** * Ensure all props option syntax are normalized into the * Object-based format. */ function normalizeProps (options, vm) { var props = options.props; if (!props) { return } var res = {}; var i, val, name; if (Array.isArray(props)) { i = props.length; while (i--) { val = props[i]; if (typeof val === 'string') { name = camelize(val); res[name] = { type: null }; } else if (process.env.NODE_ENV !== 'production') { warn('props must be strings when using array syntax.'); } } } else if (isPlainObject(props)) { for (var key in props) { val = props[key]; name = camelize(key); res[name] = isPlainObject(val) ? val : { type: val }; } } else if (process.env.NODE_ENV !== 'production') { warn( "Invalid value for option \"props\": expected an Array or an Object, " + "but got " + (toRawType(props)) + ".", vm ); } options.props = res; } /** * Normalize all injections into Object-based format */ function normalizeInject (options, vm) { var inject = options.inject; var normalized = options.inject = {}; if (Array.isArray(inject)) { for (var i = 0; i < inject.length; i++) { normalized[inject[i]] = { from: inject[i] }; } } else if (isPlainObject(inject)) { for (var key in inject) { var val = inject[key]; normalized[key] = isPlainObject(val) ? extend({ from: key }, val) : { from: val }; } } else if (process.env.NODE_ENV !== 'production' && inject) { warn( "Invalid value for option \"inject\": expected an Array or an Object, " + "but got " + (toRawType(inject)) + ".", vm ); } } /** * Normalize raw function directives into object format. */ function normalizeDirectives (options) { var dirs = options.directives; if (dirs) { for (var key in dirs) { var def = dirs[key]; if (typeof def === 'function') { dirs[key] = { bind: def, update: def }; } } } } function assertObjectType (name, value, vm) { if (!isPlainObject(value)) { warn( "Invalid value for option \"" + name + "\": expected an Object, " + "but got " + (toRawType(value)) + ".", vm ); } } /** * Merge two option objects into a new one. * Core utility used in both instantiation and inheritance. */ function mergeOptions ( parent, child, vm ) { if (process.env.NODE_ENV !== 'production') { checkComponents(child); } if (typeof child === 'function') { child = child.options; } normalizeProps(child, vm); normalizeInject(child, vm); normalizeDirectives(child); var extendsFrom = child.extends; if (extendsFrom) { parent = mergeOptions(parent, extendsFrom, vm); } if (child.mixins) { for (var i = 0, l = child.mixins.length; i < l; i++) { parent = mergeOptions(parent, child.mixins[i], vm); } } var options = {}; var key; for (key in parent) { mergeField(key); } for (key in child) { if (!hasOwn(parent, key)) { mergeField(key); } } function mergeField (key) { var strat = strats[key] || defaultStrat; options[key] = strat(parent[key], child[key], vm, key); } return options } /** * Resolve an asset. * This function is used because child instances need access * to assets defined in its ancestor chain. */ function resolveAsset ( options, type, id, warnMissing ) { /* istanbul ignore if */ if (typeof id !== 'string') { return } var assets = options[type]; // check local registration variations first if (hasOwn(assets, id)) { return assets[id] } var camelizedId = camelize(id); if (hasOwn(assets, camelizedId)) { return assets[camelizedId] } var PascalCaseId = capitalize(camelizedId); if (hasOwn(assets, PascalCaseId)) { return assets[PascalCaseId] } // fallback to prototype chain var res = assets[id] || assets[camelizedId] || assets[PascalCaseId]; if (process.env.NODE_ENV !== 'production' && warnMissing && !res) { warn( 'Failed to resolve ' + type.slice(0, -1) + ': ' + id, options ); } return res } /* */ function validateProp ( key, propOptions, propsData, vm ) { var prop = propOptions[key]; var absent = !hasOwn(propsData, key); var value = propsData[key]; // handle boolean props if (isType(Boolean, prop.type)) { if (absent && !hasOwn(prop, 'default')) { value = false; } else if (!isType(String, prop.type) && (value === '' || value === hyphenate(key))) { value = true; } } // check default value if (value === undefined) { value = getPropDefaultValue(vm, prop, key); // since the default value is a fresh copy, // make sure to observe it. var prevShouldConvert = observerState.shouldConvert; observerState.shouldConvert = true; observe(value); observerState.shouldConvert = prevShouldConvert; } if (process.env.NODE_ENV !== 'production') { assertProp(prop, key, value, vm, absent); } return value } /** * Get the default value of a prop. */ function getPropDefaultValue (vm, prop, key) { // no default, return undefined if (!hasOwn(prop, 'default')) { return undefined } var def = prop.default; // warn against non-factory defaults for Object & Array if (process.env.NODE_ENV !== 'production' && isObject(def)) { warn( 'Invalid default value for prop "' + key + '": ' + 'Props with type Object/Array must use a factory function ' + 'to return the default value.', vm ); } // the raw prop value was also undefined from previous render, // return previous default value to avoid unnecessary watcher trigger if (vm && vm.$options.propsData && vm.$options.propsData[key] === undefined && vm._props[key] !== undefined ) { return vm._props[key] } // call factory function for non-Function types // a value is Function if its prototype is function even across different execution context return typeof def === 'function' && getType(prop.type) !== 'Function' ? def.call(vm) : def } /** * Assert whether a prop is valid. */ function assertProp ( prop, name, value, vm, absent ) { if (prop.required && absent) { warn( 'Missing required prop: "' + name + '"', vm ); return } if (value == null && !prop.required) { return } var type = prop.type; var valid = !type || type === true; var expectedTypes = []; if (type) { if (!Array.isArray(type)) { type = [type]; } for (var i = 0; i < type.length && !valid; i++) { var assertedType = assertType(value, type[i]); expectedTypes.push(assertedType.expectedType || ''); valid = assertedType.valid; } } if (!valid) { warn( "Invalid prop: type check failed for prop \"" + name + "\"." + " Expected " + (expectedTypes.map(capitalize).join(', ')) + ", got " + (toRawType(value)) + ".", vm ); return } var validator = prop.validator; if (validator) { if (!validator(value)) { warn( 'Invalid prop: custom validator check failed for prop "' + name + '".', vm ); } } } var simpleCheckRE = /^(String|Number|Boolean|Function|Symbol)$/; function assertType (value, type) { var valid; var expectedType = getType(type); if (simpleCheckRE.test(expectedType)) { var t = typeof value; valid = t === expectedType.toLowerCase(); // for primitive wrapper objects if (!valid && t === 'object') { valid = value instanceof type; } } else if (expectedType === 'Object') { valid = isPlainObject(value); } else if (expectedType === 'Array') { valid = Array.isArray(value); } else { valid = value instanceof type; } return { valid: valid, expectedType: expectedType } } /** * Use function string name to check built-in types, * because a simple equality check will fail when running * across different vms / iframes. */ function getType (fn) { var match = fn && fn.toString().match(/^\s*function (\w+)/); return match ? match[1] : '' } function isType (type, fn) { if (!Array.isArray(fn)) { return getType(fn) === getType(type) } for (var i = 0, len = fn.length; i < len; i++) { if (getType(fn[i]) === getType(type)) { return true } } /* istanbul ignore next */ return false } /* */ var mark; var measure; if (process.env.NODE_ENV !== 'production') { var perf = inBrowser && window.performance; /* istanbul ignore if */ if ( perf && perf.mark && perf.measure && perf.clearMarks && perf.clearMeasures ) { mark = function (tag) { return perf.mark(tag); }; measure = function (name, startTag, endTag) { perf.measure(name, startTag, endTag); perf.clearMarks(startTag); perf.clearMarks(endTag); perf.clearMeasures(name); }; } } /* not type checking this file because flow doesn't play well with Proxy */ var initProxy; if (process.env.NODE_ENV !== 'production') { var allowedGlobals = makeMap( 'Infinity,undefined,NaN,isFinite,isNaN,' + 'parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,' + 'Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,' + 'require' // for Webpack/Browserify ); var warnNonPresent = function (target, key) { warn( "Property or method \"" + key + "\" is not defined on the instance but " + 'referenced during render. Make sure that this property is reactive, ' + 'either in the data option, or for class-based components, by ' + 'initializing the property. ' + 'See: https://vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.', target ); }; var hasProxy = typeof Proxy !== 'undefined' && Proxy.toString().match(/native code/); if (hasProxy) { var isBuiltInModifier = makeMap('stop,prevent,self,ctrl,shift,alt,meta,exact'); config.keyCodes = new Proxy(config.keyCodes, { set: function set (target, key, value) { if (isBuiltInModifier(key)) { warn(("Avoid overwriting built-in modifier in config.keyCodes: ." + key)); return false } else { target[key] = value; return true } } }); } var hasHandler = { has: function has (target, key) { var has = key in target; var isAllowed = allowedGlobals(key) || key.charAt(0) === '_'; if (!has && !isAllowed) { warnNonPresent(target, key); } return has || !isAllowed } }; var getHandler = { get: function get (target, key) { if (typeof key === 'string' && !(key in target)) { warnNonPresent(target, key); } return target[key] } }; initProxy = function initProxy (vm) { if (hasProxy) { // determine which proxy handler to use var options = vm.$options; var handlers = options.render && options.render._withStripped ? getHandler : hasHandler; vm._renderProxy = new Proxy(vm, handlers); } else { vm._renderProxy = vm; } }; } /* */ var normalizeEvent = cached(function (name) { var passive = name.charAt(0) === '&'; name = passive ? name.slice(1) : name; var once$$1 = name.charAt(0) === '~'; // Prefixed last, checked first name = once$$1 ? name.slice(1) : name; var capture = name.charAt(0) === '!'; name = capture ? name.slice(1) : name; return { name: name, once: once$$1, capture: capture, passive: passive } }); function createFnInvoker (fns) { function invoker () { var arguments$1 = arguments; var fns = invoker.fns; if (Array.isArray(fns)) { var cloned = fns.slice(); for (var i = 0; i < cloned.length; i++) { cloned[i].apply(null, arguments$1); } } else { // return handler return value for single handlers return fns.apply(null, arguments) } } invoker.fns = fns; return invoker } function updateListeners ( on, oldOn, add, remove$$1, vm ) { var name, cur, old, event; for (name in on) { cur = on[name]; old = oldOn[name]; event = normalizeEvent(name); if (isUndef(cur)) { process.env.NODE_ENV !== 'production' && warn( "Invalid handler for event \"" + (event.name) + "\": got " + String(cur), vm ); } else if (isUndef(old)) { if (isUndef(cur.fns)) { cur = on[name] = createFnInvoker(cur); } add(event.name, cur, event.once, event.capture, event.passive); } else if (cur !== old) { old.fns = cur; on[name] = old; } } for (name in oldOn) { if (isUndef(on[name])) { event = normalizeEvent(name); remove$$1(event.name, oldOn[name], event.capture); } } } /* */ function mergeVNodeHook (def, hookKey, hook) { var invoker; var oldHook = def[hookKey]; function wrappedHook () { hook.apply(this, arguments); // important: remove merged hook to ensure it's called only once // and prevent memory leak remove(invoker.fns, wrappedHook); } if (isUndef(oldHook)) { // no existing hook invoker = createFnInvoker([wrappedHook]); } else { /* istanbul ignore if */ if (isDef(oldHook.fns) && isTrue(oldHook.merged)) { // already a merged invoker invoker = oldHook; invoker.fns.push(wrappedHook); } else { // existing plain hook invoker = createFnInvoker([oldHook, wrappedHook]); } } invoker.merged = true; def[hookKey] = invoker; } /* */ function extractPropsFromVNodeData ( data, Ctor, tag ) { // we are only extracting raw values here. // validation and default values are handled in the child // component itself. var propOptions = Ctor.options.props; if (isUndef(propOptions)) { return } var res = {}; var attrs = data.attrs; var props = data.props; if (isDef(attrs) || isDef(props)) { for (var key in propOptions) { var altKey = hyphenate(key); if (process.env.NODE_ENV !== 'production') { var keyInLowerCase = key.toLowerCase(); if ( key !== keyInLowerCase && attrs && hasOwn(attrs, keyInLowerCase) ) { tip( "Prop \"" + keyInLowerCase + "\" is passed to component " + (formatComponentName(tag || Ctor)) + ", but the declared prop name is" + " \"" + key + "\". " + "Note that HTML attributes are case-insensitive and camelCased " + "props need to use their kebab-case equivalents when using in-DOM " + "templates. You should probably use \"" + altKey + "\" instead of \"" + key + "\"." ); } } checkProp(res, props, key, altKey, true) || checkProp(res, attrs, key, altKey, false); } } return res } function checkProp ( res, hash, key, altKey, preserve ) { if (isDef(hash)) { if (hasOwn(hash, key)) { res[key] = hash[key]; if (!preserve) { delete hash[key]; } return true } else if (hasOwn(hash, altKey)) { res[key] = hash[altKey]; if (!preserve) { delete hash[altKey]; } return true } } return false } /* */ // The template compiler attempts to minimize the need for normalization by // statically analyzing the template at compile time. // // For plain HTML markup, normalization can be completely skipped because the // generated render function is guaranteed to return Array<VNode>. There are // two cases where extra normalization is needed: // 1. When the children contains components - because a functional component // may return an Array instead of a single root. In this case, just a simple // normalization is needed - if any child is an Array, we flatten the whole // thing with Array.prototype.concat. It is guaranteed to be only 1-level deep // because functional components already normalize their own children. function simpleNormalizeChildren (children) { for (var i = 0; i < children.length; i++) { if (Array.isArray(children[i])) { return Array.prototype.concat.apply([], children) } } return children } // 2. When the children contains constructs that always generated nested Arrays, // e.g. <template>, <slot>, v-for, or when the children is provided by user // with hand-written render functions / JSX. In such cases a full normalization // is needed to cater to all possible types of children values. function normalizeChildren (children) { return isPrimitive(children) ? [createTextVNode(children)] : Array.isArray(children) ? normalizeArrayChildren(children) : undefined } function isTextNode (node) { return isDef(node) && isDef(node.text) && isFalse(node.isComment) } function normalizeArrayChildren (children, nestedIndex) { var res = []; var i, c, lastIndex, last; for (i = 0; i < children.length; i++) { c = children[i]; if (isUndef(c) || typeof c === 'boolean') { continue } lastIndex = res.length - 1; last = res[lastIndex]; // nested if (Array.isArray(c)) { if (c.length > 0) { c = normalizeArrayChildren(c, ((nestedIndex || '') + "_" + i)); // merge adjacent text nodes if (isTextNode(c[0]) && isTextNode(last)) { res[lastIndex] = createTextVNode(last.text + (c[0]).text); c.shift(); } res.push.apply(res, c); } } else if (isPrimitive(c)) { if (isTextNode(last)) { // merge adjacent text nodes // this is necessary for SSR hydration because text nodes are // essentially merged when rendered to HTML strings res[lastIndex] = createTextVNode(last.text + c); } else if (c !== '') { // convert primitive to vnode res.push(createTextVNode(c)); } } else { if (isTextNode(c) && isTextNode(last)) { // merge adjacent text nodes res[lastIndex] = createTextVNode(last.text + c.text); } else { // default key for nested array children (likely generated by v-for) if (isTrue(children._isVList) && isDef(c.tag) && isUndef(c.key) && isDef(nestedIndex)) { c.key = "__vlist" + nestedIndex + "_" + i + "__"; } res.push(c); } } } return res } /* */ function ensureCtor (comp, base) { if ( comp.__esModule || (hasSymbol && comp[Symbol.toStringTag] === 'Module') ) { comp = comp.default; } return isObject(comp) ? base.extend(comp) : comp } function createAsyncPlaceholder ( factory, data, context, children, tag ) { var node = createEmptyVNode(); node.asyncFactory = factory; node.asyncMeta = { data: data, context: context, children: children, tag: tag }; return node } function resolveAsyncComponent ( factory, baseCtor, context ) { if (isTrue(factory.error) && isDef(factory.errorComp)) { return factory.errorComp } if (isDef(factory.resolved)) { return factory.resolved } if (isTrue(factory.loading) && isDef(factory.loadingComp)) { return factory.loadingComp } if (isDef(factory.contexts)) { // already pending factory.contexts.push(context); } else { var contexts = factory.contexts = [context]; var sync = true; var forceRender = function () { for (var i = 0, l = contexts.length; i < l; i++) { contexts[i].$forceUpdate(); } }; var resolve = once(function (res) { // cache resolved factory.resolved = ensureCtor(res, baseCtor); // invoke callbacks only if this is not a synchronous resolve // (async resolves are shimmed as synchronous during SSR) if (!sync) { forceRender(); } }); var reject = once(function (reason) { process.env.NODE_ENV !== 'production' && warn( "Failed to resolve async component: " + (String(factory)) + (reason ? ("\nReason: " + reason) : '') ); if (isDef(factory.errorComp)) { factory.error = true; forceRender(); } }); var res = factory(resolve, reject); if (isObject(res)) { if (typeof res.then === 'function') { // () => Promise if (isUndef(factory.resolved)) { res.then(resolve, reject); } } else if (isDef(res.component) && typeof res.component.then === 'function') { res.component.then(resolve, reject); if (isDef(res.error)) { factory.errorComp = ensureCtor(res.error, baseCtor); } if (isDef(res.loading)) { factory.loadingComp = ensureCtor(res.loading, baseCtor); if (res.delay === 0) { factory.loading = true; } else { setTimeout(function () { if (isUndef(factory.resolved) && isUndef(factory.error)) { factory.loading = true; forceRender(); } }, res.delay || 200); } } if (isDef(res.timeout)) { setTimeout(function () { if (isUndef(factory.resolved)) { reject( process.env.NODE_ENV !== 'production' ? ("timeout (" + (res.timeout) + "ms)") : null ); } }, res.timeout); } } } sync = false; // return in case resolved synchronously return factory.loading ? factory.loadingComp : factory.resolved } } /* */ function isAsyncPlaceholder (node) { return node.isComment && node.asyncFactory } /* */ function getFirstComponentChild (children) { if (Array.isArray(children)) { for (var i = 0; i < children.length; i++) { var c = children[i]; if (isDef(c) && (isDef(c.componentOptions) || isAsyncPlaceholder(c))) { return c } } } } /* */ /* */ function initEvents (vm) { vm._events = Object.create(null); vm._hasHookEvent = false; // init parent attached events var listeners = vm.$options._parentListeners; if (listeners) { updateComponentListeners(vm, listeners); } } var target; function add (event, fn, once) { if (once) { target.$once(event, fn); } else { target.$on(event, fn); } } function remove$1 (event, fn) { target.$off(event, fn); } function updateComponentListeners ( vm, listeners, oldListeners ) { target = vm; updateListeners(listeners, oldListeners || {}, add, remove$1, vm); } function eventsMixin (Vue) { var hookRE = /^hook:/; Vue.prototype.$on = function (event, fn) { var this$1 = this; var vm = this; if (Array.isArray(event)) { for (var i = 0, l = event.length; i < l; i++) { this$1.$on(event[i], fn); } } else { (vm._events[event] || (vm._events[event] = [])).push(fn); // optimize hook:event cost by using a boolean flag marked at registration // instead of a hash lookup if (hookRE.test(event)) { vm._hasHookEvent = true; } } return vm }; Vue.prototype.$once = function (event, fn) { var vm = this; function on () { vm.$off(event, on); fn.apply(vm, arguments); } on.fn = fn; vm.$on(event, on); return vm }; Vue.prototype.$off = function (event, fn) { var this$1 = this; var vm = this; // all if (!arguments.length) { vm._events = Object.create(null); return vm } // array of events if (Array.isArray(event)) { for (var i = 0, l = event.length; i < l; i++) { this$1.$off(event[i], fn); } return vm } // specific event var cbs = vm._events[event]; if (!cbs) { return vm } if (arguments.length === 1) { vm._events[event] = null; return vm } if (fn) { // specific handler var cb; var i$1 = cbs.length; while (i$1--) { cb = cbs[i$1]; if (cb === fn || cb.fn === fn) { cbs.splice(i$1, 1); break } } } return vm }; Vue.prototype.$emit = function (event) { var vm = this; if (process.env.NODE_ENV !== 'production') { var lowerCaseEvent = event.toLowerCase(); if (lowerCaseEvent !== event && vm._events[lowerCaseEvent]) { tip( "Event \"" + lowerCaseEvent + "\" is emitted in component " + (formatComponentName(vm)) + " but the handler is registered for \"" + event + "\". " + "Note that HTML attributes are case-insensitive and you cannot use " + "v-on to listen to camelCase events when using in-DOM templates. " + "You should probably use \"" + (hyphenate(event)) + "\" instead of \"" + event + "\"." ); } } var cbs = vm._events[event]; if (cbs) { cbs = cbs.length > 1 ? toArray(cbs) : cbs; var args = toArray(arguments, 1); for (var i = 0, l = cbs.length; i < l; i++) { try { cbs[i].apply(vm, args); } catch (e) { handleError(e, vm, ("event handler for \"" + event + "\"")); } } } return vm }; } /* */ /** * Runtime helper for resolving raw children VNodes into a slot object. */ function resolveSlots ( children, context ) { var slots = {}; if (!children) { return slots } var defaultSlot = []; for (var i = 0, l = children.length; i < l; i++) { var child = children[i]; var data = child.data; // remove slot attribute if the node is resolved as a Vue slot node if (data && data.attrs && data.attrs.slot) { delete data.attrs.slot; } // named slots should only be respected if the vnode was rendered in the // same context. if ((child.context === context || child.functionalContext === context) && data && data.slot != null ) { var name = child.data.slot; var slot = (slots[name] || (slots[name] = [])); if (child.tag === 'template') { slot.push.apply(slot, child.children); } else { slot.push(child); } } else { defaultSlot.push(child); } } // ignore whitespace if (!defaultSlot.every(isWhitespace)) { slots.default = defaultSlot; } return slots } function isWhitespace (node) { return node.isComment || node.text === ' ' } function resolveScopedSlots ( fns, // see flow/vnode res ) { res = res || {}; for (var i = 0; i < fns.length; i++) { if (Array.isArray(fns[i])) { resolveScopedSlots(fns[i], res); } else { res[fns[i].key] = fns[i].fn; } } return res } /* */ var activeInstance = null; var isUpdatingChildComponent = false; function initLifecycle (vm) { var options = vm.$options; // locate first non-abstract parent var parent = options.parent; if (parent && !options.abstract) { while (parent.$options.abstract && parent.$parent) { parent = parent.$parent; } parent.$children.push(vm); } vm.$parent = parent; vm.$root = parent ? parent.$root : vm; vm.$children = []; vm.$refs = {}; vm._watcher = null; vm._inactive = null; vm._directInactive = false; vm._isMounted = false; vm._isDestroyed = false; vm._isBeingDestroyed = false; } function lifecycleMixin (Vue) { Vue.prototype._update = function (vnode, hydrating) { var vm = this; if (vm._isMounted) { callHook(vm, 'beforeUpdate'); } var prevEl = vm.$el; var prevVnode = vm._vnode; var prevActiveInstance = activeInstance; activeInstance = vm; vm._vnode = vnode; // Vue.prototype.__patch__ is injected in entry points // based on the rendering backend used. if (!prevVnode) { // initial render vm.$el = vm.__patch__( vm.$el, vnode, hydrating, false /* removeOnly */, vm.$options._parentElm, vm.$options._refElm ); // no need for the ref nodes after initial patch // this prevents keeping a detached DOM tree in memory (#5851) vm.$options._parentElm = vm.$options._refElm = null; } else { // updates vm.$el = vm.__patch__(prevVnode, vnode); } activeInstance = prevActiveInstance; // update __vue__ reference if (prevEl) { prevEl.__vue__ = null; } if (vm.$el) { vm.$el.__vue__ = vm; } // if parent is an HOC, update its $el as well if (vm.$vnode && vm.$parent && vm.$vnode === vm.$parent._vnode) { vm.$parent.$el = vm.$el; } // updated hook is called by the scheduler to ensure that children are // updated in a parent's updated hook. }; Vue.prototype.$forceUpdate = function () { var vm = this; if (vm._watcher) { vm._watcher.update(); } }; Vue.prototype.$destroy = function () { var vm = this; if (vm._isBeingDestroyed) { return } callHook(vm, 'beforeDestroy'); vm._isBeingDestroyed = true; // remove self from parent var parent = vm.$parent; if (parent && !parent._isBeingDestroyed && !vm.$options.abstract) { remove(parent.$children, vm); } // teardown watchers if (vm._watcher) { vm._watcher.teardown(); } var i = vm._watchers.length; while (i--) { vm._watchers[i].teardown(); } // remove reference from data ob // frozen object may not have observer. if (vm._data.__ob__) { vm._data.__ob__.vmCount--; } // call the last hook... vm._isDestroyed = true; // invoke destroy hooks on current rendered tree vm.__patch__(vm._vnode, null); // fire destroyed hook callHook(vm, 'destroyed'); // turn off all instance listeners. vm.$off(); // remove __vue__ reference if (vm.$el) { vm.$el.__vue__ = null; } // release circular reference (#6759) if (vm.$vnode) { vm.$vnode.parent = null; } }; } function mountComponent ( vm, el, hydrating ) { vm.$el = el; if (!vm.$options.render) { vm.$options.render = createEmptyVNode; if (process.env.NODE_ENV !== 'production') { /* istanbul ignore if */ if ((vm.$options.template && vm.$options.template.charAt(0) !== '#') || vm.$options.el || el) { warn( 'You are using the runtime-only build of Vue where the template ' + 'compiler is not available. Either pre-compile the templates into ' + 'render functions, or use the compiler-included build.', vm ); } else { warn( 'Failed to mount component: template or render function not defined.', vm ); } } } callHook(vm, 'beforeMount'); var updateComponent; /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production' && config.performance && mark) { updateComponent = function () { var name = vm._name; var id = vm._uid; var startTag = "vue-perf-start:" + id; var endTag = "vue-perf-end:" + id; mark(startTag); var vnode = vm._render(); mark(endTag); measure(("vue " + name + " render"), startTag, endTag); mark(startTag); vm._update(vnode, hydrating); mark(endTag); measure(("vue " + name + " patch"), startTag, endTag); }; } else { updateComponent = function () { vm._update(vm._render(), hydrating); }; } vm._watcher = new Watcher(vm, updateComponent, noop); hydrating = false; // manually mounted instance, call mounted on self // mounted is called for render-created child components in its inserted hook if (vm.$vnode == null) { vm._isMounted = true; callHook(vm, 'mounted'); } return vm } function updateChildComponent ( vm, propsData, listeners, parentVnode, renderChildren ) { if (process.env.NODE_ENV !== 'production') { isUpdatingChildComponent = true; } // determine whether component has slot children // we need to do this before overwriting $options._renderChildren var hasChildren = !!( renderChildren || // has new static slots vm.$options._renderChildren || // has old static slots parentVnode.data.scopedSlots || // has new scoped slots vm.$scopedSlots !== emptyObject // has old scoped slots ); vm.$options._parentVnode = parentVnode; vm.$vnode = parentVnode; // update vm's placeholder node without re-render if (vm._vnode) { // update child tree's parent vm._vnode.parent = parentVnode; } vm.$options._renderChildren = renderChildren; // update $attrs and $listeners hash // these are also reactive so they may trigger child update if the child // used them during render vm.$attrs = (parentVnode.data && parentVnode.data.attrs) || emptyObject; vm.$listeners = listeners || emptyObject; // update props if (propsData && vm.$options.props) { observerState.shouldConvert = false; var props = vm._props; var propKeys = vm.$options._propKeys || []; for (var i = 0; i < propKeys.length; i++) { var key = propKeys[i]; props[key] = validateProp(key, vm.$options.props, propsData, vm); } observerState.shouldConvert = true; // keep a copy of raw propsData vm.$options.propsData = propsData; } // update listeners if (listeners) { var oldListeners = vm.$options._parentListeners; vm.$options._parentListeners = listeners; updateComponentListeners(vm, listeners, oldListeners); } // resolve slots + force update if has children if (hasChildren) { vm.$slots = resolveSlots(renderChildren, parentVnode.context); vm.$forceUpdate(); } if (process.env.NODE_ENV !== 'production') { isUpdatingChildComponent = false; } } function isInInactiveTree (vm) { while (vm && (vm = vm.$parent)) { if (vm._inactive) { return true } } return false } function activateChildComponent (vm, direct) { if (direct) { vm._directInactive = false; if (isInInactiveTree(vm)) { return } } else if (vm._directInactive) { return } if (vm._inactive || vm._inactive === null) { vm._inactive = false; for (var i = 0; i < vm.$children.length; i++) { activateChildComponent(vm.$children[i]); } callHook(vm, 'activated'); } } function deactivateChildComponent (vm, direct) { if (direct) { vm._directInactive = true; if (isInInactiveTree(vm)) { return } } if (!vm._inactive) { vm._inactive = true; for (var i = 0; i < vm.$children.length; i++) { deactivateChildComponent(vm.$children[i]); } callHook(vm, 'deactivated'); } } function callHook (vm, hook) { var handlers = vm.$options[hook]; if (handlers) { for (var i = 0, j = handlers.length; i < j; i++) { try { handlers[i].call(vm); } catch (e) { handleError(e, vm, (hook + " hook")); } } } if (vm._hasHookEvent) { vm.$emit('hook:' + hook); } } /* */ var MAX_UPDATE_COUNT = 100; var queue = []; var activatedChildren = []; var has = {}; var circular = {}; var waiting = false; var flushing = false; var index = 0; /** * Reset the scheduler's state. */ function resetSchedulerState () { index = queue.length = activatedChildren.length = 0; has = {}; if (process.env.NODE_ENV !== 'production') { circular = {}; } waiting = flushing = false; } /** * Flush both queues and run the watchers. */ function flushSchedulerQueue () { flushing = true; var watcher, id; // Sort queue before flush. // This ensures that: // 1. Components are updated from parent to child. (because parent is always // created before the child) // 2. A component's user watchers are run before its render watcher (because // user watchers are created before the render watcher) // 3. If a component is destroyed during a parent component's watcher run, // its watchers can be skipped. queue.sort(function (a, b) { return a.id - b.id; }); // do not cache length because more watchers might be pushed // as we run existing watchers for (index = 0; index < queue.length; index++) { watcher = queue[index]; id = watcher.id; has[id] = null; watcher.run(); // in dev build, check and stop circular updates. if (process.env.NODE_ENV !== 'production' && has[id] != null) { circular[id] = (circular[id] || 0) + 1; if (circular[id] > MAX_UPDATE_COUNT) { warn( 'You may have an infinite update loop ' + ( watcher.user ? ("in watcher with expression \"" + (watcher.expression) + "\"") : "in a component render function." ), watcher.vm ); break } } } // keep copies of post queues before resetting state var activatedQueue = activatedChildren.slice(); var updatedQueue = queue.slice(); resetSchedulerState(); // call component updated and activated hooks callActivatedHooks(activatedQueue); callUpdatedHooks(updatedQueue); // devtool hook /* istanbul ignore if */ if (devtools && config.devtools) { devtools.emit('flush'); } } function callUpdatedHooks (queue) { var i = queue.length; while (i--) { var watcher = queue[i]; var vm = watcher.vm; if (vm._watcher === watcher && vm._isMounted) { callHook(vm, 'updated'); } } } /** * Queue a kept-alive component that was activated during patch. * The queue will be processed after the entire tree has been patched. */ function queueActivatedComponent (vm) { // setting _inactive to false here so that a render function can // rely on checking whether it's in an inactive tree (e.g. router-view) vm._inactive = false; activatedChildren.push(vm); } function callActivatedHooks (queue) { for (var i = 0; i < queue.length; i++) { queue[i]._inactive = true; activateChildComponent(queue[i], true /* true */); } } /** * Push a watcher into the watcher queue. * Jobs with duplicate IDs will be skipped unless it's * pushed when the queue is being flushed. */ function queueWatcher (watcher) { var id = watcher.id; if (has[id] == null) { has[id] = true; if (!flushing) { queue.push(watcher); } else { // if already flushing, splice the watcher based on its id // if already past its id, it will be run next immediately. var i = queue.length - 1; while (i > index && queue[i].id > watcher.id) { i--; } queue.splice(i + 1, 0, watcher); } // queue the flush if (!waiting) { waiting = true; nextTick(flushSchedulerQueue); } } } /* */ var uid$2 = 0; /** * A watcher parses an expression, collects dependencies, * and fires callback when the expression value changes. * This is used for both the $watch() api and directives. */ var Watcher = function Watcher ( vm, expOrFn, cb, options ) { this.vm = vm; vm._watchers.push(this); // options if (options) { this.deep = !!options.deep; this.user = !!options.user; this.lazy = !!options.lazy; this.sync = !!options.sync; } else { this.deep = this.user = this.lazy = this.sync = false; } this.cb = cb; this.id = ++uid$2; // uid for batching this.active = true; this.dirty = this.lazy; // for lazy watchers this.deps = []; this.newDeps = []; this.depIds = new _Set(); this.newDepIds = new _Set(); this.expression = process.env.NODE_ENV !== 'production' ? expOrFn.toString() : ''; // parse expression for getter if (typeof expOrFn === 'function') { this.getter = expOrFn; } else { this.getter = parsePath(expOrFn); if (!this.getter) { this.getter = function () {}; process.env.NODE_ENV !== 'production' && warn( "Failed watching path: \"" + expOrFn + "\" " + 'Watcher only accepts simple dot-delimited paths. ' + 'For full control, use a function instead.', vm ); } } this.value = this.lazy ? undefined : this.get(); }; /** * Evaluate the getter, and re-collect dependencies. */ Watcher.prototype.get = function get () { pushTarget(this); var value; var vm = this.vm; try { value = this.getter.call(vm, vm); } catch (e) { if (this.user) { handleError(e, vm, ("getter for watcher \"" + (this.expression) + "\"")); } else { throw e } } finally { // "touch" every property so they are all tracked as // dependencies for deep watching if (this.deep) { traverse(value); } popTarget(); this.cleanupDeps(); } return value }; /** * Add a dependency to this directive. */ Watcher.prototype.addDep = function addDep (dep) { var id = dep.id; if (!this.newDepIds.has(id)) { this.newDepIds.add(id); this.newDeps.push(dep); if (!this.depIds.has(id)) { dep.addSub(this); } } }; /** * Clean up for dependency collection. */ Watcher.prototype.cleanupDeps = function cleanupDeps () { var this$1 = this; var i = this.deps.length; while (i--) { var dep = this$1.deps[i]; if (!this$1.newDepIds.has(dep.id)) { dep.removeSub(this$1); } } var tmp = this.depIds; this.depIds = this.newDepIds; this.newDepIds = tmp; this.newDepIds.clear(); tmp = this.deps; this.deps = this.newDeps; this.newDeps = tmp; this.newDeps.length = 0; }; /** * Subscriber interface. * Will be called when a dependency changes. */ Watcher.prototype.update = function update () { /* istanbul ignore else */ if (this.lazy) { this.dirty = true; } else if (this.sync) { this.run(); } else { queueWatcher(this); } }; /** * Scheduler job interface. * Will be called by the scheduler. */ Watcher.prototype.run = function run () { if (this.active) { var value = this.get(); if ( value !== this.value || // Deep watchers and watchers on Object/Arrays should fire even // when the value is the same, because the value may // have mutated. isObject(value) || this.deep ) { // set new value var oldValue = this.value; this.value = value; if (this.user) { try { this.cb.call(this.vm, value, oldValue); } catch (e) { handleError(e, this.vm, ("callback for watcher \"" + (this.expression) + "\"")); } } else { this.cb.call(this.vm, value, oldValue); } } } }; /** * Evaluate the value of the watcher. * This only gets called for lazy watchers. */ Watcher.prototype.evaluate = function evaluate () { this.value = this.get(); this.dirty = false; }; /** * Depend on all deps collected by this watcher. */ Watcher.prototype.depend = function depend () { var this$1 = this; var i = this.deps.length; while (i--) { this$1.deps[i].depend(); } }; /** * Remove self from all dependencies' subscriber list. */ Watcher.prototype.teardown = function teardown () { var this$1 = this; if (this.active) { // remove self from vm's watcher list // this is a somewhat expensive operation so we skip it // if the vm is being destroyed. if (!this.vm._isBeingDestroyed) { remove(this.vm._watchers, this); } var i = this.deps.length; while (i--) { this$1.deps[i].removeSub(this$1); } this.active = false; } }; /** * Recursively traverse an object to evoke all converted * getters, so that every nested property inside the object * is collected as a "deep" dependency. */ var seenObjects = new _Set(); function traverse (val) { seenObjects.clear(); _traverse(val, seenObjects); } function _traverse (val, seen) { var i, keys; var isA = Array.isArray(val); if ((!isA && !isObject(val)) || !Object.isExtensible(val)) { return } if (val.__ob__) { var depId = val.__ob__.dep.id; if (seen.has(depId)) { return } seen.add(depId); } if (isA) { i = val.length; while (i--) { _traverse(val[i], seen); } } else { keys = Object.keys(val); i = keys.length; while (i--) { _traverse(val[keys[i]], seen); } } } /* */ var sharedPropertyDefinition = { enumerable: true, configurable: true, get: noop, set: noop }; function proxy (target, sourceKey, key) { sharedPropertyDefinition.get = function proxyGetter () { return this[sourceKey][key] }; sharedPropertyDefinition.set = function proxySetter (val) { this[sourceKey][key] = val; }; Object.defineProperty(target, key, sharedPropertyDefinition); } function initState (vm) { vm._watchers = []; var opts = vm.$options; if (opts.props) { initProps(vm, opts.props); } if (opts.methods) { initMethods(vm, opts.methods); } if (opts.data) { initData(vm); } else { observe(vm._data = {}, true /* asRootData */); } if (opts.computed) { initComputed(vm, opts.computed); } if (opts.watch && opts.watch !== nativeWatch) { initWatch(vm, opts.watch); } } function initProps (vm, propsOptions) { var propsData = vm.$options.propsData || {}; var props = vm._props = {}; // cache prop keys so that future props updates can iterate using Array // instead of dynamic object key enumeration. var keys = vm.$options._propKeys = []; var isRoot = !vm.$parent; // root instance props should be converted observerState.shouldConvert = isRoot; var loop = function ( key ) { keys.push(key); var value = validateProp(key, propsOptions, propsData, vm); /* istanbul ignore else */ if (process.env.NODE_ENV !== 'production') { var hyphenatedKey = hyphenate(key); if (isReservedAttribute(hyphenatedKey) || config.isReservedAttr(hyphenatedKey)) { warn( ("\"" + hyphenatedKey + "\" is a reserved attribute and cannot be used as component prop."), vm ); } defineReactive(props, key, value, function () { if (vm.$parent && !isUpdatingChildComponent) { warn( "Avoid mutating a prop directly since the value will be " + "overwritten whenever the parent component re-renders. " + "Instead, use a data or computed property based on the prop's " + "value. Prop being mutated: \"" + key + "\"", vm ); } }); } else { defineReactive(props, key, value); } // static props are already proxied on the component's prototype // during Vue.extend(). We only need to proxy props defined at // instantiation here. if (!(key in vm)) { proxy(vm, "_props", key); } }; for (var key in propsOptions) loop( key ); observerState.shouldConvert = true; } function initData (vm) { var data = vm.$options.data; data = vm._data = typeof data === 'function' ? getData(data, vm) : data || {}; if (!isPlainObject(data)) { data = {}; process.env.NODE_ENV !== 'production' && warn( 'data functions should return an object:\n' + 'https://vuejs.org/v2/guide/components.html#data-Must-Be-a-Function', vm ); } // proxy data on instance var keys = Object.keys(data); var props = vm.$options.props; var methods = vm.$options.methods; var i = keys.length; while (i--) { var key = keys[i]; if (process.env.NODE_ENV !== 'production') { if (methods && hasOwn(methods, key)) { warn( ("Method \"" + key + "\" has already been defined as a data property."), vm ); } } if (props && hasOwn(props, key)) { process.env.NODE_ENV !== 'production' && warn( "The data property \"" + key + "\" is already declared as a prop. " + "Use prop default value instead.", vm ); } else if (!isReserved(key)) { proxy(vm, "_data", key); } } // observe data observe(data, true /* asRootData */); } function getData (data, vm) { try { return data.call(vm, vm) } catch (e) { handleError(e, vm, "data()"); return {} } } var computedWatcherOptions = { lazy: true }; function initComputed (vm, computed) { var watchers = vm._computedWatchers = Object.create(null); // computed properties are just getters during SSR var isSSR = isServerRendering(); for (var key in computed) { var userDef = computed[key]; var getter = typeof userDef === 'function' ? userDef : userDef.get; if (process.env.NODE_ENV !== 'production' && getter == null) { warn( ("Getter is missing for computed property \"" + key + "\"."), vm ); } if (!isSSR) { // create internal watcher for the computed property. watchers[key] = new Watcher( vm, getter || noop, noop, computedWatcherOptions ); } // component-defined computed properties are already defined on the // component prototype. We only need to define computed properties defined // at instantiation here. if (!(key in vm)) { defineComputed(vm, key, userDef); } else if (process.env.NODE_ENV !== 'production') { if (key in vm.$data) { warn(("The computed property \"" + key + "\" is already defined in data."), vm); } else if (vm.$options.props && key in vm.$options.props) { warn(("The computed property \"" + key + "\" is already defined as a prop."), vm); } } } } function defineComputed ( target, key, userDef ) { var shouldCache = !isServerRendering(); if (typeof userDef === 'function') { sharedPropertyDefinition.get = shouldCache ? createComputedGetter(key) : userDef; sharedPropertyDefinition.set = noop; } else { sharedPropertyDefinition.get = userDef.get ? shouldCache && userDef.cache !== false ? createComputedGetter(key) : userDef.get : noop; sharedPropertyDefinition.set = userDef.set ? userDef.set : noop; } if (process.env.NODE_ENV !== 'production' && sharedPropertyDefinition.set === noop) { sharedPropertyDefinition.set = function () { warn( ("Computed property \"" + key + "\" was assigned to but it has no setter."), this ); }; } Object.defineProperty(target, key, sharedPropertyDefinition); } function createComputedGetter (key) { return function computedGetter () { var watcher = this._computedWatchers && this._computedWatchers[key]; if (watcher) { if (watcher.dirty) { watcher.evaluate(); } if (Dep.target) { watcher.depend(); } return watcher.value } } } function initMethods (vm, methods) { var props = vm.$options.props; for (var key in methods) { if (process.env.NODE_ENV !== 'production') { if (methods[key] == null) { warn( "Method \"" + key + "\" has an undefined value in the component definition. " + "Did you reference the function correctly?", vm ); } if (props && hasOwn(props, key)) { warn( ("Method \"" + key + "\" has already been defined as a prop."), vm ); } if ((key in vm) && isReserved(key)) { warn( "Method \"" + key + "\" conflicts with an existing Vue instance method. " + "Avoid defining component methods that start with _ or $." ); } } vm[key] = methods[key] == null ? noop : bind(methods[key], vm); } } function initWatch (vm, watch) { for (var key in watch) { var handler = watch[key]; if (Array.isArray(handler)) { for (var i = 0; i < handler.length; i++) { createWatcher(vm, key, handler[i]); } } else { createWatcher(vm, key, handler); } } } function createWatcher ( vm, keyOrFn, handler, options ) { if (isPlainObject(handler)) { options = handler; handler = handler.handler; } if (typeof handler === 'string') { handler = vm[handler]; } return vm.$watch(keyOrFn, handler, options) } function stateMixin (Vue) { // flow somehow has problems with directly declared definition object // when using Object.defineProperty, so we have to procedurally build up // the object here. var dataDef = {}; dataDef.get = function () { return this._data }; var propsDef = {}; propsDef.get = function () { return this._props }; if (process.env.NODE_ENV !== 'production') { dataDef.set = function (newData) { warn( 'Avoid replacing instance root $data. ' + 'Use nested data properties instead.', this ); }; propsDef.set = function () { warn("$props is readonly.", this); }; } Object.defineProperty(Vue.prototype, '$data', dataDef); Object.defineProperty(Vue.prototype, '$props', propsDef); Vue.prototype.$set = set; Vue.prototype.$delete = del; Vue.prototype.$watch = function ( expOrFn, cb, options ) { var vm = this; if (isPlainObject(cb)) { return createWatcher(vm, expOrFn, cb, options) } options = options || {}; options.user = true; var watcher = new Watcher(vm, expOrFn, cb, options); if (options.immediate) { cb.call(vm, watcher.value); } return function unwatchFn () { watcher.teardown(); } }; } /* */ function initProvide (vm) { var provide = vm.$options.provide; if (provide) { vm._provided = typeof provide === 'function' ? provide.call(vm) : provide; } } function initInjections (vm) { var result = resolveInject(vm.$options.inject, vm); if (result) { observerState.shouldConvert = false; Object.keys(result).forEach(function (key) { /* istanbul ignore else */ if (process.env.NODE_ENV !== 'production') { defineReactive(vm, key, result[key], function () { warn( "Avoid mutating an injected value directly since the changes will be " + "overwritten whenever the provided component re-renders. " + "injection being mutated: \"" + key + "\"", vm ); }); } else { defineReactive(vm, key, result[key]); } }); observerState.shouldConvert = true; } } function resolveInject (inject, vm) { if (inject) { // inject is :any because flow is not smart enough to figure out cached var result = Object.create(null); var keys = hasSymbol ? Reflect.ownKeys(inject).filter(function (key) { /* istanbul ignore next */ return Object.getOwnPropertyDescriptor(inject, key).enumerable }) : Object.keys(inject); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var provideKey = inject[key].from; var source = vm; while (source) { if (source._provided && provideKey in source._provided) { result[key] = source._provided[provideKey]; break } source = source.$parent; } if (!source) { if ('default' in inject[key]) { var provideDefault = inject[key].default; result[key] = typeof provideDefault === 'function' ? provideDefault.call(vm) : provideDefault; } else if (process.env.NODE_ENV !== 'production') { warn(("Injection \"" + key + "\" not found"), vm); } } } return result } } /* */ /** * Runtime helper for rendering v-for lists. */ function renderList ( val, render ) { var ret, i, l, keys, key; if (Array.isArray(val) || typeof val === 'string') { ret = new Array(val.length); for (i = 0, l = val.length; i < l; i++) { ret[i] = render(val[i], i); } } else if (typeof val === 'number') { ret = new Array(val); for (i = 0; i < val; i++) { ret[i] = render(i + 1, i); } } else if (isObject(val)) { keys = Object.keys(val); ret = new Array(keys.length); for (i = 0, l = keys.length; i < l; i++) { key = keys[i]; ret[i] = render(val[key], key, i); } } if (isDef(ret)) { (ret)._isVList = true; } return ret } /* */ /** * Runtime helper for rendering <slot> */ function renderSlot ( name, fallback, props, bindObject ) { var scopedSlotFn = this.$scopedSlots[name]; if (scopedSlotFn) { // scoped slot props = props || {}; if (bindObject) { if (process.env.NODE_ENV !== 'production' && !isObject(bindObject)) { warn( 'slot v-bind without argument expects an Object', this ); } props = extend(extend({}, bindObject), props); } return scopedSlotFn(props) || fallback } else { var slotNodes = this.$slots[name]; // warn duplicate slot usage if (slotNodes && process.env.NODE_ENV !== 'production') { slotNodes._rendered && warn( "Duplicate presence of slot \"" + name + "\" found in the same render tree " + "- this will likely cause render errors.", this ); slotNodes._rendered = true; } return slotNodes || fallback } } /* */ /** * Runtime helper for resolving filters */ function resolveFilter (id) { return resolveAsset(this.$options, 'filters', id, true) || identity } /* */ /** * Runtime helper for checking keyCodes from config. * exposed as Vue.prototype._k * passing in eventKeyName as last argument separately for backwards compat */ function checkKeyCodes ( eventKeyCode, key, builtInAlias, eventKeyName ) { var keyCodes = config.keyCodes[key] || builtInAlias; if (keyCodes) { if (Array.isArray(keyCodes)) { return keyCodes.indexOf(eventKeyCode) === -1 } else { return keyCodes !== eventKeyCode } } else if (eventKeyName) { return hyphenate(eventKeyName) !== key } } /* */ /** * Runtime helper for merging v-bind="object" into a VNode's data. */ function bindObjectProps ( data, tag, value, asProp, isSync ) { if (value) { if (!isObject(value)) { process.env.NODE_ENV !== 'production' && warn( 'v-bind without argument expects an Object or Array value', this ); } else { if (Array.isArray(value)) { value = toObject(value); } var hash; var loop = function ( key ) { if ( key === 'class' || key === 'style' || isReservedAttribute(key) ) { hash = data; } else { var type = data.attrs && data.attrs.type; hash = asProp || config.mustUseProp(tag, type, key) ? data.domProps || (data.domProps = {}) : data.attrs || (data.attrs = {}); } if (!(key in hash)) { hash[key] = value[key]; if (isSync) { var on = data.on || (data.on = {}); on[("update:" + key)] = function ($event) { value[key] = $event; }; } } }; for (var key in value) loop( key ); } } return data } /* */ /** * Runtime helper for rendering static trees. */ function renderStatic ( index, isInFor ) { // static trees can be rendered once and cached on the contructor options // so every instance shares the same cached trees var renderFns = this.$options.staticRenderFns; var cached = renderFns.cached || (renderFns.cached = []); var tree = cached[index]; // if has already-rendered static tree and not inside v-for, // we can reuse the same tree by doing a shallow clone. if (tree && !isInFor) { return Array.isArray(tree) ? cloneVNodes(tree) : cloneVNode(tree) } // otherwise, render a fresh tree. tree = cached[index] = renderFns[index].call(this._renderProxy, null, this); markStatic(tree, ("__static__" + index), false); return tree } /** * Runtime helper for v-once. * Effectively it means marking the node as static with a unique key. */ function markOnce ( tree, index, key ) { markStatic(tree, ("__once__" + index + (key ? ("_" + key) : "")), true); return tree } function markStatic ( tree, key, isOnce ) { if (Array.isArray(tree)) { for (var i = 0; i < tree.length; i++) { if (tree[i] && typeof tree[i] !== 'string') { markStaticNode(tree[i], (key + "_" + i), isOnce); } } } else { markStaticNode(tree, key, isOnce); } } function markStaticNode (node, key, isOnce) { node.isStatic = true; node.key = key; node.isOnce = isOnce; } /* */ function bindObjectListeners (data, value) { if (value) { if (!isPlainObject(value)) { process.env.NODE_ENV !== 'production' && warn( 'v-on without argument expects an Object value', this ); } else { var on = data.on = data.on ? extend({}, data.on) : {}; for (var key in value) { var existing = on[key]; var ours = value[key]; on[key] = existing ? [].concat(existing, ours) : ours; } } } return data } /* */ function installRenderHelpers (target) { target._o = markOnce; target._n = toNumber; target._s = toString; target._l = renderList; target._t = renderSlot; target._q = looseEqual; target._i = looseIndexOf; target._m = renderStatic; target._f = resolveFilter; target._k = checkKeyCodes; target._b = bindObjectProps; target._v = createTextVNode; target._e = createEmptyVNode; target._u = resolveScopedSlots; target._g = bindObjectListeners; } /* */ function FunctionalRenderContext ( data, props, children, parent, Ctor ) { var options = Ctor.options; this.data = data; this.props = props; this.children = children; this.parent = parent; this.listeners = data.on || emptyObject; this.injections = resolveInject(options.inject, parent); this.slots = function () { return resolveSlots(children, parent); }; // ensure the createElement function in functional components // gets a unique context - this is necessary for correct named slot check var contextVm = Object.create(parent); var isCompiled = isTrue(options._compiled); var needNormalization = !isCompiled; // support for compiled functional template if (isCompiled) { // exposing $options for renderStatic() this.$options = options; // pre-resolve slots for renderSlot() this.$slots = this.slots(); this.$scopedSlots = data.scopedSlots || emptyObject; } if (options._scopeId) { this._c = function (a, b, c, d) { var vnode = createElement(contextVm, a, b, c, d, needNormalization); if (vnode) { vnode.functionalScopeId = options._scopeId; vnode.functionalContext = parent; } return vnode }; } else { this._c = function (a, b, c, d) { return createElement(contextVm, a, b, c, d, needNormalization); }; } } installRenderHelpers(FunctionalRenderContext.prototype); function createFunctionalComponent ( Ctor, propsData, data, contextVm, children ) { var options = Ctor.options; var props = {}; var propOptions = options.props; if (isDef(propOptions)) { for (var key in propOptions) { props[key] = validateProp(key, propOptions, propsData || emptyObject); } } else { if (isDef(data.attrs)) { mergeProps(props, data.attrs); } if (isDef(data.props)) { mergeProps(props, data.props); } } var renderContext = new FunctionalRenderContext( data, props, children, contextVm, Ctor ); var vnode = options.render.call(null, renderContext._c, renderContext); if (vnode instanceof VNode) { vnode.functionalContext = contextVm; vnode.functionalOptions = options; if (data.slot) { (vnode.data || (vnode.data = {})).slot = data.slot; } } return vnode } function mergeProps (to, from) { for (var key in from) { to[camelize(key)] = from[key]; } } /* */ // hooks to be invoked on component VNodes during patch var componentVNodeHooks = { init: function init ( vnode, hydrating, parentElm, refElm ) { if (!vnode.componentInstance || vnode.componentInstance._isDestroyed) { var child = vnode.componentInstance = createComponentInstanceForVnode( vnode, activeInstance, parentElm, refElm ); child.$mount(hydrating ? vnode.elm : undefined, hydrating); } else if (vnode.data.keepAlive) { // kept-alive components, treat as a patch var mountedNode = vnode; // work around flow componentVNodeHooks.prepatch(mountedNode, mountedNode); } }, prepatch: function prepatch (oldVnode, vnode) { var options = vnode.componentOptions; var child = vnode.componentInstance = oldVnode.componentInstance; updateChildComponent( child, options.propsData, // updated props options.listeners, // updated listeners vnode, // new parent vnode options.children // new children ); }, insert: function insert (vnode) { var context = vnode.context; var componentInstance = vnode.componentInstance; if (!componentInstance._isMounted) { componentInstance._isMounted = true; callHook(componentInstance, 'mounted'); } if (vnode.data.keepAlive) { if (context._isMounted) { // vue-router#1212 // During updates, a kept-alive component's child components may // change, so directly walking the tree here may call activated hooks // on incorrect children. Instead we push them into a queue which will // be processed after the whole patch process ended. queueActivatedComponent(componentInstance); } else { activateChildComponent(componentInstance, true /* direct */); } } }, destroy: function destroy (vnode) { var componentInstance = vnode.componentInstance; if (!componentInstance._isDestroyed) { if (!vnode.data.keepAlive) { componentInstance.$destroy(); } else { deactivateChildComponent(componentInstance, true /* direct */); } } } }; var hooksToMerge = Object.keys(componentVNodeHooks); function createComponent ( Ctor, data, context, children, tag ) { if (isUndef(Ctor)) { return } var baseCtor = context.$options._base; // plain options object: turn it into a constructor if (isObject(Ctor)) { Ctor = baseCtor.extend(Ctor); } // if at this stage it's not a constructor or an async component factory, // reject. if (typeof Ctor !== 'function') { if (process.env.NODE_ENV !== 'production') { warn(("Invalid Component definition: " + (String(Ctor))), context); } return } // async component var asyncFactory; if (isUndef(Ctor.cid)) { asyncFactory = Ctor; Ctor = resolveAsyncComponent(asyncFactory, baseCtor, context); if (Ctor === undefined) { // return a placeholder node for async component, which is rendered // as a comment node but preserves all the raw information for the node. // the information will be used for async server-rendering and hydration. return createAsyncPlaceholder( asyncFactory, data, context, children, tag ) } } data = data || {}; // resolve constructor options in case global mixins are applied after // component constructor creation resolveConstructorOptions(Ctor); // transform component v-model data into props & events if (isDef(data.model)) { transformModel(Ctor.options, data); } // extract props var propsData = extractPropsFromVNodeData(data, Ctor, tag); // functional component if (isTrue(Ctor.options.functional)) { return createFunctionalComponent(Ctor, propsData, data, context, children) } // extract listeners, since these needs to be treated as // child component listeners instead of DOM listeners var listeners = data.on; // replace with listeners with .native modifier // so it gets processed during parent component patch. data.on = data.nativeOn; if (isTrue(Ctor.options.abstract)) { // abstract components do not keep anything // other than props & listeners & slot // work around flow var slot = data.slot; data = {}; if (slot) { data.slot = slot; } } // merge component management hooks onto the placeholder node mergeHooks(data); // return a placeholder vnode var name = Ctor.options.name || tag; var vnode = new VNode( ("vue-component-" + (Ctor.cid) + (name ? ("-" + name) : '')), data, undefined, undefined, undefined, context, { Ctor: Ctor, propsData: propsData, listeners: listeners, tag: tag, children: children }, asyncFactory ); return vnode } function createComponentInstanceForVnode ( vnode, // we know it's MountedComponentVNode but flow doesn't parent, // activeInstance in lifecycle state parentElm, refElm ) { var vnodeComponentOptions = vnode.componentOptions; var options = { _isComponent: true, parent: parent, propsData: vnodeComponentOptions.propsData, _componentTag: vnodeComponentOptions.tag, _parentVnode: vnode, _parentListeners: vnodeComponentOptions.listeners, _renderChildren: vnodeComponentOptions.children, _parentElm: parentElm || null, _refElm: refElm || null }; // check inline-template render functions var inlineTemplate = vnode.data.inlineTemplate; if (isDef(inlineTemplate)) { options.render = inlineTemplate.render; options.staticRenderFns = inlineTemplate.staticRenderFns; } return new vnodeComponentOptions.Ctor(options) } function mergeHooks (data) { if (!data.hook) { data.hook = {}; } for (var i = 0; i < hooksToMerge.length; i++) { var key = hooksToMerge[i]; var fromParent = data.hook[key]; var ours = componentVNodeHooks[key]; data.hook[key] = fromParent ? mergeHook$1(ours, fromParent) : ours; } } function mergeHook$1 (one, two) { return function (a, b, c, d) { one(a, b, c, d); two(a, b, c, d); } } // transform component v-model info (value and callback) into // prop and event handler respectively. function transformModel (options, data) { var prop = (options.model && options.model.prop) || 'value'; var event = (options.model && options.model.event) || 'input';(data.props || (data.props = {}))[prop] = data.model.value; var on = data.on || (data.on = {}); if (isDef(on[event])) { on[event] = [data.model.callback].concat(on[event]); } else { on[event] = data.model.callback; } } /* */ var SIMPLE_NORMALIZE = 1; var ALWAYS_NORMALIZE = 2; // wrapper function for providing a more flexible interface // without getting yelled at by flow function createElement ( context, tag, data, children, normalizationType, alwaysNormalize ) { if (Array.isArray(data) || isPrimitive(data)) { normalizationType = children; children = data; data = undefined; } if (isTrue(alwaysNormalize)) { normalizationType = ALWAYS_NORMALIZE; } return _createElement(context, tag, data, children, normalizationType) } function _createElement ( context, tag, data, children, normalizationType ) { if (isDef(data) && isDef((data).__ob__)) { process.env.NODE_ENV !== 'production' && warn( "Avoid using observed data object as vnode data: " + (JSON.stringify(data)) + "\n" + 'Always create fresh vnode data objects in each render!', context ); return createEmptyVNode() } // object syntax in v-bind if (isDef(data) && isDef(data.is)) { tag = data.is; } if (!tag) { // in case of component :is set to falsy value return createEmptyVNode() } // warn against non-primitive key if (process.env.NODE_ENV !== 'production' && isDef(data) && isDef(data.key) && !isPrimitive(data.key) ) { warn( 'Avoid using non-primitive value as key, ' + 'use string/number value instead.', context ); } // support single function children as default scoped slot if (Array.isArray(children) && typeof children[0] === 'function' ) { data = data || {}; data.scopedSlots = { default: children[0] }; children.length = 0; } if (normalizationType === ALWAYS_NORMALIZE) { children = normalizeChildren(children); } else if (normalizationType === SIMPLE_NORMALIZE) { children = simpleNormalizeChildren(children); } var vnode, ns; if (typeof tag === 'string') { var Ctor; ns = (context.$vnode && context.$vnode.ns) || config.getTagNamespace(tag); if (config.isReservedTag(tag)) { // platform built-in elements vnode = new VNode( config.parsePlatformTagName(tag), data, children, undefined, undefined, context ); } else if (isDef(Ctor = resolveAsset(context.$options, 'components', tag))) { // component vnode = createComponent(Ctor, data, context, children, tag); } else { // unknown or unlisted namespaced elements // check at runtime because it may get assigned a namespace when its // parent normalizes children vnode = new VNode( tag, data, children, undefined, undefined, context ); } } else { // direct component options / constructor vnode = createComponent(tag, data, context, children); } if (isDef(vnode)) { if (ns) { applyNS(vnode, ns); } return vnode } else { return createEmptyVNode() } } function applyNS (vnode, ns, force) { vnode.ns = ns; if (vnode.tag === 'foreignObject') { // use default namespace inside foreignObject ns = undefined; force = true; } if (isDef(vnode.children)) { for (var i = 0, l = vnode.children.length; i < l; i++) { var child = vnode.children[i]; if (isDef(child.tag) && (isUndef(child.ns) || isTrue(force))) { applyNS(child, ns, force); } } } } /* */ function initRender (vm) { vm._vnode = null; // the root of the child tree var options = vm.$options; var parentVnode = vm.$vnode = options._parentVnode; // the placeholder node in parent tree var renderContext = parentVnode && parentVnode.context; vm.$slots = resolveSlots(options._renderChildren, renderContext); vm.$scopedSlots = emptyObject; // bind the createElement fn to this instance // so that we get proper render context inside it. // args order: tag, data, children, normalizationType, alwaysNormalize // internal version is used by render functions compiled from templates vm._c = function (a, b, c, d) { return createElement(vm, a, b, c, d, false); }; // normalization is always applied for the public version, used in // user-written render functions. vm.$createElement = function (a, b, c, d) { return createElement(vm, a, b, c, d, true); }; // $attrs & $listeners are exposed for easier HOC creation. // they need to be reactive so that HOCs using them are always updated var parentData = parentVnode && parentVnode.data; /* istanbul ignore else */ if (process.env.NODE_ENV !== 'production') { defineReactive(vm, '$attrs', parentData && parentData.attrs || emptyObject, function () { !isUpdatingChildComponent && warn("$attrs is readonly.", vm); }, true); defineReactive(vm, '$listeners', options._parentListeners || emptyObject, function () { !isUpdatingChildComponent && warn("$listeners is readonly.", vm); }, true); } else { defineReactive(vm, '$attrs', parentData && parentData.attrs || emptyObject, null, true); defineReactive(vm, '$listeners', options._parentListeners || emptyObject, null, true); } } function renderMixin (Vue) { // install runtime convenience helpers installRenderHelpers(Vue.prototype); Vue.prototype.$nextTick = function (fn) { return nextTick(fn, this) }; Vue.prototype._render = function () { var vm = this; var ref = vm.$options; var render = ref.render; var _parentVnode = ref._parentVnode; if (vm._isMounted) { // if the parent didn't update, the slot nodes will be the ones from // last render. They need to be cloned to ensure "freshness" for this render. for (var key in vm.$slots) { var slot = vm.$slots[key]; if (slot._rendered) { vm.$slots[key] = cloneVNodes(slot, true /* deep */); } } } vm.$scopedSlots = (_parentVnode && _parentVnode.data.scopedSlots) || emptyObject; // set parent vnode. this allows render functions to have access // to the data on the placeholder node. vm.$vnode = _parentVnode; // render self var vnode; try { vnode = render.call(vm._renderProxy, vm.$createElement); } catch (e) { handleError(e, vm, "render"); // return error render result, // or previous vnode to prevent render error causing blank component /* istanbul ignore else */ if (process.env.NODE_ENV !== 'production') { if (vm.$options.renderError) { try { vnode = vm.$options.renderError.call(vm._renderProxy, vm.$createElement, e); } catch (e) { handleError(e, vm, "renderError"); vnode = vm._vnode; } } else { vnode = vm._vnode; } } else { vnode = vm._vnode; } } // return empty vnode in case the render function errored out if (!(vnode instanceof VNode)) { if (process.env.NODE_ENV !== 'production' && Array.isArray(vnode)) { warn( 'Multiple root nodes returned from render function. Render function ' + 'should return a single root node.', vm ); } vnode = createEmptyVNode(); } // set parent vnode.parent = _parentVnode; return vnode }; } /* */ var uid$1 = 0; function initMixin (Vue) { Vue.prototype._init = function (options) { var vm = this; // a uid vm._uid = uid$1++; var startTag, endTag; /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production' && config.performance && mark) { startTag = "vue-perf-start:" + (vm._uid); endTag = "vue-perf-end:" + (vm._uid); mark(startTag); } // a flag to avoid this being observed vm._isVue = true; // merge options if (options && options._isComponent) { // optimize internal component instantiation // since dynamic options merging is pretty slow, and none of the // internal component options needs special treatment. initInternalComponent(vm, options); } else { vm.$options = mergeOptions( resolveConstructorOptions(vm.constructor), options || {}, vm ); } /* istanbul ignore else */ if (process.env.NODE_ENV !== 'production') { initProxy(vm); } else { vm._renderProxy = vm; } // expose real self vm._self = vm; initLifecycle(vm); initEvents(vm); initRender(vm); callHook(vm, 'beforeCreate'); initInjections(vm); // resolve injections before data/props initState(vm); initProvide(vm); // resolve provide after data/props callHook(vm, 'created'); /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production' && config.performance && mark) { vm._name = formatComponentName(vm, false); mark(endTag); measure(("vue " + (vm._name) + " init"), startTag, endTag); } if (vm.$options.el) { vm.$mount(vm.$options.el); } }; } function initInternalComponent (vm, options) { var opts = vm.$options = Object.create(vm.constructor.options); // doing this because it's faster than dynamic enumeration. opts.parent = options.parent; opts.propsData = options.propsData; opts._parentVnode = options._parentVnode; opts._parentListeners = options._parentListeners; opts._renderChildren = options._renderChildren; opts._componentTag = options._componentTag; opts._parentElm = options._parentElm; opts._refElm = options._refElm; if (options.render) { opts.render = options.render; opts.staticRenderFns = options.staticRenderFns; } } function resolveConstructorOptions (Ctor) { var options = Ctor.options; if (Ctor.super) { var superOptions = resolveConstructorOptions(Ctor.super); var cachedSuperOptions = Ctor.superOptions; if (superOptions !== cachedSuperOptions) { // super option changed, // need to resolve new options. Ctor.superOptions = superOptions; // check if there are any late-modified/attached options (#4976) var modifiedOptions = resolveModifiedOptions(Ctor); // update base extend options if (modifiedOptions) { extend(Ctor.extendOptions, modifiedOptions); } options = Ctor.options = mergeOptions(superOptions, Ctor.extendOptions); if (options.name) { options.components[options.name] = Ctor; } } } return options } function resolveModifiedOptions (Ctor) { var modified; var latest = Ctor.options; var extended = Ctor.extendOptions; var sealed = Ctor.sealedOptions; for (var key in latest) { if (latest[key] !== sealed[key]) { if (!modified) { modified = {}; } modified[key] = dedupe(latest[key], extended[key], sealed[key]); } } return modified } function dedupe (latest, extended, sealed) { // compare latest and sealed to ensure lifecycle hooks won't be duplicated // between merges if (Array.isArray(latest)) { var res = []; sealed = Array.isArray(sealed) ? sealed : [sealed]; extended = Array.isArray(extended) ? extended : [extended]; for (var i = 0; i < latest.length; i++) { // push original options and not sealed options to exclude duplicated options if (extended.indexOf(latest[i]) >= 0 || sealed.indexOf(latest[i]) < 0) { res.push(latest[i]); } } return res } else { return latest } } function Vue$3 (options) { if (process.env.NODE_ENV !== 'production' && !(this instanceof Vue$3) ) { warn('Vue is a constructor and should be called with the `new` keyword'); } this._init(options); } initMixin(Vue$3); stateMixin(Vue$3); eventsMixin(Vue$3); lifecycleMixin(Vue$3); renderMixin(Vue$3); /* */ function initUse (Vue) { Vue.use = function (plugin) { var installedPlugins = (this._installedPlugins || (this._installedPlugins = [])); if (installedPlugins.indexOf(plugin) > -1) { return this } // additional parameters var args = toArray(arguments, 1); args.unshift(this); if (typeof plugin.install === 'function') { plugin.install.apply(plugin, args); } else if (typeof plugin === 'function') { plugin.apply(null, args); } installedPlugins.push(plugin); return this }; } /* */ function initMixin$1 (Vue) { Vue.mixin = function (mixin) { this.options = mergeOptions(this.options, mixin); return this }; } /* */ function initExtend (Vue) { /** * Each instance constructor, including Vue, has a unique * cid. This enables us to create wrapped "child * constructors" for prototypal inheritance and cache them. */ Vue.cid = 0; var cid = 1; /** * Class inheritance */ Vue.extend = function (extendOptions) { extendOptions = extendOptions || {}; var Super = this; var SuperId = Super.cid; var cachedCtors = extendOptions._Ctor || (extendOptions._Ctor = {}); if (cachedCtors[SuperId]) { return cachedCtors[SuperId] } var name = extendOptions.name || Super.options.name; if (process.env.NODE_ENV !== 'production') { if (!/^[a-zA-Z][\w-]*$/.test(name)) { warn( 'Invalid component name: "' + name + '". Component names ' + 'can only contain alphanumeric characters and the hyphen, ' + 'and must start with a letter.' ); } } var Sub = function VueComponent (options) { this._init(options); }; Sub.prototype = Object.create(Super.prototype); Sub.prototype.constructor = Sub; Sub.cid = cid++; Sub.options = mergeOptions( Super.options, extendOptions ); Sub['super'] = Super; // For props and computed properties, we define the proxy getters on // the Vue instances at extension time, on the extended prototype. This // avoids Object.defineProperty calls for each instance created. if (Sub.options.props) { initProps$1(Sub); } if (Sub.options.computed) { initComputed$1(Sub); } // allow further extension/mixin/plugin usage Sub.extend = Super.extend; Sub.mixin = Super.mixin; Sub.use = Super.use; // create asset registers, so extended classes // can have their private assets too. ASSET_TYPES.forEach(function (type) { Sub[type] = Super[type]; }); // enable recursive self-lookup if (name) { Sub.options.components[name] = Sub; } // keep a reference to the super options at extension time. // later at instantiation we can check if Super's options have // been updated. Sub.superOptions = Super.options; Sub.extendOptions = extendOptions; Sub.sealedOptions = extend({}, Sub.options); // cache constructor cachedCtors[SuperId] = Sub; return Sub }; } function initProps$1 (Comp) { var props = Comp.options.props; for (var key in props) { proxy(Comp.prototype, "_props", key); } } function initComputed$1 (Comp) { var computed = Comp.options.computed; for (var key in computed) { defineComputed(Comp.prototype, key, computed[key]); } } /* */ function initAssetRegisters (Vue) { /** * Create asset registration methods. */ ASSET_TYPES.forEach(function (type) { Vue[type] = function ( id, definition ) { if (!definition) { return this.options[type + 's'][id] } else { /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production') { if (type === 'component' && config.isReservedTag(id)) { warn( 'Do not use built-in or reserved HTML elements as component ' + 'id: ' + id ); } } if (type === 'component' && isPlainObject(definition)) { definition.name = definition.name || id; definition = this.options._base.extend(definition); } if (type === 'directive' && typeof definition === 'function') { definition = { bind: definition, update: definition }; } this.options[type + 's'][id] = definition; return definition } }; }); } /* */ function getComponentName (opts) { return opts && (opts.Ctor.options.name || opts.tag) } function matches (pattern, name) { if (Array.isArray(pattern)) { return pattern.indexOf(name) > -1 } else if (typeof pattern === 'string') { return pattern.split(',').indexOf(name) > -1 } else if (isRegExp(pattern)) { return pattern.test(name) } /* istanbul ignore next */ return false } function pruneCache (keepAliveInstance, filter) { var cache = keepAliveInstance.cache; var keys = keepAliveInstance.keys; var _vnode = keepAliveInstance._vnode; for (var key in cache) { var cachedNode = cache[key]; if (cachedNode) { var name = getComponentName(cachedNode.componentOptions); if (name && !filter(name)) { pruneCacheEntry(cache, key, keys, _vnode); } } } } function pruneCacheEntry ( cache, key, keys, current ) { var cached$$1 = cache[key]; if (cached$$1 && cached$$1 !== current) { cached$$1.componentInstance.$destroy(); } cache[key] = null; remove(keys, key); } var patternTypes = [String, RegExp, Array]; var KeepAlive = { name: 'keep-alive', abstract: true, props: { include: patternTypes, exclude: patternTypes, max: [String, Number] }, created: function created () { this.cache = Object.create(null); this.keys = []; }, destroyed: function destroyed () { var this$1 = this; for (var key in this$1.cache) { pruneCacheEntry(this$1.cache, key, this$1.keys); } }, watch: { include: function include (val) { pruneCache(this, function (name) { return matches(val, name); }); }, exclude: function exclude (val) { pruneCache(this, function (name) { return !matches(val, name); }); } }, render: function render () { var vnode = getFirstComponentChild(this.$slots.default); var componentOptions = vnode && vnode.componentOptions; if (componentOptions) { // check pattern var name = getComponentName(componentOptions); if (name && ( (this.include && !matches(this.include, name)) || (this.exclude && matches(this.exclude, name)) )) { return vnode } var ref = this; var cache = ref.cache; var keys = ref.keys; var key = vnode.key == null // same constructor may get registered as different local components // so cid alone is not enough (#3269) ? componentOptions.Ctor.cid + (componentOptions.tag ? ("::" + (componentOptions.tag)) : '') : vnode.key; if (cache[key]) { vnode.componentInstance = cache[key].componentInstance; // make current key freshest remove(keys, key); keys.push(key); } else { cache[key] = vnode; keys.push(key); // prune oldest entry if (this.max && keys.length > parseInt(this.max)) { pruneCacheEntry(cache, keys[0], keys, this._vnode); } } vnode.data.keepAlive = true; } return vnode } }; var builtInComponents = { KeepAlive: KeepAlive }; /* */ function initGlobalAPI (Vue) { // config var configDef = {}; configDef.get = function () { return config; }; if (process.env.NODE_ENV !== 'production') { configDef.set = function () { warn( 'Do not replace the Vue.config object, set individual fields instead.' ); }; } Object.defineProperty(Vue, 'config', configDef); // exposed util methods. // NOTE: these are not considered part of the public API - avoid relying on // them unless you are aware of the risk. Vue.util = { warn: warn, extend: extend, mergeOptions: mergeOptions, defineReactive: defineReactive }; Vue.set = set; Vue.delete = del; Vue.nextTick = nextTick; Vue.options = Object.create(null); ASSET_TYPES.forEach(function (type) { Vue.options[type + 's'] = Object.create(null); }); // this is used to identify the "base" constructor to extend all plain-object // components with in Weex's multi-instance scenarios. Vue.options._base = Vue; extend(Vue.options.components, builtInComponents); initUse(Vue); initMixin$1(Vue); initExtend(Vue); initAssetRegisters(Vue); } initGlobalAPI(Vue$3); Object.defineProperty(Vue$3.prototype, '$isServer', { get: isServerRendering }); Object.defineProperty(Vue$3.prototype, '$ssrContext', { get: function get () { /* istanbul ignore next */ return this.$vnode && this.$vnode.ssrContext } }); Vue$3.version = '2.5.1'; /* */ // these are reserved for web because they are directly compiled away // during template compilation var isReservedAttr = makeMap('style,class'); // attributes that should be using props for binding var acceptValue = makeMap('input,textarea,option,select,progress'); var mustUseProp = function (tag, type, attr) { return ( (attr === 'value' && acceptValue(tag)) && type !== 'button' || (attr === 'selected' && tag === 'option') || (attr === 'checked' && tag === 'input') || (attr === 'muted' && tag === 'video') ) }; var isEnumeratedAttr = makeMap('contenteditable,draggable,spellcheck'); var isBooleanAttr = makeMap( 'allowfullscreen,async,autofocus,autoplay,checked,compact,controls,declare,' + 'default,defaultchecked,defaultmuted,defaultselected,defer,disabled,' + 'enabled,formnovalidate,hidden,indeterminate,inert,ismap,itemscope,loop,multiple,' + 'muted,nohref,noresize,noshade,novalidate,nowrap,open,pauseonexit,readonly,' + 'required,reversed,scoped,seamless,selected,sortable,translate,' + 'truespeed,typemustmatch,visible' ); var xlinkNS = 'http://www.w3.org/1999/xlink'; var isXlink = function (name) { return name.charAt(5) === ':' && name.slice(0, 5) === 'xlink' }; var getXlinkProp = function (name) { return isXlink(name) ? name.slice(6, name.length) : '' }; var isFalsyAttrValue = function (val) { return val == null || val === false }; /* */ function genClassForVnode (vnode) { var data = vnode.data; var parentNode = vnode; var childNode = vnode; while (isDef(childNode.componentInstance)) { childNode = childNode.componentInstance._vnode; if (childNode.data) { data = mergeClassData(childNode.data, data); } } while (isDef(parentNode = parentNode.parent)) { if (parentNode.data) { data = mergeClassData(data, parentNode.data); } } return renderClass(data.staticClass, data.class) } function mergeClassData (child, parent) { return { staticClass: concat(child.staticClass, parent.staticClass), class: isDef(child.class) ? [child.class, parent.class] : parent.class } } function renderClass ( staticClass, dynamicClass ) { if (isDef(staticClass) || isDef(dynamicClass)) { return concat(staticClass, stringifyClass(dynamicClass)) } /* istanbul ignore next */ return '' } function concat (a, b) { return a ? b ? (a + ' ' + b) : a : (b || '') } function stringifyClass (value) { if (Array.isArray(value)) { return stringifyArray(value) } if (isObject(value)) { return stringifyObject(value) } if (typeof value === 'string') { return value } /* istanbul ignore next */ return '' } function stringifyArray (value) { var res = ''; var stringified; for (var i = 0, l = value.length; i < l; i++) { if (isDef(stringified = stringifyClass(value[i])) && stringified !== '') { if (res) { res += ' '; } res += stringified; } } return res } function stringifyObject (value) { var res = ''; for (var key in value) { if (value[key]) { if (res) { res += ' '; } res += key; } } return res } /* */ var namespaceMap = { svg: 'http://www.w3.org/2000/svg', math: 'http://www.w3.org/1998/Math/MathML' }; var isHTMLTag = makeMap( 'html,body,base,head,link,meta,style,title,' + 'address,article,aside,footer,header,h1,h2,h3,h4,h5,h6,hgroup,nav,section,' + 'div,dd,dl,dt,figcaption,figure,picture,hr,img,li,main,ol,p,pre,ul,' + 'a,b,abbr,bdi,bdo,br,cite,code,data,dfn,em,i,kbd,mark,q,rp,rt,rtc,ruby,' + 's,samp,small,span,strong,sub,sup,time,u,var,wbr,area,audio,map,track,video,' + 'embed,object,param,source,canvas,script,noscript,del,ins,' + 'caption,col,colgroup,table,thead,tbody,td,th,tr,' + 'button,datalist,fieldset,form,input,label,legend,meter,optgroup,option,' + 'output,progress,select,textarea,' + 'details,dialog,menu,menuitem,summary,' + 'content,element,shadow,template,blockquote,iframe,tfoot' ); // this map is intentionally selective, only covering SVG elements that may // contain child elements. var isSVG = makeMap( 'svg,animate,circle,clippath,cursor,defs,desc,ellipse,filter,font-face,' + 'foreignObject,g,glyph,image,line,marker,mask,missing-glyph,path,pattern,' + 'polygon,polyline,rect,switch,symbol,text,textpath,tspan,use,view', true ); var isPreTag = function (tag) { return tag === 'pre'; }; var isReservedTag = function (tag) { return isHTMLTag(tag) || isSVG(tag) }; function getTagNamespace (tag) { if (isSVG(tag)) { return 'svg' } // basic support for MathML // note it doesn't support other MathML elements being component roots if (tag === 'math') { return 'math' } } var unknownElementCache = Object.create(null); function isUnknownElement (tag) { /* istanbul ignore if */ if (!inBrowser) { return true } if (isReservedTag(tag)) { return false } tag = tag.toLowerCase(); /* istanbul ignore if */ if (unknownElementCache[tag] != null) { return unknownElementCache[tag] } var el = document.createElement(tag); if (tag.indexOf('-') > -1) { // http://stackoverflow.com/a/28210364/1070244 return (unknownElementCache[tag] = ( el.constructor === window.HTMLUnknownElement || el.constructor === window.HTMLElement )) } else { return (unknownElementCache[tag] = /HTMLUnknownElement/.test(el.toString())) } } var isTextInputType = makeMap('text,number,password,search,email,tel,url'); /* */ /** * Query an element selector if it's not an element already. */ function query (el) { if (typeof el === 'string') { var selected = document.querySelector(el); if (!selected) { process.env.NODE_ENV !== 'production' && warn( 'Cannot find element: ' + el ); return document.createElement('div') } return selected } else { return el } } /* */ function createElement$1 (tagName, vnode) { var elm = document.createElement(tagName); if (tagName !== 'select') { return elm } // false or null will remove the attribute but undefined will not if (vnode.data && vnode.data.attrs && vnode.data.attrs.multiple !== undefined) { elm.setAttribute('multiple', 'multiple'); } return elm } function createElementNS (namespace, tagName) { return document.createElementNS(namespaceMap[namespace], tagName) } function createTextNode (text) { return document.createTextNode(text) } function createComment (text) { return document.createComment(text) } function insertBefore (parentNode, newNode, referenceNode) { parentNode.insertBefore(newNode, referenceNode); } function removeChild (node, child) { node.removeChild(child); } function appendChild (node, child) { node.appendChild(child); } function parentNode (node) { return node.parentNode } function nextSibling (node) { return node.nextSibling } function tagName (node) { return node.tagName } function setTextContent (node, text) { node.textContent = text; } function setAttribute (node, key, val) { node.setAttribute(key, val); } var nodeOps = Object.freeze({ createElement: createElement$1, createElementNS: createElementNS, createTextNode: createTextNode, createComment: createComment, insertBefore: insertBefore, removeChild: removeChild, appendChild: appendChild, parentNode: parentNode, nextSibling: nextSibling, tagName: tagName, setTextContent: setTextContent, setAttribute: setAttribute }); /* */ var ref = { create: function create (_, vnode) { registerRef(vnode); }, update: function update (oldVnode, vnode) { if (oldVnode.data.ref !== vnode.data.ref) { registerRef(oldVnode, true); registerRef(vnode); } }, destroy: function destroy (vnode) { registerRef(vnode, true); } }; function registerRef (vnode, isRemoval) { var key = vnode.data.ref; if (!key) { return } var vm = vnode.context; var ref = vnode.componentInstance || vnode.elm; var refs = vm.$refs; if (isRemoval) { if (Array.isArray(refs[key])) { remove(refs[key], ref); } else if (refs[key] === ref) { refs[key] = undefined; } } else { if (vnode.data.refInFor) { if (!Array.isArray(refs[key])) { refs[key] = [ref]; } else if (refs[key].indexOf(ref) < 0) { // $flow-disable-line refs[key].push(ref); } } else { refs[key] = ref; } } } /** * Virtual DOM patching algorithm based on Snabbdom by * Simon Friis Vindum (@paldepind) * Licensed under the MIT License * https://github.com/paldepind/snabbdom/blob/master/LICENSE * * modified by Evan You (@yyx990803) * * Not type-checking this because this file is perf-critical and the cost * of making flow understand it is not worth it. */ var emptyNode = new VNode('', {}, []); var hooks = ['create', 'activate', 'update', 'remove', 'destroy']; function sameVnode (a, b) { return ( a.key === b.key && ( ( a.tag === b.tag && a.isComment === b.isComment && isDef(a.data) === isDef(b.data) && sameInputType(a, b) ) || ( isTrue(a.isAsyncPlaceholder) && a.asyncFactory === b.asyncFactory && isUndef(b.asyncFactory.error) ) ) ) } function sameInputType (a, b) { if (a.tag !== 'input') { return true } var i; var typeA = isDef(i = a.data) && isDef(i = i.attrs) && i.type; var typeB = isDef(i = b.data) && isDef(i = i.attrs) && i.type; return typeA === typeB || isTextInputType(typeA) && isTextInputType(typeB) } function createKeyToOldIdx (children, beginIdx, endIdx) { var i, key; var map = {}; for (i = beginIdx; i <= endIdx; ++i) { key = children[i].key; if (isDef(key)) { map[key] = i; } } return map } function createPatchFunction (backend) { var i, j; var cbs = {}; var modules = backend.modules; var nodeOps = backend.nodeOps; for (i = 0; i < hooks.length; ++i) { cbs[hooks[i]] = []; for (j = 0; j < modules.length; ++j) { if (isDef(modules[j][hooks[i]])) { cbs[hooks[i]].push(modules[j][hooks[i]]); } } } function emptyNodeAt (elm) { return new VNode(nodeOps.tagName(elm).toLowerCase(), {}, [], undefined, elm) } function createRmCb (childElm, listeners) { function remove () { if (--remove.listeners === 0) { removeNode(childElm); } } remove.listeners = listeners; return remove } function removeNode (el) { var parent = nodeOps.parentNode(el); // element may have already been removed due to v-html / v-text if (isDef(parent)) { nodeOps.removeChild(parent, el); } } var inPre = 0; function createElm (vnode, insertedVnodeQueue, parentElm, refElm, nested) { vnode.isRootInsert = !nested; // for transition enter check if (createComponent(vnode, insertedVnodeQueue, parentElm, refElm)) { return } var data = vnode.data; var children = vnode.children; var tag = vnode.tag; if (isDef(tag)) { if (process.env.NODE_ENV !== 'production') { if (data && data.pre) { inPre++; } if ( !inPre && !vnode.ns && !( config.ignoredElements.length && config.ignoredElements.some(function (ignore) { return isRegExp(ignore) ? ignore.test(tag) : ignore === tag }) ) && config.isUnknownElement(tag) ) { warn( 'Unknown custom element: <' + tag + '> - did you ' + 'register the component correctly? For recursive components, ' + 'make sure to provide the "name" option.', vnode.context ); } } vnode.elm = vnode.ns ? nodeOps.createElementNS(vnode.ns, tag) : nodeOps.createElement(tag, vnode); setScope(vnode); /* istanbul ignore if */ { createChildren(vnode, children, insertedVnodeQueue); if (isDef(data)) { invokeCreateHooks(vnode, insertedVnodeQueue); } insert(parentElm, vnode.elm, refElm); } if (process.env.NODE_ENV !== 'production' && data && data.pre) { inPre--; } } else if (isTrue(vnode.isComment)) { vnode.elm = nodeOps.createComment(vnode.text); insert(parentElm, vnode.elm, refElm); } else { vnode.elm = nodeOps.createTextNode(vnode.text); insert(parentElm, vnode.elm, refElm); } } function createComponent (vnode, insertedVnodeQueue, parentElm, refElm) { var i = vnode.data; if (isDef(i)) { var isReactivated = isDef(vnode.componentInstance) && i.keepAlive; if (isDef(i = i.hook) && isDef(i = i.init)) { i(vnode, false /* hydrating */, parentElm, refElm); } // after calling the init hook, if the vnode is a child component // it should've created a child instance and mounted it. the child // component also has set the placeholder vnode's elm. // in that case we can just return the element and be done. if (isDef(vnode.componentInstance)) { initComponent(vnode, insertedVnodeQueue); if (isTrue(isReactivated)) { reactivateComponent(vnode, insertedVnodeQueue, parentElm, refElm); } return true } } } function initComponent (vnode, insertedVnodeQueue) { if (isDef(vnode.data.pendingInsert)) { insertedVnodeQueue.push.apply(insertedVnodeQueue, vnode.data.pendingInsert); vnode.data.pendingInsert = null; } vnode.elm = vnode.componentInstance.$el; if (isPatchable(vnode)) { invokeCreateHooks(vnode, insertedVnodeQueue); setScope(vnode); } else { // empty component root. // skip all element-related modules except for ref (#3455) registerRef(vnode); // make sure to invoke the insert hook insertedVnodeQueue.push(vnode); } } function reactivateComponent (vnode, insertedVnodeQueue, parentElm, refElm) { var i; // hack for #4339: a reactivated component with inner transition // does not trigger because the inner node's created hooks are not called // again. It's not ideal to involve module-specific logic in here but // there doesn't seem to be a better way to do it. var innerNode = vnode; while (innerNode.componentInstance) { innerNode = innerNode.componentInstance._vnode; if (isDef(i = innerNode.data) && isDef(i = i.transition)) { for (i = 0; i < cbs.activate.length; ++i) { cbs.activate[i](emptyNode, innerNode); } insertedVnodeQueue.push(innerNode); break } } // unlike a newly created component, // a reactivated keep-alive component doesn't insert itself insert(parentElm, vnode.elm, refElm); } function insert (parent, elm, ref$$1) { if (isDef(parent)) { if (isDef(ref$$1)) { if (ref$$1.parentNode === parent) { nodeOps.insertBefore(parent, elm, ref$$1); } } else { nodeOps.appendChild(parent, elm); } } } function createChildren (vnode, children, insertedVnodeQueue) { if (Array.isArray(children)) { for (var i = 0; i < children.length; ++i) { createElm(children[i], insertedVnodeQueue, vnode.elm, null, true); } } else if (isPrimitive(vnode.text)) { nodeOps.appendChild(vnode.elm, nodeOps.createTextNode(vnode.text)); } } function isPatchable (vnode) { while (vnode.componentInstance) { vnode = vnode.componentInstance._vnode; } return isDef(vnode.tag) } function invokeCreateHooks (vnode, insertedVnodeQueue) { for (var i$1 = 0; i$1 < cbs.create.length; ++i$1) { cbs.create[i$1](emptyNode, vnode); } i = vnode.data.hook; // Reuse variable if (isDef(i)) { if (isDef(i.create)) { i.create(emptyNode, vnode); } if (isDef(i.insert)) { insertedVnodeQueue.push(vnode); } } } // set scope id attribute for scoped CSS. // this is implemented as a special case to avoid the overhead // of going through the normal attribute patching process. function setScope (vnode) { var i; if (isDef(i = vnode.functionalScopeId)) { nodeOps.setAttribute(vnode.elm, i, ''); } else { var ancestor = vnode; while (ancestor) { if (isDef(i = ancestor.context) && isDef(i = i.$options._scopeId)) { nodeOps.setAttribute(vnode.elm, i, ''); } ancestor = ancestor.parent; } } // for slot content they should also get the scopeId from the host instance. if (isDef(i = activeInstance) && i !== vnode.context && i !== vnode.functionalContext && isDef(i = i.$options._scopeId) ) { nodeOps.setAttribute(vnode.elm, i, ''); } } function addVnodes (parentElm, refElm, vnodes, startIdx, endIdx, insertedVnodeQueue) { for (; startIdx <= endIdx; ++startIdx) { createElm(vnodes[startIdx], insertedVnodeQueue, parentElm, refElm); } } function invokeDestroyHook (vnode) { var i, j; var data = vnode.data; if (isDef(data)) { if (isDef(i = data.hook) && isDef(i = i.destroy)) { i(vnode); } for (i = 0; i < cbs.destroy.length; ++i) { cbs.destroy[i](vnode); } } if (isDef(i = vnode.children)) { for (j = 0; j < vnode.children.length; ++j) { invokeDestroyHook(vnode.children[j]); } } } function removeVnodes (parentElm, vnodes, startIdx, endIdx) { for (; startIdx <= endIdx; ++startIdx) { var ch = vnodes[startIdx]; if (isDef(ch)) { if (isDef(ch.tag)) { removeAndInvokeRemoveHook(ch); invokeDestroyHook(ch); } else { // Text node removeNode(ch.elm); } } } } function removeAndInvokeRemoveHook (vnode, rm) { if (isDef(rm) || isDef(vnode.data)) { var i; var listeners = cbs.remove.length + 1; if (isDef(rm)) { // we have a recursively passed down rm callback // increase the listeners count rm.listeners += listeners; } else { // directly removing rm = createRmCb(vnode.elm, listeners); } // recursively invoke hooks on child component root node if (isDef(i = vnode.componentInstance) && isDef(i = i._vnode) && isDef(i.data)) { removeAndInvokeRemoveHook(i, rm); } for (i = 0; i < cbs.remove.length; ++i) { cbs.remove[i](vnode, rm); } if (isDef(i = vnode.data.hook) && isDef(i = i.remove)) { i(vnode, rm); } else { rm(); } } else { removeNode(vnode.elm); } } function updateChildren (parentElm, oldCh, newCh, insertedVnodeQueue, removeOnly) { var oldStartIdx = 0; var newStartIdx = 0; var oldEndIdx = oldCh.length - 1; var oldStartVnode = oldCh[0]; var oldEndVnode = oldCh[oldEndIdx]; var newEndIdx = newCh.length - 1; var newStartVnode = newCh[0]; var newEndVnode = newCh[newEndIdx]; var oldKeyToIdx, idxInOld, vnodeToMove, refElm; // removeOnly is a special flag used only by <transition-group> // to ensure removed elements stay in correct relative positions // during leaving transitions var canMove = !removeOnly; while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) { if (isUndef(oldStartVnode)) { oldStartVnode = oldCh[++oldStartIdx]; // Vnode has been moved left } else if (isUndef(oldEndVnode)) { oldEndVnode = oldCh[--oldEndIdx]; } else if (sameVnode(oldStartVnode, newStartVnode)) { patchVnode(oldStartVnode, newStartVnode, insertedVnodeQueue); oldStartVnode = oldCh[++oldStartIdx]; newStartVnode = newCh[++newStartIdx]; } else if (sameVnode(oldEndVnode, newEndVnode)) { patchVnode(oldEndVnode, newEndVnode, insertedVnodeQueue); oldEndVnode = oldCh[--oldEndIdx]; newEndVnode = newCh[--newEndIdx]; } else if (sameVnode(oldStartVnode, newEndVnode)) { // Vnode moved right patchVnode(oldStartVnode, newEndVnode, insertedVnodeQueue); canMove && nodeOps.insertBefore(parentElm, oldStartVnode.elm, nodeOps.nextSibling(oldEndVnode.elm)); oldStartVnode = oldCh[++oldStartIdx]; newEndVnode = newCh[--newEndIdx]; } else if (sameVnode(oldEndVnode, newStartVnode)) { // Vnode moved left patchVnode(oldEndVnode, newStartVnode, insertedVnodeQueue); canMove && nodeOps.insertBefore(parentElm, oldEndVnode.elm, oldStartVnode.elm); oldEndVnode = oldCh[--oldEndIdx]; newStartVnode = newCh[++newStartIdx]; } else { if (isUndef(oldKeyToIdx)) { oldKeyToIdx = createKeyToOldIdx(oldCh, oldStartIdx, oldEndIdx); } idxInOld = isDef(newStartVnode.key) ? oldKeyToIdx[newStartVnode.key] : findIdxInOld(newStartVnode, oldCh, oldStartIdx, oldEndIdx); if (isUndef(idxInOld)) { // New element createElm(newStartVnode, insertedVnodeQueue, parentElm, oldStartVnode.elm); } else { vnodeToMove = oldCh[idxInOld]; /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production' && !vnodeToMove) { warn( 'It seems there are duplicate keys that is causing an update error. ' + 'Make sure each v-for item has a unique key.' ); } if (sameVnode(vnodeToMove, newStartVnode)) { patchVnode(vnodeToMove, newStartVnode, insertedVnodeQueue); oldCh[idxInOld] = undefined; canMove && nodeOps.insertBefore(parentElm, vnodeToMove.elm, oldStartVnode.elm); } else { // same key but different element. treat as new element createElm(newStartVnode, insertedVnodeQueue, parentElm, oldStartVnode.elm); } } newStartVnode = newCh[++newStartIdx]; } } if (oldStartIdx > oldEndIdx) { refElm = isUndef(newCh[newEndIdx + 1]) ? null : newCh[newEndIdx + 1].elm; addVnodes(parentElm, refElm, newCh, newStartIdx, newEndIdx, insertedVnodeQueue); } else if (newStartIdx > newEndIdx) { removeVnodes(parentElm, oldCh, oldStartIdx, oldEndIdx); } } function findIdxInOld (node, oldCh, start, end) { for (var i = start; i < end; i++) { var c = oldCh[i]; if (isDef(c) && sameVnode(node, c)) { return i } } } function patchVnode (oldVnode, vnode, insertedVnodeQueue, removeOnly) { if (oldVnode === vnode) { return } var elm = vnode.elm = oldVnode.elm; if (isTrue(oldVnode.isAsyncPlaceholder)) { if (isDef(vnode.asyncFactory.resolved)) { hydrate(oldVnode.elm, vnode, insertedVnodeQueue); } else { vnode.isAsyncPlaceholder = true; } return } // reuse element for static trees. // note we only do this if the vnode is cloned - // if the new node is not cloned it means the render functions have been // reset by the hot-reload-api and we need to do a proper re-render. if (isTrue(vnode.isStatic) && isTrue(oldVnode.isStatic) && vnode.key === oldVnode.key && (isTrue(vnode.isCloned) || isTrue(vnode.isOnce)) ) { vnode.componentInstance = oldVnode.componentInstance; return } var i; var data = vnode.data; if (isDef(data) && isDef(i = data.hook) && isDef(i = i.prepatch)) { i(oldVnode, vnode); } var oldCh = oldVnode.children; var ch = vnode.children; if (isDef(data) && isPatchable(vnode)) { for (i = 0; i < cbs.update.length; ++i) { cbs.update[i](oldVnode, vnode); } if (isDef(i = data.hook) && isDef(i = i.update)) { i(oldVnode, vnode); } } if (isUndef(vnode.text)) { if (isDef(oldCh) && isDef(ch)) { if (oldCh !== ch) { updateChildren(elm, oldCh, ch, insertedVnodeQueue, removeOnly); } } else if (isDef(ch)) { if (isDef(oldVnode.text)) { nodeOps.setTextContent(elm, ''); } addVnodes(elm, null, ch, 0, ch.length - 1, insertedVnodeQueue); } else if (isDef(oldCh)) { removeVnodes(elm, oldCh, 0, oldCh.length - 1); } else if (isDef(oldVnode.text)) { nodeOps.setTextContent(elm, ''); } } else if (oldVnode.text !== vnode.text) { nodeOps.setTextContent(elm, vnode.text); } if (isDef(data)) { if (isDef(i = data.hook) && isDef(i = i.postpatch)) { i(oldVnode, vnode); } } } function invokeInsertHook (vnode, queue, initial) { // delay insert hooks for component root nodes, invoke them after the // element is really inserted if (isTrue(initial) && isDef(vnode.parent)) { vnode.parent.data.pendingInsert = queue; } else { for (var i = 0; i < queue.length; ++i) { queue[i].data.hook.insert(queue[i]); } } } var bailed = false; // list of modules that can skip create hook during hydration because they // are already rendered on the client or has no need for initialization var isRenderedModule = makeMap('attrs,style,class,staticClass,staticStyle,key'); // Note: this is a browser-only function so we can assume elms are DOM nodes. function hydrate (elm, vnode, insertedVnodeQueue) { if (isTrue(vnode.isComment) && isDef(vnode.asyncFactory)) { vnode.elm = elm; vnode.isAsyncPlaceholder = true; return true } if (process.env.NODE_ENV !== 'production') { if (!assertNodeMatch(elm, vnode)) { return false } } vnode.elm = elm; var tag = vnode.tag; var data = vnode.data; var children = vnode.children; if (isDef(data)) { if (isDef(i = data.hook) && isDef(i = i.init)) { i(vnode, true /* hydrating */); } if (isDef(i = vnode.componentInstance)) { // child component. it should have hydrated its own tree. initComponent(vnode, insertedVnodeQueue); return true } } if (isDef(tag)) { if (isDef(children)) { // empty element, allow client to pick up and populate children if (!elm.hasChildNodes()) { createChildren(vnode, children, insertedVnodeQueue); } else { // v-html and domProps: innerHTML if (isDef(i = data) && isDef(i = i.domProps) && isDef(i = i.innerHTML)) { if (i !== elm.innerHTML) { /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production' && typeof console !== 'undefined' && !bailed ) { bailed = true; console.warn('Parent: ', elm); console.warn('server innerHTML: ', i); console.warn('client innerHTML: ', elm.innerHTML); } return false } } else { // iterate and compare children lists var childrenMatch = true; var childNode = elm.firstChild; for (var i$1 = 0; i$1 < children.length; i$1++) { if (!childNode || !hydrate(childNode, children[i$1], insertedVnodeQueue)) { childrenMatch = false; break } childNode = childNode.nextSibling; } // if childNode is not null, it means the actual childNodes list is // longer than the virtual children list. if (!childrenMatch || childNode) { /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production' && typeof console !== 'undefined' && !bailed ) { bailed = true; console.warn('Parent: ', elm); console.warn('Mismatching childNodes vs. VNodes: ', elm.childNodes, children); } return false } } } } if (isDef(data)) { for (var key in data) { if (!isRenderedModule(key)) { invokeCreateHooks(vnode, insertedVnodeQueue); break } } } } else if (elm.data !== vnode.text) { elm.data = vnode.text; } return true } function assertNodeMatch (node, vnode) { if (isDef(vnode.tag)) { return ( vnode.tag.indexOf('vue-component') === 0 || vnode.tag.toLowerCase() === (node.tagName && node.tagName.toLowerCase()) ) } else { return node.nodeType === (vnode.isComment ? 8 : 3) } } return function patch (oldVnode, vnode, hydrating, removeOnly, parentElm, refElm) { if (isUndef(vnode)) { if (isDef(oldVnode)) { invokeDestroyHook(oldVnode); } return } var isInitialPatch = false; var insertedVnodeQueue = []; if (isUndef(oldVnode)) { // empty mount (likely as component), create new root element isInitialPatch = true; createElm(vnode, insertedVnodeQueue, parentElm, refElm); } else { var isRealElement = isDef(oldVnode.nodeType); if (!isRealElement && sameVnode(oldVnode, vnode)) { // patch existing root node patchVnode(oldVnode, vnode, insertedVnodeQueue, removeOnly); } else { if (isRealElement) { // mounting to a real element // check if this is server-rendered content and if we can perform // a successful hydration. if (oldVnode.nodeType === 1 && oldVnode.hasAttribute(SSR_ATTR)) { oldVnode.removeAttribute(SSR_ATTR); hydrating = true; } if (isTrue(hydrating)) { if (hydrate(oldVnode, vnode, insertedVnodeQueue)) { invokeInsertHook(vnode, insertedVnodeQueue, true); return oldVnode } else if (process.env.NODE_ENV !== 'production') { warn( 'The client-side rendered virtual DOM tree is not matching ' + 'server-rendered content. This is likely caused by incorrect ' + 'HTML markup, for example nesting block-level elements inside ' + '<p>, or missing <tbody>. Bailing hydration and performing ' + 'full client-side render.' ); } } // either not server-rendered, or hydration failed. // create an empty node and replace it oldVnode = emptyNodeAt(oldVnode); } // replacing existing element var oldElm = oldVnode.elm; var parentElm$1 = nodeOps.parentNode(oldElm); createElm( vnode, insertedVnodeQueue, // extremely rare edge case: do not insert if old element is in a // leaving transition. Only happens when combining transition + // keep-alive + HOCs. (#4590) oldElm._leaveCb ? null : parentElm$1, nodeOps.nextSibling(oldElm) ); if (isDef(vnode.parent)) { // component root element replaced. // update parent placeholder node element, recursively var ancestor = vnode.parent; var patchable = isPatchable(vnode); while (ancestor) { for (var i = 0; i < cbs.destroy.length; ++i) { cbs.destroy[i](ancestor); } ancestor.elm = vnode.elm; if (patchable) { for (var i$1 = 0; i$1 < cbs.create.length; ++i$1) { cbs.create[i$1](emptyNode, ancestor); } // #6513 // invoke insert hooks that may have been merged by create hooks. // e.g. for directives that uses the "inserted" hook. var insert = ancestor.data.hook.insert; if (insert.merged) { // start at index 1 to avoid re-invoking component mounted hook for (var i$2 = 1; i$2 < insert.fns.length; i$2++) { insert.fns[i$2](); } } } else { registerRef(ancestor); } ancestor = ancestor.parent; } } if (isDef(parentElm$1)) { removeVnodes(parentElm$1, [oldVnode], 0, 0); } else if (isDef(oldVnode.tag)) { invokeDestroyHook(oldVnode); } } } invokeInsertHook(vnode, insertedVnodeQueue, isInitialPatch); return vnode.elm } } /* */ var directives = { create: updateDirectives, update: updateDirectives, destroy: function unbindDirectives (vnode) { updateDirectives(vnode, emptyNode); } }; function updateDirectives (oldVnode, vnode) { if (oldVnode.data.directives || vnode.data.directives) { _update(oldVnode, vnode); } } function _update (oldVnode, vnode) { var isCreate = oldVnode === emptyNode; var isDestroy = vnode === emptyNode; var oldDirs = normalizeDirectives$1(oldVnode.data.directives, oldVnode.context); var newDirs = normalizeDirectives$1(vnode.data.directives, vnode.context); var dirsWithInsert = []; var dirsWithPostpatch = []; var key, oldDir, dir; for (key in newDirs) { oldDir = oldDirs[key]; dir = newDirs[key]; if (!oldDir) { // new directive, bind callHook$1(dir, 'bind', vnode, oldVnode); if (dir.def && dir.def.inserted) { dirsWithInsert.push(dir); } } else { // existing directive, update dir.oldValue = oldDir.value; callHook$1(dir, 'update', vnode, oldVnode); if (dir.def && dir.def.componentUpdated) { dirsWithPostpatch.push(dir); } } } if (dirsWithInsert.length) { var callInsert = function () { for (var i = 0; i < dirsWithInsert.length; i++) { callHook$1(dirsWithInsert[i], 'inserted', vnode, oldVnode); } }; if (isCreate) { mergeVNodeHook(vnode.data.hook || (vnode.data.hook = {}), 'insert', callInsert); } else { callInsert(); } } if (dirsWithPostpatch.length) { mergeVNodeHook(vnode.data.hook || (vnode.data.hook = {}), 'postpatch', function () { for (var i = 0; i < dirsWithPostpatch.length; i++) { callHook$1(dirsWithPostpatch[i], 'componentUpdated', vnode, oldVnode); } }); } if (!isCreate) { for (key in oldDirs) { if (!newDirs[key]) { // no longer present, unbind callHook$1(oldDirs[key], 'unbind', oldVnode, oldVnode, isDestroy); } } } } var emptyModifiers = Object.create(null); function normalizeDirectives$1 ( dirs, vm ) { var res = Object.create(null); if (!dirs) { return res } var i, dir; for (i = 0; i < dirs.length; i++) { dir = dirs[i]; if (!dir.modifiers) { dir.modifiers = emptyModifiers; } res[getRawDirName(dir)] = dir; dir.def = resolveAsset(vm.$options, 'directives', dir.name, true); } return res } function getRawDirName (dir) { return dir.rawName || ((dir.name) + "." + (Object.keys(dir.modifiers || {}).join('.'))) } function callHook$1 (dir, hook, vnode, oldVnode, isDestroy) { var fn = dir.def && dir.def[hook]; if (fn) { try { fn(vnode.elm, dir, vnode, oldVnode, isDestroy); } catch (e) { handleError(e, vnode.context, ("directive " + (dir.name) + " " + hook + " hook")); } } } var baseModules = [ ref, directives ]; /* */ function updateAttrs (oldVnode, vnode) { var opts = vnode.componentOptions; if (isDef(opts) && opts.Ctor.options.inheritAttrs === false) { return } if (isUndef(oldVnode.data.attrs) && isUndef(vnode.data.attrs)) { return } var key, cur, old; var elm = vnode.elm; var oldAttrs = oldVnode.data.attrs || {}; var attrs = vnode.data.attrs || {}; // clone observed objects, as the user probably wants to mutate it if (isDef(attrs.__ob__)) { attrs = vnode.data.attrs = extend({}, attrs); } for (key in attrs) { cur = attrs[key]; old = oldAttrs[key]; if (old !== cur) { setAttr(elm, key, cur); } } // #4391: in IE9, setting type can reset value for input[type=radio] // #6666: IE/Edge forces progress value down to 1 before setting a max /* istanbul ignore if */ if ((isIE9 || isEdge) && attrs.value !== oldAttrs.value) { setAttr(elm, 'value', attrs.value); } for (key in oldAttrs) { if (isUndef(attrs[key])) { if (isXlink(key)) { elm.removeAttributeNS(xlinkNS, getXlinkProp(key)); } else if (!isEnumeratedAttr(key)) { elm.removeAttribute(key); } } } } function setAttr (el, key, value) { if (isBooleanAttr(key)) { // set attribute for blank value // e.g. <option disabled>Select one</option> if (isFalsyAttrValue(value)) { el.removeAttribute(key); } else { // technically allowfullscreen is a boolean attribute for <iframe>, // but Flash expects a value of "true" when used on <embed> tag value = key === 'allowfullscreen' && el.tagName === 'EMBED' ? 'true' : key; el.setAttribute(key, value); } } else if (isEnumeratedAttr(key)) { el.setAttribute(key, isFalsyAttrValue(value) || value === 'false' ? 'false' : 'true'); } else if (isXlink(key)) { if (isFalsyAttrValue(value)) { el.removeAttributeNS(xlinkNS, getXlinkProp(key)); } else { el.setAttributeNS(xlinkNS, key, value); } } else { if (isFalsyAttrValue(value)) { el.removeAttribute(key); } else { el.setAttribute(key, value); } } } var attrs = { create: updateAttrs, update: updateAttrs }; /* */ function updateClass (oldVnode, vnode) { var el = vnode.elm; var data = vnode.data; var oldData = oldVnode.data; if ( isUndef(data.staticClass) && isUndef(data.class) && ( isUndef(oldData) || ( isUndef(oldData.staticClass) && isUndef(oldData.class) ) ) ) { return } var cls = genClassForVnode(vnode); // handle transition classes var transitionClass = el._transitionClasses; if (isDef(transitionClass)) { cls = concat(cls, stringifyClass(transitionClass)); } // set the class if (cls !== el._prevClass) { el.setAttribute('class', cls); el._prevClass = cls; } } var klass = { create: updateClass, update: updateClass }; /* */ var validDivisionCharRE = /[\w).+\-_$\]]/; function parseFilters (exp) { var inSingle = false; var inDouble = false; var inTemplateString = false; var inRegex = false; var curly = 0; var square = 0; var paren = 0; var lastFilterIndex = 0; var c, prev, i, expression, filters; for (i = 0; i < exp.length; i++) { prev = c; c = exp.charCodeAt(i); if (inSingle) { if (c === 0x27 && prev !== 0x5C) { inSingle = false; } } else if (inDouble) { if (c === 0x22 && prev !== 0x5C) { inDouble = false; } } else if (inTemplateString) { if (c === 0x60 && prev !== 0x5C) { inTemplateString = false; } } else if (inRegex) { if (c === 0x2f && prev !== 0x5C) { inRegex = false; } } else if ( c === 0x7C && // pipe exp.charCodeAt(i + 1) !== 0x7C && exp.charCodeAt(i - 1) !== 0x7C && !curly && !square && !paren ) { if (expression === undefined) { // first filter, end of expression lastFilterIndex = i + 1; expression = exp.slice(0, i).trim(); } else { pushFilter(); } } else { switch (c) { case 0x22: inDouble = true; break // " case 0x27: inSingle = true; break // ' case 0x60: inTemplateString = true; break // ` case 0x28: paren++; break // ( case 0x29: paren--; break // ) case 0x5B: square++; break // [ case 0x5D: square--; break // ] case 0x7B: curly++; break // { case 0x7D: curly--; break // } } if (c === 0x2f) { // / var j = i - 1; var p = (void 0); // find first non-whitespace prev char for (; j >= 0; j--) { p = exp.charAt(j); if (p !== ' ') { break } } if (!p || !validDivisionCharRE.test(p)) { inRegex = true; } } } } if (expression === undefined) { expression = exp.slice(0, i).trim(); } else if (lastFilterIndex !== 0) { pushFilter(); } function pushFilter () { (filters || (filters = [])).push(exp.slice(lastFilterIndex, i).trim()); lastFilterIndex = i + 1; } if (filters) { for (i = 0; i < filters.length; i++) { expression = wrapFilter(expression, filters[i]); } } return expression } function wrapFilter (exp, filter) { var i = filter.indexOf('('); if (i < 0) { // _f: resolveFilter return ("_f(\"" + filter + "\")(" + exp + ")") } else { var name = filter.slice(0, i); var args = filter.slice(i + 1); return ("_f(\"" + name + "\")(" + exp + "," + args) } } /* */ function baseWarn (msg) { console.error(("[Vue compiler]: " + msg)); } function pluckModuleFunction ( modules, key ) { return modules ? modules.map(function (m) { return m[key]; }).filter(function (_) { return _; }) : [] } function addProp (el, name, value) { (el.props || (el.props = [])).push({ name: name, value: value }); } function addAttr (el, name, value) { (el.attrs || (el.attrs = [])).push({ name: name, value: value }); } function addDirective ( el, name, rawName, value, arg, modifiers ) { (el.directives || (el.directives = [])).push({ name: name, rawName: rawName, value: value, arg: arg, modifiers: modifiers }); } function addHandler ( el, name, value, modifiers, important, warn ) { // warn prevent and passive modifier /* istanbul ignore if */ if ( process.env.NODE_ENV !== 'production' && warn && modifiers && modifiers.prevent && modifiers.passive ) { warn( 'passive and prevent can\'t be used together. ' + 'Passive handler can\'t prevent default event.' ); } // check capture modifier if (modifiers && modifiers.capture) { delete modifiers.capture; name = '!' + name; // mark the event as captured } if (modifiers && modifiers.once) { delete modifiers.once; name = '~' + name; // mark the event as once } /* istanbul ignore if */ if (modifiers && modifiers.passive) { delete modifiers.passive; name = '&' + name; // mark the event as passive } var events; if (modifiers && modifiers.native) { delete modifiers.native; events = el.nativeEvents || (el.nativeEvents = {}); } else { events = el.events || (el.events = {}); } var newHandler = { value: value, modifiers: modifiers }; var handlers = events[name]; /* istanbul ignore if */ if (Array.isArray(handlers)) { important ? handlers.unshift(newHandler) : handlers.push(newHandler); } else if (handlers) { events[name] = important ? [newHandler, handlers] : [handlers, newHandler]; } else { events[name] = newHandler; } } function getBindingAttr ( el, name, getStatic ) { var dynamicValue = getAndRemoveAttr(el, ':' + name) || getAndRemoveAttr(el, 'v-bind:' + name); if (dynamicValue != null) { return parseFilters(dynamicValue) } else if (getStatic !== false) { var staticValue = getAndRemoveAttr(el, name); if (staticValue != null) { return JSON.stringify(staticValue) } } } // note: this only removes the attr from the Array (attrsList) so that it // doesn't get processed by processAttrs. // By default it does NOT remove it from the map (attrsMap) because the map is // needed during codegen. function getAndRemoveAttr ( el, name, removeFromMap ) { var val; if ((val = el.attrsMap[name]) != null) { var list = el.attrsList; for (var i = 0, l = list.length; i < l; i++) { if (list[i].name === name) { list.splice(i, 1); break } } } if (removeFromMap) { delete el.attrsMap[name]; } return val } /* */ /** * Cross-platform code generation for component v-model */ function genComponentModel ( el, value, modifiers ) { var ref = modifiers || {}; var number = ref.number; var trim = ref.trim; var baseValueExpression = '$$v'; var valueExpression = baseValueExpression; if (trim) { valueExpression = "(typeof " + baseValueExpression + " === 'string'" + "? " + baseValueExpression + ".trim()" + ": " + baseValueExpression + ")"; } if (number) { valueExpression = "_n(" + valueExpression + ")"; } var assignment = genAssignmentCode(value, valueExpression); el.model = { value: ("(" + value + ")"), expression: ("\"" + value + "\""), callback: ("function (" + baseValueExpression + ") {" + assignment + "}") }; } /** * Cross-platform codegen helper for generating v-model value assignment code. */ function genAssignmentCode ( value, assignment ) { var res = parseModel(value); if (res.key === null) { return (value + "=" + assignment) } else { return ("$set(" + (res.exp) + ", " + (res.key) + ", " + assignment + ")") } } /** * Parse a v-model expression into a base path and a final key segment. * Handles both dot-path and possible square brackets. * * Possible cases: * * - test * - test[key] * - test[test1[key]] * - test["a"][key] * - xxx.test[a[a].test1[key]] * - test.xxx.a["asa"][test1[key]] * */ var len; var str; var chr; var index$1; var expressionPos; var expressionEndPos; function parseModel (val) { len = val.length; if (val.indexOf('[') < 0 || val.lastIndexOf(']') < len - 1) { index$1 = val.lastIndexOf('.'); if (index$1 > -1) { return { exp: val.slice(0, index$1), key: '"' + val.slice(index$1 + 1) + '"' } } else { return { exp: val, key: null } } } str = val; index$1 = expressionPos = expressionEndPos = 0; while (!eof()) { chr = next(); /* istanbul ignore if */ if (isStringStart(chr)) { parseString(chr); } else if (chr === 0x5B) { parseBracket(chr); } } return { exp: val.slice(0, expressionPos), key: val.slice(expressionPos + 1, expressionEndPos) } } function next () { return str.charCodeAt(++index$1) } function eof () { return index$1 >= len } function isStringStart (chr) { return chr === 0x22 || chr === 0x27 } function parseBracket (chr) { var inBracket = 1; expressionPos = index$1; while (!eof()) { chr = next(); if (isStringStart(chr)) { parseString(chr); continue } if (chr === 0x5B) { inBracket++; } if (chr === 0x5D) { inBracket--; } if (inBracket === 0) { expressionEndPos = index$1; break } } } function parseString (chr) { var stringQuote = chr; while (!eof()) { chr = next(); if (chr === stringQuote) { break } } } /* */ var warn$1; // in some cases, the event used has to be determined at runtime // so we used some reserved tokens during compile. var RANGE_TOKEN = '__r'; var CHECKBOX_RADIO_TOKEN = '__c'; function model ( el, dir, _warn ) { warn$1 = _warn; var value = dir.value; var modifiers = dir.modifiers; var tag = el.tag; var type = el.attrsMap.type; if (process.env.NODE_ENV !== 'production') { // inputs with type="file" are read only and setting the input's // value will throw an error. if (tag === 'input' && type === 'file') { warn$1( "<" + (el.tag) + " v-model=\"" + value + "\" type=\"file\">:\n" + "File inputs are read only. Use a v-on:change listener instead." ); } } if (el.component) { genComponentModel(el, value, modifiers); // component v-model doesn't need extra runtime return false } else if (tag === 'select') { genSelect(el, value, modifiers); } else if (tag === 'input' && type === 'checkbox') { genCheckboxModel(el, value, modifiers); } else if (tag === 'input' && type === 'radio') { genRadioModel(el, value, modifiers); } else if (tag === 'input' || tag === 'textarea') { genDefaultModel(el, value, modifiers); } else if (!config.isReservedTag(tag)) { genComponentModel(el, value, modifiers); // component v-model doesn't need extra runtime return false } else if (process.env.NODE_ENV !== 'production') { warn$1( "<" + (el.tag) + " v-model=\"" + value + "\">: " + "v-model is not supported on this element type. " + 'If you are working with contenteditable, it\'s recommended to ' + 'wrap a library dedicated for that purpose inside a custom component.' ); } // ensure runtime directive metadata return true } function genCheckboxModel ( el, value, modifiers ) { var number = modifiers && modifiers.number; var valueBinding = getBindingAttr(el, 'value') || 'null'; var trueValueBinding = getBindingAttr(el, 'true-value') || 'true'; var falseValueBinding = getBindingAttr(el, 'false-value') || 'false'; addProp(el, 'checked', "Array.isArray(" + value + ")" + "?_i(" + value + "," + valueBinding + ")>-1" + ( trueValueBinding === 'true' ? (":(" + value + ")") : (":_q(" + value + "," + trueValueBinding + ")") ) ); addHandler(el, 'change', "var $$a=" + value + "," + '$$el=$event.target,' + "$$c=$$el.checked?(" + trueValueBinding + "):(" + falseValueBinding + ");" + 'if(Array.isArray($$a)){' + "var $$v=" + (number ? '_n(' + valueBinding + ')' : valueBinding) + "," + '$$i=_i($$a,$$v);' + "if($$el.checked){$$i<0&&(" + value + "=$$a.concat([$$v]))}" + "else{$$i>-1&&(" + value + "=$$a.slice(0,$$i).concat($$a.slice($$i+1)))}" + "}else{" + (genAssignmentCode(value, '$$c')) + "}", null, true ); } function genRadioModel ( el, value, modifiers ) { var number = modifiers && modifiers.number; var valueBinding = getBindingAttr(el, 'value') || 'null'; valueBinding = number ? ("_n(" + valueBinding + ")") : valueBinding; addProp(el, 'checked', ("_q(" + value + "," + valueBinding + ")")); addHandler(el, 'change', genAssignmentCode(value, valueBinding), null, true); } function genSelect ( el, value, modifiers ) { var number = modifiers && modifiers.number; var selectedVal = "Array.prototype.filter" + ".call($event.target.options,function(o){return o.selected})" + ".map(function(o){var val = \"_value\" in o ? o._value : o.value;" + "return " + (number ? '_n(val)' : 'val') + "})"; var assignment = '$event.target.multiple ? $$selectedVal : $$selectedVal[0]'; var code = "var $$selectedVal = " + selectedVal + ";"; code = code + " " + (genAssignmentCode(value, assignment)); addHandler(el, 'change', code, null, true); } function genDefaultModel ( el, value, modifiers ) { var type = el.attrsMap.type; var ref = modifiers || {}; var lazy = ref.lazy; var number = ref.number; var trim = ref.trim; var needCompositionGuard = !lazy && type !== 'range'; var event = lazy ? 'change' : type === 'range' ? RANGE_TOKEN : 'input'; var valueExpression = '$event.target.value'; if (trim) { valueExpression = "$event.target.value.trim()"; } if (number) { valueExpression = "_n(" + valueExpression + ")"; } var code = genAssignmentCode(value, valueExpression); if (needCompositionGuard) { code = "if($event.target.composing)return;" + code; } addProp(el, 'value', ("(" + value + ")")); addHandler(el, event, code, null, true); if (trim || number) { addHandler(el, 'blur', '$forceUpdate()'); } } /* */ // normalize v-model event tokens that can only be determined at runtime. // it's important to place the event as the first in the array because // the whole point is ensuring the v-model callback gets called before // user-attached handlers. function normalizeEvents (on) { /* istanbul ignore if */ if (isDef(on[RANGE_TOKEN])) { // IE input[type=range] only supports `change` event var event = isIE ? 'change' : 'input'; on[event] = [].concat(on[RANGE_TOKEN], on[event] || []); delete on[RANGE_TOKEN]; } // This was originally intended to fix #4521 but no longer necessary // after 2.5. Keeping it for backwards compat with generated code from < 2.4 /* istanbul ignore if */ if (isDef(on[CHECKBOX_RADIO_TOKEN])) { on.change = [].concat(on[CHECKBOX_RADIO_TOKEN], on.change || []); delete on[CHECKBOX_RADIO_TOKEN]; } } var target$1; function add$1 ( event, handler, once$$1, capture, passive ) { if (once$$1) { var oldHandler = handler; var _target = target$1; // save current target element in closure handler = function (ev) { var res = arguments.length === 1 ? oldHandler(ev) : oldHandler.apply(null, arguments); if (res !== null) { remove$2(event, handler, capture, _target); } }; } target$1.addEventListener( event, handler, supportsPassive ? { capture: capture, passive: passive } : capture ); } function remove$2 ( event, handler, capture, _target ) { (_target || target$1).removeEventListener(event, handler, capture); } function updateDOMListeners (oldVnode, vnode) { if (isUndef(oldVnode.data.on) && isUndef(vnode.data.on)) { return } var on = vnode.data.on || {}; var oldOn = oldVnode.data.on || {}; target$1 = vnode.elm; normalizeEvents(on); updateListeners(on, oldOn, add$1, remove$2, vnode.context); } var events = { create: updateDOMListeners, update: updateDOMListeners }; /* */ function updateDOMProps (oldVnode, vnode) { if (isUndef(oldVnode.data.domProps) && isUndef(vnode.data.domProps)) { return } var key, cur; var elm = vnode.elm; var oldProps = oldVnode.data.domProps || {}; var props = vnode.data.domProps || {}; // clone observed objects, as the user probably wants to mutate it if (isDef(props.__ob__)) { props = vnode.data.domProps = extend({}, props); } for (key in oldProps) { if (isUndef(props[key])) { elm[key] = ''; } } for (key in props) { cur = props[key]; // ignore children if the node has textContent or innerHTML, // as these will throw away existing DOM nodes and cause removal errors // on subsequent patches (#3360) if (key === 'textContent' || key === 'innerHTML') { if (vnode.children) { vnode.children.length = 0; } if (cur === oldProps[key]) { continue } // #6601 work around Chrome version <= 55 bug where single textNode // replaced by innerHTML/textContent retains its parentNode property if (elm.childNodes.length === 1) { elm.removeChild(elm.childNodes[0]); } } if (key === 'value') { // store value as _value as well since // non-string values will be stringified elm._value = cur; // avoid resetting cursor position when value is the same var strCur = isUndef(cur) ? '' : String(cur); if (shouldUpdateValue(elm, strCur)) { elm.value = strCur; } } else { elm[key] = cur; } } } // check platforms/web/util/attrs.js acceptValue function shouldUpdateValue (elm, checkVal) { return (!elm.composing && ( elm.tagName === 'OPTION' || isDirty(elm, checkVal) || isInputChanged(elm, checkVal) )) } function isDirty (elm, checkVal) { // return true when textbox (.number and .trim) loses focus and its value is // not equal to the updated value var notInFocus = true; // #6157 // work around IE bug when accessing document.activeElement in an iframe try { notInFocus = document.activeElement !== elm; } catch (e) {} return notInFocus && elm.value !== checkVal } function isInputChanged (elm, newVal) { var value = elm.value; var modifiers = elm._vModifiers; // injected by v-model runtime if (isDef(modifiers) && modifiers.number) { return toNumber(value) !== toNumber(newVal) } if (isDef(modifiers) && modifiers.trim) { return value.trim() !== newVal.trim() } return value !== newVal } var domProps = { create: updateDOMProps, update: updateDOMProps }; /* */ var parseStyleText = cached(function (cssText) { var res = {}; var listDelimiter = /;(?![^(]*\))/g; var propertyDelimiter = /:(.+)/; cssText.split(listDelimiter).forEach(function (item) { if (item) { var tmp = item.split(propertyDelimiter); tmp.length > 1 && (res[tmp[0].trim()] = tmp[1].trim()); } }); return res }); // merge static and dynamic style data on the same vnode function normalizeStyleData (data) { var style = normalizeStyleBinding(data.style); // static style is pre-processed into an object during compilation // and is always a fresh object, so it's safe to merge into it return data.staticStyle ? extend(data.staticStyle, style) : style } // normalize possible array / string values into Object function normalizeStyleBinding (bindingStyle) { if (Array.isArray(bindingStyle)) { return toObject(bindingStyle) } if (typeof bindingStyle === 'string') { return parseStyleText(bindingStyle) } return bindingStyle } /** * parent component style should be after child's * so that parent component's style could override it */ function getStyle (vnode, checkChild) { var res = {}; var styleData; if (checkChild) { var childNode = vnode; while (childNode.componentInstance) { childNode = childNode.componentInstance._vnode; if (childNode.data && (styleData = normalizeStyleData(childNode.data))) { extend(res, styleData); } } } if ((styleData = normalizeStyleData(vnode.data))) { extend(res, styleData); } var parentNode = vnode; while ((parentNode = parentNode.parent)) { if (parentNode.data && (styleData = normalizeStyleData(parentNode.data))) { extend(res, styleData); } } return res } /* */ var cssVarRE = /^--/; var importantRE = /\s*!important$/; var setProp = function (el, name, val) { /* istanbul ignore if */ if (cssVarRE.test(name)) { el.style.setProperty(name, val); } else if (importantRE.test(val)) { el.style.setProperty(name, val.replace(importantRE, ''), 'important'); } else { var normalizedName = normalize(name); if (Array.isArray(val)) { // Support values array created by autoprefixer, e.g. // {display: ["-webkit-box", "-ms-flexbox", "flex"]} // Set them one by one, and the browser will only set those it can recognize for (var i = 0, len = val.length; i < len; i++) { el.style[normalizedName] = val[i]; } } else { el.style[normalizedName] = val; } } }; var vendorNames = ['Webkit', 'Moz', 'ms']; var emptyStyle; var normalize = cached(function (prop) { emptyStyle = emptyStyle || document.createElement('div').style; prop = camelize(prop); if (prop !== 'filter' && (prop in emptyStyle)) { return prop } var capName = prop.charAt(0).toUpperCase() + prop.slice(1); for (var i = 0; i < vendorNames.length; i++) { var name = vendorNames[i] + capName; if (name in emptyStyle) { return name } } }); function updateStyle (oldVnode, vnode) { var data = vnode.data; var oldData = oldVnode.data; if (isUndef(data.staticStyle) && isUndef(data.style) && isUndef(oldData.staticStyle) && isUndef(oldData.style) ) { return } var cur, name; var el = vnode.elm; var oldStaticStyle = oldData.staticStyle; var oldStyleBinding = oldData.normalizedStyle || oldData.style || {}; // if static style exists, stylebinding already merged into it when doing normalizeStyleData var oldStyle = oldStaticStyle || oldStyleBinding; var style = normalizeStyleBinding(vnode.data.style) || {}; // store normalized style under a different key for next diff // make sure to clone it if it's reactive, since the user likely wants // to mutate it. vnode.data.normalizedStyle = isDef(style.__ob__) ? extend({}, style) : style; var newStyle = getStyle(vnode, true); for (name in oldStyle) { if (isUndef(newStyle[name])) { setProp(el, name, ''); } } for (name in newStyle) { cur = newStyle[name]; if (cur !== oldStyle[name]) { // ie9 setting to null has no effect, must use empty string setProp(el, name, cur == null ? '' : cur); } } } var style = { create: updateStyle, update: updateStyle }; /* */ /** * Add class with compatibility for SVG since classList is not supported on * SVG elements in IE */ function addClass (el, cls) { /* istanbul ignore if */ if (!cls || !(cls = cls.trim())) { return } /* istanbul ignore else */ if (el.classList) { if (cls.indexOf(' ') > -1) { cls.split(/\s+/).forEach(function (c) { return el.classList.add(c); }); } else { el.classList.add(cls); } } else { var cur = " " + (el.getAttribute('class') || '') + " "; if (cur.indexOf(' ' + cls + ' ') < 0) { el.setAttribute('class', (cur + cls).trim()); } } } /** * Remove class with compatibility for SVG since classList is not supported on * SVG elements in IE */ function removeClass (el, cls) { /* istanbul ignore if */ if (!cls || !(cls = cls.trim())) { return } /* istanbul ignore else */ if (el.classList) { if (cls.indexOf(' ') > -1) { cls.split(/\s+/).forEach(function (c) { return el.classList.remove(c); }); } else { el.classList.remove(cls); } if (!el.classList.length) { el.removeAttribute('class'); } } else { var cur = " " + (el.getAttribute('class') || '') + " "; var tar = ' ' + cls + ' '; while (cur.indexOf(tar) >= 0) { cur = cur.replace(tar, ' '); } cur = cur.trim(); if (cur) { el.setAttribute('class', cur); } else { el.removeAttribute('class'); } } } /* */ function resolveTransition (def) { if (!def) { return } /* istanbul ignore else */ if (typeof def === 'object') { var res = {}; if (def.css !== false) { extend(res, autoCssTransition(def.name || 'v')); } extend(res, def); return res } else if (typeof def === 'string') { return autoCssTransition(def) } } var autoCssTransition = cached(function (name) { return { enterClass: (name + "-enter"), enterToClass: (name + "-enter-to"), enterActiveClass: (name + "-enter-active"), leaveClass: (name + "-leave"), leaveToClass: (name + "-leave-to"), leaveActiveClass: (name + "-leave-active") } }); var hasTransition = inBrowser && !isIE9; var TRANSITION = 'transition'; var ANIMATION = 'animation'; // Transition property/event sniffing var transitionProp = 'transition'; var transitionEndEvent = 'transitionend'; var animationProp = 'animation'; var animationEndEvent = 'animationend'; if (hasTransition) { /* istanbul ignore if */ if (window.ontransitionend === undefined && window.onwebkittransitionend !== undefined ) { transitionProp = 'WebkitTransition'; transitionEndEvent = 'webkitTransitionEnd'; } if (window.onanimationend === undefined && window.onwebkitanimationend !== undefined ) { animationProp = 'WebkitAnimation'; animationEndEvent = 'webkitAnimationEnd'; } } // binding to window is necessary to make hot reload work in IE in strict mode var raf = inBrowser ? window.requestAnimationFrame ? window.requestAnimationFrame.bind(window) : setTimeout : /* istanbul ignore next */ function (fn) { return fn(); }; function nextFrame (fn) { raf(function () { raf(fn); }); } function addTransitionClass (el, cls) { var transitionClasses = el._transitionClasses || (el._transitionClasses = []); if (transitionClasses.indexOf(cls) < 0) { transitionClasses.push(cls); addClass(el, cls); } } function removeTransitionClass (el, cls) { if (el._transitionClasses) { remove(el._transitionClasses, cls); } removeClass(el, cls); } function whenTransitionEnds ( el, expectedType, cb ) { var ref = getTransitionInfo(el, expectedType); var type = ref.type; var timeout = ref.timeout; var propCount = ref.propCount; if (!type) { return cb() } var event = type === TRANSITION ? transitionEndEvent : animationEndEvent; var ended = 0; var end = function () { el.removeEventListener(event, onEnd); cb(); }; var onEnd = function (e) { if (e.target === el) { if (++ended >= propCount) { end(); } } }; setTimeout(function () { if (ended < propCount) { end(); } }, timeout + 1); el.addEventListener(event, onEnd); } var transformRE = /\b(transform|all)(,|$)/; function getTransitionInfo (el, expectedType) { var styles = window.getComputedStyle(el); var transitionDelays = styles[transitionProp + 'Delay'].split(', '); var transitionDurations = styles[transitionProp + 'Duration'].split(', '); var transitionTimeout = getTimeout(transitionDelays, transitionDurations); var animationDelays = styles[animationProp + 'Delay'].split(', '); var animationDurations = styles[animationProp + 'Duration'].split(', '); var animationTimeout = getTimeout(animationDelays, animationDurations); var type; var timeout = 0; var propCount = 0; /* istanbul ignore if */ if (expectedType === TRANSITION) { if (transitionTimeout > 0) { type = TRANSITION; timeout = transitionTimeout; propCount = transitionDurations.length; } } else if (expectedType === ANIMATION) { if (animationTimeout > 0) { type = ANIMATION; timeout = animationTimeout; propCount = animationDurations.length; } } else { timeout = Math.max(transitionTimeout, animationTimeout); type = timeout > 0 ? transitionTimeout > animationTimeout ? TRANSITION : ANIMATION : null; propCount = type ? type === TRANSITION ? transitionDurations.length : animationDurations.length : 0; } var hasTransform = type === TRANSITION && transformRE.test(styles[transitionProp + 'Property']); return { type: type, timeout: timeout, propCount: propCount, hasTransform: hasTransform } } function getTimeout (delays, durations) { /* istanbul ignore next */ while (delays.length < durations.length) { delays = delays.concat(delays); } return Math.max.apply(null, durations.map(function (d, i) { return toMs(d) + toMs(delays[i]) })) } function toMs (s) { return Number(s.slice(0, -1)) * 1000 } /* */ function enter (vnode, toggleDisplay) { var el = vnode.elm; // call leave callback now if (isDef(el._leaveCb)) { el._leaveCb.cancelled = true; el._leaveCb(); } var data = resolveTransition(vnode.data.transition); if (isUndef(data)) { return } /* istanbul ignore if */ if (isDef(el._enterCb) || el.nodeType !== 1) { return } var css = data.css; var type = data.type; var enterClass = data.enterClass; var enterToClass = data.enterToClass; var enterActiveClass = data.enterActiveClass; var appearClass = data.appearClass; var appearToClass = data.appearToClass; var appearActiveClass = data.appearActiveClass; var beforeEnter = data.beforeEnter; var enter = data.enter; var afterEnter = data.afterEnter; var enterCancelled = data.enterCancelled; var beforeAppear = data.beforeAppear; var appear = data.appear; var afterAppear = data.afterAppear; var appearCancelled = data.appearCancelled; var duration = data.duration; // activeInstance will always be the <transition> component managing this // transition. One edge case to check is when the <transition> is placed // as the root node of a child component. In that case we need to check // <transition>'s parent for appear check. var context = activeInstance; var transitionNode = activeInstance.$vnode; while (transitionNode && transitionNode.parent) { transitionNode = transitionNode.parent; context = transitionNode.context; } var isAppear = !context._isMounted || !vnode.isRootInsert; if (isAppear && !appear && appear !== '') { return } var startClass = isAppear && appearClass ? appearClass : enterClass; var activeClass = isAppear && appearActiveClass ? appearActiveClass : enterActiveClass; var toClass = isAppear && appearToClass ? appearToClass : enterToClass; var beforeEnterHook = isAppear ? (beforeAppear || beforeEnter) : beforeEnter; var enterHook = isAppear ? (typeof appear === 'function' ? appear : enter) : enter; var afterEnterHook = isAppear ? (afterAppear || afterEnter) : afterEnter; var enterCancelledHook = isAppear ? (appearCancelled || enterCancelled) : enterCancelled; var explicitEnterDuration = toNumber( isObject(duration) ? duration.enter : duration ); if (process.env.NODE_ENV !== 'production' && explicitEnterDuration != null) { checkDuration(explicitEnterDuration, 'enter', vnode); } var expectsCSS = css !== false && !isIE9; var userWantsControl = getHookArgumentsLength(enterHook); var cb = el._enterCb = once(function () { if (expectsCSS) { removeTransitionClass(el, toClass); removeTransitionClass(el, activeClass); } if (cb.cancelled) { if (expectsCSS) { removeTransitionClass(el, startClass); } enterCancelledHook && enterCancelledHook(el); } else { afterEnterHook && afterEnterHook(el); } el._enterCb = null; }); if (!vnode.data.show) { // remove pending leave element on enter by injecting an insert hook mergeVNodeHook(vnode.data.hook || (vnode.data.hook = {}), 'insert', function () { var parent = el.parentNode; var pendingNode = parent && parent._pending && parent._pending[vnode.key]; if (pendingNode && pendingNode.tag === vnode.tag && pendingNode.elm._leaveCb ) { pendingNode.elm._leaveCb(); } enterHook && enterHook(el, cb); }); } // start enter transition beforeEnterHook && beforeEnterHook(el); if (expectsCSS) { addTransitionClass(el, startClass); addTransitionClass(el, activeClass); nextFrame(function () { addTransitionClass(el, toClass); removeTransitionClass(el, startClass); if (!cb.cancelled && !userWantsControl) { if (isValidDuration(explicitEnterDuration)) { setTimeout(cb, explicitEnterDuration); } else { whenTransitionEnds(el, type, cb); } } }); } if (vnode.data.show) { toggleDisplay && toggleDisplay(); enterHook && enterHook(el, cb); } if (!expectsCSS && !userWantsControl) { cb(); } } function leave (vnode, rm) { var el = vnode.elm; // call enter callback now if (isDef(el._enterCb)) { el._enterCb.cancelled = true; el._enterCb(); } var data = resolveTransition(vnode.data.transition); if (isUndef(data)) { return rm() } /* istanbul ignore if */ if (isDef(el._leaveCb) || el.nodeType !== 1) { return } var css = data.css; var type = data.type; var leaveClass = data.leaveClass; var leaveToClass = data.leaveToClass; var leaveActiveClass = data.leaveActiveClass; var beforeLeave = data.beforeLeave; var leave = data.leave; var afterLeave = data.afterLeave; var leaveCancelled = data.leaveCancelled; var delayLeave = data.delayLeave; var duration = data.duration; var expectsCSS = css !== false && !isIE9; var userWantsControl = getHookArgumentsLength(leave); var explicitLeaveDuration = toNumber( isObject(duration) ? duration.leave : duration ); if (process.env.NODE_ENV !== 'production' && isDef(explicitLeaveDuration)) { checkDuration(explicitLeaveDuration, 'leave', vnode); } var cb = el._leaveCb = once(function () { if (el.parentNode && el.parentNode._pending) { el.parentNode._pending[vnode.key] = null; } if (expectsCSS) { removeTransitionClass(el, leaveToClass); removeTransitionClass(el, leaveActiveClass); } if (cb.cancelled) { if (expectsCSS) { removeTransitionClass(el, leaveClass); } leaveCancelled && leaveCancelled(el); } else { rm(); afterLeave && afterLeave(el); } el._leaveCb = null; }); if (delayLeave) { delayLeave(performLeave); } else { performLeave(); } function performLeave () { // the delayed leave may have already been cancelled if (cb.cancelled) { return } // record leaving element if (!vnode.data.show) { (el.parentNode._pending || (el.parentNode._pending = {}))[(vnode.key)] = vnode; } beforeLeave && beforeLeave(el); if (expectsCSS) { addTransitionClass(el, leaveClass); addTransitionClass(el, leaveActiveClass); nextFrame(function () { addTransitionClass(el, leaveToClass); removeTransitionClass(el, leaveClass); if (!cb.cancelled && !userWantsControl) { if (isValidDuration(explicitLeaveDuration)) { setTimeout(cb, explicitLeaveDuration); } else { whenTransitionEnds(el, type, cb); } } }); } leave && leave(el, cb); if (!expectsCSS && !userWantsControl) { cb(); } } } // only used in dev mode function checkDuration (val, name, vnode) { if (typeof val !== 'number') { warn( "<transition> explicit " + name + " duration is not a valid number - " + "got " + (JSON.stringify(val)) + ".", vnode.context ); } else if (isNaN(val)) { warn( "<transition> explicit " + name + " duration is NaN - " + 'the duration expression might be incorrect.', vnode.context ); } } function isValidDuration (val) { return typeof val === 'number' && !isNaN(val) } /** * Normalize a transition hook's argument length. The hook may be: * - a merged hook (invoker) with the original in .fns * - a wrapped component method (check ._length) * - a plain function (.length) */ function getHookArgumentsLength (fn) { if (isUndef(fn)) { return false } var invokerFns = fn.fns; if (isDef(invokerFns)) { // invoker return getHookArgumentsLength( Array.isArray(invokerFns) ? invokerFns[0] : invokerFns ) } else { return (fn._length || fn.length) > 1 } } function _enter (_, vnode) { if (vnode.data.show !== true) { enter(vnode); } } var transition = inBrowser ? { create: _enter, activate: _enter, remove: function remove$$1 (vnode, rm) { /* istanbul ignore else */ if (vnode.data.show !== true) { leave(vnode, rm); } else { rm(); } } } : {}; var platformModules = [ attrs, klass, events, domProps, style, transition ]; /* */ // the directive module should be applied last, after all // built-in modules have been applied. var modules = platformModules.concat(baseModules); var patch = createPatchFunction({ nodeOps: nodeOps, modules: modules }); /** * Not type checking this file because flow doesn't like attaching * properties to Elements. */ /* istanbul ignore if */ if (isIE9) { // http://www.matts411.com/post/internet-explorer-9-oninput/ document.addEventListener('selectionchange', function () { var el = document.activeElement; if (el && el.vmodel) { trigger(el, 'input'); } }); } var model$1 = { inserted: function inserted (el, binding, vnode) { if (vnode.tag === 'select') { setSelected(el, binding, vnode.context); el._vOptions = [].map.call(el.options, getValue); } else if (vnode.tag === 'textarea' || isTextInputType(el.type)) { el._vModifiers = binding.modifiers; if (!binding.modifiers.lazy) { // Safari < 10.2 & UIWebView doesn't fire compositionend when // switching focus before confirming composition choice // this also fixes the issue where some browsers e.g. iOS Chrome // fires "change" instead of "input" on autocomplete. el.addEventListener('change', onCompositionEnd); if (!isAndroid) { el.addEventListener('compositionstart', onCompositionStart); el.addEventListener('compositionend', onCompositionEnd); } /* istanbul ignore if */ if (isIE9) { el.vmodel = true; } } } }, componentUpdated: function componentUpdated (el, binding, vnode) { if (vnode.tag === 'select') { setSelected(el, binding, vnode.context); // in case the options rendered by v-for have changed, // it's possible that the value is out-of-sync with the rendered options. // detect such cases and filter out values that no longer has a matching // option in the DOM. var prevOptions = el._vOptions; var curOptions = el._vOptions = [].map.call(el.options, getValue); if (curOptions.some(function (o, i) { return !looseEqual(o, prevOptions[i]); })) { // trigger change event if // no matching option found for at least one value var needReset = el.multiple ? binding.value.some(function (v) { return hasNoMatchingOption(v, curOptions); }) : binding.value !== binding.oldValue && hasNoMatchingOption(binding.value, curOptions); if (needReset) { trigger(el, 'change'); } } } } }; function setSelected (el, binding, vm) { actuallySetSelected(el, binding, vm); /* istanbul ignore if */ if (isIE || isEdge) { setTimeout(function () { actuallySetSelected(el, binding, vm); }, 0); } } function actuallySetSelected (el, binding, vm) { var value = binding.value; var isMultiple = el.multiple; if (isMultiple && !Array.isArray(value)) { process.env.NODE_ENV !== 'production' && warn( "<select multiple v-model=\"" + (binding.expression) + "\"> " + "expects an Array value for its binding, but got " + (Object.prototype.toString.call(value).slice(8, -1)), vm ); return } var selected, option; for (var i = 0, l = el.options.length; i < l; i++) { option = el.options[i]; if (isMultiple) { selected = looseIndexOf(value, getValue(option)) > -1; if (option.selected !== selected) { option.selected = selected; } } else { if (looseEqual(getValue(option), value)) { if (el.selectedIndex !== i) { el.selectedIndex = i; } return } } } if (!isMultiple) { el.selectedIndex = -1; } } function hasNoMatchingOption (value, options) { return options.every(function (o) { return !looseEqual(o, value); }) } function getValue (option) { return '_value' in option ? option._value : option.value } function onCompositionStart (e) { e.target.composing = true; } function onCompositionEnd (e) { // prevent triggering an input event for no reason if (!e.target.composing) { return } e.target.composing = false; trigger(e.target, 'input'); } function trigger (el, type) { var e = document.createEvent('HTMLEvents'); e.initEvent(type, true, true); el.dispatchEvent(e); } /* */ // recursively search for possible transition defined inside the component root function locateNode (vnode) { return vnode.componentInstance && (!vnode.data || !vnode.data.transition) ? locateNode(vnode.componentInstance._vnode) : vnode } var show = { bind: function bind (el, ref, vnode) { var value = ref.value; vnode = locateNode(vnode); var transition$$1 = vnode.data && vnode.data.transition; var originalDisplay = el.__vOriginalDisplay = el.style.display === 'none' ? '' : el.style.display; if (value && transition$$1) { vnode.data.show = true; enter(vnode, function () { el.style.display = originalDisplay; }); } else { el.style.display = value ? originalDisplay : 'none'; } }, update: function update (el, ref, vnode) { var value = ref.value; var oldValue = ref.oldValue; /* istanbul ignore if */ if (value === oldValue) { return } vnode = locateNode(vnode); var transition$$1 = vnode.data && vnode.data.transition; if (transition$$1) { vnode.data.show = true; if (value) { enter(vnode, function () { el.style.display = el.__vOriginalDisplay; }); } else { leave(vnode, function () { el.style.display = 'none'; }); } } else { el.style.display = value ? el.__vOriginalDisplay : 'none'; } }, unbind: function unbind ( el, binding, vnode, oldVnode, isDestroy ) { if (!isDestroy) { el.style.display = el.__vOriginalDisplay; } } }; var platformDirectives = { model: model$1, show: show }; /* */ // Provides transition support for a single element/component. // supports transition mode (out-in / in-out) var transitionProps = { name: String, appear: Boolean, css: Boolean, mode: String, type: String, enterClass: String, leaveClass: String, enterToClass: String, leaveToClass: String, enterActiveClass: String, leaveActiveClass: String, appearClass: String, appearActiveClass: String, appearToClass: String, duration: [Number, String, Object] }; // in case the child is also an abstract component, e.g. <keep-alive> // we want to recursively retrieve the real component to be rendered function getRealChild (vnode) { var compOptions = vnode && vnode.componentOptions; if (compOptions && compOptions.Ctor.options.abstract) { return getRealChild(getFirstComponentChild(compOptions.children)) } else { return vnode } } function extractTransitionData (comp) { var data = {}; var options = comp.$options; // props for (var key in options.propsData) { data[key] = comp[key]; } // events. // extract listeners and pass them directly to the transition methods var listeners = options._parentListeners; for (var key$1 in listeners) { data[camelize(key$1)] = listeners[key$1]; } return data } function placeholder (h, rawChild) { if (/\d-keep-alive$/.test(rawChild.tag)) { return h('keep-alive', { props: rawChild.componentOptions.propsData }) } } function hasParentTransition (vnode) { while ((vnode = vnode.parent)) { if (vnode.data.transition) { return true } } } function isSameChild (child, oldChild) { return oldChild.key === child.key && oldChild.tag === child.tag } var Transition = { name: 'transition', props: transitionProps, abstract: true, render: function render (h) { var this$1 = this; var children = this.$options._renderChildren; if (!children) { return } // filter out text nodes (possible whitespaces) children = children.filter(function (c) { return c.tag || isAsyncPlaceholder(c); }); /* istanbul ignore if */ if (!children.length) { return } // warn multiple elements if (process.env.NODE_ENV !== 'production' && children.length > 1) { warn( '<transition> can only be used on a single element. Use ' + '<transition-group> for lists.', this.$parent ); } var mode = this.mode; // warn invalid mode if (process.env.NODE_ENV !== 'production' && mode && mode !== 'in-out' && mode !== 'out-in' ) { warn( 'invalid <transition> mode: ' + mode, this.$parent ); } var rawChild = children[0]; // if this is a component root node and the component's // parent container node also has transition, skip. if (hasParentTransition(this.$vnode)) { return rawChild } // apply transition data to child // use getRealChild() to ignore abstract components e.g. keep-alive var child = getRealChild(rawChild); /* istanbul ignore if */ if (!child) { return rawChild } if (this._leaving) { return placeholder(h, rawChild) } // ensure a key that is unique to the vnode type and to this transition // component instance. This key will be used to remove pending leaving nodes // during entering. var id = "__transition-" + (this._uid) + "-"; child.key = child.key == null ? child.isComment ? id + 'comment' : id + child.tag : isPrimitive(child.key) ? (String(child.key).indexOf(id) === 0 ? child.key : id + child.key) : child.key; var data = (child.data || (child.data = {})).transition = extractTransitionData(this); var oldRawChild = this._vnode; var oldChild = getRealChild(oldRawChild); // mark v-show // so that the transition module can hand over the control to the directive if (child.data.directives && child.data.directives.some(function (d) { return d.name === 'show'; })) { child.data.show = true; } if ( oldChild && oldChild.data && !isSameChild(child, oldChild) && !isAsyncPlaceholder(oldChild) ) { // replace old child transition data with fresh one // important for dynamic transitions! var oldData = oldChild.data.transition = extend({}, data); // handle transition mode if (mode === 'out-in') { // return placeholder node and queue update when leave finishes this._leaving = true; mergeVNodeHook(oldData, 'afterLeave', function () { this$1._leaving = false; this$1.$forceUpdate(); }); return placeholder(h, rawChild) } else if (mode === 'in-out') { if (isAsyncPlaceholder(child)) { return oldRawChild } var delayedLeave; var performLeave = function () { delayedLeave(); }; mergeVNodeHook(data, 'afterEnter', performLeave); mergeVNodeHook(data, 'enterCancelled', performLeave); mergeVNodeHook(oldData, 'delayLeave', function (leave) { delayedLeave = leave; }); } } return rawChild } }; /* */ // Provides transition support for list items. // supports move transitions using the FLIP technique. // Because the vdom's children update algorithm is "unstable" - i.e. // it doesn't guarantee the relative positioning of removed elements, // we force transition-group to update its children into two passes: // in the first pass, we remove all nodes that need to be removed, // triggering their leaving transition; in the second pass, we insert/move // into the final desired state. This way in the second pass removed // nodes will remain where they should be. var props = extend({ tag: String, moveClass: String }, transitionProps); delete props.mode; var TransitionGroup = { props: props, render: function render (h) { var tag = this.tag || this.$vnode.data.tag || 'span'; var map = Object.create(null); var prevChildren = this.prevChildren = this.children; var rawChildren = this.$slots.default || []; var children = this.children = []; var transitionData = extractTransitionData(this); for (var i = 0; i < rawChildren.length; i++) { var c = rawChildren[i]; if (c.tag) { if (c.key != null && String(c.key).indexOf('__vlist') !== 0) { children.push(c); map[c.key] = c ;(c.data || (c.data = {})).transition = transitionData; } else if (process.env.NODE_ENV !== 'production') { var opts = c.componentOptions; var name = opts ? (opts.Ctor.options.name || opts.tag || '') : c.tag; warn(("<transition-group> children must be keyed: <" + name + ">")); } } } if (prevChildren) { var kept = []; var removed = []; for (var i$1 = 0; i$1 < prevChildren.length; i$1++) { var c$1 = prevChildren[i$1]; c$1.data.transition = transitionData; c$1.data.pos = c$1.elm.getBoundingClientRect(); if (map[c$1.key]) { kept.push(c$1); } else { removed.push(c$1); } } this.kept = h(tag, null, kept); this.removed = removed; } return h(tag, null, children) }, beforeUpdate: function beforeUpdate () { // force removing pass this.__patch__( this._vnode, this.kept, false, // hydrating true // removeOnly (!important, avoids unnecessary moves) ); this._vnode = this.kept; }, updated: function updated () { var children = this.prevChildren; var moveClass = this.moveClass || ((this.name || 'v') + '-move'); if (!children.length || !this.hasMove(children[0].elm, moveClass)) { return } // we divide the work into three loops to avoid mixing DOM reads and writes // in each iteration - which helps prevent layout thrashing. children.forEach(callPendingCbs); children.forEach(recordPosition); children.forEach(applyTranslation); // force reflow to put everything in position // assign to this to avoid being removed in tree-shaking // $flow-disable-line this._reflow = document.body.offsetHeight; children.forEach(function (c) { if (c.data.moved) { var el = c.elm; var s = el.style; addTransitionClass(el, moveClass); s.transform = s.WebkitTransform = s.transitionDuration = ''; el.addEventListener(transitionEndEvent, el._moveCb = function cb (e) { if (!e || /transform$/.test(e.propertyName)) { el.removeEventListener(transitionEndEvent, cb); el._moveCb = null; removeTransitionClass(el, moveClass); } }); } }); }, methods: { hasMove: function hasMove (el, moveClass) { /* istanbul ignore if */ if (!hasTransition) { return false } /* istanbul ignore if */ if (this._hasMove) { return this._hasMove } // Detect whether an element with the move class applied has // CSS transitions. Since the element may be inside an entering // transition at this very moment, we make a clone of it and remove // all other transition classes applied to ensure only the move class // is applied. var clone = el.cloneNode(); if (el._transitionClasses) { el._transitionClasses.forEach(function (cls) { removeClass(clone, cls); }); } addClass(clone, moveClass); clone.style.display = 'none'; this.$el.appendChild(clone); var info = getTransitionInfo(clone); this.$el.removeChild(clone); return (this._hasMove = info.hasTransform) } } }; function callPendingCbs (c) { /* istanbul ignore if */ if (c.elm._moveCb) { c.elm._moveCb(); } /* istanbul ignore if */ if (c.elm._enterCb) { c.elm._enterCb(); } } function recordPosition (c) { c.data.newPos = c.elm.getBoundingClientRect(); } function applyTranslation (c) { var oldPos = c.data.pos; var newPos = c.data.newPos; var dx = oldPos.left - newPos.left; var dy = oldPos.top - newPos.top; if (dx || dy) { c.data.moved = true; var s = c.elm.style; s.transform = s.WebkitTransform = "translate(" + dx + "px," + dy + "px)"; s.transitionDuration = '0s'; } } var platformComponents = { Transition: Transition, TransitionGroup: TransitionGroup }; /* */ // install platform specific utils Vue$3.config.mustUseProp = mustUseProp; Vue$3.config.isReservedTag = isReservedTag; Vue$3.config.isReservedAttr = isReservedAttr; Vue$3.config.getTagNamespace = getTagNamespace; Vue$3.config.isUnknownElement = isUnknownElement; // install platform runtime directives & components extend(Vue$3.options.directives, platformDirectives); extend(Vue$3.options.components, platformComponents); // install platform patch function Vue$3.prototype.__patch__ = inBrowser ? patch : noop; // public mount method Vue$3.prototype.$mount = function ( el, hydrating ) { el = el && inBrowser ? query(el) : undefined; return mountComponent(this, el, hydrating) }; // devtools global hook /* istanbul ignore next */ Vue$3.nextTick(function () { if (config.devtools) { if (devtools) { devtools.emit('init', Vue$3); } else if (process.env.NODE_ENV !== 'production' && isChrome) { console[console.info ? 'info' : 'log']( 'Download the Vue Devtools extension for a better development experience:\n' + 'https://github.com/vuejs/vue-devtools' ); } } if (process.env.NODE_ENV !== 'production' && config.productionTip !== false && inBrowser && typeof console !== 'undefined' ) { console[console.info ? 'info' : 'log']( "You are running Vue in development mode.\n" + "Make sure to turn on production mode when deploying for production.\n" + "See more tips at https://vuejs.org/guide/deployment.html" ); } }, 0); /* */ // check whether current browser encodes a char inside attribute values function shouldDecode (content, encoded) { var div = document.createElement('div'); div.innerHTML = "<div a=\"" + content + "\"/>"; return div.innerHTML.indexOf(encoded) > 0 } // #3663 // IE encodes newlines inside attribute values while other browsers don't var shouldDecodeNewlines = inBrowser ? shouldDecode('\n', '&#10;') : false; /* */ var defaultTagRE = /\{\{((?:.|\n)+?)\}\}/g; var regexEscapeRE = /[-.*+?^${}()|[\]\/\\]/g; var buildRegex = cached(function (delimiters) { var open = delimiters[0].replace(regexEscapeRE, '\\$&'); var close = delimiters[1].replace(regexEscapeRE, '\\$&'); return new RegExp(open + '((?:.|\\n)+?)' + close, 'g') }); function parseText ( text, delimiters ) { var tagRE = delimiters ? buildRegex(delimiters) : defaultTagRE; if (!tagRE.test(text)) { return } var tokens = []; var lastIndex = tagRE.lastIndex = 0; var match, index; while ((match = tagRE.exec(text))) { index = match.index; // push text token if (index > lastIndex) { tokens.push(JSON.stringify(text.slice(lastIndex, index))); } // tag token var exp = parseFilters(match[1].trim()); tokens.push(("_s(" + exp + ")")); lastIndex = index + match[0].length; } if (lastIndex < text.length) { tokens.push(JSON.stringify(text.slice(lastIndex))); } return tokens.join('+') } /* */ function transformNode (el, options) { var warn = options.warn || baseWarn; var staticClass = getAndRemoveAttr(el, 'class'); if (process.env.NODE_ENV !== 'production' && staticClass) { var expression = parseText(staticClass, options.delimiters); if (expression) { warn( "class=\"" + staticClass + "\": " + 'Interpolation inside attributes has been removed. ' + 'Use v-bind or the colon shorthand instead. For example, ' + 'instead of <div class="{{ val }}">, use <div :class="val">.' ); } } if (staticClass) { el.staticClass = JSON.stringify(staticClass); } var classBinding = getBindingAttr(el, 'class', false /* getStatic */); if (classBinding) { el.classBinding = classBinding; } } function genData (el) { var data = ''; if (el.staticClass) { data += "staticClass:" + (el.staticClass) + ","; } if (el.classBinding) { data += "class:" + (el.classBinding) + ","; } return data } var klass$1 = { staticKeys: ['staticClass'], transformNode: transformNode, genData: genData }; /* */ function transformNode$1 (el, options) { var warn = options.warn || baseWarn; var staticStyle = getAndRemoveAttr(el, 'style'); if (staticStyle) { /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production') { var expression = parseText(staticStyle, options.delimiters); if (expression) { warn( "style=\"" + staticStyle + "\": " + 'Interpolation inside attributes has been removed. ' + 'Use v-bind or the colon shorthand instead. For example, ' + 'instead of <div style="{{ val }}">, use <div :style="val">.' ); } } el.staticStyle = JSON.stringify(parseStyleText(staticStyle)); } var styleBinding = getBindingAttr(el, 'style', false /* getStatic */); if (styleBinding) { el.styleBinding = styleBinding; } } function genData$1 (el) { var data = ''; if (el.staticStyle) { data += "staticStyle:" + (el.staticStyle) + ","; } if (el.styleBinding) { data += "style:(" + (el.styleBinding) + "),"; } return data } var style$1 = { staticKeys: ['staticStyle'], transformNode: transformNode$1, genData: genData$1 }; /* */ var decoder; var he = { decode: function decode (html) { decoder = decoder || document.createElement('div'); decoder.innerHTML = html; return decoder.textContent } }; /* */ var isUnaryTag = makeMap( 'area,base,br,col,embed,frame,hr,img,input,isindex,keygen,' + 'link,meta,param,source,track,wbr' ); // Elements that you can, intentionally, leave open // (and which close themselves) var canBeLeftOpenTag = makeMap( 'colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr,source' ); // HTML5 tags https://html.spec.whatwg.org/multipage/indices.html#elements-3 // Phrasing Content https://html.spec.whatwg.org/multipage/dom.html#phrasing-content var isNonPhrasingTag = makeMap( 'address,article,aside,base,blockquote,body,caption,col,colgroup,dd,' + 'details,dialog,div,dl,dt,fieldset,figcaption,figure,footer,form,' + 'h1,h2,h3,h4,h5,h6,head,header,hgroup,hr,html,legend,li,menuitem,meta,' + 'optgroup,option,param,rp,rt,source,style,summary,tbody,td,tfoot,th,thead,' + 'title,tr,track' ); /** * Not type-checking this file because it's mostly vendor code. */ /*! * HTML Parser By John Resig (ejohn.org) * Modified by Juriy "kangax" Zaytsev * Original code by Erik Arvidsson, Mozilla Public License * http://erik.eae.net/simplehtmlparser/simplehtmlparser.js */ // Regular Expressions for parsing tags and attributes var attribute = /^\s*([^\s"'<>\/=]+)(?:\s*(=)\s*(?:"([^"]*)"+|'([^']*)'+|([^\s"'=<>`]+)))?/; // could use https://www.w3.org/TR/1999/REC-xml-names-19990114/#NT-QName // but for Vue templates we can enforce a simple charset var ncname = '[a-zA-Z_][\\w\\-\\.]*'; var qnameCapture = "((?:" + ncname + "\\:)?" + ncname + ")"; var startTagOpen = new RegExp(("^<" + qnameCapture)); var startTagClose = /^\s*(\/?)>/; var endTag = new RegExp(("^<\\/" + qnameCapture + "[^>]*>")); var doctype = /^<!DOCTYPE [^>]+>/i; var comment = /^<!--/; var conditionalComment = /^<!\[/; var IS_REGEX_CAPTURING_BROKEN = false; 'x'.replace(/x(.)?/g, function (m, g) { IS_REGEX_CAPTURING_BROKEN = g === ''; }); // Special Elements (can contain anything) var isPlainTextElement = makeMap('script,style,textarea', true); var reCache = {}; var decodingMap = { '&lt;': '<', '&gt;': '>', '&quot;': '"', '&amp;': '&', '&#10;': '\n' }; var encodedAttr = /&(?:lt|gt|quot|amp);/g; var encodedAttrWithNewLines = /&(?:lt|gt|quot|amp|#10);/g; // #5992 var isIgnoreNewlineTag = makeMap('pre,textarea', true); var shouldIgnoreFirstNewline = function (tag, html) { return tag && isIgnoreNewlineTag(tag) && html[0] === '\n'; }; function decodeAttr (value, shouldDecodeNewlines) { var re = shouldDecodeNewlines ? encodedAttrWithNewLines : encodedAttr; return value.replace(re, function (match) { return decodingMap[match]; }) } function parseHTML (html, options) { var stack = []; var expectHTML = options.expectHTML; var isUnaryTag$$1 = options.isUnaryTag || no; var canBeLeftOpenTag$$1 = options.canBeLeftOpenTag || no; var index = 0; var last, lastTag; while (html) { last = html; // Make sure we're not in a plaintext content element like script/style if (!lastTag || !isPlainTextElement(lastTag)) { var textEnd = html.indexOf('<'); if (textEnd === 0) { // Comment: if (comment.test(html)) { var commentEnd = html.indexOf('-->'); if (commentEnd >= 0) { if (options.shouldKeepComment) { options.comment(html.substring(4, commentEnd)); } advance(commentEnd + 3); continue } } // http://en.wikipedia.org/wiki/Conditional_comment#Downlevel-revealed_conditional_comment if (conditionalComment.test(html)) { var conditionalEnd = html.indexOf(']>'); if (conditionalEnd >= 0) { advance(conditionalEnd + 2); continue } } // Doctype: var doctypeMatch = html.match(doctype); if (doctypeMatch) { advance(doctypeMatch[0].length); continue } // End tag: var endTagMatch = html.match(endTag); if (endTagMatch) { var curIndex = index; advance(endTagMatch[0].length); parseEndTag(endTagMatch[1], curIndex, index); continue } // Start tag: var startTagMatch = parseStartTag(); if (startTagMatch) { handleStartTag(startTagMatch); if (shouldIgnoreFirstNewline(lastTag, html)) { advance(1); } continue } } var text = (void 0), rest = (void 0), next = (void 0); if (textEnd >= 0) { rest = html.slice(textEnd); while ( !endTag.test(rest) && !startTagOpen.test(rest) && !comment.test(rest) && !conditionalComment.test(rest) ) { // < in plain text, be forgiving and treat it as text next = rest.indexOf('<', 1); if (next < 0) { break } textEnd += next; rest = html.slice(textEnd); } text = html.substring(0, textEnd); advance(textEnd); } if (textEnd < 0) { text = html; html = ''; } if (options.chars && text) { options.chars(text); } } else { var endTagLength = 0; var stackedTag = lastTag.toLowerCase(); var reStackedTag = reCache[stackedTag] || (reCache[stackedTag] = new RegExp('([\\s\\S]*?)(</' + stackedTag + '[^>]*>)', 'i')); var rest$1 = html.replace(reStackedTag, function (all, text, endTag) { endTagLength = endTag.length; if (!isPlainTextElement(stackedTag) && stackedTag !== 'noscript') { text = text .replace(/<!--([\s\S]*?)-->/g, '$1') .replace(/<!\[CDATA\[([\s\S]*?)]]>/g, '$1'); } if (shouldIgnoreFirstNewline(stackedTag, text)) { text = text.slice(1); } if (options.chars) { options.chars(text); } return '' }); index += html.length - rest$1.length; html = rest$1; parseEndTag(stackedTag, index - endTagLength, index); } if (html === last) { options.chars && options.chars(html); if (process.env.NODE_ENV !== 'production' && !stack.length && options.warn) { options.warn(("Mal-formatted tag at end of template: \"" + html + "\"")); } break } } // Clean up any remaining tags parseEndTag(); function advance (n) { index += n; html = html.substring(n); } function parseStartTag () { var start = html.match(startTagOpen); if (start) { var match = { tagName: start[1], attrs: [], start: index }; advance(start[0].length); var end, attr; while (!(end = html.match(startTagClose)) && (attr = html.match(attribute))) { advance(attr[0].length); match.attrs.push(attr); } if (end) { match.unarySlash = end[1]; advance(end[0].length); match.end = index; return match } } } function handleStartTag (match) { var tagName = match.tagName; var unarySlash = match.unarySlash; if (expectHTML) { if (lastTag === 'p' && isNonPhrasingTag(tagName)) { parseEndTag(lastTag); } if (canBeLeftOpenTag$$1(tagName) && lastTag === tagName) { parseEndTag(tagName); } } var unary = isUnaryTag$$1(tagName) || !!unarySlash; var l = match.attrs.length; var attrs = new Array(l); for (var i = 0; i < l; i++) { var args = match.attrs[i]; // hackish work around FF bug https://bugzilla.mozilla.org/show_bug.cgi?id=369778 if (IS_REGEX_CAPTURING_BROKEN && args[0].indexOf('""') === -1) { if (args[3] === '') { delete args[3]; } if (args[4] === '') { delete args[4]; } if (args[5] === '') { delete args[5]; } } var value = args[3] || args[4] || args[5] || ''; attrs[i] = { name: args[1], value: decodeAttr( value, options.shouldDecodeNewlines ) }; } if (!unary) { stack.push({ tag: tagName, lowerCasedTag: tagName.toLowerCase(), attrs: attrs }); lastTag = tagName; } if (options.start) { options.start(tagName, attrs, unary, match.start, match.end); } } function parseEndTag (tagName, start, end) { var pos, lowerCasedTagName; if (start == null) { start = index; } if (end == null) { end = index; } if (tagName) { lowerCasedTagName = tagName.toLowerCase(); } // Find the closest opened tag of the same type if (tagName) { for (pos = stack.length - 1; pos >= 0; pos--) { if (stack[pos].lowerCasedTag === lowerCasedTagName) { break } } } else { // If no tag name is provided, clean shop pos = 0; } if (pos >= 0) { // Close all the open elements, up the stack for (var i = stack.length - 1; i >= pos; i--) { if (process.env.NODE_ENV !== 'production' && (i > pos || !tagName) && options.warn ) { options.warn( ("tag <" + (stack[i].tag) + "> has no matching end tag.") ); } if (options.end) { options.end(stack[i].tag, start, end); } } // Remove the open elements from the stack stack.length = pos; lastTag = pos && stack[pos - 1].tag; } else if (lowerCasedTagName === 'br') { if (options.start) { options.start(tagName, [], true, start, end); } } else if (lowerCasedTagName === 'p') { if (options.start) { options.start(tagName, [], false, start, end); } if (options.end) { options.end(tagName, start, end); } } } } /* */ var onRE = /^@|^v-on:/; var dirRE = /^v-|^@|^:/; var forAliasRE = /(.*?)\s+(?:in|of)\s+(.*)/; var forIteratorRE = /\((\{[^}]*\}|[^,]*),([^,]*)(?:,([^,]*))?\)/; var argRE = /:(.*)$/; var bindRE = /^:|^v-bind:/; var modifierRE = /\.[^.]+/g; var decodeHTMLCached = cached(he.decode); // configurable state var warn$2; var delimiters; var transforms; var preTransforms; var postTransforms; var platformIsPreTag; var platformMustUseProp; var platformGetTagNamespace; function createASTElement ( tag, attrs, parent ) { return { type: 1, tag: tag, attrsList: attrs, attrsMap: makeAttrsMap(attrs), parent: parent, children: [] } } /** * Convert HTML string to AST. */ function parse ( template, options ) { warn$2 = options.warn || baseWarn; platformIsPreTag = options.isPreTag || no; platformMustUseProp = options.mustUseProp || no; platformGetTagNamespace = options.getTagNamespace || no; transforms = pluckModuleFunction(options.modules, 'transformNode'); preTransforms = pluckModuleFunction(options.modules, 'preTransformNode'); postTransforms = pluckModuleFunction(options.modules, 'postTransformNode'); delimiters = options.delimiters; var stack = []; var preserveWhitespace = options.preserveWhitespace !== false; var root; var currentParent; var inVPre = false; var inPre = false; var warned = false; function warnOnce (msg) { if (!warned) { warned = true; warn$2(msg); } } function endPre (element) { // check pre state if (element.pre) { inVPre = false; } if (platformIsPreTag(element.tag)) { inPre = false; } } parseHTML(template, { warn: warn$2, expectHTML: options.expectHTML, isUnaryTag: options.isUnaryTag, canBeLeftOpenTag: options.canBeLeftOpenTag, shouldDecodeNewlines: options.shouldDecodeNewlines, shouldKeepComment: options.comments, start: function start (tag, attrs, unary) { // check namespace. // inherit parent ns if there is one var ns = (currentParent && currentParent.ns) || platformGetTagNamespace(tag); // handle IE svg bug /* istanbul ignore if */ if (isIE && ns === 'svg') { attrs = guardIESVGBug(attrs); } var element = createASTElement(tag, attrs, currentParent); if (ns) { element.ns = ns; } if (isForbiddenTag(element) && !isServerRendering()) { element.forbidden = true; process.env.NODE_ENV !== 'production' && warn$2( 'Templates should only be responsible for mapping the state to the ' + 'UI. Avoid placing tags with side-effects in your templates, such as ' + "<" + tag + ">" + ', as they will not be parsed.' ); } // apply pre-transforms for (var i = 0; i < preTransforms.length; i++) { element = preTransforms[i](element, options) || element; } if (!inVPre) { processPre(element); if (element.pre) { inVPre = true; } } if (platformIsPreTag(element.tag)) { inPre = true; } if (inVPre) { processRawAttrs(element); } else if (!element.processed) { // structural directives processFor(element); processIf(element); processOnce(element); // element-scope stuff processElement(element, options); } function checkRootConstraints (el) { if (process.env.NODE_ENV !== 'production') { if (el.tag === 'slot' || el.tag === 'template') { warnOnce( "Cannot use <" + (el.tag) + "> as component root element because it may " + 'contain multiple nodes.' ); } if (el.attrsMap.hasOwnProperty('v-for')) { warnOnce( 'Cannot use v-for on stateful component root element because ' + 'it renders multiple elements.' ); } } } // tree management if (!root) { root = element; checkRootConstraints(root); } else if (!stack.length) { // allow root elements with v-if, v-else-if and v-else if (root.if && (element.elseif || element.else)) { checkRootConstraints(element); addIfCondition(root, { exp: element.elseif, block: element }); } else if (process.env.NODE_ENV !== 'production') { warnOnce( "Component template should contain exactly one root element. " + "If you are using v-if on multiple elements, " + "use v-else-if to chain them instead." ); } } if (currentParent && !element.forbidden) { if (element.elseif || element.else) { processIfConditions(element, currentParent); } else if (element.slotScope) { // scoped slot currentParent.plain = false; var name = element.slotTarget || '"default"';(currentParent.scopedSlots || (currentParent.scopedSlots = {}))[name] = element; } else { currentParent.children.push(element); element.parent = currentParent; } } if (!unary) { currentParent = element; stack.push(element); } else { endPre(element); } // apply post-transforms for (var i$1 = 0; i$1 < postTransforms.length; i$1++) { postTransforms[i$1](element, options); } }, end: function end () { // remove trailing whitespace var element = stack[stack.length - 1]; var lastNode = element.children[element.children.length - 1]; if (lastNode && lastNode.type === 3 && lastNode.text === ' ' && !inPre) { element.children.pop(); } // pop stack stack.length -= 1; currentParent = stack[stack.length - 1]; endPre(element); }, chars: function chars (text) { if (!currentParent) { if (process.env.NODE_ENV !== 'production') { if (text === template) { warnOnce( 'Component template requires a root element, rather than just text.' ); } else if ((text = text.trim())) { warnOnce( ("text \"" + text + "\" outside root element will be ignored.") ); } } return } // IE textarea placeholder bug /* istanbul ignore if */ if (isIE && currentParent.tag === 'textarea' && currentParent.attrsMap.placeholder === text ) { return } var children = currentParent.children; text = inPre || text.trim() ? isTextTag(currentParent) ? text : decodeHTMLCached(text) // only preserve whitespace if its not right after a starting tag : preserveWhitespace && children.length ? ' ' : ''; if (text) { var expression; if (!inVPre && text !== ' ' && (expression = parseText(text, delimiters))) { children.push({ type: 2, expression: expression, text: text }); } else if (text !== ' ' || !children.length || children[children.length - 1].text !== ' ') { children.push({ type: 3, text: text }); } } }, comment: function comment (text) { currentParent.children.push({ type: 3, text: text, isComment: true }); } }); return root } function processPre (el) { if (getAndRemoveAttr(el, 'v-pre') != null) { el.pre = true; } } function processRawAttrs (el) { var l = el.attrsList.length; if (l) { var attrs = el.attrs = new Array(l); for (var i = 0; i < l; i++) { attrs[i] = { name: el.attrsList[i].name, value: JSON.stringify(el.attrsList[i].value) }; } } else if (!el.pre) { // non root node in pre blocks with no attributes el.plain = true; } } function processElement (element, options) { processKey(element); // determine whether this is a plain element after // removing structural attributes element.plain = !element.key && !element.attrsList.length; processRef(element); processSlot(element); processComponent(element); for (var i = 0; i < transforms.length; i++) { element = transforms[i](element, options) || element; } processAttrs(element); } function processKey (el) { var exp = getBindingAttr(el, 'key'); if (exp) { if (process.env.NODE_ENV !== 'production' && el.tag === 'template') { warn$2("<template> cannot be keyed. Place the key on real elements instead."); } el.key = exp; } } function processRef (el) { var ref = getBindingAttr(el, 'ref'); if (ref) { el.ref = ref; el.refInFor = checkInFor(el); } } function processFor (el) { var exp; if ((exp = getAndRemoveAttr(el, 'v-for'))) { var inMatch = exp.match(forAliasRE); if (!inMatch) { process.env.NODE_ENV !== 'production' && warn$2( ("Invalid v-for expression: " + exp) ); return } el.for = inMatch[2].trim(); var alias = inMatch[1].trim(); var iteratorMatch = alias.match(forIteratorRE); if (iteratorMatch) { el.alias = iteratorMatch[1].trim(); el.iterator1 = iteratorMatch[2].trim(); if (iteratorMatch[3]) { el.iterator2 = iteratorMatch[3].trim(); } } else { el.alias = alias; } } } function processIf (el) { var exp = getAndRemoveAttr(el, 'v-if'); if (exp) { el.if = exp; addIfCondition(el, { exp: exp, block: el }); } else { if (getAndRemoveAttr(el, 'v-else') != null) { el.else = true; } var elseif = getAndRemoveAttr(el, 'v-else-if'); if (elseif) { el.elseif = elseif; } } } function processIfConditions (el, parent) { var prev = findPrevElement(parent.children); if (prev && prev.if) { addIfCondition(prev, { exp: el.elseif, block: el }); } else if (process.env.NODE_ENV !== 'production') { warn$2( "v-" + (el.elseif ? ('else-if="' + el.elseif + '"') : 'else') + " " + "used on element <" + (el.tag) + "> without corresponding v-if." ); } } function findPrevElement (children) { var i = children.length; while (i--) { if (children[i].type === 1) { return children[i] } else { if (process.env.NODE_ENV !== 'production' && children[i].text !== ' ') { warn$2( "text \"" + (children[i].text.trim()) + "\" between v-if and v-else(-if) " + "will be ignored." ); } children.pop(); } } } function addIfCondition (el, condition) { if (!el.ifConditions) { el.ifConditions = []; } el.ifConditions.push(condition); } function processOnce (el) { var once$$1 = getAndRemoveAttr(el, 'v-once'); if (once$$1 != null) { el.once = true; } } function processSlot (el) { if (el.tag === 'slot') { el.slotName = getBindingAttr(el, 'name'); if (process.env.NODE_ENV !== 'production' && el.key) { warn$2( "`key` does not work on <slot> because slots are abstract outlets " + "and can possibly expand into multiple elements. " + "Use the key on a wrapping element instead." ); } } else { var slotScope; if (el.tag === 'template') { slotScope = getAndRemoveAttr(el, 'scope'); /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production' && slotScope) { warn$2( "the \"scope\" attribute for scoped slots have been deprecated and " + "replaced by \"slot-scope\" since 2.5. The new \"slot-scope\" attribute " + "can also be used on plain elements in addition to <template> to " + "denote scoped slots.", true ); } el.slotScope = slotScope || getAndRemoveAttr(el, 'slot-scope'); } else if ((slotScope = getAndRemoveAttr(el, 'slot-scope'))) { el.slotScope = slotScope; } var slotTarget = getBindingAttr(el, 'slot'); if (slotTarget) { el.slotTarget = slotTarget === '""' ? '"default"' : slotTarget; // preserve slot as an attribute for native shadow DOM compat // only for non-scoped slots. if (!el.slotScope) { addAttr(el, 'slot', slotTarget); } } } } function processComponent (el) { var binding; if ((binding = getBindingAttr(el, 'is'))) { el.component = binding; } if (getAndRemoveAttr(el, 'inline-template') != null) { el.inlineTemplate = true; } } function processAttrs (el) { var list = el.attrsList; var i, l, name, rawName, value, modifiers, isProp; for (i = 0, l = list.length; i < l; i++) { name = rawName = list[i].name; value = list[i].value; if (dirRE.test(name)) { // mark element as dynamic el.hasBindings = true; // modifiers modifiers = parseModifiers(name); if (modifiers) { name = name.replace(modifierRE, ''); } if (bindRE.test(name)) { // v-bind name = name.replace(bindRE, ''); value = parseFilters(value); isProp = false; if (modifiers) { if (modifiers.prop) { isProp = true; name = camelize(name); if (name === 'innerHtml') { name = 'innerHTML'; } } if (modifiers.camel) { name = camelize(name); } if (modifiers.sync) { addHandler( el, ("update:" + (camelize(name))), genAssignmentCode(value, "$event") ); } } if (isProp || ( !el.component && platformMustUseProp(el.tag, el.attrsMap.type, name) )) { addProp(el, name, value); } else { addAttr(el, name, value); } } else if (onRE.test(name)) { // v-on name = name.replace(onRE, ''); addHandler(el, name, value, modifiers, false, warn$2); } else { // normal directives name = name.replace(dirRE, ''); // parse arg var argMatch = name.match(argRE); var arg = argMatch && argMatch[1]; if (arg) { name = name.slice(0, -(arg.length + 1)); } addDirective(el, name, rawName, value, arg, modifiers); if (process.env.NODE_ENV !== 'production' && name === 'model') { checkForAliasModel(el, value); } } } else { // literal attribute if (process.env.NODE_ENV !== 'production') { var expression = parseText(value, delimiters); if (expression) { warn$2( name + "=\"" + value + "\": " + 'Interpolation inside attributes has been removed. ' + 'Use v-bind or the colon shorthand instead. For example, ' + 'instead of <div id="{{ val }}">, use <div :id="val">.' ); } } addAttr(el, name, JSON.stringify(value)); } } } function checkInFor (el) { var parent = el; while (parent) { if (parent.for !== undefined) { return true } parent = parent.parent; } return false } function parseModifiers (name) { var match = name.match(modifierRE); if (match) { var ret = {}; match.forEach(function (m) { ret[m.slice(1)] = true; }); return ret } } function makeAttrsMap (attrs) { var map = {}; for (var i = 0, l = attrs.length; i < l; i++) { if ( process.env.NODE_ENV !== 'production' && map[attrs[i].name] && !isIE && !isEdge ) { warn$2('duplicate attribute: ' + attrs[i].name); } map[attrs[i].name] = attrs[i].value; } return map } // for script (e.g. type="x/template") or style, do not decode content function isTextTag (el) { return el.tag === 'script' || el.tag === 'style' } function isForbiddenTag (el) { return ( el.tag === 'style' || (el.tag === 'script' && ( !el.attrsMap.type || el.attrsMap.type === 'text/javascript' )) ) } var ieNSBug = /^xmlns:NS\d+/; var ieNSPrefix = /^NS\d+:/; /* istanbul ignore next */ function guardIESVGBug (attrs) { var res = []; for (var i = 0; i < attrs.length; i++) { var attr = attrs[i]; if (!ieNSBug.test(attr.name)) { attr.name = attr.name.replace(ieNSPrefix, ''); res.push(attr); } } return res } function checkForAliasModel (el, value) { var _el = el; while (_el) { if (_el.for && _el.alias === value) { warn$2( "<" + (el.tag) + " v-model=\"" + value + "\">: " + "You are binding v-model directly to a v-for iteration alias. " + "This will not be able to modify the v-for source array because " + "writing to the alias is like modifying a function local variable. " + "Consider using an array of objects and use v-model on an object property instead." ); } _el = _el.parent; } } /* */ /** * Expand input[v-model] with dyanmic type bindings into v-if-else chains * Turn this: * <input v-model="data[type]" :type="type"> * into this: * <input v-if="type === 'checkbox'" type="checkbox" v-model="data[type]"> * <input v-else-if="type === 'radio'" type="radio" v-model="data[type]"> * <input v-else :type="type" v-model="data[type]"> */ function preTransformNode (el, options) { if (el.tag === 'input') { var map = el.attrsMap; if (map['v-model'] && (map['v-bind:type'] || map[':type'])) { var typeBinding = getBindingAttr(el, 'type'); var ifCondition = getAndRemoveAttr(el, 'v-if', true); var ifConditionExtra = ifCondition ? ("&&(" + ifCondition + ")") : ""; // 1. checkbox var branch0 = cloneASTElement(el); // process for on the main node processFor(branch0); addRawAttr(branch0, 'type', 'checkbox'); processElement(branch0, options); branch0.processed = true; // prevent it from double-processed branch0.if = "(" + typeBinding + ")==='checkbox'" + ifConditionExtra; addIfCondition(branch0, { exp: branch0.if, block: branch0 }); // 2. add radio else-if condition var branch1 = cloneASTElement(el); getAndRemoveAttr(branch1, 'v-for', true); addRawAttr(branch1, 'type', 'radio'); processElement(branch1, options); addIfCondition(branch0, { exp: "(" + typeBinding + ")==='radio'" + ifConditionExtra, block: branch1 }); // 3. other var branch2 = cloneASTElement(el); getAndRemoveAttr(branch2, 'v-for', true); addRawAttr(branch2, ':type', typeBinding); processElement(branch2, options); addIfCondition(branch0, { exp: ifCondition, block: branch2 }); return branch0 } } } function cloneASTElement (el) { return createASTElement(el.tag, el.attrsList.slice(), el.parent) } function addRawAttr (el, name, value) { el.attrsMap[name] = value; el.attrsList.push({ name: name, value: value }); } var model$2 = { preTransformNode: preTransformNode }; var modules$1 = [ klass$1, style$1, model$2 ]; /* */ function text (el, dir) { if (dir.value) { addProp(el, 'textContent', ("_s(" + (dir.value) + ")")); } } /* */ function html (el, dir) { if (dir.value) { addProp(el, 'innerHTML', ("_s(" + (dir.value) + ")")); } } var directives$1 = { model: model, text: text, html: html }; /* */ var baseOptions = { expectHTML: true, modules: modules$1, directives: directives$1, isPreTag: isPreTag, isUnaryTag: isUnaryTag, mustUseProp: mustUseProp, canBeLeftOpenTag: canBeLeftOpenTag, isReservedTag: isReservedTag, getTagNamespace: getTagNamespace, staticKeys: genStaticKeys(modules$1) }; /* */ var isStaticKey; var isPlatformReservedTag; var genStaticKeysCached = cached(genStaticKeys$1); /** * Goal of the optimizer: walk the generated template AST tree * and detect sub-trees that are purely static, i.e. parts of * the DOM that never needs to change. * * Once we detect these sub-trees, we can: * * 1. Hoist them into constants, so that we no longer need to * create fresh nodes for them on each re-render; * 2. Completely skip them in the patching process. */ function optimize (root, options) { if (!root) { return } isStaticKey = genStaticKeysCached(options.staticKeys || ''); isPlatformReservedTag = options.isReservedTag || no; // first pass: mark all non-static nodes. markStatic$1(root); // second pass: mark static roots. markStaticRoots(root, false); } function genStaticKeys$1 (keys) { return makeMap( 'type,tag,attrsList,attrsMap,plain,parent,children,attrs' + (keys ? ',' + keys : '') ) } function markStatic$1 (node) { node.static = isStatic(node); if (node.type === 1) { // do not make component slot content static. this avoids // 1. components not able to mutate slot nodes // 2. static slot content fails for hot-reloading if ( !isPlatformReservedTag(node.tag) && node.tag !== 'slot' && node.attrsMap['inline-template'] == null ) { return } for (var i = 0, l = node.children.length; i < l; i++) { var child = node.children[i]; markStatic$1(child); if (!child.static) { node.static = false; } } if (node.ifConditions) { for (var i$1 = 1, l$1 = node.ifConditions.length; i$1 < l$1; i$1++) { var block = node.ifConditions[i$1].block; markStatic$1(block); if (!block.static) { node.static = false; } } } } } function markStaticRoots (node, isInFor) { if (node.type === 1) { if (node.static || node.once) { node.staticInFor = isInFor; } // For a node to qualify as a static root, it should have children that // are not just static text. Otherwise the cost of hoisting out will // outweigh the benefits and it's better off to just always render it fresh. if (node.static && node.children.length && !( node.children.length === 1 && node.children[0].type === 3 )) { node.staticRoot = true; return } else { node.staticRoot = false; } if (node.children) { for (var i = 0, l = node.children.length; i < l; i++) { markStaticRoots(node.children[i], isInFor || !!node.for); } } if (node.ifConditions) { for (var i$1 = 1, l$1 = node.ifConditions.length; i$1 < l$1; i$1++) { markStaticRoots(node.ifConditions[i$1].block, isInFor); } } } } function isStatic (node) { if (node.type === 2) { // expression return false } if (node.type === 3) { // text return true } return !!(node.pre || ( !node.hasBindings && // no dynamic bindings !node.if && !node.for && // not v-if or v-for or v-else !isBuiltInTag(node.tag) && // not a built-in isPlatformReservedTag(node.tag) && // not a component !isDirectChildOfTemplateFor(node) && Object.keys(node).every(isStaticKey) )) } function isDirectChildOfTemplateFor (node) { while (node.parent) { node = node.parent; if (node.tag !== 'template') { return false } if (node.for) { return true } } return false } /* */ var fnExpRE = /^\s*([\w$_]+|\([^)]*?\))\s*=>|^function\s*\(/; var simplePathRE = /^\s*[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\['.*?']|\[".*?"]|\[\d+]|\[[A-Za-z_$][\w$]*])*\s*$/; // keyCode aliases var keyCodes = { esc: 27, tab: 9, enter: 13, space: 32, up: 38, left: 37, right: 39, down: 40, 'delete': [8, 46] }; // #4868: modifiers that prevent the execution of the listener // need to explicitly return null so that we can determine whether to remove // the listener for .once var genGuard = function (condition) { return ("if(" + condition + ")return null;"); }; var modifierCode = { stop: '$event.stopPropagation();', prevent: '$event.preventDefault();', self: genGuard("$event.target !== $event.currentTarget"), ctrl: genGuard("!$event.ctrlKey"), shift: genGuard("!$event.shiftKey"), alt: genGuard("!$event.altKey"), meta: genGuard("!$event.metaKey"), left: genGuard("'button' in $event && $event.button !== 0"), middle: genGuard("'button' in $event && $event.button !== 1"), right: genGuard("'button' in $event && $event.button !== 2") }; function genHandlers ( events, isNative, warn ) { var res = isNative ? 'nativeOn:{' : 'on:{'; for (var name in events) { var handler = events[name]; // #5330: warn click.right, since right clicks do not actually fire click events. if (process.env.NODE_ENV !== 'production' && name === 'click' && handler && handler.modifiers && handler.modifiers.right ) { warn( "Use \"contextmenu\" instead of \"click.right\" since right clicks " + "do not actually fire \"click\" events." ); } res += "\"" + name + "\":" + (genHandler(name, handler)) + ","; } return res.slice(0, -1) + '}' } function genHandler ( name, handler ) { if (!handler) { return 'function(){}' } if (Array.isArray(handler)) { return ("[" + (handler.map(function (handler) { return genHandler(name, handler); }).join(',')) + "]") } var isMethodPath = simplePathRE.test(handler.value); var isFunctionExpression = fnExpRE.test(handler.value); if (!handler.modifiers) { return isMethodPath || isFunctionExpression ? handler.value : ("function($event){" + (handler.value) + "}") // inline statement } else { var code = ''; var genModifierCode = ''; var keys = []; for (var key in handler.modifiers) { if (modifierCode[key]) { genModifierCode += modifierCode[key]; // left/right if (keyCodes[key]) { keys.push(key); } } else if (key === 'exact') { var modifiers = (handler.modifiers); genModifierCode += genGuard( ['ctrl', 'shift', 'alt', 'meta'] .filter(function (keyModifier) { return !modifiers[keyModifier]; }) .map(function (keyModifier) { return ("$event." + keyModifier + "Key"); }) .join('||') ); } else { keys.push(key); } } if (keys.length) { code += genKeyFilter(keys); } // Make sure modifiers like prevent and stop get executed after key filtering if (genModifierCode) { code += genModifierCode; } var handlerCode = isMethodPath ? handler.value + '($event)' : isFunctionExpression ? ("(" + (handler.value) + ")($event)") : handler.value; return ("function($event){" + code + handlerCode + "}") } } function genKeyFilter (keys) { return ("if(!('button' in $event)&&" + (keys.map(genFilterCode).join('&&')) + ")return null;") } function genFilterCode (key) { var keyVal = parseInt(key, 10); if (keyVal) { return ("$event.keyCode!==" + keyVal) } var code = keyCodes[key]; return ( "_k($event.keyCode," + (JSON.stringify(key)) + "," + (JSON.stringify(code)) + "," + "$event.key)" ) } /* */ function on (el, dir) { if (process.env.NODE_ENV !== 'production' && dir.modifiers) { warn("v-on without argument does not support modifiers."); } el.wrapListeners = function (code) { return ("_g(" + code + "," + (dir.value) + ")"); }; } /* */ function bind$1 (el, dir) { el.wrapData = function (code) { return ("_b(" + code + ",'" + (el.tag) + "'," + (dir.value) + "," + (dir.modifiers && dir.modifiers.prop ? 'true' : 'false') + (dir.modifiers && dir.modifiers.sync ? ',true' : '') + ")") }; } /* */ var baseDirectives = { on: on, bind: bind$1, cloak: noop }; /* */ var CodegenState = function CodegenState (options) { this.options = options; this.warn = options.warn || baseWarn; this.transforms = pluckModuleFunction(options.modules, 'transformCode'); this.dataGenFns = pluckModuleFunction(options.modules, 'genData'); this.directives = extend(extend({}, baseDirectives), options.directives); var isReservedTag = options.isReservedTag || no; this.maybeComponent = function (el) { return !isReservedTag(el.tag); }; this.onceId = 0; this.staticRenderFns = []; }; function generate ( ast, options ) { var state = new CodegenState(options); var code = ast ? genElement(ast, state) : '_c("div")'; return { render: ("with(this){return " + code + "}"), staticRenderFns: state.staticRenderFns } } function genElement (el, state) { if (el.staticRoot && !el.staticProcessed) { return genStatic(el, state) } else if (el.once && !el.onceProcessed) { return genOnce(el, state) } else if (el.for && !el.forProcessed) { return genFor(el, state) } else if (el.if && !el.ifProcessed) { return genIf(el, state) } else if (el.tag === 'template' && !el.slotTarget) { return genChildren(el, state) || 'void 0' } else if (el.tag === 'slot') { return genSlot(el, state) } else { // component or element var code; if (el.component) { code = genComponent(el.component, el, state); } else { var data = el.plain ? undefined : genData$2(el, state); var children = el.inlineTemplate ? null : genChildren(el, state, true); code = "_c('" + (el.tag) + "'" + (data ? ("," + data) : '') + (children ? ("," + children) : '') + ")"; } // module transforms for (var i = 0; i < state.transforms.length; i++) { code = state.transforms[i](el, code); } return code } } // hoist static sub-trees out function genStatic (el, state) { el.staticProcessed = true; state.staticRenderFns.push(("with(this){return " + (genElement(el, state)) + "}")); return ("_m(" + (state.staticRenderFns.length - 1) + (el.staticInFor ? ',true' : '') + ")") } // v-once function genOnce (el, state) { el.onceProcessed = true; if (el.if && !el.ifProcessed) { return genIf(el, state) } else if (el.staticInFor) { var key = ''; var parent = el.parent; while (parent) { if (parent.for) { key = parent.key; break } parent = parent.parent; } if (!key) { process.env.NODE_ENV !== 'production' && state.warn( "v-once can only be used inside v-for that is keyed. " ); return genElement(el, state) } return ("_o(" + (genElement(el, state)) + "," + (state.onceId++) + "," + key + ")") } else { return genStatic(el, state) } } function genIf ( el, state, altGen, altEmpty ) { el.ifProcessed = true; // avoid recursion return genIfConditions(el.ifConditions.slice(), state, altGen, altEmpty) } function genIfConditions ( conditions, state, altGen, altEmpty ) { if (!conditions.length) { return altEmpty || '_e()' } var condition = conditions.shift(); if (condition.exp) { return ("(" + (condition.exp) + ")?" + (genTernaryExp(condition.block)) + ":" + (genIfConditions(conditions, state, altGen, altEmpty))) } else { return ("" + (genTernaryExp(condition.block))) } // v-if with v-once should generate code like (a)?_m(0):_m(1) function genTernaryExp (el) { return altGen ? altGen(el, state) : el.once ? genOnce(el, state) : genElement(el, state) } } function genFor ( el, state, altGen, altHelper ) { var exp = el.for; var alias = el.alias; var iterator1 = el.iterator1 ? ("," + (el.iterator1)) : ''; var iterator2 = el.iterator2 ? ("," + (el.iterator2)) : ''; if (process.env.NODE_ENV !== 'production' && state.maybeComponent(el) && el.tag !== 'slot' && el.tag !== 'template' && !el.key ) { state.warn( "<" + (el.tag) + " v-for=\"" + alias + " in " + exp + "\">: component lists rendered with " + "v-for should have explicit keys. " + "See https://vuejs.org/guide/list.html#key for more info.", true /* tip */ ); } el.forProcessed = true; // avoid recursion return (altHelper || '_l') + "((" + exp + ")," + "function(" + alias + iterator1 + iterator2 + "){" + "return " + ((altGen || genElement)(el, state)) + '})' } function genData$2 (el, state) { var data = '{'; // directives first. // directives may mutate the el's other properties before they are generated. var dirs = genDirectives(el, state); if (dirs) { data += dirs + ','; } // key if (el.key) { data += "key:" + (el.key) + ","; } // ref if (el.ref) { data += "ref:" + (el.ref) + ","; } if (el.refInFor) { data += "refInFor:true,"; } // pre if (el.pre) { data += "pre:true,"; } // record original tag name for components using "is" attribute if (el.component) { data += "tag:\"" + (el.tag) + "\","; } // module data generation functions for (var i = 0; i < state.dataGenFns.length; i++) { data += state.dataGenFns[i](el); } // attributes if (el.attrs) { data += "attrs:{" + (genProps(el.attrs)) + "},"; } // DOM props if (el.props) { data += "domProps:{" + (genProps(el.props)) + "},"; } // event handlers if (el.events) { data += (genHandlers(el.events, false, state.warn)) + ","; } if (el.nativeEvents) { data += (genHandlers(el.nativeEvents, true, state.warn)) + ","; } // slot target // only for non-scoped slots if (el.slotTarget && !el.slotScope) { data += "slot:" + (el.slotTarget) + ","; } // scoped slots if (el.scopedSlots) { data += (genScopedSlots(el.scopedSlots, state)) + ","; } // component v-model if (el.model) { data += "model:{value:" + (el.model.value) + ",callback:" + (el.model.callback) + ",expression:" + (el.model.expression) + "},"; } // inline-template if (el.inlineTemplate) { var inlineTemplate = genInlineTemplate(el, state); if (inlineTemplate) { data += inlineTemplate + ","; } } data = data.replace(/,$/, '') + '}'; // v-bind data wrap if (el.wrapData) { data = el.wrapData(data); } // v-on data wrap if (el.wrapListeners) { data = el.wrapListeners(data); } return data } function genDirectives (el, state) { var dirs = el.directives; if (!dirs) { return } var res = 'directives:['; var hasRuntime = false; var i, l, dir, needRuntime; for (i = 0, l = dirs.length; i < l; i++) { dir = dirs[i]; needRuntime = true; var gen = state.directives[dir.name]; if (gen) { // compile-time directive that manipulates AST. // returns true if it also needs a runtime counterpart. needRuntime = !!gen(el, dir, state.warn); } if (needRuntime) { hasRuntime = true; res += "{name:\"" + (dir.name) + "\",rawName:\"" + (dir.rawName) + "\"" + (dir.value ? (",value:(" + (dir.value) + "),expression:" + (JSON.stringify(dir.value))) : '') + (dir.arg ? (",arg:\"" + (dir.arg) + "\"") : '') + (dir.modifiers ? (",modifiers:" + (JSON.stringify(dir.modifiers))) : '') + "},"; } } if (hasRuntime) { return res.slice(0, -1) + ']' } } function genInlineTemplate (el, state) { var ast = el.children[0]; if (process.env.NODE_ENV !== 'production' && ( el.children.length !== 1 || ast.type !== 1 )) { state.warn('Inline-template components must have exactly one child element.'); } if (ast.type === 1) { var inlineRenderFns = generate(ast, state.options); return ("inlineTemplate:{render:function(){" + (inlineRenderFns.render) + "},staticRenderFns:[" + (inlineRenderFns.staticRenderFns.map(function (code) { return ("function(){" + code + "}"); }).join(',')) + "]}") } } function genScopedSlots ( slots, state ) { return ("scopedSlots:_u([" + (Object.keys(slots).map(function (key) { return genScopedSlot(key, slots[key], state) }).join(',')) + "])") } function genScopedSlot ( key, el, state ) { if (el.for && !el.forProcessed) { return genForScopedSlot(key, el, state) } var fn = "function(" + (String(el.slotScope)) + "){" + "return " + (el.tag === 'template' ? el.if ? ((el.if) + "?" + (genChildren(el, state) || 'undefined') + ":undefined") : genChildren(el, state) || 'undefined' : genElement(el, state)) + "}"; return ("{key:" + key + ",fn:" + fn + "}") } function genForScopedSlot ( key, el, state ) { var exp = el.for; var alias = el.alias; var iterator1 = el.iterator1 ? ("," + (el.iterator1)) : ''; var iterator2 = el.iterator2 ? ("," + (el.iterator2)) : ''; el.forProcessed = true; // avoid recursion return "_l((" + exp + ")," + "function(" + alias + iterator1 + iterator2 + "){" + "return " + (genScopedSlot(key, el, state)) + '})' } function genChildren ( el, state, checkSkip, altGenElement, altGenNode ) { var children = el.children; if (children.length) { var el$1 = children[0]; // optimize single v-for if (children.length === 1 && el$1.for && el$1.tag !== 'template' && el$1.tag !== 'slot' ) { return (altGenElement || genElement)(el$1, state) } var normalizationType = checkSkip ? getNormalizationType(children, state.maybeComponent) : 0; var gen = altGenNode || genNode; return ("[" + (children.map(function (c) { return gen(c, state); }).join(',')) + "]" + (normalizationType ? ("," + normalizationType) : '')) } } // determine the normalization needed for the children array. // 0: no normalization needed // 1: simple normalization needed (possible 1-level deep nested array) // 2: full normalization needed function getNormalizationType ( children, maybeComponent ) { var res = 0; for (var i = 0; i < children.length; i++) { var el = children[i]; if (el.type !== 1) { continue } if (needsNormalization(el) || (el.ifConditions && el.ifConditions.some(function (c) { return needsNormalization(c.block); }))) { res = 2; break } if (maybeComponent(el) || (el.ifConditions && el.ifConditions.some(function (c) { return maybeComponent(c.block); }))) { res = 1; } } return res } function needsNormalization (el) { return el.for !== undefined || el.tag === 'template' || el.tag === 'slot' } function genNode (node, state) { if (node.type === 1) { return genElement(node, state) } if (node.type === 3 && node.isComment) { return genComment(node) } else { return genText(node) } } function genText (text) { return ("_v(" + (text.type === 2 ? text.expression // no need for () because already wrapped in _s() : transformSpecialNewlines(JSON.stringify(text.text))) + ")") } function genComment (comment) { return ("_e(" + (JSON.stringify(comment.text)) + ")") } function genSlot (el, state) { var slotName = el.slotName || '"default"'; var children = genChildren(el, state); var res = "_t(" + slotName + (children ? ("," + children) : ''); var attrs = el.attrs && ("{" + (el.attrs.map(function (a) { return ((camelize(a.name)) + ":" + (a.value)); }).join(',')) + "}"); var bind$$1 = el.attrsMap['v-bind']; if ((attrs || bind$$1) && !children) { res += ",null"; } if (attrs) { res += "," + attrs; } if (bind$$1) { res += (attrs ? '' : ',null') + "," + bind$$1; } return res + ')' } // componentName is el.component, take it as argument to shun flow's pessimistic refinement function genComponent ( componentName, el, state ) { var children = el.inlineTemplate ? null : genChildren(el, state, true); return ("_c(" + componentName + "," + (genData$2(el, state)) + (children ? ("," + children) : '') + ")") } function genProps (props) { var res = ''; for (var i = 0; i < props.length; i++) { var prop = props[i]; res += "\"" + (prop.name) + "\":" + (transformSpecialNewlines(prop.value)) + ","; } return res.slice(0, -1) } // #3895, #4268 function transformSpecialNewlines (text) { return text .replace(/\u2028/g, '\\u2028') .replace(/\u2029/g, '\\u2029') } /* */ // these keywords should not appear inside expressions, but operators like // typeof, instanceof and in are allowed var prohibitedKeywordRE = new RegExp('\\b' + ( 'do,if,for,let,new,try,var,case,else,with,await,break,catch,class,const,' + 'super,throw,while,yield,delete,export,import,return,switch,default,' + 'extends,finally,continue,debugger,function,arguments' ).split(',').join('\\b|\\b') + '\\b'); // these unary operators should not be used as property/method names var unaryOperatorsRE = new RegExp('\\b' + ( 'delete,typeof,void' ).split(',').join('\\s*\\([^\\)]*\\)|\\b') + '\\s*\\([^\\)]*\\)'); // check valid identifier for v-for var identRE = /[A-Za-z_$][\w$]*/; // strip strings in expressions var stripStringRE = /'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*\$\{|\}(?:[^`\\]|\\.)*`|`(?:[^`\\]|\\.)*`/g; // detect problematic expressions in a template function detectErrors (ast) { var errors = []; if (ast) { checkNode(ast, errors); } return errors } function checkNode (node, errors) { if (node.type === 1) { for (var name in node.attrsMap) { if (dirRE.test(name)) { var value = node.attrsMap[name]; if (value) { if (name === 'v-for') { checkFor(node, ("v-for=\"" + value + "\""), errors); } else if (onRE.test(name)) { checkEvent(value, (name + "=\"" + value + "\""), errors); } else { checkExpression(value, (name + "=\"" + value + "\""), errors); } } } } if (node.children) { for (var i = 0; i < node.children.length; i++) { checkNode(node.children[i], errors); } } } else if (node.type === 2) { checkExpression(node.expression, node.text, errors); } } function checkEvent (exp, text, errors) { var stipped = exp.replace(stripStringRE, ''); var keywordMatch = stipped.match(unaryOperatorsRE); if (keywordMatch && stipped.charAt(keywordMatch.index - 1) !== '$') { errors.push( "avoid using JavaScript unary operator as property name: " + "\"" + (keywordMatch[0]) + "\" in expression " + (text.trim()) ); } checkExpression(exp, text, errors); } function checkFor (node, text, errors) { checkExpression(node.for || '', text, errors); checkIdentifier(node.alias, 'v-for alias', text, errors); checkIdentifier(node.iterator1, 'v-for iterator', text, errors); checkIdentifier(node.iterator2, 'v-for iterator', text, errors); } function checkIdentifier (ident, type, text, errors) { if (typeof ident === 'string' && !identRE.test(ident)) { errors.push(("invalid " + type + " \"" + ident + "\" in expression: " + (text.trim()))); } } function checkExpression (exp, text, errors) { try { new Function(("return " + exp)); } catch (e) { var keywordMatch = exp.replace(stripStringRE, '').match(prohibitedKeywordRE); if (keywordMatch) { errors.push( "avoid using JavaScript keyword as property name: " + "\"" + (keywordMatch[0]) + "\"\n Raw expression: " + (text.trim()) ); } else { errors.push( "invalid expression: " + (e.message) + " in\n\n" + " " + exp + "\n\n" + " Raw expression: " + (text.trim()) + "\n" ); } } } /* */ function createFunction (code, errors) { try { return new Function(code) } catch (err) { errors.push({ err: err, code: code }); return noop } } function createCompileToFunctionFn (compile) { var cache = Object.create(null); return function compileToFunctions ( template, options, vm ) { options = extend({}, options); var warn$$1 = options.warn || warn; delete options.warn; /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production') { // detect possible CSP restriction try { new Function('return 1'); } catch (e) { if (e.toString().match(/unsafe-eval|CSP/)) { warn$$1( 'It seems you are using the standalone build of Vue.js in an ' + 'environment with Content Security Policy that prohibits unsafe-eval. ' + 'The template compiler cannot work in this environment. Consider ' + 'relaxing the policy to allow unsafe-eval or pre-compiling your ' + 'templates into render functions.' ); } } } // check cache var key = options.delimiters ? String(options.delimiters) + template : template; if (cache[key]) { return cache[key] } // compile var compiled = compile(template, options); // check compilation errors/tips if (process.env.NODE_ENV !== 'production') { if (compiled.errors && compiled.errors.length) { warn$$1( "Error compiling template:\n\n" + template + "\n\n" + compiled.errors.map(function (e) { return ("- " + e); }).join('\n') + '\n', vm ); } if (compiled.tips && compiled.tips.length) { compiled.tips.forEach(function (msg) { return tip(msg, vm); }); } } // turn code into functions var res = {}; var fnGenErrors = []; res.render = createFunction(compiled.render, fnGenErrors); res.staticRenderFns = compiled.staticRenderFns.map(function (code) { return createFunction(code, fnGenErrors) }); // check function generation errors. // this should only happen if there is a bug in the compiler itself. // mostly for codegen development use /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production') { if ((!compiled.errors || !compiled.errors.length) && fnGenErrors.length) { warn$$1( "Failed to generate render function:\n\n" + fnGenErrors.map(function (ref) { var err = ref.err; var code = ref.code; return ((err.toString()) + " in\n\n" + code + "\n"); }).join('\n'), vm ); } } return (cache[key] = res) } } /* */ function createCompilerCreator (baseCompile) { return function createCompiler (baseOptions) { function compile ( template, options ) { var finalOptions = Object.create(baseOptions); var errors = []; var tips = []; finalOptions.warn = function (msg, tip) { (tip ? tips : errors).push(msg); }; if (options) { // merge custom modules if (options.modules) { finalOptions.modules = (baseOptions.modules || []).concat(options.modules); } // merge custom directives if (options.directives) { finalOptions.directives = extend( Object.create(baseOptions.directives), options.directives ); } // copy other options for (var key in options) { if (key !== 'modules' && key !== 'directives') { finalOptions[key] = options[key]; } } } var compiled = baseCompile(template, finalOptions); if (process.env.NODE_ENV !== 'production') { errors.push.apply(errors, detectErrors(compiled.ast)); } compiled.errors = errors; compiled.tips = tips; return compiled } return { compile: compile, compileToFunctions: createCompileToFunctionFn(compile) } } } /* */ // `createCompilerCreator` allows creating compilers that use alternative // parser/optimizer/codegen, e.g the SSR optimizing compiler. // Here we just export a default compiler using the default parts. var createCompiler = createCompilerCreator(function baseCompile ( template, options ) { var ast = parse(template.trim(), options); optimize(ast, options); var code = generate(ast, options); return { ast: ast, render: code.render, staticRenderFns: code.staticRenderFns } }); /* */ var ref$1 = createCompiler(baseOptions); var compileToFunctions = ref$1.compileToFunctions; /* */ var idToTemplate = cached(function (id) { var el = query(id); return el && el.innerHTML }); var mount = Vue$3.prototype.$mount; Vue$3.prototype.$mount = function ( el, hydrating ) { el = el && query(el); /* istanbul ignore if */ if (el === document.body || el === document.documentElement) { process.env.NODE_ENV !== 'production' && warn( "Do not mount Vue to <html> or <body> - mount to normal elements instead." ); return this } var options = this.$options; // resolve template/el and convert to render function if (!options.render) { var template = options.template; if (template) { if (typeof template === 'string') { if (template.charAt(0) === '#') { template = idToTemplate(template); /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production' && !template) { warn( ("Template element not found or is empty: " + (options.template)), this ); } } } else if (template.nodeType) { template = template.innerHTML; } else { if (process.env.NODE_ENV !== 'production') { warn('invalid template option:' + template, this); } return this } } else if (el) { template = getOuterHTML(el); } if (template) { /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production' && config.performance && mark) { mark('compile'); } var ref = compileToFunctions(template, { shouldDecodeNewlines: shouldDecodeNewlines, delimiters: options.delimiters, comments: options.comments }, this); var render = ref.render; var staticRenderFns = ref.staticRenderFns; options.render = render; options.staticRenderFns = staticRenderFns; /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production' && config.performance && mark) { mark('compile end'); measure(("vue " + (this._name) + " compile"), 'compile', 'compile end'); } } } return mount.call(this, el, hydrating) }; /** * Get outerHTML of elements, taking care * of SVG elements in IE as well. */ function getOuterHTML (el) { if (el.outerHTML) { return el.outerHTML } else { var container = document.createElement('div'); container.appendChild(el.cloneNode(true)); return container.innerHTML } } Vue$3.compile = compileToFunctions; export default Vue$3;
playground/topic/react/redux/counter/src/containers/CounterApp.js
yardfarmer/bone
import React, { Component } from 'react'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import Counter from '../components/Counter'; import * as CounterActions from '../actions/CounterActions'; class CounterApp extends Component { render() { const { counter, dispatch } = this.props; return ( <Counter counter={counter} {...bindActionCreators(CounterActions, dispatch)} /> ); } } function select(state) { return { counter: state.counter }; } export default connect(select)(CounterApp);
src/main/resources/static/scripts/components/Navigation.js
davidbogue/Urbane
/* Navigation */ import React from 'react'; import { Link } from 'react-router'; var Navigation = React.createClass({ getInitialState: function() { return { authToken: localStorage.getItem('authtoken') }; }, signOut : function(){ localStorage.removeItem('authtoken'); this.setState({authToken: null}); }, render : function() { var navStyle = {}; if(this.props.background){ navStyle={background:this.props.background}; } var addArticle = ''; if(this.state.authToken){ addArticle = <li> <Link to="/addArticle">New Post</Link> </li> } return <nav className="navbar navbar-default navbar-custom navbar-fixed-top" style={navStyle}> <div className="container-fluid"> <div className="navbar-header page-scroll"> <button type="button" className="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> <span className="sr-only">Toggle navigation</span> <span className="icon-bar"></span> <span className="icon-bar"></span> <span className="icon-bar"></span> </button> <Link className="navbar-brand" to="/"></Link> </div> <div className="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul className="nav navbar-nav navbar-right"> <li> <Link to="/">Home</Link> </li> {addArticle} <li> <AuthenticationLink authtoken={this.state.authToken} signOut={this.signOut}/> </li> </ul> </div> </div> </nav> } }); var AuthenticationLink = React.createClass({ render : function(){ if(this.props.authtoken){ return( <a href='#' onClick={this.props.signOut}>Sign Out</a> ) } else { return( <Link to="/signin">Sign In</Link> ) } } }); export default Navigation;
app/components/Home/LeftPanel/LeftPanel.js
rjzheng/kzhomepanel
import React from 'react'; import WeatherWidget from 'WeatherWidget'; import CalendarWidget from 'CalendarWidget'; import TaskWidget from 'TaskWidget'; import GroceryWidget from 'GroceryWidget'; function LeftPanel() { return ( <div className="left-panel"> <WeatherWidget /> <CalendarWidget /> <div> <TaskWidget /> <GroceryWidget /> </div> </div> ) }; export default LeftPanel;
newclient/scripts/components/user/entities/question/index.js
kuali/research-coi
/* The Conflict of Interest (COI) module of Kuali Research Copyright © 2005-2016 Kuali, Inc. 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 styles from './style'; import classNames from 'classnames'; import React from 'react'; import {QUESTION_TYPE} from '../../../../../../coi-constants'; import {RadioControl} from '../radio-control'; import {TextAreaControl} from '../text-area-control'; import {NumericControl} from '../numeric-control'; import {DateControl} from '../date-control'; import {CheckboxControl} from '../checkbox-control'; export class Question extends React.Component { constructor() { super(); this.onAnswer = this.onAnswer.bind(this); this.onAnswerMultiple = this.onAnswerMultiple.bind(this); this.getControl = this.getControl.bind(this); } onAnswer(newValue, questionId) { this.props.onAnswer(newValue, questionId); } onAnswerMultiple(value, checked, questionId) { let newAnswer; if (this.props.answer) { newAnswer = Array.from(this.props.answer); } else { newAnswer = []; } if (checked) { if (!newAnswer.includes(value)) { newAnswer.push(value); } } else { newAnswer = this.props.answer.filter(answer => { return answer !== value; }); } this.props.onAnswer(newAnswer, questionId); } getControl(question, answer) { switch (question.question.type) { case QUESTION_TYPE.YESNO: return ( <RadioControl readonly={this.props.readonly} options={['Yes', 'No']} answer={answer} onChange={this.onAnswer} questionId={question.id} invalid={this.props.invalid} /> ); case QUESTION_TYPE.YESNONA: return ( <RadioControl readonly={this.props.readonly} options={['Yes', 'No', 'NA']} answer={answer} onChange={this.onAnswer} questionId={question.id} invalid={this.props.invalid} /> ); case QUESTION_TYPE.TEXTAREA: return ( <TextAreaControl readonly={this.props.readonly} answer={answer} onChange={this.onAnswer} questionId={question.id} invalid={this.props.invalid} entityId={this.props.entityId} /> ); case QUESTION_TYPE.MULTISELECT: return ( <CheckboxControl readonly={this.props.readonly} options={question.question.options} answer={answer} onChange={this.onAnswerMultiple} questionId={question.id} invalid={this.props.invalid} /> ); case QUESTION_TYPE.NUMBER: return ( <NumericControl readonly={this.props.readonly} answer={answer} onChange={this.onAnswer} questionId={question.id} invalid={this.props.invalid} entityId={this.props.entityId} /> ); case QUESTION_TYPE.DATE: return ( <DateControl readonly={this.props.readonly} answer={answer} onChange={this.onAnswer} questionId={question.id} invalid={this.props.invalid} entityId={this.props.entityId} /> ); } } render() { const classes = classNames( styles.container, {[styles.invalid]: this.props.invalid} ); return ( <span className={classes}> <label htmlFor={`eqa${this.props.entityId}${this.props.question.id}`}> {this.props.question.question.text} </label> <div className={styles.controls}> {this.getControl(this.props.question, this.props.answer)} </div> </span> ); } }
src/utils/prop-types.js
vmaudgalya/material-ui
import React from 'react'; const horizontal = React.PropTypes.oneOf(['left', 'middle', 'right']); const vertical = React.PropTypes.oneOf(['top', 'center', 'bottom']); export default { corners: React.PropTypes.oneOf([ 'bottom-left', 'bottom-right', 'top-left', 'top-right', ]), horizontal: horizontal, vertical: vertical, origin: React.PropTypes.shape({ horizontal: horizontal, vertical: vertical, }), cornersAndCenter: React.PropTypes.oneOf([ 'bottom-center', 'bottom-left', 'bottom-right', 'top-center', 'top-left', 'top-right', ]), stringOrNumber: React.PropTypes.oneOfType([ React.PropTypes.string, React.PropTypes.number, ]), zDepth: React.PropTypes.oneOf([0, 1, 2, 3, 4, 5]), };
src/components/views/Account/NewAccount.js
jennywin/donate-for-good
import React, { Component } from 'react'; export default class NewAccount extends Component { render() { return ( <div> This is the new account page. </div> ); } }
src/GridList/GridList.spec.js
mit-cml/iot-website-source
/* eslint-env mocha */ import React from 'react'; import {shallow} from 'enzyme'; import {assert} from 'chai'; import GridList from './GridList'; import getMuiTheme from '../styles/getMuiTheme'; describe('<GridList />', () => { const muiTheme = getMuiTheme(); const shallowWithContext = (node) => shallow(node, {context: {muiTheme}}); const tilesData = [ { img: 'images/grid-list/00-52-29-429_640.jpg', title: 'Breakfast', author: 'jill111', }, { img: 'images/grid-list/burger-827309_640.jpg', title: 'Tasty burger', author: 'pashminu', }, ]; it('renders children and change cellHeight', () => { const cellHeight = 250; const wrapper = shallowWithContext( <GridList cellHeight={cellHeight}> {tilesData.map((tile) => ( <span key={tile.img} className="grid-tile" title={tile.title} subtitle={<span>by <b>{tile.author}</b></span>} > <img src={tile.img} /> </span> ))} </GridList> ); assert.strictEqual(wrapper.find('.grid-tile').length, 2, 'should contain the children'); assert.strictEqual(wrapper.children().at(0).prop('style').height, cellHeight + 4, 'should have height to 254'); }); it('renders children by default', () => { const wrapper = shallowWithContext( <GridList> {tilesData.map((tile) => ( <span key={tile.img} className="grid-tile" title={tile.title} subtitle={<span>by <b>{tile.author}</b></span>} > <img src={tile.img} /> </span> ))} </GridList> ); assert.strictEqual(wrapper.find('.grid-tile').length, 2, 'should contain the children'); }); it('renders children and change cols', () => { const wrapper = shallowWithContext( <GridList cols={4}> {tilesData.map((tile) => ( <span key={tile.img} className="grid-tile" title={tile.title} subtitle={<span>by <b>{tile.author}</b></span>} > <img src={tile.img} /> </span> ))} </GridList> ); assert.strictEqual(wrapper.find('.grid-tile').length, 2, 'should contain the children'); assert.strictEqual(wrapper.children().at(0).prop('style').width, '25%', 'should have 25% of width'); }); it('renders children and change padding', () => { const padding = 10; const wrapper = shallowWithContext( <GridList padding={padding}> {tilesData.map((tile) => ( <span key={tile.img} className="grid-tile" title={tile.title} subtitle={<span>by <b>{tile.author}</b></span>} > <img src={tile.img} /> </span> ))} </GridList> ); assert.strictEqual(wrapper.find('.grid-tile').length, 2, 'should contain the children'); assert.strictEqual(wrapper.children().at(0).prop('style').padding, padding / 2, 'should have 5 of padding'); }); it('renders children and overwrite style', () => { const style = { backgroundColor: 'red', }; const wrapper = shallowWithContext( <GridList style={style}> {tilesData.map((tile) => ( <span key={tile.img} className="grid-tile" title={tile.title} subtitle={<span>by <b>{tile.author}</b></span>} > <img src={tile.img} /> </span> ))} </GridList> ); assert.strictEqual(wrapper.find('.grid-tile').length, 2, 'should contain the children'); assert.strictEqual(wrapper.prop('style').backgroundColor, style.backgroundColor, 'should have a red backgroundColor'); }); describe('prop: cellHeight', () => { it('should accept auto as a property', () => { const wrapper = shallowWithContext( <GridList cellHeight="auto"> <div /> </GridList> ); assert.strictEqual(wrapper.children().at(0).props().style.height, 'auto'); }); }); });
packages/material-ui-icons/src/TextFormatSharp.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="M5 17v2h14v-2H5zm4.5-4.2h5l.9 2.2h2.1L12.75 4h-1.5L6.5 15h2.1l.9-2.2zM12 5.98L13.87 11h-3.74L12 5.98z" /></React.Fragment> , 'TextFormatSharp');
App/BreweryMap.js
Tyler-Losinski/Rater-Mc-Ratey-Face
import MapView, { Marker } from 'react-native-maps'; import React from 'react'; import { Dimensions, StyleSheet } from 'react-native' const width = Dimensions.get('window').width const height = Dimensions.get('window').height import { Text, Button, Left, Body, Footer, FooterTab, Icon, Container, Content, Header, Title } from 'native-base'; import { Actions } from 'react-native-router-flux'; export default class BreweryMapContainer extends React.Component { constructor(props) { super(props); this.state = { markers: [{ latlng: { latitude: 46.87719, longitude: -96.7898, }, title: 'Fargo', description: 'This is a test marker' } ] }; } render() { return ( <Container> <Header> <Left> <Button transparent onPress={() => { }}> <Icon name='ios-menu' /> </Button> </Left> <Body style={{ marginLeft: -40 }}> <Title>Brewery Locations</Title> </Body> </Header> <Content> <MapView style={styles.map} region={{ latitude: 46.87719, longitude: -96.7898, latitudeDelta: 0.015, longitudeDelta: 0.0121, }} > {this.props.breweries.map(brewery => ( <Marker coordinate={brewery} title={brewery.brewery.name} description={brewery.streetAddress} /> ))} </MapView> </Content> <Footer> <FooterTab> <Button vertical onPress={() => { Actions.pop(); }}> <Icon name="list" /> <Text>Breweries</Text> </Button> <Button active vertical > <Icon name="map" /> <Text>Map</Text> </Button> </FooterTab> </Footer> </Container> ); } } const styles = StyleSheet.create({ map: { flex: 1, width, height } });
ajax/libs/backbone-react-component/0.6.4/backbone-react-component-min.js
joeylakay/cdnjs
"use strict";!function(a,b){if("function"==typeof define&&define.amd)define(["react","backbone","underscore"],b);else if("undefined"!=typeof module&&module.exports){var c=require("react"),d=require("backbone"),e=require("underscore");module.exports=b(c,d,e)}else b(a.React,a.Backbone,a._)}(this,function(a,b,c){function d(a,f){f=f||{};var g,h=f.model,i=f.collection;(c.isElement(f.el)||b.$&&f.el instanceof b.$)&&(g=f.el,delete f.el),"undefined"!=typeof h&&(h.attributes||"object"==typeof h&&c.values(h)[0].attributes)&&(delete f.model,this.model=h,this.setPropsBackbone(h,void 0,f)),"undefined"!=typeof i&&(i.models||"object"==typeof i&&c.values(i)[0].models)&&(delete f.collection,this.collection=i,this.setPropsBackbone(i,void 0,f));var j;a.prototype?(j=this.virtualComponent=c.defaults(a.apply(this,c.rest(arguments)).__realComponentInstance,b.Events,c.omit(b.React.Component,"mixin"),{clone:function(b,c){return new d(a,b,c).virtualComponent},cid:c.uniqueId(),wrapper:this}),g&&e.setElement.call(j,g)):(j=a,this.component=j),j._owner||(this.startModelListeners(),this.startCollectionListeners())}b.React||(b.React={}),b.React.Component={extend:function(f){function g(){var a=Array.prototype.slice.call(arguments),b=function(){return d.apply(this,[h].concat(a))};return b.prototype=d.prototype,(new b).virtualComponent}g.extend=function(){return b.React.Component.extend(c.extend({},f,arguments[0]))},f.mixins?f.mixins[0]!==e&&f.mixins.splice(0,0,e):f.mixins=[e];var h=a.createClass(c.extend(g.prototype,f));return g},mount:function(b,c){if(!b&&!this.el)throw new Error("No element to mount on");return b||(b=this.el),this.wrapper.component=a.renderComponent(this,b,c),this},remove:function(){this.wrapper.component&&this.wrapper.component.isMounted()&&this.unmount(),this.wrapper.stopListening(),this.stopListening()},toHTML:function(){var b=this.clone(c.extend({},this.props,{collection:this.wrapper.collection,model:this.wrapper.model}));return a.renderComponentToString(b)},unmount:function(){var b=this.el.parentNode;if(!a.unmountComponentAtNode(b))throw new Error("There was an error unmounting the component");delete this.wrapper.component,this.setElement(b)}};var e=b.React.Component.mixin={componentDidMount:function(){this.setElement(this.getDOMNode())},componentDidUpdate:function(){this.setElement(this.getDOMNode())},componentWillMount:function(){this.wrapper||(this.isBackboneMixin=!0,this.wrapper=new d(this,this.props))},componentWillUnmount:function(){this.wrapper&&this.isBackboneMixin&&(this.wrapper.stopListening(),delete this.wrapper)},$:function(){return this.$el?this.$el.find.apply(this.$el,arguments):void 0},getCollection:function(){for(var a=this,b=a.wrapper;!b.collection;){if(a=a._owner,!a)throw new Error("Collection not found");b=a.wrapper}return b.collection},getModel:function(){for(var a=this,b=a.wrapper;!b.model;){if(a=a._owner,!a)throw new Error("Model not found");b=a.wrapper}return b.model},getOwner:function(){for(var a=this;a._owner;)a=a._owner;return a},setElement:function(a){if(a&&b.$&&a instanceof b.$){if(a.length>1)throw new Error("You can only assign one element to a component");this.el=a[0],this.$el=a}else a&&(this.el=a,b.$&&(this.$el=b.$(a)));return this}};return c.extend(d.prototype,b.Events,{onError:function(a,b,c){c.silent||this.setProps({isRequesting:!1,hasError:!0,error:b})},onRequest:function(a,b,c){c.silent||this.setProps({isRequesting:!0,hasError:!1})},onSync:function(a,b,c){c.silent||this.setProps({isRequesting:!1})},setPropsBackbone:function(a,b,c){if(a.models||a.attributes)this.setProps.apply(this,arguments);else for(b in a)this.setPropsBackbone(a[b],b,c)},setProps:function(a,d,e){e||this.component&&this.component.isMounted()||(e=this.virtualComponent.props);var f={},g=a.toJSON?a.toJSON():a;d?f[d]=g:a instanceof b.Collection?f.collection=g:f=g,e?c.extend(e,f):(this.nextProps=c.extend(this.nextProps||{},f),c.defer(c.bind(function(){this.nextProps&&(this.component&&this.component.setProps(this.nextProps),delete this.nextProps)},this)))},startCollectionListeners:function(a,b){if(a||(a=this.collection),a)if(a.models)this.listenTo(a,"add remove change sort reset",c.partial(this.setPropsBackbone,a,b,void 0)).listenTo(a,"error",this.onError).listenTo(a,"request",this.onRequest).listenTo(a,"sync",this.onSync);else if("object"==typeof a)for(b in a)a.hasOwnProperty(b)&&this.startCollectionListeners(a[b],b)},startModelListeners:function(a,b){if(a||(a=this.model),a)if(a.attributes)this.listenTo(a,"change",c.partial(this.setPropsBackbone,a,b,void 0)).listenTo(a,"error",this.onError).listenTo(a,"request",this.onRequest).listenTo(a,"sync",this.onSync);else if("object"==typeof a)for(b in a)this.startModelListeners(a[b],b)}}),b.React.Component});
common/containers/App.js
nikgraf/redux-universal-app
import React from 'react'; import { Link } from 'react-router'; const App = ({children}) => <div> Header <div> Navigation: <Link to={'/'}>Home</Link> <Link to={'/users'}>Users</Link> <Link to={'/about'}>About</Link> </div> { children } Footer </div> ; export default App;
ui/src/main/js/components/UpdateInstanceEvents.js
rdelval/aurora
import moment from 'moment'; import React from 'react'; import { Link } from 'react-router-dom'; import Icon from 'components/Icon'; import Pagination from 'components/Pagination'; import StateMachine from 'components/StateMachine'; import { addClass, sort } from 'utils/Common'; import { UPDATE_ACTION } from 'utils/Thrift'; import { actionDispatcher, getClassForUpdateAction } from 'utils/Update'; const instanceEventIcon = actionDispatcher({ success: (e) => <Icon name='ok' />, warning: (e) => <Icon name='warning-sign' />, error: (e) => <Icon name='remove' />, inProgress: (e) => <Icon name='play-circle' /> }); export class InstanceEvent extends React.Component { constructor(props) { super(props); this.state = { expanded: props.expanded || false }; } _stateMachine(events) { const states = events.map((e, i) => { return { className: addClass( getClassForUpdateAction(e.action), (i === events.length - 1) ? ' active' : ''), state: UPDATE_ACTION[e.action], timestamp: e.timestampMs, message: e.message }; }); return (<div className='update-instance-history'> <StateMachine className={getClassForUpdateAction(events[events.length - 1].action)} states={states} /> </div>); } expand() { this.setState({ expanded: !this.state.expanded }); } render() { const {events, instanceId, jobKey: {job: {role, environment, name}}} = this.props; const sorted = sort(events, (e) => e.timestampMs); const stateMachine = this.state.expanded ? this._stateMachine(sorted) : ''; const icon = this.state.expanded ? <Icon name='chevron-down' /> : <Icon name='chevron-right' />; const latestEvent = sorted[sorted.length - 1]; return (<div className='update-instance-event-container'> <div className='update-instance-event' onClick={(e) => this.expand()}> {icon} <span className='update-instance-event-id'> <Link to={`/scheduler/${role}/${environment}/${name}/${instanceId}`}> #{instanceId} </Link> </span> <span className='update-instance-event-status'> {UPDATE_ACTION[latestEvent.action]} <span className={getClassForUpdateAction(latestEvent.action)}> {instanceEventIcon(latestEvent)} </span> </span> <span className='update-instance-event-time'> {moment(latestEvent.timestampMs).utc().format('HH:mm:ss') + ' UTC'} </span> </div> {stateMachine} </div>); } }; export default function UpdateInstanceEvents({ update }) { const sortedEvents = sort(update.instanceEvents, (e) => e.timestampMs, true); const instanceMap = {}; const eventOrder = []; sortedEvents.forEach((e) => { const existing = instanceMap[e.instanceId]; if (existing) { instanceMap[e.instanceId].push(e); } else { eventOrder.push(e.instanceId); instanceMap[e.instanceId] = [e]; } }); return (<div className='instance-events'> <Pagination data={eventOrder} hideIfSinglePage numberPerPage={10} renderer={(instanceId) => <InstanceEvent events={instanceMap[instanceId]} instanceId={instanceId} jobKey={update.update.summary.key} />} /> </div>); }
game-new/src/views/diff.js
d07RiV/d3planner
import React from 'react'; import { Route, Switch } from 'react-router-dom'; import { LinkContainer } from 'react-router-bootstrap'; import { MenuItem, NavItem } from 'react-bootstrap'; import { makeRegex, underlinerFunc, NavSearchDropdown, withAsyncLoading } from 'utils'; const formatVersion = (versions, build) => { if (!versions) return build.toString(); let name = versions.versions[build] || "Unknown build"; if (versions.live == build) { name += " (Live)"; } else if (versions.ptr == build) { name += " (PTR)"; } return name; }; const NavDivider = () => ( <li className="nav-separator"/> ); class DiffMenuDropdown extends React.Component { constructor(props, context) { super(props, context); this.state = {search: ""}; } onSearch = search => this.setState({search}); onToggle = () => this.setState({search: ""}); render() { const { build: curBuild, diff, type, pathname, hash, versions } = this.props; const { search } = this.state; const searchRegex = (search.trim() ? makeRegex(search, true) : null); const formatVersionItem = build => ( searchRegex ? underlinerFunc(formatVersion(versions, build), searchRegex) : formatVersion(versions, build) ); const whitelist = type && versions && versions[type]; const itemProps = build => { const props = {}; if (whitelist && !whitelist.includes(parseInt(build, 10))) { props.className = "no-data"; props.title = "No data"; } return props; }; const keys = versions && Object.keys(versions.versions).map(build => parseInt(build, 10)).sort((a, b) => b - a); const results = (keys != null && keys.filter(build => !searchRegex || formatVersion(versions, build).match(searchRegex) ).map(build => (build != curBuild ? <LinkContainer key={build} to={`${pathname}/diff/${build}${hash}`}> <MenuItem eventKey={"diff." + build} {...itemProps(build)}>{formatVersionItem(build)}</MenuItem> </LinkContainer> : <MenuItem key={build} eventKey={"diff." + build} disabled>{formatVersionItem(build)}</MenuItem> ))); return ( <NavSearchDropdown eventKey="diff" activeKey={diff ? "diff." + diff : undefined} title={diff ? "Diff against: " +formatVersion(versions, diff) : "Diff"} search={search} onSearch={this.onSearch} onToggle={this.onToggle} id="diff-menu"> {results && results.length ? results : <MenuItem header className="no-results">No Results</MenuItem>} </NavSearchDropdown> ); } } const DiffMenuActiveWrapped = withAsyncLoading({ versions: ({versions}) => versions, }, ({match: {params: {build, type, path, diff}}, location, versions}) => ( <React.Fragment> <NavDivider/> <DiffMenuDropdown build={build} type={type} diff={diff} pathname={`/${build}/${type}${path ? "/" + path : ""}`} hash={location.hash} versions={versions}/> <LinkContainer to={`/${build}/${type}${path ? "/" + path : ""}`} exact> <NavItem>Normal view</NavItem> </LinkContainer> </React.Fragment> )); const DiffMenuInactiveWrapped = withAsyncLoading({ versions: ({versions}) => versions, }, ({match: {params: {build, type}}, location, versions}) => (["items", "skills", "itemsets", "powers"].includes(type) && <React.Fragment> <NavDivider/> <DiffMenuDropdown build={build} type={type} pathname={location.pathname} hash={location.hash} versions={versions}/> </React.Fragment> )); const DiffMenu = ({versions}) => ( <Switch> <Route path="/:build/:type?/:path*/diff/:diff" render={(props) => <DiffMenuActiveWrapped {...props} versions={versions}/>}/> <Route path="/:build/:type" render={(props) => <DiffMenuInactiveWrapped {...props} versions={versions}/>}/> </Switch> ); export { DiffMenu };
packages/cf-component-card/test/Card.js
jroyal/cf-ui
import React from 'react'; import { felaSnapshot } from 'cf-style-provider'; import { Card } from '../../cf-component-card/src/index'; test('should render', () => { const snapshot = felaSnapshot(<Card>Card</Card>); expect(snapshot.component).toMatchSnapshot(); expect(snapshot.styles).toMatchSnapshot(); });
source/containers/skills-container.js
oldirony/portfolio
import React from 'react'; import {connect} from 'react-redux'; import SkillSection from '../components/home-skills'; function mapStateToProps(state){ const {skillCategories} = state.skills; return { skillCategories } } export default connect(mapStateToProps, {})(SkillSection);
frontend/src/app/components/ExperimentEolDialog.js
6a68/testpilot
import React from 'react'; export default class ExperimentEolDialog extends React.Component { render() { const { title } = this.props; return ( <div className="modal-container"> <div id="retire-dialog-modal" className="modal feedback-modal modal-bounce-in"> <header className="modal-header-wrapper warning-modal"> <h3 className="title modal-header" data-l10n-id="disableHeader">Disable Experiment?</h3> <div className="modal-cancel" onClick={e => this.cancel(e)}/> </header> <form> <div className="modal-content modal-form"> <p data-l10n-id="eolDisableMessage" data-l10n-args={JSON.stringify({ title })} className="centered"></p> </div> <div className="modal-actions"> <button onClick={e => this.proceed(e)} data-l10n-id="disableExperiment" data-l10n-args={JSON.stringify({ title })} className="submit button warning large"></button> </div> </form> </div> </div> ); } proceed(e) { e.preventDefault(); this.props.onSubmit(e); } cancel(e) { e.preventDefault(); this.props.onCancel(); } } ExperimentEolDialog.propTypes = { title: React.PropTypes.string, onCancel: React.PropTypes.func, onSubmit: React.PropTypes.func };
src/components/home.js
erik-sn/mslt
import '../sass/home.scss'; import React, { Component } from 'react'; import { Card, CardTitle, CardMedia, CardText, CardHeader } from 'material-ui/Card'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; export default class Navbar extends Component { constructor(props) { super(props); this.state = { }; } render() { return ( <div className="home-container" key={Math.random()}> <MuiThemeProvider> <Card> <CardMedia overlay={ <CardTitle title="Manufacturing Software" subtitle="Concepts from conventional manufacturing to software design" /> } > <div className="home-img-container"><img src="/resources/img/process.png" /></div> </CardMedia> <CardText> <div className="home-message"> As I learn how to program and write software I try to apply my experience in my current line of work, manufacturing. Every day I see analogies between the two - design, maintenance, working in teams, building relationships with customers, and many others. Since I have started writing software to support manufacturing activities, it only makes sense to try and learn and improve both at the same time. <p></p> This site was originally set up as a sort of tagged, searchable journal to document different skills I have been learning. I decided to try and consolidate or <strong>reduce</strong> &nbsp;some of them into organized articles. I also use it to test out new technologies and host various projects. If you have any feedback I always appreciate it! </div> </CardText> </Card> </MuiThemeProvider> </div> ); } }
src/svg-icons/communication/chat.js
rhaedes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let CommunicationChat = (props) => ( <SvgIcon {...props}> <path d="M20 2H4c-1.1 0-1.99.9-1.99 2L2 22l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zM6 9h12v2H6V9zm8 5H6v-2h8v2zm4-6H6V6h12v2z"/> </SvgIcon> ); CommunicationChat = pure(CommunicationChat); CommunicationChat.displayName = 'CommunicationChat'; export default CommunicationChat;
test/fixtures/webpack-message-formatting/src/AppNoDefault.js
Timer/create-react-app
import React, { Component } from 'react'; import myImport from './ExportNoDefault'; class App extends Component { render() { return <div className="App">{myImport}</div>; } } export default App;
packages/material-ui-icons/src/Explicit.js
allanalexandre/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0z" /><path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-4 6h-4v2h4v2h-4v2h4v2H9V7h6v2z" /></React.Fragment> , 'Explicit');