code stringlengths 2 1.05M |
|---|
var LikeButton = React.createClass({
getInitialState: function() {
return {liked: true};
},
handleClick: function(event) {
this.setState({liked: !this.state.liked});
},
render: function() {
var text = this.state.liked ? 'like' : 'haven\'t liked';
return (
<p onClick={this.handleClick}>
You {text} this. Click to toggle.
</p>
);
}
});
ReactDOM.render(
<LikeButton />,
document.getElementById('example')
); |
/**
* # fieldValidation.js
*
* Define the validation rules for various fields such as email, username,
* and passwords. If the rules are not passed, the appropriate
* message is displayed to the user
*
*/
'use strict'
/**
* ## Imports
*
* validate and underscore
*
*/
import validate from 'validate.js'
import _ from 'underscore'
/**
* ## Email validation setup
* Used for validation of emails
*/
const emailConstraints = {
from: {
email: true
}
}
/**
* ## username validation rule
* read the message.. ;)
*/
const usernamePattern = /^[a-zA]{6,12}$/
const usernameConstraints = {
username: {
format: {
pattern: usernamePattern,
flags: 'i'
}
}
}
/**
* ## username validation rule
* read the message.. ;)
*/
const displayNamePattern = /^[a-zA]{4,12}$/
const displayNameConstraints = {
username: {
format: {
pattern: displayNamePattern,
flags: 'i'
}
}
}
/**
* ## password validation rule
* read the message... ;)
*/
const passwordPattern = /^(?=.*[0-9])(?=.*[!@#$%^&*])[a-zA-Z0-9!@#$%^&*]{6,12}$/
const passwordConstraints = {
password: {
format: {
pattern: passwordPattern,
flags: 'i'
}
}
}
const passwordAgainConstraints = {
confirmPassword: {
equality: 'password'
}
}
/**
* ## Field Validation
* @param {Object} state Redux state
* @param {Object} action type & payload
*/
export default function fieldValidation(state, action) {
const {field, value} = action.payload
switch (field) {
case('name'): {//Shipment name
if (value !== '') {
return state.setIn(['form', 'fields', 'nameHasError'],
false)
.setIn(['form', 'fields', 'nameErrorMsg'], '')
} else {
return state.setIn(['form', 'fields', 'nameHasError'], true)
.setIn(['form', 'fields', 'nameErrorMsg'], '')
}
}
/**
* ### username validation
* set the form field error
*/
case ('username'): {
// let validUsername = _.isUndefined(validate({username: value},
// usernameConstraints))
let validUsername = value.length >= 6 && value.length <= 20;
if (validUsername) {
return state.setIn(['form', 'fields', 'usernameHasError'], false)
.setIn(['form', 'fields', 'usernameErrorMsg'], '')
} else {
return state.setIn(['form', 'fields', 'usernameHasError'], true)
.setIn(['form', 'fields', 'usernameErrorMsg'],
'FieldValidation.valid_user_name')
}
}
case ('displayName'): {
let validDisplayName = _.isUndefined(validate({displayName: value}, displayNameConstraints))
if (value.length < 2) {
validDisplayName = false;
}
if (validDisplayName) {
return state.setIn(['form', 'fields', 'displayNameHasError'], false)
.setIn(['form', 'fields', 'displayNameErrorMsg'], '')
} else {
return state.setIn(['form', 'fields', 'displayNameHasError'], true)
.setIn(['form', 'fields', 'displayNameErrorMsg'],
'FieldValidation.valid_display_name')
}
}
case ('eventWhat'): {// the same as 'displayName'
let validDisplayName = _.isUndefined(validate({eventWhat: value}, displayNameConstraints))
if (value.length < 2) {
validDisplayName = false;
}
if (validDisplayName) {
return state.setIn(['form', 'fields', 'eventWhatHasError'], false)
.setIn(['form', 'fields', 'eventWhatErrorMsg'], '')
} else {
return state.setIn(['form', 'fields', 'eventWhatHasError'], true)
.setIn(['form', 'fields', 'eventWhatErrorMsg'],
'FieldValidation.valid_display_name')
}
}
case ('reviewBody'): {// the same as 'displayName'
let validReviewBody = _.isUndefined(validate({reviewBody: value}, displayNameConstraints))
if (value.length < 2) {
validReviewBody = false;
}
if (validReviewBody) {
return state.setIn(['form', 'fields', 'reviewBodyHasError'], false)
.setIn(['form', 'fields', 'reviewBodyErrorMsg'], '')
} else {
return state.setIn(['form', 'fields', 'reviewBodyHasError'], true)
.setIn(['form', 'fields', 'reviewBodyErrorMsg'],
'FieldValidation.valid_display_name')
}
}
/**
* ### email validation
* set the form field error
*/
case ('email'): {
let validEmail = _.isUndefined(validate({from: value},
emailConstraints))
if (validEmail) {
return state.setIn(['form', 'fields', 'emailHasError'], false)
} else {
return state.setIn(['form', 'fields', 'emailHasError'], true)
.setIn(['form', 'fields', 'emailErrorMsg'],
'FieldValidation.valid_email')
}
}
/**
* ### password validation
* set the form field error
*/
case ('password'): {
let validPassword = _.isUndefined(validate({password: value},
passwordConstraints))
if (validPassword) {
return state.setIn(['form', 'fields', 'passwordHasError'],
false)
.setIn(['form', 'fields', 'passwordErrorMsg'],
'')
} else {
return state.setIn(['form', 'fields', 'passwordHasError'], true)
.setIn(['form', 'fields', 'passwordErrorMsg'],
'FieldValidation.valid_password')
}
}
/**
* ### passwordAgain validation
* set the form field error
*/
case ('passwordAgain'):
let validPasswordAgain =
_.isUndefined(validate({
password: state.form.fields.password,
confirmPassword: value
}, passwordAgainConstraints))
if (validPasswordAgain) {
return state.setIn(['form', 'fields', 'passwordAgainHasError'],
false)
.setIn(['form', 'fields', 'passwordAgainErrorMsg'], '')
} else {
return state.setIn(['form', 'fields', 'passwordAgainHasError'],
true)
.setIn(['form', 'fields', 'passwordAgainErrorMsg'],
'FieldValidation.valid_password_again')
}
/**
* ### showPassword
* toggle the display of the password
*/
case ('showPassword'):
return state.setIn(['form', 'fields',
'showPassword'], value)
}
return state
}
|
// Requires:
// model/zone
if (!this.Reading) {
module.exports.Zone = require('./zone.js').Zone;
}
(function (app) { 'use strict';
var Fixations = {
init: function (options) {
options = options || {};
_minDuration = options.minDuration || 80;
_threshold = options.threshold || 70;
_sampleDuration = options.sampleDuration || 33;
_lpc = options.filterDemph || 0.4;
_invLpc = 1 - _lpc;
_zone = app.Zone;
_currentFixation = new Fixation( -10000, -10000, Number.MAX_VALUE );
_currentFixation.saccade = new Saccade( 0, 0 );
},
feed: function (data1, data2) {
var result;
if (data2 !== undefined) { // this is smaple
result = parseSample( data1, data2 );
}
else {
result = parseFixation( data1 );
}
return result;
},
add: function (x, y, duration) {
if (duration < _minDuration) {
return null;
}
var fixation = new Fixation( x, y, duration );
fixation.previous = _currentFixation;
_currentFixation.next = fixation;
fixation.saccade = new Saccade( x - _currentFixation.x, y - _currentFixation.y );
_currentFixation = fixation;
return _currentFixation;
},
reset: function () {
_fixations.length = 0;
_currentFixation = new Fixation(-10000, -10000, Number.MAX_VALUE);
_currentFixation.saccade = new Saccade(0, 0);
_candidate = null;
},
current: function() {
return _currentFixation;
}
};
// internal
var _minDuration;
var _threshold;
var _sampleDuration;
var _fixations = [];
var _currentFixation;
var _candidate = null;
var _lpc;
var _invLpc;
var _zone;
function parseSample (x, y) {
var dx = x - _currentFixation.x;
var dy = y - _currentFixation.y;
var result;
if (Math.sqrt( dx * dx + dy * dy) > _threshold) {
if (_candidate === null) {
_candidate = new Fixation(x, y, _sampleDuration);
_candidate.previous = _currentFixation;
_candidate.saccade = new Saccade(x - _currentFixation.x, y - _currentFixation.y);
_currentFixation.next = _candidate;
}
else {
_candidate.x = _lpc * x + _invLpc * _candidate.x;
_candidate.y = _lpc * y + _invLpc * _candidate.y;
_candidate.duration += _sampleDuration;
_currentFixation = _candidate;
_candidate = null;
}
}
else {
_candidate = null;
var prevDuration = _currentFixation.duration;
_currentFixation.duration += _sampleDuration;
_currentFixation.x = _lpc * _currentFixation.x + _invLpc * x;
_currentFixation.y = _lpc * _currentFixation.y + _invLpc * y;
if (prevDuration < _minDuration && _currentFixation.duration >= _minDuration) {
result = _currentFixation;
}
}
return result;
}
function parseFixation (progressingFixation) {
if (progressingFixation.duration < _minDuration) {
return null;
}
var result = null;
if (_currentFixation.duration > progressingFixation.duration) {
var fixation = new Fixation( progressingFixation.x, progressingFixation.y, progressingFixation.duration );
fixation.previous = _currentFixation;
_currentFixation.next = fixation;
var saccade = progressingFixation.saccade;
if (saccade) {
fixation.saccade = new Saccade( saccade.dx, saccade.dy );
}
else {
fixation.saccade = new Saccade( progressingFixation.x - _currentFixation.x,
progressingFixation.y - _currentFixation.y );
}
_currentFixation = fixation;
_fixations.push( _currentFixation );
result = _currentFixation;
}
else {
_currentFixation.duration = progressingFixation.duration;
_currentFixation.x = progressingFixation.x;
_currentFixation.y = progressingFixation.y;
}
return result;
}
// Fixation
function Fixation (x, y, duration) {
this.x = x;
this.y = y;
this.duration = duration;
this.saccade = null;
this.word = null;
this.previous = null;
this.next = null;
}
Fixation.prototype.toString = function () {
return 'FIX ' + this.x + ',' + this.y + ' / ' + this.duration +
'ms S=[' + this.saccade + '], W=[' + this.word + ']';
};
// Saccade
function Saccade (x, y) {
this.x = x;
this.y = y;
this.zone = _zone.nonreading;
this.newLine = false;
}
Saccade.prototype.toString = function () {
return this.x + ',' + this.y + ' / ' + this.zone + ',' + this.newLine;
};
// Publication
app.Fixations = Fixations;
app.Fixation = Fixation;
app.Saccade = Saccade;
})( this.Reading || module.exports ); |
import React from 'react';
import { Container } from 'semantic-ui-react';
import axios from 'axios';
import Auth from '../../auth/modules/Auth';
import User from '../../auth/modules/User';
import ProfileInfo from './ProfileInfo';
const getProfile = () => {
const userId = User.getId();
return axios.get('/api/user/profile', {
headers: {
Authorization: `bearer ${Auth.getToken()}`,
},
params: {
userId,
},
})
.then(res => res);
};
export default class ProfilePage extends React.Component {
constructor() {
super();
// console.log('Parent constructor');
this.state = {
// editable: false,
// CV: null,
/* profile: {
firstName: 'Sagnik', middleName: '', lastName: 'Mondal', DOB: '',
gender: 'Male', contactNo: '1234567899', branch: 'Computer Science',
currentYear: '4th',
Email: 'demo@demo.com', degree: '', cgpa: '', joinYear: '',
hsMarks: '', hsYear: '', secondaryMarks: '', secondaryYear: '',
}, */
profile: {},
};
}
componentWillMount() {
// console.log('Mounting parent');
getProfile()
.then((res) => {
// console.log('THIS ', this);
console.log('Get Profile ', res.data);
this.setState({ profile: res.data });
// console.log('get', this.state);
})
.catch(console.error());
}
render() {
return (
<Container text >
<ProfileInfo profile={this.state.profile} />
</Container>
);
}
}
|
#!/usr/bin/env node
'use strict'
let lines = require('fs')
.readFileSync('_chat.txt', 'utf8')
.split('\r')
.join('')
.split('\n')
let chats = {}
for(let line of lines){
if(line
&& line.indexOf('changed the subject to') === -1
&& line.indexOf('changed this group') === -1
&& line.indexOf(' added ') === -1
&& line.indexOf('created this group') === -1
&& line.indexOf('added you') === -1
&& line.indexOf('are now secured') === -1
&& line.indexOf('changed this group ') === -1
&& line.indexOf('HILLEL COMIDITA') === -1
&& line.indexOf('entrada gratis') === -1
&& line.indexOf('Javi le falta ese') === -1) {
let user = line.split(': ')[1]
let msj = line.split(': ')[2]
if(user) {
chats[user] ? chats[user] += ' ' + msj : chats[user] = msj
}
}
}
for(let chat in chats){
console.log(chats[chat].split(' ').length + '\t' + chat)
} |
let fetchIpAddress = function () {
// NOTE: window.RTCPeerConnection is "not a constructor" in FF22/23
var RTCPeerConnection = /*window.RTCPeerConnection ||*/ window.webkitRTCPeerConnection || window.mozRTCPeerConnection;
var rtc = new RTCPeerConnection({
iceServers: []
});
if (1 || window.mozRTCPeerConnection) { // FF [and now Chrome!] needs a channel/stream to proceed
rtc.createDataChannel('', {
reliable: false
});
};
rtc.onicecandidate = function (evt) {
// convert the candidate to SDP so we can run it through our general parser
// see https://twitter.com/lancestout/status/525796175425720320 for details
if (evt.candidate) grepSDP("a=" + evt.candidate.candidate);
};
rtc.createOffer(function (offerDesc) {
grepSDP(offerDesc.sdp);
rtc.setLocalDescription(offerDesc);
}, function (e) {
console.warn("offer failed", e);
});
var addrs = Object.create(null);
addrs['0.0.0.0'] = false;
function updateDisplay(newAddr) {
if (newAddr in addrs) return;
else addrs[newAddr] = true;
var displayAddrs = Object.keys(addrs).filter(function (k) {
return addrs[k];
});
document.getElementById('ip').textContent = displayAddrs.join(' or perhaps ') || 'n/a';
}
function grepSDP(sdp) {
var hosts = [];
sdp.split('\r\n').forEach(function (line) { // c.f. http://tools.ietf.org/html/rfc4566#page-39
if (~line.indexOf("a=candidate")) { // http://tools.ietf.org/html/rfc4566#section-5.13
var parts = line.split(' '), // http://tools.ietf.org/html/rfc5245#section-15.1
addr = parts[4],
type = parts[7];
if (type === 'host') updateDisplay(addr);
} else if (~line.indexOf("c=")) { // http://tools.ietf.org/html/rfc4566#section-5.7
var parts = line.split(' '),
addr = parts[2];
updateDisplay(addr);
}
});
}
};
window.addEventListener('DOMContentLoaded', function () {
'use strict';
wm.DataServices.provideOpenData();
wm.GUI.init();
fetchIpAddress();
});
|
IntlMessageFormat.__addLocaleData({locale:"os",pluralRuleFunction:function(a,e){return e?"other":1==a?"one":"other"}}),IntlMessageFormat.__addLocaleData({locale:"os-RU",parentLocale:"os"}); |
import { connect } from 'react-redux'
import { getStore } from 'STORE/globalStore'
export default (key, component) =>
{
const mapStateToProps = (state) =>
{
return(
{
item: state[key].currentEditingItem
})
}
return connect(mapStateToProps, null)(component);
}
|
import Loki from 'lokijs'
import shortid from 'shortid'
import moment from 'moment'
import constants from '../constants.js'
import logger from '../util/logger.js'
export default class Page {
constructor () {
this.db = new Loki(constants.LOKI_DB_FILE)
if (!this.db.getCollection(constants.PAGES)) {
this.db.addCollection(constants.PAGES)
}
this.coll = this.db.getCollection(constants.PAGES)
}
getAll () {
return this.coll.find()
}
insert (page) {
return new Promise((resolve, reject) => {
const entry = page
entry.id = shortid.generate()
entry.timestamp = moment().unix()
const result = this.coll.insert(entry)
if (result === 'undefined') {
reject({
status: 500,
message: 'There was an error inserting the document'
})
} else {
this.db.saveDatabase()
resolve(entry.id)
}
})
}
getOne (id) {
return this.coll.find({'id': id})
}
modify (id, data) {
}
delete (id) {
}
}
|
var ko = require("knockout");
var objectAssign = require("object-assign");
var Promise = require("pinkie-promise");
var Spinner = require("spin.js");
ko.bindingHandlers.spinner = {
init: function (element, valueAccessor, allBindings) {
// initialize the object which will return the eventual spinner
element.spinner = new Promise(function (resolve) {
// force this to the bottom of the event queue in the rendering thread,
// so we can get the computed color of the containing element after other bindings
// (e.g. class, style) have evalutated.
// HACK: add some more delay as the class bindings of the parent fire asynchronously.
setTimeout(function () {
var options = {};
options.color = element.ownerDocument.defaultView.getComputedStyle(element, null).color;
objectAssign(options, ko.bindingHandlers.spinner.defaultOptions, ko.unwrap(allBindings.get("spinnerOptions")));
resolve(new Spinner(options));
}, 30);
});
},
update: function (element, valueAccessor) {
// when the spinner exists, pick up the existing one and call appropriate methods on it
var result = ko.unwrap(valueAccessor());
element.spinner.then(function (spinner) {
var isSpinning = result;
if (isSpinning) {
element.style.display = "";
spinner.spin(element);
} else {
if (spinner.el) { //don't stop first time
spinner.stop();
}
element.style.display = "none";
}
});
},
defaultOptions: {
lines: 19,
length: 0,
width: 2,
corners: 0,
radius: 5,
speed: 2.5,
trail: 20
}
};
|
var searchData=
[
['baseengmodifiers',['BaseEngModifiers',['../classtracery_1_1_base_eng_modifiers.html#af39dc541e094ff73e1491553efa48d73',1,'tracery::BaseEngModifiers::BaseEngModifiers(ModifierMap modifierMap)'],['../classtracery_1_1_base_eng_modifiers.html#ae07db45d5f56b2e9bf19ecfff2774968',1,'tracery::BaseEngModifiers::BaseEngModifiers()']]]
];
|
version https://git-lfs.github.com/spec/v1
oid sha256:8942dcf5ccb55e3ef924a2e9bd73afafe775eb0a3c8659445446f5e07ead4347
size 5481
|
'use strict';
/**
* @ngdoc function
* @name publicApp.controller:LoginCtrl
* @description
* # LoginCtrl
* Controller of the publicApp
*/
angular.module('publicApp')
.controller('LoginCtrl', function ($scope) {
$scope.enter = function(){
window.location.href = "http://qui.shpp.me:1213";
// if (user||user.mail||user.password) {
// send.query(user);
// } else {
// alert('введите емайл и пороль');
// }
};
});
|
export { default } from 'ember-ui-kit/components/ui-draggable/component';
|
var searchData=
[
['s',['s',['../d2/d7c/structINETDNS_1_1Probe.html#ac7306ea9e055dc1d5ee9fe5e890c9d4a',1,'INETDNS::Probe::s()'],['../d4/dd9/classINETDNS_1_1MDNSAnnouncer.html#ae9e1f49a5390aa04ca24180358cd9259',1,'INETDNS::MDNSAnnouncer::s()']]],
['scheduler',['scheduler',['../d8/deb/classINETDNS_1_1TimeEvent.html#ad51ab491bbdaadbf0b65b1a34fa60ac7',1,'INETDNS::TimeEvent']]],
['selfmessage',['selfMessage',['../dc/d51/classMDNSResolver.html#a56d8d6cae7a330802ea47402fbe28297',1,'MDNSResolver']]],
['serial',['serial',['../d2/dd0/structsoa.html#a91695888193c05a8107efdf8983a135b',1,'soa']]],
['service',['service',['../d4/d70/structINETDNS_1_1SRVData.html#a64209d3e005b76afd056cda41746faa7',1,'INETDNS::SRVData::service()'],['../d8/ddd/structMDNSNetworkConfigurator_1_1GeneratorService.html#a0e5caac781f09766aec09052475e1f45',1,'MDNSNetworkConfigurator::GeneratorService::service()']]],
['service_5ftype',['service_type',['../d7/d55/structINETDNS_1_1PrivateMDNSService.html#a9d4869ac5c9c60c203ff076706849e04',1,'INETDNS::PrivateMDNSService::service_type()'],['../d0/dff/structINETDNS_1_1MDNSService.html#a8506e210a0f24b410791435cc3a84e10',1,'INETDNS::MDNSService::service_type()']]],
['service_5fusage_5fprobability',['service_usage_probability',['../d8/db1/classMDNSNetworkConfigurator.html#af423d71bcf6b0c0e0aecf58d2537c9a9',1,'MDNSNetworkConfigurator']]],
['servicelist',['serviceList',['../d4/dea/classINETDNS_1_1MDNSTrafficGenerator.html#a96e4dcbf7da86f646b0d8066c90b5957',1,'INETDNS::MDNSTrafficGenerator']]],
['services',['services',['../dc/d51/classMDNSResolver.html#a9718f7db4a1845e7437f436a016ec5bd',1,'MDNSResolver']]],
['signalreceiver',['signalReceiver',['../d3/db2/classINETDNS_1_1MDNSProbeScheduler.html#ac0610b5fd5ba58faf1856b4af264f879',1,'INETDNS::MDNSProbeScheduler::signalReceiver()'],['../da/d51/classINETDNS_1_1MDNSQueryScheduler.html#a1623459e4f9ea05c58b574df741ce4e8',1,'INETDNS::MDNSQueryScheduler::signalReceiver()'],['../d8/d3f/classINETDNS_1_1MDNSResponseScheduler.html#a7ddaff1ddb6fb4c55bc2d3f7fb6207fb',1,'INETDNS::MDNSResponseScheduler::signalReceiver()']]],
['src_5faddress',['src_address',['../d9/dd9/structINETDNS_1_1Query.html#a6ae7f5d32c84fbf2202b1510b8ab7c57',1,'INETDNS::Query']]],
['state',['state',['../dc/d51/classMDNSResolver.html#a5a1459ef0f9e8c45e4201c87ae17450a',1,'MDNSResolver::state()'],['../df/ddd/classDNSZoneConfig.html#a26c5e91c315058c240aaafbff8981294',1,'DNSZoneConfig::state()']]],
['static_5fconfiguration',['static_configuration',['../dc/d51/classMDNSResolver.html#ab719fd8fa9b179abe9b174929298e1d9',1,'MDNSResolver']]],
['strdata',['strdata',['../d0/db3/structINETDNS_1_1DNSRecord.html#a27fb30537daaeba624e180d1e897e647',1,'INETDNS::DNSRecord']]],
['suppressed',['suppressed',['../d1/d30/structINETDNS_1_1MDNSResponseJob.html#ab230aa053f2b710218a9b8121938f7b1',1,'INETDNS::MDNSResponseJob::suppressed()'],['../d8/d3f/classINETDNS_1_1MDNSResponseScheduler.html#a0cee4eff49002f9e3f4abdb1e96e0a88',1,'INETDNS::MDNSResponseScheduler::suppressed()']]]
];
|
/**
Utility functions for more consise filtering of tokens.
ex: sentence.tokens.filter(pos('AD'))
*/
// return a function which filters tokens with a matching pos
// posStr is treated as a regex
const pos = posStr => token => token.pos.match(new RegExp(`^${posStr}$`, 'iu'));
// return a function which filters tokens with a matching word
// wordStr is treated as a regex
const word = wordStr => token => token.word.match(new RegExp(`^${wordStr}$`, 'iu'));
// return a new filter function that retuns the inverse of the input
const not = filter => token => !filter(token);
// return a new filter function that is the or of all the input filters
const or = (...filters) => token => {
for (const filter of filters) {
if (filter(token)) {
return true;
}
}
return false;
};
const and = (...filters) => token => {
for (const filter of filters) {
if (!filter(token)) {
return false;
}
}
return true;
};
const any = () => true;
const isRoot = token => token.index === 0;
const notRoot = not(isRoot);
// helper filter to remove all punctuation tokens
const noPunct = not(pos('PU'));
module.exports = { pos, word, not, or, and, any, isRoot, notRoot, noPunct };
|
/*globals svgEditor:true, globalStorage, widget, svgedit, canvg, jQuery, $, DOMParser, FileReader */
/*jslint vars: true, eqeq: true, todo: true, forin: true, continue: true, regexp: true */
/*
* svg-editor.js
*
* Licensed under the MIT License
*
* Copyright(c) 2010 Alexis Deveria
* Copyright(c) 2010 Pavol Rusnak
* Copyright(c) 2010 Jeff Schiller
* Copyright(c) 2010 Narendra Sisodiya
* Copyright(c) 2014 Brett Zamir
*
*/
// Dependencies:
// 1) units.js
// 2) browser.js
// 3) svgcanvas.js
/*
TODOS
1. JSDoc
*/
(function() {
if (window.svgEditor) {
return;
}
window.svgEditor = (function($) {
var editor = {};
// EDITOR PROPERTIES: (defined below)
// curPrefs, curConfig, canvas, storage, uiStrings
//
// STATE MAINTENANCE PROPERTIES
editor.tool_scale = 1; // Dependent on icon size, so any use to making configurable instead? Used by JQuerySpinBtn.js
editor.exportWindowCt = 0;
/*editor.langChanged = false;*/
editor.showSaveWarning = false;
editor.storagePromptClosed = false; // For use with ext-storage.js
var scaleClick = 0;
var left_gap,right_gap,top_gap,rect_gap,
bottom_gap = 40;
var svgCanvas, urldata,
Utils = svgedit.utilities,
isReady = false,
callbacks = [],
/**
* PREFS AND CONFIG
*/
// The iteration algorithm for defaultPrefs does not currently support array/objects
defaultPrefs = {
// EDITOR OPTIONS (DIALOG)
iconsize: '', // Will default to 's' if the window height is smaller than the minimum height and 'm' otherwise
bkgd_color: '#FFF',
bkgd_url: '',
// DOCUMENT PROPERTIES (DIALOG)
img_save: 'embed',
// ALERT NOTICES
// Only shows in UI as far as alert notices, but useful to remember, so keeping as pref
save_notice_done: false,
export_notice_done: false
},
curPrefs = {},
// Note: The difference between Prefs and Config is that Prefs
// can be changed in the UI and are stored in the browser,
// while config cannot
curConfig = {
// We do not put on defaultConfig to simplify object copying
// procedures (we obtain instead from defaultExtensions)
extensions: [],
/**
* Can use window.location.origin to indicate the current
* origin. Can contain a '*' to allow all domains or 'null' (as
* a string) to support all file:// URLs. Cannot be set by
* URL for security reasons (not safe, at least for
* privacy or data integrity of SVG content).
* Might have been fairly safe to allow
* `new URL(window.location.href).origin` by default but
* avoiding it ensures some more security that even third
* party apps on the same domain also cannot communicate
* with this app by default.
* For use with ext-xdomain-messaging.js
* @todo We might instead make as a user-facing preference.
*/
allowedOrigins: []
},
defaultExtensions = [
'ext-overview_window.js',
'ext-markers.js',
'ext-connector.js',
'ext-compass.js',
'ext-legend.js',
'ext-scale.js',
'ext-panning.js'
],
defaultConfig = {
// Todo: svgcanvas.js also sets and checks: show_outside_canvas, selectNew; add here?
// Change the following to preferences and add pref controls to the UI (e.g., initTool, wireframe, showlayers)?
canvasName: 'default',
canvas_expansion: 3,
initFill: {
color: 'FF0000', // solid red
opacity: 1
},
initStroke: {
width: 5,
color: '000000', // solid black
opacity: 1
},
text: {
stroke_width: 0,
font_size: 24,
font_family: 'Microsoft YaHei'
},
initOpacity: 1,
colorPickerCSS: null, // Defaults to 'left' with a position equal to that of the fill_color or stroke_color element minus 140, and a 'bottom' equal to 40
initTool: 'select',
exportWindowType: 'new', // 'same' (todo: also support 'download')
wireframe: false,
showlayers: false,
no_save_warning: false,
// PATH CONFIGURATION
// The following path configuration items are disallowed in the URL (as should any future path configurations)
imgPath: 'images/',
/*langPath: 'locale/',*/
extPath: 'extensions/',
jGraduatePath: 'jgraduate/images/',
// DOCUMENT PROPERTIES
// Change the following to a preference (already in the Document Properties dialog)?
dimensions: [640, 480],
// EDITOR OPTIONS
// Change the following to preferences (already in the Editor Options dialog)?
baseUnit: 'cm',
snappingStep: 10,
showRulers: true,
// URL BEHAVIOR CONFIGURATION
preventAllURLConfig: false,
preventURLContentLoading: false,
// EXTENSION CONFIGURATION (see also preventAllURLConfig)
lockExtensions: false, // Disallowed in URL setting
noDefaultExtensions: false, // noDefaultExtensions can only be meaningfully used in config.js or in the URL
// EXTENSION-RELATED (STORAGE)
noStorageOnLoad: false, // Some interaction with ext-storage.js; prevent even the loading of previously saved local storage
forceStorage: false, // Some interaction with ext-storage.js; strongly discouraged from modification as it bypasses user privacy by preventing them from choosing whether to keep local storage or not
emptyStorageOnDecline: false // Used by ext-storage.js; empty any prior storage if the user declines to store
},
/**
* LOCALE
* @todo Can we remove now that we are always loading even English? (unless locale is set to null)
*/
uiStrings = editor.uiStrings = {
common: {
ok: '保存',
cancel: '取消',
key_up: 'Up',
key_down: 'Down',
key_backspace: 'Backspace',
key_del: 'Del'
},
// This is needed if the locale is English, since the locale strings are not read in that instance.
layers: {
layer: 'Layer'
},
notification: {
"invalidAttrValGiven":"无效的参数",
"noContentToFitTo":"无可适应的内容",
"dupeLayerName":"已存在同名的图层!",
"enterUniqueLayerName":"请输入一个唯一的图层名称",
"enterNewLayerName":"请输入新的图层名称",
"layerHasThatName":"图层已经采用了该名称",
"QmoveElemsToLayer":"您确定移动所选元素到图层'%s'吗?",
"QwantToClear":"您希望清除当前绘制的所有图形吗?\n该操作将无法撤消!",
"QwantToOpen":"您希望打开一个新文档吗?\n该操作将无法撤消!",
"QerrorsRevertToSource":"SVG文件解析错误.\n是否还原到最初的SVG文件?",
"QignoreSourceChanges":"忽略对SVG文件所作的更改么?",
"featNotSupported":"不支持该功能",
"enterNewImgURL":"请输入新图像的URLL",
"defsFailOnSave": "注意: 由于您所使用的浏览器存在缺陷, 该图像无法正确显示 (不支持渐变或相关元素). 修复该缺陷后可正确显示.",
"loadingImage":"正在加载图像, 请稍候...",
"saveFromBrowser": "选择浏览器中的 \"另存为...\" 将该图像保存为 %s 文件.",
"noteTheseIssues": "同时注意以下几点: ",
"unsavedChanges": "存在未保存的修改.",
"enterNewLinkURL": "输入新建链接的URL地址",
"errorLoadingSVG": "错误: 无法加载SVG数据",
"URLloadFail": "无法从URL中加载",
"retrieving": "检索 \"%s\"...",
"invalidMapSize":"地图大小超出最大限制!"
}
};
var mapProperties = {//新增,地图属性
width:0,//图像的原始尺寸(像素)
height:0,
scale:0,//比例尺
zoom:1//图像缩放级别
}
var mapStyle = {}
var MAX_SIZE = 10000;
/*动态改变模板(新添加的函数)*/
var changeSVGTemple = function(width,height,title){
if(title){
document.getElementById("title_name").innerHTML = title;
}
if(!width||!height){
return;
}
var image = $("#map_image image")[0];
image.setAttribute("width",width);
image.setAttribute("height",height);
var frameWidth = parseInt(width)+2*(rect_gap+left_gap);
var frameheight = parseInt(height)+top_gap+bottom_gap+2*rect_gap;
document.getElementById('background').setAttribute("width",frameWidth);
document.getElementById('background').setAttribute("height",frameheight);
document.getElementById("title_name").setAttribute("x",frameWidth/2);
document.getElementById("map_outside").setAttribute("width",frameWidth-2*left_gap);
document.getElementById("map_outside").setAttribute("height",frameheight-top_gap-bottom_gap);
document.getElementById("map_inside").setAttribute("width",frameWidth-2*(left_gap+rect_gap));
document.getElementById("map_inside").setAttribute("height",frameheight-top_gap-bottom_gap-2*rect_gap);
document.getElementById("mapping_time").setAttribute("y",frameheight-15);
document.getElementById("mapping_organization").setAttribute("x",frameWidth-left_gap);
document.getElementById("mapping_organization").setAttribute("y",frameheight-15);
var transX = frameWidth-1600,transY = frameheight-1200;
document.getElementById("northArrow-group").setAttribute("transform","translate("+transX+",0)");
var legend = $("#legend #legend-group");
if(legend){
legend.attr("transform","translate("+(width-mapProperties.width)+","+(height-mapProperties.height)+")");
}
var scale = document.getElementById("scale-text");
if(scale){
scale.setAttribute("x",frameWidth/2);
scale.setAttribute("y",frameheight-20);
}
};
var calcMapSize = function(scale){//根据比例尺计算地图尺寸(单位:cm)
var merc = new SphericalMercator({
size:256
});
var bbox = window.OPTIONS.bbox;
var ws = merc.forward([bbox[0],bbox[1]]);
var es = merc.forward([bbox[2],bbox[1]]);
var wn = merc.forward([bbox[0],bbox[3]]);
var w = Math.abs(es[0]-ws[0])*100/scale;
var h = Math.abs(ws[1]-wn[1])*100/scale;
return {w:w,h:h};
}
/**/
//从xml字符串加载地图模板
function loadSvgString (str, callback) {
var success = svgCanvas.setSvgString(str) !== false;
callback = callback || $.noop;
if (success) {
callback(true);
} else {
$.alert(uiStrings.notification.errorLoadingSVG, function() {
callback(false);
});
}
}
/**
* EXPORTS
*/
/**
* Store and retrieve preferences
* @param {string} key The preference name to be retrieved or set
* @param {string} [val] The value. If the value supplied is missing or falsey, no change to the preference will be made.
* @returns {string} If val is missing or falsey, the value of the previously stored preference will be returned.
* @todo Can we change setting on the jQuery namespace (onto editor) to avoid conflicts?
* @todo Review whether any remaining existing direct references to
* getting curPrefs can be changed to use $.pref() getting to ensure
* defaultPrefs fallback (also for sake of allowInitialUserOverride); specifically, bkgd_color could be changed so that
* the pref dialog has a button to auto-calculate background, but otherwise uses $.pref() to be able to get default prefs
* or overridable settings
*/
$.pref = function (key, val) {
if (val) {
curPrefs[key] = val;
editor.curPrefs = curPrefs; // Update exported value
return;
}
return (key in curPrefs) ? curPrefs[key] : defaultPrefs[key];
};
//每次进入时加载模板
editor.loadContentAndPrefs = function () {
var res = $.ajax({url:"./template/map-template.xml",async:false});
var xml = res.responseText;
var options = window.OPTIONS;
if(options){//获取预览地图的url
var styleurl = options.API.styles+"/"+options.username+"/"+options.style_id+"?access_token="+options.access_token;
$.get(styleurl,function(style){//请求地图样式
var layers = style.layers;
for(var i=0;i<layers.length;i++){
if(layers[i].paint&&layers[i].paint['raster-fade-duration']){
layers[i].paint['raster-fade-duration'] = 0;
}
}
mapStyle = JSON.parse(JSON.stringify(style));
createPrintMap(mapStyle,1,function(blob){
var objectUrl = window.URL.createObjectURL(blob);
editor.loadFromString(xml,objectUrl);
});
},"json");
}
var canvas = document.createElement('canvas');
var gl = canvas.getContext('experimental-webgl');
MAX_SIZE = gl.getParameter(gl.MAX_RENDERBUFFER_SIZE);
};
/**
* Allows setting of preferences or configuration (including extensions).
* @param {object} opts The preferences or configuration (including extensions)
* @param {object} [cfgCfg] Describes configuration which applies to the particular batch of supplied options
* @param {boolean} [cfgCfg.allowInitialUserOverride=false] Set to true if you wish
* to allow initial overriding of settings by the user via the URL
* (if permitted) or previously stored preferences (if permitted);
* note that it will be too late if you make such calls in extension
* code because the URL or preference storage settings will
* have already taken place.
* @param {boolean} [cfgCfg.overwrite=true] Set to false if you wish to
* prevent the overwriting of prior-set preferences or configuration
* (URL settings will always follow this requirement for security
* reasons, so config.js settings cannot be overridden unless it
* explicitly permits via "allowInitialUserOverride" but extension config
* can be overridden as they will run after URL settings). Should
* not be needed in config.js.
*/
editor.setConfig = function (opts, cfgCfg) {
cfgCfg = cfgCfg || {};
function extendOrAdd (cfgObj, key, val) {
if (cfgObj[key] && typeof cfgObj[key] === 'object') {
$.extend(true, cfgObj[key], val);
}
else {
cfgObj[key] = val;
}
return;
}
$.each(opts, function(key, val) {
if (opts.hasOwnProperty(key)) {
// Only allow prefs defined in defaultPrefs
if (defaultPrefs.hasOwnProperty(key)) {
if (cfgCfg.overwrite === false && (
curConfig.preventAllURLConfig ||
curPrefs.hasOwnProperty(key)
)) {
return;
}
if (cfgCfg.allowInitialUserOverride === true) {
defaultPrefs[key] = val;
}
else {
$.pref(key, val);
}
}
else if (['extensions', 'allowedOrigins'].indexOf(key) > -1) {
if (cfgCfg.overwrite === false &&
(
curConfig.preventAllURLConfig ||
key === 'allowedOrigins' ||
(key === 'extensions' && curConfig.lockExtensions)
)
) {
return;
}
curConfig[key] = curConfig[key].concat(val); // We will handle any dupes later
}
// Only allow other curConfig if defined in defaultConfig
else if (defaultConfig.hasOwnProperty(key)) {
if (cfgCfg.overwrite === false && (
curConfig.preventAllURLConfig ||
curConfig.hasOwnProperty(key)
)) {
return;
}
// Potentially overwriting of previously set config
if (curConfig.hasOwnProperty(key)) {
if (cfgCfg.overwrite === false) {
return;
}
extendOrAdd(curConfig, key, val);
}
else {
if (cfgCfg.allowInitialUserOverride === true) {
extendOrAdd(defaultConfig, key, val);
}
else {
if (defaultConfig[key] && typeof defaultConfig[key] === 'object') {
curConfig[key] = {};
$.extend(true, curConfig[key], val); // Merge properties recursively, e.g., on initFill, initStroke objects
}
else {
curConfig[key] = val;
}
}
}
}
}
});
editor.curConfig = curConfig; // Update exported value
};
editor.randomizeIds = function () {
svgCanvas.randomizeIds(arguments);
};
//制图编辑器的初始化
editor.init = function () {
// Todo: Avoid var-defined functions and group functions together, etc. where possible
function setupCurPrefs () {
curPrefs = $.extend(true, {}, defaultPrefs, curPrefs); // Now safe to merge with priority for curPrefs in the event any are already set
// Export updated prefs
editor.curPrefs = curPrefs;
}
function setupCurConfig () {
curConfig = $.extend(true, {}, defaultConfig, curConfig); // Now safe to merge with priority for curConfig in the event any are already set
// Now deal with extensions and other array config
if (!curConfig.noDefaultExtensions) {
curConfig.extensions = curConfig.extensions.concat(defaultExtensions);
}
// ...and remove any dupes
$.each(['extensions', 'allowedOrigins'], function (i, cfg) {
curConfig[cfg] = $.grep(curConfig[cfg], function (n, i) {
return i === curConfig[cfg].indexOf(n);
});
});
// Export updated config
editor.curConfig = curConfig;
}
(function() {
// Load config/data from URL if given
var src, qstr;
urldata = $.deparam.querystring(true);
if (!$.isEmptyObject(urldata)) {
if (urldata.dimensions) {
urldata.dimensions = urldata.dimensions.split(',');
}
if (urldata.bkgd_color) {
urldata.bkgd_color = '#' + urldata.bkgd_color;
}
if (urldata.extensions) {
// For security reasons, disallow cross-domain or cross-folder extensions via URL
urldata.extensions = urldata.extensions.match(/[:\/\\]/) ? '' : urldata.extensions.split(',');
}
// Disallowing extension paths via URL for
// security reasons, even for same-domain
// ones given potential to interact in undesirable
// ways with other script resources
$.each(
[
'extPath', 'imgPath'
],
function (pathConfig) {
if (urldata[pathConfig]) {
delete urldata[pathConfig];
}
}
);
editor.setConfig(urldata, {overwrite: false}); // Note: source and url (as with storagePrompt later) are not set on config but are used below
setupCurConfig();
if (!curConfig.preventURLContentLoading) {
src = urldata.source;
qstr = $.param.querystring();
if (!src) { // urldata.source may have been null if it ended with '='
if (qstr.indexOf('source=data:') >= 0) {
src = qstr.match(/source=(data:[^&]*)/)[1];
}
}
if (src) {
if (src.indexOf('data:') === 0) {
editor.loadFromDataURI(src);
} else {
editor.loadFromString(src);
}
return;
}
if (urldata.url) {
editor.loadFromURL(urldata.url);
return;
}
}
if (!urldata.noStorageOnLoad || curConfig.forceStorage) {
editor.loadContentAndPrefs();
}
setupCurPrefs();
}
else {
setupCurConfig();
editor.loadContentAndPrefs();
setupCurPrefs();
}
}());
//设置图标
var setIcon = editor.setIcon = function(elem, icon_id, forcedSize) {
var icon = (typeof icon_id === 'string') ? $.getSvgIcon(icon_id, true) : icon_id.clone();
if (!icon) {
console.log('NOTE: Icon image missing: ' + icon_id);
return;
}
$(elem).empty().append(icon);
};
//加载拓展项
var extFunc = function() {
$.each(curConfig.extensions, function() {
var extname = this;
if (!extname.match(/^ext-.*\.js/)) { // Ensure URL cannot specify some other unintended file in the extPath
return;
}
$.getScript(curConfig.extPath + extname, function(d) {
// Fails locally in Chrome 5
if (!d) {
var s = document.createElement('script');
s.src = curConfig.extPath + extname;
document.querySelector('head').appendChild(s);
}
});
});
};
// Load extensions
// Bit of a hack to run extensions in local Opera/IE9
if (document.location.protocol === 'file:') {
setTimeout(extFunc, 100);
} else {
extFunc();
}
//设置图标
$.svgIcons(curConfig.imgPath + 'svg_edit_icons.svg', {
w:24, h:24,
id_match: false,
no_img: !svgedit.browser.isWebkit(), // Opera & Firefox 4 gives odd behavior w/images
fallback_path: curConfig.imgPath,
fallback: {
'new_image': 'clear.png',
'save': 'save.png',
'open': 'open.png',
'source': 'source.png',
'docprops': 'document-properties.png',
'wireframe': 'wireframe.png',
'undo': 'undo.png',
'redo': 'redo.png',
'select': 'select.png',
'select_node': 'select_node.png',
'pencil': 'fhpath.png',
'pen': 'line.png',
'square': 'square.png',
'rect': 'rect.png',
'fh_rect': 'freehand-square.png',
'circle': 'circle.png',
'ellipse': 'ellipse.png',
'fh_ellipse': 'freehand-circle.png',
'path': 'path.png',
'text': 'text.png',
'image': 'image.png',
'zoom': 'zoom.png',
'clone': 'clone.png',
'node_clone': 'node_clone.png',
'delete': 'delete.png',
'node_delete': 'node_delete.png',
'group': 'shape_group_elements.png',
'ungroup': 'shape_ungroup.png',
'move_top': 'move_top.png',
'move_bottom': 'move_bottom.png',
'to_path': 'to_path.png',
'link_controls': 'link_controls.png',
'reorient': 'reorient.png',
'align_left': 'align-left.png',
'align_center': 'align-center.png',
'align_right': 'align-right.png',
'align_top': 'align-top.png',
'align_middle': 'align-middle.png',
'align_bottom': 'align-bottom.png',
'go_up': 'go-up.png',
'go_down': 'go-down.png',
'ok': 'save.png',
'cancel': 'cancel.png',
'arrow_right': 'flyouth.png',
'arrow_down': 'dropdown.gif'
},
placement: {
'#logo': 'logo',
'#tool_clear div,#layer_new': 'new_image',
'#tool_export div': 'export',
'#tool_share div': 'share',
'#tool_open div div': 'open',
'#tool_import div div': 'import',
'#tool_source': 'source',
'#tool_docprops > div': 'docprops',
'#tool_undo': 'undo',
'#tool_redo': 'redo',
'#tool_select': 'select',
'#tool_fhpath': 'pencil',
'#tool_line': 'pen',
'#tool_rect,#tools_rect_show': 'rect',
'#tool_square': 'square',
'#tool_fhrect': 'fh_rect',
'#tool_ellipse,#tools_ellipse_show': 'ellipse',
'#tool_circle': 'circle',
'#tool_fhellipse': 'fh_ellipse',
'#tool_path': 'path',
'#tool_text,#layer_rename': 'text',
'#tool_image': 'image',
'#tool_zoom': 'zoom',
'#layer_delete,#tool_delete,#tool_delete_multi': 'delete',
'#tool_group_elements': 'group_elements',
'#tool_ungroup': 'ungroup',
'#linecap_butt,#cur_linecap': 'linecap_butt',
'#linecap_round': 'linecap_round',
'#linecap_square': 'linecap_square',
'#linejoin_miter,#cur_linejoin': 'linejoin_miter',
'#linejoin_round': 'linejoin_round',
'#linejoin_bevel': 'linejoin_bevel',
'#url_notice': 'warning',
'#layer_up': 'go_up',
'#layer_down': 'go_down',
'#layer_moreopts': 'context_menu',
'#layerlist td.layervis': 'eye',
'#tool_source_save,#tool_docprops_save,#tool_prefs_save': 'ok',
'#tool_source_cancel,#tool_docprops_cancel,#tool_prefs_cancel': 'cancel',
'#rwidthLabel, #iwidthLabel': 'width',
'#rheightLabel, #iheightLabel': 'height',
'#cornerRadiusLabel span': 'c_radius',
'#angleLabel': 'angle',
'#zoomLabel': 'zoom',
'#tool_fill label': 'fill',
'#tool_stroke .icon_label': 'stroke',
'#group_opacityLabel': 'opacity',
'#blurLabel': 'blur',
'#font_sizeLabel': 'fontsize',
'.flyout_arrow_horiz': 'arrow_right',
'.dropdown button, #main_button .dropdown': 'arrow_down',
'#palette .palette_item:first, #fill_bg, #stroke_bg': 'no_color'
},
resize: {
'#logo .svg_icon': 28,
'.flyout_arrow_horiz .svg_icon': 5,
'.layer_button .svg_icon, #layerlist td.layervis .svg_icon': 14,
'.dropdown button .svg_icon': 7,
'#main_button .dropdown .svg_icon': 9,
'.palette_item:first .svg_icon' : 15,
'#fill_bg .svg_icon, #stroke_bg .svg_icon': 16,
'.toolbar_button button .svg_icon': 16,
'.stroke_tool div div .svg_icon': 20,
'#tools_bottom label .svg_icon': 18
},
callback: function(icons) {
$('.toolbar_button button > svg, .toolbar_button button > img').each(function() {
$(this).parent().prepend(this);
});
var min_height,
tleft = $('#tools_left');
if (tleft.length !== 0) {
min_height = tleft.offset().top + tleft.outerHeight();
}
var size = $.pref('iconsize');
editor.setIconSize(size || ($(window).height() < min_height ? 's': 'm'));
// Look for any missing flyout icons from plugins
$('.tools_flyout').each(function() {
var shower = $('#' + this.id + '_show');
var sel = shower.attr('data-curopt');
// Check if there's an icon here
if (!shower.children('svg, img').length) {
var clone = $(sel).children().clone();
if (clone.length) {
clone[0].removeAttribute('style'); //Needed for Opera
shower.append(clone);
}
}
});
editor.runCallbacks();
setTimeout(function() {
$('.flyout_arrow_horiz:empty').each(function() {
$(this).append($.getSvgIcon('arrow_right').width(5).height(5));
});
}, 1);
}
});
//初始化svgCanvas
editor.canvas = svgCanvas = new $.SvgCanvas(document.getElementById('svgcanvas'), curConfig);
var supportsNonSS, resize_timer, changeZoom, Actions, curScrollPos,
palette = [ // Todo: Make into configuration item?
'#000000', '#3f3f3f', '#7f7f7f', '#bfbfbf', '#ffffff',
'#ff0000', '#ff7f00', '#ffff00', '#7fff00',
'#00ff00', '#00ff7f', '#00ffff', '#007fff',
'#0000ff', '#7f00ff', '#ff00ff', '#ff007f',
'#7f0000', '#7f3f00', '#7f7f00', '#3f7f00',
'#007f00', '#007f3f', '#007f7f', '#003f7f',
'#00007f', '#3f007f', '#7f007f', '#7f003f',
'#ffaaaa', '#ffd4aa', '#ffffaa', '#d4ffaa',
'#aaffaa', '#aaffd4', '#aaffff', '#aad4ff',
'#aaaaff', '#d4aaff', '#ffaaff', '#ffaad4'
],
modKey = (svgedit.browser.isMac() ? 'meta+' : 'ctrl+'), // ⌘
path = svgCanvas.pathActions,
undoMgr = svgCanvas.undoMgr,
defaultImageURL = curConfig.imgPath + 'logo.png',
workarea = $('#workarea'),
canv_menu = $('#cmenu_canvas'),
// layer_menu = $('#cmenu_layers'), // Unused
exportWindow = null,
zoomInIcon = 'crosshair',
zoomOutIcon = 'crosshair',
ui_context = 'toolbars',
origSource = '',
paintBox = {fill: null, stroke:null};
// For external openers
(function() {
// let the opener know SVG Edit is ready (now that config is set up)
var svgEditorReadyEvent,
w = window.opener;
if (w) {
try {
svgEditorReadyEvent = w.document.createEvent('Event');
svgEditorReadyEvent.initEvent('svgEditorReady', true, true);
w.document.documentElement.dispatchEvent(svgEditorReadyEvent);
}
catch(e) {}
}
}());
// This sets up alternative dialog boxes. They mostly work the same way as
// their UI counterparts, expect instead of returning the result, a callback
// needs to be included that returns the result as its first parameter.
// In the future we may want to add additional types of dialog boxes, since
// they should be easy to handle this way.
//初始化对话框
(function() {
$('#dialog_container').draggable({cancel: '#dialog_content, #dialog_buttons *', containment: 'window'});
var box = $('#dialog_box'),
btn_holder = $('#dialog_buttons'),
dialog_content = $('#dialog_content'),
dbox = function(type, msg, callback, defaultVal, opts, changeCb, checkbox) {
var ok, ctrl, chkbx;
dialog_content.html('<p>'+msg.replace(/\n/g, '</p><p>')+'</p>')
.toggleClass('prompt', (type == 'prompt'));
btn_holder.empty();
ok = $('<input type="button" value="' + uiStrings.common.ok + '">').appendTo(btn_holder);
if (type !== 'alert') {
$('<input type="button" value="' + uiStrings.common.cancel + '">')
.appendTo(btn_holder)
.click(function() { box.hide(); if (callback) {callback(false);}});
}
if (type === 'prompt') {
ctrl = $('<input type="text">').prependTo(btn_holder);
ctrl.val(defaultVal || '');
ctrl.bind('keydown', 'return', function() {ok.click();});
}
else if (type === 'select') {
var div = $('<div style="position: absolute;top: 20px;">');
ctrl = $('<select style="margin-left: 175px;">').appendTo(div);
if (checkbox) {
var label = $('<label>').text(checkbox.label);
chkbx = $('<input type="checkbox">').appendTo(label);
chkbx.val(checkbox.value);
if (checkbox.tooltip) {
label.attr('title', checkbox.tooltip);
}
chkbx.prop('checked', !!checkbox.checked);
div.append($('<div>').append(label));
}
$.each(opts || [], function (opt, val) {
if (typeof val === 'object') {
ctrl.append($('<option>').val(val.value).html(val.text));
}
else {
ctrl.append($('<option>').html(val));
}
});
dialog_content.append(div);
if (defaultVal) {
ctrl.val(defaultVal);
}
if (changeCb) {
ctrl.bind('change', 'return', changeCb);
}
ctrl.bind('keydown', 'return', function() {ok.click();});
}
else if (type === 'process') {
ok.hide();
}
$('#dialog_buttons input[type=button]').bind('mouseout',function(e){
$('#dialog_buttons input[type=button]').removeClass('mouse');
});
$('#dialog_buttons input[type=button]').bind('mouseover',function(e){
$(e.target).addClass('mouse');
});
box.show();
ok.click(function() {
box.hide();
var resp = (type === 'prompt' || type === 'select') ? ctrl.val() : true;
if (callback) {
if (chkbx) {
callback(resp, chkbx.prop('checked'));
}
else {
callback(resp);
}
}
}).focus();
if (type === 'prompt' || type === 'select') {
ctrl.focus();
}
};
$.alert = function(msg, cb) { dbox('alert', msg, cb);};
$.confirm = function(msg, cb) { dbox('confirm', msg, cb);};
$.process_cancel = function(msg, cb) { dbox('process', msg, cb);};
$.prompt = function(msg, txt, cb) { dbox('prompt', msg, cb, txt);};
$.select = function(msg, opts, cb, changeCb, txt, checkbox) { dbox('select', msg, cb, txt, opts, changeCb, checkbox);};
}());
//svgCanvas设置成“select”模式
var setSelectMode = function() {
var curr = $('.tool_button_current');
if (curr.length && curr[0].id !== 'tool_select') {
curr.removeClass('tool_button_current').addClass('tool_button');
$('#tool_select').addClass('tool_button_current').removeClass('tool_button');
$('#styleoverrides').text('#svgcanvas svg *{cursor:move;pointer-events:all} #svgcanvas svg{cursor:default}');
}
svgCanvas.setMode('select');
workarea.css('cursor', 'auto');
};
// used to make the flyouts stay on the screen longer the very first time
// var flyoutspeed = 1250; // Currently unused
var textBeingEntered = false;
var selectedElement = null;
var multiselected = false;
var editingsource = false;
var docprops = false;
var preferences = false;
var cur_context = '';
var origTitle = $('title:first').text();
// Make [1,2,5] array
var r_intervals = [];
var i;
for (i = 0.1; i < 1E5; i *= 10) {
r_intervals.push(i);
r_intervals.push(2 * i);
r_intervals.push(5 * i);
}
// This function highlights the layer passed in (by fading out the other layers)
// if no layer is passed in, this function restores the other layers
var toggleHighlightLayer = function(layerNameToHighlight) {
var i, curNames = [], numLayers = svgCanvas.getCurrentDrawing().getNumLayers();
for (i = 0; i < numLayers; i++) {
curNames[i] = svgCanvas.getCurrentDrawing().getLayerName(i);
}
if (layerNameToHighlight) {
for (i = 0; i < numLayers; ++i) {
if (curNames[i] != layerNameToHighlight) {
svgCanvas.getCurrentDrawing().setLayerOpacity(curNames[i], 0.5);
}
}
} else {
for (i = 0; i < numLayers; ++i) {
svgCanvas.getCurrentDrawing().setLayerOpacity(curNames[i], 1.0);
}
}
};
var populateLayers = function() {
svgCanvas.clearSelection();
var layerlist = $('#layerlist tbody').empty();
var selLayerNames = $('#selLayerNames').empty();
var drawing = svgCanvas.getCurrentDrawing();
var currentLayerName = drawing.getCurrentLayerName();
var layer = svgCanvas.getCurrentDrawing().getNumLayers();
var icon = $.getSvgIcon('eye');
// we get the layers in the reverse z-order (the layer rendered on top is listed first)
while (layer--) {
var name = drawing.getLayerName(layer);
var layerTr = $('<tr class="layer">').toggleClass('layersel', name === currentLayerName);
var layerVis = $('<td class="layervis">').toggleClass('layerinvis', !drawing.getLayerVisibility(name));
var layerName = $('<td class="layername">' + name + '</td>');
layerlist.append(layerTr.append(layerVis, layerName));
selLayerNames.append('<option value="' + name + '">' + name + '</option>');
}
if (icon !== undefined) {
var copy = icon.clone();
$('td.layervis', layerlist).append(copy);
$.resizeSvgIcons({'td.layervis .svg_icon': 14});
}
// handle selection of layer
$('#layerlist td.layername')
.mouseup(function(evt) {
$('#layerlist tr.layer').removeClass('layersel');
$(this.parentNode).addClass('layersel');
svgCanvas.setCurrentLayer(this.textContent);
evt.preventDefault();
})
.mouseover(function() {
toggleHighlightLayer(this.textContent);
})
.mouseout(function() {
toggleHighlightLayer();
});
$('#layerlist td.layervis').click(function() {
var row = $(this.parentNode).prevAll().length;
var name = $('#layerlist tr.layer:eq(' + row + ') td.layername').text();
var vis = $(this).hasClass('layerinvis');
svgCanvas.setLayerVisibility(name, vis);
$(this).toggleClass('layerinvis');
});
// if there were too few rows, let's add a few to make it not so lonely
var num = 5 - $('#layerlist tr.layer').size();
while (num-- > 0) {
// FIXME: there must a better way to do this
layerlist.append('<tr><td style="color:white">_</td><td/></tr>');
}
};
//显示svg源代码
var showSourceEditor = function(e, forSaving) {
if (editingsource) {return;}
$('#tool_source_save').bind('mouseout',function(e){
$('#tool_source_save').removeClass('mouse');
});
$('#tool_source_save').bind('mouseover',function(e){
$(e.target).addClass('mouse');
});
$('#tool_source_cancel').bind('mouseout',function(e){
$('#tool_source_cancel').removeClass('mouse');
});
$('#tool_source_cancel').bind('mouseover',function(e){
$(e.target).addClass('mouse');
});
editingsource = true;
origSource = svgCanvas.getSvgString();
/*$('#save_output_btns').toggle(!!forSaving);*/
$('#tool_source_back').toggle(!forSaving);
$('#svg_source_textarea').val(origSource);
$('#svg_source_editor').fadeIn();
$('#svg_source_textarea').focus();
};
var operaRepaint = function() {
// Repaints canvas in Opera. Needed for stroke-dasharray change as well as fill change
if (!window.opera) {
return;
}
$('<p/>').hide().appendTo('body').remove();
};
function setStrokeOpt(opt, changeElem) {
var id = opt.id;
var bits = id.split('_');
var pre = bits[0];
var val = bits[1];
if (changeElem) {
svgCanvas.setStrokeAttr('stroke-' + pre, val);
}
operaRepaint();
setIcon('#cur_' + pre, id, 20);
$(opt).addClass('current').siblings().removeClass('current');
}
// This is a common function used when a tool has been clicked (chosen)
// It does several common things:
// - removes the tool_button_current class from whatever tool currently has it
// - hides any flyouts
// - adds the tool_button_current class to the button passed in
var toolButtonClick = editor.toolButtonClick = function(button, noHiding) {
if ($(button).hasClass('disabled')) {return false;}
if ($(button).parent().hasClass('tools_flyout')) {return true;}
var fadeFlyouts = 'normal';
if (!noHiding) {
/*$('.tools_flyout').fadeOut(fadeFlyouts);*/
}
$('#styleoverrides').text('');
workarea.css('cursor', 'auto');
$('.tool_button_current').removeClass('tool_button_current').addClass('tool_button');
$(button).addClass('tool_button_current').removeClass('tool_button');
return true;
};
var clickSelect = editor.clickSelect = function() {
if (toolButtonClick('#tool_select')) {
svgCanvas.setMode('select');
$('#styleoverrides').text('#svgcanvas svg *{cursor:move;pointer-events:all}, #svgcanvas svg{cursor:default}');
}
};
function setBackground (color, url) {
$.pref('bkgd_color', color);
$.pref('bkgd_url', url);
// This should be done in svgcanvas.js for the borderRect fill
svgCanvas.setBackground(color, url);
}
var setInputWidth = function(elem) {
var w = Math.min(Math.max(12 + elem.value.length * 6, 50), 300);
$(elem).width(w);
};
function updateRulers(scanvas, zoom) {
if (!zoom) {zoom = svgCanvas.getZoom();}
if (!scanvas) {scanvas = $('#svgcanvas');}
var d, i;
var limit = 30000;
var contentElem = svgCanvas.getContentElem();
var units = svgedit.units.getTypeMap();
var unit = units[curConfig.baseUnit]; // 1 = 1px
// draw x ruler then y ruler
for (d = 0; d < 2; d++) {
var isX = (d === 0);
var dim = isX ? 'x' : 'y';
var lentype = isX ? 'width' : 'height';
var contentDim = Number(contentElem.getAttribute(dim));
var $hcanv_orig = $('#ruler_' + dim + ' canvas:first');
// Bit of a hack to fully clear the canvas in Safari & IE9
var $hcanv = $hcanv_orig.clone();
$hcanv_orig.replaceWith($hcanv);
var hcanv = $hcanv[0];
// Set the canvas size to the width of the container
var ruler_len = scanvas[lentype]();
var total_len = ruler_len;
hcanv.parentNode.style[lentype] = total_len + 'px';
var ctx_num = 0;
var ctx = hcanv.getContext('2d');
var ctx_arr, num, ctx_arr_num;
ctx.fillStyle = 'rgb(200,0,0)';
ctx.fillRect(0, 0, hcanv.width, hcanv.height);
// Remove any existing canvasses
$hcanv.siblings().remove();
// Create multiple canvases when necessary (due to browser limits)
if (ruler_len >= limit) {
ctx_arr_num = parseInt(ruler_len / limit, 10) + 1;
ctx_arr = [];
ctx_arr[0] = ctx;
var copy;
for (i = 1; i < ctx_arr_num; i++) {
hcanv[lentype] = limit;
copy = hcanv.cloneNode(true);
hcanv.parentNode.appendChild(copy);
ctx_arr[i] = copy.getContext('2d');
}
copy[lentype] = ruler_len % limit;
// set copy width to last
ruler_len = limit;
}
hcanv[lentype] = ruler_len;
var u_multi = unit * zoom;
// Calculate the main number interval
var raw_m = 50 / u_multi;
var multi = 1;
for (i = 0; i < r_intervals.length; i++) {
num = r_intervals[i];
multi = num;
if (raw_m <= num) {
break;
}
}
var big_int = multi * u_multi;
ctx.font = '9px sans-serif';
var ruler_d = ((contentDim / u_multi) % multi) * u_multi;
var label_pos = ruler_d - big_int;
// draw big intervals
while (ruler_d < total_len) {
label_pos += big_int;
// var real_d = ruler_d - contentDim; // Currently unused
var cur_d = Math.round(ruler_d) + 0.5;
if (isX) {
ctx.moveTo(cur_d, 15);
ctx.lineTo(cur_d, 0);
}
else {
ctx.moveTo(15, cur_d);
ctx.lineTo(0, cur_d);
}
num = (label_pos - contentDim) / u_multi;
var label;
if (multi >= 1) {
label = Math.round(num);
}
else {
var decs = String(multi).split('.')[1].length;
label = num.toFixed(decs);
}
// Change 1000s to Ks
if (label !== 0 && label !== 1000 && label % 1000 === 0) {
label = (label / 1000) + 'K';
}
if (isX) {
ctx.fillText(label, ruler_d+2, 8);
} else {
// draw label vertically
var str = String(label).split('');
for (i = 0; i < str.length; i++) {
ctx.fillText(str[i], 1, (ruler_d+9) + i*9);
}
}
var part = big_int / 10;
// draw the small intervals
for (i = 1; i < 10; i++) {
var sub_d = Math.round(ruler_d + part * i) + 0.5;
if (ctx_arr && sub_d > ruler_len) {
ctx_num++;
ctx.stroke();
if (ctx_num >= ctx_arr_num) {
i = 10;
ruler_d = total_len;
continue;
}
ctx = ctx_arr[ctx_num];
ruler_d -= limit;
sub_d = Math.round(ruler_d + part * i) + 0.5;
}
// odd lines are slighly longer
var line_num = (i % 2) ? 12 : 10;
if (isX) {
ctx.moveTo(sub_d, 15);
ctx.lineTo(sub_d, line_num);
} else {
ctx.moveTo(15, sub_d);
ctx.lineTo(line_num, sub_d);
}
}
ruler_d += big_int;
}
ctx.strokeStyle = '#000';
ctx.stroke();
}
}
var updateCanvas = editor.updateCanvas = function(center, new_ctr) {
var w = workarea.width(), h = workarea.height();
var w_orig = w, h_orig = h;
var zoom = svgCanvas.getZoom();
var w_area = workarea;
var cnvs = $('#svgcanvas');
var old_ctr = {
x: w_area[0].scrollLeft + w_orig/2,
y: w_area[0].scrollTop + h_orig/2
};
var multi = curConfig.canvas_expansion;
w = Math.max(w_orig, svgCanvas.contentW * zoom * multi);
h = Math.max(h_orig, svgCanvas.contentH * zoom * multi);
if (w == w_orig && h == h_orig) {
workarea.css('overflow', 'hidden');
} else {
workarea.css('overflow', 'scroll');
}
var old_can_y = cnvs.height()/2;
var old_can_x = cnvs.width()/2;
cnvs.width(w).height(h);
var new_can_y = h/2;
var new_can_x = w/2;
var offset = svgCanvas.updateCanvas(w, h);
var ratio = new_can_x / old_can_x;
var scroll_x = w/2 - w_orig/2;
var scroll_y = h/2 - h_orig/2;
if (!new_ctr) {
var old_dist_x = old_ctr.x - old_can_x;
var new_x = new_can_x + old_dist_x * ratio;
var old_dist_y = old_ctr.y - old_can_y;
var new_y = new_can_y + old_dist_y * ratio;
new_ctr = {
x: new_x,
y: new_y
};
} else {
new_ctr.x += offset.x;
new_ctr.y += offset.y;
}
if (center) {
// Go to top-left for larger documents
if (svgCanvas.contentW > w_area.width()) {
// Top-left
workarea[0].scrollLeft = offset.x - 10;
workarea[0].scrollTop = offset.y - 10;
} else {
// Center
w_area[0].scrollLeft = scroll_x;
w_area[0].scrollTop = scroll_y;
}
} else {
w_area[0].scrollLeft = new_ctr.x - w_orig/2;
w_area[0].scrollTop = new_ctr.y - h_orig/2;
}
if (curConfig.showRulers) {
updateRulers(cnvs, zoom);
workarea.scroll();
}
if (urldata.storagePrompt !== true && !editor.storagePromptClosed) {
$('#dialog_box').hide();
}
};
var updateToolButtonState = function() {
var index, button;
var bNoFill = (svgCanvas.getColor('fill') == 'none');
var bNoStroke = (svgCanvas.getColor('stroke') == 'none');
var buttonsNeedingStroke = [ '#tool_fhpath', '#tool_line' ];
var buttonsNeedingFillAndStroke = [ '#tools_rect .tool_button', '#tools_ellipse .tool_button', '#tool_text', '#tool_path'];
if (bNoStroke) {
for (index in buttonsNeedingStroke) {
button = buttonsNeedingStroke[index];
if ($(button).hasClass('tool_button_current')) {
clickSelect();
}
$(button).addClass('disabled');
}
} else {
for (index in buttonsNeedingStroke) {
button = buttonsNeedingStroke[index];
$(button).removeClass('disabled');
}
}
if (bNoStroke && bNoFill) {
for (index in buttonsNeedingFillAndStroke) {
button = buttonsNeedingFillAndStroke[index];
if ($(button).hasClass('tool_button_current')) {
clickSelect();
}
$(button).addClass('disabled');
}
} else {
for (index in buttonsNeedingFillAndStroke) {
button = buttonsNeedingFillAndStroke[index];
$(button).removeClass('disabled');
}
}
svgCanvas.runExtensions('toolButtonStateUpdate', {
nofill: bNoFill,
nostroke: bNoStroke
});
// Disable flyouts if all inside are disabled
$('.tools_flyout').each(function() {
var shower = $('#' + this.id + '_show');
var has_enabled = false;
$(this).children().each(function() {
if (!$(this).hasClass('disabled')) {
has_enabled = true;
}
});
shower.toggleClass('disabled', !has_enabled);
});
operaRepaint();
};
// Updates the toolbar (colors, opacity, etc) based on the selected element
// This function also updates the opacity and id elements that are in the context panel
var updateToolbar = function() {
var i, len;
if (selectedElement != null) {
switch (selectedElement.tagName) {
case 'use':
case 'image':
case 'foreignObject':
break;
case 'g':
case 'a':
// Look for common styles
var gWidth = null;
var childs = selectedElement.getElementsByTagName('*');
for (i = 0, len = childs.length; i < len; i++) {
var swidth = childs[i].getAttribute('stroke-width');
if (i === 0) {
gWidth = swidth;
} else if (gWidth !== swidth) {
gWidth = null;
}
}
$('#stroke_width').val(gWidth === null ? '' : gWidth);
paintBox.fill.update(true);
paintBox.stroke.update(true);
break;
default:
paintBox.fill.update(true);
paintBox.stroke.update(true);
$('#stroke_width').val(selectedElement.getAttribute('stroke-width') || 1);
$('#stroke_style').val(selectedElement.getAttribute('stroke-dasharray') || 'none');
var attr = selectedElement.getAttribute('stroke-linejoin') || 'miter';
if ($('#linejoin_' + attr).length != 0) {
setStrokeOpt($('#linejoin_' + attr)[0]);
}
attr = selectedElement.getAttribute('stroke-linecap') || 'butt';
if ($('#linecap_' + attr).length != 0) {
setStrokeOpt($('#linecap_' + attr)[0]);
}
}
}
// All elements including image and group have opacity
if (selectedElement != null) {
var opac_perc = ((selectedElement.getAttribute('opacity')||1.0)*100);
$('#group_opacity').val(opac_perc);
$('#opac_slider').slider('option', 'value', opac_perc);
$('#elem_id').val(selectedElement.id);
$('#elem_class').val(selectedElement.getAttribute("class"));
}
updateToolButtonState();
};
// updates the context panel tools based on the selected element
var updateContextPanel = function() {
var elem = selectedElement;
// If element has just been deleted, consider it null
if (elem != null && !elem.parentNode) {elem = null;}
var currentLayerName = svgCanvas.getCurrentDrawing().getCurrentLayerName();
var currentMode = svgCanvas.getMode();
var unit = curConfig.baseUnit !== 'px' ? curConfig.baseUnit : null;
var is_node = currentMode == 'pathedit'; //elem ? (elem.id && elem.id.indexOf('pathpointgrip') == 0) : false;
var menu_items = $('#cmenu_canvas li');
$('#multiselected_panel, #g_panel,#circle_panel,#ellipse_panel, #line_panel, #text_panel').hide();
if (elem != null) {
var elname = elem.nodeName;
// If this is a link with no transform and one child, pretend
// its child is selected
var angle = svgCanvas.getRotationAngle(elem);
$('#angle').val(angle);
var blurval = svgCanvas.getBlur(elem);
$('#blur').val(blurval);
$('#blur_slider').slider('option', 'value', blurval);
// update contextual tools here
var panels = {
g: [],
a: [],
rect: ['rx', 'width', 'height'],
image: ['width', 'height'],
circle: ['cx', 'cy', 'r'],
ellipse: ['cx', 'cy', 'rx', 'ry'],
line: ['x1', 'y1', 'x2', 'y2'],
text: [],
use: []
};
var el_name = elem.tagName;
var link_href = null;
if (el_name === 'a') {
link_href = svgCanvas.getHref(elem);
$('#g_panel').show();
}
if (elem.parentNode.tagName === 'a') {
if (!$(elem).siblings().length) {
$('#a_panel').show();
link_href = svgCanvas.getHref(elem.parentNode);
}
}
if (panels[el_name]) {
var cur_panel = panels[el_name];
$('#' + el_name + '_panel').show();
$.each(cur_panel, function(i, item) {
var attrVal = elem.getAttribute(item);
if (curConfig.baseUnit !== 'px' && elem[item]) {
var bv = elem[item].baseVal.value;
attrVal = svgedit.units.convertUnit(bv);
}
$('#' + el_name + '_' + item).val(attrVal || 0);
});
if (el_name == 'text') {
$('#text_panel').css('display', 'inline');
$('#tool_font_size').css('display', 'inline');
if (svgCanvas.getItalic()) {
$('#tool_italic').addClass('push_button_pressed').removeClass('tool_button');
} else {
$('#tool_italic').removeClass('push_button_pressed').addClass('tool_button');
}
if (svgCanvas.getBold()) {
$('#tool_bold').addClass('push_button_pressed').removeClass('tool_button');
} else {
$('#tool_bold').removeClass('push_button_pressed').addClass('tool_button');
}
$('#font_family').val(font_English2Chinese(elem.getAttribute('font-family')));
$('#font_size').val(elem.getAttribute('font-size'));
$('#text').val(elem.textContent);
if (svgCanvas.addedNew) {
// Timeout needed for IE9
setTimeout(function() {
$('#text').focus().select();
}, 100);
}
} // text
}
menu_items[(el_name === 'g' ? 'en' : 'dis') + 'ableContextMenuItems']('#ungroup');
menu_items[((el_name === 'g' || !multiselected) ? 'dis' : 'en') + 'ableContextMenuItems']('#group');
} // if (elem != null)
else if (multiselected) {
$('#multiselected_panel').show();
menu_items
.enableContextMenuItems('#group')
.disableContextMenuItems('#ungroup');
} else {
menu_items.disableContextMenuItems('#delete,#cut,#copy,#group,#ungroup,#move_front,#move_up,#move_down,#move_back');
}
// update history buttons
$('#tool_undo').toggleClass('disabled', undoMgr.getUndoStackSize() === 0);
$('#tool_redo').toggleClass('disabled', undoMgr.getRedoStackSize() === 0);
svgCanvas.addedNew = false;
if ( (elem && !is_node) || multiselected) {
// update the selected elements' layer
$('#selLayerNames').removeAttr('disabled').val(currentLayerName);
// Enable regular menu options
canv_menu.enableContextMenuItems('#delete,#cut,#copy,#move_front,#move_up,#move_down,#move_back');
} else {
$('#selLayerNames').attr('disabled', 'disabled');
}
};
var updateWireFrame = function() {
// Test support
if (supportsNonSS) {return;}
var rule = '#workarea.wireframe #svgcontent * { stroke-width: ' + 1/svgCanvas.getZoom() + 'px; }';
$('#wireframe_rules').text(workarea.hasClass('wireframe') ? rule : '');
};
var updateTitle = function(title) {
title = title || svgCanvas.getDocumentTitle();
var newTitle = origTitle + (title ? ': ' + title : '');
// Remove title update with current context info, isn't really necessary
$('title:first').text(newTitle);
};
// called when we've selected a different element
var selectedChanged = function(win, elems) {
var mode = svgCanvas.getMode();
if (mode === 'select') {
setSelectMode();
}
var is_node = (mode == "pathedit");
// if elems[1] is present, then we have more than one element
selectedElement = (elems.length === 1 || elems[1] == null ? elems[0] : null);
multiselected = (elems.length >= 2 && elems[1] != null);
if (selectedElement != null) {
// unless we're already in always set the mode of the editor to select because
// upon creation of a text element the editor is switched into
// select mode and this event fires - we need our UI to be in sync
if (!is_node) {
updateToolbar();
}
} // if (elem != null)
// Deal with pathedit mode
//togglePathEditMode(is_node, elems);
updateContextPanel();
svgCanvas.runExtensions('selectedChanged', {
elems: elems,
selectedElement: selectedElement,
multiselected: multiselected
});
};
// Call when part of element is in process of changing, generally
// on mousemove actions like rotate, move, etc.
var elementTransition = function(win, elems) {
var mode = svgCanvas.getMode();
var elem = elems[0];
if (!elem) {
return;
}
multiselected = (elems.length >= 2 && elems[1] != null);
// Only updating fields for single elements for now
if (!multiselected) {
switch (mode) {
case 'rotate':
var ang = svgCanvas.getRotationAngle(elem);
$('#angle').val(ang);
$('#tool_reorient').toggleClass('disabled', ang === 0);
break;
// TODO: Update values that change on move/resize, etc
}
}
svgCanvas.runExtensions('elementTransition', {
elems: elems
});
};
/**
* Test whether an element is a layer or not.
* @param {SVGGElement} elem - The SVGGElement to test.
* @returns {boolean} True if the element is a layer
*/
function isLayer(elem) {
return elem && elem.tagName === 'g' && svgedit.draw.Layer.CLASS_REGEX.test(elem.getAttribute('class'))
}
// called when any element has changed
var elementChanged = function(win, elems) {
var i,
mode = svgCanvas.getMode();
if (mode === 'select') {
setSelectMode();
}
for (i = 0; i < elems.length; ++i) {
var elem = elems[i];
var isSvgElem = (elem && elem.tagName === 'svg');
if (isSvgElem || isLayer(elem)) {
populateLayers();
// if the element changed was the svg, then it could be a resolution change
if (isSvgElem) {
updateCanvas();
}
}
// Update selectedElement if element is no longer part of the image.
// This occurs for the text elements in Firefox
else if (elem && selectedElement && selectedElement.parentNode == null) {
selectedElement = elem;
}
}
editor.showSaveWarning = true;
// we update the contextual panel with potentially new
// positional/sizing information (we DON'T want to update the
// toolbar here as that creates an infinite loop)
// also this updates the history buttons
// we tell it to skip focusing the text control if the
// text element was previously in focus
updateContextPanel();
// In the event a gradient was flipped:
if (selectedElement && mode === 'select') {
paintBox.fill.update();
paintBox.stroke.update();
}
svgCanvas.runExtensions('elementChanged', {
elems: elems
});
};
var zoomDone = function() {
updateWireFrame();
// updateCanvas(); // necessary?
};
var zoomChanged = svgCanvas.zoomChanged = function(win, bbox, autoCenter) {
var scrbar = 15,w_area = workarea;
var z_info = svgCanvas.setBBoxZoom(bbox, w_area.width()-scrbar, w_area.height()-scrbar);
if (!z_info) {return;}
var zoomlevel = z_info.zoom,
bb = z_info.bbox;
if (zoomlevel < 0.001) {
changeZoom({value: 0.1});
return;
}
$('#zoom').val((zoomlevel*100).toFixed(1));
if (autoCenter) {
updateCanvas();
} else {
updateCanvas(false, {x: bb.x * zoomlevel + (bb.width * zoomlevel)/2, y: bb.y * zoomlevel + (bb.height * zoomlevel)/2});
}
if (svgCanvas.getMode() == 'zoom' && bb.width) {
// Go to select if a zoom box was drawn
setSelectMode();
}
zoomDone();
};
changeZoom = function(ctl) {
var zoomlevel = ctl.value / 100;
if (zoomlevel < 0.001) {
ctl.value = 0.1;
return;
}
var zoom = svgCanvas.getZoom();
var w_area = workarea;
zoomChanged(window, {
width: 0,
height: 0,
// center pt of scroll position
x: (w_area[0].scrollLeft + w_area.width()/2)/zoom,
y: (w_area[0].scrollTop + w_area.height()/2)/zoom,
zoom: zoomlevel
}, true);
};
$('#cur_context_panel').delegate('a', 'click', function() {
var link = $(this);
if (link.attr('data-root')) {
svgCanvas.leaveContext();
} else {
svgCanvas.setContext(link.text());
}
svgCanvas.clearSelection();
return false;
});
var contextChanged = function(win, context) {
var link_str = '';
if (context) {
var str = '';
link_str = '<a href="#" data-root="y">' + svgCanvas.getCurrentDrawing().getCurrentLayerName() + '</a>';
$(context).parentsUntil('#svgcontent > g').andSelf().each(function() {
if (this.id) {
str += ' > ' + this.id;
if (this !== context) {
link_str += ' > <a href="#">' + this.id + '</a>';
} else {
link_str += ' > ' + this.id;
}
}
});
cur_context = str;
} else {
cur_context = null;
}
$('#cur_context_panel').toggle(!!context).html(link_str);
updateTitle();
};
// Makes sure the current selected paint is available to work with
var prepPaints = function() {
paintBox.fill.prep();
paintBox.stroke.prep();
};
var flyout_funcs = {};
var setFlyoutTitles = function() {
$('.tools_flyout').each(function() {
var shower = $('#' + this.id + '_show');
if (shower.data('isLibrary')) {
return;
}
var tooltips = [];
$(this).children().each(function() {
tooltips.push(this.title);
});
shower[0].title = tooltips.join(' / ');
});
};
var setFlyoutPositions = function() {
$('.tools_flyout').each(function() {
var shower = $('#' + this.id + '_show');
var pos = shower.offset();
var w = shower.outerWidth();
$(this).css({left: (pos.left + w) * editor.tool_scale, top: pos.top});
});
};
var setupFlyouts = function(holders) {
$.each(holders, function(hold_sel, btn_opts) {
var buttons = $(hold_sel).children();
var show_sel = hold_sel + '_show';
var shower = $(show_sel);
var def = false;
buttons.addClass('tool_button')
.unbind('click mousedown mouseup') // may not be necessary
.each(function(i) {
// Get this buttons options
var opts = btn_opts[i];
// Remember the function that goes with this ID
flyout_funcs[opts.sel] = opts.fn;
if (opts.isDefault) {def = i;}
// Clicking the icon in flyout should set this set's icon
var func = function(event) {
var options = opts;
//find the currently selected tool if comes from keystroke
if (event.type === 'keydown') {
var flyoutIsSelected = $(options.parent + '_show').hasClass('tool_button_current');
var currentOperation = $(options.parent + '_show').attr('data-curopt');
$.each(holders[opts.parent], function(i, tool) {
if (tool.sel == currentOperation) {
if (!event.shiftKey || !flyoutIsSelected) {
options = tool;
} else {
options = holders[opts.parent][i+1] || holders[opts.parent][0];
}
}
});
}
if ($(this).hasClass('disabled')) {return false;}
if (toolButtonClick(show_sel)) {
options.fn();
}
var icon;
if (options.icon) {
icon = $.getSvgIcon(options.icon, true);
} else {
icon = $(options.sel).children().eq(0).clone();
}
icon[0].setAttribute('width', shower.width());
icon[0].setAttribute('height', shower.height());
shower.children(':not(.flyout_arrow_horiz)').remove();
shower.append(icon).attr('data-curopt', options.sel); // This sets the current mode
};
$(this).mouseup(func);
if (opts.key) {
$(document).bind('keydown', opts.key[0] + ' shift+' + opts.key[0], func);
}
});
if (def) {
shower.attr('data-curopt', btn_opts[def].sel);
} else if (!shower.attr('data-curopt')) {
// Set first as default
shower.attr('data-curopt', btn_opts[0].sel);
}
var timer;
var pos = $(show_sel).position();
// Clicking the "show" icon should set the current mode
shower.mousedown(function(evt) {
if (shower.hasClass('disabled')) {
return false;
}
var holder = $(hold_sel);
var l = pos.left + 34;
var w = holder.width() * -1;
var time = holder.data('shown_popop') ? 200 : 0;
timer = setTimeout(function() {
// Show corresponding menu
if (!shower.data('isLibrary')) {
holder.css('left', w).show().animate({
left: l
}, 150);
} else {
holder.css('left', l).show();
}
},time);
evt.preventDefault();
}).mouseup(function(evt) {
clearTimeout(timer);
var opt = $(this).attr('data-curopt');
// Is library and popped up, so do nothing
if (shower.data('isLibrary') && $(show_sel.replace('_show', '')).is(':visible')) {
toolButtonClick(show_sel, true);
return;
}
if (toolButtonClick(show_sel) && flyout_funcs[opt]) {
flyout_funcs[opt]();
}
});
// $('#tools_rect').mouseleave(function(){$('#tools_rect').fadeOut();});
});
setFlyoutTitles();
setFlyoutPositions();
};
var makeFlyoutHolder = function(id, child) {
var div = $('<div>', {
'class': 'tools_flyout',
id: id
}).appendTo('#svg_editor').append(child);
return div;
};
var uaPrefix = (function() {
var prop;
var regex = /^(Moz|Webkit|Khtml|O|ms|Icab)(?=[A-Z])/;
var someScript = document.getElementsByTagName('script')[0];
for (prop in someScript.style) {
if (regex.test(prop)) {
// test is faster than match, so it's better to perform
// that on the lot and match only when necessary
return prop.match(regex)[0];
}
}
// Nothing found so far?
if ('WebkitOpacity' in someScript.style) {return 'Webkit';}
if ('KhtmlOpacity' in someScript.style) {return 'Khtml';}
return '';
}());
var scaleElements = function(elems, scale) {
// var prefix = '-' + uaPrefix.toLowerCase() + '-'; // Currently unused
var sides = ['top', 'left', 'bottom', 'right'];
elems.each(function() {
// Handled in CSS
var i;
var el = $(this);
var w = el.outerWidth() * (scale - 1);
var h = el.outerHeight() * (scale - 1);
for (i = 0; i < 4; i++) {
var s = sides[i];
var cur = el.data('orig_margin-' + s);
if (cur == null) {
cur = parseInt(el.css('margin-' + s), 10);
// Cache the original margin
el.data('orig_margin-' + s, cur);
}
var val = cur * scale;
if (s === 'right') {
val += w;
} else if (s === 'bottom') {
val += h;
}
el.css('margin-' + s, val);
}
});
};
var setIconSize = editor.setIconSize = function (size) {
var sel_toscale = '#tools_top .toolset, #editor_panel > *, #history_panel > *,'+
' #main_button, #tools_left > *, #multiselected_panel > *,'+
' #g_panel > *, #tool_font_size > *, .tools_flyout';
var elems = $(sel_toscale);
var scale = 1;
if (typeof size === 'number') {
scale = size;
} else {
var icon_sizes = {s: 0.75, m:1, l: 1.25, xl: 1.5};
scale = icon_sizes[size];
}
editor.tool_scale = scale;
setFlyoutPositions();
var hidden_ps = elems.parents(':hidden');
hidden_ps.css('visibility', 'hidden').show();
scaleElements(elems, scale);
hidden_ps.css('visibility', 'visible').hide();
// return;
$.pref('iconsize', size);
$('#iconsize').val(size);
// Note that all rules will be prefixed with '#svg_editor' when parsed
var cssResizeRules = {
'#tools_top': {
'left': 50 + $('#main_button').width(),
'height': 72
},
'#tools_left': {
'width': 31,
'top': 74
},
'div#workarea': {
'left': 38,
'top': 74
}
};
var rule_elem = $('#tool_size_rules');
if (!rule_elem.length) {
rule_elem = $('<style id="tool_size_rules"></style>').appendTo('head');
} else {
rule_elem.empty();
}
if (size !== 'm') {
var styleStr = '';
$.each(cssResizeRules, function(selector, rules) {
selector = '#svg_editor ' + selector.replace(/,/g,', #svg_editor');
styleStr += selector + '{';
$.each(rules, function(prop, values) {
var val;
if (typeof values === 'number') {
val = (values * scale) + 'px';
} else if (values[size] || values.all) {
val = (values[size] || values.all);
}
styleStr += (prop + ':' + val + ';');
});
styleStr += '}';
});
var prefix = '-' + uaPrefix.toLowerCase() + '-';
styleStr += (sel_toscale + '{' + prefix + 'transform: scale(' + scale + ');}'
+ ' #svg_editor div.toolset .toolset {' + prefix + 'transform: scale(1); margin: 1px !important;}' // Hack for markers
+ ' #svg_editor .ui-slider {' + prefix + 'transform: scale(' + (1/scale) + ');}' // Hack for sliders
);
rule_elem.text(styleStr);
}
setFlyoutPositions();
};
// TODO: Combine this with addDropDown or find other way to optimize
var addAltDropDown = function(elem, list, callback, opts) {
var button = $(elem);
list = $(list);
var on_button = false;
var dropUp = opts.dropUp;
if (dropUp) {
$(elem).addClass('dropup');
}
list.find('li').bind('mouseup', function() {
if (opts.seticon) {
setIcon('#cur_' + button[0].id , $(this).children());
$(this).addClass('current').siblings().removeClass('current');
}
callback.apply(this, arguments);
});
$(window).mouseup(function(evt) {
if (!on_button) {
button.removeClass('down');
list.hide();
list.css({top:0, left:0});
}
on_button = false;
});
button.bind('mousedown',function() {
var off = button.offset();
if (dropUp) {
off.top -= list.height();
off.left += 8;
} else {
off.top += button.height();
}
list.offset(off);
if (!button.hasClass('down')) {
list.show();
on_button = true;
} else {
// CSS position must be reset for Webkit
list.hide();
list.css({top:0, left:0});
}
button.toggleClass('down');
}).hover(function() {
on_button = true;
}).mouseout(function() {
on_button = false;
});
if (opts.multiclick) {
list.mousedown(function() {
on_button = true;
});
}
};
/*var extsPreLang = [];*/
var extAdded = function(win, ext) {
if (!ext) {
return;
}
var cb_called = false;
var resize_done = false;
var cb_ready = true; // Set to false to delay callback (e.g. wait for $.svgIcons)
function prepResize() {
if (resize_timer) {
clearTimeout(resize_timer);
resize_timer = null;
}
if (!resize_done) {
resize_timer = setTimeout(function() {
resize_done = true;
setIconSize($.pref('iconsize'));
}, 50);
}
}
var runCallback = function() {
if (ext.callback && !cb_called && cb_ready) {
cb_called = true;
ext.callback();
}
};
var btn_selects = [];
if (ext.context_tools) {
$.each(ext.context_tools, function(i, tool) {
// Add select tool
var html;
var cont_id = tool.container_id ? (' id="' + tool.container_id + '"') : '';
var panel = $('#' + tool.panel);
// create the panel if it doesn't exist
if (!panel.length) {
panel = $('<div>', {id: tool.panel}).appendTo('#tools_top');
}
// TODO: Allow support for other types, or adding to existing tool
switch (tool.type) {
case 'tool_button':
html = '<div class="tool_button">' + tool.id + '</div>';
var div = $(html).appendTo(panel);
if (tool.events) {
$.each(tool.events, function(evt, func) {
$(div).bind(evt, func);
});
}
break;
case 'select':
html = '<label' + cont_id + '>'
+ '<select id="' + tool.id + '">';
$.each(tool.options, function(val, text) {
var sel = (val == tool.defval) ? ' selected' : '';
html += '<option value="'+val+'"' + sel + '>' + text + '</option>';
});
html += '</select></label>';
// Creates the tool, hides & adds it, returns the select element
var sel = $(html).appendTo(panel).find('select');
$.each(tool.events, function(evt, func) {
$(sel).bind(evt, func);
});
break;
case 'button-select':
html = '<div id="' + tool.id + '" class="dropdown toolset" title="' + tool.title + '">'
+ '<div id="cur_' + tool.id + '" class="icon_label"></div><button></button></div>';
var list = $('<ul id="' + tool.id + '_opts"></ul>').appendTo('#option_lists');
if (tool.colnum) {
list.addClass('optcols' + tool.colnum);
}
// Creates the tool, hides & adds it, returns the select element
var dropdown = $(html).appendTo(panel).children();
btn_selects.push({
elem: ('#' + tool.id),
list: ('#' + tool.id + '_opts'),
title: tool.title,
callback: tool.events.change,
cur: ('#cur_' + tool.id)
});
break;
case 'input':
html = '<label' + cont_id + '>'
+ '<span id="' + tool.id + '_label">'
+ tool.label + ':</span>'
+ '<input id="' + tool.id + '" title="' + tool.title
+ '" size="' + (tool.size || '4') + '" value="' + (tool.defval || '') + '" type="text"/></label>';
// Creates the tool, hides & adds it, returns the select element
// Add to given tool.panel
var inp = $(html).appendTo(panel).find('input');
if (tool.spindata) {
inp.SpinButton(tool.spindata);
}
if (tool.events) {
$.each(tool.events, function(evt, func) {
inp.bind(evt, func);
});
}
break;
default:
break;
}
});
}
if (ext.buttons) {
var fallback_obj = {},
placement_obj = {},
svgicons = ext.svgicons,
holders = {};
// Add buttons given by extension
$.each(ext.buttons, function(i, btn) {
var icon, svgicon, tls_id;
var id = btn.id;
var num = i;
// Give button a unique ID
while($('#'+id).length) {
id = btn.id + '_' + (++num);
}
if (!svgicons) {
icon = $('<img src="' + btn.icon + '">');
} else {
fallback_obj[id] = btn.icon;
svgicon = btn.svgicon || btn.id;
if (btn.type == 'app_menu') {
placement_obj['#' + id + ' > div'] = svgicon;
} else {
placement_obj['#' + id] = svgicon;
}
}
var cls, parent;
// Set button up according to its type
switch ( btn.type ) {
case 'mode_flyout':
case 'mode':
cls = 'tool_button';
parent = '#tools_left';
break;
case 'context':
cls = 'tool_button';
parent = '#' + btn.panel;
// create the panel if it doesn't exist
if (!$(parent).length) {
$('<div>', {id: btn.panel}).appendTo('#tools_top');
}
break;
case 'app_menu':
cls = '';
parent = '#main_menu ul';
break;
}
var flyout_holder, cur_h, show_btn, ref_data, ref_btn;
var button = $((btn.list || btn.type == 'app_menu') ? '<li/>' : '<div/>')
.attr('id', id)
.attr('title', btn.title)
.addClass(cls);
if (!btn.includeWith && !btn.list) {
if ('position' in btn) {
if ($(parent).children().eq(btn.position).length) {
$(parent).children().eq(btn.position).before(button);
}
else {
$(parent).children().last().before(button);
}
} else {
button.appendTo(parent);
}
if (btn.type =='mode_flyout') {
ref_btn = $(button);
flyout_holder = ref_btn.parent();
// Create a flyout menu if there isn't one already
if (!ref_btn.parent().hasClass('tools_flyout')) {
// Create flyout placeholder
tls_id = ref_btn[0].id.replace('tool_', 'tools_');
show_btn = ref_btn.clone()
.attr('id', tls_id + '_show')
.append($('<div>', {'class': 'flyout_arrow_horiz'}));
ref_btn.before(show_btn);
// Create a flyout div
flyout_holder = makeFlyoutHolder(tls_id, ref_btn);
flyout_holder.data('isLibrary', true);
show_btn.data('isLibrary', true);
}
placement_obj['#' + tls_id + '_show'] = btn.id;
// TODO: Find way to set the current icon using the iconloader if this is not default
// Include data for extension button as well as ref button
cur_h = holders['#'+flyout_holder[0].id] = [{
sel: '#'+id,
fn: btn.events.click,
icon: btn.id,
isDefault: true
}, ref_data];
} else if (btn.type == 'app_menu') {
button.append('<div>').append(btn.title);
}
}
else if (btn.list) {
// Add button to list
button.addClass('push_button');
$('#' + btn.list + '_opts').append(button);
if (btn.isDefault) {
$('#cur_' + btn.list).append(button.children().clone());
svgicon = btn.svgicon || btn.id;
placement_obj['#cur_' + btn.list] = svgicon;
}
}
else if (btn.includeWith) {
// Add to flyout menu / make flyout menu
var opts = btn.includeWith;
// opts.button, default, position
ref_btn = $(opts.button);
flyout_holder = ref_btn.parent();
// Create a flyout menu if there isn't one already
if (!ref_btn.parent().hasClass('tools_flyout')) {
// Create flyout placeholder
tls_id = ref_btn[0].id.replace('tool_', 'tools_');
show_btn = ref_btn.clone()
.attr('id',tls_id + '_show')
.append($('<div>', {'class': 'flyout_arrow_horiz'}));
ref_btn.before(show_btn);
// Create a flyout div
flyout_holder = makeFlyoutHolder(tls_id, ref_btn);
}
ref_data = Actions.getButtonData(opts.button);
if (opts.isDefault) {
placement_obj['#' + tls_id + '_show'] = btn.id;
}
// TODO: Find way to set the current icon using the iconloader if this is not default
// Include data for extension button as well as ref button
cur_h = holders['#' + flyout_holder[0].id] = [{
sel: '#' + id,
fn: btn.events.click,
icon: btn.id,
key: btn.key,
isDefault: btn.includeWith ? btn.includeWith.isDefault : 0
}, ref_data];
var pos = ('position' in opts) ? opts.position : 'last';
var len = flyout_holder.children().length;
// Add at given position or end
if (!isNaN(pos) && pos >= 0 && pos < len) {
flyout_holder.children().eq(pos).before(button);
} else {
flyout_holder.append(button);
cur_h.reverse();
}
}
if (!svgicons) {
button.append(icon);
}
if (!btn.list) {
// Add given events to button
$.each(btn.events, function(name, func) {
if (name == 'click' && btn.type == 'mode') {
if (btn.includeWith) {
button.bind(name, func);
} else {
button.bind(name, function() {
if (toolButtonClick(button)) {
func();
}
});
}
if (btn.key) {
$(document).bind('keydown', btn.key, func);
if (btn.title) {
button.attr('title', btn.title + ' ['+btn.key+']');
}
}
} else {
button.bind(name, func);
}
});
}
setupFlyouts(holders);
});
$.each(btn_selects, function() {
addAltDropDown(this.elem, this.list, this.callback, {seticon: true});
});
if (svgicons) {
cb_ready = false; // Delay callback
}
$.svgIcons(svgicons, {
w: 24, h: 24,
id_match: false,
no_img: (!svgedit.browser.isWebkit()),
fallback: fallback_obj,
placement: placement_obj,
callback: function (icons) {
// Non-ideal hack to make the icon match the current size
if ($.pref('iconsize') !== 'm') {
prepResize();
}
cb_ready = true; // Ready for callback
runCallback();
}
});
}
runCallback();
};
var getPaint = function(color, opac, type) {
// update the editor's fill paint
var opts = { alpha: opac };
if (color.indexOf('url(#') === 0) {
var refElem = svgCanvas.getRefElem(color);
if (refElem) {
refElem = refElem.cloneNode(true);
} else {
refElem = $('#' + type + '_color defs *')[0];
}
opts[refElem.tagName] = refElem;
} else if (color.indexOf('#') === 0) {
opts.solidColor = color.substr(1);
} else {
opts.solidColor = 'none';
}
return new $.jGraduate.Paint(opts);
};
$('#text').focus( function(){ textBeingEntered = true; } );
$('#text').blur( function(){ textBeingEntered = false; } );
// bind the selected event to our function that handles updates to the UI
svgCanvas.bind('selected', selectedChanged);
svgCanvas.bind('transition', elementTransition);
svgCanvas.bind('changed', elementChanged);
svgCanvas.bind('zoomed', zoomChanged);
svgCanvas.bind('contextset', contextChanged);
svgCanvas.bind('extension_added', extAdded);
svgCanvas.textActions.setInputElem($('#text')[0]);
var str = '<div class="palette_item" data-rgb="none"></div>';
$.each(palette, function(i, item) {
str += '<div class="palette_item" style="background-color: ' + item + ';" data-rgb="' + item + '"></div>';
});
$('#palette').append(str);
// Set up editor background functionality
// TODO add checkerboard as "pattern"
var color_blocks = ['#FFF', '#888', '#000']; // ,'url(data:image/gif;base64,R0lGODlhEAAQAIAAAP%2F%2F%2F9bW1iH5BAAAAAAALAAAAAAQABAAAAIfjG%2Bgq4jM3IFLJgpswNly%2FXkcBpIiVaInlLJr9FZWAQA7)'];
str = '';
$.each(color_blocks, function() {
str += '<div class="color_block" style="background-color:' + this + ';"></div>';
});
$('#bg_blocks').append(str);
var blocks = $('#bg_blocks div');
var cur_bg = 'cur_background';
blocks.each(function() {
var blk = $(this);
blk.click(function() {
blocks.removeClass(cur_bg);
$(this).addClass(cur_bg);
});
});
setBackground($.pref('bkgd_color'), $.pref('bkgd_url'));
$('#image_save_opts input').val([$.pref('img_save')]);
var changeRectRadius = function(ctl) {
svgCanvas.setRectRadius(ctl.value);
};
var changeFontSize = function(ctl) {
svgCanvas.setFontSize(ctl.value);
};
/*改变字体名称(新添加的函数)*/
var font_English2Chinese = function(font_family){
var out = font_family;
var doc = document.getElementById("font_family_dropdown-list").children;
for(var i=0;i<doc.length;i++){
var english = doc[i].getAttribute("style").split(":")[1];
var chinese = doc[i].textContent;
if(font_family == english){
out = chinese;
break;
}else if(font_family == chinese){
out = english;
break;
}
}
return out;
};
var changeStrokeWidth = function(ctl) {
var val = ctl.value;
if (val == 0 && selectedElement && ['line', 'polyline'].indexOf(selectedElement.nodeName) >= 0) {
val = ctl.value = 1;
}
svgCanvas.setStrokeWidth(val);
};
var changeRotationAngle = function(ctl) {
svgCanvas.setRotationAngle(ctl.value);
$('#tool_reorient').toggleClass('disabled', parseInt(ctl.value, 10) === 0);
};
var changeOpacity = function(ctl, val) {
if (val == null) {val = ctl.value;}
$('#group_opacity').val(val);
if (!ctl || !ctl.handle) {
$('#opac_slider').slider('option', 'value', val);
}
svgCanvas.setOpacity(val/100);
};
var changeBlur = function(ctl, val, noUndo) {
if (val == null) {val = ctl.value;}
$('#blur').val(val);
var complete = false;
if (!ctl || !ctl.handle) {
$('#blur_slider').slider('option', 'value', val);
complete = true;
}
if (noUndo) {
svgCanvas.setBlurNoUndo(val);
} else {
svgCanvas.setBlur(val, complete);
}
};
$('#stroke_style').change(function() {
svgCanvas.setStrokeAttr('stroke-dasharray', $(this).val());
operaRepaint();
});
$('#stroke_linejoin').change(function() {
svgCanvas.setStrokeAttr('stroke-linejoin', $(this).val());
operaRepaint();
});
// Lose focus for select elements when changed (Allows keyboard shortcuts to work better)
$('select').change(function(){$(this).blur();});
// fired when user wants to move elements to another layer
var promptMoveLayerOnce = false;
$('#selLayerNames').change(function() {
var destLayer = this.options[this.selectedIndex].value;
var confirmStr = uiStrings.notification.QmoveElemsToLayer.replace('%s', destLayer);
var moveToLayer = function(ok) {
if (!ok) {return;}
promptMoveLayerOnce = true;
svgCanvas.moveSelectedToLayer(destLayer);
svgCanvas.clearSelection();
populateLayers();
};
if (destLayer) {
$.confirm(confirmStr, moveToLayer);
}
});
$('#font_family').change(function() {
svgCanvas.setFontFamily(font_English2Chinese(this.value));
});
$('#text').bind("keyup input", function() {
svgCanvas.setTextContent(this.value);
});
// Prevent selection of elements when shift-clicking
$('#palette').mouseover(function() {
var inp = $('<input type="hidden">');
$(this).append(inp);
inp.focus().remove();
});
$('.palette_item').mousedown(function(evt) {
// shift key or right click for stroke
var picker = evt.shiftKey || evt.button === 2 ? 'stroke' : 'fill';
var color = $(this).data('rgb');
var paint;
// Webkit-based browsers returned 'initial' here for no stroke
if (color === 'none' || color === 'transparent' || color === 'initial') {
color = 'none';
paint = new $.jGraduate.Paint();
} else {
paint = new $.jGraduate.Paint({alpha: 100, solidColor: color.substr(1)});
}
paintBox[picker].setPaint(paint);
svgCanvas.setColor(picker, color);
if (color !== 'none' && svgCanvas.getPaintOpacity(picker) !== 1) {
svgCanvas.setPaintOpacity(picker, 1.0);
}
updateToolButtonState();
}).bind('contextmenu', function(e) {e.preventDefault();});
$('#toggle_stroke_tools').on('click', function() {
$('#tools_bottom').toggleClass('expanded');
});
(function() {
var last_x = null, last_y = null, w_area = workarea[0],
panning = false, keypan = false;
$('#svgcanvas').bind('mousemove mouseup', function(evt) {
if (panning === false) {return;}
w_area.scrollLeft -= (evt.clientX - last_x);
w_area.scrollTop -= (evt.clientY - last_y);
last_x = evt.clientX;
last_y = evt.clientY;
if (evt.type === 'mouseup') {panning = false;}
return false;
}).mousedown(function(evt) {
if (evt.button === 1 || keypan === true) {
panning = true;
last_x = evt.clientX;
last_y = evt.clientY;
return false;
}
});
$(window).mouseup(function() {
panning = false;
});
$(document).bind('keydown', 'space', function(evt) {
svgCanvas.spaceKey = keypan = true;
evt.preventDefault();
}).bind('keyup', 'space', function(evt) {
evt.preventDefault();
svgCanvas.spaceKey = keypan = false;
}).bind('keydown', 'shift', function(evt) {
if (svgCanvas.getMode() === 'zoom') {
workarea.css('cursor', zoomOutIcon);
}
}).bind('keyup', 'shift', function(evt) {
if (svgCanvas.getMode() === 'zoom') {
workarea.css('cursor', zoomInIcon);
}
});
editor.setPanning = function(active) {
svgCanvas.spaceKey = keypan = active;
};
}());
(function () {
var button = $('#main_icon');
var overlay = $('#main_icon span');
var list = $('#main_menu');
var on_button = false;
var height = 0;
var js_hover = true;
var set_click = false;
$(window).mouseup(function(evt) {
if (!on_button) {
button.removeClass('buttondown');
// do not hide if it was the file input as that input needs to be visible
// for its change event to fire
if (evt.target.tagName != 'INPUT') {
list.fadeOut(200);
} else if (!set_click) {
set_click = true;
$(evt.target).click(function() {
list.css('margin-left', '-9999px').show();
});
}
}
on_button = false;
}).mousedown(function(evt) {
// $('.contextMenu').hide();
var islib = $(evt.target).closest('div.tools_flyout, .contextMenu').length;
if (!islib) {$('.tools_flyout:visible,.contextMenu').fadeOut(250);}
});
overlay.bind('mousedown',function() {
if (!button.hasClass('buttondown')) {
// Margin must be reset in case it was changed before;
list.css('margin-left', 0).show();
if (!height) {
height = list.height();
}
// Using custom animation as slideDown has annoying 'bounce effect'
list.css('height',0).animate({
'height': height
}, 200);
on_button = true;
} else {
list.fadeOut(200);
}
button.toggleClass('buttondown buttonup');
}).hover(function() {
on_button = true;
}).mouseout(function() {
on_button = false;
});
var list_items = $('#main_menu li');
// Check if JS method of hovering needs to be used (Webkit bug)
list_items.mouseover(function() {
js_hover = ($(this).css('background-color') == 'rgba(0, 0, 0, 0)');
list_items.unbind('mouseover');
if (js_hover) {
list_items.mouseover(function() {
this.style.backgroundColor = '#FFC';
}).mouseout(function() {
this.style.backgroundColor = 'transparent';
return true;
});
}
});
$('#tool_prefs_option').unbind('mouseout');
$('#tool_prefs_option').unbind('mouseover');
$('#tool_prefs_option').bind('mouseout',function(e){
$('#tool_prefs_option').removeClass('mouse');
});
$('#tool_prefs_option').bind('mouseover',function(e){
$(e.target).addClass('mouse');
});
}());
// Made public for UI customization.
// TODO: Group UI functions into a public editor.ui interface.
editor.addDropDown = function(elem, callback, dropUp) {
if ($(elem).length == 0) {return;} // Quit if called on non-existant element
var button = $(elem).find('button');
var list = $(elem).find('ul').attr('id', $(elem)[0].id + '-list');
var on_button = false;
if (dropUp) {
$(elem).addClass('dropup');
} else {
// Move list to place where it can overflow container
$('#option_lists').append(list);
}
list.find('li').bind('mouseup', callback);
$(window).mouseup(function(evt) {
if (!on_button) {
button.removeClass('down');
list.hide();
}
on_button = false;
});
button.bind('mousedown',function() {
if (!button.hasClass('down')) {
if (!dropUp) {
var pos = $(elem).position();
list.css({
top: pos.top + 24,
left: pos.left - 10
});
}
list.show();
on_button = true;
} else {
list.hide();
}
button.toggleClass('down');
}).hover(function() {
on_button = true;
}).mouseout(function() {
on_button = false;
});
};
editor.addDropDown('#font_family_dropdown', function() {
$('#font_family').val($(this).text()).change();
});
editor.addDropDown('#opacity_dropdown', function() {
if ($(this).find('div').length) {return;}
var perc = parseInt($(this).text().split('%')[0], 10);
changeOpacity(false, perc);
}, true);
// For slider usage, see: http://jqueryui.com/demos/slider/
$('#opac_slider').slider({
start: function() {
$('#opacity_dropdown li:not(.special)').hide();
},
stop: function() {
$('#opacity_dropdown li').show();
$(window).mouseup();
},
slide: function(evt, ui) {
changeOpacity(ui);
}
});
editor.addDropDown('#blur_dropdown', $.noop);
var slideStart = false;
$('#blur_slider').slider({
max: 10,
step: 0.1,
stop: function(evt, ui) {
slideStart = false;
changeBlur(ui);
$('#blur_dropdown li').show();
$(window).mouseup();
},
start: function() {
slideStart = true;
},
slide: function(evt, ui) {
changeBlur(ui, null, slideStart);
}
});
editor.addDropDown('#zoom_dropdown', function() {
var item = $(this);
var val = item.data('val');
if (val) {
zoomChanged(window, val);
} else {
changeZoom({value: parseFloat(item.text())});
}
}, true);
addAltDropDown('#stroke_linecap', '#linecap_opts', function() {
setStrokeOpt(this, true);
}, {dropUp: true});
addAltDropDown('#stroke_linejoin', '#linejoin_opts', function() {
setStrokeOpt(this, true);
}, {dropUp: true});
addAltDropDown('#tool_position', '#position_opts', function() {
var letter = this.id.replace('tool_pos', '').charAt(0);
svgCanvas.alignSelectedElements(letter, 'page');
}, {multiclick: true});
/*
When a flyout icon is selected
(if flyout) {
- Change the icon
- Make pressing the button run its stuff
}
- Run its stuff
When its shortcut key is pressed
- If not current in list, do as above
, else:
- Just run its stuff
*/
// Unfocus text input when workarea is mousedowned.
(function() {
var inp;
var unfocus = function() {
$(inp).blur();
};
$('#svg_editor').find('button, select, input:not(#text)').focus(function() {
inp = this;
ui_context = 'toolbars';
workarea.mousedown(unfocus);
}).blur(function() {
ui_context = 'canvas';
workarea.unbind('mousedown', unfocus);
// Go back to selecting text if in textedit mode
if (svgCanvas.getMode() == 'textedit') {
$('#text').focus();
}
});
}());
var clickFHPath = function() {//铅笔工具
if (toolButtonClick('#tool_fhpath')) {
svgCanvas.setMode('fhpath');
}
};
var clickLine = function() {//连接工具
if (toolButtonClick('#tool_line')) {
svgCanvas.setMode('line');
}
};
var clickSquare = function() {//矩形----正方形
if (toolButtonClick('#tool_square')) {
svgCanvas.setMode('square');
}
};
var clickRect = function() {//矩形
if (toolButtonClick('#tool_rect')) {
svgCanvas.setMode('rect');
}
};
var clickFHRect = function() {//手绘矩形
if (toolButtonClick('#tool_fhrect')) {
svgCanvas.setMode('fhrect');
}
};
var clickCircle = function() {//圆
if (toolButtonClick('#tool_circle')) {
svgCanvas.setMode('circle');
}
};
var clickEllipse = function() {//椭圆
if (toolButtonClick('#tool_ellipse')) {
svgCanvas.setMode('ellipse');
}
};
var clickFHEllipse = function() {//手绘椭圆
if (toolButtonClick('#tool_fhellipse')) {
svgCanvas.setMode('fhellipse');
}
};
var clickImage = function() {//图像
if (toolButtonClick('#tool_image')) {
svgCanvas.setMode('image');
}
};
var clickZoom = function() {//缩放
if (toolButtonClick('#tool_zoom')) {
svgCanvas.setMode('zoom');
workarea.css('cursor', zoomInIcon);
}
};
var zoomImage = function(multiplier) {
var res = svgCanvas.getResolution();
multiplier = multiplier ? res.zoom * multiplier : 1;
// setResolution(res.w * multiplier, res.h * multiplier, true);
$('#zoom').val(multiplier * 100);
svgCanvas.setZoom(multiplier);
zoomDone();
updateCanvas(true);
};
var dblclickZoom = function() {
if (toolButtonClick('#tool_zoom')) {
zoomImage();
setSelectMode();
}
};
var clickText = function() {//文本
if (toolButtonClick('#tool_text')) {
svgCanvas.setMode('text');
}
};
// Delete is a contextual tool that only appears in the ribbon if
// an element has been selected
var deleteSelected = function() {//删除
if (selectedElement != null || multiselected) {
svgCanvas.deleteSelectedElements();
}
};
var cutSelected = function() {//剪切
if (selectedElement != null || multiselected) {
svgCanvas.cutSelectedElements();
}
};
var copySelected = function() {//复制
if (selectedElement != null || multiselected) {
svgCanvas.copySelectedElements();
}
};
var pasteInCenter = function() {//粘贴
var zoom = svgCanvas.getZoom();
var x = (workarea[0].scrollLeft + workarea.width()/2)/zoom - svgCanvas.contentW;
var y = (workarea[0].scrollTop + workarea.height()/2)/zoom - svgCanvas.contentH;
svgCanvas.pasteElements('point', x, y);
};
var moveToTopSelected = function() {//顶部对齐
if (selectedElement != null) {
svgCanvas.moveToTopSelectedElement();
}
};
var moveToBottomSelected = function() {//底部对齐
if (selectedElement != null) {
svgCanvas.moveToBottomSelectedElement();
}
};
var moveUpDownSelected = function(dir) {
if (selectedElement != null) {
svgCanvas.moveUpDownSelected(dir);
}
};
var convertToPath = function() {
if (selectedElement != null) {
svgCanvas.convertToPath();
}
};
var reorientPath = function() {
if (selectedElement != null) {
path.reorient();
}
};
var moveSelected = function(dx,dy) {
if (selectedElement != null || multiselected) {
if (curConfig.gridSnapping) {
// Use grid snap value regardless of zoom level
var multi = svgCanvas.getZoom() * curConfig.snappingStep;
dx *= multi;
dy *= multi;
}
svgCanvas.moveSelectedElements(dx,dy);
}
};
var linkControlPoints = function() {
$('#tool_node_link').toggleClass('push_button_pressed tool_button');
var linked = $('#tool_node_link').hasClass('push_button_pressed');
path.linkControlPoints(linked);
};
var clonePathNode = function() {
if (path.getNodePoint()) {
path.clonePathNode();
}
};
var deletePathNode = function() {
if (path.getNodePoint()) {
path.deletePathNode();
}
};
var addSubPath = function() {
var button = $('#tool_add_subpath');
var sp = !button.hasClass('push_button_pressed');
button.toggleClass('push_button_pressed tool_button');
path.addSubPath(sp);
};
var opencloseSubPath = function() {
path.opencloseSubPath();
};
var selectNext = function() {
svgCanvas.cycleElement(1);
};
var selectPrev = function() {
svgCanvas.cycleElement(0);
};
var rotateSelected = function(cw, step) {
if (selectedElement == null || multiselected) {return;}
if (!cw) {step *= -1;}
var angle = parseFloat($('#angle').val()) + step;
svgCanvas.setRotationAngle(angle);
updateContextPanel();
};
var clickBold = function() {//文字设置黑体
svgCanvas.setBold( !svgCanvas.getBold() );
updateContextPanel();
return false;
};
var clickItalic = function() {//文字设置斜体
svgCanvas.setItalic( !svgCanvas.getItalic() );
updateContextPanel();
return false;
};
var exportAndShare = function(type){
var prompt_text = '请选择输出图片的格式: ';
if(type == "share"){
prompt_text = '请选择分享图片的格式: ';
}
$.select(prompt_text, ['PNG','JPEG', 'BMP', 'WEBP'], function (imgType) { // todo: replace hard-coded msg with uiStrings.notification.
if (!imgType) {
return;
}
$("#spinner").css("display","block");
var str = (new XMLSerializer()).serializeToString($('#svgcontent')[0]);
var xmlObj = $.parseXML(str);//xml对象
var svg = $(xmlObj).find("svg");
var imageObj = $(xmlObj).find("image");
var viewBox = document.getElementById("svgcontent").getAttribute("viewBox");
var height = parseInt(viewBox.split(' ')[3]);
var width = parseInt(viewBox.split(' ')[2]);
if(!this.scaleClick){
var dpi = 288;//默认dpi
var scale = mapProperties.scale;//比例尺
var size = calcMapSize(scale);//地图尺寸
var mapPixelWidth = dpi*size.w/2.54;//该分辨率下地图像素宽
this.scaleClick = mapPixelWidth/mapProperties.width;
}
var mapScale = this.scaleClick == 0 ? 4 : this.scaleClick;
var svgScale = mapScale/mapProperties.zoom;
svg.attr("height",height*svgScale);
svg.attr("width",width*svgScale);
var options = window.OPTIONS;
if(document.getElementById("mapImg")&&options){
createPrintMap(mapStyle,mapScale,function(blob){
var objectUrl = window.URL.createObjectURL(blob);
getDataUri(objectUrl, function(dataUri) {
url = dataUri;
imageObj.attr("xlink:href",url);
var quality = parseInt($('#image-slider').val(), 10)/100;
if((/Trident\/7\./).test(navigator.userAgent)||(/Trident\/6\./).test(navigator.userAgent)){//IE10/IE11
svg.removeAttr("x");
svg.removeAttr("y");
ieDownload(svg[0],imgType,quality)
}else{
str = (new XMLSerializer()).serializeToString(xmlObj);
downLoad(str,imgType,quality);
}
});
});
}else{
var quality = parseInt($('#image-slider').val(), 10)/100;
if((/Trident\/7\./).test(navigator.userAgent)||(/Trident\/6\./).test(navigator.userAgent)){
ieDownload()
}else{
str = (new XMLSerializer()).serializeToString(xmlObj);
downLoad(str,imgType,quality);
}
}
function ieDownload(svg,imgType,quality){
if(imgType==="JPEG"||imgType==="WEBP"){
var quality=quality||1;
}
svg.toDataURL("image/png", {
callback: function(data) {
var image = new Image();
image.crossOrigin = "Anonymous";
image.setAttribute("src", data)
image.onload=function(){
onSvgImageLoad(this,imgType,quality);
}
}
})
}
function downLoad(str,imgType,quality){
if(imgType==="JPEG"||imgType==="WEBP"){
var quality=quality||1;
}
var svgXml = str;
var image1 = new Image();
image1.src = 'data:image/svg+xml;base64,' + window.btoa(unescape(encodeURIComponent(svgXml))); //给图片对象写入base64编码的svg流
image1.onload=function(){
onSvgImageLoad(this,imgType,quality);
}
};
function onSvgImageLoad(image,imgType,quality){
var canvas = document.getElementById('myCanvas'); //准备空画布
document.getElementById('myCanvas').setAttribute("width",image.width);
document.getElementById('myCanvas').setAttribute("height",image.height);
var context = canvas.getContext('2d'); //取得画布的2d绘图上下文
context.fillStyle = "#ffffff";
context.fillRect(0,0,image.width,image.height);
context.drawImage(image, 0, 0);
var filename = document.getElementById("title_name").innerHTML||"辅助决策用图";
if(imgType==="JPEG"){
canvas.toBlob(function(blob) {
if(type === "share"){
uploadImg(blob,imgType,filename)
}else if(type === "export"){
$("#spinner").css("display","none");
saveAs(blob, filename+".jpg");
}
},"image/jpeg",quality);
}else if(imgType==="WEBP"){
canvas.toBlob(function(blob) {
if(type === "share"){
uploadImg(blob,imgType,filename)
}else if(type === "export"){
$("#spinner").css("display","none");
saveAs(blob, filename+".webp");
}
},"image/webp",quality);
}else if(imgType==="PNG"){
canvas.toBlob(function(blob) {
if(type === "share"){
uploadImg(blob,imgType,filename)
}else if(type === "export"){
$("#spinner").css("display","none");
saveAs(blob, filename+".png");
}
},"image/png");
}else if(imgType==="BMP"){
canvas.toBlob(function(blob) {
if(type === "share"){
uploadImg(blob,imgType,filename)
}else if(type === "export"){
$("#spinner").css("display","none");
saveAs(blob, filename+".bmp");
}
},"image/bmp");
}
}
function getDataUri(url, callback) {
var image2 = new Image();
image2.onload = function () {
var canvas = document.createElement('canvas');
canvas.width = this.width; // or 'width' if you want a special/scaled size
canvas.height = this.height; // or 'height' if you want a special/scaled size
canvas.getContext('2d').drawImage(this, 0, 0);
// Get raw image data
var raw="data:image/png;base64,"+canvas.toDataURL('image/png').replace(/^data:image\/(png|jpg);base64,/, '');
callback(raw);
};
image2.crossOrigin = "Anonymous";
image2.src = url;
};
function uploadImg(blob,imgType,filename){
var options = window.OPTIONS;
var upload_url = options.API.uploads + '/' + options.username+'?access_token='+options.access_token;
var location = options.location;
if(options.selectedDistrict){
location = options.selectedDistrict;
}
var formData = new FormData();
formData.append("image", blob, filename+"."+imgType.toLowerCase());
formData.append('year', new Date().getFullYear());
formData.append('name', filename);
formData.append('location', location);
if(options.scale){
formData.append('scale',options.scale);
}
var xhr = new XMLHttpRequest();
//设置回调函数
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
var b = xhr.responseText;
if(b){
$("#spinner").css("display","none");
alert("已成功分享到决策用图!");
}else{
$("#spinner").css("display","none");
alert("分享失败!");
}
}
};
xhr.open('POST', upload_url, true);
xhr.send(formData);
}
}, function () {
var sel = $(this);
if (sel.val() === 'JPEG' || sel.val() === 'WEBP') {
if (!$('#image-slider').length) {
$('<div style="margin-top: 10px;"><label>压缩质量: <input id="image-slider" type="range" min="1" max="100" value="92" style="background-color: #eee;border-radius: 15px;-webkit-appearance: none;height: 10px;width: 240px;margin-left: 5px;-webkit-box-shadow: 0 1px 0 0px #959595, 0 1px 0 #959595 inset, 0px 2px 10px 0px #959595 inset, 1px 0px 2px rgba(0, 0, 0, 0.4) inset, 0 0px 1px rgba(0, 0, 0, 0.6) inset;"/></label></div>').appendTo(sel.parent()); // Todo: i18n-ize label
}
}
else {
$('#image-slider').parent().remove();
}
});
var sel = $("#dialog_content select");
if (!$('#image-resolution').length) {
$('<div id="image-resolution"><span>分辨率: </span><div class="resolution"><span>72</span></div><div class="resolution"><span>144</span></div><div class="resolution"><span>216</span></div><div class="resolution click"><span>288</span></div></div>').appendTo(sel.parent()); // Todo: i18n-ize label
var that = this;
that.scaleClick = 0;
$('#image-resolution .resolution').bind('click',function(e){
$('#image-resolution .resolution').removeClass('click');
var parent = $(e.target).parent(".resolution");
parent.length == 0 ? $(e.target).addClass('click') : parent.addClass('click');
var dpi = parseInt($(e.target).text());
var scale = mapProperties.scale;//比例尺
var size = calcMapSize(scale);//地图尺寸
var mapPixelWidth = dpi*size.w/2.54;//该分辨率下地图像素宽
that.scaleClick = mapPixelWidth/mapProperties.width;
});
}
};
//新增分享到决策用图模块
//制图————分享
var clickShare = function(){
exportAndShare('share');
};
//制图————导出
var clickExport = function() {
exportAndShare('export');
};
var clickUndo = function() {
if (undoMgr.getUndoStackSize() > 0) {
undoMgr.undo();
populateLayers();
}
};
var clickRedo = function() {
if (undoMgr.getRedoStackSize() > 0) {
undoMgr.redo();
populateLayers();
}
};
var clickGroup = function() {//组合或取消组合
// group
if (multiselected) {
svgCanvas.groupSelectedElements();
}
// ungroup
else if (selectedElement) {
svgCanvas.ungroupSelectedElement();
}
};
$('#svg_docprops_container, #svg_prefs_container').draggable({cancel: 'button,fieldset', containment: 'window'});
//“制图”菜单点击“输出属性”
var showDocProperties = function() {
if (docprops) {return;}
docprops = true;
// This selects the correct radio button by using the array notation
$('#image_save_opts input').val([$.pref('img_save')]);
// update resolution option with actual resolution
var res = svgCanvas.getResolution();
if (curConfig.baseUnit !== 'px') {
res.w = svgedit.units.convertUnit(res.w) + curConfig.baseUnit;
res.h = svgedit.units.convertUnit(res.h) + curConfig.baseUnit;
}
$('#canvas_width').val(res.w);
$('#canvas_height').val(res.h);
var filename = document.getElementById("title_name").innerHTML;
$('#canvas_title').val(filename);
$('#tool_docprops_save').bind('mouseout',function(e){
$('#tool_docprops_save').removeClass('mouse');
});
$('#tool_docprops_save').bind('mouseover',function(e){
$(e.target).addClass('mouse');
});
$('#tool_docprops_cancel').bind('mouseout',function(e){
$('#tool_docprops_cancel').removeClass('mouse');
});
$('#tool_docprops_cancel').bind('mouseover',function(e){
$(e.target).addClass('mouse');
});
$('#svg_docprops').show();
};
//“制图”菜单点击“选项”
var showPreferences = function() {
if (preferences) {return;}
preferences = true;
$('#main_menu').hide();
// Update background color with current one
var blocks = $('#bg_blocks div');
var cur_bg = 'cur_background';
var canvas_bg = curPrefs.bkgd_color;
var url = $.pref('bkgd_url');
blocks.each(function() {
var blk = $(this);
var is_bg = blk.css('background-color') == canvas_bg;
blk.toggleClass(cur_bg, is_bg);
if (is_bg) {$('#canvas_bg_url').removeClass(cur_bg);}
});
if (!canvas_bg) {blocks.eq(0).addClass(cur_bg);}
if (url) {
$('#canvas_bg_url').val(url);
}
$('#tool_prefs_save').bind('mouseout',function(e){
$('#tool_prefs_save').removeClass('mouse');
});
$('#tool_prefs_save').bind('mouseover',function(e){
$(e.target).addClass('mouse');
});
$('#tool_prefs_cancel').bind('mouseout',function(e){
$('#tool_prefs_cancel').removeClass('mouse');
});
$('#tool_prefs_cancel').bind('mouseover',function(e){
$(e.target).addClass('mouse');
});
$('#svg_prefs').show();
};
var hideSourceEditor = function() {
$('#svg_source_editor').hide();
editingsource = false;
$('#svg_source_textarea').blur();
};
var saveSourceEditor = function() {
if (!editingsource) {return;}
var saveChanges = function() {
svgCanvas.clearSelection();
hideSourceEditor();
zoomImage();
populateLayers();
updateTitle();
prepPaints();
};
if (!svgCanvas.setSvgString($('#svg_source_textarea').val())) {
$.confirm(uiStrings.notification.QerrorsRevertToSource, function(ok) {
if (!ok) {return false;}
saveChanges();
});
} else {
saveChanges();
}
setSelectMode();
};
var hideDocProperties = function() {
$('#svg_docprops').hide();
$('#canvas_width,#canvas_height').removeAttr('disabled');
$('#paper')[0].selectedIndex = 0;
$('#image_save_opts input').val([$.pref('img_save')]);
docprops = false;
};
var hidePreferences = function() {
$('#svg_prefs').hide();
preferences = false;
};
var saveDocProperties = function() {
// set title
var newTitle = $('#canvas_title').val();
updateTitle(newTitle);
svgCanvas.setDocumentTitle(newTitle);
// update resolution
var width = $('#canvas_width'), w = width.val();
var height = $('#canvas_height'), h = height.val();
if (w != 'fit' && !svgedit.units.isValidUnit('width', w)) {
$.alert(uiStrings.notification.invalidAttrValGiven);
width.parent().addClass('error');
return false;
}
width.parent().removeClass('error');
if (h != 'fit' && !svgedit.units.isValidUnit('height', h)) {
$.alert(uiStrings.notification.invalidAttrValGiven);
height.parent().addClass('error');
return false;
}
height.parent().removeClass('error');
if (!svgCanvas.setResolution(w, h)) {
$.alert(uiStrings.notification.noContentToFitTo);
return false;
}
var scale = mapProperties.scale = Number($("#scale_ratio").val());
updateMapFrame(scale,newTitle);
updateCanvas();
hideDocProperties();
};
var updateMapFrame = function(scale,newTitle){
if(scale){
var width = mapProperties.width*mapProperties.zoom;
var height = mapProperties.height*mapProperties.zoom;
var scaleElement = document.getElementById("scale-text");
if(scaleElement){scaleElement.innerHTML = "比例尺:1:"+scale;}
changeSVGTemple(width,height,newTitle);
}else{
changeSVGTemple(0,0,newTitle);
}
}
var savePreferences = editor.savePreferences = function() {
// Set background
var color = $('#bg_blocks div.cur_background').css('background-color') || '#FFF';
setBackground(color, $('#canvas_bg_url').val());
// set icon size
setIconSize($('#iconsize').val());
curConfig.showRulers = $('#show_rulers')[0].checked;
$('#rulers').toggle(curConfig.showRulers);
if (curConfig.showRulers) {updateRulers();}
curConfig.baseUnit = $('#base_unit').val();
svgCanvas.setConfig(curConfig);
updateCanvas();
hidePreferences();
};
var resetScrollPos = $.noop;
var cancelOverlays = function() {
$('#dialog_box').hide();
if (!editingsource && !docprops && !preferences) {
if (cur_context) {
svgCanvas.leaveContext();
}
return;
}
if (editingsource) {
if (origSource !== $('#svg_source_textarea').val()) {
$.confirm(uiStrings.notification.QignoreSourceChanges, function(ok) {
if (ok) {hideSourceEditor();}
});
} else {
hideSourceEditor();
}
} else if (docprops) {
hideDocProperties();
} else if (preferences) {
hidePreferences();
}
resetScrollPos();
};
var win_wh = {width:$(window).width(), height:$(window).height()};
// Fix for Issue 781: Drawing area jumps to top-left corner on window resize (IE9)
if (svgedit.browser.isIE()) {
(function() {
resetScrollPos = function() {
if (workarea[0].scrollLeft === 0 && workarea[0].scrollTop === 0) {
workarea[0].scrollLeft = curScrollPos.left;
workarea[0].scrollTop = curScrollPos.top;
}
};
curScrollPos = {
left: workarea[0].scrollLeft,
top: workarea[0].scrollTop
};
$(window).resize(resetScrollPos);
editor.ready(function() {
// TODO: Find better way to detect when to do this to minimize
// flickering effect
setTimeout(function() {
resetScrollPos();
}, 500);
});
workarea.scroll(function() {
curScrollPos = {
left: workarea[0].scrollLeft,
top: workarea[0].scrollTop
};
});
}());
}
$(window).resize(function(evt) {
$.each(win_wh, function(type, val) {
var curval = $(window)[type]();
workarea[0]['scroll' + (type === 'width' ? 'Left' : 'Top')] -= (curval - val)/2;
win_wh[type] = curval;
});
setFlyoutPositions();
});
(function() {
workarea.scroll(function() {
// TODO: jQuery's scrollLeft/Top() wouldn't require a null check
if ($('#ruler_x').length != 0) {
$('#ruler_x')[0].scrollLeft = workarea[0].scrollLeft;
}
if ($('#ruler_y').length != 0) {
$('#ruler_y')[0].scrollTop = workarea[0].scrollTop;
}
});
}());
$('#url_notice').click(function() {
$.alert(this.title);
});
// added these event handlers for all the push buttons so they
// behave more like buttons being pressed-in and not images
(function() {
var toolnames = ['clear', 'open', 'save', 'source', 'delete', 'delete_multi', 'paste', 'clone', 'clone_multi', 'move_top', 'move_bottom'];
var all_tools = '';
var cur_class = 'tool_button_current';
$.each(toolnames, function(i, item) {
all_tools += (i ? ',' : '') + '#tool_' + item;
});
$(all_tools).mousedown(function() {
$(this).addClass(cur_class);
}).bind('mousedown mouseout', function() {
$(this).removeClass(cur_class);
});
$('#tool_undo, #tool_redo').mousedown(function() {
if (!$(this).hasClass('disabled')) {$(this).addClass(cur_class);}
}).bind('mousedown mouseout',function() {
$(this).removeClass(cur_class);}
);
}());
// switch modifier key in tooltips if mac
// NOTE: This code is not used yet until I can figure out how to successfully bind ctrl/meta
// in Opera and Chrome
if (svgedit.browser.isMac() && !window.opera) {
var shortcutButtons = ['tool_source', 'tool_undo', 'tool_redo'];
i = shortcutButtons.length;
while (i--) {
var button = document.getElementById(shortcutButtons[i]);
if (button) {
var title = button.title;
var index = title.indexOf('Ctrl+');
button.title = [title.substr(0, index), 'Cmd+', title.substr(index + 5)].join('');
}
}
}
// TODO: go back to the color boxes having white background-color and then setting
// background-image to none.png (otherwise partially transparent gradients look weird)
var colorPicker = function(elem) {
var picker = elem.attr('id') == 'stroke_color' ? 'stroke' : 'fill';
// var opacity = (picker == 'stroke' ? $('#stroke_opacity') : $('#fill_opacity'));
var paint = paintBox[picker].paint;
var title = (picker == 'stroke' ? 'Pick a Stroke Paint and Opacity' : 'Pick a Fill Paint and Opacity');
var pos = elem.offset();
$('#color_picker')
.draggable({cancel: '.jGraduate_tabs, .jGraduate_colPick, .jGraduate_gradPick, .jPicker', containment: 'window'})
.css(curConfig.colorPickerCSS || {'left': pos.left - 140, 'bottom': 40})
.jGraduate(
{
paint: paint,
window: { pickerTitle: title },
images: { clientPath: curConfig.jGraduatePath },
newstop: 'inverse'
},
function(p) {
paint = new $.jGraduate.Paint(p);
paintBox[picker].setPaint(paint);
svgCanvas.setPaint(picker, paint);
$('#color_picker').hide();
},
function() {
$('#color_picker').hide();
});
};
var PaintBox = function(container, type) {
var paintColor, paintOpacity,
cur = curConfig[type === 'fill' ? 'initFill' : 'initStroke'];
// set up gradients to be used for the buttons
var svgdocbox = new DOMParser().parseFromString(
'<svg xmlns="http://www.w3.org/2000/svg"><rect width="16.5" height="16.5"'+
' fill="#' + cur.color + '" opacity="' + cur.opacity + '"/>'+
' <defs><linearGradient id="gradbox_"/></defs></svg>', 'text/xml');
var docElem = svgdocbox.documentElement;
docElem = $(container)[0].appendChild(document.importNode(docElem, true));
docElem.setAttribute('width',16.5);
this.rect = docElem.firstChild;
this.defs = docElem.getElementsByTagName('defs')[0];
this.grad = this.defs.firstChild;
this.paint = new $.jGraduate.Paint({solidColor: cur.color});
this.type = type;
this.setPaint = function(paint, apply) {
this.paint = paint;
var fillAttr = 'none';
var ptype = paint.type;
var opac = paint.alpha / 100;
switch ( ptype ) {
case 'solidColor':
fillAttr = (paint[ptype] != 'none') ? '#' + paint[ptype] : paint[ptype];
break;
case 'linearGradient':
case 'radialGradient':
this.defs.removeChild(this.grad);
this.grad = this.defs.appendChild(paint[ptype]);
var id = this.grad.id = 'gradbox_' + this.type;
fillAttr = 'url(#' + id + ')';
break;
}
this.rect.setAttribute('fill', fillAttr);
this.rect.setAttribute('opacity', opac);
if (apply) {
svgCanvas.setColor(this.type, paintColor, true);
svgCanvas.setPaintOpacity(this.type, paintOpacity, true);
}
};
this.update = function(apply) {
if (!selectedElement) {return;}
var i, len;
var type = this.type;
switch (selectedElement.tagName) {
case 'use':
case 'image':
case 'foreignObject':
// These elements don't have fill or stroke, so don't change
// the current value
return;
case 'g':
case 'a':
var gPaint = null;
var childs = selectedElement.getElementsByTagName('*');
for (i = 0, len = childs.length; i < len; i++) {
var elem = childs[i];
var p = elem.getAttribute(type);
if (i === 0) {
gPaint = p;
} else if (gPaint !== p) {
gPaint = null;
break;
}
}
if (gPaint === null) {
// No common color, don't update anything
paintColor = null;
return;
}
paintColor = gPaint;
paintOpacity = 1;
break;
default:
paintOpacity = parseFloat(selectedElement.getAttribute(type + '-opacity'));
if (isNaN(paintOpacity)) {
paintOpacity = 1.0;
}
var defColor = type === 'fill' ? 'black' : 'none';
paintColor = selectedElement.getAttribute(type) || defColor;
}
if (apply) {
svgCanvas.setColor(type, paintColor, true);
svgCanvas.setPaintOpacity(type, paintOpacity, true);
}
paintOpacity *= 100;
var paint = getPaint(paintColor, paintOpacity, type);
// update the rect inside #fill_color/#stroke_color
this.setPaint(paint);
};
this.prep = function() {
var ptype = this.paint.type;
switch ( ptype ) {
case 'linearGradient':
case 'radialGradient':
var paint = new $.jGraduate.Paint({copy: this.paint});
svgCanvas.setPaint(type, paint);
break;
}
};
};
paintBox.fill = new PaintBox('#fill_color', 'fill');
paintBox.stroke = new PaintBox('#stroke_color', 'stroke');
$('#stroke_width').val(curConfig.initStroke.width);
$('#group_opacity').val(curConfig.initOpacity * 100);
// Use this SVG elem to test vectorEffect support
var testEl = paintBox.fill.rect.cloneNode(false);
testEl.setAttribute('style', 'vector-effect:non-scaling-stroke');
supportsNonSS = (testEl.style.vectorEffect === 'non-scaling-stroke');
testEl.removeAttribute('style');
var svgdocbox = paintBox.fill.rect.ownerDocument;
// Use this to test support for blur element. Seems to work to test support in Webkit
var blurTest = svgdocbox.createElementNS(svgedit.NS.SVG, 'feGaussianBlur');
if (blurTest.stdDeviationX === undefined) {
$('#tool_blur').hide();
}
$(blurTest).remove();
// Test for zoom icon support
(function() {
var pre = '-' + uaPrefix.toLowerCase() + '-zoom-';
var zoom = pre + 'in';
workarea.css('cursor', zoom);
if (workarea.css('cursor') === zoom) {
zoomInIcon = zoom;
zoomOutIcon = pre + 'out';
}
workarea.css('cursor', 'auto');
}());
// Test for embedImage support (use timeout to not interfere with page load)
setTimeout(function() {
svgCanvas.embedImage('images/logo.png', function(datauri) {
if (!datauri) {
// Disable option
$('#image_save_opts [value=embed]').attr('disabled', 'disabled');
$('#image_save_opts input').val(['ref']);
$.pref('img_save', 'ref');
$('#image_opt_embed').css('color', '#666').attr('title', uiStrings.notification.featNotSupported);
}
});
}, 1000);
$('#fill_color, #tool_fill .icon_label').click(function() {
colorPicker($('#fill_color'));
updateToolButtonState();
});
$('#stroke_color, #tool_stroke .icon_label').click(function() {
colorPicker($('#stroke_color'));
updateToolButtonState();
});
$('#group_opacityLabel').click(function() {
$('#opacity_dropdown button').mousedown();
$(window).mouseup();
});
$('#zoomLabel').click(function() {
$('#zoom_dropdown button').mousedown();
$(window).mouseup();
});
$('#tool_move_top').mousedown(function(evt) {
$('#tools_stacking').show();
evt.preventDefault();
});
$('.layer_button').mousedown(function() {
$(this).addClass('layer_buttonpressed');
}).mouseout(function() {
$(this).removeClass('layer_buttonpressed');
}).mouseup(function() {
$(this).removeClass('layer_buttonpressed');
});
$('.push_button').mousedown(function() {
if (!$(this).hasClass('disabled')) {
$(this).addClass('push_button_pressed').removeClass('push_button');
}
}).mouseout(function() {
$(this).removeClass('push_button_pressed').addClass('push_button');
}).mouseup(function() {
$(this).removeClass('push_button_pressed').addClass('push_button');
});
// ask for a layer name
$('#layer_new').click(function() {
var uniqName,
i = svgCanvas.getCurrentDrawing().getNumLayers();
do {
uniqName = uiStrings.layers.layer + ' ' + (++i);
} while(svgCanvas.getCurrentDrawing().hasLayer(uniqName));
$.prompt(uiStrings.notification.enterUniqueLayerName, uniqName, function(newName) {
if (!newName) {return;}
if (svgCanvas.getCurrentDrawing().hasLayer(newName)) {
$.alert(uiStrings.notification.dupeLayerName);
return;
}
svgCanvas.createLayer(newName);
updateContextPanel();
populateLayers();
});
});
function deleteLayer() {
if (svgCanvas.deleteCurrentLayer()) {
updateContextPanel();
populateLayers();
// This matches what SvgCanvas does
// TODO: make this behavior less brittle (svg-editor should get which
// layer is selected from the canvas and then select that one in the UI)
$('#layerlist tr.layer').removeClass('layersel');
$('#layerlist tr.layer:first').addClass('layersel');
}
}
function cloneLayer() {
var name = svgCanvas.getCurrentDrawing().getCurrentLayerName() + ' copy';
$.prompt(uiStrings.notification.enterUniqueLayerName, name, function(newName) {
if (!newName) {return;}
if (svgCanvas.getCurrentDrawing().hasLayer(newName)) {
$.alert(uiStrings.notification.dupeLayerName);
return;
}
svgCanvas.cloneLayer(newName);
updateContextPanel();
populateLayers();
});
}
function mergeLayer() {
if ($('#layerlist tr.layersel').index() == svgCanvas.getCurrentDrawing().getNumLayers()-1) {
return;
}
svgCanvas.mergeLayer();
updateContextPanel();
populateLayers();
}
function moveLayer(pos) {
var curIndex = $('#layerlist tr.layersel').index();
var total = svgCanvas.getCurrentDrawing().getNumLayers();
if (curIndex > 0 || curIndex < total-1) {
curIndex += pos;
svgCanvas.setCurrentLayerPosition(total-curIndex-1);
populateLayers();
}
}
$('#layer_delete').click(deleteLayer);
$('#layer_up').click(function() {
moveLayer(-1);
});
$('#layer_down').click(function() {
moveLayer(1);
});
$('#layer_rename').click(function() {
// var curIndex = $('#layerlist tr.layersel').prevAll().length; // Currently unused
var oldName = $('#layerlist tr.layersel td.layername').text();
$.prompt(uiStrings.notification.enterNewLayerName, '', function(newName) {
if (!newName) {return;}
if (oldName == newName || svgCanvas.getCurrentDrawing().hasLayer(newName)) {
$.alert(uiStrings.notification.layerHasThatName);
return;
}
svgCanvas.renameCurrentLayer(newName);
populateLayers();
});
});
var SIDEPANEL_MAXWIDTH = 300;
var SIDEPANEL_OPENWIDTH = 150;
var sidedrag = -1, sidedragging = false, allowmove = false;
var changeSidePanelWidth = function(delta) {
var rulerX = $('#ruler_x');
$('#sidepanels').width('+=' + delta);
$('#layerpanel').width('+=' + delta);
rulerX.css('right', parseInt(rulerX.css('right'), 10) + delta);
workarea.css('right', parseInt(workarea.css('right'), 10) + delta);
svgCanvas.runExtensions('workareaResized');
};
var resizeSidePanel = function(evt) {
if (!allowmove) {return;}
if (sidedrag == -1) {return;}
sidedragging = true;
var deltaX = sidedrag - evt.pageX;
var sideWidth = $('#sidepanels').width();
if (sideWidth + deltaX > SIDEPANEL_MAXWIDTH) {
deltaX = SIDEPANEL_MAXWIDTH - sideWidth;
sideWidth = SIDEPANEL_MAXWIDTH;
} else if (sideWidth + deltaX < 2) {
deltaX = 2 - sideWidth;
sideWidth = 2;
}
if (deltaX == 0) {return;}
sidedrag -= deltaX;
changeSidePanelWidth(deltaX);
};
// if width is non-zero, then fully close it, otherwise fully open it
// the optional close argument forces the side panel closed
var toggleSidePanel = function(close) {
var w = $('#sidepanels').width();
var deltaX = (w > 2 || close ? 2 : SIDEPANEL_OPENWIDTH) - w;
changeSidePanelWidth(deltaX);
};
$('#sidepanel_handle')
.mousedown(function(evt) {
sidedrag = evt.pageX;
$(window).mousemove(resizeSidePanel);
allowmove = false;
// Silly hack for Chrome, which always runs mousemove right after mousedown
setTimeout(function() {
allowmove = true;
}, 20);
})
.mouseup(function(evt) {
if (!sidedragging) {toggleSidePanel();}
sidedrag = -1;
sidedragging = false;
});
$(window).mouseup(function() {
sidedrag = -1;
sidedragging = false;
$('#svg_editor').unbind('mousemove', resizeSidePanel);
});
populateLayers();
var centerCanvas = function() {
// this centers the canvas vertically in the workarea (horizontal handled in CSS)
workarea.css('line-height', workarea.height() + 'px');
};
$(window).bind('load resize', centerCanvas);
function stepFontSize(elem, step) {
var orig_val = Number(elem.value);
var sug_val = orig_val + step;
var increasing = sug_val >= orig_val;
if (step === 0) {return orig_val;}
if (orig_val >= 24) {
if (increasing) {
return Math.round(orig_val * 1.1);
}
return Math.round(orig_val / 1.1);
}
if (orig_val <= 1) {
if (increasing) {
return orig_val * 2;
}
return orig_val / 2;
}
return sug_val;
}
function stepZoom(elem, step) {
var orig_val = Number(elem.value);
if (orig_val === 0) {return 100;}
var sug_val = orig_val + step;
if (step === 0) {return orig_val;}
if (orig_val >= 100) {
return sug_val;
}
if (sug_val >= orig_val) {
return orig_val * 2;
}
return orig_val / 2;
}
$("input:radio[name='canvas_layout']").change(function(){
if($('#paper option:selected').val()!=='content'){
var width = $('#canvas_width').val();
var height = $('#canvas_height').val();
$('#canvas_width').val(height);
$('#canvas_height').val(width);
}
});
$('#paper').change(function() {
var layouts = $("input:radio[name='canvas_layout']");
var wh = $('#canvas_width,#canvas_height');
if (!this.selectedIndex) {
if ($('#canvas_width').val() == 'fit') {
wh.removeAttr('disabled').val(100);
}
} else if (this.value == 'content') {//适应内容
var frameWidth = mapProperties.width*mapProperties.zoom+2*(rect_gap+left_gap);
var frameheight = mapProperties.height*mapProperties.zoom+top_gap+bottom_gap+2*rect_gap;
var cmWidth = svgedit.units.convertUnit(frameWidth,"cm");
var cmHeight = svgedit.units.convertUnit(frameheight,"cm");
$('#canvas_width').val(cmWidth+"cm");
$('#canvas_height').val(cmHeight+"cm");
} else {
var dims = this.value.split('x');
if(layouts[0].checked){
$('#canvas_width').val(dims[0]);
$('#canvas_height').val(dims[1]);
}else{
$('#canvas_width').val(dims[1]);
$('#canvas_height').val(dims[0]);
}
wh.removeAttr('disabled');
}
});
$('#scale_ratio').change(function() {
var scale = Number(this.value);
window.OPTIONS.scale = scale;
var size = calcMapSize(scale);
var width = svgedit.units.convertToNum("width",size.w+"cm");
var height = svgedit.units.convertToNum("width",size.h+"cm");
mapProperties.zoom = width/mapProperties.width;
});
//Prevent browser from erroneously repopulating fields
$('input,select').attr('autocomplete', 'off');
// Associate all button actions as well as non-button keyboard shortcuts
Actions = (function() {
// sel:'selector', fn:function, evt:'event', key:[key, preventDefault, NoDisableInInput]
var tool_buttons = [
{sel: '#tool_select', fn: clickSelect, evt: 'click', key: ['V', true]},
{sel: '#tool_fhpath', fn: clickFHPath, evt: 'click', key: ['Q', true]},
{sel: '#tool_line', fn: clickLine, evt: 'click', key: ['L', true]},
{sel: '#tool_rect', fn: clickRect, evt: 'mouseup', key: ['R', true], parent: '#tools_rect', icon: 'rect'},
{sel: '#tool_square', fn: clickSquare, evt: 'mouseup', parent: '#tools_rect', icon: 'square'},
{sel: '#tool_fhrect', fn: clickFHRect, evt: 'mouseup', parent: '#tools_rect', icon: 'fh_rect'},
{sel: '#tool_ellipse', fn: clickEllipse, evt: 'mouseup', key: ['E', true], parent: '#tools_ellipse', icon: 'ellipse'},
{sel: '#tool_circle', fn: clickCircle, evt: 'mouseup', parent: '#tools_ellipse', icon: 'circle'},
{sel: '#tool_fhellipse', fn: clickFHEllipse, evt: 'mouseup', parent: '#tools_ellipse', icon: 'fh_ellipse'},
{sel: '#tool_text', fn: clickText, evt: 'click', key: ['T', true]},
{sel: '#tool_zoom', fn: clickZoom, evt: 'mouseup', key: ['Z', true]},
{sel: '#tool_export', fn: clickExport, evt: 'mouseup'},
{sel: '#tool_share', fn: clickShare, evt: 'mouseup'},
{sel: '#tool_source', fn: showSourceEditor, evt: 'click', key: ['U', true]},
{sel: '#tool_source_cancel,.overlay,#tool_docprops_cancel,#tool_prefs_cancel', fn: cancelOverlays, evt: 'click', key: ['esc', false, false], hidekey: true},
{sel: '#tool_source_save', fn: saveSourceEditor, evt: 'click'},
{sel: '#tool_docprops_save', fn: saveDocProperties, evt: 'click'},
{sel: '#tool_docprops', fn: showDocProperties, evt: 'mouseup'},
{sel: '#tool_prefs_save', fn: savePreferences, evt: 'click'},
{sel: '#tool_prefs_option', fn: function() {showPreferences(); return false;}, evt: 'mouseup'},
{sel: '#tool_undo', fn: clickUndo, evt: 'click'},
{sel: '#tool_redo', fn: clickRedo, evt: 'click'},
{sel: '#tool_group_elements', fn: clickGroup, evt: 'click', key: ['G', true]},
{sel: '#tool_ungroup', fn: clickGroup, evt: 'click'},
{sel: '#tool_bold', fn: clickBold, evt: 'mousedown'},
{sel: '#tool_italic', fn: clickItalic, evt: 'mousedown'},
{sel: '#sidepanel_handle', fn: toggleSidePanel, key: ['X']},
// Shortcuts not associated with buttons
{key: 'ctrl+left', fn: function(){rotateSelected(0,1);}},
{key: 'ctrl+right', fn: function(){rotateSelected(1,1);}},
{key: 'ctrl+shift+left', fn: function(){rotateSelected(0,5);}},
{key: 'ctrl+shift+right', fn: function(){rotateSelected(1,5);}},
{key: 'shift+O', fn: selectPrev},
{key: 'shift+P', fn: selectNext},
{key: [modKey+'up', true], fn: function(){zoomImage(2);}},
{key: [modKey+'down', true], fn: function(){zoomImage(0.5);}},
{key: [modKey+']', true], fn: function(){moveUpDownSelected('Up');}},
{key: [modKey+'[', true], fn: function(){moveUpDownSelected('Down');}},
{key: ['up', true], fn: function(){moveSelected(0,-1);}},
{key: ['down', true], fn: function(){moveSelected(0,1);}},
{key: ['left', true], fn: function(){moveSelected(-1,0);}},
{key: ['right', true], fn: function(){moveSelected(1,0);}},
{key: 'shift+up', fn: function(){moveSelected(0,-10);}},
{key: 'shift+down', fn: function(){moveSelected(0,10);}},
{key: 'shift+left', fn: function(){moveSelected(-10,0);}},
{key: 'shift+right', fn: function(){moveSelected(10,0);}},
{key: ['alt+up', true], fn: function(){svgCanvas.cloneSelectedElements(0,-1);}},
{key: ['alt+down', true], fn: function(){svgCanvas.cloneSelectedElements(0,1);}},
{key: ['alt+left', true], fn: function(){svgCanvas.cloneSelectedElements(-1,0);}},
{key: ['alt+right', true], fn: function(){svgCanvas.cloneSelectedElements(1,0);}},
{key: ['alt+shift+up', true], fn: function(){svgCanvas.cloneSelectedElements(0,-10);}},
{key: ['alt+shift+down', true], fn: function(){svgCanvas.cloneSelectedElements(0,10);}},
{key: ['alt+shift+left', true], fn: function(){svgCanvas.cloneSelectedElements(-10,0);}},
{key: ['alt+shift+right', true], fn: function(){svgCanvas.cloneSelectedElements(10,0);}},
{key: 'A', fn: function(){svgCanvas.selectAllInCurrentLayer();}},
// Standard shortcuts
{key: modKey+'z', fn: clickUndo},
{key: modKey + 'shift+z', fn: clickRedo},
{key: modKey + 'y', fn: clickRedo},
{key: modKey+'x', fn: cutSelected},
{key: modKey+'c', fn: copySelected},
{key: modKey+'v', fn: pasteInCenter}
];
// Tooltips not directly associated with a single function
var key_assocs = {
'4/Shift+4': '#tools_rect_show',
'5/Shift+5': '#tools_ellipse_show'
};
return {
setAll: function() {
var flyouts = {};
$.each(tool_buttons, function(i, opts) {
// Bind function to button
var btn;
if (opts.sel) {
btn = $(opts.sel);
if (btn.length == 0) {return true;} // Skip if markup does not exist
if (opts.evt) {
if (svgedit.browser.isTouch() && opts.evt === 'click') {
opts.evt = 'mousedown';
}
btn[opts.evt](opts.fn);
}
// Add to parent flyout menu, if able to be displayed
if (opts.parent && $(opts.parent + '_show').length != 0) {
var f_h = $(opts.parent);
if (!f_h.length) {
f_h = makeFlyoutHolder(opts.parent.substr(1));
}
f_h.append(btn);
if (!$.isArray(flyouts[opts.parent])) {
flyouts[opts.parent] = [];
}
flyouts[opts.parent].push(opts);
}
}
// Bind function to shortcut key
if (opts.key) {
// Set shortcut based on options
var keyval, disInInp = true, fn = opts.fn, pd = false;
if ($.isArray(opts.key)) {
keyval = opts.key[0];
if (opts.key.length > 1) {pd = opts.key[1];}
if (opts.key.length > 2) {disInInp = opts.key[2];}
} else {
keyval = opts.key;
}
keyval += '';
$.each(keyval.split('/'), function(i, key) {
$(document).bind('keydown', key, function(e) {
fn();
if (pd) {
e.preventDefault();
}
// Prevent default on ALL keys?
return false;
});
});
// Put shortcut in title
if (opts.sel && !opts.hidekey && btn.attr('title')) {
var newTitle = btn.attr('title').split('[')[0] + ' (' + keyval + ')';
key_assocs[keyval] = opts.sel;
// Disregard for menu items
if (!btn.parents('#main_menu').length) {
btn.attr('title', newTitle);
}
}
}
});
// Setup flyouts
setupFlyouts(flyouts);
$(window).bind('keydown', 'tab', function(e) {
if (ui_context === 'canvas') {
e.preventDefault();
selectNext();
}
}).bind('keydown', 'shift+tab', function(e) {
if (ui_context === 'canvas') {
e.preventDefault();
selectPrev();
}
});
$('#tool_zoom').dblclick(dblclickZoom);
},
setTitles: function() {
$.each(key_assocs, function(keyval, sel) {
var menu = ($(sel).parents('#main_menu').length);
$(sel).each(function() {
var t;
if (menu) {
t = $(this).text().split(' [')[0];
} else {
t = this.title.split(' [')[0];
}
var key_str = '';
// Shift+Up
$.each(keyval.split('/'), function(i, key) {
var mod_bits = key.split('+'), mod = '';
if (mod_bits.length > 1) {
mod = mod_bits[0] + '+';
key = mod_bits[1];
}
key_str += (i?'/':'') + mod + (uiStrings['key_'+key] || key);
});
if (menu) {
this.lastChild.textContent = t +' ['+key_str+']';
} else {
this.title = t +' ['+key_str+']';
}
});
});
},
getButtonData: function(sel) {
var b;
$.each(tool_buttons, function(i, btn) {
if (btn.sel === sel) {b = btn;}
});
return b;
}
};
}());
Actions.setAll();
// Select given tool
editor.ready(function() {
var tool,
itool = curConfig.initTool,
container = $('#tools_left, #svg_editor .tools_flyout'),
pre_tool = container.find('#tool_' + itool),
reg_tool = container.find('#' + itool);
if (pre_tool.length) {
tool = pre_tool;
} else if (reg_tool.length) {
tool = reg_tool;
} else {
tool = $('#tool_select');
}
tool.click().mouseup();
if (curConfig.showlayers) {
toggleSidePanel();
}
$('#rulers').toggle(!!curConfig.showRulers);
if (curConfig.showRulers) {
$('#show_rulers')[0].checked = true;
}
if (curConfig.baseUnit) {
$('#base_unit').val(curConfig.baseUnit);
}
});
// init SpinButtons
$('#rect_rx').SpinButton({ min: 0, max: 1000, callback: changeRectRadius });
$('#stroke_width').SpinButton({ min: 0, max: 99, smallStep: 0.1, callback: changeStrokeWidth });
$('#angle').SpinButton({ min: -180, max: 180, step: 5, callback: changeRotationAngle });
$('#font_size').SpinButton({ min: 0.001, stepfunc: stepFontSize, callback: changeFontSize });
$('#group_opacity').SpinButton({ min: 0, max: 100, step: 5, callback: changeOpacity });
$('#blur').SpinButton({ min: 0, max: 10, step: 0.1, callback: changeBlur });
$('#zoom').SpinButton({ min: 0.001, max: 10000, step: 50, stepfunc: stepZoom, callback: changeZoom })
// Set default zoom
.val(svgCanvas.getZoom() * 100);
$('#workarea').contextMenu({
menu: 'cmenu_canvas',
inSpeed: 0
},
function(action, el, pos) {
switch (action) {
case 'delete':
deleteSelected();
break;
case 'cut':
cutSelected();
break;
case 'copy':
copySelected();
break;
case 'paste':
svgCanvas.pasteElements();
break;
case 'paste_in_place':
svgCanvas.pasteElements('in_place');
break;
case 'group':
case 'group_elements':
svgCanvas.groupSelectedElements();
break;
case 'ungroup':
svgCanvas.ungroupSelectedElement();
break;
case 'move_front':
moveToTopSelected();
break;
case 'move_up':
moveUpDownSelected('Up');
break;
case 'move_down':
moveUpDownSelected('Down');
break;
case 'move_back':
moveToBottomSelected();
break;
default:
if (svgedit.contextmenu && svgedit.contextmenu.hasCustomHandler(action)) {
svgedit.contextmenu.getCustomHandler(action).call();
}
break;
}
if (svgCanvas.clipBoard.length) {
canv_menu.enableContextMenuItems('#paste,#paste_in_place');
}
}
);
var lmenu_func = function(action, el, pos) {
switch ( action ) {
case 'dupe':
cloneLayer();
break;
case 'delete':
deleteLayer();
break;
case 'merge_down':
mergeLayer();
break;
case 'merge_all':
svgCanvas.mergeAllLayers();
updateContextPanel();
populateLayers();
break;
}
};
$('#layerlist').contextMenu({
menu: 'cmenu_layers',
inSpeed: 0
},
lmenu_func
);
$('#layer_moreopts').contextMenu({
menu: 'cmenu_layers',
inSpeed: 0,
allowLeft: true
},
lmenu_func
);
$('.contextMenu li').mousedown(function(ev) {
ev.preventDefault();
});
$('#cmenu_canvas li').disableContextMenu();
canv_menu.enableContextMenuItems('#delete,#cut,#copy');
window.addEventListener('beforeunload', function(e) {
// Suppress warning if page is empty
if (undoMgr.getUndoStackSize() === 0) {
editor.showSaveWarning = false;
}
// showSaveWarning is set to 'false' when the page is saved.
if (!curConfig.no_save_warning && editor.showSaveWarning) {
// Browser already asks question about closing the page
e.returnValue = uiStrings.notification.unsavedChanges; // Firefox needs this when beforeunload set by addEventListener (even though message is not used)
return uiStrings.notification.unsavedChanges;
}
}, false);
editor.openPrep = function(func) {
$('#main_menu').hide();
if (undoMgr.getUndoStackSize() === 0) {
func(true);
} else {
$.confirm(uiStrings.notification.QwantToOpen, func);
}
};
function onDragEnter(e) {
e.stopPropagation();
e.preventDefault();
// and indicator should be displayed here, such as "drop files here"
}
function onDragOver(e) {
e.stopPropagation();
e.preventDefault();
}
function onDragLeave(e) {
e.stopPropagation();
e.preventDefault();
// hypothetical indicator should be removed here
}
// Use HTML5 File API: http://www.w3.org/TR/FileAPI/
// if browser has HTML5 File API support, then we will show the open menu item
// and provide a file input to click. When that change event fires, it will
// get the text contents of the file and send it to the canvas
if (window.FileReader) {
var importImage = function(e) {
$.process_cancel(uiStrings.notification.loadingImage);
e.stopPropagation();
e.preventDefault();
$('#workarea').removeAttr('style');
$('#main_menu').hide();
var file = (e.type == 'drop') ? e.dataTransfer.files[0] : this.files[0];
if (!file) {
$('#dialog_box').hide();
return;
}
if (file.type.indexOf('image') != -1) {
// Detected an image
// svg handling
var reader;
if (file.type.indexOf('svg') != -1) {
reader = new FileReader();
reader.onloadend = function(e) {
var newElement = svgCanvas.importSvgString(e.target.result, true);
svgCanvas.ungroupSelectedElement();
svgCanvas.ungroupSelectedElement();
svgCanvas.groupSelectedElements();
svgCanvas.alignSelectedElements('m', 'page');
svgCanvas.alignSelectedElements('c', 'page');
// highlight imported element, otherwise we get strange empty selectbox
svgCanvas.selectOnly([newElement]);
$('#dialog_box').hide();
};
reader.readAsText(file);
}
else {
//bitmap handling
reader = new FileReader();
reader.onloadend = function(e) {
// let's insert the new image until we know its dimensions
var insertNewImage = function(width, height) {
var newImage = svgCanvas.addSvgElementFromJson({
element: 'image',
attr: {
x: 0,
y: 0,
width: width,
height: height,
id: svgCanvas.getNextId(),
style: 'pointer-events:inherit'
}
});
svgCanvas.setHref(newImage, e.target.result);
svgCanvas.selectOnly([newImage]);
svgCanvas.alignSelectedElements('m', 'page');
svgCanvas.alignSelectedElements('c', 'page');
updateContextPanel();
$('#dialog_box').hide();
};
// create dummy img so we know the default dimensions
var imgWidth = 100;
var imgHeight = 100;
var img = new Image();
img.src = e.target.result;
img.style.opacity = 0;
img.onload = function() {
imgWidth = img.offsetWidth;
imgHeight = img.offsetHeight;
insertNewImage(imgWidth, imgHeight);
};
};
reader.readAsDataURL(file);
}
}
};
workarea[0].addEventListener('dragenter', onDragEnter, false);
workarea[0].addEventListener('dragover', onDragOver, false);
workarea[0].addEventListener('dragleave', onDragLeave, false);
workarea[0].addEventListener('drop', importImage, false);
var open = $('<input type="file">').change(function() {
var f = this;
editor.openPrep(function(ok) {
if (!ok) {return;}
svgCanvas.clear();
if (f.files.length === 1) {
$.process_cancel(uiStrings.notification.loadingImage);
var reader = new FileReader();
reader.onloadend = function(e) {
loadSvgString(e.target.result);
updateCanvas();
};
reader.readAsText(f.files[0]);
}
});
});
$('#tool_open').show().prepend(open);
var imgImport = $('<input type="file">').change(importImage);
$('#tool_import').show().prepend(imgImport);
}
updateCanvas(true);
// For Compatibility with older extensions
$(function() {
window.svgCanvas = svgCanvas;
svgCanvas.ready = editor.ready;
});
};
editor.ready = function (cb) {
if (!isReady) {
callbacks.push(cb);
} else {
cb();
}
};
editor.runCallbacks = function () {
$.each(callbacks, function() {
this();
});
isReady = true;
};
function createPrintMap(style,scale,callback) {
var options = window.options;
if(options.width>MAX_SIZE||options.height>MAX_SIZE){
$.alert(uiStrings.notification.invalidMapSize);
}
// Calculate pixel ratio
var actualPixelRatio = window.devicePixelRatio;
Object.defineProperty(window, 'devicePixelRatio', {
get: function() {return scale}
});
// Create map container
var hidden = document.createElement('div');
hidden.className = 'hidden-map';
document.body.appendChild(hidden);
var container = document.createElement('div');
container.style.width = options.width+'px';
container.style.height = options.height+'px';
hidden.appendChild(container);
// Render map
mapboxgl.accessToken = 'pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpbG10dnA3NzY3OTZ0dmtwejN2ZnUycjYifQ.1W5oTOnWXQ9R1w8u3Oo1yA';
var renderMap = new mapboxgl.Map({
container: container,
center: options.center,
zoom: options.zoom,
bearing:options.bearing,
pitch:options.pitch,
style: style,
interactive: false,
attributionControl: false
});
renderMap.once('load', function() {
renderMap.getCanvas().toBlob(function(blob) {
callback(blob);
});
renderMap.remove();
hidden.parentNode.removeChild(hidden);
Object.defineProperty(window, 'devicePixelRatio', {
get: function() {return actualPixelRatio}
});
});
}
editor.loadFromString = function (str,url) {
var options = window.OPTIONS;
if(options){
var xmlObj = $.parseXML(str);//xml对象
var xmlString;//xml字符串
var map_outside = $(xmlObj).find('#map_outside');
var map_inside = $(xmlObj).find('#map_inside');
right_gap = left_gap = parseFloat(map_outside.attr("x"));
top_gap = parseFloat(map_outside.attr("y"));
rect_gap = parseFloat(map_inside.attr("x"))-left_gap;
var image = $(xmlObj).find("image");
image.attr("xlink:href",url);//替换url
if (window.ActiveXObject){//code for ie
xmlString = xmlObj.xml;
}else{// code for Mozilla, Firefox, Opera, etc.
xmlString = (new XMLSerializer()).serializeToString(xmlObj);
}
editor.ready(function() {
loadSvgString(xmlString,xmlStringLoaded);
});
}else{
var xmlString = str;
editor.ready(function() {
loadSvgString(xmlString);
});
}
function xmlStringLoaded(flag){
if(flag===false){return;}
var img = new Image(); // 创建对象
img.src = url; // 改变图片的src
img.onload = function(){// 加载完成执行
mapProperties.width = this.width;
mapProperties.height = this.height;
var w = this.width+2*(rect_gap+left_gap);
var h = this.height+top_gap+bottom_gap+2*rect_gap;
if (w != 'fit' && !svgedit.units.isValidUnit('width', w)) {
$.alert(uiStrings.notification.invalidAttrValGiven);
return false;
}
if (h != 'fit' && !svgedit.units.isValidUnit('height', h)) {
$.alert(uiStrings.notification.invalidAttrValGiven);
return false;
}
if (!svgCanvas.setResolution(w, h)) {
$.alert(uiStrings.notification.noContentToFitTo);
return false;
}
editor.updateCanvas();
svgCanvas.zoomChanged(window,"100%");//设置100%画布缩放
if(window.OPTIONS.selectedDistrict!==""){
var templateName = window.OPTIONS.templateName;
var title = window.OPTIONS.selectedDistrict+templateName;
changeSVGTemple(this.width,this.height,title);
}else{
changeSVGTemple(this.width,this.height);
}
document.getElementById('mapImg').setAttribute("width",this.width);
document.getElementById('mapImg').setAttribute("height",this.height);
document.getElementById('background').setAttribute("width",w);
document.getElementById('background').setAttribute("height",h);
var date = new Date();
document.getElementById('mapping_time').innerHTML = date.getFullYear() + "年" + (date.getMonth()+1) +"月";
document.getElementById('mapping_organization').innerHTML = options.organization;
//计算比例尺
var merc = new SphericalMercator({
size:256
});
var bbox = window.OPTIONS.bbox;
var ws = merc.forward([bbox[0],bbox[1]]);
var es = merc.forward([bbox[2],bbox[1]]);
var wn = merc.forward([bbox[0],bbox[3]]);
var realWidth = Math.abs(es[0]-ws[0])*100;
var cmWidth = svgedit.units.convertUnit(this.width,"cm");
var scale = parseInt(realWidth/cmWidth);
window.OPTIONS.scale = mapProperties.scale = scale;
$("#scale_ratio").val(scale);
};
}
};
editor.loadFromURL = function (url, opts) {
if (!opts) {opts = {};}
var cache = opts.cache;
var cb = opts.callback;
editor.ready(function() {
$.ajax({
'url': url,
'dataType': 'text',
cache: !!cache,
beforeSend:function(){
$.process_cancel(uiStrings.notification.loadingImage);
},
success: function(str) {
loadSvgString(str, cb);
},
error: function(xhr, stat, err) {
if (xhr.status != 404 && xhr.responseText) {
loadSvgString(xhr.responseText, cb);
} else {
$.alert(uiStrings.notification.URLloadFail + ': \n' + err, cb);
}
},
complete:function(){
$('#dialog_box').hide();
}
});
});
};
editor.loadFromDataURI = function(str) {
editor.ready(function() {
var base64 = false;
var pre = str.match(/^data:image\/svg\+xml;base64,/);
if (pre) {
base64 = true;
}
else {
pre = str.match(/^data:image\/svg\+xml(?:;(?:utf8)?)?,/);
}
if (pre) {
pre = pre[0];
}
var src = str.slice(pre.length);
loadSvgString(base64 ? Utils.decode64(src) : decodeURIComponent(src));
});
};
editor.addExtension = function () {
var args = arguments;
// Note that we don't want this on editor.ready since some extensions
// may want to run before then (like server_opensave).
$(function() {
if (svgCanvas) {svgCanvas.addExtension.apply(this, args);}
});
};
return editor;
}(jQuery));
// Run init once DOM is loaded
$(svgEditor.init);
}());
|
/*!
* This file is part of Weaver.js 1.0.0.
*
* Weaver.js is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any
* later version.
*
* Weaver.js is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* Weaver.js. If not, see <http://www.gnu.org/licenses/>.
*/
// this is put as a global var in the browser
// or it's just a global to this module if commonjs
var weaver;
(function(window){ 'use strict';
// the object iteself is a function that init's an instance of weaver
var $$ = weaver = function(){ // jshint ignore:line
return;
};
$$.fn = {};
$$.version = '1.0.0';
if( typeof module !== 'undefined' && module.exports ){ // expose as a commonjs module
module.exports = weaver;
}
if( typeof define !== 'undefined' && define.amd ){ // expose as an amd/requirejs module
define('weaver', function(){
return weaver;
});
}
// make sure we always register in the window just in case (e.g. w/ derbyjs)
if( window ){
window.weaver = weaver;
}
})( typeof window === 'undefined' ? null : window );
// internal, minimal Promise impl s.t. apis can return promises in old envs
// based on thenable (http://github.com/rse/thenable)
// NB: you must use `new $$.Promise`, because you may have native promises that don't autonew for you
;(function($$){ 'use strict';
/* promise states [Promises/A+ 2.1] */
var STATE_PENDING = 0; /* [Promises/A+ 2.1.1] */
var STATE_FULFILLED = 1; /* [Promises/A+ 2.1.2] */
var STATE_REJECTED = 2; /* [Promises/A+ 2.1.3] */
/* promise object constructor */
var api = function (executor) {
/* optionally support non-constructor/plain-function call */
if (!(this instanceof api))
return new api(executor);
/* initialize object */
this.id = "Thenable/1.0.7";
this.state = STATE_PENDING; /* initial state */
this.fulfillValue = undefined; /* initial value */ /* [Promises/A+ 1.3, 2.1.2.2] */
this.rejectReason = undefined; /* initial reason */ /* [Promises/A+ 1.5, 2.1.3.2] */
this.onFulfilled = []; /* initial handlers */
this.onRejected = []; /* initial handlers */
/* provide optional information-hiding proxy */
this.proxy = {
then: this.then.bind(this)
};
/* support optional executor function */
if (typeof executor === "function")
executor.call(this, this.fulfill.bind(this), this.reject.bind(this));
};
/* promise API methods */
api.prototype = {
/* promise resolving methods */
fulfill: function (value) { return deliver(this, STATE_FULFILLED, "fulfillValue", value); },
reject: function (value) { return deliver(this, STATE_REJECTED, "rejectReason", value); },
/* "The then Method" [Promises/A+ 1.1, 1.2, 2.2] */
then: function (onFulfilled, onRejected) {
var curr = this;
var next = new api(); /* [Promises/A+ 2.2.7] */
curr.onFulfilled.push(
resolver(onFulfilled, next, "fulfill")); /* [Promises/A+ 2.2.2/2.2.6] */
curr.onRejected.push(
resolver(onRejected, next, "reject" )); /* [Promises/A+ 2.2.3/2.2.6] */
execute(curr);
return next.proxy; /* [Promises/A+ 2.2.7, 3.3] */
}
};
/* deliver an action */
var deliver = function (curr, state, name, value) {
if (curr.state === STATE_PENDING) {
curr.state = state; /* [Promises/A+ 2.1.2.1, 2.1.3.1] */
curr[name] = value; /* [Promises/A+ 2.1.2.2, 2.1.3.2] */
execute(curr);
}
return curr;
};
/* execute all handlers */
var execute = function (curr) {
if (curr.state === STATE_FULFILLED)
execute_handlers(curr, "onFulfilled", curr.fulfillValue);
else if (curr.state === STATE_REJECTED)
execute_handlers(curr, "onRejected", curr.rejectReason);
};
/* execute particular set of handlers */
var execute_handlers = function (curr, name, value) {
/* global process: true */
/* global setImmediate: true */
/* global setTimeout: true */
/* short-circuit processing */
if (curr[name].length === 0)
return;
/* iterate over all handlers, exactly once */
var handlers = curr[name];
curr[name] = []; /* [Promises/A+ 2.2.2.3, 2.2.3.3] */
var func = function () {
for (var i = 0; i < handlers.length; i++)
handlers[i](value); /* [Promises/A+ 2.2.5] */
};
/* execute procedure asynchronously */ /* [Promises/A+ 2.2.4, 3.1] */
if (typeof process === "object" && typeof process.nextTick === "function")
process.nextTick(func);
else if (typeof setImmediate === "function")
setImmediate(func);
else
setTimeout(func, 0);
};
/* generate a resolver function */
var resolver = function (cb, next, method) {
return function (value) {
if (typeof cb !== "function") /* [Promises/A+ 2.2.1, 2.2.7.3, 2.2.7.4] */
next[method].call(next, value); /* [Promises/A+ 2.2.7.3, 2.2.7.4] */
else {
var result;
try { result = cb(value); } /* [Promises/A+ 2.2.2.1, 2.2.3.1, 2.2.5, 3.2] */
catch (e) {
next.reject(e); /* [Promises/A+ 2.2.7.2] */
return;
}
resolve(next, result); /* [Promises/A+ 2.2.7.1] */
}
};
};
/* "Promise Resolution Procedure" */ /* [Promises/A+ 2.3] */
var resolve = function (promise, x) {
/* sanity check arguments */ /* [Promises/A+ 2.3.1] */
if (promise === x || promise.proxy === x) {
promise.reject(new TypeError("cannot resolve promise with itself"));
return;
}
/* surgically check for a "then" method
(mainly to just call the "getter" of "then" only once) */
var then;
if ((typeof x === "object" && x !== null) || typeof x === "function") {
try { then = x.then; } /* [Promises/A+ 2.3.3.1, 3.5] */
catch (e) {
promise.reject(e); /* [Promises/A+ 2.3.3.2] */
return;
}
}
/* handle own Thenables [Promises/A+ 2.3.2]
and similar "thenables" [Promises/A+ 2.3.3] */
if (typeof then === "function") {
var resolved = false;
try {
/* call retrieved "then" method */ /* [Promises/A+ 2.3.3.3] */
then.call(x,
/* resolvePromise */ /* [Promises/A+ 2.3.3.3.1] */
function (y) {
if (resolved) return; resolved = true; /* [Promises/A+ 2.3.3.3.3] */
if (y === x) /* [Promises/A+ 3.6] */
promise.reject(new TypeError("circular thenable chain"));
else
resolve(promise, y);
},
/* rejectPromise */ /* [Promises/A+ 2.3.3.3.2] */
function (r) {
if (resolved) return; resolved = true; /* [Promises/A+ 2.3.3.3.3] */
promise.reject(r);
}
);
}
catch (e) {
if (!resolved) /* [Promises/A+ 2.3.3.3.3] */
promise.reject(e); /* [Promises/A+ 2.3.3.3.4] */
}
return;
}
/* handle other values */
promise.fulfill(x); /* [Promises/A+ 2.3.4, 2.3.3.4] */
};
// use native promises where possible
$$.Promise = typeof Promise === 'undefined' ? api : Promise;
// so we always have Promise.all()
$$.Promise.all = $$.Promise.all || function( ps ){
return new $$.Promise(function( resolveAll, rejectAll ){
var vals = new Array( ps.length );
var doneCount = 0;
var fulfill = function( i, val ){
vals[i] = val;
doneCount++;
if( doneCount === ps.length ){
resolveAll( vals );
}
};
for( var i = 0; i < ps.length; i++ ){
(function( i ){
var p = ps[i];
var isPromise = p.then != null;
if( isPromise ){
p.then(function( val ){
fulfill( i, val );
}, function( err ){
rejectAll( err );
});
} else {
var val = p;
fulfill( i, val );
}
})( i );
}
});
};
})( weaver );
// type testing utility functions
;(function($$, window){ 'use strict';
var typeofstr = typeof '';
var typeofobj = typeof {};
var typeoffn = typeof function(){};
$$.is = {
defined: function(obj){
return obj != null; // not undefined or null
},
string: function(obj){
return obj != null && typeof obj == typeofstr;
},
fn: function(obj){
return obj != null && typeof obj === typeoffn;
},
array: function(obj){
return Array.isArray ? Array.isArray(obj) : obj != null && obj instanceof Array;
},
plainObject: function(obj){
return obj != null && typeof obj === typeofobj && !$$.is.array(obj) && obj.constructor === Object;
},
object: function(obj){
return obj != null && typeof obj === typeofobj;
},
number: function(obj){
return obj != null && typeof obj === typeof 1 && !isNaN(obj);
},
integer: function( obj ){
return $$.is.number(obj) && Math.floor(obj) === obj;
},
bool: function(obj){
return obj != null && typeof obj === typeof true;
},
event: function(obj){
return obj instanceof $$.Event;
},
thread: function(obj){
return obj instanceof $$.Thread;
},
fabric: function(obj){
return obj instanceof $$.Fabric;
},
emptyString: function(obj){
if( !obj ){ // null is empty
return true;
} else if( $$.is.string(obj) ){
if( obj === '' || obj.match(/^\s+$/) ){
return true; // empty string is empty
}
}
return false; // otherwise, we don't know what we've got
},
nonemptyString: function(obj){
if( obj && $$.is.string(obj) && obj !== '' && !obj.match(/^\s+$/) ){
return true;
}
return false;
},
domElement: function(obj){
if( typeof HTMLElement === 'undefined' ){
return false; // we're not in a browser so it doesn't matter
} else {
return obj instanceof HTMLElement;
}
},
promise: function(obj){
return $$.is.object(obj) && $$.is.fn(obj.then);
},
touch: function(){
return window && ( ('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch );
},
gecko: function(){
return typeof InstallTrigger !== 'undefined' || ('MozAppearance' in document.documentElement.style);
},
webkit: function(){
return typeof webkitURL !== 'undefined' || ('WebkitAppearance' in document.documentElement.style);
},
chromium: function(){
return typeof chrome !== 'undefined';
},
khtml: function(){
return navigator.vendor.match(/kde/i); // TODO probably a better way to detect this...
},
khtmlEtc: function(){
return $$.is.khtml() || $$.is.webkit() || $$.is.blink();
},
trident: function(){
return typeof ActiveXObject !== 'undefined' || /*@cc_on!@*/false;
},
windows: function(){
return typeof navigator !== 'undefined' && navigator.appVersion.match(/Win/i);
},
mac: function(){
return typeof navigator !== 'undefined' && navigator.appVersion.match(/Mac/i);
},
linux: function(){
return typeof navigator !== 'undefined' && navigator.appVersion.match(/Linux/i);
},
unix: function(){
return typeof navigator !== 'undefined' && navigator.appVersion.match(/X11/i);
}
};
})( weaver, typeof window === 'undefined' ? null : window );
;(function($$, window){ 'use strict';
// utility functions only for internal use
$$.util = {
// the jquery extend() function
// NB: modified to use $$.is etc since we can't use jquery functions
extend: function() {
var options, name, src, copy, copyIsArray, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === 'boolean' ) {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== 'object' && !$$.is.fn(target) ) {
target = {};
}
// extend jQuery itself if only one argument is passed
if ( length === i ) {
target = this;
--i;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( $$.is.plainObject(copy) || (copyIsArray = $$.is.array(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && $$.is.array(src) ? src : [];
} else {
clone = src && $$.is.plainObject(src) ? src : {};
}
// Never move original objects, clone them
target[ name ] = $$.util.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
},
error: function( msg ){
if( console ){
if( console.error ){
console.error.apply( console, arguments );
} else if( console.log ){
console.log.apply( console, arguments );
} else {
throw msg;
}
} else {
throw msg;
}
}
};
})( weaver, typeof window === 'undefined' ? null : window );
;(function($$){ 'use strict';
// shamelessly taken from jQuery
// https://github.com/jquery/jquery/blob/master/src/event.js
$$.Event = function( src, props ) {
// Allow instantiation without the 'new' keyword
if ( !(this instanceof $$.Event) ) {
return new $$.Event( src, props );
}
// Event object
if ( src && src.type ) {
this.originalEvent = src;
this.type = src.type;
// Events bubbling up the document may have been marked as prevented
// by a handler lower down the tree; reflect the correct value.
this.isDefaultPrevented = ( src.defaultPrevented ) ? returnTrue : returnFalse;
// Event type
} else {
this.type = src;
}
// Put explicitly provided properties onto the event object
if ( props ) {
// $$.util.extend( this, props );
// more efficient to manually copy fields we use
this.type = props.type !== undefined ? props.type : this.type;
this.namespace = props.namespace;
this.layout = props.layout;
this.data = props.data;
this.message = props.message;
}
// Create a timestamp if incoming event doesn't have one
this.timeStamp = src && src.timeStamp || +new Date();
};
function returnFalse() {
return false;
}
function returnTrue() {
return true;
}
// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
$$.Event.prototype = {
preventDefault: function() {
this.isDefaultPrevented = returnTrue;
var e = this.originalEvent;
if ( !e ) {
return;
}
// if preventDefault exists run it on the original event
if ( e.preventDefault ) {
e.preventDefault();
}
},
stopPropagation: function() {
this.isPropagationStopped = returnTrue;
var e = this.originalEvent;
if ( !e ) {
return;
}
// if stopPropagation exists run it on the original event
if ( e.stopPropagation ) {
e.stopPropagation();
}
},
stopImmediatePropagation: function() {
this.isImmediatePropagationStopped = returnTrue;
this.stopPropagation();
},
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse
};
})( weaver );
;(function($$){ 'use strict';
// use this module to cherry pick functions into your prototype
// (useful for functions shared between the core and collections, for example)
// e.g.
// $$.fn.collection({
// foo: $$.define.foo({ /* params... */ })
// });
$$.define = {
// event function reusable stuff
event: {
regex: /(\w+)(\.\w+)?/, // regex for matching event strings (e.g. "click.namespace")
optionalTypeRegex: /(\w+)?(\.\w+)?/,
falseCallback: function(){ return false; }
},
// event binding
on: function( params ){
var defaults = {
unbindSelfOnTrigger: false,
unbindAllBindersOnTrigger: false
};
params = $$.util.extend({}, defaults, params);
return function onImpl(events, data, callback){
var self = this;
var selfIsArrayLike = self.length !== undefined;
var all = selfIsArrayLike ? self : [self]; // put in array if not array-like
var eventsIsString = $$.is.string(events);
var p = params;
if( $$.is.fn(data) || data === false ){ // data is actually callback
callback = data;
data = undefined;
}
// if there isn't a callback, we can't really do anything
// (can't speak for mapped events arg version)
if( !($$.is.fn(callback) || callback === false) && eventsIsString ){
return self; // maintain chaining
}
if( eventsIsString ){ // then convert to map
var map = {};
map[ events ] = callback;
events = map;
}
for( var evts in events ){
callback = events[evts];
if( callback === false ){
callback = $$.define.event.falseCallback;
}
if( !$$.is.fn(callback) ){ continue; }
evts = evts.split(/\s+/);
for( var i = 0; i < evts.length; i++ ){
var evt = evts[i];
if( $$.is.emptyString(evt) ){ continue; }
var match = evt.match( $$.define.event.regex ); // type[.namespace]
if( match ){
var type = match[1];
var namespace = match[2] ? match[2] : undefined;
var listener = {
callback: callback, // callback to run
data: data, // extra data in eventObj.data
type: type, // the event type (e.g. 'click')
namespace: namespace, // the event namespace (e.g. ".foo")
unbindSelfOnTrigger: p.unbindSelfOnTrigger,
unbindAllBindersOnTrigger: p.unbindAllBindersOnTrigger,
binders: all // who bound together
};
for( var j = 0; j < all.length; j++ ){
var _p = all[j]._private;
_p.listeners = _p.listeners || [];
_p.listeners.push( listener );
}
}
} // for events array
} // for events map
return self; // maintain chaining
}; // function
}, // on
eventAliasesOn: function( proto ){
var p = proto;
p.addListener = p.listen = p.bind = p.on;
p.removeListener = p.unlisten = p.unbind = p.off;
p.emit = p.trigger;
// this is just a wrapper alias of .on()
p.pon = p.promiseOn = function( events, selector ){
var self = this;
var args = Array.prototype.slice.call( arguments, 0 );
return new $$.Promise(function( resolve, reject ){
var callback = function( e ){
self.off.apply( self, offArgs );
resolve( e );
};
var onArgs = args.concat([ callback ]);
var offArgs = onArgs.concat([]);
self.on.apply( self, onArgs );
});
};
},
off: function offImpl( params ){
var defaults = {
};
params = $$.util.extend({}, defaults, params);
return function(events, callback){
var self = this;
var selfIsArrayLike = self.length !== undefined;
var all = selfIsArrayLike ? self : [self]; // put in array if not array-like
var eventsIsString = $$.is.string(events);
if( arguments.length === 0 ){ // then unbind all
for( var i = 0; i < all.length; i++ ){
all[i]._private.listeners = [];
}
return self; // maintain chaining
}
if( eventsIsString ){ // then convert to map
var map = {};
map[ events ] = callback;
events = map;
}
for( var evts in events ){
callback = events[evts];
if( callback === false ){
callback = $$.define.event.falseCallback;
}
evts = evts.split(/\s+/);
for( var h = 0; h < evts.length; h++ ){
var evt = evts[h];
if( $$.is.emptyString(evt) ){ continue; }
var match = evt.match( $$.define.event.optionalTypeRegex ); // [type][.namespace]
if( match ){
var type = match[1] ? match[1] : undefined;
var namespace = match[2] ? match[2] : undefined;
for( var i = 0; i < all.length; i++ ){ //
var listeners = all[i]._private.listeners = all[i]._private.listeners || [];
for( var j = 0; j < listeners.length; j++ ){
var listener = listeners[j];
var nsMatches = !namespace || namespace === listener.namespace;
var typeMatches = !type || listener.type === type;
var cbMatches = !callback || callback === listener.callback;
var listenerMatches = nsMatches && typeMatches && cbMatches;
// delete listener if it matches
if( listenerMatches ){
listeners.splice(j, 1);
j--;
}
} // for listeners
} // for all
} // if match
} // for events array
} // for events map
return self; // maintain chaining
}; // function
}, // off
trigger: function( params ){
var defaults = {};
params = $$.util.extend({}, defaults, params);
return function triggerImpl(events, extraParams, fnToTrigger){
var self = this;
var selfIsArrayLike = self.length !== undefined;
var all = selfIsArrayLike ? self : [self]; // put in array if not array-like
var eventsIsString = $$.is.string(events);
var eventsIsObject = $$.is.plainObject(events);
var eventsIsEvent = $$.is.event(events);
if( eventsIsString ){ // then make a plain event object for each event name
var evts = events.split(/\s+/);
events = [];
for( var i = 0; i < evts.length; i++ ){
var evt = evts[i];
if( $$.is.emptyString(evt) ){ continue; }
var match = evt.match( $$.define.event.regex ); // type[.namespace]
var type = match[1];
var namespace = match[2] ? match[2] : undefined;
events.push( {
type: type,
namespace: namespace
} );
}
} else if( eventsIsObject ){ // put in length 1 array
var eventArgObj = events;
events = [ eventArgObj ];
}
if( extraParams ){
if( !$$.is.array(extraParams) ){ // make sure extra params are in an array if specified
extraParams = [ extraParams ];
}
} else { // otherwise, we've got nothing
extraParams = [];
}
for( var i = 0; i < events.length; i++ ){ // trigger each event in order
var evtObj = events[i];
for( var j = 0; j < all.length; j++ ){ // for each
var triggerer = all[j];
var listeners = triggerer._private.listeners = triggerer._private.listeners || [];
var bubbleUp = false;
// create the event for this element from the event object
var evt;
if( eventsIsEvent ){ // then just get the object
evt = evtObj;
} else { // then we have to make one
evt = new $$.Event( evtObj, {
namespace: evtObj.namespace
} );
}
if( fnToTrigger ){ // then override the listeners list with just the one we specified
listeners = [{
namespace: evt.namespace,
type: evt.type,
callback: fnToTrigger
}];
}
for( var k = 0; k < listeners.length; k++ ){ // check each listener
var lis = listeners[k];
var nsMatches = !lis.namespace || lis.namespace === evt.namespace;
var typeMatches = lis.type === evt.type;
var targetMatches = true;
var listenerMatches = nsMatches && typeMatches && targetMatches;
if( listenerMatches ){ // then trigger it
var args = [ evt ];
args = args.concat( extraParams ); // add extra params to args list
if( lis.data ){ // add on data plugged into binding
evt.data = lis.data;
} else { // or clear it in case the event obj is reused
evt.data = undefined;
}
if( lis.unbindSelfOnTrigger || lis.unbindAllBindersOnTrigger ){ // then remove listener
listeners.splice(k, 1);
k--;
}
if( lis.unbindAllBindersOnTrigger ){ // then delete the listener for all binders
var binders = lis.binders;
for( var l = 0; l < binders.length; l++ ){
var binder = binders[l];
if( !binder || binder === triggerer ){ continue; } // already handled triggerer or we can't handle it
var binderListeners = binder._private.listeners;
for( var m = 0; m < binderListeners.length; m++ ){
var binderListener = binderListeners[m];
if( binderListener === lis ){ // delete listener from list
binderListeners.splice(m, 1);
m--;
}
}
}
}
// run the callback
var context = triggerer;
var ret = lis.callback.apply( context, args );
if( ret === false || evt.isPropagationStopped() ){
// then don't bubble
bubbleUp = false;
if( ret === false ){
// returning false is a shorthand for stopping propagation and preventing the def. action
evt.stopPropagation();
evt.preventDefault();
}
}
} // if listener matches
} // for each listener
if( bubbleUp ){
// TODO if bubbling is supported...
}
} // for each of all
} // for each event
return self; // maintain chaining
}; // function
} // trigger
}; // define
})( weaver );
// cross-env thread/worker
// NB : uses (heavyweight) processes on nodejs so best not to create too many threads
;(function($$, window){ 'use strict';
$$.Thread = function( fn ){
if( !(this instanceof $$.Thread) ){
return new $$.Thread( fn );
}
this._private = {
requires: [],
files: [],
queue: null,
pass: []
};
if( fn ){
this.run( fn );
}
};
$$.thread = $$.Thread;
$$.thdfn = $$.Thread.prototype; // short alias
$$.fn.thread = function( fnMap, options ){
for( var name in fnMap ){
var fn = fnMap[name];
$$.Thread.prototype[ name ] = fn;
}
};
var stringifyFieldVal = function( val ){
var valStr = $$.is.fn( val ) ? val.toString() : 'JSON.parse("' + JSON.stringify(val) + '")';
return valStr;
};
// allows for requires with prototypes and subobjs etc
var fnAsRequire = function( fn ){
var req;
var fnName;
if( $$.is.object(fn) && fn.fn ){ // manual fn
req = fnAs( fn.fn, fn.name );
fnName = fn.name;
fn = fn.fn;
} else if( $$.is.fn(fn) ){ // auto fn
req = fn.toString();
fnName = fn.name;
} else if( $$.is.string(fn) ){ // stringified fn
req = fn;
} else if( $$.is.object(fn) ){ // plain object
if( fn.proto ){
req = '';
} else {
req = fn.name + ' = {};';
}
fnName = fn.name;
fn = fn.obj;
}
req += '\n';
var protoreq = function( val, subname ){
if( val.prototype ){
var protoNonempty = false;
for( var prop in val.prototype ){ protoNonempty = true; break; }
if( protoNonempty ){
req += fnAsRequire( {
name: subname,
obj: val,
proto: true
}, val );
}
}
};
// pull in prototype
if( fn.prototype && fnName != null ){
for( var name in fn.prototype ){
var protoStr = '';
var val = fn.prototype[ name ];
var valStr = stringifyFieldVal( val );
var subname = fnName + '.prototype.' + name;
protoStr += subname + ' = ' + valStr + ';\n';
if( protoStr ){
req += protoStr;
}
protoreq( val, subname ); // subobject with prototype
}
}
// pull in properties for obj/fns
if( !$$.is.string(fn) ){ for( var name in fn ){
var propsStr = '';
if( fn.hasOwnProperty(name) ){
var val = fn[ name ];
var valStr = stringifyFieldVal( val );
var subname = fnName + '["' + name + '"]';
propsStr += subname + ' = ' + valStr + ';\n';
}
if( propsStr ){
req += propsStr;
}
protoreq( val, subname ); // subobject with prototype
} }
return req;
};
var isPathStr = function( str ){
return $$.is.string(str) && str.match(/\.js$/);
};
$$.fn.thread({
require: function( fn, as ){
if( isPathStr(fn) ){
this._private.files.push( fn );
return this;
}
if( as ){
if( $$.is.fn(fn) ){
// disabled b/c doesn't work with forced names on functions w/ prototypes
//fn = fnAs( fn, as );
as = as || fn.name;
fn = { name: as, fn: fn };
} else {
fn = { name: as, obj: fn };
}
}
this._private.requires.push( fn );
return this; // chaining
},
pass: function( data ){
this._private.pass.push( data );
return this; // chaining
},
run: function( fn, pass ){ // fn used like main()
var self = this;
var _p = this._private;
pass = pass || _p.pass.shift();
if( _p.stopped ){
$$.util.error('Attempted to run a stopped thread! Start a new thread or do not stop the existing thread and reuse it.');
return;
}
if( _p.running ){
return _p.queue = _p.queue.then(function(){ // inductive step
return self.run( fn, pass );
});
}
var useWW = window != null;
var useNode = typeof module !== 'undefined';
self.trigger('run');
var runP = new $$.Promise(function( resolve, reject ){
_p.running = true;
var threadTechAlreadyExists = _p.ran;
var fnImplStr = $$.is.string( fn ) ? fn : fn.toString();
// worker code to exec
var fnStr = '\n' + ( _p.requires.map(function( r ){
return fnAsRequire( r );
}) ).concat( _p.files.map(function( f ){
if( useWW ){
var wwifyFile = function( file ){
if( file.match(/^\.\//) || file.match(/^\.\./) ){
return window.location.origin + window.location.pathname + file;
} else if( file.match(/^\//) ){
return window.location.origin + '/' + file;
}
return file;
};
return 'importScripts("' + wwifyFile(f) + '");';
} else if( useNode ) {
return 'eval( require("fs").readFileSync("' + f + '", { encoding: "utf8" }) );';
}
}) ).concat([
'( function(){',
'var ret = (' + fnImplStr + ')(' + JSON.stringify(pass) + ');',
'if( ret !== undefined ){ resolve(ret); }', // assume if ran fn returns defined value (incl. null), that we want to resolve to it
'} )()\n'
]).join('\n');
// because we've now consumed the requires, empty the list so we don't dupe on next run()
_p.requires = [];
_p.files = [];
if( useWW ){
var fnBlob, fnUrl;
// add normalised thread api functions
if( !threadTechAlreadyExists ){
var fnPre = fnStr + '';
fnStr = [
'function broadcast(m){ return message(m); };', // alias
'function message(m){ postMessage(m); };',
'function listen(fn){',
' self.addEventListener("message", function(m){ ',
' if( typeof m === "object" && (m.data.$$eval || m.data === "$$start") ){',
' } else { ',
' fn( m.data );',
' }',
' });',
'};',
'self.addEventListener("message", function(m){ if( m.data.$$eval ){ eval( m.data.$$eval ); } });',
'function resolve(v){ postMessage({ $$resolve: v }); };',
'function reject(v){ postMessage({ $$reject: v }); };'
].join('\n');
fnStr += fnPre;
fnBlob = new Blob([ fnStr ], {
type: 'application/javascript'
});
fnUrl = window.URL.createObjectURL( fnBlob );
}
// create webworker and let it exec the serialised code
var ww = _p.webworker = _p.webworker || new Worker( fnUrl );
if( threadTechAlreadyExists ){ // then just exec new run() code
ww.postMessage({
$$eval: fnStr
});
}
// worker messages => events
var cb;
ww.addEventListener('message', cb = function( m ){
var isObject = $$.is.object(m) && $$.is.object( m.data );
if( isObject && ('$$resolve' in m.data) ){
ww.removeEventListener('message', cb); // done listening b/c resolve()
resolve( m.data.$$resolve );
} else if( isObject && ('$$reject' in m.data) ){
ww.removeEventListener('message', cb); // done listening b/c reject()
reject( m.data.$$reject );
} else {
self.trigger( new $$.Event(m, { type: 'message', message: m.data }) );
}
}, false);
if( !threadTechAlreadyExists ){
ww.postMessage('$$start'); // start up the worker
}
} else if( useNode ){
// create a new process
var path = require('path');
var child_process = require('child_process');
var child = _p.child = _p.child || child_process.fork( path.join(__dirname, 'thread-node-fork') );
// child process messages => events
var cb;
child.on('message', cb = function( m ){
if( $$.is.object(m) && ('$$resolve' in m) ){
child.removeListener('message', cb); // done listening b/c resolve()
resolve( m.$$resolve );
} else if( $$.is.object(m) && ('$$reject' in m) ){
child.removeListener('message', cb); // done listening b/c reject()
reject( m.$$reject );
} else {
self.trigger( new $$.Event({}, { type: 'message', message: m }) );
}
});
// ask the child process to eval the worker code
child.send({
$$eval: fnStr
});
} else {
$$.error('Tried to create thread but no underlying tech found!');
// TODO fallback on main JS thread?
}
}).then(function( v ){
_p.running = false;
_p.ran = true;
self.trigger('ran');
return v;
});
if( _p.queue == null ){
_p.queue = runP; // i.e. first step of inductive promise chain (for queue)
}
return runP;
},
// send the thread a message
message: function( m ){
var _p = this._private;
if( _p.webworker ){
_p.webworker.postMessage( m );
}
if( _p.child ){
_p.child.send( m );
}
return this; // chaining
},
stop: function(){
var _p = this._private;
if( _p.webworker ){
_p.webworker.terminate();
}
if( _p.child ){
_p.child.kill();
}
_p.stopped = true;
return this.trigger('stop'); // chaining
},
stopped: function(){
return this._private.stopped;
}
});
var fnAs = function( fn, name ){
var fnStr = fn.toString();
fnStr = fnStr.replace(/function.*\(/, 'function ' + name + '(');
return fnStr;
};
var defineFnal = function( opts ){
opts = opts || {};
return function fnalImpl( fn, arg1 ){
var fnStr = fnAs( fn, '_$_$_' + opts.name );
this.require( fnStr );
return this.run( [
'function( data ){',
' var origResolve = resolve;',
' var res = [];',
' ',
' resolve = function( val ){',
' res.push( val );',
' };',
' ',
' var ret = data.' + opts.name + '( _$_$_' + opts.name + ( arguments.length > 1 ? ', ' + JSON.stringify(arg1) : '' ) + ' );',
' ',
' resolve = origResolve;',
' resolve( res.length > 0 ? res : ret );',
'}'
].join('\n') );
};
};
$$.fn.thread({
reduce: defineFnal({ name: 'reduce' }),
reduceRight: defineFnal({ name: 'reduceRight' }),
map: defineFnal({ name: 'map' })
});
// aliases
var fn = $$.thdfn;
fn.promise = fn.run;
fn.terminate = fn.halt = fn.stop;
fn.include = fn.require;
// higher level alias (in case you like the worker metaphor)
$$.worker = $$.Worker = $$.Thread;
// pull in event apis
$$.fn.thread({
on: $$.define.on(),
one: $$.define.on({ unbindSelfOnTrigger: true }),
off: $$.define.off(),
trigger: $$.define.trigger()
});
$$.define.eventAliasesOn( $$.thdfn );
})( weaver, typeof window === 'undefined' ? null : window );
;(function($$, window){ 'use strict';
$$.Fabric = function( N ){
if( !(this instanceof $$.Fabric) ){
return new $$.Fabric( N );
}
this._private = {
pass: []
};
var defN = 4;
if( $$.is.number(N) ){
// then use the specified number of threads
} if( typeof navigator !== 'undefined' && navigator.hardwareConcurrency != null ){
N = navigator.hardwareConcurrency;
} else if( typeof module !== 'undefined' ){
N = require('os').cpus().length;
} else { // TODO could use an estimation here but would the additional expense be worth it?
N = defN;
}
for( var i = 0; i < N; i++ ){
this[i] = $$.Thread();
}
this.length = N;
};
$$.fabric = $$.Fabric;
$$.fabfn = $$.Fabric.prototype; // short alias
$$.fn.fabric = function( fnMap, options ){
for( var name in fnMap ){
var fn = fnMap[name];
$$.Fabric.prototype[ name ] = fn;
}
};
$$.fn.fabric({
// require fn in all threads
require: function( fn, as ){
for( var i = 0; i < this.length; i++ ){
var thread = this[i];
thread.require( fn, as );
}
return this;
},
// get a random thread
random: function(){
var i = Math.round( (this.length - 1) * Math.random() );
var thread = this[i];
return thread;
},
// run on random thread
run: function( fn ){
var pass = this._private.pass.shift();
return this.random().pass( pass ).run( fn );
},
// sends a random thread a message
message: function( m ){
return this.random().message( m );
},
// send all threads a message
broadcast: function( m ){
for( var i = 0; i < this.length; i++ ){
var thread = this[i];
thread.message( m );
}
return this; // chaining
},
// stop all threads
stop: function(){
for( var i = 0; i < this.length; i++ ){
var thread = this[i];
thread.stop();
}
return this; // chaining
},
// pass data to be used with .spread() etc.
pass: function( data ){
var pass = this._private.pass;
if( $$.is.array(data) ){
pass.push( data );
} else {
$$.util.error('Only arrays or collections may be used with fabric.pass()');
}
return this; // chaining
},
spreadSize: function(){
var subsize = Math.ceil( this._private.pass[0].length / this.length );
subsize = Math.max( 1, subsize ); // don't pass less than one ele to each thread
return subsize;
},
// split the data into slices to spread the data equally among threads
spread: function( fn ){
var self = this;
var _p = self._private;
var subsize = self.spreadSize(); // number of pass eles to handle in each thread
var pass = _p.pass.shift().concat([]); // keep a copy
var runPs = [];
for( var i = 0; i < this.length; i++ ){
var thread = this[i];
var slice = pass.splice( 0, subsize );
var runP = thread.pass( slice ).run( fn );
runPs.push( runP );
var doneEarly = pass.length === 0;
if( doneEarly ){ break; }
}
return $$.Promise.all( runPs ).then(function( thens ){
var postpass = [];
var p = 0;
// fill postpass with the total result joined from all threads
for( var i = 0; i < thens.length; i++ ){
var then = thens[i]; // array result from thread i
for( var j = 0; j < then.length; j++ ){
var t = then[j]; // array element
postpass[ p++ ] = t;
}
}
return postpass;
});
},
// parallel version of array.map()
map: function( fn ){
var self = this;
self.require( fn, '_$_$_fabmap' );
return self.spread(function( split ){
var mapped = [];
var origResolve = resolve;
resolve = function( val ){
mapped.push( val );
};
for( var i = 0; i < split.length; i++ ){
var oldLen = mapped.length;
var ret = _$_$_fabmap( split[i] );
var nothingInsdByResolve = oldLen === mapped.length;
if( nothingInsdByResolve ){
mapped.push( ret );
}
}
resolve = origResolve;
return mapped;
});
},
// parallel version of array.filter()
filter: function( fn ){
var _p = this._private;
var pass = _p.pass[0];
return this.map( fn ).then(function( include ){
var ret = [];
for( var i = 0; i < pass.length; i++ ){
var datum = pass[i];
var incDatum = include[i];
if( incDatum ){
ret.push( datum );
}
}
return ret;
});
},
// sorts the passed array using a divide and conquer strategy
sort: function( cmp ){
var self = this;
var P = this._private.pass[0].length;
var subsize = this.spreadSize();
cmp = cmp || function( a, b ){ // default comparison function
if( a < b ){
return -1;
} else if( a > b ){
return 1;
}
return 0;
};
self.require( cmp, '_$_$_cmp' );
return self.spread(function( split ){ // sort each split normally
var sortedSplit = split.sort( _$_$_cmp );
resolve( sortedSplit );
}).then(function( joined ){
// do all the merging in the main thread to minimise data transfer
// TODO could do merging in separate threads but would incur add'l cost of data transfer
// for each level of the merge
var merge = function( i, j, max ){
// don't overflow array
j = Math.min( j, P );
max = Math.min( max, P );
// left and right sides of merge
var l = i;
var r = j;
var sorted = [];
for( var k = l; k < max; k++ ){
var eleI = joined[i];
var eleJ = joined[j];
if( i < r && ( j >= max || cmp(eleI, eleJ) <= 0 ) ){
sorted.push( eleI );
i++;
} else {
sorted.push( eleJ );
j++;
}
}
// in the array proper, put the sorted values
for( var k = 0; k < sorted.length; k++ ){ // kth sorted item
var index = l + k;
joined[ index ] = sorted[k];
}
};
for( var splitL = subsize; splitL < P; splitL *= 2 ){ // merge until array is "split" as 1
for( var i = 0; i < P; i += 2*splitL ){
merge( i, i + splitL, i + 2*splitL );
}
}
return joined;
});
}
});
var defineRandomPasser = function( opts ){
opts = opts || {};
return function( fn, arg1 ){
var pass = this._private.pass.shift();
return this.random().pass( pass )[ opts.threadFn ]( fn, arg1 );
};
};
$$.fn.fabric({
randomMap: defineRandomPasser({ threadFn: 'map' }),
reduce: defineRandomPasser({ threadFn: 'reduce' }),
reduceRight: defineRandomPasser({ threadFn: 'reduceRight' })
});
// aliases
var fn = $$.fabfn;
fn.promise = fn.run;
fn.terminate = fn.halt = fn.stop;
fn.include = fn.require;
// pull in event apis
$$.fn.fabric({
on: $$.define.on(),
one: $$.define.on({ unbindSelfOnTrigger: true }),
off: $$.define.off(),
trigger: $$.define.trigger()
});
$$.define.eventAliasesOn( $$.fabfn );
})( weaver, typeof window === 'undefined' ? null : window );
|
import { take, race, takeEvery, call, put } from 'redux-saga/effects';
import { Navigate } from '../ducks/router';
import { LOAD_TRACKS_LIST } from '../ducks/search';
import { getTracks } from '../services/kalama';
import {
setTracks,
ON_PLAYER_SHUTDOWN,
setCurrentTrackIndex,
ON_CACHE_READY
} from '../ducks/tracks';
import { showMessage } from '../ducks/flashMessages';
import { delay } from 'redux-saga';
function* doShutdown() {
yield call(::process.exit, 0);
}
function* doLoadTrackList({ payload: resource }) {
const tracks = yield call(getTracks, resource);
if (!tracks.length) {
yield put(
showMessage('No tracks! All tracks are removed by copyright')
);
return;
}
yield put(setTracks(tracks, resource));
yield put(Navigate('Player'));
yield race([take(ON_CACHE_READY), delay(200)]);
yield put(setCurrentTrackIndex(0));
}
function* navigationSaga() {
yield put(Navigate('Search'));
yield takeEvery(LOAD_TRACKS_LIST, doLoadTrackList);
yield takeEvery(ON_PLAYER_SHUTDOWN, doShutdown);
}
export default navigationSaga;
|
const sumRobot = {
threshold: 4, sum: function (numbers) {
var that = this;
var reduceFunc = function (reduced, current) {
return current > that.threshold ?
(reduced + current) :
reduced;
}
;
return numbers.reduce(reduceFunc, 0);
}
};
const sums = sumRobot.sum([3, 4, 5, 6]);
console.log(sums); |
'use strict';
angular
.module("angularStart", ['ui.router'])
.config(['$stateProvider', '$urlRouterProvider', function ($stateProvider, $urlRouterProvider, $locationProvider) {
// $locationProvider.hashPrefix('');
$urlRouterProvider.otherwise("/home");
$stateProvider
.state('home', {
url: '/home',
template: '<first-component value="123"></first-component>'
})
.state('home.two', {
// parent: 'home',
url: '/two',
template: '<two-component></two-component>'
})
.state('home.two.three', {
// parent: 'two',
url: '/three',
template: '<three-component></three-component>'
})
}]) |
describe('ngNuxeoClient module', function () {
'use strict';
var httpBackend, nuxeo, nuxeoUser, dataDocuments, dataUser, dataWorkspace;
beforeEach(module('ngNuxeoClient', 'data/documents.json', 'data/user.json', 'data/workspace.json'));
beforeEach(inject(function ($httpBackend, _nuxeo_, _nuxeoUser_, _dataDocuments_, _dataUser_, _dataWorkspace_) {
httpBackend = $httpBackend;
nuxeo = _nuxeo_;
nuxeoUser = _nuxeoUser_;
dataDocuments = _dataDocuments_;
dataUser = _dataUser_;
dataWorkspace = _dataWorkspace_;
}));
describe('nuxeo.Document object', function () {
it('is valid when instantiated with no argument', function () {
expect(nuxeo.Document.name === 'Document').toBe(true);
var doc = new nuxeo.Document();
expect(typeof doc === 'object').toBe(true);
expect(doc instanceof nuxeo.Document).toBe(true);
expect(doc.constructor === nuxeo.Document).toBe(true);
expect(nuxeo.Document.prototype instanceof nuxeo.Automation).toBe(true);
expect(doc.isDeletable).toBeFalsy();
expect(doc.isPublishable).toBeFalsy();
});
it('is valid when instantiated argument', function () {
var doc = new nuxeo.Document(dataDocuments.entries[0]);
expect(typeof doc === 'object').toBe(true);
expect(doc instanceof nuxeo.Document).toBe(true);
expect(doc.constructor === nuxeo.Document).toBe(true);
expect(nuxeo.Document.prototype instanceof nuxeo.Automation).toBe(true);
expect(doc.isDeletable).toBeDefined();
expect(doc.isPublishable).toBeDefined();
});
it('has parameters passed in instantiation', function () {
var doc = new nuxeo.Document({name: 'myDocument', type: 'Picture'});
expect(doc.name).toEqual('myDocument');
expect(doc.type).toEqual('Picture');
});
});
describe('nuxeo.Document', function () {
it('should create a Document when requested', function () {
httpBackend.whenGET('https://demo.nuxeo.com/nuxeo/api/v1/user/Administrator').respond(dataUser);
httpBackend.whenGET('https://demo.nuxeo.com/nuxeo/api/v1/path/default-domain/UserWorkspaces/fmaturel-github-com'
).respond(dataWorkspace);
httpBackend.whenPOST('https://demo.nuxeo.com/nuxeo/site/automation/Document.Create').respond('{\"type": \"Document\"}');
nuxeo.Document.create('webbanner', '/default-domain/sections', function (result) {
expect(result).toBeDefined();
expect(result.type).toEqual('Document');
});
nuxeoUser.login('Administrator', 'Administrator');
httpBackend.flush();
});
});
});
|
import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';
import services from '~/ide/services';
import Api from '~/api';
import { query } from '~/ide/services/gql';
import { escapeFileUrl } from '~/lib/utils/url_utility';
import getUserPermissions from '~/ide/queries/getUserPermissions.query.graphql';
import { projectData } from '../mock_data';
jest.mock('~/api');
jest.mock('~/ide/services/gql');
const TEST_NAMESPACE = 'alice';
const TEST_PROJECT = 'wonderland';
const TEST_PROJECT_ID = `${TEST_NAMESPACE}/${TEST_PROJECT}`;
const TEST_BRANCH = 'master-patch-123';
const TEST_COMMIT_SHA = '123456789';
const TEST_FILE_PATH = 'README2.md';
const TEST_FILE_OLD_PATH = 'OLD_README2.md';
const TEST_FILE_PATH_SPECIAL = 'READM?ME/abc';
const TEST_FILE_CONTENTS = 'raw file content';
describe('IDE services', () => {
describe('commit', () => {
let payload;
beforeEach(() => {
payload = {
branch: TEST_BRANCH,
commit_message: 'Hello world',
actions: [],
start_sha: TEST_COMMIT_SHA,
};
Api.commitMultiple.mockReturnValue(Promise.resolve());
});
it('should commit', () => {
services.commit(TEST_PROJECT_ID, payload);
expect(Api.commitMultiple).toHaveBeenCalledWith(TEST_PROJECT_ID, payload);
});
});
describe('getRawFileData', () => {
it("resolves with a file's content if its a tempfile and it isn't renamed", () => {
const file = {
path: 'file',
tempFile: true,
content: 'content',
raw: 'raw content',
};
return services.getRawFileData(file).then(raw => {
expect(raw).toBe('content');
});
});
it('resolves with file.raw if the file is renamed', () => {
const file = {
path: 'file',
tempFile: true,
content: 'content',
prevPath: 'old_path',
raw: 'raw content',
};
return services.getRawFileData(file).then(raw => {
expect(raw).toBe('raw content');
});
});
it('returns file.raw if it exists', () => {
const file = {
path: 'file',
content: 'content',
raw: 'raw content',
};
return services.getRawFileData(file).then(raw => {
expect(raw).toBe('raw content');
});
});
it("returns file.raw if file.raw is empty but file.rawPath doesn't exist", () => {
const file = {
path: 'file',
content: 'content',
raw: '',
};
return services.getRawFileData(file).then(raw => {
expect(raw).toBe('');
});
});
describe("if file.rawPath exists but file.raw doesn't exist", () => {
let file;
let mock;
beforeEach(() => {
file = {
path: 'file',
content: 'content',
raw: '',
rawPath: 'some_raw_path',
};
mock = new MockAdapter(axios);
mock.onGet(file.rawPath).reply(200, 'raw content');
jest.spyOn(axios, 'get');
});
afterEach(() => {
mock.restore();
});
it('sends a request to file.rawPath', () => {
return services.getRawFileData(file).then(raw => {
expect(raw).toEqual('raw content');
});
});
});
});
describe('getBaseRawFileData', () => {
let file;
let mock;
beforeEach(() => {
file = {
mrChange: null,
projectId: TEST_PROJECT_ID,
path: TEST_FILE_PATH,
};
jest.spyOn(axios, 'get');
mock = new MockAdapter(axios);
});
afterEach(() => {
mock.restore();
});
it('gives back file.baseRaw for files with that property present', () => {
file.baseRaw = TEST_FILE_CONTENTS;
return services.getBaseRawFileData(file, TEST_COMMIT_SHA).then(content => {
expect(content).toEqual(TEST_FILE_CONTENTS);
});
});
it('gives back file.baseRaw for files for temp files', () => {
file.tempFile = true;
file.baseRaw = TEST_FILE_CONTENTS;
return services.getBaseRawFileData(file, TEST_COMMIT_SHA).then(content => {
expect(content).toEqual(TEST_FILE_CONTENTS);
});
});
describe.each`
relativeUrlRoot | filePath | isRenamed
${''} | ${TEST_FILE_PATH} | ${false}
${''} | ${TEST_FILE_OLD_PATH} | ${true}
${''} | ${TEST_FILE_PATH_SPECIAL} | ${false}
${''} | ${TEST_FILE_PATH_SPECIAL} | ${true}
${'gitlab'} | ${TEST_FILE_OLD_PATH} | ${true}
`(
'with relativeUrlRoot ($relativeUrlRoot) and filePath ($filePath) and isRenamed ($isRenamed)',
({ relativeUrlRoot, filePath, isRenamed }) => {
beforeEach(() => {
if (isRenamed) {
file.mrChange = {
renamed_file: true,
old_path: filePath,
};
} else {
file.path = filePath;
}
gon.relative_url_root = relativeUrlRoot;
mock
.onGet(
`${relativeUrlRoot}/${TEST_PROJECT_ID}/-/raw/${TEST_COMMIT_SHA}/${escapeFileUrl(
filePath,
)}`,
)
.reply(200, TEST_FILE_CONTENTS);
});
it('fetches file content', () =>
services.getBaseRawFileData(file, TEST_COMMIT_SHA).then(content => {
expect(content).toEqual(TEST_FILE_CONTENTS);
}));
},
);
});
describe('getProjectData', () => {
it('combines gql and API requests', () => {
const gqlProjectData = {
userPermissions: {
bogus: true,
},
};
Api.project.mockReturnValue(Promise.resolve({ data: { ...projectData } }));
query.mockReturnValue(Promise.resolve({ data: { project: gqlProjectData } }));
return services.getProjectData(TEST_NAMESPACE, TEST_PROJECT).then(response => {
expect(response).toEqual({ data: { ...projectData, ...gqlProjectData } });
expect(Api.project).toHaveBeenCalledWith(TEST_PROJECT_ID);
expect(query).toHaveBeenCalledWith({
query: getUserPermissions,
variables: {
projectPath: TEST_PROJECT_ID,
},
});
});
});
});
describe('getFiles', () => {
let mock;
let relativeUrlRoot;
const TEST_RELATIVE_URL_ROOT = 'blah-blah';
beforeEach(() => {
jest.spyOn(axios, 'get');
relativeUrlRoot = gon.relative_url_root;
gon.relative_url_root = TEST_RELATIVE_URL_ROOT;
mock = new MockAdapter(axios);
mock
.onGet(`${TEST_RELATIVE_URL_ROOT}/${TEST_PROJECT_ID}/-/files/${TEST_COMMIT_SHA}`)
.reply(200, [TEST_FILE_PATH]);
});
afterEach(() => {
mock.restore();
gon.relative_url_root = relativeUrlRoot;
});
it('initates the api call based on the passed path and commit hash', () => {
return services.getFiles(TEST_PROJECT_ID, TEST_COMMIT_SHA).then(({ data }) => {
expect(axios.get).toHaveBeenCalledWith(
`${gon.relative_url_root}/${TEST_PROJECT_ID}/-/files/${TEST_COMMIT_SHA}`,
expect.any(Object),
);
expect(data).toEqual([TEST_FILE_PATH]);
});
});
});
describe('pingUsage', () => {
let mock;
let relativeUrlRoot;
const TEST_RELATIVE_URL_ROOT = 'blah-blah';
beforeEach(() => {
jest.spyOn(axios, 'post');
relativeUrlRoot = gon.relative_url_root;
gon.relative_url_root = TEST_RELATIVE_URL_ROOT;
mock = new MockAdapter(axios);
});
afterEach(() => {
mock.restore();
gon.relative_url_root = relativeUrlRoot;
});
it('posts to usage endpoint', () => {
const TEST_PROJECT_PATH = 'foo/bar';
const axiosURL = `${TEST_RELATIVE_URL_ROOT}/${TEST_PROJECT_PATH}/usage_ping/web_ide_pipelines_count`;
mock.onPost(axiosURL).reply(200);
return services.pingUsage(TEST_PROJECT_PATH).then(() => {
expect(axios.post).toHaveBeenCalledWith(axiosURL);
});
});
});
});
|
export const TOGGLE_ORDER = 'order/toggle'
export const SHOW_ADD_ORDER_PRODUCT_DIALOG = 'order/product/add-dialog/show'
export const HIDE_ADD_ORDER_PRODUCT_DIALOG = 'order/product/add-dialog/hide'
export const ADD_PRODUCT_TO_ORDER = 'order/product/add'
export const REMOVE_PRODUCT_FROM_ORDER = 'order/product/remove'
export const ADD_TO_PRODUCT_QUANTITY = 'order/product/add-quantity'
export const SUBTRACT_TO_PRODUCT_QUANTITY = 'order/product/subtract-quantity'
export const SHOW_SAVE_ORDER_DIALOG = 'order/save-dialog/show'
export const HIDE_SAVE_ORDER_DIALOG = 'order/save-dialog/hide'
export const CHANGE_ORDER_USER = 'order/user/change'
export const SAVE_NEW_ORDER_REQUEST = 'order/save-new/request'
export const SAVE_NEW_ORDER_SUCCESS = 'order/save-new/success'
export const SAVE_NEW_ORDER_FAILURE = 'order/save-new/failure'
export const SAVE_ORDER_REQUEST = 'order/save/request'
export const SAVE_ORDER_SUCCESS = 'order/save/success'
export const SAVE_ORDER_FAILURE = 'order/save/failure'
export const TOGGLE_PAID_ORDER_REQUEST = 'order/toggle-paid/request'
export const TOGGLE_PAID_ORDER_SUCCESS = 'order/toggle-paid/success'
export const TOGGLE_PAID_ORDER_FAILURE = 'order/toggle-paid/failure'
export const DELETE_ORDER_REQUEST = 'order/delete/request'
export const DELETE_ORDER_SUCCESS = 'order/delete/success'
export const DELETE_ORDER_FAILURE = 'order/delete/failure'
export const toggleOrder = (id) => ({
type: TOGGLE_ORDER,
id,
})
export const showAddOrderProductDialog = () => ({
type: SHOW_ADD_ORDER_PRODUCT_DIALOG,
})
export const hideAddOrderProductDialog = () => ({
type: HIDE_ADD_ORDER_PRODUCT_DIALOG,
})
export const addProductToOrder = (id, quantity) => ({
type: ADD_PRODUCT_TO_ORDER,
id,
quantity,
})
export const removeProductFromOrder = (id) => ({
type: REMOVE_PRODUCT_FROM_ORDER,
id,
})
export const addToProductQuantity = (id) => ({
type: ADD_TO_PRODUCT_QUANTITY,
id,
})
export const subtractToProductQuantity = (id) => ({
type: SUBTRACT_TO_PRODUCT_QUANTITY,
id,
})
export const showSaveOrderDialog = () => ({
type: SHOW_SAVE_ORDER_DIALOG,
})
export const hideSaveOrderDialog = () => ({
type: HIDE_SAVE_ORDER_DIALOG,
})
export const changeOrderUser = (user) => ({
type: CHANGE_ORDER_USER,
user,
})
export const saveNewOrder = () => ({
type: SAVE_NEW_ORDER_REQUEST,
})
export const receiveNewOrder = (order) => ({
type: SAVE_NEW_ORDER_SUCCESS,
order,
})
export const failReceiveNewOrder = (reason) => ({
type: SAVE_NEW_ORDER_FAILURE,
reason,
})
export const saveOrder = () => ({
type: SAVE_ORDER_REQUEST,
})
export const receiveOrder = (order) => ({
type: SAVE_ORDER_SUCCESS,
order,
})
export const failReceiveOrder = (reason) => ({
type: SAVE_ORDER_FAILURE,
reason,
})
export const togglePaidOrder = () => ({
type: TOGGLE_PAID_ORDER_REQUEST,
})
export const receiveTogglePaidOrder = (order) => ({
type: TOGGLE_PAID_ORDER_SUCCESS,
order,
})
export const failReceiveTogglePaidOrder = (reason) => ({
type: TOGGLE_PAID_ORDER_FAILURE,
reason,
})
export const deleteOrder = () => ({
type: DELETE_ORDER_REQUEST,
})
export const removeOrder = (order) => ({
type: DELETE_ORDER_SUCCESS,
order,
})
export const failRemoveOrder = (reason) => ({
type: DELETE_ORDER_FAILURE,
reason,
})
|
export const disallowMultipleSpaces = () => {
var message, right, wrong;
message = "Only one space is allowed between identifiers, keywords, or any other tokens.";
right = "var x = 5;";
wrong = "var x = 5;\rvar x = 5;\rvar x = 5;";
return {
message: message,
right: right,
wrong: wrong
}
}; |
/* eslint-disable no-unused-expressions */
/* global describe, it */
'use strict'
const expect = require('chai').expect
const PassThrough = require('stream').PassThrough
const MeasureStream = require('../index.js')
describe('MeasureStream', function () {
it('should pass through all chunks unmodified', function () {
const obj = new MeasureStream()
const source = new PassThrough()
const target = new PassThrough()
source.pipe(obj).pipe(target)
source.write('hello ', 'utf8')
source.write('world', 'utf8')
source.end('!', 'utf8')
const expected = Buffer.from('hello world!', 'utf8')
expect(target.read()).to.satisfy((bytes) => bytes.equals(expected))
})
it("should emit 'measure' events", function (done) {
const obj = new MeasureStream()
obj.on('measure', function (event) {
expect(event).to.deep.equal({
chunks: 1,
totalLength: 42
})
done()
})
const data = new PassThrough()
data.pipe(obj)
data.end(Buffer.alloc(42))
})
it('should emit an event even for empty streams', function (done) {
const obj = new MeasureStream()
obj.on('measure', function (event) {
expect(event).to.deep.equal({
chunks: 0,
totalLength: 0
})
done()
})
const data = new PassThrough()
data.pipe(obj)
data.end()
})
it("should have a 'measurements' property", function () {
const obj = new MeasureStream()
expect(obj).to.have.a.property('measurements').that.deep.equals({
chunks: 0,
totalLength: 0
})
})
it("should update the 'measurements' property", function () {
const obj = new MeasureStream()
const data = new PassThrough()
data.pipe(obj)
data.write(Buffer.alloc(21))
data.end(Buffer.alloc(21))
expect(obj).to.have.a.property('measurements').that.deep.equals({
chunks: 2,
totalLength: 42
})
})
it('should not have measurements setter', function (done) {
const obj = new MeasureStream()
try {
obj.measurements = {}
done(new Error('did not throw'))
} catch (e) {
done()
}
})
it("should use object copy in 'measure' event", function (done) {
const obj = new MeasureStream()
obj.on('measure', function (event) {
event.chunks = 5
event.totalLength = 30
expect(obj.measurements).to.deep.equal({
chunks: 1,
totalLength: 42
})
done()
})
const data = new PassThrough()
data.pipe(obj)
data.end(Buffer.alloc(42))
})
})
|
var marked = require('marked');
var React = require('react');
var Markdown = React.createClass({
propTypes: {
text: React.PropTypes.string.isRequired,
},
render: function() {
return (
<div
{...this.props}
dangerouslySetInnerHTML={{__html: marked(this.props.text)}} />
);
},
});
module.exports = Markdown;
|
var videoWorks = (function (app) {
'use strict';
app.registerModule ('videoWorks', ['ngMaterial', 'bw-interface', 'photoWorks', 'photoWorks.services']);
app.registerModule ('videoWorks.services');
}(ApplicationConfiguration));
|
import { expect } from 'chai';
import React from 'react';
import { mount } from 'enzyme';
import { default as Dashboard, DashboardWithoutDndContext as DashboardWithoutDndContext } from '../../lib/components/Dashboard';
import LayoutRenderer from '../../lib/components/LayoutRenderer';
describe('<Dashboard />', () => {
it('Should have a <LayoutRenderer />', () => {
const component = mount(<Dashboard />);
expect(component.find(LayoutRenderer)).to.have.length(1);
});
});
describe('<DashboardWithoutDndContext />', () => {
it('Should have a <LayoutRenderer />', () => {
const component = mount(<DashboardWithoutDndContext />);
expect(component.find(LayoutRenderer)).to.have.length(1);
});
});
|
/*!
* Lazy Load - jQuery plugin for lazy loading images
*
* Copyright (c) 2007-2015 Mika Tuupola
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/mit-license.php
*
* Project home:
* http://www.appelsiini.net/projects/lazyload
*
* Version: 1.9.7
*
*/
(function($, window, document, undefined) {
var $window = $(window);
$.fn.lazyload = function(options) {
var elements = this;
var $container;
var settings = {
threshold : 0,
failure_limit : 0,
event : "scroll",
effect : "show",
container : window,
data_attribute : "original",
skip_invisible : false,
appear : null,
load : null,
// placeholder : "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC"
};
function update() {
var counter = 0;
elements.each(function() {
var $this = $(this);
if (settings.skip_invisible && !$this.is(":visible")) {
return;
}
if ($.abovethetop(this, settings) ||
$.leftofbegin(this, settings)) {
/* Nothing. */
} else if (!$.belowthefold(this, settings) &&
!$.rightoffold(this, settings)) {
$this.trigger("appear");
/* if we found an image we'll load, reset the counter */
counter = 0;
} else {
if (++counter > settings.failure_limit) {
return false;
}
}
});
}
if(options) {
/* Maintain BC for a couple of versions. */
if (undefined !== options.failurelimit) {
options.failure_limit = options.failurelimit;
delete options.failurelimit;
}
if (undefined !== options.effectspeed) {
options.effect_speed = options.effectspeed;
delete options.effectspeed;
}
$.extend(settings, options);
}
/* Cache container as jQuery as object. */
$container = (settings.container === undefined ||
settings.container === window) ? $window : $(settings.container);
/* Fire one scroll event per scroll. Not one scroll event per image. */
if (0 === settings.event.indexOf("scroll")) {
$container.bind(settings.event, function() {
return update();
});
}
this.each(function() {
var self = this;
var $self = $(self);
self.loaded = false;
/* If no src attribute given use data:uri. */
if ($self.attr("src") === undefined || $self.attr("src") === false) {
if ($self.is("img")) {
$self.attr("src", settings.placeholder);
}
}
/* When appear is triggered load original image. */
$self.one("appear", function() {
if (!this.loaded) {
if (settings.appear) {
var elements_left = elements.length;
settings.appear.call(self, elements_left, settings);
}
$("<img />")
.bind("load", function() {
var original = $self.attr("data-" + settings.data_attribute);
$self.hide();
if ($self.is("img")) {
$self.attr("src", original);
} else {
$self.css("background-image", "url('" + original + "')");
}
$self[settings.effect](settings.effect_speed);
self.loaded = true;
/* Remove image from array so it is not looped next time. */
var temp = $.grep(elements, function(element) {
return !element.loaded;
});
elements = $(temp);
if (settings.load) {
var elements_left = elements.length;
settings.load.call(self, elements_left, settings);
}
})
.attr("src", $self.attr("data-" + settings.data_attribute));
}
});
/* When wanted event is triggered load original image */
/* by triggering appear. */
if (0 !== settings.event.indexOf("scroll")) {
$self.bind(settings.event, function() {
if (!self.loaded) {
$self.trigger("appear");
}
});
}
});
/* Check if something appears when window is resized. */
$window.bind("resize", function() {
update();
});
/* With IOS5 force loading images when navigating with back button. */
/* Non optimal workaround. */
if ((/(?:iphone|ipod|ipad).*os 5/gi).test(navigator.appVersion)) {
$window.bind("pageshow", function(event) {
if (event.originalEvent && event.originalEvent.persisted) {
elements.each(function() {
$(this).trigger("appear");
});
}
});
}
/* Force initial check if images should appear. */
$(document).ready(function() {
update();
});
return this;
};
/* Convenience methods in jQuery namespace. */
/* Use as $.belowthefold(element, {threshold : 100, container : window}) */
$.belowthefold = function(element, settings) {
var fold;
if (settings.container === undefined || settings.container === window) {
fold = (window.innerHeight ? window.innerHeight : $window.height()) + $window.scrollTop();
} else {
fold = $(settings.container).offset().top + $(settings.container).height();
}
return fold <= $(element).offset().top - settings.threshold;
};
$.rightoffold = function(element, settings) {
var fold;
if (settings.container === undefined || settings.container === window) {
fold = $window.width() + $window.scrollLeft();
} else {
fold = $(settings.container).offset().left + $(settings.container).width();
}
return fold <= $(element).offset().left - settings.threshold;
};
$.abovethetop = function(element, settings) {
var fold;
if (settings.container === undefined || settings.container === window) {
fold = $window.scrollTop();
} else {
fold = $(settings.container).offset().top;
}
return fold >= $(element).offset().top + settings.threshold + $(element).height();
};
$.leftofbegin = function(element, settings) {
var fold;
if (settings.container === undefined || settings.container === window) {
fold = $window.scrollLeft();
} else {
fold = $(settings.container).offset().left;
}
return fold >= $(element).offset().left + settings.threshold + $(element).width();
};
$.inviewport = function(element, settings) {
return !$.rightoffold(element, settings) && !$.leftofbegin(element, settings) &&
!$.belowthefold(element, settings) && !$.abovethetop(element, settings);
};
/* Custom selectors for your convenience. */
/* Use as $("img:below-the-fold").something() or */
/* $("img").filter(":below-the-fold").something() which is faster */
$.extend($.expr[":"], {
"below-the-fold" : function(a) { return $.belowthefold(a, {threshold : 0}); },
"above-the-top" : function(a) { return !$.belowthefold(a, {threshold : 0}); },
"right-of-screen": function(a) { return $.rightoffold(a, {threshold : 0}); },
"left-of-screen" : function(a) { return !$.rightoffold(a, {threshold : 0}); },
"in-viewport" : function(a) { return $.inviewport(a, {threshold : 0}); },
/* Maintain BC for couple of versions. */
"above-the-fold" : function(a) { return !$.belowthefold(a, {threshold : 0}); },
"right-of-fold" : function(a) { return $.rightoffold(a, {threshold : 0}); },
"left-of-fold" : function(a) { return !$.rightoffold(a, {threshold : 0}); }
});
})(jQuery, window, document);
|
define(function(){
/**
* @module textShadow
* @description 兼容性如图
- 
- 不需要写任何前缀
- IE9 可以用canvas中的shadow[offsetX,offsetY,blur不能为0]、filter:shadow滤镜 filter:dropshadow
- E{filter:shadow(Color=颜色值,Direction=数值,Strength=数值)}
- [canvas中的shadow](../html5/canvas/CanvasRenderingContext2D.html#shadowColor)
- 实例:
- [发光效果](../../example/css3/text-shadow/glow.html)
- [发光效果canvas效果](../../example/css3/text-shadow/glow_IE9_canvas_shadow.html)
*/
var exports = {
/**
* css3文字阴影,有两种写法,可以按照规则连写
* @param {string} color 阴影的颜色
* @param {string} offsetX 阴影的x轴偏移量
* @param {string} offsetY 阴影的Y轴偏移量
* @param {string} blur 模糊半径
* @example
* text-shadow: rgba(0,123,6,0.5) 5px 5px 5px,rbga(0,123,6,0.1) 10px 10px 3px [,...]
* text-shadow: 5px 5px 5px rgba(0,123,6,0.5), 10px 10px 3px rgba(0,123,6,.1) [,...]
* text-shadow: none
*/
textShadow1: function(color,offsetX,offsetY,blur/*[...]*/){},
/**
* 参考[textShadow1](#textShadow1)
*/
textShadow2: function(offsetX,offsetY,blur,color/*[...]*/){},
/**
* 可以直接写为none
* @property {string} none 无文字阴影
*/
textShadow3: 'none'
};
return exports;
}); |
define(["Klass","UI","FS","DeferredUtil","WebSite","R","jshint"],
function (Klass,UI,FS,DU,WebSite,R,jshint) {
var HNOP=jshint.scriptURL();
const S=Klass.define({
//----METHODS
$this:true,
$:function (t,projectDir,prjList) {
var f=projectDir;
var name=FS.PathUtil.truncSEP(f.name());
t.prjList=prjList;
t.projectDir=projectDir;
t.name=name;
var u=t.dom(f);
t.u=u;
u.appendTo(t.prjList);
setTimeout(function () {
var tn=f.rel("images/").rel("icon_thumbnail.png");
if (tn.exists()) {
u.$vars.t.attr("src",tn.getURL());
}
},10);
},
hide: function (t) {
if (t.u) t.u.hide();
},
show: function (t) {
if (t.u) t.u.show();
},
url: {
get: function (t) {
var f=t.projectDir;
return WebSite.projectEditorURL+"?dir="+f.path();
}
},
dom: function (t) {
var url=t.url;
var name=t.name;
return UI("div", {"class":"project existentproject"},
["a", {href:url,"class":"projectLink"},
["img",{width:100,$var:"t",src:WebSite.top+"/images/nowprint.png"}]],
["div",
["a", {href:url,"class":"projectLink projectName"},name],
t.submenuExpr()
]
);
},
submenuExpr:function submenuExpr(t) {
var f=t.projectDir;
return ["span",{class:"dropdown"},
["button",{
//href:HNOP,
class:"submenu prjMenuButton",
on:{click:t.$bind.openSubmenu},"data-path":f.path() }," "],
["span",{class:"dropdown-content"},
["a",{href:HNOP,class:"submenu",on:{click:t.$bind.newWindow}},R("openProjectInNewWindow")],
["a",{href:HNOP,class:"submenu",on:{click:t.$bind.rename}},R("rename")],
["a",{href:HNOP,class:"submenu",on:{click:t.$bind.download}},R("downloadAsZip")],
["a",{href:HNOP,class:"submenu nwmenu",on:{click:t.$bind.openFolder}},R("openFolder")],
["a",{href:HNOP,class:"submenu",on:{click:t.$bind.remove}},R("delete")]
]
];
},
newWindow(t) {
window.open(t.url);
},
download: function (t) {
S.closeSubmenu();
return FS.zip.zip(t.projectDir).catch(DU.E);
},
remove: function (t) {
S.closeSubmenu();
if (!t.rmd) t.rmd=UI("div",{title:R("deleteProject")},
["div",R("deleteProjectFromItem",t.name)],
["div",
["input",{$var:"dl",type:"checkbox",checked:true}],
["label",{for:"dl"},R("downloadAsZipBeforeDeletion")]
],
["div",
["button",{on:{click:doRemove}},R("yes")],
["button",{on:{click:cancel}},R("no")]
]
);
t.rmd.$vars.dl.prop("checked",true);
t.rmd.dialog();
//console.log("t.rmd.data",$.data(t.rmd[0],"ui-dialog"));
function doRemove() {
var dl=t.rmd.$vars.dl.prop("checked");
return (dl?t.download():DU.resolve()).then(function () {
t.projectDir.rm({r:1});
t.u.remove();
t.rmd.dialog("close");
}).catch(DU.E);
}
function cancel() {
//console.log("t.rmd.data.cancel",$.data(t.rmd[0],"ui-dialog"));
t.rmd.dialog("close");
}
//t.projectDir.rm({r:1});
},
rename: function (t) {
S.closeSubmenu();
var np=prompt(R("inputNewProjectName"),
t.name);
if (!np || np=="") return;
np=FS.PathUtil.truncSEP(np);
var npd=t.projectDir.sibling(np+"/");
return npd.exists(function (e) {
if (e) {
alert(R("renamedProjectExists",np));
return;
}
//link.attr("href",HNOP).text("Wait...");
return t.projectDir.moveTo(npd).then(function () {
t.projectDir=npd;
t.name=npd;
t.u.find(".projectName").text(np);
t.u.find(".projectLink").attr("href",t.url);
//console.log("Renamed",t.url);
S.closeSubmenu();
}).catch(DU.E);
});
},
openFolder: function (t){
/*global require*/
var gui = require("nw.gui");//(global.nwDispatcher||global.nw).requireNwGui();
//var SEP = process.execPath;
gui.Shell.showItemInFolder(t.projectDir.path().replace(/\//g,require("path").sep));
S.closeSubmenu();
},
openSubmenu: function openSubmenu(t) {
S.addMenuHandler();
S.closeSubmenu();
S.showingSubMenu=t.u.find(".dropdown-content");
S.showingSubMenu.addClass("show");
if (!WebSite.isNW) S.showingSubMenu.find(".nwmenu").hide();
},
static$closeSubmenu: function () {
if (S.showingSubMenu) {
S.showingSubMenu.removeClass("show");
S.showingSubMenu=null;
}
},
static$addMenuHandler: function () {
if (S.menuHandlerAdded) return;
S.menuHandlerAdded=true;
$('html').click(function(e) {
if(!$(e.target).hasClass('submenu')) {
S.closeSubmenu();
}
});
}
//----END OF METHODS
});// end of klass
return S;
});
|
var Model = require('./model');
var Stat = module.exports = function() {
}
Stat.prototype = Model;
Stat.total = function( application, name, next ) {
var query = "SELECT sum(counter) as total from app_" + application + " WHERE name = '" + name + "'";
Model.client.query(query, next);
};
Stat.today = function( application, name, next ) {
var start = new Date(),
end = new Date();
startDay(start);
endDay(end);
var query = "SELECT sum(counter) as total from app_" + application + " WHERE name = '" + name + "'" + " AND logged_at >= '" + start.toUTCString() + "' AND logged_at <= '" + end.toUTCString() + "'";
Model.client.query(query, next);
};
Stat.monthly = function( application, name, next ) {
var query = "SELECT date_trunc('month', logged_at) AS \"month\", sum(counter) AS total " +
"FROM app_" + app_name + " WHERE name = '" + name + "' AND logged_at > now() - interval '1 year' GROUP BY \"month\" ORDER BY \"month\"";
Model.client.query(query, next);
};
Stat.create = function( application, stats, next ) {
var query = '';
if( stats instanceof Array )
stats.forEach(function(stat) {
query = insertStatQuery( application, stat, query );
});
else
query = insertStatQuery( application, stats, query );
Model.client.query(query, next);
};
function insertStatQuery ( application, stat, query ) {
var counter = stat.counter || 1,
duration = stat.duration || 0;
return query + ("INSERT INTO app_" + application + " (name, counter, duration) VALUES ('" +
stat.name + "', " +
counter + ", " +
duration + ");");
}
function startDay ( date ) {
date.setUTCHours(0);
date.setUTCMinutes(0);
date.setUTCSeconds(0);
}
function endDay ( date ) {
date.setUTCHours(24);
date.setUTCMinutes(59);
date.setUTCSeconds(59);
}
|
import { Camera } from 'three';
import VglObject3d from '../core/vgl-object3d';
import { inst } from '../constants';
/**
* An abstract camera component.
*/
export default {
extends: VglObject3d,
computed: {
/** The THREE.Camera instance. */
[inst]: () => new Camera(),
},
};
|
export { default } from 'flood-dropdown/services/dropdown'; |
import {describe, it} from 'mocha'
import {assert} from 'chai'
import Time from '../src/time.js'
describe('Time', () => {
describe('when now() is called', () => {
it('will return positive integer number', () => {
var now = Time.now()
assert.typeOf(now, 'number')
assert.isAbove(now, 0)
})
})
describe('when calling now and then another now after 30ms', () => {
it('then difference of will be 30 + epsilon ms', (done) => {
var t1 = Time.now()
setTimeout(() => {
var t2 = Time.now()
assert.closeTo(t2 - t1, 30, 2)
done()
}, 30)
})
})
}) |
// Generated by CoffeeScript 1.10.0
(function() {
var COL_JSON, COL_JSON_NESTED, COL_SHEET_1_JSON, COL_SHEET_2_JSON, COL_XLSX, ROW_JSON, ROW_SHEET_1_JSON, ROW_SHEET_2_JSON, ROW_XLSX, TEST_OPTIONS, chai, expect, fs, processFile;
processFile = require('../lib/excel-as-json').processFile;
fs = require('fs');
chai = require('chai');
chai.should();
expect = chai.expect;
ROW_XLSX = 'data/row-oriented.xlsx';
ROW_JSON = 'build/row-oriented.json';
COL_XLSX = 'data/col-oriented.xlsx';
COL_JSON = 'build/col-oriented.json';
COL_JSON_NESTED = 'build/newDir/col-oriented.json';
ROW_SHEET_1_JSON = '[{"firstName":"Jihad","lastName":"Saladin","address":{"street":"12 Beaver Court","city":"Snowmass","state":"CO","zip":81615}},{"firstName":"Marcus","lastName":"Rivapoli","address":{"street":"16 Vail Rd","city":"Vail","state":"CO","zip":81657}}]';
ROW_SHEET_2_JSON = '[{"firstName":"Max","lastName":"Irwin","address":{"street":"123 Fake Street","city":"Rochester","state":"NY","zip":99999}}]';
COL_SHEET_1_JSON = '[{"firstName":"Jihad","lastName":"Saladin","address":{"street":"12 Beaver Court","city":"Snowmass","state":"CO","zip":81615},"isEmployee":true,"phones":[{"type":"home","number":"123.456.7890"},{"type":"work","number":"098.765.4321"}],"aliases":["stormagedden","bob"]},{"firstName":"Marcus","lastName":"Rivapoli","address":{"street":"16 Vail Rd","city":"Vail","state":"CO","zip":81657},"isEmployee":false,"phones":[{"type":"home","number":"123.456.7891"},{"type":"work","number":"098.765.4322"}],"aliases":["mac","markie"]}]';
COL_SHEET_2_JSON = '[{"firstName":"Max","lastName":"Irwin","address":{"street":"123 Fake Street","city":"Rochester","state":"NY","zip":99999},"isEmployee":false,"phones":[{"type":"home","number":"123.456.7890"},{"type":"work","number":"505-505-1010"}],"aliases":["binarymax","arch"]}]';
TEST_OPTIONS = {
sheet: '1',
isColOriented: false,
omitEmptyFields: false
};
describe('process file', function() {
it('should notify on file does not exist', function(done) {
return processFile('data/doesNotExist.xlsx', null, TEST_OPTIONS, function(err, data) {
err.should.be.a('string');
expect(data).to.be.an('undefined');
return done();
});
});
it('should not blow up when a file does not exist and no callback is provided', function(done) {
processFile('data/doesNotExist.xlsx', function() {});
return done();
});
it('should not blow up on read error when no callback is provided', function(done) {
processFile('data/row-oriented.csv', function() {});
return done();
});
it('should notify on read error', function(done) {
return processFile('data/row-oriented.csv', null, TEST_OPTIONS, function(err, data) {
err.should.be.a('string');
expect(data).to.be.an('undefined');
return done();
});
});
it('should use defaults when caller specifies no options', function(done) {
return processFile(ROW_XLSX, null, null, function(err, data) {
expect(err).to.be.an('undefined');
JSON.stringify(data).should.equal(ROW_SHEET_1_JSON);
return done();
});
});
it('should process row oriented Excel files, write the result, and return the parsed object', function(done) {
var options;
options = {
sheet: '1',
isColOriented: false,
omitEmptyFields: false
};
return processFile(ROW_XLSX, ROW_JSON, options, function(err, data) {
var result;
expect(err).to.be.an('undefined');
result = JSON.parse(fs.readFileSync(ROW_JSON, 'utf8'));
JSON.stringify(result).should.equal(ROW_SHEET_1_JSON);
JSON.stringify(data).should.equal(ROW_SHEET_1_JSON);
return done();
});
});
it('should process sheet 2 of row oriented Excel files, write the result, and return the parsed object', function(done) {
var options;
options = {
sheet: '2',
isColOriented: false,
omitEmptyFields: false
};
return processFile(ROW_XLSX, ROW_JSON, options, function(err, data) {
var result;
expect(err).to.be.an('undefined');
result = JSON.parse(fs.readFileSync(ROW_JSON, 'utf8'));
JSON.stringify(result).should.equal(ROW_SHEET_2_JSON);
JSON.stringify(data).should.equal(ROW_SHEET_2_JSON);
return done();
});
});
it('should process col oriented Excel files, write the result, and return the parsed object', function(done) {
var options;
options = {
sheet: '1',
isColOriented: true,
omitEmptyFields: false
};
return processFile(COL_XLSX, COL_JSON, options, function(err, data) {
var result;
expect(err).to.be.an('undefined');
result = JSON.parse(fs.readFileSync(COL_JSON, 'utf8'));
JSON.stringify(result).should.equal(COL_SHEET_1_JSON);
JSON.stringify(data).should.equal(COL_SHEET_1_JSON);
return done();
});
});
it('should process sheet 2 of col oriented Excel files, write the result, and return the parsed object', function(done) {
var options;
options = {
sheet: '2',
isColOriented: true,
omitEmptyFields: false
};
return processFile(COL_XLSX, COL_JSON, options, function(err, data) {
var result;
expect(err).to.be.an('undefined');
result = JSON.parse(fs.readFileSync(COL_JSON, 'utf8'));
JSON.stringify(result).should.equal(COL_SHEET_2_JSON);
JSON.stringify(data).should.equal(COL_SHEET_2_JSON);
return done();
});
});
it('should create the destination directory if it does not exist', function(done) {
var options;
options = {
sheet: '1',
isColOriented: true,
omitEmptyFields: false
};
return processFile(COL_XLSX, COL_JSON_NESTED, options, function(err, data) {
var result;
expect(err).to.be.an('undefined');
result = JSON.parse(fs.readFileSync(COL_JSON_NESTED, 'utf8'));
JSON.stringify(result).should.equal(COL_SHEET_1_JSON);
JSON.stringify(data).should.equal(COL_SHEET_1_JSON);
return done();
});
});
it('should return a parsed object without writing a file', function(done) {
var error, options;
try {
fs.unlinkSync(ROW_JSON);
} catch (error) {
}
options = {
sheet: '1',
isColOriented: false,
omitEmptyFields: false
};
return processFile(ROW_XLSX, void 0, options, function(err, data) {
expect(err).to.be.an('undefined');
fs.existsSync(ROW_JSON).should.equal(false);
JSON.stringify(data).should.equal(ROW_SHEET_1_JSON);
return done();
});
});
return it('should notify on write error', function(done) {
return processFile(ROW_XLSX, 'build', TEST_OPTIONS, function(err, data) {
expect(err).to.be.an('string');
return done();
});
});
});
}).call(this);
|
'use strict';
import {$} from 'Vendor';
import {Backbone} from 'Vendor';
import {Radio} from 'Vendor';
import OrderItemsCollection from 'OrderItemsCollection';
export default Backbone.Model.extend({
url: 'http://localhost:8080/',
collection: OrderItemsCollection,
customerId: null,
initialize: function() {
this.routerChannel = Radio.channel('routerChannel');
},
checkout: function() {
$.ajax({
url: this.url + 'checkout',
type: 'POST',
async: true,
data: JSON.stringify(this),
contentType: 'application/json; charset=utf-8',
dataType: 'JSON',
statusCode: {
200: (response) => {
/*
* Navigate to success page
* Empty the basket
* */
},
},
});
},
});
|
/*
* MIT License
*
* Copyright (c) 2017 Donato Rimenti
*
* 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.
*/
// Gets the DB.
var db = db.getSiblingDB('blog');
// Creates the index required.
// Index on the date used for the homepage which loads the most
// recent posts.
db.posts.createIndex( {date : -1} );
// Index on permalink used for posts lookup.
db.posts.createIndex( {permalink : 1} );
// Compound index on tags and date used to lookup posts with a
// particular tag and sort them by date.
db.posts.createIndex(
{
tags : 1,
date : -1
}
); |
export fetchLicenses from "./fetchLicenses"
export fetchPeopleInPhoto from "./fetchPeopleInPhoto"
export fetchPhotoByID from "./fetchPhotoByID"
export fetchPhotoComments from "./fetchPhotoComments"
export fetchPhotoExif from "./fetchPhotoExif"
export fetchPhotoImages from "./fetchPhotoImages"
export fetchPhotoLocation from "./fetchPhotoLocation"
export fetchPhotoNotes from "./fetchPhotoNotes"
export fetchPhotoTags from "./fetchPhotoTags"
|
// @flow
/* eslint no-underscore-dangle: 0 */
/* **********************************************************
* File: test/utils/mica/parseDataPacket.spec.js
*
* Brief: Test for data packet parsing function
*
* Authors: George Whitfield, Craig Cheney
*
* 2017.09.20 CC - Updated test suite
* 2017.07.31 GW - Document Created
*
********************************************************* */
import sinon from 'sinon';
import { parseDataPacket, __RewireAPI__ as Rewire } from '../../../app/utils/mica/parseDataPacket';
// rewire module can access non-exported variables
describe('parseDataPacket.js test', () => {
// const rewire = require('rewire');
// Create fake time
const clock = sinon.useFakeTimers(123455);
// the path given for rewire needs to be relative to where rewire is on the computer I believe.
// const actions = rewire('/Users/George/srv_bilab/micaReactElectron/test/parseFunction/parseDataPacket');
function newPacketTime() {
const packetTime = new Date();
packetTime.microsecond = 0;
packetTime.lastLogged = null;
/* Modify packetTime for microseconds */
packetTime.addMicroseconds = function (usec) {
const micro = usec + this.microsecond;
const millisecond = Math.floor(micro / 1000);
this.setTime(this.getTime() + millisecond);
this.microsecond = (micro % 1000);
return this.microsecond;
};
// Look into 'extends'
packetTime.getMicroseconds = function () {
return this.microsecond;
};
/* returns the timestamp with microseconds */
packetTime.getTimeMicro = function () {
return Number(`${this.getTime()}.${this.microsecond}`);
};
return packetTime;
}
// Packet time variable to be inserted into the parser function
const newPacketTimeVariable = newPacketTime();
// Fake data
const peripheralId = 6;
// the data array is an array of 8 bit integers
const data = [110, 209, 90, 88, 130, 77, 34, 102];
const numChannels = 5;
const periodLength = 24;
const scalingConstant = 5;
const gain = 1;
const offset = [0, 0, 0, 0, 0];
// Defining variables from parsePacketData.js
// actions.__get__ uses rewire. Rewire.__get__ uses babel-plugin-rewire
const LOW_NIBBLE_MASK = Rewire.__get__('LOW_NIBBLE_MASK');
const HALF_BYTE_SHIFT = Rewire.__get__('HALF_BYTE_SHIFT');
const BYTE_SHIFT = Rewire.__get__('BYTE_SHIFT');
const ROLLUNDER_FLAG = Rewire.__get__('ROLLUNDER_FLAG');
const BITS_12 = Rewire.__get__('BITS_12');
const IS_ODD = Rewire.__get__('IS_ODD');
const parseRewire = Rewire.__get__('parseDataPacket');
const returnOfParse = parseDataPacket(
peripheralId,
data,
numChannels,
periodLength,
newPacketTimeVariable,
scalingConstant,
gain,
offset
);
const getValue = Rewire.__get__('getValue');
const twosCompToSigned = Rewire.__get__('twosCompToSigned');
const getValueSpy = sinon.spy(getValue);
const twosCompToSignedSpy = sinon.spy(twosCompToSigned);
const parseSpy = sinon.spy(parseRewire);
describe('Test variables', () => {
// Set up spy functions before the tests.
beforeAll(() => {
Rewire.__set__({
getValue: getValueSpy,
twosCompToSigned: twosCompToSignedSpy
});
parseDataPacket(
peripheralId,
data,
numChannels,
periodLength,
newPacketTimeVariable,
scalingConstant,
gain,
offset
);
});
afterAll(() => {
// Restore the clock
clock.restore();
});
// sinon.useFakeTimers(123456);
it('LOW_NIBBLE_MASK', () => {
expect(LOW_NIBBLE_MASK).toEqual(0x0F);
});
it('HAlF_BYTE_SHIFT', () => {
expect(HALF_BYTE_SHIFT).toEqual(4);
});
it('BYTE_SHIFT', () => {
expect(BYTE_SHIFT).toEqual(8);
});
it('ROLLUNDER_FLAG', () => {
expect(ROLLUNDER_FLAG).toEqual(0x08);
});
it('BITS_12', () => {
expect(BITS_12).toEqual(12);
});
it('IS_ODD', () => {
expect(IS_ODD).toEqual(0x01);
});
});
describe('parseDataPacket function', () => {
it('getValue function is called 12 times (twice for each channel)', () => {
expect(getValueSpy.callCount).toBe(12);
});
it('twosCompToSigned is called 6 times', () => {
expect(twosCompToSignedSpy.callCount).toBe(6);
});
it('Does not throw an error', () => {
expect(parseSpy.withArgs(
peripheralId,
data,
numChannels,
periodLength,
newPacketTimeVariable,
scalingConstant,
gain,
offset
)).not.toThrow();
});
it('Returns the correct values in the dataArray', () => {
expect(returnOfParse).toEqual([{
t: 123456.797,
d: [0.0034602076124567475,
-0.0025367833587011668,
-0.002485089463220676,
-0.0075075075075075074,
0.00909090909090909
]
}]);
});
describe('Data is calculated correctly', () => {
const t = returnOfParse[0].t;
const timeWithoutFakeTime = Number((t - 123456).toFixed(5));
const micro = (timeWithoutFakeTime * 1000) + 1000;
const timeDifferential = micro - periodLength;
it('Time Differential', () => {
expect(twosCompToSignedSpy.getCall(5).returnValue).toBe(timeDifferential);
});
it('Raw Data', () => {
const rawDataCalculation = ((((scalingConstant / returnOfParse[0].d[0]) + offset[0]) / gain));
expect(twosCompToSignedSpy.args[0][0]).toBe(rawDataCalculation);
});
it('Micro', () => {
expect(micro).toBe(periodLength + timeDifferential);
});
});
});
});
// will add more tests.
|
/*
* Copyright (c) 2014 Adobe Systems Incorporated. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
define(function (require, exports, module) {
"use strict";
var Immutable = require("immutable"),
_ = require("lodash");
/**
* @private
* @param {object} model
*/
var Link = Immutable.Record({
/**
* @type {string}
*/
_obj: null,
/**
* @type {string}
*/
elementReference: null,
/**
* @type {string}
*/
_path: null
});
/**
* @constructor
* @param {object} model
*/
var SmartObject = Immutable.Record({
/**
* @type {string}
*/
_obj: null,
/**
* @type {string}
*/
fileReference: null,
/**
* @type {boolean}
*/
linked: null,
/**
* @type {boolean}
*/
linkMissing: false,
/**
* @type {boolean}
*/
linkChanged: false,
/**
* @type {Link}
*/
link: null
});
/**
* Given a descriptor object from photoshop, build a new SmartObject
*
* @param {object} descriptor
* @return {SmartObject}
*/
SmartObject.fromDescriptor = function (descriptor) {
var nextSmartObject = new SmartObject(_.omit(descriptor, "link"));
if (descriptor.link && _.isObject(descriptor.link)) {
return nextSmartObject.set("link", new Link(descriptor.link));
} else {
return nextSmartObject;
}
};
module.exports = SmartObject;
});
|
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var core_1 = require('@angular/core');
var formData_service_1 = require('../data/formData.service');
var forms_1 = require('@angular/forms');
var ui_router_ng2_1 = require("ui-router-ng2");
var PersonalComponent = (function () {
function PersonalComponent(formDataService, router) {
var _this = this;
this.formDataService = formDataService;
this.router = router;
this.title = 'Get your personal loan quote in just seconds';
this.stateListData1 = [{ "name": "Mastek", "abbreviation": "AL" }, { "name": "Infosys", "abbreviation": "AL" }, { "name": "Cognizant", "abbreviation": "AL" }, { "name": "IBM", "abbreviation": "AL" }, { "name": "Hexaware", "abbreviation": "AL" }, { "name": "Atos", "abbreviation": "AL" }];
this.typeAheadSetup1 = {
customTemplate: '<div> {{item.name}}</div>',
// timeDelay: number;
// type: 'static', //static || dynamic. default value is dynamic
placeHolder: 'Work Place',
textPrperty: 'name',
valueProperty: 'name',
searchProperty: 'name',
onSelect: function (selectedItem) { console.log(selectedItem); },
asynchDataCall: function (value, cb) {
var result1 = _this.stateListData1.filter(function (item) {
return item.name.indexOf(value) !== -1;
});
//you can place your webservice call here
setTimeout(function () {
cb(result1);
}, 200);
},
};
this.stateListData = [{ "name": "Avon", "abbreviation": "AL" }, { "name": "Ayrshire", "abbreviation": "AL" }, { "name": "Bedfordshire", "abbreviation": "AL" }, { "name": "Cambridgeshire", "abbreviation": "AL" }, { "name": "Ceredigion", "abbreviation": "AL" }, { "name": "Glasgow", "abbreviation": "AL" }, { "name": "Greater Manchester", "abbreviation": "AL" }, { "name": "Leeds", "abbreviation": "AL" }, { "name": "London", "abbreviation": "AL" }, { "name": "Bradford", "abbreviation": "AL" }];
this.typeAheadSetup = {
customTemplate: '<div> {{item.name}}</div>',
// timeDelay: number;
// type: 'static', //static || dynamic. default value is dynamic
placeHolder: 'State name',
textPrperty: 'name',
valueProperty: 'name',
searchProperty: 'name',
onSelect: function (selectedItem) { console.log(selectedItem); },
asynchDataCall: function (value, cb) {
var result = _this.stateListData.filter(function (item) {
return item.name.indexOf(value) !== -1;
});
//you can place your webservice call here
setTimeout(function () {
cb(result);
}, 200);
},
};
}
PersonalComponent.prototype.ngOnInit = function () {
//this.personal = this.formDataService.getPersonal();
//console.log('Personal feature loaded!');
this.quoteData = JSON.parse(localStorage.getItem('getQuoteData'));
this.stateList = new forms_1.FormControl(this.quoteData.city);
this.work = new forms_1.FormControl(this.quoteData.employerName);
this.sal = new forms_1.FormControl(this.quoteData.salary);
this.loanamt = new forms_1.FormControl(this.quoteData.loanAmount);
this.loanInfoForm = new forms_1.FormGroup({
stateList: this.stateList,
work: this.work,
sal: this.sal,
loanamt: this.loanamt,
});
};
PersonalComponent.prototype.saveInfo = function (formValues) {
var _this = this;
this.formDataService.postQuoteInfo(formValues)
.subscribe(function (data) {
_this.quoteDataFromApi_val = JSON.stringify(data);
//console.log("==========="+this.quoteDataFromApi);
localStorage.setItem('getQuoteData', _this.quoteDataFromApi_val);
_this.router.stateService.go('offer');
}, function (error) {
_this.error = error;
//console.log(this.error);
});
};
PersonalComponent.prototype.rangeValueChanged = function (event, start, end) {
var start_el = this.getElement(start);
var end_el = this.getElement(end);
// start_el.innerText = event.startValue;
//end_el.innerText = event.endValue;
};
PersonalComponent.prototype.getElement = function (data) {
if (typeof (data) == 'string') {
return document.getElementById(data);
}
if (typeof (data) == 'object' && data instanceof Element) {
return data;
}
return null;
};
PersonalComponent = __decorate([
core_1.Component({
selector: 'mt-wizard-personal',
templateUrl: 'app/personal/personal.component.html'
}),
__metadata('design:paramtypes', [formData_service_1.FormDataService, ui_router_ng2_1.UIRouter])
], PersonalComponent);
return PersonalComponent;
}());
exports.PersonalComponent = PersonalComponent;
//# sourceMappingURL=personal.component.ts.BASE.js.map |
import * as ENUMS from '../../enums/moonlight'
/**
* cast state data to moonlight CLI options
* @param {any} state
* @return {string[]}
*/
function getMoonlightOptionsFromState (state) {
let options = []
// screen resolution
if (!state.width || !state.height) {
options.push('-' + ENUMS.RESOLUTION.properties[ state.resolution ].value)
} else {
options.push(
'-width',
state.width,
'-height',
state.height
)
}
// parametrics
if (state.fps) options.push('-fps', state.fps)
// TODO bitrate
// TODO packet size
// booleans
if (state.unsupported) options.push('-unsupported')
if (state.remote) options.push('-remote')
if (state.surround) options.push('-surround')
if (state.windowed) options.push('-windowed')
// enumerators
if (state.codec) options.push('-codec', ENUMS.CODEC.properties[ state.codec ].value)
return options
}
/**
* Base state on store creation
*/
export const state = {
width: null,
height: null,
resolution: ENUMS.RESOLUTION.HD,
fps: 60,
bitrate: null,
packetsize: null,
codec: ENUMS.CODEC.AUTO,
remote: true, // Enable the optimizations for remote connections in GFE.
nosops: false, // Stop GFE from changing the graphical settings of the requested game or application.
unsupported: false, // Try streaming if GFE version is unsupported
debug: ENUMS.DEBUG.HIGH,
surround: false, // Enable 5.1 surround sound instead of stereo.
/*
-localaudio
Play the audio on the host computer instead of this device.
-keydir [DIRECTORY]
Change the directory to save encryption keys to DIRECTORY. By default the encryption keys are stored in $XDG_CACHE_DIR/moonlight or ~/.cache/moonlight
-mapping [MAPPING]
Use MAPPING as the mapping file for all inputs.
This mapping file should have the same format as the gamecontrollerdb.txt for SDL2.
By default the gamecontrollerdb.txt provided by Moonlight Embedded is used.
-platform [PLATFORM]
Select platform for audio and video output and input. <PLATFORM> can be pi, imx, aml, x11, x11_vdpau, sdl or fake.
-input [INPUT]
Enable the INPUT device. By default all available input devices are enabled. Only evdev devices /dev/input/event* are supported.
-audio [DEVICE]
Use <DEVICE> as audio output device. The default value is 'sysdefault' for ALSA and 'hdmi' for OMX on the Raspberry Pi.
*/
windowed: false
}
/**
* Computed properties
*/
export const getters = { }
/**
* Store mutation functions
*/
export const mutations = {
/**
* TODO docs
*/
updateMoonlightOptions (state, data) {
Object.assign(state, data)
}
}
/**
* Async store functions
*/
export const actions = {
/**
* Spawn a new moonlight command instance
*/
async spawnMoonlight ({ commit, dispatch, getters, state }, { action, profile, verify }) {
profile = profile || getters.activeProfile
verify = verify || (() => Promise.resolve())
if (!profile) throw new Error('Profile not found')
await verify(profile)
return dispatch('spawnCommand', {
command: 'moonlight',
// TODO use fake moonlight while NOT testing on a RasPi
// command: path.join(process.cwd(), 'bin', 'moonlight.js'),
args: [
action,
...getMoonlightOptionsFromState(state),
profile.host
],
options: {
shell: false,
detached: false
}
})
},
/**
* Pair this computer with the host
*/
pair ({ commit, dispatch, getters, state }, profile) {
return dispatch('spawnMoonlight', {
action: 'pair',
profile,
verify: async (profile) => {
if (profile.paired) {
throw new Error('Profile is already paired')
}
}
})
},
/**
* Unpair this computer with the host
*/
unpair ({ commit, dispatch, getters, state }, profile) {
return dispatch('spawnMoonlight', {
action: 'unpair',
profile,
verify: async (profile) => {
if (!profile.paired) {
throw new Error('This profile is not paired')
}
}
})
},
/**
* Stream game from host to this computer
*/
stream ({ commit, dispatch, getters, state }, profile) {
return dispatch('spawnMoonlight', {
action: 'stream',
profile,
verify: async (profile) => {
if (!profile.paired) {
throw new Error('This profile is not paired')
}
}
})
},
/**
* List all available games and application on host
*/
list ({ commit, dispatch, getters, state }, profile) {
return dispatch('spawnMoonlight', {
action: 'list',
profile,
verify: async (profile) => {
if (!profile.paired) {
throw new Error('This profile is not paired')
}
}
})
},
/**
* Quit the current running game or application on host
*/
quit ({ commit, dispatch, getters, state }, profile) {
return dispatch('spawnMoonlight', {
action: 'quit',
profile,
verify: async (profile) => {
if (!profile.paired) {
throw new Error('This profile is not paired')
}
}
})
}
}
|
import React from 'react';
import { Header, Segment } from 'semantic-ui-react';
import { Link } from 'redux-little-router';
import { BLOG_NAME, BLOG_SLOGAN } from '../constants/config';
export default ({ backToHome }) => (
<div>
<Header
as='h1'
attached='top'
style={{
cursor: 'pointer',
}}
>
<Link href='/'>{BLOG_NAME}</Link>
</Header>
<Segment attached>
{BLOG_SLOGAN}
</Segment>
</div>
); |
/**
* ovh-api-archive: View or compare an API archive from OVH, SYS, KS, and RunAbove.
*
* @author Jean-Philippe Blary (@blary_jp)
* @url https://github.com/blaryjp/ovh-api-archive
* @license MIT
*/
'use strict';
angular.module('apidiffApp', [
'ngCookies',
'ngSanitize',
'ngRoute',
'ui.ace'
])
.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/home.html',
controller: 'MainCtrl'
})
.when('/:api', {
templateUrl: 'views/home.html',
controller: 'MainCtrl'
})
.when('/:api/:view', {
templateUrl: 'views/main.html',
controller: 'MainCtrl',
reloadOnSearch: false
})
.otherwise({
redirectTo: '/'
});
});
|
'use strict';
/**
* Exposes the drivers
**/
var drivers = {};
module.exports = {
register: function(key, db) {
drivers[key] = db;
},
instance: function(key) {
var driver = drivers[key];
if(!driver) {
throw new Error('the specified driver is not supported');
}
return driver;
}
};
|
/** This module defines the routes for videos using the store.js as db memory
*
* @author Johannes Konert
* @licence CC BY-SA 4.0
*
* @module routes/videos
* @type {Router}
*/
// remember: in modules you have 3 variables given by CommonJS
// 1.) require() function
// 2.) module.exports
// 3.) exports (which is module.exports)
// modules
var express = require('express');
var logger = require('debug')('me2u4:videos');
var store = require('../blackbox/store');
var videos = express.Router();
// if you like, you can use this for task 1.b:
var requiredKeys = {title: 'string', src: 'string', length: 'number'};
var optionalKeys = {description: 'string', playcount: 'number', ranking: 'number'};
var internalKeys = {id: 'number', timestamp: 'number'};
/*videos.use(function (req, res, next) {
console.log('Request of type ' + req.method + ' to URL ' + req.originalUrl);
next();
});*/
// routes **********************
videos.route('/')
.get(function (req, res, next) {
var url = req.url;
//console.log(req.url);
if (req.url == "/") {
var selectionList = store.select('videos', null);
if (selectionList.length == 0) {
res.set('Content-Type', 'application/json');
res.status(204).end();
return;
}
req.body = selectionList;
res.set('Content-Type', 'application/json');
res.status(200).json(req.body).end();
} else {
var limitAndOffset = url.substring(2, url.length);
var tempArr = [];
var offset = 0;
var limit = 0;
/**
* if
* true --> more params --> split("&") --> split("=")
* else --> one param (offset or limit)--> split("=")
*/
if (limitAndOffset.length > 13) {
var splitLimitAndOffset = limitAndOffset.split("&");
var afterSplitTwo_SplitInParam = [];
//console.log(splitLimitAndOffset);
for (var i = 0; i < splitLimitAndOffset.length; i++) {
afterSplitTwo_SplitInParam.push(splitLimitAndOffset[i].split("="));
}
//console.log(afterSplitTwo_SplitInParam);
var selectionListWithMoreParams = store.select('videos', null);
if (selectionListWithMoreParams.length == 0) {
res.set('Content-Type', 'application/json');
res.status(204).end();
return;
}
for (var a = 0; a < afterSplitTwo_SplitInParam.length; a++) {
var currentParam = afterSplitTwo_SplitInParam[a];
//console.log(currentParam);
if (currentParam[0] == "offset") {
offset = currentParam[1];
try {
offset = parseInt(offset);
} catch (err) {
//console.log("not a number");
res.set('Content-Type', 'application/json');
res.status(400).end();
}
if (offset <= 0 || typeof offset !== 'number' || isNaN(offset)
|| offset == selectionListWithMoreParams.length) {
res.set('Content-Type', 'application/json');
res.status(400).end();
return;
}
} else if (currentParam[0] == "limit") {
limit = currentParam[1];
try {
limit = parseInt(limit);
} catch (err) {
//console.log("not a number");
res.set('Content-Type', 'application/json');
res.status(400).end();
}
if (limit <= 0 || typeof limit !== 'number' || isNaN(limit)) {
res.set('Content-Type', 'application/json');
res.status(400).end();
return;
}
} else {
res.end();
return;
}
}
var typeLimit = 0;
if (limit > selectionListWithMoreParams.length) {
typeLimit = selectionListWithMoreParams.length;
} else {
typeLimit = limit;
}
if (offset+typeLimit > selectionListWithMoreParams.length) {
typeLimit -= offset;
}
for (var j = 0; j < typeLimit; j++) {
tempArr.push(selectionListWithMoreParams[j+offset]);
}
} else {
var param = limitAndOffset.split("=");
//noinspection JSDuplicatedDeclaration
var selectionListWithOneParam = store.select('videos', null);
if (selectionListWithOneParam.length == 0) {
res.set('Content-Type', 'application/json');
res.status(204).end();
return;
}
if (param[0] == "offset") {
offset = param[1];
if (offset < 0) {
res.set('Content-Type', 'application/json');
res.status(400).end();
return;
}
for (var i = offset; i < selectionListWithOneParam.length; i++) {
tempArr.push(selectionListWithOneParam[i]);
}
} else if (param[0] == "limit") {
limit = param[1];
if (limit <= 0) {
res.set('Content-Type', 'application/json');
res.status(400).end();
return;
}
for (var i = 0; i < limit; i++) {
tempArr.push(selectionListWithOneParam[i]);
}
} else {
res.end();
return;
}
}
//console.log("ich bin durch2");
//console.log(tempArr);
res.set('Content-Type', 'application/json');
res.status(200).json(tempArr).end();
}
})
.post(function (req, res, next) {
req.body.timestamp = new Date().getTime();
if (req.body.playcount === undefined) req.body.playcount = 0;
if (req.body.ranking === undefined) req.body.ranking = 0;
var id = store.insert('videos', req.body);
// set code 201 "created" and send the item back
res.status(201).json(store.select('videos', id));
})
.put(function (req, res, next) {
var fehler = {error: {message: "Method Not Allowed", code: 405}};
if (req.body.error == undefined) req.body.error = fehler;
res.set('Content-Type', 'application/json');
res.status(405).json(req.body.error);
});
videos.route('/:id')
.get(function (req, res, next) {
var url = req.url;
var kindOf = url.substring(0, 12);
if (kindOf == "/" + req.params.id + "?filter=") {
var filterPart = url.substring(12, url.length);
var filterPara = filterPart.split("%2C");
var arr = {};
for (var i = 0; i < filterPara.length; i++) {
var vidArr = store.select('videos', null);
var para = filterPara[i];
if (para == "src") for (var j = 0; j < vidArr.length; j++) arr[para] = vidArr[j].src;
else if (para == "title") for (var j = 0; j < vidArr.length; j++) arr[para] = vidArr[j].title;
else if (para == "length") for (var j = 0; j < vidArr.length; j++) arr[para] = vidArr[j].length;
else if (para == "timestamp") for (var j = 0; j < vidArr.length; j++) arr[para] = vidArr[j].timestamp;
else if (para == "id") for (var j = 0; j < vidArr.length; j++) arr[para] = vidArr[j].id;
else if (para == "ranking") for (var j = 0; j < vidArr.length; j++) arr[para] = vidArr[j].ranking;
else if (para == "description") for (var j = 0; j < vidArr.length; j++) arr[para] = vidArr[j].description;
else if (para == "playcount") for (var j = 0; j < vidArr.length; j++) arr[para] = vidArr[j].playcount;
else {
res.status(400).end();
}
}
//console.log(arr);
req.body.keys = arr;
res.status(200).json(req.body.keys);
}
})
.post(function (req, res, next) {
var fehler = {error: {message: "Method Not Allowed", code: 405}};
if (req.body.error == undefined) req.body.error = fehler;
res.set('Content-Type', 'application/json');
res.status(405).json(req.body.error);
})
.delete(function (req, res, next) {
if (store.select('videos', req.params.id) != undefined) {
store.remove('videos', req.params.id);
res.set('Content-Type', 'application/json');
res.status(204).end();
}
var fehler = {error: {message: "Method Not Allowed", code: 404}};
if (req.body.error == undefined) req.body.error = fehler;
res.set('Content-Type', 'application/json');
res.status(404).json(req.body.error);
})
.put(function (req, res, next) {
store.replace('videos', req.params.id, req.body);
res.status(200).json(store.select('videos', req.params.id)).end();
});
module.exports = videos;
|
var fs = require('fs')
var net = require('net')
var crypto = require('crypto') |
import 'echarts/lib/chart/heatmap'
import 'echarts/lib/component/visualMap'
import 'echarts/extension/bmap/bmap'
import 'echarts/lib/chart/map'
import { heatmap } from './main'
import Core from '../../core'
export default Object.assign({}, Core, {
name: 'VeHeatmap',
data () {
this.chartHandler = heatmap
return {}
}
})
|
const mapService = {
MapSPResponseToSuppliers(SPsuppliersArray) {
var array = SPsuppliersArray.map(function (item) {
var newItem = {
Address: {
City: '',
Street: '',
ZipCode: ''
},
CompanyName: '',
TaxId: '',
Id: -1
};
newItem.CompanyName = item.Title ? item.Title : item.SupplierName ? item.SupplierName : "Name not found";
newItem.TaxId = item.TaxID;
newItem.Address.City = item.City;
newItem.Address.Street = item.Street;
newItem.Address.ZipCode = item.ZIP_x0020_Code ? item.ZIP_x0020_Code : item.ZIPCode ? item.ZIPCode : "Zip Code not found";
newItem.SharepointInnerId = item.Id;
return newItem;
});
return array;
}
}
export default mapService; |
import {toolsPoint} from "./toolsPoint";
import {toolsVector} from "toolsVector";
export class vector {
constructor(vx, vy, vz) {
this.vx = vx ? vx : 0;
this.vy = vy ? vy : 0;
this.vz = vz ? vz : 0;
}
toString() {
return "[object vector]";
}
/**
* @syntax setPoint(p1,p2 )
* @param {Point} p1
* @param {Point} p2
* @returns {Self} + p1 + p2
*/
setPoint(p1, p2) {
if (p1.toString() === "[object point]" && p2.toString() === "[object point]") {
var V = toolsPoint.vectorBetween(p1, p2);
this.vx = V.vx;
this.vy = V.vy;
this.vz = V.vz;
this.p1 = p1;
this.p2 = p2;
this.distance = p1.distance(p2);
this.angle = {
x: Math.atan2(this.vy, this.vx) + Math.PI
}
} else {
throw new Error("setPoint() The arguments must be a point");
}
}
/*
* @syntax vectorProduct(v2 )
* @param {Vector} v2
* @returns {Float}
*/
vectorProduct(v2) {
return toolsVector.vectorProduct(this, v2);
}
/**
* @syntax scalarProduct(v2 )
* @param {Vector} v2
* @returns {Vector}
*/
scalarProduct(v2) {
return toolsVector.scalarProduct(this, v2);
}
/**
* @syntax normalize( )
* @returns {Vector}
*/
normalize() {
return toolsVector.normalize(this);
}
/**
* @syntax cross(v2)
* @param {Vector} v2
* @returns {Point}
*/
cross(v2) {
return toolsVector.cross(this, v2);
}
/**
* @syntax angle(v2,type)
* @param {Vector} v2
* @param {String} optionnal(deg|rad) type
* @returns {Float}
*/
angleBetweenVector(v2, type) {
return toolsVector.angleBetweenVector(this, v2, type);
}
pointBelong(p1) {
return toolsVector.pointBelong(this, p1);
}
}
|
app.directive('growl', function () {
return {
restrict: 'C',
link: function (scope, element, attrs) {
scope.$on("UPDATE_ORDER_ITEM_COUNT", function (event, message) {
$.gritter.add({
title: message.title,
text: message.message,
image: message.image
});
});
}
};
});
|
var UserVo = require(_path.src + "/vo/UserVo.js");
var SqlMapClient = require(_path.lib + "/Sqlmapclient.js");
var UserDao = function()
{
this.sqlMapClient = new SqlMapClient("user");
if(UserDao.caller != UserDao.getInstance)
throw new Error("This UserDao object cannot be instanciated");
};
UserDao.instance = null;
UserDao.getInstance = function(){
if(this.instance == null)
this.instance = new UserDao();
return this.instance;
}
UserDao.prototype.getUserList = function(callback)
{
this.sqlMapClient.selectsQuery("getUserList", {}, callback);
};
UserDao.prototype.getUserById = function(id, callback)
{
var vo = new UserVo();
vo.id = id;
this.sqlMapClient.selectQuery("getUser", vo, callback);
};
UserDao.prototype.getUserByName = function(name, callback)
{
var vo = new UserVo();
vo.name = name;
this.sqlMapClient.selectQuery("getUser", userVo, callback);
};
UserDao.prototype.getUserByDisplayId = function(displayId, callback)
{
var vo = new UserVo();
vo.displayId = displayId;
this.sqlMapClient.selectQuery("getUser", userVo, callback);
};
UserDao.prototype.getUserWithInfo = function(userId, callback)
{
var vo = new UserVo();
vo.id = userId;
this.sqlMapClient.selectQuery("getUserWithInfo", vo, callback);
};
UserDao.prototype.getEncryptKey = function(id, callback)
{
this.sqlMapClient.selectQuery("getEncryptKey", id, callback);
};
UserDao.prototype.insertUser = function(userVo, callback)
{
this.sqlMapClient.insertQuery("insertUser", userVo, callback);
};
UserDao.prototype.updateUser = function(userVo, callback)
{
this.sqlMapClient.updateQuery("updateUser", userVo, callback);
};
UserDao.prototype.updateLastAccessDate = function(id, callback)
{
this.sqlMapClient.updateQuery("updateLastAccessDate", id, callback);
};
UserDao.prototype.updateUserPassword = function(id, password, callback)
{
var vo = new UserVo();
vo.id = id;
vo.password = password;
this.sqlMapClient.updateQuery("updateUserPassword", vo, callback);
};
UserDao.prototype.dropOut = function(userId, callback)
{
this.sqlMapClient.deleteQuery("dropOut", userId, callback);
};
UserDao.prototype.deleteUser = function(userId, callback)
{
this.sqlMapClient.deleteQuery("deleteUser", userId, callback);
};
module.exports = UserDao.getInstance(); |
(function() {
'use strict';
angular.module('Basket')
.factory('ContextMenu',ContextMenu);
ContextMenu.$inject = ['ContextMenuItem'];
function ContextMenu(ContextMenuItem) {
Service.prototype = {
get: get
};
function Service() {
this.menuItems = [];
angular.forEach(arguments, forEachFn.bind(this));
return this.menuItems;
function forEachFn(menuItem) {
this.menuItems.push(new ContextMenuItem(menuItem));
}
}
return Service;
////////////////
function get() {
return this.menuItems;
}
}
})(); |
'use strict';
var _ = require('lodash');
var Scope = require('../src/scope');
describe('Scope', function () {
it("can be constructed and used as an object", function () {
var scope = new Scope();
scope.aProperty = 1;
expect(scope.aProperty).toBe(1);
});
describe('digest', function () {
var scope;
beforeEach(function () {
scope = new Scope();
});
it("calls the listener function of a watch on first $digest", function () {
var watchFn = function () {
return 'wat';
};
var listenerFn = jasmine.createSpy();
scope.$watch(watchFn, listenerFn);
scope.$digest();
expect(listenerFn).toHaveBeenCalled();
});
it('calls the watch function with the scope as the argument', function () {
var watchFn = jasmine.createSpy();
var listenerFn = function () {
};
scope.$watch(watchFn, listenerFn);
scope.$digest();
expect(watchFn).toHaveBeenCalledWith(scope);
});
it('calls the listener function when the watched value changes', function () {
scope.someValue = 'a';
scope.counter = 0;
scope.$watch(
function (scope) {
return scope.someValue;
},
function (newValue, oldValue, scope) {
scope.counter++;
}
);
expect(scope.counter).toBe(0);
scope.$digest();
expect(scope.counter).toBe(1);
scope.$digest();
expect(scope.counter).toBe(1);
scope.someValue = 'b';
expect(scope.counter).toBe(1);
scope.$digest();
expect(scope.counter).toBe(2);
});
it('calls the listener when watch value is first undefined', function () {
scope.counter = 0;
scope.$watch(
function (scope) {
return scope.someValue;
},
function (newValue, oldValue, scope) {
scope.counter++;
}
);
scope.$digest();
expect(scope.counter).toBe(1);
});
it('calls listener with the new value as the old value the first time', function () {
scope.someValue = 123;
var oldValueGiven;
scope.$watch(
function (scope) {
return scope.someValue;
},
function (newValue, oldValue, scope) {
oldValueGiven = oldValue;
}
);
scope.$digest();
expect(oldValueGiven).toBe(123);
});
it('may have watchers that omit the listener function', function () {
var watchFn = jasmine.createSpy().and.returnValue('something');
scope.$watch(watchFn);
scope.$digest();
expect(watchFn).toHaveBeenCalled();
});
it('triggers chained watchers in the same digest', function () {
scope.name = 'Jane';
scope.$watch(
function (scope) {
return scope.nameUpper;
},
function (newValue, oldValue, scope) {
if (newValue) {
scope.initial = newValue.substr(0, 1) + '.';
}
}
);
scope.$watch(
function (scope) {
return scope.name;
},
function (newValue, oldValue, scope) {
if (newValue) {
scope.nameUpper = newValue.toUpperCase();
}
}
);
scope.$digest();
expect(scope.initial).toBe('J.');
scope.name = 'Bob';
scope.$digest();
expect(scope.initial).toBe('B.');
});
it('gives up on watches after 10 iterations', function () {
scope.counterA = 0;
scope.counterB = 0;
scope.$watch(
function (scope) {
return scope.counterA;
},
function (newValue, oldValue, scope) {
scope.counterB++;
}
);
scope.$watch(
function (scope) {
return scope.counterB;
},
function (newValue, oldValue, scope) {
scope.counterA++;
}
);
expect(function () {
scope.$digest();
}).toThrow();
});
it('ends the digest when the last watch is clean', function () {
scope.array = _.range(100);
var watchExecutions = 0;
_.times(100, function (i) {
scope.$watch(
function (scope) {
watchExecutions++;
return scope.array[i];
},
function (newValue, oldValue, scope) {
}
);
});
scope.$digest();
expect(watchExecutions).toBe(200);
scope.array[0] = 420;
scope.$digest();
expect(watchExecutions).toBe(301);
});
it('does not end digest so that new watches are not run', function () {
scope.aValue = 'abc';
scope.counter = 0;
scope.$watch(
function (scope) {
return scope.aValue;
},
function (newValue, oldValue, scope) {
scope.$watch(
function (scope) {
return scope.aValue;
},
function (newValue, oldValue, scope) {
scope.counter++;
}
);
}
);
scope.$digest();
expect(scope.counter).toBe(1);
});
it('compares based on values if enabled', function () {
scope.aValue = [1, 2, 3];
scope.counter = 0;
scope.$watch(
function (scope) {
return scope.aValue;
},
function (newValue, oldValue, scope) {
scope.counter++;
},
true
);
scope.$digest();
expect(scope.counter).toBe(1);
scope.aValue.push(4);
scope.$digest();
expect(scope.counter).toBe(2);
});
it('correctly handles NaNs', function () {
scope.number = 0 / 0;
scope.counter = 0;
scope.$watch(
function (scope) {
return scope.number;
},
function (newValue, oldValue, scope) {
scope.counter++;
}
);
scope.$digest();
expect(scope.counter).toBe(1);
scope.$digest();
expect(scope.counter).toBe(1);
});
it('executes $eval\'d function and returns result', function () {
scope.aValue = 42;
var result = scope.$eval(function () {
return scope.aValue;
});
expect(result).toBe(42);
});
it('passes the second $eval argument straight through', function () {
scope.aValue = 42;
var result = scope.$eval(function (scope, arg) {
return scope.aValue + arg;
}, 2);
expect(result).toBe(44);
});
it('executes $apply\'ed function and starts the digest', function () {
scope.aValue = 'someValue';
scope.counter = 0;
scope.$watch(
function (scope) {
return scope.aValue;
},
function (newValue, oldValue, scope) {
scope.counter++;
}
);
scope.$digest();
expect(scope.counter).toBe(1);
scope.$apply(function () {
scope.aValue = 'modifiedValue';
});
expect(scope.counter).toBe(2);
});
it('executes $evalAsync\'d function later but in the same digest cycle', function () {
scope.aValue = [1, 2, 3];
scope.asyncEvaluated = false;
scope.asyncEvaluatedImmediately = false;
scope.$watch(
function (scope) {
return scope.aValue;
},
function (newValue, oldValue, scope) {
scope.$evalAsync(function () {
scope.asyncEvaluated = true;
});
scope.asyncEvaluatedImmediately = scope.asyncEvaluated;
}
);
scope.$digest();
expect(scope.asyncEvaluated).toBe(true);
expect(scope.asyncEvaluatedImmediately).toBe(false);
});
it('eventually halts $evalAsyncs added by watches', function () {
scope.aValue = [1, 2, 3];
scope.$watch(
function (scope) {
scope.$evalAsync(function (scope) {
});
return scope.aValue;
},
function (newValue, oldValue, scope) {
}
);
expect(function () {
scope.$digest();
}).toThrow();
});
it('executes $evalAsync\'ed functions added by watch function', function () {
scope.aValue = [1, 2, 3];
scope.asyncEvaluated = false;
scope.$watch(
function (scope) {
if (!scope.asyncEvaluated) {
scope.$evalAsync(function (scope) {
scope.asyncEvaluated = true;
});
}
return scope.aValue;
},
function (newValue, oldValue, scope) {
}
);
scope.$digest();
expect(scope.asyncEvaluated).toBe(true);
});
it('executes $evalAsync\'ed functions even when not dirty', function () {
scope.aValue = [1, 2, 3];
scope.asyncEvaluatedTimes = 0;
scope.$watch(
function (scope) {
if (scope.asyncEvaluatedTimes < 2) {
scope.$evalAsync(function (scope) {
scope.asyncEvaluatedTimes++;
});
}
return scope.aValue;
},
function (newValue, oldValue, scope) {
}
);
scope.$digest();
expect(scope.asyncEvaluatedTimes).toBe(2);
});
it('has a $$phase field whose value is the current digest phase', function () {
scope.aValue = [1, 2, 3];
scope.phaseInWatchFunction = undefined;
scope.phaseInApplyFunction = undefined;
scope.phaseInListenerFunction = undefined;
scope.$watch(
function (scope) {
scope.phaseInWatchFunction = scope.$$phase;
return scope.aValue;
},
function (newValue, oldValue, scope) {
scope.phaseInListenerFunction = scope.$$phase;
}
);
scope.$apply(function () {
scope.phaseInApplyFunction = scope.$$phase;
});
expect(scope.phaseInWatchFunction).toBe('$digest');
expect(scope.phaseInListenerFunction).toBe('$digest');
expect(scope.phaseInApplyFunction).toBe('$apply');
});
it('schedules a digest in $evalAsync', function (done) {
scope.aValue = 'abc';
scope.counter = 0;
scope.$watch(
function (scope) {
return scope.aValue;
},
function (newValue, oldValue, scope) {
scope.counter++;
}
);
scope.$evalAsync(function (scope) {
});
expect(scope.counter).toBe(0);
setTimeout(function () {
expect(scope.counter).toBe(1);
done();
}, 50);
});
it('allows async $apply with $applyAsync', function (done) {
scope.counter = 0;
scope.$watch(
function (scope) {
return scope.aValue;
},
function (newValue, oldValue, scope) {
scope.counter++;
}
);
scope.$digest();
expect(scope.counter).toBe(1);
scope.$applyAsync(function () {
scope.aValue = 'abc';
});
setTimeout(function () {
expect(scope.counter).toBe(2);
done();
}, 50);
});
it('never executes $applyAsync\'ed function in the same cycle', function (done) {
scope.aValue = [1, 2, 3];
scope.asyncApplied = false;
scope.$watch(
function (scope) {
},
function (newValue, oldValue, scope) {
scope.$applyAsync(function (scope) {
scope.asyncApplied = true;
});
}
);
scope.$digest();
expect(scope.asyncApplied).toBe(false);
setTimeout(function () {
expect(scope.asyncApplied).toBe(true);
done();
}, 50);
});
it('coalesces many call to $applyAsync', function (done) {
scope.counter = 0;
scope.$watch(
function (scope) {
scope.counter++;
return scope.aValue;
},
function (newValue, oldValue, scope) {
}
);
scope.$applyAsync(function (scope) {
scope.aValue = 'abc';
});
scope.$applyAsync(function (scope) {
scope.aValue = 'def';
});
setTimeout(function () {
expect(scope.counter).toBe(2);
done();
}, 50);
});
it('cancels and flushes $applyAsync if digested first', function (done) {
scope.counter = 0;
scope.$watch(
function (scope) {
scope.counter++;
return scope.aValue;
},
function (newValue, oldValue, scope) {
}
);
scope.$applyAsync(
function (scope) {
scope.aValue = 'abc';
});
scope.$applyAsync(
function (scope) {
scope.aValue = 'def';
});
scope.$digest();
expect(scope.counter).toBe(2);
expect(scope.aValue).toBe('def');
setTimeout(function () {
expect(scope.counter).toBe(2);
done();
}, 50);
});
it('runs a $$postDigest function after each digest', function () {
scope.counter = 0;
scope.$$postDigest(function () {
scope.counter++;
});
expect(scope.counter).toBe(0);
scope.$digest();
expect(scope.counter).toBe(1);
scope.$digest();
expect(scope.counter).toBe(1);
});
it('does not include $$postDigest in the digest', function () {
scope.aValue = 'original value';
scope.$$postDigest(function () {
scope.aValue = 'changed value';
});
scope.$watch(
function (scope) {
return scope.aValue;
},
function (newValue, oldValue, scope) {
scope.watchedValue = newValue;
}
);
scope.$digest();
expect(scope.watchedValue).toBe('original value');
scope.$digest();
expect(scope.watchedValue).toBe('changed value');
});
it('catches exceptions in watch functions and continues', function () {
scope.aValue = 'abc';
scope.counter = 0;
scope.$watch(
function (scope) {
throw 'Error';
},
function (newValue, oldValue, scope) {
}
);
scope.$watch(
function (scope) {
return scope.aValue;
},
function (newValue, oldValue, scope) {
scope.counter++;
}
);
scope.$digest();
expect(scope.counter).toBe(1);
});
it('catches exceptions in listener functions and continues', function () {
scope.aValue = 'abc';
scope.counter = 0;
scope.$watch(
function (scope) {
return scope.aValue;
},
function (newValue, oldValue, scope) {
throw 'Error';
}
);
scope.$watch(
function (scope) {
return scope.aValue;
},
function (newValue, oldValue, scope) {
scope.counter++;
}
);
scope.$digest();
expect(scope.counter).toBe(1);
});
it('catches exceptions in $evalAsync', function (done) {
scope.aValue = 'abc';
scope.counter = 0;
scope.$watch(
function (scope) {
return scope.aValue;
},
function (newValue, oldValue, scope) {
scope.counter++;
}
);
scope.$evalAsync(function (scope) {
throw 'Error';
});
setTimeout(function () {
expect(scope.counter).toBe(1);
done();
}, 50);
});
it('catches exceptions in $applyAsync', function (done) {
scope.$applyAsync(function (scope) {
throw 'Error';
});
scope.$applyAsync(function (scope) {
throw 'Error';
});
scope.$applyAsync(function (scope) {
scope.applied = true;
});
setTimeout(function () {
expect(scope.applied).toBe(true);
done();
}, 50);
});
it('catches exceptions in $$postDigest', function () {
var didRun = false;
scope.$$postDigest(function () {
throw 'Error';
});
scope.$$postDigest(function () {
didRun = true;
});
scope.$digest();
expect(didRun).toBe(true);
});
it('allows destroying a $watch with a removal function', function () {
scope.aValue = 'abc';
scope.counter = 0;
var destroyWatch = scope.$watch(
function (scope) {
return scope.aValue;
},
function (newValue, oldValue, scope) {
scope.counter++;
}
);
scope.$digest();
expect(scope.counter).toBe(1);
scope.aValue = 'def';
scope.$digest();
expect(scope.counter).toBe(2);
scope.aValue = 'ghi';
destroyWatch();
scope.$digest();
expect(scope.counter).toBe(2);
});
it('allows destroying a $watch during a digest', function () {
scope.aValue = 'abc';
var watchCalls = [];
scope.$watch(
function (scope) {
watchCalls.push('first');
return scope.aValue;
}
);
var destroyWatch = scope.$watch(
function (scope) {
watchCalls.push('second');
destroyWatch();
}
);
scope.$watch(
function (scope) {
watchCalls.push('third');
return scope.aValue;
}
);
scope.$digest();
expect(watchCalls).toEqual(['first', 'second', 'third', 'first', 'third']);
});
it('allows a $watch to destroy another during digest', function () {
scope.aValue = 'abc';
scope.counter = 0;
scope.$watch(
function (scope) {
return scope.aValue;
},
function (newValue, oldValue, scope) {
destroyWatch();
}
);
var destroyWatch = scope.$watch(
function (scope) {
},
function (newValue, oldValue, scope) {
}
);
scope.$watch(
function (scope) {
return scope.aValue;
},
function (newValue, oldValue, scope) {
scope.counter++;
}
);
scope.$digest();
expect(scope.counter).toBe(1);
});
it('allows destroying of several $watches during digest', function () {
scope.aValue = 'abc';
scope.counter = 0;
var destroyWatch1 = scope.$watch(
function (scope) {
destroyWatch1();
destroyWatch2();
}
);
var destroyWatch2 = scope.$watch(
function (scope) {
return scope.aValue;
},
function (newValue, oldValue, scope) {
scope.counter++;
}
);
scope.$digest();
expect(scope.counter).toBe(0);
});
it('accepts expressions for watch functions', function () {
var theValue;
scope.aValue = 42;
scope.$watch('aValue',
function (newValue, oldValue, scope) {
theValue = newValue;
});
scope.$digest();
expect(theValue).toBe(42);
});
it('accepts expressions for watchGroup functions', function () {
var theValue;
scope.aColl = [1, 2, 3];
scope.$watchCollection('aColl', function (newValue, oldValue, scope) {
theValue = newValue;
});
scope.$digest();
expect(theValue).toEqual([1, 2, 3]);
});
it('accepts expressions in $eval', function () {
expect(scope.$eval('42')).toBe(42);
});
it('accepts expressions in $apply', function () {
scope.aFunction = _.constant(42);
expect(scope.$apply('aFunction()')).toBe(42);
});
it('accepts expressions in $evalAsync', function (done) {
var called;
scope.aFunction = function () {
called = true;
};
scope.$evalAsync('aFunction()');
scope.$$postDigest(function () {
expect(called).toBe(true);
done();
});
});
it('removes constant watches after first invocation', function () {
scope.$watch('[1, 2, 3]', function () {
});
scope.$digest();
expect(scope.$$watchers.length).toBe(0);
});
it('accepts one-time watches', function () {
var theValue;
scope.aValue = 42;
scope.$watch(
'::aValue',
function (newValue, oldValue, scope) {
theValue = newValue;
}
);
scope.$digest();
expect(theValue).toBe(42);
});
it('removes one-time watches after first invocation', function () {
scope.aValue = 42;
scope.$watch('::aValue', function () {
});
scope.$digest();
expect(scope.$$watchers.length).toBe(0);
});
it('does not remove one-time watches until value has been defined', function () {
scope.$watch('::aValue', function () {
});
scope.$digest();
expect(scope.$$watchers.length).toBe(1);
scope.aValue = 42;
scope.$digest();
expect(scope.$$watchers.length).toBe(0);
});
it('does not remove one-time watches until value stays defined', function () {
scope.aValue = 42;
scope.$watch('::aValue', function () {
var unwatchDeleter = scope.$watch('aValue', function () {
delete scope.aValue;
});
scope.$digest();
expect(scope.$$watchers.length).toBe(2);
scope.aValue = 42;
unwatchDeleter();
scope.$digest();
expect(scope.$$watchers.length).toBe(0);
});
});
it('does not remove one-time watches before all array items defined', function () {
scope.$watch('::[1, 2, aValue]', function () {
}, true);
scope.$digest();
expect(scope.$$watchers.length).toBe(1);
scope.aValue = 3;
scope.$digest();
expect(scope.$$watchers.length).toBe(0);
});
it('does not remove one-time watches before all object vals defined', function () {
scope.$watch('::{a: 1, b: aValue}', function () {}, true);
scope.$digest();
expect(scope.$$watchers.length).toBe(1);
scope.aValue = 3;
scope.$digest();
expect(scope.$$watchers.length).toBe(0);
});
});
describe('watchGroup', function () {
var scope;
beforeEach(function () {
scope = new Scope();
});
it('takes watches as an array and calls listener with arrays', function () {
var gotNewValues, gotOldValues;
scope.aValue = 1;
scope.anotherValue = 2;
scope.$watchGroup([
function (scope) {
return scope.aValue;
},
function (scope) {
return scope.anotherValue;
}
],
function (newValues, oldValues, scope) {
gotNewValues = newValues;
gotOldValues = oldValues;
});
scope.$digest();
expect(gotNewValues).toEqual([1, 2]);
expect(gotOldValues).toEqual([1, 2]);
});
it('only call each listener once pwer digest', function () {
var counter = 0;
scope.aValue = 1;
scope.anotherValue = 2;
scope.$watchGroup([
function (scope) {
return scope.aValue;
},
function (scope) {
return scope.anotherValue;
}
],
function (newValues, oldValues, scope) {
counter++;
});
scope.$digest();
expect(counter).toEqual(1);
});
it('uses the same array of old and new values on first run', function () {
var gotNewValues, gotOldValues;
scope.aValue = 1;
scope.anotherValue = 2;
scope.$watchGroup([
function (scope) {
return scope.aValue;
},
function (scope) {
return scope.anotherValue;
}
],
function (newValues, oldValues, scope) {
gotNewValues = newValues;
gotOldValues = oldValues;
}
);
scope.$digest();
expect(gotNewValues).toBe(gotOldValues);
});
it('uses different arrays for old and new values on subsequent runs', function () {
var gotNewValues, gotOldValues;
scope.aValue = 1;
scope.anotherValue = 2;
scope.$watchGroup([
function (scope) {
return scope.aValue;
},
function (scope) {
return scope.anotherValue;
}
],
function (newValues, oldValues, scope) {
gotNewValues = newValues;
gotOldValues = oldValues;
}
);
scope.$digest();
scope.anotherValue = 3;
scope.$digest();
expect(gotNewValues).toEqual([1, 3]);
expect(gotOldValues).toEqual([1, 2]);
});
it('calls the listener once even if the watch array is empty', function () {
var gotNewValues, gotOldValues;
scope.$watchGroup([],
function (newValues, oldValues, scope) {
gotNewValues = newValues;
gotOldValues = oldValues;
});
scope.$digest();
expect(gotNewValues).toEqual([]);
expect(gotOldValues).toEqual([]);
});
it('can be deregistered', function () {
var counter = 0;
scope.aValue = 1;
scope.anotherValue = 2;
var destroyGroup = scope.$watchGroup([
function (scope) {
return scope.aValue;
},
function (scope) {
return scope.anotherValue;
}
],
function (newValues, oldValues, scope) {
counter++;
});
scope.$digest();
scope.anotherValue = 3;
destroyGroup();
scope.$digest();
expect(counter).toEqual(1);
});
it('does not call the zero-watch listener when deregistered first', function () {
var counter = 0;
var destroyGroup = scope.$watchGroup([], function (newValues, oldValues, scope) {
counter++;
});
destroyGroup();
scope.$digest();
expect(counter).toEqual(0);
});
});
describe('inheritance', function () {
it('inherits the parent\'s properties', function () {
var parent = new Scope();
parent.aValue = [1, 2, 3];
var child = parent.$new();
expect(child.aValue).toEqual([1, 2, 3]);
});
it('does not cause a parent to inherit it\'s properties', function () {
var parent = new Scope();
var child = parent.$new();
child.aValue = [1, 2, 3];
expect(parent.aValue).toBeUndefined();
});
it('inherits the parent\'s properties whenever they are defined', function () {
var parent = new Scope();
var child = parent.$new();
parent.aValue = [1, 2, 3];
expect(child.aValue).toEqual([1, 2, 3]);
});
it('can manipulate a parent scope\'s property', function () {
var parent = new Scope();
var child = parent.$new();
parent.aValue = [1, 2, 3];
child.aValue.push(4);
expect(child.aValue).toEqual([1, 2, 3, 4]);
expect(parent.aValue).toEqual([1, 2, 3, 4]);
});
it('can watch a property in the parent', function () {
var parent = new Scope();
var child = parent.$new();
parent.aValue = [1, 2, 3];
child.counter = 0;
child.$watch(
function (scope) {
return scope.aValue;
},
function (newValue, oldValue, scope) {
scope.counter++;
},
true
);
child.$digest();
expect(child.counter).toBe(1);
parent.aValue.push(4);
child.$digest();
expect(child.counter).toBe(2);
});
it('can be nested at any depth', function () {
var a = new Scope();
var aa = a.$new();
var aaa = aa.$new();
var aab = aa.$new();
var ab = a.$new();
var abb = ab.$new();
a.value = 1;
expect(aa.value).toBe(1);
expect(aaa.value).toBe(1);
expect(aab.value).toBe(1);
expect(ab.value).toBe(1);
expect(abb.value).toBe(1);
ab.anotherValue = 2;
expect(abb.anotherValue).toBe(2);
expect(aa.anotherValue).toBeUndefined();
expect(aaa.anotherValue).toBeUndefined();
});
it('shadows a parent\'s property with the same name', function () {
var parent = new Scope();
var child = parent.$new();
parent.name = 'Jack';
child.name = 'Jill';
expect(child.name).toBe('Jill');
expect(parent.name).toBe('Jack');
});
it('does not shadow members of parent scope\'s attributes', function () {
var parent = new Scope();
var child = parent.$new();
parent.user = {name: 'Jack'};
child.user.name = 'Jill';
expect(child.user.name).toBe('Jill');
expect(parent.user.name).toBe('Jill');
});
it('does not digest it\'s parent(s)', function () {
var parent = new Scope();
var child = parent.$new();
parent.aValue = 'abc';
parent.$watch(
function (scope) {
return scope.aValue;
},
function (newValue, oldValue, scope) {
scope.aValueWas = newValue;
}
);
child.$digest();
expect(child.aValueWas).toBeUndefined();
});
it('keeps a record of it\'s children', function () {
var parent = new Scope();
var child1 = parent.$new();
var child2 = parent.$new();
var grandChild = child2.$new();
expect(parent.$$children.length).toBe(2);
expect(parent.$$children[0]).toBe(child1);
expect(parent.$$children[1]).toBe(child2);
expect(child1.$$children.length).toBe(0);
expect(child2.$$children.length).toBe(1);
expect(child2.$$children[0]).toBe(grandChild);
});
it('digest executes children', function () {
var parent = new Scope();
var child = parent.$new();
parent.aValue = 'abc';
child.$watch(
function (scope) {
return scope.aValue;
},
function (newValue, oldValue, scope) {
scope.aValueWas = newValue;
}
);
parent.$digest();
expect(child.aValueWas).toBe('abc');
});
it('digests from root on $apply', function () {
var parent = new Scope();
var child = parent.$new();
var child2 = child.$new();
parent.aValue = 'abc';
parent.counter = 0;
parent.$watch(
function (scope) {
return scope.aValue;
},
function (newValue, oldValue, scope) {
scope.counter++;
}
);
child2.$apply(function (scope) {
});
expect(parent.counter).toBe(1);
});
it('schedules a digest from the root on $evalAsync', function (done) {
var parent = new Scope();
var child = parent.$new();
var child2 = child.$new();
parent.aValue = 'abc';
parent.counter = 0;
parent.$watch(
function (scope) {
return scope.aValue;
},
function (newValue, oldValue, scope) {
scope.counter++;
}
);
child2.$evalAsync(function (scope) {
});
setTimeout(function (scope) {
expect(parent.counter).toBe(1);
done();
}, 50);
});
it('does not have access to parent attributes when isolated', function () {
var parent = new Scope();
var child = parent.$new(true);
parent.aValue = 'abc';
expect(child.aValue).toBeUndefined();
});
it('cannot watch parent attributes when isolated', function () {
var parent = new Scope();
var child = parent.$new(true);
parent.aValue = 'abc';
child.$watch(
function (scope) {
return scope.aValue;
},
function (newValue, oldValue, scope) {
scope.aValueWas = newValue;
}
);
child.$digest();
expect(child.aValueWas).toBeUndefined();
});
it('digests it\'s isolated children', function () {
var parent = new Scope();
var child = parent.$new(true);
child.aValue = 'abc';
child.$watch(
function (scope) {
return scope.aValue;
},
function (newValue, oldValue, scope) {
scope.aValueWas = newValue;
}
);
parent.$digest();
expect(child.aValueWas).toBe('abc');
});
it('digests from root on $apply when isolated', function () {
var parent = new Scope();
var child = parent.$new(true);
var child2 = child.$new();
parent.aValue = 'abc';
parent.counter = 0;
parent.$watch(
function (scope) {
return scope.aValue;
},
function (newValue, oldValue, scope) {
scope.counter++;
}
);
child2.$apply(function (scope) {
});
expect(parent.counter).toBe(1);
});
it('schedules a digest from root on $evalAsync when isolated', function (done) {
var parent = new Scope();
var child = parent.$new(true);
var child2 = child.$new();
parent.aValue = 'abc';
parent.counter = 0;
parent.$watch(
function (scope) {
return scope.aValue;
},
function (newValue, oldValue, scope) {
scope.counter++;
}
);
child2.$evalAsync(function (scope) {
});
setTimeout(function (scope) {
expect(parent.counter).toBe(1);
done();
}, 50);
});
it('executes $evalAsync functions on isolated scopes', function (done) {
var parent = new Scope();
var child = parent.$new(true);
child.$evalAsync(function (scope) {
scope.didEvalAsync = true;
});
setTimeout(function () {
expect(child.didEvalAsync).toBe(true);
done();
}, 50);
});
it('executes $$postDigest functions on isolated scopes', function () {
var parent = new Scope();
var child = parent.$new(true);
child.$$postDigest(function () {
child.didPostDigest = true;
});
parent.$digest();
expect(child.didPostDigest).toBe(true);
});
it('can take some other scope as the parent', function () {
var prototypeParent = new Scope();
var hierarchyParent = new Scope();
var child = prototypeParent.$new(false, hierarchyParent);
prototypeParent.a = 42;
expect(child.a).toBe(42);
child.counter = 0;
child.$watch(function (scope) {
scope.counter++;
});
prototypeParent.$digest();
expect(child.counter).toBe(0);
hierarchyParent.$digest();
expect(child.counter).toBe(2);
});
it('is no longer digested when $destroy has been called', function () {
var parent = new Scope();
var child = parent.$new();
child.aValue = [1, 2, 3];
child.counter = 0;
child.$watch(
function (scope) {
return scope.aValue;
},
function (newValue, oldValue, scope) {
scope.counter++;
},
true
);
parent.$digest();
expect(child.counter).toBe(1);
child.aValue.push(4);
parent.$digest();
expect(child.counter).toBe(2);
child.$destroy();
child.aValue.push(5);
parent.$digest();
expect(child.counter).toBe(2);
});
});
describe('watchCollection', function () {
var scope;
beforeEach(function () {
scope = new Scope();
});
it('works like a normal watch for non-collections', function () {
var valueProvided;
scope.aValue = 42;
scope.counter = 0;
scope.$watchCollection(
function (scope) {
return scope.aValue;
},
function (newValue, oldValue, scope) {
valueProvided = newValue;
scope.counter++;
}
);
scope.$digest();
expect(scope.counter).toBe(1);
expect(valueProvided).toBe(scope.aValue);
scope.aValue = 43;
scope.$digest();
expect(scope.counter).toBe(2);
scope.$digest();
expect(scope.counter).toBe(2);
});
it('works like a normal watch for NaNs', function () {
scope.aValue = 0 / 0;
scope.counter = 0;
scope.$watchCollection(
function (scope) {
return scope.aValue;
},
function (newValue, oldValue, scope) {
scope.counter++;
}
);
scope.$digest();
expect(scope.counter).toBe(1);
scope.$digest();
expect(scope.counter).toBe(1);
});
it('notices when the value becomes an array', function () {
scope.counter = 0;
scope.$watchCollection(
function (scope) {
return scope.arr;
},
function (newValue, oldValue, scope) {
scope.counter++;
}
);
scope.$digest();
expect(scope.counter).toBe(1);
scope.arr = [1, 2, 3];
scope.$digest();
expect(scope.counter).toBe(2);
scope.$digest();
expect(scope.counter).toBe(2);
});
it('notices an item added to an array', function () {
scope.arr = [1, 2, 3];
scope.counter = 0;
scope.$watchCollection(
function (scope) {
return scope.arr;
},
function (newValue, oldValue, scope) {
scope.counter++;
}
);
scope.$digest();
expect(scope.counter).toBe(1);
scope.arr.push(4);
scope.$digest();
expect(scope.counter).toBe(2);
scope.$digest();
expect(scope.counter).toBe(2);
});
it('notices an item removed from an array', function () {
scope.arr = [1, 2, 3];
scope.counter = 0;
scope.$watchCollection(
function (scope) {
return scope.arr;
},
function (newValue, oldValue, scope) {
scope.counter++;
}
);
scope.$digest();
expect(scope.counter).toBe(1);
scope.arr.shift();
scope.$digest();
expect(scope.counter).toBe(2);
scope.$digest();
expect(scope.counter).toBe(2);
});
it('notices an item replaced in an array', function () {
scope.arr = [1, 2, 3];
scope.counter = 0;
scope.$watchCollection(
function (scope) {
return scope.arr;
},
function (newValue, oldValue, scope) {
scope.counter++;
}
);
scope.$digest();
expect(scope.counter).toBe(1);
scope.arr[1] = 42;
scope.$digest();
expect(scope.counter).toBe(2);
scope.$digest();
expect(scope.counter).toBe(2);
});
it('notices items reordered in an array', function () {
scope.arr = [2, 1, 3];
scope.counter = 0;
scope.$watchCollection(
function (scope) {
return scope.arr;
},
function (newValue, oldValue, scope) {
scope.counter++;
}
);
scope.$digest();
expect(scope.counter).toBe(1);
scope.arr.sort();
scope.$digest();
expect(scope.counter).toBe(2);
scope.$digest();
expect(scope.counter).toBe(2);
});
it('does not fail on NaNs in arrays', function () {
scope.arr = [2, NaN, 3];
scope.counter = 0;
scope.$watchCollection(
function (scope) {
return scope.arr;
},
function (newValue, oldValue, scope) {
scope.counter++;
}
);
scope.$digest();
expect(scope.counter).toBe(1);
});
it('notices an item repalaced in an arguments object', function () {
(function () {
scope.arrayLike = arguments;
})(1, 2, 3);
scope.counter = 0;
scope.$watchCollection(
function (scope) {
return scope.arrayLike;
},
function (newValue, oldValue, scope) {
scope.counter++;
}
);
scope.$digest();
expect(scope.counter).toBe(1);
scope.arrayLike[1] = 42;
scope.$digest();
expect(scope.counter).toBe(2);
scope.$digest();
expect(scope.counter).toBe(2);
});
it('notices an item replaced in a NodeList object', function () {
document.documentElement.appendChild(document.createElement('div'));
scope.arrayLike = document.getElementsByTagName('div');
scope.counter = 0;
scope.$watchCollection(
function (scope) {
return scope.arrayLike;
},
function (newValue, oldValue, scope) {
scope.counter++;
}
);
scope.$digest();
expect(scope.counter).toBe(1);
document.documentElement.appendChild(document.createElement('div'));
scope.$digest();
expect(scope.counter).toBe(2);
scope.$digest();
expect(scope.counter).toBe(2);
});
it('notices when the value becomes an object', function () {
scope.counter = 0;
scope.$watchCollection(
function (scope) {
return scope.obj;
},
function (newValue, oldValue, scope) {
scope.counter++;
}
);
scope.$digest();
expect(scope.counter).toBe(1);
scope.obj = {a: 1};
scope.$digest();
expect(scope.counter).toBe(2);
scope.$digest();
expect(scope.counter).toBe(2);
});
it('notices when an attribute is added to an object', function () {
scope.counter = 0;
scope.obj = {a: 1};
scope.$watchCollection(
function (scope) {
return scope.obj;
},
function (newValue, oldValue, scope) {
scope.counter++;
}
);
scope.$digest();
expect(scope.counter).toBe(1);
scope.obj.b = 2;
scope.$digest();
expect(scope.counter).toBe(2);
scope.$digest();
expect(scope.counter).toBe(2);
});
it('notices when an attribute is changed in an object', function () {
scope.counter = 0;
scope.obj = {a: 1};
scope.$watchCollection(
function (scope) {
return scope.obj;
},
function (newValue, oldValue, scope) {
scope.counter++;
}
);
scope.$digest();
expect(scope.counter).toBe(1);
scope.obj.a = 2;
scope.$digest();
expect(scope.counter).toBe(2);
scope.$digest();
expect(scope.counter).toBe(2);
});
it('does not fail on NaN attributes in objects', function () {
scope.counter = 0;
scope.obj = {a: NaN};
scope.$watchCollection(
function (scope) {
return scope.obj;
},
function (newValue, oldValue, scope) {
scope.counter++;
}
);
scope.$digest();
expect(scope.counter).toBe(1);
});
it('notices when an attribute is removed from an object', function () {
scope.counter = 0;
scope.obj = {a: 1};
scope.$watchCollection(
function (scope) {
return scope.obj;
},
function (newValue, oldValue, scope) {
scope.counter++;
}
);
scope.$digest();
expect(scope.counter).toBe(1);
delete scope.obj.a;
scope.$digest();
expect(scope.counter).toBe(2);
scope.$digest();
expect(scope.counter).toBe(2);
});
it('does not consider any object with a length property an array', function () {
scope.obj = {length: 42, otherKey: 'abc'};
scope.counter = 0;
scope.$watchCollection(
function (scope) {
return scope.obj;
},
function (newValue, oldValue, scope) {
scope.counter++;
}
);
scope.$digest();
scope.obj.newKey = 'def';
scope.$digest();
expect(scope.counter).toBe(2);
});
it('gives the old non-collection value to listeners', function () {
scope.aValue = 42;
var oldValueGiven;
scope.$watchCollection(
function (scope) {
return scope.aValue;
},
function (newValue, oldValue, scope) {
oldValueGiven = oldValue;
}
);
scope.$digest();
scope.aValue = 43;
scope.$digest();
expect(oldValueGiven).toBe(42);
});
it('gives the old array value to listeners', function () {
scope.aValue = [1, 2, 3];
var oldValueGiven;
scope.$watchCollection(
function (scope) {
return scope.aValue;
},
function (newValue, oldValue, scope) {
oldValueGiven = oldValue;
}
);
scope.$digest();
scope.aValue.push(4);
scope.$digest();
expect(oldValueGiven).toEqual([1, 2, 3]);
});
it('gives old object value to listeners', function () {
scope.aValue = {a: 1, b: 2};
var oldValueGiven;
scope.$watchCollection(
function (scope) {
return scope.aValue;
},
function (newValue, oldValue, scope) {
oldValueGiven = oldValue;
}
);
scope.$digest();
scope.aValue.c = 3;
scope.$digest();
expect(oldValueGiven).toEqual({a: 1, b: 2});
});
it('uses the new value as the oldValue on first digest', function () {
scope.aValue = {a: 1, b: 2};
var oldValueGiven;
scope.$watchCollection(
function (scope) {
return scope.aValue;
},
function (newValue, oldValue, scope) {
oldValueGiven = oldValue;
}
);
scope.$digest();
expect(oldValueGiven).toEqual({a: 1, b: 2});
});
});
describe('events', function () {
var parent;
var scope;
var child;
var isolatedChild;
beforeEach(function () {
parent = new Scope();
scope = parent.$new();
child = scope.$new();
isolatedChild = scope.$new(true);
});
it('allows registering listeners', function () {
var listener1 = function () {
};
var listener2 = function () {
};
var listener3 = function () {
};
scope.$on('someEvent', listener1);
scope.$on('someEvent', listener2);
scope.$on('someOtherEvent', listener3);
expect(scope.$$listeners).toEqual({
someEvent: [listener1, listener2],
someOtherEvent: [listener3]
});
});
it('registers different listeners for ever scope', function () {
var listener1 = function () {
};
var listener2 = function () {
};
var listener3 = function () {
};
scope.$on('someEvent', listener1);
child.$on('someEvent', listener2);
isolatedChild.$on('someEvent', listener3);
expect(scope.$$listeners).toEqual({someEvent: [listener1]});
expect(child.$$listeners).toEqual({someEvent: [listener2]});
expect(isolatedChild.$$listeners).toEqual({someEvent: [listener3]});
});
_.forEach(['$emit', '$broadcast'], function (method) {
it('calls the listeners of the matching event on ' + method, function () {
var listener1 = jasmine.createSpy();
var listener2 = jasmine.createSpy();
scope.$on('someEvent', listener1);
scope.$on('someOtherEvent', listener2);
scope[method]('someEvent');
expect(listener1).toHaveBeenCalled();
expect(listener2).not.toHaveBeenCalled();
});
it('passes an event object with a name to listeners on ' + method, function () {
var listener = jasmine.createSpy();
scope.$on('someEvent', listener);
scope[method]('someEvent');
expect(listener).toHaveBeenCalled();
expect(listener.calls.mostRecent().args[0].name).toEqual('someEvent');
});
it('passes the same event object to each listener on ' + method, function () {
var listener1 = jasmine.createSpy();
var listener2 = jasmine.createSpy();
scope.$on('someEvent', listener1);
scope.$on('someEvent', listener2);
scope[method]('someEvent');
var event1 = listener1.calls.mostRecent().args[0];
var event2 = listener2.calls.mostRecent().args[0];
expect(event1).toBe(event2);
});
it('passes additional arguments to listeners on ' + method, function () {
var listener = jasmine.createSpy();
scope.$on('someEvent', listener);
scope[method]('someEvent', 'and', ['additional', 'arguments'], '...');
expect(listener.calls.mostRecent().args[1]).toEqual('and');
expect(listener.calls.mostRecent().args[2]).toEqual(['additional', 'arguments']);
expect(listener.calls.mostRecent().args[3]).toEqual('...');
});
it('returns the event object on ' + method, function () {
var returnedEvent = scope[method]('someEvent');
expect(returnedEvent).toBeDefined();
expect(returnedEvent.name).toEqual('someEvent');
});
it(method + ' can be deregistered', function () {
var listener = jasmine.createSpy();
var deregister = scope.$on('someEvent', listener);
deregister();
scope[method]('someEvent');
expect(listener).not.toHaveBeenCalled();
});
it('does not skip the next listener when removed on ' + method, function () {
var deregister;
var listener = function () {
deregister();
};
var nextListener = jasmine.createSpy();
deregister = scope.$on('someEvent', listener);
scope.$on('someEvent', nextListener);
scope[method]('someEvent');
expect(nextListener).toHaveBeenCalled();
});
it('sets defaultPrevented when preventDefault is called on ' + method, function () {
var listener = function (event) {
event.preventDefault();
};
scope.$on('someEvent', listener);
var event = scope[method]('someEvent');
expect(event.defaultPrevented).toBe(true);
});
it(method + ' does not stop propagation on exceptions', function () {
var listener1 = function (event) {
throw 'listener1 exception';
};
var listener2 = jasmine.createSpy();
scope.$on('someEvent', listener1);
scope.$on('someEvent', listener2);
scope[method]('someEvent');
expect(listener2).toHaveBeenCalled();
});
});
it('propagates up the scope hierarchy on $emit', function () {
var parentListener = jasmine.createSpy();
var scopeListener = jasmine.createSpy();
parent.$on('someEvent', parentListener);
scope.$on('someEvent', scopeListener);
scope.$emit('someEvent');
expect(scopeListener).toHaveBeenCalled();
expect(parentListener).toHaveBeenCalled();
});
it('propagates the same event up on $emit', function () {
var parentListener = jasmine.createSpy();
var scopeListener = jasmine.createSpy();
parent.$on('someEvent', parentListener);
parent.$on('someEvent', scopeListener);
scope.$emit('someEvent');
var scopeEvent = scopeListener.calls.mostRecent().args[0];
var parentEvent = parentListener.calls.mostRecent().args[0];
expect(scopeEvent).toBe(parentEvent);
});
it('propagates down the scope hierarchy on $broadcast', function () {
var scopeListener = jasmine.createSpy();
var childListener = jasmine.createSpy();
var isolatedChildListener = jasmine.createSpy();
scope.$on('someEvent', scopeListener);
child.$on('someEvent', childListener);
isolatedChild.$on('someEvent', isolatedChildListener);
scope.$broadcast('someEvent');
expect(scopeListener).toHaveBeenCalled();
expect(childListener).toHaveBeenCalled();
expect(isolatedChildListener).toHaveBeenCalled();
});
it('propagates the same event down on $broadcast', function () {
var scopeListener = jasmine.createSpy();
var childListener = jasmine.createSpy();
scope.$on('someEvent', scopeListener);
child.$on('someEvent', childListener);
scope.$broadcast('someEvent');
var scopeEvent = scopeListener.calls.mostRecent().args[0];
var childEvent = childListener.calls.mostRecent().args[0];
expect(scopeEvent).toBe(childEvent);
});
it('attaches target scope on $emit', function () {
var scopeListener = jasmine.createSpy();
var parentListener = jasmine.createSpy();
scope.$on('someEvent', scopeListener);
parent.$on('someEvent', parentListener);
scope.$emit('someEvent');
expect(scopeListener.calls.mostRecent().args[0].targetScope).toBe(scope);
expect(parentListener.calls.mostRecent().args[0].targetScope).toBe(scope);
});
it('attaches target Scope on $broadcast', function () {
var scopeListener = jasmine.createSpy();
var childListener = jasmine.createSpy();
scope.$on('someEvent', scopeListener);
child.$on('someEvent', childListener);
scope.$broadcast('someEvent');
expect(scopeListener.calls.mostRecent().args[0].targetScope).toBe(scope);
expect(childListener.calls.mostRecent().args[0].targetScope).toBe(scope);
});
it('attaches current scope on $emit', function () {
var currentScopeOnScope, currentScopeOnParent;
var scopeListener = function (event) {
currentScopeOnScope = event.currentScope;
};
var parentListener = function (event) {
currentScopeOnParent = event.currentScope;
};
scope.$on('someEvent', scopeListener);
parent.$on('someEvent', parentListener);
scope.$emit('someEvent');
expect(currentScopeOnScope).toBe(scope);
expect(currentScopeOnParent).toBe(parent);
});
it('attaches current scope on $broadcast', function () {
var currentScopeOnScope, currentScopeOnChild;
var scopeListener = function (event) {
currentScopeOnScope = event.currentScope;
};
var childListener = function (event) {
currentScopeOnChild = event.currentScope;
};
scope.$on('someEvent', scopeListener);
child.$on('someEvent', childListener);
scope.$broadcast('someEvent');
expect(currentScopeOnScope).toBe(scope);
expect(currentScopeOnChild).toBe(child);
});
it('sets currentScope to null after propagation on $emit', function () {
var event;
var scopeListener = function (evt) {
event = evt;
};
scope.$on('someEvent', scopeListener);
scope.$emit('someEvent');
expect(event.currentScope).toBe(null);
});
it('sets currentScope to null after propagation on $broadcast', function () {
var event;
var scopeListener = function (evt) {
event = evt;
};
scope.$on('someEvent', scopeListener);
scope.$broadcast('someEvent');
expect(event.currentScope).toBe(null);
});
it('does not propagate to parents when stopped', function () {
var scopeListener = function (event) {
event.stopPropagation();
};
var parentListener = jasmine.createSpy();
scope.$on('someEvent', scopeListener);
parent.$on('someEvent', parentListener);
scope.$emit('someEvent');
expect(parentListener).not.toHaveBeenCalled();
});
it('is received by listeners on current scope after being stopped', function () {
var listener1 = function (event) {
event.stopPropagation();
};
var listener2 = jasmine.createSpy();
scope.$on('someEvent', listener1);
scope.$on('someEvent', listener2);
scope.$emit('someEvent');
expect(listener2).toHaveBeenCalled();
});
it('fires $destroy when destroyed', function () {
var listener = jasmine.createSpy();
scope.$on('$destroy', listener);
scope.$destroy();
expect(listener).toHaveBeenCalled();
});
it('fires destroy when children destroyed', function () {
var listener = jasmine.createSpy();
child.$on('$destroy', listener);
scope.$destroy();
expect(listener).toHaveBeenCalled();
});
it('no longers calls listener after destruction', function () {
var listener = jasmine.createSpy();
scope.$on('myEvent', listener);
scope.$destroy();
scope.$emit('myEvent');
expect(listener).not.toHaveBeenCalled();
});
});
});
|
// Karma configuration
// Generated on Thu Aug 21 2014 10:24:39 GMT+0200 (CEST)
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['mocha', 'chai-jquery', 'jquery-1.8.3', 'sinon-chai'],
plugins: [
'karma-mocha',
'karma-chai',
'karma-sinon-chai',
'karma-chrome-launcher',
'karma-phantomjs-launcher',
'karma-jquery',
'karma-chai-jquery'
],
// list of files / patterns to load in the browser
files: [
'bower/angular/angular.js',
'bower/angular-mocks/angular-mocks.js',
'dist/clinicatdd.js',
'test/unit/**/*.js'
],
// list of files to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['PhantomJS'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false
});
};
|
'use strict';
/* jshint ignore:start */
/**
* This code was generated by
* \ / _ _ _| _ _
* | (_)\/(_)(_|\/| |(/_ v1.0.0
* / /
*/
/* jshint ignore:end */
var _ = require('lodash'); /* jshint ignore:line */
var ServiceList = require('./authy/service').ServiceList;
var Version = require('../../base/Version'); /* jshint ignore:line */
/* jshint ignore:start */
/**
* Initialize the Authy version of Preview
*
* @property {Twilio.Preview.Authy.ServiceList} services - services resource
*
* @param {Twilio.Preview} domain - The twilio domain
*/
/* jshint ignore:end */
function Authy(domain) {
Version.prototype.constructor.call(this, domain, 'Authy');
// Resources
this._services = undefined;
}
_.extend(Authy.prototype, Version.prototype);
Authy.prototype.constructor = Authy;
Object.defineProperty(Authy.prototype,
'services', {
get: function() {
this._services = this._services || new ServiceList(this);
return this._services;
}
});
module.exports = Authy;
|
function Module(factory) {
this.waiting = true;
this.factory = factory;
}
function _define(path, factory) {
cache[path] = new Module(factory);
}
function require(path) {
var exports, factory, module, modpaths, modrequire;
module = cache[path];
if (module instanceof Module) {
if (!module.waiting) {
throw new Error('Circular dependency in module "' + path + '"');
}
factory = module.factory;
module.waiting = false;
module = {};
module.exports = exports = {};
if (modpaths = mappings[path]) {
modrequire = function(name) {
return require(modpaths[name] || name);
};
}
else {
modrequire = require;
}
factory(modrequire, module, exports);
return cache[path] = module.exports;
}
return module;
}
|
angular.module('uiForDocker')
.controller('DockerCtrl', DockerCtrl);
DockerCtrl.$inject = ['$scope', '$http', 'dockerApi'];
function DockerCtrl($scope, $http, dockerApi) {
dockerApi.getInfo().then(function(res) {
console.log(res);
$scope.cpus = res.data.info.NCPU;//
$scope.architecture = res.data.info.Architecture;//
$scope.os = res.data.info.OSType;//
$scope.serverVersion = res.data.info.ServerVersion;//
$scope.driver = res.data.info.Driver;
$scope.operatingSystem = res.data.info.OperatingSystem;
$scope.dockerRootDir = res.data.info.DockerRootDir;
$scope.name = res.data.info.Name;
$scope.kernel = res.data.info.KernelVersion;
}, function(error) {})
}
|
"use-strict";
const greet = (name) => {
return "Welcome to our platform " + name;
};
module.exports = {
greet
}; |
function quoteMe(){
var quotes = new Array ();
quotes[0] = "That won't fit the grid.";
quotes[1] = "That's not in the wireframes.";
quotes[2] = "That's a developer thing.";
quotes[3] = "I didn't mock it up that way.";
quotes[4] = "The developer must have changed it.";
quotes[5] = "Did you try hitting refresh?";
quotes[6] = "No one uses IE anyway.";
quotes[7] = "That's not how I designed it.";
quotes[8] = "That's way too skeuomorphic.";
quotes[9] = "That's way too flat.";
quotes[10] = "Just put a long shadow on it.";
quotes[11] = "It wasn't designed for that kind of content.";
quotes[12] = "Josef Müller-Brockmann.";
quotes[13] = "That must be a server thing.";
quotes[14] = "It only looks bad if it's not on Retina.";
quotes[15] = "Are you looking at it in IE or something?";
quotes[16] = "That's not a recognised design pattern.";
quotes[17] = "It wasn't designed to work with this content.";
quotes[18] = "The users will never notice that.";
quotes[19] = "The users might not notice it, but they'll feel it.";
quotes[20] = "These brand guidelines are shit.";
quotes[21] = "You wouldn't get it, it's a design thing."
quotes[22] = "Jony wouldn't do it like this."
quotes[23] = "That's a dark pattern."
quotes[24] = "I don't think that's very user friendly."
quotes[25] = "That's not what the research says."
quotes[26] = "I didn't get a change request for that."
var theQuote = quotes[Math.floor(Math.random() * quotes.length)];
document.getElementById("drop_the_knowledge").innerHTML = theQuote;
}
$(document).ready(quoteMe); |
angular.module('ngStepwise',[]).directive('ngStepwise', ['$sce', '$document','$timeout', function($sce, $document, $timeout) {
console.log("[module.directive.ngStepwise]");
return {
link: function(scope, element, attrs) {
/** Wire in methods to the host scope to make available to the directive template **/
scope.getItemClass = function(thisStep, index) {
var classes=[];
if(angular.isObject(thisStep)) {
if(thisStep.complete)
classes.push('complete');
else if(thisStep.active) {
scope.activeStepIndex = index;
classes.push('active-step');
} else if(index > scope.activeStepIndex) {
classes.push('after-active-step');
};
}
return classes.join(' ');
};
scope.getItemCss=function(step, index) {
if(angular.isObject(step)) {
return {
backgroundColor: step.hasOwnProperty('incompleteBgColor')?step.incompleteBgColor:'#ccc',
borderColor: step.hasOwnProperty('incompleteBorderColor')?step.incompleteBorderColor:'#e8e8e8'
};
}
};
element.on('mouseover', function() {
if(attrs.url) {
// do something if there is a url for the task
}
});
// apply tooltips
$timeout(function() {
$("[title]").tooltip({
placement: 'bottom'
});
}, 100);
},
restrict: 'AE',
scope: {
globalOptions: '=ngDefaultOptions', /** Still working on these **/
steps: '=ngSteps' /** Channel in the steps attribute of the element to map to the scope array of steps **/
},
template: "\
<div class='stepwise-frame'><ul class='stepwise'>\
<li ng-repeat='step in steps' ng-attr-class='{{getItemClass(step, $index)}}'>\
<label>{{step.title}}</label>\
<a ng-href='{{step.url}}' target='{{step.newWindow?'_blank':'_self'}}' ng-attr-title='{{step.tooltip}}' ng-style='getItemCss(step, $index)'> </a>\
<hr class='divider' />\
</li>\
</ul></div>\
",
};
}]); |
'use strict';
var wikiInfobox = require('../index');
var nock = require('nock');
var assert = require('assert');
var language = 'en';
var page = 'Bemowo';
var initMock = function(body) {
nock('http://'+ language + '.wikipedia.org')
.get(
'/w/api.php?' +
'format=json&' +
'action=query&' +
'prop=revisions&' +
'rvprop=content&' +
'titles='+page
).reply(200, body);
};
// Simple infobox with one string field
initMock(require('./mocks/1.js'));
wikiInfobox(page, language, function(err, data) {
assert.deepEqual(data, {name: 'Bemowo'});
});
// Simple infobox with one link field
initMock(require('./mocks/2.js'));
wikiInfobox(page, language, function(err, data) {
assert.deepEqual(
data,
{ 'settlement_type':
{ 'type' : 'link',
'text' : 'Warsaw',
'url' : 'http://en.wikipedia.org/wiki/Warsaw'
}
}
);
});
// Simple infobox with one link field with alias
initMock(require('./mocks/3.js'));
wikiInfobox(page, language, function(err, data) {
assert.deepEqual(
data,
{ 'subdivision_type1' :
{ 'type' : 'link',
'text' : 'Voivodeship',
'url' : 'http://en.wikipedia.org/wiki/Voivodeships of Poland'
}
}
);
});
// Infobox with multiple links in one field
initMock(require('./mocks/4.js'));
wikiInfobox(page, language, function(err, data) {
assert.deepEqual(
data,
{ 'country':
[
{ 'type' : 'link',
'text' : 'Warsaw',
'url' : 'http://en.wikipedia.org/wiki/Warsaw'
},
{ 'type' : 'link',
'text':'Poland',
'url' : 'http://en.wikipedia.org/wiki/Poland'
}
]
}
);
});
// Infobox with multiple links (simple & with aliases) in one field
initMock(require('./mocks/5.js'));
wikiInfobox(page, language, function(err, data) {
assert.deepEqual(
data,
{ 'languages':
[
{ 'type' : 'link',
'text' : 'Official language',
'url' : 'http://en.wikipedia.org/wiki/Official language'
},
{ 'type' : 'link',
'text':'Polish',
'url' : 'http://en.wikipedia.org/wiki/Polish language'
}
]
}
);
});
// Infobox with one image field
initMock(require('./mocks/6.js'));
wikiInfobox(page, language, function(err, data) {
assert.deepEqual(
data,
{ 'map':
{ 'type' : 'image',
'text' : 'frameless',
'url' : 'http://en.wikipedia.org/wiki/File:Metro w Warszawie linia.svg'
}
}
);
});
// Infobox with one text field, multiple links in one field, link with
// alias & image
initMock(require('./mocks/7.js'));
wikiInfobox(page, language, function(err, data) {
assert.deepEqual(
data,
{ owner: 'City of Warsaw',
locale: [
{
type: 'link',
text: 'Warsaw',
url: 'http://en.wikipedia.org/wiki/Warsaw'
},
{
type: 'link',
text: 'Poland',
url: 'http://en.wikipedia.org/wiki/Poland'
}
],
transit_type: {
type: 'link',
text: 'Rapid',
url: 'http://en.wikipedia.org/wiki/Rapid transit'
},
map: {
type: 'image',
text: 'frameless',
url: 'http://en.wikipedia.org/wiki/File:Metro w Warszawie linia.svg'
},
logo: {
type: 'image',
text: 'Image:Warsaw Metro logo.svg',
url: 'http://en.wikipedia.org/wiki/Image:Warsaw Metro logo.svg'
}
}
);
});
|
var me = {"name": "wang", "mobile": "ding"};
var names = ["name", "mobile"];
console.log(me["name"]);
|
/*!
* jQuery JavaScript Library v1.8.3
* http://jquery.com/
*
* Includes Sizzle.js
* http://sizzlejs.com/
*
* Copyright 2012 jQuery Foundation and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: Tue Nov 13 2012 08:20:33 GMT-0500 (Eastern Standard Time)
*/
(function( window, undefined ) {
var
// A central reference to the root jQuery(document)
rootjQuery,
// The deferred used on DOM ready
readyList,
// Use the correct document accordingly with window argument (sandbox)
document = window.document,
location = window.location,
navigator = window.navigator,
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$,
// Save a reference to some core methods
core_push = Array.prototype.push,
core_slice = Array.prototype.slice,
core_indexOf = Array.prototype.indexOf,
core_toString = Object.prototype.toString,
core_hasOwn = Object.prototype.hasOwnProperty,
core_trim = String.prototype.trim,
// Define a local copy of jQuery
jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context, rootjQuery );
},
// Used for matching numbers
core_pnum = /[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source,
// Used for detecting and trimming whitespace
core_rnotwhite = /\S/,
core_rspace = /\s+/,
// Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE)
rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,
// A simple way to check for HTML strings
// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
rquickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,
// Match a standalone tag
rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/,
// JSON RegExp
rvalidchars = /^[\],:{}\s]*$/,
rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g,
rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,
rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,
// Matches dashed string for camelizing
rmsPrefix = /^-ms-/,
rdashAlpha = /-([\da-z])/gi,
// Used by jQuery.camelCase as callback to replace()
fcamelCase = function( all, letter ) {
return ( letter + "" ).toUpperCase();
},
// The ready event handler and self cleanup method
DOMContentLoaded = function() {
if ( document.addEventListener ) {
document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
jQuery.ready();
} else if ( document.readyState === "complete" ) {
// we're here because readyState === "complete" in oldIE
// which is good enough for us to call the dom ready!
document.detachEvent( "onreadystatechange", DOMContentLoaded );
jQuery.ready();
}
},
// [[Class]] -> type pairs
class2type = {};
jQuery.fn = jQuery.prototype = {
constructor: jQuery,
init: function( selector, context, rootjQuery ) {
var match, elem, ret, doc;
// Handle $(""), $(null), $(undefined), $(false)
if ( !selector ) {
return this;
}
// Handle $(DOMElement)
if ( selector.nodeType ) {
this.context = this[0] = selector;
this.length = 1;
return this;
}
// Handle HTML strings
if ( typeof selector === "string" ) {
if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {
// Assume that strings that start and end with <> are HTML and skip the regex check
match = [ null, selector, null ];
} else {
match = rquickExpr.exec( selector );
}
// Match html or make sure no context is specified for #id
if ( match && (match[1] || !context) ) {
// HANDLE: $(html) -> $(array)
if ( match[1] ) {
context = context instanceof jQuery ? context[0] : context;
doc = ( context && context.nodeType ? context.ownerDocument || context : document );
// scripts is true for back-compat
selector = jQuery.parseHTML( match[1], doc, true );
if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) {
this.attr.call( selector, context, true );
}
return jQuery.merge( this, selector );
// HANDLE: $(#id)
} else {
elem = document.getElementById( match[2] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE and Opera return items
// by name instead of ID
if ( elem.id !== match[2] ) {
return rootjQuery.find( selector );
}
// Otherwise, we inject the element directly into the jQuery object
this.length = 1;
this[0] = elem;
}
this.context = document;
this.selector = selector;
return this;
}
// HANDLE: $(expr, $(...))
} else if ( !context || context.jquery ) {
return ( context || rootjQuery ).find( selector );
// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
return this.constructor( context ).find( selector );
}
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return rootjQuery.ready( selector );
}
if ( selector.selector !== undefined ) {
this.selector = selector.selector;
this.context = selector.context;
}
return jQuery.makeArray( selector, this );
},
// Start with an empty selector
selector: "",
// The current version of jQuery being used
jquery: "1.8.3",
// The default length of a jQuery object is 0
length: 0,
// The number of elements contained in the matched element set
size: function() {
return this.length;
},
toArray: function() {
return core_slice.call( this );
},
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function( num ) {
return num == null ?
// Return a 'clean' array
this.toArray() :
// Return just the object
( num < 0 ? this[ this.length + num ] : this[ num ] );
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems, name, selector ) {
// Build a new jQuery matched element set
var ret = jQuery.merge( this.constructor(), elems );
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
ret.context = this.context;
if ( name === "find" ) {
ret.selector = this.selector + ( this.selector ? " " : "" ) + selector;
} else if ( name ) {
ret.selector = this.selector + "." + name + "(" + selector + ")";
}
// Return the newly-formed element set
return ret;
},
// Execute a callback for every element in the matched set.
// (You can seed the arguments with an array of args, but this is
// only used internally.)
each: function( callback, args ) {
return jQuery.each( this, callback, args );
},
ready: function( fn ) {
// Add the callback
jQuery.ready.promise().done( fn );
return this;
},
eq: function( i ) {
i = +i;
return i === -1 ?
this.slice( i ) :
this.slice( i, i + 1 );
},
first: function() {
return this.eq( 0 );
},
last: function() {
return this.eq( -1 );
},
slice: function() {
return this.pushStack( core_slice.apply( this, arguments ),
"slice", core_slice.call(arguments).join(",") );
},
map: function( callback ) {
return this.pushStack( jQuery.map(this, function( elem, i ) {
return callback.call( elem, i, elem );
}));
},
end: function() {
return this.prevObject || this.constructor(null);
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: core_push,
sort: [].sort,
splice: [].splice
};
// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;
jQuery.extend = jQuery.fn.extend = function() {
var options, name, src, copy, copyIsArray, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
target = {};
}
// extend jQuery itself if only one argument is passed
if ( length === i ) {
target = this;
--i;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && jQuery.isArray(src) ? src : [];
} else {
clone = src && jQuery.isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[ name ] = jQuery.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
jQuery.extend({
noConflict: function( deep ) {
if ( window.$ === jQuery ) {
window.$ = _$;
}
if ( deep && window.jQuery === jQuery ) {
window.jQuery = _jQuery;
}
return jQuery;
},
// Is the DOM ready to be used? Set to true once it occurs.
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
// Hold (or release) the ready event
holdReady: function( hold ) {
if ( hold ) {
jQuery.readyWait++;
} else {
jQuery.ready( true );
}
},
// Handle when the DOM is ready
ready: function( wait ) {
// Abort if there are pending holds or we're already ready
if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
return;
}
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if ( !document.body ) {
return setTimeout( jQuery.ready, 1 );
}
// Remember that the DOM is ready
jQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if ( wait !== true && --jQuery.readyWait > 0 ) {
return;
}
// If there are functions bound, to execute
readyList.resolveWith( document, [ jQuery ] );
// Trigger any bound ready events
if ( jQuery.fn.trigger ) {
jQuery( document ).trigger("ready").off("ready");
}
},
// See test/unit/core.js for details concerning isFunction.
// Since version 1.3, DOM methods and functions like alert
// aren't supported. They return false on IE (#2968).
isFunction: function( obj ) {
return jQuery.type(obj) === "function";
},
isArray: Array.isArray || function( obj ) {
return jQuery.type(obj) === "array";
},
isWindow: function( obj ) {
return obj != null && obj == obj.window;
},
isNumeric: function( obj ) {
return !isNaN( parseFloat(obj) ) && isFinite( obj );
},
type: function( obj ) {
return obj == null ?
String( obj ) :
class2type[ core_toString.call(obj) ] || "object";
},
isPlainObject: function( obj ) {
// Must be an Object.
// Because of IE, we also have to check the presence of the constructor property.
// Make sure that DOM nodes and window objects don't pass through, as well
if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
try {
// Not own constructor property must be Object
if ( obj.constructor &&
!core_hasOwn.call(obj, "constructor") &&
!core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
return false;
}
} catch ( e ) {
// IE8,9 Will throw exceptions on certain host objects #9897
return false;
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
var key;
for ( key in obj ) {}
return key === undefined || core_hasOwn.call( obj, key );
},
isEmptyObject: function( obj ) {
var name;
for ( name in obj ) {
return false;
}
return true;
},
error: function( msg ) {
throw new Error( msg );
},
// data: string of html
// context (optional): If specified, the fragment will be created in this context, defaults to document
// scripts (optional): If true, will include scripts passed in the html string
parseHTML: function( data, context, scripts ) {
var parsed;
if ( !data || typeof data !== "string" ) {
return null;
}
if ( typeof context === "boolean" ) {
scripts = context;
context = 0;
}
context = context || document;
// Single tag
if ( (parsed = rsingleTag.exec( data )) ) {
return [ context.createElement( parsed[1] ) ];
}
parsed = jQuery.buildFragment( [ data ], context, scripts ? null : [] );
return jQuery.merge( [],
(parsed.cacheable ? jQuery.clone( parsed.fragment ) : parsed.fragment).childNodes );
},
parseJSON: function( data ) {
if ( !data || typeof data !== "string") {
return null;
}
// Make sure leading/trailing whitespace is removed (IE can't handle it)
data = jQuery.trim( data );
// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
}
// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if ( rvalidchars.test( data.replace( rvalidescape, "@" )
.replace( rvalidtokens, "]" )
.replace( rvalidbraces, "")) ) {
return ( new Function( "return " + data ) )();
}
jQuery.error( "Invalid JSON: " + data );
},
// Cross-browser xml parsing
parseXML: function( data ) {
var xml, tmp;
if ( !data || typeof data !== "string" ) {
return null;
}
try {
if ( window.DOMParser ) { // Standard
tmp = new DOMParser();
xml = tmp.parseFromString( data , "text/xml" );
} else { // IE
xml = new ActiveXObject( "Microsoft.XMLDOM" );
xml.async = "false";
xml.loadXML( data );
}
} catch( e ) {
xml = undefined;
}
if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
},
noop: function() {},
// Evaluates a script in a global context
// Workarounds based on findings by Jim Driscoll
// http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
globalEval: function( data ) {
if ( data && core_rnotwhite.test( data ) ) {
// We use execScript on Internet Explorer
// We use an anonymous function so that context is window
// rather than jQuery in Firefox
( window.execScript || function( data ) {
window[ "eval" ].call( window, data );
} )( data );
}
},
// Convert dashed to camelCase; used by the css and data modules
// Microsoft forgot to hump their vendor prefix (#9572)
camelCase: function( string ) {
return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
},
nodeName: function( elem, name ) {
return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
},
// args is for internal usage only
each: function( obj, callback, args ) {
var name,
i = 0,
length = obj.length,
isObj = length === undefined || jQuery.isFunction( obj );
if ( args ) {
if ( isObj ) {
for ( name in obj ) {
if ( callback.apply( obj[ name ], args ) === false ) {
break;
}
}
} else {
for ( ; i < length; ) {
if ( callback.apply( obj[ i++ ], args ) === false ) {
break;
}
}
}
// A special, fast, case for the most common use of each
} else {
if ( isObj ) {
for ( name in obj ) {
if ( callback.call( obj[ name ], name, obj[ name ] ) === false ) {
break;
}
}
} else {
for ( ; i < length; ) {
if ( callback.call( obj[ i ], i, obj[ i++ ] ) === false ) {
break;
}
}
}
}
return obj;
},
// Use native String.trim function wherever possible
trim: core_trim && !core_trim.call("\uFEFF\xA0") ?
function( text ) {
return text == null ?
"" :
core_trim.call( text );
} :
// Otherwise use our own trimming functionality
function( text ) {
return text == null ?
"" :
( text + "" ).replace( rtrim, "" );
},
// results is for internal usage only
makeArray: function( arr, results ) {
var type,
ret = results || [];
if ( arr != null ) {
// The window, strings (and functions) also have 'length'
// Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930
type = jQuery.type( arr );
if ( arr.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( arr ) ) {
core_push.call( ret, arr );
} else {
jQuery.merge( ret, arr );
}
}
return ret;
},
inArray: function( elem, arr, i ) {
var len;
if ( arr ) {
if ( core_indexOf ) {
return core_indexOf.call( arr, elem, i );
}
len = arr.length;
i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0;
for ( ; i < len; i++ ) {
// Skip accessing in sparse arrays
if ( i in arr && arr[ i ] === elem ) {
return i;
}
}
}
return -1;
},
merge: function( first, second ) {
var l = second.length,
i = first.length,
j = 0;
if ( typeof l === "number" ) {
for ( ; j < l; j++ ) {
first[ i++ ] = second[ j ];
}
} else {
while ( second[j] !== undefined ) {
first[ i++ ] = second[ j++ ];
}
}
first.length = i;
return first;
},
grep: function( elems, callback, inv ) {
var retVal,
ret = [],
i = 0,
length = elems.length;
inv = !!inv;
// Go through the array, only saving the items
// that pass the validator function
for ( ; i < length; i++ ) {
retVal = !!callback( elems[ i ], i );
if ( inv !== retVal ) {
ret.push( elems[ i ] );
}
}
return ret;
},
// arg is for internal usage only
map: function( elems, callback, arg ) {
var value, key,
ret = [],
i = 0,
length = elems.length,
// jquery objects are treated as arrays
isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ;
// Go through the array, translating each of the items to their
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
// Go through every key on the object,
} else {
for ( key in elems ) {
value = callback( elems[ key ], key, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
}
// Flatten any nested arrays
return ret.concat.apply( [], ret );
},
// A global GUID counter for objects
guid: 1,
// Bind a function to a context, optionally partially applying any
// arguments.
proxy: function( fn, context ) {
var tmp, args, proxy;
if ( typeof context === "string" ) {
tmp = fn[ context ];
context = fn;
fn = tmp;
}
// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if ( !jQuery.isFunction( fn ) ) {
return undefined;
}
// Simulated bind
args = core_slice.call( arguments, 2 );
proxy = function() {
return fn.apply( context, args.concat( core_slice.call( arguments ) ) );
};
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || jQuery.guid++;
return proxy;
},
// Multifunctional method to get and set values of a collection
// The value/s can optionally be executed if it's a function
access: function( elems, fn, key, value, chainable, emptyGet, pass ) {
var exec,
bulk = key == null,
i = 0,
length = elems.length;
// Sets many values
if ( key && typeof key === "object" ) {
for ( i in key ) {
jQuery.access( elems, fn, i, key[i], 1, emptyGet, value );
}
chainable = 1;
// Sets one value
} else if ( value !== undefined ) {
// Optionally, function values get executed if exec is true
exec = pass === undefined && jQuery.isFunction( value );
if ( bulk ) {
// Bulk operations only iterate when executing function values
if ( exec ) {
exec = fn;
fn = function( elem, key, value ) {
return exec.call( jQuery( elem ), value );
};
// Otherwise they run against the entire set
} else {
fn.call( elems, value );
fn = null;
}
}
if ( fn ) {
for (; i < length; i++ ) {
fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass );
}
}
chainable = 1;
}
return chainable ?
elems :
// Gets
bulk ?
fn.call( elems ) :
length ? fn( elems[0], key ) : emptyGet;
},
now: function() {
return ( new Date() ).getTime();
}
});
jQuery.ready.promise = function( obj ) {
if ( !readyList ) {
readyList = jQuery.Deferred();
// Catch cases where $(document).ready() is called after the browser event has already occurred.
// we once tried to use readyState "interactive" here, but it caused issues like the one
// discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
setTimeout( jQuery.ready, 1 );
// Standards-based browsers support DOMContentLoaded
} else if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", jQuery.ready, false );
// If IE event model is used
} else {
// Ensure firing before onload, maybe late but safe also for iframes
document.attachEvent( "onreadystatechange", DOMContentLoaded );
// A fallback to window.onload, that will always work
window.attachEvent( "onload", jQuery.ready );
// If IE and not a frame
// continually check to see if the document is ready
var top = false;
try {
top = window.frameElement == null && document.documentElement;
} catch(e) {}
if ( top && top.doScroll ) {
(function doScrollCheck() {
if ( !jQuery.isReady ) {
try {
// Use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
top.doScroll("left");
} catch(e) {
return setTimeout( doScrollCheck, 50 );
}
// and execute any waiting functions
jQuery.ready();
}
})();
}
}
}
return readyList.promise( obj );
};
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
// All jQuery objects should point back to these
rootjQuery = jQuery(document);
// String to Object options format cache
var optionsCache = {};
// Convert String-formatted options into Object-formatted ones and store in cache
function createOptions( options ) {
var object = optionsCache[ options ] = {};
jQuery.each( options.split( core_rspace ), function( _, flag ) {
object[ flag ] = true;
});
return object;
}
/*
* Create a callback list using the following parameters:
*
* options: an optional list of space-separated options that will change how
* the callback list behaves or a more traditional option object
*
* By default a callback list will act like an event callback list and can be
* "fired" multiple times.
*
* Possible options:
*
* once: will ensure the callback list can only be fired once (like a Deferred)
*
* memory: will keep track of previous values and will call any callback added
* after the list has been fired right away with the latest "memorized"
* values (like a Deferred)
*
* unique: will ensure a callback can only be added once (no duplicate in the list)
*
* stopOnFalse: interrupt callings when a callback returns false
*
*/
jQuery.Callbacks = function( options ) {
// Convert options from String-formatted to Object-formatted if needed
// (we check in cache first)
options = typeof options === "string" ?
( optionsCache[ options ] || createOptions( options ) ) :
jQuery.extend( {}, options );
var // Last fire value (for non-forgettable lists)
memory,
// Flag to know if list was already fired
fired,
// Flag to know if list is currently firing
firing,
// First callback to fire (used internally by add and fireWith)
firingStart,
// End of the loop when firing
firingLength,
// Index of currently firing callback (modified by remove if needed)
firingIndex,
// Actual callback list
list = [],
// Stack of fire calls for repeatable lists
stack = !options.once && [],
// Fire callbacks
fire = function( data ) {
memory = options.memory && data;
fired = true;
firingIndex = firingStart || 0;
firingStart = 0;
firingLength = list.length;
firing = true;
for ( ; list && firingIndex < firingLength; firingIndex++ ) {
if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) {
memory = false; // To prevent further calls using add
break;
}
}
firing = false;
if ( list ) {
if ( stack ) {
if ( stack.length ) {
fire( stack.shift() );
}
} else if ( memory ) {
list = [];
} else {
self.disable();
}
}
},
// Actual Callbacks object
self = {
// Add a callback or a collection of callbacks to the list
add: function() {
if ( list ) {
// First, we save the current length
var start = list.length;
(function add( args ) {
jQuery.each( args, function( _, arg ) {
var type = jQuery.type( arg );
if ( type === "function" ) {
if ( !options.unique || !self.has( arg ) ) {
list.push( arg );
}
} else if ( arg && arg.length && type !== "string" ) {
// Inspect recursively
add( arg );
}
});
})( arguments );
// Do we need to add the callbacks to the
// current firing batch?
if ( firing ) {
firingLength = list.length;
// With memory, if we're not firing then
// we should call right away
} else if ( memory ) {
firingStart = start;
fire( memory );
}
}
return this;
},
// Remove a callback from the list
remove: function() {
if ( list ) {
jQuery.each( arguments, function( _, arg ) {
var index;
while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
list.splice( index, 1 );
// Handle firing indexes
if ( firing ) {
if ( index <= firingLength ) {
firingLength--;
}
if ( index <= firingIndex ) {
firingIndex--;
}
}
}
});
}
return this;
},
// Control if a given callback is in the list
has: function( fn ) {
return jQuery.inArray( fn, list ) > -1;
},
// Remove all callbacks from the list
empty: function() {
list = [];
return this;
},
// Have the list do nothing anymore
disable: function() {
list = stack = memory = undefined;
return this;
},
// Is it disabled?
disabled: function() {
return !list;
},
// Lock the list in its current state
lock: function() {
stack = undefined;
if ( !memory ) {
self.disable();
}
return this;
},
// Is it locked?
locked: function() {
return !stack;
},
// Call all callbacks with the given context and arguments
fireWith: function( context, args ) {
args = args || [];
args = [ context, args.slice ? args.slice() : args ];
if ( list && ( !fired || stack ) ) {
if ( firing ) {
stack.push( args );
} else {
fire( args );
}
}
return this;
},
// Call all the callbacks with the given arguments
fire: function() {
self.fireWith( this, arguments );
return this;
},
// To know if the callbacks have already been called at least once
fired: function() {
return !!fired;
}
};
return self;
};
jQuery.extend({
Deferred: function( func ) {
var tuples = [
// action, add listener, listener list, final state
[ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ],
[ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ],
[ "notify", "progress", jQuery.Callbacks("memory") ]
],
state = "pending",
promise = {
state: function() {
return state;
},
always: function() {
deferred.done( arguments ).fail( arguments );
return this;
},
then: function( /* fnDone, fnFail, fnProgress */ ) {
var fns = arguments;
return jQuery.Deferred(function( newDefer ) {
jQuery.each( tuples, function( i, tuple ) {
var action = tuple[ 0 ],
fn = fns[ i ];
// deferred[ done | fail | progress ] for forwarding actions to newDefer
deferred[ tuple[1] ]( jQuery.isFunction( fn ) ?
function() {
var returned = fn.apply( this, arguments );
if ( returned && jQuery.isFunction( returned.promise ) ) {
returned.promise()
.done( newDefer.resolve )
.fail( newDefer.reject )
.progress( newDefer.notify );
} else {
newDefer[ action + "With" ]( this === deferred ? newDefer : this, [ returned ] );
}
} :
newDefer[ action ]
);
});
fns = null;
}).promise();
},
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function( obj ) {
return obj != null ? jQuery.extend( obj, promise ) : promise;
}
},
deferred = {};
// Keep pipe for back-compat
promise.pipe = promise.then;
// Add list-specific methods
jQuery.each( tuples, function( i, tuple ) {
var list = tuple[ 2 ],
stateString = tuple[ 3 ];
// promise[ done | fail | progress ] = list.add
promise[ tuple[1] ] = list.add;
// Handle state
if ( stateString ) {
list.add(function() {
// state = [ resolved | rejected ]
state = stateString;
// [ reject_list | resolve_list ].disable; progress_list.lock
}, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock );
}
// deferred[ resolve | reject | notify ] = list.fire
deferred[ tuple[0] ] = list.fire;
deferred[ tuple[0] + "With" ] = list.fireWith;
});
// Make the deferred a promise
promise.promise( deferred );
// Call given func if any
if ( func ) {
func.call( deferred, deferred );
}
// All done!
return deferred;
},
// Deferred helper
when: function( subordinate /* , ..., subordinateN */ ) {
var i = 0,
resolveValues = core_slice.call( arguments ),
length = resolveValues.length,
// the count of uncompleted subordinates
remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0,
// the master Deferred. If resolveValues consist of only a single Deferred, just use that.
deferred = remaining === 1 ? subordinate : jQuery.Deferred(),
// Update function for both resolve and progress values
updateFunc = function( i, contexts, values ) {
return function( value ) {
contexts[ i ] = this;
values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value;
if( values === progressValues ) {
deferred.notifyWith( contexts, values );
} else if ( !( --remaining ) ) {
deferred.resolveWith( contexts, values );
}
};
},
progressValues, progressContexts, resolveContexts;
// add listeners to Deferred subordinates; treat others as resolved
if ( length > 1 ) {
progressValues = new Array( length );
progressContexts = new Array( length );
resolveContexts = new Array( length );
for ( ; i < length; i++ ) {
if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) {
resolveValues[ i ].promise()
.done( updateFunc( i, resolveContexts, resolveValues ) )
.fail( deferred.reject )
.progress( updateFunc( i, progressContexts, progressValues ) );
} else {
--remaining;
}
}
}
// if we're not waiting on anything, resolve the master
if ( !remaining ) {
deferred.resolveWith( resolveContexts, resolveValues );
}
return deferred.promise();
}
});
jQuery.support = (function() {
var support,
all,
a,
select,
opt,
input,
fragment,
eventName,
i,
isSupported,
clickFn,
div = document.createElement("div");
// Setup
div.setAttribute( "className", "t" );
div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";
// Support tests won't run in some limited or non-browser environments
all = div.getElementsByTagName("*");
a = div.getElementsByTagName("a")[ 0 ];
if ( !all || !a || !all.length ) {
return {};
}
// First batch of tests
select = document.createElement("select");
opt = select.appendChild( document.createElement("option") );
input = div.getElementsByTagName("input")[ 0 ];
a.style.cssText = "top:1px;float:left;opacity:.5";
support = {
// IE strips leading whitespace when .innerHTML is used
leadingWhitespace: ( div.firstChild.nodeType === 3 ),
// Make sure that tbody elements aren't automatically inserted
// IE will insert them into empty tables
tbody: !div.getElementsByTagName("tbody").length,
// Make sure that link elements get serialized correctly by innerHTML
// This requires a wrapper element in IE
htmlSerialize: !!div.getElementsByTagName("link").length,
// Get the style information from getAttribute
// (IE uses .cssText instead)
style: /top/.test( a.getAttribute("style") ),
// Make sure that URLs aren't manipulated
// (IE normalizes it by default)
hrefNormalized: ( a.getAttribute("href") === "/a" ),
// Make sure that element opacity exists
// (IE uses filter instead)
// Use a regex to work around a WebKit issue. See #5145
opacity: /^0.5/.test( a.style.opacity ),
// Verify style float existence
// (IE uses styleFloat instead of cssFloat)
cssFloat: !!a.style.cssFloat,
// Make sure that if no value is specified for a checkbox
// that it defaults to "on".
// (WebKit defaults to "" instead)
checkOn: ( input.value === "on" ),
// Make sure that a selected-by-default option has a working selected property.
// (WebKit defaults to false instead of true, IE too, if it's in an optgroup)
optSelected: opt.selected,
// Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7)
getSetAttribute: div.className !== "t",
// Tests for enctype support on a form (#6743)
enctype: !!document.createElement("form").enctype,
// Makes sure cloning an html5 element does not cause problems
// Where outerHTML is undefined, this still works
html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>",
// jQuery.support.boxModel DEPRECATED in 1.8 since we don't support Quirks Mode
boxModel: ( document.compatMode === "CSS1Compat" ),
// Will be defined later
submitBubbles: true,
changeBubbles: true,
focusinBubbles: false,
deleteExpando: true,
noCloneEvent: true,
inlineBlockNeedsLayout: false,
shrinkWrapBlocks: false,
reliableMarginRight: true,
boxSizingReliable: true,
pixelPosition: false
};
// Make sure checked status is properly cloned
input.checked = true;
support.noCloneChecked = input.cloneNode( true ).checked;
// Make sure that the options inside disabled selects aren't marked as disabled
// (WebKit marks them as disabled)
select.disabled = true;
support.optDisabled = !opt.disabled;
// Test to see if it's possible to delete an expando from an element
// Fails in Internet Explorer
try {
delete div.test;
} catch( e ) {
support.deleteExpando = false;
}
if ( !div.addEventListener && div.attachEvent && div.fireEvent ) {
div.attachEvent( "onclick", clickFn = function() {
// Cloning a node shouldn't copy over any
// bound event handlers (IE does this)
support.noCloneEvent = false;
});
div.cloneNode( true ).fireEvent("onclick");
div.detachEvent( "onclick", clickFn );
}
// Check if a radio maintains its value
// after being appended to the DOM
input = document.createElement("input");
input.value = "t";
input.setAttribute( "type", "radio" );
support.radioValue = input.value === "t";
input.setAttribute( "checked", "checked" );
// #11217 - WebKit loses check when the name is after the checked attribute
input.setAttribute( "name", "t" );
div.appendChild( input );
fragment = document.createDocumentFragment();
fragment.appendChild( div.lastChild );
// WebKit doesn't clone checked state correctly in fragments
support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked;
// Check if a disconnected checkbox will retain its checked
// value of true after appended to the DOM (IE6/7)
support.appendChecked = input.checked;
fragment.removeChild( input );
fragment.appendChild( div );
// Technique from Juriy Zaytsev
// http://perfectionkills.com/detecting-event-support-without-browser-sniffing/
// We only care about the case where non-standard event systems
// are used, namely in IE. Short-circuiting here helps us to
// avoid an eval call (in setAttribute) which can cause CSP
// to go haywire. See: https://developer.mozilla.org/en/Security/CSP
if ( div.attachEvent ) {
for ( i in {
submit: true,
change: true,
focusin: true
}) {
eventName = "on" + i;
isSupported = ( eventName in div );
if ( !isSupported ) {
div.setAttribute( eventName, "return;" );
isSupported = ( typeof div[ eventName ] === "function" );
}
support[ i + "Bubbles" ] = isSupported;
}
}
// Run tests that need a body at doc ready
jQuery(function() {
var container, div, tds, marginDiv,
divReset = "padding:0;margin:0;border:0;display:block;overflow:hidden;",
body = document.getElementsByTagName("body")[0];
if ( !body ) {
// Return for frameset docs that don't have a body
return;
}
container = document.createElement("div");
container.style.cssText = "visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px";
body.insertBefore( container, body.firstChild );
// Construct the test element
div = document.createElement("div");
container.appendChild( div );
// Check if table cells still have offsetWidth/Height when they are set
// to display:none and there are still other visible table cells in a
// table row; if so, offsetWidth/Height are not reliable for use when
// determining if an element has been hidden directly using
// display:none (it is still safe to use offsets if a parent element is
// hidden; don safety goggles and see bug #4512 for more information).
// (only IE 8 fails this test)
div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>";
tds = div.getElementsByTagName("td");
tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none";
isSupported = ( tds[ 0 ].offsetHeight === 0 );
tds[ 0 ].style.display = "";
tds[ 1 ].style.display = "none";
// Check if empty table cells still have offsetWidth/Height
// (IE <= 8 fail this test)
support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 );
// Check box-sizing and margin behavior
div.innerHTML = "";
div.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%;";
support.boxSizing = ( div.offsetWidth === 4 );
support.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== 1 );
// NOTE: To any future maintainer, we've window.getComputedStyle
// because jsdom on node.js will break without it.
if ( window.getComputedStyle ) {
support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%";
support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px";
// Check if div with explicit width and no margin-right incorrectly
// gets computed margin-right based on width of container. For more
// info see bug #3333
// Fails in WebKit before Feb 2011 nightlies
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
marginDiv = document.createElement("div");
marginDiv.style.cssText = div.style.cssText = divReset;
marginDiv.style.marginRight = marginDiv.style.width = "0";
div.style.width = "1px";
div.appendChild( marginDiv );
support.reliableMarginRight =
!parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight );
}
if ( typeof div.style.zoom !== "undefined" ) {
// Check if natively block-level elements act like inline-block
// elements when setting their display to 'inline' and giving
// them layout
// (IE < 8 does this)
div.innerHTML = "";
div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1";
support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 );
// Check if elements with layout shrink-wrap their children
// (IE 6 does this)
div.style.display = "block";
div.style.overflow = "visible";
div.innerHTML = "<div></div>";
div.firstChild.style.width = "5px";
support.shrinkWrapBlocks = ( div.offsetWidth !== 3 );
container.style.zoom = 1;
}
// Null elements to avoid leaks in IE
body.removeChild( container );
container = div = tds = marginDiv = null;
});
// Null elements to avoid leaks in IE
fragment.removeChild( div );
all = a = select = opt = input = fragment = div = null;
return support;
})();
var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/,
rmultiDash = /([A-Z])/g;
jQuery.extend({
cache: {},
deletedIds: [],
// Remove at next major release (1.9/2.0)
uuid: 0,
// Unique for each copy of jQuery on the page
// Non-digits removed to match rinlinejQuery
expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ),
// The following elements throw uncatchable exceptions if you
// attempt to add expando properties to them.
noData: {
"embed": true,
// Ban all objects except for Flash (which handle expandos)
"object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",
"applet": true
},
hasData: function( elem ) {
elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ];
return !!elem && !isEmptyDataObject( elem );
},
data: function( elem, name, data, pvt /* Internal Use Only */ ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var thisCache, ret,
internalKey = jQuery.expando,
getByName = typeof name === "string",
// We have to handle DOM nodes and JS objects differently because IE6-7
// can't GC object references properly across the DOM-JS boundary
isNode = elem.nodeType,
// Only DOM nodes need the global jQuery cache; JS object data is
// attached directly to the object so GC can occur automatically
cache = isNode ? jQuery.cache : elem,
// Only defining an ID for JS objects if its cache already exists allows
// the code to shortcut on the same path as a DOM node with no cache
id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey;
// Avoid doing any more work than we need to when trying to get data on an
// object that has no data at all
if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && getByName && data === undefined ) {
return;
}
if ( !id ) {
// Only DOM nodes need a new unique ID for each element since their data
// ends up in the global cache
if ( isNode ) {
elem[ internalKey ] = id = jQuery.deletedIds.pop() || jQuery.guid++;
} else {
id = internalKey;
}
}
if ( !cache[ id ] ) {
cache[ id ] = {};
// Avoids exposing jQuery metadata on plain JS objects when the object
// is serialized using JSON.stringify
if ( !isNode ) {
cache[ id ].toJSON = jQuery.noop;
}
}
// An object can be passed to jQuery.data instead of a key/value pair; this gets
// shallow copied over onto the existing cache
if ( typeof name === "object" || typeof name === "function" ) {
if ( pvt ) {
cache[ id ] = jQuery.extend( cache[ id ], name );
} else {
cache[ id ].data = jQuery.extend( cache[ id ].data, name );
}
}
thisCache = cache[ id ];
// jQuery data() is stored in a separate object inside the object's internal data
// cache in order to avoid key collisions between internal data and user-defined
// data.
if ( !pvt ) {
if ( !thisCache.data ) {
thisCache.data = {};
}
thisCache = thisCache.data;
}
if ( data !== undefined ) {
thisCache[ jQuery.camelCase( name ) ] = data;
}
// Check for both converted-to-camel and non-converted data property names
// If a data property was specified
if ( getByName ) {
// First Try to find as-is property data
ret = thisCache[ name ];
// Test for null|undefined property data
if ( ret == null ) {
// Try to find the camelCased property
ret = thisCache[ jQuery.camelCase( name ) ];
}
} else {
ret = thisCache;
}
return ret;
},
removeData: function( elem, name, pvt /* Internal Use Only */ ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var thisCache, i, l,
isNode = elem.nodeType,
// See jQuery.data for more information
cache = isNode ? jQuery.cache : elem,
id = isNode ? elem[ jQuery.expando ] : jQuery.expando;
// If there is already no cache entry for this object, there is no
// purpose in continuing
if ( !cache[ id ] ) {
return;
}
if ( name ) {
thisCache = pvt ? cache[ id ] : cache[ id ].data;
if ( thisCache ) {
// Support array or space separated string names for data keys
if ( !jQuery.isArray( name ) ) {
// try the string as a key before any manipulation
if ( name in thisCache ) {
name = [ name ];
} else {
// split the camel cased version by spaces unless a key with the spaces exists
name = jQuery.camelCase( name );
if ( name in thisCache ) {
name = [ name ];
} else {
name = name.split(" ");
}
}
}
for ( i = 0, l = name.length; i < l; i++ ) {
delete thisCache[ name[i] ];
}
// If there is no data left in the cache, we want to continue
// and let the cache object itself get destroyed
if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) {
return;
}
}
}
// See jQuery.data for more information
if ( !pvt ) {
delete cache[ id ].data;
// Don't destroy the parent cache unless the internal data object
// had been the only thing left in it
if ( !isEmptyDataObject( cache[ id ] ) ) {
return;
}
}
// Destroy the cache
if ( isNode ) {
jQuery.cleanData( [ elem ], true );
// Use delete when supported for expandos or `cache` is not a window per isWindow (#10080)
} else if ( jQuery.support.deleteExpando || cache != cache.window ) {
delete cache[ id ];
// When all else fails, null
} else {
cache[ id ] = null;
}
},
// For internal use only.
_data: function( elem, name, data ) {
return jQuery.data( elem, name, data, true );
},
// A method for determining if a DOM node can handle the data expando
acceptData: function( elem ) {
var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ];
// nodes accept data unless otherwise specified; rejection can be conditional
return !noData || noData !== true && elem.getAttribute("classid") === noData;
}
});
jQuery.fn.extend({
data: function( key, value ) {
var parts, part, attr, name, l,
elem = this[0],
i = 0,
data = null;
// Gets all values
if ( key === undefined ) {
if ( this.length ) {
data = jQuery.data( elem );
if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) {
attr = elem.attributes;
for ( l = attr.length; i < l; i++ ) {
name = attr[i].name;
if ( !name.indexOf( "data-" ) ) {
name = jQuery.camelCase( name.substring(5) );
dataAttr( elem, name, data[ name ] );
}
}
jQuery._data( elem, "parsedAttrs", true );
}
}
return data;
}
// Sets multiple values
if ( typeof key === "object" ) {
return this.each(function() {
jQuery.data( this, key );
});
}
parts = key.split( ".", 2 );
parts[1] = parts[1] ? "." + parts[1] : "";
part = parts[1] + "!";
return jQuery.access( this, function( value ) {
if ( value === undefined ) {
data = this.triggerHandler( "getData" + part, [ parts[0] ] );
// Try to fetch any internally stored data first
if ( data === undefined && elem ) {
data = jQuery.data( elem, key );
data = dataAttr( elem, key, data );
}
return data === undefined && parts[1] ?
this.data( parts[0] ) :
data;
}
parts[1] = value;
this.each(function() {
var self = jQuery( this );
self.triggerHandler( "setData" + part, parts );
jQuery.data( this, key, value );
self.triggerHandler( "changeData" + part, parts );
});
}, null, value, arguments.length > 1, null, false );
},
removeData: function( key ) {
return this.each(function() {
jQuery.removeData( this, key );
});
}
});
function dataAttr( elem, key, data ) {
// If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if ( data === undefined && elem.nodeType === 1 ) {
var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();
data = elem.getAttribute( name );
if ( typeof data === "string" ) {
try {
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null :
// Only convert to a number if it doesn't change the string
+data + "" === data ? +data :
rbrace.test( data ) ? jQuery.parseJSON( data ) :
data;
} catch( e ) {}
// Make sure we set the data so it isn't changed later
jQuery.data( elem, key, data );
} else {
data = undefined;
}
}
return data;
}
// checks a cache object for emptiness
function isEmptyDataObject( obj ) {
var name;
for ( name in obj ) {
// if the public data object is empty, the private is still empty
if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) {
continue;
}
if ( name !== "toJSON" ) {
return false;
}
}
return true;
}
jQuery.extend({
queue: function( elem, type, data ) {
var queue;
if ( elem ) {
type = ( type || "fx" ) + "queue";
queue = jQuery._data( elem, type );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( data ) {
if ( !queue || jQuery.isArray(data) ) {
queue = jQuery._data( elem, type, jQuery.makeArray(data) );
} else {
queue.push( data );
}
}
return queue || [];
}
},
dequeue: function( elem, type ) {
type = type || "fx";
var queue = jQuery.queue( elem, type ),
startLength = queue.length,
fn = queue.shift(),
hooks = jQuery._queueHooks( elem, type ),
next = function() {
jQuery.dequeue( elem, type );
};
// If the fx queue is dequeued, always remove the progress sentinel
if ( fn === "inprogress" ) {
fn = queue.shift();
startLength--;
}
if ( fn ) {
// Add a progress sentinel to prevent the fx queue from being
// automatically dequeued
if ( type === "fx" ) {
queue.unshift( "inprogress" );
}
// clear up the last queue stop function
delete hooks.stop;
fn.call( elem, next, hooks );
}
if ( !startLength && hooks ) {
hooks.empty.fire();
}
},
// not intended for public consumption - generates a queueHooks object, or returns the current one
_queueHooks: function( elem, type ) {
var key = type + "queueHooks";
return jQuery._data( elem, key ) || jQuery._data( elem, key, {
empty: jQuery.Callbacks("once memory").add(function() {
jQuery.removeData( elem, type + "queue", true );
jQuery.removeData( elem, key, true );
})
});
}
});
jQuery.fn.extend({
queue: function( type, data ) {
var setter = 2;
if ( typeof type !== "string" ) {
data = type;
type = "fx";
setter--;
}
if ( arguments.length < setter ) {
return jQuery.queue( this[0], type );
}
return data === undefined ?
this :
this.each(function() {
var queue = jQuery.queue( this, type, data );
// ensure a hooks for this queue
jQuery._queueHooks( this, type );
if ( type === "fx" && queue[0] !== "inprogress" ) {
jQuery.dequeue( this, type );
}
});
},
dequeue: function( type ) {
return this.each(function() {
jQuery.dequeue( this, type );
});
},
// Based off of the plugin by Clint Helfers, with permission.
// http://blindsignals.com/index.php/2009/07/jquery-delay/
delay: function( time, type ) {
time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
type = type || "fx";
return this.queue( type, function( next, hooks ) {
var timeout = setTimeout( next, time );
hooks.stop = function() {
clearTimeout( timeout );
};
});
},
clearQueue: function( type ) {
return this.queue( type || "fx", [] );
},
// Get a promise resolved when queues of a certain type
// are emptied (fx is the type by default)
promise: function( type, obj ) {
var tmp,
count = 1,
defer = jQuery.Deferred(),
elements = this,
i = this.length,
resolve = function() {
if ( !( --count ) ) {
defer.resolveWith( elements, [ elements ] );
}
};
if ( typeof type !== "string" ) {
obj = type;
type = undefined;
}
type = type || "fx";
while( i-- ) {
tmp = jQuery._data( elements[ i ], type + "queueHooks" );
if ( tmp && tmp.empty ) {
count++;
tmp.empty.add( resolve );
}
}
resolve();
return defer.promise( obj );
}
});
var nodeHook, boolHook, fixSpecified,
rclass = /[\t\r\n]/g,
rreturn = /\r/g,
rtype = /^(?:button|input)$/i,
rfocusable = /^(?:button|input|object|select|textarea)$/i,
rclickable = /^a(?:rea|)$/i,
rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,
getSetAttribute = jQuery.support.getSetAttribute;
jQuery.fn.extend({
attr: function( name, value ) {
return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 );
},
removeAttr: function( name ) {
return this.each(function() {
jQuery.removeAttr( this, name );
});
},
prop: function( name, value ) {
return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 );
},
removeProp: function( name ) {
name = jQuery.propFix[ name ] || name;
return this.each(function() {
// try/catch handles cases where IE balks (such as removing a property on window)
try {
this[ name ] = undefined;
delete this[ name ];
} catch( e ) {}
});
},
addClass: function( value ) {
var classNames, i, l, elem,
setClass, c, cl;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).addClass( value.call(this, j, this.className) );
});
}
if ( value && typeof value === "string" ) {
classNames = value.split( core_rspace );
for ( i = 0, l = this.length; i < l; i++ ) {
elem = this[ i ];
if ( elem.nodeType === 1 ) {
if ( !elem.className && classNames.length === 1 ) {
elem.className = value;
} else {
setClass = " " + elem.className + " ";
for ( c = 0, cl = classNames.length; c < cl; c++ ) {
if ( setClass.indexOf( " " + classNames[ c ] + " " ) < 0 ) {
setClass += classNames[ c ] + " ";
}
}
elem.className = jQuery.trim( setClass );
}
}
}
}
return this;
},
removeClass: function( value ) {
var removes, className, elem, c, cl, i, l;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).removeClass( value.call(this, j, this.className) );
});
}
if ( (value && typeof value === "string") || value === undefined ) {
removes = ( value || "" ).split( core_rspace );
for ( i = 0, l = this.length; i < l; i++ ) {
elem = this[ i ];
if ( elem.nodeType === 1 && elem.className ) {
className = (" " + elem.className + " ").replace( rclass, " " );
// loop over each item in the removal list
for ( c = 0, cl = removes.length; c < cl; c++ ) {
// Remove until there is nothing to remove,
while ( className.indexOf(" " + removes[ c ] + " ") >= 0 ) {
className = className.replace( " " + removes[ c ] + " " , " " );
}
}
elem.className = value ? jQuery.trim( className ) : "";
}
}
}
return this;
},
toggleClass: function( value, stateVal ) {
var type = typeof value,
isBool = typeof stateVal === "boolean";
if ( jQuery.isFunction( value ) ) {
return this.each(function( i ) {
jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal );
});
}
return this.each(function() {
if ( type === "string" ) {
// toggle individual class names
var className,
i = 0,
self = jQuery( this ),
state = stateVal,
classNames = value.split( core_rspace );
while ( (className = classNames[ i++ ]) ) {
// check each className given, space separated list
state = isBool ? state : !self.hasClass( className );
self[ state ? "addClass" : "removeClass" ]( className );
}
} else if ( type === "undefined" || type === "boolean" ) {
if ( this.className ) {
// store className if set
jQuery._data( this, "__className__", this.className );
}
// toggle whole className
this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || "";
}
});
},
hasClass: function( selector ) {
var className = " " + selector + " ",
i = 0,
l = this.length;
for ( ; i < l; i++ ) {
if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) {
return true;
}
}
return false;
},
val: function( value ) {
var hooks, ret, isFunction,
elem = this[0];
if ( !arguments.length ) {
if ( elem ) {
hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];
if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
return ret;
}
ret = elem.value;
return typeof ret === "string" ?
// handle most common string cases
ret.replace(rreturn, "") :
// handle cases where value is null/undef or number
ret == null ? "" : ret;
}
return;
}
isFunction = jQuery.isFunction( value );
return this.each(function( i ) {
var val,
self = jQuery(this);
if ( this.nodeType !== 1 ) {
return;
}
if ( isFunction ) {
val = value.call( this, i, self.val() );
} else {
val = value;
}
// Treat null/undefined as ""; convert numbers to string
if ( val == null ) {
val = "";
} else if ( typeof val === "number" ) {
val += "";
} else if ( jQuery.isArray( val ) ) {
val = jQuery.map(val, function ( value ) {
return value == null ? "" : value + "";
});
}
hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];
// If set returns undefined, fall back to normal setting
if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {
this.value = val;
}
});
}
});
jQuery.extend({
valHooks: {
option: {
get: function( elem ) {
// attributes.value is undefined in Blackberry 4.7 but
// uses .value. See #6932
var val = elem.attributes.value;
return !val || val.specified ? elem.value : elem.text;
}
},
select: {
get: function( elem ) {
var value, option,
options = elem.options,
index = elem.selectedIndex,
one = elem.type === "select-one" || index < 0,
values = one ? null : [],
max = one ? index + 1 : options.length,
i = index < 0 ?
max :
one ? index : 0;
// Loop through all the selected options
for ( ; i < max; i++ ) {
option = options[ i ];
// oldIE doesn't update selected after form reset (#2551)
if ( ( option.selected || i === index ) &&
// Don't return options that are disabled or in a disabled optgroup
( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) &&
( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) {
// Get the specific value for the option
value = jQuery( option ).val();
// We don't need an array for one selects
if ( one ) {
return value;
}
// Multi-Selects return an array
values.push( value );
}
}
return values;
},
set: function( elem, value ) {
var values = jQuery.makeArray( value );
jQuery(elem).find("option").each(function() {
this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0;
});
if ( !values.length ) {
elem.selectedIndex = -1;
}
return values;
}
}
},
// Unused in 1.8, left in so attrFn-stabbers won't die; remove in 1.9
attrFn: {},
attr: function( elem, name, value, pass ) {
var ret, hooks, notxml,
nType = elem.nodeType;
// don't get/set attributes on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
if ( pass && jQuery.isFunction( jQuery.fn[ name ] ) ) {
return jQuery( elem )[ name ]( value );
}
// Fallback to prop when attributes are not supported
if ( typeof elem.getAttribute === "undefined" ) {
return jQuery.prop( elem, name, value );
}
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
// All attributes are lowercase
// Grab necessary hook if one is defined
if ( notxml ) {
name = name.toLowerCase();
hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook );
}
if ( value !== undefined ) {
if ( value === null ) {
jQuery.removeAttr( elem, name );
return;
} else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
elem.setAttribute( name, value + "" );
return value;
}
} else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
ret = elem.getAttribute( name );
// Non-existent attributes return null, we normalize to undefined
return ret === null ?
undefined :
ret;
}
},
removeAttr: function( elem, value ) {
var propName, attrNames, name, isBool,
i = 0;
if ( value && elem.nodeType === 1 ) {
attrNames = value.split( core_rspace );
for ( ; i < attrNames.length; i++ ) {
name = attrNames[ i ];
if ( name ) {
propName = jQuery.propFix[ name ] || name;
isBool = rboolean.test( name );
// See #9699 for explanation of this approach (setting first, then removal)
// Do not do this for boolean attributes (see #10870)
if ( !isBool ) {
jQuery.attr( elem, name, "" );
}
elem.removeAttribute( getSetAttribute ? name : propName );
// Set corresponding property to false for boolean attributes
if ( isBool && propName in elem ) {
elem[ propName ] = false;
}
}
}
}
},
attrHooks: {
type: {
set: function( elem, value ) {
// We can't allow the type property to be changed (since it causes problems in IE)
if ( rtype.test( elem.nodeName ) && elem.parentNode ) {
jQuery.error( "type property can't be changed" );
} else if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) {
// Setting the type on a radio button after the value resets the value in IE6-9
// Reset value to it's default in case type is set after value
// This is for element creation
var val = elem.value;
elem.setAttribute( "type", value );
if ( val ) {
elem.value = val;
}
return value;
}
}
},
// Use the value property for back compat
// Use the nodeHook for button elements in IE6/7 (#1954)
value: {
get: function( elem, name ) {
if ( nodeHook && jQuery.nodeName( elem, "button" ) ) {
return nodeHook.get( elem, name );
}
return name in elem ?
elem.value :
null;
},
set: function( elem, value, name ) {
if ( nodeHook && jQuery.nodeName( elem, "button" ) ) {
return nodeHook.set( elem, value, name );
}
// Does not return so that setAttribute is also used
elem.value = value;
}
}
},
propFix: {
tabindex: "tabIndex",
readonly: "readOnly",
"for": "htmlFor",
"class": "className",
maxlength: "maxLength",
cellspacing: "cellSpacing",
cellpadding: "cellPadding",
rowspan: "rowSpan",
colspan: "colSpan",
usemap: "useMap",
frameborder: "frameBorder",
contenteditable: "contentEditable"
},
prop: function( elem, name, value ) {
var ret, hooks, notxml,
nType = elem.nodeType;
// don't get/set properties on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
if ( notxml ) {
// Fix name and attach hooks
name = jQuery.propFix[ name ] || name;
hooks = jQuery.propHooks[ name ];
}
if ( value !== undefined ) {
if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
return ( elem[ name ] = value );
}
} else {
if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
return elem[ name ];
}
}
},
propHooks: {
tabIndex: {
get: function( elem ) {
// elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
// http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
var attributeNode = elem.getAttributeNode("tabindex");
return attributeNode && attributeNode.specified ?
parseInt( attributeNode.value, 10 ) :
rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
0 :
undefined;
}
}
}
});
// Hook for boolean attributes
boolHook = {
get: function( elem, name ) {
// Align boolean attributes with corresponding properties
// Fall back to attribute presence where some booleans are not supported
var attrNode,
property = jQuery.prop( elem, name );
return property === true || typeof property !== "boolean" && ( attrNode = elem.getAttributeNode(name) ) && attrNode.nodeValue !== false ?
name.toLowerCase() :
undefined;
},
set: function( elem, value, name ) {
var propName;
if ( value === false ) {
// Remove boolean attributes when set to false
jQuery.removeAttr( elem, name );
} else {
// value is true since we know at this point it's type boolean and not false
// Set boolean attributes to the same name and set the DOM property
propName = jQuery.propFix[ name ] || name;
if ( propName in elem ) {
// Only set the IDL specifically if it already exists on the element
elem[ propName ] = true;
}
elem.setAttribute( name, name.toLowerCase() );
}
return name;
}
};
// IE6/7 do not support getting/setting some attributes with get/setAttribute
if ( !getSetAttribute ) {
fixSpecified = {
name: true,
id: true,
coords: true
};
// Use this for any attribute in IE6/7
// This fixes almost every IE6/7 issue
nodeHook = jQuery.valHooks.button = {
get: function( elem, name ) {
var ret;
ret = elem.getAttributeNode( name );
return ret && ( fixSpecified[ name ] ? ret.value !== "" : ret.specified ) ?
ret.value :
undefined;
},
set: function( elem, value, name ) {
// Set the existing or create a new attribute node
var ret = elem.getAttributeNode( name );
if ( !ret ) {
ret = document.createAttribute( name );
elem.setAttributeNode( ret );
}
return ( ret.value = value + "" );
}
};
// Set width and height to auto instead of 0 on empty string( Bug #8150 )
// This is for removals
jQuery.each([ "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
set: function( elem, value ) {
if ( value === "" ) {
elem.setAttribute( name, "auto" );
return value;
}
}
});
});
// Set contenteditable to false on removals(#10429)
// Setting to empty string throws an error as an invalid value
jQuery.attrHooks.contenteditable = {
get: nodeHook.get,
set: function( elem, value, name ) {
if ( value === "" ) {
value = "false";
}
nodeHook.set( elem, value, name );
}
};
}
// Some attributes require a special call on IE
if ( !jQuery.support.hrefNormalized ) {
jQuery.each([ "href", "src", "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
get: function( elem ) {
var ret = elem.getAttribute( name, 2 );
return ret === null ? undefined : ret;
}
});
});
}
if ( !jQuery.support.style ) {
jQuery.attrHooks.style = {
get: function( elem ) {
// Return undefined in the case of empty string
// Normalize to lowercase since IE uppercases css property names
return elem.style.cssText.toLowerCase() || undefined;
},
set: function( elem, value ) {
return ( elem.style.cssText = value + "" );
}
};
}
// Safari mis-reports the default selected property of an option
// Accessing the parent's selectedIndex property fixes it
if ( !jQuery.support.optSelected ) {
jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, {
get: function( elem ) {
var parent = elem.parentNode;
if ( parent ) {
parent.selectedIndex;
// Make sure that it also works with optgroups, see #5701
if ( parent.parentNode ) {
parent.parentNode.selectedIndex;
}
}
return null;
}
});
}
// IE6/7 call enctype encoding
if ( !jQuery.support.enctype ) {
jQuery.propFix.enctype = "encoding";
}
// Radios and checkboxes getter/setter
if ( !jQuery.support.checkOn ) {
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = {
get: function( elem ) {
// Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified
return elem.getAttribute("value") === null ? "on" : elem.value;
}
};
});
}
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], {
set: function( elem, value ) {
if ( jQuery.isArray( value ) ) {
return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 );
}
}
});
});
var rformElems = /^(?:textarea|input|select)$/i,
rtypenamespace = /^([^\.]*|)(?:\.(.+)|)$/,
rhoverHack = /(?:^|\s)hover(\.\S+|)\b/,
rkeyEvent = /^key/,
rmouseEvent = /^(?:mouse|contextmenu)|click/,
rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
hoverHack = function( events ) {
return jQuery.event.special.hover ? events : events.replace( rhoverHack, "mouseenter$1 mouseleave$1" );
};
/*
* Helper functions for managing events -- not part of the public interface.
* Props to Dean Edwards' addEvent library for many of the ideas.
*/
jQuery.event = {
add: function( elem, types, handler, data, selector ) {
var elemData, eventHandle, events,
t, tns, type, namespaces, handleObj,
handleObjIn, handlers, special;
// Don't attach events to noData or text/comment nodes (allow plain objects tho)
if ( elem.nodeType === 3 || elem.nodeType === 8 || !types || !handler || !(elemData = jQuery._data( elem )) ) {
return;
}
// Caller can pass in an object of custom data in lieu of the handler
if ( handler.handler ) {
handleObjIn = handler;
handler = handleObjIn.handler;
selector = handleObjIn.selector;
}
// Make sure that the handler has a unique ID, used to find/remove it later
if ( !handler.guid ) {
handler.guid = jQuery.guid++;
}
// Init the element's event structure and main handler, if this is the first
events = elemData.events;
if ( !events ) {
elemData.events = events = {};
}
eventHandle = elemData.handle;
if ( !eventHandle ) {
elemData.handle = eventHandle = function( e ) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ?
jQuery.event.dispatch.apply( eventHandle.elem, arguments ) :
undefined;
};
// Add elem as a property of the handle fn to prevent a memory leak with IE non-native events
eventHandle.elem = elem;
}
// Handle multiple events separated by a space
// jQuery(...).bind("mouseover mouseout", fn);
types = jQuery.trim( hoverHack(types) ).split( " " );
for ( t = 0; t < types.length; t++ ) {
tns = rtypenamespace.exec( types[t] ) || [];
type = tns[1];
namespaces = ( tns[2] || "" ).split( "." ).sort();
// If event changes its type, use the special event handlers for the changed type
special = jQuery.event.special[ type ] || {};
// If selector defined, determine special event api type, otherwise given type
type = ( selector ? special.delegateType : special.bindType ) || type;
// Update special based on newly reset type
special = jQuery.event.special[ type ] || {};
// handleObj is passed to all event handlers
handleObj = jQuery.extend({
type: type,
origType: tns[1],
data: data,
handler: handler,
guid: handler.guid,
selector: selector,
needsContext: selector && jQuery.expr.match.needsContext.test( selector ),
namespace: namespaces.join(".")
}, handleObjIn );
// Init the event handler queue if we're the first
handlers = events[ type ];
if ( !handlers ) {
handlers = events[ type ] = [];
handlers.delegateCount = 0;
// Only use addEventListener/attachEvent if the special events handler returns false
if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
// Bind the global event handler to the element
if ( elem.addEventListener ) {
elem.addEventListener( type, eventHandle, false );
} else if ( elem.attachEvent ) {
elem.attachEvent( "on" + type, eventHandle );
}
}
}
if ( special.add ) {
special.add.call( elem, handleObj );
if ( !handleObj.handler.guid ) {
handleObj.handler.guid = handler.guid;
}
}
// Add to the element's handler list, delegates in front
if ( selector ) {
handlers.splice( handlers.delegateCount++, 0, handleObj );
} else {
handlers.push( handleObj );
}
// Keep track of which events have ever been used, for event optimization
jQuery.event.global[ type ] = true;
}
// Nullify elem to prevent memory leaks in IE
elem = null;
},
global: {},
// Detach an event or set of events from an element
remove: function( elem, types, handler, selector, mappedTypes ) {
var t, tns, type, origType, namespaces, origCount,
j, events, special, eventType, handleObj,
elemData = jQuery.hasData( elem ) && jQuery._data( elem );
if ( !elemData || !(events = elemData.events) ) {
return;
}
// Once for each type.namespace in types; type may be omitted
types = jQuery.trim( hoverHack( types || "" ) ).split(" ");
for ( t = 0; t < types.length; t++ ) {
tns = rtypenamespace.exec( types[t] ) || [];
type = origType = tns[1];
namespaces = tns[2];
// Unbind all events (on this namespace, if provided) for the element
if ( !type ) {
for ( type in events ) {
jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
}
continue;
}
special = jQuery.event.special[ type ] || {};
type = ( selector? special.delegateType : special.bindType ) || type;
eventType = events[ type ] || [];
origCount = eventType.length;
namespaces = namespaces ? new RegExp("(^|\\.)" + namespaces.split(".").sort().join("\\.(?:.*\\.|)") + "(\\.|$)") : null;
// Remove matching events
for ( j = 0; j < eventType.length; j++ ) {
handleObj = eventType[ j ];
if ( ( mappedTypes || origType === handleObj.origType ) &&
( !handler || handler.guid === handleObj.guid ) &&
( !namespaces || namespaces.test( handleObj.namespace ) ) &&
( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) {
eventType.splice( j--, 1 );
if ( handleObj.selector ) {
eventType.delegateCount--;
}
if ( special.remove ) {
special.remove.call( elem, handleObj );
}
}
}
// Remove generic event handler if we removed something and no more handlers exist
// (avoids potential for endless recursion during removal of special event handlers)
if ( eventType.length === 0 && origCount !== eventType.length ) {
if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) {
jQuery.removeEvent( elem, type, elemData.handle );
}
delete events[ type ];
}
}
// Remove the expando if it's no longer used
if ( jQuery.isEmptyObject( events ) ) {
delete elemData.handle;
// removeData also checks for emptiness and clears the expando if empty
// so use it instead of delete
jQuery.removeData( elem, "events", true );
}
},
// Events that are safe to short-circuit if no handlers are attached.
// Native DOM events should not be added, they may have inline handlers.
customEvent: {
"getData": true,
"setData": true,
"changeData": true
},
trigger: function( event, data, elem, onlyHandlers ) {
// Don't do events on text and comment nodes
if ( elem && (elem.nodeType === 3 || elem.nodeType === 8) ) {
return;
}
// Event object or event type
var cache, exclusive, i, cur, old, ontype, special, handle, eventPath, bubbleType,
type = event.type || event,
namespaces = [];
// focus/blur morphs to focusin/out; ensure we're not firing them right now
if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
return;
}
if ( type.indexOf( "!" ) >= 0 ) {
// Exclusive events trigger only for the exact event (no namespaces)
type = type.slice(0, -1);
exclusive = true;
}
if ( type.indexOf( "." ) >= 0 ) {
// Namespaced trigger; create a regexp to match event type in handle()
namespaces = type.split(".");
type = namespaces.shift();
namespaces.sort();
}
if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) {
// No jQuery handlers for this event type, and it can't have inline handlers
return;
}
// Caller can pass in an Event, Object, or just an event type string
event = typeof event === "object" ?
// jQuery.Event object
event[ jQuery.expando ] ? event :
// Object literal
new jQuery.Event( type, event ) :
// Just the event type (string)
new jQuery.Event( type );
event.type = type;
event.isTrigger = true;
event.exclusive = exclusive;
event.namespace = namespaces.join( "." );
event.namespace_re = event.namespace? new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)") : null;
ontype = type.indexOf( ":" ) < 0 ? "on" + type : "";
// Handle a global trigger
if ( !elem ) {
// TODO: Stop taunting the data cache; remove global events and always attach to document
cache = jQuery.cache;
for ( i in cache ) {
if ( cache[ i ].events && cache[ i ].events[ type ] ) {
jQuery.event.trigger( event, data, cache[ i ].handle.elem, true );
}
}
return;
}
// Clean up the event in case it is being reused
event.result = undefined;
if ( !event.target ) {
event.target = elem;
}
// Clone any incoming data and prepend the event, creating the handler arg list
data = data != null ? jQuery.makeArray( data ) : [];
data.unshift( event );
// Allow special events to draw outside the lines
special = jQuery.event.special[ type ] || {};
if ( special.trigger && special.trigger.apply( elem, data ) === false ) {
return;
}
// Determine event propagation path in advance, per W3C events spec (#9951)
// Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
eventPath = [[ elem, special.bindType || type ]];
if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) {
bubbleType = special.delegateType || type;
cur = rfocusMorph.test( bubbleType + type ) ? elem : elem.parentNode;
for ( old = elem; cur; cur = cur.parentNode ) {
eventPath.push([ cur, bubbleType ]);
old = cur;
}
// Only add window if we got to document (e.g., not plain obj or detached DOM)
if ( old === (elem.ownerDocument || document) ) {
eventPath.push([ old.defaultView || old.parentWindow || window, bubbleType ]);
}
}
// Fire handlers on the event path
for ( i = 0; i < eventPath.length && !event.isPropagationStopped(); i++ ) {
cur = eventPath[i][0];
event.type = eventPath[i][1];
handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" );
if ( handle ) {
handle.apply( cur, data );
}
// Note that this is a bare JS function and not a jQuery handler
handle = ontype && cur[ ontype ];
if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) {
event.preventDefault();
}
}
event.type = type;
// If nobody prevented the default action, do it now
if ( !onlyHandlers && !event.isDefaultPrevented() ) {
if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) &&
!(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) {
// Call a native DOM method on the target with the same name name as the event.
// Can't use an .isFunction() check here because IE6/7 fails that test.
// Don't do default actions on window, that's where global variables be (#6170)
// IE<9 dies on focus/blur to hidden element (#1486)
if ( ontype && elem[ type ] && ((type !== "focus" && type !== "blur") || event.target.offsetWidth !== 0) && !jQuery.isWindow( elem ) ) {
// Don't re-trigger an onFOO event when we call its FOO() method
old = elem[ ontype ];
if ( old ) {
elem[ ontype ] = null;
}
// Prevent re-triggering of the same event, since we already bubbled it above
jQuery.event.triggered = type;
elem[ type ]();
jQuery.event.triggered = undefined;
if ( old ) {
elem[ ontype ] = old;
}
}
}
}
return event.result;
},
dispatch: function( event ) {
// Make a writable jQuery.Event from the native event object
event = jQuery.event.fix( event || window.event );
var i, j, cur, ret, selMatch, matched, matches, handleObj, sel, related,
handlers = ( (jQuery._data( this, "events" ) || {} )[ event.type ] || []),
delegateCount = handlers.delegateCount,
args = core_slice.call( arguments ),
run_all = !event.exclusive && !event.namespace,
special = jQuery.event.special[ event.type ] || {},
handlerQueue = [];
// Use the fix-ed jQuery.Event rather than the (read-only) native event
args[0] = event;
event.delegateTarget = this;
// Call the preDispatch hook for the mapped type, and let it bail if desired
if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) {
return;
}
// Determine handlers that should run if there are delegated events
// Avoid non-left-click bubbling in Firefox (#3861)
if ( delegateCount && !(event.button && event.type === "click") ) {
for ( cur = event.target; cur != this; cur = cur.parentNode || this ) {
// Don't process clicks (ONLY) on disabled elements (#6911, #8165, #11382, #11764)
if ( cur.disabled !== true || event.type !== "click" ) {
selMatch = {};
matches = [];
for ( i = 0; i < delegateCount; i++ ) {
handleObj = handlers[ i ];
sel = handleObj.selector;
if ( selMatch[ sel ] === undefined ) {
selMatch[ sel ] = handleObj.needsContext ?
jQuery( sel, this ).index( cur ) >= 0 :
jQuery.find( sel, this, null, [ cur ] ).length;
}
if ( selMatch[ sel ] ) {
matches.push( handleObj );
}
}
if ( matches.length ) {
handlerQueue.push({ elem: cur, matches: matches });
}
}
}
}
// Add the remaining (directly-bound) handlers
if ( handlers.length > delegateCount ) {
handlerQueue.push({ elem: this, matches: handlers.slice( delegateCount ) });
}
// Run delegates first; they may want to stop propagation beneath us
for ( i = 0; i < handlerQueue.length && !event.isPropagationStopped(); i++ ) {
matched = handlerQueue[ i ];
event.currentTarget = matched.elem;
for ( j = 0; j < matched.matches.length && !event.isImmediatePropagationStopped(); j++ ) {
handleObj = matched.matches[ j ];
// Triggered event must either 1) be non-exclusive and have no namespace, or
// 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace).
if ( run_all || (!event.namespace && !handleObj.namespace) || event.namespace_re && event.namespace_re.test( handleObj.namespace ) ) {
event.data = handleObj.data;
event.handleObj = handleObj;
ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler )
.apply( matched.elem, args );
if ( ret !== undefined ) {
event.result = ret;
if ( ret === false ) {
event.preventDefault();
event.stopPropagation();
}
}
}
}
}
// Call the postDispatch hook for the mapped type
if ( special.postDispatch ) {
special.postDispatch.call( this, event );
}
return event.result;
},
// Includes some event props shared by KeyEvent and MouseEvent
// *** attrChange attrName relatedNode srcElement are not normalized, non-W3C, deprecated, will be removed in 1.8 ***
props: "attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),
fixHooks: {},
keyHooks: {
props: "char charCode key keyCode".split(" "),
filter: function( event, original ) {
// Add which for key events
if ( event.which == null ) {
event.which = original.charCode != null ? original.charCode : original.keyCode;
}
return event;
}
},
mouseHooks: {
props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
filter: function( event, original ) {
var eventDoc, doc, body,
button = original.button,
fromElement = original.fromElement;
// Calculate pageX/Y if missing and clientX/Y available
if ( event.pageX == null && original.clientX != null ) {
eventDoc = event.target.ownerDocument || document;
doc = eventDoc.documentElement;
body = eventDoc.body;
event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 );
event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 );
}
// Add relatedTarget, if necessary
if ( !event.relatedTarget && fromElement ) {
event.relatedTarget = fromElement === event.target ? original.toElement : fromElement;
}
// Add which for click: 1 === left; 2 === middle; 3 === right
// Note: button is not normalized, so don't use it
if ( !event.which && button !== undefined ) {
event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
}
return event;
}
},
fix: function( event ) {
if ( event[ jQuery.expando ] ) {
return event;
}
// Create a writable copy of the event object and normalize some properties
var i, prop,
originalEvent = event,
fixHook = jQuery.event.fixHooks[ event.type ] || {},
copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props;
event = jQuery.Event( originalEvent );
for ( i = copy.length; i; ) {
prop = copy[ --i ];
event[ prop ] = originalEvent[ prop ];
}
// Fix target property, if necessary (#1925, IE 6/7/8 & Safari2)
if ( !event.target ) {
event.target = originalEvent.srcElement || document;
}
// Target should not be a text node (#504, Safari)
if ( event.target.nodeType === 3 ) {
event.target = event.target.parentNode;
}
// For mouse/key events, metaKey==false if it's undefined (#3368, #11328; IE6/7/8)
event.metaKey = !!event.metaKey;
return fixHook.filter? fixHook.filter( event, originalEvent ) : event;
},
special: {
load: {
// Prevent triggered image.load events from bubbling to window.load
noBubble: true
},
focus: {
delegateType: "focusin"
},
blur: {
delegateType: "focusout"
},
beforeunload: {
setup: function( data, namespaces, eventHandle ) {
// We only want to do this special case on windows
if ( jQuery.isWindow( this ) ) {
this.onbeforeunload = eventHandle;
}
},
teardown: function( namespaces, eventHandle ) {
if ( this.onbeforeunload === eventHandle ) {
this.onbeforeunload = null;
}
}
}
},
simulate: function( type, elem, event, bubble ) {
// Piggyback on a donor event to simulate a different one.
// Fake originalEvent to avoid donor's stopPropagation, but if the
// simulated event prevents default then we do the same on the donor.
var e = jQuery.extend(
new jQuery.Event(),
event,
{ type: type,
isSimulated: true,
originalEvent: {}
}
);
if ( bubble ) {
jQuery.event.trigger( e, null, elem );
} else {
jQuery.event.dispatch.call( elem, e );
}
if ( e.isDefaultPrevented() ) {
event.preventDefault();
}
}
};
// Some plugins are using, but it's undocumented/deprecated and will be removed.
// The 1.7 special event interface should provide all the hooks needed now.
jQuery.event.handle = jQuery.event.dispatch;
jQuery.removeEvent = document.removeEventListener ?
function( elem, type, handle ) {
if ( elem.removeEventListener ) {
elem.removeEventListener( type, handle, false );
}
} :
function( elem, type, handle ) {
var name = "on" + type;
if ( elem.detachEvent ) {
// #8545, #7054, preventing memory leaks for custom events in IE6-8
// detachEvent needed property on element, by name of that event, to properly expose it to GC
if ( typeof elem[ name ] === "undefined" ) {
elem[ name ] = null;
}
elem.detachEvent( name, handle );
}
};
jQuery.Event = function( src, props ) {
// Allow instantiation without the 'new' keyword
if ( !(this instanceof jQuery.Event) ) {
return new jQuery.Event( src, props );
}
// Event object
if ( src && src.type ) {
this.originalEvent = src;
this.type = src.type;
// Events bubbling up the document may have been marked as prevented
// by a handler lower down the tree; reflect the correct value.
this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false ||
src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse;
// Event type
} else {
this.type = src;
}
// Put explicitly provided properties onto the event object
if ( props ) {
jQuery.extend( this, props );
}
// Create a timestamp if incoming event doesn't have one
this.timeStamp = src && src.timeStamp || jQuery.now();
// Mark it as fixed
this[ jQuery.expando ] = true;
};
function returnFalse() {
return false;
}
function returnTrue() {
return true;
}
// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
preventDefault: function() {
this.isDefaultPrevented = returnTrue;
var e = this.originalEvent;
if ( !e ) {
return;
}
// if preventDefault exists run it on the original event
if ( e.preventDefault ) {
e.preventDefault();
// otherwise set the returnValue property of the original event to false (IE)
} else {
e.returnValue = false;
}
},
stopPropagation: function() {
this.isPropagationStopped = returnTrue;
var e = this.originalEvent;
if ( !e ) {
return;
}
// if stopPropagation exists run it on the original event
if ( e.stopPropagation ) {
e.stopPropagation();
}
// otherwise set the cancelBubble property of the original event to true (IE)
e.cancelBubble = true;
},
stopImmediatePropagation: function() {
this.isImmediatePropagationStopped = returnTrue;
this.stopPropagation();
},
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse
};
// Create mouseenter/leave events using mouseover/out and event-time checks
jQuery.each({
mouseenter: "mouseover",
mouseleave: "mouseout"
}, function( orig, fix ) {
jQuery.event.special[ orig ] = {
delegateType: fix,
bindType: fix,
handle: function( event ) {
var ret,
target = this,
related = event.relatedTarget,
handleObj = event.handleObj,
selector = handleObj.selector;
// For mousenter/leave call the handler if related is outside the target.
// NB: No relatedTarget if the mouse left/entered the browser window
if ( !related || (related !== target && !jQuery.contains( target, related )) ) {
event.type = handleObj.origType;
ret = handleObj.handler.apply( this, arguments );
event.type = fix;
}
return ret;
}
};
});
// IE submit delegation
if ( !jQuery.support.submitBubbles ) {
jQuery.event.special.submit = {
setup: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Lazy-add a submit handler when a descendant form may potentially be submitted
jQuery.event.add( this, "click._submit keypress._submit", function( e ) {
// Node name check avoids a VML-related crash in IE (#9807)
var elem = e.target,
form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined;
if ( form && !jQuery._data( form, "_submit_attached" ) ) {
jQuery.event.add( form, "submit._submit", function( event ) {
event._submit_bubble = true;
});
jQuery._data( form, "_submit_attached", true );
}
});
// return undefined since we don't need an event listener
},
postDispatch: function( event ) {
// If form was submitted by the user, bubble the event up the tree
if ( event._submit_bubble ) {
delete event._submit_bubble;
if ( this.parentNode && !event.isTrigger ) {
jQuery.event.simulate( "submit", this.parentNode, event, true );
}
}
},
teardown: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Remove delegated handlers; cleanData eventually reaps submit handlers attached above
jQuery.event.remove( this, "._submit" );
}
};
}
// IE change delegation and checkbox/radio fix
if ( !jQuery.support.changeBubbles ) {
jQuery.event.special.change = {
setup: function() {
if ( rformElems.test( this.nodeName ) ) {
// IE doesn't fire change on a check/radio until blur; trigger it on click
// after a propertychange. Eat the blur-change in special.change.handle.
// This still fires onchange a second time for check/radio after blur.
if ( this.type === "checkbox" || this.type === "radio" ) {
jQuery.event.add( this, "propertychange._change", function( event ) {
if ( event.originalEvent.propertyName === "checked" ) {
this._just_changed = true;
}
});
jQuery.event.add( this, "click._change", function( event ) {
if ( this._just_changed && !event.isTrigger ) {
this._just_changed = false;
}
// Allow triggered, simulated change events (#11500)
jQuery.event.simulate( "change", this, event, true );
});
}
return false;
}
// Delegated event; lazy-add a change handler on descendant inputs
jQuery.event.add( this, "beforeactivate._change", function( e ) {
var elem = e.target;
if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "_change_attached" ) ) {
jQuery.event.add( elem, "change._change", function( event ) {
if ( this.parentNode && !event.isSimulated && !event.isTrigger ) {
jQuery.event.simulate( "change", this.parentNode, event, true );
}
});
jQuery._data( elem, "_change_attached", true );
}
});
},
handle: function( event ) {
var elem = event.target;
// Swallow native change events from checkbox/radio, we already triggered them above
if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) {
return event.handleObj.handler.apply( this, arguments );
}
},
teardown: function() {
jQuery.event.remove( this, "._change" );
return !rformElems.test( this.nodeName );
}
};
}
// Create "bubbling" focus and blur events
if ( !jQuery.support.focusinBubbles ) {
jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
// Attach a single capturing handler while someone wants focusin/focusout
var attaches = 0,
handler = function( event ) {
jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true );
};
jQuery.event.special[ fix ] = {
setup: function() {
if ( attaches++ === 0 ) {
document.addEventListener( orig, handler, true );
}
},
teardown: function() {
if ( --attaches === 0 ) {
document.removeEventListener( orig, handler, true );
}
}
};
});
}
jQuery.fn.extend({
on: function( types, selector, data, fn, /*INTERNAL*/ one ) {
var origFn, type;
// Types can be a map of types/handlers
if ( typeof types === "object" ) {
// ( types-Object, selector, data )
if ( typeof selector !== "string" ) { // && selector != null
// ( types-Object, data )
data = data || selector;
selector = undefined;
}
for ( type in types ) {
this.on( type, selector, data, types[ type ], one );
}
return this;
}
if ( data == null && fn == null ) {
// ( types, fn )
fn = selector;
data = selector = undefined;
} else if ( fn == null ) {
if ( typeof selector === "string" ) {
// ( types, selector, fn )
fn = data;
data = undefined;
} else {
// ( types, data, fn )
fn = data;
data = selector;
selector = undefined;
}
}
if ( fn === false ) {
fn = returnFalse;
} else if ( !fn ) {
return this;
}
if ( one === 1 ) {
origFn = fn;
fn = function( event ) {
// Can use an empty set, since event contains the info
jQuery().off( event );
return origFn.apply( this, arguments );
};
// Use same guid so caller can remove using origFn
fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
}
return this.each( function() {
jQuery.event.add( this, types, fn, data, selector );
});
},
one: function( types, selector, data, fn ) {
return this.on( types, selector, data, fn, 1 );
},
off: function( types, selector, fn ) {
var handleObj, type;
if ( types && types.preventDefault && types.handleObj ) {
// ( event ) dispatched jQuery.Event
handleObj = types.handleObj;
jQuery( types.delegateTarget ).off(
handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType,
handleObj.selector,
handleObj.handler
);
return this;
}
if ( typeof types === "object" ) {
// ( types-object [, selector] )
for ( type in types ) {
this.off( type, selector, types[ type ] );
}
return this;
}
if ( selector === false || typeof selector === "function" ) {
// ( types [, fn] )
fn = selector;
selector = undefined;
}
if ( fn === false ) {
fn = returnFalse;
}
return this.each(function() {
jQuery.event.remove( this, types, fn, selector );
});
},
bind: function( types, data, fn ) {
return this.on( types, null, data, fn );
},
unbind: function( types, fn ) {
return this.off( types, null, fn );
},
live: function( types, data, fn ) {
jQuery( this.context ).on( types, this.selector, data, fn );
return this;
},
die: function( types, fn ) {
jQuery( this.context ).off( types, this.selector || "**", fn );
return this;
},
delegate: function( selector, types, data, fn ) {
return this.on( types, selector, data, fn );
},
undelegate: function( selector, types, fn ) {
// ( namespace ) or ( selector, types [, fn] )
return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn );
},
trigger: function( type, data ) {
return this.each(function() {
jQuery.event.trigger( type, data, this );
});
},
triggerHandler: function( type, data ) {
if ( this[0] ) {
return jQuery.event.trigger( type, data, this[0], true );
}
},
toggle: function( fn ) {
// Save reference to arguments for access in closure
var args = arguments,
guid = fn.guid || jQuery.guid++,
i = 0,
toggler = function( event ) {
// Figure out which function to execute
var lastToggle = ( jQuery._data( this, "lastToggle" + fn.guid ) || 0 ) % i;
jQuery._data( this, "lastToggle" + fn.guid, lastToggle + 1 );
// Make sure that clicks stop
event.preventDefault();
// and execute the function
return args[ lastToggle ].apply( this, arguments ) || false;
};
// link all the functions, so any of them can unbind this click handler
toggler.guid = guid;
while ( i < args.length ) {
args[ i++ ].guid = guid;
}
return this.click( toggler );
},
hover: function( fnOver, fnOut ) {
return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
}
});
jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
"change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) {
// Handle event binding
jQuery.fn[ name ] = function( data, fn ) {
if ( fn == null ) {
fn = data;
data = null;
}
return arguments.length > 0 ?
this.on( name, null, data, fn ) :
this.trigger( name );
};
if ( rkeyEvent.test( name ) ) {
jQuery.event.fixHooks[ name ] = jQuery.event.keyHooks;
}
if ( rmouseEvent.test( name ) ) {
jQuery.event.fixHooks[ name ] = jQuery.event.mouseHooks;
}
});
/*!
* Sizzle CSS Selector Engine
* Copyright 2012 jQuery Foundation and other contributors
* Released under the MIT license
* http://sizzlejs.com/
*/
(function( window, undefined ) {
var cachedruns,
assertGetIdNotName,
Expr,
getText,
isXML,
contains,
compile,
sortOrder,
hasDuplicate,
outermostContext,
baseHasDuplicate = true,
strundefined = "undefined",
expando = ( "sizcache" + Math.random() ).replace( ".", "" ),
Token = String,
document = window.document,
docElem = document.documentElement,
dirruns = 0,
done = 0,
pop = [].pop,
push = [].push,
slice = [].slice,
// Use a stripped-down indexOf if a native one is unavailable
indexOf = [].indexOf || function( elem ) {
var i = 0,
len = this.length;
for ( ; i < len; i++ ) {
if ( this[i] === elem ) {
return i;
}
}
return -1;
},
// Augment a function for special use by Sizzle
markFunction = function( fn, value ) {
fn[ expando ] = value == null || value;
return fn;
},
createCache = function() {
var cache = {},
keys = [];
return markFunction(function( key, value ) {
// Only keep the most recent entries
if ( keys.push( key ) > Expr.cacheLength ) {
delete cache[ keys.shift() ];
}
// Retrieve with (key + " ") to avoid collision with native Object.prototype properties (see Issue #157)
return (cache[ key + " " ] = value);
}, cache );
},
classCache = createCache(),
tokenCache = createCache(),
compilerCache = createCache(),
// Regex
// Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace
whitespace = "[\\x20\\t\\r\\n\\f]",
// http://www.w3.org/TR/css3-syntax/#characters
characterEncoding = "(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",
// Loosely modeled on CSS identifier characters
// An unquoted value should be a CSS identifier (http://www.w3.org/TR/css3-selectors/#attribute-selectors)
// Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
identifier = characterEncoding.replace( "w", "w#" ),
// Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors
operators = "([*^$|!~]?=)",
attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace +
"*(?:" + operators + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]",
// Prefer arguments not in parens/brackets,
// then attribute selectors and non-pseudos (denoted by :),
// then anything else
// These preferences are here to reduce the number of selectors
// needing tokenize in the PSEUDO preFilter
pseudos = ":(" + characterEncoding + ")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:" + attributes + ")|[^:]|\\\\.)*|.*))\\)|)",
// For matchExpr.POS and matchExpr.needsContext
pos = ":(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace +
"*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)",
// Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ),
rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
rcombinators = new RegExp( "^" + whitespace + "*([\\x20\\t\\r\\n\\f>+~])" + whitespace + "*" ),
rpseudo = new RegExp( pseudos ),
// Easily-parseable/retrievable ID or TAG or CLASS selectors
rquickExpr = /^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,
rnot = /^:not/,
rsibling = /[\x20\t\r\n\f]*[+~]/,
rendsWithNot = /:not\($/,
rheader = /h\d/i,
rinputs = /input|select|textarea|button/i,
rbackslash = /\\(?!\\)/g,
matchExpr = {
"ID": new RegExp( "^#(" + characterEncoding + ")" ),
"CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ),
"NAME": new RegExp( "^\\[name=['\"]?(" + characterEncoding + ")['\"]?\\]" ),
"TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ),
"ATTR": new RegExp( "^" + attributes ),
"PSEUDO": new RegExp( "^" + pseudos ),
"POS": new RegExp( pos, "i" ),
"CHILD": new RegExp( "^:(only|nth|first|last)-child(?:\\(" + whitespace +
"*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace +
"*(\\d+)|))" + whitespace + "*\\)|)", "i" ),
// For use in libraries implementing .is()
"needsContext": new RegExp( "^" + whitespace + "*[>+~]|" + pos, "i" )
},
// Support
// Used for testing something on an element
assert = function( fn ) {
var div = document.createElement("div");
try {
return fn( div );
} catch (e) {
return false;
} finally {
// release memory in IE
div = null;
}
},
// Check if getElementsByTagName("*") returns only elements
assertTagNameNoComments = assert(function( div ) {
div.appendChild( document.createComment("") );
return !div.getElementsByTagName("*").length;
}),
// Check if getAttribute returns normalized href attributes
assertHrefNotNormalized = assert(function( div ) {
div.innerHTML = "<a href='#'></a>";
return div.firstChild && typeof div.firstChild.getAttribute !== strundefined &&
div.firstChild.getAttribute("href") === "#";
}),
// Check if attributes should be retrieved by attribute nodes
assertAttributes = assert(function( div ) {
div.innerHTML = "<select></select>";
var type = typeof div.lastChild.getAttribute("multiple");
// IE8 returns a string for some attributes even when not present
return type !== "boolean" && type !== "string";
}),
// Check if getElementsByClassName can be trusted
assertUsableClassName = assert(function( div ) {
// Opera can't find a second classname (in 9.6)
div.innerHTML = "<div class='hidden e'></div><div class='hidden'></div>";
if ( !div.getElementsByClassName || !div.getElementsByClassName("e").length ) {
return false;
}
// Safari 3.2 caches class attributes and doesn't catch changes
div.lastChild.className = "e";
return div.getElementsByClassName("e").length === 2;
}),
// Check if getElementById returns elements by name
// Check if getElementsByName privileges form controls or returns elements by ID
assertUsableName = assert(function( div ) {
// Inject content
div.id = expando + 0;
div.innerHTML = "<a name='" + expando + "'></a><div name='" + expando + "'></div>";
docElem.insertBefore( div, docElem.firstChild );
// Test
var pass = document.getElementsByName &&
// buggy browsers will return fewer than the correct 2
document.getElementsByName( expando ).length === 2 +
// buggy browsers will return more than the correct 0
document.getElementsByName( expando + 0 ).length;
assertGetIdNotName = !document.getElementById( expando );
// Cleanup
docElem.removeChild( div );
return pass;
});
// If slice is not available, provide a backup
try {
slice.call( docElem.childNodes, 0 )[0].nodeType;
} catch ( e ) {
slice = function( i ) {
var elem,
results = [];
for ( ; (elem = this[i]); i++ ) {
results.push( elem );
}
return results;
};
}
function Sizzle( selector, context, results, seed ) {
results = results || [];
context = context || document;
var match, elem, xml, m,
nodeType = context.nodeType;
if ( !selector || typeof selector !== "string" ) {
return results;
}
if ( nodeType !== 1 && nodeType !== 9 ) {
return [];
}
xml = isXML( context );
if ( !xml && !seed ) {
if ( (match = rquickExpr.exec( selector )) ) {
// Speed-up: Sizzle("#ID")
if ( (m = match[1]) ) {
if ( nodeType === 9 ) {
elem = context.getElementById( m );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE, Opera, and Webkit return items
// by name instead of ID
if ( elem.id === m ) {
results.push( elem );
return results;
}
} else {
return results;
}
} else {
// Context is not a document
if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) &&
contains( context, elem ) && elem.id === m ) {
results.push( elem );
return results;
}
}
// Speed-up: Sizzle("TAG")
} else if ( match[2] ) {
push.apply( results, slice.call(context.getElementsByTagName( selector ), 0) );
return results;
// Speed-up: Sizzle(".CLASS")
} else if ( (m = match[3]) && assertUsableClassName && context.getElementsByClassName ) {
push.apply( results, slice.call(context.getElementsByClassName( m ), 0) );
return results;
}
}
}
// All others
return select( selector.replace( rtrim, "$1" ), context, results, seed, xml );
}
Sizzle.matches = function( expr, elements ) {
return Sizzle( expr, null, null, elements );
};
Sizzle.matchesSelector = function( elem, expr ) {
return Sizzle( expr, null, null, [ elem ] ).length > 0;
};
// Returns a function to use in pseudos for input types
function createInputPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === type;
};
}
// Returns a function to use in pseudos for buttons
function createButtonPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && elem.type === type;
};
}
// Returns a function to use in pseudos for positionals
function createPositionalPseudo( fn ) {
return markFunction(function( argument ) {
argument = +argument;
return markFunction(function( seed, matches ) {
var j,
matchIndexes = fn( [], seed.length, argument ),
i = matchIndexes.length;
// Match elements found at the specified indexes
while ( i-- ) {
if ( seed[ (j = matchIndexes[i]) ] ) {
seed[j] = !(matches[j] = seed[j]);
}
}
});
});
}
/**
* Utility function for retrieving the text value of an array of DOM nodes
* @param {Array|Element} elem
*/
getText = Sizzle.getText = function( elem ) {
var node,
ret = "",
i = 0,
nodeType = elem.nodeType;
if ( nodeType ) {
if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
// Use textContent for elements
// innerText usage removed for consistency of new lines (see #11153)
if ( typeof elem.textContent === "string" ) {
return elem.textContent;
} else {
// Traverse its children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
ret += getText( elem );
}
}
} else if ( nodeType === 3 || nodeType === 4 ) {
return elem.nodeValue;
}
// Do not include comment or processing instruction nodes
} else {
// If no nodeType, this is expected to be an array
for ( ; (node = elem[i]); i++ ) {
// Do not traverse comment nodes
ret += getText( node );
}
}
return ret;
};
isXML = Sizzle.isXML = function( elem ) {
// documentElement is verified for cases where it doesn't yet exist
// (such as loading iframes in IE - #4833)
var documentElement = elem && (elem.ownerDocument || elem).documentElement;
return documentElement ? documentElement.nodeName !== "HTML" : false;
};
// Element contains another
contains = Sizzle.contains = docElem.contains ?
function( a, b ) {
var adown = a.nodeType === 9 ? a.documentElement : a,
bup = b && b.parentNode;
return a === bup || !!( bup && bup.nodeType === 1 && adown.contains && adown.contains(bup) );
} :
docElem.compareDocumentPosition ?
function( a, b ) {
return b && !!( a.compareDocumentPosition( b ) & 16 );
} :
function( a, b ) {
while ( (b = b.parentNode) ) {
if ( b === a ) {
return true;
}
}
return false;
};
Sizzle.attr = function( elem, name ) {
var val,
xml = isXML( elem );
if ( !xml ) {
name = name.toLowerCase();
}
if ( (val = Expr.attrHandle[ name ]) ) {
return val( elem );
}
if ( xml || assertAttributes ) {
return elem.getAttribute( name );
}
val = elem.getAttributeNode( name );
return val ?
typeof elem[ name ] === "boolean" ?
elem[ name ] ? name : null :
val.specified ? val.value : null :
null;
};
Expr = Sizzle.selectors = {
// Can be adjusted by the user
cacheLength: 50,
createPseudo: markFunction,
match: matchExpr,
// IE6/7 return a modified href
attrHandle: assertHrefNotNormalized ?
{} :
{
"href": function( elem ) {
return elem.getAttribute( "href", 2 );
},
"type": function( elem ) {
return elem.getAttribute("type");
}
},
find: {
"ID": assertGetIdNotName ?
function( id, context, xml ) {
if ( typeof context.getElementById !== strundefined && !xml ) {
var m = context.getElementById( id );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
return m && m.parentNode ? [m] : [];
}
} :
function( id, context, xml ) {
if ( typeof context.getElementById !== strundefined && !xml ) {
var m = context.getElementById( id );
return m ?
m.id === id || typeof m.getAttributeNode !== strundefined && m.getAttributeNode("id").value === id ?
[m] :
undefined :
[];
}
},
"TAG": assertTagNameNoComments ?
function( tag, context ) {
if ( typeof context.getElementsByTagName !== strundefined ) {
return context.getElementsByTagName( tag );
}
} :
function( tag, context ) {
var results = context.getElementsByTagName( tag );
// Filter out possible comments
if ( tag === "*" ) {
var elem,
tmp = [],
i = 0;
for ( ; (elem = results[i]); i++ ) {
if ( elem.nodeType === 1 ) {
tmp.push( elem );
}
}
return tmp;
}
return results;
},
"NAME": assertUsableName && function( tag, context ) {
if ( typeof context.getElementsByName !== strundefined ) {
return context.getElementsByName( name );
}
},
"CLASS": assertUsableClassName && function( className, context, xml ) {
if ( typeof context.getElementsByClassName !== strundefined && !xml ) {
return context.getElementsByClassName( className );
}
}
},
relative: {
">": { dir: "parentNode", first: true },
" ": { dir: "parentNode" },
"+": { dir: "previousSibling", first: true },
"~": { dir: "previousSibling" }
},
preFilter: {
"ATTR": function( match ) {
match[1] = match[1].replace( rbackslash, "" );
// Move the given value to match[3] whether quoted or unquoted
match[3] = ( match[4] || match[5] || "" ).replace( rbackslash, "" );
if ( match[2] === "~=" ) {
match[3] = " " + match[3] + " ";
}
return match.slice( 0, 4 );
},
"CHILD": function( match ) {
/* matches from matchExpr["CHILD"]
1 type (only|nth|...)
2 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
3 xn-component of xn+y argument ([+-]?\d*n|)
4 sign of xn-component
5 x of xn-component
6 sign of y-component
7 y of y-component
*/
match[1] = match[1].toLowerCase();
if ( match[1] === "nth" ) {
// nth-child requires argument
if ( !match[2] ) {
Sizzle.error( match[0] );
}
// numeric x and y parameters for Expr.filter.CHILD
// remember that false/true cast respectively to 0/1
match[3] = +( match[3] ? match[4] + (match[5] || 1) : 2 * ( match[2] === "even" || match[2] === "odd" ) );
match[4] = +( ( match[6] + match[7] ) || match[2] === "odd" );
// other types prohibit arguments
} else if ( match[2] ) {
Sizzle.error( match[0] );
}
return match;
},
"PSEUDO": function( match ) {
var unquoted, excess;
if ( matchExpr["CHILD"].test( match[0] ) ) {
return null;
}
if ( match[3] ) {
match[2] = match[3];
} else if ( (unquoted = match[4]) ) {
// Only check arguments that contain a pseudo
if ( rpseudo.test(unquoted) &&
// Get excess from tokenize (recursively)
(excess = tokenize( unquoted, true )) &&
// advance to the next closing parenthesis
(excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) {
// excess is a negative index
unquoted = unquoted.slice( 0, excess );
match[0] = match[0].slice( 0, excess );
}
match[2] = unquoted;
}
// Return only captures needed by the pseudo filter method (type and argument)
return match.slice( 0, 3 );
}
},
filter: {
"ID": assertGetIdNotName ?
function( id ) {
id = id.replace( rbackslash, "" );
return function( elem ) {
return elem.getAttribute("id") === id;
};
} :
function( id ) {
id = id.replace( rbackslash, "" );
return function( elem ) {
var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id");
return node && node.value === id;
};
},
"TAG": function( nodeName ) {
if ( nodeName === "*" ) {
return function() { return true; };
}
nodeName = nodeName.replace( rbackslash, "" ).toLowerCase();
return function( elem ) {
return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
};
},
"CLASS": function( className ) {
var pattern = classCache[ expando ][ className + " " ];
return pattern ||
(pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) &&
classCache( className, function( elem ) {
return pattern.test( elem.className || (typeof elem.getAttribute !== strundefined && elem.getAttribute("class")) || "" );
});
},
"ATTR": function( name, operator, check ) {
return function( elem, context ) {
var result = Sizzle.attr( elem, name );
if ( result == null ) {
return operator === "!=";
}
if ( !operator ) {
return true;
}
result += "";
return operator === "=" ? result === check :
operator === "!=" ? result !== check :
operator === "^=" ? check && result.indexOf( check ) === 0 :
operator === "*=" ? check && result.indexOf( check ) > -1 :
operator === "$=" ? check && result.substr( result.length - check.length ) === check :
operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 :
operator === "|=" ? result === check || result.substr( 0, check.length + 1 ) === check + "-" :
false;
};
},
"CHILD": function( type, argument, first, last ) {
if ( type === "nth" ) {
return function( elem ) {
var node, diff,
parent = elem.parentNode;
if ( first === 1 && last === 0 ) {
return true;
}
if ( parent ) {
diff = 0;
for ( node = parent.firstChild; node; node = node.nextSibling ) {
if ( node.nodeType === 1 ) {
diff++;
if ( elem === node ) {
break;
}
}
}
}
// Incorporate the offset (or cast to NaN), then check against cycle size
diff -= last;
return diff === first || ( diff % first === 0 && diff / first >= 0 );
};
}
return function( elem ) {
var node = elem;
switch ( type ) {
case "only":
case "first":
while ( (node = node.previousSibling) ) {
if ( node.nodeType === 1 ) {
return false;
}
}
if ( type === "first" ) {
return true;
}
node = elem;
/* falls through */
case "last":
while ( (node = node.nextSibling) ) {
if ( node.nodeType === 1 ) {
return false;
}
}
return true;
}
};
},
"PSEUDO": function( pseudo, argument ) {
// pseudo-class names are case-insensitive
// http://www.w3.org/TR/selectors/#pseudo-classes
// Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
// Remember that setFilters inherits from pseudos
var args,
fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] ||
Sizzle.error( "unsupported pseudo: " + pseudo );
// The user may use createPseudo to indicate that
// arguments are needed to create the filter function
// just as Sizzle does
if ( fn[ expando ] ) {
return fn( argument );
}
// But maintain support for old signatures
if ( fn.length > 1 ) {
args = [ pseudo, pseudo, "", argument ];
return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ?
markFunction(function( seed, matches ) {
var idx,
matched = fn( seed, argument ),
i = matched.length;
while ( i-- ) {
idx = indexOf.call( seed, matched[i] );
seed[ idx ] = !( matches[ idx ] = matched[i] );
}
}) :
function( elem ) {
return fn( elem, 0, args );
};
}
return fn;
}
},
pseudos: {
"not": markFunction(function( selector ) {
// Trim the selector passed to compile
// to avoid treating leading and trailing
// spaces as combinators
var input = [],
results = [],
matcher = compile( selector.replace( rtrim, "$1" ) );
return matcher[ expando ] ?
markFunction(function( seed, matches, context, xml ) {
var elem,
unmatched = matcher( seed, null, xml, [] ),
i = seed.length;
// Match elements unmatched by `matcher`
while ( i-- ) {
if ( (elem = unmatched[i]) ) {
seed[i] = !(matches[i] = elem);
}
}
}) :
function( elem, context, xml ) {
input[0] = elem;
matcher( input, null, xml, results );
return !results.pop();
};
}),
"has": markFunction(function( selector ) {
return function( elem ) {
return Sizzle( selector, elem ).length > 0;
};
}),
"contains": markFunction(function( text ) {
return function( elem ) {
return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1;
};
}),
"enabled": function( elem ) {
return elem.disabled === false;
},
"disabled": function( elem ) {
return elem.disabled === true;
},
"checked": function( elem ) {
// In CSS3, :checked should return both checked and selected elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
var nodeName = elem.nodeName.toLowerCase();
return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected);
},
"selected": function( elem ) {
// Accessing this property makes selected-by-default
// options in Safari work properly
if ( elem.parentNode ) {
elem.parentNode.selectedIndex;
}
return elem.selected === true;
},
"parent": function( elem ) {
return !Expr.pseudos["empty"]( elem );
},
"empty": function( elem ) {
// http://www.w3.org/TR/selectors/#empty-pseudo
// :empty is only affected by element nodes and content nodes(including text(3), cdata(4)),
// not comment, processing instructions, or others
// Thanks to Diego Perini for the nodeName shortcut
// Greater than "@" means alpha characters (specifically not starting with "#" or "?")
var nodeType;
elem = elem.firstChild;
while ( elem ) {
if ( elem.nodeName > "@" || (nodeType = elem.nodeType) === 3 || nodeType === 4 ) {
return false;
}
elem = elem.nextSibling;
}
return true;
},
"header": function( elem ) {
return rheader.test( elem.nodeName );
},
"text": function( elem ) {
var type, attr;
// IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc)
// use getAttribute instead to test this case
return elem.nodeName.toLowerCase() === "input" &&
(type = elem.type) === "text" &&
( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === type );
},
// Input types
"radio": createInputPseudo("radio"),
"checkbox": createInputPseudo("checkbox"),
"file": createInputPseudo("file"),
"password": createInputPseudo("password"),
"image": createInputPseudo("image"),
"submit": createButtonPseudo("submit"),
"reset": createButtonPseudo("reset"),
"button": function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === "button" || name === "button";
},
"input": function( elem ) {
return rinputs.test( elem.nodeName );
},
"focus": function( elem ) {
var doc = elem.ownerDocument;
return elem === doc.activeElement && (!doc.hasFocus || doc.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
},
"active": function( elem ) {
return elem === elem.ownerDocument.activeElement;
},
// Positional types
"first": createPositionalPseudo(function() {
return [ 0 ];
}),
"last": createPositionalPseudo(function( matchIndexes, length ) {
return [ length - 1 ];
}),
"eq": createPositionalPseudo(function( matchIndexes, length, argument ) {
return [ argument < 0 ? argument + length : argument ];
}),
"even": createPositionalPseudo(function( matchIndexes, length ) {
for ( var i = 0; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"odd": createPositionalPseudo(function( matchIndexes, length ) {
for ( var i = 1; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"lt": createPositionalPseudo(function( matchIndexes, length, argument ) {
for ( var i = argument < 0 ? argument + length : argument; --i >= 0; ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"gt": createPositionalPseudo(function( matchIndexes, length, argument ) {
for ( var i = argument < 0 ? argument + length : argument; ++i < length; ) {
matchIndexes.push( i );
}
return matchIndexes;
})
}
};
function siblingCheck( a, b, ret ) {
if ( a === b ) {
return ret;
}
var cur = a.nextSibling;
while ( cur ) {
if ( cur === b ) {
return -1;
}
cur = cur.nextSibling;
}
return 1;
}
sortOrder = docElem.compareDocumentPosition ?
function( a, b ) {
if ( a === b ) {
hasDuplicate = true;
return 0;
}
return ( !a.compareDocumentPosition || !b.compareDocumentPosition ?
a.compareDocumentPosition :
a.compareDocumentPosition(b) & 4
) ? -1 : 1;
} :
function( a, b ) {
// The nodes are identical, we can exit early
if ( a === b ) {
hasDuplicate = true;
return 0;
// Fallback to using sourceIndex (in IE) if it's available on both nodes
} else if ( a.sourceIndex && b.sourceIndex ) {
return a.sourceIndex - b.sourceIndex;
}
var al, bl,
ap = [],
bp = [],
aup = a.parentNode,
bup = b.parentNode,
cur = aup;
// If the nodes are siblings (or identical) we can do a quick check
if ( aup === bup ) {
return siblingCheck( a, b );
// If no parents were found then the nodes are disconnected
} else if ( !aup ) {
return -1;
} else if ( !bup ) {
return 1;
}
// Otherwise they're somewhere else in the tree so we need
// to build up a full list of the parentNodes for comparison
while ( cur ) {
ap.unshift( cur );
cur = cur.parentNode;
}
cur = bup;
while ( cur ) {
bp.unshift( cur );
cur = cur.parentNode;
}
al = ap.length;
bl = bp.length;
// Start walking down the tree looking for a discrepancy
for ( var i = 0; i < al && i < bl; i++ ) {
if ( ap[i] !== bp[i] ) {
return siblingCheck( ap[i], bp[i] );
}
}
// We ended someplace up the tree so do a sibling check
return i === al ?
siblingCheck( a, bp[i], -1 ) :
siblingCheck( ap[i], b, 1 );
};
// Always assume the presence of duplicates if sort doesn't
// pass them to our comparison function (as in Google Chrome).
[0, 0].sort( sortOrder );
baseHasDuplicate = !hasDuplicate;
// Document sorting and removing duplicates
Sizzle.uniqueSort = function( results ) {
var elem,
duplicates = [],
i = 1,
j = 0;
hasDuplicate = baseHasDuplicate;
results.sort( sortOrder );
if ( hasDuplicate ) {
for ( ; (elem = results[i]); i++ ) {
if ( elem === results[ i - 1 ] ) {
j = duplicates.push( i );
}
}
while ( j-- ) {
results.splice( duplicates[ j ], 1 );
}
}
return results;
};
Sizzle.error = function( msg ) {
throw new Error( "Syntax error, unrecognized expression: " + msg );
};
function tokenize( selector, parseOnly ) {
var matched, match, tokens, type,
soFar, groups, preFilters,
cached = tokenCache[ expando ][ selector + " " ];
if ( cached ) {
return parseOnly ? 0 : cached.slice( 0 );
}
soFar = selector;
groups = [];
preFilters = Expr.preFilter;
while ( soFar ) {
// Comma and first run
if ( !matched || (match = rcomma.exec( soFar )) ) {
if ( match ) {
// Don't consume trailing commas as valid
soFar = soFar.slice( match[0].length ) || soFar;
}
groups.push( tokens = [] );
}
matched = false;
// Combinators
if ( (match = rcombinators.exec( soFar )) ) {
tokens.push( matched = new Token( match.shift() ) );
soFar = soFar.slice( matched.length );
// Cast descendant combinators to space
matched.type = match[0].replace( rtrim, " " );
}
// Filters
for ( type in Expr.filter ) {
if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] ||
(match = preFilters[ type ]( match ))) ) {
tokens.push( matched = new Token( match.shift() ) );
soFar = soFar.slice( matched.length );
matched.type = type;
matched.matches = match;
}
}
if ( !matched ) {
break;
}
}
// Return the length of the invalid excess
// if we're just parsing
// Otherwise, throw an error or return tokens
return parseOnly ?
soFar.length :
soFar ?
Sizzle.error( selector ) :
// Cache the tokens
tokenCache( selector, groups ).slice( 0 );
}
function addCombinator( matcher, combinator, base ) {
var dir = combinator.dir,
checkNonElements = base && combinator.dir === "parentNode",
doneName = done++;
return combinator.first ?
// Check against closest ancestor/preceding element
function( elem, context, xml ) {
while ( (elem = elem[ dir ]) ) {
if ( checkNonElements || elem.nodeType === 1 ) {
return matcher( elem, context, xml );
}
}
} :
// Check against all ancestor/preceding elements
function( elem, context, xml ) {
// We can't set arbitrary data on XML nodes, so they don't benefit from dir caching
if ( !xml ) {
var cache,
dirkey = dirruns + " " + doneName + " ",
cachedkey = dirkey + cachedruns;
while ( (elem = elem[ dir ]) ) {
if ( checkNonElements || elem.nodeType === 1 ) {
if ( (cache = elem[ expando ]) === cachedkey ) {
return elem.sizset;
} else if ( typeof cache === "string" && cache.indexOf(dirkey) === 0 ) {
if ( elem.sizset ) {
return elem;
}
} else {
elem[ expando ] = cachedkey;
if ( matcher( elem, context, xml ) ) {
elem.sizset = true;
return elem;
}
elem.sizset = false;
}
}
}
} else {
while ( (elem = elem[ dir ]) ) {
if ( checkNonElements || elem.nodeType === 1 ) {
if ( matcher( elem, context, xml ) ) {
return elem;
}
}
}
}
};
}
function elementMatcher( matchers ) {
return matchers.length > 1 ?
function( elem, context, xml ) {
var i = matchers.length;
while ( i-- ) {
if ( !matchers[i]( elem, context, xml ) ) {
return false;
}
}
return true;
} :
matchers[0];
}
function condense( unmatched, map, filter, context, xml ) {
var elem,
newUnmatched = [],
i = 0,
len = unmatched.length,
mapped = map != null;
for ( ; i < len; i++ ) {
if ( (elem = unmatched[i]) ) {
if ( !filter || filter( elem, context, xml ) ) {
newUnmatched.push( elem );
if ( mapped ) {
map.push( i );
}
}
}
}
return newUnmatched;
}
function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) {
if ( postFilter && !postFilter[ expando ] ) {
postFilter = setMatcher( postFilter );
}
if ( postFinder && !postFinder[ expando ] ) {
postFinder = setMatcher( postFinder, postSelector );
}
return markFunction(function( seed, results, context, xml ) {
var temp, i, elem,
preMap = [],
postMap = [],
preexisting = results.length,
// Get initial elements from seed or context
elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ),
// Prefilter to get matcher input, preserving a map for seed-results synchronization
matcherIn = preFilter && ( seed || !selector ) ?
condense( elems, preMap, preFilter, context, xml ) :
elems,
matcherOut = matcher ?
// If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
postFinder || ( seed ? preFilter : preexisting || postFilter ) ?
// ...intermediate processing is necessary
[] :
// ...otherwise use results directly
results :
matcherIn;
// Find primary matches
if ( matcher ) {
matcher( matcherIn, matcherOut, context, xml );
}
// Apply postFilter
if ( postFilter ) {
temp = condense( matcherOut, postMap );
postFilter( temp, [], context, xml );
// Un-match failing elements by moving them back to matcherIn
i = temp.length;
while ( i-- ) {
if ( (elem = temp[i]) ) {
matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem);
}
}
}
if ( seed ) {
if ( postFinder || preFilter ) {
if ( postFinder ) {
// Get the final matcherOut by condensing this intermediate into postFinder contexts
temp = [];
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) ) {
// Restore matcherIn since elem is not yet a final match
temp.push( (matcherIn[i] = elem) );
}
}
postFinder( null, (matcherOut = []), temp, xml );
}
// Move matched elements from seed to results to keep them synchronized
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) &&
(temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) {
seed[temp] = !(results[temp] = elem);
}
}
}
// Add elements to results, through postFinder if defined
} else {
matcherOut = condense(
matcherOut === results ?
matcherOut.splice( preexisting, matcherOut.length ) :
matcherOut
);
if ( postFinder ) {
postFinder( null, results, matcherOut, xml );
} else {
push.apply( results, matcherOut );
}
}
});
}
function matcherFromTokens( tokens ) {
var checkContext, matcher, j,
len = tokens.length,
leadingRelative = Expr.relative[ tokens[0].type ],
implicitRelative = leadingRelative || Expr.relative[" "],
i = leadingRelative ? 1 : 0,
// The foundational matcher ensures that elements are reachable from top-level context(s)
matchContext = addCombinator( function( elem ) {
return elem === checkContext;
}, implicitRelative, true ),
matchAnyContext = addCombinator( function( elem ) {
return indexOf.call( checkContext, elem ) > -1;
}, implicitRelative, true ),
matchers = [ function( elem, context, xml ) {
return ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
(checkContext = context).nodeType ?
matchContext( elem, context, xml ) :
matchAnyContext( elem, context, xml ) );
} ];
for ( ; i < len; i++ ) {
if ( (matcher = Expr.relative[ tokens[i].type ]) ) {
matchers = [ addCombinator( elementMatcher( matchers ), matcher ) ];
} else {
matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches );
// Return special upon seeing a positional matcher
if ( matcher[ expando ] ) {
// Find the next relative operator (if any) for proper handling
j = ++i;
for ( ; j < len; j++ ) {
if ( Expr.relative[ tokens[j].type ] ) {
break;
}
}
return setMatcher(
i > 1 && elementMatcher( matchers ),
i > 1 && tokens.slice( 0, i - 1 ).join("").replace( rtrim, "$1" ),
matcher,
i < j && matcherFromTokens( tokens.slice( i, j ) ),
j < len && matcherFromTokens( (tokens = tokens.slice( j )) ),
j < len && tokens.join("")
);
}
matchers.push( matcher );
}
}
return elementMatcher( matchers );
}
function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
var bySet = setMatchers.length > 0,
byElement = elementMatchers.length > 0,
superMatcher = function( seed, context, xml, results, expandContext ) {
var elem, j, matcher,
setMatched = [],
matchedCount = 0,
i = "0",
unmatched = seed && [],
outermost = expandContext != null,
contextBackup = outermostContext,
// We must always have either seed elements or context
elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ),
// Nested matchers should use non-integer dirruns
dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.E);
if ( outermost ) {
outermostContext = context !== document && context;
cachedruns = superMatcher.el;
}
// Add elements passing elementMatchers directly to results
for ( ; (elem = elems[i]) != null; i++ ) {
if ( byElement && elem ) {
for ( j = 0; (matcher = elementMatchers[j]); j++ ) {
if ( matcher( elem, context, xml ) ) {
results.push( elem );
break;
}
}
if ( outermost ) {
dirruns = dirrunsUnique;
cachedruns = ++superMatcher.el;
}
}
// Track unmatched elements for set filters
if ( bySet ) {
// They will have gone through all possible matchers
if ( (elem = !matcher && elem) ) {
matchedCount--;
}
// Lengthen the array for every element, matched or not
if ( seed ) {
unmatched.push( elem );
}
}
}
// Apply set filters to unmatched elements
matchedCount += i;
if ( bySet && i !== matchedCount ) {
for ( j = 0; (matcher = setMatchers[j]); j++ ) {
matcher( unmatched, setMatched, context, xml );
}
if ( seed ) {
// Reintegrate element matches to eliminate the need for sorting
if ( matchedCount > 0 ) {
while ( i-- ) {
if ( !(unmatched[i] || setMatched[i]) ) {
setMatched[i] = pop.call( results );
}
}
}
// Discard index placeholder values to get only actual matches
setMatched = condense( setMatched );
}
// Add matches to results
push.apply( results, setMatched );
// Seedless set matches succeeding multiple successful matchers stipulate sorting
if ( outermost && !seed && setMatched.length > 0 &&
( matchedCount + setMatchers.length ) > 1 ) {
Sizzle.uniqueSort( results );
}
}
// Override manipulation of globals by nested matchers
if ( outermost ) {
dirruns = dirrunsUnique;
outermostContext = contextBackup;
}
return unmatched;
};
superMatcher.el = 0;
return bySet ?
markFunction( superMatcher ) :
superMatcher;
}
compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) {
var i,
setMatchers = [],
elementMatchers = [],
cached = compilerCache[ expando ][ selector + " " ];
if ( !cached ) {
// Generate a function of recursive functions that can be used to check each element
if ( !group ) {
group = tokenize( selector );
}
i = group.length;
while ( i-- ) {
cached = matcherFromTokens( group[i] );
if ( cached[ expando ] ) {
setMatchers.push( cached );
} else {
elementMatchers.push( cached );
}
}
// Cache the compiled function
cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) );
}
return cached;
};
function multipleContexts( selector, contexts, results ) {
var i = 0,
len = contexts.length;
for ( ; i < len; i++ ) {
Sizzle( selector, contexts[i], results );
}
return results;
}
function select( selector, context, results, seed, xml ) {
var i, tokens, token, type, find,
match = tokenize( selector ),
j = match.length;
if ( !seed ) {
// Try to minimize operations if there is only one group
if ( match.length === 1 ) {
// Take a shortcut and set the context if the root selector is an ID
tokens = match[0] = match[0].slice( 0 );
if ( tokens.length > 2 && (token = tokens[0]).type === "ID" &&
context.nodeType === 9 && !xml &&
Expr.relative[ tokens[1].type ] ) {
context = Expr.find["ID"]( token.matches[0].replace( rbackslash, "" ), context, xml )[0];
if ( !context ) {
return results;
}
selector = selector.slice( tokens.shift().length );
}
// Fetch a seed set for right-to-left matching
for ( i = matchExpr["POS"].test( selector ) ? -1 : tokens.length - 1; i >= 0; i-- ) {
token = tokens[i];
// Abort if we hit a combinator
if ( Expr.relative[ (type = token.type) ] ) {
break;
}
if ( (find = Expr.find[ type ]) ) {
// Search, expanding context for leading sibling combinators
if ( (seed = find(
token.matches[0].replace( rbackslash, "" ),
rsibling.test( tokens[0].type ) && context.parentNode || context,
xml
)) ) {
// If seed is empty or no tokens remain, we can return early
tokens.splice( i, 1 );
selector = seed.length && tokens.join("");
if ( !selector ) {
push.apply( results, slice.call( seed, 0 ) );
return results;
}
break;
}
}
}
}
}
// Compile and execute a filtering function
// Provide `match` to avoid retokenization if we modified the selector above
compile( selector, match )(
seed,
context,
xml,
results,
rsibling.test( selector )
);
return results;
}
if ( document.querySelectorAll ) {
(function() {
var disconnectedMatch,
oldSelect = select,
rescape = /'|\\/g,
rattributeQuotes = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,
// qSa(:focus) reports false when true (Chrome 21), no need to also add to buggyMatches since matches checks buggyQSA
// A support test would require too much code (would include document ready)
rbuggyQSA = [ ":focus" ],
// matchesSelector(:active) reports false when true (IE9/Opera 11.5)
// A support test would require too much code (would include document ready)
// just skip matchesSelector for :active
rbuggyMatches = [ ":active" ],
matches = docElem.matchesSelector ||
docElem.mozMatchesSelector ||
docElem.webkitMatchesSelector ||
docElem.oMatchesSelector ||
docElem.msMatchesSelector;
// Build QSA regex
// Regex strategy adopted from Diego Perini
assert(function( div ) {
// Select is set to empty string on purpose
// This is to test IE's treatment of not explictly
// setting a boolean content attribute,
// since its presence should be enough
// http://bugs.jquery.com/ticket/12359
div.innerHTML = "<select><option selected=''></option></select>";
// IE8 - Some boolean attributes are not treated correctly
if ( !div.querySelectorAll("[selected]").length ) {
rbuggyQSA.push( "\\[" + whitespace + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)" );
}
// Webkit/Opera - :checked should return selected option elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
// IE8 throws error here (do not put tests after this one)
if ( !div.querySelectorAll(":checked").length ) {
rbuggyQSA.push(":checked");
}
});
assert(function( div ) {
// Opera 10-12/IE9 - ^= $= *= and empty values
// Should not select anything
div.innerHTML = "<p test=''></p>";
if ( div.querySelectorAll("[test^='']").length ) {
rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:\"\"|'')" );
}
// FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
// IE8 throws error here (do not put tests after this one)
div.innerHTML = "<input type='hidden'/>";
if ( !div.querySelectorAll(":enabled").length ) {
rbuggyQSA.push(":enabled", ":disabled");
}
});
// rbuggyQSA always contains :focus, so no need for a length check
rbuggyQSA = /* rbuggyQSA.length && */ new RegExp( rbuggyQSA.join("|") );
select = function( selector, context, results, seed, xml ) {
// Only use querySelectorAll when not filtering,
// when this is not xml,
// and when no QSA bugs apply
if ( !seed && !xml && !rbuggyQSA.test( selector ) ) {
var groups, i,
old = true,
nid = expando,
newContext = context,
newSelector = context.nodeType === 9 && selector;
// qSA works strangely on Element-rooted queries
// We can work around this by specifying an extra ID on the root
// and working up from there (Thanks to Andrew Dupont for the technique)
// IE 8 doesn't work on object elements
if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
groups = tokenize( selector );
if ( (old = context.getAttribute("id")) ) {
nid = old.replace( rescape, "\\$&" );
} else {
context.setAttribute( "id", nid );
}
nid = "[id='" + nid + "'] ";
i = groups.length;
while ( i-- ) {
groups[i] = nid + groups[i].join("");
}
newContext = rsibling.test( selector ) && context.parentNode || context;
newSelector = groups.join(",");
}
if ( newSelector ) {
try {
push.apply( results, slice.call( newContext.querySelectorAll(
newSelector
), 0 ) );
return results;
} catch(qsaError) {
} finally {
if ( !old ) {
context.removeAttribute("id");
}
}
}
}
return oldSelect( selector, context, results, seed, xml );
};
if ( matches ) {
assert(function( div ) {
// Check to see if it's possible to do matchesSelector
// on a disconnected node (IE 9)
disconnectedMatch = matches.call( div, "div" );
// This should fail with an exception
// Gecko does not error, returns false instead
try {
matches.call( div, "[test!='']:sizzle" );
rbuggyMatches.push( "!=", pseudos );
} catch ( e ) {}
});
// rbuggyMatches always contains :active and :focus, so no need for a length check
rbuggyMatches = /* rbuggyMatches.length && */ new RegExp( rbuggyMatches.join("|") );
Sizzle.matchesSelector = function( elem, expr ) {
// Make sure that attribute selectors are quoted
expr = expr.replace( rattributeQuotes, "='$1']" );
// rbuggyMatches always contains :active, so no need for an existence check
if ( !isXML( elem ) && !rbuggyMatches.test( expr ) && !rbuggyQSA.test( expr ) ) {
try {
var ret = matches.call( elem, expr );
// IE 9's matchesSelector returns false on disconnected nodes
if ( ret || disconnectedMatch ||
// As well, disconnected nodes are said to be in a document
// fragment in IE 9
elem.document && elem.document.nodeType !== 11 ) {
return ret;
}
} catch(e) {}
}
return Sizzle( expr, null, null, [ elem ] ).length > 0;
};
}
})();
}
// Deprecated
Expr.pseudos["nth"] = Expr.pseudos["eq"];
// Back-compat
function setFilters() {}
Expr.filters = setFilters.prototype = Expr.pseudos;
Expr.setFilters = new setFilters();
// Override sizzle attribute retrieval
Sizzle.attr = jQuery.attr;
jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.pseudos;
jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;
})( window );
var runtil = /Until$/,
rparentsprev = /^(?:parents|prev(?:Until|All))/,
isSimple = /^.[^:#\[\.,]*$/,
rneedsContext = jQuery.expr.match.needsContext,
// methods guaranteed to produce a unique set when starting from a unique set
guaranteedUnique = {
children: true,
contents: true,
next: true,
prev: true
};
jQuery.fn.extend({
find: function( selector ) {
var i, l, length, n, r, ret,
self = this;
if ( typeof selector !== "string" ) {
return jQuery( selector ).filter(function() {
for ( i = 0, l = self.length; i < l; i++ ) {
if ( jQuery.contains( self[ i ], this ) ) {
return true;
}
}
});
}
ret = this.pushStack( "", "find", selector );
for ( i = 0, l = this.length; i < l; i++ ) {
length = ret.length;
jQuery.find( selector, this[i], ret );
if ( i > 0 ) {
// Make sure that the results are unique
for ( n = length; n < ret.length; n++ ) {
for ( r = 0; r < length; r++ ) {
if ( ret[r] === ret[n] ) {
ret.splice(n--, 1);
break;
}
}
}
}
}
return ret;
},
has: function( target ) {
var i,
targets = jQuery( target, this ),
len = targets.length;
return this.filter(function() {
for ( i = 0; i < len; i++ ) {
if ( jQuery.contains( this, targets[i] ) ) {
return true;
}
}
});
},
not: function( selector ) {
return this.pushStack( winnow(this, selector, false), "not", selector);
},
filter: function( selector ) {
return this.pushStack( winnow(this, selector, true), "filter", selector );
},
is: function( selector ) {
return !!selector && (
typeof selector === "string" ?
// If this is a positional/relative selector, check membership in the returned set
// so $("p:first").is("p:last") won't return true for a doc with two "p".
rneedsContext.test( selector ) ?
jQuery( selector, this.context ).index( this[0] ) >= 0 :
jQuery.filter( selector, this ).length > 0 :
this.filter( selector ).length > 0 );
},
closest: function( selectors, context ) {
var cur,
i = 0,
l = this.length,
ret = [],
pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ?
jQuery( selectors, context || this.context ) :
0;
for ( ; i < l; i++ ) {
cur = this[i];
while ( cur && cur.ownerDocument && cur !== context && cur.nodeType !== 11 ) {
if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) {
ret.push( cur );
break;
}
cur = cur.parentNode;
}
}
ret = ret.length > 1 ? jQuery.unique( ret ) : ret;
return this.pushStack( ret, "closest", selectors );
},
// Determine the position of an element within
// the matched set of elements
index: function( elem ) {
// No argument, return index in parent
if ( !elem ) {
return ( this[0] && this[0].parentNode ) ? this.prevAll().length : -1;
}
// index in selector
if ( typeof elem === "string" ) {
return jQuery.inArray( this[0], jQuery( elem ) );
}
// Locate the position of the desired element
return jQuery.inArray(
// If it receives a jQuery object, the first element is used
elem.jquery ? elem[0] : elem, this );
},
add: function( selector, context ) {
var set = typeof selector === "string" ?
jQuery( selector, context ) :
jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ),
all = jQuery.merge( this.get(), set );
return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ?
all :
jQuery.unique( all ) );
},
addBack: function( selector ) {
return this.add( selector == null ?
this.prevObject : this.prevObject.filter(selector)
);
}
});
jQuery.fn.andSelf = jQuery.fn.addBack;
// A painfully simple check to see if an element is disconnected
// from a document (should be improved, where feasible).
function isDisconnected( node ) {
return !node || !node.parentNode || node.parentNode.nodeType === 11;
}
function sibling( cur, dir ) {
do {
cur = cur[ dir ];
} while ( cur && cur.nodeType !== 1 );
return cur;
}
jQuery.each({
parent: function( elem ) {
var parent = elem.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
parents: function( elem ) {
return jQuery.dir( elem, "parentNode" );
},
parentsUntil: function( elem, i, until ) {
return jQuery.dir( elem, "parentNode", until );
},
next: function( elem ) {
return sibling( elem, "nextSibling" );
},
prev: function( elem ) {
return sibling( elem, "previousSibling" );
},
nextAll: function( elem ) {
return jQuery.dir( elem, "nextSibling" );
},
prevAll: function( elem ) {
return jQuery.dir( elem, "previousSibling" );
},
nextUntil: function( elem, i, until ) {
return jQuery.dir( elem, "nextSibling", until );
},
prevUntil: function( elem, i, until ) {
return jQuery.dir( elem, "previousSibling", until );
},
siblings: function( elem ) {
return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem );
},
children: function( elem ) {
return jQuery.sibling( elem.firstChild );
},
contents: function( elem ) {
return jQuery.nodeName( elem, "iframe" ) ?
elem.contentDocument || elem.contentWindow.document :
jQuery.merge( [], elem.childNodes );
}
}, function( name, fn ) {
jQuery.fn[ name ] = function( until, selector ) {
var ret = jQuery.map( this, fn, until );
if ( !runtil.test( name ) ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
ret = jQuery.filter( selector, ret );
}
ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret;
if ( this.length > 1 && rparentsprev.test( name ) ) {
ret = ret.reverse();
}
return this.pushStack( ret, name, core_slice.call( arguments ).join(",") );
};
});
jQuery.extend({
filter: function( expr, elems, not ) {
if ( not ) {
expr = ":not(" + expr + ")";
}
return elems.length === 1 ?
jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] :
jQuery.find.matches(expr, elems);
},
dir: function( elem, dir, until ) {
var matched = [],
cur = elem[ dir ];
while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) {
if ( cur.nodeType === 1 ) {
matched.push( cur );
}
cur = cur[dir];
}
return matched;
},
sibling: function( n, elem ) {
var r = [];
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType === 1 && n !== elem ) {
r.push( n );
}
}
return r;
}
});
// Implement the identical functionality for filter and not
function winnow( elements, qualifier, keep ) {
// Can't pass null or undefined to indexOf in Firefox 4
// Set to 0 to skip string check
qualifier = qualifier || 0;
if ( jQuery.isFunction( qualifier ) ) {
return jQuery.grep(elements, function( elem, i ) {
var retVal = !!qualifier.call( elem, i, elem );
return retVal === keep;
});
} else if ( qualifier.nodeType ) {
return jQuery.grep(elements, function( elem, i ) {
return ( elem === qualifier ) === keep;
});
} else if ( typeof qualifier === "string" ) {
var filtered = jQuery.grep(elements, function( elem ) {
return elem.nodeType === 1;
});
if ( isSimple.test( qualifier ) ) {
return jQuery.filter(qualifier, filtered, !keep);
} else {
qualifier = jQuery.filter( qualifier, filtered );
}
}
return jQuery.grep(elements, function( elem, i ) {
return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep;
});
}
function createSafeFragment( document ) {
var list = nodeNames.split( "|" ),
safeFrag = document.createDocumentFragment();
if ( safeFrag.createElement ) {
while ( list.length ) {
safeFrag.createElement(
list.pop()
);
}
}
return safeFrag;
}
var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" +
"header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",
rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g,
rleadingWhitespace = /^\s+/,
rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,
rtagName = /<([\w:]+)/,
rtbody = /<tbody/i,
rhtml = /<|&#?\w+;/,
rnoInnerhtml = /<(?:script|style|link)/i,
rnocache = /<(?:script|object|embed|option|style)/i,
rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"),
rcheckableType = /^(?:checkbox|radio)$/,
// checked="checked" or checked
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
rscriptType = /\/(java|ecma)script/i,
rcleanScript = /^\s*<!(?:\[CDATA\[|\-\-)|[\]\-]{2}>\s*$/g,
wrapMap = {
option: [ 1, "<select multiple='multiple'>", "</select>" ],
legend: [ 1, "<fieldset>", "</fieldset>" ],
thead: [ 1, "<table>", "</table>" ],
tr: [ 2, "<table><tbody>", "</tbody></table>" ],
td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ],
area: [ 1, "<map>", "</map>" ],
_default: [ 0, "", "" ]
},
safeFragment = createSafeFragment( document ),
fragmentDiv = safeFragment.appendChild( document.createElement("div") );
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
// IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags,
// unless wrapped in a div with non-breaking characters in front of it.
if ( !jQuery.support.htmlSerialize ) {
wrapMap._default = [ 1, "X<div>", "</div>" ];
}
jQuery.fn.extend({
text: function( value ) {
return jQuery.access( this, function( value ) {
return value === undefined ?
jQuery.text( this ) :
this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) );
}, null, value, arguments.length );
},
wrapAll: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapAll( html.call(this, i) );
});
}
if ( this[0] ) {
// The elements to wrap the target around
var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true);
if ( this[0].parentNode ) {
wrap.insertBefore( this[0] );
}
wrap.map(function() {
var elem = this;
while ( elem.firstChild && elem.firstChild.nodeType === 1 ) {
elem = elem.firstChild;
}
return elem;
}).append( this );
}
return this;
},
wrapInner: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapInner( html.call(this, i) );
});
}
return this.each(function() {
var self = jQuery( this ),
contents = self.contents();
if ( contents.length ) {
contents.wrapAll( html );
} else {
self.append( html );
}
});
},
wrap: function( html ) {
var isFunction = jQuery.isFunction( html );
return this.each(function(i) {
jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html );
});
},
unwrap: function() {
return this.parent().each(function() {
if ( !jQuery.nodeName( this, "body" ) ) {
jQuery( this ).replaceWith( this.childNodes );
}
}).end();
},
append: function() {
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 ) {
this.appendChild( elem );
}
});
},
prepend: function() {
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 ) {
this.insertBefore( elem, this.firstChild );
}
});
},
before: function() {
if ( !isDisconnected( this[0] ) ) {
return this.domManip(arguments, false, function( elem ) {
this.parentNode.insertBefore( elem, this );
});
}
if ( arguments.length ) {
var set = jQuery.clean( arguments );
return this.pushStack( jQuery.merge( set, this ), "before", this.selector );
}
},
after: function() {
if ( !isDisconnected( this[0] ) ) {
return this.domManip(arguments, false, function( elem ) {
this.parentNode.insertBefore( elem, this.nextSibling );
});
}
if ( arguments.length ) {
var set = jQuery.clean( arguments );
return this.pushStack( jQuery.merge( this, set ), "after", this.selector );
}
},
// keepData is for internal use only--do not document
remove: function( selector, keepData ) {
var elem,
i = 0;
for ( ; (elem = this[i]) != null; i++ ) {
if ( !selector || jQuery.filter( selector, [ elem ] ).length ) {
if ( !keepData && elem.nodeType === 1 ) {
jQuery.cleanData( elem.getElementsByTagName("*") );
jQuery.cleanData( [ elem ] );
}
if ( elem.parentNode ) {
elem.parentNode.removeChild( elem );
}
}
}
return this;
},
empty: function() {
var elem,
i = 0;
for ( ; (elem = this[i]) != null; i++ ) {
// Remove element nodes and prevent memory leaks
if ( elem.nodeType === 1 ) {
jQuery.cleanData( elem.getElementsByTagName("*") );
}
// Remove any remaining nodes
while ( elem.firstChild ) {
elem.removeChild( elem.firstChild );
}
}
return this;
},
clone: function( dataAndEvents, deepDataAndEvents ) {
dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
return this.map( function () {
return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
});
},
html: function( value ) {
return jQuery.access( this, function( value ) {
var elem = this[0] || {},
i = 0,
l = this.length;
if ( value === undefined ) {
return elem.nodeType === 1 ?
elem.innerHTML.replace( rinlinejQuery, "" ) :
undefined;
}
// See if we can take a shortcut and just use innerHTML
if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
( jQuery.support.htmlSerialize || !rnoshimcache.test( value ) ) &&
( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) &&
!wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) {
value = value.replace( rxhtmlTag, "<$1></$2>" );
try {
for (; i < l; i++ ) {
// Remove element nodes and prevent memory leaks
elem = this[i] || {};
if ( elem.nodeType === 1 ) {
jQuery.cleanData( elem.getElementsByTagName( "*" ) );
elem.innerHTML = value;
}
}
elem = 0;
// If using innerHTML throws an exception, use the fallback method
} catch(e) {}
}
if ( elem ) {
this.empty().append( value );
}
}, null, value, arguments.length );
},
replaceWith: function( value ) {
if ( !isDisconnected( this[0] ) ) {
// Make sure that the elements are removed from the DOM before they are inserted
// this can help fix replacing a parent with child elements
if ( jQuery.isFunction( value ) ) {
return this.each(function(i) {
var self = jQuery(this), old = self.html();
self.replaceWith( value.call( this, i, old ) );
});
}
if ( typeof value !== "string" ) {
value = jQuery( value ).detach();
}
return this.each(function() {
var next = this.nextSibling,
parent = this.parentNode;
jQuery( this ).remove();
if ( next ) {
jQuery(next).before( value );
} else {
jQuery(parent).append( value );
}
});
}
return this.length ?
this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ) :
this;
},
detach: function( selector ) {
return this.remove( selector, true );
},
domManip: function( args, table, callback ) {
// Flatten any nested arrays
args = [].concat.apply( [], args );
var results, first, fragment, iNoClone,
i = 0,
value = args[0],
scripts = [],
l = this.length;
// We can't cloneNode fragments that contain checked, in WebKit
if ( !jQuery.support.checkClone && l > 1 && typeof value === "string" && rchecked.test( value ) ) {
return this.each(function() {
jQuery(this).domManip( args, table, callback );
});
}
if ( jQuery.isFunction(value) ) {
return this.each(function(i) {
var self = jQuery(this);
args[0] = value.call( this, i, table ? self.html() : undefined );
self.domManip( args, table, callback );
});
}
if ( this[0] ) {
results = jQuery.buildFragment( args, this, scripts );
fragment = results.fragment;
first = fragment.firstChild;
if ( fragment.childNodes.length === 1 ) {
fragment = first;
}
if ( first ) {
table = table && jQuery.nodeName( first, "tr" );
// Use the original fragment for the last item instead of the first because it can end up
// being emptied incorrectly in certain situations (#8070).
// Fragments from the fragment cache must always be cloned and never used in place.
for ( iNoClone = results.cacheable || l - 1; i < l; i++ ) {
callback.call(
table && jQuery.nodeName( this[i], "table" ) ?
findOrAppend( this[i], "tbody" ) :
this[i],
i === iNoClone ?
fragment :
jQuery.clone( fragment, true, true )
);
}
}
// Fix #11809: Avoid leaking memory
fragment = first = null;
if ( scripts.length ) {
jQuery.each( scripts, function( i, elem ) {
if ( elem.src ) {
if ( jQuery.ajax ) {
jQuery.ajax({
url: elem.src,
type: "GET",
dataType: "script",
async: false,
global: false,
"throws": true
});
} else {
jQuery.error("no ajax");
}
} else {
jQuery.globalEval( ( elem.text || elem.textContent || elem.innerHTML || "" ).replace( rcleanScript, "" ) );
}
if ( elem.parentNode ) {
elem.parentNode.removeChild( elem );
}
});
}
}
return this;
}
});
function findOrAppend( elem, tag ) {
return elem.getElementsByTagName( tag )[0] || elem.appendChild( elem.ownerDocument.createElement( tag ) );
}
function cloneCopyEvent( src, dest ) {
if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) {
return;
}
var type, i, l,
oldData = jQuery._data( src ),
curData = jQuery._data( dest, oldData ),
events = oldData.events;
if ( events ) {
delete curData.handle;
curData.events = {};
for ( type in events ) {
for ( i = 0, l = events[ type ].length; i < l; i++ ) {
jQuery.event.add( dest, type, events[ type ][ i ] );
}
}
}
// make the cloned public data object a copy from the original
if ( curData.data ) {
curData.data = jQuery.extend( {}, curData.data );
}
}
function cloneFixAttributes( src, dest ) {
var nodeName;
// We do not need to do anything for non-Elements
if ( dest.nodeType !== 1 ) {
return;
}
// clearAttributes removes the attributes, which we don't want,
// but also removes the attachEvent events, which we *do* want
if ( dest.clearAttributes ) {
dest.clearAttributes();
}
// mergeAttributes, in contrast, only merges back on the
// original attributes, not the events
if ( dest.mergeAttributes ) {
dest.mergeAttributes( src );
}
nodeName = dest.nodeName.toLowerCase();
if ( nodeName === "object" ) {
// IE6-10 improperly clones children of object elements using classid.
// IE10 throws NoModificationAllowedError if parent is null, #12132.
if ( dest.parentNode ) {
dest.outerHTML = src.outerHTML;
}
// This path appears unavoidable for IE9. When cloning an object
// element in IE9, the outerHTML strategy above is not sufficient.
// If the src has innerHTML and the destination does not,
// copy the src.innerHTML into the dest.innerHTML. #10324
if ( jQuery.support.html5Clone && (src.innerHTML && !jQuery.trim(dest.innerHTML)) ) {
dest.innerHTML = src.innerHTML;
}
} else if ( nodeName === "input" && rcheckableType.test( src.type ) ) {
// IE6-8 fails to persist the checked state of a cloned checkbox
// or radio button. Worse, IE6-7 fail to give the cloned element
// a checked appearance if the defaultChecked value isn't also set
dest.defaultChecked = dest.checked = src.checked;
// IE6-7 get confused and end up setting the value of a cloned
// checkbox/radio button to an empty string instead of "on"
if ( dest.value !== src.value ) {
dest.value = src.value;
}
// IE6-8 fails to return the selected option to the default selected
// state when cloning options
} else if ( nodeName === "option" ) {
dest.selected = src.defaultSelected;
// IE6-8 fails to set the defaultValue to the correct value when
// cloning other types of input fields
} else if ( nodeName === "input" || nodeName === "textarea" ) {
dest.defaultValue = src.defaultValue;
// IE blanks contents when cloning scripts
} else if ( nodeName === "script" && dest.text !== src.text ) {
dest.text = src.text;
}
// Event data gets referenced instead of copied if the expando
// gets copied too
dest.removeAttribute( jQuery.expando );
}
jQuery.buildFragment = function( args, context, scripts ) {
var fragment, cacheable, cachehit,
first = args[ 0 ];
// Set context from what may come in as undefined or a jQuery collection or a node
// Updated to fix #12266 where accessing context[0] could throw an exception in IE9/10 &
// also doubles as fix for #8950 where plain objects caused createDocumentFragment exception
context = context || document;
context = !context.nodeType && context[0] || context;
context = context.ownerDocument || context;
// Only cache "small" (1/2 KB) HTML strings that are associated with the main document
// Cloning options loses the selected state, so don't cache them
// IE 6 doesn't like it when you put <object> or <embed> elements in a fragment
// Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache
// Lastly, IE6,7,8 will not correctly reuse cached fragments that were created from unknown elems #10501
if ( args.length === 1 && typeof first === "string" && first.length < 512 && context === document &&
first.charAt(0) === "<" && !rnocache.test( first ) &&
(jQuery.support.checkClone || !rchecked.test( first )) &&
(jQuery.support.html5Clone || !rnoshimcache.test( first )) ) {
// Mark cacheable and look for a hit
cacheable = true;
fragment = jQuery.fragments[ first ];
cachehit = fragment !== undefined;
}
if ( !fragment ) {
fragment = context.createDocumentFragment();
jQuery.clean( args, context, fragment, scripts );
// Update the cache, but only store false
// unless this is a second parsing of the same content
if ( cacheable ) {
jQuery.fragments[ first ] = cachehit && fragment;
}
}
return { fragment: fragment, cacheable: cacheable };
};
jQuery.fragments = {};
jQuery.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function( name, original ) {
jQuery.fn[ name ] = function( selector ) {
var elems,
i = 0,
ret = [],
insert = jQuery( selector ),
l = insert.length,
parent = this.length === 1 && this[0].parentNode;
if ( (parent == null || parent && parent.nodeType === 11 && parent.childNodes.length === 1) && l === 1 ) {
insert[ original ]( this[0] );
return this;
} else {
for ( ; i < l; i++ ) {
elems = ( i > 0 ? this.clone(true) : this ).get();
jQuery( insert[i] )[ original ]( elems );
ret = ret.concat( elems );
}
return this.pushStack( ret, name, insert.selector );
}
};
});
function getAll( elem ) {
if ( typeof elem.getElementsByTagName !== "undefined" ) {
return elem.getElementsByTagName( "*" );
} else if ( typeof elem.querySelectorAll !== "undefined" ) {
return elem.querySelectorAll( "*" );
} else {
return [];
}
}
// Used in clean, fixes the defaultChecked property
function fixDefaultChecked( elem ) {
if ( rcheckableType.test( elem.type ) ) {
elem.defaultChecked = elem.checked;
}
}
jQuery.extend({
clone: function( elem, dataAndEvents, deepDataAndEvents ) {
var srcElements,
destElements,
i,
clone;
if ( jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) {
clone = elem.cloneNode( true );
// IE<=8 does not properly clone detached, unknown element nodes
} else {
fragmentDiv.innerHTML = elem.outerHTML;
fragmentDiv.removeChild( clone = fragmentDiv.firstChild );
}
if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) &&
(elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) {
// IE copies events bound via attachEvent when using cloneNode.
// Calling detachEvent on the clone will also remove the events
// from the original. In order to get around this, we use some
// proprietary methods to clear the events. Thanks to MooTools
// guys for this hotness.
cloneFixAttributes( elem, clone );
// Using Sizzle here is crazy slow, so we use getElementsByTagName instead
srcElements = getAll( elem );
destElements = getAll( clone );
// Weird iteration because IE will replace the length property
// with an element if you are cloning the body and one of the
// elements on the page has a name or id of "length"
for ( i = 0; srcElements[i]; ++i ) {
// Ensure that the destination node is not null; Fixes #9587
if ( destElements[i] ) {
cloneFixAttributes( srcElements[i], destElements[i] );
}
}
}
// Copy the events from the original to the clone
if ( dataAndEvents ) {
cloneCopyEvent( elem, clone );
if ( deepDataAndEvents ) {
srcElements = getAll( elem );
destElements = getAll( clone );
for ( i = 0; srcElements[i]; ++i ) {
cloneCopyEvent( srcElements[i], destElements[i] );
}
}
}
srcElements = destElements = null;
// Return the cloned set
return clone;
},
clean: function( elems, context, fragment, scripts ) {
var i, j, elem, tag, wrap, depth, div, hasBody, tbody, len, handleScript, jsTags,
safe = context === document && safeFragment,
ret = [];
// Ensure that context is a document
if ( !context || typeof context.createDocumentFragment === "undefined" ) {
context = document;
}
// Use the already-created safe fragment if context permits
for ( i = 0; (elem = elems[i]) != null; i++ ) {
if ( typeof elem === "number" ) {
elem += "";
}
if ( !elem ) {
continue;
}
// Convert html string into DOM nodes
if ( typeof elem === "string" ) {
if ( !rhtml.test( elem ) ) {
elem = context.createTextNode( elem );
} else {
// Ensure a safe container in which to render the html
safe = safe || createSafeFragment( context );
div = context.createElement("div");
safe.appendChild( div );
// Fix "XHTML"-style tags in all browsers
elem = elem.replace(rxhtmlTag, "<$1></$2>");
// Go to html and back, then peel off extra wrappers
tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase();
wrap = wrapMap[ tag ] || wrapMap._default;
depth = wrap[0];
div.innerHTML = wrap[1] + elem + wrap[2];
// Move to the right depth
while ( depth-- ) {
div = div.lastChild;
}
// Remove IE's autoinserted <tbody> from table fragments
if ( !jQuery.support.tbody ) {
// String was a <table>, *may* have spurious <tbody>
hasBody = rtbody.test(elem);
tbody = tag === "table" && !hasBody ?
div.firstChild && div.firstChild.childNodes :
// String was a bare <thead> or <tfoot>
wrap[1] === "<table>" && !hasBody ?
div.childNodes :
[];
for ( j = tbody.length - 1; j >= 0 ; --j ) {
if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) {
tbody[ j ].parentNode.removeChild( tbody[ j ] );
}
}
}
// IE completely kills leading whitespace when innerHTML is used
if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild );
}
elem = div.childNodes;
// Take out of fragment container (we need a fresh div each time)
div.parentNode.removeChild( div );
}
}
if ( elem.nodeType ) {
ret.push( elem );
} else {
jQuery.merge( ret, elem );
}
}
// Fix #11356: Clear elements from safeFragment
if ( div ) {
elem = div = safe = null;
}
// Reset defaultChecked for any radios and checkboxes
// about to be appended to the DOM in IE 6/7 (#8060)
if ( !jQuery.support.appendChecked ) {
for ( i = 0; (elem = ret[i]) != null; i++ ) {
if ( jQuery.nodeName( elem, "input" ) ) {
fixDefaultChecked( elem );
} else if ( typeof elem.getElementsByTagName !== "undefined" ) {
jQuery.grep( elem.getElementsByTagName("input"), fixDefaultChecked );
}
}
}
// Append elements to a provided document fragment
if ( fragment ) {
// Special handling of each script element
handleScript = function( elem ) {
// Check if we consider it executable
if ( !elem.type || rscriptType.test( elem.type ) ) {
// Detach the script and store it in the scripts array (if provided) or the fragment
// Return truthy to indicate that it has been handled
return scripts ?
scripts.push( elem.parentNode ? elem.parentNode.removeChild( elem ) : elem ) :
fragment.appendChild( elem );
}
};
for ( i = 0; (elem = ret[i]) != null; i++ ) {
// Check if we're done after handling an executable script
if ( !( jQuery.nodeName( elem, "script" ) && handleScript( elem ) ) ) {
// Append to fragment and handle embedded scripts
fragment.appendChild( elem );
if ( typeof elem.getElementsByTagName !== "undefined" ) {
// handleScript alters the DOM, so use jQuery.merge to ensure snapshot iteration
jsTags = jQuery.grep( jQuery.merge( [], elem.getElementsByTagName("script") ), handleScript );
// Splice the scripts into ret after their former ancestor and advance our index beyond them
ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) );
i += jsTags.length;
}
}
}
}
return ret;
},
cleanData: function( elems, /* internal */ acceptData ) {
var data, id, elem, type,
i = 0,
internalKey = jQuery.expando,
cache = jQuery.cache,
deleteExpando = jQuery.support.deleteExpando,
special = jQuery.event.special;
for ( ; (elem = elems[i]) != null; i++ ) {
if ( acceptData || jQuery.acceptData( elem ) ) {
id = elem[ internalKey ];
data = id && cache[ id ];
if ( data ) {
if ( data.events ) {
for ( type in data.events ) {
if ( special[ type ] ) {
jQuery.event.remove( elem, type );
// This is a shortcut to avoid jQuery.event.remove's overhead
} else {
jQuery.removeEvent( elem, type, data.handle );
}
}
}
// Remove cache only if it was not already removed by jQuery.event.remove
if ( cache[ id ] ) {
delete cache[ id ];
// IE does not allow us to delete expando properties from nodes,
// nor does it have a removeAttribute function on Document nodes;
// we must handle all of these cases
if ( deleteExpando ) {
delete elem[ internalKey ];
} else if ( elem.removeAttribute ) {
elem.removeAttribute( internalKey );
} else {
elem[ internalKey ] = null;
}
jQuery.deletedIds.push( id );
}
}
}
}
}
});
// Limit scope pollution from any deprecated API
(function() {
var matched, browser;
// Use of jQuery.browser is frowned upon.
// More details: http://api.jquery.com/jQuery.browser
// jQuery.uaMatch maintained for back-compat
jQuery.uaMatch = function( ua ) {
ua = ua.toLowerCase();
var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) ||
/(webkit)[ \/]([\w.]+)/.exec( ua ) ||
/(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) ||
/(msie) ([\w.]+)/.exec( ua ) ||
ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) ||
[];
return {
browser: match[ 1 ] || "",
version: match[ 2 ] || "0"
};
};
matched = jQuery.uaMatch( navigator.userAgent );
browser = {};
if ( matched.browser ) {
browser[ matched.browser ] = true;
browser.version = matched.version;
}
// Chrome is Webkit, but Webkit is also Safari.
if ( browser.chrome ) {
browser.webkit = true;
} else if ( browser.webkit ) {
browser.safari = true;
}
jQuery.browser = browser;
jQuery.sub = function() {
function jQuerySub( selector, context ) {
return new jQuerySub.fn.init( selector, context );
}
jQuery.extend( true, jQuerySub, this );
jQuerySub.superclass = this;
jQuerySub.fn = jQuerySub.prototype = this();
jQuerySub.fn.constructor = jQuerySub;
jQuerySub.sub = this.sub;
jQuerySub.fn.init = function init( selector, context ) {
if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) {
context = jQuerySub( context );
}
return jQuery.fn.init.call( this, selector, context, rootjQuerySub );
};
jQuerySub.fn.init.prototype = jQuerySub.fn;
var rootjQuerySub = jQuerySub(document);
return jQuerySub;
};
})();
var curCSS, iframe, iframeDoc,
ralpha = /alpha\([^)]*\)/i,
ropacity = /opacity=([^)]*)/,
rposition = /^(top|right|bottom|left)$/,
// swappable if display is none or starts with table except "table", "table-cell", or "table-caption"
// see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display
rdisplayswap = /^(none|table(?!-c[ea]).+)/,
rmargin = /^margin/,
rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ),
rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ),
rrelNum = new RegExp( "^([-+])=(" + core_pnum + ")", "i" ),
elemdisplay = { BODY: "block" },
cssShow = { position: "absolute", visibility: "hidden", display: "block" },
cssNormalTransform = {
letterSpacing: 0,
fontWeight: 400
},
cssExpand = [ "Top", "Right", "Bottom", "Left" ],
cssPrefixes = [ "Webkit", "O", "Moz", "ms" ],
eventsToggle = jQuery.fn.toggle;
// return a css property mapped to a potentially vendor prefixed property
function vendorPropName( style, name ) {
// shortcut for names that are not vendor prefixed
if ( name in style ) {
return name;
}
// check for vendor prefixed names
var capName = name.charAt(0).toUpperCase() + name.slice(1),
origName = name,
i = cssPrefixes.length;
while ( i-- ) {
name = cssPrefixes[ i ] + capName;
if ( name in style ) {
return name;
}
}
return origName;
}
function isHidden( elem, el ) {
elem = el || elem;
return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem );
}
function showHide( elements, show ) {
var elem, display,
values = [],
index = 0,
length = elements.length;
for ( ; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
values[ index ] = jQuery._data( elem, "olddisplay" );
if ( show ) {
// Reset the inline display of this element to learn if it is
// being hidden by cascaded rules or not
if ( !values[ index ] && elem.style.display === "none" ) {
elem.style.display = "";
}
// Set elements which have been overridden with display: none
// in a stylesheet to whatever the default browser style is
// for such an element
if ( elem.style.display === "" && isHidden( elem ) ) {
values[ index ] = jQuery._data( elem, "olddisplay", css_defaultDisplay(elem.nodeName) );
}
} else {
display = curCSS( elem, "display" );
if ( !values[ index ] && display !== "none" ) {
jQuery._data( elem, "olddisplay", display );
}
}
}
// Set the display of most of the elements in a second loop
// to avoid the constant reflow
for ( index = 0; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
if ( !show || elem.style.display === "none" || elem.style.display === "" ) {
elem.style.display = show ? values[ index ] || "" : "none";
}
}
return elements;
}
jQuery.fn.extend({
css: function( name, value ) {
return jQuery.access( this, function( elem, name, value ) {
return value !== undefined ?
jQuery.style( elem, name, value ) :
jQuery.css( elem, name );
}, name, value, arguments.length > 1 );
},
show: function() {
return showHide( this, true );
},
hide: function() {
return showHide( this );
},
toggle: function( state, fn2 ) {
var bool = typeof state === "boolean";
if ( jQuery.isFunction( state ) && jQuery.isFunction( fn2 ) ) {
return eventsToggle.apply( this, arguments );
}
return this.each(function() {
if ( bool ? state : isHidden( this ) ) {
jQuery( this ).show();
} else {
jQuery( this ).hide();
}
});
}
});
jQuery.extend({
// Add in style property hooks for overriding the default
// behavior of getting and setting a style property
cssHooks: {
opacity: {
get: function( elem, computed ) {
if ( computed ) {
// We should always get a number back from opacity
var ret = curCSS( elem, "opacity" );
return ret === "" ? "1" : ret;
}
}
}
},
// Exclude the following css properties to add px
cssNumber: {
"fillOpacity": true,
"fontWeight": true,
"lineHeight": true,
"opacity": true,
"orphans": true,
"widows": true,
"zIndex": true,
"zoom": true
},
// Add in properties whose names you wish to fix before
// setting or getting the value
cssProps: {
// normalize float css property
"float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat"
},
// Get and set the style property on a DOM Node
style: function( elem, name, value, extra ) {
// Don't set styles on text and comment nodes
if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
return;
}
// Make sure that we're working with the right name
var ret, type, hooks,
origName = jQuery.camelCase( name ),
style = elem.style;
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// Check if we're setting a value
if ( value !== undefined ) {
type = typeof value;
// convert relative number strings (+= or -=) to relative numbers. #7345
if ( type === "string" && (ret = rrelNum.exec( value )) ) {
value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) );
// Fixes bug #9237
type = "number";
}
// Make sure that NaN and null values aren't set. See: #7116
if ( value == null || type === "number" && isNaN( value ) ) {
return;
}
// If a number was passed in, add 'px' to the (except for certain CSS properties)
if ( type === "number" && !jQuery.cssNumber[ origName ] ) {
value += "px";
}
// If a hook was provided, use that value, otherwise just set the specified value
if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) {
// Wrapped to prevent IE from throwing errors when 'invalid' values are provided
// Fixes bug #5509
try {
style[ name ] = value;
} catch(e) {}
}
} else {
// If a hook was provided get the non-computed value from there
if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) {
return ret;
}
// Otherwise just get the value from the style object
return style[ name ];
}
},
css: function( elem, name, numeric, extra ) {
var val, num, hooks,
origName = jQuery.camelCase( name );
// Make sure that we're working with the right name
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// If a hook was provided get the computed value from there
if ( hooks && "get" in hooks ) {
val = hooks.get( elem, true, extra );
}
// Otherwise, if a way to get the computed value exists, use that
if ( val === undefined ) {
val = curCSS( elem, name );
}
//convert "normal" to computed value
if ( val === "normal" && name in cssNormalTransform ) {
val = cssNormalTransform[ name ];
}
// Return, converting to number if forced or a qualifier was provided and val looks numeric
if ( numeric || extra !== undefined ) {
num = parseFloat( val );
return numeric || jQuery.isNumeric( num ) ? num || 0 : val;
}
return val;
},
// A method for quickly swapping in/out CSS properties to get correct calculations
swap: function( elem, options, callback ) {
var ret, name,
old = {};
// Remember the old values, and insert the new ones
for ( name in options ) {
old[ name ] = elem.style[ name ];
elem.style[ name ] = options[ name ];
}
ret = callback.call( elem );
// Revert the old values
for ( name in options ) {
elem.style[ name ] = old[ name ];
}
return ret;
}
});
// NOTE: To any future maintainer, we've window.getComputedStyle
// because jsdom on node.js will break without it.
if ( window.getComputedStyle ) {
curCSS = function( elem, name ) {
var ret, width, minWidth, maxWidth,
computed = window.getComputedStyle( elem, null ),
style = elem.style;
if ( computed ) {
// getPropertyValue is only needed for .css('filter') in IE9, see #12537
ret = computed.getPropertyValue( name ) || computed[ name ];
if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) {
ret = jQuery.style( elem, name );
}
// A tribute to the "awesome hack by Dean Edwards"
// Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right
// Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels
// this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values
if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) {
width = style.width;
minWidth = style.minWidth;
maxWidth = style.maxWidth;
style.minWidth = style.maxWidth = style.width = ret;
ret = computed.width;
style.width = width;
style.minWidth = minWidth;
style.maxWidth = maxWidth;
}
}
return ret;
};
} else if ( document.documentElement.currentStyle ) {
curCSS = function( elem, name ) {
var left, rsLeft,
ret = elem.currentStyle && elem.currentStyle[ name ],
style = elem.style;
// Avoid setting ret to empty string here
// so we don't default to auto
if ( ret == null && style && style[ name ] ) {
ret = style[ name ];
}
// From the awesome hack by Dean Edwards
// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
// If we're not dealing with a regular pixel number
// but a number that has a weird ending, we need to convert it to pixels
// but not position css attributes, as those are proportional to the parent element instead
// and we can't measure the parent instead because it might trigger a "stacking dolls" problem
if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) {
// Remember the original values
left = style.left;
rsLeft = elem.runtimeStyle && elem.runtimeStyle.left;
// Put in the new values to get a computed value out
if ( rsLeft ) {
elem.runtimeStyle.left = elem.currentStyle.left;
}
style.left = name === "fontSize" ? "1em" : ret;
ret = style.pixelLeft + "px";
// Revert the changed values
style.left = left;
if ( rsLeft ) {
elem.runtimeStyle.left = rsLeft;
}
}
return ret === "" ? "auto" : ret;
};
}
function setPositiveNumber( elem, value, subtract ) {
var matches = rnumsplit.exec( value );
return matches ?
Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) :
value;
}
function augmentWidthOrHeight( elem, name, extra, isBorderBox ) {
var i = extra === ( isBorderBox ? "border" : "content" ) ?
// If we already have the right measurement, avoid augmentation
4 :
// Otherwise initialize for horizontal or vertical properties
name === "width" ? 1 : 0,
val = 0;
for ( ; i < 4; i += 2 ) {
// both box models exclude margin, so add it if we want it
if ( extra === "margin" ) {
// we use jQuery.css instead of curCSS here
// because of the reliableMarginRight CSS hook!
val += jQuery.css( elem, extra + cssExpand[ i ], true );
}
// From this point on we use curCSS for maximum performance (relevant in animations)
if ( isBorderBox ) {
// border-box includes padding, so remove it if we want content
if ( extra === "content" ) {
val -= parseFloat( curCSS( elem, "padding" + cssExpand[ i ] ) ) || 0;
}
// at this point, extra isn't border nor margin, so remove border
if ( extra !== "margin" ) {
val -= parseFloat( curCSS( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0;
}
} else {
// at this point, extra isn't content, so add padding
val += parseFloat( curCSS( elem, "padding" + cssExpand[ i ] ) ) || 0;
// at this point, extra isn't content nor padding, so add border
if ( extra !== "padding" ) {
val += parseFloat( curCSS( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0;
}
}
}
return val;
}
function getWidthOrHeight( elem, name, extra ) {
// Start with offset property, which is equivalent to the border-box value
var val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
valueIsBorderBox = true,
isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing" ) === "border-box";
// some non-html elements return undefined for offsetWidth, so check for null/undefined
// svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285
// MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668
if ( val <= 0 || val == null ) {
// Fall back to computed then uncomputed css if necessary
val = curCSS( elem, name );
if ( val < 0 || val == null ) {
val = elem.style[ name ];
}
// Computed unit is not pixels. Stop here and return.
if ( rnumnonpx.test(val) ) {
return val;
}
// we need the check for style in case a browser which returns unreliable values
// for getComputedStyle silently falls back to the reliable elem.style
valueIsBorderBox = isBorderBox && ( jQuery.support.boxSizingReliable || val === elem.style[ name ] );
// Normalize "", auto, and prepare for extra
val = parseFloat( val ) || 0;
}
// use the active box-sizing model to add/subtract irrelevant styles
return ( val +
augmentWidthOrHeight(
elem,
name,
extra || ( isBorderBox ? "border" : "content" ),
valueIsBorderBox
)
) + "px";
}
// Try to determine the default display value of an element
function css_defaultDisplay( nodeName ) {
if ( elemdisplay[ nodeName ] ) {
return elemdisplay[ nodeName ];
}
var elem = jQuery( "<" + nodeName + ">" ).appendTo( document.body ),
display = elem.css("display");
elem.remove();
// If the simple way fails,
// get element's real default display by attaching it to a temp iframe
if ( display === "none" || display === "" ) {
// Use the already-created iframe if possible
iframe = document.body.appendChild(
iframe || jQuery.extend( document.createElement("iframe"), {
frameBorder: 0,
width: 0,
height: 0
})
);
// Create a cacheable copy of the iframe document on first call.
// IE and Opera will allow us to reuse the iframeDoc without re-writing the fake HTML
// document to it; WebKit & Firefox won't allow reusing the iframe document.
if ( !iframeDoc || !iframe.createElement ) {
iframeDoc = ( iframe.contentWindow || iframe.contentDocument ).document;
iframeDoc.write("<!doctype html><html><body>");
iframeDoc.close();
}
elem = iframeDoc.body.appendChild( iframeDoc.createElement(nodeName) );
display = curCSS( elem, "display" );
document.body.removeChild( iframe );
}
// Store the correct default display
elemdisplay[ nodeName ] = display;
return display;
}
jQuery.each([ "height", "width" ], function( i, name ) {
jQuery.cssHooks[ name ] = {
get: function( elem, computed, extra ) {
if ( computed ) {
// certain elements can have dimension info if we invisibly show them
// however, it must have a current display style that would benefit from this
if ( elem.offsetWidth === 0 && rdisplayswap.test( curCSS( elem, "display" ) ) ) {
return jQuery.swap( elem, cssShow, function() {
return getWidthOrHeight( elem, name, extra );
});
} else {
return getWidthOrHeight( elem, name, extra );
}
}
},
set: function( elem, value, extra ) {
return setPositiveNumber( elem, value, extra ?
augmentWidthOrHeight(
elem,
name,
extra,
jQuery.support.boxSizing && jQuery.css( elem, "boxSizing" ) === "border-box"
) : 0
);
}
};
});
if ( !jQuery.support.opacity ) {
jQuery.cssHooks.opacity = {
get: function( elem, computed ) {
// IE uses filters for opacity
return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ?
( 0.01 * parseFloat( RegExp.$1 ) ) + "" :
computed ? "1" : "";
},
set: function( elem, value ) {
var style = elem.style,
currentStyle = elem.currentStyle,
opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "",
filter = currentStyle && currentStyle.filter || style.filter || "";
// IE has trouble with opacity if it does not have layout
// Force it by setting the zoom level
style.zoom = 1;
// if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652
if ( value >= 1 && jQuery.trim( filter.replace( ralpha, "" ) ) === "" &&
style.removeAttribute ) {
// Setting style.filter to null, "" & " " still leave "filter:" in the cssText
// if "filter:" is present at all, clearType is disabled, we want to avoid this
// style.removeAttribute is IE Only, but so apparently is this code path...
style.removeAttribute( "filter" );
// if there there is no filter style applied in a css rule, we are done
if ( currentStyle && !currentStyle.filter ) {
return;
}
}
// otherwise, set new filter values
style.filter = ralpha.test( filter ) ?
filter.replace( ralpha, opacity ) :
filter + " " + opacity;
}
};
}
// These hooks cannot be added until DOM ready because the support test
// for it is not run until after DOM ready
jQuery(function() {
if ( !jQuery.support.reliableMarginRight ) {
jQuery.cssHooks.marginRight = {
get: function( elem, computed ) {
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
// Work around by temporarily setting element display to inline-block
return jQuery.swap( elem, { "display": "inline-block" }, function() {
if ( computed ) {
return curCSS( elem, "marginRight" );
}
});
}
};
}
// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
// getComputedStyle returns percent when specified for top/left/bottom/right
// rather than make the css module depend on the offset module, we just check for it here
if ( !jQuery.support.pixelPosition && jQuery.fn.position ) {
jQuery.each( [ "top", "left" ], function( i, prop ) {
jQuery.cssHooks[ prop ] = {
get: function( elem, computed ) {
if ( computed ) {
var ret = curCSS( elem, prop );
// if curCSS returns percentage, fallback to offset
return rnumnonpx.test( ret ) ? jQuery( elem ).position()[ prop ] + "px" : ret;
}
}
};
});
}
});
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.hidden = function( elem ) {
return ( elem.offsetWidth === 0 && elem.offsetHeight === 0 ) || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || curCSS( elem, "display" )) === "none");
};
jQuery.expr.filters.visible = function( elem ) {
return !jQuery.expr.filters.hidden( elem );
};
}
// These hooks are used by animate to expand properties
jQuery.each({
margin: "",
padding: "",
border: "Width"
}, function( prefix, suffix ) {
jQuery.cssHooks[ prefix + suffix ] = {
expand: function( value ) {
var i,
// assumes a single number if not a string
parts = typeof value === "string" ? value.split(" ") : [ value ],
expanded = {};
for ( i = 0; i < 4; i++ ) {
expanded[ prefix + cssExpand[ i ] + suffix ] =
parts[ i ] || parts[ i - 2 ] || parts[ 0 ];
}
return expanded;
}
};
if ( !rmargin.test( prefix ) ) {
jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber;
}
});
var r20 = /%20/g,
rbracket = /\[\]$/,
rCRLF = /\r?\n/g,
rinput = /^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,
rselectTextarea = /^(?:select|textarea)/i;
jQuery.fn.extend({
serialize: function() {
return jQuery.param( this.serializeArray() );
},
serializeArray: function() {
return this.map(function(){
return this.elements ? jQuery.makeArray( this.elements ) : this;
})
.filter(function(){
return this.name && !this.disabled &&
( this.checked || rselectTextarea.test( this.nodeName ) ||
rinput.test( this.type ) );
})
.map(function( i, elem ){
var val = jQuery( this ).val();
return val == null ?
null :
jQuery.isArray( val ) ?
jQuery.map( val, function( val, i ){
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}) :
{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}).get();
}
});
//Serialize an array of form elements or a set of
//key/values into a query string
jQuery.param = function( a, traditional ) {
var prefix,
s = [],
add = function( key, value ) {
// If value is a function, invoke it and return its value
value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value );
s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
};
// Set traditional to true for jQuery <= 1.3.2 behavior.
if ( traditional === undefined ) {
traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional;
}
// If an array was passed in, assume that it is an array of form elements.
if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
// Serialize the form elements
jQuery.each( a, function() {
add( this.name, this.value );
});
} else {
// If traditional, encode the "old" way (the way 1.3.2 or older
// did it), otherwise encode params recursively.
for ( prefix in a ) {
buildParams( prefix, a[ prefix ], traditional, add );
}
}
// Return the resulting serialization
return s.join( "&" ).replace( r20, "+" );
};
function buildParams( prefix, obj, traditional, add ) {
var name;
if ( jQuery.isArray( obj ) ) {
// Serialize array item.
jQuery.each( obj, function( i, v ) {
if ( traditional || rbracket.test( prefix ) ) {
// Treat each array item as a scalar.
add( prefix, v );
} else {
// If array item is non-scalar (array or object), encode its
// numeric index to resolve deserialization ambiguity issues.
// Note that rack (as of 1.0.0) can't currently deserialize
// nested arrays properly, and attempting to do so may cause
// a server error. Possible fixes are to modify rack's
// deserialization algorithm or to provide an option or flag
// to force array serialization to be shallow.
buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add );
}
});
} else if ( !traditional && jQuery.type( obj ) === "object" ) {
// Serialize object item.
for ( name in obj ) {
buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
}
} else {
// Serialize scalar item.
add( prefix, obj );
}
}
var
// Document location
ajaxLocParts,
ajaxLocation,
rhash = /#.*$/,
rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL
// #7653, #8125, #8152: local protocol detection
rlocalProtocol = /^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,
rnoContent = /^(?:GET|HEAD)$/,
rprotocol = /^\/\//,
rquery = /\?/,
rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
rts = /([?&])_=[^&]*/,
rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,
// Keep a copy of the old load method
_load = jQuery.fn.load,
/* Prefilters
* 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
* 2) These are called:
* - BEFORE asking for a transport
* - AFTER param serialization (s.data is a string if s.processData is true)
* 3) key is the dataType
* 4) the catchall symbol "*" can be used
* 5) execution will start with transport dataType and THEN continue down to "*" if needed
*/
prefilters = {},
/* Transports bindings
* 1) key is the dataType
* 2) the catchall symbol "*" can be used
* 3) selection will start with transport dataType and THEN go to "*" if needed
*/
transports = {},
// Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
allTypes = ["*/"] + ["*"];
// #8138, IE may throw an exception when accessing
// a field from window.location if document.domain has been set
try {
ajaxLocation = location.href;
} catch( e ) {
// Use the href attribute of an A element
// since IE will modify it given document.location
ajaxLocation = document.createElement( "a" );
ajaxLocation.href = "";
ajaxLocation = ajaxLocation.href;
}
// Segment location into parts
ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || [];
// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
function addToPrefiltersOrTransports( structure ) {
// dataTypeExpression is optional and defaults to "*"
return function( dataTypeExpression, func ) {
if ( typeof dataTypeExpression !== "string" ) {
func = dataTypeExpression;
dataTypeExpression = "*";
}
var dataType, list, placeBefore,
dataTypes = dataTypeExpression.toLowerCase().split( core_rspace ),
i = 0,
length = dataTypes.length;
if ( jQuery.isFunction( func ) ) {
// For each dataType in the dataTypeExpression
for ( ; i < length; i++ ) {
dataType = dataTypes[ i ];
// We control if we're asked to add before
// any existing element
placeBefore = /^\+/.test( dataType );
if ( placeBefore ) {
dataType = dataType.substr( 1 ) || "*";
}
list = structure[ dataType ] = structure[ dataType ] || [];
// then we add to the structure accordingly
list[ placeBefore ? "unshift" : "push" ]( func );
}
}
};
}
// Base inspection function for prefilters and transports
function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR,
dataType /* internal */, inspected /* internal */ ) {
dataType = dataType || options.dataTypes[ 0 ];
inspected = inspected || {};
inspected[ dataType ] = true;
var selection,
list = structure[ dataType ],
i = 0,
length = list ? list.length : 0,
executeOnly = ( structure === prefilters );
for ( ; i < length && ( executeOnly || !selection ); i++ ) {
selection = list[ i ]( options, originalOptions, jqXHR );
// If we got redirected to another dataType
// we try there if executing only and not done already
if ( typeof selection === "string" ) {
if ( !executeOnly || inspected[ selection ] ) {
selection = undefined;
} else {
options.dataTypes.unshift( selection );
selection = inspectPrefiltersOrTransports(
structure, options, originalOptions, jqXHR, selection, inspected );
}
}
}
// If we're only executing or nothing was selected
// we try the catchall dataType if not done already
if ( ( executeOnly || !selection ) && !inspected[ "*" ] ) {
selection = inspectPrefiltersOrTransports(
structure, options, originalOptions, jqXHR, "*", inspected );
}
// unnecessary when only executing (prefilters)
// but it'll be ignored by the caller in that case
return selection;
}
// A special extend for ajax options
// that takes "flat" options (not to be deep extended)
// Fixes #9887
function ajaxExtend( target, src ) {
var key, deep,
flatOptions = jQuery.ajaxSettings.flatOptions || {};
for ( key in src ) {
if ( src[ key ] !== undefined ) {
( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ];
}
}
if ( deep ) {
jQuery.extend( true, target, deep );
}
}
jQuery.fn.load = function( url, params, callback ) {
if ( typeof url !== "string" && _load ) {
return _load.apply( this, arguments );
}
// Don't do a request if no elements are being requested
if ( !this.length ) {
return this;
}
var selector, type, response,
self = this,
off = url.indexOf(" ");
if ( off >= 0 ) {
selector = url.slice( off, url.length );
url = url.slice( 0, off );
}
// If it's a function
if ( jQuery.isFunction( params ) ) {
// We assume that it's the callback
callback = params;
params = undefined;
// Otherwise, build a param string
} else if ( params && typeof params === "object" ) {
type = "POST";
}
// Request the remote document
jQuery.ajax({
url: url,
// if "type" variable is undefined, then "GET" method will be used
type: type,
dataType: "html",
data: params,
complete: function( jqXHR, status ) {
if ( callback ) {
self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] );
}
}
}).done(function( responseText ) {
// Save response for use in complete callback
response = arguments;
// See if a selector was specified
self.html( selector ?
// Create a dummy div to hold the results
jQuery("<div>")
// inject the contents of the document in, removing the scripts
// to avoid any 'Permission Denied' errors in IE
.append( responseText.replace( rscript, "" ) )
// Locate the specified elements
.find( selector ) :
// If not, just inject the full result
responseText );
});
return this;
};
// Attach a bunch of functions for handling common AJAX events
jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){
jQuery.fn[ o ] = function( f ){
return this.on( o, f );
};
});
jQuery.each( [ "get", "post" ], function( i, method ) {
jQuery[ method ] = function( url, data, callback, type ) {
// shift arguments if data argument was omitted
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = undefined;
}
return jQuery.ajax({
type: method,
url: url,
data: data,
success: callback,
dataType: type
});
};
});
jQuery.extend({
getScript: function( url, callback ) {
return jQuery.get( url, undefined, callback, "script" );
},
getJSON: function( url, data, callback ) {
return jQuery.get( url, data, callback, "json" );
},
// Creates a full fledged settings object into target
// with both ajaxSettings and settings fields.
// If target is omitted, writes into ajaxSettings.
ajaxSetup: function( target, settings ) {
if ( settings ) {
// Building a settings object
ajaxExtend( target, jQuery.ajaxSettings );
} else {
// Extending ajaxSettings
settings = target;
target = jQuery.ajaxSettings;
}
ajaxExtend( target, settings );
return target;
},
ajaxSettings: {
url: ajaxLocation,
isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
global: true,
type: "GET",
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
processData: true,
async: true,
/*
timeout: 0,
data: null,
dataType: null,
username: null,
password: null,
cache: null,
throws: false,
traditional: false,
headers: {},
*/
accepts: {
xml: "application/xml, text/xml",
html: "text/html",
text: "text/plain",
json: "application/json, text/javascript",
"*": allTypes
},
contents: {
xml: /xml/,
html: /html/,
json: /json/
},
responseFields: {
xml: "responseXML",
text: "responseText"
},
// List of data converters
// 1) key format is "source_type destination_type" (a single space in-between)
// 2) the catchall symbol "*" can be used for source_type
converters: {
// Convert anything to text
"* text": window.String,
// Text to html (true = no transformation)
"text html": true,
// Evaluate text as a json expression
"text json": jQuery.parseJSON,
// Parse text as xml
"text xml": jQuery.parseXML
},
// For options that shouldn't be deep extended:
// you can add your own custom options here if
// and when you create one that shouldn't be
// deep extended (see ajaxExtend)
flatOptions: {
context: true,
url: true
}
},
ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
ajaxTransport: addToPrefiltersOrTransports( transports ),
// Main method
ajax: function( url, options ) {
// If url is an object, simulate pre-1.5 signature
if ( typeof url === "object" ) {
options = url;
url = undefined;
}
// Force options to be an object
options = options || {};
var // ifModified key
ifModifiedKey,
// Response headers
responseHeadersString,
responseHeaders,
// transport
transport,
// timeout handle
timeoutTimer,
// Cross-domain detection vars
parts,
// To know if global events are to be dispatched
fireGlobals,
// Loop variable
i,
// Create the final options object
s = jQuery.ajaxSetup( {}, options ),
// Callbacks context
callbackContext = s.context || s,
// Context for global events
// It's the callbackContext if one was provided in the options
// and if it's a DOM node or a jQuery collection
globalEventContext = callbackContext !== s &&
( callbackContext.nodeType || callbackContext instanceof jQuery ) ?
jQuery( callbackContext ) : jQuery.event,
// Deferreds
deferred = jQuery.Deferred(),
completeDeferred = jQuery.Callbacks( "once memory" ),
// Status-dependent callbacks
statusCode = s.statusCode || {},
// Headers (they are sent all at once)
requestHeaders = {},
requestHeadersNames = {},
// The jqXHR state
state = 0,
// Default abort message
strAbort = "canceled",
// Fake xhr
jqXHR = {
readyState: 0,
// Caches the header
setRequestHeader: function( name, value ) {
if ( !state ) {
var lname = name.toLowerCase();
name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
requestHeaders[ name ] = value;
}
return this;
},
// Raw string
getAllResponseHeaders: function() {
return state === 2 ? responseHeadersString : null;
},
// Builds headers hashtable if needed
getResponseHeader: function( key ) {
var match;
if ( state === 2 ) {
if ( !responseHeaders ) {
responseHeaders = {};
while( ( match = rheaders.exec( responseHeadersString ) ) ) {
responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
}
}
match = responseHeaders[ key.toLowerCase() ];
}
return match === undefined ? null : match;
},
// Overrides response content-type header
overrideMimeType: function( type ) {
if ( !state ) {
s.mimeType = type;
}
return this;
},
// Cancel the request
abort: function( statusText ) {
statusText = statusText || strAbort;
if ( transport ) {
transport.abort( statusText );
}
done( 0, statusText );
return this;
}
};
// Callback for when everything is done
// It is defined here because jslint complains if it is declared
// at the end of the function (which would be more logical and readable)
function done( status, nativeStatusText, responses, headers ) {
var isSuccess, success, error, response, modified,
statusText = nativeStatusText;
// Called once
if ( state === 2 ) {
return;
}
// State is "done" now
state = 2;
// Clear timeout if it exists
if ( timeoutTimer ) {
clearTimeout( timeoutTimer );
}
// Dereference transport for early garbage collection
// (no matter how long the jqXHR object will be used)
transport = undefined;
// Cache response headers
responseHeadersString = headers || "";
// Set readyState
jqXHR.readyState = status > 0 ? 4 : 0;
// Get response data
if ( responses ) {
response = ajaxHandleResponses( s, jqXHR, responses );
}
// If successful, handle type chaining
if ( status >= 200 && status < 300 || status === 304 ) {
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
modified = jqXHR.getResponseHeader("Last-Modified");
if ( modified ) {
jQuery.lastModified[ ifModifiedKey ] = modified;
}
modified = jqXHR.getResponseHeader("Etag");
if ( modified ) {
jQuery.etag[ ifModifiedKey ] = modified;
}
}
// If not modified
if ( status === 304 ) {
statusText = "notmodified";
isSuccess = true;
// If we have data
} else {
isSuccess = ajaxConvert( s, response );
statusText = isSuccess.state;
success = isSuccess.data;
error = isSuccess.error;
isSuccess = !error;
}
} else {
// We extract error from statusText
// then normalize statusText and status for non-aborts
error = statusText;
if ( !statusText || status ) {
statusText = "error";
if ( status < 0 ) {
status = 0;
}
}
}
// Set data for the fake xhr object
jqXHR.status = status;
jqXHR.statusText = ( nativeStatusText || statusText ) + "";
// Success/Error
if ( isSuccess ) {
deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
} else {
deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
}
// Status-dependent callbacks
jqXHR.statusCode( statusCode );
statusCode = undefined;
if ( fireGlobals ) {
globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ),
[ jqXHR, s, isSuccess ? success : error ] );
}
// Complete
completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );
// Handle the global AJAX counter
if ( !( --jQuery.active ) ) {
jQuery.event.trigger( "ajaxStop" );
}
}
}
// Attach deferreds
deferred.promise( jqXHR );
jqXHR.success = jqXHR.done;
jqXHR.error = jqXHR.fail;
jqXHR.complete = completeDeferred.add;
// Status-dependent callbacks
jqXHR.statusCode = function( map ) {
if ( map ) {
var tmp;
if ( state < 2 ) {
for ( tmp in map ) {
statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ];
}
} else {
tmp = map[ jqXHR.status ];
jqXHR.always( tmp );
}
}
return this;
};
// Remove hash character (#7531: and string promotion)
// Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
// We also use the url parameter if available
s.url = ( ( url || s.url ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" );
// Extract dataTypes list
s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( core_rspace );
// A cross-domain request is in order when we have a protocol:host:port mismatch
if ( s.crossDomain == null ) {
parts = rurl.exec( s.url.toLowerCase() );
s.crossDomain = !!( parts &&
( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] ||
( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) !=
( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) )
);
}
// Convert data if not already a string
if ( s.data && s.processData && typeof s.data !== "string" ) {
s.data = jQuery.param( s.data, s.traditional );
}
// Apply prefilters
inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
// If request was aborted inside a prefilter, stop there
if ( state === 2 ) {
return jqXHR;
}
// We can fire global events as of now if asked to
fireGlobals = s.global;
// Uppercase the type
s.type = s.type.toUpperCase();
// Determine if request has content
s.hasContent = !rnoContent.test( s.type );
// Watch for a new set of requests
if ( fireGlobals && jQuery.active++ === 0 ) {
jQuery.event.trigger( "ajaxStart" );
}
// More options handling for requests with no content
if ( !s.hasContent ) {
// If data is available, append data to url
if ( s.data ) {
s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data;
// #9682: remove data so that it's not used in an eventual retry
delete s.data;
}
// Get ifModifiedKey before adding the anti-cache parameter
ifModifiedKey = s.url;
// Add anti-cache in url if needed
if ( s.cache === false ) {
var ts = jQuery.now(),
// try replacing _= if it is there
ret = s.url.replace( rts, "$1_=" + ts );
// if nothing was replaced, add timestamp to the end
s.url = ret + ( ( ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" );
}
}
// Set the correct header, if data is being sent
if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
jqXHR.setRequestHeader( "Content-Type", s.contentType );
}
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
ifModifiedKey = ifModifiedKey || s.url;
if ( jQuery.lastModified[ ifModifiedKey ] ) {
jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ ifModifiedKey ] );
}
if ( jQuery.etag[ ifModifiedKey ] ) {
jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ ifModifiedKey ] );
}
}
// Set the Accepts header for the server, depending on the dataType
jqXHR.setRequestHeader(
"Accept",
s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
s.accepts[ "*" ]
);
// Check for headers option
for ( i in s.headers ) {
jqXHR.setRequestHeader( i, s.headers[ i ] );
}
// Allow custom headers/mimetypes and early abort
if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) {
// Abort if not done already and return
return jqXHR.abort();
}
// aborting is no longer a cancellation
strAbort = "abort";
// Install callbacks on deferreds
for ( i in { success: 1, error: 1, complete: 1 } ) {
jqXHR[ i ]( s[ i ] );
}
// Get transport
transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
// If no transport, we auto-abort
if ( !transport ) {
done( -1, "No Transport" );
} else {
jqXHR.readyState = 1;
// Send global event
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
}
// Timeout
if ( s.async && s.timeout > 0 ) {
timeoutTimer = setTimeout( function(){
jqXHR.abort( "timeout" );
}, s.timeout );
}
try {
state = 1;
transport.send( requestHeaders, done );
} catch (e) {
// Propagate exception as error if not done
if ( state < 2 ) {
done( -1, e );
// Simply rethrow otherwise
} else {
throw e;
}
}
}
return jqXHR;
},
// Counter for holding the number of active queries
active: 0,
// Last-Modified header cache for next request
lastModified: {},
etag: {}
});
/* Handles responses to an ajax request:
* - sets all responseXXX fields accordingly
* - finds the right dataType (mediates between content-type and expected dataType)
* - returns the corresponding response
*/
function ajaxHandleResponses( s, jqXHR, responses ) {
var ct, type, finalDataType, firstDataType,
contents = s.contents,
dataTypes = s.dataTypes,
responseFields = s.responseFields;
// Fill responseXXX fields
for ( type in responseFields ) {
if ( type in responses ) {
jqXHR[ responseFields[type] ] = responses[ type ];
}
}
// Remove auto dataType and get content-type in the process
while( dataTypes[ 0 ] === "*" ) {
dataTypes.shift();
if ( ct === undefined ) {
ct = s.mimeType || jqXHR.getResponseHeader( "content-type" );
}
}
// Check if we're dealing with a known content-type
if ( ct ) {
for ( type in contents ) {
if ( contents[ type ] && contents[ type ].test( ct ) ) {
dataTypes.unshift( type );
break;
}
}
}
// Check to see if we have a response for the expected dataType
if ( dataTypes[ 0 ] in responses ) {
finalDataType = dataTypes[ 0 ];
} else {
// Try convertible dataTypes
for ( type in responses ) {
if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) {
finalDataType = type;
break;
}
if ( !firstDataType ) {
firstDataType = type;
}
}
// Or just use first one
finalDataType = finalDataType || firstDataType;
}
// If we found a dataType
// We add the dataType to the list if needed
// and return the corresponding response
if ( finalDataType ) {
if ( finalDataType !== dataTypes[ 0 ] ) {
dataTypes.unshift( finalDataType );
}
return responses[ finalDataType ];
}
}
// Chain conversions given the request and the original response
function ajaxConvert( s, response ) {
var conv, conv2, current, tmp,
// Work with a copy of dataTypes in case we need to modify it for conversion
dataTypes = s.dataTypes.slice(),
prev = dataTypes[ 0 ],
converters = {},
i = 0;
// Apply the dataFilter if provided
if ( s.dataFilter ) {
response = s.dataFilter( response, s.dataType );
}
// Create converters map with lowercased keys
if ( dataTypes[ 1 ] ) {
for ( conv in s.converters ) {
converters[ conv.toLowerCase() ] = s.converters[ conv ];
}
}
// Convert to each sequential dataType, tolerating list modification
for ( ; (current = dataTypes[++i]); ) {
// There's only work to do if current dataType is non-auto
if ( current !== "*" ) {
// Convert response if prev dataType is non-auto and differs from current
if ( prev !== "*" && prev !== current ) {
// Seek a direct converter
conv = converters[ prev + " " + current ] || converters[ "* " + current ];
// If none found, seek a pair
if ( !conv ) {
for ( conv2 in converters ) {
// If conv2 outputs current
tmp = conv2.split(" ");
if ( tmp[ 1 ] === current ) {
// If prev can be converted to accepted input
conv = converters[ prev + " " + tmp[ 0 ] ] ||
converters[ "* " + tmp[ 0 ] ];
if ( conv ) {
// Condense equivalence converters
if ( conv === true ) {
conv = converters[ conv2 ];
// Otherwise, insert the intermediate dataType
} else if ( converters[ conv2 ] !== true ) {
current = tmp[ 0 ];
dataTypes.splice( i--, 0, current );
}
break;
}
}
}
}
// Apply converter (if not an equivalence)
if ( conv !== true ) {
// Unless errors are allowed to bubble, catch and return them
if ( conv && s["throws"] ) {
response = conv( response );
} else {
try {
response = conv( response );
} catch ( e ) {
return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current };
}
}
}
}
// Update prev for next iteration
prev = current;
}
}
return { state: "success", data: response };
}
var oldCallbacks = [],
rquestion = /\?/,
rjsonp = /(=)\?(?=&|$)|\?\?/,
nonce = jQuery.now();
// Default jsonp settings
jQuery.ajaxSetup({
jsonp: "callback",
jsonpCallback: function() {
var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) );
this[ callback ] = true;
return callback;
}
});
// Detect, normalize options and install callbacks for jsonp requests
jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
var callbackName, overwritten, responseContainer,
data = s.data,
url = s.url,
hasCallback = s.jsonp !== false,
replaceInUrl = hasCallback && rjsonp.test( url ),
replaceInData = hasCallback && !replaceInUrl && typeof data === "string" &&
!( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") &&
rjsonp.test( data );
// Handle iff the expected data type is "jsonp" or we have a parameter to set
if ( s.dataTypes[ 0 ] === "jsonp" || replaceInUrl || replaceInData ) {
// Get callback name, remembering preexisting value associated with it
callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ?
s.jsonpCallback() :
s.jsonpCallback;
overwritten = window[ callbackName ];
// Insert callback into url or form data
if ( replaceInUrl ) {
s.url = url.replace( rjsonp, "$1" + callbackName );
} else if ( replaceInData ) {
s.data = data.replace( rjsonp, "$1" + callbackName );
} else if ( hasCallback ) {
s.url += ( rquestion.test( url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName;
}
// Use data converter to retrieve json after script execution
s.converters["script json"] = function() {
if ( !responseContainer ) {
jQuery.error( callbackName + " was not called" );
}
return responseContainer[ 0 ];
};
// force json dataType
s.dataTypes[ 0 ] = "json";
// Install callback
window[ callbackName ] = function() {
responseContainer = arguments;
};
// Clean-up function (fires after converters)
jqXHR.always(function() {
// Restore preexisting value
window[ callbackName ] = overwritten;
// Save back as free
if ( s[ callbackName ] ) {
// make sure that re-using the options doesn't screw things around
s.jsonpCallback = originalSettings.jsonpCallback;
// save the callback name for future use
oldCallbacks.push( callbackName );
}
// Call if it was a function and we have a response
if ( responseContainer && jQuery.isFunction( overwritten ) ) {
overwritten( responseContainer[ 0 ] );
}
responseContainer = overwritten = undefined;
});
// Delegate to script
return "script";
}
});
// Install script dataType
jQuery.ajaxSetup({
accepts: {
script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
},
contents: {
script: /javascript|ecmascript/
},
converters: {
"text script": function( text ) {
jQuery.globalEval( text );
return text;
}
}
});
// Handle cache's special case and global
jQuery.ajaxPrefilter( "script", function( s ) {
if ( s.cache === undefined ) {
s.cache = false;
}
if ( s.crossDomain ) {
s.type = "GET";
s.global = false;
}
});
// Bind script tag hack transport
jQuery.ajaxTransport( "script", function(s) {
// This transport only deals with cross domain requests
if ( s.crossDomain ) {
var script,
head = document.head || document.getElementsByTagName( "head" )[0] || document.documentElement;
return {
send: function( _, callback ) {
script = document.createElement( "script" );
script.async = "async";
if ( s.scriptCharset ) {
script.charset = s.scriptCharset;
}
script.src = s.url;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function( _, isAbort ) {
if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) {
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
// Remove the script
if ( head && script.parentNode ) {
head.removeChild( script );
}
// Dereference the script
script = undefined;
// Callback if not abort
if ( !isAbort ) {
callback( 200, "success" );
}
}
};
// Use insertBefore instead of appendChild to circumvent an IE6 bug.
// This arises when a base node is used (#2709 and #4378).
head.insertBefore( script, head.firstChild );
},
abort: function() {
if ( script ) {
script.onload( 0, 1 );
}
}
};
}
});
var xhrCallbacks,
// #5280: Internet Explorer will keep connections alive if we don't abort on unload
xhrOnUnloadAbort = window.ActiveXObject ? function() {
// Abort all pending requests
for ( var key in xhrCallbacks ) {
xhrCallbacks[ key ]( 0, 1 );
}
} : false,
xhrId = 0;
// Functions to create xhrs
function createStandardXHR() {
try {
return new window.XMLHttpRequest();
} catch( e ) {}
}
function createActiveXHR() {
try {
return new window.ActiveXObject( "Microsoft.XMLHTTP" );
} catch( e ) {}
}
// Create the request object
// (This is still attached to ajaxSettings for backward compatibility)
jQuery.ajaxSettings.xhr = window.ActiveXObject ?
/* Microsoft failed to properly
* implement the XMLHttpRequest in IE7 (can't request local files),
* so we use the ActiveXObject when it is available
* Additionally XMLHttpRequest can be disabled in IE7/IE8 so
* we need a fallback.
*/
function() {
return !this.isLocal && createStandardXHR() || createActiveXHR();
} :
// For all other browsers, use the standard XMLHttpRequest object
createStandardXHR;
// Determine support properties
(function( xhr ) {
jQuery.extend( jQuery.support, {
ajax: !!xhr,
cors: !!xhr && ( "withCredentials" in xhr )
});
})( jQuery.ajaxSettings.xhr() );
// Create transport if the browser can provide an xhr
if ( jQuery.support.ajax ) {
jQuery.ajaxTransport(function( s ) {
// Cross domain only allowed if supported through XMLHttpRequest
if ( !s.crossDomain || jQuery.support.cors ) {
var callback;
return {
send: function( headers, complete ) {
// Get a new xhr
var handle, i,
xhr = s.xhr();
// Open the socket
// Passing null username, generates a login popup on Opera (#2865)
if ( s.username ) {
xhr.open( s.type, s.url, s.async, s.username, s.password );
} else {
xhr.open( s.type, s.url, s.async );
}
// Apply custom fields if provided
if ( s.xhrFields ) {
for ( i in s.xhrFields ) {
xhr[ i ] = s.xhrFields[ i ];
}
}
// Override mime type if needed
if ( s.mimeType && xhr.overrideMimeType ) {
xhr.overrideMimeType( s.mimeType );
}
// X-Requested-With header
// For cross-domain requests, seeing as conditions for a preflight are
// akin to a jigsaw puzzle, we simply never set it to be sure.
// (it can always be set on a per-request basis or even using ajaxSetup)
// For same-domain requests, won't change header if already provided.
if ( !s.crossDomain && !headers["X-Requested-With"] ) {
headers[ "X-Requested-With" ] = "XMLHttpRequest";
}
// Need an extra try/catch for cross domain requests in Firefox 3
try {
for ( i in headers ) {
xhr.setRequestHeader( i, headers[ i ] );
}
} catch( _ ) {}
// Do send the request
// This may raise an exception which is actually
// handled in jQuery.ajax (so no try/catch here)
xhr.send( ( s.hasContent && s.data ) || null );
// Listener
callback = function( _, isAbort ) {
var status,
statusText,
responseHeaders,
responses,
xml;
// Firefox throws exceptions when accessing properties
// of an xhr when a network error occurred
// http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE)
try {
// Was never called and is aborted or complete
if ( callback && ( isAbort || xhr.readyState === 4 ) ) {
// Only called once
callback = undefined;
// Do not keep as active anymore
if ( handle ) {
xhr.onreadystatechange = jQuery.noop;
if ( xhrOnUnloadAbort ) {
delete xhrCallbacks[ handle ];
}
}
// If it's an abort
if ( isAbort ) {
// Abort it manually if needed
if ( xhr.readyState !== 4 ) {
xhr.abort();
}
} else {
status = xhr.status;
responseHeaders = xhr.getAllResponseHeaders();
responses = {};
xml = xhr.responseXML;
// Construct response list
if ( xml && xml.documentElement /* #4958 */ ) {
responses.xml = xml;
}
// When requesting binary data, IE6-9 will throw an exception
// on any attempt to access responseText (#11426)
try {
responses.text = xhr.responseText;
} catch( e ) {
}
// Firefox throws an exception when accessing
// statusText for faulty cross-domain requests
try {
statusText = xhr.statusText;
} catch( e ) {
// We normalize with Webkit giving an empty statusText
statusText = "";
}
// Filter status for non standard behaviors
// If the request is local and we have data: assume a success
// (success with no data won't get notified, that's the best we
// can do given current implementations)
if ( !status && s.isLocal && !s.crossDomain ) {
status = responses.text ? 200 : 404;
// IE - #1450: sometimes returns 1223 when it should be 204
} else if ( status === 1223 ) {
status = 204;
}
}
}
} catch( firefoxAccessException ) {
if ( !isAbort ) {
complete( -1, firefoxAccessException );
}
}
// Call complete if needed
if ( responses ) {
complete( status, statusText, responses, responseHeaders );
}
};
if ( !s.async ) {
// if we're in sync mode we fire the callback
callback();
} else if ( xhr.readyState === 4 ) {
// (IE6 & IE7) if it's in cache and has been
// retrieved directly we need to fire the callback
setTimeout( callback, 0 );
} else {
handle = ++xhrId;
if ( xhrOnUnloadAbort ) {
// Create the active xhrs callbacks list if needed
// and attach the unload handler
if ( !xhrCallbacks ) {
xhrCallbacks = {};
jQuery( window ).unload( xhrOnUnloadAbort );
}
// Add to list of active xhrs callbacks
xhrCallbacks[ handle ] = callback;
}
xhr.onreadystatechange = callback;
}
},
abort: function() {
if ( callback ) {
callback(0,1);
}
}
};
}
});
}
var fxNow, timerId,
rfxtypes = /^(?:toggle|show|hide)$/,
rfxnum = new RegExp( "^(?:([-+])=|)(" + core_pnum + ")([a-z%]*)$", "i" ),
rrun = /queueHooks$/,
animationPrefilters = [ defaultPrefilter ],
tweeners = {
"*": [function( prop, value ) {
var end, unit,
tween = this.createTween( prop, value ),
parts = rfxnum.exec( value ),
target = tween.cur(),
start = +target || 0,
scale = 1,
maxIterations = 20;
if ( parts ) {
end = +parts[2];
unit = parts[3] || ( jQuery.cssNumber[ prop ] ? "" : "px" );
// We need to compute starting value
if ( unit !== "px" && start ) {
// Iteratively approximate from a nonzero starting point
// Prefer the current property, because this process will be trivial if it uses the same units
// Fallback to end or a simple constant
start = jQuery.css( tween.elem, prop, true ) || end || 1;
do {
// If previous iteration zeroed out, double until we get *something*
// Use a string for doubling factor so we don't accidentally see scale as unchanged below
scale = scale || ".5";
// Adjust and apply
start = start / scale;
jQuery.style( tween.elem, prop, start + unit );
// Update scale, tolerating zero or NaN from tween.cur()
// And breaking the loop if scale is unchanged or perfect, or if we've just had enough
} while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations );
}
tween.unit = unit;
tween.start = start;
// If a +=/-= token was provided, we're doing a relative animation
tween.end = parts[1] ? start + ( parts[1] + 1 ) * end : end;
}
return tween;
}]
};
// Animations created synchronously will run synchronously
function createFxNow() {
setTimeout(function() {
fxNow = undefined;
}, 0 );
return ( fxNow = jQuery.now() );
}
function createTweens( animation, props ) {
jQuery.each( props, function( prop, value ) {
var collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ),
index = 0,
length = collection.length;
for ( ; index < length; index++ ) {
if ( collection[ index ].call( animation, prop, value ) ) {
// we're done with this property
return;
}
}
});
}
function Animation( elem, properties, options ) {
var result,
index = 0,
tweenerIndex = 0,
length = animationPrefilters.length,
deferred = jQuery.Deferred().always( function() {
// don't match elem in the :animated selector
delete tick.elem;
}),
tick = function() {
var currentTime = fxNow || createFxNow(),
remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ),
// archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497)
temp = remaining / animation.duration || 0,
percent = 1 - temp,
index = 0,
length = animation.tweens.length;
for ( ; index < length ; index++ ) {
animation.tweens[ index ].run( percent );
}
deferred.notifyWith( elem, [ animation, percent, remaining ]);
if ( percent < 1 && length ) {
return remaining;
} else {
deferred.resolveWith( elem, [ animation ] );
return false;
}
},
animation = deferred.promise({
elem: elem,
props: jQuery.extend( {}, properties ),
opts: jQuery.extend( true, { specialEasing: {} }, options ),
originalProperties: properties,
originalOptions: options,
startTime: fxNow || createFxNow(),
duration: options.duration,
tweens: [],
createTween: function( prop, end, easing ) {
var tween = jQuery.Tween( elem, animation.opts, prop, end,
animation.opts.specialEasing[ prop ] || animation.opts.easing );
animation.tweens.push( tween );
return tween;
},
stop: function( gotoEnd ) {
var index = 0,
// if we are going to the end, we want to run all the tweens
// otherwise we skip this part
length = gotoEnd ? animation.tweens.length : 0;
for ( ; index < length ; index++ ) {
animation.tweens[ index ].run( 1 );
}
// resolve when we played the last frame
// otherwise, reject
if ( gotoEnd ) {
deferred.resolveWith( elem, [ animation, gotoEnd ] );
} else {
deferred.rejectWith( elem, [ animation, gotoEnd ] );
}
return this;
}
}),
props = animation.props;
propFilter( props, animation.opts.specialEasing );
for ( ; index < length ; index++ ) {
result = animationPrefilters[ index ].call( animation, elem, props, animation.opts );
if ( result ) {
return result;
}
}
createTweens( animation, props );
if ( jQuery.isFunction( animation.opts.start ) ) {
animation.opts.start.call( elem, animation );
}
jQuery.fx.timer(
jQuery.extend( tick, {
anim: animation,
queue: animation.opts.queue,
elem: elem
})
);
// attach callbacks from options
return animation.progress( animation.opts.progress )
.done( animation.opts.done, animation.opts.complete )
.fail( animation.opts.fail )
.always( animation.opts.always );
}
function propFilter( props, specialEasing ) {
var index, name, easing, value, hooks;
// camelCase, specialEasing and expand cssHook pass
for ( index in props ) {
name = jQuery.camelCase( index );
easing = specialEasing[ name ];
value = props[ index ];
if ( jQuery.isArray( value ) ) {
easing = value[ 1 ];
value = props[ index ] = value[ 0 ];
}
if ( index !== name ) {
props[ name ] = value;
delete props[ index ];
}
hooks = jQuery.cssHooks[ name ];
if ( hooks && "expand" in hooks ) {
value = hooks.expand( value );
delete props[ name ];
// not quite $.extend, this wont overwrite keys already present.
// also - reusing 'index' from above because we have the correct "name"
for ( index in value ) {
if ( !( index in props ) ) {
props[ index ] = value[ index ];
specialEasing[ index ] = easing;
}
}
} else {
specialEasing[ name ] = easing;
}
}
}
jQuery.Animation = jQuery.extend( Animation, {
tweener: function( props, callback ) {
if ( jQuery.isFunction( props ) ) {
callback = props;
props = [ "*" ];
} else {
props = props.split(" ");
}
var prop,
index = 0,
length = props.length;
for ( ; index < length ; index++ ) {
prop = props[ index ];
tweeners[ prop ] = tweeners[ prop ] || [];
tweeners[ prop ].unshift( callback );
}
},
prefilter: function( callback, prepend ) {
if ( prepend ) {
animationPrefilters.unshift( callback );
} else {
animationPrefilters.push( callback );
}
}
});
function defaultPrefilter( elem, props, opts ) {
var index, prop, value, length, dataShow, toggle, tween, hooks, oldfire,
anim = this,
style = elem.style,
orig = {},
handled = [],
hidden = elem.nodeType && isHidden( elem );
// handle queue: false promises
if ( !opts.queue ) {
hooks = jQuery._queueHooks( elem, "fx" );
if ( hooks.unqueued == null ) {
hooks.unqueued = 0;
oldfire = hooks.empty.fire;
hooks.empty.fire = function() {
if ( !hooks.unqueued ) {
oldfire();
}
};
}
hooks.unqueued++;
anim.always(function() {
// doing this makes sure that the complete handler will be called
// before this completes
anim.always(function() {
hooks.unqueued--;
if ( !jQuery.queue( elem, "fx" ).length ) {
hooks.empty.fire();
}
});
});
}
// height/width overflow pass
if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) {
// Make sure that nothing sneaks out
// Record all 3 overflow attributes because IE does not
// change the overflow attribute when overflowX and
// overflowY are set to the same value
opts.overflow = [ style.overflow, style.overflowX, style.overflowY ];
// Set display property to inline-block for height/width
// animations on inline elements that are having width/height animated
if ( jQuery.css( elem, "display" ) === "inline" &&
jQuery.css( elem, "float" ) === "none" ) {
// inline-level elements accept inline-block;
// block-level elements need to be inline with layout
if ( !jQuery.support.inlineBlockNeedsLayout || css_defaultDisplay( elem.nodeName ) === "inline" ) {
style.display = "inline-block";
} else {
style.zoom = 1;
}
}
}
if ( opts.overflow ) {
style.overflow = "hidden";
if ( !jQuery.support.shrinkWrapBlocks ) {
anim.done(function() {
style.overflow = opts.overflow[ 0 ];
style.overflowX = opts.overflow[ 1 ];
style.overflowY = opts.overflow[ 2 ];
});
}
}
// show/hide pass
for ( index in props ) {
value = props[ index ];
if ( rfxtypes.exec( value ) ) {
delete props[ index ];
toggle = toggle || value === "toggle";
if ( value === ( hidden ? "hide" : "show" ) ) {
continue;
}
handled.push( index );
}
}
length = handled.length;
if ( length ) {
dataShow = jQuery._data( elem, "fxshow" ) || jQuery._data( elem, "fxshow", {} );
if ( "hidden" in dataShow ) {
hidden = dataShow.hidden;
}
// store state if its toggle - enables .stop().toggle() to "reverse"
if ( toggle ) {
dataShow.hidden = !hidden;
}
if ( hidden ) {
jQuery( elem ).show();
} else {
anim.done(function() {
jQuery( elem ).hide();
});
}
anim.done(function() {
var prop;
jQuery.removeData( elem, "fxshow", true );
for ( prop in orig ) {
jQuery.style( elem, prop, orig[ prop ] );
}
});
for ( index = 0 ; index < length ; index++ ) {
prop = handled[ index ];
tween = anim.createTween( prop, hidden ? dataShow[ prop ] : 0 );
orig[ prop ] = dataShow[ prop ] || jQuery.style( elem, prop );
if ( !( prop in dataShow ) ) {
dataShow[ prop ] = tween.start;
if ( hidden ) {
tween.end = tween.start;
tween.start = prop === "width" || prop === "height" ? 1 : 0;
}
}
}
}
}
function Tween( elem, options, prop, end, easing ) {
return new Tween.prototype.init( elem, options, prop, end, easing );
}
jQuery.Tween = Tween;
Tween.prototype = {
constructor: Tween,
init: function( elem, options, prop, end, easing, unit ) {
this.elem = elem;
this.prop = prop;
this.easing = easing || "swing";
this.options = options;
this.start = this.now = this.cur();
this.end = end;
this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" );
},
cur: function() {
var hooks = Tween.propHooks[ this.prop ];
return hooks && hooks.get ?
hooks.get( this ) :
Tween.propHooks._default.get( this );
},
run: function( percent ) {
var eased,
hooks = Tween.propHooks[ this.prop ];
if ( this.options.duration ) {
this.pos = eased = jQuery.easing[ this.easing ](
percent, this.options.duration * percent, 0, 1, this.options.duration
);
} else {
this.pos = eased = percent;
}
this.now = ( this.end - this.start ) * eased + this.start;
if ( this.options.step ) {
this.options.step.call( this.elem, this.now, this );
}
if ( hooks && hooks.set ) {
hooks.set( this );
} else {
Tween.propHooks._default.set( this );
}
return this;
}
};
Tween.prototype.init.prototype = Tween.prototype;
Tween.propHooks = {
_default: {
get: function( tween ) {
var result;
if ( tween.elem[ tween.prop ] != null &&
(!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) {
return tween.elem[ tween.prop ];
}
// passing any value as a 4th parameter to .css will automatically
// attempt a parseFloat and fallback to a string if the parse fails
// so, simple values such as "10px" are parsed to Float.
// complex values such as "rotate(1rad)" are returned as is.
result = jQuery.css( tween.elem, tween.prop, false, "" );
// Empty strings, null, undefined and "auto" are converted to 0.
return !result || result === "auto" ? 0 : result;
},
set: function( tween ) {
// use step hook for back compat - use cssHook if its there - use .style if its
// available and use plain properties where available
if ( jQuery.fx.step[ tween.prop ] ) {
jQuery.fx.step[ tween.prop ]( tween );
} else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) {
jQuery.style( tween.elem, tween.prop, tween.now + tween.unit );
} else {
tween.elem[ tween.prop ] = tween.now;
}
}
}
};
// Remove in 2.0 - this supports IE8's panic based approach
// to setting things on disconnected nodes
Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = {
set: function( tween ) {
if ( tween.elem.nodeType && tween.elem.parentNode ) {
tween.elem[ tween.prop ] = tween.now;
}
}
};
jQuery.each([ "toggle", "show", "hide" ], function( i, name ) {
var cssFn = jQuery.fn[ name ];
jQuery.fn[ name ] = function( speed, easing, callback ) {
return speed == null || typeof speed === "boolean" ||
// special check for .toggle( handler, handler, ... )
( !i && jQuery.isFunction( speed ) && jQuery.isFunction( easing ) ) ?
cssFn.apply( this, arguments ) :
this.animate( genFx( name, true ), speed, easing, callback );
};
});
jQuery.fn.extend({
fadeTo: function( speed, to, easing, callback ) {
// show any hidden elements after setting opacity to 0
return this.filter( isHidden ).css( "opacity", 0 ).show()
// animate to the value specified
.end().animate({ opacity: to }, speed, easing, callback );
},
animate: function( prop, speed, easing, callback ) {
var empty = jQuery.isEmptyObject( prop ),
optall = jQuery.speed( speed, easing, callback ),
doAnimation = function() {
// Operate on a copy of prop so per-property easing won't be lost
var anim = Animation( this, jQuery.extend( {}, prop ), optall );
// Empty animations resolve immediately
if ( empty ) {
anim.stop( true );
}
};
return empty || optall.queue === false ?
this.each( doAnimation ) :
this.queue( optall.queue, doAnimation );
},
stop: function( type, clearQueue, gotoEnd ) {
var stopQueue = function( hooks ) {
var stop = hooks.stop;
delete hooks.stop;
stop( gotoEnd );
};
if ( typeof type !== "string" ) {
gotoEnd = clearQueue;
clearQueue = type;
type = undefined;
}
if ( clearQueue && type !== false ) {
this.queue( type || "fx", [] );
}
return this.each(function() {
var dequeue = true,
index = type != null && type + "queueHooks",
timers = jQuery.timers,
data = jQuery._data( this );
if ( index ) {
if ( data[ index ] && data[ index ].stop ) {
stopQueue( data[ index ] );
}
} else {
for ( index in data ) {
if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) {
stopQueue( data[ index ] );
}
}
}
for ( index = timers.length; index--; ) {
if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) {
timers[ index ].anim.stop( gotoEnd );
dequeue = false;
timers.splice( index, 1 );
}
}
// start the next in the queue if the last step wasn't forced
// timers currently will call their complete callbacks, which will dequeue
// but only if they were gotoEnd
if ( dequeue || !gotoEnd ) {
jQuery.dequeue( this, type );
}
});
}
});
// Generate parameters to create a standard animation
function genFx( type, includeWidth ) {
var which,
attrs = { height: type },
i = 0;
// if we include width, step value is 1 to do all cssExpand values,
// if we don't include width, step value is 2 to skip over Left and Right
includeWidth = includeWidth? 1 : 0;
for( ; i < 4 ; i += 2 - includeWidth ) {
which = cssExpand[ i ];
attrs[ "margin" + which ] = attrs[ "padding" + which ] = type;
}
if ( includeWidth ) {
attrs.opacity = attrs.width = type;
}
return attrs;
}
// Generate shortcuts for custom animations
jQuery.each({
slideDown: genFx("show"),
slideUp: genFx("hide"),
slideToggle: genFx("toggle"),
fadeIn: { opacity: "show" },
fadeOut: { opacity: "hide" },
fadeToggle: { opacity: "toggle" }
}, function( name, props ) {
jQuery.fn[ name ] = function( speed, easing, callback ) {
return this.animate( props, speed, easing, callback );
};
});
jQuery.speed = function( speed, easing, fn ) {
var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : {
complete: fn || !fn && easing ||
jQuery.isFunction( speed ) && speed,
duration: speed,
easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing
};
opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default;
// normalize opt.queue - true/undefined/null -> "fx"
if ( opt.queue == null || opt.queue === true ) {
opt.queue = "fx";
}
// Queueing
opt.old = opt.complete;
opt.complete = function() {
if ( jQuery.isFunction( opt.old ) ) {
opt.old.call( this );
}
if ( opt.queue ) {
jQuery.dequeue( this, opt.queue );
}
};
return opt;
};
jQuery.easing = {
linear: function( p ) {
return p;
},
swing: function( p ) {
return 0.5 - Math.cos( p*Math.PI ) / 2;
}
};
jQuery.timers = [];
jQuery.fx = Tween.prototype.init;
jQuery.fx.tick = function() {
var timer,
timers = jQuery.timers,
i = 0;
fxNow = jQuery.now();
for ( ; i < timers.length; i++ ) {
timer = timers[ i ];
// Checks the timer has not already been removed
if ( !timer() && timers[ i ] === timer ) {
timers.splice( i--, 1 );
}
}
if ( !timers.length ) {
jQuery.fx.stop();
}
fxNow = undefined;
};
jQuery.fx.timer = function( timer ) {
if ( timer() && jQuery.timers.push( timer ) && !timerId ) {
timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval );
}
};
jQuery.fx.interval = 13;
jQuery.fx.stop = function() {
clearInterval( timerId );
timerId = null;
};
jQuery.fx.speeds = {
slow: 600,
fast: 200,
// Default speed
_default: 400
};
// Back Compat <1.8 extension point
jQuery.fx.step = {};
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.animated = function( elem ) {
return jQuery.grep(jQuery.timers, function( fn ) {
return elem === fn.elem;
}).length;
};
}
var rroot = /^(?:body|html)$/i;
jQuery.fn.offset = function( options ) {
if ( arguments.length ) {
return options === undefined ?
this :
this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}
var docElem, body, win, clientTop, clientLeft, scrollTop, scrollLeft,
box = { top: 0, left: 0 },
elem = this[ 0 ],
doc = elem && elem.ownerDocument;
if ( !doc ) {
return;
}
if ( (body = doc.body) === elem ) {
return jQuery.offset.bodyOffset( elem );
}
docElem = doc.documentElement;
// Make sure it's not a disconnected DOM node
if ( !jQuery.contains( docElem, elem ) ) {
return box;
}
// If we don't have gBCR, just use 0,0 rather than error
// BlackBerry 5, iOS 3 (original iPhone)
if ( typeof elem.getBoundingClientRect !== "undefined" ) {
box = elem.getBoundingClientRect();
}
win = getWindow( doc );
clientTop = docElem.clientTop || body.clientTop || 0;
clientLeft = docElem.clientLeft || body.clientLeft || 0;
scrollTop = win.pageYOffset || docElem.scrollTop;
scrollLeft = win.pageXOffset || docElem.scrollLeft;
return {
top: box.top + scrollTop - clientTop,
left: box.left + scrollLeft - clientLeft
};
};
jQuery.offset = {
bodyOffset: function( body ) {
var top = body.offsetTop,
left = body.offsetLeft;
if ( jQuery.support.doesNotIncludeMarginInBodyOffset ) {
top += parseFloat( jQuery.css(body, "marginTop") ) || 0;
left += parseFloat( jQuery.css(body, "marginLeft") ) || 0;
}
return { top: top, left: left };
},
setOffset: function( elem, options, i ) {
var position = jQuery.css( elem, "position" );
// set position first, in-case top/left are set even on static elem
if ( position === "static" ) {
elem.style.position = "relative";
}
var curElem = jQuery( elem ),
curOffset = curElem.offset(),
curCSSTop = jQuery.css( elem, "top" ),
curCSSLeft = jQuery.css( elem, "left" ),
calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1,
props = {}, curPosition = {}, curTop, curLeft;
// need to be able to calculate position if either top or left is auto and position is either absolute or fixed
if ( calculatePosition ) {
curPosition = curElem.position();
curTop = curPosition.top;
curLeft = curPosition.left;
} else {
curTop = parseFloat( curCSSTop ) || 0;
curLeft = parseFloat( curCSSLeft ) || 0;
}
if ( jQuery.isFunction( options ) ) {
options = options.call( elem, i, curOffset );
}
if ( options.top != null ) {
props.top = ( options.top - curOffset.top ) + curTop;
}
if ( options.left != null ) {
props.left = ( options.left - curOffset.left ) + curLeft;
}
if ( "using" in options ) {
options.using.call( elem, props );
} else {
curElem.css( props );
}
}
};
jQuery.fn.extend({
position: function() {
if ( !this[0] ) {
return;
}
var elem = this[0],
// Get *real* offsetParent
offsetParent = this.offsetParent(),
// Get correct offsets
offset = this.offset(),
parentOffset = rroot.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset();
// Subtract element margins
// note: when an element has margin: auto the offsetLeft and marginLeft
// are the same in Safari causing offset.left to incorrectly be 0
offset.top -= parseFloat( jQuery.css(elem, "marginTop") ) || 0;
offset.left -= parseFloat( jQuery.css(elem, "marginLeft") ) || 0;
// Add offsetParent borders
parentOffset.top += parseFloat( jQuery.css(offsetParent[0], "borderTopWidth") ) || 0;
parentOffset.left += parseFloat( jQuery.css(offsetParent[0], "borderLeftWidth") ) || 0;
// Subtract the two offsets
return {
top: offset.top - parentOffset.top,
left: offset.left - parentOffset.left
};
},
offsetParent: function() {
return this.map(function() {
var offsetParent = this.offsetParent || document.body;
while ( offsetParent && (!rroot.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent || document.body;
});
}
});
// Create scrollLeft and scrollTop methods
jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) {
var top = /Y/.test( prop );
jQuery.fn[ method ] = function( val ) {
return jQuery.access( this, function( elem, method, val ) {
var win = getWindow( elem );
if ( val === undefined ) {
return win ? (prop in win) ? win[ prop ] :
win.document.documentElement[ method ] :
elem[ method ];
}
if ( win ) {
win.scrollTo(
!top ? val : jQuery( win ).scrollLeft(),
top ? val : jQuery( win ).scrollTop()
);
} else {
elem[ method ] = val;
}
}, method, val, arguments.length, null );
};
});
function getWindow( elem ) {
return jQuery.isWindow( elem ) ?
elem :
elem.nodeType === 9 ?
elem.defaultView || elem.parentWindow :
false;
}
// Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods
jQuery.each( { Height: "height", Width: "width" }, function( name, type ) {
jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) {
// margin is only for outerHeight, outerWidth
jQuery.fn[ funcName ] = function( margin, value ) {
var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ),
extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" );
return jQuery.access( this, function( elem, type, value ) {
var doc;
if ( jQuery.isWindow( elem ) ) {
// As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there
// isn't a whole lot we can do. See pull request at this URL for discussion:
// https://github.com/jquery/jquery/pull/764
return elem.document.documentElement[ "client" + name ];
}
// Get document width or height
if ( elem.nodeType === 9 ) {
doc = elem.documentElement;
// Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest
// unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it.
return Math.max(
elem.body[ "scroll" + name ], doc[ "scroll" + name ],
elem.body[ "offset" + name ], doc[ "offset" + name ],
doc[ "client" + name ]
);
}
return value === undefined ?
// Get width or height on the element, requesting but not forcing parseFloat
jQuery.css( elem, type, value, extra ) :
// Set width or height on the element
jQuery.style( elem, type, value, extra );
}, type, chainable ? margin : undefined, chainable, null );
};
});
});
// Expose jQuery to the global object
window.jQuery = window.$ = jQuery;
// Expose jQuery as an AMD module, but only for AMD loaders that
// understand the issues with loading multiple versions of jQuery
// in a page that all might call define(). The loader will indicate
// they have special allowances for multiple jQuery versions by
// specifying define.amd.jQuery = true. Register as a named module,
// since jQuery can be concatenated with other files that may use define,
// but not use a proper concatenation script that understands anonymous
// AMD modules. A named AMD is safest and most robust way to register.
// Lowercase jquery is used because AMD module names are derived from
// file names, and jQuery is normally delivered in a lowercase file name.
// Do this after creating the global so that if an AMD module wants to call
// noConflict to hide this version of jQuery, it will work.
if ( typeof define === "function" && define.amd && define.amd.jQuery ) {
define( "jquery", [], function () { return jQuery; } );
}
})( window );
|
export { default } from "./../../_gen/openfl/geom/ColorTransform"; |
/* Copyright (C) 2011-2014 Mattias Ekendahl. Used under MIT license, see full details at https://github.com/developedbyme/dbm/blob/master/LICENSE.txt */
dbm.registerClass("dbm.core.data.geometry.mesh.PointMesh", "dbm.utils.data.MultidimensionalArrayHolder", function(objectFunctions, staticFunctions, ClassReference) {
//console.log("dbm.core.data.geometry.mesh.PointMesh");
//Self reference
var PointMesh = dbm.importClass("dbm.core.data.geometry.mesh.PointMesh");
//Error report
//Dependencies
//Utils
var Point = dbm.importClass("dbm.core.data.points.Point");
//Constants
/**
* Constructor
*/
objectFunctions._init = function() {
//console.log("dbm.core.data.geometry.mesh.PointMesh::_init");
this.superCall();
return this;
};
staticFunctions.create2d = function(aNumberOfPointsX, aNumberOfPointsY, aX, aY, aWidth, aHeight) {
//console.log("dbm.core.data.geometry.mesh.PointMesh::create2d");
var newPointMesh = (new PointMesh()).init();
newPointMesh.setLengths([aNumberOfPointsX, aNumberOfPointsY]);
for(var i = 0; i < aNumberOfPointsX; i++) {
for(var j = 0; j < aNumberOfPointsY; j++) {
newPointMesh.setValue(
i,
j,
Point.create(i/(aNumberOfPointsX-1)*aWidth+aX, j/(aNumberOfPointsY-1)*aHeight+aY)
);
}
}
return newPointMesh;
};
}); |
/*!
* Chart.js
* http://chartjs.org/
* Version: {{ version }}
*
* Copyright 2015 Nick Downie
* Released under the MIT license
* https://github.com/nnnick/Chart.js/blob/master/LICENSE.md
*/
(function(){
"use strict";
//Declare root variable - window in the browser, global on the server
var root = this,
previous = root.Chart;
//Occupy the global variable of Chart, and create a simple base class
var Chart = function(context){
var chart = this;
this.canvas = context.canvas;
this.ctx = context;
//Variables global to the chart
var computeDimension = function(element,dimension)
{
if (element['offset'+dimension])
{
return element['offset'+dimension];
}
else
{
return document.defaultView.getComputedStyle(element).getPropertyValue(dimension);
}
}
var width = this.width = computeDimension(context.canvas,'Width');
var height = this.height = computeDimension(context.canvas,'Height');
// Firefox requires this to work correctly
context.canvas.width = width;
context.canvas.height = height;
var width = this.width = context.canvas.width;
var height = this.height = context.canvas.height;
this.aspectRatio = this.width / this.height;
//High pixel density displays - multiply the size of the canvas height/width by the device pixel ratio, then scale.
helpers.retinaScale(this);
return this;
};
//Globally expose the defaults to allow for user updating/changing
Chart.defaults = {
global: {
// Boolean - Whether to animate the chart
animation: true,
// Number - Number of animation steps
animationSteps: 60,
// String - Animation easing effect
animationEasing: "easeOutQuart",
// Boolean - If we should show the scale at all
showScale: true,
// Boolean - If we want to override with a hard coded scale
scaleOverride: false,
// ** Required if scaleOverride is true **
// Number - The number of steps in a hard coded scale
scaleSteps: null,
// Number - The value jump in the hard coded scale
scaleStepWidth: null,
// Number - The scale starting value
scaleStartValue: null,
// String - Colour of the scale line
scaleLineColor: "rgba(0,0,0,.1)",
// Number - Pixel width of the scale line
scaleLineWidth: 1,
// Boolean - Whether to show labels on the scale
scaleShowLabels: true,
// Interpolated JS string - can access value
scaleLabel: "<%=value%>",
// Boolean - Whether the scale should stick to integers, and not show any floats even if drawing space is there
scaleIntegersOnly: true,
// Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value
scaleBeginAtZero: false,
// String - Scale label font declaration for the scale label
scaleFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
// Number - Scale label font size in pixels
scaleFontSize: 12,
// String - Scale label font weight style
scaleFontStyle: "normal",
// String - Scale label font colour
scaleFontColor: "#666",
// Boolean - whether or not the chart should be responsive and resize when the browser does.
responsive: false,
// Boolean - whether to maintain the starting aspect ratio or not when responsive, if set to false, will take up entire container
maintainAspectRatio: true,
// Boolean - Determines whether to draw tooltips on the canvas or not - attaches events to touchmove & mousemove
showTooltips: true,
// Boolean - Determines whether to draw built-in tooltip or call custom tooltip function
customTooltips: false,
// Array - Array of string names to attach tooltip events
tooltipEvents: ["mousemove", "touchstart", "touchmove", "mouseout"],
// String - Tooltip background colour
tooltipFillColor: "rgba(0,0,0,0.8)",
// String - Tooltip label font declaration for the scale label
tooltipFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
// Number - Tooltip label font size in pixels
tooltipFontSize: 14,
// String - Tooltip font weight style
tooltipFontStyle: "normal",
// String - Tooltip label font colour
tooltipFontColor: "#fff",
// String - Tooltip title font declaration for the scale label
tooltipTitleFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
// Number - Tooltip title font size in pixels
tooltipTitleFontSize: 14,
// String - Tooltip title font weight style
tooltipTitleFontStyle: "bold",
// String - Tooltip title font colour
tooltipTitleFontColor: "#fff",
// Number - pixel width of padding around tooltip text
tooltipYPadding: 6,
// Number - pixel width of padding around tooltip text
tooltipXPadding: 6,
// Number - Size of the caret on the tooltip
tooltipCaretSize: 8,
// Number - Pixel radius of the tooltip border
tooltipCornerRadius: 6,
// Number - Pixel offset from point x to tooltip edge
tooltipXOffset: 10,
// String - Template string for single tooltips
tooltipTemplate: "<%if (label){%><%=label%>: <%}%><%= value %>",
// String - Template string for single tooltips
multiTooltipTemplate: "(<%= value %>) <%= datasetLabel %>",
// String - Colour behind the legend colour block
multiTooltipKeyBackground: '#fff',
// Function - Will fire on animation progression.
onAnimationProgress: function(){},
// Function - Will fire on animation completion.
onAnimationComplete: function(){}
}
};
//Create a dictionary of chart types, to allow for extension of existing types
Chart.types = {};
//Global Chart helpers object for utility methods and classes
var helpers = Chart.helpers = {};
//-- Basic js utility methods
var each = helpers.each = function(loopable,callback,self){
var additionalArgs = Array.prototype.slice.call(arguments, 3);
// Check to see if null or undefined firstly.
if (loopable){
if (loopable.length === +loopable.length){
var i;
for (i=0; i<loopable.length; i++){
callback.apply(self,[loopable[i], i].concat(additionalArgs));
}
}
else{
for (var item in loopable){
callback.apply(self,[loopable[item],item].concat(additionalArgs));
}
}
}
},
clone = helpers.clone = function(obj){
var objClone = {};
each(obj,function(value,key){
if (obj.hasOwnProperty(key)) objClone[key] = value;
});
return objClone;
},
extend = helpers.extend = function(base){
each(Array.prototype.slice.call(arguments,1), function(extensionObject) {
each(extensionObject,function(value,key){
if (extensionObject.hasOwnProperty(key)) base[key] = value;
});
});
return base;
},
merge = helpers.merge = function(base,master){
//Merge properties in left object over to a shallow clone of object right.
var args = Array.prototype.slice.call(arguments,0);
args.unshift({});
return extend.apply(null, args);
},
indexOf = helpers.indexOf = function(arrayToSearch, item){
if (Array.prototype.indexOf) {
return arrayToSearch.indexOf(item);
}
else{
for (var i = 0; i < arrayToSearch.length; i++) {
if (arrayToSearch[i] === item) return i;
}
return -1;
}
},
where = helpers.where = function(collection, filterCallback){
var filtered = [];
helpers.each(collection, function(item){
if (filterCallback(item)){
filtered.push(item);
}
});
return filtered;
},
findNextWhere = helpers.findNextWhere = function(arrayToSearch, filterCallback, startIndex){
// Default to start of the array
if (!startIndex){
startIndex = -1;
}
for (var i = startIndex + 1; i < arrayToSearch.length; i++) {
var currentItem = arrayToSearch[i];
if (filterCallback(currentItem)){
return currentItem;
}
}
},
findPreviousWhere = helpers.findPreviousWhere = function(arrayToSearch, filterCallback, startIndex){
// Default to end of the array
if (!startIndex){
startIndex = arrayToSearch.length;
}
for (var i = startIndex - 1; i >= 0; i--) {
var currentItem = arrayToSearch[i];
if (filterCallback(currentItem)){
return currentItem;
}
}
},
inherits = helpers.inherits = function(extensions){
//Basic javascript inheritance based on the model created in Backbone.js
var parent = this;
var ChartElement = (extensions && extensions.hasOwnProperty("constructor")) ? extensions.constructor : function(){ return parent.apply(this, arguments); };
var Surrogate = function(){ this.constructor = ChartElement;};
Surrogate.prototype = parent.prototype;
ChartElement.prototype = new Surrogate();
ChartElement.extend = inherits;
if (extensions) extend(ChartElement.prototype, extensions);
ChartElement.__super__ = parent.prototype;
return ChartElement;
},
noop = helpers.noop = function(){},
uid = helpers.uid = (function(){
var id=0;
return function(){
return "chart-" + id++;
};
})(),
warn = helpers.warn = function(str){
//Method for warning of errors
if (window.console && typeof window.console.warn == "function") console.warn(str);
},
amd = helpers.amd = (typeof define == 'function' && define.amd),
//-- Math methods
isNumber = helpers.isNumber = function(n){
return !isNaN(parseFloat(n)) && isFinite(n);
},
max = helpers.max = function(array){
return Math.max.apply( Math, array );
},
min = helpers.min = function(array){
return Math.min.apply( Math, array );
},
cap = helpers.cap = function(valueToCap,maxValue,minValue){
if(isNumber(maxValue)) {
if( valueToCap > maxValue ) {
return maxValue;
}
}
else if(isNumber(minValue)){
if ( valueToCap < minValue ){
return minValue;
}
}
return valueToCap;
},
getDecimalPlaces = helpers.getDecimalPlaces = function(num){
if (num%1!==0 && isNumber(num)){
return num.toString().split(".")[1].length;
}
else {
return 0;
}
},
toRadians = helpers.radians = function(degrees){
return degrees * (Math.PI/180);
},
// Gets the angle from vertical upright to the point about a centre.
getAngleFromPoint = helpers.getAngleFromPoint = function(centrePoint, anglePoint){
var distanceFromXCenter = anglePoint.x - centrePoint.x,
distanceFromYCenter = anglePoint.y - centrePoint.y,
radialDistanceFromCenter = Math.sqrt( distanceFromXCenter * distanceFromXCenter + distanceFromYCenter * distanceFromYCenter);
var angle = Math.PI * 2 + Math.atan2(distanceFromYCenter, distanceFromXCenter);
//If the segment is in the top left quadrant, we need to add another rotation to the angle
if (distanceFromXCenter < 0 && distanceFromYCenter < 0){
angle += Math.PI*2;
}
return {
angle: angle,
distance: radialDistanceFromCenter
};
},
aliasPixel = helpers.aliasPixel = function(pixelWidth){
return (pixelWidth % 2 === 0) ? 0 : 0.5;
},
splineCurve = helpers.splineCurve = function(FirstPoint,MiddlePoint,AfterPoint,t){
//Props to Rob Spencer at scaled innovation for his post on splining between points
//http://scaledinnovation.com/analytics/splines/aboutSplines.html
var d01=Math.sqrt(Math.pow(MiddlePoint.x-FirstPoint.x,2)+Math.pow(MiddlePoint.y-FirstPoint.y,2)),
d12=Math.sqrt(Math.pow(AfterPoint.x-MiddlePoint.x,2)+Math.pow(AfterPoint.y-MiddlePoint.y,2)),
fa=t*d01/(d01+d12),// scaling factor for triangle Ta
fb=t*d12/(d01+d12);
return {
inner : {
x : MiddlePoint.x-fa*(AfterPoint.x-FirstPoint.x),
y : MiddlePoint.y-fa*(AfterPoint.y-FirstPoint.y)
},
outer : {
x: MiddlePoint.x+fb*(AfterPoint.x-FirstPoint.x),
y : MiddlePoint.y+fb*(AfterPoint.y-FirstPoint.y)
}
};
},
calculateOrderOfMagnitude = helpers.calculateOrderOfMagnitude = function(val){
return Math.floor(Math.log(val) / Math.LN10);
},
calculateScaleRange = helpers.calculateScaleRange = function(valuesArray, drawingSize, textSize, startFromZero, integersOnly){
//Set a minimum step of two - a point at the top of the graph, and a point at the base
var minSteps = 2,
maxSteps = Math.floor(drawingSize/(textSize * 1.5)),
skipFitting = (minSteps >= maxSteps);
var maxValue = max(valuesArray),
minValue = min(valuesArray);
// We need some degree of seperation here to calculate the scales if all the values are the same
// Adding/minusing 0.5 will give us a range of 1.
if (maxValue === minValue){
maxValue += 0.5;
// So we don't end up with a graph with a negative start value if we've said always start from zero
if (minValue >= 0.5 && !startFromZero){
minValue -= 0.5;
}
else{
// Make up a whole number above the values
maxValue += 0.5;
}
}
var valueRange = Math.abs(maxValue - minValue),
rangeOrderOfMagnitude = calculateOrderOfMagnitude(valueRange),
graphMax = Math.ceil(maxValue / (1 * Math.pow(10, rangeOrderOfMagnitude))) * Math.pow(10, rangeOrderOfMagnitude),
graphMin = (startFromZero) ? 0 : Math.floor(minValue / (1 * Math.pow(10, rangeOrderOfMagnitude))) * Math.pow(10, rangeOrderOfMagnitude),
graphRange = graphMax - graphMin,
stepValue = Math.pow(10, rangeOrderOfMagnitude),
numberOfSteps = Math.round(graphRange / stepValue);
//If we have more space on the graph we'll use it to give more definition to the data
while((numberOfSteps > maxSteps || (numberOfSteps * 2) < maxSteps) && !skipFitting) {
if(numberOfSteps > maxSteps){
stepValue *=2;
numberOfSteps = Math.round(graphRange/stepValue);
// Don't ever deal with a decimal number of steps - cancel fitting and just use the minimum number of steps.
if (numberOfSteps % 1 !== 0){
skipFitting = true;
}
}
//We can fit in double the amount of scale points on the scale
else{
//If user has declared ints only, and the step value isn't a decimal
if (integersOnly && rangeOrderOfMagnitude >= 0){
//If the user has said integers only, we need to check that making the scale more granular wouldn't make it a float
if(stepValue/2 % 1 === 0){
stepValue /=2;
numberOfSteps = Math.round(graphRange/stepValue);
}
//If it would make it a float break out of the loop
else{
break;
}
}
//If the scale doesn't have to be an int, make the scale more granular anyway.
else{
stepValue /=2;
numberOfSteps = Math.round(graphRange/stepValue);
}
}
}
if (skipFitting){
numberOfSteps = minSteps;
stepValue = graphRange / numberOfSteps;
}
return {
steps : numberOfSteps,
stepValue : stepValue,
min : graphMin,
max : graphMin + (numberOfSteps * stepValue)
};
},
/* jshint ignore:start */
// Blows up jshint errors based on the new Function constructor
//Templating methods
//Javascript micro templating by John Resig - source at http://ejohn.org/blog/javascript-micro-templating/
template = helpers.template = function(templateString, valuesObject){
// If templateString is function rather than string-template - call the function for valuesObject
if(templateString instanceof Function){
return templateString(valuesObject);
}
var cache = {};
function tmpl(str, data){
// Figure out if we're getting a template, or if we need to
// load the template - and be sure to cache the result.
var fn = !/\W/.test(str) ?
cache[str] = cache[str] :
// Generate a reusable function that will serve as a template
// generator (and which will be cached).
new Function("obj",
"var p=[],print=function(){p.push.apply(p,arguments);};" +
// Introduce the data as local variables using with(){}
"with(obj){p.push('" +
// Convert the template into pure JavaScript
str
.replace(/[\r\t\n]/g, " ")
.split("<%").join("\t")
.replace(/((^|%>)[^\t]*)'/g, "$1\r")
.replace(/\t=(.*?)%>/g, "',$1,'")
.split("\t").join("');")
.split("%>").join("p.push('")
.split("\r").join("\\'") +
"');}return p.join('');"
);
// Provide some basic currying to the user
return data ? fn( data ) : fn;
}
return tmpl(templateString,valuesObject);
},
/* jshint ignore:end */
generateLabels = helpers.generateLabels = function(templateString,numberOfSteps,graphMin,stepValue){
var labelsArray = new Array(numberOfSteps);
if (labelTemplateString){
each(labelsArray,function(val,index){
labelsArray[index] = template(templateString,{value: (graphMin + (stepValue*(index+1)))});
});
}
return labelsArray;
},
//--Animation methods
//Easing functions adapted from Robert Penner's easing equations
//http://www.robertpenner.com/easing/
easingEffects = helpers.easingEffects = {
linear: function (t) {
return t;
},
easeInQuad: function (t) {
return t * t;
},
easeOutQuad: function (t) {
return -1 * t * (t - 2);
},
easeInOutQuad: function (t) {
if ((t /= 1 / 2) < 1) return 1 / 2 * t * t;
return -1 / 2 * ((--t) * (t - 2) - 1);
},
easeInCubic: function (t) {
return t * t * t;
},
easeOutCubic: function (t) {
return 1 * ((t = t / 1 - 1) * t * t + 1);
},
easeInOutCubic: function (t) {
if ((t /= 1 / 2) < 1) return 1 / 2 * t * t * t;
return 1 / 2 * ((t -= 2) * t * t + 2);
},
easeInQuart: function (t) {
return t * t * t * t;
},
easeOutQuart: function (t) {
return -1 * ((t = t / 1 - 1) * t * t * t - 1);
},
easeInOutQuart: function (t) {
if ((t /= 1 / 2) < 1) return 1 / 2 * t * t * t * t;
return -1 / 2 * ((t -= 2) * t * t * t - 2);
},
easeInQuint: function (t) {
return 1 * (t /= 1) * t * t * t * t;
},
easeOutQuint: function (t) {
return 1 * ((t = t / 1 - 1) * t * t * t * t + 1);
},
easeInOutQuint: function (t) {
if ((t /= 1 / 2) < 1) return 1 / 2 * t * t * t * t * t;
return 1 / 2 * ((t -= 2) * t * t * t * t + 2);
},
easeInSine: function (t) {
return -1 * Math.cos(t / 1 * (Math.PI / 2)) + 1;
},
easeOutSine: function (t) {
return 1 * Math.sin(t / 1 * (Math.PI / 2));
},
easeInOutSine: function (t) {
return -1 / 2 * (Math.cos(Math.PI * t / 1) - 1);
},
easeInExpo: function (t) {
return (t === 0) ? 1 : 1 * Math.pow(2, 10 * (t / 1 - 1));
},
easeOutExpo: function (t) {
return (t === 1) ? 1 : 1 * (-Math.pow(2, -10 * t / 1) + 1);
},
easeInOutExpo: function (t) {
if (t === 0) return 0;
if (t === 1) return 1;
if ((t /= 1 / 2) < 1) return 1 / 2 * Math.pow(2, 10 * (t - 1));
return 1 / 2 * (-Math.pow(2, -10 * --t) + 2);
},
easeInCirc: function (t) {
if (t >= 1) return t;
return -1 * (Math.sqrt(1 - (t /= 1) * t) - 1);
},
easeOutCirc: function (t) {
return 1 * Math.sqrt(1 - (t = t / 1 - 1) * t);
},
easeInOutCirc: function (t) {
if ((t /= 1 / 2) < 1) return -1 / 2 * (Math.sqrt(1 - t * t) - 1);
return 1 / 2 * (Math.sqrt(1 - (t -= 2) * t) + 1);
},
easeInElastic: function (t) {
var s = 1.70158;
var p = 0;
var a = 1;
if (t === 0) return 0;
if ((t /= 1) == 1) return 1;
if (!p) p = 1 * 0.3;
if (a < Math.abs(1)) {
a = 1;
s = p / 4;
} else s = p / (2 * Math.PI) * Math.asin(1 / a);
return -(a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * 1 - s) * (2 * Math.PI) / p));
},
easeOutElastic: function (t) {
var s = 1.70158;
var p = 0;
var a = 1;
if (t === 0) return 0;
if ((t /= 1) == 1) return 1;
if (!p) p = 1 * 0.3;
if (a < Math.abs(1)) {
a = 1;
s = p / 4;
} else s = p / (2 * Math.PI) * Math.asin(1 / a);
return a * Math.pow(2, -10 * t) * Math.sin((t * 1 - s) * (2 * Math.PI) / p) + 1;
},
easeInOutElastic: function (t) {
var s = 1.70158;
var p = 0;
var a = 1;
if (t === 0) return 0;
if ((t /= 1 / 2) == 2) return 1;
if (!p) p = 1 * (0.3 * 1.5);
if (a < Math.abs(1)) {
a = 1;
s = p / 4;
} else s = p / (2 * Math.PI) * Math.asin(1 / a);
if (t < 1) return -0.5 * (a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * 1 - s) * (2 * Math.PI) / p));
return a * Math.pow(2, -10 * (t -= 1)) * Math.sin((t * 1 - s) * (2 * Math.PI) / p) * 0.5 + 1;
},
easeInBack: function (t) {
var s = 1.70158;
return 1 * (t /= 1) * t * ((s + 1) * t - s);
},
easeOutBack: function (t) {
var s = 1.70158;
return 1 * ((t = t / 1 - 1) * t * ((s + 1) * t + s) + 1);
},
easeInOutBack: function (t) {
var s = 1.70158;
if ((t /= 1 / 2) < 1) return 1 / 2 * (t * t * (((s *= (1.525)) + 1) * t - s));
return 1 / 2 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2);
},
easeInBounce: function (t) {
return 1 - easingEffects.easeOutBounce(1 - t);
},
easeOutBounce: function (t) {
if ((t /= 1) < (1 / 2.75)) {
return 1 * (7.5625 * t * t);
} else if (t < (2 / 2.75)) {
return 1 * (7.5625 * (t -= (1.5 / 2.75)) * t + 0.75);
} else if (t < (2.5 / 2.75)) {
return 1 * (7.5625 * (t -= (2.25 / 2.75)) * t + 0.9375);
} else {
return 1 * (7.5625 * (t -= (2.625 / 2.75)) * t + 0.984375);
}
},
easeInOutBounce: function (t) {
if (t < 1 / 2) return easingEffects.easeInBounce(t * 2) * 0.5;
return easingEffects.easeOutBounce(t * 2 - 1) * 0.5 + 1 * 0.5;
}
},
//Request animation polyfill - http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
requestAnimFrame = helpers.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback) {
return window.setTimeout(callback, 1000 / 60);
};
})(),
cancelAnimFrame = helpers.cancelAnimFrame = (function(){
return window.cancelAnimationFrame ||
window.webkitCancelAnimationFrame ||
window.mozCancelAnimationFrame ||
window.oCancelAnimationFrame ||
window.msCancelAnimationFrame ||
function(callback) {
return window.clearTimeout(callback, 1000 / 60);
};
})(),
animationLoop = helpers.animationLoop = function(callback,totalSteps,easingString,onProgress,onComplete,chartInstance){
var currentStep = 0,
easingFunction = easingEffects[easingString] || easingEffects.linear;
var animationFrame = function(){
currentStep++;
var stepDecimal = currentStep/totalSteps;
var easeDecimal = easingFunction(stepDecimal);
callback.call(chartInstance,easeDecimal,stepDecimal, currentStep);
onProgress.call(chartInstance,easeDecimal,stepDecimal);
if (currentStep < totalSteps){
chartInstance.animationFrame = requestAnimFrame(animationFrame);
} else{
onComplete.apply(chartInstance);
}
};
requestAnimFrame(animationFrame);
},
//-- DOM methods
getRelativePosition = helpers.getRelativePosition = function(evt){
var mouseX, mouseY;
var e = evt.originalEvent || evt,
canvas = evt.currentTarget || evt.srcElement,
boundingRect = canvas.getBoundingClientRect();
if (e.touches){
mouseX = e.touches[0].clientX - boundingRect.left;
mouseY = e.touches[0].clientY - boundingRect.top;
}
else{
mouseX = e.clientX - boundingRect.left;
mouseY = e.clientY - boundingRect.top;
}
return {
x : mouseX,
y : mouseY
};
},
addEvent = helpers.addEvent = function(node,eventType,method){
if (node.addEventListener){
node.addEventListener(eventType,method);
} else if (node.attachEvent){
node.attachEvent("on"+eventType, method);
} else {
node["on"+eventType] = method;
}
},
removeEvent = helpers.removeEvent = function(node, eventType, handler){
if (node.removeEventListener){
node.removeEventListener(eventType, handler, false);
} else if (node.detachEvent){
node.detachEvent("on"+eventType,handler);
} else{
node["on" + eventType] = noop;
}
},
bindEvents = helpers.bindEvents = function(chartInstance, arrayOfEvents, handler){
// Create the events object if it's not already present
if (!chartInstance.events) chartInstance.events = {};
each(arrayOfEvents,function(eventName){
chartInstance.events[eventName] = function(){
handler.apply(chartInstance, arguments);
};
addEvent(chartInstance.chart.canvas,eventName,chartInstance.events[eventName]);
});
},
unbindEvents = helpers.unbindEvents = function (chartInstance, arrayOfEvents) {
each(arrayOfEvents, function(handler,eventName){
removeEvent(chartInstance.chart.canvas, eventName, handler);
});
},
getMaximumWidth = helpers.getMaximumWidth = function(domNode){
var container = domNode.parentNode;
// TODO = check cross browser stuff with this.
return container.clientWidth;
},
getMaximumHeight = helpers.getMaximumHeight = function(domNode){
var container = domNode.parentNode;
// TODO = check cross browser stuff with this.
return container.clientHeight;
},
getMaximumSize = helpers.getMaximumSize = helpers.getMaximumWidth, // legacy support
retinaScale = helpers.retinaScale = function(chart){
var ctx = chart.ctx,
width = chart.canvas.width,
height = chart.canvas.height;
if (window.devicePixelRatio) {
ctx.canvas.style.width = width + "px";
ctx.canvas.style.height = height + "px";
ctx.canvas.height = height * window.devicePixelRatio;
ctx.canvas.width = width * window.devicePixelRatio;
ctx.scale(window.devicePixelRatio, window.devicePixelRatio);
}
},
//-- Canvas methods
clear = helpers.clear = function(chart){
chart.ctx.clearRect(0,0,chart.width,chart.height);
},
fontString = helpers.fontString = function(pixelSize,fontStyle,fontFamily){
return fontStyle + " " + pixelSize+"px " + fontFamily;
},
longestText = helpers.longestText = function(ctx,font,arrayOfStrings){
ctx.font = font;
var longest = 0;
each(arrayOfStrings,function(string){
var textWidth = ctx.measureText(string).width;
longest = (textWidth > longest) ? textWidth : longest;
});
return longest;
},
drawRoundedRectangle = helpers.drawRoundedRectangle = function(ctx,x,y,width,height,radius){
ctx.beginPath();
ctx.moveTo(x + radius, y);
ctx.lineTo(x + width - radius, y);
ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
ctx.lineTo(x + width, y + height - radius);
ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
ctx.lineTo(x + radius, y + height);
ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
ctx.lineTo(x, y + radius);
ctx.quadraticCurveTo(x, y, x + radius, y);
ctx.closePath();
};
//Store a reference to each instance - allowing us to globally resize chart instances on window resize.
//Destroy method on the chart will remove the instance of the chart from this reference.
Chart.instances = {};
Chart.Type = function(data,options,chart){
this.options = options;
this.chart = chart;
this.id = uid();
//Add the chart instance to the global namespace
Chart.instances[this.id] = this;
// Initialize is always called when a chart type is created
// By default it is a no op, but it should be extended
if (options.responsive){
this.resize();
}
this.initialize.call(this,data);
};
//Core methods that'll be a part of every chart type
extend(Chart.Type.prototype,{
initialize : function(){return this;},
clear : function(){
clear(this.chart);
return this;
},
stop : function(){
// Stops any current animation loop occuring
cancelAnimFrame(this.animationFrame);
return this;
},
resize : function(callback){
this.stop();
var canvas = this.chart.canvas,
newWidth = getMaximumWidth(this.chart.canvas),
newHeight = this.options.maintainAspectRatio ? newWidth / this.chart.aspectRatio : getMaximumHeight(this.chart.canvas);
canvas.width = this.chart.width = newWidth;
canvas.height = this.chart.height = newHeight;
retinaScale(this.chart);
if (typeof callback === "function"){
callback.apply(this, Array.prototype.slice.call(arguments, 1));
}
return this;
},
reflow : noop,
render : function(reflow){
if (reflow){
this.reflow();
}
if (this.options.animation && !reflow){
helpers.animationLoop(
this.draw,
this.options.animationSteps,
this.options.animationEasing,
this.options.onAnimationProgress,
this.options.onAnimationComplete,
this
);
}
else{
this.draw();
this.options.onAnimationComplete.call(this);
}
return this;
},
generateLegend : function(){
return template(this.options.legendTemplate,this);
},
destroy : function(){
this.clear();
unbindEvents(this, this.events);
var canvas = this.chart.canvas;
// Reset canvas height/width attributes starts a fresh with the canvas context
canvas.width = this.chart.width;
canvas.height = this.chart.height;
// < IE9 doesn't support removeProperty
if (canvas.style.removeProperty) {
canvas.style.removeProperty('width');
canvas.style.removeProperty('height');
} else {
canvas.style.removeAttribute('width');
canvas.style.removeAttribute('height');
}
delete Chart.instances[this.id];
},
showTooltip : function(ChartElements, forceRedraw){
// Only redraw the chart if we've actually changed what we're hovering on.
if (typeof this.activeElements === 'undefined') this.activeElements = [];
var isChanged = (function(Elements){
var changed = false;
if (Elements.length !== this.activeElements.length){
changed = true;
return changed;
}
each(Elements, function(element, index){
if (element !== this.activeElements[index]){
changed = true;
}
}, this);
return changed;
}).call(this, ChartElements);
if (!isChanged && !forceRedraw){
return;
}
else{
this.activeElements = ChartElements;
}
this.draw();
if(this.options.customTooltips){
this.options.customTooltips(false);
}
if (ChartElements.length > 0){
// If we have multiple datasets, show a MultiTooltip for all of the data points at that index
if (this.datasets && this.datasets.length > 1) {
var dataArray,
dataIndex;
for (var i = this.datasets.length - 1; i >= 0; i--) {
dataArray = this.datasets[i].points || this.datasets[i].bars || this.datasets[i].segments;
dataIndex = indexOf(dataArray, ChartElements[0]);
if (dataIndex !== -1){
break;
}
}
var tooltipLabels = [],
tooltipColors = [],
medianPosition = (function(index) {
// Get all the points at that particular index
var Elements = [],
dataCollection,
xPositions = [],
yPositions = [],
xMax,
yMax,
xMin,
yMin;
helpers.each(this.datasets, function(dataset){
dataCollection = dataset.points || dataset.bars || dataset.segments;
if (dataCollection[dataIndex] && dataCollection[dataIndex].hasValue()){
Elements.push(dataCollection[dataIndex]);
}
});
helpers.each(Elements, function(element) {
xPositions.push(element.x);
yPositions.push(element.y);
//Include any colour information about the element
tooltipLabels.push(helpers.template(this.options.multiTooltipTemplate, element));
tooltipColors.push({
fill: element._saved.fillColor || element.fillColor,
stroke: element._saved.strokeColor || element.strokeColor
});
}, this);
yMin = min(yPositions);
yMax = max(yPositions);
xMin = min(xPositions);
xMax = max(xPositions);
return {
x: (xMin > this.chart.width/2) ? xMin : xMax,
y: (yMin + yMax)/2
};
}).call(this, dataIndex);
new Chart.MultiTooltip({
x: medianPosition.x,
y: medianPosition.y,
xPadding: this.options.tooltipXPadding,
yPadding: this.options.tooltipYPadding,
xOffset: this.options.tooltipXOffset,
fillColor: this.options.tooltipFillColor,
textColor: this.options.tooltipFontColor,
fontFamily: this.options.tooltipFontFamily,
fontStyle: this.options.tooltipFontStyle,
fontSize: this.options.tooltipFontSize,
titleTextColor: this.options.tooltipTitleFontColor,
titleFontFamily: this.options.tooltipTitleFontFamily,
titleFontStyle: this.options.tooltipTitleFontStyle,
titleFontSize: this.options.tooltipTitleFontSize,
cornerRadius: this.options.tooltipCornerRadius,
labels: tooltipLabels,
legendColors: tooltipColors,
legendColorBackground : this.options.multiTooltipKeyBackground,
title: ChartElements[0].label,
chart: this.chart,
ctx: this.chart.ctx,
custom: this.options.customTooltips
}).draw();
} else {
each(ChartElements, function(Element) {
var tooltipPosition = Element.tooltipPosition();
new Chart.Tooltip({
x: Math.round(tooltipPosition.x),
y: Math.round(tooltipPosition.y),
xPadding: this.options.tooltipXPadding,
yPadding: this.options.tooltipYPadding,
fillColor: this.options.tooltipFillColor,
textColor: this.options.tooltipFontColor,
fontFamily: this.options.tooltipFontFamily,
fontStyle: this.options.tooltipFontStyle,
fontSize: this.options.tooltipFontSize,
caretHeight: this.options.tooltipCaretSize,
cornerRadius: this.options.tooltipCornerRadius,
text: template(this.options.tooltipTemplate, Element),
chart: this.chart,
custom: this.options.customTooltips
}).draw();
}, this);
}
}
return this;
},
toBase64Image : function(){
return this.chart.canvas.toDataURL.apply(this.chart.canvas, arguments);
}
});
Chart.Type.extend = function(extensions){
var parent = this;
var ChartType = function(){
return parent.apply(this,arguments);
};
//Copy the prototype object of the this class
ChartType.prototype = clone(parent.prototype);
//Now overwrite some of the properties in the base class with the new extensions
extend(ChartType.prototype, extensions);
ChartType.extend = Chart.Type.extend;
if (extensions.name || parent.prototype.name){
var chartName = extensions.name || parent.prototype.name;
//Assign any potential default values of the new chart type
//If none are defined, we'll use a clone of the chart type this is being extended from.
//I.e. if we extend a line chart, we'll use the defaults from the line chart if our new chart
//doesn't define some defaults of their own.
var baseDefaults = (Chart.defaults[parent.prototype.name]) ? clone(Chart.defaults[parent.prototype.name]) : {};
Chart.defaults[chartName] = extend(baseDefaults,extensions.defaults);
Chart.types[chartName] = ChartType;
//Register this new chart type in the Chart prototype
Chart.prototype[chartName] = function(data,options){
var config = merge(Chart.defaults.global, Chart.defaults[chartName], options || {});
return new ChartType(data,config,this);
};
} else{
warn("Name not provided for this chart, so it hasn't been registered");
}
return parent;
};
Chart.Element = function(configuration){
extend(this,configuration);
this.initialize.apply(this,arguments);
this.save();
};
extend(Chart.Element.prototype,{
initialize : function(){},
restore : function(props){
if (!props){
extend(this,this._saved);
} else {
each(props,function(key){
this[key] = this._saved[key];
},this);
}
return this;
},
save : function(){
this._saved = clone(this);
delete this._saved._saved;
return this;
},
update : function(newProps){
each(newProps,function(value,key){
this._saved[key] = this[key];
this[key] = value;
},this);
return this;
},
transition : function(props,ease){
each(props,function(value,key){
this[key] = ((value - this._saved[key]) * ease) + this._saved[key];
},this);
return this;
},
tooltipPosition : function(){
return {
x : this.x,
y : this.y
};
},
hasValue: function(){
return isNumber(this.value);
}
});
Chart.Element.extend = inherits;
Chart.Point = Chart.Element.extend({
display: true,
inRange: function(chartX,chartY){
var hitDetectionRange = this.hitDetectionRadius + this.radius;
return ((Math.pow(chartX-this.x, 2)+Math.pow(chartY-this.y, 2)) < Math.pow(hitDetectionRange,2));
},
draw : function(){
if (this.display){
var ctx = this.ctx;
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI*2);
ctx.closePath();
ctx.strokeStyle = this.strokeColor;
ctx.lineWidth = this.strokeWidth;
ctx.fillStyle = this.fillColor;
ctx.fill();
ctx.stroke();
}
//Quick debug for bezier curve splining
//Highlights control points and the line between them.
//Handy for dev - stripped in the min version.
// ctx.save();
// ctx.fillStyle = "black";
// ctx.strokeStyle = "black"
// ctx.beginPath();
// ctx.arc(this.controlPoints.inner.x,this.controlPoints.inner.y, 2, 0, Math.PI*2);
// ctx.fill();
// ctx.beginPath();
// ctx.arc(this.controlPoints.outer.x,this.controlPoints.outer.y, 2, 0, Math.PI*2);
// ctx.fill();
// ctx.moveTo(this.controlPoints.inner.x,this.controlPoints.inner.y);
// ctx.lineTo(this.x, this.y);
// ctx.lineTo(this.controlPoints.outer.x,this.controlPoints.outer.y);
// ctx.stroke();
// ctx.restore();
}
});
Chart.Arc = Chart.Element.extend({
inRange : function(chartX,chartY){
var pointRelativePosition = helpers.getAngleFromPoint(this, {
x: chartX,
y: chartY
});
//Check if within the range of the open/close angle
var betweenAngles = (pointRelativePosition.angle >= this.startAngle && pointRelativePosition.angle <= this.endAngle),
withinRadius = (pointRelativePosition.distance >= this.innerRadius && pointRelativePosition.distance <= this.outerRadius);
return (betweenAngles && withinRadius);
//Ensure within the outside of the arc centre, but inside arc outer
},
tooltipPosition : function(){
var centreAngle = this.startAngle + ((this.endAngle - this.startAngle) / 2),
rangeFromCentre = (this.outerRadius - this.innerRadius) / 2 + this.innerRadius;
return {
x : this.x + (Math.cos(centreAngle) * rangeFromCentre),
y : this.y + (Math.sin(centreAngle) * rangeFromCentre)
};
},
draw : function(animationPercent){
var easingDecimal = animationPercent || 1;
var ctx = this.ctx;
ctx.beginPath();
ctx.arc(this.x, this.y, this.outerRadius, this.startAngle, this.endAngle);
ctx.arc(this.x, this.y, this.innerRadius, this.endAngle, this.startAngle, true);
ctx.closePath();
ctx.strokeStyle = this.strokeColor;
ctx.lineWidth = this.strokeWidth;
ctx.fillStyle = this.fillColor;
ctx.fill();
ctx.lineJoin = 'bevel';
if (this.showStroke){
ctx.stroke();
}
}
});
Chart.Rectangle = Chart.Element.extend({
draw : function(){
var ctx = this.ctx,
halfWidth = this.width/2,
leftX = this.x - halfWidth,
rightX = this.x + halfWidth,
top = this.base - (this.base - this.y),
halfStroke = this.strokeWidth / 2;
// Canvas doesn't allow us to stroke inside the width so we can
// adjust the sizes to fit if we're setting a stroke on the line
if (this.showStroke){
leftX += halfStroke;
rightX -= halfStroke;
top += halfStroke;
}
ctx.beginPath();
ctx.fillStyle = this.fillColor;
ctx.strokeStyle = this.strokeColor;
ctx.lineWidth = this.strokeWidth;
// It'd be nice to keep this class totally generic to any rectangle
// and simply specify which border to miss out.
ctx.moveTo(leftX, this.base);
ctx.lineTo(leftX, top);
ctx.lineTo(rightX, top);
ctx.lineTo(rightX, this.base);
ctx.fill();
if (this.showStroke){
ctx.stroke();
}
},
height : function(){
return this.base - this.y;
},
inRange : function(chartX,chartY){
return (chartX >= this.x - this.width/2 && chartX <= this.x + this.width/2) && (chartY >= this.y && chartY <= this.base);
}
});
Chart.Tooltip = Chart.Element.extend({
draw : function(){
var ctx = this.chart.ctx;
ctx.font = fontString(this.fontSize,this.fontStyle,this.fontFamily);
this.xAlign = "center";
this.yAlign = "above";
//Distance between the actual element.y position and the start of the tooltip caret
var caretPadding = this.caretPadding = 2;
var tooltipWidth = ctx.measureText(this.text).width + 2*this.xPadding,
tooltipRectHeight = this.fontSize + 2*this.yPadding,
tooltipHeight = tooltipRectHeight + this.caretHeight + caretPadding;
if (this.x + tooltipWidth/2 >this.chart.width){
this.xAlign = "left";
} else if (this.x - tooltipWidth/2 < 0){
this.xAlign = "right";
}
if (this.y - tooltipHeight < 0){
this.yAlign = "below";
}
var tooltipX = this.x - tooltipWidth/2,
tooltipY = this.y - tooltipHeight;
ctx.fillStyle = this.fillColor;
// Custom Tooltips
if(this.custom){
this.custom(this);
}
else{
switch(this.yAlign)
{
case "above":
//Draw a caret above the x/y
ctx.beginPath();
ctx.moveTo(this.x,this.y - caretPadding);
ctx.lineTo(this.x + this.caretHeight, this.y - (caretPadding + this.caretHeight));
ctx.lineTo(this.x - this.caretHeight, this.y - (caretPadding + this.caretHeight));
ctx.closePath();
ctx.fill();
break;
case "below":
tooltipY = this.y + caretPadding + this.caretHeight;
//Draw a caret below the x/y
ctx.beginPath();
ctx.moveTo(this.x, this.y + caretPadding);
ctx.lineTo(this.x + this.caretHeight, this.y + caretPadding + this.caretHeight);
ctx.lineTo(this.x - this.caretHeight, this.y + caretPadding + this.caretHeight);
ctx.closePath();
ctx.fill();
break;
}
switch(this.xAlign)
{
case "left":
tooltipX = this.x - tooltipWidth + (this.cornerRadius + this.caretHeight);
break;
case "right":
tooltipX = this.x - (this.cornerRadius + this.caretHeight);
break;
}
drawRoundedRectangle(ctx,tooltipX,tooltipY,tooltipWidth,tooltipRectHeight,this.cornerRadius);
ctx.fill();
ctx.fillStyle = this.textColor;
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(this.text, tooltipX + tooltipWidth/2, tooltipY + tooltipRectHeight/2);
}
}
});
Chart.MultiTooltip = Chart.Element.extend({
initialize : function(){
this.font = fontString(this.fontSize,this.fontStyle,this.fontFamily);
this.titleFont = fontString(this.titleFontSize,this.titleFontStyle,this.titleFontFamily);
this.height = (this.labels.length * this.fontSize) + ((this.labels.length-1) * (this.fontSize/2)) + (this.yPadding*2) + this.titleFontSize *1.5;
this.ctx.font = this.titleFont;
var titleWidth = this.ctx.measureText(this.title).width,
//Label has a legend square as well so account for this.
labelWidth = longestText(this.ctx,this.font,this.labels) + this.fontSize + 3,
longestTextWidth = max([labelWidth,titleWidth]);
this.width = longestTextWidth + (this.xPadding*2);
var halfHeight = this.height/2;
//Check to ensure the height will fit on the canvas
if (this.y - halfHeight < 0 ){
this.y = halfHeight;
} else if (this.y + halfHeight > this.chart.height){
this.y = this.chart.height - halfHeight;
}
//Decide whether to align left or right based on position on canvas
if (this.x > this.chart.width/2){
this.x -= this.xOffset + this.width;
} else {
this.x += this.xOffset;
}
},
getLineHeight : function(index){
var baseLineHeight = this.y - (this.height/2) + this.yPadding,
afterTitleIndex = index-1;
//If the index is zero, we're getting the title
if (index === 0){
return baseLineHeight + this.titleFontSize/2;
} else{
return baseLineHeight + ((this.fontSize*1.5*afterTitleIndex) + this.fontSize/2) + this.titleFontSize * 1.5;
}
},
draw : function(){
// Custom Tooltips
if(this.custom){
this.custom(this);
}
else{
drawRoundedRectangle(this.ctx,this.x,this.y - this.height/2,this.width,this.height,this.cornerRadius);
var ctx = this.ctx;
ctx.fillStyle = this.fillColor;
ctx.fill();
ctx.closePath();
ctx.textAlign = "left";
ctx.textBaseline = "middle";
ctx.fillStyle = this.titleTextColor;
ctx.font = this.titleFont;
ctx.fillText(this.title,this.x + this.xPadding, this.getLineHeight(0));
ctx.font = this.font;
helpers.each(this.labels,function(label,index){
ctx.fillStyle = this.textColor;
ctx.fillText(label,this.x + this.xPadding + this.fontSize + 3, this.getLineHeight(index + 1));
//A bit gnarly, but clearing this rectangle breaks when using explorercanvas (clears whole canvas)
//ctx.clearRect(this.x + this.xPadding, this.getLineHeight(index + 1) - this.fontSize/2, this.fontSize, this.fontSize);
//Instead we'll make a white filled block to put the legendColour palette over.
ctx.fillStyle = this.legendColorBackground;
ctx.fillRect(this.x + this.xPadding, this.getLineHeight(index + 1) - this.fontSize/2, this.fontSize, this.fontSize);
ctx.fillStyle = this.legendColors[index].fill;
ctx.fillRect(this.x + this.xPadding, this.getLineHeight(index + 1) - this.fontSize/2, this.fontSize, this.fontSize);
},this);
}
}
});
Chart.Scale = Chart.Element.extend({
initialize : function(){
this.fit();
},
buildYLabels : function(){
this.yLabels = [];
var stepDecimalPlaces = getDecimalPlaces(this.stepValue);
for (var i=0; i<=this.steps; i++){
this.yLabels.push(template(this.templateString,{value:(this.min + (i * this.stepValue)).toFixed(stepDecimalPlaces)}));
}
this.yLabelWidth = (this.display && this.showLabels) ? longestText(this.ctx,this.font,this.yLabels) : 0;
},
addXLabel : function(label){
this.xLabels.push(label);
this.valuesCount++;
this.fit();
},
removeXLabel : function(){
this.xLabels.shift();
this.valuesCount--;
this.fit();
},
// Fitting loop to rotate x Labels and figure out what fits there, and also calculate how many Y steps to use
fit: function(){
// First we need the width of the yLabels, assuming the xLabels aren't rotated
// To do that we need the base line at the top and base of the chart, assuming there is no x label rotation
this.startPoint = (this.display) ? this.fontSize : 0;
this.endPoint = (this.display) ? this.height - (this.fontSize * 1.5) - 5 : this.height; // -5 to pad labels
// Apply padding settings to the start and end point.
this.startPoint += this.padding;
this.endPoint -= this.padding;
// Cache the starting height, so can determine if we need to recalculate the scale yAxis
var cachedHeight = this.endPoint - this.startPoint,
cachedYLabelWidth;
// Build the current yLabels so we have an idea of what size they'll be to start
/*
* This sets what is returned from calculateScaleRange as static properties of this class:
*
this.steps;
this.stepValue;
this.min;
this.max;
*
*/
this.calculateYRange(cachedHeight);
// With these properties set we can now build the array of yLabels
// and also the width of the largest yLabel
this.buildYLabels();
this.calculateXLabelRotation();
while((cachedHeight > this.endPoint - this.startPoint)){
cachedHeight = this.endPoint - this.startPoint;
cachedYLabelWidth = this.yLabelWidth;
this.calculateYRange(cachedHeight);
this.buildYLabels();
// Only go through the xLabel loop again if the yLabel width has changed
if (cachedYLabelWidth < this.yLabelWidth){
this.calculateXLabelRotation();
}
}
},
calculateXLabelRotation : function(){
//Get the width of each grid by calculating the difference
//between x offsets between 0 and 1.
this.ctx.font = this.font;
var firstWidth = this.ctx.measureText(this.xLabels[0]).width,
lastWidth = this.ctx.measureText(this.xLabels[this.xLabels.length - 1]).width,
firstRotated,
lastRotated;
this.xScalePaddingRight = lastWidth/2 + 3;
this.xScalePaddingLeft = (firstWidth/2 > this.yLabelWidth + 10) ? firstWidth/2 : this.yLabelWidth + 10;
this.xLabelRotation = 0;
if (this.display){
var originalLabelWidth = longestText(this.ctx,this.font,this.xLabels),
cosRotation,
firstRotatedWidth;
this.xLabelWidth = originalLabelWidth;
//Allow 3 pixels x2 padding either side for label readability
var xGridWidth = Math.floor(this.calculateX(1) - this.calculateX(0)) - 6;
//Max label rotate should be 90 - also act as a loop counter
while ((this.xLabelWidth > xGridWidth && this.xLabelRotation === 0) || (this.xLabelWidth > xGridWidth && this.xLabelRotation <= 90 && this.xLabelRotation > 0)){
cosRotation = Math.cos(toRadians(this.xLabelRotation));
firstRotated = cosRotation * firstWidth;
lastRotated = cosRotation * lastWidth;
// We're right aligning the text now.
if (firstRotated + this.fontSize / 2 > this.yLabelWidth + 8){
this.xScalePaddingLeft = firstRotated + this.fontSize / 2;
}
this.xScalePaddingRight = this.fontSize/2;
this.xLabelRotation++;
this.xLabelWidth = cosRotation * originalLabelWidth;
}
if (this.xLabelRotation > 0){
this.endPoint -= Math.sin(toRadians(this.xLabelRotation))*originalLabelWidth + 3;
}
}
else{
this.xLabelWidth = 0;
this.xScalePaddingRight = this.padding;
this.xScalePaddingLeft = this.padding;
}
},
// Needs to be overidden in each Chart type
// Otherwise we need to pass all the data into the scale class
calculateYRange: noop,
drawingArea: function(){
return this.startPoint - this.endPoint;
},
calculateY : function(value){
var scalingFactor = this.drawingArea() / (this.min - this.max);
return this.endPoint - (scalingFactor * (value - this.min));
},
calculateX : function(index){
var isRotated = (this.xLabelRotation > 0),
// innerWidth = (this.offsetGridLines) ? this.width - offsetLeft - this.padding : this.width - (offsetLeft + halfLabelWidth * 2) - this.padding,
innerWidth = this.width - (this.xScalePaddingLeft + this.xScalePaddingRight),
valueWidth = innerWidth/Math.max((this.valuesCount - ((this.offsetGridLines) ? 0 : 1)), 1),
valueOffset = (valueWidth * index) + this.xScalePaddingLeft;
if (this.offsetGridLines){
valueOffset += (valueWidth/2);
}
return Math.round(valueOffset);
},
update : function(newProps){
helpers.extend(this, newProps);
this.fit();
},
draw : function(){
var ctx = this.ctx,
yLabelGap = (this.endPoint - this.startPoint) / this.steps,
xStart = Math.round(this.xScalePaddingLeft);
if (this.display){
ctx.fillStyle = this.textColor;
ctx.font = this.font;
each(this.yLabels,function(labelString,index){
var yLabelCenter = this.endPoint - (yLabelGap * index),
linePositionY = Math.round(yLabelCenter),
drawHorizontalLine = this.showHorizontalLines;
ctx.textAlign = "right";
ctx.textBaseline = "middle";
if (this.showLabels){
ctx.fillText(labelString,xStart - 10,yLabelCenter);
}
// This is X axis, so draw it
if (index === 0 && !drawHorizontalLine){
drawHorizontalLine = true;
}
if (drawHorizontalLine){
ctx.beginPath();
}
if (index > 0){
// This is a grid line in the centre, so drop that
ctx.lineWidth = this.gridLineWidth;
ctx.strokeStyle = this.gridLineColor;
} else {
// This is the first line on the scale
ctx.lineWidth = this.lineWidth;
ctx.strokeStyle = this.lineColor;
}
linePositionY += helpers.aliasPixel(ctx.lineWidth);
if(drawHorizontalLine){
ctx.moveTo(xStart, linePositionY);
ctx.lineTo(this.width, linePositionY);
ctx.stroke();
ctx.closePath();
}
ctx.lineWidth = this.lineWidth;
ctx.strokeStyle = this.lineColor;
ctx.beginPath();
ctx.moveTo(xStart - 5, linePositionY);
ctx.lineTo(xStart, linePositionY);
ctx.stroke();
ctx.closePath();
},this);
each(this.xLabels,function(label,index){
var xPos = this.calculateX(index) + aliasPixel(this.lineWidth),
// Check to see if line/bar here and decide where to place the line
linePos = this.calculateX(index - (this.offsetGridLines ? 0.5 : 0)) + aliasPixel(this.lineWidth),
isRotated = (this.xLabelRotation > 0),
drawVerticalLine = this.showVerticalLines;
// This is Y axis, so draw it
if (index === 0 && !drawVerticalLine){
drawVerticalLine = true;
}
if (drawVerticalLine){
ctx.beginPath();
}
if (index > 0){
// This is a grid line in the centre, so drop that
ctx.lineWidth = this.gridLineWidth;
ctx.strokeStyle = this.gridLineColor;
} else {
// This is the first line on the scale
ctx.lineWidth = this.lineWidth;
ctx.strokeStyle = this.lineColor;
}
if (drawVerticalLine){
ctx.moveTo(linePos,this.endPoint);
ctx.lineTo(linePos,this.startPoint - 3);
ctx.stroke();
ctx.closePath();
}
ctx.lineWidth = this.lineWidth;
ctx.strokeStyle = this.lineColor;
// Small lines at the bottom of the base grid line
ctx.beginPath();
ctx.moveTo(linePos,this.endPoint);
ctx.lineTo(linePos,this.endPoint + 5);
ctx.stroke();
ctx.closePath();
ctx.save();
ctx.translate(xPos,(isRotated) ? this.endPoint + 12 : this.endPoint + 8);
ctx.rotate(toRadians(this.xLabelRotation)*-1);
ctx.font = this.font;
ctx.textAlign = (isRotated) ? "right" : "center";
ctx.textBaseline = (isRotated) ? "middle" : "top";
ctx.fillText(label, 0, 0);
ctx.restore();
},this);
}
}
});
Chart.RadialScale = Chart.Element.extend({
initialize: function(){
this.size = min([this.height, this.width]);
this.drawingArea = (this.display) ? (this.size/2) - (this.fontSize/2 + this.backdropPaddingY) : (this.size/2);
},
calculateCenterOffset: function(value){
// Take into account half font size + the yPadding of the top value
var scalingFactor = this.drawingArea / (this.max - this.min);
return (value - this.min) * scalingFactor;
},
update : function(){
if (!this.lineArc){
this.setScaleSize();
} else {
this.drawingArea = (this.display) ? (this.size/2) - (this.fontSize/2 + this.backdropPaddingY) : (this.size/2);
}
this.buildYLabels();
},
buildYLabels: function(){
this.yLabels = [];
var stepDecimalPlaces = getDecimalPlaces(this.stepValue);
for (var i=0; i<=this.steps; i++){
this.yLabels.push(template(this.templateString,{value:(this.min + (i * this.stepValue)).toFixed(stepDecimalPlaces)}));
}
},
getCircumference : function(){
return ((Math.PI*2) / this.valuesCount);
},
setScaleSize: function(){
/*
* Right, this is really confusing and there is a lot of maths going on here
* The gist of the problem is here: https://gist.github.com/nnnick/696cc9c55f4b0beb8fe9
*
* Reaction: https://dl.dropboxusercontent.com/u/34601363/toomuchscience.gif
*
* Solution:
*
* We assume the radius of the polygon is half the size of the canvas at first
* at each index we check if the text overlaps.
*
* Where it does, we store that angle and that index.
*
* After finding the largest index and angle we calculate how much we need to remove
* from the shape radius to move the point inwards by that x.
*
* We average the left and right distances to get the maximum shape radius that can fit in the box
* along with labels.
*
* Once we have that, we can find the centre point for the chart, by taking the x text protrusion
* on each side, removing that from the size, halving it and adding the left x protrusion width.
*
* This will mean we have a shape fitted to the canvas, as large as it can be with the labels
* and position it in the most space efficient manner
*
* https://dl.dropboxusercontent.com/u/34601363/yeahscience.gif
*/
// Get maximum radius of the polygon. Either half the height (minus the text width) or half the width.
// Use this to calculate the offset + change. - Make sure L/R protrusion is at least 0 to stop issues with centre points
var largestPossibleRadius = min([(this.height/2 - this.pointLabelFontSize - 5), this.width/2]),
pointPosition,
i,
textWidth,
halfTextWidth,
furthestRight = this.width,
furthestRightIndex,
furthestRightAngle,
furthestLeft = 0,
furthestLeftIndex,
furthestLeftAngle,
xProtrusionLeft,
xProtrusionRight,
radiusReductionRight,
radiusReductionLeft,
maxWidthRadius;
this.ctx.font = fontString(this.pointLabelFontSize,this.pointLabelFontStyle,this.pointLabelFontFamily);
for (i=0;i<this.valuesCount;i++){
// 5px to space the text slightly out - similar to what we do in the draw function.
pointPosition = this.getPointPosition(i, largestPossibleRadius);
textWidth = this.ctx.measureText(template(this.templateString, { value: this.labels[i] })).width + 5;
if (i === 0 || i === this.valuesCount/2){
// If we're at index zero, or exactly the middle, we're at exactly the top/bottom
// of the radar chart, so text will be aligned centrally, so we'll half it and compare
// w/left and right text sizes
halfTextWidth = textWidth/2;
if (pointPosition.x + halfTextWidth > furthestRight) {
furthestRight = pointPosition.x + halfTextWidth;
furthestRightIndex = i;
}
if (pointPosition.x - halfTextWidth < furthestLeft) {
furthestLeft = pointPosition.x - halfTextWidth;
furthestLeftIndex = i;
}
}
else if (i < this.valuesCount/2) {
// Less than half the values means we'll left align the text
if (pointPosition.x + textWidth > furthestRight) {
furthestRight = pointPosition.x + textWidth;
furthestRightIndex = i;
}
}
else if (i > this.valuesCount/2){
// More than half the values means we'll right align the text
if (pointPosition.x - textWidth < furthestLeft) {
furthestLeft = pointPosition.x - textWidth;
furthestLeftIndex = i;
}
}
}
xProtrusionLeft = furthestLeft;
xProtrusionRight = Math.ceil(furthestRight - this.width);
furthestRightAngle = this.getIndexAngle(furthestRightIndex);
furthestLeftAngle = this.getIndexAngle(furthestLeftIndex);
radiusReductionRight = xProtrusionRight / Math.sin(furthestRightAngle + Math.PI/2);
radiusReductionLeft = xProtrusionLeft / Math.sin(furthestLeftAngle + Math.PI/2);
// Ensure we actually need to reduce the size of the chart
radiusReductionRight = (isNumber(radiusReductionRight)) ? radiusReductionRight : 0;
radiusReductionLeft = (isNumber(radiusReductionLeft)) ? radiusReductionLeft : 0;
this.drawingArea = largestPossibleRadius - (radiusReductionLeft + radiusReductionRight)/2;
//this.drawingArea = min([maxWidthRadius, (this.height - (2 * (this.pointLabelFontSize + 5)))/2])
this.setCenterPoint(radiusReductionLeft, radiusReductionRight);
},
setCenterPoint: function(leftMovement, rightMovement){
var maxRight = this.width - rightMovement - this.drawingArea,
maxLeft = leftMovement + this.drawingArea;
this.xCenter = (maxLeft + maxRight)/2;
// Always vertically in the centre as the text height doesn't change
this.yCenter = (this.height/2);
},
getIndexAngle : function(index){
var angleMultiplier = (Math.PI * 2) / this.valuesCount;
// Start from the top instead of right, so remove a quarter of the circle
return index * angleMultiplier - (Math.PI/2);
},
getPointPosition : function(index, distanceFromCenter){
var thisAngle = this.getIndexAngle(index);
return {
x : (Math.cos(thisAngle) * distanceFromCenter) + this.xCenter,
y : (Math.sin(thisAngle) * distanceFromCenter) + this.yCenter
};
},
draw: function(){
if (this.display){
var ctx = this.ctx;
each(this.yLabels, function(label, index){
// Don't draw a centre value
if (index > 0){
var yCenterOffset = index * (this.drawingArea/this.steps),
yHeight = this.yCenter - yCenterOffset,
pointPosition;
// Draw circular lines around the scale
if (this.lineWidth > 0){
ctx.strokeStyle = this.lineColor;
ctx.lineWidth = this.lineWidth;
if(this.lineArc){
ctx.beginPath();
ctx.arc(this.xCenter, this.yCenter, yCenterOffset, 0, Math.PI*2);
ctx.closePath();
ctx.stroke();
} else{
ctx.beginPath();
for (var i=0;i<this.valuesCount;i++)
{
pointPosition = this.getPointPosition(i, this.calculateCenterOffset(this.min + (index * this.stepValue)));
if (i === 0){
ctx.moveTo(pointPosition.x, pointPosition.y);
} else {
ctx.lineTo(pointPosition.x, pointPosition.y);
}
}
ctx.closePath();
ctx.stroke();
}
}
if(this.showLabels){
ctx.font = fontString(this.fontSize,this.fontStyle,this.fontFamily);
if (this.showLabelBackdrop){
var labelWidth = ctx.measureText(label).width;
ctx.fillStyle = this.backdropColor;
ctx.fillRect(
this.xCenter - labelWidth/2 - this.backdropPaddingX,
yHeight - this.fontSize/2 - this.backdropPaddingY,
labelWidth + this.backdropPaddingX*2,
this.fontSize + this.backdropPaddingY*2
);
}
ctx.textAlign = 'center';
ctx.textBaseline = "middle";
ctx.fillStyle = this.fontColor;
ctx.fillText(label, this.xCenter, yHeight);
}
}
}, this);
if (!this.lineArc){
ctx.lineWidth = this.angleLineWidth;
ctx.strokeStyle = this.angleLineColor;
for (var i = this.valuesCount - 1; i >= 0; i--) {
if (this.angleLineWidth > 0){
var outerPosition = this.getPointPosition(i, this.calculateCenterOffset(this.max));
ctx.beginPath();
ctx.moveTo(this.xCenter, this.yCenter);
ctx.lineTo(outerPosition.x, outerPosition.y);
ctx.stroke();
ctx.closePath();
}
// Extra 3px out for some label spacing
var pointLabelPosition = this.getPointPosition(i, this.calculateCenterOffset(this.max) + 5);
ctx.font = fontString(this.pointLabelFontSize,this.pointLabelFontStyle,this.pointLabelFontFamily);
ctx.fillStyle = this.pointLabelFontColor;
var labelsCount = this.labels.length,
halfLabelsCount = this.labels.length/2,
quarterLabelsCount = halfLabelsCount/2,
upperHalf = (i < quarterLabelsCount || i > labelsCount - quarterLabelsCount),
exactQuarter = (i === quarterLabelsCount || i === labelsCount - quarterLabelsCount);
if (i === 0){
ctx.textAlign = 'center';
} else if(i === halfLabelsCount){
ctx.textAlign = 'center';
} else if (i < halfLabelsCount){
ctx.textAlign = 'left';
} else {
ctx.textAlign = 'right';
}
// Set the correct text baseline based on outer positioning
if (exactQuarter){
ctx.textBaseline = 'middle';
} else if (upperHalf){
ctx.textBaseline = 'bottom';
} else {
ctx.textBaseline = 'top';
}
ctx.fillText(this.labels[i], pointLabelPosition.x, pointLabelPosition.y);
}
}
}
}
});
// Attach global event to resize each chart instance when the browser resizes
helpers.addEvent(window, "resize", (function(){
// Basic debounce of resize function so it doesn't hurt performance when resizing browser.
var timeout;
return function(){
clearTimeout(timeout);
timeout = setTimeout(function(){
each(Chart.instances,function(instance){
// If the responsive flag is set in the chart instance config
// Cascade the resize event down to the chart.
if (instance.options.responsive){
instance.resize(instance.render, true);
}
});
}, 50);
};
})());
if (amd) {
define(function(){
return Chart;
});
} else if (typeof module === 'object' && module.exports) {
module.exports = Chart;
}
root.Chart = Chart;
Chart.noConflict = function(){
root.Chart = previous;
return Chart;
};
}).call(this);
|
Array.prototype.push = function(elem) {
this[this.length] = elem;
return ++this.length;
}; |
'use strict';
const chai = require('chai'),
expect = chai.expect,
Support = require(__dirname + '/../support'),
current = Support.sequelize,
Op = current.Op,
sinon = require('sinon'),
DataTypes = require(__dirname + '/../../../lib/data-types'),
Promise = require('bluebird');
describe(Support.getTestDialectTeaser('Model'), () => {
describe('method findOne', () => {
before(function() {
this.oldFindAll = current.Model.findAll;
});
after(function() {
current.Model.findAll = this.oldFindAll;
});
beforeEach(function() {
this.stub = current.Model.findAll = sinon.stub().returns(Promise.resolve());
});
describe('should not add limit when querying on a primary key', () => {
it('with id primary key', function() {
const Model = current.define('model');
return Model.findOne({ where: { id: 42 }}).bind(this).then(function() {
expect(this.stub.getCall(0).args[0]).to.be.an('object').not.to.have.property('limit');
});
});
it('with custom primary key', function() {
const Model = current.define('model', {
uid: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true
}
});
return Model.findOne({ where: { uid: 42 }}).bind(this).then(function() {
expect(this.stub.getCall(0).args[0]).to.be.an('object').not.to.have.property('limit');
});
});
it('with blob primary key', function() {
const Model = current.define('model', {
id: {
type: DataTypes.BLOB,
primaryKey: true,
autoIncrement: true
}
});
return Model.findOne({ where: { id: new Buffer('foo') }}).bind(this).then(function() {
expect(this.stub.getCall(0).args[0]).to.be.an('object').not.to.have.property('limit');
});
});
});
it('should add limit when using { $ gt on the primary key', function() {
const Model = current.define('model');
return Model.findOne({ where: { id: { [Op.gt]: 42 }}}).bind(this).then(function() {
expect(this.stub.getCall(0).args[0]).to.be.an('object').to.have.property('limit');
});
});
describe('should not add limit when querying on an unique key', () => {
it('with custom unique key', function() {
const Model = current.define('model', {
unique: {
type: DataTypes.INTEGER,
unique: true
}
});
return Model.findOne({ where: { unique: 42 }}).bind(this).then(function() {
expect(this.stub.getCall(0).args[0]).to.be.an('object').not.to.have.property('limit');
});
});
it('with blob unique key', function() {
const Model = current.define('model', {
unique: {
type: DataTypes.BLOB,
unique: true
}
});
return Model.findOne({ where: { unique: new Buffer('foo') }}).bind(this).then(function() {
expect(this.stub.getCall(0).args[0]).to.be.an('object').not.to.have.property('limit');
});
});
});
it('should add limit when using multi-column unique key', function() {
const Model = current.define('model', {
unique1: {
type: DataTypes.INTEGER,
unique: 'unique'
},
unique2: {
type: DataTypes.INTEGER,
unique: 'unique'
}
});
return Model.findOne({ where: { unique1: 42}}).bind(this).then(function() {
expect(this.stub.getCall(0).args[0]).to.be.an('object').to.have.property('limit');
});
});
});
});
|
$(document).foundation();
function getTimeString(milli) {
var d, h, m, s;
s = Math.floor(milli / 1000);
m = Math.floor(s / 60);
s -= m * 60;
h = Math.floor(m / 60);
m -= h * 60;
d = Math.floor(h / 24);
h -= d * 24;
return d + ' days, ' + h + ' hours, ' + m + ' minutes, ' + s + ' seconds';
}
$(function() {
if ($("#countdowns").length > 0) {
var interval = setInterval(function() {
var now = new Date();
$('#countdowns tbody tr').each(function() {
var date = new Date(parseInt($(this).find('> td:nth(1)').attr('data:end_date')));
if (date > now) {
$(this).find('> td:nth(1)').text(getTimeString(date.getTime() - now.getTime()));
} else {
$(this).find('> td:nth(1)').text("DONE");
}
});
}, 1000);
}
});
$(function () {
if (typeof start == 'undefined' || typeof end == 'undefined') return;
var data;
var loadQuotes = function () {
setTimeout(function() {
var item;
$.each(hashtags, function(key, hash) {
item = '<div id="quote-' + key + '">"' + hash.text + '" <br> -- <span class="author">' + hash.name + '</span></div>';
$('#quotes').cycle('add', item);
});
}, 2000);
};
var getData = function (now) {
var total, remaining;
if ('undefined' == typeof(now)) {
now = new Date();
}
total = end.getTime() - start.getTime();
remaining = end.getTime() - now.getTime();
return {
percent: Math.floor((1 - (remaining / total)) * 100),
remaining: remaining
};
};
var updateElements = function (percent, timeRemaining) {
if ($("#fader").hasClass('GTFO')) percent = 100 - percent;
if (percent < 100 && percent > 0) {
$('#fader').css('opacity', percent / 100).css('filter', 'alpha(opacity=' + percent + ')');
$('#description').text(start_description);
$('#remaining').text(timeRemaining);
$('#iscoming').show();
} else {
$('#fader').css('opacity', percent / 100).css('filter', 'alpha(opacity=' + percent + ')');
$('#description').text(end_description);
finish();
}
};
var go = function() {
var interval = setInterval(function() {
data = getData(new Date());
//console.log(data);
if (data.remaining <= 0) {
// Stop the countdown
clearInterval(interval);
updateElements(data.percent, getTimeString(data.remaining));
finish();
}
updateElements(data.percent, getTimeString(data.remaining));
}, 1000);
$('#iscoming').fadeIn();
};
var finish = function () {
$('#iscoming').hide();
};
loadQuotes();
if (start >= end) {
finish();
}
go();
}); |
/**
* Models shared globally
*/
/**
* Entity model
* @param name
* @constructor
*/
function Entity(name) {
this.name = name;
this.id = 'entity-' + this.name;
this.attributes = [];
this.dom = null;
this.connectors = [];
this.relationConnectors = [];
}
Entity.prototype.archive = function() {
var position = angular.element(this.dom).position();
var attributesData = this.attributes.map(function(attr) {
return attr.archive();
});
return {
name: this.name,
id: this.id,
attributes: attributesData,
position: position
};
};
Entity.prototype.rename = function(newName) {
this.name = newName;
this.id = 'entity-' + this.name;
this.dom.id = this.id;
};
Entity.prototype.isDuplicateAttributeName = function (name) {
return this.attributes.some(function(attr) {
return attr.name.toLowerCase() === name.toLowerCase();
});
}
Entity.prototype.addAttribute = function (attributeData) {
// check for duplicate name first
if (this.isDuplicateAttributeName(attributeData.name)) {
return false;
}
var newAttr = new Attribute(attributeData);
this.attributes.push(newAttr);
return newAttr;
};
Entity.prototype.getAttribute = function (index) {
return this.attributes[index];
};
Entity.prototype.getAttributeByName = function (name) {
return this.attributes.find(function(attr) {
return attr.name === name;
});
};
/**
*
* @param index
* @param attributeData
* @returns {boolean} if the edit operation succeed or not
*/
Entity.prototype.editAttribute = function (index, attributeData) {
if (this.attributes[index].name.toLowerCase() === attributeData.name.toLowerCase()) {
this.attributes[index].updateData(attributeData);
return true;
}
if (this.isDuplicateAttributeName(attributeData.name)) {
return false;
}
this.attributes[index].updateData(attributeData);
return true;
};
Entity.prototype.removeAttribute = function (index) {
var attr = this.attributes[index];
attr.destroy();
this.attributes.splice(index, 1);
};
Entity.prototype.addConnectors = function (connectors) {
this.connectors.push(connectors);
};
Entity.prototype.removeConnectors = function (connectors) {
var idx = this.connectors.indexOf(connectors);
if (idx === -1) {
return;
}
this.connectors.splice(idx, 1);
};
Entity.prototype.addRelationConnector = function (connector) {
this.relationConnectors.push(connector);
};
Entity.prototype.removeRelationConnector = function (connector) {
var idx = this.relationConnectors.indexOf(connector);
if (idx === -1) {
return;
}
this.relationConnectors.splice(idx, 1);
};
Entity.prototype.destroy = function () {
this.attributes.forEach(function(e) {
e.destroy();
})
this.attributes = [];
if (this.dom[0] && this.dom[0].parentNode) {
this.dom[0].parentNode.removeChild(this.dom[0]);
}
};
Entity.prototype.summarize = function () {
var attributes = [];
var primaryKeys = [];
this.attributes.forEach(function (attribute) {
var meta = {
name: attribute.name,
type: attribute.type.name
};
if (attribute.type.hasLength) {
meta.length = attribute.type.length;
}
if (attribute.notNull) {
meta.notNull = true;
}
if (attribute.isPrimaryKey) {
primaryKeys.push(attribute.name);
}
attributes.push(meta);
});
return {
type: 'entity',
name: this.name,
attributes: attributes,
primaryKey: primaryKeys
}
};
/**
* Relationship model
* @param name
* @constructor
*/
function Relationship(name) {
this.name = name;
this.id = 'relationship-' + this.name;
this.attributes = [];
this.dom = null;
this.connectors = [];
this.references = [];
this.relationConnectors = [];
}
Relationship.prototype.archive = function() {
var position = angular.element(this.dom).position();
var attributesData = this.attributes.map(function(attr) {
return attr.archive();
});
var referencesData = this.references.map(function(ref) {
return ref.archive();
});
return {
name: this.name,
id: this.id,
attributes: attributesData,
references: referencesData,
position: position
};
};
Relationship.prototype.rename = function(newName) {
this.name = newName;
this.id = 'relationship-' + this.name;
this.dom.id = this.id;
};
Relationship.prototype.isDuplicateAttributeName = function (name) {
return this.attributes.some(function(attr) {
return attr.name.toLowerCase() === name.toLowerCase();
});
}
Relationship.prototype.isDuplicateReferenceName = function (name) {
return this.references.some(function(ref) {
return ref.name.toLowerCase() === name.toLowerCase();
});
}
Relationship.prototype.isDuplicateReference = function (entity, attribute) {
return this.references.some(function(ref) {
return ref.from.entity === entity && ref.from.attribute === attribute;
});
}
Relationship.prototype.addAttribute = function (attributeData) {
// check for duplicate name first
if (this.isDuplicateAttributeName(attributeData.name)) {
return false;
}
if (this.isDuplicateReferenceName(attributeData.name)) {
return false;
}
var newAttr = new Attribute(attributeData);
this.attributes.push(newAttr);
return newAttr;
};
Relationship.prototype.getAttribute = function (index) {
return this.attributes[index];
};
Relationship.prototype.editAttribute = function (index, attributeData) {
if (this.attributes[index].name.toLowerCase() === attributeData.name.toLowerCase()) {
this.attributes[index].updateData(attributeData);
return true;
}
if (this.isDuplicateAttributeName(attributeData.name)) {
return false;
}
this.attributes[index].updateData(attributeData);
return true;
};
Relationship.prototype.removeAttribute = function (index) {
// also delete connectors if needed
this.attributes.splice(index, 1);
};
Relationship.prototype.addReference = function (ctrl, data) {
// check for duplicate name first
if (this.isDuplicateReference(data.entity, data.attribute)) {
return false;
}
var reference = new Reference(ctrl, this, data.entity, data.attribute, data.name, data.type, data.isPrimaryKey);
// add to relationship
this.references.push(reference);
// add to referenced attribute
data.attribute.addReference(reference);
return reference;
};
Relationship.prototype.removeReference = function (reference) {
var idx = this.references.indexOf(reference);
if (idx === -1) {
return;
}
this.references.splice(idx, 1);
};
Relationship.prototype.addConnectors = function (connectors) {
this.connectors.push(connectors);
};
Relationship.prototype.removeConnectors = function (connectors) {
var idx = this.connectors.indexOf(connectors);
if (idx === -1) {
return;
}
this.connectors.splice(idx, 1);
};
Relationship.prototype.addRelationConnector = function (connector) {
this.relationConnectors.push(connector);
};
Relationship.prototype.removeRelationConnector = function (connector) {
var idx = this.relationConnectors.indexOf(connector);
if (idx === -1) {
return;
}
this.relationConnectors.splice(idx, 1);
};
Relationship.prototype.destroy = function () {
this.attributes.forEach(function(e) {
e.destroy();
});
for (var i = this.references.length - 1; i >= 0; i--) {
this.references[i].destroy();
}
this.attributes = [];
this.references = [];
if (this.dom[0] && this.dom[0].parentNode) {
this.dom[0].parentNode.removeChild(this.dom[0]);
}
};
Relationship.prototype.summarize = function () {
var attributes = [];
var primaryKeys = [];
var foreignKeys = [];
var linkedEntities = [];
this.attributes.forEach(function (attribute) {
var meta = {
name: attribute.name,
type: attribute.type.name
};
if (attribute.type.hasLength) {
meta.length = attribute.type.length;
}
if (attribute.notNull) {
meta.notNull = true;
}
if (attribute.isPrimaryKey) {
primaryKeys.push(attribute.name);
}
attributes.push(meta);
});
this.references.forEach(function (reference) {
var meta = {
name: reference.name,
type: reference.type.name
};
if (reference.type.hasLength) {
meta.length = reference.type.length;
}
if (reference.isPrimaryKey) {
primaryKeys.push(reference.name);
}
var foreignKeyMeta = {
attribute: reference.name,
reference: {
'source entity': reference.from.entity.name,
'source attribute': reference.from.attribute.name
}
};
if (linkedEntities.indexOf(reference.from.entity.name) === -1) {
linkedEntities.push(reference.from.entity.name);
}
foreignKeys.push(foreignKeyMeta);
attributes.push(meta);
});
return {
type: 'relationship',
name: this.name,
linkedEntities: linkedEntities,
attributes: attributes,
primaryKey: primaryKeys,
foreignKeys: foreignKeys
}
};
/**
* Attribute model
* @param attributeData
* @constructor
*/
function Attribute(attributeData) {
this.name = attributeData.name;
this.type = attributeData.type;
this.notNull = attributeData.notNull;
this.isPrimaryKey = attributeData.isPrimaryKey || false;
this.isForeignKey = attributeData.isForeignKey || false;
this.isKey = this.isPrimaryKey || this.isForeignKey;
this.dom = null;
this.connectors = [];
this.references = []; // keep the references
}
Attribute.prototype.updateData = function (attributeData) {
this.name = attributeData.name;
this.type = attributeData.type;
this.notNull = attributeData.notNull;
this.isPrimaryKey = attributeData.isPrimaryKey || false;
this.isForeignKey = attributeData.isForeignKey || false;
};
Attribute.prototype.archive = function() {
return {
name: this.name,
type: this.type,
notNull: this.notNull,
isPrimaryKey: this.isPrimaryKey,
isForeignKey: this.isForeignKey
};
};
Attribute.prototype.addConnectors = function (connectors) {
this.connectors.push(connectors);
};
/**
*
* @param {Reference} reference
*/
Attribute.prototype.addReference = function (reference) {
this.references.push(reference);
};
/**
*
* @param {Reference} r
*/
Attribute.prototype.removeReference = function(r) {
var idx = this.references.indexOf(r);
if (idx == -1) { return; }
this.references.splice(idx,1);
}
Attribute.prototype.removeConnectors = function (connectors) {
var idx = this.connectors.indexOf(connectors);
if (idx === -1) {
return;
}
this.connectors.splice(idx, 1);
};
Attribute.prototype.destroy = function () {
this.references.forEach(function(ref) {
// remove it from the owner ctrl and model
ref.ownerCtrl.onRemoveReference(ref);
});
this.references = [];
if (this.dom[0] && this.dom[0].parentNode) {
this.dom[0].parentNode.removeChild(this.dom[0]);
}
};
/**
*
* Reference model
* @param ownerCtrl
* @param {Relationship} owner
* @param {Entity} fromEntity
* @param {Attribute} fromAttribute
* @param {string} name
* @param {DataType} type
* @param {boolean} isPrimaryKey
* @constructor
*/
function Reference(ownerCtrl, owner, fromEntity, fromAttribute, name, type, isPrimaryKey) {
this.name = name;
this.ownerCtrl = ownerCtrl;
this.owner = owner;
this.type = type;
this.from = {};
this.from.entity = fromEntity;
this.from.attribute = fromAttribute;
this.isPrimaryKey = isPrimaryKey;
}
Reference.prototype.archive = function() {
return {
name: this.name,
type: this.type,
owner: this.owner.name,
from: {
entity: this.from.entity.name,
attribute: this.from.attribute.name
},
isPrimaryKey: this.isPrimaryKey
};
};
/**
*
* @param {Entity} fromEntity
* @param {Attribute} fromAttribute
* @param {string} name
* @param {DataType} type
* @param {boolean} isPrimaryKey
*/
Reference.prototype.onUpdate = function (fromEntity, fromAttribute, name, type, isPrimaryKey) {
// check the same name first
if (this.owner.isDuplicateReferenceName(name) && this.name.toLowerCase() !== name.toLowerCase()) {
return alert('The reference name already exists in this relationship');
}
// check if this gonna be a duplicate reference
if (this.owner.isDuplicateReference(fromEntity, fromAttribute) && (this.from.entity !== fromEntity || this.from.attribute !== fromAttribute)) {
return alert('This reference already exists in this relationship');
}
// if it's not the same from entity, need to remove it and redraw
// otherwise just change the diagram
if (fromEntity !== this.from.entity) {
// update the link
this.ownerCtrl.checkAndRemoveConnector(this);
this.ownerCtrl.addRelationConnectors(fromEntity);
this.from.entity = fromEntity;
}
if (fromAttribute !== this.from.attribute) {
this.from.attribute.removeReference(this);
fromAttribute.addReference(this);
this.from.attribute = fromAttribute;
}
// update meta infos
this.name = name;
this.type = type;
this.isPrimaryKey = isPrimaryKey;
};
Reference.prototype.onRemove = function () {
this.ownerCtrl.removeReference(this);
};
Reference.prototype.destroy = function () {
this.ownerCtrl.onRemoveReference(this);
};
/**
* DataType model
* @param name
* @param length
* @constructor
*/
function DataType(name, length) {
this.name = name;
this.length = length || 0;
this.hasLength = this.length !== 0 || false;
} |
var express = require('express');
var app = express();
var server = app.listen(7027);
var handlebars = require("express3-handlebars");
console.log('listening on port 7027');
if (app.get('env') === 'development') {
app.use(express.logger('dev'));
}
app.use(require('./middleware/error')(server));
app.use(express.compress());
app.use(express.favicon("favicon.ico"));
app.use(require('./middleware/cors'));
app.use(express.static('public'));
app.engine('hbs', handlebars({defaultLayout: 'main',extname: '.hbs'}));
app.set('view engine', 'hbs');
app.set('views','views');
app.use(require("./routes/tile"));
app.use(require("./routes/map"));
app.use(require("./routes/misc")); |
import moment from 'moment';
// filter reducer
const filtersReducerDefaultState = {
text: '',
sortBy: 'date',
startDate: moment().startOf('month'),
endDate: moment().endOf('month')
};
const filtersReducer = (state = filtersReducerDefaultState, action) => {
switch (action.type) {
case 'SET_TEXT_FILTER':
return {
...state,
text: action.text
}
case 'SORT_BY_AMOUNT':
return {
...state,
sortBy: 'amount'
}
case 'SORT_BY_DATE':
return {
...state,
sortBy: 'date'
}
case 'SET_START_DATE':
return {
...state,
startDate: action.startDate
};
case 'SET_END_DATE':
return {
...state,
endDate: action.endDate
};
default:
return state;
}
};
export default filtersReducer; |
/**
* Created by xesamguo@gmail.com
* 416249980@qq.com
*/
if (TouchSlide) {
throw new Error('TouchSlide: Duplicate!');
}
var TouchSlide = function (container, options) {
if (!container) {
throw new Error('TouchSlide:No container');
}
this.orientation = TouchSlide.HORIZONTAL;
if (options) {
this.orientation = options['orientation'];
}
this.container = this._$(container);
this.element = this.container.children[0];
this.slides = this.element.children;
this.slideLength = this.slides.length;
this.index = 0;
this.interval = 250;
this.slop = 20;
this.duration = 200;
this.init();
var _this = this;
this.element.addEventListener('touchstart', function (e) {
_this.touchstart(e);
}, false);
this.element.addEventListener('touchmove', function (e) {
_this.touchmove(e);
}, false);
this.element.addEventListener('touchend', function (e) {
_this.touchend(e);
}, false);
window.addEventListener('resize', function (e) {
_this.init();
}, false);
};
TouchSlide.VERTICAL = 1;
TouchSlide.HORIZONTAL = 0;
TouchSlide.prototype = {
constructor: TouchSlide,
_$: function (el) {
return 'string' == el ? document.getElementById(el) : el;
},
init: function () {
this.height = this.container.getBoundingClientRect().height;
this.width = this.container.getBoundingClientRect().width;
this.element.style.width = this.slideLength * this.width + 'px';
var index = this.slideLength;
while (index--) {
this.slides[index].style.width = this.width + 'px';
}
},
slideTo: function (index, duration) {
this.move(0, index, duration);
this.index = index;
},
move: function (delta, index, duration) {
var style = this.element.style;
style.webkitTransitionDuration = duration + 'ms';
style.webkitTransform = this.isVertical() ? 'translate3d(0, ' + ( delta - index * this.height) + 'px,0)'
: 'translate3d(' + ( delta - index * this.width) + 'px,0,0)';
},
isVertical: function () {
return this.orientation == TouchSlide.VERTICAL;
},
isValidSlide: function () {
var absDelta = Math.abs(this.deltaX);
var viewSize = this.width;
if (this.isVertical()) {
absDelta = Math.abs(this.deltaY);
viewSize = this.height;
}
return (Number(new Date()) - this.start.time < this.interval && absDelta > this.slop) || (absDelta > viewSize / 2);
},
isPastBounds: function () {
var delta = this.deltaX;
if (this.isVertical()) {
delta = this.deltaY;
}
return this.index == 0 && delta > 0 || this.index == this.slideLength - 1 && delta < 0;
},
touchstart: function (e) {
var touchEvent = e.touches[0];
this.deltaX = 0;
this.deltaY = 0;
this.start = {
x: touchEvent.pageX,
y: touchEvent.pageY,
time: Number(new Date())
};
this.originIntent = 0; //0:none; 1:horizontal; 2:vertical
this.element.style.webkitTransitionDuration = 0;
},
touchmove: function (e) {
var touchPoint = e.touches[0];
this.deltaX = touchPoint.pageX - this.start.x;
this.deltaY = touchPoint.pageY - this.start.y;
if (this.originIntent == 0) {
this.originIntent = Math.abs(this.deltaY) >= Math.abs(this.deltaX) ? 2 : 1;
}
if (this.isVertical() && this.originIntent == 2) {
e.preventDefault();
this.deltaY = this.deltaY / (this.isPastBounds() ? 2 : 1);
this.move(this.deltaY, this.index, 0);
}
if ((!this.isVertical()) && this.originIntent == 1) {
e.preventDefault();
this.deltaX = this.deltaX / (this.isPastBounds() ? 2 : 1);
this.move(this.deltaX, this.index, 0);
}
},
touchend: function (e) {
if ((this.isVertical() && this.originIntent == 2) || (!this.isVertical()) && this.originIntent == 1) {
var offset = this.isVertical() ? (this.deltaY < 0 ? 1 : -1) : (this.deltaX < 0 ? 1 : -1);
this.slideTo(this.index + ( this.isValidSlide() && !this.isPastBounds() ? offset : 0 ), this.duration);
}
}
};
|
var files =
[
[ "liczba.cpp", "liczba_8cpp.html", "liczba_8cpp" ],
[ "liczba.hh", "liczba_8hh.html", "liczba_8hh" ],
[ "macierz.cpp", "macierz_8cpp.html", "macierz_8cpp" ],
[ "macierz.hh", "macierz_8hh.html", "macierz_8hh" ],
[ "main.cpp", "main_8cpp.html", "main_8cpp" ],
[ "symbole.cpp", "symbole_8cpp.html", "symbole_8cpp" ],
[ "symbole.hh", "symbole_8hh.html", "symbole_8hh" ],
[ "typ.hh", "typ_8hh.html", "typ_8hh" ],
[ "uklad.cpp", "uklad_8cpp.html", "uklad_8cpp" ],
[ "uklad.hh", "uklad_8hh.html", "uklad_8hh" ],
[ "wektor.cpp", "wektor_8cpp.html", "wektor_8cpp" ],
[ "wektor.hh", "wektor_8hh.html", "wektor_8hh" ],
[ "zespolone.cpp", "zespolone_8cpp.html", "zespolone_8cpp" ],
[ "zespolone.hh", "zespolone_8hh.html", "zespolone_8hh" ]
]; |
export function mapValues(o, valueMapper) {
if (!o) {
return {};
}
const result = {};
Object.keys(o).forEach((key) => {
result[key] = valueMapper(o[key]);
});
return result;
}
|
// Publish the current user
Meteor.publish('currentUser', function() {
var user = Meteor.users.find({_id: this.userId}, {fields: ownUserOptions});
return user;
});
// publish all users for admins to make autocomplete work
// TODO: find a better way
Meteor.publish('allUsersAdmin', function() {
var selector = Settings.get('requirePostInvite') ? {isInvited: true} : {}; // only users that can post
if (isAdminById(this.userId)) {
return Meteor.users.find(selector, {fields: {
_id: true,
profile: true,
slug: true
}});
}
return [];
});
|
export default function errorMiddleware() {
return async (ctx, next) => {
try {
await next()
} catch (err) {
ctx.status = err.status || 500
ctx.body = { error: err.message }
ctx.app.emit('error', err, ctx)
}
}
}
|
$(document).ready(function() {
(function() {
window.onbeforeunload = function() {
return "Don't reload";
}
$(".submit-task").click(function() {
var result;
if (typeof Judicious.result === "function") {
result = Judicious.result();
} else {
result = Judicious.result;
}
if (!Judicious.validate(result)) {
return;
}
window.onbeforeunload = null;
$("body").fadeOut(650);
Judicious.postResult(Judicious.taskUUID, result, function() {
if (Judicious.turkSubmitTo !== "") {
$("#mturk_form").submit();
} else {
location.reload();
}
});
});
$("#skip-task").click(function() {
location.reload();
});
})();
});
|
module('lively.DOMAbstraction').requires().toRun(function() {
// ===========================================================================
// DOM manipulation (Browser and graphics-independent)
// ===========================================================================
Global.Namespace = {
SVG: "http:\/\/www.w3.org/2000/svg",
LIVELY: UserAgent.usableNamespacesInSerializer ? "http:\/\/www.experimentalstuff.com/Lively" : null,
XLINK: "http:\/\/www.w3.org/1999/xlink",
XHTML: "http:\/\/www.w3.org/1999/xhtml",
ATOM: "http:\/\/www.w3.org/2005/Atom",
// Google specific
OPENSEARCH: "http:\/\/a9.com/-/spec/opensearchrss/1.0/",
GBS: "http:\/\/schemas.google.com/books/2008",
DC: "http:\/\/purl.org/dc/terms",
BATCH: "http:\/\/schemas.google.com/gdata/batch",
GD: "http:\/\/schemas.google.com/g/2005",
// SVN / DAV
LP1: "DAV:"
};
Global.NodeFactory = {
remove: function(element) {
if (element.parentNode)
element.parentNode.removeChild(element);
},
createNS: function(ns, name, attributes) {
var element = Global.document.createElementNS(ns, name);
return NodeFactory.extend(ns, element, attributes);
},
create: function(name, attributes) {
//return this.createNS(Namespace.SVG, name, attributes); // doesn't work
var element = Global.document.createElementNS(Namespace.SVG, name);
return NodeFactory.extend(null, element, attributes);
},
extend: function(ns, element, attributes) {
if (attributes) {
for (var name in attributes) {
if (!attributes.hasOwnProperty(name)) continue;
element.setAttributeNS(ns, name, attributes[name]);
}
}
return element;
},
createText: function(string) {
return Global.document.createTextNode(string);
},
createNL: function(string) {
return Global.document.createTextNode("\n");
},
createCDATA: function(string) {
return Global.document.createCDATASection(string);
},
CDATAType: function() {
return Global.document.CDATA_SECTION_NODE;
},
TextType: function() {
return Global.document.TEXT_NODE;
},
FragmentType: function() {
return Global.document.DOCUMENT_FRAGMENT_NODE;
},
isTextNode: function(node) { return node && node.nodeType === this.TextType() },
isFragmentNode: function(node) { return node && node.nodeType === this.FragmentType() }
};
Global.LivelyNS = {
prefix: 'lively:',
create: function(name, attributes) {
// get takes qulaified name
return NodeFactory.createNS(Namespace.LIVELY, this.prefix + name, attributes);
},
getAttribute: function(node, name) {
if (UserAgent.isOpera) return node.getAttribute(name); // Fix for Opera 10.10
// get takes only local name
return node.getAttributeNS(Namespace.LIVELY, name) || node.getAttribute(name);
},
removeAttribute: function(node, name) {
// remove takes local name
return node.removeAttributeNS(Namespace.LIVELY, name);
},
setAttribute: function(node, name, value) {
// set takes qualified name
node.setAttributeNS(Namespace.LIVELY, this.prefix + name, value);
},
getType: function(node) {
return node.getAttributeNS(Namespace.LIVELY, "type") || node.getAttribute("type");
},
setType: function(node, string) {
node.setAttributeNS(Namespace.LIVELY, this.prefix + "type", string);
}
};
Global.XHTMLNS = {
create: function(name, attributes) {
return NodeFactory.createNS(Namespace.XHTML, name, attributes);
},
getAttribute: function(node, name) {
if (UserAgent.isOpera) return node.getAttribute(name); // Fix for Opera 10.10
return node.getAttributeNS(null, name);
},
removeAttribute: function(node, name) {
return node.removeAttributeNS(null, name);
},
setAttribute: function(node, name, value) {
node.setAttributeNS(null, name, value);
},
getType: function(node) {
return node.getAttributeNS(Namespace.LIVELY, "type");
},
setType: function(node, string) {
node.setAttributeNS(Namespace.LIVELY, "type", string);
},
newFragment: function(optChildNodes) {
var fragment = document.createDocumentFragment()
if (optChildNodes) optChildNodes.forEach(function(ea) { fragment.appendChild(ea) });
return fragment;
},
newCSSDef: function(string, id) {
var style = this.create('style'),
rules = document.createTextNode(string);
style.type = 'text/css'
if (style.styleSheet) style.styleSheet.cssText = rules.nodeValue
else style.appendChild(rules);
if (id) style.setAttribute('id', id);
return style;
},
addCSSDef: function(string, id) {
var def = XHTMLNS.newCSSDef(string, id)
Global.document.getElementsByTagName('head')[0].appendChild(def);
}
};
Object.subclass('Exporter');
Object.extend(Exporter, {
stringify: function(node) {
return node ? new XMLSerializer().serializeToString(node) : null;
}
});
Object.subclass('DocLinkConverter', {
initialize: function(codeBase, toDir) {
if (!codeBase.toString().endsWith('/')) codeBase = codeBase.toString() + '/';
if (!toDir.toString().endsWith('/')) toDir = toDir.toString() + '/';
this.codeBase = new URL(codeBase);
this.toDir = new URL(toDir).withRelativePartsResolved();
},
convert: function(doc) {
var scripts = Array.from(doc.getElementsByTagName('script'));
if (scripts.length <= 0) {
console.warn('could not convert scripts in doc in DocLinkConverter because no scripts found!');
return doc;
}
this.convertLinks(scripts);
this.convertAndRemoveCodeBaseDefs(scripts);
return doc;
},
convertAndRemoveCodeBaseDefs: function(scripts) {
var codeBaseDefs = scripts.select(function(el) {
return el.firstChild && el.firstChild.data && el.firstChild.data.startsWith('Config.codeBase=');
});
var codeBaseDef = this.createCodeBaseDef(this.codeBaseFrom(this.codeBase, this.toDir));
if (codeBaseDefs.length == 0) {
var script = NodeFactory.create('script');
script.setAttribute('name', 'codeBase');
script.appendChild(NodeFactory.createCDATA(codeBaseDef));
var localConfigScript = this.findScriptEndingWith('localconfig.js', scripts);
if (localConfigScript) {
localConfigScript.parentNode.insertBefore(script, localConfigScript);
localConfigScript.parentNode.insertBefore(NodeFactory.createNL(), localConfigScript);
}
return;
}
if (codeBaseDefs.length >= 1) {
var cdata = codeBaseDefs[0].firstChild;
cdata.data = codeBaseDef;
}
// remove remaining
for (var i = 1; i < codeBaseDefs.length; i++)
codeBaseDefs[i].parentNode.removeChild(codeBaseDefs[i]);
},
convertLinks: function(scripts) {
var links = scripts.select(function(el) { return this.getURLFrom(el) != null }, this);
links.forEach(function(el) {
var url = this.getURLFrom(el),
newUrl = this.convertPath(url);
this.setURLTo(el, newUrl);
}, this);
},
convertPath: function(path) {
if (path.startsWith('http')) return path;
var fn = this.extractFilename(path),
relative = this.relativeLivelyPathFrom(this.codeBase, this.toDir);
return relative + fn;
},
codeBaseFrom: function(codeBase, toDir) {
var urlCodeBase = new URL(codeBase),
urlToDir = new URL(toDir),
urlIsInCodeBase = (urlCodeBase.normalizedHostname() == urlToDir.normalizedHostname()) &&
(urlCodeBase.port == urlToDir.port);
return urlIsInCodeBase ? this.relativeCodeBaseFrom(codeBase, toDir) : urlCodeBase.toString();
},
relativeCodeBaseFrom: function(codeBase, toDir) {
codeBase = new URL(codeBase);
toDir = new URL(toDir);
var relative = toDir.relativePathFrom(codeBase);
if (relative.startsWith('/')) throw dbgOn(new Error('relative looks different than expected'));
var levels = relative.split('/').length -1
// FIXME result should count levels between lively root dir and codeBase
var result = Array.range(2, levels).collect(function() { return '..' }).join('/');
if (result.length > 0) result += '/';
return result;
},
relativeLivelyPathFrom: function(codeBase, toDir) {
return this.codeBaseFrom(codeBase, toDir) + 'core/lively/';
},
extractFilename: function(url) {
return url.substring(url.lastIndexOf('/') + 1, url.length);
},
createCodeBaseDef: function(relPath) {
return Strings.format('Config.codeBase=Config.getDocumentDirectory()+\'%s\'', relPath);
},
findScriptEndingWith: function(str, scripts) {
return scripts.detect(function(node) {
var url = this.getURLFrom(node);
return url && url.endsWith(str)
}, this);
},
getURLFrom: function(el) {
return el.getAttribute('xlink:href') || el.getAttribute('src')
},
setURLTo: function(el, url) {
var attrName = el.getAttribute('xlink:href') ? 'xlink:href' : 'src';
el.setAttribute(attrName, url)
}
});
Object.extend(Global, {
stringToXML: function(string) {
return new DOMParser().parseFromString(string, "text/xml").documentElement;
}
})
}); // end of module
|
var debug = require('debug')('ucwajs:auth');
var autoDiscover = require('./autoDiscover');
var Q = require('q');
var superagent = require('superagent');
module.exports = function authFactory(config, autoDiscoverResource) {
return auth.bind(this, autoDiscoverResource, config.username, config.password);
};
function auth(autoDiscoverResource, username, password) {
return autoDiscoverResource()
.then(function(autoDiscover) { return autoDiscover._links.user.href; })
.then(fetchOAuthUrl)
.then(function(oAuthUrl) { return [ oAuthUrl, username, password ]; })
.spread(fetchOAuthToken);
}
function fetchOAuthUrl(authUrl) {
debug('fetchOAuthUrl ' + authUrl);
var deferred = Q.defer();
superagent
.get(authUrl)
.end(function(err, res) {
if(err && err.status === 401) {
debug('Got unauthorized from API as expected');
var wwwAuthenticateHeader = res.header['www-authenticate'];
var matches = (/MsRtcOAuth href="([^\"]*)"/g).exec(wwwAuthenticateHeader);
if(matches.length >= 2) {
debug('Extracted OAuth url');
var oAuthUrl = matches[1];
deferred.resolve(oAuthUrl);
} else {
debug('Could not extract OAuth url');
deferred.reject(new Error('Could not extract OAuth url'));
}
} else {
debug('Did not receive unauthorized from API as we would expect');
deferred.reject(new Error('Did not receive status code 401 as expected'));
}
});
return deferred.promise;
}
function fetchOAuthToken(oAuthUrl, username, password) {
debug('fetchOAuthToken ' + oAuthUrl);
var deferred = Q.defer();
superagent
.post(oAuthUrl)
.type('form')
.send({
grant_type: 'password',
username: username,
password: password
})
.end(function(err, res) {
if(res.ok) {
if(res.body.access_token) {
debug('Receive OAuth token');
deferred.resolve(res.body.access_token);
} else {
debug('Could not read OAuth token from response');
deferred.reject(new Error('Could not read OAuth token from response'));
}
} else {
debug('Recived non-OK response from API');
deferred.reject(err);
}
});
return deferred.promise;
}
|
var o3 = require("o3"),
Class = o3.Class,
e3 = require("ezone"),
UserError = e3.UserError,
EventEmitter = require("events");
var Flow = Class.extend({
prototype: {
blocked: false,
init: function (options) {
EventEmitter.call(this);
this.dataQueue = [];
this.merge(options);
},
isDry: function () {
return !this.dataQueue.length;
},
extract: function () {
if (this.isDry())
throw new Flow.DryExtract(this);
var data = this.dataQueue.shift();
if (this.isDry())
this.emit("dry");
return data;
},
drain: function () {
if (this.isDry())
return [];
var data = this.dataQueue.slice();
this.dataQueue.length = 0;
this.emit("dry");
return data;
},
sustain: function (data) {
if (this.isBlocked())
throw new Flow.BlockedSustain(this);
this.dataQueue.push.apply(this.dataQueue, arguments);
},
block: function () {
if (this.isBlocked())
throw new Flow.AlreadyBlocked(this);
this.blocked = true;
this.emit("blocked", this);
},
isBlocked: function () {
return this.blocked;
},
isSustainable: function () {
return !this.blocked;
},
size: function () {
return this.dataQueue.length;
}
},
DryExtract: UserError.extend({
prototype: {
name: "DryExtract",
message: "Attempting to extract data from a dry flow."
}
}),
BlockedSustain: UserError.extend({
prototype: {
name: "BlockedSustain",
message: "Attempting to sustain a blocked data flow."
}
}),
AlreadyBlocked: UserError.extend({
prototype: {
name: "AlreadyBlocked",
message: "Attempting to block a data flow but which is already blocked."
}
})
}).absorb(EventEmitter);
module.exports = Flow; |
'use strict';
var UserList = require('../pages/UserList.js');
var UserDetails = require('../pages/UserDetails.js');
var ContactUser = require('../pages/ContactUser.js');
describe('my app', function() {
var users = new UserList();
var details = new UserDetails();
var contact = new ContactUser();
beforeEach(function() {
users.loadAll();
});
it('should load a list of responsavel', function() {
expect(users.count()).toBeGreaterThan(1);
});
describe('selecting a user', function() {
beforeEach(function() {
return details.contactUser();
});
it('should set focus on first button in the bottomsheet view', function() {
expect( contact.buttons().count() ).toBe(4);
expect( contact.buttons().first().getText() ).toEqual( 'PHONE' );
expect( contact.focusedButton().getText() ).toEqual( 'PHONE' );
});
});
});
|
const google_speech = require('google-speech')
const path = require('path')
const ffmpeg = require("fluent-ffmpeg")
const Stream = require("stream")
const fs = require('fs')
const keys = require('keys/api-keys.json')
const google_api_key = keys["google-speech"]
const logger = require('lib/logger')('SpeechStream')
function SpeechStream(engine = "GOOGLE", lang = "fr-FR") {
return new GoogleStream(google_api_key, lang)
}
class GoogleStream extends Stream.Writable {
constructor(api_key, lang) {
super()
this.api_key = api_key
this.lang = lang
this.textStream = new Stream.PassThrough({
objectMode: true
})
this.acc = []
this.timeout = null
this.pending = false
this.input = this.converted = null
}
_write(chunk, encoding, cb) {
clearTimeout(this.timeout)
if (this.pending) {
this.acc.push(chunk)
} else {
if (this.input == null) {
this.input = new Stream.PassThrough
this.converted = new Stream.PassThrough
ffmpeg(this.input)
.withInputFormat('s16le')
.format('s16le')
.withAudioFrequency(16000)
.pipe(this.converted)
if (this.acc.length > 0) {
this.input.write(Buffer.concat(this.acc))
this.acc = []
}
}
this.input.write(chunk)
this.timeout = setTimeout(this.makeRequest.bind(this), 500)
}
cb()
}
makeRequest() {
logger.log("Making request ..\n")
this.pending = true
this.input.end()
google_speech.ASR({
//debug: true,
developer_key: this.api_key,
stream: this.converted,
lang: this.lang
}, this.requestCallback.bind(this))
}
requestCallback(err, res) {
this.converted = null
this.input = null
this.pending = false
if (err) return logger.error(err)
this.handleResponse(res)
}
handleResponse(response) {
logger.log(JSON.stringify(response))
if (response.result && response.result.length > 0)
this.textStream.push(response.result[response.result_index].alternative)
}
}
module.exports = SpeechStream
|
angular.module("ezstuff", [])
.controller("ezCtrl", ["$scope", function($scope) {
$scope.customer = {
name: "Naomi",
address: "1600 Amphitheatre"
};
}])
.directive("ezCustomer", function() {
return {
restrict: "E",
template: "Name: {{customer.name}} Address: {{customer.address}}"
};
});
|
"use strict";
define(['dou', 'collection'], function (dou, collection) {
describe('collection.withList', function () {
var target;
beforeEach(function() {
var Clazz = dou.define({
mixins: collection.withList
});
target = new Clazz();
});
describe('append', function () {
it('should increase size of the collection', function() {
expect(target.size()).to.equal(0);
target.append('1');
expect(target.size()).to.equal(1);
});
it('should append item at the end position of the collection', function() {
target.append('1');
target.append('2');
target.append('3');
expect(target.indexOf('3')).to.equal(2);
});
});
describe('prepend', function () {
it('should insert item at the front position of the collection', function() {
target.prepend('1');
target.prepend('2');
target.prepend('3');
expect(target.indexOf('3')).to.equal(0);
});
});
describe('getAt', function () {
it('should return object at the index', function() {
target.append('1');
target.append('2');
target.append('3');
expect(target.getAt(2)).to.equal('3');
});
});
describe('insert', function () {
it('should insert item at the specified position of the collection', function() {
target.append('1');
target.append('2');
target.append('4');
target.insertAt(2, '3');
expect(target.indexOf('3')).to.equal(2);
expect(target.indexOf('4')).to.equal(3);
});
});
describe('remove', function () {
it('should remove item in the collection', function() {
target.append('1').append('2').append('3').append('4').remove('3');
expect(target.size()).to.equal(3);
expect(target.indexOf('3')).to.equal(-1);
});
});
describe('forEach', function () {
it('should execute required function for all items in the collection', function() {
var sum = 0;
target.append(1).append(2).append(3).append(4).forEach(function(item) {
sum += item;
});
expect(sum).to.equal(10);
});
it('should execute required function by the specified context', function() {
var context = {
sum : 0
};
target.append(1).append(2).append(3).append(4).forEach(function(item) {
this.sum += item;
}, context);
expect(context.sum).to.equal(10);
});
});
describe('clear', function () {
it('should remove all items in the collection', function() {
target.append(1).append(2).append(3).append(4);
expect(target.size()).to.equal(4);
target.clear();
expect(target.size()).to.equal(0);
});
it('should execute required function by the specified context', function() {
var context = {
sum : 0
};
target.append(1).append(2).append(3).append(4).forEach(function(item) {
this.sum += item;
}, context);
expect(context.sum).to.equal(10);
});
});
});
});
|
//使用echats 组件
//1.图例组件legend 2.标题组件titile 3.视觉映射组件 visualMap 4.数据区域缩放组件dataZoom 5.时间线组件timeline
// 在直角坐标系grid 和 极坐标系polar 中 使用
// 引入 ECharts 主模块
var echarts = require('echarts/lib/echarts');
//引入散点图
require('echarts/lib/chart/scatter');
require('echarts/lib/component/dataZoom');
var myecharts = echarts.init(document.getElementById('root'));
var data1 = [];
var data2 = [];
var data3 = [];
var random = function (max) {
return (Math.random() * max).toFixed(3);
};
for (var i = 0; i < 500; i++) {
data1.push([random(15), random(10), random(1)]);
data2.push([random(10), random(10), random(1)]);
data3.push([random(15), random(10), random(1)]);
}
myecharts.setOption({
animation: false,
legend: {
data: ['scatter', 'scatter2', 'scatter3']
},
xAxis: {
type: 'value',
min: 'dataMin',
max: 'dataMax',
splitLine: {
show: true
}
},
yAxis: {
type: 'value',
min: 'dataMin',
max: 'dataMax',
splitLine: {
show: true
}
},
dataZoom:[{
//这是一个dataZooom组件默认控制x轴
type: 'slider', // 这个 dataZoom 组件是 slider 型 dataZoom 组件
start: 10,// 左边在 10% 的位置。
end: 60 // 右边在 60% 的位置。
},
{ // 这个dataZoom组件,也控制x轴。
type: 'inside', // 这个 dataZoom 组件是 inside 型 dataZoom 组件
start: 10, // 左边在 10% 的位置。
end: 60 // 右边在 60% 的位置。
},
{
type: 'slider',
yAxisIndex: 0,
start: 30,
end: 80
},
{
type: 'inside',
yAxisIndex: 0,
start: 30,
end: 80
}
],
series:[{
name:'scatter1',
type:'scatter', //这是一个散点图
itemStyle:{
normal:{
opcity:0.8
}
},
symbolSize:function(val){
return val[2]*40;
},
//data: [["14.616", "7.241", "0.896"], ["3.958", "5.701", "0.955"], ["2.768", "8.971", "0.669"], ["9.051", "9.710", "0.171"], ["14.046", "4.182", "0.536"], ["12.295", "1.429", "0.962"], ["4.417", "8.167", "0.113"], ["0.492", "4.771", "0.785"], ["7.632", "2.605", "0.645"], ["14.242", "5.042", "0.368"]]
data:data1
},
{
name:'scatter2',
type: 'scatter', //这是一个散点图
itemStyle: {
normal: {
opcity: 0.8
}
},
symbolSize: function (val) {
return val[2] * 40;
},
data: data2
},
{
name: 'scatter3',
type: 'scatter', //这是一个散点图
itemStyle: {
normal: {
opcity: 0.8
}
},
symbolSize: function (val) {
return val[2] * 40;
},
data: data3
}
]
});
|
import AnimationFrame from 'slgfx/src/SpriteAnimationFrame';
/**
* PixSprite Implementation of AnimationFrame.
* @extends {AnimationFrame}
* @constructor
* @param {Object} props Object properties.
* @param {number} props.duration Object properties.
* @param {Array} props.pixArray The Array of Pix entries for this frame. Format: <br />
* {type:"TYPE", x:x, y:y, [width:width, height:height,] color:ColorObject}</br>
* where:
* <ul>
* <li>type can be either "PIXEL" or "RECTANGLE" (see {@link PixPathTypes})</li>
* <li>x, y are coordinates relative to the element's origin</li>
* <li>width, height are only used by RECTANGLE types to determine the size of the rectangle drawn</li>
* <li>color can be any of: a valid CSS color (hex format "#1234AB", or "rbg(100, 200, 255)"),
* a ColorPointer,
* or an integer value corresponding to an index on this element's color palette.</li>
* </ul>
* @see {PixSprite}
*/
function PixSpriteFrame(props) {
props = props || {};
AnimationFrame.call(this);
this._pixArray = props.pixArray;
this._duration = props.duration;
};
PixSpriteFrame.prototype = new AnimationFrame();
PixSpriteFrame.prototype.callback = PixSpriteFrame;
/** Return the duration to display this frame.
* @returns {number}
*/
PixSpriteFrame.prototype.getDuration = function() {return this._duration;};
/** Return the PixArray for this frame.
* @returns {number}
*/
PixSpriteFrame.prototype.getPixArray = function() {return this._pixArray;};
export default PixSpriteFrame;
|
"use strict";
var BlockPositioner = function(block, mediator) {
this.mediator = mediator;
this.block = block;
this._ensureElement();
this._bindFunctions();
this.initialize();
};
Object.assign(BlockPositioner.prototype, require('./function-bind'), require('./renderable'), {
bound: ['toggle', 'show', 'hide'],
className: 'st-block-positioner',
visibleClass: 'active',
initialize: function(){},
toggle: function() {
this.mediator.trigger('block-positioner-select:render', this);
this.el.classList.toggle(this.visibleClass);
},
show: function(){
this.el.classList.add(this.visibleClass);
},
hide: function(){
this.el.classList.remove(this.visibleClass);
}
});
module.exports = BlockPositioner;
|
/*
Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
CKEDITOR.plugins.setLang( 'link', 'gl', {
acccessKey: 'Chave de acceso',
advanced: 'Avanzado',
advisoryContentType: 'Tipo de contido informativo',
advisoryTitle: 'Título',
anchor: {
toolbar: 'Ancoraxe',
menu: 'Editar a ancoraxe',
title: 'Propiedades da ancoraxe',
name: 'Nome da ancoraxe',
errorName: 'Escriba o nome da ancoraxe',
remove: 'Retirar a ancoraxe'
},
anchorId: 'Polo ID do elemento',
anchorName: 'Polo nome da ancoraxe',
charset: 'Codificación do recurso ligado',
cssClasses: 'Clases da folla de estilos',
download: 'Forzar a descarga',
displayText: 'Amosar o texto',
emailAddress: 'Enderezo de correo',
emailBody: 'Corpo da mensaxe',
emailSubject: 'Asunto da mensaxe',
id: 'ID',
info: 'Información da ligazón',
langCode: 'Código do idioma',
langDir: 'Dirección de escritura do idioma',
langDirLTR: 'Esquerda a dereita (LTR)',
langDirRTL: 'Dereita a esquerda (RTL)',
menu: 'Editar a ligazón',
name: 'Nome',
noAnchors: '(Non hai ancoraxes dispoñíbeis no documento)',
noEmail: 'Escriba o enderezo de correo',
noUrl: 'Escriba a ligazón URL',
noTel: 'Escriba o número de teléfono',
other: '<other>',
phoneNumber: 'Número de teléfono',
popupDependent: 'Dependente (Netscape)',
popupFeatures: 'Características da xanela emerxente',
popupFullScreen: 'Pantalla completa (IE)',
popupLeft: 'Posición esquerda',
popupLocationBar: 'Barra de localización',
popupMenuBar: 'Barra do menú',
popupResizable: 'Redimensionábel',
popupScrollBars: 'Barras de desprazamento',
popupStatusBar: 'Barra de estado',
popupToolbar: 'Barra de ferramentas',
popupTop: 'Posición superior',
rel: 'Relación',
selectAnchor: 'Seleccionar unha ancoraxe',
styles: 'Estilo',
tabIndex: 'Índice de tabulación',
target: 'Destino',
targetFrame: '<marco>',
targetFrameName: 'Nome do marco de destino',
targetPopup: '<xanela emerxente>',
targetPopupName: 'Nome da xanela emerxente',
title: 'Ligazón',
toAnchor: 'Ligar coa ancoraxe no testo',
toEmail: 'Correo',
toUrl: 'URL',
toPhone: 'Teléfono',
toolbar: 'Ligazón',
type: 'Tipo de ligazón',
unlink: 'Eliminar a ligazón',
upload: 'Enviar'
} );
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var checkmark = exports.checkmark = { "viewBox": "0 0 16 16", "children": [{ "name": "path", "attribs": { "fill": "#000000", "d": "M13.5 2l-7.5 7.5-3.5-3.5-2.5 2.5 6 6 10-10z" } }] }; |
const gulp = require('gulp');
const plugins = require('gulp-load-plugins')();
module.exports = config => {
gulp.task('clean', () => {
return gulp
.src(config.buildDir, { read: false, allowEmpty: true })
.pipe(plugins.clean({ force: true }));
});
};
|
export { default } from './collapse-pull-request-description'
|
import React, {PropTypes, Component} from 'react';
import ReactDOM from 'react-dom';
import classNames from 'classnames';
import isOneOf from '../../utils/isOneOf';
import './Button.less';
const _type = {
type: ['primary', 'ghost', 'dashed'],
size: ['small', 'large'],
shape: ['circle']
};
const btnPrefix = 'zad-btn';
export default class Button extends Component {
constructor(props) {
super(props);
this.state = {clicked: false};
this._clickBtn = this._clickBtn.bind(this);
this._blurBtn = this._blurBtn.bind(this);
}
static propTypes = {
type: PropTypes.string,
size: PropTypes.string,
shape: PropTypes.string,
onClick: PropTypes.func
};
static defaultProps = {
onClick: () => undefined
};
componentWillUnmount() {
if (this.addClicked) {
clearTimeout(this.addClicked);
this.addClicked = null;
}
if (this.removeClicked) {
clearTimeout(this.removeClicked);
this.removeClicked = null;
}
}
_clickBtn(e) {
this.setState({clicked: false});
// 先clear,再remove
if (this.removeClicked) {
clearTimeout(this.removeClicked);
}
this.addClicked = setTimeout(() => {
this.setState({clicked: true});
}, 10);
this.removeClicked = setTimeout(() => {
this.setState({clicked: false});
}, 500);
this.props.onClick(e);
}
_blurBtn() {
ReactDOM.findDOMNode(this).blur();
}
render() {
const {type, size, shape, className, children, ...props} = this.props;
const {clicked} = this.state;
const sizeSuffix = ({
large: 'lg',
small: 'sm',
})[size];
const btnClass = classNames(btnPrefix, className, {
[`${btnPrefix}-clicked`]: clicked,
[`${btnPrefix}-${type}`]: type && isOneOf(_type.type, type),
[`${btnPrefix}-${sizeSuffix}`]: size && isOneOf(_type.size, size),
[`${btnPrefix}-${shape}`]: shape && isOneOf(_type.shape, shape)
});
const _children = React.Children.map(children, (child) => {
if (typeof child === 'string') {
return (<span>{child}</span>);
}
return child;
});
return (
<button
{...props}
type="button"
className={btnClass}
onClick={this._clickBtn}
onMouseUp={this._blurBtn}
>
{_children}
</button>
);
}
}
|
// All code points in the Combining Half Marks block as per Unicode v4.0.1:
[
0xFE20,
0xFE21,
0xFE22,
0xFE23,
0xFE24,
0xFE25,
0xFE26,
0xFE27,
0xFE28,
0xFE29,
0xFE2A,
0xFE2B,
0xFE2C,
0xFE2D,
0xFE2E,
0xFE2F
]; |
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import type {Thenable, Wakeable} from 'shared/ReactTypes';
import type {Fiber, FiberRoot} from './ReactInternalTypes';
import type {ExpirationTimeOpaque} from './ReactFiberExpirationTime.new';
import type {ReactPriorityLevel} from './ReactInternalTypes';
import type {Interaction} from 'scheduler/src/Tracing';
import type {SuspenseConfig} from './ReactFiberSuspenseConfig';
import type {SuspenseState} from './ReactFiberSuspenseComponent.new';
import type {Effect as HookEffect} from './ReactFiberHooks.new';
import {
warnAboutDeprecatedLifecycles,
deferPassiveEffectCleanupDuringUnmount,
runAllPassiveEffectDestroysBeforeCreates,
enableSuspenseServerRenderer,
replayFailedUnitOfWorkWithInvokeGuardedCallback,
enableProfilerTimer,
enableProfilerCommitHooks,
enableSchedulerTracing,
warnAboutUnmockedScheduler,
} from 'shared/ReactFeatureFlags';
import ReactSharedInternals from 'shared/ReactSharedInternals';
import invariant from 'shared/invariant';
import {
scheduleCallback,
cancelCallback,
getCurrentPriorityLevel,
runWithPriority,
shouldYield,
requestPaint,
now,
NoPriority as NoSchedulerPriority,
ImmediatePriority as ImmediateSchedulerPriority,
UserBlockingPriority as UserBlockingSchedulerPriority,
NormalPriority as NormalSchedulerPriority,
LowPriority as LowSchedulerPriority,
IdlePriority as IdleSchedulerPriority,
flushSyncCallbackQueue,
scheduleSyncCallback,
} from './SchedulerWithReactIntegration.new';
// The scheduler is imported here *only* to detect whether it's been mocked
import * as Scheduler from 'scheduler';
import {__interactionsRef, __subscriberRef} from 'scheduler/tracing';
import {
prepareForCommit,
resetAfterCommit,
scheduleTimeout,
cancelTimeout,
noTimeout,
warnsIfNotActing,
beforeActiveInstanceBlur,
afterActiveInstanceBlur,
} from './ReactFiberHostConfig';
import {
createWorkInProgress,
assignFiberPropertiesInDEV,
} from './ReactFiber.new';
import {
isRootSuspendedAtTime,
markRootSuspendedAtTime,
markRootFinishedAtTime,
markRootUpdatedAtTime,
markRootExpiredAtTime,
} from './ReactFiberRoot.new';
import {
NoMode,
StrictMode,
ProfileMode,
BlockingMode,
ConcurrentMode,
} from './ReactTypeOfMode';
import {
HostRoot,
ClassComponent,
SuspenseComponent,
SuspenseListComponent,
FunctionComponent,
ForwardRef,
MemoComponent,
SimpleMemoComponent,
Block,
} from './ReactWorkTags';
import {LegacyRoot} from './ReactRootTags';
import {
NoEffect,
PerformedWork,
Placement,
Update,
PlacementAndUpdate,
Deletion,
Ref,
ContentReset,
Snapshot,
Callback,
Passive,
PassiveUnmountPendingDev,
Incomplete,
HostEffectMask,
Hydrating,
HydratingAndUpdate,
} from './ReactSideEffectTags';
import {
NoWork,
Sync,
UserBlockingUpdateTime,
DefaultUpdateTime,
Never,
inferPriorityFromExpirationTime,
Batched,
Idle,
ContinuousHydration,
ShortTransition,
LongTransition,
isSameOrHigherPriority,
isSameExpirationTime,
bumpPriorityLower,
} from './ReactFiberExpirationTime.new';
import {
SyncLanePriority,
SyncBatchedLanePriority,
InputDiscreteLanePriority,
InputContinuousLanePriority,
DefaultLanePriority,
TransitionShortLanePriority,
TransitionLongLanePriority,
HydrationContinuousLanePriority,
IdleLanePriority,
OffscreenLanePriority,
} from './ReactFiberLane';
import {beginWork as originalBeginWork} from './ReactFiberBeginWork.new';
import {completeWork} from './ReactFiberCompleteWork.new';
import {unwindWork, unwindInterruptedWork} from './ReactFiberUnwindWork.new';
import {
throwException,
createRootErrorUpdate,
createClassErrorUpdate,
} from './ReactFiberThrow.new';
import {
commitBeforeMutationLifeCycles as commitBeforeMutationEffectOnFiber,
commitLifeCycles as commitLayoutEffectOnFiber,
commitPassiveHookEffects,
commitPlacement,
commitWork,
commitDeletion,
commitDetachRef,
commitAttachRef,
commitPassiveEffectDurations,
commitResetTextContent,
} from './ReactFiberCommitWork.new';
import {enqueueUpdate} from './ReactUpdateQueue.new';
import {resetContextDependencies} from './ReactFiberNewContext.new';
import {
resetHooksAfterThrow,
ContextOnlyDispatcher,
getIsUpdatingOpaqueValueInRenderPhaseInDEV,
} from './ReactFiberHooks.new';
import {createCapturedValue} from './ReactCapturedValue';
import {
recordCommitTime,
recordPassiveEffectDuration,
startPassiveEffectTimer,
startProfilerTimer,
stopProfilerTimerIfRunningAndRecordDelta,
} from './ReactProfilerTimer.new';
// DEV stuff
import getComponentName from 'shared/getComponentName';
import ReactStrictModeWarnings from './ReactStrictModeWarnings.new';
import {
isRendering as ReactCurrentDebugFiberIsRenderingInDEV,
current as ReactCurrentFiberCurrent,
resetCurrentFiber as resetCurrentDebugFiberInDEV,
setCurrentFiber as setCurrentDebugFiberInDEV,
} from './ReactCurrentFiber';
import {
invokeGuardedCallback,
hasCaughtError,
clearCaughtError,
} from 'shared/ReactErrorUtils';
import {onCommitRoot} from './ReactFiberDevToolsHook.new';
// Used by `act`
import enqueueTask from 'shared/enqueueTask';
import {isFiberHiddenOrDeletedAndContains} from './ReactFiberTreeReflection';
const ceil = Math.ceil;
const {
ReactCurrentDispatcher,
ReactCurrentOwner,
IsSomeRendererActing,
} = ReactSharedInternals;
type ExecutionContext = number;
const NoContext = /* */ 0b000000;
const BatchedContext = /* */ 0b000001;
const EventContext = /* */ 0b000010;
const DiscreteEventContext = /* */ 0b000100;
const LegacyUnbatchedContext = /* */ 0b001000;
const RenderContext = /* */ 0b010000;
const CommitContext = /* */ 0b100000;
type RootExitStatus = 0 | 1 | 2 | 3 | 4 | 5;
const RootIncomplete = 0;
const RootFatalErrored = 1;
const RootErrored = 2;
const RootSuspended = 3;
const RootSuspendedWithDelay = 4;
const RootCompleted = 5;
// Describes where we are in the React execution stack
let executionContext: ExecutionContext = NoContext;
// The root we're working on
let workInProgressRoot: FiberRoot | null = null;
// The fiber we're working on
let workInProgress: Fiber | null = null;
// The expiration time we're rendering
let renderExpirationTime: ExpirationTimeOpaque = NoWork;
// Whether to root completed, errored, suspended, etc.
let workInProgressRootExitStatus: RootExitStatus = RootIncomplete;
// A fatal error, if one is thrown
let workInProgressRootFatalError: mixed = null;
// Most recent event time among processed updates during this render.
// This is conceptually a time stamp but expressed in terms of an ExpirationTimeOpaque
// because we deal mostly with expiration times in the hot path, so this avoids
// the conversion happening in the hot path.
let workInProgressRootLatestProcessedEventTime: number = -1;
let workInProgressRootLatestSuspenseTimeout: number = -1;
let workInProgressRootCanSuspendUsingConfig: null | SuspenseConfig = null;
// The work left over by components that were visited during this render. Only
// includes unprocessed updates, not work in bailed out children.
let workInProgressRootNextUnprocessedUpdateTime: ExpirationTimeOpaque = NoWork;
// If we're pinged while rendering we don't always restart immediately.
// This flag determines if it might be worthwhile to restart if an opportunity
// happens latere.
let workInProgressRootHasPendingPing: boolean = false;
// The most recent time we committed a fallback. This lets us ensure a train
// model where we don't commit new loading states in too quick succession.
let globalMostRecentFallbackTime: number = 0;
const FALLBACK_THROTTLE_MS: number = 500;
const DEFAULT_TIMEOUT_MS: number = 5000;
let nextEffect: Fiber | null = null;
let hasUncaughtError = false;
let firstUncaughtError = null;
let legacyErrorBoundariesThatAlreadyFailed: Set<mixed> | null = null;
let rootDoesHavePassiveEffects: boolean = false;
let rootWithPendingPassiveEffects: FiberRoot | null = null;
let pendingPassiveEffectsRenderPriority: ReactPriorityLevel = NoSchedulerPriority;
let pendingPassiveEffectsExpirationTime: ExpirationTimeOpaque = NoWork;
let pendingPassiveHookEffectsMount: Array<HookEffect | Fiber> = [];
let pendingPassiveHookEffectsUnmount: Array<HookEffect | Fiber> = [];
let pendingPassiveProfilerEffects: Array<Fiber> = [];
let rootsWithPendingDiscreteUpdates: Map<
FiberRoot,
ExpirationTimeOpaque,
> | null = null;
// Use these to prevent an infinite loop of nested updates
const NESTED_UPDATE_LIMIT = 50;
let nestedUpdateCount: number = 0;
let rootWithNestedUpdates: FiberRoot | null = null;
const NESTED_PASSIVE_UPDATE_LIMIT = 50;
let nestedPassiveUpdateCount: number = 0;
// Marks the need to reschedule pending interactions at these expiration times
// during the commit phase. This enables them to be traced across components
// that spawn new work during render. E.g. hidden boundaries, suspended SSR
// hydration or SuspenseList.
let spawnedWorkDuringRender: null | Array<ExpirationTimeOpaque> = null;
// If two updates are scheduled within the same event, we should treat their
// event times as simultaneous, even if the actual clock time has advanced
// between the first and second call.
let currentEventTime: number = -1;
// Dev only flag that tracks if passive effects are currently being flushed.
// We warn about state updates for unmounted components differently in this case.
let isFlushingPassiveEffects = false;
let focusedInstanceHandle: null | Fiber = null;
let shouldFireAfterActiveInstanceBlur: boolean = false;
export function getWorkInProgressRoot(): FiberRoot | null {
return workInProgressRoot;
}
export function requestEventTime() {
if ((executionContext & (RenderContext | CommitContext)) !== NoContext) {
// We're inside React, so it's fine to read the actual time.
return now();
}
// We're not inside React, so we may be in the middle of a browser event.
if (currentEventTime !== -1) {
// Use the same start time for all updates until we enter React again.
return currentEventTime;
}
// This is the first update since React yielded. Compute a new start time.
currentEventTime = now();
return currentEventTime;
}
export function getCurrentTime() {
return now();
}
export function requestUpdateExpirationTime(
fiber: Fiber,
suspenseConfig: SuspenseConfig | null,
): ExpirationTimeOpaque {
// Special cases
const mode = fiber.mode;
if ((mode & BlockingMode) === NoMode) {
return Sync;
} else if ((mode & ConcurrentMode) === NoMode) {
return getCurrentPriorityLevel() === ImmediateSchedulerPriority
? (Sync: ExpirationTimeOpaque)
: Batched;
} else if ((executionContext & RenderContext) !== NoContext) {
// Use whatever time we're already rendering
// TODO: Treat render phase updates as if they came from an
// interleaved event.
return renderExpirationTime;
}
let updateLanePriority;
if (suspenseConfig !== null) {
// If there's a SuspenseConfig, choose an expiration time that's lower
// priority than a normal concurrent update (regardless of the current
// Scheduler priority.) Timeouts larger than 10 seconds move one level
// lower than that.
// TODO: This will coerce numbers larger than 31 bits to 0.
const timeoutMs = suspenseConfig.timeoutMs;
updateLanePriority =
timeoutMs === undefined || (timeoutMs | 0) < 10000
? TransitionShortLanePriority
: TransitionLongLanePriority;
} else {
// TODO: If we're not inside `runWithPriority`, this returns the priority
// of the currently running task. That's probably not what we want.
const priorityLevel = getCurrentPriorityLevel();
switch (priorityLevel) {
case ImmediateSchedulerPriority:
updateLanePriority = SyncLanePriority;
break;
case UserBlockingSchedulerPriority:
updateLanePriority = InputContinuousLanePriority;
break;
case NormalSchedulerPriority:
case LowSchedulerPriority:
// TODO: Handle LowSchedulerPriority, somehow. Maybe the same lane as hydration.
updateLanePriority = DefaultLanePriority;
break;
case IdleSchedulerPriority:
updateLanePriority = IdleLanePriority;
break;
default:
invariant(false, 'Expected a valid priority level');
}
}
// TODO: In the new system, what we'll do here is claim one of the bits of
// the root's `pendingLanes` field, based on its priority. We'll combine this
// function with `scheduleUpdateOnFiber` and `markRootUpdatedAtTime`.
let expirationTime;
switch (updateLanePriority) {
case SyncLanePriority:
return Sync;
case SyncBatchedLanePriority:
return Batched;
case InputDiscreteLanePriority:
case InputContinuousLanePriority:
expirationTime = UserBlockingUpdateTime;
break;
case DefaultLanePriority:
expirationTime = DefaultUpdateTime;
break;
case TransitionShortLanePriority:
expirationTime = ShortTransition;
break;
case TransitionLongLanePriority:
expirationTime = LongTransition;
break;
case HydrationContinuousLanePriority:
expirationTime = ContinuousHydration;
break;
case IdleLanePriority:
expirationTime = Idle;
break;
case OffscreenLanePriority:
expirationTime = Never;
break;
default:
invariant(false, 'Expected a valid priority level');
}
// If we're in the middle of rendering a tree, do not update at the same
// expiration time that is already rendering.
// TODO: We shouldn't have to do this if the update is on a different root.
// TODO: In the new system, we'll find a different bit that's not the one
// we're currently rendering.
if (
workInProgressRoot !== null &&
isSameExpirationTime(expirationTime, renderExpirationTime)
) {
// This is a trick to move this update into a separate batch
// TODO: This probably causes problems with ContinuousHydration and Idle
expirationTime = bumpPriorityLower(expirationTime);
}
return expirationTime;
}
export function scheduleUpdateOnFiber(
fiber: Fiber,
expirationTime: ExpirationTimeOpaque,
) {
checkForNestedUpdates();
warnAboutRenderPhaseUpdatesInDEV(fiber);
const root = markUpdateTimeFromFiberToRoot(fiber, expirationTime);
if (root === null) {
warnAboutUpdateOnUnmountedFiberInDEV(fiber);
return null;
}
// TODO: requestUpdateLanePriority also reads the priority. Pass the
// priority as an argument to that function and this one.
const priorityLevel = getCurrentPriorityLevel();
if (isSameExpirationTime(expirationTime, (Sync: ExpirationTimeOpaque))) {
if (
// Check if we're inside unbatchedUpdates
(executionContext & LegacyUnbatchedContext) !== NoContext &&
// Check if we're not already rendering
(executionContext & (RenderContext | CommitContext)) === NoContext
) {
// Register pending interactions on the root to avoid losing traced interaction data.
schedulePendingInteractions(root, expirationTime);
// This is a legacy edge case. The initial mount of a ReactDOM.render-ed
// root inside of batchedUpdates should be synchronous, but layout updates
// should be deferred until the end of the batch.
performSyncWorkOnRoot(root);
} else {
ensureRootIsScheduled(root);
schedulePendingInteractions(root, expirationTime);
if (executionContext === NoContext) {
// Flush the synchronous work now, unless we're already working or inside
// a batch. This is intentionally inside scheduleUpdateOnFiber instead of
// scheduleCallbackForFiber to preserve the ability to schedule a callback
// without immediately flushing it. We only do this for user-initiated
// updates, to preserve historical behavior of legacy mode.
flushSyncCallbackQueue();
}
}
} else {
ensureRootIsScheduled(root);
schedulePendingInteractions(root, expirationTime);
}
if (
(executionContext & DiscreteEventContext) !== NoContext &&
// Only updates at user-blocking priority or greater are considered
// discrete, even inside a discrete event.
(priorityLevel === UserBlockingSchedulerPriority ||
priorityLevel === ImmediateSchedulerPriority)
) {
// This is the result of a discrete event. Track the lowest priority
// discrete update per root so we can flush them early, if needed.
if (rootsWithPendingDiscreteUpdates === null) {
rootsWithPendingDiscreteUpdates = new Map([[root, expirationTime]]);
} else {
const lastDiscreteTime = rootsWithPendingDiscreteUpdates.get(root);
if (
lastDiscreteTime === undefined ||
!isSameOrHigherPriority(expirationTime, lastDiscreteTime)
) {
rootsWithPendingDiscreteUpdates.set(root, expirationTime);
}
}
}
}
// This is split into a separate function so we can mark a fiber with pending
// work without treating it as a typical update that originates from an event;
// e.g. retrying a Suspense boundary isn't an update, but it does schedule work
// on a fiber.
function markUpdateTimeFromFiberToRoot(fiber, expirationTime) {
// Update the source fiber's expiration time
if (!isSameOrHigherPriority(fiber.expirationTime_opaque, expirationTime)) {
fiber.expirationTime_opaque = expirationTime;
}
let alternate = fiber.alternate;
if (
alternate !== null &&
!isSameOrHigherPriority(alternate.expirationTime_opaque, expirationTime)
) {
alternate.expirationTime_opaque = expirationTime;
}
// Walk the parent path to the root and update the child expiration time.
let node = fiber.return;
let root = null;
if (node === null && fiber.tag === HostRoot) {
root = fiber.stateNode;
} else {
while (node !== null) {
alternate = node.alternate;
if (
!isSameOrHigherPriority(node.childExpirationTime_opaque, expirationTime)
) {
node.childExpirationTime_opaque = expirationTime;
if (
alternate !== null &&
!isSameOrHigherPriority(
alternate.childExpirationTime_opaque,
expirationTime,
)
) {
alternate.childExpirationTime_opaque = expirationTime;
}
} else if (
alternate !== null &&
!isSameOrHigherPriority(
alternate.childExpirationTime_opaque,
expirationTime,
)
) {
alternate.childExpirationTime_opaque = expirationTime;
}
if (node.return === null && node.tag === HostRoot) {
root = node.stateNode;
break;
}
node = node.return;
}
}
if (root !== null) {
if (workInProgressRoot === root) {
// Received an update to a tree that's in the middle of rendering. Mark
// that's unprocessed work on this root.
markUnprocessedUpdateTime(expirationTime);
if (workInProgressRootExitStatus === RootSuspendedWithDelay) {
// The root already suspended with a delay, which means this render
// definitely won't finish. Since we have a new update, let's mark it as
// suspended now, right before marking the incoming update. This has the
// effect of interrupting the current render and switching to the update.
// TODO: This happens to work when receiving an update during the render
// phase, because of the trick inside requestUpdateExpirationTime to
// subtract 1 from `renderExpirationTime` to move it into a
// separate bucket. But we should probably model it with an exception,
// using the same mechanism we use to force hydration of a subtree.
// TODO: This does not account for low pri updates that were already
// scheduled before the root started rendering. Need to track the next
// pending expiration time (perhaps by backtracking the return path) and
// then trigger a restart in the `renderDidSuspendDelayIfPossible` path.
markRootSuspendedAtTime(root, renderExpirationTime);
}
}
// Mark that the root has a pending update.
markRootUpdatedAtTime(root, expirationTime);
}
return root;
}
function getNextRootExpirationTimeToWorkOn(
root: FiberRoot,
): ExpirationTimeOpaque {
// Determines the next expiration time that the root should render, taking
// into account levels that may be suspended, or levels that may have
// received a ping.
const lastExpiredTime = root.lastExpiredTime_opaque;
if (!isSameExpirationTime(lastExpiredTime, (NoWork: ExpirationTimeOpaque))) {
return lastExpiredTime;
}
// "Pending" refers to any update that hasn't committed yet, including if it
// suspended. The "suspended" range is therefore a subset.
const firstPendingTime = root.firstPendingTime_opaque;
if (!isRootSuspendedAtTime(root, firstPendingTime)) {
// The highest priority pending time is not suspended. Let's work on that.
return firstPendingTime;
}
// If the first pending time is suspended, check if there's a lower priority
// pending level that we know about. Or check if we received a ping. Work
// on whichever is higher priority.
const lastPingedTime = root.lastPingedTime_opaque;
const nextKnownPendingLevel = root.nextKnownPendingLevel_opaque;
const nextLevel = !isSameOrHigherPriority(
nextKnownPendingLevel,
lastPingedTime,
)
? lastPingedTime
: nextKnownPendingLevel;
if (
isSameOrHigherPriority((Idle: ExpirationTimeOpaque), nextLevel) &&
!isSameExpirationTime(firstPendingTime, nextLevel)
) {
// Don't work on Idle/Never priority unless everything else is committed.
return NoWork;
}
return nextLevel;
}
// Use this function to schedule a task for a root. There's only one task per
// root; if a task was already scheduled, we'll check to make sure the
// expiration time of the existing task is the same as the expiration time of
// the next level that the root has work on. This function is called on every
// update, and right before exiting a task.
function ensureRootIsScheduled(root: FiberRoot) {
const existingCallbackNode = root.callbackNode;
const newCallbackId = getNextRootExpirationTimeToWorkOn(root);
if (newCallbackId === (NoWork: ExpirationTimeOpaque)) {
// Special case: There's nothing to work on.
if (existingCallbackNode !== null) {
cancelCallback(existingCallbackNode);
root.expiresAt = -1;
root.callbackNode = null;
root.callbackIsSync = false;
root.callbackId = NoWork;
}
return;
}
const newTaskIsSync =
newCallbackId === (Sync: ExpirationTimeOpaque) ||
!isSameExpirationTime(
root.lastExpiredTime_opaque,
(NoWork: ExpirationTimeOpaque),
);
// Check if there's an existing task. We may be able to reuse it.
const existingTaskId = root.callbackId;
const existingCallbackIsSync = root.callbackIsSync;
if (existingTaskId !== (NoWork: ExpirationTimeOpaque)) {
if (newCallbackId === existingTaskId) {
// This task is already scheduled. Let's check its priority.
if (
(newTaskIsSync && existingCallbackIsSync) ||
(!newTaskIsSync && !existingCallbackIsSync)
) {
// The priority hasn't changed. Exit.
return;
}
// The task ID is the same but the priority changed. Cancel the existing
// callback. We'll schedule a new one below.
}
cancelCallback(existingCallbackNode);
}
// Schedule a new callback.
let newCallbackNode;
if (newTaskIsSync) {
// Special case: Sync React callbacks are scheduled on a special internal queue
newCallbackNode = scheduleSyncCallback(
performSyncWorkOnRoot.bind(null, root),
);
} else {
// TODO: Use LanePriority instead of SchedulerPriority
const priorityLevel = inferPriorityFromExpirationTime(newCallbackId);
if (
priorityLevel === NormalSchedulerPriority ||
priorityLevel === UserBlockingSchedulerPriority
) {
const existingExpirationTime = root.expiresAt;
const currentTimeMs = now();
// Compute an expiration time based on the priority level.
const expiration =
priorityLevel === UserBlockingSchedulerPriority ? 250 : 5000;
let msUntilExpiration;
if (existingExpirationTime === -1) {
// This is the first concurrent update on the root. Use the expiration
// time we just computed.
msUntilExpiration = expiration;
root.expiresAt = msUntilExpiration + currentTimeMs;
} else {
// There's already an expiration time. Use the smaller of the current
// expiration and the one we just computed.
msUntilExpiration = existingExpirationTime - currentTimeMs;
if (expiration < msUntilExpiration) {
root.expiresAt = expiration;
}
}
newCallbackNode = scheduleCallback(
priorityLevel,
performConcurrentWorkOnRoot.bind(null, root),
);
} else {
newCallbackNode = scheduleCallback(
priorityLevel,
performConcurrentWorkOnRoot.bind(null, root),
);
}
}
root.callbackId = newCallbackId;
root.callbackNode = newCallbackNode;
root.callbackIsSync = newTaskIsSync;
}
// This is the entry point for every concurrent task, i.e. anything that
// goes through Scheduler.
function performConcurrentWorkOnRoot(root, didTimeout) {
// Since we know we're in a React event, we can clear the current
// event time. The next update will compute a new event time.
currentEventTime = -1;
// Determine the next expiration time to work on, using the fields stored
// on the root.
let expirationTime = getNextRootExpirationTimeToWorkOn(root);
if (isSameExpirationTime(expirationTime, (NoWork: ExpirationTimeOpaque))) {
return null;
}
if (didTimeout) {
// The render task took too long to complete. Mark the root as expired to
// prevent yielding to other tasks until this one finishes.
markRootExpiredAtTime(root, expirationTime);
// This will schedule a synchronous callback.
ensureRootIsScheduled(root);
return null;
}
const originalCallbackNode = root.callbackNode;
invariant(
(executionContext & (RenderContext | CommitContext)) === NoContext,
'Should not already be working.',
);
flushPassiveEffects();
let exitStatus = renderRootConcurrent(root, expirationTime);
if (exitStatus !== RootIncomplete) {
if (exitStatus === RootErrored) {
// If something threw an error, try rendering one more time. We'll
// render synchronously to block concurrent data mutations, and we'll
// render at Idle (or lower) so that all pending updates are included.
// If it still fails after the second attempt, we'll give up and commit
// the resulting tree.
expirationTime = !isSameOrHigherPriority(
(Idle: ExpirationTimeOpaque),
expirationTime,
)
? (Idle: ExpirationTimeOpaque)
: expirationTime;
exitStatus = renderRootSync(root, expirationTime);
}
if (exitStatus === RootFatalErrored) {
const fatalError = workInProgressRootFatalError;
prepareFreshStack(root, expirationTime);
markRootSuspendedAtTime(root, expirationTime);
ensureRootIsScheduled(root);
throw fatalError;
}
// We now have a consistent tree. The next step is either to commit it,
// or, if something suspended, wait to commit it after a timeout.
const finishedWork: Fiber = (root.current.alternate: any);
root.finishedWork = finishedWork;
root.finishedExpirationTime_opaque = expirationTime;
root.nextKnownPendingLevel_opaque = getRemainingExpirationTime(
finishedWork,
);
finishConcurrentRender(root, finishedWork, exitStatus, expirationTime);
}
ensureRootIsScheduled(root);
if (root.callbackNode === originalCallbackNode) {
// The task node scheduled for this root is the same one that's
// currently executed. Need to return a continuation.
return performConcurrentWorkOnRoot.bind(null, root);
}
return null;
}
function finishConcurrentRender(
root,
finishedWork,
exitStatus,
expirationTime,
) {
switch (exitStatus) {
case RootIncomplete:
case RootFatalErrored: {
invariant(false, 'Root did not complete. This is a bug in React.');
}
// Flow knows about invariant, so it complains if I add a break
// statement, but eslint doesn't know about invariant, so it complains
// if I do. eslint-disable-next-line no-fallthrough
case RootErrored: {
// We should have already attempted to retry this tree. If we reached
// this point, it errored again. Commit it.
commitRoot(root);
break;
}
case RootSuspended: {
markRootSuspendedAtTime(root, expirationTime);
const lastSuspendedTime = root.lastSuspendedTime_opaque;
// We have an acceptable loading state. We need to figure out if we
// should immediately commit it or wait a bit.
// If we have processed new updates during this render, we may now
// have a new loading state ready. We want to ensure that we commit
// that as soon as possible.
const hasNotProcessedNewUpdates =
workInProgressRootLatestProcessedEventTime === -1;
if (
hasNotProcessedNewUpdates &&
// do not delay if we're inside an act() scope
!shouldForceFlushFallbacksInDEV()
) {
// If we have not processed any new updates during this pass, then
// this is either a retry of an existing fallback state or a
// hidden tree. Hidden trees shouldn't be batched with other work
// and after that's fixed it can only be a retry. We're going to
// throttle committing retries so that we don't show too many
// loading states too quickly.
const msUntilTimeout =
globalMostRecentFallbackTime + FALLBACK_THROTTLE_MS - now();
// Don't bother with a very short suspense time.
if (msUntilTimeout > 10) {
if (workInProgressRootHasPendingPing) {
const lastPingedTime = root.lastPingedTime_opaque;
if (
isSameExpirationTime(
lastPingedTime,
(NoWork: ExpirationTimeOpaque),
) ||
isSameOrHigherPriority(lastPingedTime, expirationTime)
) {
// This render was pinged but we didn't get to restart
// earlier so try restarting now instead.
root.lastPingedTime_opaque = expirationTime;
prepareFreshStack(root, expirationTime);
break;
}
}
const nextTime = getNextRootExpirationTimeToWorkOn(root);
if (
!isSameExpirationTime(nextTime, (NoWork: ExpirationTimeOpaque)) &&
!isSameExpirationTime(nextTime, expirationTime)
) {
// There's additional work on this root.
break;
}
if (
!isSameExpirationTime(
lastSuspendedTime,
(NoWork: ExpirationTimeOpaque),
) &&
!isSameExpirationTime(lastSuspendedTime, expirationTime)
) {
// We should prefer to render the fallback of at the last
// suspended level. Ping the last suspended level to try
// rendering it again.
root.lastPingedTime_opaque = lastSuspendedTime;
break;
}
// The render is suspended, it hasn't timed out, and there's no
// lower priority work to do. Instead of committing the fallback
// immediately, wait for more data to arrive.
root.timeoutHandle = scheduleTimeout(
commitRoot.bind(null, root),
msUntilTimeout,
);
break;
}
}
// The work expired. Commit immediately.
commitRoot(root);
break;
}
case RootSuspendedWithDelay: {
markRootSuspendedAtTime(root, expirationTime);
const lastSuspendedTime = root.lastSuspendedTime_opaque;
if (
// do not delay if we're inside an act() scope
!shouldForceFlushFallbacksInDEV()
) {
// We're suspended in a state that should be avoided. We'll try to
// avoid committing it for as long as the timeouts let us.
if (workInProgressRootHasPendingPing) {
const lastPingedTime = root.lastPingedTime_opaque;
if (
isSameExpirationTime(
lastPingedTime,
(NoWork: ExpirationTimeOpaque),
) ||
isSameOrHigherPriority(lastPingedTime, expirationTime)
) {
// This render was pinged but we didn't get to restart earlier
// so try restarting now instead.
root.lastPingedTime_opaque = expirationTime;
prepareFreshStack(root, expirationTime);
break;
}
}
const nextTime = getNextRootExpirationTimeToWorkOn(root);
if (
!isSameExpirationTime(nextTime, (NoWork: ExpirationTimeOpaque)) &&
!isSameExpirationTime(nextTime, expirationTime)
) {
// There's additional work on this root.
break;
}
if (
!isSameExpirationTime(
lastSuspendedTime,
(NoWork: ExpirationTimeOpaque),
) &&
!isSameExpirationTime(lastSuspendedTime, expirationTime)
) {
// We should prefer to render the fallback of at the last
// suspended level. Ping the last suspended level to try
// rendering it again.
root.lastPingedTime_opaque = lastSuspendedTime;
break;
}
let msUntilTimeout;
if (workInProgressRootLatestSuspenseTimeout !== -1) {
// We have processed a suspense config whose expiration time we
// can use as the timeout.
msUntilTimeout = workInProgressRootLatestSuspenseTimeout - now();
} else if (workInProgressRootLatestProcessedEventTime === -1) {
// This should never normally happen because only new updates
// cause delayed states, so we should have processed something.
// However, this could also happen in an offscreen tree.
msUntilTimeout = 0;
} else {
// If we didn't process a suspense config, compute a JND based on
// the amount of time elapsed since the most recent event time.
const eventTimeMs = workInProgressRootLatestProcessedEventTime;
const timeElapsedMs = now() - eventTimeMs;
msUntilTimeout = jnd(timeElapsedMs) - timeElapsedMs;
}
// Don't bother with a very short suspense time.
if (msUntilTimeout > 10) {
// The render is suspended, it hasn't timed out, and there's no
// lower priority work to do. Instead of committing the fallback
// immediately, wait for more data to arrive.
root.timeoutHandle = scheduleTimeout(
commitRoot.bind(null, root),
msUntilTimeout,
);
break;
}
}
// The work expired. Commit immediately.
commitRoot(root);
break;
}
case RootCompleted: {
// The work completed. Ready to commit.
if (
// do not delay if we're inside an act() scope
!shouldForceFlushFallbacksInDEV() &&
workInProgressRootLatestProcessedEventTime !== -1 &&
workInProgressRootCanSuspendUsingConfig !== null
) {
// If we have exceeded the minimum loading delay, which probably
// means we have shown a spinner already, we might have to suspend
// a bit longer to ensure that the spinner is shown for
// enough time.
const msUntilTimeout = computeMsUntilSuspenseLoadingDelay(
workInProgressRootLatestProcessedEventTime,
workInProgressRootCanSuspendUsingConfig,
);
if (msUntilTimeout > 10) {
markRootSuspendedAtTime(root, expirationTime);
root.timeoutHandle = scheduleTimeout(
commitRoot.bind(null, root),
msUntilTimeout,
);
break;
}
}
commitRoot(root);
break;
}
default: {
invariant(false, 'Unknown root exit status.');
}
}
}
// This is the entry point for synchronous tasks that don't go
// through Scheduler
function performSyncWorkOnRoot(root) {
invariant(
(executionContext & (RenderContext | CommitContext)) === NoContext,
'Should not already be working.',
);
flushPassiveEffects();
const lastExpiredTime = root.lastExpiredTime_opaque;
let expirationTime;
if (!isSameExpirationTime(lastExpiredTime, (NoWork: ExpirationTimeOpaque))) {
// There's expired work on this root. Check if we have a partial tree
// that we can reuse.
if (
root === workInProgressRoot &&
isSameOrHigherPriority(renderExpirationTime, lastExpiredTime)
) {
// There's a partial tree with equal or greater than priority than the
// expired level. Finish rendering it before rendering the rest of the
// expired work.
expirationTime = renderExpirationTime;
} else {
// Start a fresh tree.
expirationTime = lastExpiredTime;
}
} else {
// There's no expired work. This must be a new, synchronous render.
expirationTime = Sync;
}
let exitStatus = renderRootSync(root, expirationTime);
if (root.tag !== LegacyRoot && exitStatus === RootErrored) {
// If something threw an error, try rendering one more time. We'll
// render synchronously to block concurrent data mutations, and we'll
// render at Idle (or lower) so that all pending updates are included.
// If it still fails after the second attempt, we'll give up and commit
// the resulting tree.
expirationTime = !isSameOrHigherPriority(
(Idle: ExpirationTimeOpaque),
expirationTime,
)
? (Idle: ExpirationTimeOpaque)
: expirationTime;
exitStatus = renderRootSync(root, expirationTime);
}
if (exitStatus === RootFatalErrored) {
const fatalError = workInProgressRootFatalError;
prepareFreshStack(root, expirationTime);
markRootSuspendedAtTime(root, expirationTime);
ensureRootIsScheduled(root);
throw fatalError;
}
// We now have a consistent tree. Because this is a sync render, we
// will commit it even if something suspended.
const finishedWork: Fiber = (root.current.alternate: any);
root.finishedWork = finishedWork;
root.finishedExpirationTime_opaque = expirationTime;
root.nextKnownPendingLevel_opaque = getRemainingExpirationTime(finishedWork);
commitRoot(root);
// Before exiting, make sure there's a callback scheduled for the next
// pending level.
ensureRootIsScheduled(root);
return null;
}
export function flushRoot(
root: FiberRoot,
expirationTime: ExpirationTimeOpaque,
) {
markRootExpiredAtTime(root, expirationTime);
ensureRootIsScheduled(root);
if ((executionContext & (RenderContext | CommitContext)) === NoContext) {
flushSyncCallbackQueue();
}
}
export function flushDiscreteUpdates() {
// TODO: Should be able to flush inside batchedUpdates, but not inside `act`.
// However, `act` uses `batchedUpdates`, so there's no way to distinguish
// those two cases. Need to fix this before exposing flushDiscreteUpdates
// as a public API.
if (
(executionContext & (BatchedContext | RenderContext | CommitContext)) !==
NoContext
) {
if (__DEV__) {
if ((executionContext & RenderContext) !== NoContext) {
console.error(
'unstable_flushDiscreteUpdates: Cannot flush updates when React is ' +
'already rendering.',
);
}
}
// We're already rendering, so we can't synchronously flush pending work.
// This is probably a nested event dispatch triggered by a lifecycle/effect,
// like `el.focus()`. Exit.
return;
}
flushPendingDiscreteUpdates();
// If the discrete updates scheduled passive effects, flush them now so that
// they fire before the next serial event.
flushPassiveEffects();
}
export function deferredUpdates<A>(fn: () => A): A {
// TODO: Remove in favor of Scheduler.next
return runWithPriority(NormalSchedulerPriority, fn);
}
export function syncUpdates<A, B, C, R>(
fn: (A, B, C) => R,
a: A,
b: B,
c: C,
): R {
return runWithPriority(ImmediateSchedulerPriority, fn.bind(null, a, b, c));
}
function flushPendingDiscreteUpdates() {
if (rootsWithPendingDiscreteUpdates !== null) {
// For each root with pending discrete updates, schedule a callback to
// immediately flush them.
const roots = rootsWithPendingDiscreteUpdates;
rootsWithPendingDiscreteUpdates = null;
roots.forEach((expirationTime, root) => {
markRootExpiredAtTime(root, expirationTime);
ensureRootIsScheduled(root);
});
// Now flush the immediate queue.
flushSyncCallbackQueue();
}
}
export function batchedUpdates<A, R>(fn: A => R, a: A): R {
const prevExecutionContext = executionContext;
executionContext |= BatchedContext;
try {
return fn(a);
} finally {
executionContext = prevExecutionContext;
if (executionContext === NoContext) {
// Flush the immediate callbacks that were scheduled during this batch
flushSyncCallbackQueue();
}
}
}
export function batchedEventUpdates<A, R>(fn: A => R, a: A): R {
const prevExecutionContext = executionContext;
executionContext |= EventContext;
try {
return fn(a);
} finally {
executionContext = prevExecutionContext;
if (executionContext === NoContext) {
// Flush the immediate callbacks that were scheduled during this batch
flushSyncCallbackQueue();
}
}
}
export function discreteUpdates<A, B, C, D, R>(
fn: (A, B, C) => R,
a: A,
b: B,
c: C,
d: D,
): R {
const prevExecutionContext = executionContext;
executionContext |= DiscreteEventContext;
try {
// Should this
return runWithPriority(
UserBlockingSchedulerPriority,
fn.bind(null, a, b, c, d),
);
} finally {
executionContext = prevExecutionContext;
if (executionContext === NoContext) {
// Flush the immediate callbacks that were scheduled during this batch
flushSyncCallbackQueue();
}
}
}
export function unbatchedUpdates<A, R>(fn: (a: A) => R, a: A): R {
const prevExecutionContext = executionContext;
executionContext &= ~BatchedContext;
executionContext |= LegacyUnbatchedContext;
try {
return fn(a);
} finally {
executionContext = prevExecutionContext;
if (executionContext === NoContext) {
// Flush the immediate callbacks that were scheduled during this batch
flushSyncCallbackQueue();
}
}
}
export function flushSync<A, R>(fn: A => R, a: A): R {
const prevExecutionContext = executionContext;
if ((prevExecutionContext & (RenderContext | CommitContext)) !== NoContext) {
if (__DEV__) {
console.error(
'flushSync was called from inside a lifecycle method. React cannot ' +
'flush when React is already rendering. Consider moving this call to ' +
'a scheduler task or micro task.',
);
}
return fn(a);
}
executionContext |= BatchedContext;
try {
return runWithPriority(ImmediateSchedulerPriority, fn.bind(null, a));
} finally {
executionContext = prevExecutionContext;
// Flush the immediate callbacks that were scheduled during this batch.
// Note that this will happen even if batchedUpdates is higher up
// the stack.
flushSyncCallbackQueue();
}
}
export function flushControlled(fn: () => mixed): void {
const prevExecutionContext = executionContext;
executionContext |= BatchedContext;
try {
runWithPriority(ImmediateSchedulerPriority, fn);
} finally {
executionContext = prevExecutionContext;
if (executionContext === NoContext) {
// Flush the immediate callbacks that were scheduled during this batch
flushSyncCallbackQueue();
}
}
}
function prepareFreshStack(root, expirationTime) {
root.finishedWork = null;
root.finishedExpirationTime_opaque = NoWork;
const timeoutHandle = root.timeoutHandle;
if (timeoutHandle !== noTimeout) {
// The root previous suspended and scheduled a timeout to commit a fallback
// state. Now that we have additional work, cancel the timeout.
root.timeoutHandle = noTimeout;
// $FlowFixMe Complains noTimeout is not a TimeoutID, despite the check above
cancelTimeout(timeoutHandle);
}
// Check if there's a suspended level at lower priority.
const lastSuspendedTime = root.lastSuspendedTime_opaque;
if (
!isSameExpirationTime(lastSuspendedTime, (NoWork: ExpirationTimeOpaque)) &&
!isSameOrHigherPriority(lastSuspendedTime, expirationTime)
) {
const lastPingedTime = root.lastPingedTime_opaque;
// Make sure the suspended level is marked as pinged so that we return back
// to it later, in case the render we're about to start gets aborted.
// Generally we only reach this path via a ping, but we shouldn't assume
// that will always be the case.
// Note: This is defensive coding to prevent a pending commit from
// being dropped without being rescheduled. It shouldn't be necessary.
if (
isSameExpirationTime(lastPingedTime, (NoWork: ExpirationTimeOpaque)) ||
!isSameOrHigherPriority(lastSuspendedTime, lastPingedTime)
) {
root.lastPingedTime_opaque = lastSuspendedTime;
}
}
if (workInProgress !== null) {
let interruptedWork = workInProgress.return;
while (interruptedWork !== null) {
unwindInterruptedWork(interruptedWork);
interruptedWork = interruptedWork.return;
}
}
workInProgressRoot = root;
workInProgress = createWorkInProgress(root.current, null);
renderExpirationTime = expirationTime;
workInProgressRootExitStatus = RootIncomplete;
workInProgressRootFatalError = null;
workInProgressRootLatestProcessedEventTime = -1;
workInProgressRootLatestSuspenseTimeout = -1;
workInProgressRootCanSuspendUsingConfig = null;
workInProgressRootNextUnprocessedUpdateTime = NoWork;
workInProgressRootHasPendingPing = false;
if (enableSchedulerTracing) {
spawnedWorkDuringRender = null;
}
if (__DEV__) {
ReactStrictModeWarnings.discardPendingWarnings();
}
}
function handleError(root, thrownValue): void {
do {
let erroredWork = workInProgress;
try {
// Reset module-level state that was set during the render phase.
resetContextDependencies();
resetHooksAfterThrow();
resetCurrentDebugFiberInDEV();
// TODO: I found and added this missing line while investigating a
// separate issue. Write a regression test using string refs.
ReactCurrentOwner.current = null;
if (erroredWork === null || erroredWork.return === null) {
// Expected to be working on a non-root fiber. This is a fatal error
// because there's no ancestor that can handle it; the root is
// supposed to capture all errors that weren't caught by an error
// boundary.
workInProgressRootExitStatus = RootFatalErrored;
workInProgressRootFatalError = thrownValue;
// Set `workInProgress` to null. This represents advancing to the next
// sibling, or the parent if there are no siblings. But since the root
// has no siblings nor a parent, we set it to null. Usually this is
// handled by `completeUnitOfWork` or `unwindWork`, but since we're
// interntionally not calling those, we need set it here.
// TODO: Consider calling `unwindWork` to pop the contexts.
workInProgress = null;
return;
}
if (enableProfilerTimer && erroredWork.mode & ProfileMode) {
// Record the time spent rendering before an error was thrown. This
// avoids inaccurate Profiler durations in the case of a
// suspended render.
stopProfilerTimerIfRunningAndRecordDelta(erroredWork, true);
}
throwException(
root,
erroredWork.return,
erroredWork,
thrownValue,
renderExpirationTime,
);
completeUnitOfWork(erroredWork);
} catch (yetAnotherThrownValue) {
// Something in the return path also threw.
thrownValue = yetAnotherThrownValue;
if (workInProgress === erroredWork && erroredWork !== null) {
// If this boundary has already errored, then we had trouble processing
// the error. Bubble it to the next boundary.
erroredWork = erroredWork.return;
workInProgress = erroredWork;
} else {
erroredWork = workInProgress;
}
continue;
}
// Return to the normal work loop.
return;
} while (true);
}
function pushDispatcher(root) {
const prevDispatcher = ReactCurrentDispatcher.current;
ReactCurrentDispatcher.current = ContextOnlyDispatcher;
if (prevDispatcher === null) {
// The React isomorphic package does not include a default dispatcher.
// Instead the first renderer will lazily attach one, in order to give
// nicer error messages.
return ContextOnlyDispatcher;
} else {
return prevDispatcher;
}
}
function popDispatcher(prevDispatcher) {
ReactCurrentDispatcher.current = prevDispatcher;
}
function pushInteractions(root) {
if (enableSchedulerTracing) {
const prevInteractions: Set<Interaction> | null = __interactionsRef.current;
__interactionsRef.current = root.memoizedInteractions;
return prevInteractions;
}
return null;
}
function popInteractions(prevInteractions) {
if (enableSchedulerTracing) {
__interactionsRef.current = prevInteractions;
}
}
export function markCommitTimeOfFallback() {
globalMostRecentFallbackTime = now();
}
export function markRenderEventTimeAndConfig(
eventTime: number,
suspenseConfig: null | SuspenseConfig,
): void {
// Track the most recent event time of all updates processed in this batch.
if (workInProgressRootLatestProcessedEventTime < eventTime) {
workInProgressRootLatestProcessedEventTime = eventTime;
}
// Track the largest/latest timeout deadline in this batch.
// TODO: If there are two transitions in the same batch, shouldn't we
// choose the smaller one? Maybe this is because when an intermediate
// transition is superseded, we should ignore its suspense config, but
// we don't currently.
if (suspenseConfig !== null) {
// If `timeoutMs` is not specified, we default to 5 seconds. We have to
// resolve this default here because `suspenseConfig` is owned
// by userspace.
// TODO: Store this on the root instead (transition -> timeoutMs)
// TODO: Should this default to a JND instead?
const timeoutMs = suspenseConfig.timeoutMs | 0 || DEFAULT_TIMEOUT_MS;
const timeoutTime = eventTime + timeoutMs;
if (timeoutTime > workInProgressRootLatestSuspenseTimeout) {
workInProgressRootLatestSuspenseTimeout = timeoutTime;
workInProgressRootCanSuspendUsingConfig = suspenseConfig;
}
}
}
export function markUnprocessedUpdateTime(
expirationTime: ExpirationTimeOpaque,
): void {
if (
!isSameOrHigherPriority(
workInProgressRootNextUnprocessedUpdateTime,
expirationTime,
)
) {
workInProgressRootNextUnprocessedUpdateTime = expirationTime;
}
}
export function renderDidSuspend(): void {
if (workInProgressRootExitStatus === RootIncomplete) {
workInProgressRootExitStatus = RootSuspended;
}
}
export function renderDidSuspendDelayIfPossible(): void {
if (
workInProgressRootExitStatus === RootIncomplete ||
workInProgressRootExitStatus === RootSuspended
) {
workInProgressRootExitStatus = RootSuspendedWithDelay;
}
// Check if there's a lower priority update somewhere else in the tree.
if (
!isSameExpirationTime(
workInProgressRootNextUnprocessedUpdateTime,
(NoWork: ExpirationTimeOpaque),
) &&
workInProgressRoot !== null
) {
// Mark the current render as suspended, and then mark that there's a
// pending update.
// TODO: This should immediately interrupt the current render, instead
// of waiting until the next time we yield.
markRootSuspendedAtTime(workInProgressRoot, renderExpirationTime);
markRootUpdatedAtTime(
workInProgressRoot,
workInProgressRootNextUnprocessedUpdateTime,
);
}
}
export function renderDidError() {
if (workInProgressRootExitStatus !== RootCompleted) {
workInProgressRootExitStatus = RootErrored;
}
}
// Called during render to determine if anything has suspended.
// Returns false if we're not sure.
export function renderHasNotSuspendedYet(): boolean {
// If something errored or completed, we can't really be sure,
// so those are false.
return workInProgressRootExitStatus === RootIncomplete;
}
function renderRootSync(root, expirationTime) {
const prevExecutionContext = executionContext;
executionContext |= RenderContext;
const prevDispatcher = pushDispatcher(root);
// If the root or expiration time have changed, throw out the existing stack
// and prepare a fresh one. Otherwise we'll continue where we left off.
if (
root !== workInProgressRoot ||
!isSameExpirationTime(expirationTime, renderExpirationTime)
) {
prepareFreshStack(root, expirationTime);
startWorkOnPendingInteractions(root, expirationTime);
}
const prevInteractions = pushInteractions(root);
do {
try {
workLoopSync();
break;
} catch (thrownValue) {
handleError(root, thrownValue);
}
} while (true);
resetContextDependencies();
if (enableSchedulerTracing) {
popInteractions(((prevInteractions: any): Set<Interaction>));
}
executionContext = prevExecutionContext;
popDispatcher(prevDispatcher);
if (workInProgress !== null) {
// This is a sync render, so we should have finished the whole tree.
invariant(
false,
'Cannot commit an incomplete root. This error is likely caused by a ' +
'bug in React. Please file an issue.',
);
}
// Set this to null to indicate there's no in-progress render.
workInProgressRoot = null;
return workInProgressRootExitStatus;
}
// The work loop is an extremely hot path. Tell Closure not to inline it.
/** @noinline */
function workLoopSync() {
// Already timed out, so perform work without checking if we need to yield.
while (workInProgress !== null) {
performUnitOfWork(workInProgress);
}
}
function renderRootConcurrent(root, expirationTime) {
const prevExecutionContext = executionContext;
executionContext |= RenderContext;
const prevDispatcher = pushDispatcher(root);
// If the root or expiration time have changed, throw out the existing stack
// and prepare a fresh one. Otherwise we'll continue where we left off.
if (
root !== workInProgressRoot ||
!isSameExpirationTime(expirationTime, renderExpirationTime)
) {
prepareFreshStack(root, expirationTime);
startWorkOnPendingInteractions(root, expirationTime);
}
const prevInteractions = pushInteractions(root);
do {
try {
workLoopConcurrent();
break;
} catch (thrownValue) {
handleError(root, thrownValue);
}
} while (true);
resetContextDependencies();
if (enableSchedulerTracing) {
popInteractions(((prevInteractions: any): Set<Interaction>));
}
popDispatcher(prevDispatcher);
executionContext = prevExecutionContext;
// Check if the tree has completed.
if (workInProgress !== null) {
// Still work remaining.
return RootIncomplete;
} else {
// Completed the tree.
// Set this to null to indicate there's no in-progress render.
workInProgressRoot = null;
// Return the final exit status.
return workInProgressRootExitStatus;
}
}
/** @noinline */
function workLoopConcurrent() {
// Perform work until Scheduler asks us to yield
while (workInProgress !== null && !shouldYield()) {
performUnitOfWork(workInProgress);
}
}
function performUnitOfWork(unitOfWork: Fiber): void {
// The current, flushed, state of this fiber is the alternate. Ideally
// nothing should rely on this, but relying on it here means that we don't
// need an additional field on the work in progress.
const current = unitOfWork.alternate;
setCurrentDebugFiberInDEV(unitOfWork);
let next;
if (enableProfilerTimer && (unitOfWork.mode & ProfileMode) !== NoMode) {
startProfilerTimer(unitOfWork);
next = beginWork(current, unitOfWork, renderExpirationTime);
stopProfilerTimerIfRunningAndRecordDelta(unitOfWork, true);
} else {
next = beginWork(current, unitOfWork, renderExpirationTime);
}
resetCurrentDebugFiberInDEV();
unitOfWork.memoizedProps = unitOfWork.pendingProps;
if (next === null) {
// If this doesn't spawn new work, complete the current work.
completeUnitOfWork(unitOfWork);
} else {
workInProgress = next;
}
ReactCurrentOwner.current = null;
}
function completeUnitOfWork(unitOfWork: Fiber): void {
// Attempt to complete the current unit of work, then move to the next
// sibling. If there are no more siblings, return to the parent fiber.
let completedWork = unitOfWork;
do {
// The current, flushed, state of this fiber is the alternate. Ideally
// nothing should rely on this, but relying on it here means that we don't
// need an additional field on the work in progress.
const current = completedWork.alternate;
const returnFiber = completedWork.return;
// Check if the work completed or if something threw.
if ((completedWork.effectTag & Incomplete) === NoEffect) {
setCurrentDebugFiberInDEV(completedWork);
let next;
if (
!enableProfilerTimer ||
(completedWork.mode & ProfileMode) === NoMode
) {
next = completeWork(current, completedWork, renderExpirationTime);
} else {
startProfilerTimer(completedWork);
next = completeWork(current, completedWork, renderExpirationTime);
// Update render duration assuming we didn't error.
stopProfilerTimerIfRunningAndRecordDelta(completedWork, false);
}
resetCurrentDebugFiberInDEV();
resetChildExpirationTime(completedWork);
if (next !== null) {
// Completing this fiber spawned new work. Work on that next.
workInProgress = next;
return;
}
if (
returnFiber !== null &&
// Do not append effects to parents if a sibling failed to complete
(returnFiber.effectTag & Incomplete) === NoEffect
) {
// Append all the effects of the subtree and this fiber onto the effect
// list of the parent. The completion order of the children affects the
// side-effect order.
if (returnFiber.firstEffect === null) {
returnFiber.firstEffect = completedWork.firstEffect;
}
if (completedWork.lastEffect !== null) {
if (returnFiber.lastEffect !== null) {
returnFiber.lastEffect.nextEffect = completedWork.firstEffect;
}
returnFiber.lastEffect = completedWork.lastEffect;
}
// If this fiber had side-effects, we append it AFTER the children's
// side-effects. We can perform certain side-effects earlier if needed,
// by doing multiple passes over the effect list. We don't want to
// schedule our own side-effect on our own list because if end up
// reusing children we'll schedule this effect onto itself since we're
// at the end.
const effectTag = completedWork.effectTag;
// Skip both NoWork and PerformedWork tags when creating the effect
// list. PerformedWork effect is read by React DevTools but shouldn't be
// committed.
if (effectTag > PerformedWork) {
if (returnFiber.lastEffect !== null) {
returnFiber.lastEffect.nextEffect = completedWork;
} else {
returnFiber.firstEffect = completedWork;
}
returnFiber.lastEffect = completedWork;
}
}
} else {
// This fiber did not complete because something threw. Pop values off
// the stack without entering the complete phase. If this is a boundary,
// capture values if possible.
const next = unwindWork(completedWork, renderExpirationTime);
// Because this fiber did not complete, don't reset its expiration time.
if (
enableProfilerTimer &&
(completedWork.mode & ProfileMode) !== NoMode
) {
// Record the render duration for the fiber that errored.
stopProfilerTimerIfRunningAndRecordDelta(completedWork, false);
// Include the time spent working on failed children before continuing.
let actualDuration = completedWork.actualDuration;
let child = completedWork.child;
while (child !== null) {
actualDuration += child.actualDuration;
child = child.sibling;
}
completedWork.actualDuration = actualDuration;
}
if (next !== null) {
// If completing this work spawned new work, do that next. We'll come
// back here again.
// Since we're restarting, remove anything that is not a host effect
// from the effect tag.
next.effectTag &= HostEffectMask;
workInProgress = next;
return;
}
if (returnFiber !== null) {
// Mark the parent fiber as incomplete and clear its effect list.
returnFiber.firstEffect = returnFiber.lastEffect = null;
returnFiber.effectTag |= Incomplete;
}
}
const siblingFiber = completedWork.sibling;
if (siblingFiber !== null) {
// If there is more work to do in this returnFiber, do that next.
workInProgress = siblingFiber;
return;
}
// Otherwise, return to the parent
completedWork = returnFiber;
// Update the next thing we're working on in case something throws.
workInProgress = completedWork;
} while (completedWork !== null);
// We've reached the root.
if (workInProgressRootExitStatus === RootIncomplete) {
workInProgressRootExitStatus = RootCompleted;
}
}
function getRemainingExpirationTime(fiber: Fiber) {
const updateExpirationTime = fiber.expirationTime_opaque;
const childExpirationTime = fiber.childExpirationTime_opaque;
return !isSameOrHigherPriority(childExpirationTime, updateExpirationTime)
? updateExpirationTime
: childExpirationTime;
}
function resetChildExpirationTime(completedWork: Fiber) {
if (
!isSameExpirationTime(
renderExpirationTime,
(Never: ExpirationTimeOpaque),
) &&
isSameExpirationTime(
completedWork.childExpirationTime_opaque,
(Never: ExpirationTimeOpaque),
)
) {
// The children of this component are hidden. Don't bubble their
// expiration times.
return;
}
let newChildExpirationTime = NoWork;
// Bubble up the earliest expiration time.
if (enableProfilerTimer && (completedWork.mode & ProfileMode) !== NoMode) {
// In profiling mode, resetChildExpirationTime is also used to reset
// profiler durations.
let actualDuration = completedWork.actualDuration;
let treeBaseDuration = completedWork.selfBaseDuration;
// When a fiber is cloned, its actualDuration is reset to 0. This value will
// only be updated if work is done on the fiber (i.e. it doesn't bailout).
// When work is done, it should bubble to the parent's actualDuration. If
// the fiber has not been cloned though, (meaning no work was done), then
// this value will reflect the amount of time spent working on a previous
// render. In that case it should not bubble. We determine whether it was
// cloned by comparing the child pointer.
const shouldBubbleActualDurations =
completedWork.alternate === null ||
completedWork.child !== completedWork.alternate.child;
let child = completedWork.child;
while (child !== null) {
const childUpdateExpirationTime = child.expirationTime_opaque;
const childChildExpirationTime = child.childExpirationTime_opaque;
if (
!isSameOrHigherPriority(
newChildExpirationTime,
childUpdateExpirationTime,
)
) {
newChildExpirationTime = childUpdateExpirationTime;
}
if (
!isSameOrHigherPriority(
newChildExpirationTime,
childChildExpirationTime,
)
) {
newChildExpirationTime = childChildExpirationTime;
}
if (shouldBubbleActualDurations) {
actualDuration += child.actualDuration;
}
treeBaseDuration += child.treeBaseDuration;
child = child.sibling;
}
completedWork.actualDuration = actualDuration;
completedWork.treeBaseDuration = treeBaseDuration;
} else {
let child = completedWork.child;
while (child !== null) {
const childUpdateExpirationTime = child.expirationTime_opaque;
const childChildExpirationTime = child.childExpirationTime_opaque;
if (
!isSameOrHigherPriority(
newChildExpirationTime,
childUpdateExpirationTime,
)
) {
newChildExpirationTime = childUpdateExpirationTime;
}
if (
!isSameOrHigherPriority(
newChildExpirationTime,
childChildExpirationTime,
)
) {
newChildExpirationTime = childChildExpirationTime;
}
child = child.sibling;
}
}
completedWork.childExpirationTime_opaque = newChildExpirationTime;
}
function commitRoot(root) {
const renderPriorityLevel = getCurrentPriorityLevel();
runWithPriority(
ImmediateSchedulerPriority,
commitRootImpl.bind(null, root, renderPriorityLevel),
);
return null;
}
function commitRootImpl(root, renderPriorityLevel) {
do {
// `flushPassiveEffects` will call `flushSyncUpdateQueue` at the end, which
// means `flushPassiveEffects` will sometimes result in additional
// passive effects. So we need to keep flushing in a loop until there are
// no more pending effects.
// TODO: Might be better if `flushPassiveEffects` did not automatically
// flush synchronous work at the end, to avoid factoring hazards like this.
flushPassiveEffects();
} while (rootWithPendingPassiveEffects !== null);
flushRenderPhaseStrictModeWarningsInDEV();
invariant(
(executionContext & (RenderContext | CommitContext)) === NoContext,
'Should not already be working.',
);
const finishedWork = root.finishedWork;
const expirationTime = root.finishedExpirationTime_opaque;
if (finishedWork === null) {
return null;
}
root.finishedWork = null;
root.finishedExpirationTime_opaque = NoWork;
invariant(
finishedWork !== root.current,
'Cannot commit the same tree as before. This error is likely caused by ' +
'a bug in React. Please file an issue.',
);
// commitRoot never returns a continuation; it always finishes synchronously.
// So we can clear these now to allow a new callback to be scheduled.
root.callbackNode = null;
root.callbackId = NoWork;
// TODO: Use LanePriority instead of SchedulerPriority
if (renderPriorityLevel < ImmediateSchedulerPriority) {
// If this was a concurrent render, we can reset the expiration time.
root.expiresAt = -1;
}
// Update the first and last pending times on this root. The new first
// pending time is whatever is left on the root fiber.
const remainingExpirationTimeBeforeCommit = getRemainingExpirationTime(
finishedWork,
);
markRootFinishedAtTime(
root,
expirationTime,
remainingExpirationTimeBeforeCommit,
);
// Clear already finished discrete updates in case that a later call of
// `flushDiscreteUpdates` starts a useless render pass which may cancels
// a scheduled timeout.
if (rootsWithPendingDiscreteUpdates !== null) {
const lastDiscreteTime = rootsWithPendingDiscreteUpdates.get(root);
if (
lastDiscreteTime !== undefined &&
!isSameOrHigherPriority(
remainingExpirationTimeBeforeCommit,
lastDiscreteTime,
)
) {
rootsWithPendingDiscreteUpdates.delete(root);
}
}
if (root === workInProgressRoot) {
// We can reset these now that they are finished.
workInProgressRoot = null;
workInProgress = null;
renderExpirationTime = NoWork;
} else {
// This indicates that the last root we worked on is not the same one that
// we're committing now. This most commonly happens when a suspended root
// times out.
}
// Get the list of effects.
let firstEffect;
if (finishedWork.effectTag > PerformedWork) {
// A fiber's effect list consists only of its children, not itself. So if
// the root has an effect, we need to add it to the end of the list. The
// resulting list is the set that would belong to the root's parent, if it
// had one; that is, all the effects in the tree including the root.
if (finishedWork.lastEffect !== null) {
finishedWork.lastEffect.nextEffect = finishedWork;
firstEffect = finishedWork.firstEffect;
} else {
firstEffect = finishedWork;
}
} else {
// There is no effect on the root.
firstEffect = finishedWork.firstEffect;
}
if (firstEffect !== null) {
const prevExecutionContext = executionContext;
executionContext |= CommitContext;
const prevInteractions = pushInteractions(root);
// Reset this to null before calling lifecycles
ReactCurrentOwner.current = null;
// The commit phase is broken into several sub-phases. We do a separate pass
// of the effect list for each phase: all mutation effects come before all
// layout effects, and so on.
// The first phase a "before mutation" phase. We use this phase to read the
// state of the host tree right before we mutate it. This is where
// getSnapshotBeforeUpdate is called.
focusedInstanceHandle = prepareForCommit(root.containerInfo);
shouldFireAfterActiveInstanceBlur = false;
nextEffect = firstEffect;
do {
if (__DEV__) {
invokeGuardedCallback(null, commitBeforeMutationEffects, null);
if (hasCaughtError()) {
invariant(nextEffect !== null, 'Should be working on an effect.');
const error = clearCaughtError();
captureCommitPhaseError(nextEffect, error);
nextEffect = nextEffect.nextEffect;
}
} else {
try {
commitBeforeMutationEffects();
} catch (error) {
invariant(nextEffect !== null, 'Should be working on an effect.');
captureCommitPhaseError(nextEffect, error);
nextEffect = nextEffect.nextEffect;
}
}
} while (nextEffect !== null);
// We no longer need to track the active instance fiber
focusedInstanceHandle = null;
if (enableProfilerTimer) {
// Mark the current commit time to be shared by all Profilers in this
// batch. This enables them to be grouped later.
recordCommitTime();
}
// The next phase is the mutation phase, where we mutate the host tree.
nextEffect = firstEffect;
do {
if (__DEV__) {
invokeGuardedCallback(
null,
commitMutationEffects,
null,
root,
renderPriorityLevel,
);
if (hasCaughtError()) {
invariant(nextEffect !== null, 'Should be working on an effect.');
const error = clearCaughtError();
captureCommitPhaseError(nextEffect, error);
nextEffect = nextEffect.nextEffect;
}
} else {
try {
commitMutationEffects(root, renderPriorityLevel);
} catch (error) {
invariant(nextEffect !== null, 'Should be working on an effect.');
captureCommitPhaseError(nextEffect, error);
nextEffect = nextEffect.nextEffect;
}
}
} while (nextEffect !== null);
if (shouldFireAfterActiveInstanceBlur) {
afterActiveInstanceBlur();
}
resetAfterCommit(root.containerInfo);
// The work-in-progress tree is now the current tree. This must come after
// the mutation phase, so that the previous tree is still current during
// componentWillUnmount, but before the layout phase, so that the finished
// work is current during componentDidMount/Update.
root.current = finishedWork;
// The next phase is the layout phase, where we call effects that read
// the host tree after it's been mutated. The idiomatic use case for this is
// layout, but class component lifecycles also fire here for legacy reasons.
nextEffect = firstEffect;
do {
if (__DEV__) {
invokeGuardedCallback(
null,
commitLayoutEffects,
null,
root,
expirationTime,
);
if (hasCaughtError()) {
invariant(nextEffect !== null, 'Should be working on an effect.');
const error = clearCaughtError();
captureCommitPhaseError(nextEffect, error);
nextEffect = nextEffect.nextEffect;
}
} else {
try {
commitLayoutEffects(root, expirationTime);
} catch (error) {
invariant(nextEffect !== null, 'Should be working on an effect.');
captureCommitPhaseError(nextEffect, error);
nextEffect = nextEffect.nextEffect;
}
}
} while (nextEffect !== null);
nextEffect = null;
// Tell Scheduler to yield at the end of the frame, so the browser has an
// opportunity to paint.
requestPaint();
if (enableSchedulerTracing) {
popInteractions(((prevInteractions: any): Set<Interaction>));
}
executionContext = prevExecutionContext;
} else {
// No effects.
root.current = finishedWork;
// Measure these anyway so the flamegraph explicitly shows that there were
// no effects.
// TODO: Maybe there's a better way to report this.
if (enableProfilerTimer) {
recordCommitTime();
}
}
const rootDidHavePassiveEffects = rootDoesHavePassiveEffects;
if (rootDoesHavePassiveEffects) {
// This commit has passive effects. Stash a reference to them. But don't
// schedule a callback until after flushing layout work.
rootDoesHavePassiveEffects = false;
rootWithPendingPassiveEffects = root;
pendingPassiveEffectsExpirationTime = expirationTime;
pendingPassiveEffectsRenderPriority = renderPriorityLevel;
} else {
// We are done with the effect chain at this point so let's clear the
// nextEffect pointers to assist with GC. If we have passive effects, we'll
// clear this in flushPassiveEffects.
nextEffect = firstEffect;
while (nextEffect !== null) {
const nextNextEffect = nextEffect.nextEffect;
nextEffect.nextEffect = null;
nextEffect = nextNextEffect;
}
}
// Check if there's remaining work on this root
const remainingExpirationTime = root.firstPendingTime_opaque;
if (
!isSameExpirationTime(
remainingExpirationTime,
(NoWork: ExpirationTimeOpaque),
)
) {
if (enableSchedulerTracing) {
if (spawnedWorkDuringRender !== null) {
const expirationTimes = spawnedWorkDuringRender;
spawnedWorkDuringRender = null;
for (let i = 0; i < expirationTimes.length; i++) {
scheduleInteractions(
root,
expirationTimes[i],
root.memoizedInteractions,
);
}
}
schedulePendingInteractions(root, remainingExpirationTime);
}
} else {
// If there's no remaining work, we can clear the set of already failed
// error boundaries.
legacyErrorBoundariesThatAlreadyFailed = null;
}
if (enableSchedulerTracing) {
if (!rootDidHavePassiveEffects) {
// If there are no passive effects, then we can complete the pending interactions.
// Otherwise, we'll wait until after the passive effects are flushed.
// Wait to do this until after remaining work has been scheduled,
// so that we don't prematurely signal complete for interactions when there's e.g. hidden work.
finishPendingInteractions(root, expirationTime);
}
}
if (
isSameExpirationTime(remainingExpirationTime, (Sync: ExpirationTimeOpaque))
) {
// Count the number of times the root synchronously re-renders without
// finishing. If there are too many, it indicates an infinite update loop.
if (root === rootWithNestedUpdates) {
nestedUpdateCount++;
} else {
nestedUpdateCount = 0;
rootWithNestedUpdates = root;
}
} else {
nestedUpdateCount = 0;
}
onCommitRoot(finishedWork.stateNode, renderPriorityLevel);
// Always call this before exiting `commitRoot`, to ensure that any
// additional work on this root is scheduled.
ensureRootIsScheduled(root);
if (hasUncaughtError) {
hasUncaughtError = false;
const error = firstUncaughtError;
firstUncaughtError = null;
throw error;
}
if ((executionContext & LegacyUnbatchedContext) !== NoContext) {
// This is a legacy edge case. We just committed the initial mount of
// a ReactDOM.render-ed root inside of batchedUpdates. The commit fired
// synchronously, but layout updates should be deferred until the end
// of the batch.
return null;
}
// If layout work was scheduled, flush it now.
flushSyncCallbackQueue();
return null;
}
function commitBeforeMutationEffects() {
while (nextEffect !== null) {
if (
!shouldFireAfterActiveInstanceBlur &&
focusedInstanceHandle !== null &&
isFiberHiddenOrDeletedAndContains(nextEffect, focusedInstanceHandle)
) {
shouldFireAfterActiveInstanceBlur = true;
beforeActiveInstanceBlur();
}
const effectTag = nextEffect.effectTag;
if ((effectTag & Snapshot) !== NoEffect) {
setCurrentDebugFiberInDEV(nextEffect);
const current = nextEffect.alternate;
commitBeforeMutationEffectOnFiber(current, nextEffect);
resetCurrentDebugFiberInDEV();
}
if ((effectTag & Passive) !== NoEffect) {
// If there are passive effects, schedule a callback to flush at
// the earliest opportunity.
if (!rootDoesHavePassiveEffects) {
rootDoesHavePassiveEffects = true;
scheduleCallback(NormalSchedulerPriority, () => {
flushPassiveEffects();
return null;
});
}
}
nextEffect = nextEffect.nextEffect;
}
}
function commitMutationEffects(root: FiberRoot, renderPriorityLevel) {
// TODO: Should probably move the bulk of this function to commitWork.
while (nextEffect !== null) {
setCurrentDebugFiberInDEV(nextEffect);
const effectTag = nextEffect.effectTag;
if (effectTag & ContentReset) {
commitResetTextContent(nextEffect);
}
if (effectTag & Ref) {
const current = nextEffect.alternate;
if (current !== null) {
commitDetachRef(current);
}
}
// The following switch statement is only concerned about placement,
// updates, and deletions. To avoid needing to add a case for every possible
// bitmap value, we remove the secondary effects from the effect tag and
// switch on that value.
const primaryEffectTag =
effectTag & (Placement | Update | Deletion | Hydrating);
switch (primaryEffectTag) {
case Placement: {
commitPlacement(nextEffect);
// Clear the "placement" from effect tag so that we know that this is
// inserted, before any life-cycles like componentDidMount gets called.
// TODO: findDOMNode doesn't rely on this any more but isMounted does
// and isMounted is deprecated anyway so we should be able to kill this.
nextEffect.effectTag &= ~Placement;
break;
}
case PlacementAndUpdate: {
// Placement
commitPlacement(nextEffect);
// Clear the "placement" from effect tag so that we know that this is
// inserted, before any life-cycles like componentDidMount gets called.
nextEffect.effectTag &= ~Placement;
// Update
const current = nextEffect.alternate;
commitWork(current, nextEffect);
break;
}
case Hydrating: {
nextEffect.effectTag &= ~Hydrating;
break;
}
case HydratingAndUpdate: {
nextEffect.effectTag &= ~Hydrating;
// Update
const current = nextEffect.alternate;
commitWork(current, nextEffect);
break;
}
case Update: {
const current = nextEffect.alternate;
commitWork(current, nextEffect);
break;
}
case Deletion: {
commitDeletion(root, nextEffect, renderPriorityLevel);
break;
}
}
resetCurrentDebugFiberInDEV();
nextEffect = nextEffect.nextEffect;
}
}
function commitLayoutEffects(
root: FiberRoot,
committedExpirationTime: ExpirationTimeOpaque,
) {
// TODO: Should probably move the bulk of this function to commitWork.
while (nextEffect !== null) {
setCurrentDebugFiberInDEV(nextEffect);
const effectTag = nextEffect.effectTag;
if (effectTag & (Update | Callback)) {
const current = nextEffect.alternate;
commitLayoutEffectOnFiber(
root,
current,
nextEffect,
committedExpirationTime,
);
}
if (effectTag & Ref) {
commitAttachRef(nextEffect);
}
resetCurrentDebugFiberInDEV();
nextEffect = nextEffect.nextEffect;
}
}
export function flushPassiveEffects() {
if (pendingPassiveEffectsRenderPriority !== NoSchedulerPriority) {
const priorityLevel =
pendingPassiveEffectsRenderPriority > NormalSchedulerPriority
? NormalSchedulerPriority
: pendingPassiveEffectsRenderPriority;
pendingPassiveEffectsRenderPriority = NoSchedulerPriority;
return runWithPriority(priorityLevel, flushPassiveEffectsImpl);
}
}
export function enqueuePendingPassiveProfilerEffect(fiber: Fiber): void {
if (enableProfilerTimer && enableProfilerCommitHooks) {
pendingPassiveProfilerEffects.push(fiber);
if (!rootDoesHavePassiveEffects) {
rootDoesHavePassiveEffects = true;
scheduleCallback(NormalSchedulerPriority, () => {
flushPassiveEffects();
return null;
});
}
}
}
export function enqueuePendingPassiveHookEffectMount(
fiber: Fiber,
effect: HookEffect,
): void {
if (runAllPassiveEffectDestroysBeforeCreates) {
pendingPassiveHookEffectsMount.push(effect, fiber);
if (!rootDoesHavePassiveEffects) {
rootDoesHavePassiveEffects = true;
scheduleCallback(NormalSchedulerPriority, () => {
flushPassiveEffects();
return null;
});
}
}
}
export function enqueuePendingPassiveHookEffectUnmount(
fiber: Fiber,
effect: HookEffect,
): void {
if (runAllPassiveEffectDestroysBeforeCreates) {
pendingPassiveHookEffectsUnmount.push(effect, fiber);
if (__DEV__) {
if (deferPassiveEffectCleanupDuringUnmount) {
fiber.effectTag |= PassiveUnmountPendingDev;
const alternate = fiber.alternate;
if (alternate !== null) {
alternate.effectTag |= PassiveUnmountPendingDev;
}
}
}
if (!rootDoesHavePassiveEffects) {
rootDoesHavePassiveEffects = true;
scheduleCallback(NormalSchedulerPriority, () => {
flushPassiveEffects();
return null;
});
}
}
}
function invokePassiveEffectCreate(effect: HookEffect): void {
const create = effect.create;
effect.destroy = create();
}
function flushPassiveEffectsImpl() {
if (rootWithPendingPassiveEffects === null) {
return false;
}
const root = rootWithPendingPassiveEffects;
const expirationTime = pendingPassiveEffectsExpirationTime;
rootWithPendingPassiveEffects = null;
pendingPassiveEffectsExpirationTime = NoWork;
invariant(
(executionContext & (RenderContext | CommitContext)) === NoContext,
'Cannot flush passive effects while already rendering.',
);
if (__DEV__) {
isFlushingPassiveEffects = true;
}
const prevExecutionContext = executionContext;
executionContext |= CommitContext;
const prevInteractions = pushInteractions(root);
if (runAllPassiveEffectDestroysBeforeCreates) {
// It's important that ALL pending passive effect destroy functions are called
// before ANY passive effect create functions are called.
// Otherwise effects in sibling components might interfere with each other.
// e.g. a destroy function in one component may unintentionally override a ref
// value set by a create function in another component.
// Layout effects have the same constraint.
// First pass: Destroy stale passive effects.
const unmountEffects = pendingPassiveHookEffectsUnmount;
pendingPassiveHookEffectsUnmount = [];
for (let i = 0; i < unmountEffects.length; i += 2) {
const effect = ((unmountEffects[i]: any): HookEffect);
const fiber = ((unmountEffects[i + 1]: any): Fiber);
const destroy = effect.destroy;
effect.destroy = undefined;
if (__DEV__) {
if (deferPassiveEffectCleanupDuringUnmount) {
fiber.effectTag &= ~PassiveUnmountPendingDev;
const alternate = fiber.alternate;
if (alternate !== null) {
alternate.effectTag &= ~PassiveUnmountPendingDev;
}
}
}
if (typeof destroy === 'function') {
if (__DEV__) {
setCurrentDebugFiberInDEV(fiber);
if (
enableProfilerTimer &&
enableProfilerCommitHooks &&
fiber.mode & ProfileMode
) {
startPassiveEffectTimer();
invokeGuardedCallback(null, destroy, null);
recordPassiveEffectDuration(fiber);
} else {
invokeGuardedCallback(null, destroy, null);
}
if (hasCaughtError()) {
invariant(fiber !== null, 'Should be working on an effect.');
const error = clearCaughtError();
captureCommitPhaseError(fiber, error);
}
resetCurrentDebugFiberInDEV();
} else {
try {
if (
enableProfilerTimer &&
enableProfilerCommitHooks &&
fiber.mode & ProfileMode
) {
try {
startPassiveEffectTimer();
destroy();
} finally {
recordPassiveEffectDuration(fiber);
}
} else {
destroy();
}
} catch (error) {
invariant(fiber !== null, 'Should be working on an effect.');
captureCommitPhaseError(fiber, error);
}
}
}
}
// Second pass: Create new passive effects.
const mountEffects = pendingPassiveHookEffectsMount;
pendingPassiveHookEffectsMount = [];
for (let i = 0; i < mountEffects.length; i += 2) {
const effect = ((mountEffects[i]: any): HookEffect);
const fiber = ((mountEffects[i + 1]: any): Fiber);
if (__DEV__) {
setCurrentDebugFiberInDEV(fiber);
if (
enableProfilerTimer &&
enableProfilerCommitHooks &&
fiber.mode & ProfileMode
) {
startPassiveEffectTimer();
invokeGuardedCallback(null, invokePassiveEffectCreate, null, effect);
recordPassiveEffectDuration(fiber);
} else {
invokeGuardedCallback(null, invokePassiveEffectCreate, null, effect);
}
if (hasCaughtError()) {
invariant(fiber !== null, 'Should be working on an effect.');
const error = clearCaughtError();
captureCommitPhaseError(fiber, error);
}
resetCurrentDebugFiberInDEV();
} else {
try {
const create = effect.create;
if (
enableProfilerTimer &&
enableProfilerCommitHooks &&
fiber.mode & ProfileMode
) {
try {
startPassiveEffectTimer();
effect.destroy = create();
} finally {
recordPassiveEffectDuration(fiber);
}
} else {
effect.destroy = create();
}
} catch (error) {
invariant(fiber !== null, 'Should be working on an effect.');
captureCommitPhaseError(fiber, error);
}
}
}
}
// Note: This currently assumes there are no passive effects on the root fiber
// because the root is not part of its own effect list.
// This could change in the future.
let effect = root.current.firstEffect;
while (effect !== null) {
// We do this work above if this flag is enabled, so we shouldn't be
// doing it here.
if (!runAllPassiveEffectDestroysBeforeCreates) {
if (__DEV__) {
setCurrentDebugFiberInDEV(effect);
invokeGuardedCallback(null, commitPassiveHookEffects, null, effect);
if (hasCaughtError()) {
invariant(effect !== null, 'Should be working on an effect.');
const error = clearCaughtError();
captureCommitPhaseError(effect, error);
}
resetCurrentDebugFiberInDEV();
} else {
try {
commitPassiveHookEffects(effect);
} catch (error) {
invariant(effect !== null, 'Should be working on an effect.');
captureCommitPhaseError(effect, error);
}
}
}
const nextNextEffect = effect.nextEffect;
// Remove nextEffect pointer to assist GC
effect.nextEffect = null;
effect = nextNextEffect;
}
if (enableProfilerTimer && enableProfilerCommitHooks) {
const profilerEffects = pendingPassiveProfilerEffects;
pendingPassiveProfilerEffects = [];
for (let i = 0; i < profilerEffects.length; i++) {
const fiber = ((profilerEffects[i]: any): Fiber);
commitPassiveEffectDurations(root, fiber);
}
}
if (enableSchedulerTracing) {
popInteractions(((prevInteractions: any): Set<Interaction>));
finishPendingInteractions(root, expirationTime);
}
if (__DEV__) {
isFlushingPassiveEffects = false;
}
executionContext = prevExecutionContext;
flushSyncCallbackQueue();
// If additional passive effects were scheduled, increment a counter. If this
// exceeds the limit, we'll fire a warning.
nestedPassiveUpdateCount =
rootWithPendingPassiveEffects === null ? 0 : nestedPassiveUpdateCount + 1;
return true;
}
export function isAlreadyFailedLegacyErrorBoundary(instance: mixed): boolean {
return (
legacyErrorBoundariesThatAlreadyFailed !== null &&
legacyErrorBoundariesThatAlreadyFailed.has(instance)
);
}
export function markLegacyErrorBoundaryAsFailed(instance: mixed) {
if (legacyErrorBoundariesThatAlreadyFailed === null) {
legacyErrorBoundariesThatAlreadyFailed = new Set([instance]);
} else {
legacyErrorBoundariesThatAlreadyFailed.add(instance);
}
}
function prepareToThrowUncaughtError(error: mixed) {
if (!hasUncaughtError) {
hasUncaughtError = true;
firstUncaughtError = error;
}
}
export const onUncaughtError = prepareToThrowUncaughtError;
function captureCommitPhaseErrorOnRoot(
rootFiber: Fiber,
sourceFiber: Fiber,
error: mixed,
) {
const errorInfo = createCapturedValue(error, sourceFiber);
const update = createRootErrorUpdate(
rootFiber,
errorInfo,
(Sync: ExpirationTimeOpaque),
);
enqueueUpdate(rootFiber, update);
const root = markUpdateTimeFromFiberToRoot(
rootFiber,
(Sync: ExpirationTimeOpaque),
);
if (root !== null) {
ensureRootIsScheduled(root);
schedulePendingInteractions(root, (Sync: ExpirationTimeOpaque));
}
}
export function captureCommitPhaseError(sourceFiber: Fiber, error: mixed) {
if (sourceFiber.tag === HostRoot) {
// Error was thrown at the root. There is no parent, so the root
// itself should capture it.
captureCommitPhaseErrorOnRoot(sourceFiber, sourceFiber, error);
return;
}
let fiber = sourceFiber.return;
while (fiber !== null) {
if (fiber.tag === HostRoot) {
captureCommitPhaseErrorOnRoot(fiber, sourceFiber, error);
return;
} else if (fiber.tag === ClassComponent) {
const ctor = fiber.type;
const instance = fiber.stateNode;
if (
typeof ctor.getDerivedStateFromError === 'function' ||
(typeof instance.componentDidCatch === 'function' &&
!isAlreadyFailedLegacyErrorBoundary(instance))
) {
const errorInfo = createCapturedValue(error, sourceFiber);
const update = createClassErrorUpdate(
fiber,
errorInfo,
(Sync: ExpirationTimeOpaque),
);
enqueueUpdate(fiber, update);
const root = markUpdateTimeFromFiberToRoot(
fiber,
(Sync: ExpirationTimeOpaque),
);
if (root !== null) {
ensureRootIsScheduled(root);
schedulePendingInteractions(root, (Sync: ExpirationTimeOpaque));
}
return;
}
}
fiber = fiber.return;
}
}
export function pingSuspendedRoot(
root: FiberRoot,
wakeable: Wakeable,
suspendedTime: ExpirationTimeOpaque,
) {
const pingCache = root.pingCache;
if (pingCache !== null) {
// The wakeable resolved, so we no longer need to memoize, because it will
// never be thrown again.
pingCache.delete(wakeable);
}
if (
workInProgressRoot === root &&
isSameExpirationTime(renderExpirationTime, suspendedTime)
) {
// Received a ping at the same priority level at which we're currently
// rendering. We might want to restart this render. This should mirror
// the logic of whether or not a root suspends once it completes.
// TODO: If we're rendering sync either due to Sync, Batched or expired,
// we should probably never restart.
// If we're suspended with delay, we'll always suspend so we can always
// restart. If we're suspended without any updates, it might be a retry.
// If it's early in the retry we can restart. We can't know for sure
// whether we'll eventually process an update during this render pass,
// but it's somewhat unlikely that we get to a ping before that, since
// getting to the root most update is usually very fast.
if (
workInProgressRootExitStatus === RootSuspendedWithDelay ||
(workInProgressRootExitStatus === RootSuspended &&
workInProgressRootLatestProcessedEventTime === -1 &&
now() - globalMostRecentFallbackTime < FALLBACK_THROTTLE_MS)
) {
// Restart from the root. Don't need to schedule a ping because
// we're already working on this tree.
prepareFreshStack(root, renderExpirationTime);
} else {
// Even though we can't restart right now, we might get an
// opportunity later. So we mark this render as having a ping.
workInProgressRootHasPendingPing = true;
}
return;
}
if (!isRootSuspendedAtTime(root, suspendedTime)) {
// The root is no longer suspended at this time.
return;
}
const lastPingedTime = root.lastPingedTime_opaque;
if (
!isSameExpirationTime(lastPingedTime, (NoWork: ExpirationTimeOpaque)) &&
!isSameOrHigherPriority(lastPingedTime, suspendedTime)
) {
// There's already a lower priority ping scheduled.
return;
}
// Mark the time at which this ping was scheduled.
root.lastPingedTime_opaque = suspendedTime;
ensureRootIsScheduled(root);
schedulePendingInteractions(root, suspendedTime);
}
function retryTimedOutBoundary(
boundaryFiber: Fiber,
retryTime: ExpirationTimeOpaque,
) {
// The boundary fiber (a Suspense component or SuspenseList component)
// previously was rendered in its fallback state. One of the promises that
// suspended it has resolved, which means at least part of the tree was
// likely unblocked. Try rendering again, at a new expiration time.
if (isSameExpirationTime(retryTime, (NoWork: ExpirationTimeOpaque))) {
const suspenseConfig = null; // Retries don't carry over the already committed update.
retryTime = requestUpdateExpirationTime(boundaryFiber, suspenseConfig);
}
// TODO: Special case idle priority?
const root = markUpdateTimeFromFiberToRoot(boundaryFiber, retryTime);
if (root !== null) {
ensureRootIsScheduled(root);
schedulePendingInteractions(root, retryTime);
}
}
export function retryDehydratedSuspenseBoundary(boundaryFiber: Fiber) {
const suspenseState: null | SuspenseState = boundaryFiber.memoizedState;
let retryTime = NoWork;
if (suspenseState !== null) {
retryTime = suspenseState.retryTime;
}
retryTimedOutBoundary(boundaryFiber, retryTime);
}
export function resolveRetryWakeable(boundaryFiber: Fiber, wakeable: Wakeable) {
let retryTime = NoWork; // Default
let retryCache: WeakSet<Wakeable> | Set<Wakeable> | null;
if (enableSuspenseServerRenderer) {
switch (boundaryFiber.tag) {
case SuspenseComponent:
retryCache = boundaryFiber.stateNode;
const suspenseState: null | SuspenseState = boundaryFiber.memoizedState;
if (suspenseState !== null) {
retryTime = suspenseState.retryTime;
}
break;
case SuspenseListComponent:
retryCache = boundaryFiber.stateNode;
break;
default:
invariant(
false,
'Pinged unknown suspense boundary type. ' +
'This is probably a bug in React.',
);
}
} else {
retryCache = boundaryFiber.stateNode;
}
if (retryCache !== null) {
// The wakeable resolved, so we no longer need to memoize, because it will
// never be thrown again.
retryCache.delete(wakeable);
}
retryTimedOutBoundary(boundaryFiber, retryTime);
}
// Computes the next Just Noticeable Difference (JND) boundary.
// The theory is that a person can't tell the difference between small differences in time.
// Therefore, if we wait a bit longer than necessary that won't translate to a noticeable
// difference in the experience. However, waiting for longer might mean that we can avoid
// showing an intermediate loading state. The longer we have already waited, the harder it
// is to tell small differences in time. Therefore, the longer we've already waited,
// the longer we can wait additionally. At some point we have to give up though.
// We pick a train model where the next boundary commits at a consistent schedule.
// These particular numbers are vague estimates. We expect to adjust them based on research.
function jnd(timeElapsed: number) {
return timeElapsed < 120
? 120
: timeElapsed < 480
? 480
: timeElapsed < 1080
? 1080
: timeElapsed < 1920
? 1920
: timeElapsed < 3000
? 3000
: timeElapsed < 4320
? 4320
: ceil(timeElapsed / 1960) * 1960;
}
function computeMsUntilSuspenseLoadingDelay(
mostRecentEventTime: number,
suspenseConfig: SuspenseConfig,
) {
const busyMinDurationMs = (suspenseConfig.busyMinDurationMs: any) | 0;
if (busyMinDurationMs <= 0) {
return 0;
}
const busyDelayMs = (suspenseConfig.busyDelayMs: any) | 0;
// Compute the time until this render pass would expire.
const currentTimeMs: number = now();
const eventTimeMs: number = mostRecentEventTime;
const timeElapsed = currentTimeMs - eventTimeMs;
if (timeElapsed <= busyDelayMs) {
// If we haven't yet waited longer than the initial delay, we don't
// have to wait any additional time.
return 0;
}
const msUntilTimeout = busyDelayMs + busyMinDurationMs - timeElapsed;
// This is the value that is passed to `setTimeout`.
return msUntilTimeout;
}
function checkForNestedUpdates() {
if (nestedUpdateCount > NESTED_UPDATE_LIMIT) {
nestedUpdateCount = 0;
rootWithNestedUpdates = null;
invariant(
false,
'Maximum update depth exceeded. This can happen when a component ' +
'repeatedly calls setState inside componentWillUpdate or ' +
'componentDidUpdate. React limits the number of nested updates to ' +
'prevent infinite loops.',
);
}
if (__DEV__) {
if (nestedPassiveUpdateCount > NESTED_PASSIVE_UPDATE_LIMIT) {
nestedPassiveUpdateCount = 0;
console.error(
'Maximum update depth exceeded. This can happen when a component ' +
"calls setState inside useEffect, but useEffect either doesn't " +
'have a dependency array, or one of the dependencies changes on ' +
'every render.',
);
}
}
}
function flushRenderPhaseStrictModeWarningsInDEV() {
if (__DEV__) {
ReactStrictModeWarnings.flushLegacyContextWarning();
if (warnAboutDeprecatedLifecycles) {
ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings();
}
}
}
let didWarnStateUpdateForUnmountedComponent: Set<string> | null = null;
function warnAboutUpdateOnUnmountedFiberInDEV(fiber) {
if (__DEV__) {
const tag = fiber.tag;
if (
tag !== HostRoot &&
tag !== ClassComponent &&
tag !== FunctionComponent &&
tag !== ForwardRef &&
tag !== MemoComponent &&
tag !== SimpleMemoComponent &&
tag !== Block
) {
// Only warn for user-defined components, not internal ones like Suspense.
return;
}
if (
deferPassiveEffectCleanupDuringUnmount &&
runAllPassiveEffectDestroysBeforeCreates
) {
// If there are pending passive effects unmounts for this Fiber,
// we can assume that they would have prevented this update.
if ((fiber.effectTag & PassiveUnmountPendingDev) !== NoEffect) {
return;
}
}
// We show the whole stack but dedupe on the top component's name because
// the problematic code almost always lies inside that component.
const componentName = getComponentName(fiber.type) || 'ReactComponent';
if (didWarnStateUpdateForUnmountedComponent !== null) {
if (didWarnStateUpdateForUnmountedComponent.has(componentName)) {
return;
}
didWarnStateUpdateForUnmountedComponent.add(componentName);
} else {
didWarnStateUpdateForUnmountedComponent = new Set([componentName]);
}
if (isFlushingPassiveEffects) {
// Do not warn if we are currently flushing passive effects!
//
// React can't directly detect a memory leak, but there are some clues that warn about one.
// One of these clues is when an unmounted React component tries to update its state.
// For example, if a component forgets to remove an event listener when unmounting,
// that listener may be called later and try to update state,
// at which point React would warn about the potential leak.
//
// Warning signals are the most useful when they're strong.
// (So we should avoid false positive warnings.)
// Updating state from within an effect cleanup function is sometimes a necessary pattern, e.g.:
// 1. Updating an ancestor that a component had registered itself with on mount.
// 2. Resetting state when a component is hidden after going offscreen.
} else {
const previousFiber = ReactCurrentFiberCurrent;
try {
setCurrentDebugFiberInDEV(fiber);
console.error(
"Can't perform a React state update on an unmounted component. This " +
'is a no-op, but it indicates a memory leak in your application. To ' +
'fix, cancel all subscriptions and asynchronous tasks in %s.',
tag === ClassComponent
? 'the componentWillUnmount method'
: 'a useEffect cleanup function',
);
} finally {
if (previousFiber) {
setCurrentDebugFiberInDEV(fiber);
} else {
resetCurrentDebugFiberInDEV();
}
}
}
}
}
let beginWork;
if (__DEV__ && replayFailedUnitOfWorkWithInvokeGuardedCallback) {
const dummyFiber = null;
beginWork = (current, unitOfWork, expirationTime) => {
// If a component throws an error, we replay it again in a synchronously
// dispatched event, so that the debugger will treat it as an uncaught
// error See ReactErrorUtils for more information.
// Before entering the begin phase, copy the work-in-progress onto a dummy
// fiber. If beginWork throws, we'll use this to reset the state.
const originalWorkInProgressCopy = assignFiberPropertiesInDEV(
dummyFiber,
unitOfWork,
);
try {
return originalBeginWork(current, unitOfWork, expirationTime);
} catch (originalError) {
if (
originalError !== null &&
typeof originalError === 'object' &&
typeof originalError.then === 'function'
) {
// Don't replay promises. Treat everything else like an error.
throw originalError;
}
// Keep this code in sync with handleError; any changes here must have
// corresponding changes there.
resetContextDependencies();
resetHooksAfterThrow();
// Don't reset current debug fiber, since we're about to work on the
// same fiber again.
// Unwind the failed stack frame
unwindInterruptedWork(unitOfWork);
// Restore the original properties of the fiber.
assignFiberPropertiesInDEV(unitOfWork, originalWorkInProgressCopy);
if (enableProfilerTimer && unitOfWork.mode & ProfileMode) {
// Reset the profiler timer.
startProfilerTimer(unitOfWork);
}
// Run beginWork again.
invokeGuardedCallback(
null,
originalBeginWork,
null,
current,
unitOfWork,
expirationTime,
);
if (hasCaughtError()) {
const replayError = clearCaughtError();
// `invokeGuardedCallback` sometimes sets an expando `_suppressLogging`.
// Rethrow this error instead of the original one.
throw replayError;
} else {
// This branch is reachable if the render phase is impure.
throw originalError;
}
}
};
} else {
beginWork = originalBeginWork;
}
let didWarnAboutUpdateInRender = false;
let didWarnAboutUpdateInRenderForAnotherComponent;
if (__DEV__) {
didWarnAboutUpdateInRenderForAnotherComponent = new Set();
}
function warnAboutRenderPhaseUpdatesInDEV(fiber) {
if (__DEV__) {
if (
ReactCurrentDebugFiberIsRenderingInDEV &&
(executionContext & RenderContext) !== NoContext &&
!getIsUpdatingOpaqueValueInRenderPhaseInDEV()
) {
switch (fiber.tag) {
case FunctionComponent:
case ForwardRef:
case SimpleMemoComponent: {
const renderingComponentName =
(workInProgress && getComponentName(workInProgress.type)) ||
'Unknown';
// Dedupe by the rendering component because it's the one that needs to be fixed.
const dedupeKey = renderingComponentName;
if (!didWarnAboutUpdateInRenderForAnotherComponent.has(dedupeKey)) {
didWarnAboutUpdateInRenderForAnotherComponent.add(dedupeKey);
const setStateComponentName =
getComponentName(fiber.type) || 'Unknown';
console.error(
'Cannot update a component (`%s`) while rendering a ' +
'different component (`%s`). To locate the bad setState() call inside `%s`, ' +
'follow the stack trace as described in https://fb.me/setstate-in-render',
setStateComponentName,
renderingComponentName,
renderingComponentName,
);
}
break;
}
case ClassComponent: {
if (!didWarnAboutUpdateInRender) {
console.error(
'Cannot update during an existing state transition (such as ' +
'within `render`). Render methods should be a pure ' +
'function of props and state.',
);
didWarnAboutUpdateInRender = true;
}
break;
}
}
}
}
}
// a 'shared' variable that changes when act() opens/closes in tests.
export const IsThisRendererActing = {current: (false: boolean)};
export function warnIfNotScopedWithMatchingAct(fiber: Fiber): void {
if (__DEV__) {
if (
warnsIfNotActing === true &&
IsSomeRendererActing.current === true &&
IsThisRendererActing.current !== true
) {
const previousFiber = ReactCurrentFiberCurrent;
try {
setCurrentDebugFiberInDEV(fiber);
console.error(
"It looks like you're using the wrong act() around your test interactions.\n" +
'Be sure to use the matching version of act() corresponding to your renderer:\n\n' +
'// for react-dom:\n' +
// Break up imports to avoid accidentally parsing them as dependencies.
'import {act} fr' +
"om 'react-dom/test-utils';\n" +
'// ...\n' +
'act(() => ...);\n\n' +
'// for react-test-renderer:\n' +
// Break up imports to avoid accidentally parsing them as dependencies.
'import TestRenderer fr' +
"om react-test-renderer';\n" +
'const {act} = TestRenderer;\n' +
'// ...\n' +
'act(() => ...);',
);
} finally {
if (previousFiber) {
setCurrentDebugFiberInDEV(fiber);
} else {
resetCurrentDebugFiberInDEV();
}
}
}
}
}
export function warnIfNotCurrentlyActingEffectsInDEV(fiber: Fiber): void {
if (__DEV__) {
if (
warnsIfNotActing === true &&
(fiber.mode & StrictMode) !== NoMode &&
IsSomeRendererActing.current === false &&
IsThisRendererActing.current === false
) {
console.error(
'An update to %s ran an effect, but was not wrapped in act(...).\n\n' +
'When testing, code that causes React state updates should be ' +
'wrapped into act(...):\n\n' +
'act(() => {\n' +
' /* fire events that update state */\n' +
'});\n' +
'/* assert on the output */\n\n' +
"This ensures that you're testing the behavior the user would see " +
'in the browser.' +
' Learn more at https://fb.me/react-wrap-tests-with-act',
getComponentName(fiber.type),
);
}
}
}
function warnIfNotCurrentlyActingUpdatesInDEV(fiber: Fiber): void {
if (__DEV__) {
if (
warnsIfNotActing === true &&
executionContext === NoContext &&
IsSomeRendererActing.current === false &&
IsThisRendererActing.current === false
) {
const previousFiber = ReactCurrentFiberCurrent;
try {
setCurrentDebugFiberInDEV(fiber);
console.error(
'An update to %s inside a test was not wrapped in act(...).\n\n' +
'When testing, code that causes React state updates should be ' +
'wrapped into act(...):\n\n' +
'act(() => {\n' +
' /* fire events that update state */\n' +
'});\n' +
'/* assert on the output */\n\n' +
"This ensures that you're testing the behavior the user would see " +
'in the browser.' +
' Learn more at https://fb.me/react-wrap-tests-with-act',
getComponentName(fiber.type),
);
} finally {
if (previousFiber) {
setCurrentDebugFiberInDEV(fiber);
} else {
resetCurrentDebugFiberInDEV();
}
}
}
}
}
export const warnIfNotCurrentlyActingUpdatesInDev = warnIfNotCurrentlyActingUpdatesInDEV;
// In tests, we want to enforce a mocked scheduler.
let didWarnAboutUnmockedScheduler = false;
// TODO Before we release concurrent mode, revisit this and decide whether a mocked
// scheduler is the actual recommendation. The alternative could be a testing build,
// a new lib, or whatever; we dunno just yet. This message is for early adopters
// to get their tests right.
export function warnIfUnmockedScheduler(fiber: Fiber) {
if (__DEV__) {
if (
didWarnAboutUnmockedScheduler === false &&
Scheduler.unstable_flushAllWithoutAsserting === undefined
) {
if (fiber.mode & BlockingMode || fiber.mode & ConcurrentMode) {
didWarnAboutUnmockedScheduler = true;
console.error(
'In Concurrent or Sync modes, the "scheduler" module needs to be mocked ' +
'to guarantee consistent behaviour across tests and browsers. ' +
'For example, with jest: \n' +
// Break up requires to avoid accidentally parsing them as dependencies.
"jest.mock('scheduler', () => require" +
"('scheduler/unstable_mock'));\n\n" +
'For more info, visit https://fb.me/react-mock-scheduler',
);
} else if (warnAboutUnmockedScheduler === true) {
didWarnAboutUnmockedScheduler = true;
console.error(
'Starting from React v17, the "scheduler" module will need to be mocked ' +
'to guarantee consistent behaviour across tests and browsers. ' +
'For example, with jest: \n' +
// Break up requires to avoid accidentally parsing them as dependencies.
"jest.mock('scheduler', () => require" +
"('scheduler/unstable_mock'));\n\n" +
'For more info, visit https://fb.me/react-mock-scheduler',
);
}
}
}
}
function computeThreadID(
root: FiberRoot,
expirationTime: ExpirationTimeOpaque,
) {
// Interaction threads are unique per root and expiration time.
// NOTE: Intentionally unsound cast. All that matters is that it's a number
// and it represents a batch of work. Could make a helper function instead,
// but meh this is fine for now.
return (expirationTime: any) * 1000 + root.interactionThreadID;
}
export function markSpawnedWork(expirationTime: ExpirationTimeOpaque) {
if (!enableSchedulerTracing) {
return;
}
if (spawnedWorkDuringRender === null) {
spawnedWorkDuringRender = [expirationTime];
} else {
spawnedWorkDuringRender.push(expirationTime);
}
}
function scheduleInteractions(
root: FiberRoot,
expirationTime: ExpirationTimeOpaque,
interactions: Set<Interaction>,
) {
if (!enableSchedulerTracing) {
return;
}
if (interactions.size > 0) {
const pendingInteractionMap = root.pendingInteractionMap_new;
const pendingInteractions = pendingInteractionMap.get(expirationTime);
if (pendingInteractions != null) {
interactions.forEach(interaction => {
if (!pendingInteractions.has(interaction)) {
// Update the pending async work count for previously unscheduled interaction.
interaction.__count++;
}
pendingInteractions.add(interaction);
});
} else {
pendingInteractionMap.set(expirationTime, new Set(interactions));
// Update the pending async work count for the current interactions.
interactions.forEach(interaction => {
interaction.__count++;
});
}
const subscriber = __subscriberRef.current;
if (subscriber !== null) {
const threadID = computeThreadID(root, expirationTime);
subscriber.onWorkScheduled(interactions, threadID);
}
}
}
function schedulePendingInteractions(
root: FiberRoot,
expirationTime: ExpirationTimeOpaque,
) {
// This is called when work is scheduled on a root.
// It associates the current interactions with the newly-scheduled expiration.
// They will be restored when that expiration is later committed.
if (!enableSchedulerTracing) {
return;
}
scheduleInteractions(root, expirationTime, __interactionsRef.current);
}
function startWorkOnPendingInteractions(
root: FiberRoot,
expirationTime: ExpirationTimeOpaque,
) {
// This is called when new work is started on a root.
if (!enableSchedulerTracing) {
return;
}
// Determine which interactions this batch of work currently includes, So that
// we can accurately attribute time spent working on it, And so that cascading
// work triggered during the render phase will be associated with it.
const interactions: Set<Interaction> = new Set();
root.pendingInteractionMap_new.forEach(
(scheduledInteractions, scheduledExpirationTime) => {
if (isSameOrHigherPriority(scheduledExpirationTime, expirationTime)) {
scheduledInteractions.forEach(interaction =>
interactions.add(interaction),
);
}
},
);
// Store the current set of interactions on the FiberRoot for a few reasons:
// We can re-use it in hot functions like performConcurrentWorkOnRoot()
// without having to recalculate it. We will also use it in commitWork() to
// pass to any Profiler onRender() hooks. This also provides DevTools with a
// way to access it when the onCommitRoot() hook is called.
root.memoizedInteractions = interactions;
if (interactions.size > 0) {
const subscriber = __subscriberRef.current;
if (subscriber !== null) {
const threadID = computeThreadID(root, expirationTime);
try {
subscriber.onWorkStarted(interactions, threadID);
} catch (error) {
// If the subscriber throws, rethrow it in a separate task
scheduleCallback(ImmediateSchedulerPriority, () => {
throw error;
});
}
}
}
}
function finishPendingInteractions(root, committedExpirationTime) {
if (!enableSchedulerTracing) {
return;
}
const earliestRemainingTimeAfterCommit = root.firstPendingTime_opaque;
let subscriber;
try {
subscriber = __subscriberRef.current;
if (subscriber !== null && root.memoizedInteractions.size > 0) {
const threadID = computeThreadID(root, committedExpirationTime);
subscriber.onWorkStopped(root.memoizedInteractions, threadID);
}
} catch (error) {
// If the subscriber throws, rethrow it in a separate task
scheduleCallback(ImmediateSchedulerPriority, () => {
throw error;
});
} finally {
// Clear completed interactions from the pending Map.
// Unless the render was suspended or cascading work was scheduled,
// In which case– leave pending interactions until the subsequent render.
const pendingInteractionMap = root.pendingInteractionMap_new;
pendingInteractionMap.forEach(
(scheduledInteractions, scheduledExpirationTime) => {
// Only decrement the pending interaction count if we're done.
// If there's still work at the current priority,
// That indicates that we are waiting for suspense data.
if (
!isSameOrHigherPriority(
earliestRemainingTimeAfterCommit,
scheduledExpirationTime,
)
) {
pendingInteractionMap.delete(scheduledExpirationTime);
scheduledInteractions.forEach(interaction => {
interaction.__count--;
if (subscriber !== null && interaction.__count === 0) {
try {
subscriber.onInteractionScheduledWorkCompleted(interaction);
} catch (error) {
// If the subscriber throws, rethrow it in a separate task
scheduleCallback(ImmediateSchedulerPriority, () => {
throw error;
});
}
}
});
}
},
);
}
}
// `act` testing API
//
// TODO: This is mostly a copy-paste from the legacy `act`, which does not have
// access to the same internals that we do here. Some trade offs in the
// implementation no longer make sense.
let isFlushingAct = false;
let isInsideThisAct = false;
// TODO: Yes, this is confusing. See above comment. We'll refactor it.
function shouldForceFlushFallbacksInDEV() {
if (!__DEV__) {
// Never force flush in production. This function should get stripped out.
return false;
}
// `IsThisRendererActing.current` is used by ReactTestUtils version of `act`.
if (IsThisRendererActing.current) {
// `isInsideAct` is only used by the reconciler implementation of `act`.
// We don't want to flush suspense fallbacks until the end.
return !isInsideThisAct;
}
// Flush callbacks at the end.
return isFlushingAct;
}
const flushMockScheduler = Scheduler.unstable_flushAllWithoutAsserting;
const isSchedulerMocked = typeof flushMockScheduler === 'function';
// Returns whether additional work was scheduled. Caller should keep flushing
// until there's no work left.
function flushActWork(): boolean {
if (flushMockScheduler !== undefined) {
const prevIsFlushing = isFlushingAct;
isFlushingAct = true;
try {
return flushMockScheduler();
} finally {
isFlushingAct = prevIsFlushing;
}
} else {
// No mock scheduler available. However, the only type of pending work is
// passive effects, which we control. So we can flush that.
const prevIsFlushing = isFlushingAct;
isFlushingAct = true;
try {
let didFlushWork = false;
while (flushPassiveEffects()) {
didFlushWork = true;
}
return didFlushWork;
} finally {
isFlushingAct = prevIsFlushing;
}
}
}
function flushWorkAndMicroTasks(onDone: (err: ?Error) => void) {
try {
flushActWork();
enqueueTask(() => {
if (flushActWork()) {
flushWorkAndMicroTasks(onDone);
} else {
onDone();
}
});
} catch (err) {
onDone(err);
}
}
// we track the 'depth' of the act() calls with this counter,
// so we can tell if any async act() calls try to run in parallel.
let actingUpdatesScopeDepth = 0;
let didWarnAboutUsingActInProd = false;
export function act(callback: () => Thenable<mixed>): Thenable<void> {
if (!__DEV__) {
if (didWarnAboutUsingActInProd === false) {
didWarnAboutUsingActInProd = true;
// eslint-disable-next-line react-internal/no-production-logging
console.error(
'act(...) is not supported in production builds of React, and might not behave as expected.',
);
}
}
const previousActingUpdatesScopeDepth = actingUpdatesScopeDepth;
actingUpdatesScopeDepth++;
const previousIsSomeRendererActing = IsSomeRendererActing.current;
const previousIsThisRendererActing = IsThisRendererActing.current;
const previousIsInsideThisAct = isInsideThisAct;
IsSomeRendererActing.current = true;
IsThisRendererActing.current = true;
isInsideThisAct = true;
function onDone() {
actingUpdatesScopeDepth--;
IsSomeRendererActing.current = previousIsSomeRendererActing;
IsThisRendererActing.current = previousIsThisRendererActing;
isInsideThisAct = previousIsInsideThisAct;
if (__DEV__) {
if (actingUpdatesScopeDepth > previousActingUpdatesScopeDepth) {
// if it's _less than_ previousActingUpdatesScopeDepth, then we can assume the 'other' one has warned
console.error(
'You seem to have overlapping act() calls, this is not supported. ' +
'Be sure to await previous act() calls before making a new one. ',
);
}
}
}
let result;
try {
result = batchedUpdates(callback);
} catch (error) {
// on sync errors, we still want to 'cleanup' and decrement actingUpdatesScopeDepth
onDone();
throw error;
}
if (
result !== null &&
typeof result === 'object' &&
typeof result.then === 'function'
) {
// setup a boolean that gets set to true only
// once this act() call is await-ed
let called = false;
if (__DEV__) {
if (typeof Promise !== 'undefined') {
//eslint-disable-next-line no-undef
Promise.resolve()
.then(() => {})
.then(() => {
if (called === false) {
console.error(
'You called act(async () => ...) without await. ' +
'This could lead to unexpected testing behaviour, interleaving multiple act ' +
'calls and mixing their scopes. You should - await act(async () => ...);',
);
}
});
}
}
// in the async case, the returned thenable runs the callback, flushes
// effects and microtasks in a loop until flushPassiveEffects() === false,
// and cleans up
return {
then(resolve, reject) {
called = true;
result.then(
() => {
if (
actingUpdatesScopeDepth > 1 ||
(isSchedulerMocked === true &&
previousIsSomeRendererActing === true)
) {
onDone();
resolve();
return;
}
// we're about to exit the act() scope,
// now's the time to flush tasks/effects
flushWorkAndMicroTasks((err: ?Error) => {
onDone();
if (err) {
reject(err);
} else {
resolve();
}
});
},
err => {
onDone();
reject(err);
},
);
},
};
} else {
if (__DEV__) {
if (result !== undefined) {
console.error(
'The callback passed to act(...) function ' +
'must return undefined, or a Promise. You returned %s',
result,
);
}
}
// flush effects until none remain, and cleanup
try {
if (
actingUpdatesScopeDepth === 1 &&
(isSchedulerMocked === false || previousIsSomeRendererActing === false)
) {
// we're about to exit the act() scope,
// now's the time to flush effects
flushActWork();
}
onDone();
} catch (err) {
onDone();
throw err;
}
// in the sync case, the returned thenable only warns *if* await-ed
return {
then(resolve) {
if (__DEV__) {
console.error(
'Do not await the result of calling act(...) with sync logic, it is not a Promise.',
);
}
resolve();
},
};
}
}
|
module.exports = async (Bot, guild) => {
// Get the default config settings
const defSet = Bot.config.defaultSettings;
// Make sure it's not a server outage that's causing it to show as leaving/ re-joining
if (!guild.available) return;
const exists = await Bot.hasGuildConf(guild.id);
if (!exists) {
// Adding a new row to the DB
Bot.database.models.settings.create({
guildID: guild.id,
adminRole: defSet.adminRole,
enableWelcome: defSet.enableWelcome,
welcomeMessage: defSet.welcomeMessage,
useEmbeds: defSet.useEmbeds,
timezone: defSet.timezone,
announceChan: defSet.announceChan,
useEventPages: defSet.useEventPages,
language: defSet.language
})
.then(() => {
// Log that it joined another guild
Bot.logger.log(`[GuildCreate] I joined ${guild.name}(${guild.id})`);
})
.catch(error => { Bot.logger.error(error, guild.id); });
} else {
// Log that it joined another guild (Again)
// Bot.log("GuildCreate", `I re-joined ${guild.name}(${guild.id})`, {color: Bot.constants.colors.green});
}
};
|
'use strict';
define(function(require) {
var angular = require('angular');
var angularSlider = require('angularSlider');
var angularXEditable = require('angularXEditable');
var displayServices = require('common/services/displayServices');
var interfaceServices = require('robots/services/interfaceServices');
var robotDirectives = require('robots/directives');
var filters = require('common/filters');
var actionModels = require('actions/models');
var ActionEditor = require('./directives/ActionEditor');
var GroupEditor = require('./directives/GroupEditor');
var PoseEditor = require('./directives/PoseEditor');
var JointEditor = require('./directives/JointEditor');
var SequenceEditor = require('./directives/SequenceEditor');
var SoundEditor = require('./directives/SoundEditor');
var moduleName = 'kasparGUI.actions.directives';
var dependancies = [
displayServices,
angularSlider,
interfaceServices,
filters,
actionModels,
robotDirectives,
angularXEditable,
];
var module = angular.module(moduleName, dependancies)
.directive('actionEditor', ActionEditor)
.directive('groupactionEditor', GroupEditor)
.directive('poseactionEditor', PoseEditor)
.directive('sequenceactionEditor', SequenceEditor)
.directive('soundactionEditor', SoundEditor)
.directive('jointEditor', JointEditor);
module.run(function(editableOptions) {editableOptions.theme = 'bs3'});
return moduleName;
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.