code stringlengths 2 1.05M |
|---|
version https://git-lfs.github.com/spec/v1
oid sha256:cf52ae3662d046b0cc6d4fdcbfd0f942a49caca8ac602306c33cb37548741760
size 172
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Monitor = function () {
function Monitor() {
var brandName = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'DELL';
var resolution = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '720x1400';
_classCallCheck(this, Monitor);
this.brandName = brandName;
this.resolution = resolution;
}
_createClass(Monitor, [{
key: 'printBrandName',
value: function printBrandName() {
console.log(this.brandName);
}
}, {
key: 'printResolution',
value: function printResolution() {
console.log(this.resolution);
}
}]);
return Monitor;
}();
;
exports.default = Monitor;
|
//@flow
export type RecordOf<Values: Object> = Values;
function f<X: Object>(x: X): X {
var o = x;
return o;
}
var y = f();
|
// compress a list of things by frequency
const topk = function(list) {
let counts = {}
list.forEach(a => {
counts[a] = counts[a] || 0
counts[a] += 1
})
let arr = Object.keys(counts)
arr = arr.sort((a, b) => {
if (counts[a] > counts[b]) {
return -1
} else {
return 1
}
})
// arr = arr.filter(a => counts[a] > 1)
return arr.map(a => [a, counts[a]])
}
module.exports = topk
|
// a force directed chart visualisation
$.fn.holder.display.chart = function(obj) {
var options = obj.holder.options;
$.fn.holder.display.chart.nodesLinks(options.response,options);
if ( !$('div.'+options.class+'.chart').length ) {
obj.append('<div class="' + options.class + ' chart" style="height:100%;"></div>');
}
if ($.fn.holder.display.chart.first) {
$.fn.holder.display.chart.first = false;
var svg = d3.select("." + options.class + ".chart").append("svg").attr("width", $("." + options.class + ".chart").width()).attr("height", $("." + options.class + ".chart").height()).call(d3.zoom().on("zoom", function() { g.attr( "transform", d3.event.transform ); }));
var g = svg.append("g");
$.fn.holder.display.chart.link = g.append("g").selectAll();
$.fn.holder.display.chart.node = g.append("g").selectAll();
$.fn.holder.display.chart.simulation = d3.forceSimulation($.fn.holder.display.chart.nodes)
//.force("charge", d3.forceManyBody().strength(-1 * $("." + options.class + ".chart").width()/12)) // change 12 to smaller number to start at closer aspect to vid
.force("link", d3.forceLink($.fn.holder.display.chart.links).distance(-50 + $("." + options.class + ".chart").width()/2))
//.force("collide",d3.forceCollide().radius(function(d) { return 300; }) )
.force("center", d3.forceCenter(1200/*$("." + options.class + ".chart").width() / 2*/, $("." + options.class + ".chart").height() / 2))
//.force("x", d3.forceX())
//.force("y", d3.forceY())
.on("tick", $.fn.holder.display.chart.tick);
}
function dragstarted(d) {
if (!d3.event.active) $.fn.holder.display.chart.simulation.alphaTarget(0.3).restart();
d.fx = d.x;
d.fy = d.y;
}
function dragged(d) {
d.fx = d3.event.x;
d.fy = d3.event.y;
}
function dragended(d) {
if (!d3.event.active) $.fn.holder.display.chart.simulation.alphaTarget(0);
d.fx = null;
d.fy = null;
}
function chart() {
$.fn.holder.display.chart.node = $.fn.holder.display.chart.node.data($.fn.holder.display.chart.nodes);
$.fn.holder.display.chart.node = $.fn.holder.display.chart.node.enter()
.append("g")
//.on("mouseover", function(d) { $.fn.holder.display.chart.hover(d,true); })
//.on("mouseout", function(d) { $.fn.holder.display.chart.hover(d,false) })
//.on("click", function(d) { $.fn.holder.display.chart.click(d); })
.call(d3.drag()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended))
.merge($.fn.holder.display.chart.node);
$.fn.holder.display.chart.node
.append("foreignObject")
.attr("x",-100).attr("y",-100).attr("class","slide")
.html(function(d) { return d.value; });
$.fn.holder.display.chart.node.exit().remove();
$.fn.holder.display.chart.link = $.fn.holder.display.chart.link.data($.fn.holder.display.chart.links);
$.fn.holder.display.chart.link.exit().remove();
$.fn.holder.display.chart.link = $.fn.holder.display.chart.link.enter().append("line").merge($.fn.holder.display.chart.link);
$.fn.holder.display.chart.link
.attr("class","link")
.attr("stroke",function(d) { return '#666'; })
.attr("stroke-width", 0.8);
$.fn.holder.display.chart.simulation.nodes($.fn.holder.display.chart.nodes);
$.fn.holder.display.chart.simulation.force("link").links($.fn.holder.display.chart.links);
$.fn.holder.display.chart.simulation.alpha(1).restart();
$.fn.holder.display.chart.tick()
}
chart();
}
$.fn.holder.display.chart.simulation;
$.fn.holder.display.chart.first = true;
$.fn.holder.display.chart.nodes = [];
$.fn.holder.display.chart.links = [];
$.fn.holder.display.chart.position = function(d,y,t) {
if (y !== undefined && y !== 'x') {
y = 'y';
} else {
y = 'x';
}
if (t === undefined && d.source !== undefined && d.source[y] !== undefined) {
return d.source[y];
} else if (t && d.target !== undefined && d.target[y] !== undefined) {
return d.target[y];
} else {
return d[y];
}
}
$.fn.holder.display.chart.tick = function() {
$.fn.holder.display.chart.node.attr("transform", function(d) { return "translate(" + [d.x, d.y] + ")"; });
$.fn.holder.display.chart.link
.attr("x1", function(d) { return $.fn.holder.display.chart.position(d); })
.attr("y1", function(d) { return $.fn.holder.display.chart.position(d,'y'); })
.attr("x2", function(d) { return $.fn.holder.display.chart.position(d,'x',true); })
.attr("y2", function(d) { return $.fn.holder.display.chart.position(d,'y',true); });
}
|
var CopyWebpackPlugin = require('copy-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
context: __dirname + '/src/js',
devtool: 'source-map',
entry: './entry.js',
output: {
path: __dirname + '/dist',
filename: 'bundle.js'
},
plugins: [
new CopyWebpackPlugin([
{ from: '../index.html', to: 'index.html' }
]),
new ExtractTextPlugin('style.css')
],
module: {
loaders: [
{ test: /\.scss$/, loader: ExtractTextPlugin.extract('style', 'css?sourceMap!autoprefixer?browsers=last 2 versions!sass') },
{ test: /\.js$/, exclude: /node_modules/, loader: 'babel!eslint'} // Automatically generates source maps without the sourceMaps config
]
},
eslint: {
failOnWarning: false,
failOnError: false
}
};
|
var Alias = require('./alias');
(function () {
module.exports.register = function (Handlebars, options) {
/*
* Loop helper.
*
* @return easy for-loop
*/
Handlebars.registerHelper('times', function (n, block) {
var content = '';
for (var i = 0; i < n; ++i)
content += block.fn(i);
return content;
});
Alias.create('repeat', Handlebars.helpers.times, Handlebars);
/*
* Loop helper.
*
* @return advanced for-loop
*/
Handlebars.registerHelper('for', function (from, to, incr, block) {
var content = '';
for (var i = from; i < to; i += incr)
content += block.fn(i);
return content;
});
};
}).call(this);
|
var triggerEvent = function (eventType, selector, opts = {}) {
let element = (typeof selector === 'string') ? document.querySelector(selector) : selector;
return new Promise(resolve => {
if (opts.position) {
const { x,y } = (typeof selector === 'string') ? element.getBoundingClientRect() : { x: 0, y: 0 };
if (eventType.indexOf('drag') !== -1) {
element.dispatchEvent(new DragEvent(eventType, {
bubbles: true,
cancelable: true,
clientX: x + opts.position.x,
clientY: y + opts.position.y
}));
} else {
element.dispatchEvent(new MouseEvent(eventType, {
bubbles: true,
cancelable: true,
clientX: x + opts.position.x,
clientY: y + opts.position.y
}));
}
} else {
element.dispatchEvent(new MouseEvent(eventType, {
bubbles: true,
cancelable: true
}));
}
setTimeout(resolve, 10);
});
};
var triggerEventSync = function (eventType, selector, opts = {}) {
let element = document.querySelector(selector);
if (opts.position) {
const { x,y } = element.getBoundingClientRect();
element.dispatchEvent(new MouseEvent(eventType, {
bubbles: true,
cancelable: true,
clientX: x + opts.position.x,
clientY: y + opts.position.y
}));
} else {
element.dispatchEvent(new Event(eventType, {
bubbles: true,
cancelable: true
}));
}
};
var waitFor = async function (timeout) {
const promise = new Promise(resolve => {
setTimeout(resolve, timeout);
});
return await promise;
};
(function (window) {
try {
new MouseEvent('test');
return false; // No need to polyfill
} catch (e) {
// Need to polyfill - fall through
}
// Polyfills DOM4 MouseEvent
var MouseEventPolyfill = function (eventType, params) {
params = params || { bubbles: false, cancelable: false };
var mouseEvent = document.createEvent('MouseEvent');
mouseEvent.initMouseEvent(eventType,
params.bubbles,
params.cancelable,
window,
0,
params.screenX || 0,
params.screenY || 0,
params.clientX || 0,
params.clientY || 0,
params.ctrlKey || false,
params.altKey || false,
params.shiftKey || false,
params.metaKey || false,
params.button || 0,
params.relatedTarget || null
);
return mouseEvent;
}
MouseEventPolyfill.prototype = Event.prototype;
window.MouseEvent = MouseEventPolyfill;
})(window);
|
//>>built
define({invalidMessage:"Mus\u00edte vybra\u0165 aspo\u0148 jednu polo\u017eku.",multiSelectLabelText:"Vybrat\u00e9 polo\u017eky: {num}"}); |
/*!
* harbor v2.16.0: A free WordPress theme for animal and pet rescue organizations
* (c) 2016 Chris Ferdinandi
* MIT License
* https://github.com/cferdinandi/harbor-wp-theme
* Open Source Credits: https://github.com/ftlabs/fastclick, https://github.com/toddmotto/fluidvids, http://photoswipe.com, http://masonry.desandro.com, http://imagesloaded.desandro.com
*/
(function (root, factory) {
if ( typeof define === 'function' && define.amd ) {
define([], factory(root));
} else if ( typeof exports === 'object' ) {
module.exports = factory(root);
} else {
root.petfinderSort = factory(root);
}
})(typeof global !== 'undefined' ? global : this.window || this.global, function (root) {
'use strict';
//
// Variables
//
var petfinderSort = {}; // Object for public APIs
var supports = 'querySelector' in document && 'addEventListener' in root && 'classList' in document.createElement('_'); // Feature test
var sessionID = 'petfinderSortStates'; // sessionStorage ID
var settings, eventTimeout, states, pets, sortBreeds, sortAttributes, sortToggles, hideAll;
// Default settings
var defaults = {
initClass: 'js-petfinder-sort',
callback: function () {}
};
//
// Methods
//
/**
* A simple forEach() implementation for Arrays, Objects and NodeLists.
* @private
* @author Todd Motto
* @link https://github.com/toddmotto/foreach
* @param {Array|Object|NodeList} collection Collection of items to iterate
* @param {Function} callback Callback function for each iteration
* @param {Array|Object|NodeList} scope Object/NodeList/Array that forEach is iterating over (aka `this`)
*/
var forEach = function ( collection, callback, scope ) {
if ( Object.prototype.toString.call( collection ) === '[object Object]' ) {
for ( var prop in collection ) {
if ( Object.prototype.hasOwnProperty.call( collection, prop ) ) {
callback.call( scope, collection[prop], prop, collection );
}
}
} else {
for ( var i = 0, len = collection.length; i < len; i++ ) {
callback.call( scope, collection[i], i, collection );
}
}
};
/**
* Merge two or more objects. Returns a new object.
* @private
* @param {Boolean} deep If true, do a deep (or recursive) merge [optional]
* @param {Object} objects The objects to merge together
* @returns {Object} Merged values of defaults and options
*/
var extend = function () {
// Variables
var extended = {};
var deep = false;
var i = 0;
var length = arguments.length;
// Check if a deep merge
if ( Object.prototype.toString.call( arguments[0] ) === '[object Boolean]' ) {
deep = arguments[0];
i++;
}
// Merge the object into the extended object
var merge = function (obj) {
for ( var prop in obj ) {
if ( Object.prototype.hasOwnProperty.call( obj, prop ) ) {
// If deep merge and property is an object, merge properties
if ( deep && Object.prototype.toString.call(obj[prop]) === '[object Object]' ) {
extended[prop] = extend( true, extended[prop], obj[prop] );
} else {
extended[prop] = obj[prop];
}
}
}
};
// Loop through each object and conduct a merge
for ( ; i < length; i++ ) {
var obj = arguments[i];
merge(obj);
}
return extended;
};
/**
* Get the closest matching element up the DOM tree.
* @private
* @param {Element} elem Starting element
* @param {String} selector Selector to match against (class, ID, data attribute, or tag)
* @return {Boolean|Element} Returns null if not match found
*/
var getClosest = function ( elem, selector ) {
// Variables
var firstChar = selector.charAt(0);
var attribute, value;
// If selector is a data attribute, split attribute from value
if ( firstChar === '[' ) {
selector = selector.substr(1, selector.length - 2);
attribute = selector.split( '=' );
if ( attribute.length > 1 ) {
value = true;
attribute[1] = attribute[1].replace( /"/g, '' ).replace( /'/g, '' );
}
}
// Get closest match
for ( ; elem && elem !== document; elem = elem.parentNode ) {
// If selector is a class
if ( firstChar === '.' ) {
if ( elem.classList.contains( selector.substr(1) ) ) {
return elem;
}
}
// If selector is an ID
if ( firstChar === '#' ) {
if ( elem.id === selector.substr(1) ) {
return elem;
}
}
// If selector is a data attribute
if ( firstChar === '[' ) {
if ( elem.hasAttribute( attribute[0] ) ) {
if ( value ) {
if ( elem.getAttribute( attribute[0] ) === attribute[1] ) {
return elem;
}
} else {
return elem;
}
}
}
// If selector is a tag
if ( elem.tagName.toLowerCase() === selector ) {
return elem;
}
}
return null;
};
/**
* Save the current state of a checkbox
* @private
* @param {Node} checkbox The checkbox
*/
var saveCheckedState = function ( checkbox ) {
// If sessionStorage isn't supported, end method
if ( !root.sessionStorage ) return;
// Get checkbox target
var name = checkbox.getAttribute( 'data-petfinder-sort-target' );
// If checkbox isn't checked, save state in sessionStorage
if ( checkbox.checked === false ) {
states[name] = 'unchecked';
sessionStorage.setItem( sessionID, JSON.stringify(states) );
settings.callback( checkbox ); // Callback
return;
}
// If checkbox is checked, remove state from sessionStorage
delete states[name];
sessionStorage.setItem( sessionID, JSON.stringify(states) );
settings.callback( checkbox ); // Callback
};
/**
* Set checkbox state based on sessionStorage data
* @private
* @param {Node} checkbox The checkbox
*/
var setCheckedState = function ( checkbox ) {
// If sessionStorage isn't supported, end method
if ( !root.sessionStorage ) return;
// Get checkbox target and sessionStorage data
var name = checkbox.getAttribute( 'data-petfinder-sort-target' );
// If checkbox is in sessionStorage, update it's state
if ( states && states[name] && states[name] === 'unchecked' ) {
checkbox.checked = false;
}
};
/**
* Get state of all checkboxes
* @private
*/
var getCheckedStates = function () {
forEach(sortBreeds, function (checkbox) { setCheckedState( checkbox ); });
forEach(sortAttributes, function (checkbox) { setCheckedState( checkbox ); });
forEach(sortToggles, function (checkbox) { setCheckedState( checkbox ); });
};
/**
* Show or hide a node in the DOM
* @private
* @param {Node} elem The node to show or hide
* @param {Boolean} hide If true, hide node. Otherwise show.
*/
var toggleVisibility = function ( elem, hide ) {
if ( hide ) {
elem.style.display = 'none';
elem.style.visibility = 'hidden';
return;
}
elem.style.display = 'block';
elem.style.visibility = 'visible';
};
/**
* Toggle all checkboxes in a category
* @private
* @param {Node} checkbox The checkbox
*/
var toggleAll = function ( checkbox ) {
// Get checkbox targets
var targets = document.querySelectorAll( checkbox.getAttribute( 'data-petfinder-sort-target' ) );
// If checkbox is checked, select all checkboxes
if ( checkbox.checked === true ) {
forEach(targets, function (target) {
target.checked = true;
saveCheckedState( target );
});
return;
}
// If checkbox is unchecked, unselect all checkboxes
forEach(targets, function (target) {
target.checked = false;
saveCheckedState( target );
});
};
/**
* Sort pets based on checkbox selections
* @private
*/
var sortPets = function () {
// Hide or show all pets
forEach(pets, function (pet) {
// If breed sorting is available, hide all pets by default
if ( hideAll ) {
toggleVisibility( pet, true );
return;
}
// Otherwise, show all pets by default
toggleVisibility( pet );
});
// If breed is checked, show matching pets
forEach(sortBreeds, function (checkbox) {
if ( checkbox.checked === true ) {
var targets = document.querySelectorAll( checkbox.getAttribute( 'data-petfinder-sort-target' ) );
forEach(targets, function (target) {
toggleVisibility( target );
});
}
});
// If checkbox is unchecked, hide matching pets
forEach(sortAttributes, function (checkbox) {
if ( checkbox.checked === false ) {
var targets = document.querySelectorAll( checkbox.getAttribute( 'data-petfinder-sort-target' ) );
forEach(targets, function (target) {
toggleVisibility( target, true );
});
}
});
};
/**
* Show all pets and check all checkboxes
* @private
*/
var resetPets = function () {
// Show all pets
forEach(pets, function (pet) {
toggleVisibility( pet );
});
// Check all breed checkboxes
forEach(sortBreeds, function (checkbox) {
checkbox.checked = true;
});
// Check all attribute checkboxes
forEach(sortAttributes, function (checkbox) {
checkbox.checked = true;
});
// Check all toggle checkboxes
forEach(sortToggles, function (checkbox) {
checkbox.checked = true;
});
};
/**
* Handle click events
* @private
* @param {Event} event The click event
*/
var eventHandler = function (event) {
// Get clicked object
var toggle = event.target;
var checkbox = getClosest(toggle, '[data-petfinder-sort]');
// If a sort checkbox, sort pets
if ( checkbox ) {
// Save checkbox state
saveCheckedState( checkbox );
// If a toggle checkbox, toggle all
if ( checkbox.getAttribute( 'data-petfinder-sort' ) === 'toggle' ) {
toggleAll( checkbox );
}
// Sort pets
sortPets();
}
};
/**
* Destroy the current initialization.
* @public
*/
petfinderSort.destroy = function () {
// If plugin isn't already initialized, stop
if ( !settings ) return;
// Remove init class for conditional CSS
document.documentElement.classList.remove( settings.initClass );
resetPets();
// Remove event listeners
document.removeEventListener('click', eventHandler, false);
// Reset variables
states = null;
settings = null;
eventTimeout = null;
pets = null;
sortBreeds = null;
sortAttributes = null;
sortToggles = null;
hideAll = null;
};
/**
* Initialize Plugin
* @public
* @param {Object} options User settings
*/
petfinderSort.init = function ( options ) {
// feature test
if ( !supports ) return;
// Destroy any existing initializations
petfinderSort.destroy();
// Variables
settings = extend( true, defaults, options || {} ); // Merge user options with defaults
pets = document.querySelectorAll( '.pf-pet' );
sortBreeds = document.querySelectorAll( '[data-petfinder-sort="breeds"]' );
sortAttributes = document.querySelectorAll( '[data-petfinder-sort="attributes"]' );
sortToggles = document.querySelectorAll( '[data-petfinder-sort="toggle"]' );
hideAll = sortBreeds.length === 0 ? false : true;
if ( root.sessionStorage ) {
states = sessionStorage.getItem( sessionID ) ? JSON.parse( sessionStorage.getItem( sessionID ) ) : {};
}
states = root.sessionStorage ? JSON.parse( sessionStorage.getItem( sessionID ) ) || {} : {};
// Add class to HTML element to activate conditional CSS
document.documentElement.classList.add( settings.initClass );
// On page load, set checkbox states and run sort
getCheckedStates();
sortPets();
// Listen for click events
document.addEventListener('click', eventHandler, false);
};
//
// Public APIs
//
return petfinderSort;
});
petfinderSort.init(); |
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
uglify: {
options: {
banner: '/*! <%= pkg.name %> <%= pkg.version %> */\n'
},
'ng-flow': {
src: ['dist/ng-flow.js'],
dest: 'dist/ng-flow.min.js'
},
'ng-flow-standalone': {
src: ['dist/ng-flow-standalone.js'],
dest: 'dist/ng-flow-standalone.min.js'
}
},
concat: {
flow: {
files: {
'dist/ng-flow.js': [
'src/provider.js',
'src/directives/init.js',
'src/directives/*.js',
'src/*.js'
],
'dist/ng-flow-standalone.js': [
'bower_components/flow.js/dist/flow.js',
'src/provider.js',
'src/directives/init.js',
'src/directives/*.js',
'src/*.js'
]
}
}
},
karma: {
options: {
configFile: 'karma.conf.js'
},
watch: {
},
continuous: {
singleRun: true
}
},
clean: {
release: ["dist/ng*"]
},
bump: {
options: {
files: ['package.json', 'bower.json'],
updateConfigs: ['pkg'],
commit: true,
commitMessage: 'Release v%VERSION%',
commitFiles: ['-a'], // '-a' for all files
createTag: true,
tagName: 'v%VERSION%',
tagMessage: 'Version %VERSION%',
push: true,
pushTo: 'origin',
gitDescribeOptions: '--tags --always --abbrev=1 --dirty=-d' // options to use with '$ git describe'
}
}
});
// Loading dependencies
for (var key in grunt.file.readJSON("package.json").devDependencies) {
if (key !== "grunt" && key.indexOf("grunt") === 0) grunt.loadNpmTasks(key);
}
grunt.registerTask('build', ['concat', 'uglify']);
grunt.registerTask('test', ['karma:continuous']);
grunt.registerTask('watch', ['karma:watch']);
grunt.registerTask('release', function(type) {
type = type ? type : 'patch';
grunt.task.run('bump-only:' + type);
grunt.task.run('clean', 'build');
grunt.task.run('bump-commit');
});
}; |
export const closeNoti = {
type: 'CLOSE_NOTI',
};
export const showNoti = (message, action) => {
return {
type: 'SHOW_NOTI',
message: message,
action: action
}
}
|
var express = require('express'),
path = require('path'),
http = require('http'),
fs = require('fs'),
parser = require('body-parser'),
template = require('art-template'),
compression = require('compression'),
utils = require('./utils/utils.js'),
widget = require('./connect/widget');
var logger = require('tracer').console({
transport: function (data) {
fs.appendFile('./file.log', data.output + '\n', (err) => {
if (err) throw err;
});
}
});
//node v8 升级,defer函数被废弃,为此打补丁
if (!Promise.defer) {
Promise.defer = function () {
var deferred = {};
deferred.resolve = null;
deferred.reject = null;
deferred.promise = new Promise(function (resolve, reject) {
this.resolve = resolve;
this.reject = reject;
}.bind(deferred));
Object.freeze(deferred);
return deferred;
}
}
var app = express();
app.set('port', 3000);
app.set('x-powered-by', false);
app.set('view engine', 'html');
fs.readdirSync('./themes').forEach(function (e) {
app.set('views', path.join(__dirname, 'themes', e, 'skins'));
});
template.config('extname', '.html');
//helper
template.helper('dateFormat', utils.dateFormat);
template.helper('subString', utils.subString);
app.engine('.html', template.__express);
//parse json
app.use(parser.json());
//parse request body
app.use(parser.urlencoded({
extended: false
}));
//gzip middleware
app.use(compression({
level: 9
}));
//set static file path
app.use(express.static(path.join(__dirname, 'themes'), {
maxAge: 24 * 60 * 60 * 1000
}));
//widget middleware init
app.use(widget.__init());
//load routes
fs.readdirSync('./routes').forEach(function (e) {
e = e.replace('.js', '');
app.use('/' + e, require('./routes/' + e));
}, this);
//widget middleware resolve function
app.use(widget.__middleware());
//handle exceptions
app.use(function (err, req, res, next) {
console.error(err.stack);
res.status(err.status || 500);
res.render('error.html', {
message: err.message
});
});
//listen app to port
app.listen(app.get('port'), function () {
console.log('安徽广播电视大学网站 服务启动于 %s 端口', app.get('port'));
logger.error('安徽广播电视大学网站 服务启动于 %s 端口', app.get('port'));
});
module.exports = app; |
var get = Ember.get, set = Ember.set, isEqual = Ember.isEqual;
/**
Merge strategy that merges on a per-field basis.
Fields which have been editted by both parties will
default to "ours".
*/
Ep.PerField = Ep.MergeStrategy.extend({
init: function() {
this.cache = Ep.ModelSet.create();
},
merge: function(ours, ancestor, theirs) {
if(this.cache.contains(ours)) return ours;
this.cache.addObject(theirs);
ours.beginPropertyChanges();
this.mergeAttributes(ours, ancestor, theirs);
this.mergeRelationships(ours, ancestor, theirs);
ours.endPropertyChanges();
return ours;
},
mergeAttributes: function(ours, ancestor, theirs) {
ours.eachAttribute(function(name, meta) {
var oursValue = get(ours, name);
var theirsValue = get(theirs, name);
var originalValue = get(ancestor, name);
if(oursValue === theirsValue) return;
// keep "ours", only merge if ours hasn't changed
if(oursValue === originalValue) {
set(ours, name, theirsValue);
}
});
},
mergeRelationships: function(ours, ancestor, theirs) {
var session = get(this, 'session');
ours.eachRelationship(function(name, relationship) {
if(relationship.kind === 'belongsTo') {
var oursValue = get(ours, name);
var theirsValue = get(theirs, name);
var originalValue = get(ancestor, name);
// keep "ours", only merge if ours hasn't changed
if(isEqual(oursValue, originalValue)) {
set(ours, name, theirsValue);
}
} else if(relationship.kind === 'hasMany') {
var theirChildren = get(theirs, name);
var ourChildren = get(ours, name);
var originalChildren = get(ancestor, name);
if(isEqual(ourChildren, originalChildren)) {
// if we haven't modified the collection locally then
// we replace
var existing = Ep.ModelSet.create();
existing.addObjects(ourChildren);
theirChildren.forEach(function(model) {
if(existing.contains(model)) {
existing.remove(model);
} else {
ourChildren.pushObject(model);
}
}, this);
ourChildren.removeObjects(existing);
}
}
}, this);
}
});
|
$(document).on('ajaxComplete ready', function () {
// Initialize WYSIWYG editors.
$('textarea[data-provides="anomaly.field_type.wysiwyg"]:not(.hasEditor)').each(function () {
/**
* Gather available buttons / plugins.
*/
var textarea = $(this);
var buttons = textarea.data('available_buttons');
var plugins = textarea.data('available_plugins');
textarea.addClass('hasEditor');
textarea.redactor({
element: $(this),
/**
* Initialize the editor icons.
*/
callbacks: {
init: function () {
var icons = {};
$.each(buttons, function (k, v) {
if (v.icon) {
icons[v.button ? v.button : k] = '<i class="' + v.icon + '"></i>';
}
});
$.each(plugins, function (k, v) {
if (v.icon) {
icons[v.button ? v.button : k] = '<i class="' + v.icon + '"></i>';
}
});
$.each(this.button.all(), $.proxy(function (i, s) {
var key = $(s).attr('rel');
if (typeof icons[key] !== 'undefined') {
var icon = icons[key];
var button = this.button.get(key);
this.button.setIcon(button, icon);
}
}, this));
}
},
/**
* Settings
*/
script: false,
structure: true,
linkTooltip: true,
cleanOnPaste: true,
toolbarFixed: false,
imagePosition: true,
imageResizable: true,
imageFloatMargin: '20px',
removeEmpty: ['strong', 'em', 'p'],
/**
* Features
*/
minHeight: textarea.data('height'),
placeholder: textarea.attr('placeholder'),
folders: textarea.data('folders').toString().split(','),
buttons: textarea.data('buttons').toString().split(','),
plugins: textarea.data('plugins').toString().split(',')
});
textarea.closest('form').on('submit', function () {
textarea.val(textarea.redactor('code.get'));
});
});
});
|
'use strict';
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Parent = function () {
_createClass(Parent, null, [{
key: 'staticMethod1',
value: function staticMethod1() {}
}]);
function Parent() {
_classCallCheck(this, Parent);
this.classMethod1 = this.classMethod1.bind(this);
this.classProp1 = 'classProp1';
this.classProp2 = 'classProp2';
}
_createClass(Parent, [{
key: 'classMethod1',
value: function classMethod1() {}
}, {
key: 'render',
value: function render() {}
}]);
return Parent;
}();
Parent.staticProp1 = 'staticProp1';
var Child = function (_Parent) {
_inherits(Child, _Parent);
_createClass(Child, null, [{
key: 'staticMethod2',
value: function staticMethod2() {}
}]);
function Child() {
_classCallCheck(this, Child);
var _this = _possibleConstructorReturn(this, (Child.__proto__ || Object.getPrototypeOf(Child)).call(this));
_this.classMethod2 = _this.classMethod2.bind(_this);
_this.classProp3 = 'classProp3';
return _this;
}
_createClass(Child, [{
key: 'classMethod2',
value: function classMethod2() {}
}]);
return Child;
}(Parent);
Child.staticProp2 = 'staticProp2';
var ChildNoConstructor = function (_Parent2) {
_inherits(ChildNoConstructor, _Parent2);
function ChildNoConstructor() {
var _ref;
var _temp, _this2, _ret;
_classCallCheck(this, ChildNoConstructor);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this2 = _possibleConstructorReturn(this, (_ref = ChildNoConstructor.__proto__ || Object.getPrototypeOf(ChildNoConstructor)).call.apply(_ref, [this].concat(args))), _this2), _this2.classMethod2 = _this2.classMethod2.bind(_this2), _temp), _possibleConstructorReturn(_this2, _ret);
}
_createClass(ChildNoConstructor, [{
key: 'classMethod2',
value: function classMethod2() {}
}]);
return ChildNoConstructor;
}(Parent);
var ChildNoConstructorWithProperties = function (_Parent3) {
_inherits(ChildNoConstructorWithProperties, _Parent3);
function ChildNoConstructorWithProperties() {
var _ref2;
var _temp2, _temp3, _this3, _ret2;
_classCallCheck(this, ChildNoConstructorWithProperties);
for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
return _ret2 = (_temp2 = (_temp3 = (_this3 = _possibleConstructorReturn(this, (_ref2 = ChildNoConstructorWithProperties.__proto__ || Object.getPrototypeOf(ChildNoConstructorWithProperties)).call.apply(_ref2, [this].concat(args))), _this3), _this3.classMethod1 = _this3.classMethod1.bind(_this3), _temp3), _this3.classProp1 = 'classProp1', _temp2), _possibleConstructorReturn(_this3, _ret2);
}
_createClass(ChildNoConstructorWithProperties, [{
key: 'classMethod1',
value: function classMethod1() {}
}, {
key: 'render',
value: function render() {}
}]);
return ChildNoConstructorWithProperties;
}(Parent);
|
import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M15 21v-4.24l-1.41 1.41-9.2-9.19-1.41 1.41 9.19 9.19L10.76 21H15zM11.25 8.48l3.54 3.54-.92 2.19 1.48 1.48 4.42-11.14-1.06-1.05L7.57 7.92 9.06 9.4l2.19-.92zm6.59-3.05l-2.23 4.87-2.64-2.64 4.87-2.23z" />
, 'TextRotationAngledownTwoTone');
|
import {
EventDispatcher,
Matrix4,
Plane,
Raycaster,
Vector2,
Vector3
} from '../../../build/three.module.js';
const _plane = new Plane();
const _raycaster = new Raycaster();
const _pointer = new Vector2();
const _offset = new Vector3();
const _intersection = new Vector3();
const _worldPosition = new Vector3();
const _inverseMatrix = new Matrix4();
class DragControls extends EventDispatcher {
constructor( _objects, _camera, _domElement ) {
super();
_domElement.style.touchAction = 'none'; // disable touch scroll
let _selected = null, _hovered = null;
const _intersections = [];
//
const scope = this;
function activate() {
_domElement.addEventListener( 'pointermove', onPointerMove );
_domElement.addEventListener( 'pointerdown', onPointerDown );
_domElement.addEventListener( 'pointerup', onPointerCancel );
_domElement.addEventListener( 'pointerleave', onPointerCancel );
}
function deactivate() {
_domElement.removeEventListener( 'pointermove', onPointerMove );
_domElement.removeEventListener( 'pointerdown', onPointerDown );
_domElement.removeEventListener( 'pointerup', onPointerCancel );
_domElement.removeEventListener( 'pointerleave', onPointerCancel );
_domElement.style.cursor = '';
}
function dispose() {
deactivate();
}
function getObjects() {
return _objects;
}
function getRaycaster() {
return _raycaster;
}
function onPointerMove( event ) {
if ( scope.enabled === false ) return;
updatePointer( event );
_raycaster.setFromCamera( _pointer, _camera );
if ( _selected ) {
if ( _raycaster.ray.intersectPlane( _plane, _intersection ) ) {
_selected.position.copy( _intersection.sub( _offset ).applyMatrix4( _inverseMatrix ) );
}
scope.dispatchEvent( { type: 'drag', object: _selected } );
return;
}
// hover support
if ( event.pointerType === 'mouse' || event.pointerType === 'pen' ) {
_intersections.length = 0;
_raycaster.setFromCamera( _pointer, _camera );
_raycaster.intersectObjects( _objects, true, _intersections );
if ( _intersections.length > 0 ) {
const object = _intersections[ 0 ].object;
_plane.setFromNormalAndCoplanarPoint( _camera.getWorldDirection( _plane.normal ), _worldPosition.setFromMatrixPosition( object.matrixWorld ) );
if ( _hovered !== object && _hovered !== null ) {
scope.dispatchEvent( { type: 'hoveroff', object: _hovered } );
_domElement.style.cursor = 'auto';
_hovered = null;
}
if ( _hovered !== object ) {
scope.dispatchEvent( { type: 'hoveron', object: object } );
_domElement.style.cursor = 'pointer';
_hovered = object;
}
} else {
if ( _hovered !== null ) {
scope.dispatchEvent( { type: 'hoveroff', object: _hovered } );
_domElement.style.cursor = 'auto';
_hovered = null;
}
}
}
}
function onPointerDown( event ) {
if ( scope.enabled === false ) return;
updatePointer( event );
_intersections.length = 0;
_raycaster.setFromCamera( _pointer, _camera );
_raycaster.intersectObjects( _objects, true, _intersections );
if ( _intersections.length > 0 ) {
_selected = ( scope.transformGroup === true ) ? _objects[ 0 ] : _intersections[ 0 ].object;
_plane.setFromNormalAndCoplanarPoint( _camera.getWorldDirection( _plane.normal ), _worldPosition.setFromMatrixPosition( _selected.matrixWorld ) );
if ( _raycaster.ray.intersectPlane( _plane, _intersection ) ) {
_inverseMatrix.copy( _selected.parent.matrixWorld ).invert();
_offset.copy( _intersection ).sub( _worldPosition.setFromMatrixPosition( _selected.matrixWorld ) );
}
_domElement.style.cursor = 'move';
scope.dispatchEvent( { type: 'dragstart', object: _selected } );
}
}
function onPointerCancel() {
if ( scope.enabled === false ) return;
if ( _selected ) {
scope.dispatchEvent( { type: 'dragend', object: _selected } );
_selected = null;
}
_domElement.style.cursor = _hovered ? 'pointer' : 'auto';
}
function updatePointer( event ) {
const rect = _domElement.getBoundingClientRect();
_pointer.x = ( event.clientX - rect.left ) / rect.width * 2 - 1;
_pointer.y = - ( event.clientY - rect.top ) / rect.height * 2 + 1;
}
activate();
// API
this.enabled = true;
this.transformGroup = false;
this.activate = activate;
this.deactivate = deactivate;
this.dispose = dispose;
this.getObjects = getObjects;
this.getRaycaster = getRaycaster;
}
}
export { DragControls };
|
const { Console } = require("console");
const Colors = require("./Colors");
const { inspect } = require("util");
const Timestamp = require("../../util/Timestamp");
/**
* Komada's console class, extends NodeJS Console class.
*
*/
class KomadaConsole extends Console {
/**
* Constructs our KomadaConsole instance
* @param {boolean} [stdout=process.stdout] The location of standard output. Must be a writable stream.
* @param {boolean} [stderr=process.stderr] The location of standrad error outputt. Must be a writable stream.
* @param {boolean} [colors={}] The colors for this console instance.
* @param {boolean} [timestamps=false] Whether or not Timestamps should be enabled.
*/
constructor({ stdout, stderr, useColor, colors = {}, timestamps = true }) {
super(stdout, stderr);
/**
* The standard output stream for this console, defaulted to process.stderr.
* @name KomadaConsole#stdout
* @type {WritableStream}
*/
Object.defineProperty(this, "stdout", { value: stdout });
/**
* The standard error output stream for this console, defaulted to process.stderr.
* @name KomadaConsole#stderr
* @type {WritableStream}
*/
Object.defineProperty(this, "stderr", { value: stderr });
/**
* Whether or not timestamps should be enabled for this console.
* @type {boolean}
*/
this.timestamps = timestamps;
/**
* Whether or not this console should use colors.
* @type {boolean}
*/
this.useColors = typeof useColor === "undefined" ? this.stdout.isTTY || false : useColor;
/**
* The colors for this console.
* @name KomadaConsole#colors
* @type {boolean|Colors}
*/
this.colors = {
debug: colors.debug || { message: { background: null, text: null, style: null }, time: { background: null, text: "lightmagenta", style: null } },
error: colors.error || { message: { background: null, text: null, style: null }, time: { background: "red", text: null, style: null } },
log: colors.log || { message: { background: null, text: null, style: null }, time: { background: null, text: "lightblue", style: null } },
verbose: colors.verbose || { message: { background: null, text: "gray", style: null }, time: { background: null, text: "gray", style: null } },
warn: colors.warn || { message: { background: null, text: null, style: null }, time: { background: "lightyellow", text: "black", style: null } },
wtf: colors.wtf || { message: { background: "red", text: null, style: ["bold", "underline"] }, time: { background: "red", text: null, style: ["bold", "underline"] } },
};
}
/**
* @memberof KomadaConsole
* @typedef {object} Colors - Time is for the timestamp of the log, message is for the actual output.
* @property {ColorObjects} debug An object containing a message and time color object.
* @property {ColorObjects} error An object containing a message and time color object.
* @property {ColorObjects} log An object containing a message and time color object.
* @property {ColorObjects} verbose An object containing a message and time color object.
* @property {ColorObjects} warn An object containing a message and time color object.
* @property {ColorObjects} wtf An object containing a message and time Color Object.
*/
/**
* @memberof KomadaConsole
* @typedef {object} ColorObjects
* @property {MessageObject} message A message object containing colors and styles.
* @property {TimeObject} time A time object containing colors and styles.
*/
/**
* @memberof KomadaConsole
* @typedef {object} MessageObject
* @property {BackgroundColorTypes} background The background color. Can be a basic string like "red", a hex string, or a RGB array.
* @property {TextColorTypes} text The text color. Can be a basic string like "red", a hex string, or a RGB array.
* @property {StyleTypes} style A style string from StyleTypes.
*/
/**
* @memberof KomadaConsole
* @typedef {object} TimeObject
* @property {BackgroundColorTypes} background The background color. Can be a basic string like "red", a hex string, or a RGB array.
* @property {TextColorTypes} text The text color. Can be a basic string like "red", a hex string, a RGB array, or HSL array.
* @property {StyleTypes} style A style string from StyleTypes.
*/
/**
* @memberof KomadaConsole
* @typedef {*} TextColorTypes - All the valid color types.
* @property {string} black
* @property {string} red
* @property {string} green
* @property {string} yellow
* @property {string} blue
* @property {string} magenta
* @property {string} cyan
* @property {string} gray
* @property {string} grey
* @property {string} lightgray
* @property {string} lightgrey
* @property {string} lightred
* @property {string} lightgreen
* @property {string} lightyellow
* @property {string} lightblue
* @property {string} lightmagenta
* @property {string} lightcyan
* @property {string} white
* @property {string} #008000 green
* @property {Array} [255,0,0] red
* @property {Array} [229,50%,50%] blue
*/
/**
* @memberof KomadaConsole
* @typedef {*} BackgroundColorTypes - One of these strings, HexStrings, RGB, or HSL are valid types.
* @property {string} black
* @property {string} red
* @property {string} green
* @property {string} blue
* @property {string} magenta
* @property {string} cyan
* @property {string} gray
* @property {string} grey
* @property {string} lightgray
* @property {string} lightgrey
* @property {string} lightred
* @property {string} lightgreen
* @property {string} lightyellow
* @property {string} lightblue
* @property {string} lightmagenta
* @property {string} lightcyan
* @property {string} white
* @property {string} #008000 green
* @property {Array} [255,0,0] red
* @property {Array} [229,50%,50%] blue
*/
/**
* @memberof KomadaConsole
* @typedef {*} StyleTypes
* @property {string} normal
* @property {string} bold
* @property {string} dim
* @property {string} italic
* @property {string} underline
* @property {string} inverse
* @property {string} hidden
* @property {string} strikethrough
*/
/**
* Logs everything to the console/writable stream.
* @param {*} stuff The stuff we want to print.
* @param {string} [type="log"] The type of log, particularly useful for coloring.
*/
log(stuff, type = "log") {
stuff = KomadaConsole.flatten(stuff, this.useColors);
const message = this.colors ? this.colors[type.toLowerCase()].message : {};
const time = this.colors ? this.colors[type.toLowerCase()].time : {};
const timestamp = this.timestamps ? `${this.timestamp(`[${Timestamp.format(new Date())}]`, time)} ` : "";
if (this[`_${type}`]) {
this[`_${type}`](stuff.split("\n").map(str => `${timestamp}${this.messages(str, message)}`).join("\n"));
} else {
super.log(stuff.split("\n").map(str => `${timestamp}${this.messages(str, message)}`).join("\n"));
}
}
/**
* Print something to console as a simple log.
* @param {*} stuff The stuff to log
*/
_log(stuff) {
super.log(stuff);
}
/**
* Print something to console as an error.
* @param {*} stuff The stuff to log
*/
_error(stuff) {
super.error(stuff);
}
/**
* Print something to console as a "WTF" error.
* @param {*} stuff The stuff to log
*/
_wtf(stuff) {
super.error(stuff);
}
/**
* Print something to console as a debug log.
* @param {*} stuff The stuff to log
*/
_debug(stuff) {
super.log(stuff);
}
/**
* Print something to console as a verbose log.
* @param {*} stuff The stuff to log
*/
_verbose(stuff) {
super.log(stuff);
}
/**
* Print something to console as a warning.
* @param {*} stuff The stuff to log
*/
_warn(stuff) {
super.log(stuff);
}
timestamp(timestamp, time) {
if (!this.useColors) return timestamp;
return `${Colors.format(timestamp, time)} `;
}
messages(string, message) {
if (!this.useColors) return string;
return Colors.format(string, message);
}
/**
* Flattens our data into a readable string.
* @param {*} data Some data to flatten
* @param {boolean} useColors Whether or not the inspection should color the output
* @return {string}
*/
static flatten(data, useColors) {
data = data.stack || data.message || data;
if (typeof data === "object" && typeof data !== "string" && !Array.isArray(data)) data = inspect(data, { depth: 0, colors: useColors });
if (Array.isArray(data)) data = data.join("\n");
return data;
}
}
module.exports = KomadaConsole;
|
'use strict';
var command = require('../cmd-helpers').command;
module.exports = function (send) {
return command(send, 'commands');
}; |
/**
* SiteController
*
* @module :: Controller
* @description :: A set of functions called `actions`.
*
* Actions contain code telling Sails how to respond to a certain type of request.
* (i.e. do stuff, then send some JSON, show an HTML page, or redirect to another URL)
*
* You can configure the blueprint URLs which trigger these actions (`config/controllers.js`)
* and/or override them with custom routes (`config/routes.js`)
*
* NOTE: The code you write here supports both HTTP and Socket.io automatically.
*
* @docs :: http://sailsjs.org/#!documentation/controllers
*/
module.exports = {
example: function (req, res, next) {
TemplateService.example(function(error, result) {
Site.createEach(result, function (error, result) {
if(error)
next(error);
else
res.json(result);
});
});
}
, replace: function (req, res, next) {
// Locate and validate id parameter
var id = req.param('id');
var data = req.params.all();
if (!id) {
return res.badRequest('No id provided.');
}
// Otherwise, find and destroy the Site in question
Site.findOne(id).exec(function found(err, result) {
// TODO: differentiate between waterline-originated validation errors
// and serious underlying issues
// TODO: Respond with badRequest if an error is encountered, w/ validation info
if (err) return res.serverError(err);
if (!result) return res.notFound();
Site.destroy(id).exec(function destroyed(err) {
// TODO: differentiate between waterline-originated validation errors
// and serious underlying issues
// TODO: Respond with badRequest if an error is encountered, w/ validation info
if (err) return res.serverError(err);
// Create new instance of Site using data from params
Site.create(data).exec(function created (err, data) {
// TODO: differentiate between waterline-originated validation errors
// and serious underlying issues
// TODO: Respond with badRequest if an error is encountered, w/ validation info
if (err) return res.serverError(err);
// If we have the pubsub hook, use the Site class's publish method
// to notify all subscribers about the created item
if (sails.hooks.pubsub) {
Site.publishUpdate(id, data.toJSON());
}
// Set status code (HTTP 201: Created)
res.status(201);
// Send JSONP-friendly response if it's supported
return res.jsonp(data.toJSON());
// Otherwise, strictly JSON.
// return res.json(data.toJSON());
});
});
});
}
/**
* Overrides for the settings in `config/controllers.js`
* (specific to SiteController)
*/
, _config: {}
}; |
var api = require('../../../../api/sample.js');
module.exports = function (router) {
router.route('/api/v1/sample').get(api.works);
}; |
(function() {
// Default to the local version.
var path = '../libs/jquery/dist/jquery.js';
// Get any jquery=___ param from the query string.
var jqversion = location.search.match(/[?&]jquery=(.*?)(?=&|$)/);
// If a version was specified, use that version from code.jquery.com.
if (jqversion) {
path = 'http://code.jquery.com/jquery-' + jqversion[1] + '.js';
}
// This is the only time I'll ever use document.write, I promise!
document.write('<script src="' + path + '"></script>');
}());
|
import {
Parser,
ObserverLocator,
EventManager,
ListenerExpression,
BindingExpression,
NameExpression,
CallExpression,
bindingMode
} from 'aurelia-binding';
import {BehaviorInstruction} from 'aurelia-templating';
export class SyntaxInterpreter {
static inject() { return [Parser,ObserverLocator,EventManager]; }
constructor(parser, observerLocator, eventManager){
this.parser = parser;
this.observerLocator = observerLocator;
this.eventManager = eventManager;
}
interpret(resources, element, info, existingInstruction){
if(info.command in this){
return this[info.command](resources, element, info, existingInstruction);
}
return this.handleUnknownCommand(resources, element, info, existingInstruction);
}
handleUnknownCommand(resources, element, info, existingInstruction){
var attrName = info.attrName,
command = info.command;
var instruction = this.options(resources, element, info, existingInstruction);
instruction.alteredAttr = true;
instruction.attrName = 'global-behavior';
instruction.attributes.aureliaAttrName = attrName;
instruction.attributes.aureliaCommand = command;
return instruction;
}
determineDefaultBindingMode(element, attrName){
var tagName = element.tagName.toLowerCase();
if(tagName === 'input'){
return attrName === 'value' || attrName === 'checked' || attrName === 'files' ? bindingMode.twoWay : bindingMode.oneWay;
}else if(tagName == 'textarea' || tagName == 'select'){
return attrName == 'value' ? bindingMode.twoWay : bindingMode.oneWay;
}else if(attrName === 'textcontent' || attrName === 'innerhtml'){
return element.contentEditable === 'true' ? bindingMode.twoWay : bindingMode.oneWay;
} else if(attrName === 'scrolltop' || attrName === 'scrollleft'){
return bindingMode.twoWay;
}
return bindingMode.oneWay;
}
bind(resources, element, info, existingInstruction){
var instruction = existingInstruction || BehaviorInstruction.attribute(info.attrName);
instruction.attributes[info.attrName] = new BindingExpression(
this.observerLocator,
this.attributeMap[info.attrName] || info.attrName,
this.parser.parse(info.attrValue),
info.defaultBindingMode || this.determineDefaultBindingMode(element, info.attrName),
resources.valueConverterLookupFunction
);
return instruction;
}
trigger(resources, element, info){
return new ListenerExpression(
this.eventManager,
info.attrName,
this.parser.parse(info.attrValue),
false,
true
);
}
delegate(resources, element, info){
return new ListenerExpression(
this.eventManager,
info.attrName,
this.parser.parse(info.attrValue),
true,
true
);
}
call(resources, element, info, existingInstruction){
var instruction = existingInstruction || BehaviorInstruction.attribute(info.attrName);
instruction.attributes[info.attrName] = new CallExpression(
this.observerLocator,
info.attrName,
this.parser.parse(info.attrValue),
resources.valueConverterLookupFunction
);
return instruction;
};
options(resources, element, info, existingInstruction){
var instruction = existingInstruction || BehaviorInstruction.attribute(info.attrName),
attrValue = info.attrValue,
language = this.language,
name = null, target = '', current, i , ii;
for(i = 0, ii = attrValue.length; i < ii; ++i){
current = attrValue[i];
if(current === ';'){
info = language.inspectAttribute(resources, name, target.trim());
language.createAttributeInstruction(resources, element, info, instruction);
if(!instruction.attributes[info.attrName]){
instruction.attributes[info.attrName] = info.attrValue;
}
target = '';
name = null;
} else if(current === ':' && name === null){
name = target.trim();
target = '';
} else {
target += current;
}
}
if(name !== null){
info = language.inspectAttribute(resources, name, target.trim());
language.createAttributeInstruction(resources, element, info, instruction);
if(!instruction.attributes[info.attrName]){
instruction.attributes[info.attrName] = info.attrValue;
}
}
return instruction;
}
}
SyntaxInterpreter.prototype['for'] = function(resources, element, info, existingInstruction){
var parts, keyValue, instruction, attrValue, isDestructuring;
attrValue = info.attrValue;
isDestructuring = attrValue.match(/[[].+[\]]/);
parts = isDestructuring ? attrValue.split('of ') : attrValue.split(' of ');
if(parts.length !== 2){
throw new Error('Incorrect syntax for "for". The form is: "$local of $items" or "[$key, $value] of $items".');
}
instruction = existingInstruction || BehaviorInstruction.attribute(info.attrName);
if(isDestructuring){
keyValue = parts[0].replace(/[[\]]/g, '').replace(/,/g, ' ').replace(/\s+/g, ' ').trim().split(' ');
instruction.attributes.key = keyValue[0];
instruction.attributes.value = keyValue[1];
}else{
instruction.attributes.local = parts[0];
}
instruction.attributes.items = new BindingExpression(
this.observerLocator,
'items',
this.parser.parse(parts[1]),
bindingMode.oneWay,
resources.valueConverterLookupFunction
);
return instruction;
};
SyntaxInterpreter.prototype['two-way'] = function(resources, element, info, existingInstruction){
var instruction = existingInstruction || BehaviorInstruction.attribute(info.attrName);
instruction.attributes[info.attrName] = new BindingExpression(
this.observerLocator,
this.attributeMap[info.attrName] || info.attrName,
this.parser.parse(info.attrValue),
bindingMode.twoWay,
resources.valueConverterLookupFunction
);
return instruction;
};
SyntaxInterpreter.prototype['one-way'] = function(resources, element, info, existingInstruction){
var instruction = existingInstruction || BehaviorInstruction.attribute(info.attrName);
instruction.attributes[info.attrName] = new BindingExpression(
this.observerLocator,
this.attributeMap[info.attrName] || info.attrName,
this.parser.parse(info.attrValue),
bindingMode.oneWay,
resources.valueConverterLookupFunction
);
return instruction;
};
SyntaxInterpreter.prototype['one-time'] = function(resources, element, info, existingInstruction){
var instruction = existingInstruction || BehaviorInstruction.attribute(info.attrName);
instruction.attributes[info.attrName] = new BindingExpression(
this.observerLocator,
this.attributeMap[info.attrName] || info.attrName,
this.parser.parse(info.attrValue),
bindingMode.oneTime,
resources.valueConverterLookupFunction
);
return instruction;
};
|
// Wait https://github.com/facebook/flow/issues/380 to be fixed
/* eslint-disable flowtype/require-valid-file-annotation */
const brown = {
50: '#efebe9',
100: '#d7ccc8',
200: '#bcaaa4',
300: '#a1887f',
400: '#8d6e63',
500: '#795548',
600: '#6d4c41',
700: '#5d4037',
800: '#4e342e',
900: '#3e2723',
A100: '#d7ccc8',
A200: '#bcaaa4',
A400: '#8d6e63',
A700: '#5d4037',
contrastDefaultColor: 'brown',
};
export default brown;
|
var Application;
(function ($) {
JSC.require(
['jsc/Controller', 'jsc/Loader', 'jsc/Notifier'],
function () {
Application = function (master, url, controller) {
Controller.call(this, master);
this.cls = 'Application';
this.controller = controller;
this.home = url;
this.loader = new Loader();
this.notifier = new Notifier();
};
Application.prototype = new Controller();
Application.prototype.constructor = Application;
Application.prototype.init = function () {
Controller.prototype.init.call(this);
return this;
};
}
);
}(jQuery)); |
// @flow
import callApi from '../utils/apiCaller';
import type { Dispatch } from './types';
import type { Game } from '../utils/globalTypes';
export function addGame(game: Game) {
return {
type: 'ADD_GAME',
game,
};
}
export function addGameRequest(game: Game) {
return (dispatch: Dispatch) =>
callApi('games', 'post', {
game: {
name: game.name,
description: game.description,
img: game.img,
backgroundImg: game.backgroundImg,
availableOn: game.availableOn,
videoLinks: game.videoLinks,
galleryLinks: game.galleryLinks,
developer: game.developer,
winBuildURL: game.winBuildURL,
macBuildURL: game.macBuildURL,
macFilename: game.macFilename,
winFilename: game.winFilename,
winExe: game.winExe,
isPrivate: game.isPrivate,
allowedPlayers: [game.developer]
}
}).then(res => dispatch(addGame(res.game)));
}
export function addGames(games: Array<Game>) {
console.log('dispatching addGames');
return {
type: 'ADD_GAMES',
games,
};
}
function requestGames() {
return {
type: 'REQUEST_GAMES'
};
}
function receiveGames(games: Array<Game>) {
return {
type: 'RECEIVE_GAMES',
games
};
}
function fetchGames() {
return dispatch => {
dispatch(requestGames());
return callApi('games').then(res =>
dispatch(receiveGames(res))
);
};
}
function shouldFetchGames(state) {
const games = state.game.items;
if (games.length === 0) {
return true;
} else if (games.isFetching) {
return false;
}
}
export function fetchGamesIfNeeded() {
return (dispatch: Dispatch, getState: Function) => {
if (shouldFetchGames(getState())) {
return dispatch(fetchGames());
}
};
}
function fetchGame(id) {
return (dispatch) => {
dispatch(requestGames());
return callApi(`games/${id}`).then(res => dispatch(addGame(res)));
};
}
function shouldFetchGame(state, id) {
state.game.items.forEach((game) => {
if (game._id === id) {
return false;
}
});
return true;
}
export function fetchGameIfNeeded(id: string) {
return (dispatch: Dispatch, getState: Function) => {
if (shouldFetchGame(getState(), id)) {
return dispatch(fetchGame(id));
}
};
}
export function fetchEditGameIfNeeded(id: string) {
return (dispatch: Dispatch, getState: Function) => {
if (shouldFetchEditGame(getState(), id)) {
return dispatch(fetchEditGame(id));
}
};
}
function shouldFetchEditGame(state, id) {
if (state.game.editGame) {
return state.game.editGame._id === id;
}
return true;
}
function fetchEditGame(id) {
return dispatch => {
dispatch(requestGames());
return callApi(`games/${id}`).then(res => dispatch(addEditGame(res)));
};
}
function addEditGame(game) {
return {
type: 'ADD_EDIT_GAME',
game
};
}
export function editGameRequest(game: Game, id: string) {
return () =>
callApi(`games/${id}`, 'put', { game });
}
export function allowPlayer(index: number, user: string) {
return {
type: 'ALLOW_PLAYER',
index,
user
};
}
export function markFeedbackRequest(
feedbackId: string,
mark: number,
childIndex: number,
parentIndex: number
) {
return (dispatch: Dispatch) =>
callApi('feedbacks/mark', 'post', {
feedbackId,
mark
}).then(() => dispatch(markFeedback(childIndex, parentIndex, mark)));
}
function markFeedback(childIndex, parentIndex, mark) {
return {
type: 'MARK_FEEDBACK',
childIndex,
parentIndex,
mark
};
}
|
module.exports={A:{A:{"1":"E A B","2":"H D G EB"},B:{"1":"C p x J L N I"},C:{"1":"9","33":"0 1 2 3 4 5 6 8 ZB BB F K H D G E A B C p x J L N I O P Q R S T U V W X Y Z b c d e f g h i j k l m n o M q r s t u v w y XB RB"},D:{"1":"0 1 2 3 4 5 6 8 9 F K H D G E A B C p x J L N I O P Q R S T U V W X Y Z b c d e f g h i j k l m n o M q r s t u v w y LB GB FB bB a HB IB JB"},E:{"1":"F K H D G E A B C KB CB MB NB OB PB QB z SB"},F:{"1":"0 7 B C J L N I O P Q R S T U V W X Y Z b c d e f g h i j k l m n o M q r s t u v w TB UB VB WB z AB YB","2":"E"},G:{"2":"G CB aB DB cB dB eB fB gB hB iB jB kB lB"},H:{"2":"mB"},I:{"1":"a rB sB","2":"BB F nB oB pB qB DB"},J:{"1":"A","2":"D"},K:{"1":"7 C M AB","16":"A B z"},L:{"1":"a"},M:{"33":"y"},N:{"1":"A B"},O:{"1":"tB"},P:{"1":"F K uB vB"},Q:{"1":"wB"},R:{"1":"xB"}},B:5,C:"::selection CSS pseudo-element"};
|
// @flow
/* eslint-disable no-console */
const validAnimationState = /^(from|to|\+?(\d*\.)?\d+%)(\s*,\s*(from|to|\+?(\d*\.)?\d+%))*$/;
export default function validateKeyframesObject(keyframes: Object) {
let valid = true;
for (const animationState in keyframes) {
const value = keyframes[animationState];
if (!validAnimationState.test(animationState)) {
valid = false;
console.warn(
`Warning: property "${animationState}" in keyframes object ${JSON.stringify(
keyframes,
)} is not a valid. Must be "from", "to", or a percentage.`,
);
}
if (typeof value !== "object") {
valid = false;
console.warn(
`Warning: value for "${animationState}" property in keyframes object ${JSON.stringify(
keyframes,
)} must be an object. Instead it was a ${typeof value}.`,
);
}
if (!valid) {
console.warn(
`Warning: object used as value for "animationName" style is invalid:`,
keyframes,
);
}
}
}
|
/**
*
* @param {Array<String>} midiMessages
* @param {TrackBank} trackBank
* @param {int} numberOfTracks
* @constructor
*/
function SceneSelectorButtons(midiMessages, trackBank, numberOfTracks)
{
ControlGroup.call(this);
this.trackBank = trackBank;
this.numberOfTracks = numberOfTracks;
this._previous = this.addControl(new Button(midiMessages.previous)).on('press', this.previous.bind(this));
this._next = this.addControl(new Button(midiMessages.next)).on('press', this.next.bind(this));
this.trackBank.addCanScrollScenesUpObserver(this._previous.value.setInternal);
this.trackBank.addCanScrollScenesDownObserver(this._next.value.setInternal);
for (var i = 0; i < this.numberOfTracks; i++)
{
this.trackBank.getTrack(i).getClipLauncherSlots().setIndication(true);
}
}
util.inherits(SceneSelectorButtons, ControlGroup);
SceneSelectorButtons.prototype.next = function ()
{
this.trackBank.scrollScenesDown();
};
SceneSelectorButtons.prototype.previous = function ()
{
this.trackBank.scrollScenesUp();
}; |
var hasNodeRequire = typeof require === 'function' && typeof window === 'undefined';
/* jshint ignore:start */
if (hasNodeRequire) {
chai = require('chai');
jDataView = require('jdataview');
jBinary = require('..');
} else {
__dirname = 'base/test';
}
/* jshint ignore:end */
var assert = chai.assert,
chr = String.fromCharCode,
dataBytes = [
0x00,
0xff, 0xfe, 0xfd, 0xfc,
0xfa, 0x00, 0xba, 0x01
],
dataStart = 1,
view = new jDataView(dataBytes.slice(), dataStart, undefined, true),
binary = new jBinary(view, {__UNUSED__: '__UNUSED__'}),
typeSet = jBinary.prototype.typeSet,
ObjectStructure = {
arrays: ['array', {
flag: ['enum', 'uint8', [false, true]],
array: ['if', 'flag', {
length: 'uint8',
values: ['array', 'uint16', 'length']
}]
}, 2]
},
ExtensionStructure = {
extraByte: 'uint8'
};
for (var typeName in typeSet) {
typeSet[typeName].isTested = {getter: false, setter: false};
}
function b() {
return new jBinary(arguments);
}
function compareInt64(value, expected) {
assert.equal(+value, expected);
}
function compareBytes(value, expected) {
value = Array.prototype.slice.call(value);
assert.deepEqual(value, expected);
}
function compareWithNaN(value, expected, message) {
assert.ok(isNaN(value), message || value + ' != NaN');
}
suite('Common operations:', function () {
test('getType', function () {
var type = binary.getType('uint32');
assert.instanceOf(type, jBinary.Type);
assert.equal(binary.getType([type]), type);
});
suite('slice', function () {
test('with bound check', function () {
assert.Throw(function () {
binary.slice(5, 10);
});
});
test('as pointer to original data', function () {
var pointerCopy = binary.slice(1, 4);
compareBytes(pointerCopy.read('blob'), [0xfe, 0xfd, 0xfc]);
pointerCopy.write('char', chr(1), 0);
assert.equal(binary.read('char', 1), chr(1));
pointerCopy.write('char', chr(0xfe), 0);
assert.equal(pointerCopy.typeSet, binary.typeSet);
});
test('as copy of original data', function () {
var copy = binary.slice(1, 4, true);
compareBytes(copy.read('blob'), [0xfe, 0xfd, 0xfc]);
copy.write('char', chr(1), 0);
assert.notEqual(binary.read('char', 1), chr(1));
assert.equal(copy.typeSet, binary.typeSet);
});
test('with only start offset argument given', function () {
var pointerCopy = binary.slice(1);
compareBytes(pointerCopy.read('blob'), [0xfe, 0xfd, 0xfc, 0xfa, 0x00, 0xba, 0x01]);
});
test('with negative start offset given', function () {
var pointerCopy = binary.slice(-2);
compareBytes(pointerCopy.read('blob'), [0xba, 0x01]);
});
test('with negative end offset given', function () {
var pointerCopy = binary.slice(1, -2);
compareBytes(pointerCopy.read('blob'), [0xfe, 0xfd, 0xfc, 0xfa, 0x00]);
});
});
suite('as (cast)', function () {
var typeSet = binary.typeSet,
typeSet2 = {MY_TYPESET: true};
test('with inheritance from original binary', function () {
var binary2 = binary.as(typeSet2);
assert.ok(binary.isPrototypeOf(binary2));
assert.equal(binary.typeSet, typeSet);
assert.isTrue(binary2.typeSet.MY_TYPESET);
});
test('with modification of original binary', function () {
var binary2 = binary.as(typeSet2, true);
assert.equal(binary, binary2);
assert.isTrue(binary.typeSet.MY_TYPESET);
binary.typeSet = typeSet;
});
});
});
//-----------------------------------------------------------------
suite('Loading data', function () {
var localFileName = __dirname + '/123.tar';
test('from data-URI', function (done) {
jBinary.loadData('data:text/plain,123', function (err, data) {
assert.notOk(err, err);
assert.equal(new jDataView(data).getString(), '123');
done();
});
});
test('from base-64 data-URI', function (done) {
jBinary.loadData('data:text/plain;base64,MTIz', function (err, data) {
assert.notOk(err, err);
assert.equal(new jDataView(data).getString(), '123');
done();
});
});
if (typeof Blob === 'function') {
test('from HTML5 Blob', function (done) {
var blob = new Blob(['123']);
jBinary.loadData(blob, function (err, data) {
assert.notOk(err, err);
assert.equal(new jDataView(data).getString(), '123');
done();
});
});
}
test('from local file', function (done) {
jBinary.loadData(localFileName, function (err, data) {
assert.notOk(err, err);
assert.equal(data.byteLength || data.length, 512);
done();
});
});
test('from non-existent local file', function (done) {
jBinary.loadData('__NON_EXISTENT__', function (err, data) {
assert.ok(err);
assert.isUndefined(data);
done();
});
});
if (hasNodeRequire && require('stream').Readable) {
test('from Node.js readable stream', function (done) {
var stream = require('stream').Readable(), i = 0;
stream._read = function () {
i++;
this.push(i <= 3 ? new Buffer([i]) : null);
};
jBinary.loadData(stream, function (err, data) {
assert.notOk(err, err);
compareBytes(data, [1, 2, 3]);
done();
});
});
test('from URL', function (done) {
this.timeout(30000);
var port = 7359;
var server = require('http').createServer(function (req, res) {
require('fs').createReadStream(localFileName).pipe(res);
});
server.listen(port);
jBinary.loadData('http://localhost:' + port, function (err, data) {
assert.notOk(err, err);
assert.equal(data.byteLength || data.length, 512);
server.close();
done();
});
});
}
if (hasNodeRequire && require('stream').Readable) {
test('from file-based readableStream', function (done) {
var stream = require('fs').createReadStream(localFileName);
jBinary.loadData(stream, function (err, data) {
assert.notOk(err, err);
assert.equal(data.byteLength || data.length, 512);
done();
});
});
}
test('with explicit typeset object', function (done) {
var typeSet = {
IS_CORRECT_TYPESET: true
};
jBinary.load(localFileName, typeSet, function (err, binary) {
assert.notOk(err, err);
assert.instanceOf(binary, jBinary);
assert.equal(binary.view.byteLength, 512);
assert.isTrue(typeSet.IS_CORRECT_TYPESET);
done();
});
});
test('with implicitly empty typeset object', function (done) {
jBinary.load(localFileName, function (err, binary) {
assert.notOk(err, err);
assert.instanceOf(binary, jBinary);
assert.equal(binary.view.byteLength, 512);
assert.equal(binary.typeSet, jBinary.prototype.typeSet);
done();
});
});
suite('as Promise', function () {
test('from data-URI', function (done) {
jBinary.loadData('data:text/plain,123').then(function (res) {
assert.equal(new jDataView(res).getString(), '123');
done();
}, function (err) {
assert.fail(err);
done();
});
});
test('with explicit typeset object', function (done) {
var typeSet = {
IS_CORRECT_TYPESET: true
};
jBinary.load(localFileName, typeSet).then(function (binary) {
assert.instanceOf(binary, jBinary);
assert.equal(binary.view.byteLength, 512);
assert.isTrue(typeSet.IS_CORRECT_TYPESET);
done();
}, function (err) {
assert.fail(err);
done();
});
});
test('from non-existent local file', function (done) {
jBinary.loadData('__NON_EXISTENT__').then(function () {
assert.fail();
done();
}, function (err) {
assert.instanceOf(err, Error);
done();
});
});
test('from non-existent local file with explicit typeset object', function (done) {
jBinary.load('__NON_EXISTENT__').then(function () {
assert.fail();
done();
}, function (err) {
assert.instanceOf(err, Error);
done();
});
});
});
});
//-----------------------------------------------------------------
suite('Saving data', function () {
test('to URI', function (done) {
jBinary.load(binary.toURI(), function (err, newBinary) {
assert.notOk(err, err);
assert.deepEqual(newBinary.read('string', 0), binary.read('string', 0));
done();
});
});
if (hasNodeRequire) {
test('to local file', function (done) {
var savedFileName = __dirname + '/' + Math.random().toString().slice(2) + '.tmp';
binary.saveAs(savedFileName, function (err) {
assert.notOk(err, err);
jBinary.load(savedFileName, function (err, newBinary) {
assert.notOk(err, err);
assert.equal(newBinary.read('string', 0), binary.read('string', 0));
require('fs').unlink(savedFileName, done);
});
});
});
if (require('stream').Writable) {
test('to Node.js writable stream', function (done) {
var stream = require('stream').Writable(), chunks = [];
stream._write = function (chunk, encoding, callback) {
chunks.push(chunk);
callback();
};
binary.saveAs(stream, function (err) {
assert.notOk(err, err);
assert.equal(Buffer.concat(chunks).toString('binary'), binary.read('string', 0));
done();
});
});
}
} else {
test('via browser dialog', function (done) {
function addListener(node, eventType, handler) {
if (node.addEventListener) {
node.addEventListener(eventType, handler);
} else {
node.attachEvent('on' + eventType, handler);
}
}
(function (onLoad) {
document.readyState === 'complete' ? onLoad() : addListener(window, 'load', onLoad);
})(function () {
var msSaveBlob = navigator.msSaveBlob;
if (msSaveBlob) {
navigator.msSaveBlob = function (blob, fileName) {
assert.instanceOf(blob, Blob);
assert.equal(fileName, 'test.dat');
};
} else {
// Phantom.JS
if (!HTMLElement.prototype.click) {
HTMLElement.prototype.click = function() {
var event = document.createEvent('MouseEvent');
event.initMouseEvent(
'click',
/*bubble*/true, /*cancelable*/true,
window, null,
0, 0, 0, 0, /*coordinates*/
false, false, false, false, /*modifier keys*/
0/*button=left*/, null
);
this.dispatchEvent(event);
};
}
addListener(jBinary.downloader, 'click', function (event) {
assert.ok(this.href);
assert.equal(this.download, 'test.dat');
event.preventDefault ? event.preventDefault() : event.returnValue = false;
});
}
binary.saveAs('test.dat', function () {
if (msSaveBlob) {
navigator.msSaveBlob = msSaveBlob;
}
done();
});
});
});
}
});
//-----------------------------------------------------------------
suite('Reading', function () {
// getter = value || {value, check?, binary?, args?, offset?}
function testGetters(typeName, getters) {
test(typeName, function () {
binary.seek(0);
for (var i = 0; i < getters.length; i++) {
var getter = getters[i];
if (typeof getter !== 'object') {
getter = {value: getter};
}
var args = getter.args,
type = args ? [typeName].concat(args) : typeName,
offset = getter.offset,
contextBinary = getter.binary || binary,
check = getter.check || assert.equal,
value = getter.value;
if (offset !== undefined) {
contextBinary.seek(offset);
}
check(contextBinary.read(type), value);
}
});
}
testGetters('blob', [
{offset: 1, args: [2], value: [0xfe, 0xfd], check: compareBytes},
{args: [3], value: [0xfc, 0xfa, 0x00], check: compareBytes}
]);
testGetters('char', [
chr(0xff),
chr(0xfe),
chr(0xfd),
chr(0xfc),
chr(0xfa),
chr(0),
chr(0xba),
chr(1)
]);
testGetters('string', [
{offset: 0, args: [1], value: chr(0xff)},
{offset: 5, args: [1], value: chr(0)},
{offset: 7, args: [1], value: chr(1)},
{binary: b(127, 0, 1, 65, 66), args: [5], value: chr(127) + chr(0) + chr(1) + chr(65) + chr(66)},
{binary: b(0xd1, 0x84, 0xd1, 0x8b, 0xd0, 0xb2), args: [6, 'utf8'], value: chr(1092) + chr(1099) + chr(1074)}
]);
testGetters('string0', [
{offset: 0, args: [8], value: chr(0xff) + chr(0xfe) + chr(0xfd) + chr(0xfc) + chr(0xfa)},
{binary: b(127, 0, 1, 65, 66), value: chr(127)}
]);
testGetters('int8', [
-1,
-2,
-3,
-4,
-6,
0,
-70,
1
]);
testGetters('uint8', [
255,
254,
253,
252,
250,
0,
186,
1
]);
testGetters('int16', [
{offset: 0, value: -257},
{offset: 1, value: -514},
{offset: 2, value: -771},
{offset: 3, value: -1284},
{offset: 4, value: 250},
{offset: 5, value: -17920},
{offset: 6, value: 442}
]);
testGetters('uint16', [
{offset: 0, value: 65279},
{offset: 1, value: 65022},
{offset: 2, value: 64765},
{offset: 3, value: 64252},
{offset: 4, value: 250},
{offset: 5, value: 47616},
{offset: 6, value: 442}
]);
testGetters('uint32', [
{offset: 0, value: 4244504319},
{offset: 1, value: 4210884094},
{offset: 2, value: 16448765},
{offset: 3, value: 3120626428},
{offset: 4, value: 28967162}
]);
testGetters('int32', [
{offset: 0, value: -50462977},
{offset: 1, value: -84083202},
{offset: 2, value: 16448765},
{offset: 3, value: -1174340868},
{offset: 4, value: 28967162}
]);
testGetters('float32', [
{offset: 0, value: -1.055058432344064e+37},
{offset: 1, value: -6.568051909668895e+35},
{offset: 2, value: 2.30496291345398e-38},
{offset: 3, value: -0.0004920212086290121},
{offset: 4, value: 6.832701044000979e-38},
{binary: b(0x7f, 0x80, 0x00, 0x00), value: Infinity},
{binary: b(0xff, 0x80, 0x00, 0x00), value: -Infinity},
{binary: b(0x00, 0x00, 0x00, 0x00), value: 0},
{binary: b(0xff, 0x80, 0x00, 0x01), check: compareWithNaN}
]);
testGetters('float64', [
{offset: 0, value: 2.426842827241402e-300},
{binary: b(0x7f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00), value: Infinity},
{binary: b(0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00), value: -Infinity},
{binary: b(0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00), value: 0},
{binary: b(0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00), value: -0},
{binary: b(0x3f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00), value: 1},
{binary: b(0x3f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01), value: 1.0000000000000002},
{binary: b(0x3f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02), value: 1.0000000000000004},
{binary: b(0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00), value: 2},
{binary: b(0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00), value: -2},
{binary: b(0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01), value: 5e-324},
{binary: b(0x00, 0x0f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff), value: 2.225073858507201e-308},
{binary: b(0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00), value: 2.2250738585072014e-308},
{binary: b(0x7f, 0xef, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff), value: 1.7976931348623157e+308},
{binary: b(0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01), check: compareWithNaN}
]);
testGetters('int64', [
{offset: 0, args: [false], value: -283686985483775, check: compareInt64},
{binary: b(0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe), value: -2, check: compareInt64},
{binary: b(0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77), value: 4822678189205111, check: compareInt64}
]);
testGetters('uint64', [
{binary: b(0x00, 0x67, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe), value: 29273397577908224, check: compareInt64},
{binary: b(0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77), value: 4822678189205111, check: compareInt64}
]);
test('skip', function () {
binary.read(['skip', 2]);
assert.equal(binary.tell(), 2);
binary.read(['skip', 1]);
assert.equal(binary.tell(), 3);
});
testGetters('enum', [
{offset: 5, args: ['uint8', [false, true]], value: false},
{offset: 7, args: ['uint8', {'0': 'false', '1': 'true'}], value: 'true'}
]);
testGetters('array', [
{offset: 0, args: ['uint16', 2], value: [65279, 64765], check: assert.deepEqual},
{offset: 5, args: ['uint8'], value: [0x00, 0xba, 0x01], check: assert.deepEqual}
]);
test('const', function () {
assert.Throw(function () {
binary.read(['const', 'uint16', 0, true], 0);
});
assert.doesNotThrow(function () {
assert.notEqual(binary.read(['const', 'uint8', 0], 0), 0);
});
var errorFlag = false;
binary.read(['const', 'uint8', 123, function (value) {
assert.equal(value, 0xff);
assert.equal(this.value, 123);
errorFlag = true;
}], 0);
assert.isTrue(errorFlag);
});
testGetters('if', [
{offset: 0, args: [true, 'uint8'], value: 0xff},
{offset: 0, args: [function () { return false }, 'uint8', 'uint16'], value: 65279}
]);
testGetters('if_not', [
{offset: 0, args: [false, 'uint8'], value: 0xff},
{offset: 0, args: [function () { return false }, 'uint16', 'uint8'], value: 65279}
]);
testGetters('bitfield', [
// padded to byte here
{offset: 1, args: [3], value: 7},
{args: [5], value: 30},
// padded to byte here
{args: [15], value: 32510},
{args: [17], value: 64000}
// padded to byte here
]);
testGetters('object', [{
binary: b(0x01, 0x02, 0xff, 0xfe, 0xfd, 0xfc, 0x00, 0x10),
args: [ObjectStructure],
value: {
arrays: [
{
flag: true,
array: {
length: 2,
values: [0xfffe, 0xfdfc]
}
},
{
flag: false
}
]
},
check: assert.deepEqual
}]);
testGetters('extend', [{
binary: b(0x01, 0x02, 0xff, 0xfe, 0xfd, 0xfc, 0x00, 0x10),
args: [ObjectStructure, ExtensionStructure],
value: {
arrays: [
{
flag: true,
array: {
length: 2,
values: [0xfffe, 0xfdfc]
}
},
{
flag: false
}
],
extraByte: 0x10
},
check: assert.deepEqual
}]);
testGetters('binary', [{
offset: 1,
args: [3, {__TEST_ME__: '__TEST_ME__'}],
value: [0xfe, 0xfd, 0xfc],
check: function (subBinary, values) {
assert.deepEqual(subBinary.read(['array', 'uint8'], 0), values);
assert.equal(subBinary.view.buffer, binary.view.buffer);
assert.equal(subBinary.typeSet.__TEST_ME__, '__TEST_ME__');
}
}]);
test('lazy', function () {
var innerType = 'uint32',
length = 4,
lazyType = ['lazy', innerType, length],
lazy,
readCount,
innerValue = binary.read(innerType, 0);
function resetAccessor() {
lazy = binary.read(lazyType, 0);
assert.notOk('value' in lazy);
readCount = 0;
var read = lazy.binary.read;
lazy.binary.read = function () {
readCount++;
return read.apply(this, arguments);
};
}
function checkState(expectedChangeState, expectedReadCount) {
assert.equal(!!lazy.wasChanged, expectedChangeState);
for (var counter = 2; counter--;) {
assert.equal(lazy(), innerValue);
}
assert.equal(readCount, expectedReadCount);
assert.equal(lazy.value, innerValue);
}
resetAccessor();
checkState(false, 1);
innerValue = 5489408;
lazy(innerValue);
checkState(true, 1);
resetAccessor();
lazy(innerValue);
checkState(true, 0);
assert.equal(lazy.binary.typeSet, binary.typeSet);
var obj = {
innerObj: {
someLazy: ['lazy', jBinary.Type({
read: function (context) {
assert.ok(context);
assert.property(context, 'someLazy');
var parentContext = this.binary.getContext(1);
assert.ok(parentContext);
assert.equal(parentContext.innerObj, context);
}
}), 0]
}
};
binary.read(obj).innerObj.someLazy();
});
this.tests.forEach(function (test) {
typeSet[test.title].isTested.getter = true;
});
});
//-----------------------------------------------------------------
suite('Writing', function () {
teardown(function () {
binary.write('blob', dataBytes.slice(dataStart), 0);
});
// setter = value || {value, args?, check?}
function testSetters(typeName, setters, stdSize) {
test(typeName, function () {
for (var i = 0; i < setters.length; i++) {
var setter = setters[i];
if (typeof setter !== 'object') {
setter = {value: setter};
}
var args = setter.args,
type = args ? [typeName].concat(args) : typeName,
check = setter.check || assert.equal,
value = setter.value;
var writtenSize = binary.write(type, value, 0);
assert.equal('size' in setter ? setter.size : stdSize, writtenSize, 'writtenSize = ' + writtenSize + ' != ' + setter.size);
check(binary.read(type, 0), value);
}
});
}
testSetters('blob', [
{args: [2], value: [0xfe, 0xfd], size: 2, check: compareBytes},
{args: [3], value: [0xfd, 0xfe, 0xff], size: 3, check: compareBytes}
]);
testSetters('char', [
chr(0xdf),
chr(0x03),
chr(0x00),
chr(0xff)
], 1);
testSetters('string', [
{args: [3], value: chr(1) + chr(2) + chr(3), size: 3},
{args: [2], value: chr(8) + chr(9), size: 2},
{args: [6, 'utf8'], value: chr(1092) + chr(1099) + chr(1074), size: 6}
]);
testSetters('string0', [
{args: [4], value: chr(0xff) + chr(0xfe) + chr(0xfd), size: 3 + 1, check: function (value, expected) {
assert.equal(value, expected);
assert.equal(binary.read('uint8', value.length), 0);
}},
{value: chr(127) + chr(0) + chr(1) + chr(65) + chr(66), size: 5 + 1, check: function (value, expected) {
assert.equal(value, expected.slice(0, value.length));
assert.equal(binary.read('uint8', value.length), 0);
}}
]);
testSetters('int8', [
-10,
29
], 1);
testSetters('uint8', [
19,
129,
0,
255,
254
], 1);
testSetters('int16', [
-17593,
23784
], 2);
testSetters('uint16', [
39571,
35
], 2);
testSetters('int32', [
-1238748268,
69359465
], 4);
testSetters('uint32', [
3592756249,
257391
], 4);
testSetters('float32', [
Math.pow(2, -149),
-Math.pow(2, -149),
Math.pow(2, -126),
-Math.pow(2, -126),
-1.055058432344064e+37,
-6.568051909668895e+35,
2.30496291345398e-38,
-0.0004920212086290121,
6.832701044000979e-38,
Infinity,
-Infinity,
0,
{value: NaN, check: compareWithNaN}
], 4);
testSetters('float64', [
Math.pow(2, -1074),
-Math.pow(2, -1074),
Math.pow(2, -1022),
-Math.pow(2, -1022),
2.426842827241402e-300,
Infinity,
-Infinity,
0,
1,
1.0000000000000004,
-2,
{value: NaN, check: compareWithNaN}
], 8);
testSetters('int64', [
{value: -283686985483775, check: compareInt64},
{value: -2, check: compareInt64},
{value: 4822678189205111, check: compareInt64}
], 8);
testSetters('uint64', [
{value: 29273397577908224, check: compareInt64},
{value: 4822678189205111, check: compareInt64}
], 8);
test('skip', function () {
binary.seek(0);
binary.write(['skip', 2]);
assert.equal(binary.tell(), 2);
binary.write(['skip', 1]);
assert.equal(binary.tell(), 3);
});
testSetters('enum', [
{args: ['uint8', {'0': false, '1': true}], value: false},
{args: ['uint8', ['false', 'true']], value: 'true'}
], 1);
testSetters('array', [
{args: ['uint16', 2], value: [65279, 64765], size: 2 * 2, check: assert.deepEqual},
{args: ['uint8', 3], value: [0x00, 0xba, 0x01], size: 1 * 3, check: assert.deepEqual}
]);
test('const', function () {
var type = ['const', 'uint16', 123, true],
size = 2;
try {
assert.equal(binary.write(type.slice(0, -1), 10, 0), size);
binary.read(type, 0);
assert.ok(false);
} catch (e) {
assert.ok(true);
}
try {
assert.equal(binary.write(type, 10, 0), size);
assert.equal(binary.read(type, 0), 123);
} catch (e) {
assert.ok(false);
}
});
testSetters('if', [
{args: [true, 'uint8'], value: 123, size: 1},
{args: [function () { return false }, 'uint8', 'uint16'], value: 17893, size: 2}
]);
testSetters('if_not', [
{args: [false, 'uint8'], value: 123, size: 1},
{args: [function () { return false }, 'uint16', 'uint8'], value: 17893, size: 2}
]);
// setter = {value, bitLength}
function testBitfieldSetters(type, setters) {
test(type, function () {
var binary = new jBinary(13);
function eachValue(callback) {
binary.seek(0);
setters.forEach(function (setter) {
callback.call(binary, setter.value, setter.bitLength);
});
}
eachValue(function (value, bitLength) {
this.write([type, bitLength], value);
});
eachValue(function (value, bitLength) {
var realValue = this.read([type, bitLength]);
assert.equal(realValue, value, 'write' + type + '(' + value + ', ' + bitLength + ') != get' + type + '(' + bitLength + ') == ' + realValue);
});
});
}
testBitfieldSetters('bitfield', [
// padded to byte here
{value: 5, bitLength: 3},
{value: 29, bitLength: 5},
// padded to byte here
{value: 19781, bitLength: 15},
{value: 68741, bitLength: 17},
// padded to byte here
{value: 0xffffffff, bitLength: 32},
// padded to byte here
{value: 0x7fffffff, bitLength: 31},
{value: 1, bitLength: 1}
]);
testSetters('object', [{
args: [ObjectStructure],
value: {
arrays: [
{
flag: true,
array: {
length: 2,
values: [0xfffe, 0xfdfc]
}
},
{
flag: false
}
]
},
size: 7,
check: assert.deepEqual
}]);
testSetters('extend', [{
args: [ObjectStructure, ExtensionStructure],
value: {
arrays: [
{
flag: true,
array: {
length: 2,
values: [0xfffe, 0xfdfc]
}
},
{
flag: false
}
],
extraByte: 0x10
},
size: 7 + 1,
check: assert.deepEqual
}]);
testSetters('binary', [
{
args: [2],
value: new jBinary([0x12, 0x34]),
size: 2,
check: function (readBinary, writeBinary) {
assert.deepEqual(readBinary.read(['array', 'uint8'], 0), writeBinary.read(['array', 'uint8'], 0));
assert.equal(readBinary.view.buffer, binary.view.buffer);
}
}
]);
test('lazy', function () {
var innerType = 'uint32',
length = 4,
lazyType = ['lazy', innerType, length],
blobType = ['array', 'uint8', length],
newBinary = new jBinary(length),
nativeAccessor = binary.read(lazyType, 0),
externalValue = 7849234,
externalAccessor = function () {
return externalValue;
};
assert.equal(newBinary.write(lazyType, nativeAccessor), length);
assert.equal(newBinary.tell(), length);
assert.ok(!('value' in nativeAccessor));
assert.deepEqual(binary.read(blobType, 0), newBinary.read(blobType, 0));
newBinary.seek(0);
assert.equal(newBinary.write(lazyType, externalAccessor), length);
assert.equal(newBinary.tell(), length);
assert.deepEqual(newBinary.read(innerType, 0), externalValue);
});
this.tests.forEach(function (test) {
typeSet[test.title].isTested.setter = true;
});
});
//-----------------------------------------------------------------
suite('Test coverage of type', function () {
function testCoverage(typeName) {
test(typeName, function () {
var isTested = typeSet[typeName].isTested;
assert.ok(isTested.getter, 'Getter tests');
assert.ok(isTested.setter, 'Setter tests');
});
}
for (var typeName in typeSet) {
testCoverage(typeName);
}
}); |
RocketChat.models.OAuthApps = new class extends RocketChat.models._Base {
constructor() {
super('oauth_apps');
}
};
// FIND
// findByRole: (role, options) ->
// query =
// roles: role
// return @find query, options
// CREATE
|
{
"AD" : "서기",
"Africa/Abidjan_Z_abbreviated" : "코트디부아르 시간",
"Africa/Abidjan_Z_short" : "GMT",
"Africa/Accra_Z_abbreviated" : "가나 시간",
"Africa/Accra_Z_short" : "GMT",
"Africa/Addis_Ababa_Z_abbreviated" : "이디오피아 시간",
"Africa/Addis_Ababa_Z_short" : "EAT",
"Africa/Algiers_Z_abbreviated" : "알제리 시간",
"Africa/Algiers_Z_short" : "WET",
"Africa/Asmara_Z_abbreviated" : "에리트리아 시간",
"Africa/Asmara_Z_short" : "EAT",
"Africa/Bamako_Z_abbreviated" : "말리 시간",
"Africa/Bamako_Z_short" : "GMT",
"Africa/Bangui_Z_abbreviated" : "중앙 아프리카 공화국 시간",
"Africa/Bangui_Z_short" : "WAT",
"Africa/Banjul_Z_abbreviated" : "감비아 시간",
"Africa/Banjul_Z_short" : "GMT",
"Africa/Bissau_Z_abbreviated" : "기네비쏘 시간",
"Africa/Bissau_Z_short" : "GMT-01:00",
"Africa/Blantyre_Z_abbreviated" : "말라위 시간",
"Africa/Blantyre_Z_short" : "CAT",
"Africa/Brazzaville_Z_abbreviated" : "콩고 시간",
"Africa/Brazzaville_Z_short" : "WAT",
"Africa/Bujumbura_Z_abbreviated" : "부룬디 시간",
"Africa/Bujumbura_Z_short" : "CAT",
"Africa/Cairo_Z_abbreviated" : "이집트 시간",
"Africa/Cairo_Z_short" : "EET",
"Africa/Casablanca_Z_abbreviated" : "모로코 시간",
"Africa/Casablanca_Z_short" : "WET",
"Africa/Conakry_Z_abbreviated" : "기니 시간",
"Africa/Conakry_Z_short" : "GMT",
"Africa/Dakar_Z_abbreviated" : "세네갈 시간",
"Africa/Dakar_Z_short" : "GMT",
"Africa/Dar_es_Salaam_Z_abbreviated" : "탄자니아 시간",
"Africa/Dar_es_Salaam_Z_short" : "EAT",
"Africa/Djibouti_Z_abbreviated" : "지부티 시간",
"Africa/Djibouti_Z_short" : "EAT",
"Africa/Douala_Z_abbreviated" : "카메룬 시간",
"Africa/Douala_Z_short" : "WAT",
"Africa/El_Aaiun_Z_abbreviated" : "서사하라 시간",
"Africa/El_Aaiun_Z_short" : "GMT-01:00",
"Africa/Freetown_Z_abbreviated" : "시에라리온 시간",
"Africa/Freetown_Z_short" : "GMT",
"Africa/Gaborone_Z_abbreviated" : "보츠와나 시간",
"Africa/Gaborone_Z_short" : "CAT",
"Africa/Harare_Z_abbreviated" : "짐바브웨 시간",
"Africa/Harare_Z_short" : "CAT",
"Africa/Johannesburg_Z_abbreviated" : "남아프리카 시간",
"Africa/Johannesburg_Z_short" : "SAST",
"Africa/Juba_Z_abbreviated" : "수단 시간",
"Africa/Juba_Z_short" : "CAT",
"Africa/Kampala_Z_abbreviated" : "우간다 시간",
"Africa/Kampala_Z_short" : "EAT",
"Africa/Khartoum_Z_abbreviated" : "수단 시간",
"Africa/Khartoum_Z_short" : "CAT",
"Africa/Kigali_Z_abbreviated" : "르완다 시간",
"Africa/Kigali_Z_short" : "CAT",
"Africa/Kinshasa_Z_abbreviated" : "콩고 민주공화국 (킨샤사)",
"Africa/Kinshasa_Z_short" : "WAT",
"Africa/Lagos_Z_abbreviated" : "나이지리아 시간",
"Africa/Lagos_Z_short" : "WAT",
"Africa/Libreville_Z_abbreviated" : "가봉 시간",
"Africa/Libreville_Z_short" : "WAT",
"Africa/Lome_Z_abbreviated" : "토고 시간",
"Africa/Lome_Z_short" : "GMT",
"Africa/Luanda_Z_abbreviated" : "앙골라 시간",
"Africa/Luanda_Z_short" : "WAT",
"Africa/Lusaka_Z_abbreviated" : "잠비아 시간",
"Africa/Lusaka_Z_short" : "CAT",
"Africa/Malabo_Z_abbreviated" : "적도 기니 시간",
"Africa/Malabo_Z_short" : "WAT",
"Africa/Maputo_Z_abbreviated" : "모잠비크 시간",
"Africa/Maputo_Z_short" : "CAT",
"Africa/Maseru_Z_abbreviated" : "레소토 시간",
"Africa/Maseru_Z_short" : "SAST",
"Africa/Mbabane_Z_abbreviated" : "스와질랜드 시간",
"Africa/Mbabane_Z_short" : "SAST",
"Africa/Mogadishu_Z_abbreviated" : "소말리아 시간",
"Africa/Mogadishu_Z_short" : "EAT",
"Africa/Monrovia_Z_abbreviated" : "라이베리아 시간",
"Africa/Monrovia_Z_short" : "GMT-00:44:30",
"Africa/Nairobi_Z_abbreviated" : "케냐 시간",
"Africa/Nairobi_Z_short" : "EAT",
"Africa/Ndjamena_Z_abbreviated" : "차드 시간",
"Africa/Ndjamena_Z_short" : "WAT",
"Africa/Niamey_Z_abbreviated" : "니제르 시간",
"Africa/Niamey_Z_short" : "WAT",
"Africa/Nouakchott_Z_abbreviated" : "모리타니 시간",
"Africa/Nouakchott_Z_short" : "GMT",
"Africa/Ouagadougou_Z_abbreviated" : "부르키나파소 시간",
"Africa/Ouagadougou_Z_short" : "GMT",
"Africa/Porto-Novo_Z_abbreviated" : "베냉 시간",
"Africa/Porto-Novo_Z_short" : "WAT",
"Africa/Sao_Tome_Z_abbreviated" : "상투메 프린시페 시간",
"Africa/Sao_Tome_Z_short" : "GMT",
"Africa/Tripoli_Z_abbreviated" : "리비아 시간",
"Africa/Tripoli_Z_short" : "EET",
"Africa/Tunis_Z_abbreviated" : "튀니지 시간",
"Africa/Tunis_Z_short" : "CET",
"Africa/Windhoek_Z_abbreviated" : "나미비아 시간",
"Africa/Windhoek_Z_short" : "SAST",
"America/Anguilla_Z_abbreviated" : "안길라 시간",
"America/Anguilla_Z_short" : "AST",
"America/Antigua_Z_abbreviated" : "앤티가 바부다 시간",
"America/Antigua_Z_short" : "AST",
"America/Araguaina_Z_abbreviated" : "브라질 (아라과이나)",
"America/Araguaina_Z_short" : "BRT",
"America/Argentina/Buenos_Aires_Z_abbreviated" : "아르헨티나 (부에노스 아이레스)",
"America/Argentina/Buenos_Aires_Z_short" : "ART",
"America/Argentina/Catamarca_Z_abbreviated" : "아르헨티나 (카타마르카)",
"America/Argentina/Catamarca_Z_short" : "ART",
"America/Argentina/Cordoba_Z_abbreviated" : "아르헨티나 (코르도바)",
"America/Argentina/Cordoba_Z_short" : "ART",
"America/Argentina/Jujuy_Z_abbreviated" : "아르헨티나 (후후이)",
"America/Argentina/Jujuy_Z_short" : "ART",
"America/Argentina/La_Rioja_Z_abbreviated" : "아르헨티나 (라 리오하)",
"America/Argentina/La_Rioja_Z_short" : "ART",
"America/Argentina/Mendoza_Z_abbreviated" : "아르헨티나 (멘도사)",
"America/Argentina/Mendoza_Z_short" : "ART",
"America/Argentina/Rio_Gallegos_Z_abbreviated" : "아르헨티나 (리오 가예고스)",
"America/Argentina/Rio_Gallegos_Z_short" : "ART",
"America/Argentina/Salta_Z_abbreviated" : "아르헨티나 (살타)",
"America/Argentina/Salta_Z_short" : "ART",
"America/Argentina/San_Juan_Z_abbreviated" : "아르헨티나 (산후안)",
"America/Argentina/San_Juan_Z_short" : "ART",
"America/Argentina/San_Luis_Z_abbreviated" : "아르헨티나 (산루이스)",
"America/Argentina/San_Luis_Z_short" : "ART",
"America/Argentina/Tucuman_Z_abbreviated" : "아르헨티나 (뚜꾸만)",
"America/Argentina/Tucuman_Z_short" : "ART",
"America/Argentina/Ushuaia_Z_abbreviated" : "아르헨티나 (우수아이아)",
"America/Argentina/Ushuaia_Z_short" : "ART",
"America/Aruba_Z_abbreviated" : "아루바 시간",
"America/Aruba_Z_short" : "AST",
"America/Asuncion_Z_abbreviated" : "파라과이 시간",
"America/Asuncion_Z_short" : "PYT",
"America/Bahia_Banderas_Z_abbreviated" : "멕시코 (Bahia Banderas)",
"America/Bahia_Banderas_Z_short" : "PST",
"America/Bahia_Z_abbreviated" : "브라질 (바히아)",
"America/Bahia_Z_short" : "BRT",
"America/Barbados_Z_abbreviated" : "바베이도스 시간",
"America/Barbados_Z_short" : "AST",
"America/Belem_Z_abbreviated" : "브라질 (벨렘)",
"America/Belem_Z_short" : "BRT",
"America/Belize_Z_abbreviated" : "벨리즈 시간",
"America/Belize_Z_short" : "CST",
"America/Blanc-Sablon_Z_abbreviated" : "캐나다 (블랑 사블롱)",
"America/Blanc-Sablon_Z_short" : "AST",
"America/Boa_Vista_Z_abbreviated" : "브라질 (보아 비스타)",
"America/Boa_Vista_Z_short" : "AMT",
"America/Bogota_Z_abbreviated" : "콜롬비아 시간",
"America/Bogota_Z_short" : "COT",
"America/Boise_Z_abbreviated" : "미국 (보이시)",
"America/Boise_Z_short" : "MST",
"America/Cambridge_Bay_Z_abbreviated" : "캐나다 (케임브리지 베이)",
"America/Cambridge_Bay_Z_short" : "MST",
"America/Campo_Grande_Z_abbreviated" : "브라질 (캄포 그란데)",
"America/Campo_Grande_Z_short" : "AMT",
"America/Cancun_Z_abbreviated" : "멕시코 (칸쿤)",
"America/Cancun_Z_short" : "CST",
"America/Caracas_Z_abbreviated" : "베네수엘라 시간",
"America/Caracas_Z_short" : "VET",
"America/Cayenne_Z_abbreviated" : "프랑스령 기아나 시간",
"America/Cayenne_Z_short" : "GFT",
"America/Cayman_Z_abbreviated" : "케이맨제도 시간",
"America/Cayman_Z_short" : "EST",
"America/Chicago_Z_abbreviated" : "미국 (시카고)",
"America/Chicago_Z_short" : "CST",
"America/Chihuahua_Z_abbreviated" : "멕시코 (치와와)",
"America/Chihuahua_Z_short" : "CST",
"America/Costa_Rica_Z_abbreviated" : "코스타리카 시간",
"America/Costa_Rica_Z_short" : "CST",
"America/Cuiaba_Z_abbreviated" : "브라질 (쿠이아바)",
"America/Cuiaba_Z_short" : "AMT",
"America/Curacao_Z_abbreviated" : "네덜란드령 안틸레스 시간",
"America/Curacao_Z_short" : "AST",
"America/Danmarkshavn_Z_abbreviated" : "그린란드 (덴마크샤븐)",
"America/Danmarkshavn_Z_short" : "WGT",
"America/Denver_Z_abbreviated" : "미국 (덴버)",
"America/Denver_Z_short" : "MST",
"America/Detroit_Z_abbreviated" : "미국 (디트로이트)",
"America/Detroit_Z_short" : "EST",
"America/Dominica_Z_abbreviated" : "도미니카 시간",
"America/Dominica_Z_short" : "AST",
"America/Edmonton_Z_abbreviated" : "캐나다 (에드먼턴)",
"America/Edmonton_Z_short" : "MST",
"America/Eirunepe_Z_abbreviated" : "브라질 (아이루네페)",
"America/Eirunepe_Z_short" : "ACT (아크레)",
"America/El_Salvador_Z_abbreviated" : "엘살바도르 시간",
"America/El_Salvador_Z_short" : "CST",
"America/Fortaleza_Z_abbreviated" : "브라질 (포르탈레자)",
"America/Fortaleza_Z_short" : "BRT",
"America/Goose_Bay_Z_abbreviated" : "캐나다 (구즈베이)",
"America/Goose_Bay_Z_short" : "AST",
"America/Grand_Turk_Z_abbreviated" : "터크스케이커스제도 시간",
"America/Grand_Turk_Z_short" : "EST",
"America/Grenada_Z_abbreviated" : "그레나다 시간",
"America/Grenada_Z_short" : "AST",
"America/Guadeloupe_Z_abbreviated" : "과들루프 시간",
"America/Guadeloupe_Z_short" : "AST",
"America/Guatemala_Z_abbreviated" : "과테말라 시간",
"America/Guatemala_Z_short" : "CST",
"America/Guayaquil_Z_abbreviated" : "에콰도르 (과야킬)",
"America/Guayaquil_Z_short" : "ECT",
"America/Guyana_Z_abbreviated" : "가이아나 시간",
"America/Guyana_Z_short" : "GYT",
"America/Halifax_Z_abbreviated" : "캐나다 (핼리팩스)",
"America/Halifax_Z_short" : "AST",
"America/Havana_Z_abbreviated" : "쿠바 시간",
"America/Havana_Z_short" : "CST (쿠바)",
"America/Hermosillo_Z_abbreviated" : "멕시코 (에르모시요)",
"America/Hermosillo_Z_short" : "PST",
"America/Indiana/Indianapolis_Z_abbreviated" : "미국 (인디애나폴리스)",
"America/Indiana/Indianapolis_Z_short" : "EST",
"America/Indiana/Knox_Z_abbreviated" : "미국 (인디애나주 녹스)",
"America/Indiana/Knox_Z_short" : "CST",
"America/Indiana/Marengo_Z_abbreviated" : "미국 (인디애나주, 마렝고)",
"America/Indiana/Marengo_Z_short" : "EST",
"America/Indiana/Petersburg_Z_abbreviated" : "미국 (인디애나주, 피츠버그)",
"America/Indiana/Petersburg_Z_short" : "CST",
"America/Indiana/Tell_City_Z_abbreviated" : "미국 (인디아나주, 텔시티)",
"America/Indiana/Tell_City_Z_short" : "EST",
"America/Indiana/Vevay_Z_abbreviated" : "미국 (자포로제)",
"America/Indiana/Vevay_Z_short" : "EST",
"America/Indiana/Vincennes_Z_abbreviated" : "미국 (인디아나주, 뱅센)",
"America/Indiana/Vincennes_Z_short" : "EST",
"America/Indiana/Winamac_Z_abbreviated" : "미국 (인디아나주, 워너맥)",
"America/Indiana/Winamac_Z_short" : "EST",
"America/Iqaluit_Z_abbreviated" : "캐나다 (이칼루이트)",
"America/Iqaluit_Z_short" : "EST",
"America/Jamaica_Z_abbreviated" : "자메이카 시간",
"America/Jamaica_Z_short" : "EST",
"America/Juneau_Z_abbreviated" : "미국 (주노)",
"America/Juneau_Z_short" : "PST",
"America/Kentucky/Louisville_Z_abbreviated" : "미국 (루이빌)",
"America/Kentucky/Louisville_Z_short" : "EST",
"America/Kentucky/Monticello_Z_abbreviated" : "미국 (켄터키주, 몬티첼로)",
"America/Kentucky/Monticello_Z_short" : "CST",
"America/La_Paz_Z_abbreviated" : "볼리비아 시간",
"America/La_Paz_Z_short" : "BOT",
"America/Lima_Z_abbreviated" : "페루 시간",
"America/Lima_Z_short" : "PET",
"America/Los_Angeles_Z_abbreviated" : "미국 (로스앤젤레스)",
"America/Los_Angeles_Z_short" : "PST",
"America/Maceio_Z_abbreviated" : "브라질 (마세이오)",
"America/Maceio_Z_short" : "BRT",
"America/Managua_Z_abbreviated" : "니카라과 시간",
"America/Managua_Z_short" : "CST",
"America/Manaus_Z_abbreviated" : "브라질 (마나우스)",
"America/Manaus_Z_short" : "AMT",
"America/Martinique_Z_abbreviated" : "말티니크 시간",
"America/Martinique_Z_short" : "AST",
"America/Matamoros_Z_abbreviated" : "멕시코 (Matamoros)",
"America/Matamoros_Z_short" : "CST",
"America/Mazatlan_Z_abbreviated" : "멕시코 (마사틀란)",
"America/Mazatlan_Z_short" : "PST",
"America/Menominee_Z_abbreviated" : "미국 (메노미니)",
"America/Menominee_Z_short" : "EST",
"America/Merida_Z_abbreviated" : "멕시코 (메리다)",
"America/Merida_Z_short" : "CST",
"America/Mexico_City_Z_abbreviated" : "멕시코 (멕시코 시티)",
"America/Mexico_City_Z_short" : "CST",
"America/Miquelon_Z_abbreviated" : "세인트피에르-미케롱 시간",
"America/Miquelon_Z_short" : "AST",
"America/Moncton_Z_abbreviated" : "캐나다 (몽턴)",
"America/Moncton_Z_short" : "AST",
"America/Monterrey_Z_abbreviated" : "멕시코 (몬테레이)",
"America/Monterrey_Z_short" : "CST",
"America/Montevideo_Z_abbreviated" : "우루과이 시간",
"America/Montevideo_Z_short" : "UYT",
"America/Montserrat_Z_abbreviated" : "몬트세라트 시간",
"America/Montserrat_Z_short" : "AST",
"America/Nassau_Z_abbreviated" : "바하마 시간",
"America/Nassau_Z_short" : "EST",
"America/New_York_Z_abbreviated" : "미국 (뉴욕)",
"America/New_York_Z_short" : "EST",
"America/Noronha_Z_abbreviated" : "브라질 (노롱야)",
"America/Noronha_Z_short" : "FNT",
"America/North_Dakota/Beulah_Z_abbreviated" : "미국 (Beulah)",
"America/North_Dakota/Beulah_Z_short" : "MST",
"America/North_Dakota/Center_Z_abbreviated" : "미국 (중부, 노스다코타)",
"America/North_Dakota/Center_Z_short" : "MST",
"America/North_Dakota/New_Salem_Z_abbreviated" : "미국 (노스 다코타주, 뉴살렘)",
"America/North_Dakota/New_Salem_Z_short" : "MST",
"America/Ojinaga_Z_abbreviated" : "멕시코 (Ojinaga)",
"America/Ojinaga_Z_short" : "CST",
"America/Panama_Z_abbreviated" : "파나마 시간",
"America/Panama_Z_short" : "EST",
"America/Pangnirtung_Z_abbreviated" : "캐나다 (팡니르퉁)",
"America/Pangnirtung_Z_short" : "AST",
"America/Paramaribo_Z_abbreviated" : "수리남 시간",
"America/Paramaribo_Z_short" : "NEGT",
"America/Phoenix_Z_abbreviated" : "미국 (피닉스)",
"America/Phoenix_Z_short" : "MST",
"America/Port-au-Prince_Z_abbreviated" : "아이티 시간",
"America/Port-au-Prince_Z_short" : "EST",
"America/Port_of_Spain_Z_abbreviated" : "트리니다드 토바고 시간",
"America/Port_of_Spain_Z_short" : "AST",
"America/Porto_Velho_Z_abbreviated" : "브라질 (포르토 벨로)",
"America/Porto_Velho_Z_short" : "AMT",
"America/Puerto_Rico_Z_abbreviated" : "푸에르토리코 시간",
"America/Puerto_Rico_Z_short" : "AST",
"America/Rankin_Inlet_Z_abbreviated" : "캐나다 (랭킹 인렛)",
"America/Rankin_Inlet_Z_short" : "CST",
"America/Recife_Z_abbreviated" : "브라질 (레시페)",
"America/Recife_Z_short" : "BRT",
"America/Regina_Z_abbreviated" : "캐나다 (리자이나)",
"America/Regina_Z_short" : "CST",
"America/Resolute_Z_abbreviated" : "캐나다 (리졸루트)",
"America/Resolute_Z_short" : "CST",
"America/Rio_Branco_Z_abbreviated" : "브라질 (리오 브랑코)",
"America/Rio_Branco_Z_short" : "ACT (아크레)",
"America/Santa_Isabel_Z_abbreviated" : "멕시코 (Santa Isabel)",
"America/Santa_Isabel_Z_short" : "PST",
"America/Santarem_Z_abbreviated" : "브라질 (산타렘)",
"America/Santarem_Z_short" : "AMT",
"America/Santiago_Z_abbreviated" : "칠레 (산티아고)",
"America/Santiago_Z_short" : "CLST",
"America/Santo_Domingo_Z_abbreviated" : "도미니카 공화국 시간",
"America/Santo_Domingo_Z_short" : "GMT-04:30",
"America/Sao_Paulo_Z_abbreviated" : "브라질 (상파울로)",
"America/Sao_Paulo_Z_short" : "BRT",
"America/St_Johns_Z_abbreviated" : "캐나다 (세인트존)",
"America/St_Johns_Z_short" : "NST",
"America/St_Kitts_Z_abbreviated" : "세인트크리스토퍼 네비스 시간",
"America/St_Kitts_Z_short" : "AST",
"America/St_Lucia_Z_abbreviated" : "세인트루시아 시간",
"America/St_Lucia_Z_short" : "AST",
"America/St_Thomas_Z_abbreviated" : "미국령 버진 아일랜드 시간",
"America/St_Thomas_Z_short" : "AST",
"America/St_Vincent_Z_abbreviated" : "세인트빈센트그레나딘 시간",
"America/St_Vincent_Z_short" : "AST",
"America/Tegucigalpa_Z_abbreviated" : "온두라스 시간",
"America/Tegucigalpa_Z_short" : "CST",
"America/Tijuana_Z_abbreviated" : "멕시코 (티후아나)",
"America/Tijuana_Z_short" : "PST",
"America/Toronto_Z_abbreviated" : "캐나다 (토론토)",
"America/Toronto_Z_short" : "EST",
"America/Tortola_Z_abbreviated" : "영국령 버진 아일랜드 시간",
"America/Tortola_Z_short" : "AST",
"America/Vancouver_Z_abbreviated" : "캐나다 (벤쿠버)",
"America/Vancouver_Z_short" : "PST",
"America/Winnipeg_Z_abbreviated" : "캐나다 (위니펙)",
"America/Winnipeg_Z_short" : "CST",
"Antarctica/Casey_Z_abbreviated" : "남극 대륙 (케이시)",
"Antarctica/Casey_Z_short" : "AWST",
"Antarctica/Davis_Z_abbreviated" : "남극 대륙 (데이비스)",
"Antarctica/Davis_Z_short" : "DAVT",
"Antarctica/DumontDUrville_Z_abbreviated" : "남극 대륙 (뒤몽 뒤르빌)",
"Antarctica/DumontDUrville_Z_short" : "DDUT",
"Antarctica/Macquarie_Z_abbreviated" : "남극 대륙 (Macquarie)",
"Antarctica/Macquarie_Z_short" : "AEDT",
"Antarctica/McMurdo_Z_abbreviated" : "남극 대륙 (맥머도)",
"Antarctica/McMurdo_Z_short" : "NZST",
"Antarctica/Palmer_Z_abbreviated" : "남극 대륙 (파머)",
"Antarctica/Palmer_Z_short" : "ART",
"Antarctica/Rothera_Z_abbreviated" : "남극 대륙 (로데라)",
"Antarctica/Rothera_Z_short" : "ROTT",
"Antarctica/Syowa_Z_abbreviated" : "남극 대륙 (쇼와)",
"Antarctica/Syowa_Z_short" : "SYOT",
"Antarctica/Vostok_Z_abbreviated" : "남극 대륙 (보스토크)",
"Antarctica/Vostok_Z_short" : "VOST",
"Asia/Aden_Z_abbreviated" : "예멘 시간",
"Asia/Aden_Z_short" : "AST(아라비아)",
"Asia/Almaty_Z_abbreviated" : "카자흐스탄 (알마티)",
"Asia/Almaty_Z_short" : "ALMT",
"Asia/Amman_Z_abbreviated" : "요르단 시간",
"Asia/Amman_Z_short" : "EET",
"Asia/Anadyr_Z_abbreviated" : "러시아 (아나디리)",
"Asia/Anadyr_Z_short" : "ANAT",
"Asia/Aqtau_Z_abbreviated" : "카자흐스탄 (아크타우)",
"Asia/Aqtau_Z_short" : "SHET",
"Asia/Aqtobe_Z_abbreviated" : "카자흐스탄 (악토브)",
"Asia/Aqtobe_Z_short" : "AKTT",
"Asia/Ashgabat_Z_abbreviated" : "투르크메니스탄 시간",
"Asia/Ashgabat_Z_short" : "ASHT",
"Asia/Baghdad_Z_abbreviated" : "이라크 시간",
"Asia/Baghdad_Z_short" : "AST(아라비아)",
"Asia/Bahrain_Z_abbreviated" : "바레인 시간",
"Asia/Bahrain_Z_short" : "GST",
"Asia/Baku_Z_abbreviated" : "아제르바이잔 시간",
"Asia/Baku_Z_short" : "BAKT",
"Asia/Bangkok_Z_abbreviated" : "태국 시간",
"Asia/Bangkok_Z_short" : "ICT",
"Asia/Beirut_Z_abbreviated" : "레바논 시간",
"Asia/Beirut_Z_short" : "EET",
"Asia/Bishkek_Z_abbreviated" : "키르기스스탄 시간",
"Asia/Bishkek_Z_short" : "FRUT",
"Asia/Brunei_Z_abbreviated" : "브루나이 시간",
"Asia/Brunei_Z_short" : "BNT",
"Asia/Choibalsan_Z_abbreviated" : "몽골 (초이발산)",
"Asia/Choibalsan_Z_short" : "ULAT",
"Asia/Chongqing_Z_abbreviated" : "중국 (충칭)",
"Asia/Chongqing_Z_short" : "LONT",
"Asia/Colombo_Z_abbreviated" : "스리랑카 시간",
"Asia/Colombo_Z_short" : "IST",
"Asia/Damascus_Z_abbreviated" : "시리아 시간",
"Asia/Damascus_Z_short" : "EET",
"Asia/Dhaka_Z_abbreviated" : "방글라데시 시간",
"Asia/Dhaka_Z_short" : "DACT",
"Asia/Dili_Z_abbreviated" : "동티모르 시간",
"Asia/Dili_Z_short" : "TLT",
"Asia/Dubai_Z_abbreviated" : "아랍에미리트 연합 시간",
"Asia/Dubai_Z_short" : "GST",
"Asia/Dushanbe_Z_abbreviated" : "타지키스탄 시간",
"Asia/Dushanbe_Z_short" : "DUST",
"Asia/Gaza_Z_abbreviated" : "팔레스타인 지구 시간",
"Asia/Gaza_Z_short" : "IST (이스라엘)",
"Asia/Harbin_Z_abbreviated" : "중국 (하얼빈)",
"Asia/Harbin_Z_short" : "CHAT",
"Asia/Hebron_Z_abbreviated" : "팔레스타인 지구 시간",
"Asia/Hebron_Z_short" : "IST (이스라엘)",
"Asia/Ho_Chi_Minh_Z_abbreviated" : "베트남 시간",
"Asia/Ho_Chi_Minh_Z_short" : "ICT",
"Asia/Hong_Kong_Z_abbreviated" : "홍콩, 중국 특별행정구 시간",
"Asia/Hong_Kong_Z_short" : "HKT",
"Asia/Hovd_Z_abbreviated" : "몽골 (호브드)",
"Asia/Hovd_Z_short" : "HOVT",
"Asia/Irkutsk_Z_abbreviated" : "러시아 (이르쿠츠크)",
"Asia/Irkutsk_Z_short" : "IRKT",
"Asia/Jakarta_Z_abbreviated" : "인도네시아 (자카르타)",
"Asia/Jakarta_Z_short" : "WIT",
"Asia/Jerusalem_Z_abbreviated" : "이스라엘 시간",
"Asia/Jerusalem_Z_short" : "IST (이스라엘)",
"Asia/Kabul_Z_abbreviated" : "아프가니스탄 시간",
"Asia/Kabul_Z_short" : "AFT",
"Asia/Kamchatka_Z_abbreviated" : "러시아 (캄차카)",
"Asia/Kamchatka_Z_short" : "PETT",
"Asia/Karachi_Z_abbreviated" : "파키스탄 시간",
"Asia/Karachi_Z_short" : "KART",
"Asia/Kashgar_Z_abbreviated" : "중국 (카슈가르)",
"Asia/Kashgar_Z_short" : "KAST",
"Asia/Kathmandu_Z_abbreviated" : "네팔 시간",
"Asia/Kathmandu_Z_short" : "NPT",
"Asia/Kolkata_Z_abbreviated" : "인도 시간",
"Asia/Kolkata_Z_short" : "IST",
"Asia/Krasnoyarsk_Z_abbreviated" : "러시아 (크라스노야르스크)",
"Asia/Krasnoyarsk_Z_short" : "KRAT",
"Asia/Kuala_Lumpur_Z_abbreviated" : "말레이시아 (쿠알라룸푸르)",
"Asia/Kuala_Lumpur_Z_short" : "MALT",
"Asia/Kuching_Z_abbreviated" : "말레이시아 (쿠칭)",
"Asia/Kuching_Z_short" : "BORT",
"Asia/Kuwait_Z_abbreviated" : "쿠웨이트 시간",
"Asia/Kuwait_Z_short" : "AST(아라비아)",
"Asia/Macau_Z_abbreviated" : "마카오, 중국 특별행정구 시간",
"Asia/Macau_Z_short" : "MOT",
"Asia/Magadan_Z_abbreviated" : "러시아 (마가단)",
"Asia/Magadan_Z_short" : "MAGT",
"Asia/Manila_Z_abbreviated" : "필리핀 시간",
"Asia/Manila_Z_short" : "PHT",
"Asia/Muscat_Z_abbreviated" : "오만 시간",
"Asia/Muscat_Z_short" : "GST",
"Asia/Nicosia_Z_abbreviated" : "사이프러스 시간",
"Asia/Nicosia_Z_short" : "EET",
"Asia/Novokuznetsk_Z_abbreviated" : "러시아 (Novokuznetsk)",
"Asia/Novokuznetsk_Z_short" : "KRAT",
"Asia/Novosibirsk_Z_abbreviated" : "러시아 (노보시비르스크)",
"Asia/Novosibirsk_Z_short" : "NOVT",
"Asia/Omsk_Z_abbreviated" : "러시아 (옴스크)",
"Asia/Omsk_Z_short" : "OMST",
"Asia/Oral_Z_abbreviated" : "카자흐스탄 (오랄)",
"Asia/Oral_Z_short" : "URAT",
"Asia/Phnom_Penh_Z_abbreviated" : "캄보디아 시간",
"Asia/Phnom_Penh_Z_short" : "ICT",
"Asia/Pontianak_Z_abbreviated" : "인도네시아 (폰티아나크)",
"Asia/Pontianak_Z_short" : "CIT",
"Asia/Qatar_Z_abbreviated" : "카타르 시간",
"Asia/Qatar_Z_short" : "GST",
"Asia/Qyzylorda_Z_abbreviated" : "카자흐스탄 (키질로르다)",
"Asia/Qyzylorda_Z_short" : "KIZT",
"Asia/Rangoon_Z_abbreviated" : "미얀마 시간",
"Asia/Rangoon_Z_short" : "MMT",
"Asia/Riyadh87_Z_abbreviated" : "Asia/Riyadh87 시간",
"Asia/Riyadh87_Z_short" : "GMT+03:07:04",
"Asia/Riyadh88_Z_abbreviated" : "Asia/Riyadh88 시간",
"Asia/Riyadh88_Z_short" : "GMT+03:07:04",
"Asia/Riyadh89_Z_abbreviated" : "Asia/Riyadh89 시간",
"Asia/Riyadh89_Z_short" : "GMT+03:07:04",
"Asia/Riyadh_Z_abbreviated" : "사우디아라비아 시간",
"Asia/Riyadh_Z_short" : "AST(아라비아)",
"Asia/Sakhalin_Z_abbreviated" : "러시아 (사할린)",
"Asia/Sakhalin_Z_short" : "SAKT",
"Asia/Samarkand_Z_abbreviated" : "우즈베키스탄 (사마르칸트)",
"Asia/Samarkand_Z_short" : "SAMT (사마르칸트)",
"Asia/Seoul_Z_abbreviated" : "KST",
"Asia/Seoul_Z_short" : "KST",
"Asia/Shanghai_Z_abbreviated" : "중국 (상하이)",
"Asia/Shanghai_Z_short" : "CST (중국)",
"Asia/Singapore_Z_abbreviated" : "싱가포르 시간",
"Asia/Singapore_Z_short" : "SGT",
"Asia/Taipei_Z_abbreviated" : "대만 시간",
"Asia/Taipei_Z_short" : "CST (TW)",
"Asia/Tbilisi_Z_abbreviated" : "그루지야 시간",
"Asia/Tbilisi_Z_short" : "TBIT",
"Asia/Tehran_Z_abbreviated" : "이란 시간",
"Asia/Tehran_Z_short" : "IRST",
"Asia/Thimphu_Z_abbreviated" : "부탄 시간",
"Asia/Thimphu_Z_short" : "IST",
"Asia/Tokyo_Z_abbreviated" : "일본 시간",
"Asia/Tokyo_Z_short" : "JST",
"Asia/Ulaanbaatar_Z_abbreviated" : "몽골 (울란바토르)",
"Asia/Ulaanbaatar_Z_short" : "ULAT",
"Asia/Urumqi_Z_abbreviated" : "중국 (우루무치)",
"Asia/Urumqi_Z_short" : "URUT",
"Asia/Vientiane_Z_abbreviated" : "라오스 시간",
"Asia/Vientiane_Z_short" : "ICT",
"Asia/Vladivostok_Z_abbreviated" : "러시아 (블라디보스토크)",
"Asia/Vladivostok_Z_short" : "VLAT",
"Asia/Yakutsk_Z_abbreviated" : "러시아 (야쿠츠크)",
"Asia/Yakutsk_Z_short" : "YAKT",
"Asia/Yekaterinburg_Z_abbreviated" : "러시아 (예카테린부르크)",
"Asia/Yekaterinburg_Z_short" : "SVET",
"Asia/Yerevan_Z_abbreviated" : "아르메니아 시간",
"Asia/Yerevan_Z_short" : "YERT",
"Atlantic/Bermuda_Z_abbreviated" : "버뮤다 시간",
"Atlantic/Bermuda_Z_short" : "AST",
"Atlantic/Cape_Verde_Z_abbreviated" : "까뽀베르데 시간",
"Atlantic/Cape_Verde_Z_short" : "CVT",
"Atlantic/Reykjavik_Z_abbreviated" : "아이슬란드 시간",
"Atlantic/Reykjavik_Z_short" : "GMT",
"Atlantic/South_Georgia_Z_abbreviated" : "사우스조지아 사우스샌드위치 제도 시간",
"Atlantic/South_Georgia_Z_short" : "GST (사우스 조지아)",
"Atlantic/St_Helena_Z_abbreviated" : "세인트헬레나 시간",
"Atlantic/St_Helena_Z_short" : "GMT",
"Atlantic/Stanley_Z_abbreviated" : "포클랜드 제도 시간",
"Atlantic/Stanley_Z_short" : "FKT",
"Australia/Adelaide_Z_abbreviated" : "오스트레일리아 (애들레이드)",
"Australia/Adelaide_Z_short" : "ACST",
"Australia/Brisbane_Z_abbreviated" : "오스트레일리아 (브리스베인)",
"Australia/Brisbane_Z_short" : "AEST",
"Australia/Darwin_Z_abbreviated" : "오스트레일리아 (다윈)",
"Australia/Darwin_Z_short" : "ACST",
"Australia/Hobart_Z_abbreviated" : "오스트레일리아 (호바트)",
"Australia/Hobart_Z_short" : "AEDT",
"Australia/Lord_Howe_Z_abbreviated" : "오스트레일리아 (로드 하우)",
"Australia/Lord_Howe_Z_short" : "AEST",
"Australia/Melbourne_Z_abbreviated" : "오스트레일리아 (멜버른)",
"Australia/Melbourne_Z_short" : "AEST",
"Australia/Perth_Z_abbreviated" : "오스트레일리아 (퍼스)",
"Australia/Perth_Z_short" : "AWST",
"Australia/Sydney_Z_abbreviated" : "오스트레일리아 (시드니)",
"Australia/Sydney_Z_short" : "AEST",
"BC" : "기원전",
"DateTimeCombination" : "{1} {0}",
"DateTimeTimezoneCombination" : "{1} {0} {2}",
"DateTimezoneCombination" : "{1} {2}",
"EST_Z_abbreviated" : "GMT-05:00",
"EST_Z_short" : "GMT-05:00",
"Etc/GMT-14_Z_abbreviated" : "GMT+14:00",
"Etc/GMT-14_Z_short" : "GMT+14:00",
"Etc/GMT_Z_abbreviated" : "GMT+00:00",
"Etc/GMT_Z_short" : "GMT+00:00",
"Europe/Amsterdam_Z_abbreviated" : "네덜란드 시간",
"Europe/Amsterdam_Z_short" : "CET",
"Europe/Andorra_Z_abbreviated" : "안도라 시간",
"Europe/Andorra_Z_short" : "CET",
"Europe/Athens_Z_abbreviated" : "그리스 시간",
"Europe/Athens_Z_short" : "EET",
"Europe/Belgrade_Z_abbreviated" : "세르비아 시간",
"Europe/Belgrade_Z_short" : "CET",
"Europe/Berlin_Z_abbreviated" : "독일 시간",
"Europe/Berlin_Z_short" : "CET",
"Europe/Brussels_Z_abbreviated" : "벨기에 시간",
"Europe/Brussels_Z_short" : "CET",
"Europe/Bucharest_Z_abbreviated" : "루마니아 시간",
"Europe/Bucharest_Z_short" : "EET",
"Europe/Budapest_Z_abbreviated" : "헝가리 시간",
"Europe/Budapest_Z_short" : "CET",
"Europe/Chisinau_Z_abbreviated" : "몰도바 시간",
"Europe/Chisinau_Z_short" : "MSK",
"Europe/Copenhagen_Z_abbreviated" : "덴마크 시간",
"Europe/Copenhagen_Z_short" : "CET",
"Europe/Gibraltar_Z_abbreviated" : "지브롤터 시간",
"Europe/Gibraltar_Z_short" : "CET",
"Europe/Helsinki_Z_abbreviated" : "핀란드 시간",
"Europe/Helsinki_Z_short" : "EET",
"Europe/Istanbul_Z_abbreviated" : "터키 시간",
"Europe/Istanbul_Z_short" : "EET",
"Europe/Kaliningrad_Z_abbreviated" : "러시아 (칼리닌그라드)",
"Europe/Kaliningrad_Z_short" : "MSK",
"Europe/Kiev_Z_abbreviated" : "우크라이나 (키예프)",
"Europe/Kiev_Z_short" : "MSK",
"Europe/Lisbon_Z_abbreviated" : "포르투갈 (리스본)",
"Europe/Lisbon_Z_short" : "CET",
"Europe/London_Z_abbreviated" : "영국 시간",
"Europe/London_Z_short" : "GMT+01:00",
"Europe/Luxembourg_Z_abbreviated" : "룩셈부르크 시간",
"Europe/Luxembourg_Z_short" : "CET",
"Europe/Madrid_Z_abbreviated" : "스페인 (마드리드)",
"Europe/Madrid_Z_short" : "CET",
"Europe/Malta_Z_abbreviated" : "몰타 시간",
"Europe/Malta_Z_short" : "CET",
"Europe/Minsk_Z_abbreviated" : "벨라루스 시간",
"Europe/Minsk_Z_short" : "MSK",
"Europe/Monaco_Z_abbreviated" : "모나코 시간",
"Europe/Monaco_Z_short" : "CET",
"Europe/Moscow_Z_abbreviated" : "러시아 (모스크바)",
"Europe/Moscow_Z_short" : "MSK",
"Europe/Oslo_Z_abbreviated" : "노르웨이 시간",
"Europe/Oslo_Z_short" : "CET",
"Europe/Paris_Z_abbreviated" : "프랑스 시간",
"Europe/Paris_Z_short" : "CET",
"Europe/Prague_Z_abbreviated" : "체코 시간",
"Europe/Prague_Z_short" : "CET",
"Europe/Riga_Z_abbreviated" : "라트비아 시간",
"Europe/Riga_Z_short" : "MSK",
"Europe/Rome_Z_abbreviated" : "이탈리아 시간",
"Europe/Rome_Z_short" : "CET",
"Europe/Samara_Z_abbreviated" : "러시아 (사마라)",
"Europe/Samara_Z_short" : "KUYT",
"Europe/Simferopol_Z_abbreviated" : "우크라이나 (심페로폴)",
"Europe/Simferopol_Z_short" : "MSK",
"Europe/Sofia_Z_abbreviated" : "불가리아 시간",
"Europe/Sofia_Z_short" : "EET",
"Europe/Stockholm_Z_abbreviated" : "스웨덴 시간",
"Europe/Stockholm_Z_short" : "CET",
"Europe/Tallinn_Z_abbreviated" : "에스토니아 시간",
"Europe/Tallinn_Z_short" : "MSK",
"Europe/Tirane_Z_abbreviated" : "알바니아 시간",
"Europe/Tirane_Z_short" : "CET",
"Europe/Uzhgorod_Z_abbreviated" : "우크라이나 (우주고로트)",
"Europe/Uzhgorod_Z_short" : "MSK",
"Europe/Vaduz_Z_abbreviated" : "리히텐슈타인 시간",
"Europe/Vaduz_Z_short" : "CET",
"Europe/Vienna_Z_abbreviated" : "오스트리아 시간",
"Europe/Vienna_Z_short" : "CET",
"Europe/Vilnius_Z_abbreviated" : "리투아니아 시간",
"Europe/Vilnius_Z_short" : "MSK",
"Europe/Volgograd_Z_abbreviated" : "러시아 (볼고그라트)",
"Europe/Volgograd_Z_short" : "VOLT",
"Europe/Warsaw_Z_abbreviated" : "폴란드 시간",
"Europe/Warsaw_Z_short" : "CET",
"Europe/Zaporozhye_Z_abbreviated" : "우크라이나 (자포로지예)",
"Europe/Zaporozhye_Z_short" : "MSK",
"Europe/Zurich_Z_abbreviated" : "스위스 시간",
"Europe/Zurich_Z_short" : "CET",
"HMS_long" : "{0} {1} {2}",
"HMS_short" : "{0}:{1}:{2}",
"HM_abbreviated" : "a h시 m분",
"HM_short" : "a h:mm",
"H_abbreviated" : "a h시",
"Indian/Antananarivo_Z_abbreviated" : "마다가스카르 시간",
"Indian/Antananarivo_Z_short" : "EAT",
"Indian/Chagos_Z_abbreviated" : "영국령인도양식민지 시간",
"Indian/Chagos_Z_short" : "IOT",
"Indian/Christmas_Z_abbreviated" : "크리스마스섬 시간",
"Indian/Christmas_Z_short" : "CXT",
"Indian/Cocos_Z_abbreviated" : "코코스제도 시간",
"Indian/Cocos_Z_short" : "CCT",
"Indian/Comoro_Z_abbreviated" : "코모로스 시간",
"Indian/Comoro_Z_short" : "EAT",
"Indian/Kerguelen_Z_abbreviated" : "프랑스 남부 지방 시간",
"Indian/Kerguelen_Z_short" : "TFT",
"Indian/Mahe_Z_abbreviated" : "쉐이쉘 시간",
"Indian/Mahe_Z_short" : "SCT",
"Indian/Maldives_Z_abbreviated" : "몰디브 시간",
"Indian/Maldives_Z_short" : "MVT",
"Indian/Mauritius_Z_abbreviated" : "모리셔스 시간",
"Indian/Mauritius_Z_short" : "MUT",
"Indian/Mayotte_Z_abbreviated" : "마요티 시간",
"Indian/Mayotte_Z_short" : "EAT",
"Indian/Reunion_Z_abbreviated" : "리유니온 시간",
"Indian/Reunion_Z_short" : "RET",
"MD_abbreviated" : "MMM d일",
"MD_long" : "MMMM d일",
"MD_short" : "M. d.",
"M_abbreviated" : "MMM",
"M_long" : "MMMM",
"Pacific/Apia_Z_abbreviated" : "사모아 시간",
"Pacific/Apia_Z_short" : "BST (베링)",
"Pacific/Auckland_Z_abbreviated" : "뉴질랜드 (오클랜드)",
"Pacific/Auckland_Z_short" : "NZST",
"Pacific/Chuuk_Z_abbreviated" : "미크로네시아 (트루크)",
"Pacific/Chuuk_Z_short" : "TRUT",
"Pacific/Efate_Z_abbreviated" : "바누아투 시간",
"Pacific/Efate_Z_short" : "VUT",
"Pacific/Fakaofo_Z_abbreviated" : "토켈라우 시간",
"Pacific/Fakaofo_Z_short" : "TKT",
"Pacific/Fiji_Z_abbreviated" : "피지 시간",
"Pacific/Fiji_Z_short" : "FJT",
"Pacific/Funafuti_Z_abbreviated" : "투발루 시간",
"Pacific/Funafuti_Z_short" : "TVT",
"Pacific/Gambier_Z_abbreviated" : "프랑스령 폴리네시아 (감비어)",
"Pacific/Gambier_Z_short" : "GAMT",
"Pacific/Guadalcanal_Z_abbreviated" : "솔로몬 제도 시간",
"Pacific/Guadalcanal_Z_short" : "SBT",
"Pacific/Guam_Z_abbreviated" : "괌 시간",
"Pacific/Guam_Z_short" : "GST (괌)",
"Pacific/Honolulu_Z_abbreviated" : "미국 (호놀룰루)",
"Pacific/Honolulu_Z_short" : "AHST",
"Pacific/Johnston_Z_abbreviated" : "미국령 해외 제도 (존스톤)",
"Pacific/Johnston_Z_short" : "AHST",
"Pacific/Majuro_Z_abbreviated" : "마샬 군도 (마주로)",
"Pacific/Majuro_Z_short" : "MHT",
"Pacific/Midway_Z_abbreviated" : "미국령 해외 제도 (미드웨이)",
"Pacific/Midway_Z_short" : "BST (베링)",
"Pacific/Nauru_Z_abbreviated" : "나우루 시간",
"Pacific/Nauru_Z_short" : "NRT",
"Pacific/Niue_Z_abbreviated" : "니우에 시간",
"Pacific/Niue_Z_short" : "NUT",
"Pacific/Norfolk_Z_abbreviated" : "노퍽섬 시간",
"Pacific/Norfolk_Z_short" : "NFT",
"Pacific/Noumea_Z_abbreviated" : "뉴 칼레도니아 시간",
"Pacific/Noumea_Z_short" : "NCT",
"Pacific/Pago_Pago_Z_abbreviated" : "아메리칸 사모아 시간",
"Pacific/Pago_Pago_Z_short" : "BST (베링)",
"Pacific/Palau_Z_abbreviated" : "팔라우 시간",
"Pacific/Palau_Z_short" : "PWT",
"Pacific/Pitcairn_Z_abbreviated" : "핏케언섬 시간",
"Pacific/Pitcairn_Z_short" : "PNT",
"Pacific/Port_Moresby_Z_abbreviated" : "파푸아뉴기니 시간",
"Pacific/Port_Moresby_Z_short" : "PGT",
"Pacific/Rarotonga_Z_abbreviated" : "쿡제도 시간",
"Pacific/Rarotonga_Z_short" : "CKT",
"Pacific/Saipan_Z_abbreviated" : "북마리아나제도 시간",
"Pacific/Saipan_Z_short" : "MPT",
"Pacific/Tarawa_Z_abbreviated" : "키리바시 (타라와)",
"Pacific/Tarawa_Z_short" : "GILT",
"Pacific/Tongatapu_Z_abbreviated" : "통가 시간",
"Pacific/Tongatapu_Z_short" : "TOT",
"Pacific/Wake_Z_abbreviated" : "미국령 해외 제도 (웨이크)",
"Pacific/Wake_Z_short" : "WAKT",
"Pacific/Wallis_Z_abbreviated" : "왈리스-푸투나 제도 시간",
"Pacific/Wallis_Z_short" : "WFT",
"RelativeTime/oneUnit" : "{0} 전",
"RelativeTime/twoUnits" : "{0} {1} 전",
"TimeTimezoneCombination" : "{0} {2}",
"WET_Z_abbreviated" : "GMT+00:00",
"WET_Z_short" : "GMT+00:00",
"WMD_abbreviated" : "MMM d일 (E)",
"WMD_long" : "M월 d일 EEEE",
"WMD_short" : "M. d. (E)",
"WYMD_abbreviated" : "y년 MMM d일 EEE",
"WYMD_long" : "y년 M월 d일 EEEE",
"WYMD_short" : "yy. M. d. EEE",
"W_abbreviated" : "EEE",
"W_long" : "EEEE",
"YMD_abbreviated" : "y년 MMM d일",
"YMD_full" : "yy. M. d.",
"YMD_long" : "y년 M월 d일",
"YMD_short" : "yy. M. d.",
"YM_long" : "y년 MMMM",
"currencyFormat" : "¤#,##0.00",
"currencyPatternPlural" : "e u",
"currencyPatternSingular" : "{0} {1}",
"dayperiod" : "오전/오후",
"decimalFormat" : "#,##0.###",
"decimalSeparator" : ".",
"exponentialSymbol" : "E",
"groupingSeparator" : ",",
"hour" : "간",
"hour_abbr" : "간",
"hours" : "간",
"hours_abbr" : "간",
"infinitySign" : "∞",
"listPatternEnd" : "{0}, {1}",
"listPatternMiddle" : "{0}, {1}",
"listPatternStart" : "{0}, {1}",
"listPatternTwo" : "{0}, {1}",
"minusSign" : "-",
"month" : "월",
"monthAprLong" : "4월",
"monthAprMedium" : "4월",
"monthAugLong" : "8월",
"monthAugMedium" : "8월",
"monthDecLong" : "12월",
"monthDecMedium" : "12월",
"monthFebLong" : "2월",
"monthFebMedium" : "2월",
"monthJanLong" : "1월",
"monthJanMedium" : "1월",
"monthJulLong" : "7월",
"monthJulMedium" : "7월",
"monthJunLong" : "6월",
"monthJunMedium" : "6월",
"monthMarLong" : "3월",
"monthMarMedium" : "3월",
"monthMayLong" : "5월",
"monthMayMedium" : "5월",
"monthNovLong" : "11월",
"monthNovMedium" : "11월",
"monthOctLong" : "10월",
"monthOctMedium" : "10월",
"monthSepLong" : "9월",
"monthSepMedium" : "9월",
"month_abbr" : "월",
"months" : "월",
"months_abbr" : "월",
"nanSymbol" : "NaN",
"numberZero" : "0",
"perMilleSign" : "‰",
"percentFormat" : "#,##0%",
"percentSign" : "%",
"periodAm" : "오전",
"periodPm" : "오후",
"plusSign" : "+",
"scientificFormat" : "#E0",
"today" : "오늘",
"tomorrow" : "내일",
"weekdayFriLong" : "금요일",
"weekdayFriMedium" : "금",
"weekdayMonLong" : "월요일",
"weekdayMonMedium" : "월",
"weekdaySatLong" : "토요일",
"weekdaySatMedium" : "토",
"weekdaySunLong" : "일요일",
"weekdaySunMedium" : "일",
"weekdayThuLong" : "목요일",
"weekdayThuMedium" : "목",
"weekdayTueLong" : "화요일",
"weekdayTueMedium" : "화",
"weekdayWedLong" : "수요일",
"weekdayWedMedium" : "수",
"yesterday" : "어제"
}
|
import {
assert,
CacheFactory
} from '../../_setup'
describe('CacheFactory#destroyAll', function () {
beforeEach(function () {
sinon.stub(CacheFactory.Cache.prototype, 'destroy')
})
afterEach(function () {
CacheFactory.Cache.prototype.destroy.restore()
})
it('should call destroy on all caches', function () {
var cache1 = this.cacheFactory.createCache(this.testId + 1)
var cache2 = this.cacheFactory.createCache(this.testId + 2)
var cache3 = this.cacheFactory.createCache(this.testId + 3)
this.cacheFactory.destroyAll()
assert.strictEqual(cache1.destroy.calledThrice, true)
assert.strictEqual(cache2.destroy.calledThrice, true)
assert.strictEqual(cache3.destroy.calledThrice, true)
assert.deepEqual(this.cacheFactory.caches, {})
})
})
|
"use strict";
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule keyMirror
* @typechecks static-only
*/
"use strict";
var invariant = require("./invariant")["default"];
/**
* Constructs an enumeration with keys equal to their value.
*
* For example:
*
* var COLORS = keyMirror({blue: null, red: null});
* var myColor = COLORS.blue;
* var isColorValid = !!COLORS[myColor];
*
* The last line could not be performed if the values of the generated enum were
* not equal to their keys.
*
* Input: {key1: val1, key2: val2}
* Output: {key1: key1, key2: key2}
*
* @param {object} obj
* @return {object}
*/
var keyMirror = function(obj) {
var ret = {};
var key;
(invariant(obj instanceof Object && !Array.isArray(obj)));
for (key in obj) {
if (!obj.hasOwnProperty(key)) {
continue;
}
ret[key] = key;
}
return ret;
};
exports["default"] = keyMirror; |
define(["require", "exports", "aurelia-router", "scripts/app-state"], function (require, exports, aur, app) {
var Login = (function () {
function Login(theRouter) {
this.theRouter = theRouter;
this.heading = "aurelia login page";
this.username = "Admin";
this.password = "xxx";
this.destination = "#/";
}
Login.prototype.activate = function (a, queryParams, c, d) {
if (queryParams && queryParams.origin)
this.destination = queryParams.origin;
};
Login.prototype.trylogin = function () {
if (app.state.login(this.username, this.password))
this.theRouter.navigate(this.destination, true);
else
alert("Access denied");
};
Login.inject = [aur.Router];
return Login;
})();
exports.Login = Login;
});
//# sourceMappingURL=login.js.map |
const arr = [ 1, 2, 3, 4, 5 ];
// const squares = arr.map( function(x) { return x * x } )
const squares = arr.map( x => x * x )
|
'use strict';
module.exports = [
'!**',
'!**/*',
'!**/*.md',
'!*.*',
'!*.js',
'!*/**/*',
'!*/**/*/',
'!*/*/*',
'!/**',
'!/**/',
'!/*/',
'!/*/**/*/',
'!/*/*/',
'!a/!b*',
'!a/!b/*',
'!a/*?b',
'!a/?',
'!a/?*b',
'!a/??b',
'!a/?b',
'!a/b/!*',
'!a/b/*',
'!a/b/c*',
'*',
'**',
'***',
'**********',
'**/',
'**/*',
'**/**',
'**/**/**',
'**/*.md',
'**/*?.md',
'**/.?.md',
'**/?.md',
'**/z*.js',
'*.js',
'*/',
'*/*',
'*/*/*',
'*/*/*/*',
'/*',
'/**',
'/**/',
'/**/*',
'/*/',
'/*/*',
'/*/**/',
'/*/**/*',
'/*/*/',
'/*/*/*',
'/*/*/*/*',
'/*/*/*/*/',
'?',
'?*?******?',
'?*?***?',
'?*?***?***????',
'?*?*?',
'?/',
'?/.?',
'?/.?*',
'?/?',
'?/?/?',
'??',
'??/??',
'???',
'????',
'a/*',
'a/*/',
'a/b/*',
'a/**/',
'a/**/b',
'a/**b',
'a/*/',
'a/*?b',
'a/?',
'a/?*b',
'a/??b',
'a/?b',
'a/b',
'a/b*',
'a/b/*',
'a/b/c',
'a/b/c/*',
'a/b/c/**/*.js',
'a/b/c/*.js',
];
|
'use strict';
var React = require('react');
var SvgIcon = require('../../svg-icon');
var ActionQueryBuilder = React.createClass({
displayName: 'ActionQueryBuilder',
render: function render() {
return React.createElement(
SvgIcon,
this.props,
React.createElement('path', { d: 'M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8zM12.5 7H11v6l5.25 3.15.75-1.23-4.5-2.67z' })
);
}
});
module.exports = ActionQueryBuilder; |
'use strict';
var routeHelper = require('../lib/route-helper');
var expect = require('chai').expect;
var _defaults = require('lodash.defaults');
describe('route-helper', function() {
it('returns "object" when a route has multiple return values', function() {
var doc = createAPIDoc({
returns: [
{ arg: 'max', type: 'number' },
{ arg: 'min', type: 'number' },
{ arg: 'avg', type: 'number' }
]
});
expect(doc.operations[0].type).to.equal('object');
});
it('converts path params when they exist in the route name', function() {
var doc = createAPIDoc({
accepts: [
{arg: 'id', type: 'string'}
],
path: '/test/:id'
});
var paramDoc = doc.operations[0].parameters[0];
expect(paramDoc.paramType).to.equal('path');
expect(paramDoc.name).to.equal('id');
expect(paramDoc.required).to.equal(false);
});
// FIXME need regex in routeHelper.acceptToParameter
xit('won\'t convert path params when they don\'t exist in the route name', function() {
var doc = createAPIDoc({
accepts: [
{arg: 'id', type: 'string'}
],
path: '/test/:identifier'
});
var paramDoc = doc.operations[0].parameters[0];
expect(paramDoc.paramType).to.equal('query');
});
it('correctly coerces param types', function() {
var doc = createAPIDoc({
accepts: [
{arg: 'binaryData', type: 'buffer'}
]
});
var paramDoc = doc.operations[0].parameters[0];
expect(paramDoc.paramType).to.equal('query');
expect(paramDoc.type).to.equal('string');
expect(paramDoc.format).to.equal('byte');
});
it('correctly converts return types (arrays)', function() {
var doc = createAPIDoc({
returns: [
{arg: 'data', type: ['customType']}
]
});
var opDoc = doc.operations[0];
expect(opDoc.type).to.equal('array');
expect(opDoc.items).to.eql({type: 'customType'});
});
it('correctly converts return types (format)', function() {
var doc = createAPIDoc({
returns: [
{arg: 'data', type: 'buffer'}
]
});
var opDoc = doc.operations[0];
expect(opDoc.type).to.equal('string');
expect(opDoc.format).to.equal('byte');
});
});
// Easy wrapper around createRoute
function createAPIDoc(def) {
return routeHelper.routeToAPIDoc(_defaults(def, {
path: '/test',
verb: 'GET',
method: 'test.get'
}));
}
|
import { Timer } from './Timer';
import { EventEmitter } from 'events';
class Pipeline extends EventEmitter {
constructor(name) {
super();
this.name = name;
this.steps = [];
this.results = {};
}
after(fn) {
let name = 'execution';
if (typeof fn === 'string') {
name = fn;
fn = arguments[1];
}
this.on(name + '-ended', fn);
}
afterStep(name, fn) {
this.on('step-ended', (evName) => {
if (name === evName) {
fn(this.results[name].result, this.results[name].elapsed);
}
});
}
before(fn) {
let name = 'execution';
if (typeof fn === 'string') {
name = fn;
fn = arguments[1];
}
this.on(name + '-started', fn);
}
addStep(name, lambda) {
this.steps.push([name, lambda]);
}
execute(jar) {
this.emit('execution-started', jar);
let elapsed = Timer.time(() => {
this._runSteps(jar);
});
this.emit('execution-ended', elapsed);
}
log() {
let args = [...arguments];
args[0] = '[' + this.name + '] ' + args[0];
console.log.apply(console, args);
}
stepResult(name) {
return this.results[name].result;
}
_runSteps(jar) {
for (let [name, lambda] of this.steps) {
this.emit('step-started', name);
let elapsed = this._runStep(jar, name, lambda);
this.emit('step-ended', name, elapsed);
}
}
_runStep(jar, name, lambda) {
let result = null;
let elapsed = Timer.time(() => {
result = lambda(jar);
});
this.results[name] = {elapsed, result };
return elapsed;
}
}
export {
Pipeline
};
|
// All material copyright ESRI, All Rights Reserved, unless otherwise specified.
// See http://js.arcgis.com/3.17/esri/copyright.txt for details.
//>>built
require({cache:{"url:esri/dijit/metadata/types/arcgis/content/templates/ContentTypCd.html":'\x3cdiv data-dojo-attach-point\x3d"containerNode"\x3e\r\n \x3cdiv data-dojo-type\x3d"esri/dijit/metadata/form/Element"\r\n data-dojo-props\x3d"target:\'ContentTypCd\',minOccurs:1,showHeader:false"\x3e\r\n \x3cdiv data-dojo-type\x3d"esri/dijit/metadata/form/Attribute"\r\n data-dojo-props\x3d"target:\'value\',minOccurs:1,showHeader:false"\x3e\r\n \x3cdiv data-dojo-type\x3d"esri/dijit/metadata/types/arcgis/form/InputSelectCode"\r\n data-dojo-props\x3d"codelistType:\'MD_CoverageContentTypeCode\'"\x3e\r\n \x3c/div\x3e \r\n \x3c/div\x3e\r\n \x3c/div\x3e\r\n\x3c/div\x3e'}});
define("esri/dijit/metadata/types/arcgis/content/ContentTypCd","dojo/_base/declare dojo/_base/lang dojo/has ../../../../../kernel ../../../base/Descriptor dojo/text!./templates/ContentTypCd.html".split(" "),function(a,b,c,d,e,f){a=a(e,{templateString:f});c("extend-esri")&&b.setObject("dijit.metadata.types.arcgis.content.ContentTypCd",a,d);return a}); |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var app = {
// Application Constructor
initialize: function() {
this.bindEvents();
},
// Bind Event Listeners
//
// Bind any events that are required on startup. Common events are:
// 'load', 'deviceready', 'offline', and 'online'.
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
// deviceready Event Handler
//
// The scope of 'this' is the event. In order to call the 'receivedEvent'
// function, we must explicity call 'app.receivedEvent(...);'
onDeviceReady: function() {
app.receivedEvent('deviceready');
},
// Update DOM on a Received Event
receivedEvent: function(id) {
console.log('Received Event: ' + id);
//angular.bootstrap(document,["myApp"]);
}
};
|
/**
* @license AngularJS v1.1.2-f0c6ebc0
* (c) 2010-2012 Google, Inc. http://angularjs.org
* License: MIT
*/
(function(window, angular, undefined) {
'use strict';
/**
* @ngdoc overview
* @name ngCookies
*/
angular.module('ngCookies', ['ng']).
/**
* @ngdoc object
* @name ngCookies.$cookies
* @requires $browser
*
* @description
* Provides read/write access to browser's cookies.
*
* Only a simple Object is exposed and by adding or removing properties to/from
* this object, new cookies are created/deleted at the end of current $eval.
*
* @example
*/
factory('$cookies', ['$rootScope', '$browser', function ($rootScope, $browser) {
var cookies = {},
lastCookies = {},
lastBrowserCookies,
runEval = false,
copy = angular.copy,
isUndefined = angular.isUndefined;
//creates a poller fn that copies all cookies from the $browser to service & inits the service
$browser.addPollFn(function() {
var currentCookies = $browser.cookies();
if (lastBrowserCookies != currentCookies) { //relies on browser.cookies() impl
lastBrowserCookies = currentCookies;
copy(currentCookies, lastCookies);
copy(currentCookies, cookies);
if (runEval) $rootScope.$apply();
}
})();
runEval = true;
//at the end of each eval, push cookies
//TODO: this should happen before the "delayed" watches fire, because if some cookies are not
// strings or browser refuses to store some cookies, we update the model in the push fn.
$rootScope.$watch(push);
return cookies;
/**
* Pushes all the cookies from the service to the browser and verifies if all cookies were stored.
*/
function push() {
var name,
value,
browserCookies,
updated;
//delete any cookies deleted in $cookies
for (name in lastCookies) {
if (isUndefined(cookies[name])) {
$browser.cookies(name, undefined);
}
}
//update all cookies updated in $cookies
for(name in cookies) {
value = cookies[name];
if (!angular.isString(value)) {
if (angular.isDefined(lastCookies[name])) {
cookies[name] = lastCookies[name];
} else {
delete cookies[name];
}
} else if (value !== lastCookies[name]) {
$browser.cookies(name, value);
updated = true;
}
}
//verify what was actually stored
if (updated){
updated = false;
browserCookies = $browser.cookies();
for (name in cookies) {
if (cookies[name] !== browserCookies[name]) {
//delete or reset all cookies that the browser dropped from $cookies
if (isUndefined(browserCookies[name])) {
delete cookies[name];
} else {
cookies[name] = browserCookies[name];
}
updated = true;
}
}
}
}
}]).
/**
* @ngdoc object
* @name ngCookies.$cookieStore
* @requires $cookies
*
* @description
* Provides a key-value (string-object) storage, that is backed by session cookies.
* Objects put or retrieved from this storage are automatically serialized or
* deserialized by angular's toJson/fromJson.
* @example
*/
factory('$cookieStore', ['$cookies', function($cookies) {
return {
/**
* @ngdoc method
* @name ngCookies.$cookieStore#get
* @methodOf ngCookies.$cookieStore
*
* @description
* Returns the value of given cookie key
*
* @param {string} key Id to use for lookup.
* @returns {Object} Deserialized cookie value.
*/
get: function(key) {
return angular.fromJson($cookies[key]);
},
/**
* @ngdoc method
* @name ngCookies.$cookieStore#put
* @methodOf ngCookies.$cookieStore
*
* @description
* Sets a value for given cookie key
*
* @param {string} key Id for the `value`.
* @param {Object} value Value to be stored.
*/
put: function(key, value) {
$cookies[key] = angular.toJson(value);
},
/**
* @ngdoc method
* @name ngCookies.$cookieStore#remove
* @methodOf ngCookies.$cookieStore
*
* @description
* Remove given cookie
*
* @param {string} key Id of the key-value pair to delete.
*/
remove: function(key) {
delete $cookies[key];
}
};
}]);
})(window, window.angular);
|
var expect = require('expect.js'),
cheerio = require('../'),
parse = cheerio.parse,
render = cheerio.render;
var html = function(str, options) {
options = options || {};
var dom = parse(str, options);
return render(dom);
};
describe('render', function() {
describe('(html)', function() {
it('should render <br /> tags correctly', function(done) {
var str = '<br />';
expect(html(str)).to.equal('<br/>');
done();
});
it('should shorten the "checked" attribute when it contains the value "checked"', function(done) {
var str = '<input checked/>';
expect(html(str)).to.equal('<input checked/>');
done();
});
it('should not shorten the "name" attribute when it contains the value "name"', function(done) {
var str = '<input name="name"/>';
expect(html(str)).to.equal('<input name="name"/>');
done();
});
it('should render comments correctly', function(done) {
var str = '<!-- comment -->';
expect(html(str)).to.equal('<!-- comment -->');
done();
});
it('should render whitespace by default', function(done) {
var str = '<a href="./haha.html">hi</a> <a href="./blah.html">blah</a>';
expect(html(str)).to.equal(str);
done();
});
it('should ignore whitespace if specified', function(done) {
var str = '<a href="./haha.html">hi</a> <a href="./blah.html">blah </a>';
expect(html(str, {ignoreWhitespace: true})).to.equal('<a href="./haha.html">hi</a><a href="./blah.html">blah </a>');
done();
});
});
});
|
define(["app/app",
"text!templates/postAttachmentTemplate.handlebars"], function(App, tpl) {
App.PostAttachmentView = Ember.View.extend({
templateName: 'post-attachment',
template: Ember.Handlebars.compile(tpl),
didInsertElement: function() {
var that = this;
this.$().on('upload-progress', function (event) {
that.get('controller').send('updateUploadProgress', event.fileName, event.percentComplete);
});
}
})
})
|
/*
* Angular Hammer v2
*
* Forked from https://github.com/randallb/angular-hammer
* Updated to support https://github.com/EightMedia/hammer.js
*
* Within an Angular.js application, allows you to specify custom behaviour on Hammer.js touch events.
*
* Usage, currently as attribute only:
*
* hm-tap="{expression}"
*
* You can change the default settings for the instance by adding a second attribute with options:
*
* hm-options="{drag: false, transform: false}"
*
* Include this file, and add `hmTouchevents` to your app's dependencies.
*
* Requires Hammer.js, tested with `v1.0.1 - 2013-02-26`.
*
*/
var hmTouchevents = angular.module('hmTouchevents', []),
hmGestures = ['hmHold:hold',
'hmTap:tap',
'hmDoubletap:doubletap',
'hmDrag:drag',
'hmDragup:dragup',
'hmDragdown:dragdown',
'hmDragleft:dragleft',
'hmDragright:dragright',
'hmSwipe:swipe',
'hmSwipeup:swipeup',
'hmSwipedown:swipedown',
'hmSwipeleft:swipeleft',
'hmSwiperight:swiperight',
'hmTransform:transform',
'hmRotate:rotate',
'hmPinch:pinch',
'hmPinchin:pinchin',
'hmPinchout:pinchout',
'hmTouch:touch',
'hmRelease:release'];
angular.forEach(hmGestures, function(name){
var directive = name.split(':'),
directiveName = directive[0],
eventName = directive[1];
hmTouchevents.directive(directiveName, ["$parse", function($parse) {
return {
scope: true,
link: function(scope, element, attr) {
var fn, opts;
fn = $parse(attr[directiveName]);
opts = $parse(attr["hmOptions"])(scope, {});
scope.hammer = scope.hammer || Hammer(element[0], opts);
return scope.hammer.on(eventName, function(event) {
return scope.$apply(function() {
return fn(scope, {
$event: event
});
});
});
}
};
}
]);
}); |
/* global assert, process, sinon, setup, suite, teardown, test */
var helpers = require('../../helpers');
var AEntity = require('core/a-entity');
var ANode = require('core/a-node');
var AScene = require('core/scene/a-scene');
/**
* Tests in this suite should not involve WebGL contexts or renderer.
* They operate with the assumption that attachedCallback is stubbed.
*
* Add tests that involve the renderer to the suite at the bottom that is meant
* to only be run locally since WebGL contexts break CI due to the headless
* environment.
*/
suite('a-scene (without renderer)', function () {
setup(function () {
var el = this.el = document.createElement('a-scene');
document.body.appendChild(el);
});
teardown(function () {
document.body.removeChild(this.el);
});
suite('createdCallback', function () {
test('initializes scene object', function () {
assert.equal(this.el.object3D.type, 'Scene');
});
});
suite('init', function () {
test('initializes scene object', function () {
var sceneEl = this.el;
sceneEl.isPlaying = false;
sceneEl.hasLoaded = true;
sceneEl.init();
assert.equal(sceneEl.isPlaying, false);
assert.equal(sceneEl.hasLoaded, false);
});
});
suite('reload', function () {
test('reload scene innerHTML to original value', function () {
var sceneEl = this.el;
sceneEl.innerHTML = 'NEW';
sceneEl.reload();
assert.equal(sceneEl.innerHTML, '');
});
test('reloads the scene and pauses', function () {
var sceneEl = this.el;
this.sinon.spy(AEntity.prototype, 'pause');
this.sinon.spy(ANode.prototype, 'load');
sceneEl.reload(true);
sinon.assert.called(AEntity.prototype.pause);
sinon.assert.called(ANode.prototype.load);
});
});
});
/**
* Skipped on CI using environment variable defined in the npm test script.
*/
helpers.getSkipCISuite()('a-scene (with renderer)', function () {
setup(function (done) {
var el;
var self = this;
AScene.prototype.setupRenderer.restore();
AScene.prototype.resize.restore();
AScene.prototype.render.restore();
process.nextTick(function () {
el = self.el = document.createElement('a-scene');
document.body.appendChild(el);
el.addEventListener('renderstart', function () {
done();
});
});
});
suite('attachedCallback', function () {
test('sets up renderer', function () {
assert.ok(this.el.renderer);
});
});
suite('detachedCallback', function () {
test('cancels request animation frame', function (done) {
var el = this.el;
var animationFrameID = el.animationFrameID;
var cancelSpy = this.sinon.spy(window, 'cancelAnimationFrame');
assert.ok(el.animationFrameID);
document.body.removeChild(el);
process.nextTick(function () {
assert.notOk(el.animationFrameID);
assert.ok(cancelSpy.calledWith(animationFrameID));
done();
});
});
test('does not destroy document.body', function (done) {
var el = this.el;
document.body.removeChild(el);
process.nextTick(function () {
assert.ok(document.body);
done();
});
});
});
test('calls behaviors', function () {
var scene = this.el;
var Component = { el: { isPlaying: true }, tick: function () {} };
this.sinon.spy(Component, 'tick');
scene.addBehavior(Component);
scene.render();
sinon.assert.called(Component.tick);
sinon.assert.calledWith(Component.tick, scene.time);
});
});
|
/* eslint no-console: 0 */
'use strict';
// This script runs a local SMTP server for testing
var SMTPServer = require('smtp-server').SMTPServer;
var crypto = require('crypto');
var counter = 0;
// Setup server
var server = new SMTPServer({
logger: false,
// not required but nice-to-have
banner: 'Welcome to My Nodemailer testserver',
// Accept messages up to 10 MB
size: 10 * 1024 * 1024,
// Setup authentication
// Allow only users with username 'testuser' and password 'testpass'
onAuth: function (auth, session, callback) {
// check username and password
if (auth.username === 'testuser' && auth.password === 'testpass') {
return callback(null, {
user: 'userdata'
});
}
return callback(new Error('Authentication failed'));
},
// Handle message stream
onData: function (stream, session, callback) {
var bytesize = 0;
var hash = crypto.createHash('md5');
stream.on('readable', function () {
var chunk;
while ((chunk = stream.read()) !== null) {
bytesize += chunk.length;
hash.update(chunk);
}
});
stream.on('end', function () {
var err;
if (stream.sizeExceeded) {
err = new Error('Error: message exceeds fixed maximum message size 10 MB');
err.responseCode = 552;
return callback(err);
}
hash = hash.digest('hex');
console.log('Received %s byte message %s (%s)', bytesize, hash, ++counter);
callback(null, 'Message hash ' + hash);
});
}
});
server.on('error', function (err) {
console.log(err.stack);
});
// start listening
server.listen(2525);
|
import { Point, ObservablePoint, Rectangle } from '../math';
import { sign, TextureCache } from '../utils';
import { BLEND_MODES } from '../const';
import Texture from '../textures/Texture';
import Container from '../display/Container';
const tempPoint = new Point();
/**
* The Sprite object is the base for all textured objects that are rendered to the screen
*
* A sprite can be created directly from an image like this:
*
* ```js
* let sprite = new PIXI.Sprite.fromImage('assets/image.png');
* ```
*
* The more efficient way to create sprites is using a {@link PIXI.Spritesheet}:
*
* ```js
* PIXI.loader.add("assets/spritesheet.json").load(setup);
*
* function setup() {
* let sheet = PIXI.loader.resources["assets/spritesheet.json"].spritesheet;
* let sprite = new PIXI.Sprite(sheet.textures["image.png"]);
* ...
* }
* ```
*
* @class
* @extends PIXI.Container
* @memberof PIXI
*/
export default class Sprite extends Container
{
/**
* @param {PIXI.Texture} texture - The texture for this sprite
*/
constructor(texture)
{
super();
/**
* The anchor sets the origin point of the texture.
* The default is 0,0 or taken from the {@link PIXI.Texture#defaultAnchor|Texture}
* passed to the constructor. A value of 0,0 means the texture's origin is the top left.
* Setting the anchor to 0.5,0.5 means the texture's origin is centered.
* Setting the anchor to 1,1 would mean the texture's origin point will be the bottom right corner.
* Note: Updating the {@link PIXI.Texture#defaultAnchor} after a Texture is
* created does _not_ update the Sprite's anchor values.
*
* @member {PIXI.ObservablePoint}
* @private
*/
this._anchor = new ObservablePoint(
this._onAnchorUpdate,
this,
(texture ? texture.defaultAnchor.x : 0),
(texture ? texture.defaultAnchor.y : 0)
);
/**
* The texture that the sprite is using
*
* @private
* @member {PIXI.Texture}
*/
this._texture = null;
/**
* The width of the sprite (this is initially set by the texture)
*
* @private
* @member {number}
*/
this._width = 0;
/**
* The height of the sprite (this is initially set by the texture)
*
* @private
* @member {number}
*/
this._height = 0;
/**
* The tint applied to the sprite. This is a hex value. A value of 0xFFFFFF will remove any tint effect.
*
* @private
* @member {number}
* @default 0xFFFFFF
*/
this._tint = null;
this._tintRGB = null;
this.tint = 0xFFFFFF;
/**
* The blend mode to be applied to the sprite. Apply a value of `PIXI.BLEND_MODES.NORMAL` to reset the blend mode.
*
* @member {number}
* @default PIXI.BLEND_MODES.NORMAL
* @see PIXI.BLEND_MODES
*/
this.blendMode = BLEND_MODES.NORMAL;
/**
* The shader that will be used to render the sprite. Set to null to remove a current shader.
*
* @member {PIXI.Filter|PIXI.Shader}
*/
this.shader = null;
/**
* An internal cached value of the tint.
*
* @private
* @member {number}
* @default 0xFFFFFF
*/
this.cachedTint = 0xFFFFFF;
// call texture setter
this.texture = texture || Texture.EMPTY;
/**
* this is used to store the vertex data of the sprite (basically a quad)
*
* @private
* @member {Float32Array}
*/
this.vertexData = new Float32Array(8);
/**
* This is used to calculate the bounds of the object IF it is a trimmed sprite
*
* @private
* @member {Float32Array}
*/
this.vertexTrimmedData = null;
this._transformID = -1;
this._textureID = -1;
this._transformTrimmedID = -1;
this._textureTrimmedID = -1;
/**
* Plugin that is responsible for rendering this element.
* Allows to customize the rendering process without overriding '_renderWebGL' & '_renderCanvas' methods.
*
* @member {string}
* @default 'sprite'
*/
this.pluginName = 'sprite';
}
/**
* When the texture is updated, this event will fire to update the scale and frame
*
* @private
*/
_onTextureUpdate()
{
this._textureID = -1;
this._textureTrimmedID = -1;
this.cachedTint = 0xFFFFFF;
// so if _width is 0 then width was not set..
if (this._width)
{
this.scale.x = sign(this.scale.x) * this._width / this._texture.orig.width;
}
if (this._height)
{
this.scale.y = sign(this.scale.y) * this._height / this._texture.orig.height;
}
}
/**
* Called when the anchor position updates.
*
* @private
*/
_onAnchorUpdate()
{
this._transformID = -1;
this._transformTrimmedID = -1;
}
/**
* calculates worldTransform * vertices, store it in vertexData
*/
calculateVertices()
{
if (this._transformID === this.transform._worldID && this._textureID === this._texture._updateID)
{
return;
}
this._transformID = this.transform._worldID;
this._textureID = this._texture._updateID;
// set the vertex data
const texture = this._texture;
const wt = this.transform.worldTransform;
const a = wt.a;
const b = wt.b;
const c = wt.c;
const d = wt.d;
const tx = wt.tx;
const ty = wt.ty;
const vertexData = this.vertexData;
const trim = texture.trim;
const orig = texture.orig;
const anchor = this._anchor;
let w0 = 0;
let w1 = 0;
let h0 = 0;
let h1 = 0;
if (trim)
{
// if the sprite is trimmed and is not a tilingsprite then we need to add the extra
// space before transforming the sprite coords.
w1 = trim.x - (anchor._x * orig.width);
w0 = w1 + trim.width;
h1 = trim.y - (anchor._y * orig.height);
h0 = h1 + trim.height;
}
else
{
w1 = -anchor._x * orig.width;
w0 = w1 + orig.width;
h1 = -anchor._y * orig.height;
h0 = h1 + orig.height;
}
// xy
vertexData[0] = (a * w1) + (c * h1) + tx;
vertexData[1] = (d * h1) + (b * w1) + ty;
// xy
vertexData[2] = (a * w0) + (c * h1) + tx;
vertexData[3] = (d * h1) + (b * w0) + ty;
// xy
vertexData[4] = (a * w0) + (c * h0) + tx;
vertexData[5] = (d * h0) + (b * w0) + ty;
// xy
vertexData[6] = (a * w1) + (c * h0) + tx;
vertexData[7] = (d * h0) + (b * w1) + ty;
}
/**
* calculates worldTransform * vertices for a non texture with a trim. store it in vertexTrimmedData
* This is used to ensure that the true width and height of a trimmed texture is respected
*/
calculateTrimmedVertices()
{
if (!this.vertexTrimmedData)
{
this.vertexTrimmedData = new Float32Array(8);
}
else if (this._transformTrimmedID === this.transform._worldID && this._textureTrimmedID === this._texture._updateID)
{
return;
}
this._transformTrimmedID = this.transform._worldID;
this._textureTrimmedID = this._texture._updateID;
// lets do some special trim code!
const texture = this._texture;
const vertexData = this.vertexTrimmedData;
const orig = texture.orig;
const anchor = this._anchor;
// lets calculate the new untrimmed bounds..
const wt = this.transform.worldTransform;
const a = wt.a;
const b = wt.b;
const c = wt.c;
const d = wt.d;
const tx = wt.tx;
const ty = wt.ty;
const w1 = -anchor._x * orig.width;
const w0 = w1 + orig.width;
const h1 = -anchor._y * orig.height;
const h0 = h1 + orig.height;
// xy
vertexData[0] = (a * w1) + (c * h1) + tx;
vertexData[1] = (d * h1) + (b * w1) + ty;
// xy
vertexData[2] = (a * w0) + (c * h1) + tx;
vertexData[3] = (d * h1) + (b * w0) + ty;
// xy
vertexData[4] = (a * w0) + (c * h0) + tx;
vertexData[5] = (d * h0) + (b * w0) + ty;
// xy
vertexData[6] = (a * w1) + (c * h0) + tx;
vertexData[7] = (d * h0) + (b * w1) + ty;
}
/**
*
* Renders the object using the WebGL renderer
*
* @private
* @param {PIXI.WebGLRenderer} renderer - The webgl renderer to use.
*/
_renderWebGL(renderer)
{
this.calculateVertices();
renderer.setObjectRenderer(renderer.plugins[this.pluginName]);
renderer.plugins[this.pluginName].render(this);
}
/**
* Renders the object using the Canvas renderer
*
* @private
* @param {PIXI.CanvasRenderer} renderer - The renderer
*/
_renderCanvas(renderer)
{
renderer.plugins[this.pluginName].render(this);
}
/**
* Updates the bounds of the sprite.
*
* @private
*/
_calculateBounds()
{
const trim = this._texture.trim;
const orig = this._texture.orig;
// First lets check to see if the current texture has a trim..
if (!trim || (trim.width === orig.width && trim.height === orig.height))
{
// no trim! lets use the usual calculations..
this.calculateVertices();
this._bounds.addQuad(this.vertexData);
}
else
{
// lets calculate a special trimmed bounds...
this.calculateTrimmedVertices();
this._bounds.addQuad(this.vertexTrimmedData);
}
}
/**
* Gets the local bounds of the sprite object.
*
* @param {PIXI.Rectangle} rect - The output rectangle.
* @return {PIXI.Rectangle} The bounds.
*/
getLocalBounds(rect)
{
// we can do a fast local bounds if the sprite has no children!
if (this.children.length === 0)
{
this._bounds.minX = this._texture.orig.width * -this._anchor._x;
this._bounds.minY = this._texture.orig.height * -this._anchor._y;
this._bounds.maxX = this._texture.orig.width * (1 - this._anchor._x);
this._bounds.maxY = this._texture.orig.height * (1 - this._anchor._y);
if (!rect)
{
if (!this._localBoundsRect)
{
this._localBoundsRect = new Rectangle();
}
rect = this._localBoundsRect;
}
return this._bounds.getRectangle(rect);
}
return super.getLocalBounds.call(this, rect);
}
/**
* Tests if a point is inside this sprite
*
* @param {PIXI.Point} point - the point to test
* @return {boolean} the result of the test
*/
containsPoint(point)
{
this.worldTransform.applyInverse(point, tempPoint);
const width = this._texture.orig.width;
const height = this._texture.orig.height;
const x1 = -width * this.anchor.x;
let y1 = 0;
if (tempPoint.x >= x1 && tempPoint.x < x1 + width)
{
y1 = -height * this.anchor.y;
if (tempPoint.y >= y1 && tempPoint.y < y1 + height)
{
return true;
}
}
return false;
}
/**
* Destroys this sprite and optionally its texture and children
*
* @param {object|boolean} [options] - Options parameter. A boolean will act as if all options
* have been set to that value
* @param {boolean} [options.children=false] - if set to true, all the children will have their destroy
* method called as well. 'options' will be passed on to those calls.
* @param {boolean} [options.texture=false] - Should it destroy the current texture of the sprite as well
* @param {boolean} [options.baseTexture=false] - Should it destroy the base texture of the sprite as well
*/
destroy(options)
{
super.destroy(options);
this._texture.off('update', this._onTextureUpdate, this);
this._anchor = null;
const destroyTexture = typeof options === 'boolean' ? options : options && options.texture;
if (destroyTexture)
{
const destroyBaseTexture = typeof options === 'boolean' ? options : options && options.baseTexture;
this._texture.destroy(!!destroyBaseTexture);
}
this._texture = null;
this.shader = null;
}
// some helper functions..
/**
* Helper function that creates a new sprite based on the source you provide.
* The source can be - frame id, image url, video url, canvas element, video element, base texture
*
* @static
* @param {number|string|PIXI.BaseTexture|HTMLCanvasElement|HTMLVideoElement} source Source to create texture from
* @return {PIXI.Sprite} The newly created sprite
*/
static from(source)
{
return new Sprite(Texture.from(source));
}
/**
* Helper function that creates a sprite that will contain a texture from the TextureCache based on the frameId
* The frame ids are created when a Texture packer file has been loaded
*
* @static
* @param {string} frameId - The frame Id of the texture in the cache
* @return {PIXI.Sprite} A new Sprite using a texture from the texture cache matching the frameId
*/
static fromFrame(frameId)
{
const texture = TextureCache[frameId];
if (!texture)
{
throw new Error(`The frameId "${frameId}" does not exist in the texture cache`);
}
return new Sprite(texture);
}
/**
* Helper function that creates a sprite that will contain a texture based on an image url
* If the image is not in the texture cache it will be loaded
*
* @static
* @param {string} imageId - The image url of the texture
* @param {boolean} [crossorigin=(auto)] - if you want to specify the cross-origin parameter
* @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - if you want to specify the scale mode,
* see {@link PIXI.SCALE_MODES} for possible values
* @return {PIXI.Sprite} A new Sprite using a texture from the texture cache matching the image id
*/
static fromImage(imageId, crossorigin, scaleMode)
{
return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode));
}
/**
* The width of the sprite, setting this will actually modify the scale to achieve the value set
*
* @member {number}
*/
get width()
{
return Math.abs(this.scale.x) * this._texture.orig.width;
}
set width(value) // eslint-disable-line require-jsdoc
{
const s = sign(this.scale.x) || 1;
this.scale.x = s * value / this._texture.orig.width;
this._width = value;
}
/**
* The height of the sprite, setting this will actually modify the scale to achieve the value set
*
* @member {number}
*/
get height()
{
return Math.abs(this.scale.y) * this._texture.orig.height;
}
set height(value) // eslint-disable-line require-jsdoc
{
const s = sign(this.scale.y) || 1;
this.scale.y = s * value / this._texture.orig.height;
this._height = value;
}
/**
* The anchor sets the origin point of the texture.
* The default is 0,0 or taken from the {@link PIXI.Texture|Texture} passed to the constructor.
* Setting the texture at a later point of time does not change the anchor.
*
* 0,0 means the texture's origin is the top left, 0.5,0.5 is the center, 1,1 the bottom right corner.
*
* @member {PIXI.ObservablePoint}
*/
get anchor()
{
return this._anchor;
}
set anchor(value) // eslint-disable-line require-jsdoc
{
this._anchor.copy(value);
}
/**
* The tint applied to the sprite. This is a hex value.
* A value of 0xFFFFFF will remove any tint effect.
*
* @member {number}
* @default 0xFFFFFF
*/
get tint()
{
return this._tint;
}
set tint(value) // eslint-disable-line require-jsdoc
{
this._tint = value;
this._tintRGB = (value >> 16) + (value & 0xff00) + ((value & 0xff) << 16);
}
/**
* The texture that the sprite is using
*
* @member {PIXI.Texture}
*/
get texture()
{
return this._texture;
}
set texture(value) // eslint-disable-line require-jsdoc
{
if (this._texture === value)
{
return;
}
this._texture = value || Texture.EMPTY;
this.cachedTint = 0xFFFFFF;
this._textureID = -1;
this._textureTrimmedID = -1;
if (value)
{
// wait for the texture to load
if (value.baseTexture.hasLoaded)
{
this._onTextureUpdate();
}
else
{
value.once('update', this._onTextureUpdate, this);
}
}
}
}
|
var Dungeon = {
map: [],
in_battle: 0,
player_position: 0
};
Dungeon.mapGenerator = function () {
this.map = [];
this.player_position = 0;
for (var i = 0; i < 100; i++) {
if (rand(0, 5) != 0) {
this.map[i] = {symbol: '_', unit: null};
}
else {
this.map[i] = {symbol: '~', unit: null};
}
}
this.map[0].special = 'enter';
this.map[99].special = 'exit';
};
Dungeon.getBattlefieldString = function () {
if (this.in_battle) {
return this.getMapString();
}
else {
return this.getMenuString();
}
};
Dungeon.getMapString = function () {
var map_string = '';
var visible_area = this.getVisibleArea();
visible_area.forEach(function (place, id) {
map_string += Dungeon.getPlaceString(id);
});
return map_string;
};
Dungeon.getVisibleArea = function () {
var shift = (this.player_position > 5) ? this.player_position - 5 : 0;
var visible_area = [];
this.map.forEach(function (place, id) {
if (id >= shift && id < shift + 20) {
visible_area[id] = place;
}
});
return visible_area; // this.map.slice(shift, shift + 20);
};
Dungeon.getPlaceString = function (id) {
var place = this.map[id];
if (place.unit) { return place.unit.symbol; }
if (place.special == 'enter') { return '0'; }
if (place.special == 'exit') { return 'O'; }
return place.symbol;
};
Dungeon.getMenuString = function () {
return '<button class="btn btn-default" onclick="Dungeon.go();">Go to dungeon</button>';
};
Dungeon.go = function () {
if (Player.action_points < 1) {
message("Not enough action points.");
return false;
}
Player.action_points--;
this.mapGenerator();
this.map[0].unit = Player.unit;
this.in_battle = 1;
};
Dungeon.tick = function () {
if (this.in_battle == 0) {
return false;
}
else {
var visible_area = this.getVisibleArea();
var units = [];
visible_area.forEach(function (place ,id) {
units[id] = place.unit;
});
units.forEach(function (unit, id) {
if (!unit) return false;
//console.log(unit);
unit.AI(id);
});
}
};
Dungeon.unitMove = function (from_id, to_id) {
var unit = this.map[from_id].unit;
if (unit == Player.unit) this.player_position = to_id;
this.map[to_id].unit = unit;
this.map[from_id].unit = null;
};
Dungeon.exit = function () {
this.in_battle = 0;
Player.knowledge++;
};
|
import { propOr } from 'ramda'
const SPECIAL_USE_FLAGS = ['\\All', '\\Archive', '\\Drafts', '\\Flagged', '\\Junk', '\\Sent', '\\Trash']
const SPECIAL_USE_BOXES = {
'\\Sent': [
'aika', 'bidaliak', 'bidalita', 'dihantar', 'e rometsweng', 'e tindami', 'elküldött', 'elküldöttek', 'enviadas',
'enviadas', 'enviados', 'enviats', 'envoyés', 'ethunyelweyo', 'expediate', 'ezipuru', 'gesendete', 'gestuur',
'gönderilmiş öğeler', 'göndərilənlər', 'iberilen', 'inviati', 'išsiųstieji', 'kuthunyelwe', 'lasa', 'lähetetyt',
'messages envoyés', 'naipadala', 'nalefa', 'napadala', 'nosūtītās ziņas', 'odeslané', 'padala', 'poslane',
'poslano', 'poslano', 'poslané', 'poslato', 'saadetud', 'saadetud kirjad', 'sendt', 'sendt', 'sent', 'sent items',
'sent messages', 'sända poster', 'sänt', 'terkirim', 'ti fi ranṣẹ', 'të dërguara', 'verzonden', 'vilivyotumwa',
'wysłane', 'đã gửi', 'σταλθέντα', 'жиберилген', 'жіберілгендер', 'изпратени', 'илгээсэн', 'ирсол шуд', 'испратено',
'надіслані', 'отправленные', 'пасланыя', 'юборилган', 'ուղարկված', 'נשלחו', 'פריטים שנשלחו', 'المرسلة', 'بھیجے گئے',
'سوزمژہ', 'لېګل شوی', 'موارد ارسال شده', 'पाठविले', 'पाठविलेले', 'प्रेषित', 'भेजा गया', 'প্রেরিত', 'প্রেরিত', 'প্ৰেৰিত', 'ਭੇਜੇ', 'મોકલેલા',
'ପଠାଗଲା', 'அனுப்பியவை', 'పంపించబడింది', 'ಕಳುಹಿಸಲಾದ', 'അയച്ചു', 'යැවු පණිවුඩ', 'ส่งแล้ว', 'გაგზავნილი', 'የተላኩ', 'បានផ្ញើ',
'寄件備份', '寄件備份', '已发信息', '送信済みメール', '발신 메시지', '보낸 편지함'
],
'\\Trash': [
'articole șterse', 'bin', 'borttagna objekt', 'deleted', 'deleted items', 'deleted messages', 'elementi eliminati',
'elementos borrados', 'elementos eliminados', 'gelöschte objekte', 'item dipadam', 'itens apagados', 'itens excluídos',
'mục đã xóa', 'odstraněné položky', 'pesan terhapus', 'poistetut', 'praht', 'prügikast', 'silinmiş öğeler',
'slettede beskeder', 'slettede elementer', 'trash', 'törölt elemek', 'usunięte wiadomości', 'verwijderde items',
'vymazané správy', 'éléments supprimés', 'видалені', 'жойылғандар', 'удаленные', 'פריטים שנמחקו', 'العناصر المحذوفة',
'موارد حذف شده', 'รายการที่ลบ', '已删除邮件', '已刪除項目', '已刪除項目'
],
'\\Junk': [
'bulk mail', 'correo no deseado', 'courrier indésirable', 'istenmeyen', 'istenmeyen e-posta', 'junk', 'levélszemét',
'nevyžiadaná pošta', 'nevyžádaná pošta', 'no deseado', 'posta indesiderata', 'pourriel', 'roskaposti', 'skräppost',
'spam', 'spam', 'spamowanie', 'søppelpost', 'thư rác', 'спам', 'דואר זבל', 'الرسائل العشوائية', 'هرزنامه', 'สแปม',
'垃圾郵件', '垃圾邮件', '垃圾電郵'
],
'\\Drafts': [
'ba brouillon', 'borrador', 'borrador', 'borradores', 'bozze', 'brouillons', 'bản thảo', 'ciorne', 'concepten', 'draf',
'drafts', 'drög', 'entwürfe', 'esborranys', 'garalamalar', 'ihe edeturu', 'iidrafti', 'izinhlaka', 'juodraščiai', 'kladd',
'kladder', 'koncepty', 'koncepty', 'konsep', 'konsepte', 'kopie robocze', 'layihələr', 'luonnokset', 'melnraksti', 'meralo',
'mesazhe të padërguara', 'mga draft', 'mustandid', 'nacrti', 'nacrti', 'osnutki', 'piszkozatok', 'rascunhos', 'rasimu',
'skice', 'taslaklar', 'tsararrun saƙonni', 'utkast', 'vakiraoka', 'vázlatok', 'zirriborroak', 'àwọn àkọpamọ́', 'πρόχειρα',
'жобалар', 'нацрти', 'нооргууд', 'сиёҳнавис', 'хомаки хатлар', 'чарнавікі', 'чернетки', 'чернови', 'черновики', 'черновиктер',
'սևագրեր', 'טיוטות', 'مسودات', 'مسودات', 'موسودې', 'پیش نویسها', 'ڈرافٹ/', 'ड्राफ़्ट', 'प्रारूप', 'খসড়া', 'খসড়া', 'ড্ৰাফ্ট', 'ਡ੍ਰਾਫਟ', 'ડ્રાફ્ટસ',
'ଡ୍ରାଫ୍ଟ', 'வரைவுகள்', 'చిత్తు ప్రతులు', 'ಕರಡುಗಳು', 'കരടുകള്', 'කෙටුම් පත්', 'ฉบับร่าง', 'მონახაზები', 'ረቂቆች', 'សារព្រាង', '下書き', '草稿',
'草稿', '草稿', '임시 보관함'
]
}
const SPECIAL_USE_BOX_FLAGS = Object.keys(SPECIAL_USE_BOXES)
/**
* Checks if a mailbox is for special use
*
* @param {Object} mailbox
* @return {String} Special use flag (if detected)
*/
export function checkSpecialUse (mailbox) {
if (mailbox.flags) {
for (let i = 0; i < SPECIAL_USE_FLAGS.length; i++) {
const type = SPECIAL_USE_FLAGS[i]
if ((mailbox.flags || []).indexOf(type) >= 0) {
mailbox.specialUse = type
mailbox.specialUseFlag = type
return type
}
}
}
return checkSpecialUseByName(mailbox)
}
function checkSpecialUseByName (mailbox) {
const name = propOr('', 'name', mailbox).toLowerCase().trim()
for (let i = 0; i < SPECIAL_USE_BOX_FLAGS.length; i++) {
const type = SPECIAL_USE_BOX_FLAGS[i]
if (SPECIAL_USE_BOXES[type].indexOf(name) >= 0) {
mailbox.specialUse = type
return type
}
}
return false
}
|
ig.module(
'plusplus.entities.trigger-reverse'
)
.requires(
'plusplus.entities.trigger'
)
.defines(function () {
"use strict";
/**
* Trigger that deactivates instead of activating.
* @class
* @extends ig.EntityTrigger
* @memberof ig
* @author Collin Hover - collinhover.com
**/
ig.EntityTriggerReverse = ig.global.EntityTriggerReverse = ig.EntityTrigger.extend(/**@lends ig.EntityTriggerReverse.prototype */{
// editor properties
_wmBoxColor: 'rgba( 255, 200, 0, 0.7 )',
/**
* @override
*/
handleTargets: function (entity, needsActivation) {
if ( needsActivation !== false ) {
this.deactivate(entity);
}
for ( var i = 0, il = this.targetSequence.length; i < il; i++ ) {
var target = this.targetSequence[i];
if ( target instanceof ig.EntityTriggerReverse ) {
target.trigger( entity );
}
else {
target.deactivate( entity );
}
}
},
/**
* Reverse trigger deactivates on activate.
* @override
**/
activate: function (entity) {
if ( this.needsTeardown ) {
this.teardown();
}
this.activated = false;
if (this.deactivateCallback) {
this.deactivateCallback.call(this.deactivateContext || this, entity);
}
},
/**
* Reverse trigger activates on deactivate.
* @override
*/
deactivate: function (entity) {
if ( !this.needsTeardown ) {
this.setup();
}
this.activated = true;
if (this.activateCallback) {
this.activateCallback.call(this.activateContext || this, entity);
}
if ( !this.triggering ) {
this.trigger( entity, false );
}
}
});
}); |
/*global define*/
'use strict';
// Dependecies
define([
'jquery',
'jquery-ui',
'pubsub',
'underscore'
], function(
jQuery,
jQuery_ui,
PubSub,
_
)
{
/* This module handles the user notes.
Each note can be connect to an atom (via IAC) or not.
Each note may appear on the canvas.
*/
// Variables
var target = undefined;
var notes = {};
var cameraData = {}; // here are stored data about the camera position that each note can be related to
var idCounter = 0;
// Module References
var $setUIValue = undefined;
var $tooltipGenerator = undefined;
var $disableUIElement = undefined;
var $menuRibbon = undefined;
var $stringEditor = undefined;
var html = undefined;
var intervalTime = 3000;
var timer;
// Contructor //
function notesTab(argument) {
// Acquire Module References //
if (!(_.isUndefined(argument.setUIValue))) $setUIValue = argument.setUIValue;
else return false;
if (!(_.isUndefined(argument.tooltipGenerator))) $tooltipGenerator = argument.tooltipGenerator;
else return false;
if (!(_.isUndefined(argument.disableUIElement))) $disableUIElement = argument.disableUIElement;
else return false;
if (!(_.isUndefined(argument.menuRibbon))) $menuRibbon = argument.menuRibbon;
else return false;
if (!(_.isUndefined(argument.stringEditor))) $stringEditor = argument.stringEditor;
else return false;
if (!(_.isUndefined(argument.html))) html = argument.html;
else return false;
// Inputs //
html.notes.properties.title.on('keyup',function(){
html.interface.screen.wrapper.find('#'+notes.activeEntry).find('.noteTitle').html(html.notes.properties.title.val() );
});
html.notes.other.body.on('keyup',function(){
html.interface.screen.wrapper.find('#'+notes.activeEntry).find('.wordwrap.notes').html(html.notes.other.body.val());
});
html.notes.properties.opacity.html('<option>0</option><option>2</option><option>4</option><option>6</option><option>8</option><option>10</option>');
html.notes.properties.opacity.selectpicker();
html.notes.properties.opacity.selectpicker('val','10');
html.notes.properties.opacity.on('change',function(){
html.interface.screen.wrapper.find('#'+notes.activeEntry).css('-ms-filter','progid:DXImageTransform.Microsoft.Alpha(Opacity='+$stringEditor.multiply10(html.notes.properties.opacity.val())+')');
html.interface.screen.wrapper.find('#'+notes.activeEntry).css('filter','alpha(opacity='+$stringEditor.multiply10(html.notes.properties.opacity.val())+')');
html.interface.screen.wrapper.find('#'+notes.activeEntry).css('opacity',$stringEditor.divide10(html.notes.properties.opacity.val()));
});
html.notes.properties.color.spectrum({
color: "#000000",
allowEmpty:true,
chooseText: "Choose",
cancelText: "Close",
move: function(){
$setUIValue.setValue({
noteColor:{
publish: { id: notes.activeEntry, color: '#'+html.notes.properties.color.spectrum('get').toHex() },
value: '#'+html.notes.properties.color.spectrum('get').toHex()
}
});
html.interface.screen.wrapper.find('#'+notes.activeEntry).css('background-color','#'+html.notes.properties.color.spectrum('get').toHex());
html.interface.screen.wrapper.find('#'+notes.activeEntry).find('.notes').css('background-color','#'+html.notes.properties.color.spectrum('get').toHex());
},
change: function(){
$setUIValue.setValue({
noteColor:{
publish: { id: notes.activeEntry, color: '#'+html.notes.properties.color.spectrum('get').toHex() },
value: '#'+html.notes.properties.color.spectrum('get').toHex()
}
});
html.interface.screen.wrapper.find('#'+notes.activeEntry).css('background-color','#'+html.notes.properties.color.spectrum('get').toHex());
html.interface.screen.wrapper.find('#'+notes.activeEntry).find('.notes').css('background-color','#'+html.notes.properties.color.spectrum('get').toHex());
}
});
html.notes.other.saveCamera.on('click',function(){
var value = undefined;
(html.notes.other.saveCamera.hasClass('active')) ? value = false : value = true;
$setUIValue.setValue({
saveCamera:{
value:value,
publish:{saveCamera:value, id : notes.activeEntry}
}
});
});
html.notes.other.enableParameters.on('click',function(){
var value = undefined;
(html.notes.other.enableParameters.hasClass('active')) ? value = false : value = true;
$setUIValue.setValue({
enableParameters:{
value:value,
publish:{enableMotifParameters:value}
}
});
});
$disableUIElement.disableElement({
noteTitle:{
value: true
},
noteBody:{
value: true
},
noteOpacity:{
value: true
},
noteColor:{
value: true
}
});
html.notes.other.table.find('tbody').sortable({
appendTo: document.body,
axis: 'y',
containment: "parent",
cursor: "move",
items: "> tr",
tolerance: "pointer",
cancel: 'td.visibility'
});
html.notes.other.table.hide('slow');
// Buttons //
html.notes.actions.new.on('click',function(){
if (!(html.notes.actions.new.hasClass('disabled'))){
highlightNote(notes.activeEntry,false);
highlightNote(addNote(),true);
$disableUIElement.disableElement({
noteTitle:{
value: false
},
noteBody:{
value: false
},
noteOpacity:{
value: false
},
noteColor:{
value: false
},
newNote:{
value: true
},
saveNote:{
value: false
},
deleteNote:{
value: false
}
});
}
});
html.notes.actions.save.on('click',function(){
if (!(html.notes.actions.save.hasClass('disabled'))){
$setUIValue.setValue({
noteVisibility:{
value: false,
other: html.notes.other.table.find('#'+notes.activeEntry)
}
});
if (notes[notes.activeEntry].atomNote === true) {
var x = parseInt(html.interface.screen.wrapper.find('#'+notes.activeEntry).css('left'),10) + parseInt(html.interface.screen.wrapper.find('#'+notes.activeEntry).css('width'),10) / 2;
var y = parseInt(html.interface.screen.wrapper.find('#'+notes.activeEntry).css('top'),10) + parseInt(html.interface.screen.wrapper.find('#'+notes.activeEntry).css('height'),10) / 2;
notes[notes.activeEntry].x = x;
notes[notes.activeEntry].y = y;
$setUIValue.setValue({
noteVisibility:{
publish: {id:notes.activeEntry, visible: false, x: x, y: y, color: notes[notes.activeEntry].color}
}
});
}
showCanvasNote(notes.activeEntry,false);
var cameraToggle = (html.notes.other.saveCamera.hasClass('active')) ? true : false;
var sceneObjsToggle = (html.notes.other.enableParameters.hasClass('active')) ? true : false;
$setUIValue.setValue({
saveNoteForSystem:{
publish: {id:notes.activeEntry, cameraToggle : cameraToggle, sceneObjsToggle : sceneObjsToggle }
}
});
editNote({
title: html.notes.properties.title.val(),
body: html.notes.other.body.val(),
color: '#'+html.notes.properties.color.spectrum('get').toHex(),
opacity: html.notes.properties.opacity.val(),
atomNote: notes[notes.activeEntry].atomNote,
x: notes[notes.activeEntry].x,
y: notes[notes.activeEntry].y
});
$disableUIElement.disableElement({
noteTitle:{
value: true
},
noteBody:{
value: true
},
noteOpacity:{
value: true
},
noteColor:{
value: true
},
newNote:{
value: false
},
saveNote:{
value: true
},
deleteNote:{
value: true
}
});
clearTimeout(timer);
$setUIValue.setValue({
playerPause:{
value:false,
publish:{play:false }
}
});
$setUIValue.setValue({
playerPlay:{
value:false,
publish:{play:false }
}
});
}
});
html.notes.actions.delete.on('click',function(){
if (!(html.notes.actions.delete.hasClass('disabled'))){
$setUIValue.setValue({
deleteNote: {
publish: {
id: notes.activeEntry
}
}
});
deleteNote();
$disableUIElement.disableElement({
noteTitle:{
value: true
},
noteBody:{
value: true
},
noteOpacity:{
value: true
},
noteColor:{
value: true
},
newNote:{
value: false
},
saveNote:{
value: true
},
deleteNote:{
value: true
}
});
}
});
// player
html.notes.other.playerSlider.slider({
value: intervalTime/1000,
min: intervalTime/1000,
max: 300,
step: 1,
animate: true,
slide: function(event, ui){
html.notes.other.interval.val(ui.value);
intervalTime = parseInt(ui.value)*1000;
}
});
html.notes.other.interval.val(intervalTime/1000);
html.notes.other.interval.prop('disabled', true);
html.notes.other.play.on('click',function(){
var value = undefined;
(html.notes.other.play.find('a').hasClass('active')) ? value = false : value = true;
if(value === true){
$setUIValue.setValue({
playerPlay:{
value:value,
publish:{play:value }
}
});
$setUIValue.setValue({
playerPause:{
value:false,
publish:{play:false}
}
});
playerTimerFunction();
}
});
html.notes.other.pause.on('click',function(){
var value = undefined;
(html.notes.other.pause.find('a').hasClass('active')) ? value = false : value = true;
if(value === true){
clearTimeout(timer);
$setUIValue.setValue({
playerPause:{
value:value,
publish:{play:value }
}
});
$setUIValue.setValue({
playerPlay:{
value:false,
publish:{play:false }
}
});
}
});
html.notes.other.repeat.on('click',function(){
var value = undefined;
(html.notes.other.repeat.find('a').hasClass('active')) ? value = false : value = true;
$setUIValue.setValue({
playerRepeat:{
value:value,
publish:{repeat:value}
}
});
});
html.notes.other.rewind.on('click',function(){
var nextID = undefined;
var id = notes.activeEntry;
var newStart = false ;
if( id === false){
newStart = true;
id = (jQuery('#'+html.notes.other.tableID+' tr:first'))[0].id ;
};
// Find Next Note //
var table = {
first: jQuery('#'+html.notes.other.tableID+' tr:first'),
last: jQuery('#'+html.notes.other.tableID+' tr:last'),
current: html.notes.other.table.find('#'+id),
next: html.notes.other.table.find('#'+id).closest('tr').prev('tr')
};
if (table.next.length > 0){
nextID = table.next[0].id;
}
else{
nextID = table.last[0].id;
}
// Hide Current Note //
$setUIValue.setValue({
noteVisibility:{
value: false,
other: html.notes.other.table.find('#'+id)
}
});
if (notes[id].atomNote === true) {
var x = parseInt(html.interface.screen.wrapper.find('#'+id).css('left'),10) + parseInt(html.interface.screen.wrapper.find('#'+id).css('width'),10) / 2;
var y = parseInt(html.interface.screen.wrapper.find('#'+id).css('top'),10) + parseInt(html.interface.screen.wrapper.find('#'+id).css('height'),10) / 2;
notes[id].x = x;
notes[id].y = y;
$setUIValue.setValue({
noteVisibility:{
publish: {id:id, visible: false, x: x, y: y, color: notes[id].color}
}
});
}
showCanvasNote(id,false);
// Show Next Note //
$setUIValue.setValue({
noteVisibility:{
value: true,
other: html.notes.other.table.find('#'+nextID)
}
});
if (notes[nextID].atomNote === true) {
var x = parseInt(html.interface.screen.wrapper.find('#'+nextID).css('left'),10) + parseInt(html.interface.screen.wrapper.find('#'+nextID).css('width'),10) / 2;
var y = parseInt(html.interface.screen.wrapper.find('#'+nextID).css('top'),10) + parseInt(html.interface.screen.wrapper.find('#'+nextID).css('height'),10) / 2;
notes[nextID].x = x;
notes[nextID].y = y;
$setUIValue.setValue({
noteVisibility:{
publish: {id: nextID, visible: true, x: x, y: y, color: notes[nextID].color}
}
});
}
showCanvasNote(nextID,true);
$setUIValue.setValue({
selectNote:{
publish: {id:nextID}
}
});
selectNote(nextID);
});
html.notes.other.forward.on('click',function(){
var nextID = undefined;
var id = notes.activeEntry;
var newStart = false ;
if( id === false){
newStart=true;
id = (jQuery('#'+html.notes.other.tableID+' tr:last'))[0].id ;
};
// Find Next Note //
var table = {
first: jQuery('#'+html.notes.other.tableID+' tr:first'),
last: jQuery('#'+html.notes.other.tableID+' tr:last'),
current: html.notes.other.table.find('#'+id),
next: html.notes.other.table.find('#'+id).closest('tr').next('tr')
};
if (table.next.length > 0){
nextID = table.next[0].id;
}
else {
nextID = table.first[0].id;
}
// Hide Current Note //
$setUIValue.setValue({
noteVisibility:{
value: false,
other: html.notes.other.table.find('#'+id)
}
});
if (notes[id].atomNote === true) {
var x = parseInt(html.interface.screen.wrapper.find('#'+id).css('left'),10) + parseInt(html.interface.screen.wrapper.find('#'+id).css('width'),10) / 2;
var y = parseInt(html.interface.screen.wrapper.find('#'+id).css('top'),10) + parseInt(html.interface.screen.wrapper.find('#'+id).css('height'),10) / 2;
notes[id].x = x;
notes[id].y = y;
$setUIValue.setValue({
noteVisibility:{
publish: {id:id, visible: false, x: x, y: y, color: notes[id].color}
}
});
}
showCanvasNote(id,false);
// Show Next Note //
$setUIValue.setValue({
noteVisibility:{
value: true,
other: html.notes.other.table.find('#'+nextID)
}
});
if (notes[nextID].atomNote === true) { console.log(9);
var x = parseInt(html.interface.screen.wrapper.find('#'+nextID).css('left'),10) + parseInt(html.interface.screen.wrapper.find('#'+nextID).css('width'),10) / 2;
var y = parseInt(html.interface.screen.wrapper.find('#'+nextID).css('top'),10) + parseInt(html.interface.screen.wrapper.find('#'+nextID).css('height'),10) / 2;
notes[nextID].x = x;
notes[nextID].y = y;
$setUIValue.setValue({
noteVisibility:{
publish: {id: nextID, visible: true, x: x, y: y, color: notes[nextID].color}
}
});
}
showCanvasNote(nextID,true);
$setUIValue.setValue({
selectNote:{
publish: {id:nextID}
}
});
selectNote(nextID);
});
};
var playerTimerFunction = function(){
var nextID = undefined;
var id = notes.activeEntry;
var newStart = false ;
if( id === false){
newStart=true;
id = (jQuery('#'+html.notes.other.tableID+' tr:last'))[0].id ;
};
// Find Next Note //
var table = {
first: jQuery('#'+html.notes.other.tableID+' tr:first'),
last: jQuery('#'+html.notes.other.tableID+' tr:last'),
current: html.notes.other.table.find('#'+id),
next: html.notes.other.table.find('#'+id).closest('tr').next('tr')
};
if (table.next.length > 0){
nextID = table.next[0].id;
}
else if((html.notes.other.repeat.find('a').hasClass('active')) || newStart === true){
nextID = table.first[0].id;
}
else{
clearTimeout(timer);
$setUIValue.setValue({
playerPlay:{
value:false,
publish:{play:false }
}
});
return;
}
// Hide Current Note //
$setUIValue.setValue({
noteVisibility:{
value: false,
other: html.notes.other.table.find('#'+id)
}
});
if (notes[id].atomNote === true) {
var x = parseInt(html.interface.screen.wrapper.find('#'+id).css('left'),10) + parseInt(html.interface.screen.wrapper.find('#'+id).css('width'),10) / 2;
var y = parseInt(html.interface.screen.wrapper.find('#'+id).css('top'),10) + parseInt(html.interface.screen.wrapper.find('#'+id).css('height'),10) / 2;
notes[id].x = x;
notes[id].y = y;
$setUIValue.setValue({
noteVisibility:{
publish: {id:id, visible: false, x: x, y: y, color: notes[id].color}
}
});
}
showCanvasNote(id,false);
// Show Next Note //
$setUIValue.setValue({
noteVisibility:{
value: true,
other: html.notes.other.table.find('#'+nextID)
}
});
if (notes[nextID].atomNote === true) { console.log(9);
var x = parseInt(html.interface.screen.wrapper.find('#'+nextID).css('left'),10) + parseInt(html.interface.screen.wrapper.find('#'+nextID).css('width'),10) / 2;
var y = parseInt(html.interface.screen.wrapper.find('#'+nextID).css('top'),10) + parseInt(html.interface.screen.wrapper.find('#'+nextID).css('height'),10) / 2;
notes[nextID].x = x;
notes[nextID].y = y;
$setUIValue.setValue({
noteVisibility:{
publish: {id: nextID, visible: true, x: x, y: y, color: notes[nextID].color}
}
});
}
showCanvasNote(nextID,true);
$setUIValue.setValue({
selectNote:{
publish: {id:nextID}
}
});
selectNote(nextID);
timer = setTimeout( playerTimerFunction, intervalTime );
};
// Add note to Table //
function addNote(newID,restore){
var id = undefined;
var atomNote = false;
// Clear Forms //
html.notes.properties.opacity.val('10');
html.notes.other.body.val('');
html.notes.properties.opacity.selectpicker('val','10');
html.notes.properties.color.children().css('background','white');
// Note is not related to an atom //
if (_.isUndefined(newID)) {
do{
id = 'note'+idCounter;
idCounter++;
} while(!(_.isUndefined(notes[id])));
}
// Restore Note //
else if (_.isUndefined(restore)){
atomNote = true;
id = newID;
}
// Atom Related //
else id = newID;
html.notes.other.table.find('tbody').append('<tr id="'+id+'" class="bg-dark-gray"><td colspan="1" class="visibility"><a class="noteButton"><img src="Images/hidden-icon-sm.png" class="img-responsive" alt=""/></a></td><td colspan="4" class="selectable note-name">Untitled Note</td><td class="selectable note-color"><div class="color-picker color-picker-sm theme-02 bg-purple"><div class="color"></div></div></td></tr>');
html.notes.other.table.show('slow');
// Create Database Entry //
notes[id] = {
title: '',
body: '',
color: '#FFFFFF',
opacity: '',
atomNote: atomNote,
x: 0,
y: 0
};
// Create on Canvas //
createCanvasNote(id);
// Handlers //
html.notes.other.table.find('#'+id).find('.selectable').on('click',function(){
$setUIValue.setValue({
selectNote:{
publish: {id:id}
}
});
selectNote(id);
});
// Note Visibility //
html.notes.other.table.find('#'+id).find('.noteButton').on('click', function(){
var value = undefined;
(html.notes.other.table.find('#'+id).find('.noteButton').hasClass('visible')) ? value = false : value = true;
$setUIValue.setValue({
noteVisibility:{
value: value,
other: html.notes.other.table.find('#'+id)
}
});
if (notes[id].atomNote === true) {
var x = parseInt(html.interface.screen.wrapper.find('#'+id).css('left'),10) + parseInt(html.interface.screen.wrapper.find('#'+id).css('width'),10) / 2;
var y = parseInt(html.interface.screen.wrapper.find('#'+id).css('top'),10) + parseInt(html.interface.screen.wrapper.find('#'+id).css('height'),10) / 2;
notes[id].x = x;
notes[id].y = y;
$setUIValue.setValue({
noteVisibility:{
publish: {id:id, visible: value, x: x, y: y, color: notes[id].color}
}
});
}
showCanvasNote(id,value);
});
// Remote Hide/Show Note //
html.notes.other.table.find('#'+id).on('hide',function(){
if(_.isUndefined(notes[id].temp)) {
return false;
}
else{
if (notes[id].temp === true){
// UI //
$setUIValue.setValue({
noteVisibility:{
value: false,
other: html.notes.other.table.find('#'+id)
}
});
showCanvasNote(id.toString(),false);
notes[id].temp = undefined;
// System //
var x = parseInt(html.interface.screen.wrapper.find('#'+id).css('left'),10) + parseInt(html.interface.screen.wrapper.find('#'+id).css('width'),10) / 2;
var y = parseInt(html.interface.screen.wrapper.find('#'+id).css('top'),10) + parseInt(html.interface.screen.wrapper.find('#'+id).css('height'),10) / 2;
notes[id].x = x;
notes[id].y = y;
$setUIValue.setValue({
noteVisibility:{
publish: {id:id, visible: false, x: x, y: y, color: notes[id].color}
}
});
}
}
});
// Initiation //
$setUIValue.setValue({
noteVisibility:{
value: true,
other: html.notes.other.table.find('#'+id)
}
});
$setUIValue.setValue({
atomNoteTable: {
publish: {
id: id,
add: true,
color : notes[id].color
}
}
});
if (notes[id].atomNote === true) {
var x = parseInt(html.interface.screen.wrapper.find('#'+id).css('left'),10) + parseInt(html.interface.screen.wrapper.find('#'+id).css('width'),10) / 2;
var y = parseInt(html.interface.screen.wrapper.find('#'+id).css('top'),10) + parseInt(html.interface.screen.wrapper.find('#'+id).css('height'),10) / 2;
notes[id].x = x;
notes[id].y = y;
$setUIValue.setValue({
noteVisibility:{
publish: {id:id, visible: true, x: x, y: y, color: notes[id].color}
}
});
}
showCanvasNote(id,true);
return id;
};
// Edit note //
function editNote(note){
// Update Database //
if (notes.activeEntry !== false) notes[notes.activeEntry] = note;
else return false;
// Update Title //
if (note.title !== '') {
html.notes.other.table.find('#'+notes.activeEntry).find('.note-name').html(note.title);
html.interface.screen.wrapper.find('#'+notes.activeEntry).find('.noteTitle').html(note.title);
}
// Color, opacity and position //
$setUIValue.setValue({
noteColor:{
publish: { id: notes.activeEntry, color: note.color },
value: note.color
}
});
html.interface.screen.wrapper.find('#'+notes.activeEntry).css('background-color',note.color);
html.interface.screen.wrapper.find('#'+notes.activeEntry).find('.notes').css('background-color',note.color);
html.interface.screen.wrapper.find('#'+notes.activeEntry).css('-ms-filter','progid:DXImageTransform.Microsoft.Alpha(Opacity='+$stringEditor.multiply10(note.opacity)+')');
html.interface.screen.wrapper.find('#'+notes.activeEntry).css('filter','alpha(opacity='+$stringEditor.multiply10(note.opacity)+')');
html.interface.screen.wrapper.find('#'+notes.activeEntry).css('opacity',$stringEditor.divide10(note.opacity));
html.interface.screen.wrapper.find('#'+notes.activeEntry).css('left', note.x+'px');
html.interface.screen.wrapper.find('#'+notes.activeEntry).css('top',note.y+'px');
if(note.atomNote) {
$setUIValue.setValue({
noteMovement:{
publish: { id: notes.activeEntry, x: note.x, y: note.y }
}
});
}
// Body //
if (note.body !== '') html.interface.screen.wrapper.find('#'+notes.activeEntry).find('.notes').html(note.body);
html.notes.other.table.find('#'+notes.activeEntry).find('.color').css('background',note.color);
highlightNote(notes.activeEntry,false);
// Clear Forms //
html.notes.properties.title.val('');
html.notes.other.body.val('');
html.notes.properties.color.children().css('background','transparent');
};
// Delete note //
function deleteNote(){
// Update Database //
if (notes.activeEntry !== false) {
if (notes[notes.activeEntry].atomNote === true) {
delete notes[notes.activeEntry];
$setUIValue.setValue({
atomNoteTable: {
publish: {
id: notes.activeEntry,
add: false
}
}
});
}
else delete notes[notes.activeEntry];
}
else return false;
// Remove Entry //
html.notes.other.table.find('#'+notes.activeEntry).remove();
deleteCanvasNote(notes.activeEntry);
highlightNote('q',false);
// Clear Forms //
html.notes.properties.title.val('');
html.notes.other.body.val('');
html.notes.properties.opacity.selectpicker('val','10');
html.notes.properties.color.children().css('background','transparent');
};
// Select Active Note //
function selectNote(id){
highlightNote(notes.activeEntry,false);
html.notes.properties.title.val(notes[id].title);
html.notes.other.body.val(notes[id].body);
if (notes[id].color !== '') {
html.notes.properties.color.spectrum('set',notes[id].color);
html.notes.properties.color.children().css('background',notes[id].color);
}
if (notes[id].opacity !== '') html.notes.properties.opacity.selectpicker('val',notes[id].opacity);
highlightNote(id,true);
$disableUIElement.disableElement({
noteTitle:{
value: false
},
noteBody:{
value: false
},
noteOpacity:{
value: false
},
noteColor:{
value: false
},
newNote:{
value: true
},
saveNote:{
value: false
},
deleteNote:{
value: false
}
});
if (notes[id].atomNote === true) {
var x = parseInt(html.interface.screen.wrapper.find('#'+id).css('left'),10) + parseInt(html.interface.screen.wrapper.find('#'+id).css('width'),10) / 2;
var y = parseInt(html.interface.screen.wrapper.find('#'+id).css('top'),10) + parseInt(html.interface.screen.wrapper.find('#'+id).css('height'),10) / 2;
notes[id].x = x;
notes[id].y = y;
$setUIValue.setValue({
noteVisibility:{
publish: {id:id, visible: true, x: x, y: y, color: notes[id].color}
}
});
}
Object.keys(notes).forEach(function (key) {
var visibility = (key === id);
$setUIValue.setValue({
noteVisibility:{
value: visibility,
other: html.notes.other.table.find('#'+key)
}
});
showCanvasNote(key,visibility);
})
};
// Highlight Table Entry //
function highlightNote(id,state){
var color = (state) ? 'bg-light-purple' : 'bg-dark-gray';
html.notes.other.table.find('#'+id).removeAttr('class');
html.notes.other.table.find('#'+id).attr('class',color);
if (state === true) notes.activeEntry = id;
else notes.activeEntry = false;
};
// Show/Hide on Canvas //
function showCanvasNote(id,value){
if (value === true) html.interface.screen.wrapper.find('#'+id).show();
else html.interface.screen.wrapper.find('#'+id).hide();
};
// Create note on Canvas //
function createCanvasNote(id){
html.interface.screen.wrapper.prepend('<div id="'+id+'" class="noteWrapper"><div class="noteBar"><img class="closeNote" src="Images/close.png" /><img class="swapRight" src="Images/right.png" /><img class="swapLeft" src="Images/left.png" /><div class="noteTitle">Title</div></div><div class="wordwrap notes">'+notes[id].body+'</div></div>');
var notepad = html.interface.screen.wrapper.find('#'+id);
notepad.hide();
notepad.draggable({
scroll: false,
drag: function(event, ui){
var x = parseInt(ui.position.left) + parseInt(html.interface.screen.wrapper.find('#'+id).css('width'),10) / 2;
var y = parseInt(ui.position.top) + parseInt(html.interface.screen.wrapper.find('#'+id).css('height'),10) / 2;
notes[id].x = x;
notes[id].y = y;
if (notes[id].atomNote === true){
$setUIValue.setValue({
noteMovement:{
publish: { id: id, x: x, y: y }
}
});
}
},
containment: html.interface.screen.appContainer
});
// Close Note Handler //
notepad.find('img.closeNote').on('click',function(){
showCanvasNote(id,false);
$setUIValue.setValue({
noteVisibility:{
value: false,
other: html.notes.other.table.find('#'+id)
}
});
if (notes[id].atomNote === true) {
var x = parseInt(html.interface.screen.wrapper.find('#'+id).css('left'),10) + parseInt(html.interface.screen.wrapper.find('#'+id).css('width'),10) / 2;
var y = parseInt(html.interface.screen.wrapper.find('#'+id).css('top'),10) + parseInt(html.interface.screen.wrapper.find('#'+id).css('height'),10) / 2;
notes[id].x = x;
notes[id].y = y;
$setUIValue.setValue({
noteVisibility:{
publish: {id:id, visible: false, x: x, y: y, color: notes[id].color}
}
});
}
});
notepad.find('img.swapRight').on('click',function(){
var nextID = undefined;
// Find Next Note //
var table = {
first: jQuery('#'+html.notes.other.tableID+' tr:first'),
last: jQuery('#'+html.notes.other.tableID+' tr:last'),
current: html.notes.other.table.find('#'+id),
next: html.notes.other.table.find('#'+id).closest('tr').next('tr')
};
if (table.next.length > 0) nextID = table.next[0].id;
else nextID = table.first[0].id;
// Hide Current Note //
$setUIValue.setValue({
noteVisibility:{
value: false,
other: html.notes.other.table.find('#'+id)
}
});
if (notes[id].atomNote === true) {
var x = parseInt(html.interface.screen.wrapper.find('#'+id).css('left'),10) + parseInt(html.interface.screen.wrapper.find('#'+id).css('width'),10) / 2;
var y = parseInt(html.interface.screen.wrapper.find('#'+id).css('top'),10) + parseInt(html.interface.screen.wrapper.find('#'+id).css('height'),10) / 2;
notes[id].x = x;
notes[id].y = y;
$setUIValue.setValue({
noteVisibility:{
publish: {id:id, visible: false, x: x, y: y, color: notes[id].color}
}
});
}
showCanvasNote(id,false);
// Show Next Note //
$setUIValue.setValue({
noteVisibility:{
value: true,
other: html.notes.other.table.find('#'+nextID)
}
});
if (notes[nextID].atomNote === true) {
var x = parseInt(html.interface.screen.wrapper.find('#'+nextID).css('left'),10) + parseInt(html.interface.screen.wrapper.find('#'+nextID).css('width'),10) / 2;
var y = parseInt(html.interface.screen.wrapper.find('#'+nextID).css('top'),10) + parseInt(html.interface.screen.wrapper.find('#'+nextID).css('height'),10) / 2;
notes[nextID].x = x;
notes[nextID].y = y;
$setUIValue.setValue({
noteVisibility:{
publish: {id:nextID, visible: true, x: x, y: y, color: notes[nextID].color}
}
});
}
showCanvasNote(nextID,true);
});
notepad.find('img.swapLeft').on('click',function(){
var nextID = undefined;
// Find Next Note //
var table = {
first: jQuery('#'+html.notes.other.tableID+' tr:first'),
last: jQuery('#'+html.notes.other.tableID+' tr:last'),
current: html.notes.other.table.find('#'+id),
prev: html.notes.other.table.find('#'+id).closest('tr').prev('tr')
};
if (table.prev.length > 0) nextID = table.prev[0].id;
else nextID = table.last[0].id;
// Hide Current Note //
$setUIValue.setValue({
noteVisibility:{
value: false,
other: html.notes.other.table.find('#'+id)
}
});
if (notes[id].atomNote === true) {
var x = parseInt(html.interface.screen.wrapper.find('#'+id).css('left'),10) + parseInt(html.interface.screen.wrapper.find('#'+id).css('width'),10) / 2;
var y = parseInt(html.interface.screen.wrapper.find('#'+id).css('top'),10) + parseInt(html.interface.screen.wrapper.find('#'+id).css('height'),10) / 2;
notes[id].x = x;
notes[id].y = y;
$setUIValue.setValue({
noteVisibility:{
publish: {id:id, visible: false, x: x, y: y, color: notes[id].color}
}
});
}
showCanvasNote(id,false);
// Show Next Note //
$setUIValue.setValue({
noteVisibility:{
value: true,
other: html.notes.other.table.find('#'+nextID)
}
});
if (notes[nextID].atomNote === true) {
var x = parseInt(html.interface.screen.wrapper.find('#'+nextID).css('left'),10) + parseInt(html.interface.screen.wrapper.find('#'+nextID).css('width'),10) / 2;
var y = parseInt(html.interface.screen.wrapper.find('#'+nextID).css('top'),10) + parseInt(html.interface.screen.wrapper.find('#'+nextID).css('height'),10) / 2;
notes[nextID].x = x;
notes[nextID].y = y;
$setUIValue.setValue({
noteVisibility:{
publish: {id:nextID, visible: true, x: x, y: y, color: notes[nextID].color}
}
});
}
showCanvasNote(nextID,true);
});
};
// Delete note from canvas //
function deleteCanvasNote(id){
html.interface.screen.wrapper.find('#'+id).remove();
};
// Get all notes //
function getAtomNoteTable(){
var table = [];
_.each(notes, function($parameter,k){
if ($parameter.atomNote === true) {
var x = parseInt(html.interface.screen.wrapper.find('#'+k).css('left'),10) + parseInt(html.interface.screen.wrapper.find('#'+k).css('width'),10) / 2;
var y = parseInt(html.interface.screen.wrapper.find('#'+k).css('top'),10) + parseInt(html.interface.screen.wrapper.find('#'+k).css('height'),10) / 2;
notes[k].x = x;
notes[k].y = y;
table.push({
id: k,
x: x,
y: y
});
}
});
return table;
};
// Module Interface //
// Focus note on Note Tab //
notesTab.prototype.moveToNote = function(id){
$menuRibbon.switchTab('notesTab');
// Create new note if none is specified //
if (_.isUndefined(notes[id])) {
highlightNote(notes.activeEntry,false);
highlightNote(addNote(id),true);
$disableUIElement.disableElement({
noteTitle:{
value: false
},
noteBody:{
value: false
},
noteOpacity:{
value: false
},
noteColor:{
value: false
},
newNote:{
value: true
},
saveNote:{
value: false
},
deleteNote:{
value: false
}
});
}
else selectNote(id);
};
notesTab.prototype.getAtomNoteTable = function(){
return getAtomNoteTable();
};
// Show Note on Canvas //
notesTab.prototype.focusNote = function(id){
if(_.isUndefined(notes[id.toString()])) return false;
else{
if(html.notes.other.table.find('#'+id).find('.noteButton').hasClass('visible')) return true;
else {
$setUIValue.setValue({
noteVisibility:{
value: true,
other: html.notes.other.table.find('#'+id)
}
});
showCanvasNote(id.toString(),true);
// Mark to close
notes[id.toString()].temp = true;
// System //
var x = parseInt(html.interface.screen.wrapper.find('#'+id).css('left'),10) + parseInt(html.interface.screen.wrapper.find('#'+id).css('width'),10) / 2;
var y = parseInt(html.interface.screen.wrapper.find('#'+id).css('top'),10) + parseInt(html.interface.screen.wrapper.find('#'+id).css('height'),10) / 2;
$setUIValue.setValue({
noteVisibility:{
publish: {id:id, visible: true, x: x, y: y, color: notes[id.toString()].color}
}
});
}
};
};
notesTab.prototype.getNotes = function(){
return notes;
};
// Restore UI + Database //
notesTab.prototype.restoreNotes = function(notesJSON){
_.each(notesJSON, function($parameter,k){
if (k !== 'activeEntry') {
// Parse possible atom connection //
var atomConnection = undefined;
if ($parameter.atomNote === 'false') atomConnection = false;
else atomConnection = true;
// Add empty note and select it //
highlightNote(notes.activeEntry,false);
highlightNote(addNote(k,true),true);
// Overwrite with data from the JSON file //
editNote({
title: $parameter.title,
opacity: $parameter.opacity,
color: $parameter.color,
body: $parameter.body,
atomNote: atomConnection,
x: parseInt($parameter.x),
y: parseInt($parameter.y)
});
if (atomConnection) {
$setUIValue.setValue({
saveNoteForSystem:{
publish: {id:k, cameraToggle : true, sceneObjsToggle : true }
}
});
}
}
});
};
notesTab.prototype.resetTable = function(){
html.notes.other.table.find('tbody').html('');
};
notesTab.prototype.doSmthWithSystemCamState = function(arg){
cameraData[arg.id] = arg ;
};
return notesTab;
}); |
'use strict';
var HapiCapitalizeModules = require('hapi-capitalize-modules');
var HapiForYou = require('hapi-for-you');
var HapiScopeStart = require('hapi-scope-start');
var NoArrowception = require('no-arrowception');
module.exports = {
rules: {
'hapi-capitalize-modules': HapiCapitalizeModules,
'hapi-for-you': HapiForYou,
'hapi-scope-start': HapiScopeStart,
'no-arrowception': NoArrowception
}
};
|
require('seneca')()
.use('../plugins/salestax-basic.js',{rate:0.2})
.listen()
|
var getTree = function (table, idIndex, pidIndex) {
var ids = _.pluck(table, idIndex);
var pids = _.pluck(table, pidIndex);
var rootIDs = _.difference(pids, ids);
var roots = table.filter(function (row) {
return _.indexOf(rootIDs, row[pidIndex]) !== -1;
});
roots.forEach(function (root) {
root.childs = table.filter(function (row) {
return row[pidIndex] === root[idIndex];
});
});
return roots;
}; |
/*
* Copyright (C) 2013 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
WebInspector.CodeMirrorUtils = {
/**
* @param {string} mimeType
* @return {function(string, function(string, string, number, number))}
*/
createTokenizer: function(mimeType)
{
var mode = CodeMirror.getMode({indentUnit: 2}, mimeType);
var state = CodeMirror.startState(mode);
function tokenize(line, callback)
{
var stream = new CodeMirror.StringStream(line);
while (!stream.eol()) {
var style = mode.token(stream, state);
var value = stream.current();
callback(value, style, stream.start, stream.start + value.length);
stream.start = stream.pos;
}
}
return tokenize;
},
/**
* @param {string} tokenType
*/
convertTokenType: function(tokenType)
{
if (tokenType.startsWith("js-variable") || tokenType.startsWith("js-property") || tokenType === "js-def")
return "javascript-ident";
if (tokenType === "js-string-2")
return "javascript-regexp";
if (tokenType === "js-number" || tokenType === "js-comment" || tokenType === "js-string" || tokenType === "js-keyword")
return "javascript-" + tokenType.substring("js-".length);
if (tokenType === "css-number")
return "css-number";
return null;
},
/**
* @param {string} modeName
* @param {string} tokenPrefix
*/
overrideModeWithPrefixedTokens: function(modeName, tokenPrefix)
{
var oldModeName = modeName + "-old";
if (CodeMirror.modes[oldModeName])
return;
CodeMirror.defineMode(oldModeName, CodeMirror.modes[modeName]);
CodeMirror.defineMode(modeName, modeConstructor);
function modeConstructor(config, parserConfig)
{
var innerConfig = {};
for (var i in parserConfig)
innerConfig[i] = parserConfig[i];
innerConfig.name = oldModeName;
var codeMirrorMode = CodeMirror.getMode(config, innerConfig);
codeMirrorMode.name = modeName;
codeMirrorMode.token = tokenOverride.bind(this, codeMirrorMode.token);
return codeMirrorMode;
}
function tokenOverride(superToken, stream, state)
{
var token = superToken(stream, state);
return token ? tokenPrefix + token : token;
}
}
}
WebInspector.CodeMirrorUtils.overrideModeWithPrefixedTokens("css-base", "css-");
WebInspector.CodeMirrorUtils.overrideModeWithPrefixedTokens("javascript", "js-");
WebInspector.CodeMirrorUtils.overrideModeWithPrefixedTokens("xml", "xml-");
|
/*
* HomePage Messages
*
* This contains all the text for the HomePage component.
*/
import { defineMessages } from 'react-intl';
export const scope = 'boilerplate.containers.HomePage';
export default defineMessages({
startProjectHeader: {
id: `${scope}.start_project.header`,
defaultMessage: 'Start your next react project in seconds',
},
startProjectMessage: {
id: `${scope}.start_project.message`,
defaultMessage:
'A highly scalable, offline-first foundation with the best DX and a focus on performance and best practices',
},
trymeHeader: {
id: `${scope}.tryme.header`,
defaultMessage: 'Try me!',
},
trymeMessage: {
id: `${scope}.tryme.message`,
defaultMessage: 'Show Github repositories by',
},
trymeAtPrefix: {
id: `${scope}.tryme.atPrefix`,
defaultMessage: '@',
},
});
|
(function(){self.JSREPLEngine=function(){function c(b,a,d,c,e,f){var g=this;this.input=b;this.output=a;this.result=d;this.error=c;this.sandbox=e;this.Unlambda=this.sandbox.Unlambda;this.result=function(a){return d(g.Unlambda.unparse(a))};f()}c.prototype.Eval=function(b){var a;try{a=this.Unlambda.parse(b)}catch(d){this.error(d);return}return this.Unlambda.eval(a,this.result,this.input,this.output,this.error)};c.prototype.EvalSync=function(b){var a;a=null;this.Unlambda.eval(this.Unlambda.parse(b),function(d){return a=
d},function(a){return a()},this.output,function(a){throw a;});return a};c.prototype.GetNextLineIndent=function(b){if(/`$/.test(b))return 0;try{return this.Unlambda.parse(b),false}catch(a){return 0}};return c}()}).call(this);
|
var gulp = require('gulp');
var jshint = require('gulp-jshint');
// config
var config = require('../../config.json');
// options
var options = require('../options/jshint');
module.exports = function () {
return gulp.src([config.destination.js + '/**/*.js', '!' + config.destination.js + '/**/*.min.js'])
.pipe(jshint(options))
.pipe(jshint.reporter('default'))
};
|
import repl from 'repl';
import net from 'net';
import logger from 'common/utils/logger';
/**
* Create the server and start listening on the given port.
*/
export function createServer (port) {
log('listening for REPL connections on port', port);
net.createServer((socket) => {
const r = repl.start({
prompt: 'browser@' + global.manifest.name + '> ',
input: socket,
output: socket,
terminal: true
});
r.on('exit', () => {
socket.end();
});
// Bridge loggers
r.context.log = logger.debugLogger('repl');
r.context.logError = logger.errorLogger('repl', false);
r.context.logFatal = logger.errorLogger('repl', true);
}).listen(port);
}
|
if ( !this.message ) {
error('message', "tell what make you happy");
}
if (this.level < 1 || this.level > 5) {
error('level', "values between 1 and 5");
}
if( this.latlng )
{
var isFloat = function(n){
return n === Number(n) && n%1 !== 0;
};
if ( !this.latlng.lat || !this.latlng.lng ) {
error('latlong', "Latlong must have lat and long properties");
}
if ( !this.latlng.lat || !isFloat(this.latlng.lat) ) {
error('latlong', "Latlong.lat must be a number");
}
if ( !this.latlng.lng || !isFloat(this.latlng.lng) ) {
error('latlong', "Latlong.long must be a number");
}
} |
/**
* Configuration file for font-awesome-webpack
*
* In order to keep the bundle size low in production,
* disable components you don't use.
*
*/
module.exports = {
styles: {
mixins: true,
core: true,
icons: true,
larger: true,
path: true,
animated: true,
}
}
|
/**
* Internationalization / Localization Settings
*
* If your app will touch people from all over the world, i18n (or internationalization)
* may be an important part of your international strategy.
*
*
* For more information, check out:
* http://sailsjs.org/#documentation
*/
module.exports.i18n = {
// Which locales are supported?
locales: ['en', 'es', 'fr', 'de'],
defaultLocale: 'es',
directory: 'config/locales',
updateFiles: true
};
|
module.exports = {
description: 'install bower dependencies',
normalizeEntityName: function() {},
afterInstall: function(options) {
var _this = this;
return _this.addBowerPackageToProject('moment').then(function() {
return _this.addBowerPackageToProject('moment-duration-format');
});
}
};
|
import * as echarts from '../../echarts';
import * as zrUtil from 'zrender/src/core/util';
import * as helper from './helper';
echarts.registerAction('dataZoom', function (payload, ecModel) {
var linkedNodesFinder = helper.createLinkedNodesFinder(
zrUtil.bind(ecModel.eachComponent, ecModel, 'dataZoom'),
helper.eachAxisDim,
function (model, dimNames) {
return model.get(dimNames.axisIndex);
}
);
var effectedModels = [];
ecModel.eachComponent(
{mainType: 'dataZoom', query: payload},
function (model, index) {
effectedModels.push.apply(
effectedModels, linkedNodesFinder(model).nodes
);
}
);
zrUtil.each(effectedModels, function (dataZoomModel, index) {
dataZoomModel.setRawRange({
start: payload.start,
end: payload.end,
startValue: payload.startValue,
endValue: payload.endValue
});
});
});
|
var mongoose = require('mongoose'),
User = require('./userAuth'),
connStr = 'mongodb://127.0.0.1:27017/440w';
//We want to check to see if the user already exists in the datebase
this.checkUser = function(userName, userPass, cb){
//Initialize Our Connection To The MongoDB With Our Provided Connection String
mongoose.connect(connStr, function(err) {
if (err) throw err;
console.log('LOGIN::checkUser::Successfully connected to MongoDB');
});
//We Use Our findOne Prototype That Queries The Database To See If It Can Find
//A User With The Set Of Credentials
var exists = User.findOne({ email: userName });
exists.exec(function(err, user){
if(err){
cb(err);
} else if(user) {
user.comparePassword(userPass, function(err, isMatch) {
if (err) throw err;
if(mongoose.connection.close()){
console.log('LOGIN::checkUser::closed connection to MongoDB');
}
if (isMatch){
cb(null,user);
} else {
cb(null);
}
});
} else {
if(mongoose.connection.close()){
console.log('LOGIN::checkUser::closed connection to MongoDB');
}
cb(null);
}
});
};
|
function dayOfWeek(){var e=new Date,n=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];return n[e.getDay()]}window.onload=function(){function e(){function e(){if("undefined"!=typeof window.scrollY)return window.scrollY;var e=document.documentElement;return e.clientHeight?e.scrollTop:document.body.scrollTop}if(window.innerWidth>=1e3)window.onscroll=function(){var n=document.getElementById("box"),o=e();28>=o?n.style.top="0px":n.style.top=o+2+"px"};else{window.onscroll=null;var n=document.getElementById("box");n.style.top="0px"}}e(),window.addEventListener("resize",e,!1),document.getElementById("day").innerHTML=dayOfWeek()}; |
'use strict';
define([
'jquery',
'three',
'explorer',
'underscore'
], function(
jQuery,
THREE,
Explorer,
_
) {
var clocks = {
rotUp : new THREE.Clock(),
rotDown : new THREE.Clock(),
rotLeft : new THREE.Clock(),
rotRight : new THREE.Clock(),
up : new THREE.Clock(),
down : new THREE.Clock(),
forth : new THREE.Clock(),
back : new THREE.Clock(),
left : new THREE.Clock(),
right : new THREE.Clock(),
orbitRreduce : new THREE.Clock(),
orbitRincrease : new THREE.Clock()
};
var clock = new THREE.Clock();
function KeyboardKeys(keyboard, crystalScene, orbitCrystal, meTemporal, crystalRendererTemporal, lattice) {
this.keyboard = keyboard;
this.crystalScene = crystalScene;
this.orbitCrystal = orbitCrystal;
this.dollmode = false;
this.mutex = false;
this.hidden = true;
this.meTemporal = meTemporal;
this.lastCameraPosition = {cam : new THREE.Vector3(), cube : new THREE.Vector3()};
this.crystalRendererTemporal = crystalRendererTemporal;
this.atomCustomizer ;
this.lattice = lattice;
};
KeyboardKeys.prototype.handleKeys = function(leapArg, speed, passport){
var _this = this;
if(this.dollmode === true || passport !== undefined){
// set limits of world
var distToCenter = (this.orbitCrystal.camera.position).distanceTo(new THREE.Vector3(0,0,0)) ;
if(distToCenter > 2500){
this.orbitCrystal.camera.position.copy(this.lastCameraPosition.cam);
this.crystalScene.movingCube.position.copy(this.lastCameraPosition.cube);
return;
}
this.lastCameraPosition.cam = this.orbitCrystal.camera.position.clone();
this.lastCameraPosition.cube = this.crystalScene.movingCube.position.clone();
speed = (speed === undefined) ? 1 : speed ;
var delta = (leapArg === undefined) ? clock.getDelta() : clocks[Object.keys(leapArg)[0]].getDelta(), helperVec;
if(delta > 0.1) {
delta = 0.1;
}
var camPos = this.orbitCrystal.camera.position ;
var cubePos = this.crystalScene.movingCube.position;
var rotationDistance = 0.2 * delta * speed ;
// algorithm to smoothly move camera
var par = Math.exp(distToCenter/50);
var distFactor = par ;
if(leapArg === undefined){
if(distFactor > 30 && distFactor < 50){
distFactor = 30 + (distFactor - 20)/2 ;
}
else if(distFactor > 50 && distFactor < 70){
distFactor = 40 + (distFactor - 40)/3 ;
}
else if(distFactor > 70 && distFactor < 80){
distFactor = 45 + (distFactor - 60)/5 ;
}
if(distFactor > 80){
distFactor = 50 ;
}
}
else{
if(distFactor > 10){
distFactor = 10;
}
}
//
leapArg = (leapArg === undefined) ? {} : leapArg ;
var timeInputDistFactor = (leapArg === undefined) ? ( delta * speed * distFactor) : (5 * delta * speed * distFactor);
var camToCubeDistance = (cubePos.clone()).sub(camPos).length() * speed ;
var camToCubeVec = (cubePos.clone()).sub(camPos) ;
camToCubeVec.setLength(timeInputDistFactor);
if ( this.keyboard.pressed("A") || (leapArg.left !== undefined)){
helperVec = (new THREE.Vector3(cubePos.x, camPos.y, cubePos.z)).sub(camPos);
helperVec.applyAxisAngle( new THREE.Vector3( 0, 1, 0 ), Math.PI / 2 );
///
helperVec.setLength(camToCubeVec.length()/2);
///
camPos.add(helperVec);
cubePos.add(helperVec);
}
if ( this.keyboard.pressed("D") || (leapArg.right !== undefined)){
helperVec = (new THREE.Vector3(cubePos.x, camPos.y, cubePos.z)).sub(camPos);
helperVec.applyAxisAngle( new THREE.Vector3( 0, 1, 0 ), Math.PI / -2 );
///
helperVec.setLength(camToCubeVec.length()/2);
///
camPos.add(helperVec);
cubePos.add(helperVec);
}
if ( this.keyboard.pressed("W") || (leapArg.forth !== undefined) ){
camPos.add(camToCubeVec);
cubePos.add(camToCubeVec);
}
if ( this.keyboard.pressed("S") || (leapArg.back !== undefined)){
camToCubeVec.negate();
camPos.add(camToCubeVec);
cubePos.add(camToCubeVec);
}
if ( this.keyboard.pressed("shift") || (leapArg.down !== undefined)){
camPos.y -= timeInputDistFactor/2 ;
cubePos.y -= timeInputDistFactor/2 ;
}
if ( this.keyboard.pressed("space") || (leapArg.up !== undefined)){
camPos.y += timeInputDistFactor/2 ;
cubePos.y += timeInputDistFactor/2 ;
}
//console.log(this.keyboard.pressed("numPad5"));
// rotations
if ( this.keyboard.pressed("numPad5") || (leapArg.rotUp !== undefined)){
this.orbitCrystal.control.rotateUp(rotationDistance);
}
if ( this.keyboard.pressed("numPad8") || (leapArg.rotDown !== undefined)){
this.orbitCrystal.control.rotateUp(-1 *rotationDistance);
}
if ( this.keyboard.pressed("numPad4") || (leapArg.rotLeft !== undefined)){
this.orbitCrystal.control.rotateLeft(-1 * rotationDistance);
}
if ( this.keyboard.pressed("numPad6") || (leapArg.rotRight !== undefined)){
this.orbitCrystal.control.rotateLeft( rotationDistance);
}
if ( leapArg.orbitRreduce !== undefined && camToCubeDistance > 0.9){
var camToCubeFact = delta * (1 + camToCubeDistance ) ;
camToCubeVec.setLength(camToCubeFact);
camPos.add(camToCubeVec);
}
else if ( leapArg.orbitRincrease !== undefined && camToCubeDistance >0.9){
camToCubeVec.negate();
var camToCubeFact = delta*(1 + camToCubeDistance ) ;
camToCubeVec.setLength(camToCubeFact);
camPos.add(camToCubeVec);
}
if((cubePos.clone()).sub(camPos).length() <= 0.9){
// to avoid stucking for ever
camToCubeVec.negate();
camPos.add(camToCubeVec);
}
this.orbitCrystal.control.target = cubePos;
this.orbitCrystal.control.rotateSpeed = 0.2;
}
///// Secret Features
if ( this.keyboard.pressed("A") && this.keyboard.pressed("ctrl") ){
if(this.mutex === false){
this.mutex = true;
this.atomCustomizer.menuIsOpen = false;
for (var i = this.lattice.actualAtoms.length - 1; i >= 0; i--) {
this.atomCustomizer.atomJustClicekd(this.lattice.actualAtoms[i], true);
};
setTimeout(function(){ _this.mutex = false;}, 400 );
}
}
if ( this.keyboard.pressed("C") && this.keyboard.pressed("alt") && this.keyboard.pressed("ctrl") ){
//delete cookie
document.cookie = "hasVisited=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
}
if ( this.keyboard.pressed("O") && this.keyboard.pressed("alt") && this.keyboard.pressed("ctrl") ){
if(this.mutex === false){
this.mutex = true;
if( this.hidden === true){
$('#secretMenu').show();
this.hidden = false;
}
else{
$('#secretMenu').hide();
this.hidden = true;
this.crystalRendererTemporal.stereoscopicEffect.setNewMaterial({'blue' :3 , 'red' : 3});
}
setTimeout(function(){ _this.mutex = false;}, 200 );
}
}
if ( this.keyboard.pressed("P") && this.keyboard.pressed("alt") && this.keyboard.pressed("ctrl") ){
if(this.mutex === false){
this.mutex = true;
if( this.hidden === true){
$('#grainStats').show();
this.hidden = false;
this.crystalRendererTemporal.rstatsON = true;
}
else{
$('#grainStats').hide();
this.hidden = true;
this.crystalRendererTemporal.rstatsON = false;
}
setTimeout(function(){ _this.mutex = false;}, 200 );
}
}
if ( this.keyboard.pressed("B") && false){
if(this.mutex === false){
this.mutex = true;
if( this.meTemporal.box3.bool === true){
this.meTemporal.box3.bool = false;
}
else{
this.meTemporal.box3.bool = true;
}
setTimeout(function(){ _this.mutex = false;}, 200 );
}
}
};
return KeyboardKeys;
});
|
/**
* Initialize standard build of the TinyMCE
*
* @param options
*/
function initTinyMCE(options) {
(function ($, undefined) {
$(function () {
var $tinymceTargets;
if(options.textarea_class){
$tinymceTargets = $('textarea' + options.textarea_class);
} else {
$tinymceTargets = $('textarea');
}
$tinymceTargets.each(function () {
var $textarea = $(this),
theme = $textarea.data('theme') || 'simple';
// Get selected theme options
var themeOptions = (typeof options.theme[theme] != 'undefined')
? options.theme[theme]
: options.theme['simple'];
themeOptions.script_url = options.jquery_script_url;
// workaround for an incompatibility with html5-validation (see: http://git.io/CMKJTw)
if ($textarea.is('[required]')) {
themeOptions.oninit = function (editor) {
editor.onChange.add(function (ed) {
ed.save();
});
};
}
// Add custom buttons to current editor
if (typeof options.tinymce_buttons == 'object') {
themeOptions.setup = function (ed) {
$.each(options.tinymce_buttons, function (id, opts) {
opts = $.extend({}, opts, {
onclick:function () {
var callback = window['tinymce_button_' + id];
if (typeof callback == 'function') {
callback(ed);
} else {
alert('You have to create callback function: "tinymce_button_' + id + '"');
}
}
});
ed.addButton(id, opts);
});
}
}
$textarea.tinymce(themeOptions);
});
});
}(jQuery));
} |
/**
* ag-grid-community - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v21.0.1
* @link http://www.ag-grid.com/
* @license MIT
*/
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
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);
};
Object.defineProperty(exports, "__esModule", { value: true });
var componentAnnotations_1 = require("../../../widgets/componentAnnotations");
var utils_1 = require("../../../utils");
var simpleFilter_1 = require("../simpleFilter");
var scalerFilter_1 = require("../scalerFilter");
var NumberFilter = /** @class */ (function (_super) {
__extends(NumberFilter, _super);
function NumberFilter() {
return _super !== null && _super.apply(this, arguments) || this;
}
NumberFilter.prototype.mapRangeFromModel = function (filterModel) {
return {
from: filterModel.filter,
to: filterModel.filterTo
};
};
NumberFilter.prototype.getDefaultDebounceMs = function () {
return 500;
};
NumberFilter.prototype.resetUiToDefaults = function () {
_super.prototype.resetUiToDefaults.call(this);
this.eValueFrom1.value = null;
this.eValueFrom2.value = null;
this.eValueTo1.value = null;
this.eValueTo2.value = null;
};
NumberFilter.prototype.setConditionIntoUi = function (model, position) {
var positionOne = position === simpleFilter_1.ConditionPosition.One;
var eValueFrom = positionOne ? this.eValueFrom1 : this.eValueFrom2;
var eValueTo = positionOne ? this.eValueTo1 : this.eValueTo2;
eValueFrom.value = model ? ('' + model.filter) : null;
eValueTo.value = model ? ('' + model.filterTo) : null;
};
NumberFilter.prototype.setValueFromFloatingFilter = function (value) {
this.eValueFrom1.value = value;
this.eValueFrom2.value = null;
this.eValueTo1.value = null;
this.eValueTo2.value = null;
};
NumberFilter.prototype.comparator = function () {
return function (left, right) {
if (left === right) {
return 0;
}
if (left < right) {
return 1;
}
if (left > right) {
return -1;
}
};
};
NumberFilter.prototype.setParams = function (params) {
_super.prototype.setParams.call(this, params);
this.addValueChangedListeners();
};
NumberFilter.prototype.addValueChangedListeners = function () {
var _this = this;
var listener = function () { return _this.onUiChanged(); };
this.addDestroyableEventListener(this.eValueFrom1, 'input', listener);
this.addDestroyableEventListener(this.eValueFrom2, 'input', listener);
this.addDestroyableEventListener(this.eValueTo1, 'input', listener);
this.addDestroyableEventListener(this.eValueTo2, 'input', listener);
};
NumberFilter.prototype.afterGuiAttached = function () {
this.eValueFrom1.focus();
};
NumberFilter.prototype.getDefaultFilterOptions = function () {
return NumberFilter.DEFAULT_FILTER_OPTIONS;
};
NumberFilter.prototype.createValueTemplate = function (position) {
var positionOne = position === simpleFilter_1.ConditionPosition.One;
var pos = positionOne ? '1' : '2';
var translate = this.translate.bind(this);
return "<div class=\"ag-filter-body\" ref=\"eCondition" + pos + "Body\">\n <div class=\"ag-input-text-wrapper\">\n <input class=\"ag-filter-filter\" ref=\"eValueFrom" + pos + "\" type=\"text\" placeholder=\"" + translate('filterOoo') + "\"/>\n </div>\n <div class=\"ag-input-text-wrapper ag-filter-number-to\" ref=\"ePanel" + pos + "\">\n <input class=\"ag-filter-filter\" ref=\"eValueTo" + pos + "\" type=\"text\" placeholder=\"" + translate('filterOoo') + "\"/>\n </div>\n </div>";
};
NumberFilter.prototype.isConditionUiComplete = function (position) {
var positionOne = position === simpleFilter_1.ConditionPosition.One;
var option = positionOne ? this.getCondition1Type() : this.getCondition2Type();
var eValue = positionOne ? this.eValueFrom1 : this.eValueFrom2;
var eValueTo = positionOne ? this.eValueTo1 : this.eValueTo2;
var value = this.stringToFloat(eValue.value);
var valueTo = this.stringToFloat(eValueTo.value);
if (option === simpleFilter_1.SimpleFilter.EMPTY) {
return false;
}
if (this.doesFilterHaveHiddenInput(option)) {
return true;
}
if (option === simpleFilter_1.SimpleFilter.IN_RANGE) {
return value != null && valueTo != null;
}
else {
return value != null;
}
};
NumberFilter.prototype.areSimpleModelsEqual = function (aSimple, bSimple) {
return aSimple.filter === bSimple.filter
&& aSimple.filterTo === bSimple.filterTo
&& aSimple.type === bSimple.type;
};
// needed for creating filter model
NumberFilter.prototype.getFilterType = function () {
return NumberFilter.FILTER_TYPE;
};
NumberFilter.prototype.stringToFloat = function (value) {
var filterText = utils_1._.makeNull(value);
if (filterText && filterText.trim() === '') {
filterText = null;
}
var newFilter;
if (filterText !== null && filterText !== undefined) {
newFilter = parseFloat(filterText);
}
else {
newFilter = null;
}
return newFilter;
};
NumberFilter.prototype.createCondition = function (position) {
var positionOne = position === simpleFilter_1.ConditionPosition.One;
var type = positionOne ? this.getCondition1Type() : this.getCondition2Type();
var eValue = positionOne ? this.eValueFrom1 : this.eValueFrom2;
var value = this.stringToFloat(eValue.value);
var eValueTo = positionOne ? this.eValueTo1 : this.eValueTo2;
var valueTo = this.stringToFloat(eValueTo.value);
var model = {
filterType: NumberFilter.FILTER_TYPE,
type: type
};
if (!this.doesFilterHaveHiddenInput(type)) {
model.filter = value;
model.filterTo = valueTo; // FIX - should only populate this when filter choice has 'to' option
}
return model;
};
NumberFilter.prototype.updateUiVisibility = function () {
_super.prototype.updateUiVisibility.call(this);
var showFrom1 = this.showValueFrom(this.getCondition1Type());
utils_1._.setVisible(this.eValueFrom1, showFrom1);
var showTo1 = this.showValueTo(this.getCondition1Type());
utils_1._.setVisible(this.eValueTo1, showTo1);
var showFrom2 = this.showValueFrom(this.getCondition2Type());
utils_1._.setVisible(this.eValueFrom2, showFrom2);
var showTo2 = this.showValueTo(this.getCondition2Type());
utils_1._.setVisible(this.eValueTo2, showTo2);
};
NumberFilter.FILTER_TYPE = 'number';
NumberFilter.DEFAULT_FILTER_OPTIONS = [scalerFilter_1.ScalerFilter.EQUALS, scalerFilter_1.ScalerFilter.NOT_EQUAL,
scalerFilter_1.ScalerFilter.LESS_THAN, scalerFilter_1.ScalerFilter.LESS_THAN_OR_EQUAL,
scalerFilter_1.ScalerFilter.GREATER_THAN, scalerFilter_1.ScalerFilter.GREATER_THAN_OR_EQUAL,
scalerFilter_1.ScalerFilter.IN_RANGE];
__decorate([
componentAnnotations_1.RefSelector('eValueFrom1'),
__metadata("design:type", HTMLInputElement)
], NumberFilter.prototype, "eValueFrom1", void 0);
__decorate([
componentAnnotations_1.RefSelector('eValueFrom2'),
__metadata("design:type", HTMLInputElement)
], NumberFilter.prototype, "eValueFrom2", void 0);
__decorate([
componentAnnotations_1.RefSelector('eValueTo1'),
__metadata("design:type", HTMLInputElement)
], NumberFilter.prototype, "eValueTo1", void 0);
__decorate([
componentAnnotations_1.RefSelector('eValueTo2'),
__metadata("design:type", HTMLInputElement)
], NumberFilter.prototype, "eValueTo2", void 0);
return NumberFilter;
}(scalerFilter_1.ScalerFilter));
exports.NumberFilter = NumberFilter;
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const ts = require("typescript");
const semver_1 = require("semver");
const interfaces_1 = require("./interfaces");
const elide_imports_1 = require("./elide_imports");
// Typescript below 2.5.0 needs a workaround.
const visitEachChild = semver_1.satisfies(ts.version, '^2.5.0')
? ts.visitEachChild
: visitEachChildWorkaround;
function makeTransform(standardTransform, getTypeChecker) {
return (context) => {
const transformer = (sf) => {
const ops = standardTransform(sf);
const removeOps = ops
.filter((op) => op.kind === interfaces_1.OPERATION_KIND.Remove);
const addOps = ops.filter((op) => op.kind === interfaces_1.OPERATION_KIND.Add);
const replaceOps = ops
.filter((op) => op.kind === interfaces_1.OPERATION_KIND.Replace);
// If nodes are removed, elide the imports as well.
// Mainly a workaround for https://github.com/Microsoft/TypeScript/issues/17552.
// WARNING: this assumes that replaceOps DO NOT reuse any of the nodes they are replacing.
// This is currently true for transforms that use replaceOps (replace_bootstrap and
// replace_resources), but may not be true for new transforms.
if (getTypeChecker && removeOps.length + replaceOps.length > 0) {
const removedNodes = removeOps.concat(replaceOps).map((op) => op.target);
removeOps.push(...elide_imports_1.elideImports(sf, removedNodes, getTypeChecker));
}
const visitor = (node) => {
let modified = false;
let modifiedNodes = [node];
// Check if node should be dropped.
if (removeOps.find((op) => op.target === node)) {
modifiedNodes = [];
modified = true;
}
// Check if node should be replaced (only replaces with first op found).
const replace = replaceOps.find((op) => op.target === node);
if (replace) {
modifiedNodes = [replace.replacement];
modified = true;
}
// Check if node should be added to.
const add = addOps.filter((op) => op.target === node);
if (add.length > 0) {
modifiedNodes = [
...add.filter((op) => op.before).map(((op) => op.before)),
...modifiedNodes,
...add.filter((op) => op.after).map(((op) => op.after))
];
modified = true;
}
// If we changed anything, return modified nodes without visiting further.
if (modified) {
return modifiedNodes;
}
else {
// Otherwise return node as is and visit children.
return visitEachChild(node, visitor, context);
}
};
// Don't visit the sourcefile at all if we don't have ops for it.
if (ops.length === 0) {
return sf;
}
const result = ts.visitNode(sf, visitor);
// If we removed any decorators, we need to clean up the decorator arrays.
if (removeOps.some((op) => op.target.kind === ts.SyntaxKind.Decorator)) {
cleanupDecorators(result);
}
return result;
};
return transformer;
};
}
exports.makeTransform = makeTransform;
/**
* This is a version of `ts.visitEachChild` that works that calls our version
* of `updateSourceFileNode`, so that typescript doesn't lose type information
* for property decorators.
* See https://github.com/Microsoft/TypeScript/issues/17384 and
* https://github.com/Microsoft/TypeScript/issues/17551, fixed by
* https://github.com/Microsoft/TypeScript/pull/18051 and released on TS 2.5.0.
*
* @param sf
* @param statements
*/
function visitEachChildWorkaround(node, visitor, context) {
if (node.kind === ts.SyntaxKind.SourceFile) {
const sf = node;
const statements = ts.visitLexicalEnvironment(sf.statements, visitor, context);
if (statements === sf.statements) {
return sf;
}
// Note: Need to clone the original file (and not use `ts.updateSourceFileNode`)
// as otherwise TS fails when resolving types for decorators.
const sfClone = ts.getMutableClone(sf);
sfClone.statements = statements;
return sfClone;
}
return ts.visitEachChild(node, visitor, context);
}
// 1) If TS sees an empty decorator array, it will still emit a `__decorate` call.
// This seems to be a TS bug.
// 2) Also ensure nodes with modified decorators have parents
// built in TS transformers assume certain nodes have parents (fixed in TS 2.7+)
function cleanupDecorators(node) {
if (node.decorators) {
if (node.decorators.length == 0) {
node.decorators = undefined;
}
else if (node.parent == undefined) {
const originalNode = ts.getParseTreeNode(node);
node.parent = originalNode.parent;
}
}
ts.forEachChild(node, node => cleanupDecorators(node));
}
//# sourceMappingURL=/users/hansl/sources/hansl/angular-cli/src/transformers/make_transform.js.map |
/* first banner */
/* second banner */
console.log( 1 + 1 );
/* first footer */
/* second footer */
|
'use strict';
var Parsimmon = require('parsimmon');
module.exports = join;
function join(expr, seperator, count) {
count = count || 0;
var defaultToken = count > 0 ?
Parsimmon.fail('must join() at least 1 token') :
Parsimmon.succeed([]);
return expr.chain(function (value) {
return seperator
.then(expr)
.atLeast(count - 1).map(function (values) {
return [value].concat(values);
});
}).or(defaultToken);
}
|
import React from 'react';
import ReactDOM from 'react-dom';
import JqxScheduler from '../../../jqwidgets-react/react_jqxscheduler.js';
class App extends React.Component {
componentDidMount () {
setTimeout(() => {
this.refs.myScheduler.scrollTop(700);
})
}
render () {
// prepare the data
let source =
{
dataType: 'json',
dataFields: [
{ name: 'id', type: 'string' },
{ name: 'status', type: 'string' },
{ name: 'about', type: 'string' },
{ name: 'address', type: 'string' },
{ name: 'company', type: 'string' },
{ name: 'name', type: 'string' },
{ name: 'style', type: 'string' },
{ name: 'calendar', type: 'string' },
{ name: 'start', type: 'date', format: 'yyyy-MM-dd HH:mm' },
{ name: 'end', type: 'date', format: 'yyyy-MM-dd HH:mm' }
],
id: 'id',
url: '../sampledata/appointments.txt'
};
let adapter = new $.jqx.dataAdapter(source);
let appointmentDataFields =
{
from: 'start',
to: 'end',
id: 'id',
description: 'about',
location: 'address',
subject: 'name',
style: 'style',
status: 'status'
};
let views =
[
{ type: 'dayView', showWeekends: true, timeRuler: { scale: 'quarterHour' } },
{ type: 'weekView', showWeekends: true, timeRuler: { scale: 'quarterHour' } }
];
return (
<JqxScheduler ref='myScheduler'
width={850} height={600} source={adapter}
date={new $.jqx.date(2016, 11, 23)} showLegend={true}
view={'weekView'} views={views}
appointmentDataFields={appointmentDataFields}
/>
)
}
}
ReactDOM.render(<App />, document.getElementById('app'));
|
/**
* Highcharts Drilldown module
*
* Author: Torstein Honsi
* License: www.highcharts.com/license
*
*/
(function (factory) {
if (typeof module === 'object' && module.exports) {
module.exports = factory;
} else {
factory(Highcharts);
}
}(function (H) {
'use strict';
var noop = function () {},
defaultOptions = H.getOptions(),
each = H.each,
extend = H.extend,
format = H.format,
pick = H.pick,
wrap = H.wrap,
Chart = H.Chart,
seriesTypes = H.seriesTypes,
PieSeries = seriesTypes.pie,
ColumnSeries = seriesTypes.column,
Tick = H.Tick,
fireEvent = H.fireEvent,
inArray = H.inArray,
ddSeriesId = 1;
// Utilities
/*
* Return an intermediate color between two colors, according to pos where 0
* is the from color and 1 is the to color. This method is copied from ColorAxis.js
* and should always be kept updated, until we get AMD support.
*/
function tweenColors(from, to, pos) {
// Check for has alpha, because rgba colors perform worse due to lack of
// support in WebKit.
var hasAlpha,
ret;
// Unsupported color, return to-color (#3920)
if (!to.rgba.length || !from.rgba.length) {
ret = to.input || 'none';
// Interpolate
} else {
from = from.rgba;
to = to.rgba;
hasAlpha = (to[3] !== 1 || from[3] !== 1);
ret = (hasAlpha ? 'rgba(' : 'rgb(') +
Math.round(to[0] + (from[0] - to[0]) * (1 - pos)) + ',' +
Math.round(to[1] + (from[1] - to[1]) * (1 - pos)) + ',' +
Math.round(to[2] + (from[2] - to[2]) * (1 - pos)) +
(hasAlpha ? (',' + (to[3] + (from[3] - to[3]) * (1 - pos))) : '') + ')';
}
return ret;
}
/**
* Handle animation of the color attributes directly
*/
each(['fill', 'stroke'], function (prop) {
H.Fx.prototype[prop + 'Setter'] = function () {
this.elem.attr(prop, tweenColors(H.Color(this.start), H.Color(this.end), this.pos));
};
});
// Add language
extend(defaultOptions.lang, {
drillUpText: '◁ Back to {series.name}'
});
defaultOptions.drilldown = {
activeAxisLabelStyle: {
cursor: 'pointer',
color: '#0d233a',
fontWeight: 'bold',
textDecoration: 'underline'
},
activeDataLabelStyle: {
cursor: 'pointer',
color: '#0d233a',
fontWeight: 'bold',
textDecoration: 'underline'
},
animation: {
duration: 500
},
drillUpButton: {
position: {
align: 'right',
x: -10,
y: 10
}
// relativeTo: 'plotBox'
// theme
}
};
/**
* A general fadeIn method
*/
H.SVGRenderer.prototype.Element.prototype.fadeIn = function (animation) {
this
.attr({
opacity: 0.1,
visibility: 'inherit'
})
.animate({
opacity: pick(this.newOpacity, 1) // newOpacity used in maps
}, animation || {
duration: 250
});
};
Chart.prototype.addSeriesAsDrilldown = function (point, ddOptions) {
this.addSingleSeriesAsDrilldown(point, ddOptions);
this.applyDrilldown();
};
Chart.prototype.addSingleSeriesAsDrilldown = function (point, ddOptions) {
var oldSeries = point.series,
xAxis = oldSeries.xAxis,
yAxis = oldSeries.yAxis,
newSeries,
color = point.color || oldSeries.color,
pointIndex,
levelSeries = [],
levelSeriesOptions = [],
level,
levelNumber,
last;
if (!this.drilldownLevels) {
this.drilldownLevels = [];
}
levelNumber = oldSeries.options._levelNumber || 0;
// See if we can reuse the registered series from last run
last = this.drilldownLevels[this.drilldownLevels.length - 1];
if (last && last.levelNumber !== levelNumber) {
last = undefined;
}
ddOptions = extend({
color: color,
_ddSeriesId: ddSeriesId++
}, ddOptions);
pointIndex = inArray(point, oldSeries.points);
// Record options for all current series
each(oldSeries.chart.series, function (series) {
if (series.xAxis === xAxis && !series.isDrilling) {
series.options._ddSeriesId = series.options._ddSeriesId || ddSeriesId++;
series.options._colorIndex = series.userOptions._colorIndex;
series.options._levelNumber = series.options._levelNumber || levelNumber; // #3182
if (last) {
levelSeries = last.levelSeries;
levelSeriesOptions = last.levelSeriesOptions;
} else {
levelSeries.push(series);
levelSeriesOptions.push(series.options);
}
}
});
// Add a record of properties for each drilldown level
level = {
levelNumber: levelNumber,
seriesOptions: oldSeries.options,
levelSeriesOptions: levelSeriesOptions,
levelSeries: levelSeries,
shapeArgs: point.shapeArgs,
bBox: point.graphic ? point.graphic.getBBox() : {}, // no graphic in line series with markers disabled
color: color,
lowerSeriesOptions: ddOptions,
pointOptions: oldSeries.options.data[pointIndex],
pointIndex: pointIndex,
oldExtremes: {
xMin: xAxis && xAxis.userMin,
xMax: xAxis && xAxis.userMax,
yMin: yAxis && yAxis.userMin,
yMax: yAxis && yAxis.userMax
}
};
// Push it to the lookup array
this.drilldownLevels.push(level);
newSeries = level.lowerSeries = this.addSeries(ddOptions, false);
newSeries.options._levelNumber = levelNumber + 1;
if (xAxis) {
xAxis.oldPos = xAxis.pos;
xAxis.userMin = xAxis.userMax = null;
yAxis.userMin = yAxis.userMax = null;
}
// Run fancy cross-animation on supported and equal types
if (oldSeries.type === newSeries.type) {
newSeries.animate = newSeries.animateDrilldown || noop;
newSeries.options.animation = true;
}
};
Chart.prototype.applyDrilldown = function () {
var drilldownLevels = this.drilldownLevels,
levelToRemove;
if (drilldownLevels && drilldownLevels.length > 0) { // #3352, async loading
levelToRemove = drilldownLevels[drilldownLevels.length - 1].levelNumber;
each(this.drilldownLevels, function (level) {
if (level.levelNumber === levelToRemove) {
each(level.levelSeries, function (series) {
if (series.options && series.options._levelNumber === levelToRemove) { // Not removed, not added as part of a multi-series drilldown
series.remove(false);
}
});
}
});
}
this.redraw();
this.showDrillUpButton();
};
Chart.prototype.getDrilldownBackText = function () {
var drilldownLevels = this.drilldownLevels,
lastLevel;
if (drilldownLevels && drilldownLevels.length > 0) { // #3352, async loading
lastLevel = drilldownLevels[drilldownLevels.length - 1];
lastLevel.series = lastLevel.seriesOptions;
return format(this.options.lang.drillUpText, lastLevel);
}
};
Chart.prototype.showDrillUpButton = function () {
var chart = this,
backText = this.getDrilldownBackText(),
buttonOptions = chart.options.drilldown.drillUpButton,
attr,
states;
if (!this.drillUpButton) {
attr = buttonOptions.theme;
states = attr && attr.states;
this.drillUpButton = this.renderer.button(
backText,
null,
null,
function () {
chart.drillUp();
},
attr,
states && states.hover,
states && states.select
)
.attr({
align: buttonOptions.position.align,
zIndex: 9
})
.add()
.align(buttonOptions.position, false, buttonOptions.relativeTo || 'plotBox');
} else {
this.drillUpButton.attr({
text: backText
})
.align();
}
};
Chart.prototype.drillUp = function () {
var chart = this,
drilldownLevels = chart.drilldownLevels,
levelNumber = drilldownLevels[drilldownLevels.length - 1].levelNumber,
i = drilldownLevels.length,
chartSeries = chart.series,
seriesI,
level,
oldSeries,
newSeries,
oldExtremes,
addSeries = function (seriesOptions) {
var addedSeries;
each(chartSeries, function (series) {
if (series.options._ddSeriesId === seriesOptions._ddSeriesId) {
addedSeries = series;
}
});
addedSeries = addedSeries || chart.addSeries(seriesOptions, false);
if (addedSeries.type === oldSeries.type && addedSeries.animateDrillupTo) {
addedSeries.animate = addedSeries.animateDrillupTo;
}
if (seriesOptions === level.seriesOptions) {
newSeries = addedSeries;
}
};
while (i--) {
level = drilldownLevels[i];
if (level.levelNumber === levelNumber) {
drilldownLevels.pop();
// Get the lower series by reference or id
oldSeries = level.lowerSeries;
if (!oldSeries.chart) { // #2786
seriesI = chartSeries.length; // #2919
while (seriesI--) {
if (chartSeries[seriesI].options.id === level.lowerSeriesOptions.id &&
chartSeries[seriesI].options._levelNumber === levelNumber + 1) { // #3867
oldSeries = chartSeries[seriesI];
break;
}
}
}
oldSeries.xData = []; // Overcome problems with minRange (#2898)
each(level.levelSeriesOptions, addSeries);
fireEvent(chart, 'drillup', { seriesOptions: level.seriesOptions });
if (newSeries.type === oldSeries.type) {
newSeries.drilldownLevel = level;
newSeries.options.animation = chart.options.drilldown.animation;
if (oldSeries.animateDrillupFrom && oldSeries.chart) { // #2919
oldSeries.animateDrillupFrom(level);
}
}
newSeries.options._levelNumber = levelNumber;
oldSeries.remove(false);
// Reset the zoom level of the upper series
if (newSeries.xAxis) {
oldExtremes = level.oldExtremes;
newSeries.xAxis.setExtremes(oldExtremes.xMin, oldExtremes.xMax, false);
newSeries.yAxis.setExtremes(oldExtremes.yMin, oldExtremes.yMax, false);
}
}
}
this.redraw();
if (this.drilldownLevels.length === 0) {
this.drillUpButton = this.drillUpButton.destroy();
} else {
this.drillUpButton.attr({
text: this.getDrilldownBackText()
})
.align();
}
this.ddDupes.length = []; // #3315
};
ColumnSeries.prototype.supportsDrilldown = true;
/**
* When drilling up, keep the upper series invisible until the lower series has
* moved into place
*/
ColumnSeries.prototype.animateDrillupTo = function (init) {
if (!init) {
var newSeries = this,
level = newSeries.drilldownLevel;
each(this.points, function (point) {
if (point.graphic) { // #3407
point.graphic.hide();
}
if (point.dataLabel) {
point.dataLabel.hide();
}
if (point.connector) {
point.connector.hide();
}
});
// Do dummy animation on first point to get to complete
setTimeout(function () {
if (newSeries.points) { // May be destroyed in the meantime, #3389
each(newSeries.points, function (point, i) {
// Fade in other points
var verb = i === (level && level.pointIndex) ? 'show' : 'fadeIn',
inherit = verb === 'show' ? true : undefined;
if (point.graphic) { // #3407
point.graphic[verb](inherit);
}
if (point.dataLabel) {
point.dataLabel[verb](inherit);
}
if (point.connector) {
point.connector[verb](inherit);
}
});
}
}, Math.max(this.chart.options.drilldown.animation.duration - 50, 0));
// Reset
this.animate = noop;
}
};
ColumnSeries.prototype.animateDrilldown = function (init) {
var series = this,
drilldownLevels = this.chart.drilldownLevels,
animateFrom,
animationOptions = this.chart.options.drilldown.animation,
xAxis = this.xAxis;
if (!init) {
each(drilldownLevels, function (level) {
if (series.options._ddSeriesId === level.lowerSeriesOptions._ddSeriesId) {
animateFrom = level.shapeArgs;
animateFrom.fill = level.color;
}
});
animateFrom.x += (pick(xAxis.oldPos, xAxis.pos) - xAxis.pos);
each(this.points, function (point) {
if (point.graphic) {
point.graphic
.attr(animateFrom)
.animate(
extend(point.shapeArgs, { fill: point.color }),
animationOptions
);
}
if (point.dataLabel) {
point.dataLabel.fadeIn(animationOptions);
}
});
this.animate = null;
}
};
/**
* When drilling up, pull out the individual point graphics from the lower series
* and animate them into the origin point in the upper series.
*/
ColumnSeries.prototype.animateDrillupFrom = function (level) {
var animationOptions = this.chart.options.drilldown.animation,
group = this.group,
series = this;
// Cancel mouse events on the series group (#2787)
each(series.trackerGroups, function (key) {
if (series[key]) { // we don't always have dataLabelsGroup
series[key].on('mouseover');
}
});
delete this.group;
each(this.points, function (point) {
var graphic = point.graphic,
complete = function () {
graphic.destroy();
if (group) {
group = group.destroy();
}
};
if (graphic) {
delete point.graphic;
if (animationOptions) {
graphic.animate(
extend(level.shapeArgs, { fill: level.color }),
H.merge(animationOptions, { complete: complete })
);
} else {
graphic.attr(level.shapeArgs);
complete();
}
}
});
};
if (PieSeries) {
extend(PieSeries.prototype, {
supportsDrilldown: true,
animateDrillupTo: ColumnSeries.prototype.animateDrillupTo,
animateDrillupFrom: ColumnSeries.prototype.animateDrillupFrom,
animateDrilldown: function (init) {
var level = this.chart.drilldownLevels[this.chart.drilldownLevels.length - 1],
animationOptions = this.chart.options.drilldown.animation,
animateFrom = level.shapeArgs,
start = animateFrom.start,
angle = animateFrom.end - start,
startAngle = angle / this.points.length;
if (!init) {
each(this.points, function (point, i) {
point.graphic
.attr(H.merge(animateFrom, {
start: start + i * startAngle,
end: start + (i + 1) * startAngle,
fill: level.color
}))[animationOptions ? 'animate' : 'attr'](
extend(point.shapeArgs, { fill: point.color }),
animationOptions
);
});
this.animate = null;
}
}
});
}
H.Point.prototype.doDrilldown = function (_holdRedraw, category) {
var series = this.series,
chart = series.chart,
drilldown = chart.options.drilldown,
i = (drilldown.series || []).length,
seriesOptions;
if (!chart.ddDupes) {
chart.ddDupes = [];
}
while (i-- && !seriesOptions) {
if (drilldown.series[i].id === this.drilldown && inArray(this.drilldown, chart.ddDupes) === -1) {
seriesOptions = drilldown.series[i];
chart.ddDupes.push(this.drilldown);
}
}
// Fire the event. If seriesOptions is undefined, the implementer can check for
// seriesOptions, and call addSeriesAsDrilldown async if necessary.
fireEvent(chart, 'drilldown', {
point: this,
seriesOptions: seriesOptions,
category: category,
points: category !== undefined && this.series.xAxis.ddPoints[category].slice(0)
});
if (seriesOptions) {
if (_holdRedraw) {
chart.addSingleSeriesAsDrilldown(this, seriesOptions);
} else {
chart.addSeriesAsDrilldown(this, seriesOptions);
}
}
};
/**
* Drill down to a given category. This is the same as clicking on an axis label.
*/
H.Axis.prototype.drilldownCategory = function (x) {
var key,
point,
ddPointsX = this.ddPoints[x];
for (key in ddPointsX) {
point = ddPointsX[key];
if (point && point.series && point.series.visible && point.doDrilldown) { // #3197
point.doDrilldown(true, x);
}
}
this.chart.applyDrilldown();
};
/**
* Create and return a collection of points associated with the X position. Reset it for each level.
*/
H.Axis.prototype.getDDPoints = function (x, levelNumber) {
var ddPoints = this.ddPoints;
if (!ddPoints) {
this.ddPoints = ddPoints = {};
}
if (!ddPoints[x]) {
ddPoints[x] = [];
}
if (ddPoints[x].levelNumber !== levelNumber) {
ddPoints[x].length = 0; // reset
}
return ddPoints[x];
};
/**
* Make a tick label drillable, or remove drilling on update
*/
Tick.prototype.drillable = function () {
var pos = this.pos,
label = this.label,
axis = this.axis,
ddPointsX = axis.ddPoints && axis.ddPoints[pos];
if (label && ddPointsX && ddPointsX.length) {
if (!label.basicStyles) {
label.basicStyles = H.merge(label.styles);
}
label
.addClass('highcharts-drilldown-axis-label')
.css(axis.chart.options.drilldown.activeAxisLabelStyle)
.on('click', function () {
axis.drilldownCategory(pos);
});
} else if (label && label.basicStyles) {
label.styles = {}; // reset for full overwrite of styles
label.css(label.basicStyles);
label.on('click', null); // #3806
}
};
/**
* Always keep the drillability updated (#3951)
*/
wrap(Tick.prototype, 'addLabel', function (proceed) {
proceed.call(this);
this.drillable();
});
/**
* On initialization of each point, identify its label and make it clickable. Also, provide a
* list of points associated to that label.
*/
wrap(H.Point.prototype, 'init', function (proceed, series, options, x) {
var point = proceed.call(this, series, options, x),
xAxis = series.xAxis,
tick = xAxis && xAxis.ticks[x],
ddPointsX = xAxis && xAxis.getDDPoints(x, series.options._levelNumber);
if (point.drilldown) {
// Add the click event to the point
H.addEvent(point, 'click', function () {
if (series.xAxis && series.chart.options.drilldown.allowPointDrilldown === false) {
series.xAxis.drilldownCategory(x);
} else {
point.doDrilldown();
}
});
/*wrap(point, 'importEvents', function (proceed) { // wrapping importEvents makes point.click event work
if (!this.hasImportedEvents) {
proceed.call(this);
H.addEvent(this, 'click', function () {
this.doDrilldown();
});
}
});*/
// Register drilldown points on this X value
if (ddPointsX) {
ddPointsX.push(point);
ddPointsX.levelNumber = series.options._levelNumber;
}
}
// Add or remove click handler and style on the tick label
if (tick) {
tick.drillable();
}
return point;
});
wrap(H.Series.prototype, 'drawDataLabels', function (proceed) {
var css = this.chart.options.drilldown.activeDataLabelStyle;
proceed.call(this);
each(this.points, function (point) {
if (point.drilldown && point.dataLabel) {
point.dataLabel
.attr({
'class': 'highcharts-drilldown-data-label'
})
.css(css);
}
});
});
// Mark the trackers with a pointer
var type,
drawTrackerWrapper = function (proceed) {
proceed.call(this);
each(this.points, function (point) {
if (point.drilldown && point.graphic) {
point.graphic
.attr({
'class': 'highcharts-drilldown-point'
})
.css({ cursor: 'pointer' });
}
});
};
for (type in seriesTypes) {
if (seriesTypes[type].prototype.supportsDrilldown) {
wrap(seriesTypes[type].prototype, 'drawTracker', drawTrackerWrapper);
}
}
}));
|
var showTriggers = new Array();
function registerShow(sectId,showFunc) {
showTriggers[sectId] = showFunc;
}
function hasClass(ele,cls) {
return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
}
function addClass(ele,cls) {
if (!this.hasClass(ele,cls)) ele.className += " "+cls;
}
function removeClass(ele,cls) {
if (hasClass(ele,cls)) {
var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
ele.className=ele.className.replace(reg,' ');
}
}
function toggleVisibility(linkObj) {
var base = linkObj.getAttribute('id');
var summary = document.getElementById(base + '-summary');
var content = document.getElementById(base + '-content');
var trigger = document.getElementById(base + '-trigger');
if ( hasClass(linkObj,'closed') ) {
summary.style.display = 'none';
content.style.display = 'block';
trigger.src = trigger.src.substring(0,trigger.src.length-10)+'open.png';
removeClass(linkObj,'closed');
addClass(linkObj,'opened');
if (showTriggers[base]) { showTriggers[base](); }
} else if ( hasClass(linkObj,'opened') ) {
summary.style.display = 'block';
content.style.display = 'none';
trigger.src = trigger.src.substring(0,trigger.src.length-8)+'closed.png';
removeClass(linkObj,'opened');
addClass(linkObj,'closed');
}
return false;
}
|
import * as React from 'react'
import SingleImage from '../../components/SingleImage'
import { images } from '../../constants'
const Page = ({ index }) => {
return <SingleImage index={index} />
}
export async function getStaticProps({ params }) {
const number = Number.parseInt(params.index, 10)
return {
props: {
index: number,
},
}
}
export async function getStaticPaths() {
return {
paths: images.map((_id, index) => {
return {
params: {
index: `${index}`,
},
}
}),
fallback: false,
}
}
export default Page
|
'use strict';
/**
* @ngdoc service
* @name ss.log:log
* @function
*
* @description
* Contains method stubs for logging to console (by default) or
* whatever logging provider you choose.
*/
/**
* @ngdoc function
* @name ss.log#trace
* @methodOf ss.log:log
* @function
* @description
* Trace function calls in socketstream and plugins. By default nothing is done.
* If you want to switch on tracing override the `trace` method.
* ```
* var ss = require('socketstream');
* ss.api.log.trace = function() {
* console.log.apply(console,arguments);
* };
* ```
*/
exports.trace = function() {
};
/**
* @ngdoc function
* @name ss.log#debug
* @methodOf ss.log:log
* @function
*
* @description
* Debug level logging, uses console.log by default. Override by assigning a
* function that takes the same parameters as console.log:
* ```
* var ss = require('socketstream');
* ss.api.log.debug = console.log;
* ```
*
* @example
* ```
* ss.log.debug("Something fairly trivial happened");
* ```
*/
exports.debug = console.log;
/**
* @ngdoc service
* @name ss.log#info
* @methodOf ss.log:log
* @function
*
* @description
* Info level logging, uses console.log by default. Override by assigning a
* function that takes the same parameters as console.log.
*
* @example
* ```
* ss.log.info("Just keeping you informed");
* ```
*/
exports.info = console.log;
/**
* @ngdoc function
* @name ss.log#warn
* @methodOf ss.log:log
* @function
*
* @description
* Warn level logging, uses console.log by default. Override by assigning a
* function that takes the same parameters as console.log:
* ```
* var ss = require('socketstream'),
* winston = require('winston');
* ss.log.warn = winston.warn;
* ```
*
* @example
* ```
* ss.log.warn("Something unexpected happened!");
* ```
*/
exports.warn = console.log;
/**
* @ngdoc function
* @name ss.log#error
* @methodOf ss.log:log
* @function
*
* @description
* Error level logging, uses console.error by default. Override by assigning a
* function that takes the same parameters as console.error.
*
* @example
* ```
* ss.log.error("Time to wakeup the sysadmin");
* ```
*/
exports.error = console.error;
var nextClientIssue = (new Date()).getTime();
exports.clientIssue = function clientIssue(client,options,err,more) {
var info = [''];
if (options.serveDebugInfo) {
err.userInfo = info;
}
info.push(err.message);
info.push('client='+client.id);
if (err.stack) {
info = info.concat(err.stack.split('\n').splice(1));
}
if (more) {
info.push('more:');
info.push(JSON.stringify(more));
}
var number = nextClientIssue++;
Object.defineProperty(err, 'userInfoHTML', {
get: function() {
return this.userInfo? this.userInfo.join('<br>') : ' issue='+number;
}
});
Object.defineProperty(err, 'userInfoText', {
get: function() {
return this.userInfo? this.userInfo.join('\n') : ' issue='+number;
}
});
this.error(('Couldn\'t serve client '+client.name+',').red, 'issue='+number, info.join('\n'));
return number;
};
|
/*!
* Module dependencies.
*/
var _ = require('underscore'),
moment = require('moment'),
keystone = require('../../../'),
util = require('util'),
knox = require('knox'),
// s3 = require('s3'),
utils = require('keystone-utils'),
grappling = require('grappling-hook'),
super_ = require('../Type');
/**
* S3File FieldType Constructor
* @extends Field
* @api public
*/
function s3file(list, path, options) {
grappling.mixin(this)
.allowHooks('pre:upload');
this._underscoreMethods = ['format', 'uploadFile'];
this._fixedSize = 'full';
// TODO: implement filtering, usage disabled for now
options.nofilter = true;
// TODO: implement initial form, usage disabled for now
if (options.initial) {
throw new Error('Invalid Configuration\n\n' +
'S3File fields (' + list.key + '.' + path + ') do not currently support being used as initial fields.\n');
}
s3file.super_.call(this, list, path, options);
// validate s3 config (has to happen after super_.call)
if (!this.s3config) {
throw new Error('Invalid Configuration\n\n' +
'S3File fields (' + list.key + '.' + path + ') require the "s3 config" option to be set.\n\n' +
'See http://keystonejs.com/docs/configuration/#services-amazons3 for more information.\n');
}
// Could be more pre- hooks, just upload for now
if (options.pre && options.pre.upload) {
this.pre('upload', options.pre.upload);
}
}
/*!
* Inherit from Field
*/
util.inherits(s3file, super_);
/**
* Exposes the custom or keystone s3 config settings
*/
Object.defineProperty(s3file.prototype, 's3config', {
get: function() {
return this.options.s3config || keystone.get('s3 config');
}
});
/**
* Registers the field on the List's Mongoose Schema.
*
* @api public
*/
s3file.prototype.addToSchema = function() {
var field = this,
schema = this.list.schema;
var paths = this.paths = {
// fields
filename: this._path.append('.filename'),
originalname: this._path.append('.originalname'),
path: this._path.append('.path'),
size: this._path.append('.size'),
filetype: this._path.append('.filetype'),
url: this._path.append('.url'),
// virtuals
exists: this._path.append('.exists'),
upload: this._path.append('_upload'),
action: this._path.append('_action')
};
var schemaPaths = this._path.addTo({}, {
filename: String,
originalname: String,
path: String,
size: Number,
filetype: String,
url: String
});
schema.add(schemaPaths);
var exists = function(item) {
return (item.get(paths.url) ? true : false);
};
// The .exists virtual indicates whether a file is stored
schema.virtual(paths.exists).get(function() {
return schemaMethods.exists.apply(this);
});
var reset = function(item) {
item.set(field.path, {
filename: '',
originalname: '',
path: '',
size: 0,
filetype: '',
url: ''
});
};
var schemaMethods = {
exists: function() {
return exists(this);
},
/**
* Resets the value of the field
*
* @api public
*/
reset: function() {
reset(this);
},
/**
* Deletes the file from S3File and resets the field
*
* @api public
*/
delete: function() {
try {
var client = knox.createClient(field.s3config);
client.deleteFile(this.get(paths.path) + this.get(paths.filename), function(err, res){ return res ? res.resume() : false; });//eslint-disable-line handle-callback-err
} catch(e) {}// eslint-disable-line no-empty
reset(this);
}
};
_.each(schemaMethods, function(fn, key) {
field.underscoreMethod(key, fn);
});
// expose a method on the field to call schema methods
this.apply = function(item, method) {
return schemaMethods[method].apply(item, Array.prototype.slice.call(arguments, 2));
};
this.bindUnderscoreMethods();
};
/**
* Formats the field value
*
* @api public
*/
s3file.prototype.format = function(item) {
if (this.hasFormatter()) {
return this.options.format(item, item[this.path]);
}
return item.get(this.paths.url);
};
/**
* Detects the field have formatter function
*
* @api public
*/
s3file.prototype.hasFormatter = function() {
return 'function' === typeof this.options.format;
};
/**
* Detects whether the field has been modified
*
* @api public
*/
s3file.prototype.isModified = function(item) {
return item.isModified(this.paths.url);
};
/**
* Validates that a value for this field has been provided in a data object
*
* @api public
*/
s3file.prototype.validateInput = function(data) {//eslint-disable-line no-unused-vars
// TODO - how should file field input be validated?
return true;
};
/**
* Updates the value for this field in the item from a data object
*
* @api public
*/
// s3file.prototype.updateItem = function(item, data) {//eslint-disable-line no-unused-vars
// TODO - direct updating of data (not via upload)
// commented out for now so super's updateItem will be called and S3FileType can be seeded with an application update
// };
/**
* Validates a header option value provided for this item, throwing an error otherwise
* @param header {Object} the header object to validate
* @param callback {Function} a callback function to call when validation is complete
* @return {Boolean}
* @api private
*/
var validateHeader = function(header, callback) {
var HEADER_NAME_KEY = 'name',
HEADER_VALUE_KEY = 'value',
validKeys = [HEADER_NAME_KEY, HEADER_VALUE_KEY],
filteredKeys;
if (!_.has(header, HEADER_NAME_KEY)){
return callback(new Error('Unsupported Header option: missing required key "' + HEADER_NAME_KEY + '" in ' + JSON.stringify(header)));
}
if (!_.has(header, HEADER_VALUE_KEY)){
return callback(new Error('Unsupported Header option: missing required key "' + HEADER_VALUE_KEY + '" in ' + JSON.stringify(header)));
}
filteredKeys = _.filter(_.keys(header), function (key){ return _.indexOf(validKeys, key) > -1; });
_.each(filteredKeys, function (key){
if (!_.isString(header[key])){
return callback(new Error('Unsupported Header option: value for ' + key + ' header must be a String ' + header[key].toString()));
}
});
return true;
};
/**
* Convenience method to validate a headers object
* @param headers {Object} the headers object to validate
* @param callback {Function} a callback function to call when validation is complete
* @return {Boolean}
* @api private
*/
var validateHeaders = function(headers, callback) {
var _headers = [];
if (!_.isObject(headers)){
return callback(new Error('Unsupported Header option: headers must be an Object ' + JSON.stringify(headers)));
}
_.each(headers, function (value, key){
_headers.push({ name: key, value: value });
});
_.each(_headers, function (header){
validateHeader(header, callback);
});
return true;
};
/**
* Generates a headers object for this item to use during upload
* @param item {Object} the list item
* @param file {Object} the uploaded file
* @param callback {Function} a callback function to call when validation is complete
* @return {Object}
* @api public
*/
s3file.prototype.generateHeaders = function (item, file, callback){
var field = this,
filetype = file.mimetype || file.type,
headers = {
'Content-Type': filetype,
'x-amz-acl': 'public-read'
},
customHeaders = {},
headersOption = {},
computedHeaders,
defaultHeaders;
if (_.has(field.s3config, 'default headers')){
defaultHeaders = field.s3config['default headers'];
if (_.isArray(defaultHeaders)){
_.each(defaultHeaders, function (header){
var _header = {};
if (validateHeader(header, callback)){
_header[header.name] = header.value;
customHeaders = _.extend(customHeaders, _header);
}
});
} else if (_.isObject(defaultHeaders)){
customHeaders = _.extend(customHeaders, defaultHeaders);
} else {
return callback(new Error('Unsupported Header option: defaults headers must be either an Object or Array ' + JSON.stringify(defaultHeaders)));
}
}
if (field.options.headers){
headersOption = field.options.headers;
if (_.isFunction(headersOption)){
computedHeaders = headersOption.call(field, item, file);
if (_.isArray(computedHeaders)){
_.each(computedHeaders, function (header){
var _header = {};
if (validateHeader(header, callback)){
_header[header.name] = header.value;
customHeaders = _.extend(customHeaders, _header);
}
});
} else if (_.isObject(computedHeaders)){
customHeaders = _.extend(customHeaders, computedHeaders);
} else {
return callback(new Error('Unsupported Header option: computed headers must be either an Object or Array ' + JSON.stringify(computedHeaders)));
}
} else if (_.isArray(headersOption)){
_.each(headersOption, function (header){
var _header = {};
if (validateHeader(header, callback)){
_header[header.name] = header.value;
customHeaders = _.extend(customHeaders, _header);
}
});
} else if (_.isObject(headersOption)){
customHeaders = _.extend(customHeaders, headersOption);
}
}
if (validateHeaders(customHeaders, callback)){
headers = _.extend(headers, customHeaders);
}
return headers;
};
/**
* Uploads the file for this field
*
* @api public
*/
s3file.prototype.uploadFile = function(item, file, update, callback) {
var field = this,
path = field.options.s3path ? field.options.s3path + '/' : '',
prefix = field.options.datePrefix ? moment().format(field.options.datePrefix) + '-' : '',
filename = prefix + file.name,
originalname = file.originalname,
filetype = file.mimetype || file.type,
headers;
if ('function' === typeof update) {
callback = update;
update = false;
}
if (field.options.allowedTypes && !_.contains(field.options.allowedTypes, filetype)) {
return callback(new Error('Unsupported File Type: ' + filetype));
}
var doUpload = function() {
if ('function' === typeof field.options.path) {
path = field.options.path(item, path);
}
if ('function' === typeof field.options.filename) {
filename = field.options.filename(item, filename, originalname);
}
headers = field.generateHeaders(item, file, callback);
knox.createClient(field.s3config).putFile(file.path, path + filename, headers, function(err, res) {
if (err) return callback(err);
if (res) {
if (res.statusCode !== 200) {
return callback(new Error('Amazon returned Http Code: ' + res.statusCode));
} else {
res.resume();
}
}
var protocol = (field.s3config.protocol && field.s3config.protocol + ':') || '',
url = res.req.url.replace(/^https?:/i, protocol);
var fileData = {
filename: filename,
originalname: originalname,
path: path,
size: file.size,
filetype: filetype,
url: url
};
if (update) {
item.set(field.path, fileData);
}
callback(null, fileData);
});
};
this.callHook('pre:upload', item, file, function(err) {
if (err) return callback(err);
doUpload();
});
};
/**
* Returns a callback that handles a standard form submission for the field
*
* Expected form parts are
* - `field.paths.action` in `req.body` (`clear` or `delete`)
* - `field.paths.upload` in `req.files` (uploads the file to s3file)
*
* @api public
*/
s3file.prototype.getRequestHandler = function(item, req, paths, callback) {
var field = this;
if (utils.isFunction(paths)) {
callback = paths;
paths = field.paths;
} else if (!paths) {
paths = field.paths;
}
callback = callback || function() {};
return function() {
if (req.body) {
var action = req.body[paths.action];
if (/^(delete|reset)$/.test(action)) {
field.apply(item, action);
}
}
if (req.files && req.files[paths.upload] && req.files[paths.upload].size) {
return field.uploadFile(item, req.files[paths.upload], true, callback);
}
return callback();
};
};
/**
* Immediately handles a standard form submission for the field (see `getRequestHandler()`)
*
* @api public
*/
s3file.prototype.handleRequest = function(item, req, paths, callback) {
this.getRequestHandler(item, req, paths, callback)();
};
/*!
* Export class
*/
exports = module.exports = s3file;
|
var Checker = require('../../lib/checker');
var assert = require('assert');
describe('rules/require-dot-notation', function() {
var checker;
beforeEach(function() {
checker = new Checker();
checker.registerDefaultRules();
checker.configure({ requireDotNotation: true });
});
it('should report literal subscription', function() {
assert(checker.checkString('var x = a[\'b\']').getErrorCount() === 1);
});
it('should not report literal subscription for reserved words', function() {
assert(checker.checkString('var x = a[\'while\']').isEmpty());
assert(checker.checkString('var x = a[null]').isEmpty());
assert(checker.checkString('var x = a[true]').isEmpty());
assert(checker.checkString('var x = a[false]').isEmpty());
assert(checker.checkString('var x = a["null"]').isEmpty());
assert(checker.checkString('var x = a["true"]').isEmpty());
assert(checker.checkString('var x = a["false"]').isEmpty());
});
it('should not report number subscription', function() {
assert(checker.checkString('var x = a[1]').isEmpty());
});
it('should not report variable subscription', function() {
assert(checker.checkString('var x = a[c]').isEmpty());
});
it('should not report object property subscription', function() {
assert(checker.checkString('var x = a[b.c]').isEmpty());
});
it('should not report dot notation', function() {
assert(checker.checkString('var x = a.b').isEmpty());
});
it('should not report for string that can\'t be identifier', function() {
assert(checker.checkString('x["a-b"]').isEmpty());
assert(checker.checkString('x["a.b"]').isEmpty());
assert(checker.checkString('x["a b"]').isEmpty());
assert(checker.checkString('x["1a"]').isEmpty());
assert(checker.checkString('x["*"]').isEmpty());
});
});
|
/**
* Copyright (c) 2008-2011 The Open Planning Project
*
* Published under the BSD license.
* See https://github.com/opengeo/gxp/raw/master/license.txt for the full text
* of the license.
*/
/**
* @requires plugins/Tool.js
* @requires widgets/form/GoogleGeocoderComboBox.js
*/
/** api: (define)
* module = gxp.plugins
* class = GoogleGeocoder
*/
/** api: (extends)
* plugins/Tool.js
*/
Ext.namespace("gxp.plugins");
/** api: constructor
* .. class:: GoogleGeocoder(config)
*
* Plugin for adding a GoogleGeocoderComboBox to a viewer. The underlying
* GoogleGeocoderComboBox can be configured by setting this tool's
* ``outputConfig`` property.
*/
gxp.plugins.GoogleGeocoder = Ext.extend(gxp.plugins.Tool, {
/** api: ptype = gxp_googlegeocoder */
ptype: "gxp_googlegeocoder",
/** api: config[updateField]
* ``String``
* If value is specified, when an item is selected in the combo, the map
* will be zoomed to the corresponding field value in the selected record.
* If ``null``, no map navigation will occur. Valid values are the field
* names described for the :class:`gxp.form.GoogleGeocoderComboBox`.
* Default is "viewport".
*/
updateField: "viewport",
init: function(target) {
var combo = new gxp.form.GoogleGeocoderComboBox(Ext.apply({
listeners: {
select: this.onComboSelect,
scope: this
}
}, this.outputConfig));
var bounds = target.mapPanel.map.restrictedExtent;
if (bounds && !combo.bounds) {
target.on({
ready: function() {
combo.bounds = bounds.clone().transform(
target.mapPanel.map.getProjectionObject(),
new OpenLayers.Projection("EPSG:4326")
);
}
});
}
this.combo = combo;
return gxp.plugins.GoogleGeocoder.superclass.init.apply(this, arguments);
},
/** api: method[addOutput]
*/
addOutput: function(config) {
return gxp.plugins.GoogleGeocoder.superclass.addOutput.call(this, this.combo);
},
/** private: method[onComboSelect]
* Listener for combo's select event.
*/
onComboSelect: function(combo, record) {
if (this.updateField) {
var map = this.target.mapPanel.map;
var location = record.get(this.updateField).clone().transform(
new OpenLayers.Projection("EPSG:4326"),
map.getProjectionObject()
);
if (location instanceof OpenLayers.Bounds) {
map.zoomToExtent(location, true);
} else {
map.setCenter(location);
}
}
}
});
Ext.preg(gxp.plugins.GoogleGeocoder.prototype.ptype, gxp.plugins.GoogleGeocoder);
|
version https://git-lfs.github.com/spec/v1
oid sha256:1a87afcf2097cc01bd4c89cda9c083d99bffafb40907ec012cab1f84e67e1989
size 3326
|
/*!
* jQuery JavaScript Library v1.10.2
* http://jquery.com/
*
* Includes Sizzle.js
* http://sizzlejs.com/
*
* Copyright 2005, 2013 jQuery Foundation, Inc. and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2013-07-03T13:48Z
*/
(function( window, undefined ) {
// Can't do this because several apps including ASP.NET trace
// the stack via arguments.caller.callee and Firefox dies if
// you try to trace through "use strict" call chains. (#13335)
// Support: Firefox 18+
//"use strict";
var
// The deferred used on DOM ready
readyList,
// A central reference to the root jQuery(document)
rootjQuery,
// Support: IE<10
// For `typeof xmlNode.method` instead of `xmlNode.method !== undefined`
core_strundefined = typeof undefined,
// Use the correct document accordingly with window argument (sandbox)
location = window.location,
document = window.document,
docElem = document.documentElement,
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$,
// [[Class]] -> type pairs
class2type = {},
// List of deleted data cache ids, so we can reuse them
core_deletedIds = [],
core_version = "1.10.2",
// Save a reference to some core methods
core_concat = core_deletedIds.concat,
core_push = core_deletedIds.push,
core_slice = core_deletedIds.slice,
core_indexOf = core_deletedIds.indexOf,
core_toString = class2type.toString,
core_hasOwn = class2type.hasOwnProperty,
core_trim = core_version.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 splitting on whitespace
core_rnotwhite = /\S+/g,
// 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)
// Strict HTML recognition (#11290: must start with <)
rquickExpr = /^(?:\s*(<[\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+(?:[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
completed = function( event ) {
// readyState === "complete" is good enough for us to call the dom ready in oldIE
if ( document.addEventListener || event.type === "load" || document.readyState === "complete" ) {
detach();
jQuery.ready();
}
},
// Clean-up method for dom ready events
detach = function() {
if ( document.addEventListener ) {
document.removeEventListener( "DOMContentLoaded", completed, false );
window.removeEventListener( "load", completed, false );
} else {
document.detachEvent( "onreadystatechange", completed );
window.detachEvent( "onload", completed );
}
};
jQuery.fn = jQuery.prototype = {
// The current version of jQuery being used
jquery: core_version,
constructor: jQuery,
init: function( selector, context, rootjQuery ) {
var match, elem;
// HANDLE: $(""), $(null), $(undefined), $(false)
if ( !selector ) {
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;
// scripts is true for back-compat
jQuery.merge( this, jQuery.parseHTML(
match[1],
context && context.nodeType ? context.ownerDocument || context : document,
true
) );
// HANDLE: $(html, props)
if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) {
for ( match in context ) {
// Properties of context are called as methods if possible
if ( jQuery.isFunction( this[ match ] ) ) {
this[ match ]( context[ match ] );
// ...and otherwise set as attributes
} else {
this.attr( match, context[ match ] );
}
}
}
return this;
// 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: $(DOMElement)
} else if ( selector.nodeType ) {
this.context = this[0] = selector;
this.length = 1;
return this;
// 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 default length of a jQuery object is 0
length: 0,
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 ) {
// 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;
// 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;
},
slice: function() {
return this.pushStack( core_slice.apply( this, arguments ) );
},
first: function() {
return this.eq( 0 );
},
last: function() {
return this.eq( -1 );
},
eq: function( i ) {
var len = this.length,
j = +i + ( i < 0 ? len : 0 );
return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] );
},
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 src, copyIsArray, copy, name, options, 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({
// Unique for each copy of jQuery on the page
// Non-digits removed to match rinlinejQuery
expando: "jQuery" + ( core_version + Math.random() ).replace( /\D/g, "" ),
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 );
}
// 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 ) {
/* jshint eqeqeq: false */
return obj != null && obj == obj.window;
},
isNumeric: function( obj ) {
return !isNaN( parseFloat(obj) ) && isFinite( obj );
},
type: function( obj ) {
if ( obj == null ) {
return String( obj );
}
return typeof obj === "object" || typeof obj === "function" ?
class2type[ core_toString.call(obj) ] || "object" :
typeof obj;
},
isPlainObject: function( obj ) {
var key;
// 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;
}
// Support: IE<9
// Handle iteration over inherited properties before own properties.
if ( jQuery.support.ownLast ) {
for ( key in obj ) {
return core_hasOwn.call( obj, key );
}
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
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
// keepScripts (optional): If true, will include scripts passed in the html string
parseHTML: function( data, context, keepScripts ) {
if ( !data || typeof data !== "string" ) {
return null;
}
if ( typeof context === "boolean" ) {
keepScripts = context;
context = false;
}
context = context || document;
var parsed = rsingleTag.exec( data ),
scripts = !keepScripts && [];
// Single tag
if ( parsed ) {
return [ context.createElement( parsed[1] ) ];
}
parsed = jQuery.buildFragment( [ data ], context, scripts );
if ( scripts ) {
jQuery( scripts ).remove();
}
return jQuery.merge( [], parsed.childNodes );
},
parseJSON: function( data ) {
// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
}
if ( data === null ) {
return data;
}
if ( typeof data === "string" ) {
// Make sure leading/trailing whitespace is removed (IE can't handle it)
data = jQuery.trim( data );
if ( 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 && jQuery.trim( 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 value,
i = 0,
length = obj.length,
isArray = isArraylike( obj );
if ( args ) {
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.apply( obj[ i ], args );
if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.apply( obj[ i ], args );
if ( value === false ) {
break;
}
}
}
// A special, fast, case for the most common use of each
} else {
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.call( obj[ i ], i, obj[ i ] );
if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.call( obj[ i ], i, obj[ i ] );
if ( value === 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 ret = results || [];
if ( arr != null ) {
if ( isArraylike( Object(arr) ) ) {
jQuery.merge( ret,
typeof arr === "string" ?
[ arr ] : arr
);
} else {
core_push.call( 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,
i = 0,
length = elems.length,
isArray = isArraylike( elems ),
ret = [];
// 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 ( i in elems ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
}
// Flatten any nested arrays
return core_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 args, proxy, tmp;
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 || this, 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, raw ) {
var i = 0,
length = elems.length,
bulk = key == null;
// Sets many values
if ( jQuery.type( key ) === "object" ) {
chainable = true;
for ( i in key ) {
jQuery.access( elems, fn, i, key[i], true, emptyGet, raw );
}
// Sets one value
} else if ( value !== undefined ) {
chainable = true;
if ( !jQuery.isFunction( value ) ) {
raw = true;
}
if ( bulk ) {
// Bulk operations run against the entire set
if ( raw ) {
fn.call( elems, value );
fn = null;
// ...except when executing function values
} else {
bulk = fn;
fn = function( elem, key, value ) {
return bulk.call( jQuery( elem ), value );
};
}
}
if ( fn ) {
for ( ; i < length; i++ ) {
fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) );
}
}
}
return chainable ?
elems :
// Gets
bulk ?
fn.call( elems ) :
length ? fn( elems[0], key ) : emptyGet;
},
now: function() {
return ( new Date() ).getTime();
},
// A method for quickly swapping in/out CSS properties to get correct calculations.
// Note: this method belongs to the css module but it's needed here for the support module.
// If support gets modularized, this method should be moved back to the css module.
swap: function( elem, options, callback, args ) {
var ret, name,
old = {};
// Remember the old values, and insert the new ones
for ( name in options ) {
old[ name ] = elem.style[ name ];
elem.style[ name ] = options[ name ];
}
ret = callback.apply( elem, args || [] );
// Revert the old values
for ( name in options ) {
elem.style[ name ] = old[ name ];
}
return ret;
}
});
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 );
// Standards-based browsers support DOMContentLoaded
} else if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", completed, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", completed, false );
// If IE event model is used
} else {
// Ensure firing before onload, maybe late but safe also for iframes
document.attachEvent( "onreadystatechange", completed );
// A fallback to window.onload, that will always work
window.attachEvent( "onload", completed );
// 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 );
}
// detach all dom ready events
detach();
// 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 Error".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
function isArraylike( obj ) {
var length = obj.length,
type = jQuery.type( obj );
if ( jQuery.isWindow( obj ) ) {
return false;
}
if ( obj.nodeType === 1 && length ) {
return true;
}
return type === "array" || type !== "function" &&
( length === 0 ||
typeof length === "number" && length > 0 && ( length - 1 ) in obj );
}
// All jQuery objects should point back to these
rootjQuery = jQuery(document);
/*!
* Sizzle CSS Selector Engine v1.10.2
* http://sizzlejs.com/
*
* Copyright 2013 jQuery Foundation, Inc. and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2013-07-03
*/
(function( window, undefined ) {
var i,
support,
cachedruns,
Expr,
getText,
isXML,
compile,
outermostContext,
sortInput,
// Local document vars
setDocument,
document,
docElem,
documentIsHTML,
rbuggyQSA,
rbuggyMatches,
matches,
contains,
// Instance-specific data
expando = "sizzle" + -(new Date()),
preferredDoc = window.document,
dirruns = 0,
done = 0,
classCache = createCache(),
tokenCache = createCache(),
compilerCache = createCache(),
hasDuplicate = false,
sortOrder = function( a, b ) {
if ( a === b ) {
hasDuplicate = true;
return 0;
}
return 0;
},
// General-purpose constants
strundefined = typeof undefined,
MAX_NEGATIVE = 1 << 31,
// Instance methods
hasOwn = ({}).hasOwnProperty,
arr = [],
pop = arr.pop,
push_native = arr.push,
push = arr.push,
slice = arr.slice,
// Use a stripped-down indexOf if we can't use a native one
indexOf = arr.indexOf || function( elem ) {
var i = 0,
len = this.length;
for ( ; i < len; i++ ) {
if ( this[i] === elem ) {
return i;
}
}
return -1;
},
booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",
// Regular expressions
// 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
attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace +
"*(?:([*^$|!~]?=)" + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]",
// Prefer arguments quoted,
// then not containing pseudos/brackets,
// then attribute selectors/non-parenthetical expressions,
// then anything else
// These preferences are here to reduce the number of selectors
// needing tokenize in the PSEUDO preFilter
pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)",
// 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 + "*([>+~]|" + whitespace + ")" + whitespace + "*" ),
rsibling = new RegExp( whitespace + "*[+~]" ),
rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*)" + whitespace + "*\\]", "g" ),
rpseudo = new RegExp( pseudos ),
ridentifier = new RegExp( "^" + identifier + "$" ),
matchExpr = {
"ID": new RegExp( "^#(" + characterEncoding + ")" ),
"CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ),
"TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ),
"ATTR": new RegExp( "^" + attributes ),
"PSEUDO": new RegExp( "^" + pseudos ),
"CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace +
"*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace +
"*(\\d+)|))" + whitespace + "*\\)|)", "i" ),
"bool": new RegExp( "^(?:" + booleans + ")$", "i" ),
// For use in libraries implementing .is()
// We use this for POS matching in `select`
"needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" +
whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" )
},
rnative = /^[^{]+\{\s*\[native \w/,
// Easily-parseable/retrievable ID or TAG or CLASS selectors
rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,
rinputs = /^(?:input|select|textarea|button)$/i,
rheader = /^h\d$/i,
rescape = /'|\\/g,
// CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters
runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ),
funescape = function( _, escaped, escapedWhitespace ) {
var high = "0x" + escaped - 0x10000;
// NaN means non-codepoint
// Support: Firefox
// Workaround erroneous numeric interpretation of +"0x"
return high !== high || escapedWhitespace ?
escaped :
// BMP codepoint
high < 0 ?
String.fromCharCode( high + 0x10000 ) :
// Supplemental Plane codepoint (surrogate pair)
String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 );
};
// Optimize for push.apply( _, NodeList )
try {
push.apply(
(arr = slice.call( preferredDoc.childNodes )),
preferredDoc.childNodes
);
// Support: Android<4.0
// Detect silently failing push.apply
arr[ preferredDoc.childNodes.length ].nodeType;
} catch ( e ) {
push = { apply: arr.length ?
// Leverage slice if possible
function( target, els ) {
push_native.apply( target, slice.call(els) );
} :
// Support: IE<9
// Otherwise append directly
function( target, els ) {
var j = target.length,
i = 0;
// Can't trust NodeList.length
while ( (target[j++] = els[i++]) ) {}
target.length = j - 1;
}
};
}
function Sizzle( selector, context, results, seed ) {
var match, elem, m, nodeType,
// QSA vars
i, groups, old, nid, newContext, newSelector;
if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) {
setDocument( context );
}
context = context || document;
results = results || [];
if ( !selector || typeof selector !== "string" ) {
return results;
}
if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) {
return [];
}
if ( documentIsHTML && !seed ) {
// Shortcuts
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, context.getElementsByTagName( selector ) );
return results;
// Speed-up: Sizzle(".CLASS")
} else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) {
push.apply( results, context.getElementsByClassName( m ) );
return results;
}
}
// QSA path
if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) {
nid = old = expando;
newContext = context;
newSelector = 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 ( 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 + toSelector( groups[i] );
}
newContext = rsibling.test( selector ) && context.parentNode || context;
newSelector = groups.join(",");
}
if ( newSelector ) {
try {
push.apply( results,
newContext.querySelectorAll( newSelector )
);
return results;
} catch(qsaError) {
} finally {
if ( !old ) {
context.removeAttribute("id");
}
}
}
}
}
// All others
return select( selector.replace( rtrim, "$1" ), context, results, seed );
}
/**
* Create key-value caches of limited size
* @returns {Function(string, Object)} Returns the Object data after storing it on itself with
* property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength)
* deleting the oldest entry
*/
function createCache() {
var keys = [];
function cache( key, value ) {
// Use (key + " ") to avoid collision with native prototype properties (see Issue #157)
if ( keys.push( key += " " ) > Expr.cacheLength ) {
// Only keep the most recent entries
delete cache[ keys.shift() ];
}
return (cache[ key ] = value);
}
return cache;
}
/**
* Mark a function for special use by Sizzle
* @param {Function} fn The function to mark
*/
function markFunction( fn ) {
fn[ expando ] = true;
return fn;
}
/**
* Support testing using an element
* @param {Function} fn Passed the created div and expects a boolean result
*/
function assert( fn ) {
var div = document.createElement("div");
try {
return !!fn( div );
} catch (e) {
return false;
} finally {
// Remove from its parent by default
if ( div.parentNode ) {
div.parentNode.removeChild( div );
}
// release memory in IE
div = null;
}
}
/**
* Adds the same handler for all of the specified attrs
* @param {String} attrs Pipe-separated list of attributes
* @param {Function} handler The method that will be applied
*/
function addHandle( attrs, handler ) {
var arr = attrs.split("|"),
i = attrs.length;
while ( i-- ) {
Expr.attrHandle[ arr[i] ] = handler;
}
}
/**
* Checks document order of two siblings
* @param {Element} a
* @param {Element} b
* @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b
*/
function siblingCheck( a, b ) {
var cur = b && a,
diff = cur && a.nodeType === 1 && b.nodeType === 1 &&
( ~b.sourceIndex || MAX_NEGATIVE ) -
( ~a.sourceIndex || MAX_NEGATIVE );
// Use IE sourceIndex if available on both nodes
if ( diff ) {
return diff;
}
// Check if b follows a
if ( cur ) {
while ( (cur = cur.nextSibling) ) {
if ( cur === b ) {
return -1;
}
}
}
return a ? 1 : -1;
}
/**
* Returns a function to use in pseudos for input types
* @param {String} type
*/
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
* @param {String} type
*/
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
* @param {Function} fn
*/
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]);
}
}
});
});
}
/**
* Detect xml
* @param {Element|Object} elem An element or a document
*/
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;
};
// Expose support vars for convenience
support = Sizzle.support = {};
/**
* Sets document-related variables once based on the current document
* @param {Element|Object} [doc] An element or document object to use to set the document
* @returns {Object} Returns the current document
*/
setDocument = Sizzle.setDocument = function( node ) {
var doc = node ? node.ownerDocument || node : preferredDoc,
parent = doc.defaultView;
// If no document and documentElement is available, return
if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) {
return document;
}
// Set our document
document = doc;
docElem = doc.documentElement;
// Support tests
documentIsHTML = !isXML( doc );
// Support: IE>8
// If iframe document is assigned to "document" variable and if iframe has been reloaded,
// IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936
// IE6-8 do not support the defaultView property so parent will be undefined
if ( parent && parent.attachEvent && parent !== parent.top ) {
parent.attachEvent( "onbeforeunload", function() {
setDocument();
});
}
/* Attributes
---------------------------------------------------------------------- */
// Support: IE<8
// Verify that getAttribute really returns attributes and not properties (excepting IE8 booleans)
support.attributes = assert(function( div ) {
div.className = "i";
return !div.getAttribute("className");
});
/* getElement(s)By*
---------------------------------------------------------------------- */
// Check if getElementsByTagName("*") returns only elements
support.getElementsByTagName = assert(function( div ) {
div.appendChild( doc.createComment("") );
return !div.getElementsByTagName("*").length;
});
// Check if getElementsByClassName can be trusted
support.getElementsByClassName = assert(function( div ) {
div.innerHTML = "<div class='a'></div><div class='a i'></div>";
// Support: Safari<4
// Catch class over-caching
div.firstChild.className = "i";
// Support: Opera<10
// Catch gEBCN failure to find non-leading classes
return div.getElementsByClassName("i").length === 2;
});
// Support: IE<10
// Check if getElementById returns elements by name
// The broken getElementById methods don't pick up programatically-set names,
// so use a roundabout getElementsByName test
support.getById = assert(function( div ) {
docElem.appendChild( div ).id = expando;
return !doc.getElementsByName || !doc.getElementsByName( expando ).length;
});
// ID find and filter
if ( support.getById ) {
Expr.find["ID"] = function( id, context ) {
if ( typeof context.getElementById !== strundefined && documentIsHTML ) {
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] : [];
}
};
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
return elem.getAttribute("id") === attrId;
};
};
} else {
// Support: IE6/7
// getElementById is not reliable as a find shortcut
delete Expr.find["ID"];
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id");
return node && node.value === attrId;
};
};
}
// Tag
Expr.find["TAG"] = support.getElementsByTagName ?
function( tag, context ) {
if ( typeof context.getElementsByTagName !== strundefined ) {
return context.getElementsByTagName( tag );
}
} :
function( tag, context ) {
var elem,
tmp = [],
i = 0,
results = context.getElementsByTagName( tag );
// Filter out possible comments
if ( tag === "*" ) {
while ( (elem = results[i++]) ) {
if ( elem.nodeType === 1 ) {
tmp.push( elem );
}
}
return tmp;
}
return results;
};
// Class
Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) {
if ( typeof context.getElementsByClassName !== strundefined && documentIsHTML ) {
return context.getElementsByClassName( className );
}
};
/* QSA/matchesSelector
---------------------------------------------------------------------- */
// QSA and matchesSelector support
// matchesSelector(:active) reports false when true (IE9/Opera 11.5)
rbuggyMatches = [];
// qSa(:focus) reports false when true (Chrome 21)
// We allow this because of a bug in IE8/9 that throws an error
// whenever `document.activeElement` is accessed on an iframe
// So, we allow :focus to pass through QSA all the time to avoid the IE error
// See http://bugs.jquery.com/ticket/13378
rbuggyQSA = [];
if ( (support.qsa = rnative.test( doc.querySelectorAll )) ) {
// 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 explicitly
// setting a boolean content attribute,
// since its presence should be enough
// http://bugs.jquery.com/ticket/12359
div.innerHTML = "<select><option selected=''></option></select>";
// Support: IE8
// Boolean attributes and "value" are not treated correctly
if ( !div.querySelectorAll("[selected]").length ) {
rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" );
}
// Webkit/Opera - :checked should return selected option elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
// IE8 throws error here and will not see later tests
if ( !div.querySelectorAll(":checked").length ) {
rbuggyQSA.push(":checked");
}
});
assert(function( div ) {
// Support: Opera 10-12/IE8
// ^= $= *= and empty values
// Should not select anything
// Support: Windows 8 Native Apps
// The type attribute is restricted during .innerHTML assignment
var input = doc.createElement("input");
input.setAttribute( "type", "hidden" );
div.appendChild( input ).setAttribute( "t", "" );
if ( div.querySelectorAll("[t^='']").length ) {
rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" );
}
// FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
// IE8 throws error here and will not see later tests
if ( !div.querySelectorAll(":enabled").length ) {
rbuggyQSA.push( ":enabled", ":disabled" );
}
// Opera 10-11 does not throw on post-comma invalid pseudos
div.querySelectorAll("*,:x");
rbuggyQSA.push(",.*:");
});
}
if ( (support.matchesSelector = rnative.test( (matches = docElem.webkitMatchesSelector ||
docElem.mozMatchesSelector ||
docElem.oMatchesSelector ||
docElem.msMatchesSelector) )) ) {
assert(function( div ) {
// Check to see if it's possible to do matchesSelector
// on a disconnected node (IE 9)
support.disconnectedMatch = matches.call( div, "div" );
// This should fail with an exception
// Gecko does not error, returns false instead
matches.call( div, "[s!='']:x" );
rbuggyMatches.push( "!=", pseudos );
});
}
rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") );
rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") );
/* Contains
---------------------------------------------------------------------- */
// Element contains another
// Purposefully does not implement inclusive descendent
// As in, an element does not contain itself
contains = rnative.test( docElem.contains ) || docElem.compareDocumentPosition ?
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 ) :
a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16
));
} :
function( a, b ) {
if ( b ) {
while ( (b = b.parentNode) ) {
if ( b === a ) {
return true;
}
}
}
return false;
};
/* Sorting
---------------------------------------------------------------------- */
// Document order sorting
sortOrder = docElem.compareDocumentPosition ?
function( a, b ) {
// Flag for duplicate removal
if ( a === b ) {
hasDuplicate = true;
return 0;
}
var compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b );
if ( compare ) {
// Disconnected nodes
if ( compare & 1 ||
(!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) {
// Choose the first element that is related to our preferred document
if ( a === doc || contains(preferredDoc, a) ) {
return -1;
}
if ( b === doc || contains(preferredDoc, b) ) {
return 1;
}
// Maintain original order
return sortInput ?
( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) :
0;
}
return compare & 4 ? -1 : 1;
}
// Not directly comparable, sort on existence of method
return a.compareDocumentPosition ? -1 : 1;
} :
function( a, b ) {
var cur,
i = 0,
aup = a.parentNode,
bup = b.parentNode,
ap = [ a ],
bp = [ b ];
// Exit early if the nodes are identical
if ( a === b ) {
hasDuplicate = true;
return 0;
// Parentless nodes are either documents or disconnected
} else if ( !aup || !bup ) {
return a === doc ? -1 :
b === doc ? 1 :
aup ? -1 :
bup ? 1 :
sortInput ?
( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) :
0;
// If the nodes are siblings, we can do a quick check
} else if ( aup === bup ) {
return siblingCheck( a, b );
}
// Otherwise we need full lists of their ancestors for comparison
cur = a;
while ( (cur = cur.parentNode) ) {
ap.unshift( cur );
}
cur = b;
while ( (cur = cur.parentNode) ) {
bp.unshift( cur );
}
// Walk down the tree looking for a discrepancy
while ( ap[i] === bp[i] ) {
i++;
}
return i ?
// Do a sibling check if the nodes have a common ancestor
siblingCheck( ap[i], bp[i] ) :
// Otherwise nodes in our document sort first
ap[i] === preferredDoc ? -1 :
bp[i] === preferredDoc ? 1 :
0;
};
return doc;
};
Sizzle.matches = function( expr, elements ) {
return Sizzle( expr, null, null, elements );
};
Sizzle.matchesSelector = function( elem, expr ) {
// Set document vars if needed
if ( ( elem.ownerDocument || elem ) !== document ) {
setDocument( elem );
}
// Make sure that attribute selectors are quoted
expr = expr.replace( rattributeQuotes, "='$1']" );
if ( support.matchesSelector && documentIsHTML &&
( !rbuggyMatches || !rbuggyMatches.test( expr ) ) &&
( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) {
try {
var ret = matches.call( elem, expr );
// IE 9's matchesSelector returns false on disconnected nodes
if ( ret || support.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, document, null, [elem] ).length > 0;
};
Sizzle.contains = function( context, elem ) {
// Set document vars if needed
if ( ( context.ownerDocument || context ) !== document ) {
setDocument( context );
}
return contains( context, elem );
};
Sizzle.attr = function( elem, name ) {
// Set document vars if needed
if ( ( elem.ownerDocument || elem ) !== document ) {
setDocument( elem );
}
var fn = Expr.attrHandle[ name.toLowerCase() ],
// Don't get fooled by Object.prototype properties (jQuery #13807)
val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ?
fn( elem, name, !documentIsHTML ) :
undefined;
return val === undefined ?
support.attributes || !documentIsHTML ?
elem.getAttribute( name ) :
(val = elem.getAttributeNode(name)) && val.specified ?
val.value :
null :
val;
};
Sizzle.error = function( msg ) {
throw new Error( "Syntax error, unrecognized expression: " + msg );
};
/**
* Document sorting and removing duplicates
* @param {ArrayLike} results
*/
Sizzle.uniqueSort = function( results ) {
var elem,
duplicates = [],
j = 0,
i = 0;
// Unless we *know* we can detect duplicates, assume their presence
hasDuplicate = !support.detectDuplicates;
sortInput = !support.sortStable && results.slice( 0 );
results.sort( sortOrder );
if ( hasDuplicate ) {
while ( (elem = results[i++]) ) {
if ( elem === results[ i ] ) {
j = duplicates.push( i );
}
}
while ( j-- ) {
results.splice( duplicates[ j ], 1 );
}
}
return results;
};
/**
* 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 no nodeType, this is expected to be an array
for ( ; (node = elem[i]); i++ ) {
// Do not traverse comment nodes
ret += getText( node );
}
} else 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
return ret;
};
Expr = Sizzle.selectors = {
// Can be adjusted by the user
cacheLength: 50,
createPseudo: markFunction,
match: matchExpr,
attrHandle: {},
find: {},
relative: {
">": { dir: "parentNode", first: true },
" ": { dir: "parentNode" },
"+": { dir: "previousSibling", first: true },
"~": { dir: "previousSibling" }
},
preFilter: {
"ATTR": function( match ) {
match[1] = match[1].replace( runescape, funescape );
// Move the given value to match[3] whether quoted or unquoted
match[3] = ( match[4] || match[5] || "" ).replace( runescape, funescape );
if ( match[2] === "~=" ) {
match[3] = " " + match[3] + " ";
}
return match.slice( 0, 4 );
},
"CHILD": function( match ) {
/* matches from matchExpr["CHILD"]
1 type (only|nth|...)
2 what (child|of-type)
3 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
4 xn-component of xn+y argument ([+-]?\d*n|)
5 sign of xn-component
6 x of xn-component
7 sign of y-component
8 y of y-component
*/
match[1] = match[1].toLowerCase();
if ( match[1].slice( 0, 3 ) === "nth" ) {
// nth-* requires argument
if ( !match[3] ) {
Sizzle.error( match[0] );
}
// numeric x and y parameters for Expr.filter.CHILD
// remember that false/true cast respectively to 0/1
match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) );
match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" );
// other types prohibit arguments
} else if ( match[3] ) {
Sizzle.error( match[0] );
}
return match;
},
"PSEUDO": function( match ) {
var excess,
unquoted = !match[5] && match[2];
if ( matchExpr["CHILD"].test( match[0] ) ) {
return null;
}
// Accept quoted arguments as-is
if ( match[3] && match[4] !== undefined ) {
match[2] = match[4];
// Strip excess characters from unquoted arguments
} else if ( unquoted && 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
match[0] = match[0].slice( 0, excess );
match[2] = unquoted.slice( 0, excess );
}
// Return only captures needed by the pseudo filter method (type and argument)
return match.slice( 0, 3 );
}
},
filter: {
"TAG": function( nodeNameSelector ) {
var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase();
return nodeNameSelector === "*" ?
function() { return true; } :
function( elem ) {
return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
};
},
"CLASS": function( className ) {
var pattern = classCache[ className + " " ];
return pattern ||
(pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) &&
classCache( className, function( elem ) {
return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== strundefined && elem.getAttribute("class") || "" );
});
},
"ATTR": function( name, operator, check ) {
return function( elem ) {
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.slice( -check.length ) === check :
operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 :
operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" :
false;
};
},
"CHILD": function( type, what, argument, first, last ) {
var simple = type.slice( 0, 3 ) !== "nth",
forward = type.slice( -4 ) !== "last",
ofType = what === "of-type";
return first === 1 && last === 0 ?
// Shortcut for :nth-*(n)
function( elem ) {
return !!elem.parentNode;
} :
function( elem, context, xml ) {
var cache, outerCache, node, diff, nodeIndex, start,
dir = simple !== forward ? "nextSibling" : "previousSibling",
parent = elem.parentNode,
name = ofType && elem.nodeName.toLowerCase(),
useCache = !xml && !ofType;
if ( parent ) {
// :(first|last|only)-(child|of-type)
if ( simple ) {
while ( dir ) {
node = elem;
while ( (node = node[ dir ]) ) {
if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) {
return false;
}
}
// Reverse direction for :only-* (if we haven't yet done so)
start = dir = type === "only" && !start && "nextSibling";
}
return true;
}
start = [ forward ? parent.firstChild : parent.lastChild ];
// non-xml :nth-child(...) stores cache data on `parent`
if ( forward && useCache ) {
// Seek `elem` from a previously-cached index
outerCache = parent[ expando ] || (parent[ expando ] = {});
cache = outerCache[ type ] || [];
nodeIndex = cache[0] === dirruns && cache[1];
diff = cache[0] === dirruns && cache[2];
node = nodeIndex && parent.childNodes[ nodeIndex ];
while ( (node = ++nodeIndex && node && node[ dir ] ||
// Fallback to seeking `elem` from the start
(diff = nodeIndex = 0) || start.pop()) ) {
// When found, cache indexes on `parent` and break
if ( node.nodeType === 1 && ++diff && node === elem ) {
outerCache[ type ] = [ dirruns, nodeIndex, diff ];
break;
}
}
// Use previously-cached element index if available
} else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) {
diff = cache[1];
// xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...)
} else {
// Use the same loop as above to seek `elem` from the start
while ( (node = ++nodeIndex && node && node[ dir ] ||
(diff = nodeIndex = 0) || start.pop()) ) {
if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) {
// Cache the index of each encountered element
if ( useCache ) {
(node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ];
}
if ( node === elem ) {
break;
}
}
}
}
// Incorporate the offset, then check against cycle size
diff -= last;
return diff === first || ( diff % first === 0 && diff / first >= 0 );
}
};
},
"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: {
// Potentially complex 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;
};
}),
// "Whether an element is represented by a :lang() selector
// is based solely on the element's language value
// being equal to the identifier C,
// or beginning with the identifier C immediately followed by "-".
// The matching of C against the element's language value is performed case-insensitively.
// The identifier C does not have to be a valid language name."
// http://www.w3.org/TR/selectors/#lang-pseudo
"lang": markFunction( function( lang ) {
// lang value must be a valid identifier
if ( !ridentifier.test(lang || "") ) {
Sizzle.error( "unsupported lang: " + lang );
}
lang = lang.replace( runescape, funescape ).toLowerCase();
return function( elem ) {
var elemLang;
do {
if ( (elemLang = documentIsHTML ?
elem.lang :
elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) {
elemLang = elemLang.toLowerCase();
return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0;
}
} while ( (elem = elem.parentNode) && elem.nodeType === 1 );
return false;
};
}),
// Miscellaneous
"target": function( elem ) {
var hash = window.location && window.location.hash;
return hash && hash.slice( 1 ) === elem.id;
},
"root": function( elem ) {
return elem === docElem;
},
"focus": function( elem ) {
return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
},
// Boolean properties
"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;
},
// Contents
"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 "?")
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
if ( elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4 ) {
return false;
}
}
return true;
},
"parent": function( elem ) {
return !Expr.pseudos["empty"]( elem );
},
// Element/input types
"header": function( elem ) {
return rheader.test( elem.nodeName );
},
"input": function( elem ) {
return rinputs.test( elem.nodeName );
},
"button": function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === "button" || name === "button";
},
"text": function( elem ) {
var 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" &&
elem.type === "text" &&
( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type );
},
// Position-in-collection
"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 ) {
var i = 0;
for ( ; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"odd": createPositionalPseudo(function( matchIndexes, length ) {
var i = 1;
for ( ; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"lt": createPositionalPseudo(function( matchIndexes, length, argument ) {
var i = argument < 0 ? argument + length : argument;
for ( ; --i >= 0; ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"gt": createPositionalPseudo(function( matchIndexes, length, argument ) {
var i = argument < 0 ? argument + length : argument;
for ( ; ++i < length; ) {
matchIndexes.push( i );
}
return matchIndexes;
})
}
};
Expr.pseudos["nth"] = Expr.pseudos["eq"];
// Add button/input type pseudos
for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) {
Expr.pseudos[ i ] = createInputPseudo( i );
}
for ( i in { submit: true, reset: true } ) {
Expr.pseudos[ i ] = createButtonPseudo( i );
}
// Easy API for creating new setFilters
function setFilters() {}
setFilters.prototype = Expr.filters = Expr.pseudos;
Expr.setFilters = new setFilters();
function tokenize( selector, parseOnly ) {
var matched, match, tokens, type,
soFar, groups, preFilters,
cached = tokenCache[ 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 )) ) {
matched = match.shift();
tokens.push({
value: matched,
// Cast descendant combinators to space
type: match[0].replace( rtrim, " " )
});
soFar = soFar.slice( matched.length );
}
// Filters
for ( type in Expr.filter ) {
if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] ||
(match = preFilters[ type ]( match ))) ) {
matched = match.shift();
tokens.push({
value: matched,
type: type,
matches: match
});
soFar = soFar.slice( matched.length );
}
}
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 toSelector( tokens ) {
var i = 0,
len = tokens.length,
selector = "";
for ( ; i < len; i++ ) {
selector += tokens[i].value;
}
return selector;
}
function addCombinator( matcher, combinator, base ) {
var dir = combinator.dir,
checkNonElements = base && dir === "parentNode",
doneName = done++;
return combinator.first ?
// Check against closest ancestor/preceding element
function( elem, context, xml ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
return matcher( elem, context, xml );
}
}
} :
// Check against all ancestor/preceding elements
function( elem, context, xml ) {
var data, cache, outerCache,
dirkey = dirruns + " " + doneName;
// We can't set arbitrary data on XML nodes, so they don't benefit from dir caching
if ( xml ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
if ( matcher( elem, context, xml ) ) {
return true;
}
}
}
} else {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
outerCache = elem[ expando ] || (elem[ expando ] = {});
if ( (cache = outerCache[ dir ]) && cache[0] === dirkey ) {
if ( (data = cache[1]) === true || data === cachedruns ) {
return data === true;
}
} else {
cache = outerCache[ dir ] = [ dirkey ];
cache[1] = matcher( elem, context, xml ) || cachedruns;
if ( cache[1] === true ) {
return true;
}
}
}
}
}
};
}
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 && toSelector(
// If the preceding token was a descendant combinator, insert an implicit any-element `*`
tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" })
).replace( rtrim, "$1" ),
matcher,
i < j && matcherFromTokens( tokens.slice( i, j ) ),
j < len && matcherFromTokens( (tokens = tokens.slice( j )) ),
j < len && toSelector( tokens )
);
}
matchers.push( matcher );
}
}
return elementMatcher( matchers );
}
function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
// A counter to specify which element is currently being matched
var matcherCachedRuns = 0,
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 ),
// Use integer dirruns iff this is the outermost matcher
dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1);
if ( outermost ) {
outermostContext = context !== document && context;
cachedruns = matcherCachedRuns;
}
// Add elements passing elementMatchers directly to results
// Keep `i` a string if there are no elements so `matchedCount` will be "00" below
for ( ; (elem = elems[i]) != null; i++ ) {
if ( byElement && elem ) {
j = 0;
while ( (matcher = elementMatchers[j++]) ) {
if ( matcher( elem, context, xml ) ) {
results.push( elem );
break;
}
}
if ( outermost ) {
dirruns = dirrunsUnique;
cachedruns = ++matcherCachedRuns;
}
}
// 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 ) {
j = 0;
while ( (matcher = setMatchers[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;
};
return bySet ?
markFunction( superMatcher ) :
superMatcher;
}
compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) {
var i,
setMatchers = [],
elementMatchers = [],
cached = compilerCache[ 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 ) {
var i, tokens, token, type, find,
match = tokenize( selector );
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" &&
support.getById && context.nodeType === 9 && documentIsHTML &&
Expr.relative[ tokens[1].type ] ) {
context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0];
if ( !context ) {
return results;
}
selector = selector.slice( tokens.shift().value.length );
}
// Fetch a seed set for right-to-left matching
i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length;
while ( 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( runescape, funescape ),
rsibling.test( tokens[0].type ) && context.parentNode || context
)) ) {
// If seed is empty or no tokens remain, we can return early
tokens.splice( i, 1 );
selector = seed.length && toSelector( tokens );
if ( !selector ) {
push.apply( results, seed );
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,
!documentIsHTML,
results,
rsibling.test( selector )
);
return results;
}
// One-time assignments
// Sort stability
support.sortStable = expando.split("").sort( sortOrder ).join("") === expando;
// Support: Chrome<14
// Always assume duplicates if they aren't passed to the comparison function
support.detectDuplicates = hasDuplicate;
// Initialize against the default document
setDocument();
// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27)
// Detached nodes confoundingly follow *each other*
support.sortDetached = assert(function( div1 ) {
// Should return 1, but returns 4 (following)
return div1.compareDocumentPosition( document.createElement("div") ) & 1;
});
// Support: IE<8
// Prevent attribute/property "interpolation"
// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
if ( !assert(function( div ) {
div.innerHTML = "<a href='#'></a>";
return div.firstChild.getAttribute("href") === "#" ;
}) ) {
addHandle( "type|href|height|width", function( elem, name, isXML ) {
if ( !isXML ) {
return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 );
}
});
}
// Support: IE<9
// Use defaultValue in place of getAttribute("value")
if ( !support.attributes || !assert(function( div ) {
div.innerHTML = "<input/>";
div.firstChild.setAttribute( "value", "" );
return div.firstChild.getAttribute( "value" ) === "";
}) ) {
addHandle( "value", function( elem, name, isXML ) {
if ( !isXML && elem.nodeName.toLowerCase() === "input" ) {
return elem.defaultValue;
}
});
}
// Support: IE<9
// Use getAttributeNode to fetch booleans when getAttribute lies
if ( !assert(function( div ) {
return div.getAttribute("disabled") == null;
}) ) {
addHandle( booleans, function( elem, name, isXML ) {
var val;
if ( !isXML ) {
return (val = elem.getAttributeNode( name )) && val.specified ?
val.value :
elem[ name ] === true ? name.toLowerCase() : null;
}
});
}
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 );
// 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.match( core_rnotwhite ) || [], 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 // Flag to know if list is currently firing
firing,
// Last fire value (for non-forgettable lists)
memory,
// Flag to know if list was already fired
fired,
// End of the loop when firing
firingLength,
// Index of currently firing callback (modified by remove if needed)
firingIndex,
// First callback to fire (used internally by add and fireWith)
firingStart,
// 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;
},
// Check if a given callback is in the list.
// If no argument is given, return whether or not list has callbacks attached.
has: function( fn ) {
return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length );
},
// Remove all callbacks from the list
empty: function() {
list = [];
firingLength = 0;
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 ) {
if ( list && ( !fired || stack ) ) {
args = args || [];
args = [ context, args.slice ? args.slice() : args ];
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 = jQuery.isFunction( fns[ i ] ) && fns[ i ];
// deferred[ done | fail | progress ] for forwarding actions to newDefer
deferred[ tuple[1] ](function() {
var returned = fn && 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 === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments );
}
});
});
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 ]
deferred[ tuple[0] ] = function() {
deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments );
return this;
};
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( support ) {
var all, a, input, select, fragment, opt, eventName, isSupported, i,
div = document.createElement("div");
// Setup
div.setAttribute( "className", "t" );
div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";
// Finish early in limited (non-browser) environments
all = div.getElementsByTagName("*") || [];
a = div.getElementsByTagName("a")[ 0 ];
if ( !a || !a.style || !all.length ) {
return support;
}
// 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";
// Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7)
support.getSetAttribute = div.className !== "t";
// IE strips leading whitespace when .innerHTML is used
support.leadingWhitespace = div.firstChild.nodeType === 3;
// Make sure that tbody elements aren't automatically inserted
// IE will insert them into empty tables
support.tbody = !div.getElementsByTagName("tbody").length;
// Make sure that link elements get serialized correctly by innerHTML
// This requires a wrapper element in IE
support.htmlSerialize = !!div.getElementsByTagName("link").length;
// Get the style information from getAttribute
// (IE uses .cssText instead)
support.style = /top/.test( a.getAttribute("style") );
// Make sure that URLs aren't manipulated
// (IE normalizes it by default)
support.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
support.opacity = /^0.5/.test( a.style.opacity );
// Verify style float existence
// (IE uses styleFloat instead of cssFloat)
support.cssFloat = !!a.style.cssFloat;
// Check the default checkbox/radio value ("" on WebKit; "on" elsewhere)
support.checkOn = !!input.value;
// 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)
support.optSelected = opt.selected;
// Tests for enctype support on a form (#6743)
support.enctype = !!document.createElement("form").enctype;
// Makes sure cloning an html5 element does not cause problems
// Where outerHTML is undefined, this still works
support.html5Clone = document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>";
// Will be defined later
support.inlineBlockNeedsLayout = false;
support.shrinkWrapBlocks = false;
support.pixelPosition = false;
support.deleteExpando = true;
support.noCloneEvent = true;
support.reliableMarginRight = true;
support.boxSizingReliable = true;
// Make sure checked status is properly cloned
input.checked = true;
support.noCloneChecked = input.cloneNode( true ).checked;
// Make sure that the options inside disabled selects aren't marked as disabled
// (WebKit marks them as disabled)
select.disabled = true;
support.optDisabled = !opt.disabled;
// Support: IE<9
try {
delete div.test;
} catch( e ) {
support.deleteExpando = false;
}
// Check if we can trust getAttribute("value")
input = document.createElement("input");
input.setAttribute( "value", "" );
support.input = input.getAttribute( "value" ) === "";
// Check if an input maintains its value after becoming a radio
input.value = "t";
input.setAttribute( "type", "radio" );
support.radioValue = input.value === "t";
// #11217 - WebKit loses check when the name is after the checked attribute
input.setAttribute( "checked", "t" );
input.setAttribute( "name", "t" );
fragment = document.createDocumentFragment();
fragment.appendChild( input );
// Check if a disconnected checkbox will retain its checked
// value of true after appended to the DOM (IE6/7)
support.appendChecked = input.checked;
// WebKit doesn't clone checked state correctly in fragments
support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked;
// Support: IE<9
// Opera does not clone events (and typeof div.attachEvent === undefined).
// IE9-10 clones events bound via attachEvent, but they don't trigger with .click()
if ( div.attachEvent ) {
div.attachEvent( "onclick", function() {
support.noCloneEvent = false;
});
div.cloneNode( true ).click();
}
// Support: IE<9 (lack submit/change bubble), Firefox 17+ (lack focusin event)
// Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP)
for ( i in { submit: true, change: true, focusin: true }) {
div.setAttribute( eventName = "on" + i, "t" );
support[ i + "Bubbles" ] = eventName in window || div.attributes[ eventName ].expando === false;
}
div.style.backgroundClip = "content-box";
div.cloneNode( true ).style.backgroundClip = "";
support.clearCloneStyle = div.style.backgroundClip === "content-box";
// Support: IE<9
// Iteration over object's inherited properties before its own.
for ( i in jQuery( support ) ) {
break;
}
support.ownLast = i !== "0";
// Run tests that need a body at doc ready
jQuery(function() {
var container, marginDiv, tds,
divReset = "padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;",
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 = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px";
body.appendChild( container ).appendChild( div );
// Support: IE8
// 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).
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";
// Support: IE8
// Check if empty table cells still have offsetWidth/Height
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%;";
// Workaround failing boxSizing test due to offsetWidth returning wrong value
// with some non-1 values of body zoom, ticket #13543
jQuery.swap( body, body.style.zoom != null ? { zoom: 1 } : {}, function() {
support.boxSizing = div.offsetWidth === 4;
});
// Use 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. (#3333)
// Fails in WebKit before Feb 2011 nightlies
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
marginDiv = div.appendChild( document.createElement("div") );
marginDiv.style.cssText = div.style.cssText = divReset;
marginDiv.style.marginRight = marginDiv.style.width = "0";
div.style.width = "1px";
support.reliableMarginRight =
!parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight );
}
if ( typeof div.style.zoom !== core_strundefined ) {
// Support: IE<8
// Check if natively block-level elements act like inline-block
// elements when setting their display to 'inline' and giving
// them layout
div.innerHTML = "";
div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1";
support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 );
// Support: IE6
// Check if elements with layout shrink-wrap their children
div.style.display = "block";
div.innerHTML = "<div></div>";
div.firstChild.style.width = "5px";
support.shrinkWrapBlocks = ( div.offsetWidth !== 3 );
if ( support.inlineBlockNeedsLayout ) {
// Prevent IE 6 from affecting layout for positioned elements #11048
// Prevent IE from shrinking the body in IE 7 mode #12869
// Support: IE<8
body.style.zoom = 1;
}
}
body.removeChild( container );
// Null elements to avoid leaks in IE
container = div = tds = marginDiv = null;
});
// Null elements to avoid leaks in IE
all = select = fragment = opt = a = input = null;
return support;
})({});
var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/,
rmultiDash = /([A-Z])/g;
function internalData( elem, name, data, pvt /* Internal Use Only */ ){
if ( !jQuery.acceptData( elem ) ) {
return;
}
var ret, thisCache,
internalKey = jQuery.expando,
// 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)) && data === undefined && typeof name === "string" ) {
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 ) {
id = elem[ internalKey ] = core_deletedIds.pop() || jQuery.guid++;
} else {
id = internalKey;
}
}
if ( !cache[ id ] ) {
// Avoid exposing jQuery metadata on plain JS objects when the object
// is serialized using JSON.stringify
cache[ id ] = isNode ? {} : { 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 ( typeof name === "string" ) {
// 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;
}
function internalRemoveData( elem, name, pvt ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var thisCache, i,
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(" ");
}
}
} else {
// If "name" is an array of keys...
// When data is initially created, via ("key", "val") signature,
// keys will be converted to camelCase.
// Since there is no way to tell _how_ a key was added, remove
// both plain key and camelCase key. #12786
// This will only penalize the array argument path.
name = name.concat( jQuery.map( name, jQuery.camelCase ) );
}
i = name.length;
while ( 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(thisCache) : !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)
/* jshint eqeqeq: false */
} else if ( jQuery.support.deleteExpando || cache != cache.window ) {
/* jshint eqeqeq: true */
delete cache[ id ];
// When all else fails, null
} else {
cache[ id ] = null;
}
}
jQuery.extend({
cache: {},
// The following elements throw uncatchable exceptions if you
// attempt to add expando properties to them.
noData: {
"applet": true,
"embed": true,
// Ban all objects except for Flash (which handle expandos)
"object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
},
hasData: function( elem ) {
elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ];
return !!elem && !isEmptyDataObject( elem );
},
data: function( elem, name, data ) {
return internalData( elem, name, data );
},
removeData: function( elem, name ) {
return internalRemoveData( elem, name );
},
// For internal use only.
_data: function( elem, name, data ) {
return internalData( elem, name, data, true );
},
_removeData: function( elem, name ) {
return internalRemoveData( elem, name, true );
},
// A method for determining if a DOM node can handle the data expando
acceptData: function( elem ) {
// Do not set data on non-element because it will not be cleared (#8335).
if ( elem.nodeType && elem.nodeType !== 1 && elem.nodeType !== 9 ) {
return false;
}
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 attrs, name,
data = null,
i = 0,
elem = this[0];
// Special expections of .data basically thwart jQuery.access,
// so implement the relevant behavior ourselves
// Gets all values
if ( key === undefined ) {
if ( this.length ) {
data = jQuery.data( elem );
if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) {
attrs = elem.attributes;
for ( ; i < attrs.length; i++ ) {
name = attrs[i].name;
if ( name.indexOf("data-") === 0 ) {
name = jQuery.camelCase( name.slice(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 );
});
}
return arguments.length > 1 ?
// Sets one value
this.each(function() {
jQuery.data( this, key, value );
}) :
// Gets one value
// Try to fetch any internally stored data first
elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : null;
},
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" );
jQuery._removeData( elem, key );
})
});
}
});
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,
rclass = /[\t\r\n\f]/g,
rreturn = /\r/g,
rfocusable = /^(?:input|select|textarea|button|object)$/i,
rclickable = /^(?:a|area)$/i,
ruseDefault = /^(?:checked|selected)$/i,
getSetAttribute = jQuery.support.getSetAttribute,
getSetInput = jQuery.support.input;
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 classes, elem, cur, clazz, j,
i = 0,
len = this.length,
proceed = typeof value === "string" && value;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).addClass( value.call( this, j, this.className ) );
});
}
if ( proceed ) {
// The disjunction here is for better compressibility (see removeClass)
classes = ( value || "" ).match( core_rnotwhite ) || [];
for ( ; i < len; i++ ) {
elem = this[ i ];
cur = elem.nodeType === 1 && ( elem.className ?
( " " + elem.className + " " ).replace( rclass, " " ) :
" "
);
if ( cur ) {
j = 0;
while ( (clazz = classes[j++]) ) {
if ( cur.indexOf( " " + clazz + " " ) < 0 ) {
cur += clazz + " ";
}
}
elem.className = jQuery.trim( cur );
}
}
}
return this;
},
removeClass: function( value ) {
var classes, elem, cur, clazz, j,
i = 0,
len = this.length,
proceed = arguments.length === 0 || typeof value === "string" && value;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).removeClass( value.call( this, j, this.className ) );
});
}
if ( proceed ) {
classes = ( value || "" ).match( core_rnotwhite ) || [];
for ( ; i < len; i++ ) {
elem = this[ i ];
// This expression is here for better compressibility (see addClass)
cur = elem.nodeType === 1 && ( elem.className ?
( " " + elem.className + " " ).replace( rclass, " " ) :
""
);
if ( cur ) {
j = 0;
while ( (clazz = classes[j++]) ) {
// Remove *all* instances
while ( cur.indexOf( " " + clazz + " " ) >= 0 ) {
cur = cur.replace( " " + clazz + " ", " " );
}
}
elem.className = value ? jQuery.trim( cur ) : "";
}
}
}
return this;
},
toggleClass: function( value, stateVal ) {
var type = typeof value;
if ( typeof stateVal === "boolean" && type === "string" ) {
return stateVal ? this.addClass( value ) : this.removeClass( value );
}
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 ),
classNames = value.match( core_rnotwhite ) || [];
while ( (className = classNames[ i++ ]) ) {
// check each className given, space separated list
if ( self.hasClass( className ) ) {
self.removeClass( className );
} else {
self.addClass( className );
}
}
// Toggle whole class name
} else if ( type === core_strundefined || type === "boolean" ) {
if ( this.className ) {
// store className if set
jQuery._data( this, "__className__", this.className );
}
// If the element has a class name or if we're passed "false",
// then remove the whole classname (if there was one, the above saved it).
// Otherwise bring back whatever was previously saved (if anything),
// falling back to the empty string if nothing was stored.
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 ret, hooks, 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;
if ( this.nodeType !== 1 ) {
return;
}
if ( isFunction ) {
val = value.call( this, i, jQuery( this ).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 ) {
// Use proper attribute retrieval(#6932, #12072)
var val = jQuery.find.attr( elem, "value" );
return val != null ?
val :
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 optionSet, option,
options = elem.options,
values = jQuery.makeArray( value ),
i = options.length;
while ( i-- ) {
option = options[ i ];
if ( (option.selected = jQuery.inArray( jQuery(option).val(), values ) >= 0) ) {
optionSet = true;
}
}
// force browsers to behave consistently when non-matching value is set
if ( !optionSet ) {
elem.selectedIndex = -1;
}
return values;
}
}
},
attr: function( elem, name, value ) {
var hooks, ret,
nType = elem.nodeType;
// don't get/set attributes on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
// Fallback to prop when attributes are not supported
if ( typeof elem.getAttribute === core_strundefined ) {
return jQuery.prop( elem, name, value );
}
// All attributes are lowercase
// Grab necessary hook if one is defined
if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {
name = name.toLowerCase();
hooks = jQuery.attrHooks[ name ] ||
( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook );
}
if ( value !== undefined ) {
if ( value === null ) {
jQuery.removeAttr( elem, name );
} else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
elem.setAttribute( name, value + "" );
return value;
}
} else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
ret = jQuery.find.attr( elem, name );
// Non-existent attributes return null, we normalize to undefined
return ret == null ?
undefined :
ret;
}
},
removeAttr: function( elem, value ) {
var name, propName,
i = 0,
attrNames = value && value.match( core_rnotwhite );
if ( attrNames && elem.nodeType === 1 ) {
while ( (name = attrNames[i++]) ) {
propName = jQuery.propFix[ name ] || name;
// Boolean attributes get special treatment (#10870)
if ( jQuery.expr.match.bool.test( name ) ) {
// Set corresponding property to false
if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) {
elem[ propName ] = false;
// Support: IE<9
// Also clear defaultChecked/defaultSelected (if appropriate)
} else {
elem[ jQuery.camelCase( "default-" + name ) ] =
elem[ propName ] = false;
}
// See #9699 for explanation of this approach (setting first, then removal)
} else {
jQuery.attr( elem, name, "" );
}
elem.removeAttribute( getSetAttribute ? name : propName );
}
}
},
attrHooks: {
type: {
set: function( elem, value ) {
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 default in case type is set after value during creation
var val = elem.value;
elem.setAttribute( "type", value );
if ( val ) {
elem.value = val;
}
return value;
}
}
}
},
propFix: {
"for": "htmlFor",
"class": "className"
},
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 ) {
return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ?
ret :
( elem[ name ] = value );
} else {
return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ?
ret :
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/
// Use proper attribute retrieval(#12072)
var tabindex = jQuery.find.attr( elem, "tabindex" );
return tabindex ?
parseInt( tabindex, 10 ) :
rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
0 :
-1;
}
}
}
});
// Hooks for boolean attributes
boolHook = {
set: function( elem, value, name ) {
if ( value === false ) {
// Remove boolean attributes when set to false
jQuery.removeAttr( elem, name );
} else if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) {
// IE<8 needs the *property* name
elem.setAttribute( !getSetAttribute && jQuery.propFix[ name ] || name, name );
// Use defaultChecked and defaultSelected for oldIE
} else {
elem[ jQuery.camelCase( "default-" + name ) ] = elem[ name ] = true;
}
return name;
}
};
jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) {
var getter = jQuery.expr.attrHandle[ name ] || jQuery.find.attr;
jQuery.expr.attrHandle[ name ] = getSetInput && getSetAttribute || !ruseDefault.test( name ) ?
function( elem, name, isXML ) {
var fn = jQuery.expr.attrHandle[ name ],
ret = isXML ?
undefined :
/* jshint eqeqeq: false */
(jQuery.expr.attrHandle[ name ] = undefined) !=
getter( elem, name, isXML ) ?
name.toLowerCase() :
null;
jQuery.expr.attrHandle[ name ] = fn;
return ret;
} :
function( elem, name, isXML ) {
return isXML ?
undefined :
elem[ jQuery.camelCase( "default-" + name ) ] ?
name.toLowerCase() :
null;
};
});
// fix oldIE attroperties
if ( !getSetInput || !getSetAttribute ) {
jQuery.attrHooks.value = {
set: function( elem, value, name ) {
if ( jQuery.nodeName( elem, "input" ) ) {
// Does not return so that setAttribute is also used
elem.defaultValue = value;
} else {
// Use nodeHook if defined (#1954); otherwise setAttribute is fine
return nodeHook && nodeHook.set( elem, value, name );
}
}
};
}
// IE6/7 do not support getting/setting some attributes with get/setAttribute
if ( !getSetAttribute ) {
// Use this for any attribute in IE6/7
// This fixes almost every IE6/7 issue
nodeHook = {
set: function( elem, value, name ) {
// Set the existing or create a new attribute node
var ret = elem.getAttributeNode( name );
if ( !ret ) {
elem.setAttributeNode(
(ret = elem.ownerDocument.createAttribute( name ))
);
}
ret.value = value += "";
// Break association with cloned elements by also using setAttribute (#9646)
return name === "value" || value === elem.getAttribute( name ) ?
value :
undefined;
}
};
jQuery.expr.attrHandle.id = jQuery.expr.attrHandle.name = jQuery.expr.attrHandle.coords =
// Some attributes are constructed with empty-string values when not defined
function( elem, name, isXML ) {
var ret;
return isXML ?
undefined :
(ret = elem.getAttributeNode( name )) && ret.value !== "" ?
ret.value :
null;
};
jQuery.valHooks.button = {
get: function( elem, name ) {
var ret = elem.getAttributeNode( name );
return ret && ret.specified ?
ret.value :
undefined;
},
set: nodeHook.set
};
// Set contenteditable to false on removals(#10429)
// Setting to empty string throws an error as an invalid value
jQuery.attrHooks.contenteditable = {
set: function( elem, value, name ) {
nodeHook.set( elem, value === "" ? false : value, name );
}
};
// 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 ] = {
set: function( elem, value ) {
if ( value === "" ) {
elem.setAttribute( name, "auto" );
return value;
}
}
};
});
}
// Some attributes require a special call on IE
// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
if ( !jQuery.support.hrefNormalized ) {
// href/src property should get the full normalized URL (#10299/#12915)
jQuery.each([ "href", "src" ], function( i, name ) {
jQuery.propHooks[ name ] = {
get: function( elem ) {
return elem.getAttribute( name, 4 );
}
};
});
}
if ( !jQuery.support.style ) {
jQuery.attrHooks.style = {
get: function( elem ) {
// Return undefined in the case of empty string
// Note: IE uppercases css property names, but if we were to .toLowerCase()
// .cssText, that would destroy case senstitivity in URL's, like in "background"
return elem.style.cssText || 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 = {
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;
}
};
}
jQuery.each([
"tabIndex",
"readOnly",
"maxLength",
"cellSpacing",
"cellPadding",
"rowSpan",
"colSpan",
"useMap",
"frameBorder",
"contentEditable"
], function() {
jQuery.propFix[ this.toLowerCase() ] = this;
});
// IE6/7 call enctype encoding
if ( !jQuery.support.enctype ) {
jQuery.propFix.enctype = "encoding";
}
// Radios and checkboxes getter/setter
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = {
set: function( elem, value ) {
if ( jQuery.isArray( value ) ) {
return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 );
}
}
};
if ( !jQuery.support.checkOn ) {
jQuery.valHooks[ this ].get = function( elem ) {
// Support: Webkit
// "" is returned instead of "on" if a value isn't specified
return elem.getAttribute("value") === null ? "on" : elem.value;
};
}
});
var rformElems = /^(?:input|select|textarea)$/i,
rkeyEvent = /^key/,
rmouseEvent = /^(?:mouse|contextmenu)|click/,
rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
rtypenamespace = /^([^.]*)(?:\.(.+)|)$/;
function returnTrue() {
return true;
}
function returnFalse() {
return false;
}
function safeActiveElement() {
try {
return document.activeElement;
} catch ( err ) { }
}
/*
* Helper functions for managing events -- not part of the public interface.
* Props to Dean Edwards' addEvent library for many of the ideas.
*/
jQuery.event = {
global: {},
add: function( elem, types, handler, data, selector ) {
var tmp, events, t, handleObjIn,
special, eventHandle, handleObj,
handlers, type, namespaces, origType,
elemData = jQuery._data( elem );
// Don't attach events to noData or text/comment nodes (but allow plain objects)
if ( !elemData ) {
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
if ( !(events = elemData.events) ) {
events = elemData.events = {};
}
if ( !(eventHandle = elemData.handle) ) {
eventHandle = elemData.handle = 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 !== core_strundefined && (!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
types = ( types || "" ).match( core_rnotwhite ) || [""];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[t] ) || [];
type = origType = tmp[1];
namespaces = ( tmp[2] || "" ).split( "." ).sort();
// There *must* be a type, no attaching namespace-only handlers
if ( !type ) {
continue;
}
// 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: origType,
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
if ( !(handlers = events[ type ]) ) {
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;
},
// Detach an event or set of events from an element
remove: function( elem, types, handler, selector, mappedTypes ) {
var j, handleObj, tmp,
origCount, t, events,
special, handlers, type,
namespaces, origType,
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 = ( types || "" ).match( core_rnotwhite ) || [""];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[t] ) || [];
type = origType = tmp[1];
namespaces = ( tmp[2] || "" ).split( "." ).sort();
// 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;
handlers = events[ type ] || [];
tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" );
// Remove matching events
origCount = j = handlers.length;
while ( j-- ) {
handleObj = handlers[ j ];
if ( ( mappedTypes || origType === handleObj.origType ) &&
( !handler || handler.guid === handleObj.guid ) &&
( !tmp || tmp.test( handleObj.namespace ) ) &&
( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) {
handlers.splice( j, 1 );
if ( handleObj.selector ) {
handlers.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 ( origCount && !handlers.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" );
}
},
trigger: function( event, data, elem, onlyHandlers ) {
var handle, ontype, cur,
bubbleType, special, tmp, i,
eventPath = [ elem || document ],
type = core_hasOwn.call( event, "type" ) ? event.type : event,
namespaces = core_hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : [];
cur = tmp = elem = elem || document;
// Don't do events on text and comment nodes
if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
return;
}
// 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 ) {
// Namespaced trigger; create a regexp to match event type in handle()
namespaces = type.split(".");
type = namespaces.shift();
namespaces.sort();
}
ontype = type.indexOf(":") < 0 && "on" + type;
// Caller can pass in a jQuery.Event object, Object, or just an event type string
event = event[ jQuery.expando ] ?
event :
new jQuery.Event( type, typeof event === "object" && event );
// Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true)
event.isTrigger = onlyHandlers ? 2 : 3;
event.namespace = namespaces.join(".");
event.namespace_re = event.namespace ?
new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) :
null;
// 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 ?
[ event ] :
jQuery.makeArray( data, [ event ] );
// Allow special events to draw outside the lines
special = jQuery.event.special[ type ] || {};
if ( !onlyHandlers && 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)
if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) {
bubbleType = special.delegateType || type;
if ( !rfocusMorph.test( bubbleType + type ) ) {
cur = cur.parentNode;
}
for ( ; cur; cur = cur.parentNode ) {
eventPath.push( cur );
tmp = cur;
}
// Only add window if we got to document (e.g., not plain obj or detached DOM)
if ( tmp === (elem.ownerDocument || document) ) {
eventPath.push( tmp.defaultView || tmp.parentWindow || window );
}
}
// Fire handlers on the event path
i = 0;
while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) {
event.type = i > 1 ?
bubbleType :
special.bindType || type;
// jQuery handler
handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" );
if ( handle ) {
handle.apply( cur, data );
}
// Native 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( eventPath.pop(), data ) === false) &&
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)
if ( ontype && elem[ type ] && !jQuery.isWindow( elem ) ) {
// Don't re-trigger an onFOO event when we call its FOO() method
tmp = elem[ ontype ];
if ( tmp ) {
elem[ ontype ] = null;
}
// Prevent re-triggering of the same event, since we already bubbled it above
jQuery.event.triggered = type;
try {
elem[ type ]();
} catch ( e ) {
// IE<9 dies on focus/blur to hidden element (#1486,#12518)
// only reproducible on winXP IE8 native, not IE9 in IE8 mode
}
jQuery.event.triggered = undefined;
if ( tmp ) {
elem[ ontype ] = tmp;
}
}
}
}
return event.result;
},
dispatch: function( event ) {
// Make a writable jQuery.Event from the native event object
event = jQuery.event.fix( event );
var i, ret, handleObj, matched, j,
handlerQueue = [],
args = core_slice.call( arguments ),
handlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || [],
special = jQuery.event.special[ event.type ] || {};
// 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
handlerQueue = jQuery.event.handlers.call( this, event, handlers );
// Run delegates first; they may want to stop propagation beneath us
i = 0;
while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) {
event.currentTarget = matched.elem;
j = 0;
while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) {
// Triggered event must either 1) have no namespace, or
// 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace).
if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) {
event.handleObj = handleObj;
event.data = handleObj.data;
ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler )
.apply( matched.elem, args );
if ( ret !== undefined ) {
if ( (event.result = 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;
},
handlers: function( event, handlers ) {
var sel, handleObj, matches, i,
handlerQueue = [],
delegateCount = handlers.delegateCount,
cur = event.target;
// Find delegate handlers
// Black-hole SVG <use> instance trees (#13180)
// Avoid non-left-click bubbling in Firefox (#3861)
if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) {
/* jshint eqeqeq: false */
for ( ; cur != this; cur = cur.parentNode || this ) {
/* jshint eqeqeq: true */
// Don't check non-elements (#13208)
// Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
if ( cur.nodeType === 1 && (cur.disabled !== true || event.type !== "click") ) {
matches = [];
for ( i = 0; i < delegateCount; i++ ) {
handleObj = handlers[ i ];
// Don't conflict with Object.prototype properties (#13203)
sel = handleObj.selector + " ";
if ( matches[ sel ] === undefined ) {
matches[ sel ] = handleObj.needsContext ?
jQuery( sel, this ).index( cur ) >= 0 :
jQuery.find( sel, this, null, [ cur ] ).length;
}
if ( matches[ sel ] ) {
matches.push( handleObj );
}
}
if ( matches.length ) {
handlerQueue.push({ elem: cur, handlers: matches });
}
}
}
}
// Add the remaining (directly-bound) handlers
if ( delegateCount < handlers.length ) {
handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) });
}
return handlerQueue;
},
fix: function( event ) {
if ( event[ jQuery.expando ] ) {
return event;
}
// Create a writable copy of the event object and normalize some properties
var i, prop, copy,
type = event.type,
originalEvent = event,
fixHook = this.fixHooks[ type ];
if ( !fixHook ) {
this.fixHooks[ type ] = fixHook =
rmouseEvent.test( type ) ? this.mouseHooks :
rkeyEvent.test( type ) ? this.keyHooks :
{};
}
copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props;
event = new jQuery.Event( originalEvent );
i = copy.length;
while ( i-- ) {
prop = copy[ i ];
event[ prop ] = originalEvent[ prop ];
}
// Support: IE<9
// Fix target property (#1925)
if ( !event.target ) {
event.target = originalEvent.srcElement || document;
}
// Support: Chrome 23+, Safari?
// Target should not be a text node (#504, #13143)
if ( event.target.nodeType === 3 ) {
event.target = event.target.parentNode;
}
// Support: IE<9
// For mouse/key events, metaKey==false if it's undefined (#3368, #11328)
event.metaKey = !!event.metaKey;
return fixHook.filter ? fixHook.filter( event, originalEvent ) : event;
},
// Includes some event props shared by KeyEvent and MouseEvent
props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),
fixHooks: {},
keyHooks: {
props: "char charCode key keyCode".split(" "),
filter: function( 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 body, eventDoc, doc,
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;
}
},
special: {
load: {
// Prevent triggered image.load events from bubbling to window.load
noBubble: true
},
focus: {
// Fire native event if possible so blur/focus sequence is correct
trigger: function() {
if ( this !== safeActiveElement() && this.focus ) {
try {
this.focus();
return false;
} catch ( e ) {
// Support: IE<9
// If we error on focus to hidden element (#1486, #12518),
// let .trigger() run the handlers
}
}
},
delegateType: "focusin"
},
blur: {
trigger: function() {
if ( this === safeActiveElement() && this.blur ) {
this.blur();
return false;
}
},
delegateType: "focusout"
},
click: {
// For checkbox, fire native event so checked state will be right
trigger: function() {
if ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) {
this.click();
return false;
}
},
// For cross-browser consistency, don't fire native .click() on links
_default: function( event ) {
return jQuery.nodeName( event.target, "a" );
}
},
beforeunload: {
postDispatch: function( event ) {
// Even when returnValue equals to undefined Firefox will still show alert
if ( event.result !== undefined ) {
event.originalEvent.returnValue = event.result;
}
}
}
},
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();
}
}
};
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 ] === core_strundefined ) {
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;
};
// 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 = {
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse,
preventDefault: function() {
var e = this.originalEvent;
this.isDefaultPrevented = returnTrue;
if ( !e ) {
return;
}
// If preventDefault exists, run it on the original event
if ( e.preventDefault ) {
e.preventDefault();
// Support: IE
// Otherwise set the returnValue property of the original event to false
} else {
e.returnValue = false;
}
},
stopPropagation: function() {
var e = this.originalEvent;
this.isPropagationStopped = returnTrue;
if ( !e ) {
return;
}
// If stopPropagation exists, run it on the original event
if ( e.stopPropagation ) {
e.stopPropagation();
}
// Support: IE
// Set the cancelBubble property of the original event to true
e.cancelBubble = true;
},
stopImmediatePropagation: function() {
this.isImmediatePropagationStopped = returnTrue;
this.stopPropagation();
}
};
// 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;
// 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, "submitBubbles" ) ) {
jQuery.event.add( form, "submit._submit", function( event ) {
event._submit_bubble = true;
});
jQuery._data( form, "submitBubbles", 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, "changeBubbles" ) ) {
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, "changeBubbles", 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 type, origFn;
// Types can be a map of types/handlers
if ( typeof types === "object" ) {
// ( types-Object, selector, data )
if ( typeof selector !== "string" ) {
// ( 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 );
});
},
trigger: function( type, data ) {
return this.each(function() {
jQuery.event.trigger( type, data, this );
});
},
triggerHandler: function( type, data ) {
var elem = this[0];
if ( elem ) {
return jQuery.event.trigger( type, data, elem, true );
}
}
});
var isSimple = /^.[^:#\[\.,]*$/,
rparentsprev = /^(?:parents|prev(?:Until|All))/,
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,
ret = [],
self = this,
len = self.length;
if ( typeof selector !== "string" ) {
return this.pushStack( jQuery( selector ).filter(function() {
for ( i = 0; i < len; i++ ) {
if ( jQuery.contains( self[ i ], this ) ) {
return true;
}
}
}) );
}
for ( i = 0; i < len; i++ ) {
jQuery.find( selector, self[ i ], ret );
}
// Needed because $( selector, context ) becomes $( context ).find( selector )
ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret );
ret.selector = this.selector ? this.selector + " " + selector : selector;
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 || [], true) );
},
filter: function( selector ) {
return this.pushStack( winnow(this, selector || [], false) );
},
is: function( selector ) {
return !!winnow(
this,
// 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".
typeof selector === "string" && rneedsContext.test( selector ) ?
jQuery( selector ) :
selector || [],
false
).length;
},
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++ ) {
for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) {
// Always skip document fragments
if ( cur.nodeType < 11 && (pos ?
pos.index(cur) > -1 :
// Don't pass non-elements to Sizzle
cur.nodeType === 1 &&
jQuery.find.matchesSelector(cur, selectors)) ) {
cur = ret.push( cur );
break;
}
}
}
return this.pushStack( ret.length > 1 ? jQuery.unique( ret ) : ret );
},
// 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.first().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( jQuery.unique(all) );
},
addBack: function( selector ) {
return this.add( selector == null ?
this.prevObject : this.prevObject.filter(selector)
);
}
});
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 ( name.slice( -5 ) !== "Until" ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
ret = jQuery.filter( selector, ret );
}
if ( this.length > 1 ) {
// Remove duplicates
if ( !guaranteedUnique[ name ] ) {
ret = jQuery.unique( ret );
}
// Reverse order for parents* and prev-derivatives
if ( rparentsprev.test( name ) ) {
ret = ret.reverse();
}
}
return this.pushStack( ret );
};
});
jQuery.extend({
filter: function( expr, elems, not ) {
var elem = elems[ 0 ];
if ( not ) {
expr = ":not(" + expr + ")";
}
return elems.length === 1 && elem.nodeType === 1 ?
jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] :
jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) {
return elem.nodeType === 1;
}));
},
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, not ) {
if ( jQuery.isFunction( qualifier ) ) {
return jQuery.grep( elements, function( elem, i ) {
/* jshint -W018 */
return !!qualifier.call( elem, i, elem ) !== not;
});
}
if ( qualifier.nodeType ) {
return jQuery.grep( elements, function( elem ) {
return ( elem === qualifier ) !== not;
});
}
if ( typeof qualifier === "string" ) {
if ( isSimple.test( qualifier ) ) {
return jQuery.filter( qualifier, elements, not );
}
qualifier = jQuery.filter( qualifier, elements );
}
return jQuery.grep( elements, function( elem ) {
return ( jQuery.inArray( elem, qualifier ) >= 0 ) !== not;
});
}
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,
rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"),
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,
manipulation_rcheckableType = /^(?:checkbox|radio)$/i,
// checked="checked" or checked
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
rscriptType = /^$|\/(?:java|ecma)script/i,
rscriptTypeMasked = /^true\/(.*)/,
rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,
// We have to close these tags to support XHTML (#13200)
wrapMap = {
option: [ 1, "<select multiple='multiple'>", "</select>" ],
legend: [ 1, "<fieldset>", "</fieldset>" ],
area: [ 1, "<map>", "</map>" ],
param: [ 1, "<object>", "</object>" ],
thead: [ 1, "<table>", "</table>" ],
tr: [ 2, "<table><tbody>", "</tbody></table>" ],
col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ],
td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
// 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.
_default: jQuery.support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X<div>", "</div>" ]
},
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;
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 );
},
append: function() {
return this.domManip( arguments, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
var target = manipulationTarget( this, elem );
target.appendChild( elem );
}
});
},
prepend: function() {
return this.domManip( arguments, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
var target = manipulationTarget( this, elem );
target.insertBefore( elem, target.firstChild );
}
});
},
before: function() {
return this.domManip( arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this );
}
});
},
after: function() {
return this.domManip( arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this.nextSibling );
}
});
},
// keepData is for internal use only--do not document
remove: function( selector, keepData ) {
var elem,
elems = selector ? jQuery.filter( selector, this ) : this,
i = 0;
for ( ; (elem = elems[i]) != null; i++ ) {
if ( !keepData && elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem ) );
}
if ( elem.parentNode ) {
if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) {
setGlobalEval( getAll( elem, "script" ) );
}
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( getAll( elem, false ) );
}
// Remove any remaining nodes
while ( elem.firstChild ) {
elem.removeChild( elem.firstChild );
}
// If this is a select, ensure that it displays empty (#12336)
// Support: IE<9
if ( elem.options && jQuery.nodeName( elem, "select" ) ) {
elem.options.length = 0;
}
}
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( getAll( elem, false ) );
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() {
var
// Snapshot the DOM in case .domManip sweeps something relevant into its fragment
args = jQuery.map( this, function( elem ) {
return [ elem.nextSibling, elem.parentNode ];
}),
i = 0;
// Make the changes, replacing each context element with the new content
this.domManip( arguments, function( elem ) {
var next = args[ i++ ],
parent = args[ i++ ];
if ( parent ) {
// Don't use the snapshot next if it has moved (#13810)
if ( next && next.parentNode !== parent ) {
next = this.nextSibling;
}
jQuery( this ).remove();
parent.insertBefore( elem, next );
}
// Allow new content to include elements from the context set
}, true );
// Force removal if there was no new content (e.g., from empty arguments)
return i ? this : this.remove();
},
detach: function( selector ) {
return this.remove( selector, true );
},
domManip: function( args, callback, allowIntersection ) {
// Flatten any nested arrays
args = core_concat.apply( [], args );
var first, node, hasScripts,
scripts, doc, fragment,
i = 0,
l = this.length,
set = this,
iNoClone = l - 1,
value = args[0],
isFunction = jQuery.isFunction( value );
// We can't cloneNode fragments that contain checked, in WebKit
if ( isFunction || !( l <= 1 || typeof value !== "string" || jQuery.support.checkClone || !rchecked.test( value ) ) ) {
return this.each(function( index ) {
var self = set.eq( index );
if ( isFunction ) {
args[0] = value.call( this, index, self.html() );
}
self.domManip( args, callback, allowIntersection );
});
}
if ( l ) {
fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, !allowIntersection && this );
first = fragment.firstChild;
if ( fragment.childNodes.length === 1 ) {
fragment = first;
}
if ( first ) {
scripts = jQuery.map( getAll( fragment, "script" ), disableScript );
hasScripts = scripts.length;
// Use the original fragment for the last item instead of the first because it can end up
// being emptied incorrectly in certain situations (#8070).
for ( ; i < l; i++ ) {
node = fragment;
if ( i !== iNoClone ) {
node = jQuery.clone( node, true, true );
// Keep references to cloned scripts for later restoration
if ( hasScripts ) {
jQuery.merge( scripts, getAll( node, "script" ) );
}
}
callback.call( this[i], node, i );
}
if ( hasScripts ) {
doc = scripts[ scripts.length - 1 ].ownerDocument;
// Reenable scripts
jQuery.map( scripts, restoreScript );
// Evaluate executable scripts on first document insertion
for ( i = 0; i < hasScripts; i++ ) {
node = scripts[ i ];
if ( rscriptType.test( node.type || "" ) &&
!jQuery._data( node, "globalEval" ) && jQuery.contains( doc, node ) ) {
if ( node.src ) {
// Hope ajax is available...
jQuery._evalUrl( node.src );
} else {
jQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) );
}
}
}
}
// Fix #11809: Avoid leaking memory
fragment = first = null;
}
}
return this;
}
});
// Support: IE<8
// Manipulating tables requires a tbody
function manipulationTarget( elem, content ) {
return jQuery.nodeName( elem, "table" ) &&
jQuery.nodeName( content.nodeType === 1 ? content : content.firstChild, "tr" ) ?
elem.getElementsByTagName("tbody")[0] ||
elem.appendChild( elem.ownerDocument.createElement("tbody") ) :
elem;
}
// Replace/restore the type attribute of script elements for safe DOM manipulation
function disableScript( elem ) {
elem.type = (jQuery.find.attr( elem, "type" ) !== null) + "/" + elem.type;
return elem;
}
function restoreScript( elem ) {
var match = rscriptTypeMasked.exec( elem.type );
if ( match ) {
elem.type = match[1];
} else {
elem.removeAttribute("type");
}
return elem;
}
// Mark scripts as having already been evaluated
function setGlobalEval( elems, refElements ) {
var elem,
i = 0;
for ( ; (elem = elems[i]) != null; i++ ) {
jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[i], "globalEval" ) );
}
}
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 fixCloneNodeIssues( src, dest ) {
var nodeName, e, data;
// We do not need to do anything for non-Elements
if ( dest.nodeType !== 1 ) {
return;
}
nodeName = dest.nodeName.toLowerCase();
// IE6-8 copies events bound via attachEvent when using cloneNode.
if ( !jQuery.support.noCloneEvent && dest[ jQuery.expando ] ) {
data = jQuery._data( dest );
for ( e in data.events ) {
jQuery.removeEvent( dest, e, data.handle );
}
// Event data gets referenced instead of copied if the expando gets copied too
dest.removeAttribute( jQuery.expando );
}
// IE blanks contents when cloning scripts, and tries to evaluate newly-set text
if ( nodeName === "script" && dest.text !== src.text ) {
disableScript( dest ).text = src.text;
restoreScript( dest );
// IE6-10 improperly clones children of object elements using classid.
// IE10 throws NoModificationAllowedError if parent is null, #12132.
} else if ( nodeName === "object" ) {
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" && manipulation_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.defaultSelected = 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;
}
}
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 ),
last = insert.length - 1;
for ( ; i <= last; i++ ) {
elems = i === last ? this : this.clone(true);
jQuery( insert[i] )[ original ]( elems );
// Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get()
core_push.apply( ret, elems.get() );
}
return this.pushStack( ret );
};
});
function getAll( context, tag ) {
var elems, elem,
i = 0,
found = typeof context.getElementsByTagName !== core_strundefined ? context.getElementsByTagName( tag || "*" ) :
typeof context.querySelectorAll !== core_strundefined ? context.querySelectorAll( tag || "*" ) :
undefined;
if ( !found ) {
for ( found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++ ) {
if ( !tag || jQuery.nodeName( elem, tag ) ) {
found.push( elem );
} else {
jQuery.merge( found, getAll( elem, tag ) );
}
}
}
return tag === undefined || tag && jQuery.nodeName( context, tag ) ?
jQuery.merge( [ context ], found ) :
found;
}
// Used in buildFragment, fixes the defaultChecked property
function fixDefaultChecked( elem ) {
if ( manipulation_rcheckableType.test( elem.type ) ) {
elem.defaultChecked = elem.checked;
}
}
jQuery.extend({
clone: function( elem, dataAndEvents, deepDataAndEvents ) {
var destElements, node, clone, i, srcElements,
inPage = jQuery.contains( elem.ownerDocument, elem );
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) ) {
// We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2
destElements = getAll( clone );
srcElements = getAll( elem );
// Fix all IE cloning issues
for ( i = 0; (node = srcElements[i]) != null; ++i ) {
// Ensure that the destination node is not null; Fixes #9587
if ( destElements[i] ) {
fixCloneNodeIssues( node, destElements[i] );
}
}
}
// Copy the events from the original to the clone
if ( dataAndEvents ) {
if ( deepDataAndEvents ) {
srcElements = srcElements || getAll( elem );
destElements = destElements || getAll( clone );
for ( i = 0; (node = srcElements[i]) != null; i++ ) {
cloneCopyEvent( node, destElements[i] );
}
} else {
cloneCopyEvent( elem, clone );
}
}
// Preserve script evaluation history
destElements = getAll( clone, "script" );
if ( destElements.length > 0 ) {
setGlobalEval( destElements, !inPage && getAll( elem, "script" ) );
}
destElements = srcElements = node = null;
// Return the cloned set
return clone;
},
buildFragment: function( elems, context, scripts, selection ) {
var j, elem, contains,
tmp, tag, tbody, wrap,
l = elems.length,
// Ensure a safe fragment
safe = createSafeFragment( context ),
nodes = [],
i = 0;
for ( ; i < l; i++ ) {
elem = elems[ i ];
if ( elem || elem === 0 ) {
// Add nodes directly
if ( jQuery.type( elem ) === "object" ) {
jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem );
// Convert non-html into a text node
} else if ( !rhtml.test( elem ) ) {
nodes.push( context.createTextNode( elem ) );
// Convert html into DOM nodes
} else {
tmp = tmp || safe.appendChild( context.createElement("div") );
// Deserialize a standard representation
tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase();
wrap = wrapMap[ tag ] || wrapMap._default;
tmp.innerHTML = wrap[1] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[2];
// Descend through wrappers to the right content
j = wrap[0];
while ( j-- ) {
tmp = tmp.lastChild;
}
// Manually add leading whitespace removed by IE
if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) );
}
// Remove IE's autoinserted <tbody> from table fragments
if ( !jQuery.support.tbody ) {
// String was a <table>, *may* have spurious <tbody>
elem = tag === "table" && !rtbody.test( elem ) ?
tmp.firstChild :
// String was a bare <thead> or <tfoot>
wrap[1] === "<table>" && !rtbody.test( elem ) ?
tmp :
0;
j = elem && elem.childNodes.length;
while ( j-- ) {
if ( jQuery.nodeName( (tbody = elem.childNodes[j]), "tbody" ) && !tbody.childNodes.length ) {
elem.removeChild( tbody );
}
}
}
jQuery.merge( nodes, tmp.childNodes );
// Fix #12392 for WebKit and IE > 9
tmp.textContent = "";
// Fix #12392 for oldIE
while ( tmp.firstChild ) {
tmp.removeChild( tmp.firstChild );
}
// Remember the top-level container for proper cleanup
tmp = safe.lastChild;
}
}
}
// Fix #11356: Clear elements from fragment
if ( tmp ) {
safe.removeChild( tmp );
}
// Reset defaultChecked for any radios and checkboxes
// about to be appended to the DOM in IE 6/7 (#8060)
if ( !jQuery.support.appendChecked ) {
jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked );
}
i = 0;
while ( (elem = nodes[ i++ ]) ) {
// #4087 - If origin and destination elements are the same, and this is
// that element, do not do anything
if ( selection && jQuery.inArray( elem, selection ) !== -1 ) {
continue;
}
contains = jQuery.contains( elem.ownerDocument, elem );
// Append to fragment
tmp = getAll( safe.appendChild( elem ), "script" );
// Preserve script evaluation history
if ( contains ) {
setGlobalEval( tmp );
}
// Capture executables
if ( scripts ) {
j = 0;
while ( (elem = tmp[ j++ ]) ) {
if ( rscriptType.test( elem.type || "" ) ) {
scripts.push( elem );
}
}
}
}
tmp = null;
return safe;
},
cleanData: function( elems, /* internal */ acceptData ) {
var elem, type, id, data,
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 ( typeof elem.removeAttribute !== core_strundefined ) {
elem.removeAttribute( internalKey );
} else {
elem[ internalKey ] = null;
}
core_deletedIds.push( id );
}
}
}
}
},
_evalUrl: function( url ) {
return jQuery.ajax({
url: url,
type: "GET",
dataType: "script",
async: false,
global: false,
"throws": true
});
}
});
jQuery.fn.extend({
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();
}
});
var iframe, getStyles, curCSS,
ralpha = /alpha\([^)]*\)/i,
ropacity = /opacity\s*=\s*([^)]*)/,
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" ];
// 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 ) {
// isHidden might be called from jQuery#filter function;
// in that case, element will be second argument
elem = el || elem;
return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem );
}
function showHide( elements, show ) {
var display, elem, hidden,
values = [],
index = 0,
length = elements.length;
for ( ; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
values[ index ] = jQuery._data( elem, "olddisplay" );
display = elem.style.display;
if ( show ) {
// Reset the inline display of this element to learn if it is
// being hidden by cascaded rules or not
if ( !values[ index ] && 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 {
if ( !values[ index ] ) {
hidden = isHidden( elem );
if ( display && display !== "none" || !hidden ) {
jQuery._data( elem, "olddisplay", hidden ? display : jQuery.css( elem, "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 ) {
var len, styles,
map = {},
i = 0;
if ( jQuery.isArray( name ) ) {
styles = getStyles( elem );
len = name.length;
for ( ; i < len; i++ ) {
map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles );
}
return map;
}
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 ) {
if ( typeof state === "boolean" ) {
return state ? this.show() : this.hide();
}
return this.each(function() {
if ( 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;
}
}
}
},
// Don't automatically add "px" to these possibly-unitless properties
cssNumber: {
"columnCount": true,
"fillOpacity": true,
"fontWeight": true,
"lineHeight": true,
"opacity": true,
"order": 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";
}
// Fixes #8908, it can be done more correctly by specifing setters in cssHooks,
// but it would mean to define eight (for every problematic property) identical functions
if ( !jQuery.support.clearCloneStyle && value === "" && name.indexOf("background") === 0 ) {
style[ name ] = "inherit";
}
// 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, extra, styles ) {
var num, val, 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, styles );
}
//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 ( extra === "" || extra ) {
num = parseFloat( val );
return extra === true || jQuery.isNumeric( num ) ? num || 0 : val;
}
return val;
}
});
// NOTE: we've included the "window" in window.getComputedStyle
// because jsdom on node.js will break without it.
if ( window.getComputedStyle ) {
getStyles = function( elem ) {
return window.getComputedStyle( elem, null );
};
curCSS = function( elem, name, _computed ) {
var width, minWidth, maxWidth,
computed = _computed || getStyles( elem ),
// getPropertyValue is only needed for .css('filter') in IE9, see #12537
ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined,
style = elem.style;
if ( computed ) {
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 ) ) {
// Remember the original values
width = style.width;
minWidth = style.minWidth;
maxWidth = style.maxWidth;
// Put in the new values to get a computed value out
style.minWidth = style.maxWidth = style.width = ret;
ret = computed.width;
// Revert the changed values
style.width = width;
style.minWidth = minWidth;
style.maxWidth = maxWidth;
}
}
return ret;
};
} else if ( document.documentElement.currentStyle ) {
getStyles = function( elem ) {
return elem.currentStyle;
};
curCSS = function( elem, name, _computed ) {
var left, rs, rsLeft,
computed = _computed || getStyles( elem ),
ret = computed ? computed[ name ] : undefined,
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;
rs = elem.runtimeStyle;
rsLeft = rs && rs.left;
// Put in the new values to get a computed value out
if ( rsLeft ) {
rs.left = elem.currentStyle.left;
}
style.left = name === "fontSize" ? "1em" : ret;
ret = style.pixelLeft + "px";
// Revert the changed values
style.left = left;
if ( rsLeft ) {
rs.left = rsLeft;
}
}
return ret === "" ? "auto" : ret;
};
}
function setPositiveNumber( elem, value, subtract ) {
var matches = rnumsplit.exec( value );
return matches ?
// Guard against undefined "subtract", e.g., when used as in cssHooks
Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) :
value;
}
function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) {
var i = extra === ( isBorderBox ? "border" : "content" ) ?
// If we already have the right measurement, avoid augmentation
4 :
// Otherwise initialize for horizontal or vertical properties
name === "width" ? 1 : 0,
val = 0;
for ( ; i < 4; i += 2 ) {
// both box models exclude margin, so add it if we want it
if ( extra === "margin" ) {
val += jQuery.css( elem, extra + cssExpand[ i ], true, styles );
}
if ( isBorderBox ) {
// border-box includes padding, so remove it if we want content
if ( extra === "content" ) {
val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
}
// at this point, extra isn't border nor margin, so remove border
if ( extra !== "margin" ) {
val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
}
} else {
// at this point, extra isn't content, so add padding
val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
// at this point, extra isn't content nor padding, so add border
if ( extra !== "padding" ) {
val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
}
}
}
return val;
}
function getWidthOrHeight( elem, name, extra ) {
// Start with offset property, which is equivalent to the border-box value
var valueIsBorderBox = true,
val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
styles = getStyles( elem ),
isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "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, styles );
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,
styles
)
) + "px";
}
// Try to determine the default display value of an element
function css_defaultDisplay( nodeName ) {
var doc = document,
display = elemdisplay[ nodeName ];
if ( !display ) {
display = actualDisplay( nodeName, doc );
// If the simple way fails, read from inside an iframe
if ( display === "none" || !display ) {
// Use the already-created iframe if possible
iframe = ( iframe ||
jQuery("<iframe frameborder='0' width='0' height='0'/>")
.css( "cssText", "display:block !important" )
).appendTo( doc.documentElement );
// Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse
doc = ( iframe[0].contentWindow || iframe[0].contentDocument ).document;
doc.write("<!doctype html><html><body>");
doc.close();
display = actualDisplay( nodeName, doc );
iframe.detach();
}
// Store the correct default display
elemdisplay[ nodeName ] = display;
}
return display;
}
// Called ONLY from within css_defaultDisplay
function actualDisplay( name, doc ) {
var elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ),
display = jQuery.css( elem[0], "display" );
elem.remove();
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
return elem.offsetWidth === 0 && rdisplayswap.test( jQuery.css( elem, "display" ) ) ?
jQuery.swap( elem, cssShow, function() {
return getWidthOrHeight( elem, name, extra );
}) :
getWidthOrHeight( elem, name, extra );
}
},
set: function( elem, value, extra ) {
var styles = extra && getStyles( elem );
return setPositiveNumber( elem, value, extra ?
augmentWidthOrHeight(
elem,
name,
extra,
jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box",
styles
) : 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 === "", then remove inline opacity #12685
if ( ( value >= 1 || value === "" ) &&
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 is no filter style applied in a css rule or unset inline opacity, we are done
if ( value === "" || 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 ) {
if ( 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" },
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 ) {
computed = curCSS( elem, prop );
// if curCSS returns percentage, fallback to offset
return rnumnonpx.test( computed ) ?
jQuery( elem ).position()[ prop ] + "px" :
computed;
}
}
};
});
}
});
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.hidden = function( elem ) {
// Support: Opera <= 12.12
// Opera reports offsetWidths and offsetHeights less than zero on some elements
return elem.offsetWidth <= 0 && elem.offsetHeight <= 0 ||
(!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none");
};
jQuery.expr.filters.visible = function( elem ) {
return !jQuery.expr.filters.hidden( elem );
};
}
// These hooks are used by animate to expand properties
jQuery.each({
margin: "",
padding: "",
border: "Width"
}, function( prefix, suffix ) {
jQuery.cssHooks[ prefix + suffix ] = {
expand: function( value ) {
var i = 0,
expanded = {},
// assumes a single number if not a string
parts = typeof value === "string" ? value.split(" ") : [ value ];
for ( ; 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,
rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i,
rsubmittable = /^(?:input|select|textarea|keygen)/i;
jQuery.fn.extend({
serialize: function() {
return jQuery.param( this.serializeArray() );
},
serializeArray: function() {
return this.map(function(){
// Can add propHook for "elements" to filter or add form elements
var elements = jQuery.prop( this, "elements" );
return elements ? jQuery.makeArray( elements ) : this;
})
.filter(function(){
var type = this.type;
// Use .is(":disabled") so that fieldset[disabled] works
return this.name && !jQuery( this ).is( ":disabled" ) &&
rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) &&
( this.checked || !manipulation_rcheckableType.test( type ) );
})
.map(function( i, elem ){
var val = jQuery( this ).val();
return val == null ?
null :
jQuery.isArray( val ) ?
jQuery.map( val, function( val ){
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 {
// Item is non-scalar (array or object), encode its numeric index.
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 );
}
}
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 ) {
return arguments.length > 0 ?
this.on( name, null, data, fn ) :
this.trigger( name );
};
});
jQuery.fn.extend({
hover: function( fnOver, fnOut ) {
return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
},
bind: function( types, data, fn ) {
return this.on( types, null, data, fn );
},
unbind: function( types, fn ) {
return this.off( types, null, fn );
},
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 );
}
});
var
// Document location
ajaxLocParts,
ajaxLocation,
ajax_nonce = jQuery.now(),
ajax_rquery = /\?/,
rhash = /#.*$/,
rts = /([?&])_=[^&]*/,
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 = /^\/\//,
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 = "*/".concat("*");
// #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,
i = 0,
dataTypes = dataTypeExpression.toLowerCase().match( core_rnotwhite ) || [];
if ( jQuery.isFunction( func ) ) {
// For each dataType in the dataTypeExpression
while ( (dataType = dataTypes[i++]) ) {
// Prepend if requested
if ( dataType[0] === "+" ) {
dataType = dataType.slice( 1 ) || "*";
(structure[ dataType ] = structure[ dataType ] || []).unshift( func );
// Otherwise append
} else {
(structure[ dataType ] = structure[ dataType ] || []).push( func );
}
}
}
};
}
// Base inspection function for prefilters and transports
function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) {
var inspected = {},
seekingTransport = ( structure === transports );
function inspect( dataType ) {
var selected;
inspected[ dataType ] = true;
jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) {
var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR );
if( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) {
options.dataTypes.unshift( dataTypeOrTransport );
inspect( dataTypeOrTransport );
return false;
} else if ( seekingTransport ) {
return !( selected = dataTypeOrTransport );
}
});
return selected;
}
return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" );
}
// A special extend for ajax options
// that takes "flat" options (not to be deep extended)
// Fixes #9887
function ajaxExtend( target, src ) {
var deep, key,
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 );
}
return target;
}
jQuery.fn.load = function( url, params, callback ) {
if ( typeof url !== "string" && _load ) {
return _load.apply( this, arguments );
}
var selector, response, type,
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";
}
// If we have elements to modify, make the request
if ( self.length > 0 ) {
jQuery.ajax({
url: url,
// if "type" variable is undefined, then "GET" method will be used
type: type,
dataType: "html",
data: params
}).done(function( responseText ) {
// Save response for use in complete callback
response = arguments;
self.html( selector ?
// If a selector was specified, locate the right elements in a dummy div
// Exclude scripts to avoid IE 'Permission Denied' errors
jQuery("<div>").append( jQuery.parseHTML( responseText ) ).find( selector ) :
// Otherwise use the full result
responseText );
}).complete( callback && function( jqXHR, status ) {
self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] );
});
}
return this;
};
// Attach a bunch of functions for handling common AJAX events
jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ){
jQuery.fn[ type ] = function( fn ){
return this.on( type, fn );
};
});
jQuery.extend({
// Counter for holding the number of active queries
active: 0,
// Last-Modified header cache for next request
lastModified: {},
etag: {},
ajaxSettings: {
url: ajaxLocation,
type: "GET",
isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
global: true,
processData: true,
async: true,
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
/*
timeout: 0,
data: null,
dataType: null,
username: null,
password: null,
cache: null,
throws: false,
traditional: false,
headers: {},
*/
accepts: {
"*": allTypes,
text: "text/plain",
html: "text/html",
xml: "application/xml, text/xml",
json: "application/json, text/javascript"
},
contents: {
xml: /xml/,
html: /html/,
json: /json/
},
responseFields: {
xml: "responseXML",
text: "responseText",
json: "responseJSON"
},
// Data converters
// Keys separate source (or catchall "*") and destination types with a single space
converters: {
// Convert anything to text
"* text": 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: {
url: true,
context: true
}
},
// 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 ) {
return settings ?
// Building a settings object
ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) :
// Extending ajaxSettings
ajaxExtend( jQuery.ajaxSettings, target );
},
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 // Cross-domain detection vars
parts,
// Loop variable
i,
// URL without anti-cache param
cacheURL,
// Response headers as string
responseHeadersString,
// timeout handle
timeoutTimer,
// To know if global events are to be dispatched
fireGlobals,
transport,
// Response headers
responseHeaders,
// Create the final options object
s = jQuery.ajaxSetup( {}, options ),
// Callbacks context
callbackContext = s.context || s,
// Context for global events is callbackContext if it is a DOM node or jQuery collection
globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.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,
// 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 == null ? null : match;
},
// Raw string
getAllResponseHeaders: function() {
return state === 2 ? responseHeadersString : null;
},
// Caches the header
setRequestHeader: function( name, value ) {
var lname = name.toLowerCase();
if ( !state ) {
name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
requestHeaders[ name ] = value;
}
return this;
},
// Overrides response content-type header
overrideMimeType: function( type ) {
if ( !state ) {
s.mimeType = type;
}
return this;
},
// Status-dependent callbacks
statusCode: function( map ) {
var code;
if ( map ) {
if ( state < 2 ) {
for ( code in map ) {
// Lazy-add the new callback in a way that preserves old ones
statusCode[ code ] = [ statusCode[ code ], map[ code ] ];
}
} else {
// Execute the appropriate callbacks
jqXHR.always( map[ jqXHR.status ] );
}
}
return this;
},
// Cancel the request
abort: function( statusText ) {
var finalText = statusText || strAbort;
if ( transport ) {
transport.abort( finalText );
}
done( 0, finalText );
return this;
}
};
// Attach deferreds
deferred.promise( jqXHR ).complete = completeDeferred.add;
jqXHR.success = jqXHR.done;
jqXHR.error = jqXHR.fail;
// Remove hash character (#7531: and string promotion)
// Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
// Handle falsy url in the settings object (#10093: consistency with old signature)
// We also use the url parameter if available
s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" );
// Alias method option to type as per ticket #12004
s.type = options.method || options.type || s.method || s.type;
// Extract dataTypes list
s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( core_rnotwhite ) || [""];
// 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;
// Watch for a new set of requests
if ( fireGlobals && jQuery.active++ === 0 ) {
jQuery.event.trigger("ajaxStart");
}
// Uppercase the type
s.type = s.type.toUpperCase();
// Determine if request has content
s.hasContent = !rnoContent.test( s.type );
// Save the URL in case we're toying with the If-Modified-Since
// and/or If-None-Match header later on
cacheURL = s.url;
// More options handling for requests with no content
if ( !s.hasContent ) {
// If data is available, append data to url
if ( s.data ) {
cacheURL = ( s.url += ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + s.data );
// #9682: remove data so that it's not used in an eventual retry
delete s.data;
}
// Add anti-cache in url if needed
if ( s.cache === false ) {
s.url = rts.test( cacheURL ) ?
// If there is already a '_' parameter, set its value
cacheURL.replace( rts, "$1_=" + ajax_nonce++ ) :
// Otherwise add one to the end
cacheURL + ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ajax_nonce++;
}
}
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
if ( jQuery.lastModified[ cacheURL ] ) {
jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] );
}
if ( jQuery.etag[ cacheURL ] ) {
jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] );
}
}
// 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 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;
}
}
}
// Callback for when everything is done
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;
// Determine if successful
isSuccess = status >= 200 && status < 300 || status === 304;
// Get response data
if ( responses ) {
response = ajaxHandleResponses( s, jqXHR, responses );
}
// Convert no matter what (that way responseXXX fields are always set)
response = ajaxConvert( s, response, jqXHR, isSuccess );
// If successful, handle type chaining
if ( isSuccess ) {
// 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[ cacheURL ] = modified;
}
modified = jqXHR.getResponseHeader("etag");
if ( modified ) {
jQuery.etag[ cacheURL ] = modified;
}
}
// if no content
if ( status === 204 || s.type === "HEAD" ) {
statusText = "nocontent";
// if not modified
} else if ( status === 304 ) {
statusText = "notmodified";
// If we have data, let's convert it
} else {
statusText = response.state;
success = response.data;
error = response.error;
isSuccess = !error;
}
} else {
// We extract error from statusText
// then normalize statusText and status for non-aborts
error = statusText;
if ( status || !statusText ) {
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( isSuccess ? "ajaxSuccess" : "ajaxError",
[ 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");
}
}
}
return jqXHR;
},
getJSON: function( url, data, callback ) {
return jQuery.get( url, data, callback, "json" );
},
getScript: function( url, callback ) {
return jQuery.get( url, undefined, callback, "script" );
}
});
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({
url: url,
type: method,
dataType: type,
data: data,
success: callback
});
};
});
/* Handles responses to an ajax request:
* - finds the right dataType (mediates between content-type and expected dataType)
* - returns the corresponding response
*/
function ajaxHandleResponses( s, jqXHR, responses ) {
var firstDataType, ct, finalDataType, type,
contents = s.contents,
dataTypes = s.dataTypes;
// 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
* Also sets the responseXXX fields on the jqXHR instance
*/
function ajaxConvert( s, response, jqXHR, isSuccess ) {
var conv2, current, conv, tmp, prev,
converters = {},
// Work with a copy of dataTypes in case we need to modify it for conversion
dataTypes = s.dataTypes.slice();
// Create converters map with lowercased keys
if ( dataTypes[ 1 ] ) {
for ( conv in s.converters ) {
converters[ conv.toLowerCase() ] = s.converters[ conv ];
}
}
current = dataTypes.shift();
// Convert to each sequential dataType
while ( current ) {
if ( s.responseFields[ current ] ) {
jqXHR[ s.responseFields[ current ] ] = response;
}
// Apply the dataFilter if provided
if ( !prev && isSuccess && s.dataFilter ) {
response = s.dataFilter( response, s.dataType );
}
prev = current;
current = dataTypes.shift();
if ( current ) {
// There's only work to do if current dataType is non-auto
if ( current === "*" ) {
current = prev;
// Convert response if prev dataType is non-auto and differs from current
} else 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.unshift( tmp[ 1 ] );
}
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 };
}
}
}
}
}
}
return { state: "success", data: response };
}
// Install script dataType
jQuery.ajaxSetup({
accepts: {
script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
},
contents: {
script: /(?:java|ecma)script/
},
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 || jQuery("head")[0] || document.documentElement;
return {
send: function( _, callback ) {
script = document.createElement("script");
script.async = true;
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 ( script.parentNode ) {
script.parentNode.removeChild( script );
}
// Dereference the script
script = null;
// Callback if not abort
if ( !isAbort ) {
callback( 200, "success" );
}
}
};
// Circumvent IE6 bugs with base elements (#2709 and #4378) by prepending
// Use native DOM manipulation to avoid our domManip AJAX trickery
head.insertBefore( script, head.firstChild );
},
abort: function() {
if ( script ) {
script.onload( undefined, true );
}
}
};
}
});
var oldCallbacks = [],
rjsonp = /(=)\?(?=&|$)|\?\?/;
// Default jsonp settings
jQuery.ajaxSetup({
jsonp: "callback",
jsonpCallback: function() {
var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( ajax_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,
jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ?
"url" :
typeof s.data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( s.data ) && "data"
);
// Handle iff the expected data type is "jsonp" or we have a parameter to set
if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) {
// Get callback name, remembering preexisting value associated with it
callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ?
s.jsonpCallback() :
s.jsonpCallback;
// Insert callback into url or form data
if ( jsonProp ) {
s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName );
} else if ( s.jsonp !== false ) {
s.url += ( ajax_rquery.test( s.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
overwritten = window[ callbackName ];
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";
}
});
var xhrCallbacks, xhrSupported,
xhrId = 0,
// #5280: Internet Explorer will keep connections alive if we don't abort on unload
xhrOnUnloadAbort = window.ActiveXObject && function() {
// Abort all pending requests
var key;
for ( key in xhrCallbacks ) {
xhrCallbacks[ key ]( undefined, true );
}
};
// 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
xhrSupported = jQuery.ajaxSettings.xhr();
jQuery.support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported );
xhrSupported = jQuery.support.ajax = !!xhrSupported;
// Create transport if the browser can provide an xhr
if ( xhrSupported ) {
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( err ) {}
// 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, responseHeaders, statusText, responses;
// 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 {
responses = {};
status = xhr.status;
responseHeaders = xhr.getAllResponseHeaders();
// When requesting binary data, IE6-9 will throw an exception
// on any attempt to access responseText (#11426)
if ( typeof xhr.responseText === "string" ) {
responses.text = xhr.responseText;
}
// Firefox throws an exception when accessing
// statusText for faulty cross-domain requests
try {
statusText = xhr.statusText;
} catch( e ) {
// We normalize with Webkit giving an empty statusText
statusText = "";
}
// Filter status for non standard behaviors
// If the request is local and we have data: assume a success
// (success with no data won't get notified, that's the best we
// can do given current implementations)
if ( !status && s.isLocal && !s.crossDomain ) {
status = responses.text ? 200 : 404;
// IE - #1450: sometimes returns 1223 when it should be 204
} else if ( status === 1223 ) {
status = 204;
}
}
}
} catch( firefoxAccessException ) {
if ( !isAbort ) {
complete( -1, firefoxAccessException );
}
}
// Call complete if needed
if ( responses ) {
complete( status, statusText, responses, responseHeaders );
}
};
if ( !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 );
} 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( undefined, true );
}
}
};
}
});
}
var fxNow, timerId,
rfxtypes = /^(?:toggle|show|hide)$/,
rfxnum = new RegExp( "^(?:([+-])=|)(" + core_pnum + ")([a-z%]*)$", "i" ),
rrun = /queueHooks$/,
animationPrefilters = [ defaultPrefilter ],
tweeners = {
"*": [function( prop, value ) {
var tween = this.createTween( prop, value ),
target = tween.cur(),
parts = rfxnum.exec( value ),
unit = parts && parts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ),
// Starting value computation is required for potential unit mismatches
start = ( jQuery.cssNumber[ prop ] || unit !== "px" && +target ) &&
rfxnum.exec( jQuery.css( tween.elem, prop ) ),
scale = 1,
maxIterations = 20;
if ( start && start[ 3 ] !== unit ) {
// Trust units reported by jQuery.css
unit = unit || start[ 3 ];
// Make sure we update the tween properties later on
parts = parts || [];
// Iteratively approximate from a nonzero starting point
start = +target || 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 );
}
// Update tween properties
if ( parts ) {
start = tween.start = +start || +target || 0;
tween.unit = unit;
// If a +=/-= token was provided, we're doing a relative animation
tween.end = parts[ 1 ] ?
start + ( parts[ 1 ] + 1 ) * parts[ 2 ] :
+parts[ 2 ];
}
return tween;
}]
};
// Animations created synchronously will run synchronously
function createFxNow() {
setTimeout(function() {
fxNow = undefined;
});
return ( fxNow = jQuery.now() );
}
function createTween( value, prop, animation ) {
var tween,
collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ),
index = 0,
length = collection.length;
for ( ; index < length; index++ ) {
if ( (tween = collection[ index ].call( animation, prop, value )) ) {
// we're done with this property
return tween;
}
}
}
function Animation( elem, properties, options ) {
var result,
stopped,
index = 0,
length = animationPrefilters.length,
deferred = jQuery.Deferred().always( function() {
// don't match elem in the :animated selector
delete tick.elem;
}),
tick = function() {
if ( stopped ) {
return false;
}
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 ) {
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;
if ( stopped ) {
return this;
}
stopped = true;
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;
}
}
jQuery.map( props, createTween, animation );
if ( jQuery.isFunction( animation.opts.start ) ) {
animation.opts.start.call( elem, animation );
}
jQuery.fx.timer(
jQuery.extend( tick, {
elem: elem,
anim: animation,
queue: animation.opts.queue
})
);
// 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 ) {
/* jshint validthis: true */
var prop, value, toggle, tween, hooks, oldfire,
anim = this,
orig = {},
style = elem.style,
hidden = elem.nodeType && isHidden( elem ),
dataShow = jQuery._data( elem, "fxshow" );
// 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.always(function() {
style.overflow = opts.overflow[ 0 ];
style.overflowX = opts.overflow[ 1 ];
style.overflowY = opts.overflow[ 2 ];
});
}
}
// show/hide pass
for ( prop in props ) {
value = props[ prop ];
if ( rfxtypes.exec( value ) ) {
delete props[ prop ];
toggle = toggle || value === "toggle";
if ( value === ( hidden ? "hide" : "show" ) ) {
continue;
}
orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop );
}
}
if ( !jQuery.isEmptyObject( orig ) ) {
if ( dataShow ) {
if ( "hidden" in dataShow ) {
hidden = dataShow.hidden;
}
} else {
dataShow = jQuery._data( elem, "fxshow", {} );
}
// 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" );
for ( prop in orig ) {
jQuery.style( elem, prop, orig[ prop ] );
}
});
for ( prop in orig ) {
tween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim );
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 an empty string as a 3rd 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, "" );
// 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;
}
}
}
};
// Support: IE <=9
// 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" ?
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, or finishing resolves immediately
if ( empty || jQuery._data( this, "finish" ) ) {
anim.stop( true );
}
};
doAnimation.finish = doAnimation;
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 );
}
});
},
finish: function( type ) {
if ( type !== false ) {
type = type || "fx";
}
return this.each(function() {
var index,
data = jQuery._data( this ),
queue = data[ type + "queue" ],
hooks = data[ type + "queueHooks" ],
timers = jQuery.timers,
length = queue ? queue.length : 0;
// enable finishing flag on private data
data.finish = true;
// empty the queue first
jQuery.queue( this, type, [] );
if ( hooks && hooks.stop ) {
hooks.stop.call( this, true );
}
// look for any active animations, and finish them
for ( index = timers.length; index--; ) {
if ( timers[ index ].elem === this && timers[ index ].queue === type ) {
timers[ index ].anim.stop( true );
timers.splice( index, 1 );
}
}
// look for any animations in the old queue and finish them
for ( index = 0; index < length; index++ ) {
if ( queue[ index ] && queue[ index ].finish ) {
queue[ index ].finish.call( this );
}
}
// turn off finishing flag
delete data.finish;
});
}
});
// 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 ) ) {
jQuery.fx.start();
}
};
jQuery.fx.interval = 13;
jQuery.fx.start = function() {
if ( !timerId ) {
timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval );
}
};
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;
};
}
jQuery.fn.offset = function( options ) {
if ( arguments.length ) {
return options === undefined ?
this :
this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}
var docElem, win,
box = { top: 0, left: 0 },
elem = this[ 0 ],
doc = elem && elem.ownerDocument;
if ( !doc ) {
return;
}
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 !== core_strundefined ) {
box = elem.getBoundingClientRect();
}
win = getWindow( doc );
return {
top: box.top + ( win.pageYOffset || docElem.scrollTop ) - ( docElem.clientTop || 0 ),
left: box.left + ( win.pageXOffset || docElem.scrollLeft ) - ( docElem.clientLeft || 0 )
};
};
jQuery.offset = {
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 offsetParent, offset,
parentOffset = { top: 0, left: 0 },
elem = this[ 0 ];
// fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is it's only offset parent
if ( jQuery.css( elem, "position" ) === "fixed" ) {
// we assume that getBoundingClientRect is available when computed position is fixed
offset = elem.getBoundingClientRect();
} else {
// Get *real* offsetParent
offsetParent = this.offsetParent();
// Get correct offsets
offset = this.offset();
if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) {
parentOffset = offsetParent.offset();
}
// Add offsetParent borders
parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true );
parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true );
}
// Subtract parent offsets and 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
return {
top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ),
left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true)
};
},
offsetParent: function() {
return this.map(function() {
var offsetParent = this.offsetParent || docElem;
while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position") === "static" ) ) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent || docElem;
});
}
});
// 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, extra ) :
// Set width or height on the element
jQuery.style( elem, type, value, extra );
}, type, chainable ? margin : undefined, chainable, null );
};
});
});
// Limit scope pollution from any deprecated API
// (function() {
// The number of elements contained in the matched element set
jQuery.fn.size = function() {
return this.length;
};
jQuery.fn.andSelf = jQuery.fn.addBack;
// })();
if ( typeof module === "object" && module && typeof module.exports === "object" ) {
// Expose jQuery as module.exports in loaders that implement the Node
// module pattern (including browserify). Do not create the global, since
// the user will be storing it themselves locally, and globals are frowned
// upon in the Node module world.
module.exports = jQuery;
} else {
// Otherwise expose jQuery to the global object as usual
window.jQuery = window.$ = jQuery;
// Register as a named AMD module, since jQuery can be concatenated with other
// files that may use define, but not via 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( "jquery", [], function () { return jQuery; } );
}
}
})( window );
/*!
* jQuery UI Core 1.10.3
* http://jqueryui.com
*
* Copyright 2013 jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*
* http://api.jqueryui.com/category/ui-core/
*/
(function( $, undefined ) {
var uuid = 0,
runiqueId = /^ui-id-\d+$/;
// $.ui might exist from components with no dependencies, e.g., $.ui.position
$.ui = $.ui || {};
$.extend( $.ui, {
version: "1.10.3",
keyCode: {
BACKSPACE: 8,
COMMA: 188,
DELETE: 46,
DOWN: 40,
END: 35,
ENTER: 13,
ESCAPE: 27,
HOME: 36,
LEFT: 37,
NUMPAD_ADD: 107,
NUMPAD_DECIMAL: 110,
NUMPAD_DIVIDE: 111,
NUMPAD_ENTER: 108,
NUMPAD_MULTIPLY: 106,
NUMPAD_SUBTRACT: 109,
PAGE_DOWN: 34,
PAGE_UP: 33,
PERIOD: 190,
RIGHT: 39,
SPACE: 32,
TAB: 9,
UP: 38
}
});
// plugins
$.fn.extend({
focus: (function( orig ) {
return function( delay, fn ) {
return typeof delay === "number" ?
this.each(function() {
var elem = this;
setTimeout(function() {
$( elem ).focus();
if ( fn ) {
fn.call( elem );
}
}, delay );
}) :
orig.apply( this, arguments );
};
})( $.fn.focus ),
scrollParent: function() {
var scrollParent;
if (($.ui.ie && (/(static|relative)/).test(this.css("position"))) || (/absolute/).test(this.css("position"))) {
scrollParent = this.parents().filter(function() {
return (/(relative|absolute|fixed)/).test($.css(this,"position")) && (/(auto|scroll)/).test($.css(this,"overflow")+$.css(this,"overflow-y")+$.css(this,"overflow-x"));
}).eq(0);
} else {
scrollParent = this.parents().filter(function() {
return (/(auto|scroll)/).test($.css(this,"overflow")+$.css(this,"overflow-y")+$.css(this,"overflow-x"));
}).eq(0);
}
return (/fixed/).test(this.css("position")) || !scrollParent.length ? $(document) : scrollParent;
},
zIndex: function( zIndex ) {
if ( zIndex !== undefined ) {
return this.css( "zIndex", zIndex );
}
if ( this.length ) {
var elem = $( this[ 0 ] ), position, value;
while ( elem.length && elem[ 0 ] !== document ) {
// Ignore z-index if position is set to a value where z-index is ignored by the browser
// This makes behavior of this function consistent across browsers
// WebKit always returns auto if the element is positioned
position = elem.css( "position" );
if ( position === "absolute" || position === "relative" || position === "fixed" ) {
// IE returns 0 when zIndex is not specified
// other browsers return a string
// we ignore the case of nested elements with an explicit value of 0
// <div style="z-index: -10;"><div style="z-index: 0;"></div></div>
value = parseInt( elem.css( "zIndex" ), 10 );
if ( !isNaN( value ) && value !== 0 ) {
return value;
}
}
elem = elem.parent();
}
}
return 0;
},
uniqueId: function() {
return this.each(function() {
if ( !this.id ) {
this.id = "ui-id-" + (++uuid);
}
});
},
removeUniqueId: function() {
return this.each(function() {
if ( runiqueId.test( this.id ) ) {
$( this ).removeAttr( "id" );
}
});
}
});
// selectors
function focusable( element, isTabIndexNotNaN ) {
var map, mapName, img,
nodeName = element.nodeName.toLowerCase();
if ( "area" === nodeName ) {
map = element.parentNode;
mapName = map.name;
if ( !element.href || !mapName || map.nodeName.toLowerCase() !== "map" ) {
return false;
}
img = $( "img[usemap=#" + mapName + "]" )[0];
return !!img && visible( img );
}
return ( /input|select|textarea|button|object/.test( nodeName ) ?
!element.disabled :
"a" === nodeName ?
element.href || isTabIndexNotNaN :
isTabIndexNotNaN) &&
// the element and all of its ancestors must be visible
visible( element );
}
function visible( element ) {
return $.expr.filters.visible( element ) &&
!$( element ).parents().addBack().filter(function() {
return $.css( this, "visibility" ) === "hidden";
}).length;
}
$.extend( $.expr[ ":" ], {
data: $.expr.createPseudo ?
$.expr.createPseudo(function( dataName ) {
return function( elem ) {
return !!$.data( elem, dataName );
};
}) :
// support: jQuery <1.8
function( elem, i, match ) {
return !!$.data( elem, match[ 3 ] );
},
focusable: function( element ) {
return focusable( element, !isNaN( $.attr( element, "tabindex" ) ) );
},
tabbable: function( element ) {
var tabIndex = $.attr( element, "tabindex" ),
isTabIndexNaN = isNaN( tabIndex );
return ( isTabIndexNaN || tabIndex >= 0 ) && focusable( element, !isTabIndexNaN );
}
});
// support: jQuery <1.8
if ( !$( "<a>" ).outerWidth( 1 ).jquery ) {
$.each( [ "Width", "Height" ], function( i, name ) {
var side = name === "Width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ],
type = name.toLowerCase(),
orig = {
innerWidth: $.fn.innerWidth,
innerHeight: $.fn.innerHeight,
outerWidth: $.fn.outerWidth,
outerHeight: $.fn.outerHeight
};
function reduce( elem, size, border, margin ) {
$.each( side, function() {
size -= parseFloat( $.css( elem, "padding" + this ) ) || 0;
if ( border ) {
size -= parseFloat( $.css( elem, "border" + this + "Width" ) ) || 0;
}
if ( margin ) {
size -= parseFloat( $.css( elem, "margin" + this ) ) || 0;
}
});
return size;
}
$.fn[ "inner" + name ] = function( size ) {
if ( size === undefined ) {
return orig[ "inner" + name ].call( this );
}
return this.each(function() {
$( this ).css( type, reduce( this, size ) + "px" );
});
};
$.fn[ "outer" + name] = function( size, margin ) {
if ( typeof size !== "number" ) {
return orig[ "outer" + name ].call( this, size );
}
return this.each(function() {
$( this).css( type, reduce( this, size, true, margin ) + "px" );
});
};
});
}
// support: jQuery <1.8
if ( !$.fn.addBack ) {
$.fn.addBack = function( selector ) {
return this.add( selector == null ?
this.prevObject : this.prevObject.filter( selector )
);
};
}
// support: jQuery 1.6.1, 1.6.2 (http://bugs.jquery.com/ticket/9413)
if ( $( "<a>" ).data( "a-b", "a" ).removeData( "a-b" ).data( "a-b" ) ) {
$.fn.removeData = (function( removeData ) {
return function( key ) {
if ( arguments.length ) {
return removeData.call( this, $.camelCase( key ) );
} else {
return removeData.call( this );
}
};
})( $.fn.removeData );
}
// deprecated
$.ui.ie = !!/msie [\w.]+/.exec( navigator.userAgent.toLowerCase() );
$.support.selectstart = "onselectstart" in document.createElement( "div" );
$.fn.extend({
disableSelection: function() {
return this.bind( ( $.support.selectstart ? "selectstart" : "mousedown" ) +
".ui-disableSelection", function( event ) {
event.preventDefault();
});
},
enableSelection: function() {
return this.unbind( ".ui-disableSelection" );
}
});
$.extend( $.ui, {
// $.ui.plugin is deprecated. Use $.widget() extensions instead.
plugin: {
add: function( module, option, set ) {
var i,
proto = $.ui[ module ].prototype;
for ( i in set ) {
proto.plugins[ i ] = proto.plugins[ i ] || [];
proto.plugins[ i ].push( [ option, set[ i ] ] );
}
},
call: function( instance, name, args ) {
var i,
set = instance.plugins[ name ];
if ( !set || !instance.element[ 0 ].parentNode || instance.element[ 0 ].parentNode.nodeType === 11 ) {
return;
}
for ( i = 0; i < set.length; i++ ) {
if ( instance.options[ set[ i ][ 0 ] ] ) {
set[ i ][ 1 ].apply( instance.element, args );
}
}
}
},
// only used by resizable
hasScroll: function( el, a ) {
//If overflow is hidden, the element might have extra content, but the user wants to hide it
if ( $( el ).css( "overflow" ) === "hidden") {
return false;
}
var scroll = ( a && a === "left" ) ? "scrollLeft" : "scrollTop",
has = false;
if ( el[ scroll ] > 0 ) {
return true;
}
// TODO: determine which cases actually cause this to happen
// if the element doesn't have the scroll set, see if it's possible to
// set the scroll
el[ scroll ] = 1;
has = ( el[ scroll ] > 0 );
el[ scroll ] = 0;
return has;
}
});
})( jQuery );
/*!
* jQuery UI Widget 1.10.3
* http://jqueryui.com
*
* Copyright 2013 jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*
* http://api.jqueryui.com/jQuery.widget/
*/
(function( $, undefined ) {
var uuid = 0,
slice = Array.prototype.slice,
_cleanData = $.cleanData;
$.cleanData = function( elems ) {
for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
try {
$( elem ).triggerHandler( "remove" );
// http://bugs.jquery.com/ticket/8235
} catch( e ) {}
}
_cleanData( elems );
};
$.widget = function( name, base, prototype ) {
var fullName, existingConstructor, constructor, basePrototype,
// proxiedPrototype allows the provided prototype to remain unmodified
// so that it can be used as a mixin for multiple widgets (#8876)
proxiedPrototype = {},
namespace = name.split( "." )[ 0 ];
name = name.split( "." )[ 1 ];
fullName = namespace + "-" + name;
if ( !prototype ) {
prototype = base;
base = $.Widget;
}
// create selector for plugin
$.expr[ ":" ][ fullName.toLowerCase() ] = function( elem ) {
return !!$.data( elem, fullName );
};
$[ namespace ] = $[ namespace ] || {};
existingConstructor = $[ namespace ][ name ];
constructor = $[ namespace ][ name ] = function( options, element ) {
// allow instantiation without "new" keyword
if ( !this._createWidget ) {
return new constructor( options, element );
}
// allow instantiation without initializing for simple inheritance
// must use "new" keyword (the code above always passes args)
if ( arguments.length ) {
this._createWidget( options, element );
}
};
// extend with the existing constructor to carry over any static properties
$.extend( constructor, existingConstructor, {
version: prototype.version,
// copy the object used to create the prototype in case we need to
// redefine the widget later
_proto: $.extend( {}, prototype ),
// track widgets that inherit from this widget in case this widget is
// redefined after a widget inherits from it
_childConstructors: []
});
basePrototype = new base();
// we need to make the options hash a property directly on the new instance
// otherwise we'll modify the options hash on the prototype that we're
// inheriting from
basePrototype.options = $.widget.extend( {}, basePrototype.options );
$.each( prototype, function( prop, value ) {
if ( !$.isFunction( value ) ) {
proxiedPrototype[ prop ] = value;
return;
}
proxiedPrototype[ prop ] = (function() {
var _super = function() {
return base.prototype[ prop ].apply( this, arguments );
},
_superApply = function( args ) {
return base.prototype[ prop ].apply( this, args );
};
return function() {
var __super = this._super,
__superApply = this._superApply,
returnValue;
this._super = _super;
this._superApply = _superApply;
returnValue = value.apply( this, arguments );
this._super = __super;
this._superApply = __superApply;
return returnValue;
};
})();
});
constructor.prototype = $.widget.extend( basePrototype, {
// TODO: remove support for widgetEventPrefix
// always use the name + a colon as the prefix, e.g., draggable:start
// don't prefix for widgets that aren't DOM-based
widgetEventPrefix: existingConstructor ? basePrototype.widgetEventPrefix : name
}, proxiedPrototype, {
constructor: constructor,
namespace: namespace,
widgetName: name,
widgetFullName: fullName
});
// If this widget is being redefined then we need to find all widgets that
// are inheriting from it and redefine all of them so that they inherit from
// the new version of this widget. We're essentially trying to replace one
// level in the prototype chain.
if ( existingConstructor ) {
$.each( existingConstructor._childConstructors, function( i, child ) {
var childPrototype = child.prototype;
// redefine the child widget using the same prototype that was
// originally used, but inherit from the new version of the base
$.widget( childPrototype.namespace + "." + childPrototype.widgetName, constructor, child._proto );
});
// remove the list of existing child constructors from the old constructor
// so the old child constructors can be garbage collected
delete existingConstructor._childConstructors;
} else {
base._childConstructors.push( constructor );
}
$.widget.bridge( name, constructor );
};
$.widget.extend = function( target ) {
var input = slice.call( arguments, 1 ),
inputIndex = 0,
inputLength = input.length,
key,
value;
for ( ; inputIndex < inputLength; inputIndex++ ) {
for ( key in input[ inputIndex ] ) {
value = input[ inputIndex ][ key ];
if ( input[ inputIndex ].hasOwnProperty( key ) && value !== undefined ) {
// Clone objects
if ( $.isPlainObject( value ) ) {
target[ key ] = $.isPlainObject( target[ key ] ) ?
$.widget.extend( {}, target[ key ], value ) :
// Don't extend strings, arrays, etc. with objects
$.widget.extend( {}, value );
// Copy everything else by reference
} else {
target[ key ] = value;
}
}
}
}
return target;
};
$.widget.bridge = function( name, object ) {
var fullName = object.prototype.widgetFullName || name;
$.fn[ name ] = function( options ) {
var isMethodCall = typeof options === "string",
args = slice.call( arguments, 1 ),
returnValue = this;
// allow multiple hashes to be passed on init
options = !isMethodCall && args.length ?
$.widget.extend.apply( null, [ options ].concat(args) ) :
options;
if ( isMethodCall ) {
this.each(function() {
var methodValue,
instance = $.data( this, fullName );
if ( !instance ) {
return $.error( "cannot call methods on " + name + " prior to initialization; " +
"attempted to call method '" + options + "'" );
}
if ( !$.isFunction( instance[options] ) || options.charAt( 0 ) === "_" ) {
return $.error( "no such method '" + options + "' for " + name + " widget instance" );
}
methodValue = instance[ options ].apply( instance, args );
if ( methodValue !== instance && methodValue !== undefined ) {
returnValue = methodValue && methodValue.jquery ?
returnValue.pushStack( methodValue.get() ) :
methodValue;
return false;
}
});
} else {
this.each(function() {
var instance = $.data( this, fullName );
if ( instance ) {
instance.option( options || {} )._init();
} else {
$.data( this, fullName, new object( options, this ) );
}
});
}
return returnValue;
};
};
$.Widget = function( /* options, element */ ) {};
$.Widget._childConstructors = [];
$.Widget.prototype = {
widgetName: "widget",
widgetEventPrefix: "",
defaultElement: "<div>",
options: {
disabled: false,
// callbacks
create: null
},
_createWidget: function( options, element ) {
element = $( element || this.defaultElement || this )[ 0 ];
this.element = $( element );
this.uuid = uuid++;
this.eventNamespace = "." + this.widgetName + this.uuid;
this.options = $.widget.extend( {},
this.options,
this._getCreateOptions(),
options );
this.bindings = $();
this.hoverable = $();
this.focusable = $();
if ( element !== this ) {
$.data( element, this.widgetFullName, this );
this._on( true, this.element, {
remove: function( event ) {
if ( event.target === element ) {
this.destroy();
}
}
});
this.document = $( element.style ?
// element within the document
element.ownerDocument :
// element is window or document
element.document || element );
this.window = $( this.document[0].defaultView || this.document[0].parentWindow );
}
this._create();
this._trigger( "create", null, this._getCreateEventData() );
this._init();
},
_getCreateOptions: $.noop,
_getCreateEventData: $.noop,
_create: $.noop,
_init: $.noop,
destroy: function() {
this._destroy();
// we can probably remove the unbind calls in 2.0
// all event bindings should go through this._on()
this.element
.unbind( this.eventNamespace )
// 1.9 BC for #7810
// TODO remove dual storage
.removeData( this.widgetName )
.removeData( this.widgetFullName )
// support: jquery <1.6.3
// http://bugs.jquery.com/ticket/9413
.removeData( $.camelCase( this.widgetFullName ) );
this.widget()
.unbind( this.eventNamespace )
.removeAttr( "aria-disabled" )
.removeClass(
this.widgetFullName + "-disabled " +
"ui-state-disabled" );
// clean up events and states
this.bindings.unbind( this.eventNamespace );
this.hoverable.removeClass( "ui-state-hover" );
this.focusable.removeClass( "ui-state-focus" );
},
_destroy: $.noop,
widget: function() {
return this.element;
},
option: function( key, value ) {
var options = key,
parts,
curOption,
i;
if ( arguments.length === 0 ) {
// don't return a reference to the internal hash
return $.widget.extend( {}, this.options );
}
if ( typeof key === "string" ) {
// handle nested keys, e.g., "foo.bar" => { foo: { bar: ___ } }
options = {};
parts = key.split( "." );
key = parts.shift();
if ( parts.length ) {
curOption = options[ key ] = $.widget.extend( {}, this.options[ key ] );
for ( i = 0; i < parts.length - 1; i++ ) {
curOption[ parts[ i ] ] = curOption[ parts[ i ] ] || {};
curOption = curOption[ parts[ i ] ];
}
key = parts.pop();
if ( value === undefined ) {
return curOption[ key ] === undefined ? null : curOption[ key ];
}
curOption[ key ] = value;
} else {
if ( value === undefined ) {
return this.options[ key ] === undefined ? null : this.options[ key ];
}
options[ key ] = value;
}
}
this._setOptions( options );
return this;
},
_setOptions: function( options ) {
var key;
for ( key in options ) {
this._setOption( key, options[ key ] );
}
return this;
},
_setOption: function( key, value ) {
this.options[ key ] = value;
if ( key === "disabled" ) {
this.widget()
.toggleClass( this.widgetFullName + "-disabled ui-state-disabled", !!value )
.attr( "aria-disabled", value );
this.hoverable.removeClass( "ui-state-hover" );
this.focusable.removeClass( "ui-state-focus" );
}
return this;
},
enable: function() {
return this._setOption( "disabled", false );
},
disable: function() {
return this._setOption( "disabled", true );
},
_on: function( suppressDisabledCheck, element, handlers ) {
var delegateElement,
instance = this;
// no suppressDisabledCheck flag, shuffle arguments
if ( typeof suppressDisabledCheck !== "boolean" ) {
handlers = element;
element = suppressDisabledCheck;
suppressDisabledCheck = false;
}
// no element argument, shuffle and use this.element
if ( !handlers ) {
handlers = element;
element = this.element;
delegateElement = this.widget();
} else {
// accept selectors, DOM elements
element = delegateElement = $( element );
this.bindings = this.bindings.add( element );
}
$.each( handlers, function( event, handler ) {
function handlerProxy() {
// allow widgets to customize the disabled handling
// - disabled as an array instead of boolean
// - disabled class as method for disabling individual parts
if ( !suppressDisabledCheck &&
( instance.options.disabled === true ||
$( this ).hasClass( "ui-state-disabled" ) ) ) {
return;
}
return ( typeof handler === "string" ? instance[ handler ] : handler )
.apply( instance, arguments );
}
// copy the guid so direct unbinding works
if ( typeof handler !== "string" ) {
handlerProxy.guid = handler.guid =
handler.guid || handlerProxy.guid || $.guid++;
}
var match = event.match( /^(\w+)\s*(.*)$/ ),
eventName = match[1] + instance.eventNamespace,
selector = match[2];
if ( selector ) {
delegateElement.delegate( selector, eventName, handlerProxy );
} else {
element.bind( eventName, handlerProxy );
}
});
},
_off: function( element, eventName ) {
eventName = (eventName || "").split( " " ).join( this.eventNamespace + " " ) + this.eventNamespace;
element.unbind( eventName ).undelegate( eventName );
},
_delay: function( handler, delay ) {
function handlerProxy() {
return ( typeof handler === "string" ? instance[ handler ] : handler )
.apply( instance, arguments );
}
var instance = this;
return setTimeout( handlerProxy, delay || 0 );
},
_hoverable: function( element ) {
this.hoverable = this.hoverable.add( element );
this._on( element, {
mouseenter: function( event ) {
$( event.currentTarget ).addClass( "ui-state-hover" );
},
mouseleave: function( event ) {
$( event.currentTarget ).removeClass( "ui-state-hover" );
}
});
},
_focusable: function( element ) {
this.focusable = this.focusable.add( element );
this._on( element, {
focusin: function( event ) {
$( event.currentTarget ).addClass( "ui-state-focus" );
},
focusout: function( event ) {
$( event.currentTarget ).removeClass( "ui-state-focus" );
}
});
},
_trigger: function( type, event, data ) {
var prop, orig,
callback = this.options[ type ];
data = data || {};
event = $.Event( event );
event.type = ( type === this.widgetEventPrefix ?
type :
this.widgetEventPrefix + type ).toLowerCase();
// the original event may come from any element
// so we need to reset the target on the new event
event.target = this.element[ 0 ];
// copy original event properties over to the new event
orig = event.originalEvent;
if ( orig ) {
for ( prop in orig ) {
if ( !( prop in event ) ) {
event[ prop ] = orig[ prop ];
}
}
}
this.element.trigger( event, data );
return !( $.isFunction( callback ) &&
callback.apply( this.element[0], [ event ].concat( data ) ) === false ||
event.isDefaultPrevented() );
}
};
$.each( { show: "fadeIn", hide: "fadeOut" }, function( method, defaultEffect ) {
$.Widget.prototype[ "_" + method ] = function( element, options, callback ) {
if ( typeof options === "string" ) {
options = { effect: options };
}
var hasOptions,
effectName = !options ?
method :
options === true || typeof options === "number" ?
defaultEffect :
options.effect || defaultEffect;
options = options || {};
if ( typeof options === "number" ) {
options = { duration: options };
}
hasOptions = !$.isEmptyObject( options );
options.complete = callback;
if ( options.delay ) {
element.delay( options.delay );
}
if ( hasOptions && $.effects && $.effects.effect[ effectName ] ) {
element[ method ]( options );
} else if ( effectName !== method && element[ effectName ] ) {
element[ effectName ]( options.duration, options.easing, callback );
} else {
element.queue(function( next ) {
$( this )[ method ]();
if ( callback ) {
callback.call( element[ 0 ] );
}
next();
});
}
};
});
})( jQuery );
d3 = function() {
var d3 = {
version: "3.3.9"
};
if (!Date.now) Date.now = function() {
return +new Date();
};
var d3_arraySlice = [].slice, d3_array = function(list) {
return d3_arraySlice.call(list);
};
var d3_document = document, d3_documentElement = d3_document.documentElement, d3_window = window;
try {
d3_array(d3_documentElement.childNodes)[0].nodeType;
} catch (e) {
d3_array = function(list) {
var i = list.length, array = new Array(i);
while (i--) array[i] = list[i];
return array;
};
}
try {
d3_document.createElement("div").style.setProperty("opacity", 0, "");
} catch (error) {
var d3_element_prototype = d3_window.Element.prototype, d3_element_setAttribute = d3_element_prototype.setAttribute, d3_element_setAttributeNS = d3_element_prototype.setAttributeNS, d3_style_prototype = d3_window.CSSStyleDeclaration.prototype, d3_style_setProperty = d3_style_prototype.setProperty;
d3_element_prototype.setAttribute = function(name, value) {
d3_element_setAttribute.call(this, name, value + "");
};
d3_element_prototype.setAttributeNS = function(space, local, value) {
d3_element_setAttributeNS.call(this, space, local, value + "");
};
d3_style_prototype.setProperty = function(name, value, priority) {
d3_style_setProperty.call(this, name, value + "", priority);
};
}
d3.ascending = function(a, b) {
return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN;
};
d3.descending = function(a, b) {
return b < a ? -1 : b > a ? 1 : b >= a ? 0 : NaN;
};
d3.min = function(array, f) {
var i = -1, n = array.length, a, b;
if (arguments.length === 1) {
while (++i < n && !((a = array[i]) != null && a <= a)) a = undefined;
while (++i < n) if ((b = array[i]) != null && a > b) a = b;
} else {
while (++i < n && !((a = f.call(array, array[i], i)) != null && a <= a)) a = undefined;
while (++i < n) if ((b = f.call(array, array[i], i)) != null && a > b) a = b;
}
return a;
};
d3.max = function(array, f) {
var i = -1, n = array.length, a, b;
if (arguments.length === 1) {
while (++i < n && !((a = array[i]) != null && a <= a)) a = undefined;
while (++i < n) if ((b = array[i]) != null && b > a) a = b;
} else {
while (++i < n && !((a = f.call(array, array[i], i)) != null && a <= a)) a = undefined;
while (++i < n) if ((b = f.call(array, array[i], i)) != null && b > a) a = b;
}
return a;
};
d3.extent = function(array, f) {
var i = -1, n = array.length, a, b, c;
if (arguments.length === 1) {
while (++i < n && !((a = c = array[i]) != null && a <= a)) a = c = undefined;
while (++i < n) if ((b = array[i]) != null) {
if (a > b) a = b;
if (c < b) c = b;
}
} else {
while (++i < n && !((a = c = f.call(array, array[i], i)) != null && a <= a)) a = undefined;
while (++i < n) if ((b = f.call(array, array[i], i)) != null) {
if (a > b) a = b;
if (c < b) c = b;
}
}
return [ a, c ];
};
d3.sum = function(array, f) {
var s = 0, n = array.length, a, i = -1;
if (arguments.length === 1) {
while (++i < n) if (!isNaN(a = +array[i])) s += a;
} else {
while (++i < n) if (!isNaN(a = +f.call(array, array[i], i))) s += a;
}
return s;
};
function d3_number(x) {
return x != null && !isNaN(x);
}
d3.mean = function(array, f) {
var n = array.length, a, m = 0, i = -1, j = 0;
if (arguments.length === 1) {
while (++i < n) if (d3_number(a = array[i])) m += (a - m) / ++j;
} else {
while (++i < n) if (d3_number(a = f.call(array, array[i], i))) m += (a - m) / ++j;
}
return j ? m : undefined;
};
d3.quantile = function(values, p) {
var H = (values.length - 1) * p + 1, h = Math.floor(H), v = +values[h - 1], e = H - h;
return e ? v + e * (values[h] - v) : v;
};
d3.median = function(array, f) {
if (arguments.length > 1) array = array.map(f);
array = array.filter(d3_number);
return array.length ? d3.quantile(array.sort(d3.ascending), .5) : undefined;
};
d3.bisector = function(f) {
return {
left: function(a, x, lo, hi) {
if (arguments.length < 3) lo = 0;
if (arguments.length < 4) hi = a.length;
while (lo < hi) {
var mid = lo + hi >>> 1;
if (f.call(a, a[mid], mid) < x) lo = mid + 1; else hi = mid;
}
return lo;
},
right: function(a, x, lo, hi) {
if (arguments.length < 3) lo = 0;
if (arguments.length < 4) hi = a.length;
while (lo < hi) {
var mid = lo + hi >>> 1;
if (x < f.call(a, a[mid], mid)) hi = mid; else lo = mid + 1;
}
return lo;
}
};
};
var d3_bisector = d3.bisector(function(d) {
return d;
});
d3.bisectLeft = d3_bisector.left;
d3.bisect = d3.bisectRight = d3_bisector.right;
d3.shuffle = function(array) {
var m = array.length, t, i;
while (m) {
i = Math.random() * m-- | 0;
t = array[m], array[m] = array[i], array[i] = t;
}
return array;
};
d3.permute = function(array, indexes) {
var i = indexes.length, permutes = new Array(i);
while (i--) permutes[i] = array[indexes[i]];
return permutes;
};
d3.pairs = function(array) {
var i = 0, n = array.length - 1, p0, p1 = array[0], pairs = new Array(n < 0 ? 0 : n);
while (i < n) pairs[i] = [ p0 = p1, p1 = array[++i] ];
return pairs;
};
d3.zip = function() {
if (!(n = arguments.length)) return [];
for (var i = -1, m = d3.min(arguments, d3_zipLength), zips = new Array(m); ++i < m; ) {
for (var j = -1, n, zip = zips[i] = new Array(n); ++j < n; ) {
zip[j] = arguments[j][i];
}
}
return zips;
};
function d3_zipLength(d) {
return d.length;
}
d3.transpose = function(matrix) {
return d3.zip.apply(d3, matrix);
};
d3.keys = function(map) {
var keys = [];
for (var key in map) keys.push(key);
return keys;
};
d3.values = function(map) {
var values = [];
for (var key in map) values.push(map[key]);
return values;
};
d3.entries = function(map) {
var entries = [];
for (var key in map) entries.push({
key: key,
value: map[key]
});
return entries;
};
d3.merge = function(arrays) {
var n = arrays.length, m, i = -1, j = 0, merged, array;
while (++i < n) j += arrays[i].length;
merged = new Array(j);
while (--n >= 0) {
array = arrays[n];
m = array.length;
while (--m >= 0) {
merged[--j] = array[m];
}
}
return merged;
};
var abs = Math.abs;
d3.range = function(start, stop, step) {
if (arguments.length < 3) {
step = 1;
if (arguments.length < 2) {
stop = start;
start = 0;
}
}
if ((stop - start) / step === Infinity) throw new Error("infinite range");
var range = [], k = d3_range_integerScale(abs(step)), i = -1, j;
start *= k, stop *= k, step *= k;
if (step < 0) while ((j = start + step * ++i) > stop) range.push(j / k); else while ((j = start + step * ++i) < stop) range.push(j / k);
return range;
};
function d3_range_integerScale(x) {
var k = 1;
while (x * k % 1) k *= 10;
return k;
}
function d3_class(ctor, properties) {
try {
for (var key in properties) {
Object.defineProperty(ctor.prototype, key, {
value: properties[key],
enumerable: false
});
}
} catch (e) {
ctor.prototype = properties;
}
}
d3.map = function(object) {
var map = new d3_Map();
if (object instanceof d3_Map) object.forEach(function(key, value) {
map.set(key, value);
}); else for (var key in object) map.set(key, object[key]);
return map;
};
function d3_Map() {}
d3_class(d3_Map, {
has: function(key) {
return d3_map_prefix + key in this;
},
get: function(key) {
return this[d3_map_prefix + key];
},
set: function(key, value) {
return this[d3_map_prefix + key] = value;
},
remove: function(key) {
key = d3_map_prefix + key;
return key in this && delete this[key];
},
keys: function() {
var keys = [];
this.forEach(function(key) {
keys.push(key);
});
return keys;
},
values: function() {
var values = [];
this.forEach(function(key, value) {
values.push(value);
});
return values;
},
entries: function() {
var entries = [];
this.forEach(function(key, value) {
entries.push({
key: key,
value: value
});
});
return entries;
},
forEach: function(f) {
for (var key in this) {
if (key.charCodeAt(0) === d3_map_prefixCode) {
f.call(this, key.substring(1), this[key]);
}
}
}
});
var d3_map_prefix = "\x00", d3_map_prefixCode = d3_map_prefix.charCodeAt(0);
d3.nest = function() {
var nest = {}, keys = [], sortKeys = [], sortValues, rollup;
function map(mapType, array, depth) {
if (depth >= keys.length) return rollup ? rollup.call(nest, array) : sortValues ? array.sort(sortValues) : array;
var i = -1, n = array.length, key = keys[depth++], keyValue, object, setter, valuesByKey = new d3_Map(), values;
while (++i < n) {
if (values = valuesByKey.get(keyValue = key(object = array[i]))) {
values.push(object);
} else {
valuesByKey.set(keyValue, [ object ]);
}
}
if (mapType) {
object = mapType();
setter = function(keyValue, values) {
object.set(keyValue, map(mapType, values, depth));
};
} else {
object = {};
setter = function(keyValue, values) {
object[keyValue] = map(mapType, values, depth);
};
}
valuesByKey.forEach(setter);
return object;
}
function entries(map, depth) {
if (depth >= keys.length) return map;
var array = [], sortKey = sortKeys[depth++];
map.forEach(function(key, keyMap) {
array.push({
key: key,
values: entries(keyMap, depth)
});
});
return sortKey ? array.sort(function(a, b) {
return sortKey(a.key, b.key);
}) : array;
}
nest.map = function(array, mapType) {
return map(mapType, array, 0);
};
nest.entries = function(array) {
return entries(map(d3.map, array, 0), 0);
};
nest.key = function(d) {
keys.push(d);
return nest;
};
nest.sortKeys = function(order) {
sortKeys[keys.length - 1] = order;
return nest;
};
nest.sortValues = function(order) {
sortValues = order;
return nest;
};
nest.rollup = function(f) {
rollup = f;
return nest;
};
return nest;
};
d3.set = function(array) {
var set = new d3_Set();
if (array) for (var i = 0, n = array.length; i < n; ++i) set.add(array[i]);
return set;
};
function d3_Set() {}
d3_class(d3_Set, {
has: function(value) {
return d3_map_prefix + value in this;
},
add: function(value) {
this[d3_map_prefix + value] = true;
return value;
},
remove: function(value) {
value = d3_map_prefix + value;
return value in this && delete this[value];
},
values: function() {
var values = [];
this.forEach(function(value) {
values.push(value);
});
return values;
},
forEach: function(f) {
for (var value in this) {
if (value.charCodeAt(0) === d3_map_prefixCode) {
f.call(this, value.substring(1));
}
}
}
});
d3.behavior = {};
d3.rebind = function(target, source) {
var i = 1, n = arguments.length, method;
while (++i < n) target[method = arguments[i]] = d3_rebind(target, source, source[method]);
return target;
};
function d3_rebind(target, source, method) {
return function() {
var value = method.apply(source, arguments);
return value === source ? target : value;
};
}
function d3_vendorSymbol(object, name) {
if (name in object) return name;
name = name.charAt(0).toUpperCase() + name.substring(1);
for (var i = 0, n = d3_vendorPrefixes.length; i < n; ++i) {
var prefixName = d3_vendorPrefixes[i] + name;
if (prefixName in object) return prefixName;
}
}
var d3_vendorPrefixes = [ "webkit", "ms", "moz", "Moz", "o", "O" ];
function d3_noop() {}
d3.dispatch = function() {
var dispatch = new d3_dispatch(), i = -1, n = arguments.length;
while (++i < n) dispatch[arguments[i]] = d3_dispatch_event(dispatch);
return dispatch;
};
function d3_dispatch() {}
d3_dispatch.prototype.on = function(type, listener) {
var i = type.indexOf("."), name = "";
if (i >= 0) {
name = type.substring(i + 1);
type = type.substring(0, i);
}
if (type) return arguments.length < 2 ? this[type].on(name) : this[type].on(name, listener);
if (arguments.length === 2) {
if (listener == null) for (type in this) {
if (this.hasOwnProperty(type)) this[type].on(name, null);
}
return this;
}
};
function d3_dispatch_event(dispatch) {
var listeners = [], listenerByName = new d3_Map();
function event() {
var z = listeners, i = -1, n = z.length, l;
while (++i < n) if (l = z[i].on) l.apply(this, arguments);
return dispatch;
}
event.on = function(name, listener) {
var l = listenerByName.get(name), i;
if (arguments.length < 2) return l && l.on;
if (l) {
l.on = null;
listeners = listeners.slice(0, i = listeners.indexOf(l)).concat(listeners.slice(i + 1));
listenerByName.remove(name);
}
if (listener) listeners.push(listenerByName.set(name, {
on: listener
}));
return dispatch;
};
return event;
}
d3.event = null;
function d3_eventPreventDefault() {
d3.event.preventDefault();
}
function d3_eventSource() {
var e = d3.event, s;
while (s = e.sourceEvent) e = s;
return e;
}
function d3_eventDispatch(target) {
var dispatch = new d3_dispatch(), i = 0, n = arguments.length;
while (++i < n) dispatch[arguments[i]] = d3_dispatch_event(dispatch);
dispatch.of = function(thiz, argumentz) {
return function(e1) {
try {
var e0 = e1.sourceEvent = d3.event;
e1.target = target;
d3.event = e1;
dispatch[e1.type].apply(thiz, argumentz);
} finally {
d3.event = e0;
}
};
};
return dispatch;
}
d3.requote = function(s) {
return s.replace(d3_requote_re, "\\$&");
};
var d3_requote_re = /[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g;
var d3_subclass = {}.__proto__ ? function(object, prototype) {
object.__proto__ = prototype;
} : function(object, prototype) {
for (var property in prototype) object[property] = prototype[property];
};
function d3_selection(groups) {
d3_subclass(groups, d3_selectionPrototype);
return groups;
}
var d3_select = function(s, n) {
return n.querySelector(s);
}, d3_selectAll = function(s, n) {
return n.querySelectorAll(s);
}, d3_selectMatcher = d3_documentElement[d3_vendorSymbol(d3_documentElement, "matchesSelector")], d3_selectMatches = function(n, s) {
return d3_selectMatcher.call(n, s);
};
if (typeof Sizzle === "function") {
d3_select = function(s, n) {
return Sizzle(s, n)[0] || null;
};
d3_selectAll = function(s, n) {
return Sizzle.uniqueSort(Sizzle(s, n));
};
d3_selectMatches = Sizzle.matchesSelector;
}
d3.selection = function() {
return d3_selectionRoot;
};
var d3_selectionPrototype = d3.selection.prototype = [];
d3_selectionPrototype.select = function(selector) {
var subgroups = [], subgroup, subnode, group, node;
selector = d3_selection_selector(selector);
for (var j = -1, m = this.length; ++j < m; ) {
subgroups.push(subgroup = []);
subgroup.parentNode = (group = this[j]).parentNode;
for (var i = -1, n = group.length; ++i < n; ) {
if (node = group[i]) {
subgroup.push(subnode = selector.call(node, node.__data__, i, j));
if (subnode && "__data__" in node) subnode.__data__ = node.__data__;
} else {
subgroup.push(null);
}
}
}
return d3_selection(subgroups);
};
function d3_selection_selector(selector) {
return typeof selector === "function" ? selector : function() {
return d3_select(selector, this);
};
}
d3_selectionPrototype.selectAll = function(selector) {
var subgroups = [], subgroup, node;
selector = d3_selection_selectorAll(selector);
for (var j = -1, m = this.length; ++j < m; ) {
for (var group = this[j], i = -1, n = group.length; ++i < n; ) {
if (node = group[i]) {
subgroups.push(subgroup = d3_array(selector.call(node, node.__data__, i, j)));
subgroup.parentNode = node;
}
}
}
return d3_selection(subgroups);
};
function d3_selection_selectorAll(selector) {
return typeof selector === "function" ? selector : function() {
return d3_selectAll(selector, this);
};
}
var d3_nsPrefix = {
svg: "http://www.w3.org/2000/svg",
xhtml: "http://www.w3.org/1999/xhtml",
xlink: "http://www.w3.org/1999/xlink",
xml: "http://www.w3.org/XML/1998/namespace",
xmlns: "http://www.w3.org/2000/xmlns/"
};
d3.ns = {
prefix: d3_nsPrefix,
qualify: function(name) {
var i = name.indexOf(":"), prefix = name;
if (i >= 0) {
prefix = name.substring(0, i);
name = name.substring(i + 1);
}
return d3_nsPrefix.hasOwnProperty(prefix) ? {
space: d3_nsPrefix[prefix],
local: name
} : name;
}
};
d3_selectionPrototype.attr = function(name, value) {
if (arguments.length < 2) {
if (typeof name === "string") {
var node = this.node();
name = d3.ns.qualify(name);
return name.local ? node.getAttributeNS(name.space, name.local) : node.getAttribute(name);
}
for (value in name) this.each(d3_selection_attr(value, name[value]));
return this;
}
return this.each(d3_selection_attr(name, value));
};
function d3_selection_attr(name, value) {
name = d3.ns.qualify(name);
function attrNull() {
this.removeAttribute(name);
}
function attrNullNS() {
this.removeAttributeNS(name.space, name.local);
}
function attrConstant() {
this.setAttribute(name, value);
}
function attrConstantNS() {
this.setAttributeNS(name.space, name.local, value);
}
function attrFunction() {
var x = value.apply(this, arguments);
if (x == null) this.removeAttribute(name); else this.setAttribute(name, x);
}
function attrFunctionNS() {
var x = value.apply(this, arguments);
if (x == null) this.removeAttributeNS(name.space, name.local); else this.setAttributeNS(name.space, name.local, x);
}
return value == null ? name.local ? attrNullNS : attrNull : typeof value === "function" ? name.local ? attrFunctionNS : attrFunction : name.local ? attrConstantNS : attrConstant;
}
function d3_collapse(s) {
return s.trim().replace(/\s+/g, " ");
}
d3_selectionPrototype.classed = function(name, value) {
if (arguments.length < 2) {
if (typeof name === "string") {
var node = this.node(), n = (name = name.trim().split(/^|\s+/g)).length, i = -1;
if (value = node.classList) {
while (++i < n) if (!value.contains(name[i])) return false;
} else {
value = node.getAttribute("class");
while (++i < n) if (!d3_selection_classedRe(name[i]).test(value)) return false;
}
return true;
}
for (value in name) this.each(d3_selection_classed(value, name[value]));
return this;
}
return this.each(d3_selection_classed(name, value));
};
function d3_selection_classedRe(name) {
return new RegExp("(?:^|\\s+)" + d3.requote(name) + "(?:\\s+|$)", "g");
}
function d3_selection_classed(name, value) {
name = name.trim().split(/\s+/).map(d3_selection_classedName);
var n = name.length;
function classedConstant() {
var i = -1;
while (++i < n) name[i](this, value);
}
function classedFunction() {
var i = -1, x = value.apply(this, arguments);
while (++i < n) name[i](this, x);
}
return typeof value === "function" ? classedFunction : classedConstant;
}
function d3_selection_classedName(name) {
var re = d3_selection_classedRe(name);
return function(node, value) {
if (c = node.classList) return value ? c.add(name) : c.remove(name);
var c = node.getAttribute("class") || "";
if (value) {
re.lastIndex = 0;
if (!re.test(c)) node.setAttribute("class", d3_collapse(c + " " + name));
} else {
node.setAttribute("class", d3_collapse(c.replace(re, " ")));
}
};
}
d3_selectionPrototype.style = function(name, value, priority) {
var n = arguments.length;
if (n < 3) {
if (typeof name !== "string") {
if (n < 2) value = "";
for (priority in name) this.each(d3_selection_style(priority, name[priority], value));
return this;
}
if (n < 2) return d3_window.getComputedStyle(this.node(), null).getPropertyValue(name);
priority = "";
}
return this.each(d3_selection_style(name, value, priority));
};
function d3_selection_style(name, value, priority) {
function styleNull() {
this.style.removeProperty(name);
}
function styleConstant() {
this.style.setProperty(name, value, priority);
}
function styleFunction() {
var x = value.apply(this, arguments);
if (x == null) this.style.removeProperty(name); else this.style.setProperty(name, x, priority);
}
return value == null ? styleNull : typeof value === "function" ? styleFunction : styleConstant;
}
d3_selectionPrototype.property = function(name, value) {
if (arguments.length < 2) {
if (typeof name === "string") return this.node()[name];
for (value in name) this.each(d3_selection_property(value, name[value]));
return this;
}
return this.each(d3_selection_property(name, value));
};
function d3_selection_property(name, value) {
function propertyNull() {
delete this[name];
}
function propertyConstant() {
this[name] = value;
}
function propertyFunction() {
var x = value.apply(this, arguments);
if (x == null) delete this[name]; else this[name] = x;
}
return value == null ? propertyNull : typeof value === "function" ? propertyFunction : propertyConstant;
}
d3_selectionPrototype.text = function(value) {
return arguments.length ? this.each(typeof value === "function" ? function() {
var v = value.apply(this, arguments);
this.textContent = v == null ? "" : v;
} : value == null ? function() {
this.textContent = "";
} : function() {
this.textContent = value;
}) : this.node().textContent;
};
d3_selectionPrototype.html = function(value) {
return arguments.length ? this.each(typeof value === "function" ? function() {
var v = value.apply(this, arguments);
this.innerHTML = v == null ? "" : v;
} : value == null ? function() {
this.innerHTML = "";
} : function() {
this.innerHTML = value;
}) : this.node().innerHTML;
};
d3_selectionPrototype.append = function(name) {
name = d3_selection_creator(name);
return this.select(function() {
return this.appendChild(name.apply(this, arguments));
});
};
function d3_selection_creator(name) {
return typeof name === "function" ? name : (name = d3.ns.qualify(name)).local ? function() {
return this.ownerDocument.createElementNS(name.space, name.local);
} : function() {
return this.ownerDocument.createElementNS(this.namespaceURI, name);
};
}
d3_selectionPrototype.insert = function(name, before) {
name = d3_selection_creator(name);
before = d3_selection_selector(before);
return this.select(function() {
return this.insertBefore(name.apply(this, arguments), before.apply(this, arguments) || null);
});
};
d3_selectionPrototype.remove = function() {
return this.each(function() {
var parent = this.parentNode;
if (parent) parent.removeChild(this);
});
};
d3_selectionPrototype.data = function(value, key) {
var i = -1, n = this.length, group, node;
if (!arguments.length) {
value = new Array(n = (group = this[0]).length);
while (++i < n) {
if (node = group[i]) {
value[i] = node.__data__;
}
}
return value;
}
function bind(group, groupData) {
var i, n = group.length, m = groupData.length, n0 = Math.min(n, m), updateNodes = new Array(m), enterNodes = new Array(m), exitNodes = new Array(n), node, nodeData;
if (key) {
var nodeByKeyValue = new d3_Map(), dataByKeyValue = new d3_Map(), keyValues = [], keyValue;
for (i = -1; ++i < n; ) {
keyValue = key.call(node = group[i], node.__data__, i);
if (nodeByKeyValue.has(keyValue)) {
exitNodes[i] = node;
} else {
nodeByKeyValue.set(keyValue, node);
}
keyValues.push(keyValue);
}
for (i = -1; ++i < m; ) {
keyValue = key.call(groupData, nodeData = groupData[i], i);
if (node = nodeByKeyValue.get(keyValue)) {
updateNodes[i] = node;
node.__data__ = nodeData;
} else if (!dataByKeyValue.has(keyValue)) {
enterNodes[i] = d3_selection_dataNode(nodeData);
}
dataByKeyValue.set(keyValue, nodeData);
nodeByKeyValue.remove(keyValue);
}
for (i = -1; ++i < n; ) {
if (nodeByKeyValue.has(keyValues[i])) {
exitNodes[i] = group[i];
}
}
} else {
for (i = -1; ++i < n0; ) {
node = group[i];
nodeData = groupData[i];
if (node) {
node.__data__ = nodeData;
updateNodes[i] = node;
} else {
enterNodes[i] = d3_selection_dataNode(nodeData);
}
}
for (;i < m; ++i) {
enterNodes[i] = d3_selection_dataNode(groupData[i]);
}
for (;i < n; ++i) {
exitNodes[i] = group[i];
}
}
enterNodes.update = updateNodes;
enterNodes.parentNode = updateNodes.parentNode = exitNodes.parentNode = group.parentNode;
enter.push(enterNodes);
update.push(updateNodes);
exit.push(exitNodes);
}
var enter = d3_selection_enter([]), update = d3_selection([]), exit = d3_selection([]);
if (typeof value === "function") {
while (++i < n) {
bind(group = this[i], value.call(group, group.parentNode.__data__, i));
}
} else {
while (++i < n) {
bind(group = this[i], value);
}
}
update.enter = function() {
return enter;
};
update.exit = function() {
return exit;
};
return update;
};
function d3_selection_dataNode(data) {
return {
__data__: data
};
}
d3_selectionPrototype.datum = function(value) {
return arguments.length ? this.property("__data__", value) : this.property("__data__");
};
d3_selectionPrototype.filter = function(filter) {
var subgroups = [], subgroup, group, node;
if (typeof filter !== "function") filter = d3_selection_filter(filter);
for (var j = 0, m = this.length; j < m; j++) {
subgroups.push(subgroup = []);
subgroup.parentNode = (group = this[j]).parentNode;
for (var i = 0, n = group.length; i < n; i++) {
if ((node = group[i]) && filter.call(node, node.__data__, i)) {
subgroup.push(node);
}
}
}
return d3_selection(subgroups);
};
function d3_selection_filter(selector) {
return function() {
return d3_selectMatches(this, selector);
};
}
d3_selectionPrototype.order = function() {
for (var j = -1, m = this.length; ++j < m; ) {
for (var group = this[j], i = group.length - 1, next = group[i], node; --i >= 0; ) {
if (node = group[i]) {
if (next && next !== node.nextSibling) next.parentNode.insertBefore(node, next);
next = node;
}
}
}
return this;
};
d3_selectionPrototype.sort = function(comparator) {
comparator = d3_selection_sortComparator.apply(this, arguments);
for (var j = -1, m = this.length; ++j < m; ) this[j].sort(comparator);
return this.order();
};
function d3_selection_sortComparator(comparator) {
if (!arguments.length) comparator = d3.ascending;
return function(a, b) {
return a && b ? comparator(a.__data__, b.__data__) : !a - !b;
};
}
d3_selectionPrototype.each = function(callback) {
return d3_selection_each(this, function(node, i, j) {
callback.call(node, node.__data__, i, j);
});
};
function d3_selection_each(groups, callback) {
for (var j = 0, m = groups.length; j < m; j++) {
for (var group = groups[j], i = 0, n = group.length, node; i < n; i++) {
if (node = group[i]) callback(node, i, j);
}
}
return groups;
}
d3_selectionPrototype.call = function(callback) {
var args = d3_array(arguments);
callback.apply(args[0] = this, args);
return this;
};
d3_selectionPrototype.empty = function() {
return !this.node();
};
d3_selectionPrototype.node = function() {
for (var j = 0, m = this.length; j < m; j++) {
for (var group = this[j], i = 0, n = group.length; i < n; i++) {
var node = group[i];
if (node) return node;
}
}
return null;
};
d3_selectionPrototype.size = function() {
var n = 0;
this.each(function() {
++n;
});
return n;
};
function d3_selection_enter(selection) {
d3_subclass(selection, d3_selection_enterPrototype);
return selection;
}
var d3_selection_enterPrototype = [];
d3.selection.enter = d3_selection_enter;
d3.selection.enter.prototype = d3_selection_enterPrototype;
d3_selection_enterPrototype.append = d3_selectionPrototype.append;
d3_selection_enterPrototype.empty = d3_selectionPrototype.empty;
d3_selection_enterPrototype.node = d3_selectionPrototype.node;
d3_selection_enterPrototype.call = d3_selectionPrototype.call;
d3_selection_enterPrototype.size = d3_selectionPrototype.size;
d3_selection_enterPrototype.select = function(selector) {
var subgroups = [], subgroup, subnode, upgroup, group, node;
for (var j = -1, m = this.length; ++j < m; ) {
upgroup = (group = this[j]).update;
subgroups.push(subgroup = []);
subgroup.parentNode = group.parentNode;
for (var i = -1, n = group.length; ++i < n; ) {
if (node = group[i]) {
subgroup.push(upgroup[i] = subnode = selector.call(group.parentNode, node.__data__, i, j));
subnode.__data__ = node.__data__;
} else {
subgroup.push(null);
}
}
}
return d3_selection(subgroups);
};
d3_selection_enterPrototype.insert = function(name, before) {
if (arguments.length < 2) before = d3_selection_enterInsertBefore(this);
return d3_selectionPrototype.insert.call(this, name, before);
};
function d3_selection_enterInsertBefore(enter) {
var i0, j0;
return function(d, i, j) {
var group = enter[j].update, n = group.length, node;
if (j != j0) j0 = j, i0 = 0;
if (i >= i0) i0 = i + 1;
while (!(node = group[i0]) && ++i0 < n) ;
return node;
};
}
d3_selectionPrototype.transition = function() {
var id = d3_transitionInheritId || ++d3_transitionId, subgroups = [], subgroup, node, transition = d3_transitionInherit || {
time: Date.now(),
ease: d3_ease_cubicInOut,
delay: 0,
duration: 250
};
for (var j = -1, m = this.length; ++j < m; ) {
subgroups.push(subgroup = []);
for (var group = this[j], i = -1, n = group.length; ++i < n; ) {
if (node = group[i]) d3_transitionNode(node, i, id, transition);
subgroup.push(node);
}
}
return d3_transition(subgroups, id);
};
d3_selectionPrototype.interrupt = function() {
return this.each(d3_selection_interrupt);
};
function d3_selection_interrupt() {
var lock = this.__transition__;
if (lock) ++lock.active;
}
d3.select = function(node) {
var group = [ typeof node === "string" ? d3_select(node, d3_document) : node ];
group.parentNode = d3_documentElement;
return d3_selection([ group ]);
};
d3.selectAll = function(nodes) {
var group = d3_array(typeof nodes === "string" ? d3_selectAll(nodes, d3_document) : nodes);
group.parentNode = d3_documentElement;
return d3_selection([ group ]);
};
var d3_selectionRoot = d3.select(d3_documentElement);
d3_selectionPrototype.on = function(type, listener, capture) {
var n = arguments.length;
if (n < 3) {
if (typeof type !== "string") {
if (n < 2) listener = false;
for (capture in type) this.each(d3_selection_on(capture, type[capture], listener));
return this;
}
if (n < 2) return (n = this.node()["__on" + type]) && n._;
capture = false;
}
return this.each(d3_selection_on(type, listener, capture));
};
function d3_selection_on(type, listener, capture) {
var name = "__on" + type, i = type.indexOf("."), wrap = d3_selection_onListener;
if (i > 0) type = type.substring(0, i);
var filter = d3_selection_onFilters.get(type);
if (filter) type = filter, wrap = d3_selection_onFilter;
function onRemove() {
var l = this[name];
if (l) {
this.removeEventListener(type, l, l.$);
delete this[name];
}
}
function onAdd() {
var l = wrap(listener, d3_array(arguments));
onRemove.call(this);
this.addEventListener(type, this[name] = l, l.$ = capture);
l._ = listener;
}
function removeAll() {
var re = new RegExp("^__on([^.]+)" + d3.requote(type) + "$"), match;
for (var name in this) {
if (match = name.match(re)) {
var l = this[name];
this.removeEventListener(match[1], l, l.$);
delete this[name];
}
}
}
return i ? listener ? onAdd : onRemove : listener ? d3_noop : removeAll;
}
var d3_selection_onFilters = d3.map({
mouseenter: "mouseover",
mouseleave: "mouseout"
});
d3_selection_onFilters.forEach(function(k) {
if ("on" + k in d3_document) d3_selection_onFilters.remove(k);
});
function d3_selection_onListener(listener, argumentz) {
return function(e) {
var o = d3.event;
d3.event = e;
argumentz[0] = this.__data__;
try {
listener.apply(this, argumentz);
} finally {
d3.event = o;
}
};
}
function d3_selection_onFilter(listener, argumentz) {
var l = d3_selection_onListener(listener, argumentz);
return function(e) {
var target = this, related = e.relatedTarget;
if (!related || related !== target && !(related.compareDocumentPosition(target) & 8)) {
l.call(target, e);
}
};
}
var d3_event_dragSelect = "onselectstart" in d3_document ? null : d3_vendorSymbol(d3_documentElement.style, "userSelect"), d3_event_dragId = 0;
function d3_event_dragSuppress() {
var name = ".dragsuppress-" + ++d3_event_dragId, click = "click" + name, w = d3.select(d3_window).on("touchmove" + name, d3_eventPreventDefault).on("dragstart" + name, d3_eventPreventDefault).on("selectstart" + name, d3_eventPreventDefault);
if (d3_event_dragSelect) {
var style = d3_documentElement.style, select = style[d3_event_dragSelect];
style[d3_event_dragSelect] = "none";
}
return function(suppressClick) {
w.on(name, null);
if (d3_event_dragSelect) style[d3_event_dragSelect] = select;
if (suppressClick) {
function off() {
w.on(click, null);
}
w.on(click, function() {
d3_eventPreventDefault();
off();
}, true);
setTimeout(off, 0);
}
};
}
d3.mouse = function(container) {
return d3_mousePoint(container, d3_eventSource());
};
var d3_mouse_bug44083 = /WebKit/.test(d3_window.navigator.userAgent) ? -1 : 0;
function d3_mousePoint(container, e) {
if (e.changedTouches) e = e.changedTouches[0];
var svg = container.ownerSVGElement || container;
if (svg.createSVGPoint) {
var point = svg.createSVGPoint();
if (d3_mouse_bug44083 < 0 && (d3_window.scrollX || d3_window.scrollY)) {
svg = d3.select("body").append("svg").style({
position: "absolute",
top: 0,
left: 0,
margin: 0,
padding: 0,
border: "none"
}, "important");
var ctm = svg[0][0].getScreenCTM();
d3_mouse_bug44083 = !(ctm.f || ctm.e);
svg.remove();
}
if (d3_mouse_bug44083) point.x = e.pageX, point.y = e.pageY; else point.x = e.clientX,
point.y = e.clientY;
point = point.matrixTransform(container.getScreenCTM().inverse());
return [ point.x, point.y ];
}
var rect = container.getBoundingClientRect();
return [ e.clientX - rect.left - container.clientLeft, e.clientY - rect.top - container.clientTop ];
}
d3.touches = function(container, touches) {
if (arguments.length < 2) touches = d3_eventSource().touches;
return touches ? d3_array(touches).map(function(touch) {
var point = d3_mousePoint(container, touch);
point.identifier = touch.identifier;
return point;
}) : [];
};
d3.behavior.drag = function() {
var event = d3_eventDispatch(drag, "drag", "dragstart", "dragend"), origin = null, mousedown = dragstart(d3_noop, d3.mouse, "mousemove", "mouseup"), touchstart = dragstart(touchid, touchposition, "touchmove", "touchend");
function drag() {
this.on("mousedown.drag", mousedown).on("touchstart.drag", touchstart);
}
function touchid() {
return d3.event.changedTouches[0].identifier;
}
function touchposition(parent, id) {
return d3.touches(parent).filter(function(p) {
return p.identifier === id;
})[0];
}
function dragstart(id, position, move, end) {
return function() {
var target = this, parent = target.parentNode, event_ = event.of(target, arguments), eventTarget = d3.event.target, eventId = id(), drag = eventId == null ? "drag" : "drag-" + eventId, origin_ = position(parent, eventId), dragged = 0, offset, w = d3.select(d3_window).on(move + "." + drag, moved).on(end + "." + drag, ended), dragRestore = d3_event_dragSuppress();
if (origin) {
offset = origin.apply(target, arguments);
offset = [ offset.x - origin_[0], offset.y - origin_[1] ];
} else {
offset = [ 0, 0 ];
}
event_({
type: "dragstart"
});
function moved() {
var p = position(parent, eventId), dx = p[0] - origin_[0], dy = p[1] - origin_[1];
dragged |= dx | dy;
origin_ = p;
event_({
type: "drag",
x: p[0] + offset[0],
y: p[1] + offset[1],
dx: dx,
dy: dy
});
}
function ended() {
w.on(move + "." + drag, null).on(end + "." + drag, null);
dragRestore(dragged && d3.event.target === eventTarget);
event_({
type: "dragend"
});
}
};
}
drag.origin = function(x) {
if (!arguments.length) return origin;
origin = x;
return drag;
};
return d3.rebind(drag, event, "on");
};
var π = Math.PI, τ = 2 * π, halfπ = π / 2, ε = 1e-6, ε2 = ε * ε, d3_radians = π / 180, d3_degrees = 180 / π;
function d3_sgn(x) {
return x > 0 ? 1 : x < 0 ? -1 : 0;
}
function d3_acos(x) {
return x > 1 ? 0 : x < -1 ? π : Math.acos(x);
}
function d3_asin(x) {
return x > 1 ? halfπ : x < -1 ? -halfπ : Math.asin(x);
}
function d3_sinh(x) {
return ((x = Math.exp(x)) - 1 / x) / 2;
}
function d3_cosh(x) {
return ((x = Math.exp(x)) + 1 / x) / 2;
}
function d3_tanh(x) {
return ((x = Math.exp(2 * x)) - 1) / (x + 1);
}
function d3_haversin(x) {
return (x = Math.sin(x / 2)) * x;
}
var ρ = Math.SQRT2, ρ2 = 2, ρ4 = 4;
d3.interpolateZoom = function(p0, p1) {
var ux0 = p0[0], uy0 = p0[1], w0 = p0[2], ux1 = p1[0], uy1 = p1[1], w1 = p1[2];
var dx = ux1 - ux0, dy = uy1 - uy0, d2 = dx * dx + dy * dy, d1 = Math.sqrt(d2), b0 = (w1 * w1 - w0 * w0 + ρ4 * d2) / (2 * w0 * ρ2 * d1), b1 = (w1 * w1 - w0 * w0 - ρ4 * d2) / (2 * w1 * ρ2 * d1), r0 = Math.log(Math.sqrt(b0 * b0 + 1) - b0), r1 = Math.log(Math.sqrt(b1 * b1 + 1) - b1), dr = r1 - r0, S = (dr || Math.log(w1 / w0)) / ρ;
function interpolate(t) {
var s = t * S;
if (dr) {
var coshr0 = d3_cosh(r0), u = w0 / (ρ2 * d1) * (coshr0 * d3_tanh(ρ * s + r0) - d3_sinh(r0));
return [ ux0 + u * dx, uy0 + u * dy, w0 * coshr0 / d3_cosh(ρ * s + r0) ];
}
return [ ux0 + t * dx, uy0 + t * dy, w0 * Math.exp(ρ * s) ];
}
interpolate.duration = S * 1e3;
return interpolate;
};
d3.behavior.zoom = function() {
var view = {
x: 0,
y: 0,
k: 1
}, translate0, center, size = [ 960, 500 ], scaleExtent = d3_behavior_zoomInfinity, mousedown = "mousedown.zoom", mousemove = "mousemove.zoom", mouseup = "mouseup.zoom", mousewheelTimer, touchstart = "touchstart.zoom", touchtime, event = d3_eventDispatch(zoom, "zoomstart", "zoom", "zoomend"), x0, x1, y0, y1;
function zoom(g) {
g.on(mousedown, mousedowned).on(d3_behavior_zoomWheel + ".zoom", mousewheeled).on(mousemove, mousewheelreset).on("dblclick.zoom", dblclicked).on(touchstart, touchstarted);
}
zoom.event = function(g) {
g.each(function() {
var event_ = event.of(this, arguments), view1 = view;
if (d3_transitionInheritId) {
d3.select(this).transition().each("start.zoom", function() {
view = this.__chart__ || {
x: 0,
y: 0,
k: 1
};
zoomstarted(event_);
}).tween("zoom:zoom", function() {
var dx = size[0], dy = size[1], cx = dx / 2, cy = dy / 2, i = d3.interpolateZoom([ (cx - view.x) / view.k, (cy - view.y) / view.k, dx / view.k ], [ (cx - view1.x) / view1.k, (cy - view1.y) / view1.k, dx / view1.k ]);
return function(t) {
var l = i(t), k = dx / l[2];
this.__chart__ = view = {
x: cx - l[0] * k,
y: cy - l[1] * k,
k: k
};
zoomed(event_);
};
}).each("end.zoom", function() {
zoomended(event_);
});
} else {
this.__chart__ = view;
zoomstarted(event_);
zoomed(event_);
zoomended(event_);
}
});
};
zoom.translate = function(_) {
if (!arguments.length) return [ view.x, view.y ];
view = {
x: +_[0],
y: +_[1],
k: view.k
};
rescale();
return zoom;
};
zoom.scale = function(_) {
if (!arguments.length) return view.k;
view = {
x: view.x,
y: view.y,
k: +_
};
rescale();
return zoom;
};
zoom.scaleExtent = function(_) {
if (!arguments.length) return scaleExtent;
scaleExtent = _ == null ? d3_behavior_zoomInfinity : [ +_[0], +_[1] ];
return zoom;
};
zoom.center = function(_) {
if (!arguments.length) return center;
center = _ && [ +_[0], +_[1] ];
return zoom;
};
zoom.size = function(_) {
if (!arguments.length) return size;
size = _ && [ +_[0], +_[1] ];
return zoom;
};
zoom.x = function(z) {
if (!arguments.length) return x1;
x1 = z;
x0 = z.copy();
view = {
x: 0,
y: 0,
k: 1
};
return zoom;
};
zoom.y = function(z) {
if (!arguments.length) return y1;
y1 = z;
y0 = z.copy();
view = {
x: 0,
y: 0,
k: 1
};
return zoom;
};
function location(p) {
return [ (p[0] - view.x) / view.k, (p[1] - view.y) / view.k ];
}
function point(l) {
return [ l[0] * view.k + view.x, l[1] * view.k + view.y ];
}
function scaleTo(s) {
view.k = Math.max(scaleExtent[0], Math.min(scaleExtent[1], s));
}
function translateTo(p, l) {
l = point(l);
view.x += p[0] - l[0];
view.y += p[1] - l[1];
}
function rescale() {
if (x1) x1.domain(x0.range().map(function(x) {
return (x - view.x) / view.k;
}).map(x0.invert));
if (y1) y1.domain(y0.range().map(function(y) {
return (y - view.y) / view.k;
}).map(y0.invert));
}
function zoomstarted(event) {
event({
type: "zoomstart"
});
}
function zoomed(event) {
rescale();
event({
type: "zoom",
scale: view.k,
translate: [ view.x, view.y ]
});
}
function zoomended(event) {
event({
type: "zoomend"
});
}
function mousedowned() {
var target = this, event_ = event.of(target, arguments), eventTarget = d3.event.target, dragged = 0, w = d3.select(d3_window).on(mousemove, moved).on(mouseup, ended), l = location(d3.mouse(target)), dragRestore = d3_event_dragSuppress();
d3_selection_interrupt.call(target);
zoomstarted(event_);
function moved() {
dragged = 1;
translateTo(d3.mouse(target), l);
zoomed(event_);
}
function ended() {
w.on(mousemove, d3_window === target ? mousewheelreset : null).on(mouseup, null);
dragRestore(dragged && d3.event.target === eventTarget);
zoomended(event_);
}
}
function touchstarted() {
var target = this, event_ = event.of(target, arguments), locations0 = {}, distance0 = 0, scale0, eventId = d3.event.changedTouches[0].identifier, touchmove = "touchmove.zoom-" + eventId, touchend = "touchend.zoom-" + eventId, w = d3.select(d3_window).on(touchmove, moved).on(touchend, ended), t = d3.select(target).on(mousedown, null).on(touchstart, started), dragRestore = d3_event_dragSuppress();
d3_selection_interrupt.call(target);
started();
zoomstarted(event_);
function relocate() {
var touches = d3.touches(target);
scale0 = view.k;
touches.forEach(function(t) {
if (t.identifier in locations0) locations0[t.identifier] = location(t);
});
return touches;
}
function started() {
var changed = d3.event.changedTouches;
for (var i = 0, n = changed.length; i < n; ++i) {
locations0[changed[i].identifier] = null;
}
var touches = relocate(), now = Date.now();
if (touches.length === 1) {
if (now - touchtime < 500) {
var p = touches[0], l = locations0[p.identifier];
scaleTo(view.k * 2);
translateTo(p, l);
d3_eventPreventDefault();
zoomed(event_);
}
touchtime = now;
} else if (touches.length > 1) {
var p = touches[0], q = touches[1], dx = p[0] - q[0], dy = p[1] - q[1];
distance0 = dx * dx + dy * dy;
}
}
function moved() {
var touches = d3.touches(target), p0, l0, p1, l1;
for (var i = 0, n = touches.length; i < n; ++i, l1 = null) {
p1 = touches[i];
if (l1 = locations0[p1.identifier]) {
if (l0) break;
p0 = p1, l0 = l1;
}
}
if (l1) {
var distance1 = (distance1 = p1[0] - p0[0]) * distance1 + (distance1 = p1[1] - p0[1]) * distance1, scale1 = distance0 && Math.sqrt(distance1 / distance0);
p0 = [ (p0[0] + p1[0]) / 2, (p0[1] + p1[1]) / 2 ];
l0 = [ (l0[0] + l1[0]) / 2, (l0[1] + l1[1]) / 2 ];
scaleTo(scale1 * scale0);
}
touchtime = null;
translateTo(p0, l0);
zoomed(event_);
}
function ended() {
if (d3.event.touches.length) {
var changed = d3.event.changedTouches;
for (var i = 0, n = changed.length; i < n; ++i) {
delete locations0[changed[i].identifier];
}
for (var identifier in locations0) {
return void relocate();
}
}
w.on(touchmove, null).on(touchend, null);
t.on(mousedown, mousedowned).on(touchstart, touchstarted);
dragRestore();
zoomended(event_);
}
}
function mousewheeled() {
var event_ = event.of(this, arguments);
if (mousewheelTimer) clearTimeout(mousewheelTimer); else d3_selection_interrupt.call(this),
zoomstarted(event_);
mousewheelTimer = setTimeout(function() {
mousewheelTimer = null;
zoomended(event_);
}, 50);
d3_eventPreventDefault();
var point = center || d3.mouse(this);
if (!translate0) translate0 = location(point);
scaleTo(Math.pow(2, d3_behavior_zoomDelta() * .002) * view.k);
translateTo(point, translate0);
zoomed(event_);
}
function mousewheelreset() {
translate0 = null;
}
function dblclicked() {
var event_ = event.of(this, arguments), p = d3.mouse(this), l = location(p), k = Math.log(view.k) / Math.LN2;
zoomstarted(event_);
scaleTo(Math.pow(2, d3.event.shiftKey ? Math.ceil(k) - 1 : Math.floor(k) + 1));
translateTo(p, l);
zoomed(event_);
zoomended(event_);
}
return d3.rebind(zoom, event, "on");
};
var d3_behavior_zoomInfinity = [ 0, Infinity ];
var d3_behavior_zoomDelta, d3_behavior_zoomWheel = "onwheel" in d3_document ? (d3_behavior_zoomDelta = function() {
return -d3.event.deltaY * (d3.event.deltaMode ? 120 : 1);
}, "wheel") : "onmousewheel" in d3_document ? (d3_behavior_zoomDelta = function() {
return d3.event.wheelDelta;
}, "mousewheel") : (d3_behavior_zoomDelta = function() {
return -d3.event.detail;
}, "MozMousePixelScroll");
function d3_Color() {}
d3_Color.prototype.toString = function() {
return this.rgb() + "";
};
d3.hsl = function(h, s, l) {
return arguments.length === 1 ? h instanceof d3_Hsl ? d3_hsl(h.h, h.s, h.l) : d3_rgb_parse("" + h, d3_rgb_hsl, d3_hsl) : d3_hsl(+h, +s, +l);
};
function d3_hsl(h, s, l) {
return new d3_Hsl(h, s, l);
}
function d3_Hsl(h, s, l) {
this.h = h;
this.s = s;
this.l = l;
}
var d3_hslPrototype = d3_Hsl.prototype = new d3_Color();
d3_hslPrototype.brighter = function(k) {
k = Math.pow(.7, arguments.length ? k : 1);
return d3_hsl(this.h, this.s, this.l / k);
};
d3_hslPrototype.darker = function(k) {
k = Math.pow(.7, arguments.length ? k : 1);
return d3_hsl(this.h, this.s, k * this.l);
};
d3_hslPrototype.rgb = function() {
return d3_hsl_rgb(this.h, this.s, this.l);
};
function d3_hsl_rgb(h, s, l) {
var m1, m2;
h = isNaN(h) ? 0 : (h %= 360) < 0 ? h + 360 : h;
s = isNaN(s) ? 0 : s < 0 ? 0 : s > 1 ? 1 : s;
l = l < 0 ? 0 : l > 1 ? 1 : l;
m2 = l <= .5 ? l * (1 + s) : l + s - l * s;
m1 = 2 * l - m2;
function v(h) {
if (h > 360) h -= 360; else if (h < 0) h += 360;
if (h < 60) return m1 + (m2 - m1) * h / 60;
if (h < 180) return m2;
if (h < 240) return m1 + (m2 - m1) * (240 - h) / 60;
return m1;
}
function vv(h) {
return Math.round(v(h) * 255);
}
return d3_rgb(vv(h + 120), vv(h), vv(h - 120));
}
d3.hcl = function(h, c, l) {
return arguments.length === 1 ? h instanceof d3_Hcl ? d3_hcl(h.h, h.c, h.l) : h instanceof d3_Lab ? d3_lab_hcl(h.l, h.a, h.b) : d3_lab_hcl((h = d3_rgb_lab((h = d3.rgb(h)).r, h.g, h.b)).l, h.a, h.b) : d3_hcl(+h, +c, +l);
};
function d3_hcl(h, c, l) {
return new d3_Hcl(h, c, l);
}
function d3_Hcl(h, c, l) {
this.h = h;
this.c = c;
this.l = l;
}
var d3_hclPrototype = d3_Hcl.prototype = new d3_Color();
d3_hclPrototype.brighter = function(k) {
return d3_hcl(this.h, this.c, Math.min(100, this.l + d3_lab_K * (arguments.length ? k : 1)));
};
d3_hclPrototype.darker = function(k) {
return d3_hcl(this.h, this.c, Math.max(0, this.l - d3_lab_K * (arguments.length ? k : 1)));
};
d3_hclPrototype.rgb = function() {
return d3_hcl_lab(this.h, this.c, this.l).rgb();
};
function d3_hcl_lab(h, c, l) {
if (isNaN(h)) h = 0;
if (isNaN(c)) c = 0;
return d3_lab(l, Math.cos(h *= d3_radians) * c, Math.sin(h) * c);
}
d3.lab = function(l, a, b) {
return arguments.length === 1 ? l instanceof d3_Lab ? d3_lab(l.l, l.a, l.b) : l instanceof d3_Hcl ? d3_hcl_lab(l.l, l.c, l.h) : d3_rgb_lab((l = d3.rgb(l)).r, l.g, l.b) : d3_lab(+l, +a, +b);
};
function d3_lab(l, a, b) {
return new d3_Lab(l, a, b);
}
function d3_Lab(l, a, b) {
this.l = l;
this.a = a;
this.b = b;
}
var d3_lab_K = 18;
var d3_lab_X = .95047, d3_lab_Y = 1, d3_lab_Z = 1.08883;
var d3_labPrototype = d3_Lab.prototype = new d3_Color();
d3_labPrototype.brighter = function(k) {
return d3_lab(Math.min(100, this.l + d3_lab_K * (arguments.length ? k : 1)), this.a, this.b);
};
d3_labPrototype.darker = function(k) {
return d3_lab(Math.max(0, this.l - d3_lab_K * (arguments.length ? k : 1)), this.a, this.b);
};
d3_labPrototype.rgb = function() {
return d3_lab_rgb(this.l, this.a, this.b);
};
function d3_lab_rgb(l, a, b) {
var y = (l + 16) / 116, x = y + a / 500, z = y - b / 200;
x = d3_lab_xyz(x) * d3_lab_X;
y = d3_lab_xyz(y) * d3_lab_Y;
z = d3_lab_xyz(z) * d3_lab_Z;
return d3_rgb(d3_xyz_rgb(3.2404542 * x - 1.5371385 * y - .4985314 * z), d3_xyz_rgb(-.969266 * x + 1.8760108 * y + .041556 * z), d3_xyz_rgb(.0556434 * x - .2040259 * y + 1.0572252 * z));
}
function d3_lab_hcl(l, a, b) {
return l > 0 ? d3_hcl(Math.atan2(b, a) * d3_degrees, Math.sqrt(a * a + b * b), l) : d3_hcl(NaN, NaN, l);
}
function d3_lab_xyz(x) {
return x > .206893034 ? x * x * x : (x - 4 / 29) / 7.787037;
}
function d3_xyz_lab(x) {
return x > .008856 ? Math.pow(x, 1 / 3) : 7.787037 * x + 4 / 29;
}
function d3_xyz_rgb(r) {
return Math.round(255 * (r <= .00304 ? 12.92 * r : 1.055 * Math.pow(r, 1 / 2.4) - .055));
}
d3.rgb = function(r, g, b) {
return arguments.length === 1 ? r instanceof d3_Rgb ? d3_rgb(r.r, r.g, r.b) : d3_rgb_parse("" + r, d3_rgb, d3_hsl_rgb) : d3_rgb(~~r, ~~g, ~~b);
};
function d3_rgbNumber(value) {
return d3_rgb(value >> 16, value >> 8 & 255, value & 255);
}
function d3_rgbString(value) {
return d3_rgbNumber(value) + "";
}
function d3_rgb(r, g, b) {
return new d3_Rgb(r, g, b);
}
function d3_Rgb(r, g, b) {
this.r = r;
this.g = g;
this.b = b;
}
var d3_rgbPrototype = d3_Rgb.prototype = new d3_Color();
d3_rgbPrototype.brighter = function(k) {
k = Math.pow(.7, arguments.length ? k : 1);
var r = this.r, g = this.g, b = this.b, i = 30;
if (!r && !g && !b) return d3_rgb(i, i, i);
if (r && r < i) r = i;
if (g && g < i) g = i;
if (b && b < i) b = i;
return d3_rgb(Math.min(255, ~~(r / k)), Math.min(255, ~~(g / k)), Math.min(255, ~~(b / k)));
};
d3_rgbPrototype.darker = function(k) {
k = Math.pow(.7, arguments.length ? k : 1);
return d3_rgb(~~(k * this.r), ~~(k * this.g), ~~(k * this.b));
};
d3_rgbPrototype.hsl = function() {
return d3_rgb_hsl(this.r, this.g, this.b);
};
d3_rgbPrototype.toString = function() {
return "#" + d3_rgb_hex(this.r) + d3_rgb_hex(this.g) + d3_rgb_hex(this.b);
};
function d3_rgb_hex(v) {
return v < 16 ? "0" + Math.max(0, v).toString(16) : Math.min(255, v).toString(16);
}
function d3_rgb_parse(format, rgb, hsl) {
var r = 0, g = 0, b = 0, m1, m2, name;
m1 = /([a-z]+)\((.*)\)/i.exec(format);
if (m1) {
m2 = m1[2].split(",");
switch (m1[1]) {
case "hsl":
{
return hsl(parseFloat(m2[0]), parseFloat(m2[1]) / 100, parseFloat(m2[2]) / 100);
}
case "rgb":
{
return rgb(d3_rgb_parseNumber(m2[0]), d3_rgb_parseNumber(m2[1]), d3_rgb_parseNumber(m2[2]));
}
}
}
if (name = d3_rgb_names.get(format)) return rgb(name.r, name.g, name.b);
if (format != null && format.charAt(0) === "#") {
if (format.length === 4) {
r = format.charAt(1);
r += r;
g = format.charAt(2);
g += g;
b = format.charAt(3);
b += b;
} else if (format.length === 7) {
r = format.substring(1, 3);
g = format.substring(3, 5);
b = format.substring(5, 7);
}
r = parseInt(r, 16);
g = parseInt(g, 16);
b = parseInt(b, 16);
}
return rgb(r, g, b);
}
function d3_rgb_hsl(r, g, b) {
var min = Math.min(r /= 255, g /= 255, b /= 255), max = Math.max(r, g, b), d = max - min, h, s, l = (max + min) / 2;
if (d) {
s = l < .5 ? d / (max + min) : d / (2 - max - min);
if (r == max) h = (g - b) / d + (g < b ? 6 : 0); else if (g == max) h = (b - r) / d + 2; else h = (r - g) / d + 4;
h *= 60;
} else {
h = NaN;
s = l > 0 && l < 1 ? 0 : h;
}
return d3_hsl(h, s, l);
}
function d3_rgb_lab(r, g, b) {
r = d3_rgb_xyz(r);
g = d3_rgb_xyz(g);
b = d3_rgb_xyz(b);
var x = d3_xyz_lab((.4124564 * r + .3575761 * g + .1804375 * b) / d3_lab_X), y = d3_xyz_lab((.2126729 * r + .7151522 * g + .072175 * b) / d3_lab_Y), z = d3_xyz_lab((.0193339 * r + .119192 * g + .9503041 * b) / d3_lab_Z);
return d3_lab(116 * y - 16, 500 * (x - y), 200 * (y - z));
}
function d3_rgb_xyz(r) {
return (r /= 255) <= .04045 ? r / 12.92 : Math.pow((r + .055) / 1.055, 2.4);
}
function d3_rgb_parseNumber(c) {
var f = parseFloat(c);
return c.charAt(c.length - 1) === "%" ? Math.round(f * 2.55) : f;
}
var d3_rgb_names = d3.map({
aliceblue: 15792383,
antiquewhite: 16444375,
aqua: 65535,
aquamarine: 8388564,
azure: 15794175,
beige: 16119260,
bisque: 16770244,
black: 0,
blanchedalmond: 16772045,
blue: 255,
blueviolet: 9055202,
brown: 10824234,
burlywood: 14596231,
cadetblue: 6266528,
chartreuse: 8388352,
chocolate: 13789470,
coral: 16744272,
cornflowerblue: 6591981,
cornsilk: 16775388,
crimson: 14423100,
cyan: 65535,
darkblue: 139,
darkcyan: 35723,
darkgoldenrod: 12092939,
darkgray: 11119017,
darkgreen: 25600,
darkgrey: 11119017,
darkkhaki: 12433259,
darkmagenta: 9109643,
darkolivegreen: 5597999,
darkorange: 16747520,
darkorchid: 10040012,
darkred: 9109504,
darksalmon: 15308410,
darkseagreen: 9419919,
darkslateblue: 4734347,
darkslategray: 3100495,
darkslategrey: 3100495,
darkturquoise: 52945,
darkviolet: 9699539,
deeppink: 16716947,
deepskyblue: 49151,
dimgray: 6908265,
dimgrey: 6908265,
dodgerblue: 2003199,
firebrick: 11674146,
floralwhite: 16775920,
forestgreen: 2263842,
fuchsia: 16711935,
gainsboro: 14474460,
ghostwhite: 16316671,
gold: 16766720,
goldenrod: 14329120,
gray: 8421504,
green: 32768,
greenyellow: 11403055,
grey: 8421504,
honeydew: 15794160,
hotpink: 16738740,
indianred: 13458524,
indigo: 4915330,
ivory: 16777200,
khaki: 15787660,
lavender: 15132410,
lavenderblush: 16773365,
lawngreen: 8190976,
lemonchiffon: 16775885,
lightblue: 11393254,
lightcoral: 15761536,
lightcyan: 14745599,
lightgoldenrodyellow: 16448210,
lightgray: 13882323,
lightgreen: 9498256,
lightgrey: 13882323,
lightpink: 16758465,
lightsalmon: 16752762,
lightseagreen: 2142890,
lightskyblue: 8900346,
lightslategray: 7833753,
lightslategrey: 7833753,
lightsteelblue: 11584734,
lightyellow: 16777184,
lime: 65280,
limegreen: 3329330,
linen: 16445670,
magenta: 16711935,
maroon: 8388608,
mediumaquamarine: 6737322,
mediumblue: 205,
mediumorchid: 12211667,
mediumpurple: 9662683,
mediumseagreen: 3978097,
mediumslateblue: 8087790,
mediumspringgreen: 64154,
mediumturquoise: 4772300,
mediumvioletred: 13047173,
midnightblue: 1644912,
mintcream: 16121850,
mistyrose: 16770273,
moccasin: 16770229,
navajowhite: 16768685,
navy: 128,
oldlace: 16643558,
olive: 8421376,
olivedrab: 7048739,
orange: 16753920,
orangered: 16729344,
orchid: 14315734,
palegoldenrod: 15657130,
palegreen: 10025880,
paleturquoise: 11529966,
palevioletred: 14381203,
papayawhip: 16773077,
peachpuff: 16767673,
peru: 13468991,
pink: 16761035,
plum: 14524637,
powderblue: 11591910,
purple: 8388736,
red: 16711680,
rosybrown: 12357519,
royalblue: 4286945,
saddlebrown: 9127187,
salmon: 16416882,
sandybrown: 16032864,
seagreen: 3050327,
seashell: 16774638,
sienna: 10506797,
silver: 12632256,
skyblue: 8900331,
slateblue: 6970061,
slategray: 7372944,
slategrey: 7372944,
snow: 16775930,
springgreen: 65407,
steelblue: 4620980,
tan: 13808780,
teal: 32896,
thistle: 14204888,
tomato: 16737095,
turquoise: 4251856,
violet: 15631086,
wheat: 16113331,
white: 16777215,
whitesmoke: 16119285,
yellow: 16776960,
yellowgreen: 10145074
});
d3_rgb_names.forEach(function(key, value) {
d3_rgb_names.set(key, d3_rgbNumber(value));
});
function d3_functor(v) {
return typeof v === "function" ? v : function() {
return v;
};
}
d3.functor = d3_functor;
function d3_identity(d) {
return d;
}
d3.xhr = d3_xhrType(d3_identity);
function d3_xhrType(response) {
return function(url, mimeType, callback) {
if (arguments.length === 2 && typeof mimeType === "function") callback = mimeType,
mimeType = null;
return d3_xhr(url, mimeType, response, callback);
};
}
function d3_xhr(url, mimeType, response, callback) {
var xhr = {}, dispatch = d3.dispatch("beforesend", "progress", "load", "error"), headers = {}, request = new XMLHttpRequest(), responseType = null;
if (d3_window.XDomainRequest && !("withCredentials" in request) && /^(http(s)?:)?\/\//.test(url)) request = new XDomainRequest();
"onload" in request ? request.onload = request.onerror = respond : request.onreadystatechange = function() {
request.readyState > 3 && respond();
};
function respond() {
var status = request.status, result;
if (!status && request.responseText || status >= 200 && status < 300 || status === 304) {
try {
result = response.call(xhr, request);
} catch (e) {
dispatch.error.call(xhr, e);
return;
}
dispatch.load.call(xhr, result);
} else {
dispatch.error.call(xhr, request);
}
}
request.onprogress = function(event) {
var o = d3.event;
d3.event = event;
try {
dispatch.progress.call(xhr, request);
} finally {
d3.event = o;
}
};
xhr.header = function(name, value) {
name = (name + "").toLowerCase();
if (arguments.length < 2) return headers[name];
if (value == null) delete headers[name]; else headers[name] = value + "";
return xhr;
};
xhr.mimeType = function(value) {
if (!arguments.length) return mimeType;
mimeType = value == null ? null : value + "";
return xhr;
};
xhr.responseType = function(value) {
if (!arguments.length) return responseType;
responseType = value;
return xhr;
};
xhr.response = function(value) {
response = value;
return xhr;
};
[ "get", "post" ].forEach(function(method) {
xhr[method] = function() {
return xhr.send.apply(xhr, [ method ].concat(d3_array(arguments)));
};
});
xhr.send = function(method, data, callback) {
if (arguments.length === 2 && typeof data === "function") callback = data, data = null;
request.open(method, url, true);
if (mimeType != null && !("accept" in headers)) headers["accept"] = mimeType + ",*/*";
if (request.setRequestHeader) for (var name in headers) request.setRequestHeader(name, headers[name]);
if (mimeType != null && request.overrideMimeType) request.overrideMimeType(mimeType);
if (responseType != null) request.responseType = responseType;
if (callback != null) xhr.on("error", callback).on("load", function(request) {
callback(null, request);
});
dispatch.beforesend.call(xhr, request);
request.send(data == null ? null : data);
return xhr;
};
xhr.abort = function() {
request.abort();
return xhr;
};
d3.rebind(xhr, dispatch, "on");
return callback == null ? xhr : xhr.get(d3_xhr_fixCallback(callback));
}
function d3_xhr_fixCallback(callback) {
return callback.length === 1 ? function(error, request) {
callback(error == null ? request : null);
} : callback;
}
d3.dsv = function(delimiter, mimeType) {
var reFormat = new RegExp('["' + delimiter + "\n]"), delimiterCode = delimiter.charCodeAt(0);
function dsv(url, row, callback) {
if (arguments.length < 3) callback = row, row = null;
var xhr = d3.xhr(url, mimeType, callback);
xhr.row = function(_) {
return arguments.length ? xhr.response((row = _) == null ? response : typedResponse(_)) : row;
};
return xhr.row(row);
}
function response(request) {
return dsv.parse(request.responseText);
}
function typedResponse(f) {
return function(request) {
return dsv.parse(request.responseText, f);
};
}
dsv.parse = function(text, f) {
var o;
return dsv.parseRows(text, function(row, i) {
if (o) return o(row, i - 1);
var a = new Function("d", "return {" + row.map(function(name, i) {
return JSON.stringify(name) + ": d[" + i + "]";
}).join(",") + "}");
o = f ? function(row, i) {
return f(a(row), i);
} : a;
});
};
dsv.parseRows = function(text, f) {
var EOL = {}, EOF = {}, rows = [], N = text.length, I = 0, n = 0, t, eol;
function token() {
if (I >= N) return EOF;
if (eol) return eol = false, EOL;
var j = I;
if (text.charCodeAt(j) === 34) {
var i = j;
while (i++ < N) {
if (text.charCodeAt(i) === 34) {
if (text.charCodeAt(i + 1) !== 34) break;
++i;
}
}
I = i + 2;
var c = text.charCodeAt(i + 1);
if (c === 13) {
eol = true;
if (text.charCodeAt(i + 2) === 10) ++I;
} else if (c === 10) {
eol = true;
}
return text.substring(j + 1, i).replace(/""/g, '"');
}
while (I < N) {
var c = text.charCodeAt(I++), k = 1;
if (c === 10) eol = true; else if (c === 13) {
eol = true;
if (text.charCodeAt(I) === 10) ++I, ++k;
} else if (c !== delimiterCode) continue;
return text.substring(j, I - k);
}
return text.substring(j);
}
while ((t = token()) !== EOF) {
var a = [];
while (t !== EOL && t !== EOF) {
a.push(t);
t = token();
}
if (f && !(a = f(a, n++))) continue;
rows.push(a);
}
return rows;
};
dsv.format = function(rows) {
if (Array.isArray(rows[0])) return dsv.formatRows(rows);
var fieldSet = new d3_Set(), fields = [];
rows.forEach(function(row) {
for (var field in row) {
if (!fieldSet.has(field)) {
fields.push(fieldSet.add(field));
}
}
});
return [ fields.map(formatValue).join(delimiter) ].concat(rows.map(function(row) {
return fields.map(function(field) {
return formatValue(row[field]);
}).join(delimiter);
})).join("\n");
};
dsv.formatRows = function(rows) {
return rows.map(formatRow).join("\n");
};
function formatRow(row) {
return row.map(formatValue).join(delimiter);
}
function formatValue(text) {
return reFormat.test(text) ? '"' + text.replace(/\"/g, '""') + '"' : text;
}
return dsv;
};
d3.csv = d3.dsv(",", "text/csv");
d3.tsv = d3.dsv(" ", "text/tab-separated-values");
var d3_timer_queueHead, d3_timer_queueTail, d3_timer_interval, d3_timer_timeout, d3_timer_active, d3_timer_frame = d3_window[d3_vendorSymbol(d3_window, "requestAnimationFrame")] || function(callback) {
setTimeout(callback, 17);
};
d3.timer = function(callback, delay, then) {
var n = arguments.length;
if (n < 2) delay = 0;
if (n < 3) then = Date.now();
var time = then + delay, timer = {
c: callback,
t: time,
f: false,
n: null
};
if (d3_timer_queueTail) d3_timer_queueTail.n = timer; else d3_timer_queueHead = timer;
d3_timer_queueTail = timer;
if (!d3_timer_interval) {
d3_timer_timeout = clearTimeout(d3_timer_timeout);
d3_timer_interval = 1;
d3_timer_frame(d3_timer_step);
}
};
function d3_timer_step() {
var now = d3_timer_mark(), delay = d3_timer_sweep() - now;
if (delay > 24) {
if (isFinite(delay)) {
clearTimeout(d3_timer_timeout);
d3_timer_timeout = setTimeout(d3_timer_step, delay);
}
d3_timer_interval = 0;
} else {
d3_timer_interval = 1;
d3_timer_frame(d3_timer_step);
}
}
d3.timer.flush = function() {
d3_timer_mark();
d3_timer_sweep();
};
function d3_timer_mark() {
var now = Date.now();
d3_timer_active = d3_timer_queueHead;
while (d3_timer_active) {
if (now >= d3_timer_active.t) d3_timer_active.f = d3_timer_active.c(now - d3_timer_active.t);
d3_timer_active = d3_timer_active.n;
}
return now;
}
function d3_timer_sweep() {
var t0, t1 = d3_timer_queueHead, time = Infinity;
while (t1) {
if (t1.f) {
t1 = t0 ? t0.n = t1.n : d3_timer_queueHead = t1.n;
} else {
if (t1.t < time) time = t1.t;
t1 = (t0 = t1).n;
}
}
d3_timer_queueTail = t0;
return time;
}
var d3_format_decimalPoint = ".", d3_format_thousandsSeparator = ",", d3_format_grouping = [ 3, 3 ], d3_format_currencySymbol = "$";
var d3_formatPrefixes = [ "y", "z", "a", "f", "p", "n", "µ", "m", "", "k", "M", "G", "T", "P", "E", "Z", "Y" ].map(d3_formatPrefix);
d3.formatPrefix = function(value, precision) {
var i = 0;
if (value) {
if (value < 0) value *= -1;
if (precision) value = d3.round(value, d3_format_precision(value, precision));
i = 1 + Math.floor(1e-12 + Math.log(value) / Math.LN10);
i = Math.max(-24, Math.min(24, Math.floor((i <= 0 ? i + 1 : i - 1) / 3) * 3));
}
return d3_formatPrefixes[8 + i / 3];
};
function d3_formatPrefix(d, i) {
var k = Math.pow(10, abs(8 - i) * 3);
return {
scale: i > 8 ? function(d) {
return d / k;
} : function(d) {
return d * k;
},
symbol: d
};
}
d3.round = function(x, n) {
return n ? Math.round(x * (n = Math.pow(10, n))) / n : Math.round(x);
};
d3.format = function(specifier) {
var match = d3_format_re.exec(specifier), fill = match[1] || " ", align = match[2] || ">", sign = match[3] || "", symbol = match[4] || "", zfill = match[5], width = +match[6], comma = match[7], precision = match[8], type = match[9], scale = 1, suffix = "", integer = false;
if (precision) precision = +precision.substring(1);
if (zfill || fill === "0" && align === "=") {
zfill = fill = "0";
align = "=";
if (comma) width -= Math.floor((width - 1) / 4);
}
switch (type) {
case "n":
comma = true;
type = "g";
break;
case "%":
scale = 100;
suffix = "%";
type = "f";
break;
case "p":
scale = 100;
suffix = "%";
type = "r";
break;
case "b":
case "o":
case "x":
case "X":
if (symbol === "#") symbol = "0" + type.toLowerCase();
case "c":
case "d":
integer = true;
precision = 0;
break;
case "s":
scale = -1;
type = "r";
break;
}
if (symbol === "#") symbol = ""; else if (symbol === "$") symbol = d3_format_currencySymbol;
if (type == "r" && !precision) type = "g";
if (precision != null) {
if (type == "g") precision = Math.max(1, Math.min(21, precision)); else if (type == "e" || type == "f") precision = Math.max(0, Math.min(20, precision));
}
type = d3_format_types.get(type) || d3_format_typeDefault;
var zcomma = zfill && comma;
return function(value) {
if (integer && value % 1) return "";
var negative = value < 0 || value === 0 && 1 / value < 0 ? (value = -value, "-") : sign;
if (scale < 0) {
var prefix = d3.formatPrefix(value, precision);
value = prefix.scale(value);
suffix = prefix.symbol;
} else {
value *= scale;
}
value = type(value, precision);
var i = value.lastIndexOf("."), before = i < 0 ? value : value.substring(0, i), after = i < 0 ? "" : d3_format_decimalPoint + value.substring(i + 1);
if (!zfill && comma) before = d3_format_group(before);
var length = symbol.length + before.length + after.length + (zcomma ? 0 : negative.length), padding = length < width ? new Array(length = width - length + 1).join(fill) : "";
if (zcomma) before = d3_format_group(padding + before);
negative += symbol;
value = before + after;
return (align === "<" ? negative + value + padding : align === ">" ? padding + negative + value : align === "^" ? padding.substring(0, length >>= 1) + negative + value + padding.substring(length) : negative + (zcomma ? value : padding + value)) + suffix;
};
};
var d3_format_re = /(?:([^{])?([<>=^]))?([+\- ])?([$#])?(0)?(\d+)?(,)?(\.-?\d+)?([a-z%])?/i;
var d3_format_types = d3.map({
b: function(x) {
return x.toString(2);
},
c: function(x) {
return String.fromCharCode(x);
},
o: function(x) {
return x.toString(8);
},
x: function(x) {
return x.toString(16);
},
X: function(x) {
return x.toString(16).toUpperCase();
},
g: function(x, p) {
return x.toPrecision(p);
},
e: function(x, p) {
return x.toExponential(p);
},
f: function(x, p) {
return x.toFixed(p);
},
r: function(x, p) {
return (x = d3.round(x, d3_format_precision(x, p))).toFixed(Math.max(0, Math.min(20, d3_format_precision(x * (1 + 1e-15), p))));
}
});
function d3_format_precision(x, p) {
return p - (x ? Math.ceil(Math.log(x) / Math.LN10) : 1);
}
function d3_format_typeDefault(x) {
return x + "";
}
var d3_format_group = d3_identity;
if (d3_format_grouping) {
var d3_format_groupingLength = d3_format_grouping.length;
d3_format_group = function(value) {
var i = value.length, t = [], j = 0, g = d3_format_grouping[0];
while (i > 0 && g > 0) {
t.push(value.substring(i -= g, i + g));
g = d3_format_grouping[j = (j + 1) % d3_format_groupingLength];
}
return t.reverse().join(d3_format_thousandsSeparator);
};
}
d3.geo = {};
function d3_adder() {}
d3_adder.prototype = {
s: 0,
t: 0,
add: function(y) {
d3_adderSum(y, this.t, d3_adderTemp);
d3_adderSum(d3_adderTemp.s, this.s, this);
if (this.s) this.t += d3_adderTemp.t; else this.s = d3_adderTemp.t;
},
reset: function() {
this.s = this.t = 0;
},
valueOf: function() {
return this.s;
}
};
var d3_adderTemp = new d3_adder();
function d3_adderSum(a, b, o) {
var x = o.s = a + b, bv = x - a, av = x - bv;
o.t = a - av + (b - bv);
}
d3.geo.stream = function(object, listener) {
if (object && d3_geo_streamObjectType.hasOwnProperty(object.type)) {
d3_geo_streamObjectType[object.type](object, listener);
} else {
d3_geo_streamGeometry(object, listener);
}
};
function d3_geo_streamGeometry(geometry, listener) {
if (geometry && d3_geo_streamGeometryType.hasOwnProperty(geometry.type)) {
d3_geo_streamGeometryType[geometry.type](geometry, listener);
}
}
var d3_geo_streamObjectType = {
Feature: function(feature, listener) {
d3_geo_streamGeometry(feature.geometry, listener);
},
FeatureCollection: function(object, listener) {
var features = object.features, i = -1, n = features.length;
while (++i < n) d3_geo_streamGeometry(features[i].geometry, listener);
}
};
var d3_geo_streamGeometryType = {
Sphere: function(object, listener) {
listener.sphere();
},
Point: function(object, listener) {
object = object.coordinates;
listener.point(object[0], object[1], object[2]);
},
MultiPoint: function(object, listener) {
var coordinates = object.coordinates, i = -1, n = coordinates.length;
while (++i < n) object = coordinates[i], listener.point(object[0], object[1], object[2]);
},
LineString: function(object, listener) {
d3_geo_streamLine(object.coordinates, listener, 0);
},
MultiLineString: function(object, listener) {
var coordinates = object.coordinates, i = -1, n = coordinates.length;
while (++i < n) d3_geo_streamLine(coordinates[i], listener, 0);
},
Polygon: function(object, listener) {
d3_geo_streamPolygon(object.coordinates, listener);
},
MultiPolygon: function(object, listener) {
var coordinates = object.coordinates, i = -1, n = coordinates.length;
while (++i < n) d3_geo_streamPolygon(coordinates[i], listener);
},
GeometryCollection: function(object, listener) {
var geometries = object.geometries, i = -1, n = geometries.length;
while (++i < n) d3_geo_streamGeometry(geometries[i], listener);
}
};
function d3_geo_streamLine(coordinates, listener, closed) {
var i = -1, n = coordinates.length - closed, coordinate;
listener.lineStart();
while (++i < n) coordinate = coordinates[i], listener.point(coordinate[0], coordinate[1], coordinate[2]);
listener.lineEnd();
}
function d3_geo_streamPolygon(coordinates, listener) {
var i = -1, n = coordinates.length;
listener.polygonStart();
while (++i < n) d3_geo_streamLine(coordinates[i], listener, 1);
listener.polygonEnd();
}
d3.geo.area = function(object) {
d3_geo_areaSum = 0;
d3.geo.stream(object, d3_geo_area);
return d3_geo_areaSum;
};
var d3_geo_areaSum, d3_geo_areaRingSum = new d3_adder();
var d3_geo_area = {
sphere: function() {
d3_geo_areaSum += 4 * π;
},
point: d3_noop,
lineStart: d3_noop,
lineEnd: d3_noop,
polygonStart: function() {
d3_geo_areaRingSum.reset();
d3_geo_area.lineStart = d3_geo_areaRingStart;
},
polygonEnd: function() {
var area = 2 * d3_geo_areaRingSum;
d3_geo_areaSum += area < 0 ? 4 * π + area : area;
d3_geo_area.lineStart = d3_geo_area.lineEnd = d3_geo_area.point = d3_noop;
}
};
function d3_geo_areaRingStart() {
var λ00, φ00, λ0, cosφ0, sinφ0;
d3_geo_area.point = function(λ, φ) {
d3_geo_area.point = nextPoint;
λ0 = (λ00 = λ) * d3_radians, cosφ0 = Math.cos(φ = (φ00 = φ) * d3_radians / 2 + π / 4),
sinφ0 = Math.sin(φ);
};
function nextPoint(λ, φ) {
λ *= d3_radians;
φ = φ * d3_radians / 2 + π / 4;
var dλ = λ - λ0, cosφ = Math.cos(φ), sinφ = Math.sin(φ), k = sinφ0 * sinφ, u = cosφ0 * cosφ + k * Math.cos(dλ), v = k * Math.sin(dλ);
d3_geo_areaRingSum.add(Math.atan2(v, u));
λ0 = λ, cosφ0 = cosφ, sinφ0 = sinφ;
}
d3_geo_area.lineEnd = function() {
nextPoint(λ00, φ00);
};
}
function d3_geo_cartesian(spherical) {
var λ = spherical[0], φ = spherical[1], cosφ = Math.cos(φ);
return [ cosφ * Math.cos(λ), cosφ * Math.sin(λ), Math.sin(φ) ];
}
function d3_geo_cartesianDot(a, b) {
return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
}
function d3_geo_cartesianCross(a, b) {
return [ a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0] ];
}
function d3_geo_cartesianAdd(a, b) {
a[0] += b[0];
a[1] += b[1];
a[2] += b[2];
}
function d3_geo_cartesianScale(vector, k) {
return [ vector[0] * k, vector[1] * k, vector[2] * k ];
}
function d3_geo_cartesianNormalize(d) {
var l = Math.sqrt(d[0] * d[0] + d[1] * d[1] + d[2] * d[2]);
d[0] /= l;
d[1] /= l;
d[2] /= l;
}
function d3_geo_spherical(cartesian) {
return [ Math.atan2(cartesian[1], cartesian[0]), d3_asin(cartesian[2]) ];
}
function d3_geo_sphericalEqual(a, b) {
return abs(a[0] - b[0]) < ε && abs(a[1] - b[1]) < ε;
}
d3.geo.bounds = function() {
var λ0, φ0, λ1, φ1, λ_, λ__, φ__, p0, dλSum, ranges, range;
var bound = {
point: point,
lineStart: lineStart,
lineEnd: lineEnd,
polygonStart: function() {
bound.point = ringPoint;
bound.lineStart = ringStart;
bound.lineEnd = ringEnd;
dλSum = 0;
d3_geo_area.polygonStart();
},
polygonEnd: function() {
d3_geo_area.polygonEnd();
bound.point = point;
bound.lineStart = lineStart;
bound.lineEnd = lineEnd;
if (d3_geo_areaRingSum < 0) λ0 = -(λ1 = 180), φ0 = -(φ1 = 90); else if (dλSum > ε) φ1 = 90; else if (dλSum < -ε) φ0 = -90;
range[0] = λ0, range[1] = λ1;
}
};
function point(λ, φ) {
ranges.push(range = [ λ0 = λ, λ1 = λ ]);
if (φ < φ0) φ0 = φ;
if (φ > φ1) φ1 = φ;
}
function linePoint(λ, φ) {
var p = d3_geo_cartesian([ λ * d3_radians, φ * d3_radians ]);
if (p0) {
var normal = d3_geo_cartesianCross(p0, p), equatorial = [ normal[1], -normal[0], 0 ], inflection = d3_geo_cartesianCross(equatorial, normal);
d3_geo_cartesianNormalize(inflection);
inflection = d3_geo_spherical(inflection);
var dλ = λ - λ_, s = dλ > 0 ? 1 : -1, λi = inflection[0] * d3_degrees * s, antimeridian = abs(dλ) > 180;
if (antimeridian ^ (s * λ_ < λi && λi < s * λ)) {
var φi = inflection[1] * d3_degrees;
if (φi > φ1) φ1 = φi;
} else if (λi = (λi + 360) % 360 - 180, antimeridian ^ (s * λ_ < λi && λi < s * λ)) {
var φi = -inflection[1] * d3_degrees;
if (φi < φ0) φ0 = φi;
} else {
if (φ < φ0) φ0 = φ;
if (φ > φ1) φ1 = φ;
}
if (antimeridian) {
if (λ < λ_) {
if (angle(λ0, λ) > angle(λ0, λ1)) λ1 = λ;
} else {
if (angle(λ, λ1) > angle(λ0, λ1)) λ0 = λ;
}
} else {
if (λ1 >= λ0) {
if (λ < λ0) λ0 = λ;
if (λ > λ1) λ1 = λ;
} else {
if (λ > λ_) {
if (angle(λ0, λ) > angle(λ0, λ1)) λ1 = λ;
} else {
if (angle(λ, λ1) > angle(λ0, λ1)) λ0 = λ;
}
}
}
} else {
point(λ, φ);
}
p0 = p, λ_ = λ;
}
function lineStart() {
bound.point = linePoint;
}
function lineEnd() {
range[0] = λ0, range[1] = λ1;
bound.point = point;
p0 = null;
}
function ringPoint(λ, φ) {
if (p0) {
var dλ = λ - λ_;
dλSum += abs(dλ) > 180 ? dλ + (dλ > 0 ? 360 : -360) : dλ;
} else λ__ = λ, φ__ = φ;
d3_geo_area.point(λ, φ);
linePoint(λ, φ);
}
function ringStart() {
d3_geo_area.lineStart();
}
function ringEnd() {
ringPoint(λ__, φ__);
d3_geo_area.lineEnd();
if (abs(dλSum) > ε) λ0 = -(λ1 = 180);
range[0] = λ0, range[1] = λ1;
p0 = null;
}
function angle(λ0, λ1) {
return (λ1 -= λ0) < 0 ? λ1 + 360 : λ1;
}
function compareRanges(a, b) {
return a[0] - b[0];
}
function withinRange(x, range) {
return range[0] <= range[1] ? range[0] <= x && x <= range[1] : x < range[0] || range[1] < x;
}
return function(feature) {
φ1 = λ1 = -(λ0 = φ0 = Infinity);
ranges = [];
d3.geo.stream(feature, bound);
var n = ranges.length;
if (n) {
ranges.sort(compareRanges);
for (var i = 1, a = ranges[0], b, merged = [ a ]; i < n; ++i) {
b = ranges[i];
if (withinRange(b[0], a) || withinRange(b[1], a)) {
if (angle(a[0], b[1]) > angle(a[0], a[1])) a[1] = b[1];
if (angle(b[0], a[1]) > angle(a[0], a[1])) a[0] = b[0];
} else {
merged.push(a = b);
}
}
var best = -Infinity, dλ;
for (var n = merged.length - 1, i = 0, a = merged[n], b; i <= n; a = b, ++i) {
b = merged[i];
if ((dλ = angle(a[1], b[0])) > best) best = dλ, λ0 = b[0], λ1 = a[1];
}
}
ranges = range = null;
return λ0 === Infinity || φ0 === Infinity ? [ [ NaN, NaN ], [ NaN, NaN ] ] : [ [ λ0, φ0 ], [ λ1, φ1 ] ];
};
}();
d3.geo.centroid = function(object) {
d3_geo_centroidW0 = d3_geo_centroidW1 = d3_geo_centroidX0 = d3_geo_centroidY0 = d3_geo_centroidZ0 = d3_geo_centroidX1 = d3_geo_centroidY1 = d3_geo_centroidZ1 = d3_geo_centroidX2 = d3_geo_centroidY2 = d3_geo_centroidZ2 = 0;
d3.geo.stream(object, d3_geo_centroid);
var x = d3_geo_centroidX2, y = d3_geo_centroidY2, z = d3_geo_centroidZ2, m = x * x + y * y + z * z;
if (m < ε2) {
x = d3_geo_centroidX1, y = d3_geo_centroidY1, z = d3_geo_centroidZ1;
if (d3_geo_centroidW1 < ε) x = d3_geo_centroidX0, y = d3_geo_centroidY0, z = d3_geo_centroidZ0;
m = x * x + y * y + z * z;
if (m < ε2) return [ NaN, NaN ];
}
return [ Math.atan2(y, x) * d3_degrees, d3_asin(z / Math.sqrt(m)) * d3_degrees ];
};
var d3_geo_centroidW0, d3_geo_centroidW1, d3_geo_centroidX0, d3_geo_centroidY0, d3_geo_centroidZ0, d3_geo_centroidX1, d3_geo_centroidY1, d3_geo_centroidZ1, d3_geo_centroidX2, d3_geo_centroidY2, d3_geo_centroidZ2;
var d3_geo_centroid = {
sphere: d3_noop,
point: d3_geo_centroidPoint,
lineStart: d3_geo_centroidLineStart,
lineEnd: d3_geo_centroidLineEnd,
polygonStart: function() {
d3_geo_centroid.lineStart = d3_geo_centroidRingStart;
},
polygonEnd: function() {
d3_geo_centroid.lineStart = d3_geo_centroidLineStart;
}
};
function d3_geo_centroidPoint(λ, φ) {
λ *= d3_radians;
var cosφ = Math.cos(φ *= d3_radians);
d3_geo_centroidPointXYZ(cosφ * Math.cos(λ), cosφ * Math.sin(λ), Math.sin(φ));
}
function d3_geo_centroidPointXYZ(x, y, z) {
++d3_geo_centroidW0;
d3_geo_centroidX0 += (x - d3_geo_centroidX0) / d3_geo_centroidW0;
d3_geo_centroidY0 += (y - d3_geo_centroidY0) / d3_geo_centroidW0;
d3_geo_centroidZ0 += (z - d3_geo_centroidZ0) / d3_geo_centroidW0;
}
function d3_geo_centroidLineStart() {
var x0, y0, z0;
d3_geo_centroid.point = function(λ, φ) {
λ *= d3_radians;
var cosφ = Math.cos(φ *= d3_radians);
x0 = cosφ * Math.cos(λ);
y0 = cosφ * Math.sin(λ);
z0 = Math.sin(φ);
d3_geo_centroid.point = nextPoint;
d3_geo_centroidPointXYZ(x0, y0, z0);
};
function nextPoint(λ, φ) {
λ *= d3_radians;
var cosφ = Math.cos(φ *= d3_radians), x = cosφ * Math.cos(λ), y = cosφ * Math.sin(λ), z = Math.sin(φ), w = Math.atan2(Math.sqrt((w = y0 * z - z0 * y) * w + (w = z0 * x - x0 * z) * w + (w = x0 * y - y0 * x) * w), x0 * x + y0 * y + z0 * z);
d3_geo_centroidW1 += w;
d3_geo_centroidX1 += w * (x0 + (x0 = x));
d3_geo_centroidY1 += w * (y0 + (y0 = y));
d3_geo_centroidZ1 += w * (z0 + (z0 = z));
d3_geo_centroidPointXYZ(x0, y0, z0);
}
}
function d3_geo_centroidLineEnd() {
d3_geo_centroid.point = d3_geo_centroidPoint;
}
function d3_geo_centroidRingStart() {
var λ00, φ00, x0, y0, z0;
d3_geo_centroid.point = function(λ, φ) {
λ00 = λ, φ00 = φ;
d3_geo_centroid.point = nextPoint;
λ *= d3_radians;
var cosφ = Math.cos(φ *= d3_radians);
x0 = cosφ * Math.cos(λ);
y0 = cosφ * Math.sin(λ);
z0 = Math.sin(φ);
d3_geo_centroidPointXYZ(x0, y0, z0);
};
d3_geo_centroid.lineEnd = function() {
nextPoint(λ00, φ00);
d3_geo_centroid.lineEnd = d3_geo_centroidLineEnd;
d3_geo_centroid.point = d3_geo_centroidPoint;
};
function nextPoint(λ, φ) {
λ *= d3_radians;
var cosφ = Math.cos(φ *= d3_radians), x = cosφ * Math.cos(λ), y = cosφ * Math.sin(λ), z = Math.sin(φ), cx = y0 * z - z0 * y, cy = z0 * x - x0 * z, cz = x0 * y - y0 * x, m = Math.sqrt(cx * cx + cy * cy + cz * cz), u = x0 * x + y0 * y + z0 * z, v = m && -d3_acos(u) / m, w = Math.atan2(m, u);
d3_geo_centroidX2 += v * cx;
d3_geo_centroidY2 += v * cy;
d3_geo_centroidZ2 += v * cz;
d3_geo_centroidW1 += w;
d3_geo_centroidX1 += w * (x0 + (x0 = x));
d3_geo_centroidY1 += w * (y0 + (y0 = y));
d3_geo_centroidZ1 += w * (z0 + (z0 = z));
d3_geo_centroidPointXYZ(x0, y0, z0);
}
}
function d3_true() {
return true;
}
function d3_geo_clipPolygon(segments, compare, clipStartInside, interpolate, listener) {
var subject = [], clip = [];
segments.forEach(function(segment) {
if ((n = segment.length - 1) <= 0) return;
var n, p0 = segment[0], p1 = segment[n];
if (d3_geo_sphericalEqual(p0, p1)) {
listener.lineStart();
for (var i = 0; i < n; ++i) listener.point((p0 = segment[i])[0], p0[1]);
listener.lineEnd();
return;
}
var a = new d3_geo_clipPolygonIntersection(p0, segment, null, true), b = new d3_geo_clipPolygonIntersection(p0, null, a, false);
a.o = b;
subject.push(a);
clip.push(b);
a = new d3_geo_clipPolygonIntersection(p1, segment, null, false);
b = new d3_geo_clipPolygonIntersection(p1, null, a, true);
a.o = b;
subject.push(a);
clip.push(b);
});
clip.sort(compare);
d3_geo_clipPolygonLinkCircular(subject);
d3_geo_clipPolygonLinkCircular(clip);
if (!subject.length) return;
for (var i = 0, entry = clipStartInside, n = clip.length; i < n; ++i) {
clip[i].e = entry = !entry;
}
var start = subject[0], points, point;
while (1) {
var current = start, isSubject = true;
while (current.v) if ((current = current.n) === start) return;
points = current.z;
listener.lineStart();
do {
current.v = current.o.v = true;
if (current.e) {
if (isSubject) {
for (var i = 0, n = points.length; i < n; ++i) listener.point((point = points[i])[0], point[1]);
} else {
interpolate(current.x, current.n.x, 1, listener);
}
current = current.n;
} else {
if (isSubject) {
points = current.p.z;
for (var i = points.length - 1; i >= 0; --i) listener.point((point = points[i])[0], point[1]);
} else {
interpolate(current.x, current.p.x, -1, listener);
}
current = current.p;
}
current = current.o;
points = current.z;
isSubject = !isSubject;
} while (!current.v);
listener.lineEnd();
}
}
function d3_geo_clipPolygonLinkCircular(array) {
if (!(n = array.length)) return;
var n, i = 0, a = array[0], b;
while (++i < n) {
a.n = b = array[i];
b.p = a;
a = b;
}
a.n = b = array[0];
b.p = a;
}
function d3_geo_clipPolygonIntersection(point, points, other, entry) {
this.x = point;
this.z = points;
this.o = other;
this.e = entry;
this.v = false;
this.n = this.p = null;
}
function d3_geo_clip(pointVisible, clipLine, interpolate, clipStart) {
return function(rotate, listener) {
var line = clipLine(listener), rotatedClipStart = rotate.invert(clipStart[0], clipStart[1]);
var clip = {
point: point,
lineStart: lineStart,
lineEnd: lineEnd,
polygonStart: function() {
clip.point = pointRing;
clip.lineStart = ringStart;
clip.lineEnd = ringEnd;
segments = [];
polygon = [];
listener.polygonStart();
},
polygonEnd: function() {
clip.point = point;
clip.lineStart = lineStart;
clip.lineEnd = lineEnd;
segments = d3.merge(segments);
var clipStartInside = d3_geo_pointInPolygon(rotatedClipStart, polygon);
if (segments.length) {
d3_geo_clipPolygon(segments, d3_geo_clipSort, clipStartInside, interpolate, listener);
} else if (clipStartInside) {
listener.lineStart();
interpolate(null, null, 1, listener);
listener.lineEnd();
}
listener.polygonEnd();
segments = polygon = null;
},
sphere: function() {
listener.polygonStart();
listener.lineStart();
interpolate(null, null, 1, listener);
listener.lineEnd();
listener.polygonEnd();
}
};
function point(λ, φ) {
var point = rotate(λ, φ);
if (pointVisible(λ = point[0], φ = point[1])) listener.point(λ, φ);
}
function pointLine(λ, φ) {
var point = rotate(λ, φ);
line.point(point[0], point[1]);
}
function lineStart() {
clip.point = pointLine;
line.lineStart();
}
function lineEnd() {
clip.point = point;
line.lineEnd();
}
var segments;
var buffer = d3_geo_clipBufferListener(), ringListener = clipLine(buffer), polygon, ring;
function pointRing(λ, φ) {
ring.push([ λ, φ ]);
var point = rotate(λ, φ);
ringListener.point(point[0], point[1]);
}
function ringStart() {
ringListener.lineStart();
ring = [];
}
function ringEnd() {
pointRing(ring[0][0], ring[0][1]);
ringListener.lineEnd();
var clean = ringListener.clean(), ringSegments = buffer.buffer(), segment, n = ringSegments.length;
ring.pop();
polygon.push(ring);
ring = null;
if (!n) return;
if (clean & 1) {
segment = ringSegments[0];
var n = segment.length - 1, i = -1, point;
listener.lineStart();
while (++i < n) listener.point((point = segment[i])[0], point[1]);
listener.lineEnd();
return;
}
if (n > 1 && clean & 2) ringSegments.push(ringSegments.pop().concat(ringSegments.shift()));
segments.push(ringSegments.filter(d3_geo_clipSegmentLength1));
}
return clip;
};
}
function d3_geo_clipSegmentLength1(segment) {
return segment.length > 1;
}
function d3_geo_clipBufferListener() {
var lines = [], line;
return {
lineStart: function() {
lines.push(line = []);
},
point: function(λ, φ) {
line.push([ λ, φ ]);
},
lineEnd: d3_noop,
buffer: function() {
var buffer = lines;
lines = [];
line = null;
return buffer;
},
rejoin: function() {
if (lines.length > 1) lines.push(lines.pop().concat(lines.shift()));
}
};
}
function d3_geo_clipSort(a, b) {
return ((a = a.x)[0] < 0 ? a[1] - halfπ - ε : halfπ - a[1]) - ((b = b.x)[0] < 0 ? b[1] - halfπ - ε : halfπ - b[1]);
}
function d3_geo_pointInPolygon(point, polygon) {
var meridian = point[0], parallel = point[1], meridianNormal = [ Math.sin(meridian), -Math.cos(meridian), 0 ], polarAngle = 0, winding = 0;
d3_geo_areaRingSum.reset();
for (var i = 0, n = polygon.length; i < n; ++i) {
var ring = polygon[i], m = ring.length;
if (!m) continue;
var point0 = ring[0], λ0 = point0[0], φ0 = point0[1] / 2 + π / 4, sinφ0 = Math.sin(φ0), cosφ0 = Math.cos(φ0), j = 1;
while (true) {
if (j === m) j = 0;
point = ring[j];
var λ = point[0], φ = point[1] / 2 + π / 4, sinφ = Math.sin(φ), cosφ = Math.cos(φ), dλ = λ - λ0, antimeridian = abs(dλ) > π, k = sinφ0 * sinφ;
d3_geo_areaRingSum.add(Math.atan2(k * Math.sin(dλ), cosφ0 * cosφ + k * Math.cos(dλ)));
polarAngle += antimeridian ? dλ + (dλ >= 0 ? τ : -τ) : dλ;
if (antimeridian ^ λ0 >= meridian ^ λ >= meridian) {
var arc = d3_geo_cartesianCross(d3_geo_cartesian(point0), d3_geo_cartesian(point));
d3_geo_cartesianNormalize(arc);
var intersection = d3_geo_cartesianCross(meridianNormal, arc);
d3_geo_cartesianNormalize(intersection);
var φarc = (antimeridian ^ dλ >= 0 ? -1 : 1) * d3_asin(intersection[2]);
if (parallel > φarc || parallel === φarc && (arc[0] || arc[1])) {
winding += antimeridian ^ dλ >= 0 ? 1 : -1;
}
}
if (!j++) break;
λ0 = λ, sinφ0 = sinφ, cosφ0 = cosφ, point0 = point;
}
}
return (polarAngle < -ε || polarAngle < ε && d3_geo_areaRingSum < 0) ^ winding & 1;
}
var d3_geo_clipAntimeridian = d3_geo_clip(d3_true, d3_geo_clipAntimeridianLine, d3_geo_clipAntimeridianInterpolate, [ -π, -π / 2 ]);
function d3_geo_clipAntimeridianLine(listener) {
var λ0 = NaN, φ0 = NaN, sλ0 = NaN, clean;
return {
lineStart: function() {
listener.lineStart();
clean = 1;
},
point: function(λ1, φ1) {
var sλ1 = λ1 > 0 ? π : -π, dλ = abs(λ1 - λ0);
if (abs(dλ - π) < ε) {
listener.point(λ0, φ0 = (φ0 + φ1) / 2 > 0 ? halfπ : -halfπ);
listener.point(sλ0, φ0);
listener.lineEnd();
listener.lineStart();
listener.point(sλ1, φ0);
listener.point(λ1, φ0);
clean = 0;
} else if (sλ0 !== sλ1 && dλ >= π) {
if (abs(λ0 - sλ0) < ε) λ0 -= sλ0 * ε;
if (abs(λ1 - sλ1) < ε) λ1 -= sλ1 * ε;
φ0 = d3_geo_clipAntimeridianIntersect(λ0, φ0, λ1, φ1);
listener.point(sλ0, φ0);
listener.lineEnd();
listener.lineStart();
listener.point(sλ1, φ0);
clean = 0;
}
listener.point(λ0 = λ1, φ0 = φ1);
sλ0 = sλ1;
},
lineEnd: function() {
listener.lineEnd();
λ0 = φ0 = NaN;
},
clean: function() {
return 2 - clean;
}
};
}
function d3_geo_clipAntimeridianIntersect(λ0, φ0, λ1, φ1) {
var cosφ0, cosφ1, sinλ0_λ1 = Math.sin(λ0 - λ1);
return abs(sinλ0_λ1) > ε ? Math.atan((Math.sin(φ0) * (cosφ1 = Math.cos(φ1)) * Math.sin(λ1) - Math.sin(φ1) * (cosφ0 = Math.cos(φ0)) * Math.sin(λ0)) / (cosφ0 * cosφ1 * sinλ0_λ1)) : (φ0 + φ1) / 2;
}
function d3_geo_clipAntimeridianInterpolate(from, to, direction, listener) {
var φ;
if (from == null) {
φ = direction * halfπ;
listener.point(-π, φ);
listener.point(0, φ);
listener.point(π, φ);
listener.point(π, 0);
listener.point(π, -φ);
listener.point(0, -φ);
listener.point(-π, -φ);
listener.point(-π, 0);
listener.point(-π, φ);
} else if (abs(from[0] - to[0]) > ε) {
var s = from[0] < to[0] ? π : -π;
φ = direction * s / 2;
listener.point(-s, φ);
listener.point(0, φ);
listener.point(s, φ);
} else {
listener.point(to[0], to[1]);
}
}
function d3_geo_clipCircle(radius) {
var cr = Math.cos(radius), smallRadius = cr > 0, notHemisphere = abs(cr) > ε, interpolate = d3_geo_circleInterpolate(radius, 6 * d3_radians);
return d3_geo_clip(visible, clipLine, interpolate, smallRadius ? [ 0, -radius ] : [ -π, radius - π ]);
function visible(λ, φ) {
return Math.cos(λ) * Math.cos(φ) > cr;
}
function clipLine(listener) {
var point0, c0, v0, v00, clean;
return {
lineStart: function() {
v00 = v0 = false;
clean = 1;
},
point: function(λ, φ) {
var point1 = [ λ, φ ], point2, v = visible(λ, φ), c = smallRadius ? v ? 0 : code(λ, φ) : v ? code(λ + (λ < 0 ? π : -π), φ) : 0;
if (!point0 && (v00 = v0 = v)) listener.lineStart();
if (v !== v0) {
point2 = intersect(point0, point1);
if (d3_geo_sphericalEqual(point0, point2) || d3_geo_sphericalEqual(point1, point2)) {
point1[0] += ε;
point1[1] += ε;
v = visible(point1[0], point1[1]);
}
}
if (v !== v0) {
clean = 0;
if (v) {
listener.lineStart();
point2 = intersect(point1, point0);
listener.point(point2[0], point2[1]);
} else {
point2 = intersect(point0, point1);
listener.point(point2[0], point2[1]);
listener.lineEnd();
}
point0 = point2;
} else if (notHemisphere && point0 && smallRadius ^ v) {
var t;
if (!(c & c0) && (t = intersect(point1, point0, true))) {
clean = 0;
if (smallRadius) {
listener.lineStart();
listener.point(t[0][0], t[0][1]);
listener.point(t[1][0], t[1][1]);
listener.lineEnd();
} else {
listener.point(t[1][0], t[1][1]);
listener.lineEnd();
listener.lineStart();
listener.point(t[0][0], t[0][1]);
}
}
}
if (v && (!point0 || !d3_geo_sphericalEqual(point0, point1))) {
listener.point(point1[0], point1[1]);
}
point0 = point1, v0 = v, c0 = c;
},
lineEnd: function() {
if (v0) listener.lineEnd();
point0 = null;
},
clean: function() {
return clean | (v00 && v0) << 1;
}
};
}
function intersect(a, b, two) {
var pa = d3_geo_cartesian(a), pb = d3_geo_cartesian(b);
var n1 = [ 1, 0, 0 ], n2 = d3_geo_cartesianCross(pa, pb), n2n2 = d3_geo_cartesianDot(n2, n2), n1n2 = n2[0], determinant = n2n2 - n1n2 * n1n2;
if (!determinant) return !two && a;
var c1 = cr * n2n2 / determinant, c2 = -cr * n1n2 / determinant, n1xn2 = d3_geo_cartesianCross(n1, n2), A = d3_geo_cartesianScale(n1, c1), B = d3_geo_cartesianScale(n2, c2);
d3_geo_cartesianAdd(A, B);
var u = n1xn2, w = d3_geo_cartesianDot(A, u), uu = d3_geo_cartesianDot(u, u), t2 = w * w - uu * (d3_geo_cartesianDot(A, A) - 1);
if (t2 < 0) return;
var t = Math.sqrt(t2), q = d3_geo_cartesianScale(u, (-w - t) / uu);
d3_geo_cartesianAdd(q, A);
q = d3_geo_spherical(q);
if (!two) return q;
var λ0 = a[0], λ1 = b[0], φ0 = a[1], φ1 = b[1], z;
if (λ1 < λ0) z = λ0, λ0 = λ1, λ1 = z;
var δλ = λ1 - λ0, polar = abs(δλ - π) < ε, meridian = polar || δλ < ε;
if (!polar && φ1 < φ0) z = φ0, φ0 = φ1, φ1 = z;
if (meridian ? polar ? φ0 + φ1 > 0 ^ q[1] < (abs(q[0] - λ0) < ε ? φ0 : φ1) : φ0 <= q[1] && q[1] <= φ1 : δλ > π ^ (λ0 <= q[0] && q[0] <= λ1)) {
var q1 = d3_geo_cartesianScale(u, (-w + t) / uu);
d3_geo_cartesianAdd(q1, A);
return [ q, d3_geo_spherical(q1) ];
}
}
function code(λ, φ) {
var r = smallRadius ? radius : π - radius, code = 0;
if (λ < -r) code |= 1; else if (λ > r) code |= 2;
if (φ < -r) code |= 4; else if (φ > r) code |= 8;
return code;
}
}
function d3_geom_clipLine(x0, y0, x1, y1) {
return function(line) {
var a = line.a, b = line.b, ax = a.x, ay = a.y, bx = b.x, by = b.y, t0 = 0, t1 = 1, dx = bx - ax, dy = by - ay, r;
r = x0 - ax;
if (!dx && r > 0) return;
r /= dx;
if (dx < 0) {
if (r < t0) return;
if (r < t1) t1 = r;
} else if (dx > 0) {
if (r > t1) return;
if (r > t0) t0 = r;
}
r = x1 - ax;
if (!dx && r < 0) return;
r /= dx;
if (dx < 0) {
if (r > t1) return;
if (r > t0) t0 = r;
} else if (dx > 0) {
if (r < t0) return;
if (r < t1) t1 = r;
}
r = y0 - ay;
if (!dy && r > 0) return;
r /= dy;
if (dy < 0) {
if (r < t0) return;
if (r < t1) t1 = r;
} else if (dy > 0) {
if (r > t1) return;
if (r > t0) t0 = r;
}
r = y1 - ay;
if (!dy && r < 0) return;
r /= dy;
if (dy < 0) {
if (r > t1) return;
if (r > t0) t0 = r;
} else if (dy > 0) {
if (r < t0) return;
if (r < t1) t1 = r;
}
if (t0 > 0) line.a = {
x: ax + t0 * dx,
y: ay + t0 * dy
};
if (t1 < 1) line.b = {
x: ax + t1 * dx,
y: ay + t1 * dy
};
return line;
};
}
var d3_geo_clipExtentMAX = 1e9;
d3.geo.clipExtent = function() {
var x0, y0, x1, y1, stream, clip, clipExtent = {
stream: function(output) {
if (stream) stream.valid = false;
stream = clip(output);
stream.valid = true;
return stream;
},
extent: function(_) {
if (!arguments.length) return [ [ x0, y0 ], [ x1, y1 ] ];
clip = d3_geo_clipExtent(x0 = +_[0][0], y0 = +_[0][1], x1 = +_[1][0], y1 = +_[1][1]);
if (stream) stream.valid = false, stream = null;
return clipExtent;
}
};
return clipExtent.extent([ [ 0, 0 ], [ 960, 500 ] ]);
};
function d3_geo_clipExtent(x0, y0, x1, y1) {
return function(listener) {
var listener_ = listener, bufferListener = d3_geo_clipBufferListener(), clipLine = d3_geom_clipLine(x0, y0, x1, y1), segments, polygon, ring;
var clip = {
point: point,
lineStart: lineStart,
lineEnd: lineEnd,
polygonStart: function() {
listener = bufferListener;
segments = [];
polygon = [];
clean = true;
},
polygonEnd: function() {
listener = listener_;
segments = d3.merge(segments);
var clipStartInside = insidePolygon([ x0, y1 ]), inside = clean && clipStartInside, visible = segments.length;
if (inside || visible) {
listener.polygonStart();
if (inside) {
listener.lineStart();
interpolate(null, null, 1, listener);
listener.lineEnd();
}
if (visible) {
d3_geo_clipPolygon(segments, compare, clipStartInside, interpolate, listener);
}
listener.polygonEnd();
}
segments = polygon = ring = null;
}
};
function insidePolygon(p) {
var wn = 0, n = polygon.length, y = p[1];
for (var i = 0; i < n; ++i) {
for (var j = 1, v = polygon[i], m = v.length, a = v[0], b; j < m; ++j) {
b = v[j];
if (a[1] <= y) {
if (b[1] > y && isLeft(a, b, p) > 0) ++wn;
} else {
if (b[1] <= y && isLeft(a, b, p) < 0) --wn;
}
a = b;
}
}
return wn !== 0;
}
function isLeft(a, b, c) {
return (b[0] - a[0]) * (c[1] - a[1]) - (c[0] - a[0]) * (b[1] - a[1]);
}
function interpolate(from, to, direction, listener) {
var a = 0, a1 = 0;
if (from == null || (a = corner(from, direction)) !== (a1 = corner(to, direction)) || comparePoints(from, to) < 0 ^ direction > 0) {
do {
listener.point(a === 0 || a === 3 ? x0 : x1, a > 1 ? y1 : y0);
} while ((a = (a + direction + 4) % 4) !== a1);
} else {
listener.point(to[0], to[1]);
}
}
function pointVisible(x, y) {
return x0 <= x && x <= x1 && y0 <= y && y <= y1;
}
function point(x, y) {
if (pointVisible(x, y)) listener.point(x, y);
}
var x__, y__, v__, x_, y_, v_, first, clean;
function lineStart() {
clip.point = linePoint;
if (polygon) polygon.push(ring = []);
first = true;
v_ = false;
x_ = y_ = NaN;
}
function lineEnd() {
if (segments) {
linePoint(x__, y__);
if (v__ && v_) bufferListener.rejoin();
segments.push(bufferListener.buffer());
}
clip.point = point;
if (v_) listener.lineEnd();
}
function linePoint(x, y) {
x = Math.max(-d3_geo_clipExtentMAX, Math.min(d3_geo_clipExtentMAX, x));
y = Math.max(-d3_geo_clipExtentMAX, Math.min(d3_geo_clipExtentMAX, y));
var v = pointVisible(x, y);
if (polygon) ring.push([ x, y ]);
if (first) {
x__ = x, y__ = y, v__ = v;
first = false;
if (v) {
listener.lineStart();
listener.point(x, y);
}
} else {
if (v && v_) listener.point(x, y); else {
var l = {
a: {
x: x_,
y: y_
},
b: {
x: x,
y: y
}
};
if (clipLine(l)) {
if (!v_) {
listener.lineStart();
listener.point(l.a.x, l.a.y);
}
listener.point(l.b.x, l.b.y);
if (!v) listener.lineEnd();
clean = false;
} else if (v) {
listener.lineStart();
listener.point(x, y);
clean = false;
}
}
}
x_ = x, y_ = y, v_ = v;
}
return clip;
};
function corner(p, direction) {
return abs(p[0] - x0) < ε ? direction > 0 ? 0 : 3 : abs(p[0] - x1) < ε ? direction > 0 ? 2 : 1 : abs(p[1] - y0) < ε ? direction > 0 ? 1 : 0 : direction > 0 ? 3 : 2;
}
function compare(a, b) {
return comparePoints(a.x, b.x);
}
function comparePoints(a, b) {
var ca = corner(a, 1), cb = corner(b, 1);
return ca !== cb ? ca - cb : ca === 0 ? b[1] - a[1] : ca === 1 ? a[0] - b[0] : ca === 2 ? a[1] - b[1] : b[0] - a[0];
}
}
function d3_geo_compose(a, b) {
function compose(x, y) {
return x = a(x, y), b(x[0], x[1]);
}
if (a.invert && b.invert) compose.invert = function(x, y) {
return x = b.invert(x, y), x && a.invert(x[0], x[1]);
};
return compose;
}
function d3_geo_conic(projectAt) {
var φ0 = 0, φ1 = π / 3, m = d3_geo_projectionMutator(projectAt), p = m(φ0, φ1);
p.parallels = function(_) {
if (!arguments.length) return [ φ0 / π * 180, φ1 / π * 180 ];
return m(φ0 = _[0] * π / 180, φ1 = _[1] * π / 180);
};
return p;
}
function d3_geo_conicEqualArea(φ0, φ1) {
var sinφ0 = Math.sin(φ0), n = (sinφ0 + Math.sin(φ1)) / 2, C = 1 + sinφ0 * (2 * n - sinφ0), ρ0 = Math.sqrt(C) / n;
function forward(λ, φ) {
var ρ = Math.sqrt(C - 2 * n * Math.sin(φ)) / n;
return [ ρ * Math.sin(λ *= n), ρ0 - ρ * Math.cos(λ) ];
}
forward.invert = function(x, y) {
var ρ0_y = ρ0 - y;
return [ Math.atan2(x, ρ0_y) / n, d3_asin((C - (x * x + ρ0_y * ρ0_y) * n * n) / (2 * n)) ];
};
return forward;
}
(d3.geo.conicEqualArea = function() {
return d3_geo_conic(d3_geo_conicEqualArea);
}).raw = d3_geo_conicEqualArea;
d3.geo.albers = function() {
return d3.geo.conicEqualArea().rotate([ 96, 0 ]).center([ -.6, 38.7 ]).parallels([ 29.5, 45.5 ]).scale(1070);
};
d3.geo.albersUsa = function() {
var lower48 = d3.geo.albers();
var alaska = d3.geo.conicEqualArea().rotate([ 154, 0 ]).center([ -2, 58.5 ]).parallels([ 55, 65 ]);
var hawaii = d3.geo.conicEqualArea().rotate([ 157, 0 ]).center([ -3, 19.9 ]).parallels([ 8, 18 ]);
var point, pointStream = {
point: function(x, y) {
point = [ x, y ];
}
}, lower48Point, alaskaPoint, hawaiiPoint;
function albersUsa(coordinates) {
var x = coordinates[0], y = coordinates[1];
point = null;
(lower48Point(x, y), point) || (alaskaPoint(x, y), point) || hawaiiPoint(x, y);
return point;
}
albersUsa.invert = function(coordinates) {
var k = lower48.scale(), t = lower48.translate(), x = (coordinates[0] - t[0]) / k, y = (coordinates[1] - t[1]) / k;
return (y >= .12 && y < .234 && x >= -.425 && x < -.214 ? alaska : y >= .166 && y < .234 && x >= -.214 && x < -.115 ? hawaii : lower48).invert(coordinates);
};
albersUsa.stream = function(stream) {
var lower48Stream = lower48.stream(stream), alaskaStream = alaska.stream(stream), hawaiiStream = hawaii.stream(stream);
return {
point: function(x, y) {
lower48Stream.point(x, y);
alaskaStream.point(x, y);
hawaiiStream.point(x, y);
},
sphere: function() {
lower48Stream.sphere();
alaskaStream.sphere();
hawaiiStream.sphere();
},
lineStart: function() {
lower48Stream.lineStart();
alaskaStream.lineStart();
hawaiiStream.lineStart();
},
lineEnd: function() {
lower48Stream.lineEnd();
alaskaStream.lineEnd();
hawaiiStream.lineEnd();
},
polygonStart: function() {
lower48Stream.polygonStart();
alaskaStream.polygonStart();
hawaiiStream.polygonStart();
},
polygonEnd: function() {
lower48Stream.polygonEnd();
alaskaStream.polygonEnd();
hawaiiStream.polygonEnd();
}
};
};
albersUsa.precision = function(_) {
if (!arguments.length) return lower48.precision();
lower48.precision(_);
alaska.precision(_);
hawaii.precision(_);
return albersUsa;
};
albersUsa.scale = function(_) {
if (!arguments.length) return lower48.scale();
lower48.scale(_);
alaska.scale(_ * .35);
hawaii.scale(_);
return albersUsa.translate(lower48.translate());
};
albersUsa.translate = function(_) {
if (!arguments.length) return lower48.translate();
var k = lower48.scale(), x = +_[0], y = +_[1];
lower48Point = lower48.translate(_).clipExtent([ [ x - .455 * k, y - .238 * k ], [ x + .455 * k, y + .238 * k ] ]).stream(pointStream).point;
alaskaPoint = alaska.translate([ x - .307 * k, y + .201 * k ]).clipExtent([ [ x - .425 * k + ε, y + .12 * k + ε ], [ x - .214 * k - ε, y + .234 * k - ε ] ]).stream(pointStream).point;
hawaiiPoint = hawaii.translate([ x - .205 * k, y + .212 * k ]).clipExtent([ [ x - .214 * k + ε, y + .166 * k + ε ], [ x - .115 * k - ε, y + .234 * k - ε ] ]).stream(pointStream).point;
return albersUsa;
};
return albersUsa.scale(1070);
};
var d3_geo_pathAreaSum, d3_geo_pathAreaPolygon, d3_geo_pathArea = {
point: d3_noop,
lineStart: d3_noop,
lineEnd: d3_noop,
polygonStart: function() {
d3_geo_pathAreaPolygon = 0;
d3_geo_pathArea.lineStart = d3_geo_pathAreaRingStart;
},
polygonEnd: function() {
d3_geo_pathArea.lineStart = d3_geo_pathArea.lineEnd = d3_geo_pathArea.point = d3_noop;
d3_geo_pathAreaSum += abs(d3_geo_pathAreaPolygon / 2);
}
};
function d3_geo_pathAreaRingStart() {
var x00, y00, x0, y0;
d3_geo_pathArea.point = function(x, y) {
d3_geo_pathArea.point = nextPoint;
x00 = x0 = x, y00 = y0 = y;
};
function nextPoint(x, y) {
d3_geo_pathAreaPolygon += y0 * x - x0 * y;
x0 = x, y0 = y;
}
d3_geo_pathArea.lineEnd = function() {
nextPoint(x00, y00);
};
}
var d3_geo_pathBoundsX0, d3_geo_pathBoundsY0, d3_geo_pathBoundsX1, d3_geo_pathBoundsY1;
var d3_geo_pathBounds = {
point: d3_geo_pathBoundsPoint,
lineStart: d3_noop,
lineEnd: d3_noop,
polygonStart: d3_noop,
polygonEnd: d3_noop
};
function d3_geo_pathBoundsPoint(x, y) {
if (x < d3_geo_pathBoundsX0) d3_geo_pathBoundsX0 = x;
if (x > d3_geo_pathBoundsX1) d3_geo_pathBoundsX1 = x;
if (y < d3_geo_pathBoundsY0) d3_geo_pathBoundsY0 = y;
if (y > d3_geo_pathBoundsY1) d3_geo_pathBoundsY1 = y;
}
function d3_geo_pathBuffer() {
var pointCircle = d3_geo_pathBufferCircle(4.5), buffer = [];
var stream = {
point: point,
lineStart: function() {
stream.point = pointLineStart;
},
lineEnd: lineEnd,
polygonStart: function() {
stream.lineEnd = lineEndPolygon;
},
polygonEnd: function() {
stream.lineEnd = lineEnd;
stream.point = point;
},
pointRadius: function(_) {
pointCircle = d3_geo_pathBufferCircle(_);
return stream;
},
result: function() {
if (buffer.length) {
var result = buffer.join("");
buffer = [];
return result;
}
}
};
function point(x, y) {
buffer.push("M", x, ",", y, pointCircle);
}
function pointLineStart(x, y) {
buffer.push("M", x, ",", y);
stream.point = pointLine;
}
function pointLine(x, y) {
buffer.push("L", x, ",", y);
}
function lineEnd() {
stream.point = point;
}
function lineEndPolygon() {
buffer.push("Z");
}
return stream;
}
function d3_geo_pathBufferCircle(radius) {
return "m0," + radius + "a" + radius + "," + radius + " 0 1,1 0," + -2 * radius + "a" + radius + "," + radius + " 0 1,1 0," + 2 * radius + "z";
}
var d3_geo_pathCentroid = {
point: d3_geo_pathCentroidPoint,
lineStart: d3_geo_pathCentroidLineStart,
lineEnd: d3_geo_pathCentroidLineEnd,
polygonStart: function() {
d3_geo_pathCentroid.lineStart = d3_geo_pathCentroidRingStart;
},
polygonEnd: function() {
d3_geo_pathCentroid.point = d3_geo_pathCentroidPoint;
d3_geo_pathCentroid.lineStart = d3_geo_pathCentroidLineStart;
d3_geo_pathCentroid.lineEnd = d3_geo_pathCentroidLineEnd;
}
};
function d3_geo_pathCentroidPoint(x, y) {
d3_geo_centroidX0 += x;
d3_geo_centroidY0 += y;
++d3_geo_centroidZ0;
}
function d3_geo_pathCentroidLineStart() {
var x0, y0;
d3_geo_pathCentroid.point = function(x, y) {
d3_geo_pathCentroid.point = nextPoint;
d3_geo_pathCentroidPoint(x0 = x, y0 = y);
};
function nextPoint(x, y) {
var dx = x - x0, dy = y - y0, z = Math.sqrt(dx * dx + dy * dy);
d3_geo_centroidX1 += z * (x0 + x) / 2;
d3_geo_centroidY1 += z * (y0 + y) / 2;
d3_geo_centroidZ1 += z;
d3_geo_pathCentroidPoint(x0 = x, y0 = y);
}
}
function d3_geo_pathCentroidLineEnd() {
d3_geo_pathCentroid.point = d3_geo_pathCentroidPoint;
}
function d3_geo_pathCentroidRingStart() {
var x00, y00, x0, y0;
d3_geo_pathCentroid.point = function(x, y) {
d3_geo_pathCentroid.point = nextPoint;
d3_geo_pathCentroidPoint(x00 = x0 = x, y00 = y0 = y);
};
function nextPoint(x, y) {
var dx = x - x0, dy = y - y0, z = Math.sqrt(dx * dx + dy * dy);
d3_geo_centroidX1 += z * (x0 + x) / 2;
d3_geo_centroidY1 += z * (y0 + y) / 2;
d3_geo_centroidZ1 += z;
z = y0 * x - x0 * y;
d3_geo_centroidX2 += z * (x0 + x);
d3_geo_centroidY2 += z * (y0 + y);
d3_geo_centroidZ2 += z * 3;
d3_geo_pathCentroidPoint(x0 = x, y0 = y);
}
d3_geo_pathCentroid.lineEnd = function() {
nextPoint(x00, y00);
};
}
function d3_geo_pathContext(context) {
var pointRadius = 4.5;
var stream = {
point: point,
lineStart: function() {
stream.point = pointLineStart;
},
lineEnd: lineEnd,
polygonStart: function() {
stream.lineEnd = lineEndPolygon;
},
polygonEnd: function() {
stream.lineEnd = lineEnd;
stream.point = point;
},
pointRadius: function(_) {
pointRadius = _;
return stream;
},
result: d3_noop
};
function point(x, y) {
context.moveTo(x, y);
context.arc(x, y, pointRadius, 0, τ);
}
function pointLineStart(x, y) {
context.moveTo(x, y);
stream.point = pointLine;
}
function pointLine(x, y) {
context.lineTo(x, y);
}
function lineEnd() {
stream.point = point;
}
function lineEndPolygon() {
context.closePath();
}
return stream;
}
function d3_geo_resample(project) {
var δ2 = .5, cosMinDistance = Math.cos(30 * d3_radians), maxDepth = 16;
function resample(stream) {
return (maxDepth ? resampleRecursive : resampleNone)(stream);
}
function resampleNone(stream) {
return d3_geo_transformPoint(stream, function(x, y) {
x = project(x, y);
stream.point(x[0], x[1]);
});
}
function resampleRecursive(stream) {
var λ00, φ00, x00, y00, a00, b00, c00, λ0, x0, y0, a0, b0, c0;
var resample = {
point: point,
lineStart: lineStart,
lineEnd: lineEnd,
polygonStart: function() {
stream.polygonStart();
resample.lineStart = ringStart;
},
polygonEnd: function() {
stream.polygonEnd();
resample.lineStart = lineStart;
}
};
function point(x, y) {
x = project(x, y);
stream.point(x[0], x[1]);
}
function lineStart() {
x0 = NaN;
resample.point = linePoint;
stream.lineStart();
}
function linePoint(λ, φ) {
var c = d3_geo_cartesian([ λ, φ ]), p = project(λ, φ);
resampleLineTo(x0, y0, λ0, a0, b0, c0, x0 = p[0], y0 = p[1], λ0 = λ, a0 = c[0], b0 = c[1], c0 = c[2], maxDepth, stream);
stream.point(x0, y0);
}
function lineEnd() {
resample.point = point;
stream.lineEnd();
}
function ringStart() {
lineStart();
resample.point = ringPoint;
resample.lineEnd = ringEnd;
}
function ringPoint(λ, φ) {
linePoint(λ00 = λ, φ00 = φ), x00 = x0, y00 = y0, a00 = a0, b00 = b0, c00 = c0;
resample.point = linePoint;
}
function ringEnd() {
resampleLineTo(x0, y0, λ0, a0, b0, c0, x00, y00, λ00, a00, b00, c00, maxDepth, stream);
resample.lineEnd = lineEnd;
lineEnd();
}
return resample;
}
function resampleLineTo(x0, y0, λ0, a0, b0, c0, x1, y1, λ1, a1, b1, c1, depth, stream) {
var dx = x1 - x0, dy = y1 - y0, d2 = dx * dx + dy * dy;
if (d2 > 4 * δ2 && depth--) {
var a = a0 + a1, b = b0 + b1, c = c0 + c1, m = Math.sqrt(a * a + b * b + c * c), φ2 = Math.asin(c /= m), λ2 = abs(abs(c) - 1) < ε ? (λ0 + λ1) / 2 : Math.atan2(b, a), p = project(λ2, φ2), x2 = p[0], y2 = p[1], dx2 = x2 - x0, dy2 = y2 - y0, dz = dy * dx2 - dx * dy2;
if (dz * dz / d2 > δ2 || abs((dx * dx2 + dy * dy2) / d2 - .5) > .3 || a0 * a1 + b0 * b1 + c0 * c1 < cosMinDistance) {
resampleLineTo(x0, y0, λ0, a0, b0, c0, x2, y2, λ2, a /= m, b /= m, c, depth, stream);
stream.point(x2, y2);
resampleLineTo(x2, y2, λ2, a, b, c, x1, y1, λ1, a1, b1, c1, depth, stream);
}
}
}
resample.precision = function(_) {
if (!arguments.length) return Math.sqrt(δ2);
maxDepth = (δ2 = _ * _) > 0 && 16;
return resample;
};
return resample;
}
d3.geo.path = function() {
var pointRadius = 4.5, projection, context, projectStream, contextStream, cacheStream;
function path(object) {
if (object) {
if (typeof pointRadius === "function") contextStream.pointRadius(+pointRadius.apply(this, arguments));
if (!cacheStream || !cacheStream.valid) cacheStream = projectStream(contextStream);
d3.geo.stream(object, cacheStream);
}
return contextStream.result();
}
path.area = function(object) {
d3_geo_pathAreaSum = 0;
d3.geo.stream(object, projectStream(d3_geo_pathArea));
return d3_geo_pathAreaSum;
};
path.centroid = function(object) {
d3_geo_centroidX0 = d3_geo_centroidY0 = d3_geo_centroidZ0 = d3_geo_centroidX1 = d3_geo_centroidY1 = d3_geo_centroidZ1 = d3_geo_centroidX2 = d3_geo_centroidY2 = d3_geo_centroidZ2 = 0;
d3.geo.stream(object, projectStream(d3_geo_pathCentroid));
return d3_geo_centroidZ2 ? [ d3_geo_centroidX2 / d3_geo_centroidZ2, d3_geo_centroidY2 / d3_geo_centroidZ2 ] : d3_geo_centroidZ1 ? [ d3_geo_centroidX1 / d3_geo_centroidZ1, d3_geo_centroidY1 / d3_geo_centroidZ1 ] : d3_geo_centroidZ0 ? [ d3_geo_centroidX0 / d3_geo_centroidZ0, d3_geo_centroidY0 / d3_geo_centroidZ0 ] : [ NaN, NaN ];
};
path.bounds = function(object) {
d3_geo_pathBoundsX1 = d3_geo_pathBoundsY1 = -(d3_geo_pathBoundsX0 = d3_geo_pathBoundsY0 = Infinity);
d3.geo.stream(object, projectStream(d3_geo_pathBounds));
return [ [ d3_geo_pathBoundsX0, d3_geo_pathBoundsY0 ], [ d3_geo_pathBoundsX1, d3_geo_pathBoundsY1 ] ];
};
path.projection = function(_) {
if (!arguments.length) return projection;
projectStream = (projection = _) ? _.stream || d3_geo_pathProjectStream(_) : d3_identity;
return reset();
};
path.context = function(_) {
if (!arguments.length) return context;
contextStream = (context = _) == null ? new d3_geo_pathBuffer() : new d3_geo_pathContext(_);
if (typeof pointRadius !== "function") contextStream.pointRadius(pointRadius);
return reset();
};
path.pointRadius = function(_) {
if (!arguments.length) return pointRadius;
pointRadius = typeof _ === "function" ? _ : (contextStream.pointRadius(+_), +_);
return path;
};
function reset() {
cacheStream = null;
return path;
}
return path.projection(d3.geo.albersUsa()).context(null);
};
function d3_geo_pathProjectStream(project) {
var resample = d3_geo_resample(function(x, y) {
return project([ x * d3_degrees, y * d3_degrees ]);
});
return function(stream) {
return d3_geo_projectionRadians(resample(stream));
};
}
d3.geo.transform = function(methods) {
return {
stream: function(stream) {
var transform = new d3_geo_transform(stream);
for (var k in methods) transform[k] = methods[k];
return transform;
}
};
};
function d3_geo_transform(stream) {
this.stream = stream;
}
d3_geo_transform.prototype = {
point: function(x, y) {
this.stream.point(x, y);
},
sphere: function() {
this.stream.sphere();
},
lineStart: function() {
this.stream.lineStart();
},
lineEnd: function() {
this.stream.lineEnd();
},
polygonStart: function() {
this.stream.polygonStart();
},
polygonEnd: function() {
this.stream.polygonEnd();
}
};
function d3_geo_transformPoint(stream, point) {
return {
point: point,
sphere: function() {
stream.sphere();
},
lineStart: function() {
stream.lineStart();
},
lineEnd: function() {
stream.lineEnd();
},
polygonStart: function() {
stream.polygonStart();
},
polygonEnd: function() {
stream.polygonEnd();
}
};
}
d3.geo.projection = d3_geo_projection;
d3.geo.projectionMutator = d3_geo_projectionMutator;
function d3_geo_projection(project) {
return d3_geo_projectionMutator(function() {
return project;
})();
}
function d3_geo_projectionMutator(projectAt) {
var project, rotate, projectRotate, projectResample = d3_geo_resample(function(x, y) {
x = project(x, y);
return [ x[0] * k + δx, δy - x[1] * k ];
}), k = 150, x = 480, y = 250, λ = 0, φ = 0, δλ = 0, δφ = 0, δγ = 0, δx, δy, preclip = d3_geo_clipAntimeridian, postclip = d3_identity, clipAngle = null, clipExtent = null, stream;
function projection(point) {
point = projectRotate(point[0] * d3_radians, point[1] * d3_radians);
return [ point[0] * k + δx, δy - point[1] * k ];
}
function invert(point) {
point = projectRotate.invert((point[0] - δx) / k, (δy - point[1]) / k);
return point && [ point[0] * d3_degrees, point[1] * d3_degrees ];
}
projection.stream = function(output) {
if (stream) stream.valid = false;
stream = d3_geo_projectionRadians(preclip(rotate, projectResample(postclip(output))));
stream.valid = true;
return stream;
};
projection.clipAngle = function(_) {
if (!arguments.length) return clipAngle;
preclip = _ == null ? (clipAngle = _, d3_geo_clipAntimeridian) : d3_geo_clipCircle((clipAngle = +_) * d3_radians);
return invalidate();
};
projection.clipExtent = function(_) {
if (!arguments.length) return clipExtent;
clipExtent = _;
postclip = _ ? d3_geo_clipExtent(_[0][0], _[0][1], _[1][0], _[1][1]) : d3_identity;
return invalidate();
};
projection.scale = function(_) {
if (!arguments.length) return k;
k = +_;
return reset();
};
projection.translate = function(_) {
if (!arguments.length) return [ x, y ];
x = +_[0];
y = +_[1];
return reset();
};
projection.center = function(_) {
if (!arguments.length) return [ λ * d3_degrees, φ * d3_degrees ];
λ = _[0] % 360 * d3_radians;
φ = _[1] % 360 * d3_radians;
return reset();
};
projection.rotate = function(_) {
if (!arguments.length) return [ δλ * d3_degrees, δφ * d3_degrees, δγ * d3_degrees ];
δλ = _[0] % 360 * d3_radians;
δφ = _[1] % 360 * d3_radians;
δγ = _.length > 2 ? _[2] % 360 * d3_radians : 0;
return reset();
};
d3.rebind(projection, projectResample, "precision");
function reset() {
projectRotate = d3_geo_compose(rotate = d3_geo_rotation(δλ, δφ, δγ), project);
var center = project(λ, φ);
δx = x - center[0] * k;
δy = y + center[1] * k;
return invalidate();
}
function invalidate() {
if (stream) stream.valid = false, stream = null;
return projection;
}
return function() {
project = projectAt.apply(this, arguments);
projection.invert = project.invert && invert;
return reset();
};
}
function d3_geo_projectionRadians(stream) {
return d3_geo_transformPoint(stream, function(x, y) {
stream.point(x * d3_radians, y * d3_radians);
});
}
function d3_geo_equirectangular(λ, φ) {
return [ λ, φ ];
}
(d3.geo.equirectangular = function() {
return d3_geo_projection(d3_geo_equirectangular);
}).raw = d3_geo_equirectangular.invert = d3_geo_equirectangular;
d3.geo.rotation = function(rotate) {
rotate = d3_geo_rotation(rotate[0] % 360 * d3_radians, rotate[1] * d3_radians, rotate.length > 2 ? rotate[2] * d3_radians : 0);
function forward(coordinates) {
coordinates = rotate(coordinates[0] * d3_radians, coordinates[1] * d3_radians);
return coordinates[0] *= d3_degrees, coordinates[1] *= d3_degrees, coordinates;
}
forward.invert = function(coordinates) {
coordinates = rotate.invert(coordinates[0] * d3_radians, coordinates[1] * d3_radians);
return coordinates[0] *= d3_degrees, coordinates[1] *= d3_degrees, coordinates;
};
return forward;
};
function d3_geo_identityRotation(λ, φ) {
return [ λ > π ? λ - τ : λ < -π ? λ + τ : λ, φ ];
}
d3_geo_identityRotation.invert = d3_geo_equirectangular;
function d3_geo_rotation(δλ, δφ, δγ) {
return δλ ? δφ || δγ ? d3_geo_compose(d3_geo_rotationλ(δλ), d3_geo_rotationφγ(δφ, δγ)) : d3_geo_rotationλ(δλ) : δφ || δγ ? d3_geo_rotationφγ(δφ, δγ) : d3_geo_identityRotation;
}
function d3_geo_forwardRotationλ(δλ) {
return function(λ, φ) {
return λ += δλ, [ λ > π ? λ - τ : λ < -π ? λ + τ : λ, φ ];
};
}
function d3_geo_rotationλ(δλ) {
var rotation = d3_geo_forwardRotationλ(δλ);
rotation.invert = d3_geo_forwardRotationλ(-δλ);
return rotation;
}
function d3_geo_rotationφγ(δφ, δγ) {
var cosδφ = Math.cos(δφ), sinδφ = Math.sin(δφ), cosδγ = Math.cos(δγ), sinδγ = Math.sin(δγ);
function rotation(λ, φ) {
var cosφ = Math.cos(φ), x = Math.cos(λ) * cosφ, y = Math.sin(λ) * cosφ, z = Math.sin(φ), k = z * cosδφ + x * sinδφ;
return [ Math.atan2(y * cosδγ - k * sinδγ, x * cosδφ - z * sinδφ), d3_asin(k * cosδγ + y * sinδγ) ];
}
rotation.invert = function(λ, φ) {
var cosφ = Math.cos(φ), x = Math.cos(λ) * cosφ, y = Math.sin(λ) * cosφ, z = Math.sin(φ), k = z * cosδγ - y * sinδγ;
return [ Math.atan2(y * cosδγ + z * sinδγ, x * cosδφ + k * sinδφ), d3_asin(k * cosδφ - x * sinδφ) ];
};
return rotation;
}
d3.geo.circle = function() {
var origin = [ 0, 0 ], angle, precision = 6, interpolate;
function circle() {
var center = typeof origin === "function" ? origin.apply(this, arguments) : origin, rotate = d3_geo_rotation(-center[0] * d3_radians, -center[1] * d3_radians, 0).invert, ring = [];
interpolate(null, null, 1, {
point: function(x, y) {
ring.push(x = rotate(x, y));
x[0] *= d3_degrees, x[1] *= d3_degrees;
}
});
return {
type: "Polygon",
coordinates: [ ring ]
};
}
circle.origin = function(x) {
if (!arguments.length) return origin;
origin = x;
return circle;
};
circle.angle = function(x) {
if (!arguments.length) return angle;
interpolate = d3_geo_circleInterpolate((angle = +x) * d3_radians, precision * d3_radians);
return circle;
};
circle.precision = function(_) {
if (!arguments.length) return precision;
interpolate = d3_geo_circleInterpolate(angle * d3_radians, (precision = +_) * d3_radians);
return circle;
};
return circle.angle(90);
};
function d3_geo_circleInterpolate(radius, precision) {
var cr = Math.cos(radius), sr = Math.sin(radius);
return function(from, to, direction, listener) {
var step = direction * precision;
if (from != null) {
from = d3_geo_circleAngle(cr, from);
to = d3_geo_circleAngle(cr, to);
if (direction > 0 ? from < to : from > to) from += direction * τ;
} else {
from = radius + direction * τ;
to = radius - .5 * step;
}
for (var point, t = from; direction > 0 ? t > to : t < to; t -= step) {
listener.point((point = d3_geo_spherical([ cr, -sr * Math.cos(t), -sr * Math.sin(t) ]))[0], point[1]);
}
};
}
function d3_geo_circleAngle(cr, point) {
var a = d3_geo_cartesian(point);
a[0] -= cr;
d3_geo_cartesianNormalize(a);
var angle = d3_acos(-a[1]);
return ((-a[2] < 0 ? -angle : angle) + 2 * Math.PI - ε) % (2 * Math.PI);
}
d3.geo.distance = function(a, b) {
var Δλ = (b[0] - a[0]) * d3_radians, φ0 = a[1] * d3_radians, φ1 = b[1] * d3_radians, sinΔλ = Math.sin(Δλ), cosΔλ = Math.cos(Δλ), sinφ0 = Math.sin(φ0), cosφ0 = Math.cos(φ0), sinφ1 = Math.sin(φ1), cosφ1 = Math.cos(φ1), t;
return Math.atan2(Math.sqrt((t = cosφ1 * sinΔλ) * t + (t = cosφ0 * sinφ1 - sinφ0 * cosφ1 * cosΔλ) * t), sinφ0 * sinφ1 + cosφ0 * cosφ1 * cosΔλ);
};
d3.geo.graticule = function() {
var x1, x0, X1, X0, y1, y0, Y1, Y0, dx = 10, dy = dx, DX = 90, DY = 360, x, y, X, Y, precision = 2.5;
function graticule() {
return {
type: "MultiLineString",
coordinates: lines()
};
}
function lines() {
return d3.range(Math.ceil(X0 / DX) * DX, X1, DX).map(X).concat(d3.range(Math.ceil(Y0 / DY) * DY, Y1, DY).map(Y)).concat(d3.range(Math.ceil(x0 / dx) * dx, x1, dx).filter(function(x) {
return abs(x % DX) > ε;
}).map(x)).concat(d3.range(Math.ceil(y0 / dy) * dy, y1, dy).filter(function(y) {
return abs(y % DY) > ε;
}).map(y));
}
graticule.lines = function() {
return lines().map(function(coordinates) {
return {
type: "LineString",
coordinates: coordinates
};
});
};
graticule.outline = function() {
return {
type: "Polygon",
coordinates: [ X(X0).concat(Y(Y1).slice(1), X(X1).reverse().slice(1), Y(Y0).reverse().slice(1)) ]
};
};
graticule.extent = function(_) {
if (!arguments.length) return graticule.minorExtent();
return graticule.majorExtent(_).minorExtent(_);
};
graticule.majorExtent = function(_) {
if (!arguments.length) return [ [ X0, Y0 ], [ X1, Y1 ] ];
X0 = +_[0][0], X1 = +_[1][0];
Y0 = +_[0][1], Y1 = +_[1][1];
if (X0 > X1) _ = X0, X0 = X1, X1 = _;
if (Y0 > Y1) _ = Y0, Y0 = Y1, Y1 = _;
return graticule.precision(precision);
};
graticule.minorExtent = function(_) {
if (!arguments.length) return [ [ x0, y0 ], [ x1, y1 ] ];
x0 = +_[0][0], x1 = +_[1][0];
y0 = +_[0][1], y1 = +_[1][1];
if (x0 > x1) _ = x0, x0 = x1, x1 = _;
if (y0 > y1) _ = y0, y0 = y1, y1 = _;
return graticule.precision(precision);
};
graticule.step = function(_) {
if (!arguments.length) return graticule.minorStep();
return graticule.majorStep(_).minorStep(_);
};
graticule.majorStep = function(_) {
if (!arguments.length) return [ DX, DY ];
DX = +_[0], DY = +_[1];
return graticule;
};
graticule.minorStep = function(_) {
if (!arguments.length) return [ dx, dy ];
dx = +_[0], dy = +_[1];
return graticule;
};
graticule.precision = function(_) {
if (!arguments.length) return precision;
precision = +_;
x = d3_geo_graticuleX(y0, y1, 90);
y = d3_geo_graticuleY(x0, x1, precision);
X = d3_geo_graticuleX(Y0, Y1, 90);
Y = d3_geo_graticuleY(X0, X1, precision);
return graticule;
};
return graticule.majorExtent([ [ -180, -90 + ε ], [ 180, 90 - ε ] ]).minorExtent([ [ -180, -80 - ε ], [ 180, 80 + ε ] ]);
};
function d3_geo_graticuleX(y0, y1, dy) {
var y = d3.range(y0, y1 - ε, dy).concat(y1);
return function(x) {
return y.map(function(y) {
return [ x, y ];
});
};
}
function d3_geo_graticuleY(x0, x1, dx) {
var x = d3.range(x0, x1 - ε, dx).concat(x1);
return function(y) {
return x.map(function(x) {
return [ x, y ];
});
};
}
function d3_source(d) {
return d.source;
}
function d3_target(d) {
return d.target;
}
d3.geo.greatArc = function() {
var source = d3_source, source_, target = d3_target, target_;
function greatArc() {
return {
type: "LineString",
coordinates: [ source_ || source.apply(this, arguments), target_ || target.apply(this, arguments) ]
};
}
greatArc.distance = function() {
return d3.geo.distance(source_ || source.apply(this, arguments), target_ || target.apply(this, arguments));
};
greatArc.source = function(_) {
if (!arguments.length) return source;
source = _, source_ = typeof _ === "function" ? null : _;
return greatArc;
};
greatArc.target = function(_) {
if (!arguments.length) return target;
target = _, target_ = typeof _ === "function" ? null : _;
return greatArc;
};
greatArc.precision = function() {
return arguments.length ? greatArc : 0;
};
return greatArc;
};
d3.geo.interpolate = function(source, target) {
return d3_geo_interpolate(source[0] * d3_radians, source[1] * d3_radians, target[0] * d3_radians, target[1] * d3_radians);
};
function d3_geo_interpolate(x0, y0, x1, y1) {
var cy0 = Math.cos(y0), sy0 = Math.sin(y0), cy1 = Math.cos(y1), sy1 = Math.sin(y1), kx0 = cy0 * Math.cos(x0), ky0 = cy0 * Math.sin(x0), kx1 = cy1 * Math.cos(x1), ky1 = cy1 * Math.sin(x1), d = 2 * Math.asin(Math.sqrt(d3_haversin(y1 - y0) + cy0 * cy1 * d3_haversin(x1 - x0))), k = 1 / Math.sin(d);
var interpolate = d ? function(t) {
var B = Math.sin(t *= d) * k, A = Math.sin(d - t) * k, x = A * kx0 + B * kx1, y = A * ky0 + B * ky1, z = A * sy0 + B * sy1;
return [ Math.atan2(y, x) * d3_degrees, Math.atan2(z, Math.sqrt(x * x + y * y)) * d3_degrees ];
} : function() {
return [ x0 * d3_degrees, y0 * d3_degrees ];
};
interpolate.distance = d;
return interpolate;
}
d3.geo.length = function(object) {
d3_geo_lengthSum = 0;
d3.geo.stream(object, d3_geo_length);
return d3_geo_lengthSum;
};
var d3_geo_lengthSum;
var d3_geo_length = {
sphere: d3_noop,
point: d3_noop,
lineStart: d3_geo_lengthLineStart,
lineEnd: d3_noop,
polygonStart: d3_noop,
polygonEnd: d3_noop
};
function d3_geo_lengthLineStart() {
var λ0, sinφ0, cosφ0;
d3_geo_length.point = function(λ, φ) {
λ0 = λ * d3_radians, sinφ0 = Math.sin(φ *= d3_radians), cosφ0 = Math.cos(φ);
d3_geo_length.point = nextPoint;
};
d3_geo_length.lineEnd = function() {
d3_geo_length.point = d3_geo_length.lineEnd = d3_noop;
};
function nextPoint(λ, φ) {
var sinφ = Math.sin(φ *= d3_radians), cosφ = Math.cos(φ), t = abs((λ *= d3_radians) - λ0), cosΔλ = Math.cos(t);
d3_geo_lengthSum += Math.atan2(Math.sqrt((t = cosφ * Math.sin(t)) * t + (t = cosφ0 * sinφ - sinφ0 * cosφ * cosΔλ) * t), sinφ0 * sinφ + cosφ0 * cosφ * cosΔλ);
λ0 = λ, sinφ0 = sinφ, cosφ0 = cosφ;
}
}
function d3_geo_azimuthal(scale, angle) {
function azimuthal(λ, φ) {
var cosλ = Math.cos(λ), cosφ = Math.cos(φ), k = scale(cosλ * cosφ);
return [ k * cosφ * Math.sin(λ), k * Math.sin(φ) ];
}
azimuthal.invert = function(x, y) {
var ρ = Math.sqrt(x * x + y * y), c = angle(ρ), sinc = Math.sin(c), cosc = Math.cos(c);
return [ Math.atan2(x * sinc, ρ * cosc), Math.asin(ρ && y * sinc / ρ) ];
};
return azimuthal;
}
var d3_geo_azimuthalEqualArea = d3_geo_azimuthal(function(cosλcosφ) {
return Math.sqrt(2 / (1 + cosλcosφ));
}, function(ρ) {
return 2 * Math.asin(ρ / 2);
});
(d3.geo.azimuthalEqualArea = function() {
return d3_geo_projection(d3_geo_azimuthalEqualArea);
}).raw = d3_geo_azimuthalEqualArea;
var d3_geo_azimuthalEquidistant = d3_geo_azimuthal(function(cosλcosφ) {
var c = Math.acos(cosλcosφ);
return c && c / Math.sin(c);
}, d3_identity);
(d3.geo.azimuthalEquidistant = function() {
return d3_geo_projection(d3_geo_azimuthalEquidistant);
}).raw = d3_geo_azimuthalEquidistant;
function d3_geo_conicConformal(φ0, φ1) {
var cosφ0 = Math.cos(φ0), t = function(φ) {
return Math.tan(π / 4 + φ / 2);
}, n = φ0 === φ1 ? Math.sin(φ0) : Math.log(cosφ0 / Math.cos(φ1)) / Math.log(t(φ1) / t(φ0)), F = cosφ0 * Math.pow(t(φ0), n) / n;
if (!n) return d3_geo_mercator;
function forward(λ, φ) {
var ρ = abs(abs(φ) - halfπ) < ε ? 0 : F / Math.pow(t(φ), n);
return [ ρ * Math.sin(n * λ), F - ρ * Math.cos(n * λ) ];
}
forward.invert = function(x, y) {
var ρ0_y = F - y, ρ = d3_sgn(n) * Math.sqrt(x * x + ρ0_y * ρ0_y);
return [ Math.atan2(x, ρ0_y) / n, 2 * Math.atan(Math.pow(F / ρ, 1 / n)) - halfπ ];
};
return forward;
}
(d3.geo.conicConformal = function() {
return d3_geo_conic(d3_geo_conicConformal);
}).raw = d3_geo_conicConformal;
function d3_geo_conicEquidistant(φ0, φ1) {
var cosφ0 = Math.cos(φ0), n = φ0 === φ1 ? Math.sin(φ0) : (cosφ0 - Math.cos(φ1)) / (φ1 - φ0), G = cosφ0 / n + φ0;
if (abs(n) < ε) return d3_geo_equirectangular;
function forward(λ, φ) {
var ρ = G - φ;
return [ ρ * Math.sin(n * λ), G - ρ * Math.cos(n * λ) ];
}
forward.invert = function(x, y) {
var ρ0_y = G - y;
return [ Math.atan2(x, ρ0_y) / n, G - d3_sgn(n) * Math.sqrt(x * x + ρ0_y * ρ0_y) ];
};
return forward;
}
(d3.geo.conicEquidistant = function() {
return d3_geo_conic(d3_geo_conicEquidistant);
}).raw = d3_geo_conicEquidistant;
var d3_geo_gnomonic = d3_geo_azimuthal(function(cosλcosφ) {
return 1 / cosλcosφ;
}, Math.atan);
(d3.geo.gnomonic = function() {
return d3_geo_projection(d3_geo_gnomonic);
}).raw = d3_geo_gnomonic;
function d3_geo_mercator(λ, φ) {
return [ λ, Math.log(Math.tan(π / 4 + φ / 2)) ];
}
d3_geo_mercator.invert = function(x, y) {
return [ x, 2 * Math.atan(Math.exp(y)) - halfπ ];
};
function d3_geo_mercatorProjection(project) {
var m = d3_geo_projection(project), scale = m.scale, translate = m.translate, clipExtent = m.clipExtent, clipAuto;
m.scale = function() {
var v = scale.apply(m, arguments);
return v === m ? clipAuto ? m.clipExtent(null) : m : v;
};
m.translate = function() {
var v = translate.apply(m, arguments);
return v === m ? clipAuto ? m.clipExtent(null) : m : v;
};
m.clipExtent = function(_) {
var v = clipExtent.apply(m, arguments);
if (v === m) {
if (clipAuto = _ == null) {
var k = π * scale(), t = translate();
clipExtent([ [ t[0] - k, t[1] - k ], [ t[0] + k, t[1] + k ] ]);
}
} else if (clipAuto) {
v = null;
}
return v;
};
return m.clipExtent(null);
}
(d3.geo.mercator = function() {
return d3_geo_mercatorProjection(d3_geo_mercator);
}).raw = d3_geo_mercator;
var d3_geo_orthographic = d3_geo_azimuthal(function() {
return 1;
}, Math.asin);
(d3.geo.orthographic = function() {
return d3_geo_projection(d3_geo_orthographic);
}).raw = d3_geo_orthographic;
var d3_geo_stereographic = d3_geo_azimuthal(function(cosλcosφ) {
return 1 / (1 + cosλcosφ);
}, function(ρ) {
return 2 * Math.atan(ρ);
});
(d3.geo.stereographic = function() {
return d3_geo_projection(d3_geo_stereographic);
}).raw = d3_geo_stereographic;
function d3_geo_transverseMercator(λ, φ) {
var B = Math.cos(φ) * Math.sin(λ);
return [ Math.log((1 + B) / (1 - B)) / 2, Math.atan2(Math.tan(φ), Math.cos(λ)) ];
}
d3_geo_transverseMercator.invert = function(x, y) {
return [ Math.atan2(d3_sinh(x), Math.cos(y)), d3_asin(Math.sin(y) / d3_cosh(x)) ];
};
(d3.geo.transverseMercator = function() {
return d3_geo_mercatorProjection(d3_geo_transverseMercator);
}).raw = d3_geo_transverseMercator;
d3.geom = {};
function d3_geom_pointX(d) {
return d[0];
}
function d3_geom_pointY(d) {
return d[1];
}
d3.geom.hull = function(vertices) {
var x = d3_geom_pointX, y = d3_geom_pointY;
if (arguments.length) return hull(vertices);
function hull(data) {
if (data.length < 3) return [];
var fx = d3_functor(x), fy = d3_functor(y), n = data.length, vertices, plen = n - 1, points = [], stack = [], d, i, j, h = 0, x1, y1, x2, y2, u, v, a, sp;
if (fx === d3_geom_pointX && y === d3_geom_pointY) vertices = data; else for (i = 0,
vertices = []; i < n; ++i) {
vertices.push([ +fx.call(this, d = data[i], i), +fy.call(this, d, i) ]);
}
for (i = 1; i < n; ++i) {
if (vertices[i][1] < vertices[h][1] || vertices[i][1] == vertices[h][1] && vertices[i][0] < vertices[h][0]) h = i;
}
for (i = 0; i < n; ++i) {
if (i === h) continue;
y1 = vertices[i][1] - vertices[h][1];
x1 = vertices[i][0] - vertices[h][0];
points.push({
angle: Math.atan2(y1, x1),
index: i
});
}
points.sort(function(a, b) {
return a.angle - b.angle;
});
a = points[0].angle;
v = points[0].index;
u = 0;
for (i = 1; i < plen; ++i) {
j = points[i].index;
if (a == points[i].angle) {
x1 = vertices[v][0] - vertices[h][0];
y1 = vertices[v][1] - vertices[h][1];
x2 = vertices[j][0] - vertices[h][0];
y2 = vertices[j][1] - vertices[h][1];
if (x1 * x1 + y1 * y1 >= x2 * x2 + y2 * y2) {
points[i].index = -1;
continue;
} else {
points[u].index = -1;
}
}
a = points[i].angle;
u = i;
v = j;
}
stack.push(h);
for (i = 0, j = 0; i < 2; ++j) {
if (points[j].index > -1) {
stack.push(points[j].index);
i++;
}
}
sp = stack.length;
for (;j < plen; ++j) {
if (points[j].index < 0) continue;
while (!d3_geom_hullCCW(stack[sp - 2], stack[sp - 1], points[j].index, vertices)) {
--sp;
}
stack[sp++] = points[j].index;
}
var poly = [];
for (i = sp - 1; i >= 0; --i) poly.push(data[stack[i]]);
return poly;
}
hull.x = function(_) {
return arguments.length ? (x = _, hull) : x;
};
hull.y = function(_) {
return arguments.length ? (y = _, hull) : y;
};
return hull;
};
function d3_geom_hullCCW(i1, i2, i3, v) {
var t, a, b, c, d, e, f;
t = v[i1];
a = t[0];
b = t[1];
t = v[i2];
c = t[0];
d = t[1];
t = v[i3];
e = t[0];
f = t[1];
return (f - b) * (c - a) - (d - b) * (e - a) > 0;
}
d3.geom.polygon = function(coordinates) {
d3_subclass(coordinates, d3_geom_polygonPrototype);
return coordinates;
};
var d3_geom_polygonPrototype = d3.geom.polygon.prototype = [];
d3_geom_polygonPrototype.area = function() {
var i = -1, n = this.length, a, b = this[n - 1], area = 0;
while (++i < n) {
a = b;
b = this[i];
area += a[1] * b[0] - a[0] * b[1];
}
return area * .5;
};
d3_geom_polygonPrototype.centroid = function(k) {
var i = -1, n = this.length, x = 0, y = 0, a, b = this[n - 1], c;
if (!arguments.length) k = -1 / (6 * this.area());
while (++i < n) {
a = b;
b = this[i];
c = a[0] * b[1] - b[0] * a[1];
x += (a[0] + b[0]) * c;
y += (a[1] + b[1]) * c;
}
return [ x * k, y * k ];
};
d3_geom_polygonPrototype.clip = function(subject) {
var input, closed = d3_geom_polygonClosed(subject), i = -1, n = this.length - d3_geom_polygonClosed(this), j, m, a = this[n - 1], b, c, d;
while (++i < n) {
input = subject.slice();
subject.length = 0;
b = this[i];
c = input[(m = input.length - closed) - 1];
j = -1;
while (++j < m) {
d = input[j];
if (d3_geom_polygonInside(d, a, b)) {
if (!d3_geom_polygonInside(c, a, b)) {
subject.push(d3_geom_polygonIntersect(c, d, a, b));
}
subject.push(d);
} else if (d3_geom_polygonInside(c, a, b)) {
subject.push(d3_geom_polygonIntersect(c, d, a, b));
}
c = d;
}
if (closed) subject.push(subject[0]);
a = b;
}
return subject;
};
function d3_geom_polygonInside(p, a, b) {
return (b[0] - a[0]) * (p[1] - a[1]) < (b[1] - a[1]) * (p[0] - a[0]);
}
function d3_geom_polygonIntersect(c, d, a, b) {
var x1 = c[0], x3 = a[0], x21 = d[0] - x1, x43 = b[0] - x3, y1 = c[1], y3 = a[1], y21 = d[1] - y1, y43 = b[1] - y3, ua = (x43 * (y1 - y3) - y43 * (x1 - x3)) / (y43 * x21 - x43 * y21);
return [ x1 + ua * x21, y1 + ua * y21 ];
}
function d3_geom_polygonClosed(coordinates) {
var a = coordinates[0], b = coordinates[coordinates.length - 1];
return !(a[0] - b[0] || a[1] - b[1]);
}
var d3_geom_voronoiEdges, d3_geom_voronoiCells, d3_geom_voronoiBeaches, d3_geom_voronoiBeachPool = [], d3_geom_voronoiFirstCircle, d3_geom_voronoiCircles, d3_geom_voronoiCirclePool = [];
function d3_geom_voronoiBeach() {
d3_geom_voronoiRedBlackNode(this);
this.edge = this.site = this.circle = null;
}
function d3_geom_voronoiCreateBeach(site) {
var beach = d3_geom_voronoiBeachPool.pop() || new d3_geom_voronoiBeach();
beach.site = site;
return beach;
}
function d3_geom_voronoiDetachBeach(beach) {
d3_geom_voronoiDetachCircle(beach);
d3_geom_voronoiBeaches.remove(beach);
d3_geom_voronoiBeachPool.push(beach);
d3_geom_voronoiRedBlackNode(beach);
}
function d3_geom_voronoiRemoveBeach(beach) {
var circle = beach.circle, x = circle.x, y = circle.cy, vertex = {
x: x,
y: y
}, previous = beach.P, next = beach.N, disappearing = [ beach ];
d3_geom_voronoiDetachBeach(beach);
var lArc = previous;
while (lArc.circle && abs(x - lArc.circle.x) < ε && abs(y - lArc.circle.cy) < ε) {
previous = lArc.P;
disappearing.unshift(lArc);
d3_geom_voronoiDetachBeach(lArc);
lArc = previous;
}
disappearing.unshift(lArc);
d3_geom_voronoiDetachCircle(lArc);
var rArc = next;
while (rArc.circle && abs(x - rArc.circle.x) < ε && abs(y - rArc.circle.cy) < ε) {
next = rArc.N;
disappearing.push(rArc);
d3_geom_voronoiDetachBeach(rArc);
rArc = next;
}
disappearing.push(rArc);
d3_geom_voronoiDetachCircle(rArc);
var nArcs = disappearing.length, iArc;
for (iArc = 1; iArc < nArcs; ++iArc) {
rArc = disappearing[iArc];
lArc = disappearing[iArc - 1];
d3_geom_voronoiSetEdgeEnd(rArc.edge, lArc.site, rArc.site, vertex);
}
lArc = disappearing[0];
rArc = disappearing[nArcs - 1];
rArc.edge = d3_geom_voronoiCreateEdge(lArc.site, rArc.site, null, vertex);
d3_geom_voronoiAttachCircle(lArc);
d3_geom_voronoiAttachCircle(rArc);
}
function d3_geom_voronoiAddBeach(site) {
var x = site.x, directrix = site.y, lArc, rArc, dxl, dxr, node = d3_geom_voronoiBeaches._;
while (node) {
dxl = d3_geom_voronoiLeftBreakPoint(node, directrix) - x;
if (dxl > ε) node = node.L; else {
dxr = x - d3_geom_voronoiRightBreakPoint(node, directrix);
if (dxr > ε) {
if (!node.R) {
lArc = node;
break;
}
node = node.R;
} else {
if (dxl > -ε) {
lArc = node.P;
rArc = node;
} else if (dxr > -ε) {
lArc = node;
rArc = node.N;
} else {
lArc = rArc = node;
}
break;
}
}
}
var newArc = d3_geom_voronoiCreateBeach(site);
d3_geom_voronoiBeaches.insert(lArc, newArc);
if (!lArc && !rArc) return;
if (lArc === rArc) {
d3_geom_voronoiDetachCircle(lArc);
rArc = d3_geom_voronoiCreateBeach(lArc.site);
d3_geom_voronoiBeaches.insert(newArc, rArc);
newArc.edge = rArc.edge = d3_geom_voronoiCreateEdge(lArc.site, newArc.site);
d3_geom_voronoiAttachCircle(lArc);
d3_geom_voronoiAttachCircle(rArc);
return;
}
if (!rArc) {
newArc.edge = d3_geom_voronoiCreateEdge(lArc.site, newArc.site);
return;
}
d3_geom_voronoiDetachCircle(lArc);
d3_geom_voronoiDetachCircle(rArc);
var lSite = lArc.site, ax = lSite.x, ay = lSite.y, bx = site.x - ax, by = site.y - ay, rSite = rArc.site, cx = rSite.x - ax, cy = rSite.y - ay, d = 2 * (bx * cy - by * cx), hb = bx * bx + by * by, hc = cx * cx + cy * cy, vertex = {
x: (cy * hb - by * hc) / d + ax,
y: (bx * hc - cx * hb) / d + ay
};
d3_geom_voronoiSetEdgeEnd(rArc.edge, lSite, rSite, vertex);
newArc.edge = d3_geom_voronoiCreateEdge(lSite, site, null, vertex);
rArc.edge = d3_geom_voronoiCreateEdge(site, rSite, null, vertex);
d3_geom_voronoiAttachCircle(lArc);
d3_geom_voronoiAttachCircle(rArc);
}
function d3_geom_voronoiLeftBreakPoint(arc, directrix) {
var site = arc.site, rfocx = site.x, rfocy = site.y, pby2 = rfocy - directrix;
if (!pby2) return rfocx;
var lArc = arc.P;
if (!lArc) return -Infinity;
site = lArc.site;
var lfocx = site.x, lfocy = site.y, plby2 = lfocy - directrix;
if (!plby2) return lfocx;
var hl = lfocx - rfocx, aby2 = 1 / pby2 - 1 / plby2, b = hl / plby2;
if (aby2) return (-b + Math.sqrt(b * b - 2 * aby2 * (hl * hl / (-2 * plby2) - lfocy + plby2 / 2 + rfocy - pby2 / 2))) / aby2 + rfocx;
return (rfocx + lfocx) / 2;
}
function d3_geom_voronoiRightBreakPoint(arc, directrix) {
var rArc = arc.N;
if (rArc) return d3_geom_voronoiLeftBreakPoint(rArc, directrix);
var site = arc.site;
return site.y === directrix ? site.x : Infinity;
}
function d3_geom_voronoiCell(site) {
this.site = site;
this.edges = [];
}
d3_geom_voronoiCell.prototype.prepare = function() {
var halfEdges = this.edges, iHalfEdge = halfEdges.length, edge;
while (iHalfEdge--) {
edge = halfEdges[iHalfEdge].edge;
if (!edge.b || !edge.a) halfEdges.splice(iHalfEdge, 1);
}
halfEdges.sort(d3_geom_voronoiHalfEdgeOrder);
return halfEdges.length;
};
function d3_geom_voronoiCloseCells(extent) {
var x0 = extent[0][0], x1 = extent[1][0], y0 = extent[0][1], y1 = extent[1][1], x2, y2, x3, y3, cells = d3_geom_voronoiCells, iCell = cells.length, cell, iHalfEdge, halfEdges, nHalfEdges, start, end;
while (iCell--) {
cell = cells[iCell];
if (!cell || !cell.prepare()) continue;
halfEdges = cell.edges;
nHalfEdges = halfEdges.length;
iHalfEdge = 0;
while (iHalfEdge < nHalfEdges) {
end = halfEdges[iHalfEdge].end(), x3 = end.x, y3 = end.y;
start = halfEdges[++iHalfEdge % nHalfEdges].start(), x2 = start.x, y2 = start.y;
if (abs(x3 - x2) > ε || abs(y3 - y2) > ε) {
halfEdges.splice(iHalfEdge, 0, new d3_geom_voronoiHalfEdge(d3_geom_voronoiCreateBorderEdge(cell.site, end, abs(x3 - x0) < ε && y1 - y3 > ε ? {
x: x0,
y: abs(x2 - x0) < ε ? y2 : y1
} : abs(y3 - y1) < ε && x1 - x3 > ε ? {
x: abs(y2 - y1) < ε ? x2 : x1,
y: y1
} : abs(x3 - x1) < ε && y3 - y0 > ε ? {
x: x1,
y: abs(x2 - x1) < ε ? y2 : y0
} : abs(y3 - y0) < ε && x3 - x0 > ε ? {
x: abs(y2 - y0) < ε ? x2 : x0,
y: y0
} : null), cell.site, null));
++nHalfEdges;
}
}
}
}
function d3_geom_voronoiHalfEdgeOrder(a, b) {
return b.angle - a.angle;
}
function d3_geom_voronoiCircle() {
d3_geom_voronoiRedBlackNode(this);
this.x = this.y = this.arc = this.site = this.cy = null;
}
function d3_geom_voronoiAttachCircle(arc) {
var lArc = arc.P, rArc = arc.N;
if (!lArc || !rArc) return;
var lSite = lArc.site, cSite = arc.site, rSite = rArc.site;
if (lSite === rSite) return;
var bx = cSite.x, by = cSite.y, ax = lSite.x - bx, ay = lSite.y - by, cx = rSite.x - bx, cy = rSite.y - by;
var d = 2 * (ax * cy - ay * cx);
if (d >= -ε2) return;
var ha = ax * ax + ay * ay, hc = cx * cx + cy * cy, x = (cy * ha - ay * hc) / d, y = (ax * hc - cx * ha) / d, cy = y + by;
var circle = d3_geom_voronoiCirclePool.pop() || new d3_geom_voronoiCircle();
circle.arc = arc;
circle.site = cSite;
circle.x = x + bx;
circle.y = cy + Math.sqrt(x * x + y * y);
circle.cy = cy;
arc.circle = circle;
var before = null, node = d3_geom_voronoiCircles._;
while (node) {
if (circle.y < node.y || circle.y === node.y && circle.x <= node.x) {
if (node.L) node = node.L; else {
before = node.P;
break;
}
} else {
if (node.R) node = node.R; else {
before = node;
break;
}
}
}
d3_geom_voronoiCircles.insert(before, circle);
if (!before) d3_geom_voronoiFirstCircle = circle;
}
function d3_geom_voronoiDetachCircle(arc) {
var circle = arc.circle;
if (circle) {
if (!circle.P) d3_geom_voronoiFirstCircle = circle.N;
d3_geom_voronoiCircles.remove(circle);
d3_geom_voronoiCirclePool.push(circle);
d3_geom_voronoiRedBlackNode(circle);
arc.circle = null;
}
}
function d3_geom_voronoiClipEdges(extent) {
var edges = d3_geom_voronoiEdges, clip = d3_geom_clipLine(extent[0][0], extent[0][1], extent[1][0], extent[1][1]), i = edges.length, e;
while (i--) {
e = edges[i];
if (!d3_geom_voronoiConnectEdge(e, extent) || !clip(e) || abs(e.a.x - e.b.x) < ε && abs(e.a.y - e.b.y) < ε) {
e.a = e.b = null;
edges.splice(i, 1);
}
}
}
function d3_geom_voronoiConnectEdge(edge, extent) {
var vb = edge.b;
if (vb) return true;
var va = edge.a, x0 = extent[0][0], x1 = extent[1][0], y0 = extent[0][1], y1 = extent[1][1], lSite = edge.l, rSite = edge.r, lx = lSite.x, ly = lSite.y, rx = rSite.x, ry = rSite.y, fx = (lx + rx) / 2, fy = (ly + ry) / 2, fm, fb;
if (ry === ly) {
if (fx < x0 || fx >= x1) return;
if (lx > rx) {
if (!va) va = {
x: fx,
y: y0
}; else if (va.y >= y1) return;
vb = {
x: fx,
y: y1
};
} else {
if (!va) va = {
x: fx,
y: y1
}; else if (va.y < y0) return;
vb = {
x: fx,
y: y0
};
}
} else {
fm = (lx - rx) / (ry - ly);
fb = fy - fm * fx;
if (fm < -1 || fm > 1) {
if (lx > rx) {
if (!va) va = {
x: (y0 - fb) / fm,
y: y0
}; else if (va.y >= y1) return;
vb = {
x: (y1 - fb) / fm,
y: y1
};
} else {
if (!va) va = {
x: (y1 - fb) / fm,
y: y1
}; else if (va.y < y0) return;
vb = {
x: (y0 - fb) / fm,
y: y0
};
}
} else {
if (ly < ry) {
if (!va) va = {
x: x0,
y: fm * x0 + fb
}; else if (va.x >= x1) return;
vb = {
x: x1,
y: fm * x1 + fb
};
} else {
if (!va) va = {
x: x1,
y: fm * x1 + fb
}; else if (va.x < x0) return;
vb = {
x: x0,
y: fm * x0 + fb
};
}
}
}
edge.a = va;
edge.b = vb;
return true;
}
function d3_geom_voronoiEdge(lSite, rSite) {
this.l = lSite;
this.r = rSite;
this.a = this.b = null;
}
function d3_geom_voronoiCreateEdge(lSite, rSite, va, vb) {
var edge = new d3_geom_voronoiEdge(lSite, rSite);
d3_geom_voronoiEdges.push(edge);
if (va) d3_geom_voronoiSetEdgeEnd(edge, lSite, rSite, va);
if (vb) d3_geom_voronoiSetEdgeEnd(edge, rSite, lSite, vb);
d3_geom_voronoiCells[lSite.i].edges.push(new d3_geom_voronoiHalfEdge(edge, lSite, rSite));
d3_geom_voronoiCells[rSite.i].edges.push(new d3_geom_voronoiHalfEdge(edge, rSite, lSite));
return edge;
}
function d3_geom_voronoiCreateBorderEdge(lSite, va, vb) {
var edge = new d3_geom_voronoiEdge(lSite, null);
edge.a = va;
edge.b = vb;
d3_geom_voronoiEdges.push(edge);
return edge;
}
function d3_geom_voronoiSetEdgeEnd(edge, lSite, rSite, vertex) {
if (!edge.a && !edge.b) {
edge.a = vertex;
edge.l = lSite;
edge.r = rSite;
} else if (edge.l === rSite) {
edge.b = vertex;
} else {
edge.a = vertex;
}
}
function d3_geom_voronoiHalfEdge(edge, lSite, rSite) {
var va = edge.a, vb = edge.b;
this.edge = edge;
this.site = lSite;
this.angle = rSite ? Math.atan2(rSite.y - lSite.y, rSite.x - lSite.x) : edge.l === lSite ? Math.atan2(vb.x - va.x, va.y - vb.y) : Math.atan2(va.x - vb.x, vb.y - va.y);
}
d3_geom_voronoiHalfEdge.prototype = {
start: function() {
return this.edge.l === this.site ? this.edge.a : this.edge.b;
},
end: function() {
return this.edge.l === this.site ? this.edge.b : this.edge.a;
}
};
function d3_geom_voronoiRedBlackTree() {
this._ = null;
}
function d3_geom_voronoiRedBlackNode(node) {
node.U = node.C = node.L = node.R = node.P = node.N = null;
}
d3_geom_voronoiRedBlackTree.prototype = {
insert: function(after, node) {
var parent, grandpa, uncle;
if (after) {
node.P = after;
node.N = after.N;
if (after.N) after.N.P = node;
after.N = node;
if (after.R) {
after = after.R;
while (after.L) after = after.L;
after.L = node;
} else {
after.R = node;
}
parent = after;
} else if (this._) {
after = d3_geom_voronoiRedBlackFirst(this._);
node.P = null;
node.N = after;
after.P = after.L = node;
parent = after;
} else {
node.P = node.N = null;
this._ = node;
parent = null;
}
node.L = node.R = null;
node.U = parent;
node.C = true;
after = node;
while (parent && parent.C) {
grandpa = parent.U;
if (parent === grandpa.L) {
uncle = grandpa.R;
if (uncle && uncle.C) {
parent.C = uncle.C = false;
grandpa.C = true;
after = grandpa;
} else {
if (after === parent.R) {
d3_geom_voronoiRedBlackRotateLeft(this, parent);
after = parent;
parent = after.U;
}
parent.C = false;
grandpa.C = true;
d3_geom_voronoiRedBlackRotateRight(this, grandpa);
}
} else {
uncle = grandpa.L;
if (uncle && uncle.C) {
parent.C = uncle.C = false;
grandpa.C = true;
after = grandpa;
} else {
if (after === parent.L) {
d3_geom_voronoiRedBlackRotateRight(this, parent);
after = parent;
parent = after.U;
}
parent.C = false;
grandpa.C = true;
d3_geom_voronoiRedBlackRotateLeft(this, grandpa);
}
}
parent = after.U;
}
this._.C = false;
},
remove: function(node) {
if (node.N) node.N.P = node.P;
if (node.P) node.P.N = node.N;
node.N = node.P = null;
var parent = node.U, sibling, left = node.L, right = node.R, next, red;
if (!left) next = right; else if (!right) next = left; else next = d3_geom_voronoiRedBlackFirst(right);
if (parent) {
if (parent.L === node) parent.L = next; else parent.R = next;
} else {
this._ = next;
}
if (left && right) {
red = next.C;
next.C = node.C;
next.L = left;
left.U = next;
if (next !== right) {
parent = next.U;
next.U = node.U;
node = next.R;
parent.L = node;
next.R = right;
right.U = next;
} else {
next.U = parent;
parent = next;
node = next.R;
}
} else {
red = node.C;
node = next;
}
if (node) node.U = parent;
if (red) return;
if (node && node.C) {
node.C = false;
return;
}
do {
if (node === this._) break;
if (node === parent.L) {
sibling = parent.R;
if (sibling.C) {
sibling.C = false;
parent.C = true;
d3_geom_voronoiRedBlackRotateLeft(this, parent);
sibling = parent.R;
}
if (sibling.L && sibling.L.C || sibling.R && sibling.R.C) {
if (!sibling.R || !sibling.R.C) {
sibling.L.C = false;
sibling.C = true;
d3_geom_voronoiRedBlackRotateRight(this, sibling);
sibling = parent.R;
}
sibling.C = parent.C;
parent.C = sibling.R.C = false;
d3_geom_voronoiRedBlackRotateLeft(this, parent);
node = this._;
break;
}
} else {
sibling = parent.L;
if (sibling.C) {
sibling.C = false;
parent.C = true;
d3_geom_voronoiRedBlackRotateRight(this, parent);
sibling = parent.L;
}
if (sibling.L && sibling.L.C || sibling.R && sibling.R.C) {
if (!sibling.L || !sibling.L.C) {
sibling.R.C = false;
sibling.C = true;
d3_geom_voronoiRedBlackRotateLeft(this, sibling);
sibling = parent.L;
}
sibling.C = parent.C;
parent.C = sibling.L.C = false;
d3_geom_voronoiRedBlackRotateRight(this, parent);
node = this._;
break;
}
}
sibling.C = true;
node = parent;
parent = parent.U;
} while (!node.C);
if (node) node.C = false;
}
};
function d3_geom_voronoiRedBlackRotateLeft(tree, node) {
var p = node, q = node.R, parent = p.U;
if (parent) {
if (parent.L === p) parent.L = q; else parent.R = q;
} else {
tree._ = q;
}
q.U = parent;
p.U = q;
p.R = q.L;
if (p.R) p.R.U = p;
q.L = p;
}
function d3_geom_voronoiRedBlackRotateRight(tree, node) {
var p = node, q = node.L, parent = p.U;
if (parent) {
if (parent.L === p) parent.L = q; else parent.R = q;
} else {
tree._ = q;
}
q.U = parent;
p.U = q;
p.L = q.R;
if (p.L) p.L.U = p;
q.R = p;
}
function d3_geom_voronoiRedBlackFirst(node) {
while (node.L) node = node.L;
return node;
}
function d3_geom_voronoi(sites, bbox) {
var site = sites.sort(d3_geom_voronoiVertexOrder).pop(), x0, y0, circle;
d3_geom_voronoiEdges = [];
d3_geom_voronoiCells = new Array(sites.length);
d3_geom_voronoiBeaches = new d3_geom_voronoiRedBlackTree();
d3_geom_voronoiCircles = new d3_geom_voronoiRedBlackTree();
while (true) {
circle = d3_geom_voronoiFirstCircle;
if (site && (!circle || site.y < circle.y || site.y === circle.y && site.x < circle.x)) {
if (site.x !== x0 || site.y !== y0) {
d3_geom_voronoiCells[site.i] = new d3_geom_voronoiCell(site);
d3_geom_voronoiAddBeach(site);
x0 = site.x, y0 = site.y;
}
site = sites.pop();
} else if (circle) {
d3_geom_voronoiRemoveBeach(circle.arc);
} else {
break;
}
}
if (bbox) d3_geom_voronoiClipEdges(bbox), d3_geom_voronoiCloseCells(bbox);
var diagram = {
cells: d3_geom_voronoiCells,
edges: d3_geom_voronoiEdges
};
d3_geom_voronoiBeaches = d3_geom_voronoiCircles = d3_geom_voronoiEdges = d3_geom_voronoiCells = null;
return diagram;
}
function d3_geom_voronoiVertexOrder(a, b) {
return b.y - a.y || b.x - a.x;
}
d3.geom.voronoi = function(points) {
var x = d3_geom_pointX, y = d3_geom_pointY, fx = x, fy = y, clipExtent = d3_geom_voronoiClipExtent;
if (points) return voronoi(points);
function voronoi(data) {
var polygons = new Array(data.length), x0 = clipExtent[0][0], y0 = clipExtent[0][1], x1 = clipExtent[1][0], y1 = clipExtent[1][1];
d3_geom_voronoi(sites(data), clipExtent).cells.forEach(function(cell, i) {
var edges = cell.edges, site = cell.site, polygon = polygons[i] = edges.length ? edges.map(function(e) {
var s = e.start();
return [ s.x, s.y ];
}) : site.x >= x0 && site.x <= x1 && site.y >= y0 && site.y <= y1 ? [ [ x0, y1 ], [ x1, y1 ], [ x1, y0 ], [ x0, y0 ] ] : [];
polygon.point = data[i];
});
return polygons;
}
function sites(data) {
return data.map(function(d, i) {
return {
x: Math.round(fx(d, i) / ε) * ε,
y: Math.round(fy(d, i) / ε) * ε,
i: i
};
});
}
voronoi.links = function(data) {
return d3_geom_voronoi(sites(data)).edges.filter(function(edge) {
return edge.l && edge.r;
}).map(function(edge) {
return {
source: data[edge.l.i],
target: data[edge.r.i]
};
});
};
voronoi.triangles = function(data) {
var triangles = [];
d3_geom_voronoi(sites(data)).cells.forEach(function(cell, i) {
var site = cell.site, edges = cell.edges.sort(d3_geom_voronoiHalfEdgeOrder), j = -1, m = edges.length, e0, s0, e1 = edges[m - 1].edge, s1 = e1.l === site ? e1.r : e1.l;
while (++j < m) {
e0 = e1;
s0 = s1;
e1 = edges[j].edge;
s1 = e1.l === site ? e1.r : e1.l;
if (i < s0.i && i < s1.i && d3_geom_voronoiTriangleArea(site, s0, s1) < 0) {
triangles.push([ data[i], data[s0.i], data[s1.i] ]);
}
}
});
return triangles;
};
voronoi.x = function(_) {
return arguments.length ? (fx = d3_functor(x = _), voronoi) : x;
};
voronoi.y = function(_) {
return arguments.length ? (fy = d3_functor(y = _), voronoi) : y;
};
voronoi.clipExtent = function(_) {
if (!arguments.length) return clipExtent === d3_geom_voronoiClipExtent ? null : clipExtent;
clipExtent = _ == null ? d3_geom_voronoiClipExtent : _;
return voronoi;
};
voronoi.size = function(_) {
if (!arguments.length) return clipExtent === d3_geom_voronoiClipExtent ? null : clipExtent && clipExtent[1];
return voronoi.clipExtent(_ && [ [ 0, 0 ], _ ]);
};
return voronoi;
};
var d3_geom_voronoiClipExtent = [ [ -1e6, -1e6 ], [ 1e6, 1e6 ] ];
function d3_geom_voronoiTriangleArea(a, b, c) {
return (a.x - c.x) * (b.y - a.y) - (a.x - b.x) * (c.y - a.y);
}
d3.geom.delaunay = function(vertices) {
return d3.geom.voronoi().triangles(vertices);
};
d3.geom.quadtree = function(points, x1, y1, x2, y2) {
var x = d3_geom_pointX, y = d3_geom_pointY, compat;
if (compat = arguments.length) {
x = d3_geom_quadtreeCompatX;
y = d3_geom_quadtreeCompatY;
if (compat === 3) {
y2 = y1;
x2 = x1;
y1 = x1 = 0;
}
return quadtree(points);
}
function quadtree(data) {
var d, fx = d3_functor(x), fy = d3_functor(y), xs, ys, i, n, x1_, y1_, x2_, y2_;
if (x1 != null) {
x1_ = x1, y1_ = y1, x2_ = x2, y2_ = y2;
} else {
x2_ = y2_ = -(x1_ = y1_ = Infinity);
xs = [], ys = [];
n = data.length;
if (compat) for (i = 0; i < n; ++i) {
d = data[i];
if (d.x < x1_) x1_ = d.x;
if (d.y < y1_) y1_ = d.y;
if (d.x > x2_) x2_ = d.x;
if (d.y > y2_) y2_ = d.y;
xs.push(d.x);
ys.push(d.y);
} else for (i = 0; i < n; ++i) {
var x_ = +fx(d = data[i], i), y_ = +fy(d, i);
if (x_ < x1_) x1_ = x_;
if (y_ < y1_) y1_ = y_;
if (x_ > x2_) x2_ = x_;
if (y_ > y2_) y2_ = y_;
xs.push(x_);
ys.push(y_);
}
}
var dx = x2_ - x1_, dy = y2_ - y1_;
if (dx > dy) y2_ = y1_ + dx; else x2_ = x1_ + dy;
function insert(n, d, x, y, x1, y1, x2, y2) {
if (isNaN(x) || isNaN(y)) return;
if (n.leaf) {
var nx = n.x, ny = n.y;
if (nx != null) {
if (abs(nx - x) + abs(ny - y) < .01) {
insertChild(n, d, x, y, x1, y1, x2, y2);
} else {
var nPoint = n.point;
n.x = n.y = n.point = null;
insertChild(n, nPoint, nx, ny, x1, y1, x2, y2);
insertChild(n, d, x, y, x1, y1, x2, y2);
}
} else {
n.x = x, n.y = y, n.point = d;
}
} else {
insertChild(n, d, x, y, x1, y1, x2, y2);
}
}
function insertChild(n, d, x, y, x1, y1, x2, y2) {
var sx = (x1 + x2) * .5, sy = (y1 + y2) * .5, right = x >= sx, bottom = y >= sy, i = (bottom << 1) + right;
n.leaf = false;
n = n.nodes[i] || (n.nodes[i] = d3_geom_quadtreeNode());
if (right) x1 = sx; else x2 = sx;
if (bottom) y1 = sy; else y2 = sy;
insert(n, d, x, y, x1, y1, x2, y2);
}
var root = d3_geom_quadtreeNode();
root.add = function(d) {
insert(root, d, +fx(d, ++i), +fy(d, i), x1_, y1_, x2_, y2_);
};
root.visit = function(f) {
d3_geom_quadtreeVisit(f, root, x1_, y1_, x2_, y2_);
};
i = -1;
if (x1 == null) {
while (++i < n) {
insert(root, data[i], xs[i], ys[i], x1_, y1_, x2_, y2_);
}
--i;
} else data.forEach(root.add);
xs = ys = data = d = null;
return root;
}
quadtree.x = function(_) {
return arguments.length ? (x = _, quadtree) : x;
};
quadtree.y = function(_) {
return arguments.length ? (y = _, quadtree) : y;
};
quadtree.extent = function(_) {
if (!arguments.length) return x1 == null ? null : [ [ x1, y1 ], [ x2, y2 ] ];
if (_ == null) x1 = y1 = x2 = y2 = null; else x1 = +_[0][0], y1 = +_[0][1], x2 = +_[1][0],
y2 = +_[1][1];
return quadtree;
};
quadtree.size = function(_) {
if (!arguments.length) return x1 == null ? null : [ x2 - x1, y2 - y1 ];
if (_ == null) x1 = y1 = x2 = y2 = null; else x1 = y1 = 0, x2 = +_[0], y2 = +_[1];
return quadtree;
};
return quadtree;
};
function d3_geom_quadtreeCompatX(d) {
return d.x;
}
function d3_geom_quadtreeCompatY(d) {
return d.y;
}
function d3_geom_quadtreeNode() {
return {
leaf: true,
nodes: [],
point: null,
x: null,
y: null
};
}
function d3_geom_quadtreeVisit(f, node, x1, y1, x2, y2) {
if (!f(node, x1, y1, x2, y2)) {
var sx = (x1 + x2) * .5, sy = (y1 + y2) * .5, children = node.nodes;
if (children[0]) d3_geom_quadtreeVisit(f, children[0], x1, y1, sx, sy);
if (children[1]) d3_geom_quadtreeVisit(f, children[1], sx, y1, x2, sy);
if (children[2]) d3_geom_quadtreeVisit(f, children[2], x1, sy, sx, y2);
if (children[3]) d3_geom_quadtreeVisit(f, children[3], sx, sy, x2, y2);
}
}
d3.interpolateRgb = d3_interpolateRgb;
function d3_interpolateRgb(a, b) {
a = d3.rgb(a);
b = d3.rgb(b);
var ar = a.r, ag = a.g, ab = a.b, br = b.r - ar, bg = b.g - ag, bb = b.b - ab;
return function(t) {
return "#" + d3_rgb_hex(Math.round(ar + br * t)) + d3_rgb_hex(Math.round(ag + bg * t)) + d3_rgb_hex(Math.round(ab + bb * t));
};
}
d3.interpolateObject = d3_interpolateObject;
function d3_interpolateObject(a, b) {
var i = {}, c = {}, k;
for (k in a) {
if (k in b) {
i[k] = d3_interpolate(a[k], b[k]);
} else {
c[k] = a[k];
}
}
for (k in b) {
if (!(k in a)) {
c[k] = b[k];
}
}
return function(t) {
for (k in i) c[k] = i[k](t);
return c;
};
}
d3.interpolateNumber = d3_interpolateNumber;
function d3_interpolateNumber(a, b) {
b -= a = +a;
return function(t) {
return a + b * t;
};
}
d3.interpolateString = d3_interpolateString;
function d3_interpolateString(a, b) {
var m, i, j, s0 = 0, s1 = 0, s = [], q = [], n, o;
a = a + "", b = b + "";
d3_interpolate_number.lastIndex = 0;
for (i = 0; m = d3_interpolate_number.exec(b); ++i) {
if (m.index) s.push(b.substring(s0, s1 = m.index));
q.push({
i: s.length,
x: m[0]
});
s.push(null);
s0 = d3_interpolate_number.lastIndex;
}
if (s0 < b.length) s.push(b.substring(s0));
for (i = 0, n = q.length; (m = d3_interpolate_number.exec(a)) && i < n; ++i) {
o = q[i];
if (o.x == m[0]) {
if (o.i) {
if (s[o.i + 1] == null) {
s[o.i - 1] += o.x;
s.splice(o.i, 1);
for (j = i + 1; j < n; ++j) q[j].i--;
} else {
s[o.i - 1] += o.x + s[o.i + 1];
s.splice(o.i, 2);
for (j = i + 1; j < n; ++j) q[j].i -= 2;
}
} else {
if (s[o.i + 1] == null) {
s[o.i] = o.x;
} else {
s[o.i] = o.x + s[o.i + 1];
s.splice(o.i + 1, 1);
for (j = i + 1; j < n; ++j) q[j].i--;
}
}
q.splice(i, 1);
n--;
i--;
} else {
o.x = d3_interpolateNumber(parseFloat(m[0]), parseFloat(o.x));
}
}
while (i < n) {
o = q.pop();
if (s[o.i + 1] == null) {
s[o.i] = o.x;
} else {
s[o.i] = o.x + s[o.i + 1];
s.splice(o.i + 1, 1);
}
n--;
}
if (s.length === 1) {
return s[0] == null ? (o = q[0].x, function(t) {
return o(t) + "";
}) : function() {
return b;
};
}
return function(t) {
for (i = 0; i < n; ++i) s[(o = q[i]).i] = o.x(t);
return s.join("");
};
}
var d3_interpolate_number = /[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g;
d3.interpolate = d3_interpolate;
function d3_interpolate(a, b) {
var i = d3.interpolators.length, f;
while (--i >= 0 && !(f = d3.interpolators[i](a, b))) ;
return f;
}
d3.interpolators = [ function(a, b) {
var t = typeof b;
return (t === "string" ? d3_rgb_names.has(b) || /^(#|rgb\(|hsl\()/.test(b) ? d3_interpolateRgb : d3_interpolateString : b instanceof d3_Color ? d3_interpolateRgb : t === "object" ? Array.isArray(b) ? d3_interpolateArray : d3_interpolateObject : d3_interpolateNumber)(a, b);
} ];
d3.interpolateArray = d3_interpolateArray;
function d3_interpolateArray(a, b) {
var x = [], c = [], na = a.length, nb = b.length, n0 = Math.min(a.length, b.length), i;
for (i = 0; i < n0; ++i) x.push(d3_interpolate(a[i], b[i]));
for (;i < na; ++i) c[i] = a[i];
for (;i < nb; ++i) c[i] = b[i];
return function(t) {
for (i = 0; i < n0; ++i) c[i] = x[i](t);
return c;
};
}
var d3_ease_default = function() {
return d3_identity;
};
var d3_ease = d3.map({
linear: d3_ease_default,
poly: d3_ease_poly,
quad: function() {
return d3_ease_quad;
},
cubic: function() {
return d3_ease_cubic;
},
sin: function() {
return d3_ease_sin;
},
exp: function() {
return d3_ease_exp;
},
circle: function() {
return d3_ease_circle;
},
elastic: d3_ease_elastic,
back: d3_ease_back,
bounce: function() {
return d3_ease_bounce;
}
});
var d3_ease_mode = d3.map({
"in": d3_identity,
out: d3_ease_reverse,
"in-out": d3_ease_reflect,
"out-in": function(f) {
return d3_ease_reflect(d3_ease_reverse(f));
}
});
d3.ease = function(name) {
var i = name.indexOf("-"), t = i >= 0 ? name.substring(0, i) : name, m = i >= 0 ? name.substring(i + 1) : "in";
t = d3_ease.get(t) || d3_ease_default;
m = d3_ease_mode.get(m) || d3_identity;
return d3_ease_clamp(m(t.apply(null, d3_arraySlice.call(arguments, 1))));
};
function d3_ease_clamp(f) {
return function(t) {
return t <= 0 ? 0 : t >= 1 ? 1 : f(t);
};
}
function d3_ease_reverse(f) {
return function(t) {
return 1 - f(1 - t);
};
}
function d3_ease_reflect(f) {
return function(t) {
return .5 * (t < .5 ? f(2 * t) : 2 - f(2 - 2 * t));
};
}
function d3_ease_quad(t) {
return t * t;
}
function d3_ease_cubic(t) {
return t * t * t;
}
function d3_ease_cubicInOut(t) {
if (t <= 0) return 0;
if (t >= 1) return 1;
var t2 = t * t, t3 = t2 * t;
return 4 * (t < .5 ? t3 : 3 * (t - t2) + t3 - .75);
}
function d3_ease_poly(e) {
return function(t) {
return Math.pow(t, e);
};
}
function d3_ease_sin(t) {
return 1 - Math.cos(t * halfπ);
}
function d3_ease_exp(t) {
return Math.pow(2, 10 * (t - 1));
}
function d3_ease_circle(t) {
return 1 - Math.sqrt(1 - t * t);
}
function d3_ease_elastic(a, p) {
var s;
if (arguments.length < 2) p = .45;
if (arguments.length) s = p / τ * Math.asin(1 / a); else a = 1, s = p / 4;
return function(t) {
return 1 + a * Math.pow(2, -10 * t) * Math.sin((t - s) * τ / p);
};
}
function d3_ease_back(s) {
if (!s) s = 1.70158;
return function(t) {
return t * t * ((s + 1) * t - s);
};
}
function d3_ease_bounce(t) {
return t < 1 / 2.75 ? 7.5625 * t * t : t < 2 / 2.75 ? 7.5625 * (t -= 1.5 / 2.75) * t + .75 : t < 2.5 / 2.75 ? 7.5625 * (t -= 2.25 / 2.75) * t + .9375 : 7.5625 * (t -= 2.625 / 2.75) * t + .984375;
}
d3.interpolateHcl = d3_interpolateHcl;
function d3_interpolateHcl(a, b) {
a = d3.hcl(a);
b = d3.hcl(b);
var ah = a.h, ac = a.c, al = a.l, bh = b.h - ah, bc = b.c - ac, bl = b.l - al;
if (isNaN(bc)) bc = 0, ac = isNaN(ac) ? b.c : ac;
if (isNaN(bh)) bh = 0, ah = isNaN(ah) ? b.h : ah; else if (bh > 180) bh -= 360; else if (bh < -180) bh += 360;
return function(t) {
return d3_hcl_lab(ah + bh * t, ac + bc * t, al + bl * t) + "";
};
}
d3.interpolateHsl = d3_interpolateHsl;
function d3_interpolateHsl(a, b) {
a = d3.hsl(a);
b = d3.hsl(b);
var ah = a.h, as = a.s, al = a.l, bh = b.h - ah, bs = b.s - as, bl = b.l - al;
if (isNaN(bs)) bs = 0, as = isNaN(as) ? b.s : as;
if (isNaN(bh)) bh = 0, ah = isNaN(ah) ? b.h : ah; else if (bh > 180) bh -= 360; else if (bh < -180) bh += 360;
return function(t) {
return d3_hsl_rgb(ah + bh * t, as + bs * t, al + bl * t) + "";
};
}
d3.interpolateLab = d3_interpolateLab;
function d3_interpolateLab(a, b) {
a = d3.lab(a);
b = d3.lab(b);
var al = a.l, aa = a.a, ab = a.b, bl = b.l - al, ba = b.a - aa, bb = b.b - ab;
return function(t) {
return d3_lab_rgb(al + bl * t, aa + ba * t, ab + bb * t) + "";
};
}
d3.interpolateRound = d3_interpolateRound;
function d3_interpolateRound(a, b) {
b -= a;
return function(t) {
return Math.round(a + b * t);
};
}
d3.transform = function(string) {
var g = d3_document.createElementNS(d3.ns.prefix.svg, "g");
return (d3.transform = function(string) {
if (string != null) {
g.setAttribute("transform", string);
var t = g.transform.baseVal.consolidate();
}
return new d3_transform(t ? t.matrix : d3_transformIdentity);
})(string);
};
function d3_transform(m) {
var r0 = [ m.a, m.b ], r1 = [ m.c, m.d ], kx = d3_transformNormalize(r0), kz = d3_transformDot(r0, r1), ky = d3_transformNormalize(d3_transformCombine(r1, r0, -kz)) || 0;
if (r0[0] * r1[1] < r1[0] * r0[1]) {
r0[0] *= -1;
r0[1] *= -1;
kx *= -1;
kz *= -1;
}
this.rotate = (kx ? Math.atan2(r0[1], r0[0]) : Math.atan2(-r1[0], r1[1])) * d3_degrees;
this.translate = [ m.e, m.f ];
this.scale = [ kx, ky ];
this.skew = ky ? Math.atan2(kz, ky) * d3_degrees : 0;
}
d3_transform.prototype.toString = function() {
return "translate(" + this.translate + ")rotate(" + this.rotate + ")skewX(" + this.skew + ")scale(" + this.scale + ")";
};
function d3_transformDot(a, b) {
return a[0] * b[0] + a[1] * b[1];
}
function d3_transformNormalize(a) {
var k = Math.sqrt(d3_transformDot(a, a));
if (k) {
a[0] /= k;
a[1] /= k;
}
return k;
}
function d3_transformCombine(a, b, k) {
a[0] += k * b[0];
a[1] += k * b[1];
return a;
}
var d3_transformIdentity = {
a: 1,
b: 0,
c: 0,
d: 1,
e: 0,
f: 0
};
d3.interpolateTransform = d3_interpolateTransform;
function d3_interpolateTransform(a, b) {
var s = [], q = [], n, A = d3.transform(a), B = d3.transform(b), ta = A.translate, tb = B.translate, ra = A.rotate, rb = B.rotate, wa = A.skew, wb = B.skew, ka = A.scale, kb = B.scale;
if (ta[0] != tb[0] || ta[1] != tb[1]) {
s.push("translate(", null, ",", null, ")");
q.push({
i: 1,
x: d3_interpolateNumber(ta[0], tb[0])
}, {
i: 3,
x: d3_interpolateNumber(ta[1], tb[1])
});
} else if (tb[0] || tb[1]) {
s.push("translate(" + tb + ")");
} else {
s.push("");
}
if (ra != rb) {
if (ra - rb > 180) rb += 360; else if (rb - ra > 180) ra += 360;
q.push({
i: s.push(s.pop() + "rotate(", null, ")") - 2,
x: d3_interpolateNumber(ra, rb)
});
} else if (rb) {
s.push(s.pop() + "rotate(" + rb + ")");
}
if (wa != wb) {
q.push({
i: s.push(s.pop() + "skewX(", null, ")") - 2,
x: d3_interpolateNumber(wa, wb)
});
} else if (wb) {
s.push(s.pop() + "skewX(" + wb + ")");
}
if (ka[0] != kb[0] || ka[1] != kb[1]) {
n = s.push(s.pop() + "scale(", null, ",", null, ")");
q.push({
i: n - 4,
x: d3_interpolateNumber(ka[0], kb[0])
}, {
i: n - 2,
x: d3_interpolateNumber(ka[1], kb[1])
});
} else if (kb[0] != 1 || kb[1] != 1) {
s.push(s.pop() + "scale(" + kb + ")");
}
n = q.length;
return function(t) {
var i = -1, o;
while (++i < n) s[(o = q[i]).i] = o.x(t);
return s.join("");
};
}
function d3_uninterpolateNumber(a, b) {
b = b - (a = +a) ? 1 / (b - a) : 0;
return function(x) {
return (x - a) * b;
};
}
function d3_uninterpolateClamp(a, b) {
b = b - (a = +a) ? 1 / (b - a) : 0;
return function(x) {
return Math.max(0, Math.min(1, (x - a) * b));
};
}
d3.layout = {};
d3.layout.bundle = function() {
return function(links) {
var paths = [], i = -1, n = links.length;
while (++i < n) paths.push(d3_layout_bundlePath(links[i]));
return paths;
};
};
function d3_layout_bundlePath(link) {
var start = link.source, end = link.target, lca = d3_layout_bundleLeastCommonAncestor(start, end), points = [ start ];
while (start !== lca) {
start = start.parent;
points.push(start);
}
var k = points.length;
while (end !== lca) {
points.splice(k, 0, end);
end = end.parent;
}
return points;
}
function d3_layout_bundleAncestors(node) {
var ancestors = [], parent = node.parent;
while (parent != null) {
ancestors.push(node);
node = parent;
parent = parent.parent;
}
ancestors.push(node);
return ancestors;
}
function d3_layout_bundleLeastCommonAncestor(a, b) {
if (a === b) return a;
var aNodes = d3_layout_bundleAncestors(a), bNodes = d3_layout_bundleAncestors(b), aNode = aNodes.pop(), bNode = bNodes.pop(), sharedNode = null;
while (aNode === bNode) {
sharedNode = aNode;
aNode = aNodes.pop();
bNode = bNodes.pop();
}
return sharedNode;
}
d3.layout.chord = function() {
var chord = {}, chords, groups, matrix, n, padding = 0, sortGroups, sortSubgroups, sortChords;
function relayout() {
var subgroups = {}, groupSums = [], groupIndex = d3.range(n), subgroupIndex = [], k, x, x0, i, j;
chords = [];
groups = [];
k = 0, i = -1;
while (++i < n) {
x = 0, j = -1;
while (++j < n) {
x += matrix[i][j];
}
groupSums.push(x);
subgroupIndex.push(d3.range(n));
k += x;
}
if (sortGroups) {
groupIndex.sort(function(a, b) {
return sortGroups(groupSums[a], groupSums[b]);
});
}
if (sortSubgroups) {
subgroupIndex.forEach(function(d, i) {
d.sort(function(a, b) {
return sortSubgroups(matrix[i][a], matrix[i][b]);
});
});
}
k = (τ - padding * n) / k;
x = 0, i = -1;
while (++i < n) {
x0 = x, j = -1;
while (++j < n) {
var di = groupIndex[i], dj = subgroupIndex[di][j], v = matrix[di][dj], a0 = x, a1 = x += v * k;
subgroups[di + "-" + dj] = {
index: di,
subindex: dj,
startAngle: a0,
endAngle: a1,
value: v
};
}
groups[di] = {
index: di,
startAngle: x0,
endAngle: x,
value: (x - x0) / k
};
x += padding;
}
i = -1;
while (++i < n) {
j = i - 1;
while (++j < n) {
var source = subgroups[i + "-" + j], target = subgroups[j + "-" + i];
if (source.value || target.value) {
chords.push(source.value < target.value ? {
source: target,
target: source
} : {
source: source,
target: target
});
}
}
}
if (sortChords) resort();
}
function resort() {
chords.sort(function(a, b) {
return sortChords((a.source.value + a.target.value) / 2, (b.source.value + b.target.value) / 2);
});
}
chord.matrix = function(x) {
if (!arguments.length) return matrix;
n = (matrix = x) && matrix.length;
chords = groups = null;
return chord;
};
chord.padding = function(x) {
if (!arguments.length) return padding;
padding = x;
chords = groups = null;
return chord;
};
chord.sortGroups = function(x) {
if (!arguments.length) return sortGroups;
sortGroups = x;
chords = groups = null;
return chord;
};
chord.sortSubgroups = function(x) {
if (!arguments.length) return sortSubgroups;
sortSubgroups = x;
chords = null;
return chord;
};
chord.sortChords = function(x) {
if (!arguments.length) return sortChords;
sortChords = x;
if (chords) resort();
return chord;
};
chord.chords = function() {
if (!chords) relayout();
return chords;
};
chord.groups = function() {
if (!groups) relayout();
return groups;
};
return chord;
};
d3.layout.force = function() {
var force = {}, event = d3.dispatch("start", "tick", "end"), size = [ 1, 1 ], drag, alpha, friction = .9, linkDistance = d3_layout_forceLinkDistance, linkStrength = d3_layout_forceLinkStrength, charge = -30, gravity = .1, theta = .8, nodes = [], links = [], distances, strengths, charges;
function repulse(node) {
return function(quad, x1, _, x2) {
if (quad.point !== node) {
var dx = quad.cx - node.x, dy = quad.cy - node.y, dn = 1 / Math.sqrt(dx * dx + dy * dy);
if ((x2 - x1) * dn < theta) {
var k = quad.charge * dn * dn;
node.px -= dx * k;
node.py -= dy * k;
return true;
}
if (quad.point && isFinite(dn)) {
var k = quad.pointCharge * dn * dn;
node.px -= dx * k;
node.py -= dy * k;
}
}
return !quad.charge;
};
}
force.tick = function() {
if ((alpha *= .99) < .005) {
event.end({
type: "end",
alpha: alpha = 0
});
return true;
}
var n = nodes.length, m = links.length, q, i, o, s, t, l, k, x, y;
for (i = 0; i < m; ++i) {
o = links[i];
s = o.source;
t = o.target;
x = t.x - s.x;
y = t.y - s.y;
if (l = x * x + y * y) {
l = alpha * strengths[i] * ((l = Math.sqrt(l)) - distances[i]) / l;
x *= l;
y *= l;
t.x -= x * (k = s.weight / (t.weight + s.weight));
t.y -= y * k;
s.x += x * (k = 1 - k);
s.y += y * k;
}
}
if (k = alpha * gravity) {
x = size[0] / 2;
y = size[1] / 2;
i = -1;
if (k) while (++i < n) {
o = nodes[i];
o.x += (x - o.x) * k;
o.y += (y - o.y) * k;
}
}
if (charge) {
d3_layout_forceAccumulate(q = d3.geom.quadtree(nodes), alpha, charges);
i = -1;
while (++i < n) {
if (!(o = nodes[i]).fixed) {
q.visit(repulse(o));
}
}
}
i = -1;
while (++i < n) {
o = nodes[i];
if (o.fixed) {
o.x = o.px;
o.y = o.py;
} else {
o.x -= (o.px - (o.px = o.x)) * friction;
o.y -= (o.py - (o.py = o.y)) * friction;
}
}
event.tick({
type: "tick",
alpha: alpha
});
};
force.nodes = function(x) {
if (!arguments.length) return nodes;
nodes = x;
return force;
};
force.links = function(x) {
if (!arguments.length) return links;
links = x;
return force;
};
force.size = function(x) {
if (!arguments.length) return size;
size = x;
return force;
};
force.linkDistance = function(x) {
if (!arguments.length) return linkDistance;
linkDistance = typeof x === "function" ? x : +x;
return force;
};
force.distance = force.linkDistance;
force.linkStrength = function(x) {
if (!arguments.length) return linkStrength;
linkStrength = typeof x === "function" ? x : +x;
return force;
};
force.friction = function(x) {
if (!arguments.length) return friction;
friction = +x;
return force;
};
force.charge = function(x) {
if (!arguments.length) return charge;
charge = typeof x === "function" ? x : +x;
return force;
};
force.gravity = function(x) {
if (!arguments.length) return gravity;
gravity = +x;
return force;
};
force.theta = function(x) {
if (!arguments.length) return theta;
theta = +x;
return force;
};
force.alpha = function(x) {
if (!arguments.length) return alpha;
x = +x;
if (alpha) {
if (x > 0) alpha = x; else alpha = 0;
} else if (x > 0) {
event.start({
type: "start",
alpha: alpha = x
});
d3.timer(force.tick);
}
return force;
};
force.start = function() {
var i, n = nodes.length, m = links.length, w = size[0], h = size[1], neighbors, o;
for (i = 0; i < n; ++i) {
(o = nodes[i]).index = i;
o.weight = 0;
}
for (i = 0; i < m; ++i) {
o = links[i];
if (typeof o.source == "number") o.source = nodes[o.source];
if (typeof o.target == "number") o.target = nodes[o.target];
++o.source.weight;
++o.target.weight;
}
for (i = 0; i < n; ++i) {
o = nodes[i];
if (isNaN(o.x)) o.x = position("x", w);
if (isNaN(o.y)) o.y = position("y", h);
if (isNaN(o.px)) o.px = o.x;
if (isNaN(o.py)) o.py = o.y;
}
distances = [];
if (typeof linkDistance === "function") for (i = 0; i < m; ++i) distances[i] = +linkDistance.call(this, links[i], i); else for (i = 0; i < m; ++i) distances[i] = linkDistance;
strengths = [];
if (typeof linkStrength === "function") for (i = 0; i < m; ++i) strengths[i] = +linkStrength.call(this, links[i], i); else for (i = 0; i < m; ++i) strengths[i] = linkStrength;
charges = [];
if (typeof charge === "function") for (i = 0; i < n; ++i) charges[i] = +charge.call(this, nodes[i], i); else for (i = 0; i < n; ++i) charges[i] = charge;
function position(dimension, size) {
if (!neighbors) {
neighbors = new Array(n);
for (j = 0; j < n; ++j) {
neighbors[j] = [];
}
for (j = 0; j < m; ++j) {
var o = links[j];
neighbors[o.source.index].push(o.target);
neighbors[o.target.index].push(o.source);
}
}
var candidates = neighbors[i], j = -1, m = candidates.length, x;
while (++j < m) if (!isNaN(x = candidates[j][dimension])) return x;
return Math.random() * size;
}
return force.resume();
};
force.resume = function() {
return force.alpha(.1);
};
force.stop = function() {
return force.alpha(0);
};
force.drag = function() {
if (!drag) drag = d3.behavior.drag().origin(d3_identity).on("dragstart.force", d3_layout_forceDragstart).on("drag.force", dragmove).on("dragend.force", d3_layout_forceDragend);
if (!arguments.length) return drag;
this.on("mouseover.force", d3_layout_forceMouseover).on("mouseout.force", d3_layout_forceMouseout).call(drag);
};
function dragmove(d) {
d.px = d3.event.x, d.py = d3.event.y;
force.resume();
}
return d3.rebind(force, event, "on");
};
function d3_layout_forceDragstart(d) {
d.fixed |= 2;
}
function d3_layout_forceDragend(d) {
d.fixed &= ~6;
}
function d3_layout_forceMouseover(d) {
d.fixed |= 4;
d.px = d.x, d.py = d.y;
}
function d3_layout_forceMouseout(d) {
d.fixed &= ~4;
}
function d3_layout_forceAccumulate(quad, alpha, charges) {
var cx = 0, cy = 0;
quad.charge = 0;
if (!quad.leaf) {
var nodes = quad.nodes, n = nodes.length, i = -1, c;
while (++i < n) {
c = nodes[i];
if (c == null) continue;
d3_layout_forceAccumulate(c, alpha, charges);
quad.charge += c.charge;
cx += c.charge * c.cx;
cy += c.charge * c.cy;
}
}
if (quad.point) {
if (!quad.leaf) {
quad.point.x += Math.random() - .5;
quad.point.y += Math.random() - .5;
}
var k = alpha * charges[quad.point.index];
quad.charge += quad.pointCharge = k;
cx += k * quad.point.x;
cy += k * quad.point.y;
}
quad.cx = cx / quad.charge;
quad.cy = cy / quad.charge;
}
var d3_layout_forceLinkDistance = 20, d3_layout_forceLinkStrength = 1;
d3.layout.hierarchy = function() {
var sort = d3_layout_hierarchySort, children = d3_layout_hierarchyChildren, value = d3_layout_hierarchyValue;
function recurse(node, depth, nodes) {
var childs = children.call(hierarchy, node, depth);
node.depth = depth;
nodes.push(node);
if (childs && (n = childs.length)) {
var i = -1, n, c = node.children = new Array(n), v = 0, j = depth + 1, d;
while (++i < n) {
d = c[i] = recurse(childs[i], j, nodes);
d.parent = node;
v += d.value;
}
if (sort) c.sort(sort);
if (value) node.value = v;
} else {
delete node.children;
if (value) {
node.value = +value.call(hierarchy, node, depth) || 0;
}
}
return node;
}
function revalue(node, depth) {
var children = node.children, v = 0;
if (children && (n = children.length)) {
var i = -1, n, j = depth + 1;
while (++i < n) v += revalue(children[i], j);
} else if (value) {
v = +value.call(hierarchy, node, depth) || 0;
}
if (value) node.value = v;
return v;
}
function hierarchy(d) {
var nodes = [];
recurse(d, 0, nodes);
return nodes;
}
hierarchy.sort = function(x) {
if (!arguments.length) return sort;
sort = x;
return hierarchy;
};
hierarchy.children = function(x) {
if (!arguments.length) return children;
children = x;
return hierarchy;
};
hierarchy.value = function(x) {
if (!arguments.length) return value;
value = x;
return hierarchy;
};
hierarchy.revalue = function(root) {
revalue(root, 0);
return root;
};
return hierarchy;
};
function d3_layout_hierarchyRebind(object, hierarchy) {
d3.rebind(object, hierarchy, "sort", "children", "value");
object.nodes = object;
object.links = d3_layout_hierarchyLinks;
return object;
}
function d3_layout_hierarchyChildren(d) {
return d.children;
}
function d3_layout_hierarchyValue(d) {
return d.value;
}
function d3_layout_hierarchySort(a, b) {
return b.value - a.value;
}
function d3_layout_hierarchyLinks(nodes) {
return d3.merge(nodes.map(function(parent) {
return (parent.children || []).map(function(child) {
return {
source: parent,
target: child
};
});
}));
}
d3.layout.partition = function() {
var hierarchy = d3.layout.hierarchy(), size = [ 1, 1 ];
function position(node, x, dx, dy) {
var children = node.children;
node.x = x;
node.y = node.depth * dy;
node.dx = dx;
node.dy = dy;
if (children && (n = children.length)) {
var i = -1, n, c, d;
dx = node.value ? dx / node.value : 0;
while (++i < n) {
position(c = children[i], x, d = c.value * dx, dy);
x += d;
}
}
}
function depth(node) {
var children = node.children, d = 0;
if (children && (n = children.length)) {
var i = -1, n;
while (++i < n) d = Math.max(d, depth(children[i]));
}
return 1 + d;
}
function partition(d, i) {
var nodes = hierarchy.call(this, d, i);
position(nodes[0], 0, size[0], size[1] / depth(nodes[0]));
return nodes;
}
partition.size = function(x) {
if (!arguments.length) return size;
size = x;
return partition;
};
return d3_layout_hierarchyRebind(partition, hierarchy);
};
d3.layout.pie = function() {
var value = Number, sort = d3_layout_pieSortByValue, startAngle = 0, endAngle = τ;
function pie(data) {
var values = data.map(function(d, i) {
return +value.call(pie, d, i);
});
var a = +(typeof startAngle === "function" ? startAngle.apply(this, arguments) : startAngle);
var k = ((typeof endAngle === "function" ? endAngle.apply(this, arguments) : endAngle) - a) / d3.sum(values);
var index = d3.range(data.length);
if (sort != null) index.sort(sort === d3_layout_pieSortByValue ? function(i, j) {
return values[j] - values[i];
} : function(i, j) {
return sort(data[i], data[j]);
});
var arcs = [];
index.forEach(function(i) {
var d;
arcs[i] = {
data: data[i],
value: d = values[i],
startAngle: a,
endAngle: a += d * k
};
});
return arcs;
}
pie.value = function(x) {
if (!arguments.length) return value;
value = x;
return pie;
};
pie.sort = function(x) {
if (!arguments.length) return sort;
sort = x;
return pie;
};
pie.startAngle = function(x) {
if (!arguments.length) return startAngle;
startAngle = x;
return pie;
};
pie.endAngle = function(x) {
if (!arguments.length) return endAngle;
endAngle = x;
return pie;
};
return pie;
};
var d3_layout_pieSortByValue = {};
d3.layout.stack = function() {
var values = d3_identity, order = d3_layout_stackOrderDefault, offset = d3_layout_stackOffsetZero, out = d3_layout_stackOut, x = d3_layout_stackX, y = d3_layout_stackY;
function stack(data, index) {
var series = data.map(function(d, i) {
return values.call(stack, d, i);
});
var points = series.map(function(d) {
return d.map(function(v, i) {
return [ x.call(stack, v, i), y.call(stack, v, i) ];
});
});
var orders = order.call(stack, points, index);
series = d3.permute(series, orders);
points = d3.permute(points, orders);
var offsets = offset.call(stack, points, index);
var n = series.length, m = series[0].length, i, j, o;
for (j = 0; j < m; ++j) {
out.call(stack, series[0][j], o = offsets[j], points[0][j][1]);
for (i = 1; i < n; ++i) {
out.call(stack, series[i][j], o += points[i - 1][j][1], points[i][j][1]);
}
}
return data;
}
stack.values = function(x) {
if (!arguments.length) return values;
values = x;
return stack;
};
stack.order = function(x) {
if (!arguments.length) return order;
order = typeof x === "function" ? x : d3_layout_stackOrders.get(x) || d3_layout_stackOrderDefault;
return stack;
};
stack.offset = function(x) {
if (!arguments.length) return offset;
offset = typeof x === "function" ? x : d3_layout_stackOffsets.get(x) || d3_layout_stackOffsetZero;
return stack;
};
stack.x = function(z) {
if (!arguments.length) return x;
x = z;
return stack;
};
stack.y = function(z) {
if (!arguments.length) return y;
y = z;
return stack;
};
stack.out = function(z) {
if (!arguments.length) return out;
out = z;
return stack;
};
return stack;
};
function d3_layout_stackX(d) {
return d.x;
}
function d3_layout_stackY(d) {
return d.y;
}
function d3_layout_stackOut(d, y0, y) {
d.y0 = y0;
d.y = y;
}
var d3_layout_stackOrders = d3.map({
"inside-out": function(data) {
var n = data.length, i, j, max = data.map(d3_layout_stackMaxIndex), sums = data.map(d3_layout_stackReduceSum), index = d3.range(n).sort(function(a, b) {
return max[a] - max[b];
}), top = 0, bottom = 0, tops = [], bottoms = [];
for (i = 0; i < n; ++i) {
j = index[i];
if (top < bottom) {
top += sums[j];
tops.push(j);
} else {
bottom += sums[j];
bottoms.push(j);
}
}
return bottoms.reverse().concat(tops);
},
reverse: function(data) {
return d3.range(data.length).reverse();
},
"default": d3_layout_stackOrderDefault
});
var d3_layout_stackOffsets = d3.map({
silhouette: function(data) {
var n = data.length, m = data[0].length, sums = [], max = 0, i, j, o, y0 = [];
for (j = 0; j < m; ++j) {
for (i = 0, o = 0; i < n; i++) o += data[i][j][1];
if (o > max) max = o;
sums.push(o);
}
for (j = 0; j < m; ++j) {
y0[j] = (max - sums[j]) / 2;
}
return y0;
},
wiggle: function(data) {
var n = data.length, x = data[0], m = x.length, i, j, k, s1, s2, s3, dx, o, o0, y0 = [];
y0[0] = o = o0 = 0;
for (j = 1; j < m; ++j) {
for (i = 0, s1 = 0; i < n; ++i) s1 += data[i][j][1];
for (i = 0, s2 = 0, dx = x[j][0] - x[j - 1][0]; i < n; ++i) {
for (k = 0, s3 = (data[i][j][1] - data[i][j - 1][1]) / (2 * dx); k < i; ++k) {
s3 += (data[k][j][1] - data[k][j - 1][1]) / dx;
}
s2 += s3 * data[i][j][1];
}
y0[j] = o -= s1 ? s2 / s1 * dx : 0;
if (o < o0) o0 = o;
}
for (j = 0; j < m; ++j) y0[j] -= o0;
return y0;
},
expand: function(data) {
var n = data.length, m = data[0].length, k = 1 / n, i, j, o, y0 = [];
for (j = 0; j < m; ++j) {
for (i = 0, o = 0; i < n; i++) o += data[i][j][1];
if (o) for (i = 0; i < n; i++) data[i][j][1] /= o; else for (i = 0; i < n; i++) data[i][j][1] = k;
}
for (j = 0; j < m; ++j) y0[j] = 0;
return y0;
},
zero: d3_layout_stackOffsetZero
});
function d3_layout_stackOrderDefault(data) {
return d3.range(data.length);
}
function d3_layout_stackOffsetZero(data) {
var j = -1, m = data[0].length, y0 = [];
while (++j < m) y0[j] = 0;
return y0;
}
function d3_layout_stackMaxIndex(array) {
var i = 1, j = 0, v = array[0][1], k, n = array.length;
for (;i < n; ++i) {
if ((k = array[i][1]) > v) {
j = i;
v = k;
}
}
return j;
}
function d3_layout_stackReduceSum(d) {
return d.reduce(d3_layout_stackSum, 0);
}
function d3_layout_stackSum(p, d) {
return p + d[1];
}
d3.layout.histogram = function() {
var frequency = true, valuer = Number, ranger = d3_layout_histogramRange, binner = d3_layout_histogramBinSturges;
function histogram(data, i) {
var bins = [], values = data.map(valuer, this), range = ranger.call(this, values, i), thresholds = binner.call(this, range, values, i), bin, i = -1, n = values.length, m = thresholds.length - 1, k = frequency ? 1 : 1 / n, x;
while (++i < m) {
bin = bins[i] = [];
bin.dx = thresholds[i + 1] - (bin.x = thresholds[i]);
bin.y = 0;
}
if (m > 0) {
i = -1;
while (++i < n) {
x = values[i];
if (x >= range[0] && x <= range[1]) {
bin = bins[d3.bisect(thresholds, x, 1, m) - 1];
bin.y += k;
bin.push(data[i]);
}
}
}
return bins;
}
histogram.value = function(x) {
if (!arguments.length) return valuer;
valuer = x;
return histogram;
};
histogram.range = function(x) {
if (!arguments.length) return ranger;
ranger = d3_functor(x);
return histogram;
};
histogram.bins = function(x) {
if (!arguments.length) return binner;
binner = typeof x === "number" ? function(range) {
return d3_layout_histogramBinFixed(range, x);
} : d3_functor(x);
return histogram;
};
histogram.frequency = function(x) {
if (!arguments.length) return frequency;
frequency = !!x;
return histogram;
};
return histogram;
};
function d3_layout_histogramBinSturges(range, values) {
return d3_layout_histogramBinFixed(range, Math.ceil(Math.log(values.length) / Math.LN2 + 1));
}
function d3_layout_histogramBinFixed(range, n) {
var x = -1, b = +range[0], m = (range[1] - b) / n, f = [];
while (++x <= n) f[x] = m * x + b;
return f;
}
function d3_layout_histogramRange(values) {
return [ d3.min(values), d3.max(values) ];
}
d3.layout.tree = function() {
var hierarchy = d3.layout.hierarchy().sort(null).value(null), separation = d3_layout_treeSeparation, size = [ 1, 1 ], nodeSize = false;
function tree(d, i) {
var nodes = hierarchy.call(this, d, i), root = nodes[0];
function firstWalk(node, previousSibling) {
var children = node.children, layout = node._tree;
if (children && (n = children.length)) {
var n, firstChild = children[0], previousChild, ancestor = firstChild, child, i = -1;
while (++i < n) {
child = children[i];
firstWalk(child, previousChild);
ancestor = apportion(child, previousChild, ancestor);
previousChild = child;
}
d3_layout_treeShift(node);
var midpoint = .5 * (firstChild._tree.prelim + child._tree.prelim);
if (previousSibling) {
layout.prelim = previousSibling._tree.prelim + separation(node, previousSibling);
layout.mod = layout.prelim - midpoint;
} else {
layout.prelim = midpoint;
}
} else {
if (previousSibling) {
layout.prelim = previousSibling._tree.prelim + separation(node, previousSibling);
}
}
}
function secondWalk(node, x) {
node.x = node._tree.prelim + x;
var children = node.children;
if (children && (n = children.length)) {
var i = -1, n;
x += node._tree.mod;
while (++i < n) {
secondWalk(children[i], x);
}
}
}
function apportion(node, previousSibling, ancestor) {
if (previousSibling) {
var vip = node, vop = node, vim = previousSibling, vom = node.parent.children[0], sip = vip._tree.mod, sop = vop._tree.mod, sim = vim._tree.mod, som = vom._tree.mod, shift;
while (vim = d3_layout_treeRight(vim), vip = d3_layout_treeLeft(vip), vim && vip) {
vom = d3_layout_treeLeft(vom);
vop = d3_layout_treeRight(vop);
vop._tree.ancestor = node;
shift = vim._tree.prelim + sim - vip._tree.prelim - sip + separation(vim, vip);
if (shift > 0) {
d3_layout_treeMove(d3_layout_treeAncestor(vim, node, ancestor), node, shift);
sip += shift;
sop += shift;
}
sim += vim._tree.mod;
sip += vip._tree.mod;
som += vom._tree.mod;
sop += vop._tree.mod;
}
if (vim && !d3_layout_treeRight(vop)) {
vop._tree.thread = vim;
vop._tree.mod += sim - sop;
}
if (vip && !d3_layout_treeLeft(vom)) {
vom._tree.thread = vip;
vom._tree.mod += sip - som;
ancestor = node;
}
}
return ancestor;
}
d3_layout_treeVisitAfter(root, function(node, previousSibling) {
node._tree = {
ancestor: node,
prelim: 0,
mod: 0,
change: 0,
shift: 0,
number: previousSibling ? previousSibling._tree.number + 1 : 0
};
});
firstWalk(root);
secondWalk(root, -root._tree.prelim);
var left = d3_layout_treeSearch(root, d3_layout_treeLeftmost), right = d3_layout_treeSearch(root, d3_layout_treeRightmost), deep = d3_layout_treeSearch(root, d3_layout_treeDeepest), x0 = left.x - separation(left, right) / 2, x1 = right.x + separation(right, left) / 2, y1 = deep.depth || 1;
d3_layout_treeVisitAfter(root, nodeSize ? function(node) {
node.x *= size[0];
node.y = node.depth * size[1];
delete node._tree;
} : function(node) {
node.x = (node.x - x0) / (x1 - x0) * size[0];
node.y = node.depth / y1 * size[1];
delete node._tree;
});
return nodes;
}
tree.separation = function(x) {
if (!arguments.length) return separation;
separation = x;
return tree;
};
tree.size = function(x) {
if (!arguments.length) return nodeSize ? null : size;
nodeSize = (size = x) == null;
return tree;
};
tree.nodeSize = function(x) {
if (!arguments.length) return nodeSize ? size : null;
nodeSize = (size = x) != null;
return tree;
};
return d3_layout_hierarchyRebind(tree, hierarchy);
};
function d3_layout_treeSeparation(a, b) {
return a.parent == b.parent ? 1 : 2;
}
function d3_layout_treeLeft(node) {
var children = node.children;
return children && children.length ? children[0] : node._tree.thread;
}
function d3_layout_treeRight(node) {
var children = node.children, n;
return children && (n = children.length) ? children[n - 1] : node._tree.thread;
}
function d3_layout_treeSearch(node, compare) {
var children = node.children;
if (children && (n = children.length)) {
var child, n, i = -1;
while (++i < n) {
if (compare(child = d3_layout_treeSearch(children[i], compare), node) > 0) {
node = child;
}
}
}
return node;
}
function d3_layout_treeRightmost(a, b) {
return a.x - b.x;
}
function d3_layout_treeLeftmost(a, b) {
return b.x - a.x;
}
function d3_layout_treeDeepest(a, b) {
return a.depth - b.depth;
}
function d3_layout_treeVisitAfter(node, callback) {
function visit(node, previousSibling) {
var children = node.children;
if (children && (n = children.length)) {
var child, previousChild = null, i = -1, n;
while (++i < n) {
child = children[i];
visit(child, previousChild);
previousChild = child;
}
}
callback(node, previousSibling);
}
visit(node, null);
}
function d3_layout_treeShift(node) {
var shift = 0, change = 0, children = node.children, i = children.length, child;
while (--i >= 0) {
child = children[i]._tree;
child.prelim += shift;
child.mod += shift;
shift += child.shift + (change += child.change);
}
}
function d3_layout_treeMove(ancestor, node, shift) {
ancestor = ancestor._tree;
node = node._tree;
var change = shift / (node.number - ancestor.number);
ancestor.change += change;
node.change -= change;
node.shift += shift;
node.prelim += shift;
node.mod += shift;
}
function d3_layout_treeAncestor(vim, node, ancestor) {
return vim._tree.ancestor.parent == node.parent ? vim._tree.ancestor : ancestor;
}
d3.layout.pack = function() {
var hierarchy = d3.layout.hierarchy().sort(d3_layout_packSort), padding = 0, size = [ 1, 1 ], radius;
function pack(d, i) {
var nodes = hierarchy.call(this, d, i), root = nodes[0], w = size[0], h = size[1], r = radius == null ? Math.sqrt : typeof radius === "function" ? radius : function() {
return radius;
};
root.x = root.y = 0;
d3_layout_treeVisitAfter(root, function(d) {
d.r = +r(d.value);
});
d3_layout_treeVisitAfter(root, d3_layout_packSiblings);
if (padding) {
var dr = padding * (radius ? 1 : Math.max(2 * root.r / w, 2 * root.r / h)) / 2;
d3_layout_treeVisitAfter(root, function(d) {
d.r += dr;
});
d3_layout_treeVisitAfter(root, d3_layout_packSiblings);
d3_layout_treeVisitAfter(root, function(d) {
d.r -= dr;
});
}
d3_layout_packTransform(root, w / 2, h / 2, radius ? 1 : 1 / Math.max(2 * root.r / w, 2 * root.r / h));
return nodes;
}
pack.size = function(_) {
if (!arguments.length) return size;
size = _;
return pack;
};
pack.radius = function(_) {
if (!arguments.length) return radius;
radius = _ == null || typeof _ === "function" ? _ : +_;
return pack;
};
pack.padding = function(_) {
if (!arguments.length) return padding;
padding = +_;
return pack;
};
return d3_layout_hierarchyRebind(pack, hierarchy);
};
function d3_layout_packSort(a, b) {
return a.value - b.value;
}
function d3_layout_packInsert(a, b) {
var c = a._pack_next;
a._pack_next = b;
b._pack_prev = a;
b._pack_next = c;
c._pack_prev = b;
}
function d3_layout_packSplice(a, b) {
a._pack_next = b;
b._pack_prev = a;
}
function d3_layout_packIntersects(a, b) {
var dx = b.x - a.x, dy = b.y - a.y, dr = a.r + b.r;
return .999 * dr * dr > dx * dx + dy * dy;
}
function d3_layout_packSiblings(node) {
if (!(nodes = node.children) || !(n = nodes.length)) return;
var nodes, xMin = Infinity, xMax = -Infinity, yMin = Infinity, yMax = -Infinity, a, b, c, i, j, k, n;
function bound(node) {
xMin = Math.min(node.x - node.r, xMin);
xMax = Math.max(node.x + node.r, xMax);
yMin = Math.min(node.y - node.r, yMin);
yMax = Math.max(node.y + node.r, yMax);
}
nodes.forEach(d3_layout_packLink);
a = nodes[0];
a.x = -a.r;
a.y = 0;
bound(a);
if (n > 1) {
b = nodes[1];
b.x = b.r;
b.y = 0;
bound(b);
if (n > 2) {
c = nodes[2];
d3_layout_packPlace(a, b, c);
bound(c);
d3_layout_packInsert(a, c);
a._pack_prev = c;
d3_layout_packInsert(c, b);
b = a._pack_next;
for (i = 3; i < n; i++) {
d3_layout_packPlace(a, b, c = nodes[i]);
var isect = 0, s1 = 1, s2 = 1;
for (j = b._pack_next; j !== b; j = j._pack_next, s1++) {
if (d3_layout_packIntersects(j, c)) {
isect = 1;
break;
}
}
if (isect == 1) {
for (k = a._pack_prev; k !== j._pack_prev; k = k._pack_prev, s2++) {
if (d3_layout_packIntersects(k, c)) {
break;
}
}
}
if (isect) {
if (s1 < s2 || s1 == s2 && b.r < a.r) d3_layout_packSplice(a, b = j); else d3_layout_packSplice(a = k, b);
i--;
} else {
d3_layout_packInsert(a, c);
b = c;
bound(c);
}
}
}
}
var cx = (xMin + xMax) / 2, cy = (yMin + yMax) / 2, cr = 0;
for (i = 0; i < n; i++) {
c = nodes[i];
c.x -= cx;
c.y -= cy;
cr = Math.max(cr, c.r + Math.sqrt(c.x * c.x + c.y * c.y));
}
node.r = cr;
nodes.forEach(d3_layout_packUnlink);
}
function d3_layout_packLink(node) {
node._pack_next = node._pack_prev = node;
}
function d3_layout_packUnlink(node) {
delete node._pack_next;
delete node._pack_prev;
}
function d3_layout_packTransform(node, x, y, k) {
var children = node.children;
node.x = x += k * node.x;
node.y = y += k * node.y;
node.r *= k;
if (children) {
var i = -1, n = children.length;
while (++i < n) d3_layout_packTransform(children[i], x, y, k);
}
}
function d3_layout_packPlace(a, b, c) {
var db = a.r + c.r, dx = b.x - a.x, dy = b.y - a.y;
if (db && (dx || dy)) {
var da = b.r + c.r, dc = dx * dx + dy * dy;
da *= da;
db *= db;
var x = .5 + (db - da) / (2 * dc), y = Math.sqrt(Math.max(0, 2 * da * (db + dc) - (db -= dc) * db - da * da)) / (2 * dc);
c.x = a.x + x * dx + y * dy;
c.y = a.y + x * dy - y * dx;
} else {
c.x = a.x + db;
c.y = a.y;
}
}
d3.layout.cluster = function() {
var hierarchy = d3.layout.hierarchy().sort(null).value(null), separation = d3_layout_treeSeparation, size = [ 1, 1 ], nodeSize = false;
function cluster(d, i) {
var nodes = hierarchy.call(this, d, i), root = nodes[0], previousNode, x = 0;
d3_layout_treeVisitAfter(root, function(node) {
var children = node.children;
if (children && children.length) {
node.x = d3_layout_clusterX(children);
node.y = d3_layout_clusterY(children);
} else {
node.x = previousNode ? x += separation(node, previousNode) : 0;
node.y = 0;
previousNode = node;
}
});
var left = d3_layout_clusterLeft(root), right = d3_layout_clusterRight(root), x0 = left.x - separation(left, right) / 2, x1 = right.x + separation(right, left) / 2;
d3_layout_treeVisitAfter(root, nodeSize ? function(node) {
node.x = (node.x - root.x) * size[0];
node.y = (root.y - node.y) * size[1];
} : function(node) {
node.x = (node.x - x0) / (x1 - x0) * size[0];
node.y = (1 - (root.y ? node.y / root.y : 1)) * size[1];
});
return nodes;
}
cluster.separation = function(x) {
if (!arguments.length) return separation;
separation = x;
return cluster;
};
cluster.size = function(x) {
if (!arguments.length) return nodeSize ? null : size;
nodeSize = (size = x) == null;
return cluster;
};
cluster.nodeSize = function(x) {
if (!arguments.length) return nodeSize ? size : null;
nodeSize = (size = x) != null;
return cluster;
};
return d3_layout_hierarchyRebind(cluster, hierarchy);
};
function d3_layout_clusterY(children) {
return 1 + d3.max(children, function(child) {
return child.y;
});
}
function d3_layout_clusterX(children) {
return children.reduce(function(x, child) {
return x + child.x;
}, 0) / children.length;
}
function d3_layout_clusterLeft(node) {
var children = node.children;
return children && children.length ? d3_layout_clusterLeft(children[0]) : node;
}
function d3_layout_clusterRight(node) {
var children = node.children, n;
return children && (n = children.length) ? d3_layout_clusterRight(children[n - 1]) : node;
}
d3.layout.treemap = function() {
var hierarchy = d3.layout.hierarchy(), round = Math.round, size = [ 1, 1 ], padding = null, pad = d3_layout_treemapPadNull, sticky = false, stickies, mode = "squarify", ratio = .5 * (1 + Math.sqrt(5));
function scale(children, k) {
var i = -1, n = children.length, child, area;
while (++i < n) {
area = (child = children[i]).value * (k < 0 ? 0 : k);
child.area = isNaN(area) || area <= 0 ? 0 : area;
}
}
function squarify(node) {
var children = node.children;
if (children && children.length) {
var rect = pad(node), row = [], remaining = children.slice(), child, best = Infinity, score, u = mode === "slice" ? rect.dx : mode === "dice" ? rect.dy : mode === "slice-dice" ? node.depth & 1 ? rect.dy : rect.dx : Math.min(rect.dx, rect.dy), n;
scale(remaining, rect.dx * rect.dy / node.value);
row.area = 0;
while ((n = remaining.length) > 0) {
row.push(child = remaining[n - 1]);
row.area += child.area;
if (mode !== "squarify" || (score = worst(row, u)) <= best) {
remaining.pop();
best = score;
} else {
row.area -= row.pop().area;
position(row, u, rect, false);
u = Math.min(rect.dx, rect.dy);
row.length = row.area = 0;
best = Infinity;
}
}
if (row.length) {
position(row, u, rect, true);
row.length = row.area = 0;
}
children.forEach(squarify);
}
}
function stickify(node) {
var children = node.children;
if (children && children.length) {
var rect = pad(node), remaining = children.slice(), child, row = [];
scale(remaining, rect.dx * rect.dy / node.value);
row.area = 0;
while (child = remaining.pop()) {
row.push(child);
row.area += child.area;
if (child.z != null) {
position(row, child.z ? rect.dx : rect.dy, rect, !remaining.length);
row.length = row.area = 0;
}
}
children.forEach(stickify);
}
}
function worst(row, u) {
var s = row.area, r, rmax = 0, rmin = Infinity, i = -1, n = row.length;
while (++i < n) {
if (!(r = row[i].area)) continue;
if (r < rmin) rmin = r;
if (r > rmax) rmax = r;
}
s *= s;
u *= u;
return s ? Math.max(u * rmax * ratio / s, s / (u * rmin * ratio)) : Infinity;
}
function position(row, u, rect, flush) {
var i = -1, n = row.length, x = rect.x, y = rect.y, v = u ? round(row.area / u) : 0, o;
if (u == rect.dx) {
if (flush || v > rect.dy) v = rect.dy;
while (++i < n) {
o = row[i];
o.x = x;
o.y = y;
o.dy = v;
x += o.dx = Math.min(rect.x + rect.dx - x, v ? round(o.area / v) : 0);
}
o.z = true;
o.dx += rect.x + rect.dx - x;
rect.y += v;
rect.dy -= v;
} else {
if (flush || v > rect.dx) v = rect.dx;
while (++i < n) {
o = row[i];
o.x = x;
o.y = y;
o.dx = v;
y += o.dy = Math.min(rect.y + rect.dy - y, v ? round(o.area / v) : 0);
}
o.z = false;
o.dy += rect.y + rect.dy - y;
rect.x += v;
rect.dx -= v;
}
}
function treemap(d) {
var nodes = stickies || hierarchy(d), root = nodes[0];
root.x = 0;
root.y = 0;
root.dx = size[0];
root.dy = size[1];
if (stickies) hierarchy.revalue(root);
scale([ root ], root.dx * root.dy / root.value);
(stickies ? stickify : squarify)(root);
if (sticky) stickies = nodes;
return nodes;
}
treemap.size = function(x) {
if (!arguments.length) return size;
size = x;
return treemap;
};
treemap.padding = function(x) {
if (!arguments.length) return padding;
function padFunction(node) {
var p = x.call(treemap, node, node.depth);
return p == null ? d3_layout_treemapPadNull(node) : d3_layout_treemapPad(node, typeof p === "number" ? [ p, p, p, p ] : p);
}
function padConstant(node) {
return d3_layout_treemapPad(node, x);
}
var type;
pad = (padding = x) == null ? d3_layout_treemapPadNull : (type = typeof x) === "function" ? padFunction : type === "number" ? (x = [ x, x, x, x ],
padConstant) : padConstant;
return treemap;
};
treemap.round = function(x) {
if (!arguments.length) return round != Number;
round = x ? Math.round : Number;
return treemap;
};
treemap.sticky = function(x) {
if (!arguments.length) return sticky;
sticky = x;
stickies = null;
return treemap;
};
treemap.ratio = function(x) {
if (!arguments.length) return ratio;
ratio = x;
return treemap;
};
treemap.mode = function(x) {
if (!arguments.length) return mode;
mode = x + "";
return treemap;
};
return d3_layout_hierarchyRebind(treemap, hierarchy);
};
function d3_layout_treemapPadNull(node) {
return {
x: node.x,
y: node.y,
dx: node.dx,
dy: node.dy
};
}
function d3_layout_treemapPad(node, padding) {
var x = node.x + padding[3], y = node.y + padding[0], dx = node.dx - padding[1] - padding[3], dy = node.dy - padding[0] - padding[2];
if (dx < 0) {
x += dx / 2;
dx = 0;
}
if (dy < 0) {
y += dy / 2;
dy = 0;
}
return {
x: x,
y: y,
dx: dx,
dy: dy
};
}
d3.random = {
normal: function(µ, σ) {
var n = arguments.length;
if (n < 2) σ = 1;
if (n < 1) µ = 0;
return function() {
var x, y, r;
do {
x = Math.random() * 2 - 1;
y = Math.random() * 2 - 1;
r = x * x + y * y;
} while (!r || r > 1);
return µ + σ * x * Math.sqrt(-2 * Math.log(r) / r);
};
},
logNormal: function() {
var random = d3.random.normal.apply(d3, arguments);
return function() {
return Math.exp(random());
};
},
irwinHall: function(m) {
return function() {
for (var s = 0, j = 0; j < m; j++) s += Math.random();
return s / m;
};
}
};
d3.scale = {};
function d3_scaleExtent(domain) {
var start = domain[0], stop = domain[domain.length - 1];
return start < stop ? [ start, stop ] : [ stop, start ];
}
function d3_scaleRange(scale) {
return scale.rangeExtent ? scale.rangeExtent() : d3_scaleExtent(scale.range());
}
function d3_scale_bilinear(domain, range, uninterpolate, interpolate) {
var u = uninterpolate(domain[0], domain[1]), i = interpolate(range[0], range[1]);
return function(x) {
return i(u(x));
};
}
function d3_scale_nice(domain, nice) {
var i0 = 0, i1 = domain.length - 1, x0 = domain[i0], x1 = domain[i1], dx;
if (x1 < x0) {
dx = i0, i0 = i1, i1 = dx;
dx = x0, x0 = x1, x1 = dx;
}
domain[i0] = nice.floor(x0);
domain[i1] = nice.ceil(x1);
return domain;
}
function d3_scale_niceStep(step) {
return step ? {
floor: function(x) {
return Math.floor(x / step) * step;
},
ceil: function(x) {
return Math.ceil(x / step) * step;
}
} : d3_scale_niceIdentity;
}
var d3_scale_niceIdentity = {
floor: d3_identity,
ceil: d3_identity
};
function d3_scale_polylinear(domain, range, uninterpolate, interpolate) {
var u = [], i = [], j = 0, k = Math.min(domain.length, range.length) - 1;
if (domain[k] < domain[0]) {
domain = domain.slice().reverse();
range = range.slice().reverse();
}
while (++j <= k) {
u.push(uninterpolate(domain[j - 1], domain[j]));
i.push(interpolate(range[j - 1], range[j]));
}
return function(x) {
var j = d3.bisect(domain, x, 1, k) - 1;
return i[j](u[j](x));
};
}
d3.scale.linear = function() {
return d3_scale_linear([ 0, 1 ], [ 0, 1 ], d3_interpolate, false);
};
function d3_scale_linear(domain, range, interpolate, clamp) {
var output, input;
function rescale() {
var linear = Math.min(domain.length, range.length) > 2 ? d3_scale_polylinear : d3_scale_bilinear, uninterpolate = clamp ? d3_uninterpolateClamp : d3_uninterpolateNumber;
output = linear(domain, range, uninterpolate, interpolate);
input = linear(range, domain, uninterpolate, d3_interpolate);
return scale;
}
function scale(x) {
return output(x);
}
scale.invert = function(y) {
return input(y);
};
scale.domain = function(x) {
if (!arguments.length) return domain;
domain = x.map(Number);
return rescale();
};
scale.range = function(x) {
if (!arguments.length) return range;
range = x;
return rescale();
};
scale.rangeRound = function(x) {
return scale.range(x).interpolate(d3_interpolateRound);
};
scale.clamp = function(x) {
if (!arguments.length) return clamp;
clamp = x;
return rescale();
};
scale.interpolate = function(x) {
if (!arguments.length) return interpolate;
interpolate = x;
return rescale();
};
scale.ticks = function(m) {
return d3_scale_linearTicks(domain, m);
};
scale.tickFormat = function(m, format) {
return d3_scale_linearTickFormat(domain, m, format);
};
scale.nice = function(m) {
d3_scale_linearNice(domain, m);
return rescale();
};
scale.copy = function() {
return d3_scale_linear(domain, range, interpolate, clamp);
};
return rescale();
}
function d3_scale_linearRebind(scale, linear) {
return d3.rebind(scale, linear, "range", "rangeRound", "interpolate", "clamp");
}
function d3_scale_linearNice(domain, m) {
return d3_scale_nice(domain, d3_scale_niceStep(d3_scale_linearTickRange(domain, m)[2]));
}
function d3_scale_linearTickRange(domain, m) {
if (m == null) m = 10;
var extent = d3_scaleExtent(domain), span = extent[1] - extent[0], step = Math.pow(10, Math.floor(Math.log(span / m) / Math.LN10)), err = m / span * step;
if (err <= .15) step *= 10; else if (err <= .35) step *= 5; else if (err <= .75) step *= 2;
extent[0] = Math.ceil(extent[0] / step) * step;
extent[1] = Math.floor(extent[1] / step) * step + step * .5;
extent[2] = step;
return extent;
}
function d3_scale_linearTicks(domain, m) {
return d3.range.apply(d3, d3_scale_linearTickRange(domain, m));
}
function d3_scale_linearTickFormat(domain, m, format) {
var range = d3_scale_linearTickRange(domain, m);
return d3.format(format ? format.replace(d3_format_re, function(a, b, c, d, e, f, g, h, i, j) {
return [ b, c, d, e, f, g, h, i || "." + d3_scale_linearFormatPrecision(j, range), j ].join("");
}) : ",." + d3_scale_linearPrecision(range[2]) + "f");
}
var d3_scale_linearFormatSignificant = {
s: 1,
g: 1,
p: 1,
r: 1,
e: 1
};
function d3_scale_linearPrecision(value) {
return -Math.floor(Math.log(value) / Math.LN10 + .01);
}
function d3_scale_linearFormatPrecision(type, range) {
var p = d3_scale_linearPrecision(range[2]);
return type in d3_scale_linearFormatSignificant ? Math.abs(p - d3_scale_linearPrecision(Math.max(Math.abs(range[0]), Math.abs(range[1])))) + +(type !== "e") : p - (type === "%") * 2;
}
d3.scale.log = function() {
return d3_scale_log(d3.scale.linear().domain([ 0, 1 ]), 10, true, [ 1, 10 ]);
};
function d3_scale_log(linear, base, positive, domain) {
function log(x) {
return (positive ? Math.log(x < 0 ? 0 : x) : -Math.log(x > 0 ? 0 : -x)) / Math.log(base);
}
function pow(x) {
return positive ? Math.pow(base, x) : -Math.pow(base, -x);
}
function scale(x) {
return linear(log(x));
}
scale.invert = function(x) {
return pow(linear.invert(x));
};
scale.domain = function(x) {
if (!arguments.length) return domain;
positive = x[0] >= 0;
linear.domain((domain = x.map(Number)).map(log));
return scale;
};
scale.base = function(_) {
if (!arguments.length) return base;
base = +_;
linear.domain(domain.map(log));
return scale;
};
scale.nice = function() {
var niced = d3_scale_nice(domain.map(log), positive ? Math : d3_scale_logNiceNegative);
linear.domain(niced);
domain = niced.map(pow);
return scale;
};
scale.ticks = function() {
var extent = d3_scaleExtent(domain), ticks = [], u = extent[0], v = extent[1], i = Math.floor(log(u)), j = Math.ceil(log(v)), n = base % 1 ? 2 : base;
if (isFinite(j - i)) {
if (positive) {
for (;i < j; i++) for (var k = 1; k < n; k++) ticks.push(pow(i) * k);
ticks.push(pow(i));
} else {
ticks.push(pow(i));
for (;i++ < j; ) for (var k = n - 1; k > 0; k--) ticks.push(pow(i) * k);
}
for (i = 0; ticks[i] < u; i++) {}
for (j = ticks.length; ticks[j - 1] > v; j--) {}
ticks = ticks.slice(i, j);
}
return ticks;
};
scale.tickFormat = function(n, format) {
if (!arguments.length) return d3_scale_logFormat;
if (arguments.length < 2) format = d3_scale_logFormat; else if (typeof format !== "function") format = d3.format(format);
var k = Math.max(.1, n / scale.ticks().length), f = positive ? (e = 1e-12, Math.ceil) : (e = -1e-12,
Math.floor), e;
return function(d) {
return d / pow(f(log(d) + e)) <= k ? format(d) : "";
};
};
scale.copy = function() {
return d3_scale_log(linear.copy(), base, positive, domain);
};
return d3_scale_linearRebind(scale, linear);
}
var d3_scale_logFormat = d3.format(".0e"), d3_scale_logNiceNegative = {
floor: function(x) {
return -Math.ceil(-x);
},
ceil: function(x) {
return -Math.floor(-x);
}
};
d3.scale.pow = function() {
return d3_scale_pow(d3.scale.linear(), 1, [ 0, 1 ]);
};
function d3_scale_pow(linear, exponent, domain) {
var powp = d3_scale_powPow(exponent), powb = d3_scale_powPow(1 / exponent);
function scale(x) {
return linear(powp(x));
}
scale.invert = function(x) {
return powb(linear.invert(x));
};
scale.domain = function(x) {
if (!arguments.length) return domain;
linear.domain((domain = x.map(Number)).map(powp));
return scale;
};
scale.ticks = function(m) {
return d3_scale_linearTicks(domain, m);
};
scale.tickFormat = function(m, format) {
return d3_scale_linearTickFormat(domain, m, format);
};
scale.nice = function(m) {
return scale.domain(d3_scale_linearNice(domain, m));
};
scale.exponent = function(x) {
if (!arguments.length) return exponent;
powp = d3_scale_powPow(exponent = x);
powb = d3_scale_powPow(1 / exponent);
linear.domain(domain.map(powp));
return scale;
};
scale.copy = function() {
return d3_scale_pow(linear.copy(), exponent, domain);
};
return d3_scale_linearRebind(scale, linear);
}
function d3_scale_powPow(e) {
return function(x) {
return x < 0 ? -Math.pow(-x, e) : Math.pow(x, e);
};
}
d3.scale.sqrt = function() {
return d3.scale.pow().exponent(.5);
};
d3.scale.ordinal = function() {
return d3_scale_ordinal([], {
t: "range",
a: [ [] ]
});
};
function d3_scale_ordinal(domain, ranger) {
var index, range, rangeBand;
function scale(x) {
return range[((index.get(x) || ranger.t === "range" && index.set(x, domain.push(x))) - 1) % range.length];
}
function steps(start, step) {
return d3.range(domain.length).map(function(i) {
return start + step * i;
});
}
scale.domain = function(x) {
if (!arguments.length) return domain;
domain = [];
index = new d3_Map();
var i = -1, n = x.length, xi;
while (++i < n) if (!index.has(xi = x[i])) index.set(xi, domain.push(xi));
return scale[ranger.t].apply(scale, ranger.a);
};
scale.range = function(x) {
if (!arguments.length) return range;
range = x;
rangeBand = 0;
ranger = {
t: "range",
a: arguments
};
return scale;
};
scale.rangePoints = function(x, padding) {
if (arguments.length < 2) padding = 0;
var start = x[0], stop = x[1], step = (stop - start) / (Math.max(1, domain.length - 1) + padding);
range = steps(domain.length < 2 ? (start + stop) / 2 : start + step * padding / 2, step);
rangeBand = 0;
ranger = {
t: "rangePoints",
a: arguments
};
return scale;
};
scale.rangeBands = function(x, padding, outerPadding) {
if (arguments.length < 2) padding = 0;
if (arguments.length < 3) outerPadding = padding;
var reverse = x[1] < x[0], start = x[reverse - 0], stop = x[1 - reverse], step = (stop - start) / (domain.length - padding + 2 * outerPadding);
range = steps(start + step * outerPadding, step);
if (reverse) range.reverse();
rangeBand = step * (1 - padding);
ranger = {
t: "rangeBands",
a: arguments
};
return scale;
};
scale.rangeRoundBands = function(x, padding, outerPadding) {
if (arguments.length < 2) padding = 0;
if (arguments.length < 3) outerPadding = padding;
var reverse = x[1] < x[0], start = x[reverse - 0], stop = x[1 - reverse], step = Math.floor((stop - start) / (domain.length - padding + 2 * outerPadding)), error = stop - start - (domain.length - padding) * step;
range = steps(start + Math.round(error / 2), step);
if (reverse) range.reverse();
rangeBand = Math.round(step * (1 - padding));
ranger = {
t: "rangeRoundBands",
a: arguments
};
return scale;
};
scale.rangeBand = function() {
return rangeBand;
};
scale.rangeExtent = function() {
return d3_scaleExtent(ranger.a[0]);
};
scale.copy = function() {
return d3_scale_ordinal(domain, ranger);
};
return scale.domain(domain);
}
d3.scale.category10 = function() {
return d3.scale.ordinal().range(d3_category10);
};
d3.scale.category20 = function() {
return d3.scale.ordinal().range(d3_category20);
};
d3.scale.category20b = function() {
return d3.scale.ordinal().range(d3_category20b);
};
d3.scale.category20c = function() {
return d3.scale.ordinal().range(d3_category20c);
};
var d3_category10 = [ 2062260, 16744206, 2924588, 14034728, 9725885, 9197131, 14907330, 8355711, 12369186, 1556175 ].map(d3_rgbString);
var d3_category20 = [ 2062260, 11454440, 16744206, 16759672, 2924588, 10018698, 14034728, 16750742, 9725885, 12955861, 9197131, 12885140, 14907330, 16234194, 8355711, 13092807, 12369186, 14408589, 1556175, 10410725 ].map(d3_rgbString);
var d3_category20b = [ 3750777, 5395619, 7040719, 10264286, 6519097, 9216594, 11915115, 13556636, 9202993, 12426809, 15186514, 15190932, 8666169, 11356490, 14049643, 15177372, 8077683, 10834324, 13528509, 14589654 ].map(d3_rgbString);
var d3_category20c = [ 3244733, 7057110, 10406625, 13032431, 15095053, 16616764, 16625259, 16634018, 3253076, 7652470, 10607003, 13101504, 7695281, 10394312, 12369372, 14342891, 6513507, 9868950, 12434877, 14277081 ].map(d3_rgbString);
d3.scale.quantile = function() {
return d3_scale_quantile([], []);
};
function d3_scale_quantile(domain, range) {
var thresholds;
function rescale() {
var k = 0, q = range.length;
thresholds = [];
while (++k < q) thresholds[k - 1] = d3.quantile(domain, k / q);
return scale;
}
function scale(x) {
if (!isNaN(x = +x)) return range[d3.bisect(thresholds, x)];
}
scale.domain = function(x) {
if (!arguments.length) return domain;
domain = x.filter(function(d) {
return !isNaN(d);
}).sort(d3.ascending);
return rescale();
};
scale.range = function(x) {
if (!arguments.length) return range;
range = x;
return rescale();
};
scale.quantiles = function() {
return thresholds;
};
scale.invertExtent = function(y) {
y = range.indexOf(y);
return y < 0 ? [ NaN, NaN ] : [ y > 0 ? thresholds[y - 1] : domain[0], y < thresholds.length ? thresholds[y] : domain[domain.length - 1] ];
};
scale.copy = function() {
return d3_scale_quantile(domain, range);
};
return rescale();
}
d3.scale.quantize = function() {
return d3_scale_quantize(0, 1, [ 0, 1 ]);
};
function d3_scale_quantize(x0, x1, range) {
var kx, i;
function scale(x) {
return range[Math.max(0, Math.min(i, Math.floor(kx * (x - x0))))];
}
function rescale() {
kx = range.length / (x1 - x0);
i = range.length - 1;
return scale;
}
scale.domain = function(x) {
if (!arguments.length) return [ x0, x1 ];
x0 = +x[0];
x1 = +x[x.length - 1];
return rescale();
};
scale.range = function(x) {
if (!arguments.length) return range;
range = x;
return rescale();
};
scale.invertExtent = function(y) {
y = range.indexOf(y);
y = y < 0 ? NaN : y / kx + x0;
return [ y, y + 1 / kx ];
};
scale.copy = function() {
return d3_scale_quantize(x0, x1, range);
};
return rescale();
}
d3.scale.threshold = function() {
return d3_scale_threshold([ .5 ], [ 0, 1 ]);
};
function d3_scale_threshold(domain, range) {
function scale(x) {
if (x <= x) return range[d3.bisect(domain, x)];
}
scale.domain = function(_) {
if (!arguments.length) return domain;
domain = _;
return scale;
};
scale.range = function(_) {
if (!arguments.length) return range;
range = _;
return scale;
};
scale.invertExtent = function(y) {
y = range.indexOf(y);
return [ domain[y - 1], domain[y] ];
};
scale.copy = function() {
return d3_scale_threshold(domain, range);
};
return scale;
}
d3.scale.identity = function() {
return d3_scale_identity([ 0, 1 ]);
};
function d3_scale_identity(domain) {
function identity(x) {
return +x;
}
identity.invert = identity;
identity.domain = identity.range = function(x) {
if (!arguments.length) return domain;
domain = x.map(identity);
return identity;
};
identity.ticks = function(m) {
return d3_scale_linearTicks(domain, m);
};
identity.tickFormat = function(m, format) {
return d3_scale_linearTickFormat(domain, m, format);
};
identity.copy = function() {
return d3_scale_identity(domain);
};
return identity;
}
d3.svg = {};
d3.svg.arc = function() {
var innerRadius = d3_svg_arcInnerRadius, outerRadius = d3_svg_arcOuterRadius, startAngle = d3_svg_arcStartAngle, endAngle = d3_svg_arcEndAngle;
function arc() {
var r0 = innerRadius.apply(this, arguments), r1 = outerRadius.apply(this, arguments), a0 = startAngle.apply(this, arguments) + d3_svg_arcOffset, a1 = endAngle.apply(this, arguments) + d3_svg_arcOffset, da = (a1 < a0 && (da = a0,
a0 = a1, a1 = da), a1 - a0), df = da < π ? "0" : "1", c0 = Math.cos(a0), s0 = Math.sin(a0), c1 = Math.cos(a1), s1 = Math.sin(a1);
return da >= d3_svg_arcMax ? r0 ? "M0," + r1 + "A" + r1 + "," + r1 + " 0 1,1 0," + -r1 + "A" + r1 + "," + r1 + " 0 1,1 0," + r1 + "M0," + r0 + "A" + r0 + "," + r0 + " 0 1,0 0," + -r0 + "A" + r0 + "," + r0 + " 0 1,0 0," + r0 + "Z" : "M0," + r1 + "A" + r1 + "," + r1 + " 0 1,1 0," + -r1 + "A" + r1 + "," + r1 + " 0 1,1 0," + r1 + "Z" : r0 ? "M" + r1 * c0 + "," + r1 * s0 + "A" + r1 + "," + r1 + " 0 " + df + ",1 " + r1 * c1 + "," + r1 * s1 + "L" + r0 * c1 + "," + r0 * s1 + "A" + r0 + "," + r0 + " 0 " + df + ",0 " + r0 * c0 + "," + r0 * s0 + "Z" : "M" + r1 * c0 + "," + r1 * s0 + "A" + r1 + "," + r1 + " 0 " + df + ",1 " + r1 * c1 + "," + r1 * s1 + "L0,0" + "Z";
}
arc.innerRadius = function(v) {
if (!arguments.length) return innerRadius;
innerRadius = d3_functor(v);
return arc;
};
arc.outerRadius = function(v) {
if (!arguments.length) return outerRadius;
outerRadius = d3_functor(v);
return arc;
};
arc.startAngle = function(v) {
if (!arguments.length) return startAngle;
startAngle = d3_functor(v);
return arc;
};
arc.endAngle = function(v) {
if (!arguments.length) return endAngle;
endAngle = d3_functor(v);
return arc;
};
arc.centroid = function() {
var r = (innerRadius.apply(this, arguments) + outerRadius.apply(this, arguments)) / 2, a = (startAngle.apply(this, arguments) + endAngle.apply(this, arguments)) / 2 + d3_svg_arcOffset;
return [ Math.cos(a) * r, Math.sin(a) * r ];
};
return arc;
};
var d3_svg_arcOffset = -halfπ, d3_svg_arcMax = τ - ε;
function d3_svg_arcInnerRadius(d) {
return d.innerRadius;
}
function d3_svg_arcOuterRadius(d) {
return d.outerRadius;
}
function d3_svg_arcStartAngle(d) {
return d.startAngle;
}
function d3_svg_arcEndAngle(d) {
return d.endAngle;
}
function d3_svg_line(projection) {
var x = d3_geom_pointX, y = d3_geom_pointY, defined = d3_true, interpolate = d3_svg_lineLinear, interpolateKey = interpolate.key, tension = .7;
function line(data) {
var segments = [], points = [], i = -1, n = data.length, d, fx = d3_functor(x), fy = d3_functor(y);
function segment() {
segments.push("M", interpolate(projection(points), tension));
}
while (++i < n) {
if (defined.call(this, d = data[i], i)) {
points.push([ +fx.call(this, d, i), +fy.call(this, d, i) ]);
} else if (points.length) {
segment();
points = [];
}
}
if (points.length) segment();
return segments.length ? segments.join("") : null;
}
line.x = function(_) {
if (!arguments.length) return x;
x = _;
return line;
};
line.y = function(_) {
if (!arguments.length) return y;
y = _;
return line;
};
line.defined = function(_) {
if (!arguments.length) return defined;
defined = _;
return line;
};
line.interpolate = function(_) {
if (!arguments.length) return interpolateKey;
if (typeof _ === "function") interpolateKey = interpolate = _; else interpolateKey = (interpolate = d3_svg_lineInterpolators.get(_) || d3_svg_lineLinear).key;
return line;
};
line.tension = function(_) {
if (!arguments.length) return tension;
tension = _;
return line;
};
return line;
}
d3.svg.line = function() {
return d3_svg_line(d3_identity);
};
var d3_svg_lineInterpolators = d3.map({
linear: d3_svg_lineLinear,
"linear-closed": d3_svg_lineLinearClosed,
step: d3_svg_lineStep,
"step-before": d3_svg_lineStepBefore,
"step-after": d3_svg_lineStepAfter,
basis: d3_svg_lineBasis,
"basis-open": d3_svg_lineBasisOpen,
"basis-closed": d3_svg_lineBasisClosed,
bundle: d3_svg_lineBundle,
cardinal: d3_svg_lineCardinal,
"cardinal-open": d3_svg_lineCardinalOpen,
"cardinal-closed": d3_svg_lineCardinalClosed,
monotone: d3_svg_lineMonotone
});
d3_svg_lineInterpolators.forEach(function(key, value) {
value.key = key;
value.closed = /-closed$/.test(key);
});
function d3_svg_lineLinear(points) {
return points.join("L");
}
function d3_svg_lineLinearClosed(points) {
return d3_svg_lineLinear(points) + "Z";
}
function d3_svg_lineStep(points) {
var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ];
while (++i < n) path.push("H", (p[0] + (p = points[i])[0]) / 2, "V", p[1]);
if (n > 1) path.push("H", p[0]);
return path.join("");
}
function d3_svg_lineStepBefore(points) {
var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ];
while (++i < n) path.push("V", (p = points[i])[1], "H", p[0]);
return path.join("");
}
function d3_svg_lineStepAfter(points) {
var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ];
while (++i < n) path.push("H", (p = points[i])[0], "V", p[1]);
return path.join("");
}
function d3_svg_lineCardinalOpen(points, tension) {
return points.length < 4 ? d3_svg_lineLinear(points) : points[1] + d3_svg_lineHermite(points.slice(1, points.length - 1), d3_svg_lineCardinalTangents(points, tension));
}
function d3_svg_lineCardinalClosed(points, tension) {
return points.length < 3 ? d3_svg_lineLinear(points) : points[0] + d3_svg_lineHermite((points.push(points[0]),
points), d3_svg_lineCardinalTangents([ points[points.length - 2] ].concat(points, [ points[1] ]), tension));
}
function d3_svg_lineCardinal(points, tension) {
return points.length < 3 ? d3_svg_lineLinear(points) : points[0] + d3_svg_lineHermite(points, d3_svg_lineCardinalTangents(points, tension));
}
function d3_svg_lineHermite(points, tangents) {
if (tangents.length < 1 || points.length != tangents.length && points.length != tangents.length + 2) {
return d3_svg_lineLinear(points);
}
var quad = points.length != tangents.length, path = "", p0 = points[0], p = points[1], t0 = tangents[0], t = t0, pi = 1;
if (quad) {
path += "Q" + (p[0] - t0[0] * 2 / 3) + "," + (p[1] - t0[1] * 2 / 3) + "," + p[0] + "," + p[1];
p0 = points[1];
pi = 2;
}
if (tangents.length > 1) {
t = tangents[1];
p = points[pi];
pi++;
path += "C" + (p0[0] + t0[0]) + "," + (p0[1] + t0[1]) + "," + (p[0] - t[0]) + "," + (p[1] - t[1]) + "," + p[0] + "," + p[1];
for (var i = 2; i < tangents.length; i++, pi++) {
p = points[pi];
t = tangents[i];
path += "S" + (p[0] - t[0]) + "," + (p[1] - t[1]) + "," + p[0] + "," + p[1];
}
}
if (quad) {
var lp = points[pi];
path += "Q" + (p[0] + t[0] * 2 / 3) + "," + (p[1] + t[1] * 2 / 3) + "," + lp[0] + "," + lp[1];
}
return path;
}
function d3_svg_lineCardinalTangents(points, tension) {
var tangents = [], a = (1 - tension) / 2, p0, p1 = points[0], p2 = points[1], i = 1, n = points.length;
while (++i < n) {
p0 = p1;
p1 = p2;
p2 = points[i];
tangents.push([ a * (p2[0] - p0[0]), a * (p2[1] - p0[1]) ]);
}
return tangents;
}
function d3_svg_lineBasis(points) {
if (points.length < 3) return d3_svg_lineLinear(points);
var i = 1, n = points.length, pi = points[0], x0 = pi[0], y0 = pi[1], px = [ x0, x0, x0, (pi = points[1])[0] ], py = [ y0, y0, y0, pi[1] ], path = [ x0, ",", y0, "L", d3_svg_lineDot4(d3_svg_lineBasisBezier3, px), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, py) ];
points.push(points[n - 1]);
while (++i <= n) {
pi = points[i];
px.shift();
px.push(pi[0]);
py.shift();
py.push(pi[1]);
d3_svg_lineBasisBezier(path, px, py);
}
points.pop();
path.push("L", pi);
return path.join("");
}
function d3_svg_lineBasisOpen(points) {
if (points.length < 4) return d3_svg_lineLinear(points);
var path = [], i = -1, n = points.length, pi, px = [ 0 ], py = [ 0 ];
while (++i < 3) {
pi = points[i];
px.push(pi[0]);
py.push(pi[1]);
}
path.push(d3_svg_lineDot4(d3_svg_lineBasisBezier3, px) + "," + d3_svg_lineDot4(d3_svg_lineBasisBezier3, py));
--i;
while (++i < n) {
pi = points[i];
px.shift();
px.push(pi[0]);
py.shift();
py.push(pi[1]);
d3_svg_lineBasisBezier(path, px, py);
}
return path.join("");
}
function d3_svg_lineBasisClosed(points) {
var path, i = -1, n = points.length, m = n + 4, pi, px = [], py = [];
while (++i < 4) {
pi = points[i % n];
px.push(pi[0]);
py.push(pi[1]);
}
path = [ d3_svg_lineDot4(d3_svg_lineBasisBezier3, px), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, py) ];
--i;
while (++i < m) {
pi = points[i % n];
px.shift();
px.push(pi[0]);
py.shift();
py.push(pi[1]);
d3_svg_lineBasisBezier(path, px, py);
}
return path.join("");
}
function d3_svg_lineBundle(points, tension) {
var n = points.length - 1;
if (n) {
var x0 = points[0][0], y0 = points[0][1], dx = points[n][0] - x0, dy = points[n][1] - y0, i = -1, p, t;
while (++i <= n) {
p = points[i];
t = i / n;
p[0] = tension * p[0] + (1 - tension) * (x0 + t * dx);
p[1] = tension * p[1] + (1 - tension) * (y0 + t * dy);
}
}
return d3_svg_lineBasis(points);
}
function d3_svg_lineDot4(a, b) {
return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3];
}
var d3_svg_lineBasisBezier1 = [ 0, 2 / 3, 1 / 3, 0 ], d3_svg_lineBasisBezier2 = [ 0, 1 / 3, 2 / 3, 0 ], d3_svg_lineBasisBezier3 = [ 0, 1 / 6, 2 / 3, 1 / 6 ];
function d3_svg_lineBasisBezier(path, x, y) {
path.push("C", d3_svg_lineDot4(d3_svg_lineBasisBezier1, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier1, y), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier2, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier2, y), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, y));
}
function d3_svg_lineSlope(p0, p1) {
return (p1[1] - p0[1]) / (p1[0] - p0[0]);
}
function d3_svg_lineFiniteDifferences(points) {
var i = 0, j = points.length - 1, m = [], p0 = points[0], p1 = points[1], d = m[0] = d3_svg_lineSlope(p0, p1);
while (++i < j) {
m[i] = (d + (d = d3_svg_lineSlope(p0 = p1, p1 = points[i + 1]))) / 2;
}
m[i] = d;
return m;
}
function d3_svg_lineMonotoneTangents(points) {
var tangents = [], d, a, b, s, m = d3_svg_lineFiniteDifferences(points), i = -1, j = points.length - 1;
while (++i < j) {
d = d3_svg_lineSlope(points[i], points[i + 1]);
if (abs(d) < ε) {
m[i] = m[i + 1] = 0;
} else {
a = m[i] / d;
b = m[i + 1] / d;
s = a * a + b * b;
if (s > 9) {
s = d * 3 / Math.sqrt(s);
m[i] = s * a;
m[i + 1] = s * b;
}
}
}
i = -1;
while (++i <= j) {
s = (points[Math.min(j, i + 1)][0] - points[Math.max(0, i - 1)][0]) / (6 * (1 + m[i] * m[i]));
tangents.push([ s || 0, m[i] * s || 0 ]);
}
return tangents;
}
function d3_svg_lineMonotone(points) {
return points.length < 3 ? d3_svg_lineLinear(points) : points[0] + d3_svg_lineHermite(points, d3_svg_lineMonotoneTangents(points));
}
d3.svg.line.radial = function() {
var line = d3_svg_line(d3_svg_lineRadial);
line.radius = line.x, delete line.x;
line.angle = line.y, delete line.y;
return line;
};
function d3_svg_lineRadial(points) {
var point, i = -1, n = points.length, r, a;
while (++i < n) {
point = points[i];
r = point[0];
a = point[1] + d3_svg_arcOffset;
point[0] = r * Math.cos(a);
point[1] = r * Math.sin(a);
}
return points;
}
function d3_svg_area(projection) {
var x0 = d3_geom_pointX, x1 = d3_geom_pointX, y0 = 0, y1 = d3_geom_pointY, defined = d3_true, interpolate = d3_svg_lineLinear, interpolateKey = interpolate.key, interpolateReverse = interpolate, L = "L", tension = .7;
function area(data) {
var segments = [], points0 = [], points1 = [], i = -1, n = data.length, d, fx0 = d3_functor(x0), fy0 = d3_functor(y0), fx1 = x0 === x1 ? function() {
return x;
} : d3_functor(x1), fy1 = y0 === y1 ? function() {
return y;
} : d3_functor(y1), x, y;
function segment() {
segments.push("M", interpolate(projection(points1), tension), L, interpolateReverse(projection(points0.reverse()), tension), "Z");
}
while (++i < n) {
if (defined.call(this, d = data[i], i)) {
points0.push([ x = +fx0.call(this, d, i), y = +fy0.call(this, d, i) ]);
points1.push([ +fx1.call(this, d, i), +fy1.call(this, d, i) ]);
} else if (points0.length) {
segment();
points0 = [];
points1 = [];
}
}
if (points0.length) segment();
return segments.length ? segments.join("") : null;
}
area.x = function(_) {
if (!arguments.length) return x1;
x0 = x1 = _;
return area;
};
area.x0 = function(_) {
if (!arguments.length) return x0;
x0 = _;
return area;
};
area.x1 = function(_) {
if (!arguments.length) return x1;
x1 = _;
return area;
};
area.y = function(_) {
if (!arguments.length) return y1;
y0 = y1 = _;
return area;
};
area.y0 = function(_) {
if (!arguments.length) return y0;
y0 = _;
return area;
};
area.y1 = function(_) {
if (!arguments.length) return y1;
y1 = _;
return area;
};
area.defined = function(_) {
if (!arguments.length) return defined;
defined = _;
return area;
};
area.interpolate = function(_) {
if (!arguments.length) return interpolateKey;
if (typeof _ === "function") interpolateKey = interpolate = _; else interpolateKey = (interpolate = d3_svg_lineInterpolators.get(_) || d3_svg_lineLinear).key;
interpolateReverse = interpolate.reverse || interpolate;
L = interpolate.closed ? "M" : "L";
return area;
};
area.tension = function(_) {
if (!arguments.length) return tension;
tension = _;
return area;
};
return area;
}
d3_svg_lineStepBefore.reverse = d3_svg_lineStepAfter;
d3_svg_lineStepAfter.reverse = d3_svg_lineStepBefore;
d3.svg.area = function() {
return d3_svg_area(d3_identity);
};
d3.svg.area.radial = function() {
var area = d3_svg_area(d3_svg_lineRadial);
area.radius = area.x, delete area.x;
area.innerRadius = area.x0, delete area.x0;
area.outerRadius = area.x1, delete area.x1;
area.angle = area.y, delete area.y;
area.startAngle = area.y0, delete area.y0;
area.endAngle = area.y1, delete area.y1;
return area;
};
d3.svg.chord = function() {
var source = d3_source, target = d3_target, radius = d3_svg_chordRadius, startAngle = d3_svg_arcStartAngle, endAngle = d3_svg_arcEndAngle;
function chord(d, i) {
var s = subgroup(this, source, d, i), t = subgroup(this, target, d, i);
return "M" + s.p0 + arc(s.r, s.p1, s.a1 - s.a0) + (equals(s, t) ? curve(s.r, s.p1, s.r, s.p0) : curve(s.r, s.p1, t.r, t.p0) + arc(t.r, t.p1, t.a1 - t.a0) + curve(t.r, t.p1, s.r, s.p0)) + "Z";
}
function subgroup(self, f, d, i) {
var subgroup = f.call(self, d, i), r = radius.call(self, subgroup, i), a0 = startAngle.call(self, subgroup, i) + d3_svg_arcOffset, a1 = endAngle.call(self, subgroup, i) + d3_svg_arcOffset;
return {
r: r,
a0: a0,
a1: a1,
p0: [ r * Math.cos(a0), r * Math.sin(a0) ],
p1: [ r * Math.cos(a1), r * Math.sin(a1) ]
};
}
function equals(a, b) {
return a.a0 == b.a0 && a.a1 == b.a1;
}
function arc(r, p, a) {
return "A" + r + "," + r + " 0 " + +(a > π) + ",1 " + p;
}
function curve(r0, p0, r1, p1) {
return "Q 0,0 " + p1;
}
chord.radius = function(v) {
if (!arguments.length) return radius;
radius = d3_functor(v);
return chord;
};
chord.source = function(v) {
if (!arguments.length) return source;
source = d3_functor(v);
return chord;
};
chord.target = function(v) {
if (!arguments.length) return target;
target = d3_functor(v);
return chord;
};
chord.startAngle = function(v) {
if (!arguments.length) return startAngle;
startAngle = d3_functor(v);
return chord;
};
chord.endAngle = function(v) {
if (!arguments.length) return endAngle;
endAngle = d3_functor(v);
return chord;
};
return chord;
};
function d3_svg_chordRadius(d) {
return d.radius;
}
d3.svg.diagonal = function() {
var source = d3_source, target = d3_target, projection = d3_svg_diagonalProjection;
function diagonal(d, i) {
var p0 = source.call(this, d, i), p3 = target.call(this, d, i), m = (p0.y + p3.y) / 2, p = [ p0, {
x: p0.x,
y: m
}, {
x: p3.x,
y: m
}, p3 ];
p = p.map(projection);
return "M" + p[0] + "C" + p[1] + " " + p[2] + " " + p[3];
}
diagonal.source = function(x) {
if (!arguments.length) return source;
source = d3_functor(x);
return diagonal;
};
diagonal.target = function(x) {
if (!arguments.length) return target;
target = d3_functor(x);
return diagonal;
};
diagonal.projection = function(x) {
if (!arguments.length) return projection;
projection = x;
return diagonal;
};
return diagonal;
};
function d3_svg_diagonalProjection(d) {
return [ d.x, d.y ];
}
d3.svg.diagonal.radial = function() {
var diagonal = d3.svg.diagonal(), projection = d3_svg_diagonalProjection, projection_ = diagonal.projection;
diagonal.projection = function(x) {
return arguments.length ? projection_(d3_svg_diagonalRadialProjection(projection = x)) : projection;
};
return diagonal;
};
function d3_svg_diagonalRadialProjection(projection) {
return function() {
var d = projection.apply(this, arguments), r = d[0], a = d[1] + d3_svg_arcOffset;
return [ r * Math.cos(a), r * Math.sin(a) ];
};
}
d3.svg.symbol = function() {
var type = d3_svg_symbolType, size = d3_svg_symbolSize;
function symbol(d, i) {
return (d3_svg_symbols.get(type.call(this, d, i)) || d3_svg_symbolCircle)(size.call(this, d, i));
}
symbol.type = function(x) {
if (!arguments.length) return type;
type = d3_functor(x);
return symbol;
};
symbol.size = function(x) {
if (!arguments.length) return size;
size = d3_functor(x);
return symbol;
};
return symbol;
};
function d3_svg_symbolSize() {
return 64;
}
function d3_svg_symbolType() {
return "circle";
}
function d3_svg_symbolCircle(size) {
var r = Math.sqrt(size / π);
return "M0," + r + "A" + r + "," + r + " 0 1,1 0," + -r + "A" + r + "," + r + " 0 1,1 0," + r + "Z";
}
var d3_svg_symbols = d3.map({
circle: d3_svg_symbolCircle,
cross: function(size) {
var r = Math.sqrt(size / 5) / 2;
return "M" + -3 * r + "," + -r + "H" + -r + "V" + -3 * r + "H" + r + "V" + -r + "H" + 3 * r + "V" + r + "H" + r + "V" + 3 * r + "H" + -r + "V" + r + "H" + -3 * r + "Z";
},
diamond: function(size) {
var ry = Math.sqrt(size / (2 * d3_svg_symbolTan30)), rx = ry * d3_svg_symbolTan30;
return "M0," + -ry + "L" + rx + ",0" + " 0," + ry + " " + -rx + ",0" + "Z";
},
square: function(size) {
var r = Math.sqrt(size) / 2;
return "M" + -r + "," + -r + "L" + r + "," + -r + " " + r + "," + r + " " + -r + "," + r + "Z";
},
"triangle-down": function(size) {
var rx = Math.sqrt(size / d3_svg_symbolSqrt3), ry = rx * d3_svg_symbolSqrt3 / 2;
return "M0," + ry + "L" + rx + "," + -ry + " " + -rx + "," + -ry + "Z";
},
"triangle-up": function(size) {
var rx = Math.sqrt(size / d3_svg_symbolSqrt3), ry = rx * d3_svg_symbolSqrt3 / 2;
return "M0," + -ry + "L" + rx + "," + ry + " " + -rx + "," + ry + "Z";
}
});
d3.svg.symbolTypes = d3_svg_symbols.keys();
var d3_svg_symbolSqrt3 = Math.sqrt(3), d3_svg_symbolTan30 = Math.tan(30 * d3_radians);
function d3_transition(groups, id) {
d3_subclass(groups, d3_transitionPrototype);
groups.id = id;
return groups;
}
var d3_transitionPrototype = [], d3_transitionId = 0, d3_transitionInheritId, d3_transitionInherit;
d3_transitionPrototype.call = d3_selectionPrototype.call;
d3_transitionPrototype.empty = d3_selectionPrototype.empty;
d3_transitionPrototype.node = d3_selectionPrototype.node;
d3_transitionPrototype.size = d3_selectionPrototype.size;
d3.transition = function(selection) {
return arguments.length ? d3_transitionInheritId ? selection.transition() : selection : d3_selectionRoot.transition();
};
d3.transition.prototype = d3_transitionPrototype;
d3_transitionPrototype.select = function(selector) {
var id = this.id, subgroups = [], subgroup, subnode, node;
selector = d3_selection_selector(selector);
for (var j = -1, m = this.length; ++j < m; ) {
subgroups.push(subgroup = []);
for (var group = this[j], i = -1, n = group.length; ++i < n; ) {
if ((node = group[i]) && (subnode = selector.call(node, node.__data__, i, j))) {
if ("__data__" in node) subnode.__data__ = node.__data__;
d3_transitionNode(subnode, i, id, node.__transition__[id]);
subgroup.push(subnode);
} else {
subgroup.push(null);
}
}
}
return d3_transition(subgroups, id);
};
d3_transitionPrototype.selectAll = function(selector) {
var id = this.id, subgroups = [], subgroup, subnodes, node, subnode, transition;
selector = d3_selection_selectorAll(selector);
for (var j = -1, m = this.length; ++j < m; ) {
for (var group = this[j], i = -1, n = group.length; ++i < n; ) {
if (node = group[i]) {
transition = node.__transition__[id];
subnodes = selector.call(node, node.__data__, i, j);
subgroups.push(subgroup = []);
for (var k = -1, o = subnodes.length; ++k < o; ) {
if (subnode = subnodes[k]) d3_transitionNode(subnode, k, id, transition);
subgroup.push(subnode);
}
}
}
}
return d3_transition(subgroups, id);
};
d3_transitionPrototype.filter = function(filter) {
var subgroups = [], subgroup, group, node;
if (typeof filter !== "function") filter = d3_selection_filter(filter);
for (var j = 0, m = this.length; j < m; j++) {
subgroups.push(subgroup = []);
for (var group = this[j], i = 0, n = group.length; i < n; i++) {
if ((node = group[i]) && filter.call(node, node.__data__, i)) {
subgroup.push(node);
}
}
}
return d3_transition(subgroups, this.id);
};
d3_transitionPrototype.tween = function(name, tween) {
var id = this.id;
if (arguments.length < 2) return this.node().__transition__[id].tween.get(name);
return d3_selection_each(this, tween == null ? function(node) {
node.__transition__[id].tween.remove(name);
} : function(node) {
node.__transition__[id].tween.set(name, tween);
});
};
function d3_transition_tween(groups, name, value, tween) {
var id = groups.id;
return d3_selection_each(groups, typeof value === "function" ? function(node, i, j) {
node.__transition__[id].tween.set(name, tween(value.call(node, node.__data__, i, j)));
} : (value = tween(value), function(node) {
node.__transition__[id].tween.set(name, value);
}));
}
d3_transitionPrototype.attr = function(nameNS, value) {
if (arguments.length < 2) {
for (value in nameNS) this.attr(value, nameNS[value]);
return this;
}
var interpolate = nameNS == "transform" ? d3_interpolateTransform : d3_interpolate, name = d3.ns.qualify(nameNS);
function attrNull() {
this.removeAttribute(name);
}
function attrNullNS() {
this.removeAttributeNS(name.space, name.local);
}
function attrTween(b) {
return b == null ? attrNull : (b += "", function() {
var a = this.getAttribute(name), i;
return a !== b && (i = interpolate(a, b), function(t) {
this.setAttribute(name, i(t));
});
});
}
function attrTweenNS(b) {
return b == null ? attrNullNS : (b += "", function() {
var a = this.getAttributeNS(name.space, name.local), i;
return a !== b && (i = interpolate(a, b), function(t) {
this.setAttributeNS(name.space, name.local, i(t));
});
});
}
return d3_transition_tween(this, "attr." + nameNS, value, name.local ? attrTweenNS : attrTween);
};
d3_transitionPrototype.attrTween = function(nameNS, tween) {
var name = d3.ns.qualify(nameNS);
function attrTween(d, i) {
var f = tween.call(this, d, i, this.getAttribute(name));
return f && function(t) {
this.setAttribute(name, f(t));
};
}
function attrTweenNS(d, i) {
var f = tween.call(this, d, i, this.getAttributeNS(name.space, name.local));
return f && function(t) {
this.setAttributeNS(name.space, name.local, f(t));
};
}
return this.tween("attr." + nameNS, name.local ? attrTweenNS : attrTween);
};
d3_transitionPrototype.style = function(name, value, priority) {
var n = arguments.length;
if (n < 3) {
if (typeof name !== "string") {
if (n < 2) value = "";
for (priority in name) this.style(priority, name[priority], value);
return this;
}
priority = "";
}
function styleNull() {
this.style.removeProperty(name);
}
function styleString(b) {
return b == null ? styleNull : (b += "", function() {
var a = d3_window.getComputedStyle(this, null).getPropertyValue(name), i;
return a !== b && (i = d3_interpolate(a, b), function(t) {
this.style.setProperty(name, i(t), priority);
});
});
}
return d3_transition_tween(this, "style." + name, value, styleString);
};
d3_transitionPrototype.styleTween = function(name, tween, priority) {
if (arguments.length < 3) priority = "";
function styleTween(d, i) {
var f = tween.call(this, d, i, d3_window.getComputedStyle(this, null).getPropertyValue(name));
return f && function(t) {
this.style.setProperty(name, f(t), priority);
};
}
return this.tween("style." + name, styleTween);
};
d3_transitionPrototype.text = function(value) {
return d3_transition_tween(this, "text", value, d3_transition_text);
};
function d3_transition_text(b) {
if (b == null) b = "";
return function() {
this.textContent = b;
};
}
d3_transitionPrototype.remove = function() {
return this.each("end.transition", function() {
var p;
if (this.__transition__.count < 2 && (p = this.parentNode)) p.removeChild(this);
});
};
d3_transitionPrototype.ease = function(value) {
var id = this.id;
if (arguments.length < 1) return this.node().__transition__[id].ease;
if (typeof value !== "function") value = d3.ease.apply(d3, arguments);
return d3_selection_each(this, function(node) {
node.__transition__[id].ease = value;
});
};
d3_transitionPrototype.delay = function(value) {
var id = this.id;
return d3_selection_each(this, typeof value === "function" ? function(node, i, j) {
node.__transition__[id].delay = +value.call(node, node.__data__, i, j);
} : (value = +value, function(node) {
node.__transition__[id].delay = value;
}));
};
d3_transitionPrototype.duration = function(value) {
var id = this.id;
return d3_selection_each(this, typeof value === "function" ? function(node, i, j) {
node.__transition__[id].duration = Math.max(1, value.call(node, node.__data__, i, j));
} : (value = Math.max(1, value), function(node) {
node.__transition__[id].duration = value;
}));
};
d3_transitionPrototype.each = function(type, listener) {
var id = this.id;
if (arguments.length < 2) {
var inherit = d3_transitionInherit, inheritId = d3_transitionInheritId;
d3_transitionInheritId = id;
d3_selection_each(this, function(node, i, j) {
d3_transitionInherit = node.__transition__[id];
type.call(node, node.__data__, i, j);
});
d3_transitionInherit = inherit;
d3_transitionInheritId = inheritId;
} else {
d3_selection_each(this, function(node) {
var transition = node.__transition__[id];
(transition.event || (transition.event = d3.dispatch("start", "end"))).on(type, listener);
});
}
return this;
};
d3_transitionPrototype.transition = function() {
var id0 = this.id, id1 = ++d3_transitionId, subgroups = [], subgroup, group, node, transition;
for (var j = 0, m = this.length; j < m; j++) {
subgroups.push(subgroup = []);
for (var group = this[j], i = 0, n = group.length; i < n; i++) {
if (node = group[i]) {
transition = Object.create(node.__transition__[id0]);
transition.delay += transition.duration;
d3_transitionNode(node, i, id1, transition);
}
subgroup.push(node);
}
}
return d3_transition(subgroups, id1);
};
function d3_transitionNode(node, i, id, inherit) {
var lock = node.__transition__ || (node.__transition__ = {
active: 0,
count: 0
}), transition = lock[id];
if (!transition) {
var time = inherit.time;
transition = lock[id] = {
tween: new d3_Map(),
time: time,
ease: inherit.ease,
delay: inherit.delay,
duration: inherit.duration
};
++lock.count;
d3.timer(function(elapsed) {
var d = node.__data__, ease = transition.ease, delay = transition.delay, duration = transition.duration, timer = d3_timer_active, tweened = [];
timer.t = delay + time;
if (delay <= elapsed) return start(elapsed - delay);
timer.c = start;
function start(elapsed) {
if (lock.active > id) return stop();
lock.active = id;
transition.event && transition.event.start.call(node, d, i);
transition.tween.forEach(function(key, value) {
if (value = value.call(node, d, i)) {
tweened.push(value);
}
});
d3.timer(function() {
timer.c = tick(elapsed || 1) ? d3_true : tick;
return 1;
}, 0, time);
}
function tick(elapsed) {
if (lock.active !== id) return stop();
var t = elapsed / duration, e = ease(t), n = tweened.length;
while (n > 0) {
tweened[--n].call(node, e);
}
if (t >= 1) {
transition.event && transition.event.end.call(node, d, i);
return stop();
}
}
function stop() {
if (--lock.count) delete lock[id]; else delete node.__transition__;
return 1;
}
}, 0, time);
}
}
d3.svg.axis = function() {
var scale = d3.scale.linear(), orient = d3_svg_axisDefaultOrient, innerTickSize = 6, outerTickSize = 6, tickPadding = 3, tickArguments_ = [ 10 ], tickValues = null, tickFormat_;
function axis(g) {
g.each(function() {
var g = d3.select(this);
var scale0 = this.__chart__ || scale, scale1 = this.__chart__ = scale.copy();
var ticks = tickValues == null ? scale1.ticks ? scale1.ticks.apply(scale1, tickArguments_) : scale1.domain() : tickValues, tickFormat = tickFormat_ == null ? scale1.tickFormat ? scale1.tickFormat.apply(scale1, tickArguments_) : d3_identity : tickFormat_, tick = g.selectAll(".tick").data(ticks, scale1), tickEnter = tick.enter().insert("g", ".domain").attr("class", "tick").style("opacity", ε), tickExit = d3.transition(tick.exit()).style("opacity", ε).remove(), tickUpdate = d3.transition(tick).style("opacity", 1), tickTransform;
var range = d3_scaleRange(scale1), path = g.selectAll(".domain").data([ 0 ]), pathUpdate = (path.enter().append("path").attr("class", "domain"),
d3.transition(path));
tickEnter.append("line");
tickEnter.append("text");
var lineEnter = tickEnter.select("line"), lineUpdate = tickUpdate.select("line"), text = tick.select("text").text(tickFormat), textEnter = tickEnter.select("text"), textUpdate = tickUpdate.select("text");
switch (orient) {
case "bottom":
{
tickTransform = d3_svg_axisX;
lineEnter.attr("y2", innerTickSize);
textEnter.attr("y", Math.max(innerTickSize, 0) + tickPadding);
lineUpdate.attr("x2", 0).attr("y2", innerTickSize);
textUpdate.attr("x", 0).attr("y", Math.max(innerTickSize, 0) + tickPadding);
text.attr("dy", ".71em").style("text-anchor", "middle");
pathUpdate.attr("d", "M" + range[0] + "," + outerTickSize + "V0H" + range[1] + "V" + outerTickSize);
break;
}
case "top":
{
tickTransform = d3_svg_axisX;
lineEnter.attr("y2", -innerTickSize);
textEnter.attr("y", -(Math.max(innerTickSize, 0) + tickPadding));
lineUpdate.attr("x2", 0).attr("y2", -innerTickSize);
textUpdate.attr("x", 0).attr("y", -(Math.max(innerTickSize, 0) + tickPadding));
text.attr("dy", "0em").style("text-anchor", "middle");
pathUpdate.attr("d", "M" + range[0] + "," + -outerTickSize + "V0H" + range[1] + "V" + -outerTickSize);
break;
}
case "left":
{
tickTransform = d3_svg_axisY;
lineEnter.attr("x2", -innerTickSize);
textEnter.attr("x", -(Math.max(innerTickSize, 0) + tickPadding));
lineUpdate.attr("x2", -innerTickSize).attr("y2", 0);
textUpdate.attr("x", -(Math.max(innerTickSize, 0) + tickPadding)).attr("y", 0);
text.attr("dy", ".32em").style("text-anchor", "end");
pathUpdate.attr("d", "M" + -outerTickSize + "," + range[0] + "H0V" + range[1] + "H" + -outerTickSize);
break;
}
case "right":
{
tickTransform = d3_svg_axisY;
lineEnter.attr("x2", innerTickSize);
textEnter.attr("x", Math.max(innerTickSize, 0) + tickPadding);
lineUpdate.attr("x2", innerTickSize).attr("y2", 0);
textUpdate.attr("x", Math.max(innerTickSize, 0) + tickPadding).attr("y", 0);
text.attr("dy", ".32em").style("text-anchor", "start");
pathUpdate.attr("d", "M" + outerTickSize + "," + range[0] + "H0V" + range[1] + "H" + outerTickSize);
break;
}
}
if (scale1.rangeBand) {
var dx = scale1.rangeBand() / 2, x = function(d) {
return scale1(d) + dx;
};
tickEnter.call(tickTransform, x);
tickUpdate.call(tickTransform, x);
} else {
tickEnter.call(tickTransform, scale0);
tickUpdate.call(tickTransform, scale1);
tickExit.call(tickTransform, scale1);
}
});
}
axis.scale = function(x) {
if (!arguments.length) return scale;
scale = x;
return axis;
};
axis.orient = function(x) {
if (!arguments.length) return orient;
orient = x in d3_svg_axisOrients ? x + "" : d3_svg_axisDefaultOrient;
return axis;
};
axis.ticks = function() {
if (!arguments.length) return tickArguments_;
tickArguments_ = arguments;
return axis;
};
axis.tickValues = function(x) {
if (!arguments.length) return tickValues;
tickValues = x;
return axis;
};
axis.tickFormat = function(x) {
if (!arguments.length) return tickFormat_;
tickFormat_ = x;
return axis;
};
axis.tickSize = function(x) {
var n = arguments.length;
if (!n) return innerTickSize;
innerTickSize = +x;
outerTickSize = +arguments[n - 1];
return axis;
};
axis.innerTickSize = function(x) {
if (!arguments.length) return innerTickSize;
innerTickSize = +x;
return axis;
};
axis.outerTickSize = function(x) {
if (!arguments.length) return outerTickSize;
outerTickSize = +x;
return axis;
};
axis.tickPadding = function(x) {
if (!arguments.length) return tickPadding;
tickPadding = +x;
return axis;
};
axis.tickSubdivide = function() {
return arguments.length && axis;
};
return axis;
};
var d3_svg_axisDefaultOrient = "bottom", d3_svg_axisOrients = {
top: 1,
right: 1,
bottom: 1,
left: 1
};
function d3_svg_axisX(selection, x) {
selection.attr("transform", function(d) {
return "translate(" + x(d) + ",0)";
});
}
function d3_svg_axisY(selection, y) {
selection.attr("transform", function(d) {
return "translate(0," + y(d) + ")";
});
}
d3.svg.brush = function() {
var event = d3_eventDispatch(brush, "brushstart", "brush", "brushend"), x = null, y = null, xExtent = [ 0, 0 ], yExtent = [ 0, 0 ], xExtentDomain, yExtentDomain, xClamp = true, yClamp = true, resizes = d3_svg_brushResizes[0];
function brush(g) {
g.each(function() {
var g = d3.select(this).style("pointer-events", "all").style("-webkit-tap-highlight-color", "rgba(0,0,0,0)").on("mousedown.brush", brushstart).on("touchstart.brush", brushstart);
var background = g.selectAll(".background").data([ 0 ]);
background.enter().append("rect").attr("class", "background").style("visibility", "hidden").style("cursor", "crosshair");
g.selectAll(".extent").data([ 0 ]).enter().append("rect").attr("class", "extent").style("cursor", "move");
var resize = g.selectAll(".resize").data(resizes, d3_identity);
resize.exit().remove();
resize.enter().append("g").attr("class", function(d) {
return "resize " + d;
}).style("cursor", function(d) {
return d3_svg_brushCursor[d];
}).append("rect").attr("x", function(d) {
return /[ew]$/.test(d) ? -3 : null;
}).attr("y", function(d) {
return /^[ns]/.test(d) ? -3 : null;
}).attr("width", 6).attr("height", 6).style("visibility", "hidden");
resize.style("display", brush.empty() ? "none" : null);
var gUpdate = d3.transition(g), backgroundUpdate = d3.transition(background), range;
if (x) {
range = d3_scaleRange(x);
backgroundUpdate.attr("x", range[0]).attr("width", range[1] - range[0]);
redrawX(gUpdate);
}
if (y) {
range = d3_scaleRange(y);
backgroundUpdate.attr("y", range[0]).attr("height", range[1] - range[0]);
redrawY(gUpdate);
}
redraw(gUpdate);
});
}
brush.event = function(g) {
g.each(function() {
var event_ = event.of(this, arguments), extent1 = {
x: xExtent,
y: yExtent,
i: xExtentDomain,
j: yExtentDomain
}, extent0 = this.__chart__ || extent1;
this.__chart__ = extent1;
if (d3_transitionInheritId) {
d3.select(this).transition().each("start.brush", function() {
xExtentDomain = extent0.i;
yExtentDomain = extent0.j;
xExtent = extent0.x;
yExtent = extent0.y;
event_({
type: "brushstart"
});
}).tween("brush:brush", function() {
var xi = d3_interpolateArray(xExtent, extent1.x), yi = d3_interpolateArray(yExtent, extent1.y);
xExtentDomain = yExtentDomain = null;
return function(t) {
xExtent = extent1.x = xi(t);
yExtent = extent1.y = yi(t);
event_({
type: "brush",
mode: "resize"
});
};
}).each("end.brush", function() {
xExtentDomain = extent1.i;
yExtentDomain = extent1.j;
event_({
type: "brush",
mode: "resize"
});
event_({
type: "brushend"
});
});
} else {
event_({
type: "brushstart"
});
event_({
type: "brush",
mode: "resize"
});
event_({
type: "brushend"
});
}
});
};
function redraw(g) {
g.selectAll(".resize").attr("transform", function(d) {
return "translate(" + xExtent[+/e$/.test(d)] + "," + yExtent[+/^s/.test(d)] + ")";
});
}
function redrawX(g) {
g.select(".extent").attr("x", xExtent[0]);
g.selectAll(".extent,.n>rect,.s>rect").attr("width", xExtent[1] - xExtent[0]);
}
function redrawY(g) {
g.select(".extent").attr("y", yExtent[0]);
g.selectAll(".extent,.e>rect,.w>rect").attr("height", yExtent[1] - yExtent[0]);
}
function brushstart() {
var target = this, eventTarget = d3.select(d3.event.target), event_ = event.of(target, arguments), g = d3.select(target), resizing = eventTarget.datum(), resizingX = !/^(n|s)$/.test(resizing) && x, resizingY = !/^(e|w)$/.test(resizing) && y, dragging = eventTarget.classed("extent"), dragRestore = d3_event_dragSuppress(), center, origin = d3.mouse(target), offset;
var w = d3.select(d3_window).on("keydown.brush", keydown).on("keyup.brush", keyup);
if (d3.event.changedTouches) {
w.on("touchmove.brush", brushmove).on("touchend.brush", brushend);
} else {
w.on("mousemove.brush", brushmove).on("mouseup.brush", brushend);
}
g.interrupt().selectAll("*").interrupt();
if (dragging) {
origin[0] = xExtent[0] - origin[0];
origin[1] = yExtent[0] - origin[1];
} else if (resizing) {
var ex = +/w$/.test(resizing), ey = +/^n/.test(resizing);
offset = [ xExtent[1 - ex] - origin[0], yExtent[1 - ey] - origin[1] ];
origin[0] = xExtent[ex];
origin[1] = yExtent[ey];
} else if (d3.event.altKey) center = origin.slice();
g.style("pointer-events", "none").selectAll(".resize").style("display", null);
d3.select("body").style("cursor", eventTarget.style("cursor"));
event_({
type: "brushstart"
});
brushmove();
function keydown() {
if (d3.event.keyCode == 32) {
if (!dragging) {
center = null;
origin[0] -= xExtent[1];
origin[1] -= yExtent[1];
dragging = 2;
}
d3_eventPreventDefault();
}
}
function keyup() {
if (d3.event.keyCode == 32 && dragging == 2) {
origin[0] += xExtent[1];
origin[1] += yExtent[1];
dragging = 0;
d3_eventPreventDefault();
}
}
function brushmove() {
var point = d3.mouse(target), moved = false;
if (offset) {
point[0] += offset[0];
point[1] += offset[1];
}
if (!dragging) {
if (d3.event.altKey) {
if (!center) center = [ (xExtent[0] + xExtent[1]) / 2, (yExtent[0] + yExtent[1]) / 2 ];
origin[0] = xExtent[+(point[0] < center[0])];
origin[1] = yExtent[+(point[1] < center[1])];
} else center = null;
}
if (resizingX && move1(point, x, 0)) {
redrawX(g);
moved = true;
}
if (resizingY && move1(point, y, 1)) {
redrawY(g);
moved = true;
}
if (moved) {
redraw(g);
event_({
type: "brush",
mode: dragging ? "move" : "resize"
});
}
}
function move1(point, scale, i) {
var range = d3_scaleRange(scale), r0 = range[0], r1 = range[1], position = origin[i], extent = i ? yExtent : xExtent, size = extent[1] - extent[0], min, max;
if (dragging) {
r0 -= position;
r1 -= size + position;
}
min = (i ? yClamp : xClamp) ? Math.max(r0, Math.min(r1, point[i])) : point[i];
if (dragging) {
max = (min += position) + size;
} else {
if (center) position = Math.max(r0, Math.min(r1, 2 * center[i] - min));
if (position < min) {
max = min;
min = position;
} else {
max = position;
}
}
if (extent[0] != min || extent[1] != max) {
if (i) yExtentDomain = null; else xExtentDomain = null;
extent[0] = min;
extent[1] = max;
return true;
}
}
function brushend() {
brushmove();
g.style("pointer-events", "all").selectAll(".resize").style("display", brush.empty() ? "none" : null);
d3.select("body").style("cursor", null);
w.on("mousemove.brush", null).on("mouseup.brush", null).on("touchmove.brush", null).on("touchend.brush", null).on("keydown.brush", null).on("keyup.brush", null);
dragRestore();
event_({
type: "brushend"
});
}
}
brush.x = function(z) {
if (!arguments.length) return x;
x = z;
resizes = d3_svg_brushResizes[!x << 1 | !y];
return brush;
};
brush.y = function(z) {
if (!arguments.length) return y;
y = z;
resizes = d3_svg_brushResizes[!x << 1 | !y];
return brush;
};
brush.clamp = function(z) {
if (!arguments.length) return x && y ? [ xClamp, yClamp ] : x ? xClamp : y ? yClamp : null;
if (x && y) xClamp = !!z[0], yClamp = !!z[1]; else if (x) xClamp = !!z; else if (y) yClamp = !!z;
return brush;
};
brush.extent = function(z) {
var x0, x1, y0, y1, t;
if (!arguments.length) {
if (x) {
if (xExtentDomain) {
x0 = xExtentDomain[0], x1 = xExtentDomain[1];
} else {
x0 = xExtent[0], x1 = xExtent[1];
if (x.invert) x0 = x.invert(x0), x1 = x.invert(x1);
if (x1 < x0) t = x0, x0 = x1, x1 = t;
}
}
if (y) {
if (yExtentDomain) {
y0 = yExtentDomain[0], y1 = yExtentDomain[1];
} else {
y0 = yExtent[0], y1 = yExtent[1];
if (y.invert) y0 = y.invert(y0), y1 = y.invert(y1);
if (y1 < y0) t = y0, y0 = y1, y1 = t;
}
}
return x && y ? [ [ x0, y0 ], [ x1, y1 ] ] : x ? [ x0, x1 ] : y && [ y0, y1 ];
}
if (x) {
x0 = z[0], x1 = z[1];
if (y) x0 = x0[0], x1 = x1[0];
xExtentDomain = [ x0, x1 ];
if (x.invert) x0 = x(x0), x1 = x(x1);
if (x1 < x0) t = x0, x0 = x1, x1 = t;
if (x0 != xExtent[0] || x1 != xExtent[1]) xExtent = [ x0, x1 ];
}
if (y) {
y0 = z[0], y1 = z[1];
if (x) y0 = y0[1], y1 = y1[1];
yExtentDomain = [ y0, y1 ];
if (y.invert) y0 = y(y0), y1 = y(y1);
if (y1 < y0) t = y0, y0 = y1, y1 = t;
if (y0 != yExtent[0] || y1 != yExtent[1]) yExtent = [ y0, y1 ];
}
return brush;
};
brush.clear = function() {
if (!brush.empty()) {
xExtent = [ 0, 0 ], yExtent = [ 0, 0 ];
xExtentDomain = yExtentDomain = null;
}
return brush;
};
brush.empty = function() {
return !!x && xExtent[0] == xExtent[1] || !!y && yExtent[0] == yExtent[1];
};
return d3.rebind(brush, event, "on");
};
var d3_svg_brushCursor = {
n: "ns-resize",
e: "ew-resize",
s: "ns-resize",
w: "ew-resize",
nw: "nwse-resize",
ne: "nesw-resize",
se: "nwse-resize",
sw: "nesw-resize"
};
var d3_svg_brushResizes = [ [ "n", "e", "s", "w", "nw", "ne", "se", "sw" ], [ "e", "w" ], [ "n", "s" ], [] ];
var d3_time = d3.time = {}, d3_date = Date, d3_time_daySymbols = [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ];
function d3_date_utc() {
this._ = new Date(arguments.length > 1 ? Date.UTC.apply(this, arguments) : arguments[0]);
}
d3_date_utc.prototype = {
getDate: function() {
return this._.getUTCDate();
},
getDay: function() {
return this._.getUTCDay();
},
getFullYear: function() {
return this._.getUTCFullYear();
},
getHours: function() {
return this._.getUTCHours();
},
getMilliseconds: function() {
return this._.getUTCMilliseconds();
},
getMinutes: function() {
return this._.getUTCMinutes();
},
getMonth: function() {
return this._.getUTCMonth();
},
getSeconds: function() {
return this._.getUTCSeconds();
},
getTime: function() {
return this._.getTime();
},
getTimezoneOffset: function() {
return 0;
},
valueOf: function() {
return this._.valueOf();
},
setDate: function() {
d3_time_prototype.setUTCDate.apply(this._, arguments);
},
setDay: function() {
d3_time_prototype.setUTCDay.apply(this._, arguments);
},
setFullYear: function() {
d3_time_prototype.setUTCFullYear.apply(this._, arguments);
},
setHours: function() {
d3_time_prototype.setUTCHours.apply(this._, arguments);
},
setMilliseconds: function() {
d3_time_prototype.setUTCMilliseconds.apply(this._, arguments);
},
setMinutes: function() {
d3_time_prototype.setUTCMinutes.apply(this._, arguments);
},
setMonth: function() {
d3_time_prototype.setUTCMonth.apply(this._, arguments);
},
setSeconds: function() {
d3_time_prototype.setUTCSeconds.apply(this._, arguments);
},
setTime: function() {
d3_time_prototype.setTime.apply(this._, arguments);
}
};
var d3_time_prototype = Date.prototype;
var d3_time_formatDateTime = "%a %b %e %X %Y", d3_time_formatDate = "%m/%d/%Y", d3_time_formatTime = "%H:%M:%S";
var d3_time_days = [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ], d3_time_dayAbbreviations = [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ], d3_time_months = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ], d3_time_monthAbbreviations = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ];
function d3_time_interval(local, step, number) {
function round(date) {
var d0 = local(date), d1 = offset(d0, 1);
return date - d0 < d1 - date ? d0 : d1;
}
function ceil(date) {
step(date = local(new d3_date(date - 1)), 1);
return date;
}
function offset(date, k) {
step(date = new d3_date(+date), k);
return date;
}
function range(t0, t1, dt) {
var time = ceil(t0), times = [];
if (dt > 1) {
while (time < t1) {
if (!(number(time) % dt)) times.push(new Date(+time));
step(time, 1);
}
} else {
while (time < t1) times.push(new Date(+time)), step(time, 1);
}
return times;
}
function range_utc(t0, t1, dt) {
try {
d3_date = d3_date_utc;
var utc = new d3_date_utc();
utc._ = t0;
return range(utc, t1, dt);
} finally {
d3_date = Date;
}
}
local.floor = local;
local.round = round;
local.ceil = ceil;
local.offset = offset;
local.range = range;
var utc = local.utc = d3_time_interval_utc(local);
utc.floor = utc;
utc.round = d3_time_interval_utc(round);
utc.ceil = d3_time_interval_utc(ceil);
utc.offset = d3_time_interval_utc(offset);
utc.range = range_utc;
return local;
}
function d3_time_interval_utc(method) {
return function(date, k) {
try {
d3_date = d3_date_utc;
var utc = new d3_date_utc();
utc._ = date;
return method(utc, k)._;
} finally {
d3_date = Date;
}
};
}
d3_time.year = d3_time_interval(function(date) {
date = d3_time.day(date);
date.setMonth(0, 1);
return date;
}, function(date, offset) {
date.setFullYear(date.getFullYear() + offset);
}, function(date) {
return date.getFullYear();
});
d3_time.years = d3_time.year.range;
d3_time.years.utc = d3_time.year.utc.range;
d3_time.day = d3_time_interval(function(date) {
var day = new d3_date(2e3, 0);
day.setFullYear(date.getFullYear(), date.getMonth(), date.getDate());
return day;
}, function(date, offset) {
date.setDate(date.getDate() + offset);
}, function(date) {
return date.getDate() - 1;
});
d3_time.days = d3_time.day.range;
d3_time.days.utc = d3_time.day.utc.range;
d3_time.dayOfYear = function(date) {
var year = d3_time.year(date);
return Math.floor((date - year - (date.getTimezoneOffset() - year.getTimezoneOffset()) * 6e4) / 864e5);
};
d3_time_daySymbols.forEach(function(day, i) {
day = day.toLowerCase();
i = 7 - i;
var interval = d3_time[day] = d3_time_interval(function(date) {
(date = d3_time.day(date)).setDate(date.getDate() - (date.getDay() + i) % 7);
return date;
}, function(date, offset) {
date.setDate(date.getDate() + Math.floor(offset) * 7);
}, function(date) {
var day = d3_time.year(date).getDay();
return Math.floor((d3_time.dayOfYear(date) + (day + i) % 7) / 7) - (day !== i);
});
d3_time[day + "s"] = interval.range;
d3_time[day + "s"].utc = interval.utc.range;
d3_time[day + "OfYear"] = function(date) {
var day = d3_time.year(date).getDay();
return Math.floor((d3_time.dayOfYear(date) + (day + i) % 7) / 7);
};
});
d3_time.week = d3_time.sunday;
d3_time.weeks = d3_time.sunday.range;
d3_time.weeks.utc = d3_time.sunday.utc.range;
d3_time.weekOfYear = d3_time.sundayOfYear;
d3_time.format = d3_time_format;
function d3_time_format(template) {
var n = template.length;
function format(date) {
var string = [], i = -1, j = 0, c, p, f;
while (++i < n) {
if (template.charCodeAt(i) === 37) {
string.push(template.substring(j, i));
if ((p = d3_time_formatPads[c = template.charAt(++i)]) != null) c = template.charAt(++i);
if (f = d3_time_formats[c]) c = f(date, p == null ? c === "e" ? " " : "0" : p);
string.push(c);
j = i + 1;
}
}
string.push(template.substring(j, i));
return string.join("");
}
format.parse = function(string) {
var d = {
y: 1900,
m: 0,
d: 1,
H: 0,
M: 0,
S: 0,
L: 0,
Z: null
}, i = d3_time_parse(d, template, string, 0);
if (i != string.length) return null;
if ("p" in d) d.H = d.H % 12 + d.p * 12;
var localZ = d.Z != null && d3_date !== d3_date_utc, date = new (localZ ? d3_date_utc : d3_date)();
if ("j" in d) date.setFullYear(d.y, 0, d.j); else if ("w" in d && ("W" in d || "U" in d)) {
date.setFullYear(d.y, 0, 1);
date.setFullYear(d.y, 0, "W" in d ? (d.w + 6) % 7 + d.W * 7 - (date.getDay() + 5) % 7 : d.w + d.U * 7 - (date.getDay() + 6) % 7);
} else date.setFullYear(d.y, d.m, d.d);
date.setHours(d.H + Math.floor(d.Z / 100), d.M + d.Z % 100, d.S, d.L);
return localZ ? date._ : date;
};
format.toString = function() {
return template;
};
return format;
}
function d3_time_parse(date, template, string, j) {
var c, p, t, i = 0, n = template.length, m = string.length;
while (i < n) {
if (j >= m) return -1;
c = template.charCodeAt(i++);
if (c === 37) {
t = template.charAt(i++);
p = d3_time_parsers[t in d3_time_formatPads ? template.charAt(i++) : t];
if (!p || (j = p(date, string, j)) < 0) return -1;
} else if (c != string.charCodeAt(j++)) {
return -1;
}
}
return j;
}
function d3_time_formatRe(names) {
return new RegExp("^(?:" + names.map(d3.requote).join("|") + ")", "i");
}
function d3_time_formatLookup(names) {
var map = new d3_Map(), i = -1, n = names.length;
while (++i < n) map.set(names[i].toLowerCase(), i);
return map;
}
function d3_time_formatPad(value, fill, width) {
var sign = value < 0 ? "-" : "", string = (sign ? -value : value) + "", length = string.length;
return sign + (length < width ? new Array(width - length + 1).join(fill) + string : string);
}
var d3_time_dayRe = d3_time_formatRe(d3_time_days), d3_time_dayLookup = d3_time_formatLookup(d3_time_days), d3_time_dayAbbrevRe = d3_time_formatRe(d3_time_dayAbbreviations), d3_time_dayAbbrevLookup = d3_time_formatLookup(d3_time_dayAbbreviations), d3_time_monthRe = d3_time_formatRe(d3_time_months), d3_time_monthLookup = d3_time_formatLookup(d3_time_months), d3_time_monthAbbrevRe = d3_time_formatRe(d3_time_monthAbbreviations), d3_time_monthAbbrevLookup = d3_time_formatLookup(d3_time_monthAbbreviations), d3_time_percentRe = /^%/;
var d3_time_formatPads = {
"-": "",
_: " ",
"0": "0"
};
var d3_time_formats = {
a: function(d) {
return d3_time_dayAbbreviations[d.getDay()];
},
A: function(d) {
return d3_time_days[d.getDay()];
},
b: function(d) {
return d3_time_monthAbbreviations[d.getMonth()];
},
B: function(d) {
return d3_time_months[d.getMonth()];
},
c: d3_time_format(d3_time_formatDateTime),
d: function(d, p) {
return d3_time_formatPad(d.getDate(), p, 2);
},
e: function(d, p) {
return d3_time_formatPad(d.getDate(), p, 2);
},
H: function(d, p) {
return d3_time_formatPad(d.getHours(), p, 2);
},
I: function(d, p) {
return d3_time_formatPad(d.getHours() % 12 || 12, p, 2);
},
j: function(d, p) {
return d3_time_formatPad(1 + d3_time.dayOfYear(d), p, 3);
},
L: function(d, p) {
return d3_time_formatPad(d.getMilliseconds(), p, 3);
},
m: function(d, p) {
return d3_time_formatPad(d.getMonth() + 1, p, 2);
},
M: function(d, p) {
return d3_time_formatPad(d.getMinutes(), p, 2);
},
p: function(d) {
return d.getHours() >= 12 ? "PM" : "AM";
},
S: function(d, p) {
return d3_time_formatPad(d.getSeconds(), p, 2);
},
U: function(d, p) {
return d3_time_formatPad(d3_time.sundayOfYear(d), p, 2);
},
w: function(d) {
return d.getDay();
},
W: function(d, p) {
return d3_time_formatPad(d3_time.mondayOfYear(d), p, 2);
},
x: d3_time_format(d3_time_formatDate),
X: d3_time_format(d3_time_formatTime),
y: function(d, p) {
return d3_time_formatPad(d.getFullYear() % 100, p, 2);
},
Y: function(d, p) {
return d3_time_formatPad(d.getFullYear() % 1e4, p, 4);
},
Z: d3_time_zone,
"%": function() {
return "%";
}
};
var d3_time_parsers = {
a: d3_time_parseWeekdayAbbrev,
A: d3_time_parseWeekday,
b: d3_time_parseMonthAbbrev,
B: d3_time_parseMonth,
c: d3_time_parseLocaleFull,
d: d3_time_parseDay,
e: d3_time_parseDay,
H: d3_time_parseHour24,
I: d3_time_parseHour24,
j: d3_time_parseDayOfYear,
L: d3_time_parseMilliseconds,
m: d3_time_parseMonthNumber,
M: d3_time_parseMinutes,
p: d3_time_parseAmPm,
S: d3_time_parseSeconds,
U: d3_time_parseWeekNumberSunday,
w: d3_time_parseWeekdayNumber,
W: d3_time_parseWeekNumberMonday,
x: d3_time_parseLocaleDate,
X: d3_time_parseLocaleTime,
y: d3_time_parseYear,
Y: d3_time_parseFullYear,
Z: d3_time_parseZone,
"%": d3_time_parseLiteralPercent
};
function d3_time_parseWeekdayAbbrev(date, string, i) {
d3_time_dayAbbrevRe.lastIndex = 0;
var n = d3_time_dayAbbrevRe.exec(string.substring(i));
return n ? (date.w = d3_time_dayAbbrevLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;
}
function d3_time_parseWeekday(date, string, i) {
d3_time_dayRe.lastIndex = 0;
var n = d3_time_dayRe.exec(string.substring(i));
return n ? (date.w = d3_time_dayLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;
}
function d3_time_parseWeekdayNumber(date, string, i) {
d3_time_numberRe.lastIndex = 0;
var n = d3_time_numberRe.exec(string.substring(i, i + 1));
return n ? (date.w = +n[0], i + n[0].length) : -1;
}
function d3_time_parseWeekNumberSunday(date, string, i) {
d3_time_numberRe.lastIndex = 0;
var n = d3_time_numberRe.exec(string.substring(i));
return n ? (date.U = +n[0], i + n[0].length) : -1;
}
function d3_time_parseWeekNumberMonday(date, string, i) {
d3_time_numberRe.lastIndex = 0;
var n = d3_time_numberRe.exec(string.substring(i));
return n ? (date.W = +n[0], i + n[0].length) : -1;
}
function d3_time_parseMonthAbbrev(date, string, i) {
d3_time_monthAbbrevRe.lastIndex = 0;
var n = d3_time_monthAbbrevRe.exec(string.substring(i));
return n ? (date.m = d3_time_monthAbbrevLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;
}
function d3_time_parseMonth(date, string, i) {
d3_time_monthRe.lastIndex = 0;
var n = d3_time_monthRe.exec(string.substring(i));
return n ? (date.m = d3_time_monthLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;
}
function d3_time_parseLocaleFull(date, string, i) {
return d3_time_parse(date, d3_time_formats.c.toString(), string, i);
}
function d3_time_parseLocaleDate(date, string, i) {
return d3_time_parse(date, d3_time_formats.x.toString(), string, i);
}
function d3_time_parseLocaleTime(date, string, i) {
return d3_time_parse(date, d3_time_formats.X.toString(), string, i);
}
function d3_time_parseFullYear(date, string, i) {
d3_time_numberRe.lastIndex = 0;
var n = d3_time_numberRe.exec(string.substring(i, i + 4));
return n ? (date.y = +n[0], i + n[0].length) : -1;
}
function d3_time_parseYear(date, string, i) {
d3_time_numberRe.lastIndex = 0;
var n = d3_time_numberRe.exec(string.substring(i, i + 2));
return n ? (date.y = d3_time_expandYear(+n[0]), i + n[0].length) : -1;
}
function d3_time_parseZone(date, string, i) {
return /^[+-]\d{4}$/.test(string = string.substring(i, i + 5)) ? (date.Z = +string,
i + 5) : -1;
}
function d3_time_expandYear(d) {
return d + (d > 68 ? 1900 : 2e3);
}
function d3_time_parseMonthNumber(date, string, i) {
d3_time_numberRe.lastIndex = 0;
var n = d3_time_numberRe.exec(string.substring(i, i + 2));
return n ? (date.m = n[0] - 1, i + n[0].length) : -1;
}
function d3_time_parseDay(date, string, i) {
d3_time_numberRe.lastIndex = 0;
var n = d3_time_numberRe.exec(string.substring(i, i + 2));
return n ? (date.d = +n[0], i + n[0].length) : -1;
}
function d3_time_parseDayOfYear(date, string, i) {
d3_time_numberRe.lastIndex = 0;
var n = d3_time_numberRe.exec(string.substring(i, i + 3));
return n ? (date.j = +n[0], i + n[0].length) : -1;
}
function d3_time_parseHour24(date, string, i) {
d3_time_numberRe.lastIndex = 0;
var n = d3_time_numberRe.exec(string.substring(i, i + 2));
return n ? (date.H = +n[0], i + n[0].length) : -1;
}
function d3_time_parseMinutes(date, string, i) {
d3_time_numberRe.lastIndex = 0;
var n = d3_time_numberRe.exec(string.substring(i, i + 2));
return n ? (date.M = +n[0], i + n[0].length) : -1;
}
function d3_time_parseSeconds(date, string, i) {
d3_time_numberRe.lastIndex = 0;
var n = d3_time_numberRe.exec(string.substring(i, i + 2));
return n ? (date.S = +n[0], i + n[0].length) : -1;
}
function d3_time_parseMilliseconds(date, string, i) {
d3_time_numberRe.lastIndex = 0;
var n = d3_time_numberRe.exec(string.substring(i, i + 3));
return n ? (date.L = +n[0], i + n[0].length) : -1;
}
var d3_time_numberRe = /^\s*\d+/;
function d3_time_parseAmPm(date, string, i) {
var n = d3_time_amPmLookup.get(string.substring(i, i += 2).toLowerCase());
return n == null ? -1 : (date.p = n, i);
}
var d3_time_amPmLookup = d3.map({
am: 0,
pm: 1
});
function d3_time_zone(d) {
var z = d.getTimezoneOffset(), zs = z > 0 ? "-" : "+", zh = ~~(abs(z) / 60), zm = abs(z) % 60;
return zs + d3_time_formatPad(zh, "0", 2) + d3_time_formatPad(zm, "0", 2);
}
function d3_time_parseLiteralPercent(date, string, i) {
d3_time_percentRe.lastIndex = 0;
var n = d3_time_percentRe.exec(string.substring(i, i + 1));
return n ? i + n[0].length : -1;
}
d3_time_format.utc = d3_time_formatUtc;
function d3_time_formatUtc(template) {
var local = d3_time_format(template);
function format(date) {
try {
d3_date = d3_date_utc;
var utc = new d3_date();
utc._ = date;
return local(utc);
} finally {
d3_date = Date;
}
}
format.parse = function(string) {
try {
d3_date = d3_date_utc;
var date = local.parse(string);
return date && date._;
} finally {
d3_date = Date;
}
};
format.toString = local.toString;
return format;
}
var d3_time_formatIso = d3_time_formatUtc("%Y-%m-%dT%H:%M:%S.%LZ");
d3_time_format.iso = Date.prototype.toISOString && +new Date("2000-01-01T00:00:00.000Z") ? d3_time_formatIsoNative : d3_time_formatIso;
function d3_time_formatIsoNative(date) {
return date.toISOString();
}
d3_time_formatIsoNative.parse = function(string) {
var date = new Date(string);
return isNaN(date) ? null : date;
};
d3_time_formatIsoNative.toString = d3_time_formatIso.toString;
d3_time.second = d3_time_interval(function(date) {
return new d3_date(Math.floor(date / 1e3) * 1e3);
}, function(date, offset) {
date.setTime(date.getTime() + Math.floor(offset) * 1e3);
}, function(date) {
return date.getSeconds();
});
d3_time.seconds = d3_time.second.range;
d3_time.seconds.utc = d3_time.second.utc.range;
d3_time.minute = d3_time_interval(function(date) {
return new d3_date(Math.floor(date / 6e4) * 6e4);
}, function(date, offset) {
date.setTime(date.getTime() + Math.floor(offset) * 6e4);
}, function(date) {
return date.getMinutes();
});
d3_time.minutes = d3_time.minute.range;
d3_time.minutes.utc = d3_time.minute.utc.range;
d3_time.hour = d3_time_interval(function(date) {
var timezone = date.getTimezoneOffset() / 60;
return new d3_date((Math.floor(date / 36e5 - timezone) + timezone) * 36e5);
}, function(date, offset) {
date.setTime(date.getTime() + Math.floor(offset) * 36e5);
}, function(date) {
return date.getHours();
});
d3_time.hours = d3_time.hour.range;
d3_time.hours.utc = d3_time.hour.utc.range;
d3_time.month = d3_time_interval(function(date) {
date = d3_time.day(date);
date.setDate(1);
return date;
}, function(date, offset) {
date.setMonth(date.getMonth() + offset);
}, function(date) {
return date.getMonth();
});
d3_time.months = d3_time.month.range;
d3_time.months.utc = d3_time.month.utc.range;
function d3_time_scale(linear, methods, format) {
function scale(x) {
return linear(x);
}
scale.invert = function(x) {
return d3_time_scaleDate(linear.invert(x));
};
scale.domain = function(x) {
if (!arguments.length) return linear.domain().map(d3_time_scaleDate);
linear.domain(x);
return scale;
};
function tickMethod(extent, count) {
var span = extent[1] - extent[0], target = span / count, i = d3.bisect(d3_time_scaleSteps, target);
return i == d3_time_scaleSteps.length ? [ methods.year, d3_scale_linearTickRange(extent.map(function(d) {
return d / 31536e6;
}), count)[2] ] : !i ? [ d3_time_scaleMilliseconds, d3_scale_linearTickRange(extent, count)[2] ] : methods[target / d3_time_scaleSteps[i - 1] < d3_time_scaleSteps[i] / target ? i - 1 : i];
}
scale.nice = function(interval, skip) {
var domain = scale.domain(), extent = d3_scaleExtent(domain), method = interval == null ? tickMethod(extent, 10) : typeof interval === "number" && tickMethod(extent, interval);
if (method) interval = method[0], skip = method[1];
function skipped(date) {
return !isNaN(date) && !interval.range(date, d3_time_scaleDate(+date + 1), skip).length;
}
return scale.domain(d3_scale_nice(domain, skip > 1 ? {
floor: function(date) {
while (skipped(date = interval.floor(date))) date = d3_time_scaleDate(date - 1);
return date;
},
ceil: function(date) {
while (skipped(date = interval.ceil(date))) date = d3_time_scaleDate(+date + 1);
return date;
}
} : interval));
};
scale.ticks = function(interval, skip) {
var extent = d3_scaleExtent(scale.domain()), method = interval == null ? tickMethod(extent, 10) : typeof interval === "number" ? tickMethod(extent, interval) : !interval.range && [ {
range: interval
}, skip ];
if (method) interval = method[0], skip = method[1];
return interval.range(extent[0], d3_time_scaleDate(+extent[1] + 1), skip < 1 ? 1 : skip);
};
scale.tickFormat = function() {
return format;
};
scale.copy = function() {
return d3_time_scale(linear.copy(), methods, format);
};
return d3_scale_linearRebind(scale, linear);
}
function d3_time_scaleDate(t) {
return new Date(t);
}
function d3_time_scaleFormat(formats) {
return function(date) {
var i = formats.length - 1, f = formats[i];
while (!f[1](date)) f = formats[--i];
return f[0](date);
};
}
var d3_time_scaleSteps = [ 1e3, 5e3, 15e3, 3e4, 6e4, 3e5, 9e5, 18e5, 36e5, 108e5, 216e5, 432e5, 864e5, 1728e5, 6048e5, 2592e6, 7776e6, 31536e6 ];
var d3_time_scaleLocalMethods = [ [ d3_time.second, 1 ], [ d3_time.second, 5 ], [ d3_time.second, 15 ], [ d3_time.second, 30 ], [ d3_time.minute, 1 ], [ d3_time.minute, 5 ], [ d3_time.minute, 15 ], [ d3_time.minute, 30 ], [ d3_time.hour, 1 ], [ d3_time.hour, 3 ], [ d3_time.hour, 6 ], [ d3_time.hour, 12 ], [ d3_time.day, 1 ], [ d3_time.day, 2 ], [ d3_time.week, 1 ], [ d3_time.month, 1 ], [ d3_time.month, 3 ], [ d3_time.year, 1 ] ];
var d3_time_scaleLocalFormats = [ [ d3_time_format("%Y"), d3_true ], [ d3_time_format("%B"), function(d) {
return d.getMonth();
} ], [ d3_time_format("%b %d"), function(d) {
return d.getDate() != 1;
} ], [ d3_time_format("%a %d"), function(d) {
return d.getDay() && d.getDate() != 1;
} ], [ d3_time_format("%I %p"), function(d) {
return d.getHours();
} ], [ d3_time_format("%I:%M"), function(d) {
return d.getMinutes();
} ], [ d3_time_format(":%S"), function(d) {
return d.getSeconds();
} ], [ d3_time_format(".%L"), function(d) {
return d.getMilliseconds();
} ] ];
var d3_time_scaleLocalFormat = d3_time_scaleFormat(d3_time_scaleLocalFormats);
d3_time_scaleLocalMethods.year = d3_time.year;
d3_time.scale = function() {
return d3_time_scale(d3.scale.linear(), d3_time_scaleLocalMethods, d3_time_scaleLocalFormat);
};
var d3_time_scaleMilliseconds = {
range: function(start, stop, step) {
return d3.range(+start, +stop, step).map(d3_time_scaleDate);
}
};
var d3_time_scaleUTCMethods = d3_time_scaleLocalMethods.map(function(m) {
return [ m[0].utc, m[1] ];
});
var d3_time_scaleUTCFormats = [ [ d3_time_formatUtc("%Y"), d3_true ], [ d3_time_formatUtc("%B"), function(d) {
return d.getUTCMonth();
} ], [ d3_time_formatUtc("%b %d"), function(d) {
return d.getUTCDate() != 1;
} ], [ d3_time_formatUtc("%a %d"), function(d) {
return d.getUTCDay() && d.getUTCDate() != 1;
} ], [ d3_time_formatUtc("%I %p"), function(d) {
return d.getUTCHours();
} ], [ d3_time_formatUtc("%I:%M"), function(d) {
return d.getUTCMinutes();
} ], [ d3_time_formatUtc(":%S"), function(d) {
return d.getUTCSeconds();
} ], [ d3_time_formatUtc(".%L"), function(d) {
return d.getUTCMilliseconds();
} ] ];
var d3_time_scaleUTCFormat = d3_time_scaleFormat(d3_time_scaleUTCFormats);
d3_time_scaleUTCMethods.year = d3_time.year.utc;
d3_time.scale.utc = function() {
return d3_time_scale(d3.scale.linear(), d3_time_scaleUTCMethods, d3_time_scaleUTCFormat);
};
d3.text = d3_xhrType(function(request) {
return request.responseText;
});
d3.json = function(url, callback) {
return d3_xhr(url, "application/json", d3_json, callback);
};
function d3_json(request) {
return JSON.parse(request.responseText);
}
d3.html = function(url, callback) {
return d3_xhr(url, "text/html", d3_html, callback);
};
function d3_html(request) {
var range = d3_document.createRange();
range.selectNode(d3_document.body);
return range.createContextualFragment(request.responseText);
}
d3.xml = d3_xhrType(function(request) {
return request.responseXML;
});
return d3;
}();
/*!
* jQuery UI Mouse 1.10.3
* http://jqueryui.com
*
* Copyright 2013 jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*
* http://api.jqueryui.com/mouse/
*
* Depends:
* jquery.ui.widget.js
*/
(function( $, undefined ) {
var mouseHandled = false;
$( document ).mouseup( function() {
mouseHandled = false;
});
$.widget("ui.mouse", {
version: "1.10.3",
options: {
cancel: "input,textarea,button,select,option",
distance: 1,
delay: 0
},
_mouseInit: function() {
var that = this;
this.element
.bind("mousedown."+this.widgetName, function(event) {
return that._mouseDown(event);
})
.bind("click."+this.widgetName, function(event) {
if (true === $.data(event.target, that.widgetName + ".preventClickEvent")) {
$.removeData(event.target, that.widgetName + ".preventClickEvent");
event.stopImmediatePropagation();
return false;
}
});
this.started = false;
},
// TODO: make sure destroying one instance of mouse doesn't mess with
// other instances of mouse
_mouseDestroy: function() {
this.element.unbind("."+this.widgetName);
if ( this._mouseMoveDelegate ) {
$(document)
.unbind("mousemove."+this.widgetName, this._mouseMoveDelegate)
.unbind("mouseup."+this.widgetName, this._mouseUpDelegate);
}
},
_mouseDown: function(event) {
// don't let more than one widget handle mouseStart
if( mouseHandled ) { return; }
// we may have missed mouseup (out of window)
(this._mouseStarted && this._mouseUp(event));
this._mouseDownEvent = event;
var that = this,
btnIsLeft = (event.which === 1),
// event.target.nodeName works around a bug in IE 8 with
// disabled inputs (#7620)
elIsCancel = (typeof this.options.cancel === "string" && event.target.nodeName ? $(event.target).closest(this.options.cancel).length : false);
if (!btnIsLeft || elIsCancel || !this._mouseCapture(event)) {
return true;
}
this.mouseDelayMet = !this.options.delay;
if (!this.mouseDelayMet) {
this._mouseDelayTimer = setTimeout(function() {
that.mouseDelayMet = true;
}, this.options.delay);
}
if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
this._mouseStarted = (this._mouseStart(event) !== false);
if (!this._mouseStarted) {
event.preventDefault();
return true;
}
}
// Click event may never have fired (Gecko & Opera)
if (true === $.data(event.target, this.widgetName + ".preventClickEvent")) {
$.removeData(event.target, this.widgetName + ".preventClickEvent");
}
// these delegates are required to keep context
this._mouseMoveDelegate = function(event) {
return that._mouseMove(event);
};
this._mouseUpDelegate = function(event) {
return that._mouseUp(event);
};
$(document)
.bind("mousemove."+this.widgetName, this._mouseMoveDelegate)
.bind("mouseup."+this.widgetName, this._mouseUpDelegate);
event.preventDefault();
mouseHandled = true;
return true;
},
_mouseMove: function(event) {
// IE mouseup check - mouseup happened when mouse was out of window
if ($.ui.ie && ( !document.documentMode || document.documentMode < 9 ) && !event.button) {
return this._mouseUp(event);
}
if (this._mouseStarted) {
this._mouseDrag(event);
return event.preventDefault();
}
if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
this._mouseStarted =
(this._mouseStart(this._mouseDownEvent, event) !== false);
(this._mouseStarted ? this._mouseDrag(event) : this._mouseUp(event));
}
return !this._mouseStarted;
},
_mouseUp: function(event) {
$(document)
.unbind("mousemove."+this.widgetName, this._mouseMoveDelegate)
.unbind("mouseup."+this.widgetName, this._mouseUpDelegate);
if (this._mouseStarted) {
this._mouseStarted = false;
if (event.target === this._mouseDownEvent.target) {
$.data(event.target, this.widgetName + ".preventClickEvent", true);
}
this._mouseStop(event);
}
return false;
},
_mouseDistanceMet: function(event) {
return (Math.max(
Math.abs(this._mouseDownEvent.pageX - event.pageX),
Math.abs(this._mouseDownEvent.pageY - event.pageY)
) >= this.options.distance
);
},
_mouseDelayMet: function(/* event */) {
return this.mouseDelayMet;
},
// These are placeholder methods, to be overriden by extending plugin
_mouseStart: function(/* event */) {},
_mouseDrag: function(/* event */) {},
_mouseStop: function(/* event */) {},
_mouseCapture: function(/* event */) { return true; }
});
})(jQuery);
/*!
* jQuery UI Position 1.10.3
* http://jqueryui.com
*
* Copyright 2013 jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*
* http://api.jqueryui.com/position/
*/
(function( $, undefined ) {
$.ui = $.ui || {};
var cachedScrollbarWidth,
max = Math.max,
abs = Math.abs,
round = Math.round,
rhorizontal = /left|center|right/,
rvertical = /top|center|bottom/,
roffset = /[\+\-]\d+(\.[\d]+)?%?/,
rposition = /^\w+/,
rpercent = /%$/,
_position = $.fn.position;
function getOffsets( offsets, width, height ) {
return [
parseFloat( offsets[ 0 ] ) * ( rpercent.test( offsets[ 0 ] ) ? width / 100 : 1 ),
parseFloat( offsets[ 1 ] ) * ( rpercent.test( offsets[ 1 ] ) ? height / 100 : 1 )
];
}
function parseCss( element, property ) {
return parseInt( $.css( element, property ), 10 ) || 0;
}
function getDimensions( elem ) {
var raw = elem[0];
if ( raw.nodeType === 9 ) {
return {
width: elem.width(),
height: elem.height(),
offset: { top: 0, left: 0 }
};
}
if ( $.isWindow( raw ) ) {
return {
width: elem.width(),
height: elem.height(),
offset: { top: elem.scrollTop(), left: elem.scrollLeft() }
};
}
if ( raw.preventDefault ) {
return {
width: 0,
height: 0,
offset: { top: raw.pageY, left: raw.pageX }
};
}
return {
width: elem.outerWidth(),
height: elem.outerHeight(),
offset: elem.offset()
};
}
$.position = {
scrollbarWidth: function() {
if ( cachedScrollbarWidth !== undefined ) {
return cachedScrollbarWidth;
}
var w1, w2,
div = $( "<div style='display:block;width:50px;height:50px;overflow:hidden;'><div style='height:100px;width:auto;'></div></div>" ),
innerDiv = div.children()[0];
$( "body" ).append( div );
w1 = innerDiv.offsetWidth;
div.css( "overflow", "scroll" );
w2 = innerDiv.offsetWidth;
if ( w1 === w2 ) {
w2 = div[0].clientWidth;
}
div.remove();
return (cachedScrollbarWidth = w1 - w2);
},
getScrollInfo: function( within ) {
var overflowX = within.isWindow ? "" : within.element.css( "overflow-x" ),
overflowY = within.isWindow ? "" : within.element.css( "overflow-y" ),
hasOverflowX = overflowX === "scroll" ||
( overflowX === "auto" && within.width < within.element[0].scrollWidth ),
hasOverflowY = overflowY === "scroll" ||
( overflowY === "auto" && within.height < within.element[0].scrollHeight );
return {
width: hasOverflowY ? $.position.scrollbarWidth() : 0,
height: hasOverflowX ? $.position.scrollbarWidth() : 0
};
},
getWithinInfo: function( element ) {
var withinElement = $( element || window ),
isWindow = $.isWindow( withinElement[0] );
return {
element: withinElement,
isWindow: isWindow,
offset: withinElement.offset() || { left: 0, top: 0 },
scrollLeft: withinElement.scrollLeft(),
scrollTop: withinElement.scrollTop(),
width: isWindow ? withinElement.width() : withinElement.outerWidth(),
height: isWindow ? withinElement.height() : withinElement.outerHeight()
};
}
};
$.fn.position = function( options ) {
if ( !options || !options.of ) {
return _position.apply( this, arguments );
}
// make a copy, we don't want to modify arguments
options = $.extend( {}, options );
var atOffset, targetWidth, targetHeight, targetOffset, basePosition, dimensions,
target = $( options.of ),
within = $.position.getWithinInfo( options.within ),
scrollInfo = $.position.getScrollInfo( within ),
collision = ( options.collision || "flip" ).split( " " ),
offsets = {};
dimensions = getDimensions( target );
if ( target[0].preventDefault ) {
// force left top to allow flipping
options.at = "left top";
}
targetWidth = dimensions.width;
targetHeight = dimensions.height;
targetOffset = dimensions.offset;
// clone to reuse original targetOffset later
basePosition = $.extend( {}, targetOffset );
// force my and at to have valid horizontal and vertical positions
// if a value is missing or invalid, it will be converted to center
$.each( [ "my", "at" ], function() {
var pos = ( options[ this ] || "" ).split( " " ),
horizontalOffset,
verticalOffset;
if ( pos.length === 1) {
pos = rhorizontal.test( pos[ 0 ] ) ?
pos.concat( [ "center" ] ) :
rvertical.test( pos[ 0 ] ) ?
[ "center" ].concat( pos ) :
[ "center", "center" ];
}
pos[ 0 ] = rhorizontal.test( pos[ 0 ] ) ? pos[ 0 ] : "center";
pos[ 1 ] = rvertical.test( pos[ 1 ] ) ? pos[ 1 ] : "center";
// calculate offsets
horizontalOffset = roffset.exec( pos[ 0 ] );
verticalOffset = roffset.exec( pos[ 1 ] );
offsets[ this ] = [
horizontalOffset ? horizontalOffset[ 0 ] : 0,
verticalOffset ? verticalOffset[ 0 ] : 0
];
// reduce to just the positions without the offsets
options[ this ] = [
rposition.exec( pos[ 0 ] )[ 0 ],
rposition.exec( pos[ 1 ] )[ 0 ]
];
});
// normalize collision option
if ( collision.length === 1 ) {
collision[ 1 ] = collision[ 0 ];
}
if ( options.at[ 0 ] === "right" ) {
basePosition.left += targetWidth;
} else if ( options.at[ 0 ] === "center" ) {
basePosition.left += targetWidth / 2;
}
if ( options.at[ 1 ] === "bottom" ) {
basePosition.top += targetHeight;
} else if ( options.at[ 1 ] === "center" ) {
basePosition.top += targetHeight / 2;
}
atOffset = getOffsets( offsets.at, targetWidth, targetHeight );
basePosition.left += atOffset[ 0 ];
basePosition.top += atOffset[ 1 ];
return this.each(function() {
var collisionPosition, using,
elem = $( this ),
elemWidth = elem.outerWidth(),
elemHeight = elem.outerHeight(),
marginLeft = parseCss( this, "marginLeft" ),
marginTop = parseCss( this, "marginTop" ),
collisionWidth = elemWidth + marginLeft + parseCss( this, "marginRight" ) + scrollInfo.width,
collisionHeight = elemHeight + marginTop + parseCss( this, "marginBottom" ) + scrollInfo.height,
position = $.extend( {}, basePosition ),
myOffset = getOffsets( offsets.my, elem.outerWidth(), elem.outerHeight() );
if ( options.my[ 0 ] === "right" ) {
position.left -= elemWidth;
} else if ( options.my[ 0 ] === "center" ) {
position.left -= elemWidth / 2;
}
if ( options.my[ 1 ] === "bottom" ) {
position.top -= elemHeight;
} else if ( options.my[ 1 ] === "center" ) {
position.top -= elemHeight / 2;
}
position.left += myOffset[ 0 ];
position.top += myOffset[ 1 ];
// if the browser doesn't support fractions, then round for consistent results
if ( !$.support.offsetFractions ) {
position.left = round( position.left );
position.top = round( position.top );
}
collisionPosition = {
marginLeft: marginLeft,
marginTop: marginTop
};
$.each( [ "left", "top" ], function( i, dir ) {
if ( $.ui.position[ collision[ i ] ] ) {
$.ui.position[ collision[ i ] ][ dir ]( position, {
targetWidth: targetWidth,
targetHeight: targetHeight,
elemWidth: elemWidth,
elemHeight: elemHeight,
collisionPosition: collisionPosition,
collisionWidth: collisionWidth,
collisionHeight: collisionHeight,
offset: [ atOffset[ 0 ] + myOffset[ 0 ], atOffset [ 1 ] + myOffset[ 1 ] ],
my: options.my,
at: options.at,
within: within,
elem : elem
});
}
});
if ( options.using ) {
// adds feedback as second argument to using callback, if present
using = function( props ) {
var left = targetOffset.left - position.left,
right = left + targetWidth - elemWidth,
top = targetOffset.top - position.top,
bottom = top + targetHeight - elemHeight,
feedback = {
target: {
element: target,
left: targetOffset.left,
top: targetOffset.top,
width: targetWidth,
height: targetHeight
},
element: {
element: elem,
left: position.left,
top: position.top,
width: elemWidth,
height: elemHeight
},
horizontal: right < 0 ? "left" : left > 0 ? "right" : "center",
vertical: bottom < 0 ? "top" : top > 0 ? "bottom" : "middle"
};
if ( targetWidth < elemWidth && abs( left + right ) < targetWidth ) {
feedback.horizontal = "center";
}
if ( targetHeight < elemHeight && abs( top + bottom ) < targetHeight ) {
feedback.vertical = "middle";
}
if ( max( abs( left ), abs( right ) ) > max( abs( top ), abs( bottom ) ) ) {
feedback.important = "horizontal";
} else {
feedback.important = "vertical";
}
options.using.call( this, props, feedback );
};
}
elem.offset( $.extend( position, { using: using } ) );
});
};
$.ui.position = {
fit: {
left: function( position, data ) {
var within = data.within,
withinOffset = within.isWindow ? within.scrollLeft : within.offset.left,
outerWidth = within.width,
collisionPosLeft = position.left - data.collisionPosition.marginLeft,
overLeft = withinOffset - collisionPosLeft,
overRight = collisionPosLeft + data.collisionWidth - outerWidth - withinOffset,
newOverRight;
// element is wider than within
if ( data.collisionWidth > outerWidth ) {
// element is initially over the left side of within
if ( overLeft > 0 && overRight <= 0 ) {
newOverRight = position.left + overLeft + data.collisionWidth - outerWidth - withinOffset;
position.left += overLeft - newOverRight;
// element is initially over right side of within
} else if ( overRight > 0 && overLeft <= 0 ) {
position.left = withinOffset;
// element is initially over both left and right sides of within
} else {
if ( overLeft > overRight ) {
position.left = withinOffset + outerWidth - data.collisionWidth;
} else {
position.left = withinOffset;
}
}
// too far left -> align with left edge
} else if ( overLeft > 0 ) {
position.left += overLeft;
// too far right -> align with right edge
} else if ( overRight > 0 ) {
position.left -= overRight;
// adjust based on position and margin
} else {
position.left = max( position.left - collisionPosLeft, position.left );
}
},
top: function( position, data ) {
var within = data.within,
withinOffset = within.isWindow ? within.scrollTop : within.offset.top,
outerHeight = data.within.height,
collisionPosTop = position.top - data.collisionPosition.marginTop,
overTop = withinOffset - collisionPosTop,
overBottom = collisionPosTop + data.collisionHeight - outerHeight - withinOffset,
newOverBottom;
// element is taller than within
if ( data.collisionHeight > outerHeight ) {
// element is initially over the top of within
if ( overTop > 0 && overBottom <= 0 ) {
newOverBottom = position.top + overTop + data.collisionHeight - outerHeight - withinOffset;
position.top += overTop - newOverBottom;
// element is initially over bottom of within
} else if ( overBottom > 0 && overTop <= 0 ) {
position.top = withinOffset;
// element is initially over both top and bottom of within
} else {
if ( overTop > overBottom ) {
position.top = withinOffset + outerHeight - data.collisionHeight;
} else {
position.top = withinOffset;
}
}
// too far up -> align with top
} else if ( overTop > 0 ) {
position.top += overTop;
// too far down -> align with bottom edge
} else if ( overBottom > 0 ) {
position.top -= overBottom;
// adjust based on position and margin
} else {
position.top = max( position.top - collisionPosTop, position.top );
}
}
},
flip: {
left: function( position, data ) {
var within = data.within,
withinOffset = within.offset.left + within.scrollLeft,
outerWidth = within.width,
offsetLeft = within.isWindow ? within.scrollLeft : within.offset.left,
collisionPosLeft = position.left - data.collisionPosition.marginLeft,
overLeft = collisionPosLeft - offsetLeft,
overRight = collisionPosLeft + data.collisionWidth - outerWidth - offsetLeft,
myOffset = data.my[ 0 ] === "left" ?
-data.elemWidth :
data.my[ 0 ] === "right" ?
data.elemWidth :
0,
atOffset = data.at[ 0 ] === "left" ?
data.targetWidth :
data.at[ 0 ] === "right" ?
-data.targetWidth :
0,
offset = -2 * data.offset[ 0 ],
newOverRight,
newOverLeft;
if ( overLeft < 0 ) {
newOverRight = position.left + myOffset + atOffset + offset + data.collisionWidth - outerWidth - withinOffset;
if ( newOverRight < 0 || newOverRight < abs( overLeft ) ) {
position.left += myOffset + atOffset + offset;
}
}
else if ( overRight > 0 ) {
newOverLeft = position.left - data.collisionPosition.marginLeft + myOffset + atOffset + offset - offsetLeft;
if ( newOverLeft > 0 || abs( newOverLeft ) < overRight ) {
position.left += myOffset + atOffset + offset;
}
}
},
top: function( position, data ) {
var within = data.within,
withinOffset = within.offset.top + within.scrollTop,
outerHeight = within.height,
offsetTop = within.isWindow ? within.scrollTop : within.offset.top,
collisionPosTop = position.top - data.collisionPosition.marginTop,
overTop = collisionPosTop - offsetTop,
overBottom = collisionPosTop + data.collisionHeight - outerHeight - offsetTop,
top = data.my[ 1 ] === "top",
myOffset = top ?
-data.elemHeight :
data.my[ 1 ] === "bottom" ?
data.elemHeight :
0,
atOffset = data.at[ 1 ] === "top" ?
data.targetHeight :
data.at[ 1 ] === "bottom" ?
-data.targetHeight :
0,
offset = -2 * data.offset[ 1 ],
newOverTop,
newOverBottom;
if ( overTop < 0 ) {
newOverBottom = position.top + myOffset + atOffset + offset + data.collisionHeight - outerHeight - withinOffset;
if ( ( position.top + myOffset + atOffset + offset) > overTop && ( newOverBottom < 0 || newOverBottom < abs( overTop ) ) ) {
position.top += myOffset + atOffset + offset;
}
}
else if ( overBottom > 0 ) {
newOverTop = position.top - data.collisionPosition.marginTop + myOffset + atOffset + offset - offsetTop;
if ( ( position.top + myOffset + atOffset + offset) > overBottom && ( newOverTop > 0 || abs( newOverTop ) < overBottom ) ) {
position.top += myOffset + atOffset + offset;
}
}
}
},
flipfit: {
left: function() {
$.ui.position.flip.left.apply( this, arguments );
$.ui.position.fit.left.apply( this, arguments );
},
top: function() {
$.ui.position.flip.top.apply( this, arguments );
$.ui.position.fit.top.apply( this, arguments );
}
}
};
// fraction support test
(function () {
var testElement, testElementParent, testElementStyle, offsetLeft, i,
body = document.getElementsByTagName( "body" )[ 0 ],
div = document.createElement( "div" );
//Create a "fake body" for testing based on method used in jQuery.support
testElement = document.createElement( body ? "div" : "body" );
testElementStyle = {
visibility: "hidden",
width: 0,
height: 0,
border: 0,
margin: 0,
background: "none"
};
if ( body ) {
$.extend( testElementStyle, {
position: "absolute",
left: "-1000px",
top: "-1000px"
});
}
for ( i in testElementStyle ) {
testElement.style[ i ] = testElementStyle[ i ];
}
testElement.appendChild( div );
testElementParent = body || document.documentElement;
testElementParent.insertBefore( testElement, testElementParent.firstChild );
div.style.cssText = "position: absolute; left: 10.7432222px;";
offsetLeft = $( div ).offset().left;
$.support.offsetFractions = offsetLeft > 10 && offsetLeft < 11;
testElement.innerHTML = "";
testElementParent.removeChild( testElement );
})();
}( jQuery ) );
/*!
* jQuery UI Touch Punch 0.2.2
*
* Copyright 2011, Dave Furfero
* Dual licensed under the MIT or GPL Version 2 licenses.
*
* Depends:
* jquery.ui.widget.js
* jquery.ui.mouse.js
*/
(function ($) {
// Detect touch support
$.support.touch = 'ontouchend' in document;
// Ignore browsers without touch support
if (!$.support.touch) {
return;
}
var mouseProto = $.ui.mouse.prototype,
_mouseInit = mouseProto._mouseInit,
touchHandled;
/**
* Simulate a mouse event based on a corresponding touch event
* @param {Object} event A touch event
* @param {String} simulatedType The corresponding mouse event
*/
function simulateMouseEvent (event, simulatedType) {
// Ignore multi-touch events
if (event.originalEvent.touches.length > 1) {
return;
}
event.preventDefault();
var touch = event.originalEvent.changedTouches[0],
simulatedEvent = document.createEvent('MouseEvents');
// Initialize the simulated mouse event using the touch event's coordinates
simulatedEvent.initMouseEvent(
simulatedType, // type
true, // bubbles
true, // cancelable
window, // view
1, // detail
touch.screenX, // screenX
touch.screenY, // screenY
touch.clientX, // clientX
touch.clientY, // clientY
false, // ctrlKey
false, // altKey
false, // shiftKey
false, // metaKey
0, // button
null // relatedTarget
);
// Dispatch the simulated event to the target element
event.target.dispatchEvent(simulatedEvent);
}
/**
* Handle the jQuery UI widget's touchstart events
* @param {Object} event The widget element's touchstart event
*/
mouseProto._touchStart = function (event) {
var self = this;
// Ignore the event if another widget is already being handled
if (touchHandled || !self._mouseCapture(event.originalEvent.changedTouches[0])) {
return;
}
// Set the flag to prevent other widgets from inheriting the touch event
touchHandled = true;
// Track movement to determine if interaction was a click
self._touchMoved = false;
// Simulate the mouseover event
simulateMouseEvent(event, 'mouseover');
// Simulate the mousemove event
simulateMouseEvent(event, 'mousemove');
// Simulate the mousedown event
simulateMouseEvent(event, 'mousedown');
};
/**
* Handle the jQuery UI widget's touchmove events
* @param {Object} event The document's touchmove event
*/
mouseProto._touchMove = function (event) {
// Ignore event if not handled
if (!touchHandled) {
return;
}
// Interaction was not a click
this._touchMoved = true;
// Simulate the mousemove event
simulateMouseEvent(event, 'mousemove');
};
/**
* Handle the jQuery UI widget's touchend events
* @param {Object} event The document's touchend event
*/
mouseProto._touchEnd = function (event) {
// Ignore event if not handled
if (!touchHandled) {
return;
}
// Simulate the mouseup event
simulateMouseEvent(event, 'mouseup');
// Simulate the mouseout event
simulateMouseEvent(event, 'mouseout');
// If the touch interaction did not move, it should trigger a click
if (!this._touchMoved) {
// Simulate the click event
simulateMouseEvent(event, 'click');
}
// Unset the flag to allow other widgets to inherit the touch event
touchHandled = false;
};
/**
* A duck punch of the $.ui.mouse _mouseInit method to support touch events.
* This method extends the widget with bound touch event handlers that
* translate touch events to mouse events and pass them to the widget's
* original mouse event handling methods.
*/
mouseProto._mouseInit = function () {
var self = this;
// Delegate the touch handlers to the widget's element
self.element
.bind('touchstart', $.proxy(self, '_touchStart'))
.bind('touchmove', $.proxy(self, '_touchMove'))
.bind('touchend', $.proxy(self, '_touchEnd'));
// Call the original $.ui.mouse init method
_mouseInit.call(self);
};
})(jQuery);
/*!
* jQuery Cookie Plugin v1.3.1
* https://github.com/carhartl/jquery-cookie
*
* Copyright 2013 Klaus Hartl
* Released under the MIT license
*/
(function (factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as anonymous module.
define(['jquery'], factory);
} else {
// Browser globals.
factory(jQuery);
}
}(function ($) {
var pluses = /\+/g;
function raw(s) {
return s;
}
function decoded(s) {
return decodeURIComponent(s.replace(pluses, ' '));
}
function converted(s) {
if (s.indexOf('"') === 0) {
// This is a quoted cookie as according to RFC2068, unescape
s = s.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\');
}
try {
return config.json ? JSON.parse(s) : s;
} catch(er) {}
}
var config = $.cookie = function (key, value, options) {
// write
if (value !== undefined) {
options = $.extend({}, config.defaults, options);
if (typeof options.expires === 'number') {
var days = options.expires, t = options.expires = new Date();
t.setDate(t.getDate() + days);
}
value = config.json ? JSON.stringify(value) : String(value);
return (document.cookie = [
config.raw ? key : encodeURIComponent(key),
'=',
config.raw ? value : encodeURIComponent(value),
options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
options.path ? '; path=' + options.path : '',
options.domain ? '; domain=' + options.domain : '',
options.secure ? '; secure' : ''
].join(''));
}
// read
var decode = config.raw ? raw : decoded;
var cookies = document.cookie.split('; ');
var result = key ? undefined : {};
for (var i = 0, l = cookies.length; i < l; i++) {
var parts = cookies[i].split('=');
var name = decode(parts.shift());
var cookie = decode(parts.join('='));
if (key && key === name) {
result = converted(cookie);
break;
}
if (!key) {
result[name] = converted(cookie);
}
}
return result;
};
config.defaults = {};
$.removeCookie = function (key, options) {
if ($.cookie(key) !== undefined) {
// Must not alter options, thus extending a fresh object...
$.cookie(key, '', $.extend({}, options, { expires: -1 }));
return true;
}
return false;
};
}));
|
/*jslint white:true, plusplus:true, nomen:true, vars:true, browser:true */
/*global buster, sinon, wooga */
var assert = buster.assertions.assert;
var refute = buster.assertions.refute;
(function() {
"use strict";
buster.testCase("Spawner test case", {
setUp: function() {
this.game = {
entities: [],
createEntity: function(config) {
this.entities.push({
definition: {
"class": "enemy"
},
key: config.key
});
},
removeEntity: function(entity) {
this.entities.splice(this.entities.indexOf(entity), 1);
}
};
this.view = {
views: [],
createEntityView: function(entity) {
this.views.push({entity: entity});
return {
findNewPosition: function() {
return true;
},
invalidatePosition: function() {}
};
},
removeEntityView: function(view) {
this.views.splice(this.views.indexOf(view), 1);
}
};
this.spawner = new wooga.castle.Spawner(this.game, this.view);
},
tearDown: function() {},
"test spawn creates a new entity and view": function() {
this.spawner.spawn("godzilla");
this.spawner.spawn("borg");
this.spawner.spawn("jar jar binks");
assert.equals(this.game.entities.length, 3);
assert.equals(this.view.views.length, 3);
},
"test getAllowedEnemies returns a difference between expected and existing number of enemies": function() {
this.spawner.spawnRandomEnemies(5);
assert.equals(this.spawner.getAllowedEnemies(12), 7);
assert.equals(this.spawner.getAllowedEnemies(3), 0);
},
"test spawnRandomEnemies creates a given number of random enemies": function() {
this.spawner.spawnRandomEnemies(100);
var trolls = this.game.entities.filter(function(enemy) {
return enemy.key.indexOf("troll") > -1;
});
var goblins = this.game.entities.filter(function(enemy) {
return enemy.key.indexOf("goblins") > -1;
});
var giants = this.game.entities.filter(function(enemy) {
return enemy.key.indexOf("giant") > -1;
});
assert(trolls.length);
assert(goblins.length);
assert(giants.length);
}
});
}());
|
$(function () {
function pageLoad() {
removeActiveClass();
}
function removeActiveClass() {
$('.nav-tabs').on('shown.bs.tab', 'a', function (e) {
if (e.relatedTarget) {
$(e.relatedTarget).removeClass('active');
}
});
}
pageLoad();
SingApp.onPageLoad(pageLoad);
}); |
//>>built
define({doNew:"[novo]",edit:"[uredi]",save:"[sa\u010duvaj]",cancel:"[otka\u017ei]"}); |
var BlocktrailSDK = require('../api_client');
var _ = require('lodash');
var q = require('q');
var async = require('async');
/**
*
* @param options
* @constructor
*/
var BlocktrailBitcoinService = function(options) {
this.defaultSettings = {
apiKey: null,
apiSecret: null,
network: 'BTC',
testnet: false,
retryLimit: 5,
retryDelay: 20,
paginationLimit: 200 //max records to return per page
};
this.settings = _.merge({}, this.defaultSettings, options);
//normalise the network settings
var networkSettings = this.normaliseNetwork(this.settings.network, this.settings.testnet);
this.settings.network = networkSettings.network;
this.settings.testnet = networkSettings.testnet;
this.client = new BlocktrailSDK(this.settings);
};
BlocktrailBitcoinService.prototype.normaliseNetwork = function(network, testnet) {
switch (network.toLowerCase()) {
case 'btc':
case 'bitcoin':
if (testnet) {
return {network: "BTC", testnet: true};
} else {
return {network: "BTC", testnet: false};
}
break;
case 'tbtc':
case 'bitcoin-testnet':
return {network: "BTC", testnet: true};
case 'bcc':
if (testnet) {
return {network: "BCC", testnet: true};
} else {
return {network: "BCC", testnet: false};
}
break;
case 'tbcc':
return {network: "BCC", testnet: true};
default:
throw new Error("Unknown network " + network);
}
};
BlocktrailBitcoinService.prototype.setPaginationLimit = function(limit) {
this.settings.paginationLimit = limit;
};
BlocktrailBitcoinService.prototype.estimateFee = function() {
var self = this;
return self.client.feePerKB().then(function(r) {
return Math.max(r['optimal'], r['min_relay_fee']);
});
};
/**
* gets unspent outputs for a batch of addresses, returning an array of outputs with hash, index,
* value, and script pub hex mapped to each corresponding address
*
* @param {array} addresses array of addresses
* @returns {q.Promise} promise resolves with array of unspent outputs mapped to addresses as
* { address: [{"hash": hash, "index": index, "value": value, "script_hex": scriptHex}]}
*/
BlocktrailBitcoinService.prototype.getBatchUnspentOutputs = function(addresses) {
var self = this;
var deferred = q.defer();
var page = 1;
var results = null;
var utxos = [];
//get unspent outputs for the current chunk of addresses - required data: hash, index, value, and script hex,
async.doWhilst(function(done) {
//do
var params = {
page: page,
limit: self.settings.paginationLimit
};
self.client.batchAddressUnspentOutputs(addresses, params).then(function(results) {
utxos = utxos.concat(results['data']);
page++;
done();
}, function(err) {
console.log('error happened:', err);
done(err);
});
}, function() {
//while
return results && results['data'].length > 0;
}, function(err) {
//all done
if (err) {
console.log("complete, but with errors", err.message);
}
var batchResults = {}; //utxos mapped to addresses
//reduce the returned data into the values we're interested in, and map to the relevant addresses
utxos.forEach(function(utxo) {
var address = utxo['address'];
if (typeof batchResults[address] === "undefined") {
batchResults[address] = [];
}
batchResults[address].push({
'hash': utxo['hash'],
'index': utxo['index'],
'value': utxo['value'],
'script_hex': utxo['script_hex']
});
});
deferred.resolve(batchResults);
});
return deferred.promise;
};
/**
* @param {array} addresses array of addresses
* @returns {q.Promise}
*/
BlocktrailBitcoinService.prototype.batchAddressHasTransactions = function(addresses) {
var self = this;
return self.client.batchAddressHasTransactions(addresses)
.then(function(result) {
return result.has_transactions;
});
};
module.exports = BlocktrailBitcoinService;
|
import Vue from 'vue';
import headerComponent from '~/vue_merge_request_widget/components/mr_widget_header';
const createComponent = (mr) => {
const Component = Vue.extend(headerComponent);
return new Component({
el: document.createElement('div'),
propsData: { mr },
});
};
describe('MRWidgetHeader', () => {
describe('props', () => {
it('should have props', () => {
const { mr } = headerComponent.props;
expect(mr.type instanceof Object).toBeTruthy();
expect(mr.required).toBeTruthy();
});
});
describe('computed', () => {
let vm;
beforeEach(() => {
vm = createComponent({
divergedCommitsCount: 12,
sourceBranch: 'mr-widget-refactor',
sourceBranchLink: '/foo/bar/mr-widget-refactor',
targetBranch: 'master',
});
});
it('shouldShowCommitsBehindText', () => {
expect(vm.shouldShowCommitsBehindText).toBeTruthy();
vm.mr.divergedCommitsCount = 0;
expect(vm.shouldShowCommitsBehindText).toBeFalsy();
});
it('commitsText', () => {
expect(vm.commitsText).toEqual('commits');
vm.mr.divergedCommitsCount = 1;
expect(vm.commitsText).toEqual('commit');
});
});
describe('template', () => {
let vm;
let el;
const sourceBranchPath = '/foo/bar/mr-widget-refactor';
const mr = {
divergedCommitsCount: 12,
sourceBranch: 'mr-widget-refactor',
sourceBranchLink: `<a href="${sourceBranchPath}">mr-widget-refactor</a>`,
targetBranchPath: 'foo/bar/commits-path',
targetBranchTreePath: 'foo/bar/tree/path',
targetBranch: 'master',
isOpen: true,
emailPatchesPath: '/mr/email-patches',
plainDiffPath: '/mr/plainDiffPath',
};
beforeEach(() => {
vm = createComponent(mr);
el = vm.$el;
});
it('should render template elements correctly', () => {
expect(el.classList.contains('mr-source-target')).toBeTruthy();
const sourceBranchLink = el.querySelectorAll('.label-branch')[0];
const targetBranchLink = el.querySelectorAll('.label-branch')[1];
const commitsCount = el.querySelector('.diverged-commits-count');
expect(sourceBranchLink.textContent).toContain(mr.sourceBranch);
expect(targetBranchLink.textContent).toContain(mr.targetBranch);
expect(sourceBranchLink.querySelector('a').getAttribute('href')).toEqual(sourceBranchPath);
expect(targetBranchLink.querySelector('a').getAttribute('href')).toEqual(mr.targetBranchTreePath);
expect(commitsCount.textContent).toContain('12 commits behind');
expect(commitsCount.querySelector('a').getAttribute('href')).toEqual(mr.targetBranchPath);
expect(el.textContent).toContain('Check out branch');
expect(el.querySelectorAll('.dropdown li a')[0].getAttribute('href')).toEqual(mr.emailPatchesPath);
expect(el.querySelectorAll('.dropdown li a')[1].getAttribute('href')).toEqual(mr.plainDiffPath);
});
it('should not have right action links if the MR state is not open', (done) => {
vm.mr.isOpen = false;
Vue.nextTick(() => {
expect(el.textContent).not.toContain('Check out branch');
expect(el.querySelectorAll('.dropdown li a').length).toEqual(0);
done();
});
});
it('should not render diverged commits count if the MR has no diverged commits', (done) => {
vm.mr.divergedCommitsCount = null;
Vue.nextTick(() => {
expect(el.textContent).not.toContain('commits behind');
expect(el.querySelectorAll('.diverged-commits-count').length).toEqual(0);
done();
});
});
});
});
|
$(function() {
function ConcreteBlockForm(data) {
'use strict';
this.data = data;
this.setupEvents(data);
this.init(data);
}
ConcreteBlockForm.prototype.setupEvents = function(data) {
var my = this,
$chooseContainer = $('#ccm-block-express-form-choose-type'),
$tabsContainer = $('#ccm-block-express-form-tabs');
Concrete.event.unbind('add_control.block_express_form');
Concrete.event.bind('add_control.block_express_form', function(e, data) {
var $tabEdit = $('#ccm-block-express-form-edit'),
$list = $tabEdit.find('ul');
$list.append(data.controlTemplate({'control': data.control}));
my.rescanEmailFields();
});
Concrete.event.unbind('update_control.block_express_form');
Concrete.event.bind('update_control.block_express_form', function(e, data) {
var $tabEdit = $('#ccm-block-express-form-edit'),
$control = $tabEdit.find('[data-form-control-id=' + data.control.id + ']');
if ($control) {
$control.replaceWith(data.controlTemplate({'control': data.control}));
}
my.rescanEmailFields();
});
if (data.task == 'add') {
$tabsContainer.hide();
} else {
my.chooseFormType(data.mode);
}
$chooseContainer.find('button').on('click', function() {
var action = $(this).attr('data-action');
if (action == 'choose-new-form') {
my.chooseFormType('new');
} else {
my.chooseFormType('existing');
}
});
}
ConcreteBlockForm.prototype.chooseFormType = function(mode) {
var my = this,
$chooseContainer = $('#ccm-block-express-form-choose-type'),
$tabsContainer = $('#ccm-block-express-form-tabs');
switch(mode) {
case 'new':
$tabsContainer.find('li').eq(2).remove();
break;
case 'existing':
$tabsContainer.find('li').eq(0).remove();
$tabsContainer.find('li').eq(0).remove();
break;
}
$tabsContainer.find('li').eq(0).find('a').trigger('click');
$tabsContainer.show();
$chooseContainer.hide();
}
ConcreteBlockForm.prototype.destroyContents = function($element) {
if (typeof CKEDITOR != 'undefined') {
for (name in CKEDITOR.instances) {
var instance = CKEDITOR.instances[name];
if ($.contains($element.get(0), instance.container.$)) {
instance.destroy(true);
}
}
}
$element.children().remove().hide();
}
ConcreteBlockForm.prototype.init = function(data) {
var my = this,
$tabAdd = $('#ccm-block-express-form-add'),
$tabEdit = $('#ccm-block-express-form-edit'),
$tabResults = $('#ccm-block-express-form-results'),
$tabOptions = $('#ccm-block-express-form-options'),
$storeFormSubmission = $tabResults.find('input[name=storeFormSubmission]'),
$formResultsFolderSection = $tabResults.find('div[data-section=form-results-folder]'),
controlTemplate = _.template($('script[data-template=express-form-form-control]').html()),
questionTemplate = _.template($('script[data-template=express-form-form-question]').html());
$tabOptions.on('change', 'input[name=notifyMeOnSubmission]', function() {
var $emailReplyToView = $('#ccm-block-express-form-options div[data-view=form-options-email-reply-to]');
$('input[name=recipientEmail]').focus();
if ($(this).is(':checked')) {
$emailReplyToView.show();
} else {
$emailReplyToView.hide();
}
}).trigger('change');
$storeFormSubmission.on('change', function() {
var $submissionAlert = $tabResults.find('div.alert');
if (!$(this).is(':checked')) {
$submissionAlert.show();
$formResultsFolderSection.hide();
} else {
$submissionAlert.hide();
$formResultsFolderSection.show();
}
}).trigger('change');
$tabAdd.find('div[data-view=add-question-inner]').html(questionTemplate({
'question': '',
'id': null,
'isRequired': false,
'selectedType': '',
'types': data.types,
'typeContent': null
}));
var $types = $('div[data-group=field-types]'),
$typeData = $('div[data-group=field-type-data]'),
$controlName = $('div[data-group=control-name]'),
$controlRequired = $('div[data-group=control-required]'),
$addQuestionGroup = $('div[data-group=add-question]');
$tabAdd.on('click', 'button[data-action=add-question]', function() {
var $form = $tabAdd.find(':input');
var data = $form.serializeArray();
jQuery.fn.dialog.showLoader();
$.concreteAjax({
url: $tabAdd.attr('data-action'),
data: data,
success: function(r) {
$types.find('option').eq(0).prop('selected', true);
$types.find('select').trigger('change');
$types.closest('.ui-dialog-content').scrollTop(0);
$tabAdd.find('input[name=question]').val('');
$tabAdd.find('input[name=required][value=0]').prop('checked', true);
$tabAdd.find('div.alert-success').show().addClass("animated fadeIn");
Concrete.event.publish('add_control.block_express_form', {
'control': r,
'controlTemplate': controlTemplate
});
setTimeout(function() {
$tabAdd.find('div.alert-success').hide();
}, 2000);
}
});
});
$tabEdit.on('click', 'button[data-action=update-question]', function() {
var $form = $tabEdit.find(':input');
var data = $form.serializeArray();
jQuery.fn.dialog.showLoader();
$.concreteAjax({
url: $tabEdit.attr('data-action'),
data: data,
success: function(r) {
var $fields = $tabEdit.find('[data-view=form-fields]'),
$editQuestion = $tabEdit.find('[data-view=edit-question]'),
$editQuestionInner = $tabEdit.find('[data-view=edit-question-inner]');
$tabEdit.find('div.alert-success').show().addClass("animated fadeIn");
$editQuestion.hide();
$fields.show();
my.destroyContents($editQuestionInner);
Concrete.event.publish('update_control.block_express_form', {
'control': r,
'controlTemplate': controlTemplate
});
setTimeout(function() {
$tabEdit.find('div.alert-success').hide();
}, 2000);
}
});
});
$tabEdit.on('click', 'a[data-action=delete-control]', function() {
$(this).closest('li').queue(function() {
$(this).addClass('animated bounceOutLeft');
$(this).dequeue();
}).delay(500).queue(function () {
$(this).remove();
my.rescanEmailFields();
$(this).dequeue();
})
});
$tabEdit.on('click', 'button[data-action=cancel-edit]', function() {
var $fields = $tabEdit.find('[data-view=form-fields]'),
$editQuestion = $tabEdit.find('[data-view=edit-question]'),
$editQuestionInner = $tabEdit.find('[data-view=edit-question-inner]');
$editQuestion.hide();
my.destroyContents($editQuestionInner);
$fields.show();
});
$tabEdit.on('click', 'a[data-action=edit-control]', function() {
var $control = $(this).closest('[data-form-control-id]');
$.concreteAjax({
url: $control.attr('data-action'),
type: 'get',
data: {'control': $control.attr('data-form-control-id')},
success: function(r) {
var $fields = $tabEdit.find('[data-view=form-fields]'),
$editQuestion = $tabEdit.find('[data-view=edit-question]'),
$editQuestionInner = $tabEdit.find('[data-view=edit-question-inner]');
$fields.hide();
_.each(r.assets.css, function(css) {
ConcreteAssetLoader.loadCSS(css);
});
_.each(r.assets.javascript, function(javascript) {
ConcreteAssetLoader.loadJavaScript(javascript);
});
$editQuestionInner.html(questionTemplate({
'id': r.id,
'question': r.question,
'isRequired': r.isRequired,
'selectedType': r.type,
'selectedTypeDisplayName': r.typeDisplayName,
'types': data.types,
'typeContent': r.typeContent
}));
$editQuestion.show();
if (r.showControlName) {
$editQuestion.find('div[data-group=control-name]').show();
}
if (r.showControlRequired) {
$editQuestion.find('div[data-group=control-required]').show();
}
}
});
});
$tabEdit.find('ul').sortable({
placeholder: "ui-state-highlight",
axis: "y",
handle: "i.fa-arrows-alt",
cursor: "move",
update: function() {
}
});
$types.find('select').on('change', function() {
my.destroyContents($typeData);
$controlName.hide();
$controlRequired.hide();
$addQuestionGroup.hide();
var value = $(this).val();
if (value) {
$types.find('i.fa-refresh').show();
$.concreteAjax({
url: $types.attr('data-action'),
data: {'id': value},
loader: false,
success: function(r) {
_.each(r.assets.css, function(css) {
ConcreteAssetLoader.loadCSS(css);
});
_.each(r.assets.javascript, function(javascript) {
ConcreteAssetLoader.loadJavaScript(javascript);
});
if (r.showControlName) {
$controlName.show();
}
if (r.showControlRequired) {
$controlRequired.show();
}
$typeData.html(r.content);
$typeData.show();
$addQuestionGroup.show();
},
complete: function() {
$types.find('i.fa-refresh').hide();
}
});
}
});
if (data.controls) {
_.each(data.controls, function(control) {
Concrete.event.publish('add_control.block_express_form', {
'control': control,
'controlTemplate': controlTemplate
});
});
}
$('[data-tree]').each(function() {
$(this).concreteTree({
ajaxData: {
displayOnly: 'express_entry_category'
},
treeNodeParentID: $(this).attr('data-root-tree-node-id'),
selectNodesByKey: [$('input[name=resultsFolder]').val()],
onSelect : function(nodes) {
if (nodes.length) {
$('input[name=resultsFolder]').val(nodes[0]);
} else {
$('input[name=resultsFolder]').val('');
}
},
chooseNodeInForm: 'single'
});
});
}
ConcreteBlockForm.prototype.rescanEmailFields = function($emailReplyToView) {
// Gather all the email controls
var $tabEdit = $('#ccm-block-express-form-edit'),
$emailReplyToView = $('#ccm-block-express-form-options div[data-view=form-options-email-reply-to]'),
emailReplyToTemplate = _.template($('script[data-template=express-form-reply-to-email]').html()),
$controls = $tabEdit.find('li[data-form-control-id]'),
selected = $emailReplyToView.find('select[name=replyToEmailControlID]').val(),
controls = [];
if (!selected) {
selected = this.data.settings.replyToEmailControlID;
}
$controls.each(function() {
var $control = $(this);
if ($control.attr('data-form-control-field-type') == 'email') {
controls.push({
key: $control.attr('data-form-control-id'),
value: $control.attr('data-form-control-label')
});
}
});
if (!controls.length) {
$emailReplyToView.html('');
} else {
$emailReplyToView.html(emailReplyToTemplate({'controls': controls, 'selected': selected}));
}
}
Concrete.event.bind('open.block_express_form', function(e, data) {
var form = new ConcreteBlockForm(data);
});
}); |
(function($) {
//
// Public interface
//
// The main event - creates a pretty graph. See index.html for documentation.
$.fn.tufteBar = function(options) {
var defaultCopy = $.extend(true, {}, $.fn.tufteBar.defaults);
var options = $.extend(true, defaultCopy, options);
return this.each(function () {
draw(makePlot($(this), options), options);
});
}
// Defaults are exposed publically so you can reuse bits that you find
// handy (the colors, for instance)
$.fn.tufteBar.defaults = {
barWidth: 0.8,
colors: ['#07093D', '#0C0F66', '#476FB2'],
color: function(index, stackedIndex, options) { return options.colors[stackedIndex % options.colors.length]; },
barLabel: function(index, stackedIndex) {
return $.tufteBar.formatNumber(totalValue(this[0]));
},
axisLabel: function(index, stackedIndex) { return index; },
legend: {
color: function(index, options) { return options.colors[index % options.colors.length]; },
label: function(index) { return this; }
}
}
$.tufteBar = {
// Add thousands separators to a number to make it look pretty.
// 1000 -> 1,000
formatNumber: function(nStr) {
// http://www.mredkj.com/javascript/nfbasic.html
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
}
//
// Private functions
//
// This function should be applied to any option used from the options hash.
// It allows options to be provided as either static values or functions which are
// evaluated each time they are used
function resolveOption(option, element) {
// the @arguments@ special variable looks like an array, but really isn't, so we
// need to transform it in order to perform array function on it
function toArray() {
var result = []
for (var i = 0; i < this.length; i++)
result.push(this[i])
return(result)
}
return $.isFunction(option) ? option.apply(element, toArray.apply(arguments).slice(2, arguments.length)) : option;
}
// Returns the total value of a bar, for labeling or plotting. Y values can either be
// a single number (for a normal graph), or an array of numbers (for a stacked graph)
function totalValue(value) {
if (value instanceof Array)
return $.sum(value);
else
return value;
}
function draw(plot, options) {
var ctx = plot.ctx;
var axis = plot.axis;
// Iterate over each bar
$(options.data).each(function (i) {
var element = this;
var x = i + 0.5;
var all_y = null;
if (element[0] instanceof Array) {
// This is a stacked bar, so the data is all good to go
all_y = element[0];
} else {
// This is a normal bar, wrap in an array to make it a stacked bar with one data point
all_y = [element[0]];
}
if ($(all_y).any(function() { return isNaN(+this); })) {
throw("Non-numeric value provided for y: " + element[0]);
}
var lastY = 0;
pixel_scaling_function = function(axis) {
var scale = axis.pixelLength / (Math.abs(axis.max - axis.min));
return function (value) {
return value * scale;
}
}
// These functions transform a value from plot coordinates to pixel coordinates
var t = {}
t.W = pixel_scaling_function(axis.x);
t.H = pixel_scaling_function(axis.y);
t.X = t.W;
// Y needs to invert the result since 0 in plot coords is bottom left, but 0 in pixel coords is top left
t.Y = function(y) { return axis.y.pixelLength - t.H(y) };
// Iterate over each data point for this bar and render a rectangle for each
$(all_y).each(function(stackedIndex) {
var optionResolver = function(option) { // Curry resolveOption for convenience
return resolveOption(option, element, i, stackedIndex, options);
}
var y = all_y[stackedIndex];
var halfBar = optionResolver(options.barWidth) / 2;
var left = x - halfBar,
width = halfBar * 2,
height = Math.abs(y);
// Need to both fill and stroke the rect to make sure the whole area is covered
// You get nasty artifacts otherwise
var color = optionResolver(options.color);
if( y > 0 ) {
var top = lastY + y + Math.abs(axis.y.min);
var coords = [t.X(left), t.Y(top), t.W(width), t.H(height)];
} else {
var top = lastY + Math.abs(axis.y.min);
var coords = [t.X(left), t.Y(top), t.W(width), t.H(height)];
}
ctx.rect(coords[0], coords[1], coords[2], coords[3]).attr({stroke: color, fill: color});
if( (lastY >= 0 && y >= 0) || (lastY <= 0 && y <= 0) ) {
lastY = lastY + y;
} else {
lastY = 0;
}
});
addLabel = function(klass, text, pos) {
html = '<div style="position:absolute;" class="label ' + klass + '">' + text + "</div>";
$(html).css(pos).appendTo( plot.target );
}
getLabelHeight = function( klass ) {
// create an invisible div to get the height
if( $('.' + klass).length === 0 ) {
html = '<div style="display:none" class="label ' + klass + '">empty label</div>';
$(html).appendTo( plot.target );
}
return $('.' + klass).height();
}
var optionResolver = function(option) { // Curry resolveOption for convenience
return resolveOption(option, element, i, options);
}
var barLabelBottom = (lastY >= 0) ?
t.H(lastY + Math.abs(axis.y.min)) :
t.H(lastY + Math.abs(axis.y.min)) - 2 * getLabelHeight('bar-label')
addLabel('bar-label', optionResolver(options.barLabel), {
left: t.X(x - 0.5),
bottom: barLabelBottom,
width: t.W(1)
});
addLabel('axis-label', optionResolver(options.axisLabel), {
left: t.X(x - 0.5),
top: t.Y(0) + 2 * getLabelHeight('axis-label'),
width: t.W(1)
});
});
addLegend(plot, options);
}
// If legend data has been provided, transform it into an
// absolutely positioned table placed at the top right of the graph
function addLegend(plot, options) {
if (options.legend.data) {
elements = $(options.legend.data).collect(function(i) {
var optionResolver = (function (element) {
return function(option) { // Curry resolveOption for convenience
return resolveOption(option, element, i, options);
}
})(this);
var colorBox = '<div class="color-box" style="background-color:' + optionResolver(options.legend.color) + '"></div>';
var label = optionResolver(options.legend.label);
return "<tr><td>" + colorBox + "</td><td>" + label + "</td></tr>";
});
$('<table class="legend">' + elements.reverse().join("") + '</table>').css({
position: 'absolute',
top: '0px',
left: plot.width + 'px'
}).appendTo( plot.target );
}
}
// Calculates the range of the graph by looking for the
// maximum y-value
function makeAxis(options) {
var axis = {
x: {},
y: {}
}
axis.x.min = 0
axis.x.max = options.data.length;
axis.y.min = 0;
axis.y.max = 0;
$(options.data).each(function() {
var y = totalValue(this[0]);
if( y > axis.y.max ) axis.y.max = y;
if( y < axis.y.min ) axis.y.min = y;
});
if( axis.x.max <= 0) throw("You must have at least one data point");
return axis;
}
// Creates the canvas object to draw on, and set up the axes
function makePlot(target, options) {
var plot = {};
plot.target = target;
plot.width = target.width();
plot.height = target.height();
target.html( '' ).css( 'position', 'relative' );
if( plot.width <= 0 || plot.height <= 0 ) {
throw "Invalid dimensions for plot, width = " + plot.width + ", height = " + plot.height;
}
// the canvas
plot.ctx = Raphael(target[0].id, plot.width, plot.height);
plot.axis = makeAxis(options);
plot.axis.x.pixelLength = plot.width;
plot.axis.y.pixelLength = plot.height;
return plot;
}
} )( jQuery );
|
import Network from '../../src/app/utils/Network';
import Address from '../../src/app/utils/Address';
import convert from '../../src/app/utils/convert';
describe('WalletBuilder service tests', function() {
let WalletBuilder
beforeEach(angular.mock.module('app'));
beforeEach(angular.mock.inject(function(_WalletBuilder_) {
WalletBuilder = _WalletBuilder_;
}));
it("Can create new wallet", function(done) {
// Arrange:
let walletName = "Quantum_Mechanics";
let password = "TestTest";
let network = Network.data.Mainnet.id;
// Act
WalletBuilder.createWallet(walletName, password, network).then((wallet) => {
// Assert
expect(wallet).not.toBe(0);
done();
});
});
describe('Create new wallet edge-cases', function() {
it("Can't create new wallet without password", function(done) {
// Arrange:
let walletName = "Quantum_Mechanics";
let password = "";
let network = Network.data.Mainnet.id;
// Act
WalletBuilder.createWallet(walletName, password, network).then((wallet) => {
},
(err) => {
// Assert
expect(err).toBeDefined();
done();
});
});
it("Can't create new wallet without name", function(done) {
// Arrange:
let walletName = "";
let password = "TestTest";
let network = Network.data.Mainnet.id;
// Act
WalletBuilder.createWallet(walletName, password, network).then((wallet) => {
},
(err) => {
// Assert
expect(err).toBeDefined();
done();
});
});
it("Can't create new wallet without network", function(done) {
// Arrange:
let walletName = "Quantum_Mechanics";
let password = "TestTest";
let network = "";
//// Act
WalletBuilder.createWallet(walletName, password, network).then((wallet) => {
},
(err) => {
// Assert
expect(err).toBeDefined();
done();
});
});
});
it("Can create brain wallet", function(done) {
// Arrange:
let walletName = "Quantum_Mechanics";
let password = "TestTest";
let network = Network.data.Mainnet.id;
let expectedWallet = {
"privateKey": "",
"name": "Quantum_Mechanics",
"accounts": {
"0": {
"brain": true,
"algo": "pass:6k",
"encrypted": "",
"iv": "",
"address": "NCTIKLMIWKRZC3TRKD5JYZUQHV76LGS3TTSUIXM6",
"label": "Primary",
"network": 104,
"child": "fda69cfb780e65ee400be32101f80c7611ba95930cd838a4d32dabb4c738f1af"
}
}
};
// Act
WalletBuilder.createBrainWallet(walletName, password, network).then((wallet) => {
// Assert
expect(wallet).toEqual(expectedWallet);
done();
});
});
describe('Create brain wallet edge-cases', function() {
it("Can't create brain wallet without password", function(done) {
// Arrange:
let walletName = "Quantum_Mechanics";
let password = "";
let network = Network.data.Mainnet.id;
// Act
WalletBuilder.createBrainWallet(walletName, password, network).then((wallet) => {
},
(err) => {
// Assert
expect(err).toBeDefined();
done();
});
});
it("Can't create brain wallet without name", function(done) {
// Arrange:
let walletName = "";
let password = "TestTest";
let network = Network.data.Mainnet.id;
// Act
WalletBuilder.createBrainWallet(walletName, password, network).then((wallet) => {
},
(err) => {
// Assert
expect(err).toBeDefined();
done();
});
});
it("Can't create brain wallet without network", function(done) {
// Arrange:
let walletName = "Quantum_Mechanics";
let password = "TestTest";
let network = "";
// Act
WalletBuilder.createBrainWallet(walletName, password, network).then((wallet) => {
},
(err) => {
// Assert
expect(err).toBeDefined();
done();
});
});
});
it("Can create private key wallet", function(done) {
// Arrange:
let walletName = "Quantum_Mechanics";
let password = "TestTest";
let privateKey = "73d0d250a2214274c4f433f79573ff1d50cde37b5d181b341f9942d096341225";
let address = "NBJ2XZMCAFAAVZXTPUPJ4MDAJOYCFB7X3MKBHFCK";
let network = Network.data.Mainnet.id;
// Act
WalletBuilder.createPrivateKeyWallet(walletName, password, address, privateKey, network).then((wallet) => {
// Assert
expect(wallet).not.toBe(0);
done();
});
});
describe('Create private key wallet edge-cases', function() {
it("Can't create private Key wallet without password", function(done) {
// Arrange:
let walletName = "Quantum_Mechanics";
let password = "";
let privateKey = "73d0d250a2214274c4f433f79573ff1d50cde37b5d181b341f9942d096341225";
let address = "NBJ2XZMCAFAAVZXTPUPJ4MDAJOYCFB7X3MKBHFCK";
let network = Network.data.Mainnet.id;
// Act
WalletBuilder.createPrivateKeyWallet(walletName, password, address, privateKey, network).then((wallet) => {
},
(err) => {
// Assert
expect(err).toBeDefined();
done();
});
});
it("Can't create private Key wallet without private key", function(done) {
// Arrange:
let walletName = "Quantum_Mechanics";
let password = "TestTest";
let privateKey = "";
let address = "NBJ2XZMCAFAAVZXTPUPJ4MDAJOYCFB7X3MKBHFCK";
let network = Network.data.Mainnet.id;
// Act
WalletBuilder.createPrivateKeyWallet(walletName, password, address, privateKey, network).then((wallet) => {
},
(err) => {
// Assert
expect(err).toBeDefined();
done();
});
});
it("Can't create private Key wallet without address", function(done) {
// Arrange:
let walletName = "Quantum_Mechanics";
let password = "TestTest";
let privateKey = "73d0d250a2214274c4f433f79573ff1d50cde37b5d181b341f9942d096341225";
let address = "";
let network = Network.data.Mainnet.id;
// Act
WalletBuilder.createPrivateKeyWallet(walletName, password, address, privateKey, network).then((wallet) => {
},
(err) => {
// Assert
expect(err).toBeDefined();
done();
});
});
it("Can't create private Key wallet without name", function(done) {
// Arrange:
let walletName = "";
let password = "TestTest";
let privateKey = "73d0d250a2214274c4f433f79573ff1d50cde37b5d181b341f9942d096341225";
let address = "NBJ2XZMCAFAAVZXTPUPJ4MDAJOYCFB7X3MKBHFCK";
let network = Network.data.Mainnet.id;
// Act
WalletBuilder.createPrivateKeyWallet(walletName, password, address, privateKey, network).then((wallet) => {
},
(err) => {
// Assert
expect(err).toBeDefined();
done();
});
});
it("Can't create private Key wallet without network", function(done) {
// Arrange:
let walletName = "Quantum_Mechanics";
let password = "TestTest";
let privateKey = "73d0d250a2214274c4f433f79573ff1d50cde37b5d181b341f9942d096341225";
let address = "NBJ2XZMCAFAAVZXTPUPJ4MDAJOYCFB7X3MKBHFCK";
let network = "";
// Act
WalletBuilder.createPrivateKeyWallet(walletName, password, address, privateKey, network).then((wallet) => {
},
(err) => {
// Assert
expect(err).toBeDefined();
done();
});
});
});
}); |
/**
* @license
* v1.2.8
* MIT (https://github.com/pnp/pnpjs/blob/master/LICENSE)
* Copyright (c) 2019 Microsoft
* docs: https://pnp.github.io/pnpjs/
* source: https://github.com/pnp/pnpjs
* bugs: https://github.com/pnp/pnpjs/issues
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@pnp/common'), require('@pnp/logging'), require('@pnp/odata')) :
typeof define === 'function' && define.amd ? define(['exports', '@pnp/common', '@pnp/logging', '@pnp/odata'], factory) :
(factory((global.pnp = global.pnp || {}, global.pnp.sp = {}),global.pnp.common,global.pnp.logging,global.pnp.odata));
}(this, (function (exports,common,logging,odata) { 'use strict';
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/* global Reflect, Promise */
var extendStatics = function(d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
function __extends(d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
function __decorate(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;
}
function __awaiter(thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
}
function extractWebUrl(candidateUrl) {
if (common.stringIsNullOrEmpty(candidateUrl)) {
return "";
}
var index = candidateUrl.indexOf("_api/");
if (index < 0) {
index = candidateUrl.indexOf("_vti_bin/");
}
if (index > -1) {
return candidateUrl.substr(0, index);
}
// if all else fails just give them what they gave us back
return candidateUrl;
}
function odataUrlFrom(candidate) {
var parts = [];
var s = ["odata.type", "odata.editLink", "__metadata", "odata.metadata"];
if (common.hOP(candidate, s[0]) && candidate[s[0]] === "SP.Web") {
// webs return an absolute url in the editLink
if (common.hOP(candidate, s[1])) {
parts.push(candidate[s[1]]);
}
else if (common.hOP(candidate, s[2])) {
// we are dealing with verbose, which has an absolute uri
parts.push(candidate.__metadata.uri);
}
}
else {
if (common.hOP(candidate, s[3]) && common.hOP(candidate, s[1])) {
// we are dealign with minimal metadata (default)
parts.push(extractWebUrl(candidate[s[3]]), "_api", candidate[s[1]]);
}
else if (common.hOP(candidate, s[1])) {
parts.push("_api", candidate[s[1]]);
}
else if (common.hOP(candidate, s[2])) {
// we are dealing with verbose, which has an absolute uri
parts.push(candidate.__metadata.uri);
}
}
if (parts.length < 1) {
logging.Logger.write("No uri information found in ODataEntity parsing, chaining will fail for this object.", 2 /* Warning */);
return "";
}
return common.combine.apply(void 0, parts);
}
var SPODataEntityParserImpl = /** @class */ (function (_super) {
__extends(SPODataEntityParserImpl, _super);
function SPODataEntityParserImpl(factory) {
var _this = _super.call(this) || this;
_this.factory = factory;
_this.hydrate = function (d) {
var o = new _this.factory(odataUrlFrom(d), null);
return common.extend(o, d);
};
return _this;
}
SPODataEntityParserImpl.prototype.parse = function (r) {
var _this = this;
return _super.prototype.parse.call(this, r).then(function (d) {
var o = new _this.factory(odataUrlFrom(d), null);
return common.extend(o, d);
});
};
return SPODataEntityParserImpl;
}(odata.ODataParserBase));
var SPODataEntityArrayParserImpl = /** @class */ (function (_super) {
__extends(SPODataEntityArrayParserImpl, _super);
function SPODataEntityArrayParserImpl(factory) {
var _this = _super.call(this) || this;
_this.factory = factory;
_this.hydrate = function (d) {
return d.map(function (v) {
var o = new _this.factory(odataUrlFrom(v), null);
return common.extend(o, v);
});
};
return _this;
}
SPODataEntityArrayParserImpl.prototype.parse = function (r) {
var _this = this;
return _super.prototype.parse.call(this, r).then(function (d) {
return d.map(function (v) {
var o = new _this.factory(odataUrlFrom(v), null);
return common.extend(o, v);
});
});
};
return SPODataEntityArrayParserImpl;
}(odata.ODataParserBase));
function spODataEntity(factory) {
return new SPODataEntityParserImpl(factory);
}
function spODataEntityArray(factory) {
return new SPODataEntityArrayParserImpl(factory);
}
function setup(config) {
common.RuntimeConfig.extend(config);
}
var SPRuntimeConfigImpl = /** @class */ (function () {
function SPRuntimeConfigImpl() {
}
Object.defineProperty(SPRuntimeConfigImpl.prototype, "headers", {
get: function () {
var spPart = common.RuntimeConfig.get("sp");
if (spPart !== undefined && spPart.headers !== undefined) {
return spPart.headers;
}
return {};
},
enumerable: true,
configurable: true
});
Object.defineProperty(SPRuntimeConfigImpl.prototype, "baseUrl", {
get: function () {
var spPart = common.RuntimeConfig.get("sp");
if (spPart !== undefined && spPart.baseUrl !== undefined) {
return spPart.baseUrl;
}
if (common.RuntimeConfig.spfxContext !== undefined && common.RuntimeConfig.spfxContext !== null) {
return common.RuntimeConfig.spfxContext.pageContext.web.absoluteUrl;
}
return null;
},
enumerable: true,
configurable: true
});
Object.defineProperty(SPRuntimeConfigImpl.prototype, "fetchClientFactory", {
get: function () {
var spPart = common.RuntimeConfig.get("sp");
if (spPart !== undefined && spPart.fetchClientFactory !== undefined) {
return spPart.fetchClientFactory;
}
else {
return function () { return new common.FetchClient(); };
}
},
enumerable: true,
configurable: true
});
return SPRuntimeConfigImpl;
}());
var SPRuntimeConfig = new SPRuntimeConfigImpl();
var CachedDigest = /** @class */ (function () {
function CachedDigest() {
}
return CachedDigest;
}());
// allows for the caching of digests across all HttpClient's which each have their own DigestCache wrapper.
var digests = new Map();
var DigestCache = /** @class */ (function () {
function DigestCache(_httpClient, _digests) {
if (_digests === void 0) { _digests = digests; }
this._httpClient = _httpClient;
this._digests = _digests;
}
DigestCache.prototype.getDigest = function (webUrl) {
var _this = this;
var cachedDigest = this._digests.get(webUrl);
if (cachedDigest !== undefined) {
var now = new Date();
if (now < cachedDigest.expiration) {
return Promise.resolve(cachedDigest.value);
}
}
var url = common.combine(webUrl, "/_api/contextinfo");
var headers = {
"Accept": "application/json;odata=verbose",
"Content-Type": "application/json;odata=verbose;charset=utf-8",
};
return this._httpClient.fetchRaw(url, {
cache: "no-cache",
credentials: "same-origin",
headers: common.extend(headers, SPRuntimeConfig.headers, true),
method: "POST",
}).then(function (response) {
var parser = new odata.ODataDefaultParser();
return parser.parse(response).then(function (d) { return d.GetContextWebInformation; });
}).then(function (data) {
var newCachedDigest = new CachedDigest();
newCachedDigest.value = data.FormDigestValue;
var seconds = data.FormDigestTimeoutSeconds;
var expiration = new Date();
expiration.setTime(expiration.getTime() + 1000 * seconds);
newCachedDigest.expiration = expiration;
_this._digests.set(webUrl, newCachedDigest);
return newCachedDigest.value;
});
};
DigestCache.prototype.clear = function () {
this._digests.clear();
};
return DigestCache;
}());
var SPHttpClient = /** @class */ (function () {
function SPHttpClient(_impl) {
if (_impl === void 0) { _impl = SPRuntimeConfig.fetchClientFactory(); }
this._impl = _impl;
this._digestCache = new DigestCache(this);
}
SPHttpClient.prototype.fetch = function (url, options) {
var _this = this;
if (options === void 0) { options = {}; }
var opts = common.extend(options, { cache: "no-cache", credentials: "same-origin" }, true);
var headers = new Headers();
// first we add the global headers so they can be overwritten by any passed in locally to this call
common.mergeHeaders(headers, SPRuntimeConfig.headers);
// second we add the local options so we can overwrite the globals
common.mergeHeaders(headers, options.headers);
// lastly we apply any default headers we need that may not exist
if (!headers.has("Accept")) {
headers.append("Accept", "application/json");
}
if (!headers.has("Content-Type")) {
headers.append("Content-Type", "application/json;odata=verbose;charset=utf-8");
}
if (!headers.has("X-ClientService-ClientTag")) {
headers.append("X-ClientService-ClientTag", "PnPCoreJS:@pnp-1.2.8");
}
if (!headers.has("User-Agent")) {
// this marks the requests for understanding by the service
headers.append("User-Agent", "NONISV|SharePointPnP|PnPCoreJS/1.2.8");
}
opts = common.extend(opts, { headers: headers });
if (opts.method && opts.method.toUpperCase() !== "GET") {
// if we have either a request digest or an authorization header we don't need a digest
if (!headers.has("X-RequestDigest") && !headers.has("Authorization")) {
return this._digestCache.getDigest(extractWebUrl(url))
.then(function (digest) {
headers.append("X-RequestDigest", digest);
return _this.fetchRaw(url, opts);
});
}
}
return this.fetchRaw(url, opts);
};
SPHttpClient.prototype.fetchRaw = function (url, options) {
var _this = this;
if (options === void 0) { options = {}; }
// here we need to normalize the headers
var rawHeaders = new Headers();
common.mergeHeaders(rawHeaders, options.headers);
options = common.extend(options, { headers: rawHeaders });
var retry = function (ctx) {
// handles setting the proper timeout for a retry
var setRetry = function (response) {
var delay;
if (response.headers.has("Retry-After")) {
// if we have gotten a header, use that value as the delay value
delay = parseInt(response.headers.get("Retry-After"), 10);
}
else {
// grab our current delay
delay = ctx.delay;
// Increment our counters.
ctx.delay *= 2;
}
ctx.attempts++;
// If we have exceeded the retry count, reject.
if (ctx.retryCount <= ctx.attempts) {
ctx.reject(Error("Retry count exceeded (" + ctx.retryCount + ") for request. Response status: [" + response.status + "] " + response.statusText));
}
else {
// Set our retry timeout for {delay} milliseconds.
setTimeout(common.getCtxCallback(_this, retry, ctx), delay);
}
};
// send the actual request
_this._impl.fetch(url, options).then(function (response) {
if (response.status === 429) {
// we have been throttled
setRetry(response);
}
else {
ctx.resolve(response);
}
}).catch(function (response) {
if (response.status === 503) {
// http status code 503, we can retry this
setRetry(response);
}
else {
ctx.reject(response);
}
});
};
return new Promise(function (resolve, reject) {
var retryContext = {
attempts: 0,
delay: 100,
reject: reject,
resolve: resolve,
retryCount: 7,
};
retry.call(_this, retryContext);
});
};
SPHttpClient.prototype.get = function (url, options) {
if (options === void 0) { options = {}; }
var opts = common.extend(options, { method: "GET" });
return this.fetch(url, opts);
};
SPHttpClient.prototype.post = function (url, options) {
if (options === void 0) { options = {}; }
var opts = common.extend(options, { method: "POST" });
return this.fetch(url, opts);
};
SPHttpClient.prototype.patch = function (url, options) {
if (options === void 0) { options = {}; }
var opts = common.extend(options, { method: "PATCH" });
return this.fetch(url, opts);
};
SPHttpClient.prototype.delete = function (url, options) {
if (options === void 0) { options = {}; }
var opts = common.extend(options, { method: "DELETE" });
return this.fetch(url, opts);
};
return SPHttpClient;
}());
var global$1 = (typeof global !== "undefined" ? global :
typeof self !== "undefined" ? self :
typeof window !== "undefined" ? window : {});
/**
* Ensures that a given url is absolute for the current web based on context
*
* @param candidateUrl The url to make absolute
*
*/
function toAbsoluteUrl(candidateUrl) {
return new Promise(function (resolve) {
if (common.isUrlAbsolute(candidateUrl)) {
// if we are already absolute, then just return the url
return resolve(candidateUrl);
}
if (SPRuntimeConfig.baseUrl !== null) {
// base url specified either with baseUrl of spfxContext config property
return resolve(common.combine(SPRuntimeConfig.baseUrl, candidateUrl));
}
if (global$1._spPageContextInfo !== undefined) {
// operating in classic pages
if (common.hOP(global$1._spPageContextInfo, "webAbsoluteUrl")) {
return resolve(common.combine(global$1._spPageContextInfo.webAbsoluteUrl, candidateUrl));
}
else if (common.hOP(global$1._spPageContextInfo, "webServerRelativeUrl")) {
return resolve(common.combine(global$1._spPageContextInfo.webServerRelativeUrl, candidateUrl));
}
}
// does window.location exist and have a certain path part in it?
if (global$1.location !== undefined) {
var baseUrl_1 = global$1.location.toString().toLowerCase();
["/_layouts/", "/siteassets/"].forEach(function (s) {
var index = baseUrl_1.indexOf(s);
if (index > 0) {
return resolve(common.combine(baseUrl_1.substr(0, index), candidateUrl));
}
});
}
return resolve(candidateUrl);
});
}
function metadata(type) {
return {
"__metadata": { "type": type },
};
}
/**
* SharePointQueryable Base Class
*
*/
var SharePointQueryable = /** @class */ (function (_super) {
__extends(SharePointQueryable, _super);
/**
* Creates a new instance of the SharePointQueryable class
*
* @constructor
* @param baseUrl A string or SharePointQueryable that should form the base part of the url
*
*/
function SharePointQueryable(baseUrl, path) {
var _this = _super.call(this) || this;
_this._forceCaching = false;
if (typeof baseUrl === "string") {
// we need to do some extra parsing to get the parent url correct if we are
// being created from just a string.
if (common.isUrlAbsolute(baseUrl) || baseUrl.lastIndexOf("/") < 0) {
_this._parentUrl = baseUrl;
_this._url = common.combine(baseUrl, path);
}
else if (baseUrl.lastIndexOf("/") > baseUrl.lastIndexOf("(")) {
// .../items(19)/fields
var index = baseUrl.lastIndexOf("/");
_this._parentUrl = baseUrl.slice(0, index);
path = common.combine(baseUrl.slice(index), path);
_this._url = common.combine(_this._parentUrl, path);
}
else {
// .../items(19)
var index = baseUrl.lastIndexOf("(");
_this._parentUrl = baseUrl.slice(0, index);
_this._url = common.combine(baseUrl, path);
}
}
else {
_this.extend(baseUrl, path);
var target = baseUrl.query.get("@target");
if (target !== undefined) {
_this.query.set("@target", target);
}
}
return _this;
}
/**
* Creates a new instance of the supplied factory and extends this into that new instance
*
* @param factory constructor for the new SharePointQueryable
*/
SharePointQueryable.prototype.as = function (factory) {
var o = new factory(this._url, null);
return common.extend(o, this, true);
};
/**
* Gets the full url with query information
*
*/
SharePointQueryable.prototype.toUrlAndQuery = function () {
var aliasedParams = new Map(this.query);
var url = this.toUrl().replace(/'!(@.*?)::(.*?)'/ig, function (match, labelName, value) {
logging.Logger.write("Rewriting aliased parameter from match " + match + " to label: " + labelName + " value: " + value, 0 /* Verbose */);
aliasedParams.set(labelName, "'" + value + "'");
return labelName;
});
if (aliasedParams.size > 0) {
var char = url.indexOf("?") > -1 ? "&" : "?";
url += "" + char + Array.from(aliasedParams).map(function (v) { return v[0] + "=" + v[1]; }).join("&");
}
return url;
};
/**
* Choose which fields to return
*
* @param selects One or more fields to return
*/
SharePointQueryable.prototype.select = function () {
var selects = [];
for (var _i = 0; _i < arguments.length; _i++) {
selects[_i] = arguments[_i];
}
if (selects.length > 0) {
this.query.set("$select", selects.join(","));
}
return this;
};
/**
* Expands fields such as lookups to get additional data
*
* @param expands The Fields for which to expand the values
*/
SharePointQueryable.prototype.expand = function () {
var expands = [];
for (var _i = 0; _i < arguments.length; _i++) {
expands[_i] = arguments[_i];
}
if (expands.length > 0) {
this.query.set("$expand", expands.join(","));
}
return this;
};
/**
* Gets a parent for this instance as specified
*
* @param factory The contructor for the class to create
*/
SharePointQueryable.prototype.getParent = function (factory, baseUrl, path, batch) {
if (baseUrl === void 0) { baseUrl = this.parentUrl; }
var parent = new factory(baseUrl, path).configureFrom(this);
var t = "@target";
if (this.query.has(t)) {
parent.query.set(t, this.query.get(t));
}
if (batch !== undefined) {
parent = parent.inBatch(batch);
}
return parent;
};
/**
* Clones this SharePointQueryable into a new SharePointQueryable instance of T
* @param factory Constructor used to create the new instance
* @param additionalPath Any additional path to include in the clone
* @param includeBatch If true this instance's batch will be added to the cloned instance
*/
SharePointQueryable.prototype.clone = function (factory, additionalPath, includeBatch) {
if (includeBatch === void 0) { includeBatch = true; }
var clone = _super.prototype._clone.call(this, new factory(this, additionalPath), { includeBatch: includeBatch });
// handle sp specific clone actions
var t = "@target";
if (this.query.has(t)) {
clone.query.set(t, this.query.get(t));
}
return clone;
};
/**
* Converts the current instance to a request context
*
* @param verb The request verb
* @param options The set of supplied request options
* @param parser The supplied ODataParser instance
* @param pipeline Optional request processing pipeline
*/
SharePointQueryable.prototype.toRequestContext = function (verb, options, parser, pipeline) {
var _this = this;
if (options === void 0) { options = {}; }
var dependencyDispose = this.hasBatch ? this._batchDependency : function () { return; };
return toAbsoluteUrl(this.toUrlAndQuery()).then(function (url) {
common.mergeOptions(options, _this._options);
// build our request context
var context = {
batch: _this.batch,
batchDependency: dependencyDispose,
cachingOptions: _this._cachingOptions,
clientFactory: function () { return new SPHttpClient(); },
isBatched: _this.hasBatch,
isCached: _this._forceCaching || (_this._useCaching && /^get$/i.test(verb)),
options: options,
parser: parser,
pipeline: pipeline,
requestAbsoluteUrl: url,
requestId: common.getGUID(),
verb: verb,
};
return context;
});
};
return SharePointQueryable;
}(odata.ODataQueryable));
/**
* Represents a REST collection which can be filtered, paged, and selected
*
*/
var SharePointQueryableCollection = /** @class */ (function (_super) {
__extends(SharePointQueryableCollection, _super);
function SharePointQueryableCollection() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Filters the returned collection (https://msdn.microsoft.com/en-us/library/office/fp142385.aspx#bk_supported)
*
* @param filter The string representing the filter query
*/
SharePointQueryableCollection.prototype.filter = function (filter) {
this.query.set("$filter", filter);
return this;
};
/**
* Orders based on the supplied fields
*
* @param orderby The name of the field on which to sort
* @param ascending If false DESC is appended, otherwise ASC (default)
*/
SharePointQueryableCollection.prototype.orderBy = function (orderBy, ascending) {
if (ascending === void 0) { ascending = true; }
var o = "$orderby";
var query = this.query.has(o) ? this.query.get(o).split(",") : [];
query.push(orderBy + " " + (ascending ? "asc" : "desc"));
this.query.set(o, query.join(","));
return this;
};
/**
* Skips the specified number of items
*
* @param skip The number of items to skip
*/
SharePointQueryableCollection.prototype.skip = function (skip) {
this.query.set("$skip", skip.toString());
return this;
};
/**
* Limits the query to only return the specified number of items
*
* @param top The query row limit
*/
SharePointQueryableCollection.prototype.top = function (top) {
this.query.set("$top", top.toString());
return this;
};
return SharePointQueryableCollection;
}(SharePointQueryable));
/**
* Represents an instance that can be selected
*
*/
var SharePointQueryableInstance = /** @class */ (function (_super) {
__extends(SharePointQueryableInstance, _super);
function SharePointQueryableInstance() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Curries the update function into the common pieces
*
* @param type
* @param mapper
*/
SharePointQueryableInstance.prototype._update = function (type, mapper) {
var _this = this;
return function (props) { return _this.postCore({
body: common.jsS(common.extend(metadata(type), props)),
headers: {
"X-HTTP-Method": "MERGE",
},
}).then(function (d) { return mapper(d, props); }); };
};
/**
* Deletes this instance
*
*/
SharePointQueryableInstance.prototype._delete = function () {
return this.postCore({
headers: {
"X-HTTP-Method": "DELETE",
},
});
};
/**
* Deletes this instance with an etag value in the headers
*
* @param eTag eTag to delete
*/
SharePointQueryableInstance.prototype._deleteWithETag = function (eTag) {
if (eTag === void 0) { eTag = "*"; }
return this.postCore({
headers: {
"IF-Match": eTag,
"X-HTTP-Method": "DELETE",
},
});
};
return SharePointQueryableInstance;
}(SharePointQueryable));
/**
* Decorator used to specify the default path for SharePointQueryable objects
*
* @param path
*/
function defaultPath(path) {
return function (target) {
return /** @class */ (function (_super) {
__extends(class_1, _super);
function class_1() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return _super.call(this, args[0], args.length > 1 && args[1] !== undefined ? args[1] : path) || this;
}
return class_1;
}(target));
};
}
/**
* Describes a collection of all site collection users
*
*/
var SiteUsers = /** @class */ (function (_super) {
__extends(SiteUsers, _super);
function SiteUsers() {
return _super !== null && _super.apply(this, arguments) || this;
}
SiteUsers_1 = SiteUsers;
/**
* Gets a user from the collection by id
*
* @param id The id of the user to retrieve
*/
SiteUsers.prototype.getById = function (id) {
return new SiteUser(this, "getById(" + id + ")");
};
/**
* Gets a user from the collection by email
*
* @param email The email address of the user to retrieve
*/
SiteUsers.prototype.getByEmail = function (email) {
return new SiteUser(this, "getByEmail('" + email + "')");
};
/**
* Gets a user from the collection by login name
*
* @param loginName The login name of the user to retrieve
*/
SiteUsers.prototype.getByLoginName = function (loginName) {
var su = new SiteUser(this);
su.concat("('!@v::" + encodeURIComponent(loginName) + "')");
return su;
};
/**
* Removes a user from the collection by id
*
* @param id The id of the user to remove
*/
SiteUsers.prototype.removeById = function (id) {
return this.clone(SiteUsers_1, "removeById(" + id + ")").postCore();
};
/**
* Removes a user from the collection by login name
*
* @param loginName The login name of the user to remove
*/
SiteUsers.prototype.removeByLoginName = function (loginName) {
var o = this.clone(SiteUsers_1, "removeByLoginName(@v)");
o.query.set("@v", "'" + encodeURIComponent(loginName) + "'");
return o.postCore();
};
/**
* Adds a user to a group
*
* @param loginName The login name of the user to add to the group
*
*/
SiteUsers.prototype.add = function (loginName) {
var _this = this;
return this.clone(SiteUsers_1, null).postCore({
body: common.jsS(common.extend(metadata("SP.User"), { LoginName: loginName })),
}).then(function () { return _this.getByLoginName(loginName); });
};
var SiteUsers_1;
SiteUsers = SiteUsers_1 = __decorate([
defaultPath("siteusers")
], SiteUsers);
return SiteUsers;
}(SharePointQueryableCollection));
/**
* Base class for a user
*
*/
var UserBase = /** @class */ (function (_super) {
__extends(UserBase, _super);
function UserBase() {
return _super !== null && _super.apply(this, arguments) || this;
}
Object.defineProperty(UserBase.prototype, "groups", {
/**
* Gets the groups for this user
*
*/
get: function () {
return new SiteGroups(this, "groups");
},
enumerable: true,
configurable: true
});
return UserBase;
}(SharePointQueryableInstance));
/**
* Describes a single user
*
*/
var SiteUser = /** @class */ (function (_super) {
__extends(SiteUser, _super);
function SiteUser() {
var _this = _super !== null && _super.apply(this, arguments) || this;
/**
* Updates this user instance with the supplied properties
*
* @param properties A plain object of property names and values to update for the user
*/
_this.update = _this._update("SP.User", function (data) { return ({ data: data, user: _this }); });
/**
* Delete this user
*
*/
_this.delete = _this._delete;
return _this;
}
return SiteUser;
}(UserBase));
/**
* Represents the current user
*/
var CurrentUser = /** @class */ (function (_super) {
__extends(CurrentUser, _super);
function CurrentUser() {
return _super !== null && _super.apply(this, arguments) || this;
}
CurrentUser = __decorate([
defaultPath("currentuser")
], CurrentUser);
return CurrentUser;
}(UserBase));
/**
* Principal Type enum
*
*/
var PrincipalType;
(function (PrincipalType) {
PrincipalType[PrincipalType["None"] = 0] = "None";
PrincipalType[PrincipalType["User"] = 1] = "User";
PrincipalType[PrincipalType["DistributionList"] = 2] = "DistributionList";
PrincipalType[PrincipalType["SecurityGroup"] = 4] = "SecurityGroup";
PrincipalType[PrincipalType["SharePointGroup"] = 8] = "SharePointGroup";
PrincipalType[PrincipalType["All"] = 15] = "All";
})(PrincipalType || (PrincipalType = {}));
/**
* Describes a collection of site groups
*
*/
var SiteGroups = /** @class */ (function (_super) {
__extends(SiteGroups, _super);
function SiteGroups() {
return _super !== null && _super.apply(this, arguments) || this;
}
SiteGroups_1 = SiteGroups;
/**
* Gets a group from the collection by id
*
* @param id The id of the group to retrieve
*/
SiteGroups.prototype.getById = function (id) {
var sg = new SiteGroup(this);
sg.concat("(" + id + ")");
return sg;
};
/**
* Adds a new group to the site collection
*
* @param props The group properties object of property names and values to be set for the group
*/
SiteGroups.prototype.add = function (properties) {
var _this = this;
var postBody = common.jsS(common.extend(metadata("SP.Group"), properties));
return this.postCore({ body: postBody }).then(function (data) {
return {
data: data,
group: _this.getById(data.Id),
};
});
};
/**
* Gets a group from the collection by name
*
* @param groupName The name of the group to retrieve
*/
SiteGroups.prototype.getByName = function (groupName) {
return new SiteGroup(this, "getByName('" + groupName + "')");
};
/**
* Removes the group with the specified member id from the collection
*
* @param id The id of the group to remove
*/
SiteGroups.prototype.removeById = function (id) {
return this.clone(SiteGroups_1, "removeById('" + id + "')").postCore();
};
/**
* Removes the cross-site group with the specified name from the collection
*
* @param loginName The name of the group to remove
*/
SiteGroups.prototype.removeByLoginName = function (loginName) {
return this.clone(SiteGroups_1, "removeByLoginName('" + loginName + "')").postCore();
};
var SiteGroups_1;
SiteGroups = SiteGroups_1 = __decorate([
defaultPath("sitegroups")
], SiteGroups);
return SiteGroups;
}(SharePointQueryableCollection));
/**
* Describes a single group
*
*/
var SiteGroup = /** @class */ (function (_super) {
__extends(SiteGroup, _super);
function SiteGroup() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.update = _this._update("SP.Group", function (d, p) {
var retGroup = _this;
if (common.hOP(p, "Title")) {
/* tslint:disable-next-line no-string-literal */
retGroup = _this.getParent(SiteGroup, _this.parentUrl, "getByName('" + p["Title"] + "')");
}
return {
data: d,
group: retGroup,
};
});
return _this;
}
Object.defineProperty(SiteGroup.prototype, "users", {
/**
* Gets the users for this group
*
*/
get: function () {
return new SiteUsers(this, "users");
},
enumerable: true,
configurable: true
});
return SiteGroup;
}(SharePointQueryableInstance));
/**
* Describes a set of role assignments for the current scope
*
*/
var RoleAssignments = /** @class */ (function (_super) {
__extends(RoleAssignments, _super);
function RoleAssignments() {
return _super !== null && _super.apply(this, arguments) || this;
}
RoleAssignments_1 = RoleAssignments;
/**
* Gets the role assignment associated with the specified principal id from the collection.
*
* @param id The id of the role assignment
*/
RoleAssignments.prototype.getById = function (id) {
var ra = new RoleAssignment(this);
ra.concat("(" + id + ")");
return ra;
};
/**
* Adds a new role assignment with the specified principal and role definitions to the collection
*
* @param principalId The id of the user or group to assign permissions to
* @param roleDefId The id of the role definition that defines the permissions to assign
*
*/
RoleAssignments.prototype.add = function (principalId, roleDefId) {
return this.clone(RoleAssignments_1, "addroleassignment(principalid=" + principalId + ", roledefid=" + roleDefId + ")").postCore();
};
/**
* Removes the role assignment with the specified principal and role definition from the collection
*
* @param principalId The id of the user or group in the role assignment
* @param roleDefId The id of the role definition in the role assignment
*
*/
RoleAssignments.prototype.remove = function (principalId, roleDefId) {
return this.clone(RoleAssignments_1, "removeroleassignment(principalid=" + principalId + ", roledefid=" + roleDefId + ")").postCore();
};
var RoleAssignments_1;
RoleAssignments = RoleAssignments_1 = __decorate([
defaultPath("roleassignments")
], RoleAssignments);
return RoleAssignments;
}(SharePointQueryableCollection));
/**
* Describes a role assignment
*
*/
var RoleAssignment = /** @class */ (function (_super) {
__extends(RoleAssignment, _super);
function RoleAssignment() {
var _this = _super !== null && _super.apply(this, arguments) || this;
/**
* Deletes this role assignment
*
*/
_this.delete = _this._delete;
return _this;
}
Object.defineProperty(RoleAssignment.prototype, "groups", {
/**
* Gets the groups that directly belong to the access control list (ACL) for this securable object
*
*/
get: function () {
return new SiteGroups(this, "groups");
},
enumerable: true,
configurable: true
});
Object.defineProperty(RoleAssignment.prototype, "bindings", {
/**
* Gets the role definition bindings for this role assignment
*
*/
get: function () {
return new RoleDefinitionBindings(this);
},
enumerable: true,
configurable: true
});
return RoleAssignment;
}(SharePointQueryableInstance));
/**
* Describes a collection of role definitions
*
*/
var RoleDefinitions = /** @class */ (function (_super) {
__extends(RoleDefinitions, _super);
function RoleDefinitions() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Gets the role definition with the specified id from the collection
*
* @param id The id of the role definition
*
*/
RoleDefinitions.prototype.getById = function (id) {
return new RoleDefinition(this, "getById(" + id + ")");
};
/**
* Gets the role definition with the specified name
*
* @param name The name of the role definition
*
*/
RoleDefinitions.prototype.getByName = function (name) {
return new RoleDefinition(this, "getbyname('" + name + "')");
};
/**
* Gets the role definition with the specified role type
*
* @param roleTypeKind The roletypekind of the role definition (None=0, Guest=1, Reader=2, Contributor=3, WebDesigner=4, Administrator=5, Editor=6, System=7)
*
*/
RoleDefinitions.prototype.getByType = function (roleTypeKind) {
return new RoleDefinition(this, "getbytype(" + roleTypeKind + ")");
};
/**
* Creates a role definition
*
* @param name The new role definition's name
* @param description The new role definition's description
* @param order The order in which the role definition appears
* @param basePermissions The permissions mask for this role definition
*
*/
RoleDefinitions.prototype.add = function (name, description, order, basePermissions) {
var _this = this;
var postBody = common.jsS({
BasePermissions: common.extend({ __metadata: { type: "SP.BasePermissions" } }, basePermissions),
Description: description,
Name: name,
Order: order,
__metadata: { "type": "SP.RoleDefinition" },
});
return this.postCore({ body: postBody }).then(function (data) {
return {
data: data,
definition: _this.getById(data.Id),
};
});
};
RoleDefinitions = __decorate([
defaultPath("roledefinitions")
], RoleDefinitions);
return RoleDefinitions;
}(SharePointQueryableCollection));
/**
* Describes a role definition
*
*/
var RoleDefinition = /** @class */ (function (_super) {
__extends(RoleDefinition, _super);
function RoleDefinition() {
var _this = _super !== null && _super.apply(this, arguments) || this;
/**
* Deletes this role definition
*
*/
_this.delete = _this._delete;
return _this;
/* tslint:enable */
}
/**
* Updates this role definition with the supplied properties
*
* @param properties A plain object hash of values to update for the role definition
*/
/* tslint:disable no-string-literal */
RoleDefinition.prototype.update = function (properties) {
var _this = this;
var s = ["BasePermissions"];
if (common.hOP(properties, s[0]) !== undefined) {
properties[s[0]] = common.extend({ __metadata: { type: "SP." + s[0] } }, properties[s[0]]);
}
var postBody = common.jsS(common.extend(metadata("SP.RoleDefinition"), properties));
return this.postCore({
body: postBody,
headers: {
"X-HTTP-Method": "MERGE",
},
}).then(function (data) {
var retDef = _this;
if (common.hOP(properties, "Name")) {
var parent_1 = _this.getParent(RoleDefinitions, _this.parentUrl, "");
retDef = parent_1.getByName(properties["Name"]);
}
return {
data: data,
definition: retDef,
};
});
};
return RoleDefinition;
}(SharePointQueryableInstance));
/**
* Describes the role definitons bound to a role assignment object
*
*/
var RoleDefinitionBindings = /** @class */ (function (_super) {
__extends(RoleDefinitionBindings, _super);
function RoleDefinitionBindings() {
return _super !== null && _super.apply(this, arguments) || this;
}
RoleDefinitionBindings = __decorate([
defaultPath("roledefinitionbindings")
], RoleDefinitionBindings);
return RoleDefinitionBindings;
}(SharePointQueryableCollection));
/**
* Determines the display mode of the given control or view
*/
(function (ControlMode) {
ControlMode[ControlMode["Display"] = 1] = "Display";
ControlMode[ControlMode["Edit"] = 2] = "Edit";
ControlMode[ControlMode["New"] = 3] = "New";
})(exports.ControlMode || (exports.ControlMode = {}));
(function (FieldTypes) {
FieldTypes[FieldTypes["Invalid"] = 0] = "Invalid";
FieldTypes[FieldTypes["Integer"] = 1] = "Integer";
FieldTypes[FieldTypes["Text"] = 2] = "Text";
FieldTypes[FieldTypes["Note"] = 3] = "Note";
FieldTypes[FieldTypes["DateTime"] = 4] = "DateTime";
FieldTypes[FieldTypes["Counter"] = 5] = "Counter";
FieldTypes[FieldTypes["Choice"] = 6] = "Choice";
FieldTypes[FieldTypes["Lookup"] = 7] = "Lookup";
FieldTypes[FieldTypes["Boolean"] = 8] = "Boolean";
FieldTypes[FieldTypes["Number"] = 9] = "Number";
FieldTypes[FieldTypes["Currency"] = 10] = "Currency";
FieldTypes[FieldTypes["URL"] = 11] = "URL";
FieldTypes[FieldTypes["Computed"] = 12] = "Computed";
FieldTypes[FieldTypes["Threading"] = 13] = "Threading";
FieldTypes[FieldTypes["Guid"] = 14] = "Guid";
FieldTypes[FieldTypes["MultiChoice"] = 15] = "MultiChoice";
FieldTypes[FieldTypes["GridChoice"] = 16] = "GridChoice";
FieldTypes[FieldTypes["Calculated"] = 17] = "Calculated";
FieldTypes[FieldTypes["File"] = 18] = "File";
FieldTypes[FieldTypes["Attachments"] = 19] = "Attachments";
FieldTypes[FieldTypes["User"] = 20] = "User";
FieldTypes[FieldTypes["Recurrence"] = 21] = "Recurrence";
FieldTypes[FieldTypes["CrossProjectLink"] = 22] = "CrossProjectLink";
FieldTypes[FieldTypes["ModStat"] = 23] = "ModStat";
FieldTypes[FieldTypes["Error"] = 24] = "Error";
FieldTypes[FieldTypes["ContentTypeId"] = 25] = "ContentTypeId";
FieldTypes[FieldTypes["PageSeparator"] = 26] = "PageSeparator";
FieldTypes[FieldTypes["ThreadIndex"] = 27] = "ThreadIndex";
FieldTypes[FieldTypes["WorkflowStatus"] = 28] = "WorkflowStatus";
FieldTypes[FieldTypes["AllDayEvent"] = 29] = "AllDayEvent";
FieldTypes[FieldTypes["WorkflowEventType"] = 30] = "WorkflowEventType";
})(exports.FieldTypes || (exports.FieldTypes = {}));
(function (DateTimeFieldFormatType) {
DateTimeFieldFormatType[DateTimeFieldFormatType["DateOnly"] = 0] = "DateOnly";
DateTimeFieldFormatType[DateTimeFieldFormatType["DateTime"] = 1] = "DateTime";
})(exports.DateTimeFieldFormatType || (exports.DateTimeFieldFormatType = {}));
(function (AddFieldOptions) {
/**
* Specify that a new field added to the list must also be added to the default content type in the site collection
*/
AddFieldOptions[AddFieldOptions["DefaultValue"] = 0] = "DefaultValue";
/**
* Specify that a new field added to the list must also be added to the default content type in the site collection.
*/
AddFieldOptions[AddFieldOptions["AddToDefaultContentType"] = 1] = "AddToDefaultContentType";
/**
* Specify that a new field must not be added to any other content type
*/
AddFieldOptions[AddFieldOptions["AddToNoContentType"] = 2] = "AddToNoContentType";
/**
* Specify that a new field that is added to the specified list must also be added to all content types in the site collection
*/
AddFieldOptions[AddFieldOptions["AddToAllContentTypes"] = 4] = "AddToAllContentTypes";
/**
* Specify adding an internal field name hint for the purpose of avoiding possible database locking or field renaming operations
*/
AddFieldOptions[AddFieldOptions["AddFieldInternalNameHint"] = 8] = "AddFieldInternalNameHint";
/**
* Specify that a new field that is added to the specified list must also be added to the default list view
*/
AddFieldOptions[AddFieldOptions["AddFieldToDefaultView"] = 16] = "AddFieldToDefaultView";
/**
* Specify to confirm that no other field has the same display name
*/
AddFieldOptions[AddFieldOptions["AddFieldCheckDisplayName"] = 32] = "AddFieldCheckDisplayName";
})(exports.AddFieldOptions || (exports.AddFieldOptions = {}));
(function (CalendarType) {
CalendarType[CalendarType["Gregorian"] = 1] = "Gregorian";
CalendarType[CalendarType["Japan"] = 3] = "Japan";
CalendarType[CalendarType["Taiwan"] = 4] = "Taiwan";
CalendarType[CalendarType["Korea"] = 5] = "Korea";
CalendarType[CalendarType["Hijri"] = 6] = "Hijri";
CalendarType[CalendarType["Thai"] = 7] = "Thai";
CalendarType[CalendarType["Hebrew"] = 8] = "Hebrew";
CalendarType[CalendarType["GregorianMEFrench"] = 9] = "GregorianMEFrench";
CalendarType[CalendarType["GregorianArabic"] = 10] = "GregorianArabic";
CalendarType[CalendarType["GregorianXLITEnglish"] = 11] = "GregorianXLITEnglish";
CalendarType[CalendarType["GregorianXLITFrench"] = 12] = "GregorianXLITFrench";
CalendarType[CalendarType["KoreaJapanLunar"] = 14] = "KoreaJapanLunar";
CalendarType[CalendarType["ChineseLunar"] = 15] = "ChineseLunar";
CalendarType[CalendarType["SakaEra"] = 16] = "SakaEra";
CalendarType[CalendarType["UmAlQura"] = 23] = "UmAlQura";
})(exports.CalendarType || (exports.CalendarType = {}));
(function (UrlFieldFormatType) {
UrlFieldFormatType[UrlFieldFormatType["Hyperlink"] = 0] = "Hyperlink";
UrlFieldFormatType[UrlFieldFormatType["Image"] = 1] = "Image";
})(exports.UrlFieldFormatType || (exports.UrlFieldFormatType = {}));
(function (PermissionKind) {
/**
* Has no permissions on the Site. Not available through the user interface.
*/
PermissionKind[PermissionKind["EmptyMask"] = 0] = "EmptyMask";
/**
* View items in lists, documents in document libraries, and Web discussion comments.
*/
PermissionKind[PermissionKind["ViewListItems"] = 1] = "ViewListItems";
/**
* Add items to lists, documents to document libraries, and Web discussion comments.
*/
PermissionKind[PermissionKind["AddListItems"] = 2] = "AddListItems";
/**
* Edit items in lists, edit documents in document libraries, edit Web discussion comments
* in documents, and customize Web Part Pages in document libraries.
*/
PermissionKind[PermissionKind["EditListItems"] = 3] = "EditListItems";
/**
* Delete items from a list, documents from a document library, and Web discussion
* comments in documents.
*/
PermissionKind[PermissionKind["DeleteListItems"] = 4] = "DeleteListItems";
/**
* Approve a minor version of a list item or document.
*/
PermissionKind[PermissionKind["ApproveItems"] = 5] = "ApproveItems";
/**
* View the source of documents with server-side file handlers.
*/
PermissionKind[PermissionKind["OpenItems"] = 6] = "OpenItems";
/**
* View past versions of a list item or document.
*/
PermissionKind[PermissionKind["ViewVersions"] = 7] = "ViewVersions";
/**
* Delete past versions of a list item or document.
*/
PermissionKind[PermissionKind["DeleteVersions"] = 8] = "DeleteVersions";
/**
* Discard or check in a document which is checked out to another user.
*/
PermissionKind[PermissionKind["CancelCheckout"] = 9] = "CancelCheckout";
/**
* Create, change, and delete personal views of lists.
*/
PermissionKind[PermissionKind["ManagePersonalViews"] = 10] = "ManagePersonalViews";
/**
* Create and delete lists, add or remove columns in a list, and add or remove public views of a list.
*/
PermissionKind[PermissionKind["ManageLists"] = 12] = "ManageLists";
/**
* View forms, views, and application pages, and enumerate lists.
*/
PermissionKind[PermissionKind["ViewFormPages"] = 13] = "ViewFormPages";
/**
* Make content of a list or document library retrieveable for anonymous users through SharePoint search.
* The list permissions in the site do not change.
*/
PermissionKind[PermissionKind["AnonymousSearchAccessList"] = 14] = "AnonymousSearchAccessList";
/**
* Allow users to open a Site, list, or folder to access items inside that container.
*/
PermissionKind[PermissionKind["Open"] = 17] = "Open";
/**
* View pages in a Site.
*/
PermissionKind[PermissionKind["ViewPages"] = 18] = "ViewPages";
/**
* Add, change, or delete HTML pages or Web Part Pages, and edit the Site using
* a Windows SharePoint Services compatible editor.
*/
PermissionKind[PermissionKind["AddAndCustomizePages"] = 19] = "AddAndCustomizePages";
/**
* Apply a theme or borders to the entire Site.
*/
PermissionKind[PermissionKind["ApplyThemeAndBorder"] = 20] = "ApplyThemeAndBorder";
/**
* Apply a style sheet (.css file) to the Site.
*/
PermissionKind[PermissionKind["ApplyStyleSheets"] = 21] = "ApplyStyleSheets";
/**
* View reports on Site usage.
*/
PermissionKind[PermissionKind["ViewUsageData"] = 22] = "ViewUsageData";
/**
* Create a Site using Self-Service Site Creation.
*/
PermissionKind[PermissionKind["CreateSSCSite"] = 23] = "CreateSSCSite";
/**
* Create subsites such as team sites, Meeting Workspace sites, and Document Workspace sites.
*/
PermissionKind[PermissionKind["ManageSubwebs"] = 24] = "ManageSubwebs";
/**
* Create a group of users that can be used anywhere within the site collection.
*/
PermissionKind[PermissionKind["CreateGroups"] = 25] = "CreateGroups";
/**
* Create and change permission levels on the Site and assign permissions to users
* and groups.
*/
PermissionKind[PermissionKind["ManagePermissions"] = 26] = "ManagePermissions";
/**
* Enumerate files and folders in a Site using Microsoft Office SharePoint Designer
* and WebDAV interfaces.
*/
PermissionKind[PermissionKind["BrowseDirectories"] = 27] = "BrowseDirectories";
/**
* View information about users of the Site.
*/
PermissionKind[PermissionKind["BrowseUserInfo"] = 28] = "BrowseUserInfo";
/**
* Add or remove personal Web Parts on a Web Part Page.
*/
PermissionKind[PermissionKind["AddDelPrivateWebParts"] = 29] = "AddDelPrivateWebParts";
/**
* Update Web Parts to display personalized information.
*/
PermissionKind[PermissionKind["UpdatePersonalWebParts"] = 30] = "UpdatePersonalWebParts";
/**
* Grant the ability to perform all administration tasks for the Site as well as
* manage content, activate, deactivate, or edit properties of Site scoped Features
* through the object model or through the user interface (UI). When granted on the
* root Site of a Site Collection, activate, deactivate, or edit properties of
* site collection scoped Features through the object model. To browse to the Site
* Collection Features page and activate or deactivate Site Collection scoped Features
* through the UI, you must be a Site Collection administrator.
*/
PermissionKind[PermissionKind["ManageWeb"] = 31] = "ManageWeb";
/**
* Content of lists and document libraries in the Web site will be retrieveable for anonymous users through
* SharePoint search if the list or document library has AnonymousSearchAccessList set.
*/
PermissionKind[PermissionKind["AnonymousSearchAccessWebLists"] = 32] = "AnonymousSearchAccessWebLists";
/**
* Use features that launch client applications. Otherwise, users must work on documents
* locally and upload changes.
*/
PermissionKind[PermissionKind["UseClientIntegration"] = 37] = "UseClientIntegration";
/**
* Use SOAP, WebDAV, or Microsoft Office SharePoint Designer interfaces to access the Site.
*/
PermissionKind[PermissionKind["UseRemoteAPIs"] = 38] = "UseRemoteAPIs";
/**
* Manage alerts for all users of the Site.
*/
PermissionKind[PermissionKind["ManageAlerts"] = 39] = "ManageAlerts";
/**
* Create e-mail alerts.
*/
PermissionKind[PermissionKind["CreateAlerts"] = 40] = "CreateAlerts";
/**
* Allows a user to change his or her user information, such as adding a picture.
*/
PermissionKind[PermissionKind["EditMyUserInfo"] = 41] = "EditMyUserInfo";
/**
* Enumerate permissions on Site, list, folder, document, or list item.
*/
PermissionKind[PermissionKind["EnumeratePermissions"] = 63] = "EnumeratePermissions";
/**
* Has all permissions on the Site. Not available through the user interface.
*/
PermissionKind[PermissionKind["FullMask"] = 65] = "FullMask";
})(exports.PermissionKind || (exports.PermissionKind = {}));
(function (PrincipalType) {
/**
* Enumeration whose value specifies no principal type.
*/
PrincipalType[PrincipalType["None"] = 0] = "None";
/**
* Enumeration whose value specifies a user as the principal type.
*/
PrincipalType[PrincipalType["User"] = 1] = "User";
/**
* Enumeration whose value specifies a distribution list as the principal type.
*/
PrincipalType[PrincipalType["DistributionList"] = 2] = "DistributionList";
/**
* Enumeration whose value specifies a security group as the principal type.
*/
PrincipalType[PrincipalType["SecurityGroup"] = 4] = "SecurityGroup";
/**
* Enumeration whose value specifies a group as the principal type.
*/
PrincipalType[PrincipalType["SharePointGroup"] = 8] = "SharePointGroup";
/**
* Enumeration whose value specifies all principal types.
*/
PrincipalType[PrincipalType["All"] = 15] = "All";
})(exports.PrincipalType || (exports.PrincipalType = {}));
(function (PrincipalSource) {
/**
* Enumeration whose value specifies no principal source.
*/
PrincipalSource[PrincipalSource["None"] = 0] = "None";
/**
* Enumeration whose value specifies user information list as the principal source.
*/
PrincipalSource[PrincipalSource["UserInfoList"] = 1] = "UserInfoList";
/**
* Enumeration whose value specifies Active Directory as the principal source.
*/
PrincipalSource[PrincipalSource["Windows"] = 2] = "Windows";
/**
* Enumeration whose value specifies the current membership provider as the principal source.
*/
PrincipalSource[PrincipalSource["MembershipProvider"] = 4] = "MembershipProvider";
/**
* Enumeration whose value specifies the current role provider as the principal source.
*/
PrincipalSource[PrincipalSource["RoleProvider"] = 8] = "RoleProvider";
/**
* Enumeration whose value specifies all principal sources.
*/
PrincipalSource[PrincipalSource["All"] = 15] = "All";
})(exports.PrincipalSource || (exports.PrincipalSource = {}));
(function (RoleType) {
RoleType[RoleType["None"] = 0] = "None";
RoleType[RoleType["Guest"] = 1] = "Guest";
RoleType[RoleType["Reader"] = 2] = "Reader";
RoleType[RoleType["Contributor"] = 3] = "Contributor";
RoleType[RoleType["WebDesigner"] = 4] = "WebDesigner";
RoleType[RoleType["Administrator"] = 5] = "Administrator";
})(exports.RoleType || (exports.RoleType = {}));
(function (PageType) {
PageType[PageType["Invalid"] = -1] = "Invalid";
PageType[PageType["DefaultView"] = 0] = "DefaultView";
PageType[PageType["NormalView"] = 1] = "NormalView";
PageType[PageType["DialogView"] = 2] = "DialogView";
PageType[PageType["View"] = 3] = "View";
PageType[PageType["DisplayForm"] = 4] = "DisplayForm";
PageType[PageType["DisplayFormDialog"] = 5] = "DisplayFormDialog";
PageType[PageType["EditForm"] = 6] = "EditForm";
PageType[PageType["EditFormDialog"] = 7] = "EditFormDialog";
PageType[PageType["NewForm"] = 8] = "NewForm";
PageType[PageType["NewFormDialog"] = 9] = "NewFormDialog";
PageType[PageType["SolutionForm"] = 10] = "SolutionForm";
PageType[PageType["PAGE_MAXITEMS"] = 11] = "PAGE_MAXITEMS";
})(exports.PageType || (exports.PageType = {}));
(function (SharingLinkKind) {
/**
* Uninitialized link
*/
SharingLinkKind[SharingLinkKind["Uninitialized"] = 0] = "Uninitialized";
/**
* Direct link to the object being shared
*/
SharingLinkKind[SharingLinkKind["Direct"] = 1] = "Direct";
/**
* Organization-shareable link to the object being shared with view permissions
*/
SharingLinkKind[SharingLinkKind["OrganizationView"] = 2] = "OrganizationView";
/**
* Organization-shareable link to the object being shared with edit permissions
*/
SharingLinkKind[SharingLinkKind["OrganizationEdit"] = 3] = "OrganizationEdit";
/**
* View only anonymous link
*/
SharingLinkKind[SharingLinkKind["AnonymousView"] = 4] = "AnonymousView";
/**
* Read/Write anonymous link
*/
SharingLinkKind[SharingLinkKind["AnonymousEdit"] = 5] = "AnonymousEdit";
/**
* Flexible sharing Link where properties can change without affecting link URL
*/
SharingLinkKind[SharingLinkKind["Flexible"] = 6] = "Flexible";
})(exports.SharingLinkKind || (exports.SharingLinkKind = {}));
(function (SharingRole) {
SharingRole[SharingRole["None"] = 0] = "None";
SharingRole[SharingRole["View"] = 1] = "View";
SharingRole[SharingRole["Edit"] = 2] = "Edit";
SharingRole[SharingRole["Owner"] = 3] = "Owner";
})(exports.SharingRole || (exports.SharingRole = {}));
(function (SharingOperationStatusCode) {
/**
* The share operation completed without errors.
*/
SharingOperationStatusCode[SharingOperationStatusCode["CompletedSuccessfully"] = 0] = "CompletedSuccessfully";
/**
* The share operation completed and generated requests for access.
*/
SharingOperationStatusCode[SharingOperationStatusCode["AccessRequestsQueued"] = 1] = "AccessRequestsQueued";
/**
* The share operation failed as there were no resolved users.
*/
SharingOperationStatusCode[SharingOperationStatusCode["NoResolvedUsers"] = -1] = "NoResolvedUsers";
/**
* The share operation failed due to insufficient permissions.
*/
SharingOperationStatusCode[SharingOperationStatusCode["AccessDenied"] = -2] = "AccessDenied";
/**
* The share operation failed when attempting a cross site share, which is not supported.
*/
SharingOperationStatusCode[SharingOperationStatusCode["CrossSiteRequestNotSupported"] = -3] = "CrossSiteRequestNotSupported";
/**
* The sharing operation failed due to an unknown error.
*/
SharingOperationStatusCode[SharingOperationStatusCode["UnknowError"] = -4] = "UnknowError";
/**
* The text you typed is too long. Please shorten it.
*/
SharingOperationStatusCode[SharingOperationStatusCode["EmailBodyTooLong"] = -5] = "EmailBodyTooLong";
/**
* The maximum number of unique scopes in the list has been exceeded.
*/
SharingOperationStatusCode[SharingOperationStatusCode["ListUniqueScopesExceeded"] = -6] = "ListUniqueScopesExceeded";
/**
* The share operation failed because a sharing capability is disabled in the site.
*/
SharingOperationStatusCode[SharingOperationStatusCode["CapabilityDisabled"] = -7] = "CapabilityDisabled";
/**
* The specified object for the share operation is not supported.
*/
SharingOperationStatusCode[SharingOperationStatusCode["ObjectNotSupported"] = -8] = "ObjectNotSupported";
/**
* A SharePoint group cannot contain another SharePoint group.
*/
SharingOperationStatusCode[SharingOperationStatusCode["NestedGroupsNotSupported"] = -9] = "NestedGroupsNotSupported";
})(exports.SharingOperationStatusCode || (exports.SharingOperationStatusCode = {}));
(function (SPSharedObjectType) {
SPSharedObjectType[SPSharedObjectType["Unknown"] = 0] = "Unknown";
SPSharedObjectType[SPSharedObjectType["File"] = 1] = "File";
SPSharedObjectType[SPSharedObjectType["Folder"] = 2] = "Folder";
SPSharedObjectType[SPSharedObjectType["Item"] = 3] = "Item";
SPSharedObjectType[SPSharedObjectType["List"] = 4] = "List";
SPSharedObjectType[SPSharedObjectType["Web"] = 5] = "Web";
SPSharedObjectType[SPSharedObjectType["Max"] = 6] = "Max";
})(exports.SPSharedObjectType || (exports.SPSharedObjectType = {}));
(function (SharingDomainRestrictionMode) {
SharingDomainRestrictionMode[SharingDomainRestrictionMode["None"] = 0] = "None";
SharingDomainRestrictionMode[SharingDomainRestrictionMode["AllowList"] = 1] = "AllowList";
SharingDomainRestrictionMode[SharingDomainRestrictionMode["BlockList"] = 2] = "BlockList";
})(exports.SharingDomainRestrictionMode || (exports.SharingDomainRestrictionMode = {}));
(function (RenderListDataOptions) {
RenderListDataOptions[RenderListDataOptions["None"] = 0] = "None";
RenderListDataOptions[RenderListDataOptions["ContextInfo"] = 1] = "ContextInfo";
RenderListDataOptions[RenderListDataOptions["ListData"] = 2] = "ListData";
RenderListDataOptions[RenderListDataOptions["ListSchema"] = 4] = "ListSchema";
RenderListDataOptions[RenderListDataOptions["MenuView"] = 8] = "MenuView";
RenderListDataOptions[RenderListDataOptions["ListContentType"] = 16] = "ListContentType";
RenderListDataOptions[RenderListDataOptions["FileSystemItemId"] = 32] = "FileSystemItemId";
RenderListDataOptions[RenderListDataOptions["ClientFormSchema"] = 64] = "ClientFormSchema";
RenderListDataOptions[RenderListDataOptions["QuickLaunch"] = 128] = "QuickLaunch";
RenderListDataOptions[RenderListDataOptions["Spotlight"] = 256] = "Spotlight";
RenderListDataOptions[RenderListDataOptions["Visualization"] = 512] = "Visualization";
RenderListDataOptions[RenderListDataOptions["ViewMetadata"] = 1024] = "ViewMetadata";
RenderListDataOptions[RenderListDataOptions["DisableAutoHyperlink"] = 2048] = "DisableAutoHyperlink";
RenderListDataOptions[RenderListDataOptions["EnableMediaTAUrls"] = 4096] = "EnableMediaTAUrls";
RenderListDataOptions[RenderListDataOptions["ParentInfo"] = 8192] = "ParentInfo";
RenderListDataOptions[RenderListDataOptions["PageContextInfo"] = 16384] = "PageContextInfo";
RenderListDataOptions[RenderListDataOptions["ClientSideComponentManifest"] = 32768] = "ClientSideComponentManifest";
})(exports.RenderListDataOptions || (exports.RenderListDataOptions = {}));
(function (FieldUserSelectionMode) {
FieldUserSelectionMode[FieldUserSelectionMode["PeopleAndGroups"] = 1] = "PeopleAndGroups";
FieldUserSelectionMode[FieldUserSelectionMode["PeopleOnly"] = 0] = "PeopleOnly";
})(exports.FieldUserSelectionMode || (exports.FieldUserSelectionMode = {}));
(function (ChoiceFieldFormatType) {
ChoiceFieldFormatType[ChoiceFieldFormatType["Dropdown"] = 0] = "Dropdown";
ChoiceFieldFormatType[ChoiceFieldFormatType["RadioButtons"] = 1] = "RadioButtons";
})(exports.ChoiceFieldFormatType || (exports.ChoiceFieldFormatType = {}));
(function (UrlZone) {
/**
* Specifies the default zone used for requests unless another zone is specified.
*/
UrlZone[UrlZone["DefaultZone"] = 0] = "DefaultZone";
/**
* Specifies an intranet zone.
*/
UrlZone[UrlZone["Intranet"] = 1] = "Intranet";
/**
* Specifies an Internet zone.
*/
UrlZone[UrlZone["Internet"] = 2] = "Internet";
/**
* Specifies a custom zone.
*/
UrlZone[UrlZone["Custom"] = 3] = "Custom";
/**
* Specifies an extranet zone.
*/
UrlZone[UrlZone["Extranet"] = 4] = "Extranet";
})(exports.UrlZone || (exports.UrlZone = {}));
var SharePointQueryableSecurable = /** @class */ (function (_super) {
__extends(SharePointQueryableSecurable, _super);
function SharePointQueryableSecurable() {
return _super !== null && _super.apply(this, arguments) || this;
}
Object.defineProperty(SharePointQueryableSecurable.prototype, "roleAssignments", {
/**
* Gets the set of role assignments for this item
*
*/
get: function () {
return new RoleAssignments(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(SharePointQueryableSecurable.prototype, "firstUniqueAncestorSecurableObject", {
/**
* Gets the closest securable up the security hierarchy whose permissions are applied to this list item
*
*/
get: function () {
return new SharePointQueryableInstance(this, "FirstUniqueAncestorSecurableObject");
},
enumerable: true,
configurable: true
});
/**
* Gets the effective permissions for the user supplied
*
* @param loginName The claims username for the user (ex: i:0#.f|membership|user@domain.com)
*/
SharePointQueryableSecurable.prototype.getUserEffectivePermissions = function (loginName) {
var q = this.clone(SharePointQueryable, "getUserEffectivePermissions(@user)");
q.query.set("@user", "'" + encodeURIComponent(loginName) + "'");
return q.get().then(function (r) {
// handle verbose mode
return common.hOP(r, "GetUserEffectivePermissions") ? r.GetUserEffectivePermissions : r;
});
};
/**
* Gets the effective permissions for the current user
*/
SharePointQueryableSecurable.prototype.getCurrentUserEffectivePermissions = function () {
var _this = this;
// remove need to reference Web here, which created a circular build issue
var w = new SharePointQueryableInstance("_api/web", "currentuser");
return w.configureFrom(this).select("LoginName").get().then(function (user) {
return _this.getUserEffectivePermissions(user.LoginName);
});
};
/**
* Breaks the security inheritance at this level optinally copying permissions and clearing subscopes
*
* @param copyRoleAssignments If true the permissions are copied from the current parent scope
* @param clearSubscopes Optional. true to make all child securable objects inherit role assignments from the current object
*/
SharePointQueryableSecurable.prototype.breakRoleInheritance = function (copyRoleAssignments, clearSubscopes) {
if (copyRoleAssignments === void 0) { copyRoleAssignments = false; }
if (clearSubscopes === void 0) { clearSubscopes = false; }
return this.clone(SharePointQueryableSecurable, "breakroleinheritance(copyroleassignments=" + copyRoleAssignments + ", clearsubscopes=" + clearSubscopes + ")").postCore();
};
/**
* Removes the local role assignments so that it re-inherit role assignments from the parent object.
*
*/
SharePointQueryableSecurable.prototype.resetRoleInheritance = function () {
return this.clone(SharePointQueryableSecurable, "resetroleinheritance").postCore();
};
/**
* Determines if a given user has the appropriate permissions
*
* @param loginName The user to check
* @param permission The permission being checked
*/
SharePointQueryableSecurable.prototype.userHasPermissions = function (loginName, permission) {
var _this = this;
return this.getUserEffectivePermissions(loginName).then(function (perms) {
return _this.hasPermissions(perms, permission);
});
};
/**
* Determines if the current user has the requested permissions
*
* @param permission The permission we wish to check
*/
SharePointQueryableSecurable.prototype.currentUserHasPermissions = function (permission) {
var _this = this;
return this.getCurrentUserEffectivePermissions().then(function (perms) {
return _this.hasPermissions(perms, permission);
});
};
/**
* Taken from sp.js, checks the supplied permissions against the mask
*
* @param value The security principal's permissions on the given object
* @param perm The permission checked against the value
*/
/* tslint:disable:no-bitwise */
SharePointQueryableSecurable.prototype.hasPermissions = function (value, perm) {
if (!perm) {
return true;
}
if (perm === exports.PermissionKind.FullMask) {
return (value.High & 32767) === 32767 && value.Low === 65535;
}
perm = perm - 1;
var num = 1;
if (perm >= 0 && perm < 32) {
num = num << perm;
return 0 !== (value.Low & num);
}
else if (perm >= 32 && perm < 64) {
num = num << perm - 32;
return 0 !== (value.High & num);
}
return false;
};
return SharePointQueryableSecurable;
}(SharePointQueryableInstance));
/**
* Internal helper class used to augment classes to include sharing functionality
*/
var SharePointQueryableShareable = /** @class */ (function (_super) {
__extends(SharePointQueryableShareable, _super);
function SharePointQueryableShareable() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Gets a sharing link for the supplied
*
* @param kind The kind of link to share
* @param expiration The optional expiration for this link
*/
SharePointQueryableShareable.prototype.getShareLink = function (kind, expiration) {
if (expiration === void 0) { expiration = null; }
// date needs to be an ISO string or null
var expString = expiration !== null ? expiration.toISOString() : null;
// clone using the factory and send the request
return this.clone(SharePointQueryableShareable, "shareLink").postCore({
body: common.jsS({
request: {
createLink: true,
emailData: null,
settings: {
expiration: expString,
linkKind: kind,
},
},
}),
});
};
/**
* Shares this instance with the supplied users
*
* @param loginNames Resolved login names to share
* @param role The role
* @param requireSignin True to require the user is authenticated, otherwise false
* @param propagateAcl True to apply this share to all children
* @param emailData If supplied an email will be sent with the indicated properties
*/
SharePointQueryableShareable.prototype.shareWith = function (loginNames, role, requireSignin, propagateAcl, emailData) {
var _this = this;
if (requireSignin === void 0) { requireSignin = false; }
if (propagateAcl === void 0) { propagateAcl = false; }
// handle the multiple input types
if (!Array.isArray(loginNames)) {
loginNames = [loginNames];
}
var userStr = common.jsS(loginNames.map(function (login) { return { Key: login }; }));
var roleFilter = role === exports.SharingRole.Edit ? exports.RoleType.Contributor : exports.RoleType.Reader;
// start by looking up the role definition id we need to set the roleValue
// remove need to reference Web here, which created a circular build issue
var w = new SharePointQueryableCollection("_api/web", "roledefinitions");
return w.select("Id").filter("RoleTypeKind eq " + roleFilter).get().then(function (def) {
if (!Array.isArray(def) || def.length < 1) {
throw Error("Could not locate a role defintion with RoleTypeKind " + roleFilter);
}
var postBody = {
includeAnonymousLinkInEmail: requireSignin,
peoplePickerInput: userStr,
propagateAcl: propagateAcl,
roleValue: "role:" + def[0].Id,
useSimplifiedRoles: true,
};
if (emailData !== undefined) {
postBody = common.extend(postBody, {
emailBody: emailData.body,
emailSubject: emailData.subject !== undefined ? emailData.subject : "",
sendEmail: true,
});
}
return _this.clone(SharePointQueryableShareable, "shareObject").postCore({
body: common.jsS(postBody),
});
});
};
/**
* Shares an object based on the supplied options
*
* @param options The set of options to send to the ShareObject method
* @param bypass If true any processing is skipped and the options are sent directly to the ShareObject method
*/
SharePointQueryableShareable.prototype.shareObject = function (options, bypass) {
var _this = this;
if (bypass === void 0) { bypass = false; }
if (bypass) {
// if the bypass flag is set send the supplied parameters directly to the service
return this.sendShareObjectRequest(options);
}
// extend our options with some defaults
options = common.extend(options, {
group: null,
includeAnonymousLinkInEmail: false,
propagateAcl: false,
useSimplifiedRoles: true,
}, true);
return this.getRoleValue(options.role, options.group).then(function (roleValue) {
// handle the multiple input types
if (!Array.isArray(options.loginNames)) {
options.loginNames = [options.loginNames];
}
var userStr = common.jsS(options.loginNames.map(function (login) { return { Key: login }; }));
var postBody = {
peoplePickerInput: userStr,
roleValue: roleValue,
url: options.url,
};
if (options.emailData !== undefined && options.emailData !== null) {
postBody = common.extend(postBody, {
emailBody: options.emailData.body,
emailSubject: options.emailData.subject !== undefined ? options.emailData.subject : "Shared with you.",
sendEmail: true,
});
}
return _this.sendShareObjectRequest(postBody);
});
};
/**
* Calls the web's UnshareObject method
*
* @param url The url of the object to unshare
*/
SharePointQueryableShareable.prototype.unshareObjectWeb = function (url) {
return this.clone(SharePointQueryableShareable, "unshareObject").postCore({
body: common.jsS({
url: url,
}),
});
};
/**
* Checks Permissions on the list of Users and returns back role the users have on the Item.
*
* @param recipients The array of Entities for which Permissions need to be checked.
*/
SharePointQueryableShareable.prototype.checkPermissions = function (recipients) {
return this.clone(SharePointQueryableShareable, "checkPermissions").postCore({
body: common.jsS({
recipients: recipients,
}),
});
};
/**
* Get Sharing Information.
*
* @param request The SharingInformationRequest Object.
* @param expands Expand more fields.
*
*/
SharePointQueryableShareable.prototype.getSharingInformation = function (request, expands) {
if (request === void 0) { request = null; }
var q = this.clone(SharePointQueryableShareable, "getSharingInformation");
return q.expand.apply(q, expands).postCore({
body: common.jsS({
request: request,
}),
});
};
/**
* Gets the sharing settings of an item.
*
* @param useSimplifiedRoles Determines whether to use simplified roles.
*/
SharePointQueryableShareable.prototype.getObjectSharingSettings = function (useSimplifiedRoles) {
if (useSimplifiedRoles === void 0) { useSimplifiedRoles = true; }
return this.clone(SharePointQueryableShareable, "getObjectSharingSettings").postCore({
body: common.jsS({
useSimplifiedRoles: useSimplifiedRoles,
}),
});
};
/**
* Unshares this object
*/
SharePointQueryableShareable.prototype.unshareObject = function () {
return this.clone(SharePointQueryableShareable, "unshareObject").postCore();
};
/**
* Deletes a link by type
*
* @param kind Deletes a sharing link by the kind of link
*/
SharePointQueryableShareable.prototype.deleteLinkByKind = function (kind) {
return this.clone(SharePointQueryableShareable, "deleteLinkByKind").postCore({
body: common.jsS({ linkKind: kind }),
});
};
/**
* Removes the specified link to the item.
*
* @param kind The kind of link to be deleted.
* @param shareId
*/
SharePointQueryableShareable.prototype.unshareLink = function (kind, shareId) {
if (shareId === void 0) { shareId = "00000000-0000-0000-0000-000000000000"; }
return this.clone(SharePointQueryableShareable, "unshareLink").postCore({
body: common.jsS({ linkKind: kind, shareId: shareId }),
});
};
/**
* Calculates the roleValue string used in the sharing query
*
* @param role The Sharing Role
* @param group The Group type
*/
SharePointQueryableShareable.prototype.getRoleValue = function (role, group) {
// we will give group precedence, because we had to make a choice
if (group !== undefined && group !== null) {
switch (group) {
case exports.RoleType.Contributor:
// remove need to reference Web here, which created a circular build issue
var memberGroup = new SharePointQueryableInstance("_api/web", "associatedmembergroup");
return memberGroup.select("Id").get().then(function (g) { return "group: " + g.Id; });
case exports.RoleType.Reader:
case exports.RoleType.Guest:
// remove need to reference Web here, which created a circular build issue
var visitorGroup = new SharePointQueryableInstance("_api/web", "associatedvisitorgroup");
return visitorGroup.select("Id").get().then(function (g) { return "group: " + g.Id; });
default:
throw Error("Could not determine role value for supplied value. Contributor, Reader, and Guest are supported");
}
}
else {
var roleFilter = role === exports.SharingRole.Edit ? exports.RoleType.Contributor : exports.RoleType.Reader;
// remove need to reference Web here, which created a circular build issue
var roleDefs = new SharePointQueryableCollection("_api/web", "roledefinitions");
return roleDefs.select("Id").top(1).filter("RoleTypeKind eq " + roleFilter).get().then(function (def) {
if (def.length < 1) {
throw Error("Could not locate associated role definition for supplied role. Edit and View are supported");
}
return "role: " + def[0].Id;
});
}
};
SharePointQueryableShareable.prototype.getShareObjectWeb = function (candidate) {
return Promise.resolve(new SharePointQueryableInstance(extractWebUrl(candidate), "/_api/SP.Web.ShareObject"));
};
SharePointQueryableShareable.prototype.sendShareObjectRequest = function (options) {
return this.getShareObjectWeb(this.toUrl()).then(function (web) {
return web.expand("UsersWithAccessRequests", "GroupsSharedWith").as(SharePointQueryableShareable).postCore({
body: common.jsS(options),
});
});
};
return SharePointQueryableShareable;
}(SharePointQueryable));
var SharePointQueryableShareableWeb = /** @class */ (function (_super) {
__extends(SharePointQueryableShareableWeb, _super);
function SharePointQueryableShareableWeb() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Shares this web with the supplied users
* @param loginNames The resolved login names to share
* @param role The role to share this web
* @param emailData Optional email data
*/
SharePointQueryableShareableWeb.prototype.shareWith = function (loginNames, role, emailData) {
var _this = this;
if (role === void 0) { role = exports.SharingRole.View; }
var dependency = this.addBatchDependency();
// remove need to reference Web here, which created a circular build issue
var web = new SharePointQueryableInstance(extractWebUrl(this.toUrl()), "/_api/web/url");
return web.get().then(function (url) {
dependency();
return _this.shareObject(common.combine(url, "/_layouts/15/aclinv.aspx?forSharing=1&mbypass=1"), loginNames, role, emailData);
});
};
/**
* Provides direct access to the static web.ShareObject method
*
* @param url The url to share
* @param loginNames Resolved loginnames string[] of a single login name string
* @param roleValue Role value
* @param emailData Optional email data
* @param groupId Optional group id
* @param propagateAcl
* @param includeAnonymousLinkInEmail
* @param useSimplifiedRoles
*/
SharePointQueryableShareableWeb.prototype.shareObject = function (url, loginNames, role, emailData, group, propagateAcl, includeAnonymousLinkInEmail, useSimplifiedRoles) {
if (propagateAcl === void 0) { propagateAcl = false; }
if (includeAnonymousLinkInEmail === void 0) { includeAnonymousLinkInEmail = false; }
if (useSimplifiedRoles === void 0) { useSimplifiedRoles = true; }
return this.clone(SharePointQueryableShareable, null).shareObject({
emailData: emailData,
group: group,
includeAnonymousLinkInEmail: includeAnonymousLinkInEmail,
loginNames: loginNames,
propagateAcl: propagateAcl,
role: role,
url: url,
useSimplifiedRoles: useSimplifiedRoles,
});
};
/**
* Supplies a method to pass any set of arguments to ShareObject
*
* @param options The set of options to send to ShareObject
*/
SharePointQueryableShareableWeb.prototype.shareObjectRaw = function (options) {
return this.clone(SharePointQueryableShareable, null).shareObject(options, true);
};
/**
* Unshares the object
*
* @param url The url of the object to stop sharing
*/
SharePointQueryableShareableWeb.prototype.unshareObject = function (url) {
return this.clone(SharePointQueryableShareable, null).unshareObjectWeb(url);
};
return SharePointQueryableShareableWeb;
}(SharePointQueryableSecurable));
var SharePointQueryableShareableItem = /** @class */ (function (_super) {
__extends(SharePointQueryableShareableItem, _super);
function SharePointQueryableShareableItem() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Gets a link suitable for sharing for this item
*
* @param kind The type of link to share
* @param expiration The optional expiration date
*/
SharePointQueryableShareableItem.prototype.getShareLink = function (kind, expiration) {
if (kind === void 0) { kind = exports.SharingLinkKind.OrganizationView; }
if (expiration === void 0) { expiration = null; }
return this.clone(SharePointQueryableShareable, null).getShareLink(kind, expiration);
};
/**
* Shares this item with one or more users
*
* @param loginNames string or string[] of resolved login names to which this item will be shared
* @param role The role (View | Edit) applied to the share
* @param emailData Optional, if inlucded an email will be sent. Note subject currently has no effect.
*/
SharePointQueryableShareableItem.prototype.shareWith = function (loginNames, role, requireSignin, emailData) {
if (role === void 0) { role = exports.SharingRole.View; }
if (requireSignin === void 0) { requireSignin = false; }
return this.clone(SharePointQueryableShareable, null).shareWith(loginNames, role, requireSignin, false, emailData);
};
/**
* Checks Permissions on the list of Users and returns back role the users have on the Item.
*
* @param recipients The array of Entities for which Permissions need to be checked.
*/
SharePointQueryableShareableItem.prototype.checkSharingPermissions = function (recipients) {
return this.clone(SharePointQueryableShareable, null).checkPermissions(recipients);
};
/**
* Get Sharing Information.
*
* @param request The SharingInformationRequest Object.
* @param expands Expand more fields.
*
*/
SharePointQueryableShareableItem.prototype.getSharingInformation = function (request, expands) {
if (request === void 0) { request = null; }
return this.clone(SharePointQueryableShareable, null).getSharingInformation(request, expands);
};
/**
* Gets the sharing settings of an item.
*
* @param useSimplifiedRoles Determines whether to use simplified roles.
*/
SharePointQueryableShareableItem.prototype.getObjectSharingSettings = function (useSimplifiedRoles) {
if (useSimplifiedRoles === void 0) { useSimplifiedRoles = true; }
return this.clone(SharePointQueryableShareable, null).getObjectSharingSettings(useSimplifiedRoles);
};
/**
* Unshare this item
*/
SharePointQueryableShareableItem.prototype.unshare = function () {
return this.clone(SharePointQueryableShareable, null).unshareObject();
};
/**
* Deletes a sharing link by kind
*
* @param kind Deletes a sharing link by the kind of link
*/
SharePointQueryableShareableItem.prototype.deleteSharingLinkByKind = function (kind) {
return this.clone(SharePointQueryableShareable, null).deleteLinkByKind(kind);
};
/**
* Removes the specified link to the item.
*
* @param kind The kind of link to be deleted.
* @param shareId
*/
SharePointQueryableShareableItem.prototype.unshareLink = function (kind, shareId) {
return this.clone(SharePointQueryableShareable, null).unshareLink(kind, shareId);
};
return SharePointQueryableShareableItem;
}(SharePointQueryableSecurable));
var FileFolderShared = /** @class */ (function (_super) {
__extends(FileFolderShared, _super);
function FileFolderShared() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Gets a link suitable for sharing
*
* @param kind The kind of link to get
* @param expiration Optional, an expiration for this link
*/
FileFolderShared.prototype.getShareLink = function (kind, expiration) {
if (kind === void 0) { kind = exports.SharingLinkKind.OrganizationView; }
if (expiration === void 0) { expiration = null; }
var dependency = this.addBatchDependency();
return this.getShareable().then(function (shareable) {
dependency();
return shareable.getShareLink(kind, expiration);
});
};
/**
* Checks Permissions on the list of Users and returns back role the users have on the Item.
*
* @param recipients The array of Entities for which Permissions need to be checked.
*/
FileFolderShared.prototype.checkSharingPermissions = function (recipients) {
var dependency = this.addBatchDependency();
return this.getShareable().then(function (shareable) {
dependency();
return shareable.checkPermissions(recipients);
});
};
/**
* Get Sharing Information.
*
* @param request The SharingInformationRequest Object.
* @param expands Expand more fields.
*
*/
FileFolderShared.prototype.getSharingInformation = function (request, expands) {
if (request === void 0) { request = null; }
var dependency = this.addBatchDependency();
return this.getShareable().then(function (shareable) {
dependency();
return shareable.getSharingInformation(request, expands);
});
};
/**
* Gets the sharing settings of an item.
*
* @param useSimplifiedRoles Determines whether to use simplified roles.
*/
FileFolderShared.prototype.getObjectSharingSettings = function (useSimplifiedRoles) {
if (useSimplifiedRoles === void 0) { useSimplifiedRoles = true; }
var dependency = this.addBatchDependency();
return this.getShareable().then(function (shareable) {
dependency();
return shareable.getObjectSharingSettings(useSimplifiedRoles);
});
};
/**
* Unshare this item
*/
FileFolderShared.prototype.unshare = function () {
var dependency = this.addBatchDependency();
return this.getShareable().then(function (shareable) {
dependency();
return shareable.unshareObject();
});
};
/**
* Deletes a sharing link by the kind of link
*
* @param kind The kind of link to be deleted.
*/
FileFolderShared.prototype.deleteSharingLinkByKind = function (kind) {
var dependency = this.addBatchDependency();
return this.getShareable().then(function (shareable) {
dependency();
return shareable.deleteLinkByKind(kind);
});
};
/**
* Removes the specified link to the item.
*
* @param kind The kind of link to be deleted.
* @param shareId The share id to delete
*/
FileFolderShared.prototype.unshareLink = function (kind, shareId) {
var dependency = this.addBatchDependency();
return this.getShareable().then(function (shareable) {
dependency();
return shareable.unshareLink(kind, shareId);
});
};
/**
* For files and folders we need to use the associated item end point
*/
FileFolderShared.prototype.getShareable = function () {
var _this = this;
// sharing only works on the item end point, not the file one - so we create a folder instance with the item url internally
return this.clone(SharePointQueryableShareableFile, "listItemAllFields", false).select("odata.id").get().then(function (d) {
var shareable = new SharePointQueryableShareable(odataUrlFrom(d));
// we need to handle batching
if (_this.hasBatch) {
shareable = shareable.inBatch(_this.batch);
}
return shareable;
});
};
return FileFolderShared;
}(SharePointQueryableInstance));
var SharePointQueryableShareableFile = /** @class */ (function (_super) {
__extends(SharePointQueryableShareableFile, _super);
function SharePointQueryableShareableFile() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Shares this item with one or more users
*
* @param loginNames string or string[] of resolved login names to which this item will be shared
* @param role The role (View | Edit) applied to the share
* @param shareEverything Share everything in this folder, even items with unique permissions.
* @param requireSignin If true the user must signin to view link, otherwise anyone with the link can access the resource
* @param emailData Optional, if inlucded an email will be sent. Note subject currently has no effect.
*/
SharePointQueryableShareableFile.prototype.shareWith = function (loginNames, role, requireSignin, emailData) {
if (role === void 0) { role = exports.SharingRole.View; }
if (requireSignin === void 0) { requireSignin = false; }
var dependency = this.addBatchDependency();
return this.getShareable().then(function (shareable) {
dependency();
return shareable.shareWith(loginNames, role, requireSignin, false, emailData);
});
};
return SharePointQueryableShareableFile;
}(FileFolderShared));
var SharePointQueryableShareableFolder = /** @class */ (function (_super) {
__extends(SharePointQueryableShareableFolder, _super);
function SharePointQueryableShareableFolder() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Shares this item with one or more users
*
* @param loginNames string or string[] of resolved login names to which this item will be shared
* @param role The role (View | Edit) applied to the share
* @param shareEverything Share everything in this folder, even items with unique permissions.
* @param requireSignin If true the user must signin to view link, otherwise anyone with the link can access the resource
* @param emailData Optional, if inlucded an email will be sent. Note subject currently has no effect.
*/
SharePointQueryableShareableFolder.prototype.shareWith = function (loginNames, role, requireSignin, shareEverything, emailData) {
if (role === void 0) { role = exports.SharingRole.View; }
if (requireSignin === void 0) { requireSignin = false; }
if (shareEverything === void 0) { shareEverything = false; }
var dependency = this.addBatchDependency();
return this.getShareable().then(function (shareable) {
dependency();
return shareable.shareWith(loginNames, role, requireSignin, shareEverything, emailData);
});
};
return SharePointQueryableShareableFolder;
}(FileFolderShared));
var LimitedWebPartManager = /** @class */ (function (_super) {
__extends(LimitedWebPartManager, _super);
function LimitedWebPartManager() {
return _super !== null && _super.apply(this, arguments) || this;
}
Object.defineProperty(LimitedWebPartManager.prototype, "webparts", {
/**
* Gets the set of web part definitions contained by this web part manager
*
*/
get: function () {
return new WebPartDefinitions(this, "webparts");
},
enumerable: true,
configurable: true
});
/**
* Exports a webpart definition
*
* @param id the GUID id of the definition to export
*/
LimitedWebPartManager.prototype.export = function (id) {
return this.clone(LimitedWebPartManager, "ExportWebPart").postCore({
body: common.jsS({ webPartId: id }),
});
};
/**
* Imports a webpart
*
* @param xml webpart definition which must be valid XML in the .dwp or .webpart format
*/
LimitedWebPartManager.prototype.import = function (xml) {
return this.clone(LimitedWebPartManager, "ImportWebPart").postCore({
body: common.jsS({ webPartXml: xml }),
});
};
return LimitedWebPartManager;
}(SharePointQueryable));
var WebPartDefinitions = /** @class */ (function (_super) {
__extends(WebPartDefinitions, _super);
function WebPartDefinitions() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Gets a web part definition from the collection by id
*
* @param id The storage ID of the SPWebPartDefinition to retrieve
*/
WebPartDefinitions.prototype.getById = function (id) {
return new WebPartDefinition(this, "getbyid('" + id + "')");
};
/**
* Gets a web part definition from the collection by storage id
*
* @param id The WebPart.ID of the SPWebPartDefinition to retrieve
*/
WebPartDefinitions.prototype.getByControlId = function (id) {
return new WebPartDefinition(this, "getByControlId('" + id + "')");
};
return WebPartDefinitions;
}(SharePointQueryableCollection));
var WebPartDefinition = /** @class */ (function (_super) {
__extends(WebPartDefinition, _super);
function WebPartDefinition() {
return _super !== null && _super.apply(this, arguments) || this;
}
Object.defineProperty(WebPartDefinition.prototype, "webpart", {
/**
* Gets the webpart information associated with this definition
*/
get: function () {
return new WebPart(this);
},
enumerable: true,
configurable: true
});
/**
* Saves changes to the Web Part made using other properties and methods on the SPWebPartDefinition object
*/
WebPartDefinition.prototype.saveChanges = function () {
return this.clone(WebPartDefinition, "SaveWebPartChanges").postCore();
};
/**
* Moves the Web Part to a different location on a Web Part Page
*
* @param zoneId The ID of the Web Part Zone to which to move the Web Part
* @param zoneIndex A Web Part zone index that specifies the position at which the Web Part is to be moved within the destination Web Part zone
*/
WebPartDefinition.prototype.moveTo = function (zoneId, zoneIndex) {
return this.clone(WebPartDefinition, "MoveWebPartTo(zoneID='" + zoneId + "', zoneIndex=" + zoneIndex + ")").postCore();
};
/**
* Closes the Web Part. If the Web Part is already closed, this method does nothing
*/
WebPartDefinition.prototype.close = function () {
return this.clone(WebPartDefinition, "CloseWebPart").postCore();
};
/**
* Opens the Web Part. If the Web Part is already closed, this method does nothing
*/
WebPartDefinition.prototype.open = function () {
return this.clone(WebPartDefinition, "OpenWebPart").postCore();
};
/**
* Removes a webpart from a page, all settings will be lost
*/
WebPartDefinition.prototype.delete = function () {
return this.clone(WebPartDefinition, "DeleteWebPart").postCore();
};
return WebPartDefinition;
}(SharePointQueryableInstance));
var WebPart = /** @class */ (function (_super) {
__extends(WebPart, _super);
function WebPart() {
return _super !== null && _super.apply(this, arguments) || this;
}
WebPart = __decorate([
defaultPath("webpart")
], WebPart);
return WebPart;
}(SharePointQueryableInstance));
/**
* Describes a collection of Folder objects
*
*/
var Folders = /** @class */ (function (_super) {
__extends(Folders, _super);
function Folders() {
return _super !== null && _super.apply(this, arguments) || this;
}
Folders_1 = Folders;
/**
* Gets a folder by folder name
*
*/
Folders.prototype.getByName = function (name) {
var f = new Folder(this);
f.concat("('" + name + "')");
return f;
};
/**
* Adds a new folder to the current folder (relative) or any folder (absolute)
*
* @param url The relative or absolute url where the new folder will be created. Urls starting with a forward slash are absolute.
* @returns The new Folder and the raw response.
*/
Folders.prototype.add = function (url) {
var _this = this;
return this.clone(Folders_1, "add('" + url + "')").postCore().then(function (response) {
return {
data: response,
folder: _this.getByName(url),
};
});
};
var Folders_1;
Folders = Folders_1 = __decorate([
defaultPath("folders")
], Folders);
return Folders;
}(SharePointQueryableCollection));
/**
* Describes a single Folder instance
*
*/
var Folder = /** @class */ (function (_super) {
__extends(Folder, _super);
function Folder() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.update = _this._update("SP.Folder", function (data) { return ({ data: data, folder: _this }); });
return _this;
}
Object.defineProperty(Folder.prototype, "contentTypeOrder", {
/**
* Specifies the sequence in which content types are displayed.
*
*/
get: function () {
return new SharePointQueryableCollection(this, "contentTypeOrder");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Folder.prototype, "files", {
/**
* Gets this folder's files
*
*/
get: function () {
return new Files(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Folder.prototype, "folders", {
/**
* Gets this folder's sub folders
*
*/
get: function () {
return new Folders(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Folder.prototype, "listItemAllFields", {
/**
* Gets this folder's list item field values
*
*/
get: function () {
return new SharePointQueryableInstance(this, "listItemAllFields");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Folder.prototype, "parentFolder", {
/**
* Gets the parent folder, if available
*
*/
get: function () {
return new Folder(this, "parentFolder");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Folder.prototype, "properties", {
/**
* Gets this folder's properties
*
*/
get: function () {
return new SharePointQueryableInstance(this, "properties");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Folder.prototype, "serverRelativeUrl", {
/**
* Gets this folder's server relative url
*
*/
get: function () {
return new SharePointQueryable(this, "serverRelativeUrl");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Folder.prototype, "uniqueContentTypeOrder", {
/**
* Gets a value that specifies the content type order.
*
*/
get: function () {
return new SharePointQueryableCollection(this, "uniqueContentTypeOrder");
},
enumerable: true,
configurable: true
});
/**
* Delete this folder
*
* @param eTag Value used in the IF-Match header, by default "*"
*/
Folder.prototype.delete = function (eTag) {
if (eTag === void 0) { eTag = "*"; }
return this.clone(Folder, null).postCore({
headers: {
"IF-Match": eTag,
"X-HTTP-Method": "DELETE",
},
});
};
/**
* Moves the folder to the Recycle Bin and returns the identifier of the new Recycle Bin item.
*/
Folder.prototype.recycle = function () {
return this.clone(Folder, "recycle").postCore();
};
/**
* Gets the associated list item for this folder, loading the default properties
*/
Folder.prototype.getItem = function () {
var selects = [];
for (var _i = 0; _i < arguments.length; _i++) {
selects[_i] = arguments[_i];
}
var q = this.listItemAllFields;
return q.select.apply(q, selects).get().then(function (d) {
return common.extend(new Item(odataUrlFrom(d)), d);
});
};
/**
* Moves a folder to destination path
*
* @param destUrl Absolute or relative URL of the destination path
*/
Folder.prototype.moveTo = function (destUrl) {
var _this = this;
return this.select("ServerRelativeUrl").get().then(function (_a) {
var srcUrl = _a.ServerRelativeUrl;
var client = new SPHttpClient();
var webBaseUrl = _this.toUrl().split("/_api")[0];
var hostUrl = webBaseUrl.replace("://", "___").split("/")[0].replace("___", "://");
var methodUrl = webBaseUrl + "/_api/SP.MoveCopyUtil.MoveFolder()";
return client.post(methodUrl, {
body: common.jsS({
destUrl: destUrl.indexOf("http") === 0 ? destUrl : "" + hostUrl + destUrl,
srcUrl: "" + hostUrl + srcUrl,
}),
}).then(function (r) { return r.json(); });
});
};
return Folder;
}(SharePointQueryableShareableFolder));
/**
* Describes a collection of content types
*
*/
var ContentTypes = /** @class */ (function (_super) {
__extends(ContentTypes, _super);
function ContentTypes() {
return _super !== null && _super.apply(this, arguments) || this;
}
ContentTypes_1 = ContentTypes;
/**
* Adds an existing contenttype to a content type collection
*
* @param contentTypeId in the following format, for example: 0x010102
*/
ContentTypes.prototype.addAvailableContentType = function (contentTypeId) {
var _this = this;
var postBody = common.jsS({
"contentTypeId": contentTypeId,
});
return this.clone(ContentTypes_1, "addAvailableContentType").postCore({ body: postBody }).then(function (data) {
return {
contentType: _this.getById(data.id),
data: data,
};
});
};
/**
* Gets a ContentType by content type id
*/
ContentTypes.prototype.getById = function (id) {
var ct = new ContentType(this);
ct.concat("('" + id + "')");
return ct;
};
/**
* Adds a new content type to the collection
*
* @param id The desired content type id for the new content type (also determines the parent content type)
* @param name The name of the content type
* @param description The description of the content type
* @param group The group in which to add the content type
* @param additionalSettings Any additional settings to provide when creating the content type
*
*/
ContentTypes.prototype.add = function (id, name, description, group, additionalSettings) {
var _this = this;
if (description === void 0) { description = ""; }
if (group === void 0) { group = "Custom Content Types"; }
if (additionalSettings === void 0) { additionalSettings = {}; }
var postBody = common.jsS(Object.assign(metadata("SP.ContentType"), {
"Description": description,
"Group": group,
"Id": { "StringValue": id },
"Name": name,
}, additionalSettings));
return this.postCore({ body: postBody }).then(function (data) {
return { contentType: _this.getById(data.id), data: data };
});
};
var ContentTypes_1;
ContentTypes = ContentTypes_1 = __decorate([
defaultPath("contenttypes")
], ContentTypes);
return ContentTypes;
}(SharePointQueryableCollection));
/**
* Describes a single ContentType instance
*
*/
var ContentType = /** @class */ (function (_super) {
__extends(ContentType, _super);
function ContentType() {
var _this = _super !== null && _super.apply(this, arguments) || this;
/**
* Delete this content type
*/
_this.delete = _this._delete;
return _this;
}
Object.defineProperty(ContentType.prototype, "fieldLinks", {
/**
* Gets the column (also known as field) references in the content type.
*/
get: function () {
return new FieldLinks(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(ContentType.prototype, "fields", {
/**
* Gets a value that specifies the collection of fields for the content type.
*/
get: function () {
return new SharePointQueryableCollection(this, "fields");
},
enumerable: true,
configurable: true
});
Object.defineProperty(ContentType.prototype, "parent", {
/**
* Gets the parent content type of the content type.
*/
get: function () {
return new ContentType(this, "parent");
},
enumerable: true,
configurable: true
});
Object.defineProperty(ContentType.prototype, "workflowAssociations", {
/**
* Gets a value that specifies the collection of workflow associations for the content type.
*/
get: function () {
return new SharePointQueryableCollection(this, "workflowAssociations");
},
enumerable: true,
configurable: true
});
return ContentType;
}(SharePointQueryableInstance));
/**
* Represents a collection of field link instances
*/
var FieldLinks = /** @class */ (function (_super) {
__extends(FieldLinks, _super);
function FieldLinks() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Gets a FieldLink by GUID id
*
* @param id The GUID id of the field link
*/
FieldLinks.prototype.getById = function (id) {
var fl = new FieldLink(this);
fl.concat("(guid'" + id + "')");
return fl;
};
FieldLinks = __decorate([
defaultPath("fieldlinks")
], FieldLinks);
return FieldLinks;
}(SharePointQueryableCollection));
/**
* Represents a field link instance
*/
var FieldLink = /** @class */ (function (_super) {
__extends(FieldLink, _super);
function FieldLink() {
return _super !== null && _super.apply(this, arguments) || this;
}
return FieldLink;
}(SharePointQueryableInstance));
/**
* Describes a collection of Item objects
*
*/
var AttachmentFiles = /** @class */ (function (_super) {
__extends(AttachmentFiles, _super);
function AttachmentFiles() {
return _super !== null && _super.apply(this, arguments) || this;
}
AttachmentFiles_1 = AttachmentFiles;
/**
* Gets a Attachment File by filename
*
* @param name The name of the file, including extension.
*/
AttachmentFiles.prototype.getByName = function (name) {
var f = new AttachmentFile(this);
f.concat("('" + name + "')");
return f;
};
/**
* Adds a new attachment to the collection. Not supported for batching.
*
* @param name The name of the file, including extension.
* @param content The Base64 file content.
*/
AttachmentFiles.prototype.add = function (name, content) {
var _this = this;
return this.clone(AttachmentFiles_1, "add(FileName='" + name + "')", false).postCore({
body: content,
}).then(function (response) {
return {
data: response,
file: _this.getByName(name),
};
});
};
/**
* Adds multiple new attachment to the collection. Not supported for batching.
*
* @param files The collection of files to add
*/
AttachmentFiles.prototype.addMultiple = function (files) {
var _this = this;
// add the files in series so we don't get update conflicts
return files.reduce(function (chain, file) { return chain.then(function () { return _this.clone(AttachmentFiles_1, "add(FileName='" + file.name + "')", false).postCore({
body: file.content,
}); }); }, Promise.resolve());
};
/**
* Delete multiple attachments from the collection. Not supported for batching.
*
* @param files The collection of files to delete
*/
AttachmentFiles.prototype.deleteMultiple = function () {
var _this = this;
var files = [];
for (var _i = 0; _i < arguments.length; _i++) {
files[_i] = arguments[_i];
}
return files.reduce(function (chain, file) { return chain.then(function () { return _this.getByName(file).delete(); }); }, Promise.resolve());
};
/**
* Delete multiple attachments from the collection and send to recycle bin. Not supported for batching.
*
* @param files The collection of files to be deleted and sent to recycle bin
*/
AttachmentFiles.prototype.recycleMultiple = function () {
var _this = this;
var files = [];
for (var _i = 0; _i < arguments.length; _i++) {
files[_i] = arguments[_i];
}
return files.reduce(function (chain, file) { return chain.then(function () { return _this.getByName(file).recycle(); }); }, Promise.resolve());
};
var AttachmentFiles_1;
AttachmentFiles = AttachmentFiles_1 = __decorate([
defaultPath("AttachmentFiles")
], AttachmentFiles);
return AttachmentFiles;
}(SharePointQueryableCollection));
/**
* Describes a single attachment file instance
*
*/
var AttachmentFile = /** @class */ (function (_super) {
__extends(AttachmentFile, _super);
function AttachmentFile() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.delete = _this._deleteWithETag;
return _this;
}
/**
* Gets the contents of the file as text
*
*/
AttachmentFile.prototype.getText = function () {
return this.getParsed(new odata.TextParser());
};
/**
* Gets the contents of the file as a blob, does not work in Node.js
*
*/
AttachmentFile.prototype.getBlob = function () {
return this.getParsed(new odata.BlobParser());
};
/**
* Gets the contents of a file as an ArrayBuffer, works in Node.js
*/
AttachmentFile.prototype.getBuffer = function () {
return this.getParsed(new odata.BufferParser());
};
/**
* Gets the contents of a file as an ArrayBuffer, works in Node.js
*/
AttachmentFile.prototype.getJSON = function () {
return this.getParsed(new odata.JSONParser());
};
/**
* Sets the content of a file. Not supported for batching
*
* @param content The value to set for the file contents
*/
AttachmentFile.prototype.setContent = function (content) {
var _this = this;
return this.clone(AttachmentFile, "$value", false).postCore({
body: content,
headers: {
"X-HTTP-Method": "PUT",
},
}).then(function (_) { return new AttachmentFile(_this); });
};
/**
* Delete this attachment file and send it to recycle bin
*
* @param eTag Value used in the IF-Match header, by default "*"
*/
AttachmentFile.prototype.recycle = function (eTag) {
if (eTag === void 0) { eTag = "*"; }
return this.clone(AttachmentFile, "recycleObject").postCore({
headers: {
"IF-Match": eTag,
"X-HTTP-Method": "DELETE",
},
});
};
// /**
// * Delete this attachment file
// *
// * @param eTag Value used in the IF-Match header, by default "*"
// */
// public delete(eTag = "*"): Promise<void> {
// return this.postCore({
// headers: {
// "IF-Match": eTag,
// "X-HTTP-Method": "DELETE",
// },
// });
// }
AttachmentFile.prototype.getParsed = function (parser) {
return this.clone(AttachmentFile, "$value", false).get(parser);
};
return AttachmentFile;
}(SharePointQueryableInstance));
/**
* Describes the views available in the current context
*
*/
var Views = /** @class */ (function (_super) {
__extends(Views, _super);
function Views() {
return _super !== null && _super.apply(this, arguments) || this;
}
Views_1 = Views;
/**
* Gets a view by guid id
*
* @param id The GUID id of the view
*/
Views.prototype.getById = function (id) {
var v = new View(this);
v.concat("('" + id + "')");
return v;
};
/**
* Gets a view by title (case-sensitive)
*
* @param title The case-sensitive title of the view
*/
Views.prototype.getByTitle = function (title) {
return new View(this, "getByTitle('" + title + "')");
};
/**
* Adds a new view to the collection
*
* @param title The new views's title
* @param personalView True if this is a personal view, otherwise false, default = false
* @param additionalSettings Will be passed as part of the view creation body
*/
Views.prototype.add = function (title, personalView, additionalSettings) {
var _this = this;
if (personalView === void 0) { personalView = false; }
if (additionalSettings === void 0) { additionalSettings = {}; }
var postBody = common.jsS(Object.assign(metadata("SP.View"), {
"PersonalView": personalView,
"Title": title,
}, additionalSettings));
return this.clone(Views_1, null).postCore({ body: postBody }).then(function (data) {
return {
data: data,
view: _this.getById(data.Id),
};
});
};
var Views_1;
Views = Views_1 = __decorate([
defaultPath("views")
], Views);
return Views;
}(SharePointQueryableCollection));
/**
* Describes a single View instance
*
*/
var View = /** @class */ (function (_super) {
__extends(View, _super);
function View() {
var _this = _super !== null && _super.apply(this, arguments) || this;
/**
* Updates this view intance with the supplied properties
*
* @param properties A plain object hash of values to update for the view
*/
_this.update = _this._update("SP.View", function (data) { return ({ data: data, view: _this }); });
/**
* Delete this view
*
*/
_this.delete = _this._delete;
return _this;
}
Object.defineProperty(View.prototype, "fields", {
get: function () {
return new ViewFields(this);
},
enumerable: true,
configurable: true
});
/**
* Returns the list view as HTML.
*
*/
View.prototype.renderAsHtml = function () {
return this.clone(SharePointQueryable, "renderashtml").get();
};
/**
* Sets the view schema
*
* @param viewXml The view XML to set
*/
View.prototype.setViewXml = function (viewXml) {
return this.clone(View, "SetViewXml").postCore({
body: common.jsS({
viewXml: viewXml,
}),
});
};
return View;
}(SharePointQueryableInstance));
var ViewFields = /** @class */ (function (_super) {
__extends(ViewFields, _super);
function ViewFields() {
return _super !== null && _super.apply(this, arguments) || this;
}
ViewFields_1 = ViewFields;
/**
* Gets a value that specifies the XML schema that represents the collection.
*/
ViewFields.prototype.getSchemaXml = function () {
return this.clone(SharePointQueryable, "schemaxml").get();
};
/**
* Adds the field with the specified field internal name or display name to the collection.
*
* @param fieldTitleOrInternalName The case-sensitive internal name or display name of the field to add.
*/
ViewFields.prototype.add = function (fieldTitleOrInternalName) {
return this.clone(ViewFields_1, "addviewfield('" + fieldTitleOrInternalName + "')").postCore();
};
/**
* Moves the field with the specified field internal name to the specified position in the collection.
*
* @param fieldInternalName The case-sensitive internal name of the field to move.
* @param index The zero-based index of the new position for the field.
*/
ViewFields.prototype.move = function (fieldInternalName, index) {
return this.clone(ViewFields_1, "moveviewfieldto").postCore({
body: common.jsS({ "field": fieldInternalName, "index": index }),
});
};
/**
* Removes all the fields from the collection.
*/
ViewFields.prototype.removeAll = function () {
return this.clone(ViewFields_1, "removeallviewfields").postCore();
};
/**
* Removes the field with the specified field internal name from the collection.
*
* @param fieldInternalName The case-sensitive internal name of the field to remove from the view.
*/
ViewFields.prototype.remove = function (fieldInternalName) {
return this.clone(ViewFields_1, "removeviewfield('" + fieldInternalName + "')").postCore();
};
var ViewFields_1;
ViewFields = ViewFields_1 = __decorate([
defaultPath("viewfields")
], ViewFields);
return ViewFields;
}(SharePointQueryableCollection));
/**
* Describes a collection of Field objects
*
*/
var Fields = /** @class */ (function (_super) {
__extends(Fields, _super);
function Fields() {
return _super !== null && _super.apply(this, arguments) || this;
}
Fields_1 = Fields;
/**
* Gets a field from the collection by id
*
* @param id The Id of the list
*/
Fields.prototype.getById = function (id) {
var f = new Field(this);
f.concat("('" + id + "')");
return f;
};
/**
* Gets a field from the collection by title
*
* @param title The case-sensitive title of the field
*/
Fields.prototype.getByTitle = function (title) {
return new Field(this, "getByTitle('" + title + "')");
};
/**
* Gets a field from the collection by using internal name or title
*
* @param name The case-sensitive internal name or title of the field
*/
Fields.prototype.getByInternalNameOrTitle = function (name) {
return new Field(this, "getByInternalNameOrTitle('" + name + "')");
};
/**
* Creates a field based on the specified schema
*/
Fields.prototype.createFieldAsXml = function (xml) {
var _this = this;
var info;
if (typeof xml === "string") {
info = { SchemaXml: xml };
}
else {
info = xml;
}
var postBody = common.jsS({
"parameters": common.extend(metadata("SP.XmlSchemaFieldCreationInformation"), info),
});
return this.clone(Fields_1, "createfieldasxml").postCore({ body: postBody }).then(function (data) {
return {
data: data,
field: _this.getById(data.Id),
};
});
};
/**
* Adds a new field to the collection
*
* @param title The new field's title
* @param fieldType The new field's type (ex: SP.FieldText)
* @param properties Differ by type of field being created (see: https://msdn.microsoft.com/en-us/library/office/dn600182.aspx)
*/
Fields.prototype.add = function (title, fieldType, properties) {
var _this = this;
var postBody = common.jsS(Object.assign(metadata(fieldType), {
"Title": title,
}, properties));
return this.clone(Fields_1, null).postCore({ body: postBody }).then(function (data) {
return {
data: data,
field: _this.getById(data.Id),
};
});
};
/**
* Adds a new SP.FieldText to the collection
*
* @param title The field title
* @param maxLength The maximum number of characters allowed in the value of the field.
* @param properties Differ by type of field being created (see: https://msdn.microsoft.com/en-us/library/office/dn600182.aspx)
*/
Fields.prototype.addText = function (title, maxLength, properties) {
if (maxLength === void 0) { maxLength = 255; }
var props = {
FieldTypeKind: 2,
MaxLength: maxLength,
};
return this.add(title, "SP.FieldText", common.extend(props, properties));
};
/**
* Adds a new SP.FieldCalculated to the collection
*
* @param title The field title.
* @param formula The formula for the field.
* @param dateFormat The date and time format that is displayed in the field.
* @param outputType Specifies the output format for the field. Represents a FieldType value.
* @param properties Differ by type of field being created (see: https://msdn.microsoft.com/en-us/library/office/dn600182.aspx)
*/
Fields.prototype.addCalculated = function (title, formula, dateFormat, outputType, properties) {
if (outputType === void 0) { outputType = exports.FieldTypes.Text; }
var props = {
DateFormat: dateFormat,
FieldTypeKind: 17,
Formula: formula,
OutputType: outputType,
};
return this.add(title, "SP.FieldCalculated", common.extend(props, properties));
};
/**
* Adds a new SP.FieldDateTime to the collection
*
* @param title The field title
* @param displayFormat The format of the date and time that is displayed in the field.
* @param calendarType Specifies the calendar type of the field.
* @param properties Differ by type of field being created (see: https://msdn.microsoft.com/en-us/library/office/dn600182.aspx)
*/
Fields.prototype.addDateTime = function (title, displayFormat, calendarType, friendlyDisplayFormat, properties) {
if (displayFormat === void 0) { displayFormat = exports.DateTimeFieldFormatType.DateOnly; }
if (calendarType === void 0) { calendarType = exports.CalendarType.Gregorian; }
if (friendlyDisplayFormat === void 0) { friendlyDisplayFormat = 0; }
var props = {
DateTimeCalendarType: calendarType,
DisplayFormat: displayFormat,
FieldTypeKind: 4,
FriendlyDisplayFormat: friendlyDisplayFormat,
};
return this.add(title, "SP.FieldDateTime", common.extend(props, properties));
};
/**
* Adds a new SP.FieldNumber to the collection
*
* @param title The field title
* @param minValue The field's minimum value
* @param maxValue The field's maximum value
* @param properties Differ by type of field being created (see: https://msdn.microsoft.com/en-us/library/office/dn600182.aspx)
*/
Fields.prototype.addNumber = function (title, minValue, maxValue, properties) {
var props = { FieldTypeKind: 9 };
if (minValue !== undefined) {
props = common.extend({ MinimumValue: minValue }, props);
}
if (maxValue !== undefined) {
props = common.extend({ MaximumValue: maxValue }, props);
}
return this.add(title, "SP.FieldNumber", common.extend(props, properties));
};
/**
* Adds a new SP.FieldCurrency to the collection
*
* @param title The field title
* @param minValue The field's minimum value
* @param maxValue The field's maximum value
* @param currencyLocalId Specifies the language code identifier (LCID) used to format the value of the field
* @param properties Differ by type of field being created (see: https://msdn.microsoft.com/en-us/library/office/dn600182.aspx)
*/
Fields.prototype.addCurrency = function (title, minValue, maxValue, currencyLocalId, properties) {
if (currencyLocalId === void 0) { currencyLocalId = 1033; }
var props = {
CurrencyLocaleId: currencyLocalId,
FieldTypeKind: 10,
};
if (minValue !== undefined) {
props = common.extend({ MinimumValue: minValue }, props);
}
if (maxValue !== undefined) {
props = common.extend({ MaximumValue: maxValue }, props);
}
return this.add(title, "SP.FieldCurrency", common.extend(props, properties));
};
/**
* Adds a new SP.FieldMultiLineText to the collection
*
* @param title The field title
* @param numberOfLines Specifies the number of lines of text to display for the field.
* @param richText Specifies whether the field supports rich formatting.
* @param restrictedMode Specifies whether the field supports a subset of rich formatting.
* @param appendOnly Specifies whether all changes to the value of the field are displayed in list forms.
* @param allowHyperlink Specifies whether a hyperlink is allowed as a value of the field.
* @param properties Differ by type of field being created (see: https://msdn.microsoft.com/en-us/library/office/dn600182.aspx)
*
*/
Fields.prototype.addMultilineText = function (title, numberOfLines, richText, restrictedMode, appendOnly, allowHyperlink, properties) {
if (numberOfLines === void 0) { numberOfLines = 6; }
if (richText === void 0) { richText = true; }
if (restrictedMode === void 0) { restrictedMode = false; }
if (appendOnly === void 0) { appendOnly = false; }
if (allowHyperlink === void 0) { allowHyperlink = true; }
var props = {
AllowHyperlink: allowHyperlink,
AppendOnly: appendOnly,
FieldTypeKind: 3,
NumberOfLines: numberOfLines,
RestrictedMode: restrictedMode,
RichText: richText,
};
return this.add(title, "SP.FieldMultiLineText", common.extend(props, properties));
};
/**
* Adds a new SP.FieldUrl to the collection
*
* @param title The field title
*/
Fields.prototype.addUrl = function (title, displayFormat, properties) {
if (displayFormat === void 0) { displayFormat = exports.UrlFieldFormatType.Hyperlink; }
var props = {
DisplayFormat: displayFormat,
FieldTypeKind: 11,
};
return this.add(title, "SP.FieldUrl", common.extend(props, properties));
};
/** Adds a user field to the colleciton
*
* @param title The new field's title
* @param selectionMode The selection mode of the field
* @param selectionGroup Value that specifies the identifier of the SharePoint group whose members can be selected as values of the field
* @param properties
*/
Fields.prototype.addUser = function (title, selectionMode, properties) {
var props = {
FieldTypeKind: 20,
SelectionMode: selectionMode,
};
return this.add(title, "SP.FieldUser", common.extend(props, properties));
};
/**
* Adds a SP.FieldLookup to the collection
*
* @param title The new field's title
* @param lookupListId The guid id of the list where the source of the lookup is found
* @param lookupFieldName The internal name of the field in the source list
* @param properties Set of additional properties to set on the new field
*/
Fields.prototype.addLookup = function (title, lookupListId, lookupFieldName, properties) {
var _this = this;
var props = common.extend({
FieldTypeKind: 7,
LookupFieldName: lookupFieldName,
LookupListId: lookupListId,
Title: title,
}, properties);
var postBody = common.jsS({
"parameters": common.extend(metadata("SP.FieldCreationInformation"), props),
});
return this.clone(Fields_1, "addfield").postCore({ body: postBody }).then(function (data) {
return {
data: data,
field: _this.getById(data.Id),
};
});
};
/**
* Adds a new SP.FieldChoice to the collection
*
* @param title The field title.
* @param choices The choices for the field.
* @param format The display format of the available options for the field.
* @param fillIn Specifies whether the field allows fill-in values.
* @param properties Differ by type of field being created (see: https://msdn.microsoft.com/en-us/library/office/dn600182.aspx)
*/
Fields.prototype.addChoice = function (title, choices, format, fillIn, properties) {
if (format === void 0) { format = exports.ChoiceFieldFormatType.Dropdown; }
var props = {
Choices: {
results: choices,
},
EditFormat: format,
FieldTypeKind: 6,
FillInChoice: fillIn,
};
return this.add(title, "SP.FieldChoice", common.extend(props, properties));
};
/**
* Adds a new SP.FieldMultiChoice to the collection
*
* @param title The field title.
* @param choices The choices for the field.
* @param fillIn Specifies whether the field allows fill-in values.
* @param properties Differ by type of field being created (see: https://msdn.microsoft.com/en-us/library/office/dn600182.aspx)
*/
Fields.prototype.addMultiChoice = function (title, choices, fillIn, properties) {
var props = {
Choices: {
results: choices,
},
FieldTypeKind: 15,
FillInChoice: fillIn,
};
return this.add(title, "SP.FieldMultiChoice", common.extend(props, properties));
};
/**
* Adds a new SP.FieldBoolean to the collection
*
* @param title The field title.
* @param properties Differ by type of field being created (see: https://msdn.microsoft.com/en-us/library/office/dn600182.aspx)
*/
Fields.prototype.addBoolean = function (title, properties) {
var props = {
FieldTypeKind: 8,
};
return this.add(title, "SP.Field", common.extend(props, properties));
};
/**
* Creates a secondary (dependent) lookup field, based on the Id of the primary lookup field.
*
* @param displayName The display name of the new field.
* @param primaryLookupFieldId The guid of the primary Lookup Field.
* @param showField Which field to show from the lookup list.
*/
Fields.prototype.addDependentLookupField = function (displayName, primaryLookupFieldId, showField) {
var _this = this;
return this.clone(Fields_1, "adddependentlookupfield(displayName='" + displayName + "', primarylookupfieldid='" + primaryLookupFieldId + "', showfield='" + showField + "')")
.postCore()
.then(function (data) {
return {
data: data,
field: _this.getById(data.Id),
};
});
};
/**
* Adds a new SP.FieldLocation to the collection
*
* @param title The field title.
* @param properties Differ by type of field being created (see: https://msdn.microsoft.com/en-us/library/office/dn600182.aspx)
*/
Fields.prototype.addLocation = function (title, properties) {
var props = { FieldTypeKind: 33 };
return this.add(title, "SP.FieldLocation", common.extend(props, properties));
};
var Fields_1;
Fields = Fields_1 = __decorate([
defaultPath("fields")
], Fields);
return Fields;
}(SharePointQueryableCollection));
/**
* Describes a single of Field instance
*
*/
var Field = /** @class */ (function (_super) {
__extends(Field, _super);
function Field() {
var _this = _super !== null && _super.apply(this, arguments) || this;
/**
* Delete this fields
*
*/
_this.delete = _this._delete;
return _this;
}
/**
* Updates this field intance with the supplied properties
*
* @param properties A plain object hash of values to update for the list
* @param fieldType The type value, required to update child field type properties
*/
Field.prototype.update = function (properties, fieldType) {
var _this = this;
if (fieldType === void 0) { fieldType = "SP.Field"; }
var postBody = common.jsS(common.extend(metadata(fieldType), properties));
return this.postCore({
body: postBody,
headers: {
"X-HTTP-Method": "MERGE",
},
}).then(function (data) {
return {
data: data,
field: _this,
};
});
};
/**
* Sets the value of the ShowInDisplayForm property for this field.
*/
Field.prototype.setShowInDisplayForm = function (show) {
return this.clone(Field, "setshowindisplayform(" + show + ")").postCore();
};
/**
* Sets the value of the ShowInEditForm property for this field.
*/
Field.prototype.setShowInEditForm = function (show) {
return this.clone(Field, "setshowineditform(" + show + ")").postCore();
};
/**
* Sets the value of the ShowInNewForm property for this field.
*/
Field.prototype.setShowInNewForm = function (show) {
return this.clone(Field, "setshowinnewform(" + show + ")").postCore();
};
return Field;
}(SharePointQueryableInstance));
/**
* Describes a collection of Field objects
*
*/
var Forms = /** @class */ (function (_super) {
__extends(Forms, _super);
function Forms() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Gets a form by id
*
* @param id The guid id of the item to retrieve
*/
Forms.prototype.getById = function (id) {
var i = new Form(this);
i.concat("('" + id + "')");
return i;
};
Forms = __decorate([
defaultPath("forms")
], Forms);
return Forms;
}(SharePointQueryableCollection));
/**
* Describes a single of Form instance
*
*/
var Form = /** @class */ (function (_super) {
__extends(Form, _super);
function Form() {
return _super !== null && _super.apply(this, arguments) || this;
}
return Form;
}(SharePointQueryableInstance));
/**
* Describes a collection of webhook subscriptions
*
*/
var Subscriptions = /** @class */ (function (_super) {
__extends(Subscriptions, _super);
function Subscriptions() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Returns all the webhook subscriptions or the specified webhook subscription
*
* @param subscriptionId The id of a specific webhook subscription to retrieve, omit to retrieve all the webhook subscriptions
*/
Subscriptions.prototype.getById = function (subscriptionId) {
var s = new Subscription(this);
s.concat("('" + subscriptionId + "')");
return s;
};
/**
* Creates a new webhook subscription
*
* @param notificationUrl The url to receive the notifications
* @param expirationDate The date and time to expire the subscription in the form YYYY-MM-ddTHH:mm:ss+00:00 (maximum of 6 months)
* @param clientState A client specific string (optional)
*/
Subscriptions.prototype.add = function (notificationUrl, expirationDate, clientState) {
var _this = this;
var postBody = {
"expirationDateTime": expirationDate,
"notificationUrl": notificationUrl,
"resource": this.toUrl(),
};
if (clientState) {
postBody.clientState = clientState;
}
return this.postCore({ body: common.jsS(postBody), headers: { "Content-Type": "application/json" } }).then(function (result) {
return { data: result, subscription: _this.getById(result.id) };
});
};
Subscriptions = __decorate([
defaultPath("subscriptions")
], Subscriptions);
return Subscriptions;
}(SharePointQueryableCollection));
/**
* Describes a single webhook subscription instance
*
*/
var Subscription = /** @class */ (function (_super) {
__extends(Subscription, _super);
function Subscription() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Renews this webhook subscription
*
* @param expirationDate The date and time to expire the subscription in the form YYYY-MM-ddTHH:mm:ss+00:00 (maximum of 6 months, optional)
* @param notificationUrl The url to receive the notifications (optional)
* @param clientState A client specific string (optional)
*/
Subscription.prototype.update = function (expirationDate, notificationUrl, clientState) {
var _this = this;
var postBody = {};
if (expirationDate) {
postBody.expirationDateTime = expirationDate;
}
if (notificationUrl) {
postBody.notificationUrl = notificationUrl;
}
if (clientState) {
postBody.clientState = clientState;
}
return this.patchCore({ body: common.jsS(postBody), headers: { "Content-Type": "application/json" } }).then(function (data) {
return { data: data, subscription: _this };
});
};
/**
* Removes this webhook subscription
*
*/
Subscription.prototype.delete = function () {
return _super.prototype.deleteCore.call(this);
};
return Subscription;
}(SharePointQueryableInstance));
/**
* Describes a collection of user custom actions
*
*/
var UserCustomActions = /** @class */ (function (_super) {
__extends(UserCustomActions, _super);
function UserCustomActions() {
return _super !== null && _super.apply(this, arguments) || this;
}
UserCustomActions_1 = UserCustomActions;
/**
* Returns the user custom action with the specified id
*
* @param id The GUID id of the user custom action to retrieve
*/
UserCustomActions.prototype.getById = function (id) {
var uca = new UserCustomAction(this);
uca.concat("('" + id + "')");
return uca;
};
/**
* Creates a user custom action
*
* @param properties The information object of property names and values which define the new user custom action
*
*/
UserCustomActions.prototype.add = function (properties) {
var _this = this;
var postBody = common.jsS(common.extend({ __metadata: { "type": "SP.UserCustomAction" } }, properties));
return this.postCore({ body: postBody }).then(function (data) {
return {
action: _this.getById(data.Id),
data: data,
};
});
};
/**
* Deletes all user custom actions in the collection
*
*/
UserCustomActions.prototype.clear = function () {
return this.clone(UserCustomActions_1, "clear").postCore();
};
var UserCustomActions_1;
UserCustomActions = UserCustomActions_1 = __decorate([
defaultPath("usercustomactions")
], UserCustomActions);
return UserCustomActions;
}(SharePointQueryableCollection));
/**
* Describes a single user custom action
*
*/
var UserCustomAction = /** @class */ (function (_super) {
__extends(UserCustomAction, _super);
function UserCustomAction() {
var _this = _super !== null && _super.apply(this, arguments) || this;
/**
* Updates this user custom action with the supplied properties
*
* @param properties An information object of property names and values to update for this user custom action
*/
_this.update = _this._update("SP.UserCustomAction", function (data) { return ({ data: data, action: _this }); });
return _this;
}
/**
* Removes this user custom action
*
*/
UserCustomAction.prototype.delete = function () {
return _super.prototype.deleteCore.call(this);
};
return UserCustomAction;
}(SharePointQueryableInstance));
/**
* Describes a collection of List objects
*
*/
var Lists = /** @class */ (function (_super) {
__extends(Lists, _super);
function Lists() {
return _super !== null && _super.apply(this, arguments) || this;
}
Lists_1 = Lists;
/**
* Gets a list from the collection by guid id
*
* @param id The Id of the list (GUID)
*/
Lists.prototype.getById = function (id) {
var list = new List(this);
list.concat("('" + id + "')");
return list;
};
/**
* Gets a list from the collection by title
*
* @param title The title of the list
*/
Lists.prototype.getByTitle = function (title) {
return new List(this, "getByTitle('" + title + "')");
};
/**
* Adds a new list to the collection
*
* @param title The new list's title
* @param description The new list's description
* @param template The list template value
* @param enableContentTypes If true content types will be allowed and enabled, otherwise they will be disallowed and not enabled
* @param additionalSettings Will be passed as part of the list creation body
*/
Lists.prototype.add = function (title, description, template, enableContentTypes, additionalSettings) {
var _this = this;
if (description === void 0) { description = ""; }
if (template === void 0) { template = 100; }
if (enableContentTypes === void 0) { enableContentTypes = false; }
if (additionalSettings === void 0) { additionalSettings = {}; }
var addSettings = common.extend({
"AllowContentTypes": enableContentTypes,
"BaseTemplate": template,
"ContentTypesEnabled": enableContentTypes,
"Description": description,
"Title": title,
"__metadata": { "type": "SP.List" },
}, additionalSettings);
return this.postCore({ body: common.jsS(addSettings) }).then(function (data) {
return { data: data, list: _this.getByTitle(addSettings.Title) };
});
};
/**
* Ensures that the specified list exists in the collection (note: this method not supported for batching)
*
* @param title The new list's title
* @param description The new list's description
* @param template The list template value
* @param enableContentTypes If true content types will be allowed and enabled, otherwise they will be disallowed and not enabled
* @param additionalSettings Will be passed as part of the list creation body or used to update an existing list
*/
Lists.prototype.ensure = function (title, description, template, enableContentTypes, additionalSettings) {
var _this = this;
if (description === void 0) { description = ""; }
if (template === void 0) { template = 100; }
if (enableContentTypes === void 0) { enableContentTypes = false; }
if (additionalSettings === void 0) { additionalSettings = {}; }
if (this.hasBatch) {
throw Error("The ensure list method is not supported for use in a batch.");
}
return new Promise(function (resolve, reject) {
var addOrUpdateSettings = common.extend(additionalSettings, { Title: title, Description: description, ContentTypesEnabled: enableContentTypes }, true);
var list = _this.getByTitle(addOrUpdateSettings.Title);
list.get().then(function (_) {
list.update(addOrUpdateSettings).then(function (d) {
resolve({ created: false, data: d, list: _this.getByTitle(addOrUpdateSettings.Title) });
}).catch(function (e) { return reject(e); });
}).catch(function (_) {
_this.add(title, description, template, enableContentTypes, addOrUpdateSettings).then(function (r) {
resolve({ created: true, data: r.data, list: _this.getByTitle(addOrUpdateSettings.Title) });
}).catch(function (e) { return reject(e); });
});
});
};
/**
* Gets a list that is the default asset location for images or other files, which the users upload to their wiki pages.
*/
Lists.prototype.ensureSiteAssetsLibrary = function () {
return this.clone(Lists_1, "ensuresiteassetslibrary").postCore().then(function (json) {
return new List(odataUrlFrom(json));
});
};
/**
* Gets a list that is the default location for wiki pages.
*/
Lists.prototype.ensureSitePagesLibrary = function () {
return this.clone(Lists_1, "ensuresitepageslibrary").postCore().then(function (json) {
return new List(odataUrlFrom(json));
});
};
var Lists_1;
Lists = Lists_1 = __decorate([
defaultPath("lists")
], Lists);
return Lists;
}(SharePointQueryableCollection));
/**
* Describes a single List instance
*
*/
var List = /** @class */ (function (_super) {
__extends(List, _super);
function List() {
return _super !== null && _super.apply(this, arguments) || this;
}
Object.defineProperty(List.prototype, "contentTypes", {
/**
* Gets the content types in this list
*
*/
get: function () {
return new ContentTypes(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(List.prototype, "items", {
/**
* Gets the items in this list
*
*/
get: function () {
return new Items(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(List.prototype, "views", {
/**
* Gets the views in this list
*
*/
get: function () {
return new Views(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(List.prototype, "fields", {
/**
* Gets the fields in this list
*
*/
get: function () {
return new Fields(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(List.prototype, "forms", {
/**
* Gets the forms in this list
*
*/
get: function () {
return new Forms(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(List.prototype, "defaultView", {
/**
* Gets the default view of this list
*
*/
get: function () {
return new View(this, "DefaultView");
},
enumerable: true,
configurable: true
});
Object.defineProperty(List.prototype, "userCustomActions", {
/**
* Get all custom actions on a site collection
*
*/
get: function () {
return new UserCustomActions(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(List.prototype, "effectiveBasePermissions", {
/**
* Gets the effective base permissions of this list
*
*/
get: function () {
return new SharePointQueryable(this, "EffectiveBasePermissions");
},
enumerable: true,
configurable: true
});
Object.defineProperty(List.prototype, "eventReceivers", {
/**
* Gets the event receivers attached to this list
*
*/
get: function () {
return new SharePointQueryableCollection(this, "EventReceivers");
},
enumerable: true,
configurable: true
});
Object.defineProperty(List.prototype, "relatedFields", {
/**
* Gets the related fields of this list
*
*/
get: function () {
return new SharePointQueryable(this, "getRelatedFields");
},
enumerable: true,
configurable: true
});
Object.defineProperty(List.prototype, "informationRightsManagementSettings", {
/**
* Gets the IRM settings for this list
*
*/
get: function () {
return new SharePointQueryable(this, "InformationRightsManagementSettings");
},
enumerable: true,
configurable: true
});
Object.defineProperty(List.prototype, "subscriptions", {
/**
* Gets the webhook subscriptions of this list
*
*/
get: function () {
return new Subscriptions(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(List.prototype, "rootFolder", {
/**
* The root folder of the list
*/
get: function () {
return new Folder(this, "rootFolder");
},
enumerable: true,
configurable: true
});
/**
* Gets a view by view guid id
*
*/
List.prototype.getView = function (viewId) {
return new View(this, "getView('" + viewId + "')");
};
/**
* Updates this list intance with the supplied properties
*
* @param properties A plain object hash of values to update for the list
* @param eTag Value used in the IF-Match header, by default "*"
*/
/* tslint:disable no-string-literal */
List.prototype.update = function (properties, eTag) {
var _this = this;
if (eTag === void 0) { eTag = "*"; }
var postBody = common.jsS(common.extend({
"__metadata": { "type": "SP.List" },
}, properties));
return this.postCore({
body: postBody,
headers: {
"IF-Match": eTag,
"X-HTTP-Method": "MERGE",
},
}).then(function (data) {
var retList = _this;
if (common.hOP(properties, "Title")) {
retList = _this.getParent(List, _this.parentUrl, "getByTitle('" + properties["Title"] + "')");
}
return {
data: data,
list: retList,
};
});
};
/* tslint:enable */
/**
* Delete this list
*
* @param eTag Value used in the IF-Match header, by default "*"
*/
List.prototype.delete = function (eTag) {
if (eTag === void 0) { eTag = "*"; }
return this.postCore({
headers: {
"IF-Match": eTag,
"X-HTTP-Method": "DELETE",
},
});
};
/**
* Returns the collection of changes from the change log that have occurred within the list, based on the specified query.
*/
List.prototype.getChanges = function (query) {
return this.clone(List, "getchanges").postCore({
body: common.jsS({ "query": common.extend({ "__metadata": { "type": "SP.ChangeQuery" } }, query) }),
});
};
/**
* Returns a collection of items from the list based on the specified query.
*
* @param CamlQuery The Query schema of Collaborative Application Markup
* Language (CAML) is used in various ways within the context of Microsoft SharePoint Foundation
* to define queries against list data.
* see:
*
* https://msdn.microsoft.com/en-us/library/office/ms467521.aspx
*
* @param expands A URI with a $expand System Query Option indicates that Entries associated with
* the Entry or Collection of Entries identified by the Resource Path
* section of the URI must be represented inline (i.e. eagerly loaded).
* see:
*
* https://msdn.microsoft.com/en-us/library/office/fp142385.aspx
*
* http://www.odata.org/documentation/odata-version-2-0/uri-conventions/#ExpandSystemQueryOption
*/
List.prototype.getItemsByCAMLQuery = function (query) {
var expands = [];
for (var _i = 1; _i < arguments.length; _i++) {
expands[_i - 1] = arguments[_i];
}
var q = this.clone(List, "getitems");
return q.expand.apply(q, expands).postCore({
body: common.jsS({ "query": common.extend({ "__metadata": { "type": "SP.CamlQuery" } }, query) }),
});
};
/**
* See: https://msdn.microsoft.com/en-us/library/office/dn292554.aspx
*/
List.prototype.getListItemChangesSinceToken = function (query) {
return this.clone(List, "getlistitemchangessincetoken").postCore({
body: common.jsS({ "query": common.extend({ "__metadata": { "type": "SP.ChangeLogItemQuery" } }, query) }),
}, { parse: function (r) { return r.text(); } });
};
/**
* Moves the list to the Recycle Bin and returns the identifier of the new Recycle Bin item.
*/
List.prototype.recycle = function () {
return this.clone(List, "recycle").postCore().then(function (data) {
if (common.hOP(data, "Recycle")) {
return data.Recycle;
}
else {
return data;
}
});
};
/**
* Renders list data based on the view xml provided
*/
List.prototype.renderListData = function (viewXml) {
var q = this.clone(List, "renderlistdata(@viewXml)");
q.query.set("@viewXml", "'" + viewXml + "'");
return q.postCore().then(function (data) {
// data will be a string, so we parse it again
return JSON.parse(common.hOP(data, "RenderListData") ? data.RenderListData : data);
});
};
/**
* Returns the data for the specified query view
*
* @param parameters The parameters to be used to render list data as JSON string.
* @param overrideParameters The parameters that are used to override and extend the regular SPRenderListDataParameters.
*/
List.prototype.renderListDataAsStream = function (parameters, overrideParameters) {
if (overrideParameters === void 0) { overrideParameters = null; }
var postBody = {
overrideParameters: common.extend(metadata("SP.RenderListDataOverrideParameters"), overrideParameters),
parameters: common.extend(metadata("SP.RenderListDataParameters"), parameters),
};
return this.clone(List, "RenderListDataAsStream", true).postCore({
body: common.jsS(postBody),
});
};
/**
* Gets the field values and field schema attributes for a list item.
*/
List.prototype.renderListFormData = function (itemId, formId, mode) {
return this.clone(List, "renderlistformdata(itemid=" + itemId + ", formid='" + formId + "', mode='" + mode + "')").postCore().then(function (data) {
// data will be a string, so we parse it again
return JSON.parse(common.hOP(data, "RenderListFormData") ? data.RenderListFormData : data);
});
};
/**
* Reserves a list item ID for idempotent list item creation.
*/
List.prototype.reserveListItemId = function () {
return this.clone(List, "reservelistitemid").postCore().then(function (data) {
if (common.hOP(data, "ReserveListItemId")) {
return data.ReserveListItemId;
}
else {
return data;
}
});
};
/**
* Returns the ListItemEntityTypeFullName for this list, used when adding/updating list items. Does not support batching.
*
*/
List.prototype.getListItemEntityTypeFullName = function () {
return this.clone(List, null, false).select("ListItemEntityTypeFullName").get().then(function (o) { return o.ListItemEntityTypeFullName; });
};
/**
* Creates an item using path (in a folder), validates and sets its field values.
*
* @param formValues The fields to change and their new values.
* @param decodedUrl Path decoded url; folder's server relative path.
* @param bNewDocumentUpdate true if the list item is a document being updated after upload; otherwise false.
* @param checkInComment Optional check in comment.
*/
List.prototype.addValidateUpdateItemUsingPath = function (formValues, decodedUrl, bNewDocumentUpdate, checkInComment) {
if (bNewDocumentUpdate === void 0) { bNewDocumentUpdate = false; }
return this.clone(List, "AddValidateUpdateItemUsingPath()").postCore({
body: common.jsS({
bNewDocumentUpdate: bNewDocumentUpdate,
checkInComment: checkInComment,
formValues: formValues,
listItemCreateInfo: {
FolderPath: {
DecodedUrl: decodedUrl,
__metadata: { type: "SP.ResourcePath" },
},
__metadata: { type: "SP.ListItemCreationInformationUsingPath" },
},
}),
}).then(function (res) {
if (typeof res.AddValidateUpdateItemUsingPath !== "undefined") {
return res.AddValidateUpdateItemUsingPath.results;
}
return res;
});
};
return List;
}(SharePointQueryableSecurable));
/**
* Represents a Collection of comments
*/
var Comments = /** @class */ (function (_super) {
__extends(Comments, _super);
function Comments() {
return _super !== null && _super.apply(this, arguments) || this;
}
Comments_1 = Comments;
/**
* Adds a new comment to this collection
*
* @param info Comment information to add
*/
Comments.prototype.add = function (info) {
var _this = this;
if (typeof info === "string") {
info = { text: info };
}
var postBody = common.jsS(common.extend(metadata("Microsoft.SharePoint.Comments.comment"), info));
return this.clone(Comments_1, null).postCore({ body: postBody }).then(function (d) {
return common.extend(_this.getById(d.id), d);
});
};
/**
* Gets a comment by id
*
* @param id Id of the comment to load
*/
Comments.prototype.getById = function (id) {
var c = new Comment(this);
c.concat("(" + id + ")");
return c;
};
/**
* Deletes all the comments in this collection
*/
Comments.prototype.clear = function () {
return this.clone(Comments_1, "DeleteAll").postCore();
};
var Comments_1;
Comments = Comments_1 = __decorate([
defaultPath("comments")
], Comments);
return Comments;
}(SharePointQueryableCollection));
/**
* Represents a comment
*/
var Comment = /** @class */ (function (_super) {
__extends(Comment, _super);
function Comment() {
return _super !== null && _super.apply(this, arguments) || this;
}
Object.defineProperty(Comment.prototype, "replies", {
get: function () {
return new Replies(this);
},
enumerable: true,
configurable: true
});
/**
* Likes the comment as the current user
*/
Comment.prototype.like = function () {
return this.clone(Comment, "Like").postCore();
};
/**
* Unlikes the comment as the current user
*/
Comment.prototype.unlike = function () {
return this.clone(Comment, "Unlike").postCore();
};
/**
* Deletes this comment
*/
Comment.prototype.delete = function () {
return this.clone(Comment, "DeleteComment").postCore();
};
return Comment;
}(SharePointQueryableInstance));
/**
* Represents a Collection of comments
*/
var Replies = /** @class */ (function (_super) {
__extends(Replies, _super);
function Replies() {
return _super !== null && _super.apply(this, arguments) || this;
}
Replies_1 = Replies;
/**
* Adds a new reply to this collection
*
* @param info Comment information to add
*/
Replies.prototype.add = function (info) {
if (typeof info === "string") {
info = { text: info };
}
var postBody = common.jsS(common.extend(metadata("Microsoft.SharePoint.Comments.comment"), info));
return this.clone(Replies_1, null).postCore({ body: postBody }).then(function (d) {
return common.extend(new Comment(odataUrlFrom(d)), d);
});
};
var Replies_1;
Replies = Replies_1 = __decorate([
defaultPath("replies")
], Replies);
return Replies;
}(SharePointQueryableCollection));
/**
* Describes a collection of Item objects
*
*/
var Items = /** @class */ (function (_super) {
__extends(Items, _super);
function Items() {
return _super !== null && _super.apply(this, arguments) || this;
}
Items_1 = Items;
/**
* Gets an Item by id
*
* @param id The integer id of the item to retrieve
*/
Items.prototype.getById = function (id) {
var i = new Item(this);
i.concat("(" + id + ")");
return i;
};
/**
* Gets BCS Item by string id
*
* @param stringId The string id of the BCS item to retrieve
*/
Items.prototype.getItemByStringId = function (stringId) {
// creates an item with the parent list path and append out method call
return new Item(this.parentUrl, "getItemByStringId('" + stringId + "')");
};
/**
* Skips the specified number of items (https://msdn.microsoft.com/en-us/library/office/fp142385.aspx#sectionSection6)
*
* @param skip The starting id where the page should start, use with top to specify pages
* @param reverse It true the PagedPrev=true parameter is added allowing backwards navigation in the collection
*/
Items.prototype.skip = function (skip, reverse) {
if (reverse === void 0) { reverse = false; }
if (reverse) {
this.query.set("$skiptoken", encodeURIComponent("Paged=TRUE&PagedPrev=TRUE&p_ID=" + skip));
}
else {
this.query.set("$skiptoken", encodeURIComponent("Paged=TRUE&p_ID=" + skip));
}
return this;
};
/**
* Gets a collection designed to aid in paging through data
*
*/
Items.prototype.getPaged = function () {
return this.get(new PagedItemCollectionParser(this));
};
/**
* Gets all the items in a list, regardless of count. Does not support batching or caching
*
* @param requestSize Number of items to return in each request (Default: 2000)
* @param acceptHeader Allows for setting the value of the Accept header for SP 2013 support
*/
Items.prototype.getAll = function (requestSize, acceptHeader) {
if (requestSize === void 0) { requestSize = 2000; }
if (acceptHeader === void 0) { acceptHeader = "application/json;odata=nometadata"; }
logging.Logger.write("Calling items.getAll should be done sparingly. Ensure this is the correct choice. If you are unsure, it is not.", 2 /* Warning */);
// this will be used for the actual query
// and we set no metadata here to try and reduce traffic
var items = new Items_1(this, "").top(requestSize).configure({
headers: {
"Accept": acceptHeader,
},
});
// let's copy over the odata query params that can be applied
// $top - allow setting the page size this way (override what we did above)
// $select - allow picking the return fields (good behavior)
// $filter - allow setting a filter, though this may fail due for large lists
this.query.forEach(function (v, k) {
if (/^\$select|filter|top|expand$/i.test(k)) {
items.query.set(k, v);
}
});
// give back the promise
return new Promise(function (resolve, reject) {
// this will eventually hold the items we return
var itemsCollector = [];
// action that will gather up our results recursively
var gatherer = function (last) {
// collect that set of results
[].push.apply(itemsCollector, last.results);
// if we have more, repeat - otherwise resolve with the collected items
if (last.hasNext) {
last.getNext().then(gatherer).catch(reject);
}
else {
resolve(itemsCollector);
}
};
// start the cycle
items.getPaged().then(gatherer).catch(reject);
});
};
/**
* Adds a new item to the collection
*
* @param properties The new items's properties
* @param listItemEntityTypeFullName The type name of the list's entities
*/
Items.prototype.add = function (properties, listItemEntityTypeFullName) {
var _this = this;
if (properties === void 0) { properties = {}; }
if (listItemEntityTypeFullName === void 0) { listItemEntityTypeFullName = null; }
var removeDependency = this.addBatchDependency();
return this.ensureListItemEntityTypeName(listItemEntityTypeFullName).then(function (listItemEntityType) {
var postBody = common.jsS(common.extend(metadata(listItemEntityType), properties));
var promise = _this.clone(Items_1, "").postCore({ body: postBody }).then(function (data) {
return {
data: data,
item: _this.getById(data.Id),
};
});
removeDependency();
return promise;
});
};
/**
* Ensures we have the proper list item entity type name, either from the value provided or from the list
*
* @param candidatelistItemEntityTypeFullName The potential type name
*/
Items.prototype.ensureListItemEntityTypeName = function (candidatelistItemEntityTypeFullName) {
return candidatelistItemEntityTypeFullName ?
Promise.resolve(candidatelistItemEntityTypeFullName) :
this.getParent(List).getListItemEntityTypeFullName();
};
var Items_1;
Items = Items_1 = __decorate([
defaultPath("items")
], Items);
return Items;
}(SharePointQueryableCollection));
/**
* Descrines a single Item instance
*
*/
var Item = /** @class */ (function (_super) {
__extends(Item, _super);
function Item() {
var _this = _super !== null && _super.apply(this, arguments) || this;
/**
* Delete this item
*
* @param eTag Value used in the IF-Match header, by default "*"
*/
_this.delete = _this._deleteWithETag;
return _this;
}
Object.defineProperty(Item.prototype, "attachmentFiles", {
/**
* Gets the set of attachments for this item
*
*/
get: function () {
return new AttachmentFiles(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Item.prototype, "contentType", {
/**
* Gets the content type for this item
*
*/
get: function () {
return new ContentType(this, "ContentType");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Item.prototype, "comments", {
/**
* Gets the collection of comments associated with this list item
*/
get: function () {
return new Comments(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Item.prototype, "effectiveBasePermissions", {
/**
* Gets the effective base permissions for the item
*
*/
get: function () {
return new SharePointQueryable(this, "EffectiveBasePermissions");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Item.prototype, "effectiveBasePermissionsForUI", {
/**
* Gets the effective base permissions for the item in a UI context
*
*/
get: function () {
return new SharePointQueryable(this, "EffectiveBasePermissionsForUI");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Item.prototype, "fieldValuesAsHTML", {
/**
* Gets the field values for this list item in their HTML representation
*
*/
get: function () {
return new SharePointQueryableInstance(this, "FieldValuesAsHTML");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Item.prototype, "fieldValuesAsText", {
/**
* Gets the field values for this list item in their text representation
*
*/
get: function () {
return new SharePointQueryableInstance(this, "FieldValuesAsText");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Item.prototype, "fieldValuesForEdit", {
/**
* Gets the field values for this list item for use in editing controls
*
*/
get: function () {
return new SharePointQueryableInstance(this, "FieldValuesForEdit");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Item.prototype, "folder", {
/**
* Gets the folder associated with this list item (if this item represents a folder)
*
*/
get: function () {
return new Folder(this, "folder");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Item.prototype, "file", {
/**
* Gets the folder associated with this list item (if this item represents a folder)
*
*/
get: function () {
return new File(this, "file");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Item.prototype, "versions", {
/**
* Gets the collection of versions associated with this item
*/
get: function () {
return new ItemVersions(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Item.prototype, "list", {
get: function () {
return this.getParent(List, this.parentUrl.substr(0, this.parentUrl.lastIndexOf("/")));
},
enumerable: true,
configurable: true
});
/**
* Updates this list intance with the supplied properties
*
* @param properties A plain object hash of values to update for the list
* @param eTag Value used in the IF-Match header, by default "*"
* @param listItemEntityTypeFullName The type name of the list's entities
*/
Item.prototype.update = function (properties, eTag, listItemEntityTypeFullName) {
var _this = this;
if (eTag === void 0) { eTag = "*"; }
if (listItemEntityTypeFullName === void 0) { listItemEntityTypeFullName = null; }
return new Promise(function (resolve, reject) {
var removeDependency = _this.addBatchDependency();
return _this.ensureListItemEntityTypeName(listItemEntityTypeFullName).then(function (listItemEntityType) {
var postBody = common.jsS(common.extend(metadata(listItemEntityType), properties));
removeDependency();
return _this.postCore({
body: postBody,
headers: {
"IF-Match": eTag,
"X-HTTP-Method": "MERGE",
},
}, new ItemUpdatedParser()).then(function (data) {
resolve({
data: data,
item: _this,
});
});
}).catch(function (e) { return reject(e); });
});
};
/**
* Gets the collection of people who have liked this item
*/
Item.prototype.getLikedBy = function () {
return this.clone(Item, "likedBy").postCore();
};
/**
* Likes this item as the current user
*/
Item.prototype.like = function () {
return this.clone(Item, "like").postCore();
};
/**
* Unlikes this item as the current user
*/
Item.prototype.unlike = function () {
return this.clone(Item, "unlike").postCore();
};
/**
* Moves the list item to the Recycle Bin and returns the identifier of the new Recycle Bin item.
*/
Item.prototype.recycle = function () {
return this.clone(Item, "recycle").postCore();
};
/**
* Gets a string representation of the full URL to the WOPI frame.
* If there is no associated WOPI application, or no associated action, an empty string is returned.
*
* @param action Display mode: 0: view, 1: edit, 2: mobileView, 3: interactivePreview
*/
Item.prototype.getWopiFrameUrl = function (action) {
if (action === void 0) { action = 0; }
var i = this.clone(Item, "getWOPIFrameUrl(@action)");
i.query.set("@action", action);
return i.postCore().then(function (data) {
// handle verbose mode
if (common.hOP(data, "GetWOPIFrameUrl")) {
return data.GetWOPIFrameUrl;
}
return data;
});
};
/**
* Validates and sets the values of the specified collection of fields for the list item.
*
* @param formValues The fields to change and their new values.
* @param newDocumentUpdate true if the list item is a document being updated after upload; otherwise false.
*/
Item.prototype.validateUpdateListItem = function (formValues, newDocumentUpdate) {
if (newDocumentUpdate === void 0) { newDocumentUpdate = false; }
return this.clone(Item, "validateupdatelistitem").postCore({
body: common.jsS({ "formValues": formValues, bNewDocumentUpdate: newDocumentUpdate }),
});
};
/**
* Get the like by information for a modern site page
*/
Item.prototype.getLikedByInformation = function () {
return this.clone(Item, "likedByInformation").expand("likedby").getCore();
};
/**
* Ensures we have the proper list item entity type name, either from the value provided or from the list
*
* @param candidatelistItemEntityTypeFullName The potential type name
*/
Item.prototype.ensureListItemEntityTypeName = function (candidatelistItemEntityTypeFullName) {
return candidatelistItemEntityTypeFullName ?
Promise.resolve(candidatelistItemEntityTypeFullName) :
this.list.getListItemEntityTypeFullName();
};
return Item;
}(SharePointQueryableShareableItem));
/**
* Describes a collection of Version objects
*
*/
var ItemVersions = /** @class */ (function (_super) {
__extends(ItemVersions, _super);
function ItemVersions() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Gets a version by id
*
* @param versionId The id of the version to retrieve
*/
ItemVersions.prototype.getById = function (versionId) {
var v = new ItemVersion(this);
v.concat("(" + versionId + ")");
return v;
};
ItemVersions = __decorate([
defaultPath("versions")
], ItemVersions);
return ItemVersions;
}(SharePointQueryableCollection));
/**
* Describes a single Version instance
*
*/
var ItemVersion = /** @class */ (function (_super) {
__extends(ItemVersion, _super);
function ItemVersion() {
var _this = _super !== null && _super.apply(this, arguments) || this;
/**
* Delete a specific version of a file.
*
* @param eTag Value used in the IF-Match header, by default "*"
*/
_this.delete = _this._deleteWithETag;
return _this;
}
return ItemVersion;
}(SharePointQueryableInstance));
/**
* Provides paging functionality for list items
*/
var PagedItemCollection = /** @class */ (function () {
function PagedItemCollection(parent, nextUrl, results) {
this.parent = parent;
this.nextUrl = nextUrl;
this.results = results;
}
Object.defineProperty(PagedItemCollection.prototype, "hasNext", {
/**
* If true there are more results available in the set, otherwise there are not
*/
get: function () {
return typeof this.nextUrl === "string" && this.nextUrl.length > 0;
},
enumerable: true,
configurable: true
});
/**
* Gets the next set of results, or resolves to null if no results are available
*/
PagedItemCollection.prototype.getNext = function () {
if (this.hasNext) {
var items = new Items(this.nextUrl, null).configureFrom(this.parent);
return items.getPaged();
}
return new Promise(function (r) { return r(null); });
};
return PagedItemCollection;
}());
var PagedItemCollectionParser = /** @class */ (function (_super) {
__extends(PagedItemCollectionParser, _super);
function PagedItemCollectionParser(_parent) {
var _this = _super.call(this) || this;
_this._parent = _parent;
return _this;
}
PagedItemCollectionParser.prototype.parse = function (r) {
var _this = this;
return new Promise(function (resolve, reject) {
if (_this.handleError(r, reject)) {
r.json().then(function (json) {
var nextUrl = common.hOP(json, "d") && common.hOP(json.d, "__next") ? json.d.__next : json["odata.nextLink"];
resolve(new PagedItemCollection(_this._parent, nextUrl, _this.parseODataJSON(json)));
});
}
});
};
return PagedItemCollectionParser;
}(odata.ODataParserBase));
var ItemUpdatedParser = /** @class */ (function (_super) {
__extends(ItemUpdatedParser, _super);
function ItemUpdatedParser() {
return _super !== null && _super.apply(this, arguments) || this;
}
ItemUpdatedParser.prototype.parse = function (r) {
var _this = this;
return new Promise(function (resolve, reject) {
if (_this.handleError(r, reject)) {
resolve({
"odata.etag": r.headers.get("etag"),
});
}
});
};
return ItemUpdatedParser;
}(odata.ODataParserBase));
/**
* Describes a collection of File objects
*
*/
var Files = /** @class */ (function (_super) {
__extends(Files, _super);
function Files() {
return _super !== null && _super.apply(this, arguments) || this;
}
Files_1 = Files;
/**
* Gets a File by filename
*
* @param name The name of the file, including extension.
*/
Files.prototype.getByName = function (name) {
var f = new File(this);
f.concat("('" + name + "')");
return f;
};
/**
* Uploads a file. Not supported for batching
*
* @param url The folder-relative url of the file.
* @param content The file contents blob.
* @param shouldOverWrite Should a file with the same name in the same location be overwritten? (default: true)
* @returns The new File and the raw response.
*/
Files.prototype.add = function (url, content, shouldOverWrite) {
var _this = this;
if (shouldOverWrite === void 0) { shouldOverWrite = true; }
return new Files_1(this, "add(overwrite=" + shouldOverWrite + ",url='" + url + "')")
.postCore({
body: content,
}).then(function (response) {
return {
data: response,
file: _this.getByName(url),
};
});
};
/**
* Uploads a file. Not supported for batching
*
* @param url The folder-relative url of the file.
* @param content The Blob file content to add
* @param progress A callback function which can be used to track the progress of the upload
* @param shouldOverWrite Should a file with the same name in the same location be overwritten? (default: true)
* @param chunkSize The size of each file slice, in bytes (default: 10485760)
* @returns The new File and the raw response.
*/
Files.prototype.addChunked = function (url, content, progress, shouldOverWrite, chunkSize) {
var _this = this;
if (shouldOverWrite === void 0) { shouldOverWrite = true; }
if (chunkSize === void 0) { chunkSize = 10485760; }
var adder = this.clone(Files_1, "add(overwrite=" + shouldOverWrite + ",url='" + url + "')", false);
return adder.postCore()
.then(function () { return _this.getByName(url); })
.then(function (file) { return file.setContentChunked(content, progress, chunkSize); });
};
/**
* Adds a ghosted file to an existing list or document library. Not supported for batching.
*
* @param fileUrl The server-relative url where you want to save the file.
* @param templateFileType The type of use to create the file.
* @returns The template file that was added and the raw response.
*/
Files.prototype.addTemplateFile = function (fileUrl, templateFileType) {
var _this = this;
return this.clone(Files_1, "addTemplateFile(urloffile='" + fileUrl + "',templatefiletype=" + templateFileType + ")", false)
.postCore().then(function (response) {
return {
data: response,
file: _this.getByName(fileUrl),
};
});
};
var Files_1;
Files = Files_1 = __decorate([
defaultPath("files")
], Files);
return Files;
}(SharePointQueryableCollection));
/**
* Describes a single File instance
*
*/
var File = /** @class */ (function (_super) {
__extends(File, _super);
function File() {
return _super !== null && _super.apply(this, arguments) || this;
}
Object.defineProperty(File.prototype, "listItemAllFields", {
/**
* Gets a value that specifies the list item field values for the list item corresponding to the file.
*
*/
get: function () {
return new SharePointQueryableInstance(this, "listItemAllFields");
},
enumerable: true,
configurable: true
});
Object.defineProperty(File.prototype, "versions", {
/**
* Gets a collection of versions
*
*/
get: function () {
return new Versions(this);
},
enumerable: true,
configurable: true
});
/**
* Approves the file submitted for content approval with the specified comment.
* Only documents in lists that are enabled for content approval can be approved.
*
* @param comment The comment for the approval.
*/
File.prototype.approve = function (comment) {
if (comment === void 0) { comment = ""; }
return this.clone(File, "approve(comment='" + comment + "')").postCore();
};
/**
* Stops the chunk upload session without saving the uploaded data. Does not support batching.
* If the file doesn’t already exist in the library, the partially uploaded file will be deleted.
* Use this in response to user action (as in a request to cancel an upload) or an error or exception.
* Use the uploadId value that was passed to the StartUpload method that started the upload session.
* This method is currently available only on Office 365.
*
* @param uploadId The unique identifier of the upload session.
*/
File.prototype.cancelUpload = function (uploadId) {
return this.clone(File, "cancelUpload(uploadId=guid'" + uploadId + "')", false).postCore();
};
/**
* Checks the file in to a document library based on the check-in type.
*
* @param comment A comment for the check-in. Its length must be <= 1023.
* @param checkinType The check-in type for the file.
*/
File.prototype.checkin = function (comment, checkinType) {
if (comment === void 0) { comment = ""; }
if (checkinType === void 0) { checkinType = exports.CheckinType.Major; }
if (comment.length > 1023) {
throw Error("The maximum comment length is 1023 characters.");
}
return this.clone(File, "checkin(comment='" + comment + "',checkintype=" + checkinType + ")").postCore();
};
/**
* Checks out the file from a document library.
*/
File.prototype.checkout = function () {
return this.clone(File, "checkout").postCore();
};
/**
* Copies the file to the destination url.
*
* @param url The absolute url or server relative url of the destination file path to copy to.
* @param shouldOverWrite Should a file with the same name in the same location be overwritten?
*/
File.prototype.copyTo = function (url, shouldOverWrite) {
if (shouldOverWrite === void 0) { shouldOverWrite = true; }
return this.clone(File, "copyTo(strnewurl='" + url + "',boverwrite=" + shouldOverWrite + ")").postCore();
};
/**
* Delete this file.
*
* @param eTag Value used in the IF-Match header, by default "*"
*/
File.prototype.delete = function (eTag) {
if (eTag === void 0) { eTag = "*"; }
return this.clone(File, null).postCore({
headers: {
"IF-Match": eTag,
"X-HTTP-Method": "DELETE",
},
});
};
/**
* Denies approval for a file that was submitted for content approval.
* Only documents in lists that are enabled for content approval can be denied.
*
* @param comment The comment for the denial.
*/
File.prototype.deny = function (comment) {
if (comment === void 0) { comment = ""; }
if (comment.length > 1023) {
throw Error("The maximum comment length is 1023 characters.");
}
return this.clone(File, "deny(comment='" + comment + "')").postCore();
};
/**
* Specifies the control set used to access, modify, or add Web Parts associated with this Web Part Page and view.
* An exception is thrown if the file is not an ASPX page.
*
* @param scope The WebPartsPersonalizationScope view on the Web Parts page.
*/
File.prototype.getLimitedWebPartManager = function (scope) {
if (scope === void 0) { scope = exports.WebPartsPersonalizationScope.Shared; }
return new LimitedWebPartManager(this, "getLimitedWebPartManager(scope=" + scope + ")");
};
/**
* Moves the file to the specified destination url.
*
* @param url The absolute url or server relative url of the destination file path to move to.
* @param moveOperations The bitwise MoveOperations value for how to move the file.
*/
File.prototype.moveTo = function (url, moveOperations) {
if (moveOperations === void 0) { moveOperations = exports.MoveOperations.Overwrite; }
return this.clone(File, "moveTo(newurl='" + url + "',flags=" + moveOperations + ")").postCore();
};
/**
* Submits the file for content approval with the specified comment.
*
* @param comment The comment for the published file. Its length must be <= 1023.
*/
File.prototype.publish = function (comment) {
if (comment === void 0) { comment = ""; }
if (comment.length > 1023) {
throw Error("The maximum comment length is 1023 characters.");
}
return this.clone(File, "publish(comment='" + comment + "')").postCore();
};
/**
* Moves the file to the Recycle Bin and returns the identifier of the new Recycle Bin item.
*
* @returns The GUID of the recycled file.
*/
File.prototype.recycle = function () {
return this.clone(File, "recycle").postCore();
};
/**
* Reverts an existing checkout for the file.
*
*/
File.prototype.undoCheckout = function () {
return this.clone(File, "undoCheckout").postCore();
};
/**
* Removes the file from content approval or unpublish a major version.
*
* @param comment The comment for the unpublish operation. Its length must be <= 1023.
*/
File.prototype.unpublish = function (comment) {
if (comment === void 0) { comment = ""; }
if (comment.length > 1023) {
throw Error("The maximum comment length is 1023 characters.");
}
return this.clone(File, "unpublish(comment='" + comment + "')").postCore();
};
/**
* Gets the contents of the file as text. Not supported in batching.
*
*/
File.prototype.getText = function () {
return this.clone(File, "$value", false).get(new odata.TextParser(), { headers: { "binaryStringResponseBody": "true" } });
};
/**
* Gets the contents of the file as a blob, does not work in Node.js. Not supported in batching.
*
*/
File.prototype.getBlob = function () {
return this.clone(File, "$value", false).get(new odata.BlobParser(), { headers: { "binaryStringResponseBody": "true" } });
};
/**
* Gets the contents of a file as an ArrayBuffer, works in Node.js. Not supported in batching.
*/
File.prototype.getBuffer = function () {
return this.clone(File, "$value", false).get(new odata.BufferParser(), { headers: { "binaryStringResponseBody": "true" } });
};
/**
* Gets the contents of a file as an ArrayBuffer, works in Node.js. Not supported in batching.
*/
File.prototype.getJSON = function () {
return this.clone(File, "$value", false).get(new odata.JSONParser(), { headers: { "binaryStringResponseBody": "true" } });
};
/**
* Sets the content of a file, for large files use setContentChunked. Not supported in batching.
*
* @param content The file content
*
*/
File.prototype.setContent = function (content) {
var _this = this;
return this.clone(File, "$value", false).postCore({
body: content,
headers: {
"X-HTTP-Method": "PUT",
},
}).then(function (_) { return new File(_this); });
};
/**
* Gets the associated list item for this folder, loading the default properties
*/
File.prototype.getItem = function () {
var selects = [];
for (var _i = 0; _i < arguments.length; _i++) {
selects[_i] = arguments[_i];
}
var q = this.listItemAllFields;
return q.select.apply(q, selects).get().then(function (d) {
return common.extend(new Item(odataUrlFrom(d)), d);
});
};
/**
* Sets the contents of a file using a chunked upload approach. Not supported in batching.
*
* @param file The file to upload
* @param progress A callback function which can be used to track the progress of the upload
* @param chunkSize The size of each file slice, in bytes (default: 10485760)
*/
File.prototype.setContentChunked = function (file, progress, chunkSize) {
var _this = this;
if (chunkSize === void 0) { chunkSize = 10485760; }
if (progress === undefined) {
progress = function () { return null; };
}
var fileSize = file.size;
var blockCount = parseInt((file.size / chunkSize).toString(), 10) + ((file.size % chunkSize === 0) ? 1 : 0);
var uploadId = common.getGUID();
// start the chain with the first fragment
progress({ uploadId: uploadId, blockNumber: 1, chunkSize: chunkSize, currentPointer: 0, fileSize: fileSize, stage: "starting", totalBlocks: blockCount });
var chain = this.startUpload(uploadId, file.slice(0, chunkSize));
var _loop_1 = function (i) {
chain = chain.then(function (pointer) {
progress({ uploadId: uploadId, blockNumber: i, chunkSize: chunkSize, currentPointer: pointer, fileSize: fileSize, stage: "continue", totalBlocks: blockCount });
return _this.continueUpload(uploadId, pointer, file.slice(pointer, pointer + chunkSize));
});
};
// skip the first and last blocks
for (var i = 2; i < blockCount; i++) {
_loop_1(i);
}
return chain.then(function (pointer) {
progress({ uploadId: uploadId, blockNumber: blockCount, chunkSize: chunkSize, currentPointer: pointer, fileSize: fileSize, stage: "finishing", totalBlocks: blockCount });
return _this.finishUpload(uploadId, pointer, file.slice(pointer));
});
};
/**
* Starts a new chunk upload session and uploads the first fragment.
* The current file content is not changed when this method completes.
* The method is idempotent (and therefore does not change the result) as long as you use the same values for uploadId and stream.
* The upload session ends either when you use the CancelUpload method or when you successfully
* complete the upload session by passing the rest of the file contents through the ContinueUpload and FinishUpload methods.
* The StartUpload and ContinueUpload methods return the size of the running total of uploaded data in bytes,
* so you can pass those return values to subsequent uses of ContinueUpload and FinishUpload.
* This method is currently available only on Office 365.
*
* @param uploadId The unique identifier of the upload session.
* @param fragment The file contents.
* @returns The size of the total uploaded data in bytes.
*/
File.prototype.startUpload = function (uploadId, fragment) {
return this.clone(File, "startUpload(uploadId=guid'" + uploadId + "')", false)
.postCore({ body: fragment })
.then(function (n) {
// When OData=verbose the payload has the following shape:
// { StartUpload: "10485760" }
if (typeof n === "object") {
n = n.StartUpload;
}
return parseFloat(n);
});
};
/**
* Continues the chunk upload session with an additional fragment.
* The current file content is not changed.
* Use the uploadId value that was passed to the StartUpload method that started the upload session.
* This method is currently available only on Office 365.
*
* @param uploadId The unique identifier of the upload session.
* @param fileOffset The size of the offset into the file where the fragment starts.
* @param fragment The file contents.
* @returns The size of the total uploaded data in bytes.
*/
File.prototype.continueUpload = function (uploadId, fileOffset, fragment) {
return this.clone(File, "continueUpload(uploadId=guid'" + uploadId + "',fileOffset=" + fileOffset + ")", false)
.postCore({ body: fragment })
.then(function (n) {
// When OData=verbose the payload has the following shape:
// { ContinueUpload: "20971520" }
if (typeof n === "object") {
n = n.ContinueUpload;
}
return parseFloat(n);
});
};
/**
* Uploads the last file fragment and commits the file. The current file content is changed when this method completes.
* Use the uploadId value that was passed to the StartUpload method that started the upload session.
* This method is currently available only on Office 365.
*
* @param uploadId The unique identifier of the upload session.
* @param fileOffset The size of the offset into the file where the fragment starts.
* @param fragment The file contents.
* @returns The newly uploaded file.
*/
File.prototype.finishUpload = function (uploadId, fileOffset, fragment) {
return this.clone(File, "finishUpload(uploadId=guid'" + uploadId + "',fileOffset=" + fileOffset + ")", false)
.postCore({ body: fragment })
.then(function (response) {
return {
data: response,
file: new File(odataUrlFrom(response)),
};
});
};
return File;
}(SharePointQueryableShareableFile));
/**
* Describes a collection of Version objects
*
*/
var Versions = /** @class */ (function (_super) {
__extends(Versions, _super);
function Versions() {
return _super !== null && _super.apply(this, arguments) || this;
}
Versions_1 = Versions;
/**
* Gets a version by id
*
* @param versionId The id of the version to retrieve
*/
Versions.prototype.getById = function (versionId) {
var v = new Version(this);
v.concat("(" + versionId + ")");
return v;
};
/**
* Deletes all the file version objects in the collection.
*
*/
Versions.prototype.deleteAll = function () {
return new Versions_1(this, "deleteAll").postCore();
};
/**
* Deletes the specified version of the file.
*
* @param versionId The ID of the file version to delete.
*/
Versions.prototype.deleteById = function (versionId) {
return this.clone(Versions_1, "deleteById(vid=" + versionId + ")").postCore();
};
/**
* Recycles the specified version of the file.
*
* @param versionId The ID of the file version to delete.
*/
Versions.prototype.recycleByID = function (versionId) {
return this.clone(Versions_1, "recycleByID(vid=" + versionId + ")").postCore();
};
/**
* Deletes the file version object with the specified version label.
*
* @param label The version label of the file version to delete, for example: 1.2
*/
Versions.prototype.deleteByLabel = function (label) {
return this.clone(Versions_1, "deleteByLabel(versionlabel='" + label + "')").postCore();
};
/**
* Recycles the file version object with the specified version label.
*
* @param label The version label of the file version to delete, for example: 1.2
*/
Versions.prototype.recycleByLabel = function (label) {
return this.clone(Versions_1, "recycleByLabel(versionlabel='" + label + "')").postCore();
};
/**
* Creates a new file version from the file specified by the version label.
*
* @param label The version label of the file version to restore, for example: 1.2
*/
Versions.prototype.restoreByLabel = function (label) {
return this.clone(Versions_1, "restoreByLabel(versionlabel='" + label + "')").postCore();
};
var Versions_1;
Versions = Versions_1 = __decorate([
defaultPath("versions")
], Versions);
return Versions;
}(SharePointQueryableCollection));
/**
* Describes a single Version instance
*
*/
var Version = /** @class */ (function (_super) {
__extends(Version, _super);
function Version() {
var _this = _super !== null && _super.apply(this, arguments) || this;
/**
* Delete a specific version of a file.
*
* @param eTag Value used in the IF-Match header, by default "*"
*/
_this.delete = _this._deleteWithETag;
return _this;
// /**
// * Delete a specific version of a file.
// *
// * @param eTag Value used in the IF-Match header, by default "*"
// */
// public delete(eTag = "*"): Promise<void> {
// return this.postCore({
// headers: {
// "IF-Match": eTag,
// "X-HTTP-Method": "DELETE",
// },
// });
// }
}
return Version;
}(SharePointQueryableInstance));
(function (CheckinType) {
CheckinType[CheckinType["Minor"] = 0] = "Minor";
CheckinType[CheckinType["Major"] = 1] = "Major";
CheckinType[CheckinType["Overwrite"] = 2] = "Overwrite";
})(exports.CheckinType || (exports.CheckinType = {}));
(function (WebPartsPersonalizationScope) {
WebPartsPersonalizationScope[WebPartsPersonalizationScope["User"] = 0] = "User";
WebPartsPersonalizationScope[WebPartsPersonalizationScope["Shared"] = 1] = "Shared";
})(exports.WebPartsPersonalizationScope || (exports.WebPartsPersonalizationScope = {}));
(function (MoveOperations) {
MoveOperations[MoveOperations["Overwrite"] = 1] = "Overwrite";
MoveOperations[MoveOperations["AllowBrokenThickets"] = 8] = "AllowBrokenThickets";
})(exports.MoveOperations || (exports.MoveOperations = {}));
(function (TemplateFileType) {
TemplateFileType[TemplateFileType["StandardPage"] = 0] = "StandardPage";
TemplateFileType[TemplateFileType["WikiPage"] = 1] = "WikiPage";
TemplateFileType[TemplateFileType["FormPage"] = 2] = "FormPage";
TemplateFileType[TemplateFileType["ClientSidePage"] = 3] = "ClientSidePage";
})(exports.TemplateFileType || (exports.TemplateFileType = {}));
/**
* Represents an app catalog
*/
var AppCatalog = /** @class */ (function (_super) {
__extends(AppCatalog, _super);
function AppCatalog(baseUrl, path) {
if (path === void 0) { path = "_api/web/tenantappcatalog/AvailableApps"; }
return _super.call(this, extractWebUrl(typeof baseUrl === "string" ? baseUrl : baseUrl.toUrl()), path) || this;
}
/**
* Get details of specific app from the app catalog
* @param id - Specify the guid of the app
*/
AppCatalog.prototype.getAppById = function (id) {
return new App(this, "getById('" + id + "')");
};
/**
* Uploads an app package. Not supported for batching
*
* @param filename Filename to create.
* @param content app package data (eg: the .app or .sppkg file).
* @param shouldOverWrite Should an app with the same name in the same location be overwritten? (default: true)
* @returns Promise<AppAddResult>
*/
AppCatalog.prototype.add = function (filename, content, shouldOverWrite) {
if (shouldOverWrite === void 0) { shouldOverWrite = true; }
// you don't add to the availableapps collection
var adder = new AppCatalog(extractWebUrl(this.toUrl()), "_api/web/tenantappcatalog/add(overwrite=" + shouldOverWrite + ",url='" + filename + "')");
return adder.postCore({
body: content,
}).then(function (r) {
return {
data: r,
file: new File(odataUrlFrom(r)),
};
});
};
return AppCatalog;
}(SharePointQueryableCollection));
/**
* Represents the actions you can preform on a given app within the catalog
*/
var App = /** @class */ (function (_super) {
__extends(App, _super);
function App() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* This method deploys an app on the app catalog. It must be called in the context
* of the tenant app catalog web or it will fail.
*
* @param skipFeatureDeployment Deploy the app to the entire tenant
*/
App.prototype.deploy = function (skipFeatureDeployment) {
if (skipFeatureDeployment === void 0) { skipFeatureDeployment = false; }
return this.clone(App, "Deploy(" + skipFeatureDeployment + ")").postCore();
};
/**
* This method retracts a deployed app on the app catalog. It must be called in the context
* of the tenant app catalog web or it will fail.
*/
App.prototype.retract = function () {
return this.clone(App, "Retract").postCore();
};
/**
* This method allows an app which is already deployed to be installed on a web
*/
App.prototype.install = function () {
return this.clone(App, "Install").postCore();
};
/**
* This method allows an app which is already insatlled to be uninstalled on a web
*/
App.prototype.uninstall = function () {
return this.clone(App, "Uninstall").postCore();
};
/**
* This method allows an app which is already insatlled to be upgraded on a web
*/
App.prototype.upgrade = function () {
return this.clone(App, "Upgrade").postCore();
};
/**
* This method removes an app from the app catalog. It must be called in the context
* of the tenant app catalog web or it will fail.
*/
App.prototype.remove = function () {
return this.clone(App, "Remove").postCore();
};
return App;
}(SharePointQueryableInstance));
/**
* Manages a batch of OData operations
*/
var SPBatch = /** @class */ (function (_super) {
__extends(SPBatch, _super);
function SPBatch(baseUrl) {
var _this = _super.call(this) || this;
_this.baseUrl = baseUrl;
return _this;
}
/**
* Parses the response from a batch request into an array of Response instances
*
* @param body Text body of the response from the batch request
*/
SPBatch.ParseResponse = function (body) {
return new Promise(function (resolve, reject) {
var responses = [];
var header = "--batchresponse_";
// Ex. "HTTP/1.1 500 Internal Server Error"
var statusRegExp = new RegExp("^HTTP/[0-9.]+ +([0-9]+) +(.*)", "i");
var lines = body.split("\n");
var state = "batch";
var status;
var statusText;
for (var i = 0; i < lines.length; ++i) {
var line = lines[i];
switch (state) {
case "batch":
if (line.substr(0, header.length) === header) {
state = "batchHeaders";
}
else {
if (line.trim() !== "") {
throw Error("Invalid response, line " + i);
}
}
break;
case "batchHeaders":
if (line.trim() === "") {
state = "status";
}
break;
case "status":
var parts = statusRegExp.exec(line);
if (parts.length !== 3) {
throw Error("Invalid status, line " + i);
}
status = parseInt(parts[1], 10);
statusText = parts[2];
state = "statusHeaders";
break;
case "statusHeaders":
if (line.trim() === "") {
state = "body";
}
break;
case "body":
responses.push((status === 204) ? new Response() : new Response(line, { status: status, statusText: statusText }));
state = "batch";
break;
}
}
if (state !== "status") {
reject(Error("Unexpected end of input"));
}
resolve(responses);
});
};
SPBatch.prototype.executeImpl = function () {
var _this = this;
logging.Logger.write("[" + this.batchId + "] (" + (new Date()).getTime() + ") Executing batch with " + this.requests.length + " requests.", 1 /* Info */);
// if we don't have any requests, don't bother sending anything
// this could be due to caching further upstream, or just an empty batch
if (this.requests.length < 1) {
logging.Logger.write("Resolving empty batch.", 1 /* Info */);
return Promise.resolve();
}
// creating the client here allows the url to be populated for nodejs client as well as potentially
// any other hacks needed for other types of clients. Essentially allows the absoluteRequestUrl
// below to be correct
var client = new SPHttpClient();
// due to timing we need to get the absolute url here so we can use it for all the individual requests
// and for sending the entire batch
return toAbsoluteUrl(this.baseUrl).then(function (absoluteRequestUrl) {
// build all the requests, send them, pipe results in order to parsers
var batchBody = [];
var currentChangeSetId = "";
for (var i = 0; i < _this.requests.length; i++) {
var reqInfo = _this.requests[i];
if (reqInfo.method === "GET") {
if (currentChangeSetId.length > 0) {
// end an existing change set
batchBody.push("--changeset_" + currentChangeSetId + "--\n\n");
currentChangeSetId = "";
}
batchBody.push("--batch_" + _this.batchId + "\n");
}
else {
if (currentChangeSetId.length < 1) {
// start new change set
currentChangeSetId = common.getGUID();
batchBody.push("--batch_" + _this.batchId + "\n");
batchBody.push("Content-Type: multipart/mixed; boundary=\"changeset_" + currentChangeSetId + "\"\n\n");
}
batchBody.push("--changeset_" + currentChangeSetId + "\n");
}
// common batch part prefix
batchBody.push("Content-Type: application/http\n");
batchBody.push("Content-Transfer-Encoding: binary\n\n");
var headers = new Headers();
// this is the url of the individual request within the batch
var url = common.isUrlAbsolute(reqInfo.url) ? reqInfo.url : common.combine(absoluteRequestUrl, reqInfo.url);
logging.Logger.write("[" + _this.batchId + "] (" + (new Date()).getTime() + ") Adding request " + reqInfo.method + " " + url + " to batch.", 0 /* Verbose */);
if (reqInfo.method !== "GET") {
var method = reqInfo.method;
var castHeaders = reqInfo.options.headers;
if (common.hOP(reqInfo, "options") && common.hOP(reqInfo.options, "headers") && castHeaders["X-HTTP-Method"] !== undefined) {
method = castHeaders["X-HTTP-Method"];
delete castHeaders["X-HTTP-Method"];
}
batchBody.push(method + " " + url + " HTTP/1.1\n");
headers.set("Content-Type", "application/json;odata=verbose;charset=utf-8");
}
else {
batchBody.push(reqInfo.method + " " + url + " HTTP/1.1\n");
}
// merge global config headers
common.mergeHeaders(headers, SPRuntimeConfig.headers);
// merge per-request headers
if (reqInfo.options) {
common.mergeHeaders(headers, reqInfo.options.headers);
}
// lastly we apply any default headers we need that may not exist
if (!headers.has("Accept")) {
headers.append("Accept", "application/json");
}
if (!headers.has("Content-Type")) {
headers.append("Content-Type", "application/json;odata=verbose;charset=utf-8");
}
if (!headers.has("X-ClientService-ClientTag")) {
headers.append("X-ClientService-ClientTag", "PnPCoreJS:@pnp-1.2.8");
}
// write headers into batch body
headers.forEach(function (value, name) {
batchBody.push(name + ": " + value + "\n");
});
batchBody.push("\n");
if (reqInfo.options.body) {
batchBody.push(reqInfo.options.body + "\n\n");
}
}
if (currentChangeSetId.length > 0) {
// Close the changeset
batchBody.push("--changeset_" + currentChangeSetId + "--\n\n");
currentChangeSetId = "";
}
batchBody.push("--batch_" + _this.batchId + "--\n");
var batchOptions = {
"body": batchBody.join(""),
"headers": {
"Content-Type": "multipart/mixed; boundary=batch_" + _this.batchId,
},
"method": "POST",
};
logging.Logger.write("[" + _this.batchId + "] (" + (new Date()).getTime() + ") Sending batch request.", 1 /* Info */);
return client.fetch(common.combine(absoluteRequestUrl, "/_api/$batch"), batchOptions)
.then(function (r) { return r.text(); })
.then(SPBatch.ParseResponse)
.then(function (responses) {
if (responses.length !== _this.requests.length) {
throw Error("Could not properly parse responses to match requests in batch.");
}
logging.Logger.write("[" + _this.batchId + "] (" + (new Date()).getTime() + ") Resolving batched requests.", 1 /* Info */);
return responses.reduce(function (chain, response, index) {
var request = _this.requests[index];
logging.Logger.write("[" + request.id + "] (" + (new Date()).getTime() + ") Resolving request in batch " + _this.batchId + ".", 1 /* Info */);
return chain.then(function (_) { return request.parser.parse(response).then(request.resolve).catch(request.reject); });
}, Promise.resolve());
});
});
};
return SPBatch;
}(odata.ODataBatch));
(function (PromotedState) {
/**
* Regular client side page
*/
PromotedState[PromotedState["NotPromoted"] = 0] = "NotPromoted";
/**
* Page that will be promoted as news article after publishing
*/
PromotedState[PromotedState["PromoteOnPublish"] = 1] = "PromoteOnPublish";
/**
* Page that is promoted as news article
*/
PromotedState[PromotedState["Promoted"] = 2] = "Promoted";
})(exports.PromotedState || (exports.PromotedState = {}));
/**
* Gets the next order value 1 based for the provided collection
*
* @param collection Collection of orderable things
*/
function getNextOrder(collection) {
if (collection.length < 1) {
return 1;
}
return Math.max.apply(null, collection.map(function (i) { return i.order; })) + 1;
}
/**
* After https://stackoverflow.com/questions/273789/is-there-a-version-of-javascripts-string-indexof-that-allows-for-regular-expr/274094#274094
*
* @param this Types the called context this to a string in which the search will be conducted
* @param regex A regex or string to match
* @param startpos A starting position from which the search will begin
*/
function regexIndexOf(regex, startpos) {
if (startpos === void 0) { startpos = 0; }
var indexOf = this.substring(startpos).search(regex);
return (indexOf >= 0) ? (indexOf + (startpos)) : indexOf;
}
/**
* Finds bounded blocks of markup bounded by divs, ensuring to match the ending div even with nested divs in the interstitial markup
*
* @param html HTML to search
* @param boundaryStartPattern The starting pattern to find, typically a div with attribute
* @param collector A func to take the found block and provide a way to form it into a useful return that is added into the return array
*/
function getBoundedDivMarkup(html, boundaryStartPattern, collector) {
var blocks = [];
if (html === undefined || html === null) {
return blocks;
}
// remove some extra whitespace if present
var cleanedHtml = html.replace(/[\t\r\n]/g, "");
// find the first div
var startIndex = regexIndexOf.call(cleanedHtml, boundaryStartPattern);
if (startIndex < 0) {
// we found no blocks in the supplied html
return blocks;
}
// this loop finds each of the blocks
while (startIndex > -1) {
// we have one open div counting from the one found above using boundaryStartPattern so we need to ensure we find it's close
var openCounter = 1;
var searchIndex = startIndex + 1;
var nextDivOpen = -1;
var nextCloseDiv = -1;
// this loop finds the </div> tag that matches the opening of the control
while (true) {
// find both the next opening and closing div tags from our current searching index
nextDivOpen = regexIndexOf.call(cleanedHtml, /<div[^>]*>/i, searchIndex);
nextCloseDiv = regexIndexOf.call(cleanedHtml, /<\/div>/i, searchIndex);
if (nextDivOpen < 0) {
// we have no more opening divs, just set this to simplify checks below
nextDivOpen = cleanedHtml.length + 1;
}
// determine which we found first, then increment or decrement our counter
// and set the location to begin searching again
if (nextDivOpen < nextCloseDiv) {
openCounter++;
searchIndex = nextDivOpen + 1;
}
else if (nextCloseDiv < nextDivOpen) {
openCounter--;
searchIndex = nextCloseDiv + 1;
}
// once we have no open divs back to the level of the opening control div
// meaning we have all of the markup we intended to find
if (openCounter === 0) {
// get the bounded markup, +6 is the size of the ending </div> tag
var markup = cleanedHtml.substring(startIndex, nextCloseDiv + 6).trim();
// save the control data we found to the array
blocks.push(collector(markup));
// get out of our while loop
break;
}
if (openCounter > 1000 || openCounter < 0) {
// this is an arbitrary cut-off but likely we will not have 1000 nested divs
// something has gone wrong above and we are probably stuck in our while loop
// let's get out of our while loop and not hang everything
throw Error("getBoundedDivMarkup exceeded depth parameters.");
}
}
// get the start of the next control
startIndex = regexIndexOf.call(cleanedHtml, boundaryStartPattern, nextCloseDiv);
}
return blocks;
}
/**
* Normalizes the order value for all the sections, columns, and controls to be 1 based and stepped (1, 2, 3...)
*
* @param collection The collection to normalize
*/
function reindex(collection) {
for (var i = 0; i < collection.length; i++) {
collection[i].order = i + 1;
if (common.hOP(collection[i], "columns")) {
reindex(collection[i].columns);
}
else if (common.hOP(collection[i], "controls")) {
reindex(collection[i].controls);
}
}
}
/**
* Represents the data and methods associated with client side "modern" pages
*/
var ClientSidePage = /** @class */ (function (_super) {
__extends(ClientSidePage, _super);
/**
* Creates a new instance of the ClientSidePage class
*
* @param baseUrl The url or SharePointQueryable which forms the parent of this web collection
* @param commentsDisabled Indicates if comments are disabled, not valid until load is called
*/
function ClientSidePage(file, sections, commentsDisabled) {
if (sections === void 0) { sections = []; }
if (commentsDisabled === void 0) { commentsDisabled = false; }
var _this = _super.call(this, file) || this;
_this.sections = sections;
_this.commentsDisabled = commentsDisabled;
return _this;
}
/**
* Creates a new blank page within the supplied library
*
* @param library The library in which to create the page
* @param pageName Filename of the page, such as "page.aspx"
* @param title The display title of the page
* @param pageLayoutType Layout type of the page to use
*/
ClientSidePage.create = function (library, pageName, title, pageLayoutType) {
if (pageLayoutType === void 0) { pageLayoutType = "Article"; }
// see if file exists, if not create it
return library.rootFolder.files.select("Name").filter("Name eq '" + pageName + "'").get().then(function (fs) {
if (fs.length > 0) {
throw Error("A file with the name '" + pageName + "' already exists in the library '" + library.toUrl() + "'.");
}
// get our server relative path
return library.rootFolder.select("ServerRelativePath").get().then(function (path) {
var pageServerRelPath = common.combine("/", path.ServerRelativePath.DecodedUrl, pageName);
// add the template file
return library.rootFolder.files.addTemplateFile(pageServerRelPath, exports.TemplateFileType.ClientSidePage).then(function (far) {
// get the item associated with the file
return far.file.getItem().then(function (i) {
// update the item to have the correct values to create the client side page
return i.update({
BannerImageUrl: {
Url: "/_layouts/15/images/sitepagethumbnail.png",
},
CanvasContent1: "",
ClientSideApplicationId: "b6917cb1-93a0-4b97-a84d-7cf49975d4ec",
ContentTypeId: "0x0101009D1CB255DA76424F860D91F20E6C4118",
PageLayoutType: pageLayoutType,
PromotedState: 0 /* NotPromoted */,
Title: title,
}).then(function (iar) { return new ClientSidePage(iar.item.file, iar.item.CommentsDisabled); });
});
});
});
});
};
/**
* Creates a new ClientSidePage instance from the provided html content string
*
* @param html HTML markup representing the page
*/
ClientSidePage.fromFile = function (file) {
var page = new ClientSidePage(file);
return page.load().then(function (_) { return page; });
};
/**
* Converts a json object to an escaped string appropriate for use in attributes when storing client-side controls
*
* @param json The json object to encode into a string
*/
ClientSidePage.jsonToEscapedString = function (json) {
return common.jsS(json)
.replace(/"/g, """)
.replace(/:/g, ":")
.replace(/{/g, "{")
.replace(/}/g, "}")
.replace(/\[/g, "\[")
.replace(/\]/g, "\]")
.replace(/\*/g, "\*")
.replace(/\$/g, "\$")
.replace(/\./g, "\.");
};
/**
* Converts an escaped string from a client-side control attribute to a json object
*
* @param escapedString
*/
ClientSidePage.escapedStringToJson = function (escapedString) {
var unespace = function (escaped) {
var mapDict = [
[/"/g, "\""], [/:/g, ":"], [/{/g, "{"], [/}/g, "}"],
[/\\\\/g, "\\"], [/\\\?/g, "?"], [/\\\./g, "."], [/\\\[/g, "["], [/\\\]/g, "]"],
[/\\\(/g, "("], [/\\\)/g, ")"], [/\\\|/g, "|"], [/\\\+/g, "+"], [/\\\*/g, "*"],
[/\\\$/g, "$"],
];
return mapDict.reduce(function (r, m) { return r.replace(m[0], m[1]); }, escaped);
};
return common.objectDefinedNotNull(escapedString) ? JSON.parse(unespace(escapedString)) : null;
};
/**
* Add a section to this page
*/
ClientSidePage.prototype.addSection = function () {
var section = new CanvasSection(this, getNextOrder(this.sections));
this.sections.push(section);
return section;
};
/**
* Converts this page's content to html markup
*/
ClientSidePage.prototype.toHtml = function () {
// trigger reindex of the entire tree
reindex(this.sections);
var html = [];
html.push("<div>");
for (var i = 0; i < this.sections.length; i++) {
html.push(this.sections[i].toHtml());
}
html.push("</div>");
return html.join("");
};
/**
* Loads this page instance's content from the supplied html
*
* @param html html string representing the page's content
*/
ClientSidePage.prototype.fromHtml = function (html) {
var _this = this;
// reset sections
this.sections = [];
// gather our controls from the supplied html
getBoundedDivMarkup(html, /<div\b[^>]*data-sp-canvascontrol[^>]*?>/i, function (markup) {
// get the control type
var ct = /controlType":(\d*?),/i.exec(markup);
// if no control type is present this is a column which we give type 0 to let us process it
var controlType = ct == null || ct.length < 2 ? 0 : parseInt(ct[1], 10);
var control = null;
switch (controlType) {
case 0:
// empty canvas column
control = new CanvasColumn(null, 0);
control.fromHtml(markup);
_this.mergeColumnToTree(control);
break;
case 3:
// client side webpart
control = new ClientSideWebpart("");
control.fromHtml(markup);
_this.mergePartToTree(control);
break;
case 4:
// client side text
control = new ClientSideText();
control.fromHtml(markup);
_this.mergePartToTree(control);
break;
}
});
// refresh all the orders within the tree
reindex(this.sections);
return this;
};
/**
* Loads this page's content from the server
*/
ClientSidePage.prototype.load = function () {
var _this = this;
return this.getItem("CanvasContent1", "CommentsDisabled").then(function (item) {
_this.fromHtml(item.CanvasContent1);
_this.commentsDisabled = item.CommentsDisabled;
});
};
/**
* Persists the content changes (sections, columns, and controls)
*/
ClientSidePage.prototype.save = function () {
return this.updateProperties({ CanvasContent1: this.toHtml() });
};
/**
* Enables comments on this page
*/
ClientSidePage.prototype.enableComments = function () {
var _this = this;
return this.setCommentsOn(true).then(function (r) {
_this.commentsDisabled = false;
return r;
});
};
/**
* Disables comments on this page
*/
ClientSidePage.prototype.disableComments = function () {
var _this = this;
return this.setCommentsOn(false).then(function (r) {
_this.commentsDisabled = true;
return r;
});
};
/**
* Finds a control by the specified instance id
*
* @param id Instance id of the control to find
*/
ClientSidePage.prototype.findControlById = function (id) {
return this.findControl(function (c) { return c.id === id; });
};
/**
* Finds a control within this page's control tree using the supplied predicate
*
* @param predicate Takes a control and returns true or false, if true that control is returned by findControl
*/
ClientSidePage.prototype.findControl = function (predicate) {
// check all sections
for (var i = 0; i < this.sections.length; i++) {
// check all columns
for (var j = 0; j < this.sections[i].columns.length; j++) {
// check all controls
for (var k = 0; k < this.sections[i].columns[j].controls.length; k++) {
// check to see if the predicate likes this control
if (predicate(this.sections[i].columns[j].controls[k])) {
return this.sections[i].columns[j].controls[k];
}
}
}
}
// we found nothing so give nothing back
return null;
};
/**
* Like the modern site page
*/
ClientSidePage.prototype.like = function () {
return this.getItem().then(function (i) {
return i.like();
});
};
/**
* Unlike the modern site page
*/
ClientSidePage.prototype.unlike = function () {
return this.getItem().then(function (i) {
return i.unlike();
});
};
/**
* Get the liked by information for a modern site page
*/
ClientSidePage.prototype.getLikedByInformation = function () {
return this.getItem().then(function (i) {
return i.getLikedByInformation();
});
};
/**
* Sets the comments flag for a page
*
* @param on If true comments are enabled, false they are disabled
*/
ClientSidePage.prototype.setCommentsOn = function (on) {
return this.getItem().then(function (i) {
var updater = new Item(i, "SetCommentsDisabled(" + !on + ")");
return updater.update({});
});
};
/**
* Merges the control into the tree of sections and columns for this page
*
* @param control The control to merge
*/
ClientSidePage.prototype.mergePartToTree = function (control) {
var section = null;
var column = null;
var sectionFactor = 12;
var sectionIndex = 0;
var zoneIndex = 0;
// handle case where we don't have position data
if (common.hOP(control.controlData, "position")) {
if (common.hOP(control.controlData.position, "zoneIndex")) {
zoneIndex = control.controlData.position.zoneIndex;
}
if (common.hOP(control.controlData.position, "sectionIndex")) {
sectionIndex = control.controlData.position.sectionIndex;
}
if (common.hOP(control.controlData.position, "sectionFactor")) {
sectionFactor = control.controlData.position.sectionFactor;
}
}
var sections = this.sections.filter(function (s) { return s.order === zoneIndex; });
if (sections.length < 1) {
section = new CanvasSection(this, zoneIndex);
this.sections.push(section);
}
else {
section = sections[0];
}
var columns = section.columns.filter(function (c) { return c.order === sectionIndex; });
if (columns.length < 1) {
column = new CanvasColumn(section, sectionIndex, sectionFactor);
section.columns.push(column);
}
else {
column = columns[0];
}
control.column = column;
column.addControl(control);
};
/**
* Merges the supplied column into the tree
*
* @param column Column to merge
* @param position The position data for the column
*/
ClientSidePage.prototype.mergeColumnToTree = function (column) {
var order = common.hOP(column.controlData, "position") && common.hOP(column.controlData.position, "zoneIndex") ? column.controlData.position.zoneIndex : 0;
var section = null;
var sections = this.sections.filter(function (s) { return s.order === order; });
if (sections.length < 1) {
section = new CanvasSection(this, order);
this.sections.push(section);
}
else {
section = sections[0];
}
column.section = section;
section.columns.push(column);
};
/**
* Updates the properties of the underlying ListItem associated with this ClientSidePage
*
* @param properties Set of properties to update
* @param eTag Value used in the IF-Match header, by default "*"
*/
ClientSidePage.prototype.updateProperties = function (properties, eTag) {
if (eTag === void 0) { eTag = "*"; }
return this.getItem().then(function (i) { return i.update(properties, eTag); });
};
return ClientSidePage;
}(File));
var CanvasSection = /** @class */ (function () {
function CanvasSection(page, order, columns) {
if (columns === void 0) { columns = []; }
this.page = page;
this.order = order;
this.columns = columns;
this._memId = common.getGUID();
}
Object.defineProperty(CanvasSection.prototype, "defaultColumn", {
/**
* Default column (this.columns[0]) for this section
*/
get: function () {
if (this.columns.length < 1) {
this.addColumn(12);
}
return this.columns[0];
},
enumerable: true,
configurable: true
});
/**
* Adds a new column to this section
*/
CanvasSection.prototype.addColumn = function (factor) {
var column = new CanvasColumn(this, getNextOrder(this.columns), factor);
this.columns.push(column);
return column;
};
/**
* Adds a control to the default column for this section
*
* @param control Control to add to the default column
*/
CanvasSection.prototype.addControl = function (control) {
this.defaultColumn.addControl(control);
return this;
};
CanvasSection.prototype.toHtml = function () {
var html = [];
for (var i = 0; i < this.columns.length; i++) {
html.push(this.columns[i].toHtml());
}
return html.join("");
};
/**
* Removes this section and all contained columns and controls from the collection
*/
CanvasSection.prototype.remove = function () {
var _this = this;
this.page.sections = this.page.sections.filter(function (section) { return section._memId !== _this._memId; });
reindex(this.page.sections);
};
return CanvasSection;
}());
var CanvasControl = /** @class */ (function () {
function CanvasControl(controlType, dataVersion, column, order, id, controlData) {
if (column === void 0) { column = null; }
if (order === void 0) { order = 1; }
if (id === void 0) { id = common.getGUID(); }
if (controlData === void 0) { controlData = null; }
this.controlType = controlType;
this.dataVersion = dataVersion;
this.column = column;
this.order = order;
this.id = id;
this.controlData = controlData;
}
Object.defineProperty(CanvasControl.prototype, "jsonData", {
/**
* Value of the control's "data-sp-controldata" attribute
*/
get: function () {
return ClientSidePage.jsonToEscapedString(this.getControlData());
},
enumerable: true,
configurable: true
});
CanvasControl.prototype.fromHtml = function (html) {
this.controlData = ClientSidePage.escapedStringToJson(common.getAttrValueFromString(html, "data-sp-controldata"));
this.dataVersion = common.getAttrValueFromString(html, "data-sp-canvasdataversion");
this.controlType = this.controlData.controlType;
this.id = this.controlData.id;
};
return CanvasControl;
}());
var CanvasColumn = /** @class */ (function (_super) {
__extends(CanvasColumn, _super);
function CanvasColumn(section, order, factor, controls, dataVersion) {
if (factor === void 0) { factor = 12; }
if (controls === void 0) { controls = []; }
if (dataVersion === void 0) { dataVersion = "1.0"; }
var _this = _super.call(this, 0, dataVersion) || this;
_this.section = section;
_this.order = order;
_this.factor = factor;
_this.controls = controls;
return _this;
}
CanvasColumn.prototype.addControl = function (control) {
control.column = this;
this.controls.push(control);
return this;
};
CanvasColumn.prototype.getControl = function (index) {
return this.controls[index];
};
CanvasColumn.prototype.toHtml = function () {
var html = [];
if (this.controls.length < 1) {
html.push("<div data-sp-canvascontrol=\"\" data-sp-canvasdataversion=\"" + this.dataVersion + "\" data-sp-controldata=\"" + this.jsonData + "\"></div>");
}
else {
for (var i = 0; i < this.controls.length; i++) {
html.push(this.controls[i].toHtml(i + 1));
}
}
return html.join("");
};
CanvasColumn.prototype.fromHtml = function (html) {
_super.prototype.fromHtml.call(this, html);
this.controlData = ClientSidePage.escapedStringToJson(common.getAttrValueFromString(html, "data-sp-controldata"));
if (common.hOP(this.controlData, "position")) {
if (common.hOP(this.controlData.position, "sectionFactor")) {
this.factor = this.controlData.position.sectionFactor;
}
if (common.hOP(this.controlData.position, "sectionIndex")) {
this.order = this.controlData.position.sectionIndex;
}
}
};
CanvasColumn.prototype.getControlData = function () {
return {
displayMode: 2,
position: {
sectionFactor: this.factor,
sectionIndex: this.order,
zoneIndex: this.section.order,
},
};
};
/**
* Removes this column and all contained controls from the collection
*/
CanvasColumn.prototype.remove = function () {
var _this = this;
this.section.columns = this.section.columns.filter(function (column) { return column.id !== _this.id; });
reindex(this.column.controls);
};
return CanvasColumn;
}(CanvasControl));
/**
* Abstract class with shared functionality for parts
*/
var ClientSidePart = /** @class */ (function (_super) {
__extends(ClientSidePart, _super);
function ClientSidePart() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Removes this column and all contained controls from the collection
*/
ClientSidePart.prototype.remove = function () {
var _this = this;
this.column.controls = this.column.controls.filter(function (control) { return control.id !== _this.id; });
reindex(this.column.controls);
};
return ClientSidePart;
}(CanvasControl));
var ClientSideText = /** @class */ (function (_super) {
__extends(ClientSideText, _super);
function ClientSideText(text) {
if (text === void 0) { text = ""; }
var _this = _super.call(this, 4, "1.0") || this;
_this.text = text;
return _this;
}
Object.defineProperty(ClientSideText.prototype, "text", {
/**
* The text markup of this control
*/
get: function () {
return this._text;
},
set: function (text) {
if (!text.startsWith("<p>")) {
text = "<p>" + text + "</p>";
}
this._text = text;
},
enumerable: true,
configurable: true
});
ClientSideText.prototype.getControlData = function () {
return {
controlType: this.controlType,
editorType: "CKEditor",
id: this.id,
position: {
controlIndex: this.order,
sectionFactor: this.column.factor,
sectionIndex: this.column.order,
zoneIndex: this.column.section.order,
},
};
};
ClientSideText.prototype.toHtml = function (index) {
// set our order to the value passed in
this.order = index;
var html = [];
html.push("<div data-sp-canvascontrol=\"\" data-sp-canvasdataversion=\"" + this.dataVersion + "\" data-sp-controldata=\"" + this.jsonData + "\">");
html.push("<div data-sp-rte=\"\">");
html.push("" + this.text);
html.push("</div>");
html.push("</div>");
return html.join("");
};
ClientSideText.prototype.fromHtml = function (html) {
var _this = this;
_super.prototype.fromHtml.call(this, html);
this.text = "";
getBoundedDivMarkup(html, /<div[^>]*data-sp-rte[^>]*>/i, function (s) {
// now we need to grab the inner text between the divs
var match = /<div[^>]*data-sp-rte[^>]*>(.*?)<\/div>$/i.exec(s);
_this.text = match.length > 1 ? match[1] : "";
});
};
return ClientSideText;
}(ClientSidePart));
var ClientSideWebpart = /** @class */ (function (_super) {
__extends(ClientSideWebpart, _super);
function ClientSideWebpart(title, description, propertieJson, webPartId, htmlProperties, serverProcessedContent, canvasDataVersion) {
if (description === void 0) { description = ""; }
if (propertieJson === void 0) { propertieJson = {}; }
if (webPartId === void 0) { webPartId = ""; }
if (htmlProperties === void 0) { htmlProperties = ""; }
if (serverProcessedContent === void 0) { serverProcessedContent = null; }
if (canvasDataVersion === void 0) { canvasDataVersion = "1.0"; }
var _this = _super.call(this, 3, "1.0") || this;
_this.title = title;
_this.description = description;
_this.propertieJson = propertieJson;
_this.webPartId = webPartId;
_this.htmlProperties = htmlProperties;
_this.serverProcessedContent = serverProcessedContent;
_this.canvasDataVersion = canvasDataVersion;
return _this;
}
ClientSideWebpart.fromComponentDef = function (definition) {
var part = new ClientSideWebpart("");
part.import(definition);
return part;
};
ClientSideWebpart.prototype.import = function (component) {
this.webPartId = component.Id.replace(/^\{|\}$/g, "").toLowerCase();
var manifest = JSON.parse(component.Manifest);
this.title = manifest.preconfiguredEntries[0].title.default;
this.description = manifest.preconfiguredEntries[0].description.default;
this.dataVersion = "1.0";
this.propertieJson = this.parseJsonProperties(manifest.preconfiguredEntries[0].properties);
};
ClientSideWebpart.prototype.setProperties = function (properties) {
this.propertieJson = common.extend(this.propertieJson, properties);
return this;
};
ClientSideWebpart.prototype.getProperties = function () {
return this.propertieJson;
};
ClientSideWebpart.prototype.toHtml = function (index) {
// set our order to the value passed in
this.order = index;
// will form the value of the data-sp-webpartdata attribute
var data = {
dataVersion: this.dataVersion,
description: this.description,
id: this.webPartId,
instanceId: this.id,
properties: this.propertieJson,
serverProcessedContent: this.serverProcessedContent,
title: this.title,
};
var html = [];
html.push("<div data-sp-canvascontrol=\"\" data-sp-canvasdataversion=\"" + this.canvasDataVersion + "\" data-sp-controldata=\"" + this.jsonData + "\">");
html.push("<div data-sp-webpart=\"\" data-sp-webpartdataversion=\"" + this.dataVersion + "\" data-sp-webpartdata=\"" + ClientSidePage.jsonToEscapedString(data) + "\">");
html.push("<div data-sp-componentid>");
html.push(this.webPartId);
html.push("</div>");
html.push("<div data-sp-htmlproperties=\"\">");
html.push(this.renderHtmlProperties());
html.push("</div>");
html.push("</div>");
html.push("</div>");
return html.join("");
};
ClientSideWebpart.prototype.fromHtml = function (html) {
_super.prototype.fromHtml.call(this, html);
var webPartData = ClientSidePage.escapedStringToJson(common.getAttrValueFromString(html, "data-sp-webpartdata"));
this.title = webPartData.title;
this.description = webPartData.description;
this.webPartId = webPartData.id;
this.canvasDataVersion = common.getAttrValueFromString(html, "data-sp-canvasdataversion").replace(/\\\./, ".");
this.dataVersion = common.getAttrValueFromString(html, "data-sp-webpartdataversion").replace(/\\\./, ".");
this.setProperties(webPartData.properties);
if (webPartData.serverProcessedContent !== undefined) {
this.serverProcessedContent = webPartData.serverProcessedContent;
}
// get our html properties
var htmlProps = getBoundedDivMarkup(html, /<div\b[^>]*data-sp-htmlproperties[^>]*?>/i, function (markup) {
return markup.replace(/^<div\b[^>]*data-sp-htmlproperties[^>]*?>/i, "").replace(/<\/div>$/i, "");
});
this.htmlProperties = htmlProps.length > 0 ? htmlProps[0] : "";
};
ClientSideWebpart.prototype.getControlData = function () {
return {
controlType: this.controlType,
id: this.id,
position: {
controlIndex: this.order,
sectionFactor: this.column.factor,
sectionIndex: this.column.order,
zoneIndex: this.column.section.order,
},
webPartId: this.webPartId,
};
};
ClientSideWebpart.prototype.renderHtmlProperties = function () {
var html = [];
if (this.serverProcessedContent === undefined || this.serverProcessedContent === null) {
html.push(this.htmlProperties);
}
else if (this.serverProcessedContent !== undefined) {
if (this.serverProcessedContent.searchablePlainTexts !== undefined) {
var keys = Object.keys(this.serverProcessedContent.searchablePlainTexts);
for (var i = 0; i < keys.length; i++) {
html.push("<div data-sp-prop-name=\"" + keys[i] + "\" data-sp-searchableplaintext=\"true\">");
html.push(this.serverProcessedContent.searchablePlainTexts[keys[i]]);
html.push("</div>");
}
}
if (this.serverProcessedContent.imageSources !== undefined) {
var keys = Object.keys(this.serverProcessedContent.imageSources);
for (var i = 0; i < keys.length; i++) {
html.push("<img data-sp-prop-name=\"" + keys[i] + "\" src=\"" + this.serverProcessedContent.imageSources[keys[i]] + "\" />");
}
}
if (this.serverProcessedContent.links !== undefined) {
var keys = Object.keys(this.serverProcessedContent.links);
for (var i = 0; i < keys.length; i++) {
html.push("<a data-sp-prop-name=\"" + keys[i] + "\" href=\"" + this.serverProcessedContent.links[keys[i]] + "\"></a>");
}
}
}
return html.join("");
};
ClientSideWebpart.prototype.parseJsonProperties = function (props) {
// If the web part has the serverProcessedContent property then keep this one as it might be needed as input to render the web part HTML later on
if (props.webPartData !== undefined && props.webPartData.serverProcessedContent !== undefined) {
this.serverProcessedContent = props.webPartData.serverProcessedContent;
}
else if (props.serverProcessedContent !== undefined) {
this.serverProcessedContent = props.serverProcessedContent;
}
else {
this.serverProcessedContent = null;
}
if (props.webPartData !== undefined && props.webPartData.properties !== undefined) {
return props.webPartData.properties;
}
else if (props.properties !== undefined) {
return props.properties;
}
else {
return props;
}
};
return ClientSideWebpart;
}(ClientSidePart));
/**
* Represents a collection of navigation nodes
*
*/
var NavigationNodes = /** @class */ (function (_super) {
__extends(NavigationNodes, _super);
function NavigationNodes() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Gets a navigation node by id
*
* @param id The id of the node
*/
NavigationNodes.prototype.getById = function (id) {
var node = new NavigationNode(this);
node.concat("(" + id + ")");
return node;
};
/**
* Adds a new node to the collection
*
* @param title Display name of the node
* @param url The url of the node
* @param visible If true the node is visible, otherwise it is hidden (default: true)
*/
NavigationNodes.prototype.add = function (title, url, visible) {
var _this = this;
if (visible === void 0) { visible = true; }
var postBody = common.jsS(common.extend(metadata("SP.NavigationNode"), {
IsVisible: visible,
Title: title,
Url: url,
}));
return this.clone(NavigationNodes, null).postCore({ body: postBody }).then(function (data) {
return {
data: data,
node: _this.getById(data.Id),
};
});
};
/**
* Moves a node to be after another node in the navigation
*
* @param nodeId Id of the node to move
* @param previousNodeId Id of the node after which we move the node specified by nodeId
*/
NavigationNodes.prototype.moveAfter = function (nodeId, previousNodeId) {
var postBody = common.jsS({
nodeId: nodeId,
previousNodeId: previousNodeId,
});
return this.clone(NavigationNodes, "MoveAfter").postCore({ body: postBody });
};
return NavigationNodes;
}(SharePointQueryableCollection));
/**
* Represents an instance of a navigation node
*
*/
var NavigationNode = /** @class */ (function (_super) {
__extends(NavigationNode, _super);
function NavigationNode() {
return _super !== null && _super.apply(this, arguments) || this;
}
Object.defineProperty(NavigationNode.prototype, "children", {
/**
* Represents the child nodes of this node
*/
get: function () {
return new NavigationNodes(this, "Children");
},
enumerable: true,
configurable: true
});
/**
* Deletes this node and any child nodes
*/
NavigationNode.prototype.delete = function () {
return _super.prototype.deleteCore.call(this);
};
/**
* Updates this node
*
* @param properties Properties used to update this node
*/
NavigationNode.prototype.update = function (properties) {
var _this = this;
var postBody = common.jsS(common.extend({
"__metadata": { "type": "SP.NavigationNode" },
}, properties));
return this.postCore({
body: postBody,
headers: {
"X-HTTP-Method": "MERGE",
},
}).then(function (data) {
return {
data: data,
node: _this,
};
});
};
return NavigationNode;
}(SharePointQueryableInstance));
/**
* Exposes the navigation components
*
*/
var Navigation = /** @class */ (function (_super) {
__extends(Navigation, _super);
function Navigation() {
return _super !== null && _super.apply(this, arguments) || this;
}
Object.defineProperty(Navigation.prototype, "quicklaunch", {
/**
* Gets the quicklaunch navigation nodes for the current context
*
*/
get: function () {
return new NavigationNodes(this, "quicklaunch");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Navigation.prototype, "topNavigationBar", {
/**
* Gets the top bar navigation nodes for the current context
*
*/
get: function () {
return new NavigationNodes(this, "topnavigationbar");
},
enumerable: true,
configurable: true
});
Navigation = __decorate([
defaultPath("navigation")
], Navigation);
return Navigation;
}(SharePointQueryable));
/**
* Represents the top level navigation service
*/
var NavigationService = /** @class */ (function (_super) {
__extends(NavigationService, _super);
function NavigationService(path) {
if (path === void 0) { path = null; }
return _super.call(this, "_api/navigation", path) || this;
}
/**
* The MenuState service operation returns a Menu-State (dump) of a SiteMapProvider on a site.
*
* @param menuNodeKey MenuNode.Key of the start node within the SiteMapProvider If no key is provided the SiteMapProvider.RootNode will be the root of the menu state.
* @param depth Depth of the dump. If no value is provided a dump with the depth of 10 is returned
* @param mapProviderName The name identifying the SiteMapProvider to be used
* @param customProperties comma seperated list of custom properties to be returned.
*/
NavigationService.prototype.getMenuState = function (menuNodeKey, depth, mapProviderName, customProperties) {
if (menuNodeKey === void 0) { menuNodeKey = null; }
if (depth === void 0) { depth = 10; }
if (mapProviderName === void 0) { mapProviderName = null; }
if (customProperties === void 0) { customProperties = null; }
return (new NavigationService("MenuState")).postCore({
body: common.jsS({
customProperties: customProperties,
depth: depth,
mapProviderName: mapProviderName,
menuNodeKey: menuNodeKey,
}),
});
};
/**
* Tries to get a SiteMapNode.Key for a given URL within a site collection.
*
* @param currentUrl A url representing the SiteMapNode
* @param mapProviderName The name identifying the SiteMapProvider to be used
*/
NavigationService.prototype.getMenuNodeKey = function (currentUrl, mapProviderName) {
if (mapProviderName === void 0) { mapProviderName = null; }
return (new NavigationService("MenuNodeKey")).postCore({
body: common.jsS({
currentUrl: currentUrl,
mapProviderName: mapProviderName,
}),
});
};
return NavigationService;
}(SharePointQueryable));
/**
* Describes regional settings ODada object
*/
var RegionalSettings = /** @class */ (function (_super) {
__extends(RegionalSettings, _super);
function RegionalSettings() {
return _super !== null && _super.apply(this, arguments) || this;
}
Object.defineProperty(RegionalSettings.prototype, "installedLanguages", {
/**
* Gets the collection of languages used in a server farm.
*/
get: function () {
return new InstalledLanguages(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(RegionalSettings.prototype, "globalInstalledLanguages", {
/**
* Gets the collection of language packs that are installed on the server.
*/
get: function () {
return new InstalledLanguages(this, "globalinstalledlanguages");
},
enumerable: true,
configurable: true
});
Object.defineProperty(RegionalSettings.prototype, "timeZone", {
/**
* Gets time zone
*/
get: function () {
return new TimeZone(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(RegionalSettings.prototype, "timeZones", {
/**
* Gets time zones
*/
get: function () {
return new TimeZones(this);
},
enumerable: true,
configurable: true
});
RegionalSettings = __decorate([
defaultPath("regionalsettings")
], RegionalSettings);
return RegionalSettings;
}(SharePointQueryableInstance));
/**
* Describes installed languages ODada queriable collection
*/
var InstalledLanguages = /** @class */ (function (_super) {
__extends(InstalledLanguages, _super);
function InstalledLanguages() {
return _super !== null && _super.apply(this, arguments) || this;
}
InstalledLanguages = __decorate([
defaultPath("installedlanguages")
], InstalledLanguages);
return InstalledLanguages;
}(SharePointQueryableCollection));
/**
* Describes TimeZone ODada object
*/
var TimeZone = /** @class */ (function (_super) {
__extends(TimeZone, _super);
function TimeZone() {
return _super !== null && _super.apply(this, arguments) || this;
}
TimeZone_1 = TimeZone;
/**
* Gets an Local Time by UTC Time
*
* @param utcTime UTC Time as Date or ISO String
*/
TimeZone.prototype.utcToLocalTime = function (utcTime) {
var dateIsoString;
if (typeof utcTime === "string") {
dateIsoString = utcTime;
}
else {
dateIsoString = utcTime.toISOString();
}
return this.clone(TimeZone_1, "utctolocaltime('" + dateIsoString + "')")
.postCore()
.then(function (res) { return common.hOP(res, "UTCToLocalTime") ? res.UTCToLocalTime : res; });
};
/**
* Gets an UTC Time by Local Time
*
* @param localTime Local Time as Date or ISO String
*/
TimeZone.prototype.localTimeToUTC = function (localTime) {
var dateIsoString;
if (typeof localTime === "string") {
dateIsoString = localTime;
}
else {
dateIsoString = common.dateAdd(localTime, "minute", localTime.getTimezoneOffset() * -1).toISOString();
}
return this.clone(TimeZone_1, "localtimetoutc('" + dateIsoString + "')")
.postCore()
.then(function (res) { return common.hOP(res, "LocalTimeToUTC") ? res.LocalTimeToUTC : res; });
};
var TimeZone_1;
TimeZone = TimeZone_1 = __decorate([
defaultPath("timezone")
], TimeZone);
return TimeZone;
}(SharePointQueryableInstance));
/**
* Describes time zones queriable collection
*/
var TimeZones = /** @class */ (function (_super) {
__extends(TimeZones, _super);
function TimeZones() {
return _super !== null && _super.apply(this, arguments) || this;
}
TimeZones_1 = TimeZones;
// https://msdn.microsoft.com/en-us/library/office/jj247008.aspx - timezones ids
/**
* Gets an TimeZone by id
*
* @param id The integer id of the timezone to retrieve
*/
TimeZones.prototype.getById = function (id) {
// do the post and merge the result into a TimeZone instance so the data and methods are available
return this.clone(TimeZones_1, "GetById(" + id + ")").postCore({}, spODataEntity(TimeZone));
};
var TimeZones_1;
TimeZones = TimeZones_1 = __decorate([
defaultPath("timezones")
], TimeZones);
return TimeZones;
}(SharePointQueryableCollection));
var funcs = new Map([
["text", "Querytext"],
["template", "QueryTemplate"],
["sourceId", "SourceId"],
["trimDuplicatesIncludeId", ""],
["startRow", ""],
["rowLimit", ""],
["rankingModelId", ""],
["rowsPerPage", ""],
["selectProperties", ""],
["culture", ""],
["timeZoneId", ""],
["refinementFilters", ""],
["refiners", ""],
["hiddenConstraints", ""],
["sortList", ""],
["timeout", ""],
["hithighlightedProperties", ""],
["clientType", ""],
["personalizationData", ""],
["resultsURL", ""],
["queryTag", ""],
["properties", ""],
["queryTemplatePropertiesUrl", ""],
["reorderingRules", ""],
["hitHighlightedMultivaluePropertyLimit", ""],
["collapseSpecification", ""],
["uiLanguage", ""],
["desiredSnippetLength", ""],
["maxSnippetLength", ""],
["summaryLength", ""],
]);
var props = new Map([]);
function toPropCase(str) {
return str.replace(/^(.)/, function ($1) { return $1.toUpperCase(); });
}
/**
* Creates a new instance of the SearchQueryBuilder
*
* @param queryText Initial query text
* @param _query Any initial query configuration
*/
function SearchQueryBuilder(queryText, _query) {
if (queryText === void 0) { queryText = ""; }
if (_query === void 0) { _query = {}; }
return new Proxy({
query: Object.assign({
Querytext: queryText,
}, _query),
}, {
get: function (self, propertyKey, proxy) {
var pk = propertyKey.toString();
if (pk === "toSearchQuery") {
return function () { return self.query; };
}
if (funcs.has(pk)) {
return function () {
var value = [];
for (var _i = 0; _i < arguments.length; _i++) {
value[_i] = arguments[_i];
}
var mappedPk = funcs.get(pk);
self.query[mappedPk.length > 0 ? mappedPk : toPropCase(pk)] = value.length > 1 ? value : value[0];
return proxy;
};
}
var propKey = props.has(pk) ? props.get(pk) : toPropCase(pk);
self.query[propKey] = true;
return proxy;
},
});
}
/**
* Describes the search API
*
*/
var Search = /** @class */ (function (_super) {
__extends(Search, _super);
function Search() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* @returns Promise
*/
Search.prototype.execute = function (queryInit) {
var _this = this;
var query = this.parseQuery(queryInit);
var postBody = common.jsS({
request: common.extend(metadata("Microsoft.Office.Server.Search.REST.SearchRequest"), Object.assign({}, query, {
HitHighlightedProperties: this.fixArrProp(query.HitHighlightedProperties),
Properties: this.fixArrProp(query.Properties),
RefinementFilters: this.fixArrProp(query.RefinementFilters),
ReorderingRules: this.fixArrProp(query.ReorderingRules),
SelectProperties: this.fixArrProp(query.SelectProperties),
SortList: this.fixArrProp(query.SortList),
})),
});
// if we are using caching with this search request, then we need to handle some work upfront to enable that
if (this._useCaching) {
// force use of the cache for this request if .usingCaching was called
this._forceCaching = true;
// because all the requests use the same url they would collide in the cache we use a special key
var cacheKey = "PnPjs.SearchWithCaching(" + common.getHashCode(postBody) + ")";
if (common.objectDefinedNotNull(this._cachingOptions)) {
// if our key ends in the postquery url we overwrite it
if (/\/_api\/search\/postquery$/i.test(this._cachingOptions.key)) {
this._cachingOptions.key = cacheKey;
}
}
else {
this._cachingOptions = new odata.CachingOptions(cacheKey);
}
}
return this.postCore({ body: postBody }).then(function (data) { return new SearchResults(data, _this.toUrl(), query); });
};
/**
* Fix array property
*
* @param prop property to fix for container struct
*/
Search.prototype.fixArrProp = function (prop) {
if (typeof prop === "undefined") {
return ({ results: [] });
}
prop = common.isArray(prop) ? prop : [prop];
return common.hOP(prop, "results") ? prop : { results: prop };
};
/**
* Translates one of the query initializers into a SearchQuery instance
*
* @param query
*/
Search.prototype.parseQuery = function (query) {
var finalQuery;
if (typeof query === "string") {
finalQuery = { Querytext: query };
}
else if (query.toSearchQuery) {
finalQuery = query.toSearchQuery();
}
else {
finalQuery = query;
}
return finalQuery;
};
Search = __decorate([
defaultPath("_api/search/postquery")
], Search);
return Search;
}(SharePointQueryableInstance));
/**
* Describes the SearchResults class, which returns the formatted and raw version of the query response
*/
var SearchResults = /** @class */ (function () {
/**
* Creates a new instance of the SearchResult class
*
*/
function SearchResults(rawResponse, _url, _query, _raw, _primary) {
if (_raw === void 0) { _raw = null; }
if (_primary === void 0) { _primary = null; }
this._url = _url;
this._query = _query;
this._raw = _raw;
this._primary = _primary;
this._raw = rawResponse.postquery ? rawResponse.postquery : rawResponse;
}
Object.defineProperty(SearchResults.prototype, "ElapsedTime", {
get: function () {
return this.RawSearchResults.ElapsedTime;
},
enumerable: true,
configurable: true
});
Object.defineProperty(SearchResults.prototype, "RowCount", {
get: function () {
return this.RawSearchResults.PrimaryQueryResult.RelevantResults.RowCount;
},
enumerable: true,
configurable: true
});
Object.defineProperty(SearchResults.prototype, "TotalRows", {
get: function () {
return this.RawSearchResults.PrimaryQueryResult.RelevantResults.TotalRows;
},
enumerable: true,
configurable: true
});
Object.defineProperty(SearchResults.prototype, "TotalRowsIncludingDuplicates", {
get: function () {
return this.RawSearchResults.PrimaryQueryResult.RelevantResults.TotalRowsIncludingDuplicates;
},
enumerable: true,
configurable: true
});
Object.defineProperty(SearchResults.prototype, "RawSearchResults", {
get: function () {
return this._raw;
},
enumerable: true,
configurable: true
});
Object.defineProperty(SearchResults.prototype, "PrimarySearchResults", {
get: function () {
if (this._primary === null) {
this._primary = this.formatSearchResults(this._raw.PrimaryQueryResult.RelevantResults.Table.Rows);
}
return this._primary;
},
enumerable: true,
configurable: true
});
/**
* Gets a page of results
*
* @param pageNumber Index of the page to return. Used to determine StartRow
* @param pageSize Optional, items per page (default = 10)
*/
SearchResults.prototype.getPage = function (pageNumber, pageSize) {
// if we got all the available rows we don't have another page
if (this.TotalRows < this.RowCount) {
return Promise.resolve(null);
}
// if pageSize is supplied, then we use that regardless of any previous values
// otherwise get the previous RowLimit or default to 10
var rows = pageSize !== undefined ? pageSize : common.hOP(this._query, "RowLimit") ? this._query.RowLimit : 10;
var query = common.extend(this._query, {
RowLimit: rows,
StartRow: rows * (pageNumber - 1),
});
// we have reached the end
if (query.StartRow > this.TotalRows) {
return Promise.resolve(null);
}
var search = new Search(this._url, null);
return search.execute(query);
};
/**
* Formats a search results array
*
* @param rawResults The array to process
*/
SearchResults.prototype.formatSearchResults = function (rawResults) {
var results = new Array();
var tempResults = rawResults.results ? rawResults.results : rawResults;
for (var _i = 0, tempResults_1 = tempResults; _i < tempResults_1.length; _i++) {
var tempResult = tempResults_1[_i];
var cells = tempResult.Cells.results ? tempResult.Cells.results : tempResult.Cells;
results.push(cells.reduce(function (res, cell) {
Object.defineProperty(res, cell.Key, {
configurable: false,
enumerable: true,
value: cell.Value,
writable: false,
});
return res;
}, {}));
}
return results;
};
return SearchResults;
}());
(function (SortDirection) {
SortDirection[SortDirection["Ascending"] = 0] = "Ascending";
SortDirection[SortDirection["Descending"] = 1] = "Descending";
SortDirection[SortDirection["FQLFormula"] = 2] = "FQLFormula";
})(exports.SortDirection || (exports.SortDirection = {}));
(function (ReorderingRuleMatchType) {
ReorderingRuleMatchType[ReorderingRuleMatchType["ResultContainsKeyword"] = 0] = "ResultContainsKeyword";
ReorderingRuleMatchType[ReorderingRuleMatchType["TitleContainsKeyword"] = 1] = "TitleContainsKeyword";
ReorderingRuleMatchType[ReorderingRuleMatchType["TitleMatchesKeyword"] = 2] = "TitleMatchesKeyword";
ReorderingRuleMatchType[ReorderingRuleMatchType["UrlStartsWith"] = 3] = "UrlStartsWith";
ReorderingRuleMatchType[ReorderingRuleMatchType["UrlExactlyMatches"] = 4] = "UrlExactlyMatches";
ReorderingRuleMatchType[ReorderingRuleMatchType["ContentTypeIs"] = 5] = "ContentTypeIs";
ReorderingRuleMatchType[ReorderingRuleMatchType["FileExtensionMatches"] = 6] = "FileExtensionMatches";
ReorderingRuleMatchType[ReorderingRuleMatchType["ResultHasTag"] = 7] = "ResultHasTag";
ReorderingRuleMatchType[ReorderingRuleMatchType["ManualCondition"] = 8] = "ManualCondition";
})(exports.ReorderingRuleMatchType || (exports.ReorderingRuleMatchType = {}));
(function (QueryPropertyValueType) {
QueryPropertyValueType[QueryPropertyValueType["None"] = 0] = "None";
QueryPropertyValueType[QueryPropertyValueType["StringType"] = 1] = "StringType";
QueryPropertyValueType[QueryPropertyValueType["Int32Type"] = 2] = "Int32Type";
QueryPropertyValueType[QueryPropertyValueType["BooleanType"] = 3] = "BooleanType";
QueryPropertyValueType[QueryPropertyValueType["StringArrayType"] = 4] = "StringArrayType";
QueryPropertyValueType[QueryPropertyValueType["UnSupportedType"] = 5] = "UnSupportedType";
})(exports.QueryPropertyValueType || (exports.QueryPropertyValueType = {}));
var SearchBuiltInSourceId = /** @class */ (function () {
function SearchBuiltInSourceId() {
}
SearchBuiltInSourceId.Documents = "e7ec8cee-ded8-43c9-beb5-436b54b31e84";
SearchBuiltInSourceId.ItemsMatchingContentType = "5dc9f503-801e-4ced-8a2c-5d1237132419";
SearchBuiltInSourceId.ItemsMatchingTag = "e1327b9c-2b8c-4b23-99c9-3730cb29c3f7";
SearchBuiltInSourceId.ItemsRelatedToCurrentUser = "48fec42e-4a92-48ce-8363-c2703a40e67d";
SearchBuiltInSourceId.ItemsWithSameKeywordAsThisItem = "5c069288-1d17-454a-8ac6-9c642a065f48";
SearchBuiltInSourceId.LocalPeopleResults = "b09a7990-05ea-4af9-81ef-edfab16c4e31";
SearchBuiltInSourceId.LocalReportsAndDataResults = "203fba36-2763-4060-9931-911ac8c0583b";
SearchBuiltInSourceId.LocalSharePointResults = "8413cd39-2156-4e00-b54d-11efd9abdb89";
SearchBuiltInSourceId.LocalVideoResults = "78b793ce-7956-4669-aa3b-451fc5defebf";
SearchBuiltInSourceId.Pages = "5e34578e-4d08-4edc-8bf3-002acf3cdbcc";
SearchBuiltInSourceId.Pictures = "38403c8c-3975-41a8-826e-717f2d41568a";
SearchBuiltInSourceId.Popular = "97c71db1-58ce-4891-8b64-585bc2326c12";
SearchBuiltInSourceId.RecentlyChangedItems = "ba63bbae-fa9c-42c0-b027-9a878f16557c";
SearchBuiltInSourceId.RecommendedItems = "ec675252-14fa-4fbe-84dd-8d098ed74181";
SearchBuiltInSourceId.Wiki = "9479bf85-e257-4318-b5a8-81a180f5faa1";
return SearchBuiltInSourceId;
}());
var SearchSuggest = /** @class */ (function (_super) {
__extends(SearchSuggest, _super);
function SearchSuggest() {
return _super !== null && _super.apply(this, arguments) || this;
}
SearchSuggest.prototype.execute = function (query) {
this.mapQueryToQueryString(query);
return this.get().then(function (response) {
var mapper = common.hOP(response, "suggest") ? function (s) { return response.suggest[s].results; } : function (s) { return response[s]; };
return {
PeopleNames: mapper("PeopleNames"),
PersonalResults: mapper("PersonalResults"),
Queries: mapper("Queries"),
};
});
};
SearchSuggest.prototype.mapQueryToQueryString = function (query) {
var _this = this;
var setProp = function (q) { return function (checkProp) { return function (sp) {
if (common.hOP(q, checkProp)) {
_this.query.set(sp, q[checkProp].toString());
}
}; }; };
this.query.set("querytext", "'" + query.querytext + "'");
var querySetter = setProp(query);
querySetter("count")("inumberofquerysuggestions");
querySetter("personalCount")("inumberofresultsuggestions");
querySetter("preQuery")("fprequerysuggestions");
querySetter("hitHighlighting")("fhithighlighting");
querySetter("capitalize")("fcapitalizefirstletters");
querySetter("culture")("culture");
querySetter("stemming")("enablestemming");
querySetter("includePeople")("showpeoplenamesuggestions");
querySetter("queryRules")("enablequeryrules");
querySetter("prefixMatch")("fprefixmatchallterms");
};
SearchSuggest = __decorate([
defaultPath("_api/search/suggest")
], SearchSuggest);
return SearchSuggest;
}(SharePointQueryableInstance));
/**
* Describes a collection of List objects
*
*/
var Features = /** @class */ (function (_super) {
__extends(Features, _super);
function Features() {
return _super !== null && _super.apply(this, arguments) || this;
}
Features_1 = Features;
/**
* Adds a new list to the collection
*
* @param id The Id of the feature (GUID)
* @param force If true the feature activation will be forced
*/
Features.prototype.add = function (id, force) {
var _this = this;
if (force === void 0) { force = false; }
return this.clone(Features_1, "add").postCore({
body: common.jsS({
featdefScope: 0,
featureId: id,
force: force,
}),
}).then(function (data) {
return {
data: data,
feature: _this.getById(id),
};
});
};
/**
* Gets a list from the collection by guid id
*
* @param id The Id of the feature (GUID)
*/
Features.prototype.getById = function (id) {
var feature = new Feature(this);
feature.concat("('" + id + "')");
return feature;
};
/**
* Removes (deactivates) a feature from the collection
*
* @param id The Id of the feature (GUID)
* @param force If true the feature deactivation will be forced
*/
Features.prototype.remove = function (id, force) {
if (force === void 0) { force = false; }
return this.clone(Features_1, "remove").postCore({
body: common.jsS({
featureId: id,
force: force,
}),
});
};
var Features_1;
Features = Features_1 = __decorate([
defaultPath("features")
], Features);
return Features;
}(SharePointQueryableCollection));
var Feature = /** @class */ (function (_super) {
__extends(Feature, _super);
function Feature() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Removes (deactivates) a feature from the collection
*
* @param force If true the feature deactivation will be forced
*/
Feature.prototype.deactivate = function (force) {
var _this = this;
if (force === void 0) { force = false; }
var removeDependency = this.addBatchDependency();
var idGet = new Feature(this).select("DefinitionId");
return idGet.get().then(function (feature) {
var promise = _this.getParent(Features, _this.parentUrl, "", _this.batch).remove(feature.DefinitionId, force);
removeDependency();
return promise;
});
};
return Feature;
}(SharePointQueryableInstance));
var RelatedItemManagerImpl = /** @class */ (function (_super) {
__extends(RelatedItemManagerImpl, _super);
function RelatedItemManagerImpl() {
return _super !== null && _super.apply(this, arguments) || this;
}
RelatedItemManagerImpl_1 = RelatedItemManagerImpl;
RelatedItemManagerImpl.FromUrl = function (url) {
if (url === null) {
return new RelatedItemManagerImpl_1("");
}
var index = url.indexOf("_api/");
if (index > -1) {
return new RelatedItemManagerImpl_1(url.substr(0, index));
}
return new RelatedItemManagerImpl_1(url);
};
RelatedItemManagerImpl.prototype.getRelatedItems = function (sourceListName, sourceItemId) {
var query = this.clone(RelatedItemManagerImpl_1, null);
query.concat(".GetRelatedItems");
return query.postCore({
body: common.jsS({
SourceItemID: sourceItemId,
SourceListName: sourceListName,
}),
});
};
RelatedItemManagerImpl.prototype.getPageOneRelatedItems = function (sourceListName, sourceItemId) {
var query = this.clone(RelatedItemManagerImpl_1, null);
query.concat(".GetPageOneRelatedItems");
return query.postCore({
body: common.jsS({
SourceItemID: sourceItemId,
SourceListName: sourceListName,
}),
});
};
RelatedItemManagerImpl.prototype.addSingleLink = function (sourceListName, sourceItemId, sourceWebUrl, targetListName, targetItemID, targetWebUrl, tryAddReverseLink) {
if (tryAddReverseLink === void 0) { tryAddReverseLink = false; }
var query = this.clone(RelatedItemManagerImpl_1, null);
query.concat(".AddSingleLink");
return query.postCore({
body: common.jsS({
SourceItemID: sourceItemId,
SourceListName: sourceListName,
SourceWebUrl: sourceWebUrl,
TargetItemID: targetItemID,
TargetListName: targetListName,
TargetWebUrl: targetWebUrl,
TryAddReverseLink: tryAddReverseLink,
}),
});
};
/**
* Adds a related item link from an item specified by list name and item id, to an item specified by url
*
* @param sourceListName The source list name or list id
* @param sourceItemId The source item id
* @param targetItemUrl The target item url
* @param tryAddReverseLink If set to true try to add the reverse link (will not return error if it fails)
*/
RelatedItemManagerImpl.prototype.addSingleLinkToUrl = function (sourceListName, sourceItemId, targetItemUrl, tryAddReverseLink) {
if (tryAddReverseLink === void 0) { tryAddReverseLink = false; }
var query = this.clone(RelatedItemManagerImpl_1, null);
query.concat(".AddSingleLinkToUrl");
return query.postCore({
body: common.jsS({
SourceItemID: sourceItemId,
SourceListName: sourceListName,
TargetItemUrl: targetItemUrl,
TryAddReverseLink: tryAddReverseLink,
}),
});
};
/**
* Adds a related item link from an item specified by url, to an item specified by list name and item id
*
* @param sourceItemUrl The source item url
* @param targetListName The target list name or list id
* @param targetItemId The target item id
* @param tryAddReverseLink If set to true try to add the reverse link (will not return error if it fails)
*/
RelatedItemManagerImpl.prototype.addSingleLinkFromUrl = function (sourceItemUrl, targetListName, targetItemId, tryAddReverseLink) {
if (tryAddReverseLink === void 0) { tryAddReverseLink = false; }
var query = this.clone(RelatedItemManagerImpl_1, null);
query.concat(".AddSingleLinkFromUrl");
return query.postCore({
body: common.jsS({
SourceItemUrl: sourceItemUrl,
TargetItemID: targetItemId,
TargetListName: targetListName,
TryAddReverseLink: tryAddReverseLink,
}),
});
};
RelatedItemManagerImpl.prototype.deleteSingleLink = function (sourceListName, sourceItemId, sourceWebUrl, targetListName, targetItemId, targetWebUrl, tryDeleteReverseLink) {
if (tryDeleteReverseLink === void 0) { tryDeleteReverseLink = false; }
var query = this.clone(RelatedItemManagerImpl_1, null);
query.concat(".DeleteSingleLink");
return query.postCore({
body: common.jsS({
SourceItemID: sourceItemId,
SourceListName: sourceListName,
SourceWebUrl: sourceWebUrl,
TargetItemID: targetItemId,
TargetListName: targetListName,
TargetWebUrl: targetWebUrl,
TryDeleteReverseLink: tryDeleteReverseLink,
}),
});
};
var RelatedItemManagerImpl_1;
RelatedItemManagerImpl = RelatedItemManagerImpl_1 = __decorate([
defaultPath("_api/SP.RelatedItemManager")
], RelatedItemManagerImpl);
return RelatedItemManagerImpl;
}(SharePointQueryable));
/**
* Describes a collection of webs
*
*/
var Webs = /** @class */ (function (_super) {
__extends(Webs, _super);
function Webs() {
return _super !== null && _super.apply(this, arguments) || this;
}
Webs_1 = Webs;
/**
* Adds a new web to the collection
*
* @param title The new web's title
* @param url The new web's relative url
* @param description The new web's description
* @param template The new web's template internal name (default = STS)
* @param language The locale id that specifies the new web's language (default = 1033 [English, US])
* @param inheritPermissions When true, permissions will be inherited from the new web's parent (default = true)
*/
Webs.prototype.add = function (title, url, description, template, language, inheritPermissions) {
if (description === void 0) { description = ""; }
if (template === void 0) { template = "STS"; }
if (language === void 0) { language = 1033; }
if (inheritPermissions === void 0) { inheritPermissions = true; }
var props = {
Description: description,
Language: language,
Title: title,
Url: url,
UseSamePermissionsAsParentSite: inheritPermissions,
WebTemplate: template,
};
var postBody = common.jsS({
"parameters": common.extend({
"__metadata": { "type": "SP.WebCreationInformation" },
}, props),
});
return this.clone(Webs_1, "add").postCore({ body: postBody }).then(function (data) {
return {
data: data,
web: new Web(odataUrlFrom(data).replace(/_api\/web\/?/i, "")),
};
});
};
var Webs_1;
Webs = Webs_1 = __decorate([
defaultPath("webs")
], Webs);
return Webs;
}(SharePointQueryableCollection));
/**
* Describes a collection of web infos
*
*/
var WebInfos = /** @class */ (function (_super) {
__extends(WebInfos, _super);
function WebInfos() {
return _super !== null && _super.apply(this, arguments) || this;
}
WebInfos = __decorate([
defaultPath("webinfos")
], WebInfos);
return WebInfos;
}(SharePointQueryableCollection));
/**
* Describes a web
*
*/
var Web = /** @class */ (function (_super) {
__extends(Web, _super);
function Web() {
return _super !== null && _super.apply(this, arguments) || this;
}
Web_1 = Web;
/**
* Creates a new web instance from the given url by indexing the location of the /_api/
* segment. If this is not found the method creates a new web with the entire string as
* supplied.
*
* @param url
*/
Web.fromUrl = function (url, path) {
return new Web_1(extractWebUrl(url), path);
};
Object.defineProperty(Web.prototype, "webs", {
/**
* Gets this web's subwebs
*
*/
get: function () {
return new Webs(this);
},
enumerable: true,
configurable: true
});
/**
* Gets this web's parent web and data
*
*/
Web.prototype.getParentWeb = function () {
var _this = this;
return this.select("ParentWeb/Id").expand("ParentWeb").get()
.then(function (_a) {
var ParentWeb = _a.ParentWeb;
return ParentWeb ? new Site(_this.parentUrl).openWebById(ParentWeb.Id) : null;
});
};
/**
* Returns a collection of objects that contain metadata about subsites of the current site in which the current user is a member.
*
* @param nWebTemplateFilter Specifies the site definition (default = -1)
* @param nConfigurationFilter A 16-bit integer that specifies the identifier of a configuration (default = -1)
*/
Web.prototype.getSubwebsFilteredForCurrentUser = function (nWebTemplateFilter, nConfigurationFilter) {
if (nWebTemplateFilter === void 0) { nWebTemplateFilter = -1; }
if (nConfigurationFilter === void 0) { nConfigurationFilter = -1; }
return this.clone(Webs, "getSubwebsFilteredForCurrentUser(nWebTemplateFilter=" + nWebTemplateFilter + ",nConfigurationFilter=" + nConfigurationFilter + ")");
};
Object.defineProperty(Web.prototype, "allProperties", {
/**
* Allows access to the web's all properties collection
*/
get: function () {
return this.clone(SharePointQueryableCollection, "allproperties");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "webinfos", {
/**
* Gets a collection of WebInfos for this web's subwebs
*
*/
get: function () {
return new WebInfos(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "contentTypes", {
/**
* Gets the content types available in this web
*
*/
get: function () {
return new ContentTypes(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "lists", {
/**
* Gets the lists in this web
*
*/
get: function () {
return new Lists(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "fields", {
/**
* Gets the fields in this web
*
*/
get: function () {
return new Fields(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "features", {
/**
* Gets the active features for this web
*
*/
get: function () {
return new Features(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "availablefields", {
/**
* Gets the available fields in this web
*
*/
get: function () {
return new Fields(this, "availablefields");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "navigation", {
/**
* Gets the navigation options in this web
*
*/
get: function () {
return new Navigation(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "siteUsers", {
/**
* Gets the site users
*
*/
get: function () {
return new SiteUsers(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "siteGroups", {
/**
* Gets the site groups
*
*/
get: function () {
return new SiteGroups(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "siteUserInfoList", {
/**
* Gets site user info list
*
*/
get: function () {
return new List(this, "siteuserinfolist");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "regionalSettings", {
/**
* Gets regional settings
*
*/
get: function () {
return new RegionalSettings(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "currentUser", {
/**
* Gets the current user
*/
get: function () {
return new CurrentUser(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "folders", {
/**
* Gets the top-level folders in this web
*
*/
get: function () {
return new Folders(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "userCustomActions", {
/**
* Gets all user custom actions for this web
*
*/
get: function () {
return new UserCustomActions(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "roleDefinitions", {
/**
* Gets the collection of RoleDefinition resources
*
*/
get: function () {
return new RoleDefinitions(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "relatedItems", {
/**
* Provides an interface to manage related items
*
*/
get: function () {
return RelatedItemManagerImpl.FromUrl(this.toUrl());
},
enumerable: true,
configurable: true
});
/**
* Creates a new batch for requests within the context of this web
*
*/
Web.prototype.createBatch = function () {
return new SPBatch(this.parentUrl);
};
Object.defineProperty(Web.prototype, "rootFolder", {
/**
* Gets the root folder of this web
*
*/
get: function () {
return new Folder(this, "rootFolder");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "associatedOwnerGroup", {
/**
* Gets the associated owner group for this web
*
*/
get: function () {
return new SiteGroup(this, "associatedownergroup");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "associatedMemberGroup", {
/**
* Gets the associated member group for this web
*
*/
get: function () {
return new SiteGroup(this, "associatedmembergroup");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "associatedVisitorGroup", {
/**
* Gets the associated visitor group for this web
*
*/
get: function () {
return new SiteGroup(this, "associatedvisitorgroup");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "defaultDocumentLibrary", {
/**
* Gets the default document library for this web
*
*/
get: function () {
return new List(this, "DefaultDocumentLibrary");
},
enumerable: true,
configurable: true
});
/**
* Gets a folder by server relative url
*
* @param folderRelativeUrl The server relative path to the folder (including /sites/ if applicable)
*/
Web.prototype.getFolderByServerRelativeUrl = function (folderRelativeUrl) {
return new Folder(this, "getFolderByServerRelativeUrl('" + folderRelativeUrl + "')");
};
/**
* Gets a folder by server relative relative path if your folder name contains # and % characters
* you need to first encode the file name using encodeURIComponent() and then pass the url
* let url = "/sites/test/Shared Documents/" + encodeURIComponent("%123");
* This works only in SharePoint online.
*
* @param folderRelativeUrl The server relative path to the folder (including /sites/ if applicable)
*/
Web.prototype.getFolderByServerRelativePath = function (folderRelativeUrl) {
return new Folder(this, "getFolderByServerRelativePath(decodedUrl='" + folderRelativeUrl + "')");
};
/**
* Gets a file by server relative url
*
* @param fileRelativeUrl The server relative path to the file (including /sites/ if applicable)
*/
Web.prototype.getFileByServerRelativeUrl = function (fileRelativeUrl) {
return new File(this, "getFileByServerRelativeUrl('" + fileRelativeUrl + "')");
};
/**
* Gets a file by server relative url if your file name contains # and % characters
* you need to first encode the file name using encodeURIComponent() and then pass the url
* let url = "/sites/test/Shared Documents/" + encodeURIComponent("%123.docx");
*
* @param fileRelativeUrl The server relative path to the file (including /sites/ if applicable)
*/
Web.prototype.getFileByServerRelativePath = function (fileRelativeUrl) {
return new File(this, "getFileByServerRelativePath(decodedUrl='" + fileRelativeUrl + "')");
};
/**
* Gets a list by server relative url (list's root folder)
*
* @param listRelativeUrl The server relative path to the list's root folder (including /sites/ if applicable)
*/
Web.prototype.getList = function (listRelativeUrl) {
return new List(this, "getList('" + listRelativeUrl + "')");
};
/**
* Updates this web instance with the supplied properties
*
* @param properties A plain object hash of values to update for the web
*/
Web.prototype.update = function (properties) {
var _this = this;
var postBody = common.jsS(common.extend({
"__metadata": { "type": "SP.Web" },
}, properties));
return this.postCore({
body: postBody,
headers: {
"X-HTTP-Method": "MERGE",
},
}).then(function (data) {
return {
data: data,
web: _this,
};
});
};
/**
* Deletes this web
*
*/
Web.prototype.delete = function () {
return _super.prototype.deleteCore.call(this);
};
/**
* Applies the theme specified by the contents of each of the files specified in the arguments to the site
*
* @param colorPaletteUrl The server-relative URL of the color palette file
* @param fontSchemeUrl The server-relative URL of the font scheme
* @param backgroundImageUrl The server-relative URL of the background image
* @param shareGenerated When true, the generated theme files are stored in the root site. When false, they are stored in this web
*/
Web.prototype.applyTheme = function (colorPaletteUrl, fontSchemeUrl, backgroundImageUrl, shareGenerated) {
var postBody = common.jsS({
backgroundImageUrl: backgroundImageUrl,
colorPaletteUrl: colorPaletteUrl,
fontSchemeUrl: fontSchemeUrl,
shareGenerated: shareGenerated,
});
return this.clone(Web_1, "applytheme").postCore({ body: postBody });
};
/**
* Applies the specified site definition or site template to the Web site that has no template applied to it
*
* @param template Name of the site definition or the name of the site template
*/
Web.prototype.applyWebTemplate = function (template) {
var q = this.clone(Web_1, "applywebtemplate");
q.concat("(@t)");
q.query.set("@t", template);
return q.postCore();
};
/**
* Checks whether the specified login name belongs to a valid user in the web. If the user doesn't exist, adds the user to the web.
*
* @param loginName The login name of the user (ex: i:0#.f|membership|user@domain.onmicrosoft.com)
*/
Web.prototype.ensureUser = function (loginName) {
var postBody = common.jsS({
logonName: loginName,
});
return this.clone(Web_1, "ensureuser").postCore({ body: postBody }).then(function (data) {
return {
data: data,
user: new SiteUser(odataUrlFrom(data)),
};
});
};
/**
* Returns a collection of site templates available for the site
*
* @param language The locale id of the site templates to retrieve (default = 1033 [English, US])
* @param includeCrossLanguage When true, includes language-neutral site templates; otherwise false (default = true)
*/
Web.prototype.availableWebTemplates = function (language, includeCrossLanugage) {
if (language === void 0) { language = 1033; }
if (includeCrossLanugage === void 0) { includeCrossLanugage = true; }
return new SharePointQueryableCollection(this, "getavailablewebtemplates(lcid=" + language + ", doincludecrosslanguage=" + includeCrossLanugage + ")");
};
/**
* Returns the list gallery on the site
*
* @param type The gallery type - WebTemplateCatalog = 111, WebPartCatalog = 113 ListTemplateCatalog = 114,
* MasterPageCatalog = 116, SolutionCatalog = 121, ThemeCatalog = 123, DesignCatalog = 124, AppDataCatalog = 125
*/
Web.prototype.getCatalog = function (type) {
return this.clone(Web_1, "getcatalog(" + type + ")").select("Id").get().then(function (data) {
return new List(odataUrlFrom(data));
});
};
/**
* Returns the collection of changes from the change log that have occurred within the list, based on the specified query
*
* @param query The change query
*/
Web.prototype.getChanges = function (query) {
var postBody = common.jsS({ "query": common.extend({ "__metadata": { "type": "SP.ChangeQuery" } }, query) });
return this.clone(Web_1, "getchanges").postCore({ body: postBody });
};
Object.defineProperty(Web.prototype, "customListTemplate", {
/**
* Gets the custom list templates for the site
*
*/
get: function () {
return new SharePointQueryableCollection(this, "getcustomlisttemplates");
},
enumerable: true,
configurable: true
});
/**
* Returns the user corresponding to the specified member identifier for the current site
*
* @param id The id of the user
*/
Web.prototype.getUserById = function (id) {
return new SiteUser(this, "getUserById(" + id + ")");
};
/**
* Returns the name of the image file for the icon that is used to represent the specified file
*
* @param filename The file name. If this parameter is empty, the server returns an empty string
* @param size The size of the icon: 16x16 pixels = 0, 32x32 pixels = 1 (default = 0)
* @param progId The ProgID of the application that was used to create the file, in the form OLEServerName.ObjectName
*/
Web.prototype.mapToIcon = function (filename, size, progId) {
if (size === void 0) { size = 0; }
if (progId === void 0) { progId = ""; }
return this.clone(Web_1, "maptoicon(filename='" + filename + "', progid='" + progId + "', size=" + size + ")").get();
};
/**
* Returns the tenant property corresponding to the specified key in the app catalog site
*
* @param key Id of storage entity to be set
*/
Web.prototype.getStorageEntity = function (key) {
return this.clone(Web_1, "getStorageEntity('" + key + "')").get();
};
/**
* This will set the storage entity identified by the given key (MUST be called in the context of the app catalog)
*
* @param key Id of storage entity to be set
* @param value Value of storage entity to be set
* @param description Description of storage entity to be set
* @param comments Comments of storage entity to be set
*/
Web.prototype.setStorageEntity = function (key, value, description, comments) {
if (description === void 0) { description = ""; }
if (comments === void 0) { comments = ""; }
return this.clone(Web_1, "setStorageEntity").postCore({
body: common.jsS({
comments: comments,
description: description,
key: key,
value: value,
}),
});
};
/**
* This will remove the storage entity identified by the given key
*
* @param key Id of storage entity to be removed
*/
Web.prototype.removeStorageEntity = function (key) {
return this.clone(Web_1, "removeStorageEntity('" + key + "')").postCore();
};
/**
* Gets the app catalog for this web
*
* @param url Optional url or web containing the app catalog (default: current web)
*/
Web.prototype.getAppCatalog = function (url) {
return new AppCatalog(url || this);
};
/**
* Gets the collection of available client side web parts for this web instance
*/
Web.prototype.getClientSideWebParts = function () {
return this.clone(SharePointQueryableCollection, "GetClientSideWebParts").get();
};
/**
* Creates a new client side page
*
* @param pageName Name of the new page
* @param title Display title of the new page
* @param libraryTitle Title of the library in which to create the new page. Default: "Site Pages"
*/
Web.prototype.addClientSidePage = function (pageName, title, libraryTitle) {
if (title === void 0) { title = pageName.replace(/\.[^/.]+$/, ""); }
if (libraryTitle === void 0) { libraryTitle = "Site Pages"; }
return ClientSidePage.create(this.lists.getByTitle(libraryTitle), pageName, title);
};
/**
* Creates a new client side page using the library path
*
* @param pageName Name of the new page
* @param listRelativePath The server relative path to the list's root folder (including /sites/ if applicable)
* @param title Display title of the new page
*/
Web.prototype.addClientSidePageByPath = function (pageName, listRelativePath, title) {
if (title === void 0) { title = pageName.replace(/\.[^/.]+$/, ""); }
return ClientSidePage.create(this.getList(listRelativePath), pageName, title);
};
/**
* Creates the default associated groups (Members, Owners, Visitors) and gives them the default permissions on the site.
* The target site must have unique permissions and no associated members / owners / visitors groups
*
* @param siteOwner The user login name to be added to the site Owners group. Default is the current user
* @param siteOwner2 The second user login name to be added to the site Owners group. Default is empty
* @param groupNameSeed The base group name. E.g. 'TestSite' would produce 'TestSite Members' etc.
*/
Web.prototype.createDefaultAssociatedGroups = function (siteOwner, siteOwner2, groupNameSeed) {
var q = this.clone(Web_1, "createDefaultAssociatedGroups(userLogin=@u,userLogin2=@v,groupNameSeed=@s)");
q.query.set("@u", "'" + encodeURIComponent(siteOwner || "") + "'");
q.query.set("@v", "'" + encodeURIComponent(siteOwner2 || "") + "'");
q.query.set("@s", "'" + encodeURIComponent(groupNameSeed || "") + "'");
return q.postCore();
};
/**
* Gets hub site data for the current web.
*
* @param forceRefresh Default value is false. When false, the data is returned from the server's cache.
* When true, the cache is refreshed with the latest updates and then returned.
* Use this if you just made changes and need to see those changes right away.
*/
Web.prototype.hubSiteData = function (forceRefresh) {
if (forceRefresh === void 0) { forceRefresh = false; }
return this.clone(Web_1, "hubSiteData(" + forceRefresh + ")").get();
};
/**
* Applies theme updates from the parent hub site collection.
*/
Web.prototype.syncHubSiteTheme = function () {
return this.clone(Web_1, "syncHubSiteTheme").postCore();
};
var Web_1;
Web = Web_1 = __decorate([
defaultPath("_api/web")
], Web);
return Web;
}(SharePointQueryableShareableWeb));
/**
* Describes a site collection
*
*/
var Site = /** @class */ (function (_super) {
__extends(Site, _super);
function Site() {
return _super !== null && _super.apply(this, arguments) || this;
}
Site_1 = Site;
Object.defineProperty(Site.prototype, "rootWeb", {
/**
* Gets the root web of the site collection
*
*/
get: function () {
return new Web(this, "rootweb");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Site.prototype, "features", {
/**
* Gets the active features for this site collection
*
*/
get: function () {
return new Features(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Site.prototype, "userCustomActions", {
/**
* Gets all custom actions for this site collection
*
*/
get: function () {
return new UserCustomActions(this);
},
enumerable: true,
configurable: true
});
/**
* Gets a Web instance representing the root web of the site collection
* correctly setup for chaining within the library
*/
Site.prototype.getRootWeb = function () {
return this.rootWeb.select("Url").get().then(function (web) { return new Web(web.Url); });
};
/**
* Gets the context information for this site collection
*/
Site.prototype.getContextInfo = function () {
var q = new Site_1(this.parentUrl, "_api/contextinfo");
return q.postCore().then(function (data) {
if (common.hOP(data, "GetContextWebInformation")) {
var info = data.GetContextWebInformation;
info.SupportedSchemaVersions = info.SupportedSchemaVersions.results;
return info;
}
else {
return data;
}
});
};
/**
* Gets the document libraries on a site. Static method. (SharePoint Online only)
*
* @param absoluteWebUrl The absolute url of the web whose document libraries should be returned
*/
Site.prototype.getDocumentLibraries = function (absoluteWebUrl) {
var q = new SharePointQueryable("", "_api/sp.web.getdocumentlibraries(@v)");
q.query.set("@v", "'" + absoluteWebUrl + "'");
return q.get().then(function (data) {
if (common.hOP(data, "GetDocumentLibraries")) {
return data.GetDocumentLibraries;
}
else {
return data;
}
});
};
/**
* Gets the site url from a page url
*
* @param absolutePageUrl The absolute url of the page
*/
Site.prototype.getWebUrlFromPageUrl = function (absolutePageUrl) {
var q = new SharePointQueryable("", "_api/sp.web.getweburlfrompageurl(@v)");
q.query.set("@v", "'" + absolutePageUrl + "'");
return q.get().then(function (data) {
if (common.hOP(data, "GetWebUrlFromPageUrl")) {
return data.GetWebUrlFromPageUrl;
}
else {
return data;
}
});
};
/**
* Creates a new batch for requests within the context of this site collection
*
*/
Site.prototype.createBatch = function () {
return new SPBatch(this.parentUrl);
};
/**
* Opens a web by id (using POST)
*
* @param webId The GUID id of the web to open
*/
Site.prototype.openWebById = function (webId) {
return this.clone(Site_1, "openWebById('" + webId + "')").postCore().then(function (d) { return ({
data: d,
web: Web.fromUrl(d["odata.id"] || d.__metadata.uri),
}); });
};
/**
* Associates a site collection to a hub site.
*
* @param siteId Id of the hub site collection you want to join.
* If you want to disassociate the site collection from hub site, then
* pass the siteId as 00000000-0000-0000-0000-000000000000
*/
Site.prototype.joinHubSite = function (siteId) {
return this.clone(Site_1, "joinHubSite('" + siteId + "')").postCore();
};
/**
* Registers the current site collection as hub site collection
*/
Site.prototype.registerHubSite = function () {
return this.clone(Site_1, "registerHubSite").postCore();
};
/**
* Unregisters the current site collection as hub site collection.
*/
Site.prototype.unRegisterHubSite = function () {
return this.clone(Site_1, "unRegisterHubSite").postCore();
};
/**
* Creates a Modern communication site.
*
* @param title The title of the site to create
* @param lcid The language to use for the site. If not specified will default to 1033 (English).
* @param shareByEmailEnabled If set to true, it will enable sharing files via Email. By default it is set to false
* @param url The fully qualified URL (e.g. https://yourtenant.sharepoint.com/sites/mysitecollection) of the site.
* @param description The description of the communication site.
* @param classification The Site classification to use. For instance 'Contoso Classified'. See https://www.youtube.com/watch?v=E-8Z2ggHcS0 for more information
* @param siteDesignId The Guid of the site design to be used.
* You can use the below default OOTB GUIDs:
* Topic: 00000000-0000-0000-0000-000000000000
* Showcase: 6142d2a0-63a5-4ba0-aede-d9fefca2c767
* Blank: f6cc5403-0d63-442e-96c0-285923709ffc
*/
Site.prototype.createCommunicationSite = function (title, lcid, shareByEmailEnabled, url, description, classification, siteDesignId) {
var _this = this;
if (lcid === void 0) { lcid = 1033; }
if (shareByEmailEnabled === void 0) { shareByEmailEnabled = false; }
if (description === void 0) { description = ""; }
if (classification === void 0) { classification = ""; }
if (siteDesignId === void 0) { siteDesignId = "00000000-0000-0000-0000-000000000000"; }
var props = {
Classification: classification,
Description: description,
Lcid: lcid,
ShareByEmailEnabled: shareByEmailEnabled,
SiteDesignId: siteDesignId,
Title: title,
Url: url,
WebTemplate: "SITEPAGEPUBLISHING#0",
WebTemplateExtensionId: "00000000-0000-0000-0000-000000000000",
};
var postBody = common.jsS({
"request": common.extend({
"__metadata": { "type": "Microsoft.SharePoint.Portal.SPSiteCreationRequest" },
}, props),
});
return this.getRootWeb().then(function (d) { return __awaiter(_this, void 0, void 0, function () {
var client, methodUrl;
return __generator(this, function (_a) {
client = new SPHttpClient();
methodUrl = d.parentUrl + "/_api/SPSiteManager/Create";
return [2 /*return*/, client.post(methodUrl, {
body: postBody,
headers: {
"Accept": "application/json;odata=verbose",
"Content-Type": "application/json;odata=verbose;charset=utf-8",
},
}).then(function (r) { return r.json(); })];
});
}); });
};
/**
* Creates a Modern team site backed by Office 365 group. For use in SP Online only. This will not work with App-only tokens
*
* @param displayName The title or display name of the Modern team site to be created
* @param alias Alias of the underlying Office 365 Group
* @param isPublic Defines whether the Office 365 Group will be public (default), or private.
* @param lcid The language to use for the site. If not specified will default to English (1033).
* @param description The description of the site to be created.
* @param classification The Site classification to use. For instance 'Contoso Classified'. See https://www.youtube.com/watch?v=E-8Z2ggHcS0 for more information
* @param owners The Owners of the site to be created
*/
Site.prototype.createModernTeamSite = function (displayName, alias, isPublic, lcid, description, classification, owners) {
var _this = this;
if (isPublic === void 0) { isPublic = true; }
if (lcid === void 0) { lcid = 1033; }
if (description === void 0) { description = ""; }
if (classification === void 0) { classification = ""; }
var postBody = common.jsS({
alias: alias,
displayName: displayName,
isPublic: isPublic,
optionalParams: {
Classification: classification,
CreationOptions: {
"results": ["SPSiteLanguage:" + lcid],
},
Description: description,
Owners: {
"results": owners ? owners : [],
},
},
});
return this.getRootWeb().then(function (d) { return __awaiter(_this, void 0, void 0, function () {
var client, methodUrl;
return __generator(this, function (_a) {
client = new SPHttpClient();
methodUrl = d.parentUrl + "/_api/GroupSiteManager/CreateGroupEx";
return [2 /*return*/, client.post(methodUrl, {
body: postBody,
headers: {
"Accept": "application/json;odata=verbose",
"Content-Type": "application/json;odata=verbose;charset=utf-8",
},
}).then(function (r) { return r.json(); })];
});
}); });
};
var Site_1;
Site = Site_1 = __decorate([
defaultPath("_api/site")
], Site);
return Site;
}(SharePointQueryableInstance));
var UserProfileQuery = /** @class */ (function (_super) {
__extends(UserProfileQuery, _super);
/**
* Creates a new instance of the UserProfileQuery class
*
* @param baseUrl The url or SharePointQueryable which forms the parent of this user profile query
*/
function UserProfileQuery(baseUrl, path) {
if (path === void 0) { path = "_api/sp.userprofiles.peoplemanager"; }
var _this = _super.call(this, baseUrl, path) || this;
_this.clientPeoplePickerQuery = (new ClientPeoplePickerQuery(baseUrl)).configureFrom(_this);
_this.profileLoader = (new ProfileLoader(baseUrl)).configureFrom(_this);
return _this;
}
Object.defineProperty(UserProfileQuery.prototype, "editProfileLink", {
/**
* The url of the edit profile page for the current user
*/
get: function () {
return this.clone(UserProfileQuery, "EditProfileLink").get();
},
enumerable: true,
configurable: true
});
Object.defineProperty(UserProfileQuery.prototype, "isMyPeopleListPublic", {
/**
* A boolean value that indicates whether the current user's "People I'm Following" list is public
*/
get: function () {
return this.clone(UserProfileQuery, "IsMyPeopleListPublic").get();
},
enumerable: true,
configurable: true
});
/**
* A boolean value that indicates whether the current user is being followed by the specified user
*
* @param loginName The account name of the user
*/
UserProfileQuery.prototype.amIFollowedBy = function (loginName) {
var q = this.clone(UserProfileQuery, "amifollowedby(@v)");
q.query.set("@v", "'" + encodeURIComponent(loginName) + "'");
return q.get();
};
/**
* A boolean value that indicates whether the current user is following the specified user
*
* @param loginName The account name of the user
*/
UserProfileQuery.prototype.amIFollowing = function (loginName) {
var q = this.clone(UserProfileQuery, "amifollowing(@v)");
q.query.set("@v", "'" + encodeURIComponent(loginName) + "'");
return q.get();
};
/**
* Gets tags that the current user is following
*
* @param maxCount The maximum number of tags to retrieve (default is 20)
*/
UserProfileQuery.prototype.getFollowedTags = function (maxCount) {
if (maxCount === void 0) { maxCount = 20; }
return this.clone(UserProfileQuery, "getfollowedtags(" + maxCount + ")").get();
};
/**
* Gets the people who are following the specified user
*
* @param loginName The account name of the user
*/
UserProfileQuery.prototype.getFollowersFor = function (loginName) {
var q = this.clone(UserProfileQuery, "getfollowersfor(@v)");
q.query.set("@v", "'" + encodeURIComponent(loginName) + "'");
return q.get();
};
Object.defineProperty(UserProfileQuery.prototype, "myFollowers", {
/**
* Gets the people who are following the current user
*
*/
get: function () {
return new SharePointQueryableCollection(this, "getmyfollowers");
},
enumerable: true,
configurable: true
});
Object.defineProperty(UserProfileQuery.prototype, "myProperties", {
/**
* Gets user properties for the current user
*
*/
get: function () {
return new UserProfileQuery(this, "getmyproperties");
},
enumerable: true,
configurable: true
});
/**
* Gets the people who the specified user is following
*
* @param loginName The account name of the user.
*/
UserProfileQuery.prototype.getPeopleFollowedBy = function (loginName) {
var q = this.clone(UserProfileQuery, "getpeoplefollowedby(@v)");
q.query.set("@v", "'" + encodeURIComponent(loginName) + "'");
return q.get();
};
/**
* Gets user properties for the specified user.
*
* @param loginName The account name of the user.
*/
UserProfileQuery.prototype.getPropertiesFor = function (loginName) {
var q = this.clone(UserProfileQuery, "getpropertiesfor(@v)");
q.query.set("@v", "'" + encodeURIComponent(loginName) + "'");
return q.get();
};
Object.defineProperty(UserProfileQuery.prototype, "trendingTags", {
/**
* Gets the 20 most popular hash tags over the past week, sorted so that the most popular tag appears first
*
*/
get: function () {
var q = this.clone(UserProfileQuery, null);
q.concat(".gettrendingtags");
return q.get();
},
enumerable: true,
configurable: true
});
/**
* Gets the specified user profile property for the specified user
*
* @param loginName The account name of the user
* @param propertyName The case-sensitive name of the property to get
*/
UserProfileQuery.prototype.getUserProfilePropertyFor = function (loginName, propertyName) {
var q = this.clone(UserProfileQuery, "getuserprofilepropertyfor(accountname=@v, propertyname='" + propertyName + "')");
q.query.set("@v", "'" + encodeURIComponent(loginName) + "'");
return q.get();
};
/**
* Removes the specified user from the user's list of suggested people to follow
*
* @param loginName The account name of the user
*/
UserProfileQuery.prototype.hideSuggestion = function (loginName) {
var q = this.clone(UserProfileQuery, "hidesuggestion(@v)");
q.query.set("@v", "'" + encodeURIComponent(loginName) + "'");
return q.postCore();
};
/**
* A boolean values that indicates whether the first user is following the second user
*
* @param follower The account name of the user who might be following the followee
* @param followee The account name of the user who might be followed by the follower
*/
UserProfileQuery.prototype.isFollowing = function (follower, followee) {
var q = this.clone(UserProfileQuery, null);
q.concat(".isfollowing(possiblefolloweraccountname=@v, possiblefolloweeaccountname=@y)");
q.query.set("@v", "'" + encodeURIComponent(follower) + "'");
q.query.set("@y", "'" + encodeURIComponent(followee) + "'");
return q.get();
};
/**
* Uploads and sets the user profile picture (Users can upload a picture to their own profile only). Not supported for batching.
*
* @param profilePicSource Blob data representing the user's picture in BMP, JPEG, or PNG format of up to 4.76MB
*/
UserProfileQuery.prototype.setMyProfilePic = function (profilePicSource) {
var _this = this;
return new Promise(function (resolve, reject) {
var buffer = null;
var reader = new FileReader();
reader.onload = function (e) { return buffer = e.target.result; };
reader.readAsArrayBuffer(profilePicSource);
var request = new UserProfileQuery(_this, "setmyprofilepicture");
request.postCore({
body: String.fromCharCode.apply(null, new Uint16Array(buffer)),
}).then(function (_) { return resolve(); }).catch(function (e) { return reject(e); });
});
};
/**
* Sets single value User Profile property
*
* @param accountName The account name of the user
* @param propertyName Property name
* @param propertyValue Property value
*/
UserProfileQuery.prototype.setSingleValueProfileProperty = function (accountName, propertyName, propertyValue) {
var postBody = common.jsS({
accountName: accountName,
propertyName: propertyName,
propertyValue: propertyValue,
});
return this.clone(UserProfileQuery, "SetSingleValueProfileProperty")
.postCore({ body: postBody });
};
/**
* Sets multi valued User Profile property
*
* @param accountName The account name of the user
* @param propertyName Property name
* @param propertyValues Property values
*/
UserProfileQuery.prototype.setMultiValuedProfileProperty = function (accountName, propertyName, propertyValues) {
var postBody = common.jsS({
accountName: accountName,
propertyName: propertyName,
propertyValues: propertyValues,
});
return this.clone(UserProfileQuery, "SetMultiValuedProfileProperty")
.postCore({ body: postBody });
};
/**
* Provisions one or more users' personal sites. (My Site administrator on SharePoint Online only)
*
* @param emails The email addresses of the users to provision sites for
*/
UserProfileQuery.prototype.createPersonalSiteEnqueueBulk = function () {
var emails = [];
for (var _i = 0; _i < arguments.length; _i++) {
emails[_i] = arguments[_i];
}
return this.profileLoader.createPersonalSiteEnqueueBulk(emails);
};
Object.defineProperty(UserProfileQuery.prototype, "ownerUserProfile", {
/**
* Gets the user profile of the site owner
*
*/
get: function () {
return this.profileLoader.ownerUserProfile;
},
enumerable: true,
configurable: true
});
Object.defineProperty(UserProfileQuery.prototype, "userProfile", {
/**
* Gets the user profile for the current user
*/
get: function () {
return this.profileLoader.userProfile;
},
enumerable: true,
configurable: true
});
/**
* Enqueues creating a personal site for this user, which can be used to share documents, web pages, and other files
*
* @param interactiveRequest true if interactively (web) initiated request, or false (default) if non-interactively (client) initiated request
*/
UserProfileQuery.prototype.createPersonalSite = function (interactiveRequest) {
if (interactiveRequest === void 0) { interactiveRequest = false; }
return this.profileLoader.createPersonalSite(interactiveRequest);
};
/**
* Sets the privacy settings for this profile
*
* @param share true to make all social data public; false to make all social data private
*/
UserProfileQuery.prototype.shareAllSocialData = function (share) {
return this.profileLoader.shareAllSocialData(share);
};
/**
* Resolves user or group using specified query parameters
*
* @param queryParams The query parameters used to perform resolve
*/
UserProfileQuery.prototype.clientPeoplePickerResolveUser = function (queryParams) {
return this.clientPeoplePickerQuery.clientPeoplePickerResolveUser(queryParams);
};
/**
* Searches for users or groups using specified query parameters
*
* @param queryParams The query parameters used to perform search
*/
UserProfileQuery.prototype.clientPeoplePickerSearchUser = function (queryParams) {
return this.clientPeoplePickerQuery.clientPeoplePickerSearchUser(queryParams);
};
return UserProfileQuery;
}(SharePointQueryableInstance));
var ProfileLoader = /** @class */ (function (_super) {
__extends(ProfileLoader, _super);
function ProfileLoader() {
return _super !== null && _super.apply(this, arguments) || this;
}
ProfileLoader_1 = ProfileLoader;
/**
* Provisions one or more users' personal sites. (My Site administrator on SharePoint Online only) Doesn't support batching
*
* @param emails The email addresses of the users to provision sites for
*/
ProfileLoader.prototype.createPersonalSiteEnqueueBulk = function (emails) {
return this.clone(ProfileLoader_1, "createpersonalsiteenqueuebulk", false).postCore({
body: common.jsS({ "emailIDs": emails }),
});
};
Object.defineProperty(ProfileLoader.prototype, "ownerUserProfile", {
/**
* Gets the user profile of the site owner.
*
*/
get: function () {
var q = this.getParent(ProfileLoader_1, this.parentUrl, "_api/sp.userprofiles.profileloader.getowneruserprofile");
if (this.hasBatch) {
q = q.inBatch(this.batch);
}
return q.postCore();
},
enumerable: true,
configurable: true
});
Object.defineProperty(ProfileLoader.prototype, "userProfile", {
/**
* Gets the user profile of the current user.
*
*/
get: function () {
return this.clone(ProfileLoader_1, "getuserprofile").postCore();
},
enumerable: true,
configurable: true
});
/**
* Enqueues creating a personal site for this user, which can be used to share documents, web pages, and other files.
*
* @param interactiveRequest true if interactively (web) initiated request, or false (default) if non-interactively (client) initiated request
*/
ProfileLoader.prototype.createPersonalSite = function (interactiveRequest) {
if (interactiveRequest === void 0) { interactiveRequest = false; }
return this.clone(ProfileLoader_1, "getuserprofile/createpersonalsiteenque(" + interactiveRequest + ")").postCore();
};
/**
* Sets the privacy settings for this profile
*
* @param share true to make all social data public; false to make all social data private.
*/
ProfileLoader.prototype.shareAllSocialData = function (share) {
return this.clone(ProfileLoader_1, "getuserprofile/shareallsocialdata(" + share + ")").postCore();
};
var ProfileLoader_1;
ProfileLoader = ProfileLoader_1 = __decorate([
defaultPath("_api/sp.userprofiles.profileloader.getprofileloader")
], ProfileLoader);
return ProfileLoader;
}(SharePointQueryable));
var ClientPeoplePickerQuery = /** @class */ (function (_super) {
__extends(ClientPeoplePickerQuery, _super);
function ClientPeoplePickerQuery() {
return _super !== null && _super.apply(this, arguments) || this;
}
ClientPeoplePickerQuery_1 = ClientPeoplePickerQuery;
/**
* Resolves user or group using specified query parameters
*
* @param queryParams The query parameters used to perform resolve
*/
ClientPeoplePickerQuery.prototype.clientPeoplePickerResolveUser = function (queryParams) {
var q = this.clone(ClientPeoplePickerQuery_1, null);
q.concat(".clientpeoplepickerresolveuser");
return q.postCore({
body: this.createClientPeoplePickerQueryParametersRequestBody(queryParams),
})
.then(function (res) {
if (typeof res === "object") {
return res.ClientPeoplePickerResolveUser;
}
return res;
})
.then(JSON.parse);
};
/**
* Searches for users or groups using specified query parameters
*
* @param queryParams The query parameters used to perform search
*/
ClientPeoplePickerQuery.prototype.clientPeoplePickerSearchUser = function (queryParams) {
var q = this.clone(ClientPeoplePickerQuery_1, null);
q.concat(".clientpeoplepickersearchuser");
return q.postCore({
body: this.createClientPeoplePickerQueryParametersRequestBody(queryParams),
})
.then(function (res) {
if (typeof res === "object") {
return res.ClientPeoplePickerSearchUser;
}
return res;
})
.then(JSON.parse);
};
/**
* Creates ClientPeoplePickerQueryParameters request body
*
* @param queryParams The query parameters to create request body
*/
ClientPeoplePickerQuery.prototype.createClientPeoplePickerQueryParametersRequestBody = function (queryParams) {
return common.jsS({
"queryParams": common.extend(metadata("SP.UI.ApplicationPages.ClientPeoplePickerQueryParameters"), queryParams),
});
};
var ClientPeoplePickerQuery_1;
ClientPeoplePickerQuery = ClientPeoplePickerQuery_1 = __decorate([
defaultPath("_api/sp.ui.applicationpages.clientpeoplepickerwebserviceinterface")
], ClientPeoplePickerQuery);
return ClientPeoplePickerQuery;
}(SharePointQueryable));
/**
* Exposes social following methods
*/
var SocialQuery = /** @class */ (function (_super) {
__extends(SocialQuery, _super);
function SocialQuery() {
return _super !== null && _super.apply(this, arguments) || this;
}
SocialQuery_1 = SocialQuery;
Object.defineProperty(SocialQuery.prototype, "my", {
get: function () {
return new MySocialQuery(this);
},
enumerable: true,
configurable: true
});
/**
* Gets a URI to a site that lists the current user's followed sites.
*/
SocialQuery.prototype.getFollowedSitesUri = function () {
return this.clone(SocialQuery_1, "FollowedSitesUri").get().then(function (r) {
return r.FollowedSitesUri || r;
});
};
/**
* Gets a URI to a site that lists the current user's followed documents.
*/
SocialQuery.prototype.getFollowedDocumentsUri = function () {
return this.clone(SocialQuery_1, "FollowedDocumentsUri").get().then(function (r) {
return r.FollowedDocumentsUri || r;
});
};
/**
* Makes the current user start following a user, document, site, or tag
*
* @param actorInfo The actor to start following
*/
SocialQuery.prototype.follow = function (actorInfo) {
return this.clone(SocialQuery_1, "follow").postCore({ body: this.createSocialActorInfoRequestBody(actorInfo) });
};
/**
* Indicates whether the current user is following a specified user, document, site, or tag
*
* @param actorInfo The actor to find the following status for
*/
SocialQuery.prototype.isFollowed = function (actorInfo) {
return this.clone(SocialQuery_1, "isfollowed").postCore({ body: this.createSocialActorInfoRequestBody(actorInfo) });
};
/**
* Makes the current user stop following a user, document, site, or tag
*
* @param actorInfo The actor to stop following
*/
SocialQuery.prototype.stopFollowing = function (actorInfo) {
return this.clone(SocialQuery_1, "stopfollowing").postCore({ body: this.createSocialActorInfoRequestBody(actorInfo) });
};
/**
* Creates SocialActorInfo request body
*
* @param actorInfo The actor to create request body
*/
SocialQuery.prototype.createSocialActorInfoRequestBody = function (actorInfo) {
return common.jsS({
"actor": Object.assign(metadata("SP.Social.SocialActorInfo"), {
Id: null,
}, actorInfo),
});
};
var SocialQuery_1;
SocialQuery = SocialQuery_1 = __decorate([
defaultPath("_api/social.following")
], SocialQuery);
return SocialQuery;
}(SharePointQueryableInstance));
var MySocialQuery = /** @class */ (function (_super) {
__extends(MySocialQuery, _super);
function MySocialQuery() {
return _super !== null && _super.apply(this, arguments) || this;
}
MySocialQuery_1 = MySocialQuery;
/**
* Gets users, documents, sites, and tags that the current user is following.
*
* @param types Bitwise set of SocialActorTypes to retrieve
*/
MySocialQuery.prototype.followed = function (types) {
return this.clone(MySocialQuery_1, "followed(types=" + types + ")").get().then(function (r) {
return common.hOP(r, "Followed") ? r.Followed.results : r;
});
};
/**
* Gets the count of users, documents, sites, and tags that the current user is following.
*
* @param types Bitwise set of SocialActorTypes to retrieve
*/
MySocialQuery.prototype.followedCount = function (types) {
return this.clone(MySocialQuery_1, "followedcount(types=" + types + ")").get().then(function (r) {
return r.FollowedCount || r;
});
};
/**
* Gets the users who are following the current user.
*/
MySocialQuery.prototype.followers = function () {
return this.clone(MySocialQuery_1, "followers").get().then(function (r) {
return common.hOP(r, "Followers") ? r.Followers.results : r;
});
};
/**
* Gets users who the current user might want to follow.
*/
MySocialQuery.prototype.suggestions = function () {
return this.clone(MySocialQuery_1, "suggestions").get().then(function (r) {
return common.hOP(r, "Suggestions") ? r.Suggestions.results : r;
});
};
var MySocialQuery_1;
MySocialQuery = MySocialQuery_1 = __decorate([
defaultPath("my")
], MySocialQuery);
return MySocialQuery;
}(SharePointQueryableInstance));
(function (SocialActorType) {
SocialActorType[SocialActorType["User"] = 0] = "User";
SocialActorType[SocialActorType["Document"] = 1] = "Document";
SocialActorType[SocialActorType["Site"] = 2] = "Site";
SocialActorType[SocialActorType["Tag"] = 3] = "Tag";
})(exports.SocialActorType || (exports.SocialActorType = {}));
(function (SocialActorTypes) {
SocialActorTypes[SocialActorTypes["None"] = 0] = "None";
SocialActorTypes[SocialActorTypes["User"] = 1] = "User";
SocialActorTypes[SocialActorTypes["Document"] = 2] = "Document";
SocialActorTypes[SocialActorTypes["Site"] = 4] = "Site";
SocialActorTypes[SocialActorTypes["Tag"] = 8] = "Tag";
/**
* The set excludes documents and sites that do not have feeds.
*/
SocialActorTypes[SocialActorTypes["ExcludeContentWithoutFeeds"] = 268435456] = "ExcludeContentWithoutFeeds";
/**
* The set includes group sites
*/
SocialActorTypes[SocialActorTypes["IncludeGroupsSites"] = 536870912] = "IncludeGroupsSites";
/**
* The set includes only items created within the last 24 hours
*/
SocialActorTypes[SocialActorTypes["WithinLast24Hours"] = 1073741824] = "WithinLast24Hours";
})(exports.SocialActorTypes || (exports.SocialActorTypes = {}));
(function (SocialFollowResult) {
SocialFollowResult[SocialFollowResult["Ok"] = 0] = "Ok";
SocialFollowResult[SocialFollowResult["AlreadyFollowing"] = 1] = "AlreadyFollowing";
SocialFollowResult[SocialFollowResult["LimitReached"] = 2] = "LimitReached";
SocialFollowResult[SocialFollowResult["InternalError"] = 3] = "InternalError";
})(exports.SocialFollowResult || (exports.SocialFollowResult = {}));
(function (SocialStatusCode) {
/**
* The operation completed successfully
*/
SocialStatusCode[SocialStatusCode["OK"] = 0] = "OK";
/**
* The request is invalid.
*/
SocialStatusCode[SocialStatusCode["InvalidRequest"] = 1] = "InvalidRequest";
/**
* The current user is not authorized to perform the operation.
*/
SocialStatusCode[SocialStatusCode["AccessDenied"] = 2] = "AccessDenied";
/**
* The target of the operation was not found.
*/
SocialStatusCode[SocialStatusCode["ItemNotFound"] = 3] = "ItemNotFound";
/**
* The operation is invalid for the target's current state.
*/
SocialStatusCode[SocialStatusCode["InvalidOperation"] = 4] = "InvalidOperation";
/**
* The operation completed without modifying the target.
*/
SocialStatusCode[SocialStatusCode["ItemNotModified"] = 5] = "ItemNotModified";
/**
* The operation failed because an internal error occurred.
*/
SocialStatusCode[SocialStatusCode["InternalError"] = 6] = "InternalError";
/**
* The operation failed because the server could not access the distributed cache.
*/
SocialStatusCode[SocialStatusCode["CacheReadError"] = 7] = "CacheReadError";
/**
* The operation succeeded but the server could not update the distributed cache.
*/
SocialStatusCode[SocialStatusCode["CacheUpdateError"] = 8] = "CacheUpdateError";
/**
* No personal site exists for the current user, and no further information is available.
*/
SocialStatusCode[SocialStatusCode["PersonalSiteNotFound"] = 9] = "PersonalSiteNotFound";
/**
* No personal site exists for the current user, and a previous attempt to create one failed.
*/
SocialStatusCode[SocialStatusCode["FailedToCreatePersonalSite"] = 10] = "FailedToCreatePersonalSite";
/**
* No personal site exists for the current user, and a previous attempt to create one was not authorized.
*/
SocialStatusCode[SocialStatusCode["NotAuthorizedToCreatePersonalSite"] = 11] = "NotAuthorizedToCreatePersonalSite";
/**
* No personal site exists for the current user, and no attempt should be made to create one.
*/
SocialStatusCode[SocialStatusCode["CannotCreatePersonalSite"] = 12] = "CannotCreatePersonalSite";
/**
* The operation was rejected because an internal limit had been reached.
*/
SocialStatusCode[SocialStatusCode["LimitReached"] = 13] = "LimitReached";
/**
* The operation failed because an error occurred during the processing of the specified attachment.
*/
SocialStatusCode[SocialStatusCode["AttachmentError"] = 14] = "AttachmentError";
/**
* The operation succeeded with recoverable errors; the returned data is incomplete.
*/
SocialStatusCode[SocialStatusCode["PartialData"] = 15] = "PartialData";
/**
* A required SharePoint feature is not enabled.
*/
SocialStatusCode[SocialStatusCode["FeatureDisabled"] = 16] = "FeatureDisabled";
/**
* The site's storage quota has been exceeded.
*/
SocialStatusCode[SocialStatusCode["StorageQuotaExceeded"] = 17] = "StorageQuotaExceeded";
/**
* The operation failed because the server could not access the database.
*/
SocialStatusCode[SocialStatusCode["DatabaseError"] = 18] = "DatabaseError";
})(exports.SocialStatusCode || (exports.SocialStatusCode = {}));
/**
* Implements the site script API REST methods
*
*/
var SiteScripts = /** @class */ (function (_super) {
__extends(SiteScripts, _super);
/**
* Creates a new instance of the SiteScripts method class
*
* @param baseUrl The parent url provider
* @param methodName The static method name to call on the utility class
*/
function SiteScripts(baseUrl, methodName) {
return _super.call(this, SiteScripts.getBaseUrl(baseUrl), "_api/Microsoft.Sharepoint.Utilities.WebTemplateExtensions.SiteScriptUtility." + methodName) || this;
}
SiteScripts.getBaseUrl = function (candidate) {
if (typeof candidate === "string") {
return candidate;
}
var c = candidate;
var url = c.toUrl();
var index = url.indexOf("_api/");
if (index < 0) {
return url;
}
return url.substr(0, index);
};
SiteScripts.prototype.execute = function (props) {
return this.postCore({
body: JSON.stringify(props),
});
};
/**
* Gets a list of information on all existing site scripts.
*/
SiteScripts.prototype.getSiteScripts = function () {
return this.clone(SiteScripts, "GetSiteScripts", true).execute({});
};
/**
* Creates a new site script.
*
* @param title The display name of the site design.
* @param content JSON value that describes the script. For more information, see JSON reference.
*/
SiteScripts.prototype.createSiteScript = function (title, description, content) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.clone(SiteScripts, "CreateSiteScript(Title=@title,Description=@desc)?@title='" + encodeURIComponent(title) + "'&@desc='" + encodeURIComponent(description) + "'")
.execute(content)];
case 1: return [2 /*return*/, _a.sent()];
}
});
});
};
/**
* Gets information about a specific site script. It also returns the JSON of the script.
*
* @param id The ID of the site script to get information about.
*/
SiteScripts.prototype.getSiteScriptMetadata = function (id) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.clone(SiteScripts, "GetSiteScriptMetadata").execute({ id: id })];
case 1: return [2 /*return*/, _a.sent()];
}
});
});
};
/**
* Deletes a site script.
*
* @param id The ID of the site script to delete.
*/
SiteScripts.prototype.deleteSiteScript = function (id) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.clone(SiteScripts, "DeleteSiteScript").execute({ id: id })];
case 1:
_a.sent();
return [2 /*return*/];
}
});
});
};
/**
* Updates a site script with new values. In the REST call, all parameters are optional except the site script Id.
*
* @param siteScriptUpdateInfo Object that contains the information to update a site script.
* Make sure you stringify the content object or pass it in the second 'content' parameter
* @param content (Optional) A new JSON script defining the script actions. For more information, see Site design JSON schema.
*/
SiteScripts.prototype.updateSiteScript = function (siteScriptUpdateInfo, content) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (content) {
siteScriptUpdateInfo.Content = JSON.stringify(content);
}
return [4 /*yield*/, this.clone(SiteScripts, "UpdateSiteScript").execute({ updateInfo: siteScriptUpdateInfo })];
case 1: return [2 /*return*/, _a.sent()];
}
});
});
};
return SiteScripts;
}(SharePointQueryable));
/**
* Implements the site designs API REST methods
*
*/
var SiteDesigns = /** @class */ (function (_super) {
__extends(SiteDesigns, _super);
/**
* Creates a new instance of the SiteDesigns method class
*
* @param baseUrl The parent url provider
* @param methodName The static method name to call on the utility class
*/
function SiteDesigns(baseUrl, methodName) {
return _super.call(this, SiteDesigns.getBaseUrl(baseUrl), "_api/Microsoft.Sharepoint.Utilities.WebTemplateExtensions.SiteScriptUtility." + methodName) || this;
}
SiteDesigns.getBaseUrl = function (candidate) {
if (typeof candidate === "string") {
return candidate;
}
var c = candidate;
var url = c.toUrl();
var index = url.indexOf("_api/");
if (index < 0) {
return url;
}
return url.substr(0, index);
};
SiteDesigns.prototype.execute = function (props) {
return this.postCore({
body: JSON.stringify(props),
headers: {
"Content-Type": "application/json;charset=utf-8",
},
});
};
/**
* Creates a new site design available to users when they create a new site from the SharePoint home page.
*
* @param creationInfo A sitedesign creation information object
*/
SiteDesigns.prototype.createSiteDesign = function (creationInfo) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.clone(SiteDesigns, "CreateSiteDesign").execute({ info: creationInfo })];
case 1: return [2 /*return*/, _a.sent()];
}
});
});
};
/**
* Applies a site design to an existing site collection.
*
* @param siteDesignId The ID of the site design to apply.
* @param webUrl The URL of the site collection where you want to apply the site design.
*/
SiteDesigns.prototype.applySiteDesign = function (siteDesignId, webUrl) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.clone(SiteDesigns, "ApplySiteDesign").execute({ siteDesignId: siteDesignId, "webUrl": webUrl })];
case 1: return [2 /*return*/, _a.sent()];
}
});
});
};
/**
* Gets a list of information about existing site designs.
*/
SiteDesigns.prototype.getSiteDesigns = function () {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.clone(SiteDesigns, "GetSiteDesigns").execute({})];
case 1: return [2 /*return*/, _a.sent()];
}
});
});
};
/**
* Gets information about a specific site design.
* @param id The ID of the site design to get information about.
*/
SiteDesigns.prototype.getSiteDesignMetadata = function (id) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.clone(SiteDesigns, "GetSiteDesignMetadata").execute({ id: id })];
case 1: return [2 /*return*/, _a.sent()];
}
});
});
};
/**
* Updates a site design with new values. In the REST call, all parameters are optional except the site script Id.
* If you had previously set the IsDefault parameter to TRUE and wish it to remain true, you must pass in this parameter again (otherwise it will be reset to FALSE).
* @param updateInfo A sitedesign update information object
*/
SiteDesigns.prototype.updateSiteDesign = function (updateInfo) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.clone(SiteDesigns, "UpdateSiteDesign").execute({ updateInfo: updateInfo })];
case 1: return [2 /*return*/, _a.sent()];
}
});
});
};
/**
* Deletes a site design.
* @param id The ID of the site design to delete.
*/
SiteDesigns.prototype.deleteSiteDesign = function (id) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.clone(SiteDesigns, "DeleteSiteDesign").execute({ id: id })];
case 1: return [2 /*return*/, _a.sent()];
}
});
});
};
/**
* Gets a list of principals that have access to a site design.
* @param id The ID of the site design to get rights information from.
*/
SiteDesigns.prototype.getSiteDesignRights = function (id) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.clone(SiteDesigns, "GetSiteDesignRights").execute({ id: id })];
case 1: return [2 /*return*/, _a.sent()];
}
});
});
};
/**
* Grants access to a site design for one or more principals.
* @param id The ID of the site design to grant rights on.
* @param principalNames An array of one or more principals to grant view rights.
* Principals can be users or mail-enabled security groups in the form of "alias" or "alias@<domain name>.com"
* @param grantedRights Always set to 1. This represents the View right.
*/
SiteDesigns.prototype.grantSiteDesignRights = function (id, principalNames, grantedRights) {
if (grantedRights === void 0) { grantedRights = 1; }
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.clone(SiteDesigns, "GrantSiteDesignRights")
.execute({
"grantedRights": grantedRights.toString(),
"id": id,
"principalNames": principalNames,
})];
case 1: return [2 /*return*/, _a.sent()];
}
});
});
};
/**
* Revokes access from a site design for one or more principals.
* @param id The ID of the site design to revoke rights from.
* @param principalNames An array of one or more principals to revoke view rights from.
* If all principals have rights revoked on the site design, the site design becomes viewable to everyone.
*/
SiteDesigns.prototype.revokeSiteDesignRights = function (id, principalNames) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.clone(SiteDesigns, "RevokeSiteDesignRights")
.execute({
"id": id,
"principalNames": principalNames,
})];
case 1: return [2 /*return*/, _a.sent()];
}
});
});
};
return SiteDesigns;
}(SharePointQueryable));
/**
* Allows for calling of the static SP.Utilities.Utility methods by supplying the method name
*/
var UtilityMethod = /** @class */ (function (_super) {
__extends(UtilityMethod, _super);
/**
* Creates a new instance of the Utility method class
*
* @param baseUrl The parent url provider
* @param methodName The static method name to call on the utility class
*/
function UtilityMethod(baseUrl, methodName) {
return _super.call(this, UtilityMethod.getBaseUrl(baseUrl), "_api/SP.Utilities.Utility." + methodName) || this;
}
UtilityMethod.getBaseUrl = function (candidate) {
if (typeof candidate === "string") {
return candidate;
}
var c = candidate;
var url = c.toUrl();
var index = url.indexOf("_api/");
if (index < 0) {
return url;
}
return url.substr(0, index);
};
UtilityMethod.prototype.excute = function (props) {
return this.postCore({
body: common.jsS(props),
});
};
/**
* Sends an email based on the supplied properties
*
* @param props The properties of the email to send
*/
UtilityMethod.prototype.sendEmail = function (props) {
var params = {
properties: common.extend(metadata("SP.Utilities.EmailProperties"), {
Body: props.Body,
From: props.From,
Subject: props.Subject,
}),
};
if (props.To && props.To.length > 0) {
params.properties = common.extend(params.properties, {
To: { results: props.To },
});
}
if (props.CC && props.CC.length > 0) {
params.properties = common.extend(params.properties, {
CC: { results: props.CC },
});
}
if (props.BCC && props.BCC.length > 0) {
params.properties = common.extend(params.properties, {
BCC: { results: props.BCC },
});
}
if (props.AdditionalHeaders) {
params.properties = common.extend(params.properties, {
AdditionalHeaders: props.AdditionalHeaders,
});
}
return this.clone(UtilityMethod, "SendEmail", true).excute(params);
};
UtilityMethod.prototype.getCurrentUserEmailAddresses = function () {
return this.clone(UtilityMethod, "GetCurrentUserEmailAddresses", true).excute({});
};
UtilityMethod.prototype.resolvePrincipal = function (input, scopes, sources, inputIsEmailOnly, addToUserInfoList, matchUserInfoList) {
if (matchUserInfoList === void 0) { matchUserInfoList = false; }
var params = {
addToUserInfoList: addToUserInfoList,
input: input,
inputIsEmailOnly: inputIsEmailOnly,
matchUserInfoList: matchUserInfoList,
scopes: scopes,
sources: sources,
};
return this.clone(UtilityMethod, "ResolvePrincipalInCurrentContext", true).excute(params);
};
UtilityMethod.prototype.searchPrincipals = function (input, scopes, sources, groupName, maxCount) {
var params = {
groupName: groupName,
input: input,
maxCount: maxCount,
scopes: scopes,
sources: sources,
};
return this.clone(UtilityMethod, "SearchPrincipalsUsingContextWeb", true).excute(params);
};
UtilityMethod.prototype.createEmailBodyForInvitation = function (pageAddress) {
var params = {
pageAddress: pageAddress,
};
return this.clone(UtilityMethod, "CreateEmailBodyForInvitation", true).excute(params);
};
UtilityMethod.prototype.expandGroupsToPrincipals = function (inputs, maxCount) {
if (maxCount === void 0) { maxCount = 30; }
var params = {
inputs: inputs,
maxCount: maxCount,
};
return this.clone(UtilityMethod, "ExpandGroupsToPrincipals", true).excute(params);
};
UtilityMethod.prototype.createWikiPage = function (info) {
return this.clone(UtilityMethod, "CreateWikiPageInContextWeb", true).excute({
parameters: info,
}).then(function (r) {
return {
data: r,
file: new File(odataUrlFrom(r)),
};
});
};
/**
* Checks if file or folder name contains invalid characters
*
* @param input File or folder name to check
* @param onPremise Set to true for SharePoint On-Premise
* @returns True if contains invalid chars, false otherwise
*/
UtilityMethod.prototype.containsInvalidFileFolderChars = function (input, onPremise) {
if (onPremise === void 0) { onPremise = false; }
if (onPremise) {
return UtilityMethod.InvalidFileFolderNameCharsOnPremiseRegex.test(input);
}
else {
return UtilityMethod.InvalidFileFolderNameCharsOnlineRegex.test(input);
}
};
/**
* Removes invalid characters from file or folder name
*
* @param input File or folder name
* @param replacer Value that will replace invalid characters
* @param onPremise Set to true for SharePoint On-Premise
* @returns File or folder name with replaced invalid characters
*/
UtilityMethod.prototype.stripInvalidFileFolderChars = function (input, replacer, onPremise) {
if (replacer === void 0) { replacer = ""; }
if (onPremise === void 0) { onPremise = false; }
if (onPremise) {
return input.replace(UtilityMethod.InvalidFileFolderNameCharsOnPremiseRegex, replacer);
}
else {
return input.replace(UtilityMethod.InvalidFileFolderNameCharsOnlineRegex, replacer);
}
};
UtilityMethod.InvalidFileFolderNameCharsOnlineRegex = /["*:<>?/\\|\x00-\x1f\x7f-\x9f]/g;
UtilityMethod.InvalidFileFolderNameCharsOnPremiseRegex = /["#%*:<>?/\\|\x00-\x1f\x7f-\x9f]/g;
return UtilityMethod;
}(SharePointQueryable));
/**
* Root of the SharePoint REST module
*/
var SPRest = /** @class */ (function () {
/**
* Creates a new instance of the SPRest class
*
* @param options Additional options
* @param baseUrl A string that should form the base part of the url
*/
function SPRest(_options, _baseUrl) {
if (_options === void 0) { _options = {}; }
if (_baseUrl === void 0) { _baseUrl = ""; }
this._options = _options;
this._baseUrl = _baseUrl;
}
/**
* Configures instance with additional options and baseUrl.
* Provided configuration used by other objects in a chain
*
* @param options Additional options
* @param baseUrl A string that should form the base part of the url
*/
SPRest.prototype.configure = function (options, baseUrl) {
if (baseUrl === void 0) { baseUrl = ""; }
return new SPRest(options, baseUrl);
};
/**
* Global SharePoint configuration options
*
* @param config The SharePoint configuration to apply
*/
SPRest.prototype.setup = function (config) {
setup(config);
};
/**
* Executes a search against this web context
*
* @param query The SearchQuery definition
*/
SPRest.prototype.searchSuggest = function (query) {
var finalQuery;
if (typeof query === "string") {
finalQuery = { querytext: query };
}
else {
finalQuery = query;
}
return this.create(SearchSuggest).execute(finalQuery);
};
/**
* Executes a search against this web context
*
* @param query The SearchQuery definition
*/
SPRest.prototype.search = function (query) {
return this.create(Search).execute(query);
};
/**
* Executes the provided search query, caching the results
*
* @param query The SearchQuery definition
* @param options The set of caching options used to store the results
*/
SPRest.prototype.searchWithCaching = function (query, options) {
return this.create(Search).usingCaching(options).execute(query);
};
Object.defineProperty(SPRest.prototype, "site", {
/**
* Begins a site collection scoped REST request
*
*/
get: function () {
return this.create(Site);
},
enumerable: true,
configurable: true
});
Object.defineProperty(SPRest.prototype, "web", {
/**
* Begins a web scoped REST request
*
*/
get: function () {
return this.create(Web);
},
enumerable: true,
configurable: true
});
Object.defineProperty(SPRest.prototype, "profiles", {
/**
* Access to user profile methods
*
*/
get: function () {
return this.create(UserProfileQuery);
},
enumerable: true,
configurable: true
});
Object.defineProperty(SPRest.prototype, "social", {
/**
* Access to social methods
*/
get: function () {
return this.create(SocialQuery);
},
enumerable: true,
configurable: true
});
Object.defineProperty(SPRest.prototype, "navigation", {
/**
* Access to the site collection level navigation service
*/
get: function () {
return new NavigationService();
},
enumerable: true,
configurable: true
});
/**
* Creates a new batch object for use with the SharePointQueryable.addToBatch method
*
*/
SPRest.prototype.createBatch = function () {
return this.web.createBatch();
};
Object.defineProperty(SPRest.prototype, "utility", {
/**
* Static utilities methods from SP.Utilities.Utility
*/
get: function () {
return this.create(UtilityMethod, "");
},
enumerable: true,
configurable: true
});
Object.defineProperty(SPRest.prototype, "siteScripts", {
/**
* Access to sitescripts methods
*/
get: function () {
return this.create(SiteScripts, "");
},
enumerable: true,
configurable: true
});
Object.defineProperty(SPRest.prototype, "siteDesigns", {
/**
* Access to sitedesigns methods
*/
get: function () {
return this.create(SiteDesigns, "");
},
enumerable: true,
configurable: true
});
/**
* Handles creating and configuring the objects returned from this class
*
* @param fm The factory method used to create the instance
* @param path Optional additional path information to pass to the factory method
*/
SPRest.prototype.create = function (fm, path) {
return new fm(this._baseUrl, path).configure(this._options);
};
return SPRest;
}());
var sp = new SPRest();
exports.odataUrlFrom = odataUrlFrom;
exports.spODataEntity = spODataEntity;
exports.spODataEntityArray = spODataEntityArray;
exports.SharePointQueryable = SharePointQueryable;
exports.SharePointQueryableInstance = SharePointQueryableInstance;
exports.SharePointQueryableCollection = SharePointQueryableCollection;
exports.SharePointQueryableSecurable = SharePointQueryableSecurable;
exports.FileFolderShared = FileFolderShared;
exports.SharePointQueryableShareable = SharePointQueryableShareable;
exports.SharePointQueryableShareableFile = SharePointQueryableShareableFile;
exports.SharePointQueryableShareableFolder = SharePointQueryableShareableFolder;
exports.SharePointQueryableShareableItem = SharePointQueryableShareableItem;
exports.SharePointQueryableShareableWeb = SharePointQueryableShareableWeb;
exports.AppCatalog = AppCatalog;
exports.App = App;
exports.SPBatch = SPBatch;
exports.ContentType = ContentType;
exports.ContentTypes = ContentTypes;
exports.FieldLink = FieldLink;
exports.FieldLinks = FieldLinks;
exports.Field = Field;
exports.Fields = Fields;
exports.File = File;
exports.Files = Files;
exports.Folder = Folder;
exports.Folders = Folders;
exports.SPHttpClient = SPHttpClient;
exports.Item = Item;
exports.Items = Items;
exports.ItemVersion = ItemVersion;
exports.ItemVersions = ItemVersions;
exports.PagedItemCollection = PagedItemCollection;
exports.NavigationNodes = NavigationNodes;
exports.NavigationNode = NavigationNode;
exports.NavigationService = NavigationService;
exports.List = List;
exports.Lists = Lists;
exports.RegionalSettings = RegionalSettings;
exports.InstalledLanguages = InstalledLanguages;
exports.TimeZone = TimeZone;
exports.TimeZones = TimeZones;
exports.sp = sp;
exports.SPRest = SPRest;
exports.RoleDefinitionBindings = RoleDefinitionBindings;
exports.Search = Search;
exports.SearchQueryBuilder = SearchQueryBuilder;
exports.SearchResults = SearchResults;
exports.SearchBuiltInSourceId = SearchBuiltInSourceId;
exports.SearchSuggest = SearchSuggest;
exports.Site = Site;
exports.UserProfileQuery = UserProfileQuery;
exports.toAbsoluteUrl = toAbsoluteUrl;
exports.extractWebUrl = extractWebUrl;
exports.UtilityMethod = UtilityMethod;
exports.View = View;
exports.Views = Views;
exports.ViewFields = ViewFields;
exports.WebPartDefinitions = WebPartDefinitions;
exports.WebPartDefinition = WebPartDefinition;
exports.WebPart = WebPart;
exports.Web = Web;
exports.SiteScripts = SiteScripts;
exports.SiteDesigns = SiteDesigns;
exports.ClientSidePage = ClientSidePage;
exports.CanvasSection = CanvasSection;
exports.CanvasControl = CanvasControl;
exports.CanvasColumn = CanvasColumn;
exports.ClientSidePart = ClientSidePart;
exports.ClientSideText = ClientSideText;
exports.ClientSideWebpart = ClientSideWebpart;
exports.Comments = Comments;
exports.Comment = Comment;
exports.Replies = Replies;
exports.SocialQuery = SocialQuery;
exports.MySocialQuery = MySocialQuery;
Object.defineProperty(exports, '__esModule', { value: true });
})));
//# sourceMappingURL=sp.es5.umd.js.map
|
/**
* Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
'use strict';
module.exports = function promisify(fn) {
return function () {
const args = Array.prototype.slice.call(arguments);
return new Promise((resolve, reject) => {
args.push((err, res) => {
if (err) {
reject(err);} else
{
resolve(res);}});
fn.apply(this, args);});};}; |
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var React = require('react');
var core = require('primereact/core');
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
var React__default = /*#__PURE__*/_interopDefaultLegacy(React);
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function _typeof(obj) {
return typeof obj;
};
} else {
_typeof = function _typeof(obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
}
return _assertThisInitialized(self);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var TriStateCheckbox = /*#__PURE__*/function (_Component) {
_inherits(TriStateCheckbox, _Component);
var _super = _createSuper(TriStateCheckbox);
function TriStateCheckbox(props) {
var _this;
_classCallCheck(this, TriStateCheckbox);
_this = _super.call(this, props);
_this.state = {
focused: false
};
_this.onClick = _this.onClick.bind(_assertThisInitialized(_this));
_this.onFocus = _this.onFocus.bind(_assertThisInitialized(_this));
_this.onBlur = _this.onBlur.bind(_assertThisInitialized(_this));
_this.inputRef = /*#__PURE__*/React.createRef(_this.props.inputRef);
return _this;
}
_createClass(TriStateCheckbox, [{
key: "onClick",
value: function onClick(event) {
if (!this.props.disabled) {
this.toggle(event);
this.inputRef.current.focus();
}
}
}, {
key: "toggle",
value: function toggle(event) {
var newValue;
if (this.props.value === null || this.props.value === undefined) newValue = true;else if (this.props.value === true) newValue = false;else if (this.props.value === false) newValue = null;
if (this.props.onChange) {
this.props.onChange({
originalEvent: event,
value: newValue,
stopPropagation: function stopPropagation() {},
preventDefault: function preventDefault() {},
target: {
name: this.props.name,
id: this.props.id,
value: newValue
}
});
}
}
}, {
key: "onFocus",
value: function onFocus() {
this.setState({
focused: true
});
}
}, {
key: "onBlur",
value: function onBlur() {
this.setState({
focused: false
});
}
}, {
key: "updateInputRef",
value: function updateInputRef() {
var ref = this.props.inputRef;
if (ref) {
if (typeof ref === 'function') {
ref(this.inputRef.current);
} else {
ref.current = this.inputRef.current;
}
}
}
}, {
key: "componentDidMount",
value: function componentDidMount() {
this.updateInputRef();
if (this.props.tooltip && !this.props.disabled) {
this.renderTooltip();
}
}
}, {
key: "componentDidUpdate",
value: function componentDidUpdate(prevProps) {
if (prevProps.tooltip !== this.props.tooltip || prevProps.tooltipOptions !== this.props.tooltipOptions) {
if (this.tooltip) this.tooltip.update(_objectSpread({
content: this.props.tooltip
}, this.props.tooltipOptions || {}));else this.renderTooltip();
}
}
}, {
key: "componentWillUnmount",
value: function componentWillUnmount() {
if (this.tooltip) {
this.tooltip.destroy();
this.tooltip = null;
}
}
}, {
key: "renderTooltip",
value: function renderTooltip() {
this.tooltip = core.tip({
target: this.element,
content: this.props.tooltip,
options: this.props.tooltipOptions
});
}
}, {
key: "render",
value: function render() {
var _this2 = this;
var containerClass = core.classNames('p-tristatecheckbox p-checkbox p-component', this.props.className);
var boxClass = core.classNames('p-checkbox-box', {
'p-highlight': (this.props.value || !this.props.value) && this.props.value !== null,
'p-disabled': this.props.disabled,
'p-focus': this.state.focused
});
var iconClass = core.classNames('p-checkbox-icon p-c', {
'pi pi-check': this.props.value === true,
'pi pi-times': this.props.value === false
});
return /*#__PURE__*/React__default['default'].createElement("div", {
ref: function ref(el) {
return _this2.element = el;
},
id: this.props.id,
className: containerClass,
style: this.props.style,
onClick: this.onClick
}, /*#__PURE__*/React__default['default'].createElement("div", {
className: "p-hidden-accessible"
}, /*#__PURE__*/React__default['default'].createElement("input", {
ref: this.inputRef,
type: "checkbox",
"aria-labelledby": this.props.ariaLabelledBy,
id: this.props.inputId,
name: this.props.name,
onFocus: this.onFocus,
onBlur: this.onBlur,
disabled: this.props.disabled,
defaultChecked: this.props.value
})), /*#__PURE__*/React__default['default'].createElement("div", {
className: boxClass,
ref: function ref(el) {
return _this2.box = el;
},
role: "checkbox",
"aria-checked": this.props.value === true
}, /*#__PURE__*/React__default['default'].createElement("span", {
className: iconClass
})));
}
}]);
return TriStateCheckbox;
}(React.Component);
_defineProperty(TriStateCheckbox, "defaultProps", {
id: null,
inputRef: null,
inputId: null,
value: null,
name: null,
style: null,
className: null,
disabled: false,
tooltip: null,
tooltipOptions: null,
ariaLabelledBy: null,
onChange: null
});
exports.TriStateCheckbox = TriStateCheckbox;
|
/*! UIkit 3.1.0 | http://www.getuikit.com | (c) 2014 - 2018 YOOtheme | MIT License */
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('uikit-util')) :
typeof define === 'function' && define.amd ? define('uikitfilter', ['uikit-util'], factory) :
(global = global || self, global.UIkitFilter = factory(global.UIkit.util));
}(this, function (uikitUtil) { 'use strict';
var targetClass = 'uk-animation-target';
var Animate = {
props: {
animation: Number
},
data: {
animation: 150
},
computed: {
target: function() {
return this.$el;
}
},
methods: {
animate: function(action) {
var this$1 = this;
addStyle();
var children = uikitUtil.toNodes(this.target.children);
var propsFrom = children.map(function (el) { return getProps(el, true); });
var oldHeight = uikitUtil.height(this.target);
var oldScrollY = window.pageYOffset;
action();
uikitUtil.Transition.cancel(this.target);
children.forEach(uikitUtil.Transition.cancel);
reset(this.target);
this.$update(this.target);
uikitUtil.fastdom.flush();
var newHeight = uikitUtil.height(this.target);
children = children.concat(uikitUtil.toNodes(this.target.children).filter(function (el) { return !uikitUtil.includes(children, el); }));
var propsTo = children.map(function (el, i) { return el.parentNode && i in propsFrom
? propsFrom[i]
? uikitUtil.isVisible(el)
? getPositionWithMargin(el)
: {opacity: 0}
: {opacity: uikitUtil.isVisible(el) ? 1 : 0}
: false; }
);
propsFrom = propsTo.map(function (props, i) {
var from = children[i].parentNode === this$1.target
? propsFrom[i] || getProps(children[i])
: false;
if (from) {
if (!props) {
delete from.opacity;
} else if (!('opacity' in props)) {
var opacity = from.opacity;
if (opacity % 1) {
props.opacity = 1;
} else {
delete from.opacity;
}
}
}
return from;
});
uikitUtil.addClass(this.target, targetClass);
children.forEach(function (el, i) { return propsFrom[i] && uikitUtil.css(el, propsFrom[i]); });
uikitUtil.css(this.target, 'height', oldHeight);
uikitUtil.scrollTop(window, oldScrollY);
return uikitUtil.Promise.all(children.map(function (el, i) { return propsFrom[i] && propsTo[i]
? uikitUtil.Transition.start(el, propsTo[i], this$1.animation, 'ease')
: uikitUtil.Promise.resolve(); }
).concat(uikitUtil.Transition.start(this.target, {height: newHeight}, this.animation, 'ease'))).then(function () {
children.forEach(function (el, i) { return uikitUtil.css(el, {display: propsTo[i].opacity === 0 ? 'none' : '', zIndex: ''}); });
reset(this$1.target);
this$1.$update(this$1.target);
uikitUtil.fastdom.flush(); // needed for IE11
}, uikitUtil.noop);
}
}
};
function getProps(el, opacity) {
var zIndex = uikitUtil.css(el, 'zIndex');
return uikitUtil.isVisible(el)
? uikitUtil.assign({
display: '',
opacity: opacity ? uikitUtil.css(el, 'opacity') : '0',
pointerEvents: 'none',
position: 'absolute',
zIndex: zIndex === 'auto' ? uikitUtil.index(el) : zIndex
}, getPositionWithMargin(el))
: false;
}
function reset(el) {
uikitUtil.css(el.children, {
height: '',
left: '',
opacity: '',
pointerEvents: '',
position: '',
top: '',
width: ''
});
uikitUtil.removeClass(el, targetClass);
uikitUtil.css(el, 'height', '');
}
function getPositionWithMargin(el) {
var ref = el.getBoundingClientRect();
var height = ref.height;
var width = ref.width;
var ref$1 = uikitUtil.position(el);
var top = ref$1.top;
var left = ref$1.left;
top += uikitUtil.toFloat(uikitUtil.css(el, 'marginTop'));
return {top: top, left: left, height: height, width: width};
}
var style;
function addStyle() {
if (style) {
return;
}
style = uikitUtil.append(document.head, '<style>').sheet;
style.insertRule(
("." + targetClass + " > * {\n margin-top: 0 !important;\n transform: none !important;\n }"), 0
);
}
var Component = {
mixins: [Animate],
args: 'target',
props: {
target: Boolean,
selActive: Boolean
},
data: {
target: null,
selActive: false,
attrItem: 'uk-filter-control',
cls: 'uk-active',
animation: 250
},
computed: {
toggles: {
get: function(ref, $el) {
var attrItem = ref.attrItem;
return uikitUtil.$$(("[" + (this.attrItem) + "],[data-" + (this.attrItem) + "]"), $el);
},
watch: function() {
this.updateState();
}
},
target: function(ref, $el) {
var target = ref.target;
return uikitUtil.$(target, $el);
},
children: {
get: function() {
return uikitUtil.toNodes(this.target.children);
},
watch: function(list, old) {
if (!isEqualList(list, old)) {
this.updateState();
}
}
}
},
events: [
{
name: 'click',
delegate: function() {
return ("[" + (this.attrItem) + "],[data-" + (this.attrItem) + "]");
},
handler: function(e) {
e.preventDefault();
this.apply(e.current);
}
}
],
connected: function() {
var this$1 = this;
this.updateState();
if (this.selActive === false) {
return;
}
var actives = uikitUtil.$$(this.selActive, this.$el);
this.toggles.forEach(function (el) { return uikitUtil.toggleClass(el, this$1.cls, uikitUtil.includes(actives, el)); });
},
methods: {
apply: function(el) {
this.setState(mergeState(el, this.attrItem, this.getState()));
},
getState: function() {
var this$1 = this;
return this.toggles
.filter(function (item) { return uikitUtil.hasClass(item, this$1.cls); })
.reduce(function (state, el) { return mergeState(el, this$1.attrItem, state); }, {filter: {'': ''}, sort: []});
},
setState: function(state, animate) {
var this$1 = this;
if ( animate === void 0 ) animate = true;
state = uikitUtil.assign({filter: {'': ''}, sort: []}, state);
uikitUtil.trigger(this.$el, 'beforeFilter', [this, state]);
var ref = this;
var children = ref.children;
this.toggles.forEach(function (el) { return uikitUtil.toggleClass(el, this$1.cls, matchFilter(el, this$1.attrItem, state)); });
var apply = function () {
var selector = getSelector(state);
children.forEach(function (el) { return uikitUtil.css(el, 'display', selector && !uikitUtil.matches(el, selector) ? 'none' : ''); });
var ref = state.sort;
var sort = ref[0];
var order = ref[1];
if (sort) {
var sorted = sortItems(children, sort, order);
if (!uikitUtil.isEqual(sorted, children)) {
sorted.forEach(function (el) { return uikitUtil.append(this$1.target, el); });
}
}
};
if (animate) {
this.animate(apply).then(function () { return uikitUtil.trigger(this$1.$el, 'afterFilter', [this$1]); });
} else {
apply();
uikitUtil.trigger(this.$el, 'afterFilter', [this]);
}
},
updateState: function() {
var this$1 = this;
uikitUtil.fastdom.write(function () { return this$1.setState(this$1.getState(), false); });
}
}
};
function getFilter(el, attr) {
return uikitUtil.parseOptions(uikitUtil.data(el, attr), ['filter']);
}
function mergeState(el, attr, state) {
uikitUtil.toNodes(el).forEach(function (el) {
var filterBy = getFilter(el, attr);
var filter = filterBy.filter;
var group = filterBy.group;
var sort = filterBy.sort;
var order = filterBy.order; if ( order === void 0 ) order = 'asc';
if (filter || uikitUtil.isUndefined(sort)) {
if (group) {
delete state.filter[''];
state.filter[group] = filter;
} else {
state.filter = {'': filter || ''};
}
}
if (!uikitUtil.isUndefined(sort)) {
state.sort = [sort, order];
}
});
return state;
}
function matchFilter(el, attr, ref) {
var stateFilter = ref.filter; if ( stateFilter === void 0 ) stateFilter = {'': ''};
var ref_sort = ref.sort;
var stateSort = ref_sort[0];
var stateOrder = ref_sort[1];
var ref$1 = getFilter(el, attr);
var filter = ref$1.filter;
var group = ref$1.group; if ( group === void 0 ) group = '';
var sort = ref$1.sort;
var order = ref$1.order; if ( order === void 0 ) order = 'asc';
filter = uikitUtil.isUndefined(sort) ? filter || '' : filter;
sort = uikitUtil.isUndefined(filter) ? sort || '' : sort;
return (uikitUtil.isUndefined(filter) || group in stateFilter && filter === stateFilter[group])
&& (uikitUtil.isUndefined(sort) || stateSort === sort && stateOrder === order);
}
function isEqualList(listA, listB) {
return listA.length === listB.length
&& listA.every(function (el) { return ~listB.indexOf(el); });
}
function getSelector(ref) {
var filter = ref.filter;
var selector = '';
uikitUtil.each(filter, function (value) { return selector += value || ''; });
return selector;
}
function sortItems(nodes, sort, order) {
return uikitUtil.assign([], nodes).sort(function (a, b) { return uikitUtil.data(a, sort).localeCompare(uikitUtil.data(b, sort), undefined, {numeric: true}) * (order === 'asc' || -1); });
}
/* global UIkit, 'filter' */
if (typeof window !== 'undefined' && window.UIkit) {
window.UIkit.component('filter', Component);
}
return Component;
}));
|
var utils = require("utils/utils");
var common = require("./grid-layout-common");
var view_1 = require("ui/core/view");
global.moduleMerge(common, exports);
function setNativeProperty(data, setter) {
var view = data.object;
if (view instanceof view_1.View) {
var nativeView = view._nativeView;
var lp = nativeView.getLayoutParams();
if (!(lp instanceof org.nativescript.widgets.CommonLayoutParams)) {
lp = new org.nativescript.widgets.CommonLayoutParams();
}
setter(lp);
nativeView.setLayoutParams(lp);
}
}
function setNativeRowProperty(data) {
setNativeProperty(data, function (lp) { lp.row = data.newValue; });
}
function setNativeRowSpanProperty(data) {
setNativeProperty(data, function (lp) { lp.rowSpan = data.newValue; });
}
function setNativeColumnProperty(data) {
setNativeProperty(data, function (lp) { lp.column = data.newValue; });
}
function setNativeColumnSpanProperty(data) {
setNativeProperty(data, function (lp) { lp.columnSpan = data.newValue; });
}
common.GridLayout.rowProperty.metadata.onSetNativeValue = setNativeRowProperty;
common.GridLayout.rowSpanProperty.metadata.onSetNativeValue = setNativeRowSpanProperty;
common.GridLayout.columnProperty.metadata.onSetNativeValue = setNativeColumnProperty;
common.GridLayout.columnSpanProperty.metadata.onSetNativeValue = setNativeColumnSpanProperty;
function createNativeSpec(itemSpec) {
switch (itemSpec.gridUnitType) {
case common.GridUnitType.auto:
return new org.nativescript.widgets.ItemSpec(itemSpec.value, org.nativescript.widgets.GridUnitType.auto);
case common.GridUnitType.star:
return new org.nativescript.widgets.ItemSpec(itemSpec.value, org.nativescript.widgets.GridUnitType.star);
case common.GridUnitType.pixel:
return new org.nativescript.widgets.ItemSpec(itemSpec.value * utils.layout.getDisplayDensity(), org.nativescript.widgets.GridUnitType.pixel);
default:
throw new Error("Invalid gridUnitType: " + itemSpec.gridUnitType);
}
}
var ItemSpec = (function (_super) {
__extends(ItemSpec, _super);
function ItemSpec() {
_super.apply(this, arguments);
}
Object.defineProperty(ItemSpec.prototype, "actualLength", {
get: function () {
if (this.nativeSpec) {
return Math.round(this.nativeSpec.getActualLength() / utils.layout.getDisplayDensity());
}
return 0;
},
enumerable: true,
configurable: true
});
return ItemSpec;
}(common.ItemSpec));
exports.ItemSpec = ItemSpec;
var GridLayout = (function (_super) {
__extends(GridLayout, _super);
function GridLayout() {
_super.apply(this, arguments);
}
Object.defineProperty(GridLayout.prototype, "android", {
get: function () {
return this._layout;
},
enumerable: true,
configurable: true
});
Object.defineProperty(GridLayout.prototype, "_nativeView", {
get: function () {
return this._layout;
},
enumerable: true,
configurable: true
});
GridLayout.prototype._createUI = function () {
var _this = this;
this._layout = new org.nativescript.widgets.GridLayout(this._context);
this.getRows().forEach(function (itemSpec, index, rows) { _this._onRowAdded(itemSpec); }, this);
this.getColumns().forEach(function (itemSpec, index, rows) { _this._onColumnAdded(itemSpec); }, this);
};
GridLayout.prototype._onRowAdded = function (itemSpec) {
if (this._layout) {
var nativeSpec = createNativeSpec(itemSpec);
itemSpec.nativeSpec = nativeSpec;
this._layout.addRow(nativeSpec);
}
};
GridLayout.prototype._onColumnAdded = function (itemSpec) {
if (this._layout) {
var nativeSpec = createNativeSpec(itemSpec);
itemSpec.nativeSpec = nativeSpec;
this._layout.addColumn(nativeSpec);
}
};
GridLayout.prototype._onRowRemoved = function (itemSpec, index) {
itemSpec.nativeSpec = null;
if (this._layout) {
this._layout.removeRowAt(index);
}
};
GridLayout.prototype._onColumnRemoved = function (itemSpec, index) {
itemSpec.nativeSpec = null;
if (this._layout) {
this._layout.removeColumnAt(index);
}
};
GridLayout.prototype.invalidate = function () {
};
return GridLayout;
}(common.GridLayout));
exports.GridLayout = GridLayout;
|
"use strict";
var logParser = require('../log-parser');
var stats = require('../stats');
module.exports = function (req, res, next) {
if (req.isCDN) {
return void next();
}
var referrer = req.get('referrer');
if (referrer) {
referrer = req.canonicalReferrer = referrer.replace(/\?.*$/, '');
}
if (!logParser.enabled) {
stats.logRequest(req.path, referrer);
}
// TODO: Would be nice if we could track response sizes here, but that's a
// little complicated when we're piping GitHub responses directly to the
// client.
next();
};
|
'use strict';
import Vue from 'vue';
const _ = Vue.util;
let toString = Object.prototype.toString,
join = function() {
return this && this.length ? Array.prototype.join.apply(this, arguments) : '';
};
let getType = function(o) {
let _t = typeof o;
let result;
if (_t == 'object') {
if (o == null) result = 'null';
else result = Object.prototype.toString.call(o).slice(8,-1);
} else {
result = _t;
}
return result.toLowerCase();
}
let getStyle = function(el, styleName) {
if (el.style[styleName]) {
return el.style[styleName];
} else if (el.currentStyle) {
return el.currentStyle[styleName];
} else {
return window.getComputedStyle(el, null)[styleName];
}
}
let getStyleNum = function(el, styleName) {
return parseInt(getStyle(el, styleName).replace(/px|pt|em/ig,''));
}
let setStyle = function(el, obj) {
if (getType(obj) === 'object') {
for (let s in obj) {
let cssArrt = s.split('-');
for (let i = 1; i < cssArrt.length; i++) {
cssArrt[i] = cssArrt[i].replace(cssArrt[i].charAt(0), cssArrt[i].charAt(0).toUpperCase());
}
let cssArrtNew = cssArrt.join('');
el.style[cssArrtNew] = obj[s];
}
} else {
if (getType(obj) === 'string') {
el.style.cssText = obj;
}
}
}
let getSize = function(el) {
if (getStyle(el, 'display') != 'none' && (el.parentNode && el.parentNode.nodeType != 11)) {
return {
width: el.offsetWidth || getStyleNum(el, 'width'),
height: el.offsetHeight || getStyleNum(el, 'height')
};
} else {
document.body.appendChild(el);
}
let _newCss = {
display: '',
position: 'absolute',
left: -9999,
visibility: 'hidden'
};
let _oldCss = {};
for (let i in _newCss) {
_oldCss[i] = getStyle(el, i);
}
setStyle(el, _newCss);
let width = el.clientWidth || getStyleNum(el, 'width');
let height = el.clientHeight || getStyleNum(el, 'height');
for (let j in _oldCss) {
setStyle(el, _oldCss);
}
return { width, height };
}
class Dom {
constructor(el) {
if ('[object String]' == toString.call(el) && el.match(/^\s*\</)) {
let div = document.createElement('div');
div.innerHTML = el;
this.$el = div.firstChild;
} else {
if ('[object String]' != toString.call(el) || el.match(/^\s*\</)) {
this.$el = el;
} else {
this.$el = document.querySelector(el);
}
}
}
children() {
this.$el = this.$el.children;
return this;
}
/**
* 插入节点
*
* @param {[type]} el [description]
* @return {[type]} [description]
*/
append(el) {
// 如果el是一个dom实例的话
if (el instanceof Dom) el = el.$el;
if (typeof el === 'string') {
let _el = document.createElement('div');
_el.innerHTML = el;
this.$el.appendChild(_el.children[0]);
} else {
this.$el.appendChild(el);
}
return this;
}
// Todo
hasClass(className) {
}
/**
* 添加class
*
* @param {[type]} el [description]
*/
addClass(className) {
let fn = function(_el) {
// 过滤重复的类
let classList = join.call(_el.classList, '|').replace(className, '').split('|');
classList.push(className);
_el.setAttribute('class', join.call(classList, ' '));
}
if (this.$el) {
if (this.$el.length) {
Array.prototype.slice.call(this.$el).forEach(function(_el) {
fn(_el);
});
} else {
fn(this.$el);
}
}
return this;
}
/**
* 删除class
*
* @param {[type]} el [description]
* @return {[type]} [description]
*/
removeClass(className) {
let fn = function(_el) {
let classList = join.call(_el.classList, '|').replace(className, '').split('|');
_el.setAttribute('class', join.call(classList, ' '));
}
if (this.$el) {
if (this.$el.length) {
Array.prototype.slice.call(this.$el).forEach(function(_el) {
fn(_el);
});
} else {
fn(this.$el);
}
}
return this;
}
/**
* 删除节点
*
* @return {[type]} [description]
*/
remove() {
let fn = function(_el) {
let el = _el.parentNode;
el.removeChild(_el);
}
if (this.$el) {
if (this.$el.length) {
Array.prototype.slice.call(this.$el).forEach(function(_el) {
fn(_el);
});
} else {
fn(this.$el);
}
}
return this;
}
/**
* 获取data
*
* @param {[type]} key [description]
* @param {[type]} value [description]
* @return {[type]} [description]
*/
data(key, value) {
if (key && value) {
this.$el.setAttribute('data-' + key, value);
return this;
} else if (key) {
return this.$el.getAttribute('data-' + key);
} else {
return this.$el.dataset;
}
}
on(type, fn) {
this.$el.addEventListener(type, fn, false);
return this;
}
off(type, fn) {
this.$el.removeEventListener(type, fn);
return this;
}
trigger(type) {
let evObj;
if (document.createEvent) {
setTimeout(() => {
evObj = document.createEvent("MouseEvents");
evObj.initEvent(type, true, true);
this.$el.dispatchEvent(evObj);
}, 0);
} else {
setTimeout(() => {
if (document.createEventObject) {
evObj = document.createEventObject();
evObj.cancelBubble = true;
this.$el.fireEvent("on" + type, evObj);
}
}, 0);
}
}
attr(attr) {
return _.attr(this.$el, attr);
}
width(value) {
if (value != null) {
this.$el.style.width = value;
} else {
return getSize(this.$el).width;
}
}
height(value) {
if (value != null) {
this.$el.style.height = value;
} else {
return getSize(this.$el).height;
}
}
matchNode(el) {
let current;
let isMatch = false;
if (this.$el === el) isMatch = true;
else {
let parentNode = this.$el.parentNode;
if (!parentNode) return false;
this.$el = this.$el.parentNode;
return this.matchNode(el);
}
return isMatch;
}
// todo
closest() {
}
parent() {
return new Dom(this.$el.parentNode || this.$el);
}
find(el) {
return new Dom(this.$el.querySelector(el));
}
is(str) {
let match;
if (match = /^\.(.*)/.exec(str)) {
let className = match[1];
let classNameStr = join.call(this.$el.classList, '|');
if (classNameStr.indexOf(className) > -1) return true;
} else if (match = /^#(.*)/.test(str)) {
let id = match[1];
if (this.$el.id === id) return true;
}
return false;
}
}
export default function(el) {
return el instanceof Dom ? el : new Dom(el);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.