hexsha
string
size
int64
ext
string
lang
string
max_stars_repo_path
string
max_stars_repo_name
string
max_stars_repo_head_hexsha
string
max_stars_repo_licenses
list
max_stars_count
int64
max_stars_repo_stars_event_min_datetime
string
max_stars_repo_stars_event_max_datetime
string
max_issues_repo_path
string
max_issues_repo_name
string
max_issues_repo_head_hexsha
string
max_issues_repo_licenses
list
max_issues_count
int64
max_issues_repo_issues_event_min_datetime
string
max_issues_repo_issues_event_max_datetime
string
max_forks_repo_path
string
max_forks_repo_name
string
max_forks_repo_head_hexsha
string
max_forks_repo_licenses
list
max_forks_count
int64
max_forks_repo_forks_event_min_datetime
string
max_forks_repo_forks_event_max_datetime
string
content
string
avg_line_length
float64
max_line_length
int64
alphanum_fraction
float64
3d558d4dc5f93a7c466f436e545a6f624784719d
18,500
js
JavaScript
app/screens/Send/index.js
Groestlcoin/shocknet-wallet
0ecc89a695424fef1b92bbd41da45b3cb6237a46
[ "ISC" ]
null
null
null
app/screens/Send/index.js
Groestlcoin/shocknet-wallet
0ecc89a695424fef1b92bbd41da45b3cb6237a46
[ "ISC" ]
null
null
null
app/screens/Send/index.js
Groestlcoin/shocknet-wallet
0ecc89a695424fef1b92bbd41da45b3cb6237a46
[ "ISC" ]
null
null
null
/** * @format */ import React, { Component } from 'react' import { // Clipboard, StyleSheet, Text, View, ScrollView, ImageBackground, Dimensions, ActivityIndicator, Image, TouchableOpacity, Switch, } from 'react-native' import Logger from 'react-native-file-log' // @ts-ignore import { Dropdown } from 'react-native-material-dropdown' // @ts-ignore import SwipeVerify from 'react-native-swipe-verify' import Ionicons from 'react-native-vector-icons/Ionicons' import { connect } from 'react-redux' import Big from 'big.js' import wavesBG from '../../assets/images/shock-bg.png' import Nav from '../../components/Nav' import InputGroup from '../../components/InputGroup' import ContactsSearch from '../../components/Search/ContactsSearch' import Suggestion from '../../components/Search/Suggestion' import QRScanner from '../QRScanner' import BitcoinAccepted from '../../assets/images/bitcoin-accepted.png' import * as CSS from '../../res/css' import * as Wallet from '../../services/wallet' import * as API from '../../services/contact-api/index' import { selectContact, resetSelectedContact } from '../../actions/ChatActions' import { resetInvoice, decodePaymentRequest, } from '../../actions/InvoiceActions' import { WALLET_OVERVIEW } from '../WalletOverview' export const SEND_SCREEN = 'SEND_SCREEN' /** * @typedef {import('react-navigation').NavigationScreenProp<{}, {}>} Navigation */ /** * @typedef {import('../../actions/ChatActions').Contact | import('../../actions/ChatActions').BTCAddress} ContactTypes */ /** * @typedef {({ type: 'error', error: Error }|undefined)} DecodeResponse */ /** * @typedef {object} Props * @prop {(Navigation)=} navigation * @prop {import('../../../reducers/ChatReducer').State} chat * @prop {import('../../../reducers/InvoiceReducer').State} invoice * @prop {(contact: ContactTypes) => ContactTypes} selectContact * @prop {() => void} resetSelectedContact * @prop {() => void} resetInvoice * @prop {(invoice: string) => Promise<DecodeResponse>} decodePaymentRequest */ /** * @typedef {object} State * @prop {string} description * @prop {string} unitSelected * @prop {string} amount * @prop {string} contactsSearch * @prop {boolean} sending * @prop {boolean} paymentSuccessful * @prop {boolean} scanningQR * @prop {boolean} sendAll * @prop {Error|null} error */ /** * @augments React.Component<Props, State, never> */ class SendScreen extends Component { state = { description: '', unitSelected: 'gros', amount: '0', contactsSearch: '', paymentSuccessful: false, scanningQR: false, sending: false, sendAll: false, error: null, } amountOptionList = React.createRef() componentDidMount() { this.resetSearchState() } /** * @param {keyof State} key * @returns {(value: any) => void} */ onChange = key => value => { /** * @type {Pick<State, keyof State>} */ // @ts-ignore TODO: fix typing const updatedState = { [key]: value, } this.setState(updatedState) } isFilled = () => { const { amount, sendAll } = this.state const { paymentRequest } = this.props.invoice const { selectedContact } = this.props.chat return ( ((selectedContact?.address?.length > 0 || selectedContact?.type === 'contact') && parseFloat(amount) > 0) || (selectedContact?.type === 'btc' && sendAll) || !!paymentRequest ) } sendBTCRequest = async () => { try { const { selectedContact } = this.props.chat const { amount, sendAll } = this.state if (!selectedContact.address) { return } this.setState({ sending: true, }) const transactionId = await Wallet.sendCoins({ addr: selectedContact.address, amount: sendAll ? parseInt(amount, 10) : undefined, send_all: sendAll, }) Logger.log('New Transaction ID:', transactionId) this.setState({ sending: false, }) if (this.props.navigation) { this.props.navigation.goBack() } } catch (e) { Logger.log(e) this.setState({ sending: false, error: e.message, }) } } payLightningInvoice = async () => { try { const { invoice, navigation } = this.props const { amount } = this.state this.setState({ sending: true, }) await Wallet.CAUTION_payInvoice({ amt: invoice.paymentRequest && invoice.amount && Big(invoice.amount).gt(0) ? undefined : parseInt(amount, 10), payreq: invoice.paymentRequest, }) this.setState({ sending: false, paymentSuccessful: true, }) setTimeout(() => { if (navigation) { navigation.navigate(WALLET_OVERVIEW) } }, 500) } catch (err) { this.setState({ sending: false, error: err, }) } } sendPayment = async () => { try { const { chat } = this.props const { amount, description } = this.state const { selectedContact } = chat await API.Actions.sendPayment(selectedContact.pk, amount, description) return true } catch (err) { this.setState({ sending: false, error: err, }) return false } } resetSearchState = () => { const { resetSelectedContact, resetInvoice } = this.props resetSelectedContact() resetInvoice() this.setState({ contactsSearch: '', }) } renderContactsSearch = () => { const { chat, invoice } = this.props const { contactsSearch } = this.state if (invoice.paymentRequest) { return ( <Suggestion name={invoice.paymentRequest} onPress={this.resetSearchState} type="invoice" style={styles.suggestion} /> ) } if (!chat.selectedContact) { return ( <ContactsSearch onChange={this.onChange('contactsSearch')} onError={this.onChange('error')} enabledFeatures={['btc', 'invoice', 'contacts']} placeholder="Enter invoice or address..." value={contactsSearch} style={styles.contactsSearch} /> ) } if (chat.selectedContact.type === 'btc') { return ( <Suggestion name={chat.selectedContact.address} onPress={this.resetSearchState} type="btc" style={styles.suggestion} /> ) } return ( <Suggestion name={chat.selectedContact.displayName} avatar={chat.selectedContact.avatar} onPress={this.resetSearchState} style={styles.suggestion} /> ) } getErrorMessage = () => { const { error } = this.state if (!error) { return null } // @ts-ignore Typescript is being crazy here if (error.message) { // @ts-ignore return error.message } return error } toggleQRScreen = () => { const { scanningQR } = this.state this.setState({ scanningQR: !scanningQR, }) } /** * @param {string} address */ sanitizeAddress = address => address.replace(/(.*):/, '').replace(/\?(.*)/, '') /** * @param {string} value */ isBTCAddress = value => { const sanitizedAddress = this.sanitizeAddress(value) const btcTest = /^[13][a-km-zA-HJ-NP-Z1-9]{25,34}$/.test(sanitizedAddress) const bech32Test = /^(bc1|[13])[a-zA-HJ-NP-Z0-9]{25,90}$/.test( sanitizedAddress, ) return btcTest || bech32Test } /** * @param {string} value */ isLightningInvoice = value => /^(ln(tb|bc))[0-9][a-z0-9]{180,7089}$/.test(value.toLowerCase()) /** * @param {string} data */ sanitizeQR = data => data.replace(/((lightning:)|(http(s)?:\/\/))/gi, '') onQRRead = async (data = '') => { this.resetSearchState() const { decodePaymentRequest, selectContact } = this.props const sanitizedQR = this.sanitizeQR(data) Logger.log('QR Value:', sanitizedQR) Logger.log('Lightning Invoice?', this.isLightningInvoice(sanitizedQR)) Logger.log('GRS Address?', this.isBTCAddress(sanitizedQR)) this.onChange('error')('') if (this.isLightningInvoice(sanitizedQR)) { const data = await decodePaymentRequest(sanitizedQR) if (data && data.type === 'error') { this.onChange('error')(data.error.message) } } else if (this.isBTCAddress(sanitizedQR)) { selectContact({ address: this.sanitizeAddress(sanitizedQR), type: 'btc' }) } else { this.onChange('error')('Invalid QR Code') } this.toggleQRScreen() } onSwipe = async () => { try { const { invoice, chat } = this.props if (chat.selectedContact?.type === 'contact') { await this.sendPayment() return true } if (invoice.paymentRequest) { await this.payLightningInvoice() return true } await this.sendBTCRequest() return true } catch (err) { return false } } render() { const { description, unitSelected, amount, sending, error, paymentSuccessful, scanningQR, sendAll, } = this.state const { navigation, invoice, chat } = this.props const { width, height } = Dimensions.get('window') const editable = !!( invoice.paymentRequest && invoice.amount && Big(invoice.amount).eq(0) ) || !invoice.paymentRequest if (scanningQR) { return ( <View style={CSS.styles.flex}> <QRScanner onQRSuccess={this.onQRRead} toggleQRScreen={this.toggleQRScreen} type="send" /> </View> ) } return ( <ImageBackground source={wavesBG} resizeMode="cover" style={styles.container} > <Nav backButton title="Send" navigation={navigation} /> <View style={[ styles.sendContainer, { width: width - 50, maxHeight: height - 200, }, ]} > <ScrollView> <View style={styles.scrollInnerContent}> {error ? ( <View style={styles.errorRow}> <Text style={styles.errorText}>{this.getErrorMessage()}</Text> </View> ) : null} <TouchableOpacity style={styles.scanBtn} onPress={this.toggleQRScreen} > <Text style={styles.scanBtnText}>SCAN QR</Text> <Ionicons name="md-qr-scanner" color="gray" size={24} /> </TouchableOpacity> {this.renderContactsSearch()} {invoice.paymentRequest ? ( <InputGroup label="Destination" value={invoice.recipientAddress} style={styles.destinationInput} inputStyle={styles.destinationInput} disabled /> ) : null} <View style={styles.amountContainer}> <InputGroup label="Enter Amount" value={!editable ? invoice.amount : amount} onChange={this.onChange('amount')} style={styles.amountInput} disabled={!editable} type="numeric" /> <Dropdown data={[ { value: 'gros', }, { value: 'GRS', }, ]} disabled={!editable} onChangeText={this.onChange('unitSelected')} containerStyle={styles.amountSelect} value={invoice.paymentRequest ? 'gros' : unitSelected} lineWidth={0} inputContainerStyle={styles.amountSelectInput} rippleOpacity={0} pickerStyle={styles.amountPicker} dropdownOffset={{ top: 8, left: 0 }} rippleInsets={{ top: 8, bottom: 0, right: 0, left: 0 }} /> </View> {chat.selectedContact?.type === 'btc' ? ( <View style={styles.toggleContainer}> <Text style={styles.toggleTitle}>Send All</Text> <Switch value={sendAll} onValueChange={this.onChange('sendAll')} /> </View> ) : null} <InputGroup label="Description" value={ invoice.paymentRequest ? invoice.description : description } multiline onChange={this.onChange('description')} inputStyle={styles.descInput} disabled={!!invoice.paymentRequest} /> {sending ? ( <View style={[ styles.sendingOverlay, { width: width - 50, height: height - 194, }, ]} > <ActivityIndicator color={CSS.Colors.FUN_BLUE} size="large" /> <Text style={styles.sendingText}>Sending Transaction...</Text> </View> ) : null} {paymentSuccessful ? ( <View style={[ styles.sendingOverlay, { width: width - 50, height: height - 194, }, ]} > <Ionicons name="md-checkmark-circle-outline" size={60} color={CSS.Colors.FUN_BLUE} /> <Text style={styles.sendingText}> Transaction sent successfully! </Text> </View> ) : null} </View> </ScrollView> </View> <View style={styles.sendSwipeContainer}> {this.isFilled() ? ( <SwipeVerify width="100%" buttonSize={60} height={50} style={styles.swipeBtn} buttonColor={CSS.Colors.BACKGROUND_WHITE} borderColor={CSS.Colors.TRANSPARENT} backgroundColor={CSS.Colors.BACKGROUND_WHITE} textColor="#37474F" borderRadius={100} swipeColor={CSS.Colors.GOLD} icon={ <Image source={BitcoinAccepted} resizeMethod="resize" resizeMode="contain" style={styles.btcIcon} /> } disabled={!this.isFilled()} onVerified={this.onSwipe} > <Text style={styles.swipeBtnText}>SLIDE TO SEND</Text> </SwipeVerify> ) : null} </View> </ImageBackground> ) } } /** @param {{ invoice: import('../../../reducers/InvoiceReducer').State, chat: import('../../../reducers/ChatReducer').State }} state */ const mapStateToProps = ({ chat, invoice }) => ({ chat, invoice }) const mapDispatchToProps = { selectContact, resetSelectedContact, resetInvoice, decodePaymentRequest, } export default connect( mapStateToProps, mapDispatchToProps, )(SendScreen) const styles = StyleSheet.create({ container: { height: 170, flex: 1, justifyContent: 'flex-start', alignItems: 'center', }, contactsSearch: { marginBottom: 20 }, sendContainer: { marginTop: 5, backgroundColor: CSS.Colors.BACKGROUND_WHITE, height: 'auto', borderRadius: 40, overflow: 'hidden', }, scrollInnerContent: { height: '100%', width: '100%', paddingVertical: 23, paddingHorizontal: 35, paddingBottom: 0, }, destinationInput: { marginBottom: 10, }, suggestion: { marginVertical: 10 }, sendingOverlay: { position: 'absolute', left: 0, top: 0, right: 0, width: '100%', height: '100%', alignItems: 'center', justifyContent: 'center', backgroundColor: CSS.Colors.BACKGROUND_WHITE_TRANSPARENT95, elevation: 10, zIndex: 1000, }, sendingText: { color: CSS.Colors.TEXT_GRAY, fontSize: 14, fontFamily: 'Montserrat-700', marginTop: 10, }, errorRow: { width: '100%', paddingVertical: 5, paddingHorizontal: 15, borderRadius: 100, backgroundColor: CSS.Colors.BACKGROUND_RED, alignItems: 'center', marginBottom: 10, }, errorText: { fontFamily: 'Montserrat-700', color: CSS.Colors.TEXT_WHITE, textAlign: 'center', }, scanBtn: { width: '100%', flexDirection: 'row', backgroundColor: CSS.Colors.BACKGROUND_WHITE, paddingVertical: 10, alignItems: 'center', justifyContent: 'center', borderRadius: 30, marginBottom: 30, elevation: 10, }, scanBtnText: { color: CSS.Colors.GRAY, fontSize: 14, fontFamily: 'Montserrat-700', marginRight: 10, }, amountContainer: { width: '100%', flexDirection: 'row', justifyContent: 'space-between', alignItems: 'flex-end', marginBottom: 20, }, amountInput: { width: '60%', marginBottom: 0, }, amountSelect: { width: '35%', marginBottom: 0, height: 45, }, amountSelectInput: { borderBottomColor: CSS.Colors.TRANSPARENT, elevation: 4, paddingHorizontal: 15, borderRadius: 100, height: 45, alignItems: 'center', backgroundColor: CSS.Colors.BACKGROUND_WHITE, }, amountPicker: { borderRadius: 15 }, toggleContainer: { flexDirection: 'row', justifyContent: 'space-between', }, toggleTitle: { fontFamily: 'Montserrat-700', }, sendSwipeContainer: { width: '100%', height: 70, paddingHorizontal: 35, justifyContent: 'center', marginTop: 10, }, swipeBtn: { marginBottom: 10, }, btcIcon: { height: 30, }, swipeBtnText: { fontSize: 12, fontFamily: 'Montserrat-700', color: CSS.Colors.TEXT_GRAY, }, descInput: { height: 90, borderRadius: 15, textAlignVertical: 'top', }, })
26.241135
136
0.544162
3d55cdde4d8077284642941a0c81fcb12ad0e4ea
608
js
JavaScript
components/common/Dot.js
syuneara/neara_data
ff1316983be320c21375d3a860109d6e613d28d5
[ "MIT" ]
null
null
null
components/common/Dot.js
syuneara/neara_data
ff1316983be320c21375d3a860109d6e613d28d5
[ "MIT" ]
null
null
null
components/common/Dot.js
syuneara/neara_data
ff1316983be320c21375d3a860109d6e613d28d5
[ "MIT" ]
null
null
null
import React from "react"; import PropTypes from "prop-types"; import classNames from "classnames"; import styles from "./Dot.module.css"; function Dot({ color, size, className }) { return ( <div className={styles.wrapper}> <div style={{ background: color }} className={classNames(styles.dot, className, { [styles.small]: size === "small", [styles.large]: size === "large", })} /> </div> ); } Dot.propTypes = { color: PropTypes.string, size: PropTypes.oneOf(["small", "large"]), className: PropTypes.string, }; export default Dot;
22.518519
54
0.606908
3d57301c82428d74b418273531967bed98831728
398
js
JavaScript
index.js
lamansky/copy-own
532ddfdd4ef517fa6391f3209414e6f7f847cdde
[ "MIT" ]
null
null
null
index.js
lamansky/copy-own
532ddfdd4ef517fa6391f3209414e6f7f847cdde
[ "MIT" ]
null
null
null
index.js
lamansky/copy-own
532ddfdd4ef517fa6391f3209414e6f7f847cdde
[ "MIT" ]
null
null
null
'use strict' module.exports = function copyOwn (from, to = {}, {enumOnly, override = true, overwrite = true} = {}) { for (const key of (enumOnly ? Object.keys : Reflect.ownKeys)(from)) { if ((overwrite || !Object.prototype.hasOwnProperty.call(to, key)) && (override || !(key in to))) { Object.defineProperty(to, key, Object.getOwnPropertyDescriptor(from, key)) } } return to }
36.181818
103
0.650754
3d577fff4493c00f24f4907da3fb6ca6721e6178
1,713
js
JavaScript
client/cypress/support/redash-api/index.js
ivanli1990/redash
4508975749368e5851fd01f88b83a7aa16c58f62
[ "BSD-2-Clause" ]
1
2019-07-31T01:41:13.000Z
2019-07-31T01:41:13.000Z
client/cypress/support/redash-api/index.js
ivanli1990/redash
4508975749368e5851fd01f88b83a7aa16c58f62
[ "BSD-2-Clause" ]
1
2019-05-21T14:38:05.000Z
2019-05-23T09:30:55.000Z
client/cypress/support/redash-api/index.js
ivanli1990/redash
4508975749368e5851fd01f88b83a7aa16c58f62
[ "BSD-2-Clause" ]
null
null
null
/* global cy, Cypress */ const { extend, get, merge } = Cypress._; export function createDashboard(name) { return cy.request('POST', 'api/dashboards', { name }) .then(({ body }) => body); } export function createQuery(data, shouldPublish = true) { const merged = extend({ name: 'Test Query', query: 'select 1', data_source_id: 1, options: { parameters: [], }, schedule: null, }, data); // eslint-disable-next-line cypress/no-assigning-return-values let request = cy.request('POST', '/api/queries', merged); if (shouldPublish) { request = request.then(({ body }) => ( cy.request('POST', `/api/queries/${body.id}`, { is_draft: false }) .then(() => body) )); } return request; } export function addTextbox(dashboardId, text = 'text', options = {}) { const defaultOptions = { position: { col: 0, row: 0, sizeX: 3, sizeY: 3 }, }; const data = { width: 1, dashboard_id: dashboardId, visualization_id: null, text, options: merge(defaultOptions, options), }; return cy.request('POST', 'api/widgets', data) .then(({ body }) => { const id = get(body, 'id'); assert.isDefined(id, 'Widget api call returns widget id'); return body; }); } export function addWidget(dashboardId, visualizationId) { const data = { width: 1, dashboard_id: dashboardId, visualization_id: visualizationId, options: { position: { col: 0, row: 0, sizeX: 3, sizeY: 3 }, }, }; return cy.request('POST', 'api/widgets', data) .then(({ body }) => { const id = get(body, 'id'); assert.isDefined(id, 'Widget api call returns widget id'); return body; }); }
24.126761
72
0.594279
3d5780c3617e112c9d9516d284e61420ad73f081
6,225
js
JavaScript
native/packages/react-native-bpk-component-button/stories.js
sogame/backpack
e833eb69f3834d16faff764ccd6b1f98e4ec49a3
[ "Apache-2.0" ]
null
null
null
native/packages/react-native-bpk-component-button/stories.js
sogame/backpack
e833eb69f3834d16faff764ccd6b1f98e4ec49a3
[ "Apache-2.0" ]
null
null
null
native/packages/react-native-bpk-component-button/stories.js
sogame/backpack
e833eb69f3834d16faff764ccd6b1f98e4ec49a3
[ "Apache-2.0" ]
null
null
null
/* * Backpack - Skyscanner's Design System * * Copyright 2017 Skyscanner Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import React from 'react'; import { Text, StyleSheet, View, ScrollView, Platform, } from 'react-native'; import { storiesOf } from '@storybook/react-native'; import { action } from '@storybook/addon-actions'; import BpkThemeProvider from 'react-native-bpk-theming'; import { StoryHeading, StorySubheading } from '../../storybook/TextStyles'; import BpkButton, { BUTTON_TYPES } from './src/BpkButton'; const tokens = Platform.OS === 'ios' ? require('bpk-tokens/tokens/ios/base.react.native.common.js') : require('bpk-tokens/tokens/android/base.react.native.common.js'); const styles = StyleSheet.create({ btnContainer: { flexDirection: 'row', flexWrap: 'wrap', justifyContent: 'flex-start', }, buttonStyles: { marginBottom: tokens.spacingMd, marginRight: tokens.spacingMd, }, }); const theme = { contentColor: '#2d244c', backgroundColor: tokens.colorWhite, brandColors: { gradientStart: '#fce134', gradientEnd: '#f8c42d', }, }; const themeAttributes = { buttonPrimaryGradientStartColor: theme.brandColors.gradientStart, buttonPrimaryGradientEndColor: theme.brandColors.gradientEnd, buttonPrimaryTextColor: theme.contentColor, buttonSecondaryBackgroundColor: theme.backgroundColor, buttonSecondaryTextColor: theme.contentColor, buttonSecondaryBorderColor: theme.contentColor, }; const getIconType = type => ( type === 'destructive' ? 'trash' : 'long-arrow-right' ); const generateButtonStoryForType = (type) => { function getLargeVersion() { return ( <View> <StorySubheading>Large</StorySubheading> <View style={styles.btnContainer}> <BpkButton large type={type} title="Button" onPress={action(`${type} pressed`)} style={styles.buttonStyles} /> <BpkButton large type={type} disabled title="Disabled" onPress={action(`${type} disabled pressed, somehow`)} style={styles.buttonStyles} /> <BpkButton large type={type} title="Icon only" icon={getIconType(type)} iconOnly onPress={action(`${type} icon only button clicked`)} style={styles.buttonStyles} /> </View> </View> ); } return ( <View key={type}> <StorySubheading>Default</StorySubheading> <View style={styles.btnContainer}> <BpkButton type={type} title="Button" onPress={action(`${type} pressed`)} style={styles.buttonStyles} /> <BpkButton type={type} disabled title="Disabled" onPress={action(`${type} disabled pressed, somehow`)} style={styles.buttonStyles} /> {Platform.OS === 'ios' ? <BpkButton type={type} title="Icon only" icon={getIconType(type)} iconOnly onPress={action(`${type} icon only button clicked`)} style={styles.buttonStyles} /> : null} </View> {Platform.OS === 'ios' ? getLargeVersion() : null} </View> ); }; const allButtonStories = BUTTON_TYPES.map(generateButtonStoryForType); const allThemedButtons = ( <BpkThemeProvider theme={themeAttributes}> <View> <StoryHeading>Primary</StoryHeading> {generateButtonStoryForType('primary')} <StoryHeading>Secondary</StoryHeading> {generateButtonStoryForType('secondary')} </View> </BpkThemeProvider> ); storiesOf('BpkButton', module) .add('docs:primary', () => ( <View> {generateButtonStoryForType('primary')} </View> )) .add('docs:secondary', () => ( <View> {generateButtonStoryForType('secondary')} </View> )) .add('docs:destructive', () => ( <View> {generateButtonStoryForType('destructive')} </View> )) .add('docs:featured', () => ( <View> {generateButtonStoryForType('featured')} </View> )) .add('docs:withTheme', () => allThemedButtons) .add('All Button Types', () => ( <ScrollView> <StoryHeading>All Types</StoryHeading> {allButtonStories} <StoryHeading>Themed</StoryHeading> {allThemedButtons} </ScrollView> )) .add('Edge Cases', () => { function getLargeVersion() { return ( <BpkButton large type="primary" title="I also have a really long title" onPress={action('Large button with long title pressed')} style={styles.buttonStyles} /> ); } function getIconOnlyVersion() { return ( <View> <StorySubheading>Passing arbitrary components as the icon prop</StorySubheading> <BpkButton type="primary" title="I am an icon" icon={<Text>Foo</Text>} iconOnly onPress={action('Image component button pressed')} /> </View> ); } return ( <View> <StoryHeading>Edge Cases</StoryHeading> <StorySubheading>Long button titles</StorySubheading> <BpkButton type="primary" title="I have a really long title" onPress={action('Button with long title pressed')} style={styles.buttonStyles} /> {Platform.OS === 'ios' ? <View> {getLargeVersion()} {getIconOnlyVersion()} </View> : null} </View>); });
26.948052
90
0.597751
3d57f6aa377f90b9c7e95f035c65c52f5654268f
4,230
js
JavaScript
Angular2Testing/node_modules/ng-dynamic/src/dynamic-component/dynamic-component.directive.js
rdonalson/General-Testing
834ca4cefdbba12afe1d7dd4b58a31fc9eb5e3fd
[ "MIT" ]
null
null
null
Angular2Testing/node_modules/ng-dynamic/src/dynamic-component/dynamic-component.directive.js
rdonalson/General-Testing
834ca4cefdbba12afe1d7dd4b58a31fc9eb5e3fd
[ "MIT" ]
null
null
null
Angular2Testing/node_modules/ng-dynamic/src/dynamic-component/dynamic-component.directive.js
rdonalson/General-Testing
834ca4cefdbba12afe1d7dd4b58a31fc9eb5e3fd
[ "MIT" ]
null
null
null
import { Component, Compiler, Directive, Input, NgModule, ViewContainerRef, ReflectiveInjector } from '@angular/core'; import { DynamicComponentOptions } from './options'; /** * DynamicComponent is a directive to create dynamic component. * * Example: * * ```ts * @Component({ * selector: 'my-app', * template: ` * <div *dynamicComponent="template; context: self; selector:'my-component'"></div> * ` * }) * export class AppComponent { * self = this; * * template = ` * <div> * <p>Dynamic Component</p> * </div>`; * } * ``` * * Result: * * ```html * <my-component> * <div> * <p>Dynamic Component</p> * </div> * </my-component> * ``` * */ export var DynamicComponentDirective = (function () { function DynamicComponentDirective(options, vcRef, compiler) { this.options = options; this.vcRef = vcRef; this.compiler = compiler; } DynamicComponentDirective.prototype.createComponentType = function () { var metadata = new Component({ selector: this.selector, template: this.template, }); var cmpClass = (function () { function _() { } return _; }()); return Component(metadata)(cmpClass); }; DynamicComponentDirective.prototype.createNgModuleType = function (componentType) { var declarations = [].concat(this.options.ngModuleMetadata.declarations || []); declarations.push(componentType); var moduleMeta = { imports: this.options.ngModuleMetadata.imports, providers: this.options.ngModuleMetadata.providers, schemas: this.options.ngModuleMetadata.schemas, declarations: declarations }; return NgModule(moduleMeta)((function () { function _() { } return _; }())); }; DynamicComponentDirective.prototype.ngOnChanges = function (changes) { var _this = this; if (!this.template) { return; } this.cmpType = this.createComponentType(); this.moduleType = this.createNgModuleType(this.cmpType); var injector = ReflectiveInjector.fromResolvedProviders([], this.vcRef.parentInjector); this.compiler.compileModuleAndAllComponentsAsync(this.moduleType) .then(function (factory) { var cmpFactory; for (var i = factory.componentFactories.length - 1; i >= 0; i--) { if (factory.componentFactories[i].componentType === _this.cmpType) { cmpFactory = factory.componentFactories[i]; break; } } return cmpFactory; }, function (error) { }) .then(function (cmpFactory) { if (cmpFactory) { _this.vcRef.clear(); _this.component = _this.vcRef.createComponent(cmpFactory, 0, injector); Object.assign(_this.component.instance, _this.context); _this.component.changeDetectorRef.detectChanges(); } }); }; DynamicComponentDirective.prototype.ngOnDestroy = function () { if (this.component) { this.component.destroy(); } if (this.compiler) { if (this.cmpType) { this.compiler.clearCacheFor(this.cmpType); } if (this.moduleType) { this.compiler.clearCacheFor(this.moduleType); } } }; DynamicComponentDirective.decorators = [ { type: Directive, args: [{ selector: '[dynamicComponent]', },] }, ]; /** @nocollapse */ DynamicComponentDirective.ctorParameters = [ { type: DynamicComponentOptions, }, { type: ViewContainerRef, }, { type: Compiler, }, ]; DynamicComponentDirective.propDecorators = { 'template': [{ type: Input, args: ['dynamicComponent',] },], 'selector': [{ type: Input, args: ['dynamicComponentSelector',] },], 'context': [{ type: Input, args: ['dynamicComponentContext',] },], }; return DynamicComponentDirective; }());
32.790698
118
0.567376
3d581907f2785b7bbde2b0e95d9555728c780e5c
2,233
js
JavaScript
index.js
axetroy/stone
e11350436196c34b2cc77c787ef23beae1bf886f
[ "MIT" ]
null
null
null
index.js
axetroy/stone
e11350436196c34b2cc77c787ef23beae1bf886f
[ "MIT" ]
4
2017-07-02T02:40:46.000Z
2020-04-11T06:13:24.000Z
index.js
axetroy/stone
e11350436196c34b2cc77c787ef23beae1bf886f
[ "MIT" ]
null
null
null
export default class Stone { constructor(obj = {}) { this.subscriber = []; this.state = { ...{}, ...obj }; Object.defineProperty(this, 'state', { enumerable: false, configurable: false }); Object.defineProperty(this, 'subscriber', { enumerable: false, configurable: false }); Object.defineProperty(this, 'length', { configurable: true, enumerable: false, get() { return this.keys().length; } }); for (let key in obj) { if (obj.hasOwnProperty(key)) { this.set(key, obj[key]); } } } // 自实现的方法 set(key, value) { const oldValue = this[key]; this.state = { ...this.state, ...{ [key]: value } }; if (!Object.getOwnPropertyDescriptor(this, key)) { Object.defineProperty(this, key, { enumerable: true, configurable: true, get() { return this.state[key]; }, set(value) { throw new Error(`can't set value for ${key}, please use .set`); } }); } if (oldValue !== value) { this.subscriber.forEach(func => { func.call(this, key, oldValue, value); }); } return this; } remove(key) { delete this.state[key]; if (this.hasOwnProperty(key)) { delete this[key]; } return this; } subscribe(func) { func.__id__ = Math.random().toFixed(5); this.subscriber.push(func); return () => { const index = this.subscriber.findIndex(handler => { return handler.__id__ && handler.__id__ === func.__id__; }); if (index >= 0) { this.subscriber.splice(index, 1); } }; } watch(key, callback) { return this.subscribe((_key, oldValue, newValue) => { if (key === _key) { callback.call(this, oldValue, newValue); } }); } // Object method keys() { return Object.keys(this.state); } values() { let values = []; for (let key in this.state) { if (this.state.hasOwnProperty(key)) { values.push(this.state[key]); } } return values; } toString() { return this.state.toString(); } stringify() { return JSON.stringify(this.state); } }
21.066038
73
0.535155
3d58e0442ccac8698ff9438262c5a226575ad1d3
3,617
js
JavaScript
geonode_mapstore_client/static/geonode/js/ms2/utils/ms2_base_plugins.js
kartoza/geonode-mapstore-client
276e9d898671764fe762b03ab6a74f34eb9969ac
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
geonode_mapstore_client/static/geonode/js/ms2/utils/ms2_base_plugins.js
kartoza/geonode-mapstore-client
276e9d898671764fe762b03ab6a74f34eb9969ac
[ "BSD-2-Clause-FreeBSD" ]
2
2021-06-21T06:53:05.000Z
2022-03-22T07:19:55.000Z
geonode_mapstore_client/static/geonode/js/ms2/utils/ms2_base_plugins.js
kartoza/geonode-mapstore-client
276e9d898671764fe762b03ab6a74f34eb9969ac
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
/** Base configuration for map and layer preview These are maps are shown embedded in geonode */ var MS2_BASE_PLUGINS = { "desktop": [{ "name": "Map", "cfg": { "tools": ["locate", "measurement", "draw", "box"], "mapOptions": { "openlayers": { "attribution": { "container": "#footer-attribution-container" }, "interactions": { "pinchRotate": false, "altShiftDragRotate": false } } }, "toolsOptions": { "locate": { // "maxZoom": 5 use a custom max zoom } } } }, { "name": "BackgroundSelector", "cfg": { "style": { "bottom": 0, "marginBottom": 25 }, "dimensions": { "side": 65, "sidePreview": 65, "frame": 3, "margin": 5, "label": false, "vertical": true, } } }, { "name": "Identify", "cfg": { "showFullscreen": false, "dock": true, "position": "right", "size": 0.4, "fluid": true, "viewerOptions": { "container": "{context.ReactSwipe}" } }, "override": { "Toolbar": { "position": 11, "alwaysVisible": false } } }, { "name": "TOC", "cfg": { "activateMapTitle": false, "activateMetedataTool": false, "activateRemoveLayer": false, "activateAddGroupButton": true } }, { "name": "Settings", "cfg": { "wrap": true } }, { "name": "Toolbar", "id": "NavigationBar", "cfg": { "id": "navigationBar", "layout": "horizontal" } }, { "name": "MapLoading", "override": { "Toolbar": { "alwaysVisible": true } } }, { "name": "DrawerMenu", "cfg": { "show": true } }, "Cookie", "OmniBar", "Expander", "Undo", "Redo", "BurgerMenu", "MapFooter", "Measure", "Annotations", "Share", "AddGroup", "GeonodeMetadata", "IgracDownload", { "name": "CRSSelector", "cfg": { "filterAllowedCRS": [ "EPSG:4326", "EPSG:3857" ], "additionalCRS": {} } }, { "name": "Tutorial", "cfg": { "presetList": { "default_tutorial": [ { "selector": "#map-search-bar", "title": "Search Bar", "text": "Write the address of a place to find. e.g. '1st avenue, new york'. " + "You can even insert coordinates in this format: 43.87,10.20", }, { "selector": "#zoomin-btn", "title": "Zoom In", "text": "Click to enlarge the map", }, { "selector": "#zoomout-btn", "title": "Zoom Out", "text": "Click to reduce the map", }, { "selector": ".glyphicon-add-layer", "title": "Add Layer", "text": "Browse services (WMS/WMTS/CSW) to add layers to the map", }, { "selector": ".glyphicon-add-folder", "title": "Add Layer Group", "text": "Allows users to create new layer groups in the TOC", } ] } } }, { "name": "Print", "cfg": { "disablePluginIf": "{state('mapType') === 'cesium'}", "useFixedScales": true, "mapWidth": 256 } }, { "name": "ZoomAll", "override": { "Toolbar": { "alwaysVisible": false } } }, { "name": "ZoomIn", "override": { "Toolbar": { "alwaysVisible": true } } }, { "name": "ZoomOut", "override": { "Toolbar": { "alwaysVisible": true } } }, { "name": "Timeline", "cfg": { "style": { "marginBottom": 30, "marginLeft": 80, "marginRight": 45 }, "compact": true } }, "Playback", { "name": "LayerDownload" } ] }
18.085
96
0.482997
3d59559f790330a7ddb73fb2769e7dfd1d949a8c
468
js
JavaScript
JS_Fundamentals/05. Exercises Functions and Arrow Functions/03. Template Format.js
ekov1/SoftUni-Exercises
12e3035692512f2b7273e2e75538bb6df1a08e88
[ "MIT" ]
null
null
null
JS_Fundamentals/05. Exercises Functions and Arrow Functions/03. Template Format.js
ekov1/SoftUni-Exercises
12e3035692512f2b7273e2e75538bb6df1a08e88
[ "MIT" ]
null
null
null
JS_Fundamentals/05. Exercises Functions and Arrow Functions/03. Template Format.js
ekov1/SoftUni-Exercises
12e3035692512f2b7273e2e75538bb6df1a08e88
[ "MIT" ]
null
null
null
function printTemplates(input) { let template = `<?xml version="1.0" encoding="UTF-8"?> <quiz> `; function printTemplate([str1, str2]) { template += `<question> ${str1} </question> <answer> ${str2} </answer>\n`; } for (let i = 0; i < input.length - 1; i += 2) { let [question, answer] = [input[i], input[i + 1]]; printTemplate([question, answer]); } template += '</quiz>'; console.log(template); }
19.5
58
0.534188
3d5958fd851b4eb6a8fe158b7ff474aeb5e276c9
408
js
JavaScript
static/js/hotjar.js
LBHackney-IT/education-evidence-upload-tool
5339c166fd6b2411e251a722a62c3c7cd56d981c
[ "MIT" ]
2
2022-03-11T11:09:08.000Z
2022-03-11T11:09:12.000Z
static/js/hotjar.js
LBHackney-IT/education-evidence-upload-tool
5339c166fd6b2411e251a722a62c3c7cd56d981c
[ "MIT" ]
null
null
null
static/js/hotjar.js
LBHackney-IT/education-evidence-upload-tool
5339c166fd6b2411e251a722a62c3c7cd56d981c
[ "MIT" ]
null
null
null
(function(h, o, t, j, a, r) { h.hj = h.hj || function() { (h.hj.q = h.hj.q || []).push(arguments); }; h._hjSettings = { hjid: 1958227, hjsv: 6 }; a = o.getElementsByTagName('head')[0]; r = o.createElement('script'); r.async = 1; r.src = t + h._hjSettings.hjid + j + h._hjSettings.hjsv; a.appendChild(r); })(window, document, 'https://static.hotjar.com/c/hotjar-', '.js?sv=');
29.142857
71
0.558824
3d596c54089d2a999fd6a3b8291c81687484e310
2,066
js
JavaScript
index.js
mreinstein/nexkey
787b759f58a8dfbddff0f49659deacbd985ffe72
[ "MIT" ]
3
2018-03-27T22:16:19.000Z
2019-08-20T16:43:35.000Z
index.js
mreinstein/nexkey
787b759f58a8dfbddff0f49659deacbd985ffe72
[ "MIT" ]
3
2018-03-21T22:36:21.000Z
2018-06-11T15:07:27.000Z
index.js
mreinstein/nexkey
787b759f58a8dfbddff0f49659deacbd985ffe72
[ "MIT" ]
null
null
null
import fetch from 'node-fetch' // dashboard (production) https://nexkey-web.herokuapp.com/apikeys // dashboard (sandbox) https://nk-web-beta.herokuapp.com/apikeys // CONFIRMED by Nexkey: if phone and email are listed for 2 users, // the sendKey and revokeKey functions prioritize phone number and ignore // the email if a user is found with the phone number. export default function nexkey(options) { const { NEXKEY_API_SECRET, NEXKEY_API_KEY } = options const API_HOST = (options.ENVIRONMENT === 'STAGING') ? 'https://nexkey-beta.herokuapp.com' : 'https://api.nexkey.com' const signIn = async function(options) { const { userIdentifier, password } = options return _post('signIn', { userIdentifier, password }) } // @return Array Retrieve keys for a target lock. const getLockUsers = async function(lockId) { return _post('getLockUsers', { lockId }) } const sendKey = async function(options) { const { phone, email, lockId } = options return _post('sendKey', { email, phone, lockId }) } const revokeKey = async function(options) { const { phone, email, lockId } = options return _post('revokeKey', { email, phone, lockId }) } // returns list of user's keys intersecting with the all of the keys accessible to the nexkey account // NOTE: passing empty phone and email returns all keys for the API key const getUserKeys = async function(options) { const { phone, email } = options return _post('getUserKeys', { email, phone }) } // @return Promise resolves to a javascript object const _post = async function(fnName, body) { const url = API_HOST + '/rest/functions/' + fnName const result = await fetch(url, { method: 'POST', body: JSON.stringify(body), headers: { 'Nexkey-Api-Version': '2.0.0', 'Nexkey-Api-Secret': NEXKEY_API_SECRET, 'Nexkey-Api-Key': NEXKEY_API_KEY, 'Content-Type': 'application/json', } }) return result.json() } return { signIn, getLockUsers, sendKey, revokeKey, getUserKeys } }
29.942029
119
0.677154
3d599d345cbb5fad2540f4c818ba7397b49e7107
518
js
JavaScript
tasks/replace.js
khanani92/SimpleCurrencyConverter-forClientTest
1cb3255e937367b18563495ae733e25108e07ecf
[ "MIT" ]
null
null
null
tasks/replace.js
khanani92/SimpleCurrencyConverter-forClientTest
1cb3255e937367b18563495ae733e25108e07ecf
[ "MIT" ]
null
null
null
tasks/replace.js
khanani92/SimpleCurrencyConverter-forClientTest
1cb3255e937367b18563495ae733e25108e07ecf
[ "MIT" ]
null
null
null
module.exports = { scripts: { src: ['.tmp/concat/scripts/*.js'], overwrite: true, replacements: [{ from: /src\/[a-zA-Z0-9]*\//g, to: 'views/' }, { from: "angular.module('app', [", to: "angular.module('app', ['templates-htmlmin'," }] }, styles: { src: ['dist/styles/main.css'], overwrite: true, replacements: [{ from: '../../fonts', to: '../fonts' }, { from: '../../images', to: '../images' }] } };
19.185185
57
0.436293
3d59f9ba628de99ca7db65fb796337038cf37e1f
15,243
js
JavaScript
ide/main/src/content/application.js
davidgonzalezbarbe/Selenium
55e370c99a289d36a6ecc41978f7fe2d3813b21c
[ "Apache-2.0" ]
12
2015-02-13T14:53:27.000Z
2020-03-23T07:47:39.000Z
ide/main/src/content/application.js
davidgonzalezbarbe/Selenium
55e370c99a289d36a6ecc41978f7fe2d3813b21c
[ "Apache-2.0" ]
3
2017-02-13T11:30:32.000Z
2022-02-13T15:14:07.000Z
ide/main/src/content/application.js
davidgonzalezbarbe/Selenium
55e370c99a289d36a6ecc41978f7fe2d3813b21c
[ "Apache-2.0" ]
14
2015-04-29T15:01:54.000Z
2022-03-18T14:48:29.000Z
/* * Copyright 2005 Shinya Kasatani * * 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. */ // shortcut this.Preferences = SeleniumIDE.Preferences; /* * A model that represents the state of the application. */ function Application() { this.baseURL = ""; this.options = Preferences.load(); this.pluginManager = new PluginManager(this.options); this.baseURLHistory = new StoredHistory("baseURLHistory", 20); this.testCase = null; this.testSuite = null; this.formats = null; this.currentFormat = null; this.clipboardFormat = null; this.recentTestSuites = new StoredHistory("recentTestSuites"); this.recentTestCases = new StoredHistory("recentTestCases"); } Application.prototype = { saveState: function() { if (this.options.rememberBaseURL == 'true'){ Preferences.setAndSave(this.options, 'baseURL', this.baseURL); } }, getBaseURL: function() { //if there is a testCase with a base URL return it //if not, return the value of the baseURL value return this.testCase && this.testCase.baseURL ? this.testCase.baseURL : this.baseURL; }, setBaseURL: function(baseURL) { this.baseURL = baseURL; this.baseURLHistory.add(baseURL); if (this.testCase) { this.testCase.setBaseURL(baseURL); } this.notify("baseURLChanged"); }, getBaseURLHistory: function() { return this.baseURLHistory.list(); }, initOptions: function() { if (this.options.rememberBaseURL == 'true' && this.options.baseURL != null) { this.setBaseURL(this.options.baseURL); } this.setOptions(this.options); // to notify optionsChanged to views }, getBooleanOption: function(option) { if (this.options[option]){ return this.options[option].toLowerCase() == 'true'; } return false; }, getOptions: function(options) { return this.options; }, setOptions: function(options) { this.options = options; this.pluginManager.load(options); this.formats = new FormatCollection(options, this.pluginManager); this.currentFormat = this.formats.selectFormat(options.selectedFormat || null); this.clipboardFormat = this.formats.selectFormat(options.clipboardFormat || null); this.notify("optionsChanged", options); }, userSetCurrentFormat: function(format) { //Samit: TODO: this whole concept of format changing needs to be thought through again //if the testcase is manually changed var edited = this.testCase.edited; //if the format is reversible (implements the "parse" method) //or if the testcase isn't changed manually by user: all be fine //if not, the format isn't changed if (this.currentFormat != format) { //if (!(this.currentFormat.isReversible && this.currentFormat.isReversible())){ //prompt that user will lose changes if (this.getBooleanOption('disableFormatChangeMsg') || confirm(Editor.getString('format.switch.warn'))){ //user wants to take the risk //change the current format this.setCurrentFormat(format); } //} } }, setCurrentFormat: function(format) { //sync the testcase with the data view this.notify("currentFormatChanging"); this.currentFormat = format; Preferences.setAndSave(this.options, 'selectedFormat', format.id); this.notify("currentFormatChanged", format); }, getCurrentFormat: function() { return this.currentFormat; }, isPlayable: function() { return this.getCurrentFormat().getFormatter().playable; }, setClipboardFormat: function(format) { this.clipboardFormat = format; Preferences.setAndSave(this.options, 'clipboardFormat', format.id); this.notify("clipboardFormatChanged", format); }, getClipboardFormat: function() { return this.clipboardFormat; }, getFormats: function() { return this.formats; }, newTestSuite: function() { this.log.debug("newTestSuite"); var testSuite = new TestSuite(); var testCase = new TestCase(); testSuite.addTestCaseFromContent(testCase); this.setTestSuite(testSuite); this.setTestCase(testCase); Preferences.setAndSave(this.options, 'lastSavedTestSuite', ''); Preferences.setAndSave(this.options, 'lastSavedTestCase', ''); }, setTestSuite: function(testSuite) { if (this.testSuite) { this.notify("testSuiteUnloaded", this.testSuite); } this.testSuite = testSuite; this.notify("testSuiteChanged", testSuite); }, getTestSuite: function() { return this.testSuite; }, addRecentTestSuite: function(testSuite) { this.recentTestSuites.add(testSuite.file.path); Preferences.setAndSave(this.options, 'lastSavedTestSuite', testSuite.file.path); Preferences.setAndSave(this.options, 'lastSavedTestCase', ''); }, addRecentTestCase: function(testCase, isNewSuite) { this.recentTestCases.add(testCase.file.path); if (isNewSuite) { Preferences.setAndSave(this.options, 'lastSavedTestSuite', ''); } if (this.options.lastSavedTestSuite.length === 0) { Preferences.setAndSave(this.options, 'lastSavedTestCase', testCase.file.path); } }, reopenLastTestCaseOrSuite: function() { try { if (FileUtils.fileExists(this.options.lastSavedTestSuite)) { this.loadTestSuite(this.options.lastSavedTestSuite); return true; } else if (FileUtils.fileExists(this.options.lastSavedTestCase)) { this.loadTestCaseWithNewSuite(this.options.lastSavedTestCase); return true; } } catch (e) { //error occurred alert("Error reopening test suite / case " + e); } return false; }, setTestCase: function(testCase) { if (this.testCase) { if (testCase == this.testCase) return; this.notify("testCaseUnloaded", this.testCase); } this.testCase = testCase; if (testCase.baseURL) { this.setBaseURL(testCase.baseURL); } else { testCase.setBaseURL(this.baseURL); } this.notify("testCaseChanged", this.testCase); }, getTestCase: function() { return this.testCase; }, newTestCase: function() { var testCase = new TestCase(this.testSuite.generateNewTestCaseTitle()); this.testSuite.addTestCaseFromContent(testCase); this.setTestCase(testCase); }, /** * Adds a testcase to the current suite */ addTestCase: function(path) { if (path) { var testCase = this._loadTestCase(FileUtils.getFile(path)); if (testCase) { this.testSuite.addTestCaseFromContent(testCase); this.setTestCase(testCase); } }else { //Samit: Enh: Allow multiple test cases to be added in one operation var nsIFilePicker = Components.interfaces.nsIFilePicker; var fp = Components.classes["@mozilla.org/filepicker;1"].createInstance(nsIFilePicker); fp.init(window, "Select one or more test cases to add", nsIFilePicker.modeOpenMultiple); fp.appendFilters(nsIFilePicker.filterAll); if (fp.show() == nsIFilePicker.returnOK) { var files = fp.files; while (files.hasMoreElements()) { try { testCase = this._loadTestCase(files.getNext().QueryInterface(Components.interfaces.nsILocalFile)); if (testCase) { this.testSuite.addTestCaseFromContent(testCase); this.setTestCase(testCase); } }catch(error) { this.log.error("AddTestCase: "+error); } } } } }, loadTestCaseWithNewSuite: function(path) { var file = null; if (path) { file = FileUtils.getFile(path); } else { //Samit: We are going to need the file to retry it as a test suite file = showFilePicker(window, "Select a File", Components.interfaces.nsIFilePicker.modeOpen, Format.TEST_CASE_DIRECTORY_PREF, function(fp) { return fp.file; }); } if (file) { try { var testCase = this._loadTestCase(file, null, true); if (testCase) { this.setTestCaseWithNewSuite(testCase); } } catch(errorCase) { //Samit: Enh: Try to handle the common error of trying to open a test suite try { this.loadTestSuite(file.path, true); } catch(e) { //Since this failed, show them the original testcase load error alert("error loading test case: " + errorCase); } } } }, setTestCaseWithNewSuite: function(testCase) { var testSuite = new TestSuite(); testSuite.addTestCaseFromContent(testCase); this.setTestSuite(testSuite); this.setTestCase(testCase); this.addRecentTestCase(testCase, true); }, // show specified TestSuite.TestCase object. showTestCaseFromSuite: function(testCase) { if (testCase.content) { this.setTestCase(testCase.content); } else { try { var content = this._loadTestCase(testCase.getFile(), function(test) { test.title = testCase.getTitle(); // load title from suite testCase.content = test; }, true); if (content) { this.setTestCase(content); } } catch(error) { if (error.name && error.name == "NS_ERROR_FILE_NOT_FOUND") { alert("The test case does not exist. You should probably remove it from the suite. The path specified is " + testCase.getFile().path ); }else { alert("error loading test case: " + error); } } } }, _loadTestCase: function(file, testCaseHandler, noErrorAlert) { this.log.debug("loadTestCase"); try { var testCase = null; if (file) { testCase = this.getCurrentFormat().loadFile(file, false); } else { testCase = this.getCurrentFormat().load(); } if (testCase != null) { if (testCaseHandler) testCaseHandler(testCase); // this.setTestCase(testCase); // this.addRecentTestCase(testCase); return testCase; } return false; } catch (error) { if (noErrorAlert) { //Samit: Enh: allow error messages to be supressed, so caller can make intelligent ux decisions throw error; } alert("error loading test case: " + error); return false; } }, loadTestSuite: function(path, noErrorAlert) { this.log.debug("loadTestSuite"); try { var testSuite = null; if (path) { testSuite = TestSuite.loadFile(FileUtils.getFile(path)); } else { testSuite = TestSuite.load(); } if (testSuite) { this.setTestSuite(testSuite); this.addRecentTestSuite(testSuite); //Samit: Fix: Switch to the first testcase in the newly loaded suite if (testSuite.tests.length > 0) { var testCase = testSuite.tests[0]; if (testCase) this.showTestCaseFromSuite(testCase); } } } catch (error) { if (noErrorAlert) { //Samit: Enh: allow error messages to be supressed, so caller can make intelligent ux decisions throw error; } alert("error loading test suite: " + error); } }, saveTestSuite: function(suppressTestCasePrompt) { //Samit: Enh: Added suppressTestCasePrompt to allow saving test suite and test cases without a yes/no prompt for each test case return this._saveTestSuiteAs(function(testSuite) { return testSuite.save(false); }, suppressTestCasePrompt); }, saveNewTestSuite: function(suppressTestCasePrompt) { //Samit: Enh: Added suppressTestCasePrompt to allow saving test suite and test cases without a yes/no prompt for each test case return this._saveTestSuiteAs(function(testSuite) { return testSuite.save(true); }, suppressTestCasePrompt); }, _saveTestSuiteAs: function(handler, suppressTestCasePrompt) { this.log.debug("saveTestSuite"); var cancelled = false; this.getTestSuite().tests.forEach(function(test) { if (cancelled) return; if (test.content && (test.content.modified || !test.filename)) { //Samit: Enh: Added suppressTestCasePrompt to allow saving test suite and test cases without a yes/no prompt for each test case if (suppressTestCasePrompt || confirm("The test case " + test.getTitle() + " is modified. Do you want to save this test case?")) { if (!this.getCurrentFormat().save(test.content)) { cancelled = true; } } else { cancelled = true; } } }, this); if (!cancelled) { if (handler(this.getTestSuite())) { this.addRecentTestSuite(this.getTestSuite()); return true; } } return false; }, saveTestCase: function() { var result = this.getCurrentFormat().save(this.getTestCase()); if (result) { this.addRecentTestCase(this.getTestCase()); } return result; }, saveNewTestCase: function() { var result = this.getCurrentFormat().saveAsNew(this.getTestCase()); if (result) { this.addRecentTestCase(this.getTestCase()); } } }; Application.prototype.log = Application.log = new Log("Application"); observable(Application);
36.035461
155
0.585515
3d5a1d85f90d91bab705348c55341e423b2969f2
5,463
js
JavaScript
src/components/rangeUsePlanPage/pdf/content/common.js
jonotron/range-web
4e52bc47ab10366c501fac3f8872221dd4f007af
[ "Apache-2.0" ]
null
null
null
src/components/rangeUsePlanPage/pdf/content/common.js
jonotron/range-web
4e52bc47ab10366c501fac3f8872221dd4f007af
[ "Apache-2.0" ]
null
null
null
src/components/rangeUsePlanPage/pdf/content/common.js
jonotron/range-web
4e52bc47ab10366c501fac3f8872221dd4f007af
[ "Apache-2.0" ]
1
2019-10-02T21:13:37.000Z
2019-10-02T21:13:37.000Z
import { handleNullValue, formatDateFromServer, getPrimaryClientFullName } from '../helper' export const checkYPositionAndAddPage = (doc, currY) => { const { contentEndY, afterHeaderY } = doc.config if (currY >= contentEndY) { doc.addPage() return afterHeaderY } return currY } export const writeText = ({ doc, text: t, x, y, fontSize, fontStyle = 'normal', fontColor, hAlign = null, vAlign = null, cusContentWidth = null }) => { const { blackColor, normalFontSize, contentWidth } = doc.config let currY = y; doc .setFontSize(fontSize || normalFontSize) .setFontStyle(fontStyle) .setTextColor(fontColor || blackColor) const width = cusContentWidth || contentWidth const text = t ? `${t}` : handleNullValue(t) const splitTextArray = doc.splitTextToSize(text, width) splitTextArray.map(textChunk => { // remove the first empty space if (textChunk[0] === ' ') { doc.textEx( textChunk.substring(1, textChunk.length), x, currY, hAlign, vAlign ) } else { doc.textEx(textChunk, x, currY, hAlign, vAlign) } currY += 5 return null }) return currY - 5 } export const writeFieldText = ( doc, title, content, x, y, cusContentWidth = null ) => { const { fieldTitleFontSize, grayColor } = doc.config let currY = writeText({ doc, text: title, x, y, fontSize: fieldTitleFontSize }) currY = writeText({ doc, text: content, x, y: currY + 5, fontColor: grayColor, cusContentWidth }) return currY } export const writeLogoImage = (doc, logoImage) => { const { startX, startY } = doc.config const di = 10 doc.addImage(logoImage, 'PNG', startX - 3.5, startY - 3, 600 / di, 214 / di) } const writeHeader = (doc, plan, logoImage) => { const { startY, contentEndX, blackColor, grayColor } = doc.config const { forestFileId, agreementStartDate: asd, agreementEndDate: aed, clients } = plan.agreement || {} if (logoImage) { writeLogoImage(doc, logoImage) } doc .setFontSize(15) .setFontStyle('bold') .setTextColor(blackColor) doc.textEx('Range Use Plan', contentEndX - 0.5, startY, 'right') doc .setFontSize(10) .setFontStyle('normal') .setTextColor(grayColor) doc.textEx( `${forestFileId} | ${getPrimaryClientFullName(clients)}`, contentEndX - 1, startY + 7, 'right' ) doc.textEx( `${formatDateFromServer(asd)} - ${formatDateFromServer(aed)}`, contentEndX - 0.5, startY + 12, 'right' ) } const writeFooter = (doc, currPage, totalPages) => { const { contentEndX, grayColor, normalFontSize, pageHeight, startX } = doc.config doc .setFontSize(normalFontSize) .setFontStyle('normal') .setTextColor(grayColor) const currDate = formatDateFromServer(new Date()) const footerY = pageHeight - 1 doc.textEx( `Generated ${currDate} by the MyRangeBC web application.`, startX, footerY ) doc.textEx(`Page ${currPage} of ${totalPages}`, contentEndX, footerY, 'right') // horizontal line on the top of the footer doc.setLineWidth(0.2).setDrawColor('#cccccc') doc.line(startX, footerY - 1.5, contentEndX, footerY - 1.5) } export const writeHeadersAndFooters = (doc, plan, logoImage) => { const totalPages = doc.internal.getNumberOfPages() for (let i = 1; i <= totalPages; i += 1) { doc.setPage(i) if (i > 1) { // for the front page writeHeader(doc, plan, logoImage) } writeFooter(doc, i, totalPages) } } export const drawHorizontalLine = (doc, y, thickness) => { const { startX, contentEndX, primaryColor } = doc.config const currY = checkYPositionAndAddPage(doc, y) doc.setLineWidth(thickness).setDrawColor(primaryColor) doc.line(startX, currY, contentEndX, currY) // horizontal line return currY + thickness } export const drawVerticalLine = ( doc, x, y1, y2, firstPage, lastPage, thickness, cusColor = null ) => { const { accentColor, contentEndY, afterHeaderY } = doc.config const color = cusColor || accentColor const pageAdded = firstPage !== lastPage if (pageAdded) { for (let page = firstPage; page <= lastPage; page += 1) { if (page === firstPage) { if (y1 < contentEndY) { // go back to the first page and draw doc.setPage(page) doc.setLineWidth(thickness).setDrawColor(color) doc.line(x, y1, x, contentEndY + 2) } } else if (page === lastPage) { // go to the last page and finish drawing doc.setPage(page) doc.setLineWidth(thickness).setDrawColor(color) doc.line(x, afterHeaderY, x, y2 + 4) } else { // draw the line from top to the bottom in the pages // between the first and last page doc.setPage(page) doc.setLineWidth(thickness).setDrawColor(color) doc.line(x, afterHeaderY, x, contentEndY + 2) } } } else { doc.setLineWidth(thickness).setDrawColor(color) doc.line(x, y1, x, y2 + 4) } } export const writeTitle = (doc, title) => { const { startX, afterHeaderY, blackColor } = doc.config let currY = writeText({ doc, text: title, x: startX, y: afterHeaderY, fontSize: 16, fontColor: blackColor, fontStyle: 'bold' }) currY += 8 currY = drawHorizontalLine(doc, currY, 0.5) return currY }
22.297959
80
0.63024
3d5a3f4bf4925fab450dd001aef387142c81c2d8
315
js
JavaScript
src/index.js
leonidtrubchik/brackets
d21b9a682d3c496a199742e2b49786e649d00fd4
[ "MIT" ]
null
null
null
src/index.js
leonidtrubchik/brackets
d21b9a682d3c496a199742e2b49786e649d00fd4
[ "MIT" ]
null
null
null
src/index.js
leonidtrubchik/brackets
d21b9a682d3c496a199742e2b49786e649d00fd4
[ "MIT" ]
null
null
null
module.exports = function check(str, bracketsConfig) { let arr = []; bracketsConfig.forEach( value => arr.push(value.join('')) ); for (let i = 0; i < arr.length; i++) { if (str.includes(arr[i]) ){ str = str.replace(arr[i], ''); i = -1; } } return str.length === 0 ? true : false; }
22.5
62
0.542857
3d5b569f09a4a6780f8eba7f206f0f5d7fb3bc22
853
js
JavaScript
Build/BuildEssentials/JSUnit/phantom.js
lux-net/lux-server
fd7331854ce487006d236d3857729f5061b6ce73
[ "Apache-2.0" ]
2
2018-01-28T18:10:33.000Z
2018-01-28T21:07:44.000Z
Build/BuildEssentials/JSUnit/phantom.js
lux-net/lux-server
fd7331854ce487006d236d3857729f5061b6ce73
[ "Apache-2.0" ]
null
null
null
Build/BuildEssentials/JSUnit/phantom.js
lux-net/lux-server
fd7331854ce487006d236d3857729f5061b6ce73
[ "Apache-2.0" ]
null
null
null
var system = require('system'), captureUrl = 'http://localhost:1111/capture'; if (system.args.length==2) { captureUrl = system.args[1]; } phantom.silent = false; var page = new WebPage(); page.open(captureUrl, function(status) { if(!phantom.silent) { if (status !== 'success') { console.log('Phantomjs failed to connect'); phantom.exit(1); } else { console.log('Successfully connected Phantomjs'); } page.onConsoleMessage = function (msg, line, id) { if (id) { var fileName = id.split('/'); // format the output message with filename, line number and message // weird gotcha: phantom only uses the first console.log argument it gets :( console.log(fileName[fileName.length-1]+', '+ line +': '+ msg); } else { console.log(msg); } }; page.onAlert = function(msg) { console.log(msg); }; } });
24.371429
80
0.640094
3d5b6744606127b683938fa6000e01ee9520791e
2,883
js
JavaScript
src/tooltip/tooltip.js
allenhwkim/mce
3a5bc779398ec45989d01773c127a5d447d40c02
[ "MIT" ]
18
2018-01-08T05:08:07.000Z
2020-06-17T03:47:03.000Z
src/tooltip/tooltip.js
allenhwkim/mce
3a5bc779398ec45989d01773c127a5d447d40c02
[ "MIT" ]
3
2018-08-10T19:03:55.000Z
2018-09-16T04:05:19.000Z
src/tooltip/tooltip.js
allenhwkim/custom-elements
3a5bc779398ec45989d01773c127a5d447d40c02
[ "MIT" ]
3
2018-06-04T12:02:08.000Z
2019-02-09T16:29:22.000Z
// FYI, http://plnkr.co/edit/I9mfBNIKJtALHwKmS0CH?p=preview. ARIA tooltip approach. /** * Tooltips are text labels that appear when the user hovers over, focuses on, or touches an element. * * [Material Design Spec](https://material.io/guidelines/components/tooltips.html) * * ### Example * ``` * <mce-button class="mce-raised"> * <mce-tooltip>This is a tooltip for a button</mce-tooltip> * Mouse * </mce-button> * <mce-button class="mce-raised" style="float: right"> * <mce-tooltip>This is a tooltip for a button</mce-tooltip> * Tooltip * </mce-button> * ``` * * <iframe height='265' scrolling='no' title='ZvvQap' src='//codepen.io/allenhwkim/embed/ZvvQap/?height=265&theme-id=0&default-tab=html,result&embed-version=2' frameborder='no' allowtransparency='true' allowfullscreen='true' style='width: 100%;'>See the Pen <a href='https://codepen.io/allenhwkim/pen/ZvvQap/'>ZvvQap</a> by Allen kim (<a href='https://codepen.io/allenhwkim'>@allenhwkim</a>) on <a href='https://codepen.io'>CodePen</a>. </iframe> * */ export class Tooltip extends HTMLElement { connectedCallback() { this._addEventListeners(); } _addEventListeners() { this.parentElement.addEventListener('mouseenter', event => { this.originalPos = { parent: event.target, nextSibling: this.nextSiblingNode }; this._showTooltip(); }); this.parentElement.addEventListener('mouseleave', _ => { this.classList.remove('mce-visible'); this.originalPos.parent.insertBefore(this, this.originalPos.nextSibling); }); } _showTooltip() { let parentBCR = this.originalPos.parent.getBoundingClientRect(); // relative to viewport let body = document.body; let docEl = document.documentElement; let scrollTop = window.pageYOffset || docEl.scrollTop || body.scrollTop; let scrollLeft = window.pageXOffset || docEl.scrollLeft || body.scrollLeft; let clientTop = docEl.clientTop || body.clientTop || 0; let clientLeft = docEl.clientLeft || body.clientLeft || 0; let docPosTop = Math.round(parentBCR.top + scrollTop - clientTop); let docPosLeft = Math.round(parentBCR.left + scrollLeft - clientLeft); let top = docPosTop + parentBCR.height + 24; this.style.top = top + 'px'; this.style.left = ''; this.style.right = ''; document.body.appendChild(this); setTimeout(_ => { let thisBCR = this.getBoundingClientRect(); // it needs time to calc this properly let left = docPosLeft + (parentBCR.width / 2) - (thisBCR.width / 2); if (left < 8) { this.style.left = '8px'; } else if (left + thisBCR.width > document.body.clientWidth) { this.style.right = '8px'; } else { this.style.left = left + 'px'; } this.classList.add('mce-visible'); }, 100); } } customElements.define('mce-tooltip', Tooltip);
35.158537
436
0.662504
3d5bddc3bcbc9dc574be1e307c98f0a9f732d539
6,930
js
JavaScript
public/admin/vendors/Chart.js/src/scales/scale.logarithmic.js
shayzism/Laravel-VegStore
cc030290041574fa2ad39d55c7a0eed6aee3767f
[ "MIT" ]
18
2017-03-23T23:19:17.000Z
2020-07-01T12:41:04.000Z
public/admin/vendors/Chart.js/src/scales/scale.logarithmic.js
shayzism/Laravel-VegStore
cc030290041574fa2ad39d55c7a0eed6aee3767f
[ "MIT" ]
13
2021-02-02T17:48:37.000Z
2021-09-21T12:26:04.000Z
public/admin/vendors/Chart.js/src/scales/scale.logarithmic.js
shayzism/Laravel-VegStore
cc030290041574fa2ad39d55c7a0eed6aee3767f
[ "MIT" ]
8
2017-03-31T11:35:17.000Z
2020-11-12T15:45:09.000Z
"use strict"; module.exports = function(Chart) { var helpers = Chart.helpers; var defaultConfig = { position: "left", // label settings ticks: { callback: function(value, index, arr) { var remain = value / (Math.pow(10, Math.floor(helpers.log10(value)))); if (remain === 1 || remain === 2 || remain === 5 || index === 0 || index === arr.length - 1) { return value.toExponential(); } else { return ''; } } } }; var LogarithmicScale = Chart.Scale.extend({ determineDataLimits: function() { var me = this; var opts = me.options; var tickOpts = opts.ticks; var chart = me.chart; var data = chart.data; var datasets = data.datasets; var getValueOrDefault = helpers.getValueOrDefault; var isHorizontal = me.isHorizontal(); function IDMatches(meta) { return isHorizontal ? meta.xAxisID === me.id : meta.yAxisID === me.id; } // Calculate Range me.min = null; me.max = null; if (opts.stacked) { var valuesPerType = {}; helpers.each(datasets, function(dataset, datasetIndex) { var meta = chart.getDatasetMeta(datasetIndex); if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) { if (valuesPerType[meta.type] === undefined) { valuesPerType[meta.type] = []; } helpers.each(dataset.data, function(rawValue, index) { var values = valuesPerType[meta.type]; var value = +me.getRightValue(rawValue); if (isNaN(value) || meta.data[index].hidden) { return; } values[index] = values[index] || 0; if (opts.relativePoints) { values[index] = 100; } else { // Don't need to split positive and negative since the log scale can't handle a 0 crossing values[index] += value; } }); } }); helpers.each(valuesPerType, function(valuesForType) { var minVal = helpers.min(valuesForType); var maxVal = helpers.max(valuesForType); me.min = me.min === null ? minVal : Math.min(me.min, minVal); me.max = me.max === null ? maxVal : Math.max(me.max, maxVal); }); } else { helpers.each(datasets, function(dataset, datasetIndex) { var meta = chart.getDatasetMeta(datasetIndex); if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) { helpers.each(dataset.data, function(rawValue, index) { var value = +me.getRightValue(rawValue); if (isNaN(value) || meta.data[index].hidden) { return; } if (me.min === null) { me.min = value; } else if (value < me.min) { me.min = value; } if (me.max === null) { me.max = value; } else if (value > me.max) { me.max = value; } }); } }); } me.min = getValueOrDefault(tickOpts.min, me.min); me.max = getValueOrDefault(tickOpts.max, me.max); if (me.min === me.max) { if (me.min !== 0 && me.min !== null) { me.min = Math.pow(10, Math.floor(helpers.log10(me.min)) - 1); me.max = Math.pow(10, Math.floor(helpers.log10(me.max)) + 1); } else { me.min = 1; me.max = 10; } } }, buildTicks: function() { var me = this; var opts = me.options; var tickOpts = opts.ticks; var getValueOrDefault = helpers.getValueOrDefault; // Reset the ticks array. Later on, we will draw a grid line at these positions // The array simply contains the numerical value of the spots where ticks will be var ticks = me.ticks = []; // Figure out what the max number of ticks we can support it is based on the size of // the axis area. For now, we say that the minimum tick spacing in pixels must be 50 // We also limit the maximum number of ticks to 11 which gives a nice 10 squares on // the graph var tickVal = getValueOrDefault(tickOpts.min, Math.pow(10, Math.floor(helpers.log10(me.min)))); while (tickVal < me.max) { ticks.push(tickVal); var exp = Math.floor(helpers.log10(tickVal)); var significand = Math.floor(tickVal / Math.pow(10, exp)) + 1; if (significand === 10) { significand = 1; ++exp; } tickVal = significand * Math.pow(10, exp); } var lastTick = getValueOrDefault(tickOpts.max, tickVal); ticks.push(lastTick); if (!me.isHorizontal()) { // We are in a vertical orientation. The top value is the highest. So reverse the array ticks.reverse(); } // At this point, we need to update our max and min given the tick values since we have expanded the // range of the scale me.max = helpers.max(ticks); me.min = helpers.min(ticks); if (tickOpts.reverse) { ticks.reverse(); me.start = me.max; me.end = me.min; } else { me.start = me.min; me.end = me.max; } }, convertTicksToLabels: function() { this.tickValues = this.ticks.slice(); Chart.Scale.prototype.convertTicksToLabels.call(this); }, // Get the correct tooltip label getLabelForIndex: function(index, datasetIndex) { return +this.getRightValue(this.chart.data.datasets[datasetIndex].data[index]); }, getPixelForTick: function(index, includeOffset) { return this.getPixelForValue(this.tickValues[index], null, null, includeOffset); }, getPixelForValue: function(value, index, datasetIndex, includeOffset) { var me = this; var innerDimension; var pixel; var start = me.start; var newVal = +me.getRightValue(value); var range = helpers.log10(me.end) - helpers.log10(start); var paddingTop = me.paddingTop; var paddingBottom = me.paddingBottom; var paddingLeft = me.paddingLeft; if (me.isHorizontal()) { if (newVal === 0) { pixel = me.left + paddingLeft; } else { innerDimension = me.width - (paddingLeft + me.paddingRight); pixel = me.left + (innerDimension / range * (helpers.log10(newVal) - helpers.log10(start))); pixel += paddingLeft; } } else { // Bottom - top since pixels increase downard on a screen if (newVal === 0) { pixel = me.top + paddingTop; } else { innerDimension = me.height - (paddingTop + paddingBottom); pixel = (me.bottom - paddingBottom) - (innerDimension / range * (helpers.log10(newVal) - helpers.log10(start))); } } return pixel; }, getValueForPixel: function(pixel) { var me = this; var offset; var range = helpers.log10(me.end) - helpers.log10(me.start); var value; var innerDimension; if (me.isHorizontal()) { innerDimension = me.width - (me.paddingLeft + me.paddingRight); value = me.start * Math.pow(10, (pixel - me.left - me.paddingLeft) * range / innerDimension); } else { innerDimension = me.height - (me.paddingTop + me.paddingBottom); value = Math.pow(10, (me.bottom - me.paddingBottom - pixel) * range / innerDimension) / me.start; } return value; } }); Chart.scaleService.registerScaleType("logarithmic", LogarithmicScale, defaultConfig); };
29.364407
117
0.62482
3d5cbfb3ce2a5bebe947b702c2346e79c2e9f542
1,662
js
JavaScript
app/Resources/webpack/js/index.js
EffingFancy/AdventureLookup
7edf374166109f8a720e7aa3468fcbf9ecf975e1
[ "MIT" ]
null
null
null
app/Resources/webpack/js/index.js
EffingFancy/AdventureLookup
7edf374166109f8a720e7aa3468fcbf9ecf975e1
[ "MIT" ]
null
null
null
app/Resources/webpack/js/index.js
EffingFancy/AdventureLookup
7edf374166109f8a720e7aa3468fcbf9ecf975e1
[ "MIT" ]
null
null
null
import 'jquery/src/jquery' import 'bootstrap/dist/js/bootstrap.js'; import 'selectize/dist/js/standalone/selectize' import autosize from 'autosize'; import toastr from 'toastr/toastr'; import '../sass/style.scss'; import 'cookieconsent/build/cookieconsent.min'; import './adventures'; import './adventure'; import './reviews'; import './adventure_list'; import './paginated_list_group'; window.cookieconsent.initialise({ palette: { popup: { background: "#fff" }, button: { background: "#f56e4e", text: "#fff", }, }, revokable: false, location: false, theme: "edgeless", position: "bottom-left", }); toastr.options = { "closeButton": false, "debug": false, "newestOnTop": false, "progressBar": true, "positionClass": "toast-top-right", "preventDuplicates": false, "onclick": null, "showDuration": "300", "hideDuration": "1000", "timeOut": "5000", "extendedTimeOut": "1000", "showEasing": "swing", "hideEasing": "linear", "showMethod": "fadeIn", "hideMethod": "fadeOut" }; autosize(document.querySelectorAll('textarea.autosize')); // Hack to reload CSS using HMR // https://github.com/symfony/webpack-encore/pull/8#issuecomment-312599836 // Needed until https://github.com/symfony/webpack-encore/issues/3 is fixed import hotEmitter from 'webpack/hot/emitter'; if (module.hot) { hotEmitter.on('webpackHotUpdate', () => { document.querySelectorAll('link[href][rel=stylesheet]').forEach((link) => { link.href = link.href.replace(/(\?\d+)?$/, `?${Date.now()}`); // eslint-disable-line }); }); }
27.7
96
0.638387
3d5da4700c61df9354cd873d3b804689c5b3ffb1
363
js
JavaScript
jstests/core/bad_index_plugin.js
SunguckLee/real-mongodb
fef0e44fafc6d3709a84101327e7d2f54dd18d88
[ "Apache-2.0" ]
4
2018-02-06T01:53:12.000Z
2018-02-20T01:47:36.000Z
jstests/core/bad_index_plugin.js
SunguckLee/real-mongodb
fef0e44fafc6d3709a84101327e7d2f54dd18d88
[ "Apache-2.0" ]
null
null
null
jstests/core/bad_index_plugin.js
SunguckLee/real-mongodb
fef0e44fafc6d3709a84101327e7d2f54dd18d88
[ "Apache-2.0" ]
3
2018-02-06T01:53:18.000Z
2021-07-28T09:48:15.000Z
// SERVER-5826 ensure you can't build an index with a non-existent plugin t = db.bad_index_plugin; assert.commandWorked(t.ensureIndex({good: 1})); assert.eq(t.getIndexes().length, 2); // good + _id var err = t.ensureIndex({bad: 'bad'}); assert.commandFailed(err); assert(err.code >= 0); assert.eq(t.getIndexes().length, 2); // good + _id (no bad)
30.25
74
0.669421
3d5daee43751fbf7e55196f582e45b2eb14f58d0
9,277
js
JavaScript
jQuery.weightMask.js
dsenko/weight-mask
e6ffb04b9bbb4912d794c923168fae32f55e0c3e
[ "MIT" ]
null
null
null
jQuery.weightMask.js
dsenko/weight-mask
e6ffb04b9bbb4912d794c923168fae32f55e0c3e
[ "MIT" ]
null
null
null
jQuery.weightMask.js
dsenko/weight-mask
e6ffb04b9bbb4912d794c923168fae32f55e0c3e
[ "MIT" ]
2
2021-05-07T14:54:23.000Z
2021-07-21T03:03:28.000Z
/*var console = { log: function (msg) { $('#log').prepend('<p>' + JSON.stringify(msg) + '</p>'); } } */ jQuery.fn.extend({ maskWeight: function (userOptions) { window._maskData = { selector: $(this), arr: [/*'0', '0', '0', '0', '0', '0'*/], insertCount: 0, numberPressed: false, options: {}, defOptions: { integerDigits: 3, decimalDigits: 3, decimalMark: '.', initVal: '',//'000,000', roundingZeros: true, digitsCount: 6, callBack: null, doFocus: true, }, initializeOptions: function (userOptions) { this.options = $.extend(true, this.defOptions); this.arr = []; this.insertCount = 0; this.numberPressed = false; if (userOptions) { for (var prop in userOptions) { if (userOptions[prop] !== undefined && userOptions[prop] !== null) { this.options[prop] = userOptions[prop]; } } } if (this.options.decimalDigits == 0) { this.options.decimalMark = ''; } var initValFromUser = false; if (this.options.initVal == '') { if (this.options.roundingZeros) { this.options.initVal += '0'; } else { for (var i = 0; i < this.options.integerDigits; i++) { this.options.initVal += '0'; } } this.options.initVal += this.options.decimalMark; for (var i = 0; i < this.options.decimalDigits; i++) { this.options.initVal += '0'; } } else { initValFromUser = true; } this.options.digitsCount = this.options.integerDigits + this.options.decimalDigits; this.arr = []; for (var i = 0; i < this.options.digitsCount; i++) { this.arr.push('0'); } if (initValFromUser && parseInt(this.options.initVal) > 0) { this.createInitialValueArr(); } }, createInitialValueArr: function () { this.options.initVal = this.options.decimalDigits == 0 ? parseInt(this.options.initVal) : parseFloat(this.options.initVal.toString().replace(',', '.')).toFixed(this.options.decimalDigits).replace('.', this.options.decimalMark); var splitted = this.options.initVal.toString().replace('.', '').replace(',', '').split(''); for (var i = 0; i < splitted.length; i++) { this.insert(splitted[i]); } }, insert: function (num) { var insert = this.mask(num); this.selector.val(insert); this.setCartetOnEnd(); }, mask: function (num) { if (num == 'backspace') { if (this.insertCount > 0) { this.arr.pop(); this.arr.unshift('0'); this.insertCount--; } } else { if (this.insertCount < this.options.digitsCount) { this.arr.shift(); this.arr.push(num.toString()); this.insertCount++; } } var value = ''; for (var i = 0; i < this.arr.length; i++) { value += this.arr[i]; } value = this.reduce(value); return value; }, reduce: function (value) { if (this.options.decimalDigits == 0) { if (this.options.roundingZeros) { return parseInt(value); } else { return value; } } else { if (this.options.roundingZeros) { return parseInt(value.substring(0, this.options.integerDigits)) + this.options.decimalMark + value.substring(this.options.integerDigits, this.options.digitsCount); } else { return value.substring(0, this.options.integerDigits) + this.options.decimalMark + value.substring(this.options.integerDigits, this.options.digitsCount); } } }, getNumber: function (e) { return String.fromCharCode(e.keyCode || e.which); }, setCartetOnEnd: function () { var self = this; setTimeout(function () { var len = self.selector.val().length; if(self.options.doFocus){ self.selector[0].focus(); } self.selector[0].setSelectionRange(len, len); //self.selector.selectionStart = self.selector.selectionEnd = 10000; }, 1); }, isNumberOrBackspace: function (num) { if (num == 'backspace') { return true; } if (parseInt(num) || parseInt(num) == 0) { return true; } return false; }, init: function () { var self = this; this.selector.val(this.options.initVal); this.selector.on('click', function (e) { self.setCartetOnEnd(); }); var ua = navigator.userAgent.toLowerCase(); var isAndroid = ua.indexOf("android") > -1; if (isAndroid) { window._maskDataLastVal = this.selector.val(); this.selector[0].removeEventListener('input', window._maskDataAndroidMaskHandler, true); setTimeout(function () { window._maskDataAndroidMaskHandler = function (e) { e.preventDefault(); e.stopPropagation(); if (self.selector.val().length < window._maskDataLastVal.length) { self.insert('backspace'); } else { var num = self.selector.val().charAt(self.selector.val().length - 1); if(parseFloat(self.selector.val().replace(',','.')) == 0 && parseInt(num) == 0){ self.insert('backspace'); }else{ self.insert(num); } } window._maskDataLastVal = self.selector.val(); if(self.options.callBack){ self.options.callBack(); } return false; }; self.selector[0].addEventListener('input', window._maskDataAndroidMaskHandler, true); }, 0); } else { this.selector.on('keydown', function (e) { var key = e.keyCode || e.which; if (key == 8 || key == 46) { e.preventDefault(); e.stopPropagation(); self.insert('backspace'); } if(self.options.callBack){ self.options.callBack(); } }); this.selector.on('keypress', function (e) { var key = e.keyCode || e.which; e.preventDefault(); e.stopPropagation(); var num = self.getNumber(e); if (self.isNumberOrBackspace(num)) { if(parseFloat(self.selector.val().replace(',','.')) == 0 && parseInt(num) == 0){ self.insert('backspace'); }else{ self.insert(num); } } if(self.options.callBack){ self.options.callBack(); } }); } } }; window._maskData.initializeOptions(userOptions); window._maskData.init(); }, removeMask: function () { if (window._maskData) { $(this).unbind(); window._maskData = null; } }, });
28.900312
243
0.397003
3d5e2b4a21d9fa2a5ce45ee5d3e1f310737157ca
173
js
JavaScript
src/cells/Button/constants.js
JuanPabloOS/test-package
2569922a824de420312d725e8685b80f15dad4d8
[ "MIT" ]
1
2021-03-04T01:55:29.000Z
2021-03-04T01:55:29.000Z
src/cells/Button/constants.js
JuanPabloOS/test-package
2569922a824de420312d725e8685b80f15dad4d8
[ "MIT" ]
null
null
null
src/cells/Button/constants.js
JuanPabloOS/test-package
2569922a824de420312d725e8685b80f15dad4d8
[ "MIT" ]
null
null
null
export const SIZE = { small: 'small', default: 'default', large: 'large', }; export const FONT_SIZE = { small: '0.694rem', default: '0.833rem', large: '1rem', };
17.3
26
0.601156
3d5e5346951fbe44fba1cb43ac2783668f7b12c7
3,325
js
JavaScript
node_modules/@amcharts/amcharts4/.internal/core/elements/Triangle.js
krishnawork/Crm
9d740ff77a7a96e71c4e7de3790549a1f84b05cd
[ "MTLL" ]
null
null
null
node_modules/@amcharts/amcharts4/.internal/core/elements/Triangle.js
krishnawork/Crm
9d740ff77a7a96e71c4e7de3790549a1f84b05cd
[ "MTLL" ]
null
null
null
node_modules/@amcharts/amcharts4/.internal/core/elements/Triangle.js
krishnawork/Crm
9d740ff77a7a96e71c4e7de3790549a1f84b05cd
[ "MTLL" ]
null
null
null
/** * Functionality for drawing triangles. */ import { __extends } from "tslib"; /** * ============================================================================ * IMPORTS * ============================================================================ * @hidden */ import { Sprite } from "../Sprite"; import { registry } from "../Registry"; import * as $path from "../rendering/Path"; /** * ============================================================================ * MAIN CLASS * ============================================================================ * @hidden */ /** * Used to draw a triangle. * * @see {@link ITriangleEvents} for a list of available events * @see {@link ITriangleAdapters} for a list of available Adapters */ var Triangle = /** @class */ (function (_super) { __extends(Triangle, _super); /** * Constructor */ function Triangle() { var _this = _super.call(this) || this; _this.className = "Triangle"; _this.element = _this.paper.add("path"); _this.direction = "top"; _this.applyTheme(); return _this; } /** * Draws the element. * * @ignore Exclude from docs */ Triangle.prototype.draw = function () { _super.prototype.draw.call(this); var w = this.pixelWidth; var h = this.pixelHeight; var path; switch (this.direction) { case "right": path = $path.moveTo({ x: 0, y: 0 }) + $path.lineTo({ x: w, y: h / 2 }) + $path.lineTo({ x: 0, y: h }) + $path.closePath(); break; case "left": path = $path.moveTo({ x: w, y: 0 }) + $path.lineTo({ x: 0, y: h / 2 }) + $path.lineTo({ x: w, y: h }) + $path.closePath(); break; case "bottom": path = $path.moveTo({ x: 0, y: 0 }) + $path.lineTo({ x: w, y: 0 }) + $path.lineTo({ x: w / 2, y: h }) + $path.closePath(); break; case "top": path = $path.moveTo({ x: w / 2, y: 0 }) + $path.lineTo({ x: w, y: h }) + $path.lineTo({ x: 0, y: h }) + $path.closePath(); break; } this.path = path; }; Object.defineProperty(Triangle.prototype, "direction", { /** * Returns direction of a triangle * * @return value */ get: function () { return this.getPropertyValue("direction"); }, /** * Sets direction of a triangle * * @param value */ set: function (value) { this.setPropertyValue("direction", value, true); }, enumerable: true, configurable: true }); return Triangle; }(Sprite)); export { Triangle }; /** * Register class in system, so that it can be instantiated using its name from * anywhere. * * @ignore */ registry.registeredClasses["Triangle"] = Triangle; //# sourceMappingURL=Triangle.js.map
31.074766
80
0.411128
3d5f57bb47c5d1cbc185ab61450df801538f25f6
699
js
JavaScript
src/actions/currentGame/currentGameConstants.js
vasconita/tic-tac-toe
d2339d8b7b9ba0c69cea38a371929413839149ce
[ "MIT" ]
null
null
null
src/actions/currentGame/currentGameConstants.js
vasconita/tic-tac-toe
d2339d8b7b9ba0c69cea38a371929413839149ce
[ "MIT" ]
2
2021-03-10T08:54:36.000Z
2022-02-27T00:12:27.000Z
src/actions/currentGame/currentGameConstants.js
vasconita/tic-tac-toe
d2339d8b7b9ba0c69cea38a371929413839149ce
[ "MIT" ]
null
null
null
export const SCORE = 'score'; export const GAME_IN_COURSE = 'gameInCourse'; export const ID = 'id'; export const GRID = 'grid'; export const SELECTED_BY_USER = 'selectedByUser'; export const SELECTED_BY_MACHINE = 'selectedByMachine'; export const USER_CAN_SELECT = 'userCanSelect'; export const GRID_ENTRIES = 9; // Standard Tic Tac Toe. export const USER = 'user'; export const MACHINE = 'machine'; export const WINNER = 'winner'; export const GRID_KEYS = Array.from({length: GRID_ENTRIES}, (v, k) => k); export const WIN_COMBINATIONS = [ [0, 1, 2], [3, 4, 5], [6, 7, 8], // Horizontals [0, 3, 6], [1, 4, 7], [2, 5, 8], // Verticals [0, 4, 8], [2, 4, 6], // Diagonals ];
34.95
73
0.653791
3d5f6f82c3691b27fb66eb4debcb76f83aef0c72
18,455
js
JavaScript
public/assets/js/popper.min.js
haseebhassan006/bmapi
3489468e27d303eb9c48e71710494a137665feb3
[ "MIT" ]
null
null
null
public/assets/js/popper.min.js
haseebhassan006/bmapi
3489468e27d303eb9c48e71710494a137665feb3
[ "MIT" ]
null
null
null
public/assets/js/popper.min.js
haseebhassan006/bmapi
3489468e27d303eb9c48e71710494a137665feb3
[ "MIT" ]
null
null
null
/** * @popperjs/core v2.6.0 - MIT License */ "use strict";!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e=e||self).Popper={})}(this,(function(e){function t(e){return{width:(e=e.getBoundingClientRect()).width,height:e.height,top:e.top,right:e.right,bottom:e.bottom,left:e.left,x:e.left,y:e.top}}function n(e){return"[object Window]"!==e.toString()?(e=e.ownerDocument)&&e.defaultView||window:e}function r(e){return{scrollLeft:(e=n(e)).pageXOffset,scrollTop:e.pageYOffset}}function o(e){return e instanceof n(e).Element||e instanceof Element}function i(e){return e instanceof n(e).HTMLElement||e instanceof HTMLElement}function a(e){return e?(e.nodeName||"").toLowerCase():null}function s(e){return((o(e)?e.ownerDocument:e.document)||window.document).documentElement}function f(e){return t(s(e)).left+r(e).scrollLeft}function c(e){return n(e).getComputedStyle(e)}function p(e){return e=c(e),/auto|scroll|overlay|hidden/.test(e.overflow+e.overflowY+e.overflowX)}function l(e,o,c){void 0===c&&(c=!1);var l=s(o);e=t(e);var u=i(o),d={scrollLeft:0,scrollTop:0},m={x:0,y:0};return(u||!u&&!c)&&(("body"!==a(o)||p(l))&&(d=o!==n(o)&&i(o)?{scrollLeft:o.scrollLeft,scrollTop:o.scrollTop}:r(o)),i(o)?((m=t(o)).x+=o.clientLeft,m.y+=o.clientTop):l&&(m.x=f(l))),{x:e.left+d.scrollLeft-m.x,y:e.top+d.scrollTop-m.y,width:e.width,height:e.height}}function u(e){return{x:e.offsetLeft,y:e.offsetTop,width:e.offsetWidth,height:e.offsetHeight}}function d(e){return"html"===a(e)?e:e.assignedSlot||e.parentNode||e.host||s(e)}function m(e,t){void 0===t&&(t=[]);var r=function e(t){return 0<=["html","body","#document"].indexOf(a(t))?t.ownerDocument.body:i(t)&&p(t)?t:e(d(t))}(e);e="body"===a(r);var o=n(r);return r=e?[o].concat(o.visualViewport||[],p(r)?r:[]):r,t=t.concat(r),e?t:t.concat(m(d(r)))}function h(e){if(!i(e)||"fixed"===c(e).position)return null;if(e=e.offsetParent){var t=s(e);if("body"===a(e)&&"static"===c(e).position&&"static"!==c(t).position)return t}return e}function g(e){for(var t=n(e),r=h(e);r&&0<=["table","td","th"].indexOf(a(r))&&"static"===c(r).position;)r=h(r);if(r&&"body"===a(r)&&"static"===c(r).position)return t;if(!r)e:{for(e=d(e);i(e)&&0>["html","body"].indexOf(a(e));){if("none"!==(r=c(e)).transform||"none"!==r.perspective||r.willChange&&"auto"!==r.willChange){r=e;break e}e=e.parentNode}r=null}return r||t}function v(e){var t=new Map,n=new Set,r=[];return e.forEach((function(e){t.set(e.name,e)})),e.forEach((function(e){n.has(e.name)||function e(o){n.add(o.name),[].concat(o.requires||[],o.requiresIfExists||[]).forEach((function(r){n.has(r)||(r=t.get(r))&&e(r)})),r.push(o)}(e)})),r}function b(e){var t;return function(){return t||(t=new Promise((function(n){Promise.resolve().then((function(){t=void 0,n(e())}))}))),t}}function y(e){return e.split("-")[0]}function O(e,t){var r,o=t.getRootNode&&t.getRootNode();if(e.contains(t))return!0;if((r=o)&&(r=o instanceof(r=n(o).ShadowRoot)||o instanceof ShadowRoot),r)do{if(t&&e.isSameNode(t))return!0;t=t.parentNode||t.host}while(t);return!1}function w(e){return Object.assign(Object.assign({},e),{},{left:e.x,top:e.y,right:e.x+e.width,bottom:e.y+e.height})}function x(e,o){if("viewport"===o){o=n(e);var a=s(e);o=o.visualViewport;var p=a.clientWidth;a=a.clientHeight;var l=0,u=0;o&&(p=o.width,a=o.height,/^((?!chrome|android).)*safari/i.test(navigator.userAgent)||(l=o.offsetLeft,u=o.offsetTop)),e=w(e={width:p,height:a,x:l+f(e),y:u})}else i(o)?((e=t(o)).top+=o.clientTop,e.left+=o.clientLeft,e.bottom=e.top+o.clientHeight,e.right=e.left+o.clientWidth,e.width=o.clientWidth,e.height=o.clientHeight,e.x=e.left,e.y=e.top):(u=s(e),e=s(u),l=r(u),o=u.ownerDocument.body,p=Math.max(e.scrollWidth,e.clientWidth,o?o.scrollWidth:0,o?o.clientWidth:0),a=Math.max(e.scrollHeight,e.clientHeight,o?o.scrollHeight:0,o?o.clientHeight:0),u=-l.scrollLeft+f(u),l=-l.scrollTop,"rtl"===c(o||e).direction&&(u+=Math.max(e.clientWidth,o?o.clientWidth:0)-p),e=w({width:p,height:a,x:u,y:l}));return e}function j(e,t,n){return t="clippingParents"===t?function(e){var t=m(d(e)),n=0<=["absolute","fixed"].indexOf(c(e).position)&&i(e)?g(e):e;return o(n)?t.filter((function(e){return o(e)&&O(e,n)&&"body"!==a(e)})):[]}(e):[].concat(t),(n=(n=[].concat(t,[n])).reduce((function(t,n){return n=x(e,n),t.top=Math.max(n.top,t.top),t.right=Math.min(n.right,t.right),t.bottom=Math.min(n.bottom,t.bottom),t.left=Math.max(n.left,t.left),t}),x(e,n[0]))).width=n.right-n.left,n.height=n.bottom-n.top,n.x=n.left,n.y=n.top,n}function M(e){return 0<=["top","bottom"].indexOf(e)?"x":"y"}function E(e){var t=e.reference,n=e.element,r=(e=e.placement)?y(e):null;e=e?e.split("-")[1]:null;var o=t.x+t.width/2-n.width/2,i=t.y+t.height/2-n.height/2;switch(r){case"top":o={x:o,y:t.y-n.height};break;case"bottom":o={x:o,y:t.y+t.height};break;case"right":o={x:t.x+t.width,y:i};break;case"left":o={x:t.x-n.width,y:i};break;default:o={x:t.x,y:t.y}}if(null!=(r=r?M(r):null))switch(i="y"===r?"height":"width",e){case"start":o[r]-=t[i]/2-n[i]/2;break;case"end":o[r]+=t[i]/2-n[i]/2}return o}function D(e){return Object.assign(Object.assign({},{top:0,right:0,bottom:0,left:0}),e)}function P(e,t){return t.reduce((function(t,n){return t[n]=e,t}),{})}function L(e,n){void 0===n&&(n={});var r=n;n=void 0===(n=r.placement)?e.placement:n;var i=r.boundary,a=void 0===i?"clippingParents":i,f=void 0===(i=r.rootBoundary)?"viewport":i;i=void 0===(i=r.elementContext)?"popper":i;var c=r.altBoundary,p=void 0!==c&&c;r=D("number"!=typeof(r=void 0===(r=r.padding)?0:r)?r:P(r,T));var l=e.elements.reference;c=e.rects.popper,a=j(o(p=e.elements[p?"popper"===i?"reference":"popper":i])?p:p.contextElement||s(e.elements.popper),a,f),p=E({reference:f=t(l),element:c,strategy:"absolute",placement:n}),c=w(Object.assign(Object.assign({},c),p)),f="popper"===i?c:f;var u={top:a.top-f.top+r.top,bottom:f.bottom-a.bottom+r.bottom,left:a.left-f.left+r.left,right:f.right-a.right+r.right};if(e=e.modifiersData.offset,"popper"===i&&e){var d=e[n];Object.keys(u).forEach((function(e){var t=0<=["right","bottom"].indexOf(e)?1:-1,n=0<=["top","bottom"].indexOf(e)?"y":"x";u[e]+=d[n]*t}))}return u}function k(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];return!t.some((function(e){return!(e&&"function"==typeof e.getBoundingClientRect)}))}function B(e){void 0===e&&(e={});var t=e.defaultModifiers,n=void 0===t?[]:t,r=void 0===(e=e.defaultOptions)?V:e;return function(e,t,i){function a(){f.forEach((function(e){return e()})),f=[]}void 0===i&&(i=r);var s={placement:"bottom",orderedModifiers:[],options:Object.assign(Object.assign({},V),r),modifiersData:{},elements:{reference:e,popper:t},attributes:{},styles:{}},f=[],c=!1,p={state:s,setOptions:function(i){return a(),s.options=Object.assign(Object.assign(Object.assign({},r),s.options),i),s.scrollParents={reference:o(e)?m(e):e.contextElement?m(e.contextElement):[],popper:m(t)},i=function(e){var t=v(e);return N.reduce((function(e,n){return e.concat(t.filter((function(e){return e.phase===n})))}),[])}(function(e){var t=e.reduce((function(e,t){var n=e[t.name];return e[t.name]=n?Object.assign(Object.assign(Object.assign({},n),t),{},{options:Object.assign(Object.assign({},n.options),t.options),data:Object.assign(Object.assign({},n.data),t.data)}):t,e}),{});return Object.keys(t).map((function(e){return t[e]}))}([].concat(n,s.options.modifiers))),s.orderedModifiers=i.filter((function(e){return e.enabled})),s.orderedModifiers.forEach((function(e){var t=e.name,n=e.options;n=void 0===n?{}:n,"function"==typeof(e=e.effect)&&(t=e({state:s,name:t,instance:p,options:n}),f.push(t||function(){}))})),p.update()},forceUpdate:function(){if(!c){var e=s.elements,t=e.reference;if(k(t,e=e.popper))for(s.rects={reference:l(t,g(e),"fixed"===s.options.strategy),popper:u(e)},s.reset=!1,s.placement=s.options.placement,s.orderedModifiers.forEach((function(e){return s.modifiersData[e.name]=Object.assign({},e.data)})),t=0;t<s.orderedModifiers.length;t++)if(!0===s.reset)s.reset=!1,t=-1;else{var n=s.orderedModifiers[t];e=n.fn;var r=n.options;r=void 0===r?{}:r,n=n.name,"function"==typeof e&&(s=e({state:s,options:r,name:n,instance:p})||s)}}},update:b((function(){return new Promise((function(e){p.forceUpdate(),e(s)}))})),destroy:function(){a(),c=!0}};return k(e,t)?(p.setOptions(i).then((function(e){!c&&i.onFirstUpdate&&i.onFirstUpdate(e)})),p):p}}function W(e){var t,r=e.popper,o=e.popperRect,i=e.placement,a=e.offsets,f=e.position,c=e.gpuAcceleration,p=e.adaptive;e.roundOffsets?(e=window.devicePixelRatio||1,e={x:Math.round(a.x*e)/e||0,y:Math.round(a.y*e)/e||0}):e=a;var l=e;e=void 0===(e=l.x)?0:e,l=void 0===(l=l.y)?0:l;var u=a.hasOwnProperty("x");a=a.hasOwnProperty("y");var d,m="left",h="top",v=window;if(p){var b=g(r);b===n(r)&&(b=s(r)),"top"===i&&(h="bottom",l-=b.clientHeight-o.height,l*=c?1:-1),"left"===i&&(m="right",e-=b.clientWidth-o.width,e*=c?1:-1)}return r=Object.assign({position:f},p&&z),c?Object.assign(Object.assign({},r),{},((d={})[h]=a?"0":"",d[m]=u?"0":"",d.transform=2>(v.devicePixelRatio||1)?"translate("+e+"px, "+l+"px)":"translate3d("+e+"px, "+l+"px, 0)",d)):Object.assign(Object.assign({},r),{},((t={})[h]=a?l+"px":"",t[m]=u?e+"px":"",t.transform="",t))}function A(e){return e.replace(/left|right|bottom|top/g,(function(e){return G[e]}))}function H(e){return e.replace(/start|end/g,(function(e){return J[e]}))}function R(e,t,n){return void 0===n&&(n={x:0,y:0}),{top:e.top-t.height-n.y,right:e.right-t.width+n.x,bottom:e.bottom-t.height+n.y,left:e.left-t.width-n.x}}function S(e){return["top","right","bottom","left"].some((function(t){return 0<=e[t]}))}var T=["top","bottom","right","left"],q=T.reduce((function(e,t){return e.concat([t+"-start",t+"-end"])}),[]),C=[].concat(T,["auto"]).reduce((function(e,t){return e.concat([t,t+"-start",t+"-end"])}),[]),N="beforeRead read afterRead beforeMain main afterMain beforeWrite write afterWrite".split(" "),V={placement:"bottom",modifiers:[],strategy:"absolute"},I={passive:!0},_={name:"eventListeners",enabled:!0,phase:"write",fn:function(){},effect:function(e){var t=e.state,r=e.instance,o=(e=e.options).scroll,i=void 0===o||o,a=void 0===(e=e.resize)||e,s=n(t.elements.popper),f=[].concat(t.scrollParents.reference,t.scrollParents.popper);return i&&f.forEach((function(e){e.addEventListener("scroll",r.update,I)})),a&&s.addEventListener("resize",r.update,I),function(){i&&f.forEach((function(e){e.removeEventListener("scroll",r.update,I)})),a&&s.removeEventListener("resize",r.update,I)}},data:{}},U={name:"popperOffsets",enabled:!0,phase:"read",fn:function(e){var t=e.state;t.modifiersData[e.name]=E({reference:t.rects.reference,element:t.rects.popper,strategy:"absolute",placement:t.placement})},data:{}},z={top:"auto",right:"auto",bottom:"auto",left:"auto"},F={name:"computeStyles",enabled:!0,phase:"beforeWrite",fn:function(e){var t=e.state,n=e.options;e=void 0===(e=n.gpuAcceleration)||e;var r=n.adaptive;r=void 0===r||r,n=void 0===(n=n.roundOffsets)||n,e={placement:y(t.placement),popper:t.elements.popper,popperRect:t.rects.popper,gpuAcceleration:e},null!=t.modifiersData.popperOffsets&&(t.styles.popper=Object.assign(Object.assign({},t.styles.popper),W(Object.assign(Object.assign({},e),{},{offsets:t.modifiersData.popperOffsets,position:t.options.strategy,adaptive:r,roundOffsets:n})))),null!=t.modifiersData.arrow&&(t.styles.arrow=Object.assign(Object.assign({},t.styles.arrow),W(Object.assign(Object.assign({},e),{},{offsets:t.modifiersData.arrow,position:"absolute",adaptive:!1,roundOffsets:n})))),t.attributes.popper=Object.assign(Object.assign({},t.attributes.popper),{},{"data-popper-placement":t.placement})},data:{}},X={name:"applyStyles",enabled:!0,phase:"write",fn:function(e){var t=e.state;Object.keys(t.elements).forEach((function(e){var n=t.styles[e]||{},r=t.attributes[e]||{},o=t.elements[e];i(o)&&a(o)&&(Object.assign(o.style,n),Object.keys(r).forEach((function(e){var t=r[e];!1===t?o.removeAttribute(e):o.setAttribute(e,!0===t?"":t)})))}))},effect:function(e){var t=e.state,n={popper:{position:t.options.strategy,left:"0",top:"0",margin:"0"},arrow:{position:"absolute"},reference:{}};return Object.assign(t.elements.popper.style,n.popper),t.elements.arrow&&Object.assign(t.elements.arrow.style,n.arrow),function(){Object.keys(t.elements).forEach((function(e){var r=t.elements[e],o=t.attributes[e]||{};e=Object.keys(t.styles.hasOwnProperty(e)?t.styles[e]:n[e]).reduce((function(e,t){return e[t]="",e}),{}),i(r)&&a(r)&&(Object.assign(r.style,e),Object.keys(o).forEach((function(e){r.removeAttribute(e)})))}))}},requires:["computeStyles"]},Y={name:"offset",enabled:!0,phase:"main",requires:["popperOffsets"],fn:function(e){var t=e.state,n=e.name,r=void 0===(e=e.options.offset)?[0,0]:e,o=(e=C.reduce((function(e,n){var o=t.rects,i=y(n),a=0<=["left","top"].indexOf(i)?-1:1,s="function"==typeof r?r(Object.assign(Object.assign({},o),{},{placement:n})):r;return o=(o=s[0])||0,s=((s=s[1])||0)*a,i=0<=["left","right"].indexOf(i)?{x:s,y:o}:{x:o,y:s},e[n]=i,e}),{}))[t.placement],i=o.x;o=o.y,null!=t.modifiersData.popperOffsets&&(t.modifiersData.popperOffsets.x+=i,t.modifiersData.popperOffsets.y+=o),t.modifiersData[n]=e}},G={left:"right",right:"left",bottom:"top",top:"bottom"},J={start:"end",end:"start"},K={name:"flip",enabled:!0,phase:"main",fn:function(e){var t=e.state,n=e.options;if(e=e.name,!t.modifiersData[e]._skip){var r=n.mainAxis;r=void 0===r||r;var o=n.altAxis;o=void 0===o||o;var i=n.fallbackPlacements,a=n.padding,s=n.boundary,f=n.rootBoundary,c=n.altBoundary,p=n.flipVariations,l=void 0===p||p,u=n.allowedAutoPlacements;p=y(n=t.options.placement),i=i||(p!==n&&l?function(e){if("auto"===y(e))return[];var t=A(e);return[H(e),t,H(t)]}(n):[A(n)]);var d=[n].concat(i).reduce((function(e,n){return e.concat("auto"===y(n)?function(e,t){void 0===t&&(t={});var n=t.boundary,r=t.rootBoundary,o=t.padding,i=t.flipVariations,a=t.allowedAutoPlacements,s=void 0===a?C:a,f=t.placement.split("-")[1];0===(i=(t=f?i?q:q.filter((function(e){return e.split("-")[1]===f})):T).filter((function(e){return 0<=s.indexOf(e)}))).length&&(i=t);var c=i.reduce((function(t,i){return t[i]=L(e,{placement:i,boundary:n,rootBoundary:r,padding:o})[y(i)],t}),{});return Object.keys(c).sort((function(e,t){return c[e]-c[t]}))}(t,{placement:n,boundary:s,rootBoundary:f,padding:a,flipVariations:l,allowedAutoPlacements:u}):n)}),[]);n=t.rects.reference,i=t.rects.popper;var m=new Map;p=!0;for(var h=d[0],g=0;g<d.length;g++){var v=d[g],b=y(v),O="start"===v.split("-")[1],w=0<=["top","bottom"].indexOf(b),x=w?"width":"height",j=L(t,{placement:v,boundary:s,rootBoundary:f,altBoundary:c,padding:a});if(O=w?O?"right":"left":O?"bottom":"top",n[x]>i[x]&&(O=A(O)),x=A(O),w=[],r&&w.push(0>=j[b]),o&&w.push(0>=j[O],0>=j[x]),w.every((function(e){return e}))){h=v,p=!1;break}m.set(v,w)}if(p)for(r=function(e){var t=d.find((function(t){if(t=m.get(t))return t.slice(0,e).every((function(e){return e}))}));if(t)return h=t,"break"},o=l?3:1;0<o&&"break"!==r(o);o--);t.placement!==h&&(t.modifiersData[e]._skip=!0,t.placement=h,t.reset=!0)}},requiresIfExists:["offset"],data:{_skip:!1}},Q={name:"preventOverflow",enabled:!0,phase:"main",fn:function(e){var t=e.state,n=e.options;e=e.name;var r=n.mainAxis,o=void 0===r||r;r=void 0!==(r=n.altAxis)&&r;var i=n.tether;i=void 0===i||i;var a=n.tetherOffset,s=void 0===a?0:a;n=L(t,{boundary:n.boundary,rootBoundary:n.rootBoundary,padding:n.padding,altBoundary:n.altBoundary}),a=y(t.placement);var f=t.placement.split("-")[1],c=!f,p=M(a);a="x"===p?"y":"x";var l=t.modifiersData.popperOffsets,d=t.rects.reference,m=t.rects.popper,h="function"==typeof s?s(Object.assign(Object.assign({},t.rects),{},{placement:t.placement})):s;if(s={x:0,y:0},l){if(o){var v="y"===p?"top":"left",b="y"===p?"bottom":"right",O="y"===p?"height":"width";o=l[p];var w=l[p]+n[v],x=l[p]-n[b],j=i?-m[O]/2:0,E="start"===f?d[O]:m[O];f="start"===f?-m[O]:-d[O],m=t.elements.arrow,m=i&&m?u(m):{width:0,height:0};var D=t.modifiersData["arrow#persistent"]?t.modifiersData["arrow#persistent"].padding:{top:0,right:0,bottom:0,left:0};v=D[v],b=D[b],m=Math.max(0,Math.min(d[O],m[O])),E=c?d[O]/2-j-m-v-h:E-m-v-h,c=c?-d[O]/2+j+m+b+h:f+m+b+h,h=t.elements.arrow&&g(t.elements.arrow),d=t.modifiersData.offset?t.modifiersData.offset[t.placement][p]:0,h=l[p]+E-d-(h?"y"===p?h.clientTop||0:h.clientLeft||0:0),c=l[p]+c-d,i=Math.max(i?Math.min(w,h):w,Math.min(o,i?Math.max(x,c):x)),l[p]=i,s[p]=i-o}r&&(r=l[a],i=Math.max(r+n["x"===p?"top":"left"],Math.min(r,r-n["x"===p?"bottom":"right"])),l[a]=i,s[a]=i-r),t.modifiersData[e]=s}},requiresIfExists:["offset"]},Z={name:"arrow",enabled:!0,phase:"main",fn:function(e){var t,n=e.state;e=e.name;var r=n.elements.arrow,o=n.modifiersData.popperOffsets,i=y(n.placement),a=M(i);if(i=0<=["left","right"].indexOf(i)?"height":"width",r&&o){var s=n.modifiersData[e+"#persistent"].padding,f=u(r),c="y"===a?"top":"left",p="y"===a?"bottom":"right",l=n.rects.reference[i]+n.rects.reference[a]-o[a]-n.rects.popper[i];o=o[a]-n.rects.reference[a],l=(r=(r=g(r))?"y"===a?r.clientHeight||0:r.clientWidth||0:0)/2-f[i]/2+(l/2-o/2),i=Math.max(s[c],Math.min(l,r-f[i]-s[p])),n.modifiersData[e]=((t={})[a]=i,t.centerOffset=i-l,t)}},effect:function(e){var t=e.state,n=e.options;e=e.name;var r=n.element;if(r=void 0===r?"[data-popper-arrow]":r,n=void 0===(n=n.padding)?0:n,null!=r){if("string"==typeof r&&!(r=t.elements.popper.querySelector(r)))return;O(t.elements.popper,r)&&(t.elements.arrow=r,t.modifiersData[e+"#persistent"]={padding:D("number"!=typeof n?n:P(n,T))})}},requires:["popperOffsets"],requiresIfExists:["preventOverflow"]},$={name:"hide",enabled:!0,phase:"main",requiresIfExists:["preventOverflow"],fn:function(e){var t=e.state;e=e.name;var n=t.rects.reference,r=t.rects.popper,o=t.modifiersData.preventOverflow,i=L(t,{elementContext:"reference"}),a=L(t,{altBoundary:!0});n=R(i,n),r=R(a,r,o),o=S(n),a=S(r),t.modifiersData[e]={referenceClippingOffsets:n,popperEscapeOffsets:r,isReferenceHidden:o,hasPopperEscaped:a},t.attributes.popper=Object.assign(Object.assign({},t.attributes.popper),{},{"data-popper-reference-hidden":o,"data-popper-escaped":a})}},ee=B({defaultModifiers:[_,U,F,X]}),te=[_,U,F,X,Y,K,Q,Z,$],ne=B({defaultModifiers:te});e.applyStyles=X,e.arrow=Z,e.computeStyles=F,e.createPopper=ne,e.createPopperLite=ee,e.defaultModifiers=te,e.detectOverflow=L,e.eventListeners=_,e.flip=K,e.hide=$,e.offset=Y,e.popperGenerator=B,e.popperOffsets=U,e.preventOverflow=Q,Object.defineProperty(e,"__esModule",{value:!0})})); //# sourceMappingURL=popper.min.js.map
2,636.428571
18,366
0.674235
3d5f9b51ce87633ddb497cbc95b59bb5bf0cac5e
3,073
js
JavaScript
packages/node_modules/@webex/internal-plugin-calendar/src/index.js
antti2000/spark-js-sdk
b9363a8cacc42597a7ffe8d338cd88f7a25eef62
[ "MIT" ]
null
null
null
packages/node_modules/@webex/internal-plugin-calendar/src/index.js
antti2000/spark-js-sdk
b9363a8cacc42597a7ffe8d338cd88f7a25eef62
[ "MIT" ]
null
null
null
packages/node_modules/@webex/internal-plugin-calendar/src/index.js
antti2000/spark-js-sdk
b9363a8cacc42597a7ffe8d338cd88f7a25eef62
[ "MIT" ]
null
null
null
/*! * Copyright (c) 2015-2017 Cisco Systems, Inc. See LICENSE file. */ import '@webex/internal-plugin-wdm'; import '@webex/internal-plugin-encryption'; import '@webex/internal-plugin-conversation'; import {registerInternalPlugin} from '@webex/webex-core'; import Calendar from './calendar'; import config from './config'; import {has} from 'lodash'; registerInternalPlugin('calendar', Calendar, { config, payloadTransformer: { predicates: [ { name: 'transformMeetingArray', direction: 'inbound', test(ctx, response) { return Promise.resolve(has(response, 'body.items[0].seriesId')); }, extract(response) { return Promise.resolve(response.body.items); } }, { name: 'transformMeeting', direction: 'inbound', test(ctx, response) { return Promise.resolve(has(response, 'body.seriesId')); }, extract(response) { return Promise.resolve(response.body); } }, { name: 'transformMeeting', direction: 'inbound', test(ctx, response) { return Promise.resolve(has(response, 'calendarMeetingExternal')); }, extract(response) { return Promise.resolve(response.calendarMeetingExternal); } } ], transforms: [ { name: 'transformMeetingArray', fn(ctx, array) { return Promise.all(array.map((item) => ctx.transform('transformMeeting', item))); } }, { name: 'transformMeeting', direction: 'inbound', fn(ctx, object) { if (!object) { return Promise.resolve(); } if (!object.encryptionKeyUrl) { return Promise.resolve(); } // Decrypt participant properties const decryptedParticipants = object.encryptedParticipants.map((participant) => Promise.all([ ctx.transform('decryptTextProp', 'encryptedEmailAddress', object.encryptionKeyUrl, participant), ctx.transform('decryptTextProp', 'encryptedName', object.encryptionKeyUrl, participant) ])); return Promise.all([ ctx.transform('decryptTextProp', 'encryptedSubject', object.encryptionKeyUrl, object), ctx.transform('decryptTextProp', 'encryptedLocation', object.encryptionKeyUrl, object), ctx.transform('decryptTextProp', 'encryptedNotes', object.encryptionKeyUrl, object), ctx.transform('decryptTextProp', 'webexURI', object.encryptionKeyUrl, object), ctx.transform('decryptTextProp', 'webexURL', object.encryptionKeyUrl, object), ctx.transform('decryptTextProp', 'spaceMeetURL', object.encryptionKeyUrl, object), ctx.transform('decryptTextProp', 'spaceURI', object.encryptionKeyUrl, object), ctx.transform('decryptTextProp', 'spaceURL', object.encryptionKeyUrl, object) ].concat(decryptedParticipants)); } } ] } }); export {default} from './calendar';
33.769231
108
0.612756
3d5faac1af5a51a2ccad20dfef1bfb76f1d0ef85
74,390
js
JavaScript
app/containers/SettingsList.js
fakob/MoviePrint_v004
46ba13bfc63a666d5a1ec1f4d85a6bfa899f19f2
[ "MIT" ]
88
2018-02-15T07:47:52.000Z
2022-02-11T07:59:27.000Z
app/containers/SettingsList.js
fakob/MoviePrint_v004
46ba13bfc63a666d5a1ec1f4d85a6bfa899f19f2
[ "MIT" ]
23
2018-12-18T03:13:50.000Z
2022-03-31T17:46:36.000Z
app/containers/SettingsList.js
fakob/MoviePrint_v004
46ba13bfc63a666d5a1ec1f4d85a6bfa899f19f2
[ "MIT" ]
24
2018-08-07T12:16:39.000Z
2022-01-14T05:20:33.000Z
// @flow import React, { Component, Fragment } from 'react'; import PropTypes from 'prop-types'; import Slider, { Handle, createSliderWithTooltip } from 'rc-slider'; import Tooltip from 'rc-tooltip'; import { SketchPicker } from 'react-color'; import throttle from 'lodash/throttle'; import { Checkboard } from 'react-color/lib/components/common'; import { Accordion, Button, Icon, Label, Radio, Dropdown, Container, Statistic, Divider, Checkbox, Grid, List, Message, Popup, Input, } from 'semantic-ui-react'; import styles from './Settings.css'; import stylesPop from '../components/Popup.css'; import { frameCountToMinutes, getCustomFileName, limitRange, sanitizeString, typeInTextarea } from '../utils/utils'; import { CACHED_FRAMES_SIZE_OPTIONS, COLOR_PALETTE_PICO_EIGHT, DEFAULT_ALLTHUMBS_NAME, DEFAULT_FRAMEINFO_BACKGROUND_COLOR, DEFAULT_FRAMEINFO_COLOR, DEFAULT_FRAMEINFO_MARGIN, DEFAULT_FRAMEINFO_POSITION, DEFAULT_FRAMEINFO_SCALE, DEFAULT_MOVIE_HEIGHT, DEFAULT_MOVIE_WIDTH, DEFAULT_MOVIEPRINT_BACKGROUND_COLOR, DEFAULT_MOVIEPRINT_NAME, DEFAULT_SHOW_FACERECT, DEFAULT_SINGLETHUMB_NAME, DEFAULT_OUTPUT_JPG_QUALITY, DEFAULT_THUMB_FORMAT, DEFAULT_THUMB_JPG_QUALITY, FACE_CONFIDENCE_THRESHOLD, FACE_SIZE_THRESHOLD, FACE_UNIQUENESS_THRESHOLD, FRAMEINFO_POSITION_OPTIONS, MENU_FOOTER_HEIGHT, MENU_HEADER_HEIGHT, MOVIEPRINT_WIDTH_HEIGHT, MOVIEPRINT_WIDTH_HEIGHT_SIZE_LIMIT, OUTPUT_FORMAT_OPTIONS, OUTPUT_FORMAT, PAPER_LAYOUT_OPTIONS, SHEET_TYPE, SHOT_DETECTION_METHOD_OPTIONS, THUMB_SELECTION, } from '../utils/constants'; import getScaleValueObject from '../utils/getScaleValueObject'; const SliderWithTooltip = createSliderWithTooltip(Slider); const handle = props => { const { value, dragging, index, ...restProps } = props; return ( <Tooltip prefixCls="rc-slider-tooltip" overlay={value} visible placement="top" key={index}> <Handle value={value} {...restProps} /> </Tooltip> ); }; const getOutputSizeOptions = ( baseSizeArray, file = { width: DEFAULT_MOVIE_WIDTH, height: DEFAULT_MOVIE_HEIGHT, }, columnCountTemp, thumbCountTemp, settings, visibilitySettings, sceneArray, secondsPerRowTemp, isGridView, ) => { const newScaleValueObject = getScaleValueObject( file, settings, visibilitySettings, columnCountTemp, thumbCountTemp, 4096, undefined, 1, undefined, undefined, sceneArray, secondsPerRowTemp, ); // set base size options const moviePrintSize = MOVIEPRINT_WIDTH_HEIGHT.map(item => { const otherDim = isGridView ? Math.round(item * newScaleValueObject.moviePrintAspectRatioInv) : Math.round(item / newScaleValueObject.timelineMoviePrintAspectRatioInv); return { value: item, otherdim: otherDim, text: isGridView ? `${item}px (×${otherDim}px)` : `${otherDim}px (×${item}px)`, 'data-tid': `${item}-option`, }; }); // add max option if ( isGridView ? newScaleValueObject.moviePrintAspectRatioInv > 1 : newScaleValueObject.timelineMoviePrintAspectRatioInv < 1 ) { const maxDim = isGridView ? Math.round(MOVIEPRINT_WIDTH_HEIGHT_SIZE_LIMIT / newScaleValueObject.moviePrintAspectRatioInv) : Math.round(MOVIEPRINT_WIDTH_HEIGHT_SIZE_LIMIT * newScaleValueObject.timelineMoviePrintAspectRatioInv); // to avoid duplicates due to rounding if (maxDim !== MOVIEPRINT_WIDTH_HEIGHT_SIZE_LIMIT) { moviePrintSize.push({ value: maxDim, otherdim: MOVIEPRINT_WIDTH_HEIGHT_SIZE_LIMIT, text: isGridView ? `${maxDim}px (×${MOVIEPRINT_WIDTH_HEIGHT_SIZE_LIMIT}px)` : `${MOVIEPRINT_WIDTH_HEIGHT_SIZE_LIMIT}px (×${maxDim}px)`, 'data-tid': `other-max-option`, }); } } // filter options const moviePrintSizeArray = moviePrintSize.filter(item => { const useOtherDim = isGridView ? newScaleValueObject.moviePrintAspectRatioInv > 1 : newScaleValueObject.timelineMoviePrintAspectRatioInv < 1; return useOtherDim ? item.otherdim <= MOVIEPRINT_WIDTH_HEIGHT_SIZE_LIMIT : item.value <= MOVIEPRINT_WIDTH_HEIGHT_SIZE_LIMIT; }); // console.log(moviePrintSizeArray); return moviePrintSizeArray; }; class SettingsList extends Component { constructor(props) { super(props); this.state = { changeSceneCount: false, showSliders: true, displayColorPicker: { moviePrintBackgroundColor: false, frameninfoBackgroundColor: false, frameinfoColor: false, }, previewMoviePrintName: DEFAULT_MOVIEPRINT_NAME, previewSingleThumbName: DEFAULT_SINGLETHUMB_NAME, previewAllThumbsName: DEFAULT_ALLTHUMBS_NAME, focusReference: undefined, activeIndex: -1, }; this.onChangeDefaultMoviePrintNameThrottled = throttle( value => this.props.onChangeDefaultMoviePrintName(value), 1000, { leading: false }, ); this.onChangeDefaultMoviePrintNameThrottled = this.onChangeDefaultMoviePrintNameThrottled.bind(this); this.onChangeDefaultSingleThumbNameThrottled = throttle( value => this.props.onChangeDefaultSingleThumbName(value), 1000, { leading: false }, ); this.onChangeDefaultSingleThumbNameThrottled = this.onChangeDefaultSingleThumbNameThrottled.bind(this); this.onChangeDefaultAllThumbsNameThrottled = throttle( value => this.props.onChangeDefaultAllThumbsName(value), 1000, { leading: false }, ); this.onChangeDefaultAllThumbsNameThrottled = this.onChangeDefaultAllThumbsNameThrottled.bind(this); // this.onToggleSliders = this.onToggleSliders.bind(this); this.onGetPreviewCustomFileName = this.onGetPreviewCustomFileName.bind(this); this.onShowSliders = this.onShowSliders.bind(this); this.onChangeSceneCount = this.onChangeSceneCount.bind(this); this.onChangePaperAspectRatio = this.onChangePaperAspectRatio.bind(this); this.onChangeShowPaperPreview = this.onChangeShowPaperPreview.bind(this); this.onChangeOutputPathFromMovie = this.onChangeOutputPathFromMovie.bind(this); this.onChangeTimelineViewFlow = this.onChangeTimelineViewFlow.bind(this); this.onChangeDetectInOutPoint = this.onChangeDetectInOutPoint.bind(this); this.onChangeReCapture = this.onChangeReCapture.bind(this); this.onChangeShowHeader = this.onChangeShowHeader.bind(this); this.onChangeShowPathInHeader = this.onChangeShowPathInHeader.bind(this); this.onChangeShowDetailsInHeader = this.onChangeShowDetailsInHeader.bind(this); this.onChangeShowTimelineInHeader = this.onChangeShowTimelineInHeader.bind(this); this.onChangeRoundedCorners = this.onChangeRoundedCorners.bind(this); this.onChangeShowHiddenThumbs = this.onChangeShowHiddenThumbs.bind(this); this.onChangeThumbInfo = this.onChangeThumbInfo.bind(this); this.onChangeOutputFormat = this.onChangeOutputFormat.bind(this); this.onChangeThumbFormat = this.onChangeThumbFormat.bind(this); this.onChangeFrameinfoPosition = this.onChangeFrameinfoPosition.bind(this); this.onChangeCachedFramesSize = this.onChangeCachedFramesSize.bind(this); this.onChangeOverwrite = this.onChangeOverwrite.bind(this); this.onChangeIncludeIndividual = this.onChangeIncludeIndividual.bind(this); this.onChangeEmbedFrameNumbers = this.onChangeEmbedFrameNumbers.bind(this); this.onChangeEmbedFilePath = this.onChangeEmbedFilePath.bind(this); this.onChangeOpenFileExplorerAfterSaving = this.onChangeOpenFileExplorerAfterSaving.bind(this); this.onChangeThumbnailScale = this.onChangeThumbnailScale.bind(this); this.onChangeMoviePrintWidth = this.onChangeMoviePrintWidth.bind(this); this.onChangeShotDetectionMethod = this.onChangeShotDetectionMethod.bind(this); this.onSubmitDefaultMoviePrintName = this.onSubmitDefaultMoviePrintName.bind(this); this.onSubmitDefaultSingleThumbName = this.onSubmitDefaultSingleThumbName.bind(this); this.setFocusReference = this.setFocusReference.bind(this); this.addAttributeIntoInput = this.addAttributeIntoInput.bind(this); this.onSubmitDefaultAllThumbsName = this.onSubmitDefaultAllThumbsName.bind(this); this.onChangeColumnCountViaInput = this.onChangeColumnCountViaInput.bind(this); this.onChangeColumnCountViaInputAndApply = this.onChangeColumnCountViaInputAndApply.bind(this); this.onChangeRowViaInput = this.onChangeRowViaInput.bind(this); this.onChangeTimelineViewSecondsPerRowViaInput = this.onChangeTimelineViewSecondsPerRowViaInput.bind(this); this.handleClick = this.handleClick.bind(this); } componentDidUpdate(prevProps) { const { file, sheetName, settings } = this.props; if ( file !== undefined && prevProps.file !== undefined && prevProps.file.name !== undefined && file.name !== undefined ) { if (file.name !== prevProps.file.name || sheetName !== prevProps.sheetName) { const { defaultMoviePrintName = DEFAULT_MOVIEPRINT_NAME, defaultSingleThumbName = DEFAULT_SINGLETHUMB_NAME, defaultAllThumbsName = DEFAULT_ALLTHUMBS_NAME, } = settings; this.setState({ previewMoviePrintName: this.onGetPreviewCustomFileName(defaultMoviePrintName), previewSingleThumbName: this.onGetPreviewCustomFileName(defaultSingleThumbName), previewAllThumbsName: this.onGetPreviewCustomFileName(defaultAllThumbsName), }); } } } // onToggleSliders = () => { // this.setState(state => ({ // showSliders: !state.showSliders // })); // } handleClick = (e, titleProps) => { const { index } = titleProps; const { activeIndex } = this.state; const newIndex = activeIndex === index ? -1 : index; this.setState({ activeIndex: newIndex }); }; onGetPreviewCustomFileName = (customFileName, props = this.props) => { const { file, settings, sheetName } = props; const previewName = getCustomFileName(file !== undefined ? file.name : '', sheetName, `000000`, customFileName); return previewName; }; onShowSliders = (e, { checked }) => { this.setState({ showSliders: !checked, }); }; setFocusReference = e => { const ref = e.target; this.setState({ focusReference: ref, }); }; addAttributeIntoInput = attribute => { const { focusReference } = this.state; if (focusReference !== undefined) { // console.log(focusReference); const newText = typeInTextarea(focusReference, attribute); const previewName = this.onGetPreviewCustomFileName(newText); switch (focusReference.name) { case 'defaultMoviePrintNameInput': this.setState({ previewMoviePrintName: previewName, }); break; case 'defaultSingleThumbNameInput': this.setState({ previewSingleThumbName: previewName, }); break; case 'defaultAllThumbsNameInput': this.setState({ previewAllThumbsName: previewName, }); break; default: } } }; onSubmitDefaultMoviePrintName = e => { const value = sanitizeString(e.target.value); const previewMoviePrintName = this.onGetPreviewCustomFileName(value); this.setState({ previewMoviePrintName, }); this.onChangeDefaultMoviePrintNameThrottled(value); }; onSubmitDefaultSingleThumbName = e => { const value = sanitizeString(e.target.value); const previewSingleThumbName = this.onGetPreviewCustomFileName(value); this.setState({ previewSingleThumbName, }); this.onChangeDefaultSingleThumbNameThrottled(value); }; onSubmitDefaultAllThumbsName = e => { const value = sanitizeString(e.target.value); const previewAllThumbsName = this.onGetPreviewCustomFileName(value); this.setState({ previewAllThumbsName, }); this.onChangeDefaultAllThumbsNameThrottled(value); }; onChangeColumnCountViaInput = e => { if (e.key === 'Enter') { const value = limitRange(Math.floor(e.target.value), 1, 100); this.props.onChangeColumn(value); } }; onChangeColumnCountViaInputAndApply = e => { if (e.key === 'Enter') { const value = limitRange(Math.floor(e.target.value), 1, 100); this.props.onChangeColumnAndApply(value); } }; onChangeRowViaInput = e => { if (e.key === 'Enter') { const value = limitRange(Math.floor(e.target.value), 1, 100); this.props.onChangeRow(value); } }; onChangeTimelineViewSecondsPerRowViaInput = e => { if (e.key === 'Enter') { const value = limitRange(Math.floor(e.target.value), 1, 20000); // 1 second to 5 hours this.props.onChangeTimelineViewSecondsPerRow(value); } }; onChangeSceneCount = (e, { checked }) => { this.setState({ changeSceneCount: checked }); }; onChangeTimelineViewFlow = (e, { checked }) => { this.props.onTimelineViewFlowClick(checked); }; onChangeShowPaperPreview = (e, { checked }) => { this.props.onShowPaperPreviewClick(checked); }; onChangeOutputPathFromMovie = (e, { checked }) => { this.props.onOutputPathFromMovieClick(checked); }; onChangePaperAspectRatio = (e, { value }) => { this.props.onPaperAspectRatioClick(value); }; onChangeDetectInOutPoint = (e, { checked }) => { this.props.onDetectInOutPointClick(checked); }; onChangeReCapture = (e, { checked }) => { this.props.onReCaptureClick(checked); }; onChangeShowHeader = (e, { checked }) => { this.props.onToggleHeaderClick(checked); }; onChangeShowPathInHeader = (e, { checked }) => { this.props.onShowPathInHeaderClick(checked); }; onChangeShowFaceRect = (e, { checked }) => { this.props.onChangeShowFaceRectClick(checked); }; onChangeShowDetailsInHeader = (e, { checked }) => { this.props.onShowDetailsInHeaderClick(checked); }; onChangeShowTimelineInHeader = (e, { checked }) => { this.props.onShowTimelineInHeaderClick(checked); }; onChangeRoundedCorners = (e, { checked }) => { this.props.onRoundedCornersClick(checked); }; onChangeShowHiddenThumbs = (e, { checked }) => { this.props.onShowHiddenThumbsClick(checked); }; onChangeThumbInfo = (e, { value }) => { this.props.onThumbInfoClick(value); }; onChangeOutputFormat = (e, { value }) => { this.props.onOutputFormatClick(value); }; onChangeThumbFormat = (e, { value }) => { this.props.onThumbFormatClick(value); }; onChangeFrameinfoPosition = (e, { value }) => { this.props.onFrameinfoPositionClick(value); }; onChangeCachedFramesSize = (e, { value }) => { this.props.onCachedFramesSizeClick(value); }; onChangeOverwrite = (e, { checked }) => { this.props.onOverwriteClick(checked); }; onChangeIncludeIndividual = (e, { checked }) => { this.props.onIncludeIndividualClick(checked); }; onChangeEmbedFrameNumbers = (e, { checked }) => { this.props.onEmbedFrameNumbersClick(checked); }; onChangeEmbedFilePath = (e, { checked }) => { this.props.onEmbedFilePathClick(checked); }; onChangeOpenFileExplorerAfterSaving = (e, { checked }) => { this.props.onOpenFileExplorerAfterSavingClick(checked); }; onChangeThumbnailScale = (e, { value }) => { this.props.onThumbnailScaleClick(value); }; onChangeMoviePrintWidth = (e, { value }) => { this.props.onMoviePrintWidthClick(value); }; onChangeShotDetectionMethod = (e, { value }) => { this.props.onShotDetectionMethodClick(value); }; colorPickerHandleClick = (e, id) => { e.stopPropagation(); this.setState({ displayColorPicker: { ...this.state.displayColorPicker, [id]: !this.state.displayColorPicker[id], }, }); }; colorPickerHandleClose = (e, id) => { e.stopPropagation(); this.setState({ displayColorPicker: { ...this.state.displayColorPicker, [id]: false, }, }); }; colorPickerHandleChange = (colorLocation, color) => { console.log(colorLocation); console.log(color); this.props.onMoviePrintBackgroundColorClick(colorLocation, color.rgb); }; render() { const { columnCountTemp, file, fileScanRunning, isGridView, onApplyNewGridClick, onChangeColumn, onChangeColumnAndApply, onChangeMargin, onChangeOutputJpgQuality, onChangeThumbJpgQuality, onChangeFaceSizeThreshold, onChangeFaceConfidenceThreshold, onChangeFrameinfoMargin, onChangeFrameinfoScale, onChangeMinDisplaySceneLength, onChangeOutputPathClick, onChangeRow, onChangeSceneDetectionThreshold, onChangeTimelineViewWidthScale, onToggleDetectionChart, reCapture, recaptureAllFrames, rowCountTemp, sceneArray, secondsPerRowTemp, settings, sheetType, sheetName, showChart, thumbCount, thumbCountTemp, visibilitySettings, } = this.props; const { activeIndex, displayColorPicker, focusReference, outputSizeOptions, previewMoviePrintName, previewSingleThumbName, previewAllThumbsName, showSliders, } = this.state; const { defaultCachedFramesSize = 0, defaultDetectInOutPoint, defaultEmbedFilePath, defaultEmbedFrameNumbers, defaultShowFaceRect = DEFAULT_SHOW_FACERECT, defaultFaceSizeThreshold = FACE_SIZE_THRESHOLD, defaultFaceConfidenceThreshold = FACE_CONFIDENCE_THRESHOLD, defaultFaceUniquenessThreshold = FACE_UNIQUENESS_THRESHOLD, defaultFrameinfoBackgroundColor = DEFAULT_FRAMEINFO_BACKGROUND_COLOR, defaultFrameinfoColor = DEFAULT_FRAMEINFO_COLOR, defaultFrameinfoPosition = DEFAULT_FRAMEINFO_POSITION, defaultFrameinfoScale = DEFAULT_FRAMEINFO_SCALE, defaultFrameinfoMargin = DEFAULT_FRAMEINFO_MARGIN, defaultMarginRatio, defaultOutputJpgQuality = DEFAULT_OUTPUT_JPG_QUALITY, defaultThumbJpgQuality = DEFAULT_THUMB_JPG_QUALITY, defaultMarginSliderFactor, defaultMoviePrintBackgroundColor = DEFAULT_MOVIEPRINT_BACKGROUND_COLOR, defaultMoviePrintWidth, defaultOpenFileExplorerAfterSaving, defaultOutputFormat, defaultThumbFormat = DEFAULT_THUMB_FORMAT, defaultOutputPath, defaultOutputPathFromMovie, defaultPaperAspectRatioInv, defaultRoundedCorners, defaultSaveOptionIncludeIndividual, defaultSaveOptionOverwrite, defaultSceneDetectionThreshold, defaultShotDetectionMethod, defaultShowDetailsInHeader, defaultShowHeader, defaultShowPaperPreview, defaultShowPathInHeader, defaultShowTimelineInHeader, defaultThumbInfo, defaultTimelineViewFlow, defaultTimelineViewMinDisplaySceneLengthInFrames, defaultTimelineViewWidthScale, defaultMoviePrintName = DEFAULT_MOVIEPRINT_NAME, defaultSingleThumbName = DEFAULT_SINGLETHUMB_NAME, defaultAllThumbsName = DEFAULT_ALLTHUMBS_NAME, } = settings; const fileFps = file !== undefined ? file.fps : 25; const minutes = file !== undefined ? frameCountToMinutes(file.frameCount, fileFps) : undefined; const minutesRounded = Math.round(minutes); const cutsPerMinuteRounded = Math.round((thumbCountTemp - 1) / minutes); const frameNumberOrTimecode = ['[FN]', '[TC]']; const defaultSingleThumbNameContainsFrameNumberOrTimeCode = frameNumberOrTimecode.some(item => defaultSingleThumbName.includes(item), ); const defaultAllThumbsNameContainsFrameNumberOrTimeCode = frameNumberOrTimecode.some(item => defaultAllThumbsName.includes(item), ); const moviePrintBackgroundColorDependentOnFormat = defaultOutputFormat === OUTPUT_FORMAT.JPG // set alpha only for PNG ? { r: defaultMoviePrintBackgroundColor.r, g: defaultMoviePrintBackgroundColor.g, b: defaultMoviePrintBackgroundColor.b, } : defaultMoviePrintBackgroundColor; const moviePrintBackgroundColorDependentOnFormatString = defaultOutputFormat === OUTPUT_FORMAT.JPG // set alpha only for PNG ? `rgb(${defaultMoviePrintBackgroundColor.r}, ${defaultMoviePrintBackgroundColor.g}, ${defaultMoviePrintBackgroundColor.b})` : `rgba(${defaultMoviePrintBackgroundColor.r}, ${defaultMoviePrintBackgroundColor.g}, ${defaultMoviePrintBackgroundColor.b}, ${defaultMoviePrintBackgroundColor.a})`; const frameninfoBackgroundColorString = `rgba(${defaultFrameinfoBackgroundColor.r}, ${defaultFrameinfoBackgroundColor.g}, ${defaultFrameinfoBackgroundColor.b}, ${defaultFrameinfoBackgroundColor.a})`; const frameinfoColorString = `rgba(${defaultFrameinfoColor.r}, ${defaultFrameinfoColor.g}, ${defaultFrameinfoColor.b}, ${defaultFrameinfoColor.a})`; return ( <Container style={{ marginBottom: `${MENU_HEADER_HEIGHT + MENU_FOOTER_HEIGHT}px`, }} > <Grid padded inverted> {!isGridView && ( <Grid.Row> <Grid.Column width={16}> <Statistic inverted size="tiny"> <Statistic.Value>{thumbCountTemp}</Statistic.Value> <Statistic.Label>{thumbCountTemp === 1 ? 'Shot' : 'Shots'}</Statistic.Label> </Statistic> <Statistic inverted size="tiny"> <Statistic.Value>/</Statistic.Value> </Statistic> <Statistic inverted size="tiny"> <Statistic.Value>~{minutesRounded}</Statistic.Value> <Statistic.Label>{minutesRounded === 1 ? 'Minute' : 'Minutes'}</Statistic.Label> </Statistic> <Statistic inverted size="tiny"> <Statistic.Value>≈</Statistic.Value> </Statistic> <Statistic inverted size="tiny"> <Statistic.Value>{cutsPerMinuteRounded}</Statistic.Value> <Statistic.Label>cut/min</Statistic.Label> </Statistic> </Grid.Column> </Grid.Row> )} {isGridView && ( <Grid.Row> <Grid.Column width={16}> <Statistic inverted size="tiny"> <Statistic.Value>{columnCountTemp}</Statistic.Value> <Statistic.Label>{columnCountTemp === 1 ? 'Column' : 'Columns'}</Statistic.Label> </Statistic> <Statistic inverted size="tiny"> <Statistic.Value>×</Statistic.Value> </Statistic> <Statistic inverted size="tiny"> <Statistic.Value>{rowCountTemp}</Statistic.Value> <Statistic.Label>{rowCountTemp === 1 ? 'Row' : 'Rows'}</Statistic.Label> </Statistic> <Statistic inverted size="tiny"> <Statistic.Value>{columnCountTemp * rowCountTemp === thumbCountTemp ? '=' : '≈'}</Statistic.Value> </Statistic> <Statistic inverted size="tiny" color={reCapture ? 'orange' : undefined}> <Statistic.Value>{thumbCountTemp}</Statistic.Value> <Statistic.Label>{reCapture ? 'Count' : 'Count'}</Statistic.Label> </Statistic> </Grid.Column> </Grid.Row> )} {isGridView && ( <Grid.Row> <Grid.Column width={4}>Columns</Grid.Column> <Grid.Column width={12}> {showSliders && ( <SliderWithTooltip data-tid="columnCountSlider" className={styles.slider} min={1} max={20} defaultValue={columnCountTemp} value={columnCountTemp} marks={{ 1: '1', 20: '20', }} handle={handle} onChange={ sheetType === SHEET_TYPE.INTERVAL && reCapture && isGridView ? onChangeColumn : onChangeColumnAndApply } /> )} {!showSliders && ( <Input type="number" data-tid="columnCountInput" className={styles.input} defaultValue={columnCountTemp} onKeyDown={ reCapture && isGridView ? this.onChangeColumnCountViaInput : this.onChangeColumnCountViaInputAndApply } /> )} </Grid.Column> </Grid.Row> )} {sheetType === SHEET_TYPE.INTERVAL && isGridView && reCapture && ( <Grid.Row> <Grid.Column width={4}>Rows</Grid.Column> <Grid.Column width={12}> {showSliders && ( <SliderWithTooltip data-tid="rowCountSlider" disabled={!reCapture} className={styles.slider} min={1} max={20} defaultValue={rowCountTemp} value={rowCountTemp} {...(reCapture ? {} : { value: rowCountTemp })} marks={{ 1: '1', 20: '20', }} handle={handle} onChange={onChangeRow} /> )} {!showSliders && ( <Input type="number" data-tid="rowCountInput" className={styles.input} defaultValue={rowCountTemp} onKeyDown={this.onChangeRowViaInput} /> )} </Grid.Column> </Grid.Row> )} {!isGridView && ( <> <Grid.Row> <Grid.Column width={4}>Minutes per row</Grid.Column> <Grid.Column width={12}> {showSliders && ( <SliderWithTooltip data-tid="minutesPerRowSlider" className={styles.slider} min={10} max={1800} defaultValue={secondsPerRowTemp} value={secondsPerRowTemp} marks={{ 10: '0.1', 60: '1', 300: '5', 600: '10', 1200: '20', 1800: '30', }} handle={handle} onChange={this.props.onChangeTimelineViewSecondsPerRow} /> )} {!showSliders && ( <Input type="number" data-tid="minutesPerRowInput" className={styles.input} label={{ basic: true, content: 'sec' }} labelPosition="right" defaultValue={secondsPerRowTemp} onKeyDown={this.onChangeTimelineViewSecondsPerRowViaInput} /> )} </Grid.Column> </Grid.Row> {sheetType === SHEET_TYPE.SCENES && ( <Grid.Row> <Grid.Column width={4}></Grid.Column> <Grid.Column width={12}> <Checkbox data-tid="changeTimelineViewFlow" label={<label className={styles.label}>Natural flow</label>} checked={defaultTimelineViewFlow} onChange={this.onChangeTimelineViewFlow} /> </Grid.Column> </Grid.Row> )} {sheetType === SHEET_TYPE.SCENES && ( <Grid.Row> <Grid.Column width={4}>Count</Grid.Column> <Grid.Column width={12}> <Checkbox data-tid="changeSceneCountCheckbox" label={<label className={styles.label}>Change scene count</label>} checked={this.state.changeSceneCount} onChange={this.onChangeSceneCount} /> </Grid.Column> </Grid.Row> )} {sheetType === SHEET_TYPE.SCENES && this.state.changeSceneCount && ( <> <Grid.Row> <Grid.Column width={4}>Shot detection threshold</Grid.Column> <Grid.Column width={12}> <SliderWithTooltip // data-tid='sceneDetectionThresholdSlider' className={styles.slider} min={3} max={40} defaultValue={defaultSceneDetectionThreshold} marks={{ 3: '3', 15: '15', 30: '30', }} handle={handle} onChange={onChangeSceneDetectionThreshold} /> </Grid.Column> </Grid.Row> <Grid.Row> <Grid.Column width={4}></Grid.Column> <Grid.Column width={12}> <Popup trigger={ <Button data-tid="runSceneDetectionBtn" fluid color="orange" loading={fileScanRunning} disabled={fileScanRunning} onClick={() => this.props.runSceneDetection( file.id, file.path, file.useRatio, defaultSceneDetectionThreshold, ) } > Add new MoviePrint </Button> } mouseEnterDelay={1000} on={['hover']} position="bottom center" className={stylesPop.popup} content="Run shot detection with new threshold" /> </Grid.Column> </Grid.Row> </> )} </> )} {sheetType === SHEET_TYPE.INTERVAL && isGridView && ( <Grid.Row> <Grid.Column width={4}>Count</Grid.Column> <Grid.Column width={12}> <Checkbox data-tid="changeThumbCountCheckbox" label={<label className={styles.label}>Change thumb count</label>} checked={reCapture} onChange={this.onChangeReCapture} /> </Grid.Column> </Grid.Row> )} {sheetType === SHEET_TYPE.INTERVAL && isGridView && thumbCount !== thumbCountTemp && ( <Grid.Row> <Grid.Column width={4} /> <Grid.Column width={12}> <Message data-tid="applyNewGridMessage" color="orange" size="mini"> Applying a new grid will overwrite your previously selected thumbs. Don&apos;t worry, this can be undone. </Message> </Grid.Column> </Grid.Row> )} {sheetType === SHEET_TYPE.INTERVAL && isGridView && ( <Grid.Row> <Grid.Column width={4} /> <Grid.Column width={12}> <Popup trigger={ <Button data-tid="applyNewGridBtn" fluid color="orange" disabled={thumbCount === thumbCountTemp} onClick={onApplyNewGridClick} > Apply </Button> } mouseEnterDelay={1000} on={['hover']} position="bottom center" className={stylesPop.popup} content="Apply new grid for MoviePrint" /> </Grid.Column> </Grid.Row> )} <Grid.Row> <Grid.Column width={16}> <Accordion inverted className={styles.accordion}> <Accordion.Title active={activeIndex === 0} index={0} onClick={this.handleClick}> <Icon name="dropdown" /> Guide layout </Accordion.Title> <Accordion.Content active={activeIndex === 0}> <Grid padded inverted> <Grid.Row> <Grid.Column width={4} textAlign="right" verticalAlign="middle"> <Checkbox data-tid="showPaperPreviewCheckbox" checked={defaultShowPaperPreview} onChange={this.onChangeShowPaperPreview} /> </Grid.Column> <Grid.Column width={12}> <Dropdown data-tid="paperLayoutOptionsDropdown" placeholder="Select..." selection disabled={!defaultShowPaperPreview} options={PAPER_LAYOUT_OPTIONS} defaultValue={defaultPaperAspectRatioInv} onChange={this.onChangePaperAspectRatio} /> </Grid.Column> </Grid.Row> </Grid> </Accordion.Content> <Accordion.Title active={activeIndex === 1} index={1} onClick={this.handleClick}> <Icon name="dropdown" /> Styling </Accordion.Title> <Accordion.Content active={activeIndex === 1}> <Grid padded inverted> <Grid.Row> <Grid.Column width={4}>Grid margin</Grid.Column> <Grid.Column width={12}> <SliderWithTooltip // data-tid='marginSlider' className={styles.slider} min={0} max={20} defaultValue={defaultMarginRatio * defaultMarginSliderFactor} marks={{ 0: '0', 20: '20', }} handle={handle} onChange={onChangeMargin} /> </Grid.Column> </Grid.Row> {!isGridView && ( <Grid.Row> <Grid.Column width={4}>Scene width ratio</Grid.Column> <Grid.Column width={12}> <SliderWithTooltip data-tid="sceneWidthRatioSlider" className={styles.slider} min={0} max={100} defaultValue={defaultTimelineViewWidthScale} marks={{ 0: '-10', 50: '0', 100: '+10', }} handle={handle} onChange={onChangeTimelineViewWidthScale} /> </Grid.Column> </Grid.Row> )} {!isGridView && ( <Grid.Row> <Grid.Column width={4}>Min scene width</Grid.Column> <Grid.Column width={12}> <SliderWithTooltip data-tid="minSceneWidthSlider" className={styles.slider} min={0} max={10} defaultValue={Math.round( defaultTimelineViewMinDisplaySceneLengthInFrames / (fileFps * 1.0), )} marks={{ 0: '0', 10: '10', }} handle={handle} onChange={onChangeMinDisplaySceneLength} /> </Grid.Column> </Grid.Row> )} <Grid.Row> <Grid.Column width={4}>Options</Grid.Column> <Grid.Column width={12}> <List> {isGridView && ( <> <List.Item> <Checkbox data-tid="showHeaderCheckbox" label={<label className={styles.label}>Show header</label>} checked={defaultShowHeader} onChange={this.onChangeShowHeader} /> </List.Item> <List.Item> <Checkbox data-tid="showFilePathCheckbox" className={styles.subCheckbox} label={<label className={styles.label}>Show file path</label>} disabled={!defaultShowHeader} checked={defaultShowPathInHeader} onChange={this.onChangeShowPathInHeader} /> </List.Item> <List.Item> <Checkbox data-tid="showFileDetailsCheckbox" className={styles.subCheckbox} label={<label className={styles.label}>Show file details</label>} disabled={!defaultShowHeader} checked={defaultShowDetailsInHeader} onChange={this.onChangeShowDetailsInHeader} /> </List.Item> <List.Item> <Checkbox data-tid="showTimelineCheckbox" className={styles.subCheckbox} label={<label className={styles.label}>Show timeline</label>} disabled={!defaultShowHeader} checked={defaultShowTimelineInHeader} onChange={this.onChangeShowTimelineInHeader} /> </List.Item> <List.Item> <Checkbox data-tid="roundedCornersCheckbox" label={<label className={styles.label}>Rounded corners</label>} checked={defaultRoundedCorners} onChange={this.onChangeRoundedCorners} /> </List.Item> <List.Item> <Checkbox data-tid="showHiddenThumbsCheckbox" label={<label className={styles.label}>Show hidden thumbs</label>} checked={visibilitySettings.visibilityFilter === THUMB_SELECTION.ALL_THUMBS} onChange={this.onChangeShowHiddenThumbs} /> </List.Item> </> )} </List> </Grid.Column> </Grid.Row> <Divider inverted /> <Grid.Row> <Grid.Column width={4}>Frame info</Grid.Column> <Grid.Column width={12}> <List> <List.Item> <Radio data-tid="showFramesRadioBtn" label={<label className={styles.label}>Show frames</label>} name="radioGroup" value="frames" checked={defaultThumbInfo === 'frames'} onChange={this.onChangeThumbInfo} /> </List.Item> <List.Item> <Radio data-tid="showTimecodeRadioBtn" label={<label className={styles.label}>Show timecode</label>} name="radioGroup" value="timecode" checked={defaultThumbInfo === 'timecode'} onChange={this.onChangeThumbInfo} /> </List.Item> <List.Item> <Radio data-tid="hideInfoRadioBtn" label={<label className={styles.label}>Hide info</label>} name="radioGroup" value="hideInfo" checked={defaultThumbInfo === 'hideInfo'} onChange={this.onChangeThumbInfo} /> </List.Item> </List> </Grid.Column> </Grid.Row> <Grid.Row> <Grid.Column width={4}>Font color</Grid.Column> <Grid.Column width={12}> <div> <div className={styles.colorPickerSwatch} onClick={e => this.colorPickerHandleClick(e, 'frameinfoColor')} > <Checkboard /> <div className={`${styles.colorPickerColor} ${styles.colorPickerText}`} style={{ backgroundColor: frameninfoBackgroundColorString, color: frameinfoColorString, }} > 00:00:00:00 </div> </div> {displayColorPicker.frameinfoColor ? ( <div className={styles.colorPickerPopover} // onMouseLeave={(e) => this.colorPickerHandleClose(e, 'frameinfoColor')} > <div className={styles.colorPickerCover} onClick={e => this.colorPickerHandleClose(e, 'frameinfoColor')} /> <SketchPicker color={defaultFrameinfoColor} onChange={color => this.colorPickerHandleChange('frameinfoColor', color)} presetColors={COLOR_PALETTE_PICO_EIGHT} /> </div> ) : null} </div> </Grid.Column> </Grid.Row> <Grid.Row> <Grid.Column width={4}>Background color</Grid.Column> <Grid.Column width={12}> <div> <div className={styles.colorPickerSwatch} onClick={e => this.colorPickerHandleClick(e, 'frameninfoBackgroundColor')} > <Checkboard /> <div className={styles.colorPickerColor} style={{ backgroundColor: frameninfoBackgroundColorString, }} /> </div> {displayColorPicker.frameninfoBackgroundColor ? ( <div className={styles.colorPickerPopover} // onMouseLeave={(e) => this.colorPickerHandleClose(e, 'frameninfoBackgroundColor')} > <div className={styles.colorPickerCover} onClick={e => this.colorPickerHandleClose(e, 'frameninfoBackgroundColor')} /> <SketchPicker color={defaultFrameinfoBackgroundColor} onChange={color => this.colorPickerHandleChange('frameninfoBackgroundColor', color)} presetColors={COLOR_PALETTE_PICO_EIGHT} /> </div> ) : null} </div> </Grid.Column> </Grid.Row> <Grid.Row> <Grid.Column width={4}>Position</Grid.Column> <Grid.Column width={12}> <Dropdown data-tid="changeFrameinfoPositionDropdown" placeholder="Select..." selection options={FRAMEINFO_POSITION_OPTIONS} defaultValue={defaultFrameinfoPosition} onChange={this.onChangeFrameinfoPosition} /> </Grid.Column> </Grid.Row> <Grid.Row> <Grid.Column width={4}>Size</Grid.Column> <Grid.Column width={12}> <SliderWithTooltip data-tid="frameinfoScaleSlider" className={styles.slider} min={1} max={100} defaultValue={defaultFrameinfoScale} marks={{ 1: '1', 10: '10', 100: '100', }} handle={handle} onChange={onChangeFrameinfoScale} /> </Grid.Column> </Grid.Row> <Grid.Row> <Grid.Column width={4}>Margin</Grid.Column> <Grid.Column width={12}> <SliderWithTooltip data-tid="frameinfoMarginSlider" className={styles.slider} min={0} max={50} defaultValue={defaultFrameinfoMargin} marks={{ 0: '0', 50: '50', }} handle={handle} onChange={onChangeFrameinfoMargin} /> </Grid.Column> </Grid.Row> </Grid> </Accordion.Content> <Accordion.Title active={activeIndex === 2} index={2} onClick={this.handleClick}> <Icon name="dropdown" /> Output </Accordion.Title> <Accordion.Content active={activeIndex === 2}> <Grid padded inverted> <Grid.Row> <Grid.Column width={4}>File path</Grid.Column> <Grid.Column width={12}> <List> <List.Item> <div style={{ wordWrap: 'break-word', opacity: defaultOutputPathFromMovie ? '0.5' : '1.0', }} > {defaultOutputPath} </div> </List.Item> <List.Item> <Button data-tid="changeOutputPathBtn" onClick={onChangeOutputPathClick} disabled={defaultOutputPathFromMovie} > Change... </Button> </List.Item> <List.Item> <Checkbox data-tid="showPaperPreviewCheckbox" label={<label className={styles.label}>Same as movie file</label>} style={{ marginTop: '8px', }} checked={defaultOutputPathFromMovie} onChange={this.onChangeOutputPathFromMovie} /> </List.Item> </List> </Grid.Column> </Grid.Row> <Divider inverted /> <Grid.Row> <Grid.Column width={16}> <h4>MoviePrint</h4> </Grid.Column> </Grid.Row> <Grid.Row> <Grid.Column width={4}>Size</Grid.Column> <Grid.Column width={12}> <Dropdown data-tid="changeMoviePrintWidthDropdown" placeholder="Select..." selection options={getOutputSizeOptions( MOVIEPRINT_WIDTH_HEIGHT, file, columnCountTemp, thumbCountTemp, settings, visibilitySettings, sceneArray, secondsPerRowTemp, isGridView, )} defaultValue={defaultMoviePrintWidth} onChange={this.onChangeMoviePrintWidth} /> </Grid.Column> </Grid.Row> <Grid.Row> <Grid.Column width={4}>Format</Grid.Column> <Grid.Column width={12}> <Dropdown data-tid="changeOutputFormatDropdown" placeholder="Select..." selection options={OUTPUT_FORMAT_OPTIONS} defaultValue={defaultOutputFormat} onChange={this.onChangeOutputFormat} /> </Grid.Column> </Grid.Row> {defaultOutputFormat === OUTPUT_FORMAT.JPG && ( <Grid.Row> <Grid.Column width={4}>JPG quality</Grid.Column> <Grid.Column width={12}> <SliderWithTooltip data-tid="outputJpgQualitySlider" className={styles.slider} min={0} max={100} defaultValue={defaultOutputJpgQuality} marks={{ 0: '0', 80: '80', 100: '100', }} handle={handle} onChange={onChangeOutputJpgQuality} /> </Grid.Column> </Grid.Row> )} <Grid.Row> <Grid.Column width={4}>Background color</Grid.Column> <Grid.Column width={12}> <div> <div className={styles.colorPickerSwatch} onClick={e => this.colorPickerHandleClick(e, 'moviePrintBackgroundColor')} > <Checkboard /> <div className={styles.colorPickerColor} style={{ backgroundColor: moviePrintBackgroundColorDependentOnFormatString, }} /> </div> {displayColorPicker.moviePrintBackgroundColor ? ( <div className={styles.colorPickerPopover} // onMouseLeave={(e) => this.colorPickerHandleClose(e, 'moviePrintBackgroundColor')} > <div className={styles.colorPickerCover} onClick={e => this.colorPickerHandleClose(e, 'moviePrintBackgroundColor')} /> <SketchPicker color={moviePrintBackgroundColorDependentOnFormat} onChange={color => this.colorPickerHandleChange('moviePrintBackgroundColor', color)} disableAlpha={defaultOutputFormat === OUTPUT_FORMAT.JPG} presetColors={COLOR_PALETTE_PICO_EIGHT} /> </div> ) : null} </div> </Grid.Column> </Grid.Row> <Grid.Row> <Grid.Column width={4}>Save options</Grid.Column> <Grid.Column width={12}> <List> <List.Item> <Checkbox data-tid="overwriteExistingCheckbox" label={<label className={styles.label}>Overwrite existing</label>} checked={defaultSaveOptionOverwrite} onChange={this.onChangeOverwrite} /> </List.Item> <List.Item> <Checkbox data-tid="includeIndividualFramesCheckbox" label={<label className={styles.label}>Include individual thumbs</label>} checked={defaultSaveOptionIncludeIndividual} onChange={this.onChangeIncludeIndividual} /> </List.Item> <List.Item> <Checkbox data-tid="embedFrameNumbersCheckbox" label={<label className={styles.label}>Embed frameNumbers (only PNG)</label>} checked={defaultEmbedFrameNumbers} onChange={this.onChangeEmbedFrameNumbers} /> </List.Item> <List.Item> <Checkbox data-tid="embedFilePathCheckbox" label={<label className={styles.label}>Embed filePath (only PNG)</label>} checked={defaultEmbedFilePath} onChange={this.onChangeEmbedFilePath} /> </List.Item> <List.Item> <Checkbox data-tid="embedFilePathCheckbox" label={<label className={styles.label}>Open File Explorer after saving</label>} checked={defaultOpenFileExplorerAfterSaving} onChange={this.onChangeOpenFileExplorerAfterSaving} /> </List.Item> </List> </Grid.Column> </Grid.Row> <Divider inverted /> <Grid.Row> <Grid.Column width={16}> <h4>Thumbs</h4> </Grid.Column> </Grid.Row> <Grid.Row> <Grid.Column width={4}>Format</Grid.Column> <Grid.Column width={12}> <Dropdown data-tid="changeThumbFormatDropdown" placeholder="Select..." selection options={OUTPUT_FORMAT_OPTIONS} defaultValue={defaultThumbFormat} onChange={this.onChangeThumbFormat} /> </Grid.Column> </Grid.Row> {defaultThumbFormat === OUTPUT_FORMAT.JPG && ( <Grid.Row> <Grid.Column width={4}>JPG quality</Grid.Column> <Grid.Column width={12}> <SliderWithTooltip data-tid="thumbJpgQualitySlider" className={styles.slider} min={0} max={100} defaultValue={defaultThumbJpgQuality} marks={{ 0: '0', 95: '95', 100: '100', }} handle={handle} onChange={onChangeThumbJpgQuality} /> </Grid.Column> </Grid.Row> )} </Grid> </Accordion.Content> <Accordion.Title active={activeIndex === 3} index={3} onClick={this.handleClick}> <Icon name="dropdown" /> Naming scheme </Accordion.Title> <Accordion.Content active={activeIndex === 3}> <Grid padded inverted> <Grid.Row> <Grid.Column width={16}> <label>File name when saving a MoviePrint</label> <Input // ref={this.inputDefaultMoviePrintName} data-tid="defaultMoviePrintNameInput" name="defaultMoviePrintNameInput" // needed for addAttributeIntoInput fluid placeholder="MoviePrint name" defaultValue={defaultMoviePrintName} onFocus={this.setFocusReference} onBlur={this.onSubmitDefaultMoviePrintName} onKeyUp={this.onSubmitDefaultMoviePrintName} /> <Label className={styles.previewCustomName}> {previewMoviePrintName}.{defaultOutputFormat} </Label> <Divider hidden className={styles.smallDivider} /> <label>File name of thumb when saving a single thumb</label> <Input // ref={this.inputDefaultSingleThumbName} data-tid="defaultSingleThumbNameInput" name="defaultSingleThumbNameInput" // needed for addAttributeIntoInput fluid placeholder="Name when saving a single thumb" defaultValue={defaultSingleThumbName} onFocus={this.setFocusReference} onBlur={this.onSubmitDefaultSingleThumbName} onKeyUp={this.onSubmitDefaultSingleThumbName} /> <Label className={styles.previewCustomName} color={defaultSingleThumbNameContainsFrameNumberOrTimeCode ? undefined : 'orange'} pointing={defaultSingleThumbNameContainsFrameNumberOrTimeCode ? undefined : true} > {defaultSingleThumbNameContainsFrameNumberOrTimeCode ? undefined : 'The framenumber attribute is missing. This can lead to the thumb being overwritten. | '} {previewSingleThumbName}.jpg </Label> <Divider hidden className={styles.smallDivider} /> <label> File name of thumbs when <em>Include individual thumbs</em> is selected </label> <Input // ref={this.inputDefaultAllThumbsName} data-tid="defaultAllThumbsNameInput" name="defaultAllThumbsNameInput" // needed for addAttributeIntoInput fluid placeholder="Name when including individual thumbs" defaultValue={defaultAllThumbsName} onFocus={this.setFocusReference} onBlur={this.onSubmitDefaultAllThumbsName} onKeyUp={this.onSubmitDefaultAllThumbsName} /> <Label className={styles.previewCustomName} color={defaultAllThumbsNameContainsFrameNumberOrTimeCode ? undefined : 'orange'} pointing={defaultAllThumbsNameContainsFrameNumberOrTimeCode ? undefined : true} > {defaultAllThumbsNameContainsFrameNumberOrTimeCode ? undefined : 'The framenumber attribute is missing. This can lead to the thumb being overwritten. | '} {previewAllThumbsName}.jpg </Label> <h6>Available attributes</h6> <Button data-tid="addAttribute[MN]IntoInputButton" className={styles.attributeButton} onClick={() => this.addAttributeIntoInput('[MN]')} disabled={focusReference === undefined} size="mini" > [MN] Movie name </Button> <Button data-tid="addAttribute[ME]IntoInputButton" className={styles.attributeButton} onClick={() => this.addAttributeIntoInput('[ME]')} disabled={focusReference === undefined} size="mini" > [ME] Movie extension </Button> <Button data-tid="addAttribute[MPN]IntoInputButton" className={styles.attributeButton} onClick={() => this.addAttributeIntoInput('[MPN]')} disabled={focusReference === undefined} size="mini" > [MPN] MoviePrint name </Button> <Button data-tid="addAttribute[FN]IntoInputButton" className={styles.attributeButton} onClick={() => this.addAttributeIntoInput('[FN]')} disabled={focusReference === undefined} size="mini" > [FN] Frame number </Button> <Button data-tid="addAttribute[TC]IntoInputButton" className={styles.attributeButton} onClick={() => this.addAttributeIntoInput('[TC]')} disabled={focusReference === undefined} size="mini" > [TC] Timecode </Button> </Grid.Column> </Grid.Row> </Grid> </Accordion.Content> <Accordion.Title active={activeIndex === 4} index={4} onClick={this.handleClick}> <Icon name="dropdown" /> Face detection </Accordion.Title> <Accordion.Content active={activeIndex === 4}> <Grid padded inverted> <Grid.Row> <Grid.Column width={4}>Face confidence threshold</Grid.Column> <Grid.Column width={12}> <SliderWithTooltip data-tid="faceConfidenceThresholdSlider" className={styles.slider} min={0} max={100} defaultValue={defaultFaceConfidenceThreshold} marks={{ 0: '0', 50: '50', 100: '100', }} handle={handle} onChange={onChangeFaceConfidenceThreshold} /> </Grid.Column> </Grid.Row> <Grid.Row> <Grid.Column width={4}>Face size threshold</Grid.Column> <Grid.Column width={12}> <SliderWithTooltip data-tid="faceSizeThresholdSlider" className={styles.slider} min={0} max={100} defaultValue={defaultFaceSizeThreshold} marks={{ 0: '0', 50: '50', 100: '100', }} handle={handle} onChange={onChangeFaceSizeThreshold} /> <br /> <em>Changes take effect on next face scan.</em> </Grid.Column> </Grid.Row> </Grid> </Accordion.Content> <Accordion.Title active={activeIndex === 5} index={5} onClick={this.handleClick}> <Icon name="dropdown" /> Frame cache </Accordion.Title> <Accordion.Content active={activeIndex === 5}> <Grid padded inverted> <Grid.Row> <Grid.Column width={4}>Max size</Grid.Column> <Grid.Column width={12}> <Dropdown data-tid="changeCachedFramesSizeDropdown" placeholder="Select..." selection options={CACHED_FRAMES_SIZE_OPTIONS} defaultValue={defaultCachedFramesSize} onChange={this.onChangeCachedFramesSize} /> </Grid.Column> </Grid.Row> <Grid.Row> <Grid.Column width={4} /> <Grid.Column width={12}> <Popup trigger={ <Button data-tid="updateFrameCacheBtn" onClick={recaptureAllFrames}> Update frame cache </Button> } mouseEnterDelay={1000} on={['hover']} position="bottom center" className={stylesPop.popup} content="Recapture all frames and store it in the frame cache (uses max size)" /> </Grid.Column> </Grid.Row> </Grid> </Accordion.Content> <Accordion.Title active={activeIndex === 6} index={6} onClick={this.handleClick}> <Icon name="dropdown" /> Experimental </Accordion.Title> <Accordion.Content active={activeIndex === 6}> <Grid padded inverted> <Grid.Row> <Grid.Column width={4}>Shot detection method</Grid.Column> <Grid.Column width={12}> <Dropdown data-tid="shotDetectionMethodOptionsDropdown" placeholder="Select..." selection options={SHOT_DETECTION_METHOD_OPTIONS} defaultValue={defaultShotDetectionMethod} onChange={this.onChangeShotDetectionMethod} /> </Grid.Column> </Grid.Row> <Grid.Row> <Grid.Column width={4}>Detection chart</Grid.Column> <Grid.Column width={12}> <Popup trigger={ <Button data-tid="showDetectionChartBtn" // fluid onClick={onToggleDetectionChart} > {showChart ? 'Hide detection chart' : 'Show detection chart'} </Button> } mouseEnterDelay={1000} on={['hover']} position="bottom center" className={stylesPop.popup} content="Show detection chart with mean and difference values per frame" /> </Grid.Column> </Grid.Row> <Grid.Row> <Grid.Column width={4}>Import options</Grid.Column> <Grid.Column width={12}> <Checkbox data-tid="automaticDetectionInOutPointCheckbox" label={<label className={styles.label}>Automatic detection of In and Outpoint</label>} checked={defaultDetectInOutPoint} onChange={this.onChangeDetectInOutPoint} /> </Grid.Column> </Grid.Row> <Grid.Row> <Grid.Column width={4}>Expert</Grid.Column> <Grid.Column width={12}> <Checkbox data-tid="showSlidersCheckbox" label={<label className={styles.label}>Show input field instead of slider</label>} checked={!this.state.showSliders} onChange={this.onShowSliders} /> </Grid.Column> </Grid.Row> </Grid> </Accordion.Content> </Accordion> </Grid.Column> </Grid.Row> </Grid> </Container> ); } } SettingsList.contextTypes = { store: PropTypes.object, }; export default SettingsList;
42.075792
203
0.471354
3d60eb81175030d195b60a8eb18effa9c7bc8584
766,568
js
JavaScript
core/built/scripts/vendor.js
simonkberg/ghost-openshift
84be877e9192d0748edde953d591ae14ab8245cb
[ "MIT" ]
1
2015-10-07T16:53:00.000Z
2015-10-07T16:53:00.000Z
core/built/scripts/vendor.js
octohost/ghost
e877730d4d2029ea92902aedb971b20ae6107dce
[ "MIT" ]
null
null
null
core/built/scripts/vendor.js
octohost/ghost
e877730d4d2029ea92902aedb971b20ae6107dce
[ "MIT" ]
1
2019-11-17T14:53:01.000Z
2019-11-17T14:53:01.000Z
/*! jQuery v1.10.2 | (c) 2005, 2013 jQuery Foundation, Inc. | jquery.org/license //@ sourceMappingURL=/../../shared/vendor/jquery/jquery.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); /*! jQuery UI - v1.10.3 - 2013-06-03 * http://jqueryui.com * Includes: jquery.ui.core.js, jquery.ui.widget.js, jquery.ui.mouse.js, jquery.ui.draggable.js * Copyright 2013 jQuery Foundation and other contributors Licensed MIT */ (function(e,t){function i(t,i){var a,n,r,o=t.nodeName.toLowerCase();return"area"===o?(a=t.parentNode,n=a.name,t.href&&n&&"map"===a.nodeName.toLowerCase()?(r=e("img[usemap=#"+n+"]")[0],!!r&&s(r)):!1):(/input|select|textarea|button|object/.test(o)?!t.disabled:"a"===o?t.href||i:i)&&s(t)}function s(t){return e.expr.filters.visible(t)&&!e(t).parents().addBack().filter(function(){return"hidden"===e.css(this,"visibility")}).length}var a=0,n=/^ui-id-\d+$/;e.ui=e.ui||{},e.extend(e.ui,{version:"1.10.3",keyCode:{BACKSPACE:8,COMMA:188,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,LEFT:37,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,SPACE:32,TAB:9,UP:38}}),e.fn.extend({focus:function(t){return function(i,s){return"number"==typeof i?this.each(function(){var t=this;setTimeout(function(){e(t).focus(),s&&s.call(t)},i)}):t.apply(this,arguments)}}(e.fn.focus),scrollParent:function(){var t;return t=e.ui.ie&&/(static|relative)/.test(this.css("position"))||/absolute/.test(this.css("position"))?this.parents().filter(function(){return/(relative|absolute|fixed)/.test(e.css(this,"position"))&&/(auto|scroll)/.test(e.css(this,"overflow")+e.css(this,"overflow-y")+e.css(this,"overflow-x"))}).eq(0):this.parents().filter(function(){return/(auto|scroll)/.test(e.css(this,"overflow")+e.css(this,"overflow-y")+e.css(this,"overflow-x"))}).eq(0),/fixed/.test(this.css("position"))||!t.length?e(document):t},zIndex:function(i){if(i!==t)return this.css("zIndex",i);if(this.length)for(var s,a,n=e(this[0]);n.length&&n[0]!==document;){if(s=n.css("position"),("absolute"===s||"relative"===s||"fixed"===s)&&(a=parseInt(n.css("zIndex"),10),!isNaN(a)&&0!==a))return a;n=n.parent()}return 0},uniqueId:function(){return this.each(function(){this.id||(this.id="ui-id-"+ ++a)})},removeUniqueId:function(){return this.each(function(){n.test(this.id)&&e(this).removeAttr("id")})}}),e.extend(e.expr[":"],{data:e.expr.createPseudo?e.expr.createPseudo(function(t){return function(i){return!!e.data(i,t)}}):function(t,i,s){return!!e.data(t,s[3])},focusable:function(t){return i(t,!isNaN(e.attr(t,"tabindex")))},tabbable:function(t){var s=e.attr(t,"tabindex"),a=isNaN(s);return(a||s>=0)&&i(t,!a)}}),e("<a>").outerWidth(1).jquery||e.each(["Width","Height"],function(i,s){function a(t,i,s,a){return e.each(n,function(){i-=parseFloat(e.css(t,"padding"+this))||0,s&&(i-=parseFloat(e.css(t,"border"+this+"Width"))||0),a&&(i-=parseFloat(e.css(t,"margin"+this))||0)}),i}var n="Width"===s?["Left","Right"]:["Top","Bottom"],r=s.toLowerCase(),o={innerWidth:e.fn.innerWidth,innerHeight:e.fn.innerHeight,outerWidth:e.fn.outerWidth,outerHeight:e.fn.outerHeight};e.fn["inner"+s]=function(i){return i===t?o["inner"+s].call(this):this.each(function(){e(this).css(r,a(this,i)+"px")})},e.fn["outer"+s]=function(t,i){return"number"!=typeof t?o["outer"+s].call(this,t):this.each(function(){e(this).css(r,a(this,t,!0,i)+"px")})}}),e.fn.addBack||(e.fn.addBack=function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}),e("<a>").data("a-b","a").removeData("a-b").data("a-b")&&(e.fn.removeData=function(t){return function(i){return arguments.length?t.call(this,e.camelCase(i)):t.call(this)}}(e.fn.removeData)),e.ui.ie=!!/msie [\w.]+/.exec(navigator.userAgent.toLowerCase()),e.support.selectstart="onselectstart"in document.createElement("div"),e.fn.extend({disableSelection:function(){return this.bind((e.support.selectstart?"selectstart":"mousedown")+".ui-disableSelection",function(e){e.preventDefault()})},enableSelection:function(){return this.unbind(".ui-disableSelection")}}),e.extend(e.ui,{plugin:{add:function(t,i,s){var a,n=e.ui[t].prototype;for(a in s)n.plugins[a]=n.plugins[a]||[],n.plugins[a].push([i,s[a]])},call:function(e,t,i){var s,a=e.plugins[t];if(a&&e.element[0].parentNode&&11!==e.element[0].parentNode.nodeType)for(s=0;a.length>s;s++)e.options[a[s][0]]&&a[s][1].apply(e.element,i)}},hasScroll:function(t,i){if("hidden"===e(t).css("overflow"))return!1;var s=i&&"left"===i?"scrollLeft":"scrollTop",a=!1;return t[s]>0?!0:(t[s]=1,a=t[s]>0,t[s]=0,a)}})})(jQuery);(function(e,t){var i=0,s=Array.prototype.slice,n=e.cleanData;e.cleanData=function(t){for(var i,s=0;null!=(i=t[s]);s++)try{e(i).triggerHandler("remove")}catch(a){}n(t)},e.widget=function(i,s,n){var a,r,o,h,l={},u=i.split(".")[0];i=i.split(".")[1],a=u+"-"+i,n||(n=s,s=e.Widget),e.expr[":"][a.toLowerCase()]=function(t){return!!e.data(t,a)},e[u]=e[u]||{},r=e[u][i],o=e[u][i]=function(e,i){return this._createWidget?(arguments.length&&this._createWidget(e,i),t):new o(e,i)},e.extend(o,r,{version:n.version,_proto:e.extend({},n),_childConstructors:[]}),h=new s,h.options=e.widget.extend({},h.options),e.each(n,function(i,n){return e.isFunction(n)?(l[i]=function(){var e=function(){return s.prototype[i].apply(this,arguments)},t=function(e){return s.prototype[i].apply(this,e)};return function(){var i,s=this._super,a=this._superApply;return this._super=e,this._superApply=t,i=n.apply(this,arguments),this._super=s,this._superApply=a,i}}(),t):(l[i]=n,t)}),o.prototype=e.widget.extend(h,{widgetEventPrefix:r?h.widgetEventPrefix:i},l,{constructor:o,namespace:u,widgetName:i,widgetFullName:a}),r?(e.each(r._childConstructors,function(t,i){var s=i.prototype;e.widget(s.namespace+"."+s.widgetName,o,i._proto)}),delete r._childConstructors):s._childConstructors.push(o),e.widget.bridge(i,o)},e.widget.extend=function(i){for(var n,a,r=s.call(arguments,1),o=0,h=r.length;h>o;o++)for(n in r[o])a=r[o][n],r[o].hasOwnProperty(n)&&a!==t&&(i[n]=e.isPlainObject(a)?e.isPlainObject(i[n])?e.widget.extend({},i[n],a):e.widget.extend({},a):a);return i},e.widget.bridge=function(i,n){var a=n.prototype.widgetFullName||i;e.fn[i]=function(r){var o="string"==typeof r,h=s.call(arguments,1),l=this;return r=!o&&h.length?e.widget.extend.apply(null,[r].concat(h)):r,o?this.each(function(){var s,n=e.data(this,a);return n?e.isFunction(n[r])&&"_"!==r.charAt(0)?(s=n[r].apply(n,h),s!==n&&s!==t?(l=s&&s.jquery?l.pushStack(s.get()):s,!1):t):e.error("no such method '"+r+"' for "+i+" widget instance"):e.error("cannot call methods on "+i+" prior to initialization; "+"attempted to call method '"+r+"'")}):this.each(function(){var t=e.data(this,a);t?t.option(r||{})._init():e.data(this,a,new n(r,this))}),l}},e.Widget=function(){},e.Widget._childConstructors=[],e.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",defaultElement:"<div>",options:{disabled:!1,create:null},_createWidget:function(t,s){s=e(s||this.defaultElement||this)[0],this.element=e(s),this.uuid=i++,this.eventNamespace="."+this.widgetName+this.uuid,this.options=e.widget.extend({},this.options,this._getCreateOptions(),t),this.bindings=e(),this.hoverable=e(),this.focusable=e(),s!==this&&(e.data(s,this.widgetFullName,this),this._on(!0,this.element,{remove:function(e){e.target===s&&this.destroy()}}),this.document=e(s.style?s.ownerDocument:s.document||s),this.window=e(this.document[0].defaultView||this.document[0].parentWindow)),this._create(),this._trigger("create",null,this._getCreateEventData()),this._init()},_getCreateOptions:e.noop,_getCreateEventData:e.noop,_create:e.noop,_init:e.noop,destroy:function(){this._destroy(),this.element.unbind(this.eventNamespace).removeData(this.widgetName).removeData(this.widgetFullName).removeData(e.camelCase(this.widgetFullName)),this.widget().unbind(this.eventNamespace).removeAttr("aria-disabled").removeClass(this.widgetFullName+"-disabled "+"ui-state-disabled"),this.bindings.unbind(this.eventNamespace),this.hoverable.removeClass("ui-state-hover"),this.focusable.removeClass("ui-state-focus")},_destroy:e.noop,widget:function(){return this.element},option:function(i,s){var n,a,r,o=i;if(0===arguments.length)return e.widget.extend({},this.options);if("string"==typeof i)if(o={},n=i.split("."),i=n.shift(),n.length){for(a=o[i]=e.widget.extend({},this.options[i]),r=0;n.length-1>r;r++)a[n[r]]=a[n[r]]||{},a=a[n[r]];if(i=n.pop(),s===t)return a[i]===t?null:a[i];a[i]=s}else{if(s===t)return this.options[i]===t?null:this.options[i];o[i]=s}return this._setOptions(o),this},_setOptions:function(e){var t;for(t in e)this._setOption(t,e[t]);return this},_setOption:function(e,t){return this.options[e]=t,"disabled"===e&&(this.widget().toggleClass(this.widgetFullName+"-disabled ui-state-disabled",!!t).attr("aria-disabled",t),this.hoverable.removeClass("ui-state-hover"),this.focusable.removeClass("ui-state-focus")),this},enable:function(){return this._setOption("disabled",!1)},disable:function(){return this._setOption("disabled",!0)},_on:function(i,s,n){var a,r=this;"boolean"!=typeof i&&(n=s,s=i,i=!1),n?(s=a=e(s),this.bindings=this.bindings.add(s)):(n=s,s=this.element,a=this.widget()),e.each(n,function(n,o){function h(){return i||r.options.disabled!==!0&&!e(this).hasClass("ui-state-disabled")?("string"==typeof o?r[o]:o).apply(r,arguments):t}"string"!=typeof o&&(h.guid=o.guid=o.guid||h.guid||e.guid++);var l=n.match(/^(\w+)\s*(.*)$/),u=l[1]+r.eventNamespace,c=l[2];c?a.delegate(c,u,h):s.bind(u,h)})},_off:function(e,t){t=(t||"").split(" ").join(this.eventNamespace+" ")+this.eventNamespace,e.unbind(t).undelegate(t)},_delay:function(e,t){function i(){return("string"==typeof e?s[e]:e).apply(s,arguments)}var s=this;return setTimeout(i,t||0)},_hoverable:function(t){this.hoverable=this.hoverable.add(t),this._on(t,{mouseenter:function(t){e(t.currentTarget).addClass("ui-state-hover")},mouseleave:function(t){e(t.currentTarget).removeClass("ui-state-hover")}})},_focusable:function(t){this.focusable=this.focusable.add(t),this._on(t,{focusin:function(t){e(t.currentTarget).addClass("ui-state-focus")},focusout:function(t){e(t.currentTarget).removeClass("ui-state-focus")}})},_trigger:function(t,i,s){var n,a,r=this.options[t];if(s=s||{},i=e.Event(i),i.type=(t===this.widgetEventPrefix?t:this.widgetEventPrefix+t).toLowerCase(),i.target=this.element[0],a=i.originalEvent)for(n in a)n in i||(i[n]=a[n]);return this.element.trigger(i,s),!(e.isFunction(r)&&r.apply(this.element[0],[i].concat(s))===!1||i.isDefaultPrevented())}},e.each({show:"fadeIn",hide:"fadeOut"},function(t,i){e.Widget.prototype["_"+t]=function(s,n,a){"string"==typeof n&&(n={effect:n});var r,o=n?n===!0||"number"==typeof n?i:n.effect||i:t;n=n||{},"number"==typeof n&&(n={duration:n}),r=!e.isEmptyObject(n),n.complete=a,n.delay&&s.delay(n.delay),r&&e.effects&&e.effects.effect[o]?s[t](n):o!==t&&s[o]?s[o](n.duration,n.easing,a):s.queue(function(i){e(this)[t](),a&&a.call(s[0]),i()})}})})(jQuery);(function(e){var t=!1;e(document).mouseup(function(){t=!1}),e.widget("ui.mouse",{version:"1.10.3",options:{cancel:"input,textarea,button,select,option",distance:1,delay:0},_mouseInit:function(){var t=this;this.element.bind("mousedown."+this.widgetName,function(e){return t._mouseDown(e)}).bind("click."+this.widgetName,function(i){return!0===e.data(i.target,t.widgetName+".preventClickEvent")?(e.removeData(i.target,t.widgetName+".preventClickEvent"),i.stopImmediatePropagation(),!1):undefined}),this.started=!1},_mouseDestroy:function(){this.element.unbind("."+this.widgetName),this._mouseMoveDelegate&&e(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate)},_mouseDown:function(i){if(!t){this._mouseStarted&&this._mouseUp(i),this._mouseDownEvent=i;var s=this,n=1===i.which,a="string"==typeof this.options.cancel&&i.target.nodeName?e(i.target).closest(this.options.cancel).length:!1;return n&&!a&&this._mouseCapture(i)?(this.mouseDelayMet=!this.options.delay,this.mouseDelayMet||(this._mouseDelayTimer=setTimeout(function(){s.mouseDelayMet=!0},this.options.delay)),this._mouseDistanceMet(i)&&this._mouseDelayMet(i)&&(this._mouseStarted=this._mouseStart(i)!==!1,!this._mouseStarted)?(i.preventDefault(),!0):(!0===e.data(i.target,this.widgetName+".preventClickEvent")&&e.removeData(i.target,this.widgetName+".preventClickEvent"),this._mouseMoveDelegate=function(e){return s._mouseMove(e)},this._mouseUpDelegate=function(e){return s._mouseUp(e)},e(document).bind("mousemove."+this.widgetName,this._mouseMoveDelegate).bind("mouseup."+this.widgetName,this._mouseUpDelegate),i.preventDefault(),t=!0,!0)):!0}},_mouseMove:function(t){return e.ui.ie&&(!document.documentMode||9>document.documentMode)&&!t.button?this._mouseUp(t):this._mouseStarted?(this._mouseDrag(t),t.preventDefault()):(this._mouseDistanceMet(t)&&this._mouseDelayMet(t)&&(this._mouseStarted=this._mouseStart(this._mouseDownEvent,t)!==!1,this._mouseStarted?this._mouseDrag(t):this._mouseUp(t)),!this._mouseStarted)},_mouseUp:function(t){return e(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate),this._mouseStarted&&(this._mouseStarted=!1,t.target===this._mouseDownEvent.target&&e.data(t.target,this.widgetName+".preventClickEvent",!0),this._mouseStop(t)),!1},_mouseDistanceMet:function(e){return Math.max(Math.abs(this._mouseDownEvent.pageX-e.pageX),Math.abs(this._mouseDownEvent.pageY-e.pageY))>=this.options.distance},_mouseDelayMet:function(){return this.mouseDelayMet},_mouseStart:function(){},_mouseDrag:function(){},_mouseStop:function(){},_mouseCapture:function(){return!0}})})(jQuery);(function(e){e.widget("ui.draggable",e.ui.mouse,{version:"1.10.3",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,drag:null,start:null,stop:null},_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(){this.element.removeClass("ui-draggable ui-draggable-dragging ui-draggable-disabled"),this._mouseDestroy()},_mouseCapture:function(t){var i=this.options;return this.helper||i.disabled||e(t.target).closest(".ui-resizable-handle").length>0?!1:(this.handle=this._getHandle(t),this.handle?(e(i.iframeFix===!0?"iframe":i.iframeFix).each(function(){e("<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(e(this).offset()).appendTo("body")}),!0):!1)},_mouseStart:function(t){var i=this.options;return this.helper=this._createHelper(t),this.helper.addClass("ui-draggable-dragging"),this._cacheHelperProportions(),e.ui.ddmanager&&(e.ui.ddmanager.current=this),this._cacheMargins(),this.cssPosition=this.helper.css("position"),this.scrollParent=this.helper.scrollParent(),this.offsetParent=this.helper.offsetParent(),this.offsetParentCssPosition=this.offsetParent.css("position"),this.offset=this.positionAbs=this.element.offset(),this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left},this.offset.scroll=!1,e.extend(this.offset,{click:{left:t.pageX-this.offset.left,top:t.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()}),this.originalPosition=this.position=this._generatePosition(t),this.originalPageX=t.pageX,this.originalPageY=t.pageY,i.cursorAt&&this._adjustOffsetFromHelper(i.cursorAt),this._setContainment(),this._trigger("start",t)===!1?(this._clear(),!1):(this._cacheHelperProportions(),e.ui.ddmanager&&!i.dropBehaviour&&e.ui.ddmanager.prepareOffsets(this,t),this._mouseDrag(t,!0),e.ui.ddmanager&&e.ui.ddmanager.dragStart(this,t),!0)},_mouseDrag:function(t,i){if("fixed"===this.offsetParentCssPosition&&(this.offset.parent=this._getParentOffset()),this.position=this._generatePosition(t),this.positionAbs=this._convertPositionTo("absolute"),!i){var s=this._uiHash();if(this._trigger("drag",t,s)===!1)return this._mouseUp({}),!1;this.position=s.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"),e.ui.ddmanager&&e.ui.ddmanager.drag(this,t),!1},_mouseStop:function(t){var i=this,s=!1;return e.ui.ddmanager&&!this.options.dropBehaviour&&(s=e.ui.ddmanager.drop(this,t)),this.dropped&&(s=this.dropped,this.dropped=!1),"original"!==this.options.helper||e.contains(this.element[0].ownerDocument,this.element[0])?("invalid"===this.options.revert&&!s||"valid"===this.options.revert&&s||this.options.revert===!0||e.isFunction(this.options.revert)&&this.options.revert.call(this.element,s)?e(this.helper).animate(this.originalPosition,parseInt(this.options.revertDuration,10),function(){i._trigger("stop",t)!==!1&&i._clear()}):this._trigger("stop",t)!==!1&&this._clear(),!1):!1},_mouseUp:function(t){return e("div.ui-draggable-iframeFix").each(function(){this.parentNode.removeChild(this)}),e.ui.ddmanager&&e.ui.ddmanager.dragStop(this,t),e.ui.mouse.prototype._mouseUp.call(this,t)},cancel:function(){return this.helper.is(".ui-draggable-dragging")?this._mouseUp({}):this._clear(),this},_getHandle:function(t){return this.options.handle?!!e(t.target).closest(this.element.find(this.options.handle)).length:!0},_createHelper:function(t){var i=this.options,s=e.isFunction(i.helper)?e(i.helper.apply(this.element[0],[t])):"clone"===i.helper?this.element.clone().removeAttr("id"):this.element;return s.parents("body").length||s.appendTo("parent"===i.appendTo?this.element[0].parentNode:i.appendTo),s[0]===this.element[0]||/(fixed|absolute)/.test(s.css("position"))||s.css("position","absolute"),s},_adjustOffsetFromHelper:function(t){"string"==typeof t&&(t=t.split(" ")),e.isArray(t)&&(t={left:+t[0],top:+t[1]||0}),"left"in t&&(this.offset.click.left=t.left+this.margins.left),"right"in t&&(this.offset.click.left=this.helperProportions.width-t.right+this.margins.left),"top"in t&&(this.offset.click.top=t.top+this.margins.top),"bottom"in t&&(this.offset.click.top=this.helperProportions.height-t.bottom+this.margins.top)},_getParentOffset:function(){var t=this.offsetParent.offset();return"absolute"===this.cssPosition&&this.scrollParent[0]!==document&&e.contains(this.scrollParent[0],this.offsetParent[0])&&(t.left+=this.scrollParent.scrollLeft(),t.top+=this.scrollParent.scrollTop()),(this.offsetParent[0]===document.body||this.offsetParent[0].tagName&&"html"===this.offsetParent[0].tagName.toLowerCase()&&e.ui.ie)&&(t={top:0,left:0}),{top:t.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:t.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if("relative"===this.cssPosition){var e=this.element.position();return{top:e.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:e.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 t,i,s,n=this.options;return n.containment?"window"===n.containment?(this.containment=[e(window).scrollLeft()-this.offset.relative.left-this.offset.parent.left,e(window).scrollTop()-this.offset.relative.top-this.offset.parent.top,e(window).scrollLeft()+e(window).width()-this.helperProportions.width-this.margins.left,e(window).scrollTop()+(e(window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top],undefined):"document"===n.containment?(this.containment=[0,0,e(document).width()-this.helperProportions.width-this.margins.left,(e(document).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top],undefined):n.containment.constructor===Array?(this.containment=n.containment,undefined):("parent"===n.containment&&(n.containment=this.helper[0].parentNode),i=e(n.containment),s=i[0],s&&(t="hidden"!==i.css("overflow"),this.containment=[(parseInt(i.css("borderLeftWidth"),10)||0)+(parseInt(i.css("paddingLeft"),10)||0),(parseInt(i.css("borderTopWidth"),10)||0)+(parseInt(i.css("paddingTop"),10)||0),(t?Math.max(s.scrollWidth,s.offsetWidth):s.offsetWidth)-(parseInt(i.css("borderRightWidth"),10)||0)-(parseInt(i.css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left-this.margins.right,(t?Math.max(s.scrollHeight,s.offsetHeight):s.offsetHeight)-(parseInt(i.css("borderBottomWidth"),10)||0)-(parseInt(i.css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top-this.margins.bottom],this.relative_container=i),undefined):(this.containment=null,undefined)},_convertPositionTo:function(t,i){i||(i=this.position);var s="absolute"===t?1:-1,n="absolute"!==this.cssPosition||this.scrollParent[0]!==document&&e.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent;return this.offset.scroll||(this.offset.scroll={top:n.scrollTop(),left:n.scrollLeft()}),{top:i.top+this.offset.relative.top*s+this.offset.parent.top*s-("fixed"===this.cssPosition?-this.scrollParent.scrollTop():this.offset.scroll.top)*s,left:i.left+this.offset.relative.left*s+this.offset.parent.left*s-("fixed"===this.cssPosition?-this.scrollParent.scrollLeft():this.offset.scroll.left)*s}},_generatePosition:function(t){var i,s,n,a,o=this.options,r="absolute"!==this.cssPosition||this.scrollParent[0]!==document&&e.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,h=t.pageX,l=t.pageY;return this.offset.scroll||(this.offset.scroll={top:r.scrollTop(),left:r.scrollLeft()}),this.originalPosition&&(this.containment&&(this.relative_container?(s=this.relative_container.offset(),i=[this.containment[0]+s.left,this.containment[1]+s.top,this.containment[2]+s.left,this.containment[3]+s.top]):i=this.containment,t.pageX-this.offset.click.left<i[0]&&(h=i[0]+this.offset.click.left),t.pageY-this.offset.click.top<i[1]&&(l=i[1]+this.offset.click.top),t.pageX-this.offset.click.left>i[2]&&(h=i[2]+this.offset.click.left),t.pageY-this.offset.click.top>i[3]&&(l=i[3]+this.offset.click.top)),o.grid&&(n=o.grid[1]?this.originalPageY+Math.round((l-this.originalPageY)/o.grid[1])*o.grid[1]:this.originalPageY,l=i?n-this.offset.click.top>=i[1]||n-this.offset.click.top>i[3]?n:n-this.offset.click.top>=i[1]?n-o.grid[1]:n+o.grid[1]:n,a=o.grid[0]?this.originalPageX+Math.round((h-this.originalPageX)/o.grid[0])*o.grid[0]:this.originalPageX,h=i?a-this.offset.click.left>=i[0]||a-this.offset.click.left>i[2]?a:a-this.offset.click.left>=i[0]?a-o.grid[0]:a+o.grid[0]:a)),{top:l-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+("fixed"===this.cssPosition?-this.scrollParent.scrollTop():this.offset.scroll.top),left:h-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+("fixed"===this.cssPosition?-this.scrollParent.scrollLeft():this.offset.scroll.left)}},_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(t,i,s){return s=s||this._uiHash(),e.ui.plugin.call(this,t,[i,s]),"drag"===t&&(this.positionAbs=this._convertPositionTo("absolute")),e.Widget.prototype._trigger.call(this,t,i,s)},plugins:{},_uiHash:function(){return{helper:this.helper,position:this.position,originalPosition:this.originalPosition,offset:this.positionAbs}}}),e.ui.plugin.add("draggable","connectToSortable",{start:function(t,i){var s=e(this).data("ui-draggable"),n=s.options,a=e.extend({},i,{item:s.element});s.sortables=[],e(n.connectToSortable).each(function(){var i=e.data(this,"ui-sortable");i&&!i.options.disabled&&(s.sortables.push({instance:i,shouldRevert:i.options.revert}),i.refreshPositions(),i._trigger("activate",t,a))})},stop:function(t,i){var s=e(this).data("ui-draggable"),n=e.extend({},i,{item:s.element});e.each(s.sortables,function(){this.instance.isOver?(this.instance.isOver=0,s.cancelHelperRemoval=!0,this.instance.cancelHelperRemoval=!1,this.shouldRevert&&(this.instance.options.revert=this.shouldRevert),this.instance._mouseStop(t),this.instance.options.helper=this.instance.options._helper,"original"===s.options.helper&&this.instance.currentItem.css({top:"auto",left:"auto"})):(this.instance.cancelHelperRemoval=!1,this.instance._trigger("deactivate",t,n))})},drag:function(t,i){var s=e(this).data("ui-draggable"),n=this;e.each(s.sortables,function(){var a=!1,o=this;this.instance.positionAbs=s.positionAbs,this.instance.helperProportions=s.helperProportions,this.instance.offset.click=s.offset.click,this.instance._intersectsWith(this.instance.containerCache)&&(a=!0,e.each(s.sortables,function(){return this.instance.positionAbs=s.positionAbs,this.instance.helperProportions=s.helperProportions,this.instance.offset.click=s.offset.click,this!==o&&this.instance._intersectsWith(this.instance.containerCache)&&e.contains(o.instance.element[0],this.instance.element[0])&&(a=!1),a})),a?(this.instance.isOver||(this.instance.isOver=1,this.instance.currentItem=e(n).clone().removeAttr("id").appendTo(this.instance.element).data("ui-sortable-item",!0),this.instance.options._helper=this.instance.options.helper,this.instance.options.helper=function(){return i.helper[0]},t.target=this.instance.currentItem[0],this.instance._mouseCapture(t,!0),this.instance._mouseStart(t,!0,!0),this.instance.offset.click.top=s.offset.click.top,this.instance.offset.click.left=s.offset.click.left,this.instance.offset.parent.left-=s.offset.parent.left-this.instance.offset.parent.left,this.instance.offset.parent.top-=s.offset.parent.top-this.instance.offset.parent.top,s._trigger("toSortable",t),s.dropped=this.instance.element,s.currentItem=s.element,this.instance.fromOutside=s),this.instance.currentItem&&this.instance._mouseDrag(t)):this.instance.isOver&&(this.instance.isOver=0,this.instance.cancelHelperRemoval=!0,this.instance.options.revert=!1,this.instance._trigger("out",t,this.instance._uiHash(this.instance)),this.instance._mouseStop(t,!0),this.instance.options.helper=this.instance.options._helper,this.instance.currentItem.remove(),this.instance.placeholder&&this.instance.placeholder.remove(),s._trigger("fromSortable",t),s.dropped=!1)})}}),e.ui.plugin.add("draggable","cursor",{start:function(){var t=e("body"),i=e(this).data("ui-draggable").options;t.css("cursor")&&(i._cursor=t.css("cursor")),t.css("cursor",i.cursor)},stop:function(){var t=e(this).data("ui-draggable").options;t._cursor&&e("body").css("cursor",t._cursor)}}),e.ui.plugin.add("draggable","opacity",{start:function(t,i){var s=e(i.helper),n=e(this).data("ui-draggable").options;s.css("opacity")&&(n._opacity=s.css("opacity")),s.css("opacity",n.opacity)},stop:function(t,i){var s=e(this).data("ui-draggable").options;s._opacity&&e(i.helper).css("opacity",s._opacity)}}),e.ui.plugin.add("draggable","scroll",{start:function(){var t=e(this).data("ui-draggable");t.scrollParent[0]!==document&&"HTML"!==t.scrollParent[0].tagName&&(t.overflowOffset=t.scrollParent.offset())},drag:function(t){var i=e(this).data("ui-draggable"),s=i.options,n=!1;i.scrollParent[0]!==document&&"HTML"!==i.scrollParent[0].tagName?(s.axis&&"x"===s.axis||(i.overflowOffset.top+i.scrollParent[0].offsetHeight-t.pageY<s.scrollSensitivity?i.scrollParent[0].scrollTop=n=i.scrollParent[0].scrollTop+s.scrollSpeed:t.pageY-i.overflowOffset.top<s.scrollSensitivity&&(i.scrollParent[0].scrollTop=n=i.scrollParent[0].scrollTop-s.scrollSpeed)),s.axis&&"y"===s.axis||(i.overflowOffset.left+i.scrollParent[0].offsetWidth-t.pageX<s.scrollSensitivity?i.scrollParent[0].scrollLeft=n=i.scrollParent[0].scrollLeft+s.scrollSpeed:t.pageX-i.overflowOffset.left<s.scrollSensitivity&&(i.scrollParent[0].scrollLeft=n=i.scrollParent[0].scrollLeft-s.scrollSpeed))):(s.axis&&"x"===s.axis||(t.pageY-e(document).scrollTop()<s.scrollSensitivity?n=e(document).scrollTop(e(document).scrollTop()-s.scrollSpeed):e(window).height()-(t.pageY-e(document).scrollTop())<s.scrollSensitivity&&(n=e(document).scrollTop(e(document).scrollTop()+s.scrollSpeed))),s.axis&&"y"===s.axis||(t.pageX-e(document).scrollLeft()<s.scrollSensitivity?n=e(document).scrollLeft(e(document).scrollLeft()-s.scrollSpeed):e(window).width()-(t.pageX-e(document).scrollLeft())<s.scrollSensitivity&&(n=e(document).scrollLeft(e(document).scrollLeft()+s.scrollSpeed)))),n!==!1&&e.ui.ddmanager&&!s.dropBehaviour&&e.ui.ddmanager.prepareOffsets(i,t)}}),e.ui.plugin.add("draggable","snap",{start:function(){var t=e(this).data("ui-draggable"),i=t.options;t.snapElements=[],e(i.snap.constructor!==String?i.snap.items||":data(ui-draggable)":i.snap).each(function(){var i=e(this),s=i.offset();this!==t.element[0]&&t.snapElements.push({item:this,width:i.outerWidth(),height:i.outerHeight(),top:s.top,left:s.left})})},drag:function(t,i){var s,n,a,o,r,h,l,u,c,d,p=e(this).data("ui-draggable"),f=p.options,m=f.snapTolerance,g=i.offset.left,v=g+p.helperProportions.width,b=i.offset.top,y=b+p.helperProportions.height;for(c=p.snapElements.length-1;c>=0;c--)r=p.snapElements[c].left,h=r+p.snapElements[c].width,l=p.snapElements[c].top,u=l+p.snapElements[c].height,r-m>v||g>h+m||l-m>y||b>u+m||!e.contains(p.snapElements[c].item.ownerDocument,p.snapElements[c].item)?(p.snapElements[c].snapping&&p.options.snap.release&&p.options.snap.release.call(p.element,t,e.extend(p._uiHash(),{snapItem:p.snapElements[c].item})),p.snapElements[c].snapping=!1):("inner"!==f.snapMode&&(s=m>=Math.abs(l-y),n=m>=Math.abs(u-b),a=m>=Math.abs(r-v),o=m>=Math.abs(h-g),s&&(i.position.top=p._convertPositionTo("relative",{top:l-p.helperProportions.height,left:0}).top-p.margins.top),n&&(i.position.top=p._convertPositionTo("relative",{top:u,left:0}).top-p.margins.top),a&&(i.position.left=p._convertPositionTo("relative",{top:0,left:r-p.helperProportions.width}).left-p.margins.left),o&&(i.position.left=p._convertPositionTo("relative",{top:0,left:h}).left-p.margins.left)),d=s||n||a||o,"outer"!==f.snapMode&&(s=m>=Math.abs(l-b),n=m>=Math.abs(u-y),a=m>=Math.abs(r-g),o=m>=Math.abs(h-v),s&&(i.position.top=p._convertPositionTo("relative",{top:l,left:0}).top-p.margins.top),n&&(i.position.top=p._convertPositionTo("relative",{top:u-p.helperProportions.height,left:0}).top-p.margins.top),a&&(i.position.left=p._convertPositionTo("relative",{top:0,left:r}).left-p.margins.left),o&&(i.position.left=p._convertPositionTo("relative",{top:0,left:h-p.helperProportions.width}).left-p.margins.left)),!p.snapElements[c].snapping&&(s||n||a||o||d)&&p.options.snap.snap&&p.options.snap.snap.call(p.element,t,e.extend(p._uiHash(),{snapItem:p.snapElements[c].item})),p.snapElements[c].snapping=s||n||a||o||d)}}),e.ui.plugin.add("draggable","stack",{start:function(){var t,i=this.data("ui-draggable").options,s=e.makeArray(e(i.stack)).sort(function(t,i){return(parseInt(e(t).css("zIndex"),10)||0)-(parseInt(e(i).css("zIndex"),10)||0)});s.length&&(t=parseInt(e(s[0]).css("zIndex"),10)||0,e(s).each(function(i){e(this).css("zIndex",t+i)}),this.css("zIndex",t+s.length))}}),e.ui.plugin.add("draggable","zIndex",{start:function(t,i){var s=e(i.helper),n=e(this).data("ui-draggable").options;s.css("zIndex")&&(n._zIndex=s.css("zIndex")),s.css("zIndex",n.zIndex)},stop:function(t,i){var s=e(this).data("ui-draggable").options;s._zIndex&&e(i.helper).css("zIndex",s._zIndex)}})})(jQuery); // # Ghost jQuery Utils /*global window, document, $ */ (function () { "use strict"; // ## UTILS /** * Allows to check contents of each element exactly * @param obj * @param index * @param meta * @param stack * @returns {boolean} */ $.expr[":"].containsExact = function (obj, index, meta, stack) { return (obj.textContent || obj.innerText || $(obj).text() || "") === meta[3]; }; /** * Center an element to the window vertically and centrally * @returns {*} */ $.fn.center = function (options) { var $window = $(window), config = $.extend({ animate : true, successTrigger : 'centered' }, options); return this.each(function () { var $this = $(this); $this.css({ 'position': 'absolute' }); if (config.animate) { $this.animate({ 'left': ($window.width() / 2) - $this.outerWidth() / 2 + 'px', 'top': ($window.height() / 2) - $this.outerHeight() / 2 + 'px' }); } else { $this.css({ 'left': ($window.width() / 2) - $this.outerWidth() / 2 + 'px', 'top': ($window.height() / 2) - $this.outerHeight() / 2 + 'px' }); } $(window).trigger(config.successTrigger); }); }; // ## getTransformProperty // This returns the transition duration for an element, good for calling things after a transition has finished. // **Original**: [https://gist.github.com/mandelbro/4067903](https://gist.github.com/mandelbro/4067903) // **returns:** the elements transition duration $.fn.transitionDuration = function () { var $this = $(this); // check the main transition duration property if ($this.css('transition-duration')) { return Math.round(parseFloat(this.css('transition-duration')) * 1000); } // check the vendor transition duration properties if (this.css('-webkit-transtion-duration')) { return Math.round(parseFloat(this.css('-webkit-transtion-duration')) * 1000); } if (this.css('-ms-transtion-duration')) { return Math.round(parseFloat(this.css('-ms-transtion-duration')) * 1000); } if (this.css('-moz-transtion-duration')) { return Math.round(parseFloat(this.css('-moz-transtion-duration')) * 1000); } if (this.css('-o-transtion-duration')) { return Math.round(parseFloat(this.css('-o-transtion-duration')) * 1000); } // if we're here, then no transition duration was found, return 0 return 0; }; // ## scrollShadow // This adds a 'scroll' class to the targeted element when the element is scrolled // **target:** The element in which the class is applied. Defaults to scrolled element. // **class-name:** The class which is applied. // **offset:** How far the user has to scroll before the class is applied. $.fn.scrollClass = function (options) { var config = $.extend({ 'target' : '', 'class-name' : 'scrolling', 'offset' : 1 }, options); return this.each(function () { var $this = $(this), $target = $this; if (config.target) { $target = $(config.target); } $this.scroll(function () { if ($this.scrollTop() > config.offset) { $target.addClass(config['class-name']); } else { $target.removeClass(config['class-name']); } }); }); }; $.fn.selectText = function () { var elem = this[0], range, selection; if (document.body.createTextRange) { range = document.body.createTextRange(); range.moveToElementText(elem); range.select(); } else if (window.getSelection) { selection = window.getSelection(); range = document.createRange(); range.selectNodeContents(elem); selection.removeAllRanges(); selection.addRange(range); } }; /** * Set interactions for all menus and overlays * This finds all visible 'hideClass' elements and hides them upon clicking away from the element itself. * A callback can be defined to customise the results. By default it will hide the element. * @param callback */ $.fn.hideAway = function (callback) { var $self = $(this); $("body").on('click', function (event) { var $target = $(event.target), hideClass = $self.selector; if (!$target.parents().is(hideClass + ":visible") && !$target.is(hideClass + ":visible")) { if (callback) { callback($("body").find(hideClass + ":visible")); } else { $("body").find(hideClass + ":visible").fadeOut(); // Toggle active classes on menu headers $("[data-toggle].active").removeClass("active"); } } }); return this; }; // ## GLOBALS $('.overlay').hideAway(); /** * Adds appropriate inflection for pluralizing the singular form of a word when appropriate. * This is an overly simplistic implementation that does not handle irregular plurals. * @param {Number} count * @param {String} singularWord * @returns {String} */ $.pluralize = function inflect(count, singularWord) { var base = [count, ' ', singularWord]; return (count === 1) ? base.join('') : base.concat('s').join(''); }; }()); /*global jQuery, Ghost, document, Image, window */ (function ($) { "use strict"; var UploadUi; UploadUi = function ($dropzone, settings) { var source, $url = '<div class="js-url"><input class="url js-upload-url" type="url" placeholder="http://"/></div>', $cancel = '<a class="image-cancel js-cancel"><span class="hidden">Delete</span></a>', $progress = $('<div />', { "class" : "js-upload-progress progress progress-success active", "role": "progressbar", "aria-valuemin": "0", "aria-valuemax": "100" }).append($("<div />", { "class": "js-upload-progress-bar bar", "style": "width:0%" })); $.extend(this, { complete: function (result) { var self = this; function showImage(width, height) { $dropzone.find('img.js-upload-target').attr({"width": width, "height": height}).css({"display": "block"}); $dropzone.find('.fileupload-loading').remove(); $dropzone.css({"height": "auto"}); $dropzone.delay(250).animate({opacity: 100}, 1000, function () { self.init(); }); } function animateDropzone($img) { $dropzone.animate({opacity: 0}, 250, function () { $dropzone.removeClass('image-uploader').addClass('pre-image-uploader'); $dropzone.css({minHeight: 0}); self.removeExtras(); $dropzone.animate({height: $img.height()}, 250, function () { showImage($img.width(), $img.height()); }); }); } function preLoadImage() { var $img = $dropzone.find('img.js-upload-target') .attr({'src': '', "width": 'auto', "height": 'auto'}); $progress.animate({"opacity": 0}, 250, function () { $dropzone.find('span.media').after('<img class="fileupload-loading" src="/ghost/img/loadingcat.gif" />'); if (!settings.editor) {$progress.find('.fileupload-loading').css({"top": "56px"}); } }); $dropzone.trigger("uploadsuccess", [result]); $img.one('load', function () { animateDropzone($img); }).attr('src', result); } preLoadImage(); }, bindFileUpload: function () { var self = this; $dropzone.find('.js-fileupload').fileupload().fileupload("option", { url: '/ghost/upload/', headers: { 'X-CSRF-Token': $("meta[name='csrf-param']").attr('content') }, add: function (e, data) { $dropzone.find('.js-fileupload').removeClass('right'); $dropzone.find('.js-url, button.centre').remove(); $progress.find('.js-upload-progress-bar').removeClass('fail'); $dropzone.trigger('uploadstart', [$dropzone.attr('id')]); $dropzone.find('span.media, div.description, a.image-url, a.image-webcam') .animate({opacity: 0}, 250, function () { $dropzone.find('div.description').hide().css({"opacity": 100}); if (settings.progressbar) { $dropzone.find('div.js-fail').after($progress); $progress.animate({opacity: 100}, 250); } data.submit(); }); }, dropZone: $dropzone, progressall: function (e, data) { var progress = parseInt(data.loaded / data.total * 100, 10); if (!settings.editor) {$progress.find('div.js-progress').css({"position": "absolute", "top": "40px"}); } if (settings.progressbar) { $dropzone.trigger("uploadprogress", [progress, data]); $progress.find('.js-upload-progress-bar').css('width', progress + '%'); } }, fail: function (e, data) { $dropzone.trigger("uploadfailure", [data.result]); $dropzone.find('.js-upload-progress-bar').addClass('fail'); $dropzone.find('div.js-fail, button.js-fail').fadeIn(1500); $dropzone.find('button.js-fail').on('click', function () { $dropzone.css({minHeight: 0}); $dropzone.find('div.description').show(); self.removeExtras(); self.init(); }); }, done: function (e, data) { self.complete(data.result); } }); }, buildExtras: function () { if (!$dropzone.find('span.media')[0]) { $dropzone.prepend('<span class="media"><span class="hidden">Image Upload</span></span>'); } if (!$dropzone.find('div.description')[0]) { $dropzone.append('<div class="description">Add image</div>'); } if (!$dropzone.find('div.js-fail')[0]) { $dropzone.append('<div class="js-fail failed" style="display: none">Something went wrong :(</div>'); } if (!$dropzone.find('button.js-fail')[0]) { $dropzone.append('<button class="js-fail button-add" style="display: none">Try Again</button>'); } if (!$dropzone.find('a.image-url')[0]) { $dropzone.append('<a class="image-url" title="Add image from URL"><span class="hidden">URL</span></a>'); } // if (!$dropzone.find('a.image-webcam')[0]) { // $dropzone.append('<a class="image-webcam" title="Add image from webcam"><span class="hidden">Webcam</span></a>'); // } }, removeExtras: function () { $dropzone.find('span.media, div.js-upload-progress, a.image-url, a.image-webcam, div.js-fail, button.js-fail, a.js-cancel').remove(); }, initWithDropzone: function () { var self = this; //This is the start point if no image exists $dropzone.find('img.js-upload-target').css({"display": "none"}); $dropzone.removeClass('pre-image-uploader image-uploader-url').addClass('image-uploader'); this.removeExtras(); this.buildExtras(); this.bindFileUpload(); $dropzone.find('a.image-url').on('click', function () { self.initUrl(); }); }, initUrl: function () { var self = this, val; this.removeExtras(); $dropzone.addClass('image-uploader-url').removeClass('pre-image-uploader'); $dropzone.find('.js-fileupload').addClass('right'); $dropzone.append($cancel); $dropzone.find('.js-cancel').on('click', function () { $dropzone.find('.js-url').remove(); $dropzone.find('.js-fileupload').removeClass('right'); $dropzone.find('button.centre').remove(); self.removeExtras(); self.initWithDropzone(); }); if (settings.editor) { $dropzone.find('div.description').after('<button class="js-button-accept button-save centre">Save</button>'); } $dropzone.find('div.description').before($url); $dropzone.find('.js-button-accept').on('click', function () { val = $dropzone.find('.js-upload-url').val(); $dropzone.find('div.description').hide(); $dropzone.find('.js-fileupload').removeClass('right'); $dropzone.find('.js-url').remove(); $dropzone.find('button.centre').remove(); if (val === "") { $dropzone.trigger("uploadsuccess", 'http://'); self.initWithDropzone(); } else { self.complete(val); } }); }, initWithImage: function () { var self = this, val; // This is the start point if an image already exists source = $dropzone.find('img.js-upload-target').attr('src'); $dropzone.removeClass('image-uploader image-uploader-url').addClass('pre-image-uploader'); $dropzone.find('div.description').hide(); $dropzone.append($cancel); $dropzone.find('.js-cancel').on('click', function () { $dropzone.find('img.js-upload-target').attr({'src': ''}); $dropzone.find('div.description').show(); $dropzone.delay(2500).animate({opacity: 100}, 1000, function () { self.init(); }); $dropzone.trigger("uploadsuccess", 'http://'); self.initWithDropzone(); }); }, init: function () { // First check if field image is defined by checking for js-upload-target class if (!$dropzone.find('img.js-upload-target')[0]) { // This ensures there is an image we can hook into to display uploaded image $dropzone.prepend('<img class="js-upload-target" style="display: none" src="" />'); } if ($dropzone.find('img.js-upload-target').attr('src') === '') { this.initWithDropzone(); } else { this.initWithImage(); } } }); }; $.fn.upload = function (options) { var settings = $.extend({ progressbar: true, editor: false }, options); return this.each(function () { var $dropzone = $(this), ui; ui = new UploadUi($dropzone, settings); ui.init(); }); }; }(jQuery)); // Underscore.js 1.5.2 // http://underscorejs.org // (c) 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors // Underscore may be freely distributed under the MIT license. (function() { // Baseline setup // -------------- // Establish the root object, `window` in the browser, or `exports` on the server. var root = this; // Save the previous value of the `_` variable. var previousUnderscore = root._; // Establish the object that gets returned to break out of a loop iteration. var breaker = {}; // Save bytes in the minified (but not gzipped) version: var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype; // Create quick reference variables for speed access to core prototypes. var push = ArrayProto.push, slice = ArrayProto.slice, concat = ArrayProto.concat, toString = ObjProto.toString, hasOwnProperty = ObjProto.hasOwnProperty; // All **ECMAScript 5** native function implementations that we hope to use // are declared here. var nativeForEach = ArrayProto.forEach, nativeMap = ArrayProto.map, nativeReduce = ArrayProto.reduce, nativeReduceRight = ArrayProto.reduceRight, nativeFilter = ArrayProto.filter, nativeEvery = ArrayProto.every, nativeSome = ArrayProto.some, nativeIndexOf = ArrayProto.indexOf, nativeLastIndexOf = ArrayProto.lastIndexOf, nativeIsArray = Array.isArray, nativeKeys = Object.keys, nativeBind = FuncProto.bind; // Create a safe reference to the Underscore object for use below. var _ = function(obj) { if (obj instanceof _) return obj; if (!(this instanceof _)) return new _(obj); this._wrapped = obj; }; // Export the Underscore object for **Node.js**, with // backwards-compatibility for the old `require()` API. If we're in // the browser, add `_` as a global object via a string identifier, // for Closure Compiler "advanced" mode. if (typeof exports !== 'undefined') { if (typeof module !== 'undefined' && module.exports) { exports = module.exports = _; } exports._ = _; } else { root._ = _; } // Current version. _.VERSION = '1.5.2'; // Collection Functions // -------------------- // The cornerstone, an `each` implementation, aka `forEach`. // Handles objects with the built-in `forEach`, arrays, and raw objects. // Delegates to **ECMAScript 5**'s native `forEach` if available. var each = _.each = _.forEach = function(obj, iterator, context) { if (obj == null) return; if (nativeForEach && obj.forEach === nativeForEach) { obj.forEach(iterator, context); } else if (obj.length === +obj.length) { for (var i = 0, length = obj.length; i < length; i++) { if (iterator.call(context, obj[i], i, obj) === breaker) return; } } else { var keys = _.keys(obj); for (var i = 0, length = keys.length; i < length; i++) { if (iterator.call(context, obj[keys[i]], keys[i], obj) === breaker) return; } } }; // Return the results of applying the iterator to each element. // Delegates to **ECMAScript 5**'s native `map` if available. _.map = _.collect = function(obj, iterator, context) { var results = []; if (obj == null) return results; if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context); each(obj, function(value, index, list) { results.push(iterator.call(context, value, index, list)); }); return results; }; var reduceError = 'Reduce of empty array with no initial value'; // **Reduce** builds up a single result from a list of values, aka `inject`, // or `foldl`. Delegates to **ECMAScript 5**'s native `reduce` if available. _.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) { var initial = arguments.length > 2; if (obj == null) obj = []; if (nativeReduce && obj.reduce === nativeReduce) { if (context) iterator = _.bind(iterator, context); return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator); } each(obj, function(value, index, list) { if (!initial) { memo = value; initial = true; } else { memo = iterator.call(context, memo, value, index, list); } }); if (!initial) throw new TypeError(reduceError); return memo; }; // The right-associative version of reduce, also known as `foldr`. // Delegates to **ECMAScript 5**'s native `reduceRight` if available. _.reduceRight = _.foldr = function(obj, iterator, memo, context) { var initial = arguments.length > 2; if (obj == null) obj = []; if (nativeReduceRight && obj.reduceRight === nativeReduceRight) { if (context) iterator = _.bind(iterator, context); return initial ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator); } var length = obj.length; if (length !== +length) { var keys = _.keys(obj); length = keys.length; } each(obj, function(value, index, list) { index = keys ? keys[--length] : --length; if (!initial) { memo = obj[index]; initial = true; } else { memo = iterator.call(context, memo, obj[index], index, list); } }); if (!initial) throw new TypeError(reduceError); return memo; }; // Return the first value which passes a truth test. Aliased as `detect`. _.find = _.detect = function(obj, iterator, context) { var result; any(obj, function(value, index, list) { if (iterator.call(context, value, index, list)) { result = value; return true; } }); return result; }; // Return all the elements that pass a truth test. // Delegates to **ECMAScript 5**'s native `filter` if available. // Aliased as `select`. _.filter = _.select = function(obj, iterator, context) { var results = []; if (obj == null) return results; if (nativeFilter && obj.filter === nativeFilter) return obj.filter(iterator, context); each(obj, function(value, index, list) { if (iterator.call(context, value, index, list)) results.push(value); }); return results; }; // Return all the elements for which a truth test fails. _.reject = function(obj, iterator, context) { return _.filter(obj, function(value, index, list) { return !iterator.call(context, value, index, list); }, context); }; // Determine whether all of the elements match a truth test. // Delegates to **ECMAScript 5**'s native `every` if available. // Aliased as `all`. _.every = _.all = function(obj, iterator, context) { iterator || (iterator = _.identity); var result = true; if (obj == null) return result; if (nativeEvery && obj.every === nativeEvery) return obj.every(iterator, context); each(obj, function(value, index, list) { if (!(result = result && iterator.call(context, value, index, list))) return breaker; }); return !!result; }; // Determine if at least one element in the object matches a truth test. // Delegates to **ECMAScript 5**'s native `some` if available. // Aliased as `any`. var any = _.some = _.any = function(obj, iterator, context) { iterator || (iterator = _.identity); var result = false; if (obj == null) return result; if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context); each(obj, function(value, index, list) { if (result || (result = iterator.call(context, value, index, list))) return breaker; }); return !!result; }; // Determine if the array or object contains a given value (using `===`). // Aliased as `include`. _.contains = _.include = function(obj, target) { if (obj == null) return false; if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1; return any(obj, function(value) { return value === target; }); }; // Invoke a method (with arguments) on every item in a collection. _.invoke = function(obj, method) { var args = slice.call(arguments, 2); var isFunc = _.isFunction(method); return _.map(obj, function(value) { return (isFunc ? method : value[method]).apply(value, args); }); }; // Convenience version of a common use case of `map`: fetching a property. _.pluck = function(obj, key) { return _.map(obj, function(value){ return value[key]; }); }; // Convenience version of a common use case of `filter`: selecting only objects // containing specific `key:value` pairs. _.where = function(obj, attrs, first) { if (_.isEmpty(attrs)) return first ? void 0 : []; return _[first ? 'find' : 'filter'](obj, function(value) { for (var key in attrs) { if (attrs[key] !== value[key]) return false; } return true; }); }; // Convenience version of a common use case of `find`: getting the first object // containing specific `key:value` pairs. _.findWhere = function(obj, attrs) { return _.where(obj, attrs, true); }; // Return the maximum element or (element-based computation). // Can't optimize arrays of integers longer than 65,535 elements. // See [WebKit Bug 80797](https://bugs.webkit.org/show_bug.cgi?id=80797) _.max = function(obj, iterator, context) { if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) { return Math.max.apply(Math, obj); } if (!iterator && _.isEmpty(obj)) return -Infinity; var result = {computed : -Infinity, value: -Infinity}; each(obj, function(value, index, list) { var computed = iterator ? iterator.call(context, value, index, list) : value; computed > result.computed && (result = {value : value, computed : computed}); }); return result.value; }; // Return the minimum element (or element-based computation). _.min = function(obj, iterator, context) { if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) { return Math.min.apply(Math, obj); } if (!iterator && _.isEmpty(obj)) return Infinity; var result = {computed : Infinity, value: Infinity}; each(obj, function(value, index, list) { var computed = iterator ? iterator.call(context, value, index, list) : value; computed < result.computed && (result = {value : value, computed : computed}); }); return result.value; }; // Shuffle an array, using the modern version of the // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle). _.shuffle = function(obj) { var rand; var index = 0; var shuffled = []; each(obj, function(value) { rand = _.random(index++); shuffled[index - 1] = shuffled[rand]; shuffled[rand] = value; }); return shuffled; }; // Sample **n** random values from a collection. // If **n** is not specified, returns a single random element. // The internal `guard` argument allows it to work with `map`. _.sample = function(obj, n, guard) { if (n == null || guard) { if (obj.length !== +obj.length) obj = _.values(obj); return obj[_.random(obj.length - 1)]; } return _.shuffle(obj).slice(0, Math.max(0, n)); }; // An internal function to generate lookup iterators. var lookupIterator = function(value) { return _.isFunction(value) ? value : function(obj){ return obj[value]; }; }; // Sort the object's values by a criterion produced by an iterator. _.sortBy = function(obj, value, context) { var iterator = lookupIterator(value); return _.pluck(_.map(obj, function(value, index, list) { return { value: value, index: index, criteria: iterator.call(context, value, index, list) }; }).sort(function(left, right) { var a = left.criteria; var b = right.criteria; if (a !== b) { if (a > b || a === void 0) return 1; if (a < b || b === void 0) return -1; } return left.index - right.index; }), 'value'); }; // An internal function used for aggregate "group by" operations. var group = function(behavior) { return function(obj, value, context) { var result = {}; var iterator = value == null ? _.identity : lookupIterator(value); each(obj, function(value, index) { var key = iterator.call(context, value, index, obj); behavior(result, key, value); }); return result; }; }; // Groups the object's values by a criterion. Pass either a string attribute // to group by, or a function that returns the criterion. _.groupBy = group(function(result, key, value) { (_.has(result, key) ? result[key] : (result[key] = [])).push(value); }); // Indexes the object's values by a criterion, similar to `groupBy`, but for // when you know that your index values will be unique. _.indexBy = group(function(result, key, value) { result[key] = value; }); // Counts instances of an object that group by a certain criterion. Pass // either a string attribute to count by, or a function that returns the // criterion. _.countBy = group(function(result, key) { _.has(result, key) ? result[key]++ : result[key] = 1; }); // Use a comparator function to figure out the smallest index at which // an object should be inserted so as to maintain order. Uses binary search. _.sortedIndex = function(array, obj, iterator, context) { iterator = iterator == null ? _.identity : lookupIterator(iterator); var value = iterator.call(context, obj); var low = 0, high = array.length; while (low < high) { var mid = (low + high) >>> 1; iterator.call(context, array[mid]) < value ? low = mid + 1 : high = mid; } return low; }; // Safely create a real, live array from anything iterable. _.toArray = function(obj) { if (!obj) return []; if (_.isArray(obj)) return slice.call(obj); if (obj.length === +obj.length) return _.map(obj, _.identity); return _.values(obj); }; // Return the number of elements in an object. _.size = function(obj) { if (obj == null) return 0; return (obj.length === +obj.length) ? obj.length : _.keys(obj).length; }; // Array Functions // --------------- // Get the first element of an array. Passing **n** will return the first N // values in the array. Aliased as `head` and `take`. The **guard** check // allows it to work with `_.map`. _.first = _.head = _.take = function(array, n, guard) { if (array == null) return void 0; return (n == null) || guard ? array[0] : slice.call(array, 0, n); }; // Returns everything but the last entry of the array. Especially useful on // the arguments object. Passing **n** will return all the values in // the array, excluding the last N. The **guard** check allows it to work with // `_.map`. _.initial = function(array, n, guard) { return slice.call(array, 0, array.length - ((n == null) || guard ? 1 : n)); }; // Get the last element of an array. Passing **n** will return the last N // values in the array. The **guard** check allows it to work with `_.map`. _.last = function(array, n, guard) { if (array == null) return void 0; if ((n == null) || guard) { return array[array.length - 1]; } else { return slice.call(array, Math.max(array.length - n, 0)); } }; // Returns everything but the first entry of the array. Aliased as `tail` and `drop`. // Especially useful on the arguments object. Passing an **n** will return // the rest N values in the array. The **guard** // check allows it to work with `_.map`. _.rest = _.tail = _.drop = function(array, n, guard) { return slice.call(array, (n == null) || guard ? 1 : n); }; // Trim out all falsy values from an array. _.compact = function(array) { return _.filter(array, _.identity); }; // Internal implementation of a recursive `flatten` function. var flatten = function(input, shallow, output) { if (shallow && _.every(input, _.isArray)) { return concat.apply(output, input); } each(input, function(value) { if (_.isArray(value) || _.isArguments(value)) { shallow ? push.apply(output, value) : flatten(value, shallow, output); } else { output.push(value); } }); return output; }; // Flatten out an array, either recursively (by default), or just one level. _.flatten = function(array, shallow) { return flatten(array, shallow, []); }; // Return a version of the array that does not contain the specified value(s). _.without = function(array) { return _.difference(array, slice.call(arguments, 1)); }; // Produce a duplicate-free version of the array. If the array has already // been sorted, you have the option of using a faster algorithm. // Aliased as `unique`. _.uniq = _.unique = function(array, isSorted, iterator, context) { if (_.isFunction(isSorted)) { context = iterator; iterator = isSorted; isSorted = false; } var initial = iterator ? _.map(array, iterator, context) : array; var results = []; var seen = []; each(initial, function(value, index) { if (isSorted ? (!index || seen[seen.length - 1] !== value) : !_.contains(seen, value)) { seen.push(value); results.push(array[index]); } }); return results; }; // Produce an array that contains the union: each distinct element from all of // the passed-in arrays. _.union = function() { return _.uniq(_.flatten(arguments, true)); }; // Produce an array that contains every item shared between all the // passed-in arrays. _.intersection = function(array) { var rest = slice.call(arguments, 1); return _.filter(_.uniq(array), function(item) { return _.every(rest, function(other) { return _.indexOf(other, item) >= 0; }); }); }; // Take the difference between one array and a number of other arrays. // Only the elements present in just the first array will remain. _.difference = function(array) { var rest = concat.apply(ArrayProto, slice.call(arguments, 1)); return _.filter(array, function(value){ return !_.contains(rest, value); }); }; // Zip together multiple lists into a single array -- elements that share // an index go together. _.zip = function() { var length = _.max(_.pluck(arguments, "length").concat(0)); var results = new Array(length); for (var i = 0; i < length; i++) { results[i] = _.pluck(arguments, '' + i); } return results; }; // Converts lists into objects. Pass either a single array of `[key, value]` // pairs, or two parallel arrays of the same length -- one of keys, and one of // the corresponding values. _.object = function(list, values) { if (list == null) return {}; var result = {}; for (var i = 0, length = list.length; i < length; i++) { if (values) { result[list[i]] = values[i]; } else { result[list[i][0]] = list[i][1]; } } return result; }; // If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**), // we need this function. Return the position of the first occurrence of an // item in an array, or -1 if the item is not included in the array. // Delegates to **ECMAScript 5**'s native `indexOf` if available. // If the array is large and already in sort order, pass `true` // for **isSorted** to use binary search. _.indexOf = function(array, item, isSorted) { if (array == null) return -1; var i = 0, length = array.length; if (isSorted) { if (typeof isSorted == 'number') { i = (isSorted < 0 ? Math.max(0, length + isSorted) : isSorted); } else { i = _.sortedIndex(array, item); return array[i] === item ? i : -1; } } if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item, isSorted); for (; i < length; i++) if (array[i] === item) return i; return -1; }; // Delegates to **ECMAScript 5**'s native `lastIndexOf` if available. _.lastIndexOf = function(array, item, from) { if (array == null) return -1; var hasIndex = from != null; if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) { return hasIndex ? array.lastIndexOf(item, from) : array.lastIndexOf(item); } var i = (hasIndex ? from : array.length); while (i--) if (array[i] === item) return i; return -1; }; // Generate an integer Array containing an arithmetic progression. A port of // the native Python `range()` function. See // [the Python documentation](http://docs.python.org/library/functions.html#range). _.range = function(start, stop, step) { if (arguments.length <= 1) { stop = start || 0; start = 0; } step = arguments[2] || 1; var length = Math.max(Math.ceil((stop - start) / step), 0); var idx = 0; var range = new Array(length); while(idx < length) { range[idx++] = start; start += step; } return range; }; // Function (ahem) Functions // ------------------ // Reusable constructor function for prototype setting. var ctor = function(){}; // Create a function bound to a given object (assigning `this`, and arguments, // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if // available. _.bind = function(func, context) { var args, bound; if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1)); if (!_.isFunction(func)) throw new TypeError; args = slice.call(arguments, 2); return bound = function() { if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments))); ctor.prototype = func.prototype; var self = new ctor; ctor.prototype = null; var result = func.apply(self, args.concat(slice.call(arguments))); if (Object(result) === result) return result; return self; }; }; // Partially apply a function by creating a version that has had some of its // arguments pre-filled, without changing its dynamic `this` context. _.partial = function(func) { var args = slice.call(arguments, 1); return function() { return func.apply(this, args.concat(slice.call(arguments))); }; }; // Bind all of an object's methods to that object. Useful for ensuring that // all callbacks defined on an object belong to it. _.bindAll = function(obj) { var funcs = slice.call(arguments, 1); if (funcs.length === 0) throw new Error("bindAll must be passed function names"); each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); }); return obj; }; // Memoize an expensive function by storing its results. _.memoize = function(func, hasher) { var memo = {}; hasher || (hasher = _.identity); return function() { var key = hasher.apply(this, arguments); return _.has(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments)); }; }; // Delays a function for the given number of milliseconds, and then calls // it with the arguments supplied. _.delay = function(func, wait) { var args = slice.call(arguments, 2); return setTimeout(function(){ return func.apply(null, args); }, wait); }; // Defers a function, scheduling it to run after the current call stack has // cleared. _.defer = function(func) { return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1))); }; // Returns a function, that, when invoked, will only be triggered at most once // during a given window of time. Normally, the throttled function will run // as much as it can, without ever going more than once per `wait` duration; // but if you'd like to disable the execution on the leading edge, pass // `{leading: false}`. To disable execution on the trailing edge, ditto. _.throttle = function(func, wait, options) { var context, args, result; var timeout = null; var previous = 0; options || (options = {}); var later = function() { previous = options.leading === false ? 0 : new Date; timeout = null; result = func.apply(context, args); }; return function() { var now = new Date; if (!previous && options.leading === false) previous = now; var remaining = wait - (now - previous); context = this; args = arguments; if (remaining <= 0) { clearTimeout(timeout); timeout = null; previous = now; result = func.apply(context, args); } else if (!timeout && options.trailing !== false) { timeout = setTimeout(later, remaining); } return result; }; }; // Returns a function, that, as long as it continues to be invoked, will not // be triggered. The function will be called after it stops being called for // N milliseconds. If `immediate` is passed, trigger the function on the // leading edge, instead of the trailing. _.debounce = function(func, wait, immediate) { var timeout, args, context, timestamp, result; return function() { context = this; args = arguments; timestamp = new Date(); var later = function() { var last = (new Date()) - timestamp; if (last < wait) { timeout = setTimeout(later, wait - last); } else { timeout = null; if (!immediate) result = func.apply(context, args); } }; var callNow = immediate && !timeout; if (!timeout) { timeout = setTimeout(later, wait); } if (callNow) result = func.apply(context, args); return result; }; }; // Returns a function that will be executed at most one time, no matter how // often you call it. Useful for lazy initialization. _.once = function(func) { var ran = false, memo; return function() { if (ran) return memo; ran = true; memo = func.apply(this, arguments); func = null; return memo; }; }; // Returns the first function passed as an argument to the second, // allowing you to adjust arguments, run code before and after, and // conditionally execute the original function. _.wrap = function(func, wrapper) { return function() { var args = [func]; push.apply(args, arguments); return wrapper.apply(this, args); }; }; // Returns a function that is the composition of a list of functions, each // consuming the return value of the function that follows. _.compose = function() { var funcs = arguments; return function() { var args = arguments; for (var i = funcs.length - 1; i >= 0; i--) { args = [funcs[i].apply(this, args)]; } return args[0]; }; }; // Returns a function that will only be executed after being called N times. _.after = function(times, func) { return function() { if (--times < 1) { return func.apply(this, arguments); } }; }; // Object Functions // ---------------- // Retrieve the names of an object's properties. // Delegates to **ECMAScript 5**'s native `Object.keys` _.keys = nativeKeys || function(obj) { if (obj !== Object(obj)) throw new TypeError('Invalid object'); var keys = []; for (var key in obj) if (_.has(obj, key)) keys.push(key); return keys; }; // Retrieve the values of an object's properties. _.values = function(obj) { var keys = _.keys(obj); var length = keys.length; var values = new Array(length); for (var i = 0; i < length; i++) { values[i] = obj[keys[i]]; } return values; }; // Convert an object into a list of `[key, value]` pairs. _.pairs = function(obj) { var keys = _.keys(obj); var length = keys.length; var pairs = new Array(length); for (var i = 0; i < length; i++) { pairs[i] = [keys[i], obj[keys[i]]]; } return pairs; }; // Invert the keys and values of an object. The values must be serializable. _.invert = function(obj) { var result = {}; var keys = _.keys(obj); for (var i = 0, length = keys.length; i < length; i++) { result[obj[keys[i]]] = keys[i]; } return result; }; // Return a sorted list of the function names available on the object. // Aliased as `methods` _.functions = _.methods = function(obj) { var names = []; for (var key in obj) { if (_.isFunction(obj[key])) names.push(key); } return names.sort(); }; // Extend a given object with all the properties in passed-in object(s). _.extend = function(obj) { each(slice.call(arguments, 1), function(source) { if (source) { for (var prop in source) { obj[prop] = source[prop]; } } }); return obj; }; // Return a copy of the object only containing the whitelisted properties. _.pick = function(obj) { var copy = {}; var keys = concat.apply(ArrayProto, slice.call(arguments, 1)); each(keys, function(key) { if (key in obj) copy[key] = obj[key]; }); return copy; }; // Return a copy of the object without the blacklisted properties. _.omit = function(obj) { var copy = {}; var keys = concat.apply(ArrayProto, slice.call(arguments, 1)); for (var key in obj) { if (!_.contains(keys, key)) copy[key] = obj[key]; } return copy; }; // Fill in a given object with default properties. _.defaults = function(obj) { each(slice.call(arguments, 1), function(source) { if (source) { for (var prop in source) { if (obj[prop] === void 0) obj[prop] = source[prop]; } } }); return obj; }; // Create a (shallow-cloned) duplicate of an object. _.clone = function(obj) { if (!_.isObject(obj)) return obj; return _.isArray(obj) ? obj.slice() : _.extend({}, obj); }; // Invokes interceptor with the obj, and then returns obj. // The primary purpose of this method is to "tap into" a method chain, in // order to perform operations on intermediate results within the chain. _.tap = function(obj, interceptor) { interceptor(obj); return obj; }; // Internal recursive comparison function for `isEqual`. var eq = function(a, b, aStack, bStack) { // Identical objects are equal. `0 === -0`, but they aren't identical. // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal). if (a === b) return a !== 0 || 1 / a == 1 / b; // A strict comparison is necessary because `null == undefined`. if (a == null || b == null) return a === b; // Unwrap any wrapped objects. if (a instanceof _) a = a._wrapped; if (b instanceof _) b = b._wrapped; // Compare `[[Class]]` names. var className = toString.call(a); if (className != toString.call(b)) return false; switch (className) { // Strings, numbers, dates, and booleans are compared by value. case '[object String]': // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is // equivalent to `new String("5")`. return a == String(b); case '[object Number]': // `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for // other numeric values. return a != +a ? b != +b : (a == 0 ? 1 / a == 1 / b : a == +b); case '[object Date]': case '[object Boolean]': // Coerce dates and booleans to numeric primitive values. Dates are compared by their // millisecond representations. Note that invalid dates with millisecond representations // of `NaN` are not equivalent. return +a == +b; // RegExps are compared by their source patterns and flags. case '[object RegExp]': return a.source == b.source && a.global == b.global && a.multiline == b.multiline && a.ignoreCase == b.ignoreCase; } if (typeof a != 'object' || typeof b != 'object') return false; // Assume equality for cyclic structures. The algorithm for detecting cyclic // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`. var length = aStack.length; while (length--) { // Linear search. Performance is inversely proportional to the number of // unique nested structures. if (aStack[length] == a) return bStack[length] == b; } // Objects with different constructors are not equivalent, but `Object`s // from different frames are. var aCtor = a.constructor, bCtor = b.constructor; if (aCtor !== bCtor && !(_.isFunction(aCtor) && (aCtor instanceof aCtor) && _.isFunction(bCtor) && (bCtor instanceof bCtor))) { return false; } // Add the first object to the stack of traversed objects. aStack.push(a); bStack.push(b); var size = 0, result = true; // Recursively compare objects and arrays. if (className == '[object Array]') { // Compare array lengths to determine if a deep comparison is necessary. size = a.length; result = size == b.length; if (result) { // Deep compare the contents, ignoring non-numeric properties. while (size--) { if (!(result = eq(a[size], b[size], aStack, bStack))) break; } } } else { // Deep compare objects. for (var key in a) { if (_.has(a, key)) { // Count the expected number of properties. size++; // Deep compare each member. if (!(result = _.has(b, key) && eq(a[key], b[key], aStack, bStack))) break; } } // Ensure that both objects contain the same number of properties. if (result) { for (key in b) { if (_.has(b, key) && !(size--)) break; } result = !size; } } // Remove the first object from the stack of traversed objects. aStack.pop(); bStack.pop(); return result; }; // Perform a deep comparison to check if two objects are equal. _.isEqual = function(a, b) { return eq(a, b, [], []); }; // Is a given array, string, or object empty? // An "empty" object has no enumerable own-properties. _.isEmpty = function(obj) { if (obj == null) return true; if (_.isArray(obj) || _.isString(obj)) return obj.length === 0; for (var key in obj) if (_.has(obj, key)) return false; return true; }; // Is a given value a DOM element? _.isElement = function(obj) { return !!(obj && obj.nodeType === 1); }; // Is a given value an array? // Delegates to ECMA5's native Array.isArray _.isArray = nativeIsArray || function(obj) { return toString.call(obj) == '[object Array]'; }; // Is a given variable an object? _.isObject = function(obj) { return obj === Object(obj); }; // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp. each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'], function(name) { _['is' + name] = function(obj) { return toString.call(obj) == '[object ' + name + ']'; }; }); // Define a fallback version of the method in browsers (ahem, IE), where // there isn't any inspectable "Arguments" type. if (!_.isArguments(arguments)) { _.isArguments = function(obj) { return !!(obj && _.has(obj, 'callee')); }; } // Optimize `isFunction` if appropriate. if (typeof (/./) !== 'function') { _.isFunction = function(obj) { return typeof obj === 'function'; }; } // Is a given object a finite number? _.isFinite = function(obj) { return isFinite(obj) && !isNaN(parseFloat(obj)); }; // Is the given value `NaN`? (NaN is the only number which does not equal itself). _.isNaN = function(obj) { return _.isNumber(obj) && obj != +obj; }; // Is a given value a boolean? _.isBoolean = function(obj) { return obj === true || obj === false || toString.call(obj) == '[object Boolean]'; }; // Is a given value equal to null? _.isNull = function(obj) { return obj === null; }; // Is a given variable undefined? _.isUndefined = function(obj) { return obj === void 0; }; // Shortcut function for checking if an object has a given property directly // on itself (in other words, not on a prototype). _.has = function(obj, key) { return hasOwnProperty.call(obj, key); }; // Utility Functions // ----------------- // Run Underscore.js in *noConflict* mode, returning the `_` variable to its // previous owner. Returns a reference to the Underscore object. _.noConflict = function() { root._ = previousUnderscore; return this; }; // Keep the identity function around for default iterators. _.identity = function(value) { return value; }; // Run a function **n** times. _.times = function(n, iterator, context) { var accum = Array(Math.max(0, n)); for (var i = 0; i < n; i++) accum[i] = iterator.call(context, i); return accum; }; // Return a random integer between min and max (inclusive). _.random = function(min, max) { if (max == null) { max = min; min = 0; } return min + Math.floor(Math.random() * (max - min + 1)); }; // List of HTML entities for escaping. var entityMap = { escape: { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#x27;' } }; entityMap.unescape = _.invert(entityMap.escape); // Regexes containing the keys and values listed immediately above. var entityRegexes = { escape: new RegExp('[' + _.keys(entityMap.escape).join('') + ']', 'g'), unescape: new RegExp('(' + _.keys(entityMap.unescape).join('|') + ')', 'g') }; // Functions for escaping and unescaping strings to/from HTML interpolation. _.each(['escape', 'unescape'], function(method) { _[method] = function(string) { if (string == null) return ''; return ('' + string).replace(entityRegexes[method], function(match) { return entityMap[method][match]; }); }; }); // If the value of the named `property` is a function then invoke it with the // `object` as context; otherwise, return it. _.result = function(object, property) { if (object == null) return void 0; var value = object[property]; return _.isFunction(value) ? value.call(object) : value; }; // Add your own custom functions to the Underscore object. _.mixin = function(obj) { each(_.functions(obj), function(name) { var func = _[name] = obj[name]; _.prototype[name] = function() { var args = [this._wrapped]; push.apply(args, arguments); return result.call(this, func.apply(_, args)); }; }); }; // Generate a unique integer id (unique within the entire client session). // Useful for temporary DOM ids. var idCounter = 0; _.uniqueId = function(prefix) { var id = ++idCounter + ''; return prefix ? prefix + id : id; }; // By default, Underscore uses ERB-style template delimiters, change the // following template settings to use alternative delimiters. _.templateSettings = { evaluate : /<%([\s\S]+?)%>/g, interpolate : /<%=([\s\S]+?)%>/g, escape : /<%-([\s\S]+?)%>/g }; // When customizing `templateSettings`, if you don't want to define an // interpolation, evaluation or escaping regex, we need one that is // guaranteed not to match. var noMatch = /(.)^/; // Certain characters need to be escaped so that they can be put into a // string literal. var escapes = { "'": "'", '\\': '\\', '\r': 'r', '\n': 'n', '\t': 't', '\u2028': 'u2028', '\u2029': 'u2029' }; var escaper = /\\|'|\r|\n|\t|\u2028|\u2029/g; // JavaScript micro-templating, similar to John Resig's implementation. // Underscore templating handles arbitrary delimiters, preserves whitespace, // and correctly escapes quotes within interpolated code. _.template = function(text, data, settings) { var render; settings = _.defaults({}, settings, _.templateSettings); // Combine delimiters into one regular expression via alternation. var matcher = new RegExp([ (settings.escape || noMatch).source, (settings.interpolate || noMatch).source, (settings.evaluate || noMatch).source ].join('|') + '|$', 'g'); // Compile the template source, escaping string literals appropriately. var index = 0; var source = "__p+='"; text.replace(matcher, function(match, escape, interpolate, evaluate, offset) { source += text.slice(index, offset) .replace(escaper, function(match) { return '\\' + escapes[match]; }); if (escape) { source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'"; } if (interpolate) { source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'"; } if (evaluate) { source += "';\n" + evaluate + "\n__p+='"; } index = offset + match.length; return match; }); source += "';\n"; // If a variable is not specified, place data values in local scope. if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n'; source = "var __t,__p='',__j=Array.prototype.join," + "print=function(){__p+=__j.call(arguments,'');};\n" + source + "return __p;\n"; try { render = new Function(settings.variable || 'obj', '_', source); } catch (e) { e.source = source; throw e; } if (data) return render(data, _); var template = function(data) { return render.call(this, data, _); }; // Provide the compiled function source as a convenience for precompilation. template.source = 'function(' + (settings.variable || 'obj') + '){\n' + source + '}'; return template; }; // Add a "chain" function, which will delegate to the wrapper. _.chain = function(obj) { return _(obj).chain(); }; // OOP // --------------- // If Underscore is called as a function, it returns a wrapped object that // can be used OO-style. This wrapper holds altered versions of all the // underscore functions. Wrapped objects may be chained. // Helper function to continue chaining intermediate results. var result = function(obj) { return this._chain ? _(obj).chain() : obj; }; // Add all of the Underscore functions to the wrapper object. _.mixin(_); // Add all mutator Array functions to the wrapper. each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) { var method = ArrayProto[name]; _.prototype[name] = function() { var obj = this._wrapped; method.apply(obj, arguments); if ((name == 'shift' || name == 'splice') && obj.length === 0) delete obj[0]; return result.call(this, obj); }; }); // Add all accessor Array functions to the wrapper. each(['concat', 'join', 'slice'], function(name) { var method = ArrayProto[name]; _.prototype[name] = function() { return result.call(this, method.apply(this._wrapped, arguments)); }; }); _.extend(_.prototype, { // Start chaining a wrapped Underscore object. chain: function() { this._chain = true; return this; }, // Extracts the result from a wrapped and chained object. value: function() { return this._wrapped; } }); }).call(this); // Backbone.js 1.0.0 // (c) 2010-2013 Jeremy Ashkenas, DocumentCloud Inc. // Backbone may be freely distributed under the MIT license. // For all details and documentation: // http://backbonejs.org (function(){ // Initial Setup // ------------- // Save a reference to the global object (`window` in the browser, `exports` // on the server). var root = this; // Save the previous value of the `Backbone` variable, so that it can be // restored later on, if `noConflict` is used. var previousBackbone = root.Backbone; // Create local references to array methods we'll want to use later. var array = []; var push = array.push; var slice = array.slice; var splice = array.splice; // The top-level namespace. All public Backbone classes and modules will // be attached to this. Exported for both the browser and the server. var Backbone; if (typeof exports !== 'undefined') { Backbone = exports; } else { Backbone = root.Backbone = {}; } // Current version of the library. Keep in sync with `package.json`. Backbone.VERSION = '1.0.0'; // Require Underscore, if we're on the server, and it's not already present. var _ = root._; if (!_ && (typeof require !== 'undefined')) _ = require('underscore'); // For Backbone's purposes, jQuery, Zepto, Ender, or My Library (kidding) owns // the `$` variable. Backbone.$ = root.jQuery || root.Zepto || root.ender || root.$; // Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable // to its previous owner. Returns a reference to this Backbone object. Backbone.noConflict = function() { root.Backbone = previousBackbone; return this; }; // Turn on `emulateHTTP` to support legacy HTTP servers. Setting this option // will fake `"PUT"` and `"DELETE"` requests via the `_method` parameter and // set a `X-Http-Method-Override` header. Backbone.emulateHTTP = false; // Turn on `emulateJSON` to support legacy servers that can't deal with direct // `application/json` requests ... will encode the body as // `application/x-www-form-urlencoded` instead and will send the model in a // form param named `model`. Backbone.emulateJSON = false; // Backbone.Events // --------------- // A module that can be mixed in to *any object* in order to provide it with // custom events. You may bind with `on` or remove with `off` callback // functions to an event; `trigger`-ing an event fires all callbacks in // succession. // // var object = {}; // _.extend(object, Backbone.Events); // object.on('expand', function(){ alert('expanded'); }); // object.trigger('expand'); // var Events = Backbone.Events = { // Bind an event to a `callback` function. Passing `"all"` will bind // the callback to all events fired. on: function(name, callback, context) { if (!eventsApi(this, 'on', name, [callback, context]) || !callback) return this; this._events || (this._events = {}); var events = this._events[name] || (this._events[name] = []); events.push({callback: callback, context: context, ctx: context || this}); return this; }, // Bind an event to only be triggered a single time. After the first time // the callback is invoked, it will be removed. once: function(name, callback, context) { if (!eventsApi(this, 'once', name, [callback, context]) || !callback) return this; var self = this; var once = _.once(function() { self.off(name, once); callback.apply(this, arguments); }); once._callback = callback; return this.on(name, once, context); }, // Remove one or many callbacks. If `context` is null, removes all // callbacks with that function. If `callback` is null, removes all // callbacks for the event. If `name` is null, removes all bound // callbacks for all events. off: function(name, callback, context) { var retain, ev, events, names, i, l, j, k; if (!this._events || !eventsApi(this, 'off', name, [callback, context])) return this; if (!name && !callback && !context) { this._events = {}; return this; } names = name ? [name] : _.keys(this._events); for (i = 0, l = names.length; i < l; i++) { name = names[i]; if (events = this._events[name]) { this._events[name] = retain = []; if (callback || context) { for (j = 0, k = events.length; j < k; j++) { ev = events[j]; if ((callback && callback !== ev.callback && callback !== ev.callback._callback) || (context && context !== ev.context)) { retain.push(ev); } } } if (!retain.length) delete this._events[name]; } } return this; }, // Trigger one or many events, firing all bound callbacks. Callbacks are // passed the same arguments as `trigger` is, apart from the event name // (unless you're listening on `"all"`, which will cause your callback to // receive the true name of the event as the first argument). trigger: function(name) { if (!this._events) return this; var args = slice.call(arguments, 1); if (!eventsApi(this, 'trigger', name, args)) return this; var events = this._events[name]; var allEvents = this._events.all; if (events) triggerEvents(events, args); if (allEvents) triggerEvents(allEvents, arguments); return this; }, // Tell this object to stop listening to either specific events ... or // to every object it's currently listening to. stopListening: function(obj, name, callback) { var listeners = this._listeners; if (!listeners) return this; var deleteListener = !name && !callback; if (typeof name === 'object') callback = this; if (obj) (listeners = {})[obj._listenerId] = obj; for (var id in listeners) { listeners[id].off(name, callback, this); if (deleteListener) delete this._listeners[id]; } return this; } }; // Regular expression used to split event strings. var eventSplitter = /\s+/; // Implement fancy features of the Events API such as multiple event // names `"change blur"` and jQuery-style event maps `{change: action}` // in terms of the existing API. var eventsApi = function(obj, action, name, rest) { if (!name) return true; // Handle event maps. if (typeof name === 'object') { for (var key in name) { obj[action].apply(obj, [key, name[key]].concat(rest)); } return false; } // Handle space separated event names. if (eventSplitter.test(name)) { var names = name.split(eventSplitter); for (var i = 0, l = names.length; i < l; i++) { obj[action].apply(obj, [names[i]].concat(rest)); } return false; } return true; }; // A difficult-to-believe, but optimized internal dispatch function for // triggering events. Tries to keep the usual cases speedy (most internal // Backbone events have 3 arguments). var triggerEvents = function(events, args) { var ev, i = -1, l = events.length, a1 = args[0], a2 = args[1], a3 = args[2]; switch (args.length) { case 0: while (++i < l) (ev = events[i]).callback.call(ev.ctx); return; case 1: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1); return; case 2: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2); return; case 3: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2, a3); return; default: while (++i < l) (ev = events[i]).callback.apply(ev.ctx, args); } }; var listenMethods = {listenTo: 'on', listenToOnce: 'once'}; // Inversion-of-control versions of `on` and `once`. Tell *this* object to // listen to an event in another object ... keeping track of what it's // listening to. _.each(listenMethods, function(implementation, method) { Events[method] = function(obj, name, callback) { var listeners = this._listeners || (this._listeners = {}); var id = obj._listenerId || (obj._listenerId = _.uniqueId('l')); listeners[id] = obj; if (typeof name === 'object') callback = this; obj[implementation](name, callback, this); return this; }; }); // Aliases for backwards compatibility. Events.bind = Events.on; Events.unbind = Events.off; // Allow the `Backbone` object to serve as a global event bus, for folks who // want global "pubsub" in a convenient place. _.extend(Backbone, Events); // Backbone.Model // -------------- // Backbone **Models** are the basic data object in the framework -- // frequently representing a row in a table in a database on your server. // A discrete chunk of data and a bunch of useful, related methods for // performing computations and transformations on that data. // Create a new model with the specified attributes. A client id (`cid`) // is automatically generated and assigned for you. var Model = Backbone.Model = function(attributes, options) { var defaults; var attrs = attributes || {}; options || (options = {}); this.cid = _.uniqueId('c'); this.attributes = {}; _.extend(this, _.pick(options, modelOptions)); if (options.parse) attrs = this.parse(attrs, options) || {}; if (defaults = _.result(this, 'defaults')) { attrs = _.defaults({}, attrs, defaults); } this.set(attrs, options); this.changed = {}; this.initialize.apply(this, arguments); }; // A list of options to be attached directly to the model, if provided. var modelOptions = ['url', 'urlRoot', 'collection']; // Attach all inheritable methods to the Model prototype. _.extend(Model.prototype, Events, { // A hash of attributes whose current and previous value differ. changed: null, // The value returned during the last failed validation. validationError: null, // The default name for the JSON `id` attribute is `"id"`. MongoDB and // CouchDB users may want to set this to `"_id"`. idAttribute: 'id', // Initialize is an empty function by default. Override it with your own // initialization logic. initialize: function(){}, // Return a copy of the model's `attributes` object. toJSON: function(options) { return _.clone(this.attributes); }, // Proxy `Backbone.sync` by default -- but override this if you need // custom syncing semantics for *this* particular model. sync: function() { return Backbone.sync.apply(this, arguments); }, // Get the value of an attribute. get: function(attr) { return this.attributes[attr]; }, // Get the HTML-escaped value of an attribute. escape: function(attr) { return _.escape(this.get(attr)); }, // Returns `true` if the attribute contains a value that is not null // or undefined. has: function(attr) { return this.get(attr) != null; }, // Set a hash of model attributes on the object, firing `"change"`. This is // the core primitive operation of a model, updating the data and notifying // anyone who needs to know about the change in state. The heart of the beast. set: function(key, val, options) { var attr, attrs, unset, changes, silent, changing, prev, current; if (key == null) return this; // Handle both `"key", value` and `{key: value}` -style arguments. if (typeof key === 'object') { attrs = key; options = val; } else { (attrs = {})[key] = val; } options || (options = {}); // Run validation. if (!this._validate(attrs, options)) return false; // Extract attributes and options. unset = options.unset; silent = options.silent; changes = []; changing = this._changing; this._changing = true; if (!changing) { this._previousAttributes = _.clone(this.attributes); this.changed = {}; } current = this.attributes, prev = this._previousAttributes; // Check for changes of `id`. if (this.idAttribute in attrs) this.id = attrs[this.idAttribute]; // For each `set` attribute, update or delete the current value. for (attr in attrs) { val = attrs[attr]; if (!_.isEqual(current[attr], val)) changes.push(attr); if (!_.isEqual(prev[attr], val)) { this.changed[attr] = val; } else { delete this.changed[attr]; } unset ? delete current[attr] : current[attr] = val; } // Trigger all relevant attribute changes. if (!silent) { if (changes.length) this._pending = true; for (var i = 0, l = changes.length; i < l; i++) { this.trigger('change:' + changes[i], this, current[changes[i]], options); } } // You might be wondering why there's a `while` loop here. Changes can // be recursively nested within `"change"` events. if (changing) return this; if (!silent) { while (this._pending) { this._pending = false; this.trigger('change', this, options); } } this._pending = false; this._changing = false; return this; }, // Remove an attribute from the model, firing `"change"`. `unset` is a noop // if the attribute doesn't exist. unset: function(attr, options) { return this.set(attr, void 0, _.extend({}, options, {unset: true})); }, // Clear all attributes on the model, firing `"change"`. clear: function(options) { var attrs = {}; for (var key in this.attributes) attrs[key] = void 0; return this.set(attrs, _.extend({}, options, {unset: true})); }, // Determine if the model has changed since the last `"change"` event. // If you specify an attribute name, determine if that attribute has changed. hasChanged: function(attr) { if (attr == null) return !_.isEmpty(this.changed); return _.has(this.changed, attr); }, // Return an object containing all the attributes that have changed, or // false if there are no changed attributes. Useful for determining what // parts of a view need to be updated and/or what attributes need to be // persisted to the server. Unset attributes will be set to undefined. // You can also pass an attributes object to diff against the model, // determining if there *would be* a change. changedAttributes: function(diff) { if (!diff) return this.hasChanged() ? _.clone(this.changed) : false; var val, changed = false; var old = this._changing ? this._previousAttributes : this.attributes; for (var attr in diff) { if (_.isEqual(old[attr], (val = diff[attr]))) continue; (changed || (changed = {}))[attr] = val; } return changed; }, // Get the previous value of an attribute, recorded at the time the last // `"change"` event was fired. previous: function(attr) { if (attr == null || !this._previousAttributes) return null; return this._previousAttributes[attr]; }, // Get all of the attributes of the model at the time of the previous // `"change"` event. previousAttributes: function() { return _.clone(this._previousAttributes); }, // Fetch the model from the server. If the server's representation of the // model differs from its current attributes, they will be overridden, // triggering a `"change"` event. fetch: function(options) { options = options ? _.clone(options) : {}; if (options.parse === void 0) options.parse = true; var model = this; var success = options.success; options.success = function(resp) { if (!model.set(model.parse(resp, options), options)) return false; if (success) success(model, resp, options); model.trigger('sync', model, resp, options); }; wrapError(this, options); return this.sync('read', this, options); }, // Set a hash of model attributes, and sync the model to the server. // If the server returns an attributes hash that differs, the model's // state will be `set` again. save: function(key, val, options) { var attrs, method, xhr, attributes = this.attributes; // Handle both `"key", value` and `{key: value}` -style arguments. if (key == null || typeof key === 'object') { attrs = key; options = val; } else { (attrs = {})[key] = val; } // If we're not waiting and attributes exist, save acts as `set(attr).save(null, opts)`. if (attrs && (!options || !options.wait) && !this.set(attrs, options)) return false; options = _.extend({validate: true}, options); // Do not persist invalid models. if (!this._validate(attrs, options)) return false; // Set temporary attributes if `{wait: true}`. if (attrs && options.wait) { this.attributes = _.extend({}, attributes, attrs); } // After a successful server-side save, the client is (optionally) // updated with the server-side state. if (options.parse === void 0) options.parse = true; var model = this; var success = options.success; options.success = function(resp) { // Ensure attributes are restored during synchronous saves. model.attributes = attributes; var serverAttrs = model.parse(resp, options); if (options.wait) serverAttrs = _.extend(attrs || {}, serverAttrs); if (_.isObject(serverAttrs) && !model.set(serverAttrs, options)) { return false; } if (success) success(model, resp, options); model.trigger('sync', model, resp, options); }; wrapError(this, options); method = this.isNew() ? 'create' : (options.patch ? 'patch' : 'update'); if (method === 'patch') options.attrs = attrs; xhr = this.sync(method, this, options); // Restore attributes. if (attrs && options.wait) this.attributes = attributes; return xhr; }, // Destroy this model on the server if it was already persisted. // Optimistically removes the model from its collection, if it has one. // If `wait: true` is passed, waits for the server to respond before removal. destroy: function(options) { options = options ? _.clone(options) : {}; var model = this; var success = options.success; var destroy = function() { model.trigger('destroy', model, model.collection, options); }; options.success = function(resp) { if (options.wait || model.isNew()) destroy(); if (success) success(model, resp, options); if (!model.isNew()) model.trigger('sync', model, resp, options); }; if (this.isNew()) { options.success(); return false; } wrapError(this, options); var xhr = this.sync('delete', this, options); if (!options.wait) destroy(); return xhr; }, // Default URL for the model's representation on the server -- if you're // using Backbone's restful methods, override this to change the endpoint // that will be called. url: function() { var base = _.result(this, 'urlRoot') || _.result(this.collection, 'url') || urlError(); if (this.isNew()) return base; return base + (base.charAt(base.length - 1) === '/' ? '' : '/') + encodeURIComponent(this.id); }, // **parse** converts a response into the hash of attributes to be `set` on // the model. The default implementation is just to pass the response along. parse: function(resp, options) { return resp; }, // Create a new model with identical attributes to this one. clone: function() { return new this.constructor(this.attributes); }, // A model is new if it has never been saved to the server, and lacks an id. isNew: function() { return this.id == null; }, // Check if the model is currently in a valid state. isValid: function(options) { return this._validate({}, _.extend(options || {}, { validate: true })); }, // Run validation against the next complete set of model attributes, // returning `true` if all is well. Otherwise, fire an `"invalid"` event. _validate: function(attrs, options) { if (!options.validate || !this.validate) return true; attrs = _.extend({}, this.attributes, attrs); var error = this.validationError = this.validate(attrs, options) || null; if (!error) return true; this.trigger('invalid', this, error, _.extend(options || {}, {validationError: error})); return false; } }); // Underscore methods that we want to implement on the Model. var modelMethods = ['keys', 'values', 'pairs', 'invert', 'pick', 'omit']; // Mix in each Underscore method as a proxy to `Model#attributes`. _.each(modelMethods, function(method) { Model.prototype[method] = function() { var args = slice.call(arguments); args.unshift(this.attributes); return _[method].apply(_, args); }; }); // Backbone.Collection // ------------------- // If models tend to represent a single row of data, a Backbone Collection is // more analagous to a table full of data ... or a small slice or page of that // table, or a collection of rows that belong together for a particular reason // -- all of the messages in this particular folder, all of the documents // belonging to this particular author, and so on. Collections maintain // indexes of their models, both in order, and for lookup by `id`. // Create a new **Collection**, perhaps to contain a specific type of `model`. // If a `comparator` is specified, the Collection will maintain // its models in sort order, as they're added and removed. var Collection = Backbone.Collection = function(models, options) { options || (options = {}); if (options.url) this.url = options.url; if (options.model) this.model = options.model; if (options.comparator !== void 0) this.comparator = options.comparator; this._reset(); this.initialize.apply(this, arguments); if (models) this.reset(models, _.extend({silent: true}, options)); }; // Default options for `Collection#set`. var setOptions = {add: true, remove: true, merge: true}; var addOptions = {add: true, merge: false, remove: false}; // Define the Collection's inheritable methods. _.extend(Collection.prototype, Events, { // The default model for a collection is just a **Backbone.Model**. // This should be overridden in most cases. model: Model, // Initialize is an empty function by default. Override it with your own // initialization logic. initialize: function(){}, // The JSON representation of a Collection is an array of the // models' attributes. toJSON: function(options) { return this.map(function(model){ return model.toJSON(options); }); }, // Proxy `Backbone.sync` by default. sync: function() { return Backbone.sync.apply(this, arguments); }, // Add a model, or list of models to the set. add: function(models, options) { return this.set(models, _.defaults(options || {}, addOptions)); }, // Remove a model, or a list of models from the set. remove: function(models, options) { models = _.isArray(models) ? models.slice() : [models]; options || (options = {}); var i, l, index, model; for (i = 0, l = models.length; i < l; i++) { model = this.get(models[i]); if (!model) continue; delete this._byId[model.id]; delete this._byId[model.cid]; index = this.indexOf(model); this.models.splice(index, 1); this.length--; if (!options.silent) { options.index = index; model.trigger('remove', model, this, options); } this._removeReference(model); } return this; }, // Update a collection by `set`-ing a new list of models, adding new ones, // removing models that are no longer present, and merging models that // already exist in the collection, as necessary. Similar to **Model#set**, // the core operation for updating the data contained by the collection. set: function(models, options) { options = _.defaults(options || {}, setOptions); if (options.parse) models = this.parse(models, options); if (!_.isArray(models)) models = models ? [models] : []; var i, l, model, attrs, existing, sort; var at = options.at; var sortable = this.comparator && (at == null) && options.sort !== false; var sortAttr = _.isString(this.comparator) ? this.comparator : null; var toAdd = [], toRemove = [], modelMap = {}; // Turn bare objects into model references, and prevent invalid models // from being added. for (i = 0, l = models.length; i < l; i++) { if (!(model = this._prepareModel(models[i], options))) continue; // If a duplicate is found, prevent it from being added and // optionally merge it into the existing model. if (existing = this.get(model)) { if (options.remove) modelMap[existing.cid] = true; if (options.merge) { existing.set(model.attributes, options); if (sortable && !sort && existing.hasChanged(sortAttr)) sort = true; } // This is a new model, push it to the `toAdd` list. } else if (options.add) { toAdd.push(model); // Listen to added models' events, and index models for lookup by // `id` and by `cid`. model.on('all', this._onModelEvent, this); this._byId[model.cid] = model; if (model.id != null) this._byId[model.id] = model; } } // Remove nonexistent models if appropriate. if (options.remove) { for (i = 0, l = this.length; i < l; ++i) { if (!modelMap[(model = this.models[i]).cid]) toRemove.push(model); } if (toRemove.length) this.remove(toRemove, options); } // See if sorting is needed, update `length` and splice in new models. if (toAdd.length) { if (sortable) sort = true; this.length += toAdd.length; if (at != null) { splice.apply(this.models, [at, 0].concat(toAdd)); } else { push.apply(this.models, toAdd); } } // Silently sort the collection if appropriate. if (sort) this.sort({silent: true}); if (options.silent) return this; // Trigger `add` events. for (i = 0, l = toAdd.length; i < l; i++) { (model = toAdd[i]).trigger('add', model, this, options); } // Trigger `sort` if the collection was sorted. if (sort) this.trigger('sort', this, options); return this; }, // When you have more items than you want to add or remove individually, // you can reset the entire set with a new list of models, without firing // any granular `add` or `remove` events. Fires `reset` when finished. // Useful for bulk operations and optimizations. reset: function(models, options) { options || (options = {}); for (var i = 0, l = this.models.length; i < l; i++) { this._removeReference(this.models[i]); } options.previousModels = this.models; this._reset(); this.add(models, _.extend({silent: true}, options)); if (!options.silent) this.trigger('reset', this, options); return this; }, // Add a model to the end of the collection. push: function(model, options) { model = this._prepareModel(model, options); this.add(model, _.extend({at: this.length}, options)); return model; }, // Remove a model from the end of the collection. pop: function(options) { var model = this.at(this.length - 1); this.remove(model, options); return model; }, // Add a model to the beginning of the collection. unshift: function(model, options) { model = this._prepareModel(model, options); this.add(model, _.extend({at: 0}, options)); return model; }, // Remove a model from the beginning of the collection. shift: function(options) { var model = this.at(0); this.remove(model, options); return model; }, // Slice out a sub-array of models from the collection. slice: function(begin, end) { return this.models.slice(begin, end); }, // Get a model from the set by id. get: function(obj) { if (obj == null) return void 0; return this._byId[obj.id != null ? obj.id : obj.cid || obj]; }, // Get the model at the given index. at: function(index) { return this.models[index]; }, // Return models with matching attributes. Useful for simple cases of // `filter`. where: function(attrs, first) { if (_.isEmpty(attrs)) return first ? void 0 : []; return this[first ? 'find' : 'filter'](function(model) { for (var key in attrs) { if (attrs[key] !== model.get(key)) return false; } return true; }); }, // Return the first model with matching attributes. Useful for simple cases // of `find`. findWhere: function(attrs) { return this.where(attrs, true); }, // Force the collection to re-sort itself. You don't need to call this under // normal circumstances, as the set will maintain sort order as each item // is added. sort: function(options) { if (!this.comparator) throw new Error('Cannot sort a set without a comparator'); options || (options = {}); // Run sort based on type of `comparator`. if (_.isString(this.comparator) || this.comparator.length === 1) { this.models = this.sortBy(this.comparator, this); } else { this.models.sort(_.bind(this.comparator, this)); } if (!options.silent) this.trigger('sort', this, options); return this; }, // Figure out the smallest index at which a model should be inserted so as // to maintain order. sortedIndex: function(model, value, context) { value || (value = this.comparator); var iterator = _.isFunction(value) ? value : function(model) { return model.get(value); }; return _.sortedIndex(this.models, model, iterator, context); }, // Pluck an attribute from each model in the collection. pluck: function(attr) { return _.invoke(this.models, 'get', attr); }, // Fetch the default set of models for this collection, resetting the // collection when they arrive. If `reset: true` is passed, the response // data will be passed through the `reset` method instead of `set`. fetch: function(options) { options = options ? _.clone(options) : {}; if (options.parse === void 0) options.parse = true; var success = options.success; var collection = this; options.success = function(resp) { var method = options.reset ? 'reset' : 'set'; collection[method](resp, options); if (success) success(collection, resp, options); collection.trigger('sync', collection, resp, options); }; wrapError(this, options); return this.sync('read', this, options); }, // Create a new instance of a model in this collection. Add the model to the // collection immediately, unless `wait: true` is passed, in which case we // wait for the server to agree. create: function(model, options) { options = options ? _.clone(options) : {}; if (!(model = this._prepareModel(model, options))) return false; if (!options.wait) this.add(model, options); var collection = this; var success = options.success; options.success = function(resp) { if (options.wait) collection.add(model, options); if (success) success(model, resp, options); }; model.save(null, options); return model; }, // **parse** converts a response into a list of models to be added to the // collection. The default implementation is just to pass it through. parse: function(resp, options) { return resp; }, // Create a new collection with an identical list of models as this one. clone: function() { return new this.constructor(this.models); }, // Private method to reset all internal state. Called when the collection // is first initialized or reset. _reset: function() { this.length = 0; this.models = []; this._byId = {}; }, // Prepare a hash of attributes (or other model) to be added to this // collection. _prepareModel: function(attrs, options) { if (attrs instanceof Model) { if (!attrs.collection) attrs.collection = this; return attrs; } options || (options = {}); options.collection = this; var model = new this.model(attrs, options); if (!model._validate(attrs, options)) { this.trigger('invalid', this, attrs, options); return false; } return model; }, // Internal method to sever a model's ties to a collection. _removeReference: function(model) { if (this === model.collection) delete model.collection; model.off('all', this._onModelEvent, this); }, // Internal method called every time a model in the set fires an event. // Sets need to update their indexes when models change ids. All other // events simply proxy through. "add" and "remove" events that originate // in other collections are ignored. _onModelEvent: function(event, model, collection, options) { if ((event === 'add' || event === 'remove') && collection !== this) return; if (event === 'destroy') this.remove(model, options); if (model && event === 'change:' + model.idAttribute) { delete this._byId[model.previous(model.idAttribute)]; if (model.id != null) this._byId[model.id] = model; } this.trigger.apply(this, arguments); } }); // Underscore methods that we want to implement on the Collection. // 90% of the core usefulness of Backbone Collections is actually implemented // right here: var methods = ['forEach', 'each', 'map', 'collect', 'reduce', 'foldl', 'inject', 'reduceRight', 'foldr', 'find', 'detect', 'filter', 'select', 'reject', 'every', 'all', 'some', 'any', 'include', 'contains', 'invoke', 'max', 'min', 'toArray', 'size', 'first', 'head', 'take', 'initial', 'rest', 'tail', 'drop', 'last', 'without', 'indexOf', 'shuffle', 'lastIndexOf', 'isEmpty', 'chain']; // Mix in each Underscore method as a proxy to `Collection#models`. _.each(methods, function(method) { Collection.prototype[method] = function() { var args = slice.call(arguments); args.unshift(this.models); return _[method].apply(_, args); }; }); // Underscore methods that take a property name as an argument. var attributeMethods = ['groupBy', 'countBy', 'sortBy']; // Use attributes instead of properties. _.each(attributeMethods, function(method) { Collection.prototype[method] = function(value, context) { var iterator = _.isFunction(value) ? value : function(model) { return model.get(value); }; return _[method](this.models, iterator, context); }; }); // Backbone.View // ------------- // Backbone Views are almost more convention than they are actual code. A View // is simply a JavaScript object that represents a logical chunk of UI in the // DOM. This might be a single item, an entire list, a sidebar or panel, or // even the surrounding frame which wraps your whole app. Defining a chunk of // UI as a **View** allows you to define your DOM events declaratively, without // having to worry about render order ... and makes it easy for the view to // react to specific changes in the state of your models. // Creating a Backbone.View creates its initial element outside of the DOM, // if an existing element is not provided... var View = Backbone.View = function(options) { this.cid = _.uniqueId('view'); this._configure(options || {}); this._ensureElement(); this.initialize.apply(this, arguments); this.delegateEvents(); }; // Cached regex to split keys for `delegate`. var delegateEventSplitter = /^(\S+)\s*(.*)$/; // List of view options to be merged as properties. var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName', 'events']; // Set up all inheritable **Backbone.View** properties and methods. _.extend(View.prototype, Events, { // The default `tagName` of a View's element is `"div"`. tagName: 'div', // jQuery delegate for element lookup, scoped to DOM elements within the // current view. This should be prefered to global lookups where possible. $: function(selector) { return this.$el.find(selector); }, // Initialize is an empty function by default. Override it with your own // initialization logic. initialize: function(){}, // **render** is the core function that your view should override, in order // to populate its element (`this.el`), with the appropriate HTML. The // convention is for **render** to always return `this`. render: function() { return this; }, // Remove this view by taking the element out of the DOM, and removing any // applicable Backbone.Events listeners. remove: function() { this.$el.remove(); this.stopListening(); return this; }, // Change the view's element (`this.el` property), including event // re-delegation. setElement: function(element, delegate) { if (this.$el) this.undelegateEvents(); this.$el = element instanceof Backbone.$ ? element : Backbone.$(element); this.el = this.$el[0]; if (delegate !== false) this.delegateEvents(); return this; }, // Set callbacks, where `this.events` is a hash of // // *{"event selector": "callback"}* // // { // 'mousedown .title': 'edit', // 'click .button': 'save' // 'click .open': function(e) { ... } // } // // pairs. Callbacks will be bound to the view, with `this` set properly. // Uses event delegation for efficiency. // Omitting the selector binds the event to `this.el`. // This only works for delegate-able events: not `focus`, `blur`, and // not `change`, `submit`, and `reset` in Internet Explorer. delegateEvents: function(events) { if (!(events || (events = _.result(this, 'events')))) return this; this.undelegateEvents(); for (var key in events) { var method = events[key]; if (!_.isFunction(method)) method = this[events[key]]; if (!method) continue; var match = key.match(delegateEventSplitter); var eventName = match[1], selector = match[2]; method = _.bind(method, this); eventName += '.delegateEvents' + this.cid; if (selector === '') { this.$el.on(eventName, method); } else { this.$el.on(eventName, selector, method); } } return this; }, // Clears all callbacks previously bound to the view with `delegateEvents`. // You usually don't need to use this, but may wish to if you have multiple // Backbone views attached to the same DOM element. undelegateEvents: function() { this.$el.off('.delegateEvents' + this.cid); return this; }, // Performs the initial configuration of a View with a set of options. // Keys with special meaning *(e.g. model, collection, id, className)* are // attached directly to the view. See `viewOptions` for an exhaustive // list. _configure: function(options) { if (this.options) options = _.extend({}, _.result(this, 'options'), options); _.extend(this, _.pick(options, viewOptions)); this.options = options; }, // Ensure that the View has a DOM element to render into. // If `this.el` is a string, pass it through `$()`, take the first // matching element, and re-assign it to `el`. Otherwise, create // an element from the `id`, `className` and `tagName` properties. _ensureElement: function() { if (!this.el) { var attrs = _.extend({}, _.result(this, 'attributes')); if (this.id) attrs.id = _.result(this, 'id'); if (this.className) attrs['class'] = _.result(this, 'className'); var $el = Backbone.$('<' + _.result(this, 'tagName') + '>').attr(attrs); this.setElement($el, false); } else { this.setElement(_.result(this, 'el'), false); } } }); // Backbone.sync // ------------- // Override this function to change the manner in which Backbone persists // models to the server. You will be passed the type of request, and the // model in question. By default, makes a RESTful Ajax request // to the model's `url()`. Some possible customizations could be: // // * Use `setTimeout` to batch rapid-fire updates into a single request. // * Send up the models as XML instead of JSON. // * Persist models via WebSockets instead of Ajax. // // Turn on `Backbone.emulateHTTP` in order to send `PUT` and `DELETE` requests // as `POST`, with a `_method` parameter containing the true HTTP method, // as well as all requests with the body as `application/x-www-form-urlencoded` // instead of `application/json` with the model in a param named `model`. // Useful when interfacing with server-side languages like **PHP** that make // it difficult to read the body of `PUT` requests. Backbone.sync = function(method, model, options) { var type = methodMap[method]; // Default options, unless specified. _.defaults(options || (options = {}), { emulateHTTP: Backbone.emulateHTTP, emulateJSON: Backbone.emulateJSON }); // Default JSON-request options. var params = {type: type, dataType: 'json'}; // Ensure that we have a URL. if (!options.url) { params.url = _.result(model, 'url') || urlError(); } // Ensure that we have the appropriate request data. if (options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) { params.contentType = 'application/json'; params.data = JSON.stringify(options.attrs || model.toJSON(options)); } // For older servers, emulate JSON by encoding the request into an HTML-form. if (options.emulateJSON) { params.contentType = 'application/x-www-form-urlencoded'; params.data = params.data ? {model: params.data} : {}; } // For older servers, emulate HTTP by mimicking the HTTP method with `_method` // And an `X-HTTP-Method-Override` header. if (options.emulateHTTP && (type === 'PUT' || type === 'DELETE' || type === 'PATCH')) { params.type = 'POST'; if (options.emulateJSON) params.data._method = type; var beforeSend = options.beforeSend; options.beforeSend = function(xhr) { xhr.setRequestHeader('X-HTTP-Method-Override', type); if (beforeSend) return beforeSend.apply(this, arguments); }; } // Don't process data on a non-GET request. if (params.type !== 'GET' && !options.emulateJSON) { params.processData = false; } // If we're sending a `PATCH` request, and we're in an old Internet Explorer // that still has ActiveX enabled by default, override jQuery to use that // for XHR instead. Remove this line when jQuery supports `PATCH` on IE8. if (params.type === 'PATCH' && window.ActiveXObject && !(window.external && window.external.msActiveXFilteringEnabled)) { params.xhr = function() { return new ActiveXObject("Microsoft.XMLHTTP"); }; } // Make the request, allowing the user to override any Ajax options. var xhr = options.xhr = Backbone.ajax(_.extend(params, options)); model.trigger('request', model, xhr, options); return xhr; }; // Map from CRUD to HTTP for our default `Backbone.sync` implementation. var methodMap = { 'create': 'POST', 'update': 'PUT', 'patch': 'PATCH', 'delete': 'DELETE', 'read': 'GET' }; // Set the default implementation of `Backbone.ajax` to proxy through to `$`. // Override this if you'd like to use a different library. Backbone.ajax = function() { return Backbone.$.ajax.apply(Backbone.$, arguments); }; // Backbone.Router // --------------- // Routers map faux-URLs to actions, and fire events when routes are // matched. Creating a new one sets its `routes` hash, if not set statically. var Router = Backbone.Router = function(options) { options || (options = {}); if (options.routes) this.routes = options.routes; this._bindRoutes(); this.initialize.apply(this, arguments); }; // Cached regular expressions for matching named param parts and splatted // parts of route strings. var optionalParam = /\((.*?)\)/g; var namedParam = /(\(\?)?:\w+/g; var splatParam = /\*\w+/g; var escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g; // Set up all inheritable **Backbone.Router** properties and methods. _.extend(Router.prototype, Events, { // Initialize is an empty function by default. Override it with your own // initialization logic. initialize: function(){}, // Manually bind a single named route to a callback. For example: // // this.route('search/:query/p:num', 'search', function(query, num) { // ... // }); // route: function(route, name, callback) { if (!_.isRegExp(route)) route = this._routeToRegExp(route); if (_.isFunction(name)) { callback = name; name = ''; } if (!callback) callback = this[name]; var router = this; Backbone.history.route(route, function(fragment) { var args = router._extractParameters(route, fragment); callback && callback.apply(router, args); router.trigger.apply(router, ['route:' + name].concat(args)); router.trigger('route', name, args); Backbone.history.trigger('route', router, name, args); }); return this; }, // Simple proxy to `Backbone.history` to save a fragment into the history. navigate: function(fragment, options) { Backbone.history.navigate(fragment, options); return this; }, // Bind all defined routes to `Backbone.history`. We have to reverse the // order of the routes here to support behavior where the most general // routes can be defined at the bottom of the route map. _bindRoutes: function() { if (!this.routes) return; this.routes = _.result(this, 'routes'); var route, routes = _.keys(this.routes); while ((route = routes.pop()) != null) { this.route(route, this.routes[route]); } }, // Convert a route string into a regular expression, suitable for matching // against the current location hash. _routeToRegExp: function(route) { route = route.replace(escapeRegExp, '\\$&') .replace(optionalParam, '(?:$1)?') .replace(namedParam, function(match, optional){ return optional ? match : '([^\/]+)'; }) .replace(splatParam, '(.*?)'); return new RegExp('^' + route + '$'); }, // Given a route, and a URL fragment that it matches, return the array of // extracted decoded parameters. Empty or unmatched parameters will be // treated as `null` to normalize cross-browser behavior. _extractParameters: function(route, fragment) { var params = route.exec(fragment).slice(1); return _.map(params, function(param) { return param ? decodeURIComponent(param) : null; }); } }); // Backbone.History // ---------------- // Handles cross-browser history management, based on either // [pushState](http://diveintohtml5.info/history.html) and real URLs, or // [onhashchange](https://developer.mozilla.org/en-US/docs/DOM/window.onhashchange) // and URL fragments. If the browser supports neither (old IE, natch), // falls back to polling. var History = Backbone.History = function() { this.handlers = []; _.bindAll(this, 'checkUrl'); // Ensure that `History` can be used outside of the browser. if (typeof window !== 'undefined') { this.location = window.location; this.history = window.history; } }; // Cached regex for stripping a leading hash/slash and trailing space. var routeStripper = /^[#\/]|\s+$/g; // Cached regex for stripping leading and trailing slashes. var rootStripper = /^\/+|\/+$/g; // Cached regex for detecting MSIE. var isExplorer = /msie [\w.]+/; // Cached regex for removing a trailing slash. var trailingSlash = /\/$/; // Has the history handling already been started? History.started = false; // Set up all inheritable **Backbone.History** properties and methods. _.extend(History.prototype, Events, { // The default interval to poll for hash changes, if necessary, is // twenty times a second. interval: 50, // Gets the true hash value. Cannot use location.hash directly due to bug // in Firefox where location.hash will always be decoded. getHash: function(window) { var match = (window || this).location.href.match(/#(.*)$/); return match ? match[1] : ''; }, // Get the cross-browser normalized URL fragment, either from the URL, // the hash, or the override. getFragment: function(fragment, forcePushState) { if (fragment == null) { if (this._hasPushState || !this._wantsHashChange || forcePushState) { fragment = this.location.pathname; var root = this.root.replace(trailingSlash, ''); if (!fragment.indexOf(root)) fragment = fragment.substr(root.length); } else { fragment = this.getHash(); } } return fragment.replace(routeStripper, ''); }, // Start the hash change handling, returning `true` if the current URL matches // an existing route, and `false` otherwise. start: function(options) { if (History.started) throw new Error("Backbone.history has already been started"); History.started = true; // Figure out the initial configuration. Do we need an iframe? // Is pushState desired ... is it available? this.options = _.extend({}, {root: '/'}, this.options, options); this.root = this.options.root; this._wantsHashChange = this.options.hashChange !== false; this._wantsPushState = !!this.options.pushState; this._hasPushState = !!(this.options.pushState && this.history && this.history.pushState); var fragment = this.getFragment(); var docMode = document.documentMode; var oldIE = (isExplorer.exec(navigator.userAgent.toLowerCase()) && (!docMode || docMode <= 7)); // Normalize root to always include a leading and trailing slash. this.root = ('/' + this.root + '/').replace(rootStripper, '/'); if (oldIE && this._wantsHashChange) { this.iframe = Backbone.$('<iframe src="javascript:0" tabindex="-1" />').hide().appendTo('body')[0].contentWindow; this.navigate(fragment); } // Depending on whether we're using pushState or hashes, and whether // 'onhashchange' is supported, determine how we check the URL state. if (this._hasPushState) { Backbone.$(window).on('popstate', this.checkUrl); } else if (this._wantsHashChange && ('onhashchange' in window) && !oldIE) { Backbone.$(window).on('hashchange', this.checkUrl); } else if (this._wantsHashChange) { this._checkUrlInterval = setInterval(this.checkUrl, this.interval); } // Determine if we need to change the base url, for a pushState link // opened by a non-pushState browser. this.fragment = fragment; var loc = this.location; var atRoot = loc.pathname.replace(/[^\/]$/, '$&/') === this.root; // If we've started off with a route from a `pushState`-enabled browser, // but we're currently in a browser that doesn't support it... if (this._wantsHashChange && this._wantsPushState && !this._hasPushState && !atRoot) { this.fragment = this.getFragment(null, true); this.location.replace(this.root + this.location.search + '#' + this.fragment); // Return immediately as browser will do redirect to new url return true; // Or if we've started out with a hash-based route, but we're currently // in a browser where it could be `pushState`-based instead... } else if (this._wantsPushState && this._hasPushState && atRoot && loc.hash) { this.fragment = this.getHash().replace(routeStripper, ''); this.history.replaceState({}, document.title, this.root + this.fragment + loc.search); } if (!this.options.silent) return this.loadUrl(); }, // Disable Backbone.history, perhaps temporarily. Not useful in a real app, // but possibly useful for unit testing Routers. stop: function() { Backbone.$(window).off('popstate', this.checkUrl).off('hashchange', this.checkUrl); clearInterval(this._checkUrlInterval); History.started = false; }, // Add a route to be tested when the fragment changes. Routes added later // may override previous routes. route: function(route, callback) { this.handlers.unshift({route: route, callback: callback}); }, // Checks the current URL to see if it has changed, and if it has, // calls `loadUrl`, normalizing across the hidden iframe. checkUrl: function(e) { var current = this.getFragment(); if (current === this.fragment && this.iframe) { current = this.getFragment(this.getHash(this.iframe)); } if (current === this.fragment) return false; if (this.iframe) this.navigate(current); this.loadUrl() || this.loadUrl(this.getHash()); }, // Attempt to load the current URL fragment. If a route succeeds with a // match, returns `true`. If no defined routes matches the fragment, // returns `false`. loadUrl: function(fragmentOverride) { var fragment = this.fragment = this.getFragment(fragmentOverride); var matched = _.any(this.handlers, function(handler) { if (handler.route.test(fragment)) { handler.callback(fragment); return true; } }); return matched; }, // Save a fragment into the hash history, or replace the URL state if the // 'replace' option is passed. You are responsible for properly URL-encoding // the fragment in advance. // // The options object can contain `trigger: true` if you wish to have the // route callback be fired (not usually desirable), or `replace: true`, if // you wish to modify the current URL without adding an entry to the history. navigate: function(fragment, options) { if (!History.started) return false; if (!options || options === true) options = {trigger: options}; fragment = this.getFragment(fragment || ''); if (this.fragment === fragment) return; this.fragment = fragment; var url = this.root + fragment; // If pushState is available, we use it to set the fragment as a real URL. if (this._hasPushState) { this.history[options.replace ? 'replaceState' : 'pushState']({}, document.title, url); // If hash changes haven't been explicitly disabled, update the hash // fragment to store history. } else if (this._wantsHashChange) { this._updateHash(this.location, fragment, options.replace); if (this.iframe && (fragment !== this.getFragment(this.getHash(this.iframe)))) { // Opening and closing the iframe tricks IE7 and earlier to push a // history entry on hash-tag change. When replace is true, we don't // want this. if(!options.replace) this.iframe.document.open().close(); this._updateHash(this.iframe.location, fragment, options.replace); } // If you've told us that you explicitly don't want fallback hashchange- // based history, then `navigate` becomes a page refresh. } else { return this.location.assign(url); } if (options.trigger) this.loadUrl(fragment); }, // Update the hash location, either replacing the current entry, or adding // a new one to the browser history. _updateHash: function(location, fragment, replace) { if (replace) { var href = location.href.replace(/(javascript:|#).*$/, ''); location.replace(href + '#' + fragment); } else { // Some browsers require that `hash` contains a leading #. location.hash = '#' + fragment; } } }); // Create the default Backbone.history. Backbone.history = new History; // Helpers // ------- // Helper function to correctly set up the prototype chain, for subclasses. // Similar to `goog.inherits`, but uses a hash of prototype properties and // class properties to be extended. var extend = function(protoProps, staticProps) { var parent = this; var child; // The constructor function for the new subclass is either defined by you // (the "constructor" property in your `extend` definition), or defaulted // by us to simply call the parent's constructor. if (protoProps && _.has(protoProps, 'constructor')) { child = protoProps.constructor; } else { child = function(){ return parent.apply(this, arguments); }; } // Add static properties to the constructor function, if supplied. _.extend(child, parent, staticProps); // Set the prototype chain to inherit from `parent`, without calling // `parent`'s constructor function. var Surrogate = function(){ this.constructor = child; }; Surrogate.prototype = parent.prototype; child.prototype = new Surrogate; // Add prototype properties (instance properties) to the subclass, // if supplied. if (protoProps) _.extend(child.prototype, protoProps); // Set a convenience property in case the parent's prototype is needed // later. child.__super__ = parent.prototype; return child; }; // Set up inheritance for the model, collection, router, view and history. Model.extend = Collection.extend = Router.extend = View.extend = History.extend = extend; // Throw an error when a URL is needed, and none is supplied. var urlError = function() { throw new Error('A "url" property or function must be specified'); }; // Wrap an optional error callback with a fallback error event. var wrapError = function (model, options) { var error = options.error; options.error = function(resp) { if (error) error(model, resp, options); model.trigger('error', model, resp, options); }; }; }).call(this); /* Copyright (C) 2011 by Yehuda Katz Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // lib/handlebars/browser-prefix.js var Handlebars = {}; (function(Handlebars, undefined) { ; // lib/handlebars/base.js Handlebars.VERSION = "1.0.0"; Handlebars.COMPILER_REVISION = 4; Handlebars.REVISION_CHANGES = { 1: '<= 1.0.rc.2', // 1.0.rc.2 is actually rev2 but doesn't report it 2: '== 1.0.0-rc.3', 3: '== 1.0.0-rc.4', 4: '>= 1.0.0' }; Handlebars.helpers = {}; Handlebars.partials = {}; var toString = Object.prototype.toString, functionType = '[object Function]', objectType = '[object Object]'; Handlebars.registerHelper = function(name, fn, inverse) { if (toString.call(name) === objectType) { if (inverse || fn) { throw new Handlebars.Exception('Arg not supported with multiple helpers'); } Handlebars.Utils.extend(this.helpers, name); } else { if (inverse) { fn.not = inverse; } this.helpers[name] = fn; } }; Handlebars.registerPartial = function(name, str) { if (toString.call(name) === objectType) { Handlebars.Utils.extend(this.partials, name); } else { this.partials[name] = str; } }; Handlebars.registerHelper('helperMissing', function(arg) { if(arguments.length === 2) { return undefined; } else { throw new Error("Missing helper: '" + arg + "'"); } }); Handlebars.registerHelper('blockHelperMissing', function(context, options) { var inverse = options.inverse || function() {}, fn = options.fn; var type = toString.call(context); if(type === functionType) { context = context.call(this); } if(context === true) { return fn(this); } else if(context === false || context == null) { return inverse(this); } else if(type === "[object Array]") { if(context.length > 0) { return Handlebars.helpers.each(context, options); } else { return inverse(this); } } else { return fn(context); } }); Handlebars.K = function() {}; Handlebars.createFrame = Object.create || function(object) { Handlebars.K.prototype = object; var obj = new Handlebars.K(); Handlebars.K.prototype = null; return obj; }; Handlebars.logger = { DEBUG: 0, INFO: 1, WARN: 2, ERROR: 3, level: 3, methodMap: {0: 'debug', 1: 'info', 2: 'warn', 3: 'error'}, // can be overridden in the host environment log: function(level, obj) { if (Handlebars.logger.level <= level) { var method = Handlebars.logger.methodMap[level]; if (typeof console !== 'undefined' && console[method]) { console[method].call(console, obj); } } } }; Handlebars.log = function(level, obj) { Handlebars.logger.log(level, obj); }; Handlebars.registerHelper('each', function(context, options) { var fn = options.fn, inverse = options.inverse; var i = 0, ret = "", data; var type = toString.call(context); if(type === functionType) { context = context.call(this); } if (options.data) { data = Handlebars.createFrame(options.data); } if(context && typeof context === 'object') { if(context instanceof Array){ for(var j = context.length; i<j; i++) { if (data) { data.index = i; } ret = ret + fn(context[i], { data: data }); } } else { for(var key in context) { if(context.hasOwnProperty(key)) { if(data) { data.key = key; } ret = ret + fn(context[key], {data: data}); i++; } } } } if(i === 0){ ret = inverse(this); } return ret; }); Handlebars.registerHelper('if', function(conditional, options) { var type = toString.call(conditional); if(type === functionType) { conditional = conditional.call(this); } if(!conditional || Handlebars.Utils.isEmpty(conditional)) { return options.inverse(this); } else { return options.fn(this); } }); Handlebars.registerHelper('unless', function(conditional, options) { return Handlebars.helpers['if'].call(this, conditional, {fn: options.inverse, inverse: options.fn}); }); Handlebars.registerHelper('with', function(context, options) { var type = toString.call(context); if(type === functionType) { context = context.call(this); } if (!Handlebars.Utils.isEmpty(context)) return options.fn(context); }); Handlebars.registerHelper('log', function(context, options) { var level = options.data && options.data.level != null ? parseInt(options.data.level, 10) : 1; Handlebars.log(level, context); }); ; // lib/handlebars/utils.js var errorProps = ['description', 'fileName', 'lineNumber', 'message', 'name', 'number', 'stack']; Handlebars.Exception = function(message) { var tmp = Error.prototype.constructor.apply(this, arguments); // Unfortunately errors are not enumerable in Chrome (at least), so `for prop in tmp` doesn't work. for (var idx = 0; idx < errorProps.length; idx++) { this[errorProps[idx]] = tmp[errorProps[idx]]; } }; Handlebars.Exception.prototype = new Error(); // Build out our basic SafeString type Handlebars.SafeString = function(string) { this.string = string; }; Handlebars.SafeString.prototype.toString = function() { return this.string.toString(); }; var escape = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#x27;", "`": "&#x60;" }; var badChars = /[&<>"'`]/g; var possible = /[&<>"'`]/; var escapeChar = function(chr) { return escape[chr] || "&amp;"; }; Handlebars.Utils = { extend: function(obj, value) { for(var key in value) { if(value.hasOwnProperty(key)) { obj[key] = value[key]; } } }, escapeExpression: function(string) { // don't escape SafeStrings, since they're already safe if (string instanceof Handlebars.SafeString) { return string.toString(); } else if (string == null || string === false) { return ""; } // Force a string conversion as this will be done by the append regardless and // the regex test will do this transparently behind the scenes, causing issues if // an object's to string has escaped characters in it. string = string.toString(); if(!possible.test(string)) { return string; } return string.replace(badChars, escapeChar); }, isEmpty: function(value) { if (!value && value !== 0) { return true; } else if(toString.call(value) === "[object Array]" && value.length === 0) { return true; } else { return false; } } }; ; // lib/handlebars/runtime.js Handlebars.VM = { template: function(templateSpec) { // Just add water var container = { escapeExpression: Handlebars.Utils.escapeExpression, invokePartial: Handlebars.VM.invokePartial, programs: [], program: function(i, fn, data) { var programWrapper = this.programs[i]; if(data) { programWrapper = Handlebars.VM.program(i, fn, data); } else if (!programWrapper) { programWrapper = this.programs[i] = Handlebars.VM.program(i, fn); } return programWrapper; }, merge: function(param, common) { var ret = param || common; if (param && common) { ret = {}; Handlebars.Utils.extend(ret, common); Handlebars.Utils.extend(ret, param); } return ret; }, programWithDepth: Handlebars.VM.programWithDepth, noop: Handlebars.VM.noop, compilerInfo: null }; return function(context, options) { options = options || {}; var result = templateSpec.call(container, Handlebars, context, options.helpers, options.partials, options.data); var compilerInfo = container.compilerInfo || [], compilerRevision = compilerInfo[0] || 1, currentRevision = Handlebars.COMPILER_REVISION; if (compilerRevision !== currentRevision) { if (compilerRevision < currentRevision) { var runtimeVersions = Handlebars.REVISION_CHANGES[currentRevision], compilerVersions = Handlebars.REVISION_CHANGES[compilerRevision]; throw "Template was precompiled with an older version of Handlebars than the current runtime. "+ "Please update your precompiler to a newer version ("+runtimeVersions+") or downgrade your runtime to an older version ("+compilerVersions+")."; } else { // Use the embedded version info since the runtime doesn't know about this revision yet throw "Template was precompiled with a newer version of Handlebars than the current runtime. "+ "Please update your runtime to a newer version ("+compilerInfo[1]+")."; } } return result; }; }, programWithDepth: function(i, fn, data /*, $depth */) { var args = Array.prototype.slice.call(arguments, 3); var program = function(context, options) { options = options || {}; return fn.apply(this, [context, options.data || data].concat(args)); }; program.program = i; program.depth = args.length; return program; }, program: function(i, fn, data) { var program = function(context, options) { options = options || {}; return fn(context, options.data || data); }; program.program = i; program.depth = 0; return program; }, noop: function() { return ""; }, invokePartial: function(partial, name, context, helpers, partials, data) { var options = { helpers: helpers, partials: partials, data: data }; if(partial === undefined) { throw new Handlebars.Exception("The partial " + name + " could not be found"); } else if(partial instanceof Function) { return partial(context, options); } else if (!Handlebars.compile) { throw new Handlebars.Exception("The partial " + name + " could not be compiled when running in runtime-only mode"); } else { partials[name] = Handlebars.compile(partial, {data: data !== undefined}); return partials[name](context, options); } } }; Handlebars.template = Handlebars.VM.template; ; // lib/handlebars/browser-suffix.js })(Handlebars); ; // moment.js // version : 2.1.0 // author : Tim Wood // license : MIT // momentjs.com (function (undefined) { /************************************ Constants ************************************/ var moment, VERSION = "2.1.0", round = Math.round, i, // internal storage for language config files languages = {}, // check for nodeJS hasModule = (typeof module !== 'undefined' && module.exports), // ASP.NET json date format regex aspNetJsonRegex = /^\/?Date\((\-?\d+)/i, aspNetTimeSpanJsonRegex = /(\-)?(\d*)?\.?(\d+)\:(\d+)\:(\d+)\.?(\d{3})?/, // format tokens formattingTokens = /(\[[^\[]*\])|(\\)?(Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|mm?|ss?|SS?S?|X|zz?|ZZ?|.)/g, localFormattingTokens = /(\[[^\[]*\])|(\\)?(LT|LL?L?L?|l{1,4})/g, // parsing token regexes parseTokenOneOrTwoDigits = /\d\d?/, // 0 - 99 parseTokenOneToThreeDigits = /\d{1,3}/, // 0 - 999 parseTokenThreeDigits = /\d{3}/, // 000 - 999 parseTokenFourDigits = /\d{1,4}/, // 0 - 9999 parseTokenSixDigits = /[+\-]?\d{1,6}/, // -999,999 - 999,999 parseTokenWord = /[0-9]*['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+|[\u0600-\u06FF\/]+(\s*?[\u0600-\u06FF]+){1,2}/i, // any word (or two) characters or numbers including two/three word month in arabic. parseTokenTimezone = /Z|[\+\-]\d\d:?\d\d/i, // +00:00 -00:00 +0000 -0000 or Z parseTokenT = /T/i, // T (ISO seperator) parseTokenTimestampMs = /[\+\-]?\d+(\.\d{1,3})?/, // 123456789 123456789.123 // preliminary iso regex // 0000-00-00 + T + 00 or 00:00 or 00:00:00 or 00:00:00.000 + +00:00 or +0000 isoRegex = /^\s*\d{4}-\d\d-\d\d((T| )(\d\d(:\d\d(:\d\d(\.\d\d?\d?)?)?)?)?([\+\-]\d\d:?\d\d)?)?/, isoFormat = 'YYYY-MM-DDTHH:mm:ssZ', // iso time formats and regexes isoTimes = [ ['HH:mm:ss.S', /(T| )\d\d:\d\d:\d\d\.\d{1,3}/], ['HH:mm:ss', /(T| )\d\d:\d\d:\d\d/], ['HH:mm', /(T| )\d\d:\d\d/], ['HH', /(T| )\d\d/] ], // timezone chunker "+10:00" > ["10", "00"] or "-1530" > ["-15", "30"] parseTimezoneChunker = /([\+\-]|\d\d)/gi, // getter and setter names proxyGettersAndSetters = 'Date|Hours|Minutes|Seconds|Milliseconds'.split('|'), unitMillisecondFactors = { 'Milliseconds' : 1, 'Seconds' : 1e3, 'Minutes' : 6e4, 'Hours' : 36e5, 'Days' : 864e5, 'Months' : 2592e6, 'Years' : 31536e6 }, unitAliases = { ms : 'millisecond', s : 'second', m : 'minute', h : 'hour', d : 'day', w : 'week', M : 'month', y : 'year' }, // format function strings formatFunctions = {}, // tokens to ordinalize and pad ordinalizeTokens = 'DDD w W M D d'.split(' '), paddedTokens = 'M D H h m s w W'.split(' '), formatTokenFunctions = { M : function () { return this.month() + 1; }, MMM : function (format) { return this.lang().monthsShort(this, format); }, MMMM : function (format) { return this.lang().months(this, format); }, D : function () { return this.date(); }, DDD : function () { return this.dayOfYear(); }, d : function () { return this.day(); }, dd : function (format) { return this.lang().weekdaysMin(this, format); }, ddd : function (format) { return this.lang().weekdaysShort(this, format); }, dddd : function (format) { return this.lang().weekdays(this, format); }, w : function () { return this.week(); }, W : function () { return this.isoWeek(); }, YY : function () { return leftZeroFill(this.year() % 100, 2); }, YYYY : function () { return leftZeroFill(this.year(), 4); }, YYYYY : function () { return leftZeroFill(this.year(), 5); }, gg : function () { return leftZeroFill(this.weekYear() % 100, 2); }, gggg : function () { return this.weekYear(); }, ggggg : function () { return leftZeroFill(this.weekYear(), 5); }, GG : function () { return leftZeroFill(this.isoWeekYear() % 100, 2); }, GGGG : function () { return this.isoWeekYear(); }, GGGGG : function () { return leftZeroFill(this.isoWeekYear(), 5); }, e : function () { return this.weekday(); }, E : function () { return this.isoWeekday(); }, a : function () { return this.lang().meridiem(this.hours(), this.minutes(), true); }, A : function () { return this.lang().meridiem(this.hours(), this.minutes(), false); }, H : function () { return this.hours(); }, h : function () { return this.hours() % 12 || 12; }, m : function () { return this.minutes(); }, s : function () { return this.seconds(); }, S : function () { return ~~(this.milliseconds() / 100); }, SS : function () { return leftZeroFill(~~(this.milliseconds() / 10), 2); }, SSS : function () { return leftZeroFill(this.milliseconds(), 3); }, Z : function () { var a = -this.zone(), b = "+"; if (a < 0) { a = -a; b = "-"; } return b + leftZeroFill(~~(a / 60), 2) + ":" + leftZeroFill(~~a % 60, 2); }, ZZ : function () { var a = -this.zone(), b = "+"; if (a < 0) { a = -a; b = "-"; } return b + leftZeroFill(~~(10 * a / 6), 4); }, z : function () { return this.zoneAbbr(); }, zz : function () { return this.zoneName(); }, X : function () { return this.unix(); } }; function padToken(func, count) { return function (a) { return leftZeroFill(func.call(this, a), count); }; } function ordinalizeToken(func, period) { return function (a) { return this.lang().ordinal(func.call(this, a), period); }; } while (ordinalizeTokens.length) { i = ordinalizeTokens.pop(); formatTokenFunctions[i + 'o'] = ordinalizeToken(formatTokenFunctions[i], i); } while (paddedTokens.length) { i = paddedTokens.pop(); formatTokenFunctions[i + i] = padToken(formatTokenFunctions[i], 2); } formatTokenFunctions.DDDD = padToken(formatTokenFunctions.DDD, 3); /************************************ Constructors ************************************/ function Language() { } // Moment prototype object function Moment(config) { extend(this, config); } // Duration Constructor function Duration(duration) { var years = duration.years || duration.year || duration.y || 0, months = duration.months || duration.month || duration.M || 0, weeks = duration.weeks || duration.week || duration.w || 0, days = duration.days || duration.day || duration.d || 0, hours = duration.hours || duration.hour || duration.h || 0, minutes = duration.minutes || duration.minute || duration.m || 0, seconds = duration.seconds || duration.second || duration.s || 0, milliseconds = duration.milliseconds || duration.millisecond || duration.ms || 0; // store reference to input for deterministic cloning this._input = duration; // representation for dateAddRemove this._milliseconds = milliseconds + seconds * 1e3 + // 1000 minutes * 6e4 + // 1000 * 60 hours * 36e5; // 1000 * 60 * 60 // Because of dateAddRemove treats 24 hours as different from a // day when working around DST, we need to store them separately this._days = days + weeks * 7; // It is impossible translate months into days without knowing // which months you are are talking about, so we have to store // it separately. this._months = months + years * 12; this._data = {}; this._bubble(); } /************************************ Helpers ************************************/ function extend(a, b) { for (var i in b) { if (b.hasOwnProperty(i)) { a[i] = b[i]; } } return a; } function absRound(number) { if (number < 0) { return Math.ceil(number); } else { return Math.floor(number); } } // left zero fill a number // see http://jsperf.com/left-zero-filling for performance comparison function leftZeroFill(number, targetLength) { var output = number + ''; while (output.length < targetLength) { output = '0' + output; } return output; } // helper function for _.addTime and _.subtractTime function addOrSubtractDurationFromMoment(mom, duration, isAdding, ignoreUpdateOffset) { var milliseconds = duration._milliseconds, days = duration._days, months = duration._months, minutes, hours, currentDate; if (milliseconds) { mom._d.setTime(+mom._d + milliseconds * isAdding); } // store the minutes and hours so we can restore them if (days || months) { minutes = mom.minute(); hours = mom.hour(); } if (days) { mom.date(mom.date() + days * isAdding); } if (months) { mom.month(mom.month() + months * isAdding); } if (milliseconds && !ignoreUpdateOffset) { moment.updateOffset(mom); } // restore the minutes and hours after possibly changing dst if (days || months) { mom.minute(minutes); mom.hour(hours); } } // check if is an array function isArray(input) { return Object.prototype.toString.call(input) === '[object Array]'; } // compare two arrays, return the number of differences function compareArrays(array1, array2) { var len = Math.min(array1.length, array2.length), lengthDiff = Math.abs(array1.length - array2.length), diffs = 0, i; for (i = 0; i < len; i++) { if (~~array1[i] !== ~~array2[i]) { diffs++; } } return diffs + lengthDiff; } function normalizeUnits(units) { return units ? unitAliases[units] || units.toLowerCase().replace(/(.)s$/, '$1') : units; } /************************************ Languages ************************************/ Language.prototype = { set : function (config) { var prop, i; for (i in config) { prop = config[i]; if (typeof prop === 'function') { this[i] = prop; } else { this['_' + i] = prop; } } }, _months : "January_February_March_April_May_June_July_August_September_October_November_December".split("_"), months : function (m) { return this._months[m.month()]; }, _monthsShort : "Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"), monthsShort : function (m) { return this._monthsShort[m.month()]; }, monthsParse : function (monthName) { var i, mom, regex; if (!this._monthsParse) { this._monthsParse = []; } for (i = 0; i < 12; i++) { // make the regex if we don't have it already if (!this._monthsParse[i]) { mom = moment([2000, i]); regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, ''); this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i'); } // test the regex if (this._monthsParse[i].test(monthName)) { return i; } } }, _weekdays : "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"), weekdays : function (m) { return this._weekdays[m.day()]; }, _weekdaysShort : "Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"), weekdaysShort : function (m) { return this._weekdaysShort[m.day()]; }, _weekdaysMin : "Su_Mo_Tu_We_Th_Fr_Sa".split("_"), weekdaysMin : function (m) { return this._weekdaysMin[m.day()]; }, weekdaysParse : function (weekdayName) { var i, mom, regex; if (!this._weekdaysParse) { this._weekdaysParse = []; } for (i = 0; i < 7; i++) { // make the regex if we don't have it already if (!this._weekdaysParse[i]) { mom = moment([2000, 1]).day(i); regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, ''); this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i'); } // test the regex if (this._weekdaysParse[i].test(weekdayName)) { return i; } } }, _longDateFormat : { LT : "h:mm A", L : "MM/DD/YYYY", LL : "MMMM D YYYY", LLL : "MMMM D YYYY LT", LLLL : "dddd, MMMM D YYYY LT" }, longDateFormat : function (key) { var output = this._longDateFormat[key]; if (!output && this._longDateFormat[key.toUpperCase()]) { output = this._longDateFormat[key.toUpperCase()].replace(/MMMM|MM|DD|dddd/g, function (val) { return val.slice(1); }); this._longDateFormat[key] = output; } return output; }, isPM : function (input) { return ((input + '').toLowerCase()[0] === 'p'); }, _meridiemParse : /[ap]\.?m?\.?/i, meridiem : function (hours, minutes, isLower) { if (hours > 11) { return isLower ? 'pm' : 'PM'; } else { return isLower ? 'am' : 'AM'; } }, _calendar : { sameDay : '[Today at] LT', nextDay : '[Tomorrow at] LT', nextWeek : 'dddd [at] LT', lastDay : '[Yesterday at] LT', lastWeek : '[Last] dddd [at] LT', sameElse : 'L' }, calendar : function (key, mom) { var output = this._calendar[key]; return typeof output === 'function' ? output.apply(mom) : output; }, _relativeTime : { future : "in %s", past : "%s ago", s : "a few seconds", m : "a minute", mm : "%d minutes", h : "an hour", hh : "%d hours", d : "a day", dd : "%d days", M : "a month", MM : "%d months", y : "a year", yy : "%d years" }, relativeTime : function (number, withoutSuffix, string, isFuture) { var output = this._relativeTime[string]; return (typeof output === 'function') ? output(number, withoutSuffix, string, isFuture) : output.replace(/%d/i, number); }, pastFuture : function (diff, output) { var format = this._relativeTime[diff > 0 ? 'future' : 'past']; return typeof format === 'function' ? format(output) : format.replace(/%s/i, output); }, ordinal : function (number) { return this._ordinal.replace("%d", number); }, _ordinal : "%d", preparse : function (string) { return string; }, postformat : function (string) { return string; }, week : function (mom) { return weekOfYear(mom, this._week.dow, this._week.doy).week; }, _week : { dow : 0, // Sunday is the first day of the week. doy : 6 // The week that contains Jan 1st is the first week of the year. } }; // Loads a language definition into the `languages` cache. The function // takes a key and optionally values. If not in the browser and no values // are provided, it will load the language file module. As a convenience, // this function also returns the language values. function loadLang(key, values) { values.abbr = key; if (!languages[key]) { languages[key] = new Language(); } languages[key].set(values); return languages[key]; } // Determines which language definition to use and returns it. // // With no parameters, it will return the global language. If you // pass in a language key, such as 'en', it will return the // definition for 'en', so long as 'en' has already been loaded using // moment.lang. function getLangDefinition(key) { if (!key) { return moment.fn._lang; } if (!languages[key] && hasModule) { try { require('./lang/' + key); } catch (e) { // call with no params to set to default return moment.fn._lang; } } return languages[key]; } /************************************ Formatting ************************************/ function removeFormattingTokens(input) { if (input.match(/\[.*\]/)) { return input.replace(/^\[|\]$/g, ""); } return input.replace(/\\/g, ""); } function makeFormatFunction(format) { var array = format.match(formattingTokens), i, length; for (i = 0, length = array.length; i < length; i++) { if (formatTokenFunctions[array[i]]) { array[i] = formatTokenFunctions[array[i]]; } else { array[i] = removeFormattingTokens(array[i]); } } return function (mom) { var output = ""; for (i = 0; i < length; i++) { output += array[i] instanceof Function ? array[i].call(mom, format) : array[i]; } return output; }; } // format date using native date object function formatMoment(m, format) { var i = 5; function replaceLongDateFormatTokens(input) { return m.lang().longDateFormat(input) || input; } while (i-- && localFormattingTokens.test(format)) { format = format.replace(localFormattingTokens, replaceLongDateFormatTokens); } if (!formatFunctions[format]) { formatFunctions[format] = makeFormatFunction(format); } return formatFunctions[format](m); } /************************************ Parsing ************************************/ // get the regex to find the next token function getParseRegexForToken(token, config) { switch (token) { case 'DDDD': return parseTokenThreeDigits; case 'YYYY': return parseTokenFourDigits; case 'YYYYY': return parseTokenSixDigits; case 'S': case 'SS': case 'SSS': case 'DDD': return parseTokenOneToThreeDigits; case 'MMM': case 'MMMM': case 'dd': case 'ddd': case 'dddd': return parseTokenWord; case 'a': case 'A': return getLangDefinition(config._l)._meridiemParse; case 'X': return parseTokenTimestampMs; case 'Z': case 'ZZ': return parseTokenTimezone; case 'T': return parseTokenT; case 'MM': case 'DD': case 'YY': case 'HH': case 'hh': case 'mm': case 'ss': case 'M': case 'D': case 'd': case 'H': case 'h': case 'm': case 's': return parseTokenOneOrTwoDigits; default : return new RegExp(token.replace('\\', '')); } } function timezoneMinutesFromString(string) { var tzchunk = (parseTokenTimezone.exec(string) || [])[0], parts = (tzchunk + '').match(parseTimezoneChunker) || ['-', 0, 0], minutes = +(parts[1] * 60) + ~~parts[2]; return parts[0] === '+' ? -minutes : minutes; } // function to convert string input to date function addTimeToArrayFromToken(token, input, config) { var a, datePartArray = config._a; switch (token) { // MONTH case 'M' : // fall through to MM case 'MM' : datePartArray[1] = (input == null) ? 0 : ~~input - 1; break; case 'MMM' : // fall through to MMMM case 'MMMM' : a = getLangDefinition(config._l).monthsParse(input); // if we didn't find a month name, mark the date as invalid. if (a != null) { datePartArray[1] = a; } else { config._isValid = false; } break; // DAY OF MONTH case 'D' : // fall through to DDDD case 'DD' : // fall through to DDDD case 'DDD' : // fall through to DDDD case 'DDDD' : if (input != null) { datePartArray[2] = ~~input; } break; // YEAR case 'YY' : datePartArray[0] = ~~input + (~~input > 68 ? 1900 : 2000); break; case 'YYYY' : case 'YYYYY' : datePartArray[0] = ~~input; break; // AM / PM case 'a' : // fall through to A case 'A' : config._isPm = getLangDefinition(config._l).isPM(input); break; // 24 HOUR case 'H' : // fall through to hh case 'HH' : // fall through to hh case 'h' : // fall through to hh case 'hh' : datePartArray[3] = ~~input; break; // MINUTE case 'm' : // fall through to mm case 'mm' : datePartArray[4] = ~~input; break; // SECOND case 's' : // fall through to ss case 'ss' : datePartArray[5] = ~~input; break; // MILLISECOND case 'S' : case 'SS' : case 'SSS' : datePartArray[6] = ~~ (('0.' + input) * 1000); break; // UNIX TIMESTAMP WITH MS case 'X': config._d = new Date(parseFloat(input) * 1000); break; // TIMEZONE case 'Z' : // fall through to ZZ case 'ZZ' : config._useUTC = true; config._tzm = timezoneMinutesFromString(input); break; } // if the input is null, the date is not valid if (input == null) { config._isValid = false; } } // convert an array to a date. // the array should mirror the parameters below // note: all values past the year are optional and will default to the lowest possible value. // [year, month, day , hour, minute, second, millisecond] function dateFromArray(config) { var i, date, input = []; if (config._d) { return; } for (i = 0; i < 7; i++) { config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i]; } // add the offsets to the time to be parsed so that we can have a clean array for checking isValid input[3] += ~~((config._tzm || 0) / 60); input[4] += ~~((config._tzm || 0) % 60); date = new Date(0); if (config._useUTC) { date.setUTCFullYear(input[0], input[1], input[2]); date.setUTCHours(input[3], input[4], input[5], input[6]); } else { date.setFullYear(input[0], input[1], input[2]); date.setHours(input[3], input[4], input[5], input[6]); } config._d = date; } // date from string and format string function makeDateFromStringAndFormat(config) { // This array is used to make a Date, either with `new Date` or `Date.UTC` var tokens = config._f.match(formattingTokens), string = config._i, i, parsedInput; config._a = []; for (i = 0; i < tokens.length; i++) { parsedInput = (getParseRegexForToken(tokens[i], config).exec(string) || [])[0]; if (parsedInput) { string = string.slice(string.indexOf(parsedInput) + parsedInput.length); } // don't parse if its not a known token if (formatTokenFunctions[tokens[i]]) { addTimeToArrayFromToken(tokens[i], parsedInput, config); } } // add remaining unparsed input to the string if (string) { config._il = string; } // handle am pm if (config._isPm && config._a[3] < 12) { config._a[3] += 12; } // if is 12 am, change hours to 0 if (config._isPm === false && config._a[3] === 12) { config._a[3] = 0; } // return dateFromArray(config); } // date from string and array of format strings function makeDateFromStringAndArray(config) { var tempConfig, tempMoment, bestMoment, scoreToBeat = 99, i, currentScore; for (i = 0; i < config._f.length; i++) { tempConfig = extend({}, config); tempConfig._f = config._f[i]; makeDateFromStringAndFormat(tempConfig); tempMoment = new Moment(tempConfig); currentScore = compareArrays(tempConfig._a, tempMoment.toArray()); // if there is any input that was not parsed // add a penalty for that format if (tempMoment._il) { currentScore += tempMoment._il.length; } if (currentScore < scoreToBeat) { scoreToBeat = currentScore; bestMoment = tempMoment; } } extend(config, bestMoment); } // date from iso format function makeDateFromString(config) { var i, string = config._i, match = isoRegex.exec(string); if (match) { // match[2] should be "T" or undefined config._f = 'YYYY-MM-DD' + (match[2] || " "); for (i = 0; i < 4; i++) { if (isoTimes[i][1].exec(string)) { config._f += isoTimes[i][0]; break; } } if (parseTokenTimezone.exec(string)) { config._f += " Z"; } makeDateFromStringAndFormat(config); } else { config._d = new Date(string); } } function makeDateFromInput(config) { var input = config._i, matched = aspNetJsonRegex.exec(input); if (input === undefined) { config._d = new Date(); } else if (matched) { config._d = new Date(+matched[1]); } else if (typeof input === 'string') { makeDateFromString(config); } else if (isArray(input)) { config._a = input.slice(0); dateFromArray(config); } else { config._d = input instanceof Date ? new Date(+input) : new Date(input); } } /************************************ Relative Time ************************************/ // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize function substituteTimeAgo(string, number, withoutSuffix, isFuture, lang) { return lang.relativeTime(number || 1, !!withoutSuffix, string, isFuture); } function relativeTime(milliseconds, withoutSuffix, lang) { var seconds = round(Math.abs(milliseconds) / 1000), minutes = round(seconds / 60), hours = round(minutes / 60), days = round(hours / 24), years = round(days / 365), args = seconds < 45 && ['s', seconds] || minutes === 1 && ['m'] || minutes < 45 && ['mm', minutes] || hours === 1 && ['h'] || hours < 22 && ['hh', hours] || days === 1 && ['d'] || days <= 25 && ['dd', days] || days <= 45 && ['M'] || days < 345 && ['MM', round(days / 30)] || years === 1 && ['y'] || ['yy', years]; args[2] = withoutSuffix; args[3] = milliseconds > 0; args[4] = lang; return substituteTimeAgo.apply({}, args); } /************************************ Week of Year ************************************/ // firstDayOfWeek 0 = sun, 6 = sat // the day of the week that starts the week // (usually sunday or monday) // firstDayOfWeekOfYear 0 = sun, 6 = sat // the first week is the week that contains the first // of this day of the week // (eg. ISO weeks use thursday (4)) function weekOfYear(mom, firstDayOfWeek, firstDayOfWeekOfYear) { var end = firstDayOfWeekOfYear - firstDayOfWeek, daysToDayOfWeek = firstDayOfWeekOfYear - mom.day(), adjustedMoment; if (daysToDayOfWeek > end) { daysToDayOfWeek -= 7; } if (daysToDayOfWeek < end - 7) { daysToDayOfWeek += 7; } adjustedMoment = moment(mom).add('d', daysToDayOfWeek); return { week: Math.ceil(adjustedMoment.dayOfYear() / 7), year: adjustedMoment.year() }; } /************************************ Top Level Functions ************************************/ function makeMoment(config) { var input = config._i, format = config._f; if (input === null || input === '') { return null; } if (typeof input === 'string') { config._i = input = getLangDefinition().preparse(input); } if (moment.isMoment(input)) { config = extend({}, input); config._d = new Date(+input._d); } else if (format) { if (isArray(format)) { makeDateFromStringAndArray(config); } else { makeDateFromStringAndFormat(config); } } else { makeDateFromInput(config); } return new Moment(config); } moment = function (input, format, lang) { return makeMoment({ _i : input, _f : format, _l : lang, _isUTC : false }); }; // creating with utc moment.utc = function (input, format, lang) { return makeMoment({ _useUTC : true, _isUTC : true, _l : lang, _i : input, _f : format }); }; // creating with unix timestamp (in seconds) moment.unix = function (input) { return moment(input * 1000); }; // duration moment.duration = function (input, key) { var isDuration = moment.isDuration(input), isNumber = (typeof input === 'number'), duration = (isDuration ? input._input : (isNumber ? {} : input)), matched = aspNetTimeSpanJsonRegex.exec(input), sign, ret; if (isNumber) { if (key) { duration[key] = input; } else { duration.milliseconds = input; } } else if (matched) { sign = (matched[1] === "-") ? -1 : 1; duration = { y: 0, d: ~~matched[2] * sign, h: ~~matched[3] * sign, m: ~~matched[4] * sign, s: ~~matched[5] * sign, ms: ~~matched[6] * sign }; } ret = new Duration(duration); if (isDuration && input.hasOwnProperty('_lang')) { ret._lang = input._lang; } return ret; }; // version number moment.version = VERSION; // default format moment.defaultFormat = isoFormat; // This function will be called whenever a moment is mutated. // It is intended to keep the offset in sync with the timezone. moment.updateOffset = function () {}; // This function will load languages and then set the global language. If // no arguments are passed in, it will simply return the current global // language key. moment.lang = function (key, values) { if (!key) { return moment.fn._lang._abbr; } if (values) { loadLang(key, values); } else if (!languages[key]) { getLangDefinition(key); } moment.duration.fn._lang = moment.fn._lang = getLangDefinition(key); }; // returns language data moment.langData = function (key) { if (key && key._lang && key._lang._abbr) { key = key._lang._abbr; } return getLangDefinition(key); }; // compare moment object moment.isMoment = function (obj) { return obj instanceof Moment; }; // for typechecking Duration objects moment.isDuration = function (obj) { return obj instanceof Duration; }; /************************************ Moment Prototype ************************************/ moment.fn = Moment.prototype = { clone : function () { return moment(this); }, valueOf : function () { return +this._d + ((this._offset || 0) * 60000); }, unix : function () { return Math.floor(+this / 1000); }, toString : function () { return this.format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ"); }, toDate : function () { return this._offset ? new Date(+this) : this._d; }, toISOString : function () { return formatMoment(moment(this).utc(), 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]'); }, toArray : function () { var m = this; return [ m.year(), m.month(), m.date(), m.hours(), m.minutes(), m.seconds(), m.milliseconds() ]; }, isValid : function () { if (this._isValid == null) { if (this._a) { this._isValid = !compareArrays(this._a, (this._isUTC ? moment.utc(this._a) : moment(this._a)).toArray()); } else { this._isValid = !isNaN(this._d.getTime()); } } return !!this._isValid; }, utc : function () { return this.zone(0); }, local : function () { this.zone(0); this._isUTC = false; return this; }, format : function (inputString) { var output = formatMoment(this, inputString || moment.defaultFormat); return this.lang().postformat(output); }, add : function (input, val) { var dur; // switch args to support add('s', 1) and add(1, 's') if (typeof input === 'string') { dur = moment.duration(+val, input); } else { dur = moment.duration(input, val); } addOrSubtractDurationFromMoment(this, dur, 1); return this; }, subtract : function (input, val) { var dur; // switch args to support subtract('s', 1) and subtract(1, 's') if (typeof input === 'string') { dur = moment.duration(+val, input); } else { dur = moment.duration(input, val); } addOrSubtractDurationFromMoment(this, dur, -1); return this; }, diff : function (input, units, asFloat) { var that = this._isUTC ? moment(input).zone(this._offset || 0) : moment(input).local(), zoneDiff = (this.zone() - that.zone()) * 6e4, diff, output; units = normalizeUnits(units); if (units === 'year' || units === 'month') { // average number of days in the months in the given dates diff = (this.daysInMonth() + that.daysInMonth()) * 432e5; // 24 * 60 * 60 * 1000 / 2 // difference in months output = ((this.year() - that.year()) * 12) + (this.month() - that.month()); // adjust by taking difference in days, average number of days // and dst in the given months. output += ((this - moment(this).startOf('month')) - (that - moment(that).startOf('month'))) / diff; // same as above but with zones, to negate all dst output -= ((this.zone() - moment(this).startOf('month').zone()) - (that.zone() - moment(that).startOf('month').zone())) * 6e4 / diff; if (units === 'year') { output = output / 12; } } else { diff = (this - that); output = units === 'second' ? diff / 1e3 : // 1000 units === 'minute' ? diff / 6e4 : // 1000 * 60 units === 'hour' ? diff / 36e5 : // 1000 * 60 * 60 units === 'day' ? (diff - zoneDiff) / 864e5 : // 1000 * 60 * 60 * 24, negate dst units === 'week' ? (diff - zoneDiff) / 6048e5 : // 1000 * 60 * 60 * 24 * 7, negate dst diff; } return asFloat ? output : absRound(output); }, from : function (time, withoutSuffix) { return moment.duration(this.diff(time)).lang(this.lang()._abbr).humanize(!withoutSuffix); }, fromNow : function (withoutSuffix) { return this.from(moment(), withoutSuffix); }, calendar : function () { var diff = this.diff(moment().startOf('day'), 'days', true), format = diff < -6 ? 'sameElse' : diff < -1 ? 'lastWeek' : diff < 0 ? 'lastDay' : diff < 1 ? 'sameDay' : diff < 2 ? 'nextDay' : diff < 7 ? 'nextWeek' : 'sameElse'; return this.format(this.lang().calendar(format, this)); }, isLeapYear : function () { var year = this.year(); return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; }, isDST : function () { return (this.zone() < this.clone().month(0).zone() || this.zone() < this.clone().month(5).zone()); }, day : function (input) { var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay(); if (input != null) { if (typeof input === 'string') { input = this.lang().weekdaysParse(input); if (typeof input !== 'number') { return this; } } return this.add({ d : input - day }); } else { return day; } }, month : function (input) { var utc = this._isUTC ? 'UTC' : '', dayOfMonth, daysInMonth; if (input != null) { if (typeof input === 'string') { input = this.lang().monthsParse(input); if (typeof input !== 'number') { return this; } } dayOfMonth = this.date(); this.date(1); this._d['set' + utc + 'Month'](input); this.date(Math.min(dayOfMonth, this.daysInMonth())); moment.updateOffset(this); return this; } else { return this._d['get' + utc + 'Month'](); } }, startOf: function (units) { units = normalizeUnits(units); // the following switch intentionally omits break keywords // to utilize falling through the cases. switch (units) { case 'year': this.month(0); /* falls through */ case 'month': this.date(1); /* falls through */ case 'week': case 'day': this.hours(0); /* falls through */ case 'hour': this.minutes(0); /* falls through */ case 'minute': this.seconds(0); /* falls through */ case 'second': this.milliseconds(0); /* falls through */ } // weeks are a special case if (units === 'week') { this.weekday(0); } return this; }, endOf: function (units) { return this.startOf(units).add(units, 1).subtract('ms', 1); }, isAfter: function (input, units) { units = typeof units !== 'undefined' ? units : 'millisecond'; return +this.clone().startOf(units) > +moment(input).startOf(units); }, isBefore: function (input, units) { units = typeof units !== 'undefined' ? units : 'millisecond'; return +this.clone().startOf(units) < +moment(input).startOf(units); }, isSame: function (input, units) { units = typeof units !== 'undefined' ? units : 'millisecond'; return +this.clone().startOf(units) === +moment(input).startOf(units); }, min: function (other) { other = moment.apply(null, arguments); return other < this ? this : other; }, max: function (other) { other = moment.apply(null, arguments); return other > this ? this : other; }, zone : function (input) { var offset = this._offset || 0; if (input != null) { if (typeof input === "string") { input = timezoneMinutesFromString(input); } if (Math.abs(input) < 16) { input = input * 60; } this._offset = input; this._isUTC = true; if (offset !== input) { addOrSubtractDurationFromMoment(this, moment.duration(offset - input, 'm'), 1, true); } } else { return this._isUTC ? offset : this._d.getTimezoneOffset(); } return this; }, zoneAbbr : function () { return this._isUTC ? "UTC" : ""; }, zoneName : function () { return this._isUTC ? "Coordinated Universal Time" : ""; }, daysInMonth : function () { return moment.utc([this.year(), this.month() + 1, 0]).date(); }, dayOfYear : function (input) { var dayOfYear = round((moment(this).startOf('day') - moment(this).startOf('year')) / 864e5) + 1; return input == null ? dayOfYear : this.add("d", (input - dayOfYear)); }, weekYear : function (input) { var year = weekOfYear(this, this.lang()._week.dow, this.lang()._week.doy).year; return input == null ? year : this.add("y", (input - year)); }, isoWeekYear : function (input) { var year = weekOfYear(this, 1, 4).year; return input == null ? year : this.add("y", (input - year)); }, week : function (input) { var week = this.lang().week(this); return input == null ? week : this.add("d", (input - week) * 7); }, isoWeek : function (input) { var week = weekOfYear(this, 1, 4).week; return input == null ? week : this.add("d", (input - week) * 7); }, weekday : function (input) { var weekday = (this._d.getDay() + 7 - this.lang()._week.dow) % 7; return input == null ? weekday : this.add("d", input - weekday); }, isoWeekday : function (input) { // behaves the same as moment#day except // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6) // as a setter, sunday should belong to the previous week. return input == null ? this.day() || 7 : this.day(this.day() % 7 ? input : input - 7); }, // If passed a language key, it will set the language for this // instance. Otherwise, it will return the language configuration // variables for this instance. lang : function (key) { if (key === undefined) { return this._lang; } else { this._lang = getLangDefinition(key); return this; } } }; // helper for adding shortcuts function makeGetterAndSetter(name, key) { moment.fn[name] = moment.fn[name + 's'] = function (input) { var utc = this._isUTC ? 'UTC' : ''; if (input != null) { this._d['set' + utc + key](input); moment.updateOffset(this); return this; } else { return this._d['get' + utc + key](); } }; } // loop through and add shortcuts (Month, Date, Hours, Minutes, Seconds, Milliseconds) for (i = 0; i < proxyGettersAndSetters.length; i ++) { makeGetterAndSetter(proxyGettersAndSetters[i].toLowerCase().replace(/s$/, ''), proxyGettersAndSetters[i]); } // add shortcut for year (uses different syntax than the getter/setter 'year' == 'FullYear') makeGetterAndSetter('year', 'FullYear'); // add plural methods moment.fn.days = moment.fn.day; moment.fn.months = moment.fn.month; moment.fn.weeks = moment.fn.week; moment.fn.isoWeeks = moment.fn.isoWeek; // add aliased format methods moment.fn.toJSON = moment.fn.toISOString; /************************************ Duration Prototype ************************************/ moment.duration.fn = Duration.prototype = { _bubble : function () { var milliseconds = this._milliseconds, days = this._days, months = this._months, data = this._data, seconds, minutes, hours, years; // The following code bubbles up values, see the tests for // examples of what that means. data.milliseconds = milliseconds % 1000; seconds = absRound(milliseconds / 1000); data.seconds = seconds % 60; minutes = absRound(seconds / 60); data.minutes = minutes % 60; hours = absRound(minutes / 60); data.hours = hours % 24; days += absRound(hours / 24); data.days = days % 30; months += absRound(days / 30); data.months = months % 12; years = absRound(months / 12); data.years = years; }, weeks : function () { return absRound(this.days() / 7); }, valueOf : function () { return this._milliseconds + this._days * 864e5 + (this._months % 12) * 2592e6 + ~~(this._months / 12) * 31536e6; }, humanize : function (withSuffix) { var difference = +this, output = relativeTime(difference, !withSuffix, this.lang()); if (withSuffix) { output = this.lang().pastFuture(difference, output); } return this.lang().postformat(output); }, add : function (input, val) { // supports only 2.0-style add(1, 's') or add(moment) var dur = moment.duration(input, val); this._milliseconds += dur._milliseconds; this._days += dur._days; this._months += dur._months; this._bubble(); return this; }, subtract : function (input, val) { var dur = moment.duration(input, val); this._milliseconds -= dur._milliseconds; this._days -= dur._days; this._months -= dur._months; this._bubble(); return this; }, get : function (units) { units = normalizeUnits(units); return this[units.toLowerCase() + 's'](); }, as : function (units) { units = normalizeUnits(units); return this['as' + units.charAt(0).toUpperCase() + units.slice(1) + 's'](); }, lang : moment.fn.lang }; function makeDurationGetter(name) { moment.duration.fn[name] = function () { return this._data[name]; }; } function makeDurationAsGetter(name, factor) { moment.duration.fn['as' + name] = function () { return +this / factor; }; } for (i in unitMillisecondFactors) { if (unitMillisecondFactors.hasOwnProperty(i)) { makeDurationAsGetter(i, unitMillisecondFactors[i]); makeDurationGetter(i.toLowerCase()); } } makeDurationAsGetter('Weeks', 6048e5); moment.duration.fn.asMonths = function () { return (+this - this.years() * 31536e6) / 2592e6 + this.years() * 12; }; /************************************ Default Lang ************************************/ // Set default language, other languages will inherit from English. moment.lang('en', { ordinal : function (number) { var b = number % 10, output = (~~ (number % 100 / 10) === 1) ? 'th' : (b === 1) ? 'st' : (b === 2) ? 'nd' : (b === 3) ? 'rd' : 'th'; return number + output; } }); /************************************ Exposing Moment ************************************/ // CommonJS module is defined if (hasModule) { module.exports = moment; } /*global ender:false */ if (typeof ender === 'undefined') { // here, `this` means `window` in the browser, or `global` on the server // add `moment` as a global object via a string identifier, // for Closure Compiler "advanced" mode this['moment'] = moment; } /*global define:false */ if (typeof define === "function" && define.amd) { define("moment", [], function () { return moment; }); } }).call(this); /*! * iCheck v0.8.5 jQuery plugin, http://git.io/uhUPMA */ (function(f,m,z,u,k,r,l,n,D,t,v,s){function A(a,c,j){var d=a[0],b=/ble/.test(j)?r:k;active="update"==j?{checked:d[k],disabled:d[r]}:d[b];if(/^ch|di/.test(j)&&!active)w(a,b);else if(/^un|en/.test(j)&&active)x(a,b);else if("update"==j)for(var b in active)active[b]?w(a,b,!0):x(a,b,!0);else if(!c||"toggle"==j)c||a.trigger("ifClicked"),active?d[l]!==u&&x(a,b):w(a,b)}function w(a,c,j){var d=a[0],b=a.parent(),E=c==r?"enabled":"un"+k,n=e(a,E+g(d[l])),h=e(a,c+g(d[l]));if(!0!==d[c]&&!j&&(d[c]=!0,a.trigger("ifChanged").trigger("if"+ g(c)),c==k&&d[l]==u&&d.name)){j=a.closest("form");var p='input[name="'+d.name+'"]',p=j.length?j.find(p):f(p);p.each(function(){this!==d&&f(this).data(m)&&x(f(this),c)})}d[r]&&e(a,s,!0)&&b.find("."+m+"-helper").css(s,"default");b[t](h||e(a,c));b[v](n||e(a,E)||"")}function x(a,c,j){var d=a[0],b=a.parent(),f=c==r?"enabled":"un"+k,n=e(a,f+g(d[l])),h=e(a,c+g(d[l]));!1!==d[c]&&!j&&(d[c]=!1,a.trigger("ifChanged").trigger("if"+g(f)));!d[r]&&e(a,s,!0)&&b.find("."+m+"-helper").css(s,"pointer");b[v](h||e(a, c)||"");b[t](n||e(a,f))}function F(a,c){a.data(m)&&(a.parent().html(a.attr("style",a.data(m).s||"").trigger(c||"")),a.off(".i").unwrap(),f('label[for="'+a[0].id+'"]').add(a.closest("label")).off(".i"))}function e(a,c,f){if(a.data(m))return a.data(m).o[c+(f?"":"Class")]}function g(a){return a.charAt(0).toUpperCase()+a.slice(1)}f.fn[m]=function(a,c){var j=navigator.userAgent,d=/ipad|iphone|ipod/i.test(j),b=":"+z+", :"+u,e=f(),g=function(a){a.each(function(){var a=f(this);e=a.is(b)?e.add(a):e.add(a.find(b))})}; if(/^(check|uncheck|toggle|disable|enable|update|destroy)$/.test(a))return g(this),e.each(function(){var d=f(this);"destroy"==a?F(d,"ifDestroyed"):A(d,!0,a);f.isFunction(c)&&c()});if("object"==typeof a||!a){var h=f.extend({checkedClass:k,disabledClass:r,labelHover:!0},a),p=h.handle,s=h.hoverClass||"hover",I=h.focusClass||"focus",G=h.activeClass||"active",H=!!h.labelHover,C=h.labelHoverClass||"hover",y=(""+h.increaseArea).replace("%","")|0;if(p==z||p==u)b=":"+p;-50>y&&(y=-50);g(this);return e.each(function(){var a= f(this);F(a);var c=this,b=c.id,e=-y+"%",g=100+2*y+"%",g={position:"absolute",top:e,left:e,display:"block",width:g,height:g,margin:0,padding:0,background:"#fff",border:0,opacity:0},e=d||/android|blackberry|windows phone|opera mini/i.test(j)?{position:"absolute",visibility:"hidden"}:y?g:{position:"absolute",opacity:0},p=c[l]==z?h.checkboxClass||"i"+z:h.radioClass||"i"+u,B=f('label[for="'+b+'"]').add(a.closest("label")),q=a.wrap('<div class="'+p+'"/>').trigger("ifCreated").parent().append(h.insert), g=f('<ins class="'+m+'-helper"/>').css(g).appendTo(q);a.data(m,{o:h,s:a.attr("style")}).css(e);h.inheritClass&&q[t](c.className);h.inheritID&&b&&q.attr("id",m+"-"+b);"static"==q.css("position")&&q.css("position","relative");A(a,!0,"update");if(B.length)B.on(n+".i mouseenter.i mouseleave.i "+D,function(b){var e=b[l],g=f(this);if(!c[r])if(e==n?A(a,!1,!0):H&&(/ve|nd/.test(e)?(q[v](s),g[v](C)):(q[t](s),g[t](C))),d)b.stopPropagation();else return!1});a.on(n+".i focus.i blur.i keyup.i keydown.i keypress.i", function(b){var d=b[l];b=b.keyCode;if(d==n)return!1;if("keydown"==d&&32==b)return c[l]==u&&c[k]||(c[k]?x(a,k):w(a,k)),!1;if("keyup"==d&&c[l]==u)!c[k]&&w(a,k);else if(/us|ur/.test(d))q["blur"==d?v:t](I)});g.on(n+" mousedown mouseup mouseover mouseout "+D,function(b){var e=b[l],f=/wn|up/.test(e)?G:s;if(!c[r]){if(e==n)A(a,!1,!0);else{if(/wn|er|in/.test(e))q[t](f);else q[v](f+" "+G);if(B.length&&H&&f==s)B[/ut|nd/.test(e)?v:t](C)}if(d)b.stopPropagation();else return!1}})})}return this}})(jQuery,"iCheck", "checkbox","radio","checked","disabled","type","click","touchbegin.i touchend.i","addClass","removeClass","cursor"); /* * jQuery UI Widget 1.10.1+amd * https://github.com/blueimp/jQuery-File-Upload * * Copyright 2013 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/jQuery.widget/ */ (function (factory) { if (typeof define === "function" && define.amd) { // Register as an anonymous AMD module: define(["jquery"], factory); } else { // Browser globals: factory(jQuery); } }(function( $, undefined ) { var uuid = 0, slice = Array.prototype.slice, _cleanData = $.cleanData; $.cleanData = function( elems ) { for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { try { $( elem ).triggerHandler( "remove" ); // http://bugs.jquery.com/ticket/8235 } catch( e ) {} } _cleanData( elems ); }; $.widget = function( name, base, prototype ) { var fullName, existingConstructor, constructor, basePrototype, // proxiedPrototype allows the provided prototype to remain unmodified // so that it can be used as a mixin for multiple widgets (#8876) proxiedPrototype = {}, namespace = name.split( "." )[ 0 ]; name = name.split( "." )[ 1 ]; fullName = namespace + "-" + name; if ( !prototype ) { prototype = base; base = $.Widget; } // create selector for plugin $.expr[ ":" ][ fullName.toLowerCase() ] = function( elem ) { return !!$.data( elem, fullName ); }; $[ namespace ] = $[ namespace ] || {}; existingConstructor = $[ namespace ][ name ]; constructor = $[ namespace ][ name ] = function( options, element ) { // allow instantiation without "new" keyword if ( !this._createWidget ) { return new constructor( options, element ); } // allow instantiation without initializing for simple inheritance // must use "new" keyword (the code above always passes args) if ( arguments.length ) { this._createWidget( options, element ); } }; // extend with the existing constructor to carry over any static properties $.extend( constructor, existingConstructor, { version: prototype.version, // copy the object used to create the prototype in case we need to // redefine the widget later _proto: $.extend( {}, prototype ), // track widgets that inherit from this widget in case this widget is // redefined after a widget inherits from it _childConstructors: [] }); basePrototype = new base(); // we need to make the options hash a property directly on the new instance // otherwise we'll modify the options hash on the prototype that we're // inheriting from basePrototype.options = $.widget.extend( {}, basePrototype.options ); $.each( prototype, function( prop, value ) { if ( !$.isFunction( value ) ) { proxiedPrototype[ prop ] = value; return; } proxiedPrototype[ prop ] = (function() { var _super = function() { return base.prototype[ prop ].apply( this, arguments ); }, _superApply = function( args ) { return base.prototype[ prop ].apply( this, args ); }; return function() { var __super = this._super, __superApply = this._superApply, returnValue; this._super = _super; this._superApply = _superApply; returnValue = value.apply( this, arguments ); this._super = __super; this._superApply = __superApply; return returnValue; }; })(); }); constructor.prototype = $.widget.extend( basePrototype, { // TODO: remove support for widgetEventPrefix // always use the name + a colon as the prefix, e.g., draggable:start // don't prefix for widgets that aren't DOM-based widgetEventPrefix: existingConstructor ? basePrototype.widgetEventPrefix : name }, proxiedPrototype, { constructor: constructor, namespace: namespace, widgetName: name, widgetFullName: fullName }); // If this widget is being redefined then we need to find all widgets that // are inheriting from it and redefine all of them so that they inherit from // the new version of this widget. We're essentially trying to replace one // level in the prototype chain. if ( existingConstructor ) { $.each( existingConstructor._childConstructors, function( i, child ) { var childPrototype = child.prototype; // redefine the child widget using the same prototype that was // originally used, but inherit from the new version of the base $.widget( childPrototype.namespace + "." + childPrototype.widgetName, constructor, child._proto ); }); // remove the list of existing child constructors from the old constructor // so the old child constructors can be garbage collected delete existingConstructor._childConstructors; } else { base._childConstructors.push( constructor ); } $.widget.bridge( name, constructor ); }; $.widget.extend = function( target ) { var input = slice.call( arguments, 1 ), inputIndex = 0, inputLength = input.length, key, value; for ( ; inputIndex < inputLength; inputIndex++ ) { for ( key in input[ inputIndex ] ) { value = input[ inputIndex ][ key ]; if ( input[ inputIndex ].hasOwnProperty( key ) && value !== undefined ) { // Clone objects if ( $.isPlainObject( value ) ) { target[ key ] = $.isPlainObject( target[ key ] ) ? $.widget.extend( {}, target[ key ], value ) : // Don't extend strings, arrays, etc. with objects $.widget.extend( {}, value ); // Copy everything else by reference } else { target[ key ] = value; } } } } return target; }; $.widget.bridge = function( name, object ) { var fullName = object.prototype.widgetFullName || name; $.fn[ name ] = function( options ) { var isMethodCall = typeof options === "string", args = slice.call( arguments, 1 ), returnValue = this; // allow multiple hashes to be passed on init options = !isMethodCall && args.length ? $.widget.extend.apply( null, [ options ].concat(args) ) : options; if ( isMethodCall ) { this.each(function() { var methodValue, instance = $.data( this, fullName ); if ( !instance ) { return $.error( "cannot call methods on " + name + " prior to initialization; " + "attempted to call method '" + options + "'" ); } if ( !$.isFunction( instance[options] ) || options.charAt( 0 ) === "_" ) { return $.error( "no such method '" + options + "' for " + name + " widget instance" ); } methodValue = instance[ options ].apply( instance, args ); if ( methodValue !== instance && methodValue !== undefined ) { returnValue = methodValue && methodValue.jquery ? returnValue.pushStack( methodValue.get() ) : methodValue; return false; } }); } else { this.each(function() { var instance = $.data( this, fullName ); if ( instance ) { instance.option( options || {} )._init(); } else { $.data( this, fullName, new object( options, this ) ); } }); } return returnValue; }; }; $.Widget = function( /* options, element */ ) {}; $.Widget._childConstructors = []; $.Widget.prototype = { widgetName: "widget", widgetEventPrefix: "", defaultElement: "<div>", options: { disabled: false, // callbacks create: null }, _createWidget: function( options, element ) { element = $( element || this.defaultElement || this )[ 0 ]; this.element = $( element ); this.uuid = uuid++; this.eventNamespace = "." + this.widgetName + this.uuid; this.options = $.widget.extend( {}, this.options, this._getCreateOptions(), options ); this.bindings = $(); this.hoverable = $(); this.focusable = $(); if ( element !== this ) { $.data( element, this.widgetFullName, this ); this._on( true, this.element, { remove: function( event ) { if ( event.target === element ) { this.destroy(); } } }); this.document = $( element.style ? // element within the document element.ownerDocument : // element is window or document element.document || element ); this.window = $( this.document[0].defaultView || this.document[0].parentWindow ); } this._create(); this._trigger( "create", null, this._getCreateEventData() ); this._init(); }, _getCreateOptions: $.noop, _getCreateEventData: $.noop, _create: $.noop, _init: $.noop, destroy: function() { this._destroy(); // we can probably remove the unbind calls in 2.0 // all event bindings should go through this._on() this.element .unbind( this.eventNamespace ) // 1.9 BC for #7810 // TODO remove dual storage .removeData( this.widgetName ) .removeData( this.widgetFullName ) // support: jquery <1.6.3 // http://bugs.jquery.com/ticket/9413 .removeData( $.camelCase( this.widgetFullName ) ); this.widget() .unbind( this.eventNamespace ) .removeAttr( "aria-disabled" ) .removeClass( this.widgetFullName + "-disabled " + "ui-state-disabled" ); // clean up events and states this.bindings.unbind( this.eventNamespace ); this.hoverable.removeClass( "ui-state-hover" ); this.focusable.removeClass( "ui-state-focus" ); }, _destroy: $.noop, widget: function() { return this.element; }, option: function( key, value ) { var options = key, parts, curOption, i; if ( arguments.length === 0 ) { // don't return a reference to the internal hash return $.widget.extend( {}, this.options ); } if ( typeof key === "string" ) { // handle nested keys, e.g., "foo.bar" => { foo: { bar: ___ } } options = {}; parts = key.split( "." ); key = parts.shift(); if ( parts.length ) { curOption = options[ key ] = $.widget.extend( {}, this.options[ key ] ); for ( i = 0; i < parts.length - 1; i++ ) { curOption[ parts[ i ] ] = curOption[ parts[ i ] ] || {}; curOption = curOption[ parts[ i ] ]; } key = parts.pop(); if ( value === undefined ) { return curOption[ key ] === undefined ? null : curOption[ key ]; } curOption[ key ] = value; } else { if ( value === undefined ) { return this.options[ key ] === undefined ? null : this.options[ key ]; } options[ key ] = value; } } this._setOptions( options ); return this; }, _setOptions: function( options ) { var key; for ( key in options ) { this._setOption( key, options[ key ] ); } return this; }, _setOption: function( key, value ) { this.options[ key ] = value; if ( key === "disabled" ) { this.widget() .toggleClass( this.widgetFullName + "-disabled ui-state-disabled", !!value ) .attr( "aria-disabled", value ); this.hoverable.removeClass( "ui-state-hover" ); this.focusable.removeClass( "ui-state-focus" ); } return this; }, enable: function() { return this._setOption( "disabled", false ); }, disable: function() { return this._setOption( "disabled", true ); }, _on: function( suppressDisabledCheck, element, handlers ) { var delegateElement, instance = this; // no suppressDisabledCheck flag, shuffle arguments if ( typeof suppressDisabledCheck !== "boolean" ) { handlers = element; element = suppressDisabledCheck; suppressDisabledCheck = false; } // no element argument, shuffle and use this.element if ( !handlers ) { handlers = element; element = this.element; delegateElement = this.widget(); } else { // accept selectors, DOM elements element = delegateElement = $( element ); this.bindings = this.bindings.add( element ); } $.each( handlers, function( event, handler ) { function handlerProxy() { // allow widgets to customize the disabled handling // - disabled as an array instead of boolean // - disabled class as method for disabling individual parts if ( !suppressDisabledCheck && ( instance.options.disabled === true || $( this ).hasClass( "ui-state-disabled" ) ) ) { return; } return ( typeof handler === "string" ? instance[ handler ] : handler ) .apply( instance, arguments ); } // copy the guid so direct unbinding works if ( typeof handler !== "string" ) { handlerProxy.guid = handler.guid = handler.guid || handlerProxy.guid || $.guid++; } var match = event.match( /^(\w+)\s*(.*)$/ ), eventName = match[1] + instance.eventNamespace, selector = match[2]; if ( selector ) { delegateElement.delegate( selector, eventName, handlerProxy ); } else { element.bind( eventName, handlerProxy ); } }); }, _off: function( element, eventName ) { eventName = (eventName || "").split( " " ).join( this.eventNamespace + " " ) + this.eventNamespace; element.unbind( eventName ).undelegate( eventName ); }, _delay: function( handler, delay ) { function handlerProxy() { return ( typeof handler === "string" ? instance[ handler ] : handler ) .apply( instance, arguments ); } var instance = this; return setTimeout( handlerProxy, delay || 0 ); }, _hoverable: function( element ) { this.hoverable = this.hoverable.add( element ); this._on( element, { mouseenter: function( event ) { $( event.currentTarget ).addClass( "ui-state-hover" ); }, mouseleave: function( event ) { $( event.currentTarget ).removeClass( "ui-state-hover" ); } }); }, _focusable: function( element ) { this.focusable = this.focusable.add( element ); this._on( element, { focusin: function( event ) { $( event.currentTarget ).addClass( "ui-state-focus" ); }, focusout: function( event ) { $( event.currentTarget ).removeClass( "ui-state-focus" ); } }); }, _trigger: function( type, event, data ) { var prop, orig, callback = this.options[ type ]; data = data || {}; event = $.Event( event ); event.type = ( type === this.widgetEventPrefix ? type : this.widgetEventPrefix + type ).toLowerCase(); // the original event may come from any element // so we need to reset the target on the new event event.target = this.element[ 0 ]; // copy original event properties over to the new event orig = event.originalEvent; if ( orig ) { for ( prop in orig ) { if ( !( prop in event ) ) { event[ prop ] = orig[ prop ]; } } } this.element.trigger( event, data ); return !( $.isFunction( callback ) && callback.apply( this.element[0], [ event ].concat( data ) ) === false || event.isDefaultPrevented() ); } }; $.each( { show: "fadeIn", hide: "fadeOut" }, function( method, defaultEffect ) { $.Widget.prototype[ "_" + method ] = function( element, options, callback ) { if ( typeof options === "string" ) { options = { effect: options }; } var hasOptions, effectName = !options ? method : options === true || typeof options === "number" ? defaultEffect : options.effect || defaultEffect; options = options || {}; if ( typeof options === "number" ) { options = { duration: options }; } hasOptions = !$.isEmptyObject( options ); options.complete = callback; if ( options.delay ) { element.delay( options.delay ); } if ( hasOptions && $.effects && $.effects.effect[ effectName ] ) { element[ method ]( options ); } else if ( effectName !== method && element[ effectName ] ) { element[ effectName ]( options.duration, options.easing, callback ); } else { element.queue(function( next ) { $( this )[ method ](); if ( callback ) { callback.call( element[ 0 ] ); } next(); }); } }; }); })); /* * jQuery Iframe Transport Plugin 1.6.1 * https://github.com/blueimp/jQuery-File-Upload * * Copyright 2011, Sebastian Tschan * https://blueimp.net * * Licensed under the MIT license: * http://www.opensource.org/licenses/MIT */ /*jslint unparam: true, nomen: true */ /*global define, window, document */ (function (factory) { 'use strict'; if (typeof define === 'function' && define.amd) { // Register as an anonymous AMD module: define(['jquery'], factory); } else { // Browser globals: factory(window.jQuery); } }(function ($) { 'use strict'; // Helper variable to create unique names for the transport iframes: var counter = 0; // The iframe transport accepts three additional options: // options.fileInput: a jQuery collection of file input fields // options.paramName: the parameter name for the file form data, // overrides the name property of the file input field(s), // can be a string or an array of strings. // options.formData: an array of objects with name and value properties, // equivalent to the return data of .serializeArray(), e.g.: // [{name: 'a', value: 1}, {name: 'b', value: 2}] $.ajaxTransport('iframe', function (options) { if (options.async) { var form, iframe, addParamChar; return { send: function (_, completeCallback) { form = $('<form style="display:none;"></form>'); form.attr('accept-charset', options.formAcceptCharset); addParamChar = /\?/.test(options.url) ? '&' : '?'; // XDomainRequest only supports GET and POST: if (options.type === 'DELETE') { options.url = options.url + addParamChar + '_method=DELETE'; options.type = 'POST'; } else if (options.type === 'PUT') { options.url = options.url + addParamChar + '_method=PUT'; options.type = 'POST'; } else if (options.type === 'PATCH') { options.url = options.url + addParamChar + '_method=PATCH'; options.type = 'POST'; } // javascript:false as initial iframe src // prevents warning popups on HTTPS in IE6. // IE versions below IE8 cannot set the name property of // elements that have already been added to the DOM, // so we set the name along with the iframe HTML markup: iframe = $( '<iframe src="javascript:false;" name="iframe-transport-' + (counter += 1) + '"></iframe>' ).bind('load', function () { var fileInputClones, paramNames = $.isArray(options.paramName) ? options.paramName : [options.paramName]; iframe .unbind('load') .bind('load', function () { var response; // Wrap in a try/catch block to catch exceptions thrown // when trying to access cross-domain iframe contents: try { response = iframe.contents(); // Google Chrome and Firefox do not throw an // exception when calling iframe.contents() on // cross-domain requests, so we unify the response: if (!response.length || !response[0].firstChild) { throw new Error(); } } catch (e) { response = undefined; } // The complete callback returns the // iframe content document as response object: completeCallback( 200, 'success', {'iframe': response} ); // Fix for IE endless progress bar activity bug // (happens on form submits to iframe targets): $('<iframe src="javascript:false;"></iframe>') .appendTo(form); form.remove(); }); form .prop('target', iframe.prop('name')) .prop('action', options.url) .prop('method', options.type); if (options.formData) { $.each(options.formData, function (index, field) { $('<input type="hidden"/>') .prop('name', field.name) .val(field.value) .appendTo(form); }); } if (options.fileInput && options.fileInput.length && options.type === 'POST') { fileInputClones = options.fileInput.clone(); // Insert a clone for each file input field: options.fileInput.after(function (index) { return fileInputClones[index]; }); if (options.paramName) { options.fileInput.each(function (index) { $(this).prop( 'name', paramNames[index] || options.paramName ); }); } // Appending the file input fields to the hidden form // removes them from their original location: form .append(options.fileInput) .prop('enctype', 'multipart/form-data') // enctype must be set as encoding for IE: .prop('encoding', 'multipart/form-data'); } form.submit(); // Insert the file input fields at their original location // by replacing the clones with the originals: if (fileInputClones && fileInputClones.length) { options.fileInput.each(function (index, input) { var clone = $(fileInputClones[index]); $(input).prop('name', clone.prop('name')); clone.replaceWith(input); }); } }); form.append(iframe).appendTo(document.body); }, abort: function () { if (iframe) { // javascript:false as iframe src aborts the request // and prevents warning popups on HTTPS in IE6. // concat is used to avoid the "Script URL" JSLint error: iframe .unbind('load') .prop('src', 'javascript'.concat(':false;')); } if (form) { form.remove(); } } }; } }); // The iframe transport returns the iframe content document as response. // The following adds converters from iframe to text, json, html, and script: $.ajaxSetup({ converters: { 'iframe text': function (iframe) { return iframe && $(iframe[0].body).text(); }, 'iframe json': function (iframe) { return iframe && $.parseJSON($(iframe[0].body).text()); }, 'iframe html': function (iframe) { return iframe && $(iframe[0].body).html(); }, 'iframe script': function (iframe) { return iframe && $.globalEval($(iframe[0].body).text()); } } }); })); /* * jQuery File Upload Plugin 5.31 * https://github.com/blueimp/jQuery-File-Upload * * Copyright 2010, Sebastian Tschan * https://blueimp.net * * Licensed under the MIT license: * http://www.opensource.org/licenses/MIT */ /*jslint nomen: true, unparam: true, regexp: true */ /*global define, window, document, File, Blob, FormData, location */ (function (factory) { 'use strict'; if (typeof define === 'function' && define.amd) { // Register as an anonymous AMD module: define([ 'jquery', 'jquery.ui.widget' ], factory); } else { // Browser globals: factory(window.jQuery); } }(function ($) { 'use strict'; // The FileReader API is not actually used, but works as feature detection, // as e.g. Safari supports XHR file uploads via the FormData API, // but not non-multipart XHR file uploads: $.support.xhrFileUpload = !!(window.XMLHttpRequestUpload && window.FileReader); $.support.xhrFormDataFileUpload = !!window.FormData; // The fileupload widget listens for change events on file input fields defined // via fileInput setting and paste or drop events of the given dropZone. // In addition to the default jQuery Widget methods, the fileupload widget // exposes the "add" and "send" methods, to add or directly send files using // the fileupload API. // By default, files added via file input selection, paste, drag & drop or // "add" method are uploaded immediately, but it is possible to override // the "add" callback option to queue file uploads. $.widget('blueimp.fileupload', { options: { // The drop target element(s), by the default the complete document. // Set to null to disable drag & drop support: dropZone: $(document), // The paste target element(s), by the default the complete document. // Set to null to disable paste support: pasteZone: $(document), // The file input field(s), that are listened to for change events. // If undefined, it is set to the file input fields inside // of the widget element on plugin initialization. // Set to null to disable the change listener. fileInput: undefined, // By default, the file input field is replaced with a clone after // each input field change event. This is required for iframe transport // queues and allows change events to be fired for the same file // selection, but can be disabled by setting the following option to false: replaceFileInput: true, // The parameter name for the file form data (the request argument name). // If undefined or empty, the name property of the file input field is // used, or "files[]" if the file input name property is also empty, // can be a string or an array of strings: paramName: undefined, // By default, each file of a selection is uploaded using an individual // request for XHR type uploads. Set to false to upload file // selections in one request each: singleFileUploads: true, // To limit the number of files uploaded with one XHR request, // set the following option to an integer greater than 0: limitMultiFileUploads: undefined, // Set the following option to true to issue all file upload requests // in a sequential order: sequentialUploads: false, // To limit the number of concurrent uploads, // set the following option to an integer greater than 0: limitConcurrentUploads: undefined, // Set the following option to true to force iframe transport uploads: forceIframeTransport: false, // Set the following option to the location of a redirect url on the // origin server, for cross-domain iframe transport uploads: redirect: undefined, // The parameter name for the redirect url, sent as part of the form // data and set to 'redirect' if this option is empty: redirectParamName: undefined, // Set the following option to the location of a postMessage window, // to enable postMessage transport uploads: postMessage: undefined, // By default, XHR file uploads are sent as multipart/form-data. // The iframe transport is always using multipart/form-data. // Set to false to enable non-multipart XHR uploads: multipart: true, // To upload large files in smaller chunks, set the following option // to a preferred maximum chunk size. If set to 0, null or undefined, // or the browser does not support the required Blob API, files will // be uploaded as a whole. maxChunkSize: undefined, // When a non-multipart upload or a chunked multipart upload has been // aborted, this option can be used to resume the upload by setting // it to the size of the already uploaded bytes. This option is most // useful when modifying the options object inside of the "add" or // "send" callbacks, as the options are cloned for each file upload. uploadedBytes: undefined, // By default, failed (abort or error) file uploads are removed from the // global progress calculation. Set the following option to false to // prevent recalculating the global progress data: recalculateProgress: true, // Interval in milliseconds to calculate and trigger progress events: progressInterval: 100, // Interval in milliseconds to calculate progress bitrate: bitrateInterval: 500, // By default, uploads are started automatically when adding files: autoUpload: true, // Error and info messages: messages: { uploadedBytes: 'Uploaded bytes exceed file size' }, // Translation function, gets the message key to be translated // and an object with context specific data as arguments: i18n: function (message, context) { message = this.messages[message] || message.toString(); if (context) { $.each(context, function (key, value) { message = message.replace('{' + key + '}', value); }); } return message; }, // Additional form data to be sent along with the file uploads can be set // using this option, which accepts an array of objects with name and // value properties, a function returning such an array, a FormData // object (for XHR file uploads), or a simple object. // The form of the first fileInput is given as parameter to the function: formData: function (form) { return form.serializeArray(); }, // The add callback is invoked as soon as files are added to the fileupload // widget (via file input selection, drag & drop, paste or add API call). // If the singleFileUploads option is enabled, this callback will be // called once for each file in the selection for XHR file uplaods, else // once for each file selection. // The upload starts when the submit method is invoked on the data parameter. // The data object contains a files property holding the added files // and allows to override plugin options as well as define ajax settings. // Listeners for this callback can also be bound the following way: // .bind('fileuploadadd', func); // data.submit() returns a Promise object and allows to attach additional // handlers using jQuery's Deferred callbacks: // data.submit().done(func).fail(func).always(func); add: function (e, data) { if (data.autoUpload || (data.autoUpload !== false && $(this).fileupload('option', 'autoUpload'))) { data.process().done(function () { data.submit(); }); } }, // Other callbacks: // Callback for the submit event of each file upload: // submit: function (e, data) {}, // .bind('fileuploadsubmit', func); // Callback for the start of each file upload request: // send: function (e, data) {}, // .bind('fileuploadsend', func); // Callback for successful uploads: // done: function (e, data) {}, // .bind('fileuploaddone', func); // Callback for failed (abort or error) uploads: // fail: function (e, data) {}, // .bind('fileuploadfail', func); // Callback for completed (success, abort or error) requests: // always: function (e, data) {}, // .bind('fileuploadalways', func); // Callback for upload progress events: // progress: function (e, data) {}, // .bind('fileuploadprogress', func); // Callback for global upload progress events: // progressall: function (e, data) {}, // .bind('fileuploadprogressall', func); // Callback for uploads start, equivalent to the global ajaxStart event: // start: function (e) {}, // .bind('fileuploadstart', func); // Callback for uploads stop, equivalent to the global ajaxStop event: // stop: function (e) {}, // .bind('fileuploadstop', func); // Callback for change events of the fileInput(s): // change: function (e, data) {}, // .bind('fileuploadchange', func); // Callback for paste events to the pasteZone(s): // paste: function (e, data) {}, // .bind('fileuploadpaste', func); // Callback for drop events of the dropZone(s): // drop: function (e, data) {}, // .bind('fileuploaddrop', func); // Callback for dragover events of the dropZone(s): // dragover: function (e) {}, // .bind('fileuploaddragover', func); // Callback for the start of each chunk upload request: // chunksend: function (e, data) {}, // .bind('fileuploadchunksend', func); // Callback for successful chunk uploads: // chunkdone: function (e, data) {}, // .bind('fileuploadchunkdone', func); // Callback for failed (abort or error) chunk uploads: // chunkfail: function (e, data) {}, // .bind('fileuploadchunkfail', func); // Callback for completed (success, abort or error) chunk upload requests: // chunkalways: function (e, data) {}, // .bind('fileuploadchunkalways', func); // The plugin options are used as settings object for the ajax calls. // The following are jQuery ajax settings required for the file uploads: processData: false, contentType: false, cache: false }, // A list of options that require reinitializing event listeners and/or // special initialization code: _specialOptions: [ 'fileInput', 'dropZone', 'pasteZone', 'multipart', 'forceIframeTransport' ], _BitrateTimer: function () { this.timestamp = ((Date.now) ? Date.now() : (new Date()).getTime()); this.loaded = 0; this.bitrate = 0; this.getBitrate = function (now, loaded, interval) { var timeDiff = now - this.timestamp; if (!this.bitrate || !interval || timeDiff > interval) { this.bitrate = (loaded - this.loaded) * (1000 / timeDiff) * 8; this.loaded = loaded; this.timestamp = now; } return this.bitrate; }; }, _isXHRUpload: function (options) { return !options.forceIframeTransport && ((!options.multipart && $.support.xhrFileUpload) || $.support.xhrFormDataFileUpload); }, _getFormData: function (options) { var formData; if (typeof options.formData === 'function') { return options.formData(options.form); } if ($.isArray(options.formData)) { return options.formData; } if ($.type(options.formData) === 'object') { formData = []; $.each(options.formData, function (name, value) { formData.push({name: name, value: value}); }); return formData; } return []; }, _getTotal: function (files) { var total = 0; $.each(files, function (index, file) { total += file.size || 1; }); return total; }, _initProgressObject: function (obj) { var progress = { loaded: 0, total: 0, bitrate: 0 }; if (obj._progress) { $.extend(obj._progress, progress); } else { obj._progress = progress; } }, _initResponseObject: function (obj) { var prop; if (obj._response) { for (prop in obj._response) { if (obj._response.hasOwnProperty(prop)) { delete obj._response[prop]; } } } else { obj._response = {}; } }, _onProgress: function (e, data) { if (e.lengthComputable) { var now = ((Date.now) ? Date.now() : (new Date()).getTime()), loaded; if (data._time && data.progressInterval && (now - data._time < data.progressInterval) && e.loaded !== e.total) { return; } data._time = now; loaded = Math.floor( e.loaded / e.total * (data.chunkSize || data._progress.total) ) + (data.uploadedBytes || 0); // Add the difference from the previously loaded state // to the global loaded counter: this._progress.loaded += (loaded - data._progress.loaded); this._progress.bitrate = this._bitrateTimer.getBitrate( now, this._progress.loaded, data.bitrateInterval ); data._progress.loaded = data.loaded = loaded; data._progress.bitrate = data.bitrate = data._bitrateTimer.getBitrate( now, loaded, data.bitrateInterval ); // Trigger a custom progress event with a total data property set // to the file size(s) of the current upload and a loaded data // property calculated accordingly: this._trigger('progress', e, data); // Trigger a global progress event for all current file uploads, // including ajax calls queued for sequential file uploads: this._trigger('progressall', e, this._progress); } }, _initProgressListener: function (options) { var that = this, xhr = options.xhr ? options.xhr() : $.ajaxSettings.xhr(); // Accesss to the native XHR object is required to add event listeners // for the upload progress event: if (xhr.upload) { $(xhr.upload).bind('progress', function (e) { var oe = e.originalEvent; // Make sure the progress event properties get copied over: e.lengthComputable = oe.lengthComputable; e.loaded = oe.loaded; e.total = oe.total; that._onProgress(e, options); }); options.xhr = function () { return xhr; }; } }, _isInstanceOf: function (type, obj) { // Cross-frame instanceof check return Object.prototype.toString.call(obj) === '[object ' + type + ']'; }, _initXHRData: function (options) { var that = this, formData, file = options.files[0], // Ignore non-multipart setting if not supported: multipart = options.multipart || !$.support.xhrFileUpload, paramName = options.paramName[0]; options.headers = options.headers || {}; if (options.contentRange) { options.headers['Content-Range'] = options.contentRange; } if (!multipart) { options.headers['Content-Disposition'] = 'attachment; filename="' + encodeURI(file.name) + '"'; options.contentType = file.type; options.data = options.blob || file; } else if ($.support.xhrFormDataFileUpload) { if (options.postMessage) { // window.postMessage does not allow sending FormData // objects, so we just add the File/Blob objects to // the formData array and let the postMessage window // create the FormData object out of this array: formData = this._getFormData(options); if (options.blob) { formData.push({ name: paramName, value: options.blob }); } else { $.each(options.files, function (index, file) { formData.push({ name: options.paramName[index] || paramName, value: file }); }); } } else { if (that._isInstanceOf('FormData', options.formData)) { formData = options.formData; } else { formData = new FormData(); $.each(this._getFormData(options), function (index, field) { formData.append(field.name, field.value); }); } if (options.blob) { options.headers['Content-Disposition'] = 'attachment; filename="' + encodeURI(file.name) + '"'; formData.append(paramName, options.blob, file.name); } else { $.each(options.files, function (index, file) { // This check allows the tests to run with // dummy objects: if (that._isInstanceOf('File', file) || that._isInstanceOf('Blob', file)) { formData.append( options.paramName[index] || paramName, file, file.name ); } }); } } options.data = formData; } // Blob reference is not needed anymore, free memory: options.blob = null; }, _initIframeSettings: function (options) { // Setting the dataType to iframe enables the iframe transport: options.dataType = 'iframe ' + (options.dataType || ''); // The iframe transport accepts a serialized array as form data: options.formData = this._getFormData(options); // Add redirect url to form data on cross-domain uploads: if (options.redirect && $('<a></a>').prop('href', options.url) .prop('host') !== location.host) { options.formData.push({ name: options.redirectParamName || 'redirect', value: options.redirect }); } }, _initDataSettings: function (options) { if (this._isXHRUpload(options)) { if (!this._chunkedUpload(options, true)) { if (!options.data) { this._initXHRData(options); } this._initProgressListener(options); } if (options.postMessage) { // Setting the dataType to postmessage enables the // postMessage transport: options.dataType = 'postmessage ' + (options.dataType || ''); } } else { this._initIframeSettings(options); } }, _getParamName: function (options) { var fileInput = $(options.fileInput), paramName = options.paramName; if (!paramName) { paramName = []; fileInput.each(function () { var input = $(this), name = input.prop('name') || 'files[]', i = (input.prop('files') || [1]).length; while (i) { paramName.push(name); i -= 1; } }); if (!paramName.length) { paramName = [fileInput.prop('name') || 'files[]']; } } else if (!$.isArray(paramName)) { paramName = [paramName]; } return paramName; }, _initFormSettings: function (options) { // Retrieve missing options from the input field and the // associated form, if available: if (!options.form || !options.form.length) { options.form = $(options.fileInput.prop('form')); // If the given file input doesn't have an associated form, // use the default widget file input's form: if (!options.form.length) { options.form = $(this.options.fileInput.prop('form')); } } options.paramName = this._getParamName(options); if (!options.url) { options.url = options.form.prop('action') || location.href; } // The HTTP request method must be "POST" or "PUT": options.type = (options.type || options.form.prop('method') || '') .toUpperCase(); if (options.type !== 'POST' && options.type !== 'PUT' && options.type !== 'PATCH') { options.type = 'POST'; } if (!options.formAcceptCharset) { options.formAcceptCharset = options.form.attr('accept-charset'); } }, _getAJAXSettings: function (data) { var options = $.extend({}, this.options, data); this._initFormSettings(options); this._initDataSettings(options); return options; }, // jQuery 1.6 doesn't provide .state(), // while jQuery 1.8+ removed .isRejected() and .isResolved(): _getDeferredState: function (deferred) { if (deferred.state) { return deferred.state(); } if (deferred.isResolved()) { return 'resolved'; } if (deferred.isRejected()) { return 'rejected'; } return 'pending'; }, // Maps jqXHR callbacks to the equivalent // methods of the given Promise object: _enhancePromise: function (promise) { promise.success = promise.done; promise.error = promise.fail; promise.complete = promise.always; return promise; }, // Creates and returns a Promise object enhanced with // the jqXHR methods abort, success, error and complete: _getXHRPromise: function (resolveOrReject, context, args) { var dfd = $.Deferred(), promise = dfd.promise(); context = context || this.options.context || promise; if (resolveOrReject === true) { dfd.resolveWith(context, args); } else if (resolveOrReject === false) { dfd.rejectWith(context, args); } promise.abort = dfd.promise; return this._enhancePromise(promise); }, // Adds convenience methods to the data callback argument: _addConvenienceMethods: function (e, data) { var that = this, getPromise = function (data) { return $.Deferred().resolveWith(that, [data]).promise(); }; data.process = function (resolveFunc, rejectFunc) { if (resolveFunc || rejectFunc) { data._processQueue = this._processQueue = (this._processQueue || getPromise(this)) .pipe(resolveFunc, rejectFunc); } return this._processQueue || getPromise(this); }; data.submit = function () { if (this.state() !== 'pending') { data.jqXHR = this.jqXHR = (that._trigger('submit', e, this) !== false) && that._onSend(e, this); } return this.jqXHR || that._getXHRPromise(); }; data.abort = function () { if (this.jqXHR) { return this.jqXHR.abort(); } return that._getXHRPromise(); }; data.state = function () { if (this.jqXHR) { return that._getDeferredState(this.jqXHR); } if (this._processQueue) { return that._getDeferredState(this._processQueue); } }; data.progress = function () { return this._progress; }; data.response = function () { return this._response; }; }, // Parses the Range header from the server response // and returns the uploaded bytes: _getUploadedBytes: function (jqXHR) { var range = jqXHR.getResponseHeader('Range'), parts = range && range.split('-'), upperBytesPos = parts && parts.length > 1 && parseInt(parts[1], 10); return upperBytesPos && upperBytesPos + 1; }, // Uploads a file in multiple, sequential requests // by splitting the file up in multiple blob chunks. // If the second parameter is true, only tests if the file // should be uploaded in chunks, but does not invoke any // upload requests: _chunkedUpload: function (options, testOnly) { var that = this, file = options.files[0], fs = file.size, ub = options.uploadedBytes = options.uploadedBytes || 0, mcs = options.maxChunkSize || fs, slice = file.slice || file.webkitSlice || file.mozSlice, dfd = $.Deferred(), promise = dfd.promise(), jqXHR, upload; if (!(this._isXHRUpload(options) && slice && (ub || mcs < fs)) || options.data) { return false; } if (testOnly) { return true; } if (ub >= fs) { file.error = options.i18n('uploadedBytes'); return this._getXHRPromise( false, options.context, [null, 'error', file.error] ); } // The chunk upload method: upload = function () { // Clone the options object for each chunk upload: var o = $.extend({}, options), currentLoaded = o._progress.loaded; o.blob = slice.call( file, ub, ub + mcs, file.type ); // Store the current chunk size, as the blob itself // will be dereferenced after data processing: o.chunkSize = o.blob.size; // Expose the chunk bytes position range: o.contentRange = 'bytes ' + ub + '-' + (ub + o.chunkSize - 1) + '/' + fs; // Process the upload data (the blob and potential form data): that._initXHRData(o); // Add progress listeners for this chunk upload: that._initProgressListener(o); jqXHR = ((that._trigger('chunksend', null, o) !== false && $.ajax(o)) || that._getXHRPromise(false, o.context)) .done(function (result, textStatus, jqXHR) { ub = that._getUploadedBytes(jqXHR) || (ub + o.chunkSize); // Create a progress event if no final progress event // with loaded equaling total has been triggered // for this chunk: if (o._progress.loaded === currentLoaded) { that._onProgress($.Event('progress', { lengthComputable: true, loaded: ub - o.uploadedBytes, total: ub - o.uploadedBytes }), o); } options.uploadedBytes = o.uploadedBytes = ub; o.result = result; o.textStatus = textStatus; o.jqXHR = jqXHR; that._trigger('chunkdone', null, o); that._trigger('chunkalways', null, o); if (ub < fs) { // File upload not yet complete, // continue with the next chunk: upload(); } else { dfd.resolveWith( o.context, [result, textStatus, jqXHR] ); } }) .fail(function (jqXHR, textStatus, errorThrown) { o.jqXHR = jqXHR; o.textStatus = textStatus; o.errorThrown = errorThrown; that._trigger('chunkfail', null, o); that._trigger('chunkalways', null, o); dfd.rejectWith( o.context, [jqXHR, textStatus, errorThrown] ); }); }; this._enhancePromise(promise); promise.abort = function () { return jqXHR.abort(); }; upload(); return promise; }, _beforeSend: function (e, data) { if (this._active === 0) { // the start callback is triggered when an upload starts // and no other uploads are currently running, // equivalent to the global ajaxStart event: this._trigger('start'); // Set timer for global bitrate progress calculation: this._bitrateTimer = new this._BitrateTimer(); // Reset the global progress values: this._progress.loaded = this._progress.total = 0; this._progress.bitrate = 0; } // Make sure the container objects for the .response() and // .progress() methods on the data object are available // and reset to their initial state: this._initResponseObject(data); this._initProgressObject(data); data._progress.loaded = data.loaded = data.uploadedBytes || 0; data._progress.total = data.total = this._getTotal(data.files) || 1; data._progress.bitrate = data.bitrate = 0; this._active += 1; // Initialize the global progress values: this._progress.loaded += data.loaded; this._progress.total += data.total; }, _onDone: function (result, textStatus, jqXHR, options) { var total = options._progress.total, response = options._response; if (options._progress.loaded < total) { // Create a progress event if no final progress event // with loaded equaling total has been triggered: this._onProgress($.Event('progress', { lengthComputable: true, loaded: total, total: total }), options); } response.result = options.result = result; response.textStatus = options.textStatus = textStatus; response.jqXHR = options.jqXHR = jqXHR; this._trigger('done', null, options); }, _onFail: function (jqXHR, textStatus, errorThrown, options) { var response = options._response; if (options.recalculateProgress) { // Remove the failed (error or abort) file upload from // the global progress calculation: this._progress.loaded -= options._progress.loaded; this._progress.total -= options._progress.total; } response.jqXHR = options.jqXHR = jqXHR; response.textStatus = options.textStatus = textStatus; response.errorThrown = options.errorThrown = errorThrown; this._trigger('fail', null, options); }, _onAlways: function (jqXHRorResult, textStatus, jqXHRorError, options) { // jqXHRorResult, textStatus and jqXHRorError are added to the // options object via done and fail callbacks this._trigger('always', null, options); }, _onSend: function (e, data) { if (!data.submit) { this._addConvenienceMethods(e, data); } var that = this, jqXHR, aborted, slot, pipe, options = that._getAJAXSettings(data), send = function () { that._sending += 1; // Set timer for bitrate progress calculation: options._bitrateTimer = new that._BitrateTimer(); jqXHR = jqXHR || ( ((aborted || that._trigger('send', e, options) === false) && that._getXHRPromise(false, options.context, aborted)) || that._chunkedUpload(options) || $.ajax(options) ).done(function (result, textStatus, jqXHR) { that._onDone(result, textStatus, jqXHR, options); }).fail(function (jqXHR, textStatus, errorThrown) { that._onFail(jqXHR, textStatus, errorThrown, options); }).always(function (jqXHRorResult, textStatus, jqXHRorError) { that._onAlways( jqXHRorResult, textStatus, jqXHRorError, options ); that._sending -= 1; that._active -= 1; if (options.limitConcurrentUploads && options.limitConcurrentUploads > that._sending) { // Start the next queued upload, // that has not been aborted: var nextSlot = that._slots.shift(); while (nextSlot) { if (that._getDeferredState(nextSlot) === 'pending') { nextSlot.resolve(); break; } nextSlot = that._slots.shift(); } } if (that._active === 0) { // The stop callback is triggered when all uploads have // been completed, equivalent to the global ajaxStop event: that._trigger('stop'); } }); return jqXHR; }; this._beforeSend(e, options); if (this.options.sequentialUploads || (this.options.limitConcurrentUploads && this.options.limitConcurrentUploads <= this._sending)) { if (this.options.limitConcurrentUploads > 1) { slot = $.Deferred(); this._slots.push(slot); pipe = slot.pipe(send); } else { pipe = (this._sequence = this._sequence.pipe(send, send)); } // Return the piped Promise object, enhanced with an abort method, // which is delegated to the jqXHR object of the current upload, // and jqXHR callbacks mapped to the equivalent Promise methods: pipe.abort = function () { aborted = [undefined, 'abort', 'abort']; if (!jqXHR) { if (slot) { slot.rejectWith(options.context, aborted); } return send(); } return jqXHR.abort(); }; return this._enhancePromise(pipe); } return send(); }, _onAdd: function (e, data) { var that = this, result = true, options = $.extend({}, this.options, data), limit = options.limitMultiFileUploads, paramName = this._getParamName(options), paramNameSet, paramNameSlice, fileSet, i; if (!(options.singleFileUploads || limit) || !this._isXHRUpload(options)) { fileSet = [data.files]; paramNameSet = [paramName]; } else if (!options.singleFileUploads && limit) { fileSet = []; paramNameSet = []; for (i = 0; i < data.files.length; i += limit) { fileSet.push(data.files.slice(i, i + limit)); paramNameSlice = paramName.slice(i, i + limit); if (!paramNameSlice.length) { paramNameSlice = paramName; } paramNameSet.push(paramNameSlice); } } else { paramNameSet = paramName; } data.originalFiles = data.files; $.each(fileSet || data.files, function (index, element) { var newData = $.extend({}, data); newData.files = fileSet ? element : [element]; newData.paramName = paramNameSet[index]; that._initResponseObject(newData); that._initProgressObject(newData); that._addConvenienceMethods(e, newData); result = that._trigger('add', e, newData); return result; }); return result; }, _replaceFileInput: function (input) { var inputClone = input.clone(true); $('<form></form>').append(inputClone)[0].reset(); // Detaching allows to insert the fileInput on another form // without loosing the file input value: input.after(inputClone).detach(); // Avoid memory leaks with the detached file input: $.cleanData(input.unbind('remove')); // Replace the original file input element in the fileInput // elements set with the clone, which has been copied including // event handlers: this.options.fileInput = this.options.fileInput.map(function (i, el) { if (el === input[0]) { return inputClone[0]; } return el; }); // If the widget has been initialized on the file input itself, // override this.element with the file input clone: if (input[0] === this.element[0]) { this.element = inputClone; } }, _handleFileTreeEntry: function (entry, path) { var that = this, dfd = $.Deferred(), errorHandler = function (e) { if (e && !e.entry) { e.entry = entry; } // Since $.when returns immediately if one // Deferred is rejected, we use resolve instead. // This allows valid files and invalid items // to be returned together in one set: dfd.resolve([e]); }, dirReader; path = path || ''; if (entry.isFile) { if (entry._file) { // Workaround for Chrome bug #149735 entry._file.relativePath = path; dfd.resolve(entry._file); } else { entry.file(function (file) { file.relativePath = path; dfd.resolve(file); }, errorHandler); } } else if (entry.isDirectory) { dirReader = entry.createReader(); dirReader.readEntries(function (entries) { that._handleFileTreeEntries( entries, path + entry.name + '/' ).done(function (files) { dfd.resolve(files); }).fail(errorHandler); }, errorHandler); } else { // Return an empy list for file system items // other than files or directories: dfd.resolve([]); } return dfd.promise(); }, _handleFileTreeEntries: function (entries, path) { var that = this; return $.when.apply( $, $.map(entries, function (entry) { return that._handleFileTreeEntry(entry, path); }) ).pipe(function () { return Array.prototype.concat.apply( [], arguments ); }); }, _getDroppedFiles: function (dataTransfer) { dataTransfer = dataTransfer || {}; var items = dataTransfer.items; if (items && items.length && (items[0].webkitGetAsEntry || items[0].getAsEntry)) { return this._handleFileTreeEntries( $.map(items, function (item) { var entry; if (item.webkitGetAsEntry) { entry = item.webkitGetAsEntry(); if (entry) { // Workaround for Chrome bug #149735: entry._file = item.getAsFile(); } return entry; } return item.getAsEntry(); }) ); } return $.Deferred().resolve( $.makeArray(dataTransfer.files) ).promise(); }, _getSingleFileInputFiles: function (fileInput) { fileInput = $(fileInput); var entries = fileInput.prop('webkitEntries') || fileInput.prop('entries'), files, value; if (entries && entries.length) { return this._handleFileTreeEntries(entries); } files = $.makeArray(fileInput.prop('files')); if (!files.length) { value = fileInput.prop('value'); if (!value) { return $.Deferred().resolve([]).promise(); } // If the files property is not available, the browser does not // support the File API and we add a pseudo File object with // the input value as name with path information removed: files = [{name: value.replace(/^.*\\/, '')}]; } else if (files[0].name === undefined && files[0].fileName) { // File normalization for Safari 4 and Firefox 3: $.each(files, function (index, file) { file.name = file.fileName; file.size = file.fileSize; }); } return $.Deferred().resolve(files).promise(); }, _getFileInputFiles: function (fileInput) { if (!(fileInput instanceof $) || fileInput.length === 1) { return this._getSingleFileInputFiles(fileInput); } return $.when.apply( $, $.map(fileInput, this._getSingleFileInputFiles) ).pipe(function () { return Array.prototype.concat.apply( [], arguments ); }); }, _onChange: function (e) { var that = this, data = { fileInput: $(e.target), form: $(e.target.form) }; this._getFileInputFiles(data.fileInput).always(function (files) { data.files = files; if (that.options.replaceFileInput) { that._replaceFileInput(data.fileInput); } if (that._trigger('change', e, data) !== false) { that._onAdd(e, data); } }); }, _onPaste: function (e) { var items = e.originalEvent && e.originalEvent.clipboardData && e.originalEvent.clipboardData.items, data = {files: []}; if (items && items.length) { $.each(items, function (index, item) { var file = item.getAsFile && item.getAsFile(); if (file) { data.files.push(file); } }); if (this._trigger('paste', e, data) === false || this._onAdd(e, data) === false) { return false; } } }, _onDrop: function (e) { var that = this, dataTransfer = e.dataTransfer = e.originalEvent && e.originalEvent.dataTransfer, data = {}; if (dataTransfer && dataTransfer.files && dataTransfer.files.length) { e.preventDefault(); this._getDroppedFiles(dataTransfer).always(function (files) { data.files = files; if (that._trigger('drop', e, data) !== false) { that._onAdd(e, data); } }); } }, _onDragOver: function (e) { var dataTransfer = e.dataTransfer = e.originalEvent && e.originalEvent.dataTransfer; if (dataTransfer) { if (this._trigger('dragover', e) === false) { return false; } if ($.inArray('Files', dataTransfer.types) !== -1) { dataTransfer.dropEffect = 'copy'; e.preventDefault(); } } }, _initEventHandlers: function () { if (this._isXHRUpload(this.options)) { this._on(this.options.dropZone, { dragover: this._onDragOver, drop: this._onDrop }); this._on(this.options.pasteZone, { paste: this._onPaste }); } this._on(this.options.fileInput, { change: this._onChange }); }, _destroyEventHandlers: function () { this._off(this.options.dropZone, 'dragover drop'); this._off(this.options.pasteZone, 'paste'); this._off(this.options.fileInput, 'change'); }, _setOption: function (key, value) { var reinit = $.inArray(key, this._specialOptions) !== -1; if (reinit) { this._destroyEventHandlers(); } this._super(key, value); if (reinit) { this._initSpecialOptions(); this._initEventHandlers(); } }, _initSpecialOptions: function () { var options = this.options; if (options.fileInput === undefined) { options.fileInput = this.element.is('input[type="file"]') ? this.element : this.element.find('input[type="file"]'); } else if (!(options.fileInput instanceof $)) { options.fileInput = $(options.fileInput); } if (!(options.dropZone instanceof $)) { options.dropZone = $(options.dropZone); } if (!(options.pasteZone instanceof $)) { options.pasteZone = $(options.pasteZone); } }, _getRegExp: function (str) { var parts = str.split('/'), modifiers = parts.pop(); parts.shift(); return new RegExp(parts.join('/'), modifiers); }, _isRegExpOption: function (key, value) { return key !== 'url' && $.type(value) === 'string' && /^\/.*\/[igm]{0,3}$/.test(value); }, _initDataAttributes: function () { var that = this, options = this.options; // Initialize options set via HTML5 data-attributes: $.each( $(this.element[0].cloneNode(false)).data(), function (key, value) { if (that._isRegExpOption(key, value)) { value = that._getRegExp(value); } options[key] = value; } ); }, _create: function () { this._initDataAttributes(); this._initSpecialOptions(); this._slots = []; this._sequence = this._getXHRPromise(true); this._sending = this._active = 0; this._initProgressObject(this); this._initEventHandlers(); }, // This method is exposed to the widget API and allows to query // the number of active uploads: active: function () { return this._active; }, // This method is exposed to the widget API and allows to query // the widget upload progress. // It returns an object with loaded, total and bitrate properties // for the running uploads: progress: function () { return this._progress; }, // This method is exposed to the widget API and allows adding files // using the fileupload API. The data parameter accepts an object which // must have a files property and can contain additional options: // .fileupload('add', {files: filesList}); add: function (data) { var that = this; if (!data || this.options.disabled) { return; } if (data.fileInput && !data.files) { this._getFileInputFiles(data.fileInput).always(function (files) { data.files = files; that._onAdd(null, data); }); } else { data.files = $.makeArray(data.files); this._onAdd(null, data); } }, // This method is exposed to the widget API and allows sending files // using the fileupload API. The data parameter accepts an object which // must have a files or fileInput property and can contain additional options: // .fileupload('send', {files: filesList}); // The method returns a Promise object for the file upload call. send: function (data) { if (data && !this.options.disabled) { if (data.fileInput && !data.files) { var that = this, dfd = $.Deferred(), promise = dfd.promise(), jqXHR, aborted; promise.abort = function () { aborted = true; if (jqXHR) { return jqXHR.abort(); } dfd.reject(null, 'abort', 'abort'); return promise; }; this._getFileInputFiles(data.fileInput).always( function (files) { if (aborted) { return; } data.files = files; jqXHR = that._onSend(null, data).then( function (result, textStatus, jqXHR) { dfd.resolve(result, textStatus, jqXHR); }, function (jqXHR, textStatus, errorThrown) { dfd.reject(jqXHR, textStatus, errorThrown); } ); } ); return this._enhancePromise(promise); } data.files = $.makeArray(data.files); if (data.files.length) { return this._onSend(null, data); } } return this._getXHRPromise(false, data && data.context); } }); })); // CodeMirror version 3.15 // // CodeMirror is the only global var we claim window.CodeMirror = (function() { "use strict"; // BROWSER SNIFFING // Crude, but necessary to handle a number of hard-to-feature-detect // bugs and behavior differences. var gecko = /gecko\/\d/i.test(navigator.userAgent); var ie = /MSIE \d/.test(navigator.userAgent); var ie_lt8 = ie && (document.documentMode == null || document.documentMode < 8); var ie_lt9 = ie && (document.documentMode == null || document.documentMode < 9); var webkit = /WebKit\//.test(navigator.userAgent); var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(navigator.userAgent); var chrome = /Chrome\//.test(navigator.userAgent); var opera = /Opera\//.test(navigator.userAgent); var safari = /Apple Computer/.test(navigator.vendor); var khtml = /KHTML\//.test(navigator.userAgent); var mac_geLion = /Mac OS X 1\d\D([7-9]|\d\d)\D/.test(navigator.userAgent); var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(navigator.userAgent); var phantom = /PhantomJS/.test(navigator.userAgent); var ios = /AppleWebKit/.test(navigator.userAgent) && /Mobile\/\w+/.test(navigator.userAgent); // This is woefully incomplete. Suggestions for alternative methods welcome. var mobile = ios || /Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(navigator.userAgent); var mac = ios || /Mac/.test(navigator.platform); var windows = /windows/i.test(navigator.platform); var opera_version = opera && navigator.userAgent.match(/Version\/(\d*\.\d*)/); if (opera_version) opera_version = Number(opera_version[1]); if (opera_version && opera_version >= 15) { opera = false; webkit = true; } // Some browsers use the wrong event properties to signal cmd/ctrl on OS X var flipCtrlCmd = mac && (qtwebkit || opera && (opera_version == null || opera_version < 12.11)); var captureMiddleClick = gecko || (ie && !ie_lt9); // Optimize some code when these features are not used var sawReadOnlySpans = false, sawCollapsedSpans = false; // CONSTRUCTOR function CodeMirror(place, options) { if (!(this instanceof CodeMirror)) return new CodeMirror(place, options); this.options = options = options || {}; // Determine effective options based on given values and defaults. for (var opt in defaults) if (!options.hasOwnProperty(opt) && defaults.hasOwnProperty(opt)) options[opt] = defaults[opt]; setGuttersForLineNumbers(options); var docStart = typeof options.value == "string" ? 0 : options.value.first; var display = this.display = makeDisplay(place, docStart); display.wrapper.CodeMirror = this; updateGutters(this); if (options.autofocus && !mobile) focusInput(this); this.state = {keyMaps: [], overlays: [], modeGen: 0, overwrite: false, focused: false, suppressEdits: false, pasteIncoming: false, draggingText: false, highlight: new Delayed()}; themeChanged(this); if (options.lineWrapping) this.display.wrapper.className += " CodeMirror-wrap"; var doc = options.value; if (typeof doc == "string") doc = new Doc(options.value, options.mode); operation(this, attachDoc)(this, doc); // Override magic textarea content restore that IE sometimes does // on our hidden textarea on reload if (ie) setTimeout(bind(resetInput, this, true), 20); registerEventHandlers(this); // IE throws unspecified error in certain cases, when // trying to access activeElement before onload var hasFocus; try { hasFocus = (document.activeElement == display.input); } catch(e) { } if (hasFocus || (options.autofocus && !mobile)) setTimeout(bind(onFocus, this), 20); else onBlur(this); operation(this, function() { for (var opt in optionHandlers) if (optionHandlers.propertyIsEnumerable(opt)) optionHandlers[opt](this, options[opt], Init); for (var i = 0; i < initHooks.length; ++i) initHooks[i](this); })(); } // DISPLAY CONSTRUCTOR function makeDisplay(place, docStart) { var d = {}; var input = d.input = elt("textarea", null, null, "position: absolute; padding: 0; width: 1px; height: 1em; outline: none; font-size: 4px;"); if (webkit) input.style.width = "1000px"; else input.setAttribute("wrap", "off"); // if border: 0; -- iOS fails to open keyboard (issue #1287) if (ios) input.style.border = "1px solid black"; input.setAttribute("autocorrect", "off"); input.setAttribute("autocapitalize", "off"); input.setAttribute("spellcheck", "false"); // Wraps and hides input textarea d.inputDiv = elt("div", [input], null, "overflow: hidden; position: relative; width: 3px; height: 0px;"); // The actual fake scrollbars. d.scrollbarH = elt("div", [elt("div", null, null, "height: 1px")], "CodeMirror-hscrollbar"); d.scrollbarV = elt("div", [elt("div", null, null, "width: 1px")], "CodeMirror-vscrollbar"); d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler"); d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler"); // DIVs containing the selection and the actual code d.lineDiv = elt("div", null, "CodeMirror-code"); d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1"); // Blinky cursor, and element used to ensure cursor fits at the end of a line d.cursor = elt("div", "\u00a0", "CodeMirror-cursor"); // Secondary cursor, shown when on a 'jump' in bi-directional text d.otherCursor = elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"); // Used to measure text size d.measure = elt("div", null, "CodeMirror-measure"); // Wraps everything that needs to exist inside the vertically-padded coordinate system d.lineSpace = elt("div", [d.measure, d.selectionDiv, d.lineDiv, d.cursor, d.otherCursor], null, "position: relative; outline: none"); // Moved around its parent to cover visible view d.mover = elt("div", [elt("div", [d.lineSpace], "CodeMirror-lines")], null, "position: relative"); // Set to the height of the text, causes scrolling d.sizer = elt("div", [d.mover], "CodeMirror-sizer"); // D is needed because behavior of elts with overflow: auto and padding is inconsistent across browsers d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerCutOff + "px; width: 1px;"); // Will contain the gutters, if any d.gutters = elt("div", null, "CodeMirror-gutters"); d.lineGutter = null; // Provides scrolling d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll"); d.scroller.setAttribute("tabIndex", "-1"); // The element in which the editor lives. d.wrapper = elt("div", [d.inputDiv, d.scrollbarH, d.scrollbarV, d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror"); // Work around IE7 z-index bug if (ie_lt8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; } if (place.appendChild) place.appendChild(d.wrapper); else place(d.wrapper); // Needed to hide big blue blinking cursor on Mobile Safari if (ios) input.style.width = "0px"; if (!webkit) d.scroller.draggable = true; // Needed to handle Tab key in KHTML if (khtml) { d.inputDiv.style.height = "1px"; d.inputDiv.style.position = "absolute"; } // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8). else if (ie_lt8) d.scrollbarH.style.minWidth = d.scrollbarV.style.minWidth = "18px"; // Current visible range (may be bigger than the view window). d.viewOffset = d.lastSizeC = 0; d.showingFrom = d.showingTo = docStart; // Used to only resize the line number gutter when necessary (when // the amount of lines crosses a boundary that makes its width change) d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null; // See readInput and resetInput d.prevInput = ""; // Set to true when a non-horizontal-scrolling widget is added. As // an optimization, widget aligning is skipped when d is false. d.alignWidgets = false; // Flag that indicates whether we currently expect input to appear // (after some event like 'keypress' or 'input') and are polling // intensively. d.pollingFast = false; // Self-resetting timeout for the poller d.poll = new Delayed(); d.cachedCharWidth = d.cachedTextHeight = null; d.measureLineCache = []; d.measureLineCachePos = 0; // Tracks when resetInput has punted to just putting a short // string instead of the (large) selection. d.inaccurateSelection = false; // Tracks the maximum line length so that the horizontal scrollbar // can be kept static when scrolling. d.maxLine = null; d.maxLineLength = 0; d.maxLineChanged = false; // Used for measuring wheel scrolling granularity d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null; return d; } // STATE UPDATES // Used to get the editor into a consistent state again when options change. function loadMode(cm) { cm.doc.mode = CodeMirror.getMode(cm.options, cm.doc.modeOption); cm.doc.iter(function(line) { if (line.stateAfter) line.stateAfter = null; if (line.styles) line.styles = null; }); cm.doc.frontier = cm.doc.first; startWorker(cm, 100); cm.state.modeGen++; if (cm.curOp) regChange(cm); } function wrappingChanged(cm) { if (cm.options.lineWrapping) { cm.display.wrapper.className += " CodeMirror-wrap"; cm.display.sizer.style.minWidth = ""; } else { cm.display.wrapper.className = cm.display.wrapper.className.replace(" CodeMirror-wrap", ""); computeMaxLength(cm); } estimateLineHeights(cm); regChange(cm); clearCaches(cm); setTimeout(function(){updateScrollbars(cm);}, 100); } function estimateHeight(cm) { var th = textHeight(cm.display), wrapping = cm.options.lineWrapping; var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3); return function(line) { if (lineIsHidden(cm.doc, line)) return 0; else if (wrapping) return (Math.ceil(line.text.length / perLine) || 1) * th; else return th; }; } function estimateLineHeights(cm) { var doc = cm.doc, est = estimateHeight(cm); doc.iter(function(line) { var estHeight = est(line); if (estHeight != line.height) updateLineHeight(line, estHeight); }); } function keyMapChanged(cm) { var map = keyMap[cm.options.keyMap], style = map.style; cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-keymap-\S+/g, "") + (style ? " cm-keymap-" + style : ""); cm.state.disableInput = map.disableInput; } function themeChanged(cm) { cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") + cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-"); clearCaches(cm); } function guttersChanged(cm) { updateGutters(cm); regChange(cm); setTimeout(function(){alignHorizontally(cm);}, 20); } function updateGutters(cm) { var gutters = cm.display.gutters, specs = cm.options.gutters; removeChildren(gutters); for (var i = 0; i < specs.length; ++i) { var gutterClass = specs[i]; var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass)); if (gutterClass == "CodeMirror-linenumbers") { cm.display.lineGutter = gElt; gElt.style.width = (cm.display.lineNumWidth || 1) + "px"; } } gutters.style.display = i ? "" : "none"; } function lineLength(doc, line) { if (line.height == 0) return 0; var len = line.text.length, merged, cur = line; while (merged = collapsedSpanAtStart(cur)) { var found = merged.find(); cur = getLine(doc, found.from.line); len += found.from.ch - found.to.ch; } cur = line; while (merged = collapsedSpanAtEnd(cur)) { var found = merged.find(); len -= cur.text.length - found.from.ch; cur = getLine(doc, found.to.line); len += cur.text.length - found.to.ch; } return len; } function computeMaxLength(cm) { var d = cm.display, doc = cm.doc; d.maxLine = getLine(doc, doc.first); d.maxLineLength = lineLength(doc, d.maxLine); d.maxLineChanged = true; doc.iter(function(line) { var len = lineLength(doc, line); if (len > d.maxLineLength) { d.maxLineLength = len; d.maxLine = line; } }); } // Make sure the gutters options contains the element // "CodeMirror-linenumbers" when the lineNumbers option is true. function setGuttersForLineNumbers(options) { var found = false; for (var i = 0; i < options.gutters.length; ++i) { if (options.gutters[i] == "CodeMirror-linenumbers") { if (options.lineNumbers) found = true; else options.gutters.splice(i--, 1); } } if (!found && options.lineNumbers) options.gutters.push("CodeMirror-linenumbers"); } // SCROLLBARS // Re-synchronize the fake scrollbars with the actual size of the // content. Optionally force a scrollTop. function updateScrollbars(cm) { var d = cm.display, docHeight = cm.doc.height; var totalHeight = docHeight + paddingVert(d); d.sizer.style.minHeight = d.heightForcer.style.top = totalHeight + "px"; d.gutters.style.height = Math.max(totalHeight, d.scroller.clientHeight - scrollerCutOff) + "px"; var scrollHeight = Math.max(totalHeight, d.scroller.scrollHeight); var needsH = d.scroller.scrollWidth > (d.scroller.clientWidth + 1); var needsV = scrollHeight > (d.scroller.clientHeight + 1); if (needsV) { d.scrollbarV.style.display = "block"; d.scrollbarV.style.bottom = needsH ? scrollbarWidth(d.measure) + "px" : "0"; d.scrollbarV.firstChild.style.height = (scrollHeight - d.scroller.clientHeight + d.scrollbarV.clientHeight) + "px"; } else d.scrollbarV.style.display = ""; if (needsH) { d.scrollbarH.style.display = "block"; d.scrollbarH.style.right = needsV ? scrollbarWidth(d.measure) + "px" : "0"; d.scrollbarH.firstChild.style.width = (d.scroller.scrollWidth - d.scroller.clientWidth + d.scrollbarH.clientWidth) + "px"; } else d.scrollbarH.style.display = ""; if (needsH && needsV) { d.scrollbarFiller.style.display = "block"; d.scrollbarFiller.style.height = d.scrollbarFiller.style.width = scrollbarWidth(d.measure) + "px"; } else d.scrollbarFiller.style.display = ""; if (needsH && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) { d.gutterFiller.style.display = "block"; d.gutterFiller.style.height = scrollbarWidth(d.measure) + "px"; d.gutterFiller.style.width = d.gutters.offsetWidth + "px"; } else d.gutterFiller.style.display = ""; if (mac_geLion && scrollbarWidth(d.measure) === 0) d.scrollbarV.style.minWidth = d.scrollbarH.style.minHeight = mac_geMountainLion ? "18px" : "12px"; } function visibleLines(display, doc, viewPort) { var top = display.scroller.scrollTop, height = display.wrapper.clientHeight; if (typeof viewPort == "number") top = viewPort; else if (viewPort) {top = viewPort.top; height = viewPort.bottom - viewPort.top;} top = Math.floor(top - paddingTop(display)); var bottom = Math.ceil(top + height); return {from: lineAtHeight(doc, top), to: lineAtHeight(doc, bottom)}; } // LINE NUMBERS function alignHorizontally(cm) { var display = cm.display; if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) return; var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft; var gutterW = display.gutters.offsetWidth, l = comp + "px"; for (var n = display.lineDiv.firstChild; n; n = n.nextSibling) if (n.alignable) { for (var i = 0, a = n.alignable; i < a.length; ++i) a[i].style.left = l; } if (cm.options.fixedGutter) display.gutters.style.left = (comp + gutterW) + "px"; } function maybeUpdateLineNumberWidth(cm) { if (!cm.options.lineNumbers) return false; var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display; if (last.length != display.lineNumChars) { var test = display.measure.appendChild(elt("div", [elt("div", last)], "CodeMirror-linenumber CodeMirror-gutter-elt")); var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW; display.lineGutter.style.width = ""; display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding); display.lineNumWidth = display.lineNumInnerWidth + padding; display.lineNumChars = display.lineNumInnerWidth ? last.length : -1; display.lineGutter.style.width = display.lineNumWidth + "px"; return true; } return false; } function lineNumberFor(options, i) { return String(options.lineNumberFormatter(i + options.firstLineNumber)); } function compensateForHScroll(display) { return getRect(display.scroller).left - getRect(display.sizer).left; } // DISPLAY DRAWING function updateDisplay(cm, changes, viewPort, forced) { var oldFrom = cm.display.showingFrom, oldTo = cm.display.showingTo, updated; var visible = visibleLines(cm.display, cm.doc, viewPort); for (;;) { if (!updateDisplayInner(cm, changes, visible, forced)) break; forced = false; updated = true; updateSelection(cm); updateScrollbars(cm); // Clip forced viewport to actual scrollable area if (viewPort) viewPort = Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight, typeof viewPort == "number" ? viewPort : viewPort.top); visible = visibleLines(cm.display, cm.doc, viewPort); if (visible.from >= cm.display.showingFrom && visible.to <= cm.display.showingTo) break; changes = []; } if (updated) { signalLater(cm, "update", cm); if (cm.display.showingFrom != oldFrom || cm.display.showingTo != oldTo) signalLater(cm, "viewportChange", cm, cm.display.showingFrom, cm.display.showingTo); } return updated; } // Uses a set of changes plus the current scroll position to // determine which DOM updates have to be made, and makes the // updates. function updateDisplayInner(cm, changes, visible, forced) { var display = cm.display, doc = cm.doc; if (!display.wrapper.clientWidth) { display.showingFrom = display.showingTo = doc.first; display.viewOffset = 0; return; } // Bail out if the visible area is already rendered and nothing changed. if (!forced && changes.length == 0 && visible.from > display.showingFrom && visible.to < display.showingTo) return; if (maybeUpdateLineNumberWidth(cm)) changes = [{from: doc.first, to: doc.first + doc.size}]; var gutterW = display.sizer.style.marginLeft = display.gutters.offsetWidth + "px"; display.scrollbarH.style.left = cm.options.fixedGutter ? gutterW : "0"; // Used to determine which lines need their line numbers updated var positionsChangedFrom = Infinity; if (cm.options.lineNumbers) for (var i = 0; i < changes.length; ++i) if (changes[i].diff) { positionsChangedFrom = changes[i].from; break; } var end = doc.first + doc.size; var from = Math.max(visible.from - cm.options.viewportMargin, doc.first); var to = Math.min(end, visible.to + cm.options.viewportMargin); if (display.showingFrom < from && from - display.showingFrom < 20) from = Math.max(doc.first, display.showingFrom); if (display.showingTo > to && display.showingTo - to < 20) to = Math.min(end, display.showingTo); if (sawCollapsedSpans) { from = lineNo(visualLine(doc, getLine(doc, from))); while (to < end && lineIsHidden(doc, getLine(doc, to))) ++to; } // Create a range of theoretically intact lines, and punch holes // in that using the change info. var intact = [{from: Math.max(display.showingFrom, doc.first), to: Math.min(display.showingTo, end)}]; if (intact[0].from >= intact[0].to) intact = []; else intact = computeIntact(intact, changes); // When merged lines are present, we might have to reduce the // intact ranges because changes in continued fragments of the // intact lines do require the lines to be redrawn. if (sawCollapsedSpans) for (var i = 0; i < intact.length; ++i) { var range = intact[i], merged; while (merged = collapsedSpanAtEnd(getLine(doc, range.to - 1))) { var newTo = merged.find().from.line; if (newTo > range.from) range.to = newTo; else { intact.splice(i--, 1); break; } } } // Clip off the parts that won't be visible var intactLines = 0; for (var i = 0; i < intact.length; ++i) { var range = intact[i]; if (range.from < from) range.from = from; if (range.to > to) range.to = to; if (range.from >= range.to) intact.splice(i--, 1); else intactLines += range.to - range.from; } if (!forced && intactLines == to - from && from == display.showingFrom && to == display.showingTo) { updateViewOffset(cm); return; } intact.sort(function(a, b) {return a.from - b.from;}); // Avoid crashing on IE's "unspecified error" when in iframes try { var focused = document.activeElement; } catch(e) {} if (intactLines < (to - from) * .7) display.lineDiv.style.display = "none"; patchDisplay(cm, from, to, intact, positionsChangedFrom); display.lineDiv.style.display = ""; if (focused && document.activeElement != focused && focused.offsetHeight) focused.focus(); var different = from != display.showingFrom || to != display.showingTo || display.lastSizeC != display.wrapper.clientHeight; // This is just a bogus formula that detects when the editor is // resized or the font size changes. if (different) { display.lastSizeC = display.wrapper.clientHeight; startWorker(cm, 400); } display.showingFrom = from; display.showingTo = to; updateHeightsInViewport(cm); updateViewOffset(cm); return true; } function updateHeightsInViewport(cm) { var display = cm.display; var prevBottom = display.lineDiv.offsetTop; for (var node = display.lineDiv.firstChild, height; node; node = node.nextSibling) if (node.lineObj) { if (ie_lt8) { var bot = node.offsetTop + node.offsetHeight; height = bot - prevBottom; prevBottom = bot; } else { var box = getRect(node); height = box.bottom - box.top; } var diff = node.lineObj.height - height; if (height < 2) height = textHeight(display); if (diff > .001 || diff < -.001) { updateLineHeight(node.lineObj, height); var widgets = node.lineObj.widgets; if (widgets) for (var i = 0; i < widgets.length; ++i) widgets[i].height = widgets[i].node.offsetHeight; } } } function updateViewOffset(cm) { var off = cm.display.viewOffset = heightAtLine(cm, getLine(cm.doc, cm.display.showingFrom)); // Position the mover div to align with the current virtual scroll position cm.display.mover.style.top = off + "px"; } function computeIntact(intact, changes) { for (var i = 0, l = changes.length || 0; i < l; ++i) { var change = changes[i], intact2 = [], diff = change.diff || 0; for (var j = 0, l2 = intact.length; j < l2; ++j) { var range = intact[j]; if (change.to <= range.from && change.diff) { intact2.push({from: range.from + diff, to: range.to + diff}); } else if (change.to <= range.from || change.from >= range.to) { intact2.push(range); } else { if (change.from > range.from) intact2.push({from: range.from, to: change.from}); if (change.to < range.to) intact2.push({from: change.to + diff, to: range.to + diff}); } } intact = intact2; } return intact; } function getDimensions(cm) { var d = cm.display, left = {}, width = {}; for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) { left[cm.options.gutters[i]] = n.offsetLeft; width[cm.options.gutters[i]] = n.offsetWidth; } return {fixedPos: compensateForHScroll(d), gutterTotalWidth: d.gutters.offsetWidth, gutterLeft: left, gutterWidth: width, wrapperWidth: d.wrapper.clientWidth}; } function patchDisplay(cm, from, to, intact, updateNumbersFrom) { var dims = getDimensions(cm); var display = cm.display, lineNumbers = cm.options.lineNumbers; if (!intact.length && (!webkit || !cm.display.currentWheelTarget)) removeChildren(display.lineDiv); var container = display.lineDiv, cur = container.firstChild; function rm(node) { var next = node.nextSibling; if (webkit && mac && cm.display.currentWheelTarget == node) { node.style.display = "none"; node.lineObj = null; } else { node.parentNode.removeChild(node); } return next; } var nextIntact = intact.shift(), lineN = from; cm.doc.iter(from, to, function(line) { if (nextIntact && nextIntact.to == lineN) nextIntact = intact.shift(); if (lineIsHidden(cm.doc, line)) { if (line.height != 0) updateLineHeight(line, 0); if (line.widgets && cur.previousSibling) for (var i = 0; i < line.widgets.length; ++i) { var w = line.widgets[i]; if (w.showIfHidden) { var prev = cur.previousSibling; if (/pre/i.test(prev.nodeName)) { var wrap = elt("div", null, null, "position: relative"); prev.parentNode.replaceChild(wrap, prev); wrap.appendChild(prev); prev = wrap; } var wnode = prev.appendChild(elt("div", [w.node], "CodeMirror-linewidget")); if (!w.handleMouseEvents) wnode.ignoreEvents = true; positionLineWidget(w, wnode, prev, dims); } } } else if (nextIntact && nextIntact.from <= lineN && nextIntact.to > lineN) { // This line is intact. Skip to the actual node. Update its // line number if needed. while (cur.lineObj != line) cur = rm(cur); if (lineNumbers && updateNumbersFrom <= lineN && cur.lineNumber) setTextContent(cur.lineNumber, lineNumberFor(cm.options, lineN)); cur = cur.nextSibling; } else { // For lines with widgets, make an attempt to find and reuse // the existing element, so that widgets aren't needlessly // removed and re-inserted into the dom if (line.widgets) for (var j = 0, search = cur, reuse; search && j < 20; ++j, search = search.nextSibling) if (search.lineObj == line && /div/i.test(search.nodeName)) { reuse = search; break; } // This line needs to be generated. var lineNode = buildLineElement(cm, line, lineN, dims, reuse); if (lineNode != reuse) { container.insertBefore(lineNode, cur); } else { while (cur != reuse) cur = rm(cur); cur = cur.nextSibling; } lineNode.lineObj = line; } ++lineN; }); while (cur) cur = rm(cur); } function buildLineElement(cm, line, lineNo, dims, reuse) { var lineElement = lineContent(cm, line); var markers = line.gutterMarkers, display = cm.display, wrap; if (!cm.options.lineNumbers && !markers && !line.bgClass && !line.wrapClass && !line.widgets) return lineElement; // Lines with gutter elements, widgets or a background class need // to be wrapped again, and have the extra elements added to the // wrapper div if (reuse) { reuse.alignable = null; var isOk = true, widgetsSeen = 0, insertBefore = null; for (var n = reuse.firstChild, next; n; n = next) { next = n.nextSibling; if (!/\bCodeMirror-linewidget\b/.test(n.className)) { reuse.removeChild(n); } else { for (var i = 0; i < line.widgets.length; ++i) { var widget = line.widgets[i]; if (widget.node == n.firstChild) { if (!widget.above && !insertBefore) insertBefore = n; positionLineWidget(widget, n, reuse, dims); ++widgetsSeen; break; } } if (i == line.widgets.length) { isOk = false; break; } } } reuse.insertBefore(lineElement, insertBefore); if (isOk && widgetsSeen == line.widgets.length) { wrap = reuse; reuse.className = line.wrapClass || ""; } } if (!wrap) { wrap = elt("div", null, line.wrapClass, "position: relative"); wrap.appendChild(lineElement); } // Kludge to make sure the styled element lies behind the selection (by z-index) if (line.bgClass) wrap.insertBefore(elt("div", null, line.bgClass + " CodeMirror-linebackground"), wrap.firstChild); if (cm.options.lineNumbers || markers) { var gutterWrap = wrap.insertBefore(elt("div", null, null, "position: absolute; left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px"), wrap.firstChild); if (cm.options.fixedGutter) (wrap.alignable || (wrap.alignable = [])).push(gutterWrap); if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"])) wrap.lineNumber = gutterWrap.appendChild( elt("div", lineNumberFor(cm.options, lineNo), "CodeMirror-linenumber CodeMirror-gutter-elt", "left: " + dims.gutterLeft["CodeMirror-linenumbers"] + "px; width: " + display.lineNumInnerWidth + "px")); if (markers) for (var k = 0; k < cm.options.gutters.length; ++k) { var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id]; if (found) gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", "left: " + dims.gutterLeft[id] + "px; width: " + dims.gutterWidth[id] + "px")); } } if (ie_lt8) wrap.style.zIndex = 2; if (line.widgets && wrap != reuse) for (var i = 0, ws = line.widgets; i < ws.length; ++i) { var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget"); if (!widget.handleMouseEvents) node.ignoreEvents = true; positionLineWidget(widget, node, wrap, dims); if (widget.above) wrap.insertBefore(node, cm.options.lineNumbers && line.height != 0 ? gutterWrap : lineElement); else wrap.appendChild(node); signalLater(widget, "redraw"); } return wrap; } function positionLineWidget(widget, node, wrap, dims) { if (widget.noHScroll) { (wrap.alignable || (wrap.alignable = [])).push(node); var width = dims.wrapperWidth; node.style.left = dims.fixedPos + "px"; if (!widget.coverGutter) { width -= dims.gutterTotalWidth; node.style.paddingLeft = dims.gutterTotalWidth + "px"; } node.style.width = width + "px"; } if (widget.coverGutter) { node.style.zIndex = 5; node.style.position = "relative"; if (!widget.noHScroll) node.style.marginLeft = -dims.gutterTotalWidth + "px"; } } // SELECTION / CURSOR function updateSelection(cm) { var display = cm.display; var collapsed = posEq(cm.doc.sel.from, cm.doc.sel.to); if (collapsed || cm.options.showCursorWhenSelecting) updateSelectionCursor(cm); else display.cursor.style.display = display.otherCursor.style.display = "none"; if (!collapsed) updateSelectionRange(cm); else display.selectionDiv.style.display = "none"; // Move the hidden textarea near the cursor to prevent scrolling artifacts if (cm.options.moveInputWithCursor) { var headPos = cursorCoords(cm, cm.doc.sel.head, "div"); var wrapOff = getRect(display.wrapper), lineOff = getRect(display.lineDiv); display.inputDiv.style.top = Math.max(0, Math.min(display.wrapper.clientHeight - 10, headPos.top + lineOff.top - wrapOff.top)) + "px"; display.inputDiv.style.left = Math.max(0, Math.min(display.wrapper.clientWidth - 10, headPos.left + lineOff.left - wrapOff.left)) + "px"; } } // No selection, plain cursor function updateSelectionCursor(cm) { var display = cm.display, pos = cursorCoords(cm, cm.doc.sel.head, "div"); display.cursor.style.left = pos.left + "px"; display.cursor.style.top = pos.top + "px"; display.cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px"; display.cursor.style.display = ""; if (pos.other) { display.otherCursor.style.display = ""; display.otherCursor.style.left = pos.other.left + "px"; display.otherCursor.style.top = pos.other.top + "px"; display.otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px"; } else { display.otherCursor.style.display = "none"; } } // Highlight selection function updateSelectionRange(cm) { var display = cm.display, doc = cm.doc, sel = cm.doc.sel; var fragment = document.createDocumentFragment(); var clientWidth = display.lineSpace.offsetWidth, pl = paddingLeft(cm.display); function add(left, top, width, bottom) { if (top < 0) top = 0; fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left + "px; top: " + top + "px; width: " + (width == null ? clientWidth - left : width) + "px; height: " + (bottom - top) + "px")); } function drawForLine(line, fromArg, toArg) { var lineObj = getLine(doc, line); var lineLen = lineObj.text.length; var start, end; function coords(ch, bias) { return charCoords(cm, Pos(line, ch), "div", lineObj, bias); } iterateBidiSections(getOrder(lineObj), fromArg || 0, toArg == null ? lineLen : toArg, function(from, to, dir) { var leftPos = coords(from, "left"), rightPos, left, right; if (from == to) { rightPos = leftPos; left = right = leftPos.left; } else { rightPos = coords(to - 1, "right"); if (dir == "rtl") { var tmp = leftPos; leftPos = rightPos; rightPos = tmp; } left = leftPos.left; right = rightPos.right; } if (fromArg == null && from == 0) left = pl; if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part add(left, leftPos.top, null, leftPos.bottom); left = pl; if (leftPos.bottom < rightPos.top) add(left, leftPos.bottom, null, rightPos.top); } if (toArg == null && to == lineLen) right = clientWidth; if (!start || leftPos.top < start.top || leftPos.top == start.top && leftPos.left < start.left) start = leftPos; if (!end || rightPos.bottom > end.bottom || rightPos.bottom == end.bottom && rightPos.right > end.right) end = rightPos; if (left < pl + 1) left = pl; add(left, rightPos.top, right - left, rightPos.bottom); }); return {start: start, end: end}; } if (sel.from.line == sel.to.line) { drawForLine(sel.from.line, sel.from.ch, sel.to.ch); } else { var fromLine = getLine(doc, sel.from.line), toLine = getLine(doc, sel.to.line); var singleVLine = visualLine(doc, fromLine) == visualLine(doc, toLine); var leftEnd = drawForLine(sel.from.line, sel.from.ch, singleVLine ? fromLine.text.length : null).end; var rightStart = drawForLine(sel.to.line, singleVLine ? 0 : null, sel.to.ch).start; if (singleVLine) { if (leftEnd.top < rightStart.top - 2) { add(leftEnd.right, leftEnd.top, null, leftEnd.bottom); add(pl, rightStart.top, rightStart.left, rightStart.bottom); } else { add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom); } } if (leftEnd.bottom < rightStart.top) add(pl, leftEnd.bottom, null, rightStart.top); } removeChildrenAndAdd(display.selectionDiv, fragment); display.selectionDiv.style.display = ""; } // Cursor-blinking function restartBlink(cm) { if (!cm.state.focused) return; var display = cm.display; clearInterval(display.blinker); var on = true; display.cursor.style.visibility = display.otherCursor.style.visibility = ""; display.blinker = setInterval(function() { display.cursor.style.visibility = display.otherCursor.style.visibility = (on = !on) ? "" : "hidden"; }, cm.options.cursorBlinkRate); } // HIGHLIGHT WORKER function startWorker(cm, time) { if (cm.doc.mode.startState && cm.doc.frontier < cm.display.showingTo) cm.state.highlight.set(time, bind(highlightWorker, cm)); } function highlightWorker(cm) { var doc = cm.doc; if (doc.frontier < doc.first) doc.frontier = doc.first; if (doc.frontier >= cm.display.showingTo) return; var end = +new Date + cm.options.workTime; var state = copyState(doc.mode, getStateBefore(cm, doc.frontier)); var changed = [], prevChange; doc.iter(doc.frontier, Math.min(doc.first + doc.size, cm.display.showingTo + 500), function(line) { if (doc.frontier >= cm.display.showingFrom) { // Visible var oldStyles = line.styles; line.styles = highlightLine(cm, line, state); var ischange = !oldStyles || oldStyles.length != line.styles.length; for (var i = 0; !ischange && i < oldStyles.length; ++i) ischange = oldStyles[i] != line.styles[i]; if (ischange) { if (prevChange && prevChange.end == doc.frontier) prevChange.end++; else changed.push(prevChange = {start: doc.frontier, end: doc.frontier + 1}); } line.stateAfter = copyState(doc.mode, state); } else { processLine(cm, line, state); line.stateAfter = doc.frontier % 5 == 0 ? copyState(doc.mode, state) : null; } ++doc.frontier; if (+new Date > end) { startWorker(cm, cm.options.workDelay); return true; } }); if (changed.length) operation(cm, function() { for (var i = 0; i < changed.length; ++i) regChange(this, changed[i].start, changed[i].end); })(); } // Finds the line to start with when starting a parse. Tries to // find a line with a stateAfter, so that it can start with a // valid state. If that fails, it returns the line with the // smallest indentation, which tends to need the least context to // parse correctly. function findStartLine(cm, n, precise) { var minindent, minline, doc = cm.doc; for (var search = n, lim = n - 100; search > lim; --search) { if (search <= doc.first) return doc.first; var line = getLine(doc, search - 1); if (line.stateAfter && (!precise || search <= doc.frontier)) return search; var indented = countColumn(line.text, null, cm.options.tabSize); if (minline == null || minindent > indented) { minline = search - 1; minindent = indented; } } return minline; } function getStateBefore(cm, n, precise) { var doc = cm.doc, display = cm.display; if (!doc.mode.startState) return true; var pos = findStartLine(cm, n, precise), state = pos > doc.first && getLine(doc, pos-1).stateAfter; if (!state) state = startState(doc.mode); else state = copyState(doc.mode, state); doc.iter(pos, n, function(line) { processLine(cm, line, state); var save = pos == n - 1 || pos % 5 == 0 || pos >= display.showingFrom && pos < display.showingTo; line.stateAfter = save ? copyState(doc.mode, state) : null; ++pos; }); return state; } // POSITION MEASUREMENT function paddingTop(display) {return display.lineSpace.offsetTop;} function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight;} function paddingLeft(display) { var e = removeChildrenAndAdd(display.measure, elt("pre", null, null, "text-align: left")).appendChild(elt("span", "x")); return e.offsetLeft; } function measureChar(cm, line, ch, data, bias) { var dir = -1; data = data || measureLine(cm, line); for (var pos = ch;; pos += dir) { var r = data[pos]; if (r) break; if (dir < 0 && pos == 0) dir = 1; } bias = pos > ch ? "left" : pos < ch ? "right" : bias; if (bias == "left" && r.leftSide) r = r.leftSide; else if (bias == "right" && r.rightSide) r = r.rightSide; return {left: pos < ch ? r.right : r.left, right: pos > ch ? r.left : r.right, top: r.top, bottom: r.bottom}; } function findCachedMeasurement(cm, line) { var cache = cm.display.measureLineCache; for (var i = 0; i < cache.length; ++i) { var memo = cache[i]; if (memo.text == line.text && memo.markedSpans == line.markedSpans && cm.display.scroller.clientWidth == memo.width && memo.classes == line.textClass + "|" + line.bgClass + "|" + line.wrapClass) return memo; } } function clearCachedMeasurement(cm, line) { var exists = findCachedMeasurement(cm, line); if (exists) exists.text = exists.measure = exists.markedSpans = null; } function measureLine(cm, line) { // First look in the cache var cached = findCachedMeasurement(cm, line); if (cached) return cached.measure; // Failing that, recompute and store result in cache var measure = measureLineInner(cm, line); var cache = cm.display.measureLineCache; var memo = {text: line.text, width: cm.display.scroller.clientWidth, markedSpans: line.markedSpans, measure: measure, classes: line.textClass + "|" + line.bgClass + "|" + line.wrapClass}; if (cache.length == 16) cache[++cm.display.measureLineCachePos % 16] = memo; else cache.push(memo); return measure; } function measureLineInner(cm, line) { var display = cm.display, measure = emptyArray(line.text.length); var pre = lineContent(cm, line, measure, true); // IE does not cache element positions of inline elements between // calls to getBoundingClientRect. This makes the loop below, // which gathers the positions of all the characters on the line, // do an amount of layout work quadratic to the number of // characters. When line wrapping is off, we try to improve things // by first subdividing the line into a bunch of inline blocks, so // that IE can reuse most of the layout information from caches // for those blocks. This does interfere with line wrapping, so it // doesn't work when wrapping is on, but in that case the // situation is slightly better, since IE does cache line-wrapping // information and only recomputes per-line. if (ie && !ie_lt8 && !cm.options.lineWrapping && pre.childNodes.length > 100) { var fragment = document.createDocumentFragment(); var chunk = 10, n = pre.childNodes.length; for (var i = 0, chunks = Math.ceil(n / chunk); i < chunks; ++i) { var wrap = elt("div", null, null, "display: inline-block"); for (var j = 0; j < chunk && n; ++j) { wrap.appendChild(pre.firstChild); --n; } fragment.appendChild(wrap); } pre.appendChild(fragment); } removeChildrenAndAdd(display.measure, pre); var outer = getRect(display.lineDiv); var vranges = [], data = emptyArray(line.text.length), maxBot = pre.offsetHeight; // Work around an IE7/8 bug where it will sometimes have randomly // replaced our pre with a clone at this point. if (ie_lt9 && display.measure.first != pre) removeChildrenAndAdd(display.measure, pre); function measureRect(rect) { var top = rect.top - outer.top, bot = rect.bottom - outer.top; if (bot > maxBot) bot = maxBot; if (top < 0) top = 0; for (var i = vranges.length - 2; i >= 0; i -= 2) { var rtop = vranges[i], rbot = vranges[i+1]; if (rtop > bot || rbot < top) continue; if (rtop <= top && rbot >= bot || top <= rtop && bot >= rbot || Math.min(bot, rbot) - Math.max(top, rtop) >= (bot - top) >> 1) { vranges[i] = Math.min(top, rtop); vranges[i+1] = Math.max(bot, rbot); break; } } if (i < 0) { i = vranges.length; vranges.push(top, bot); } return {left: rect.left - outer.left, right: rect.right - outer.left, top: i, bottom: null}; } function finishRect(rect) { rect.bottom = vranges[rect.top+1]; rect.top = vranges[rect.top]; } for (var i = 0, cur; i < measure.length; ++i) if (cur = measure[i]) { var node = cur, rect = null; // A widget might wrap, needs special care if (/\bCodeMirror-widget\b/.test(cur.className) && cur.getClientRects) { if (cur.firstChild.nodeType == 1) node = cur.firstChild; var rects = node.getClientRects(); if (rects.length > 1) { rect = data[i] = measureRect(rects[0]); rect.rightSide = measureRect(rects[rects.length - 1]); } } if (!rect) rect = data[i] = measureRect(getRect(node)); if (cur.measureRight) rect.right = getRect(cur.measureRight).left; if (cur.leftSide) rect.leftSide = measureRect(getRect(cur.leftSide)); } for (var i = 0, cur; i < data.length; ++i) if (cur = data[i]) { finishRect(cur); if (cur.leftSide) finishRect(cur.leftSide); if (cur.rightSide) finishRect(cur.rightSide); } return data; } function measureLineWidth(cm, line) { var hasBadSpan = false; if (line.markedSpans) for (var i = 0; i < line.markedSpans; ++i) { var sp = line.markedSpans[i]; if (sp.collapsed && (sp.to == null || sp.to == line.text.length)) hasBadSpan = true; } var cached = !hasBadSpan && findCachedMeasurement(cm, line); if (cached) return measureChar(cm, line, line.text.length, cached.measure, "right").right; var pre = lineContent(cm, line, null, true); var end = pre.appendChild(zeroWidthElement(cm.display.measure)); removeChildrenAndAdd(cm.display.measure, pre); return getRect(end).right - getRect(cm.display.lineDiv).left; } function clearCaches(cm) { cm.display.measureLineCache.length = cm.display.measureLineCachePos = 0; cm.display.cachedCharWidth = cm.display.cachedTextHeight = null; if (!cm.options.lineWrapping) cm.display.maxLineChanged = true; cm.display.lineNumChars = null; } function pageScrollX() { return window.pageXOffset || (document.documentElement || document.body).scrollLeft; } function pageScrollY() { return window.pageYOffset || (document.documentElement || document.body).scrollTop; } // Context is one of "line", "div" (display.lineDiv), "local"/null (editor), or "page" function intoCoordSystem(cm, lineObj, rect, context) { if (lineObj.widgets) for (var i = 0; i < lineObj.widgets.length; ++i) if (lineObj.widgets[i].above) { var size = widgetHeight(lineObj.widgets[i]); rect.top += size; rect.bottom += size; } if (context == "line") return rect; if (!context) context = "local"; var yOff = heightAtLine(cm, lineObj); if (context == "local") yOff += paddingTop(cm.display); else yOff -= cm.display.viewOffset; if (context == "page" || context == "window") { var lOff = getRect(cm.display.lineSpace); yOff += lOff.top + (context == "window" ? 0 : pageScrollY()); var xOff = lOff.left + (context == "window" ? 0 : pageScrollX()); rect.left += xOff; rect.right += xOff; } rect.top += yOff; rect.bottom += yOff; return rect; } // Context may be "window", "page", "div", or "local"/null // Result is in "div" coords function fromCoordSystem(cm, coords, context) { if (context == "div") return coords; var left = coords.left, top = coords.top; // First move into "page" coordinate system if (context == "page") { left -= pageScrollX(); top -= pageScrollY(); } else if (context == "local" || !context) { var localBox = getRect(cm.display.sizer); left += localBox.left; top += localBox.top; } var lineSpaceBox = getRect(cm.display.lineSpace); return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top}; } function charCoords(cm, pos, context, lineObj, bias) { if (!lineObj) lineObj = getLine(cm.doc, pos.line); return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, null, bias), context); } function cursorCoords(cm, pos, context, lineObj, measurement) { lineObj = lineObj || getLine(cm.doc, pos.line); if (!measurement) measurement = measureLine(cm, lineObj); function get(ch, right) { var m = measureChar(cm, lineObj, ch, measurement, right ? "right" : "left"); if (right) m.left = m.right; else m.right = m.left; return intoCoordSystem(cm, lineObj, m, context); } function getBidi(ch, partPos) { var part = order[partPos], right = part.level % 2; if (ch == bidiLeft(part) && partPos && part.level < order[partPos - 1].level) { part = order[--partPos]; ch = bidiRight(part) - (part.level % 2 ? 0 : 1); right = true; } else if (ch == bidiRight(part) && partPos < order.length - 1 && part.level < order[partPos + 1].level) { part = order[++partPos]; ch = bidiLeft(part) - part.level % 2; right = false; } if (right && ch == part.to && ch > part.from) return get(ch - 1); return get(ch, right); } var order = getOrder(lineObj), ch = pos.ch; if (!order) return get(ch); var partPos = getBidiPartAt(order, ch); var val = getBidi(ch, partPos); if (bidiOther != null) val.other = getBidi(ch, bidiOther); return val; } function PosWithInfo(line, ch, outside, xRel) { var pos = new Pos(line, ch); pos.xRel = xRel; if (outside) pos.outside = true; return pos; } // Coords must be lineSpace-local function coordsChar(cm, x, y) { var doc = cm.doc; y += cm.display.viewOffset; if (y < 0) return PosWithInfo(doc.first, 0, true, -1); var lineNo = lineAtHeight(doc, y), last = doc.first + doc.size - 1; if (lineNo > last) return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, true, 1); if (x < 0) x = 0; for (;;) { var lineObj = getLine(doc, lineNo); var found = coordsCharInner(cm, lineObj, lineNo, x, y); var merged = collapsedSpanAtEnd(lineObj); var mergedPos = merged && merged.find(); if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0)) lineNo = mergedPos.to.line; else return found; } } function coordsCharInner(cm, lineObj, lineNo, x, y) { var innerOff = y - heightAtLine(cm, lineObj); var wrongLine = false, adjust = 2 * cm.display.wrapper.clientWidth; var measurement = measureLine(cm, lineObj); function getX(ch) { var sp = cursorCoords(cm, Pos(lineNo, ch), "line", lineObj, measurement); wrongLine = true; if (innerOff > sp.bottom) return sp.left - adjust; else if (innerOff < sp.top) return sp.left + adjust; else wrongLine = false; return sp.left; } var bidi = getOrder(lineObj), dist = lineObj.text.length; var from = lineLeft(lineObj), to = lineRight(lineObj); var fromX = getX(from), fromOutside = wrongLine, toX = getX(to), toOutside = wrongLine; if (x > toX) return PosWithInfo(lineNo, to, toOutside, 1); // Do a binary search between these bounds. for (;;) { if (bidi ? to == from || to == moveVisually(lineObj, from, 1) : to - from <= 1) { var ch = x < fromX || x - fromX <= toX - x ? from : to; var xDiff = x - (ch == from ? fromX : toX); while (isExtendingChar.test(lineObj.text.charAt(ch))) ++ch; var pos = PosWithInfo(lineNo, ch, ch == from ? fromOutside : toOutside, xDiff < 0 ? -1 : xDiff ? 1 : 0); return pos; } var step = Math.ceil(dist / 2), middle = from + step; if (bidi) { middle = from; for (var i = 0; i < step; ++i) middle = moveVisually(lineObj, middle, 1); } var middleX = getX(middle); if (middleX > x) {to = middle; toX = middleX; if (toOutside = wrongLine) toX += 1000; dist = step;} else {from = middle; fromX = middleX; fromOutside = wrongLine; dist -= step;} } } var measureText; function textHeight(display) { if (display.cachedTextHeight != null) return display.cachedTextHeight; if (measureText == null) { measureText = elt("pre"); // Measure a bunch of lines, for browsers that compute // fractional heights. for (var i = 0; i < 49; ++i) { measureText.appendChild(document.createTextNode("x")); measureText.appendChild(elt("br")); } measureText.appendChild(document.createTextNode("x")); } removeChildrenAndAdd(display.measure, measureText); var height = measureText.offsetHeight / 50; if (height > 3) display.cachedTextHeight = height; removeChildren(display.measure); return height || 1; } function charWidth(display) { if (display.cachedCharWidth != null) return display.cachedCharWidth; var anchor = elt("span", "x"); var pre = elt("pre", [anchor]); removeChildrenAndAdd(display.measure, pre); var width = anchor.offsetWidth; if (width > 2) display.cachedCharWidth = width; return width || 10; } // OPERATIONS // Operations are used to wrap changes in such a way that each // change won't have to update the cursor and display (which would // be awkward, slow, and error-prone), but instead updates are // batched and then all combined and executed at once. var nextOpId = 0; function startOperation(cm) { cm.curOp = { // An array of ranges of lines that have to be updated. See // updateDisplay. changes: [], forceUpdate: false, updateInput: null, userSelChange: null, textChanged: null, selectionChanged: false, cursorActivity: false, updateMaxLine: false, updateScrollPos: false, id: ++nextOpId }; if (!delayedCallbackDepth++) delayedCallbacks = []; } function endOperation(cm) { var op = cm.curOp, doc = cm.doc, display = cm.display; cm.curOp = null; if (op.updateMaxLine) computeMaxLength(cm); if (display.maxLineChanged && !cm.options.lineWrapping && display.maxLine) { var width = measureLineWidth(cm, display.maxLine); display.sizer.style.minWidth = Math.max(0, width + 3 + scrollerCutOff) + "px"; display.maxLineChanged = false; var maxScrollLeft = Math.max(0, display.sizer.offsetLeft + display.sizer.offsetWidth - display.scroller.clientWidth); if (maxScrollLeft < doc.scrollLeft && !op.updateScrollPos) setScrollLeft(cm, Math.min(display.scroller.scrollLeft, maxScrollLeft), true); } var newScrollPos, updated; if (op.updateScrollPos) { newScrollPos = op.updateScrollPos; } else if (op.selectionChanged && display.scroller.clientHeight) { // don't rescroll if not visible var coords = cursorCoords(cm, doc.sel.head); newScrollPos = calculateScrollPos(cm, coords.left, coords.top, coords.left, coords.bottom); } if (op.changes.length || op.forceUpdate || newScrollPos && newScrollPos.scrollTop != null) { updated = updateDisplay(cm, op.changes, newScrollPos && newScrollPos.scrollTop, op.forceUpdate); if (cm.display.scroller.offsetHeight) cm.doc.scrollTop = cm.display.scroller.scrollTop; } if (!updated && op.selectionChanged) updateSelection(cm); if (op.updateScrollPos) { display.scroller.scrollTop = display.scrollbarV.scrollTop = doc.scrollTop = newScrollPos.scrollTop; display.scroller.scrollLeft = display.scrollbarH.scrollLeft = doc.scrollLeft = newScrollPos.scrollLeft; alignHorizontally(cm); if (op.scrollToPos) scrollPosIntoView(cm, clipPos(cm.doc, op.scrollToPos), op.scrollToPosMargin); } else if (newScrollPos) { scrollCursorIntoView(cm); } if (op.selectionChanged) restartBlink(cm); if (cm.state.focused && op.updateInput) resetInput(cm, op.userSelChange); var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers; if (hidden) for (var i = 0; i < hidden.length; ++i) if (!hidden[i].lines.length) signal(hidden[i], "hide"); if (unhidden) for (var i = 0; i < unhidden.length; ++i) if (unhidden[i].lines.length) signal(unhidden[i], "unhide"); var delayed; if (!--delayedCallbackDepth) { delayed = delayedCallbacks; delayedCallbacks = null; } if (op.textChanged) signal(cm, "change", cm, op.textChanged); if (op.cursorActivity) signal(cm, "cursorActivity", cm); if (delayed) for (var i = 0; i < delayed.length; ++i) delayed[i](); } // Wraps a function in an operation. Returns the wrapped function. function operation(cm1, f) { return function() { var cm = cm1 || this, withOp = !cm.curOp; if (withOp) startOperation(cm); try { var result = f.apply(cm, arguments); } finally { if (withOp) endOperation(cm); } return result; }; } function docOperation(f) { return function() { var withOp = this.cm && !this.cm.curOp, result; if (withOp) startOperation(this.cm); try { result = f.apply(this, arguments); } finally { if (withOp) endOperation(this.cm); } return result; }; } function runInOp(cm, f) { var withOp = !cm.curOp, result; if (withOp) startOperation(cm); try { result = f(); } finally { if (withOp) endOperation(cm); } return result; } function regChange(cm, from, to, lendiff) { if (from == null) from = cm.doc.first; if (to == null) to = cm.doc.first + cm.doc.size; cm.curOp.changes.push({from: from, to: to, diff: lendiff}); } // INPUT HANDLING function slowPoll(cm) { if (cm.display.pollingFast) return; cm.display.poll.set(cm.options.pollInterval, function() { readInput(cm); if (cm.state.focused) slowPoll(cm); }); } function fastPoll(cm) { var missed = false; cm.display.pollingFast = true; function p() { var changed = readInput(cm); if (!changed && !missed) {missed = true; cm.display.poll.set(60, p);} else {cm.display.pollingFast = false; slowPoll(cm);} } cm.display.poll.set(20, p); } // prevInput is a hack to work with IME. If we reset the textarea // on every change, that breaks IME. So we look for changes // compared to the previous content instead. (Modern browsers have // events that indicate IME taking place, but these are not widely // supported or compatible enough yet to rely on.) function readInput(cm) { var input = cm.display.input, prevInput = cm.display.prevInput, doc = cm.doc, sel = doc.sel; if (!cm.state.focused || hasSelection(input) || isReadOnly(cm) || cm.state.disableInput) return false; var text = input.value; if (text == prevInput && posEq(sel.from, sel.to)) return false; if (ie && !ie_lt9 && cm.display.inputHasSelection === text) { resetInput(cm, true); return false; } var withOp = !cm.curOp; if (withOp) startOperation(cm); sel.shift = false; var same = 0, l = Math.min(prevInput.length, text.length); while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) ++same; var from = sel.from, to = sel.to; if (same < prevInput.length) from = Pos(from.line, from.ch - (prevInput.length - same)); else if (cm.state.overwrite && posEq(from, to) && !cm.state.pasteIncoming) to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + (text.length - same))); var updateInput = cm.curOp.updateInput; var changeEvent = {from: from, to: to, text: splitLines(text.slice(same)), origin: cm.state.pasteIncoming ? "paste" : "+input"}; makeChange(cm.doc, changeEvent, "end"); cm.curOp.updateInput = updateInput; signalLater(cm, "inputRead", cm, changeEvent); if (text.length > 1000 || text.indexOf("\n") > -1) input.value = cm.display.prevInput = ""; else cm.display.prevInput = text; if (withOp) endOperation(cm); cm.state.pasteIncoming = false; return true; } function resetInput(cm, user) { var minimal, selected, doc = cm.doc; if (!posEq(doc.sel.from, doc.sel.to)) { cm.display.prevInput = ""; minimal = hasCopyEvent && (doc.sel.to.line - doc.sel.from.line > 100 || (selected = cm.getSelection()).length > 1000); var content = minimal ? "-" : selected || cm.getSelection(); cm.display.input.value = content; if (cm.state.focused) selectInput(cm.display.input); if (ie && !ie_lt9) cm.display.inputHasSelection = content; } else if (user) { cm.display.prevInput = cm.display.input.value = ""; if (ie && !ie_lt9) cm.display.inputHasSelection = null; } cm.display.inaccurateSelection = minimal; } function focusInput(cm) { if (cm.options.readOnly != "nocursor" && (!mobile || document.activeElement != cm.display.input)) cm.display.input.focus(); } function isReadOnly(cm) { return cm.options.readOnly || cm.doc.cantEdit; } // EVENT HANDLERS function registerEventHandlers(cm) { var d = cm.display; on(d.scroller, "mousedown", operation(cm, onMouseDown)); if (ie) on(d.scroller, "dblclick", operation(cm, function(e) { if (signalDOMEvent(cm, e)) return; var pos = posFromMouse(cm, e); if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) return; e_preventDefault(e); var word = findWordAt(getLine(cm.doc, pos.line).text, pos); extendSelection(cm.doc, word.from, word.to); })); else on(d.scroller, "dblclick", function(e) { signalDOMEvent(cm, e) || e_preventDefault(e); }); on(d.lineSpace, "selectstart", function(e) { if (!eventInWidget(d, e)) e_preventDefault(e); }); // Gecko browsers fire contextmenu *after* opening the menu, at // which point we can't mess with it anymore. Context menu is // handled in onMouseDown for Gecko. if (!captureMiddleClick) on(d.scroller, "contextmenu", function(e) {onContextMenu(cm, e);}); on(d.scroller, "scroll", function() { if (d.scroller.clientHeight) { setScrollTop(cm, d.scroller.scrollTop); setScrollLeft(cm, d.scroller.scrollLeft, true); signal(cm, "scroll", cm); } }); on(d.scrollbarV, "scroll", function() { if (d.scroller.clientHeight) setScrollTop(cm, d.scrollbarV.scrollTop); }); on(d.scrollbarH, "scroll", function() { if (d.scroller.clientHeight) setScrollLeft(cm, d.scrollbarH.scrollLeft); }); on(d.scroller, "mousewheel", function(e){onScrollWheel(cm, e);}); on(d.scroller, "DOMMouseScroll", function(e){onScrollWheel(cm, e);}); function reFocus() { if (cm.state.focused) setTimeout(bind(focusInput, cm), 0); } on(d.scrollbarH, "mousedown", reFocus); on(d.scrollbarV, "mousedown", reFocus); // Prevent wrapper from ever scrolling on(d.wrapper, "scroll", function() { d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; }); var resizeTimer; function onResize() { if (resizeTimer == null) resizeTimer = setTimeout(function() { resizeTimer = null; // Might be a text scaling operation, clear size caches. d.cachedCharWidth = d.cachedTextHeight = knownScrollbarWidth = null; clearCaches(cm); runInOp(cm, bind(regChange, cm)); }, 100); } on(window, "resize", onResize); // Above handler holds on to the editor and its data structures. // Here we poll to unregister it when the editor is no longer in // the document, so that it can be garbage-collected. function unregister() { for (var p = d.wrapper.parentNode; p && p != document.body; p = p.parentNode) {} if (p) setTimeout(unregister, 5000); else off(window, "resize", onResize); } setTimeout(unregister, 5000); on(d.input, "keyup", operation(cm, function(e) { if (signalDOMEvent(cm, e) || cm.options.onKeyEvent && cm.options.onKeyEvent(cm, addStop(e))) return; if (e.keyCode == 16) cm.doc.sel.shift = false; })); on(d.input, "input", bind(fastPoll, cm)); on(d.input, "keydown", operation(cm, onKeyDown)); on(d.input, "keypress", operation(cm, onKeyPress)); on(d.input, "focus", bind(onFocus, cm)); on(d.input, "blur", bind(onBlur, cm)); function drag_(e) { if (signalDOMEvent(cm, e) || cm.options.onDragEvent && cm.options.onDragEvent(cm, addStop(e))) return; e_stop(e); } if (cm.options.dragDrop) { on(d.scroller, "dragstart", function(e){onDragStart(cm, e);}); on(d.scroller, "dragenter", drag_); on(d.scroller, "dragover", drag_); on(d.scroller, "drop", operation(cm, onDrop)); } on(d.scroller, "paste", function(e){ if (eventInWidget(d, e)) return; focusInput(cm); fastPoll(cm); }); on(d.input, "paste", function() { cm.state.pasteIncoming = true; fastPoll(cm); }); function prepareCopy() { if (d.inaccurateSelection) { d.prevInput = ""; d.inaccurateSelection = false; d.input.value = cm.getSelection(); selectInput(d.input); } } on(d.input, "cut", prepareCopy); on(d.input, "copy", prepareCopy); // Needed to handle Tab key in KHTML if (khtml) on(d.sizer, "mouseup", function() { if (document.activeElement == d.input) d.input.blur(); focusInput(cm); }); } function eventInWidget(display, e) { for (var n = e_target(e); n != display.wrapper; n = n.parentNode) { if (!n || n.ignoreEvents || n.parentNode == display.sizer && n != display.mover) return true; } } function posFromMouse(cm, e, liberal) { var display = cm.display; if (!liberal) { var target = e_target(e); if (target == display.scrollbarH || target == display.scrollbarH.firstChild || target == display.scrollbarV || target == display.scrollbarV.firstChild || target == display.scrollbarFiller || target == display.gutterFiller) return null; } var x, y, space = getRect(display.lineSpace); // Fails unpredictably on IE[67] when mouse is dragged around quickly. try { x = e.clientX; y = e.clientY; } catch (e) { return null; } return coordsChar(cm, x - space.left, y - space.top); } var lastClick, lastDoubleClick; function onMouseDown(e) { if (signalDOMEvent(this, e)) return; var cm = this, display = cm.display, doc = cm.doc, sel = doc.sel; sel.shift = e.shiftKey; if (eventInWidget(display, e)) { if (!webkit) { display.scroller.draggable = false; setTimeout(function(){display.scroller.draggable = true;}, 100); } return; } if (clickInGutter(cm, e)) return; var start = posFromMouse(cm, e); switch (e_button(e)) { case 3: if (captureMiddleClick) onContextMenu.call(cm, cm, e); return; case 2: if (start) extendSelection(cm.doc, start); setTimeout(bind(focusInput, cm), 20); e_preventDefault(e); return; } // For button 1, if it was clicked inside the editor // (posFromMouse returning non-null), we have to adjust the // selection. if (!start) {if (e_target(e) == display.scroller) e_preventDefault(e); return;} if (!cm.state.focused) onFocus(cm); var now = +new Date, type = "single"; if (lastDoubleClick && lastDoubleClick.time > now - 400 && posEq(lastDoubleClick.pos, start)) { type = "triple"; e_preventDefault(e); setTimeout(bind(focusInput, cm), 20); selectLine(cm, start.line); } else if (lastClick && lastClick.time > now - 400 && posEq(lastClick.pos, start)) { type = "double"; lastDoubleClick = {time: now, pos: start}; e_preventDefault(e); var word = findWordAt(getLine(doc, start.line).text, start); extendSelection(cm.doc, word.from, word.to); } else { lastClick = {time: now, pos: start}; } var last = start; if (cm.options.dragDrop && dragAndDrop && !isReadOnly(cm) && !posEq(sel.from, sel.to) && !posLess(start, sel.from) && !posLess(sel.to, start) && type == "single") { var dragEnd = operation(cm, function(e2) { if (webkit) display.scroller.draggable = false; cm.state.draggingText = false; off(document, "mouseup", dragEnd); off(display.scroller, "drop", dragEnd); if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) { e_preventDefault(e2); extendSelection(cm.doc, start); focusInput(cm); } }); // Let the drag handler handle this. if (webkit) display.scroller.draggable = true; cm.state.draggingText = dragEnd; // IE's approach to draggable if (display.scroller.dragDrop) display.scroller.dragDrop(); on(document, "mouseup", dragEnd); on(display.scroller, "drop", dragEnd); return; } e_preventDefault(e); if (type == "single") extendSelection(cm.doc, clipPos(doc, start)); var startstart = sel.from, startend = sel.to, lastPos = start; function doSelect(cur) { if (posEq(lastPos, cur)) return; lastPos = cur; if (type == "single") { extendSelection(cm.doc, clipPos(doc, start), cur); return; } startstart = clipPos(doc, startstart); startend = clipPos(doc, startend); if (type == "double") { var word = findWordAt(getLine(doc, cur.line).text, cur); if (posLess(cur, startstart)) extendSelection(cm.doc, word.from, startend); else extendSelection(cm.doc, startstart, word.to); } else if (type == "triple") { if (posLess(cur, startstart)) extendSelection(cm.doc, startend, clipPos(doc, Pos(cur.line, 0))); else extendSelection(cm.doc, startstart, clipPos(doc, Pos(cur.line + 1, 0))); } } var editorSize = getRect(display.wrapper); // Used to ensure timeout re-tries don't fire when another extend // happened in the meantime (clearTimeout isn't reliable -- at // least on Chrome, the timeouts still happen even when cleared, // if the clear happens after their scheduled firing time). var counter = 0; function extend(e) { var curCount = ++counter; var cur = posFromMouse(cm, e, true); if (!cur) return; if (!posEq(cur, last)) { if (!cm.state.focused) onFocus(cm); last = cur; doSelect(cur); var visible = visibleLines(display, doc); if (cur.line >= visible.to || cur.line < visible.from) setTimeout(operation(cm, function(){if (counter == curCount) extend(e);}), 150); } else { var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0; if (outside) setTimeout(operation(cm, function() { if (counter != curCount) return; display.scroller.scrollTop += outside; extend(e); }), 50); } } function done(e) { counter = Infinity; e_preventDefault(e); focusInput(cm); off(document, "mousemove", move); off(document, "mouseup", up); } var move = operation(cm, function(e) { if (!ie && !e_button(e)) done(e); else extend(e); }); var up = operation(cm, done); on(document, "mousemove", move); on(document, "mouseup", up); } function clickInGutter(cm, e) { var display = cm.display; try { var mX = e.clientX, mY = e.clientY; } catch(e) { return false; } if (mX >= Math.floor(getRect(display.gutters).right)) return false; e_preventDefault(e); if (!hasHandler(cm, "gutterClick")) return true; var lineBox = getRect(display.lineDiv); if (mY > lineBox.bottom) return true; mY -= lineBox.top - display.viewOffset; for (var i = 0; i < cm.options.gutters.length; ++i) { var g = display.gutters.childNodes[i]; if (g && getRect(g).right >= mX) { var line = lineAtHeight(cm.doc, mY); var gutter = cm.options.gutters[i]; signalLater(cm, "gutterClick", cm, line, gutter, e); break; } } return true; } // Kludge to work around strange IE behavior where it'll sometimes // re-fire a series of drag-related events right after the drop (#1551) var lastDrop = 0; function onDrop(e) { var cm = this; if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e) || (cm.options.onDragEvent && cm.options.onDragEvent(cm, addStop(e)))) return; e_preventDefault(e); if (ie) lastDrop = +new Date; var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files; if (!pos || isReadOnly(cm)) return; if (files && files.length && window.FileReader && window.File) { var n = files.length, text = Array(n), read = 0; var loadFile = function(file, i) { var reader = new FileReader; reader.onload = function() { text[i] = reader.result; if (++read == n) { pos = clipPos(cm.doc, pos); makeChange(cm.doc, {from: pos, to: pos, text: splitLines(text.join("\n")), origin: "paste"}, "around"); } }; reader.readAsText(file); }; for (var i = 0; i < n; ++i) loadFile(files[i], i); } else { // Don't do a replace if the drop happened inside of the selected text. if (cm.state.draggingText && !(posLess(pos, cm.doc.sel.from) || posLess(cm.doc.sel.to, pos))) { cm.state.draggingText(e); // Ensure the editor is re-focused setTimeout(bind(focusInput, cm), 20); return; } try { var text = e.dataTransfer.getData("Text"); if (text) { var curFrom = cm.doc.sel.from, curTo = cm.doc.sel.to; setSelection(cm.doc, pos, pos); if (cm.state.draggingText) replaceRange(cm.doc, "", curFrom, curTo, "paste"); cm.replaceSelection(text, null, "paste"); focusInput(cm); onFocus(cm); } } catch(e){} } } function onDragStart(cm, e) { if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return; } if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) return; var txt = cm.getSelection(); e.dataTransfer.setData("Text", txt); // Use dummy image instead of default browsers image. // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there. if (e.dataTransfer.setDragImage && !safari) { var img = elt("img", null, null, "position: fixed; left: 0; top: 0;"); if (opera) { img.width = img.height = 1; cm.display.wrapper.appendChild(img); // Force a relayout, or Opera won't use our image for some obscure reason img._top = img.offsetTop; } e.dataTransfer.setDragImage(img, 0, 0); if (opera) img.parentNode.removeChild(img); } } function setScrollTop(cm, val) { if (Math.abs(cm.doc.scrollTop - val) < 2) return; cm.doc.scrollTop = val; if (!gecko) updateDisplay(cm, [], val); if (cm.display.scroller.scrollTop != val) cm.display.scroller.scrollTop = val; if (cm.display.scrollbarV.scrollTop != val) cm.display.scrollbarV.scrollTop = val; if (gecko) updateDisplay(cm, []); startWorker(cm, 100); } function setScrollLeft(cm, val, isScroller) { if (isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) return; val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth); cm.doc.scrollLeft = val; alignHorizontally(cm); if (cm.display.scroller.scrollLeft != val) cm.display.scroller.scrollLeft = val; if (cm.display.scrollbarH.scrollLeft != val) cm.display.scrollbarH.scrollLeft = val; } // Since the delta values reported on mouse wheel events are // unstandardized between browsers and even browser versions, and // generally horribly unpredictable, this code starts by measuring // the scroll effect that the first few mouse wheel events have, // and, from that, detects the way it can convert deltas to pixel // offsets afterwards. // // The reason we want to know the amount a wheel event will scroll // is that it gives us a chance to update the display before the // actual scrolling happens, reducing flickering. var wheelSamples = 0, wheelPixelsPerUnit = null; // Fill in a browser-detected starting value on browsers where we // know one. These don't have to be accurate -- the result of them // being wrong would just be a slight flicker on the first wheel // scroll (if it is large enough). if (ie) wheelPixelsPerUnit = -.53; else if (gecko) wheelPixelsPerUnit = 15; else if (chrome) wheelPixelsPerUnit = -.7; else if (safari) wheelPixelsPerUnit = -1/3; function onScrollWheel(cm, e) { var dx = e.wheelDeltaX, dy = e.wheelDeltaY; if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) dx = e.detail; if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) dy = e.detail; else if (dy == null) dy = e.wheelDelta; var display = cm.display, scroll = display.scroller; // Quit if there's nothing to scroll here if (!(dx && scroll.scrollWidth > scroll.clientWidth || dy && scroll.scrollHeight > scroll.clientHeight)) return; // Webkit browsers on OS X abort momentum scrolls when the target // of the scroll event is removed from the scrollable element. // This hack (see related code in patchDisplay) makes sure the // element is kept around. if (dy && mac && webkit) { for (var cur = e.target; cur != scroll; cur = cur.parentNode) { if (cur.lineObj) { cm.display.currentWheelTarget = cur; break; } } } // On some browsers, horizontal scrolling will cause redraws to // happen before the gutter has been realigned, causing it to // wriggle around in a most unseemly way. When we have an // estimated pixels/delta value, we just handle horizontal // scrolling entirely here. It'll be slightly off from native, but // better than glitching out. if (dx && !gecko && !opera && wheelPixelsPerUnit != null) { if (dy) setScrollTop(cm, Math.max(0, Math.min(scroll.scrollTop + dy * wheelPixelsPerUnit, scroll.scrollHeight - scroll.clientHeight))); setScrollLeft(cm, Math.max(0, Math.min(scroll.scrollLeft + dx * wheelPixelsPerUnit, scroll.scrollWidth - scroll.clientWidth))); e_preventDefault(e); display.wheelStartX = null; // Abort measurement, if in progress return; } if (dy && wheelPixelsPerUnit != null) { var pixels = dy * wheelPixelsPerUnit; var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight; if (pixels < 0) top = Math.max(0, top + pixels - 50); else bot = Math.min(cm.doc.height, bot + pixels + 50); updateDisplay(cm, [], {top: top, bottom: bot}); } if (wheelSamples < 20) { if (display.wheelStartX == null) { display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop; display.wheelDX = dx; display.wheelDY = dy; setTimeout(function() { if (display.wheelStartX == null) return; var movedX = scroll.scrollLeft - display.wheelStartX; var movedY = scroll.scrollTop - display.wheelStartY; var sample = (movedY && display.wheelDY && movedY / display.wheelDY) || (movedX && display.wheelDX && movedX / display.wheelDX); display.wheelStartX = display.wheelStartY = null; if (!sample) return; wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1); ++wheelSamples; }, 200); } else { display.wheelDX += dx; display.wheelDY += dy; } } } function doHandleBinding(cm, bound, dropShift) { if (typeof bound == "string") { bound = commands[bound]; if (!bound) return false; } // Ensure previous input has been read, so that the handler sees a // consistent view of the document if (cm.display.pollingFast && readInput(cm)) cm.display.pollingFast = false; var doc = cm.doc, prevShift = doc.sel.shift, done = false; try { if (isReadOnly(cm)) cm.state.suppressEdits = true; if (dropShift) doc.sel.shift = false; done = bound(cm) != Pass; } finally { doc.sel.shift = prevShift; cm.state.suppressEdits = false; } return done; } function allKeyMaps(cm) { var maps = cm.state.keyMaps.slice(0); if (cm.options.extraKeys) maps.push(cm.options.extraKeys); maps.push(cm.options.keyMap); return maps; } var maybeTransition; function handleKeyBinding(cm, e) { // Handle auto keymap transitions var startMap = getKeyMap(cm.options.keyMap), next = startMap.auto; clearTimeout(maybeTransition); if (next && !isModifierKey(e)) maybeTransition = setTimeout(function() { if (getKeyMap(cm.options.keyMap) == startMap) { cm.options.keyMap = (next.call ? next.call(null, cm) : next); keyMapChanged(cm); } }, 50); var name = keyName(e, true), handled = false; if (!name) return false; var keymaps = allKeyMaps(cm); if (e.shiftKey) { // First try to resolve full name (including 'Shift-'). Failing // that, see if there is a cursor-motion command (starting with // 'go') bound to the keyname without 'Shift-'. handled = lookupKey("Shift-" + name, keymaps, function(b) {return doHandleBinding(cm, b, true);}) || lookupKey(name, keymaps, function(b) { if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion) return doHandleBinding(cm, b); }); } else { handled = lookupKey(name, keymaps, function(b) { return doHandleBinding(cm, b); }); } if (handled) { e_preventDefault(e); restartBlink(cm); if (ie_lt9) { e.oldKeyCode = e.keyCode; e.keyCode = 0; } signalLater(cm, "keyHandled", cm, name, e); } return handled; } function handleCharBinding(cm, e, ch) { var handled = lookupKey("'" + ch + "'", allKeyMaps(cm), function(b) { return doHandleBinding(cm, b, true); }); if (handled) { e_preventDefault(e); restartBlink(cm); signalLater(cm, "keyHandled", cm, "'" + ch + "'", e); } return handled; } var lastStoppedKey = null; function onKeyDown(e) { var cm = this; if (!cm.state.focused) onFocus(cm); if (ie && e.keyCode == 27) { e.returnValue = false; } if (signalDOMEvent(cm, e) || cm.options.onKeyEvent && cm.options.onKeyEvent(cm, addStop(e))) return; var code = e.keyCode; // IE does strange things with escape. cm.doc.sel.shift = code == 16 || e.shiftKey; // First give onKeyEvent option a chance to handle this. var handled = handleKeyBinding(cm, e); if (opera) { lastStoppedKey = handled ? code : null; // Opera has no cut event... we try to at least catch the key combo if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey)) cm.replaceSelection(""); } } function onKeyPress(e) { var cm = this; if (signalDOMEvent(cm, e) || cm.options.onKeyEvent && cm.options.onKeyEvent(cm, addStop(e))) return; var keyCode = e.keyCode, charCode = e.charCode; if (opera && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;} if (((opera && (!e.which || e.which < 10)) || khtml) && handleKeyBinding(cm, e)) return; var ch = String.fromCharCode(charCode == null ? keyCode : charCode); if (this.options.electricChars && this.doc.mode.electricChars && this.options.smartIndent && !isReadOnly(this) && this.doc.mode.electricChars.indexOf(ch) > -1) setTimeout(operation(cm, function() {indentLine(cm, cm.doc.sel.to.line, "smart");}), 75); if (handleCharBinding(cm, e, ch)) return; if (ie && !ie_lt9) cm.display.inputHasSelection = null; fastPoll(cm); } function onFocus(cm) { if (cm.options.readOnly == "nocursor") return; if (!cm.state.focused) { signal(cm, "focus", cm); cm.state.focused = true; if (cm.display.wrapper.className.search(/\bCodeMirror-focused\b/) == -1) cm.display.wrapper.className += " CodeMirror-focused"; resetInput(cm, true); } slowPoll(cm); restartBlink(cm); } function onBlur(cm) { if (cm.state.focused) { signal(cm, "blur", cm); cm.state.focused = false; cm.display.wrapper.className = cm.display.wrapper.className.replace(" CodeMirror-focused", ""); } clearInterval(cm.display.blinker); setTimeout(function() {if (!cm.state.focused) cm.doc.sel.shift = false;}, 150); } var detectingSelectAll; function onContextMenu(cm, e) { if (signalDOMEvent(cm, e, "contextmenu")) return; var display = cm.display, sel = cm.doc.sel; if (eventInWidget(display, e)) return; var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop; if (!pos || opera) return; // Opera is difficult. if (posEq(sel.from, sel.to) || posLess(pos, sel.from) || !posLess(pos, sel.to)) operation(cm, setSelection)(cm.doc, pos, pos); var oldCSS = display.input.style.cssText; display.inputDiv.style.position = "absolute"; display.input.style.cssText = "position: fixed; width: 30px; height: 30px; top: " + (e.clientY - 5) + "px; left: " + (e.clientX - 5) + "px; z-index: 1000; background: white; outline: none;" + "border-width: 0; outline: none; overflow: hidden; opacity: .05; -ms-opacity: .05; filter: alpha(opacity=5);"; focusInput(cm); resetInput(cm, true); // Adds "Select all" to context menu in FF if (posEq(sel.from, sel.to)) display.input.value = display.prevInput = " "; function prepareSelectAllHack() { if (display.input.selectionStart != null) { var extval = display.input.value = " " + (posEq(sel.from, sel.to) ? "" : display.input.value); display.prevInput = " "; display.input.selectionStart = 1; display.input.selectionEnd = extval.length; } } function rehide() { display.inputDiv.style.position = "relative"; display.input.style.cssText = oldCSS; if (ie_lt9) display.scrollbarV.scrollTop = display.scroller.scrollTop = scrollPos; slowPoll(cm); // Try to detect the user choosing select-all if (display.input.selectionStart != null) { if (!ie || ie_lt9) prepareSelectAllHack(); clearTimeout(detectingSelectAll); var i = 0, poll = function(){ if (display.prevInput == " " && display.input.selectionStart == 0) operation(cm, commands.selectAll)(cm); else if (i++ < 10) detectingSelectAll = setTimeout(poll, 500); else resetInput(cm); }; detectingSelectAll = setTimeout(poll, 200); } } if (ie && !ie_lt9) prepareSelectAllHack(); if (captureMiddleClick) { e_stop(e); var mouseup = function() { off(window, "mouseup", mouseup); setTimeout(rehide, 20); }; on(window, "mouseup", mouseup); } else { setTimeout(rehide, 50); } } // UPDATING var changeEnd = CodeMirror.changeEnd = function(change) { if (!change.text) return change.to; return Pos(change.from.line + change.text.length - 1, lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0)); }; // Make sure a position will be valid after the given change. function clipPostChange(doc, change, pos) { if (!posLess(change.from, pos)) return clipPos(doc, pos); var diff = (change.text.length - 1) - (change.to.line - change.from.line); if (pos.line > change.to.line + diff) { var preLine = pos.line - diff, lastLine = doc.first + doc.size - 1; if (preLine > lastLine) return Pos(lastLine, getLine(doc, lastLine).text.length); return clipToLen(pos, getLine(doc, preLine).text.length); } if (pos.line == change.to.line + diff) return clipToLen(pos, lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0) + getLine(doc, change.to.line).text.length - change.to.ch); var inside = pos.line - change.from.line; return clipToLen(pos, change.text[inside].length + (inside ? 0 : change.from.ch)); } // Hint can be null|"end"|"start"|"around"|{anchor,head} function computeSelAfterChange(doc, change, hint) { if (hint && typeof hint == "object") // Assumed to be {anchor, head} object return {anchor: clipPostChange(doc, change, hint.anchor), head: clipPostChange(doc, change, hint.head)}; if (hint == "start") return {anchor: change.from, head: change.from}; var end = changeEnd(change); if (hint == "around") return {anchor: change.from, head: end}; if (hint == "end") return {anchor: end, head: end}; // hint is null, leave the selection alone as much as possible var adjustPos = function(pos) { if (posLess(pos, change.from)) return pos; if (!posLess(change.to, pos)) return end; var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch; if (pos.line == change.to.line) ch += end.ch - change.to.ch; return Pos(line, ch); }; return {anchor: adjustPos(doc.sel.anchor), head: adjustPos(doc.sel.head)}; } function filterChange(doc, change, update) { var obj = { canceled: false, from: change.from, to: change.to, text: change.text, origin: change.origin, cancel: function() { this.canceled = true; } }; if (update) obj.update = function(from, to, text, origin) { if (from) this.from = clipPos(doc, from); if (to) this.to = clipPos(doc, to); if (text) this.text = text; if (origin !== undefined) this.origin = origin; }; signal(doc, "beforeChange", doc, obj); if (doc.cm) signal(doc.cm, "beforeChange", doc.cm, obj); if (obj.canceled) return null; return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin}; } // Replace the range from from to to by the strings in replacement. // change is a {from, to, text [, origin]} object function makeChange(doc, change, selUpdate, ignoreReadOnly) { if (doc.cm) { if (!doc.cm.curOp) return operation(doc.cm, makeChange)(doc, change, selUpdate, ignoreReadOnly); if (doc.cm.state.suppressEdits) return; } if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) { change = filterChange(doc, change, true); if (!change) return; } // Possibly split or suppress the update based on the presence // of read-only spans in its range. var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to); if (split) { for (var i = split.length - 1; i >= 1; --i) makeChangeNoReadonly(doc, {from: split[i].from, to: split[i].to, text: [""]}); if (split.length) makeChangeNoReadonly(doc, {from: split[0].from, to: split[0].to, text: change.text}, selUpdate); } else { makeChangeNoReadonly(doc, change, selUpdate); } } function makeChangeNoReadonly(doc, change, selUpdate) { var selAfter = computeSelAfterChange(doc, change, selUpdate); addToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN); makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change)); var rebased = []; linkedDocs(doc, function(doc, sharedHist) { if (!sharedHist && indexOf(rebased, doc.history) == -1) { rebaseHist(doc.history, change); rebased.push(doc.history); } makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change)); }); } function makeChangeFromHistory(doc, type) { if (doc.cm && doc.cm.state.suppressEdits) return; var hist = doc.history; var event = (type == "undo" ? hist.done : hist.undone).pop(); if (!event) return; var anti = {changes: [], anchorBefore: event.anchorAfter, headBefore: event.headAfter, anchorAfter: event.anchorBefore, headAfter: event.headBefore, generation: hist.generation}; (type == "undo" ? hist.undone : hist.done).push(anti); hist.generation = event.generation || ++hist.maxGeneration; var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange"); for (var i = event.changes.length - 1; i >= 0; --i) { var change = event.changes[i]; change.origin = type; if (filter && !filterChange(doc, change, false)) { (type == "undo" ? hist.done : hist.undone).length = 0; return; } anti.changes.push(historyChangeFromChange(doc, change)); var after = i ? computeSelAfterChange(doc, change, null) : {anchor: event.anchorBefore, head: event.headBefore}; makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change)); var rebased = []; linkedDocs(doc, function(doc, sharedHist) { if (!sharedHist && indexOf(rebased, doc.history) == -1) { rebaseHist(doc.history, change); rebased.push(doc.history); } makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change)); }); } } function shiftDoc(doc, distance) { function shiftPos(pos) {return Pos(pos.line + distance, pos.ch);} doc.first += distance; if (doc.cm) regChange(doc.cm, doc.first, doc.first, distance); doc.sel.head = shiftPos(doc.sel.head); doc.sel.anchor = shiftPos(doc.sel.anchor); doc.sel.from = shiftPos(doc.sel.from); doc.sel.to = shiftPos(doc.sel.to); } function makeChangeSingleDoc(doc, change, selAfter, spans) { if (doc.cm && !doc.cm.curOp) return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans); if (change.to.line < doc.first) { shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line)); return; } if (change.from.line > doc.lastLine()) return; // Clip the change to the size of this doc if (change.from.line < doc.first) { var shift = change.text.length - 1 - (doc.first - change.from.line); shiftDoc(doc, shift); change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch), text: [lst(change.text)], origin: change.origin}; } var last = doc.lastLine(); if (change.to.line > last) { change = {from: change.from, to: Pos(last, getLine(doc, last).text.length), text: [change.text[0]], origin: change.origin}; } change.removed = getBetween(doc, change.from, change.to); if (!selAfter) selAfter = computeSelAfterChange(doc, change, null); if (doc.cm) makeChangeSingleDocInEditor(doc.cm, change, spans, selAfter); else updateDoc(doc, change, spans, selAfter); } function makeChangeSingleDocInEditor(cm, change, spans, selAfter) { var doc = cm.doc, display = cm.display, from = change.from, to = change.to; var recomputeMaxLength = false, checkWidthStart = from.line; if (!cm.options.lineWrapping) { checkWidthStart = lineNo(visualLine(doc, getLine(doc, from.line))); doc.iter(checkWidthStart, to.line + 1, function(line) { if (line == display.maxLine) { recomputeMaxLength = true; return true; } }); } if (!posLess(doc.sel.head, change.from) && !posLess(change.to, doc.sel.head)) cm.curOp.cursorActivity = true; updateDoc(doc, change, spans, selAfter, estimateHeight(cm)); if (!cm.options.lineWrapping) { doc.iter(checkWidthStart, from.line + change.text.length, function(line) { var len = lineLength(doc, line); if (len > display.maxLineLength) { display.maxLine = line; display.maxLineLength = len; display.maxLineChanged = true; recomputeMaxLength = false; } }); if (recomputeMaxLength) cm.curOp.updateMaxLine = true; } // Adjust frontier, schedule worker doc.frontier = Math.min(doc.frontier, from.line); startWorker(cm, 400); var lendiff = change.text.length - (to.line - from.line) - 1; // Remember that these lines changed, for updating the display regChange(cm, from.line, to.line + 1, lendiff); if (hasHandler(cm, "change")) { var changeObj = {from: from, to: to, text: change.text, removed: change.removed, origin: change.origin}; if (cm.curOp.textChanged) { for (var cur = cm.curOp.textChanged; cur.next; cur = cur.next) {} cur.next = changeObj; } else cm.curOp.textChanged = changeObj; } } function replaceRange(doc, code, from, to, origin) { if (!to) to = from; if (posLess(to, from)) { var tmp = to; to = from; from = tmp; } if (typeof code == "string") code = splitLines(code); makeChange(doc, {from: from, to: to, text: code, origin: origin}, null); } // POSITION OBJECT function Pos(line, ch) { if (!(this instanceof Pos)) return new Pos(line, ch); this.line = line; this.ch = ch; } CodeMirror.Pos = Pos; function posEq(a, b) {return a.line == b.line && a.ch == b.ch;} function posLess(a, b) {return a.line < b.line || (a.line == b.line && a.ch < b.ch);} function copyPos(x) {return Pos(x.line, x.ch);} // SELECTION function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1));} function clipPos(doc, pos) { if (pos.line < doc.first) return Pos(doc.first, 0); var last = doc.first + doc.size - 1; if (pos.line > last) return Pos(last, getLine(doc, last).text.length); return clipToLen(pos, getLine(doc, pos.line).text.length); } function clipToLen(pos, linelen) { var ch = pos.ch; if (ch == null || ch > linelen) return Pos(pos.line, linelen); else if (ch < 0) return Pos(pos.line, 0); else return pos; } function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size;} // If shift is held, this will move the selection anchor. Otherwise, // it'll set the whole selection. function extendSelection(doc, pos, other, bias) { if (doc.sel.shift || doc.sel.extend) { var anchor = doc.sel.anchor; if (other) { var posBefore = posLess(pos, anchor); if (posBefore != posLess(other, anchor)) { anchor = pos; pos = other; } else if (posBefore != posLess(pos, other)) { pos = other; } } setSelection(doc, anchor, pos, bias); } else { setSelection(doc, pos, other || pos, bias); } if (doc.cm) doc.cm.curOp.userSelChange = true; } function filterSelectionChange(doc, anchor, head) { var obj = {anchor: anchor, head: head}; signal(doc, "beforeSelectionChange", doc, obj); if (doc.cm) signal(doc.cm, "beforeSelectionChange", doc.cm, obj); obj.anchor = clipPos(doc, obj.anchor); obj.head = clipPos(doc, obj.head); return obj; } // Update the selection. Last two args are only used by // updateDoc, since they have to be expressed in the line // numbers before the update. function setSelection(doc, anchor, head, bias, checkAtomic) { if (!checkAtomic && hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange")) { var filtered = filterSelectionChange(doc, anchor, head); head = filtered.head; anchor = filtered.anchor; } var sel = doc.sel; sel.goalColumn = null; // Skip over atomic spans. if (checkAtomic || !posEq(anchor, sel.anchor)) anchor = skipAtomic(doc, anchor, bias, checkAtomic != "push"); if (checkAtomic || !posEq(head, sel.head)) head = skipAtomic(doc, head, bias, checkAtomic != "push"); if (posEq(sel.anchor, anchor) && posEq(sel.head, head)) return; sel.anchor = anchor; sel.head = head; var inv = posLess(head, anchor); sel.from = inv ? head : anchor; sel.to = inv ? anchor : head; if (doc.cm) doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = doc.cm.curOp.cursorActivity = true; signalLater(doc, "cursorActivity", doc); } function reCheckSelection(cm) { setSelection(cm.doc, cm.doc.sel.from, cm.doc.sel.to, null, "push"); } function skipAtomic(doc, pos, bias, mayClear) { var flipped = false, curPos = pos; var dir = bias || 1; doc.cantEdit = false; search: for (;;) { var line = getLine(doc, curPos.line); if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) { var sp = line.markedSpans[i], m = sp.marker; if ((sp.from == null || (m.inclusiveLeft ? sp.from <= curPos.ch : sp.from < curPos.ch)) && (sp.to == null || (m.inclusiveRight ? sp.to >= curPos.ch : sp.to > curPos.ch))) { if (mayClear) { signal(m, "beforeCursorEnter"); if (m.explicitlyCleared) { if (!line.markedSpans) break; else {--i; continue;} } } if (!m.atomic) continue; var newPos = m.find()[dir < 0 ? "from" : "to"]; if (posEq(newPos, curPos)) { newPos.ch += dir; if (newPos.ch < 0) { if (newPos.line > doc.first) newPos = clipPos(doc, Pos(newPos.line - 1)); else newPos = null; } else if (newPos.ch > line.text.length) { if (newPos.line < doc.first + doc.size - 1) newPos = Pos(newPos.line + 1, 0); else newPos = null; } if (!newPos) { if (flipped) { // Driven in a corner -- no valid cursor position found at all // -- try again *with* clearing, if we didn't already if (!mayClear) return skipAtomic(doc, pos, bias, true); // Otherwise, turn off editing until further notice, and return the start of the doc doc.cantEdit = true; return Pos(doc.first, 0); } flipped = true; newPos = pos; dir = -dir; } } curPos = newPos; continue search; } } } return curPos; } } // SCROLLING function scrollCursorIntoView(cm) { var coords = scrollPosIntoView(cm, cm.doc.sel.head, cm.options.cursorScrollMargin); if (!cm.state.focused) return; var display = cm.display, box = getRect(display.sizer), doScroll = null; if (coords.top + box.top < 0) doScroll = true; else if (coords.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) doScroll = false; if (doScroll != null && !phantom) { var hidden = display.cursor.style.display == "none"; if (hidden) { display.cursor.style.display = ""; display.cursor.style.left = coords.left + "px"; display.cursor.style.top = (coords.top - display.viewOffset) + "px"; } display.cursor.scrollIntoView(doScroll); if (hidden) display.cursor.style.display = "none"; } } function scrollPosIntoView(cm, pos, margin) { if (margin == null) margin = 0; for (;;) { var changed = false, coords = cursorCoords(cm, pos); var scrollPos = calculateScrollPos(cm, coords.left, coords.top - margin, coords.left, coords.bottom + margin); var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft; if (scrollPos.scrollTop != null) { setScrollTop(cm, scrollPos.scrollTop); if (Math.abs(cm.doc.scrollTop - startTop) > 1) changed = true; } if (scrollPos.scrollLeft != null) { setScrollLeft(cm, scrollPos.scrollLeft); if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) changed = true; } if (!changed) return coords; } } function scrollIntoView(cm, x1, y1, x2, y2) { var scrollPos = calculateScrollPos(cm, x1, y1, x2, y2); if (scrollPos.scrollTop != null) setScrollTop(cm, scrollPos.scrollTop); if (scrollPos.scrollLeft != null) setScrollLeft(cm, scrollPos.scrollLeft); } function calculateScrollPos(cm, x1, y1, x2, y2) { var display = cm.display, snapMargin = textHeight(cm.display); if (y1 < 0) y1 = 0; var screen = display.scroller.clientHeight - scrollerCutOff, screentop = display.scroller.scrollTop, result = {}; var docBottom = cm.doc.height + paddingVert(display); var atTop = y1 < snapMargin, atBottom = y2 > docBottom - snapMargin; if (y1 < screentop) { result.scrollTop = atTop ? 0 : y1; } else if (y2 > screentop + screen) { var newTop = Math.min(y1, (atBottom ? docBottom : y2) - screen); if (newTop != screentop) result.scrollTop = newTop; } var screenw = display.scroller.clientWidth - scrollerCutOff, screenleft = display.scroller.scrollLeft; x1 += display.gutters.offsetWidth; x2 += display.gutters.offsetWidth; var gutterw = display.gutters.offsetWidth; var atLeft = x1 < gutterw + 10; if (x1 < screenleft + gutterw || atLeft) { if (atLeft) x1 = 0; result.scrollLeft = Math.max(0, x1 - 10 - gutterw); } else if (x2 > screenw + screenleft - 3) { result.scrollLeft = x2 + 10 - screenw; } return result; } function updateScrollPos(cm, left, top) { cm.curOp.updateScrollPos = {scrollLeft: left == null ? cm.doc.scrollLeft : left, scrollTop: top == null ? cm.doc.scrollTop : top}; } function addToScrollPos(cm, left, top) { var pos = cm.curOp.updateScrollPos || (cm.curOp.updateScrollPos = {scrollLeft: cm.doc.scrollLeft, scrollTop: cm.doc.scrollTop}); var scroll = cm.display.scroller; pos.scrollTop = Math.max(0, Math.min(scroll.scrollHeight - scroll.clientHeight, pos.scrollTop + top)); pos.scrollLeft = Math.max(0, Math.min(scroll.scrollWidth - scroll.clientWidth, pos.scrollLeft + left)); } // API UTILITIES function indentLine(cm, n, how, aggressive) { var doc = cm.doc; if (how == null) how = "add"; if (how == "smart") { if (!cm.doc.mode.indent) how = "prev"; else var state = getStateBefore(cm, n); } var tabSize = cm.options.tabSize; var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize); var curSpaceString = line.text.match(/^\s*/)[0], indentation; if (how == "smart") { indentation = cm.doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text); if (indentation == Pass) { if (!aggressive) return; how = "prev"; } } if (how == "prev") { if (n > doc.first) indentation = countColumn(getLine(doc, n-1).text, null, tabSize); else indentation = 0; } else if (how == "add") { indentation = curSpace + cm.options.indentUnit; } else if (how == "subtract") { indentation = curSpace - cm.options.indentUnit; } else if (typeof how == "number") { indentation = curSpace + how; } indentation = Math.max(0, indentation); var indentString = "", pos = 0; if (cm.options.indentWithTabs) for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";} if (pos < indentation) indentString += spaceStr(indentation - pos); if (indentString != curSpaceString) replaceRange(cm.doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input"); line.stateAfter = null; } function changeLine(cm, handle, op) { var no = handle, line = handle, doc = cm.doc; if (typeof handle == "number") line = getLine(doc, clipLine(doc, handle)); else no = lineNo(handle); if (no == null) return null; if (op(line, no)) regChange(cm, no, no + 1); else return null; return line; } function findPosH(doc, pos, dir, unit, visually) { var line = pos.line, ch = pos.ch, origDir = dir; var lineObj = getLine(doc, line); var possible = true; function findNextLine() { var l = line + dir; if (l < doc.first || l >= doc.first + doc.size) return (possible = false); line = l; return lineObj = getLine(doc, l); } function moveOnce(boundToLine) { var next = (visually ? moveVisually : moveLogically)(lineObj, ch, dir, true); if (next == null) { if (!boundToLine && findNextLine()) { if (visually) ch = (dir < 0 ? lineRight : lineLeft)(lineObj); else ch = dir < 0 ? lineObj.text.length : 0; } else return (possible = false); } else ch = next; return true; } if (unit == "char") moveOnce(); else if (unit == "column") moveOnce(true); else if (unit == "word" || unit == "group") { var sawType = null, group = unit == "group"; for (var first = true;; first = false) { if (dir < 0 && !moveOnce(!first)) break; var cur = lineObj.text.charAt(ch) || "\n"; var type = isWordChar(cur) ? "w" : !group ? null : /\s/.test(cur) ? null : "p"; if (sawType && sawType != type) { if (dir < 0) {dir = 1; moveOnce();} break; } if (type) sawType = type; if (dir > 0 && !moveOnce(!first)) break; } } var result = skipAtomic(doc, Pos(line, ch), origDir, true); if (!possible) result.hitSide = true; return result; } function findPosV(cm, pos, dir, unit) { var doc = cm.doc, x = pos.left, y; if (unit == "page") { var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight); y = pos.top + dir * (pageSize - (dir < 0 ? 1.5 : .5) * textHeight(cm.display)); } else if (unit == "line") { y = dir > 0 ? pos.bottom + 3 : pos.top - 3; } for (;;) { var target = coordsChar(cm, x, y); if (!target.outside) break; if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break; } y += dir * 5; } return target; } function findWordAt(line, pos) { var start = pos.ch, end = pos.ch; if (line) { if ((pos.xRel < 0 || end == line.length) && start) --start; else ++end; var startChar = line.charAt(start); var check = isWordChar(startChar) ? isWordChar : /\s/.test(startChar) ? function(ch) {return /\s/.test(ch);} : function(ch) {return !/\s/.test(ch) && !isWordChar(ch);}; while (start > 0 && check(line.charAt(start - 1))) --start; while (end < line.length && check(line.charAt(end))) ++end; } return {from: Pos(pos.line, start), to: Pos(pos.line, end)}; } function selectLine(cm, line) { extendSelection(cm.doc, Pos(line, 0), clipPos(cm.doc, Pos(line + 1, 0))); } // PROTOTYPE // The publicly visible API. Note that operation(null, f) means // 'wrap f in an operation, performed on its `this` parameter' CodeMirror.prototype = { constructor: CodeMirror, focus: function(){window.focus(); focusInput(this); onFocus(this); fastPoll(this);}, setOption: function(option, value) { var options = this.options, old = options[option]; if (options[option] == value && option != "mode") return; options[option] = value; if (optionHandlers.hasOwnProperty(option)) operation(this, optionHandlers[option])(this, value, old); }, getOption: function(option) {return this.options[option];}, getDoc: function() {return this.doc;}, addKeyMap: function(map, bottom) { this.state.keyMaps[bottom ? "push" : "unshift"](map); }, removeKeyMap: function(map) { var maps = this.state.keyMaps; for (var i = 0; i < maps.length; ++i) if (maps[i] == map || (typeof maps[i] != "string" && maps[i].name == map)) { maps.splice(i, 1); return true; } }, addOverlay: operation(null, function(spec, options) { var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec); if (mode.startState) throw new Error("Overlays may not be stateful."); this.state.overlays.push({mode: mode, modeSpec: spec, opaque: options && options.opaque}); this.state.modeGen++; regChange(this); }), removeOverlay: operation(null, function(spec) { var overlays = this.state.overlays; for (var i = 0; i < overlays.length; ++i) { var cur = overlays[i].modeSpec; if (cur == spec || typeof spec == "string" && cur.name == spec) { overlays.splice(i, 1); this.state.modeGen++; regChange(this); return; } } }), indentLine: operation(null, function(n, dir, aggressive) { if (typeof dir != "string" && typeof dir != "number") { if (dir == null) dir = this.options.smartIndent ? "smart" : "prev"; else dir = dir ? "add" : "subtract"; } if (isLine(this.doc, n)) indentLine(this, n, dir, aggressive); }), indentSelection: operation(null, function(how) { var sel = this.doc.sel; if (posEq(sel.from, sel.to)) return indentLine(this, sel.from.line, how); var e = sel.to.line - (sel.to.ch ? 0 : 1); for (var i = sel.from.line; i <= e; ++i) indentLine(this, i, how); }), // Fetch the parser token for a given character. Useful for hacks // that want to inspect the mode state (say, for completion). getTokenAt: function(pos, precise) { var doc = this.doc; pos = clipPos(doc, pos); var state = getStateBefore(this, pos.line, precise), mode = this.doc.mode; var line = getLine(doc, pos.line); var stream = new StringStream(line.text, this.options.tabSize); while (stream.pos < pos.ch && !stream.eol()) { stream.start = stream.pos; var style = mode.token(stream, state); } return {start: stream.start, end: stream.pos, string: stream.current(), className: style || null, // Deprecated, use 'type' instead type: style || null, state: state}; }, getTokenTypeAt: function(pos) { pos = clipPos(this.doc, pos); var styles = getLineStyles(this, getLine(this.doc, pos.line)); var before = 0, after = (styles.length - 1) / 2, ch = pos.ch; if (ch == 0) return styles[2]; for (;;) { var mid = (before + after) >> 1; if ((mid ? styles[mid * 2 - 1] : 0) >= ch) after = mid; else if (styles[mid * 2 + 1] < ch) before = mid + 1; else return styles[mid * 2 + 2]; } }, getModeAt: function(pos) { var mode = this.doc.mode; if (!mode.innerMode) return mode; return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode; }, getHelper: function(pos, type) { if (!helpers.hasOwnProperty(type)) return; var help = helpers[type], mode = this.getModeAt(pos); return mode[type] && help[mode[type]] || mode.helperType && help[mode.helperType] || help[mode.name]; }, getStateAfter: function(line, precise) { var doc = this.doc; line = clipLine(doc, line == null ? doc.first + doc.size - 1: line); return getStateBefore(this, line + 1, precise); }, cursorCoords: function(start, mode) { var pos, sel = this.doc.sel; if (start == null) pos = sel.head; else if (typeof start == "object") pos = clipPos(this.doc, start); else pos = start ? sel.from : sel.to; return cursorCoords(this, pos, mode || "page"); }, charCoords: function(pos, mode) { return charCoords(this, clipPos(this.doc, pos), mode || "page"); }, coordsChar: function(coords, mode) { coords = fromCoordSystem(this, coords, mode || "page"); return coordsChar(this, coords.left, coords.top); }, lineAtHeight: function(height, mode) { height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top; return lineAtHeight(this.doc, height + this.display.viewOffset); }, heightAtLine: function(line, mode) { var end = false, last = this.doc.first + this.doc.size - 1; if (line < this.doc.first) line = this.doc.first; else if (line > last) { line = last; end = true; } var lineObj = getLine(this.doc, line); return intoCoordSystem(this, getLine(this.doc, line), {top: 0, left: 0}, mode || "page").top + (end ? lineObj.height : 0); }, defaultTextHeight: function() { return textHeight(this.display); }, defaultCharWidth: function() { return charWidth(this.display); }, setGutterMarker: operation(null, function(line, gutterID, value) { return changeLine(this, line, function(line) { var markers = line.gutterMarkers || (line.gutterMarkers = {}); markers[gutterID] = value; if (!value && isEmpty(markers)) line.gutterMarkers = null; return true; }); }), clearGutter: operation(null, function(gutterID) { var cm = this, doc = cm.doc, i = doc.first; doc.iter(function(line) { if (line.gutterMarkers && line.gutterMarkers[gutterID]) { line.gutterMarkers[gutterID] = null; regChange(cm, i, i + 1); if (isEmpty(line.gutterMarkers)) line.gutterMarkers = null; } ++i; }); }), addLineClass: operation(null, function(handle, where, cls) { return changeLine(this, handle, function(line) { var prop = where == "text" ? "textClass" : where == "background" ? "bgClass" : "wrapClass"; if (!line[prop]) line[prop] = cls; else if (new RegExp("(?:^|\\s)" + cls + "(?:$|\\s)").test(line[prop])) return false; else line[prop] += " " + cls; return true; }); }), removeLineClass: operation(null, function(handle, where, cls) { return changeLine(this, handle, function(line) { var prop = where == "text" ? "textClass" : where == "background" ? "bgClass" : "wrapClass"; var cur = line[prop]; if (!cur) return false; else if (cls == null) line[prop] = null; else { var found = cur.match(new RegExp("(?:^|\\s+)" + cls + "(?:$|\\s+)")); if (!found) return false; var end = found.index + found[0].length; line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null; } return true; }); }), addLineWidget: operation(null, function(handle, node, options) { return addLineWidget(this, handle, node, options); }), removeLineWidget: function(widget) { widget.clear(); }, lineInfo: function(line) { if (typeof line == "number") { if (!isLine(this.doc, line)) return null; var n = line; line = getLine(this.doc, line); if (!line) return null; } else { var n = lineNo(line); if (n == null) return null; } return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers, textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass, widgets: line.widgets}; }, getViewport: function() { return {from: this.display.showingFrom, to: this.display.showingTo};}, addWidget: function(pos, node, scroll, vert, horiz) { var display = this.display; pos = cursorCoords(this, clipPos(this.doc, pos)); var top = pos.bottom, left = pos.left; node.style.position = "absolute"; display.sizer.appendChild(node); if (vert == "over") { top = pos.top; } else if (vert == "above" || vert == "near") { var vspace = Math.max(display.wrapper.clientHeight, this.doc.height), hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth); // Default to positioning above (if specified and possible); otherwise default to positioning below if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight) top = pos.top - node.offsetHeight; else if (pos.bottom + node.offsetHeight <= vspace) top = pos.bottom; if (left + node.offsetWidth > hspace) left = hspace - node.offsetWidth; } node.style.top = top + "px"; node.style.left = node.style.right = ""; if (horiz == "right") { left = display.sizer.clientWidth - node.offsetWidth; node.style.right = "0px"; } else { if (horiz == "left") left = 0; else if (horiz == "middle") left = (display.sizer.clientWidth - node.offsetWidth) / 2; node.style.left = left + "px"; } if (scroll) scrollIntoView(this, left, top, left + node.offsetWidth, top + node.offsetHeight); }, triggerOnKeyDown: operation(null, onKeyDown), execCommand: function(cmd) {return commands[cmd](this);}, findPosH: function(from, amount, unit, visually) { var dir = 1; if (amount < 0) { dir = -1; amount = -amount; } for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) { cur = findPosH(this.doc, cur, dir, unit, visually); if (cur.hitSide) break; } return cur; }, moveH: operation(null, function(dir, unit) { var sel = this.doc.sel, pos; if (sel.shift || sel.extend || posEq(sel.from, sel.to)) pos = findPosH(this.doc, sel.head, dir, unit, this.options.rtlMoveVisually); else pos = dir < 0 ? sel.from : sel.to; extendSelection(this.doc, pos, pos, dir); }), deleteH: operation(null, function(dir, unit) { var sel = this.doc.sel; if (!posEq(sel.from, sel.to)) replaceRange(this.doc, "", sel.from, sel.to, "+delete"); else replaceRange(this.doc, "", sel.from, findPosH(this.doc, sel.head, dir, unit, false), "+delete"); this.curOp.userSelChange = true; }), findPosV: function(from, amount, unit, goalColumn) { var dir = 1, x = goalColumn; if (amount < 0) { dir = -1; amount = -amount; } for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) { var coords = cursorCoords(this, cur, "div"); if (x == null) x = coords.left; else coords.left = x; cur = findPosV(this, coords, dir, unit); if (cur.hitSide) break; } return cur; }, moveV: operation(null, function(dir, unit) { var sel = this.doc.sel; var pos = cursorCoords(this, sel.head, "div"); if (sel.goalColumn != null) pos.left = sel.goalColumn; var target = findPosV(this, pos, dir, unit); if (unit == "page") addToScrollPos(this, 0, charCoords(this, target, "div").top - pos.top); extendSelection(this.doc, target, target, dir); sel.goalColumn = pos.left; }), toggleOverwrite: function(value) { if (value != null && value == this.state.overwrite) return; if (this.state.overwrite = !this.state.overwrite) this.display.cursor.className += " CodeMirror-overwrite"; else this.display.cursor.className = this.display.cursor.className.replace(" CodeMirror-overwrite", ""); }, hasFocus: function() { return this.state.focused; }, scrollTo: operation(null, function(x, y) { updateScrollPos(this, x, y); }), getScrollInfo: function() { var scroller = this.display.scroller, co = scrollerCutOff; return {left: scroller.scrollLeft, top: scroller.scrollTop, height: scroller.scrollHeight - co, width: scroller.scrollWidth - co, clientHeight: scroller.clientHeight - co, clientWidth: scroller.clientWidth - co}; }, scrollIntoView: operation(null, function(pos, margin) { if (typeof pos == "number") pos = Pos(pos, 0); if (!margin) margin = 0; var coords = pos; if (!pos || pos.line != null) { this.curOp.scrollToPos = pos ? clipPos(this.doc, pos) : this.doc.sel.head; this.curOp.scrollToPosMargin = margin; coords = cursorCoords(this, this.curOp.scrollToPos); } var sPos = calculateScrollPos(this, coords.left, coords.top - margin, coords.right, coords.bottom + margin); updateScrollPos(this, sPos.scrollLeft, sPos.scrollTop); }), setSize: operation(null, function(width, height) { function interpret(val) { return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; } if (width != null) this.display.wrapper.style.width = interpret(width); if (height != null) this.display.wrapper.style.height = interpret(height); if (this.options.lineWrapping) this.display.measureLineCache.length = this.display.measureLineCachePos = 0; this.curOp.forceUpdate = true; }), operation: function(f){return runInOp(this, f);}, refresh: operation(null, function() { clearCaches(this); updateScrollPos(this, this.doc.scrollLeft, this.doc.scrollTop); regChange(this); }), swapDoc: operation(null, function(doc) { var old = this.doc; old.cm = null; attachDoc(this, doc); clearCaches(this); resetInput(this, true); updateScrollPos(this, doc.scrollLeft, doc.scrollTop); return old; }), getInputField: function(){return this.display.input;}, getWrapperElement: function(){return this.display.wrapper;}, getScrollerElement: function(){return this.display.scroller;}, getGutterElement: function(){return this.display.gutters;} }; eventMixin(CodeMirror); // OPTION DEFAULTS var optionHandlers = CodeMirror.optionHandlers = {}; // The default configuration options. var defaults = CodeMirror.defaults = {}; function option(name, deflt, handle, notOnInit) { CodeMirror.defaults[name] = deflt; if (handle) optionHandlers[name] = notOnInit ? function(cm, val, old) {if (old != Init) handle(cm, val, old);} : handle; } var Init = CodeMirror.Init = {toString: function(){return "CodeMirror.Init";}}; // These two are, on init, called from the constructor because they // have to be initialized before the editor can start at all. option("value", "", function(cm, val) { cm.setValue(val); }, true); option("mode", null, function(cm, val) { cm.doc.modeOption = val; loadMode(cm); }, true); option("indentUnit", 2, loadMode, true); option("indentWithTabs", false); option("smartIndent", true); option("tabSize", 4, function(cm) { loadMode(cm); clearCaches(cm); regChange(cm); }, true); option("electricChars", true); option("rtlMoveVisually", !windows); option("theme", "default", function(cm) { themeChanged(cm); guttersChanged(cm); }, true); option("keyMap", "default", keyMapChanged); option("extraKeys", null); option("onKeyEvent", null); option("onDragEvent", null); option("lineWrapping", false, wrappingChanged, true); option("gutters", [], function(cm) { setGuttersForLineNumbers(cm.options); guttersChanged(cm); }, true); option("fixedGutter", true, function(cm, val) { cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0"; cm.refresh(); }, true); option("coverGutterNextToScrollbar", false, updateScrollbars, true); option("lineNumbers", false, function(cm) { setGuttersForLineNumbers(cm.options); guttersChanged(cm); }, true); option("firstLineNumber", 1, guttersChanged, true); option("lineNumberFormatter", function(integer) {return integer;}, guttersChanged, true); option("showCursorWhenSelecting", false, updateSelection, true); option("readOnly", false, function(cm, val) { if (val == "nocursor") {onBlur(cm); cm.display.input.blur();} else if (!val) resetInput(cm, true); }); option("dragDrop", true); option("cursorBlinkRate", 530); option("cursorScrollMargin", 0); option("cursorHeight", 1); option("workTime", 100); option("workDelay", 100); option("flattenSpans", true); option("pollInterval", 100); option("undoDepth", 40, function(cm, val){cm.doc.history.undoDepth = val;}); option("historyEventDelay", 500); option("viewportMargin", 10, function(cm){cm.refresh();}, true); option("maxHighlightLength", 10000, function(cm){loadMode(cm); cm.refresh();}, true); option("moveInputWithCursor", true, function(cm, val) { if (!val) cm.display.inputDiv.style.top = cm.display.inputDiv.style.left = 0; }); option("tabindex", null, function(cm, val) { cm.display.input.tabIndex = val || ""; }); option("autofocus", null); // MODE DEFINITION AND QUERYING // Known modes, by name and by MIME var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {}; CodeMirror.defineMode = function(name, mode) { if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name; if (arguments.length > 2) { mode.dependencies = []; for (var i = 2; i < arguments.length; ++i) mode.dependencies.push(arguments[i]); } modes[name] = mode; }; CodeMirror.defineMIME = function(mime, spec) { mimeModes[mime] = spec; }; CodeMirror.resolveMode = function(spec) { if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) { spec = mimeModes[spec]; } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) { var found = mimeModes[spec.name]; spec = createObj(found, spec); spec.name = found.name; } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) { return CodeMirror.resolveMode("application/xml"); } if (typeof spec == "string") return {name: spec}; else return spec || {name: "null"}; }; CodeMirror.getMode = function(options, spec) { var spec = CodeMirror.resolveMode(spec); var mfactory = modes[spec.name]; if (!mfactory) return CodeMirror.getMode(options, "text/plain"); var modeObj = mfactory(options, spec); if (modeExtensions.hasOwnProperty(spec.name)) { var exts = modeExtensions[spec.name]; for (var prop in exts) { if (!exts.hasOwnProperty(prop)) continue; if (modeObj.hasOwnProperty(prop)) modeObj["_" + prop] = modeObj[prop]; modeObj[prop] = exts[prop]; } } modeObj.name = spec.name; return modeObj; }; CodeMirror.defineMode("null", function() { return {token: function(stream) {stream.skipToEnd();}}; }); CodeMirror.defineMIME("text/plain", "null"); var modeExtensions = CodeMirror.modeExtensions = {}; CodeMirror.extendMode = function(mode, properties) { var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {}); copyObj(properties, exts); }; // EXTENSIONS CodeMirror.defineExtension = function(name, func) { CodeMirror.prototype[name] = func; }; CodeMirror.defineDocExtension = function(name, func) { Doc.prototype[name] = func; }; CodeMirror.defineOption = option; var initHooks = []; CodeMirror.defineInitHook = function(f) {initHooks.push(f);}; var helpers = CodeMirror.helpers = {}; CodeMirror.registerHelper = function(type, name, value) { if (!helpers.hasOwnProperty(type)) helpers[type] = CodeMirror[type] = {}; helpers[type][name] = value; }; // UTILITIES CodeMirror.isWordChar = isWordChar; // MODE STATE HANDLING // Utility functions for working with state. Exported because modes // sometimes need to do this. function copyState(mode, state) { if (state === true) return state; if (mode.copyState) return mode.copyState(state); var nstate = {}; for (var n in state) { var val = state[n]; if (val instanceof Array) val = val.concat([]); nstate[n] = val; } return nstate; } CodeMirror.copyState = copyState; function startState(mode, a1, a2) { return mode.startState ? mode.startState(a1, a2) : true; } CodeMirror.startState = startState; CodeMirror.innerMode = function(mode, state) { while (mode.innerMode) { var info = mode.innerMode(state); if (!info || info.mode == mode) break; state = info.state; mode = info.mode; } return info || {mode: mode, state: state}; }; // STANDARD COMMANDS var commands = CodeMirror.commands = { selectAll: function(cm) {cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()));}, killLine: function(cm) { var from = cm.getCursor(true), to = cm.getCursor(false), sel = !posEq(from, to); if (!sel && cm.getLine(from.line).length == from.ch) cm.replaceRange("", from, Pos(from.line + 1, 0), "+delete"); else cm.replaceRange("", from, sel ? to : Pos(from.line), "+delete"); }, deleteLine: function(cm) { var l = cm.getCursor().line; cm.replaceRange("", Pos(l, 0), Pos(l), "+delete"); }, delLineLeft: function(cm) { var cur = cm.getCursor(); cm.replaceRange("", Pos(cur.line, 0), cur, "+delete"); }, undo: function(cm) {cm.undo();}, redo: function(cm) {cm.redo();}, goDocStart: function(cm) {cm.extendSelection(Pos(cm.firstLine(), 0));}, goDocEnd: function(cm) {cm.extendSelection(Pos(cm.lastLine()));}, goLineStart: function(cm) { cm.extendSelection(lineStart(cm, cm.getCursor().line)); }, goLineStartSmart: function(cm) { var cur = cm.getCursor(), start = lineStart(cm, cur.line); var line = cm.getLineHandle(start.line); var order = getOrder(line); if (!order || order[0].level == 0) { var firstNonWS = Math.max(0, line.text.search(/\S/)); var inWS = cur.line == start.line && cur.ch <= firstNonWS && cur.ch; cm.extendSelection(Pos(start.line, inWS ? 0 : firstNonWS)); } else cm.extendSelection(start); }, goLineEnd: function(cm) { cm.extendSelection(lineEnd(cm, cm.getCursor().line)); }, goLineRight: function(cm) { var top = cm.charCoords(cm.getCursor(), "div").top + 5; cm.extendSelection(cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div")); }, goLineLeft: function(cm) { var top = cm.charCoords(cm.getCursor(), "div").top + 5; cm.extendSelection(cm.coordsChar({left: 0, top: top}, "div")); }, goLineUp: function(cm) {cm.moveV(-1, "line");}, goLineDown: function(cm) {cm.moveV(1, "line");}, goPageUp: function(cm) {cm.moveV(-1, "page");}, goPageDown: function(cm) {cm.moveV(1, "page");}, goCharLeft: function(cm) {cm.moveH(-1, "char");}, goCharRight: function(cm) {cm.moveH(1, "char");}, goColumnLeft: function(cm) {cm.moveH(-1, "column");}, goColumnRight: function(cm) {cm.moveH(1, "column");}, goWordLeft: function(cm) {cm.moveH(-1, "word");}, goGroupRight: function(cm) {cm.moveH(1, "group");}, goGroupLeft: function(cm) {cm.moveH(-1, "group");}, goWordRight: function(cm) {cm.moveH(1, "word");}, delCharBefore: function(cm) {cm.deleteH(-1, "char");}, delCharAfter: function(cm) {cm.deleteH(1, "char");}, delWordBefore: function(cm) {cm.deleteH(-1, "word");}, delWordAfter: function(cm) {cm.deleteH(1, "word");}, delGroupBefore: function(cm) {cm.deleteH(-1, "group");}, delGroupAfter: function(cm) {cm.deleteH(1, "group");}, indentAuto: function(cm) {cm.indentSelection("smart");}, indentMore: function(cm) {cm.indentSelection("add");}, indentLess: function(cm) {cm.indentSelection("subtract");}, insertTab: function(cm) {cm.replaceSelection("\t", "end", "+input");}, defaultTab: function(cm) { if (cm.somethingSelected()) cm.indentSelection("add"); else cm.replaceSelection("\t", "end", "+input"); }, transposeChars: function(cm) { var cur = cm.getCursor(), line = cm.getLine(cur.line); if (cur.ch > 0 && cur.ch < line.length - 1) cm.replaceRange(line.charAt(cur.ch) + line.charAt(cur.ch - 1), Pos(cur.line, cur.ch - 1), Pos(cur.line, cur.ch + 1)); }, newlineAndIndent: function(cm) { operation(cm, function() { cm.replaceSelection("\n", "end", "+input"); cm.indentLine(cm.getCursor().line, null, true); })(); }, toggleOverwrite: function(cm) {cm.toggleOverwrite();} }; // STANDARD KEYMAPS var keyMap = CodeMirror.keyMap = {}; keyMap.basic = { "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown", "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown", "Delete": "delCharAfter", "Backspace": "delCharBefore", "Tab": "defaultTab", "Shift-Tab": "indentAuto", "Enter": "newlineAndIndent", "Insert": "toggleOverwrite" }; // Note that the save and find-related commands aren't defined by // default. Unknown commands are simply ignored. keyMap.pcDefault = { "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo", "Ctrl-Home": "goDocStart", "Alt-Up": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Down": "goDocEnd", "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd", "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find", "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll", "Ctrl-[": "indentLess", "Ctrl-]": "indentMore", fallthrough: "basic" }; keyMap.macDefault = { "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft", "Alt-Right": "goGroupRight", "Cmd-Left": "goLineStart", "Cmd-Right": "goLineEnd", "Alt-Backspace": "delGroupBefore", "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find", "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll", "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delLineLeft", fallthrough: ["basic", "emacsy"] }; keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault; keyMap.emacsy = { "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown", "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd", "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore", "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars" }; // KEYMAP DISPATCH function getKeyMap(val) { if (typeof val == "string") return keyMap[val]; else return val; } function lookupKey(name, maps, handle) { function lookup(map) { map = getKeyMap(map); var found = map[name]; if (found === false) return "stop"; if (found != null && handle(found)) return true; if (map.nofallthrough) return "stop"; var fallthrough = map.fallthrough; if (fallthrough == null) return false; if (Object.prototype.toString.call(fallthrough) != "[object Array]") return lookup(fallthrough); for (var i = 0, e = fallthrough.length; i < e; ++i) { var done = lookup(fallthrough[i]); if (done) return done; } return false; } for (var i = 0; i < maps.length; ++i) { var done = lookup(maps[i]); if (done) return done != "stop"; } } function isModifierKey(event) { var name = keyNames[event.keyCode]; return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"; } function keyName(event, noShift) { if (opera && event.keyCode == 34 && event["char"]) return false; var name = keyNames[event.keyCode]; if (name == null || event.altGraphKey) return false; if (event.altKey) name = "Alt-" + name; if (flipCtrlCmd ? event.metaKey : event.ctrlKey) name = "Ctrl-" + name; if (flipCtrlCmd ? event.ctrlKey : event.metaKey) name = "Cmd-" + name; if (!noShift && event.shiftKey) name = "Shift-" + name; return name; } CodeMirror.lookupKey = lookupKey; CodeMirror.isModifierKey = isModifierKey; CodeMirror.keyName = keyName; // FROMTEXTAREA CodeMirror.fromTextArea = function(textarea, options) { if (!options) options = {}; options.value = textarea.value; if (!options.tabindex && textarea.tabindex) options.tabindex = textarea.tabindex; if (!options.placeholder && textarea.placeholder) options.placeholder = textarea.placeholder; // Set autofocus to true if this textarea is focused, or if it has // autofocus and no other element is focused. if (options.autofocus == null) { var hasFocus = document.body; // doc.activeElement occasionally throws on IE try { hasFocus = document.activeElement; } catch(e) {} options.autofocus = hasFocus == textarea || textarea.getAttribute("autofocus") != null && hasFocus == document.body; } function save() {textarea.value = cm.getValue();} if (textarea.form) { on(textarea.form, "submit", save); // Deplorable hack to make the submit method do the right thing. if (!options.leaveSubmitMethodAlone) { var form = textarea.form, realSubmit = form.submit; try { var wrappedSubmit = form.submit = function() { save(); form.submit = realSubmit; form.submit(); form.submit = wrappedSubmit; }; } catch(e) {} } } textarea.style.display = "none"; var cm = CodeMirror(function(node) { textarea.parentNode.insertBefore(node, textarea.nextSibling); }, options); cm.save = save; cm.getTextArea = function() { return textarea; }; cm.toTextArea = function() { save(); textarea.parentNode.removeChild(cm.getWrapperElement()); textarea.style.display = ""; if (textarea.form) { off(textarea.form, "submit", save); if (typeof textarea.form.submit == "function") textarea.form.submit = realSubmit; } }; return cm; }; // STRING STREAM // Fed to the mode parsers, provides helper functions to make // parsers more succinct. // The character stream used by a mode's parser. function StringStream(string, tabSize) { this.pos = this.start = 0; this.string = string; this.tabSize = tabSize || 8; this.lastColumnPos = this.lastColumnValue = 0; } StringStream.prototype = { eol: function() {return this.pos >= this.string.length;}, sol: function() {return this.pos == 0;}, peek: function() {return this.string.charAt(this.pos) || undefined;}, next: function() { if (this.pos < this.string.length) return this.string.charAt(this.pos++); }, eat: function(match) { var ch = this.string.charAt(this.pos); if (typeof match == "string") var ok = ch == match; else var ok = ch && (match.test ? match.test(ch) : match(ch)); if (ok) {++this.pos; return ch;} }, eatWhile: function(match) { var start = this.pos; while (this.eat(match)){} return this.pos > start; }, eatSpace: function() { var start = this.pos; while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos; return this.pos > start; }, skipToEnd: function() {this.pos = this.string.length;}, skipTo: function(ch) { var found = this.string.indexOf(ch, this.pos); if (found > -1) {this.pos = found; return true;} }, backUp: function(n) {this.pos -= n;}, column: function() { if (this.lastColumnPos < this.start) { this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue); this.lastColumnPos = this.start; } return this.lastColumnValue; }, indentation: function() {return countColumn(this.string, null, this.tabSize);}, match: function(pattern, consume, caseInsensitive) { if (typeof pattern == "string") { var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;}; var substr = this.string.substr(this.pos, pattern.length); if (cased(substr) == cased(pattern)) { if (consume !== false) this.pos += pattern.length; return true; } } else { var match = this.string.slice(this.pos).match(pattern); if (match && match.index > 0) return null; if (match && consume !== false) this.pos += match[0].length; return match; } }, current: function(){return this.string.slice(this.start, this.pos);} }; CodeMirror.StringStream = StringStream; // TEXTMARKERS function TextMarker(doc, type) { this.lines = []; this.type = type; this.doc = doc; } CodeMirror.TextMarker = TextMarker; eventMixin(TextMarker); TextMarker.prototype.clear = function() { if (this.explicitlyCleared) return; var cm = this.doc.cm, withOp = cm && !cm.curOp; if (withOp) startOperation(cm); if (hasHandler(this, "clear")) { var found = this.find(); if (found) signalLater(this, "clear", found.from, found.to); } var min = null, max = null; for (var i = 0; i < this.lines.length; ++i) { var line = this.lines[i]; var span = getMarkedSpanFor(line.markedSpans, this); if (span.to != null) max = lineNo(line); line.markedSpans = removeMarkedSpan(line.markedSpans, span); if (span.from != null) min = lineNo(line); else if (this.collapsed && !lineIsHidden(this.doc, line) && cm) updateLineHeight(line, textHeight(cm.display)); } if (cm && this.collapsed && !cm.options.lineWrapping) for (var i = 0; i < this.lines.length; ++i) { var visual = visualLine(cm.doc, this.lines[i]), len = lineLength(cm.doc, visual); if (len > cm.display.maxLineLength) { cm.display.maxLine = visual; cm.display.maxLineLength = len; cm.display.maxLineChanged = true; } } if (min != null && cm) regChange(cm, min, max + 1); this.lines.length = 0; this.explicitlyCleared = true; if (this.atomic && this.doc.cantEdit) { this.doc.cantEdit = false; if (cm) reCheckSelection(cm); } if (withOp) endOperation(cm); }; TextMarker.prototype.find = function() { var from, to; for (var i = 0; i < this.lines.length; ++i) { var line = this.lines[i]; var span = getMarkedSpanFor(line.markedSpans, this); if (span.from != null || span.to != null) { var found = lineNo(line); if (span.from != null) from = Pos(found, span.from); if (span.to != null) to = Pos(found, span.to); } } if (this.type == "bookmark") return from; return from && {from: from, to: to}; }; TextMarker.prototype.changed = function() { var pos = this.find(), cm = this.doc.cm; if (!pos || !cm) return; var line = getLine(this.doc, pos.from.line); clearCachedMeasurement(cm, line); if (pos.from.line >= cm.display.showingFrom && pos.from.line < cm.display.showingTo) { for (var node = cm.display.lineDiv.firstChild; node; node = node.nextSibling) if (node.lineObj == line) { if (node.offsetHeight != line.height) updateLineHeight(line, node.offsetHeight); break; } runInOp(cm, function() { cm.curOp.selectionChanged = cm.curOp.forceUpdate = cm.curOp.updateMaxLine = true; }); } }; TextMarker.prototype.attachLine = function(line) { if (!this.lines.length && this.doc.cm) { var op = this.doc.cm.curOp; if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1) (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this); } this.lines.push(line); }; TextMarker.prototype.detachLine = function(line) { this.lines.splice(indexOf(this.lines, line), 1); if (!this.lines.length && this.doc.cm) { var op = this.doc.cm.curOp; (op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this); } }; function markText(doc, from, to, options, type) { if (options && options.shared) return markTextShared(doc, from, to, options, type); if (doc.cm && !doc.cm.curOp) return operation(doc.cm, markText)(doc, from, to, options, type); var marker = new TextMarker(doc, type); if (type == "range" && !posLess(from, to)) return marker; if (options) copyObj(options, marker); if (marker.replacedWith) { marker.collapsed = true; marker.replacedWith = elt("span", [marker.replacedWith], "CodeMirror-widget"); if (!options.handleMouseEvents) marker.replacedWith.ignoreEvents = true; } if (marker.collapsed) sawCollapsedSpans = true; if (marker.addToHistory) addToHistory(doc, {from: from, to: to, origin: "markText"}, {head: doc.sel.head, anchor: doc.sel.anchor}, NaN); var curLine = from.line, size = 0, collapsedAtStart, collapsedAtEnd, cm = doc.cm, updateMaxLine; doc.iter(curLine, to.line + 1, function(line) { if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(doc, line) == cm.display.maxLine) updateMaxLine = true; var span = {from: null, to: null, marker: marker}; size += line.text.length; if (curLine == from.line) {span.from = from.ch; size -= from.ch;} if (curLine == to.line) {span.to = to.ch; size -= line.text.length - to.ch;} if (marker.collapsed) { if (curLine == to.line) collapsedAtEnd = collapsedSpanAt(line, to.ch); if (curLine == from.line) collapsedAtStart = collapsedSpanAt(line, from.ch); else updateLineHeight(line, 0); } addMarkedSpan(line, span); ++curLine; }); if (marker.collapsed) doc.iter(from.line, to.line + 1, function(line) { if (lineIsHidden(doc, line)) updateLineHeight(line, 0); }); if (marker.clearOnEnter) on(marker, "beforeCursorEnter", function() { marker.clear(); }); if (marker.readOnly) { sawReadOnlySpans = true; if (doc.history.done.length || doc.history.undone.length) doc.clearHistory(); } if (marker.collapsed) { if (collapsedAtStart != collapsedAtEnd) throw new Error("Inserting collapsed marker overlapping an existing one"); marker.size = size; marker.atomic = true; } if (cm) { if (updateMaxLine) cm.curOp.updateMaxLine = true; if (marker.className || marker.title || marker.startStyle || marker.endStyle || marker.collapsed) regChange(cm, from.line, to.line + 1); if (marker.atomic) reCheckSelection(cm); } return marker; } // SHARED TEXTMARKERS function SharedTextMarker(markers, primary) { this.markers = markers; this.primary = primary; for (var i = 0, me = this; i < markers.length; ++i) { markers[i].parent = this; on(markers[i], "clear", function(){me.clear();}); } } CodeMirror.SharedTextMarker = SharedTextMarker; eventMixin(SharedTextMarker); SharedTextMarker.prototype.clear = function() { if (this.explicitlyCleared) return; this.explicitlyCleared = true; for (var i = 0; i < this.markers.length; ++i) this.markers[i].clear(); signalLater(this, "clear"); }; SharedTextMarker.prototype.find = function() { return this.primary.find(); }; function markTextShared(doc, from, to, options, type) { options = copyObj(options); options.shared = false; var markers = [markText(doc, from, to, options, type)], primary = markers[0]; var widget = options.replacedWith; linkedDocs(doc, function(doc) { if (widget) options.replacedWith = widget.cloneNode(true); markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type)); for (var i = 0; i < doc.linked.length; ++i) if (doc.linked[i].isParent) return; primary = lst(markers); }); return new SharedTextMarker(markers, primary); } // TEXTMARKER SPANS function getMarkedSpanFor(spans, marker) { if (spans) for (var i = 0; i < spans.length; ++i) { var span = spans[i]; if (span.marker == marker) return span; } } function removeMarkedSpan(spans, span) { for (var r, i = 0; i < spans.length; ++i) if (spans[i] != span) (r || (r = [])).push(spans[i]); return r; } function addMarkedSpan(line, span) { line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span]; span.marker.attachLine(line); } function markedSpansBefore(old, startCh, isInsert) { if (old) for (var i = 0, nw; i < old.length; ++i) { var span = old[i], marker = span.marker; var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh); if (startsBefore || marker.type == "bookmark" && span.from == startCh && (!isInsert || !span.marker.insertLeft)) { var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh); (nw || (nw = [])).push({from: span.from, to: endsAfter ? null : span.to, marker: marker}); } } return nw; } function markedSpansAfter(old, endCh, isInsert) { if (old) for (var i = 0, nw; i < old.length; ++i) { var span = old[i], marker = span.marker; var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh); if (endsAfter || marker.type == "bookmark" && span.from == endCh && (!isInsert || span.marker.insertLeft)) { var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh); (nw || (nw = [])).push({from: startsBefore ? null : span.from - endCh, to: span.to == null ? null : span.to - endCh, marker: marker}); } } return nw; } function stretchSpansOverChange(doc, change) { var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans; var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans; if (!oldFirst && !oldLast) return null; var startCh = change.from.ch, endCh = change.to.ch, isInsert = posEq(change.from, change.to); // Get the spans that 'stick out' on both sides var first = markedSpansBefore(oldFirst, startCh, isInsert); var last = markedSpansAfter(oldLast, endCh, isInsert); // Next, merge those two ends var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0); if (first) { // Fix up .to properties of first for (var i = 0; i < first.length; ++i) { var span = first[i]; if (span.to == null) { var found = getMarkedSpanFor(last, span.marker); if (!found) span.to = startCh; else if (sameLine) span.to = found.to == null ? null : found.to + offset; } } } if (last) { // Fix up .from in last (or move them into first in case of sameLine) for (var i = 0; i < last.length; ++i) { var span = last[i]; if (span.to != null) span.to += offset; if (span.from == null) { var found = getMarkedSpanFor(first, span.marker); if (!found) { span.from = offset; if (sameLine) (first || (first = [])).push(span); } } else { span.from += offset; if (sameLine) (first || (first = [])).push(span); } } } if (sameLine && first) { // Make sure we didn't create any zero-length spans for (var i = 0; i < first.length; ++i) if (first[i].from != null && first[i].from == first[i].to && first[i].marker.type != "bookmark") first.splice(i--, 1); if (!first.length) first = null; } var newMarkers = [first]; if (!sameLine) { // Fill gap with whole-line-spans var gap = change.text.length - 2, gapMarkers; if (gap > 0 && first) for (var i = 0; i < first.length; ++i) if (first[i].to == null) (gapMarkers || (gapMarkers = [])).push({from: null, to: null, marker: first[i].marker}); for (var i = 0; i < gap; ++i) newMarkers.push(gapMarkers); newMarkers.push(last); } return newMarkers; } function mergeOldSpans(doc, change) { var old = getOldSpans(doc, change); var stretched = stretchSpansOverChange(doc, change); if (!old) return stretched; if (!stretched) return old; for (var i = 0; i < old.length; ++i) { var oldCur = old[i], stretchCur = stretched[i]; if (oldCur && stretchCur) { spans: for (var j = 0; j < stretchCur.length; ++j) { var span = stretchCur[j]; for (var k = 0; k < oldCur.length; ++k) if (oldCur[k].marker == span.marker) continue spans; oldCur.push(span); } } else if (stretchCur) { old[i] = stretchCur; } } return old; } function removeReadOnlyRanges(doc, from, to) { var markers = null; doc.iter(from.line, to.line + 1, function(line) { if (line.markedSpans) for (var i = 0; i < line.markedSpans.length; ++i) { var mark = line.markedSpans[i].marker; if (mark.readOnly && (!markers || indexOf(markers, mark) == -1)) (markers || (markers = [])).push(mark); } }); if (!markers) return null; var parts = [{from: from, to: to}]; for (var i = 0; i < markers.length; ++i) { var mk = markers[i], m = mk.find(); for (var j = 0; j < parts.length; ++j) { var p = parts[j]; if (posLess(p.to, m.from) || posLess(m.to, p.from)) continue; var newParts = [j, 1]; if (posLess(p.from, m.from) || !mk.inclusiveLeft && posEq(p.from, m.from)) newParts.push({from: p.from, to: m.from}); if (posLess(m.to, p.to) || !mk.inclusiveRight && posEq(p.to, m.to)) newParts.push({from: m.to, to: p.to}); parts.splice.apply(parts, newParts); j += newParts.length - 1; } } return parts; } function collapsedSpanAt(line, ch) { var sps = sawCollapsedSpans && line.markedSpans, found; if (sps) for (var sp, i = 0; i < sps.length; ++i) { sp = sps[i]; if (!sp.marker.collapsed) continue; if ((sp.from == null || sp.from < ch) && (sp.to == null || sp.to > ch) && (!found || found.width < sp.marker.width)) found = sp.marker; } return found; } function collapsedSpanAtStart(line) { return collapsedSpanAt(line, -1); } function collapsedSpanAtEnd(line) { return collapsedSpanAt(line, line.text.length + 1); } function visualLine(doc, line) { var merged; while (merged = collapsedSpanAtStart(line)) line = getLine(doc, merged.find().from.line); return line; } function lineIsHidden(doc, line) { var sps = sawCollapsedSpans && line.markedSpans; if (sps) for (var sp, i = 0; i < sps.length; ++i) { sp = sps[i]; if (!sp.marker.collapsed) continue; if (sp.from == null) return true; if (sp.marker.replacedWith) continue; if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp)) return true; } } function lineIsHiddenInner(doc, line, span) { if (span.to == null) { var end = span.marker.find().to, endLine = getLine(doc, end.line); return lineIsHiddenInner(doc, endLine, getMarkedSpanFor(endLine.markedSpans, span.marker)); } if (span.marker.inclusiveRight && span.to == line.text.length) return true; for (var sp, i = 0; i < line.markedSpans.length; ++i) { sp = line.markedSpans[i]; if (sp.marker.collapsed && !sp.marker.replacedWith && sp.from == span.to && (sp.marker.inclusiveLeft || span.marker.inclusiveRight) && lineIsHiddenInner(doc, line, sp)) return true; } } function detachMarkedSpans(line) { var spans = line.markedSpans; if (!spans) return; for (var i = 0; i < spans.length; ++i) spans[i].marker.detachLine(line); line.markedSpans = null; } function attachMarkedSpans(line, spans) { if (!spans) return; for (var i = 0; i < spans.length; ++i) spans[i].marker.attachLine(line); line.markedSpans = spans; } // LINE WIDGETS var LineWidget = CodeMirror.LineWidget = function(cm, node, options) { if (options) for (var opt in options) if (options.hasOwnProperty(opt)) this[opt] = options[opt]; this.cm = cm; this.node = node; }; eventMixin(LineWidget); function widgetOperation(f) { return function() { var withOp = !this.cm.curOp; if (withOp) startOperation(this.cm); try {var result = f.apply(this, arguments);} finally {if (withOp) endOperation(this.cm);} return result; }; } LineWidget.prototype.clear = widgetOperation(function() { var ws = this.line.widgets, no = lineNo(this.line); if (no == null || !ws) return; for (var i = 0; i < ws.length; ++i) if (ws[i] == this) ws.splice(i--, 1); if (!ws.length) this.line.widgets = null; var aboveVisible = heightAtLine(this.cm, this.line) < this.cm.doc.scrollTop; updateLineHeight(this.line, Math.max(0, this.line.height - widgetHeight(this))); if (aboveVisible) addToScrollPos(this.cm, 0, -this.height); regChange(this.cm, no, no + 1); }); LineWidget.prototype.changed = widgetOperation(function() { var oldH = this.height; this.height = null; var diff = widgetHeight(this) - oldH; if (!diff) return; updateLineHeight(this.line, this.line.height + diff); var no = lineNo(this.line); regChange(this.cm, no, no + 1); }); function widgetHeight(widget) { if (widget.height != null) return widget.height; if (!widget.node.parentNode || widget.node.parentNode.nodeType != 1) removeChildrenAndAdd(widget.cm.display.measure, elt("div", [widget.node], null, "position: relative")); return widget.height = widget.node.offsetHeight; } function addLineWidget(cm, handle, node, options) { var widget = new LineWidget(cm, node, options); if (widget.noHScroll) cm.display.alignWidgets = true; changeLine(cm, handle, function(line) { var widgets = line.widgets || (line.widgets = []); if (widget.insertAt == null) widgets.push(widget); else widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget); widget.line = line; if (!lineIsHidden(cm.doc, line) || widget.showIfHidden) { var aboveVisible = heightAtLine(cm, line) < cm.doc.scrollTop; updateLineHeight(line, line.height + widgetHeight(widget)); if (aboveVisible) addToScrollPos(cm, 0, widget.height); } return true; }); return widget; } // LINE DATA STRUCTURE // Line objects. These hold state related to a line, including // highlighting info (the styles array). var Line = CodeMirror.Line = function(text, markedSpans, estimateHeight) { this.text = text; attachMarkedSpans(this, markedSpans); this.height = estimateHeight ? estimateHeight(this) : 1; }; eventMixin(Line); function updateLine(line, text, markedSpans, estimateHeight) { line.text = text; if (line.stateAfter) line.stateAfter = null; if (line.styles) line.styles = null; if (line.order != null) line.order = null; detachMarkedSpans(line); attachMarkedSpans(line, markedSpans); var estHeight = estimateHeight ? estimateHeight(line) : 1; if (estHeight != line.height) updateLineHeight(line, estHeight); } function cleanUpLine(line) { line.parent = null; detachMarkedSpans(line); } // Run the given mode's parser over a line, update the styles // array, which contains alternating fragments of text and CSS // classes. function runMode(cm, text, mode, state, f) { var flattenSpans = mode.flattenSpans; if (flattenSpans == null) flattenSpans = cm.options.flattenSpans; var curStart = 0, curStyle = null; var stream = new StringStream(text, cm.options.tabSize), style; if (text == "" && mode.blankLine) mode.blankLine(state); while (!stream.eol()) { if (stream.pos > cm.options.maxHighlightLength) { flattenSpans = false; // Webkit seems to refuse to render text nodes longer than 57444 characters stream.pos = Math.min(text.length, stream.start + 50000); style = null; } else { style = mode.token(stream, state); } if (!flattenSpans || curStyle != style) { if (curStart < stream.start) f(stream.start, curStyle); curStart = stream.start; curStyle = style; } stream.start = stream.pos; } if (curStart < stream.pos) f(stream.pos, curStyle); } function highlightLine(cm, line, state) { // A styles array always starts with a number identifying the // mode/overlays that it is based on (for easy invalidation). var st = [cm.state.modeGen]; // Compute the base array of styles runMode(cm, line.text, cm.doc.mode, state, function(end, style) {st.push(end, style);}); // Run overlays, adjust style array. for (var o = 0; o < cm.state.overlays.length; ++o) { var overlay = cm.state.overlays[o], i = 1, at = 0; runMode(cm, line.text, overlay.mode, true, function(end, style) { var start = i; // Ensure there's a token end at the current position, and that i points at it while (at < end) { var i_end = st[i]; if (i_end > end) st.splice(i, 1, end, st[i+1], i_end); i += 2; at = Math.min(end, i_end); } if (!style) return; if (overlay.opaque) { st.splice(start, i - start, end, style); i = start + 2; } else { for (; start < i; start += 2) { var cur = st[start+1]; st[start+1] = cur ? cur + " " + style : style; } } }); } return st; } function getLineStyles(cm, line) { if (!line.styles || line.styles[0] != cm.state.modeGen) line.styles = highlightLine(cm, line, line.stateAfter = getStateBefore(cm, lineNo(line))); return line.styles; } // Lightweight form of highlight -- proceed over this line and // update state, but don't save a style array. function processLine(cm, line, state) { var mode = cm.doc.mode; var stream = new StringStream(line.text, cm.options.tabSize); if (line.text == "" && mode.blankLine) mode.blankLine(state); while (!stream.eol() && stream.pos <= cm.options.maxHighlightLength) { mode.token(stream, state); stream.start = stream.pos; } } var styleToClassCache = {}; function styleToClass(style) { if (!style) return null; return styleToClassCache[style] || (styleToClassCache[style] = "cm-" + style.replace(/ +/g, " cm-")); } function lineContent(cm, realLine, measure, copyWidgets) { var merged, line = realLine, empty = true; while (merged = collapsedSpanAtStart(line)) line = getLine(cm.doc, merged.find().from.line); var builder = {pre: elt("pre"), col: 0, pos: 0, measure: null, measuredSomething: false, cm: cm, copyWidgets: copyWidgets}; if (line.textClass) builder.pre.className = line.textClass; do { if (line.text) empty = false; builder.measure = line == realLine && measure; builder.pos = 0; builder.addToken = builder.measure ? buildTokenMeasure : buildToken; if ((ie || webkit) && cm.getOption("lineWrapping")) builder.addToken = buildTokenSplitSpaces(builder.addToken); var next = insertLineContent(line, builder, getLineStyles(cm, line)); if (measure && line == realLine && !builder.measuredSomething) { measure[0] = builder.pre.appendChild(zeroWidthElement(cm.display.measure)); builder.measuredSomething = true; } if (next) line = getLine(cm.doc, next.to.line); } while (next); if (measure && !builder.measuredSomething && !measure[0]) measure[0] = builder.pre.appendChild(empty ? elt("span", "\u00a0") : zeroWidthElement(cm.display.measure)); if (!builder.pre.firstChild && !lineIsHidden(cm.doc, realLine)) builder.pre.appendChild(document.createTextNode("\u00a0")); var order; // Work around problem with the reported dimensions of single-char // direction spans on IE (issue #1129). See also the comment in // cursorCoords. if (measure && ie && (order = getOrder(line))) { var l = order.length - 1; if (order[l].from == order[l].to) --l; var last = order[l], prev = order[l - 1]; if (last.from + 1 == last.to && prev && last.level < prev.level) { var span = measure[builder.pos - 1]; if (span) span.parentNode.insertBefore(span.measureRight = zeroWidthElement(cm.display.measure), span.nextSibling); } } signal(cm, "renderLine", cm, realLine, builder.pre); return builder.pre; } var tokenSpecialChars = /[\t\u0000-\u0019\u00ad\u200b\u2028\u2029\uFEFF]/g; function buildToken(builder, text, style, startStyle, endStyle, title) { if (!text) return; if (!tokenSpecialChars.test(text)) { builder.col += text.length; var content = document.createTextNode(text); } else { var content = document.createDocumentFragment(), pos = 0; while (true) { tokenSpecialChars.lastIndex = pos; var m = tokenSpecialChars.exec(text); var skipped = m ? m.index - pos : text.length - pos; if (skipped) { content.appendChild(document.createTextNode(text.slice(pos, pos + skipped))); builder.col += skipped; } if (!m) break; pos += skipped + 1; if (m[0] == "\t") { var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize; content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab")); builder.col += tabWidth; } else { var token = elt("span", "\u2022", "cm-invalidchar"); token.title = "\\u" + m[0].charCodeAt(0).toString(16); content.appendChild(token); builder.col += 1; } } } if (style || startStyle || endStyle || builder.measure) { var fullStyle = style || ""; if (startStyle) fullStyle += startStyle; if (endStyle) fullStyle += endStyle; var token = elt("span", [content], fullStyle); if (title) token.title = title; return builder.pre.appendChild(token); } builder.pre.appendChild(content); } function buildTokenMeasure(builder, text, style, startStyle, endStyle) { var wrapping = builder.cm.options.lineWrapping; for (var i = 0; i < text.length; ++i) { var ch = text.charAt(i), start = i == 0; if (ch >= "\ud800" && ch < "\udbff" && i < text.length - 1) { ch = text.slice(i, i + 2); ++i; } else if (i && wrapping && spanAffectsWrapping(text, i)) { builder.pre.appendChild(elt("wbr")); } var old = builder.measure[builder.pos]; var span = builder.measure[builder.pos] = buildToken(builder, ch, style, start && startStyle, i == text.length - 1 && endStyle); if (old) span.leftSide = old.leftSide || old; // In IE single-space nodes wrap differently than spaces // embedded in larger text nodes, except when set to // white-space: normal (issue #1268). if (ie && wrapping && ch == " " && i && !/\s/.test(text.charAt(i - 1)) && i < text.length - 1 && !/\s/.test(text.charAt(i + 1))) span.style.whiteSpace = "normal"; builder.pos += ch.length; } if (text.length) builder.measuredSomething = true; } function buildTokenSplitSpaces(inner) { function split(old) { var out = " "; for (var i = 0; i < old.length - 2; ++i) out += i % 2 ? " " : "\u00a0"; out += " "; return out; } return function(builder, text, style, startStyle, endStyle, title) { return inner(builder, text.replace(/ {3,}/, split), style, startStyle, endStyle, title); }; } function buildCollapsedSpan(builder, size, marker, ignoreWidget) { var widget = !ignoreWidget && marker.replacedWith; if (widget) { if (builder.copyWidgets) widget = widget.cloneNode(true); builder.pre.appendChild(widget); if (builder.measure) { if (size) { builder.measure[builder.pos] = widget; } else { var elt = builder.measure[builder.pos] = zeroWidthElement(builder.cm.display.measure); if (marker.type != "bookmark" || marker.insertLeft) builder.pre.insertBefore(elt, widget); else builder.pre.appendChild(elt); } builder.measuredSomething = true; } } builder.pos += size; } // Outputs a number of spans to make up a line, taking highlighting // and marked text into account. function insertLineContent(line, builder, styles) { var spans = line.markedSpans, allText = line.text, at = 0; if (!spans) { for (var i = 1; i < styles.length; i+=2) builder.addToken(builder, allText.slice(at, at = styles[i]), styleToClass(styles[i+1])); return; } var len = allText.length, pos = 0, i = 1, text = "", style; var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed; for (;;) { if (nextChange == pos) { // Update current marker set spanStyle = spanEndStyle = spanStartStyle = title = ""; collapsed = null; nextChange = Infinity; var foundBookmark = null; for (var j = 0; j < spans.length; ++j) { var sp = spans[j], m = sp.marker; if (sp.from <= pos && (sp.to == null || sp.to > pos)) { if (sp.to != null && nextChange > sp.to) { nextChange = sp.to; spanEndStyle = ""; } if (m.className) spanStyle += " " + m.className; if (m.startStyle && sp.from == pos) spanStartStyle += " " + m.startStyle; if (m.endStyle && sp.to == nextChange) spanEndStyle += " " + m.endStyle; if (m.title && !title) title = m.title; if (m.collapsed && (!collapsed || collapsed.marker.size < m.size)) collapsed = sp; } else if (sp.from > pos && nextChange > sp.from) { nextChange = sp.from; } if (m.type == "bookmark" && sp.from == pos && m.replacedWith) foundBookmark = m; } if (collapsed && (collapsed.from || 0) == pos) { buildCollapsedSpan(builder, (collapsed.to == null ? len : collapsed.to) - pos, collapsed.marker, collapsed.from == null); if (collapsed.to == null) return collapsed.marker.find(); } if (foundBookmark && !collapsed) buildCollapsedSpan(builder, 0, foundBookmark); } if (pos >= len) break; var upto = Math.min(len, nextChange); while (true) { if (text) { var end = pos + text.length; if (!collapsed) { var tokenText = end > upto ? text.slice(0, upto - pos) : text; builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle, spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title); } if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;} pos = end; spanStartStyle = ""; } text = allText.slice(at, at = styles[i++]); style = styleToClass(styles[i++]); } } } // DOCUMENT DATA STRUCTURE function updateDoc(doc, change, markedSpans, selAfter, estimateHeight) { function spansFor(n) {return markedSpans ? markedSpans[n] : null;} function update(line, text, spans) { updateLine(line, text, spans, estimateHeight); signalLater(line, "change", line, change); } var from = change.from, to = change.to, text = change.text; var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line); var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line; // First adjust the line structure if (from.ch == 0 && to.ch == 0 && lastText == "") { // This is a whole-line replace. Treated specially to make // sure line objects move the way they are supposed to. for (var i = 0, e = text.length - 1, added = []; i < e; ++i) added.push(new Line(text[i], spansFor(i), estimateHeight)); update(lastLine, lastLine.text, lastSpans); if (nlines) doc.remove(from.line, nlines); if (added.length) doc.insert(from.line, added); } else if (firstLine == lastLine) { if (text.length == 1) { update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans); } else { for (var added = [], i = 1, e = text.length - 1; i < e; ++i) added.push(new Line(text[i], spansFor(i), estimateHeight)); added.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight)); update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)); doc.insert(from.line + 1, added); } } else if (text.length == 1) { update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0)); doc.remove(from.line + 1, nlines); } else { update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)); update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans); for (var i = 1, e = text.length - 1, added = []; i < e; ++i) added.push(new Line(text[i], spansFor(i), estimateHeight)); if (nlines > 1) doc.remove(from.line + 1, nlines - 1); doc.insert(from.line + 1, added); } signalLater(doc, "change", doc, change); setSelection(doc, selAfter.anchor, selAfter.head, null, true); } function LeafChunk(lines) { this.lines = lines; this.parent = null; for (var i = 0, e = lines.length, height = 0; i < e; ++i) { lines[i].parent = this; height += lines[i].height; } this.height = height; } LeafChunk.prototype = { chunkSize: function() { return this.lines.length; }, removeInner: function(at, n) { for (var i = at, e = at + n; i < e; ++i) { var line = this.lines[i]; this.height -= line.height; cleanUpLine(line); signalLater(line, "delete"); } this.lines.splice(at, n); }, collapse: function(lines) { lines.splice.apply(lines, [lines.length, 0].concat(this.lines)); }, insertInner: function(at, lines, height) { this.height += height; this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at)); for (var i = 0, e = lines.length; i < e; ++i) lines[i].parent = this; }, iterN: function(at, n, op) { for (var e = at + n; at < e; ++at) if (op(this.lines[at])) return true; } }; function BranchChunk(children) { this.children = children; var size = 0, height = 0; for (var i = 0, e = children.length; i < e; ++i) { var ch = children[i]; size += ch.chunkSize(); height += ch.height; ch.parent = this; } this.size = size; this.height = height; this.parent = null; } BranchChunk.prototype = { chunkSize: function() { return this.size; }, removeInner: function(at, n) { this.size -= n; for (var i = 0; i < this.children.length; ++i) { var child = this.children[i], sz = child.chunkSize(); if (at < sz) { var rm = Math.min(n, sz - at), oldHeight = child.height; child.removeInner(at, rm); this.height -= oldHeight - child.height; if (sz == rm) { this.children.splice(i--, 1); child.parent = null; } if ((n -= rm) == 0) break; at = 0; } else at -= sz; } if (this.size - n < 25) { var lines = []; this.collapse(lines); this.children = [new LeafChunk(lines)]; this.children[0].parent = this; } }, collapse: function(lines) { for (var i = 0, e = this.children.length; i < e; ++i) this.children[i].collapse(lines); }, insertInner: function(at, lines, height) { this.size += lines.length; this.height += height; for (var i = 0, e = this.children.length; i < e; ++i) { var child = this.children[i], sz = child.chunkSize(); if (at <= sz) { child.insertInner(at, lines, height); if (child.lines && child.lines.length > 50) { while (child.lines.length > 50) { var spilled = child.lines.splice(child.lines.length - 25, 25); var newleaf = new LeafChunk(spilled); child.height -= newleaf.height; this.children.splice(i + 1, 0, newleaf); newleaf.parent = this; } this.maybeSpill(); } break; } at -= sz; } }, maybeSpill: function() { if (this.children.length <= 10) return; var me = this; do { var spilled = me.children.splice(me.children.length - 5, 5); var sibling = new BranchChunk(spilled); if (!me.parent) { // Become the parent node var copy = new BranchChunk(me.children); copy.parent = me; me.children = [copy, sibling]; me = copy; } else { me.size -= sibling.size; me.height -= sibling.height; var myIndex = indexOf(me.parent.children, me); me.parent.children.splice(myIndex + 1, 0, sibling); } sibling.parent = me.parent; } while (me.children.length > 10); me.parent.maybeSpill(); }, iterN: function(at, n, op) { for (var i = 0, e = this.children.length; i < e; ++i) { var child = this.children[i], sz = child.chunkSize(); if (at < sz) { var used = Math.min(n, sz - at); if (child.iterN(at, used, op)) return true; if ((n -= used) == 0) break; at = 0; } else at -= sz; } } }; var nextDocId = 0; var Doc = CodeMirror.Doc = function(text, mode, firstLine) { if (!(this instanceof Doc)) return new Doc(text, mode, firstLine); if (firstLine == null) firstLine = 0; BranchChunk.call(this, [new LeafChunk([new Line("", null)])]); this.first = firstLine; this.scrollTop = this.scrollLeft = 0; this.cantEdit = false; this.history = makeHistory(); this.cleanGeneration = 1; this.frontier = firstLine; var start = Pos(firstLine, 0); this.sel = {from: start, to: start, head: start, anchor: start, shift: false, extend: false, goalColumn: null}; this.id = ++nextDocId; this.modeOption = mode; if (typeof text == "string") text = splitLines(text); updateDoc(this, {from: start, to: start, text: text}, null, {head: start, anchor: start}); }; Doc.prototype = createObj(BranchChunk.prototype, { constructor: Doc, iter: function(from, to, op) { if (op) this.iterN(from - this.first, to - from, op); else this.iterN(this.first, this.first + this.size, from); }, insert: function(at, lines) { var height = 0; for (var i = 0, e = lines.length; i < e; ++i) height += lines[i].height; this.insertInner(at - this.first, lines, height); }, remove: function(at, n) { this.removeInner(at - this.first, n); }, getValue: function(lineSep) { var lines = getLines(this, this.first, this.first + this.size); if (lineSep === false) return lines; return lines.join(lineSep || "\n"); }, setValue: function(code) { var top = Pos(this.first, 0), last = this.first + this.size - 1; makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length), text: splitLines(code), origin: "setValue"}, {head: top, anchor: top}, true); }, replaceRange: function(code, from, to, origin) { from = clipPos(this, from); to = to ? clipPos(this, to) : from; replaceRange(this, code, from, to, origin); }, getRange: function(from, to, lineSep) { var lines = getBetween(this, clipPos(this, from), clipPos(this, to)); if (lineSep === false) return lines; return lines.join(lineSep || "\n"); }, getLine: function(line) {var l = this.getLineHandle(line); return l && l.text;}, setLine: function(line, text) { if (isLine(this, line)) replaceRange(this, text, Pos(line, 0), clipPos(this, Pos(line))); }, removeLine: function(line) { if (line) replaceRange(this, "", clipPos(this, Pos(line - 1)), clipPos(this, Pos(line))); else replaceRange(this, "", Pos(0, 0), clipPos(this, Pos(1, 0))); }, getLineHandle: function(line) {if (isLine(this, line)) return getLine(this, line);}, getLineNumber: function(line) {return lineNo(line);}, getLineHandleVisualStart: function(line) { if (typeof line == "number") line = getLine(this, line); return visualLine(this, line); }, lineCount: function() {return this.size;}, firstLine: function() {return this.first;}, lastLine: function() {return this.first + this.size - 1;}, clipPos: function(pos) {return clipPos(this, pos);}, getCursor: function(start) { var sel = this.sel, pos; if (start == null || start == "head") pos = sel.head; else if (start == "anchor") pos = sel.anchor; else if (start == "end" || start === false) pos = sel.to; else pos = sel.from; return copyPos(pos); }, somethingSelected: function() {return !posEq(this.sel.head, this.sel.anchor);}, setCursor: docOperation(function(line, ch, extend) { var pos = clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line); if (extend) extendSelection(this, pos); else setSelection(this, pos, pos); }), setSelection: docOperation(function(anchor, head) { setSelection(this, clipPos(this, anchor), clipPos(this, head || anchor)); }), extendSelection: docOperation(function(from, to) { extendSelection(this, clipPos(this, from), to && clipPos(this, to)); }), getSelection: function(lineSep) {return this.getRange(this.sel.from, this.sel.to, lineSep);}, replaceSelection: function(code, collapse, origin) { makeChange(this, {from: this.sel.from, to: this.sel.to, text: splitLines(code), origin: origin}, collapse || "around"); }, undo: docOperation(function() {makeChangeFromHistory(this, "undo");}), redo: docOperation(function() {makeChangeFromHistory(this, "redo");}), setExtending: function(val) {this.sel.extend = val;}, historySize: function() { var hist = this.history; return {undo: hist.done.length, redo: hist.undone.length}; }, clearHistory: function() {this.history = makeHistory(this.history.maxGeneration);}, markClean: function() { this.cleanGeneration = this.changeGeneration(); }, changeGeneration: function() { this.history.lastOp = this.history.lastOrigin = null; return this.history.generation; }, isClean: function (gen) { return this.history.generation == (gen || this.cleanGeneration); }, getHistory: function() { return {done: copyHistoryArray(this.history.done), undone: copyHistoryArray(this.history.undone)}; }, setHistory: function(histData) { var hist = this.history = makeHistory(this.history.maxGeneration); hist.done = histData.done.slice(0); hist.undone = histData.undone.slice(0); }, markText: function(from, to, options) { return markText(this, clipPos(this, from), clipPos(this, to), options, "range"); }, setBookmark: function(pos, options) { var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options), insertLeft: options && options.insertLeft}; pos = clipPos(this, pos); return markText(this, pos, pos, realOpts, "bookmark"); }, findMarksAt: function(pos) { pos = clipPos(this, pos); var markers = [], spans = getLine(this, pos.line).markedSpans; if (spans) for (var i = 0; i < spans.length; ++i) { var span = spans[i]; if ((span.from == null || span.from <= pos.ch) && (span.to == null || span.to >= pos.ch)) markers.push(span.marker.parent || span.marker); } return markers; }, getAllMarks: function() { var markers = []; this.iter(function(line) { var sps = line.markedSpans; if (sps) for (var i = 0; i < sps.length; ++i) if (sps[i].from != null) markers.push(sps[i].marker); }); return markers; }, posFromIndex: function(off) { var ch, lineNo = this.first; this.iter(function(line) { var sz = line.text.length + 1; if (sz > off) { ch = off; return true; } off -= sz; ++lineNo; }); return clipPos(this, Pos(lineNo, ch)); }, indexFromPos: function (coords) { coords = clipPos(this, coords); var index = coords.ch; if (coords.line < this.first || coords.ch < 0) return 0; this.iter(this.first, coords.line, function (line) { index += line.text.length + 1; }); return index; }, copy: function(copyHistory) { var doc = new Doc(getLines(this, this.first, this.first + this.size), this.modeOption, this.first); doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft; doc.sel = {from: this.sel.from, to: this.sel.to, head: this.sel.head, anchor: this.sel.anchor, shift: this.sel.shift, extend: false, goalColumn: this.sel.goalColumn}; if (copyHistory) { doc.history.undoDepth = this.history.undoDepth; doc.setHistory(this.getHistory()); } return doc; }, linkedDoc: function(options) { if (!options) options = {}; var from = this.first, to = this.first + this.size; if (options.from != null && options.from > from) from = options.from; if (options.to != null && options.to < to) to = options.to; var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from); if (options.sharedHist) copy.history = this.history; (this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist}); copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}]; return copy; }, unlinkDoc: function(other) { if (other instanceof CodeMirror) other = other.doc; if (this.linked) for (var i = 0; i < this.linked.length; ++i) { var link = this.linked[i]; if (link.doc != other) continue; this.linked.splice(i, 1); other.unlinkDoc(this); break; } // If the histories were shared, split them again if (other.history == this.history) { var splitIds = [other.id]; linkedDocs(other, function(doc) {splitIds.push(doc.id);}, true); other.history = makeHistory(); other.history.done = copyHistoryArray(this.history.done, splitIds); other.history.undone = copyHistoryArray(this.history.undone, splitIds); } }, iterLinkedDocs: function(f) {linkedDocs(this, f);}, getMode: function() {return this.mode;}, getEditor: function() {return this.cm;} }); Doc.prototype.eachLine = Doc.prototype.iter; // The Doc methods that should be available on CodeMirror instances var dontDelegate = "iter insert remove copy getEditor".split(" "); for (var prop in Doc.prototype) if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0) CodeMirror.prototype[prop] = (function(method) { return function() {return method.apply(this.doc, arguments);}; })(Doc.prototype[prop]); eventMixin(Doc); function linkedDocs(doc, f, sharedHistOnly) { function propagate(doc, skip, sharedHist) { if (doc.linked) for (var i = 0; i < doc.linked.length; ++i) { var rel = doc.linked[i]; if (rel.doc == skip) continue; var shared = sharedHist && rel.sharedHist; if (sharedHistOnly && !shared) continue; f(rel.doc, shared); propagate(rel.doc, doc, shared); } } propagate(doc, null, true); } function attachDoc(cm, doc) { if (doc.cm) throw new Error("This document is already in use."); cm.doc = doc; doc.cm = cm; estimateLineHeights(cm); loadMode(cm); if (!cm.options.lineWrapping) computeMaxLength(cm); cm.options.mode = doc.modeOption; regChange(cm); } // LINE UTILITIES function getLine(chunk, n) { n -= chunk.first; while (!chunk.lines) { for (var i = 0;; ++i) { var child = chunk.children[i], sz = child.chunkSize(); if (n < sz) { chunk = child; break; } n -= sz; } } return chunk.lines[n]; } function getBetween(doc, start, end) { var out = [], n = start.line; doc.iter(start.line, end.line + 1, function(line) { var text = line.text; if (n == end.line) text = text.slice(0, end.ch); if (n == start.line) text = text.slice(start.ch); out.push(text); ++n; }); return out; } function getLines(doc, from, to) { var out = []; doc.iter(from, to, function(line) { out.push(line.text); }); return out; } function updateLineHeight(line, height) { var diff = height - line.height; for (var n = line; n; n = n.parent) n.height += diff; } function lineNo(line) { if (line.parent == null) return null; var cur = line.parent, no = indexOf(cur.lines, line); for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) { for (var i = 0;; ++i) { if (chunk.children[i] == cur) break; no += chunk.children[i].chunkSize(); } } return no + cur.first; } function lineAtHeight(chunk, h) { var n = chunk.first; outer: do { for (var i = 0, e = chunk.children.length; i < e; ++i) { var child = chunk.children[i], ch = child.height; if (h < ch) { chunk = child; continue outer; } h -= ch; n += child.chunkSize(); } return n; } while (!chunk.lines); for (var i = 0, e = chunk.lines.length; i < e; ++i) { var line = chunk.lines[i], lh = line.height; if (h < lh) break; h -= lh; } return n + i; } function heightAtLine(cm, lineObj) { lineObj = visualLine(cm.doc, lineObj); var h = 0, chunk = lineObj.parent; for (var i = 0; i < chunk.lines.length; ++i) { var line = chunk.lines[i]; if (line == lineObj) break; else h += line.height; } for (var p = chunk.parent; p; chunk = p, p = chunk.parent) { for (var i = 0; i < p.children.length; ++i) { var cur = p.children[i]; if (cur == chunk) break; else h += cur.height; } } return h; } function getOrder(line) { var order = line.order; if (order == null) order = line.order = bidiOrdering(line.text); return order; } // HISTORY function makeHistory(startGen) { return { // Arrays of history events. Doing something adds an event to // done and clears undo. Undoing moves events from done to // undone, redoing moves them in the other direction. done: [], undone: [], undoDepth: Infinity, // Used to track when changes can be merged into a single undo // event lastTime: 0, lastOp: null, lastOrigin: null, // Used by the isClean() method generation: startGen || 1, maxGeneration: startGen || 1 }; } function attachLocalSpans(doc, change, from, to) { var existing = change["spans_" + doc.id], n = 0; doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function(line) { if (line.markedSpans) (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans; ++n; }); } function historyChangeFromChange(doc, change) { var from = { line: change.from.line, ch: change.from.ch }; var histChange = {from: from, to: changeEnd(change), text: getBetween(doc, change.from, change.to)}; attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); linkedDocs(doc, function(doc) {attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);}, true); return histChange; } function addToHistory(doc, change, selAfter, opId) { var hist = doc.history; hist.undone.length = 0; var time = +new Date, cur = lst(hist.done); if (cur && (hist.lastOp == opId || hist.lastOrigin == change.origin && change.origin && ((change.origin.charAt(0) == "+" && doc.cm && hist.lastTime > time - doc.cm.options.historyEventDelay) || change.origin.charAt(0) == "*"))) { // Merge this change into the last event var last = lst(cur.changes); if (posEq(change.from, change.to) && posEq(change.from, last.to)) { // Optimized case for simple insertion -- don't want to add // new changesets for every character typed last.to = changeEnd(change); } else { // Add new sub-event cur.changes.push(historyChangeFromChange(doc, change)); } cur.anchorAfter = selAfter.anchor; cur.headAfter = selAfter.head; } else { // Can not be merged, start a new event. cur = {changes: [historyChangeFromChange(doc, change)], generation: hist.generation, anchorBefore: doc.sel.anchor, headBefore: doc.sel.head, anchorAfter: selAfter.anchor, headAfter: selAfter.head}; hist.done.push(cur); hist.generation = ++hist.maxGeneration; while (hist.done.length > hist.undoDepth) hist.done.shift(); } hist.lastTime = time; hist.lastOp = opId; hist.lastOrigin = change.origin; } function removeClearedSpans(spans) { if (!spans) return null; for (var i = 0, out; i < spans.length; ++i) { if (spans[i].marker.explicitlyCleared) { if (!out) out = spans.slice(0, i); } else if (out) out.push(spans[i]); } return !out ? spans : out.length ? out : null; } function getOldSpans(doc, change) { var found = change["spans_" + doc.id]; if (!found) return null; for (var i = 0, nw = []; i < change.text.length; ++i) nw.push(removeClearedSpans(found[i])); return nw; } // Used both to provide a JSON-safe object in .getHistory, and, when // detaching a document, to split the history in two function copyHistoryArray(events, newGroup) { for (var i = 0, copy = []; i < events.length; ++i) { var event = events[i], changes = event.changes, newChanges = []; copy.push({changes: newChanges, anchorBefore: event.anchorBefore, headBefore: event.headBefore, anchorAfter: event.anchorAfter, headAfter: event.headAfter}); for (var j = 0; j < changes.length; ++j) { var change = changes[j], m; newChanges.push({from: change.from, to: change.to, text: change.text}); if (newGroup) for (var prop in change) if (m = prop.match(/^spans_(\d+)$/)) { if (indexOf(newGroup, Number(m[1])) > -1) { lst(newChanges)[prop] = change[prop]; delete change[prop]; } } } } return copy; } // Rebasing/resetting history to deal with externally-sourced changes function rebaseHistSel(pos, from, to, diff) { if (to < pos.line) { pos.line += diff; } else if (from < pos.line) { pos.line = from; pos.ch = 0; } } // Tries to rebase an array of history events given a change in the // document. If the change touches the same lines as the event, the // event, and everything 'behind' it, is discarded. If the change is // before the event, the event's positions are updated. Uses a // copy-on-write scheme for the positions, to avoid having to // reallocate them all on every rebase, but also avoid problems with // shared position objects being unsafely updated. function rebaseHistArray(array, from, to, diff) { for (var i = 0; i < array.length; ++i) { var sub = array[i], ok = true; for (var j = 0; j < sub.changes.length; ++j) { var cur = sub.changes[j]; if (!sub.copied) { cur.from = copyPos(cur.from); cur.to = copyPos(cur.to); } if (to < cur.from.line) { cur.from.line += diff; cur.to.line += diff; } else if (from <= cur.to.line) { ok = false; break; } } if (!sub.copied) { sub.anchorBefore = copyPos(sub.anchorBefore); sub.headBefore = copyPos(sub.headBefore); sub.anchorAfter = copyPos(sub.anchorAfter); sub.readAfter = copyPos(sub.headAfter); sub.copied = true; } if (!ok) { array.splice(0, i + 1); i = 0; } else { rebaseHistSel(sub.anchorBefore); rebaseHistSel(sub.headBefore); rebaseHistSel(sub.anchorAfter); rebaseHistSel(sub.headAfter); } } } function rebaseHist(hist, change) { var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1; rebaseHistArray(hist.done, from, to, diff); rebaseHistArray(hist.undone, from, to, diff); } // EVENT OPERATORS function stopMethod() {e_stop(this);} // Ensure an event has a stop method. function addStop(event) { if (!event.stop) event.stop = stopMethod; return event; } function e_preventDefault(e) { if (e.preventDefault) e.preventDefault(); else e.returnValue = false; } function e_stopPropagation(e) { if (e.stopPropagation) e.stopPropagation(); else e.cancelBubble = true; } function e_defaultPrevented(e) { return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false; } function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);} CodeMirror.e_stop = e_stop; CodeMirror.e_preventDefault = e_preventDefault; CodeMirror.e_stopPropagation = e_stopPropagation; function e_target(e) {return e.target || e.srcElement;} function e_button(e) { var b = e.which; if (b == null) { if (e.button & 1) b = 1; else if (e.button & 2) b = 3; else if (e.button & 4) b = 2; } if (mac && e.ctrlKey && b == 1) b = 3; return b; } // EVENT HANDLING function on(emitter, type, f) { if (emitter.addEventListener) emitter.addEventListener(type, f, false); else if (emitter.attachEvent) emitter.attachEvent("on" + type, f); else { var map = emitter._handlers || (emitter._handlers = {}); var arr = map[type] || (map[type] = []); arr.push(f); } } function off(emitter, type, f) { if (emitter.removeEventListener) emitter.removeEventListener(type, f, false); else if (emitter.detachEvent) emitter.detachEvent("on" + type, f); else { var arr = emitter._handlers && emitter._handlers[type]; if (!arr) return; for (var i = 0; i < arr.length; ++i) if (arr[i] == f) { arr.splice(i, 1); break; } } } function signal(emitter, type /*, values...*/) { var arr = emitter._handlers && emitter._handlers[type]; if (!arr) return; var args = Array.prototype.slice.call(arguments, 2); for (var i = 0; i < arr.length; ++i) arr[i].apply(null, args); } var delayedCallbacks, delayedCallbackDepth = 0; function signalLater(emitter, type /*, values...*/) { var arr = emitter._handlers && emitter._handlers[type]; if (!arr) return; var args = Array.prototype.slice.call(arguments, 2); if (!delayedCallbacks) { ++delayedCallbackDepth; delayedCallbacks = []; setTimeout(fireDelayed, 0); } function bnd(f) {return function(){f.apply(null, args);};}; for (var i = 0; i < arr.length; ++i) delayedCallbacks.push(bnd(arr[i])); } function signalDOMEvent(cm, e, override) { signal(cm, override || e.type, cm, e); return e_defaultPrevented(e) || e.codemirrorIgnore; } function fireDelayed() { --delayedCallbackDepth; var delayed = delayedCallbacks; delayedCallbacks = null; for (var i = 0; i < delayed.length; ++i) delayed[i](); } function hasHandler(emitter, type) { var arr = emitter._handlers && emitter._handlers[type]; return arr && arr.length > 0; } CodeMirror.on = on; CodeMirror.off = off; CodeMirror.signal = signal; function eventMixin(ctor) { ctor.prototype.on = function(type, f) {on(this, type, f);}; ctor.prototype.off = function(type, f) {off(this, type, f);}; } // MISC UTILITIES // Number of pixels added to scroller and sizer to hide scrollbar var scrollerCutOff = 30; // Returned or thrown by various protocols to signal 'I'm not // handling this'. var Pass = CodeMirror.Pass = {toString: function(){return "CodeMirror.Pass";}}; function Delayed() {this.id = null;} Delayed.prototype = {set: function(ms, f) {clearTimeout(this.id); this.id = setTimeout(f, ms);}}; // Counts the column offset in a string, taking tabs into account. // Used mostly to find indentation. function countColumn(string, end, tabSize, startIndex, startValue) { if (end == null) { end = string.search(/[^\s\u00a0]/); if (end == -1) end = string.length; } for (var i = startIndex || 0, n = startValue || 0; i < end; ++i) { if (string.charAt(i) == "\t") n += tabSize - (n % tabSize); else ++n; } return n; } CodeMirror.countColumn = countColumn; var spaceStrs = [""]; function spaceStr(n) { while (spaceStrs.length <= n) spaceStrs.push(lst(spaceStrs) + " "); return spaceStrs[n]; } function lst(arr) { return arr[arr.length-1]; } function selectInput(node) { if (ios) { // Mobile Safari apparently has a bug where select() is broken. node.selectionStart = 0; node.selectionEnd = node.value.length; } else { // Suppress mysterious IE10 errors try { node.select(); } catch(_e) {} } } function indexOf(collection, elt) { if (collection.indexOf) return collection.indexOf(elt); for (var i = 0, e = collection.length; i < e; ++i) if (collection[i] == elt) return i; return -1; } function createObj(base, props) { function Obj() {} Obj.prototype = base; var inst = new Obj(); if (props) copyObj(props, inst); return inst; } function copyObj(obj, target) { if (!target) target = {}; for (var prop in obj) if (obj.hasOwnProperty(prop)) target[prop] = obj[prop]; return target; } function emptyArray(size) { for (var a = [], i = 0; i < size; ++i) a.push(undefined); return a; } function bind(f) { var args = Array.prototype.slice.call(arguments, 1); return function(){return f.apply(null, args);}; } var nonASCIISingleCaseWordChar = /[\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/; function isWordChar(ch) { return /\w/.test(ch) || ch > "\x80" && (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch)); } function isEmpty(obj) { for (var n in obj) if (obj.hasOwnProperty(n) && obj[n]) return false; return true; } var isExtendingChar = /[\u0300-\u036F\u0483-\u0487\u0488-\u0489\u0591-\u05BD\u05BF\u05C1-\u05C2\u05C4-\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7-\u06E8\u06EA-\u06ED\uA66F\uA670-\uA672\uA674-\uA67D\uA69F\udc00-\udfff]/; // DOM UTILITIES function elt(tag, content, className, style) { var e = document.createElement(tag); if (className) e.className = className; if (style) e.style.cssText = style; if (typeof content == "string") setTextContent(e, content); else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]); return e; } function removeChildren(e) { for (var count = e.childNodes.length; count > 0; --count) e.removeChild(e.firstChild); return e; } function removeChildrenAndAdd(parent, e) { return removeChildren(parent).appendChild(e); } function setTextContent(e, str) { if (ie_lt9) { e.innerHTML = ""; e.appendChild(document.createTextNode(str)); } else e.textContent = str; } function getRect(node) { return node.getBoundingClientRect(); } CodeMirror.replaceGetRect = function(f) { getRect = f; }; // FEATURE DETECTION // Detect drag-and-drop var dragAndDrop = function() { // There is *some* kind of drag-and-drop support in IE6-8, but I // couldn't get it to work yet. if (ie_lt9) return false; var div = elt('div'); return "draggable" in div || "dragDrop" in div; }(); // For a reason I have yet to figure out, some browsers disallow // word wrapping between certain characters *only* if a new inline // element is started between them. This makes it hard to reliably // measure the position of things, since that requires inserting an // extra span. This terribly fragile set of tests matches the // character combinations that suffer from this phenomenon on the // various browsers. function spanAffectsWrapping() { return false; } if (gecko) // Only for "$'" spanAffectsWrapping = function(str, i) { return str.charCodeAt(i - 1) == 36 && str.charCodeAt(i) == 39; }; else if (safari && !/Version\/([6-9]|\d\d)\b/.test(navigator.userAgent)) spanAffectsWrapping = function(str, i) { return /\-[^ \-?]|\?[^ !\'\"\),.\-\/:;\?\]\}]/.test(str.slice(i - 1, i + 1)); }; else if (webkit && !/Chrome\/(?:29|[3-9]\d|\d\d\d)\./.test(navigator.userAgent)) spanAffectsWrapping = function(str, i) { if (i > 1 && str.charCodeAt(i - 1) == 45) { if (/\w/.test(str.charAt(i - 2)) && /[^\-?\.]/.test(str.charAt(i))) return true; if (i > 2 && /[\d\.,]/.test(str.charAt(i - 2)) && /[\d\.,]/.test(str.charAt(i))) return false; } return /[~!#%&*)=+}\]|\"\.>,:;][({[<]|-[^\-?\.\u2010-\u201f\u2026]|\?[\w~`@#$%\^&*(_=+{[|><]|…[\w~`@#$%\^&*(_=+{[><]/.test(str.slice(i - 1, i + 1)); }; var knownScrollbarWidth; function scrollbarWidth(measure) { if (knownScrollbarWidth != null) return knownScrollbarWidth; var test = elt("div", null, null, "width: 50px; height: 50px; overflow-x: scroll"); removeChildrenAndAdd(measure, test); if (test.offsetWidth) knownScrollbarWidth = test.offsetHeight - test.clientHeight; return knownScrollbarWidth || 0; } var zwspSupported; function zeroWidthElement(measure) { if (zwspSupported == null) { var test = elt("span", "\u200b"); removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")])); if (measure.firstChild.offsetHeight != 0) zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !ie_lt8; } if (zwspSupported) return elt("span", "\u200b"); else return elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px"); } // See if "".split is the broken IE version, if so, provide an // alternative way to split lines. var splitLines = "\n\nb".split(/\n/).length != 3 ? function(string) { var pos = 0, result = [], l = string.length; while (pos <= l) { var nl = string.indexOf("\n", pos); if (nl == -1) nl = string.length; var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl); var rt = line.indexOf("\r"); if (rt != -1) { result.push(line.slice(0, rt)); pos += rt + 1; } else { result.push(line); pos = nl + 1; } } return result; } : function(string){return string.split(/\r\n?|\n/);}; CodeMirror.splitLines = splitLines; var hasSelection = window.getSelection ? function(te) { try { return te.selectionStart != te.selectionEnd; } catch(e) { return false; } } : function(te) { try {var range = te.ownerDocument.selection.createRange();} catch(e) {} if (!range || range.parentElement() != te) return false; return range.compareEndPoints("StartToEnd", range) != 0; }; var hasCopyEvent = (function() { var e = elt("div"); if ("oncopy" in e) return true; e.setAttribute("oncopy", "return;"); return typeof e.oncopy == 'function'; })(); // KEY NAMING var keyNames = {3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt", 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End", 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert", 46: "Delete", 59: ";", 91: "Mod", 92: "Mod", 93: "Mod", 109: "-", 107: "=", 127: "Delete", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\", 221: "]", 222: "'", 63276: "PageUp", 63277: "PageDown", 63275: "End", 63273: "Home", 63234: "Left", 63232: "Up", 63235: "Right", 63233: "Down", 63302: "Insert", 63272: "Delete"}; CodeMirror.keyNames = keyNames; (function() { // Number keys for (var i = 0; i < 10; i++) keyNames[i + 48] = String(i); // Alphabetic keys for (var i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i); // Function keys for (var i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i; })(); // BIDI HELPERS function iterateBidiSections(order, from, to, f) { if (!order) return f(from, to, "ltr"); var found = false; for (var i = 0; i < order.length; ++i) { var part = order[i]; if (part.from < to && part.to > from || from == to && part.to == from) { f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr"); found = true; } } if (!found) f(from, to, "ltr"); } function bidiLeft(part) { return part.level % 2 ? part.to : part.from; } function bidiRight(part) { return part.level % 2 ? part.from : part.to; } function lineLeft(line) { var order = getOrder(line); return order ? bidiLeft(order[0]) : 0; } function lineRight(line) { var order = getOrder(line); if (!order) return line.text.length; return bidiRight(lst(order)); } function lineStart(cm, lineN) { var line = getLine(cm.doc, lineN); var visual = visualLine(cm.doc, line); if (visual != line) lineN = lineNo(visual); var order = getOrder(visual); var ch = !order ? 0 : order[0].level % 2 ? lineRight(visual) : lineLeft(visual); return Pos(lineN, ch); } function lineEnd(cm, lineN) { var merged, line; while (merged = collapsedSpanAtEnd(line = getLine(cm.doc, lineN))) lineN = merged.find().to.line; var order = getOrder(line); var ch = !order ? line.text.length : order[0].level % 2 ? lineLeft(line) : lineRight(line); return Pos(lineN, ch); } function compareBidiLevel(order, a, b) { var linedir = order[0].level; if (a == linedir) return true; if (b == linedir) return false; return a < b; } var bidiOther; function getBidiPartAt(order, pos) { for (var i = 0, found; i < order.length; ++i) { var cur = order[i]; if (cur.from < pos && cur.to > pos) { bidiOther = null; return i; } if (cur.from == pos || cur.to == pos) { if (found == null) { found = i; } else if (compareBidiLevel(order, cur.level, order[found].level)) { bidiOther = found; return i; } else { bidiOther = i; return found; } } } bidiOther = null; return found; } function moveInLine(line, pos, dir, byUnit) { if (!byUnit) return pos + dir; do pos += dir; while (pos > 0 && isExtendingChar.test(line.text.charAt(pos))); return pos; } // This is somewhat involved. It is needed in order to move // 'visually' through bi-directional text -- i.e., pressing left // should make the cursor go left, even when in RTL text. The // tricky part is the 'jumps', where RTL and LTR text touch each // other. This often requires the cursor offset to move more than // one unit, in order to visually move one unit. function moveVisually(line, start, dir, byUnit) { var bidi = getOrder(line); if (!bidi) return moveLogically(line, start, dir, byUnit); var pos = getBidiPartAt(bidi, start), part = bidi[pos]; var target = moveInLine(line, start, part.level % 2 ? -dir : dir, byUnit); for (;;) { if (target > part.from && target < part.to) return target; if (target == part.from || target == part.to) { if (getBidiPartAt(bidi, target) == pos) return target; part = bidi[pos += dir]; return (dir > 0) == part.level % 2 ? part.to : part.from; } else { part = bidi[pos += dir]; if (!part) return null; if ((dir > 0) == part.level % 2) target = moveInLine(line, part.to, -1, byUnit); else target = moveInLine(line, part.from, 1, byUnit); } } } function moveLogically(line, start, dir, byUnit) { var target = start + dir; if (byUnit) while (target > 0 && isExtendingChar.test(line.text.charAt(target))) target += dir; return target < 0 || target > line.text.length ? null : target; } // Bidirectional ordering algorithm // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm // that this (partially) implements. // One-char codes used for character types: // L (L): Left-to-Right // R (R): Right-to-Left // r (AL): Right-to-Left Arabic // 1 (EN): European Number // + (ES): European Number Separator // % (ET): European Number Terminator // n (AN): Arabic Number // , (CS): Common Number Separator // m (NSM): Non-Spacing Mark // b (BN): Boundary Neutral // s (B): Paragraph Separator // t (S): Segment Separator // w (WS): Whitespace // N (ON): Other Neutrals // Returns null if characters are ordered as they appear // (left-to-right), or an array of sections ({from, to, level} // objects) in the order in which they occur visually. var bidiOrdering = (function() { // Character types for codepoints 0 to 0xff var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLL"; // Character types for codepoints 0x600 to 0x6ff var arabicTypes = "rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmmrrrrrrrrrrrrrrrrrr"; function charType(code) { if (code <= 0xff) return lowTypes.charAt(code); else if (0x590 <= code && code <= 0x5f4) return "R"; else if (0x600 <= code && code <= 0x6ff) return arabicTypes.charAt(code - 0x600); else if (0x700 <= code && code <= 0x8ac) return "r"; else return "L"; } var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/; var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/; // Browsers seem to always treat the boundaries of block elements as being L. var outerType = "L"; return function(str) { if (!bidiRE.test(str)) return false; var len = str.length, types = []; for (var i = 0, type; i < len; ++i) types.push(type = charType(str.charCodeAt(i))); // W1. Examine each non-spacing mark (NSM) in the level run, and // change the type of the NSM to the type of the previous // character. If the NSM is at the start of the level run, it will // get the type of sor. for (var i = 0, prev = outerType; i < len; ++i) { var type = types[i]; if (type == "m") types[i] = prev; else prev = type; } // W2. Search backwards from each instance of a European number // until the first strong type (R, L, AL, or sor) is found. If an // AL is found, change the type of the European number to Arabic // number. // W3. Change all ALs to R. for (var i = 0, cur = outerType; i < len; ++i) { var type = types[i]; if (type == "1" && cur == "r") types[i] = "n"; else if (isStrong.test(type)) { cur = type; if (type == "r") types[i] = "R"; } } // W4. A single European separator between two European numbers // changes to a European number. A single common separator between // two numbers of the same type changes to that type. for (var i = 1, prev = types[0]; i < len - 1; ++i) { var type = types[i]; if (type == "+" && prev == "1" && types[i+1] == "1") types[i] = "1"; else if (type == "," && prev == types[i+1] && (prev == "1" || prev == "n")) types[i] = prev; prev = type; } // W5. A sequence of European terminators adjacent to European // numbers changes to all European numbers. // W6. Otherwise, separators and terminators change to Other // Neutral. for (var i = 0; i < len; ++i) { var type = types[i]; if (type == ",") types[i] = "N"; else if (type == "%") { for (var end = i + 1; end < len && types[end] == "%"; ++end) {} var replace = (i && types[i-1] == "!") || (end < len - 1 && types[end] == "1") ? "1" : "N"; for (var j = i; j < end; ++j) types[j] = replace; i = end - 1; } } // W7. Search backwards from each instance of a European number // until the first strong type (R, L, or sor) is found. If an L is // found, then change the type of the European number to L. for (var i = 0, cur = outerType; i < len; ++i) { var type = types[i]; if (cur == "L" && type == "1") types[i] = "L"; else if (isStrong.test(type)) cur = type; } // N1. A sequence of neutrals takes the direction of the // surrounding strong text if the text on both sides has the same // direction. European and Arabic numbers act as if they were R in // terms of their influence on neutrals. Start-of-level-run (sor) // and end-of-level-run (eor) are used at level run boundaries. // N2. Any remaining neutrals take the embedding direction. for (var i = 0; i < len; ++i) { if (isNeutral.test(types[i])) { for (var end = i + 1; end < len && isNeutral.test(types[end]); ++end) {} var before = (i ? types[i-1] : outerType) == "L"; var after = (end < len - 1 ? types[end] : outerType) == "L"; var replace = before || after ? "L" : "R"; for (var j = i; j < end; ++j) types[j] = replace; i = end - 1; } } // Here we depart from the documented algorithm, in order to avoid // building up an actual levels array. Since there are only three // levels (0, 1, 2) in an implementation that doesn't take // explicit embedding into account, we can build up the order on // the fly, without following the level-based algorithm. var order = [], m; for (var i = 0; i < len;) { if (countsAsLeft.test(types[i])) { var start = i; for (++i; i < len && countsAsLeft.test(types[i]); ++i) {} order.push({from: start, to: i, level: 0}); } else { var pos = i, at = order.length; for (++i; i < len && types[i] != "L"; ++i) {} for (var j = pos; j < i;) { if (countsAsNum.test(types[j])) { if (pos < j) order.splice(at, 0, {from: pos, to: j, level: 1}); var nstart = j; for (++j; j < i && countsAsNum.test(types[j]); ++j) {} order.splice(at, 0, {from: nstart, to: j, level: 2}); pos = j; } else ++j; } if (pos < i) order.splice(at, 0, {from: pos, to: i, level: 1}); } } if (order[0].level == 1 && (m = str.match(/^\s+/))) { order[0].from = m[0].length; order.unshift({from: 0, to: m[0].length, level: 0}); } if (lst(order).level == 1 && (m = str.match(/\s+$/))) { lst(order).to -= m[0].length; order.push({from: len - m[0].length, to: len, level: 0}); } if (order[0].level != lst(order).level) order.push({from: len, to: len, level: order[0].level}); return order; }; })(); // THE END CodeMirror.version = "3.15.0"; return CodeMirror; })(); // Utility function that allows modes to be combined. The mode given // as the base argument takes care of most of the normal mode // functionality, but a second (typically simple) mode is used, which // can override the style of text. Both modes get to parse all of the // text, but when both assign a non-null style to a piece of code, the // overlay wins, unless the combine argument was true, in which case // the styles are combined. // overlayParser is the old, deprecated name CodeMirror.overlayMode = CodeMirror.overlayParser = function(base, overlay, combine) { return { startState: function() { return { base: CodeMirror.startState(base), overlay: CodeMirror.startState(overlay), basePos: 0, baseCur: null, overlayPos: 0, overlayCur: null }; }, copyState: function(state) { return { base: CodeMirror.copyState(base, state.base), overlay: CodeMirror.copyState(overlay, state.overlay), basePos: state.basePos, baseCur: null, overlayPos: state.overlayPos, overlayCur: null }; }, token: function(stream, state) { if (stream.start == state.basePos) { state.baseCur = base.token(stream, state.base); state.basePos = stream.pos; } if (stream.start == state.overlayPos) { stream.pos = stream.start; state.overlayCur = overlay.token(stream, state.overlay); state.overlayPos = stream.pos; } stream.pos = Math.min(state.basePos, state.overlayPos); if (stream.eol()) state.basePos = state.overlayPos = 0; if (state.overlayCur == null) return state.baseCur; if (state.baseCur != null && combine) return state.baseCur + " " + state.overlayCur; else return state.overlayCur; }, indent: base.indent && function(state, textAfter) { return base.indent(state.base, textAfter); }, electricChars: base.electricChars, innerMode: function(state) { return {state: state.base, mode: base}; }, blankLine: function(state) { if (base.blankLine) base.blankLine(state.base); if (overlay.blankLine) overlay.blankLine(state.overlay); } }; }; CodeMirror.defineMode("markdown", function(cmCfg, modeCfg) { var htmlFound = CodeMirror.modes.hasOwnProperty("xml"); var htmlMode = CodeMirror.getMode(cmCfg, htmlFound ? {name: "xml", htmlMode: true} : "text/plain"); var aliases = { html: "htmlmixed", js: "javascript", json: "application/json", c: "text/x-csrc", "c++": "text/x-c++src", java: "text/x-java", csharp: "text/x-csharp", "c#": "text/x-csharp", scala: "text/x-scala" }; var getMode = (function () { var i, modes = {}, mimes = {}, mime; var list = []; for (var m in CodeMirror.modes) if (CodeMirror.modes.propertyIsEnumerable(m)) list.push(m); for (i = 0; i < list.length; i++) { modes[list[i]] = list[i]; } var mimesList = []; for (var m in CodeMirror.mimeModes) if (CodeMirror.mimeModes.propertyIsEnumerable(m)) mimesList.push({mime: m, mode: CodeMirror.mimeModes[m]}); for (i = 0; i < mimesList.length; i++) { mime = mimesList[i].mime; mimes[mime] = mimesList[i].mime; } for (var a in aliases) { if (aliases[a] in modes || aliases[a] in mimes) modes[a] = aliases[a]; } return function (lang) { return modes[lang] ? CodeMirror.getMode(cmCfg, modes[lang]) : null; }; }()); // Should underscores in words open/close em/strong? if (modeCfg.underscoresBreakWords === undefined) modeCfg.underscoresBreakWords = true; // Turn on fenced code blocks? ("```" to start/end) if (modeCfg.fencedCodeBlocks === undefined) modeCfg.fencedCodeBlocks = false; // Turn on task lists? ("- [ ] " and "- [x] ") if (modeCfg.taskLists === undefined) modeCfg.taskLists = false; var codeDepth = 0; var header = 'header' , code = 'comment' , quote1 = 'atom' , quote2 = 'number' , list1 = 'variable-2' , list2 = 'variable-3' , list3 = 'keyword' , hr = 'hr' , image = 'tag' , linkinline = 'link' , linkemail = 'link' , linktext = 'link' , linkhref = 'string' , em = 'em' , strong = 'strong'; var hrRE = /^([*\-=_])(?:\s*\1){2,}\s*$/ , ulRE = /^[*\-+]\s+/ , olRE = /^[0-9]+\.\s+/ , taskListRE = /^\[(x| )\](?=\s)/ // Must follow ulRE or olRE , headerRE = /^(?:\={1,}|-{1,})$/ , textRE = /^[^!\[\]*_\\<>` "'(]+/; function switchInline(stream, state, f) { state.f = state.inline = f; return f(stream, state); } function switchBlock(stream, state, f) { state.f = state.block = f; return f(stream, state); } // Blocks function blankLine(state) { // Reset linkTitle state state.linkTitle = false; // Reset EM state state.em = false; // Reset STRONG state state.strong = false; // Reset state.quote state.quote = 0; if (!htmlFound && state.f == htmlBlock) { state.f = inlineNormal; state.block = blockNormal; } // Reset state.trailingSpace state.trailingSpace = 0; state.trailingSpaceNewLine = false; // Mark this line as blank state.thisLineHasContent = false; return null; } function blockNormal(stream, state) { var prevLineIsList = (state.list !== false); if (state.list !== false && state.indentationDiff >= 0) { // Continued list if (state.indentationDiff < 4) { // Only adjust indentation if *not* a code block state.indentation -= state.indentationDiff; } state.list = null; } else if (state.list !== false && state.indentation > 0) { state.list = null; state.listDepth = Math.floor(state.indentation / 4); } else if (state.list !== false) { // No longer a list state.list = false; state.listDepth = 0; } if (state.indentationDiff >= 4) { state.indentation -= 4; stream.skipToEnd(); return code; } else if (stream.eatSpace()) { return null; } else if (stream.peek() === '#' || (state.prevLineHasContent && stream.match(headerRE)) ) { state.header = true; } else if (stream.eat('>')) { state.indentation++; state.quote = 1; stream.eatSpace(); while (stream.eat('>')) { stream.eatSpace(); state.quote++; } } else if (stream.peek() === '[') { return switchInline(stream, state, footnoteLink); } else if (stream.match(hrRE, true)) { return hr; } else if ((!state.prevLineHasContent || prevLineIsList) && (stream.match(ulRE, true) || stream.match(olRE, true))) { state.indentation += 4; state.list = true; state.listDepth++; if (modeCfg.taskLists && stream.match(taskListRE, false)) { state.taskList = true; } } else if (modeCfg.fencedCodeBlocks && stream.match(/^```([\w+#]*)/, true)) { // try switching mode state.localMode = getMode(RegExp.$1); if (state.localMode) state.localState = state.localMode.startState(); switchBlock(stream, state, local); return code; } return switchInline(stream, state, state.inline); } function htmlBlock(stream, state) { var style = htmlMode.token(stream, state.htmlState); if (htmlFound && style === 'tag' && state.htmlState.type !== 'openTag' && !state.htmlState.context) { state.f = inlineNormal; state.block = blockNormal; } if (state.md_inside && stream.current().indexOf(">")!=-1) { state.f = inlineNormal; state.block = blockNormal; state.htmlState.context = undefined; } return style; } function local(stream, state) { if (stream.sol() && stream.match(/^```/, true)) { state.localMode = state.localState = null; state.f = inlineNormal; state.block = blockNormal; return code; } else if (state.localMode) { return state.localMode.token(stream, state.localState); } else { stream.skipToEnd(); return code; } } // Inline function getType(state) { var styles = []; if (state.taskOpen) { return "meta"; } if (state.taskClosed) { return "property"; } if (state.strong) { styles.push(strong); } if (state.em) { styles.push(em); } if (state.linkText) { styles.push(linktext); } if (state.code) { styles.push(code); } if (state.header) { styles.push(header); } if (state.quote) { styles.push(state.quote % 2 ? quote1 : quote2); } if (state.list !== false) { var listMod = (state.listDepth - 1) % 3; if (!listMod) { styles.push(list1); } else if (listMod === 1) { styles.push(list2); } else { styles.push(list3); } } if (state.trailingSpaceNewLine) { styles.push("trailing-space-new-line"); } else if (state.trailingSpace) { styles.push("trailing-space-" + (state.trailingSpace % 2 ? "a" : "b")); } return styles.length ? styles.join(' ') : null; } function handleText(stream, state) { if (stream.match(textRE, true)) { return getType(state); } return undefined; } function inlineNormal(stream, state) { var style = state.text(stream, state); if (typeof style !== 'undefined') return style; if (state.list) { // List marker (*, +, -, 1., etc) state.list = null; return getType(state); } if (state.taskList) { var taskOpen = stream.match(taskListRE, true)[1] !== "x"; if (taskOpen) state.taskOpen = true; else state.taskClosed = true; state.taskList = false; return getType(state); } state.taskOpen = false; state.taskClosed = false; var ch = stream.next(); if (ch === '\\') { stream.next(); return getType(state); } // Matches link titles present on next line if (state.linkTitle) { state.linkTitle = false; var matchCh = ch; if (ch === '(') { matchCh = ')'; } matchCh = (matchCh+'').replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1"); var regex = '^\\s*(?:[^' + matchCh + '\\\\]+|\\\\\\\\|\\\\.)' + matchCh; if (stream.match(new RegExp(regex), true)) { return linkhref; } } // If this block is changed, it may need to be updated in GFM mode if (ch === '`') { var t = getType(state); var before = stream.pos; stream.eatWhile('`'); var difference = 1 + stream.pos - before; if (!state.code) { codeDepth = difference; state.code = true; return getType(state); } else { if (difference === codeDepth) { // Must be exact state.code = false; return t; } return getType(state); } } else if (state.code) { return getType(state); } if (ch === '!' && stream.match(/\[[^\]]*\] ?(?:\(|\[)/, false)) { stream.match(/\[[^\]]*\]/); state.inline = state.f = linkHref; return image; } if (ch === '[' && stream.match(/.*\](\(| ?\[)/, false)) { state.linkText = true; return getType(state); } if (ch === ']' && state.linkText) { var type = getType(state); state.linkText = false; state.inline = state.f = linkHref; return type; } if (ch === '<' && stream.match(/^(https?|ftps?):\/\/(?:[^\\>]|\\.)+>/, false)) { return switchInline(stream, state, inlineElement(linkinline, '>')); } if (ch === '<' && stream.match(/^[^> \\]+@(?:[^\\>]|\\.)+>/, false)) { return switchInline(stream, state, inlineElement(linkemail, '>')); } if (ch === '<' && stream.match(/^\w/, false)) { if (stream.string.indexOf(">")!=-1) { var atts = stream.string.substring(1,stream.string.indexOf(">")); if (/markdown\s*=\s*('|"){0,1}1('|"){0,1}/.test(atts)) { state.md_inside = true; } } stream.backUp(1); return switchBlock(stream, state, htmlBlock); } if (ch === '<' && stream.match(/^\/\w*?>/)) { state.md_inside = false; return "tag"; } var ignoreUnderscore = false; if (!modeCfg.underscoresBreakWords) { if (ch === '_' && stream.peek() !== '_' && stream.match(/(\w)/, false)) { var prevPos = stream.pos - 2; if (prevPos >= 0) { var prevCh = stream.string.charAt(prevPos); if (prevCh !== '_' && prevCh.match(/(\w)/, false)) { ignoreUnderscore = true; } } } } var t = getType(state); if (ch === '*' || (ch === '_' && !ignoreUnderscore)) { if (state.strong === ch && stream.eat(ch)) { // Remove STRONG state.strong = false; return t; } else if (!state.strong && stream.eat(ch)) { // Add STRONG state.strong = ch; return getType(state); } else if (state.em === ch) { // Remove EM state.em = false; return t; } else if (!state.em) { // Add EM state.em = ch; return getType(state); } } else if (ch === ' ') { if (stream.eat('*') || stream.eat('_')) { // Probably surrounded by spaces if (stream.peek() === ' ') { // Surrounded by spaces, ignore return getType(state); } else { // Not surrounded by spaces, back up pointer stream.backUp(1); } } } if (ch === ' ') { if (stream.match(/ +$/, false)) { state.trailingSpace++; } else if (state.trailingSpace) { state.trailingSpaceNewLine = true; } } return getType(state); } function linkHref(stream, state) { // Check if space, and return NULL if so (to avoid marking the space) if(stream.eatSpace()){ return null; } var ch = stream.next(); if (ch === '(' || ch === '[') { return switchInline(stream, state, inlineElement(linkhref, ch === '(' ? ')' : ']')); } return 'error'; } function footnoteLink(stream, state) { if (stream.match(/^[^\]]*\]:/, true)) { state.f = footnoteUrl; return linktext; } return switchInline(stream, state, inlineNormal); } function footnoteUrl(stream, state) { // Check if space, and return NULL if so (to avoid marking the space) if(stream.eatSpace()){ return null; } // Match URL stream.match(/^[^\s]+/, true); // Check for link title if (stream.peek() === undefined) { // End of line, set flag to check next line state.linkTitle = true; } else { // More content on line, check if link title stream.match(/^(?:\s+(?:"(?:[^"\\]|\\\\|\\.)+"|'(?:[^'\\]|\\\\|\\.)+'|\((?:[^)\\]|\\\\|\\.)+\)))?/, true); } state.f = state.inline = inlineNormal; return linkhref; } var savedInlineRE = []; function inlineRE(endChar) { if (!savedInlineRE[endChar]) { // Escape endChar for RegExp (taken from http://stackoverflow.com/a/494122/526741) endChar = (endChar+'').replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1"); // Match any non-endChar, escaped character, as well as the closing // endChar. savedInlineRE[endChar] = new RegExp('^(?:[^\\\\]|\\\\.)*?(' + endChar + ')'); } return savedInlineRE[endChar]; } function inlineElement(type, endChar, next) { next = next || inlineNormal; return function(stream, state) { stream.match(inlineRE(endChar)); state.inline = state.f = next; return type; }; } return { startState: function() { return { f: blockNormal, prevLineHasContent: false, thisLineHasContent: false, block: blockNormal, htmlState: CodeMirror.startState(htmlMode), indentation: 0, inline: inlineNormal, text: handleText, linkText: false, linkTitle: false, em: false, strong: false, header: false, taskList: false, list: false, listDepth: 0, quote: 0, trailingSpace: 0, trailingSpaceNewLine: false }; }, copyState: function(s) { return { f: s.f, prevLineHasContent: s.prevLineHasContent, thisLineHasContent: s.thisLineHasContent, block: s.block, htmlState: CodeMirror.copyState(htmlMode, s.htmlState), indentation: s.indentation, localMode: s.localMode, localState: s.localMode ? CodeMirror.copyState(s.localMode, s.localState) : null, inline: s.inline, text: s.text, linkTitle: s.linkTitle, em: s.em, strong: s.strong, header: s.header, taskList: s.taskList, list: s.list, listDepth: s.listDepth, quote: s.quote, trailingSpace: s.trailingSpace, trailingSpaceNewLine: s.trailingSpaceNewLine, md_inside: s.md_inside }; }, token: function(stream, state) { if (stream.sol()) { if (stream.match(/^\s*$/, true)) { state.prevLineHasContent = false; return blankLine(state); } else { state.prevLineHasContent = state.thisLineHasContent; state.thisLineHasContent = true; } // Reset state.header state.header = false; // Reset state.taskList state.taskList = false; // Reset state.code state.code = false; // Reset state.trailingSpace state.trailingSpace = 0; state.trailingSpaceNewLine = false; state.f = state.block; var indentation = stream.match(/^\s*/, true)[0].replace(/\t/g, ' ').length; var difference = Math.floor((indentation - state.indentation) / 4) * 4; if (difference > 4) difference = 4; var adjustedIndentation = state.indentation + difference; state.indentationDiff = adjustedIndentation - state.indentation; state.indentation = adjustedIndentation; if (indentation > 0) return null; } return state.f(stream, state); }, blankLine: blankLine, getType: getType }; }, "xml"); CodeMirror.defineMIME("text/x-markdown", "markdown"); CodeMirror.defineMode("gfm", function(config) { var codeDepth = 0; function blankLine(state) { state.code = false; return null; } var gfmOverlay = { startState: function() { return { code: false, codeBlock: false, ateSpace: false }; }, copyState: function(s) { return { code: s.code, codeBlock: s.codeBlock, ateSpace: s.ateSpace }; }, token: function(stream, state) { // Hack to prevent formatting override inside code blocks (block and inline) if (state.codeBlock) { if (stream.match(/^```/)) { state.codeBlock = false; return null; } stream.skipToEnd(); return null; } if (stream.sol()) { state.code = false; } if (stream.sol() && stream.match(/^```/)) { stream.skipToEnd(); state.codeBlock = true; return null; } // If this block is changed, it may need to be updated in Markdown mode if (stream.peek() === '`') { stream.next(); var before = stream.pos; stream.eatWhile('`'); var difference = 1 + stream.pos - before; if (!state.code) { codeDepth = difference; state.code = true; } else { if (difference === codeDepth) { // Must be exact state.code = false; } } return null; } else if (state.code) { stream.next(); return null; } // Check if space. If so, links can be formatted later on if (stream.eatSpace()) { state.ateSpace = true; return null; } if (stream.sol() || state.ateSpace) { state.ateSpace = false; if(stream.match(/^(?:[a-zA-Z0-9\-_]+\/)?(?:[a-zA-Z0-9\-_]+@)?(?:[a-f0-9]{7,40}\b)/)) { // User/Project@SHA // User@SHA // SHA return "link"; } else if (stream.match(/^(?:[a-zA-Z0-9\-_]+\/)?(?:[a-zA-Z0-9\-_]+)?#[0-9]+\b/)) { // User/Project#Num // User#Num // #Num return "link"; } } if (stream.match(/^((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\([^\s()<>]*\))+(?:\([^\s()<>]*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))/i)) { // URLs // Taken from http://daringfireball.net/2010/07/improved_regex_for_matching_urls // And then (issue #1160) simplified to make it not crash the Chrome Regexp engine return "link"; } stream.next(); return null; }, blankLine: blankLine }; CodeMirror.defineMIME("gfmBase", { name: "markdown", underscoresBreakWords: false, taskLists: true, fencedCodeBlocks: true }); return CodeMirror.overlayMode(CodeMirror.getMode(config, "gfmBase"), gfmOverlay); }, "markdown"); // // showdown.js -- A javascript port of Markdown. // // Copyright (c) 2007 John Fraser. // // Original Markdown Copyright (c) 2004-2005 John Gruber // <http://daringfireball.net/projects/markdown/> // // Redistributable under a BSD-style open source license. // See license.txt for more information. // // The full source distribution is at: // // A A L // T C A // T K B // // <http://www.attacklab.net/> // // // Wherever possible, Showdown is a straight, line-by-line port // of the Perl version of Markdown. // // This is not a normal parser design; it's basically just a // series of string substitutions. It's hard to read and // maintain this way, but keeping Showdown close to the original // design makes it easier to port new features. // // More importantly, Showdown behaves like markdown.pl in most // edge cases. So web applications can do client-side preview // in Javascript, and then build identical HTML on the server. // // This port needs the new RegExp functionality of ECMA 262, // 3rd Edition (i.e. Javascript 1.5). Most modern web browsers // should do fine. Even with the new regular expression features, // We do a lot of work to emulate Perl's regex functionality. // The tricky changes in this file mostly have the "attacklab:" // label. Major or self-explanatory changes don't. // // Smart diff tools like Araxis Merge will be able to match up // this file with markdown.pl in a useful way. A little tweaking // helps: in a copy of markdown.pl, replace "#" with "//" and // replace "$text" with "text". Be sure to ignore whitespace // and line endings. // // // Showdown usage: // // var text = "Markdown *rocks*."; // // var converter = new Showdown.converter(); // var html = converter.makeHtml(text); // // alert(html); // // Note: move the sample code to the bottom of this // file before uncommenting it. // // // Showdown namespace // var Showdown={extensions:{}},forEach=Showdown.forEach=function(a,b){if(typeof a.forEach=="function")a.forEach(b);else{var c,d=a.length;for(c=0;c<d;c++)b(a[c],c,a)}},stdExtName=function(a){return a.replace(/[_-]||\s/g,"").toLowerCase()};Showdown.converter=function(a){var b,c,d,e=0,f=[],g=[];if(typeof module!="undefind"&&typeof exports!="undefined"&&typeof require!="undefind"){var h=require("fs");if(h){var i=h.readdirSync((__dirname||".")+"/extensions").filter(function(a){return~a.indexOf(".js")}).map(function(a){return a.replace(/\.js$/,"")});Showdown.forEach(i,function(a){var b=stdExtName(a);Showdown.extensions[b]=require("./extensions/"+a)})}}this.makeHtml=function(a){return b={},c={},d=[],a=a.replace(/~/g,"~T"),a=a.replace(/\$/g,"~D"),a=a.replace(/\r\n/g,"\n"),a=a.replace(/\r/g,"\n"),a="\n\n"+a+"\n\n",a=M(a),a=a.replace(/^[ \t]+$/mg,""),Showdown.forEach(f,function(b){a=k(b,a)}),a=z(a),a=m(a),a=l(a),a=o(a),a=K(a),a=a.replace(/~D/g,"$$"),a=a.replace(/~T/g,"~"),Showdown.forEach(g,function(b){a=k(b,a)}),a};if(a&&a.extensions){var j=this;Showdown.forEach(a.extensions,function(a){typeof a=="string"&&(a=Showdown.extensions[stdExtName(a)]);if(typeof a!="function")throw"Extension '"+a+"' could not be loaded. It was either not found or is not a valid extension.";Showdown.forEach(a(j),function(a){a.type?a.type==="language"||a.type==="lang"?f.push(a):(a.type==="output"||a.type==="html")&&g.push(a):g.push(a)})})}var k=function(a,b){if(a.regex){var c=new RegExp(a.regex,"g");return b.replace(c,a.replace)}if(a.filter)return a.filter(b)},l=function(a){return a+="~0",a=a.replace(/^[ ]{0,3}\[(.+)\]:[ \t]*\n?[ \t]*<?(\S+?)>?[ \t]*\n?[ \t]*(?:(\n*)["(](.+?)[")][ \t]*)?(?:\n+|(?=~0))/gm,function(a,d,e,f,g){return d=d.toLowerCase(),b[d]=G(e),f?f+g:(g&&(c[d]=g.replace(/"/g,"&quot;")),"")}),a=a.replace(/~0/,""),a},m=function(a){a=a.replace(/\n/g,"\n\n");var b="p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del|style|section|header|footer|nav|article|aside",c="p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|style|section|header|footer|nav|article|aside";return a=a.replace(/^(<(p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del)\b[^\r]*?\n<\/\2>[ \t]*(?=\n+))/gm,n),a=a.replace(/^(<(p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|style|section|header|footer|nav|article|aside)\b[^\r]*?<\/\2>[ \t]*(?=\n+)\n)/gm,n),a=a.replace(/(\n[ ]{0,3}(<(hr)\b([^<>])*?\/?>)[ \t]*(?=\n{2,}))/g,n),a=a.replace(/(\n\n[ ]{0,3}<!(--[^\r]*?--\s*)+>[ \t]*(?=\n{2,}))/g,n),a=a.replace(/(?:\n\n)([ ]{0,3}(?:<([?%])[^\r]*?\2>)[ \t]*(?=\n{2,}))/g,n),a=a.replace(/\n\n/g,"\n"),a},n=function(a,b){var c=b;return c=c.replace(/\n\n/g,"\n"),c=c.replace(/^\n/,""),c=c.replace(/\n+$/g,""),c="\n\n~K"+(d.push(c)-1)+"K\n\n",c},o=function(a){a=v(a);var b=A("<hr />");return a=a.replace(/^[ ]{0,2}([ ]?\*[ ]?){3,}[ \t]*$/gm,b),a=a.replace(/^[ ]{0,2}([ ]?\-[ ]?){3,}[ \t]*$/gm,b),a=a.replace(/^[ ]{0,2}([ ]?\_[ ]?){3,}[ \t]*$/gm,b),a=x(a),a=y(a),a=E(a),a=m(a),a=F(a),a},p=function(a){return a=B(a),a=q(a),a=H(a),a=t(a),a=r(a),a=I(a),a=G(a),a=D(a),a=a.replace(/ +\n/g," <br />\n"),a},q=function(a){var b=/(<[a-z\/!$]("[^"]*"|'[^']*'|[^'">])*>|<!(--.*?--\s*)+>)/gi;return a=a.replace(b,function(a){var b=a.replace(/(.)<\/?code>(?=.)/g,"$1`");return b=N(b,"\\`*_"),b}),a},r=function(a){return a=a.replace(/(\[((?:\[[^\]]*\]|[^\[\]])*)\][ ]?(?:\n[ ]*)?\[(.*?)\])()()()()/g,s),a=a.replace(/(\[((?:\[[^\]]*\]|[^\[\]])*)\]\([ \t]*()<?(.*?(?:\(.*?\).*?)?)>?[ \t]*((['"])(.*?)\6[ \t]*)?\))/g,s),a=a.replace(/(\[([^\[\]]+)\])()()()()()/g,s),a},s=function(a,d,e,f,g,h,i,j){j==undefined&&(j="");var k=d,l=e,m=f.toLowerCase(),n=g,o=j;if(n==""){m==""&&(m=l.toLowerCase().replace(/ ?\n/g," ")),n="#"+m;if(b[m]!=undefined)n=b[m],c[m]!=undefined&&(o=c[m]);else{if(!(k.search(/\(\s*\)$/m)>-1))return k;n=""}}n=N(n,"*_");var p='<a href="'+n+'"';return o!=""&&(o=o.replace(/"/g,"&quot;"),o=N(o,"*_"),p+=' title="'+o+'"'),p+=">"+l+"</a>",p},t=function(a){return a=a.replace(/(!\[(.*?)\][ ]?(?:\n[ ]*)?\[(.*?)\])()()()()/g,u),a=a.replace(/(!\[(.*?)\]\s?\([ \t]*()<?(\S+?)>?[ \t]*((['"])(.*?)\6[ \t]*)?\))/g,u),a},u=function(a,d,e,f,g,h,i,j){var k=d,l=e,m=f.toLowerCase(),n=g,o=j;o||(o="");if(n==""){m==""&&(m=l.toLowerCase().replace(/ ?\n/g," ")),n="#"+m;if(b[m]==undefined)return k;n=b[m],c[m]!=undefined&&(o=c[m])}l=l.replace(/"/g,"&quot;"),n=N(n,"*_");var p='<img src="'+n+'" alt="'+l+'"';return o=o.replace(/"/g,"&quot;"),o=N(o,"*_"),p+=' title="'+o+'"',p+=" />",p},v=function(a){function b(a){return a.replace(/[^\w]/g,"").toLowerCase()}return a=a.replace(/^(.+)[ \t]*\n=+[ \t]*\n+/gm,function(a,c){return A('<h1 id="'+b(c)+'">'+p(c)+"</h1>")}),a=a.replace(/^(.+)[ \t]*\n-+[ \t]*\n+/gm,function(a,c){return A('<h2 id="'+b(c)+'">'+p(c)+"</h2>")}),a=a.replace(/^(\#{1,6})[ \t]*(.+?)[ \t]*\#*\n+/gm,function(a,c,d){var e=c.length;return A("<h"+e+' id="'+b(d)+'">'+p(d)+"</h"+e+">")}),a},w,x=function(a){a+="~0";var b=/^(([ ]{0,3}([*+-]|\d+[.])[ \t]+)[^\r]+?(~0|\n{2,}(?=\S)(?![ \t]*(?:[*+-]|\d+[.])[ \t]+)))/gm;return e?a=a.replace(b,function(a,b,c){var d=b,e=c.search(/[*+-]/g)>-1?"ul":"ol";d=d.replace(/\n{2,}/g,"\n\n\n");var f=w(d);return f=f.replace(/\s+$/,""),f="<"+e+">"+f+"</"+e+">\n",f}):(b=/(\n\n|^\n?)(([ ]{0,3}([*+-]|\d+[.])[ \t]+)[^\r]+?(~0|\n{2,}(?=\S)(?![ \t]*(?:[*+-]|\d+[.])[ \t]+)))/g,a=a.replace(b,function(a,b,c,d){var e=b,f=c,g=d.search(/[*+-]/g)>-1?"ul":"ol",f=f.replace(/\n{2,}/g,"\n\n\n"),h=w(f);return h=e+"<"+g+">\n"+h+"</"+g+">\n",h})),a=a.replace(/~0/,""),a};w=function(a){return e++,a=a.replace(/\n{2,}$/,"\n"),a+="~0",a=a.replace(/(\n)?(^[ \t]*)([*+-]|\d+[.])[ \t]+([^\r]+?(\n{1,2}))(?=\n*(~0|\2([*+-]|\d+[.])[ \t]+))/gm,function(a,b,c,d,e){var f=e,g=b,h=c;return g||f.search(/\n{2,}/)>-1?f=o(L(f)):(f=x(L(f)),f=f.replace(/\n$/,""),f=p(f)),"<li>"+f+"</li>\n"}),a=a.replace(/~0/g,""),e--,a};var y=function(a){return a+="~0",a=a.replace(/(?:\n\n|^)((?:(?:[ ]{4}|\t).*\n+)+)(\n*[ ]{0,3}[^ \t\n]|(?=~0))/g,function(a,b,c){var d=b,e=c;return d=C(L(d)),d=M(d),d=d.replace(/^\n+/g,""),d=d.replace(/\n+$/g,""),d="<pre><code>"+d+"\n</code></pre>",A(d)+e}),a=a.replace(/~0/,""),a},z=function(a){return a+="~0",a=a.replace(/(?:^|\n)```(.*)\n([\s\S]*?)\n```/g,function(a,b,c){var d=b,e=c;return e=C(e),e=M(e),e=e.replace(/^\n+/g,""),e=e.replace(/\n+$/g,""),e="<pre><code"+(d?' class="'+d+'"':"")+">"+e+"\n</code></pre>",A(e)}),a=a.replace(/~0/,""),a},A=function(a){return a=a.replace(/(^\n+|\n+$)/g,""),"\n\n~K"+(d.push(a)-1)+"K\n\n"},B=function(a){return a=a.replace(/(^|[^\\])(`+)([^\r]*?[^`])\2(?!`)/gm,function(a,b,c,d,e){var f=d;return f=f.replace(/^([ \t]*)/g,""),f=f.replace(/[ \t]*$/g,""),f=C(f),b+"<code>"+f+"</code>"}),a},C=function(a){return a=a.replace(/&/g,"&amp;"),a=a.replace(/</g,"&lt;"),a=a.replace(/>/g,"&gt;"),a=N(a,"*_{}[]\\",!1),a},D=function(a){return a=a.replace(/(\*\*|__)(?=\S)([^\r]*?\S[*_]*)\1/g,"<strong>$2</strong>"),a=a.replace(/(\*|_)(?=\S)([^\r]*?\S)\1/g,"<em>$2</em>"),a},E=function(a){return a=a.replace(/((^[ \t]*>[ \t]?.+\n(.+\n)*\n*)+)/gm,function(a,b){var c=b;return c=c.replace(/^[ \t]*>[ \t]?/gm,"~0"),c=c.replace(/~0/g,""),c=c.replace(/^[ \t]+$/gm,""),c=o(c),c=c.replace(/(^|\n)/g,"$1 "),c=c.replace(/(\s*<pre>[^\r]+?<\/pre>)/gm,function(a,b){var c=b;return c=c.replace(/^ /mg,"~0"),c=c.replace(/~0/g,""),c}),A("<blockquote>\n"+c+"\n</blockquote>")}),a},F=function(a){a=a.replace(/^\n+/g,""),a=a.replace(/\n+$/g,"");var b=a.split(/\n{2,}/g),c=[],e=b.length;for(var f=0;f<e;f++){var g=b[f];g.search(/~K(\d+)K/g)>=0?c.push(g):g.search(/\S/)>=0&&(g=p(g),g=g.replace(/^([ \t]*)/g,"<p>"),g+="</p>",c.push(g))}e=c.length;for(var f=0;f<e;f++)while(c[f].search(/~K(\d+)K/)>=0){var h=d[RegExp.$1];h=h.replace(/\$/g,"$$$$"),c[f]=c[f].replace(/~K\d+K/,h)}return c.join("\n\n")},G=function(a){return a=a.replace(/&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)/g,"&amp;"),a=a.replace(/<(?![a-z\/?\$!])/gi,"&lt;"),a},H=function(a){return a=a.replace(/\\(\\)/g,O),a=a.replace(/\\([`*_{}\[\]()>#+-.!])/g,O),a},I=function(a){return a=a.replace(/<((https?|ftp|dict):[^'">\s]+)>/gi,'<a href="$1">$1</a>'),a=a.replace(/<(?:mailto:)?([-.\w]+\@[-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+)>/gi,function(a,b){return J(K(b))}),a},J=function(a){var b=[function(a){return"&#"+a.charCodeAt(0)+";"},function(a){return"&#x"+a.charCodeAt(0).toString(16)+";"},function(a){return a}];return a="mailto:"+a,a=a.replace(/./g,function(a){if(a=="@")a=b[Math.floor(Math.random()*2)](a);else if(a!=":"){var c=Math.random();a=c>.9?b[2](a):c>.45?b[1](a):b[0](a)}return a}),a='<a href="'+a+'">'+a+"</a>",a=a.replace(/">.+:/g,'">'),a},K=function(a){return a=a.replace(/~E(\d+)E/g,function(a,b){var c=parseInt(b);return String.fromCharCode(c)}),a},L=function(a){return a=a.replace(/^(\t|[ ]{1,4})/gm,"~0"),a=a.replace(/~0/g,""),a},M=function(a){return a=a.replace(/\t(?=\t)/g," "),a=a.replace(/\t/g,"~A~B"),a=a.replace(/~B(.+?)~A/g,function(a,b,c){var d=b,e=4-d.length%4;for(var f=0;f<e;f++)d+=" ";return d}),a=a.replace(/~A/g," "),a=a.replace(/~B/g,""),a},N=function(a,b,c){var d="(["+b.replace(/([\[\]\\])/g,"\\$1")+"])";c&&(d="\\\\"+d);var e=new RegExp(d,"g");return a=a.replace(e,O),a},O=function(a,b){var c=b.charCodeAt(0);return"~E"+c+"E"}},typeof module!="undefined"&&(module.exports=Showdown),typeof define=="function"&&define.amd&&define("showdown",function(){return Showdown}); (function () { var ghostdown = function () { return [ // ![] image syntax { type: 'lang', filter: function (text) { var imageMarkdownRegex = /^(?:\{<(.*?)>\})?!(?:\[([^\n\]]*)\])(?:\(([^\n\]]*)\))?$/gim, /* regex from isURL in node-validator. Yum! */ uriRegex = /^(?!mailto:)(?:(?:https?|ftp):\/\/)?(?:\S+(?::\S*)?@)?(?:(?:(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[0-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))|localhost)(?::\d{2,5})?(?:\/[^\s]*)?$/i, pathRegex = /^(\/)?([^\/\0]+(\/)?)+$/i; return text.replace(imageMarkdownRegex, function (match, key, alt, src) { var result = ""; if (src && (src.match(uriRegex) || src.match(pathRegex))) { result = '<img class="js-upload-target" src="' + src + '"/>'; } return '<section id="image_upload_' + key + '" class="js-drop-zone image-uploader">' + result + '<div class="description">Add image of <strong>' + alt + '</strong></div>' + '<input data-url="upload" class="js-fileupload main fileupload" type="file" name="uploadimage">' + '</section>'; }); } } ]; }; // Client-side export if (typeof window !== 'undefined' && window.Showdown && window.Showdown.extensions) { window.Showdown.extensions.ghostdown = ghostdown; } // Server-side export if (typeof module !== 'undefined') module.exports = ghostdown; }()); // // Github Extension (WIP) // ~~strike-through~~ -> <del>strike-through</del> // (function () { var github = function (converter) { return [ { // strike-through // NOTE: showdown already replaced "~" with "~T", so we need to adjust accordingly. type : 'lang', regex : '(~T){2}([^~]+)(~T){2}', replace : function (match, prefix, content, suffix) { return '<del>' + content + '</del>'; } }, { // GFM newline and underscore modifications, happen BEFORE showdown type : 'lang', filter : function (text) { var preExtractions = {}, imageMarkdownRegex = /^(?:\{(.*?)\})?!(?:\[([^\n\]]*)\])(?:\(([^\n\]]*)\))?$/gim, hashID = 0; function hashId() { return hashID++; } // Extract pre blocks text = text.replace(/<pre>[\s\S]*?<\/pre>/gim, function (x) { var hash = hashId(); preExtractions[hash] = x; return "{gfm-js-extract-pre-" + hash + "}"; }, 'm'); //prevent foo_bar and foo_bar_baz from ending up with an italic word in the middle text = text.replace(/(^(?! {4}|\t)\w+_\w+_\w[\w_]*)/gm, function (x) { return x.replace(/_/gm, '\\_'); }); // in very clear cases, let newlines become <br /> tags text = text.replace(/^[\w\<][^\n]*\n+/gm, function (x) { return x.match(/\n{2}/) ? x : x.trim() + " \n"; }); // better URL support, but no title support text = text.replace(imageMarkdownRegex, function (match, key, alt, src) { if (src) { return '<img src="' + src + '" alt="' + alt + '" />'; } return ''; }); text = text.replace(/\{gfm-js-extract-pre-([0-9]+)\}/gm, function (x, y) { return "\n\n" + preExtractions[y]; }); return text; } }, { // GFM autolinking & custom image handling, happens AFTER showdown type : 'html', filter : function (text) { var refExtractions = {}, preExtractions = {}, hashID = 0; function hashId() { return hashID++; } // Extract pre blocks text = text.replace(/<(pre|code)>[\s\S]*?<\/(\1)>/gim, function (x) { var hash = hashId(); preExtractions[hash] = x; return "{gfm-js-extract-pre-" + hash + "}"; }, 'm'); // filter out def urls // from Marked https://github.com/chjj/marked/blob/master/lib/marked.js#L24 text = text.replace(/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +["(]([^\n]+)[")])? *(?:\n+|$)/gmi, function (x) { var hash = hashId(); refExtractions[hash] = x; return "{gfm-js-extract-ref-url-" + hash + "}"; }); // match a URL // adapted from https://gist.github.com/jorilallo/1283095#L158 // and http://blog.stevenlevithan.com/archives/mimic-lookbehind-javascript text = text.replace(/(\]\(|\]|\[|<a[^\>]*?\>)?https?\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!]/gmi, function (wholeMatch, lookBehind, matchIndex) { // Check we are not inside an HTML tag var left = text.slice(0, matchIndex), right = text.slice(matchIndex); if ((left.match(/<[^>]+$/) && right.match(/^[^>]*>/)) || lookBehind) { return wholeMatch; } // If we have a matching lookBehind, this is a failure, else wrap the match in <a> tag return lookBehind ? wholeMatch : "<a href='" + wholeMatch + "'>" + wholeMatch + "</a>"; }); // match email text = text.replace(/[a-z0-9_\-+=.]+@[a-z0-9\-]+(\.[a-z0-9-]+)+/gmi, function (wholeMatch) { return "<a href='mailto:" + wholeMatch + "'>" + wholeMatch + "</a>"; }); // replace extractions text = text.replace(/\{gfm-js-extract-pre-([0-9]+)\}/gm, function (x, y) { return preExtractions[y]; }); text = text.replace(/\{gfm-js-extract-ref-url-([0-9]+)\}/gi, function (x, y) { return "\n\n" + refExtractions[y]; }); return text; } } ]; }; // Client-side export if (typeof window !== 'undefined' && window.Showdown && window.Showdown.extensions) { window.Showdown.extensions.github = github; } // Server-side export if (typeof module !== 'undefined') module.exports = github; }()); /** * http://www.openjs.com/scripts/events/keyboard_shortcuts/ * Version : 2.01.B * By Binny V A * License : BSD */ shortcut = { 'all_shortcuts':{},//All the shortcuts are stored in this array 'add': function(shortcut_combination,callback,opt) { //Provide a set of default options var default_options = { 'type':'keydown', 'propagate':false, 'disable_in_input':false, 'target':document, 'keycode':false } if(!opt) opt = default_options; else { for(var dfo in default_options) { if(typeof opt[dfo] == 'undefined') opt[dfo] = default_options[dfo]; } } var ele = opt.target; if(typeof opt.target == 'string') ele = document.getElementById(opt.target); var ths = this; shortcut_combination = shortcut_combination.toLowerCase(); //The function to be called at keypress var func = function(e) { e = e || window.event; if(opt['disable_in_input']) { //Don't enable shortcut keys in Input, Textarea fields var element; if(e.target) element=e.target; else if(e.srcElement) element=e.srcElement; if(element.nodeType==3) element=element.parentNode; if(element.tagName == 'INPUT' || element.tagName == 'TEXTAREA') return; } //Find Which key is pressed if (e.keyCode) code = e.keyCode; else if (e.which) code = e.which; var character = String.fromCharCode(code).toLowerCase(); if(code == 188) character=","; //If the user presses , when the type is onkeydown if(code == 190) character="."; //If the user presses , when the type is onkeydown var keys = shortcut_combination.split("+"); //Key Pressed - counts the number of valid keypresses - if it is same as the number of keys, the shortcut function is invoked var kp = 0; //Work around for stupid Shift key bug created by using lowercase - as a result the shift+num combination was broken var shift_nums = { "`":"~", "1":"!", "2":"@", "3":"#", "4":"$", "5":"%", "6":"^", "7":"&", "8":"*", "9":"(", "0":")", "-":"_", "=":"+", ";":":", "'":"\"", ",":"<", ".":">", "/":"?", "\\":"|" } //Special Keys - and their codes var special_keys = { 'esc':27, 'escape':27, 'tab':9, 'space':32, 'return':13, 'enter':13, 'backspace':8, 'scrolllock':145, 'scroll_lock':145, 'scroll':145, 'capslock':20, 'caps_lock':20, 'caps':20, 'numlock':144, 'num_lock':144, 'num':144, 'pause':19, 'break':19, 'insert':45, 'home':36, 'delete':46, 'end':35, 'pageup':33, 'page_up':33, 'pu':33, 'pagedown':34, 'page_down':34, 'pd':34, 'left':37, 'up':38, 'right':39, 'down':40, 'f1':112, 'f2':113, 'f3':114, 'f4':115, 'f5':116, 'f6':117, 'f7':118, 'f8':119, 'f9':120, 'f10':121, 'f11':122, 'f12':123 } var modifiers = { shift: { wanted:false, pressed:false}, ctrl : { wanted:false, pressed:false}, alt : { wanted:false, pressed:false}, meta : { wanted:false, pressed:false} //Meta is Mac specific }; if(e.ctrlKey) modifiers.ctrl.pressed = true; if(e.shiftKey) modifiers.shift.pressed = true; if(e.altKey) modifiers.alt.pressed = true; if(e.metaKey) modifiers.meta.pressed = true; for(var i=0; k=keys[i],i<keys.length; i++) { //Modifiers if(k == 'ctrl' || k == 'control') { kp++; modifiers.ctrl.wanted = true; } else if(k == 'shift') { kp++; modifiers.shift.wanted = true; } else if(k == 'alt') { kp++; modifiers.alt.wanted = true; } else if(k == 'meta') { kp++; modifiers.meta.wanted = true; } else if(k.length > 1) { //If it is a special key if(special_keys[k] == code) kp++; } else if(opt['keycode']) { if(opt['keycode'] == code) kp++; } else { //The special keys did not match if(character == k) kp++; else { if(shift_nums[character] && e.shiftKey) { //Stupid Shift key bug created by using lowercase character = shift_nums[character]; if(character == k) kp++; } } } } if(kp == keys.length && modifiers.ctrl.pressed == modifiers.ctrl.wanted && modifiers.shift.pressed == modifiers.shift.wanted && modifiers.alt.pressed == modifiers.alt.wanted && modifiers.meta.pressed == modifiers.meta.wanted) { callback(e); if(!opt['propagate']) { //Stop the event //e.cancelBubble is supported by IE - this will kill the bubbling process. e.cancelBubble = true; e.returnValue = false; //e.stopPropagation works in Firefox. if (e.stopPropagation) { e.stopPropagation(); e.preventDefault(); } return false; } } } this.all_shortcuts[shortcut_combination] = { 'callback':func, 'target':ele, 'event': opt['type'] }; //Attach the function with the event if(ele.addEventListener) ele.addEventListener(opt['type'], func, false); else if(ele.attachEvent) ele.attachEvent('on'+opt['type'], func); else ele['on'+opt['type']] = func; }, //Remove the shortcut - just specify the shortcut and I will remove the binding 'remove':function(shortcut_combination) { shortcut_combination = shortcut_combination.toLowerCase(); var binding = this.all_shortcuts[shortcut_combination]; delete(this.all_shortcuts[shortcut_combination]) if(!binding) return; var type = binding['event']; var ele = binding['target']; var callback = binding['callback']; if(ele.detachEvent) ele.detachEvent('on'+type, callback); else if(ele.removeEventListener) ele.removeEventListener(type, callback, false); else ele['on'+type] = false; } }; /*! * Copyright (c) 2010 Chris O'Hara <cohara87@gmail.com> * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // follow Universal Module Definition (UMD) pattern for defining module as AMD, CommonJS, and Browser compatible (function (root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define(['exports'], factory); } else if (typeof exports === 'object') { // CommonJS factory(exports); } else { // Browser globals // N.B. Here is a slight difference to regular UMD as the current API for node-validator in browser adds each export directly to the window // rather than to a namespaced object such as window.nodeValidator, which would be better practice, but would break backwards compatibility // as such unable to use build tools like grunt-umd factory(root); } }(this, function(exports) { var entities = { '&nbsp;': '\u00a0', '&iexcl;': '\u00a1', '&cent;': '\u00a2', '&pound;': '\u00a3', '&curren;': '\u20ac', '&yen;': '\u00a5', '&brvbar;': '\u0160', '&sect;': '\u00a7', '&uml;': '\u0161', '&copy;': '\u00a9', '&ordf;': '\u00aa', '&laquo;': '\u00ab', '&not;': '\u00ac', '&shy;': '\u00ad', '&reg;': '\u00ae', '&macr;': '\u00af', '&deg;': '\u00b0', '&plusmn;': '\u00b1', '&sup2;': '\u00b2', '&sup3;': '\u00b3', '&acute;': '\u017d', '&micro;': '\u00b5', '&para;': '\u00b6', '&middot;': '\u00b7', '&cedil;': '\u017e', '&sup1;': '\u00b9', '&ordm;': '\u00ba', '&raquo;': '\u00bb', '&frac14;': '\u0152', '&frac12;': '\u0153', '&frac34;': '\u0178', '&iquest;': '\u00bf', '&Agrave;': '\u00c0', '&Aacute;': '\u00c1', '&Acirc;': '\u00c2', '&Atilde;': '\u00c3', '&Auml;': '\u00c4', '&Aring;': '\u00c5', '&AElig;': '\u00c6', '&Ccedil;': '\u00c7', '&Egrave;': '\u00c8', '&Eacute;': '\u00c9', '&Ecirc;': '\u00ca', '&Euml;': '\u00cb', '&Igrave;': '\u00cc', '&Iacute;': '\u00cd', '&Icirc;': '\u00ce', '&Iuml;': '\u00cf', '&ETH;': '\u00d0', '&Ntilde;': '\u00d1', '&Ograve;': '\u00d2', '&Oacute;': '\u00d3', '&Ocirc;': '\u00d4', '&Otilde;': '\u00d5', '&Ouml;': '\u00d6', '&times;': '\u00d7', '&Oslash;': '\u00d8', '&Ugrave;': '\u00d9', '&Uacute;': '\u00da', '&Ucirc;': '\u00db', '&Uuml;': '\u00dc', '&Yacute;': '\u00dd', '&THORN;': '\u00de', '&szlig;': '\u00df', '&agrave;': '\u00e0', '&aacute;': '\u00e1', '&acirc;': '\u00e2', '&atilde;': '\u00e3', '&auml;': '\u00e4', '&aring;': '\u00e5', '&aelig;': '\u00e6', '&ccedil;': '\u00e7', '&egrave;': '\u00e8', '&eacute;': '\u00e9', '&ecirc;': '\u00ea', '&euml;': '\u00eb', '&igrave;': '\u00ec', '&iacute;': '\u00ed', '&icirc;': '\u00ee', '&iuml;': '\u00ef', '&eth;': '\u00f0', '&ntilde;': '\u00f1', '&ograve;': '\u00f2', '&oacute;': '\u00f3', '&ocirc;': '\u00f4', '&otilde;': '\u00f5', '&ouml;': '\u00f6', '&divide;': '\u00f7', '&oslash;': '\u00f8', '&ugrave;': '\u00f9', '&uacute;': '\u00fa', '&ucirc;': '\u00fb', '&uuml;': '\u00fc', '&yacute;': '\u00fd', '&thorn;': '\u00fe', '&yuml;': '\u00ff', '&quot;': '\u0022', '&lt;': '\u003c', '&gt;': '\u003e', '&apos;': '\u0027', '&minus;': '\u2212', '&circ;': '\u02c6', '&tilde;': '\u02dc', '&Scaron;': '\u0160', '&lsaquo;': '\u2039', '&OElig;': '\u0152', '&lsquo;': '\u2018', '&rsquo;': '\u2019', '&ldquo;': '\u201c', '&rdquo;': '\u201d', '&bull;': '\u2022', '&ndash;': '\u2013', '&mdash;': '\u2014', '&trade;': '\u2122', '&scaron;': '\u0161', '&rsaquo;': '\u203a', '&oelig;': '\u0153', '&Yuml;': '\u0178', '&fnof;': '\u0192', '&Alpha;': '\u0391', '&Beta;': '\u0392', '&Gamma;': '\u0393', '&Delta;': '\u0394', '&Epsilon;': '\u0395', '&Zeta;': '\u0396', '&Eta;': '\u0397', '&Theta;': '\u0398', '&Iota;': '\u0399', '&Kappa;': '\u039a', '&Lambda;': '\u039b', '&Mu;': '\u039c', '&Nu;': '\u039d', '&Xi;': '\u039e', '&Omicron;': '\u039f', '&Pi;': '\u03a0', '&Rho;': '\u03a1', '&Sigma;': '\u03a3', '&Tau;': '\u03a4', '&Upsilon;': '\u03a5', '&Phi;': '\u03a6', '&Chi;': '\u03a7', '&Psi;': '\u03a8', '&Omega;': '\u03a9', '&alpha;': '\u03b1', '&beta;': '\u03b2', '&gamma;': '\u03b3', '&delta;': '\u03b4', '&epsilon;': '\u03b5', '&zeta;': '\u03b6', '&eta;': '\u03b7', '&theta;': '\u03b8', '&iota;': '\u03b9', '&kappa;': '\u03ba', '&lambda;': '\u03bb', '&mu;': '\u03bc', '&nu;': '\u03bd', '&xi;': '\u03be', '&omicron;': '\u03bf', '&pi;': '\u03c0', '&rho;': '\u03c1', '&sigmaf;': '\u03c2', '&sigma;': '\u03c3', '&tau;': '\u03c4', '&upsilon;': '\u03c5', '&phi;': '\u03c6', '&chi;': '\u03c7', '&psi;': '\u03c8', '&omega;': '\u03c9', '&thetasym;': '\u03d1', '&upsih;': '\u03d2', '&piv;': '\u03d6', '&ensp;': '\u2002', '&emsp;': '\u2003', '&thinsp;': '\u2009', '&zwnj;': '\u200c', '&zwj;': '\u200d', '&lrm;': '\u200e', '&rlm;': '\u200f', '&sbquo;': '\u201a', '&bdquo;': '\u201e', '&dagger;': '\u2020', '&Dagger;': '\u2021', '&hellip;': '\u2026', '&permil;': '\u2030', '&prime;': '\u2032', '&Prime;': '\u2033', '&oline;': '\u203e', '&frasl;': '\u2044', '&euro;': '\u20ac', '&image;': '\u2111', '&weierp;': '\u2118', '&real;': '\u211c', '&alefsym;': '\u2135', '&larr;': '\u2190', '&uarr;': '\u2191', '&rarr;': '\u2192', '&darr;': '\u2193', '&harr;': '\u2194', '&crarr;': '\u21b5', '&lArr;': '\u21d0', '&uArr;': '\u21d1', '&rArr;': '\u21d2', '&dArr;': '\u21d3', '&hArr;': '\u21d4', '&forall;': '\u2200', '&part;': '\u2202', '&exist;': '\u2203', '&empty;': '\u2205', '&nabla;': '\u2207', '&isin;': '\u2208', '&notin;': '\u2209', '&ni;': '\u220b', '&prod;': '\u220f', '&sum;': '\u2211', '&lowast;': '\u2217', '&radic;': '\u221a', '&prop;': '\u221d', '&infin;': '\u221e', '&ang;': '\u2220', '&and;': '\u2227', '&or;': '\u2228', '&cap;': '\u2229', '&cup;': '\u222a', '&int;': '\u222b', '&there4;': '\u2234', '&sim;': '\u223c', '&cong;': '\u2245', '&asymp;': '\u2248', '&ne;': '\u2260', '&equiv;': '\u2261', '&le;': '\u2264', '&ge;': '\u2265', '&sub;': '\u2282', '&sup;': '\u2283', '&nsub;': '\u2284', '&sube;': '\u2286', '&supe;': '\u2287', '&oplus;': '\u2295', '&otimes;': '\u2297', '&perp;': '\u22a5', '&sdot;': '\u22c5', '&lceil;': '\u2308', '&rceil;': '\u2309', '&lfloor;': '\u230a', '&rfloor;': '\u230b', '&lang;': '\u2329', '&rang;': '\u232a', '&loz;': '\u25ca', '&spades;': '\u2660', '&clubs;': '\u2663', '&hearts;': '\u2665', '&diams;': '\u2666' }; var decode = function (str) { if (!~str.indexOf('&')) return str; //Decode literal entities for (var i in entities) { str = str.replace(new RegExp(i, 'g'), entities[i]); } //Decode hex entities str = str.replace(/&#x(0*[0-9a-f]{2,5});?/gi, function (m, code) { return String.fromCharCode(parseInt(+code, 16)); }); //Decode numeric entities str = str.replace(/&#([0-9]{2,4});?/gi, function (m, code) { return String.fromCharCode(+code); }); str = str.replace(/&amp;/g, '&'); return str; } var encode = function (str) { str = str.replace(/&/g, '&amp;'); //IE doesn't accept &apos; str = str.replace(/'/g, '&#39;'); //Encode literal entities for (var i in entities) { str = str.replace(new RegExp(entities[i], 'g'), i); } return str; } exports.entities = { encode: encode, decode: decode } //This module is adapted from the CodeIgniter framework //The license is available at http://codeigniter.com/ var never_allowed_str = { 'document.cookie': '', 'document.write': '', '.parentNode': '', '.innerHTML': '', 'window.location': '', '-moz-binding': '', '<!--': '&lt;!--', '-->': '--&gt;', '<![CDATA[': '&lt;![CDATA[' }; var never_allowed_regex = { 'javascript\\s*:': '', 'expression\\s*(\\(|&\\#40;)': '', 'vbscript\\s*:': '', 'Redirect\\s+302': '' }; var non_displayables = [ /%0[0-8bcef]/g, // url encoded 00-08, 11, 12, 14, 15 /%1[0-9a-f]/g, // url encoded 16-31 /[\x00-\x08]/g, // 00-08 /\x0b/g, /\x0c/g, // 11,12 /[\x0e-\x1f]/g // 14-31 ]; var compact_words = [ 'javascript', 'expression', 'vbscript', 'script', 'applet', 'alert', 'document', 'write', 'cookie', 'window' ]; exports.xssClean = function(str, is_image) { //Recursively clean objects and arrays if (typeof str === 'object') { for (var i in str) { str[i] = exports.xssClean(str[i]); } return str; } //Remove invisible characters str = remove_invisible_characters(str); //Protect query string variables in URLs => 901119URL5918AMP18930PROTECT8198 str = str.replace(/\&([a-z\_0-9]+)\=([a-z\_0-9]+)/i, xss_hash() + '$1=$2'); //Validate standard character entities - add a semicolon if missing. We do this to enable //the conversion of entities to ASCII later. str = str.replace(/(&\#?[0-9a-z]{2,})([\x00-\x20])*;?/i, '$1;$2'); //Validate UTF16 two byte encoding (x00) - just as above, adds a semicolon if missing. str = str.replace(/(&\#x?)([0-9A-F]+);?/i, '$1;$2'); //Un-protect query string variables str = str.replace(xss_hash(), '&'); //Decode just in case stuff like this is submitted: //<a href="http://%77%77%77%2E%67%6F%6F%67%6C%65%2E%63%6F%6D">Google</a> try { str = decodeURIComponent(str); } catch (e) { // str was not actually URI-encoded } //Convert character entities to ASCII - this permits our tests below to work reliably. //We only convert entities that are within tags since these are the ones that will pose security problems. str = str.replace(/[a-z]+=([\'\"]).*?\1/gi, function(m, match) { return m.replace(match, convert_attribute(match)); }); //Remove invisible characters again str = remove_invisible_characters(str); //Convert tabs to spaces str = str.replace('\t', ' '); //Captured the converted string for later comparison var converted_string = str; //Remove strings that are never allowed for (var i in never_allowed_str) { str = str.replace(i, never_allowed_str[i]); } //Remove regex patterns that are never allowed for (var i in never_allowed_regex) { str = str.replace(new RegExp(i, 'i'), never_allowed_regex[i]); } //Compact any exploded words like: j a v a s c r i p t // We only want to do this when it is followed by a non-word character for (var i in compact_words) { var spacified = compact_words[i].split('').join('\\s*')+'\\s*'; str = str.replace(new RegExp('('+spacified+')(\\W)', 'ig'), function(m, compat, after) { return compat.replace(/\s+/g, '') + after; }); } //Remove disallowed Javascript in links or img tags do { var original = str; if (str.match(/<a/i)) { str = str.replace(/<a\s+([^>]*?)(>|$)/gi, function(m, attributes, end_tag) { attributes = filter_attributes(attributes.replace('<','').replace('>','')); return m.replace(attributes, attributes.replace(/href=.*?(alert\(|alert&\#40;|javascript\:|charset\=|window\.|document\.|\.cookie|<script|<xss|base64\s*,)/gi, '')); }); } if (str.match(/<img/i)) { str = str.replace(/<img\s+([^>]*?)(\s?\/?>|$)/gi, function(m, attributes, end_tag) { attributes = filter_attributes(attributes.replace('<','').replace('>','')); return m.replace(attributes, attributes.replace(/src=.*?(alert\(|alert&\#40;|javascript\:|charset\=|window\.|document\.|\.cookie|<script|<xss|base64\s*,)/gi, '')); }); } if (str.match(/script/i) || str.match(/xss/i)) { str = str.replace(/<(\/*)(script|xss)(.*?)\>/gi, ''); } } while(original != str); //Remove JavaScript Event Handlers - Note: This code is a little blunt. It removes the event //handler and anything up to the closing >, but it's unlikely to be a problem. event_handlers = ['[^a-z_\-]on\\w*']; //Adobe Photoshop puts XML metadata into JFIF images, including namespacing, //so we have to allow this for images if (!is_image) { event_handlers.push('xmlns'); } str = str.replace(new RegExp("<([^><]+?)("+event_handlers.join('|')+")(\\s*=\\s*[^><]*)([><]*)", 'i'), '<$1$4'); //Sanitize naughty HTML elements //If a tag containing any of the words in the list //below is found, the tag gets converted to entities. //So this: <blink> //Becomes: &lt;blink&gt; naughty = 'alert|applet|audio|basefont|base|behavior|bgsound|blink|body|embed|expression|form|frameset|frame|head|html|ilayer|iframe|input|isindex|layer|link|meta|object|plaintext|style|script|textarea|title|video|xml|xss'; str = str.replace(new RegExp('<(/*\\s*)('+naughty+')([^><]*)([><]*)', 'gi'), function(m, a, b, c, d) { return '&lt;' + a + b + c + d.replace('>','&gt;').replace('<','&lt;'); }); //Sanitize naughty scripting elements Similar to above, only instead of looking for //tags it looks for PHP and JavaScript commands that are disallowed. Rather than removing the //code, it simply converts the parenthesis to entities rendering the code un-executable. //For example: eval('some code') //Becomes: eval&#40;'some code'&#41; str = str.replace(/(alert|cmd|passthru|eval|exec|expression|system|fopen|fsockopen|file|file_get_contents|readfile|unlink)(\s*)\((.*?)\)/gi, '$1$2&#40;$3&#41;'); //This adds a bit of extra precaution in case something got through the above filters for (var i in never_allowed_str) { str = str.replace(i, never_allowed_str[i]); } for (var i in never_allowed_regex) { str = str.replace(new RegExp(i, 'i'), never_allowed_regex[i]); } //Images are handled in a special way if (is_image && str !== converted_string) { throw new Error('Image may contain XSS'); } return str; } function remove_invisible_characters(str) { for (var i in non_displayables) { str = str.replace(non_displayables[i], ''); } return str; } function xss_hash() { //TODO: Create a random hash return '!*$^#(@*#&'; } function convert_attribute(str) { return str.replace('>','&gt;').replace('<','&lt;').replace('\\','\\\\'); } //Filter Attributes - filters tag attributes for consistency and safety function filter_attributes(str) { var comments = /\/\*.*?\*\//g; return str.replace(/\s*[a-z-]+\s*=\s*'[^']*'/gi, function (m) { return m.replace(comments, ''); }).replace(/\s*[a-z-]+\s*=\s*"[^"]*"/gi, function (m) { return m.replace(comments, ''); }).replace(/\s*[a-z-]+\s*=\s*[^\s]+/gi, function (m) { return m.replace(comments, ''); }); } var Validator = exports.Validator = function() {} Validator.prototype.check = function(str, fail_msg) { this.str = typeof( str ) === 'undefined' || str === null || (isNaN(str) && str.length === undefined) ? '' : str+''; this.msg = fail_msg; this._errors = this._errors || []; return this; } function internal_is_ipv4(str) { if (/^(\d?\d?\d)\.(\d?\d?\d)\.(\d?\d?\d)\.(\d?\d?\d)$/.test(str)) { var parts = str.split('.').sort(); // no need to check for < 0 as regex won't match in that case if (parts[3] > 255) { return false; } return true; } return false; } function internal_is_ipv6(str) { if (/^::|^::1|^([a-fA-F0-9]{1,4}::?){1,7}([a-fA-F0-9]{1,4})$/.test(str)) { return true; } return false; } //Create some aliases - may help code readability Validator.prototype.validate = Validator.prototype.check; Validator.prototype.assert = Validator.prototype.check; Validator.prototype.error = function(msg) { throw new Error(msg); } function toDate(date) { if (date instanceof Date) { return date; } var intDate = Date.parse(date); if (isNaN(intDate)) { return null; } return new Date(intDate); } Validator.prototype.isAfter = function(date) { date = date || new Date(); var origDate = toDate(this.str) , compDate = toDate(date); if (!(origDate && compDate && origDate >= compDate)) { return this.error(this.msg || 'Invalid date'); } return this; }; Validator.prototype.isBefore = function(date) { date = date || new Date(); var origDate = toDate(this.str) , compDate = toDate(date); if (!(origDate && compDate && origDate <= compDate)) { return this.error(this.msg || 'Invalid date'); } return this; }; Validator.prototype.isEmail = function() { if (!this.str.match(/^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!\.)){0,61}[a-zA-Z0-9]?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!$)){0,61}[a-zA-Z0-9]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$/)) { return this.error(this.msg || 'Invalid email'); } return this; } //Will work against Visa, MasterCard, American Express, Discover, Diners Club, and JCB card numbering formats Validator.prototype.isCreditCard = function() { this.str = this.str.replace(/[^0-9]+/g, ''); //remove all dashes, spaces, etc. if (!this.str.match(/^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11})$/)) { return this.error(this.msg || 'Invalid credit card'); } // Doing Luhn check var sum = 0; var digit; var tmpNum; var shouldDouble = false; for (var i = this.length - 1; i >= 0; i--) { digit = this.substring(i, (i + 1)); tmpNum = parseInt(digit, 10); if (shouldDouble) { tmpNum *= 2; if (tmpNum >= 10) { sum += ((tmpNum % 10) + 1); } else { sum += tmpNum; } } else { sum += tmpNum; } if (shouldDouble) { shouldDouble = false; } else { shouldDouble = true; } } if ((sum % 10) !== 0) { return this.error(this.msg || 'Invalid credit card'); } return this; } Validator.prototype.isUrl = function() { if (!this.str.match(/^(?!mailto:)(?:(?:https?|ftp):\/\/)?(?:\S+(?::\S*)?@)?(?:(?:(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))|localhost)(?::\d{2,5})?(?:\/[^\s]*)?$/i) || this.str.length > 2083) { return this.error(this.msg || 'Invalid URL'); } return this; } Validator.prototype.isIPv4 = function() { if (internal_is_ipv4(this.str)) { return this; } return this.error(this.msg || 'Invalid IP'); } Validator.prototype.isIPv6 = function() { if (internal_is_ipv6(this.str)) { return this; } return this.error(this.msg || 'Invalid IP'); } Validator.prototype.isIP = function() { if (internal_is_ipv4(this.str) || internal_is_ipv6(this.str)) { return this; } return this.error(this.msg || 'Invalid IP'); } Validator.prototype.isAlpha = function() { if (!this.str.match(/^[a-zA-Z]+$/)) { return this.error(this.msg || 'Invalid characters'); } return this; } Validator.prototype.isAlphanumeric = function() { if (!this.str.match(/^[a-zA-Z0-9]+$/)) { return this.error(this.msg || 'Invalid characters'); } return this; } Validator.prototype.isNumeric = function() { if (!this.str.match(/^-?[0-9]+$/)) { return this.error(this.msg || 'Invalid number'); } return this; } Validator.prototype.isHexadecimal = function() { if (!this.str.match(/^[0-9a-fA-F]+$/)) { return this.error(this.msg || 'Invalid hexadecimal'); } return this; } Validator.prototype.isHexColor = function() { if (!this.str.match(/^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/)) { return this.error(this.msg || 'Invalid hexcolor'); } return this; } Validator.prototype.isLowercase = function() { if (this.str !== this.str.toLowerCase()) { return this.error(this.msg || 'Invalid characters'); } return this; } Validator.prototype.isUppercase = function() { if (this.str !== this.str.toUpperCase()) { return this.error(this.msg || 'Invalid characters'); } return this; } Validator.prototype.isInt = function() { if (!this.str.match(/^(?:-?(?:0|[1-9][0-9]*))$/)) { return this.error(this.msg || 'Invalid integer'); } return this; } Validator.prototype.isDecimal = function() { if (!this.str.match(/^(?:-?(?:0|[1-9][0-9]*))?(?:\.[0-9]*)?$/)) { return this.error(this.msg || 'Invalid decimal'); } return this; } Validator.prototype.isDivisibleBy = function(n) { return (parseFloat(this.str) % parseInt(n, 10)) === 0; } Validator.prototype.isFloat = function() { return this.isDecimal(); } Validator.prototype.notNull = function() { if (this.str === '') { return this.error(this.msg || 'String is empty'); } return this; } Validator.prototype.isNull = function() { if (this.str !== '') { return this.error(this.msg || 'String is not empty'); } return this; } Validator.prototype.notEmpty = function() { if (this.str.match(/^[\s\t\r\n]*$/)) { return this.error(this.msg || 'String is whitespace'); } return this; } Validator.prototype.equals = function(equals) { if (this.str != equals) { return this.error(this.msg || 'Not equal'); } return this; } Validator.prototype.contains = function(str) { if (this.str.indexOf(str) === -1 || !str) { return this.error(this.msg || 'Invalid characters'); } return this; } Validator.prototype.notContains = function(str) { if (this.str.indexOf(str) >= 0) { return this.error(this.msg || 'Invalid characters'); } return this; } Validator.prototype.regex = Validator.prototype.is = function(pattern, modifiers) { if (Object.prototype.toString.call(pattern).slice(8, -1) !== 'RegExp') { pattern = new RegExp(pattern, modifiers); } if (! this.str.match(pattern)) { return this.error(this.msg || 'Invalid characters'); } return this; } Validator.prototype.notRegex = Validator.prototype.not = function(pattern, modifiers) { if (Object.prototype.toString.call(pattern).slice(8, -1) !== 'RegExp') { pattern = new RegExp(pattern, modifiers); } if (this.str.match(pattern)) { this.error(this.msg || 'Invalid characters'); } return this; } Validator.prototype.len = function(min, max) { if (this.str.length < min) { return this.error(this.msg || 'String is too small'); } if (typeof max !== undefined && this.str.length > max) { return this.error(this.msg || 'String is too large'); } return this; } //Thanks to github.com/sreuter for the idea. Validator.prototype.isUUID = function(version) { var pattern; if (version == 3 || version == 'v3') { pattern = /[0-9A-F]{8}-[0-9A-F]{4}-3[0-9A-F]{3}-[0-9A-F]{4}-[0-9A-F]{12}$/i; } else if (version == 4 || version == 'v4') { pattern = /[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i; } else if (version == 5 || version == 'v5') { pattern = /^[0-9A-F]{8}-[0-9A-F]{4}-5[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i; } else { pattern = /[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i; } if (!this.str.match(pattern)) { return this.error(this.msg || 'Not a UUID'); } return this; } Validator.prototype.isUUIDv3 = function() { return this.isUUID(3); } Validator.prototype.isUUIDv4 = function() { return this.isUUID(4); } Validator.prototype.isUUIDv5 = function() { return this.isUUID(5); } Validator.prototype.isDate = function() { var intDate = Date.parse(this.str); if (isNaN(intDate)) { return this.error(this.msg || 'Not a date'); } return this; } Validator.prototype.isIn = function(options) { if (options && typeof options.indexOf === 'function') { if (!~options.indexOf(this.str)) { return this.error(this.msg || 'Unexpected value'); } return this; } else { return this.error(this.msg || 'Invalid in() argument'); } } Validator.prototype.notIn = function(options) { if (options && typeof options.indexOf === 'function') { if (options.indexOf(this.str) !== -1) { return this.error(this.msg || 'Unexpected value'); } return this; } else { return this.error(this.msg || 'Invalid notIn() argument'); } } Validator.prototype.min = function(val) { var number = parseFloat(this.str); if (!isNaN(number) && number < val) { return this.error(this.msg || 'Invalid number'); } return this; } Validator.prototype.max = function(val) { var number = parseFloat(this.str); if (!isNaN(number) && number > val) { return this.error(this.msg || 'Invalid number'); } return this; } var Filter = exports.Filter = function() {} var whitespace = '\\r\\n\\t\\s'; Filter.prototype.modify = function(str) { this.str = str; } //Create some aliases - may help code readability Filter.prototype.convert = Filter.prototype.sanitize = function(str) { this.str = str == null ? '' : str + ''; return this; } Filter.prototype.xss = function(is_image) { this.modify(exports.xssClean(this.str, is_image)); return this.str; } Filter.prototype.entityDecode = function() { this.modify(decode(this.str)); return this.str; } Filter.prototype.entityEncode = function() { this.modify(encode(this.str)); return this.str; } Filter.prototype.escape = function() { this.modify(this.str.replace(/&/g, '&amp;') .replace(/"/g, '&quot;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;')); return this.str; }; Filter.prototype.ltrim = function(chars) { chars = chars || whitespace; this.modify(this.str.replace(new RegExp('^['+chars+']+', 'g'), '')); return this.str; } Filter.prototype.rtrim = function(chars) { chars = chars || whitespace; this.modify(this.str.replace(new RegExp('['+chars+']+$', 'g'), '')); return this.str; } Filter.prototype.trim = function(chars) { chars = chars || whitespace; this.modify(this.str.replace(new RegExp('^['+chars+']+|['+chars+']+$', 'g'), '')); return this.str; } Filter.prototype.ifNull = function(replace) { if (!this.str || this.str === '') { this.modify(replace); } return this.str; } Filter.prototype.toFloat = function() { this.modify(parseFloat(this.str)); return this.str; } Filter.prototype.toInt = function(radix) { radix = radix || 10; this.modify(parseInt(this.str, radix)); return this.str; } //Any strings with length > 0 (except for '0' and 'false') are considered true, //all other strings are false Filter.prototype.toBoolean = function() { if (!this.str || this.str == '0' || this.str == 'false' || this.str == '') { this.modify(false); } else { this.modify(true); } return this.str; } //String must be equal to '1' or 'true' to be considered true, all other strings //are false Filter.prototype.toBooleanStrict = function() { if (this.str == '1' || this.str == 'true') { this.modify(true); } else { this.modify(false); } return this.str; } //Quick access methods exports.sanitize = exports.convert = function(str) { var filter = new exports.Filter(); return filter.sanitize(str); } exports.check = exports.validate = exports.assert = function(str, fail_msg) { var validator = new exports.Validator(); return validator.check(str, fail_msg); } return exports; })); /** * Countable is a script to allow for live paragraph-, word- and character- * counting on an HTML element. * * @author Sacha Schmid (<https://github.com/RadLikeWhoa>) * @version 2.0.0 * @license MIT * @see <http://radlikewhoa.github.io/Countable/> */ /** * Note: For the purpose of this internal documentation, arguments of the type * {Nodes} are to be interpreted as either {NodeList} or {Element}. */ ;(function (global) { 'use strict' /** * @private * * `_liveElements` holds all elements that have the live-counting * functionality bound to them. * * `_event` holds the event to handle the live counting, based on the * browser's capabilities. */ var _liveElements = [], _event = 'oninput' in document ? 'input' : 'keyup' /** * `String.trim()` polyfill for non-supporting browsers. This is the * recommended polyfill on MDN. * * @see <http://goo.gl/uYveB> * @see <http://goo.gl/xjIxJ> * * @return {String} The original string with leading and trailing whitespace * removed. */ if (!String.prototype.trim) { String.prototype.trim = function () { return this.replace(/^\s+|\s+$/g, '') } } /** * `ucs2decode` function from the punycode.js library. * * Creates an array containing the decimal code points of each Unicode * character in the string. While JavaScript uses UCS-2 internally, this * function will convert a pair of surrogate halves (each of which UCS-2 * exposes as separate characters) into a single code point, matching * UTF-16. * * @see <http://goo.gl/8M09r> * @see <http://goo.gl/u4UUC> * * @param {String} string The Unicode input string (UCS-2). * * @return {Array} The new array of code points. */ function _decode (string) { var output = [], counter = 0, length = string.length, value, extra while (counter < length) { value = string.charCodeAt(counter++) if ((value & 0xF800) == 0xD800 && counter < length) { // High surrogate, and there is a next character. extra = string.charCodeAt(counter++) if ((extra & 0xFC00) == 0xDC00) { // Low surrogate. output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000) } else { output.push(value, extra) } } else { output.push(value) } } return output } /** * `_validateArguments` validates the arguments given to each function call. * Errors are logged to the console as warnings, but Countable fails silently. * * @private * * @param {Nodes} elements The (collection of) element(s) to * validate. * * @param {Function} callback The callback function to validate. * * @return {Boolean} Returns whether all arguments are vaild. */ function _validateArguments (elements, callback) { var elementsValid = elements && ((Object.prototype.toString.call(elements) === '[object NodeList]' && elements.length) || (elements.nodeType === 1)), callbackValid = callback && typeof callback === 'function' if ('console' in window && 'warn' in console) { if (!elementsValid) console.warn('Countable: No valid elements were found') if (!callbackValid) console.warn('Countable: "' + callback + '" is not a valid callback function') } return elementsValid && callbackValid } /** * `_extendDefaults` is a function to extend a set of default options with the * ones given in the function call. Available options are described below. * * {Boolean} hardReturns Use two returns to seperate a paragraph instead of * one. * {Boolean} stripTags Strip HTML tags before counting the values. * * @private * * @param {Object} options Countable allows the options described above. * They can be used in a function call to override * the default behaviour. * * @return {Object} The new options object. */ function _extendDefaults (options) { var defaults = { hardReturns: false, stripTags: false } for (var prop in options) { if (defaults.hasOwnProperty(prop)) defaults[prop] = options[prop] } return defaults } /** * `_count` trims an element's value, optionally strips HTML tags and counts * paragraphs, words, characters and characters plus spaces. * * @private * * @param {Element} element The element whose value is to be counted. * * @param {Object} options The options to use for the counting. * * @return {Object} The object containing the number of paragraphs, * words, characters and characters plus spaces. */ function _count (element, options) { var original = 'value' in element ? element.value : element.innerText || element.textContent, temp, trimmed /** * The initial implementation to allow for HTML tags stripping was created * @craniumslows while the current one was created by @Rob--W. * * @see <http://goo.gl/Exmlr> * @see <http://goo.gl/gFQQh> */ if (options.stripTags) original = original.replace(/<\/?[a-z][^>]*>/gi, '') trimmed = original.trim() /** * Most of the performance improvements are based on the works of @epmatsw. * * @see <http://goo.gl/SWOLB> */ return { paragraphs: trimmed ? (trimmed.match(options.hardReturns ? /\n{2,}/g : /\n+/g) || []).length + 1 : 0, words: trimmed ? (trimmed.replace(/['";:,.?¿\-!¡]+/g, '').match(/\S+/g) || []).length : 0, characters: trimmed ? _decode(trimmed.replace(/\s/g, '')).length : 0, all: _decode(original.replace(/[\n\r]/g, '')).length } } /** * `_loop` is a helper function to iterate over a collection, e.g. a NodeList * or an Array. The callback receives the current element as the single * parameter. * * @private * * @param {Array} which The collection to iterate over. * * @param {Function} callback The callback function to call on each * iteration. */ function _loop (which, callback) { var len = which.length if (typeof len !== 'undefined') { while (len--) { callback(which[len]) } } else { callback(which) } } /** * This is the main object that will later be exposed to other scripts. It * holds all the public methods that can be used to enable the Countable * functionality. */ var Countable = { /** * The `live` method binds the counting handler to all given elements. The * event is either `oninput` or `onkeydown`, based on the capabilities of * the browser. * * @param {Nodes} elements All elements that should receive the * Countable functionality. * * @param {Function} callback The callback to fire whenever the * element's value changes. The callback is * called with the relevant element bound to * `this` and the counted values as the * single parameter. * * @param {Object} [options] An object to modify Countable's * behaviour. Refer to `_extendDefaults` for * a list of available options. * * @return {Object} Returns the Countable object to allow for chaining. */ live: function (elements, callback, options) { var ops = _extendDefaults(options), bind = function (element) { var handler = function () { callback.call(element, _count(element, ops)) } _liveElements.push({ element: element, handler: handler }) handler() if (element.addEventListener) { element.addEventListener(_event, handler, false) } else if (element.attachEvent) { element.attachEvent('on' + _event, handler) } } if (!_validateArguments(elements, callback)) return if (elements.length) { _loop(elements, bind) } else { bind(elements) } return this }, /** * The `die` method removes the Countable functionality from all given * elements. * * @param {Nodes} elements All elements whose Countable functionality * should be unbound. * * @return {Object} Returns the Countable object to allow for chaining. */ die: function (elements) { if (!_validateArguments(elements, function () {})) return _loop(elements, function (element) { var liveElement _loop(_liveElements, function (live) { if (live.element === element) liveElement = live }) if (!liveElement) return if (element.removeEventListener) { element.removeEventListener(_event, liveElement.handler, false) } else if (element.detachEvent) { element.detachEvent('on' + _event, liveElement.handler) } _liveElements.splice(_liveElements.indexOf(liveElement), 1) }) return this }, /** * The `once` method works mostly like the `live` method, but no events are * bound, the functionality is only executed once. * * @param {Nodes} elements All elements that should receive the * Countable functionality. * * @param {Function} callback The callback to fire whenever the * element's value changes. The callback is * called with the relevant element bound to * `this` and the counted values as the * single parameter. * * @param {Object} [options] An object to modify Countable's * behaviour. Refer to `_extendDefaults` * for a list of available options. * * @return {Object} Returns the Countable object to allow for chaining. */ once: function (elements, callback, options) { if (!_validateArguments(elements, callback)) return _loop(elements, function (element) { callback.call(element, _count(element, _extendDefaults(options))) }) return this }, /** * The `enabled` method checks if the live-counting functionality is bound * to an element. * * @param {Element} element A single Element. * * @return {Boolean} A boolean value representing whether Countable * functionality is bound to the given element. */ enabled: function (element) { var isEnabled = false if (element && element.nodeType === 1) { _loop(_liveElements, function (live) { if (live.element === element) isEnabled = true }) } return isEnabled } } /** * Expose Countable depending on the module system used across the * application. (Node / CommonJS, AMD, global) */ if (typeof exports === 'object') { module.exports = Countable } else if (typeof define === 'function' && define.amd) { define(function () { return Countable }) } else { global.Countable = Countable } }(this)) /* * To Title Case 2.0.1 – http://individed.com/code/to-title-case/ * Copyright © 2008–2012 David Gouch. Licensed under the MIT License. */ String.prototype.toTitleCase = function () { var smallWords = /^(a|an|and|as|at|but|by|en|for|if|in|of|on|or|the|to|vs?\.?|via)$/i; return this.replace(/([^\W_]+[^\s-]*) */g, function (match, p1, index, title) { if (index > 0 && index + p1.length !== title.length && p1.search(smallWords) > -1 && title.charAt(index - 2) !== ":" && title.charAt(index - 1).search(/[^\s-]/) < 0) { return match.toLowerCase(); } if (p1.substr(1).search(/[A-Z]|\../) > -1) { return match; } return match.charAt(0).toUpperCase() + match.substr(1); }); }; /*! * Packery PACKAGED v1.0.6 * bin-packing layout library * http://packery.metafizzy.co * * Commercial use requires one-time purchase of a commercial license * http://packery.metafizzy.co/license.html * * Non-commercial use is licensed under the MIT License * * Copyright 2013 Metafizzy */ (function(t){"use strict";function e(t){return RegExp("(^|\\s+)"+t+"(\\s+|$)")}function i(t,e){var i=n(t,e)?r:o;i(t,e)}var n,o,r;"classList"in document.documentElement?(n=function(t,e){return t.classList.contains(e)},o=function(t,e){t.classList.add(e)},r=function(t,e){t.classList.remove(e)}):(n=function(t,i){return e(i).test(t.className)},o=function(t,e){n(t,e)||(t.className=t.className+" "+e)},r=function(t,i){t.className=t.className.replace(e(i)," ")});var s={hasClass:n,addClass:o,removeClass:r,toggleClass:i,has:n,add:o,remove:r,toggle:i};"function"==typeof define&&define.amd?define(s):t.classie=s})(window),function(t){"use strict";var e=document.documentElement,i=function(){};e.addEventListener?i=function(t,e,i){t.addEventListener(e,i,!1)}:e.attachEvent&&(i=function(e,i,n){e[i+n]=n.handleEvent?function(){var e=t.event;e.target=e.target||e.srcElement,n.handleEvent.call(n,e)}:function(){var i=t.event;i.target=i.target||i.srcElement,n.call(e,i)},e.attachEvent("on"+i,e[i+n])});var n=function(){};e.removeEventListener?n=function(t,e,i){t.removeEventListener(e,i,!1)}:e.detachEvent&&(n=function(t,e,i){t.detachEvent("on"+e,t[e+i]);try{delete t[e+i]}catch(n){t[e+i]=void 0}});var o={bind:i,unbind:n};"function"==typeof define&&define.amd?define(o):t.eventie=o}(this),function(t){"use strict";function e(t){"function"==typeof t&&(e.isReady?t():r.push(t))}function i(t){var i="readystatechange"===t.type&&"complete"!==o.readyState;if(!e.isReady&&!i){e.isReady=!0;for(var n=0,s=r.length;s>n;n++){var a=r[n];a()}}}function n(n){return n.bind(o,"DOMContentLoaded",i),n.bind(o,"readystatechange",i),n.bind(t,"load",i),e}var o=t.document,r=[];e.isReady=!1,"function"==typeof define&&define.amd?define(["eventie"],n):t.docReady=n(t.eventie)}(this),function(t){"use strict";function e(){}function i(t,e){if(o)return e.indexOf(t);for(var i=e.length;i--;)if(e[i]===t)return i;return-1}var n=e.prototype,o=Array.prototype.indexOf?!0:!1;n._getEvents=function(){return this._events||(this._events={})},n.getListeners=function(t){var e,i,n=this._getEvents();if("object"==typeof t){e={};for(i in n)n.hasOwnProperty(i)&&t.test(i)&&(e[i]=n[i])}else e=n[t]||(n[t]=[]);return e},n.getListenersAsObject=function(t){var e,i=this.getListeners(t);return i instanceof Array&&(e={},e[t]=i),e||i},n.addListener=function(t,e){var n,o=this.getListenersAsObject(t);for(n in o)o.hasOwnProperty(n)&&-1===i(e,o[n])&&o[n].push(e);return this},n.on=n.addListener,n.defineEvent=function(t){return this.getListeners(t),this},n.defineEvents=function(t){for(var e=0;t.length>e;e+=1)this.defineEvent(t[e]);return this},n.removeListener=function(t,e){var n,o,r=this.getListenersAsObject(t);for(o in r)r.hasOwnProperty(o)&&(n=i(e,r[o]),-1!==n&&r[o].splice(n,1));return this},n.off=n.removeListener,n.addListeners=function(t,e){return this.manipulateListeners(!1,t,e)},n.removeListeners=function(t,e){return this.manipulateListeners(!0,t,e)},n.manipulateListeners=function(t,e,i){var n,o,r=t?this.removeListener:this.addListener,s=t?this.removeListeners:this.addListeners;if("object"!=typeof e||e instanceof RegExp)for(n=i.length;n--;)r.call(this,e,i[n]);else for(n in e)e.hasOwnProperty(n)&&(o=e[n])&&("function"==typeof o?r.call(this,n,o):s.call(this,n,o));return this},n.removeEvent=function(t){var e,i=typeof t,n=this._getEvents();if("string"===i)delete n[t];else if("object"===i)for(e in n)n.hasOwnProperty(e)&&t.test(e)&&delete n[e];else delete this._events;return this},n.emitEvent=function(t,e){var i,n,o,r=this.getListenersAsObject(t);for(n in r)if(r.hasOwnProperty(n))for(i=r[n].length;i--;)o=e?r[n][i].apply(null,e):r[n][i](),o===!0&&this.removeListener(t,r[n][i]);return this},n.trigger=n.emitEvent,n.emit=function(t){var e=Array.prototype.slice.call(arguments,1);return this.emitEvent(t,e)},"function"==typeof define&&define.amd?define(function(){return e}):t.EventEmitter=e}(this),function(t){"use strict";function e(t){if(t){if("string"==typeof n[t])return t;t=t.charAt(0).toUpperCase()+t.slice(1);for(var e,o=0,r=i.length;r>o;o++)if(e=i[o]+t,"string"==typeof n[e])return e}}var i="Webkit Moz ms Ms O".split(" "),n=document.documentElement.style;"function"==typeof define&&define.amd?define(function(){return e}):t.getStyleProperty=e}(window),function(t){"use strict";function e(t){var e=parseFloat(t),i=-1===t.indexOf("%")&&!isNaN(e);return i&&e}function i(){for(var t={width:0,height:0,innerWidth:0,innerHeight:0,outerWidth:0,outerHeight:0},e=0,i=s.length;i>e;e++){var n=s[e];t[n]=0}return t}function n(t){function n(t){if("object"==typeof t&&t.nodeType){var n=r(t);if("none"===n.display)return i();var h={};h.width=t.offsetWidth,h.height=t.offsetHeight;for(var p=h.isBorderBox=!(!a||!n[a]||"border-box"!==n[a]),c=0,u=s.length;u>c;c++){var d=s[c],l=n[d],f=parseFloat(l);h[d]=isNaN(f)?0:f}var m=h.paddingLeft+h.paddingRight,y=h.paddingTop+h.paddingBottom,g=h.marginLeft+h.marginRight,v=h.marginTop+h.marginBottom,x=h.borderLeftWidth+h.borderRightWidth,E=h.borderTopWidth+h.borderBottomWidth,w=p&&o,S=e(n.width);S!==!1&&(h.width=S+(w?0:m+x));var b=e(n.height);return b!==!1&&(h.height=b+(w?0:y+E)),h.innerWidth=h.width-(m+x),h.innerHeight=h.height-(y+E),h.outerWidth=h.width+g,h.outerHeight=h.height+v,h}}var o,a=t("boxSizing");return function(){if(a){var t=document.createElement("div");t.style.width="200px",t.style.padding="1px 2px 3px 4px",t.style.borderStyle="solid",t.style.borderWidth="1px 2px 3px 4px",t.style[a]="border-box";var i=document.body||document.documentElement;i.appendChild(t);var n=r(t);o=200===e(n.width),i.removeChild(t)}}(),n}var o=document.defaultView,r=o&&o.getComputedStyle?function(t){return o.getComputedStyle(t,null)}:function(t){return t.currentStyle},s=["paddingLeft","paddingRight","paddingTop","paddingBottom","marginLeft","marginRight","marginTop","marginBottom","borderLeftWidth","borderRightWidth","borderTopWidth","borderBottomWidth"];"function"==typeof define&&define.amd?define(["get-style-property"],n):t.getSize=n(t.getStyleProperty)}(window),function(t){"use strict";function e(){}function i(t){function i(e){e.prototype.option||(e.prototype.option=function(e){t.isPlainObject(e)&&(this.options=t.extend(!0,this.options,e))})}function o(e,i){t.fn[e]=function(o){if("string"==typeof o){for(var s=n.call(arguments,1),a=0,h=this.length;h>a;a++){var p=this[a],c=t.data(p,e);if(c)if(t.isFunction(c[o])&&"_"!==o.charAt(0)){var u=c[o].apply(c,s);if(void 0!==u)return u}else r("no such method '"+o+"' for "+e+" instance");else r("cannot call methods on "+e+" prior to initialization; "+"attempted to call '"+o+"'")}return this}return this.each(function(){var n=t.data(this,e);n?(n.option(o),n._init()):(n=new i(this,o),t.data(this,e,n))})}}if(t){var r="undefined"==typeof console?e:function(t){console.error(t)};t.bridget=function(t,e){i(e),o(t,e)}}}var n=Array.prototype.slice;"function"==typeof define&&define.amd?define(["jquery"],i):i(t.jQuery)}(window),function(t,e){"use strict";function i(t,e){return t[a](e)}function n(t){if(!t.parentNode){var e=document.createDocumentFragment();e.appendChild(t)}}function o(t,e){n(t);for(var i=t.parentNode.querySelectorAll(e),o=0,r=i.length;r>o;o++)if(i[o]===t)return!0;return!1}function r(t,e){return n(t),i(t,e)}var s,a=function(){if(e.matchesSelector)return"matchesSelector";for(var t=["webkit","moz","ms","o"],i=0,n=t.length;n>i;i++){var o=t[i],r=o+"MatchesSelector";if(e[r])return r}}();if(a){var h=document.createElement("div"),p=i(h,"div");s=p?i:r}else s=o;"function"==typeof define&&define.amd?define(function(){return s}):window.matchesSelector=s}(this,Element.prototype),function(t){"use strict";function e(t){for(var i in e.defaults)this[i]=e.defaults[i];for(i in t)this[i]=t[i]}var i=t.Packery=function(){};i.Rect=e,e.defaults={x:0,y:0,width:0,height:0},e.prototype.contains=function(t){var e=t.width||0,i=t.height||0;return this.x<=t.x&&this.y<=t.y&&this.x+this.width>=t.x+e&&this.y+this.height>=t.y+i},e.prototype.overlaps=function(t){var e=this.x+this.width,i=this.y+this.height,n=t.x+t.width,o=t.y+t.height;return n>this.x&&e>t.x&&o>this.y&&i>t.y},e.prototype.getMaximalFreeRects=function(t){if(!this.overlaps(t))return!1;var i,n=[],o=this.x+this.width,r=this.y+this.height,s=t.x+t.width,a=t.y+t.height;return this.y<t.y&&(i=new e({x:this.x,y:this.y,width:this.width,height:t.y-this.y}),n.push(i)),o>s&&(i=new e({x:s,y:this.y,width:o-s,height:this.height}),n.push(i)),r>a&&(i=new e({x:this.x,y:a,width:this.width,height:r-a}),n.push(i)),this.x<t.x&&(i=new e({x:this.x,y:this.y,width:t.x-this.x,height:this.height}),n.push(i)),n},e.prototype.canFit=function(t){return this.width>=t.width&&this.height>=t.height}}(window),function(t){"use strict";function e(t,e){this.width=t||0,this.height=e||0,this.reset()}var i=t.Packery,n=i.Rect;e.prototype.reset=function(){this.spaces=[],this.newSpaces=[];var t=new n({x:0,y:0,width:this.width,height:this.height});this.spaces.push(t)},e.prototype.pack=function(t){for(var e=0,i=this.spaces.length;i>e;e++){var n=this.spaces[e];if(n.canFit(t)){this.placeInSpace(t,n);break}}},e.prototype.placeInSpace=function(t,e){t.x=e.x,t.y=e.y,this.placed(t)},e.prototype.placed=function(t){for(var i=[],n=0,o=this.spaces.length;o>n;n++){var r=this.spaces[n],s=r.getMaximalFreeRects(t);s?i.push.apply(i,s):i.push(r)}this.spaces=i,e.mergeRects(this.spaces),this.spaces.sort(e.spaceSorterTopLeft)},e.mergeRects=function(t){for(var e=0,i=t.length;i>e;e++){var n=t[e];if(n){var o=t.slice(0);o.splice(e,1);for(var r=0,s=0,a=o.length;a>s;s++){var h=o[s],p=e>s?0:1;n.contains(h)&&(t.splice(s+p-r,1),r++)}}}return t},e.spaceSorterTopLeft=function(t,e){return t.y-e.y||t.x-e.x},e.spaceSorterLeftTop=function(t,e){return t.x-e.x||t.y-e.y},i.Packer=e}(window),function(t){"use strict";function e(t,e){for(var i in e)t[i]=e[i];return t}function i(t,e){this.element=t,this.packery=e,this.position={x:0,y:0},this.rect=new o,this.placeRect=new o,this.element.style.position="absolute"}var n=t.Packery,o=n.Rect,r=t.getSize,s=t.getStyleProperty,a=t.EventEmitter,h=document.defaultView,p=h&&h.getComputedStyle?function(t){return h.getComputedStyle(t,null)}:function(t){return t.currentStyle},c=s("transition"),u=s("transform"),d=c&&u,l=!!s("perspective"),f={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"otransitionend",transition:"transitionend"}[c],m={WebkitTransform:"-webkit-transform",MozTransform:"-moz-transform",OTransform:"-o-transform",transform:"transform"}[u];e(i.prototype,a.prototype),i.prototype.handleEvent=function(t){var e="on"+t.type;this[e]&&this[e](t)},i.prototype.getSize=function(){this.size=r(this.element)},i.prototype.css=function(t){var e=this.element.style;for(var i in t)e[i]=t[i]},i.prototype.getPosition=function(){var t=p(this.element),e=parseInt(t.left,10),i=parseInt(t.top,10);e=isNaN(e)?0:e,i=isNaN(i)?0:i;var n=this.packery.elementSize;e-=n.paddingLeft,i-=n.paddingTop,this.position.x=e,this.position.y=i};var y=l?function(t,e){return"translate3d( "+t+"px, "+e+"px, 0)"}:function(t,e){return"translate( "+t+"px, "+e+"px)"};i.prototype._transitionTo=function(t,e){this.getPosition();var i=this.position.x,n=this.position.y,o=parseInt(t,10),r=parseInt(e,10),s=o===this.position.x&&r===this.position.y;if(this.setPosition(t,e),s&&!this.isTransitioning)return this.layoutPosition(),void 0;var a=t-i,h=e-n,p={};p[m]=y(a,h),this.transition(p,this.layoutPosition)},i.prototype.goTo=function(t,e){this.setPosition(t,e),this.layoutPosition()},i.prototype.moveTo=d?i.prototype._transitionTo:i.prototype.goTo,i.prototype.setPosition=function(t,e){this.position.x=parseInt(t,10),this.position.y=parseInt(e,10)},i.prototype.layoutPosition=function(){var t=this.packery.elementSize;this.css({left:this.position.x+t.paddingLeft+"px",top:this.position.y+t.paddingTop+"px"}),this.emitEvent("layout",[this])},i.prototype._nonTransition=function(t,e){this.css(t),e&&e.call(this)},i.prototype._transition=function(t,e){this.transitionStyle=t;var i=[];for(var n in t)i.push(n);var o={};o[c+"Property"]=i.join(","),o[c+"Duration"]=this.packery.options.transitionDuration,this.element.addEventListener(f,this,!1),e&&this.on("transitionEnd",function(t){return e.call(t),!0}),this.css(o),this.css(t),this.isTransitioning=!0},i.prototype.transition=i.prototype[c?"_transition":"_nonTransition"],i.prototype.onwebkitTransitionEnd=function(t){this.ontransitionend(t)},i.prototype.onotransitionend=function(t){this.ontransitionend(t)},i.prototype.ontransitionend=function(t){if(t.target===this.element){this.onTransitionEnd&&(this.onTransitionEnd(),delete this.onTransitionEnd),this.removeTransitionStyles();var e={};for(var i in this.transitionStyle)e[i]="";this.css(e),this.element.removeEventListener(f,this,!1),delete this.transitionStyle,this.isTransitioning=!1,this.emitEvent("transitionEnd",[this])}},i.prototype.removeTransitionStyles=function(){var t={};t[c+"Property"]="",t[c+"Duration"]="",this.css(t)},i.prototype.remove=function(){var t={opacity:0};t[m]="scale(0.001)",this.transition(t,this.removeElem)},i.prototype.removeElem=function(){this.element.parentNode.removeChild(this.element),this.emitEvent("remove",[this])},i.prototype.reveal=c?function(){var t={opacity:0};t[m]="scale(0.001)",this.css(t);var e=this.element.offsetHeight,i={opacity:1};i[m]="scale(1)",this.transition(i),e=null}:function(){},i.prototype.destroy=function(){this.css({position:"",left:"",top:""})},i.prototype.dragStart=function(){this.getPosition(),this.removeTransitionStyles(),this.isTransitioning&&u&&(this.element.style[u]="none"),this.getSize(),this.isPlacing=!0,this.needsPositioning=!1,this.positionPlaceRect(this.position.x,this.position.y),this.isTransitioning=!1,this.didDrag=!1},i.prototype.dragMove=function(t,e){this.didDrag=!0;var i=this.packery.elementSize;t-=i.paddingLeft,e-=i.paddingTop,this.positionPlaceRect(t,e)},i.prototype.dragStop=function(){this.getPosition();var t=this.position.x!==this.placeRect.x,e=this.position.y!==this.placeRect.y;this.needsPositioning=t||e,this.didDrag=!1},i.prototype.positionPlaceRect=function(t,e,i){this.placeRect.x=this.getPlaceRectCoord(t,!0),this.placeRect.y=this.getPlaceRectCoord(e,!1,i)},i.prototype.getPlaceRectCoord=function(t,e,i){var n=e?"Width":"Height",o=this.size["outer"+n],r=this.packery[e?"columnWidth":"rowHeight"],s=this.packery.elementSize["inner"+n];e||(s=Math.max(s,this.packery.maxY),this.packery.rowHeight||(s-=this.packery.gutter));var a;if(r){r+=this.packery.gutter,s+=e?this.packery.gutter:0,t=Math.round(t/r);var h=Math[e?"floor":"ceil"](s/r);h-=Math.ceil(o/r),a=h}else a=s-o;return t=i?t:Math.min(t,a),t*=r||1,Math.max(0,t)},i.prototype.copyPlaceRectPosition=function(){this.rect.x=this.placeRect.x,this.rect.y=this.placeRect.y},n.Item=i}(window),function(t){"use strict";function e(t,e){for(var i in e)t[i]=e[i];return t}function i(t){var e=[];if("number"==typeof t.length)for(var i=0,n=t.length;n>i;i++)e.push(t[i]);else e.push(t);return e}function n(t,i){if(!t||!g(t))return m&&m.error("bad Packery element: "+t),void 0;this.element=t,this.options=e({},this.options),e(this.options,i);var n=++x;this.element.packeryGUID=n,E[n]=this,this._create(),this.options.isInitLayout&&this.layout()}var o=t.Packery,r=o.Rect,s=o.Packer,a=o.Item,h=t.classie,p=t.docReady,c=t.EventEmitter,u=t.eventie,d=t.getSize,l=t.matchesSelector,f=t.document,m=t.console,y=t.jQuery,g="object"==typeof HTMLElement?function(t){return t instanceof HTMLElement}:function(t){return t&&"object"==typeof t&&1===t.nodeType&&"string"==typeof t.nodeName},v=Array.prototype.indexOf?function(t,e){return t.indexOf(e)}:function(t,e){for(var i=0,n=t.length;n>i;i++)if(t[i]===e)return i;return-1},x=0,E={};e(n.prototype,c.prototype),n.prototype.options={containerStyle:{position:"relative"},isInitLayout:!0,isResizeBound:!0,transitionDuration:"0.4s"},n.prototype._create=function(){this.packer=new s,this.reloadItems(),this.stampedElements=[],this.stamp(this.options.stamped);var t=this.options.containerStyle;e(this.element.style,t),this.options.isResizeBound&&this.bindResize();var i=this;this.handleDraggabilly={dragStart:function(t){i.itemDragStart(t.element)},dragMove:function(t){i.itemDragMove(t.element,t.position.x,t.position.y)},dragEnd:function(t){i.itemDragEnd(t.element)}},this.handleUIDraggable={start:function(t){i.itemDragStart(t.currentTarget)},drag:function(t,e){i.itemDragMove(t.currentTarget,e.position.left,e.position.top)},stop:function(t){i.itemDragEnd(t.currentTarget)}}},n.prototype.reloadItems=function(){this.items=this._getItems(this.element.children)},n.prototype._getItems=function(t){for(var e=this._filterFindItemElements(t),i=[],n=0,o=e.length;o>n;n++){var r=e[n],s=new a(r,this);i.push(s)}return i},n.prototype._filterFindItemElements=function(t){t=i(t);var e=this.options.itemSelector;if(!e)return t;for(var n=[],o=0,r=t.length;r>o;o++){var s=t[o];l(s,e)&&n.push(s);for(var a=s.querySelectorAll(e),h=0,p=a.length;p>h;h++)n.push(a[h])}return n},n.prototype.getItemElements=function(){for(var t=[],e=0,i=this.items.length;i>e;e++)t.push(this.items[e].element);return t},n.prototype.layout=function(){this._prelayout();var t=void 0!==this.options.isLayoutInstant?this.options.isLayoutInstant:!this._isLayoutInited;this.layoutItems(this.items,t),this._isLayoutInited=!0},n.prototype._init=n.prototype.layout,n.prototype._prelayout=function(){this.elementSize=d(this.element),this._getMeasurements(),this.packer.width=this.elementSize.innerWidth+this.gutter,this.packer.height=Number.POSITIVE_INFINITY,this.packer.reset(),this.maxY=0,this.placeStampedElements()},n.prototype._getMeasurements=function(){this._getMeasurement("columnWidth","width"),this._getMeasurement("rowHeight","height"),this._getMeasurement("gutter","width")},n.prototype._getMeasurement=function(t,e){var i,n=this.options[t];n?("string"==typeof n?i=this.element.querySelector(n):g(n)&&(i=n),this[t]=i?d(i)[e]:n):this[t]=0},n.prototype.layoutItems=function(t,e){var i=this._getLayoutItems(t);if(i&&i.length){this._itemsOn(i,"layout",function(){this.emitEvent("layoutComplete",[this,i])});for(var n=0,o=i.length;o>n;n++){var r=i[n];this._packItem(r),this._layoutItem(r,e)}}else this.emitEvent("layoutComplete",[this,[]]);var s=this.elementSize,a=this.maxY-this.gutter;s.isBorderBox&&(a+=s.paddingBottom+s.paddingTop+s.borderTopWidth+s.borderBottomWidth),a=Math.max(a,0),this.element.style.height=a+"px"},n.prototype._getLayoutItems=function(t){for(var e=[],i=0,n=t.length;n>i;i++){var o=t[i];o.isIgnored||e.push(o)}return e},n.prototype._packItem=function(t){this._setRectSize(t.element,t.rect),this.packer.pack(t.rect),this._setMaxY(t.rect)},n.prototype._setMaxY=function(t){this.maxY=Math.max(t.y+t.height,this.maxY)},n.prototype._setRectSize=function(t,e){var i=d(t),n=i.outerWidth,o=i.outerHeight,r=this.columnWidth+this.gutter,s=this.rowHeight+this.gutter;n=this.columnWidth?Math.ceil(n/r)*r:n+this.gutter,o=this.rowHeight?Math.ceil(o/s)*s:o+this.gutter,e.width=Math.min(n,this.packer.width),e.height=o},n.prototype._layoutItem=function(t,e){var i=t.rect;e?t.goTo(i.x,i.y):t.moveTo(i.x,i.y)},n.prototype._itemsOn=function(t,e,i){function n(){return o++,o===r&&i.call(s),!0}for(var o=0,r=t.length,s=this,a=0,h=t.length;h>a;a++){var p=t[a];p.on(e,n)}},n.prototype.stamp=function(t){if(t){"string"==typeof t&&(t=this.element.querySelectorAll(t)),t=i(t),this.stampedElements.push.apply(this.stampedElements,t);for(var e=0,n=t.length;n>e;e++){var o=t[e];this.ignore(o)}}},n.prototype.unstamp=function(t){if(t){t=i(t);for(var e=0,n=t.length;n>e;e++){var o=t[e],r=v(this.stampedElements,o);-1!==r&&this.stampedElements.splice(r,1),this.unignore(o)}}},n.prototype.placeStampedElements=function(){if(this.stampedElements&&this.stampedElements.length){this._getBounds();for(var t=0,e=this.stampedElements.length;e>t;t++){var i=this.stampedElements[t];this.placeStamp(i)}}},n.prototype._getBounds=function(){var t=this.element.getBoundingClientRect();this._boundingLeft=t.left+this.elementSize.paddingLeft,this._boundingTop=t.top+this.elementSize.paddingTop},n.prototype.placeStamp=function(t){var e,i=this.getItem(t);e=i&&i.isPlacing?i.placeRect:this._getElementOffsetRect(t),this._setRectSize(t,e),this.packer.placed(e),this._setMaxY(e)},n.prototype._getElementOffsetRect=function(t){var e=t.getBoundingClientRect(),i=new r({x:e.left-this._boundingLeft,y:e.top-this._boundingTop});return i.x-=this.elementSize.borderLeftWidth,i.y-=this.elementSize.borderTopWidth,i},n.prototype.handleEvent=function(t){var e="on"+t.type;this[e]&&this[e](t)},n.prototype.bindResize=function(){this.isResizeBound||(u.bind(t,"resize",this),this.isResizeBound=!0)},n.prototype.unbindResize=function(){u.unbind(t,"resize",this),this.isResizeBound=!1},n.prototype.onresize=function(){function t(){e.resize()}this.resizeTimeout&&clearTimeout(this.resizeTimeout);var e=this;this.resizeTimeout=setTimeout(t,100)},n.prototype.resize=function(){var t=d(this.element),e=this.elementSize&&t;e&&t.innerWidth===this.elementSize.innerWidth||(this.layout(),delete this.resizeTimeout)},n.prototype.addItems=function(t){var e=this._getItems(t);if(e.length)return this.items.push.apply(this.items,e),e},n.prototype.appended=function(t){var e=this.addItems(t);e.length&&(this.layoutItems(e,!0),this.reveal(e))},n.prototype.prepended=function(t){var e=this._getItems(t);if(e.length){var i=this.items.slice(0);this.items=e.concat(i),this._prelayout(),this.layoutItems(e,!0),this.reveal(e),this.layoutItems(i)}},n.prototype.reveal=function(t){if(t&&t.length)for(var e=0,i=t.length;i>e;e++){var n=t[e];n.reveal()}},n.prototype.getItem=function(t){for(var e=0,i=this.items.length;i>e;e++){var n=this.items[e];if(n.element===t)return n}},n.prototype.getItems=function(t){if(t&&t.length){for(var e=[],i=0,n=t.length;n>i;i++){var o=t[i],r=this.getItem(o);r&&e.push(r)}return e}},n.prototype.remove=function(t){t=i(t);var e=this.getItems(t);this._itemsOn(e,"remove",function(){this.emitEvent("removeComplete",[this,e])});for(var n=0,o=e.length;o>n;n++){var r=e[n];r.remove();var s=v(this.items,r);this.items.splice(s,1)}},n.prototype.ignore=function(t){var e=this.getItem(t);e&&(e.isIgnored=!0)},n.prototype.unignore=function(t){var e=this.getItem(t);e&&delete e.isIgnored},n.prototype.sortItemsByPosition=function(){this.items.sort(function(t,e){return t.position.y-e.position.y||t.position.x-e.position.x})},n.prototype.fit=function(t,e,i){function n(){s++,2===s&&r.emitEvent("fitComplete",[r,o])}var o=this.getItem(t);if(o){this._getMeasurements(),this.stamp(o.element),o.getSize(),o.isPlacing=!0,e=void 0===e?o.rect.x:e,i=void 0===i?o.rect.y:i,o.positionPlaceRect(e,i,!0);var r=this,s=0;o.on("layout",function(){return n(),!0}),this.on("layoutComplete",function(){return n(),!0}),o.moveTo(o.placeRect.x,o.placeRect.y),this.layout(),this.unstamp(o.element),this.sortItemsByPosition(),o.isPlacing=!1,o.copyPlaceRectPosition()}},n.prototype.itemDragStart=function(t){this.stamp(t);var e=this.getItem(t);e&&e.dragStart()},n.prototype.itemDragMove=function(t,e,i){function n(){r.layout(),delete r.dragTimeout}var o=this.getItem(t);o&&o.dragMove(e,i);var r=this;this.clearDragTimeout(),this.dragTimeout=setTimeout(n,40)},n.prototype.clearDragTimeout=function(){this.dragTimeout&&clearTimeout(this.dragTimeout)},n.prototype.itemDragEnd=function(t){function e(){return s++,s!==r?!0:(n&&(h.remove(n.element,"is-positioning-post-drag"),n.isPlacing=!1,n.copyPlaceRectPosition()),a.unstamp(t),a.sortItemsByPosition(),n&&o&&a.emitEvent("dragItemPositioned",[a,n]),!0)}var i,n=this.getItem(t);if(n&&(i=n.didDrag,n.dragStop()),!n||!i&&!n.needsPositioning)return this.unstamp(t),void 0;h.add(n.element,"is-positioning-post-drag");var o=n.needsPositioning,r=o?2:1,s=0,a=this;o?(n.on("layout",e),n.moveTo(n.placeRect.x,n.placeRect.y)):n&&n.copyPlaceRectPosition(),this.clearDragTimeout(),this.on("layoutComplete",e),this.layout()},n.prototype.bindDraggabillyEvents=function(t){t.on("dragStart",this.handleDraggabilly.dragStart),t.on("dragMove",this.handleDraggabilly.dragMove),t.on("dragEnd",this.handleDraggabilly.dragEnd)},n.prototype.bindUIDraggableEvents=function(t){t.on("dragstart",this.handleUIDraggable.start).on("drag",this.handleUIDraggable.drag).on("dragstop",this.handleUIDraggable.stop)},n.prototype.destroy=function(){this.element.style.position="",this.element.style.height="",delete this.element.packeryGUID;for(var t=0,e=this.items.length;e>t;t++){var i=this.items[t];i.destroy()}this.unbindResize()},n.data=function(t){var e=t.packeryGUID;return e&&E[e]},p(function(){for(var t=f.querySelectorAll(".js-packery"),e=0,i=t.length;i>e;e++){var o,r=t[e],s=r.getAttribute("data-packery-options");try{o=s&&JSON.parse(s)}catch(a){m&&m.error("Error parsing data-packery-options on "+r.nodeName.toLowerCase()+(r.id?"#"+r.id:"")+": "+a);continue}var h=new n(r,o);y&&y.data(r,"packery",h)}}),y&&y.bridget&&y.bridget("packery",n),n.Rect=r,n.Packer=s,n.Item=a,t.Packery=n}(window); /** * @preserve FastClick: polyfill to remove click delays on browsers with touch UIs. * * @version 0.6.9 * @codingstandard ftlabs-jsv2 * @copyright The Financial Times Limited [All Rights Reserved] * @license MIT License (see LICENSE.txt) */ /*jslint browser:true, node:true*/ /*global define, Event, Node*/ /** * Instantiate fast-clicking listeners on the specificed layer. * * @constructor * @param {Element} layer The layer to listen on */ function FastClick(layer) { 'use strict'; var oldOnClick, self = this; /** * Whether a click is currently being tracked. * * @type boolean */ this.trackingClick = false; /** * Timestamp for when when click tracking started. * * @type number */ this.trackingClickStart = 0; /** * The element being tracked for a click. * * @type EventTarget */ this.targetElement = null; /** * X-coordinate of touch start event. * * @type number */ this.touchStartX = 0; /** * Y-coordinate of touch start event. * * @type number */ this.touchStartY = 0; /** * ID of the last touch, retrieved from Touch.identifier. * * @type number */ this.lastTouchIdentifier = 0; /** * Touchmove boundary, beyond which a click will be cancelled. * * @type number */ this.touchBoundary = 10; /** * The FastClick layer. * * @type Element */ this.layer = layer; if (!layer || !layer.nodeType) { throw new TypeError('Layer must be a document node'); } /** @type function() */ this.onClick = function() { return FastClick.prototype.onClick.apply(self, arguments); }; /** @type function() */ this.onMouse = function() { return FastClick.prototype.onMouse.apply(self, arguments); }; /** @type function() */ this.onTouchStart = function() { return FastClick.prototype.onTouchStart.apply(self, arguments); }; /** @type function() */ this.onTouchMove = function() { return FastClick.prototype.onTouchMove.apply(self, arguments); }; /** @type function() */ this.onTouchEnd = function() { return FastClick.prototype.onTouchEnd.apply(self, arguments); }; /** @type function() */ this.onTouchCancel = function() { return FastClick.prototype.onTouchCancel.apply(self, arguments); }; if (FastClick.notNeeded(layer)) { return; } // Set up event handlers as required if (this.deviceIsAndroid) { layer.addEventListener('mouseover', this.onMouse, true); layer.addEventListener('mousedown', this.onMouse, true); layer.addEventListener('mouseup', this.onMouse, true); } layer.addEventListener('click', this.onClick, true); layer.addEventListener('touchstart', this.onTouchStart, false); layer.addEventListener('touchmove', this.onTouchMove, false); layer.addEventListener('touchend', this.onTouchEnd, false); layer.addEventListener('touchcancel', this.onTouchCancel, false); // Hack is required for browsers that don't support Event#stopImmediatePropagation (e.g. Android 2) // which is how FastClick normally stops click events bubbling to callbacks registered on the FastClick // layer when they are cancelled. if (!Event.prototype.stopImmediatePropagation) { layer.removeEventListener = function(type, callback, capture) { var rmv = Node.prototype.removeEventListener; if (type === 'click') { rmv.call(layer, type, callback.hijacked || callback, capture); } else { rmv.call(layer, type, callback, capture); } }; layer.addEventListener = function(type, callback, capture) { var adv = Node.prototype.addEventListener; if (type === 'click') { adv.call(layer, type, callback.hijacked || (callback.hijacked = function(event) { if (!event.propagationStopped) { callback(event); } }), capture); } else { adv.call(layer, type, callback, capture); } }; } // If a handler is already declared in the element's onclick attribute, it will be fired before // FastClick's onClick handler. Fix this by pulling out the user-defined handler function and // adding it as listener. if (typeof layer.onclick === 'function') { // Android browser on at least 3.2 requires a new reference to the function in layer.onclick // - the old one won't work if passed to addEventListener directly. oldOnClick = layer.onclick; layer.addEventListener('click', function(event) { oldOnClick(event); }, false); layer.onclick = null; } } /** * Android requires exceptions. * * @type boolean */ FastClick.prototype.deviceIsAndroid = navigator.userAgent.indexOf('Android') > 0; /** * iOS requires exceptions. * * @type boolean */ FastClick.prototype.deviceIsIOS = /iP(ad|hone|od)/.test(navigator.userAgent); /** * iOS 4 requires an exception for select elements. * * @type boolean */ FastClick.prototype.deviceIsIOS4 = FastClick.prototype.deviceIsIOS && (/OS 4_\d(_\d)?/).test(navigator.userAgent); /** * iOS 6.0(+?) requires the target element to be manually derived * * @type boolean */ FastClick.prototype.deviceIsIOSWithBadTarget = FastClick.prototype.deviceIsIOS && (/OS ([6-9]|\d{2})_\d/).test(navigator.userAgent); /** * Determine whether a given element requires a native click. * * @param {EventTarget|Element} target Target DOM element * @returns {boolean} Returns true if the element needs a native click */ FastClick.prototype.needsClick = function(target) { 'use strict'; switch (target.nodeName.toLowerCase()) { // Don't send a synthetic click to disabled inputs (issue #62) case 'button': case 'select': case 'textarea': if (target.disabled) { return true; } break; case 'input': // File inputs need real clicks on iOS 6 due to a browser bug (issue #68) if ((this.deviceIsIOS && target.type === 'file') || target.disabled) { return true; } break; case 'label': case 'video': return true; } return (/\bneedsclick\b/).test(target.className); }; /** * Determine whether a given element requires a call to focus to simulate click into element. * * @param {EventTarget|Element} target Target DOM element * @returns {boolean} Returns true if the element requires a call to focus to simulate native click. */ FastClick.prototype.needsFocus = function(target) { 'use strict'; switch (target.nodeName.toLowerCase()) { case 'textarea': case 'select': return true; case 'input': switch (target.type) { case 'button': case 'checkbox': case 'file': case 'image': case 'radio': case 'submit': return false; } // No point in attempting to focus disabled inputs return !target.disabled && !target.readOnly; default: return (/\bneedsfocus\b/).test(target.className); } }; /** * Send a click event to the specified element. * * @param {EventTarget|Element} targetElement * @param {Event} event */ FastClick.prototype.sendClick = function(targetElement, event) { 'use strict'; var clickEvent, touch; // On some Android devices activeElement needs to be blurred otherwise the synthetic click will have no effect (#24) if (document.activeElement && document.activeElement !== targetElement) { document.activeElement.blur(); } touch = event.changedTouches[0]; // Synthesise a click event, with an extra attribute so it can be tracked clickEvent = document.createEvent('MouseEvents'); clickEvent.initMouseEvent('click', true, true, window, 1, touch.screenX, touch.screenY, touch.clientX, touch.clientY, false, false, false, false, 0, null); clickEvent.forwardedTouchEvent = true; targetElement.dispatchEvent(clickEvent); }; /** * @param {EventTarget|Element} targetElement */ FastClick.prototype.focus = function(targetElement) { 'use strict'; var length; if (this.deviceIsIOS && targetElement.setSelectionRange) { length = targetElement.value.length; targetElement.setSelectionRange(length, length); } else { targetElement.focus(); } }; /** * Check whether the given target element is a child of a scrollable layer and if so, set a flag on it. * * @param {EventTarget|Element} targetElement */ FastClick.prototype.updateScrollParent = function(targetElement) { 'use strict'; var scrollParent, parentElement; scrollParent = targetElement.fastClickScrollParent; // Attempt to discover whether the target element is contained within a scrollable layer. Re-check if the // target element was moved to another parent. if (!scrollParent || !scrollParent.contains(targetElement)) { parentElement = targetElement; do { if (parentElement.scrollHeight > parentElement.offsetHeight) { scrollParent = parentElement; targetElement.fastClickScrollParent = parentElement; break; } parentElement = parentElement.parentElement; } while (parentElement); } // Always update the scroll top tracker if possible. if (scrollParent) { scrollParent.fastClickLastScrollTop = scrollParent.scrollTop; } }; /** * @param {EventTarget} targetElement * @returns {Element|EventTarget} */ FastClick.prototype.getTargetElementFromEventTarget = function(eventTarget) { 'use strict'; // On some older browsers (notably Safari on iOS 4.1 - see issue #56) the event target may be a text node. if (eventTarget.nodeType === Node.TEXT_NODE) { return eventTarget.parentNode; } return eventTarget; }; /** * On touch start, record the position and scroll offset. * * @param {Event} event * @returns {boolean} */ FastClick.prototype.onTouchStart = function(event) { 'use strict'; var targetElement, touch, selection; // Ignore multiple touches, otherwise pinch-to-zoom is prevented if both fingers are on the FastClick element (issue #111). if (event.targetTouches.length > 1) { return true; } targetElement = this.getTargetElementFromEventTarget(event.target); touch = event.targetTouches[0]; if (this.deviceIsIOS) { // Only trusted events will deselect text on iOS (issue #49) selection = window.getSelection(); if (selection.rangeCount && !selection.isCollapsed) { return true; } if (!this.deviceIsIOS4) { // Weird things happen on iOS when an alert or confirm dialog is opened from a click event callback (issue #23): // when the user next taps anywhere else on the page, new touchstart and touchend events are dispatched // with the same identifier as the touch event that previously triggered the click that triggered the alert. // Sadly, there is an issue on iOS 4 that causes some normal touch events to have the same identifier as an // immediately preceeding touch event (issue #52), so this fix is unavailable on that platform. if (touch.identifier === this.lastTouchIdentifier) { event.preventDefault(); return false; } this.lastTouchIdentifier = touch.identifier; // If the target element is a child of a scrollable layer (using -webkit-overflow-scrolling: touch) and: // 1) the user does a fling scroll on the scrollable layer // 2) the user stops the fling scroll with another tap // then the event.target of the last 'touchend' event will be the element that was under the user's finger // when the fling scroll was started, causing FastClick to send a click event to that layer - unless a check // is made to ensure that a parent layer was not scrolled before sending a synthetic click (issue #42). this.updateScrollParent(targetElement); } } this.trackingClick = true; this.trackingClickStart = event.timeStamp; this.targetElement = targetElement; this.touchStartX = touch.pageX; this.touchStartY = touch.pageY; // Prevent phantom clicks on fast double-tap (issue #36) if ((event.timeStamp - this.lastClickTime) < 200) { event.preventDefault(); } return true; }; /** * Based on a touchmove event object, check whether the touch has moved past a boundary since it started. * * @param {Event} event * @returns {boolean} */ FastClick.prototype.touchHasMoved = function(event) { 'use strict'; var touch = event.changedTouches[0], boundary = this.touchBoundary; if (Math.abs(touch.pageX - this.touchStartX) > boundary || Math.abs(touch.pageY - this.touchStartY) > boundary) { return true; } return false; }; /** * Update the last position. * * @param {Event} event * @returns {boolean} */ FastClick.prototype.onTouchMove = function(event) { 'use strict'; if (!this.trackingClick) { return true; } // If the touch has moved, cancel the click tracking if (this.targetElement !== this.getTargetElementFromEventTarget(event.target) || this.touchHasMoved(event)) { this.trackingClick = false; this.targetElement = null; } return true; }; /** * Attempt to find the labelled control for the given label element. * * @param {EventTarget|HTMLLabelElement} labelElement * @returns {Element|null} */ FastClick.prototype.findControl = function(labelElement) { 'use strict'; // Fast path for newer browsers supporting the HTML5 control attribute if (labelElement.control !== undefined) { return labelElement.control; } // All browsers under test that support touch events also support the HTML5 htmlFor attribute if (labelElement.htmlFor) { return document.getElementById(labelElement.htmlFor); } // If no for attribute exists, attempt to retrieve the first labellable descendant element // the list of which is defined here: http://www.w3.org/TR/html5/forms.html#category-label return labelElement.querySelector('button, input:not([type=hidden]), keygen, meter, output, progress, select, textarea'); }; /** * On touch end, determine whether to send a click event at once. * * @param {Event} event * @returns {boolean} */ FastClick.prototype.onTouchEnd = function(event) { 'use strict'; var forElement, trackingClickStart, targetTagName, scrollParent, touch, targetElement = this.targetElement; if (!this.trackingClick) { return true; } // Prevent phantom clicks on fast double-tap (issue #36) if ((event.timeStamp - this.lastClickTime) < 200) { this.cancelNextClick = true; return true; } this.lastClickTime = event.timeStamp; trackingClickStart = this.trackingClickStart; this.trackingClick = false; this.trackingClickStart = 0; // On some iOS devices, the targetElement supplied with the event is invalid if the layer // is performing a transition or scroll, and has to be re-detected manually. Note that // for this to function correctly, it must be called *after* the event target is checked! // See issue #57; also filed as rdar://13048589 . if (this.deviceIsIOSWithBadTarget) { touch = event.changedTouches[0]; // In certain cases arguments of elementFromPoint can be negative, so prevent setting targetElement to null targetElement = document.elementFromPoint(touch.pageX - window.pageXOffset, touch.pageY - window.pageYOffset) || targetElement; targetElement.fastClickScrollParent = this.targetElement.fastClickScrollParent; } targetTagName = targetElement.tagName.toLowerCase(); if (targetTagName === 'label') { forElement = this.findControl(targetElement); if (forElement) { this.focus(targetElement); if (this.deviceIsAndroid) { return false; } targetElement = forElement; } } else if (this.needsFocus(targetElement)) { // Case 1: If the touch started a while ago (best guess is 100ms based on tests for issue #36) then focus will be triggered anyway. Return early and unset the target element reference so that the subsequent click will be allowed through. // Case 2: Without this exception for input elements tapped when the document is contained in an iframe, then any inputted text won't be visible even though the value attribute is updated as the user types (issue #37). if ((event.timeStamp - trackingClickStart) > 100 || (this.deviceIsIOS && window.top !== window && targetTagName === 'input')) { this.targetElement = null; return false; } this.focus(targetElement); // Select elements need the event to go through on iOS 4, otherwise the selector menu won't open. if (!this.deviceIsIOS4 || targetTagName !== 'select') { this.targetElement = null; event.preventDefault(); } return false; } if (this.deviceIsIOS && !this.deviceIsIOS4) { // Don't send a synthetic click event if the target element is contained within a parent layer that was scrolled // and this tap is being used to stop the scrolling (usually initiated by a fling - issue #42). scrollParent = targetElement.fastClickScrollParent; if (scrollParent && scrollParent.fastClickLastScrollTop !== scrollParent.scrollTop) { return true; } } // Prevent the actual click from going though - unless the target node is marked as requiring // real clicks or if it is in the whitelist in which case only non-programmatic clicks are permitted. if (!this.needsClick(targetElement)) { event.preventDefault(); this.sendClick(targetElement, event); } return false; }; /** * On touch cancel, stop tracking the click. * * @returns {void} */ FastClick.prototype.onTouchCancel = function() { 'use strict'; this.trackingClick = false; this.targetElement = null; }; /** * Determine mouse events which should be permitted. * * @param {Event} event * @returns {boolean} */ FastClick.prototype.onMouse = function(event) { 'use strict'; // If a target element was never set (because a touch event was never fired) allow the event if (!this.targetElement) { return true; } if (event.forwardedTouchEvent) { return true; } // Programmatically generated events targeting a specific element should be permitted if (!event.cancelable) { return true; } // Derive and check the target element to see whether the mouse event needs to be permitted; // unless explicitly enabled, prevent non-touch click events from triggering actions, // to prevent ghost/doubleclicks. if (!this.needsClick(this.targetElement) || this.cancelNextClick) { // Prevent any user-added listeners declared on FastClick element from being fired. if (event.stopImmediatePropagation) { event.stopImmediatePropagation(); } else { // Part of the hack for browsers that don't support Event#stopImmediatePropagation (e.g. Android 2) event.propagationStopped = true; } // Cancel the event event.stopPropagation(); event.preventDefault(); return false; } // If the mouse event is permitted, return true for the action to go through. return true; }; /** * On actual clicks, determine whether this is a touch-generated click, a click action occurring * naturally after a delay after a touch (which needs to be cancelled to avoid duplication), or * an actual click which should be permitted. * * @param {Event} event * @returns {boolean} */ FastClick.prototype.onClick = function(event) { 'use strict'; var permitted; // It's possible for another FastClick-like library delivered with third-party code to fire a click event before FastClick does (issue #44). In that case, set the click-tracking flag back to false and return early. This will cause onTouchEnd to return early. if (this.trackingClick) { this.targetElement = null; this.trackingClick = false; return true; } // Very odd behaviour on iOS (issue #18): if a submit element is present inside a form and the user hits enter in the iOS simulator or clicks the Go button on the pop-up OS keyboard the a kind of 'fake' click event will be triggered with the submit-type input element as the target. if (event.target.type === 'submit' && event.detail === 0) { return true; } permitted = this.onMouse(event); // Only unset targetElement if the click is not permitted. This will ensure that the check for !targetElement in onMouse fails and the browser's click doesn't go through. if (!permitted) { this.targetElement = null; } // If clicks are permitted, return true for the action to go through. return permitted; }; /** * Remove all FastClick's event listeners. * * @returns {void} */ FastClick.prototype.destroy = function() { 'use strict'; var layer = this.layer; if (this.deviceIsAndroid) { layer.removeEventListener('mouseover', this.onMouse, true); layer.removeEventListener('mousedown', this.onMouse, true); layer.removeEventListener('mouseup', this.onMouse, true); } layer.removeEventListener('click', this.onClick, true); layer.removeEventListener('touchstart', this.onTouchStart, false); layer.removeEventListener('touchmove', this.onTouchMove, false); layer.removeEventListener('touchend', this.onTouchEnd, false); layer.removeEventListener('touchcancel', this.onTouchCancel, false); }; /** * Check whether FastClick is needed. * * @param {Element} layer The layer to listen on */ FastClick.notNeeded = function(layer) { 'use strict'; var metaViewport; // Devices that don't support touch don't need FastClick if (typeof window.ontouchstart === 'undefined') { return true; } if ((/Chrome\/[0-9]+/).test(navigator.userAgent)) { // Chrome on Android with user-scalable="no" doesn't need FastClick (issue #89) if (FastClick.prototype.deviceIsAndroid) { metaViewport = document.querySelector('meta[name=viewport]'); if (metaViewport && metaViewport.content.indexOf('user-scalable=no') !== -1) { return true; } // Chrome desktop doesn't need FastClick (issue #15) } else { return true; } } // IE10 with -ms-touch-action: none, which disables double-tap-to-zoom (issue #97) if (layer.style.msTouchAction === 'none') { return true; } return false; }; /** * Factory method for creating a FastClick object * * @param {Element} layer The layer to listen on */ FastClick.attach = function(layer) { 'use strict'; return new FastClick(layer); }; if (typeof define !== 'undefined' && define.amd) { // AMD. Register as an anonymous module. define(function() { 'use strict'; return FastClick; }); } else if (typeof module !== 'undefined' && module.exports) { module.exports = FastClick.attach; module.exports.FastClick = FastClick; } else { window.FastClick = FastClick; }
46.560253
32,072
0.586063
3d612ab1d1e4fb1e4726dae5658803656a7a7af5
5,023
js
JavaScript
client/src/js/components/forms/EditSegmentFormFields.js
ychung-mot/crt
df45f8794671bb538c1954fcc8fe8f3381e8e2f8
[ "Apache-2.0" ]
null
null
null
client/src/js/components/forms/EditSegmentFormFields.js
ychung-mot/crt
df45f8794671bb538c1954fcc8fe8f3381e8e2f8
[ "Apache-2.0" ]
16
2020-12-02T18:37:41.000Z
2022-03-02T12:51:34.000Z
client/src/js/components/forms/EditSegmentFormFields.js
ychung-mot/crt
df45f8794671bb538c1954fcc8fe8f3381e8e2f8
[ "Apache-2.0" ]
6
2020-12-02T19:08:08.000Z
2021-11-18T17:38:30.000Z
import React, { useEffect, useState, useRef } from 'react'; import _ from 'lodash'; import { Button, Modal, ModalHeader, ModalBody, ModalFooter } from 'reactstrap'; import PageSpinner from '../ui/PageSpinner'; import * as Constants from '../../Constants'; import * as api from '../../Api'; const defaultFormState = { startCoordinates: '', endCoordinates: '', description: '' }; function EditSegmentFormFields({ closeForm, projectId, refreshData, formType, segmentId }) { const [loading, setLoading] = useState(false); const [modalOpen, setModalOpen] = useState(false); const [initialFormState, setInitialFormState] = useState(defaultFormState); const [url, setURL] = useState(`${Constants.PATHS.TWM}?c=crt&project=${projectId}`); const myIframe = useRef(null); useEffect(() => { window.addEventListener('message', addEventListenerCloseForm); window.addEventListener('message', addEventListenerInitialFormState); return function cleanUp() { removeEventListenerCloseForm(); removeEventListenerInitialFormState(); }; }); useEffect(() => { if (formType === Constants.FORM_TYPE.EDIT) { setURL(`${url}&segment=${segmentId}`); } // eslint-disable-next-line react-hooks/exhaustive-deps }, []); //event functions const addEventListenerCloseForm = (event) => { if (event.data.message === 'closeForm' && event.origin === `${window.location.protocol}//${window.location.host}`) { setLoading(true); //convert route lineString data into groups of 2. Represents lon and lat coordinates. let data = _.chunk(event.data.route, 2); let description = event.data.description; if (formType === Constants.FORM_TYPE.ADD) { api .postSegment(projectId, { route: data, description }) .then(() => { setLoading(false); refreshData(); closeForm(); }) .catch((error) => { console.log(error); }); } else if (formType === Constants.FORM_TYPE.EDIT) { api .putSegment(projectId, segmentId, { route: data, description }) .then(() => { setLoading(false); refreshData(); closeForm(); }) .catch((error) => { console.log(error); }); } } }; const addEventListenerInitialFormState = (event) => { if ( event.data.message === 'setInitialFormState' && event.origin === `${window.location.protocol}//${window.location.host}` ) { let { startCoordinates, endCoordinates, description } = event.data.formState; //space needed after comma in start/end coordinates to match TWM //this is needed for the dirtyCheck(); //ie. startCoordinate = 56.698250,-121.707720 //convert to 56.698250, -121.707720 startCoordinates = startCoordinates.replace(',', ', '); endCoordinates = endCoordinates.replace(',', ', '); setInitialFormState({ ...defaultFormState, startCoordinates, endCoordinates, description }); } }; const removeEventListenerCloseForm = () => { window.removeEventListener('message', addEventListenerCloseForm); }; const removeEventListenerInitialFormState = () => { window.removeEventListener('message', addEventListenerInitialFormState); }; //modal helper functions const toggle = () => { setModalOpen(!modalOpen); }; const handleClose = () => { if (dirtyCheck()) { toggle(); } else { closeForm(); } }; const dirtyCheck = () => { // check if iFrame form is empty. if it's dirty we should ask user to confirm leaving let myForm = myIframe.current.contentWindow.document.forms['simple-router-form']; let dirtyFlag = false; //fixes crash if myiFrame hasn't loaded and user clicks cancel. if (!myForm) { return dirtyFlag; } for (let each in initialFormState) { if (initialFormState[each] !== myForm[each].value) { dirtyFlag = true; } } return dirtyFlag; }; if (loading) return <PageSpinner />; return ( <React.Fragment> <iframe className="w-100" style={{ height: '800px' }} src={url} name="myIframe" id="myIframe" title="map" ref={myIframe} /> <Button className="float-right mb-2" onClick={handleClose}> Cancel </Button> <Modal isOpen={modalOpen}> <ModalHeader>You have unsaved changes.</ModalHeader> <ModalBody> If the screen is closed before saving these changes, they will be lost. Do you want to continue without saving? </ModalBody> <ModalFooter> <Button size="sm" color="primary" onClick={closeForm}> Leave </Button> <Button color="secondary" size="sm" onClick={toggle}> Go Back </Button> </ModalFooter> </Modal> </React.Fragment> ); } export default EditSegmentFormFields;
29.89881
120
0.612383
3d61f515cd4e58444a787c472b6447419a779ee5
3,004
js
JavaScript
src/sap.ui.webc.fiori/src/sap/ui/webc/fiori/thirdparty/generated/themes/UploadCollectionItem.css.js
piejanssens/openui5
c684d949766e05522cdb56dc1a3333ef7210fe05
[ "MIT", "Apache-2.0", "BSD-2-Clause", "BSD-3-Clause" ]
2,724
2015-01-02T22:36:10.000Z
2022-03-30T10:48:25.000Z
src/sap.ui.webc.fiori/src/sap/ui/webc/fiori/thirdparty/generated/themes/UploadCollectionItem.css.js
piejanssens/openui5
c684d949766e05522cdb56dc1a3333ef7210fe05
[ "MIT", "Apache-2.0", "BSD-2-Clause", "BSD-3-Clause" ]
2,991
2015-01-03T17:00:12.000Z
2022-03-31T15:56:23.000Z
src/sap.ui.webc.fiori/src/sap/ui/webc/fiori/thirdparty/generated/themes/UploadCollectionItem.css.js
piejanssens/openui5
c684d949766e05522cdb56dc1a3333ef7210fe05
[ "MIT", "Apache-2.0", "BSD-2-Clause", "BSD-3-Clause" ]
1,620
2015-01-01T00:01:02.000Z
2022-03-14T23:31:35.000Z
sap.ui.define(['sap/ui/webc/common/thirdparty/base/asset-registries/Themes', 'sap/ui/webc/common/thirdparty/theme-base/generated/themes/sap_fiori_3/parameters-bundle.css', './sap_fiori_3/parameters-bundle.css'], function (Themes, defaultThemeBase, parametersBundle_css) { 'use strict'; function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e['default'] : e; } var defaultThemeBase__default = /*#__PURE__*/_interopDefaultLegacy(defaultThemeBase); Themes.registerThemePropertiesLoader("@ui5/webcomponents-theme-base", "sap_fiori_3", () => defaultThemeBase__default); Themes.registerThemePropertiesLoader("@ui5/webcomponents-fiori", "sap_fiori_3", () => parametersBundle_css); var UploadCollectionItemCss = ":host{height:auto}:host(:not([hidden])){display:block}.ui5-li-root.ui5-uci-root{padding:1rem}.ui5-uci-thumbnail{width:3rem;height:3rem;margin-right:.75rem}::slotted([ui5-icon][slot=thumbnail]){width:3rem;height:3rem;font-size:2.5rem}::slotted(img[slot=thumbnail]){width:3rem;height:3rem}:host([actionable]) ::slotted([ui5-icon][slot=thumbnail]){color:var(--sapContent_IconColor)}.ui5-uci-content-and-edit-container{flex:1 1 auto;min-width:0;display:flex;align-items:center}.ui5-uci-content-and-progress{max-width:100%;min-width:0;display:flex;flex:1 1 auto}.ui5-uci-content{flex:1 1 auto;margin-right:.5rem;width:100%;min-width:0}.ui5-uci-file-name{width:100%;display:block;font-family:\"72override\",var(--sapFontFamily);font-size:var(--sapFontLargeSize);color:var(--sapTextColor);margin-bottom:.25rem;white-space:nowrap;text-overflow:ellipsis;overflow:hidden}[ui5-link].ui5-uci-file-name{pointer-events:all}.ui5-uci-description{margin-top:.375rem;font-family:\"72override\",var(--sapFontFamily);font-size:var(--sapFontMediumSize);color:var(--sapContent_LabelColor);white-space:normal}.ui5-uci-edit-container [ui5-input]{width:60%;pointer-events:all;min-width:auto}.ui5-uci-file-extension{font-family:\"72override\",var(--sapFontFamily);font-size:var(--sapFontMediumSize);color:var(--sapTextColor);white-space:no-wrap;overflow:hidden;margin-left:.5rem;width:40%;display:inline-block;vertical-align:middle}.ui5-uci-root-editing .ui5-li-deletebtn,.ui5-uci-root-editing .ui5-li-detailbtn,.ui5-uci-root-uploading .ui5-li-deletebtn,.ui5-uci-root-uploading .ui5-li-detailbtn{display:none}.ui5-uci-edit-buttons{pointer-events:all;margin-left:1rem}.ui5-uci-edit-rename-btn{margin-right:.125rem}.ui5-uci-progress-box{width:20%;min-width:4rem}@media(max-width:30rem){.ui5-uci-content-and-edit-container{display:block}.ui5-uci-content-and-progress{flex-wrap:wrap}.ui5-uci-progress-box{width:100%;margin-top:.5rem}.ui5-uci-content{width:100%}.ui5-li-deletebtn,.ui5-li-detailbtn,.ui5-uci-edit-buttons{margin-top:.75rem}.ui5-uci-edit-buttons{margin-left:0}}.ui5-uci-progress-indicator{height:1.125rem;margin-bottom:.5rem;padding:5px 0;box-sizing:border-box}.ui5-uci-progress-labels{display:flex;justify-content:space-between}"; return UploadCollectionItemCss; });
214.571429
2,246
0.780626
3d62019a1cfa3bb66ad0fa171b17d669a39d1a43
25,387
js
JavaScript
modules/db.js
Speed-r/Twitch-Blizzbot
e0ecb9a07dfcbbecae2a14d02382139dc6354086
[ "MIT" ]
6
2021-01-25T12:47:12.000Z
2022-03-09T13:48:57.000Z
modules/db.js
Speed-r/Twitch-Blizzbot
e0ecb9a07dfcbbecae2a14d02382139dc6354086
[ "MIT" ]
3
2021-02-09T17:13:27.000Z
2021-10-17T10:45:39.000Z
modules/db.js
Speed-r/Twitch-Blizzbot
e0ecb9a07dfcbbecae2a14d02382139dc6354086
[ "MIT" ]
22
2021-01-25T10:48:14.000Z
2021-12-28T11:35:32.000Z
const { Pool } = require("pg"); const { permissions } = require("./constants"); const { currentMonth } = require("./functions"); const { EOL } = require("os"); /** * @typedef watchtimeuser * @property {string} viewer * @property {number} watchtime */ /** * @typedef resolvedAlias * @property {string} alias * @property {string} command * @property {string} response * @property {number} permissions */ /** * @typedef cmdData * @property {string} commandname * @property {string} response * @property {number} permissions */ class DB { #statements; /* eslint-ignore*/ /** * @class DB * Database class - currently based on postgres * @property {import("./statements").statements} #statements * @property {config} #config */ constructor(config) { this.#statements = require("./statements.json"); this.doingWatchtime = false; this.db = new Pool(config); this.dbname = config.database; /** @type {import("./clients").Clients}*/ this.clients = undefined; this.#ensureTables(); } /** * @param {string} sql * @param {any[]} data */ async query(sql, ...data) { const client = await this.db.connect(); try { const res = await client.query(sql, data).catch(e => { throw e; }); return res; } catch (e) { this.clients.logger.error(e?.toString()); } finally { client.release(); } } /** * initializes the Database */ async #ensureTables() { const client = await this.db.connect(); try { const tables = (await client.query("SELECT * FROM pg_catalog.pg_tables WHERE schemaname != 'pg_catalog' AND schemaname != 'information_schema';")).rows; this.clients.logger.log("debug", "Existing databases: " + tables.map(t => t.tablename).join(", ")); let todoTables = [ ["streamer", "CREATE TABLE streamer (name VARCHAR(25) PRIMARY KEY, automessage BOOLEAN DEFAULT TRUE);"], ["watchtime", `CREATE TABLE watchtime (channel VARCHAR(25) NOT NULL REFERENCES streamer(name) ON UPDATE CASCADE ON DELETE CASCADE, viewer VARCHAR(25) NOT NULL, watchtime INTEGER DEFAULT 0, month VARCHAR(7) NOT NULL, PRIMARY KEY(channel, viewer, month));`], ["customcommands", `CREATE TABLE customcommands (channel VARCHAR(25) NOT NULL references streamer(name), command TEXT NOT NULL, response TEXT, permissions INTEGER, PRIMARY KEY(channel, command));`], ["aliases", `CREATE TABLE aliases (alias TEXT, command TEXT NOT NULL, channel VARCHAR(25) NOT NULL, PRIMARY KEY(channel, alias), FOREIGN KEY(channel, command) REFERENCES customcommands(channel, command) ON UPDATE CASCADE ON DELETE CASCADE);`], ["counters", `CREATE TABLE counters (channel VARCHAR(25) NOT NULL references streamer(name) ON UPDATE CASCADE ON DELETE CASCADE, name TEXT, cur INTEGER DEFAULT 0, inc INTEGER DEFAULT 1, PRIMARY KEY(channel, name));`], ["userlink", `CREATE TABLE userlink (discordid VARCHAR(30) PRIMARY KEY, twitchname VARCHAR(25) NOT NULL);`], ["blacklist", `create table blacklist (channel VARCHAR(25) REFERENCES streamer(name) ON DELETE CASCADE ON UPDATE CASCADE, blwords TEXT [], UNIQUE(channel));`], ]; if (tables && tables.length > 0) { /** @type {string[]}*/ const tablenames = tables.map(t => t.tablename); todoTables = todoTables.filter((val) => tablenames.indexOf(val[0]) == -1); } for (const stmt of todoTables) { this.clients.logger.log("debug", "creating table " + stmt[0]); client.query(stmt[1]); } } catch (e) { this.clients.logger.error(e); throw e; } finally { client.release(); } } /** * stops the database */ stop() { return this.db.end(); } /** * add a new channel to the database * @param {string} channel */ async newChannel(channel) { const client = await this.db.connect(); try { channel = channel.replace(/#+/g, ""); await client.query(this.#statements.newChannel, [channel, true]).catch((e) => { throw e; }); await client.query(this.#statements.newBlacklist, [channel]).catch((e) => { throw e; }); } catch (e) { this.clients.logger.error(e); } finally { client.release(); } } /** * add a new channel to the database * @param {string} channel */ async getChannel(channel) { const client = await this.db.connect(); try { channel = channel.replace(/#+/g, ""); const data = await client.query(this.#statements.getChannel, [channel]).catch((e) => { throw e; }); return data.rows.length == 0 ? null : data.rows[0]; } catch (e) { this.clients.logger.error(e); } finally { client.release(); } } // #region Aliases /** * adds an Alias to a custom command * @param {string} channel Channel where to add the Alias * @param {string} name name of the Alias * @param {string} command Command the alias refers to */ async newAlias(channel, name, command) { const client = await this.db.connect(); try { channel = channel.replace(/#+/g, ""); await client.query(this.#statements.newAlias, [channel, name, command]).catch((e) => { throw e; }); } catch (e) { this.clients.logger.error(e); } finally { client.release(); } } /** * @param {string} channel * @param {string} name * @returns {Promise<resolvedAlias?>} command data */ async resolveAlias(channel, name) { const client = await this.db.connect(); try { channel = channel.replace(/#+/g, ""); const data = await client.query(this.#statements.resolveAlias, [name, channel]).catch((e) => { throw e; }); return data.rows.length == 0 ? null : data.rows[0]; } catch (e) { this.clients.logger.error(e); } finally { client.release(); } } /** * delete an alias * @param {string} name Name of the Alias to delete * @param {string} channel */ async deleteAlias(channel, name) { const client = await this.db.connect(); try { channel = channel.replace(/#+/g, ""); await client.query(this.#statements.delAlias, [channel, name]).catch((e) => { throw e; }); } catch (e) { this.clients.logger.error(e); } finally { client.release(); } } /** * Get all existing aliases * @param {string} channel * @returns {Promise<{channel: string, command: string, alias: string}[]>} List of all Aliases */ async getAliases(channel) { const client = await this.db.connect(); try { channel = channel.replace(/#+/g, ""); return (await client.query(this.#statements.getAliases, [channel]).catch((e) => { throw e; }))?.rows || []; } catch (e) { this.clients.logger.error(e); } finally { client.release(); } } // #endregion aliasses // #region counters /** * creates a new counter * @param {string} channel channel to create the counter for * @param {string} name counter name * @param {number} inc=1 the automatic increase * @param {number} defaultVal=0 the starting value */ async newCounter(channel, name, inc = 1, defaultVal = 0) { const client = await this.db.connect(); try { channel = channel.replace(/#+/g, ""); await client.query(this.#statements.newCounter, [channel, name, defaultVal, inc]).catch((e) => { throw e; }); } catch (e) { this.clients.logger.error(e); } finally { client.release(); } } /** * read only, does NOT modify the value * @param {string} channel * @param {string} name * @returns {Promise<number?>} value if exists */ async readCounter(channel, name) { const client = await this.db.connect(); try { channel = channel.replace(/#+/g, ""); const data = await client.query(this.#statements.getCounter, [name, channel]).catch((e) => { throw e; }); if (data.rows.length == 0) return; return data.rows[0].cur; } catch (e) { this.clients.logger.error(e); } finally { client.release(); } } /** * @param {string} channel * @param {string} name * @returns {Promise<number?>} */ async getCounter(channel, name) { const client = await this.db.connect(); try { channel = channel.replace(/#+/g, ""); const data = await client.query(this.#statements.incCounter, [name, channel]).catch((e) => { throw e; }); if (data.rows.length == 0) return; return data.rows[0]?.cur; } catch (e) { this.clients.logger.error(e); } finally { client.release(); } } /** * @param {string} channel * @param {string} name * @param {number} val */ async setCounter(channel, name, val) { const client = await this.db.connect(); try { channel = channel.replace(/#+/g, ""); await client.query(this.#statements.setCounter, [val, name, channel]).catch((e) => { throw e; }); } catch (e) { this.clients.logger.error(e); } finally { client.release(); } } /** * @param {string} channel * @param {string} name * @param {number} inc */ async editCounter(channel, name, inc) { const client = await this.db.connect(); try { channel = channel.replace(/#+/g, ""); await client.query(this.#statements.editCounter, [inc, name, channel]).catch((e) => { throw e; }); } catch (e) { this.clients.logger.error(e); } finally { client.release(); } } /** * @param {string} channel * @param {string} name */ async delCounter(channel, name) { const client = await this.db.connect(); try { channel = channel.replace(/#+/g, ""); await client.query(this.#statements.delCounter, [channel, name]).catch((e) => { throw e; }); } catch (e) { this.clients.logger.error(e.message); } finally { client.release(); } } async allCounters(channel) { const client = await this.db.connect(); try { channel = channel.replace(/#+/g, ""); const data = await client.query(this.#statements.allCounters, [channel]).catch((e) => { throw e; }); return data.rows; } catch (e) { this.clients.logger.error(e.message); } finally { client.release(); } } // #endregion counters // #region Customcommands /** * get all customcommands * @returns {Promise<string[]>} list of customcommands * @param {string} channel * @param {number} permission */ async allCcmds(channel, permission = permissions.user) { const client = await this.db.connect(); try { channel = channel.replace(/#+/g, ""); return (await client.query(this.#statements.getAllCommands, [channel, permission]).catch((e) => { throw e; }))?.rows?.map((row) => row.command); } catch (e) { this.clients.logger.error(e); } finally { client.release(); } } /** * get response of customcommand * @param {string} commandname * @param {string} channel * @returns {Promise<?cmdData>} response */ async getCcmd(channel, commandname) { const client = await this.db.connect(); try { channel = channel.replace(/#+/g, ""); const data = await client.query(this.#statements.getCommand, [commandname, channel]).catch((e) => { throw e; }); return data.rows.length > 0 ? data.rows[0] : undefined; } catch (e) { this.clients.logger.error(e); } finally { client.release(); } } /** * Create new Customcommand/change its response * @param {string} channel * @param {string} commandname * @param {string} response * @param {number} perms */ async newCcmd(channel, commandname, response, perms) { const client = await this.db.connect(); try { channel = channel.replace(/#+/g, ""); await client.query(this.#statements.newCommand, [commandname, response, channel, perms]).catch((e) => { throw e; }); } catch (e) { this.clients.logger.error(e); } finally { client.release(); } } /** * @param {cmdData[]} cmdData * @param {string} channel * @param {"user"|"mod"} cmdType */ async migrateCustomcommands(cmdData, channel, cmdType) { const client = await this.db.connect(); try { channel = channel.replace(/#+/, ""); (async (cmds) => { await client.query("BEGIN"); for (const cmd of cmds) { await client.query(this.#statements.newCommand, [cmd.commandname, cmd.response, channel, permissions[cmdType]]).catch((e) => { throw e; }); } return await client.query("COMMIT").catch((e) => { throw e; }); })(cmdData); } catch (e) { this.clients.logger.error(e); } finally { client.release(); } } /** * Edit a Customcommand/change its response * @param {string} channel * @param {string} commandname * @param {string} response */ async editCcmd(channel, commandname, response) { const client = await this.db.connect(); try { channel = channel.replace(/#+/g, ""); await client.query(this.#statements.updateCommand, [response, commandname, channel]).catch((e) => { throw e; }); } catch (e) { this.clients.logger.error(e); } finally { client.release(); } } /** * delete a Customcommand * @param {string} channel * @param {string} commandname */ async delCcmd(channel, commandname) { const client = await this.db.connect(); try { channel = channel.replace(/#+/g, ""); await client.query(this.#statements.deleteCommand, [commandname, channel]).catch((e) => { throw e; }); } catch (e) { this.clients.logger.error(e); } finally { client.release(); } } /** * transfers a customcommande to another permission level * @param {string} channel * @param {string} commandname */ async transferCmd(channel, commandname) { const client = await this.db.connect(); try { channel = channel.replace(/#+/g, ""); const cmd = await client.query(this.#statements.getCommandPermission, [commandname, channel]).catch((e) => { throw e; }); if (cmd?.rows?.length == 0) { return "no_such_command"; } const newPerm = cmd.rows[0].permissions == permissions.user ? permissions.mod : permissions.user; await client.query(this.#statements.changeCommandPermissions, [newPerm, commandname, channel]).catch((e) => { throw e; }); return "ok"; } catch (e) { this.clients.logger.error(e); } finally { client.release(); } } // #endregion Customcommands // #region watchtime /** * Default Watchtime Increase (and creation for new users) * @param {string} channel Channel where to add Watchtime * @param {string[]} chatters List of Users to add Watchtime to */ async watchtime(channel, chatters) { if (this.doingWatchtime) { return this.clients.logger.error("watchtime already in progress at " + (new Date).toLocaleTimeString()); } this.doingWatchtime = true; const client = await this.db.connect(); try { const started = new Date; this.clients.logger.log("debug", "starting watchtime at " + started.toLocaleTimeString()); channel = channel.replace(/#+/, ""); const month = currentMonth(); (async (users) => { await client.query("BEGIN"); await client.query(this.#statements.watchtimeNew, [channel, users, month]).catch((e) => { this.clients.logger.error("insert month" + e?.toString()); client.query("ROLLBACK"); }); await client.query(this.#statements.watchtimeNew, [channel, users, "alltime"]).catch((e) => { this.clients.logger.error("insert alltime" + e?.toString()); client.query("ROLLBACK"); }); await client.query(this.#statements.watchtimeInc, [users, channel, month]).catch((e) => { this.clients.logger.error("inc month" + e?.toString()); client.query("ROLLBACK"); }); await client.query(this.#statements.watchtimeInc, [users, channel, "alltime"]).catch((e) => { this.clients.logger.error("inc alltime" + e?.toString()); client.query("ROLLBACK"); }); client.query("COMMIT").catch((e) => { throw e; }); })(chatters); const endtime = new Date; this.clients.logger.log("debug", "finished watchtime at " + endtime.toLocaleTimeString() + EOL + "Took " + (endtime.getTime() - started.getTime()) + "ms."); } catch (e) { this.clients.logger.error(e?.toString()); } finally { client.release(); this.doingWatchtime = false; } } /** * rename a watchtime user * @param {string} channel Channel where to rename the viewer * @param {string} oldName previous name of the viewer * @param {string} newName new name to change to */ async renameWatchtimeUser(channel, oldName, newName) { const client = await this.db.connect(); try { channel = channel.replace(/#+/g, ""); await client.query(this.#statements.renameWatchtimeUser, [channel, newName, oldName]).catch((e) => { throw e; }); } catch (e) { this.clients.logger.error(e); } finally { client.release(); } } /** @typedef old_watchtime * @property {number} watchtime * @property {string} user */ /** * Watchtime migration method (and creation for new users) * @param {string} channel Channel where to add Watchtime * @param {old_watchtime[]} chatters List of Users to add Watchtime to * @param {string} month The month to add the watchtime at */ async migrateWatchtime(channel, chatters, month) { const client = await this.db.connect(); try { channel = channel.replace(/#+/, ""); (async (users) => { await client.query("BEGIN"); const usernames = users.map((u) => u.user); await client.query(this.#statements.watchtimeNew, [channel, usernames, month]).catch((e) => { throw e; }); for (const user of users) { await client.query(this.#statements.watchtimeIncBy, [user.user, channel, month, user.watchtime]).catch((e) => { throw e; }); } return await client.query("COMMIT").catch((e) => { throw e; }); })(chatters); } catch (e) { this.clients.logger.error(e); } finally { client.release(); } } /** * get a top list of watchtime * @param {string} channel Twitch Channel Name * @param {number} max Amount of Viewers to fetch * @param {number} page * @returns {Promise<watchtimeuser[]>} Sorted Watchtime List * @param {string | number} month */ async watchtimeList(channel, month, max, page = 1) { const client = await this.db.connect(); try { channel = channel.replace(/#+/g, ""); if (!(typeof max == "number")) throw new TypeError("You have to select how many entries you need as a number."); if (!(typeof page == "number")) throw new TypeError("You need to supply a number as page"); return (await client.query(this.#statements.watchtimeList, [month, channel, max, (page - 1) * max]).catch((e) => { throw e; }))?.rows; } catch (e) { this.clients.logger.error(e); } finally { client.release(); } } /** * get Watchtime for User on Channel * @param {string} channel * @param {string} user * @returns {Promise<?number>} watchtime of the user * @param {string} [month] */ async getWatchtime(channel, user, month = "alltime") { const client = await this.db.connect(); try { channel = channel.replace("#", ""); const data = await client.query(this.#statements.getWatchtime, [user, channel, month]).catch((e) => { throw e; }); return data.rows.length > 0 ? data.rows[0].watchtime : undefined; } catch (e) { this.clients.logger.error(e); } finally { client.release(); } } // #endregion watchtime /** * get linked twitch account if exists, otherwise returns null * @param {import("discord.js").User} user discord user * @returns {Promise<string | null>} twitch username */ async getDiscordConnection(user) { const client = await this.db.connect(); try { const data = await client.query(this.#statements.getDiscordConnection, [user.id]).catch((e) => { throw e; }); return data?.rows?.length > 0 ? data.rows[0].twitchname : null; } catch (e) { this.clients.logger.error(e); } finally { client.release(); } } /** * Set a twitch user to your discord user * @param {import("discord.js").User} user discord user * @param {string} twitchname twitch username */ async newDiscordConnection(user, twitchname) { const client = await this.db.connect(); try { await client.query(this.#statements.newDiscordConnection, [user.id, twitchname]).catch((e) => { throw e; }); } catch (e) { this.clients.logger.error(e); } finally { client.release(); } } /** * @param {import("discord.js").User} user */ async deleteDiscordConnection(user) { const client = await this.db.connect(); try { await client.query(this.#statements.deleteDiscordConnection, [user.id]).catch((e) => { throw e; }); } catch (e) { this.clients.logger.error(e); } finally { client.release(); } } // #region blacklist async saveBlacklist() { const channels = this.clients.twitch.channels; const client = await this.db.connect(); try { (async () => { await client.query("BEGIN"); for (let channel of channels) { channel = channel.replace(/#+/, ""); const blacklist = this.clients.twitch.blacklist[channel]; await client.query(this.#statements.saveBlacklist, [channel, blacklist]).catch((e) => { throw e; }); } return await client.query("COMMIT").catch((e) => { throw e; }); })(); } catch (e) { this.clients.logger.error(e); } finally { client.release(); } } async loadBlacklist() { const client = await this.db.connect(); try { const data = (await client.query(this.#statements.loadBlacklist).catch((e) => { throw e; }))?.rows; data.forEach((b) => { this.clients.twitch.blacklist[b.channel] = b.blwords; }); } catch (e) { this.clients.logger.error(e); } finally { client.release(); } } // #endregion } exports.DB = DB;
37.115497
168
0.532674
3d62cd900bd3e6195e710ed2a279496d14a5395a
5,240
js
JavaScript
src/pages/CustomerManage/RealName/container/Personal.js
wsnbbbb/bss
31d57313f06bc177cf4e6911370db1c3176b90db
[ "Apache-2.0" ]
null
null
null
src/pages/CustomerManage/RealName/container/Personal.js
wsnbbbb/bss
31d57313f06bc177cf4e6911370db1c3176b90db
[ "Apache-2.0" ]
null
null
null
src/pages/CustomerManage/RealName/container/Personal.js
wsnbbbb/bss
31d57313f06bc177cf4e6911370db1c3176b90db
[ "Apache-2.0" ]
null
null
null
/* eslint-disable no-duplicate-imports */ /* eslint-disable react/prop-types */ /** 后台用户管理中心 实名认证列表 **/ // ================== // 所需的各种插件 // ================== import React from 'react'; import P from 'prop-types'; import _ from 'lodash'; import 'braft-editor/dist/index.css'; import BraftEditor from 'braft-editor'; import { Form, Button, Input, Select, } from 'antd'; import { inject, observer } from 'mobx-react'; import { withRouter } from 'react-router'; import { User } from '@src/util/user.js'; import { formItemLayout2 } from '@src/config/commvar'; // 全局通用变量 import { SYS_DICT_CUSTOMER } from '@src/config/sysDict';// 后台用户管理中心字典 // ================== // Definition // ================== const FormItem = Form.Item; const { Option } = Select; @withRouter @inject('root') @observer class Personal extends React.Component { static propTypes = { location: P.any, // 路径 history: P.any, match: P.any, root: P.any, // 全局状态 defaultData: P.any, // 当前选中的信息 onOk: P.func, // 弹框确认 onClose: P.func, // 只关闭弹窗 onFail: P.func, // 审核失败回调 id: P.any, // 当前id that: P.any, // 父组件对象 }; // formRefAdd = React.createRef(); constructor (props) { super(props); this.selectedRowKeys = [];// 选中的key this.formRefEdit = React.createRef(); this.searchCondition = {}; this.state = { lists: [], loading: false, showModal: false, pageNum: 1, // 当前第几页 page_size: 20, // 每页多少条 total: 0, // 数据库总共多少条数据 pages: 0, selectedRowKeys: [], editorState: BraftEditor.createEditorState(null) }; } /** 点击关闭时触发 **/ onClose = () => { this.props.onClose(); }; selectedRow = (selectedRowKeys, selectedRows) => { this.setState({ selectedRowKeys }); } // 审核通过 onFinishok () { this.props.onOk(); }; // 审核失败 onFail () { this.props.onFail(); } // OCR审核 onFinish (values) { let obj = { ...values, frontImage: 'http://bss2.oss-cn-hongkong.aliyuncs.com/' + values.frontImage }; console.log(obj); this.props.onOCR(obj); }; handleChange = (editorState) => { this.setState({ editorState }); } render () { const defaultData = { ...this.props.defaultData, }; let imgsrc1 = 'http://bss2.oss-cn-hongkong.aliyuncs.com/' + this.props.defaultData.frontImage; let imgsrc2 = 'http://bss2.oss-cn-hongkong.aliyuncs.com/' + this.props.defaultData.backImage; const { certificate_type, customer_period_status } = SYS_DICT_CUSTOMER; return ( <Form name="form_in_modal" ref={this.formRefEdit} className="g-modal-field" initialValues={defaultData} onFinish={(values) => {this.onFinish(values);}}> <FormItem name="email" label="用户邮箱" rules={[{ required: true }]} {...formItemLayout2}> <Input type="text" disabled /> </FormItem> <FormItem name="cardName" label="真实姓名" rules={[{ required: true }]} {...formItemLayout2}> <Input type="text" disabled /> </FormItem> <FormItem name="certificateType" label="证件类型" rules={[{ required: true }]} {...formItemLayout2}> <Select disabled> { _.map(certificate_type, (item, key) => <Option value={parseInt(key)} key={key} > {item} </Option>) } </Select> </FormItem> <FormItem name="cardNumber" label="证件号码" rules={[{ required: true }]} {...formItemLayout2}> <Input type="text" disabled /> </FormItem> <FormItem name="tel" label="联系方式" {...formItemLayout2}> <Input type="text" disabled /> </FormItem> <FormItem name="contactAddress" label="通讯地址" {...formItemLayout2}> <Input type="text" disabled /> </FormItem> <FormItem name="frontImage" label="请上传实名材料" // rules={[{ required: true }]} {...formItemLayout2}> <p style={{ marginTop: '5px' }}>个人手持身份证头像面彩色照,照片上所有信息需要清晰可见,内容真实有效,不得做任何修改,照片支持JPG,JPEG,大小不超过1M</p> <img src={imgsrc1} style={{ maxWidth: '80%' }}></img> <p style={{ marginTop: '15px' }}>个人手持身份证国徽面彩色照,照片上所有信息需要清晰可见,内容真实有效,不得做任何修改,照片支持JPG,JPEG,大小不超过1M</p> <img src={imgsrc2} style={{ maxWidth: '80%' }}></img> </FormItem> <div className="actions-btn"> {User.hasPermission('customerAuth-auditOK') && <Button onClick={() => {this.onFinishok();}} className="action-btn ok">审核通过</Button>} {User.hasPermission('customerAuth-auditError') && <Button onClick={() => {this.onFail();}} className="action-btn ok">审核失败</Button>} {User.hasPermission('customerAuth-idcard') && <Button htmlType="submit" className="action-btn ok">OCR审核</Button>} </div> </Form> ); } } export default Personal;
28.63388
143
0.53874
3d62e5547fa70f6fe7fba61185cd92ca26ad530f
648
js
JavaScript
assets/arcgis_js_api/library/4.10/esri/core/accessorSupport/decorators/writer.js
MalonzaElkanah/e-cafe
dcef1ceb8ccb86bdd598d17015369db55bcf63f1
[ "Apache-2.0" ]
2
2019-05-06T08:23:55.000Z
2020-04-04T12:58:11.000Z
assets/arcgis_js_api/library/4.10/esri/core/accessorSupport/decorators/writer.js
MalonzaElkanah/e-cafe
dcef1ceb8ccb86bdd598d17015369db55bcf63f1
[ "Apache-2.0" ]
null
null
null
assets/arcgis_js_api/library/4.10/esri/core/accessorSupport/decorators/writer.js
MalonzaElkanah/e-cafe
dcef1ceb8ccb86bdd598d17015369db55bcf63f1
[ "Apache-2.0" ]
1
2021-12-05T18:59:25.000Z
2021-12-05T18:59:25.000Z
// All material copyright ESRI, All Rights Reserved, unless otherwise specified. // See https://js.arcgis.com/4.10/esri/copyright.txt for details. //>>built define(["require","exports","../../object","./property"],function(m,f,h,k){Object.defineProperty(f,"__esModule",{value:!0});f.writer=function(a,c,g){var d,e;void 0===c?(e=a,d=[void 0]):"string"!==typeof c?(e=a,d=[void 0],g=c):(e=c,d=Array.isArray(a)?a:[a]);return function(a,c,f){var l=a.constructor.prototype;d.forEach(function(b){b=k.propertyJSONMeta(a,b,e);b.write&&"object"!==typeof b.write&&(b.write={});g&&h.setDeepValue("write.target",g,b);h.setDeepValue("write.writer",l[c],b)})}}});
162
491
0.683642
3d643ecd230d933977a5cef4ab0674d8e73168f2
1,203
js
JavaScript
check.js
simoraman/line-check
38bb49a66c12c6fcb4f5b6edf3e5ec8376365f66
[ "MIT" ]
null
null
null
check.js
simoraman/line-check
38bb49a66c12c6fcb4f5b6edf3e5ec8376365f66
[ "MIT" ]
null
null
null
check.js
simoraman/line-check
38bb49a66c12c6fcb4f5b6edf3e5ec8376365f66
[ "MIT" ]
null
null
null
'use strict'; const check = function check(template, json) { const isNumber = function isNumber(param) { return !isNaN(param); }; const createResult = function createResult(result, message) { return { match: result, message: result ? '' : message }; }; let result = true; for (var prop in template) { if (template.hasOwnProperty(prop)) { if (!json.hasOwnProperty(prop)) { return createResult(false, `missing key ${prop}`); } let templateProperty = template[prop]; let jsonProperty = json[prop]; if (Array.isArray(templateProperty)) { return createResult(Array.isArray(jsonProperty), `key ${prop} is not an array`); } if (isNumber(templateProperty)) { return createResult(isNumber(jsonProperty), `key ${prop} is not a number`); } if (typeof templateProperty === 'object') { return check(templateProperty, jsonProperty); } } } return { match: result }; }; module.exports = check;
31.657895
67
0.527847
3d64403ed56f1a13975c7b99ba5720c460b27e54
2,709
js
JavaScript
client/src/helpers/EventHelpers/__test__/CardTimerEvent.test.js
devVenus1202/nuggetai
16a0c67a516a3b9e0910d0f8e874004e4a790c44
[ "MIT" ]
null
null
null
client/src/helpers/EventHelpers/__test__/CardTimerEvent.test.js
devVenus1202/nuggetai
16a0c67a516a3b9e0910d0f8e874004e4a790c44
[ "MIT" ]
1
2021-09-02T11:38:46.000Z
2021-09-02T11:38:46.000Z
client/src/helpers/EventHelpers/__test__/CardTimerEvent.test.js
devVenus1202/nuggetai
16a0c67a516a3b9e0910d0f8e874004e4a790c44
[ "MIT" ]
null
null
null
import { advanceBy, advanceTo, clear } from 'jest-date-mock'; import { onFocusAccordion, result, getResult, init } from '../CardTimerEvent'; const expectation = [ { '0': { startedAt: 1530075600000 } }, { '0': { duration: 3000 }, '1': { startedAt: 1530075603000 } }, { '0': { duration: 3000 }, '1': { duration: 6000 }, '2': { startedAt: 1530075609000 } }, { '0': { duration: 3000, startedAt: 1530075612000 }, '1': { duration: 6000 }, '2': { duration: 3000 } }, { '0': '6.00', '1': '6.00', '2': '3.00' }, { '0': { startedAt: 1530075615000 } }, { '0': { duration: 3000 }, '3': { startedAt: 1530075618000 } } ]; describe('Event - CardTimerEvent Test', () => { test('onFocusAccordion method should store time spent on Accordion ', () => { advanceTo(new Date(1530075600000)); // 2018, 5, 27, 0, 0, 0 onFocusAccordion(0); expect(result).toEqual(expectation[0]); // 3000ms spent on First Accordion and focused to Second advanceBy(3000); onFocusAccordion(1); expect(result).toEqual(expectation[1]); // 3000ms spent on Second Accordion advanceBy(3000); onFocusAccordion(1); expect(result).toEqual(expectation[1]); // 6000ms spent on Second Accordion and focused to Third advanceBy(3000); onFocusAccordion(2); expect(result).toEqual(expectation[2]); // 3000ms spent on Third Accordion and focused to First & 3000ms spent on First advanceBy(3000); onFocusAccordion(0); expect(result).toEqual(expectation[3]); init(); clear(); }); test('getResult method should get the final result so far ', () => { advanceTo(new Date(1530075600000)); // 2018, 5, 27, 0, 0, 0 onFocusAccordion(0); expect(result).toEqual(expectation[0]); // 3000ms spent on First Accordion and focused to Second advanceBy(3000); onFocusAccordion(1); expect(result).toEqual(expectation[1]); // 3000ms spent on Second Accordion advanceBy(3000); onFocusAccordion(1); expect(result).toEqual(expectation[1]); // 6000ms spent on Second Accordion and focused to Third advanceBy(3000); onFocusAccordion(2); expect(result).toEqual(expectation[2]); // 3000ms spent on Third Accordion and focused to First & 3000ms spent on First advanceBy(3000); onFocusAccordion(0); expect(result).toEqual(expectation[3]); // another 3000ms spent on First Accordion but didn't focus to other accordion advanceBy(3000); getResult(); expect(result).toEqual(expectation[4]); init(); expect(result).toEqual(expectation[5]); advanceBy(3000); onFocusAccordion(3); expect(result).toEqual(expectation[6]); clear(); }); });
29.129032
83
0.643411
3d64502b3ea6affb1ae6877d57563064bc0860bb
908
js
JavaScript
src/models/globalConf.js
iQoderi/qox-website
b2984cb55a507acc51b277d40d6b01103eab331f
[ "MIT" ]
null
null
null
src/models/globalConf.js
iQoderi/qox-website
b2984cb55a507acc51b277d40d6b01103eab331f
[ "MIT" ]
null
null
null
src/models/globalConf.js
iQoderi/qox-website
b2984cb55a507acc51b277d40d6b01103eab331f
[ "MIT" ]
null
null
null
import { routerRedux } from 'dva/router'; import { message } from 'antd'; import { fetchGlobalConf, updateGlobalConf } from '../services/api'; export default { namespace: 'globalConf', state: { id: '', content: '', }, effects: { *fetch(_, { call, put }) { const { data } = yield call(fetchGlobalConf); console.log(data); yield put({ type: 'get', payload: data }); }, *save({payload}, {call, put}) { const result = yield call(updateGlobalConf, payload); message.success('保存成功:-D'); }, *update({payload}, {call, put}) { yield put({ type: 'update', payload }); } }, reducers: { get(state, action) { return { ...state, ...action.payload } }, update(state, action) { return { ...state, ...action.payload } } } };
19.319149
68
0.5
3d648610f016432921eef48d6c94fcd4f9fa99b4
2,935
js
JavaScript
src/blocks/shop/checkout/checkout.js
andrey-glotov/renome
916ac3f4869f4d51e57369b3bc15c11b0ed0d132
[ "MIT" ]
null
null
null
src/blocks/shop/checkout/checkout.js
andrey-glotov/renome
916ac3f4869f4d51e57369b3bc15c11b0ed0d132
[ "MIT" ]
null
null
null
src/blocks/shop/checkout/checkout.js
andrey-glotov/renome
916ac3f4869f4d51e57369b3bc15c11b0ed0d132
[ "MIT" ]
null
null
null
/** * @file Implementation of the checkout page block * @author Andrey Glotov */ import Select from '../../common/select/select'; // -------------------------- BEGIN MODULE VARIABLES -------------------------- // Block name const BLOCK = 'checkout'; // Element selectors const SELECTORS = { BLOCK: `.${BLOCK}`, SELECT: `.${BLOCK}__select`, CHECKBOX: `.${BLOCK}__checkbox`, INPUT_HIDDEN: '.form__input:hidden', PAYMENTS: `.${BLOCK}__payments`, }; // Element class names const CLASSES = { ERROR: 'error form__error', INPUT: 'input', INPUT_INVALID: 'input_invalid', TEXTAREA: 'text-area', TEXTAREA_INVALID: 'text-area_invalid', }; // --------------------------- END MODULE VARIABLES --------------------------- // ------------------------- BEGIN UTILITY FUNCTIONS -------------------------- /** * Given the input element, get a classname containing the invalid modifier * * @param {JQuery} $element The input element */ function getInvalidClassName($element) { if ($element.hasClass(CLASSES.INPUT)) { return CLASSES.INPUT_INVALID; } else if ($element.hasClass(CLASSES.TEXTAREA)) { return CLASSES.TEXTAREA_INVALID; } } // -------------------------- END UTILITY FUNCTIONS --------------------------- // --------------------------- BEGIN EVENT HANDLERS --------------------------- /** * Handle change events on checkboxes. * Toggle the corresponding form section. */ const handleCheckboxChange = function() { const $target = $('#' + $(this).data('toggle')); $target.slideToggle(); }; // ---------------------------- END EVENT HANDLERS ---------------------------- // --------------------------- BEGIN PRIVATE METHODS -------------------------- /** * Initialize the checkout block. */ function initBlock() { const $form = $(SELECTORS.BLOCK); if ($form.length == 0) { return; } $(SELECTORS.SELECT, $form).each(function() { new Select($(this), { theme: 'checkout' }); }); $('#shipping-fields', $form).hide(); $(SELECTORS.CHECKBOX, $form).change(handleCheckboxChange); $form.validate({ errorClass: CLASSES.ERROR, ignore: SELECTORS.INPUT_HIDDEN, highlight(element) { $(element).addClass(getInvalidClassName($(element))); }, unhighlight(element) { $(element).removeClass(getInvalidClassName($(element))); }, errorPlacement($error, $element) { if ($element.attr('name') === 'payment') { $element .closest(SELECTORS.PAYMENTS) .prepend($error); } else { $error.insertAfter($element); } }, messages: { payment: 'Please select a payment method', }, }); } // ---------------------------- END PRIVATE METHODS --------------------------- initBlock();
26.205357
79
0.50494
3d64961356f87934d274ef79ea17e3fbf2d785a4
1,865
js
JavaScript
src/__tests__/Button.js
hichroma/priceline-design-system
9155251d0a5ce30f808ecbd274b2895cecd09688
[ "MIT" ]
null
null
null
src/__tests__/Button.js
hichroma/priceline-design-system
9155251d0a5ce30f808ecbd274b2895cecd09688
[ "MIT" ]
1
2022-03-20T06:17:47.000Z
2022-03-20T06:17:47.000Z
src/__tests__/Button.js
hichroma/priceline-design-system
9155251d0a5ce30f808ecbd274b2895cecd09688
[ "MIT" ]
1
2022-03-19T19:21:20.000Z
2022-03-19T19:21:20.000Z
import React from 'react' import renderer from 'react-test-renderer' import { Button, theme } from '..' describe('Button', () => { test('renders', () => { const json = renderer.create(<Button />).toJSON() expect(json).toMatchSnapshot() }) test('size small sets height and font-size', () => { const json = renderer.create(<Button size="small" />).toJSON() expect(json).toMatchSnapshot() expect(json).toHaveStyleRule('height', '32px') expect(json).toHaveStyleRule('font-size', '12px') expect(json).toHaveStyleRule('background-color', theme.colors.blue) expect(json).toHaveStyleRule('color', theme.colors.white) }) test('size medium sets height and font-size', () => { const json = renderer.create(<Button size="medium" />).toJSON() expect(json).toMatchSnapshot() expect(json).toHaveStyleRule('height', '40px') expect(json).toHaveStyleRule('font-size', '14px') }) test('size large sets height and font-size', () => { const json = renderer.create(<Button size="large" />).toJSON() expect(json).toMatchSnapshot() expect(json).toHaveStyleRule('height', '48px') expect(json).toHaveStyleRule('font-size', '16px') }) test('fullWidth prop sets width to 100%', () => { const json = renderer.create(<Button fullWidth />).toJSON() expect(json).toMatchSnapshot() expect(json).toHaveStyleRule('width', '100%') }) test('disabled prop sets', () => { const json = renderer.create(<Button disabled />).toJSON() expect(json).toMatchSnapshot() expect(json).toHaveStyleRule('background-color', theme.colors.blue) }) test('without disabled prop sets', () => { const json = renderer.create(<Button />).toJSON() expect(json).toMatchSnapshot() expect(json).toHaveStyleRule('background-color', theme.colors.darkBlue, { modifier: ':hover' }) }) })
34.537037
77
0.6563
3d64ea1c319512a0481fde8f9c3955c1ad831db9
2,705
js
JavaScript
lib/login.js
NightRaider73/node-autotip
5f856ff5486845615fa9bbde0fdf96f745e73102
[ "MIT" ]
20
2018-06-28T14:31:44.000Z
2021-12-27T10:01:24.000Z
lib/login.js
NightRaider73/node-autotip
5f856ff5486845615fa9bbde0fdf96f745e73102
[ "MIT" ]
20
2019-05-03T23:49:38.000Z
2022-03-29T21:36:10.000Z
lib/login.js
NightRaider73/node-autotip
5f856ff5486845615fa9bbde0fdf96f745e73102
[ "MIT" ]
10
2019-05-14T01:32:42.000Z
2021-10-05T19:00:50.000Z
/* eslint comma-dangle: ["error", {"functions": "never"}] */ const request = require('request'); const os = require('os'); const packageJson = require('../package.json'); const util = require('../util/utility'); const logger = require('./logger'); const bigInt = require('big-integer'); const createHash = require('../util/createHash'); const Session = require('./session'); const { getTipCount } = require('./tracker'); const headers = { 'User-Agent': `node-autotip@${packageJson.version}` }; function getServerHash(uuid) { const salt = bigInt.randBetween('0', '1.3611295e39').toString(32); return createHash(uuid + salt); } function joinServer(params, cb) { const options = { url: 'https://sessionserver.mojang.com/session/minecraft/join', method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(params) }; request(options, (err, res) => { if (err) { return cb(err, null); } if (![200, 204].includes(res.statusCode)) { logger.error(`Error ${res.statusCode} during authentication: Session servers down?`); return cb(res.statusCode, null); } return cb(null, true); }); } function autotipLogin(uuid, session, hash, cb) { getTipCount(uuid, (tipCount) => { request( { url: `https://api.autotip.pro/login?username=${session.selectedProfile.name}&uuid=${util.removeDashes(uuid)}&tips=${tipCount + 1}&v=2.1.0.6&mc=1.8.9&os=${os.type()}&hash=${hash}`, headers }, (err, res, body) => { if (err) { cb(err, null); } cb(null, body); } ); }); } function login(uuid, session, cb) { const { accessToken } = session; logger.debug(`Trying to log in as ${util.removeDashes(uuid)}`); const hash = getServerHash(util.removeDashes(uuid)); logger.debug(`Server hash is: ${hash}`); joinServer({ accessToken, selectedProfile: util.removeDashes(uuid), serverId: hash }, (err, success) => { if (success) { logger.debug('Successfully created Mojang session!'); autotipLogin(uuid, session, hash, (loginErr, body) => { let json = {}; if (loginErr) { logger.error(`Unable to login to autotip: ${loginErr}`); } else { try { json = JSON.parse(body); } catch (e) { logger.warn(`Invalid json response from autotip login server! ${e}`); } if (!json.success) { logger.error(`Autotip login failed! ${body}`); throw body; } logger.debug(`Autotip session: ${body}`); cb(new Session(json)); } }); } }); } module.exports = login;
27.886598
187
0.585213
3d667adb9d4a06e3aef692a39c393a0486573868
63
js
JavaScript
app/models/uni-form-field.js
dollarshaveclub/ember-uni-form
5c19bd6f9e65168ad62e9d9bd5bea3d3d414d937
[ "MIT" ]
27
2015-09-19T00:15:36.000Z
2019-11-20T02:00:31.000Z
app/models/uni-form-field.js
dollarshaveclub/ember-uni-form
5c19bd6f9e65168ad62e9d9bd5bea3d3d414d937
[ "MIT" ]
11
2015-10-30T00:43:04.000Z
2017-08-17T17:44:55.000Z
app/models/uni-form-field.js
dollarshaveclub/ember-uni-form
5c19bd6f9e65168ad62e9d9bd5bea3d3d414d937
[ "MIT" ]
4
2015-10-21T02:43:25.000Z
2017-04-21T19:18:23.000Z
export { default } from 'ember-uni-form/models/uni-form-field'
31.5
62
0.746032
3d66998791a65cad23046e49d559740ebb9dc06e
1,773
js
JavaScript
tests/lib/rules/no-short-assign.js
onechiporenko/eslint-plugin-sentry
76acaf4b762e88bc29397ea18d01b0c29b92d3c7
[ "MIT" ]
null
null
null
tests/lib/rules/no-short-assign.js
onechiporenko/eslint-plugin-sentry
76acaf4b762e88bc29397ea18d01b0c29b92d3c7
[ "MIT" ]
7
2016-03-13T19:51:58.000Z
2016-03-20T18:11:36.000Z
tests/lib/rules/no-short-assign.js
onechiporenko/eslint-plugin-sentry
76acaf4b762e88bc29397ea18d01b0c29b92d3c7
[ "MIT" ]
null
null
null
/** * @fileoverview * @author onechiporenko * @copyright 2016 onechiporenko. All rights reserved. * See LICENSE file in root directory for full license. */ "use strict"; //------------------------------------------------------------------------------ // Requirements //------------------------------------------------------------------------------ const rule = require("../../../lib/rules/no-short-assign"), RuleTester = require("eslint").RuleTester; const Jsonium = require("jsonium"); const j = new Jsonium(); const m = "Looks like `a =+ b` is used instead of `a += b` (same for `=-`)"; //------------------------------------------------------------------------------ // Tests //------------------------------------------------------------------------------ const validAssignments = [ {ASSIGN: "a += b;"}, {ASSIGN: "a = +b;"}, {ASSIGN: "a =\t+b;"}, {ASSIGN: "a -= b;"}, {ASSIGN: "a = -b;"}, {ASSIGN: "a =\t-b;"}, {ASSIGN: "a =-a;"}, {ASSIGN: "a =- a;"}, {ASSIGN: "a =- 1;"}, {ASSIGN: "var a =- 1;"}, {ASSIGN: "a =+b;"}, {ASSIGN: "a =-b;"}, {ASSIGN: "a=+b;"}, {ASSIGN: "a=-b;"} ]; const invalidAssignment = [ {ASSIGN: "a =+ b;"}, {ASSIGN: "a =- b;"} ]; const validTestTemplates = [ { code: "{{ASSIGN}}" } ]; const invalidTestTemplates = [ { code: "{{ASSIGN}}", errors: [ {message: m} ] } ]; const ruleTester = new RuleTester({env: {es6: true}}); ruleTester.run("no-short-assign", rule, { valid: j .setTemplates(validTestTemplates) .createCombos(["code"], validAssignments) .uniqueCombos() .getCombos(), invalid: j .setTemplates(invalidTestTemplates) .createCombos(["code", "errors.0.message"], invalidAssignment) .uniqueCombos() .getCombos() });
23.328947
80
0.461929
3d6728bad5fcebbddad26ed45a6c6e762310181f
120
js
JavaScript
migrations/2_deploy_contracts.js
NemboKid/PopBank
2e19d18c2c4cf0da20b4925fe9003209c44581c3
[ "MIT" ]
2
2019-09-23T18:27:11.000Z
2020-01-09T09:03:43.000Z
migrations/2_deploy_contracts.js
NemboKid/PopBank
2e19d18c2c4cf0da20b4925fe9003209c44581c3
[ "MIT" ]
null
null
null
migrations/2_deploy_contracts.js
NemboKid/PopBank
2e19d18c2c4cf0da20b4925fe9003209c44581c3
[ "MIT" ]
null
null
null
var PopBank = artifacts.require("./PopBank.sol"); module.exports = function(deployer) { deployer.deploy(PopBank); };
20
49
0.716667
3d677582cf97358cce541775c8276fb8c34557c1
2,468
js
JavaScript
out/peer/remote-peer.js
jpillora/pnode
e9a4fb9e0de3548eeb5db751fbea09e6ed06c62c
[ "Unlicense" ]
4
2015-04-16T01:28:57.000Z
2019-06-27T13:28:19.000Z
out/peer/remote-peer.js
jpillora/pnode
e9a4fb9e0de3548eeb5db751fbea09e6ed06c62c
[ "Unlicense" ]
null
null
null
out/peer/remote-peer.js
jpillora/pnode
e9a4fb9e0de3548eeb5db751fbea09e6ed06c62c
[ "Unlicense" ]
null
null
null
// Generated by CoffeeScript 1.6.3 var Logger, RemoteContext, RemotePeer, helper, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; Logger = require('../logger'); RemoteContext = require('../context'); helper = require('../helper'); module.exports = RemotePeer = (function(_super) { __extends(RemotePeer, _super); RemotePeer.prototype.name = 'RemotePeer'; function RemotePeer(local, guid, id, ips) { var _this = this; this.local = local; this.guid = guid; this.id = id; this.ips = ips; this.opts = this.local.opts; this.cliconns = []; Object.defineProperty(this, 'uri', { get: function() { var _ref; return (_ref = _this.cliconns[0]) != null ? _ref.uri : void 0; } }); this.connecting = false; this.ctx = new RemoteContext; this.ctx.id = id; this.ctx.guid = guid; this.isUp(false); } RemotePeer.prototype.add = function(cliconn) { var _this = this; this.ctx.combine(cliconn.ctx); this.cliconns.push(cliconn); cliconn.once('down', function() { _this.cliconns.splice(_this.cliconns.indexOf(cliconn), 1); return _this.setActive(); }); return this.setActive(); }; RemotePeer.prototype.setActive = function() { var c; c = this.cliconns[0]; this.remote = c ? c.remote : null; this.publish = c ? c.publish.bind(c) : null; this.subscribe = c ? c.subscribe.bind(c) : null; return this.isUp(!!this.remote); }; RemotePeer.prototype.isUp = function(up) { if (this.up === up) { return; } if (up) { this.up = true; this.emit('up'); } else { this.up = false; this.remote = null; this.emit('down'); } this.log("" + (this.up ? 'UP' : 'DOWN') + " (#conns:" + this.cliconns.length + ")"); }; RemotePeer.prototype.serialize = function() { return { id: this.id, guid: this.guid, ips: this.ips, clients: helper.serialize(this.clients) }; }; RemotePeer.prototype.toString = function() { return "" + this.name + ": " + this.local.id + ": " + this.id + ":"; }; return RemotePeer; })(Logger); /* //@ sourceMappingURL=remote-peer.map */
26.537634
290
0.602107
3d6799f321aab2296686313f7d1a38761218acb9
7,257
js
JavaScript
.circleci/runbuild.js
corny/twilio-video.js
aa0151e25fad977c4c4d910f68f78f069d872a16
[ "BSD-3-Clause" ]
498
2016-10-16T19:31:27.000Z
2022-03-22T18:51:21.000Z
.circleci/runbuild.js
corny/twilio-video.js
aa0151e25fad977c4c4d910f68f78f069d872a16
[ "BSD-3-Clause" ]
1,168
2016-10-17T04:33:04.000Z
2022-03-31T22:24:52.000Z
.circleci/runbuild.js
corny/twilio-video.js
aa0151e25fad977c4c4d910f68f78f069d872a16
[ "BSD-3-Clause" ]
220
2016-11-23T13:35:28.000Z
2022-03-10T03:52:25.000Z
#!/usr/bin/env node 'use strict'; /* eslint-disable camelcase */ const http = require('https'); const inquirer = require('inquirer'); const simpleGit = require('simple-git')(); /* posts a request for a circleci workflow you can alternatively use a curl command like: curl -u ${CIRCLECI_TOKEN}: -X POST \ --header 'Content-Type: application/json' \ -d '{ "branch": "master", "parameters": { "pr_workflow": false, "custom_workflow": false, "backend_workflow": true, "test_stability" : "stable", "environment": "stage" } }' \ https://circleci.com/api/v2/project/github/twilio/twilio-video.js/pipeline Note: environment, tag, test_stability are optional parameters. */ // returns a Promise that resolves with branch information let branchesPromise = null; function getBranches() { if (branchesPromise === null) { branchesPromise = new Promise((resolve, reject) => { simpleGit.branchLocal((e, branches) => { if (e) { reject(e); } else { resolve(branches); } }); }); } return branchesPromise; } // generates a circleCI request using parameters provided function generateBuildRequest(program) { // https://circleci.com/api/v2/project/github/twilio/twilio-video.js/pipeline var options = { hostname: 'circleci.com', path: '/api/v2/project/github/twilio/twilio-video.js/pipeline', method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': 'Basic ' + Buffer.from(program.token).toString('base64'), 'Accept': 'application/json', 'Host': 'circleci.com', } }; const body = { branch: 'master', parameters: { pr_workflow: program.workflow === 'pr', custom_workflow: program.workflow === 'custom', backend_workflow: program.workflow === 'backend', environment: program.environment, test_stability: program.test_stability, test_files: program.test_files } }; if (program.workflow === 'pr') { body.branch = program.branch; } else if (program.workflow === 'custom') { body.branch = program.branch; body.parameters.browser = program.browser; body.parameters.bver = program.bver; body.parameters.topology = program.topology; } else if (program.workflow === 'backend') { body.branch = program.branch; body.parameters.tag = program.tag; } return { options, body }; } // sends a request using given options/body function triggerBuild({options, body}) { console.log('Triggering:', options, body); return new Promise((resolve, reject) => { const request = http.request(options, function(res) { const chunks = []; res.on('data', chunk => chunks.push(chunk)); res.on('end', () => { var resBody = Buffer.concat(chunks); resolve(resBody.toString()); }); }); request.once('error', reject); request.end(JSON.stringify(body)); }); } const tokenPrompt = { type: 'input', name: 'token', message: 'Circle CI Token:', validate: (val) => { return typeof val === 'string' && val.length > 5; } }; const workflowPrompt = { type: 'list', name: 'workflow', message: 'Workflow:', choices: ['pr', 'custom', 'backend'], default: 'pr' }; const stableTestsPrompt = { when: (answers) => answers.workflow === 'custom', validate: answer => answer.length > 0, type: 'checkbox', name: 'test_stability', message: 'Run Stable Tests Only:', choices: ['stable', 'unstable'], default: 'all' }; // you may pick branch for pr or custom workflow. const branchPrompt = { // when: (answers) => answers.workflow !== 'backend', type: 'list', name: 'branch', message: 'Branch:', choices: () => getBranches().then(branches => [branches.current, new inquirer.Separator(), ...branches.all]), default: () => getBranches().then(branches => branches.current) }; // environment defaults to stage for backend workflow. const environmentListPrompt = { when: (answers) => answers.workflow !== 'custom', type: 'list', name: 'environment', message: 'Environment:', choices: ['prod', 'stage', 'dev'], default: (answers) => answers.workflow === 'backend' ? 'stage' :'prod' }; const environmentCheckboxPrompt = { when: (answers) => answers.workflow === 'custom', validate: answer => answer.length > 0, type: 'checkbox', name: 'environment', message: 'Environment:', choices: ['prod', 'stage', 'dev'], default: (answers) => answers.workflow === 'backend' ? 'stage' :'prod' }; const browserPrompt = { when: (answers) => answers.workflow === 'custom', validate: answer => answer.length > 0, type: 'checkbox', name: 'browser', message: 'Browser:', choices: ['chrome', 'firefox'], default: 'chrome' }; const bverPrompt = { when: (answers) => answers.workflow === 'custom', validate: answer => answer.length > 0, type: 'checkbox', name: 'bver', message: 'Bver:', choices: ['stable', 'beta', 'unstable'], default: 'stable' }; const topologyPrompt = { when: (answers) => answers.workflow === 'custom', type: 'checkbox', name: 'topology', message: 'Topology:', choices: ['group', 'peer-to-peer'], validate: answer => answer.length > 0, default: 'group', }; const testFilesPrompt = { when: (answers) => answers.workflow === 'custom', type: 'input', name: 'test_files', message: 'Files to test against:', default: 'auto', validate: (val) => { return typeof val === 'string' && val.length > 3; } }; // tag can be chosen only for backend workflow const tagPrompt = { when: (answers) => answers.workflow === 'backend', type: 'input', name: 'tag', message: 'Tag to use (type branch name if you do not want to use tag):', default: '2.0.0-beta15', validate: (val) => { return typeof val === 'string' && val.length > 5; } }; const confirmPrompt = { type: 'confirm', name: 'confirm', message: 'Confirm the build request:', default: true, }; if (process.env.CIRCLECI_TOKEN) { tokenPrompt.default = process.env.CIRCLECI_TOKEN; } inquirer.prompt([ tokenPrompt, workflowPrompt, branchPrompt, tagPrompt, environmentCheckboxPrompt, environmentListPrompt, browserPrompt, bverPrompt, topologyPrompt, stableTestsPrompt, testFilesPrompt ]).then(answers => { console.log('Will make a CI request with:', answers); // get basic values from answers. const { branch, token, workflow, tag, test_files } = answers; // make combo of possible multi-select (checkbox) values. var combo = ['browser', 'bver', 'environment', 'topology', 'test_stability'].reduce( (acc, dim) => { const dimValues = Array.isArray(answers[dim]) ? answers[dim] : [answers[dim]]; const result = []; acc.forEach(accElement => dimValues.forEach(dimValue => result.push({ ...accElement, [dim]: dimValue}))); return result; }, [{ branch, token, workflow, tag, test_files }]); inquirer.prompt([confirmPrompt]).then(({ confirm }) => { if (confirm) { combo.map(build => { const {options, body} = generateBuildRequest(build); triggerBuild({options, body}).then((result) => { console.log(result); }).catch(e => console.log('Failed to trigger a build:', e)); }); } }); });
27.488636
111
0.634422
3d67b2250e79f22837f3307074a21825c1ac9369
3,528
js
JavaScript
audioVisual/script.js
FlyingSky-CN/BiliOB-Watcher
e53b9c8b2592e4934e0be030ac9a1d1546b50299
[ "MIT" ]
1
2022-01-30T03:52:40.000Z
2022-01-30T03:52:40.000Z
script.js
FlyingSky-CN/AudioDataVisualization
6cbe642402d6876e6ea91f14aaf90b2fcef622f3
[ "MIT" ]
null
null
null
script.js
FlyingSky-CN/AudioDataVisualization
6cbe642402d6876e6ea91f14aaf90b2fcef622f3
[ "MIT" ]
1
2020-11-26T11:25:58.000Z
2020-11-26T11:25:58.000Z
/** * BiliOB-Watcher * * @author FlyingSky-CN * @package audioVisual */ config.width = config.multiple * config.width; config.height = config.multiple * config.height; $('body').css('background', config.background); $('#casvased').attr('width', config.width); $('#casvased').attr('height', config.height); $('#casvased').css('padding', 8 * config.multiple); var canvas = document.getElementById("casvased"); var canvasCtx = canvas.getContext("2d"); var AudioContext = window.AudioContext || window.webkitAudioContext || window.mozAudioContext; var audioContext = new AudioContext(); $('#musicFile').change(function () { $(this).attr('hidden', true); if (this.files.length !== 1) return; var fileReader = new FileReader(); fileReader.readAsArrayBuffer(this.files[0]); fileReader.onload = visual; }) var visual = (e) => audioContext.decodeAudioData(e.target.result, (buffer) => { /** * AudioBufferSourceNode * 用于播放解码出来的 buffer 的节点 */ var audioBufferSourceNode = audioContext.createBufferSource(); /** * AnalyserNode * 用于分析音频频谱的节点 */ var analyser = audioContext.createAnalyser(); /** * 音频频谱的密集程度 */ analyser.fftSize = config.fftSize; /** * 连接节点,audioContext.destination 是音频要最终输出的目标。 * 所以所有节点中的最后一个节点应该再连接到 audioContext.destination 才能听到声音。 */ audioBufferSourceNode.connect(analyser); analyser.connect(audioContext.destination); /** * 播放音频 */ audioBufferSourceNode.buffer = buffer; //回调函数传入的参数 audioBufferSourceNode.start(); //部分浏览器是 noteOn() 函数,用法相同 /** * 可视化 */ var bufferLength = analyser.frequencyBinCount; var dataArray = new Uint8Array(bufferLength); canvasCtx.clearRect(0, 0, config.width, config.height); function draw() { drawVisual = requestAnimationFrame(draw); analyser.getByteFrequencyData(dataArray); canvasCtx.fillStyle = config.background; canvasCtx.fillRect(0, 0, config.width, config.height); var space = config.space * config.multiple; var barWidth = config.width / bufferLength - space; var barHeight; var x = 0; /** * 绘制圆角矩形(纯色填充) * * @param {object} context canvasContext * @param {number} x x * @param {number} y y * @param {number} w width * @param {number} h height * @param {number} r round */ var roundRectColor = (context, x, y, w, h, r) => { context.save(); context.fillStyle = config.fill; context.strokeStyle = config.fill; context.lineJoin = 'round'; context.lineWidth = r; context.strokeRect(x + r / 2, y + r / 2, w - r, h - r); context.fillRect(x + r, y + r, w - r * 2, h - r * 2); context.stroke(); context.closePath(); } for (var i = 0; i < bufferLength - config.ignore; i++) { barHeight = dataArray[i] / 255 * (config.height - barWidth * config.basic) + barWidth * config.basic; roundRectColor( canvasCtx, x, (config.way === 'top') ? 0 : (config.way === 'bottom') ? config.height - barHeight : (config.height - barHeight) / 2, barWidth, barHeight, config.round ? barWidth : 0 ); x += barWidth + space; } }; draw(); });
29.157025
113
0.575113
3d67be82a354a9778630c7bafd7198438b2d5b71
127
js
JavaScript
src/index.js
davidroyer/v-editor
3a70aae20fb9ce023d012ef156dfb056700c1d12
[ "MIT" ]
null
null
null
src/index.js
davidroyer/v-editor
3a70aae20fb9ce023d012ef156dfb056700c1d12
[ "MIT" ]
null
null
null
src/index.js
davidroyer/v-editor
3a70aae20fb9ce023d012ef156dfb056700c1d12
[ "MIT" ]
null
null
null
// import ClassicEditor from '@ckeditor/ckeditor5-build-classic'; import VEditor from './VEditor.vue' export default VEditor
21.166667
65
0.779528
3d6978c35c1694ac1ca7b933f03c16f0b34a133e
1,195
js
JavaScript
src/components/Svg/SandClock.js
mouhsinelonly/el-student-spa
8009a0df8896edf19f69c65445cdce4d173ca4ef
[ "MIT" ]
null
null
null
src/components/Svg/SandClock.js
mouhsinelonly/el-student-spa
8009a0df8896edf19f69c65445cdce4d173ca4ef
[ "MIT" ]
null
null
null
src/components/Svg/SandClock.js
mouhsinelonly/el-student-spa
8009a0df8896edf19f69c65445cdce4d173ca4ef
[ "MIT" ]
null
null
null
// @flow import React from 'react' type PropsType = { fill: string, width: number, height: number }; const SandClock = (props: PropsType): React.Element<'svg'> => ( <svg overflow='visible' preserveAspectRatio='none' viewBox='-8.512 0 56 56' width={props.width || 64} height={props.height || 64} {...props} > <path d='M35.5 49h-.4c-.3-9.7-4.9-18-9.6-21 5.1-3.1 9-13.1 9.3-21h.8C37.4 7 39 5.4 39 3.5S37.4 0 35.5 0h-32C1.6 0 0 1.6 0 3.5c0 1.7 1.3 3.1 2.9 3.4.3 9.6 4.9 18.1 9.6 21-5.1 3.2-9 12.6-9.3 21-1.7.2-3.2 1.7-3.2 3.6C0 54.4 1.6 56 3.5 56h32.1c1.9 0 3.5-1.6 3.5-3.5-.1-1.9-1.7-3.5-3.6-3.5zM2 3.5C2 2.7 2.7 2 3.5 2h32.1c.7 0 1.4.7 1.4 1.5S36.3 5 35.5 5h-32C2.7 5 2 4.3 2 3.5zm13.2 25.4c.3 0 .5.1.8.1h1v-2h-1c-.3 0-.5 0-.8.1-3.9-1-9.9-9.5-10.3-20.1h27.8c-.2 4.8-1.5 10.1-3.8 14.1-1.8 3.2-4.1 5.3-6.1 5.8H21v2h1c.3 0 .5 0 .8-.1 3.9 1 9.9 9 10.3 20.1H5.3c.2-5.1 1.5-10.1 3.8-14.2 1.9-3.1 4.2-5.3 6.1-5.8zM35.5 54h-32c-.8 0-1.5-.7-1.5-1.5S2.7 51 3.5 51h32.1c.8 0 1.5.7 1.5 1.5-.1.8-.8 1.5-1.6 1.5z' vectorEffect='non-scaling-stroke' fill={props.fill || '#b9c2cb'} /> </svg> ) export default SandClock
42.678571
691
0.564017
3d69f89d972e47798359239dbf45b28e444055a8
3,616
js
JavaScript
test/models/BaseEvents.test.js
advanced-rest-client/arc-navigation-events
0b5edcd3bda505aeea23a9ad04528fa18ac2e4d1
[ "MIT" ]
null
null
null
test/models/BaseEvents.test.js
advanced-rest-client/arc-navigation-events
0b5edcd3bda505aeea23a9ad04528fa18ac2e4d1
[ "MIT" ]
5
2021-06-02T01:11:34.000Z
2021-09-26T21:20:32.000Z
test/models/BaseEvents.test.js
advanced-rest-client/arc-navigation-events
0b5edcd3bda505aeea23a9ad04528fa18ac2e4d1
[ "MIT" ]
null
null
null
import { assert } from '@open-wc/testing'; import { ARCEntityDeletedEvent, ARCEntityListEvent, ARCModelDeleteEvent, ARCModelStateDeleteEvent, } from '../../src/models/BaseEvents.js'; describe('BaseEvents', () => { describe('ARCEntityDeletedEvent', () => { const type = 'eventtype'; const id = 'saved-id'; const rev = 'saved-rev'; it('throws when no type argument', () => { let e; assert.throws(() => { e = new ARCEntityDeletedEvent(undefined, id, rev); }); assert.isUndefined(e); }); it('throws when no id argument', () => { let e; assert.throws(() => { e = new ARCEntityDeletedEvent(type, undefined, rev); }); assert.isUndefined(e); }); it('throws when no rev argument', () => { let e; assert.throws(() => { e = new ARCEntityDeletedEvent(type, id, undefined); }); assert.isUndefined(e); }); it('has readonly id property', () => { const e = new ARCEntityDeletedEvent(type, id, rev); assert.equal(e.id, id, 'has the id property'); assert.throws(() => { // @ts-ignore e.id = 'test'; }); }); it('has readonly rev property', () => { const e = new ARCEntityDeletedEvent(type, id, rev); assert.equal(e.rev, rev, 'has the rev property'); assert.throws(() => { // @ts-ignore e.rev = 'test'; }); }); it('has the type property', () => { const e = new ARCEntityDeletedEvent(type, id, rev); assert.equal(e.type, type); }); }); describe('ARCEntityListEvent', () => { const type = 'eventtype'; const opts = { limit: 5, nextPageToken: 'token' }; it('throws when no type argument', () => { let e; assert.throws(() => { e = new ARCEntityListEvent(undefined); }); assert.isUndefined(e); }); it('has readonly limit property', () => { const e = new ARCEntityListEvent(type, opts); assert.equal(e.limit, opts.limit, 'has the id property'); assert.throws(() => { // @ts-ignore e.limit = 100; }); }); it('has readonly nextPageToken property', () => { const e = new ARCEntityListEvent(type, opts); assert.equal(e.nextPageToken, opts.nextPageToken, 'has the id property'); assert.throws(() => { // @ts-ignore e.nextPageToken = 'test'; }); }); it('has the type property', () => { const e = new ARCEntityListEvent(type); assert.equal(e.type, type); }); }); describe('ARCModelDeleteEvent', () => { const stores = ['test']; it('throws when no type argument', () => { let e; assert.throws(() => { e = new ARCModelDeleteEvent(undefined); }); assert.isUndefined(e); }); it('has readonly stores property', () => { const e = new ARCModelDeleteEvent(stores); assert.deepEqual(e.stores, stores, 'has the id property'); assert.throws(() => { // @ts-ignore e.stores = []; }); }); }); describe('ARCModelStateDeleteEvent', () => { const store = 'test'; it('throws when no type argument', () => { let e; assert.throws(() => { e = new ARCModelStateDeleteEvent(undefined); }); assert.isUndefined(e); }); it('has readonly store property', () => { const e = new ARCModelStateDeleteEvent(store); assert.deepEqual(e.store, store, 'has the id property'); assert.throws(() => { // @ts-ignore e.store = 'other'; }); }); }); });
25.64539
79
0.537058
3d6b30cf83327ed774516e334ff65f9d08ccdf33
4,514
js
JavaScript
scripts/examples_postinstall.js
aksmfosef11/react-native-change-icon
9e77faff613da65e67f9f8072c1e764dd3799e9f
[ "MIT" ]
null
null
null
scripts/examples_postinstall.js
aksmfosef11/react-native-change-icon
9e77faff613da65e67f9f8072c1e764dd3799e9f
[ "MIT" ]
null
null
null
scripts/examples_postinstall.js
aksmfosef11/react-native-change-icon
9e77faff613da65e67f9f8072c1e764dd3799e9f
[ "MIT" ]
null
null
null
#!/usr/bin/env node /* * Using libraries within examples and linking them within packages.json like: * "react-native-library-name": "file:../" * will cause problems with the metro bundler if the example will run via * `react-native run-[ios|android]`. This will result in an error as the metro * bundler will find multiple versions for the same module while resolving it. * The reason for that is that if the library is installed it also copies in the * example folder itself as well as the node_modules folder of the library * although their are defined in .npmignore and should be ignored in theory. * * This postinstall script removes the node_modules folder as well as all * entries from the libraries .npmignore file within the examples node_modules * folder after the library was installed. This should resolve the metro * bundler issue mentioned above. * * It is expected this scripts lives in the libraries root folder within a * scripts folder. As first parameter the relative path to the libraries * folder within the example's node_modules folder may be provided. * This script will determine the path from this project's package.json file * if no such relative path is provided. * An example's package.json entry could look like: * "postinstall": "node ../scripts/examples_postinstall.js node_modules/react-native-library-name/" */ 'use strict'; const fs = require('fs'); const path = require('path'); /// Delete all files and directories for the given path const removeFileDirectoryRecursively = fileDirPath => { // Remove file if (!fs.lstatSync(fileDirPath).isDirectory()) { fs.unlinkSync(fileDirPath); return; } // Go down the directory an remove each file / directory recursively fs.readdirSync(fileDirPath).forEach(entry => { const entryPath = path.join(fileDirPath, entry); removeFileDirectoryRecursively(entryPath); }); fs.rmdirSync(fileDirPath); }; /// Remove example/node_modules/react-native-library-name/node_modules directory const removeLibraryNodeModulesPath = (libraryNodeModulesPath) => { const nodeModulesPath = path.resolve(libraryNodeModulesPath, 'node_modules') if (!fs.existsSync(nodeModulesPath)) { // console.log(`No node_modules path found at ${nodeModulesPath}. Skipping delete.`) return; } // console.log(`Deleting: ${nodeModulesPath}`) try { removeFileDirectoryRecursively(nodeModulesPath); // console.log(`Successfully deleted: ${nodeModulesPath}`) } catch (err) { // console.log(`Error deleting ${nodeModulesPath}: ${err.message}`); } }; /// Remove all entries from the .npmignore within example/node_modules/react-native-library-name/ const removeLibraryNpmIgnorePaths = (npmIgnorePath, libraryNodeModulesPath) => { if (!fs.existsSync(npmIgnorePath)) { // console.log(`No .npmignore path found at ${npmIgnorePath}. Skipping deleting content.`); return; } fs.readFileSync(npmIgnorePath, 'utf8').split(/\r?\n/).forEach(entry => { if (entry.length === 0) { return } const npmIgnoreLibraryNodeModulesEntryPath = path.resolve(libraryNodeModulesPath, entry); if (!fs.existsSync(npmIgnoreLibraryNodeModulesEntryPath)) { return; } // console.log(`Deleting: ${npmIgnoreLibraryNodeModulesEntryPath}`) try { removeFileDirectoryRecursively(npmIgnoreLibraryNodeModulesEntryPath); // console.log(`Successfully deleted: ${npmIgnoreLibraryNodeModulesEntryPath}`) } catch (err) { // console.log(`Error deleting ${npmIgnoreLibraryNodeModulesEntryPath}: ${err.message}`); } }); }; // Main start sweeping process (() => { // Read out dir of example project const exampleDir = process.cwd(); // // console.log(`Starting postinstall cleanup for ${exampleDir}`); // Resolve the React Native library's path within the example's node_modules directory const libraryNodeModulesPath = process.argv.length > 2 ? path.resolve(exampleDir, process.argv[2]) : path.resolve(exampleDir, 'node_modules', require('../package.json').name); // // console.log(`Removing unwanted artifacts for ${libraryNodeModulesPath}`); removeLibraryNodeModulesPath(libraryNodeModulesPath); const npmIgnorePath = path.resolve(__dirname, '../.npmignore'); removeLibraryNpmIgnorePaths(npmIgnorePath, libraryNodeModulesPath); })();
40.303571
101
0.704475
3d6b39d7a0961336e73525581f277ebd45cbd04e
4,005
js
JavaScript
Node/examples/dropbox/upload.js
sachinpatil2/botauth
97a57245383acd1791517ae7cdca08af59bb8f66
[ "MIT" ]
21
2017-05-08T15:15:41.000Z
2018-01-03T14:03:57.000Z
Node/examples/dropbox/upload.js
sachinpatil2/botauth
97a57245383acd1791517ae7cdca08af59bb8f66
[ "MIT" ]
9
2017-06-08T23:01:55.000Z
2018-01-11T22:53:47.000Z
Node/examples/dropbox/upload.js
sachinpatil2/botauth
97a57245383acd1791517ae7cdca08af59bb8f66
[ "MIT" ]
17
2017-01-27T17:22:32.000Z
2017-12-25T23:52:18.000Z
"use strict"; const url = require("url"); const https = require("https"); const restify = require("restify"); const envx = require("envx"); const Dropbox = require("dropbox"); //bot application identity const MICROSOFT_APP_ID = envx("MICROSOFT_APP_ID"); const MICROSOFT_APP_PASSWORD = envx("MICROSOFT_APP_PASSWORD"); /** * */ function getSourceToken(callback) { restify.createStringClient({ url : "https://login.microsoftonline.com" }).post({ path : "/common/oauth2/v2.0/token" }, { grant_type : "client_credentials", scope : "https://graph.microsoft.com/.default", client_id : MICROSOFT_APP_ID, client_secret : MICROSOFT_APP_PASSWORD }, (tokenErr, tokenRequest, tokenResponse, tokenData) => { let tokenResult = JSON.parse(tokenData); callback(tokenErr, tokenResult.access_token); }); } function getSourceMeta(options, callback) { let u = url.parse(options.sourceUrl.replace("/views/original", "")); let token = options.sourceToken; let client = restify.createClient({ url : url.resolve(u, "/"), headers : { Authorization : `Bearer ${token}` } }); let cb = 0; client.get(u.path, (err, req) => { req.on("result", function(err, result) { if(err) { return callback(err); } var data = ""; result.on("data", function(chunk) { data += chunk; }); result.on("end", function() { callback(null, data); }); }); }); } /** * */ function getSourceData(options, callback) { let u = url.parse(options.sourceUrl); let token = options.sourceToken; let client = restify.createClient({ url : url.resolve(u, "/"), headers : { Authorization : `Bearer ${token}` } }); let cb = 0; client.get(u.path, (err, req) => { req.on("result", callback); }); } /** * */ function dropboxUpload(options, callback) { let args = { "path": options.path, "mode": "add", "autorename": true, "mute": false }; let client = restify.createClient({ url : "https://content.dropboxapi.com", headers : { Authorization : `Bearer ${options.dropboxToken}`, "Content-Type" : "application/octet-stream", "Dropbox-API-Arg" : JSON.stringify(args) } }); client.post({ path : "/2/files/upload"}, (err, req) => { if(err) { //connection error return callback (err, null); } req.on("result", (resErr, res) => { if(resErr) { // http error return callback (resErr, null); } let buffs = []; res.on("data", (chunk) => { buffs.push(Buffer.from(chunk)); }); res.on("end", () => { let raw = Buffer.concat(buffs).toString("utf8"); let json = JSON.parse(raw); return callback(null, json); }); }); options.sourceStream.pipe(req); }); } /** * */ function upload(options, callback) { getSourceToken((tokenErr, token) => { if(tokenErr) { callback(tokenErr, null); } getSourceMeta({ sourceUrl : options.sourceUrl, sourceToken : token }, (metaErr, meta) => { if(metaErr) { return callback(metaErr); } getSourceData({ sourceUrl : options.sourceUrl, sourceToken : token }, (sourceErr, sourceStream) => { if(sourceErr) { return callback(sourceErr, null); } dropboxUpload({ dropboxToken : options.dropboxToken, path : options.path, sourceStream : sourceStream }, callback); }); }); }); } module.exports = upload;
25.188679
131
0.518102
3d6bb8b0dda3d1806399cd6fc95158fa1ed4e133
22,879
js
JavaScript
sparrow-web/sparrow-myweb/src/main/webapp/js/common/tree/tree.js
aniu2002/sparrow-egg
aea640b4339ea24d7bfd32311f093560573635d3
[ "Apache-2.0" ]
1
2020-09-20T11:34:23.000Z
2020-09-20T11:34:23.000Z
sparrow-web/sparrow-myweb/src/main/webapp/js/common/tree/tree.js
aniu2002/sparrow-egg
aea640b4339ea24d7bfd32311f093560573635d3
[ "Apache-2.0" ]
3
2020-06-15T19:40:40.000Z
2022-01-27T16:15:21.000Z
sparrow-web/sparrow-myweb/src/main/webapp/js/common/tree/tree.js
aniu2002/sparrow-egg
aea640b4339ea24d7bfd32311f093560573635d3
[ "Apache-2.0" ]
null
null
null
// JavaScript Document function DemoTree(el) { this.defaultChildClass = null; this.domNode = (typeof (el) == 'string' ? document.getElementById(el) : el) || document.createElement("DIV"); this.containerNode = null; this.treeId = ''; this.needNodeIco = false; this.needCheckbox = false; this.checkProfix = "DemoCheck"; this.nodeTemplate = null; this.expandNodeTemplate = null; this.labelNodeTemplate = null; this.contentNodeTemplate = null; this.parent = null; this.children = []; this.listeners = []; this.selectedNode = null; this.isTree = true; this.defaultEventNames = { onexpand : null, oncollapse : null, onclick : null, oncontextmenu : "oncontextmenu", onselect : null }; } // DemoTree.defaultEventNames={onexpand:null,oncollapse:null,onclick:null,oncontextmenu:null,onselect:null}; DemoTree.prototype = { createNode : function(data, parent) { data.tree = this.treeId; if (this.defaultChildClass.createTreeNode) { return this.defaultChildClass.createTreeNode(this, parent, data); // tree,parent,data } }, makeNodeTemplate : function(isRoot) { var domNode = document.createElement("div"); var expandNode = document.createElement("span"); var labelNode = document.createElement("span"); var contentNode = document.createElement("div"); // 设置class this.nodeTemplate = domNode; domNode.className = "TreeNode TreeExpandLeaf"; this.expandNodeTemplate = expandNode; expandNode.className = "TreeExpand TreeIEExpand"; this.labelNodeTemplate = labelNode; labelNode.className = "TreeLabel"; this.contentNodeTemplate = contentNode; contentNode.className = "TreeContent TreeIEContent"; domNode.appendChild(expandNode); domNode.appendChild(contentNode); contentNode.appendChild(labelNode); }, makeContainerNodeTemplate : function() { var div = document.createElement("div"); div.style.display = "none"; this.containerNodeTemplate = div; }, initialize : function(args) { this.domNode.treeId = this.treeId; this.defaultChildClass = DemoTreeNodeUtil; this.makeNodeTemplate(true); this.makeContainerNodeTemplate(); this.containerNode = this.domNode; }, removeChildren : function() { while (this.containerNode.childNodes.length > 0) { this.containerNode.removeChild(this.containerNode.childNodes[0]); } }, clear : function() { while (this.containerNode.childNodes.length > 0) { this.containerNode.removeChild(this.containerNode.childNodes[0]); } this.children = undefined; }, hasChild : function() { return typeof (this.children) != 'undefined' && this.children.length > 0; }, setChildren : function(childrenArray) { var f = this.hasChild(); if (f && childrenArray.length > 0) this.removeChildren(); if (childrenArray) this.children = childrenArray; f = this.hasChild(); if (!f) return; var lastIndex = this.children.length - 1; for ( var i = 0; i < this.children.length; i++) { var child = this.children[i]; if (i == lastIndex) child.isLastChild = true; else child.isLastChild = false; child.isRoot = true; if (typeof (child) == "object") { child = this.children[i] = this.createNode(child, this); } if (!child.parent) { child.parent = this; // child.viewAddLayout(); } this.containerNode.appendChild(child.domNode); // } }, listenTree : function(tree) { if (typeof (tree) != "object") return; }, registryEventHandle : function(eventName, handleObj) // {listener,handlemethod} { if (handleObj.listener == null) handleObj.listener = this; handleObj.handle = null; this.defaultEventNames[eventName] = handleObj; }, addListener : function(listener) { if (listener.init) listener.init(); listener.tree = this; this.listeners[this.listeners.length] = listener; }, toString : function() { return 'DemoTree--' + this.treeId; } } function DemoTreeNodeUtil() { } DemoTreeNodeUtil.createTreeNode = function(tree, pare, para) { var treeNode = new DemoTreeNode(); for ( var ar in para) { treeNode[ar] = para[ar]; } treeNode.tree = tree; treeNode.parent = pare; treeNode.title = para.title; if (para.folder) para.nodeId = "p_" + para.nodeId; if (typeof (para.nodeId) != "undefined") { treeNode.nodeId = para.nodeId; } else if (typeof (para.cid) != "undefined") { treeNode.nodeId = para.cid; } else if (typeof (para.serialid) != "undefined") { treeNode.nodeId = para.serialid; // 应是nodeId } if (typeof (para.pid) != "undefined") { treeNode.pid = para.pid; } treeNode.isLastChild = para.isLastChild; if (typeof (para.folder) == "undefined") treeNode.isFolder = false; else treeNode.isFolder = para.folder; if (para.children && para.children.length) treeNode.children = para.children; if (treeNode.children && treeNode.children.length > 0) { treeNode.isFolder = true; } if (treeNode.isRoot) treeNode.initTemplate(true); else treeNode.initTemplate(); treeNode.initContainer(); return treeNode; } DemoTreeNodeUtil.createFunction = function(obj, strFunc, args) { if (!obj) obj = window; return function() { obj[strFunc].apply(obj, args); } } DemoTreeNodeUtil.removeArray = function(arry, index) { if (arry.length) { var len = arry.length; if (arry.length < index + 1) return; for ( var i = index; i < arry.length - 1; i++) { arry[i] = arry[i + 1]; arry[i].index = i; } arry[len - 1] = null; arry.length = len - 1; } } DemoTreeNodeUtil.doHandleCheckbox = function(node) { var state = node.checkNode.checked; DemoTreeNodeUtil.doSelectedSubs(node, state); DemoTreeNodeUtil.doSelectedParent(node.parent); if (DemoTreeNodeUtil.afterCheckHandle) { DemoTreeNodeUtil.checkedNodes = []; DemoTreeNodeUtil.selectCheckedNodes(node.tree); DemoTreeNodeUtil.afterCheckHandle(DemoTreeNodeUtil.checkedNodes); } } DemoTreeNodeUtil.doSelectedSubs = function(node, state) { if (node.children == null) return; if (typeof (node.children.length) == "undefined") return; for ( var i = 0; i < node.children.length; i++) { var treeNode = node.children[i]; if (treeNode.checkNode != null) { treeNode.checkNode.checked = state; DemoTreeNodeUtil.doSelectedSubs(treeNode, state); } } } DemoTreeNodeUtil.doSelectedParent = function(node) { if (node == null) return; if (node.isTree) return; if (node.children == null) return; if (DemoTreeNodeUtil.searchBrother(node.children)) { if (node.checkNode != null) node.checkNode.checked = true; } else { if (node.checkNode != null) node.checkNode.checked = false; } if (node.parent == null) return; else DemoTreeNodeUtil.doSelectedParent(node.parent); } DemoTreeNodeUtil.searchBrother = function(children) { if (children == null) return false; if (typeof (children.length) == "undefined") return false; for ( var i = 0; i < children.length; i++) { var node = children[i]; if (node.checkNode != null) { if (node.checkNode.checked == false) return false; } } return true; } DemoTreeNodeUtil.getCheckedNodes = function(node) { var str = ""; if (node == null) return null; if (node.children == null) return null; for ( var i = 0; i < node.children.length; i++) { var tnod = node.children[i]; if (tnod.children == null || tnod.children.length < 1) { if (tnod.checkNode != null && tnod.checkNode.checked == true) { str += "," + tnod.nodeId; } } else { /* * if(tnod.checkNode!=null&&tnod.checkNode.checked==true){ * str+=","+tnod.nodeId; } */ var temp = DemoTreeNodeUtil.getCheckedNodes(tnod); if (temp != null && temp != "") { str += "," + temp; } } } if (str != "") { str = str.substring(1); } return str; }; /** * 查询树的某个接点 返回treeNode对象 */ DemoTreeNodeUtil.searchNodeById = function(node, nid) { if (node == null) return null; if (node.children == null) return null; // alert(node.children.length); for ( var i = 0; i < node.children.length; i++) { var tnod = node.children[i]; var neid = "" + tnod.nodeId; if (neid == nid) { return tnod; } else if (tnod.isFolder && tnod.children != null && tnod.children.length > 0) { var nod = DemoTreeNodeUtil.searchNodeById(tnod, nid); if (nod != null) return nod; } } return null; }; function DemoTreeNode() { this.nodeId = ""; this.srcTreeId = ""; this.domNode = null; this.expandNode = null; this.contentNode = null; this.labelNode = null; this.parent = null; this.title = null; this.tree = null; this.children = []; this.isFolder = false; this.isTreeNode = true; this.state = false; this.loadStates = { LOADED : true, UNLOADED : false }; this.containerNode = null; this.isLastChild = false; this.isExpanded = false; this.isLoaded = false; this.domNodeClassName = "TreeNode"; } DemoTreeNode.prototype = { initTemplate : function(isRoot) { this.domNode = this.tree.nodeTemplate.cloneNode(true); this.expandNode = this.domNode.firstChild; this.contentNode = this.domNode.childNodes[1]; this.labelNode = this.contentNode.firstChild; var isRt = (typeof (isRoot) == "undefined") ? false : true; if (this.nodeId == null || this.nodeId == "") this.domNode.nodeId = this.domNode.uniqueID; this.domNode.nodeId = this.nodeId; this.labelNode.innerHTML = this.title; var clasName = "TreeNode"; if (isRt) clasName = "TreeIsRoot"; if (this.isFolder) { if (this.isExpanded) clasName += " TreeExpandOpen"; else clasName += " TreeExpandClosed"; } else clasName += " TreeExpandLeaf"; // this.labelNode.onmousedown = DemoTreeNodeUtil.createFunction(this, // "registryListener", [ "draglistener", "onmousedown", this ]); // this.contentNode.onmouseover = DemoTreeNodeUtil.createFunction(this, // "registryListener", [ "draglistener", "onmouseover", this ]); // this.contentNode.onmouseout = DemoTreeNodeUtil.createFunction(this, // "registryListener", [ "draglistener", "onmouseout", this ]); // this.labelNode.onmouseup=DemoTreeNodeUtil.createFunction(this,"registryListener",["draglistener","onmouseup",this]); this.expandNode.onclick = DemoTreeNodeUtil.createFunction(this, "processExpandClick", [ this ]); // this.labelNode.oncontextmenu = DemoTreeNodeUtil.createFunction(this, // "processLabelNodeEvent", [ "oncontextmenu", this ]); // this.labelNode.onfocus = DemoTreeNodeUtil.createFunction(this, // "processLabelNodeEvent", [ "onlabelfocus", this ]); // this.labelNode.onclick=DemoTreeNodeUtil.createFunction(this,"processLabelSelected",[this]); // //"onlabelclick", this.labelNode.onclick = DemoTreeNodeUtil.createFunction(this, "processLabelNodeEvent", [ "onlabelclick", this ]); if (this.isLastChild) clasName += " TreeIsLast"; this.domNodeClassName = clasName; this.domNode.className = clasName; this.domNode.descname = "container"; // this.domNode.style.zIndex = 5; if (!this.isFolder) { Common.addEvent(this.labelNode, 'mouseover', this.mouseOver); Common.addEvent(this.labelNode, 'mouseout', this.mouseOut); } this.createIconNode(this); }, mouseOver : function() { //$(this).css({cursor:'pointer'}); this.style.cssText = "cursor:pointer;"; //this.style.cursor = 'hand'; }, mouseOut : function() { this.style.cssText = "cursor:default;"; //$(this).css({cursor:'default'}); }, createIconNode : function(node) { var needIco = node.tree.needNodeIco; var needCheck = node.tree.needCheckbox; var prefix = "Tree"; if (needIco) { node.contentIconNode = document.createElement("div"); var clazz = prefix + "IconContent"; var ftype = ""; if (node.isFolder) ftype = "Folder"; else if(node.icon) ftype = "Folderx"; else ftype = "Document"; //if (node.icon) // ftype = "v"; node.contentIconNode.className = clazz; node.contentNode.parentNode.replaceChild(node.contentIconNode, node.expandNode); node.iconNode = document.createElement("div"); var iconclass = prefix + "Icon" + " " + prefix + "Icon" + ftype; node.iconNode.className = iconclass; node.contentIconNode.appendChild(node.expandNode); node.contentIconNode.appendChild(node.iconNode); } if (needCheck) { var tex = document.createTextNode(node.title); node.checkNode = document.createElement("input"); // node.checkNode.srcNode=node; node.checkNode.setAttribute("type", "checkbox"); var lid = this.tree.checkProfix + node.nodeId; node.checkNode.setAttribute("id", lid, 1); node.checkNode.onclick = DemoTreeNodeUtil.createFunction( DemoTreeNodeUtil, 'doHandleCheckbox', [ node ]); // node.checkNode.setAttribute("checked",true,1); node.labelNode.innerHTML = ""; node.labelNode.appendChild(node.checkNode); node.labelNode.appendChild(tex); // node.checkNode.checked=true; } }, updateIconNodeView : function(node) { var prefix = "Tree"; var clazz = prefix + "IconContent"; var ftype = ""; if (node.isFolder) ftype = "Folder"; else ftype = "Document"; if (node.contentIconNode) node.contentIconNode.className = clazz; var iconclass = prefix + "Icon" + " " + prefix + "Icon" + ftype; if (node.iconNode) node.iconNode.className = iconclass; }, initContainer : function() { this.containerNode = this.tree.containerNodeTemplate.cloneNode(true); this.domNode.appendChild(this.containerNode); }, setFolder : function() { this.isFolder = true; }, removeChildren : function() { while (this.containerNode.childNodes.length > 0) { this.containerNode.removeChild(this.containerNode.childNodes[0]); } this.children = []; }, clear : function() { while (this.containerNode.childNodes.length > 0) { this.containerNode.removeChild(this.containerNode.childNodes[0]); } this.children = []; }, showChildren : function() { if (this.state == false) this.updateView(); this.domNodeClassName = this.domNodeClassName.replace( "TreeExpandClosed", "TreeExpandOpen"); this.domNode.className = this.domNodeClassName; this.containerNode.style.display = "block"; this.isExpanded = true; }, collapse : function() { this.domNodeClassName = this.domNodeClassName.replace("TreeExpandOpen", "TreeExpandClosed"); this.domNode.className = this.domNodeClassName; this.containerNode.style.display = "none"; this.isExpanded = false; }, expand : function() { this.showChildren(); }, hidden : function() { this.collapse(); }, updateNodeView : function(treeNode) { var clasName = "TreeNode"; if (treeNode == null) return; if (treeNode.isFolder) { if (treeNode.isExpanded) clasName += " TreeExpandOpen"; else clasName += " TreeExpandClosed"; } else clasName += " TreeExpandLeaf"; if (treeNode.isLastChild) clasName += " TreeIsLast"; treeNode.domNodeClassName = clasName; treeNode.domNode.className = clasName; this.updateIconNodeView(treeNode); }, hasChild : function() { return this.children && this.children.length > 0; }, updateView : function() { if (!this.hasChild()) return; var lastIndex = this.children.length - 1; for ( var i = 0; i < this.children.length; i++) { var child = this.children[i]; if (child.parent && child.parent == this) { if (child.isLastChild && i < lastIndex) { child.isLastChild = false; this.updateNodeView(child); } if (child.isLastChild == false && i == lastIndex) { child.isLastChild = true; this.updateNodeView(child); } continue; } if (i == lastIndex) child.isLastChild = true; else child.isLastChild = false; if (typeof (child) == "object") { child = this.children[i] = this.tree.createNode(child, this); } if (!child.parent) { child.parent = this; } this.children[i].index = i; this.containerNode.appendChild(child.domNode); // // 添加了后才能设置checkbox的长度 if (child.parent != null && child.parent.checkNode != null) { child.checkNode.checked = child.parent.checkNode.checked; } } this.state = true; }, setChildren : function(childrenArray) { if (this.isTreeNode && !this.isFolder) { this.setFolder(); } else { if (this.isTreeNode) this.state = this.loadStates.LOADED; } var hadChildren = this.children && this.children.length > 0; if (hadChildren && childrenArray) { this.removeChildren(); } if (childrenArray) { this.children = childrenArray; } var hasChildren = this.children && this.children.length > 0; if (!hasChildren) return; var lastIndex = this.children.length - 1; for ( var i = 0; i < this.children.length; i++) { var child = this.children[i]; if (i == lastIndex) child.isLastChild = true; else child.isLashChild = false; if (typeof (child) == "object") { child = this.children[i] = this.tree.createNode(child, this); } this.children[i].index = i; if (!child.parent) { child.parent = this; } this.containerNode.appendChild(child.domNode); // } this.state = true; }, addChild : function(data) // var data={title:""}; { var child = this.tree.createNode(data, this); if (data.title == null || data.title == "") return; if (this.isFolder == false) { this.domNodeClassName = "TreeNode TreeExpandClosed"; if (this.isLastChild) this.domNodeClassName += " TreeIsLast"; this.domNode.className = this.domNodeClassName; this.isFolder = true; } this.updateIconNodeView(this); this.state = false; this.children[this.children.length] = data; this.showChildren(); }, removeChild : function(index) { if (index >= this.children.length || index < 0) return; this.containerNode.removeChild(this.children[index].domNode); DemoTreeNodeUtil.removeArray(this.children, index); if (this.children.length == 0) { this.isFolder = false; this.updateNodeView(this); } else { var snode = this.children[this.children.length - 1]; snode.isLastChild = true; this.updateNodeView(snode); } }, processLabelSelected : function(treeNode) { if (this.tree.selectedNode) this.tree.selectedNode.labelNode.className = "TreeLabelDefault"; treeNode.labelNode.className = "TreeLabelFocused"; this.tree.selectedNode = treeNode; }, processLabelNodeEvent : function(eventName, treeNode) { this.bindListener(eventName, treeNode); }, processExpandClick : function(treeNode) { if (treeNode.isFolder == false) return; var eventName = "onexpand"; if (treeNode.isExpanded) eventName = "oncollapse"; this.bindListener(eventName, treeNode); }, registryListener : function(listentype, eventName, node) { this.bindListener(eventName, node, listentype); }, bindListener : function(eventName, node, listentype) { var treeListener = this.tree.listeners; var listenType = null; if (typeof (listentype) != "undefined") { listenType = listentype; } if (listenType != null && listenType != "undefined") { for ( var i = 0; i < treeListener.length; i++) { if (treeListener[i].type == listenType) { treeListener[i].fireEvent(eventName, node); } } return; } for ( var i = 0; i < treeListener.length; i++) { treeListener[i].fireEvent(eventName, node); } }, toString : function() { return "[tree_node]--" + this.title; } }; function BaseController() { this.tree = null; this.type = "actionlistener"; } BaseController.defaultEventHandle = { onexpand : "expand", oncollapse : "collapse", onlabelfocus : "labelFocus", onlabelclick : "labelClick", onmousedown : "onmousedown", onmouseover : "onmouseover", onmouseout : "onmouseout" }; // ,oncontextmenu:'oncontextmenu' BaseController.prototype = { fireEvent : function(eventName, treeNode) { var funname = BaseController.defaultEventHandle[eventName]; if (!funname) return; if (this[funname]) this[funname](eventName, treeNode); }, expand : function(eventName, treeNode) { treeNode.expand(); }, collapse : function(eventName, treeNode) { treeNode.collapse(); }, oncontextmenu : function(eventName, treeNode) { this.selectNode(treeNode); }, labelFocus : function(eventName, treeNode) { treeNode.labelNode.className = 'TreeLabelFocused'; }, labelClick : function(eventName, treeNode) { if (this.tree.needCheckbox) return; else this.selectNode(treeNode); // alert('ok'); DemoTreeNodeUtil.handleLabelClick(treeNode); // alert(treeNode.nodeId); // treeNode.labelNode.className='TreeLabelFocused'; }, expandAll : function(node) { this._expandAll(node); }, _expandAll : function(node) { if (node.children == null) return; if (typeof (node.children.length) == "undefined") return; for ( var i = 0; i < node.children.length; i++) { var treeNode = node.children[i]; if (treeNode.isTreeNode) { treeNode.expand(); this._expandAll(treeNode); } } }, expandToLeval : function(node, deep) { this._expandToLeval(node, 1, deep); }, _expandToLeval : function(node, leval, final) { if (leval > final) return; leval = leval + 1; if (node.children == null) return; if (typeof (node.children.length) == "undefined") return; for ( var i = 0; i < node.children.length; i++) { var treeNode = node.children[i]; if (treeNode.isTreeNode) { treeNode.expand(); this._expandToLeval(treeNode, leval, final); } } }, selectNode : function(treeNode) { if (this.tree.selectedNode) { var clas = this.tree.selectedNode.labelNode.className; clas = clas.replace("TreeLabelFocused", ""); this.tree.selectedNode.labelNode.className = clas; } treeNode.labelNode.className = "TreeLabelFocused"; this.tree.selectedNode = treeNode; }, onmousedown : function() { }, getSelectedNode : function() { return this.tree.selectedNode; }, onmouseover : function() { }, onmouseout : function() { }, getCheckedItems : function() { return DemoTreeNodeUtil.getCheckedNodes(this.tree); }, toString : function() { return " BaseController : "; } }; DemoTreeNodeUtil.checkedNodes = []; DemoTreeNodeUtil.selectCheckedNodes = function(node) { if (node == null) return null; if (node.children == null) return null; for ( var i = 0; i < node.children.length; i++) { var tnod = node.children[i]; if (tnod.checkNode != null && tnod.checkNode.checked == true) if (tnod.isFolder) DemoTreeNodeUtil.featchCheckedNodes(tnod); // folder // 其下的子接点未展开所以无checkedNode else { DemoTreeNodeUtil.checkedNodes.push(tnod); } else if (tnod.isFolder) { DemoTreeNodeUtil.selectCheckedNodes(tnod); } } }; DemoTreeNodeUtil.featchCheckedNodes = function(node) { if (node == null) return null; if (node.children == null) return null; for ( var i = 0; i < node.children.length; i++) { var tnod = node.children[i]; if (tnod.children == null || tnod.children.length < 1) { if (!tnod.isFolder) DemoTreeNodeUtil.checkedNodes.push(tnod); } DemoTreeNodeUtil.featchCheckedNodes(tnod); } }; DemoTreeNodeUtil.handleLabelClick = function() { };
25.998864
121
0.677565
3d6c2f9d02d4ed46206be726bb60dda8f412983f
1,229
js
JavaScript
index.js
makbol/gulp-inline-source
7d2edf4b5e48d29a495cb5c976d3073f699b02fc
[ "MIT" ]
null
null
null
index.js
makbol/gulp-inline-source
7d2edf4b5e48d29a495cb5c976d3073f699b02fc
[ "MIT" ]
null
null
null
index.js
makbol/gulp-inline-source
7d2edf4b5e48d29a495cb5c976d3073f699b02fc
[ "MIT" ]
null
null
null
var { inlineSource } = require('inline-source'), PluginError = require('plugin-error'), path = require('path'), through = require('through2'); const PLUGIN_NAME = 'gulp-inline-source'; function gulpInlineSource (options) { 'use strict'; return through.obj(function (file, enc, cb) { var self = this; if (file.isNull() || file.isDirectory()) { this.push(file); return cb(); } if (file.isStream()) { this.emit('error', new PluginError(PLUGIN_NAME, 'Streaming not supported')); return cb(); } var fileOptions = { rootpath: path.dirname(file.path), htmlpath: file.path }; if (options) { for (var i in options) { fileOptions[i] = options[i]; } } inlineSource(file.contents.toString(), fileOptions) .then(html => { file.contents = Buffer.from(html || ''); self.push(file); cb(); }) .catch(err => { self.emit('error', new PluginError(PLUGIN_NAME, err)); }); }); } module.exports = gulpInlineSource;
25.604167
88
0.500407
3d6ccdfe6921ba91bc6665040292df9e2d3e93b3
45,223
js
JavaScript
irods-cloud-frontend/app/edit/edit.js
kelseyurgo/irods-cloud-browser
65946ed6d3f88ce2f34e96083e0e65ea9543bf71
[ "BSD-2-Clause" ]
19
2015-03-27T14:50:19.000Z
2019-03-26T16:09:46.000Z
irods-cloud-frontend/app/edit/edit.js
kelseyurgo/irods-cloud-browser
65946ed6d3f88ce2f34e96083e0e65ea9543bf71
[ "BSD-2-Clause" ]
204
2015-03-26T12:56:29.000Z
2018-08-21T13:46:30.000Z
irods-cloud-frontend/app/edit/edit.js
kelseyurgo/irods-cloud-browser
65946ed6d3f88ce2f34e96083e0e65ea9543bf71
[ "BSD-2-Clause" ]
18
2016-02-22T18:56:57.000Z
2019-02-12T22:02:39.000Z
'use strict'; angular.module('myApp.edit', ['ngRoute']) .config(['$routeProvider', function($routeProvider) { $routeProvider.when('/edit', { templateUrl: 'edit/edit.html', controller: 'editCtrl', resolve: { dataProfile: function ($route, fileService) { var dataProfile = fileService.retrieveDataProfile($route.current.params.path); return dataProfile; } } }); }]) .directive('onLastRepeat', function () { return function (scope, element, attrs) { if (scope.$last) setTimeout(function () { scope.$emit('onRepeatLast', element, attrs); }, 1); }; }) .controller('editCtrl', ['$scope','$log', 'Upload', '$http', '$location', 'MessageService','globals','breadcrumbsService','virtualCollectionsService','collectionsService','fileService','metadataService','dataProfile',function ($scope, $log, Upload, $http, $location, MessageService, $globals, breadcrumbsService, $virtualCollectionsService, $collectionsService, fileService, metadataService, dataProfile) { $scope.dataProfile = dataProfile; $scope.pop_up_form = ""; $scope.initial_file_content = ""; $scope.initial_rule_string = ""; $scope.file_content = ""; $scope.rule_object = ""; $scope.rule_results_raw = ""; $scope.get_file_content = function () { $log.info("getting file content"); return $http({ method: 'GET', url: $globals.backendUrl('fileEdit'), params: { irodsPath: $scope.dataProfile.parentPath + '/' + $scope.dataProfile.childName } }).success(function (data) { $scope.file_content = data; $scope.initial_file_content = data; }).error(function () { $scope.file_content = ""; }); }; $scope.get_rule_string = function () { $log.info("getting rule object"); return $http({ method: 'GET', url: $globals.backendUrl('rawRule'), params: { irodsPath: $scope.dataProfile.parentPath + '/' + $scope.dataProfile.childName } }).success(function (data) { $scope.rule_string = data; $scope.initial_rule_string_body = $scope.rule_string.ruleText; $scope.initial_rule_string = data; }).error(function () { $scope.rule_string = ""; }); }; $scope.exec_rule = function () { $log.info("executing rule"); return $http({ method: 'POST', url: $globals.backendUrl('ruleExecution'), params: { rule: $scope.rule_string.ruleText } }).success(function (data) { $scope.rule_results_raw = data; }) }; $scope.save_rule = function () { $log.info("saving rule"); return $http({ method: 'POST', url: $globals.backendUrl('rawRule'), params: { irodsPath: $scope.dataProfile.parentPath + '/' + $scope.dataProfile.childName, rule: $scope.rule_string.ruleText } }).success(function () { MessageService.success("Rule saved!"); $scope.get_rule_string(); }) }; $scope.reload_file_content = function(){ $scope.get_file_content(); }; $scope.reload_rule_string = function(){ $scope.get_rule_string(); $scope.rule_results_raw = ""; }; if($scope.dataProfile.mimeType == "text/plain"){ $scope.editorOptions = { lineWrapping : false, lineNumbers: true }; }else if($scope.dataProfile.mimeType == "application/xml"){ $scope.editorOptions = { lineWrapping : false, lineNumbers: true, mode: {name:"xml", typescript: true} }; }else if($scope.dataProfile.mimeType == "application/irods-rule"){ $scope.editorOptions = { lineWrapping : false, lineNumbers: true, mode: {name:"javascript", typescript: true} }; } $scope.resultsOptions = { lineWrapping : true, lineNumbers: true, readOnly: true, mode: {name:"javascript", typescript: true} }; $http({ method: 'GET', url: $globals.backendUrl('collection/') + 'root', params: { path: $scope.dataProfile.parentPath, offset: 0 } }).then(function (data) { $scope.copy_list = data; }).then(function () { return $http({ method: 'GET', url: $globals.backendUrl('virtualCollection/') + 'root' }) }).then(function (data) { $scope.copyVC = data; $scope.getBreadcrumbPaths(); }); $scope.getBreadcrumbPaths = function () { $scope.breadcrumb_full_array = $scope.copy_list.data.pagingAwareCollectionListingDescriptor.parentAbsolutePath.split("/"); $scope.breadcrumb_full_array.shift(); $scope.breadcrumb_full_array_paths = []; var totalPath = ""; for (var i = 0; i < $scope.breadcrumb_full_array.length; i++) { totalPath = totalPath + "/" + $scope.breadcrumb_full_array[i]; $scope.breadcrumb_full_array_paths.push({b:$scope.breadcrumb_full_array[i],path:totalPath}); } if($scope.breadcrumb_full_array.length > 5){ $scope.breadcrumb_compressed_array = $scope.breadcrumb_full_array_paths.splice(0,($scope.breadcrumb_full_array_paths.length)-5); }else{ $scope.breadcrumb_compressed_array = []; } } $scope.goToBreadcrumb = function (path) { if (!path) { $log.error("cannot go to breadcrumb, no path"); return; } $location.path("/home/root"); $location.search("path", path); }; $scope.$on('onRepeatLast', function (scope, element, attrs) { $(".selectable").selectable({ stop: function () { $('.list_content').removeClass("ui-selected"); $('span').removeClass("ui-selected"); $('img').removeClass("ui-selected"); var result = $("#select-result").empty(); $(".dropdown").removeClass("open"); var copy_path_display = $(".copy_select_result").empty(); if ($(".copy_list_item.ui-selected").length == 1) { var copy_path = $('.copy_list_item.ui-selected').children('.list_content').children('.collection_object').text(); copy_path_display.append(copy_path); $scope.copy_target = $('.copy_list_item.ui-selected').attr('id'); } if ($(".copy_list_item.ui-selected").length > 1) { $('.copy_list_item.ui-selected').not(':first').removeClass('ui-selected'); var copy_path = $('.copy_list_item.ui-selected').children('.list_content').children('.collection_object').text(); copy_path_display.append(copy_path); $scope.copy_target = $('.copy_list_item.ui-selected').attr('id'); } if ($(".move_list_item.ui-selected").length == 1) { var move_path = $('.move_list_item.ui-selected').children('.list_content').children('.collection_object').text(); copy_path_display.append(move_path); $scope.copy_target = $('.move_list_item.ui-selected').attr('id'); } if ($(".move_list_item.ui-selected").length > 1) { $('.move_list_item.ui-selected').not(':first').removeClass('ui-selected'); var move_path = $('.move_list_item.ui-selected').children('.list_content').children('.collection_object').text(); copy_path_display.append(move_path); $scope.move_target = $('.move_list_item.ui-selected').attr('id'); } if ($(".general_list_item .ui-selected").length > 1) { result.append("You've selected: " + $('.general_list_item .ui-selected').length + " items"); $(".download_button").css('opacity', '0.8'); $(".download_button").css('pointer-events', 'auto'); $(".rename_button").css('opacity', '0.1'); $(".rename_button").css('pointer-events', 'none'); $(".rename_divider").css('opacity', '0.8'); $(".download_divider").css('opacity', '0.8'); $(".tablet_download_button").fadeIn(); $(".tablet_rename_button").fadeOut(); $(".empty_selection").fadeOut(); } else if ($(".general_list_item .ui-selected").length == 1) { $scope.selected_target = $('.general_list_item .ui-selected').attr("id"); var name_of_selection = "You've selected: " + $('.ui-selected').children('.list_content').children('.data_object').text(); if (name_of_selection == "You've selected: ") { var name_of_selection = "You've selected: " + $('.ui-selected').children('.list_content').children('.collection_object').text(); } result.append(name_of_selection); $(".download_button").css('opacity', '0.8'); $(".download_button").css('pointer-events', 'auto'); $(".rename_button").css('opacity', '0.8'); $(".rename_button").css('pointer-events', 'auto'); $(".rename_divider").css('opacity', '0.8'); $(".download_divider").css('opacity', '0.8'); $(".tablet_download_button").fadeIn(); $(".tablet_rename_button").fadeIn(); $(".empty_selection").fadeOut(); } else if ($(".general_list_item .ui-selected").length == 0) { $(".download_button").css('opacity', '0.1'); $(".download_button").css('pointer-events', 'none'); $(".rename_button").css('opacity', '0.1'); $(".rename_button").css('pointer-events', 'none'); $(".rename_divider").css('opacity', '0.1'); $(".download_divider").css('opacity', '0.1'); $(".tablet_download_button").fadeOut(); $(".tablet_rename_button").fadeOut(); $(".empty_selection").fadeIn(); } } }); }); /* Get a default list of the virtual collections that apply to the logged in user, for side nav */ $scope.go_back = function(){ if($scope.file_content != $scope.initial_file_content || $scope.rule_string.ruleText != $scope.initial_rule_string_body){ if (confirm('Are you sure you want to leave this page without saving your changes?')) { window.history.go(-1); } else { } }else{ window.history.go(-1); } }; $scope.listVirtualCollections = function () { $log.info("getting virtual colls"); return $http({method: 'GET', url: $globals.backendUrl('virtualCollection')}).success(function (data) { $scope.virtualCollections = data; }).error(function () { $scope.virtualCollections = []; }); }; $scope.listVirtualCollections(); var side_nav_toggled = "yes"; $scope.side_nav_toggle = function () { if (side_nav_toggled == "no") { side_nav_toggled = "yes"; $('.side_nav_options').animate({'opacity': '0'}); $('#side_nav').addClass('collapsed_nav'); $('#side_nav').removeClass('uncollapsed_nav'); $('#main_contents').addClass('uncollapsed_main_contents'); $('#main_contents').removeClass('collapsed_main_contents'); } else if (side_nav_toggled == "yes") { side_nav_toggled = "no"; $('#side_nav').addClass('uncollapsed_nav'); $('#side_nav').removeClass('collapsed_nav'); $('#main_contents').addClass('collapsed_main_contents'); $('#main_contents').removeClass('uncollapsed_main_contents'); $('.side_nav_options').animate({'opacity': '1'}); } }; var toggle_on $scope.side_nav_autotoggle = function (auto_toggle) { if (auto_toggle == 'off') { if (side_nav_toggled == "no") { toggle_on = setTimeout($scope.side_nav_toggle, 1000); } } else if (auto_toggle == 'on') { clearTimeout(toggle_on); } }; $scope.$watch('files', function () { $scope.upload($scope.files); }); $scope.multiple = true; $scope.current_page = 'info_view'; $scope.upload = function (files) { if (files && files.length) { $(".upload_container").css('display','none'); $(".upload_container_result").css('display','block'); for (var i = 0; i < files.length; i++) { var file = files[i]; $(".upload_container_result ul").append('<li id="uploading_item_'+i+'" class="light_back_option_even"><div class="col-xs-7 list_content"><img src="images/data_object_icon.png">'+file.name+'</div></li>'); Upload.upload({ url: $globals.backendUrl('file') , fields:{collectionParentName: $scope.dataProfile.parentPath + "/" +$scope.dataProfile.childName}, file: file }).progress(function (evt) { var progressPercentage = parseInt(100.0 * evt.loaded / evt.total); $log.info(progressPercentage); }).success(function (data, status, headers, config) { console.log('file ' + config.file.name + 'uploaded. Response: ' + data); }); } } }; $scope.save_content_action = function () { $log.info("saving file content"); return $http({ method: 'POST', url: $globals.backendUrl('fileEdit'), params: { data:$scope.file_content, irodsPath: $scope.dataProfile.parentPath + '/' + $scope.dataProfile.childName } }).success(function (data) { MessageService.success("File saved!"); $scope.get_file_content(); }).error(function () { }); }; $scope.get_file_content(); $scope.get_rule_string(); $scope.delete_action = function (){ var delete_paths = $scope.dataProfile.parentPath + "/" +$scope.dataProfile.childName; $log.info('Deleting:'+delete_paths); return $http({ method: 'DELETE', url: $globals.backendUrl('file'), params: { path : delete_paths } }).then(function (data) { MessageService.info("Deletion completed!"); window.history.back(); }) }; $scope.rename_action = function (){ var rename_path = $scope.dataProfile.parentPath + "/" + $scope.dataProfile.childName; var new_name = $('#new_renaming_name').val(); var old_url = window.location; var n = String(old_url).lastIndexOf("%2F"); var new_url = String(old_url).substr(0,n); var new_url = new_url + "%2F" + new_name; $log.info('Renaming:'+rename_path); var data_name_unique = 'yes'; for (var i = 0; i < $scope.copy_list.data.collectionAndDataObjectListingEntries.length; i++) { var file = $scope.copy_list.data.collectionAndDataObjectListingEntries[i]; if (new_name === file.nodeLabelDisplayValue) { MessageService.danger('There is already an item named "' + new_name + '", please choose a different name'); data_name_unique = "no"; $('#new_renaming_name').addClass('has_error'); $('#new_renaming_name').focus(); } } if(data_name_unique === "yes"){ $log.info('Renaming:' + rename_path ); $http({ method: 'PUT', url: $globals.backendUrl('rename'), params: {path: rename_path, newName: new_name} }).then(function (data) { MessageService.success("Renaming completed!"); location.assign(new_url); }) } }; $scope.copy_action = function (){ $scope.copy_source = $scope.dataProfile.parentPath + "/" + $scope.dataProfile.childName; $log.info('||||||||||||| copying:'+ $scope.copy_source +' to '+ $scope.copy_target); $http({ method: 'POST', url: $globals.backendUrl('copy'), params: {sourcePath: $scope.copy_source, targetPath: $scope.copy_target, resource:'', overwrite: 'false' } }).then(function () { MessageService.success("Copy completed!"); $scope.pop_up_close_clear(); }) }; $scope.move_action = function (){ $scope.copy_source = $scope.dataProfile.parentPath + "/" + $scope.dataProfile.childName; var new_name = $scope.dataProfile.childName; var old_url = window.location; var n = String(old_url).lastIndexOf("="); var new_url = String(old_url).substr(0,n); var new_url = new_url + "=" + $scope.copy_target + "%2F" + new_name; $log.info('||||||||||||| moving:'+ $scope.copy_source +' to '+ $scope.copy_target); $http({ method: 'POST', url: $globals.backendUrl('move'), params: {sourcePath: $scope.copy_source, targetPath: $scope.copy_target, resource:'', overwrite: 'false' } }).then(function () { MessageService.success("Move completed!"); location.assign(new_url); }) }; $scope.logout_func = function () { var promise = $http({ method: 'POST', url: $globals.backendUrl('logout') }).then(function () { // The then function here is an opportunity to modify the response // The return value gets picked up by the then in the controller. //setTimeout(function () { $location.path("/login").search({}); $globals.setLastPath("/home"); //}, 0); }); return promise; }; $scope.getCopyBreadcrumbPaths = function () { $scope.breadcrumb_popup_full_array = $scope.copy_list.data.pagingAwareCollectionListingDescriptor.parentAbsolutePath.split("/"); $scope.breadcrumb_popup_full_array.shift(); $scope.breadcrumb_popup_full_array_paths = []; var popup_totalPath = ""; for (var i = 0; i < $scope.breadcrumb_popup_full_array.length; i++) { popup_totalPath = popup_totalPath + "/" + $scope.breadcrumb_popup_full_array[i]; $scope.breadcrumb_popup_full_array_paths.push({b:$scope.breadcrumb_popup_full_array[i],path:popup_totalPath}); } if($scope.breadcrumb_popup_full_array.length > 5){ $scope.breadcrumb_popup_compressed_array = $scope.breadcrumb_popup_full_array_paths.splice(0,($scope.breadcrumb_popup_full_array_paths.length)-5); }else{ $scope.breadcrumb_popup_compressed_array = []; } } $scope.set_path = function (path_name,path) { var copy_path_display = $(".copy_select_result").empty(); var move_path = path_name; copy_path_display.append(move_path); $scope.copy_target = path; }; $scope.hide_breadcrumbs = function () { $(".dark_back_option_double").removeClass("open"); }; $scope.copy_list_refresh = function (VC, selectedPath) { if(VC == ""){ var pop_up_vc = 'root'; }else{ var pop_up_vc = VC; } $http({ method: 'GET', url: $globals.backendUrl('collection/') + pop_up_vc, params: {path: selectedPath, offset: 0} }).then(function (data) { $scope.copy_list = data; }).then(function () { return $http({ method: 'GET', url: $globals.backendUrl('virtualCollection/') + pop_up_vc }) }).then(function (data) { $scope.copyVC = data; if($scope.copyVC.data.type == 'COLLECTION'){ $scope.getCopyBreadcrumbPaths(); } }); }; $(window).keyup(function($event){ if($event.keyCode == "13"){ if($scope.pop_up_form === "delete"){ $scope.pop_up_form = ""; $scope.delete_action(); } if($scope.pop_up_form === "upload"){ $scope.upload(); } if($scope.pop_up_form === "copy"){ $scope.pop_up_form = ""; $scope.copy_action(); } if($scope.pop_up_form === "move"){ $scope.pop_up_form = ""; $scope.move_action(); } if($scope.pop_up_form === "create"){ $scope.pop_up_form = ""; $scope.create_collection_action(); } if($scope.pop_up_form === "rename"){ $scope.pop_up_form = ""; $scope.rename_action(); } } }); $scope.move_pop_up_open = function(){ $scope.pop_up_form = "move"; $scope.copy_source = $('.general_list_item .ui-selected').attr('id'); $('.pop_up_window').fadeIn(100); var copy_path_display = $(".copy_select_result").empty(); var path_array = $scope.copy_list.data.pagingAwareCollectionListingDescriptor.pathComponents; var current_collection = path_array[path_array.length - 1]; $scope.copy_source = $scope.dataProfile.parentPath + "/" + $scope.dataProfile.childName; $scope.copy_target = $scope.dataProfile.parentPath; copy_path_display.append(current_collection); if ($scope.dataProfile.file == true) { $(".move_container ul").append('<li class="light_back_option_even"><div class="col-xs-12 list_content"><img src="images/data_object_icon.png">' + $scope.dataProfile.childName + '</div></li>'); } else { $(".move_container ul").append('<li class="light_back_option_even"><div class="col-xs-12 list_content"><img src="images/collection_icon.png">' + $scope.dataProfile.childName + '</div></li>'); }; $('.mover').fadeIn(100); $('.mover_button').fadeIn(100); $http({ method: 'GET', url: $globals.backendUrl('virtualCollection') }).then(function (data) { $scope.copy_vc_list = data; $scope.getCopyBreadcrumbPaths(); }); }; $scope.copy_pop_up_open = function(){ $scope.pop_up_form = "copy"; $scope.copy_source = $('.general_list_item .ui-selected').attr('id'); $('.pop_up_window').fadeIn(100); var copy_path_display = $(".copy_select_result").empty(); var path_array = $scope.copy_list.data.pagingAwareCollectionListingDescriptor.pathComponents; var current_collection = path_array[path_array.length - 1]; $scope.copy_source = $scope.dataProfile.parentPath + "/" + $scope.dataProfile.childName; $scope.copy_target = $scope.dataProfile.parentPath; copy_path_display.append(current_collection); if ($scope.dataProfile.file == true) { $(".copy_container ul").append('<li class="light_back_option_even"><div class="col-xs-12 list_content"><img src="images/data_object_icon.png">' + $scope.dataProfile.childName + '</div></li>'); } else { $(".copy_container ul").append('<li class="light_back_option_even"><div class="col-xs-12 list_content"><img src="images/collection_icon.png">' + $scope.dataProfile.childName + '</div></li>'); }; $('.copier').fadeIn(100); $('.copier_button').fadeIn(100); $http({ method: 'GET', url: $globals.backendUrl('virtualCollection') }).then(function (data) { $scope.copy_vc_list = data; $scope.getCopyBreadcrumbPaths(); }); }; $scope.upload_pop_up_open = function(){ $scope.pop_up_form = "upload"; $('.pop_up_window').fadeIn(100); $('.uploader').fadeIn(100); }; $scope.rename_pop_up_open = function(){ $scope.pop_up_form = "rename"; $('.pop_up_window').fadeIn(100); $('.renamer').fadeIn(100); $('#new_renaming_name').focus(); var name_of_selection = $scope.dataProfile.childName; $('.selected_object').append(name_of_selection); }; $scope.delete_pop_up_open = function(){ $scope.pop_up_form = "delete"; $('.pop_up_window').fadeIn(100); if($scope.dataProfile.file == true){ $(".delete_container ul").append('<li class="light_back_option_even"><div class="col-xs-7 list_content"><img src="images/data_object_icon.png">&nbsp;'+$scope.dataProfile.parentPath + "/" +$scope.dataProfile.childName+'</div></li>'); }else{ $(".delete_container ul").append('<li class="light_back_option_even"><div class="col-xs-7 list_content"><img src="images/collection_icon.png">&nbsp;'+$scope.dataProfile.parentPath + "/" +$scope.dataProfile.childName+'</div></li>'); } $('.deleter').fadeIn(100); }; $scope.pop_up_close_clear = function () { $('.pop_up_window').fadeOut(200, function () { $(".move_container ul").empty(); $(".delete_container ul").empty(); $('#new_collection_name').val(''); $('.selected_object').empty(); $('#new_renaming_name').val(''); $('#new_renaming_name').removeClass('has_error'); $('#new_collection_name').removeClass('has_error'); $(".upload_container").css('display', 'block'); $(".upload_container_result ul").empty(); $(".upload_container_result").css('display', 'none'); $('.uploader').fadeOut(100); $('.deleter').fadeOut(100); $('.creater').fadeOut(100); $('.renamer').fadeOut(100); $('.copier').fadeOut(100); $('.mover').fadeOut(100); $('.metadata_adder').fadeOut(100); $('.metadata_editor').fadeOut(100); $('.metadata_deleter').fadeOut(100); $('.copier_button').fadeOut(100); $('.mover_button').fadeOut(100); $scope.pop_up_form = ""; $scope.files_to_upload = []; $scope.files_name = []; $("#select-result").empty(); $(".download_button").animate({'opacity': '0.1'}); $(".download_button").css('pointer-events', 'none'); $(".rename_button").animate({'opacity': '0.1'}); $(".rename_button").css('pointer-events', 'none'); $(".rename_divider").animate({'opacity': '0.1'}); $(".download_divider").animate({'opacity': '0.1'}); $(".tablet_download_button").fadeOut(); $(".tablet_rename_button").fadeOut(); $(".empty_selection").fadeIn(); }); }; $scope.pop_up_close = function () { $('.pop_up_window').fadeOut(200, function () { $(".move_container ul").empty(); $(".delete_container ul").empty(); $('#new_collection_name').val(''); $('.selected_object').empty(); $('#new_renaming_name').val(''); $('#new_renaming_name').removeClass('has_error'); $('#new_collection_name').removeClass('has_error'); $(".upload_container").css('display', 'block'); $(".upload_container_result ul").empty(); $(".upload_container_result").css('display', 'none'); $('.metadata_adder').fadeOut(100); $('.metadata_editor').fadeOut(100); $('.metadata_deleter').fadeOut(100); $('.uploader').fadeOut(100); $('.deleter').fadeOut(100); $('.creater').fadeOut(100); $('.renamer').fadeOut(100); $('.copier').fadeOut(100); $('.mover').fadeOut(100); $('.copier_button').fadeOut(100); $('.mover_button').fadeOut(100); $('#new_metadata_attribute').removeClass('has_error'); $('#new_metadata_value').removeClass('has_error'); $scope.pop_up_form = ""; $scope.files_to_upload = []; $scope.files_name = []; }); }; /* Retrieve the data profile for the data object at the given absolute path */ $scope.selectProfile = function (irodsAbsolutePath, touch_event) { $log.info("going to Data Profile"); if (!irodsAbsolutePath) { $log.error("missing irodsAbsolutePath") MessageService.danger("missing irodsAbsolutePath"); } //alert("setting location.."); //$location.search(null); $location.url("/profile/"); $location.search("path", irodsAbsolutePath); $log.info('end: '+irodsAbsolutePath); if(touch_event == true){ $scope.$apply(); }; }; $(window).mousedown(function(event) { switch (event.which) { case 1: if($(event.target).is("div")){ if ($(event.target).parents().hasClass("ui-selectee") || $(event.target).parents().hasClass("selection_actions_container") || $(event.target).parents().hasClass("pop_up_window")) { }else{ $(".general_list_item .ui-selected").removeClass("ui-selected"); $(".download_button").css('opacity', '0.1'); $(".download_button").css('pointer-events', 'none'); $(".rename_button").css('opacity', '0.1'); $(".rename_button").css('pointer-events', 'none'); $(".rename_divider").css('opacity', '0.1'); $(".download_divider").css('opacity', '0.1'); $(".tablet_download_button").fadeOut(); $(".tablet_rename_button").fadeOut(); $(".empty_selection").fadeIn(); $("#select-result").empty(); } } break; case 3: if ($(".general_list_item .ui-selected").length == 0 || $(".general_list_item .ui-selected").length == 1) { $(".general_list_item .ui-selected").removeClass("ui-selected"); $(event.target).parents("li").addClass("ui-selected","fast",function(){ $(".download_button").css('opacity','0.8'); $(".download_button").css('pointer-events', 'auto'); $(".rename_button").css('opacity','0.8'); $(".rename_button").css('pointer-events', 'auto'); $(".rename_divider").css('opacity','0.8'); $(".download_divider").css('opacity','0.8'); $(".tablet_download_button").fadeIn(); $(".tablet_rename_button").fadeIn(); $(".empty_selection").fadeOut(); }); } if ($(".general_list_item .ui-selected").length > 1) { if(!$(event.target).parents("li").hasClass("ui-selected")){ $(".general_list_item .ui-selected").removeClass("ui-selected"); $(event.target).parents("li").addClass("ui-selected","fast",function(){ $(".download_button").css('opacity','0.8'); $(".download_button").css('pointer-events', 'auto'); $(".rename_button").css('opacity','0.8'); $(".rename_button").css('pointer-events', 'auto'); $(".rename_divider").css('opacity','0.8'); $(".download_divider").css('opacity','0.8'); $(".tablet_download_button").fadeIn(); $(".tablet_rename_button").fadeIn(); $(".empty_selection").fadeOut(); }); } } break; } }); /*||||||||||||||||||||||||||||||| |||||||| METADATA ACTIONS ||||||| |||||||||||||||||||||||||||||||*/ $scope.available_metadata = $scope.dataProfile.metadata; $scope.star_action = function(){ var star_path = $scope.dataProfile.parentPath + "/" + $scope.dataProfile.childName; fileService.starFileOrFolder(star_path).then(function() { $http({method: 'GET', url: $globals.backendUrl('file') , params: {path: $scope.dataProfile.parentPath + "/" + $scope.dataProfile.childName}}).success(function(data){ $scope.new_meta = data; $scope.available_metadata = $scope.new_meta.metadata; }); $scope.pop_up_close_clear(); $scope.dataProfile.starred = true; }); //location.reload(); }; $scope.unstar_action = function(){ var unstar_path = $scope.dataProfile.parentPath + "/" + $scope.dataProfile.childName; //fileService.unstarFileOrFolder(unstar_path); fileService.unstarFileOrFolder(unstar_path).then(function() { $http({method: 'GET', url: $globals.backendUrl('file') , params: {path: $scope.dataProfile.parentPath + "/" + $scope.dataProfile.childName}}).success(function(data){ $scope.new_meta = data; $scope.available_metadata = $scope.new_meta.metadata; }); $scope.pop_up_close_clear(); $scope.dataProfile.starred = false; }); //location.reload(); }; $scope.add_metadata_pop_up = function (){ $('#new_metadata_attribute').val(''); $('#new_metadata_value').val(''); $('#new_metadata_unit').val(''); $('.pop_up_window').fadeIn(100); $('.metadata_adder').fadeIn(100); }; $scope.edit_metadata_pop_up = function (){ $('.pop_up_window').fadeIn(100); $('.metadata_editor').fadeIn(100); $('#edit_metadata_attribute').val($('.metadata_item.ui-selected').children('.metadata_attribute').text()); $('#edit_metadata_value').val($('.metadata_item.ui-selected').children('.metadata_value').text()); $('#edit_metadata_unit').val($('.metadata_item.ui-selected').children('.metadata_unit').text()); $scope.old_metadata_attribute = $('.metadata_item.ui-selected').children('.metadata_attribute').text(); $scope.old_metadata_value = $('.metadata_item.ui-selected').children('.metadata_value').text(); $scope.old_metadata_unit = $('.metadata_item.ui-selected').children('.metadata_unit').text(); }; $scope.delete_metadata_pop_up = function(){ $('.pop_up_window').fadeIn(100); $scope.delete_objects = $('.metadata_item.ui-selected'); $scope.old_metadata_attribute = $('.metadata_item.ui-selected').children('.metadata_attribute').text(); $scope.old_metadata_value = $('.metadata_item.ui-selected').children('.metadata_value').text(); $scope.old_metadata_unit = $('.metadata_item.ui-selected').children('.metadata_unit').text(); $log.info($scope.delete_objects); $(".metadata_delete_container ul").empty(); $(".metadata_delete_container ul").append('<li class="light_back_option_even"><div class="q_column"><b>ATTRIBUTE</b></div><div class="q_column"><b>VALUE</b></div><div class="q_column"><b>UNIT</b></div></li>'); $scope.delete_objects.each(function () { $(".metadata_delete_container ul").append('<li class="light_back_option_even"><div class="q_column">'+$(this).children('.metadata_attribute').text()+'</div><div class="q_column">'+$(this).children('.metadata_value').text()+'</div><div class="q_column">'+$(this).children('.metadata_unit').text()+'</div></li>'); }); $('.metadata_deleter').fadeIn(100); }; $scope.metadata_add_action = function(){ var data_path = $scope.dataProfile.parentPath + "/" + $scope.dataProfile.childName; var new_attribute = $('#new_metadata_attribute').val(); var new_value = $('#new_metadata_value').val(); var new_unit = $('#new_metadata_unit').val(); var att_unique = 'yes'; var value_unique = 'yes'; for (var i = 0; i < $scope.available_metadata.length; i++) { var avu = $scope.available_metadata[i]; if (new_attribute === avu.avuAttribute) { att_unique = "no"; } if (new_value === avu.avuValue) { value_unique = "no"; } } if(value_unique == "no" && att_unique == "no"){ MessageService.danger('There is already an AVU with Attribute: "' + new_attribute + '" and Value: "' + new_value + '". Please choose a different Attribute or Value'); $('#new_metadata_attribute').addClass('has_error'); $('#new_metadata_value').addClass('has_error'); $('#new_metadata_attribute').focus(); }else{ metadataService.addMetadataForPath(data_path, new_attribute, new_value, new_unit).then(function () { $http({method: 'GET', url: $globals.backendUrl('file') , params: {path: $scope.dataProfile.parentPath + "/" + $scope.dataProfile.childName}}).success(function(data){ $scope.new_meta = data; $scope.available_metadata = $scope.new_meta.metadata; }); $scope.pop_up_close_clear(); }); } }; $scope.metadata_edit_action = function(){ var data_path = $scope.dataProfile.parentPath + "/" + $scope.dataProfile.childName; var new_attribute = $('#edit_metadata_attribute').val(); var new_value = $('#edit_metadata_value').val(); var new_unit = $('#edit_metadata_unit').val(); metadataService.updateMetadataForPath(data_path, $scope.old_metadata_attribute, $scope.old_metadata_value, $scope.old_metadata_unit, new_attribute, new_value, new_unit).then(function () { $http({method: 'GET', url: $globals.backendUrl('file') , params: {path: $scope.dataProfile.parentPath + "/" + $scope.dataProfile.childName}}).success(function(data){ $scope.new_meta = data; $scope.available_metadata = $scope.new_meta.metadata; }); $scope.pop_up_close_clear(); }); }; $scope.metadata_delete_action = function(){ var data_path = $scope.dataProfile.parentPath + "/" + $scope.dataProfile.childName; var new_attribute = $('#edit_metadata_attribute').val(); var new_value = $('#edit_metadata_value').val(); var new_unit = $('#edit_metadata_unit').val(); metadataService.deleteMetadataForPath(data_path, $scope.old_metadata_attribute, $scope.old_metadata_value, $scope.old_metadata_unit).then(function () { $http({method: 'GET', url: $globals.backendUrl('file') , params: {path: $scope.dataProfile.parentPath + "/" + $scope.dataProfile.childName}}).success(function(data){ $scope.new_meta = data; $scope.available_metadata = $scope.new_meta.metadata; }); $scope.pop_up_close_clear(); }); }; /*|||||||||||||||||||||||||||||||||||||| |||||||| END OF METADATA ACTIONS ||||||| ||||||||||||||||||||||||||||||||||||||*/ $scope.green_action_toggle= function($event){ var content = $event.currentTarget.nextElementSibling; var container = $event.currentTarget.parentElement; $(content).toggle('normal'); $(container).toggleClass('green_toggle_container_open'); }; $scope.getDownloadLink = function() { return $globals.backendUrl('download') + "?path=" + $scope.dataProfile.domainObject.absolutePath; }; /** * Upon the selection of an element in a breadrumb link, set that as the location of the browser, triggering * a view of that collection * @param index */ }]);
49.915011
410
0.492736
3d6df74d164b1a848a57ca679c007df406ac40de
2,349
js
JavaScript
node_modules/replace-in-file/lib/replace-in-file.js
kube-HPC/load-version
45c7df871b1e5c2162a4977ad6d4eb05e5bc50dc
[ "MIT" ]
1
2020-03-24T09:05:42.000Z
2020-03-24T09:05:42.000Z
node_modules/replace-in-file/lib/replace-in-file.js
kube-HPC/load-version
45c7df871b1e5c2162a4977ad6d4eb05e5bc50dc
[ "MIT" ]
2
2021-03-10T08:32:22.000Z
2021-09-02T06:48:12.000Z
node_modules/replace-in-file/lib/replace-in-file.js
kube-HPC/load-version
45c7df871b1e5c2162a4977ad6d4eb05e5bc50dc
[ "MIT" ]
null
null
null
'use strict'; /** * Dependencies */ const chalk = require('chalk'); const parseConfig = require('./helpers/parse-config'); const getPathsSync = require('./helpers/get-paths-sync'); const getPathsAsync = require('./helpers/get-paths-async'); const replaceSync = require('./helpers/replace-sync'); const replaceAsync = require('./helpers/replace-async'); /** * Replace in file helper */ function replaceInFile(config, cb) { //Parse config try { config = parseConfig(config); } catch (error) { if (cb) { return cb(error, null); } return Promise.reject(error); } //Get config const { files, from, to, encoding, ignore, allowEmptyPaths, disableGlobs, dry, verbose, glob, } = config; //Dry run? //istanbul ignore if: No need to test console logs if (dry && verbose) { console.log(chalk.yellow('Dry run, not making actual changes')); } //Find paths return getPathsAsync(files, ignore, disableGlobs, allowEmptyPaths, glob) //Make replacements .then(paths => Promise.all(paths.map(file => { return replaceAsync(file, from, to, encoding, dry); }))) //Convert results to array of changed files .then(results => { return results .filter(result => result.hasChanged) .map(result => result.file); }) //Success handler .then(changedFiles => { if (cb) { cb(null, changedFiles); } return changedFiles; }) //Error handler .catch(error => { if (cb) { cb(error); } else { throw error; } }); } /** * Sync API */ replaceInFile.sync = function(config) { //Parse config config = parseConfig(config); //Get config, paths, and initialize changed files const { files, from, to, encoding, ignore, disableGlobs, dry, verbose, glob, } = config; const paths = getPathsSync(files, ignore, disableGlobs, glob); const changedFiles = []; //Dry run? //istanbul ignore if: No need to test console logs if (dry && verbose) { console.log(chalk.yellow('Dry run, not making any changes')); } //Process synchronously paths.forEach(path => { if (replaceSync(path, from, to, encoding, dry)) { changedFiles.push(path); } }); //Return changed files return changedFiles; }; //Export module.exports = replaceInFile;
21.550459
74
0.624521
3d6e62c2d14fe448a73e8dcf11d6201e5cabccc3
345
js
JavaScript
docs/doc/blake2/sidebar-items.js
AtlDragoon/Fennel-Protocol
f5f1a87d1564543484f27b4819a7a196fe91994f
[ "Unlicense" ]
null
null
null
docs/doc/blake2/sidebar-items.js
AtlDragoon/Fennel-Protocol
f5f1a87d1564543484f27b4819a7a196fe91994f
[ "Unlicense" ]
null
null
null
docs/doc/blake2/sidebar-items.js
AtlDragoon/Fennel-Protocol
f5f1a87d1564543484f27b4819a7a196fe91994f
[ "Unlicense" ]
null
null
null
initSidebarItems({"struct":[["Blake2b","Blake2b instance with a fixed output."],["Blake2s","Blake2s instance with a fixed output."],["VarBlake2b","Blake2b instance with a variable output."],["VarBlake2s","Blake2s instance with a variable output."]],"trait":[["Digest","The `Digest` trait specifies an interface common for digest functions."]]});
345
345
0.73913
3d6e995a91e3007fd708165c7e613aa8158b2ca2
72
js
JavaScript
app/src/assets/localization/index.js
ferlzc/opentrons
29fac8ae6e456439f87fce60e8c935c2a2aaa582
[ "Apache-2.0" ]
null
null
null
app/src/assets/localization/index.js
ferlzc/opentrons
29fac8ae6e456439f87fce60e8c935c2a2aaa582
[ "Apache-2.0" ]
null
null
null
app/src/assets/localization/index.js
ferlzc/opentrons
29fac8ae6e456439f87fce60e8c935c2a2aaa582
[ "Apache-2.0" ]
null
null
null
// @flow import { en } from './en' export const resources = { en, }
9
26
0.555556
3d6f670049a78009b0687997ac4d5638cc520ee7
5,324
js
JavaScript
src/__tests__/code/model/expected/UserAuth.model.js
tobkle/create-graphql-server-authorization
d40718907f6d2bfb76fdcb4d2e0ae8ede5701456
[ "MIT" ]
null
null
null
src/__tests__/code/model/expected/UserAuth.model.js
tobkle/create-graphql-server-authorization
d40718907f6d2bfb76fdcb4d2e0ae8ede5701456
[ "MIT" ]
null
null
null
src/__tests__/code/model/expected/UserAuth.model.js
tobkle/create-graphql-server-authorization
d40718907f6d2bfb76fdcb4d2e0ae8ede5701456
[ "MIT" ]
null
null
null
/* eslint-disable prettier */ import { queryForRoles, onAuthRegisterLoader, authlog, checkAuthDoc, protectFields } from 'create-graphql-server-authorization'; import bcrypt from 'bcrypt'; const SALT_ROUNDS = 10; export default class User { constructor(context) { this.context = context; this.collection = context.db.collection('user'); this.pubsub = context.pubsub; this.authRole = User.authRole; const { me } = context; queryForRoles( me, ['admin'], ['_id'], { User }, onAuthRegisterLoader('user findOneById', 'readOne', me, this) ); } static authRole(user) { return user && user.role ? user.role : null; } async findOneById(id, me, resolver) { const log = authlog(resolver, 'readOne', me); if (!this.authorizedLoader) { log.error('not authorized'); return null; } return await this.authorizedLoader.load(id); } find({ lastCreatedAt = 0, limit = 10, baseQuery = {} }, me, resolver) { const authQuery = queryForRoles( me, ['admin'], ['_id'], { User: this.context.User }, authlog(resolver, 'readMany', me) ); const finalQuery = { ...baseQuery, ...authQuery, createdAt: { $gt: lastCreatedAt } }; return this.collection .find(finalQuery) .sort({ createdAt: 1 }) .limit(limit) .toArray(); } tweets(user, { minLikes, lastCreatedAt = 0, limit = 10 }, me, resolver) { const baseQuery = { authorId: user._id }; return this.context.Tweet.find( { baseQuery, minLikes, lastCreatedAt, limit }, me, resolver ); } liked(user, { lastCreatedAt = 0, limit = 10 }, me, resolver) { const baseQuery = { _id: { $in: user.likedIds || [] } }; return this.context.Tweet.find( { baseQuery, lastCreatedAt, limit }, me, resolver ); } following(user, { lastCreatedAt = 0, limit = 10 }, me, resolver) { const baseQuery = { _id: { $in: user.followingIds || [] } }; return this.context.User.find( { baseQuery, lastCreatedAt, limit }, me, resolver ); } followers(user, { lastCreatedAt = 0, limit = 10 }, me, resolver) { const baseQuery = { followingIds: user._id }; return this.context.User.find( { baseQuery, lastCreatedAt, limit }, me, resolver ); } createdBy(user, me, resolver) { return this.context.User.findOneById(user.createdById, me, resolver); } updatedBy(user, me, resolver) { return this.context.User.findOneById(user.updatedById, me, resolver); } async insert(doc, me, resolver) { // We don't want to store passwords in plaintext const { password, ...rest } = doc; const hash = await bcrypt.hash(password, SALT_ROUNDS); let docToInsert = Object.assign({}, rest, { hash, createdAt: Date.now(), updatedAt: Date.now(), createdById: me && me._id ? me._id : 'unknown', updatedById: me && me._id ? me._id : 'unknown' }); checkAuthDoc( docToInsert, me, ['admin'], ['_id'], { User: this.context.User }, authlog(resolver, 'create', me) ); docToInsert = protectFields(me, ['admin'], ['role'], docToInsert, { User: this.context.User }); const id = (await this.collection.insertOne(docToInsert)).insertedId; if (!id) { throw new Error(`insert user not possible.`); } this.context.log.debug(`inserted user ${id}.`); const insertedDoc = this.findOneById(id, me, 'pubsub userInserted'); this.pubsub.publish('userInserted', insertedDoc); return insertedDoc; } async updateById(id, doc, me, resolver) { const docToUpdate = { $set: Object.assign({}, doc, { updatedAt: Date.now(), updatedById: me && me._id ? me._id : 'unknown' }) }; const baseQuery = { _id: id }; const authQuery = queryForRoles( me, ['admin'], ['_id'], { User: this.context.User }, authlog(resolver, 'update', me) ); docToUpdate.$set = protectFields( me, ['admin'], ['role'], docToUpdate.$set, { User: this.context.User } ); const finalQuery = { ...baseQuery, ...authQuery }; const result = await this.collection.updateOne(finalQuery, docToUpdate); if (result.result.ok !== 1 || result.result.n !== 1) { throw new Error(`update user not possible for ${id}.`); } this.context.log.debug(`updated user ${id}.`); this.authorizedLoader.clear(id); const updatedDoc = this.findOneById(id, me, 'pubsub userUpdated'); this.pubsub.publish('userUpdated', updatedDoc); return updatedDoc; } async removeById(id, me, resolver) { const baseQuery = { _id: id }; const authQuery = queryForRoles( me, ['admin'], ['_id'], { User: this.context.User }, authlog(resolver, 'delete', me) ); const finalQuery = { ...baseQuery, ...authQuery }; const result = await this.collection.remove(finalQuery); if (result.result.ok !== 1 || result.result.n !== 1) { throw new Error(`remove user not possible for ${id}.`); } this.context.log.debug(`removed user ${id}.`); this.authorizedLoader.clear(id); this.pubsub.publish('userRemoved', id); return result; } }
27.874346
76
0.596356
3d6fabc18d3f82d8d0d981d623877dfce897b68e
4,001
js
JavaScript
js/app.js
ashleybiermann/bhabib-201d62
5acdebf96122f2e7d28a7ed95ce746881796ccc5
[ "MIT" ]
null
null
null
js/app.js
ashleybiermann/bhabib-201d62
5acdebf96122f2e7d28a7ed95ce746881796ccc5
[ "MIT" ]
null
null
null
js/app.js
ashleybiermann/bhabib-201d62
5acdebf96122f2e7d28a7ed95ce746881796ccc5
[ "MIT" ]
null
null
null
'use strict'; /* === Lab 03 Planning === 1. (HTML) Create 'Top Ten' (any) as an ordered list [X] 2. (HTML) Convert work experience and education to an unordered list 3. (JS) Add 6th question to guessing game that takes in a numeric input and prompts user to guess a number - use a random number generator [X] 4. (JS) Add alert for number-guessing question that says whether guess is too high or low [X] 5. (JS) Give the user 4 opportunities to answer the number-guessing game and give correct answer after all tries are exhausted [X] 6. (JS) Add 7th question with multiple correct answers stored in an array [X] 7. (JS) Give the user 6 attempts to guess and display all correct answers if they fail [X] 8. (JS) Guesses end when the user gives a correct answer or exhausts all attempts [X] 9. (JS) Convert the first five questions into an array with a 'for loop' that iterates through them [X] 10. (JS) Keep track of number of correct answers and tell users how many they get right/wrong at the end [X] */ //Welcome Message var userName = prompt('What\'s your name?'); alert('Welcome, ' + userName + ', to Bade\'s About Me quiz!'); var numAnswersCorrect = 0; //ask 5 questions function askQuestion(qPrompt, correction, answerFlag) { var trueAnswer, falseAnswer; if(answerFlag) { trueAnswer = ['yes', 'y']; falseAnswer = ['no', 'n']; } else { trueAnswer = ['no', 'n']; falseAnswer = ['yes', 'y']; } let currPrompt = prompt(qPrompt).toLowerCase(); if(currPrompt === trueAnswer[0] || currPrompt === trueAnswer[1]) { console.log('Correct!'); alert('Correct!'); numAnswersCorrect++; } else if(currPrompt === falseAnswer[0] || currPrompt === falseAnswer[1]) { console.log(correction); alert(correction); } } //Random Number Guessing Game function playNumberGuess(maxNumber, maxTries){ var randNumber = Math.random() * Math.floor(maxNumber); randNumber = Math.round(randNumber); var answeredCorrectly = false; var numGuessPrompt = prompt('I\'m thinking of a random number from 1 to ' + maxNumber + '. Try to guess it.'); console.log('random number: ' + randNumber); if(numGuessPrompt == randNumber) { alert('Correct!'); } else { for (let i = 1; i < maxTries; i++) { if(numGuessPrompt < randNumber) { numGuessPrompt = prompt('Too low! Try again...'); } else if(numGuessPrompt > randNumber) { numGuessPrompt = prompt('Too high! Try again...'); } else if(numGuessPrompt == randNumber) { alert('Correct!'); answeredCorrectly = true; numAnswersCorrect++; break; } } if(!answeredCorrectly) alert('Didn\'t guess the number!'); } } // Multiple Answer Question function askMultiAnswerQuestion(correctAnswers, maxTries) { var answeredCorrectly = false; for(let i = 0; i < maxTries; i++) { let lastPrompt = prompt('What are one of my top 3 games? Use proper spelling, it\'s important!'); for(let i = 0; i < correctAnswers.length; i++) { if(lastPrompt === correctAnswers[i]) { alert('Correct!'); answeredCorrectly = true; numAnswersCorrect++; break; } } if(answeredCorrectly) break; else alert('Wrong answer! Try again!'); } if(!answeredCorrectly) alert('Didn\'t guess correctly!'); } //function calls askQuestion('Was I born in Colorado?', 'Wrong. I was born in New Mexico.', 0); askQuestion('Was I in the Coast Guard?', 'Wrong. I was in the Navy.', 0); askQuestion('Do I have an Associate\'s degree?', 'Wrong. I do have an Associate\'s degree.', 1); askQuestion('Is Bade my legal name?', 'Wrong. My legal name is Cristian.', 0); askQuestion('Do I have prior experience with coding?', 'Wrong. I do have experience in coding.', 1); playNumberGuess(10, 4); askMultiAnswerQuestion(['Torment: Numenera','Legend Of Zelda: Breath Of The Wild','Armello'], 6); //Goodbye message alert('Thank you for taking the quiz, ' + userName + '. You got ' + numAnswersCorrect + ' correct!');
36.372727
142
0.669083
3d6fbe89ff338e64e5449ff4b8e036045a1a72ee
1,994
js
JavaScript
docs/tailwind.js
ryanjkelly/vue-tippy
8795fa35f00d129d47ee6a929f9ca07bf208096d
[ "MIT" ]
null
null
null
docs/tailwind.js
ryanjkelly/vue-tippy
8795fa35f00d129d47ee6a929f9ca07bf208096d
[ "MIT" ]
null
null
null
docs/tailwind.js
ryanjkelly/vue-tippy
8795fa35f00d129d47ee6a929f9ca07bf208096d
[ "MIT" ]
null
null
null
var config = require('tailwindcss/defaultConfig')() config.colors = Object.assign(config.colors, { 'tailwind-teal-light': '#5ebcca', 'tailwind-teal': '#44a8b3', 'tailwind-teal-dark': '#2f8696' }) config.fonts = { 'sans': 'aktiv-grotesk, -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen, Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue', 'serif': 'Constantia, "Lucida Bright", Lucidabright, "Lucida Serif", Lucida, "DejaVu Serif", "Bitstream Vera Serif", "Liberation Serif", Georgia, serif', 'mono': 'Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace' } config.textSizes = { 'xs': '.75rem', // 12px 'sm': '.875rem', // 14px 'base': '1rem', // 16px 'lg': '1.125rem', // 18px 'xl': '1.25rem', // 20px '2xl': '1.5rem', // 24px '3xl': '1.875rem', // 30px '4xl': '2.25rem', // 36px '5xl': '3rem' // 48px } config.fontWeights = { 'light': 300, 'normal': 400, 'semibold': 500, 'bold': 700 } config.tracking = { 'tight': '-0.02em', 'normal': '0', 'wide': '0.05em' } config.textColors = config.colors config.backgroundColors = config.colors config.borderWidths = Object.assign(config.borderWidths, { '6': '6px' }) config.borderColors = Object.assign(config.colors, { default: config.colors['grey-light'] }) config.width = Object.assign(config.width, { '5': '1.25rem', '128': '32rem' }) config.height = Object.assign(config.height, { '7': '1.75rem', '128': '32rem' }) config.maxHeight = Object.assign(config.maxHeight, { 'sm': '30rem' }) config.padding = Object.assign(config.padding, { '10': '2.5rem', '12': '3rem', '16': '4rem', '20': '5rem', '80': '20rem' }) config.margin = Object.assign(config.margin, { '10': '2.5rem', '12': '3rem', '16': '4rem', '20': '5rem', '80': '20rem' }) config.negativeMargin = config.margin config.shadows = Object.assign({ 'md-light': '0 0 12px 8px rgb(255,255,255)' }, config.shadows) module.exports = config
22.404494
155
0.617854
3d6fd580972b986c52c8928001c3581a7d1f09e3
171
js
JavaScript
test/__mocks__/@adobe/aio-lib-ims.js
purplecabbage/aio-cli-plugin-console
6330004a7ce20961c80dc7cc217478f617356773
[ "Apache-2.0" ]
4
2019-03-17T18:04:59.000Z
2020-08-29T13:10:28.000Z
test/__mocks__/@adobe/aio-lib-ims.js
purplecabbage/aio-cli-plugin-console
6330004a7ce20961c80dc7cc217478f617356773
[ "Apache-2.0" ]
152
2018-08-31T04:48:09.000Z
2022-03-02T10:30:47.000Z
test/__mocks__/@adobe/aio-lib-ims.js
purplecabbage/aio-cli-plugin-console
6330004a7ce20961c80dc7cc217478f617356773
[ "Apache-2.0" ]
10
2018-08-31T09:13:29.000Z
2022-03-04T06:16:29.000Z
const mockConsole = { getToken: jest.fn(() => 'VALID_TOKEN'), context: { getCli: jest.fn(() => 'stage'), setCli: jest.fn() } } module.exports = mockConsole
17.1
41
0.590643
3d6ff34f17dcd408a5075ff6a3d1cbbfc278e469
78
js
JavaScript
node_modules/carbon-icons-svelte/lib/MigrateAlt16/index.js
seekersapp2013/new
1e393c593ad30dc1aa8642703dad69b84bad3992
[ "MIT" ]
null
null
null
node_modules/carbon-icons-svelte/lib/MigrateAlt16/index.js
seekersapp2013/new
1e393c593ad30dc1aa8642703dad69b84bad3992
[ "MIT" ]
null
null
null
node_modules/carbon-icons-svelte/lib/MigrateAlt16/index.js
seekersapp2013/new
1e393c593ad30dc1aa8642703dad69b84bad3992
[ "MIT" ]
null
null
null
import MigrateAlt16 from "./MigrateAlt16.svelte"; export default MigrateAlt16;
39
49
0.833333
3d70693106fbdca7206cd3d7fa1fc4c6de4a67a1
33
js
JavaScript
vendor/github.com/olebedev/gojax/fetch/index.js
prantoran/GoogleAuthentication_React_Go
e2770ab85dbc989a97f48acdf3817b75345541e0
[ "MIT" ]
3,245
2015-07-02T08:50:09.000Z
2022-03-27T19:37:19.000Z
vendor/github.com/olebedev/gojax/fetch/index.js
xiaoxiaosaohuo/go-starter-kit
12d8bc473581b5ce9b29342e49f8e3086c79ae33
[ "MIT" ]
90
2015-07-20T19:25:34.000Z
2019-11-27T21:33:39.000Z
vendor/github.com/olebedev/gojax/fetch/index.js
xiaoxiaosaohuo/go-starter-kit
12d8bc473581b5ce9b29342e49f8e3086c79ae33
[ "MIT" ]
526
2015-07-21T04:40:09.000Z
2022-03-26T02:14:04.000Z
require('expose?fetch!./fetch');
16.5
32
0.69697
3d7193067a10bccd7be4a6cb770385279cf99554
39
js
JavaScript
packages/1985/05/31/index.js
antonmedv/year
ae5d8524f58eaad481c2ba599389c7a9a38c0819
[ "MIT" ]
7
2017-07-03T19:53:01.000Z
2021-04-05T18:15:55.000Z
packages/1985/05/31/index.js
antonmedv/year
ae5d8524f58eaad481c2ba599389c7a9a38c0819
[ "MIT" ]
1
2018-09-05T11:53:41.000Z
2018-12-16T12:36:21.000Z
packages/1985/05/31/index.js
antonmedv/year
ae5d8524f58eaad481c2ba599389c7a9a38c0819
[ "MIT" ]
2
2019-01-27T16:57:34.000Z
2020-10-11T09:30:25.000Z
module.exports = new Date(1985, 4, 31)
19.5
38
0.692308
3d72ae0fcf22585f7afa4b864aebd10596a4da45
2,088
js
JavaScript
Modules/Taobao/node_modules/vant/es/progress/index.js
xiaodui12/bokang_api
3381183efe7886b84a801be5fee7785834b21261
[ "MIT" ]
null
null
null
Modules/Taobao/node_modules/vant/es/progress/index.js
xiaodui12/bokang_api
3381183efe7886b84a801be5fee7785834b21261
[ "MIT" ]
5
2021-03-09T13:20:40.000Z
2022-02-26T15:53:40.000Z
Modules/Taobao/node_modules/vant/es/progress/index.js
xiaodui12/bokang_api
3381183efe7886b84a801be5fee7785834b21261
[ "MIT" ]
null
null
null
import { createNamespace, isDef } from '../utils'; import { BLUE, WHITE } from '../utils/color'; var _createNamespace = createNamespace('progress'), createComponent = _createNamespace[0], bem = _createNamespace[1]; export default createComponent({ props: { inactive: Boolean, pivotText: String, pivotColor: String, percentage: { type: Number, required: true, validator: function validator(value) { return value >= 0 && value <= 100; } }, showPivot: { type: Boolean, default: true }, color: { type: String, default: BLUE }, textColor: { type: String, default: WHITE } }, data: function data() { return { pivotWidth: 0, progressWidth: 0 }; }, mounted: function mounted() { this.getWidth(); }, watch: { showPivot: function showPivot() { this.getWidth(); }, pivotText: function pivotText() { this.getWidth(); } }, methods: { getWidth: function getWidth() { var _this = this; this.$nextTick(function () { _this.progressWidth = _this.$el.offsetWidth; _this.pivotWidth = _this.$refs.pivot ? _this.$refs.pivot.offsetWidth : 0; }); } }, render: function render(h) { var pivotText = this.pivotText, percentage = this.percentage; var text = isDef(pivotText) ? pivotText : percentage + '%'; var showPivot = this.showPivot && text; var background = this.inactive ? '#cacaca' : this.color; var pivotStyle = { color: this.textColor, background: this.pivotColor || background }; var portionStyle = { background: background, width: (this.progressWidth - this.pivotWidth) * percentage / 100 + 'px' }; return h("div", { "class": bem() }, [h("span", { "class": bem('portion', { 'with-pivot': showPivot }), "style": portionStyle }, [showPivot && h("span", { "ref": "pivot", "style": pivotStyle, "class": bem('pivot') }, [text])])]); } });
24
81
0.565613
3d72d79f79e53e774faea8f02d475129e329bdfe
1,048
js
JavaScript
js/controllers/DetailController.js
knutator2/Rolling-Stone
c062e51b5f913d3462c6f4dedcf2eb3763e64596
[ "MIT" ]
2
2015-05-26T12:30:29.000Z
2017-01-28T16:42:00.000Z
js/controllers/DetailController.js
knutator2/Rolling-Stone
c062e51b5f913d3462c6f4dedcf2eb3763e64596
[ "MIT" ]
62
2015-08-31T22:59:48.000Z
2016-03-02T22:51:56.000Z
js/controllers/DetailController.js
knutator2/Rolling-Stone
c062e51b5f913d3462c6f4dedcf2eb3763e64596
[ "MIT" ]
null
null
null
'use strict'; // var DetailController = function($scope) { // $scope.name = "DetailTEST"; // } // var app.controller("DetailController", ['$scope', '$routeParams', 'StonesService', var DetailController = function( $scope, $routeParams, StoneDataService ) { $scope.name = "BLUBB"; // $scope.currentStone = {}; var qwertz = StoneDataService.getStoneById(parseInt($routeParams.stoneId,10)); console.log( qwertz ); // // qwertz.then(function(response) { // $scope.currentStone = response; // }); $scope.currentStone = {test: "yeee"}; $scope.stones = []; // Could be used for later // StonesService.get().then(function(data) { // $scope.len = data.length; // $scope.stones = data; // angular.forEach(data, function(value) { // if (value.museum_id === parseInt($routeParams.stone)) { // $scope.currentStone = value; // } // }); // console.log($routeParams); // }); } // ]); module.exports = DetailController;
26.871795
85
0.578244
3d7313374edc8aadd6057a39b7b10cff7feb6a5b
1,249
js
JavaScript
src/pages/blog.js
C4org/development-site
de1e88c91dda093de2c4d7d1ee869e52ff6c4d14
[ "RSA-MD" ]
null
null
null
src/pages/blog.js
C4org/development-site
de1e88c91dda093de2c4d7d1ee869e52ff6c4d14
[ "RSA-MD" ]
null
null
null
src/pages/blog.js
C4org/development-site
de1e88c91dda093de2c4d7d1ee869e52ff6c4d14
[ "RSA-MD" ]
null
null
null
/* eslint-disable import/no-extraneous-dependencies */ import React from "react" import Navbar from "../components/Navbar" import "../styles/styles.css" import Index from "../components/BlogIndex" import Footer from "../components/Footer" import SEO from "../components/seo" export default function App() { return ( <div className="container main-container min-h-screen mx-auto font-serif debug-screens"> <SEO title="The Blog"></SEO> <Navbar></Navbar> <div className="flex flex-col min-h-full longpage"> <div className="mx-auto text-4xl font-display text-bold text-center pt-6 pb-2"> Blog Posts </div> <div className="mx-auto text-xl text-center font-serif"> <p className="text-xl text-center font-serif"> Welcome to the C4 Blog! Every now and then, a new post will appear here in one of various categories. It might be part of our educational series, or just some news we'd like to share. </p> <p className="text-xl text-center font-serif"> If you have questions, comments or suggestions for any articles feel free to let us know! </p> </div> <Index /> </div> <Footer></Footer> </div> ) }
39.03125
195
0.644516
3d7367e620a0137276afde057bf7e13cbf37a7cf
24,088
js
JavaScript
docs/lib/controllers/view_pager.js
zuixjs/zkit
43323860ed8dd13c12d7a25fb9bd824360fcfd76
[ "Apache-2.0" ]
11
2019-02-03T08:39:30.000Z
2022-03-14T19:35:09.000Z
docs/lib/controllers/view_pager.js
zuixjs/zkit
43323860ed8dd13c12d7a25fb9bd824360fcfd76
[ "Apache-2.0" ]
3
2021-05-06T23:49:42.000Z
2022-03-28T00:23:05.000Z
source/lib/controllers/view_pager.js
zuixjs/zkit
43323860ed8dd13c12d7a25fb9bd824360fcfd76
[ "Apache-2.0" ]
2
2018-08-26T10:42:15.000Z
2021-07-14T13:16:42.000Z
/** * zUIx - ViewPager Component * * @version 1.0.6 (2018-08-24) * @author Gene * * @version 1.0.5 (2018-08-21) * @author Gene * * @version 1.0.4 (2018-06-29) * @author Gene * * @version 1.0.3 (2018-06-26) * @author Gene * * @version 1.0.1 (2018-02-12) * @author Gene * */ 'use strict'; zuix.controller(function(cp) { const DEFAULT_PAGE_TRANSITION = {duration: 0.3, easing: 'ease'}; const BOUNDARY_HIT_EASING = 'cubic-bezier(0.0,0.1,0.35,1.1)'; const DECELERATE_SCROLL_EASING = 'cubic-bezier(0.0,0.1,0.35,1.0)'; const LAYOUT_HORIZONTAL = 'horizontal'; const LAYOUT_VERTICAL = 'vertical'; const SLIDE_DIRECTION_FORWARD = 1; const SLIDE_DIRECTION_BACKWARD = -1; // state vars let currentPage = -1; let oldPage = 0; let slideTimeout = null; let slideIntervalMs = 3000; let slideDirection = SLIDE_DIRECTION_FORWARD; let updateLayoutTimeout = null; let inputCaptured = false; // options let layoutType = LAYOUT_HORIZONTAL; let enableAutoSlide = false; let enablePaging = false; let holdTouch = false; let passiveMode = true; let startGap = 0; let hideOffViewElements = false; // status let isDragging = false; let wasVisible = false; let isLazyContainer = false; let isFlying = false; let actualViewSize = { width: 0, height: 0 }; // timers let componentizeInterval = null; let componentizeTimeout = null; /** @typedef {ZxQuery} */ let pageList = null; // Create a mutation observer instance to watch for child add/remove const domObserver = new MutationObserver(function(a, b) { // update child list and re-layout pageList = cp.view().children(); updateLayout(); }); cp.init = function() { let options = cp.options(); let view = cp.view(); options.html = false; options.css = false; enablePaging = (options.enablePaging === true || (view.attr('data-o-paging') === 'true')); enableAutoSlide = (options.autoSlide === true || (view.attr('data-o-slide') === 'true')); passiveMode = (options.passive !== false && (view.attr('data-o-passive') !== 'false')); holdTouch = (options.holdTouch === true || (view.attr('data-o-hold') === 'true')); startGap = (options.startGap || view.attr('data-o-startgap')); if (options.verticalLayout === true || (view.attr('data-o-layout') === LAYOUT_VERTICAL)) { layoutType = LAYOUT_VERTICAL; } if (options.slideInterval != null) { slideIntervalMs = options.slideInterval; } else if (view.attr('data-o-slide-interval') != null) { slideIntervalMs = parseInt(view.attr('data-o-slide-interval')); } hideOffViewElements = (options.autohide === true || (view.attr('data-o-autohide') === 'true')); }; cp.create = function() { // enable absolute positioning for items in this view const view = cp.view().css({ 'position': 'relative', 'overflow': 'hidden' }); // get child items (pages) pageList = view.children(); // loading of images could change elements size, so layout update might be required view.find('img').each(function(i, el) { this.one('load', updateLayout); }); // re-arrange view on layout changes zuix.$(window) .on('resize', function() { layoutElements(true); }).on('orientationchange', function() { layoutElements(true); }); // Options for the observer (which mutations to observe) // Register DOM mutation observer callback domObserver.observe(view.get(), { attributes: false, childList: true, subtree: true, characterData: false }); updateLayout(); // Set starting page setPage(0); let tapTimeout = null; // gestures handling - load gesture_helper controller zuix.load('@lib/controllers/gesture_helper', { view: view, passive: passiveMode, startGap: startGap, on: { 'gesture:touch': function(e, tp) { inputCaptured = false; stopAutoSlide(); dragStart(); if (holdTouch) tp.cancel(); }, 'gesture:release': function(e, tp) { dragStop(tp); resetAutoSlide(); }, 'gesture:tap': function(e, tp) { if (tapTimeout != null) { clearTimeout(tapTimeout); } tapTimeout = setTimeout(function() { handleTap(e, tp); }, 50); }, 'gesture:pan': handlePan, 'gesture:swipe': handleSwipe }, ready: function() { layoutElements(true); } }); // public component methods cp.expose('page', function(number) { if (number == null) { return parseInt(currentPage); } else setPage(number, DEFAULT_PAGE_TRANSITION); }).expose('get', function(number) { return pageList.eq(number); }).expose('slide', function(activate) { if (activate === true) { resetAutoSlide(); } else stopAutoSlide(); }).expose('layout', function(mode) { if (mode == null) { return layoutType; } else if (mode === LAYOUT_VERTICAL) { layoutType = LAYOUT_VERTICAL; } else layoutType = LAYOUT_HORIZONTAL; updateLayout(); }).expose('refresh', function() { layoutElements(true); }).expose('next', next) .expose('prev', prev) .expose('last', last) .expose('first', first); }; cp.destroy = function() { if (domObserver != null) { domObserver.disconnect(); } }; function updateLayout() { if (updateLayoutTimeout != null) { clearTimeout(updateLayoutTimeout); } updateLayoutTimeout = setTimeout(layoutElements, 250); } function layoutElements(force) { if (!force && (isDragging || componentizeInterval != null)) { updateLayout(); return; } // init elements pageList.each(function(i, el) { this.css({ 'position': 'absolute', 'left': 0, 'top': 0 }); }); // measure const viewSize = getSize(cp.view().get()); if (viewSize.width === 0 || viewSize.height === 0) { if (viewSize.height === 0 && cp.view().position().visible) { let maxHeight = 0; // guess and set view_pager height pageList.each(function(i, el) { let size = getSize(el); if (size.height > maxHeight) { maxHeight = size.height; } }); if (viewSize.height < maxHeight) { cp.view().css('height', maxHeight + 'px'); } } // cannot measure view, try again later updateLayout(); return; } actualViewSize = viewSize; // position elements let offset = 0; let isLazy = false; pageList.each(function(i, el) { let size = getSize(el); if (layoutType === LAYOUT_HORIZONTAL) { let centerY = (viewSize.height-size.height)/2; if (centerY < 0) centerY = 0; // TODO: centering with negative offset was not working transition(this, DEFAULT_PAGE_TRANSITION); position(this, offset, centerY); offset += size.width; } else { let centerX = (viewSize.width-size.width)/2; if (centerX < 0) centerX = 0; // TODO: centering with negative offset was not working transition(this, DEFAULT_PAGE_TRANSITION); position(this, centerX, offset); offset += size.height; } if (this.attr('data-ui-lazyload') === 'true' || this.find('[data-ui-lazyload="true"]').length() > 0) { isLazy = true; } }); isLazyContainer = isLazy; // focus to current page setPage(currentPage); // start automatic slide if (pageList.length() > 1) { resetAutoSlide(); } } function next() { let isLast = false; let page = parseInt(currentPage)+1; if (page >= pageList.length()) { page = pageList.length()-1; isLast = true; } setPage(page, DEFAULT_PAGE_TRANSITION); return !isLast; } function prev() { let isFirst = false; let page = parseInt(currentPage)-1; if (page < 0) { page = 0; isFirst = true; } setPage(page, DEFAULT_PAGE_TRANSITION); return !isFirst; } function first() { setPage(0, DEFAULT_PAGE_TRANSITION); } function last() { setPage(pageList.length()-1, DEFAULT_PAGE_TRANSITION); } function slideNext() { setPage(parseInt(currentPage) + slideDirection, DEFAULT_PAGE_TRANSITION); resetAutoSlide(); } function resetAutoSlide(timeout) { stopAutoSlide(); if (enableAutoSlide === true) { const visible = cp.view().position().visible; if (visible) { if (!wasVisible) { zuix.componentize(cp.view()); } slideTimeout = setTimeout(slideNext, slideIntervalMs); } else { slideTimeout = setTimeout(resetAutoSlide, 500); } wasVisible = visible; } } function stopAutoSlide() { if (slideTimeout != null) { clearTimeout(slideTimeout); } } function getItemIndexAt(x, y) { let focusedPage = 0; pageList.each(function(i, el) { let data = getData(this); focusedPage = i; const size = getSize(el); const rect = { x: data.position.x, y: data.position.y, w: size.width, h: size.height }; if ((layoutType === LAYOUT_HORIZONTAL && (rect.x > x || rect.x+rect.w > x)) || (layoutType === LAYOUT_VERTICAL && (rect.y > y || rect.y+rect.h > y))) { return false; } }); return focusedPage; } function focusPageAt(tp, transition) { let vp = cp.view().position(); let page = getItemIndexAt(tp.x-vp.x, tp.y-vp.y); setPage(page, transition != null ? transition : DEFAULT_PAGE_TRANSITION); } function setPage(n, transition) { oldPage = currentPage; if (n < 0) { slideDirection = SLIDE_DIRECTION_FORWARD; n = 0; } else if (n >= pageList.length()) { slideDirection = SLIDE_DIRECTION_BACKWARD; n = pageList.length() - 1; } else if (n !== currentPage) { slideDirection = (currentPage < n) ? SLIDE_DIRECTION_FORWARD : SLIDE_DIRECTION_BACKWARD; } currentPage = n; if (currentPage != oldPage) { pageList.eq(currentPage).css('z-index', 1); if (oldPage !== -1) { pageList.eq(oldPage).css('z-index', 0); } cp.trigger('page:change', {in: currentPage, out: oldPage}); } const el = pageList.eq(n); const data = getData(el); const elSize = getSize(el.get()); const focusPoint = { x: (actualViewSize.width - elSize.width) / 2 - data.position.x, y: (actualViewSize.height - elSize.height) / 2 - data.position.y }; flyTo(focusPoint, transition); resetAutoSlide(); } function flyTo(targetPoint, transition) { const spec = getFrameSpec(); const firstData = getData(pageList.eq(0)); const lastPage = pageList.eq(pageList.length() - 1); const lastData = getData(lastPage); pageList.each(function(i, el) { const data = getData(this); const frameSpec = getFrameSpec(); data.dragStart = { x: frameSpec.marginLeft + data.position.x, y: frameSpec.marginTop + data.position.y }; }); if (layoutType === LAYOUT_HORIZONTAL) { let x = targetPoint.x; if (firstData.position.x + targetPoint.x > 0) { x = -firstData.position.x; } else { if (lastData.position.x + lastPage.get().offsetWidth + targetPoint.x < actualViewSize.width) { x = -spec.marginLeft*2 + actualViewSize.width - (lastData.position.x + lastPage.get().offsetWidth); } } // check if boundary was adjusted and adjust flying duration accordingly if (targetPoint.x-x !== 0 && transition != null) { transition = { duration: transition.duration * (x / targetPoint.x), easing: BOUNDARY_HIT_EASING }; if (!isFinite(transition.duration) || transition.duration < 0) { transition.duration = 0.2; } } dragShift(x, 0, transition); } else { let y = targetPoint.y; if (firstData.position.y + targetPoint.y > 0) { y = -firstData.position.y; } else { if (lastData.position.y + lastPage.get().offsetHeight + targetPoint.y < actualViewSize.height) { y = -spec.marginTop*2 + actualViewSize.height - (lastData.position.y + lastPage.get().offsetHeight); } } // check if boundary was adjusted and adjust flying duration accordingly if (targetPoint.y-y !== 0 && transition != null) { transition = { duration: transition.duration * (y / targetPoint.y), easing: BOUNDARY_HIT_EASING }; if (!isFinite(transition.duration) || transition.duration < 0) { transition.duration = 0.2; } } dragShift(0, y, transition); } isFlying = true; } function getSize(el) { const rect = el.getBoundingClientRect(); const width = rect.width || el.offsetWidth; const height = el.offsetHeight || rect.height; return {width: width, height: height}; } function getData(el) { const data = el.get().data = el.get().data || {}; data.position = data.position || {x: 0, y: 0}; return data; } function componentizeStart() { if (isLazyContainer) { componentizeStop(); if (componentizeTimeout != null) { clearTimeout(componentizeTimeout); } if (componentizeInterval != null) { clearInterval(componentizeInterval); } componentizeInterval = setInterval(function() { if (hideOffViewElements) { pageList.each(function(i, el) { // hide elements if not inside the view_pager const computed = window.getComputedStyle(el, null); const size = { width: parseFloat(computed.width.replace('px', '')), height: parseFloat(computed.height.replace('px', '')) }; const x = parseFloat(computed.left.replace('px', '')); const y = parseFloat(computed.top.replace('px', '')); if (size.width > 0 && size.height > 0) { el = zuix.$(el); // check if element is inside the view_pager if (x + size.width < 0 || y + size.height < 0 || x > actualViewSize.width || y > actualViewSize.height) { if (el.visibility() !== 'hidden') { el.visibility('hidden'); } } else if (el.visibility() !== 'visible') { el.visibility('visible'); } } }); } zuix.componentize(cp.view()); }, 10); } } function componentizeStop() { if (isLazyContainer && componentizeTimeout == null) { clearInterval(componentizeInterval); } } function dragStart() { isDragging = true; isFlying = false; pageList.each(function(i, el) { const data = getData(this); const frameSpec = getFrameSpec(); const computed = window.getComputedStyle(el, null); data.position.x = parseFloat(computed.left.replace('px', '')); data.position.y = parseFloat(computed.top.replace('px', '')); this.css('left', data.position.x+'px'); this.css('top', data.position.y+'px'); data.dragStart = {x: frameSpec.marginLeft+data.position.x, y: frameSpec.marginTop+data.position.y}; }); } function getFrameSpec() { const spec = { w: 0, h: 0, marginLeft: 0, marginTop: 0 }; pageList.each(function(i, el) { const size = getSize(el); spec.w += size.width; spec.h += size.height; }); if (layoutType === LAYOUT_HORIZONTAL && spec.w < actualViewSize.width) { spec.marginLeft = (actualViewSize.width - spec.w) / 2; } else if (layoutType === LAYOUT_VERTICAL && spec.h < actualViewSize.height) { spec.marginTop = (actualViewSize.height - spec.h) / 2; } return spec; } function dragShift(x, y, tr) { if (tr != null) { componentizeStart(); componentizeTimeout = setTimeout(function() { componentizeTimeout = null; componentizeStop(); }, tr.duration*1000); tr = tr.duration+'s '+tr.easing; } else if (isLazyContainer) { zuix.componentize(cp.view()); } pageList.each(function(i, el) { const data = getData(this); transition(this, tr); position(this, data.dragStart.x+x, data.dragStart.y+y); }); } function dragStop(tp) { if (tp != null) { tp.done = true; // decelerate if (!isFlying && ((layoutType === LAYOUT_HORIZONTAL && tp.scrollIntent() === 'horizontal') || (layoutType === LAYOUT_VERTICAL && tp.scrollIntent() === 'vertical'))) { decelerate(null, tp); } } componentizeStop(); isDragging = false; } // Gesture handling function handlePan(e, tp) { if (!tp.scrollIntent() || tp.done) { return; } if (inputCaptured || ((tp.direction === 'left' || tp.direction === 'right') && layoutType === LAYOUT_HORIZONTAL) || ((tp.direction === 'up' || tp.direction === 'down') && layoutType === LAYOUT_VERTICAL)) { // capture click event if (!inputCaptured && tp.event.touches == null) { cp.view().get().addEventListener('click', function(e) { if (inputCaptured) { inputCaptured = false; e.cancelBubble = true; // TODO: 'preventDefault' should not be used with passive listeners e.preventDefault(); } // release mouse click capture cp.view().get().removeEventListener('click', this, true); }, true); } inputCaptured = true; tp.cancel(); } const spec = getFrameSpec(); if (layoutType === LAYOUT_HORIZONTAL && tp.scrollIntent() === 'horizontal') { dragShift(tp.shiftX-spec.marginLeft, 0); } else if (layoutType === LAYOUT_VERTICAL && tp.scrollIntent() === 'vertical') { dragShift(0, tp.shiftY-spec.marginTop); } } function handleTap(e, tp) { let vp = cp.view().position(); let page = getItemIndexAt(tp.x-vp.x, tp.y-vp.y); cp.trigger('page:tap', page, tp); if (enablePaging) focusPageAt(tp); } function decelerate(e, tp) { const minSpeed = 0.01; const minStepSpeed = 1.25; const accelerationFactor = Math.exp(Math.abs(tp.velocity / (Math.abs(tp.velocity) <= minStepSpeed ? 5 : 2))+1); let friction = 0.990 + (accelerationFactor / 1000); if (friction > 0.999) { friction = 0.999; } const duration = Math.log(minSpeed / Math.abs(tp.velocity)) / Math.log(friction); const decelerateEasing = { duration: duration / 1000, // ms to s easing: DECELERATE_SCROLL_EASING }; const fly = function(destination, shift) { if (enablePaging) { decelerateEasing.duration *= 0.5; if (layoutType === LAYOUT_HORIZONTAL) { focusPageAt({ x: destination.x - shift.x, y: destination.y }, decelerateEasing); } else { focusPageAt({ x: destination.x, y: destination.y - shift.y }, decelerateEasing); } } else { flyTo(shift, decelerateEasing); } }; const flyingDistance = tp.stepSpeed < minStepSpeed ? 0 : accelerationFactor * tp.velocity * (1 - Math.pow(friction, duration + 1)) / (1 - friction); const ap = { x: flyingDistance, y: flyingDistance }; if (willFly(tp) || e == null) fly(tp, ap); } function willFly(tp) { return (!enablePaging || Math.abs(tp.velocity) > 1.25); } function handleSwipe(e, tp) { if (willFly(tp)) { return; } switch (tp.direction) { case 'right': if (layoutType === LAYOUT_HORIZONTAL) prev(); break; case 'left': if (layoutType === LAYOUT_HORIZONTAL) next(); break; case 'down': if (layoutType === LAYOUT_VERTICAL) prev(); break; case 'up': if (layoutType === LAYOUT_VERTICAL) next(); break; } } function position(el, x, y) { const data = getData(el); if (!isNaN(x) && !isNaN(y)) { data.position = {'x': x, 'y': y}; el.css({'left': data.position.x+'px', 'top': data.position.y+'px'}); } return data; } function transition(el, transition) { if (transition == null) { transition = 'none'; } el.css({ '-webkit-transition': transition, '-moz-transition': transition, '-ms-transition': transition, '-o-transition': transition, 'transition': transition }); } });
35.898659
178
0.500457
3d736e09c58b2953b6c880d64732439af050dc50
276
js
JavaScript
src/components/SocialMediaLinks/SocialMediaLinks.lazy.js
BrunoBiluca/bruno-biluca-portal-website
4bb5afd75c43c9cb59f8be5ef2fd2af2ec782162
[ "Apache-2.0" ]
null
null
null
src/components/SocialMediaLinks/SocialMediaLinks.lazy.js
BrunoBiluca/bruno-biluca-portal-website
4bb5afd75c43c9cb59f8be5ef2fd2af2ec782162
[ "Apache-2.0" ]
null
null
null
src/components/SocialMediaLinks/SocialMediaLinks.lazy.js
BrunoBiluca/bruno-biluca-portal-website
4bb5afd75c43c9cb59f8be5ef2fd2af2ec782162
[ "Apache-2.0" ]
null
null
null
import React, { lazy, Suspense } from 'react'; const LazySocialMediaLinks = lazy(() => import('./SocialMediaLinks')); const SocialMediaLinks = props => ( <Suspense fallback={null}> <LazySocialMediaLinks {...props} /> </Suspense> ); export default SocialMediaLinks;
23
70
0.692029
3d748e6ef2841bd94b0cb8770d06d2b7b57941a3
14,442
js
JavaScript
index.js
terebentina/numDate
d2ce01ec36cdb22db9263d177886d5dedc7c7da4
[ "MIT" ]
null
null
null
index.js
terebentina/numDate
d2ce01ec36cdb22db9263d177886d5dedc7c7da4
[ "MIT" ]
null
null
null
index.js
terebentina/numDate
d2ce01ec36cdb22db9263d177886d5dedc7c7da4
[ "MIT" ]
null
null
null
const overflows = { second: 60, minute: 60, hour: 24, day: [ // not a leap year [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], // leap year [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], ], month: 12 }; const lang = { MMM: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], ddd: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], dd: ['SU', 'MO', 'TU', 'WE', 'TH', 'FR', 'SA'], ll: 'MMM D YYYY', }; function zeroPad(num) { return ('0' + num).slice(-2); } function isLeapYear(year) { if (year % 4) { return false; } else if (year % 100) { return true; } else { return year % 400 == 0; } } function absFloor(number) { if (number < 0) { return Math.ceil(number); } else { return Math.floor(number); } } function normalizeUnits(unit) { const normal = { seconds: 'second', second: 'second', minutes: 'minute', minute: 'minute', hours: 'hour', hour: 'hour', days: 'day', day: 'day', weeks: 'week', week: 'week', months: 'month', month: 'month', years: 'year', year: 'year', }; return normal[unit]; } /** * adapted from moment.js * @param {NumDate} a * @param {NumDate} b * @returns {number} */ function monthDiff(a, b) { // difference in months var wholeMonthDiff = ((b.year() - a.year()) * 12) + (b.month() - a.month()); // b is in (anchor - 1 month, anchor + 1 month) var anchor = a.clone().add(wholeMonthDiff, 'months'); var anchor2, adjust; if (b.getTime() - anchor.getTime() < 0) { anchor2 = a.clone().add(wholeMonthDiff - 1, 'months'); // linear across the month adjust = (b.getTime() - anchor.getTime()) / (anchor.getTime() - anchor2.getTime()); } else { anchor2 = a.clone().add(wholeMonthDiff + 1, 'months'); // linear across the month adjust = (b.getTime() - anchor.getTime()) / (anchor2.getTime() - anchor.getTime()); } return -(wholeMonthDiff + adjust); } class NumDate { constructor(num) { this.data = { year: 0, month: 0, day: 0, hour: 0, minute: 0, second: 0, }; this.jsDate = null; if (num) { var str = String(num); if (str.length >= 4) { this.data.year = parseInt(str.substr(0, 4), 10); if (str.length >= 6) { this.data.month = parseInt(str.substr(4, 2), 10) - 1; if (str.length >= 8) { this.data.day = parseInt(str.substr(6, 2), 10); if (str.length >= 10) { this.data.hour = parseInt(str.substr(8, 2), 10); if (str.length >= 12) { this.data.minute = parseInt(str.substr(10, 2), 10); if (str.length >= 14) { this.data.second = parseInt(str.substr(12, 2), 10); } } } } } } } } year(val) { if (typeof val == 'undefined') { return this.data.year; } else { this.data.year = parseInt(val, 10); this.jsDate = null; return this; } } month(val) { if (typeof val == 'undefined') { return this.data.month; } else { this.data.month = parseInt(val, 10); this.jsDate = null; return this; } } date(val) { if (typeof val == 'undefined') { return this.data.day; } else { this.data.day = parseInt(val, 10); this.jsDate = null; return this; } } hours(val) { if (typeof val == 'undefined') { return this.data.hour; } else { this.data.hour = parseInt(val, 10); this.jsDate = null; return this; } } minutes(val) { if (typeof val == 'undefined') { return this.data.minute; } else { this.data.minute = parseInt(val, 10); this.jsDate = null; return this; } } seconds(val) { if (typeof val == 'undefined') { return this.data.second; } else { this.data.second = parseInt(val, 10); this.jsDate = null; return this; } } /** * @returns {Date} */ toDate() { if (!this.jsDate) { this.jsDate = new Date(this.data.year, this.data.month, this.data.day, this.data.hour, this.data.minute, this.data.second); } return this.jsDate; } /** * @returns {Number} */ getTime() { return this.toDate().getTime(); } /** * @returns {string} */ toString() { return '' + this.data.year + zeroPad(this.data.month + 1) + zeroPad(this.data.day) + zeroPad(this.data.hour) + zeroPad(this.data.minute) + zeroPad(this.data.second); } /** * @returns {Number} */ valueOf() { return parseInt(this.toString(), 10); } /** * @returns {NumDate} */ toGMT() { var offset = this.toDate().getTimezoneOffset(); if (offset < 0) { this.subtract(Math.abs(offset), 'minutes'); } else if (offset > 0) { this.add(offset, 'minutes'); } return this; } /** * @returns {NumDate} */ fromGMT() { var offset = this.toDate().getTimezoneOffset(); if (offset < 0) { this.add(Math.abs(offset), 'minutes'); } else if (offset > 0) { this.subtract(offset, 'minutes'); } return this; } /** * @param {Number} amount * @param {String} unit one of minute(s)|hour(s)|day(s)|month(s)|year(s) * @returns {NumDate} */ add(amount, unit) { unit = normalizeUnits(unit); // this changes from unit to unit var qty = amount; // this changes from unit to unit var type = unit; var tmp = 0; if (type == 'week') { type = 'day'; qty *= 7; } if (type == 'second') { tmp = this.data.second + qty; if (tmp >= overflows.second) { this.data.second = tmp % overflows.second; qty = Math.floor(tmp / overflows.second); type = 'minute'; } else { this.data.second = tmp; } } if (type == 'minute') { tmp = this.data.minute + qty; if (tmp >= overflows.minute) { this.data.minute = tmp % overflows.minute; qty = Math.floor(tmp / overflows.minute); type = 'hour'; } else { this.data.minute = tmp; } } if (type == 'hour') { tmp = this.data.hour + qty; if (tmp >= overflows.hour) { this.data.hour = tmp % overflows.hour; qty = Math.floor(tmp / overflows.hour); type = 'day'; } else { this.data.hour = tmp; } } if (type == 'day') { var tmpDayOverflow = overflows.day[0 + isLeapYear(this.data.year)]; tmp = this.data.day + qty; if (tmp > tmpDayOverflow[this.data.month]) { var thisMonth = this.data.month; var nextMonth = thisMonth == 11 ? 0 : thisMonth + 1; var thisYear = this.data.year; var nextMonthsYear = thisMonth == 11 ? thisYear + 1 : thisYear; // get the day to the end of the current month tmp -= tmpDayOverflow[thisMonth]; while (tmp > overflows.day[0 + isLeapYear(nextMonthsYear)][nextMonth]) { tmp -= overflows.day[0 + isLeapYear(nextMonthsYear)][nextMonth]; thisMonth = nextMonth; thisYear = nextMonthsYear; nextMonth = thisMonth == 11 ? 0 : thisMonth + 1; nextMonthsYear = thisMonth == 11 ? thisYear + 1 : thisYear; } this.data.day = tmp; this.data.month = nextMonth; this.data.year = nextMonthsYear; } else { this.data.day = tmp; } } else { if (type == 'month') { tmp = this.data.month + qty; if (tmp > overflows.month) { this.data.month = tmp % overflows.month; qty = Math.floor(tmp / overflows.month); type = 'year'; } else { this.data.month = tmp; } } if (type == 'year') { this.data.year += qty; } } this.jsDate = null; return this; } /** * @param {Number} amount * @param {String} unit one of minute(s)|hour(s)|day(s)|month(s)|year(s) * @returns {NumDate} */ subtract(amount, unit) { unit = normalizeUnits(unit); // this changes from unit to unit var qty = amount; // this changes from unit to unit var type = unit; var tmp = 0; if (type == 'week') { type = 'day'; qty *= 7; } if (type == 'second') { tmp = this.data.second - qty; if (tmp < 0) { // we use + below because tmp is negative this.data.second = overflows.second + tmp % overflows.second; qty = Math.abs(Math.floor(tmp / overflows.second)); type = 'minute'; } else { this.data.second = tmp; } } if (type == 'minute') { tmp = this.data.minute - qty; if (tmp < 0) { // we use + below because tmp is negative this.data.minute = overflows.minute + tmp % overflows.minute; qty = Math.abs(Math.floor(tmp / overflows.minute)); type = 'hour'; } else { this.data.minute = tmp; } } if (type == 'hour') { tmp = this.data.hour - qty; if (tmp < 0) { this.data.hour = overflows.hour + tmp % overflows.hour; qty = Math.abs(Math.floor(tmp / overflows.hour)); type = 'day'; } else { this.data.hour = tmp; } } if (type == 'day') { tmp = this.data.day - qty; if (tmp < 1) { var thisMonth = this.data.month; var prevMonth = thisMonth == 0 ? 11 : thisMonth - 1; var thisYear = this.data.year; var prevMonthsYear = thisMonth == 0 ? thisYear - 1 : thisYear; do { tmp += overflows.day[0 + isLeapYear(prevMonthsYear)][prevMonth]; thisMonth = prevMonth; thisYear = prevMonthsYear; prevMonth = thisMonth == 0 ? 11 : thisMonth - 1; prevMonthsYear = thisMonth == 0 ? thisYear - 1 : thisYear; } while (-tmp >= overflows.day[0 + isLeapYear(prevMonthsYear)][prevMonth]); if (tmp > 0) { this.data.day = tmp; this.data.month = thisMonth; this.data.year = thisYear; } else { this.data.day = overflows.day[0 + isLeapYear(prevMonthsYear)][prevMonth] + tmp; this.data.month = prevMonth; this.data.year = prevMonthsYear; } } else { this.data.day = tmp; } } else { if (type == 'month') { tmp = this.data.month - qty; if (tmp < 0) { this.data.month = overflows.month + tmp % overflows.month; qty = Math.abs(Math.floor(tmp / overflows.month)); type = 'year'; } else { this.data.month = tmp; } } if (type == 'year') { this.data.year -= qty; } } this.jsDate = null; return this; } /** * @todo watch out for double replacing - see the inline comment * @param {String} str * @returns {String} */ format(str) { return str .replace('ll', lang.ll) .replace('YYYY', this.data.year) .replace('DD', zeroPad(this.data.day)) // D has to come before MMM because 'Dec' contains D and 'Dec' would look like '6ec' .replace('D', this.data.day) .replace('MMM', lang.MMM[this.data.month]) .replace('MM', zeroPad(this.data.month + 1)) .replace('ddd', lang.ddd[(new Date(this.data.year, this.data.month, this.data.day)).getDay()]) .replace('dd', lang.dd[(new Date(this.data.year, this.data.month, this.data.day)).getDay()]) .replace('HH', zeroPad(this.data.hour)) .replace('H', this.data.hour) .replace('mm', zeroPad(this.data.minute)) .replace('m', this.data.minute) .replace('ss', zeroPad(this.data.second)); } /** * calculates the difference in the requested unit between 2 NumDates * @param {NumDate} num * @param {String} units * @returns {Number} */ diff(num, units) { units = normalizeUnits(units); var output; var target = num.clone(); if (units == 'year' || units == 'month') { output = monthDiff(this, target); if (units === 'year') { output = output / 12; } } else { var delta = this.getTime() - target.getTime(); output = units === 'second' ? delta / 1e3 : // 1000 units === 'minute' ? delta / 6e4 : // 1000 * 60 units === 'hour' ? delta / 36e5 : // 1000 * 60 * 60 units === 'day' ? delta / 864e5 : // 1000 * 60 * 60 * 24 units === 'week' ? delta / 6048e5 : // 1000 * 60 * 60 * 24 * 7 delta; } return absFloor(output); } /** * @param {Number} num * @returns {boolean} */ isBefore(num) { return this.valueOf() < exports(num).valueOf(); } /** * @param {Number} num * @returns {boolean} */ isAfter(num) { return this.valueOf() > exports(num).valueOf(); } /** * @param {Number} num * @returns {boolean} */ isSame(num) { return this.toString() == exports(num).toString(); } /** * @returns {NumDate} */ clone() { return exports(this); } /** * time ago in a human readable format. Note that this function only calculates dates in the past, not in the future. * @returns {String} */ fromNow() { var now = exports(); var yearDiff = now.diff(this, 'years'); if (yearDiff > 1) { return yearDiff + ' years ago'; } else if (yearDiff == 1) { return '1 year ago'; } else if (yearDiff == 0) { var monthDiff = now.diff(this, 'months'); if (monthDiff > 1) { return monthDiff + ' months ago'; } else if (monthDiff == 1) { return '1 month ago'; } else if (monthDiff == 0) { var dayDiff = now.diff(this, 'days'); if (dayDiff > 1) { return dayDiff + ' days ago'; } else if (dayDiff == 1) { return '1 day ago'; } else if (dayDiff == 0) { var hourDiff = now.diff(this, 'hours'); if (hourDiff > 1) { return hourDiff + ' hours ago'; } else if (hourDiff == 1) { return '1 hour ago'; } else if (hourDiff == 0) { var minuteDiff = now.diff(this, 'minutes'); if (minuteDiff > 20) { return minuteDiff + ' minutes ago'; } else if (minuteDiff > 1) { return 'a few minutes ago'; } else if (minuteDiff == 0) { return 'a few seconds ago'; } } } } } return ''; } } /** * @param {Date} date * @param {boolean} withTime * @returns {NumDate} */ export function fromDate(date, withTime) { if (!date) { date = new Date(); } var str = date.getFullYear() + zeroPad(date.getMonth() + 1) + zeroPad(date.getDate()) + (withTime ? zeroPad(date.getHours()) + zeroPad(date.getMinutes()) + zeroPad(date.getSeconds()) : '000000'); return new NumDate(str); } /** * @param {Number|String|Array|NumDate} num * @param {boolean} withTime * @returns {NumDate} */ var exports = function(num = undefined, withTime = true) { if (typeof num == 'undefined') { return fromDate(new Date(), true); } else if (Array.isArray(num)) { var date = new NumDate(); date.year(num[0]).month(num[1]).date(num[2]); if (num.length > 3) { date.hours(num[3]); if (num.length > 4) { date.minutes(num[4]); if (num.length > 5) { date.seconds(num[5]); } } } return date; } else if (typeof num == 'object' && num instanceof Date) { return fromDate(num, withTime); } else if (typeof num == 'number' && String(num).length <= 13) { return fromDate(new Date(num), withTime); } // this handles the case when num is a NumDate. Basically a way to clone a NumDate return new NumDate(num); }; export default exports;
24.272269
167
0.577967
3d7505781a121d6d8fbb9cf54dd8595fcf64063e
121
js
JavaScript
concurrent/dns.js
jmanzanog/golab
c912b13d789186a8c18cf3ea98b845f29f141dec
[ "MIT" ]
null
null
null
concurrent/dns.js
jmanzanog/golab
c912b13d789186a8c18cf3ea98b845f29f141dec
[ "MIT" ]
null
null
null
concurrent/dns.js
jmanzanog/golab
c912b13d789186a8c18cf3ea98b845f29f141dec
[ "MIT" ]
null
null
null
[ {"url": "https://www.facebook.com/"}, {"url": "https://www.google.com/"}, {"url": "https://golang.org/"} ]
20.166667
41
0.487603
3d758698e861ec9dbd7ace9ce3570f0a598799a5
25
js
JavaScript
wildcard-js/two.js
snowpackjs/export-map-test
e49af70a9e3e626dfbcbfc3745ac4c5a1790d26a
[ "MIT" ]
null
null
null
wildcard-js/two.js
snowpackjs/export-map-test
e49af70a9e3e626dfbcbfc3745ac4c5a1790d26a
[ "MIT" ]
null
null
null
wildcard-js/two.js
snowpackjs/export-map-test
e49af70a9e3e626dfbcbfc3745ac4c5a1790d26a
[ "MIT" ]
null
null
null
// ./wildcard-ext/two.js
12.5
24
0.64
3d75de1ca09634ca2eb08649a42a638d3875c1ba
520
js
JavaScript
strategies/indicators/x2EMA.js
tobby2002/tradyai-api
1314528ee5200114a951e298a64633d4485eef62
[ "MIT" ]
12
2020-02-01T14:58:15.000Z
2021-04-21T18:54:50.000Z
strategies/indicators/x2EMA.js
tobby2002/tradyai-api
1314528ee5200114a951e298a64633d4485eef62
[ "MIT" ]
12
2020-09-16T08:15:26.000Z
2022-01-06T10:02:02.000Z
strategies/indicators/x2EMA.js
tobby2002/tradyai-api
1314528ee5200114a951e298a64633d4485eef62
[ "MIT" ]
7
2019-10-05T07:35:13.000Z
2021-03-10T12:15:58.000Z
// filename "DEMA.js" already in use by some old legacy code // name x2EMA means: "double EMA" (usually called DEMA) // (2 * x1EMA(x)) - x1EMA(x1EMA(x)) var x1EMA = require('./EMA.js'); var Indicator = function(weight) { this.EMA = new x1EMA(weight); this.EMAprime = new x1EMA(weight); } Indicator.prototype.update = function(weight) { var EMA = 0.0; this.EMA.update(weight); EMA = this.EMA.result; this.EMAprime.update(EMA); this.result = (2 * EMA) - this.EMAprime.result; } module.exports = Indicator;
24.761905
60
0.676923
3d7617a8cc4db3a4d8ee8a966fc7d9879dec14af
1,402
js
JavaScript
src/tigers/transitions/cubeOut.js
Mefjus/react-tiger-transition
48f89133cc7a011602fd427a166b309204ca5d21
[ "MIT" ]
502
2019-12-01T08:03:43.000Z
2022-03-13T19:45:33.000Z
src/tigers/transitions/cubeOut.js
Mefjus/react-tiger-transition
48f89133cc7a011602fd427a166b309204ca5d21
[ "MIT" ]
35
2019-12-13T18:11:07.000Z
2022-02-26T19:56:45.000Z
src/tigers/transitions/cubeOut.js
Mefjus/react-tiger-transition
48f89133cc7a011602fd427a166b309204ca5d21
[ "MIT" ]
33
2019-10-27T10:12:13.000Z
2022-03-13T19:45:37.000Z
import { getEasing } from '../../utils'; export default ({ name = 'cube', direction = 'left', duration = 700, easing = 'ease-in', opacity = 0.3, zIndex = 2, depth = 200, delay = 0, } = {}) => { const config = { left: ['100% 50%', 'X(-50%)', 'Y(-45deg)', 'X(-100%)', 'Y(-90deg)'], right: ['0% 50%', 'X(50%)', 'Y(45deg)', 'X(100%)', 'Y(90deg)'], top: ['50% 100%', 'Y(-50%)', 'X(45deg)', 'Y(-100%)', 'X(90deg)'], bottom: ['50% 0%', 'Y(50%)', 'X(-45deg)', 'Y(100%)', 'X(-90deg)'], }; const animationName = `${name}--react-tiger-transition-cube-out`; const transformOrigin = config[direction][0]; const animationCss = `${animationName} ${duration}ms both ${getEasing(easing)}`; const transform50 = `translate${config[direction][1]} translateZ(${-depth}px) rotate${config[direction][2]}`; const transform100 = `translate${config[direction][3]} rotate${config[direction][4]}`; const style = ` .${name}-exit { transform-origin: ${transformOrigin}; z-index: ${zIndex}; opacity: 1; } .${name}-exit-active { animation: ${animationCss}; animation-delay: ${delay}ms; } @keyframes ${animationName} { 0% { opacity: 1; } 50% { transform: ${transform50}; animation-timing-function: ease-out; } 100% { opacity: ${opacity}; transform: ${transform100}; } } `; return style; };
25.035714
111
0.553495
3d770bc40f95d32aa63944191f2ba5524a67be21
6,564
js
JavaScript
_includes/js/theme.js
verovanporras/jekyll-hp-base-theme
b75d9ba2e869931b8c999054c855885b9ed05675
[ "Apache-2.0" ]
null
null
null
_includes/js/theme.js
verovanporras/jekyll-hp-base-theme
b75d9ba2e869931b8c999054c855885b9ed05675
[ "Apache-2.0" ]
null
null
null
_includes/js/theme.js
verovanporras/jekyll-hp-base-theme
b75d9ba2e869931b8c999054c855885b9ed05675
[ "Apache-2.0" ]
null
null
null
// control the navbar // https://bulma.io/documentation/components/navbar/ document.addEventListener('DOMContentLoaded', () => { // Get all "navbar-burger" elements const $navbarBurgers = Array.prototype.slice.call(document.querySelectorAll('.menu-toggle'), 0); // Check if there are any navbar burgers // Copied verbatim, but why check when it is a foreach loop. Does some browsers return null instead of empty array? if ($navbarBurgers.length > 0) { // Add a click event on each of them $navbarBurgers.forEach($el => { $el.addEventListener('click', () => { // Get the target from the "data-target" attribute const target = $el.dataset.target; const $target = document.getElementById(target); // Toggle the "is-active" class on both the "navbar-burger" and the "navbar-menu" $el.classList.toggle('is-active'); $target.classList.toggle('is-active'); let isActive = $el.classList.contains('is-active'); $el.setAttribute('aria-expanded', isActive) }); }); } }); // control the sidebar pagenav document.addEventListener('DOMContentLoaded', () => { // Get the page navigation const $pageNavLists = Array.prototype.slice.call(document.querySelectorAll('#pageNavbar .navbar-link'), 0); if ($pageNavLists.length > 0) { // Add a click event on each of them $pageNavLists.forEach($el => { $el.addEventListener('click', () => { // The target is the next element const $target = $el.nextElementSibling; // const $target = document.getElementById(target); // Toggle the "is-active" class on both the "navbar-burger" and the "navbar-menu" $el.classList.toggle('is-expanded'); $target.classList.toggle('is-expanded'); let isActive = $el.classList.contains('is-expanded'); $el.setAttribute('aria-expanded', isActive) }); }); } // expand active node const $activeLink = document.querySelector('#pageNavbar .active'); expandNavNode($activeLink); }); function expandNavNode(node) { if (node) { const $ul = node.parentNode.parentNode; const $navbarLink = $ul.previousElementSibling; if ($navbarLink.classList.contains('navbar-link')) { $navbarLink.classList.add('is-expanded'); $ul.classList.add('is-expanded'); $navbarLink.setAttribute('aria-expanded', true) $ul.setAttribute('aria-expanded', true) expandNavNode($navbarLink); } } } // add ajax count // util for getting deep values in json objects by passing a string // https://stackoverflow.com/questions/6491463/accessing-nested-javascript-objects-and-arays-by-string-path function resolve(path, obj = self, separator = '.') { var properties = Array.isArray(path) ? path : path.split(separator) return properties.reduce((prev, curr) => prev && prev[curr], obj) } document.addEventListener('DOMContentLoaded', () => { // Get all "count" elements const $counts = document.querySelectorAll('[data-ajax-url]'); // for each element, do the async lookup $counts.forEach($el => { // get url var url = $el.attributes['data-ajax-url'].value.trim(); var pathAttribute = $el.attributes['data-ajax-path']; var path = 'count'; if (pathAttribute) { var path = pathAttribute.value.trim(); } $el.classList.add('ajax-is-loading'); fetch(url) .then(function (response) { return response.json(); }) .then(function (jsonResponse) { var value = resolve(path, jsonResponse) if (typeof value !== 'undefined') { var text = value; if (typeof value === 'number') { text = value.toLocaleString(currentLocale); } const newContent = document.createTextNode(text); // $el.innerHTML = ''; // $el.appendChild(newContent); $el.textContent = text; $el.classList.remove('ajax-is-loading'); $el.classList.add('ajax-is-loaded'); } }) .catch(function (err) { $el.classList.remove('ajax-is-loading'); $el.classList.add('ajax-loading-failed'); }); }); }); function highlightRightNav(heading) { tocItems.forEach(function (x) { x.classList.remove('active'); }); if (heading) { var activeTocItem = document.querySelector(".toc a[href='#" + heading + "']"); if (activeTocItem) { activeTocItem.classList.add("active"); } } } let headlines = []; let currentHeading = ''; let tocMaxDepth = 6; const tocItems = Array.from(document.querySelectorAll('.toc a')); if (tocItems.length > 0) { tocMaxDepth = document.gbifTocMaxDepth || tocMaxDepth; var headlineSelector = ''; for (var i = 1; i <= tocMaxDepth; i++ ) { headlineSelector += '.article h' + i + '[id]'; if (i < tocMaxDepth) headlineSelector += ','; } headlines = Array.from(document.querySelectorAll(headlineSelector)); currentHeading = ''; } function highligtToc() { if (tocItems.length <= 0) return; var headingPositions = []; headlines.forEach(function (x) { headingPositions[x.id] = x.getBoundingClientRect().top; }); headingPositions.sort(); // the headings have all been grabbed and sorted in order of their scroll // position (from the top of the page). First one is toppermost. for (var key in headingPositions) { if (!headingPositions.hasOwnProperty(key)) { continue; } if (headingPositions[key] > 0 && headingPositions[key] < 300) { if (currentHeading !== key) { // a new heading has scrolled to within 200px of the top of the page. // highlight the right-nav entry and de-highlight the others. highlightRightNav(key); currentHeading = key; } break; } } } // Scroll the given menu item into view. We actually pick the item *above* // the current item to give some headroom above function scrollToNavItem(selector) { let container = document.querySelector(selector); if (!container) return; let item = container.querySelector('.active'); if (item) { item = item.closest('li') } if (item) { document.querySelector(selector).scrollTop = item.offsetTop - 100; } } var hasScrolled; highligtToc(); document.addEventListener('scroll', function() { highligtToc(); if (!hasScrolled) { hasScrolled = true; scrollToNavItem('.toc'); scrollToNavItem('#pageNavbar'); } }); {% if jekyll.environment != "production" and site.algae.hideHelper != true %} {% include js/themeFeedback.js %} {% endif %}
28.415584
117
0.64153
3d7729327f2843dacf5d77749b14a7c8c99d79cc
646
js
JavaScript
src/js/dropdown.js
reboy/weui
036ac8f94ebd12cca6f0894f167e174c5630dc8a
[ "MIT" ]
null
null
null
src/js/dropdown.js
reboy/weui
036ac8f94ebd12cca6f0894f167e174c5630dc8a
[ "MIT" ]
null
null
null
src/js/dropdown.js
reboy/weui
036ac8f94ebd12cca6f0894f167e174c5630dc8a
[ "MIT" ]
null
null
null
/* global $:true */ +function ($) { var menus = document.getElementsByClassName("menus"); var arr = []; for (var i = 0; i < menus.length; i++) { var c = i; menus[i].onclick = function () { arr[i] = 0; $(this).next().slideDown(300); $(".mask").fadeIn(400); }; $(".mask").click(function () { // alert(menus[c]); $(".mask").fadeOut(400); $(".list").slideUp(300); }); document.addEventListener("touchmove", function () { $(".mask").fadeOut(400); $(".list").slideUp(300); }); } }($);
29.363636
60
0.428793
3d77bdb1c885cc264a6cb1bfb152c91b7835e352
2,044
js
JavaScript
src/sap.ui.rta/src/sap/ui/rta/command/AddXML.js
Trulsaa/openui5
4f32ec982e60507e25288ab3c2c122e04dcf3b9d
[ "Apache-2.0" ]
null
null
null
src/sap.ui.rta/src/sap/ui/rta/command/AddXML.js
Trulsaa/openui5
4f32ec982e60507e25288ab3c2c122e04dcf3b9d
[ "Apache-2.0" ]
null
null
null
src/sap.ui.rta/src/sap/ui/rta/command/AddXML.js
Trulsaa/openui5
4f32ec982e60507e25288ab3c2c122e04dcf3b9d
[ "Apache-2.0" ]
null
null
null
/*! * ${copyright} */ sap.ui.define([ 'sap/ui/rta/command/FlexCommand' ], function( FlexCommand ) { "use strict"; /** * Add a control from a XML fragment * * @class * @extends sap.ui.rta.command.FlexCommand * @author SAP SE * @version ${version} * @constructor * @private * @since 1.54 * @alias sap.ui.rta.command.AddXML * @experimental Since 1.54. This class is experimental and provides only limited functionality. Also the API might be * changed in future. */ var AddXML = FlexCommand.extend("sap.ui.rta.command.AddXML", { metadata : { library : "sap.ui.rta", properties : { fragment : { type : "string" }, fragmentPath : { type : "string" }, targetAggregation : { type : "string" }, index: { type: "int" }, changeType : { type : "string", defaultValue : "addXML" } }, associations : {}, events : {} } }); /** * @override to suppress the binding strings to be used as */ AddXML.prototype.bindProperty = function(sName, oBindingInfo){ if (sName === "fragment"){ return this.setFragment(oBindingInfo.bindingString); } return FlexCommand.prototype.bindProperty.apply(this, arguments); }; AddXML.prototype._getChangeSpecificData = function() { var mSpecificInfo = { changeType : this.getChangeType(), fragmentPath: this.getFragmentPath(), targetAggregation: this.getTargetAggregation(), index: this.getIndex() }; return mSpecificInfo; }; /** * Normally when the changes are loaded, the backend preloads the fragment as a module, * When first applying a change we need to do the same. * @override */ AddXML.prototype._applyChange = function(vChange) { // preload the module to be applicable in this session var mModulePreloads = {}; mModulePreloads[vChange.getModuleName] = this.getFragment(); sap.ui.require.preload(mModulePreloads); return FlexCommand.prototype._applyChange.apply(this, arguments); }; return AddXML; }, /* bExport= */true);
22.966292
119
0.653131
3d77d73e20487fec1386ba0aa25f5345b080324d
3,799
js
JavaScript
js/components/supervisor/evaluation/defectSummary.js
heiseish/SIA
3b755a2be3209bb87d2e9ffbe70bacb11d00846c
[ "MIT" ]
null
null
null
js/components/supervisor/evaluation/defectSummary.js
heiseish/SIA
3b755a2be3209bb87d2e9ffbe70bacb11d00846c
[ "MIT" ]
null
null
null
js/components/supervisor/evaluation/defectSummary.js
heiseish/SIA
3b755a2be3209bb87d2e9ffbe70bacb11d00846c
[ "MIT" ]
null
null
null
//@flow 'use-strict'; import React, { Component } from 'react'; import { Dimensions, Platform} from 'react-native'; import { Image, primary, secondary, Button, alert } from '../../common' import { Text, View, Icon } from 'native-base'; import { getPresentableDateAndTimeFromUnix } from '../../../lib' import { connect } from 'react-redux'; let ios = Platform.OS === 'ios' const width = Dimensions.get('window').width const height = Dimensions.get('window').height type Props = { defect: { name: string, priority: number, status: string, creator: string, id: string, image?: string } }; export default class DefectSummary extends Component { constructor(props: Props) { super(props) } render() { let defect = this.props.defect return ( <View style={styles.container}> {this.renderHeader(defect.name)} {this.renderDetails(defect)} {this.renderHeader('Personels')} {defect.supervisor ? <Text style={styles.subTitle}> Supervised by <Text> {defect.supervisor}</Text></Text> : <View style={{height: 30}}/>} {defect.staff ? <Text style={styles.subTitle}> Technician support <Text> {defect.staff}</Text></Text> : <View style={{height: 30}}/>} <Text style={styles.subTitle}> Started at <Text> {getPresentableDateAndTimeFromUnix(defect.startTime)}</Text></Text> <Text style={styles.subTitle}> Ended at <Text> {getPresentableDateAndTimeFromUnix(defect.endTime)}</Text></Text> </View> ) } renderHeader = (title: string) => ( <Button color={secondary.background} style={styles.header}> <Text style={styles.title}>{title}</Text> </Button> ) renderDetails = (defect: any) => ( <View style={styles.body}> <View style={styles.row}> {this.renderParticular('Priority',defect.priority)} {this.renderParticular('Status', defect.status)} {this.renderParticular('Created by', defect.creator)} </View> <View style={styles.row}> <View style={styles.description}> <Text style={styles.subTitle}>Description</Text> <Text>{defect.description}</Text> </View> {defect.image && <Image style={styles.image} source={{uri: defect.image}}/>} </View> </View> ) renderParticular = (title: string, value: string | number) => ( <View style={styles.particular}> <Text style={styles.subTitle}>{title}</Text> <Text>{value}</Text> </View> ) } const styles = { container: { flexDirection: 'column', }, header: { width: width, height: 60, marginBottom: 0, borderWidth: 1, borderColor: primary.normal }, title: { fontSize: 30, fontStyle: 'italic', color: primary.normal, backgroundColor: 'transparent', alignSelf: 'flex-start', marginLeft: 30 }, body: { width: width, height: 300, flexDirection: 'column', }, row: { width: width, height: 100, flexDirection: 'row', justifyContent: "space-between", marginBottom: 20 }, subTitle: { fontWeight: '400', color: primary.normal, marginTop: 10, marginBottom: 10 }, image: { width: 200, height: 200, borderRadius: 10, alignSelf: 'center' }, particular: { flexDirection: 'column', width: 130, height: 70, alignItems: 'center', justifyContent: 'center' }, description: { flexDirection: 'column', width: 200, height: 200, alignItems: 'center', justifyContent: 'flex-start' }, button: { width: 190, height: 50, borderRadius: 30 }, buttonCenter: { width: 190, height: 50, borderRadius: 30, alignSelf: 'center' }, }
23.74375
132
0.599895
3d78a60d3a450b5b63e6de974269225581f6062f
103,388
js
JavaScript
unpackage/dist/build/app-plus/app-view.js
victor24680/jxqcUni-App
2dc4d3d93f5f5194ab69d94590561a47910d4c15
[ "MIT" ]
null
null
null
unpackage/dist/build/app-plus/app-view.js
victor24680/jxqcUni-App
2dc4d3d93f5f5194ab69d94590561a47910d4c15
[ "MIT" ]
null
null
null
unpackage/dist/build/app-plus/app-view.js
victor24680/jxqcUni-App
2dc4d3d93f5f5194ab69d94590561a47910d4c15
[ "MIT" ]
null
null
null
(function(A){var e={};function t(n){if(e[n])return e[n].exports;var i=e[n]={i:n,l:!1,exports:{}};return A[n].call(i.exports,i,i.exports,t),i.l=!0,i.exports}t.m=A,t.c=e,t.d=function(A,e,n){t.o(A,e)||Object.defineProperty(A,e,{enumerable:!0,get:n})},t.r=function(A){"undefined"!==typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(A,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(A,"__esModule",{value:!0})},t.t=function(A,e){if(1&e&&(A=t(A)),8&e)return A;if(4&e&&"object"===typeof A&&A&&A.__esModule)return A;var n=Object.create(null);if(t.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:A}),2&e&&"string"!=typeof A)for(var i in A)t.d(n,i,function(e){return A[e]}.bind(null,i));return n},t.n=function(A){var e=A&&A.__esModule?function(){return A["default"]}:function(){return A};return t.d(e,"a",e),e},t.o=function(A,e){return Object.prototype.hasOwnProperty.call(A,e)},t.p="./",t(t.s="596b")})({"00ec":function(A,e,t){var n=t("24fb");e=n(!1),e.push([A.i,".t-table[data-v-2c41134d]{width:100%;border:1px #d0dee5 solid;border-left:none;border-top:none;box-sizing:border-box}.t-table[data-v-2c41134d] t-tr{display:-webkit-box;display:-webkit-flex;display:flex}.t-table[data-v-2c41134d] t-tr:nth-child(2n){background:#f5f5f5}\n\n\n\n",""]),A.exports=e},"0666":function(A,e,t){"use strict";t.r(e);var n=t("b263"),i=t.n(n);for(var c in n)"default"!==c&&function(A){t.d(e,A,(function(){return n[A]}))}(c);e["default"]=i.a},"0a1f":function(A,e,t){"use strict";t.r(e);var n=t("b725"),i=t("93bb");for(var c in i)"default"!==c&&function(A){t.d(e,A,(function(){return i[A]}))}(c);t("0ecf");var o,a=t("f0c5"),r=Object(a["a"])(i["default"],n["b"],n["c"],!1,null,"0f454c05",null,!1,n["a"],o);e["default"]=r.exports},"0c37":function(A,e,t){"use strict";var n={cmdProgress:t("8f66").default},i=function(){var A=this,e=A.$createElement,t=A._self._c||e;return t("v-uni-view",{staticClass:A._$g(0,"sc"),attrs:{_i:0}},[t("v-uni-view",{staticClass:A._$g(1,"sc"),staticStyle:{"background-color":"#FFFFFF"},attrs:{_i:1}},[t("uni-list",{attrs:{_i:2}},[t("uni-list-item",{staticClass:A._$g(3,"sc"),attrs:{_i:3}}),t("uni-list-item",{staticStyle:{"font-size":"14px"},attrs:{_i:4}},[A._v(A._$g(4,"t0-0"))]),t("uni-list-item",{staticClass:A._$g(5,"sc"),attrs:{_i:5}}),t("uni-list-item",{staticStyle:{"font-size":"14px"},attrs:{_i:6}},[A._v(A._$g(6,"t0-0"))]),t("uni-list-item",{staticClass:A._$g(7,"sc"),attrs:{_i:7}}),t("uni-list-item",{staticStyle:{"font-size":"14px"},attrs:{_i:8}},[A._v(A._$g(8,"t0-0"))]),t("uni-list-item",{staticClass:A._$g(9,"sc"),attrs:{_i:9}}),t("uni-list-item",{staticStyle:{"font-size":"14px"},attrs:{_i:10}},[A._v(A._$g(10,"t0-0"))]),t("uni-list-item",{staticClass:A._$g(11,"sc"),attrs:{_i:11}}),t("uni-list-item",{staticStyle:{"font-size":"12px"},attrs:{_i:12}},[t("v-uni-view",{staticClass:A._$g(13,"sc"),attrs:{_i:13}},[t("v-uni-view",{attrs:{_i:14}},[t("v-uni-radio-group",{attrs:{_i:15},on:{change:function(e){return A.$handleViewEvent(e)}}},A._l(A._$g(16,"f"),(function(e,n,i,c){return t("v-uni-label",{key:e,staticClass:A._$g("16-"+c,"sc"),attrs:{_i:"16-"+c}},[t("v-uni-radio",{staticStyle:{"margin-left":"30rpx"},attrs:{value:A._$g("17-"+c,"a-value"),color:"#0FAEFF",checked:A._$g("17-"+c,"a-checked"),_i:"17-"+c},on:{click:function(e){return A.$handleViewEvent(e)}}}),A._v(A._$g("16-"+c,"t1-0"))],1)})),1)],1)],1)],1),t("uni-list-item",{staticClass:A._$g(18,"sc"),attrs:{_i:18}}),t("uni-list-item",{attrs:{_i:19}},[t("v-uni-text",{attrs:{_i:20}},[A._v("\u5df2\u6295\u7968")]),t("cmd-progress",{staticStyle:{"margin-top":"5rpx"},attrs:{_i:21}}),A._l(A._$g(22,"f"),(function(e,n,i,c){return t("v-uni-view",{key:e,staticStyle:{"margin-top":"20rpx"},attrs:{_i:"22-"+c}},[t("v-uni-text",{attrs:{_i:"23-"+c}},[A._v(A._$g("23-"+c,"t0-0"))]),t("cmd-progress",{staticStyle:{"margin-top":"5rpx"},attrs:{_i:"24-"+c}})],1)}))],2),A._$g(25,"i")?t("v-uni-view",{staticStyle:{"margin-top":"50rpx","margin-bottom":"210rpx"},attrs:{_i:25}},[t("v-uni-view",{staticClass:A._$g(26,"sc"),attrs:{_i:26}},[t("v-uni-button",{staticStyle:{"background-color":"#00AAEE"},attrs:{type:"primary",_i:27},on:{click:function(e){return A.$handleViewEvent(e)}}},[A._v("\u786e \u8ba4 \u6295 \u7968")])],1)],1):A._e(),A._$g(28,"i")?t("v-uni-view",{staticStyle:{"margin-top":"50rpx","margin-bottom":"210rpx"},attrs:{_i:28}},[t("v-uni-view",{staticClass:A._$g(29,"sc"),attrs:{_i:29}},[t("v-uni-button",{staticStyle:{"background-color":"#62ABFB"},attrs:{type:"primary",disabled:"true",_i:30}},[A._v("\u5df2 \u6295 \u7968")])],1)],1):A._e()],1)],1)],1)},c=[];t.d(e,"b",(function(){return i})),t.d(e,"c",(function(){return c})),t.d(e,"a",(function(){return n}))},"0ecf":function(A,e,t){"use strict";var n=t("fe47"),i=t.n(n);i.a},"117a":function(A,e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var n={name:"UniBadge",props:["type","inverted","text","size"],data:function(){return{wxsProps:{}}},components:{}};e.default=n},"11e0":function(A,e,t){"use strict";var n=t("e370"),i=t.n(n);i.a},1244:function(A,e,t){"use strict";t.r(e);var n=t("0c37"),i=t("8ac0");for(var c in i)"default"!==c&&function(A){t.d(e,A,(function(){return i[A]}))}(c);t("1340");var o,a=t("f0c5"),r=Object(a["a"])(i["default"],n["b"],n["c"],!1,null,null,null,!1,n["a"],o);e["default"]=r.exports},1340:function(A,e,t){"use strict";var n=t("bb03"),i=t.n(n);i.a},"13cd":function(A,e,t){var n=t("66ba");"string"===typeof n&&(n=[[A.i,n,""]]),n.locals&&(A.exports=n.locals);var i=t("7f7e").default;i("5d591204",n,!0,{sourceMap:!1,shadowMode:!1})},"142d":function(A,e,t){"use strict";var n=t("41c7"),i=t.n(n);i.a},1529:function(A,e,t){"use strict";var n,i=function(){var A=this,e=A.$createElement,t=A._self._c||e;return t("v-uni-text",{staticClass:A._$g(0,"sc"),style:A._$g(0,"s"),attrs:{_i:0},on:{click:function(e){return A.$handleViewEvent(e)}}},[A._v(A._$g(0,"t0-0"))])},c=[];t.d(e,"b",(function(){return i})),t.d(e,"c",(function(){return c})),t.d(e,"a",(function(){return n}))},"1b4e":function(A,e,t){"use strict";var n=t("afd2"),i=t.n(n);i.a},"1ee0":function(A,e,t){"use strict";t.r(e);var n=t("7567"),i=t("f9fd");for(var c in i)"default"!==c&&function(A){t.d(e,A,(function(){return i[A]}))}(c);var o,a=t("f0c5"),r=Object(a["a"])(i["default"],n["b"],n["c"],!1,null,null,null,!1,n["a"],o);e["default"]=r.exports},"24fb":function(A,e,t){"use strict";function n(A,e){var t=A[1]||"",n=A[3];if(!n)return t;if(e&&"function"===typeof btoa){var c=i(n),o=n.sources.map((function(A){return"/*# sourceURL=".concat(n.sourceRoot||"").concat(A," */")}));return[t].concat(o).concat([c]).join("\n")}return[t].join("\n")}function i(A){var e=btoa(unescape(encodeURIComponent(JSON.stringify(A)))),t="sourceMappingURL=data:application/json;charset=utf-8;base64,".concat(e);return"/*# ".concat(t," */")}A.exports=function(A){var e=[];return e.toString=function(){return this.map((function(e){var t=n(e,A);return e[2]?"@media ".concat(e[2]," {").concat(t,"}"):t})).join("")},e.i=function(A,t,n){"string"===typeof A&&(A=[[null,A,""]]);var i={};if(n)for(var c=0;c<this.length;c++){var o=this[c][0];null!=o&&(i[o]=!0)}for(var a=0;a<A.length;a++){var r=[].concat(A[a]);n&&i[r[0]]||(t&&(r[2]?r[2]="".concat(t," and ").concat(r[2]):r[2]=t),e.push(r))}},e}},2544:function(A,e,t){var n=t("24fb");e=n(!1),e.push([A.i,".list-shu-style{font-weight:700;border-left:3px solid #333;height:80rpx}.chat-custom-right{-webkit-box-flex:1;-webkit-flex:1;flex:1;\r\ndisplay:-webkit-box;display:-webkit-flex;display:flex;\r\n-webkit-box-orient:vertical;-webkit-box-direction:normal;-webkit-flex-direction:column;flex-direction:column;-webkit-box-pack:justify;-webkit-justify-content:space-between;justify-content:space-between;-webkit-box-align:end;-webkit-align-items:flex-end;align-items:flex-end}.chat-custom-text{font-size:12px;color:#999}",""]),A.exports=e},"2bc5":function(A,e,t){"use strict";t.r(e);var n=t("62db"),i=t("a3a7");for(var c in i)"default"!==c&&function(A){t.d(e,A,(function(){return i[A]}))}(c);t("2d58");var o,a=t("f0c5"),r=Object(a["a"])(i["default"],n["b"],n["c"],!1,null,"17058646",null,!1,n["a"],o);e["default"]=r.exports},"2d2c":function(A,e,t){"use strict";var n,i=function(){var A=this,e=A.$createElement,t=A._self._c||e;return t("v-uni-view",{staticClass:A._$g(0,"sc"),class:A._$g(0,"c"),attrs:{_i:0}},[A._$g(1,"i")?[t("v-uni-view",{staticClass:A._$g(2,"sc"),class:A._$g(2,"c"),attrs:{_i:2}},[t("v-uni-view",{staticClass:A._$g(3,"sc"),style:A._$g(3,"s"),attrs:{_i:3}},[t("v-uni-text",{style:A._$g(4,"s"),attrs:{_i:4}}),A._$g(5,"i")?[t("v-uni-text",{staticClass:A._$g(6,"sc"),attrs:{title:A._$g(6,"a-title"),_i:6}},[A._$g(7,"i")?[A._v(A._$g(7,"t0-0"))]:A._e(),A._$g(8,"i")?t("v-uni-text",{style:A._$g(8,"s"),attrs:{_i:8}}):A._e()],2)]:A._e()],2)],1)]:A._e(),A._$g(9,"i")?[t("v-uni-view",{staticClass:A._$g(10,"sc"),attrs:{_i:10}},[t("v-uni-view",{staticClass:A._$g(11,"sc"),style:A._$g(11,"s"),attrs:{_i:11}},[t("v-uni-view",{staticClass:A._$g(12,"sc"),style:A._$g(12,"s"),attrs:{_i:12}}),A._$g(13,"i")?t("v-uni-view",{staticClass:A._$g(13,"sc"),style:A._$g(13,"s"),attrs:{_i:13}}):A._e()],1)],1),A._$g(14,"i")?[t("v-uni-text",{staticClass:A._$g(15,"sc"),attrs:{title:A._$g(15,"a-title"),_i:15}},[A._$g(16,"i")?[A._v(A._$g(16,"t0-0"))]:A._e(),A._$g(17,"i")?t("v-uni-text",{style:A._$g(17,"s"),attrs:{_i:17}}):A._e()],2)]:A._e()]:A._e()],2)},c=[];t.d(e,"b",(function(){return i})),t.d(e,"c",(function(){return c})),t.d(e,"a",(function(){return n}))},"2d58":function(A,e,t){"use strict";var n=t("c077"),i=t.n(n);i.a},"2e29":function(A,e,t){var n=t("7883");"string"===typeof n&&(n=[[A.i,n,""]]),n.locals&&(A.exports=n.locals);var i=t("7f7e").default;i("2c6598a9",n,!0,{sourceMap:!1,shadowMode:!1})},"2f63":function(A,e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var n=i(t("a261"));function i(A){return A&&A.__esModule?A:{default:A}}var c={data:function(){return{wxsProps:{}}},components:{mInput:n.default}};e.default=c},"30df":function(A,e,t){"use strict";t.r(e);var n=t("4d70"),i=t("3aa7");for(var c in i)"default"!==c&&function(A){t.d(e,A,(function(){return i[A]}))}(c);t("7376");var o,a=t("f0c5"),r=Object(a["a"])(i["default"],n["b"],n["c"],!1,null,"d1078a2a",null,!1,n["a"],o);e["default"]=r.exports},3198:function(A,e,t){var n=t("dd93");"string"===typeof n&&(n=[[A.i,n,""]]),n.locals&&(A.exports=n.locals);var i=t("7f7e").default;i("de45f2b0",n,!0,{sourceMap:!1,shadowMode:!1})},"351d":function(A,e,t){"use strict";t.r(e);var n=t("7e78"),i=t.n(n);for(var c in n)"default"!==c&&function(A){t.d(e,A,(function(){return n[A]}))}(c);e["default"]=i.a},3750:function(A,e,t){"use strict";t.r(e);var n=t("e581"),i=t.n(n);for(var c in n)"default"!==c&&function(A){t.d(e,A,(function(){return n[A]}))}(c);e["default"]=i.a},"3aa7":function(A,e,t){"use strict";t.r(e);var n=t("8109"),i=t.n(n);for(var c in n)"default"!==c&&function(A){t.d(e,A,(function(){return n[A]}))}(c);e["default"]=i.a},"3be8":function(A,e,t){var n=t("00ec");"string"===typeof n&&(n=[[A.i,n,""]]),n.locals&&(A.exports=n.locals);var i=t("7f7e").default;i("1691958e",n,!0,{sourceMap:!1,shadowMode:!1})},"3c17":function(A,e,t){var n=t("24fb");e=n(!1),e.push([A.i,".m-input-view[data-v-55a66033]{display:-webkit-inline-box;display:-webkit-inline-flex;display:inline-flex;-webkit-box-orient:horizontal;-webkit-box-direction:normal;-webkit-flex-direction:row;flex-direction:row;-webkit-box-align:center;-webkit-align-items:center;align-items:center;\n\t/* width: 100%; */-webkit-box-flex:1;-webkit-flex:1;flex:1;padding:0 10px}.m-input-input[data-v-55a66033]{-webkit-box-flex:1;-webkit-flex:1;flex:1;width:100%;height:20px;line-height:inherit;background-color:transparent}.m-input-icon[data-v-55a66033]{width:20px;font-size:20px;line-height:20px;color:#666}",""]),A.exports=e},"3c23":function(A,e,t){"use strict";t.r(e);var n=t("3198"),i=t.n(n);for(var c in n)"default"!==c&&function(A){t.d(e,A,(function(){return n[A]}))}(c);e["default"]=i.a},"41c7":function(A,e,t){var n=t("b531");"string"===typeof n&&(n=[[A.i,n,""]]),n.locals&&(A.exports=n.locals);var i=t("7f7e").default;i("44581b5e",n,!0,{sourceMap:!1,shadowMode:!1})},"4af9":function(A,e,t){"use strict";t.r(e);var n=t("f491"),i=t.n(n);for(var c in n)"default"!==c&&function(A){t.d(e,A,(function(){return n[A]}))}(c);e["default"]=i.a},"4c39":function(A,e,t){"use strict";var n,i=function(){var A=this,e=A.$createElement,t=A._self._c||e;return t("v-uni-view",{staticClass:A._$g(0,"sc"),attrs:{_i:0}},[t("v-uni-view",{staticClass:A._$g(1,"sc"),attrs:{_i:1}},[t("v-uni-view",{staticClass:A._$g(2,"sc"),attrs:{_i:2}},[t("v-uni-text",{staticClass:A._$g(3,"sc"),attrs:{_i:3}},[A._v("\u8d26\u6237\uff1a")]),t("m-input",{staticClass:A._$g(4,"sc"),attrs:{_i:4},model:{value:A._$g(4,"v-model"),callback:function(){},expression:"account"}})],1),t("v-uni-view",{staticClass:A._$g(5,"sc"),attrs:{_i:5}},[t("v-uni-text",{staticClass:A._$g(6,"sc"),attrs:{_i:6}},[A._v("\u5bc6\u7801\uff1a")]),t("m-input",{attrs:{_i:7},model:{value:A._$g(7,"v-model"),callback:function(){},expression:"password"}})],1)],1),t("v-uni-view",{staticClass:A._$g(8,"sc"),attrs:{_i:8}},[t("v-uni-button",{staticClass:A._$g(9,"sc"),attrs:{type:"primary",_i:9},on:{click:function(e){return A.$handleViewEvent(e)}}},[A._v("\u767b\u5f55")])],1),t("v-uni-view",{staticClass:A._$g(10,"sc"),attrs:{_i:10}},[t("v-uni-navigator",{attrs:{url:"../reg/reg",_i:11}},[A._v("\u6ce8\u518c\u8d26\u53f7")]),t("v-uni-text",{attrs:{_i:12}},[A._v("|")]),t("v-uni-navigator",{attrs:{url:"../pwd/pwd",_i:13}},[A._v("\u5fd8\u8bb0\u5bc6\u7801")])],1),A._$g(14,"i")?t("v-uni-view",{staticClass:A._$g(14,"sc"),style:A._$g(14,"s"),attrs:{_i:14}},A._l(A._$g(15,"f"),(function(e,n,i,c){return t("v-uni-view",{key:e,staticClass:A._$g("15-"+c,"sc"),attrs:{_i:"15-"+c}},[t("v-uni-image",{attrs:{src:A._$g("16-"+c,"a-src"),_i:"16-"+c},on:{click:function(e){return A.$handleViewEvent(e)}}})],1)})),1):A._e()],1)},c=[];t.d(e,"b",(function(){return i})),t.d(e,"c",(function(){return c})),t.d(e,"a",(function(){return n}))},"4d70":function(A,e,t){"use strict";var n,i=function(){var A=this,e=A.$createElement,t=A._self._c||e;return t("v-uni-view",{staticClass:A._$g(0,"sc"),style:A._$g(0,"s"),attrs:{_i:0}},[A._t("default",null,{_i:1})],2)},c=[];t.d(e,"b",(function(){return i})),t.d(e,"c",(function(){return c})),t.d(e,"a",(function(){return n}))},"4ff3":function(A,e,t){"use strict";var n,i=function(){var A=this,e=A.$createElement,t=A._self._c||e;return t("v-uni-view",{staticClass:A._$g(0,"sc"),style:A._$g(0,"s"),attrs:{_i:0}},[A._t("default",null,{_i:1})],2)},c=[];t.d(e,"b",(function(){return i})),t.d(e,"c",(function(){return c})),t.d(e,"a",(function(){return n}))},"56ee":function(A,e,t){var n=t("c4e5");"string"===typeof n&&(n=[[A.i,n,""]]),n.locals&&(A.exports=n.locals);var i=t("7f7e").default;i("acfb2c2e",n,!0,{sourceMap:!1,shadowMode:!1})},"58bc":function(A,e,t){"use strict";var n={tTable:t("65e5").default},i=function(){var A=this,e=A.$createElement,t=A._self._c||e;return t("v-uni-view",{staticClass:A._$g(0,"sc"),staticStyle:{border:"none"},attrs:{_i:0}},[A._$g(1,"i")?t("v-uni-view",{staticClass:A._$g(1,"sc"),staticStyle:{display:"block"},attrs:{_i:1}},[t("v-uni-view",{staticClass:A._$g(2,"sc"),attrs:{_i:2}},[t("t-table",{staticStyle:{margin:"0rpx"},attrs:{_i:3}},[t("t-tr",{attrs:{_i:4}},[t("t-th",{attrs:{_i:5}},[A._v("\u57fa\u91d1\u540d")]),t("t-th",{attrs:{_i:6}},[A._v("\u65e5\u671f")]),t("t-th",{attrs:{_i:7}},[A._v("\u91d1\u989d")]),t("t-th",{attrs:{_i:8}},[A._v("\u64cd\u4f5c")])],1),A._l(A._$g(9,"f"),(function(e,n,i,c){return t("t-tr",{key:e,attrs:{_i:"9-"+c}},[t("t-td",{attrs:{_i:"10-"+c}},[A._v(A._$g("10-"+c,"t0-0"))]),t("t-td",{attrs:{_i:"11-"+c}},[A._v(A._$g("11-"+c,"t0-0"))]),t("t-td",{attrs:{_i:"12-"+c}},[A._v(A._$g("12-"+c,"t0-0"))]),t("t-td",{attrs:{_i:"13-"+c}},[t("v-uni-navigator",{staticStyle:{color:"#0077cc"},attrs:{_i:"14-"+c},on:{click:function(e){return A.$handleViewEvent(e)}}},[A._v("\u6295\u7968\u8be6\u60c5")])],1)],1)}))],2)],1)],1):A._e(),A._$g(15,"i")?t("v-uni-view",{staticClass:A._$g(15,"sc"),staticStyle:{"background-color":"#FFFFFF"},attrs:{_i:15}}):A._e()],1)},c=[];t.d(e,"b",(function(){return i})),t.d(e,"c",(function(){return c})),t.d(e,"a",(function(){return n}))},"596b":function(A,e,t){"use strict";function n(){function A(A){var e=t("3c23");e.__inject__&&e.__inject__(A)}"function"===typeof A&&A(),UniViewJSBridge.publishHandler("webviewReady")}t("9f3c"),"undefined"!==typeof plus?n():document.addEventListener("plusready",n)},"5c1c":function(A,e,t){"use strict";var n=t("2e29"),i=t.n(n);i.a},6015:function(A,e,t){"use strict";t.r(e);var n=t("d12e"),i=t("6951");for(var c in i)"default"!==c&&function(A){t.d(e,A,(function(){return i[A]}))}(c);t("f909");var o,a=t("f0c5"),r=Object(a["a"])(i["default"],n["b"],n["c"],!1,null,"08ae19da",null,!1,n["a"],o);e["default"]=r.exports},"62db":function(A,e,t){"use strict";var n,i=function(){var A=this,e=A.$createElement,t=A._self._c||e;return t("v-uni-view",{staticClass:A._$g(0,"sc"),class:A._$g(0,"c"),attrs:{"hover-class":A._$g(0,"a-hover-class"),_i:0},on:{click:function(e){return A.$handleViewEvent(e)}}},[t("v-uni-view",{staticClass:A._$g(1,"sc"),class:A._$g(1,"c"),attrs:{_i:1}},[A._$g(2,"i")?t("v-uni-view",{staticClass:A._$g(2,"sc"),attrs:{_i:2}},[t("v-uni-image",{staticClass:A._$g(3,"sc"),class:A._$g(3,"c"),attrs:{src:A._$g(3,"a-src"),_i:3}})],1):A._$g(4,"e")?t("v-uni-view",{staticClass:A._$g(4,"sc"),attrs:{_i:4}},[t("uni-icons",{staticClass:A._$g(5,"sc"),attrs:{_i:5}})],1):A._e(),t("v-uni-view",{staticClass:A._$g(6,"sc"),attrs:{_i:6}},[A._t("default",null,{_i:7}),A._$g(8,"i")?t("v-uni-text",{staticClass:A._$g(8,"sc"),attrs:{_i:8}},[A._v(A._$g(8,"t0-0"))]):A._e(),A._$g(9,"i")?t("v-uni-text",{staticClass:A._$g(9,"sc"),attrs:{_i:9}},[A._v(A._$g(9,"t0-0"))]):A._e()],2),t("v-uni-view",{staticClass:A._$g(10,"sc"),attrs:{_i:10}},[A._$g(11,"i")?t("v-uni-text",{staticClass:A._$g(11,"sc"),attrs:{_i:11}},[A._v(A._$g(11,"t0-0"))]):A._e(),A._$g(12,"i")?t("uni-badge",{attrs:{_i:12}}):A._e(),A._$g(13,"i")?t("v-uni-switch",{attrs:{disabled:A._$g(13,"a-disabled"),checked:A._$g(13,"a-checked"),_i:13},on:{change:function(e){return A.$handleViewEvent(e)}}}):A._e(),A._t("right",null,{_i:14}),A._$g(15,"i")?t("uni-icons",{staticClass:A._$g(15,"sc"),attrs:{_i:15}}):A._e()],2)],1)],1)},c=[];t.d(e,"b",(function(){return i})),t.d(e,"c",(function(){return c})),t.d(e,"a",(function(){return n}))},"64e4":function(A,e,t){"use strict";t.r(e);var n=t("a9f9"),i=t("7d91");for(var c in i)"default"!==c&&function(A){t.d(e,A,(function(){return i[A]}))}(c);t("a0ad");var o,a=t("f0c5"),r=Object(a["a"])(i["default"],n["b"],n["c"],!1,null,null,null,!1,n["a"],o);e["default"]=r.exports},"65e5":function(A,e,t){"use strict";t.r(e);var n=t("4ff3"),i=t("4af9");for(var c in i)"default"!==c&&function(A){t.d(e,A,(function(){return i[A]}))}(c);t("feeb");var o,a=t("f0c5"),r=Object(a["a"])(i["default"],n["b"],n["c"],!1,null,"2c41134d",null,!1,n["a"],o);e["default"]=r.exports},"66ba":function(A,e,t){var n=t("24fb");e=n(!1),e.push([A.i,".t-th[data-v-d1078a2a]{-webkit-box-flex:1;-webkit-flex:1;flex:1;display:-webkit-box;display:-webkit-flex;display:flex;-webkit-box-align:center;-webkit-align-items:center;align-items:center;font-size:30upx;font-weight:700;text-align:center;color:#3b4246;border-left:1px #d0dee5 solid;border-top:1px #d0dee5 solid;padding:15upx}",""]),A.exports=e},"68c5":function(A,e,t){var n=t("24fb");e=n(!1),e.push([A.i,".action-row{display:-webkit-box;display:-webkit-flex;display:flex;-webkit-box-orient:horizontal;-webkit-box-direction:normal;-webkit-flex-direction:row;flex-direction:row;-webkit-box-pack:center;-webkit-justify-content:center;justify-content:center}.action-row uni-navigator{color:#007aff;padding:0 10px}.oauth-row{display:-webkit-box;display:-webkit-flex;display:flex;-webkit-box-orient:horizontal;-webkit-box-direction:normal;-webkit-flex-direction:row;flex-direction:row;-webkit-box-pack:center;-webkit-justify-content:center;justify-content:center;position:absolute;top:0;left:0;width:100%}.oauth-image{position:relative;width:50px;height:50px;border:1px solid #ddd;border-radius:50px;margin:0 20px;background-color:#fff}.oauth-image uni-image{width:30px;height:30px;margin:10px}.oauth-image uni-button{position:absolute;left:0;top:0;width:100%;height:100%;opacity:0}",""]),A.exports=e},6951:function(A,e,t){"use strict";t.r(e);var n=t("cfea"),i=t.n(n);for(var c in n)"default"!==c&&function(A){t.d(e,A,(function(){return n[A]}))}(c);e["default"]=i.a},"6feb":function(A,e,t){var n=t("24fb");e=n(!1),e.push([A.i,".uni-list[data-v-614d7620]{display:-webkit-box;display:-webkit-flex;display:flex;background-color:#fff;position:relative;-webkit-box-orient:vertical;-webkit-box-direction:normal;-webkit-flex-direction:column;flex-direction:column}.uni-list--border[data-v-614d7620]{position:relative;border-top-color:#c8c7cc;border-top-style:solid;border-top-width:.5px;border-bottom-color:#c8c7cc;border-bottom-style:solid;border-bottom-width:.5px;z-index:-1}.uni-list--border-top[data-v-614d7620]{position:absolute;top:0;right:0;left:0;height:1px;-webkit-transform:scaleY(.5);transform:scaleY(.5);background-color:#c8c7cc;z-index:1}.uni-list--border-bottom[data-v-614d7620]{position:absolute;bottom:0;right:0;left:0;height:1px;-webkit-transform:scaleY(.5);transform:scaleY(.5);background-color:#c8c7cc}",""]),A.exports=e},"70f7":function(A,e,t){"use strict";t.r(e);var n=t("d339"),i=t.n(n);for(var c in n)"default"!==c&&function(A){t.d(e,A,(function(){return n[A]}))}(c);e["default"]=i.a},7167:function(A,e,t){var n=t("24fb");e=n(!1),e.push([A.i,".t-td[data-v-0f454c05]{-webkit-box-flex:1;-webkit-flex:1;flex:1;display:-webkit-box;display:-webkit-flex;display:flex;-webkit-box-align:center;-webkit-align-items:center;align-items:center;width:100%;padding:14upx;border-top:1px #d0dee5 solid;border-left:1px #d0dee5 solid;text-align:center;color:#555c60;font-size:28upx}",""]),A.exports=e},"71df":function(A,e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var n=i(t("7de8"));function i(A){return A&&A.__esModule?A:{default:A}}var c={props:["type","value","placeholder","clearable","displayable","focus"],data:function(){return{wxsProps:{}}},components:{mIcon:n.default}};e.default=c},7259:function(A,e,t){var n=t("24fb");e=n(!1),e.push([A.i,'@font-face{font-family:uniicons;src:url("data:font/truetype;charset=utf-8;base64,AAEAAAANAIAAAwBQRkZUTYoJ48wAAGf4AAAAHEdERUYAJwCMAABn2AAAAB5PUy8yWXpc3QAAAVgAAABgY21hcB9SCa8AAAPQAAADImdhc3D//wADAABn0AAAAAhnbHlmWWfecQAACAQAAFYcaGVhZBehAMAAAADcAAAANmhoZWEH+gSHAAABFAAAACRobXR4D3IujAAAAbgAAAIYbG9jYa77miAAAAb0AAABDm1heHABnACoAAABOAAAACBuYW1lj4vbUwAAXiAAAAM5cG9zdH/g11YAAGFcAAAGcwABAAAAAQAAGbvTeF8PPPUACwQAAAAAANoxE3MAAAAA2jSpUAAA/5UEHANrAAAACAACAAAAAAAAAAEAAAOA/4AAXASAAAAAAAQcAAEAAAAAAAAAAAAAAAAAAACGAAEAAACGAJwADAAAAAAAAgAAAAoACgAAAP8AAAAAAAAAAwQBAZAABQAAAokCzAAAAI8CiQLMAAAB6wAyAQgAAAIABQMAAAAAAAAAAAAAEAAAAAAAAAAAAAAAUGZFZABAAB3o6QOA/4AAXAOAAIAAAAABAAAAAAIAAs0AAAAgAAEEAAAAAAAAAAFVAAAEAABLBAAAiQQAACEEAABLBAAAlwQAACkEAABdBAAAJwQAACgEAAAABAAAcwQAACcEAAAoBAAAAAQAACAEgABVBAAAegQAACgEAACcBAAAkgQAAAgEAADNBAAAyQQAAN0EAADJBAAAeAQAAAYEAABCBAAAVgQAAGoEAACEBAAAhAQAAEsEAAAxBAAAMQQAAEsEAAAcBAAASwQAAEsEAABLBAAASwQAAEsEAAAcBAAASwQAAEsEAABLBAAASQQAAOMEAAEABAAASwQAABwEAAAdBAAAbQQAAJ8EAAFABAABQAQAALgEAAALBAAASwQAAFYEAAA/BAAASwQAAEsEAADRBAAAZAQAAIMEAAALBAAAVgQAAEsEAABLBAAAZAQAAFAEAABRBAAAkgQAAAQEAABqBAAAAAQAAIwEAACMBAABLwQAAS4EAAC7BAAAuwQAAHIEAAByBAABHgQAAA0EAAA5BAAAQAQAADEEAAAxBAAACAQAABEEAAASBAAASQQAAEsEAAAABAAAAAQAAAAEAACDBAAAVQQAADwEAABVBAAAVgQAADwEAABWBAAAKAQAACYEAAAmBAAA1gQAAEEEAAFfBAAAZwQAAEsEAAA/BAAABgQAAAAEAAAABAAASwQAAHgEAAAABAAAhAQAAJIEAACEBAAARQQAAIQEEgAcBBIAHAQSABwEEgAcAVUAAAAAAAMAAAADAAAAHAABAAAAAAIcAAMAAQAAABwABAIAAAAAfABAAAUAPAAAAB3hAuEy4gPiM+Jk4wPjM+Ng42TkCeQR5DTkOeRC5GPkZuRo5HLlCOUw5TLlNeU35WDlY+Vl5WjliOWQ5gnmEufW59nn7+f15/roAegl6EDoR+hO6FboXOhe6GToaOhu6Hfoe+iE6JLooeik6K/osei/6Nzo5ujp//8AAAAAAB3hAOEw4gDiMOJg4wDjMuNg42PkAOQQ5DTkN+RA5GDkZeRo5HDlAOUw5TLlNOU35WDlYuVl5WflgOWQ5gnmEufW59nn7+f05/roAegi6DvoR+hN6FboXOhe6GToaOhu6HfoeuiE6JLooeik6K/osei/6Nzo5Ojp//8AAf/kHwMe1h4JHd0dsR0WHOgcvBy6HB8cGRv3G/Ub7xvSG9Eb0BvJGzwbFRsUGxMbEhrqGuka6BrnGtAayRpRGkkYhhiEGG8YaxhnGGEYQRgsGCYYIRgaGBUYFBgPGAwYBxf/F/0X9RfoF9oX2BfOF80XwBekF50XmwABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQYAAAEAAAAAAAAAAQIAAAACAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEoAmgEgAWIBkAH4AnACwgMUA5YD3AQkBE4EoAU0Ba4GPgauBvQHVgfsCFAIigjgCRIJmgnkCkAKigsUC2oLvgwUDHQM1A1ADaYN+A42DmQOqA8CDzIPcA+aD9oQEhBAEGoQsBEAEfoSNhJmEnoSjhK6ExwTaBQuFIAU2hVIFYwV6BY+FpwXChdSF6wX4Bh4GN4ZHhmAGd4aGho8GmIahBqqGtwbDhtAG3IbhBwMHLgdOh1wHaYeEB5oHsgfFB8uH5QgAiBSIIog7iGgIgQiMCLiIzQjhCPUJDwkbCSmJNolNCViJZwl5iY+Jpgm0CdCJ64n+CgqKHIowik6KcQqJCquKw4rDgAAAAMAS//LA7UDNQALAB0AKQAABT4BNy4BJw4BBx4BEw4BBy4BJz4BNx4BFxQGBy4BJz4BNy4BJw4BBx4BAgC4+AUF+Li59wUF+LhijCIrMAEEzJybzQQxKyKMYj9TAQJSPz9TAQJSNQX4uLj4BQX4uLj4AR4BOScwfEebzQQEzZtHfDEoOUoBWkZDWgICWkNGWQAAAAAEAIn/8gN3Aw0ACwAXACIALQAAAT4BNy4BJw4BBx4BNy4BJz4BNx4BFw4BASEWJy4BJw4BBwY3Bjc0NjceARUWJwIAT2gCAmhPTmkCAmlOMEMBAUIxMkEBAUL+wgIaagEBxbCwxQEBVhEBnZSUnQEQAYACclVUbgICb1RVcT4CTDo5SgEBSTk6Tf4xAUZbsQYGsVtGQgENO4kGBok7DQEABQAh/6wD4ANUAAsAFwAsADgAVQAAAT4BNy4BJw4BBx4BNy4BJz4BNx4BFw4BByIGBxYXNjceARcWJyEGByEWJy4BAT4BNy4BJw4BBx4BNyImPQEjLgE0NjsBNTQ2MhYdATMyFhQGByMVFAYCaU5pAgJoT05pAgJpTjFCAQFCMTFCAQFCMTplKRsVP1mUnAEBEf6FAQoBcmoBAsT94lt8AgJ7XFx7AwN7XAsRUgsPDwtSERcQUgsPDwtSEAHHAnJVVW0CAm9TVXI/AUw7OUkBAUk5Ok13GRYWHB8BBok7DQEhIAFGW7H+IQJ8XFx7AgJ7XF17Sg4NWAEPFg9ZDA4ODFkPFg8BWA0OAAAAAAMAS//LA7UDNQALABcAJAAABT4BNy4BJw4BBx4BEx4BFw4BBy4BJz4BARcOASImJzc+ATceAQIAuPgFBfi4ufcFBfi4P1ICAVM/P1MBAVMBRAEziJaJMgEchmNjhTUF+Li4+AUF+Li4+AKnAlpDRloBAllGQ1r+DQU1Ojo1BSlBAgJBAAIAl///A2kDAQALABgAAAE+ATcuAScOAQceAQMhMjY1LgEnDgEHFBYCAEdjAgJjR0diAgJixgIaMioCv6iovwIqAYwBalJRZgEBZ1FRav5yHB1ZqAYGqFkdHAAABAAp/7ID2ANOAAsAGgAmAEMAAAE+ATcuAScOAQceARciBgceARUUByEyNicuAQE+ATcuAScOAQceATciJic1IyImNDY7ATU+ATIWFxUzMhYUBisBFQ4BAm9HYgICYkdHYgICYkc3XycvNggBbTIqAQG//etcewMCfFxcewICe10MEAFRDA8PDFEBEBcQAVEMDg4MUQEQAdkCaVJRZgEBZ1FRaU8YFCZuQSAfHRxZqP4sAnxbXHwCAnxcXHtKDgxZDxcPWQwODgxZDxcPWQwOAAIAXf/cA6QDJAAnAE4AAAUWNj8BNic2LwEmIg8BBicuAycmPwE+AS8BJiMmDwEOARUUHgI3Ii4CJzY3Njc+AR8BFhQPAQYUFx4DFxYyPwE2Mh8BFgYPAQYCzDdQIQknAQE5fR0/GyEODxI6MiwNCg4hGgEVVycuKSsMJCBu0NRdU8CrbwEBMgQFEycMUwcKJhYQEzc0QhoWMhYmChUKfRMBEgYuIwEhJQosKC8oVhQaIQ4KDDIyMxUODiEbPx19OAEnCSBQN13V0G5Ca6vEVEgtAwQQAhN9ChUKJhcxFho+NDoUEBYmCgZUDCcUCDEAAAUAJwAPA9kC8QANABcAHQAhAC4AADchMjY1ETQjISIGFREUCQE2MyEyFwEGIgURNRcHJgERJzcBIiclFxY3Fj8BBQYjrQKyOz+G/U46QAGm/rwOFAKqFA/+vRsy/oD39gEDMPX1/RMSDQEAHCwtLC0cAQAOEw9CQwHZhEJC/ieFAVsBQAYH/sEbuwHZBPLzBAHc/iLx8f3gBv0bKwEBKxv9BgAAAgAo/74D2AM5ABkAMAAAJTYXFjM+ATcuAScOAQcUFh8BMiMXHgEXNzYBNiQ3FgQXBgQHIicxJgYHBj4BLwEuAQFlKSsjJK/kBATkr6/kBEQ/EgECBxkZARoM/ssFAQrJyQEKBQX+9skrKCtZaC1EIx0XSlVkDgkFBLyJibwEBLyJRnwvDQQTLxsNBgFMqOAEBOCoqd8FBghFHwxHVhkQN5kAAAADAAD/tQQAAuUAJwBAAFkAABcyNj8BFhczFx4BMz4BPQEzPgE3NS4BJyM1LgEnIQ4BBxEeARczFRQ3LgErASImJxE+ATMhMhYXFSMOAQcVFBcHBScuASsBIiYnNT4BMyEyFhcVDgErASIGB/ENGRB4J0t7dxAWDRIUD0RQAQFQRDgBUEn+AkdTAQFTRy82AQ8MRjA0AQE0MAH3MDQB6UdNAQeDAiZyChIOdi0xAQExLQFULTEBATEtJgwPASMMD2srAWYNDwEXFVUBTEfSR0wBG0lPAQFPSf63SU8BYSqjEA4zMgFFMjMzMhkBTEfSHRh5J2cJBzAv0C8wMC/QLzAODwAAAAEAc//xA40DDwAsAAAlHgEXFjc+ATU0Ji8BJiMGDwEGIicuAycmND8BNjc0LwEmByIGBw4BFR4BAUxf0V5TOxITDQ+EHRccHB8HFAcUPUEzCwUGHh4BFVwYJBUqEx8dAnjNXnsCAT8TKxYQHgtdFQEeHgYEDDNBPRQIEgcgHBwXHoEfARMSHkkpXs8ABAAnAA8D2QLxAAoAEQAYACQAAAEWNwEmIyEiBwEWBQkBBhURFAU2NRE0JwkBITI3AQcGIi8BARYCARobAXQYP/1ONxUBdxv+SwEv/tAKA6gKCf7R/gwCsjYV/swdKlwqHf7MGAFPARwBcRYV/o4c+gErASwSLP4nLhITLQHZKxL+1f6QFAEyHCoqHP7PFQAAAQAo/74D2AM5ABYAABM2JDcWBBcGBAciJzEmBgcGPgEvAS4BKAUBCsnJAQoFBf72ySsoK1loLUQjHRdKVQGtqOAEBOCoqd8FBghFHwxHVhkQN5kAAgAA/7IEAALtABwANQAAFzI2PwEuASc1PgE7AScuASchDgEHER4BFzMVFBYFPgE9ATM+ATc1LgEnIQ4BHQEUFhczFx4B5gsSDWoQFQEBXlT+AQRHPv4PP0oBAUo/PBECWQ8RJj9KAQFKP/6aQkhIQnODDRIbCwxiCy4s8FRdDjhCAQFGQf6cQksBaREUMwEUEGoBS0HdQUYBAUZB3UFLAXcMDAAHACAAGgP6AzYACwAgACwAOABEAE0AVgAAATYmBwYmNzYWBwYmAS4BJzQ2Nz4BBwY2NzYWBwYWFxYCAy4BBw4BFx4BNz4BAwYWNzYWBwYWNzYmAQ4BJy4BNz4BFx4BIyYOAR4BPgEmNyYOAR4BPgEmAxsJLCMgCx5JWRMNNf6enPEGS0SU0yEEGANzhCIECQu3zhoLrXp6mAULrXp6mBkjDiVqgxwGPQ8nuP7XGnU9OioYG2w7PDG5EygXCSUqGAsqBw8IAw8QCAQCEyMxBgM2CwxlRh0R/iYBh3g/ikSNBIYRBQEvMF8NCQNN/ssBAVBaCg56UVBbCg96AkIMPwMRkGkkFCGTzP2hODESFV80MzAOEV0IDiUkEQ4mJCEDBg4NBwYPDQAAAAYAVf/2BBwDCgAWAB8AKAA5AEMATQAAATIXLgEnDgEHFBYXBzceATMyNyY1PgEnMhYUBiImNDYHIiY0NjIWFAYBLgEnDgEHHgEXMjY3Fyc+ASUiJjQ2Nx4BFAYzIiY0NjceARQGAuMREBm/gZHBBEhBIncgOR8QEAoCozsUFxcoHh7bFB8fJxcXAs0EqHd9owMDo30ZNBpeGjRD/oAOFBQOExcXqQ4UFQ0TFxcCGwJqhQIDo31GdC1nPAcKASImc5hgFycXFycXVRcnFxcnF/7uaYwDA4xpaowDCwc0VidkZRUaFAEBFBsUFRoUAQEUGxQAAAAJAHr/+gOGAwYABwAQABgAIAAoAEAASABQAFgAACUOAR8BPgE3JRUWFzI3JyYGEyIHFxY3NSYFBgcUFzc2JzcOAQchMjYnBxUUHwEWOwEyPwE2PQE0LwEmKwEiDwEGJQcGFzM2NzQDERQWPwEuAQEeARcRLgEHAfUCAgKQPGMj/hRNWigl7QIFpycl7gUBTf5FJQEI7gMGETxjIwFRAgICtgJeAgOFAwJeAgJeAgOFAwJeAgIm7QQGzCUBrQUCkBZN/YQVTjUBBAKoAQQCkBVNNUXNJQEI7QICAhcH7gMFzSXdTVsoJe4FAsgWTTUFAp2EAwJeAgJeAgOEBAJdAwNdAwftBQJNWycBHf6wAgICkDxj/lw8YyMBUQICAgAAAAAFACj/xQPYAzsAGAAxADoAQwBMAAAFMjY/ASE+ATURNCYjISIGFREUFhczFRQWNzU0JisBIiY1ETQ2MyEyFhURFAYjISIGBwMuASIGFBYyNjcuASIGFBYyNjc0JiIGFBYyNgEvEBsTlAETYGRkYP3YYGRkYBUYKA8RNUE+PkECKEE+PkH+6hEXDFEBIDAgIDAgxAEgMCAgMCDEITAgIDAhOxERgwFlXwFIX2VlX/64X2UBbxkdTnwSD0A/AUg/QEA//rg/QAgNAScYICAwISEYGCAgMCEhGBggIDAhIQAAAAEAnP/ZA2QDJgApAAAlLgEnFAYHHgEHBiYnDgEnJjY3LgE1DgEHIiY3Nj8BJjY3HgEHFxYXFgYDWhE2AykrGDsIE8A0NMATCDsYKykDNhEIAhoMECYFgI2MgAQmEAwaAnEETQYoWiYHHhQOAgYGAg4UHgcmWigGTQROVigoX5TKBATIll8oKFZOAAAABACSAKUDbgJbAA8AHwAtAD8AABMVHgEzITI2PQE0JiMhIgYnITIWFREUBiMhIiYnET4BBRUUHwEWNjc1LgEPAQYnNz4BHgEVERQOASYvASY9ATTbARQQASUPFRUP/tsQFAEBbh4rKx7+kh4qAQEqAjEHJAkUAQEUCSQHKW0JFBQLCxQUCW0OAe7cDxUVD9wPFRVeKx7+3B4rKx4BJB4rtUwJBR4GCguGCwoGHgUlWAYDCRIL/uILEgkCB1gLEXARAAAAAAUACP/nA/gDGQAbADsARwBVAGQAABchNjcRJisBIiYvAS4BKwEiBg8BDgErASIHERY3IiY1ETQ2OwEyNj8BPgE7ATIWHwEeATsBMhYVERQGIyU+ATcuAScOAQceAQEyNjc0LgEiDgEVFBYXAS4BJz4BNzIeAhQOAo8C4oYBAYZkGBoNIw8nIasgKA8jDRoYYYYBAYcgIyMgcR0kECIRHhx/HB4RIhAkHXQgIyMg/pBkgwMDg2RkgwMDgwGYFh4BDhkcGQ4eF/7MSF8CAl9IIj0wGhowPRkBhAHBhA0QJhITExImEA2E/j+ERCIiAbkiIQ4SJRQPDxQlEg4hIv5HIiJEA4RkZIQCAoRkZIQBUR4WDxgODhgPFh4B/u8BYEhIXwIZMD5EPjAZAAAAAAMAzf+1AzMDSwANABkAQgAAAREuAScOAQcRHgEXPgEnFAYiJjURNDYyFhcBIgYUFjMhMjY0JisBNT4BNzU0JiIGHQEOAQcuASc1NCYiBgcVHgEXFQKcAVVGRlUBAVVGRlVAMVMyMlMxAf7lDhISDgF/DRMTDaB9lAITGxMBgXBvggETGhMBApR9AZUBDktbAgJbS/7yS1wBAVxLMDg4MAEOMDc3MP1TExsTExsTZAyggFcNExMNVW+CAgKCb1UNExMNV4CgDGQAAgDJ/8QDNwM3ABAAHwAAAS4BJw4BBx4BHwEWMj8BPgElPgE3HgEXBgIHBiInJgIC7gKCamqCAgJsWQoLJAsKWWz93QOwhISwAwm4SRQzE0m4AduBkQEBkYFL0nUODQ0OddNKprUBAbWmg/7YVhYWVQEpAAACAN3/xAMjAzwADQA2AAABES4BJw4BBxEeARc+AQEOARQWMyEyNjQmJyM1PgE3NTQmIgYHFQ4BBy4BJzUuASIGHQEeARcVAoIBRzo6RwEBRzo6R/63DRMTDQGQDRMTDah3iwESGhIBAX1mZn0BARIaEgGLdgGAATI9TAEBTD3+zjxNAQFN/sEBExoTExoTAV4MmndlDRISDWVkfAICfGRlDRISDWV3mgxeAAAAAgDJ/8QDNwM3AA4AGgAAEz4BNx4BFwYCBwYiJyYCJT4BNy4BJw4BBx4ByQOwhISwAwm4SRQzE0m4AS4vPgEBPi8vPgEBPgHbprUBAbWmg/7YVhYWVQEpOgE+Ly8+AQE+Ly8+AAUAeP/AA4cDQAARAB0APgBKAFkAAAEeAR0BFxEuAScOAQ8BFzU+AQEWMjY0JwEmIgYUFxMiBhQWMyEyNjQmKwE1NjcnBgcuASc1NCYiBh0BHgEXFQE0JiIGBxUUBxc2NQUyNjcnBiMiJic1JxUeAQHoJSxCAk9COkwJAT8BLAGLChsTCv00ChsUCp4NExMNAZANExMNp1I7LjVLZnwCEhsSAop3AUMSGhIBBTUP/tUZJA41Bg8iJgFCAU0DAgEzJ85CAQ5EVgEBQzYNPiwnM/0dChMbCgLNChQbCv0WExoTExoTXggqLiQBAn1kZQ0SEg1ld5sMXgHhDRISDWUZGTMuN5MJCTQHKSIaQ1RKSQAAAwAG//UD+gMLAAwAHwArAAAXITI3ESYnISIHERYzAS4BDwEnJiciDwERNjMhMhYVESU+ATcuAScOAQceAY0C5oYBAYb9GoYBAYYCQR1HHcFQGx4dGoABQQLkICL9kio5AQE5Kis5AQE5CoQCDIQBhf30hQGMGgEbrUgYARhzAdhDISL+J9MBOiorOQICOSsqOQAAAAQAQv/RA74DLwAbACUALAA4AAAFMj8BNjURJiciDwEnJiIPAQYVERQWMzI/ARcWJSI1ETQ/AREHBgUmLwERHwETETc2NxYXERQPAQYCjRgT4SUBMA8U5OkTMBTeJhoXDxXZ7Rj+GAYOwMIDAdYJCboNv0XCBAIFAQ6sCi8LfxUrAlIwAQt+jgwMfxUq/a4YGgx1hQxpBwITDwlv/cxrAQ4FBWkCMgh0/c8CNWkCAQEG/e0QCGQGAAADAFb/zQOmAzAACQARACkAAAE3NjQvASYGDwEBNwEnAQcGFgMhMjY3EQcRDgEjISInETYzITchIgcRFgN8HwsLCgobCx/+TVMBezv+hicCCasB9zo/AUUBHhf+C0ECAkEBc0X+R4YBAQLKHwwbCwsKAgof/gckAXo6/oZQBgr+w0NCAd1F/mshIkMB50NFhP4ShQAABgBq/6EDlgNfAB8AKQAzAEAATQBZAAAlEzMyNjQmJyM1NCYnIw4BBxUjDgEUFjsBEx4BFyE+AQE0NjsBMhYdASMDLgEnAyEDDgEHJzI2NxM0JiIGBwMUFiMyNjUDNCYiBhUTHgE3ETQmIgYHER4BMjYDLh4rDRISDbw5MqEyOAG6DRMTDSsdAzgvAYkuOP5eGBSWFBjuRxMYAR4CDxwBGBQ/Cw4BDA4VDgENDvMLDg0PFQ4NAQ2kDxUPAQEPFQ8GAnMSGxMBQC42AQE2LkABEhwS/Y0vNQEBNQMfEhcXEjz9JwEYEwJs/ZQTGAFMDw0BxA0PDwz+OwwQEAwBxQwPDw3+PA0PHAHFDA8PDP47DBAQAAAAAgCE/5wDfQNkABoAOAAAJTI2NREnFxYyNjQvASYiDwEOARYyPwEHERQWAyE2JxE2JyMVMzIWFREUBiMhJicRNjczNSMiFREUAgAOFAJdChsSCpEMGgyRCQERHApeAxToAeyHAQGHd3YgIiIg/hdCAQFCdniG7BMOAbhAYwoQGwmMDAyMCRoRCmRB/kgOE/6wAYQBp4QBRSIi/mEiIgFDAZ9DAUWF/lmFAAAAAAIAhP+xA30DTgAaADgAACUyPwE2NCYiDwE3ETQmIgYVERcnJiIGFh8BFgMhMicRNicjFTMyFhURFAYjISInETY3MzUjBhURFAIADQyRChIbCl0CFBwUA14KHBEBCpAM6QHshwEBh3x7ICIiIP4XQgEBQnp8hssMiwobEApkQAHEDhMTDv48QGQKEBsKiw3+6IQBu4QBRSMh/k0iIUMBs0MBRQGE/kWFAAMAS//LA7UDNQALABcANAAABT4BNy4BJw4BBx4BNy4BJz4BNx4BFw4BJTI/ARcWMjY0LwE3NjQmIg8BJyYiBhQfAQcGFBYCALj4BQX4uLn3BQX4uJvNBATMnJvNBAPO/tIPCnp5Ch4TCnp7ChQcCnt7ChwUCnp6ChQ1Bfi4uPgFBfi4uPhEBMycm80EBM2bnMyyC3p6ChMeCXp7ChwUCnt6ChMdCnp6CR4TAAACADH/9gPPAwkAIAA+AAAFMjY3ATY0JwEuASMiBh0BIwYCFx4BMxY2Nz4BFzMVFBY3Ij0BNAcjDgEHBiI1PgE3MxY9ATQ2MhcBFhQHAQYCKw8cEAFSFxf+rhIZDxccDebVAQEZEg4bCzinew0cLwYOOpnCJQIFAqzZOg4DBwMBMQUF/s8ECQ4OAT8YLBgBPBAPHheiAv7w8BwdAQ0TaFABpBYcXAamDwEBX1IEBZ7xBwEPqgMDA/7bBAgE/t8EAAACADH/9gPPAwkAIAA+AAAFMjY9ATM2FhceATcyNjc2AicjNTQmIyIGBwEGFBcBHgEnIicBJjQ3ATYyFh0BFDczHgEXFCInLgEnIyYdARQB1RYcDXunNwwbDhIZAQHV5g0cFw8aEf6uFxcBUhAbCQME/s8FBQExAwcDDjrZrAIGASXCmToOCRwWpAFQZxQNAR0c8AEQA6IWHg8Q/sQYLBj+wQ4OXAQBIQQIBAElAwMDqg8BB/GfBARSXwEBD6YGAAADAEv/ywO1AzUACwAXAEMAAAU+ATcuAScOAQceATcuASc+ATceARcOAQEeARc+ATc0JiIGFQ4BBy4BJz4BNzIXBwYeATI/ATY0LwEmIgYUHwEmIw4BAgC4+AUF+Li59wUF+LibzQQEzJybzQQDzv6lAmxSUWsCERgRAko4OUoCAko5CAcqCAEOFwhTCAhSCBgOBx4GBkpqNQX4uLj4BQX4uLj4RATMnJvNBATNm5zMAVRSbQICbVEMEBAMOUoCAko5OEoCASkIGA8IUwgXCVQIEBcIHwECaQACABz/sQPkA0kAGQA9AAAXFj8BFxY2JwM3NiYjBQMmIgcDJSIGHwEDBjciPwE2LwEmNjMFFj8BNjIfARY3JTIWDwEGHwEWBi8BJg8BBtsaKOPjKDUQWeUoFDL+51UPQRBV/ucxFSnlWhBZAQFVCRbVAwEEAQMaCEoCAwFKCBoBBAMBA9UWClUBAgPOFhXPAjwTHqamHicuAQukHD8CAQwvL/70Aj8cpP71LkEE9RkPkwIDBQEa+AQE+BoBBQMCkw8Z9QQCA50QEJ4CAAADAEv/ywO1AzUACwAXADQAAAU+ATcuAScOAQceATcuASc+ATceARcOASc+ATc1MzI2NCYnIzUuASIGHQEjDgEUFjsBFRQWAgC4+AUF+Li59wUF+LibzQQEzJybzQQDzpwREwGGEhYVE4YBEyIShhMWFxKGEjUF+Li4+AUF+Li4+EQEzJybzQQEzZuczJwBFRN/EiMSAYYTFhYThgESIxJ/EhYAAAMAS//LA7UDNQALABcAIwAABT4BNy4BJw4BBx4BNy4BJz4BNx4BFw4BASEyNjQmIyEiBhQWAgC4+AUF+Li59wUF+LibzQQEzJybzQQDzv64AVkSFhUT/qcTFhc1Bfi4uPgFBfi4uPhEBMycm80EBM2bnMwBRBIiExMiEgACAEv/ywO1AzUACwAXAAAFPgE3LgEnDgEHHgE3LgEnPgE3HgEXDgECALj4BQX4uLn3BQX4uJvNBATMnJvNBAPONQX4uLj4BQX4uLj4RATMnJvNBATNm5zMAAAAAAIAS//LA7UDNQALACgAAAU+ATcuAScOAQceATciJjQ/AScmNDYyHwE3Nh4CDwEXFhQGIi8BBwYCALj4BQX4uLn3BQX4Hg8VC4CACxUeCoGBCx0UAQuAgAoVHgqAgAs1Bfi4uPgFBfi4uPjyFR4KgYAKHhQKgIAMARQeCoGACh8VCoGBCgAAAAACAEv/ywO1AzUACwA3AAAFPgE3LgEnDgEHHgEDPgE3MhcnJjQ2Mh8BHgEPAQYiJjQ/ASYHDgEHHgEXPgE3NDYyFhUOAQcuAQIAuPgFBfi4ufcFBfgLA2tMBgYfBw8YCFQHAQhUCRcPCCoHCDpMAQFMOjlLAhEZEQJtUlNuNQX4uLj4BQX4uLj4AZ5SawIBHwgYEAhWCBgIVAgPGAgqAQEBSzk6SwICSzoMEREMU24CAm8AAAABABz/sQPkA0kAGQAAFxY/ARcWNicDNzYmIwUDJiIHAyUiBh8BAwbbGijj4yg1EFnlKBQy/udVD0EQVf7nMRUp5VoQPBMepqYeJy4BC6QcPwIBDC8v/vQCPxyk/vUuAAACAEv/ywO1AzUACwAoAAAFPgE3LgEnDgEHHgE3IiY9ASMiJjQ2OwE1NDYyFh0BMzIWDgErARUUBgIAuPgFBfi4ufcFBfi3EhONExcWFI0TJBSNFBcBFhSNFDUF+Li4+AUF+Li4+NsXE4UTJROOExcWFI4TJROFFBYAAAAAAgBL/8sDtQM1AAsAFwAABT4BNy4BJw4BBx4BEyImNDYzITIWFAYjAgC4+AUF+Li59wUF+AMUFxcUAWoUFhcTNQX4uLj4BQX4uLj4AYoTJRMTJRMAAwBL/8sDtQM1AAsAFwAjAAAFPgE3LgEnDgEHHgE3LgEnPgE3HgEXDgEnPgE3LgEnDgEHHgECALj4BQX4uLn3BQX4uJvNBATMnJvNBAPOm3SeAwOedHadAwOeNQX4uLj4BQX4uLj4RATMnJvNBATNm5zMUgOedXWeAwOedXWeAAACAEn/yQO3AzcACwAgAAAFLgEnPgE3HgEXDgETJiIPAQYiLwEmIgYUHwEWMj8BNjQCALr4BQX4urr4BQX4CwkaCcgKGQk7ChkTCWgJGQr0CTcF+Lq6+AUF+Lq6+AJGCQnICgo6ChMZCmcJCfQKGQAAAQDjAGMDHQKdABsAADcGFBYyPwEXFjI2NC8BNzY0JiIPAScmIgYUHwHuCxYfDNzcCx8XC9zcCxcfC9zcDB8WC9ukCx8XC9zcCxcfC9zcCx8XC9zcCxcfC9wAAAABAQAAgAMAAtgAFgAAJS4BJz4BNzUXBzUOAQceARc+ATczDgECAG2QAwOQbcDAXHoCAnpcXHoCKAOQgAOQbW2QA1iAb28CelxcegICelxtkQAAAAABAEv/nQO1A14AKQAABT4BNy4BJyYOARYXHgEXDgEHLgEnPgE3FR4BPwE2NC8BJgYHFQ4BBx4BAgC4+AUBYlQPHREHDUVRAQPOm5vNBAOafAEZEooODokSGgGZxgMF+GMF+LhtuD0LBRwbCjKYXZvNBATNm4XAHj4WDA1gChsLYAwLFz0g66K4+AAAAAIAHP+xA+QDSQAZAC0AABcWPwEXFjYnAzc2JiMFAyYiBwMlIgYfAQMGJRE2HwEWNyUyFg8BBh8BFgYvASbbGijj4yg1EFnlKBQy/udVD0EQVf7nMRUp5VoQAUACAUoIGgEEAwED1RYKVQECA84KPBMepqYeJy4BC6QcPwIBDC8v/vQCPxyk/vUu5wIiAQT4GgEFAwKTDxn1BAIDnQgAAAAMAB3/nQPjA2MADAAZACYAMwBAAE0AWgBnAHQAgQCOAJsAAAEiBgcVHgEyNjc1LgEHDgEfAR4BPgEvAS4BBSYGDwEGHgE2PwE2JgUGFh8BFj4BJi8BJgYFLgEPAQ4BHgE/AT4BFzQmJyMOARQWFzM+ASUUFhczPgE0JicjDgEFNiYvASYOARYfARY2JR4BPwE+AS4BDwEOAQU+AS8BLgEOAR8BHgElFjY/ATYuAQYPAQYWFzI2NzUuASIGBxUeAQIADREBAREaEQEBEf4MBgZMBxgWBwdMBxcB2AwXCEwGBxYYB0wGBv1gBgcLhAsYDQYMhAsYAz8HGAuFCwYNFwyECwc6EQ6YDRERDZgOEfw6EQ2ZDRERDZkNEQOGBgcLhAwXDQYLhAwY/MEHGAuFCwYNGAuECwcCmgwGBkwHGBcGBkwIF/4pCxcISwcGGBcHTAYG/Q0RAQERGhEBAREDYxEOmA0REQ2YDhFABxgLhQsGDRgLhAsHBgYHC4QLGQwGC4ULGKoMFwhMBgYXGAdMBgYMDAYGTAcYFwYGTAgX5g0RAQERGhEBARENDREBAREaEQEBEf4LFwhMBgYXGAdMBgYMDAYGTAcYFwYGTAgXvQcYC4ULBg0XDIQLBwYGBwuEDBcNBgyECxhHEQ6YDRERDZgOEQAAAAIAbf/pA5QDFwAVACEAACUyNjcXFjI+AS8BPgE3LgEnDgEHHgE3LgEnPgE3HgEXDgEBtjRhK8sOKhoBDsogIwEEuoyMugMDuoxtkwICk21tkwMDk4QgHssOGykPyiplOYu7AwO7i4y6QwOTbW2SAwOSbW2TAAAAAAEAnwAXA2EC6AAcAAAlPgE1ESE+ATQmIyERNCYiBhURISIGFBYXIREUFgIAEBYBFRAWFhD+6xYgFv7rEBYWEAEVFhcBFQ8BHQEWIBYBHg8VFQ/+4hYgFgH+4w8VAAAAAAEBQABAAsACwAAFAAABNwkBJwEBQEEBP/7BQQD/An9B/sD+wEEA/wABAUAAQALAAsAABQAAAScJATcDAsBB/sEBP0H/An9B/sD+wEEA/wAAAQC4AIUDWgJ/ABcAAAEXFhQHAQYiLwEmND8BNjIfARYyNwE2MgNDDQoK/lwLHQy1CwsNCx0LdQwdCwFjCx0CdA0LHQv+XAsLtgsdDAwLC3UKCgFjCwAAAAIAC/+9A/UDQwAnAD0AABchPgE1ERcWFzI2NyYvATU0JicjDgEdAScmIgcBBgceATM2PwERFBYBNCYrASIGFREjJicRAT4BFwERBgcj5wIzLjI3DRIQFAEBDJURDjgOEaoXOBf+SwwBARQQEg03MwHCEQ+2DxKPKQEBJgcQBwEmASmQQwExLQGHMg4BEg8TCof9DhABARAOkZoVFf5yCRMPEgEOMv55LjABYQ8REQ/+4wEqAbUBDAYBB/70/ksqAQAAAAADAEv/ywO1AzUACwAXACwAAAU+ATcuAScOAQceATcuASc+ATceARcOASUyPwE2Mh8BFjI2JicDJiIHAwYUFgIAuPgFBfi4ufcFBfi4m80EBMycm80EA87+tQsGlAYKBpMIFQ0BA6QLKgqlAww1Bfi4uPgFBfi4uPhEBMycm80EBM2bnMyIB5QFBZQHDRMJAaMaGv5dCBQNAAQAVv/TA6wDKgAtAGYAcgB+AAAlNjc+ATc2NyY2NyYnBiY3NSYnBwYiLwEHFRYGJyMHFxYUDwEWFzM2FgcWFz4BByYnNzYmDwEmJzc2NC8BNjcXFjYvATY3FxYyPwEWFwcGFj8BFhcHBhQfAQYHJyYGHwEGBycmIg8BEz4BNy4BJw4BBx4BFy4BJz4BNx4BFw4BAoYPDwJlTQcGNwI4BAZSaQILDAI6lzoGEwJrUwoHBj09AwUFBFJrAQ4OOJGsQzsCATovMSMRJyEhKQ8gOC86AQM4PiUgUyAiQDcCATsuLCMOHiIiHBElJS86AQI8RBkgUyAcXy8+AQE+Ly8+AQE+L0ZdAgJdRkZdAgJdGwYHTWUCDw85kTgODgFrUgQFBQM9PQcIClNrAhMGOpc5AwwLAmlSBgQ4An4OIywvOgECN0AiIFMgJT44AwE6LzggDykhIScRIzEvOgECO0McIFMgGUQ8AgE7LiUlERwiIh8BPwE+Ly8+AQE+Ly8+OAJdRkZdAgJdRkZdAAAAAAMAP/+/A8EDQQAUACAALQAABTI2NwE2NCYiBwEOARUUFhcFEx4BAyUmNDclNj8BBwYHAyInAwE+ATcHBgcDBgJXFyIMARkMGCse/R8cJCgfATVaCRxr/tgKCQJEGRkxLhcSmAQDWgEmEigRFwwK2wRBJR8C3R4rGAz+5QohFx0cCVr+ziEpAb1aAwgE2woMFyUTEv15CgEoAScSMBYxGRr9vAkABABL/8sDtQM1AAsAFwAgADkAAAU+ATcuAScOAQceATcuASc+ATceARcOAQMyNjQmIgYUFgMzPgE0JisBNTQmKwEiBhQWOwEVIyIGFBYCALj4BQX4uLn3BQX4uJvNBATMnJvNBAPOnxgfHzAfIDCuDhERDjUREFENEhINLjUOERE1Bfi4uPgFBfi4uPhEBMycm80EBM2bnMwCASAvICAvIP57ARAaEdoSFREaEcURGhAAAAAABABL/8sDtQM1AAsAFwA8AEUAAAU+ATcuAScOAQceATcuASc+ATceARcOAQM+AT0BNDY3PgE3LgEOAQcGFRQWMzI2NzY3HgEVFAYHDgEdARQXPgE0JiIGFBYCALj4BQX4uLn3BQX4uJvNBATMnJvNBAPOpBATFRYgJwECTnBFCQQSCxIPCRUrHSMbHBgeIRMbGicbGzUF+Li4+AUF+Li4+EQEzJybzQQEzZuczAEPARENBREbDxMvJTY4ASseCwsODxEMJQEBHRkVHhIQJx8GIoABGSYZGSYZAAAAAAMA0f/LAy8DNQAUABwAKwAAASIGBxUGFREUFjMhMjY1ETQnNS4BBz4BMhYXFSEFMhYVERQGIyEGNRE0NjMCAF2FA0owMAGeMDBKA4X9AlqIWgL+wAFtDw4OD/5mHQ4PAzWBg2IJW/7FNDExNAE7Wwlig4H7Wl9fWmlBDhL+vBIPASIBRBIOAAAGAGQBLgOdAdMACAASABsAJQAuADgAAAEeARQGIiY0NjcOARQWMjY0JicFHgEUBiImNDY3DgEUFjI2NCYnBR4BFAYiJjQ2Nw4BFBYyNjQmJwIAFBoaKBoaFCMvL0YvLyP+thMbGycaGhQkLi5HLy8jApUUGhonGxsTIy8vRy4uJAGvARooGhooGiUBL0YvL0YvASQBGigaGigaJQEvRi8vRi8BJAEaKBoaKBolAS9GLy9GLwEAAAAAAgCD/9sDfQMlACEANAAAFz4BNzU+ATceARcyPgI3ES4BIw4BBy4BJyIOAgcRHgEBLgEnIgYHET4BMx4BFzY3EQ4BpA4SAQg6MHO4bTE1LRoBARkTD0A3brd0MTUtGgEBEgI5Z7l4JDwSBDYybrhzRiwFNSUBEg7uBA8BBUQFCxUkHQG0ERMBEAEFRAULFSQd/TgOEgEVBUQFCAgBkwsWBEQFAQ3+bwsWAAAAAAIAC/+9A/UDQwAhADkAABMeATM2NwE2MhcBFhcyNjcmLwE1NCYnIw4BHQEnJiIHAQYTFBYXMxE0NjczHgEVETM+ATURASYiBwELARQQEg0BogcQBwGiDRIQFAEBDJUQDjkOEaoXOBf+Swx6My2uEg+XDxKtLjL+lAcPB/6VAYMPEgEOAX0HB/6DDgESDxMKh/0OEAEBEA6SmxUV/nMK/oYtMQEBMQ8RAQERD/7PATEtATkBSAcH/rYAAAAAAgBW/9MDrAMqADgARAAABSYnNzYmDwEmJzc2NC8BNjcXFjYvATY3FxYyPwEWFwcGFj8BFhcHBhQfAQYHJyYGHwEGBycmIg8BNz4BNy4BJw4BBx4BAaFDOwIBOi8xIxEnISEpDyA4LzoBAzg+JSBTICJANwIBOy4sIw4eIiIcESUlLzoBAjxEGSBTIBxfTmcCAmdOTmcCAmcsDiMsLzoBAjdAIiBTICU+OAMBOi84IA8pISEnESMxLzoBAjtDHCBTIBlEPAIBOy4lJREcIiIf9gJnTk5nAgJnTk5nAAMAS//LA7UDNQALABQALQAABT4BNy4BJw4BBx4BEyImNDYyHgEGAy4BNDY7ATUjIiY0NjsBMhYdATMyFhQGBwIAuPgFBfi4ufcFBfi0FyAfMB8BIV4OEREONS4NEhINURARNQ4REQ41Bfi4uPgFBfi4uPgCSSAvICAvIP57ARAaEcURGhEVEtoRGhABAAAAAAMAS//LA7UDNQALADAAOQAABT4BNy4BJw4BBx4BEyI9ATQ2Nz4BNTQmJwYHDgEjIiYnNDc+AhYXDgEHDgEdARQGByImNDYyFg4BAgC4+AUF+Li59wUF+LAkHxkeHCQfLRUKERILEwEECUl2UgIBKSEXGBIQExwcJxwBHDUF+Li4+AUF+Li4+AFTIwYhKRETIBYaHgECJg0REA8LCyAtATs4JzEVDxwTBQ4SgRopGRkpGgAAAAMAZAEuA50B0wAJABMAHQAAAQ4BFBYyNjQmJyEOARQWMjY0JichDgEUFjI2NCYnAgAjLy9GLy8j/rYkLi5HLy8jApUjLy9HLi4kAdMBL0YvL0YvAQEvRi8vRi8BAS9GLy9GLwEAAAAABgBQABMDsALsABgAIQA5AEIAWwBkAAABMjY3MzI2NCYrAS4BIgYHISIOARYzIR4BNy4BNDYyFhQGBSIGFBYXMx4BMjY3IT4CJichLgEiBgcXIiY0Nh4BFAYBPgE3MzI2NCYnIy4BIgYHIQ4BHgEzIR4BNyImNDYyHgEGApohNAyUDRMTDZQMM0Q0C/46DxMBFQ4Bxgs0IhYcHSocHP3CDRMTDZkLNEQ0CwHBDxMBFQ7+Pws0RDMMYRUdHSscHAEZIjMLlQ0TEw2VCzRDNAv+Og4VARMPAcYLNCIVHRwrHAEeAh8lHxQdFB4mJh4UHRQfJTQBHCsdHCwcshMeEwEeJiUfARMdFAEeJSUeVR0qHQEcKxz+xQElHxMeEwEfJCQfARQdEx8lNB0rHBwrHQAAAAYAUQBHA7ACuQAIABQAHQApADIAPgAAEz4BNCYOARQWNyEyNjQmJyEOARQWAzI2NCYiBhQWNyE+AS4BJyEOARQWAz4BNCYOARQWNyEyNjQmJyEOARQWhhYgIC0eHtUCSQ8TEw/9tw8TE68WICAtHh7VAkkOFQETD/23DxMTrxcfIC0eHtUCSQ8TEw/9tw8TEwJNAR8sIAEeLh4TEx4TAQETHhP+6SAsIB8uHhIBFB0TAQETHhP+6QEeLSABHi4eExMeEwEBEx4TAAAAAAMAkgClA20CWwAMABkAJgAAEz4BMyEyFhQGByEiJhU+ATchHgEUBgchLgEVPgE3IR4BFAYjISImkgEUEAKSEBQUEP1uDxYBFBACkhAUFBD9bg8WARQQApIQFBQQ/W4PFgI3DxUVHxQBFqgQFAEBFCAUAQEVqBAUAQEUHxUVAAAAAgAE/88D/AMYAB0AOwAAASMuAScOAQcGHgE2Nz4BNx4BFyMiBh8BFjI/ATYmBTMeARc+ATc2LgEGBw4BBy4BJzM+AS8BLgEPAQYWA9o4FeilX6M7CwIZGgsyiU2HwRM9FgsMXAoaCl0MC/w1OBXopV+jOwsCGBsKMIlQiMATPRYLDFwKGgpdDAsBn6HUBAFORA0dEQQMOT4BA6qGGRGEDg6DEhlYodMEAU5DDh0RBAw4PwECqoYBGBKDDgEPgxEZAAAAAAEAav+3A50DUAAzAAAJAQYuAjcBPgEXFgYHAQYuAjcBPgEmBgcBDgEXFjY3ATY0Jy4BBwEGFhceATcBNi4BBgMm/sU/kG0DPAGuJl4lIgYl/lwQIhcDDwElCgETGAr+2SABHiBTIgGmPDU1jD/+UE4ESEvDUwE9CgETGgFw/sU9BG2PQAGtJgcjJV4m/lwQBBchEQElChgTAQr+2iJVHiACIQGmPos2NAE8/lBTw0tIBE4BPQocEwEAAAAAAwAAAC8EAAKyAAsAFwAgAAAlNiQ3JiQnBgQHFgQ3LgEnPgE3HgEXDgEnMjY0JiIGFBYCAOcBFQQE/urm5f7pBAQBGORadwICd1padwICd1ogLCtBLCwvDe5HRu4NDe5GR+5iA3dZWnYCAnZaWXeELEArK0AsAAAAAQCMAK8DdAJRABAAADcGFBYyNwkBFjI2NCcBJiIHlwsWIgsBMQExCyIWC/60DCIM8QojFQsBOP7ICxUjCgFUDAwAAAABAIwArgN0AlIAEQAAJTY3ATY0JgYHCQEuAQYUFwEWAgARDAFMCxcgDP7P/s8MIBcLAUwMrgEMAVQLIBgBC/7IATgLARggDP6tDAAAAQEvAAwC0QL0ABAAACUWMjY0JwkBNjQmIgcBBhQXAo8LIhUL/sgBOAsVIgv+rAwMFwsWIQwBMQExDCEWC/60DCIMAAABAS4ADALRAvQAEQAAJTI3ATY0JwEmIgYWFwkBBhQWAVYQDAFTDAz+rQwgGAELATj+yAsWDAsBTA0hDAFLDBcgDP7P/s8LIhYAAAAAAQC7/+sDRQMVABwAAAUyNjURJx8BFjI2NCcBJiIHAQYUFjI/AgcRFBYCABEVA4BiCyAVDP7kDSAM/uMMFSALYoADFRUVEQI0XI1gChUfDQEdDQ3+4w0fFQpgjVz9zBEVAAAAAAEAu//rA0UDFQAcAAABIgYVERcvASYiBhQXARYyNwE2NCYiDwI3ETQmAgARFQOAYgsgFQwBHA0gDAEdDBUgC2KAAxUDFRUR/cxcjWAKFR8N/uMNDQEdDR8VCmCNXAI0ERUAAAABAHIAOwOOAsYAHAAAExQXARYyNjQvAhchMjY0JiMhBz8BNi4CBwEGcg0BHQ0fFQpgkWgCHhEVFRH94meQYAsBFR8O/uQNAYAQDf7kDBUgC2KDBhUiFQaDYgsgFQEO/uUNAAAAAQByADsDjgLGABwAAAE0JwEmDgEUHwInISIGFBYzITcPAQYUFjI3ATYDjg3+5A4fFQpgkWj94hEVFRECHmiRYAoVHw0BHQ0BgBANARsOARUgC2KDBhUiFQaDYgsgFQwBHA0AAAEBHgAHAtoC3wAGAAAlEyMRIxEjAfzekZuQBwEoAbD+UAAAAAQADf/3A/MDCQAZAC4ARQBbAAAFMjY1ETQmIyIGDwEGKwEmHQEUNzMyHwEeASUWNjc+ATQmJy4BDgEXHgEUBgcGFgUiLwEuASsBBj0BNDsBMjY/ATYyFREUNxY2Nz4BNCYnLgEHDgEXHgEUBgcGFgH2FhwcFw8aEckEB39bW38HBMkQGwGCDRsKKi8uKwobGQMJJCgoJAkD/oEDBL4IDgiPGRmPCA4IvgMK2gwaChocHRkKGgwOAwoTFRYSCgMJHBYCqxceDxCyBAFgq2ABBLQODlcIBg07l6aXPA0FERsPNIGQgjMOHAYEqwcFARq1GQQIrAMG/bAGcAgFDSJdZl0jDAUHCh0OGkdORxoOHAAABgA5/98D0gMiACQATABQAGIAZgByAAABNDEmLwEuAQchJgYPAgYVHgEXMzI2Nx4BNzY3HgEzMRY3PgEHBisBIiYvAQcGBwYHIiYvAQcOASsBLgE9ATQ/AjY3ITIWHwIWBgcmJwcXIwYHFSE1JicRFBYzITI2NRElJicHASEiJjQ2NyEeARQGA74BAkwLNCH95CAyC1MBCQFiSwcoRxozjjsMChpHKC4pOi+MFxkEGCoPODgGCB0mFyoPOTgQKhcGLDoFAlIFDgInBwwDTAIMHNoCAgPxAh8j/ZYnIh8XApAXH/3/AgEDAWv+PBAWFhABxBAWFgIUAQUEwR8kAQEiH8gFHB5NZwMiIDsMMAsMICEBFiF5WgwUE0RECAYYARQTREUSFQI9LgESEQXHDgEKB8MGKElrAQECCg8G4OEHEv70FxsbFwEKBwEBAgEAFR8UAQEUHxUAAAAFAED/4APAAyAACwAfADMASABdAAABISImNDYzITIWFAYDIyImNDY7ATI2PQE0NjIWHQEOAQUjLgEnNTQ2MhYdARQWOwEyFhQGAyImPQE+ATczMhYUBisBIgYdARQGISImPQE0JisBIiY0NjsBHgEXFRQGA6D8wA4SEg4DQA4SEm7ADhISDsAOEhIcEgE2/fegKTYBEhwSEg6gDhIS7g4SATYpoA4SEg6gDhISAvIOEhIOwA4SEg7AKTYBEgFgEhwSEhwS/oASHBISDqAOEhIOoCk2AQE2KaAOEhIOoA4SEhwSAiASDqApNgESHBISDqAOEhIOoA4SEhwSATYpoA4SAAAAAAEAMf/2A88DCQAgAAAFMjY9ATM2FhceATcyNjc2AicjNTQmIyIGBwEGFBcBHgEB1RYcDXunNwwbDhIZAQHV5g0cFw8aEf6uFxcBUhAbCRwWpAFQZxQNAR0c8AEQA6IWHg8Q/sQYLBj+wQ4OAAEAMf/2A88DCQAgAAAFMjY3ATY0JwEuASMiBh0BIwYCFx4BMxY2Nz4BFzMVFBYCKw8cEAFSFxf+rhIZDxccDebVAQEZEg4bCzinew0cCQ4OAT8YLBgBPBAPHheiAv7w8BwdAQ0TaFABpBYcAAQACP/nA/gDGQAbACcANQBEAAAXITY3ESYrASImLwEuASsBIgYPAQ4BKwEiBxEWJS4BJz4BNx4BFw4BEyImNTQ+ATIeARUOAQcBMj4CNC4CIw4BBx4BjwLihgEBhmQYGg0jDychqyAoDyMNGhhhhgEBAfdkgwMDg2RkgwMDg9AXHg4ZHBkOAR4W/swiPTAaGjA9IkhfAgJfGQGEAcGEDRAmEhMTEiYQDYT+P4SIA4RkZIQCAoRkZIQBUR4WDxgODhgPFh4B/u8ZMD5EPjAZAl9ISGAAAwAR/9sD7wMlACUALgA3AAATHgE7ARMeATMhMjY0JiMhLgEvASEyNj8BNjcuASMhJy4BKwEiBgEeATI2NCYiBgUUFjI2NCYiBhEBEg2RRQYyLwH0DRISDf4TEhYDBwIgLzIHIgEBARUR/UQIAxkglw0SATgBJzopKTonAZAoOygoOygDBQ0T/ikuNRIcEgEXFC01LuMKBhATNxgZE/0OHicoOignHh4nJzwnJwAAAAAEABL/2wPvAyUAJAArADQAPQAAJSEyNjQmIyEuAS8BITI2PwE2Ny4BIyEnLgErASIGFBY7ARMeAQEHDgEjIScTMjY0JiIGFBYhMjY0JiIGFBYBbgH0DRISDf4TEhYDBwIgLzIHIgEBARUR/UQIAxkglw0SEg2RRQYyAmcfAhYT/d4lexwpKTonJwGuHigoOygoqxIcEgEXFC01LuMKBhATNxgZExoT/ikuNQHRzRQX+P1fKDooJzwnJzwnJzwnAAADAEn/yQO3AzcAFAAgACwAAAEWFA8BBiIvASY0NjIfARYyPwE2MgM+ATcuAScOAQceARcuASc+ATceARcOAQLFCQn0ChkJaAkTGQo7CRkKyAoZvJvPBATPm5vPBATPm7r4BQX4urr4BQX4AhQKGQr0CQlnChkTCjoKCsgJ/fUEz5ubzwQEz5ubz00F+Lq6+AUF+Lq6+AAAAAEAS//LA7UDNQALAAAFPgE3LgEnDgEHHgECALj4BQX4uLn3BQX4NQX4uLj4BQX4uLj4AAAFAAAAFgQAAr4ACwAcAC0ANgA8AAAlFjI+AScBJg4CFwE+ATcmJCcGBxc2Mx4BFxQPATY3JwYjLgEnNDcnDgEHFgQBLgMjIgcXJx4BFzMnAyQJFxABCf2RCBgQAQkCklhgAQP+6+hfUmImKVl1AhG/aFZiKzFZdQIWgl1mAQQBFgFdAREiKxgHB4TtAkMzD4YfCREXCQJvCAEQGAj9+zt7I0bqDQEcYRECdForJO0BH2MWAnZXMyqDPH8lReoBNxgrIhEBgw8yQwGGAAAFAAAAGAQAArsACwAdAC8ANwA/AAAlFj4BNCcBJg4CFyUGBxc2Mx4BFxQGBxc+ATcmJAM2NycGBy4BJz4BNycOAQcWBCU2NS4BJwYHEzY3AQYVHgEDHwoWEQj9lgkXEAEIAUtgUDA9Q8D7BFlOLlhhAQP+7OlnVjBCS8D7BAFeUi5dZgEEARYBpBECdVgsJVExKv7rFQJ0IQkBEBcJAmoIARAXCRQBHTATDMktGWMxLjx8I0bq/ZQBHjEVAQvFMhZoMy48fyRF698mK1l0AgEQ/nMBFQEVKjJXdQAABAAAAC8EAAKxAAsAFwAjACwAACU2JDcmJCcGBAcWBDcuASc+ATceARcOASc+ATcuAScOAQceATcuATQ2MhYUBgIA5wEVBAT+6+fk/ugEBAEY5L78BAT8vr39BAT9vVp2AgJ2Wlp3AQJ2Wh4oKDwnJy8M7kdG7g0N7kZH7i8LyDMtzA0NzC0zyCkCeFhadQICdVpYeIoBJzsoKDsnAAAAAAEAg//bA30DJQAhAAAXPgE3NT4BNx4BFzI+AjcRLgEjDgEHLgEnIg4CBxEeAaQOEgEIOjBzuG0xNS0aAQEZEw9AN263dDE1LRoBARIlARIO7gQPAQVEBQsVJB0BtBETARABBUQFCxUkHf04DhIAAAACAFX/wwOrAzwAMgBAAAATDgEHFhcWBw4BFRQXFgcOARUUHgEOARUUFjsBHgEVDgEHFBYzMjY3PgE3PgE3NCYnIyIBLgEnIx4BBw4BBzM+AdwaKAEBCgQHFB0PBwsPEgkTFgsqIZkdIwRABCIaFh0MMXQzKikBrpk8VQKrAWhSTTo3AQMxHj9KYAMzBiIfGQ0JAwkkGh4TCgcIIhYPHRARHRIgLAEbGC+HPB8hHRlem0I2bkt6mwT+62OGAyt8SlF1IwKFAAAAAAMAPP+dA8QDYwAwAGkAdwAAASMiBgcOAQcWFw4BFBcOARUUFwYVHgEXMzYXDgEHHgEXMjY3PgE3Mz4BNy4BJyMuAQczHgEXFgYHDgEHDgEnIic+ATcuASsBLgE1JjY3NjQnLgE1NDc2NTQnLgE1Jjc2NTQnLgE1NDc+AQUeARcOAQcjPgE1NCYnAZ47KUIYLDMBAQQWGAoPEQ4TAT8xohEBBUAEATUsHy8UJmZMUVJrAgJ1WI0rZXY8iaICASUrMnYyDBIKIQEFQAQBMyeZFRsBCw0GBAsJHQ0DCQgBLgoCCAQvEzoBuDtSAQFJNCcYFionA2MFBgs5KBAPEC81Fw8qFyEZGygxQAIBDiWJRC04ASMoSpRbA5dwb5YDFxlBA4dvRGk5QJ5fGRABJTeGNSUpARsWDxcMBg0FDxcNHhYJCwUEERQLIhcFCgMFEhAHIQwFBTADcVRVcgItYTg8ZygAAAAAAgBV/8QDqwM9ADIAQAAABT4BNyYnJjc+ATc0JyY3PgE1NC4BPgE1NCYnIyImJz4BNzQmIyIGBw4BBw4BFRQWFzMyAR4BFzMuATc+ATcjDgEDIxsoAQEKBQgUHAEPCAwPEgoSFgsqIZkeIgEFQAQiGhYdDDF0Myoqrpk8VP1WAWhSTTo3AQMxHj9KYDMGIh8YDgkDCSQaHhMKBwgiFg8dEBEdEiArARwYL4c8HiIdGV6cQTZuTHmbBAEVY4YDK3tLUXUjAoUAAAABAFb/9wOqAwkAFwAABTI2NzYSNy4BJyIGBy4BIw4BBxYSFx4BAgAHEQe40QIDhmo9XR0dXjxqhgMC0LkHEQkHBHQBB4pzjQJANzdAAo1ziv73cgQHAAAAAwA8/50DxANjADEAagB4AAAFMzI2Nz4BNyYnPgE0Jz4BNTQmJzY1LgEnIyInPgE3LgEnIgYHDgEHIw4BBx4BFzMeATcnLgEnJjY3PgE3PgEXMhcOAQceATsBHgEVFgYHBhQXHgEVFAcGFQYXHgEVFgcGFRQXHgEVFAcOASUuASc+ATczDgEVFBYXAmI7KUIYLDMBAQQWGAoPEQcHEwE/MaIRAQVABAE1LB8vFCZmTFFSawICdViNK2V2PImiAgElKzJ2MgwSCiEBBUAEATMnmRUbAQsNBgQLCR0MAQMJCAEuCgIIBC8TOv5IO1IBAUk0JxgWKidjBQYLOSgQDxAvNhYPKhgPHgwbKDFAAg0liUQtOAEjKEqUWwOWcW+WAxcZQQECh29EaTlAnl8ZEAElNoc1JSkBGxYPFwwGDQUPFwwfFgkLBAURFAsiFwUKAwUSEAchDAUFMANxVFVyAi1hODxnKAACAFb/9wOqAwkAFgAwAAATFhIXHgEyNjc2EjcuASciBgcuASMOARc+ATceARceATI2Nz4BNx4BFw4BBwYiJy4BVgLStwcRDhEHt9ICA4ZqPV0dHV48aoZCAl9NO0oVCA4ODQkVSjtNXwIFzIsHBQaLzAIHiv76dQQHBwR1AQaKc40CMywsMwKNc1ZmAQE6IgwKCgwiOgEBZlZ67VwFBVztAAAAAAQAKP/DA9gDPQAYACEAKgAzAAAFMjY/ASEyNjURNCYnIQ4BFREUFjsBFRQWEw4BIiY0NjIWFw4BIiY0NjIWFw4BIiY0NjIWASYNFg+bASFgZGRg/dhgZGRgFBRZASU1JCM2JdcBJTQlJDUl1wEkNSQkNSQ9Dg6NZV8BSF9lAQFlX/64X2V8FRcB/xskJDUlJRobJCQ1JSUaGyQkNSUlAAACACb/mwPaA2UAIgAsAAAXAScmNwE+ATIWFwEWFA8BATY1ETYmJwEuASIGBwEOARcRFBchMjcBJiIHARYxARToDQ4BbhAYGRYRAW8HB+YBEgoBERf+pxgqLioX/qYXEQF6ArI/Gf6LGzQb/okVHwER4RALARwNDQ0N/uQFDwfh/vASLAGyIioTAQsTFhYT/vUTKiL+Ti1YFwFxGxv+jRUABQAm/5UD2gNrABMAIwApADAAOgAAFyEyNRE2JicBLgEiBgcBDgEXERQBLgEiBg8BLQE+ATIWFw0CETcXByYBERQHJzcWASIjATYyFwEiI60CpoYBGB7+tRcrLioX/rUeGQECMxYtLSwWHP7/AUIPFxsWDwFD/wD98gH28QYDMAXw9AH9EwQFASsbMhsBKgUFa4UBqi02FwEEExYWE/78FzYt/laFAZsWFBQWG/37DA0NDPz8+wG2DPTsDAHI/koRDe3xBP4BASYcHP7aAAAAAAIA1v/OAyoDMgAUABwAAAEiBgcVBhURFBYzITI2NRE0JzUuAQc+ATIWFxUhAgBdhQNFKyoBqiorRQOF/QJaiFoC/sADMoGDZwdS/rkuKysuAUhSB2aDgftaX19abwAAAAMAQf/UA74DLAAHABQAIAAABREnJicRFxYlMj8BEQYPAQYXERQWBTY/ATY1ESYnIg8BAnHUCw3YCv4MDxW0DAzLJwEaAlAGB+AlATAPFL4sAs2BBwP9KXkFCgthAtcFB3UVKv2uGBkMAQV/FSoCUzABC2kAAgFf/7oCoQNGABMAHAAABTI2NxE+ATcuAScOAQceARcRHgEDLgE0NjIWFAYCAA4ZATZCAQJaRUVaAgFDNQEZIBcfHy4fH0ZkYAGKD1U4RVsCAltFOVUO/nZgYwLgASAuHx8uIAAAAAADAGf/ywOZAzUAFQAeADgAACUyNjc1PgE3NC4CIw4BBx4BFxUeAQMiJjQ2MhYUBhM+ATcuAScVHgEXDgEHLgEnPgE3NQ4BBx4BAgAOGQE2QgEYLjsgRVoCAUM1ARkgFx8fLh8fF8TUAQjFYUSJBgKnlZWnAgaJRGHFCAHUamRfyg9VOSA7LhgCW0Q6VA/KX2QCISAuICAuIP1AA2xLV2EBQwE7MDRGAgFHNDA7AUMBYVdLbAACAEv/ywO1AzUACwAXAAAFPgE3LgEnDgEHHgETLgEnPgE3HgEXDgECALj4BQX4uLn3BQX4uDdMAQFMNzhLAQFLNQX4uLj4BQX4uLj4ASwBSzg3SwEBSzc4SwAAAAEAP/+/A8EDQQAfAAAFMjY3ATY0JiIHAQ4BFRQWHwEWNjcBNhYHAQ4BHwEeAQJXFyIMARkMGCse/R8cJCgf6BQbDgHWCQ4H/koMBAdDCRxBJR8C3R4rGAz+5QohFx0cCUYGAw0BtwcOCf4oDBwV4iEpAAAAAwAG//UD+gMLAAwAGAAsAAAXITI3ESYnISIHERYzEy4BJz4BNx4BFw4BAy4BPQE3NjMyHwE3NjIfARUUBgeNAuaGAQGG/RqGAQGGuy08AQE8LSw8AQE85h8jgx0eIB1SzSBJIMUjHwqEAgyEAYX99IUBgQE7LS08AQE8LS07/sMBIx8bchobSbYbHLZDHyIBAAAAAAQAAP/ABAADAgAOABoAIwA6AAATNDYzITU0IyEiFREUOwEXITI1ETQjISIXEQYBLgE0NjIWFAYDIiY9ATc+ATIWHwE3PgEyFh8BFQ4BI41VUwIJef21enoTrgJLenr9tXoBAQEPJzIyTDMzvhscQxokKCcaJX8fMDIxH2MBHBoB2VNUCnh4/mh3u3gBnHd3/mR4AUoBM0wzM0wz/vMdGiA+FxwcGCByHSMiHl5RGh0ABAAA/8AEAAMCABMAIQAzADwAADczFQYzITI1ETQrATU0IyEiFREUNyInETY3IRYXFSEiFxETNjMhMhcRJy4BDwEnJiMiDwE3PgE0JiIGFBZ6SAF6Akt6ekh5/bV6ezsCAjsCSTsB/jt6AT4BOwJJOwKOGkAbrkUZHBkZZdImNDRNMzN7Q3h4AZx3P3h4/mh3Pj0BkTwBATw8d/7lARc9Pf69hhcBGJo/FhZYqQE0TTQ0TTQAAgBL/8sDtQM1AAsAIAAABT4BNy4BJw4BBx4BNyImNDcTNjIXExYUBiIvASYiDwEGAgC4+AUF+Li59wUF+A4KDAOfCikJnwQMFQePBQoFjwc1Bfi4uPgFBfi4uPjVDBMIAZUZGf5rCBMMBo8GBo8GAAUAeP/EA4cDPAAIABQANQBBAEgAAAERLgEnDgEHFQEWMjY0JwEmIgYUFxMOARQWMyEyNjQmJyM1NjcnBgcuASc1NCYiBh0BHgEXFQE0JiIGBxUUBxc2NQcnFR4BFzICagFGOzlHAQHoChsTCv00ChsUCp4NExMNAZANExMNp1I7LjVLZnwCER0RAop3AUMRHBEBBTUP570BRjojAawBBj1MAQFKOgf9cgoUGgsCzAoUGwr9FwETGhMTGhMBXgcqLiMBAnxkZA8REQ9kd5oMXgHfDxERD2QZGDQvNnq9QzxNAQAAAAMAAP/4BAADBAAZAC4ARAAABTI2NRE0JiciBg8BBisBIgcVFhczMh8BHgElFjY3PgE0JicuAQ4BFx4BFAYHBhYnFjY3PgE0JicuAQcOARceARQGBwYWAdsXGxwWEBkRuwUGf1sBAVt/BgW7DxwBqwwbCiouLioKGxkDCiMnJyQJBJ4LGwoZHB0YChoMDgQLEhUVEwkDCBwWAqYWHQEPELEEYKVgAQSzDg1XCQYNO5allTwMBhEcDjOBjoEzDhxqBwUMIlxmXCINBQgKHA8ZRk1HGg4cAAAAAAIAhP+xA30DTgALAC4AAAE+ATIWFzU0JiIGFRcRBz8BPgEWFA8BBiIvASY0NjIfAScRIyYVERQ3ITInETYjAd4BExwTARQcFEUCG0EJHRILkA0aDZALEhwKXQPThoYB7IcBAYcCWA0TEw3VDhMTDrr+8T4dRQoBEhsKjAwMjAobEgtiPgEPAYX+R4UBhAG5hAAAAAADAJIApQNuAlsAAAAMAB4AABMzITIVERQjISI1ETQFNz4BHgEVERQOASYvASY9ATSSSQFuSUn+kkkCM20JFBQLCxQUCW0OAltJ/txJSQEkSYdYBgMJEgv+4gsSCQIHWAsRcBEAAgCE/5wDfQNkABoALgAAAT4BPQEnFxYyNjQvASYiDwEOARYyPwEHFRQWAyE2JxE2KwERDgEiJjURIyIVERQCAA4UAl0KGxIKkQwaDJEJAREcCl4DFOgB7IcBAYfKARkkGcuGAh4BEg6HP2MKERoJjAwMjAkaEQpkQIcOEv19AYQBmoX+zRIYGBIBM4X+ZoUAAwBF/+QDuwMcABwAKgA4AAA3MzI9AT4BNx4BFxUUOwEyNj0BLgEnIw4BBxUUFhczMjY9ATQmJyMGBxUWITMyPQE0JyMOAR0BFBZlFwsCzaqrzAILFw4SA+u+Hr7rAxKJKScrKycpKwEBAkMoLS0oKCoqjgvxm7MBAbOb8QsQDe+u0QMD0a7vDRCqKCW5JicBASv8LCz8KwEBJya5JSgAAAUAhP+vA3wDUQAfACkANgBDAE8AABsBHgEzITI2NxMzMjY0JicjNS4BKwEiBgcVIw4BFBYzNzQ2OwEyFh0BIxMuATUTPgEyFhUDDgEFLgE1AzQ2MhYVExQGNw4BIiYnET4BMhYV1RsCLSgBcigtAhwxDRISDbABMyudKjMBrw4SEg7pGBSOFBjm/gwQEgEQGBATAQ/+3gwPFBEYEBIPnAERGBABARAYEgJ0/Y4pKiopAnISHBIBPSwzMyw9ARIcEn4SFxcSPf1RARIOAfENEhIN/g4OEQEBEQ4B8g0SEg3+Dw4SIA4SEg4B8Q0SEg0AAAIAHP+5BAkDOwBBAFwAACU1MzI+AjcuAS8BNzY1LgEnIgYPAScmDgIfAQcOAQcUHgI7ARUjLgEnPgE3Jj4CFz4BNx4BFxQHHgEXDgEHBRY/ATY0JiIPATcRNCYiBhURFycmDgEUHwEWAonOFigfEAEBLiY6BgEDeFs2Xh4cMRYqIxMBATcpMwESIysZwsJRagIBUUABID5LJSd6S3ifAwE8TAECZEz+ug0MkQoSGwpdAhQcFANeChwQCpANp0UQICgWJzoJDjsKClt4AjMuKg4GCBsnFjkMC0ArGCwiEkUCa1BFZBAnRDAOCzpFAQOfeA0ND15ATGUC7QEMjAkbEApjQAFKDhMTDv62QGMLARAbCYwMAAIAHAADBAoDOwAgADwAACUVDgEmJzUhLgEnPgE3Jj4CFz4BNx4BFxQHHgEXDgEHASYPAQYUFjI/AgcVHgEyNjc1JxcWMjY0LwEmAjYBJCMB/uxQawIBUUABIT5KJiZ7S3ifAwI9SwICZUz+ugwNkAoRHAlBHQMBEx0TAQNeChsRCpEMp3sUFRUUewJrUEVkECdEMA4LOkUBA594DQ0PXkBMZQIBagEMjAkbEQtEH0C2DhMTDrZAYwsRGwmMDAAAAAIAHAAIBAoDOwA/AFoAACU1Mz4BNy4BLwE3NjUuASciBg8BJyYOAh8BBw4BFRQeAjsBFSMuASc+ATcmPgIXPgE3HgEXFAceARcOAQcBNh8BFhQGIi8BFxEOASImJxE3BwYiJjQ/ATYCis0vPgEBLiU6BQECeVo3Xh4cMRUrIxMBAjcqMxIiLBjDw1BrAgFRQAEhPkomJntLeJ8DAj1LAgJlTP66DQyRChEbCl4DARMdEwEDXgkcEQqQDadFAT4vJzoJDjsKClt4AjMuKg4GCBsnFjkMC0ArGCwiEkUCa1BFZBAnRDAOCzpFAQOfeA0ND15ATGUCAWoBDIwJGxELY0D+tg4TEw4BSkBjCxEbCYwMAAAAAAIAHP+5BAkDOwAjAD4AACU1NC4BIg4BHQEhLgEnPgE3Jj4CFz4BNx4BFxQHHgEXDgEHBRY/ATY0JiIPATc1NCYiBh0BFycmDgEUHwEWAj0MFBgUDP70UWoCAVFAASA+SyUnekt4nwMBPEwBAmRM/roNDJEKEhsKXQIUHBQDXgocEAqQDafxDBQMDBQM8QJrUEVkECdEMA4LOkUBA594DQ0PXkBMZQLtAQyMCRsQCmNATw4TEw5PQGMLARAbCYwMAAAAEgDeAAEAAAAAAAAAEwAoAAEAAAAAAAEACABOAAEAAAAAAAIABwBnAAEAAAAAAAMAFQCbAAEAAAAAAAQACADDAAEAAAAAAAUAOwFEAAEAAAAAAAYACAGSAAEAAAAAAAoAKwHzAAEAAAAAAAsAEwJHAAMAAQQJAAAAJgAAAAMAAQQJAAEAEAA8AAMAAQQJAAIADgBXAAMAAQQJAAMAKgBvAAMAAQQJAAQAEACxAAMAAQQJAAUAdgDMAAMAAQQJAAYAEAGAAAMAAQQJAAoAVgGbAAMAAQQJAAsAJgIfAEMAcgBlAGEAdABlAGQAIABiAHkAIABpAGMAbwBuAGYAbwBuAHQAAENyZWF0ZWQgYnkgaWNvbmZvbnQAAHUAbgBpAGkAYwBvAG4AcwAAdW5paWNvbnMAAFIAZQBnAHUAbABhAHIAAFJlZ3VsYXIAAHUAbgBpAGkAYwBvAG4AcwA6AFYAZQByAHMAaQBvAG4AIAAxAC4AMAAwAAB1bmlpY29uczpWZXJzaW9uIDEuMDAAAHUAbgBpAGkAYwBvAG4AcwAAdW5paWNvbnMAAFYAZQByAHMAaQBvAG4AIAAxAC4AMAAwADsASgBhAG4AdQBhAHIAeQAgADMALAAgADIAMAAyADAAOwBGAG8AbgB0AEMAcgBlAGEAdABvAHIAIAAxADIALgAwAC4AMAAuADIANQAzADUAIAA2ADQALQBiAGkAdAAAVmVyc2lvbiAxLjAwO0phbnVhcnkgMywgMjAyMDtGb250Q3JlYXRvciAxMi4wLjAuMjUzNSA2NC1iaXQAAHUAbgBpAGkAYwBvAG4AcwAAdW5paWNvbnMAAEcAZQBuAGUAcgBhAHQAZQBkACAAYgB5ACAAcwB2AGcAMgB0AHQAZgAgAGYAcgBvAG0AIABGAG8AbgB0AGUAbABsAG8AIABwAHIAbwBqAGUAYwB0AC4AAEdlbmVyYXRlZCBieSBzdmcydHRmIGZyb20gRm9udGVsbG8gcHJvamVjdC4AAGgAdAB0AHAAOgAvAC8AZgBvAG4AdABlAGwAbABvAC4AYwBvAG0AAGh0dHA6Ly9mb250ZWxsby5jb20AAAAAAAIAAAAAAAAACQABAAAAAAAAAAAAAAAAAAAAAAAAAAAAhgAAAQIAAgEDAQQBBQEGAQcBCAEJAQoBCwEMAQ0BDgEPARABEQESARMBFAEVARYBFwEYARkBGgEbARwBHQEeAR8BIAEhASIBIwEkASUBJgEnAA4A7wEoASkBKgErASwBLQEuAS8BMAExATIBMwE0ATUBNgE3ATgBOQE6ATsBPAE9AT4BPwFAAUEBQgFDAUQBRQFGAUcBSAFJAUoBSwFMAU0BTgFPAVABUQFSAVMBVAFVAVYBVwFYAVkBWgFbAVwBXQFeAV8BYAFhAWIBYwFkAWUBZgFnAWgBaQFqAWsBbAFtAW4BbwFwAXEBcgFzAXQBdQF2AXcBeAF5AXoBewF8AX0BfgF/AYABgQGCAYMHdW5pMDAwMAdjb250YWN0BnBlcnNvbglwZXJzb25hZGQNY29udGFjdGZpbGxlZAxwZXJzb25maWxsZWQPcGVyc29uYWRkZmlsbGVkBXBob25lBWVtYWlsCmNoYXRidWJibGUJY2hhdGJveGVzC3Bob25lZmlsbGVkC2VtYWlsZmlsbGVkEGNoYXRidWJibGVmaWxsZWQPY2hhdGJveGVzZmlsbGVkBXdlaWJvBndlaXhpbgtwZW5neW91cXVhbgRjaGF0AnFxCHZpZGVvY2FtBmNhbWVyYQNtaWMIbG9jYXRpb24JbWljZmlsbGVkDmxvY2F0aW9uZmlsbGVkBm1pY29mZgVpbWFnZQNtYXAHY29tcG9zZQV0cmFzaAZ1cGxvYWQIZG93bmxvYWQFY2xvc2UEcmVkbwR1bmRvB3JlZnJlc2gEc3Rhcgt3aGl0ZWNpcmNsZQVjbGVhcg1yZWZyZXNoZmlsbGVkCnN0YXJmaWxsZWQKcGx1c2ZpbGxlZAttaW51c2ZpbGxlZAxjaXJjbGVmaWxsZWQOY2hlY2tib3hmaWxsZWQKY2xvc2VlbXB0eQxyZWZyZXNoZW1wdHkGcmVsb2FkCHN0YXJoYWxmDHNwaW5uZXJjeWNsZQZzZWFyY2gJcGx1c2VtcHR5B2ZvcndhcmQEYmFjaw5jaGVja21hcmtlbXB0eQRob21lCG5hdmlnYXRlBGdlYXIKcGFwZXJwbGFuZQRpbmZvBGhlbHAGbG9ja2VkBG1vcmUEZmxhZwpob21lZmlsbGVkCmdlYXJmaWxsZWQKaW5mb2ZpbGxlZApoZWxwZmlsbGVkCm1vcmVmaWxsZWQIc2V0dGluZ3MEbGlzdARiYXJzBGxvb3AJcGFwZXJjbGlwCWV5ZWZpbGxlZAx1cHdhcmRzYXJyb3cOZG93bndhcmRzYXJyb3cObGVmdHdhcmRzYXJyb3cPcmlnaHR3YXJkc2Fycm93C2Fycm93dGhpbnVwDWFycm93dGhpbmRvd24NYXJyb3d0aGlubGVmdA5hcnJvd3RoaW5yaWdodAhwdWxsZG93bgVzb3VuZARzaG9wBHNjYW4KdW5kb2ZpbGxlZApyZWRvZmlsbGVkDGNhbWVyYWZpbGxlZApjYXJ0ZmlsbGVkBGNhcnQIY2hlY2tib3gRc21hbGxjaXJjbGVmaWxsZWQOZXllc2xhc2hmaWxsZWQIZXllc2xhc2gDZXllCmZsYWdmaWxsZWQVaGFuZHRodW1ic2Rvd25fZmlsbGVkDmhhbmR0aHVtYnNkb3duEmhhbmR0aHVtYnN1cGZpbGxlZAtoZWFydGZpbGxlZAxoYW5kdGh1bWJzdXAOYmxhY2toZWFydHN1aXQKY2hhdGZpbGxlZA5tYWlsb3BlbmZpbGxlZAhtYWlsb3Blbgxsb2NrZWRmaWxsZWQJbWFwZmlsbGVkBm1hcHBpbg1tYXBwaW5lbGxpcHNlC3NtYWxsY2lyY2xlEHBhcGVycGxhbmVmaWxsZWQLaW1hZ2VmaWxsZWQMaW1hZ2VzZmlsbGVkBmltYWdlcw5uYXZpZ2F0ZWZpbGxlZA5taWNzbGFzaGZpbGxlZAtzb3VuZGZpbGxlZA5kb3dubG9hZGZpbGxlZA52aWRlb2NhbWZpbGxlZAx1cGxvYWRmaWxsZWQKaGVhZHBob25lcwt0cmFzaGZpbGxlZA1jbG91ZGRvd25sb2FkEWNsb3VkdXBsb2FkZmlsbGVkC2Nsb3VkdXBsb2FkE2Nsb3VkZG93bmxvYWRmaWxsZWQHdW5pMDAwOQAAAAAB//8AAgABAAAADAAAABYAAAACAAEAAQCFAAEABAAAAAIAAAAAAAAAAQAAAADVpCcIAAAAANoxE3MAAAAA2jSpUA==") format("truetype")}.uni-icons[data-v-57a0af20]{font-family:uniicons;text-decoration:none;text-align:center}',""]),A.exports=e},7333:function(A,e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var n={props:["align"],data:function(){return{wxsProps:{}}},components:{}};e.default=n},7374:function(A,e,t){"use strict";var n={mIcon:t("7de8").default},i=function(){var A=this,e=A.$createElement,t=A._self._c||e;return t("v-uni-view",{staticClass:A._$g(0,"sc"),attrs:{_i:0}},[t("v-uni-input",{staticClass:A._$g(1,"sc"),attrs:{focus:A._$g(1,"a-focus"),type:A._$g(1,"a-type"),value:A._$g(1,"a-value"),placeholder:A._$g(1,"a-placeholder"),password:A._$g(1,"a-password"),_i:1},on:{input:function(e){return A.$handleViewEvent(e)},focus:function(e){return A.$handleViewEvent(e)},blur:function(e){return A.$handleViewEvent(e)}}}),A._$g(2,"i")?t("v-uni-view",{staticClass:A._$g(2,"sc"),attrs:{_i:2}},[t("m-icon",{attrs:{_i:3},on:{click:function(e){return A.$handleViewEvent(e)}}})],1):A._e(),A._$g(4,"i")?t("v-uni-view",{staticClass:A._$g(4,"sc"),attrs:{_i:4}},[t("m-icon",{style:A._$g(5,"s"),attrs:{_i:5},on:{click:function(e){return A.$handleViewEvent(e)}}})],1):A._e()],1)},c=[];t.d(e,"b",(function(){return i})),t.d(e,"c",(function(){return c})),t.d(e,"a",(function(){return n}))},7376:function(A,e,t){"use strict";var n=t("13cd"),i=t.n(n);i.a},7567:function(A,e,t){"use strict";var n,i=function(){var A=this,e=A.$createElement,t=A._self._c||e;return t("v-uni-view",{staticClass:A._$g(0,"sc"),attrs:{_i:0}},[t("v-uni-view",{staticClass:A._$g(1,"sc"),attrs:{_i:1}},[t("v-uni-view",{staticClass:A._$g(2,"sc"),attrs:{_i:2}},[t("v-uni-text",{staticClass:A._$g(3,"sc"),attrs:{_i:3}},[A._v("\u8d26\xa0\xa0\u53f7\uff1a")]),t("m-input",{attrs:{_i:4},model:{value:A._$g(4,"v-model"),callback:function(){},expression:"account"}})],1),t("v-uni-view",{staticClass:A._$g(5,"sc"),attrs:{_i:5}},[t("v-uni-text",{staticClass:A._$g(6,"sc"),attrs:{_i:6}},[A._v("\u5bc6\xa0\xa0\u7801\uff1a")]),t("m-input",{attrs:{_i:7},model:{value:A._$g(7,"v-model"),callback:function(){},expression:"password"}})],1),t("v-uni-view",{staticClass:A._$g(8,"sc"),attrs:{_i:8}},[t("v-uni-text",{staticClass:A._$g(9,"sc"),attrs:{_i:9}},[A._v("\u624b\u673a\u53f7\uff1a")]),t("m-input",{attrs:{_i:10},model:{value:A._$g(10,"v-model"),callback:function(){},expression:"phone"}})],1),t("v-uni-view",{staticClass:A._$g(11,"sc"),attrs:{_i:11}},[t("v-uni-text",{staticClass:A._$g(12,"sc"),attrs:{_i:12}},[A._v("\u59d3\xa0\xa0\u540d\uff1a")]),t("m-input",{attrs:{_i:13},model:{value:A._$g(13,"v-model"),callback:function(){},expression:"real_name"}})],1),t("v-uni-view",{staticClass:A._$g(14,"sc"),attrs:{_i:14}},[t("v-uni-text",{staticClass:A._$g(15,"sc"),attrs:{_i:15}},[A._v("\u8eab\u4efd\u8bc1\uff1a")]),t("m-input",{attrs:{_i:16},model:{value:A._$g(16,"v-model"),callback:function(){},expression:"id_card"}})],1)],1),t("v-uni-view",{staticClass:A._$g(17,"sc"),attrs:{_i:17}},[t("v-uni-button",{staticClass:A._$g(18,"sc"),attrs:{type:"primary",_i:18},on:{click:function(e){return A.$handleViewEvent(e)}}},[A._v("\u6ce8\u518c")])],1)],1)},c=[];t.d(e,"b",(function(){return i})),t.d(e,"c",(function(){return c})),t.d(e,"a",(function(){return n}))},7883:function(A,e,t){var n=t("24fb");e=n(!1),e.push([A.i,'.cmd-progress[data-v-9f7e1b5a]{box-sizing:border-box;margin:0;padding:0;list-style:none;display:inline-block}.cmd-progress-line[data-v-9f7e1b5a]{width:100%;font-size:28upx;position:relative;display:-webkit-box;display:-webkit-flex;display:flex;-webkit-box-orient:horizontal;-webkit-box-direction:normal;-webkit-flex-direction:row;flex-direction:row;-webkit-box-pack:center;-webkit-justify-content:center;justify-content:center;-webkit-box-align:center;-webkit-align-items:center;align-items:center}.cmd-progress-outer[data-v-9f7e1b5a]{display:inline-block;width:100%;margin-right:0;padding-right:0}.cmd-progress-show-info .cmd-progress-outer[data-v-9f7e1b5a]{-webkit-box-flex:1;-webkit-flex:1;flex:1}.cmd-progress-inner[data-v-9f7e1b5a]{display:inline-block;width:100%;background-color:#f5f5f5;border-radius:200upx;vertical-align:middle;position:relative}.cmd-progress-circle-trail[data-v-9f7e1b5a]{stroke:#f5f5f5}.cmd-progress-circle-path[data-v-9f7e1b5a]{stroke:#1890ff;-webkit-animation:appear .3s;animation:appear .3s}.cmd-progress-success-bg[data-v-9f7e1b5a],\n.cmd-progress-bg[data-v-9f7e1b5a]{background-color:#1890ff;-webkit-transition:all .4s cubic-bezier(.08,.82,.17,1) 0s;transition:all .4s cubic-bezier(.08,.82,.17,1) 0s;position:relative}.cmd-progress-success-bg[data-v-9f7e1b5a]{background-color:#52c41a;position:absolute;top:0;left:0}.cmd-progress-text[data-v-9f7e1b5a]{word-break:normal;width:60upx;text-align:left;margin-left:16upx;vertical-align:middle;display:inline-block;white-space:nowrap;color:rgba(0,0,0,.45);line-height:1}.cmd-progress-status-active .cmd-progress-bg[data-v-9f7e1b5a]:before{content:"";opacity:0;position:absolute;top:0;left:0;right:0;bottom:0;background:#fff;border-radius:20upx;-webkit-animation:cmd-progress-active-data-v-9f7e1b5a 2.4s cubic-bezier(.23,1,.32,1) infinite;animation:cmd-progress-active-data-v-9f7e1b5a 2.4s cubic-bezier(.23,1,.32,1) infinite}.cmd-progress-status-exception .cmd-progress-bg[data-v-9f7e1b5a]{background-color:#f5222d}.cmd-progress-status-exception .cmd-progress-text[data-v-9f7e1b5a]{color:#f5222d}.cmd-progress-status-exception .cmd-progress-circle-path[data-v-9f7e1b5a]{stroke:#f5222d}.cmd-progress-status-success .cmd-progress-bg[data-v-9f7e1b5a]{background-color:#52c41a}.cmd-progress-status-success .cmd-progress-text[data-v-9f7e1b5a]{color:#52c41a}.cmd-progress-status-success .cmd-progress-circle-path[data-v-9f7e1b5a]{stroke:#52c41a}.cmd-progress-circle .cmd-progress-inner[data-v-9f7e1b5a]{position:relative;line-height:1;background-color:initial}.cmd-progress-circle .cmd-progress-text[data-v-9f7e1b5a]{display:block;position:absolute;width:100%;text-align:center;line-height:1;top:50%;-webkit-transform:translateY(-50%);transform:translateY(-50%);left:0;margin:0;color:rgba(0,0,0,.65);white-space:normal}.cmd-progress-circle .cmd-progress-status-exception .cmd-progress-text[data-v-9f7e1b5a]{color:#f5222d}.cmd-progress-circle .cmd-progress-status-success .cmd-progress-text[data-v-9f7e1b5a]{color:#52c41a}@-webkit-keyframes cmd-progress-active-data-v-9f7e1b5a{0%{opacity:.1;width:0}20%{opacity:.5;width:0}100%{opacity:0;width:100%}}@keyframes cmd-progress-active-data-v-9f7e1b5a{0%{opacity:.1;width:0}20%{opacity:.5;width:0}100%{opacity:0;width:100%}}',""]),A.exports=e},"7d91":function(A,e,t){"use strict";t.r(e);var n=t("ae00"),i=t.n(n);for(var c in n)"default"!==c&&function(A){t.d(e,A,(function(){return n[A]}))}(c);e["default"]=i.a},"7de8":function(A,e,t){"use strict";t.r(e);var n=t("a96a"),i=t("9fa1");for(var c in i)"default"!==c&&function(A){t.d(e,A,(function(){return i[A]}))}(c);t("1b4e");var o,a=t("f0c5"),r=Object(a["a"])(i["default"],n["b"],n["c"],!1,null,"a4c0901e",null,!1,n["a"],o);e["default"]=r.exports},"7e78":function(A,e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var n={name:"UniIcons",props:["type","color","size"],data:function(){return{wxsProps:{}}},components:{}};e.default=n},"7f59":function(A,e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var n=i(t("a261"));function i(A){return A&&A.__esModule?A:{default:A}}var c={data:function(){return{wxsProps:{}}},components:{mInput:n.default}};e.default=c},"7f7e":function(A,e,t){"use strict";function n(A,e){for(var t=[],n={},i=0;i<e.length;i++){var c=e[i],o=c[0],a=c[1],r=c[2],s=c[3],B={id:A+":"+i,css:a,media:r,sourceMap:s};n[o]?n[o].parts.push(B):t.push(n[o]={id:o,parts:[B]})}return t}t.r(e),t.d(e,"default",(function(){return g}));var i="undefined"!==typeof document;if("undefined"!==typeof DEBUG&&DEBUG&&!i)throw new Error("vue-style-loader cannot be used in a non-browser environment. Use { target: 'node' } in your Webpack config to indicate a server-rendering environment.");var c={},o=i&&(document.head||document.getElementsByTagName("head")[0]),a=null,r=0,s=!1,B=function(){},l=null,u="data-vue-ssr-id",f="undefined"!==typeof navigator&&/msie [6-9]\b/.test(navigator.userAgent.toLowerCase());function g(A,e,t,i){s=t,l=i||{};var o=n(A,e);return E(o),function(e){for(var t=[],i=0;i<o.length;i++){var a=o[i],r=c[a.id];r.refs--,t.push(r)}e?(o=n(A,e),E(o)):o=[];for(i=0;i<t.length;i++){r=t[i];if(0===r.refs){for(var s=0;s<r.parts.length;s++)r.parts[s]();delete c[r.id]}}}}function E(A){for(var e=0;e<A.length;e++){var t=A[e],n=c[t.id];if(n){n.refs++;for(var i=0;i<n.parts.length;i++)n.parts[i](t.parts[i]);for(;i<t.parts.length;i++)n.parts.push(w(t.parts[i]));n.parts.length>t.parts.length&&(n.parts.length=t.parts.length)}else{var o=[];for(i=0;i<t.parts.length;i++)o.push(w(t.parts[i]));c[t.id]={id:t.id,refs:1,parts:o}}}}function d(){var A=document.createElement("style");return A.type="text/css",o.appendChild(A),A}function w(A){var e,t,n=document.querySelector("style["+u+'~="'+A.id+'"]');if(n){if(s)return B;n.parentNode.removeChild(n)}if(f){var i=r++;n=a||(a=d()),e=b.bind(null,n,i,!1),t=b.bind(null,n,i,!0)}else n=d(),e=v.bind(null,n),t=function(){n.parentNode.removeChild(n)};return e(A),function(n){if(n){if(n.css===A.css&&n.media===A.media&&n.sourceMap===A.sourceMap)return;e(A=n)}else t()}}var Q=function(){var A=[];return function(e,t){return A[e]=t,A.filter(Boolean).join("\n")}}();function b(A,e,t,n){var i=t?"":F(n.css);if(A.styleSheet)A.styleSheet.cssText=Q(e,i);else{var c=document.createTextNode(i),o=A.childNodes;o[e]&&A.removeChild(o[e]),o.length?A.insertBefore(c,o[e]):A.appendChild(c)}}function v(A,e){var t=F(e.css),n=e.media,i=e.sourceMap;if(n&&A.setAttribute("media",n),l.ssrId&&A.setAttribute(u,e.id),i&&(t+="\n/*# sourceURL="+i.sources[0]+" */",t+="\n/*# sourceMappingURL=data:application/json;base64,"+btoa(unescape(encodeURIComponent(JSON.stringify(i))))+" */"),A.styleSheet)A.styleSheet.cssText=t;else{while(A.firstChild)A.removeChild(A.firstChild);A.appendChild(document.createTextNode(t))}}var x=/([+-]?\d+(\.\d+)?)[r|u]px/g,h=/var\(--status-bar-height\)/gi,p=/var\(--window-top\)/gi,C=/var\(--window-bottom\)/gi,m=!1;function F(A){if(!uni.canIUse("css.var")){!1===m&&(m=plus.navigator.getStatusbarHeight());var e={statusBarHeight:m,top:window.__WINDOW_TOP||0,bottom:window.__WINDOW_BOTTOM||0};A=A.replace(h,e.statusBarHeight+"px").replace(p,e.top+"px").replace(C,e.bottom+"px")}return A.replace(/\{[\s\S]+?\}/g,(function(A){return A.replace(x,(function(A,e){return uni.upx2px(e)+"px"}))}))}},"7f99":function(A,e,t){"use strict";var n=t("93ef"),i=t.n(n);i.a},"80c8":function(A,e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var n=c(t("ab4a")),i=c(t("c1fa"));function c(A){return A&&A.__esModule?A:{default:A}}var o={name:"UniListItem",props:["title","note","disabled","clickable","link","to","showBadge","showSwitch","switchChecked","badgeText","badgeType","rightText","thumb","thumbSize","showExtraIcon","extraIcon"],data:function(){return{wxsProps:{}}},components:{uniIcons:n.default,uniBadge:i.default}};e.default=o},8109:function(A,e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var n={props:["align"],data:function(){return{wxsProps:{}}},components:{}};e.default=n},"86f6":function(A,e,t){"use strict";var n=t("a081"),i=t.n(n);i.a},"8a4e":function(A,e,t){"use strict";var n,i=function(){var A=this,e=A.$createElement,t=A._self._c||e;return A._$g(0,"i")?t("v-uni-text",{staticClass:A._$g(0,"sc"),class:A._$g(0,"c"),style:A._$g(0,"s"),attrs:{_i:0},on:{click:function(e){return A.$handleViewEvent(e)}}},[A._v(A._$g(0,"t0-0"))]):A._e()},c=[];t.d(e,"b",(function(){return i})),t.d(e,"c",(function(){return c})),t.d(e,"a",(function(){return n}))},"8ac0":function(A,e,t){"use strict";t.r(e);var n=t("bc53"),i=t.n(n);for(var c in n)"default"!==c&&function(A){t.d(e,A,(function(){return n[A]}))}(c);e["default"]=i.a},"8e8b":function(A,e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var n={props:["type"],data:function(){return{wxsProps:{}}},components:{}};e.default=n},"8f66":function(A,e,t){"use strict";t.r(e);var n=t("2d2c"),i=t("c6c7");for(var c in i)"default"!==c&&function(A){t.d(e,A,(function(){return i[A]}))}(c);t("5c1c");var o,a=t("f0c5"),r=Object(a["a"])(i["default"],n["b"],n["c"],!1,null,"9f7e1b5a",null,!1,n["a"],o);e["default"]=r.exports},"93bb":function(A,e,t){"use strict";t.r(e);var n=t("7333"),i=t.n(n);for(var c in n)"default"!==c&&function(A){t.d(e,A,(function(){return n[A]}))}(c);e["default"]=i.a},"93ef":function(A,e,t){var n=t("6feb");"string"===typeof n&&(n=[[A.i,n,""]]),n.locals&&(A.exports=n.locals);var i=t("7f7e").default;i("4a254516",n,!0,{sourceMap:!1,shadowMode:!1})},"9e28":function(A,e,t){var n=t("2544");"string"===typeof n&&(n=[[A.i,n,""]]),n.locals&&(A.exports=n.locals);var i=t("7f7e").default;i("6c3534b4",n,!0,{sourceMap:!1,shadowMode:!1})},"9f3c":function(A,e,t){"undefined"===typeof Promise||Promise.prototype.finally||(Promise.prototype.finally=function(A){var e=this.constructor;return this.then((function(t){return e.resolve(A()).then((function(){return t}))}),(function(t){return e.resolve(A()).then((function(){throw t}))}))}),uni.restoreGlobal&&uni.restoreGlobal(weex,plus,setTimeout,clearTimeout,setInterval,clearInterval),__definePage("pages/main/main",(function(){return Vue.extend(t("a82f").default)})),__definePage("pages/login/login",(function(){return Vue.extend(t("e288").default)})),__definePage("pages/reg/reg",(function(){return Vue.extend(t("1ee0").default)})),__definePage("pages/pwd/pwd",(function(){return Vue.extend(t("cbf5").default)})),__definePage("pages/user/user",(function(){return Vue.extend(t("64e4").default)})),__definePage("pages/detail/detail",(function(){return Vue.extend(t("1244").default)})),__definePage("pages/vertify/vertify",(function(){return Vue.extend(t("d71f").default)}))},"9fa1":function(A,e,t){"use strict";t.r(e);var n=t("8e8b"),i=t.n(n);for(var c in n)"default"!==c&&function(A){t.d(e,A,(function(){return n[A]}))}(c);e["default"]=i.a},"9fba":function(A,e,t){"use strict";t.r(e);var n=t("cfe3"),i=t("3750");for(var c in i)"default"!==c&&function(A){t.d(e,A,(function(){return i[A]}))}(c);t("7f99");var o,a=t("f0c5"),r=Object(a["a"])(i["default"],n["b"],n["c"],!1,null,"614d7620",null,!1,n["a"],o);e["default"]=r.exports},a081:function(A,e,t){var n=t("ea78");"string"===typeof n&&(n=[[A.i,n,""]]),n.locals&&(A.exports=n.locals);var i=t("7f7e").default;i("581eae54",n,!0,{sourceMap:!1,shadowMode:!1})},a0ad:function(A,e,t){"use strict";var n=t("9e28"),i=t.n(n);i.a},a194:function(A,e,t){"use strict";var n,i=function(){var A=this,e=A.$createElement,t=A._self._c||e;return t("v-uni-view",{staticClass:A._$g(0,"sc"),attrs:{_i:0}},[t("v-uni-form",{attrs:{_i:1},on:{submit:function(e){return A.$handleViewEvent(e)},reset:function(e){return A.$handleViewEvent(e)}}},[t("v-uni-view",{staticClass:A._$g(2,"sc"),staticStyle:{"text-align":"center",width:"100%","font-size":"32rpx","padding-bottom":"10rpx"},attrs:{_i:2}},[t("v-uni-view",{staticClass:A._$g(3,"sc"),attrs:{_i:3}},[t("v-uni-text",{staticClass:A._$g(4,"sc"),attrs:{_i:4}},[A._v("\u59d3 \u540d\uff1a")]),t("m-input",{staticClass:A._$g(5,"sc"),attrs:{_i:5},model:{value:A._$g(5,"v-model"),callback:function(){},expression:"realname"}})],1),t("v-uni-view",{staticClass:A._$g(6,"sc"),attrs:{_i:6}},[t("v-uni-text",{staticClass:A._$g(7,"sc"),attrs:{_i:7}},[A._v("\u8eab\u4efd\u8bc1\uff1a")]),t("m-input",{attrs:{_i:8},model:{value:A._$g(8,"v-model"),callback:function(){},expression:"idcard"}})],1)],1),t("v-uni-view",{staticClass:A._$g(9,"sc"),attrs:{_i:9}},[t("v-uni-button",{staticClass:A._$g(10,"sc"),attrs:{type:"primary",_i:10},on:{click:function(e){return A.$handleViewEvent(e)}}},[A._v("\u5f00 \u59cb \u8ba4 \u8bc1")])],1)],1)],1)},c=[];t.d(e,"b",(function(){return i})),t.d(e,"c",(function(){return c})),t.d(e,"a",(function(){return n}))},a261:function(A,e,t){"use strict";t.r(e);var n=t("7374"),i=t("fa3e");for(var c in i)"default"!==c&&function(A){t.d(e,A,(function(){return i[A]}))}(c);t("11e0");var o,a=t("f0c5"),r=Object(a["a"])(i["default"],n["b"],n["c"],!1,null,"55a66033",null,!1,n["a"],o);e["default"]=r.exports},a39c:function(A,e,t){var n=t("7259");"string"===typeof n&&(n=[[A.i,n,""]]),n.locals&&(A.exports=n.locals);var i=t("7f7e").default;i("33ac2de4",n,!0,{sourceMap:!1,shadowMode:!1})},a3a7:function(A,e,t){"use strict";t.r(e);var n=t("80c8"),i=t.n(n);for(var c in n)"default"!==c&&function(A){t.d(e,A,(function(){return n[A]}))}(c);e["default"]=i.a},a477:function(A,e,t){var n=t("24fb");e=n(!1),e.push([A.i,'.uni-list-item[data-v-17058646]{font-size:32rpx;position:relative;-webkit-box-orient:vertical;-webkit-box-direction:normal;-webkit-flex-direction:column;flex-direction:column;-webkit-box-pack:justify;-webkit-justify-content:space-between;justify-content:space-between;padding-left:30rpx;background-color:#fff}.uni-list-item--disabled[data-v-17058646]{opacity:.3}.uni-list-item--hover[data-v-17058646]{background-color:#f1f1f1}.uni-list-item__container[data-v-17058646]{position:relative;display:-webkit-box;display:-webkit-flex;display:flex;-webkit-box-orient:horizontal;-webkit-box-direction:normal;-webkit-flex-direction:row;flex-direction:row;padding:24rpx 30rpx;padding-left:0;-webkit-box-flex:1;-webkit-flex:1;flex:1;position:relative;-webkit-box-pack:justify;-webkit-justify-content:space-between;justify-content:space-between;-webkit-box-align:center;-webkit-align-items:center;align-items:center}.uni-list--border[data-v-17058646]{position:relative;border-top-color:#c8c7cc;border-top-style:solid;border-top-width:.5px}.uni-list--border[data-v-17058646]:after{position:absolute;top:0;right:0;left:0;height:1px;content:"";-webkit-transform:scaleY(.5);transform:scaleY(.5);background-color:#c8c7cc}.uni-list-item--first[data-v-17058646]:after{height:0}.uni-list-item--first[data-v-17058646]{border-top-width:0}.uni-list-item__content[data-v-17058646]{display:-webkit-box;display:-webkit-flex;display:flex;-webkit-box-flex:1;-webkit-flex:1;flex:1;overflow:hidden;-webkit-box-orient:vertical;-webkit-box-direction:normal;-webkit-flex-direction:column;flex-direction:column;color:#3b4144}.uni-list-item__content-title[data-v-17058646]{font-size:28rpx;color:#3b4144;overflow:hidden}.uni-list-item__content-note[data-v-17058646]{margin-top:6rpx;color:#999;font-size:24rpx;overflow:hidden}.uni-list-item__extra[data-v-17058646]{display:-webkit-box;display:-webkit-flex;display:flex;-webkit-box-orient:horizontal;-webkit-box-direction:normal;-webkit-flex-direction:row;flex-direction:row;-webkit-box-pack:end;-webkit-justify-content:flex-end;justify-content:flex-end;-webkit-box-align:center;-webkit-align-items:center;align-items:center}.uni-list-item__icon[data-v-17058646]{margin-right:18rpx;-webkit-box-orient:horizontal;-webkit-box-direction:normal;-webkit-flex-direction:row;flex-direction:row;-webkit-box-pack:center;-webkit-justify-content:center;justify-content:center;-webkit-box-align:center;-webkit-align-items:center;align-items:center}.uni-list-item__icon-img[data-v-17058646]{display:block}.uni-list--lg[data-v-17058646]{height:80rpx;width:80rpx}.uni-list--base[data-v-17058646]{height:52rpx;width:52rpx}.uni-list--sm[data-v-17058646]{height:40rpx;width:40rpx}.uni-list-item__extra-text[data-v-17058646]{color:#999;font-size:24rpx}',""]),A.exports=e},a82f:function(A,e,t){"use strict";t.r(e);var n=t("58bc"),i=t("c42f");for(var c in i)"default"!==c&&function(A){t.d(e,A,(function(){return i[A]}))}(c);t("86f6");var o,a=t("f0c5"),r=Object(a["a"])(i["default"],n["b"],n["c"],!1,null,null,null,!1,n["a"],o);e["default"]=r.exports},a96a:function(A,e,t){"use strict";var n,i=function(){var A=this,e=A.$createElement,t=A._self._c||e;return t("v-uni-view",{staticClass:A._$g(0,"sc"),class:A._$g(0,"c"),attrs:{_i:0},on:{click:function(e){return A.$handleViewEvent(e)}}})},c=[];t.d(e,"b",(function(){return i})),t.d(e,"c",(function(){return c})),t.d(e,"a",(function(){return n}))},a9f9:function(A,e,t){"use strict";var n,i=function(){var A=this,e=A.$createElement,t=A._self._c||e;return t("v-uni-view",{staticClass:A._$g(0,"sc"),attrs:{_i:0}},[t("uni-list",{attrs:{_i:1}},[t("uni-list-item",{staticClass:A._$g(2,"sc"),attrs:{_i:2}}),t("uni-list-item",{staticStyle:{"font-size":"14rpx"},attrs:{_i:3}},[t("v-uni-view",{staticClass:A._$g(4,"sc"),attrs:{_i:4}},[t("v-uni-button",{staticStyle:{"background-color":"#0077cc"},attrs:{type:"primary",_i:5},on:{click:function(e){return A.$handleViewEvent(e)}}},[A._v("\u5f00 \u59cb \u8ba4 \u8bc1")])],1)],1)],1),t("v-uni-view",{staticClass:A._$g(6,"sc"),attrs:{_i:6}},[A._$g(7,"i")?t("v-uni-button",{staticClass:A._$g(7,"sc"),attrs:{type:"primary",_i:7},on:{click:function(e){return A.$handleViewEvent(e)}}},[A._v("\u767b\u5f55")]):A._e(),A._$g(8,"i")?t("v-uni-button",{attrs:{type:"default",_i:8},on:{click:function(e){return A.$handleViewEvent(e)}}},[A._v("\u9000\u51fa\u767b\u5f55")]):A._e()],1)],1)},c=[];t.d(e,"b",(function(){return i})),t.d(e,"c",(function(){return c})),t.d(e,"a",(function(){return n}))},aa17:function(A,e,t){"use strict";var n=t("a39c"),i=t.n(n);i.a},aa96:function(A,e,t){"use strict";t.r(e);var n=t("2f63"),i=t.n(n);for(var c in n)"default"!==c&&function(A){t.d(e,A,(function(){return n[A]}))}(c);e["default"]=i.a},ab4a:function(A,e,t){"use strict";t.r(e);var n=t("1529"),i=t("351d");for(var c in i)"default"!==c&&function(A){t.d(e,A,(function(){return i[A]}))}(c);t("aa17");var o,a=t("f0c5"),r=Object(a["a"])(i["default"],n["b"],n["c"],!1,null,"57a0af20",null,!1,n["a"],o);e["default"]=r.exports},ae00:function(A,e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var n=c(t("9fba")),i=c(t("2bc5"));function c(A){return A&&A.__esModule?A:{default:A}}var o={data:function(){return{wxsProps:{}}},components:{uniList:n.default,uniListItem:i.default}};e.default=o},aeaa:function(A,e,t){"use strict";var n,i=function(){var A=this,e=A.$createElement,t=A._self._c||e;return t("v-uni-view",{staticClass:A._$g(0,"sc"),attrs:{_i:0}},[t("v-uni-view",{staticClass:A._$g(1,"sc"),attrs:{_i:1}},[t("v-uni-view",{staticClass:A._$g(2,"sc"),attrs:{_i:2}},[t("v-uni-text",{staticClass:A._$g(3,"sc"),attrs:{_i:3}},[A._v("\u90ae\u7bb1\uff1a")]),t("m-input",{attrs:{_i:4},model:{value:A._$g(4,"v-model"),callback:function(){},expression:"email"}})],1)],1),t("v-uni-view",{staticClass:A._$g(5,"sc"),attrs:{_i:5}},[t("v-uni-button",{staticClass:A._$g(6,"sc"),attrs:{type:"primary",_i:6},on:{click:function(e){return A.$handleViewEvent(e)}}},[A._v("\u63d0\u4ea4")])],1)],1)},c=[];t.d(e,"b",(function(){return i})),t.d(e,"c",(function(){return c})),t.d(e,"a",(function(){return n}))},afd2:function(A,e,t){var n=t("d45c");"string"===typeof n&&(n=[[A.i,n,""]]),n.locals&&(A.exports=n.locals);var i=t("7f7e").default;i("22b14d0f",n,!0,{sourceMap:!1,shadowMode:!1})},b263:function(A,e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var n=i(t("a261"));function i(A){return A&&A.__esModule?A:{default:A}}var c={data:function(){return{wxsProps:{}}},components:{mInput:n.default}};e.default=c},b531:function(A,e,t){var n=t("24fb");e=n(!1),e.push([A.i,".uni-badge[data-v-3fb01ae3]{-webkit-box-pack:center;-webkit-justify-content:center;justify-content:center;-webkit-box-orient:horizontal;-webkit-box-direction:normal;-webkit-flex-direction:row;flex-direction:row;height:20px;line-height:20px;color:#333;border-radius:100px;background-color:#f1f1f1;background-color:initial;text-align:center;font-family:Helvetica Neue,Helvetica,sans-serif;font-size:12px;padding:0 6px}.uni-badge--inverted[data-v-3fb01ae3]{padding:0 5px 0 0;color:#f1f1f1}.uni-badge--default[data-v-3fb01ae3]{color:#333;background-color:#f1f1f1}.uni-badge--default-inverted[data-v-3fb01ae3]{color:#999;background-color:initial}.uni-badge--primary[data-v-3fb01ae3]{color:#fff;background-color:#007aff}.uni-badge--primary-inverted[data-v-3fb01ae3]{color:#007aff;background-color:initial}.uni-badge--success[data-v-3fb01ae3]{color:#fff;background-color:#4cd964}.uni-badge--success-inverted[data-v-3fb01ae3]{color:#4cd964;background-color:initial}.uni-badge--warning[data-v-3fb01ae3]{color:#fff;background-color:#f0ad4e}.uni-badge--warning-inverted[data-v-3fb01ae3]{color:#f0ad4e;background-color:initial}.uni-badge--error[data-v-3fb01ae3]{color:#fff;background-color:#dd524d}.uni-badge--error-inverted[data-v-3fb01ae3]{color:#dd524d;background-color:initial}.uni-badge--small[data-v-3fb01ae3]{-webkit-transform:scale(.8);transform:scale(.8);-webkit-transform-origin:center center;transform-origin:center center}",""]),A.exports=e},b725:function(A,e,t){"use strict";var n,i=function(){var A=this,e=A.$createElement,t=A._self._c||e;return t("v-uni-view",{staticClass:A._$g(0,"sc"),style:A._$g(0,"s"),attrs:{_i:0}},[A._t("default",null,{_i:1})],2)},c=[];t.d(e,"b",(function(){return i})),t.d(e,"c",(function(){return c})),t.d(e,"a",(function(){return n}))},bb03:function(A,e,t){var n=t("f91f");"string"===typeof n&&(n=[[A.i,n,""]]),n.locals&&(A.exports=n.locals);var i=t("7f7e").default;i("7dbf136c",n,!0,{sourceMap:!1,shadowMode:!1})},bc53:function(A,e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var n=o(t("9fba")),i=o(t("2bc5")),c=o(t("8f66"));function o(A){return A&&A.__esModule?A:{default:A}}var a={data:function(){return{wxsProps:{}}},components:{uniList:n.default,uniListItem:i.default,components:c.default}};e.default=a},c077:function(A,e,t){var n=t("a477");"string"===typeof n&&(n=[[A.i,n,""]]),n.locals&&(A.exports=n.locals);var i=t("7f7e").default;i("05c212cf",n,!0,{sourceMap:!1,shadowMode:!1})},c1fa:function(A,e,t){"use strict";t.r(e);var n=t("8a4e"),i=t("c608");for(var c in i)"default"!==c&&function(A){t.d(e,A,(function(){return i[A]}))}(c);t("142d");var o,a=t("f0c5"),r=Object(a["a"])(i["default"],n["b"],n["c"],!1,null,"3fb01ae3",null,!1,n["a"],o);e["default"]=r.exports},c42f:function(A,e,t){"use strict";t.r(e);var n=t("fdbd"),i=t.n(n);for(var c in n)"default"!==c&&function(A){t.d(e,A,(function(){return n[A]}))}(c);e["default"]=i.a},c4e5:function(A,e,t){var n=t("24fb");e=n(!1),e.push([A.i,".t-tr[data-v-08ae19da]{width:100%;display:-webkit-box;display:-webkit-flex;display:flex}.t-tr t-th[data-v-08ae19da],\n.t-tr t-td[data-v-08ae19da]{display:-webkit-box;display:-webkit-flex;display:flex;-webkit-box-flex:1;-webkit-flex:1;flex:1}.t-tr .t-check-box[data-v-08ae19da]{-webkit-flex-shrink:0;flex-shrink:0;display:-webkit-box;display:-webkit-flex;display:flex;-webkit-box-pack:center;-webkit-justify-content:center;justify-content:center;-webkit-box-align:center;-webkit-align-items:center;align-items:center;width:80upx;color:#3b4246;border-left:1px #d0dee5 solid;border-top:1px #d0dee5 solid}.t-tr .t-check-box uni-checkbox[data-v-08ae19da]{-webkit-transform:scale(.8);transform:scale(.8)}",""]),A.exports=e},c608:function(A,e,t){"use strict";t.r(e);var n=t("117a"),i=t.n(n);for(var c in n)"default"!==c&&function(A){t.d(e,A,(function(){return n[A]}))}(c);e["default"]=i.a},c6c7:function(A,e,t){"use strict";t.r(e);var n=t("d90f"),i=t.n(n);for(var c in n)"default"!==c&&function(A){t.d(e,A,(function(){return n[A]}))}(c);e["default"]=i.a},cbf5:function(A,e,t){"use strict";t.r(e);var n=t("aeaa"),i=t("70f7");for(var c in i)"default"!==c&&function(A){t.d(e,A,(function(){return i[A]}))}(c);var o,a=t("f0c5"),r=Object(a["a"])(i["default"],n["b"],n["c"],!1,null,null,null,!1,n["a"],o);e["default"]=r.exports},cfe3:function(A,e,t){"use strict";var n,i=function(){var A=this,e=A.$createElement,t=A._self._c||e;return t("v-uni-view",{staticClass:A._$g(0,"sc"),attrs:{_i:0}},[A._$g(1,"i")?t("v-uni-view",{staticClass:A._$g(1,"sc"),attrs:{_i:1}}):A._e(),A._t("default",null,{_i:2}),A._$g(3,"i")?t("v-uni-view",{staticClass:A._$g(3,"sc"),attrs:{_i:3}}):A._e()],2)},c=[];t.d(e,"b",(function(){return i})),t.d(e,"c",(function(){return c})),t.d(e,"a",(function(){return n}))},cfea:function(A,e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var n={props:["fontSize","color","align"],data:function(){return{wxsProps:{}}},components:{}};e.default=n},d12e:function(A,e,t){"use strict";var n,i=function(){var A=this,e=A.$createElement,t=A._self._c||e;return t("v-uni-view",{staticClass:A._$g(0,"sc"),attrs:{_i:0}},[A._$g(1,"i")?t("v-uni-view",{staticClass:A._$g(1,"sc"),style:A._$g(1,"s"),attrs:{_i:1}},[t("v-uni-checkbox-group",{attrs:{_i:2},on:{change:function(e){return A.$handleViewEvent(e)}}},[t("v-uni-checkbox",{attrs:{value:A._$g(3,"a-value"),checked:A._$g(3,"a-checked"),_i:3}})],1)],1):A._e(),A._t("default",null,{_i:4})],2)},c=[];t.d(e,"b",(function(){return i})),t.d(e,"c",(function(){return c})),t.d(e,"a",(function(){return n}))},d339:function(A,e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var n=i(t("a261"));function i(A){return A&&A.__esModule?A:{default:A}}var c={data:function(){return{wxsProps:{}}},components:{mInput:n.default}};e.default=c},d45c:function(A,e,t){var n=t("24fb");e=n(!1),e.push([A.i,'@font-face{font-family:uniicons;font-weight:400;font-style:normal;src:url(https://img-cdn-qiniu.dcloud.net.cn/fonts/uni.ttf?t=1536565627510) format("truetype")}.m-icon[data-v-a4c0901e]{font-family:uniicons;font-size:24px;font-weight:400;font-style:normal;line-height:1;display:inline-block;text-decoration:none;-webkit-font-smoothing:antialiased}.m-icon.uni-active[data-v-a4c0901e]{color:#007aff}.m-icon-contact[data-v-a4c0901e]:before{content:"\\e100"}.m-icon-person[data-v-a4c0901e]:before{content:"\\e101"}.m-icon-personadd[data-v-a4c0901e]:before{content:"\\e102"}.m-icon-contact-filled[data-v-a4c0901e]:before{content:"\\e130"}.m-icon-person-filled[data-v-a4c0901e]:before{content:"\\e131"}.m-icon-personadd-filled[data-v-a4c0901e]:before{content:"\\e132"}.m-icon-phone[data-v-a4c0901e]:before{content:"\\e200"}.m-icon-email[data-v-a4c0901e]:before{content:"\\e201"}.m-icon-chatbubble[data-v-a4c0901e]:before{content:"\\e202"}.m-icon-chatboxes[data-v-a4c0901e]:before{content:"\\e203"}.m-icon-phone-filled[data-v-a4c0901e]:before{content:"\\e230"}.m-icon-email-filled[data-v-a4c0901e]:before{content:"\\e231"}.m-icon-chatbubble-filled[data-v-a4c0901e]:before{content:"\\e232"}.m-icon-chatboxes-filled[data-v-a4c0901e]:before{content:"\\e233"}.m-icon-weibo[data-v-a4c0901e]:before{content:"\\e260"}.m-icon-weixin[data-v-a4c0901e]:before{content:"\\e261"}.m-icon-pengyouquan[data-v-a4c0901e]:before{content:"\\e262"}.m-icon-chat[data-v-a4c0901e]:before{content:"\\e263"}.m-icon-qq[data-v-a4c0901e]:before{content:"\\e264"}.m-icon-videocam[data-v-a4c0901e]:before{content:"\\e300"}.m-icon-camera[data-v-a4c0901e]:before{content:"\\e301"}.m-icon-mic[data-v-a4c0901e]:before{content:"\\e302"}.m-icon-location[data-v-a4c0901e]:before{content:"\\e303"}.m-icon-mic-filled[data-v-a4c0901e]:before,\r\n.m-icon-speech[data-v-a4c0901e]:before{content:"\\e332"}.m-icon-location-filled[data-v-a4c0901e]:before{content:"\\e333"}.m-icon-micoff[data-v-a4c0901e]:before{content:"\\e360"}.m-icon-image[data-v-a4c0901e]:before{content:"\\e363"}.m-icon-map[data-v-a4c0901e]:before{content:"\\e364"}.m-icon-compose[data-v-a4c0901e]:before{content:"\\e400"}.m-icon-trash[data-v-a4c0901e]:before{content:"\\e401"}.m-icon-upload[data-v-a4c0901e]:before{content:"\\e402"}.m-icon-download[data-v-a4c0901e]:before{content:"\\e403"}.m-icon-close[data-v-a4c0901e]:before{content:"\\e404"}.m-icon-redo[data-v-a4c0901e]:before{content:"\\e405"}.m-icon-undo[data-v-a4c0901e]:before{content:"\\e406"}.m-icon-refresh[data-v-a4c0901e]:before{content:"\\e407"}.m-icon-star[data-v-a4c0901e]:before{content:"\\e408"}.m-icon-plus[data-v-a4c0901e]:before{content:"\\e409"}.m-icon-minus[data-v-a4c0901e]:before{content:"\\e410"}.m-icon-circle[data-v-a4c0901e]:before,\r\n.m-icon-checkbox[data-v-a4c0901e]:before{content:"\\e411"}.m-icon-close-filled[data-v-a4c0901e]:before,\r\n.m-icon-clear[data-v-a4c0901e]:before{content:"\\e434"}.m-icon-refresh-filled[data-v-a4c0901e]:before{content:"\\e437"}.m-icon-star-filled[data-v-a4c0901e]:before{content:"\\e438"}.m-icon-plus-filled[data-v-a4c0901e]:before{content:"\\e439"}.m-icon-minus-filled[data-v-a4c0901e]:before{content:"\\e440"}.m-icon-circle-filled[data-v-a4c0901e]:before{content:"\\e441"}.m-icon-checkbox-filled[data-v-a4c0901e]:before{content:"\\e442"}.m-icon-closeempty[data-v-a4c0901e]:before{content:"\\e460"}.m-icon-refreshempty[data-v-a4c0901e]:before{content:"\\e461"}.m-icon-reload[data-v-a4c0901e]:before{content:"\\e462"}.m-icon-starhalf[data-v-a4c0901e]:before{content:"\\e463"}.m-icon-spinner[data-v-a4c0901e]:before{content:"\\e464"}.m-icon-spinner-cycle[data-v-a4c0901e]:before{content:"\\e465"}.m-icon-search[data-v-a4c0901e]:before{content:"\\e466"}.m-icon-plusempty[data-v-a4c0901e]:before{content:"\\e468"}.m-icon-forward[data-v-a4c0901e]:before{content:"\\e470"}.m-icon-back[data-v-a4c0901e]:before,\r\n.m-icon-left-nav[data-v-a4c0901e]:before{content:"\\e471"}.m-icon-checkmarkempty[data-v-a4c0901e]:before{content:"\\e472"}.m-icon-home[data-v-a4c0901e]:before{content:"\\e500"}.m-icon-navigate[data-v-a4c0901e]:before{content:"\\e501"}.m-icon-gear[data-v-a4c0901e]:before{content:"\\e502"}.m-icon-paperplane[data-v-a4c0901e]:before{content:"\\e503"}.m-icon-info[data-v-a4c0901e]:before{content:"\\e504"}.m-icon-help[data-v-a4c0901e]:before{content:"\\e505"}.m-icon-locked[data-v-a4c0901e]:before{content:"\\e506"}.m-icon-more[data-v-a4c0901e]:before{content:"\\e507"}.m-icon-flag[data-v-a4c0901e]:before{content:"\\e508"}.m-icon-home-filled[data-v-a4c0901e]:before{content:"\\e530"}.m-icon-gear-filled[data-v-a4c0901e]:before{content:"\\e532"}.m-icon-info-filled[data-v-a4c0901e]:before{content:"\\e534"}.m-icon-help-filled[data-v-a4c0901e]:before{content:"\\e535"}.m-icon-more-filled[data-v-a4c0901e]:before{content:"\\e537"}.m-icon-settings[data-v-a4c0901e]:before{content:"\\e560"}.m-icon-list[data-v-a4c0901e]:before{content:"\\e562"}.m-icon-bars[data-v-a4c0901e]:before{content:"\\e563"}.m-icon-loop[data-v-a4c0901e]:before{content:"\\e565"}.m-icon-paperclip[data-v-a4c0901e]:before{content:"\\e567"}.m-icon-eye[data-v-a4c0901e]:before{content:"\\e568"}.m-icon-arrowup[data-v-a4c0901e]:before{content:"\\e580"}.m-icon-arrowdown[data-v-a4c0901e]:before{content:"\\e581"}.m-icon-arrowleft[data-v-a4c0901e]:before{content:"\\e582"}.m-icon-arrowright[data-v-a4c0901e]:before{content:"\\e583"}.m-icon-arrowthinup[data-v-a4c0901e]:before{content:"\\e584"}.m-icon-arrowthindown[data-v-a4c0901e]:before{content:"\\e585"}.m-icon-arrowthinleft[data-v-a4c0901e]:before{content:"\\e586"}.m-icon-arrowthinright[data-v-a4c0901e]:before{content:"\\e587"}.m-icon-pulldown[data-v-a4c0901e]:before{content:"\\e588"}.m-icon-scan[data-v-a4c0901e]:before{content:"\\e612"}',""]),A.exports=e},d71f:function(A,e,t){"use strict";t.r(e);var n=t("a194"),i=t("aa96");for(var c in i)"default"!==c&&function(A){t.d(e,A,(function(){return i[A]}))}(c);var o,a=t("f0c5"),r=Object(a["a"])(i["default"],n["b"],n["c"],!1,null,null,null,!1,n["a"],o);e["default"]=r.exports},d90f:function(A,e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var n={name:"cmd-progress",props:["type","percent","successPercent","showInfo","status","strokeWidth","strokeColor","strokeShape","width","gapDegree","gapPosition"],data:function(){return{wxsProps:{}}},components:{}};e.default=n},dd93:function(A,e,t){var n=t("24fb");e=n(!1),e.push([A.i,'\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n/* \u5934\u6761\u5c0f\u7a0b\u5e8f\u9700\u8981\u628a iconfont \u6837\u5f0f\u653e\u5230\u7ec4\u4ef6\u5916 */@font-face{font-family:uniicons;font-weight:400;font-style:normal;src:url(https://img-cdn-qiniu.dcloud.net.cn/fonts/uni.ttf?t=1536565627510) format("truetype")}.m-icon{font-family:uniicons;font-size:24px;font-weight:400;font-style:normal;line-height:1;display:inline-block;text-decoration:none;-webkit-font-smoothing:antialiased}.m-icon.uni-active{color:#007aff}.m-icon-contact:before{content:"\\e100"}.m-icon-person:before{content:"\\e101"}.m-icon-personadd:before{content:"\\e102"}.m-icon-contact-filled:before{content:"\\e130"}.m-icon-person-filled:before{content:"\\e131"}.m-icon-personadd-filled:before{content:"\\e132"}.m-icon-phone:before{content:"\\e200"}.m-icon-email:before{content:"\\e201"}.m-icon-chatbubble:before{content:"\\e202"}.m-icon-chatboxes:before{content:"\\e203"}.m-icon-phone-filled:before{content:"\\e230"}.m-icon-email-filled:before{content:"\\e231"}.m-icon-chatbubble-filled:before{content:"\\e232"}.m-icon-chatboxes-filled:before{content:"\\e233"}.m-icon-weibo:before{content:"\\e260"}.m-icon-weixin:before{content:"\\e261"}.m-icon-pengyouquan:before{content:"\\e262"}.m-icon-chat:before{content:"\\e263"}.m-icon-qq:before{content:"\\e264"}.m-icon-videocam:before{content:"\\e300"}.m-icon-camera:before{content:"\\e301"}.m-icon-mic:before{content:"\\e302"}.m-icon-location:before{content:"\\e303"}.m-icon-mic-filled:before,\r\n.m-icon-speech:before{content:"\\e332"}.m-icon-location-filled:before{content:"\\e333"}.m-icon-micoff:before{content:"\\e360"}.m-icon-image:before{content:"\\e363"}.m-icon-map:before{content:"\\e364"}.m-icon-compose:before{content:"\\e400"}.m-icon-trash:before{content:"\\e401"}.m-icon-upload:before{content:"\\e402"}.m-icon-download:before{content:"\\e403"}.m-icon-close:before{content:"\\e404"}.m-icon-redo:before{content:"\\e405"}.m-icon-undo:before{content:"\\e406"}.m-icon-refresh:before{content:"\\e407"}.m-icon-star:before{content:"\\e408"}.m-icon-plus:before{content:"\\e409"}.m-icon-minus:before{content:"\\e410"}.m-icon-circle:before,\r\n.m-icon-checkbox:before{content:"\\e411"}.m-icon-close-filled:before,\r\n.m-icon-clear:before{content:"\\e434"}.m-icon-refresh-filled:before{content:"\\e437"}.m-icon-star-filled:before{content:"\\e438"}.m-icon-plus-filled:before{content:"\\e439"}.m-icon-minus-filled:before{content:"\\e440"}.m-icon-circle-filled:before{content:"\\e441"}.m-icon-checkbox-filled:before{content:"\\e442"}.m-icon-closeempty:before{content:"\\e460"}.m-icon-refreshempty:before{content:"\\e461"}.m-icon-reload:before{content:"\\e462"}.m-icon-starhalf:before{content:"\\e463"}.m-icon-spinner:before{content:"\\e464"}.m-icon-spinner-cycle:before{content:"\\e465"}.m-icon-search:before{content:"\\e466"}.m-icon-plusempty:before{content:"\\e468"}.m-icon-forward:before{content:"\\e470"}.m-icon-back:before,\r\n.m-icon-left-nav:before{content:"\\e471"}.m-icon-checkmarkempty:before{content:"\\e472"}.m-icon-home:before{content:"\\e500"}.m-icon-navigate:before{content:"\\e501"}.m-icon-gear:before{content:"\\e502"}.m-icon-paperplane:before{content:"\\e503"}.m-icon-info:before{content:"\\e504"}.m-icon-help:before{content:"\\e505"}.m-icon-locked:before{content:"\\e506"}.m-icon-more:before{content:"\\e507"}.m-icon-flag:before{content:"\\e508"}.m-icon-home-filled:before{content:"\\e530"}.m-icon-gear-filled:before{content:"\\e532"}.m-icon-info-filled:before{content:"\\e534"}.m-icon-help-filled:before{content:"\\e535"}.m-icon-more-filled:before{content:"\\e537"}.m-icon-settings:before{content:"\\e560"}.m-icon-list:before{content:"\\e562"}.m-icon-bars:before{content:"\\e563"}.m-icon-loop:before{content:"\\e565"}.m-icon-paperclip:before{content:"\\e567"}.m-icon-eye:before{content:"\\e568"}.m-icon-arrowup:before{content:"\\e580"}.m-icon-arrowdown:before{content:"\\e581"}.m-icon-arrowleft:before{content:"\\e582"}.m-icon-arrowright:before{content:"\\e583"}.m-icon-arrowthinup:before{content:"\\e584"}.m-icon-arrowthindown:before{content:"\\e585"}.m-icon-arrowthinleft:before{content:"\\e586"}.m-icon-arrowthinright:before{content:"\\e587"}.m-icon-pulldown:before{content:"\\e588"}.m-icon-scan:before{content:"\\e612"}\r\n/*\u6bcf\u4e2a\u9875\u9762\u516c\u5171css */body{min-height:100%;display:-webkit-box;display:-webkit-flex;display:flex;font-size:16px}\r\n\r\n\r\n\r\n\r\n\r\n/* \u539f\u751f\u7ec4\u4ef6\u6a21\u5f0f\u4e0b\u9700\u8981\u6ce8\u610f\u7ec4\u4ef6\u5916\u90e8\u6837\u5f0f */m-input{width:100%;\r\n\t/* min-height: 100%; */display:-webkit-box;display:-webkit-flex;display:flex;-webkit-box-flex:1;-webkit-flex:1;flex:1}.content{display:-webkit-box;display:-webkit-flex;display:flex;-webkit-box-flex:1;-webkit-flex:1;flex:1;-webkit-box-orient:vertical;-webkit-box-direction:normal;-webkit-flex-direction:column;flex-direction:column;background-color:#efeff4;padding:10px}.input-group{background-color:#fff;margin-top:20px;position:relative}.input-group::before{position:absolute;right:0;top:0;left:0;height:1px;content:"";-webkit-transform:scaleY(.5);transform:scaleY(.5);background-color:#c8c7cc}.input-group::after{position:absolute;right:0;bottom:0;left:0;height:1px;content:"";-webkit-transform:scaleY(.5);transform:scaleY(.5);background-color:#c8c7cc}.input-row{display:-webkit-box;display:-webkit-flex;display:flex;-webkit-box-orient:horizontal;-webkit-box-direction:normal;-webkit-flex-direction:row;flex-direction:row;position:relative;font-size:18px;line-height:40px}.input-row .title{width:100px;padding-left:15px}.input-row.border::after{position:absolute;right:0;bottom:0;left:8px;height:1px;content:"";-webkit-transform:scaleY(.5);transform:scaleY(.5);background-color:#c8c7cc}.btn-row{margin-top:25px;padding:10px}uni-button.primary{background-color:#0faeff}',""]),A.exports=e},e288:function(A,e,t){"use strict";t.r(e);var n=t("4c39"),i=t("0666");for(var c in i)"default"!==c&&function(A){t.d(e,A,(function(){return i[A]}))}(c);t("f8e5");var o,a=t("f0c5"),r=Object(a["a"])(i["default"],n["b"],n["c"],!1,null,null,null,!1,n["a"],o);e["default"]=r.exports},e370:function(A,e,t){var n=t("3c17");"string"===typeof n&&(n=[[A.i,n,""]]),n.locals&&(A.exports=n.locals);var i=t("7f7e").default;i("1180bca8",n,!0,{sourceMap:!1,shadowMode:!1})},e581:function(A,e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var n={name:"UniList",props:["enableBackToTop","scrollY","border"],data:function(){return{wxsProps:{}}},components:{}};e.default=n},ea78:function(A,e,t){var n=t("24fb");e=n(!1),e.push([A.i,".hello{display:-webkit-box;display:-webkit-flex;display:flex;-webkit-box-flex:1;-webkit-flex:1;flex:1;-webkit-box-orient:vertical;-webkit-box-direction:normal;-webkit-flex-direction:column;flex-direction:column}.title{color:#8f8f94;margin-top:25px}.ul{font-size:15px;color:#8f8f94;margin-top:25px}.ul>uni-view{line-height:25px}",""]),A.exports=e},f0c5:function(A,e,t){"use strict";function n(A,e,t,n,i,c,o,a,r,s){var B,l="function"===typeof A?A.options:A;if(r){l.components||(l.components={});var u=Object.prototype.hasOwnProperty;for(var f in r)u.call(r,f)&&!u.call(l.components,f)&&(l.components[f]=r[f])}if(s&&((s.beforeCreate||(s.beforeCreate=[])).unshift((function(){this[s.__module]=this})),(l.mixins||(l.mixins=[])).push(s)),e&&(l.render=e,l.staticRenderFns=t,l._compiled=!0),n&&(l.functional=!0),c&&(l._scopeId="data-v-"+c),o?(B=function(A){A=A||this.$vnode&&this.$vnode.ssrContext||this.parent&&this.parent.$vnode&&this.parent.$vnode.ssrContext,A||"undefined"===typeof __VUE_SSR_CONTEXT__||(A=__VUE_SSR_CONTEXT__),i&&i.call(this,A),A&&A._registeredComponents&&A._registeredComponents.add(o)},l._ssrRegister=B):i&&(B=a?function(){i.call(this,this.$root.$options.shadowRoot)}:i),B)if(l.functional){l._injectStyles=B;var g=l.render;l.render=function(A,e){return B.call(e),g(A,e)}}else{var E=l.beforeCreate;l.beforeCreate=E?[].concat(E,B):[B]}return{exports:A,options:l}}t.d(e,"a",(function(){return n}))},f375:function(A,e,t){var n=t("68c5");"string"===typeof n&&(n=[[A.i,n,""]]),n.locals&&(A.exports=n.locals);var i=t("7f7e").default;i("1b1686a4",n,!0,{sourceMap:!1,shadowMode:!1})},f491:function(A,e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var n={props:["border","borderColor","isCheck"],data:function(){return{wxsProps:{}}},components:{}};e.default=n},f8e5:function(A,e,t){"use strict";var n=t("f375"),i=t.n(n);i.a},f909:function(A,e,t){"use strict";var n=t("56ee"),i=t.n(n);i.a},f91f:function(A,e,t){var n=t("24fb");e=n(!1),e.push([A.i,".list-shu-style{font-weight:700;border-left:3px solid #333;height:80rpx}.chat-custom-right{-webkit-box-flex:1;-webkit-flex:1;flex:1;\ndisplay:-webkit-box;display:-webkit-flex;display:flex;\n-webkit-box-orient:vertical;-webkit-box-direction:normal;-webkit-flex-direction:column;flex-direction:column;-webkit-box-pack:justify;-webkit-justify-content:space-between;justify-content:space-between;-webkit-box-align:end;-webkit-align-items:flex-end;align-items:flex-end}.chat-custom-text{font-size:12px;color:#999}",""]),A.exports=e},f9fd:function(A,e,t){"use strict";t.r(e);var n=t("7f59"),i=t.n(n);for(var c in n)"default"!==c&&function(A){t.d(e,A,(function(){return n[A]}))}(c);e["default"]=i.a},fa3e:function(A,e,t){"use strict";t.r(e);var n=t("71df"),i=t.n(n);for(var c in n)"default"!==c&&function(A){t.d(e,A,(function(){return n[A]}))}(c);e["default"]=i.a},fdbd:function(A,e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var n=a(t("65e5")),i=a(t("30df")),c=a(t("6015")),o=a(t("0a1f"));function a(A){return A&&A.__esModule?A:{default:A}}var r={data:function(){return{wxsProps:{}}},components:{tTable:n.default,tTh:i.default,tTr:c.default,tTd:o.default}};e.default=r},fe47:function(A,e,t){var n=t("7167");"string"===typeof n&&(n=[[A.i,n,""]]),n.locals&&(A.exports=n.locals);var i=t("7f7e").default;i("ef26b6fa",n,!0,{sourceMap:!1,shadowMode:!1})},feeb:function(A,e,t){"use strict";var n=t("3be8"),i=t.n(n);i.a}});
103,388
103,388
0.78099
3d79220fa2fa50ae4203bbc89500f4e29b7de026
272
js
JavaScript
models/business.js
Tallglass9000/localTest
5f455bfc3b9c0f089203418aa8ed18304a3ca32d
[ "MIT" ]
null
null
null
models/business.js
Tallglass9000/localTest
5f455bfc3b9c0f089203418aa8ed18304a3ca32d
[ "MIT" ]
null
null
null
models/business.js
Tallglass9000/localTest
5f455bfc3b9c0f089203418aa8ed18304a3ca32d
[ "MIT" ]
null
null
null
var mongoose = require('mongoose'); var businessSchema = new mongoose.Schema({ businessname: String, city: String, state: String, category: String, distance: String, coupons: [{ title: String, }] }); module.exports = mongoose.model("Business", businessSchema);
19.428571
60
0.709559
3d792e258b6e59b8ca9a0f27544935787c8f7b0a
1,696
js
JavaScript
src/main/webapp/mock/BillMock.js
alvin198761/erp_laozhang
572efe71b03b91bd82e2d38c45c87fc69ee458c5
[ "MIT" ]
null
null
null
src/main/webapp/mock/BillMock.js
alvin198761/erp_laozhang
572efe71b03b91bd82e2d38c45c87fc69ee458c5
[ "MIT" ]
null
null
null
src/main/webapp/mock/BillMock.js
alvin198761/erp_laozhang
572efe71b03b91bd82e2d38c45c87fc69ee458c5
[ "MIT" ]
1
2018-11-27T01:44:12.000Z
2018-11-27T01:44:12.000Z
/*开票信息模拟数据},作者:唐植超,日期:2018-11-27 14:04:59*/ 'use strict'; var Mock = require('mockjs') var Random = Mock.Random; module.exports = { 'POST /api/bill/queryPage': function (req, res, next) { var data = Mock.mock({ 'content|10': [{ id: "@integer(100,200)",//主键 vendor_id: "@integer(100,200)",//供应商 bank: "@word(5,10)",// 开户行 account: "@word(5,10)",// 账号 taxpayer_no: "@word(5,10)",// 纳税人识别号 remark: "@word(5,10)",// 备注 }], 'number': '@integer(100,200)', 'size': 10, 'totalElements': 500, }); setTimeout(function () { res.json(data); }, 500); }, 'POST /api/bill/update': function (req, res, next) { setTimeout(function () { res.json({}); }, 500); }, 'POST /api/bill/save': function (req, res, next) { setTimeout(function () { res.json({}); }, 500); }, 'POST /api/bill/queryList': function (req, res, next) { var data = Mock.mock({ 'content|10': [{ id: "@integer(100,200)",//主键 vendor_id: "@integer(100,200)",//供应商 bank: "@word(5,10)",// 开户行 account: "@word(5,10)",// 账号 taxpayer_no: "@word(5,10)",// 纳税人识别号 remark: "@word(5,10)",// 备注 }] }); setTimeout(function () { res.json(data.content); }, 500); }, 'POST /api/bill/delete': function (req, res, next) { setTimeout(function () { res.json({}); }, 500); }, }
28.745763
59
0.433373
3d7a05228cd6c0d0233bdedafc275bb116747c86
184
js
JavaScript
src/__test__/lib/test.env.js
puppyPound/puppy-pound
b066bddf1ba632f0097e13519045699b141f9992
[ "MIT" ]
null
null
null
src/__test__/lib/test.env.js
puppyPound/puppy-pound
b066bddf1ba632f0097e13519045699b141f9992
[ "MIT" ]
6
2018-05-16T18:06:13.000Z
2018-06-18T16:56:59.000Z
src/__test__/lib/test.env.js
puppyPound/puppy-pound
b066bddf1ba632f0097e13519045699b141f9992
[ "MIT" ]
null
null
null
process.env.NODE_ENV = 'development'; process.env.PORT = 7000; process.env.MONGODB_URI = 'mongodb://localhost/testing'; process.env.PUPPY_SECRET = 'llsjdlgjsldkgjslkdjgfskdfgjlsdgfj';
36.8
63
0.793478
3d7a124ca9e615cba7db9697d5f117d8f355e694
9,465
js
JavaScript
resources/gulpfile.js
asazernik/immutable-js
5d6d1fd2e0a2c4c035715ec74c0ec079ef9ead73
[ "MIT" ]
null
null
null
resources/gulpfile.js
asazernik/immutable-js
5d6d1fd2e0a2c4c035715ec74c0ec079ef9ead73
[ "MIT" ]
null
null
null
resources/gulpfile.js
asazernik/immutable-js
5d6d1fd2e0a2c4c035715ec74c0ec079ef9ead73
[ "MIT" ]
null
null
null
var browserify = require('browserify'); var browserSync = require('browser-sync'); var buffer = require('vinyl-buffer'); var child_process = require('child_process'); var concat = require('gulp-concat'); var del = require('del'); var filter = require('gulp-filter'); var fs = require('fs'); var gulp = require('gulp'); var gutil = require('gulp-util'); var header = require('gulp-header'); var Immutable = require('../'); var less = require('gulp-less'); var mkdirp = require('mkdirp'); var path = require('path'); var React = require('react/addons'); var reactTools = require('react-tools'); var size = require('gulp-size'); var source = require('vinyl-source-stream'); var sourcemaps = require('gulp-sourcemaps'); var through = require('through2'); var uglify = require('gulp-uglify'); var vm = require('vm'); function requireFresh(path) { delete require.cache[require.resolve(path)]; return require(path); } var SRC_DIR = '../pages/src/'; var BUILD_DIR = '../pages/out/'; gulp.task('clean', () => del([BUILD_DIR], { force: true })); gulp.task('readme', async () => { var genMarkdownDoc = requireFresh('../pages/lib/genMarkdownDoc'); var readmePath = path.join(__dirname, '../README.md'); var fileContents = fs.readFileSync(readmePath, 'utf8'); var writePath = path.join(__dirname, '../pages/generated/readme.json'); var contents = JSON.stringify(genMarkdownDoc(fileContents)); mkdirp.sync(path.dirname(writePath)); fs.writeFileSync(writePath, contents); }); gulp.task('typedefs', async () => { var genTypeDefData = requireFresh('../pages/lib/genTypeDefData'); var typeDefPath = path.join(__dirname, '../type-definitions/Immutable.d.ts'); var fileContents = fs.readFileSync(typeDefPath, 'utf8'); var fileSource = fileContents.replace( "module 'immutable'", 'module Immutable' ); var writePath = path.join(__dirname, '../pages/generated/immutable.d.json'); var contents = JSON.stringify(genTypeDefData(typeDefPath, fileSource)); mkdirp.sync(path.dirname(writePath)); fs.writeFileSync(writePath, contents); }); gulp.task('js', gulpJS('')); gulp.task('js-docs', gulpJS('docs/')); function gulpJS(subDir) { var reactGlobalModulePath = path.relative( path.resolve(SRC_DIR + subDir), path.resolve('./react-global.js') ); var immutableGlobalModulePath = path.relative( path.resolve(SRC_DIR + subDir), path.resolve('./immutable-global.js') ); return function () { return ( browserify({ debug: true, basedir: SRC_DIR + subDir, }) .add('./src/index.js') .require('./src/index.js') .require(reactGlobalModulePath, { expose: 'react' }) .require(immutableGlobalModulePath, { expose: 'immutable' }) // Helpful when developing with no wifi // .require('react', { expose: 'react' }) // .require('immutable', { expose: 'immutable' }) .transform(reactTransformify) .bundle() .on('error', handleError) .pipe(source('bundle.js')) .pipe(buffer()) .pipe( sourcemaps.init({ loadMaps: true, }) ) // .pipe(uglify()) .pipe(sourcemaps.write('./maps')) .pipe(gulp.dest(BUILD_DIR + subDir)) .pipe(filter('**/*.js')) .pipe(size({ showFiles: true })) .on('error', handleError) ); }; } gulp.task('pre-render', gulpPreRender('')); gulp.task('pre-render-docs', gulpPreRender('docs/')); function gulpPreRender(subDir) { return function () { return gulp .src(SRC_DIR + subDir + 'index.html') .pipe(preRender(subDir)) .pipe(size({ showFiles: true })) .pipe(gulp.dest(BUILD_DIR + subDir)) .on('error', handleError); }; } gulp.task('less', gulpLess('')); gulp.task('less-docs', gulpLess('docs/')); function gulpLess(subDir) { return function () { return gulp .src(SRC_DIR + subDir + 'src/*.less') .pipe(sourcemaps.init()) .pipe( less({ compress: true, }) ) .on('error', handleError) .pipe(concat('bundle.css')) .pipe(sourcemaps.write('./maps')) .pipe(gulp.dest(BUILD_DIR + subDir)) .pipe(filter('**/*.css')) .pipe(size({ showFiles: true })) .pipe(browserSync.reload({ stream: true })) .on('error', handleError); }; } gulp.task('statics', gulpStatics('')); gulp.task('statics-docs', gulpStatics('docs/')); function gulpStatics(subDir) { return function () { return gulp .src(SRC_DIR + subDir + 'static/**/*') .pipe(gulp.dest(BUILD_DIR + subDir + 'static')) .on('error', handleError) .pipe(browserSync.reload({ stream: true })) .on('error', handleError); }; } gulp.task('immutable-copy', () => gulp .src(SRC_DIR + '../../dist/immutable.js') .pipe(gulp.dest(BUILD_DIR)) .on('error', handleError) .pipe(browserSync.reload({ stream: true })) .on('error', handleError) ); gulp.task( 'build', gulp.series( 'typedefs', 'readme', gulp.parallel( 'js', 'js-docs', 'less', 'less-docs', 'immutable-copy', 'statics', 'statics-docs' ), gulp.parallel('pre-render', 'pre-render-docs') ) ); gulp.task('default', gulp.series('clean', 'build')); // watch files for changes and reload gulp.task( 'dev', gulp.series('default', async () => { browserSync({ port: 8040, server: { baseDir: BUILD_DIR, }, }); gulp.watch('../README.md', gulp.series('build')); gulp.watch('../pages/lib/**/*.js', gulp.series('build')); gulp.watch('../pages/src/**/*.less', gulp.series('less', 'less-docs')); gulp.watch('../pages/src/src/**/*.js', gulp.series('rebuild-js')); gulp.watch('../pages/src/docs/src/**/*.js', gulp.series('rebuild-js-docs')); gulp.watch( '../pages/src/**/*.html', gulp.series('pre-render', 'pre-render-docs') ); gulp.watch( '../pages/src/static/**/*', gulp.series('statics', 'statics-docs') ); gulp.watch( '../type-definitions/*', gulp.series('typedefs', 'rebuild-js-docs') ); }) ); gulp.task( 'rebuild-js', gulp.series('js', 'pre-render', async () => browserSync.reload()) ); gulp.task( 'rebuild-js-docs', gulp.series('js-docs', 'pre-render-docs', async () => browserSync.reload()) ); function handleError(error) { gutil.log(error.message); } function preRender(subDir) { return through.obj(function (file, enc, cb) { var src = file.contents.toString(enc); var components = []; src = src.replace( /<!--\s*React\(\s*(.*)\s*\)\s*-->/g, function (_, relComponent) { var id = 'r' + components.length; var component = path.resolve(SRC_DIR + subDir, relComponent); components.push(component); try { return ( '<div id="' + id + '">' + vm.runInNewContext( fs.readFileSync(BUILD_DIR + subDir + 'bundle.js') + // ugly '\nrequire("react").renderToString(' + 'require("react").createElement(require(component)))', { global: { React: React, Immutable: Immutable, }, window: {}, component: component, console: console, } ) + '</div>' ); } catch (error) { return '<div id="' + id + '">' + error.message + '</div>'; } } ); if (components.length) { src = src.replace( /<!--\s*ReactRender\(\)\s*-->/g, '<script>' + components.map(function (component, index) { return ( 'var React = require("react");' + 'React.render(' + 'React.createElement(require("' + component + '")),' + 'document.getElementById("r' + index + '")' + ');' ); }) + '</script>' ); } file.contents = new Buffer(src, enc); this.push(file); cb(); }); } function reactTransform() { var parseError; return through.obj( function (file, enc, cb) { if (path.extname(file.path) !== '.js') { this.push(file); return cb(); } try { file.contents = new Buffer( reactTools.transform(file.contents.toString(enc), { harmony: true }), enc ); this.push(file); cb(); } catch (error) { parseError = new gutil.PluginError('transform', { message: file.relative + ' : ' + error.message, showStack: false, }); cb(); } }, function (done) { parseError && this.emit('error', parseError); done(); } ); } function reactTransformify(filePath) { if (path.extname(filePath) !== '.js') { return through(); } var code = ''; var parseError; return through.obj( function (file, enc, cb) { code += file; cb(); }, function (done) { try { this.push(reactTools.transform(code, { harmony: true })); } catch (error) { parseError = new gutil.PluginError('transform', { message: error.message, showStack: false, }); } parseError && this.emit('error', parseError); done(); } ); }
26.587079
80
0.556366
3d7a2bf180216236d75ea8e546fdca00899ebeb4
554
js
JavaScript
src/dream-team.js
VonKrolock/basic-js
177f06137dc808fd93343a3b0e6adb9f433dd7e0
[ "MIT" ]
null
null
null
src/dream-team.js
VonKrolock/basic-js
177f06137dc808fd93343a3b0e6adb9f433dd7e0
[ "MIT" ]
null
null
null
src/dream-team.js
VonKrolock/basic-js
177f06137dc808fd93343a3b0e6adb9f433dd7e0
[ "MIT" ]
null
null
null
module.exports = function createDreamTeam(members) { if(typeof(members) !== 'object' || !Array.isArray(members)) { return false; } return members.filter(team => typeof(team) === 'string') .map((team) => {team = team.toUpperCase() for(let k = 0; k < team.length; k++) { if(team[k] >= 'A' && team[k] <= 'Z') { return team[k]; } } }) .sort() .join(''); }
26.380952
63
0.382671
3d7b8f5d12c3c9c2dd56603a56cf818e48086229
894
js
JavaScript
lib/config.js
aaharu/nuxt-optimized-images
d455cba5a930cfba85f1f42c7c70868f6372d6d6
[ "MIT" ]
402
2019-02-28T23:20:46.000Z
2020-04-10T17:20:14.000Z
lib/config.js
aaharu/nuxt-optimized-images
d455cba5a930cfba85f1f42c7c70868f6372d6d6
[ "MIT" ]
97
2020-07-07T11:21:06.000Z
2022-03-26T20:41:51.000Z
lib/config.js
aaharu/nuxt-optimized-images
d455cba5a930cfba85f1f42c7c70868f6372d6d6
[ "MIT" ]
25
2020-07-17T07:44:23.000Z
2022-03-05T12:28:28.000Z
/** * Enriches the @aceforth/nuxt-optimized-images configuration object with default config values for * next-optimized-iamges and returns it * * @param {object} moduleConfig - @aceforth/nuxt-optimized-images configuration object * @returns {object} enriched config */ const defaultConfig = { optimizeImages: true, optimizeImagesInDev: false, handleImages: ['jpeg', 'png', 'svg', 'webp', 'gif'], imagesName: ({ isDev }) => isDev ? '[path][name][hash:optimized].[ext]' : 'img/[contenthash:7].[ext]', responsiveImagesName: ({ isDev }) => isDev ? '[path][name]--[width][hash:optimized].[ext]' : 'img/[contenthash:7]-[width].[ext]', inlineImageLimit: 1000, defaultImageLoader: 'img-loader', mozjpeg: {}, optipng: {}, pngquant: {}, gifsicle: { interlaced: true, optimizationLevel: 3 }, svgo: {}, webp: {}, sqip: {} } module.exports = { defaultConfig }
28.83871
131
0.659955
3d7ba35592e5dc471592a5deb8d23a678ea4f133
7,338
js
JavaScript
src/RichTextInputArea/EditorUtilities.js
alonbltest/wix-style-react
7fed4cd08271aac2a3e8fb4c603fba2bceddcfce
[ "MIT" ]
null
null
null
src/RichTextInputArea/EditorUtilities.js
alonbltest/wix-style-react
7fed4cd08271aac2a3e8fb4c603fba2bceddcfce
[ "MIT" ]
null
null
null
src/RichTextInputArea/EditorUtilities.js
alonbltest/wix-style-react
7fed4cd08271aac2a3e8fb4c603fba2bceddcfce
[ "MIT" ]
null
null
null
import { EditorState, SelectionState, Modifier, RichUtils } from 'draft-js'; import { stateToHTML } from 'draft-js-export-html'; import { blockTypes, entityTypes } from './RichTextInputAreaTypes'; /** Returns whether the specified style is applied on a block */ const hasStyle = (editorState, style) => { const currentStyle = editorState.getCurrentInlineStyle(); return currentStyle.has(style); }; /** Returns whether a block with the specified type exists */ const hasBlockType = (editorState, blockType) => { const selection = editorState.getSelection(); const currentBlockType = editorState .getCurrentContent() .getBlockForKey(selection.getStartKey()) .getType(); return currentBlockType === blockType; }; /** Returns whether the specified entity is applied on a block */ const hasEntity = (editorState, entity) => { const selection = editorState.getSelection(); const contentState = editorState.getCurrentContent(); const currentKey = contentState .getBlockForKey(selection.getStartKey()) .getEntityAt(selection.getStartOffset()); if (currentKey) { const currentEntity = contentState.getEntity(currentKey); return currentEntity.type === entity; } return false; }; /** Returns whether the block of the selected text is linked to an entity */ const hasRemovableEntityInSelection = editorState => { if (_hasSelectedText(editorState)) { const { contentBlock, startOffset } = _getSelectedBlock(editorState); // Finds the entity that's related to the selected text const entity = contentBlock.getEntityAt(startOffset); if (entity) { return true; } } return false; }; /** Returns an EditorState with the rendered selection. * Mainly useful in order to maintain the selection after creating new state */ const keepCurrentSelection = editorState => EditorState.forceSelection(editorState, editorState.getSelection()); /** Returns an EditorState so that the specified style is toggled on the selection */ const toggleStyle = (editorState, toggledStyle) => { return RichUtils.toggleInlineStyle( keepCurrentSelection(editorState), toggledStyle, ); }; /** Returns an EditorState so that the specified block type is toggled on the selection */ const toggleBlockType = (editorState, toggledBlockType) => { return RichUtils.toggleBlockType( keepCurrentSelection(editorState), toggledBlockType, ); }; const toggleLink = (editorState, linkData) => { if (hasRemovableEntityInSelection(editorState)) { const { contentBlock, startOffset } = _getSelectedBlock(editorState); const entity = contentBlock.getEntityAt(startOffset); return _removeEntityFromBlock(editorState, contentBlock, entity); } return _attachLinkEntityToText(editorState, linkData); }; const getSelectedText = editorState => { const { contentBlock, startOffset, endOffset } = _getSelectedBlock( editorState, ); return contentBlock.getText().slice(startOffset, endOffset); }; const findLinkEntities = (contentBlock, callback, contentState) => { contentBlock.findEntityRanges(character => { const entityKey = character.getEntity(); return ( entityKey !== null && contentState.getEntity(entityKey).getType() === entityTypes.link ); }, callback); }; const convertToHtml = editorState => { const markupConfig = { inlineStyles: { ITALIC: { element: 'em', }, }, entityStyleFn: entity => { const entityType = entity.get('type').toLowerCase(); if (entityType === 'link') { const { url } = entity.getData(); return { element: 'a', attributes: { rel: 'noopener noreferrer', target: '_blank', href: url, }, }; } }, }; return stateToHTML(editorState.getCurrentContent(), markupConfig); }; const isEditorFocused = editorState => editorState.getSelection().getHasFocus(); /** Returns true in case the editor's content does not contain any block which has a non-default type or text. It means that if the user changes the block type before entering any text, the content will be considered as non-empty. */ const isEditorEmpty = editorState => !editorState.getCurrentContent().hasText() && editorState .getCurrentContent() .getBlockMap() .first() .getType() === blockTypes.unstyled; // Returns whether a text is selected const _hasSelectedText = editorState => !editorState.getSelection().isCollapsed(); const _getSelectedBlock = editorState => { const selection = editorState.getSelection(); const currentContent = editorState.getCurrentContent(); // Resolves the current block of the selection const anchorKey = selection.getAnchorKey(); const currentBlock = currentContent.getBlockForKey(anchorKey); // Resolves the current block with extra information return { contentBlock: currentBlock, startOffset: selection.getStartOffset(), endOffset: selection.getEndOffset(), startKey: selection.getStartKey(), endKey: selection.getEndKey(), }; }; const _attachLinkEntityToText = (editorState, { text, url }) => { const contentState = editorState.getCurrentContent(); const selectionState = editorState.getSelection(); const contentStateWithEntity = contentState.createEntity('LINK', 'MUTABLE', { url, }); const entityKey = contentStateWithEntity.getLastCreatedEntityKey(); const startPosition = selectionState.getStartOffset(); const endPosition = startPosition + text.length; // A key for the block that containing the start of the selection range const blockKey = selectionState.getStartKey(); // Replaces the content in specified selection range with text const contentStateWithText = Modifier.replaceText( contentState, selectionState, text, ); const newSelectionState = new SelectionState({ anchorOffset: startPosition, anchorKey: blockKey, focusOffset: endPosition, focusKey: blockKey, }); const newEditorState = EditorState.push( editorState, contentStateWithText, 'insert-characters', ); return RichUtils.toggleLink(newEditorState, newSelectionState, entityKey); }; const _removeEntityFromBlock = (editorState, contentBlock, entity) => { const contentState = editorState.getCurrentContent(); const selectionState = editorState.getSelection(); let selectionWithEntity = null; contentBlock.findEntityRanges( character => character.getEntity() === entity, (start, end) => { // Creates a selection state that contains the whole text that's linked to the entity selectionWithEntity = selectionState.merge({ anchorOffset: start, focusOffset: end, }); }, ); // Removes the linking between the text and entity const contentStateWithoutEntity = Modifier.applyEntity( contentState, selectionWithEntity, null, ); const newEditorState = EditorState.push( editorState, contentStateWithoutEntity, 'apply-entity', ); return RichUtils.toggleLink(newEditorState, selectionState, null); }; export default { hasStyle, hasBlockType, hasEntity, hasRemovableEntityInSelection, toggleStyle, toggleBlockType, toggleLink, getSelectedText, findLinkEntities, convertToHtml, isEditorFocused, isEditorEmpty, };
29.003953
123
0.714909
3d7c3dddfba4e1b085f8645ab1520868c15bf35f
5,787
js
JavaScript
popup.js
Difegue/Tsukihi
262e8241460bf96e901c34c8d3bfb2b036e7e0c4
[ "MIT" ]
21
2021-04-07T12:55:40.000Z
2022-03-28T11:55:06.000Z
popup.js
Difegue/Tsukihi
262e8241460bf96e901c34c8d3bfb2b036e7e0c4
[ "MIT" ]
10
2021-04-18T02:47:52.000Z
2021-09-07T13:26:04.000Z
popup.js
Difegue/Tsukihi
262e8241460bf96e901c34c8d3bfb2b036e7e0c4
[ "MIT" ]
null
null
null
// Use of this source code is governed by a license that can be // found in the LICENSE file. 'use strict'; // Ask background.js about the state of this tab, and update popup accordingly. chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) { chrome.runtime.sendMessage({ type: "getTabInfo", tab: tabs[0] }, (response) => updatePopup(response)); }); // Add a listener to receive dynamic updates from background.js chrome.runtime.onMessage.addListener((request, s, c) => { if (request.type == "updateFromBackground") { updatePopup(request.data); } }); // Hook up buttons document.getElementById('downloadUrl').onclick = () => chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) { chrome.runtime.sendMessage({ type: "downloadUrl", tab: tabs[0] }); }); document.getElementById('downloadLeft').onclick = () => chrome.tabs.query({ currentWindow: true }, function (tabs) { chrome.runtime.sendMessage({ type: "batchDownload", tabs: getLeftSideTags(tabs) }); }); document.getElementById('downloadRight').onclick = () => chrome.tabs.query({ currentWindow: true }, function (tabs) { chrome.runtime.sendMessage({ type: "batchDownload", tabs: getRightSideTags(tabs) }); }); document.getElementById('allDownloads').onclick = () => chrome.storage.sync.get(['server'], function (result) { if (typeof result.server !== 'undefined' && result.server.trim() !== "") // check for undefined chrome.tabs.create({ url: `${result.server}/minion/jobs` }); }); document.getElementById('openSettings').onclick = () => chrome.runtime.openOptionsPage(); document.getElementById('recheckTab').onclick = () => chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) { chrome.runtime.sendMessage({ type: "recheckTab", tab: tabs[0] }); }); // Wow actual logic function updatePopup(dataFromBackground) { console.log("Received data from background.js: " + JSON.stringify(dataFromBackground)); document.getElementById('statusMsg').style = "color:black" document.getElementById('downloadUrl').disabled = false; try { switch (dataFromBackground.status) { case "downloaded": document.getElementById('statusIcon').textContent = "✅"; document.getElementById('statusMsg').textContent = " saved to your LRR server!"; document.getElementById('statusMsg').style = "color:green" document.getElementById('downloadUrl').disabled = true; chrome.storage.sync.get(['server'], function (result) { safeHtmlInject(document.getElementById('statusDetail'), `<span>(id: <a href="${result.server}/reader?id=${dataFromBackground.arcId}" target= "_blank"> ${dataFromBackground.arcId} </a>)</span>`); }); break; case "downloading": document.getElementById('statusIcon').textContent = "🔜"; document.getElementById('statusMsg').textContent = " being downloaded..."; document.getElementById('statusMsg').style = "color:blue" document.getElementById('statusDetail').textContent = `(job: #${dataFromBackground.jobId})`; break; case "checking": document.getElementById('statusIcon').textContent = "⌛"; document.getElementById('statusMsg').textContent = " being checked..."; document.getElementById('statusMsg').style = "color:orange" document.getElementById('statusDetail').textContent = `(Please wait warmly.)`; break; case "other": document.getElementById('statusIcon').textContent = "⁉"; document.getElementById('statusMsg').textContent = "... just a tab."; document.getElementById('statusDetail').textContent = `(${dataFromBackground.message})`; break; case "error": document.getElementById('statusIcon').textContent = "❌"; document.getElementById('statusMsg').textContent = " not okay."; document.getElementById('statusMsg').style = "color:red" document.getElementById('statusDetail').textContent = `(Error: ${dataFromBackground.message})`; break; default: document.getElementById('statusIcon').textContent = "👻"; document.getElementById('statusMsg').textContent = " a mystery."; document.getElementById('statusDetail').textContent = `(Unknown status message ${dataFromBackground.status})`; } } catch (e) { console.log(e); document.getElementById('statusIcon').textContent = "👻"; document.getElementById('statusMsg').textContent = " a mystery."; document.getElementById('statusDetail').textContent = `(${e})`; } } function getLeftSideTags(tabs) { var filtered_tabs = []; var activeIndex = -1; for (var i = 0; i < tabs.length; i++) { if (tabs[i].active) { activeIndex = tabs[i].index; break; } } for (var i = 0; i < tabs.length; i++) { if (tabs[i].index < activeIndex) { filtered_tabs.push(tabs[i]); } } return filtered_tabs; } function getRightSideTags(tabs) { var filtered_tabs = []; var activeIndex = -1; for (var i = 0; i < tabs.length; i++) { if (tabs[i].active) { activeIndex = tabs[i].index; break; } } for (var i = 0; i < tabs.length; i++) { if (tabs[i].index > activeIndex) { filtered_tabs.push(tabs[i]); } } return filtered_tabs; } // Thanks firefox I guess https://devtidbits.com/2017/12/06/quick-fix-the-unsafe_var_assignment-warning-in-javascript function safeHtmlInject(element, html) { element.textContent = ""; const parser = new DOMParser() const parsed = parser.parseFromString(html, "text/html") const tags = parsed.getElementsByTagName("body")[0].children; for (const tag of tags) { element.appendChild(tag) } }
35.286585
118
0.658545
3d7dab4f4ea651b82ef24f98c8cd58a03ec7417b
708
js
JavaScript
dapp/src/utils/calculator.js
leonprou/CLN-community-app
b8e9bae1c11e64bee8aeb81806a7892844b3b8d4
[ "MIT" ]
3
2018-05-21T18:36:21.000Z
2018-06-20T03:15:31.000Z
dapp/src/utils/calculator.js
leonprou/CLN-community-app
b8e9bae1c11e64bee8aeb81806a7892844b3b8d4
[ "MIT" ]
27
2018-08-14T09:19:57.000Z
2021-05-07T03:36:52.000Z
dapp/src/utils/calculator.js
leonprou/CLN-community-app
b8e9bae1c11e64bee8aeb81806a7892844b3b8d4
[ "MIT" ]
3
2018-07-12T12:29:41.000Z
2018-08-07T10:59:04.000Z
export const predictClnReserves = ({ initialClnReserve, amountOfTransactions, averageTransactionInUsd, clnPrice, gainRatio, iterations }) => { const clnGain = calcClnGain({ averageTransactionInUsd, clnPrice, amountOfTransactions, gainRatio }) let nextClnReserve = initialClnReserve const clnReserves = [nextClnReserve] for (let i = 0; i < iterations; i++) { nextClnReserve += clnGain clnReserves.push(nextClnReserve) } return clnReserves } export const calcClnGain = ({ averageTransactionInUsd, clnPrice, amountOfTransactions, gainRatio }) => { const averageTransactionInCln = averageTransactionInUsd / clnPrice return averageTransactionInCln * amountOfTransactions * gainRatio }
39.333333
104
0.775424
3d7dbf857c1fd36f13a71a3edf810be7222e178e
819
js
JavaScript
style/chartWithUpwardsTrend.js
buildbreakdo/emoji
2271819ec4839a478fdd8388d78d0799df8c258b
[ "CC-BY-4.0", "MIT" ]
3
2019-04-29T08:25:34.000Z
2020-09-22T15:51:47.000Z
style/chartWithUpwardsTrend.js
buildbreakdo/emoji
2271819ec4839a478fdd8388d78d0799df8c258b
[ "CC-BY-4.0", "MIT" ]
null
null
null
style/chartWithUpwardsTrend.js
buildbreakdo/emoji
2271819ec4839a478fdd8388d78d0799df8c258b
[ "CC-BY-4.0", "MIT" ]
1
2019-09-14T04:05:36.000Z
2019-09-14T04:05:36.000Z
module.exports = { "background": "center / contain no-repeat url(\"data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 64 64'%3e%3cpath fill='white' d='m0 0h64v64h-64z'/%3e%3cpath fill='%2352c18e' d='m58.7 5.3h-5.6l-15.8 20.2-9.6-11.2-27.7 40.2v9.5h6.4l22.2-32.3 9.2 10.6 20.9-26.8z'/%3e%3cpath d='m64 0h-64v50.7l3-4.3h-.9v-13.3h10l1.5-2.1h-11.5v-13.4h13.3v10.7l2.1-3.1v-7.6h5.2l1.5-2.1h-6.7v-13.4h13.3v12.7l2.4 2.8h7.5l1.7-2.1h-9.4v-13.4h13.3v8.3l2.1-2.7v-5.6h13.3v13.3h-1.1v.8l-1 1.3h2.1v13.3h-12.4l-2.9 3.8v11.7h-13.3v-6.3l-2.1-2.5v8.7h-9.8l-1.5 2.1h11.3v13.3h-13.4v-10.1l-2.1 3.1v7.3h-5l-1.5 2.1h55v-64m-48.5 15.5h-13.4v-13.4h13.3c.1 0 .1 13.4.1 13.4m30.9 46.4h-13.3v-13.4h13.3c0 0 0 13.4 0 13.4m15.5 0h-13.4v-13.4h13.3v13.4zm0-15.5h-13.4v-13.3h13.3v13.3z' fill='%23d0d5d8'/%3e%3c/svg%3e\")" }
819
819
0.671551
3d7de87cb137ca92ac50cd573b410964df5023f6
4,231
js
JavaScript
src/components/Projects/AddProjectForm.js
lilian-n/defect-tracker-frontend
a24fb776c44dd9ade099680eec91ebd117c13dac
[ "MIT" ]
null
null
null
src/components/Projects/AddProjectForm.js
lilian-n/defect-tracker-frontend
a24fb776c44dd9ade099680eec91ebd117c13dac
[ "MIT" ]
null
null
null
src/components/Projects/AddProjectForm.js
lilian-n/defect-tracker-frontend
a24fb776c44dd9ade099680eec91ebd117c13dac
[ "MIT" ]
null
null
null
import React from "react"; import { useDispatch } from "react-redux"; import { useAuth0 } from "@auth0/auth0-react"; import { useForm, Controller } from "react-hook-form"; import { Form, FormText, Modal, ModalHeader, ModalBody, ModalFooter, Button, FormGroup, Label, Input } from "reactstrap"; import DateTimePicker from "react-widgets/lib/DateTimePicker" import { addProject } from "../../redux-store/projectSlice"; const AddProjectForm = ({ open, setOpen }) => { // set default values for react hook form const defaultValues = { projectTitle: "", projectDescription: "", projectStartDate: new Date(), projectTargetEndDate: null } const dispatch = useDispatch(); const { getAccessTokenSilently } = useAuth0(); const { register, errors, handleSubmit, control } = useForm({ defaultValues }); function handleClose() { setOpen(false); } async function onSubmit(data) { const token = await getAccessTokenSilently(); const newValues = { token, title: data.projectTitle, description: data.projectDescription, startDate: data.projectStartDate, targetEndDate: data.projectTargetEndDate } dispatch(addProject(newValues)) setOpen(false); } return ( <Modal isOpen={open} toggle={handleClose} backdrop="static"> <Form onSubmit={handleSubmit(onSubmit)}> <ModalHeader toggle={handleClose}>Add a new project</ModalHeader> <ModalBody> <FormGroup> <Label for="projectTitle">Project Title</Label> <Input type="text" name="projectTitle" innerRef={register({ required: true })} /> <FormText color="muted"> Required </FormText> <p style={{ color: "red" }}>{errors.projectTitle && "Project title is required."}</p> </FormGroup> <FormGroup> <Label for="projectDescription">Project Description</Label> <Input type="text" name="projectDescription" id="projectDescription" innerRef={register({ required: true })} /> <FormText color="muted"> Required </FormText> <p style={{ color: "red" }}>{errors.projectDescription && "Project description is required."}</p> </FormGroup> <FormGroup> <Label for="projectStartDate">Project Start Date</Label> <Controller name="projectStartDate" control={control} register={register({ required: true })} rules={{ required: true }} render={props => <DateTimePicker onChange={(e) => props.onChange(e)} value={props.value} format="MM/DD/YYYY" time={false} /> } /> <FormText color="muted"> Required </FormText> <p style={{ color: "red" }}>{errors.projectStartDate && "Project start date is required."}</p> </FormGroup> <FormGroup> <Label for="projectTargetEndDate">Project Target End Date</Label> <Controller name="projectTargetEndDate" control={control} register={register({ required: true })} rules={{ required: true }} render={props => <DateTimePicker onChange={(e) => props.onChange(e)} value={props.value} format="MM/DD/YYYY" time={false} /> } /> <FormText color="muted"> Required </FormText> <p style={{ color: "red" }}>{errors.projectTargetEndDate && "Project target end date is required."}</p> </FormGroup> </ModalBody> <ModalFooter> <Button color="danger" onClick={handleClose}>Cancel</Button> <Button color="info" type="submit">Submit</Button> </ModalFooter> </Form> </Modal> ); } export default AddProjectForm;
29.795775
115
0.542661
3d7e460e94f21466b8f39458ba881368415acf1a
988
js
JavaScript
src/modules/drag.and.drop.module.js
astec/blog-electron-app-sexy
8f61fb1bde0b3e62384cdd0de5c3955152883101
[ "CC0-1.0" ]
null
null
null
src/modules/drag.and.drop.module.js
astec/blog-electron-app-sexy
8f61fb1bde0b3e62384cdd0de5c3955152883101
[ "CC0-1.0" ]
null
null
null
src/modules/drag.and.drop.module.js
astec/blog-electron-app-sexy
8f61fb1bde0b3e62384cdd0de5c3955152883101
[ "CC0-1.0" ]
null
null
null
module.exports = { init: () => { const dragAndDrop = document.getElementById('drag-and-drop'); dragAndDrop.ondragover = () => { return false; }; dragAndDrop.ondragleave = () => { return false; }; dragAndDrop.ondragend = () => { return false; }; dragAndDrop.ondrop = (e) => { e.preventDefault(); const paths = []; for (let file of e.dataTransfer.files) { paths.push(file.path); } // create html from file paths const fileItems = paths.reduce((html, file) => { html += `<li class="file-item">${file}</li>`; return html; }, ''); // put File paths items into fileList element const fileList = document.getElementById('fileList'); fileList.innerHTML = fileItems; return false; }; }, };
27.444444
69
0.464575
3d7e8ffd1a4d5e14d120eb165c7740a5688b78a1
678
js
JavaScript
V11411_Code File/S09/9_1_project_files/js_sandbox/app.js
danomanion/Modern-JavaScript-From-The-Beginning
3e6110d84434d00113713cdfee7cc1d24fa1fcee
[ "MIT" ]
null
null
null
V11411_Code File/S09/9_1_project_files/js_sandbox/app.js
danomanion/Modern-JavaScript-From-The-Beginning
3e6110d84434d00113713cdfee7cc1d24fa1fcee
[ "MIT" ]
null
null
null
V11411_Code File/S09/9_1_project_files/js_sandbox/app.js
danomanion/Modern-JavaScript-From-The-Beginning
3e6110d84434d00113713cdfee7cc1d24fa1fcee
[ "MIT" ]
null
null
null
const user = {email: 'jdoe@gmail.com'}; try { // Produce a ReferenceError // myFunction(); // Produce a TypeError // null.myFunction(); // Will produce SyntaxError // eval('Hello World'); // Will produce a URIError // decodeURIComponent('%'); if(!user.name) { //throw 'User has no name'; throw new SyntaxError('User has no name'); } } catch(e) { console.log(`User Error: ${e.message}`); // console.log(e); // console.log(e.message); // console.log(e.name); // console.log(e instanceof TypeError); } finally { console.log('Finally runs reguardless of result...'); } console.log('Program continues...');
21.870968
56
0.59882
3d7ebee662f056a4f47d5c47ca757e2b05629c4e
3,304
js
JavaScript
test/globcp-spec.js
abelnation/globcp
44151032640dd696494d71456b3a0c6951246d0f
[ "MIT" ]
1
2016-04-07T19:59:34.000Z
2016-04-07T19:59:34.000Z
test/globcp-spec.js
abelnation/globcp
44151032640dd696494d71456b3a0c6951246d0f
[ "MIT" ]
null
null
null
test/globcp-spec.js
abelnation/globcp
44151032640dd696494d71456b3a0c6951246d0f
[ "MIT" ]
null
null
null
var _ = require('lodash') var fs = require('fs-extra') var path = require('path') var assert = require('chai').assert var fsAssert = require('./helpers/fs-assert') var Globcp = require('../lib/globcp') describe('globcp', function() { var tmpDir var fixturesDir var globcp function checkResult(destDir, expectedFiles, done) { return function(err) { if (err) { return done(err) } _.each(expectedFiles, function(relPath) { var destPath = path.resolve(destDir, relPath) assert(fs.existsSync(destPath), 'file exists: ' + destPath) }) done() } } before(function() { tmpDir = '/tmp/globcp' fs.ensureDirSync(tmpDir) fixturesDir = path.resolve(__dirname, 'fixtures') globcp = new Globcp({ debug: true }) }) beforeEach(function() { fs.emptyDirSync(tmpDir) }) after(function() { // fs.removeSync(tmpDir) }) describe('flat copy to dest dir', function() { it('**', function(done) { var srcDir = path.resolve(fixturesDir, 'flat_01') var destDir = path.resolve(tmpDir, 'dest') globcp.copyFlat(srcDir, '**', destDir, checkResult(destDir, [ 'a.html', 'a.txt', 'b.txt', 'c.txt' ], done)) }) it('*.txt', function(done) { var srcDir = path.resolve(fixturesDir, 'flat_01') var destDir = path.resolve(tmpDir, 'dest') globcp.copyFlat(srcDir, '**', destDir, checkResult(destDir, [ 'a.txt', 'b.txt', 'c.txt' ], done)) }) it('a.*', function(done) { var srcDir = path.resolve(fixturesDir, 'flat_01') var destDir = path.resolve(tmpDir, 'dest') globcp.copyFlat(srcDir, 'a.*', destDir, checkResult(destDir, [ 'a.html', 'a.txt' ], done)) }) it('nested src, **/*.txt', function(done) { var srcDir = path.resolve(fixturesDir, 'tree_01') var destDir = path.resolve(tmpDir, 'dest') globcp.copyFlat(srcDir, '**/*.txt', destDir, checkResult(destDir, [ 'a.txt', 'b.txt', 'c.txt' ], done)) }) it('nested src, **/b*', function(done) { var srcDir = path.resolve(fixturesDir, 'tree_01') var destDir = path.resolve(tmpDir, 'dest') globcp.copyFlat(srcDir, '**/*.txt', destDir, checkResult(destDir, [ 'b.txt' ], done)) }) }) describe('copy and preserve tree with base dir', function() { it('**', function(done) { var srcDir = path.resolve(fixturesDir, 'flat_01') var destDir = path.resolve(tmpDir, 'dest') globcp.copyTree(srcDir, '**', destDir, checkResult(destDir, [ 'a.html', 'a.txt', 'b.txt', 'c.txt' ], done)) }) it('nested src, **', function(done) { var srcDir = path.resolve(fixturesDir, 'tree_01') var destDir = path.resolve(tmpDir, 'dest') globcp.copyTree(srcDir, '**', destDir, checkResult(destDir, [ 'a/a.txt', 'a/b/b.txt', 'a/b/c/c.txt' ], done)) }) }) })
31.466667
79
0.515436
3d7ef1ee44a6a0dd2b051a09d6b2edb5d6f3a366
927
js
JavaScript
models/user.js
tboyd4/video-game-trader
a60f4109a1a7f5ee5dff5c7ebc97cbf415c45fcb
[ "MIT" ]
1
2020-05-02T15:29:36.000Z
2020-05-02T15:29:36.000Z
models/user.js
tboyd4/video-game-trader
a60f4109a1a7f5ee5dff5c7ebc97cbf415c45fcb
[ "MIT" ]
4
2020-05-02T15:05:02.000Z
2021-05-11T12:53:18.000Z
models/user.js
tboyd4/video-game-trader
a60f4109a1a7f5ee5dff5c7ebc97cbf415c45fcb
[ "MIT" ]
1
2021-06-15T22:30:25.000Z
2021-06-15T22:30:25.000Z
module.exports = function (Sequelize, DataTypes) { var User = Sequelize.define("User", { id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true, }, userName: { type: DataTypes.TEXT, }, email: { type: DataTypes.STRING, validate: { isEmail: true, }, }, password: { type: DataTypes.STRING, allowNull: false, }, firstName: { type: DataTypes.TEXT, allowNull: false, }, lastName: { type: DataTypes.TEXT, allowNull: false, }, centaurs: { type: DataTypes.DECIMAL(10, 2), allowNull: false, defaultValue: 0, } }); User.associate = function (models) { // Associating User with their character // When a User is deleted, also delete any associated characters User.hasMany(models.Game, { onDelete: "cascade", }); }; return User; };
20.152174
68
0.562028
3d800e4e2964006690067dfb2edd3fdbed9c97cc
7,377
js
JavaScript
app/features/settings/components/SettingsDrawer.js
PolynomialDivision/jitsi-meet-electron
4c1894f230882e38a4907d3c9e0b87469cf6056d
[ "Apache-2.0" ]
null
null
null
app/features/settings/components/SettingsDrawer.js
PolynomialDivision/jitsi-meet-electron
4c1894f230882e38a4907d3c9e0b87469cf6056d
[ "Apache-2.0" ]
3
2020-10-06T15:21:19.000Z
2022-03-25T19:05:39.000Z
app/features/settings/components/SettingsDrawer.js
PolynomialDivision/jitsi-meet-electron
4c1894f230882e38a4907d3c9e0b87469cf6056d
[ "Apache-2.0" ]
null
null
null
// @flow import Avatar from '@atlaskit/avatar'; import FieldText from '@atlaskit/field-text'; import ArrowLeft from '@atlaskit/icon/glyph/arrow-left'; import { AkCustomDrawer } from '@atlaskit/navigation'; import { SpotlightTarget } from '@atlaskit/onboarding'; import React, { Component } from 'react'; import { connect } from 'react-redux'; import type { Dispatch } from 'redux'; import { closeDrawer, DrawerContainer, Logo } from '../../navbar'; import { Onboarding, startOnboarding } from '../../onboarding'; import { AvatarContainer, SettingsContainer, TogglesContainer } from '../styled'; import { setEmail, setName } from '../actions'; import AlwaysOnTopWindowToggle from './AlwaysOnTopWindowToggle'; import ServerURLField from './ServerURLField'; import StartMutedToggles from './StartMutedToggles'; type Props = { /** * Redux dispatch. */ dispatch: Dispatch<*>; /** * Is the drawer open or not. */ isOpen: boolean; /** * Avatar URL. */ _avatarURL: string; /** * Email of the user. */ _email: string; /** * Name of the user. */ _name: string; }; /** * Drawer that open when SettingsAction is clicked. */ class SettingsDrawer extends Component<Props, *> { /** * Initializes a new {@code SettingsDrawer} instance. * * @inheritdoc */ constructor(props) { super(props); this._onBackButton = this._onBackButton.bind(this); this._onEmailBlur = this._onEmailBlur.bind(this); this._onEmailFormSubmit = this._onEmailFormSubmit.bind(this); this._onNameBlur = this._onNameBlur.bind(this); this._onNameFormSubmit = this._onNameFormSubmit.bind(this); } /** * Start Onboarding once component is mounted. * * NOTE: It automatically checks if the onboarding is shown or not. * * @param {Props} prevProps - Props before component updated. * @returns {void} */ componentDidUpdate(prevProps: Props) { if (!prevProps.isOpen && this.props.isOpen) { // TODO - Find a better way for this. // Delay for 300ms to let drawer open. setTimeout(() => { this.props.dispatch(startOnboarding('settings-drawer')); }, 300); } } /** * Render function of component. * * @returns {ReactElement} */ render() { return ( <AkCustomDrawer backIcon = { <ArrowLeft label = 'Back' /> } isOpen = { this.props.isOpen } onBackButton = { this._onBackButton } primaryIcon = { <Logo /> } > <DrawerContainer> <SettingsContainer> <AvatarContainer> <Avatar size = 'xlarge' src = { this.props._avatarURL } /> </AvatarContainer> <SpotlightTarget name = 'name-setting'> <form onSubmit = { this._onNameFormSubmit }> <FieldText label = 'Name' onBlur = { this._onNameBlur } shouldFitContainer = { true } type = 'text' value = { this.props._name } /> </form> </SpotlightTarget> <SpotlightTarget name = 'email-setting'> <form onSubmit = { this._onEmailFormSubmit }> <FieldText label = 'Email' onBlur = { this._onEmailBlur } shouldFitContainer = { true } type = 'text' value = { this.props._email } /> </form> </SpotlightTarget> <SpotlightTarget name = 'server-setting'> <ServerURLField /> </SpotlightTarget> <TogglesContainer> <SpotlightTarget name = 'start-muted-toggles'> <StartMutedToggles /> </SpotlightTarget> <SpotlightTarget name = 'always-on-top-window'> <AlwaysOnTopWindowToggle /> </SpotlightTarget> </TogglesContainer> <Onboarding section = 'settings-drawer' /> </SettingsContainer> </DrawerContainer> </AkCustomDrawer> ); } _onBackButton: (*) => void; /** * Closes the drawer when back button is clicked. * * @returns {void} */ _onBackButton() { this.props.dispatch(closeDrawer()); } _onEmailBlur: (*) => void; /** * Updates Avatar URL in (redux) state when email is updated. * * @param {SyntheticInputEvent<HTMLInputElement>} event - Event by which * this function is called. * @returns {void} */ _onEmailBlur(event: SyntheticInputEvent<HTMLInputElement>) { this.props.dispatch(setEmail(event.currentTarget.value)); } _onEmailFormSubmit: (*) => void; /** * Prevents submission of the form and updates email. * * @param {SyntheticEvent<HTMLFormElement>} event - Event by which * this function is called. * @returns {void} */ _onEmailFormSubmit(event: SyntheticEvent<HTMLFormElement>) { event.preventDefault(); // $FlowFixMe this.props.dispatch(setEmail(event.currentTarget.elements[0].value)); } _onNameBlur: (*) => void; /** * Updates Avatar URL in (redux) state when name is updated. * * @param {SyntheticInputEvent<HTMLInputElement>} event - Event by which * this function is called. * @returns {void} */ _onNameBlur(event: SyntheticInputEvent<HTMLInputElement>) { this.props.dispatch(setName(event.currentTarget.value)); } _onNameFormSubmit: (*) => void; /** * Prevents submission of the form and updates name. * * @param {SyntheticEvent<HTMLFormElement>} event - Event by which * this function is called. * @returns {void} */ _onNameFormSubmit(event: SyntheticEvent<HTMLFormElement>) { event.preventDefault(); // $FlowFixMe this.props.dispatch(setName(event.currentTarget.elements[0].value)); } } /** * Maps (parts of) the redux state to the React props. * * @param {Object} state - The redux state. * @returns {{ * _avatarURL: string, * _email: string, * _name: string * }} */ function _mapStateToProps(state: Object) { return { _avatarURL: state.settings.avatarURL, _email: state.settings.email, _name: state.settings.name }; } export default connect(_mapStateToProps)(SettingsDrawer);
30.7375
81
0.518097
3d8069b3075dcb713bae3784a151d62b84af2021
64
js
JavaScript
js/arithmatic.js
dambergn/js-ten-key-calc
b97c37fdff0c0dd79dfe73d2a0e78cc7e7d39942
[ "MIT" ]
null
null
null
js/arithmatic.js
dambergn/js-ten-key-calc
b97c37fdff0c0dd79dfe73d2a0e78cc7e7d39942
[ "MIT" ]
null
null
null
js/arithmatic.js
dambergn/js-ten-key-calc
b97c37fdff0c0dd79dfe73d2a0e78cc7e7d39942
[ "MIT" ]
null
null
null
'use strict'; // Addition, Subtraction, Multiplication, Division
32
50
0.78125
3d809cda414e1237ad637c912fa9c088c55ab21d
3,202
js
JavaScript
src/components/inputs/text-input.js
jlvvlj/glitch-test
c0d635ad3535b819b18cafc5061de6caa2a1e5f6
[ "Apache-2.0" ]
null
null
null
src/components/inputs/text-input.js
jlvvlj/glitch-test
c0d635ad3535b819b18cafc5061de6caa2a1e5f6
[ "Apache-2.0" ]
null
null
null
src/components/inputs/text-input.js
jlvvlj/glitch-test
c0d635ad3535b819b18cafc5061de6caa2a1e5f6
[ "Apache-2.0" ]
null
null
null
import React, { forwardRef } from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import { pickBy } from 'lodash'; import useUniqueId from 'Hooks/use-unique-id'; import InputErrorMessage from './input-error-message'; import InputErrorIcon from './input-error-icon'; import styles from './text-input.styl'; import { visuallyHidden } from '../global.styl'; const TYPES = ['email', 'password', 'search', 'text']; const InputPart = ({ children, className }) => <span className={classNames(styles.inputPart, className)}>{children}</span>; const TextInput = forwardRef(({ autoFocus, className, disabled, error, labelText, maxLength, name, onChange, onBlur, onFocus, opaque, placeholder, postfix, prefix, testingId, type, value, ...props }, ref) => { const uniqueId = useUniqueId(); const outerClassName = classNames(className, styles.outer); const borderClassName = classNames(styles.inputBorder, { [styles.underline]: !opaque, [styles.opaque]: opaque, }); const inputClassName = classNames(styles.inputPart, styles.input, { [styles.search]: type === 'search', }); const eventProps = pickBy(props, (_, key) => key.startsWith('on')); return ( <label className={outerClassName} htmlFor={uniqueId}> <span className={visuallyHidden}>{labelText}</span> <span className={borderClassName}> {!!prefix && <InputPart>{prefix}</InputPart>} <input {...eventProps} ref={ref} autoFocus={autoFocus} // eslint-disable-line jsx-a11y/no-autofocus className={inputClassName} disabled={disabled} id={uniqueId} data-cy={testingId} maxLength={maxLength} name={name} onChange={(evt) => onChange(evt.target.value)} onBlur={onBlur} onFocus={onFocus} placeholder={placeholder} type={type} value={value} spellCheck={type !== 'email' && type !== 'password'} /> {!!error && ( <InputPart className={styles.errorIcon}> <InputErrorIcon /> </InputPart> )} {!!postfix && <InputPart>{postfix}</InputPart>} </span> {!!error && <InputErrorMessage>{error}</InputErrorMessage>} </label> ); }); TextInput.propTypes = { autoFocus: PropTypes.bool, className: PropTypes.string, disabled: PropTypes.bool, error: PropTypes.node, labelText: PropTypes.string.isRequired, maxLength: PropTypes.number, name: PropTypes.string, onChange: PropTypes.func.isRequired, onBlur: PropTypes.func, onFocus: PropTypes.func, opaque: PropTypes.bool, placeholder: PropTypes.string, postfix: PropTypes.node, prefix: PropTypes.node, testingId: PropTypes.string, type: PropTypes.oneOf(TYPES), value: PropTypes.string.isRequired, }; TextInput.defaultProps = { autoFocus: false, className: '', disabled: false, error: null, maxLength: undefined, name: undefined, onBlur: undefined, onFocus: undefined, opaque: false, placeholder: undefined, postfix: null, prefix: null, testingId: undefined, type: 'text', }; export default TextInput;
26.683333
123
0.648345
3d816b07b3e62610eca9b9b9ceb652464eb61e21
7,987
js
JavaScript
test/destroy.test.js
cafreeman/ember-cli-typescript-blueprint-polyfill
8bede4c079219d3f7a68fedabed08296c89460a0
[ "MIT" ]
null
null
null
test/destroy.test.js
cafreeman/ember-cli-typescript-blueprint-polyfill
8bede4c079219d3f7a68fedabed08296c89460a0
[ "MIT" ]
null
null
null
test/destroy.test.js
cafreeman/ember-cli-typescript-blueprint-polyfill
8bede4c079219d3f7a68fedabed08296c89460a0
[ "MIT" ]
1
2022-02-09T22:32:38.000Z
2022-02-09T22:32:38.000Z
/* eslint jest/expect-expect: ["error", { "assertFunctionNames": ["expect", "assertFilesExist", "assertFilesNotExist"] }] */ const { Project } = require('fixturify-project'); const path = require('path'); const execa = require('execa'); const fs = require('fs-extra'); const ROOT = process.cwd(); const EmberCLITargets = ['ember-cli-3-24', 'ember-cli-3-28', 'ember-cli']; // const EmberCLITargets = ['ember-cli']; describe('ember destroy', () => { let fixturifyProject; EmberCLITargets.forEach((target) => { describe(`ember-cli: ${target}`, function () { const cliBinPath = require.resolve(`${target}/bin/ember`); function ember(args) { return execa(cliBinPath, args); } beforeEach(() => { fixturifyProject = new Project('best-ever', '0.0.0', { files: {}, }); fixturifyProject.linkDevDependency('ember-cli', { baseDir: __dirname, resolveName: target, }); addAddon('my-addon', '1.0.0', (addon) => { addon.files.blueprints = { 'my-blueprint': { 'index.js': ` const typescriptBlueprintPolyfill = require('ember-cli-typescript-blueprint-polyfill'); module.exports = { shouldTransformTypeScript: true, init() { this._super && this._super.init.apply(this, arguments); typescriptBlueprintPolyfill(this); } } `, files: { app: { 'my-blueprints': { '__name__.ts': `export default function <%= camelizedModuleName %>(a: string, b: number): string { return a + b; } `, }, }, }, }, }; }); }); afterEach(() => { process.chdir(ROOT); fixturifyProject.dispose(); }); function addAddon(name, version, callback = () => {}) { let addon = fixturifyProject.addDevDependency(name, version, { files: { 'index.js': `module.exports = { name: require("./package").name };`, }, }); addon.pkg.keywords.push('ember-addon'); addon.pkg['ember-addon'] = {}; addon.linkDependency('ember-cli-typescript-blueprint-polyfill', { target: path.join(__dirname, '..'), }); callback(addon); } function assertFilesExist(files) { files.forEach((file) => { expect(fs.pathExistsSync(file)).toBe(true); }); } async function assertFilesNotExist(files) { files.forEach((file) => { expect(fs.pathExistsSync(file)).toBe(false); }); } describe('with flags', () => { beforeEach(() => { fixturifyProject.writeSync(); process.chdir(fixturifyProject.baseDir); }); test('it deletes JS files generated from typescript blueprints and transformed', async () => { const files = ['app/my-blueprints/foo.js']; await ember(['generate', 'my-blueprint', 'foo']); assertFilesExist(files); await ember(['destroy', 'my-blueprint', 'foo']); assertFilesNotExist(files); }); it('deletes TS files generated from typescript blueprints with --typescript', async function () { const files = ['app/my-blueprints/foo.ts']; await ember(['generate', 'my-blueprint', 'foo', '--typescript']); assertFilesExist(files); await ember(['destroy', 'my-blueprint', 'foo']); assertFilesNotExist(files); }); it('deletes TS files generated from typescript blueprints when --typescript is passed', async function () { const files = ['app/my-blueprints/foo.ts']; await ember(['generate', 'my-blueprint', 'foo', '--typescript']); assertFilesExist(files); await ember(['destroy', 'my-blueprint', 'foo', '--typescript']); assertFilesNotExist(files); }); it('does not delete anything if --typescript is passed and there are no TS files', async function () { const files = ['app/my-blueprints/foo.js']; await ember(['generate', 'my-blueprint', 'foo']); assertFilesExist(files); await ember(['destroy', 'my-blueprint', 'foo', '--typescript']); assertFilesExist(files); }); it('does not delete anything if --no-typescript is passed and there are no JS files', async function () { const files = ['app/my-blueprints/foo.ts']; await ember(['generate', 'my-blueprint', 'foo', '--typescript']); assertFilesExist(files); await ember(['destroy', 'my-blueprint', 'foo', '--no-typescript']); assertFilesExist(files); }); describe('when JS and TS files are present', function () { it('deletes the TS file when --typescript is passed', async function () { const files = [ 'app/my-blueprints/foo.ts', 'app/my-blueprints/foo.js', ]; const [tsFile, jsFile] = files; await ember(['generate', 'my-blueprint', 'foo']); await ember(['generate', 'my-blueprint', 'foo', '--typescript']); assertFilesExist(files); await ember(['destroy', 'my-blueprint', 'foo', '--typescript']); assertFilesNotExist([tsFile]); assertFilesExist([jsFile]); }); it('deletes the JS file when --no-typescript flag is passed', async function () { const files = [ 'app/my-blueprints/foo.ts', 'app/my-blueprints/foo.js', ]; const [tsFile, jsFile] = files; await ember(['generate', 'my-blueprint', 'foo']); await ember(['generate', 'my-blueprint', 'foo', '--typescript']); assertFilesExist(files); await ember(['destroy', 'my-blueprint', 'foo', '--no-typescript']); assertFilesExist([tsFile]); assertFilesNotExist([jsFile]); }); it('deletes both files when no flags are passed', async function () { const files = [ 'app/my-blueprints/foo.ts', 'app/my-blueprints/foo.js', ]; await ember(['generate', 'my-blueprint', 'foo']); await ember(['generate', 'my-blueprint', 'foo', '--typescript']); assertFilesExist(files); await ember(['destroy', 'my-blueprint', 'foo']); assertFilesNotExist(files); }); }); }); describe('with project config', () => { it('deletes TS files generated from typescript blueprints in a typescript project', async function () { const files = ['app/my-blueprints/foo.ts']; fixturifyProject.files['.ember-cli'] = JSON.stringify({ isTypeScriptProject: true, }); fixturifyProject.writeSync(); process.chdir(fixturifyProject.baseDir); await ember(['generate', 'my-blueprint', 'foo']); assertFilesExist(files); await ember(['destroy', 'my-blueprint', 'foo']); assertFilesNotExist(files); }); it('deletes TS files generated from typescript blueprints when {typescript: true} is present in .ember-cli', async function () { const files = ['app/my-blueprints/foo.ts']; fixturifyProject.files['.ember-cli'] = JSON.stringify({ typescript: true, }); fixturifyProject.writeSync(); process.chdir(fixturifyProject.baseDir); await ember(['generate', 'my-blueprint', 'foo']); assertFilesExist(files); await ember(['destroy', 'my-blueprint', 'foo']); assertFilesNotExist(files); }); }); }); }); });
33.987234
136
0.536747
3d8191e917e8c990d7128c6543689398e54f293b
133
js
JavaScript
01 JS Fundamentals/01 Intro to JS/EXE_DataTypesAndControlFlow/P08_ImperialUnits.js
stStoyanov93/SoftUni-JavaScript-Core-2018
9501c6655e5b654d9e80c9943012658d76ccff26
[ "MIT" ]
null
null
null
01 JS Fundamentals/01 Intro to JS/EXE_DataTypesAndControlFlow/P08_ImperialUnits.js
stStoyanov93/SoftUni-JavaScript-Core-2018
9501c6655e5b654d9e80c9943012658d76ccff26
[ "MIT" ]
null
null
null
01 JS Fundamentals/01 Intro to JS/EXE_DataTypesAndControlFlow/P08_ImperialUnits.js
stStoyanov93/SoftUni-JavaScript-Core-2018
9501c6655e5b654d9e80c9943012658d76ccff26
[ "MIT" ]
null
null
null
function convertInchesToFeet(inches) { let feet = Math.floor(inches / 12); inches %= 12; return `${feet}'-${inches}"`; }
22.166667
39
0.609023
3d821eb2551c4ac9d3a08c8b5bbf1a2d7f3175d9
419
js
JavaScript
api/classSimTK_1_1Exception_1_1OperationNotAllowedOnNonconstReadOnlyView.js
simbody/simbody-3.6-doxygen
4b5a050652af3d6fd10294ccf6329dd14a6b583b
[ "Apache-2.0" ]
1
2019-12-08T08:34:11.000Z
2019-12-08T08:34:11.000Z
api/classSimTK_1_1Exception_1_1OperationNotAllowedOnNonconstReadOnlyView.js
simbody/simbody-3.6-doxygen
4b5a050652af3d6fd10294ccf6329dd14a6b583b
[ "Apache-2.0" ]
null
null
null
api/classSimTK_1_1Exception_1_1OperationNotAllowedOnNonconstReadOnlyView.js
simbody/simbody-3.6-doxygen
4b5a050652af3d6fd10294ccf6329dd14a6b583b
[ "Apache-2.0" ]
null
null
null
var classSimTK_1_1Exception_1_1OperationNotAllowedOnNonconstReadOnlyView = [ [ "OperationNotAllowedOnNonconstReadOnlyView", "classSimTK_1_1Exception_1_1OperationNotAllowedOnNonconstReadOnlyView.html#a3901ceb68d972dc0f4a8919b8b81b5f3", null ], [ "~OperationNotAllowedOnNonconstReadOnlyView", "classSimTK_1_1Exception_1_1OperationNotAllowedOnNonconstReadOnlyView.html#a31d6b360dfdaac7d4b9a31651448c385", null ] ];
83.8
169
0.885442
3d83b3f8411f4bad1823ba9bdaa7d5baf4e09c6e
3,500
js
JavaScript
gatsby-config.js
gtoyoung/tempBlog
17a40ebfae9d7364810422f8a4c36d84a48f80b5
[ "MIT" ]
null
null
null
gatsby-config.js
gtoyoung/tempBlog
17a40ebfae9d7364810422f8a4c36d84a48f80b5
[ "MIT" ]
null
null
null
gatsby-config.js
gtoyoung/tempBlog
17a40ebfae9d7364810422f8a4c36d84a48f80b5
[ "MIT" ]
null
null
null
require("dotenv").config({ path: `.env.${process.env.NODE_ENV}`, }); const contentfulConfig = { spaceId: process.env.CONTENTFUL_SPACE_ID, accessToken: process.env.CONTENTFUL_ACCESS_TOKEN || process.env.CONTENTFUL_DELIVERY_TOKEN, }; // If you want to use the preview API please define // CONTENTFUL_HOST and CONTENTFUL_PREVIEW_ACCESS_TOKEN in your // environment config. // // CONTENTFUL_HOST should map to `preview.contentful.com` // CONTENTFUL_PREVIEW_ACCESS_TOKEN should map to your // Content Preview API token // // For more information around the Preview API check out the documentation at // https://www.contentful.com/developers/docs/references/content-preview-api/#/reference/spaces/space/get-a-space/console/js // // To change back to the normal CDA, remove the CONTENTFUL_HOST variable from your environment. if (process.env.CONTENTFUL_HOST) { contentfulConfig.host = process.env.CONTENTFUL_HOST; contentfulConfig.accessToken = process.env.CONTENTFUL_PREVIEW_ACCESS_TOKEN; } const { spaceId, accessToken } = contentfulConfig; if (!spaceId || !accessToken) { throw new Error( "Contentful spaceId and the access token need to be provided." ); } module.exports = { siteMetadata: { title: "DOVB`s Blog", }, pathPrefix: "/gatsby-contentful-starter", plugins: [ "gatsby-transformer-sharp", "gatsby-plugin-react-helmet", "gatsby-plugin-sharp", "gatsby-plugin-dark-mode", { resolve: "gatsby-source-contentful", options: contentfulConfig, }, `gatsby-plugin-offline`, { resolve: `gatsby-transformer-remark`, options: { plugins: [ { resolve: `gatsby-remark-autolink-headers`, options: { offsetY: `100`, className: `custom-class`, maintainCase: false, removeAccents: true, elements: [`h2`, `h3`, `h4`, `h5`], }, }, ], }, }, { resolve: `gatsby-plugin-mdx`, options: { gatsbyRemarkPlugins: [ { resolve: `gatsby-remark-highlight-code`, options: { terminal: "ubuntu", theme: "solarized-dark", }, }, { resolve: "gatsby-remark-prismjs", options: { classPrefix: "language-", }, }, { resolve: `gatsby-remark-autolink-headers`, options: { offsetY: `200`, className: `custom-class`, maintainCase: false, removeAccents: true, elements: [`h2`, `h3`, `h4`, `h5`], }, }, { resolve: "gatsby-remark-emoji", // <-- this adds emoji options: { // default emojiConversion --> shortnameToUnicode emojiConversion: "shortnameToUnicode", // when true, matches ASCII characters (in unicodeToImage and shortnameToImage) // e.g. ;) --> 😉 ascii: false, }, }, ], }, }, ], }; const siteMetadata = module.exports.siteMetadata; module.exports.plugins.push({ resolve: `gatsby-plugin-manifest`, options: { name: siteMetadata.title, short_name: `PWA Survival`, start_url: `/`, background_color: `#FF453C`, theme_color: `#070707`, display: "standalone", icon: `src/main.jpg`, legacy: true, }, });
27.559055
124
0.577429